From 066e9193fd1a43ebc524c4f9105e7faee35bb008 Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 11:36:19 -0500 Subject: [PATCH 1/9] Initial commit --- README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..a91d4f77 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# UnityDecompiled +An unofficial repo of decompiled Unity dll files From 7193071e7ae7df5a8706bb4304c5e8a9179113ef Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 11:41:02 -0500 Subject: [PATCH 2/9] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index a91d4f77..94d356d5 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,6 @@ # UnityDecompiled An unofficial repo of decompiled Unity dll files + +Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) + +Permission here: https://twitter.com/aras_p/status/568126504997138434 From 4276010f5a5ba44c5d7b7a2b50fa4e63e9b5eaa4 Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 12:06:12 -0500 Subject: [PATCH 3/9] Initial commit of Unity 4.6.3f1 --- .gitattributes | 23 + .gitignore | 5 + README.md | 2 + UnityDecompiled.sln | 31 + UnityEditor/AssemblyValidation.cs | 135 + UnityEditor/AssemblyValidationRule.cs | 20 + UnityEditor/AssetModificationProcessor.cs | 5 + UnityEditor/ClangCompiler.cs | 56 + UnityEditor/ClangCompilerSettingsx86.cs | 32 + UnityEditor/DesktopStandalonePostProcessor.cs | 127 + UnityEditor/FlashDotNetAPIValidationRule.cs | 82 + UnityEditor/FlashFileHelper.cs | 187 + UnityEditor/FlashPostProcessSettings.cs | 136 + UnityEditor/FlashTemplateWriterUtility.cs | 62 + UnityEditor/GendarmeOptions.cs | 7 + UnityEditor/GendarmeValidationRule.cs | 82 + UnityEditor/GendarmeXMLTemplateTags.cs | 73 + UnityEditor/GenerateIconsWithMipLevels.cs | 264 + UnityEditor/ICompilerSettings.cs | 20 + UnityEditor/INativeCompiler.cs | 6 + UnityEditor/IValidationRule.cs | 6 + .../LinuxDesktopStandalonePostProcessor.cs | 131 + UnityEditor/MSVCCompiler.cs | 95 + UnityEditor/MSVCCompilerSettingsx64.cs | 49 + UnityEditor/MSVCCompilerSettingsx86.cs | 49 + UnityEditor/MxmlcHelper.cs | 69 + UnityEditor/NUnitFrameworkUser.cs | 9 + UnityEditor/NativeCompiler.cs | 118 + .../OSXDesktopStandalonePostProcessor.cs | 111 + UnityEditor/ParticleSystemCurveEditor.cs | 684 +++ UnityEditor/PatchImportSettingRecycleID.cs | 38 + UnityEditor/PostProcessDashboardWidget.cs | 35 + UnityEditor/PostProcessFlashPlayer.cs | 164 + UnityEditor/PostProcessFlashPlayerOptions.cs | 24 + UnityEditor/PostProcessStandalonePlayer.cs | 4 + UnityEditor/PostProcessWebPlayer.cs | 128 + UnityEditor/PreviewGUI.cs | 118 + UnityEditor/Properties/AssemblyInfo.cs | 23 + .../SerializedFileContainerPreparer.cs | 71 + UnityEditor/SerializedStringTable.cs | 84 + UnityEditor/TreeEditor/FractalNoise.cs | 92 + UnityEditor/TreeEditor/Perlin.cs | 177 + UnityEditor/TreeEditor/RingLoop.cs | 329 + UnityEditor/TreeEditor/SmoothRandom.cs | 27 + UnityEditor/TreeEditor/SplineNode.cs | 27 + UnityEditor/TreeEditor/TextureAtlas.cs | 244 + UnityEditor/TreeEditor/TreeAOSphere.cs | 31 + UnityEditor/TreeEditor/TreeAttribute.cs | 112 + UnityEditor/TreeEditor/TreeData.cs | 1203 ++++ UnityEditor/TreeEditor/TreeEditor.cs | 2278 +++++++ UnityEditor/TreeEditor/TreeEditorHelper.cs | 423 ++ UnityEditor/TreeEditor/TreeGroup.cs | 476 ++ UnityEditor/TreeEditor/TreeGroupBranch.cs | 721 +++ UnityEditor/TreeEditor/TreeGroupLeaf.cs | 537 ++ UnityEditor/TreeEditor/TreeGroupRoot.cs | 40 + UnityEditor/TreeEditor/TreeMaterial.cs | 10 + UnityEditor/TreeEditor/TreeNode.cs | 122 + UnityEditor/TreeEditor/TreeSpline.cs | 257 + UnityEditor/TreeEditor/TreeTriangle.cs | 43 + UnityEditor/TreeEditor/TreeVertex.cs | 38 + .../UnityEditor.AnimatedValues/AnimBool.cs | 43 + .../UnityEditor.AnimatedValues/AnimFloat.cs | 23 + .../AnimQuaternion.cs | 23 + .../UnityEditor.AnimatedValues/AnimVector3.cs | 26 + .../BaseAnimValue.cs | 141 + .../UnityEditor.Callbacks/DidReloadScripts.cs | 15 + .../OnOpenAssetAttribute.cs | 15 + .../PostProcessBuildAttribute.cs | 15 + .../PostProcessSceneAttribute.cs | 15 + .../UnityEditor.Events/UnityEventTools.cs | 129 + .../LinuxStandaloneIl2CppPlatformProvider.cs | 58 + .../UnityEditor.Macros/MacroEvaluator.cs | 79 + .../UnityEditor.Macros/MethodEvaluator.cs | 66 + .../BuildLaunchPlayerArgs.cs | 12 + .../BuildPostProcessArgs.cs | 18 + .../DefaultPlayerSettingsEditorExtension.cs | 34 + .../IBuildPostprocessor.cs | 12 + .../IPlatformSupportModule.cs | 18 + .../IPreferenceWindowExtension.cs | 11 + .../ISettingEditorExtension.cs | 15 + .../UnityEditor.Modules/ModuleManager.cs | 469 ++ .../OSXStandaloneIl2CppPlatformProvider.cs | 45 + .../DoCreateAnimatorController.cs | 13 + .../DoCreateFolder.cs | 15 + .../DoCreateNewAsset.cs | 12 + .../DoCreatePrefab.cs | 13 + .../DoCreateScriptAsset.cs | 13 + .../EndNameEditAction.cs | 17 + .../BooCompiler.cs | 49 + .../BooCompilerOutputParser.cs | 17 + .../BooLanguage.cs | 33 + .../CSharpLanguage.cs | 91 + .../Cil2AsOutputParser.cs | 27 + .../CommandLineFormatter.cs | 67 + .../CompilerMessage.cs | 12 + .../CompilerMessageType.cs | 9 + .../CompilerOutputParserBase.cs | 62 + .../FlexCompilerOutputParser.cs | 17 + .../GendarmeOutputParser.cs | 113 + .../GendarmeRuleData.cs | 17 + .../Il2CppOutputParser.cs | 58 + .../MicrosoftCSharpCompiler.cs | 261 + .../MicrosoftCSharpCompilerOutputParser.cs | 17 + .../MonoCSharpCompiler.cs | 103 + .../MonoCSharpCompilerOutputParser.cs | 17 + .../MonoScriptCompilerBase.cs | 30 + .../ScriptCompilerBase.cs | 128 + .../SupportedLanguage.cs | 14 + .../UnityScriptCompiler.cs | 80 + .../UnityScriptCompilerOutputParser.cs | 17 + .../UnityScriptLanguage.cs | 19 + .../Weaver.cs | 66 + .../UnityEditor.Scripting/ManagedProgram.cs | 64 + .../UnityEditor.Scripting/MonoIsland.cs | 26 + .../UnityEditor.Scripting/PragmaFixing30.cs | 140 + .../UnityEditor.Scripting/ScriptCompilers.cs | 71 + .../SupportedLanguageStruct.cs | 9 + .../UnityEditor.Sprites/AtlasSettings.cs | 18 + .../UnityEditor.Sprites/DataUtility.cs | 31 + .../DefaultPackerPolicy.cs | 137 + .../UnityEditor.Sprites/IPackerPolicy.cs | 9 + UnityEditor/UnityEditor.Sprites/Packer.cs | 177 + UnityEditor/UnityEditor.Sprites/PackerJob.cs | 18 + .../UnityEditor.Sprites/PackerWindow.cs | 308 + .../UnityEditor.Sprites/TightPackerPolicy.cs | 21 + .../MonoInstallationFinder.cs | 34 + UnityEditor/UnityEditor.Utils/Paths.cs | 76 + .../UnityEditor.Utils/PerformanceChecks.cs | 85 + .../ProcessOutputStreamReader.cs | 70 + UnityEditor/UnityEditor.Utils/Program.cs | 163 + .../UnityEditor.VersionControl/Asset.cs | 204 + .../UnityEditor.VersionControl/AssetList.cs | 73 + .../UnityEditor.VersionControl/ChangeSet.cs | 57 + .../UnityEditor.VersionControl/ChangeSets.cs | 8 + .../CheckoutMode.cs | 11 + .../CommandContext.cs | 9 + .../CompletionAction.cs | 14 + .../UnityEditor.VersionControl/ConfigField.cs | 48 + .../CustomCommand.cs | 31 + .../UnityEditor.VersionControl/FileMode.cs | 11 + .../UnityEditor.VersionControl/MergeMethod.cs | 11 + .../UnityEditor.VersionControl/Message.cs | 46 + .../UnityEditor.VersionControl/OnlineState.cs | 11 + .../UnityEditor.VersionControl/Plugin.cs | 36 + .../UnityEditor.VersionControl/Provider.cs | 544 ++ .../ResolveMethod.cs | 11 + .../UnityEditor.VersionControl/RevertMode.cs | 11 + .../SubmitResult.cs | 11 + .../UnityEditor.VersionControl/Task.cs | 119 + .../WindowChange.cs | 379 ++ .../WindowPending.cs | 500 ++ .../WindowResolve.cs | 166 + .../WindowRevert.cs | 103 + .../DefaultSolutionSynchronizationSettings.cs | 170 + .../ISolutionSynchronizationSettings.cs | 41 + .../ScriptingLanguage.cs | 11 + .../SolutionGuidGenerator.cs | 48 + .../SolutionSynchronizer.cs | 547 ++ ...WindowsStandaloneIl2CppPlatformProvider.cs | 60 + UnityEditor/UnityEditor.csproj | 1098 ++++ UnityEditor/UnityEditor/AInfo.cs | 60 + UnityEditor/UnityEditor/ASCommitWindow.cs | 1411 +++++ UnityEditor/UnityEditor/ASConfigWindow.cs | 346 ++ UnityEditor/UnityEditor/ASEditorBackend.cs | 290 + UnityEditor/UnityEditor/ASHistoryFileView.cs | 1099 ++++ UnityEditor/UnityEditor/ASHistoryWindow.cs | 1084 ++++ UnityEditor/UnityEditor/ASMainWindow.cs | 1496 +++++ UnityEditor/UnityEditor/ASRefreshState.cs | 9 + .../UnityEditor/ASServerAdminWindow.cs | 493 ++ .../ASUpdateConflictResolveWindow.cs | 698 +++ UnityEditor/UnityEditor/ASUpdateWindow.cs | 548 ++ UnityEditor/UnityEditor/AboutWindow.cs | 181 + UnityEditor/UnityEditor/AboutWindowNames.cs | 645 ++ .../UnityEditor/ActiveEditorTracker.cs | 108 + UnityEditor/UnityEditor/AddComponentWindow.cs | 849 +++ UnityEditor/UnityEditor/AlphabeticalSort.cs | 33 + UnityEditor/UnityEditor/Analytics.cs | 15 + .../UnityEditor/AnchoredJoint2DEditor.cs | 57 + .../UnityEditor/AndroidBuildSubtarget.cs | 14 + .../AndroidPreferredInstallLocation.cs | 10 + UnityEditor/UnityEditor/AndroidSdkRoot.cs | 84 + UnityEditor/UnityEditor/AndroidSdkVersions.cs | 18 + .../AndroidShowActivityIndicatorOnLoading.cs | 12 + .../UnityEditor/AndroidSplashScreenScale.cs | 10 + .../UnityEditor/AndroidTargetDevice.cs | 12 + .../UnityEditor/AnimationClipCurveData.cs | 28 + .../UnityEditor/AnimationClipEditor.cs | 1208 ++++ .../AnimationClipInfoProperties.cs | 543 ++ .../UnityEditor/AnimationClipSettings.cs | 22 + UnityEditor/UnityEditor/AnimationClipStats.cs | 46 + .../UnityEditor/AnimationCurveContextMenu.cs | 51 + UnityEditor/UnityEditor/AnimationEditor.cs | 83 + .../UnityEditor/AnimationEventPopup.cs | 573 ++ .../UnityEditor/AnimationEventTimeLine.cs | 318 + .../UnityEditor/AnimationHierarchyData.cs | 65 + UnityEditor/UnityEditor/AnimationMode.cs | 42 + UnityEditor/UnityEditor/AnimationSelection.cs | 503 ++ UnityEditor/UnityEditor/AnimationUtility.cs | 178 + UnityEditor/UnityEditor/AnimationWindow.cs | 1603 +++++ UnityEditor/UnityEditor/AnimatorInspector.cs | 50 + .../AnimatorOverrideControllerInspector.cs | 94 + UnityEditor/UnityEditor/Annotation.cs | 12 + UnityEditor/UnityEditor/AnnotationUtility.cs | 66 + UnityEditor/UnityEditor/AnnotationWindow.cs | 546 ++ .../UnityEditor/ApiCompatibilityLevel.cs | 9 + UnityEditor/UnityEditor/AppStatusBar.cs | 125 + UnityEditor/UnityEditor/ArrayUtility.cs | 92 + UnityEditor/UnityEditor/AspectRatio.cs | 12 + UnityEditor/UnityEditor/AssembleEditorSkin.cs | 19 + .../AssembliesShippedWithWebPlayerProvider.cs | 17 + UnityEditor/UnityEditor/AssemblyHelper.cs | 347 ++ .../UnityEditor/AssemblyReferenceChecker.cs | 179 + .../UnityEditor/AssemblyReloadEvents.cs | 21 + .../UnityEditor/AssemblyTypeInfoGenerator.cs | 180 + UnityEditor/UnityEditor/AssetDatabase.cs | 362 ++ UnityEditor/UnityEditor/AssetDeleteResult.cs | 11 + UnityEditor/UnityEditor/AssetImporter.cs | 33 + .../UnityEditor/AssetImporterInspector.cs | 217 + .../UnityEditor/AssetImporterTabbedEditor.cs | 74 + UnityEditor/UnityEditor/AssetInspector.cs | 159 + .../UnityEditor/AssetModificationProcessor.cs | 7 + .../AssetModificationProcessorInternal.cs | 334 + UnityEditor/UnityEditor/AssetMoveResult.cs | 11 + .../AssetOrGameObjectTreeViewDragging.cs | 75 + .../AssetPostprocessingInternal.cs | 282 + UnityEditor/UnityEditor/AssetPostprocessor.cs | 67 + UnityEditor/UnityEditor/AssetPreview.cs | 79 + .../UnityEditor/AssetPreviewUpdater.cs | 39 + UnityEditor/UnityEditor/AssetSaveDialog.cs | 231 + UnityEditor/UnityEditor/AssetServer.cs | 362 ++ UnityEditor/UnityEditor/AssetServerConfig.cs | 133 + UnityEditor/UnityEditor/AssetStatus.cs | 18 + UnityEditor/UnityEditor/AssetStoreAsset.cs | 113 + .../UnityEditor/AssetStoreAssetInspector.cs | 553 ++ .../UnityEditor/AssetStoreAssetSelection.cs | 248 + .../UnityEditor/AssetStoreAssetsInfo.cs | 118 + UnityEditor/UnityEditor/AssetStoreClient.cs | 455 ++ UnityEditor/UnityEditor/AssetStoreContext.cs | 284 + .../UnityEditor/AssetStoreInstaBuyWindow.cs | 488 ++ .../UnityEditor/AssetStoreLoginWindow.cs | 213 + .../UnityEditor/AssetStorePreviewManager.cs | 345 ++ UnityEditor/UnityEditor/AssetStoreResponse.cs | 61 + .../UnityEditor/AssetStoreResultBase.cs | 46 + .../UnityEditor/AssetStoreSearchResults.cs | 115 + UnityEditor/UnityEditor/AssetStoreUtils.cs | 91 + UnityEditor/UnityEditor/AssetStoreWindow.cs | 240 + UnityEditor/UnityEditor/AssetsItem.cs | 21 + .../UnityEditor/AssetsTreeViewDataSource.cs | 300 + UnityEditor/UnityEditor/AssetsTreeViewGUI.cs | 110 + UnityEditor/UnityEditor/AsyncHTTPClient.cs | 233 + UnityEditor/UnityEditor/AsyncProgressBar.cs | 33 + UnityEditor/UnityEditor/AttachProfilerUI.cs | 141 + UnityEditor/UnityEditor/AttributeHelper.cs | 267 + .../UnityEditor/AudioChorusFilterEditor.cs | 20 + UnityEditor/UnityEditor/AudioClipInspector.cs | 330 + .../AudioDistortionFilterEditor.cs | 20 + .../UnityEditor/AudioEchoFilterEditor.cs | 20 + UnityEditor/UnityEditor/AudioFilterGUI.cs | 46 + .../UnityEditor/AudioHighPassFilterEditor.cs | 20 + UnityEditor/UnityEditor/AudioImporter.cs | 172 + .../UnityEditor/AudioImporterChannels.cs | 11 + .../UnityEditor/AudioImporterFormat.cs | 9 + .../UnityEditor/AudioImporterInspector.cs | 219 + .../UnityEditor/AudioImporterLoadType.cs | 10 + .../AudioLowPassFilterInspector.cs | 41 + .../UnityEditor/AudioReverbFilterEditor.cs | 76 + .../UnityEditor/AudioReverbZoneEditor.cs | 100 + .../UnityEditor/AudioSourceInspector.cs | 650 ++ UnityEditor/UnityEditor/AudioUtil.cs | 143 + UnityEditor/UnityEditor/AvatarAutoMapper.cs | 1095 ++++ .../UnityEditor/AvatarColliderEditor.cs | 7 + UnityEditor/UnityEditor/AvatarControl.cs | 222 + UnityEditor/UnityEditor/AvatarEditor.cs | 467 ++ UnityEditor/UnityEditor/AvatarHandleEditor.cs | 7 + .../UnityEditor/AvatarMappingEditor.cs | 769 +++ .../UnityEditor/AvatarMaskInspector.cs | 440 ++ UnityEditor/UnityEditor/AvatarMaskUtility.cs | 73 + UnityEditor/UnityEditor/AvatarMuscleEditor.cs | 899 +++ UnityEditor/UnityEditor/AvatarPreview.cs | 797 +++ .../UnityEditor/AvatarPreviewSelection.cs | 38 + UnityEditor/UnityEditor/AvatarSetupTool.cs | 1319 ++++ .../UnityEditor/AvatarSkeletonDrawer.cs | 159 + UnityEditor/UnityEditor/AvatarSubEditor.cs | 140 + UnityEditor/UnityEditor/AvatarUtility.cs | 15 + UnityEditor/UnityEditor/BaseHierarchySort.cs | 20 + UnityEditor/UnityEditor/BaseProjectWindow.cs | 1997 ++++++ .../UnityEditor/BlackBerryBuildSubtarget.cs | 11 + .../UnityEditor/BlackBerryBuildType.cs | 9 + UnityEditor/UnityEditor/BlendTreeInspector.cs | 1693 ++++++ UnityEditor/UnityEditor/BodyMaskEditor.cs | 138 + UnityEditor/UnityEditor/BodyPart.cs | 18 + UnityEditor/UnityEditor/BoneState.cs | 13 + .../UnityEditor/BoxCollider2DEditor.cs | 53 + UnityEditor/UnityEditor/BoxColliderEditor.cs | 57 + UnityEditor/UnityEditor/BoxEditor.cs | 282 + UnityEditor/UnityEditor/Brush.cs | 110 + .../UnityEditor/BuildAssetBundleOptions.cs | 13 + UnityEditor/UnityEditor/BuildOptions.cs | 26 + UnityEditor/UnityEditor/BuildPackageResult.cs | 30 + UnityEditor/UnityEditor/BuildPipeline.cs | 226 + UnityEditor/UnityEditor/BuildPlayerWindow.cs | 1760 ++++++ UnityEditor/UnityEditor/BuildTarget.cs | 34 + UnityEditor/UnityEditor/BuildTargetGroup.cs | 27 + .../UnityEditor/BuildUploadCompletedWindow.cs | 379 ++ UnityEditor/UnityEditor/BuildVerifier.cs | 68 + UnityEditor/UnityEditor/BuiltinResource.cs | 11 + .../BumpMapSettingsFixingWindow.cs | 78 + .../UnityEditor/CacheServerPreferences.cs | 87 + .../UnityEditor/CallbackOrderAttribute.cs | 15 + UnityEditor/UnityEditor/CameraEditor.cs | 368 ++ .../UnityEditor/CanEditMultipleObjects.cs | 7 + UnityEditor/UnityEditor/CanvasEditor.cs | 193 + .../UnityEditor/CapsuleColliderEditor.cs | 137 + UnityEditor/UnityEditor/ChangeFlags.cs | 15 + UnityEditor/UnityEditor/Changeset.cs | 15 + UnityEditor/UnityEditor/ChangesetItem.cs | 19 + .../UnityEditor/CharacterControllerEditor.cs | 147 + .../UnityEditor/CircleCollider2DEditor.cs | 62 + .../UnityEditor/ClampVelocityModuleUI.cs | 85 + .../UnityEditor/ClipAnimationMaskType.cs | 9 + UnityEditor/UnityEditor/ClothInspector.cs | 738 +++ UnityEditor/UnityEditor/CodeStrippingUtils.cs | 223 + .../UnityEditor/Collider2DEditorBase.cs | 47 + .../UnityEditor/Collider3DEditorBase.cs | 26 + UnityEditor/UnityEditor/ColliderEditorBase.cs | 136 + UnityEditor/UnityEditor/ColliderUtil.cs | 15 + UnityEditor/UnityEditor/CollisionModuleUI.cs | 391 ++ .../UnityEditor/ColorByVelocityModuleUI.cs | 41 + UnityEditor/UnityEditor/ColorModuleUI.cs | 37 + UnityEditor/UnityEditor/ColorPicker.cs | 1020 ++++ UnityEditor/UnityEditor/ColorPresetLibrary.cs | 231 + .../UnityEditor/ColorPresetLibraryEditor.cs | 36 + UnityEditor/UnityEditor/ColumnView.cs | 291 + UnityEditor/UnityEditor/ColumnViewElement.cs | 14 + UnityEditor/UnityEditor/CompareInfo.cs | 18 + UnityEditor/UnityEditor/ConsoleWindow.cs | 465 ++ UnityEditor/UnityEditor/ContainerWindow.cs | 656 ++ UnityEditor/UnityEditor/CreateAssetUtility.cs | 101 + .../UnityEditor/CreateBuiltinWindows.cs | 70 + .../UnityEditor/CrossCompileOptions.cs | 14 + .../UnityEditor/CubemapTextureInspector.cs | 234 + UnityEditor/UnityEditor/CurveEditor.cs | 2517 ++++++++ .../UnityEditor/CurveEditorSettings.cs | 165 + UnityEditor/UnityEditor/CurveEditorWindow.cs | 532 ++ UnityEditor/UnityEditor/CurveLibraryType.cs | 9 + UnityEditor/UnityEditor/CurveMenuManager.cs | 253 + UnityEditor/UnityEditor/CurvePresetLibrary.cs | 117 + .../UnityEditor/CurvePresetLibraryEditor.cs | 96 + .../CurvePresetsContentsForPopupWindow.cs | 137 + UnityEditor/UnityEditor/CurveRenderer.cs | 19 + UnityEditor/UnityEditor/CurveRendererCache.cs | 39 + UnityEditor/UnityEditor/CurveSelection.cs | 111 + UnityEditor/UnityEditor/CurveState.cs | 120 + UnityEditor/UnityEditor/CurveUpdater.cs | 9 + UnityEditor/UnityEditor/CurveUtility.cs | 384 ++ UnityEditor/UnityEditor/CurveWrapper.cs | 59 + UnityEditor/UnityEditor/CustomEditor.cs | 28 + .../UnityEditor/CustomEditorAttributes.cs | 96 + .../UnityEditor/CustomPreviewAttribute.cs | 13 + .../UnityEditor/CustomPropertyDrawer.cs | 19 + UnityEditor/UnityEditor/D3D9FullscreenMode.cs | 9 + UnityEditor/UnityEditor/DebugUtils.cs | 45 + UnityEditor/UnityEditor/DecoratorDrawer.cs | 23 + UnityEditor/UnityEditor/DeleteWindowLayout.cs | 54 + UnityEditor/UnityEditor/DeletedAsset.cs | 21 + .../UnityEditor/DetailMeshRenderMode.cs | 9 + UnityEditor/UnityEditor/DetailMeshWizard.cs | 115 + UnityEditor/UnityEditor/DetailPainter.cs | 58 + .../UnityEditor/DetailTextureWizard.cs | 104 + .../UnityEditor/DistanceJoint2DEditor.cs | 25 + UnityEditor/UnityEditor/DockArea.cs | 685 +++ UnityEditor/UnityEditor/DoubleCurve.cs | 70 + .../UnityEditor/DoubleCurvePresetLibrary.cs | 109 + .../DoubleCurvePresetLibraryEditor.cs | 35 + ...oubleCurvePresetsContentsForPopupWindow.cs | 151 + UnityEditor/UnityEditor/DownloadResolution.cs | 12 + UnityEditor/UnityEditor/DragAndDrop.cs | 123 + UnityEditor/UnityEditor/DragAndDropDelay.cs | 13 + .../UnityEditor/DragAndDropVisualMode.cs | 13 + UnityEditor/UnityEditor/DragRectGUI.cs | 62 + UnityEditor/UnityEditor/DrawCameraMode.cs | 13 + UnityEditor/UnityEditor/DrawGizmo.cs | 18 + UnityEditor/UnityEditor/DrawGridParameters.cs | 14 + .../UnityEditor/DrivenRectTransformUndo.cs | 17 + UnityEditor/UnityEditor/DropInfo.cs | 22 + .../UnityEditor/EdgeCollider2DEditor.cs | 56 + UnityEditor/UnityEditor/Editor.cs | 562 ++ UnityEditor/UnityEditor/EditorApplication.cs | 298 + .../UnityEditor/EditorApplicationLayout.cs | 66 + UnityEditor/UnityEditor/EditorAssemblies.cs | 53 + UnityEditor/UnityEditor/EditorBehaviorMode.cs | 9 + .../UnityEditor/EditorBuildSettings.cs | 18 + .../UnityEditor/EditorBuildSettingsScene.cs | 50 + UnityEditor/UnityEditor/EditorCache.cs | 74 + UnityEditor/UnityEditor/EditorCurveBinding.cs | 74 + .../UnityEditor/EditorExtensionMethods.cs | 39 + UnityEditor/UnityEditor/EditorFeatures.cs | 11 + UnityEditor/UnityEditor/EditorGUI.cs | 5367 +++++++++++++++++ UnityEditor/UnityEditor/EditorGUIExt.cs | 824 +++ UnityEditor/UnityEditor/EditorGUIInternal.cs | 57 + UnityEditor/UnityEditor/EditorGUILayout.cs | 1260 ++++ .../EditorGUILayoutUtilityInternal.cs | 19 + UnityEditor/UnityEditor/EditorGUIUtility.cs | 1082 ++++ UnityEditor/UnityEditor/EditorLook.cs | 10 + .../UnityEditor/EditorMaterialUtility.cs | 15 + UnityEditor/UnityEditor/EditorPrefs.cs | 67 + UnityEditor/UnityEditor/EditorSettings.cs | 63 + .../UnityEditor/EditorSettingsInspector.cs | 374 ++ UnityEditor/UnityEditor/EditorSkin.cs | 10 + UnityEditor/UnityEditor/EditorStyles.cs | 631 ++ UnityEditor/UnityEditor/EditorUpdateWindow.cs | 136 + .../UnityEditor/EditorUserBuildSettings.cs | 281 + UnityEditor/UnityEditor/EditorUserSettings.cs | 60 + UnityEditor/UnityEditor/EditorUtility.cs | 355 ++ UnityEditor/UnityEditor/EditorWindow.cs | 779 +++ UnityEditor/UnityEditor/EditorWrapper.cs | 106 + UnityEditor/UnityEditor/EmissionModuleUI.cs | 136 + UnityEditor/UnityEditor/Empty.cs | 14 + .../UnityEditor/EulerCurveCombinedRenderer.cs | 276 + UnityEditor/UnityEditor/EulerCurveRenderer.cs | 59 + .../UnityEditor/EventManipulationHandler.cs | 222 + .../UnityEditor/ExportPackageOptions.cs | 13 + UnityEditor/UnityEditor/ExportRawHeightmap.cs | 112 + UnityEditor/UnityEditor/ExposablePopupMenu.cs | 137 + .../UnityEditor/ExposeTransformEditor.cs | 61 + .../UnityEditor/ExternalForcesModuleUI.cs | 42 + .../UnityEditor/ExternalVersionControl.cs | 28 + UnityEditor/UnityEditor/EyeDropper.cs | 153 + .../UnityEditor/FallbackEditorWindow.cs | 28 + UnityEditor/UnityEditor/FilePathAttribute.cs | 40 + UnityEditor/UnityEditor/FileUtil.cs | 324 + UnityEditor/UnityEditor/FilteredHierarchy.cs | 332 + .../UnityEditor/FilteredHierarchyProperty.cs | 178 + .../UnityEditor/FlashBuildSubtarget.cs | 14 + UnityEditor/UnityEditor/FlattenHeightmap.cs | 26 + UnityEditor/UnityEditor/FlexibleMenu.cs | 296 + .../UnityEditor/FlexibleMenuModifyItemUI.cs | 46 + UnityEditor/UnityEditor/FlowLayout.cs | 172 + .../UnityEditor/FoldoutComponentState.cs | 117 + UnityEditor/UnityEditor/FoldoutObjectState.cs | 147 + UnityEditor/UnityEditor/FoldoutTree.cs | 60 + UnityEditor/UnityEditor/FontInspector.cs | 22 + UnityEditor/UnityEditor/FontRenderingMode.cs | 11 + UnityEditor/UnityEditor/FontTextureCase.cs | 13 + UnityEditor/UnityEditor/ForceModuleUI.cs | 72 + UnityEditor/UnityEditor/GUIDrawer.cs | 7 + UnityEditor/UnityEditor/GUILayoutFadeGroup.cs | 17 + UnityEditor/UnityEditor/GUISlideGroup.cs | 119 + UnityEditor/UnityEditor/GUIStyleX.cs | 9 + UnityEditor/UnityEditor/GUIView.cs | 240 + .../UnityEditor/GameObjectInspector.cs | 754 +++ .../GameObjectTreeViewDataSource.cs | 219 + .../UnityEditor/GameObjectTreeViewGUI.cs | 114 + .../UnityEditor/GameObjectTreeViewItem.cs | 69 + UnityEditor/UnityEditor/GameObjectUtility.cs | 99 + UnityEditor/UnityEditor/GameView.cs | 361 ++ UnityEditor/UnityEditor/GameViewGUI.cs | 118 + UnityEditor/UnityEditor/GameViewSize.cs | 188 + UnityEditor/UnityEditor/GameViewSizeGroup.cs | 123 + .../UnityEditor/GameViewSizeGroupType.cs | 16 + UnityEditor/UnityEditor/GameViewSizeType.cs | 9 + UnityEditor/UnityEditor/GameViewSizes.cs | 470 ++ .../GameViewSizesMenuItemProvider.cs | 99 + .../GameViewSizesMenuModifyItemUI.cs | 134 + UnityEditor/UnityEditor/GccCompiler.cs | 50 + .../UnityEditor/GccCompilerSettingsx86.cs | 35 + .../UnityEditor/GccCompilerSettingsx86_64.cs | 35 + UnityEditor/UnityEditor/GenericInspector.cs | 76 + UnityEditor/UnityEditor/GenericMenu.cs | 98 + .../GenericPresetLibraryInspector.cs | 186 + UnityEditor/UnityEditor/GizmoType.cs | 12 + .../UnityEditor/GradientContextMenu.cs | 40 + UnityEditor/UnityEditor/GradientEditor.cs | 565 ++ UnityEditor/UnityEditor/GradientPicker.cs | 228 + .../UnityEditor/GradientPresetLibrary.cs | 138 + .../GradientPresetLibraryEditor.cs | 36 + UnityEditor/UnityEditor/HandleUtility.cs | 658 ++ UnityEditor/UnityEditor/Handles.cs | 1618 +++++ UnityEditor/UnityEditor/HeaderDrawer.cs | 19 + UnityEditor/UnityEditor/HeapshotReader.cs | 343 ++ UnityEditor/UnityEditor/HeapshotWindow.cs | 544 ++ UnityEditor/UnityEditor/HeightmapFilters.cs | 70 + UnityEditor/UnityEditor/HeightmapPainter.cs | 93 + UnityEditor/UnityEditor/Help.cs | 32 + UnityEditor/UnityEditor/HierarchyProperty.cs | 155 + UnityEditor/UnityEditor/HierarchyType.cs | 9 + UnityEditor/UnityEditor/HierarchyWindow.cs | 11 + UnityEditor/UnityEditor/HighLevelEvent.cs | 16 + .../UnityEditor/HighlightSearchMode.cs | 12 + UnityEditor/UnityEditor/Highlighter.cs | 286 + UnityEditor/UnityEditor/HingeJoint2DEditor.cs | 52 + UnityEditor/UnityEditor/HorizontalLayout.cs | 21 + UnityEditor/UnityEditor/HostView.cs | 280 + UnityEditor/UnityEditor/HumanTemplate.cs | 21 + UnityEditor/UnityEditor/ICleanuppable.cs | 8 + UnityEditor/UnityEditor/IDropArea.cs | 10 + UnityEditor/UnityEditor/IEditablePoint.cs | 21 + .../UnityEditor/IFlexibleMenuItemProvider.cs | 17 + UnityEditor/UnityEditor/IHasCustomMenu.cs | 8 + UnityEditor/UnityEditor/IHierarchyProperty.cs | 78 + UnityEditor/UnityEditor/IPrefType.cs | 9 + UnityEditor/UnityEditor/IPreviewable.cs | 22 + .../UnityEditor/ITreeViewDataSource.cs | 28 + UnityEditor/UnityEditor/ITreeViewDragging.cs | 19 + UnityEditor/UnityEditor/ITreeViewGUI.cs | 26 + UnityEditor/UnityEditor/IconDrawStyle.cs | 9 + UnityEditor/UnityEditor/IconSelector.cs | 321 + UnityEditor/UnityEditor/ImportAssetOptions.cs | 14 + UnityEditor/UnityEditor/ImportRawHeightmap.cs | 148 + UnityEditor/UnityEditor/InitialModuleUI.cs | 127 + .../UnityEditor/InitializeOnLoadAttribute.cs | 8 + UnityEditor/UnityEditor/InspectorMode.cs | 10 + UnityEditor/UnityEditor/InspectorState.cs | 62 + UnityEditor/UnityEditor/InspectorWindow.cs | 1139 ++++ UnityEditor/UnityEditor/InternalMeshUtil.cs | 27 + UnityEditor/UnityEditor/Joint2DEditorBase.cs | 142 + UnityEditor/UnityEditor/KeyIdentifier.cs | 31 + UnityEditor/UnityEditor/LODGroupEditor.cs | 1226 ++++ UnityEditor/UnityEditor/LODUtility.cs | 18 + .../LODVisualizationInformation.cs | 17 + UnityEditor/UnityEditor/LabelGUI.cs | 194 + UnityEditor/UnityEditor/LayerMatrixGUI.cs | 86 + .../UnityEditor/LayerVisibilityWindow.cs | 284 + .../UnityEditor/LayoutDropdownWindow.cs | 565 ++ .../UnityEditor/LazyTreeViewDataSource.cs | 64 + .../UnityEditor/LicenseManagementWindow.cs | 120 + UnityEditor/UnityEditor/LightEditor.cs | 322 + UnityEditor/UnityEditor/LightProbeGUI.cs | 15 + .../UnityEditor/LightProbeGroupEditor.cs | 485 ++ .../UnityEditor/LightProbeGroupInspector.cs | 154 + .../UnityEditor/LightProbeGroupSelection.cs | 10 + .../UnityEditor/LightProbesInspector.cs | 18 + .../UnityEditor/LightmapBakeQuality.cs | 9 + .../UnityEditor/LightmapEditorSettings.cs | 202 + .../UnityEditor/LightmapVisualization.cs | 98 + UnityEditor/UnityEditor/Lightmapping.cs | 42 + UnityEditor/UnityEditor/LightmappingWindow.cs | 1212 ++++ UnityEditor/UnityEditor/ListViewElement.cs | 11 + UnityEditor/UnityEditor/ListViewGUI.cs | 117 + UnityEditor/UnityEditor/ListViewGUILayout.cs | 182 + UnityEditor/UnityEditor/ListViewOptions.cs | 11 + UnityEditor/UnityEditor/ListViewShared.cs | 622 ++ UnityEditor/UnityEditor/ListViewState.cs | 45 + UnityEditor/UnityEditor/MacFullscreenMode.cs | 10 + UnityEditor/UnityEditor/MainWindow.cs | 57 + .../UnityEditor/MaintDatabaseRecord.cs | 12 + UnityEditor/UnityEditor/MaintUserRecord.cs | 14 + .../UnityEditor/ManagedEditorCodeRebuilder.cs | 91 + UnityEditor/UnityEditor/ManipulationTool.cs | 22 + .../UnityEditor/ManipulationToolUtility.cs | 67 + UnityEditor/UnityEditor/MaskFieldGUI.cs | 164 + UnityEditor/UnityEditor/MaterialEditor.cs | 1070 ++++ UnityEditor/UnityEditor/MaterialEnumDrawer.cs | 172 + .../UnityEditor/MaterialKeywordEnumDrawer.cs | 172 + .../UnityEditor/MaterialPowerSliderDrawer.cs | 38 + UnityEditor/UnityEditor/MaterialProperty.cs | 298 + .../UnityEditor/MaterialPropertyDrawer.cs | 131 + .../UnityEditor/MaterialToggleDrawer.cs | 77 + UnityEditor/UnityEditor/MathUtils.cs | 347 ++ UnityEditor/UnityEditor/MaximizedHostView.cs | 88 + UnityEditor/UnityEditor/MecanimUtilities.cs | 86 + UnityEditor/UnityEditor/MemoryElement.cs | 160 + .../UnityEditor/MemoryElementDataManager.cs | 119 + .../UnityEditor/MemoryElementSelection.cs | 108 + UnityEditor/UnityEditor/MemoryTreeList.cs | 301 + .../UnityEditor/MemoryTreeListClickable.cs | 60 + UnityEditor/UnityEditor/MenuCommand.cs | 22 + UnityEditor/UnityEditor/MenuItem.cs | 33 + UnityEditor/UnityEditor/MenuUtils.cs | 47 + UnityEditor/UnityEditor/MeshColliderEditor.cs | 29 + UnityEditor/UnityEditor/MeshRendererEditor.cs | 33 + UnityEditor/UnityEditor/MeshUtility.cs | 42 + UnityEditor/UnityEditor/MessageType.cs | 11 + .../MetroBuildAndRunDeployTarget.cs | 10 + UnityEditor/UnityEditor/MetroBuildType.cs | 12 + .../MetroCertificatePasswordWindow.cs | 111 + .../MetroCreateTestCertificateWindow.cs | 163 + UnityEditor/UnityEditor/MetroSDK.cs | 11 + UnityEditor/UnityEditor/MinMaxCurveState.cs | 11 + .../UnityEditor/MinMaxGradientState.cs | 11 + UnityEditor/UnityEditor/ModelImporter.cs | 384 ++ .../ModelImporterAnimationCompression.cs | 11 + .../UnityEditor/ModelImporterAnimationType.cs | 11 + .../UnityEditor/ModelImporterClipAnimation.cs | 273 + .../UnityEditor/ModelImporterClipEditor.cs | 628 ++ .../UnityEditor/ModelImporterEditor.cs | 41 + .../ModelImporterGenerateAnimations.cs | 12 + .../ModelImporterGenerateMaterials.cs | 11 + .../UnityEditor/ModelImporterMaterialName.cs | 11 + .../ModelImporterMaterialSearch.cs | 10 + .../ModelImporterMeshCompression.cs | 11 + .../UnityEditor/ModelImporterModelEditor.cs | 334 + .../UnityEditor/ModelImporterRigEditor.cs | 574 ++ .../ModelImporterTangentSpaceMode.cs | 10 + UnityEditor/UnityEditor/ModelInspector.cs | 161 + UnityEditor/UnityEditor/ModuleUI.cs | 952 +++ .../UnityEditor/MonoAOTRegistration.cs | 246 + .../UnityEditor/MonoAssemblyStripping.cs | 217 + UnityEditor/UnityEditor/MonoCrossCompile.cs | 287 + UnityEditor/UnityEditor/MonoImporter.cs | 30 + UnityEditor/UnityEditor/MonoManager.cs | 8 + UnityEditor/UnityEditor/MonoProcessUtility.cs | 109 + .../UnityEditor/MonoReloadableIntPtr.cs | 8 + .../UnityEditor/MonoReloadableIntPtrClear.cs | 8 + UnityEditor/UnityEditor/MonoScript.cs | 39 + .../MonoScriptImporterInspector.cs | 110 + .../UnityEditor/MonoScriptInspector.cs | 11 + UnityEditor/UnityEditor/MouseCursor.cs | 27 + UnityEditor/UnityEditor/MoveTool.cs | 30 + UnityEditor/UnityEditor/MovieImporter.cs | 33 + .../UnityEditor/MovieImporterInspector.cs | 77 + .../UnityEditor/MovieTextureInspector.cs | 101 + UnityEditor/UnityEditor/MultilineDrawer.cs | 36 + .../UnityEditor/MuscleClipEditorUtilities.cs | 15 + .../UnityEditor/MuscleClipQualityInfo.cs | 11 + UnityEditor/UnityEditor/NETVersion.cs | 9 + .../UnityEditor/NameConflictResolution.cs | 10 + .../UnityEditor/NavMeshAgentInspector.cs | 90 + UnityEditor/UnityEditor/NavMeshBuilder.cs | 33 + .../UnityEditor/NavMeshEditorWindow.cs | 477 ++ .../UnityEditor/NavMeshObstacleInspector.cs | 34 + .../NavMeshVisualizationSettings.cs | 78 + .../UnityEditor/NormalCurveRenderer.cs | 393 ++ UnityEditor/UnityEditor/OSColorPicker.cs | 40 + UnityEditor/UnityEditor/OSUtil.cs | 18 + UnityEditor/UnityEditor/ObjectCopier.cs | 31 + UnityEditor/UnityEditor/ObjectInfo.cs | 14 + UnityEditor/UnityEditor/ObjectListArea.cs | 3415 +++++++++++ .../UnityEditor/ObjectListAreaState.cs | 25 + UnityEditor/UnityEditor/ObjectNames.cs | 59 + UnityEditor/UnityEditor/ObjectPreview.cs | 220 + .../UnityEditor/ObjectReferenceKeyframe.cs | 10 + UnityEditor/UnityEditor/ObjectSelector.cs | 661 ++ .../UnityEditor/OcclusionAreaEditor.cs | 74 + .../UnityEditor/OcclusionCullingWindow.cs | 516 ++ .../UnityEditor/OcclusionPortalInspector.cs | 35 + .../UnityEditor/OffMeshLinkInspector.cs | 66 + UnityEditor/UnityEditor/OptimizedGUIBlock.cs | 127 + UnityEditor/UnityEditor/OverwriteHandling.cs | 11 + UnityEditor/UnityEditor/PListConfig.cs | 71 + UnityEditor/UnityEditor/PSP2BuildSubtarget.cs | 9 + UnityEditor/UnityEditor/PackageExport.cs | 244 + UnityEditor/UnityEditor/PackageImport.cs | 267 + .../UnityEditor/PackageImportTreeView.cs | 464 ++ UnityEditor/UnityEditor/PackageInfo.cs | 15 + UnityEditor/UnityEditor/PaneDragTab.cs | 209 + UnityEditor/UnityEditor/ParentViewFile.cs | 23 + UnityEditor/UnityEditor/ParentViewFolder.cs | 53 + UnityEditor/UnityEditor/ParentViewState.cs | 211 + UnityEditor/UnityEditor/ParticleEffectUI.cs | 927 +++ .../UnityEditor/ParticleEffectUIOwner.cs | 8 + .../UnityEditor/ParticleEffectUtils.cs | 31 + .../UnityEditor/ParticleSystemClipboard.cs | 84 + .../UnityEditor/ParticleSystemEditorUtils.cs | 117 + .../UnityEditor/ParticleSystemInspector.cs | 206 + .../UnityEditor/ParticleSystemStyles.cs | 47 + UnityEditor/UnityEditor/ParticleSystemUI.cs | 599 ++ .../UnityEditor/ParticleSystemWindow.cs | 279 + UnityEditor/UnityEditor/Physics2DSettings.cs | 8 + .../UnityEditor/Physics2DSettingsInspector.cs | 24 + UnityEditor/UnityEditor/PhysicsManager.cs | 8 + .../UnityEditor/PhysicsManagerInspector.cs | 24 + UnityEditor/UnityEditor/PingData.cs | 69 + UnityEditor/UnityEditor/PivotMode.cs | 9 + UnityEditor/UnityEditor/PivotRotation.cs | 9 + UnityEditor/UnityEditor/PlaceTreeWizard.cs | 18 + UnityEditor/UnityEditor/PlayerSettings.cs | 2124 +++++++ .../UnityEditor/PlayerSettingsEditor.cs | 2310 +++++++ UnityEditor/UnityEditor/PointEditor.cs | 239 + .../UnityEditor/PolygonColliderEditor.cs | 102 + UnityEditor/UnityEditor/PolygonEditor.cs | 65 + .../UnityEditor/PolygonEditorUtility.cs | 321 + UnityEditor/UnityEditor/PopupList.cs | 526 ++ .../UnityEditor/PopupLocationHelper.cs | 166 + UnityEditor/UnityEditor/PopupWindow.cs | 80 + UnityEditor/UnityEditor/PopupWindowContent.cs | 24 + .../PopupWindowContentForNewLibrary.cs | 124 + .../UnityEditor/PopupWindowWithoutFocus.cs | 119 + .../UnityEditor/PostProcessAttribute.cs | 18 + .../UnityEditor/PostprocessBuildPlayer.cs | 466 ++ UnityEditor/UnityEditor/PostprocessScene.cs | 23 + UnityEditor/UnityEditor/PragmaFixingWindow.cs | 79 + UnityEditor/UnityEditor/PrefColor.cs | 93 + UnityEditor/UnityEditor/PrefKey.cs | 80 + UnityEditor/UnityEditor/PrefabInspector.cs | 51 + UnityEditor/UnityEditor/PrefabType.cs | 15 + UnityEditor/UnityEditor/PrefabUtility.cs | 97 + UnityEditor/UnityEditor/PreferenceItem.cs | 13 + UnityEditor/UnityEditor/PreferencesWindow.cs | 838 +++ UnityEditor/UnityEditor/PresetFileLocation.cs | 9 + UnityEditor/UnityEditor/PresetLibrary.cs | 18 + .../UnityEditor/PresetLibraryEditor.cs | 1062 ++++ .../UnityEditor/PresetLibraryEditorState.cs | 63 + .../UnityEditor/PresetLibraryHelpers.cs | 32 + .../UnityEditor/PresetLibraryLocations.cs | 132 + .../UnityEditor/PresetLibraryManager.cs | 170 + UnityEditor/UnityEditor/PreviewBlendTree.cs | 199 + UnityEditor/UnityEditor/PreviewHelpers.cs | 28 + .../UnityEditor/PreviewRenderUtility.cs | 185 + UnityEditor/UnityEditor/PreviewResizer.cs | 174 + UnityEditor/UnityEditor/PreviewWindow.cs | 86 + .../ProceduralMaterialInformation.cs | 68 + .../ProceduralMaterialInspector.cs | 1262 ++++ .../UnityEditor/ProceduralTextureInspector.cs | 89 + UnityEditor/UnityEditor/ProfilerIPWindow.cs | 46 + UnityEditor/UnityEditor/ProfilerWindow.cs | 889 +++ UnityEditor/UnityEditor/ProjectBrowser.cs | 2542 ++++++++ ...ojectBrowserColumnOneTreeViewDataSource.cs | 103 + ...ProjectBrowserColumnOneTreeViewDragging.cs | 83 + .../ProjectBrowserColumnOneTreeViewGUI.cs | 144 + UnityEditor/UnityEditor/ProjectWindowUtil.cs | 260 + .../UnityEditor/PropertyAndTargetHandler.cs | 17 + UnityEditor/UnityEditor/PropertyDrawer.cs | 47 + UnityEditor/UnityEditor/PropertyGUIData.cs | 21 + UnityEditor/UnityEditor/PropertyHandler.cs | 232 + .../UnityEditor/PropertyHandlerCache.cs | 41 + .../UnityEditor/PropertyModification.cs | 14 + UnityEditor/UnityEditor/PurchaseResult.cs | 77 + UnityEditor/UnityEditor/QualityCurvesTime.cs | 11 + .../UnityEditor/QualitySettingsEditor.cs | 467 ++ .../QuaternionCurveTangentCalculation.cs | 240 + UnityEditor/UnityEditor/RagdollBuilder.cs | 518 ++ UnityEditor/UnityEditor/RangeDrawer.cs | 28 + UnityEditor/UnityEditor/RectHandles.cs | 278 + UnityEditor/UnityEditor/RectSelection.cs | 315 + UnityEditor/UnityEditor/RectTool.cs | 617 ++ .../UnityEditor/RectTransformEditor.cs | 1316 ++++ .../UnityEditor/RectTransformSnapping.cs | 230 + UnityEditor/UnityEditor/RemoveAssetOptions.cs | 9 + UnityEditor/UnityEditor/RenameOverlay.cs | 311 + .../UnityEditor/RenderTextureInspector.cs | 107 + .../UnityEditor/RenderThumbnailUtility.cs | 93 + UnityEditor/UnityEditor/RendererModuleUI.cs | 169 + .../UnityEditor/ReplacePrefabOptions.cs | 10 + .../UnityEditor/ResolutionDialogSetting.cs | 10 + UnityEditor/UnityEditor/RigidbodyEditor.cs | 62 + UnityEditor/UnityEditor/RotateTool.cs | 58 + .../UnityEditor/RotationByVelocityModuleUI.cs | 47 + .../UnityEditor/RotationCurveInterpolation.cs | 247 + UnityEditor/UnityEditor/RotationModuleUI.cs | 47 + .../UnityEditor/RuntimeClassRegistry.cs | 393 ++ UnityEditor/UnityEditor/SCEBuildSubtarget.cs | 10 + .../UnityEditor/SaveAssetsProcessor.cs | 8 + UnityEditor/UnityEditor/SaveType.cs | 9 + UnityEditor/UnityEditor/SaveWindowLayout.cs | 35 + UnityEditor/UnityEditor/SavedBool.cs | 34 + UnityEditor/UnityEditor/SavedFilter.cs | 20 + UnityEditor/UnityEditor/SavedFloat.cs | 34 + UnityEditor/UnityEditor/SavedGUIState.cs | 48 + UnityEditor/UnityEditor/SavedInt.cs | 34 + .../UnityEditor/SavedRenderTargetState.cs | 31 + UnityEditor/UnityEditor/SavedSearchFilters.cs | 408 ++ UnityEditor/UnityEditor/ScaleTool.cs | 35 + UnityEditor/UnityEditor/SceneFXWindow.cs | 112 + .../SceneHierarchySortingWindow.cs | 115 + .../UnityEditor/SceneHierarchyWindow.cs | 658 ++ UnityEditor/UnityEditor/SceneModeUtility.cs | 220 + UnityEditor/UnityEditor/SceneView.cs | 1819 ++++++ UnityEditor/UnityEditor/SceneViewGrid.cs | 70 + UnityEditor/UnityEditor/SceneViewMotion.cs | 532 ++ UnityEditor/UnityEditor/SceneViewOverlay.cs | 168 + UnityEditor/UnityEditor/SceneViewRotation.cs | 500 ++ UnityEditor/UnityEditor/ScreenShots.cs | 164 + .../UnityEditor/ScriptAttributeUtility.cs | 263 + .../ScriptCallOptimizationLevel.cs | 9 + .../ScriptExecutionOrderInspector.cs | 652 ++ .../UnityEditor/ScriptReloadProperties.cs | 82 + .../ScriptableObjectSaveLoadHelper.cs | 80 + .../UnityEditor/ScriptableSingleton.cs | 87 + UnityEditor/UnityEditor/ScriptableWizard.cs | 207 + .../UnityEditor/ScriptingImplementation.cs | 10 + UnityEditor/UnityEditor/SearchFilter.cs | 299 + .../UnityEditor/SearchFilterTreeItem.cs | 19 + UnityEditor/UnityEditor/SearchUtility.cs | 161 + .../UnityEditor/SearchableEditorWindow.cs | 247 + UnityEditor/UnityEditor/Selection.cs | 147 + UnityEditor/UnityEditor/SelectionMode.cs | 15 + UnityEditor/UnityEditor/SerializationMode.cs | 10 + .../SerializedFileContainerWriter.cs | 87 + .../UnityEditor/SerializedMinMaxColor.cs | 24 + .../UnityEditor/SerializedMinMaxCurve.cs | 393 ++ .../UnityEditor/SerializedMinMaxGradient.cs | 68 + UnityEditor/UnityEditor/SerializedModule.cs | 50 + UnityEditor/UnityEditor/SerializedObject.cs | 110 + UnityEditor/UnityEditor/SerializedProperty.cs | 579 ++ .../UnityEditor/SerializedPropertyType.cs | 26 + .../UnityEditor/SetResolutionWizard.cs | 107 + UnityEditor/UnityEditor/Settings.cs | 43 + UnityEditor/UnityEditor/ShaderImporter.cs | 18 + .../UnityEditor/ShaderImporterInspector.cs | 153 + UnityEditor/UnityEditor/ShaderInspector.cs | 296 + UnityEditor/UnityEditor/ShaderUtil.cs | 244 + UnityEditor/UnityEditor/ShapeModuleUI.cs | 301 + UnityEditor/UnityEditor/ShowMode.cs | 13 + UnityEditor/UnityEditor/SimpleProfiler.cs | 51 + .../UnityEditor/SizeByVelocityModuleUI.cs | 43 + UnityEditor/UnityEditor/SizeModuleUI.cs | 27 + .../UnityEditor/SkinnedMeshRendererEditor.cs | 129 + .../UnityEditor/SliderJoint2DEditor.cs | 40 + UnityEditor/UnityEditor/SnapEdge.cs | 164 + UnityEditor/UnityEditor/SnapGuide.cs | 37 + .../UnityEditor/SnapGuideCollection.cs | 70 + UnityEditor/UnityEditor/SnapSettings.cs | 169 + UnityEditor/UnityEditor/SpaceDrawer.cs | 13 + .../UnityEditor/SphereColliderEditor.cs | 69 + UnityEditor/UnityEditor/SplatPainter.cs | 88 + UnityEditor/UnityEditor/SplitView.cs | 804 +++ UnityEditor/UnityEditor/SplitterGUILayout.cs | 207 + UnityEditor/UnityEditor/SplitterState.cs | 214 + .../UnityEditor/SpringJoint2DEditor.cs | 25 + .../SpriteEditorTexturePostprocessor.cs | 27 + UnityEditor/UnityEditor/SpriteEditorWindow.cs | 1298 ++++ UnityEditor/UnityEditor/SpriteImportMode.cs | 10 + UnityEditor/UnityEditor/SpriteInspector.cs | 298 + UnityEditor/UnityEditor/SpriteMetaData.cs | 13 + UnityEditor/UnityEditor/SpritePackerMode.cs | 10 + UnityEditor/UnityEditor/SpriteRect.cs | 21 + UnityEditor/UnityEditor/SpriteRectCache.cs | 71 + .../UnityEditor/SpriteRendererInspector.cs | 129 + UnityEditor/UnityEditor/SpriteUtility.cs | 344 ++ .../UnityEditor/SpriteUtilityWindow.cs | 277 + UnityEditor/UnityEditor/StaticEditorFlags.cs | 14 + .../UnityEditor/StaticOcclusionCulling.cs | 69 + .../StaticOcclusionCullingVisualization.cs | 90 + UnityEditor/UnityEditor/StrippingLevel.cs | 11 + UnityEditor/UnityEditor/StructPropertyGUI.cs | 38 + .../UnityEditor/StructPropertyGUILayout.cs | 35 + UnityEditor/UnityEditor/SubModuleUI.cs | 217 + UnityEditor/UnityEditor/SubstanceArchive.cs | 8 + UnityEditor/UnityEditor/SubstanceImporter.cs | 123 + .../UnityEditor/SubstanceImporterInspector.cs | 462 ++ UnityEditor/UnityEditor/SyncVS.cs | 353 ++ UnityEditor/UnityEditor/TabbedEditor.cs | 61 + UnityEditor/UnityEditor/TagManager.cs | 9 + .../UnityEditor/TagManagerInspector.cs | 134 + UnityEditor/UnityEditor/TakeInfo.cs | 14 + UnityEditor/UnityEditor/TangentMode.cs | 12 + .../UnityEditor/TargetChoiceHandler.cs | 76 + UnityEditor/UnityEditor/TargetGlesGraphics.cs | 11 + UnityEditor/UnityEditor/TargetIOSGraphics.cs | 11 + .../UnityEditor/TerrainDetailContextMenus.cs | 56 + .../UnityEditor/TerrainEditorUtility.cs | 123 + UnityEditor/UnityEditor/TerrainInspector.cs | 1163 ++++ .../UnityEditor/TerrainInspectorUtil.cs | 31 + UnityEditor/UnityEditor/TerrainMenus.cs | 78 + .../UnityEditor/TerrainSplatContextMenus.cs | 36 + UnityEditor/UnityEditor/TerrainSplatEditor.cs | 199 + UnityEditor/UnityEditor/TerrainTool.cs | 16 + .../UnityEditor/TerrainTreeContextMenus.cs | 38 + UnityEditor/UnityEditor/TerrainWizard.cs | 40 + UnityEditor/UnityEditor/TerrainWizards.cs | 7 + UnityEditor/UnityEditor/TextAreaDrawer.cs | 42 + UnityEditor/UnityEditor/TextAssetInspector.cs | 43 + UnityEditor/UnityEditor/TextMeshInspector.cs | 33 + UnityEditor/UnityEditor/Texture3DInspector.cs | 104 + .../UnityEditor/TextureImportInstructions.cs | 27 + UnityEditor/UnityEditor/TextureImporter.cs | 388 ++ .../UnityEditor/TextureImporterFormat.cs | 48 + .../TextureImporterGenerateCubemap.cs | 13 + .../UnityEditor/TextureImporterInspector.cs | 2150 +++++++ .../UnityEditor/TextureImporterMipFilter.cs | 9 + .../UnityEditor/TextureImporterNPOTScale.cs | 11 + .../TextureImporterNormalFilter.cs | 9 + .../UnityEditor/TextureImporterSettings.cs | 466 ++ .../UnityEditor/TextureImporterType.cs | 16 + UnityEditor/UnityEditor/TextureInspector.cs | 374 ++ UnityEditor/UnityEditor/TextureUsageMode.cs | 13 + UnityEditor/UnityEditor/TextureUtil.cs | 114 + UnityEditor/UnityEditor/TickHandler.cs | 203 + UnityEditor/UnityEditor/TickStyle.cs | 30 + UnityEditor/UnityEditor/TimeArea.cs | 337 ++ UnityEditor/UnityEditor/TimeControl.cs | 216 + UnityEditor/UnityEditor/TimeHelper.cs | 19 + UnityEditor/UnityEditor/TimeUpdater.cs | 8 + UnityEditor/UnityEditor/Timeline.cs | 811 +++ .../UnityEditor/TizenBuildSubtarget.cs | 10 + UnityEditor/UnityEditor/Tool.cs | 13 + UnityEditor/UnityEditor/Toolbar.cs | 244 + UnityEditor/UnityEditor/Tools.cs | 518 ++ UnityEditor/UnityEditor/TooltipView.cs | 82 + UnityEditor/UnityEditor/TransformInspector.cs | 61 + .../UnityEditor/TransformManipulator.cs | 321 + .../UnityEditor/TransformRotationGUI.cs | 70 + UnityEditor/UnityEditor/TransformSort.cs | 17 + UnityEditor/UnityEditor/TransformX.cs | 11 + UnityEditor/UnityEditor/TransitionPreview.cs | 630 ++ UnityEditor/UnityEditor/TreeAO.cs | 136 + UnityEditor/UnityEditor/TreeAOImporter.cs | 58 + UnityEditor/UnityEditor/TreePainter.cs | 92 + .../UnityEditor/TreePlacementUtility.cs | 39 + UnityEditor/UnityEditor/TreeView.cs | 776 +++ UnityEditor/UnityEditor/TreeViewDataSource.cs | 198 + UnityEditor/UnityEditor/TreeViewDragging.cs | 223 + UnityEditor/UnityEditor/TreeViewGUI.cs | 361 ++ UnityEditor/UnityEditor/TreeViewItem.cs | 114 + UnityEditor/UnityEditor/TreeViewState.cs | 94 + UnityEditor/UnityEditor/TreeViewTest.cs | 664 ++ UnityEditor/UnityEditor/TreeViewTestWindow.cs | 34 + UnityEditor/UnityEditor/TreeViewUtility.cs | 125 + UnityEditor/UnityEditor/TreeWizard.cs | 84 + .../UnityEditor/TrueTypeFontImporter.cs | 125 + .../TrueTypeFontImporterInspector.cs | 242 + UnityEditor/UnityEditor/TypeSelection.cs | 33 + UnityEditor/UnityEditor/TypeSelectionList.cs | 37 + UnityEditor/UnityEditor/UIOrientation.cs | 12 + UnityEditor/UnityEditor/UVModuleUI.cs | 87 + UnityEditor/UnityEditor/Undo.cs | 150 + .../UnityEditor/UndoPropertyModification.cs | 20 + UnityEditor/UnityEditor/UndoSnapshot.cs | 18 + UnityEditor/UnityEditor/UnityStats.cs | 150 + UnityEditor/UnityEditor/Unsupported.cs | 175 + UnityEditor/UnityEditor/UnwrapParam.cs | 17 + UnityEditor/UnityEditor/Unwrapping.cs | 30 + UnityEditor/UnityEditor/UploadingBuild.cs | 11 + .../UnityEditor/UploadingBuildStatus.cs | 12 + .../UnityEditor/UploadingBuildsMonitor.cs | 189 + .../UnityEditor/UploadingBuildsUtility.cs | 33 + UnityEditor/UnityEditor/ValueSmoother.cs | 44 + UnityEditor/UnityEditor/VelocityModuleUI.cs | 61 + UnityEditor/UnityEditor/VertexSnapping.cs | 127 + UnityEditor/UnityEditor/VerticalGrid.cs | 173 + .../UnityEditor/VerticalGridWithSplitter.cs | 150 + UnityEditor/UnityEditor/VerticalLayout.cs | 21 + UnityEditor/UnityEditor/View.cs | 280 + UnityEditor/UnityEditor/ViewTool.cs | 12 + .../UnityEditor/VisualStudioVersion.cs | 11 + .../UnityEditor/VisualizationBlendTree.cs | 107 + .../UnityEditor/WebCamTextureInspector.cs | 91 + UnityEditor/UnityEditor/WebScriptObject.cs | 174 + UnityEditor/UnityEditor/WebView.cs | 288 + UnityEditor/UnityEditor/WelcomeScreen.cs | 167 + .../UnityEditor/WheelColliderEditor.cs | 40 + UnityEditor/UnityEditor/WheelJoint2DEditor.cs | 27 + UnityEditor/UnityEditor/WindInspector.cs | 29 + UnityEditor/UnityEditor/WindowFocusState.cs | 32 + UnityEditor/UnityEditor/WindowLayout.cs | 685 +++ UnityEditor/UnityEditor/WrapModeFixed.cs | 12 + UnityEditor/UnityEditor/WrapModeFixedCurve.cs | 10 + UnityEditor/UnityEditor/XboxBuildSubtarget.cs | 10 + UnityEditor/UnityEditor/XboxOneRunMethod.cs | 9 + UnityEditor/UnityEditor/XboxRunMethod.cs | 10 + UnityEditor/UnityEditor/ZoomableArea.cs | 689 +++ .../UnityEditor/iOSLaunchScreenType.cs | 12 + UnityEditor/UnityEditor/iOSSdkVersion.cs | 9 + .../iOSShowActivityIndicatorOnLoading.cs | 11 + UnityEditor/UnityEditor/iOSStatusBarStyle.cs | 10 + UnityEditor/UnityEditor/iOSTargetDevice.cs | 10 + UnityEditor/UnityEditor/iOSTargetOSVersion.cs | 19 + .../UnityEditor/iOSTargetResolution.cs | 13 + UnityEditor/UnityEditor/iPhoneArchitecture.cs | 10 + .../AssetModificationHook.cs | 87 + .../ChangeSetContextMenu.cs | 111 + .../ListControl.cs | 1194 ++++ .../ListItem.cs | 467 ++ .../Overlay.cs | 119 + .../PendingWindowContextMenu.cs | 92 + .../ProjectContextMenu.cs | 119 + .../ProjectHooks.cs | 21 + .../UnityEditorInternal/AddCurvesPopup.cs | 90 + .../AddCurvesPopupGameObjectNode.cs | 12 + .../AddCurvesPopupHierarchy.cs | 45 + .../AddCurvesPopupHierarchyDataSource.cs | 156 + .../AddCurvesPopupHierarchyGUI.cs | 60 + .../AddCurvesPopupObjectNode.cs | 11 + .../AddCurvesPopupPropertyNode.cs | 28 + .../AnimationCurvePreviewCache.cs | 81 + .../UnityEditorInternal/AnimationKeyTime.cs | 68 + .../UnityEditorInternal/AnimationRecording.cs | 119 + .../AnimationWindowCurve.cs | 226 + .../AnimationWindowHierarchy.cs | 47 + .../AnimationWindowHierarchyAddButtonNode.cs | 10 + .../AnimationWindowHierarchyDataSource.cs | 135 + .../AnimationWindowHierarchyDragging.cs | 33 + .../AnimationWindowHierarchyGUI.cs | 807 +++ .../AnimationWindowHierarchyMasterNode.cs | 10 + .../AnimationWindowHierarchyNode.cs | 22 + ...imationWindowHierarchyPropertyGroupNode.cs | 11 + .../AnimationWindowHierarchyPropertyNode.cs | 14 + .../AnimationWindowHierarchyState.cs | 26 + .../AnimationWindowKeyframe.cs | 97 + .../AnimationWindowState.cs | 887 +++ .../AnimationWindowUtility.cs | 433 ++ .../UnityEditorInternal/AnimatorCondition.cs | 97 + .../UnityEditorInternal/AnimatorController.cs | 250 + .../AnimatorControllerLayer.cs | 153 + .../AnimatorControllerParameter.cs | 111 + .../AnimatorControllerParameterType.cs | 11 + .../AnimatorLayerBlendingMode.cs | 9 + .../UnityEditorInternal/AssemblyStripper.cs | 125 + UnityEditor/UnityEditorInternal/AssetStore.cs | 19 + .../AssetStoreToolUtils.cs | 27 + UnityEditor/UnityEditorInternal/AvatarMask.cs | 72 + .../BaseIl2CppPlatformProvider.cs | 146 + .../UnityEditorInternal/BaseObjectTools.cs | 24 + UnityEditor/UnityEditorInternal/BlendTree.cs | 136 + .../BlendTreePreviewUtility.cs | 22 + .../UnityEditorInternal/BlendTreeType.cs | 11 + UnityEditor/UnityEditorInternal/Button.cs | 58 + .../UnityEditorInternal/CameraUtility.cs | 21 + .../UnityEditorInternal/CanAppendBuild.cs | 10 + UnityEditor/UnityEditorInternal/Chart.cs | 728 +++ UnityEditor/UnityEditorInternal/ChartData.cs | 46 + .../UnityEditorInternal/ChartSeries.cs | 27 + .../UnityEditorInternal/ComponentUtility.cs | 24 + UnityEditor/UnityEditorInternal/Disc.cs | 147 + UnityEditor/UnityEditorInternal/DopeLine.cs | 75 + .../UnityEditorInternal/DopeSheetEditor.cs | 1259 ++++ .../EditorResourcesUtility.cs | 57 + UnityEditor/UnityEditorInternal/FreeMove.cs | 139 + UnityEditor/UnityEditorInternal/FreeRotate.cs | 106 + .../GradientPreviewCache.cs | 19 + .../IIl2CppPlatformProvider.cs | 53 + .../UnityEditorInternal/IL2CPPBuilder.cs | 238 + .../UnityEditorInternal/IL2CPPUtils.cs | 34 + .../IProfilerWindowController.cs | 11 + .../InternalEditorUtility.cs | 1170 ++++ .../InternalGraphUtility.cs | 18 + .../InternalSpriteUtility.cs | 19 + .../UnityEditorInternal/JSONParseException.cs | 10 + UnityEditor/UnityEditorInternal/JSONParser.cs | 370 ++ .../UnityEditorInternal/JSONTypeException.cs | 10 + UnityEditor/UnityEditorInternal/JSONValue.cs | 303 + UnityEditor/UnityEditorInternal/LogEntries.cs | 60 + UnityEditor/UnityEditorInternal/LogEntry.cs | 17 + .../MaterialAnimationUtility.cs | 87 + .../UnityEditorInternal/MemoryInfoGCReason.cs | 16 + .../UnityEditorInternal/MonoScripts.cs | 14 + .../UnityEditorInternal/NativeProgram.cs | 24 + .../UnityEditorInternal/ObjectMemoryInfo.cs | 16 + .../ObjectMemoryStackInfo.cs | 16 + .../PostProcessNaclPlayer.cs | 201 + .../UnityEditorInternal/ProfilerArea.cs | 15 + .../UnityEditorInternal/ProfilerChart.cs | 47 + .../UnityEditorInternal/ProfilerColors.cs | 19 + .../UnityEditorInternal/ProfilerColumn.cs | 21 + .../UnityEditorInternal/ProfilerDriver.cs | 159 + .../ProfilerFrameDataIterator.cs | 83 + .../ProfilerHierarchyGUI.cs | 645 ++ .../UnityEditorInternal/ProfilerMemoryView.cs | 9 + .../UnityEditorInternal/ProfilerProperty.cs | 95 + .../ProfilerTimelineGUI.cs | 400 ++ .../UnityEditorInternal/ProfilerViewType.cs | 10 + .../UnityEditorInternal/RegistryUtil.cs | 12 + .../UnityEditorInternal/ReorderableList.cs | 651 ++ UnityEditor/UnityEditorInternal/Runner.cs | 69 + UnityEditor/UnityEditorInternal/Slider1D.cs | 82 + UnityEditor/UnityEditorInternal/Slider2D.cs | 144 + .../UnityEditorInternal/SliderScale.cs | 143 + .../SpriteEditorHandles.cs | 304 + .../UnityEditorInternal/SpriteEditorMenu.cs | 184 + .../SpriteEditorUtility.cs | 131 + UnityEditor/UnityEditorInternal/State.cs | 140 + .../UnityEditorInternal/StateMachine.cs | 280 + UnityEditor/UnityEditorInternal/Transition.cs | 162 + .../TransitionConditionMode.cs | 14 + .../UnityEditorInternal/UnityEventDrawer.cs | 670 ++ UnityEditor/ValidationResult.cs | 9 + UnityEditor/WinRTUtils.cs | 9 + .../WindowsDesktopStandalonePostProcessor.cs | 88 + .../AOT/MonoPInvokeCallbackAttribute.cs | 11 + UnityEngine/Properties/AssemblyInfo.cs | 10 + .../UnityEngine.Events/ArgumentCache.cs | 84 + .../UnityEngine.Events/BaseInvokableCall.cs | 39 + .../UnityEngine.Events/CachedInvokableCall.cs | 17 + .../UnityEngine.Events/InvokableCall.cs | 207 + .../UnityEngine.Events/InvokableCallList.cs | 57 + .../UnityEngine.Events/PersistentCall.cs | 142 + .../UnityEngine.Events/PersistentCallGroup.cs | 125 + .../PersistentListenerMode.cs | 15 + UnityEngine/UnityEngine.Events/UnityAction.cs | 9 + UnityEngine/UnityEngine.Events/UnityEvent.cs | 253 + .../UnityEngine.Events/UnityEventBase.cs | 366 ++ .../UnityEngine.Events/UnityEventCallState.cs | 10 + UnityEngine/UnityEngine.Flash/ActionScript.cs | 21 + UnityEngine/UnityEngine.Flash/FlashPlayer.cs | 28 + .../DefaultValueAttribute.cs | 42 + .../ExcludeFromDocsAttribute.cs | 9 + .../UnityEngine.Rendering/BlendMode.cs | 18 + UnityEngine/UnityEngine.Rendering/BlendOp.cs | 28 + .../UnityEngine.Rendering/ColorWriteMask.cs | 13 + .../UnityEngine.Rendering/CompareFunction.cs | 16 + UnityEngine/UnityEngine.Rendering/CullMode.cs | 10 + .../UnityEngine.Rendering/StencilOp.cs | 15 + .../DictionarySerializationSurrogate.cs | 33 + .../FormerlySerializedAsAttribute.cs | 20 + .../ListSerializationSurrogate.cs | 42 + .../SerializationHelper.cs | 18 + .../UnitySurrogateSelector.cs | 37 + .../GameCenterPlatform.cs | 20 + .../Achievement.cs | 91 + .../AchievementDescription.cs | 91 + .../Leaderboard.cs | 135 + .../LocalUser.cs | 57 + .../UnityEngine.SocialPlatforms.Impl/Score.cs | 100 + .../UserProfile.cs | 99 + .../ActivePlatform.cs | 27 + .../IAchievement.cs | 30 + .../IAchievementDescription.cs | 36 + .../ILeaderboard.cs | 49 + .../UnityEngine.SocialPlatforms/ILocalUser.cs | 21 + .../UnityEngine.SocialPlatforms/IScore.cs | 34 + .../ISocialPlatform.cs | 25 + .../IUserProfile.cs | 27 + .../UnityEngine.SocialPlatforms/Local.cs | 308 + .../UnityEngine.SocialPlatforms/Range.cs | 14 + .../UnityEngine.SocialPlatforms/TimeScope.cs | 10 + .../UnityEngine.SocialPlatforms/UserScope.cs | 9 + .../UnityEngine.SocialPlatforms/UserState.cs | 12 + .../UnityEngine.Sprites/DataUtility.cs | 26 + UnityEngine/UnityEngine.csproj | 611 ++ UnityEngine/UnityEngine/ADBannerView.cs | 181 + UnityEngine/UnityEngine/ADInterstitialAd.cs | 98 + UnityEngine/UnityEngine/AccelerationEvent.cs | 23 + UnityEngine/UnityEngine/AddComponentMenu.cs | 33 + UnityEngine/UnityEngine/AnchoredJoint2D.cs | 46 + .../AndroidActivityIndicatorStyle.cs | 12 + UnityEngine/UnityEngine/AndroidInput.cs | 38 + UnityEngine/UnityEngine/AndroidJNI.cs | 444 ++ UnityEngine/UnityEngine/AndroidJNIHelper.cs | 116 + UnityEngine/UnityEngine/AndroidJNISafe.cs | 1218 ++++ UnityEngine/UnityEngine/AndroidJavaClass.cs | 29 + .../UnityEngine/AndroidJavaException.cs | 10 + UnityEngine/UnityEngine/AndroidJavaObject.cs | 762 +++ UnityEngine/UnityEngine/AndroidJavaProxy.cs | 79 + .../UnityEngine/AndroidJavaRunnable.cs | 5 + .../UnityEngine/AndroidJavaRunnableProxy.cs | 16 + UnityEngine/UnityEngine/AndroidReflection.cs | 88 + UnityEngine/UnityEngine/Animation.cs | 320 + UnityEngine/UnityEngine/AnimationBlendMode.cs | 9 + UnityEngine/UnityEngine/AnimationClip.cs | 90 + UnityEngine/UnityEngine/AnimationClipPair.cs | 12 + .../UnityEngine/AnimationCullingType.cs | 11 + UnityEngine/UnityEngine/AnimationCurve.cs | 129 + UnityEngine/UnityEngine/AnimationEvent.cs | 110 + UnityEngine/UnityEngine/AnimationInfo.cs | 27 + UnityEngine/UnityEngine/AnimationPlayMode.cs | 10 + UnityEngine/UnityEngine/AnimationState.cs | 123 + UnityEngine/UnityEngine/Animator.cs | 762 +++ .../UnityEngine/AnimatorCullingMode.cs | 9 + .../UnityEngine/AnimatorOverrideController.cs | 114 + UnityEngine/UnityEngine/AnimatorStateInfo.cs | 57 + .../UnityEngine/AnimatorTransitionInfo.cs | 39 + UnityEngine/UnityEngine/AnimatorUpdateMode.cs | 10 + UnityEngine/UnityEngine/AnimatorUtility.cs | 14 + .../UnityEngine/AnisotropicFiltering.cs | 10 + UnityEngine/UnityEngine/Application.cs | 434 ++ UnityEngine/UnityEngine/ArmDoF.cs | 17 + .../UnityEngine/AssemblyIsEditorAssembly.cs | 8 + UnityEngine/UnityEngine/AssetBundle.cs | 47 + .../UnityEngine/AssetBundleCreateRequest.cs | 17 + UnityEngine/UnityEngine/AssetBundleRequest.cs | 19 + UnityEngine/UnityEngine/AsyncOperation.cs | 49 + .../UnityEngine/AttributeHelperEngine.cs | 83 + UnityEngine/UnityEngine/AudioChorusFilter.cs | 81 + UnityEngine/UnityEngine/AudioClip.cs | 132 + .../UnityEngine/AudioDistortionFilter.cs | 17 + UnityEngine/UnityEngine/AudioEchoFilter.cs | 44 + .../UnityEngine/AudioHighPassFilter.cs | 26 + UnityEngine/UnityEngine/AudioListener.cs | 63 + UnityEngine/UnityEngine/AudioLowPassFilter.cs | 26 + UnityEngine/UnityEngine/AudioReverbFilter.cs | 152 + UnityEngine/UnityEngine/AudioReverbPreset.cs | 35 + UnityEngine/UnityEngine/AudioReverbZone.cs | 161 + UnityEngine/UnityEngine/AudioRolloffMode.cs | 10 + UnityEngine/UnityEngine/AudioSettings.cs | 44 + UnityEngine/UnityEngine/AudioSource.cs | 327 + UnityEngine/UnityEngine/AudioSpeakerMode.cs | 15 + UnityEngine/UnityEngine/AudioType.cs | 20 + .../UnityEngine/AudioVelocityUpdateMode.cs | 10 + UnityEngine/UnityEngine/Avatar.cs | 52 + UnityEngine/UnityEngine/AvatarBuilder.cs | 18 + UnityEngine/UnityEngine/AvatarIKGoal.cs | 11 + UnityEngine/UnityEngine/AvatarTarget.cs | 13 + UnityEngine/UnityEngine/Behaviour.cs | 23 + UnityEngine/UnityEngine/BitStream.cs | 119 + UnityEngine/UnityEngine/BlendWeights.cs | 10 + UnityEngine/UnityEngine/BodyDoF.cs | 14 + UnityEngine/UnityEngine/BoneWeight.cs | 134 + UnityEngine/UnityEngine/Bounds.cs | 172 + UnityEngine/UnityEngine/BoxCollider.cs | 58 + UnityEngine/UnityEngine/BoxCollider2D.cs | 46 + UnityEngine/UnityEngine/CacheIndex.cs | 11 + UnityEngine/UnityEngine/Caching.cs | 115 + UnityEngine/UnityEngine/CalendarIdentifier.cs | 18 + UnityEngine/UnityEngine/CalendarUnit.cs | 18 + UnityEngine/UnityEngine/Camera.cs | 584 ++ UnityEngine/UnityEngine/CameraClearFlags.cs | 12 + .../UnityEngine/CanConvertToFlashAttribute.cs | 15 + UnityEngine/UnityEngine/Canvas.cs | 162 + UnityEngine/UnityEngine/CanvasGroup.cs | 48 + UnityEngine/UnityEngine/CanvasRenderer.cs | 106 + UnityEngine/UnityEngine/CapsuleCollider.cs | 54 + .../UnityEngine/CharacterController.cs | 110 + UnityEngine/UnityEngine/CharacterInfo.cs | 14 + UnityEngine/UnityEngine/CharacterJoint.cs | 160 + UnityEngine/UnityEngine/CircleCollider2D.cs | 36 + .../UnityEngine/ClassLibraryInitializer.cs | 11 + UnityEngine/UnityEngine/Cloth.cs | 121 + UnityEngine/UnityEngine/ClothRenderer.cs | 17 + .../UnityEngine/ClothSkinningCoefficient.cs | 11 + UnityEngine/UnityEngine/Collider.cs | 80 + UnityEngine/UnityEngine/Collider2D.cs | 63 + .../UnityEngine/ColliderErrorState2D.cs | 10 + UnityEngine/UnityEngine/Collision.cs | 84 + UnityEngine/UnityEngine/Collision2D.cs | 55 + .../UnityEngine/CollisionDetectionMode.cs | 10 + .../UnityEngine/CollisionDetectionMode2D.cs | 9 + UnityEngine/UnityEngine/CollisionFlags.cs | 14 + UnityEngine/UnityEngine/Color.cs | 252 + UnityEngine/UnityEngine/Color32.cs | 51 + UnityEngine/UnityEngine/ColorSpace.cs | 10 + UnityEngine/UnityEngine/CombineInstance.cs | 47 + UnityEngine/UnityEngine/Compass.cs | 47 + UnityEngine/UnityEngine/Component.cs | 310 + UnityEngine/UnityEngine/ComputeBuffer.cs | 74 + UnityEngine/UnityEngine/ComputeBufferType.cs | 13 + UnityEngine/UnityEngine/ComputeShader.cs | 47 + UnityEngine/UnityEngine/ConfigurableJoint.cs | 420 ++ .../UnityEngine/ConfigurableJointMotion.cs | 10 + .../UnityEngine/ConnectionTesterStatus.cs | 18 + UnityEngine/UnityEngine/ConstantForce.cs | 84 + .../UnityEngine/ConstructorSafeAttribute.cs | 8 + UnityEngine/UnityEngine/ContactPoint.cs | 39 + UnityEngine/UnityEngine/ContactPoint2D.cs | 39 + UnityEngine/UnityEngine/ContextMenu.cs | 19 + .../UnityEngine/ContextMenuItemAttribute.cs | 15 + .../UnityEngine/ControllerColliderHit.cs | 90 + UnityEngine/UnityEngine/Coroutine.cs | 21 + UnityEngine/UnityEngine/CppBodyAttribute.cs | 11 + UnityEngine/UnityEngine/CppDefineAttribute.cs | 11 + .../UnityEngine/CppIncludeAttribute.cs | 11 + UnityEngine/UnityEngine/CppInvokeAttribute.cs | 8 + .../UnityEngine/CppPropertyAttribute.cs | 14 + .../UnityEngine/CppPropertyBodyAttribute.cs | 14 + UnityEngine/UnityEngine/CrashReport.cs | 138 + UnityEngine/UnityEngine/Cubemap.cs | 75 + UnityEngine/UnityEngine/CubemapFace.cs | 13 + UnityEngine/UnityEngine/Cursor.cs | 19 + UnityEngine/UnityEngine/CursorMode.cs | 9 + UnityEngine/UnityEngine/Debug.cs | 130 + UnityEngine/UnityEngine/DepthTextureMode.cs | 11 + UnityEngine/UnityEngine/DetailPrototype.cs | 153 + UnityEngine/UnityEngine/DetailRenderMode.cs | 10 + UnityEngine/UnityEngine/DeviceOrientation.cs | 14 + UnityEngine/UnityEngine/DeviceType.cs | 11 + .../UnityEngine/DisallowMultipleComponent.cs | 8 + UnityEngine/UnityEngine/Display.cs | 147 + UnityEngine/UnityEngine/DistanceJoint2D.cs | 42 + UnityEngine/UnityEngine/DoF.cs | 24 + .../UnityEngine/DrivenRectTransformTracker.cs | 41 + .../UnityEngine/DrivenTransformProperties.cs | 33 + UnityEngine/UnityEngine/EdgeCollider2D.cs | 32 + UnityEngine/UnityEngine/Event.cs | 718 +++ UnityEngine/UnityEngine/EventModifiers.cs | 16 + UnityEngine/UnityEngine/EventType.cs | 37 + UnityEngine/UnityEngine/ExecuteInEditMode.cs | 7 + UnityEngine/UnityEngine/ExitGUIException.cs | 7 + UnityEngine/UnityEngine/FFTWindow.cs | 13 + UnityEngine/UnityEngine/FilterMode.cs | 10 + UnityEngine/UnityEngine/FingerDoF.cs | 12 + UnityEngine/UnityEngine/FixedJoint.cs | 7 + UnityEngine/UnityEngine/Flare.cs | 7 + UnityEngine/UnityEngine/FocusType.cs | 10 + UnityEngine/UnityEngine/FogMode.cs | 10 + UnityEngine/UnityEngine/Font.cs | 130 + UnityEngine/UnityEngine/FontStyle.cs | 11 + UnityEngine/UnityEngine/ForceMode.cs | 11 + UnityEngine/UnityEngine/ForceMode2D.cs | 9 + .../UnityEngine/FullScreenMovieControlMode.cs | 11 + .../UnityEngine/FullScreenMovieScalingMode.cs | 11 + UnityEngine/UnityEngine/GL.cs | 178 + UnityEngine/UnityEngine/GUI.cs | 1628 +++++ UnityEngine/UnityEngine/GUIAspectSizer.cs | 17 + UnityEngine/UnityEngine/GUIClip.cs | 109 + UnityEngine/UnityEngine/GUIContent.cs | 144 + UnityEngine/UnityEngine/GUIElement.cs | 31 + UnityEngine/UnityEngine/GUIGridSizer.cs | 143 + UnityEngine/UnityEngine/GUILayer.cs | 15 + UnityEngine/UnityEngine/GUILayout.cs | 655 ++ UnityEngine/UnityEngine/GUILayoutEntry.cs | 176 + UnityEngine/UnityEngine/GUILayoutGroup.cs | 589 ++ UnityEngine/UnityEngine/GUILayoutOption.cs | 31 + UnityEngine/UnityEngine/GUILayoutUtility.cs | 390 ++ UnityEngine/UnityEngine/GUIScrollGroup.cs | 151 + UnityEngine/UnityEngine/GUISettings.cs | 81 + UnityEngine/UnityEngine/GUISkin.cs | 557 ++ UnityEngine/UnityEngine/GUIStateObjects.cs | 30 + UnityEngine/UnityEngine/GUIStyle.cs | 707 +++ UnityEngine/UnityEngine/GUIStyleState.cs | 81 + UnityEngine/UnityEngine/GUIText.cs | 140 + UnityEngine/UnityEngine/GUITexture.cs | 64 + UnityEngine/UnityEngine/GUIUtility.cs | 237 + UnityEngine/UnityEngine/GUIWordWrapSizer.cs | 57 + UnityEngine/UnityEngine/GameObject.cs | 458 ++ UnityEngine/UnityEngine/GeometryUtility.cs | 32 + UnityEngine/UnityEngine/Gizmos.cs | 133 + UnityEngine/UnityEngine/Gradient.cs | 68 + UnityEngine/UnityEngine/GradientAlphaKey.cs | 14 + UnityEngine/UnityEngine/GradientColorKey.cs | 14 + UnityEngine/UnityEngine/Graphics.cs | 377 ++ UnityEngine/UnityEngine/Gyroscope.cs | 97 + UnityEngine/UnityEngine/Handheld.cs | 72 + UnityEngine/UnityEngine/HeadDoF.cs | 20 + UnityEngine/UnityEngine/HeaderAttribute.cs | 13 + UnityEngine/UnityEngine/HideFlags.cs | 14 + UnityEngine/UnityEngine/HideInInspector.cs | 7 + UnityEngine/UnityEngine/HingeJoint.cs | 104 + UnityEngine/UnityEngine/HingeJoint2D.cs | 111 + UnityEngine/UnityEngine/HorizontalWrapMode.cs | 9 + UnityEngine/UnityEngine/HostData.cs | 129 + UnityEngine/UnityEngine/HumanBodyBones.cs | 62 + UnityEngine/UnityEngine/HumanBodyPart.cs | 11 + UnityEngine/UnityEngine/HumanBone.cs | 32 + UnityEngine/UnityEngine/HumanDescription.cs | 93 + UnityEngine/UnityEngine/HumanLimit.cs | 67 + UnityEngine/UnityEngine/HumanParameter.cs | 14 + UnityEngine/UnityEngine/HumanTrait.cs | 56 + .../UnityEngine/ICanvasRaycastFilter.cs | 8 + UnityEngine/UnityEngine/IMECompositionMode.cs | 10 + .../ISerializationCallbackReceiver.cs | 9 + UnityEngine/UnityEngine/ImageEffectOpaque.cs | 7 + .../UnityEngine/ImageEffectTransformsToLDR.cs | 7 + UnityEngine/UnityEngine/ImagePosition.cs | 11 + .../ImplementedInActionScriptAttribute.cs | 8 + UnityEngine/UnityEngine/Input.cs | 313 + UnityEngine/UnityEngine/InteractiveCloth.cs | 119 + .../InternalDrawTextureArguments.cs | 16 + .../InternalEmitParticleArguments.cs | 14 + .../InternalStaticBatchingUtility.cs | 199 + .../UnityEngine/Internal_DrawArguments.cs | 13 + .../Internal_DrawMeshMatrixArguments.cs | 12 + .../Internal_DrawMeshTRArguments.cs | 13 + ...Internal_DrawWithTextSelectionArguments.cs | 18 + UnityEngine/UnityEngine/Joint.cs | 110 + UnityEngine/UnityEngine/Joint2D.cs | 26 + UnityEngine/UnityEngine/JointAngleLimits2D.cs | 31 + UnityEngine/UnityEngine/JointDrive.cs | 55 + UnityEngine/UnityEngine/JointDriveMode.cs | 12 + UnityEngine/UnityEngine/JointLimitState2D.cs | 11 + UnityEngine/UnityEngine/JointLimits.cs | 57 + UnityEngine/UnityEngine/JointMotor.cs | 43 + UnityEngine/UnityEngine/JointMotor2D.cs | 31 + .../UnityEngine/JointProjectionMode.cs | 10 + UnityEngine/UnityEngine/JointSpring.cs | 10 + UnityEngine/UnityEngine/JointSuspension2D.cs | 43 + .../UnityEngine/JointTranslationLimits2D.cs | 31 + UnityEngine/UnityEngine/KeyCode.cs | 248 + UnityEngine/UnityEngine/Keyframe.cs | 83 + UnityEngine/UnityEngine/LOD.cs | 14 + UnityEngine/UnityEngine/LODGroup.cs | 60 + UnityEngine/UnityEngine/LayerMask.cs | 50 + UnityEngine/UnityEngine/LegDoF.cs | 16 + UnityEngine/UnityEngine/LensFlare.cs | 54 + UnityEngine/UnityEngine/Light.cs | 227 + UnityEngine/UnityEngine/LightProbeGroup.cs | 17 + UnityEngine/UnityEngine/LightProbes.cs | 42 + UnityEngine/UnityEngine/LightRenderMode.cs | 10 + UnityEngine/UnityEngine/LightShadows.cs | 10 + UnityEngine/UnityEngine/LightType.cs | 11 + UnityEngine/UnityEngine/LightmapData.cs | 45 + UnityEngine/UnityEngine/LightmapSettings.cs | 44 + UnityEngine/UnityEngine/LightmapsMode.cs | 10 + UnityEngine/UnityEngine/LineRenderer.cs | 45 + UnityEngine/UnityEngine/LocalNotification.cs | 144 + .../UnityEngine/LocalNotificationType.cs | 11 + UnityEngine/UnityEngine/LocationInfo.cs | 55 + UnityEngine/UnityEngine/LocationService.cs | 46 + .../UnityEngine/LocationServiceStatus.cs | 11 + UnityEngine/UnityEngine/LogType.cs | 12 + .../UnityEngine/MarshallOnlyFirstField.cs | 9 + UnityEngine/UnityEngine/MasterServer.cs | 66 + UnityEngine/UnityEngine/MasterServerEvent.cs | 12 + .../UnityEngine/MatchTargetWeightMask.cs | 36 + UnityEngine/UnityEngine/Material.cs | 276 + .../UnityEngine/MaterialPropertyBlock.cs | 148 + UnityEngine/UnityEngine/Mathf.cs | 444 ++ UnityEngine/UnityEngine/Matrix4x4.cs | 411 ++ UnityEngine/UnityEngine/Mesh.cs | 236 + UnityEngine/UnityEngine/MeshCollider.cs | 47 + UnityEngine/UnityEngine/MeshFilter.cs | 26 + UnityEngine/UnityEngine/MeshRenderer.cs | 7 + .../UnityEngine/MeshSubsetCombineUtility.cs | 21 + UnityEngine/UnityEngine/MeshTopology.cs | 12 + UnityEngine/UnityEngine/Microphone.cs | 29 + .../UnityEngine/MissingComponentException.cs | 26 + .../UnityEngine/MissingReferenceException.cs | 26 + UnityEngine/UnityEngine/MonoBehaviour.cs | 88 + UnityEngine/UnityEngine/Motion.cs | 53 + UnityEngine/UnityEngine/MovieTexture.cs | 62 + UnityEngine/UnityEngine/MultilineAttribute.cs | 17 + UnityEngine/UnityEngine/NPOTSupport.cs | 10 + UnityEngine/UnityEngine/NavMesh.cs | 68 + UnityEngine/UnityEngine/NavMeshAgent.cs | 389 ++ UnityEngine/UnityEngine/NavMeshHit.cs | 67 + UnityEngine/UnityEngine/NavMeshObstacle.cs | 63 + UnityEngine/UnityEngine/NavMeshPath.cs | 55 + UnityEngine/UnityEngine/NavMeshPathStatus.cs | 10 + .../UnityEngine/NavMeshTriangulation.cs | 10 + UnityEngine/UnityEngine/Network.cs | 401 ++ .../UnityEngine/NetworkConnectionError.cs | 22 + .../UnityEngine/NetworkDisconnection.cs | 9 + UnityEngine/UnityEngine/NetworkLogLevel.cs | 10 + UnityEngine/UnityEngine/NetworkMessageInfo.cs | 40 + UnityEngine/UnityEngine/NetworkPeerType.cs | 11 + UnityEngine/UnityEngine/NetworkPlayer.cs | 117 + .../UnityEngine/NetworkReachability.cs | 10 + .../NetworkStateSynchronization.cs | 10 + UnityEngine/UnityEngine/NetworkView.cs | 96 + UnityEngine/UnityEngine/NetworkViewID.cs | 86 + .../UnityEngine/NotConvertedAttribute.cs | 8 + .../UnityEngine/NotFlashValidatedAttribute.cs | 8 + .../UnityEngine/NotRenamedAttribute.cs | 8 + .../UnityEngine/NotificationServices.cs | 103 + UnityEngine/UnityEngine/Object.cs | 158 + .../UnityEngine/ObstacleAvoidanceType.cs | 12 + UnityEngine/UnityEngine/OcclusionArea.cs | 46 + UnityEngine/UnityEngine/OcclusionPortal.cs | 17 + UnityEngine/UnityEngine/OffMeshLink.cs | 80 + UnityEngine/UnityEngine/OffMeshLinkData.cs | 59 + UnityEngine/UnityEngine/OffMeshLinkType.cs | 10 + UnityEngine/UnityEngine/Particle.cs | 103 + UnityEngine/UnityEngine/ParticleAnimator.cs | 129 + UnityEngine/UnityEngine/ParticleEmitter.cs | 245 + UnityEngine/UnityEngine/ParticleRenderMode.cs | 12 + UnityEngine/UnityEngine/ParticleRenderer.cs | 145 + UnityEngine/UnityEngine/ParticleSystem.cs | 603 ++ .../UnityEngine/ParticleSystemRenderMode.cs | 12 + .../UnityEngine/ParticleSystemRenderer.cs | 71 + .../ParticleSystemSimulationSpace.cs | 9 + UnityEngine/UnityEngine/PhysicMaterial.cs | 125 + .../UnityEngine/PhysicMaterialCombine.cs | 11 + UnityEngine/UnityEngine/Physics.cs | 459 ++ UnityEngine/UnityEngine/Physics2D.cs | 997 +++ UnityEngine/UnityEngine/PhysicsMaterial2D.cs | 37 + UnityEngine/UnityEngine/Ping.cs | 37 + UnityEngine/UnityEngine/Plane.cs | 82 + UnityEngine/UnityEngine/PlatformSelection.cs | 10 + UnityEngine/UnityEngine/PlayMode.cs | 9 + UnityEngine/UnityEngine/PlayerPrefs.cs | 78 + .../UnityEngine/PlayerPrefsException.cs | 10 + UnityEngine/UnityEngine/PolygonCollider2D.cs | 56 + UnityEngine/UnityEngine/PrimitiveType.cs | 13 + .../UnityEngine/ProceduralCacheSize.cs | 12 + .../UnityEngine/ProceduralLoadingBehavior.cs | 13 + UnityEngine/UnityEngine/ProceduralMaterial.cs | 163 + .../UnityEngine/ProceduralOutputType.cs | 14 + .../UnityEngine/ProceduralProcessorUsage.cs | 11 + .../ProceduralPropertyDescription.cs | 19 + .../UnityEngine/ProceduralPropertyType.cs | 16 + UnityEngine/UnityEngine/ProceduralTexture.cs | 32 + UnityEngine/UnityEngine/Profiler.cs | 83 + UnityEngine/UnityEngine/Projector.cs | 102 + UnityEngine/UnityEngine/PropertyAttribute.cs | 13 + UnityEngine/UnityEngine/QualityLevel.cs | 14 + UnityEngine/UnityEngine/QualitySettings.cs | 193 + UnityEngine/UnityEngine/Quaternion.cs | 345 ++ UnityEngine/UnityEngine/QueueMode.cs | 9 + UnityEngine/UnityEngine/RPC.cs | 8 + UnityEngine/UnityEngine/RPCMode.cs | 12 + UnityEngine/UnityEngine/Random.cs | 79 + UnityEngine/UnityEngine/RangeAttribute.cs | 15 + UnityEngine/UnityEngine/Ray.cs | 56 + UnityEngine/UnityEngine/Ray2D.cs | 56 + UnityEngine/UnityEngine/RaycastCollider.cs | 38 + UnityEngine/UnityEngine/RaycastHit.cs | 145 + UnityEngine/UnityEngine/RaycastHit2D.cs | 114 + UnityEngine/UnityEngine/Rect.cs | 320 + UnityEngine/UnityEngine/RectOffset.cs | 117 + UnityEngine/UnityEngine/RectTransform.cs | 288 + .../UnityEngine/RectTransformUtility.cs | 174 + UnityEngine/UnityEngine/ReferenceData.cs | 9 + UnityEngine/UnityEngine/RemoteNotification.cs | 50 + .../UnityEngine/RemoteNotificationType.cs | 11 + UnityEngine/UnityEngine/RenderBuffer.cs | 9 + UnityEngine/UnityEngine/RenderMode.cs | 10 + UnityEngine/UnityEngine/RenderSettings.cs | 127 + UnityEngine/UnityEngine/RenderTexture.cs | 313 + .../UnityEngine/RenderTextureFormat.cs | 24 + .../UnityEngine/RenderTextureReadWrite.cs | 10 + UnityEngine/UnityEngine/Renderer.cs | 213 + UnityEngine/UnityEngine/RenderingPath.cs | 11 + UnityEngine/UnityEngine/RequireComponent.cs | 26 + UnityEngine/UnityEngine/Resolution.cs | 43 + UnityEngine/UnityEngine/ResourceRequest.cs | 18 + UnityEngine/UnityEngine/Resources.cs | 82 + UnityEngine/UnityEngine/Rigidbody.cs | 508 ++ UnityEngine/UnityEngine/Rigidbody2D.cs | 347 ++ .../UnityEngine/RigidbodyConstraints.cs | 17 + .../UnityEngine/RigidbodyInterpolation.cs | 10 + .../UnityEngine/RigidbodyInterpolation2D.cs | 10 + .../UnityEngine/RigidbodySleepMode2D.cs | 10 + UnityEngine/UnityEngine/RotationDriveMode.cs | 9 + .../UnityEngine/RuntimeAnimatorController.cs | 7 + UnityEngine/UnityEngine/RuntimePlatform.cs | 33 + UnityEngine/UnityEngine/RuntimeUndo.cs | 17 + UnityEngine/UnityEngine/SamsungTV.cs | 23 + UnityEngine/UnityEngine/ScaleMode.cs | 10 + UnityEngine/UnityEngine/Screen.cs | 136 + UnityEngine/UnityEngine/ScreenOrientation.cs | 14 + UnityEngine/UnityEngine/ScriptableObject.cs | 39 + .../UnityEngine/ScrollWaitDefinitions.cs | 9 + UnityEngine/UnityEngine/Security.cs | 172 + .../UnityEngine/SelectionBaseAttribute.cs | 8 + UnityEngine/UnityEngine/SendMessageOptions.cs | 9 + UnityEngine/UnityEngine/SendMouseEvents.cs | 185 + UnityEngine/UnityEngine/SerializeField.cs | 7 + .../UnityEngine/SerializePrivateVariables.cs | 8 + UnityEngine/UnityEngine/SetupCoroutine.cs | 32 + UnityEngine/UnityEngine/Shader.cs | 123 + UnityEngine/UnityEngine/ShadowProjection.cs | 9 + UnityEngine/UnityEngine/SkeletonBone.cs | 12 + UnityEngine/UnityEngine/SkinQuality.cs | 11 + UnityEngine/UnityEngine/SkinnedCloth.cs | 45 + .../UnityEngine/SkinnedMeshRenderer.cs | 98 + UnityEngine/UnityEngine/Skybox.cs | 17 + UnityEngine/UnityEngine/SleepTimeout.cs | 9 + UnityEngine/UnityEngine/SliderHandler.cs | 262 + UnityEngine/UnityEngine/SliderJoint2D.cs | 104 + UnityEngine/UnityEngine/SliderState.cs | 10 + UnityEngine/UnityEngine/Social.cs | 66 + UnityEngine/UnityEngine/SoftJointLimit.cs | 67 + UnityEngine/UnityEngine/Space.cs | 9 + UnityEngine/UnityEngine/SpaceAttribute.cs | 13 + UnityEngine/UnityEngine/SparseTexture.cs | 46 + UnityEngine/UnityEngine/SphereCollider.cs | 36 + UnityEngine/UnityEngine/SplatPrototype.cs | 57 + UnityEngine/UnityEngine/SpringJoint.cs | 44 + UnityEngine/UnityEngine/SpringJoint2D.cs | 51 + UnityEngine/UnityEngine/Sprite.cs | 112 + UnityEngine/UnityEngine/SpriteAlignment.cs | 17 + UnityEngine/UnityEngine/SpriteMeshType.cs | 9 + UnityEngine/UnityEngine/SpritePackingMode.cs | 9 + .../UnityEngine/SpritePackingRotation.cs | 9 + UnityEngine/UnityEngine/SpriteRenderer.cs | 44 + UnityEngine/UnityEngine/StackTraceUtility.cs | 218 + .../UnityEngine/StaticBatchingUtility.cs | 22 + UnityEngine/UnityEngine/SystemClock.cs | 14 + UnityEngine/UnityEngine/SystemInfo.cs | 209 + UnityEngine/UnityEngine/SystemLanguage.cs | 49 + UnityEngine/UnityEngine/Terrain.cs | 608 ++ .../UnityEngine/TerrainChangedFlags.cs | 15 + UnityEngine/UnityEngine/TerrainCollider.cs | 17 + UnityEngine/UnityEngine/TerrainData.cs | 355 ++ UnityEngine/UnityEngine/TerrainRenderFlags.cs | 11 + UnityEngine/UnityEngine/TexGenMode.cs | 13 + UnityEngine/UnityEngine/TextAlignment.cs | 10 + UnityEngine/UnityEngine/TextAnchor.cs | 16 + UnityEngine/UnityEngine/TextAreaAttribute.cs | 20 + UnityEngine/UnityEngine/TextAsset.cs | 24 + UnityEngine/UnityEngine/TextClipping.cs | 9 + UnityEngine/UnityEngine/TextEditor.cs | 1407 +++++ .../UnityEngine/TextGenerationSettings.cs | 37 + UnityEngine/UnityEngine/TextGenerator.cs | 263 + UnityEngine/UnityEngine/TextMesh.cs | 126 + UnityEngine/UnityEngine/Texture.cs | 111 + UnityEngine/UnityEngine/Texture2D.cs | 235 + UnityEngine/UnityEngine/Texture3D.cs | 55 + .../UnityEngine/TextureCompressionQuality.cs | 10 + UnityEngine/UnityEngine/TextureFormat.cs | 50 + UnityEngine/UnityEngine/TextureWrapMode.cs | 9 + UnityEngine/UnityEngine/ThreadPriority.cs | 11 + .../UnityEngine/ThreadSafeAttribute.cs | 8 + UnityEngine/UnityEngine/Time.cs | 104 + UnityEngine/UnityEngine/TooltipAttribute.cs | 13 + UnityEngine/UnityEngine/Touch.cs | 63 + UnityEngine/UnityEngine/TouchPhase.cs | 12 + .../UnityEngine/TouchScreenKeyboard.cs | 158 + .../UnityEngine/TouchScreenKeyboardType.cs | 15 + ...oard_InternalConstructorHelperArguments.cs | 12 + UnityEngine/UnityEngine/TrackedReference.cs | 46 + UnityEngine/UnityEngine/TrailRenderer.cs | 44 + UnityEngine/UnityEngine/Transform.cs | 537 ++ .../UnityEngine/TransparencySortMode.cs | 10 + UnityEngine/UnityEngine/Tree.cs | 17 + UnityEngine/UnityEngine/TreeInstance.cs | 91 + UnityEngine/UnityEngine/TreePrototype.cs | 33 + UnityEngine/UnityEngine/Types.cs | 21 + UnityEngine/UnityEngine/UICharInfo.cs | 9 + UnityEngine/UnityEngine/UILineInfo.cs | 9 + UnityEngine/UnityEngine/UIVertex.cs | 24 + .../UnassignedReferenceException.cs | 26 + .../UnityEngine/UnhandledExceptionHandler.cs | 32 + UnityEngine/UnityEngine/UnityException.cs | 26 + UnityEngine/UnityEngine/UnityLogWriter.cs | 32 + UnityEngine/UnityEngine/UnityString.cs | 11 + UnityEngine/UnityEngine/UserAuthorization.cs | 9 + .../UnityEngine/UserAuthorizationDialog.cs | 142 + UnityEngine/UnityEngine/Vector2.cs | 277 + UnityEngine/UnityEngine/Vector3.cs | 397 ++ UnityEngine/UnityEngine/Vector4.cs | 274 + UnityEngine/UnityEngine/VerticalWrapMode.cs | 9 + UnityEngine/UnityEngine/WWW.cs | 502 ++ UnityEngine/UnityEngine/WWWForm.cs | 206 + UnityEngine/UnityEngine/WWWTranscoder.cs | 200 + UnityEngine/UnityEngine/WaitForEndOfFrame.cs | 7 + UnityEngine/UnityEngine/WaitForFixedUpdate.cs | 7 + UnityEngine/UnityEngine/WaitForSeconds.cs | 14 + .../UnityEngine/WeakListenerBindings.cs | 12 + UnityEngine/UnityEngine/WebCamDevice.cs | 23 + UnityEngine/UnityEngine/WebCamFlags.cs | 8 + UnityEngine/UnityEngine/WebCamTexture.cs | 151 + UnityEngine/UnityEngine/WheelCollider.cs | 153 + UnityEngine/UnityEngine/WheelFrictionCurve.cs | 67 + UnityEngine/UnityEngine/WheelHit.cs | 103 + UnityEngine/UnityEngine/WheelJoint2D.cs | 74 + UnityEngine/UnityEngine/WindZone.cs | 62 + UnityEngine/UnityEngine/WindZoneMode.cs | 9 + UnityEngine/UnityEngine/WrapMode.cs | 13 + UnityEngine/UnityEngine/WrapperlessIcall.cs | 7 + UnityEngine/UnityEngine/WritableAttribute.cs | 8 + UnityEngine/UnityEngine/YieldInstruction.cs | 9 + UnityEngine/UnityEngine/_AndroidJNIHelper.cs | 792 +++ .../UnityEngine/iOSActivityIndicatorStyle.cs | 11 + UnityEngine/UnityEngine/iPhone.cs | 113 + .../UnityEngine/iPhoneAccelerationEvent.cs | 32 + UnityEngine/UnityEngine/iPhoneGeneration.cs | 35 + UnityEngine/UnityEngine/iPhoneInput.cs | 87 + UnityEngine/UnityEngine/iPhoneKeyboard.cs | 134 + UnityEngine/UnityEngine/iPhoneKeyboardType.cs | 16 + ...oard_InternalConstructorHelperArguments.cs | 14 + .../UnityEngine/iPhoneMovieControlMode.cs | 13 + .../UnityEngine/iPhoneMovieScalingMode.cs | 12 + .../UnityEngine/iPhoneNetworkReachability.cs | 11 + UnityEngine/UnityEngine/iPhoneOrientation.cs | 15 + .../UnityEngine/iPhoneScreenOrientation.cs | 14 + UnityEngine/UnityEngine/iPhoneSettings.cs | 117 + UnityEngine/UnityEngine/iPhoneTouch.cs | 72 + UnityEngine/UnityEngine/iPhoneTouchPhase.cs | 13 + UnityEngine/UnityEngine/iPhoneUtils.cs | 71 + UnityEngine/UnityEngine/jvalue.cs | 27 + .../FastCallExceptionHandler.cs | 5 + .../UnityEngineInternal/GenericStack.cs | 8 + .../UnityEngineInternal/GetMethodDelegate.cs | 6 + .../UnityEngineInternal/Reproduction.cs | 12 + .../TypeInferenceRuleAttribute.cs | 21 + .../UnityEngineInternal/TypeInferenceRules.cs | 11 + 1636 files changed, 245763 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 UnityDecompiled.sln create mode 100644 UnityEditor/AssemblyValidation.cs create mode 100644 UnityEditor/AssemblyValidationRule.cs create mode 100644 UnityEditor/AssetModificationProcessor.cs create mode 100644 UnityEditor/ClangCompiler.cs create mode 100644 UnityEditor/ClangCompilerSettingsx86.cs create mode 100644 UnityEditor/DesktopStandalonePostProcessor.cs create mode 100644 UnityEditor/FlashDotNetAPIValidationRule.cs create mode 100644 UnityEditor/FlashFileHelper.cs create mode 100644 UnityEditor/FlashPostProcessSettings.cs create mode 100644 UnityEditor/FlashTemplateWriterUtility.cs create mode 100644 UnityEditor/GendarmeOptions.cs create mode 100644 UnityEditor/GendarmeValidationRule.cs create mode 100644 UnityEditor/GendarmeXMLTemplateTags.cs create mode 100644 UnityEditor/GenerateIconsWithMipLevels.cs create mode 100644 UnityEditor/ICompilerSettings.cs create mode 100644 UnityEditor/INativeCompiler.cs create mode 100644 UnityEditor/IValidationRule.cs create mode 100644 UnityEditor/LinuxDesktopStandalonePostProcessor.cs create mode 100644 UnityEditor/MSVCCompiler.cs create mode 100644 UnityEditor/MSVCCompilerSettingsx64.cs create mode 100644 UnityEditor/MSVCCompilerSettingsx86.cs create mode 100644 UnityEditor/MxmlcHelper.cs create mode 100644 UnityEditor/NUnitFrameworkUser.cs create mode 100644 UnityEditor/NativeCompiler.cs create mode 100644 UnityEditor/OSXDesktopStandalonePostProcessor.cs create mode 100644 UnityEditor/ParticleSystemCurveEditor.cs create mode 100644 UnityEditor/PatchImportSettingRecycleID.cs create mode 100644 UnityEditor/PostProcessDashboardWidget.cs create mode 100644 UnityEditor/PostProcessFlashPlayer.cs create mode 100644 UnityEditor/PostProcessFlashPlayerOptions.cs create mode 100644 UnityEditor/PostProcessStandalonePlayer.cs create mode 100644 UnityEditor/PostProcessWebPlayer.cs create mode 100644 UnityEditor/PreviewGUI.cs create mode 100644 UnityEditor/Properties/AssemblyInfo.cs create mode 100644 UnityEditor/SerializedFileContainerPreparer.cs create mode 100644 UnityEditor/SerializedStringTable.cs create mode 100644 UnityEditor/TreeEditor/FractalNoise.cs create mode 100644 UnityEditor/TreeEditor/Perlin.cs create mode 100644 UnityEditor/TreeEditor/RingLoop.cs create mode 100644 UnityEditor/TreeEditor/SmoothRandom.cs create mode 100644 UnityEditor/TreeEditor/SplineNode.cs create mode 100644 UnityEditor/TreeEditor/TextureAtlas.cs create mode 100644 UnityEditor/TreeEditor/TreeAOSphere.cs create mode 100644 UnityEditor/TreeEditor/TreeAttribute.cs create mode 100644 UnityEditor/TreeEditor/TreeData.cs create mode 100644 UnityEditor/TreeEditor/TreeEditor.cs create mode 100644 UnityEditor/TreeEditor/TreeEditorHelper.cs create mode 100644 UnityEditor/TreeEditor/TreeGroup.cs create mode 100644 UnityEditor/TreeEditor/TreeGroupBranch.cs create mode 100644 UnityEditor/TreeEditor/TreeGroupLeaf.cs create mode 100644 UnityEditor/TreeEditor/TreeGroupRoot.cs create mode 100644 UnityEditor/TreeEditor/TreeMaterial.cs create mode 100644 UnityEditor/TreeEditor/TreeNode.cs create mode 100644 UnityEditor/TreeEditor/TreeSpline.cs create mode 100644 UnityEditor/TreeEditor/TreeTriangle.cs create mode 100644 UnityEditor/TreeEditor/TreeVertex.cs create mode 100644 UnityEditor/UnityEditor.AnimatedValues/AnimBool.cs create mode 100644 UnityEditor/UnityEditor.AnimatedValues/AnimFloat.cs create mode 100644 UnityEditor/UnityEditor.AnimatedValues/AnimQuaternion.cs create mode 100644 UnityEditor/UnityEditor.AnimatedValues/AnimVector3.cs create mode 100644 UnityEditor/UnityEditor.AnimatedValues/BaseAnimValue.cs create mode 100644 UnityEditor/UnityEditor.Callbacks/DidReloadScripts.cs create mode 100644 UnityEditor/UnityEditor.Callbacks/OnOpenAssetAttribute.cs create mode 100644 UnityEditor/UnityEditor.Callbacks/PostProcessBuildAttribute.cs create mode 100644 UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs create mode 100644 UnityEditor/UnityEditor.Events/UnityEventTools.cs create mode 100644 UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor.Macros/MacroEvaluator.cs create mode 100644 UnityEditor/UnityEditor.Macros/MethodEvaluator.cs create mode 100644 UnityEditor/UnityEditor.Modules/BuildLaunchPlayerArgs.cs create mode 100644 UnityEditor/UnityEditor.Modules/BuildPostProcessArgs.cs create mode 100644 UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs create mode 100644 UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs create mode 100644 UnityEditor/UnityEditor.Modules/IPreferenceWindowExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/ModuleManager.cs create mode 100644 UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateFolder.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateNewAsset.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreatePrefab.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateScriptAsset.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/EndNameEditAction.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/CommandLineFormatter.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessageType.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/GendarmeRuleData.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/Il2CppOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs create mode 100644 UnityEditor/UnityEditor.Scripting/ManagedProgram.cs create mode 100644 UnityEditor/UnityEditor.Scripting/MonoIsland.cs create mode 100644 UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs create mode 100644 UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs create mode 100644 UnityEditor/UnityEditor.Scripting/SupportedLanguageStruct.cs create mode 100644 UnityEditor/UnityEditor.Sprites/AtlasSettings.cs create mode 100644 UnityEditor/UnityEditor.Sprites/DataUtility.cs create mode 100644 UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs create mode 100644 UnityEditor/UnityEditor.Sprites/IPackerPolicy.cs create mode 100644 UnityEditor/UnityEditor.Sprites/Packer.cs create mode 100644 UnityEditor/UnityEditor.Sprites/PackerJob.cs create mode 100644 UnityEditor/UnityEditor.Sprites/PackerWindow.cs create mode 100644 UnityEditor/UnityEditor.Sprites/TightPackerPolicy.cs create mode 100644 UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs create mode 100644 UnityEditor/UnityEditor.Utils/Paths.cs create mode 100644 UnityEditor/UnityEditor.Utils/PerformanceChecks.cs create mode 100644 UnityEditor/UnityEditor.Utils/ProcessOutputStreamReader.cs create mode 100644 UnityEditor/UnityEditor.Utils/Program.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/Asset.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/AssetList.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/ChangeSet.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/ChangeSets.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/CheckoutMode.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/CommandContext.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/CompletionAction.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/ConfigField.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/CustomCommand.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/FileMode.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/MergeMethod.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/Message.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/OnlineState.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/Plugin.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/Provider.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/ResolveMethod.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/RevertMode.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/SubmitResult.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/Task.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/WindowChange.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/WindowPending.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/WindowResolve.cs create mode 100644 UnityEditor/UnityEditor.VersionControl/WindowRevert.cs create mode 100644 UnityEditor/UnityEditor.VisualStudioIntegration/DefaultSolutionSynchronizationSettings.cs create mode 100644 UnityEditor/UnityEditor.VisualStudioIntegration/ISolutionSynchronizationSettings.cs create mode 100644 UnityEditor/UnityEditor.VisualStudioIntegration/ScriptingLanguage.cs create mode 100644 UnityEditor/UnityEditor.VisualStudioIntegration/SolutionGuidGenerator.cs create mode 100644 UnityEditor/UnityEditor.VisualStudioIntegration/SolutionSynchronizer.cs create mode 100644 UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor.csproj create mode 100644 UnityEditor/UnityEditor/AInfo.cs create mode 100644 UnityEditor/UnityEditor/ASCommitWindow.cs create mode 100644 UnityEditor/UnityEditor/ASConfigWindow.cs create mode 100644 UnityEditor/UnityEditor/ASEditorBackend.cs create mode 100644 UnityEditor/UnityEditor/ASHistoryFileView.cs create mode 100644 UnityEditor/UnityEditor/ASHistoryWindow.cs create mode 100644 UnityEditor/UnityEditor/ASMainWindow.cs create mode 100644 UnityEditor/UnityEditor/ASRefreshState.cs create mode 100644 UnityEditor/UnityEditor/ASServerAdminWindow.cs create mode 100644 UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs create mode 100644 UnityEditor/UnityEditor/ASUpdateWindow.cs create mode 100644 UnityEditor/UnityEditor/AboutWindow.cs create mode 100644 UnityEditor/UnityEditor/AboutWindowNames.cs create mode 100644 UnityEditor/UnityEditor/ActiveEditorTracker.cs create mode 100644 UnityEditor/UnityEditor/AddComponentWindow.cs create mode 100644 UnityEditor/UnityEditor/AlphabeticalSort.cs create mode 100644 UnityEditor/UnityEditor/Analytics.cs create mode 100644 UnityEditor/UnityEditor/AnchoredJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/AndroidBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/AndroidPreferredInstallLocation.cs create mode 100644 UnityEditor/UnityEditor/AndroidSdkRoot.cs create mode 100644 UnityEditor/UnityEditor/AndroidSdkVersions.cs create mode 100644 UnityEditor/UnityEditor/AndroidShowActivityIndicatorOnLoading.cs create mode 100644 UnityEditor/UnityEditor/AndroidSplashScreenScale.cs create mode 100644 UnityEditor/UnityEditor/AndroidTargetDevice.cs create mode 100644 UnityEditor/UnityEditor/AnimationClipCurveData.cs create mode 100644 UnityEditor/UnityEditor/AnimationClipEditor.cs create mode 100644 UnityEditor/UnityEditor/AnimationClipInfoProperties.cs create mode 100644 UnityEditor/UnityEditor/AnimationClipSettings.cs create mode 100644 UnityEditor/UnityEditor/AnimationClipStats.cs create mode 100644 UnityEditor/UnityEditor/AnimationCurveContextMenu.cs create mode 100644 UnityEditor/UnityEditor/AnimationEditor.cs create mode 100644 UnityEditor/UnityEditor/AnimationEventPopup.cs create mode 100644 UnityEditor/UnityEditor/AnimationEventTimeLine.cs create mode 100644 UnityEditor/UnityEditor/AnimationHierarchyData.cs create mode 100644 UnityEditor/UnityEditor/AnimationMode.cs create mode 100644 UnityEditor/UnityEditor/AnimationSelection.cs create mode 100644 UnityEditor/UnityEditor/AnimationUtility.cs create mode 100644 UnityEditor/UnityEditor/AnimationWindow.cs create mode 100644 UnityEditor/UnityEditor/AnimatorInspector.cs create mode 100644 UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs create mode 100644 UnityEditor/UnityEditor/Annotation.cs create mode 100644 UnityEditor/UnityEditor/AnnotationUtility.cs create mode 100644 UnityEditor/UnityEditor/AnnotationWindow.cs create mode 100644 UnityEditor/UnityEditor/ApiCompatibilityLevel.cs create mode 100644 UnityEditor/UnityEditor/AppStatusBar.cs create mode 100644 UnityEditor/UnityEditor/ArrayUtility.cs create mode 100644 UnityEditor/UnityEditor/AspectRatio.cs create mode 100644 UnityEditor/UnityEditor/AssembleEditorSkin.cs create mode 100644 UnityEditor/UnityEditor/AssembliesShippedWithWebPlayerProvider.cs create mode 100644 UnityEditor/UnityEditor/AssemblyHelper.cs create mode 100644 UnityEditor/UnityEditor/AssemblyReferenceChecker.cs create mode 100644 UnityEditor/UnityEditor/AssemblyReloadEvents.cs create mode 100644 UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs create mode 100644 UnityEditor/UnityEditor/AssetDatabase.cs create mode 100644 UnityEditor/UnityEditor/AssetDeleteResult.cs create mode 100644 UnityEditor/UnityEditor/AssetImporter.cs create mode 100644 UnityEditor/UnityEditor/AssetImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs create mode 100644 UnityEditor/UnityEditor/AssetInspector.cs create mode 100644 UnityEditor/UnityEditor/AssetModificationProcessor.cs create mode 100644 UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs create mode 100644 UnityEditor/UnityEditor/AssetMoveResult.cs create mode 100644 UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/AssetPostprocessingInternal.cs create mode 100644 UnityEditor/UnityEditor/AssetPostprocessor.cs create mode 100644 UnityEditor/UnityEditor/AssetPreview.cs create mode 100644 UnityEditor/UnityEditor/AssetPreviewUpdater.cs create mode 100644 UnityEditor/UnityEditor/AssetSaveDialog.cs create mode 100644 UnityEditor/UnityEditor/AssetServer.cs create mode 100644 UnityEditor/UnityEditor/AssetServerConfig.cs create mode 100644 UnityEditor/UnityEditor/AssetStatus.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreAsset.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreAssetInspector.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreAssetSelection.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreAssetsInfo.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreClient.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreContext.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreLoginWindow.cs create mode 100644 UnityEditor/UnityEditor/AssetStorePreviewManager.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreResponse.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreResultBase.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreSearchResults.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreUtils.cs create mode 100644 UnityEditor/UnityEditor/AssetStoreWindow.cs create mode 100644 UnityEditor/UnityEditor/AssetsItem.cs create mode 100644 UnityEditor/UnityEditor/AssetsTreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/AssetsTreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/AsyncHTTPClient.cs create mode 100644 UnityEditor/UnityEditor/AsyncProgressBar.cs create mode 100644 UnityEditor/UnityEditor/AttachProfilerUI.cs create mode 100644 UnityEditor/UnityEditor/AttributeHelper.cs create mode 100644 UnityEditor/UnityEditor/AudioChorusFilterEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioClipInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioDistortionFilterEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioEchoFilterEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioFilterGUI.cs create mode 100644 UnityEditor/UnityEditor/AudioHighPassFilterEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioImporter.cs create mode 100644 UnityEditor/UnityEditor/AudioImporterChannels.cs create mode 100644 UnityEditor/UnityEditor/AudioImporterFormat.cs create mode 100644 UnityEditor/UnityEditor/AudioImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioImporterLoadType.cs create mode 100644 UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioReverbFilterEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioReverbZoneEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioSourceInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioUtil.cs create mode 100644 UnityEditor/UnityEditor/AvatarAutoMapper.cs create mode 100644 UnityEditor/UnityEditor/AvatarColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarControl.cs create mode 100644 UnityEditor/UnityEditor/AvatarEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarHandleEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarMappingEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarMaskInspector.cs create mode 100644 UnityEditor/UnityEditor/AvatarMaskUtility.cs create mode 100644 UnityEditor/UnityEditor/AvatarMuscleEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarPreview.cs create mode 100644 UnityEditor/UnityEditor/AvatarPreviewSelection.cs create mode 100644 UnityEditor/UnityEditor/AvatarSetupTool.cs create mode 100644 UnityEditor/UnityEditor/AvatarSkeletonDrawer.cs create mode 100644 UnityEditor/UnityEditor/AvatarSubEditor.cs create mode 100644 UnityEditor/UnityEditor/AvatarUtility.cs create mode 100644 UnityEditor/UnityEditor/BaseHierarchySort.cs create mode 100644 UnityEditor/UnityEditor/BaseProjectWindow.cs create mode 100644 UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/BlackBerryBuildType.cs create mode 100644 UnityEditor/UnityEditor/BlendTreeInspector.cs create mode 100644 UnityEditor/UnityEditor/BodyMaskEditor.cs create mode 100644 UnityEditor/UnityEditor/BodyPart.cs create mode 100644 UnityEditor/UnityEditor/BoneState.cs create mode 100644 UnityEditor/UnityEditor/BoxCollider2DEditor.cs create mode 100644 UnityEditor/UnityEditor/BoxColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/BoxEditor.cs create mode 100644 UnityEditor/UnityEditor/Brush.cs create mode 100644 UnityEditor/UnityEditor/BuildAssetBundleOptions.cs create mode 100644 UnityEditor/UnityEditor/BuildOptions.cs create mode 100644 UnityEditor/UnityEditor/BuildPackageResult.cs create mode 100644 UnityEditor/UnityEditor/BuildPipeline.cs create mode 100644 UnityEditor/UnityEditor/BuildPlayerWindow.cs create mode 100644 UnityEditor/UnityEditor/BuildTarget.cs create mode 100644 UnityEditor/UnityEditor/BuildTargetGroup.cs create mode 100644 UnityEditor/UnityEditor/BuildUploadCompletedWindow.cs create mode 100644 UnityEditor/UnityEditor/BuildVerifier.cs create mode 100644 UnityEditor/UnityEditor/BuiltinResource.cs create mode 100644 UnityEditor/UnityEditor/BumpMapSettingsFixingWindow.cs create mode 100644 UnityEditor/UnityEditor/CacheServerPreferences.cs create mode 100644 UnityEditor/UnityEditor/CallbackOrderAttribute.cs create mode 100644 UnityEditor/UnityEditor/CameraEditor.cs create mode 100644 UnityEditor/UnityEditor/CanEditMultipleObjects.cs create mode 100644 UnityEditor/UnityEditor/CanvasEditor.cs create mode 100644 UnityEditor/UnityEditor/CapsuleColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/ChangeFlags.cs create mode 100644 UnityEditor/UnityEditor/Changeset.cs create mode 100644 UnityEditor/UnityEditor/ChangesetItem.cs create mode 100644 UnityEditor/UnityEditor/CharacterControllerEditor.cs create mode 100644 UnityEditor/UnityEditor/CircleCollider2DEditor.cs create mode 100644 UnityEditor/UnityEditor/ClampVelocityModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ClipAnimationMaskType.cs create mode 100644 UnityEditor/UnityEditor/ClothInspector.cs create mode 100644 UnityEditor/UnityEditor/CodeStrippingUtils.cs create mode 100644 UnityEditor/UnityEditor/Collider2DEditorBase.cs create mode 100644 UnityEditor/UnityEditor/Collider3DEditorBase.cs create mode 100644 UnityEditor/UnityEditor/ColliderEditorBase.cs create mode 100644 UnityEditor/UnityEditor/ColliderUtil.cs create mode 100644 UnityEditor/UnityEditor/CollisionModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ColorByVelocityModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ColorModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ColorPicker.cs create mode 100644 UnityEditor/UnityEditor/ColorPresetLibrary.cs create mode 100644 UnityEditor/UnityEditor/ColorPresetLibraryEditor.cs create mode 100644 UnityEditor/UnityEditor/ColumnView.cs create mode 100644 UnityEditor/UnityEditor/ColumnViewElement.cs create mode 100644 UnityEditor/UnityEditor/CompareInfo.cs create mode 100644 UnityEditor/UnityEditor/ConsoleWindow.cs create mode 100644 UnityEditor/UnityEditor/ContainerWindow.cs create mode 100644 UnityEditor/UnityEditor/CreateAssetUtility.cs create mode 100644 UnityEditor/UnityEditor/CreateBuiltinWindows.cs create mode 100644 UnityEditor/UnityEditor/CrossCompileOptions.cs create mode 100644 UnityEditor/UnityEditor/CubemapTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/CurveEditor.cs create mode 100644 UnityEditor/UnityEditor/CurveEditorSettings.cs create mode 100644 UnityEditor/UnityEditor/CurveEditorWindow.cs create mode 100644 UnityEditor/UnityEditor/CurveLibraryType.cs create mode 100644 UnityEditor/UnityEditor/CurveMenuManager.cs create mode 100644 UnityEditor/UnityEditor/CurvePresetLibrary.cs create mode 100644 UnityEditor/UnityEditor/CurvePresetLibraryEditor.cs create mode 100644 UnityEditor/UnityEditor/CurvePresetsContentsForPopupWindow.cs create mode 100644 UnityEditor/UnityEditor/CurveRenderer.cs create mode 100644 UnityEditor/UnityEditor/CurveRendererCache.cs create mode 100644 UnityEditor/UnityEditor/CurveSelection.cs create mode 100644 UnityEditor/UnityEditor/CurveState.cs create mode 100644 UnityEditor/UnityEditor/CurveUpdater.cs create mode 100644 UnityEditor/UnityEditor/CurveUtility.cs create mode 100644 UnityEditor/UnityEditor/CurveWrapper.cs create mode 100644 UnityEditor/UnityEditor/CustomEditor.cs create mode 100644 UnityEditor/UnityEditor/CustomEditorAttributes.cs create mode 100644 UnityEditor/UnityEditor/CustomPreviewAttribute.cs create mode 100644 UnityEditor/UnityEditor/CustomPropertyDrawer.cs create mode 100644 UnityEditor/UnityEditor/D3D9FullscreenMode.cs create mode 100644 UnityEditor/UnityEditor/DebugUtils.cs create mode 100644 UnityEditor/UnityEditor/DecoratorDrawer.cs create mode 100644 UnityEditor/UnityEditor/DeleteWindowLayout.cs create mode 100644 UnityEditor/UnityEditor/DeletedAsset.cs create mode 100644 UnityEditor/UnityEditor/DetailMeshRenderMode.cs create mode 100644 UnityEditor/UnityEditor/DetailMeshWizard.cs create mode 100644 UnityEditor/UnityEditor/DetailPainter.cs create mode 100644 UnityEditor/UnityEditor/DetailTextureWizard.cs create mode 100644 UnityEditor/UnityEditor/DistanceJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/DockArea.cs create mode 100644 UnityEditor/UnityEditor/DoubleCurve.cs create mode 100644 UnityEditor/UnityEditor/DoubleCurvePresetLibrary.cs create mode 100644 UnityEditor/UnityEditor/DoubleCurvePresetLibraryEditor.cs create mode 100644 UnityEditor/UnityEditor/DoubleCurvePresetsContentsForPopupWindow.cs create mode 100644 UnityEditor/UnityEditor/DownloadResolution.cs create mode 100644 UnityEditor/UnityEditor/DragAndDrop.cs create mode 100644 UnityEditor/UnityEditor/DragAndDropDelay.cs create mode 100644 UnityEditor/UnityEditor/DragAndDropVisualMode.cs create mode 100644 UnityEditor/UnityEditor/DragRectGUI.cs create mode 100644 UnityEditor/UnityEditor/DrawCameraMode.cs create mode 100644 UnityEditor/UnityEditor/DrawGizmo.cs create mode 100644 UnityEditor/UnityEditor/DrawGridParameters.cs create mode 100644 UnityEditor/UnityEditor/DrivenRectTransformUndo.cs create mode 100644 UnityEditor/UnityEditor/DropInfo.cs create mode 100644 UnityEditor/UnityEditor/EdgeCollider2DEditor.cs create mode 100644 UnityEditor/UnityEditor/Editor.cs create mode 100644 UnityEditor/UnityEditor/EditorApplication.cs create mode 100644 UnityEditor/UnityEditor/EditorApplicationLayout.cs create mode 100644 UnityEditor/UnityEditor/EditorAssemblies.cs create mode 100644 UnityEditor/UnityEditor/EditorBehaviorMode.cs create mode 100644 UnityEditor/UnityEditor/EditorBuildSettings.cs create mode 100644 UnityEditor/UnityEditor/EditorBuildSettingsScene.cs create mode 100644 UnityEditor/UnityEditor/EditorCache.cs create mode 100644 UnityEditor/UnityEditor/EditorCurveBinding.cs create mode 100644 UnityEditor/UnityEditor/EditorExtensionMethods.cs create mode 100644 UnityEditor/UnityEditor/EditorFeatures.cs create mode 100644 UnityEditor/UnityEditor/EditorGUI.cs create mode 100644 UnityEditor/UnityEditor/EditorGUIExt.cs create mode 100644 UnityEditor/UnityEditor/EditorGUIInternal.cs create mode 100644 UnityEditor/UnityEditor/EditorGUILayout.cs create mode 100644 UnityEditor/UnityEditor/EditorGUILayoutUtilityInternal.cs create mode 100644 UnityEditor/UnityEditor/EditorGUIUtility.cs create mode 100644 UnityEditor/UnityEditor/EditorLook.cs create mode 100644 UnityEditor/UnityEditor/EditorMaterialUtility.cs create mode 100644 UnityEditor/UnityEditor/EditorPrefs.cs create mode 100644 UnityEditor/UnityEditor/EditorSettings.cs create mode 100644 UnityEditor/UnityEditor/EditorSettingsInspector.cs create mode 100644 UnityEditor/UnityEditor/EditorSkin.cs create mode 100644 UnityEditor/UnityEditor/EditorStyles.cs create mode 100644 UnityEditor/UnityEditor/EditorUpdateWindow.cs create mode 100644 UnityEditor/UnityEditor/EditorUserBuildSettings.cs create mode 100644 UnityEditor/UnityEditor/EditorUserSettings.cs create mode 100644 UnityEditor/UnityEditor/EditorUtility.cs create mode 100644 UnityEditor/UnityEditor/EditorWindow.cs create mode 100644 UnityEditor/UnityEditor/EditorWrapper.cs create mode 100644 UnityEditor/UnityEditor/EmissionModuleUI.cs create mode 100644 UnityEditor/UnityEditor/Empty.cs create mode 100644 UnityEditor/UnityEditor/EulerCurveCombinedRenderer.cs create mode 100644 UnityEditor/UnityEditor/EulerCurveRenderer.cs create mode 100644 UnityEditor/UnityEditor/EventManipulationHandler.cs create mode 100644 UnityEditor/UnityEditor/ExportPackageOptions.cs create mode 100644 UnityEditor/UnityEditor/ExportRawHeightmap.cs create mode 100644 UnityEditor/UnityEditor/ExposablePopupMenu.cs create mode 100644 UnityEditor/UnityEditor/ExposeTransformEditor.cs create mode 100644 UnityEditor/UnityEditor/ExternalForcesModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ExternalVersionControl.cs create mode 100644 UnityEditor/UnityEditor/EyeDropper.cs create mode 100644 UnityEditor/UnityEditor/FallbackEditorWindow.cs create mode 100644 UnityEditor/UnityEditor/FilePathAttribute.cs create mode 100644 UnityEditor/UnityEditor/FileUtil.cs create mode 100644 UnityEditor/UnityEditor/FilteredHierarchy.cs create mode 100644 UnityEditor/UnityEditor/FilteredHierarchyProperty.cs create mode 100644 UnityEditor/UnityEditor/FlashBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/FlattenHeightmap.cs create mode 100644 UnityEditor/UnityEditor/FlexibleMenu.cs create mode 100644 UnityEditor/UnityEditor/FlexibleMenuModifyItemUI.cs create mode 100644 UnityEditor/UnityEditor/FlowLayout.cs create mode 100644 UnityEditor/UnityEditor/FoldoutComponentState.cs create mode 100644 UnityEditor/UnityEditor/FoldoutObjectState.cs create mode 100644 UnityEditor/UnityEditor/FoldoutTree.cs create mode 100644 UnityEditor/UnityEditor/FontInspector.cs create mode 100644 UnityEditor/UnityEditor/FontRenderingMode.cs create mode 100644 UnityEditor/UnityEditor/FontTextureCase.cs create mode 100644 UnityEditor/UnityEditor/ForceModuleUI.cs create mode 100644 UnityEditor/UnityEditor/GUIDrawer.cs create mode 100644 UnityEditor/UnityEditor/GUILayoutFadeGroup.cs create mode 100644 UnityEditor/UnityEditor/GUISlideGroup.cs create mode 100644 UnityEditor/UnityEditor/GUIStyleX.cs create mode 100644 UnityEditor/UnityEditor/GUIView.cs create mode 100644 UnityEditor/UnityEditor/GameObjectInspector.cs create mode 100644 UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/GameObjectTreeViewItem.cs create mode 100644 UnityEditor/UnityEditor/GameObjectUtility.cs create mode 100644 UnityEditor/UnityEditor/GameView.cs create mode 100644 UnityEditor/UnityEditor/GameViewGUI.cs create mode 100644 UnityEditor/UnityEditor/GameViewSize.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizeGroup.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizeGroupType.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizeType.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizes.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizesMenuItemProvider.cs create mode 100644 UnityEditor/UnityEditor/GameViewSizesMenuModifyItemUI.cs create mode 100644 UnityEditor/UnityEditor/GccCompiler.cs create mode 100644 UnityEditor/UnityEditor/GccCompilerSettingsx86.cs create mode 100644 UnityEditor/UnityEditor/GccCompilerSettingsx86_64.cs create mode 100644 UnityEditor/UnityEditor/GenericInspector.cs create mode 100644 UnityEditor/UnityEditor/GenericMenu.cs create mode 100644 UnityEditor/UnityEditor/GenericPresetLibraryInspector.cs create mode 100644 UnityEditor/UnityEditor/GizmoType.cs create mode 100644 UnityEditor/UnityEditor/GradientContextMenu.cs create mode 100644 UnityEditor/UnityEditor/GradientEditor.cs create mode 100644 UnityEditor/UnityEditor/GradientPicker.cs create mode 100644 UnityEditor/UnityEditor/GradientPresetLibrary.cs create mode 100644 UnityEditor/UnityEditor/GradientPresetLibraryEditor.cs create mode 100644 UnityEditor/UnityEditor/HandleUtility.cs create mode 100644 UnityEditor/UnityEditor/Handles.cs create mode 100644 UnityEditor/UnityEditor/HeaderDrawer.cs create mode 100644 UnityEditor/UnityEditor/HeapshotReader.cs create mode 100644 UnityEditor/UnityEditor/HeapshotWindow.cs create mode 100644 UnityEditor/UnityEditor/HeightmapFilters.cs create mode 100644 UnityEditor/UnityEditor/HeightmapPainter.cs create mode 100644 UnityEditor/UnityEditor/Help.cs create mode 100644 UnityEditor/UnityEditor/HierarchyProperty.cs create mode 100644 UnityEditor/UnityEditor/HierarchyType.cs create mode 100644 UnityEditor/UnityEditor/HierarchyWindow.cs create mode 100644 UnityEditor/UnityEditor/HighLevelEvent.cs create mode 100644 UnityEditor/UnityEditor/HighlightSearchMode.cs create mode 100644 UnityEditor/UnityEditor/Highlighter.cs create mode 100644 UnityEditor/UnityEditor/HingeJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/HorizontalLayout.cs create mode 100644 UnityEditor/UnityEditor/HostView.cs create mode 100644 UnityEditor/UnityEditor/HumanTemplate.cs create mode 100644 UnityEditor/UnityEditor/ICleanuppable.cs create mode 100644 UnityEditor/UnityEditor/IDropArea.cs create mode 100644 UnityEditor/UnityEditor/IEditablePoint.cs create mode 100644 UnityEditor/UnityEditor/IFlexibleMenuItemProvider.cs create mode 100644 UnityEditor/UnityEditor/IHasCustomMenu.cs create mode 100644 UnityEditor/UnityEditor/IHierarchyProperty.cs create mode 100644 UnityEditor/UnityEditor/IPrefType.cs create mode 100644 UnityEditor/UnityEditor/IPreviewable.cs create mode 100644 UnityEditor/UnityEditor/ITreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/ITreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/ITreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/IconDrawStyle.cs create mode 100644 UnityEditor/UnityEditor/IconSelector.cs create mode 100644 UnityEditor/UnityEditor/ImportAssetOptions.cs create mode 100644 UnityEditor/UnityEditor/ImportRawHeightmap.cs create mode 100644 UnityEditor/UnityEditor/InitialModuleUI.cs create mode 100644 UnityEditor/UnityEditor/InitializeOnLoadAttribute.cs create mode 100644 UnityEditor/UnityEditor/InspectorMode.cs create mode 100644 UnityEditor/UnityEditor/InspectorState.cs create mode 100644 UnityEditor/UnityEditor/InspectorWindow.cs create mode 100644 UnityEditor/UnityEditor/InternalMeshUtil.cs create mode 100644 UnityEditor/UnityEditor/Joint2DEditorBase.cs create mode 100644 UnityEditor/UnityEditor/KeyIdentifier.cs create mode 100644 UnityEditor/UnityEditor/LODGroupEditor.cs create mode 100644 UnityEditor/UnityEditor/LODUtility.cs create mode 100644 UnityEditor/UnityEditor/LODVisualizationInformation.cs create mode 100644 UnityEditor/UnityEditor/LabelGUI.cs create mode 100644 UnityEditor/UnityEditor/LayerMatrixGUI.cs create mode 100644 UnityEditor/UnityEditor/LayerVisibilityWindow.cs create mode 100644 UnityEditor/UnityEditor/LayoutDropdownWindow.cs create mode 100644 UnityEditor/UnityEditor/LazyTreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/LicenseManagementWindow.cs create mode 100644 UnityEditor/UnityEditor/LightEditor.cs create mode 100644 UnityEditor/UnityEditor/LightProbeGUI.cs create mode 100644 UnityEditor/UnityEditor/LightProbeGroupEditor.cs create mode 100644 UnityEditor/UnityEditor/LightProbeGroupInspector.cs create mode 100644 UnityEditor/UnityEditor/LightProbeGroupSelection.cs create mode 100644 UnityEditor/UnityEditor/LightProbesInspector.cs create mode 100644 UnityEditor/UnityEditor/LightmapBakeQuality.cs create mode 100644 UnityEditor/UnityEditor/LightmapEditorSettings.cs create mode 100644 UnityEditor/UnityEditor/LightmapVisualization.cs create mode 100644 UnityEditor/UnityEditor/Lightmapping.cs create mode 100644 UnityEditor/UnityEditor/LightmappingWindow.cs create mode 100644 UnityEditor/UnityEditor/ListViewElement.cs create mode 100644 UnityEditor/UnityEditor/ListViewGUI.cs create mode 100644 UnityEditor/UnityEditor/ListViewGUILayout.cs create mode 100644 UnityEditor/UnityEditor/ListViewOptions.cs create mode 100644 UnityEditor/UnityEditor/ListViewShared.cs create mode 100644 UnityEditor/UnityEditor/ListViewState.cs create mode 100644 UnityEditor/UnityEditor/MacFullscreenMode.cs create mode 100644 UnityEditor/UnityEditor/MainWindow.cs create mode 100644 UnityEditor/UnityEditor/MaintDatabaseRecord.cs create mode 100644 UnityEditor/UnityEditor/MaintUserRecord.cs create mode 100644 UnityEditor/UnityEditor/ManagedEditorCodeRebuilder.cs create mode 100644 UnityEditor/UnityEditor/ManipulationTool.cs create mode 100644 UnityEditor/UnityEditor/ManipulationToolUtility.cs create mode 100644 UnityEditor/UnityEditor/MaskFieldGUI.cs create mode 100644 UnityEditor/UnityEditor/MaterialEditor.cs create mode 100644 UnityEditor/UnityEditor/MaterialEnumDrawer.cs create mode 100644 UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs create mode 100644 UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs create mode 100644 UnityEditor/UnityEditor/MaterialProperty.cs create mode 100644 UnityEditor/UnityEditor/MaterialPropertyDrawer.cs create mode 100644 UnityEditor/UnityEditor/MaterialToggleDrawer.cs create mode 100644 UnityEditor/UnityEditor/MathUtils.cs create mode 100644 UnityEditor/UnityEditor/MaximizedHostView.cs create mode 100644 UnityEditor/UnityEditor/MecanimUtilities.cs create mode 100644 UnityEditor/UnityEditor/MemoryElement.cs create mode 100644 UnityEditor/UnityEditor/MemoryElementDataManager.cs create mode 100644 UnityEditor/UnityEditor/MemoryElementSelection.cs create mode 100644 UnityEditor/UnityEditor/MemoryTreeList.cs create mode 100644 UnityEditor/UnityEditor/MemoryTreeListClickable.cs create mode 100644 UnityEditor/UnityEditor/MenuCommand.cs create mode 100644 UnityEditor/UnityEditor/MenuItem.cs create mode 100644 UnityEditor/UnityEditor/MenuUtils.cs create mode 100644 UnityEditor/UnityEditor/MeshColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/MeshRendererEditor.cs create mode 100644 UnityEditor/UnityEditor/MeshUtility.cs create mode 100644 UnityEditor/UnityEditor/MessageType.cs create mode 100644 UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs create mode 100644 UnityEditor/UnityEditor/MetroBuildType.cs create mode 100644 UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs create mode 100644 UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs create mode 100644 UnityEditor/UnityEditor/MetroSDK.cs create mode 100644 UnityEditor/UnityEditor/MinMaxCurveState.cs create mode 100644 UnityEditor/UnityEditor/MinMaxGradientState.cs create mode 100644 UnityEditor/UnityEditor/ModelImporter.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterAnimationCompression.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterAnimationType.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterClipAnimation.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterClipEditor.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterEditor.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterGenerateAnimations.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterGenerateMaterials.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterMaterialName.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterMaterialSearch.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterMeshCompression.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterModelEditor.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterRigEditor.cs create mode 100644 UnityEditor/UnityEditor/ModelImporterTangentSpaceMode.cs create mode 100644 UnityEditor/UnityEditor/ModelInspector.cs create mode 100644 UnityEditor/UnityEditor/ModuleUI.cs create mode 100644 UnityEditor/UnityEditor/MonoAOTRegistration.cs create mode 100644 UnityEditor/UnityEditor/MonoAssemblyStripping.cs create mode 100644 UnityEditor/UnityEditor/MonoCrossCompile.cs create mode 100644 UnityEditor/UnityEditor/MonoImporter.cs create mode 100644 UnityEditor/UnityEditor/MonoManager.cs create mode 100644 UnityEditor/UnityEditor/MonoProcessUtility.cs create mode 100644 UnityEditor/UnityEditor/MonoReloadableIntPtr.cs create mode 100644 UnityEditor/UnityEditor/MonoReloadableIntPtrClear.cs create mode 100644 UnityEditor/UnityEditor/MonoScript.cs create mode 100644 UnityEditor/UnityEditor/MonoScriptImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/MonoScriptInspector.cs create mode 100644 UnityEditor/UnityEditor/MouseCursor.cs create mode 100644 UnityEditor/UnityEditor/MoveTool.cs create mode 100644 UnityEditor/UnityEditor/MovieImporter.cs create mode 100644 UnityEditor/UnityEditor/MovieImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/MovieTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/MultilineDrawer.cs create mode 100644 UnityEditor/UnityEditor/MuscleClipEditorUtilities.cs create mode 100644 UnityEditor/UnityEditor/MuscleClipQualityInfo.cs create mode 100644 UnityEditor/UnityEditor/NETVersion.cs create mode 100644 UnityEditor/UnityEditor/NameConflictResolution.cs create mode 100644 UnityEditor/UnityEditor/NavMeshAgentInspector.cs create mode 100644 UnityEditor/UnityEditor/NavMeshBuilder.cs create mode 100644 UnityEditor/UnityEditor/NavMeshEditorWindow.cs create mode 100644 UnityEditor/UnityEditor/NavMeshObstacleInspector.cs create mode 100644 UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs create mode 100644 UnityEditor/UnityEditor/NormalCurveRenderer.cs create mode 100644 UnityEditor/UnityEditor/OSColorPicker.cs create mode 100644 UnityEditor/UnityEditor/OSUtil.cs create mode 100644 UnityEditor/UnityEditor/ObjectCopier.cs create mode 100644 UnityEditor/UnityEditor/ObjectInfo.cs create mode 100644 UnityEditor/UnityEditor/ObjectListArea.cs create mode 100644 UnityEditor/UnityEditor/ObjectListAreaState.cs create mode 100644 UnityEditor/UnityEditor/ObjectNames.cs create mode 100644 UnityEditor/UnityEditor/ObjectPreview.cs create mode 100644 UnityEditor/UnityEditor/ObjectReferenceKeyframe.cs create mode 100644 UnityEditor/UnityEditor/ObjectSelector.cs create mode 100644 UnityEditor/UnityEditor/OcclusionAreaEditor.cs create mode 100644 UnityEditor/UnityEditor/OcclusionCullingWindow.cs create mode 100644 UnityEditor/UnityEditor/OcclusionPortalInspector.cs create mode 100644 UnityEditor/UnityEditor/OffMeshLinkInspector.cs create mode 100644 UnityEditor/UnityEditor/OptimizedGUIBlock.cs create mode 100644 UnityEditor/UnityEditor/OverwriteHandling.cs create mode 100644 UnityEditor/UnityEditor/PListConfig.cs create mode 100644 UnityEditor/UnityEditor/PSP2BuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/PackageExport.cs create mode 100644 UnityEditor/UnityEditor/PackageImport.cs create mode 100644 UnityEditor/UnityEditor/PackageImportTreeView.cs create mode 100644 UnityEditor/UnityEditor/PackageInfo.cs create mode 100644 UnityEditor/UnityEditor/PaneDragTab.cs create mode 100644 UnityEditor/UnityEditor/ParentViewFile.cs create mode 100644 UnityEditor/UnityEditor/ParentViewFolder.cs create mode 100644 UnityEditor/UnityEditor/ParentViewState.cs create mode 100644 UnityEditor/UnityEditor/ParticleEffectUI.cs create mode 100644 UnityEditor/UnityEditor/ParticleEffectUIOwner.cs create mode 100644 UnityEditor/UnityEditor/ParticleEffectUtils.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemClipboard.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemEditorUtils.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemInspector.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemStyles.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemUI.cs create mode 100644 UnityEditor/UnityEditor/ParticleSystemWindow.cs create mode 100644 UnityEditor/UnityEditor/Physics2DSettings.cs create mode 100644 UnityEditor/UnityEditor/Physics2DSettingsInspector.cs create mode 100644 UnityEditor/UnityEditor/PhysicsManager.cs create mode 100644 UnityEditor/UnityEditor/PhysicsManagerInspector.cs create mode 100644 UnityEditor/UnityEditor/PingData.cs create mode 100644 UnityEditor/UnityEditor/PivotMode.cs create mode 100644 UnityEditor/UnityEditor/PivotRotation.cs create mode 100644 UnityEditor/UnityEditor/PlaceTreeWizard.cs create mode 100644 UnityEditor/UnityEditor/PlayerSettings.cs create mode 100644 UnityEditor/UnityEditor/PlayerSettingsEditor.cs create mode 100644 UnityEditor/UnityEditor/PointEditor.cs create mode 100644 UnityEditor/UnityEditor/PolygonColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/PolygonEditor.cs create mode 100644 UnityEditor/UnityEditor/PolygonEditorUtility.cs create mode 100644 UnityEditor/UnityEditor/PopupList.cs create mode 100644 UnityEditor/UnityEditor/PopupLocationHelper.cs create mode 100644 UnityEditor/UnityEditor/PopupWindow.cs create mode 100644 UnityEditor/UnityEditor/PopupWindowContent.cs create mode 100644 UnityEditor/UnityEditor/PopupWindowContentForNewLibrary.cs create mode 100644 UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs create mode 100644 UnityEditor/UnityEditor/PostProcessAttribute.cs create mode 100644 UnityEditor/UnityEditor/PostprocessBuildPlayer.cs create mode 100644 UnityEditor/UnityEditor/PostprocessScene.cs create mode 100644 UnityEditor/UnityEditor/PragmaFixingWindow.cs create mode 100644 UnityEditor/UnityEditor/PrefColor.cs create mode 100644 UnityEditor/UnityEditor/PrefKey.cs create mode 100644 UnityEditor/UnityEditor/PrefabInspector.cs create mode 100644 UnityEditor/UnityEditor/PrefabType.cs create mode 100644 UnityEditor/UnityEditor/PrefabUtility.cs create mode 100644 UnityEditor/UnityEditor/PreferenceItem.cs create mode 100644 UnityEditor/UnityEditor/PreferencesWindow.cs create mode 100644 UnityEditor/UnityEditor/PresetFileLocation.cs create mode 100644 UnityEditor/UnityEditor/PresetLibrary.cs create mode 100644 UnityEditor/UnityEditor/PresetLibraryEditor.cs create mode 100644 UnityEditor/UnityEditor/PresetLibraryEditorState.cs create mode 100644 UnityEditor/UnityEditor/PresetLibraryHelpers.cs create mode 100644 UnityEditor/UnityEditor/PresetLibraryLocations.cs create mode 100644 UnityEditor/UnityEditor/PresetLibraryManager.cs create mode 100644 UnityEditor/UnityEditor/PreviewBlendTree.cs create mode 100644 UnityEditor/UnityEditor/PreviewHelpers.cs create mode 100644 UnityEditor/UnityEditor/PreviewRenderUtility.cs create mode 100644 UnityEditor/UnityEditor/PreviewResizer.cs create mode 100644 UnityEditor/UnityEditor/PreviewWindow.cs create mode 100644 UnityEditor/UnityEditor/ProceduralMaterialInformation.cs create mode 100644 UnityEditor/UnityEditor/ProceduralMaterialInspector.cs create mode 100644 UnityEditor/UnityEditor/ProceduralTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/ProfilerIPWindow.cs create mode 100644 UnityEditor/UnityEditor/ProfilerWindow.cs create mode 100644 UnityEditor/UnityEditor/ProjectBrowser.cs create mode 100644 UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/ProjectWindowUtil.cs create mode 100644 UnityEditor/UnityEditor/PropertyAndTargetHandler.cs create mode 100644 UnityEditor/UnityEditor/PropertyDrawer.cs create mode 100644 UnityEditor/UnityEditor/PropertyGUIData.cs create mode 100644 UnityEditor/UnityEditor/PropertyHandler.cs create mode 100644 UnityEditor/UnityEditor/PropertyHandlerCache.cs create mode 100644 UnityEditor/UnityEditor/PropertyModification.cs create mode 100644 UnityEditor/UnityEditor/PurchaseResult.cs create mode 100644 UnityEditor/UnityEditor/QualityCurvesTime.cs create mode 100644 UnityEditor/UnityEditor/QualitySettingsEditor.cs create mode 100644 UnityEditor/UnityEditor/QuaternionCurveTangentCalculation.cs create mode 100644 UnityEditor/UnityEditor/RagdollBuilder.cs create mode 100644 UnityEditor/UnityEditor/RangeDrawer.cs create mode 100644 UnityEditor/UnityEditor/RectHandles.cs create mode 100644 UnityEditor/UnityEditor/RectSelection.cs create mode 100644 UnityEditor/UnityEditor/RectTool.cs create mode 100644 UnityEditor/UnityEditor/RectTransformEditor.cs create mode 100644 UnityEditor/UnityEditor/RectTransformSnapping.cs create mode 100644 UnityEditor/UnityEditor/RemoveAssetOptions.cs create mode 100644 UnityEditor/UnityEditor/RenameOverlay.cs create mode 100644 UnityEditor/UnityEditor/RenderTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/RenderThumbnailUtility.cs create mode 100644 UnityEditor/UnityEditor/RendererModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ReplacePrefabOptions.cs create mode 100644 UnityEditor/UnityEditor/ResolutionDialogSetting.cs create mode 100644 UnityEditor/UnityEditor/RigidbodyEditor.cs create mode 100644 UnityEditor/UnityEditor/RotateTool.cs create mode 100644 UnityEditor/UnityEditor/RotationByVelocityModuleUI.cs create mode 100644 UnityEditor/UnityEditor/RotationCurveInterpolation.cs create mode 100644 UnityEditor/UnityEditor/RotationModuleUI.cs create mode 100644 UnityEditor/UnityEditor/RuntimeClassRegistry.cs create mode 100644 UnityEditor/UnityEditor/SCEBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/SaveAssetsProcessor.cs create mode 100644 UnityEditor/UnityEditor/SaveType.cs create mode 100644 UnityEditor/UnityEditor/SaveWindowLayout.cs create mode 100644 UnityEditor/UnityEditor/SavedBool.cs create mode 100644 UnityEditor/UnityEditor/SavedFilter.cs create mode 100644 UnityEditor/UnityEditor/SavedFloat.cs create mode 100644 UnityEditor/UnityEditor/SavedGUIState.cs create mode 100644 UnityEditor/UnityEditor/SavedInt.cs create mode 100644 UnityEditor/UnityEditor/SavedRenderTargetState.cs create mode 100644 UnityEditor/UnityEditor/SavedSearchFilters.cs create mode 100644 UnityEditor/UnityEditor/ScaleTool.cs create mode 100644 UnityEditor/UnityEditor/SceneFXWindow.cs create mode 100644 UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs create mode 100644 UnityEditor/UnityEditor/SceneHierarchyWindow.cs create mode 100644 UnityEditor/UnityEditor/SceneModeUtility.cs create mode 100644 UnityEditor/UnityEditor/SceneView.cs create mode 100644 UnityEditor/UnityEditor/SceneViewGrid.cs create mode 100644 UnityEditor/UnityEditor/SceneViewMotion.cs create mode 100644 UnityEditor/UnityEditor/SceneViewOverlay.cs create mode 100644 UnityEditor/UnityEditor/SceneViewRotation.cs create mode 100644 UnityEditor/UnityEditor/ScreenShots.cs create mode 100644 UnityEditor/UnityEditor/ScriptAttributeUtility.cs create mode 100644 UnityEditor/UnityEditor/ScriptCallOptimizationLevel.cs create mode 100644 UnityEditor/UnityEditor/ScriptExecutionOrderInspector.cs create mode 100644 UnityEditor/UnityEditor/ScriptReloadProperties.cs create mode 100644 UnityEditor/UnityEditor/ScriptableObjectSaveLoadHelper.cs create mode 100644 UnityEditor/UnityEditor/ScriptableSingleton.cs create mode 100644 UnityEditor/UnityEditor/ScriptableWizard.cs create mode 100644 UnityEditor/UnityEditor/ScriptingImplementation.cs create mode 100644 UnityEditor/UnityEditor/SearchFilter.cs create mode 100644 UnityEditor/UnityEditor/SearchFilterTreeItem.cs create mode 100644 UnityEditor/UnityEditor/SearchUtility.cs create mode 100644 UnityEditor/UnityEditor/SearchableEditorWindow.cs create mode 100644 UnityEditor/UnityEditor/Selection.cs create mode 100644 UnityEditor/UnityEditor/SelectionMode.cs create mode 100644 UnityEditor/UnityEditor/SerializationMode.cs create mode 100644 UnityEditor/UnityEditor/SerializedFileContainerWriter.cs create mode 100644 UnityEditor/UnityEditor/SerializedMinMaxColor.cs create mode 100644 UnityEditor/UnityEditor/SerializedMinMaxCurve.cs create mode 100644 UnityEditor/UnityEditor/SerializedMinMaxGradient.cs create mode 100644 UnityEditor/UnityEditor/SerializedModule.cs create mode 100644 UnityEditor/UnityEditor/SerializedObject.cs create mode 100644 UnityEditor/UnityEditor/SerializedProperty.cs create mode 100644 UnityEditor/UnityEditor/SerializedPropertyType.cs create mode 100644 UnityEditor/UnityEditor/SetResolutionWizard.cs create mode 100644 UnityEditor/UnityEditor/Settings.cs create mode 100644 UnityEditor/UnityEditor/ShaderImporter.cs create mode 100644 UnityEditor/UnityEditor/ShaderImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/ShaderInspector.cs create mode 100644 UnityEditor/UnityEditor/ShaderUtil.cs create mode 100644 UnityEditor/UnityEditor/ShapeModuleUI.cs create mode 100644 UnityEditor/UnityEditor/ShowMode.cs create mode 100644 UnityEditor/UnityEditor/SimpleProfiler.cs create mode 100644 UnityEditor/UnityEditor/SizeByVelocityModuleUI.cs create mode 100644 UnityEditor/UnityEditor/SizeModuleUI.cs create mode 100644 UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs create mode 100644 UnityEditor/UnityEditor/SliderJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/SnapEdge.cs create mode 100644 UnityEditor/UnityEditor/SnapGuide.cs create mode 100644 UnityEditor/UnityEditor/SnapGuideCollection.cs create mode 100644 UnityEditor/UnityEditor/SnapSettings.cs create mode 100644 UnityEditor/UnityEditor/SpaceDrawer.cs create mode 100644 UnityEditor/UnityEditor/SphereColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/SplatPainter.cs create mode 100644 UnityEditor/UnityEditor/SplitView.cs create mode 100644 UnityEditor/UnityEditor/SplitterGUILayout.cs create mode 100644 UnityEditor/UnityEditor/SplitterState.cs create mode 100644 UnityEditor/UnityEditor/SpringJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/SpriteEditorTexturePostprocessor.cs create mode 100644 UnityEditor/UnityEditor/SpriteEditorWindow.cs create mode 100644 UnityEditor/UnityEditor/SpriteImportMode.cs create mode 100644 UnityEditor/UnityEditor/SpriteInspector.cs create mode 100644 UnityEditor/UnityEditor/SpriteMetaData.cs create mode 100644 UnityEditor/UnityEditor/SpritePackerMode.cs create mode 100644 UnityEditor/UnityEditor/SpriteRect.cs create mode 100644 UnityEditor/UnityEditor/SpriteRectCache.cs create mode 100644 UnityEditor/UnityEditor/SpriteRendererInspector.cs create mode 100644 UnityEditor/UnityEditor/SpriteUtility.cs create mode 100644 UnityEditor/UnityEditor/SpriteUtilityWindow.cs create mode 100644 UnityEditor/UnityEditor/StaticEditorFlags.cs create mode 100644 UnityEditor/UnityEditor/StaticOcclusionCulling.cs create mode 100644 UnityEditor/UnityEditor/StaticOcclusionCullingVisualization.cs create mode 100644 UnityEditor/UnityEditor/StrippingLevel.cs create mode 100644 UnityEditor/UnityEditor/StructPropertyGUI.cs create mode 100644 UnityEditor/UnityEditor/StructPropertyGUILayout.cs create mode 100644 UnityEditor/UnityEditor/SubModuleUI.cs create mode 100644 UnityEditor/UnityEditor/SubstanceArchive.cs create mode 100644 UnityEditor/UnityEditor/SubstanceImporter.cs create mode 100644 UnityEditor/UnityEditor/SubstanceImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/SyncVS.cs create mode 100644 UnityEditor/UnityEditor/TabbedEditor.cs create mode 100644 UnityEditor/UnityEditor/TagManager.cs create mode 100644 UnityEditor/UnityEditor/TagManagerInspector.cs create mode 100644 UnityEditor/UnityEditor/TakeInfo.cs create mode 100644 UnityEditor/UnityEditor/TangentMode.cs create mode 100644 UnityEditor/UnityEditor/TargetChoiceHandler.cs create mode 100644 UnityEditor/UnityEditor/TargetGlesGraphics.cs create mode 100644 UnityEditor/UnityEditor/TargetIOSGraphics.cs create mode 100644 UnityEditor/UnityEditor/TerrainDetailContextMenus.cs create mode 100644 UnityEditor/UnityEditor/TerrainEditorUtility.cs create mode 100644 UnityEditor/UnityEditor/TerrainInspector.cs create mode 100644 UnityEditor/UnityEditor/TerrainInspectorUtil.cs create mode 100644 UnityEditor/UnityEditor/TerrainMenus.cs create mode 100644 UnityEditor/UnityEditor/TerrainSplatContextMenus.cs create mode 100644 UnityEditor/UnityEditor/TerrainSplatEditor.cs create mode 100644 UnityEditor/UnityEditor/TerrainTool.cs create mode 100644 UnityEditor/UnityEditor/TerrainTreeContextMenus.cs create mode 100644 UnityEditor/UnityEditor/TerrainWizard.cs create mode 100644 UnityEditor/UnityEditor/TerrainWizards.cs create mode 100644 UnityEditor/UnityEditor/TextAreaDrawer.cs create mode 100644 UnityEditor/UnityEditor/TextAssetInspector.cs create mode 100644 UnityEditor/UnityEditor/TextMeshInspector.cs create mode 100644 UnityEditor/UnityEditor/Texture3DInspector.cs create mode 100644 UnityEditor/UnityEditor/TextureImportInstructions.cs create mode 100644 UnityEditor/UnityEditor/TextureImporter.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterFormat.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterMipFilter.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterNPOTScale.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterNormalFilter.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterSettings.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterType.cs create mode 100644 UnityEditor/UnityEditor/TextureInspector.cs create mode 100644 UnityEditor/UnityEditor/TextureUsageMode.cs create mode 100644 UnityEditor/UnityEditor/TextureUtil.cs create mode 100644 UnityEditor/UnityEditor/TickHandler.cs create mode 100644 UnityEditor/UnityEditor/TickStyle.cs create mode 100644 UnityEditor/UnityEditor/TimeArea.cs create mode 100644 UnityEditor/UnityEditor/TimeControl.cs create mode 100644 UnityEditor/UnityEditor/TimeHelper.cs create mode 100644 UnityEditor/UnityEditor/TimeUpdater.cs create mode 100644 UnityEditor/UnityEditor/Timeline.cs create mode 100644 UnityEditor/UnityEditor/TizenBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/Tool.cs create mode 100644 UnityEditor/UnityEditor/Toolbar.cs create mode 100644 UnityEditor/UnityEditor/Tools.cs create mode 100644 UnityEditor/UnityEditor/TooltipView.cs create mode 100644 UnityEditor/UnityEditor/TransformInspector.cs create mode 100644 UnityEditor/UnityEditor/TransformManipulator.cs create mode 100644 UnityEditor/UnityEditor/TransformRotationGUI.cs create mode 100644 UnityEditor/UnityEditor/TransformSort.cs create mode 100644 UnityEditor/UnityEditor/TransformX.cs create mode 100644 UnityEditor/UnityEditor/TransitionPreview.cs create mode 100644 UnityEditor/UnityEditor/TreeAO.cs create mode 100644 UnityEditor/UnityEditor/TreeAOImporter.cs create mode 100644 UnityEditor/UnityEditor/TreePainter.cs create mode 100644 UnityEditor/UnityEditor/TreePlacementUtility.cs create mode 100644 UnityEditor/UnityEditor/TreeView.cs create mode 100644 UnityEditor/UnityEditor/TreeViewDataSource.cs create mode 100644 UnityEditor/UnityEditor/TreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/TreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/TreeViewItem.cs create mode 100644 UnityEditor/UnityEditor/TreeViewState.cs create mode 100644 UnityEditor/UnityEditor/TreeViewTest.cs create mode 100644 UnityEditor/UnityEditor/TreeViewTestWindow.cs create mode 100644 UnityEditor/UnityEditor/TreeViewUtility.cs create mode 100644 UnityEditor/UnityEditor/TreeWizard.cs create mode 100644 UnityEditor/UnityEditor/TrueTypeFontImporter.cs create mode 100644 UnityEditor/UnityEditor/TrueTypeFontImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/TypeSelection.cs create mode 100644 UnityEditor/UnityEditor/TypeSelectionList.cs create mode 100644 UnityEditor/UnityEditor/UIOrientation.cs create mode 100644 UnityEditor/UnityEditor/UVModuleUI.cs create mode 100644 UnityEditor/UnityEditor/Undo.cs create mode 100644 UnityEditor/UnityEditor/UndoPropertyModification.cs create mode 100644 UnityEditor/UnityEditor/UndoSnapshot.cs create mode 100644 UnityEditor/UnityEditor/UnityStats.cs create mode 100644 UnityEditor/UnityEditor/Unsupported.cs create mode 100644 UnityEditor/UnityEditor/UnwrapParam.cs create mode 100644 UnityEditor/UnityEditor/Unwrapping.cs create mode 100644 UnityEditor/UnityEditor/UploadingBuild.cs create mode 100644 UnityEditor/UnityEditor/UploadingBuildStatus.cs create mode 100644 UnityEditor/UnityEditor/UploadingBuildsMonitor.cs create mode 100644 UnityEditor/UnityEditor/UploadingBuildsUtility.cs create mode 100644 UnityEditor/UnityEditor/ValueSmoother.cs create mode 100644 UnityEditor/UnityEditor/VelocityModuleUI.cs create mode 100644 UnityEditor/UnityEditor/VertexSnapping.cs create mode 100644 UnityEditor/UnityEditor/VerticalGrid.cs create mode 100644 UnityEditor/UnityEditor/VerticalGridWithSplitter.cs create mode 100644 UnityEditor/UnityEditor/VerticalLayout.cs create mode 100644 UnityEditor/UnityEditor/View.cs create mode 100644 UnityEditor/UnityEditor/ViewTool.cs create mode 100644 UnityEditor/UnityEditor/VisualStudioVersion.cs create mode 100644 UnityEditor/UnityEditor/VisualizationBlendTree.cs create mode 100644 UnityEditor/UnityEditor/WebCamTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/WebScriptObject.cs create mode 100644 UnityEditor/UnityEditor/WebView.cs create mode 100644 UnityEditor/UnityEditor/WelcomeScreen.cs create mode 100644 UnityEditor/UnityEditor/WheelColliderEditor.cs create mode 100644 UnityEditor/UnityEditor/WheelJoint2DEditor.cs create mode 100644 UnityEditor/UnityEditor/WindInspector.cs create mode 100644 UnityEditor/UnityEditor/WindowFocusState.cs create mode 100644 UnityEditor/UnityEditor/WindowLayout.cs create mode 100644 UnityEditor/UnityEditor/WrapModeFixed.cs create mode 100644 UnityEditor/UnityEditor/WrapModeFixedCurve.cs create mode 100644 UnityEditor/UnityEditor/XboxBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/XboxOneRunMethod.cs create mode 100644 UnityEditor/UnityEditor/XboxRunMethod.cs create mode 100644 UnityEditor/UnityEditor/ZoomableArea.cs create mode 100644 UnityEditor/UnityEditor/iOSLaunchScreenType.cs create mode 100644 UnityEditor/UnityEditor/iOSSdkVersion.cs create mode 100644 UnityEditor/UnityEditor/iOSShowActivityIndicatorOnLoading.cs create mode 100644 UnityEditor/UnityEditor/iOSStatusBarStyle.cs create mode 100644 UnityEditor/UnityEditor/iOSTargetDevice.cs create mode 100644 UnityEditor/UnityEditor/iOSTargetOSVersion.cs create mode 100644 UnityEditor/UnityEditor/iOSTargetResolution.cs create mode 100644 UnityEditor/UnityEditor/iPhoneArchitecture.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/AssetModificationHook.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/ChangeSetContextMenu.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/ListItem.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/ProjectContextMenu.cs create mode 100644 UnityEditor/UnityEditorInternal.VersionControl/ProjectHooks.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopup.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupGameObjectNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyDataSource.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupObjectNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AddCurvesPopupPropertyNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationCurvePreviewCache.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationKeyTime.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationRecording.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowCurve.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchy.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyAddButtonNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDataSource.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDragging.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyMasterNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyGroupNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyNode.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowHierarchyState.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowKeyframe.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowState.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorCondition.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorController.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs create mode 100644 UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs create mode 100644 UnityEditor/UnityEditorInternal/AssemblyStripper.cs create mode 100644 UnityEditor/UnityEditorInternal/AssetStore.cs create mode 100644 UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs create mode 100644 UnityEditor/UnityEditorInternal/AvatarMask.cs create mode 100644 UnityEditor/UnityEditorInternal/BaseIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditorInternal/BaseObjectTools.cs create mode 100644 UnityEditor/UnityEditorInternal/BlendTree.cs create mode 100644 UnityEditor/UnityEditorInternal/BlendTreePreviewUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/BlendTreeType.cs create mode 100644 UnityEditor/UnityEditorInternal/Button.cs create mode 100644 UnityEditor/UnityEditorInternal/CameraUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/CanAppendBuild.cs create mode 100644 UnityEditor/UnityEditorInternal/Chart.cs create mode 100644 UnityEditor/UnityEditorInternal/ChartData.cs create mode 100644 UnityEditor/UnityEditorInternal/ChartSeries.cs create mode 100644 UnityEditor/UnityEditorInternal/ComponentUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/Disc.cs create mode 100644 UnityEditor/UnityEditorInternal/DopeLine.cs create mode 100644 UnityEditor/UnityEditorInternal/DopeSheetEditor.cs create mode 100644 UnityEditor/UnityEditorInternal/EditorResourcesUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/FreeMove.cs create mode 100644 UnityEditor/UnityEditorInternal/FreeRotate.cs create mode 100644 UnityEditor/UnityEditorInternal/GradientPreviewCache.cs create mode 100644 UnityEditor/UnityEditorInternal/IIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditorInternal/IL2CPPBuilder.cs create mode 100644 UnityEditor/UnityEditorInternal/IL2CPPUtils.cs create mode 100644 UnityEditor/UnityEditorInternal/IProfilerWindowController.cs create mode 100644 UnityEditor/UnityEditorInternal/InternalEditorUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/InternalGraphUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/InternalSpriteUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/JSONParseException.cs create mode 100644 UnityEditor/UnityEditorInternal/JSONParser.cs create mode 100644 UnityEditor/UnityEditorInternal/JSONTypeException.cs create mode 100644 UnityEditor/UnityEditorInternal/JSONValue.cs create mode 100644 UnityEditor/UnityEditorInternal/LogEntries.cs create mode 100644 UnityEditor/UnityEditorInternal/LogEntry.cs create mode 100644 UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/MemoryInfoGCReason.cs create mode 100644 UnityEditor/UnityEditorInternal/MonoScripts.cs create mode 100644 UnityEditor/UnityEditorInternal/NativeProgram.cs create mode 100644 UnityEditor/UnityEditorInternal/ObjectMemoryInfo.cs create mode 100644 UnityEditor/UnityEditorInternal/ObjectMemoryStackInfo.cs create mode 100644 UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerArea.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerChart.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerColors.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerColumn.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerDriver.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerMemoryView.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerProperty.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerViewType.cs create mode 100644 UnityEditor/UnityEditorInternal/RegistryUtil.cs create mode 100644 UnityEditor/UnityEditorInternal/ReorderableList.cs create mode 100644 UnityEditor/UnityEditorInternal/Runner.cs create mode 100644 UnityEditor/UnityEditorInternal/Slider1D.cs create mode 100644 UnityEditor/UnityEditorInternal/Slider2D.cs create mode 100644 UnityEditor/UnityEditorInternal/SliderScale.cs create mode 100644 UnityEditor/UnityEditorInternal/SpriteEditorHandles.cs create mode 100644 UnityEditor/UnityEditorInternal/SpriteEditorMenu.cs create mode 100644 UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/State.cs create mode 100644 UnityEditor/UnityEditorInternal/StateMachine.cs create mode 100644 UnityEditor/UnityEditorInternal/Transition.cs create mode 100644 UnityEditor/UnityEditorInternal/TransitionConditionMode.cs create mode 100644 UnityEditor/UnityEditorInternal/UnityEventDrawer.cs create mode 100644 UnityEditor/ValidationResult.cs create mode 100644 UnityEditor/WinRTUtils.cs create mode 100644 UnityEditor/WindowsDesktopStandalonePostProcessor.cs create mode 100644 UnityEngine/AOT/MonoPInvokeCallbackAttribute.cs create mode 100644 UnityEngine/Properties/AssemblyInfo.cs create mode 100644 UnityEngine/UnityEngine.Events/ArgumentCache.cs create mode 100644 UnityEngine/UnityEngine.Events/BaseInvokableCall.cs create mode 100644 UnityEngine/UnityEngine.Events/CachedInvokableCall.cs create mode 100644 UnityEngine/UnityEngine.Events/InvokableCall.cs create mode 100644 UnityEngine/UnityEngine.Events/InvokableCallList.cs create mode 100644 UnityEngine/UnityEngine.Events/PersistentCall.cs create mode 100644 UnityEngine/UnityEngine.Events/PersistentCallGroup.cs create mode 100644 UnityEngine/UnityEngine.Events/PersistentListenerMode.cs create mode 100644 UnityEngine/UnityEngine.Events/UnityAction.cs create mode 100644 UnityEngine/UnityEngine.Events/UnityEvent.cs create mode 100644 UnityEngine/UnityEngine.Events/UnityEventBase.cs create mode 100644 UnityEngine/UnityEngine.Events/UnityEventCallState.cs create mode 100644 UnityEngine/UnityEngine.Flash/ActionScript.cs create mode 100644 UnityEngine/UnityEngine.Flash/FlashPlayer.cs create mode 100644 UnityEngine/UnityEngine.Internal/DefaultValueAttribute.cs create mode 100644 UnityEngine/UnityEngine.Internal/ExcludeFromDocsAttribute.cs create mode 100644 UnityEngine/UnityEngine.Rendering/BlendMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/BlendOp.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ColorWriteMask.cs create mode 100644 UnityEngine/UnityEngine.Rendering/CompareFunction.cs create mode 100644 UnityEngine/UnityEngine.Rendering/CullMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/StencilOp.cs create mode 100644 UnityEngine/UnityEngine.Serialization/DictionarySerializationSurrogate.cs create mode 100644 UnityEngine/UnityEngine.Serialization/FormerlySerializedAsAttribute.cs create mode 100644 UnityEngine/UnityEngine.Serialization/ListSerializationSurrogate.cs create mode 100644 UnityEngine/UnityEngine.Serialization/SerializationHelper.cs create mode 100644 UnityEngine/UnityEngine.Serialization/UnitySurrogateSelector.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.GameCenter/GameCenterPlatform.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/Achievement.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/AchievementDescription.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/Leaderboard.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/LocalUser.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/Score.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms.Impl/UserProfile.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/ActivePlatform.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/IAchievement.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/IAchievementDescription.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/ILeaderboard.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/ILocalUser.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/IScore.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/ISocialPlatform.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/IUserProfile.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/Local.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/Range.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/TimeScope.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/UserScope.cs create mode 100644 UnityEngine/UnityEngine.SocialPlatforms/UserState.cs create mode 100644 UnityEngine/UnityEngine.Sprites/DataUtility.cs create mode 100644 UnityEngine/UnityEngine.csproj create mode 100644 UnityEngine/UnityEngine/ADBannerView.cs create mode 100644 UnityEngine/UnityEngine/ADInterstitialAd.cs create mode 100644 UnityEngine/UnityEngine/AccelerationEvent.cs create mode 100644 UnityEngine/UnityEngine/AddComponentMenu.cs create mode 100644 UnityEngine/UnityEngine/AnchoredJoint2D.cs create mode 100644 UnityEngine/UnityEngine/AndroidActivityIndicatorStyle.cs create mode 100644 UnityEngine/UnityEngine/AndroidInput.cs create mode 100644 UnityEngine/UnityEngine/AndroidJNI.cs create mode 100644 UnityEngine/UnityEngine/AndroidJNIHelper.cs create mode 100644 UnityEngine/UnityEngine/AndroidJNISafe.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaClass.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaException.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaObject.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaProxy.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaRunnable.cs create mode 100644 UnityEngine/UnityEngine/AndroidJavaRunnableProxy.cs create mode 100644 UnityEngine/UnityEngine/AndroidReflection.cs create mode 100644 UnityEngine/UnityEngine/Animation.cs create mode 100644 UnityEngine/UnityEngine/AnimationBlendMode.cs create mode 100644 UnityEngine/UnityEngine/AnimationClip.cs create mode 100644 UnityEngine/UnityEngine/AnimationClipPair.cs create mode 100644 UnityEngine/UnityEngine/AnimationCullingType.cs create mode 100644 UnityEngine/UnityEngine/AnimationCurve.cs create mode 100644 UnityEngine/UnityEngine/AnimationEvent.cs create mode 100644 UnityEngine/UnityEngine/AnimationInfo.cs create mode 100644 UnityEngine/UnityEngine/AnimationPlayMode.cs create mode 100644 UnityEngine/UnityEngine/AnimationState.cs create mode 100644 UnityEngine/UnityEngine/Animator.cs create mode 100644 UnityEngine/UnityEngine/AnimatorCullingMode.cs create mode 100644 UnityEngine/UnityEngine/AnimatorOverrideController.cs create mode 100644 UnityEngine/UnityEngine/AnimatorStateInfo.cs create mode 100644 UnityEngine/UnityEngine/AnimatorTransitionInfo.cs create mode 100644 UnityEngine/UnityEngine/AnimatorUpdateMode.cs create mode 100644 UnityEngine/UnityEngine/AnimatorUtility.cs create mode 100644 UnityEngine/UnityEngine/AnisotropicFiltering.cs create mode 100644 UnityEngine/UnityEngine/Application.cs create mode 100644 UnityEngine/UnityEngine/ArmDoF.cs create mode 100644 UnityEngine/UnityEngine/AssemblyIsEditorAssembly.cs create mode 100644 UnityEngine/UnityEngine/AssetBundle.cs create mode 100644 UnityEngine/UnityEngine/AssetBundleCreateRequest.cs create mode 100644 UnityEngine/UnityEngine/AssetBundleRequest.cs create mode 100644 UnityEngine/UnityEngine/AsyncOperation.cs create mode 100644 UnityEngine/UnityEngine/AttributeHelperEngine.cs create mode 100644 UnityEngine/UnityEngine/AudioChorusFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioClip.cs create mode 100644 UnityEngine/UnityEngine/AudioDistortionFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioEchoFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioHighPassFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioListener.cs create mode 100644 UnityEngine/UnityEngine/AudioLowPassFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioReverbFilter.cs create mode 100644 UnityEngine/UnityEngine/AudioReverbPreset.cs create mode 100644 UnityEngine/UnityEngine/AudioReverbZone.cs create mode 100644 UnityEngine/UnityEngine/AudioRolloffMode.cs create mode 100644 UnityEngine/UnityEngine/AudioSettings.cs create mode 100644 UnityEngine/UnityEngine/AudioSource.cs create mode 100644 UnityEngine/UnityEngine/AudioSpeakerMode.cs create mode 100644 UnityEngine/UnityEngine/AudioType.cs create mode 100644 UnityEngine/UnityEngine/AudioVelocityUpdateMode.cs create mode 100644 UnityEngine/UnityEngine/Avatar.cs create mode 100644 UnityEngine/UnityEngine/AvatarBuilder.cs create mode 100644 UnityEngine/UnityEngine/AvatarIKGoal.cs create mode 100644 UnityEngine/UnityEngine/AvatarTarget.cs create mode 100644 UnityEngine/UnityEngine/Behaviour.cs create mode 100644 UnityEngine/UnityEngine/BitStream.cs create mode 100644 UnityEngine/UnityEngine/BlendWeights.cs create mode 100644 UnityEngine/UnityEngine/BodyDoF.cs create mode 100644 UnityEngine/UnityEngine/BoneWeight.cs create mode 100644 UnityEngine/UnityEngine/Bounds.cs create mode 100644 UnityEngine/UnityEngine/BoxCollider.cs create mode 100644 UnityEngine/UnityEngine/BoxCollider2D.cs create mode 100644 UnityEngine/UnityEngine/CacheIndex.cs create mode 100644 UnityEngine/UnityEngine/Caching.cs create mode 100644 UnityEngine/UnityEngine/CalendarIdentifier.cs create mode 100644 UnityEngine/UnityEngine/CalendarUnit.cs create mode 100644 UnityEngine/UnityEngine/Camera.cs create mode 100644 UnityEngine/UnityEngine/CameraClearFlags.cs create mode 100644 UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs create mode 100644 UnityEngine/UnityEngine/Canvas.cs create mode 100644 UnityEngine/UnityEngine/CanvasGroup.cs create mode 100644 UnityEngine/UnityEngine/CanvasRenderer.cs create mode 100644 UnityEngine/UnityEngine/CapsuleCollider.cs create mode 100644 UnityEngine/UnityEngine/CharacterController.cs create mode 100644 UnityEngine/UnityEngine/CharacterInfo.cs create mode 100644 UnityEngine/UnityEngine/CharacterJoint.cs create mode 100644 UnityEngine/UnityEngine/CircleCollider2D.cs create mode 100644 UnityEngine/UnityEngine/ClassLibraryInitializer.cs create mode 100644 UnityEngine/UnityEngine/Cloth.cs create mode 100644 UnityEngine/UnityEngine/ClothRenderer.cs create mode 100644 UnityEngine/UnityEngine/ClothSkinningCoefficient.cs create mode 100644 UnityEngine/UnityEngine/Collider.cs create mode 100644 UnityEngine/UnityEngine/Collider2D.cs create mode 100644 UnityEngine/UnityEngine/ColliderErrorState2D.cs create mode 100644 UnityEngine/UnityEngine/Collision.cs create mode 100644 UnityEngine/UnityEngine/Collision2D.cs create mode 100644 UnityEngine/UnityEngine/CollisionDetectionMode.cs create mode 100644 UnityEngine/UnityEngine/CollisionDetectionMode2D.cs create mode 100644 UnityEngine/UnityEngine/CollisionFlags.cs create mode 100644 UnityEngine/UnityEngine/Color.cs create mode 100644 UnityEngine/UnityEngine/Color32.cs create mode 100644 UnityEngine/UnityEngine/ColorSpace.cs create mode 100644 UnityEngine/UnityEngine/CombineInstance.cs create mode 100644 UnityEngine/UnityEngine/Compass.cs create mode 100644 UnityEngine/UnityEngine/Component.cs create mode 100644 UnityEngine/UnityEngine/ComputeBuffer.cs create mode 100644 UnityEngine/UnityEngine/ComputeBufferType.cs create mode 100644 UnityEngine/UnityEngine/ComputeShader.cs create mode 100644 UnityEngine/UnityEngine/ConfigurableJoint.cs create mode 100644 UnityEngine/UnityEngine/ConfigurableJointMotion.cs create mode 100644 UnityEngine/UnityEngine/ConnectionTesterStatus.cs create mode 100644 UnityEngine/UnityEngine/ConstantForce.cs create mode 100644 UnityEngine/UnityEngine/ConstructorSafeAttribute.cs create mode 100644 UnityEngine/UnityEngine/ContactPoint.cs create mode 100644 UnityEngine/UnityEngine/ContactPoint2D.cs create mode 100644 UnityEngine/UnityEngine/ContextMenu.cs create mode 100644 UnityEngine/UnityEngine/ContextMenuItemAttribute.cs create mode 100644 UnityEngine/UnityEngine/ControllerColliderHit.cs create mode 100644 UnityEngine/UnityEngine/Coroutine.cs create mode 100644 UnityEngine/UnityEngine/CppBodyAttribute.cs create mode 100644 UnityEngine/UnityEngine/CppDefineAttribute.cs create mode 100644 UnityEngine/UnityEngine/CppIncludeAttribute.cs create mode 100644 UnityEngine/UnityEngine/CppInvokeAttribute.cs create mode 100644 UnityEngine/UnityEngine/CppPropertyAttribute.cs create mode 100644 UnityEngine/UnityEngine/CppPropertyBodyAttribute.cs create mode 100644 UnityEngine/UnityEngine/CrashReport.cs create mode 100644 UnityEngine/UnityEngine/Cubemap.cs create mode 100644 UnityEngine/UnityEngine/CubemapFace.cs create mode 100644 UnityEngine/UnityEngine/Cursor.cs create mode 100644 UnityEngine/UnityEngine/CursorMode.cs create mode 100644 UnityEngine/UnityEngine/Debug.cs create mode 100644 UnityEngine/UnityEngine/DepthTextureMode.cs create mode 100644 UnityEngine/UnityEngine/DetailPrototype.cs create mode 100644 UnityEngine/UnityEngine/DetailRenderMode.cs create mode 100644 UnityEngine/UnityEngine/DeviceOrientation.cs create mode 100644 UnityEngine/UnityEngine/DeviceType.cs create mode 100644 UnityEngine/UnityEngine/DisallowMultipleComponent.cs create mode 100644 UnityEngine/UnityEngine/Display.cs create mode 100644 UnityEngine/UnityEngine/DistanceJoint2D.cs create mode 100644 UnityEngine/UnityEngine/DoF.cs create mode 100644 UnityEngine/UnityEngine/DrivenRectTransformTracker.cs create mode 100644 UnityEngine/UnityEngine/DrivenTransformProperties.cs create mode 100644 UnityEngine/UnityEngine/EdgeCollider2D.cs create mode 100644 UnityEngine/UnityEngine/Event.cs create mode 100644 UnityEngine/UnityEngine/EventModifiers.cs create mode 100644 UnityEngine/UnityEngine/EventType.cs create mode 100644 UnityEngine/UnityEngine/ExecuteInEditMode.cs create mode 100644 UnityEngine/UnityEngine/ExitGUIException.cs create mode 100644 UnityEngine/UnityEngine/FFTWindow.cs create mode 100644 UnityEngine/UnityEngine/FilterMode.cs create mode 100644 UnityEngine/UnityEngine/FingerDoF.cs create mode 100644 UnityEngine/UnityEngine/FixedJoint.cs create mode 100644 UnityEngine/UnityEngine/Flare.cs create mode 100644 UnityEngine/UnityEngine/FocusType.cs create mode 100644 UnityEngine/UnityEngine/FogMode.cs create mode 100644 UnityEngine/UnityEngine/Font.cs create mode 100644 UnityEngine/UnityEngine/FontStyle.cs create mode 100644 UnityEngine/UnityEngine/ForceMode.cs create mode 100644 UnityEngine/UnityEngine/ForceMode2D.cs create mode 100644 UnityEngine/UnityEngine/FullScreenMovieControlMode.cs create mode 100644 UnityEngine/UnityEngine/FullScreenMovieScalingMode.cs create mode 100644 UnityEngine/UnityEngine/GL.cs create mode 100644 UnityEngine/UnityEngine/GUI.cs create mode 100644 UnityEngine/UnityEngine/GUIAspectSizer.cs create mode 100644 UnityEngine/UnityEngine/GUIClip.cs create mode 100644 UnityEngine/UnityEngine/GUIContent.cs create mode 100644 UnityEngine/UnityEngine/GUIElement.cs create mode 100644 UnityEngine/UnityEngine/GUIGridSizer.cs create mode 100644 UnityEngine/UnityEngine/GUILayer.cs create mode 100644 UnityEngine/UnityEngine/GUILayout.cs create mode 100644 UnityEngine/UnityEngine/GUILayoutEntry.cs create mode 100644 UnityEngine/UnityEngine/GUILayoutGroup.cs create mode 100644 UnityEngine/UnityEngine/GUILayoutOption.cs create mode 100644 UnityEngine/UnityEngine/GUILayoutUtility.cs create mode 100644 UnityEngine/UnityEngine/GUIScrollGroup.cs create mode 100644 UnityEngine/UnityEngine/GUISettings.cs create mode 100644 UnityEngine/UnityEngine/GUISkin.cs create mode 100644 UnityEngine/UnityEngine/GUIStateObjects.cs create mode 100644 UnityEngine/UnityEngine/GUIStyle.cs create mode 100644 UnityEngine/UnityEngine/GUIStyleState.cs create mode 100644 UnityEngine/UnityEngine/GUIText.cs create mode 100644 UnityEngine/UnityEngine/GUITexture.cs create mode 100644 UnityEngine/UnityEngine/GUIUtility.cs create mode 100644 UnityEngine/UnityEngine/GUIWordWrapSizer.cs create mode 100644 UnityEngine/UnityEngine/GameObject.cs create mode 100644 UnityEngine/UnityEngine/GeometryUtility.cs create mode 100644 UnityEngine/UnityEngine/Gizmos.cs create mode 100644 UnityEngine/UnityEngine/Gradient.cs create mode 100644 UnityEngine/UnityEngine/GradientAlphaKey.cs create mode 100644 UnityEngine/UnityEngine/GradientColorKey.cs create mode 100644 UnityEngine/UnityEngine/Graphics.cs create mode 100644 UnityEngine/UnityEngine/Gyroscope.cs create mode 100644 UnityEngine/UnityEngine/Handheld.cs create mode 100644 UnityEngine/UnityEngine/HeadDoF.cs create mode 100644 UnityEngine/UnityEngine/HeaderAttribute.cs create mode 100644 UnityEngine/UnityEngine/HideFlags.cs create mode 100644 UnityEngine/UnityEngine/HideInInspector.cs create mode 100644 UnityEngine/UnityEngine/HingeJoint.cs create mode 100644 UnityEngine/UnityEngine/HingeJoint2D.cs create mode 100644 UnityEngine/UnityEngine/HorizontalWrapMode.cs create mode 100644 UnityEngine/UnityEngine/HostData.cs create mode 100644 UnityEngine/UnityEngine/HumanBodyBones.cs create mode 100644 UnityEngine/UnityEngine/HumanBodyPart.cs create mode 100644 UnityEngine/UnityEngine/HumanBone.cs create mode 100644 UnityEngine/UnityEngine/HumanDescription.cs create mode 100644 UnityEngine/UnityEngine/HumanLimit.cs create mode 100644 UnityEngine/UnityEngine/HumanParameter.cs create mode 100644 UnityEngine/UnityEngine/HumanTrait.cs create mode 100644 UnityEngine/UnityEngine/ICanvasRaycastFilter.cs create mode 100644 UnityEngine/UnityEngine/IMECompositionMode.cs create mode 100644 UnityEngine/UnityEngine/ISerializationCallbackReceiver.cs create mode 100644 UnityEngine/UnityEngine/ImageEffectOpaque.cs create mode 100644 UnityEngine/UnityEngine/ImageEffectTransformsToLDR.cs create mode 100644 UnityEngine/UnityEngine/ImagePosition.cs create mode 100644 UnityEngine/UnityEngine/ImplementedInActionScriptAttribute.cs create mode 100644 UnityEngine/UnityEngine/Input.cs create mode 100644 UnityEngine/UnityEngine/InteractiveCloth.cs create mode 100644 UnityEngine/UnityEngine/InternalDrawTextureArguments.cs create mode 100644 UnityEngine/UnityEngine/InternalEmitParticleArguments.cs create mode 100644 UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs create mode 100644 UnityEngine/UnityEngine/Internal_DrawArguments.cs create mode 100644 UnityEngine/UnityEngine/Internal_DrawMeshMatrixArguments.cs create mode 100644 UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs create mode 100644 UnityEngine/UnityEngine/Internal_DrawWithTextSelectionArguments.cs create mode 100644 UnityEngine/UnityEngine/Joint.cs create mode 100644 UnityEngine/UnityEngine/Joint2D.cs create mode 100644 UnityEngine/UnityEngine/JointAngleLimits2D.cs create mode 100644 UnityEngine/UnityEngine/JointDrive.cs create mode 100644 UnityEngine/UnityEngine/JointDriveMode.cs create mode 100644 UnityEngine/UnityEngine/JointLimitState2D.cs create mode 100644 UnityEngine/UnityEngine/JointLimits.cs create mode 100644 UnityEngine/UnityEngine/JointMotor.cs create mode 100644 UnityEngine/UnityEngine/JointMotor2D.cs create mode 100644 UnityEngine/UnityEngine/JointProjectionMode.cs create mode 100644 UnityEngine/UnityEngine/JointSpring.cs create mode 100644 UnityEngine/UnityEngine/JointSuspension2D.cs create mode 100644 UnityEngine/UnityEngine/JointTranslationLimits2D.cs create mode 100644 UnityEngine/UnityEngine/KeyCode.cs create mode 100644 UnityEngine/UnityEngine/Keyframe.cs create mode 100644 UnityEngine/UnityEngine/LOD.cs create mode 100644 UnityEngine/UnityEngine/LODGroup.cs create mode 100644 UnityEngine/UnityEngine/LayerMask.cs create mode 100644 UnityEngine/UnityEngine/LegDoF.cs create mode 100644 UnityEngine/UnityEngine/LensFlare.cs create mode 100644 UnityEngine/UnityEngine/Light.cs create mode 100644 UnityEngine/UnityEngine/LightProbeGroup.cs create mode 100644 UnityEngine/UnityEngine/LightProbes.cs create mode 100644 UnityEngine/UnityEngine/LightRenderMode.cs create mode 100644 UnityEngine/UnityEngine/LightShadows.cs create mode 100644 UnityEngine/UnityEngine/LightType.cs create mode 100644 UnityEngine/UnityEngine/LightmapData.cs create mode 100644 UnityEngine/UnityEngine/LightmapSettings.cs create mode 100644 UnityEngine/UnityEngine/LightmapsMode.cs create mode 100644 UnityEngine/UnityEngine/LineRenderer.cs create mode 100644 UnityEngine/UnityEngine/LocalNotification.cs create mode 100644 UnityEngine/UnityEngine/LocalNotificationType.cs create mode 100644 UnityEngine/UnityEngine/LocationInfo.cs create mode 100644 UnityEngine/UnityEngine/LocationService.cs create mode 100644 UnityEngine/UnityEngine/LocationServiceStatus.cs create mode 100644 UnityEngine/UnityEngine/LogType.cs create mode 100644 UnityEngine/UnityEngine/MarshallOnlyFirstField.cs create mode 100644 UnityEngine/UnityEngine/MasterServer.cs create mode 100644 UnityEngine/UnityEngine/MasterServerEvent.cs create mode 100644 UnityEngine/UnityEngine/MatchTargetWeightMask.cs create mode 100644 UnityEngine/UnityEngine/Material.cs create mode 100644 UnityEngine/UnityEngine/MaterialPropertyBlock.cs create mode 100644 UnityEngine/UnityEngine/Mathf.cs create mode 100644 UnityEngine/UnityEngine/Matrix4x4.cs create mode 100644 UnityEngine/UnityEngine/Mesh.cs create mode 100644 UnityEngine/UnityEngine/MeshCollider.cs create mode 100644 UnityEngine/UnityEngine/MeshFilter.cs create mode 100644 UnityEngine/UnityEngine/MeshRenderer.cs create mode 100644 UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs create mode 100644 UnityEngine/UnityEngine/MeshTopology.cs create mode 100644 UnityEngine/UnityEngine/Microphone.cs create mode 100644 UnityEngine/UnityEngine/MissingComponentException.cs create mode 100644 UnityEngine/UnityEngine/MissingReferenceException.cs create mode 100644 UnityEngine/UnityEngine/MonoBehaviour.cs create mode 100644 UnityEngine/UnityEngine/Motion.cs create mode 100644 UnityEngine/UnityEngine/MovieTexture.cs create mode 100644 UnityEngine/UnityEngine/MultilineAttribute.cs create mode 100644 UnityEngine/UnityEngine/NPOTSupport.cs create mode 100644 UnityEngine/UnityEngine/NavMesh.cs create mode 100644 UnityEngine/UnityEngine/NavMeshAgent.cs create mode 100644 UnityEngine/UnityEngine/NavMeshHit.cs create mode 100644 UnityEngine/UnityEngine/NavMeshObstacle.cs create mode 100644 UnityEngine/UnityEngine/NavMeshPath.cs create mode 100644 UnityEngine/UnityEngine/NavMeshPathStatus.cs create mode 100644 UnityEngine/UnityEngine/NavMeshTriangulation.cs create mode 100644 UnityEngine/UnityEngine/Network.cs create mode 100644 UnityEngine/UnityEngine/NetworkConnectionError.cs create mode 100644 UnityEngine/UnityEngine/NetworkDisconnection.cs create mode 100644 UnityEngine/UnityEngine/NetworkLogLevel.cs create mode 100644 UnityEngine/UnityEngine/NetworkMessageInfo.cs create mode 100644 UnityEngine/UnityEngine/NetworkPeerType.cs create mode 100644 UnityEngine/UnityEngine/NetworkPlayer.cs create mode 100644 UnityEngine/UnityEngine/NetworkReachability.cs create mode 100644 UnityEngine/UnityEngine/NetworkStateSynchronization.cs create mode 100644 UnityEngine/UnityEngine/NetworkView.cs create mode 100644 UnityEngine/UnityEngine/NetworkViewID.cs create mode 100644 UnityEngine/UnityEngine/NotConvertedAttribute.cs create mode 100644 UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs create mode 100644 UnityEngine/UnityEngine/NotRenamedAttribute.cs create mode 100644 UnityEngine/UnityEngine/NotificationServices.cs create mode 100644 UnityEngine/UnityEngine/Object.cs create mode 100644 UnityEngine/UnityEngine/ObstacleAvoidanceType.cs create mode 100644 UnityEngine/UnityEngine/OcclusionArea.cs create mode 100644 UnityEngine/UnityEngine/OcclusionPortal.cs create mode 100644 UnityEngine/UnityEngine/OffMeshLink.cs create mode 100644 UnityEngine/UnityEngine/OffMeshLinkData.cs create mode 100644 UnityEngine/UnityEngine/OffMeshLinkType.cs create mode 100644 UnityEngine/UnityEngine/Particle.cs create mode 100644 UnityEngine/UnityEngine/ParticleAnimator.cs create mode 100644 UnityEngine/UnityEngine/ParticleEmitter.cs create mode 100644 UnityEngine/UnityEngine/ParticleRenderMode.cs create mode 100644 UnityEngine/UnityEngine/ParticleRenderer.cs create mode 100644 UnityEngine/UnityEngine/ParticleSystem.cs create mode 100644 UnityEngine/UnityEngine/ParticleSystemRenderMode.cs create mode 100644 UnityEngine/UnityEngine/ParticleSystemRenderer.cs create mode 100644 UnityEngine/UnityEngine/ParticleSystemSimulationSpace.cs create mode 100644 UnityEngine/UnityEngine/PhysicMaterial.cs create mode 100644 UnityEngine/UnityEngine/PhysicMaterialCombine.cs create mode 100644 UnityEngine/UnityEngine/Physics.cs create mode 100644 UnityEngine/UnityEngine/Physics2D.cs create mode 100644 UnityEngine/UnityEngine/PhysicsMaterial2D.cs create mode 100644 UnityEngine/UnityEngine/Ping.cs create mode 100644 UnityEngine/UnityEngine/Plane.cs create mode 100644 UnityEngine/UnityEngine/PlatformSelection.cs create mode 100644 UnityEngine/UnityEngine/PlayMode.cs create mode 100644 UnityEngine/UnityEngine/PlayerPrefs.cs create mode 100644 UnityEngine/UnityEngine/PlayerPrefsException.cs create mode 100644 UnityEngine/UnityEngine/PolygonCollider2D.cs create mode 100644 UnityEngine/UnityEngine/PrimitiveType.cs create mode 100644 UnityEngine/UnityEngine/ProceduralCacheSize.cs create mode 100644 UnityEngine/UnityEngine/ProceduralLoadingBehavior.cs create mode 100644 UnityEngine/UnityEngine/ProceduralMaterial.cs create mode 100644 UnityEngine/UnityEngine/ProceduralOutputType.cs create mode 100644 UnityEngine/UnityEngine/ProceduralProcessorUsage.cs create mode 100644 UnityEngine/UnityEngine/ProceduralPropertyDescription.cs create mode 100644 UnityEngine/UnityEngine/ProceduralPropertyType.cs create mode 100644 UnityEngine/UnityEngine/ProceduralTexture.cs create mode 100644 UnityEngine/UnityEngine/Profiler.cs create mode 100644 UnityEngine/UnityEngine/Projector.cs create mode 100644 UnityEngine/UnityEngine/PropertyAttribute.cs create mode 100644 UnityEngine/UnityEngine/QualityLevel.cs create mode 100644 UnityEngine/UnityEngine/QualitySettings.cs create mode 100644 UnityEngine/UnityEngine/Quaternion.cs create mode 100644 UnityEngine/UnityEngine/QueueMode.cs create mode 100644 UnityEngine/UnityEngine/RPC.cs create mode 100644 UnityEngine/UnityEngine/RPCMode.cs create mode 100644 UnityEngine/UnityEngine/Random.cs create mode 100644 UnityEngine/UnityEngine/RangeAttribute.cs create mode 100644 UnityEngine/UnityEngine/Ray.cs create mode 100644 UnityEngine/UnityEngine/Ray2D.cs create mode 100644 UnityEngine/UnityEngine/RaycastCollider.cs create mode 100644 UnityEngine/UnityEngine/RaycastHit.cs create mode 100644 UnityEngine/UnityEngine/RaycastHit2D.cs create mode 100644 UnityEngine/UnityEngine/Rect.cs create mode 100644 UnityEngine/UnityEngine/RectOffset.cs create mode 100644 UnityEngine/UnityEngine/RectTransform.cs create mode 100644 UnityEngine/UnityEngine/RectTransformUtility.cs create mode 100644 UnityEngine/UnityEngine/ReferenceData.cs create mode 100644 UnityEngine/UnityEngine/RemoteNotification.cs create mode 100644 UnityEngine/UnityEngine/RemoteNotificationType.cs create mode 100644 UnityEngine/UnityEngine/RenderBuffer.cs create mode 100644 UnityEngine/UnityEngine/RenderMode.cs create mode 100644 UnityEngine/UnityEngine/RenderSettings.cs create mode 100644 UnityEngine/UnityEngine/RenderTexture.cs create mode 100644 UnityEngine/UnityEngine/RenderTextureFormat.cs create mode 100644 UnityEngine/UnityEngine/RenderTextureReadWrite.cs create mode 100644 UnityEngine/UnityEngine/Renderer.cs create mode 100644 UnityEngine/UnityEngine/RenderingPath.cs create mode 100644 UnityEngine/UnityEngine/RequireComponent.cs create mode 100644 UnityEngine/UnityEngine/Resolution.cs create mode 100644 UnityEngine/UnityEngine/ResourceRequest.cs create mode 100644 UnityEngine/UnityEngine/Resources.cs create mode 100644 UnityEngine/UnityEngine/Rigidbody.cs create mode 100644 UnityEngine/UnityEngine/Rigidbody2D.cs create mode 100644 UnityEngine/UnityEngine/RigidbodyConstraints.cs create mode 100644 UnityEngine/UnityEngine/RigidbodyInterpolation.cs create mode 100644 UnityEngine/UnityEngine/RigidbodyInterpolation2D.cs create mode 100644 UnityEngine/UnityEngine/RigidbodySleepMode2D.cs create mode 100644 UnityEngine/UnityEngine/RotationDriveMode.cs create mode 100644 UnityEngine/UnityEngine/RuntimeAnimatorController.cs create mode 100644 UnityEngine/UnityEngine/RuntimePlatform.cs create mode 100644 UnityEngine/UnityEngine/RuntimeUndo.cs create mode 100644 UnityEngine/UnityEngine/SamsungTV.cs create mode 100644 UnityEngine/UnityEngine/ScaleMode.cs create mode 100644 UnityEngine/UnityEngine/Screen.cs create mode 100644 UnityEngine/UnityEngine/ScreenOrientation.cs create mode 100644 UnityEngine/UnityEngine/ScriptableObject.cs create mode 100644 UnityEngine/UnityEngine/ScrollWaitDefinitions.cs create mode 100644 UnityEngine/UnityEngine/Security.cs create mode 100644 UnityEngine/UnityEngine/SelectionBaseAttribute.cs create mode 100644 UnityEngine/UnityEngine/SendMessageOptions.cs create mode 100644 UnityEngine/UnityEngine/SendMouseEvents.cs create mode 100644 UnityEngine/UnityEngine/SerializeField.cs create mode 100644 UnityEngine/UnityEngine/SerializePrivateVariables.cs create mode 100644 UnityEngine/UnityEngine/SetupCoroutine.cs create mode 100644 UnityEngine/UnityEngine/Shader.cs create mode 100644 UnityEngine/UnityEngine/ShadowProjection.cs create mode 100644 UnityEngine/UnityEngine/SkeletonBone.cs create mode 100644 UnityEngine/UnityEngine/SkinQuality.cs create mode 100644 UnityEngine/UnityEngine/SkinnedCloth.cs create mode 100644 UnityEngine/UnityEngine/SkinnedMeshRenderer.cs create mode 100644 UnityEngine/UnityEngine/Skybox.cs create mode 100644 UnityEngine/UnityEngine/SleepTimeout.cs create mode 100644 UnityEngine/UnityEngine/SliderHandler.cs create mode 100644 UnityEngine/UnityEngine/SliderJoint2D.cs create mode 100644 UnityEngine/UnityEngine/SliderState.cs create mode 100644 UnityEngine/UnityEngine/Social.cs create mode 100644 UnityEngine/UnityEngine/SoftJointLimit.cs create mode 100644 UnityEngine/UnityEngine/Space.cs create mode 100644 UnityEngine/UnityEngine/SpaceAttribute.cs create mode 100644 UnityEngine/UnityEngine/SparseTexture.cs create mode 100644 UnityEngine/UnityEngine/SphereCollider.cs create mode 100644 UnityEngine/UnityEngine/SplatPrototype.cs create mode 100644 UnityEngine/UnityEngine/SpringJoint.cs create mode 100644 UnityEngine/UnityEngine/SpringJoint2D.cs create mode 100644 UnityEngine/UnityEngine/Sprite.cs create mode 100644 UnityEngine/UnityEngine/SpriteAlignment.cs create mode 100644 UnityEngine/UnityEngine/SpriteMeshType.cs create mode 100644 UnityEngine/UnityEngine/SpritePackingMode.cs create mode 100644 UnityEngine/UnityEngine/SpritePackingRotation.cs create mode 100644 UnityEngine/UnityEngine/SpriteRenderer.cs create mode 100644 UnityEngine/UnityEngine/StackTraceUtility.cs create mode 100644 UnityEngine/UnityEngine/StaticBatchingUtility.cs create mode 100644 UnityEngine/UnityEngine/SystemClock.cs create mode 100644 UnityEngine/UnityEngine/SystemInfo.cs create mode 100644 UnityEngine/UnityEngine/SystemLanguage.cs create mode 100644 UnityEngine/UnityEngine/Terrain.cs create mode 100644 UnityEngine/UnityEngine/TerrainChangedFlags.cs create mode 100644 UnityEngine/UnityEngine/TerrainCollider.cs create mode 100644 UnityEngine/UnityEngine/TerrainData.cs create mode 100644 UnityEngine/UnityEngine/TerrainRenderFlags.cs create mode 100644 UnityEngine/UnityEngine/TexGenMode.cs create mode 100644 UnityEngine/UnityEngine/TextAlignment.cs create mode 100644 UnityEngine/UnityEngine/TextAnchor.cs create mode 100644 UnityEngine/UnityEngine/TextAreaAttribute.cs create mode 100644 UnityEngine/UnityEngine/TextAsset.cs create mode 100644 UnityEngine/UnityEngine/TextClipping.cs create mode 100644 UnityEngine/UnityEngine/TextEditor.cs create mode 100644 UnityEngine/UnityEngine/TextGenerationSettings.cs create mode 100644 UnityEngine/UnityEngine/TextGenerator.cs create mode 100644 UnityEngine/UnityEngine/TextMesh.cs create mode 100644 UnityEngine/UnityEngine/Texture.cs create mode 100644 UnityEngine/UnityEngine/Texture2D.cs create mode 100644 UnityEngine/UnityEngine/Texture3D.cs create mode 100644 UnityEngine/UnityEngine/TextureCompressionQuality.cs create mode 100644 UnityEngine/UnityEngine/TextureFormat.cs create mode 100644 UnityEngine/UnityEngine/TextureWrapMode.cs create mode 100644 UnityEngine/UnityEngine/ThreadPriority.cs create mode 100644 UnityEngine/UnityEngine/ThreadSafeAttribute.cs create mode 100644 UnityEngine/UnityEngine/Time.cs create mode 100644 UnityEngine/UnityEngine/TooltipAttribute.cs create mode 100644 UnityEngine/UnityEngine/Touch.cs create mode 100644 UnityEngine/UnityEngine/TouchPhase.cs create mode 100644 UnityEngine/UnityEngine/TouchScreenKeyboard.cs create mode 100644 UnityEngine/UnityEngine/TouchScreenKeyboardType.cs create mode 100644 UnityEngine/UnityEngine/TouchScreenKeyboard_InternalConstructorHelperArguments.cs create mode 100644 UnityEngine/UnityEngine/TrackedReference.cs create mode 100644 UnityEngine/UnityEngine/TrailRenderer.cs create mode 100644 UnityEngine/UnityEngine/Transform.cs create mode 100644 UnityEngine/UnityEngine/TransparencySortMode.cs create mode 100644 UnityEngine/UnityEngine/Tree.cs create mode 100644 UnityEngine/UnityEngine/TreeInstance.cs create mode 100644 UnityEngine/UnityEngine/TreePrototype.cs create mode 100644 UnityEngine/UnityEngine/Types.cs create mode 100644 UnityEngine/UnityEngine/UICharInfo.cs create mode 100644 UnityEngine/UnityEngine/UILineInfo.cs create mode 100644 UnityEngine/UnityEngine/UIVertex.cs create mode 100644 UnityEngine/UnityEngine/UnassignedReferenceException.cs create mode 100644 UnityEngine/UnityEngine/UnhandledExceptionHandler.cs create mode 100644 UnityEngine/UnityEngine/UnityException.cs create mode 100644 UnityEngine/UnityEngine/UnityLogWriter.cs create mode 100644 UnityEngine/UnityEngine/UnityString.cs create mode 100644 UnityEngine/UnityEngine/UserAuthorization.cs create mode 100644 UnityEngine/UnityEngine/UserAuthorizationDialog.cs create mode 100644 UnityEngine/UnityEngine/Vector2.cs create mode 100644 UnityEngine/UnityEngine/Vector3.cs create mode 100644 UnityEngine/UnityEngine/Vector4.cs create mode 100644 UnityEngine/UnityEngine/VerticalWrapMode.cs create mode 100644 UnityEngine/UnityEngine/WWW.cs create mode 100644 UnityEngine/UnityEngine/WWWForm.cs create mode 100644 UnityEngine/UnityEngine/WWWTranscoder.cs create mode 100644 UnityEngine/UnityEngine/WaitForEndOfFrame.cs create mode 100644 UnityEngine/UnityEngine/WaitForFixedUpdate.cs create mode 100644 UnityEngine/UnityEngine/WaitForSeconds.cs create mode 100644 UnityEngine/UnityEngine/WeakListenerBindings.cs create mode 100644 UnityEngine/UnityEngine/WebCamDevice.cs create mode 100644 UnityEngine/UnityEngine/WebCamFlags.cs create mode 100644 UnityEngine/UnityEngine/WebCamTexture.cs create mode 100644 UnityEngine/UnityEngine/WheelCollider.cs create mode 100644 UnityEngine/UnityEngine/WheelFrictionCurve.cs create mode 100644 UnityEngine/UnityEngine/WheelHit.cs create mode 100644 UnityEngine/UnityEngine/WheelJoint2D.cs create mode 100644 UnityEngine/UnityEngine/WindZone.cs create mode 100644 UnityEngine/UnityEngine/WindZoneMode.cs create mode 100644 UnityEngine/UnityEngine/WrapMode.cs create mode 100644 UnityEngine/UnityEngine/WrapperlessIcall.cs create mode 100644 UnityEngine/UnityEngine/WritableAttribute.cs create mode 100644 UnityEngine/UnityEngine/YieldInstruction.cs create mode 100644 UnityEngine/UnityEngine/_AndroidJNIHelper.cs create mode 100644 UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs create mode 100644 UnityEngine/UnityEngine/iPhone.cs create mode 100644 UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs create mode 100644 UnityEngine/UnityEngine/iPhoneGeneration.cs create mode 100644 UnityEngine/UnityEngine/iPhoneInput.cs create mode 100644 UnityEngine/UnityEngine/iPhoneKeyboard.cs create mode 100644 UnityEngine/UnityEngine/iPhoneKeyboardType.cs create mode 100644 UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs create mode 100644 UnityEngine/UnityEngine/iPhoneMovieControlMode.cs create mode 100644 UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs create mode 100644 UnityEngine/UnityEngine/iPhoneNetworkReachability.cs create mode 100644 UnityEngine/UnityEngine/iPhoneOrientation.cs create mode 100644 UnityEngine/UnityEngine/iPhoneScreenOrientation.cs create mode 100644 UnityEngine/UnityEngine/iPhoneSettings.cs create mode 100644 UnityEngine/UnityEngine/iPhoneTouch.cs create mode 100644 UnityEngine/UnityEngine/iPhoneTouchPhase.cs create mode 100644 UnityEngine/UnityEngine/iPhoneUtils.cs create mode 100644 UnityEngine/UnityEngine/jvalue.cs create mode 100644 UnityEngine/UnityEngineInternal/FastCallExceptionHandler.cs create mode 100644 UnityEngine/UnityEngineInternal/GenericStack.cs create mode 100644 UnityEngine/UnityEngineInternal/GetMethodDelegate.cs create mode 100644 UnityEngine/UnityEngineInternal/Reproduction.cs create mode 100644 UnityEngine/UnityEngineInternal/TypeInferenceRuleAttribute.cs create mode 100644 UnityEngine/UnityEngineInternal/TypeInferenceRules.cs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..461816a6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,23 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union +*.asset text + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f61f930b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.userprefs +*.suo +*bin/ +*obj/ +*Debug/ \ No newline at end of file diff --git a/README.md b/README.md index 94d356d5..ae4ba4e1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # UnityDecompiled An unofficial repo of decompiled Unity dll files +This version: 4.6.3f1 (other versions will be put in tags) + Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) Permission here: https://twitter.com/aras_p/status/568126504997138434 diff --git a/UnityDecompiled.sln b/UnityDecompiled.sln new file mode 100644 index 00000000..dc05cbf1 --- /dev/null +++ b/UnityDecompiled.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2013 +VisualStudioVersion = 12.0.31101.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnityEngine", "UnityEngine\UnityEngine.csproj", "{731BEF47-7B99-4BB3-86B7-595906204083}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnityEditor", "UnityEditor\UnityEditor.csproj", "{A273AAF0-2CB5-491E-9C0D-D66717004282}" + ProjectSection(ProjectDependencies) = postProject + {731BEF47-7B99-4BB3-86B7-595906204083} = {731BEF47-7B99-4BB3-86B7-595906204083} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {731BEF47-7B99-4BB3-86B7-595906204083}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {731BEF47-7B99-4BB3-86B7-595906204083}.Debug|Any CPU.Build.0 = Debug|Any CPU + {731BEF47-7B99-4BB3-86B7-595906204083}.Release|Any CPU.ActiveCfg = Release|Any CPU + {731BEF47-7B99-4BB3-86B7-595906204083}.Release|Any CPU.Build.0 = Release|Any CPU + {A273AAF0-2CB5-491E-9C0D-D66717004282}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A273AAF0-2CB5-491E-9C0D-D66717004282}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A273AAF0-2CB5-491E-9C0D-D66717004282}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A273AAF0-2CB5-491E-9C0D-D66717004282}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/UnityEditor/AssemblyValidation.cs b/UnityEditor/AssemblyValidation.cs new file mode 100644 index 00000000..d36c8ebd --- /dev/null +++ b/UnityEditor/AssemblyValidation.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using UnityEngine; +internal class AssemblyValidation +{ + private static Dictionary> _rulesByPlatform; + public static ValidationResult Validate(RuntimePlatform platform, IEnumerable userAssemblies, params object[] options) + { + AssemblyValidation.WarmUpRulesCache(); + string[] array = (userAssemblies as string[]) ?? userAssemblies.ToArray(); + if (array.Length != 0) + { + foreach (IValidationRule current in AssemblyValidation.ValidationRulesFor(platform, options)) + { + ValidationResult result = current.Validate(array, options); + if (!result.Success) + { + return result; + } + } + } + return new ValidationResult + { + Success = true + }; + } + private static void WarmUpRulesCache() + { + if (AssemblyValidation._rulesByPlatform != null) + { + return; + } + AssemblyValidation._rulesByPlatform = new Dictionary>(); + Assembly assembly = typeof(AssemblyValidation).Assembly; + foreach (Type current in assembly.GetTypes().Where(new Func(AssemblyValidation.IsValidationRule))) + { + AssemblyValidation.RegisterValidationRule(current); + } + } + private static bool IsValidationRule(Type type) + { + return AssemblyValidation.ValidationRuleAttributesFor(type).Any(); + } + private static IEnumerable ValidationRulesFor(RuntimePlatform platform, params object[] options) + { + return + from t in AssemblyValidation.ValidationRuleTypesFor(platform) + select AssemblyValidation.CreateValidationRuleWithOptions(t, options) into v + where v != null + select v; + } + [DebuggerHidden] + private static IEnumerable ValidationRuleTypesFor(RuntimePlatform platform) + { + AssemblyValidation.c__Iterator2 c__Iterator = new AssemblyValidation.c__Iterator2(); + c__Iterator.platform = platform; + c__Iterator.<$>platform = platform; + AssemblyValidation.c__Iterator2 expr_15 = c__Iterator; + expr_15.$PC = -2; + return expr_15; + } + private static IValidationRule CreateValidationRuleWithOptions(Type type, params object[] options) + { + List list = new List(options); + object[] array; + ConstructorInfo constructorInfo; + while (true) + { + array = list.ToArray(); + constructorInfo = AssemblyValidation.ConstructorFor(type, array); + if (constructorInfo != null) + { + break; + } + if (list.Count == 0) + { + goto Block_2; + } + list.RemoveAt(list.Count - 1); + } + return (IValidationRule)constructorInfo.Invoke(array); + Block_2: + return null; + } + private static ConstructorInfo ConstructorFor(Type type, IEnumerable options) + { + Type[] types = ( + from o in options + select o.GetType()).ToArray(); + return type.GetConstructor(types); + } + internal static void RegisterValidationRule(Type type) + { + foreach (AssemblyValidationRule current in AssemblyValidation.ValidationRuleAttributesFor(type)) + { + AssemblyValidation.RegisterValidationRuleForPlatform(current.Platform, type); + } + } + internal static void RegisterValidationRuleForPlatform(RuntimePlatform platform, Type type) + { + if (!AssemblyValidation._rulesByPlatform.ContainsKey(platform)) + { + AssemblyValidation._rulesByPlatform[platform] = new List(); + } + if (AssemblyValidation._rulesByPlatform[platform].IndexOf(type) == -1) + { + AssemblyValidation._rulesByPlatform[platform].Add(type); + } + AssemblyValidation._rulesByPlatform[platform].Sort((Type a, Type b) => AssemblyValidation.CompareValidationRulesByPriority(a, b, platform)); + } + internal static int CompareValidationRulesByPriority(Type a, Type b, RuntimePlatform platform) + { + int num = AssemblyValidation.PriorityFor(a, platform); + int num2 = AssemblyValidation.PriorityFor(b, platform); + if (num == num2) + { + return 0; + } + return (num >= num2) ? 1 : -1; + } + private static int PriorityFor(Type type, RuntimePlatform platform) + { + return ( + from attr in AssemblyValidation.ValidationRuleAttributesFor(type) + where attr.Platform == platform + select attr.Priority).FirstOrDefault(); + } + private static IEnumerable ValidationRuleAttributesFor(Type type) + { + return type.GetCustomAttributes(true).OfType(); + } +} diff --git a/UnityEditor/AssemblyValidationRule.cs b/UnityEditor/AssemblyValidationRule.cs new file mode 100644 index 00000000..a7dfc47d --- /dev/null +++ b/UnityEditor/AssemblyValidationRule.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] +internal class AssemblyValidationRule : Attribute +{ + public int Priority; + private readonly RuntimePlatform _platform; + public RuntimePlatform Platform + { + get + { + return this._platform; + } + } + public AssemblyValidationRule(RuntimePlatform platform) + { + this._platform = platform; + this.Priority = 0; + } +} diff --git a/UnityEditor/AssetModificationProcessor.cs b/UnityEditor/AssetModificationProcessor.cs new file mode 100644 index 00000000..6816acd2 --- /dev/null +++ b/UnityEditor/AssetModificationProcessor.cs @@ -0,0 +1,5 @@ +using System; +[Obsolete("Use UnityEditor.AssetModificationProcessor")] +public class AssetModificationProcessor +{ +} diff --git a/UnityEditor/ClangCompiler.cs b/UnityEditor/ClangCompiler.cs new file mode 100644 index 00000000..56361e21 --- /dev/null +++ b/UnityEditor/ClangCompiler.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +internal class ClangCompiler : NativeCompiler +{ + private readonly ICompilerSettings m_Settings; + protected override string objectFileExtension + { + get + { + return "o"; + } + } + public ClangCompiler(ICompilerSettings settings) + { + this.m_Settings = settings; + } + public override void CompileDynamicLibrary(string outFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths) + { + string[] array = sources.ToArray(); + string includeDirs = includePaths.Aggregate(string.Empty, (string current, string sourceDir) => current + "-I" + sourceDir + " "); + string text = NativeCompiler.Aggregate(libraries, "-force_load ", " "); + string text2 = NativeCompiler.Aggregate(libraryPaths.Union(this.m_Settings.LibPaths), "-L", " "); + NativeCompiler.ParallelFor(array, delegate(string file) + { + this.Compile(file, includeDirs); + }); + string arg_11A_1 = "ld"; + string[] expr_95 = new string[9]; + expr_95[0] = "-dylib"; + expr_95[1] = "-arch " + this.m_Settings.MachineSpecification; + expr_95[2] = "-macosx_version_min 10.6"; + expr_95[3] = "-lSystem"; + expr_95[4] = "-lstdc++"; + expr_95[5] = "-o " + outFile; + expr_95[6] = array.Select(new Func(base.ObjectFileFor)).Aggregate((string buff, string s) => buff + " " + s); + expr_95[7] = text2; + expr_95[8] = text; + base.ExecuteCommand(arg_11A_1, expr_95); + } + private void Compile(string file, string includePaths) + { + string arguments = string.Format(" -c -arch {0} -stdlib=libstdc++ -O0 -Wno-unused-value -Wno-invalid-offsetof -fvisibility=hidden -fno-rtti -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include {1} -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk -mmacosx-version-min=10.6 -single_module -compatibility_version 1 -current_version 1 {2} -o {3}", new object[] + { + this.m_Settings.MachineSpecification, + includePaths, + file, + base.ObjectFileFor(file) + }); + base.Execute(arguments, this.m_Settings.CompilerPath); + } + protected override void SetupProcessStartInfo(ProcessStartInfo startInfo) + { + } +} diff --git a/UnityEditor/ClangCompilerSettingsx86.cs b/UnityEditor/ClangCompilerSettingsx86.cs new file mode 100644 index 00000000..33e95cf0 --- /dev/null +++ b/UnityEditor/ClangCompilerSettingsx86.cs @@ -0,0 +1,32 @@ +using System; +internal class ClangCompilerSettingsx86 : ICompilerSettings +{ + public string CompilerPath + { + get + { + return "clang++"; + } + } + public string LinkerPath + { + get + { + return "ld"; + } + } + public string[] LibPaths + { + get + { + return new string[0]; + } + } + public string MachineSpecification + { + get + { + return "i386"; + } + } +} diff --git a/UnityEditor/DesktopStandalonePostProcessor.cs b/UnityEditor/DesktopStandalonePostProcessor.cs new file mode 100644 index 00000000..3c803262 --- /dev/null +++ b/UnityEditor/DesktopStandalonePostProcessor.cs @@ -0,0 +1,127 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEditor.Modules; +using UnityEditorInternal; +internal abstract class DesktopStandalonePostProcessor +{ + protected BuildPostProcessArgs m_PostProcessArgs; + protected abstract string StagingAreaPluginsFolder + { + get; + } + protected abstract string DestinationFolderForInstallingIntoBuildsFolder + { + get; + } + protected bool InstallingIntoBuildsFolder + { + get + { + return (this.m_PostProcessArgs.options & BuildOptions.InstallInBuildFolder) != BuildOptions.None; + } + } + protected bool UseIl2Cpp + { + get + { + return (this.m_PostProcessArgs.options & BuildOptions.Il2CPP) != BuildOptions.None; + } + } + protected string StagingArea + { + get + { + return this.m_PostProcessArgs.stagingArea; + } + } + protected string InstallPath + { + get + { + return this.m_PostProcessArgs.installPath; + } + } + protected string DataFolder + { + get + { + return this.StagingArea + "/Data"; + } + } + protected BuildTarget Target + { + get + { + return this.m_PostProcessArgs.target; + } + } + protected string DestinationFolder + { + get + { + return FileUtil.UnityGetDirectoryName(this.m_PostProcessArgs.installPath); + } + } + protected bool Development + { + get + { + return (this.m_PostProcessArgs.options & BuildOptions.Development) != BuildOptions.None; + } + } + protected DesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) + { + this.m_PostProcessArgs = postProcessArgs; + } + public void PostProcess() + { + this.SetupStagingArea(); + this.CopyStagingAreaIntoDestination(); + } + protected virtual void SetupStagingArea() + { + Directory.CreateDirectory(this.DataFolder); + PostprocessBuildPlayer.InstallPlugins(this.StagingAreaPluginsFolder, this.m_PostProcessArgs.target); + PostprocessBuildPlayer.InstallStreamingAssets(this.DataFolder); + if (this.UseIl2Cpp) + { + this.CopyVariationFolderIntoStagingArea(); + IL2CPPUtils.RunIl2Cpp(this.StagingArea + "/Data", this.GetPlatformProvider(this.m_PostProcessArgs.target), delegate(string s) + { + }, this.m_PostProcessArgs.usedClassRegistry); + } + if (this.InstallingIntoBuildsFolder) + { + return; + } + if (!this.UseIl2Cpp) + { + this.CopyVariationFolderIntoStagingArea(); + } + this.RenameFilesInStagingArea(); + } + protected virtual void CopyVariationFolderIntoStagingArea() + { + string source = this.m_PostProcessArgs.playerPackage + "/Variations/" + this.GetVariationName(); + FileUtil.CopyDirectoryFiltered(source, this.StagingArea, true, (string f) => !f.Contains("UnityEngine.mdb"), true); + } + protected void CopyStagingAreaIntoDestination() + { + if (this.InstallingIntoBuildsFolder) + { + FileUtil.CopyDirectoryFiltered(this.DataFolder, Unsupported.GetBaseUnityDeveloperFolder() + "/" + this.DestinationFolderForInstallingIntoBuildsFolder, true, (string f) => true, true); + return; + } + this.DeleteDestination(); + FileUtil.CopyDirectoryFiltered(this.StagingArea, this.DestinationFolder, true, (string f) => true, true); + } + protected abstract void DeleteDestination(); + protected virtual string GetVariationName() + { + return this.PlatformStringFor(this.m_PostProcessArgs.target) + "_" + (((this.m_PostProcessArgs.options & BuildOptions.Development) == BuildOptions.None) ? "nondevelopment" : "development"); + } + protected abstract string PlatformStringFor(BuildTarget target); + protected abstract void RenameFilesInStagingArea(); + protected abstract IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target); +} diff --git a/UnityEditor/FlashDotNetAPIValidationRule.cs b/UnityEditor/FlashDotNetAPIValidationRule.cs new file mode 100644 index 00000000..d4ded628 --- /dev/null +++ b/UnityEditor/FlashDotNetAPIValidationRule.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; +[AssemblyValidationRule(RuntimePlatform.FlashPlayer)] +internal class FlashDotNetAPIValidationRule : GendarmeValidationRule +{ + private readonly string _configFilePath; + private readonly FlashFileHelper _fileHelper; + private readonly FlashPostProcessSettings _settings; + public FlashDotNetAPIValidationRule(PostProcessFlashPlayerOptions options) : base(FlashFileHelper.CreateFrom(options).PathForGendarmeExe()) + { + this._fileHelper = FlashFileHelper.CreateFrom(options); + this._settings = FlashPostProcessSettings.CreateFrom(options); + this._configFilePath = Path.GetTempFileName(); + } + ~FlashDotNetAPIValidationRule() + { + File.Delete(this._configFilePath); + } + protected override GendarmeOptions ConfigureGendarme(IEnumerable userAssemblies) + { + string[] array = (userAssemblies as string[]) ?? userAssemblies.ToArray(); + if (array.Length != 0) + { + this.UpdateRulesTemplate(); + } + return new GendarmeOptions + { + ConfigFilePath = this._configFilePath, + RuleSet = "UnityFlash", + UserAssemblies = array + }; + } + private void UpdateRulesTemplate() + { + GendarmeXMLTemplateTags gendarmeXMLTemplateTags = new GendarmeXMLTemplateTags(); + gendarmeXMLTemplateTags.LimitToNamespaces.Add("System"); + gendarmeXMLTemplateTags.WhiteListFiles.Add(this._fileHelper.PathForFileInCil2As("gendarme-whitelist.txt")); + FlashDotNetAPIValidationRule.AddHardcodedWhiteListTypes(gendarmeXMLTemplateTags); + FlashTemplateWriterUtility.WriteGendarmeXMLTemplate(this._settings, this._fileHelper, gendarmeXMLTemplateTags, this._configFilePath); + } + private static void AddHardcodedWhiteListTypes(GendarmeXMLTemplateTags gendarmeXMLTemplateTags) + { + string[] collection = new string[] + { + "System.Array", + "System.Enum", + "System.RuntimeTypeHandle", + "System.IFormattable", + "System.ValueType", + "System.Delegate", + "System.MulticastDelegate", + "System.Runtime.Serialization.ISerializable", + "System.Runtime.Serialization.IDeserializationCallback", + "System.RuntimeFieldHandle", + "System.Runtime.CompilerServices.RuntimeHelpers", + "System.Math", + "System.Func", + "System.Func`1", + "System.Func`2", + "System.Func`3", + "System.Func`4", + "System.Action", + "System.Action`1", + "System.Action`2", + "System.Action`3", + "System.Action`4", + "System.Predicate`1", + "System.Runtime.InteropServices._Exception", + "System.Runtime.InteropServices._Attribute", + "System.Comparison`1", + "System.AsyncCallback", + "System.AttributeTargets", + "System.StringSplitOptions", + "System.EventHandler`1", + "System.EventHandler" + }; + gendarmeXMLTemplateTags.WhiteListTypes.AddRange(collection); + } +} diff --git a/UnityEditor/FlashFileHelper.cs b/UnityEditor/FlashFileHelper.cs new file mode 100644 index 00000000..09d00e48 --- /dev/null +++ b/UnityEditor/FlashFileHelper.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Scripting.Compilers; +internal class FlashFileHelper +{ + public string ProjectFolder + { + get; + private set; + } + public string InstallPath + { + get; + private set; + } + public string PlayerPackage + { + get; + private set; + } + public string StagingArea + { + get; + private set; + } + private FlashFileHelper(string stagingArea, string playerPackage, string installPath) + { + this.StagingArea = stagingArea; + this.PlayerPackage = playerPackage; + this.InstallPath = installPath; + this.ProjectFolder = Directory.GetCurrentDirectory(); + } + internal IEnumerable GetUserAssemblies() + { + return ( + from s in Directory.GetFiles(this.PathForManagedCode(), "*.dll") + where FlashFileHelper.IsUserCodeAssembly(Path.GetFileName(s)) + select s).ToArray(); + } + internal IEnumerable FindUserSwcs() + { + return this.FindActionScriptDirectoriesInProject().SelectMany((string dir) => Directory.GetFiles(dir, "*.swc", SearchOption.AllDirectories)); + } + internal IEnumerable FindUserSourcePaths() + { + return this.FindActionScriptDirectoriesInProject(); + } + private IEnumerable FindActionScriptDirectoriesInProject() + { + return Directory.GetDirectories(this.Combine(this.ProjectFolder, "Assets"), "ActionScript", SearchOption.AllDirectories); + } + internal string FullPathForUnityNativeSwc(string swcFileName) + { + return this.PrepareFileName(this.Combine(this.PlayerPackage, swcFileName)); + } + internal string GetInstallPath() + { + return this.PrepareFileName(this.InstallPath); + } + private string PathForManagedCode() + { + return this.Combine(this.StagingArea, "Managed"); + } + internal string ProjectName() + { + return Path.GetFileNameWithoutExtension(this.InstallPath); + } + internal void CopyResourcesFromPlayerPackageToStaging() + { + FileUtil.CopyFileOrDirectory(this.Combine(this.PlayerPackage, this.Combine("Resources", "unity default resources")), this.Combine(this.StagingArea, this.Combine("Resources", "unity default resources"))); + } + internal void SaveUnprocessedSwfCopy() + { + FileUtil.CopyFileOrDirectory(this.PathForTempSwf(), this.PathForTempSwf().Replace("temp.swf", "unprocessed.swf")); + } + internal string PathForFlexFrameworks() + { + return this.PathForFlex("frameworks"); + } + internal string PathForUnityEngineDLL() + { + return this.Combine(this.Combine(this.PlayerPackage, "Managed"), "UnityEngine.dll"); + } + internal string PathForConvertedDotNetCode() + { + return this.Combine(this.PathForAs3Code(), "ConvertedDotNetCode"); + } + internal string PathForFileInBuildTools(string file) + { + return this.Combine(this.PathForBuildTools(), file); + } + internal string PathForInstallationDir() + { + return Path.GetDirectoryName(this.InstallPath); + } + internal string PathForFileInInstallPath(string file) + { + return this.Combine(this.PathForInstallationDir(), file); + } + internal string PathForUserBuildAs3() + { + return this.Combine(this.PathForBuildTools(), "UserBuild_AS3"); + } + internal string PathForAs3Code() + { + return this.StagingArea; + } + internal string PathForAs3Src() + { + return this.Combine(this.PathForAs3Code(), "src"); + } + internal string PathForUnityAppDotAs() + { + return this.PrepareFileName(this.Combine(this.PathForUserBuildAs3(), "UnityApp.as")); + } + internal string PathForHtmlInInstallPath() + { + return this.PathForFileInInstallPath(this.ProjectName() + ".html"); + } + internal string PathForCil2AsExe() + { + return this.PathForFileInCil2As("cil2as.exe"); + } + public string PathForFileInCil2As(string file) + { + return this.Combine(this.Combine(this.PathForBuildTools(), "cil2as"), file); + } + internal string PathForGendarmeExe() + { + return this.PathForFileInGendarme("Gendarme.exe"); + } + public string PathForFileInGendarme(string path) + { + return this.Combine(this.Combine(this.PathForBuildTools(), "Gendarme"), path); + } + internal string PathForSwfPostProcessorExe() + { + return this.Combine(this.PathForBuildTools(), "SwfPostProcessor.exe"); + } + internal string PathForMxmlc() + { + return this.PathForFlex(this.Combine("lib", "mxmlc.jar")); + } + internal string PathForFlex(string relativePath) + { + return this.PrepareFileName(this.Combine(this.PathForFlexHome(), relativePath).Replace("\\", "/")); + } + internal string PathForFlexHome() + { + return this.Combine(this.PathForBuildTools(), "Flex"); + } + internal string PathForBuildTools() + { + return this.Combine(this.PlayerPackage, "BuildTools"); + } + internal string PathForTempSwfUnprepared() + { + return this.Combine(this.ProjectFolder, this.Combine(this.StagingArea, "temp.swf")); + } + internal string PathForTempSwf() + { + return this.PrepareFileName(this.PathForTempSwfUnprepared()); + } + internal string Combine(string path1, string path2) + { + return Path.Combine(path1, path2); + } + internal string PrepareFileName(string file) + { + return CommandLineFormatter.PrepareFileName(file); + } + internal static FlashFileHelper CreateWithBuildArguments(string stagingArea, string playerPackage, string installPath) + { + return new FlashFileHelper(stagingArea, playerPackage, installPath); + } + internal static bool IsUserCodeAssembly(string file) + { + return !file.StartsWith("mscorlib.dll") && !file.StartsWith("System.") && !file.StartsWith("Mono.") && !file.StartsWith("UnityEngine.") && !file.StartsWith("Boo.") && !file.StartsWith("UnityScript.") && !file.StartsWith("UnityEngine.UI"); + } + public static FlashFileHelper CreateFrom(PostProcessFlashPlayerOptions options) + { + return FlashFileHelper.CreateWithBuildArguments(options.StagingAreaData, options.PlayerPackage, options.InstallPath); + } +} diff --git a/UnityEditor/FlashPostProcessSettings.cs b/UnityEditor/FlashPostProcessSettings.cs new file mode 100644 index 00000000..d22154b0 --- /dev/null +++ b/UnityEditor/FlashPostProcessSettings.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +internal class FlashPostProcessSettings +{ + internal const string UnityFlashConstantNamespace = "UNITY_FLASH"; + public FlashBuildSubtarget FlashBuildSubtarget; + public bool IsDevelopment; + public bool StripPhysics; + public int Width; + public int Height; + internal string GetUnityNativeSwcForSubTarget(bool stripPhysics) + { + string str; + switch (this.FlashBuildSubtarget) + { + case FlashBuildSubtarget.Flash11dot2: + case FlashBuildSubtarget.Flash11dot3: + case FlashBuildSubtarget.Flash11dot4: + case FlashBuildSubtarget.Flash11dot5: + case FlashBuildSubtarget.Flash11dot6: + case FlashBuildSubtarget.Flash11dot7: + case FlashBuildSubtarget.Flash11dot8: + str = "UnityNative11dot2"; + break; + default: + str = "UnityNative11dot2"; + break; + } + if (this.StripPhysics) + { + str += "_nophysx"; + } + return str + ".swc"; + } + internal int GetSwfVersionForPlayerVersion() + { + switch (this.FlashBuildSubtarget) + { + case FlashBuildSubtarget.Flash11dot2: + return 15; + case FlashBuildSubtarget.Flash11dot3: + return 16; + case FlashBuildSubtarget.Flash11dot4: + return 17; + case FlashBuildSubtarget.Flash11dot5: + return 18; + case FlashBuildSubtarget.Flash11dot6: + return 19; + case FlashBuildSubtarget.Flash11dot7: + return 20; + case FlashBuildSubtarget.Flash11dot8: + return 21; + default: + return 15; + } + } + internal string GetTargetPlayerForSubtarget() + { + switch (this.FlashBuildSubtarget) + { + case FlashBuildSubtarget.Flash11dot2: + return "11.2.0"; + case FlashBuildSubtarget.Flash11dot3: + return "11.3.0"; + case FlashBuildSubtarget.Flash11dot4: + return "11.4.0"; + case FlashBuildSubtarget.Flash11dot5: + return "11.5.0"; + case FlashBuildSubtarget.Flash11dot6: + return "11.6.0"; + case FlashBuildSubtarget.Flash11dot7: + return "11.7.0"; + case FlashBuildSubtarget.Flash11dot8: + return "11.8.0"; + default: + return "11.2.0"; + } + } + internal string MxmlcCompileTimeConstants() + { + return FlashPostProcessSettings.CompileTimeConstantsFor(this).Aggregate(string.Empty, (string agg, KeyValuePair value) => agg + string.Format("-define+={0}::{1},{2} ", "UNITY_FLASH", value.Key, FlashPostProcessSettings.EncodeMxmlcConstant(value.Value))); + } + private static Dictionary CompileTimeConstantsFor(FlashPostProcessSettings settings) + { + Dictionary dictionary = new Dictionary + { + + { + "TargetFlashPlayerVersion", + settings.GetTargetPlayerForSubtarget() + }, + + { + "TargetSwfVersion", + settings.GetSwfVersionForPlayerVersion().ToString() + } + }; + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot2, "11dot2", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot3, "11dot3", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot4, "11dot4", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot5, "11dot5", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot6, "11dot6", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot7, "11dot7", dictionary); + FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot8, "11dot8", dictionary); + return dictionary; + } + private static void AddConfigDefineForFlashPlayerFeatureLevel(bool enabled, string level, IDictionary dict) + { + dict.Add(string.Format("PLAYERFEATURE_LEVEL_{0}", level), enabled); + } + private static string EncodeMxmlcConstant(object value) + { + if (value is string) + { + return string.Format("\"'{0}'\"", value); + } + return value.ToString().ToLower(); + } + public static FlashPostProcessSettings CreateWithBuildArguments(BuildOptions options, int width, int height) + { + return new FlashPostProcessSettings + { + Width = Math.Min(Math.Max(width, 1), 4096), + Height = Math.Min(Math.Max(height, 1), 4096), + StripPhysics = PlayerSettings.stripPhysics, + IsDevelopment = (options & BuildOptions.Development) != BuildOptions.None, + FlashBuildSubtarget = EditorUserBuildSettings.flashBuildSubtarget + }; + } + public static FlashPostProcessSettings CreateFrom(PostProcessFlashPlayerOptions options) + { + return FlashPostProcessSettings.CreateWithBuildArguments(options.Options, options.Width, options.Height); + } +} diff --git a/UnityEditor/FlashTemplateWriterUtility.cs b/UnityEditor/FlashTemplateWriterUtility.cs new file mode 100644 index 00000000..2b7d8556 --- /dev/null +++ b/UnityEditor/FlashTemplateWriterUtility.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +internal class FlashTemplateWriterUtility +{ + private readonly string _outputFile; + private readonly string _templateFile; + private readonly Dictionary _tagsToReplace; + public FlashTemplateWriterUtility(string templateFile, string outputFile, Dictionary tagsToReplace) + { + this._outputFile = outputFile; + this._tagsToReplace = tagsToReplace; + this._templateFile = templateFile; + } + public void WriteTemplate() + { + string seed = File.ReadAllText(this._templateFile); + string contents = this._tagsToReplace.Aggregate(seed, (string current, KeyValuePair kvp) => current.Replace("[%" + kvp.Key + "%]", kvp.Value)); + File.WriteAllText(this._outputFile, contents); + } + public static void WriteGendarmeXMLTemplate(FlashPostProcessSettings settings, FlashFileHelper fileHelper, GendarmeXMLTemplateTags gendarmeXMLTemplateTags, string output) + { + new FlashTemplateWriterUtility(fileHelper.PathForFileInGendarme("rules_template.xml"), output, gendarmeXMLTemplateTags.ToTagsDictionary()).WriteTemplate(); + } + public static void WriteHTMLTemplate(FlashPostProcessSettings settings, FlashFileHelper fileHelper) + { + new FlashTemplateWriterUtility(fileHelper.PathForFileInBuildTools("index.html"), fileHelper.PathForHtmlInInstallPath(), FlashTemplateWriterUtility.GetTagsToReplaceForHTML(settings, fileHelper)).WriteTemplate(); + } + private static Dictionary GetTagsToReplaceForHTML(FlashPostProcessSettings settings, FlashFileHelper fileHelper) + { + int num = settings.Height / 2; + return new Dictionary + { + + { + "hdimy", + num.ToString() + }, + + { + "dimx", + settings.Width.ToString() + }, + + { + "dimy", + settings.Height.ToString() + }, + + { + "swfname", + fileHelper.ProjectName() + ".swf" + }, + + { + "flashplayer_version", + settings.GetTargetPlayerForSubtarget() + } + }; + } +} diff --git a/UnityEditor/GendarmeOptions.cs b/UnityEditor/GendarmeOptions.cs new file mode 100644 index 00000000..a267da99 --- /dev/null +++ b/UnityEditor/GendarmeOptions.cs @@ -0,0 +1,7 @@ +using System; +internal struct GendarmeOptions +{ + public string RuleSet; + public string ConfigFilePath; + public string[] UserAssemblies; +} diff --git a/UnityEditor/GendarmeValidationRule.cs b/UnityEditor/GendarmeValidationRule.cs new file mode 100644 index 00000000..72e5d5fa --- /dev/null +++ b/UnityEditor/GendarmeValidationRule.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Scripting; +using UnityEditor.Scripting.Compilers; +using UnityEditor.Utils; +internal abstract class GendarmeValidationRule : IValidationRule +{ + private readonly string _gendarmeExePath; + protected GendarmeValidationRule(string gendarmeExePath) + { + this._gendarmeExePath = gendarmeExePath; + } + public ValidationResult Validate(IEnumerable userAssemblies, params object[] options) + { + string arguments = this.BuildGendarmeCommandLineArguments(userAssemblies); + ValidationResult validationResult = default(ValidationResult); + ValidationResult validationResult2 = validationResult; + validationResult2.Success = true; + validationResult2.Rule = this; + validationResult = validationResult2; + try + { + validationResult.Success = GendarmeValidationRule.StartManagedProgram(this._gendarmeExePath, arguments, new GendarmeOutputParser(), ref validationResult.CompilerMessages); + } + catch (Exception ex) + { + validationResult.Success = false; + validationResult.CompilerMessages = new CompilerMessage[] + { + new CompilerMessage + { + file = "Exception", + message = ex.Message + } + }; + } + return validationResult; + } + protected abstract GendarmeOptions ConfigureGendarme(IEnumerable userAssemblies); + protected string BuildGendarmeCommandLineArguments(IEnumerable userAssemblies) + { + GendarmeOptions gendarmeOptions = this.ConfigureGendarme(userAssemblies); + if (gendarmeOptions.UserAssemblies == null || gendarmeOptions.UserAssemblies.Length == 0) + { + return null; + } + List list = new List + { + "--config " + gendarmeOptions.ConfigFilePath, + "--set " + gendarmeOptions.RuleSet + }; + list.AddRange(gendarmeOptions.UserAssemblies); + return list.Aggregate((string agg, string i) => agg + " " + i); + } + private static bool StartManagedProgram(string exe, string arguments, CompilerOutputParserBase parser, ref IEnumerable compilerMessages) + { + using (ManagedProgram managedProgram = GendarmeValidationRule.ManagedProgramFor(exe, arguments)) + { + managedProgram.LogProcessStartInfo(); + try + { + managedProgram.Start(); + } + catch + { + throw new Exception("Could not start " + exe); + } + managedProgram.WaitForExit(); + if (managedProgram.ExitCode == 0) + { + return true; + } + compilerMessages = parser.Parse(managedProgram.GetErrorOutput(), managedProgram.GetStandardOutput(), true); + } + return false; + } + private static ManagedProgram ManagedProgramFor(string exe, string arguments) + { + return new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, arguments); + } +} diff --git a/UnityEditor/GendarmeXMLTemplateTags.cs b/UnityEditor/GendarmeXMLTemplateTags.cs new file mode 100644 index 00000000..971978d7 --- /dev/null +++ b/UnityEditor/GendarmeXMLTemplateTags.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +internal class GendarmeXMLTemplateTags +{ + public bool IncludePrimitiveTypes; + public bool AutomaticallyWhitelistAttributes; + public List WhiteListFiles = new List(); + public List BlackListFiles = new List(); + public List WhiteListAssemblies = new List(); + public List BlackListAssemblies = new List(); + public List LimitToNamespaces = new List(); + public List WhiteListTypes = new List(); + public GendarmeXMLTemplateTags() + { + this.IncludePrimitiveTypes = true; + this.AutomaticallyWhitelistAttributes = true; + } + public Dictionary ToTagsDictionary() + { + return new Dictionary + { + + { + "IncludePrimitiveTypes", + (!this.IncludePrimitiveTypes) ? "0" : "1" + }, + + { + "AutomaticallyWhitelistAttributes", + (!this.AutomaticallyWhitelistAttributes) ? "0" : "1" + }, + + { + "LimitToNamespaces", + this.AggregateIntoString(this.LimitToNamespaces) + }, + + { + "WhiteListTypes", + this.AggregateIntoString(this.WhiteListTypes) + }, + + { + "WhiteListFiles", + this.AggregateIntoString(this.WhiteListFiles) + }, + + { + "BlackListFiles", + this.AggregateIntoString(this.BlackListFiles) + }, + + { + "WhiteListAssemblies", + this.AggregateIntoString(this.WhiteListAssemblies) + }, + + { + "BlackListAssemblies", + this.AggregateIntoString(this.BlackListAssemblies) + } + }; + } + private string AggregateIntoString(IEnumerable list) + { + return list.DefaultIfEmpty().Aggregate(new Func(GendarmeXMLTemplateTags.ToCommaSeparatedString)); + } + private static string ToCommaSeparatedString(string agg, string s) + { + return agg + "," + s; + } +} diff --git a/UnityEditor/GenerateIconsWithMipLevels.cs b/UnityEditor/GenerateIconsWithMipLevels.cs new file mode 100644 index 00000000..f6bb1910 --- /dev/null +++ b/UnityEditor/GenerateIconsWithMipLevels.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +internal class GenerateIconsWithMipLevels +{ + private class InputData + { + public string sourceFolder; + public string targetFolder; + public string mipIdentifier; + public string mipFileExtension; + public List generatedFileNames = new List(); + public string GetMipFileName(string baseName, int mipResolution) + { + return string.Concat(new object[] + { + this.sourceFolder, + baseName, + this.mipIdentifier, + mipResolution, + ".", + this.mipFileExtension + }); + } + } + private static string k_IconSourceFolder = "Assets/MipLevels For Icons/"; + private static string k_IconTargetFolder = "Assets/Editor Default Resources/Icons/Generated"; + public static void GenerateAllIconsWithMipLevels() + { + GenerateIconsWithMipLevels.InputData inputData = new GenerateIconsWithMipLevels.InputData(); + inputData.sourceFolder = GenerateIconsWithMipLevels.k_IconSourceFolder; + inputData.targetFolder = GenerateIconsWithMipLevels.k_IconTargetFolder; + inputData.mipIdentifier = "@"; + inputData.mipFileExtension = "png"; + if (AssetDatabase.GetMainAssetInstanceID(inputData.targetFolder) != 0) + { + AssetDatabase.DeleteAsset(inputData.targetFolder); + AssetDatabase.Refresh(); + } + GenerateIconsWithMipLevels.EnsureFolderIsCreated(inputData.targetFolder); + float realtimeSinceStartup = Time.realtimeSinceStartup; + GenerateIconsWithMipLevels.GenerateIconsWithMips(inputData); + Debug.Log(string.Format("Generated {0} icons with mip levels in {1} seconds", inputData.generatedFileNames.Count, Time.realtimeSinceStartup - realtimeSinceStartup)); + GenerateIconsWithMipLevels.RemoveUnusedFiles(inputData.generatedFileNames); + AssetDatabase.Refresh(); + InternalEditorUtility.RepaintAllViews(); + } + public static void GenerateSelectedIconsWithMips() + { + if (Selection.activeInstanceID == 0) + { + Debug.Log("Ensure to select a mip texture..." + Selection.activeInstanceID); + return; + } + GenerateIconsWithMipLevels.InputData inputData = new GenerateIconsWithMipLevels.InputData(); + inputData.sourceFolder = GenerateIconsWithMipLevels.k_IconSourceFolder; + inputData.targetFolder = GenerateIconsWithMipLevels.k_IconTargetFolder; + inputData.mipIdentifier = "@"; + inputData.mipFileExtension = "png"; + int activeInstanceID = Selection.activeInstanceID; + string assetPath = AssetDatabase.GetAssetPath(activeInstanceID); + if (assetPath.IndexOf(inputData.sourceFolder) < 0) + { + Debug.Log("Selection is not a valid mip texture, it should be located in: " + inputData.sourceFolder); + return; + } + if (assetPath.IndexOf(inputData.mipIdentifier) < 0) + { + Debug.Log("Selection does not have a valid mip identifier " + assetPath + " " + inputData.mipIdentifier); + return; + } + float realtimeSinceStartup = Time.realtimeSinceStartup; + string text = assetPath.Replace(inputData.sourceFolder, string.Empty); + text = text.Substring(0, text.LastIndexOf(inputData.mipIdentifier)); + List iconAssetPaths = GenerateIconsWithMipLevels.GetIconAssetPaths(inputData.sourceFolder, inputData.mipIdentifier, inputData.mipFileExtension); + GenerateIconsWithMipLevels.EnsureFolderIsCreated(inputData.targetFolder); + GenerateIconsWithMipLevels.GenerateIcon(inputData, text, iconAssetPaths); + Debug.Log(string.Format("Generated {0} icon with mip levels in {1} seconds", text, Time.realtimeSinceStartup - realtimeSinceStartup)); + InternalEditorUtility.RepaintAllViews(); + } + private static void GenerateIconsWithMips(GenerateIconsWithMipLevels.InputData inputData) + { + List iconAssetPaths = GenerateIconsWithMipLevels.GetIconAssetPaths(inputData.sourceFolder, inputData.mipIdentifier, inputData.mipFileExtension); + if (iconAssetPaths.Count == 0) + { + Debug.LogWarning("No mip files found for generating icons! Searching in: " + inputData.sourceFolder + ", for files with extension: " + inputData.mipFileExtension); + } + string[] baseNames = GenerateIconsWithMipLevels.GetBaseNames(inputData, iconAssetPaths); + string[] array = baseNames; + for (int i = 0; i < array.Length; i++) + { + string baseName = array[i]; + GenerateIconsWithMipLevels.GenerateIcon(inputData, baseName, iconAssetPaths); + } + } + private static void GenerateIcon(GenerateIconsWithMipLevels.InputData inputData, string baseName, List assetPathsOfAllIcons) + { + Texture2D texture2D = GenerateIconsWithMipLevels.CreateIconWithMipLevels(inputData, baseName, assetPathsOfAllIcons); + if (texture2D == null) + { + Debug.Log("CreateIconWithMipLevels failed"); + return; + } + texture2D.name = baseName + " Icon.png"; + string text = inputData.targetFolder + "/" + baseName + " Icon.asset"; + GenerateIconsWithMipLevels.EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(text)); + AssetDatabase.CreateAsset(texture2D, text); + inputData.generatedFileNames.Add(text); + } + private static Texture2D CreateIconWithMipLevels(GenerateIconsWithMipLevels.InputData inputData, string baseName, List assetPathsOfAllIcons) + { + List list = assetPathsOfAllIcons.FindAll((string o) => o.IndexOf(baseName + inputData.mipIdentifier) >= 0); + List list2 = new List(); + foreach (string current in list) + { + Texture2D texture2D = GenerateIconsWithMipLevels.GetTexture2D(current); + if (texture2D != null) + { + list2.Add(texture2D); + } + else + { + Debug.LogError("Mip not found " + current); + } + } + int num = 99999; + int num2 = 0; + foreach (Texture2D current2 in list2) + { + int width = current2.width; + if (width > num2) + { + num2 = width; + } + if (width < num) + { + num = width; + } + } + if (num2 == 0) + { + return null; + } + Texture2D texture2D2 = new Texture2D(num2, num2, TextureFormat.ARGB32, true, true); + if (GenerateIconsWithMipLevels.BlitMip(texture2D2, inputData.GetMipFileName(baseName, num2), 0)) + { + texture2D2.Apply(true); + int num3 = num2; + for (int i = 1; i < texture2D2.mipmapCount; i++) + { + num3 /= 2; + if (num3 < num) + { + break; + } + GenerateIconsWithMipLevels.BlitMip(texture2D2, inputData.GetMipFileName(baseName, num3), i); + } + texture2D2.Apply(false, true); + return texture2D2; + } + return texture2D2; + } + private static bool BlitMip(Texture2D iconWithMips, string mipFile, int mipLevel) + { + Texture2D texture2D = GenerateIconsWithMipLevels.GetTexture2D(mipFile); + if (texture2D) + { + GenerateIconsWithMipLevels.Blit(texture2D, iconWithMips, mipLevel); + return true; + } + Debug.Log("Mip file NOT found: " + mipFile); + return false; + } + private static Texture2D GetTexture2D(string path) + { + return AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; + } + private static List GetIconAssetPaths(string folderPath, string mustHaveIdentifier, string extension) + { + string currentDirectory = Directory.GetCurrentDirectory(); + string text = Path.Combine(currentDirectory, folderPath); + Uri uri = new Uri(text); + List list = new List(Directory.GetFiles(text, "*." + extension, SearchOption.AllDirectories)); + list.RemoveAll((string o) => o.IndexOf(mustHaveIdentifier) < 0); + for (int i = 0; i < list.Count; i++) + { + Uri uri2 = new Uri(list[i]); + Uri uri3 = uri.MakeRelativeUri(uri2); + list[i] = folderPath + uri3.ToString(); + } + return list; + } + private static void Blit(Texture2D source, Texture2D dest, int mipLevel) + { + Color32[] pixels = source.GetPixels32(); + for (int i = 0; i < pixels.Length; i++) + { + Color32 color = pixels[i]; + if (color.a >= 3) + { + color.a -= 3; + } + pixels[i] = color; + } + dest.SetPixels32(pixels, mipLevel); + } + private static void EnsureFolderIsCreatedRecursively(string targetFolder) + { + if (AssetDatabase.GetMainAssetInstanceID(targetFolder) == 0) + { + GenerateIconsWithMipLevels.EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(targetFolder)); + Debug.Log("Created target folder " + targetFolder); + AssetDatabase.CreateFolder(Path.GetDirectoryName(targetFolder), Path.GetFileName(targetFolder)); + } + } + private static void EnsureFolderIsCreated(string targetFolder) + { + if (AssetDatabase.GetMainAssetInstanceID(targetFolder) == 0) + { + Debug.Log("Created target folder " + targetFolder); + AssetDatabase.CreateFolder(Path.GetDirectoryName(targetFolder), Path.GetFileName(targetFolder)); + } + } + private static void DeleteFile(string file) + { + if (AssetDatabase.GetMainAssetInstanceID(file) != 0) + { + Debug.Log("Deleted unused file: " + file); + AssetDatabase.DeleteAsset(file); + } + } + private static void RemoveUnusedFiles(List generatedFiles) + { + for (int i = 0; i < generatedFiles.Count; i++) + { + string text = generatedFiles[i].Replace("Icons/Generated", "Icons"); + text = text.Replace(".asset", ".png"); + GenerateIconsWithMipLevels.DeleteFile(text); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); + if (!fileNameWithoutExtension.StartsWith("d_")) + { + text = text.Replace(fileNameWithoutExtension, "d_" + fileNameWithoutExtension); + GenerateIconsWithMipLevels.DeleteFile(text); + } + } + AssetDatabase.Refresh(); + } + private static string[] GetBaseNames(GenerateIconsWithMipLevels.InputData inputData, List files) + { + string[] array = new string[files.Count]; + int length = inputData.sourceFolder.Length; + for (int i = 0; i < files.Count; i++) + { + array[i] = files[i].Substring(length, files[i].IndexOf(inputData.mipIdentifier) - length); + } + HashSet hashSet = new HashSet(array); + array = new string[hashSet.Count]; + hashSet.CopyTo(array); + return array; + } +} diff --git a/UnityEditor/ICompilerSettings.cs b/UnityEditor/ICompilerSettings.cs new file mode 100644 index 00000000..821f6696 --- /dev/null +++ b/UnityEditor/ICompilerSettings.cs @@ -0,0 +1,20 @@ +using System; +internal interface ICompilerSettings +{ + string[] LibPaths + { + get; + } + string CompilerPath + { + get; + } + string LinkerPath + { + get; + } + string MachineSpecification + { + get; + } +} diff --git a/UnityEditor/INativeCompiler.cs b/UnityEditor/INativeCompiler.cs new file mode 100644 index 00000000..3ddb26c3 --- /dev/null +++ b/UnityEditor/INativeCompiler.cs @@ -0,0 +1,6 @@ +using System; +using System.Collections.Generic; +internal interface INativeCompiler +{ + void CompileDynamicLibrary(string outFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths); +} diff --git a/UnityEditor/IValidationRule.cs b/UnityEditor/IValidationRule.cs new file mode 100644 index 00000000..5404cb91 --- /dev/null +++ b/UnityEditor/IValidationRule.cs @@ -0,0 +1,6 @@ +using System; +using System.Collections.Generic; +internal interface IValidationRule +{ + ValidationResult Validate(IEnumerable userAssemblies, params object[] options); +} diff --git a/UnityEditor/LinuxDesktopStandalonePostProcessor.cs b/UnityEditor/LinuxDesktopStandalonePostProcessor.cs new file mode 100644 index 00000000..bdc94d88 --- /dev/null +++ b/UnityEditor/LinuxDesktopStandalonePostProcessor.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.LinuxStandalone; +using UnityEditor.Modules; +using UnityEditorInternal; +internal class LinuxDesktopStandalonePostProcessor : DesktopStandalonePostProcessor +{ + protected override string StagingAreaPluginsFolder + { + get + { + string text = FileUtil.CombinePaths(new string[] + { + base.StagingArea, + "Data", + "Plugins" + }); + return (base.Target != BuildTarget.StandaloneLinuxUniversal) ? Path.Combine(text, this.ArchitecturePostFixFor(base.Target)) : text; + } + } + private bool Headless + { + get + { + return (this.m_PostProcessArgs.options & BuildOptions.EnableHeadlessMode) != BuildOptions.None; + } + } + private string FullDataFolderPath + { + get + { + return Path.Combine(base.DestinationFolder, Path.GetFileNameWithoutExtension(base.InstallPath) + "_Data"); + } + } + protected override string DestinationFolderForInstallingIntoBuildsFolder + { + get + { + throw new NotSupportedException(); + } + } + public LinuxDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) + { + } + private string ArchitecturePostFixFor(BuildTarget buildTarget) + { + return (buildTarget != BuildTarget.StandaloneLinux64) ? "x86" : "x86_64"; + } + protected override void CopyVariationFolderIntoStagingArea() + { + if (base.Target != BuildTarget.StandaloneLinuxUniversal) + { + base.CopyVariationFolderIntoStagingArea(); + return; + } + BuildTarget[] array = new BuildTarget[] + { + BuildTarget.StandaloneLinux, + BuildTarget.StandaloneLinux64 + }; + for (int i = 0; i < array.Length; i++) + { + BuildTarget buildTarget = array[i]; + string source = FileUtil.CombinePaths(new string[] + { + this.m_PostProcessArgs.playerPackage, + "Variations", + this.VariationNameFor(buildTarget) + }); + FileUtil.CopyDirectoryFiltered(source, base.StagingArea, true, (string f) => true, true); + this.RenameStagingAreaFile("LinuxPlayer", Path.ChangeExtension("LinuxPlayer", this.ArchitecturePostFixFor(buildTarget))); + } + } + protected override void RenameFilesInStagingArea() + { + this.RenameStagingAreaFile("Data", FileUtil.UnityGetFileNameWithoutExtension(base.InstallPath) + "_Data"); + if (base.Target != BuildTarget.StandaloneLinuxUniversal) + { + this.RenameStagingAreaFile("LinuxPlayer", FileUtil.UnityGetFileName(base.InstallPath)); + return; + } + foreach (string current in new BuildTarget[] + { + BuildTarget.StandaloneLinux, + BuildTarget.StandaloneLinux64 + }.Select(new Func(this.ArchitecturePostFixFor))) + { + this.RenameStagingAreaFile(Path.ChangeExtension("LinuxPlayer", current), Path.ChangeExtension(FileUtil.UnityGetFileName(base.InstallPath), current)); + } + } + private void RenameStagingAreaFile(string from, string to) + { + FileUtil.MoveFileOrDirectory(Path.Combine(base.StagingArea, from), Path.Combine(base.StagingArea, to)); + } + protected override string GetVariationName() + { + return this.VariationNameFor(base.Target); + } + private string VariationNameFor(BuildTarget target) + { + return string.Format("{0}_{1}_{2}", this.PlatformStringFor(target), (!this.Headless) ? "withgfx" : "headless", (!base.Development) ? "nondevelopment" : "development"); + } + protected override void DeleteDestination() + { + FileUtil.DeleteFileOrDirectory(Path.ChangeExtension(base.InstallPath, this.ArchitecturePostFixFor(BuildTarget.StandaloneLinux))); + FileUtil.DeleteFileOrDirectory(Path.ChangeExtension(base.InstallPath, this.ArchitecturePostFixFor(BuildTarget.StandaloneLinux64))); + FileUtil.DeleteFileOrDirectory(this.FullDataFolderPath); + } + protected override string PlatformStringFor(BuildTarget target) + { + if (target == BuildTarget.StandaloneLinux64) + { + return "linux64"; + } + if (target == BuildTarget.StandaloneLinuxUniversal) + { + return "universal"; + } + if (target != BuildTarget.StandaloneLinux) + { + throw new ArgumentException("Unexpected target: " + target); + } + return "linux32"; + } + protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) + { + return new LinuxStandaloneIl2CppPlatformProvider(target, base.DataFolder); + } +} diff --git a/UnityEditor/MSVCCompiler.cs b/UnityEditor/MSVCCompiler.cs new file mode 100644 index 00000000..f0571fe8 --- /dev/null +++ b/UnityEditor/MSVCCompiler.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +internal class MSVCCompiler : NativeCompiler +{ + private readonly ICompilerSettings m_Settings; + private readonly string m_CompilerOptions = "/bigobj /Od /Zi /MTd /MP /EHsc /D_SECURE_SCL=0 /D_HAS_ITERATOR_DEBUGGING=0"; + private readonly string m_DefFile; + private readonly string[] m_IncludePaths = new string[] + { + "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\vc\\include", + "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Include" + }; + private readonly string[] m_Libraries = new string[] + { + "user32.lib", + "advapi32.lib", + "ole32.lib", + "ws2_32.lib" + }; + protected override string objectFileExtension + { + get + { + return "obj"; + } + } + public MSVCCompiler(ICompilerSettings settings, string defFile) + { + this.m_Settings = settings; + this.m_DefFile = defFile; + } + public override void CompileDynamicLibrary(string outputFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths) + { + string[] array = sources.ToArray(); + string text = NativeCompiler.Aggregate(array.Select(new Func(base.ObjectFileFor)), " ", " " + Environment.NewLine); + string includePathsString = NativeCompiler.Aggregate(includePaths.Union(this.m_IncludePaths), "/I \"", "\" "); + string text2 = NativeCompiler.Aggregate(libraries.Union(this.m_Libraries), " ", " "); + string text3 = NativeCompiler.Aggregate(libraryPaths.Union(this.m_Settings.LibPaths), "/LIBPATH:\"", "\" "); + this.GenerateEmptyPdbFile(outputFile); + NativeCompiler.ParallelFor(array, delegate(string file) + { + this.Compile(file, includePathsString); + }); + string contents = string.Format(" {0} {1} {2} /DEBUG /INCREMENTAL:NO /MACHINE:{4} /DLL /out:\"{3}\" /DEF:\"{5}\" ", new object[] + { + text, + text2, + text3, + outputFile, + this.m_Settings.MachineSpecification, + this.m_DefFile + }); + string tempFileName = Path.GetTempFileName(); + File.WriteAllText(tempFileName, contents); + base.Execute(string.Format("@{0}", tempFileName), "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\bin\\link.exe"); + } + private void GenerateEmptyPdbFile(string outputFile) + { + string tempFileName = Path.GetTempFileName(); + File.WriteAllText(tempFileName, " /* **** */"); + string fullPath = Path.GetFullPath(Path.GetDirectoryName(outputFile)); + string arg = Path.Combine(fullPath, Path.GetFileNameWithoutExtension(outputFile) + ".pdb"); + Directory.CreateDirectory(fullPath); + string arg2 = string.Format(" -c /Tp {0} /Zi /Fd\"{1}\"", tempFileName, arg); + base.Execute(string.Format("{0}", arg2), this.m_Settings.CompilerPath); + } + private void Compile(string file, string includePaths) + { + string arg = string.Format(" /c {0} {1} {2} /Fo{3}\\ ", new object[] + { + this.m_CompilerOptions, + file, + includePaths, + Path.GetDirectoryName(file) + }); + base.Execute(string.Format("{0}", arg), this.m_Settings.CompilerPath); + } + protected override void SetupProcessStartInfo(ProcessStartInfo startInfo) + { + startInfo.CreateNoWindow = true; + if (!startInfo.EnvironmentVariables.ContainsKey("PATH")) + { + startInfo.EnvironmentVariables.Add("PATH", "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE"); + } + else + { + string text = startInfo.EnvironmentVariables["PATH"]; + text = "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE" + Path.PathSeparator + text; + startInfo.EnvironmentVariables["PATH"] = text; + } + } +} diff --git a/UnityEditor/MSVCCompilerSettingsx64.cs b/UnityEditor/MSVCCompilerSettingsx64.cs new file mode 100644 index 00000000..375d898b --- /dev/null +++ b/UnityEditor/MSVCCompilerSettingsx64.cs @@ -0,0 +1,49 @@ +using System; +internal class MSVCCompilerSettingsx64 : ICompilerSettings +{ + private readonly string m_CompilerPath; + private readonly string m_LinkerPath; + private readonly string[] m_LibPaths; + public string CompilerPath + { + get + { + return this.m_CompilerPath; + } + } + public string LinkerPath + { + get + { + return this.m_LinkerPath; + } + } + public string[] LibPaths + { + get + { + return this.m_LibPaths; + } + } + public string MachineSpecification + { + get + { + return "X64"; + } + } + public MSVCCompilerSettingsx64() + { + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("VS100COMNTOOLS"))) + { + throw new Exception("Environment variable 'VS100COMNTOOLS' is not set indicating Visual Studio is not properly installed."); + } + this.m_CompilerPath = Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\bin\\amd64\\cl.exe"); + this.m_LinkerPath = Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\bin\\amd64\\link.exe"); + this.m_LibPaths = new string[] + { + Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\lib\\amd64"), + "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Lib\\x64" + }; + } +} diff --git a/UnityEditor/MSVCCompilerSettingsx86.cs b/UnityEditor/MSVCCompilerSettingsx86.cs new file mode 100644 index 00000000..74f7cf3c --- /dev/null +++ b/UnityEditor/MSVCCompilerSettingsx86.cs @@ -0,0 +1,49 @@ +using System; +internal class MSVCCompilerSettingsx86 : ICompilerSettings +{ + private readonly string m_CompilerPath; + private readonly string m_LinkerPath; + private readonly string[] m_LibPaths; + public string CompilerPath + { + get + { + return this.m_CompilerPath; + } + } + public string LinkerPath + { + get + { + return this.m_LinkerPath; + } + } + public string[] LibPaths + { + get + { + return this.m_LibPaths; + } + } + public string MachineSpecification + { + get + { + return "X86"; + } + } + public MSVCCompilerSettingsx86() + { + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("VS100COMNTOOLS"))) + { + throw new Exception("Environment variable 'VS100COMNTOOLS' is not set indicating Visual Studio is not properly installed."); + } + this.m_CompilerPath = Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\bin\\cl.exe"); + this.m_LinkerPath = Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\bin\\link.exe"); + this.m_LibPaths = new string[] + { + Environment.ExpandEnvironmentVariables("%VS100COMNTOOLS%..\\..\\VC\\lib"), + "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Lib" + }; + } +} diff --git a/UnityEditor/MxmlcHelper.cs b/UnityEditor/MxmlcHelper.cs new file mode 100644 index 00000000..429ce795 --- /dev/null +++ b/UnityEditor/MxmlcHelper.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnityEditor.Scripting.Compilers; +internal class MxmlcHelper +{ + internal static string[] MxmlcArgumentsFor(FlashPostProcessSettings settings, FlashFileHelper fileHelper) + { + string text = fileHelper.FindUserSwcs().Aggregate(string.Empty, (string current, string includeLib) => current + " -include-libraries=" + fileHelper.PrepareFileName(includeLib)); + string text2 = "-debug=" + ((!settings.IsDevelopment) ? "false" : "true"); + string text3 = "-optimize=" + ((!settings.IsDevelopment) ? "true" : "false"); + string text4 = string.Concat(new object[] + { + "-default-size ", + settings.Width, + " ", + settings.Height + }); + return new string[] + { + "-Xmx768m -Dsun.io.useCanonCaches=false -Duser.region=US -Duser.language=en", + "-jar " + fileHelper.PathForMxmlc(), + "+flexlib=" + fileHelper.PathForFlexFrameworks(), + fileHelper.PathForUnityAppDotAs(), + text2, + text3, + "-include-libraries=" + fileHelper.FullPathForUnityNativeSwc(settings.GetUnityNativeSwcForSubTarget(settings.StripPhysics)), + text, + MxmlcHelper.AllSourcePaths(fileHelper), + "-static-link-runtime-shared-libraries=true", + "-swf-version=" + settings.GetSwfVersionForPlayerVersion(), + text4, + "-omit-trace-statements=false", + "-default-script-limits=1000,60", + "-target-player=" + settings.GetTargetPlayerForSubtarget(), + "-verbose-stacktraces=true", + "-compress=false", + settings.MxmlcCompileTimeConstants(), + "-output=" + fileHelper.PathForTempSwf() + }; + } + internal static string AllSourcePaths(FlashFileHelper fileHelper) + { + IEnumerable paths = new string[] + { + fileHelper.PathForAs3Src(), + fileHelper.PathForConvertedDotNetCode(), + fileHelper.PathForUserBuildAs3() + }.Concat(fileHelper.FindUserSourcePaths()); + return MxmlcHelper.FormatSourcePathsForCmdline(paths); + } + private static string FormatSourcePathsForCmdline(IEnumerable paths) + { + StringBuilder stringBuilder = new StringBuilder(); + bool flag = true; + foreach (string current in paths) + { + if (!flag) + { + stringBuilder.Append(" "); + } + stringBuilder.Append("-source-path="); + stringBuilder.Append(CommandLineFormatter.PrepareFileName(current)); + flag = false; + } + return stringBuilder.ToString(); + } +} diff --git a/UnityEditor/NUnitFrameworkUser.cs b/UnityEditor/NUnitFrameworkUser.cs new file mode 100644 index 00000000..cb86ec30 --- /dev/null +++ b/UnityEditor/NUnitFrameworkUser.cs @@ -0,0 +1,9 @@ +using NUnit.Framework; +using System; +internal class NUnitFrameworkUser +{ + private void Useit() + { + Assert.AreEqual(1, 1); + } +} diff --git a/UnityEditor/NativeCompiler.cs b/UnityEditor/NativeCompiler.cs new file mode 100644 index 00000000..56437cba --- /dev/null +++ b/UnityEditor/NativeCompiler.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using UnityEditor.Utils; +using UnityEngine; +internal abstract class NativeCompiler : INativeCompiler +{ + private class Counter + { + public int index; + } + protected virtual string objectFileExtension + { + get + { + return "o"; + } + } + public abstract void CompileDynamicLibrary(string outFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths); + protected virtual void SetupProcessStartInfo(ProcessStartInfo startInfo) + { + } + protected void Execute(string arguments, string compilerPath) + { + ProcessStartInfo startInfo = new ProcessStartInfo(compilerPath, arguments); + this.SetupProcessStartInfo(startInfo); + this.RunProgram(startInfo); + } + protected void ExecuteCommand(string command, params string[] arguments) + { + ProcessStartInfo startInfo = new ProcessStartInfo(command, arguments.Aggregate((string buff, string s) => buff + " " + s)); + this.SetupProcessStartInfo(startInfo); + this.RunProgram(startInfo); + } + private void RunProgram(ProcessStartInfo startInfo) + { + using (Program program = new Program(startInfo)) + { + program.Start(); + while (!program.WaitForExit(100)) + { + } + string text = string.Empty; + string[] standardOutput = program.GetStandardOutput(); + if (standardOutput.Length > 0) + { + text = standardOutput.Aggregate((string buf, string s) => buf + Environment.NewLine + s); + } + string[] errorOutput = program.GetErrorOutput(); + if (errorOutput.Length > 0) + { + text += errorOutput.Aggregate((string buf, string s) => buf + Environment.NewLine + s); + } + if (program.ExitCode != 0) + { + UnityEngine.Debug.LogError(string.Concat(new string[] + { + "Failed running ", + startInfo.FileName, + " ", + startInfo.Arguments, + "\n\n", + text + })); + throw new Exception("IL2CPP compile failed."); + } + } + } + protected static string Aggregate(IEnumerable items, string prefix, string suffix) + { + return items.Aggregate(string.Empty, (string current, string additionalFile) => current + prefix + additionalFile + suffix); + } + internal static void ParallelFor(T[] sources, Action action) + { + Thread[] array = new Thread[Environment.ProcessorCount]; + NativeCompiler.Counter parameter = new NativeCompiler.Counter(); + for (int i = 0; i < array.Length; i++) + { + array[i] = new Thread(delegate(object obj) + { + NativeCompiler.Counter counter = (NativeCompiler.Counter)obj; + int num; + while ((num = Interlocked.Increment(ref counter.index)) <= sources.Length) + { + action(sources[num - 1]); + } + }); + } + Thread[] array2 = array; + for (int j = 0; j < array2.Length; j++) + { + Thread thread = array2[j]; + thread.Start(parameter); + } + Thread[] array3 = array; + for (int k = 0; k < array3.Length; k++) + { + Thread thread2 = array3[k]; + thread2.Join(); + } + } + protected internal static IEnumerable AllSourceFilesIn(string directory) + { + return Directory.GetFiles(directory, "*.cpp", SearchOption.AllDirectories).Concat(Directory.GetFiles(directory, "*.c", SearchOption.AllDirectories)); + } + protected internal static bool IsSourceFile(string source) + { + string extension = Path.GetExtension(source); + return extension == "cpp" || extension == "c"; + } + protected string ObjectFileFor(string source) + { + return Path.ChangeExtension(source, this.objectFileExtension); + } +} diff --git a/UnityEditor/OSXDesktopStandalonePostProcessor.cs b/UnityEditor/OSXDesktopStandalonePostProcessor.cs new file mode 100644 index 00000000..bc475b1d --- /dev/null +++ b/UnityEditor/OSXDesktopStandalonePostProcessor.cs @@ -0,0 +1,111 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEditor.Modules; +using UnityEditor.OSXStandalone; +using UnityEditorInternal; +internal class OSXDesktopStandalonePostProcessor : DesktopStandalonePostProcessor +{ + private string StagingAreaContents + { + get + { + return base.StagingArea + "/UnityPlayer.app/Contents"; + } + } + protected override string DestinationFolderForInstallingIntoBuildsFolder + { + get + { + return "build/MacStandaloneSupport/Variations/macosx32_development/UnityPlayer.app/Contents/Data"; + } + } + protected override string StagingAreaPluginsFolder + { + get + { + return this.StagingAreaContents + "/Plugins"; + } + } + private string InstallNameWithoutExtension + { + get + { + return FileUtil.UnityGetFileNameWithoutExtension(this.m_PostProcessArgs.installPath); + } + } + public OSXDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) + { + } + protected override void RenameFilesInStagingArea() + { + File.Move(this.StagingAreaContents + "/MacOS/UnityPlayer", this.StagingAreaContents + "/MacOS/" + this.InstallNameWithoutExtension); + FileUtil.CopyDirectoryFiltered(base.StagingArea + "/Data", this.StagingAreaContents + "/Data", true, (string f) => true, true); + FileUtil.DeleteFileOrDirectory(base.StagingArea + "/Data"); + if (base.UseIl2Cpp) + { + FileUtil.DeleteFileOrDirectory(this.StagingAreaContents + "/Resources/Data/Managed"); + FileUtil.DeleteFileOrDirectory(this.StagingAreaContents + "/Resources/Data/il2cppOutput"); + } + string text = PostprocessBuildPlayer.GenerateBundleIdentifier(this.m_PostProcessArgs.companyName, this.m_PostProcessArgs.productName); + FileUtil.ReplaceText(this.StagingAreaContents + "/Info.plist", new string[] + { + "UNITY_BUNDLE_IDENTIFIER", + text, + "UnityPlayer", + this.InstallNameWithoutExtension + }); + string to = base.StagingArea + "/" + this.InstallNameWithoutExtension + ".app"; + FileUtil.MoveFileOrDirectory(base.StagingArea + "/UnityPlayer.app", to); + } + protected override void DeleteDestination() + { + FileUtil.DeleteFileOrDirectory(this.m_PostProcessArgs.installPath); + } + protected override string GetVariationName() + { + string arg = "mono"; + if (base.UseIl2Cpp) + { + arg = "il2cpp"; + } + return string.Format("{0}_{1}", base.GetVariationName(), arg); + } + protected override string PlatformStringFor(BuildTarget target) + { + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + return "universal"; + case (BuildTarget)3: + IL_16: + if (target != BuildTarget.StandaloneOSXIntel64) + { + throw new ArgumentException("Unexpected target: " + target); + } + return "macosx64"; + case BuildTarget.StandaloneOSXIntel: + return "macosx32"; + } + goto IL_16; + } + protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) + { + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + goto IL_23; + case (BuildTarget)3: + IL_16: + if (target != BuildTarget.StandaloneOSXIntel64) + { + throw new Exception("Build target not supported."); + } + goto IL_23; + } + goto IL_16; + IL_23: + return new OSXStandaloneIl2CppPlatformProvider(target, this.StagingAreaContents + "/Data", base.Development); + } +} diff --git a/UnityEditor/ParticleSystemCurveEditor.cs b/UnityEditor/ParticleSystemCurveEditor.cs new file mode 100644 index 00000000..318b1b17 --- /dev/null +++ b/UnityEditor/ParticleSystemCurveEditor.cs @@ -0,0 +1,684 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +internal class ParticleSystemCurveEditor +{ + internal class Styles + { + public GUIStyle curveEditorBackground = "AnimationCurveEditorBackground"; + public GUIStyle curveSwatch = "PopupCurveEditorSwatch"; + public GUIStyle curveSwatchArea = "PopupCurveSwatchBackground"; + public GUIStyle minus = "OL Minus"; + public GUIStyle plus = "OL Plus"; + public GUIStyle yAxisHeader = new GUIStyle(ParticleSystemStyles.Get().label); + public GUIContent optimizeCurveText = new GUIContent(string.Empty, "Click to optimize curve. Optimized curves are defined by having at most 3 keys, with a key at both ends"); + public GUIContent removeCurveText = new GUIContent(string.Empty, "Remove selected curve(s)"); + public GUIContent curveLibraryPopup = new GUIContent(string.Empty, "Open curve library"); + public GUIContent presetTooltip = new GUIContent(); + } + public class CurveData + { + public SerializedProperty m_Max; + public SerializedProperty m_Min; + public bool m_SignedRange; + public Color m_Color; + public string m_UniqueName; + public GUIContent m_DisplayName; + public CurveWrapper.GetAxisScalarsCallback m_GetAxisScalarsCallback; + public CurveWrapper.SetAxisScalarsCallback m_SetAxisScalarsCallback; + public int m_MaxId; + public int m_MinId; + public bool m_Visible; + private static int s_IdCounter; + public CurveData(string name, GUIContent displayName, SerializedProperty min, SerializedProperty max, Color color, bool signedRange, CurveWrapper.GetAxisScalarsCallback getAxisScalars, CurveWrapper.SetAxisScalarsCallback setAxisScalars, bool visible) + { + this.m_UniqueName = name; + this.m_DisplayName = displayName; + this.m_SignedRange = signedRange; + this.m_Min = min; + this.m_Max = max; + if (this.m_Min != null) + { + this.m_MinId = ++ParticleSystemCurveEditor.CurveData.s_IdCounter; + } + if (this.m_Max != null) + { + this.m_MaxId = ++ParticleSystemCurveEditor.CurveData.s_IdCounter; + } + this.m_Color = color; + this.m_GetAxisScalarsCallback = getAxisScalars; + this.m_SetAxisScalarsCallback = setAxisScalars; + this.m_Visible = visible; + if (this.m_Max == null || this.m_MaxId == 0) + { + Debug.LogError("Max curve should always be valid! (Min curve can be null)"); + } + } + public bool IsRegion() + { + return this.m_Min != null; + } + } + public const float k_PresetsHeight = 30f; + private List m_AddedCurves; + private CurveEditor m_CurveEditor; + private static CurveEditorSettings m_CurveEditorSettings = new CurveEditorSettings(); + private Color[] m_Colors; + private List m_AvailableColors; + private DoubleCurvePresetsContentsForPopupWindow m_DoubleCurvePresets; + internal static ParticleSystemCurveEditor.Styles s_Styles; + private int m_LastTopMostCurveID = -1; + public void OnDisable() + { + this.m_CurveEditor.OnDisable(); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public void OnDestroy() + { + this.m_DoubleCurvePresets.GetPresetLibraryEditor().UnloadUsedLibraries(); + } + public void Refresh() + { + this.ContentChanged(); + AnimationCurvePreviewCache.ClearCache(); + } + public void Init() + { + if (this.m_AddedCurves != null) + { + return; + } + this.m_AddedCurves = new List(); + this.m_Colors = new Color[] + { + new Color(1f, 0.619607866f, 0.129411772f), + new Color(0.8745098f, 0.211764708f, 0.5803922f), + new Color(0f, 0.6862745f, 1f), + new Color(1f, 0.921568632f, 0f), + new Color(0.196078435f, 1f, 0.266666681f), + new Color(0.980392158f, 0f, 0f) + }; + this.m_AvailableColors = new List(this.m_Colors); + ParticleSystemCurveEditor.m_CurveEditorSettings.useFocusColors = true; + ParticleSystemCurveEditor.m_CurveEditorSettings.showAxisLabels = false; + ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMin = 0f; + ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMin = 0f; + ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMax = 1f; + ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMax = 1f; + ParticleSystemCurveEditor.m_CurveEditorSettings.vSlider = false; + ParticleSystemCurveEditor.m_CurveEditorSettings.hSlider = false; + ParticleSystemCurveEditor.m_CurveEditorSettings.wrapColor = new Color(0f, 0f, 0f, 0f); + ParticleSystemCurveEditor.m_CurveEditorSettings.hTickLabelOffset = 5f; + ParticleSystemCurveEditor.m_CurveEditorSettings.allowDraggingCurvesAndRegions = true; + ParticleSystemCurveEditor.m_CurveEditorSettings.allowDeleteLastKeyInCurve = false; + TickStyle tickStyle = new TickStyle(); + tickStyle.color = new Color(0f, 0f, 0f, 0.2f); + tickStyle.distLabel = 30; + tickStyle.stubs = false; + tickStyle.centerLabel = true; + ParticleSystemCurveEditor.m_CurveEditorSettings.hTickStyle = tickStyle; + TickStyle tickStyle2 = new TickStyle(); + tickStyle2.color = new Color(0f, 0f, 0f, 0.2f); + tickStyle2.distLabel = 20; + tickStyle2.stubs = false; + tickStyle2.centerLabel = true; + ParticleSystemCurveEditor.m_CurveEditorSettings.vTickStyle = tickStyle2; + this.m_CurveEditor = new CurveEditor(new Rect(0f, 0f, 1000f, 100f), this.CreateCurveWrapperArray(), false); + this.m_CurveEditor.settings = ParticleSystemCurveEditor.m_CurveEditorSettings; + this.m_CurveEditor.leftmargin = 40f; + ZoomableArea arg_2A2_0 = this.m_CurveEditor; + float num = 25f; + this.m_CurveEditor.bottommargin = num; + num = num; + this.m_CurveEditor.topmargin = num; + arg_2A2_0.rightmargin = num; + this.m_CurveEditor.SetShownHRangeInsideMargins(ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMin, ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMax); + this.m_CurveEditor.SetShownVRangeInsideMargins(ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMin, ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMax); + this.m_CurveEditor.ignoreScrollWheelUntilClicked = false; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + private void UndoRedoPerformed() + { + this.ContentChanged(); + } + private void UpdateRangeBasedOnShownCurves() + { + bool flag = false; + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + flag |= this.m_AddedCurves[i].m_SignedRange; + } + float num = (!flag) ? 0f : -1f; + if (num != ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMin) + { + ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMin = num; + this.m_CurveEditor.settings = ParticleSystemCurveEditor.m_CurveEditorSettings; + this.m_CurveEditor.SetShownVRangeInsideMargins(ParticleSystemCurveEditor.m_CurveEditorSettings.vRangeMin, ParticleSystemCurveEditor.m_CurveEditorSettings.hRangeMax); + } + } + public bool IsAdded(SerializedProperty min, SerializedProperty max) + { + return this.FindIndex(min, max) != -1; + } + public bool IsAdded(SerializedProperty max) + { + return this.FindIndex(null, max) != -1; + } + public void AddCurve(ParticleSystemCurveEditor.CurveData curveData) + { + this.Add(curveData); + } + public void RemoveCurve(SerializedProperty max) + { + this.RemoveCurve(null, max); + } + public void RemoveCurve(SerializedProperty min, SerializedProperty max) + { + if (this.Remove(this.FindIndex(min, max))) + { + this.ContentChanged(); + this.UpdateRangeBasedOnShownCurves(); + } + } + public Color GetCurveColor(SerializedProperty max) + { + int num = this.FindIndex(max); + if (num >= 0 && num < this.m_AddedCurves.Count) + { + return this.m_AddedCurves[num].m_Color; + } + return new Color(0.8f, 0.8f, 0.8f, 0.7f); + } + public void AddCurveDataIfNeeded(string curveName, ParticleSystemCurveEditor.CurveData curveData) + { + Vector3 vector = InspectorState.GetVector3(curveName, Vector3.zero); + if (vector != Vector3.zero) + { + Color color = new Color(vector.x, vector.y, vector.z); + curveData.m_Color = color; + this.AddCurve(curveData); + for (int i = 0; i < this.m_AvailableColors.Count; i++) + { + if (ParticleSystemCurveEditor.SameColor(this.m_AvailableColors[i], color)) + { + this.m_AvailableColors.RemoveAt(i); + break; + } + } + } + } + public void SetVisible(SerializedProperty curveProp, bool visible) + { + int num = this.FindIndex(curveProp); + if (num >= 0) + { + this.m_AddedCurves[num].m_Visible = visible; + } + } + private static bool SameColor(Color c1, Color c2) + { + return Mathf.Abs(c1.r - c2.r) < 0.01f && Mathf.Abs(c1.g - c2.g) < 0.01f && Mathf.Abs(c1.b - c2.b) < 0.01f; + } + private int FindIndex(SerializedProperty prop) + { + return this.FindIndex(null, prop); + } + private int FindIndex(SerializedProperty min, SerializedProperty max) + { + if (max == null) + { + return -1; + } + if (min == null) + { + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + if (this.m_AddedCurves[i].m_Max == max) + { + return i; + } + } + } + else + { + for (int j = 0; j < this.m_AddedCurves.Count; j++) + { + if (this.m_AddedCurves[j].m_Max == max && this.m_AddedCurves[j].m_Min == min) + { + return j; + } + } + } + return -1; + } + private void Add(ParticleSystemCurveEditor.CurveData cd) + { + this.m_CurveEditor.SelectNone(); + this.m_AddedCurves.Add(cd); + this.ContentChanged(); + InspectorState.SetVector3(cd.m_UniqueName, new Vector3(cd.m_Color.r, cd.m_Color.g, cd.m_Color.b)); + this.UpdateRangeBasedOnShownCurves(); + } + private bool Remove(int index) + { + if (index >= 0 && index < this.m_AddedCurves.Count) + { + Color color = this.m_AddedCurves[index].m_Color; + this.m_AvailableColors.Add(color); + string uniqueName = this.m_AddedCurves[index].m_UniqueName; + InspectorState.EraseVector3(uniqueName); + this.m_AddedCurves.RemoveAt(index); + if (this.m_AddedCurves.Count == 0) + { + this.m_AvailableColors = new List(this.m_Colors); + } + return true; + } + Debug.Log("Invalid index in ParticleSystemCurveEditor::Remove"); + return false; + } + private void RemoveTopMost() + { + int num; + if (this.m_CurveEditor.GetTopMostCurveID(out num)) + { + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + ParticleSystemCurveEditor.CurveData curveData = this.m_AddedCurves[i]; + if (curveData.m_MaxId == num || curveData.m_MinId == num) + { + this.Remove(i); + this.ContentChanged(); + this.UpdateRangeBasedOnShownCurves(); + return; + } + } + } + } + private void RemoveSelected() + { + bool flag = false; + List selectedCurves = this.m_CurveEditor.selectedCurves; + for (int i = 0; i < selectedCurves.Count; i++) + { + int curveID = selectedCurves[i].curveID; + for (int j = 0; j < this.m_AddedCurves.Count; j++) + { + ParticleSystemCurveEditor.CurveData curveData = this.m_AddedCurves[j]; + if (curveData.m_MaxId == curveID || curveData.m_MinId == curveID) + { + flag |= this.Remove(j); + break; + } + } + } + if (flag) + { + this.ContentChanged(); + this.UpdateRangeBasedOnShownCurves(); + } + this.m_CurveEditor.SelectNone(); + } + private void RemoveAll() + { + bool flag = false; + while (this.m_AddedCurves.Count > 0) + { + flag |= this.Remove(0); + } + if (flag) + { + this.ContentChanged(); + this.UpdateRangeBasedOnShownCurves(); + } + } + public Color GetAvailableColor() + { + if (this.m_AvailableColors.Count == 0) + { + this.m_AvailableColors = new List(this.m_Colors); + } + int index = this.m_AvailableColors.Count - 1; + Color result = this.m_AvailableColors[index]; + this.m_AvailableColors.RemoveAt(index); + return result; + } + public void OnGUI(Rect rect) + { + this.Init(); + if (ParticleSystemCurveEditor.s_Styles == null) + { + ParticleSystemCurveEditor.s_Styles = new ParticleSystemCurveEditor.Styles(); + } + Rect rect2 = new Rect(rect.x, rect.y, rect.width, rect.height - 30f); + Rect rect3 = new Rect(rect.x, rect.y + rect2.height, rect.width, 30f); + GUI.Label(rect2, GUIContent.none, ParticleSystemCurveEditor.s_Styles.curveEditorBackground); + this.m_CurveEditor.rect = rect2; + this.m_CurveEditor.OnGUI(); + this.DoLabelForTopMostCurve(new Rect(rect.x + 4f, rect.y, rect.width, 20f)); + this.DoRemoveSelectedButton(new Rect(rect2.x, rect2.y, rect2.width, 24f)); + this.DoOptimizeCurveButton(rect3); + rect3.x += 30f; + rect3.width -= 60f; + this.PresetCurveButtons(rect3, rect); + this.SaveChangedCurves(); + } + private void DoLabelForTopMostCurve(Rect rect) + { + int num; + if ((this.m_CurveEditor.IsDraggingCurveOrRegion() || this.m_CurveEditor.selectedCurves.Count <= 1) && this.m_CurveEditor.GetTopMostCurveID(out num)) + { + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + if (this.m_AddedCurves[i].m_MaxId == num || this.m_AddedCurves[i].m_MinId == num) + { + ParticleSystemCurveEditor.s_Styles.yAxisHeader.normal.textColor = this.m_AddedCurves[i].m_Color; + GUI.Label(rect, this.m_AddedCurves[i].m_DisplayName, ParticleSystemCurveEditor.s_Styles.yAxisHeader); + return; + } + } + } + } + private void SetConstantCurve(CurveWrapper cw, float constantValue) + { + Keyframe[] array = new Keyframe[1]; + array[0].time = 0f; + array[0].value = constantValue; + cw.curve.keys = array; + cw.changed = true; + } + private void SetCurve(CurveWrapper cw, AnimationCurve curve) + { + Keyframe[] array = new Keyframe[curve.keys.Length]; + Array.Copy(curve.keys, array, array.Length); + cw.curve.keys = array; + cw.changed = true; + } + private void SetTopMostCurve(DoubleCurve doubleCurve) + { + int num; + if (this.m_CurveEditor.GetTopMostCurveID(out num)) + { + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + ParticleSystemCurveEditor.CurveData curveData = this.m_AddedCurves[i]; + if (curveData.m_MaxId == num || curveData.m_MinId == num) + { + if (doubleCurve.signedRange == curveData.m_SignedRange) + { + if (curveData.m_MaxId > 0) + { + this.SetCurve(this.m_CurveEditor.GetCurveFromID(curveData.m_MaxId), doubleCurve.maxCurve); + } + if (curveData.m_MinId > 0) + { + this.SetCurve(this.m_CurveEditor.GetCurveFromID(curveData.m_MinId), doubleCurve.minCurve); + } + } + else + { + Debug.LogWarning("Cannot assign a curves with different signed range"); + } + } + } + } + } + private DoubleCurve CreateDoubleCurveFromTopMostCurve() + { + int num; + if (this.m_CurveEditor.GetTopMostCurveID(out num)) + { + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + ParticleSystemCurveEditor.CurveData curveData = this.m_AddedCurves[i]; + if (curveData.m_MaxId == num || curveData.m_MinId == num) + { + AnimationCurve maxCurve = null; + AnimationCurve minCurve = null; + if (curveData.m_Min != null) + { + minCurve = curveData.m_Min.animationCurveValue; + } + if (curveData.m_Max != null) + { + maxCurve = curveData.m_Max.animationCurveValue; + } + return new DoubleCurve(minCurve, maxCurve, curveData.m_SignedRange); + } + } + } + return null; + } + private void PresetDropDown(Rect rect) + { + if (EditorGUI.ButtonMouseDown(rect, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) + { + DoubleCurve doubleCurve = this.CreateDoubleCurveFromTopMostCurve(); + if (doubleCurve != null) + { + this.InitDoubleCurvePresets(); + if (this.m_DoubleCurvePresets != null) + { + this.m_DoubleCurvePresets.doubleCurveToSave = this.CreateDoubleCurveFromTopMostCurve(); + PopupWindow.Show(rect, this.m_DoubleCurvePresets); + } + } + } + } + private void InitDoubleCurvePresets() + { + int num; + if (this.m_CurveEditor.GetTopMostCurveID(out num) && (this.m_DoubleCurvePresets == null || this.m_LastTopMostCurveID != num)) + { + this.m_LastTopMostCurveID = num; + Action presetSelectedCallback = delegate(DoubleCurve presetDoubleCurve) + { + this.SetTopMostCurve(presetDoubleCurve); + InternalEditorUtility.RepaintAllViews(); + }; + DoubleCurve doubleCurveToSave = this.CreateDoubleCurveFromTopMostCurve(); + this.m_DoubleCurvePresets = new DoubleCurvePresetsContentsForPopupWindow(doubleCurveToSave, presetSelectedCallback); + this.m_DoubleCurvePresets.InitIfNeeded(); + } + } + private void PresetCurveButtons(Rect position, Rect curveEditorRect) + { + if (this.m_CurveEditor.animationCurves.Length == 0) + { + return; + } + this.InitDoubleCurvePresets(); + if (this.m_DoubleCurvePresets == null) + { + return; + } + DoubleCurvePresetLibrary currentLib = this.m_DoubleCurvePresets.GetPresetLibraryEditor().GetCurrentLib(); + int a = (!(currentLib != null)) ? 0 : currentLib.Count(); + int num = Mathf.Min(a, 9); + float num2 = 30f; + float num3 = 15f; + float num4 = 10f; + float num5 = (float)num * num2 + (float)(num - 1) * num4; + float num6 = (position.width - num5) * 0.5f; + float num7 = (position.height - num3) * 0.5f; + float num8 = 3f; + if (num6 > 0f) + { + num8 = num6; + } + this.PresetDropDown(new Rect(num8 - 20f + position.x, num7 + position.y, 16f, 16f)); + GUI.BeginGroup(position); + Color color; + Color.white.a = color.a * 0.6f; + for (int i = 0; i < num; i++) + { + if (i > 0) + { + num8 += num4; + } + Rect rect = new Rect(num8, num7, num2, num3); + ParticleSystemCurveEditor.s_Styles.presetTooltip.tooltip = currentLib.GetName(i); + if (GUI.Button(rect, ParticleSystemCurveEditor.s_Styles.presetTooltip, GUIStyle.none)) + { + DoubleCurve doubleCurve = currentLib.GetPreset(i) as DoubleCurve; + if (doubleCurve != null) + { + this.SetTopMostCurve(doubleCurve); + } + } + if (Event.current.type == EventType.Repaint) + { + currentLib.Draw(rect, i); + } + num8 += num2; + } + GUI.EndGroup(); + } + private void DoOptimizeCurveButton(Rect rect) + { + if (this.m_CurveEditor.IsDraggingCurveOrRegion()) + { + return; + } + Rect position = new Rect(rect.xMax - 10f - 14f, rect.y + (rect.height - 14f) * 0.5f, 14f, 14f); + int num = 0; + List selectedCurves = this.m_CurveEditor.selectedCurves; + if (selectedCurves.Count > 0) + { + for (int i = 0; i < selectedCurves.Count; i++) + { + CurveWrapper curveWrapper = selectedCurves[i].curveWrapper; + num += ((!AnimationUtility.IsValidPolynomialCurve(curveWrapper.curve)) ? 0 : 1); + } + if (selectedCurves.Count != num && GUI.Button(position, ParticleSystemCurveEditor.s_Styles.optimizeCurveText, ParticleSystemCurveEditor.s_Styles.plus)) + { + for (int j = 0; j < selectedCurves.Count; j++) + { + CurveWrapper curveWrapper2 = selectedCurves[j].curveWrapper; + if (!AnimationUtility.IsValidPolynomialCurve(curveWrapper2.curve)) + { + AnimationUtility.ConstrainToPolynomialCurve(curveWrapper2.curve); + curveWrapper2.changed = true; + } + } + this.m_CurveEditor.SelectNone(); + } + } + else + { + int id; + if (this.m_CurveEditor.GetTopMostCurveID(out id)) + { + CurveWrapper curveWrapperById = this.m_CurveEditor.getCurveWrapperById(id); + if (!AnimationUtility.IsValidPolynomialCurve(curveWrapperById.curve) && GUI.Button(position, ParticleSystemCurveEditor.s_Styles.optimizeCurveText, ParticleSystemCurveEditor.s_Styles.plus)) + { + AnimationUtility.ConstrainToPolynomialCurve(curveWrapperById.curve); + curveWrapperById.changed = true; + } + } + } + } + private void DoRemoveSelectedButton(Rect rect) + { + if (this.m_CurveEditor.animationCurves.Length == 0) + { + return; + } + float num = 14f; + Rect position = new Rect(rect.x + rect.width - num - 10f, rect.y + (rect.height - num) * 0.5f, num, num); + if (GUI.Button(position, ParticleSystemCurveEditor.s_Styles.removeCurveText, ParticleSystemCurveEditor.s_Styles.minus)) + { + if (this.m_CurveEditor.selectedCurves.Count > 0) + { + this.RemoveSelected(); + } + else + { + this.RemoveTopMost(); + } + } + } + private void SaveCurve(SerializedProperty prop, CurveWrapper cw) + { + prop.animationCurveValue = cw.curve; + cw.changed = false; + } + private void SaveChangedCurves() + { + CurveWrapper[] animationCurves = this.m_CurveEditor.animationCurves; + bool flag = false; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (curveWrapper.changed) + { + for (int j = 0; j < this.m_AddedCurves.Count; j++) + { + if (this.m_AddedCurves[j].m_MaxId == curveWrapper.id) + { + this.SaveCurve(this.m_AddedCurves[j].m_Max, curveWrapper); + break; + } + if (this.m_AddedCurves[j].IsRegion() && this.m_AddedCurves[j].m_MinId == curveWrapper.id) + { + this.SaveCurve(this.m_AddedCurves[j].m_Min, curveWrapper); + break; + } + } + flag = true; + } + } + if (flag) + { + AnimationCurvePreviewCache.ClearCache(); + HandleUtility.Repaint(); + } + } + private CurveWrapper CreateCurveWrapper(SerializedProperty curve, int id, int regionId, Color color, bool signedRange, CurveWrapper.GetAxisScalarsCallback getAxisScalarsCallback, CurveWrapper.SetAxisScalarsCallback setAxisScalarsCallback) + { + float end = 1f; + CurveWrapper curveWrapper = new CurveWrapper(); + curveWrapper.id = id; + curveWrapper.regionId = regionId; + curveWrapper.color = color; + curveWrapper.renderer = new NormalCurveRenderer(curve.animationCurveValue); + curveWrapper.renderer.SetCustomRange(0f, end); + curveWrapper.vRangeMin = ((!signedRange) ? 0f : -1f); + curveWrapper.getAxisUiScalarsCallback = getAxisScalarsCallback; + curveWrapper.setAxisUiScalarsCallback = setAxisScalarsCallback; + return curveWrapper; + } + private CurveWrapper[] CreateCurveWrapperArray() + { + List list = new List(); + int num = 0; + for (int i = 0; i < this.m_AddedCurves.Count; i++) + { + ParticleSystemCurveEditor.CurveData curveData = this.m_AddedCurves[i]; + if (curveData.m_Visible) + { + int regionId = -1; + if (curveData.IsRegion()) + { + num = (regionId = num + 1); + } + if (curveData.m_Max != null) + { + list.Add(this.CreateCurveWrapper(curveData.m_Max, curveData.m_MaxId, regionId, curveData.m_Color, curveData.m_SignedRange, curveData.m_GetAxisScalarsCallback, curveData.m_SetAxisScalarsCallback)); + } + if (curveData.m_Min != null) + { + list.Add(this.CreateCurveWrapper(curveData.m_Min, curveData.m_MinId, regionId, curveData.m_Color, curveData.m_SignedRange, curveData.m_GetAxisScalarsCallback, curveData.m_SetAxisScalarsCallback)); + } + } + } + return list.ToArray(); + } + private void ContentChanged() + { + this.m_CurveEditor.animationCurves = this.CreateCurveWrapperArray(); + ParticleSystemCurveEditor.m_CurveEditorSettings.showAxisLabels = (this.m_CurveEditor.animationCurves.Length > 0); + } +} diff --git a/UnityEditor/PatchImportSettingRecycleID.cs b/UnityEditor/PatchImportSettingRecycleID.cs new file mode 100644 index 00000000..e01ee02f --- /dev/null +++ b/UnityEditor/PatchImportSettingRecycleID.cs @@ -0,0 +1,38 @@ +using System; +using UnityEditor; +internal class PatchImportSettingRecycleID +{ + private const int kMaxObjectsPerClassID = 100000; + public static void Patch(SerializedObject serializedObject, int classID, string oldName, string newName) + { + PatchImportSettingRecycleID.PatchMultiple(serializedObject, classID, new string[] + { + oldName + }, new string[] + { + newName + }); + } + public static void PatchMultiple(SerializedObject serializedObject, int classID, string[] oldNames, string[] newNames) + { + int num = oldNames.Length; + SerializedProperty serializedProperty = serializedObject.FindProperty("m_FileIDToRecycleName"); + foreach (SerializedProperty serializedProperty2 in serializedProperty) + { + SerializedProperty serializedProperty3 = serializedProperty2.FindPropertyRelative("first"); + if (serializedProperty3.intValue >= 100000 * classID && serializedProperty3.intValue < 100000 * (classID + 1)) + { + SerializedProperty serializedProperty4 = serializedProperty2.FindPropertyRelative("second"); + int num2 = Array.IndexOf(oldNames, serializedProperty4.stringValue); + if (num2 >= 0) + { + serializedProperty4.stringValue = newNames[num2]; + if (--num == 0) + { + break; + } + } + } + } + } +} diff --git a/UnityEditor/PostProcessDashboardWidget.cs b/UnityEditor/PostProcessDashboardWidget.cs new file mode 100644 index 00000000..1a3782d8 --- /dev/null +++ b/UnityEditor/PostProcessDashboardWidget.cs @@ -0,0 +1,35 @@ +using System; +using UnityEditor; +internal class PostProcessDashboardWidget +{ + public static void PostProcess(BuildTarget target, string installPath, string stagingArea, string playerPackage, string companyName, string productName, int width, int height) + { + string text = stagingArea + "/DashboardBuild"; + FileUtil.DeleteFileOrDirectory(text); + FileUtil.CopyFileOrDirectory(playerPackage, text); + FileUtil.MoveFileOrDirectory("Temp/unitystream.unity3d", text + "/widget.unity3d"); + PostprocessBuildPlayer.InstallPlugins(text + "/Plugins", target); + string text2 = PostprocessBuildPlayer.GenerateBundleIdentifier(companyName, productName) + ".widget"; + int num = width + 32; + int num2 = height + 32; + string[] input = new string[] + { + "UNITY_WIDTH_PLUS32", + num.ToString(), + "UNITY_HEIGHT_PLUS32", + num2.ToString(), + "UNITY_WIDTH", + width.ToString(), + "UNITY_HEIGHT", + height.ToString(), + "UNITY_BUNDLE_IDENTIFIER", + text2, + "UNITY_BUNDLE_NAME", + productName + }; + FileUtil.ReplaceText(text + "/UnityWidget.html", input); + FileUtil.ReplaceText(text + "/Info.plist", input); + FileUtil.DeleteFileOrDirectory(installPath); + FileUtil.MoveFileOrDirectory(text, installPath); + } +} diff --git a/UnityEditor/PostProcessFlashPlayer.cs b/UnityEditor/PostProcessFlashPlayer.cs new file mode 100644 index 00000000..383cbc9f --- /dev/null +++ b/UnityEditor/PostProcessFlashPlayer.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using UnityEditor; +using UnityEditor.Scripting; +using UnityEditor.Scripting.Compilers; +using UnityEditor.Utils; +using UnityEngine; +internal class PostProcessFlashPlayer +{ + private static FlashPostProcessSettings _settings; + private static FlashFileHelper _fileHelper; + internal static void PostProcess(PostProcessFlashPlayerOptions options) + { + PostProcessFlashPlayer._settings = FlashPostProcessSettings.CreateFrom(options); + PostProcessFlashPlayer._fileHelper = FlashFileHelper.CreateFrom(options); + PostProcessFlashPlayer.CleanWorkingPaths(); + if (!PostProcessFlashPlayer.ValidateAssemblies(options)) + { + return; + } + PostProcessFlashPlayer.RunCil2As(); + PostProcessFlashPlayer.CreateSerializedFileContainer(); + PostProcessFlashPlayer.RunMxmlc(); + PostProcessFlashPlayer.RunSwfPostProcessor(); + PostProcessFlashPlayer.DeleteAndCopyDefaultFiles(); + PostProcessFlashPlayer.WriteHtml(); + if (options.IsAutoRunPlayer) + { + Process.Start(PostProcessFlashPlayer._fileHelper.PathForHtmlInInstallPath()); + } + } + private static bool ValidateAssemblies(PostProcessFlashPlayerOptions options) + { + ValidationResult validationResult = AssemblyValidation.Validate(RuntimePlatform.FlashPlayer, PostProcessFlashPlayer._fileHelper.GetUserAssemblies(), new object[] + { + options + }); + if (validationResult.Success) + { + return true; + } + foreach (CompilerMessage current in validationResult.CompilerMessages) + { + UnityEngine.Debug.LogPlayerBuildError(current.message, current.file, current.line, current.column); + } + throw new Exception("Validation step " + validationResult.Rule + " Failed!"); + } + private static void CleanWorkingPaths() + { + FileUtil.CreateOrCleanDirectory(PostProcessFlashPlayer._fileHelper.PathForConvertedDotNetCode()); + FileUtil.CreateOrCleanDirectory(PostProcessFlashPlayer._fileHelper.PathForAs3Src()); + } + private static void CreateSerializedFileContainer() + { + PostProcessFlashPlayer._fileHelper.CopyResourcesFromPlayerPackageToStaging(); + SerializedFileContainerPreparer.CreateSerializedFileContainer(PostProcessFlashPlayer._fileHelper); + } + private static void RunCil2As() + { + StringBuilder stringBuilder = new StringBuilder("-with-class-index -libid:ConvertedDotNetCode -with-global-package --baseclasslibraries-directory="); + stringBuilder.Append(CommandLineFormatter.PrepareFileName(MonoInstallationFinder.GetProfileDirectory(BuildTarget.FlashPlayer, "unity"))); + stringBuilder.Append(" "); + PostProcessFlashPlayer.AppendUserAssembliesFormattedForCommandLine(stringBuilder); + string value = PostProcessFlashPlayer._fileHelper.PathForConvertedDotNetCode(); + stringBuilder.Append(value); + PostProcessFlashPlayer.StartManagedProgram(stringBuilder.ToString(), new Cil2AsOutputParser(), PostProcessFlashPlayer._fileHelper.PathForCil2AsExe()); + } + private static void AppendUserAssembliesFormattedForCommandLine(StringBuilder cmdline) + { + foreach (string current in PostProcessFlashPlayer._fileHelper.GetUserAssemblies()) + { + cmdline.Append(current); + cmdline.Append(" "); + } + } + private static void RunMxmlc() + { + PostProcessFlashPlayer.StartProgramChecked(new Program(new ProcessStartInfo + { + FileName = "java", + Arguments = string.Join(" ", MxmlcHelper.MxmlcArgumentsFor(PostProcessFlashPlayer._settings, PostProcessFlashPlayer._fileHelper)), + CreateNoWindow = true + }), new FlexCompilerOutputParser(), "java"); + } + private static bool RunSwfPostProcessor() + { + string value = PostProcessFlashPlayer._fileHelper.PathForTempSwf(); + StringBuilder stringBuilder = new StringBuilder(" -nativeskip -upp "); + stringBuilder.Append(value); + stringBuilder.Append(" -o "); + stringBuilder.Append(value); + stringBuilder.Append((!PostProcessFlashPlayer._settings.IsDevelopment) ? " -clzma " : " -cnone "); + stringBuilder.Append(" -inject-telemetry "); + return PostProcessFlashPlayer.StartManagedProgram(stringBuilder.ToString(), new Cil2AsOutputParser(), PostProcessFlashPlayer._fileHelper.PathForSwfPostProcessorExe()); + } + private static void DeleteAndCopyDefaultFiles() + { + FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForHtmlInInstallPath()); + FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("swfobject.js")); + FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("embeddingapi.swc")); + FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.InstallPath); + FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForTempSwfUnprepared(), PostProcessFlashPlayer._fileHelper.InstallPath); + FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInBuildTools("swfobject.js"), PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("swfobject.js")); + FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInBuildTools("UnityShared.swc"), PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("embeddingapi.swc")); + } + private static void WriteHtml() + { + FlashTemplateWriterUtility.WriteHTMLTemplate(PostProcessFlashPlayer._settings, PostProcessFlashPlayer._fileHelper); + } + private static bool StartManagedProgram(string arguments, UnityScriptCompilerOutputParser parser, string exe) + { + return PostProcessFlashPlayer.StartProgramChecked(new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, arguments), parser, exe); + } + private static bool StartProgramChecked(Program p, CompilerOutputParserBase parser, string exe) + { + bool result; + try + { + p.LogProcessStartInfo(); + try + { + p.Start(); + } + catch + { + throw new Exception("Could not start " + exe); + } + p.WaitForExit(); + if (p.ExitCode != 0) + { + string[] errorOutput = p.GetErrorOutput(); + string[] standardOutput = p.GetStandardOutput(); + PostProcessFlashPlayer.LogCompilerMessages(parser.Parse(errorOutput, standardOutput, true)); + throw new Exception(string.Concat(new string[] + { + exe, + " Failed:", + Environment.NewLine, + p.GetStandardOutputAsString(), + Environment.NewLine, + string.Join(Environment.NewLine, errorOutput) + })); + } + result = true; + } + finally + { + if (p != null) + { + ((IDisposable)p).Dispose(); + } + } + return result; + } + private static void LogCompilerMessages(IEnumerable messages) + { + foreach (CompilerMessage current in messages) + { + UnityEngine.Debug.LogPlayerBuildError(current.message, current.file, current.line, current.column); + } + } +} diff --git a/UnityEditor/PostProcessFlashPlayerOptions.cs b/UnityEditor/PostProcessFlashPlayerOptions.cs new file mode 100644 index 00000000..a66b0fa9 --- /dev/null +++ b/UnityEditor/PostProcessFlashPlayerOptions.cs @@ -0,0 +1,24 @@ +using System; +using UnityEditor; +internal class PostProcessFlashPlayerOptions +{ + public BuildTarget Target; + public string StagingAreaData; + public string StagingArea; + public string StagingAreaDataManaged; + public string PlayerPackage; + public string InstallPath; + public string CompanyName; + public string ProductName; + public BuildOptions Options; + public RuntimeClassRegistry UsedClassRegistry; + public int Width; + public int Height; + public bool IsAutoRunPlayer + { + get + { + return (this.Options & BuildOptions.AutoRunPlayer) != BuildOptions.None; + } + } +} diff --git a/UnityEditor/PostProcessStandalonePlayer.cs b/UnityEditor/PostProcessStandalonePlayer.cs new file mode 100644 index 00000000..2e8bbf92 --- /dev/null +++ b/UnityEditor/PostProcessStandalonePlayer.cs @@ -0,0 +1,4 @@ +using System; +internal class PostProcessStandalonePlayer +{ +} diff --git a/UnityEditor/PostProcessWebPlayer.cs b/UnityEditor/PostProcessWebPlayer.cs new file mode 100644 index 00000000..6b4a6fc8 --- /dev/null +++ b/UnityEditor/PostProcessWebPlayer.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +internal class PostProcessWebPlayer +{ + private static Dictionary optionNames = new Dictionary + { + + { + BuildOptions.AllowDebugging, + "enableDebugging" + } + }; + public static void PostProcess(BuildOptions options, string installPath, string downloadWebplayerUrl, int width, int height) + { + string str = FileUtil.UnityGetFileName(installPath); + string text = "Temp/BuildingWebplayerTemplate"; + FileUtil.DeleteFileOrDirectory(text); + if (PlayerSettings.webPlayerTemplate == null || !PlayerSettings.webPlayerTemplate.Contains(":")) + { + Debug.LogError("Invalid WebPlayer template selection! Select a template in player settings."); + return; + } + string[] array = PlayerSettings.webPlayerTemplate.Split(new char[] + { + ':' + }); + string text2; + if (array[0].Equals("PROJECT")) + { + text2 = Application.dataPath; + } + else + { + text2 = Path.Combine(EditorApplication.applicationContentsPath, "Resources"); + } + text2 = Path.Combine(Path.Combine(text2, "WebPlayerTemplates"), array[1]); + if (!Directory.Exists(text2)) + { + Debug.LogError("Invalid WebPlayer template path! Select a template in player settings."); + return; + } + string[] files = Directory.GetFiles(text2, "index.*"); + if (files.Length < 1) + { + Debug.LogError("Invalid WebPlayer template selection! Select a template in player settings."); + return; + } + FileUtil.CopyDirectoryRecursive(text2, text); + files = Directory.GetFiles(text, "index.*"); + string text3 = files[0]; + string extension = Path.GetExtension(text3); + string text4 = Path.Combine(text, str + extension); + FileUtil.MoveFileOrDirectory(text3, text4); + string[] files2 = Directory.GetFiles(text, "thumbnail.*"); + if (files2.Length > 0) + { + FileUtil.DeleteFileOrDirectory(files2[0]); + } + bool flag = (options & BuildOptions.WebPlayerOfflineDeployment) != BuildOptions.None; + string item = (!flag) ? (downloadWebplayerUrl + "/3.0/uo/UnityObject2.js") : "UnityObject2.js"; + string item2 = string.Format("", (!flag) ? "https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js" : "jquery.min.js"); + List list = new List(); + list.Add("%UNITY_UNITYOBJECT_DEPENDENCIES%"); + list.Add(item2); + list.Add("%UNITY_UNITYOBJECT_URL%"); + list.Add(item); + list.Add("%UNITY_WIDTH%"); + list.Add(width.ToString()); + list.Add("%UNITY_HEIGHT%"); + list.Add(height.ToString()); + list.Add("%UNITY_PLAYER_PARAMS%"); + list.Add(PostProcessWebPlayer.GeneratePlayerParamsString(options)); + list.Add("%UNITY_WEB_NAME%"); + list.Add(PlayerSettings.productName); + list.Add("%UNITY_WEB_PATH%"); + list.Add(str + ".unity3d"); + if (InternalEditorUtility.IsUnityBeta()) + { + list.Add("%UNITY_BETA_WARNING%"); + list.Add("\r\n\t\t

Built with beta version of Unity. Will only work on your computer!

"); + list.Add("%UNITY_SET_BASE_DOWNLOAD_URL%"); + list.Add(",baseDownloadUrl: \"" + downloadWebplayerUrl + "/\""); + } + else + { + list.Add("%UNITY_BETA_WARNING%"); + list.Add(string.Empty); + list.Add("%UNITY_SET_BASE_DOWNLOAD_URL%"); + list.Add(string.Empty); + } + string[] templateCustomKeys = PlayerSettings.templateCustomKeys; + for (int i = 0; i < templateCustomKeys.Length; i++) + { + string text5 = templateCustomKeys[i]; + list.Add("%UNITY_CUSTOM_" + text5.ToUpper() + "%"); + list.Add(PlayerSettings.GetTemplateCustomValue(text5)); + } + FileUtil.ReplaceText(text4, list.ToArray()); + if (flag) + { + string text6 = Path.Combine(text, "UnityObject2.js"); + FileUtil.DeleteFileOrDirectory(text6); + FileUtil.UnityFileCopy(EditorApplication.applicationContentsPath + "/Resources/UnityObject2.js", text6); + text6 = Path.Combine(text, "jquery.min.js"); + FileUtil.DeleteFileOrDirectory(text6); + FileUtil.UnityFileCopy(EditorApplication.applicationContentsPath + "/Resources/jquery.min.js", text6); + } + FileUtil.CopyDirectoryRecursive(text, installPath, true); + string text7 = Path.Combine(installPath, str + ".unity3d"); + FileUtil.DeleteFileOrDirectory(text7); + FileUtil.MoveFileOrDirectory("Temp/unitystream.unity3d", text7); + if (Directory.Exists("Assets/StreamingAssets")) + { + FileUtil.CopyDirectoryRecursiveForPostprocess("Assets/StreamingAssets", Path.Combine(installPath, "StreamingAssets"), true); + } + } + private static string GeneratePlayerParamsString(BuildOptions options) + { + return string.Format("{{ {0} }}", string.Join(",", ( + from pair in PostProcessWebPlayer.optionNames + select string.Format("{0}:\"{1}\"", pair.Value, (pair.Key != (options & pair.Key)) ? 0 : 1)).ToArray())); + } +} diff --git a/UnityEditor/PreviewGUI.cs b/UnityEditor/PreviewGUI.cs new file mode 100644 index 00000000..aa1278ed --- /dev/null +++ b/UnityEditor/PreviewGUI.cs @@ -0,0 +1,118 @@ +using System; +using UnityEditor; +using UnityEngine; +internal class PreviewGUI +{ + internal class Styles + { + public static GUIStyle preButton; + public static void Init() + { + PreviewGUI.Styles.preButton = "preButton"; + } + } + private static int sliderHash = "Slider".GetHashCode(); + private static Rect s_ViewRect; + private static Rect s_Position; + private static Vector2 s_ScrollPos; + internal static void BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar) + { + PreviewGUI.s_ScrollPos = scrollPosition; + PreviewGUI.s_ViewRect = viewRect; + PreviewGUI.s_Position = position; + GUIClip.Push(position, new Vector2(Mathf.Round(-scrollPosition.x - viewRect.x - (viewRect.width - position.width) * 0.5f), Mathf.Round(-scrollPosition.y - viewRect.y - (viewRect.height - position.height) * 0.5f)), Vector2.zero, false); + } + public static int CycleButton(int selected, GUIContent[] options) + { + PreviewGUI.Styles.Init(); + return EditorGUILayout.CycleButton(selected, options, PreviewGUI.Styles.preButton); + } + public static Vector2 EndScrollView() + { + GUIClip.Pop(); + Rect rect = PreviewGUI.s_Position; + Rect rect2 = PreviewGUI.s_Position; + Rect rect3 = PreviewGUI.s_ViewRect; + Vector2 result = PreviewGUI.s_ScrollPos; + EventType type = Event.current.type; + if (type != EventType.Layout) + { + if (type != EventType.Used) + { + bool flag = false; + bool flag2 = false; + if (flag2 || rect3.width > rect.width) + { + flag2 = true; + } + if (flag || rect3.height > rect.height) + { + flag = true; + } + int controlID = GUIUtility.GetControlID(PreviewGUI.sliderHash, FocusType.Passive); + if (flag2) + { + GUIStyle gUIStyle = "PreHorizontalScrollbar"; + GUIStyle thumb = "PreHorizontalScrollbarThumb"; + float num = (rect3.width - rect.width) * 0.5f; + result.x = GUI.Slider(new Rect(rect2.x, rect2.yMax - gUIStyle.fixedHeight, rect.width - ((!flag) ? 0f : gUIStyle.fixedHeight), gUIStyle.fixedHeight), result.x, rect.width + num, -num, rect3.width, gUIStyle, thumb, true, controlID); + } + else + { + result.x = 0f; + } + controlID = GUIUtility.GetControlID(PreviewGUI.sliderHash, FocusType.Passive); + if (flag) + { + GUIStyle gUIStyle2 = "PreVerticalScrollbar"; + GUIStyle thumb2 = "PreVerticalScrollbarThumb"; + float num2 = (rect3.height - rect.height) * 0.5f; + result.y = GUI.Slider(new Rect(rect.xMax - gUIStyle2.fixedWidth, rect.y, gUIStyle2.fixedWidth, rect.height), result.y, rect.height + num2, -num2, rect3.height, gUIStyle2, thumb2, false, controlID); + } + else + { + result.y = 0f; + } + } + } + else + { + GUIUtility.GetControlID(PreviewGUI.sliderHash, FocusType.Passive); + GUIUtility.GetControlID(PreviewGUI.sliderHash, FocusType.Passive); + } + return result; + } + public static Vector2 Drag2D(Vector2 scrollPosition, Rect position) + { + int controlID = GUIUtility.GetControlID(PreviewGUI.sliderHash, FocusType.Passive); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && position.width > 50f) + { + GUIUtility.hotControl = controlID; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + } + EditorGUIUtility.SetWantsMouseJumping(0); + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + scrollPosition -= current.delta * (float)((!current.shift) ? 1 : 3) / Mathf.Min(position.width, position.height) * 140f; + scrollPosition.y = Mathf.Clamp(scrollPosition.y, -90f, 90f); + current.Use(); + GUI.changed = true; + } + break; + } + return scrollPosition; + } +} diff --git a/UnityEditor/Properties/AssemblyInfo.cs b/UnityEditor/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..427084c5 --- /dev/null +++ b/UnityEditor/Properties/AssemblyInfo.cs @@ -0,0 +1,23 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEngine; +[assembly: AssemblyVersion("0.0.0.0")] +[assembly: InternalsVisibleTo("Unity.PureCSharpTests")] +[assembly: InternalsVisibleTo("Unity.IntegrationTests")] +[assembly: InternalsVisibleTo("UnityEditor.Graphs")] +[assembly: InternalsVisibleTo("UnityEditor.WP8.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.Metro.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.iOS.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.Xbox360.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.BB10.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.Android.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.Tizen.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.PS3.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.SamsungTV.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.XboxOne.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.PSP2.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.PS4.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.PSM.Extensions")] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] +[assembly: AssemblyIsEditorAssembly] diff --git a/UnityEditor/SerializedFileContainerPreparer.cs b/UnityEditor/SerializedFileContainerPreparer.cs new file mode 100644 index 00000000..8f7d0bee --- /dev/null +++ b/UnityEditor/SerializedFileContainerPreparer.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +internal class SerializedFileContainerPreparer +{ + private static string _stagingAreaData; + public static void CreateSerializedFileContainer(FlashFileHelper flashFileHelper) + { + SerializedFileContainerPreparer._stagingAreaData = flashFileHelper.StagingArea; + IEnumerable source = SerializedFileContainerPreparer.FindFilesThatShouldBeEmbedded(); + SerializedFileContainerWriter.SerializedFile[] files = ( + from f in source + select SerializedFileContainerPreparer.GetSerializedFile(f)).ToArray(); + SerializedFileContainerWriter.Write(SerializedFileContainerPreparer._stagingAreaData, files, flashFileHelper.PathForAs3Src()); + } + private static IEnumerable FindFilesThatShouldBeEmbedded() + { + List list = new List + { + "mainData", + "Resources/unity default resources" + }; + string[] patterns = new string[] + { + "\\.assets$", + "level", + "PlayerConnectionConfigFile" + }; + list.AddRange( + from ps in Directory.GetFiles(SerializedFileContainerPreparer._stagingAreaData) + where SerializedFileContainerPreparer.MatchesFilter(ps, patterns) + select ps into f + select Path.GetFileName(f)); + string path = Path.Combine(SerializedFileContainerPreparer._stagingAreaData, "Resources/unity_builtin_extra"); + if (File.Exists(path)) + { + list.Add("Resources/unity_builtin_extra"); + } + return list; + } + private static SerializedFileContainerWriter.SerializedFile GetSerializedFile(string file) + { + long length = new FileInfo(SerializedFileContainerPreparer._stagingAreaData + "/" + file).Length; + return new SerializedFileContainerWriter.SerializedFile + { + Name = file, + FileName = SerializedFileContainerPreparer.GetTextPlaceHolderForFile(file), + FileSize = length + }; + } + private static string GetTextPlaceHolderForFile(string fileName) + { + string str = Environment.CurrentDirectory + "/" + SerializedFileContainerPreparer._stagingAreaData + "/"; + UTF8Encoding uTF8Encoding = new UTF8Encoding(); + string str2 = fileName + "_txt"; + string text = "_UNITY_REPLACEFORFILE__" + str + fileName; + using (FileStream fileStream = new FileStream(SerializedFileContainerPreparer._stagingAreaData + "/" + str2, FileMode.CreateNew)) + { + fileStream.Write(uTF8Encoding.GetBytes(text), 0, uTF8Encoding.GetByteCount(text)); + } + return fileName; + } + private static bool MatchesFilter(string input, IEnumerable patterns) + { + return patterns.Any((string p) => Regex.Match(input, p).Success); + } +} diff --git a/UnityEditor/SerializedStringTable.cs b/UnityEditor/SerializedStringTable.cs new file mode 100644 index 00000000..da4c71b4 --- /dev/null +++ b/UnityEditor/SerializedStringTable.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections; +using UnityEngine; +[Serializable] +internal class SerializedStringTable +{ + [SerializeField] + private string[] keys; + [SerializeField] + private int[] values; + private Hashtable table; + public Hashtable hashtable + { + get + { + this.SanityCheck(); + return this.table; + } + } + public int Length + { + get + { + this.SanityCheck(); + return this.keys.Length; + } + } + private void SanityCheck() + { + if (this.keys == null) + { + this.keys = new string[0]; + this.values = new int[0]; + } + if (this.table == null) + { + this.table = new Hashtable(); + for (int i = 0; i < this.keys.Length; i++) + { + this.table[this.keys[i]] = this.values[i]; + } + } + } + private void SynchArrays() + { + this.keys = new string[this.table.Count]; + this.values = new int[this.table.Count]; + this.table.Keys.CopyTo(this.keys, 0); + this.table.Values.CopyTo(this.values, 0); + } + public void Set(string key, int value) + { + this.SanityCheck(); + this.table[key] = value; + this.SynchArrays(); + } + public void Set(string key) + { + this.Set(key, 0); + } + public bool Contains(string key) + { + this.SanityCheck(); + return this.table.Contains(key); + } + public int Get(string key) + { + this.SanityCheck(); + if (!this.table.Contains(key)) + { + return -1; + } + return (int)this.table[key]; + } + public void Remove(string key) + { + this.SanityCheck(); + if (this.table.Contains(key)) + { + this.table.Remove(key); + } + this.SynchArrays(); + } +} diff --git a/UnityEditor/TreeEditor/FractalNoise.cs b/UnityEditor/TreeEditor/FractalNoise.cs new file mode 100644 index 00000000..a83f103c --- /dev/null +++ b/UnityEditor/TreeEditor/FractalNoise.cs @@ -0,0 +1,92 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + public class FractalNoise + { + private Perlin m_Noise; + private float[] m_Exponent; + private int m_IntOctaves; + private float m_Octaves; + private float m_Lacunarity; + public FractalNoise(float inH, float inLacunarity, float inOctaves) : this(inH, inLacunarity, inOctaves, null) + { + } + public FractalNoise(float inH, float inLacunarity, float inOctaves, Perlin noise) + { + this.m_Lacunarity = inLacunarity; + this.m_Octaves = inOctaves; + this.m_IntOctaves = (int)inOctaves; + this.m_Exponent = new float[this.m_IntOctaves + 1]; + float num = 1f; + for (int i = 0; i < this.m_IntOctaves + 1; i++) + { + this.m_Exponent[i] = (float)Math.Pow((double)this.m_Lacunarity, (double)(-(double)inH)); + num *= this.m_Lacunarity; + } + if (noise == null) + { + this.m_Noise = new Perlin(); + } + else + { + this.m_Noise = noise; + } + } + public float HybridMultifractal(float x, float y, float offset) + { + float num = (this.m_Noise.Noise(x, y) + offset) * this.m_Exponent[0]; + float num2 = num; + x *= this.m_Lacunarity; + y *= this.m_Lacunarity; + int i; + for (i = 1; i < this.m_IntOctaves; i++) + { + if (num2 > 1f) + { + num2 = 1f; + } + float num3 = (this.m_Noise.Noise(x, y) + offset) * this.m_Exponent[i]; + num += num2 * num3; + num2 *= num3; + x *= this.m_Lacunarity; + y *= this.m_Lacunarity; + } + float num4 = this.m_Octaves - (float)this.m_IntOctaves; + return num + num4 * this.m_Noise.Noise(x, y) * this.m_Exponent[i]; + } + public float RidgedMultifractal(float x, float y, float offset, float gain) + { + float num = Mathf.Abs(this.m_Noise.Noise(x, y)); + num = offset - num; + num *= num; + float num2 = num; + for (int i = 1; i < this.m_IntOctaves; i++) + { + x *= this.m_Lacunarity; + y *= this.m_Lacunarity; + float num3 = num * gain; + num3 = Mathf.Clamp01(num3); + num = Mathf.Abs(this.m_Noise.Noise(x, y)); + num = offset - num; + num *= num; + num *= num3; + num2 += num * this.m_Exponent[i]; + } + return num2; + } + public float BrownianMotion(float x, float y) + { + float num = 0f; + long num2; + for (num2 = 0L; num2 < (long)this.m_IntOctaves; num2 += 1L) + { + num = this.m_Noise.Noise(x, y) * this.m_Exponent[(int)checked((IntPtr)num2)]; + x *= this.m_Lacunarity; + y *= this.m_Lacunarity; + } + float num3 = this.m_Octaves - (float)this.m_IntOctaves; + return num + num3 * this.m_Noise.Noise(x, y) * this.m_Exponent[(int)checked((IntPtr)num2)]; + } + } +} diff --git a/UnityEditor/TreeEditor/Perlin.cs b/UnityEditor/TreeEditor/Perlin.cs new file mode 100644 index 00000000..c53c2e7d --- /dev/null +++ b/UnityEditor/TreeEditor/Perlin.cs @@ -0,0 +1,177 @@ +using System; +namespace TreeEditor +{ + public class Perlin + { + private const int B = 256; + private const int BM = 255; + private const int N = 4096; + private int[] p = new int[514]; + private float[,] g3 = new float[514, 3]; + private float[,] g2 = new float[514, 2]; + private float[] g1 = new float[514]; + public Perlin() + { + this.SetSeed(0); + } + private float s_curve(float t) + { + return t * t * (3f - 2f * t); + } + private float lerp(float t, float a, float b) + { + return a + t * (b - a); + } + private void setup(float value, out int b0, out int b1, out float r0, out float r1) + { + float num = value + 4096f; + b0 = ((int)num & 255); + b1 = (b0 + 1 & 255); + r0 = num - (float)((int)num); + r1 = r0 - 1f; + } + private float at2(float rx, float ry, float x, float y) + { + return rx * x + ry * y; + } + private float at3(float rx, float ry, float rz, float x, float y, float z) + { + return rx * x + ry * y + rz * z; + } + public float Noise(float arg) + { + int num; + int num2; + float num3; + float num4; + this.setup(arg, out num, out num2, out num3, out num4); + float t = this.s_curve(num3); + float a = num3 * this.g1[this.p[num]]; + float b = num4 * this.g1[this.p[num2]]; + return this.lerp(t, a, b); + } + public float Noise(float x, float y) + { + int num; + int num2; + float num3; + float rx; + this.setup(x, out num, out num2, out num3, out rx); + int num4; + int num5; + float num6; + float ry; + this.setup(y, out num4, out num5, out num6, out ry); + int num7 = this.p[num]; + int num8 = this.p[num2]; + int num9 = this.p[num7 + num4]; + int num10 = this.p[num8 + num4]; + int num11 = this.p[num7 + num5]; + int num12 = this.p[num8 + num5]; + float t = this.s_curve(num3); + float t2 = this.s_curve(num6); + float a = this.at2(num3, num6, this.g2[num9, 0], this.g2[num9, 1]); + float b = this.at2(rx, num6, this.g2[num10, 0], this.g2[num10, 1]); + float a2 = this.lerp(t, a, b); + a = this.at2(num3, ry, this.g2[num11, 0], this.g2[num11, 1]); + b = this.at2(rx, ry, this.g2[num12, 0], this.g2[num12, 1]); + float b2 = this.lerp(t, a, b); + return this.lerp(t2, a2, b2); + } + public float Noise(float x, float y, float z) + { + int num; + int num2; + float num3; + float rx; + this.setup(x, out num, out num2, out num3, out rx); + int num4; + int num5; + float num6; + float ry; + this.setup(y, out num4, out num5, out num6, out ry); + int num7; + int num8; + float num9; + float rz; + this.setup(z, out num7, out num8, out num9, out rz); + int num10 = this.p[num]; + int num11 = this.p[num2]; + int num12 = this.p[num10 + num4]; + int num13 = this.p[num11 + num4]; + int num14 = this.p[num10 + num5]; + int num15 = this.p[num11 + num5]; + float t = this.s_curve(num3); + float t2 = this.s_curve(num6); + float t3 = this.s_curve(num9); + float a = this.at3(num3, num6, num9, this.g3[num12 + num7, 0], this.g3[num12 + num7, 1], this.g3[num12 + num7, 2]); + float b = this.at3(rx, num6, num9, this.g3[num13 + num7, 0], this.g3[num13 + num7, 1], this.g3[num13 + num7, 2]); + float a2 = this.lerp(t, a, b); + a = this.at3(num3, ry, num9, this.g3[num14 + num7, 0], this.g3[num14 + num7, 1], this.g3[num14 + num7, 2]); + b = this.at3(rx, ry, num9, this.g3[num15 + num7, 0], this.g3[num15 + num7, 1], this.g3[num15 + num7, 2]); + float b2 = this.lerp(t, a, b); + float a3 = this.lerp(t2, a2, b2); + a = this.at3(num3, num6, rz, this.g3[num12 + num8, 0], this.g3[num12 + num8, 2], this.g3[num12 + num8, 2]); + b = this.at3(rx, num6, rz, this.g3[num13 + num8, 0], this.g3[num13 + num8, 1], this.g3[num13 + num8, 2]); + a2 = this.lerp(t, a, b); + a = this.at3(num3, ry, rz, this.g3[num14 + num8, 0], this.g3[num14 + num8, 1], this.g3[num14 + num8, 2]); + b = this.at3(rx, ry, rz, this.g3[num15 + num8, 0], this.g3[num15 + num8, 1], this.g3[num15 + num8, 2]); + b2 = this.lerp(t, a, b); + float b3 = this.lerp(t2, a2, b2); + return this.lerp(t3, a3, b3); + } + private void normalize2(ref float x, ref float y) + { + float num = (float)Math.Sqrt((double)(x * x + y * y)); + x = y / num; + y /= num; + } + private void normalize3(ref float x, ref float y, ref float z) + { + float num = (float)Math.Sqrt((double)(x * x + y * y + z * z)); + x = y / num; + y /= num; + z /= num; + } + public void SetSeed(int seed) + { + Random random = new Random(seed); + int i; + for (i = 0; i < 256; i++) + { + this.p[i] = i; + this.g1[i] = (float)(random.Next(512) - 256) / 256f; + for (int j = 0; j < 2; j++) + { + this.g2[i, j] = (float)(random.Next(512) - 256) / 256f; + } + this.normalize2(ref this.g2[i, 0], ref this.g2[i, 1]); + for (int j = 0; j < 3; j++) + { + this.g3[i, j] = (float)(random.Next(512) - 256) / 256f; + } + this.normalize3(ref this.g3[i, 0], ref this.g3[i, 1], ref this.g3[i, 2]); + } + while (--i != 0) + { + int num = this.p[i]; + int j; + this.p[i] = this.p[j = random.Next(256)]; + this.p[j] = num; + } + for (i = 0; i < 258; i++) + { + this.p[256 + i] = this.p[i]; + this.g1[256 + i] = this.g1[i]; + for (int j = 0; j < 2; j++) + { + this.g2[256 + i, j] = this.g2[i, j]; + } + for (int j = 0; j < 3; j++) + { + this.g3[256 + i, j] = this.g3[i, j]; + } + } + } + } +} diff --git a/UnityEditor/TreeEditor/RingLoop.cs b/UnityEditor/TreeEditor/RingLoop.cs new file mode 100644 index 00000000..5987c9fc --- /dev/null +++ b/UnityEditor/TreeEditor/RingLoop.cs @@ -0,0 +1,329 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace TreeEditor +{ + public class RingLoop + { + public float radius; + private Matrix4x4 matrix; + private int segments; + public float baseOffset; + private Vector4 animParams; + private float spreadTop; + private float spreadBot; + private float noiseScale; + private float noiseScaleU = 1f; + private float noiseScaleV = 1f; + private float flareRadius; + private float flareNoise; + private float surfAngleCos; + private float surfAngleSin; + private int vertOffset; + private static Perlin perlin = new Perlin(); + private static int noiseSeed = -1; + public static void SetNoiseSeed(int seed) + { + if (RingLoop.noiseSeed != seed) + { + RingLoop.perlin.SetSeed(seed); + } + } + public RingLoop Clone() + { + return new RingLoop + { + radius = this.radius, + matrix = this.matrix, + segments = this.segments, + baseOffset = this.baseOffset, + animParams = this.animParams, + spreadTop = this.spreadTop, + spreadBot = this.spreadBot, + noiseScale = this.noiseScale, + noiseScaleU = this.noiseScaleU, + noiseScaleV = this.noiseScaleV, + flareRadius = this.flareRadius, + flareNoise = this.flareNoise, + surfAngleCos = this.surfAngleCos, + surfAngleSin = this.surfAngleSin + }; + } + public void Reset(float r, Matrix4x4 m, float bOffset, int segs) + { + this.radius = r; + this.matrix = m; + this.baseOffset = bOffset; + this.segments = segs; + this.vertOffset = 0; + } + public void SetSurfaceAngle(float angleDeg) + { + this.surfAngleCos = Mathf.Cos(angleDeg * 0.0174532924f); + this.surfAngleSin = -Mathf.Sin(angleDeg * 0.0174532924f); + } + public void SetAnimationProperties(float primaryFactor, float secondaryFactor, float edgeFactor, float phase) + { + this.animParams = new Vector4(primaryFactor, secondaryFactor, edgeFactor, phase); + } + public void SetSpread(float top, float bottom) + { + this.spreadTop = top; + this.spreadBot = bottom; + } + public void SetNoise(float scale, float scaleU, float scaleV) + { + this.noiseScale = scale; + this.noiseScaleU = scaleU; + this.noiseScaleV = scaleV; + } + public void SetFlares(float radius, float noise) + { + this.flareRadius = radius; + this.flareNoise = noise; + } + public void BuildVertices(List verts) + { + this.vertOffset = verts.Count; + for (int i = 0; i <= this.segments; i++) + { + float f = (float)i * 3.14159274f * 2f / (float)this.segments; + TreeVertex treeVertex = new TreeVertex(); + float num = this.radius; + float num2 = 1f - (float)i / (float)this.segments; + float num3 = this.baseOffset; + float num4 = num2; + float num5 = num3; + if (i == this.segments) + { + num4 = 1f; + } + float num6 = Mathf.Cos(f); + float num7; + if (num6 > 0f) + { + num7 = Mathf.Pow(num6, 3f) * this.radius * this.spreadBot; + } + else + { + num7 = Mathf.Pow(Mathf.Abs(num6), 3f) * this.radius * this.spreadTop; + } + float x = num4 * this.noiseScaleU; + float y = num5 * this.noiseScaleV; + num += this.radius * (RingLoop.perlin.Noise(x, y) * this.noiseScale); + x = num4 * this.flareNoise; + num += this.flareRadius * Mathf.Abs(RingLoop.perlin.Noise(x, 0.12932f)); + treeVertex.pos = this.matrix.MultiplyPoint(new Vector3(Mathf.Sin(f) * (num + num7 * 0.25f), 0f, Mathf.Cos(f) * (num + num7))); + treeVertex.uv0 = new Vector2(num2, num3); + treeVertex.SetAnimationProperties(this.animParams.x, this.animParams.y, this.animParams.z, this.animParams.w); + verts.Add(treeVertex); + } + if (this.radius == 0f) + { + for (int j = 0; j <= this.segments; j++) + { + TreeVertex treeVertex2 = verts[j + this.vertOffset]; + float num8 = (float)j * 3.14159274f * 2f / (float)this.segments; + float f2 = num8 - 1.57079637f; + Vector3 zero = Vector3.zero; + zero.x = Mathf.Sin(num8) * this.surfAngleCos; + zero.y = this.surfAngleSin; + zero.z = Mathf.Cos(num8) * this.surfAngleCos; + treeVertex2.nor = Vector3.Normalize(this.matrix.MultiplyVector(zero)); + Vector3 v = Vector3.zero; + v.x = Mathf.Sin(f2); + v.y = 0f; + v.z = Mathf.Cos(f2); + v = Vector3.Normalize(this.matrix.MultiplyVector(v)); + treeVertex2.tangent = new Vector4(v.x, v.y, v.z, -1f); + } + return; + } + Matrix4x4 inverse = this.matrix.inverse; + for (int k = 0; k <= this.segments; k++) + { + int num9 = k - 1; + if (num9 < 0) + { + num9 = this.segments - 1; + } + int num10 = k + 1; + if (num10 > this.segments) + { + num10 = 1; + } + TreeVertex treeVertex3 = verts[num9 + this.vertOffset]; + TreeVertex treeVertex4 = verts[num10 + this.vertOffset]; + TreeVertex treeVertex5 = verts[k + this.vertOffset]; + Vector3 vector = Vector3.Normalize(treeVertex3.pos - treeVertex4.pos); + Vector3 v2 = inverse.MultiplyVector(treeVertex3.pos - treeVertex4.pos); + v2.y = v2.x; + v2.x = v2.z; + v2.z = -v2.y; + v2.y = 0f; + v2.Normalize(); + v2.x = this.surfAngleCos * v2.x; + v2.y = this.surfAngleSin; + v2.z = this.surfAngleCos * v2.z; + treeVertex5.nor = Vector3.Normalize(this.matrix.MultiplyVector(v2)); + treeVertex5.tangent.x = vector.x; + treeVertex5.tangent.y = vector.y; + treeVertex5.tangent.z = vector.z; + treeVertex5.tangent.w = -1f; + } + } + public void Cap(float sphereFactor, float noise, int mappingMode, float mappingScale, List verts, List tris, int materialIndex) + { + int num = Mathf.Max(1, (int)((float)(this.segments / 2) * Mathf.Clamp01(sphereFactor))); + int num2 = this.segments; + int num3 = num; + if (mappingMode == 1) + { + num2++; + num3++; + mappingScale /= Mathf.Max(1f, sphereFactor); + } + int count = verts.Count; + Vector3 vector = Vector3.Normalize(this.matrix.MultiplyVector(Vector3.up)); + Vector3 a = this.matrix.MultiplyPoint(Vector3.zero); + TreeVertex treeVertex = new TreeVertex(); + treeVertex.nor = vector; + treeVertex.pos = a + treeVertex.nor * sphereFactor * this.radius; + Vector3 vector2 = Vector3.Normalize(this.matrix.MultiplyVector(Vector3.right)); + treeVertex.tangent = new Vector4(vector2.x, vector2.y, vector2.z, -1f); + treeVertex.SetAnimationProperties(this.animParams.x, this.animParams.y, this.animParams.z, this.animParams.w); + if (mappingMode == 0) + { + treeVertex.uv0 = new Vector2(0.5f, 0.5f); + } + else + { + treeVertex.uv0 = new Vector2(0.5f, this.baseOffset + sphereFactor * mappingScale); + } + verts.Add(treeVertex); + int count2 = verts.Count; + Matrix4x4 inverse = this.matrix.inverse; + for (int i = 0; i < num3; i++) + { + float f = (1f - (float)i / (float)num) * 3.14159274f * 0.5f; + float num4 = Mathf.Sin(f); + float num5 = num4; + float num6 = num4 * Mathf.Clamp01(sphereFactor) + num4 * 0.5f * Mathf.Clamp01(1f - sphereFactor); + float num7 = Mathf.Cos(f); + for (int j = 0; j < num2; j++) + { + TreeVertex treeVertex2 = verts[this.vertOffset + j]; + Vector3 vector3 = inverse.MultiplyPoint(treeVertex2.pos).normalized * 0.5f * num4; + TreeVertex treeVertex3 = new TreeVertex(); + treeVertex3.pos = treeVertex2.pos * num5 + a * (1f - num5) + vector * num7 * sphereFactor * this.radius; + treeVertex3.nor = (treeVertex2.nor * num6 + vector * (1f - num6)).normalized; + treeVertex3.SetAnimationProperties(this.animParams.x, this.animParams.y, this.animParams.z, this.animParams.w); + if (mappingMode == 0) + { + treeVertex3.tangent = treeVertex.tangent; + treeVertex3.uv0 = new Vector2(0.5f + vector3.x, 0.5f + vector3.z); + } + else + { + treeVertex3.tangent = treeVertex2.tangent; + treeVertex3.uv0 = new Vector2((float)j / (float)this.segments, this.baseOffset + sphereFactor * num7 * mappingScale); + } + verts.Add(treeVertex3); + } + } + float num8 = 3f; + for (int k = this.vertOffset; k < verts.Count; k++) + { + float x = verts[k].pos.x * num8; + float y = verts[k].pos.z * num8; + float d = this.radius * (RingLoop.perlin.Noise(x, y) * noise); + verts[k].pos += treeVertex.nor * d; + } + for (int l = 0; l < num; l++) + { + for (int m = 0; m < num2; m++) + { + if (l == num3 - 1) + { + int num9 = m + count2 + num2 * l; + int v = num9 + 1; + if (m == num2 - 1) + { + v = count2 + num2 * l; + } + tris.Add(new TreeTriangle(materialIndex, count, num9, v, false, false, false)); + } + else + { + int num10 = m + count2 + num2 * l; + int v2 = num10 + 1; + int num11 = m + count2 + num2 * (l + 1); + int num12 = num11 + 1; + if (m == num2 - 1) + { + v2 = count2 + num2 * l; + num12 = count2 + num2 * (l + 1); + } + tris.Add(new TreeTriangle(materialIndex, num10, v2, num12, false, false, false)); + tris.Add(new TreeTriangle(materialIndex, num10, num12, num11, false, false, false)); + } + } + } + } + public void Connect(RingLoop other, List tris, int materialIndex, bool flipTris, bool lowres) + { + if (other.segments > this.segments) + { + other.Connect(this, tris, materialIndex, true, lowres); + return; + } + if (lowres) + { + for (int i = 0; i < this.segments / 2; i++) + { + int num = 0 + i + other.vertOffset; + int num2 = other.segments / 2 + i + other.vertOffset; + int num3 = 0 + i + this.vertOffset; + int num4 = this.segments / 2 + i + this.vertOffset; + if (flipTris) + { + int num5 = num; + num = num2; + num2 = num5; + num5 = num3; + num3 = num4; + num4 = num5; + } + tris.Add(new TreeTriangle(materialIndex, num, num2, num3, false, true, false)); + tris.Add(new TreeTriangle(materialIndex, num2, num4, num3, false, true, false)); + } + } + else + { + for (int j = 0; j < this.segments; j++) + { + int num6 = Mathf.Min((int)Mathf.Round((float)j / (float)this.segments * (float)other.segments), other.segments); + int num7 = Mathf.Min((int)Mathf.Round((float)(j + 1) / (float)this.segments * (float)other.segments), other.segments); + int num8 = Mathf.Min(j + 1, this.segments); + int num9 = num6 + other.vertOffset; + int num10 = j + this.vertOffset; + int v = num7 + other.vertOffset; + int num11 = j + this.vertOffset; + int num12 = num8 + this.vertOffset; + int v2 = num7 + other.vertOffset; + if (flipTris) + { + int num13 = num10; + num10 = num9; + num9 = num13; + num13 = num12; + num12 = num11; + num11 = num13; + } + tris.Add(new TreeTriangle(materialIndex, num9, num10, v, false, true, false)); + tris.Add(new TreeTriangle(materialIndex, num11, num12, v2, false, true, false)); + } + } + } + } +} diff --git a/UnityEditor/TreeEditor/SmoothRandom.cs b/UnityEditor/TreeEditor/SmoothRandom.cs new file mode 100644 index 00000000..68c6276d --- /dev/null +++ b/UnityEditor/TreeEditor/SmoothRandom.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + public class SmoothRandom + { + private static FractalNoise s_Noise; + public static Vector3 GetVector3(float speed) + { + float x = Time.time * 0.01f * speed; + return new Vector3(SmoothRandom.Get().HybridMultifractal(x, 15.73f, 0.58f), SmoothRandom.Get().HybridMultifractal(x, 63.94f, 0.58f), SmoothRandom.Get().HybridMultifractal(x, 0.2f, 0.58f)); + } + public static float Get(float speed) + { + float num = Time.time * 0.01f * speed; + return SmoothRandom.Get().HybridMultifractal(num * 0.01f, 15.7f, 0.65f); + } + private static FractalNoise Get() + { + if (SmoothRandom.s_Noise == null) + { + SmoothRandom.s_Noise = new FractalNoise(1.27f, 2.04f, 8.36f); + } + return SmoothRandom.s_Noise; + } + } +} diff --git a/UnityEditor/TreeEditor/SplineNode.cs b/UnityEditor/TreeEditor/SplineNode.cs new file mode 100644 index 00000000..f35d390a --- /dev/null +++ b/UnityEditor/TreeEditor/SplineNode.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class SplineNode + { + public Vector3 point = Vector3.zero; + public Quaternion rot = Quaternion.identity; + public Vector3 normal = Vector3.zero; + public Vector3 tangent = Vector3.zero; + public float time; + public SplineNode(Vector3 p, float t) + { + this.point = p; + this.time = t; + } + public SplineNode(SplineNode o) + { + this.point = o.point; + this.rot = o.rot; + this.normal = o.normal; + this.tangent = o.tangent; + this.time = o.time; + } + } +} diff --git a/UnityEditor/TreeEditor/TextureAtlas.cs b/UnityEditor/TreeEditor/TextureAtlas.cs new file mode 100644 index 00000000..c3745dff --- /dev/null +++ b/UnityEditor/TreeEditor/TextureAtlas.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace TreeEditor +{ + public class TextureAtlas + { + public class TextureNode + { + public string name; + public Texture2D diffuseTexture; + public Color diffuseColor; + public Texture2D normalTexture; + public Texture2D glossTexture; + public Texture2D translucencyTexture; + public Texture2D shadowOffsetTexture; + public float shininess; + public Vector2 scale = new Vector2(1f, 1f); + public bool tileV; + public Vector2 uvTiling; + public Rect sourceRect = new Rect(0f, 0f, 0f, 0f); + public Rect packedRect = new Rect(0f, 0f, 0f, 0f); + public Rect uvRect = new Rect(0f, 0f, 0f, 0f); + public static bool Overlap(TextureAtlas.TextureNode a, TextureAtlas.TextureNode b) + { + if (a.tileV || b.tileV) + { + return a.packedRect.x <= b.packedRect.x + b.packedRect.width && a.packedRect.x + a.packedRect.width >= b.packedRect.x; + } + return a.packedRect.x <= b.packedRect.x + b.packedRect.width && a.packedRect.x + a.packedRect.width >= b.packedRect.x && a.packedRect.y <= b.packedRect.y + b.packedRect.height && a.packedRect.y + a.packedRect.height >= b.packedRect.y; + } + public int CompareTo(TextureAtlas.TextureNode b) + { + if (this.tileV && b.tileV) + { + return -this.packedRect.width.CompareTo(b.packedRect.width); + } + if (this.tileV) + { + return -1; + } + if (b.tileV) + { + return 1; + } + return -this.packedRect.height.CompareTo(b.packedRect.height); + } + } + public int atlasWidth; + public int atlasHeight; + public int atlasPadding; + public List nodes = new List(); + public override int GetHashCode() + { + int num = 0; + for (int i = 0; i < this.nodes.Count; i++) + { + num ^= this.nodes[i].uvRect.GetHashCode(); + } + return num; + } + public void AddTexture(string name, Texture2D diffuse, Color diffuseColor, Texture2D normal, Texture2D gloss, Texture2D transtex, Texture2D shadowOffsetTex, float shininess, Vector2 scale, bool tileV, Vector2 uvTiling) + { + TextureAtlas.TextureNode textureNode = new TextureAtlas.TextureNode(); + textureNode.name = name; + textureNode.diffuseTexture = diffuse; + textureNode.diffuseColor = diffuseColor; + textureNode.normalTexture = normal; + textureNode.glossTexture = gloss; + textureNode.translucencyTexture = transtex; + textureNode.shadowOffsetTexture = shadowOffsetTex; + textureNode.shininess = shininess; + textureNode.scale = scale; + textureNode.tileV = tileV; + textureNode.uvTiling = uvTiling; + if (diffuse) + { + textureNode.sourceRect.width = (float)diffuse.width; + textureNode.sourceRect.height = (float)diffuse.height; + } + else + { + textureNode.sourceRect.width = 64f; + textureNode.sourceRect.height = 64f; + textureNode.scale = new Vector2(1f, 1f); + } + this.nodes.Add(textureNode); + } + public Vector2 GetTexTiling(string name) + { + for (int i = 0; i < this.nodes.Count; i++) + { + if (this.nodes[i].name == name) + { + return this.nodes[i].uvTiling; + } + } + return new Vector2(1f, 1f); + } + public Rect GetUVRect(string name) + { + for (int i = 0; i < this.nodes.Count; i++) + { + if (this.nodes[i].name == name) + { + return this.nodes[i].uvRect; + } + } + return new Rect(0f, 0f, 0f, 0f); + } + public void Pack(ref int targetWidth, int targetHeight, int padding, bool correctPow2) + { + if (padding % 2 != 0) + { + Debug.LogWarning("Padding not an even number"); + padding++; + } + for (int i = 0; i < this.nodes.Count; i++) + { + TextureAtlas.TextureNode textureNode = this.nodes[i]; + textureNode.packedRect.x = 0f; + textureNode.packedRect.y = 0f; + textureNode.packedRect.width = Mathf.Round(textureNode.sourceRect.width * textureNode.scale.x); + textureNode.packedRect.height = Mathf.Min((float)targetHeight, Mathf.Round(textureNode.sourceRect.height * textureNode.scale.y)); + if (textureNode.tileV) + { + textureNode.packedRect.height = (float)targetHeight; + } + if (correctPow2) + { + textureNode.packedRect.width = (float)Mathf.ClosestPowerOfTwo((int)textureNode.packedRect.width); + textureNode.packedRect.height = (float)Mathf.ClosestPowerOfTwo((int)textureNode.packedRect.height); + } + } + this.nodes.Sort((TextureAtlas.TextureNode a, TextureAtlas.TextureNode b) => a.CompareTo(b)); + int num = 0; + int num2 = 0; + for (int j = 0; j < this.nodes.Count; j++) + { + TextureAtlas.TextureNode textureNode2 = this.nodes[j]; + bool flag = false; + for (int k = 0; k < num; k++) + { + textureNode2.packedRect.x = (float)k; + textureNode2.packedRect.y = 0f; + flag = true; + for (int l = 0; l <= num2; l++) + { + flag = true; + textureNode2.packedRect.y = (float)l; + for (int m = 0; m < j; m++) + { + TextureAtlas.TextureNode textureNode3 = this.nodes[m]; + if (TextureAtlas.TextureNode.Overlap(textureNode2, textureNode3)) + { + flag = false; + if (textureNode3.tileV) + { + l = num2; + } + else + { + l = (int)(textureNode3.packedRect.y + textureNode3.packedRect.height); + } + break; + } + } + if (flag) + { + break; + } + } + if (flag) + { + break; + } + } + if (!flag) + { + textureNode2.packedRect.x = (float)num; + textureNode2.packedRect.y = 0f; + } + num = Mathf.Max(num, (int)(textureNode2.packedRect.x + textureNode2.packedRect.width)); + num2 = Mathf.Max(num2, (int)(textureNode2.packedRect.y + textureNode2.packedRect.height)); + } + int min = Mathf.Max(Mathf.ClosestPowerOfTwo(padding * 2), 64); + int num3 = Mathf.Clamp(Mathf.ClosestPowerOfTwo(num), min, targetWidth); + targetWidth = num3; + this.atlasWidth = targetWidth; + this.atlasHeight = targetHeight; + this.atlasPadding = padding; + float num4 = (float)targetWidth / (float)num; + float num5 = (float)targetHeight / (float)num2; + for (int n = 0; n < this.nodes.Count; n++) + { + TextureAtlas.TextureNode textureNode4 = this.nodes[n]; + TextureAtlas.TextureNode expr_32A_cp_0 = textureNode4; + expr_32A_cp_0.packedRect.x = expr_32A_cp_0.packedRect.x * num4; + TextureAtlas.TextureNode expr_33F_cp_0 = textureNode4; + expr_33F_cp_0.packedRect.y = expr_33F_cp_0.packedRect.y * num5; + TextureAtlas.TextureNode expr_354_cp_0 = textureNode4; + expr_354_cp_0.packedRect.width = expr_354_cp_0.packedRect.width * num4; + TextureAtlas.TextureNode expr_369_cp_0 = textureNode4; + expr_369_cp_0.packedRect.height = expr_369_cp_0.packedRect.height * num5; + if (textureNode4.tileV) + { + textureNode4.packedRect.y = 0f; + textureNode4.packedRect.height = (float)targetHeight; + TextureAtlas.TextureNode expr_3A9_cp_0 = textureNode4; + expr_3A9_cp_0.packedRect.x = expr_3A9_cp_0.packedRect.x + (float)(padding / 2); + TextureAtlas.TextureNode expr_3C0_cp_0 = textureNode4; + expr_3C0_cp_0.packedRect.width = expr_3C0_cp_0.packedRect.width - (float)padding; + } + else + { + TextureAtlas.TextureNode expr_3DA_cp_0 = textureNode4; + expr_3DA_cp_0.packedRect.x = expr_3DA_cp_0.packedRect.x + (float)(padding / 2); + TextureAtlas.TextureNode expr_3F1_cp_0 = textureNode4; + expr_3F1_cp_0.packedRect.y = expr_3F1_cp_0.packedRect.y + (float)(padding / 2); + TextureAtlas.TextureNode expr_408_cp_0 = textureNode4; + expr_408_cp_0.packedRect.width = expr_408_cp_0.packedRect.width - (float)padding; + TextureAtlas.TextureNode expr_41D_cp_0 = textureNode4; + expr_41D_cp_0.packedRect.height = expr_41D_cp_0.packedRect.height - (float)padding; + } + if (textureNode4.packedRect.width < 1f) + { + textureNode4.packedRect.width = 1f; + } + if (textureNode4.packedRect.height < 1f) + { + textureNode4.packedRect.height = 1f; + } + textureNode4.packedRect.x = Mathf.Round(textureNode4.packedRect.x); + textureNode4.packedRect.y = Mathf.Round(textureNode4.packedRect.y); + textureNode4.packedRect.width = Mathf.Round(textureNode4.packedRect.width); + textureNode4.packedRect.height = Mathf.Round(textureNode4.packedRect.height); + textureNode4.uvRect.x = textureNode4.packedRect.x / (float)targetWidth; + textureNode4.uvRect.y = textureNode4.packedRect.y / (float)targetHeight; + textureNode4.uvRect.width = textureNode4.packedRect.width / (float)targetWidth; + textureNode4.uvRect.height = textureNode4.packedRect.height / (float)targetHeight; + } + } + } +} diff --git a/UnityEditor/TreeEditor/TreeAOSphere.cs b/UnityEditor/TreeEditor/TreeAOSphere.cs new file mode 100644 index 00000000..0567c1bc --- /dev/null +++ b/UnityEditor/TreeEditor/TreeAOSphere.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + public class TreeAOSphere + { + public bool flag; + public float area; + public float radius; + public float density = 1f; + public Vector3 position; + public TreeAOSphere(Vector3 pos, float radius, float density) + { + this.position = pos; + this.radius = radius; + this.area = radius * radius; + this.density = density; + } + public float PointOcclusion(Vector3 pos, Vector3 nor) + { + Vector3 rhs = this.position - pos; + float sqrMagnitude = rhs.sqrMagnitude; + float num = Mathf.Max(0f, sqrMagnitude - this.area); + if (sqrMagnitude > 1.401298E-45f) + { + rhs.Normalize(); + } + return (1f - 1f / Mathf.Sqrt(this.area / num + 1f)) * Mathf.Clamp01(4f * Vector3.Dot(nor, rhs)); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeAttribute.cs b/UnityEditor/TreeEditor/TreeAttribute.cs new file mode 100644 index 00000000..8387afaa --- /dev/null +++ b/UnityEditor/TreeEditor/TreeAttribute.cs @@ -0,0 +1,112 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class TreeAttribute : Attribute + { + public string uiLabel; + public string uiGadget; + public string uiCurve; + public string uiRequirement; + public GUIContent[] uiOptions; + public float uiCurveMin; + public float uiCurveMax; + public float uiMin; + public float uiMax; + public TreeAttribute(string uiLabel, string uiGadget, float uiMin, float uiMax) + { + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiMin = uiMin; + this.uiMax = uiMax; + this.uiCurve = string.Empty; + this.uiRequirement = string.Empty; + } + public TreeAttribute(string uiLabel, string uiGadget, float uiMin, float uiMax, string uiRequirement) + { + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiMin = uiMin; + this.uiMax = uiMax; + this.uiCurve = string.Empty; + this.uiRequirement = uiRequirement; + } + public TreeAttribute(string uiLabel, string uiGadget, float uiMin, float uiMax, string uiCurve, float uiCurveMin, float uiCurveMax) + { + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiMin = uiMin; + this.uiMax = uiMax; + this.uiCurve = uiCurve; + this.uiCurveMin = uiCurveMin; + this.uiCurveMax = uiCurveMax; + this.uiRequirement = string.Empty; + } + public TreeAttribute(string uiLabel, string uiGadget, float uiMin, float uiMax, string uiCurve, float uiCurveMin, float uiCurveMax, string uiRequirement) + { + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiMin = uiMin; + this.uiMax = uiMax; + this.uiCurve = uiCurve; + this.uiCurveMin = uiCurveMin; + this.uiCurveMax = uiCurveMax; + this.uiRequirement = uiRequirement; + } + public TreeAttribute(string uiLabel, string uiGadget, string uiOptions) + { + char[] separator = new char[] + { + ',' + }; + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiRequirement = uiOptions; + string[] array = uiOptions.Split(separator); + this.uiOptions = new GUIContent[array.Length]; + for (int i = 0; i < array.Length; i++) + { + this.uiOptions[i] = new GUIContent(array[i]); + } + } + public TreeAttribute(string uiLabel, string uiGadget, string uiOptions, string uiCurve, float uiCurveMin, float uiCurveMax, string uiRequirement) + { + char[] separator = new char[] + { + ',' + }; + this.uiLabel = uiLabel; + this.uiGadget = uiGadget; + this.uiRequirement = uiRequirement; + this.uiCurve = uiCurve; + this.uiCurveMin = uiCurveMin; + this.uiCurveMax = uiCurveMax; + string[] array = uiOptions.Split(separator); + this.uiOptions = new GUIContent[array.Length]; + for (int i = 0; i < array.Length; i++) + { + this.uiOptions[i] = new GUIContent(array[i]); + } + } + public override string ToString() + { + string text = string.Concat(new object[] + { + "uiLabel: ", + this.uiLabel, + ", uiGadget: ", + this.uiGadget, + ", uiMin: ", + this.uiMin, + ", uiMax: ", + this.uiMax + }); + if (this.uiCurve != string.Empty) + { + text = text + ", uiCurve: " + this.uiCurve; + } + return text; + } + } +} diff --git a/UnityEditor/TreeEditor/TreeData.cs b/UnityEditor/TreeEditor/TreeData.cs new file mode 100644 index 00000000..992abd98 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeData.cs @@ -0,0 +1,1203 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +namespace TreeEditor +{ + public class TreeData : ScriptableObject + { + [SerializeField] + private int _uniqueID; + public string materialHash; + public TreeGroupRoot root; + public TreeGroupBranch[] branchGroups; + public TreeGroupLeaf[] leafGroups; + public TreeNode[] nodes; + public Mesh mesh; + public Material optimizedSolidMaterial; + public Material optimizedCutoutMaterial; + public bool isInPreviewMode; + public TreeGroup GetGroup(int id) + { + if (id == this.root.uniqueID) + { + return this.root; + } + for (int i = 0; i < this.branchGroups.Length; i++) + { + if (this.branchGroups[i].uniqueID == id) + { + return this.branchGroups[i]; + } + } + for (int j = 0; j < this.leafGroups.Length; j++) + { + if (this.leafGroups[j].uniqueID == id) + { + return this.leafGroups[j]; + } + } + return null; + } + public TreeNode GetNode(int id) + { + for (int i = 0; i < this.nodes.Length; i++) + { + if (this.nodes[i].uniqueID == id) + { + return this.nodes[i]; + } + } + return null; + } + private int GetNodeCount() + { + return this.nodes.Length; + } + private TreeNode GetNodeAt(int i) + { + if (i >= 0 && i < this.nodes.Length) + { + return this.nodes[i]; + } + return null; + } + private int GetGroupCount() + { + return 1 + this.branchGroups.Length + this.leafGroups.Length; + } + private TreeGroup GetGroupAt(int i) + { + if (i == 0) + { + return this.root; + } + i--; + if (i >= 0 && i < this.branchGroups.Length) + { + return this.branchGroups[i]; + } + i -= this.branchGroups.Length; + if (i >= 0 && i < this.leafGroups.Length) + { + return this.leafGroups[i]; + } + return null; + } + public void ValidateReferences() + { + Profiler.BeginSample("ValidateReferences"); + int groupCount = this.GetGroupCount(); + for (int i = 0; i < groupCount; i++) + { + TreeGroup groupAt = this.GetGroupAt(i); + groupAt.parentGroup = this.GetGroup(groupAt.parentGroupID); + groupAt.childGroups.Clear(); + groupAt.nodes.Clear(); + for (int j = 0; j < groupAt.childGroupIDs.Length; j++) + { + TreeGroup group = this.GetGroup(groupAt.childGroupIDs[j]); + groupAt.childGroups.Add(group); + } + for (int k = 0; k < groupAt.nodeIDs.Length; k++) + { + TreeNode node = this.GetNode(groupAt.nodeIDs[k]); + groupAt.nodes.Add(node); + } + } + int nodeCount = this.GetNodeCount(); + for (int l = 0; l < nodeCount; l++) + { + TreeNode nodeAt = this.GetNodeAt(l); + nodeAt.parent = this.GetNode(nodeAt.parentID); + nodeAt.group = this.GetGroup(nodeAt.groupID); + } + Profiler.EndSample(); + } + public void ClearReferences() + { + for (int i = 0; i < this.branchGroups.Length; i++) + { + this.branchGroups[i].parentGroup = null; + this.branchGroups[i].childGroups.Clear(); + this.branchGroups[i].nodes.Clear(); + } + for (int j = 0; j < this.leafGroups.Length; j++) + { + this.leafGroups[j].parentGroup = null; + this.leafGroups[j].childGroups.Clear(); + this.leafGroups[j].nodes.Clear(); + } + for (int k = 0; k < this.nodes.Length; k++) + { + this.nodes[k].parent = null; + this.nodes[k].group = null; + } + } + public TreeGroup AddGroup(TreeGroup parent, Type type) + { + TreeGroup treeGroup; + if (type == typeof(TreeGroupBranch)) + { + treeGroup = new TreeGroupBranch(); + this.branchGroups = this.ArrayAdd(this.branchGroups, treeGroup as TreeGroupBranch); + } + else + { + if (type != typeof(TreeGroupLeaf)) + { + return null; + } + treeGroup = new TreeGroupLeaf(); + this.leafGroups = this.ArrayAdd(this.leafGroups, treeGroup as TreeGroupLeaf); + } + treeGroup.uniqueID = this._uniqueID; + this._uniqueID++; + treeGroup.parentGroupID = 0; + treeGroup.distributionFrequency = 1; + this.SetGroupParent(treeGroup, parent); + return treeGroup; + } + private void CopyFields(object n, object n2) + { + if (n.GetType() != n2.GetType()) + { + return; + } + FieldInfo[] fields = n.GetType().GetFields(); + for (int i = 0; i < fields.Length; i++) + { + if (fields[i].IsPublic) + { + if (fields[i].FieldType == typeof(TreeSpline)) + { + TreeSpline o = fields[i].GetValue(n) as TreeSpline; + fields[i].SetValue(n2, new TreeSpline(o)); + } + else + { + if (fields[i].FieldType == typeof(AnimationCurve)) + { + AnimationCurve animationCurve = fields[i].GetValue(n) as AnimationCurve; + AnimationCurve animationCurve2 = new AnimationCurve(animationCurve.keys); + animationCurve2.postWrapMode = animationCurve.postWrapMode; + animationCurve2.preWrapMode = animationCurve.preWrapMode; + fields[i].SetValue(n2, animationCurve2); + } + else + { + fields[i].SetValue(n2, fields[i].GetValue(n)); + } + } + } + } + } + public TreeGroup DuplicateGroup(TreeGroup g) + { + TreeGroup treeGroup = this.AddGroup(this.GetGroup(g.parentGroupID), g.GetType()); + this.CopyFields(g, treeGroup); + treeGroup.childGroupIDs = new int[0]; + treeGroup.nodeIDs = new int[0]; + for (int i = 0; i < g.nodeIDs.Length; i++) + { + TreeNode node = this.GetNode(g.nodeIDs[i]); + TreeNode treeNode = this.AddNode(treeGroup, this.GetNode(node.parentID)); + this.CopyFields(node, treeNode); + treeNode.groupID = treeGroup.uniqueID; + } + return treeGroup; + } + public void DeleteGroup(TreeGroup g) + { + for (int i = g.nodes.Count - 1; i >= 0; i--) + { + this.DeleteNode(g.nodes[i], false); + } + if (g.GetType() == typeof(TreeGroupBranch)) + { + this.branchGroups = this.ArrayRemove(this.branchGroups, g as TreeGroupBranch); + } + else + { + if (g.GetType() == typeof(TreeGroupLeaf)) + { + this.leafGroups = this.ArrayRemove(this.leafGroups, g as TreeGroupLeaf); + } + } + this.SetGroupParent(g, null); + } + public void SetGroupParent(TreeGroup g, TreeGroup parent) + { + TreeGroup group = this.GetGroup(g.parentGroupID); + if (group != null) + { + group.childGroupIDs = this.ArrayRemove(group.childGroupIDs, g.uniqueID); + group.childGroups.Remove(g); + } + if (parent != null) + { + g.parentGroup = parent; + g.parentGroupID = parent.uniqueID; + parent.childGroups.Add(g); + parent.childGroupIDs = this.ArrayAdd(parent.childGroupIDs, g.uniqueID); + } + else + { + g.parentGroup = null; + g.parentGroupID = 0; + } + this.ValidateReferences(); + this.UpdateFrequency(g.uniqueID); + } + public void LockGroup(TreeGroup g) + { + g.Lock(); + } + public void UnlockGroup(TreeGroup g) + { + g.Unlock(); + this.UpdateFrequency(g.uniqueID); + } + public bool IsAncestor(TreeGroup ancestor, TreeGroup g) + { + if (g == null) + { + return false; + } + for (TreeGroup group = this.GetGroup(g.parentGroupID); group != null; group = this.GetGroup(group.parentGroupID)) + { + if (group == ancestor) + { + return true; + } + } + return false; + } + public TreeNode AddNode(TreeGroup g, TreeNode parent) + { + return this.AddNode(g, parent, true); + } + public TreeNode AddNode(TreeGroup g, TreeNode parent, bool validate) + { + if (g == null) + { + return null; + } + TreeNode treeNode = new TreeNode(); + treeNode.uniqueID = this._uniqueID; + this._uniqueID++; + this.SetNodeParent(treeNode, parent); + treeNode.groupID = g.uniqueID; + treeNode.group = g; + g.nodeIDs = this.ArrayAdd(g.nodeIDs, treeNode.uniqueID); + g.nodes.Add(treeNode); + this.nodes = this.ArrayAdd(this.nodes, treeNode); + if (validate) + { + this.ValidateReferences(); + } + return treeNode; + } + public void SetNodeParent(TreeNode n, TreeNode parent) + { + if (parent != null) + { + n.parentID = parent.uniqueID; + n.parent = parent; + } + else + { + n.parentID = 0; + n.parent = null; + } + } + public void DeleteNode(TreeNode n) + { + this.DeleteNode(n, true); + } + public void DeleteNode(TreeNode n, bool validate) + { + TreeGroup group = this.GetGroup(n.groupID); + if (group != null) + { + group.nodeIDs = this.ArrayRemove(group.nodeIDs, n.uniqueID); + group.nodes.Remove(n); + for (int i = 0; i < group.childGroups.Count; i++) + { + TreeGroup treeGroup = group.childGroups[i]; + for (int j = treeGroup.nodes.Count - 1; j >= 0; j--) + { + if (treeGroup.nodes[j] != null && treeGroup.nodes[j].parentID == n.uniqueID) + { + this.DeleteNode(treeGroup.nodes[j], false); + } + } + } + } + n.group = null; + n.groupID = 0; + n.parent = null; + n.parentID = 0; + this.nodes = this.ArrayRemove(this.nodes, n); + if (validate) + { + this.ValidateReferences(); + } + } + public TreeNode DuplicateNode(TreeNode n) + { + TreeGroup group = this.GetGroup(n.groupID); + if (group == null) + { + return null; + } + TreeNode treeNode = this.AddNode(group, this.GetNode(n.parentID)); + this.CopyFields(n, treeNode); + return treeNode; + } + public void Initialize() + { + if (this.root == null) + { + this.branchGroups = new TreeGroupBranch[0]; + this.leafGroups = new TreeGroupLeaf[0]; + this.nodes = new TreeNode[0]; + this._uniqueID = 1; + this.root = new TreeGroupRoot(); + this.root.uniqueID = this._uniqueID; + this.root.distributionFrequency = 1; + this._uniqueID++; + this.UpdateFrequency(this.root.uniqueID); + this.AddGroup(this.root, typeof(TreeGroupBranch)); + } + } + public void UpdateSeed(int id) + { + TreeGroup group = this.GetGroup(id); + if (group == null) + { + return; + } + int seed = UnityEngine.Random.seed; + this.ClearReferences(); + this.ValidateReferences(); + group.UpdateSeed(); + group.UpdateDistribution(true, true); + this.ClearReferences(); + UnityEngine.Random.seed = seed; + } + public void UpdateFrequency(int id) + { + TreeGroup group = this.GetGroup(id); + if (group == null) + { + return; + } + int seed = UnityEngine.Random.seed; + this.ClearReferences(); + this.ValidateReferences(); + group.UpdateFrequency(this); + this.ClearReferences(); + UnityEngine.Random.seed = seed; + } + public void UpdateDistribution(int id) + { + TreeGroup group = this.GetGroup(id); + if (group == null) + { + return; + } + int seed = UnityEngine.Random.seed; + this.ClearReferences(); + this.ValidateReferences(); + group.UpdateDistribution(true, true); + this.ClearReferences(); + UnityEngine.Random.seed = seed; + } + public static int GetAdaptiveHeightSegments(float h, float adaptiveQuality) + { + return (int)Mathf.Max(h * adaptiveQuality, 2f); + } + public static int GetAdaptiveRadialSegments(float r, float adaptiveQuality) + { + int value = (int)(r * 24f * adaptiveQuality) / 2 * 2; + return Mathf.Clamp(value, 4, 32); + } + public static List GetAdaptiveSamples(TreeGroup group, TreeNode node, float adaptiveQuality) + { + List list = new List(); + if (node.spline == null) + { + return list; + } + float num = 1f - node.capRange; + SplineNode[] array = node.spline.GetNodes(); + for (int i = 0; i < array.Length; i++) + { + if (array[i].time >= node.breakOffset) + { + list.Add(node.breakOffset); + break; + } + if (array[i].time > num) + { + list.Add(num); + break; + } + list.Add(array[i].time); + } + list.Sort(); + if (list.Count < 2) + { + return list; + } + float num2 = 1f; + if (group.GetType() == typeof(TreeGroupBranch)) + { + num2 = ((TreeGroupBranch)group).radius; + } + float num3 = Mathf.Lerp(0.999f, 0.99999f, adaptiveQuality); + float num4 = Mathf.Lerp(0.5f, 0.985f, adaptiveQuality); + float num5 = Mathf.Lerp(0.3f * num2, 0.1f * num2, adaptiveQuality); + int num6 = 200; + int j = 0; + while (j < list.Count - 1) + { + for (int k = j; k < list.Count - 1; k++) + { + Quaternion rotationAtTime = node.spline.GetRotationAtTime(list[k]); + Quaternion rotationAtTime2 = node.spline.GetRotationAtTime(list[k + 1]); + Vector3 lhs = rotationAtTime * Vector3.up; + Vector3 rhs = rotationAtTime2 * Vector3.up; + Vector3 lhs2 = rotationAtTime * Vector3.right; + Vector3 rhs2 = rotationAtTime2 * Vector3.right; + Vector3 lhs3 = rotationAtTime * Vector3.forward; + Vector3 rhs3 = rotationAtTime2 * Vector3.forward; + float radiusAtTime = group.GetRadiusAtTime(node, list[k], true); + float radiusAtTime2 = group.GetRadiusAtTime(node, list[k + 1], true); + bool flag = false; + if (Vector3.Dot(lhs, rhs) < num4) + { + flag = true; + } + if (Vector3.Dot(lhs2, rhs2) < num4) + { + flag = true; + } + if (Vector3.Dot(lhs3, rhs3) < num4) + { + flag = true; + } + if (Mathf.Abs(radiusAtTime - radiusAtTime2) > num5) + { + flag = true; + } + if (flag) + { + num6--; + if (num6 > 0) + { + float item = (list[k] + list[k + 1]) * 0.5f; + list.Insert(k + 1, item); + break; + } + } + j = k + 1; + } + } + for (int l = 0; l < list.Count - 2; l++) + { + Vector3 positionAtTime = node.spline.GetPositionAtTime(list[l]); + Vector3 positionAtTime2 = node.spline.GetPositionAtTime(list[l + 1]); + Vector3 positionAtTime3 = node.spline.GetPositionAtTime(list[l + 2]); + float radiusAtTime3 = group.GetRadiusAtTime(node, list[l], true); + float radiusAtTime4 = group.GetRadiusAtTime(node, list[l + 1], true); + float radiusAtTime5 = group.GetRadiusAtTime(node, list[l + 2], true); + Vector3 normalized = (positionAtTime2 - positionAtTime).normalized; + Vector3 normalized2 = (positionAtTime3 - positionAtTime).normalized; + bool flag2 = false; + if (Vector3.Dot(normalized, normalized2) >= num3) + { + flag2 = true; + } + if (Mathf.Abs(radiusAtTime3 - radiusAtTime4) > num5) + { + flag2 = false; + } + if (Mathf.Abs(radiusAtTime4 - radiusAtTime5) > num5) + { + flag2 = false; + } + if (flag2) + { + list.RemoveAt(l + 1); + l--; + } + } + if (node.capRange > 0f) + { + int num7 = 1 + Mathf.CeilToInt(node.capRange * 16f * adaptiveQuality); + for (int m = 0; m < num7; m++) + { + float f = (float)(m + 1) / (float)num7 * 3.14159274f * 0.5f; + float num8 = Mathf.Sin(f); + float num9 = num + node.capRange * num8; + if (num9 < node.breakOffset) + { + list.Add(num9); + } + } + list.Sort(); + } + if (1f <= node.breakOffset) + { + if (list[list.Count - 1] < 1f) + { + list.Add(1f); + } + else + { + list[list.Count - 1] = 1f; + } + } + return list; + } + public void PreviewMesh(Matrix4x4 worldToLocalMatrix, out Material[] outMaterials) + { + outMaterials = null; + if (!this.mesh) + { + Debug.LogError("TreeData must have mesh assigned"); + return; + } + bool enableAmbientOcclusion = this.root.enableAmbientOcclusion; + float adaptiveLODQuality = this.root.adaptiveLODQuality; + this.root.enableMaterialOptimize = false; + this.root.enableWelding = false; + this.root.enableAmbientOcclusion = false; + this.root.adaptiveLODQuality = 0f; + this.UpdateMesh(worldToLocalMatrix, out outMaterials); + this.root.enableWelding = true; + this.root.enableMaterialOptimize = true; + this.root.enableAmbientOcclusion = enableAmbientOcclusion; + this.root.adaptiveLODQuality = adaptiveLODQuality; + this.isInPreviewMode = true; + } + public void UpdateMesh(Matrix4x4 worldToLocalMatrix, out Material[] outMaterials) + { + outMaterials = null; + if (!this.mesh) + { + Debug.LogError("TreeData must have mesh assigned"); + return; + } + this.isInPreviewMode = false; + List materials = new List(); + List list = new List(); + List list2 = new List(); + List aoSpheres = new List(); + int num = 0; + if (this.root.enableAmbientOcclusion) + { + num |= 1; + } + if (this.root.enableWelding) + { + num |= 2; + } + this.UpdateMesh(worldToLocalMatrix, materials, list, list2, aoSpheres, num, this.root.adaptiveLODQuality, this.root.aoDensity); + if (list.Count > 65000) + { + Debug.LogWarning("Tree mesh would exceed maximum vertex limit .. aborting"); + return; + } + this.mesh.Clear(); + if (list.Count == 0 || list2.Count == 0) + { + return; + } + this.OptimizeMaterial(materials, list, list2); + Profiler.BeginSample("CopyMeshData"); + Vector3[] array = new Vector3[list.Count]; + Vector3[] array2 = new Vector3[list.Count]; + Vector2[] array3 = new Vector2[list.Count]; + Vector2[] array4 = new Vector2[list.Count]; + Vector4[] array5 = new Vector4[list.Count]; + Color[] array6 = new Color[list.Count]; + for (int i = 0; i < list.Count; i++) + { + array[i] = list[i].pos; + array2[i] = list[i].nor; + array3[i] = list[i].uv0; + array4[i] = list[i].uv1; + array5[i] = list[i].tangent; + array6[i] = list[i].color; + } + this.mesh.vertices = array; + this.mesh.normals = array2; + this.mesh.uv = array3; + this.mesh.uv1 = array4; + this.mesh.tangents = array5; + this.mesh.colors = array6; + int[] array7 = new int[list2.Count * 3]; + List list3 = new List(2); + this.mesh.subMeshCount = 2; + for (int j = 0; j < 2; j++) + { + int num2 = 0; + for (int k = 0; k < list2.Count; k++) + { + if (list2[k].materialIndex == j) + { + array7[num2] = list2[k].v[0]; + array7[num2 + 1] = list2[k].v[1]; + array7[num2 + 2] = list2[k].v[2]; + num2 += 3; + } + } + if (num2 > 0) + { + int[] array8 = new int[num2]; + for (int l = 0; l < num2; l++) + { + array8[l] = array7[l]; + } + this.mesh.SetTriangles(array8, list3.Count); + if (j == 0) + { + list3.Add(this.optimizedSolidMaterial); + } + else + { + list3.Add(this.optimizedCutoutMaterial); + } + } + } + outMaterials = list3.ToArray(); + this.mesh.subMeshCount = list3.Count; + Profiler.EndSample(); + this.mesh.RecalculateBounds(); + } + private static void ExtractOptimizedShaders(List materials, out Shader optimizedSolidShader, out Shader optimizedCutoutShader) + { + List list = new List(); + List list2 = new List(); + foreach (TreeMaterial current in materials) + { + Material material = current.material; + if (material && material.shader) + { + if (TreeEditorHelper.IsTreeBarkShader(material.shader)) + { + list.Add(material.shader); + } + else + { + if (TreeEditorHelper.IsTreeLeafShader(material.shader)) + { + list2.Add(material.shader); + } + } + } + } + optimizedSolidShader = null; + optimizedCutoutShader = null; + if (list.Count > 0) + { + optimizedSolidShader = Shader.Find(TreeEditorHelper.GetOptimizedShaderName(list[0])); + } + if (list2.Count > 0) + { + optimizedCutoutShader = Shader.Find(TreeEditorHelper.GetOptimizedShaderName(list2[0])); + } + if (!optimizedSolidShader) + { + optimizedSolidShader = TreeEditorHelper.DefaultOptimizedBarkShader; + } + if (!optimizedCutoutShader) + { + optimizedCutoutShader = TreeEditorHelper.DefaultOptimizedLeafShader; + } + } + public bool OptimizeMaterial(List materials, List vertices, List triangles) + { + if (!this.optimizedSolidMaterial || !this.optimizedCutoutMaterial) + { + Debug.LogError("Optimized materials haven't been assigned"); + return false; + } + Shader shader; + Shader shader2; + TreeData.ExtractOptimizedShaders(materials, out shader, out shader2); + this.optimizedSolidMaterial.shader = shader; + this.optimizedCutoutMaterial.shader = shader2; + int num = 1024; + int num2 = 1024; + int padding = 32; + Profiler.BeginSample("OptimizeMaterial"); + float[] array = new float[materials.Count]; + float num3 = 0f; + float num4 = 0f; + for (int i = 0; i < materials.Count; i++) + { + if (!materials[i].tileV) + { + num4 += 1f; + } + else + { + num3 += 1f; + } + } + for (int j = 0; j < materials.Count; j++) + { + if (materials[j].tileV) + { + array[j] = 1f; + } + else + { + array[j] = 1f / num4; + } + } + TextureAtlas textureAtlas = new TextureAtlas(); + for (int k = 0; k < materials.Count; k++) + { + Texture2D texture2D = null; + Texture2D normal = null; + Texture2D gloss = null; + Texture2D transtex = null; + Texture2D shadowOffsetTex = null; + Color color = new Color(1f, 1f, 1f, 1f); + float num5 = 0.03f; + Vector2 textureScale = new Vector2(1f, 1f); + Material material = materials[k].material; + if (material) + { + if (material.HasProperty("_Color")) + { + color = material.GetColor("_Color"); + } + if (material.HasProperty("_MainTex")) + { + texture2D = (material.mainTexture as Texture2D); + textureScale = material.GetTextureScale("_MainTex"); + } + if (material.HasProperty("_BumpMap")) + { + normal = (material.GetTexture("_BumpMap") as Texture2D); + } + if (material.HasProperty("_GlossMap")) + { + gloss = (material.GetTexture("_GlossMap") as Texture2D); + } + if (material.HasProperty("_TranslucencyMap")) + { + transtex = (material.GetTexture("_TranslucencyMap") as Texture2D); + } + if (material.HasProperty("_Shininess")) + { + num5 = material.GetFloat("_Shininess"); + } + if (material.HasProperty("_ShadowOffset")) + { + shadowOffsetTex = (material.GetTexture("_ShadowOffset") as Texture2D); + } + } + num5 = Mathf.Clamp(num5, 0.03f, 1f); + Vector2 scale = new Vector2(array[k], array[k]); + if (texture2D) + { + scale.x *= (float)num / (float)texture2D.width; + scale.y *= (float)num2 / (float)texture2D.height; + } + bool tileV = materials[k].tileV; + if (!tileV) + { + textureScale = new Vector2(1f, 1f); + } + textureAtlas.AddTexture("tex" + k, texture2D, color, normal, gloss, transtex, shadowOffsetTex, num5, scale, tileV, textureScale); + } + textureAtlas.Pack(ref num, num2, padding, true); + this.UpdateTextures(textureAtlas, materials); + Rect rect = default(Rect); + Vector2 texTiling = new Vector2(1f, 1f); + int num6 = -1; + for (int l = 0; l < triangles.Count; l++) + { + TreeTriangle treeTriangle = triangles[l]; + if (treeTriangle.materialIndex != num6) + { + num6 = treeTriangle.materialIndex; + rect = textureAtlas.GetUVRect("tex" + treeTriangle.materialIndex); + texTiling = textureAtlas.GetTexTiling("tex" + treeTriangle.materialIndex); + } + for (int m = 0; m < 3; m++) + { + TreeVertex treeVertex = vertices[treeTriangle.v[m]]; + if (!treeVertex.flag) + { + treeVertex.uv0.x = rect.x + treeVertex.uv0.x * rect.width; + treeVertex.uv0.y = (rect.y + treeVertex.uv0.y * rect.height) * texTiling.y; + treeVertex.flag = true; + } + } + if (treeTriangle.isCutout) + { + treeTriangle.materialIndex = 1; + } + else + { + treeTriangle.materialIndex = 0; + } + } + Profiler.EndSample(); + return true; + } + private static Texture2D[] WriteOptimizedTextures(string treeAssetPath, Texture2D[] textures) + { + string[] array = new string[textures.Length]; + string text = Path.Combine(Path.GetDirectoryName(treeAssetPath), Path.GetFileNameWithoutExtension(treeAssetPath) + "_Textures"); + Directory.CreateDirectory(text); + for (int i = 0; i < textures.Length; i++) + { + byte[] bytes = textures[i].EncodeToPNG(); + array[i] = Path.Combine(text, textures[i].name + ".png"); + File.WriteAllBytes(array[i], bytes); + } + AssetDatabase.Refresh(); + for (int j = 0; j < textures.Length; j++) + { + textures[j] = (AssetDatabase.LoadMainAssetAtPath(array[j]) as Texture2D); + } + return textures; + } + public bool CheckExternalChanges() + { + this.ValidateReferences(); + return this.root.CheckExternalChanges(); + } + private void UpdateShadowTexture(Texture2D shadowTexture, int texWidth, int texHeight) + { + if (!shadowTexture) + { + return; + } + string assetPath = AssetDatabase.GetAssetPath(shadowTexture); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + int[] array = new int[] + { + 1, + 2, + 4, + 8, + 16 + }; + int num = Mathf.Max(8, Mathf.ClosestPowerOfTwo(Mathf.Min(texWidth, texHeight) / array[this.root.shadowTextureQuality])); + if (num != textureImporter.maxTextureSize) + { + textureImporter.maxTextureSize = num; + textureImporter.mipmapEnabled = true; + AssetDatabase.ImportAsset(assetPath); + } + } + private bool UpdateTextures(TextureAtlas atlas, List materials) + { + if (!this.root.enableMaterialOptimize) + { + return false; + } + bool flag = this.optimizedSolidMaterial.GetTexture("_MainTex") != null && this.optimizedSolidMaterial.GetTexture("_BumpSpecMap") != null && this.optimizedSolidMaterial.GetTexture("_TranslucencyMap") != null && this.optimizedCutoutMaterial.GetTexture("_MainTex") != null && this.optimizedCutoutMaterial.GetTexture("_ShadowTex") != null && this.optimizedCutoutMaterial.GetTexture("_BumpSpecMap") != null && this.optimizedCutoutMaterial.GetTexture("_TranslucencyMap"); + UnityEngine.Object[] array = new UnityEngine.Object[materials.Count]; + for (int i = 0; i < materials.Count; i++) + { + array[i] = materials[i].material; + } + string text = InternalEditorUtility.CalculateHashForObjectsAndDependencies(array); + text += atlas.GetHashCode(); + if (this.materialHash == text && flag) + { + this.UpdateShadowTexture(this.optimizedCutoutMaterial.GetTexture("_ShadowTex") as Texture2D, atlas.atlasWidth, atlas.atlasHeight); + return false; + } + this.materialHash = text; + int atlasWidth = atlas.atlasWidth; + int atlasHeight = atlas.atlasHeight; + int atlasPadding = atlas.atlasPadding; + Texture2D texture2D = new Texture2D(atlasWidth, atlasHeight, TextureFormat.ARGB32, true); + Texture2D texture2D2 = new Texture2D(atlasWidth, atlasHeight, TextureFormat.RGB24, true); + Texture2D texture2D3 = new Texture2D(atlasWidth, atlasHeight, TextureFormat.ARGB32, true); + Texture2D texture2D4 = new Texture2D(atlasWidth, atlasHeight, TextureFormat.ARGB32, true); + texture2D.name = "diffuse"; + texture2D2.name = "shadow"; + texture2D3.name = "normal_specular"; + texture2D4.name = "translucency_gloss"; + SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState(); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + RenderTexture temporary = RenderTexture.GetTemporary(atlasWidth, atlasHeight, 0, RenderTextureFormat.ARGB32); + Color white = Color.white; + Color color = new Color(0.03f, 0.5f, 0f, 0.5f); + Color color2 = new Color(0f, 0f, 0f, 0f); + Texture2D texture2D5 = new Texture2D(1, 1); + texture2D5.SetPixel(0, 0, white); + texture2D5.Apply(); + Texture2D texture2D6 = new Texture2D(1, 1); + texture2D6.SetPixel(0, 0, white); + texture2D6.Apply(); + Texture2D texture2D7 = new Texture2D(1, 1); + texture2D7.SetPixel(0, 0, color); + texture2D7.Apply(); + Texture2D texture2D8 = new Texture2D(1, 1); + texture2D8.SetPixel(0, 0, color2); + texture2D8.Apply(); + Texture2D texture2D9 = texture2D8; + Texture2D texture2D10 = new Texture2D(1, 1); + texture2D10.SetPixel(0, 0, Color.white); + texture2D10.Apply(); + Material material = EditorGUIUtility.LoadRequired("Inspectors/TreeCreator/TreeTextureCombinerMaterial.mat") as Material; + for (int j = 0; j < 4; j++) + { + RenderTexture.active = temporary; + GL.LoadPixelMatrix(0f, (float)atlasWidth, 0f, (float)atlasHeight); + material.SetVector("_TexSize", new Vector4((float)atlasWidth, (float)atlasHeight, 0f, 0f)); + switch (j) + { + case 0: + GL.Clear(false, true, color); + break; + case 1: + GL.Clear(false, true, color2); + break; + case 2: + GL.Clear(false, true, color2); + break; + case 3: + GL.Clear(false, true, color2); + break; + } + for (int k = 0; k < atlas.nodes.Count; k++) + { + TextureAtlas.TextureNode textureNode = atlas.nodes[k]; + Rect packedRect = textureNode.packedRect; + Texture texture = null; + Texture texture2 = null; + Color color3 = default(Color); + switch (j) + { + case 0: + texture = textureNode.normalTexture; + texture2 = textureNode.shadowOffsetTexture; + color3 = new Color(textureNode.shininess, 0f, 0f, 0f); + if (texture == null) + { + texture = texture2D7; + } + if (texture2 == null) + { + texture2 = texture2D9; + } + break; + case 1: + texture = textureNode.diffuseTexture; + color3 = textureNode.diffuseColor; + if (texture == null) + { + texture = texture2D5; + } + break; + case 2: + texture = textureNode.translucencyTexture; + texture2 = textureNode.glossTexture; + if (texture == null) + { + texture = texture2D10; + } + if (texture2 == null) + { + texture2 = texture2D8; + } + break; + case 3: + texture2 = textureNode.diffuseTexture; + if (texture2 == null) + { + texture2 = texture2D5; + } + break; + } + if (textureNode.tileV) + { + float x = packedRect.x; + float num = (float)atlasPadding / 2f; + for (float num2 = num; num2 > 0f; num2 -= 1f) + { + Rect rect = new Rect(packedRect); + Rect rect2 = new Rect(packedRect); + rect.x = x - num2; + rect2.x = x + num2; + this.DrawTexture(rect, texture, texture2, material, color3, j); + this.DrawTexture(rect2, texture, texture2, material, color3, j); + } + } + this.DrawTexture(packedRect, texture, texture2, material, color3, j); + } + switch (j) + { + case 0: + texture2D3.ReadPixels(new Rect(0f, 0f, (float)atlasWidth, (float)atlasHeight), 0, 0); + texture2D3.Apply(true); + break; + case 1: + texture2D.ReadPixels(new Rect(0f, 0f, (float)atlasWidth, (float)atlasHeight), 0, 0); + texture2D.Apply(true); + break; + case 2: + texture2D4.ReadPixels(new Rect(0f, 0f, (float)atlasWidth, (float)atlasHeight), 0, 0); + texture2D4.Apply(true); + break; + case 3: + texture2D2.ReadPixels(new Rect(0f, 0f, (float)atlasWidth, (float)atlasHeight), 0, 0); + texture2D2.Apply(true); + break; + } + } + savedRenderTargetState.Restore(); + this.optimizedSolidMaterial.SetPass(0); + RenderTexture.ReleaseTemporary(temporary); + UnityEngine.Object.DestroyImmediate(texture2D5); + UnityEngine.Object.DestroyImmediate(texture2D6); + UnityEngine.Object.DestroyImmediate(texture2D10); + UnityEngine.Object.DestroyImmediate(texture2D8); + UnityEngine.Object.DestroyImmediate(texture2D7); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + Texture2D[] array2 = new Texture2D[] + { + texture2D, + texture2D3, + texture2D4, + texture2D2 + }; + array2 = TreeData.WriteOptimizedTextures(AssetDatabase.GetAssetPath(this), array2); + UnityEngine.Object.DestroyImmediate(texture2D); + UnityEngine.Object.DestroyImmediate(texture2D3); + UnityEngine.Object.DestroyImmediate(texture2D4); + UnityEngine.Object.DestroyImmediate(texture2D2); + this.optimizedSolidMaterial.SetTexture("_MainTex", array2[0]); + this.optimizedSolidMaterial.SetTexture("_BumpSpecMap", array2[1]); + this.optimizedSolidMaterial.SetTexture("_TranslucencyMap", array2[2]); + this.optimizedCutoutMaterial.SetTexture("_MainTex", array2[0]); + this.optimizedCutoutMaterial.SetTexture("_BumpSpecMap", array2[1]); + this.optimizedCutoutMaterial.SetTexture("_TranslucencyMap", array2[2]); + this.optimizedCutoutMaterial.SetTexture("_ShadowTex", array2[3]); + this.UpdateShadowTexture(array2[3], atlas.atlasWidth, atlas.atlasHeight); + return true; + } + private void DrawTexture(Rect rect, Texture rgbTexture, Texture alphaTexture, Material material, Color color, int pass) + { + material.SetColor("_Color", color); + material.SetTexture("_RGBSource", rgbTexture); + material.SetTexture("_AlphaSource", alphaTexture); + material.SetPass(pass); + RenderTexture active = RenderTexture.active; + Vector2 vector = Vector2.Scale(active.GetTexelOffset(), new Vector2((float)active.width, (float)active.height)) * -1f; + rect.x += vector.x; + rect.y += vector.y; + GL.Begin(7); + GL.TexCoord(new Vector3(0f, 0f, 0f)); + GL.Vertex3(rect.x, rect.y, 0f); + GL.TexCoord(new Vector3(1f, 0f, 0f)); + GL.Vertex3(rect.x + rect.width, rect.y, 0f); + GL.TexCoord(new Vector3(1f, 1f, 0f)); + GL.Vertex3(rect.x + rect.width, rect.y + rect.height, 0f); + GL.TexCoord(new Vector3(0f, 1f, 0f)); + GL.Vertex3(rect.x, rect.y + rect.height, 0f); + GL.End(); + } + public void UpdateMesh(Matrix4x4 matrix, List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + int seed = UnityEngine.Random.seed; + RingLoop.SetNoiseSeed(this.root.seed); + this.ClearReferences(); + this.ValidateReferences(); + this.root.UpdateSeed(); + this.root.SetRootMatrix(matrix); + this.root.UpdateDistribution(false, true); + this.root.UpdateParameters(); + if ((buildFlags & 1) != 0) + { + this.root.BuildAOSpheres(aoSpheres); + } + this.root.UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, this.root.adaptiveLODQuality, this.root.aoDensity); + this.ClearReferences(); + UnityEngine.Random.seed = seed; + } + private int[] ArrayAdd(int[] array, int value) + { + return new List(array) + { + value + }.ToArray(); + } + private TreeGroup[] ArrayAdd(TreeGroup[] array, TreeGroup value) + { + return new List(array) + { + value + }.ToArray(); + } + private TreeGroupBranch[] ArrayAdd(TreeGroupBranch[] array, TreeGroupBranch value) + { + return new List(array) + { + value + }.ToArray(); + } + private TreeGroupLeaf[] ArrayAdd(TreeGroupLeaf[] array, TreeGroupLeaf value) + { + return new List(array) + { + value + }.ToArray(); + } + private TreeNode[] ArrayAdd(TreeNode[] array, TreeNode value) + { + return new List(array) + { + value + }.ToArray(); + } + private int[] ArrayRemove(int[] array, int value) + { + List list = new List(array); + list.Remove(value); + return list.ToArray(); + } + private TreeGroup[] ArrayRemove(TreeGroup[] array, TreeGroup value) + { + List list = new List(array); + list.Remove(value); + return list.ToArray(); + } + private TreeGroupBranch[] ArrayRemove(TreeGroupBranch[] array, TreeGroupBranch value) + { + List list = new List(array); + list.Remove(value); + return list.ToArray(); + } + private TreeGroupLeaf[] ArrayRemove(TreeGroupLeaf[] array, TreeGroupLeaf value) + { + List list = new List(array); + list.Remove(value); + return list.ToArray(); + } + private TreeNode[] ArrayRemove(TreeNode[] array, TreeNode value) + { + List list = new List(array); + list.Remove(value); + return list.ToArray(); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeEditor.cs b/UnityEditor/TreeEditor/TreeEditor.cs new file mode 100644 index 00000000..c0926e03 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeEditor.cs @@ -0,0 +1,2278 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace TreeEditor +{ + [CustomEditor(typeof(Tree))] + internal class TreeEditor : Editor + { + private enum PropertyType + { + Normal, + FullUndo, + FullUpdate, + FullUndoUpdate + } + public enum EditMode + { + None = -1, + MoveNode, + RotateNode, + Freehand, + Parameter, + Everything, + Delete, + CreateGroup, + Duplicate + } + public class Styles + { + public GUIContent iconAddLeaves = EditorGUIUtility.IconContent("TreeEditor.AddLeaves", "Add Leaf Group"); + public GUIContent iconAddBranches = EditorGUIUtility.IconContent("TreeEditor.AddBranches", "Add Branch Group"); + public GUIContent iconTrash = EditorGUIUtility.IconContent("TreeEditor.Trash", "Delete Selected Group"); + public GUIContent iconDuplicate = EditorGUIUtility.IconContent("TreeEditor.Duplicate", "Duplicate Selected Group"); + public GUIContent iconRefresh = EditorGUIUtility.IconContent("TreeEditor.Refresh", "Recompute Tree"); + public GUIStyle toolbar = "TE Toolbar"; + public GUIStyle toolbarButton = "TE toolbarbutton"; + public GUIStyle nodeBackground = "TE NodeBackground"; + public GUIStyle[] nodeBoxes = new GUIStyle[] + { + "TE NodeBox", + "TE NodeBoxSelected" + }; + public GUIContent warningIcon = EditorGUIUtility.IconContent("editicon.sml"); + public GUIContent[] nodeIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("tree_icon_branch_frond"), + EditorGUIUtility.IconContent("tree_icon_branch"), + EditorGUIUtility.IconContent("tree_icon_frond"), + EditorGUIUtility.IconContent("tree_icon_leaf"), + EditorGUIUtility.IconContent("tree_icon") + }; + public GUIContent[] visibilityIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("animationvisibilitytoggleon"), + EditorGUIUtility.IconContent("animationvisibilitytoggleoff") + }; + public GUIStyle nodeLabelTop = "TE NodeLabelTop"; + public GUIStyle nodeLabelBot = "TE NodeLabelBot"; + public GUIStyle pinLabel = "TE PinLabel"; + } + internal class HierachyNode + { + internal Vector3 pos; + internal TreeGroup group; + internal Rect rect; + } + private const float kSectionSpace = 10f; + private const float kIndentSpace = 16f; + private const float kCurveSpace = 50f; + private static Vector3 s_StartPosition; + private static int s_SelectedPoint = -1; + private static TreeNode s_SelectedNode; + private static TreeGroup s_SelectedGroup; + private static TreeEditor.EditMode s_EditMode = TreeEditor.EditMode.MoveNode; + private static string s_SavedSourceMaterialsHash; + private static float s_CutoutMaterialHashBeforeUndo; + private bool m_WantCompleteUpdate; + private bool m_WantedCompleteUpdateInPreviousFrame; + private bool m_SectionHasCurves = true; + private static int s_ShowCategory = -1; + private readonly Rect m_CurveRangesA = new Rect(0f, 0f, 1f, 1f); + private readonly Rect m_CurveRangesB = new Rect(0f, -1f, 1f, 2f); + private static readonly Color s_GroupColor = new Color(1f, 0f, 1f, 1f); + private static readonly Color s_NormalColor = new Color(1f, 1f, 0f, 1f); + private static TreeGroupRoot s_CopyPasteGroup; + private readonly TreeEditorHelper m_TreeEditorHelper = new TreeEditorHelper(); + private readonly AnimBool[] m_SectionAnimators = new AnimBool[6]; + private Vector3 m_LockedWorldPos = Vector3.zero; + private Matrix4x4 m_StartMatrix = Matrix4x4.identity; + private Quaternion m_StartPointRotation = Quaternion.identity; + private bool m_StartPointRotationDirty; + private Quaternion m_GlobalToolRotation = Quaternion.identity; + private TreeSpline m_TempSpline; + public static TreeEditor.Styles styles; + private Vector2 hierachyScroll = default(Vector2); + private Vector2 hierachyNodeSize = new Vector2(40f, 48f); + private Vector2 hierachyNodeSpace = new Vector2(16f, 16f); + private Vector2 hierachySpread = new Vector2(32f, 32f); + private Rect hierachyView = new Rect(0f, 0f, 0f, 0f); + private Rect hierachyRect = new Rect(0f, 0f, 0f, 0f); + private Rect hierachyDisplayRect = new Rect(0f, 0f, 0f, 0f); + private TreeEditor.HierachyNode dragNode; + private TreeEditor.HierachyNode dropNode; + private bool isDragging; + private Vector2 dragClickPos; + public static TreeEditor.EditMode editMode + { + get + { + switch (Tools.current) + { + case Tool.View: + TreeEditor.s_EditMode = TreeEditor.EditMode.None; + break; + case Tool.Move: + TreeEditor.s_EditMode = TreeEditor.EditMode.MoveNode; + break; + case Tool.Rotate: + TreeEditor.s_EditMode = TreeEditor.EditMode.RotateNode; + break; + case Tool.Scale: + TreeEditor.s_EditMode = TreeEditor.EditMode.None; + break; + } + return TreeEditor.s_EditMode; + } + set + { + switch (value + 1) + { + case TreeEditor.EditMode.MoveNode: + break; + case TreeEditor.EditMode.RotateNode: + Tools.current = Tool.Move; + break; + case TreeEditor.EditMode.Freehand: + Tools.current = Tool.Rotate; + break; + default: + Tools.current = Tool.None; + break; + } + TreeEditor.s_EditMode = value; + } + } + [MenuItem("GameObject/3D Object/Tree", false, 3001)] + private static void CreateNewTree(MenuCommand menuCommand) + { + Mesh mesh = new Mesh(); + mesh.name = "Mesh"; + Material material = new Material(TreeEditorHelper.DefaultOptimizedBarkShader); + material.name = "Optimized Bark Material"; + material.hideFlags = (HideFlags.HideInInspector | HideFlags.NotEditable); + Material material2 = new Material(TreeEditorHelper.DefaultOptimizedLeafShader); + material2.name = "Optimized Leaf Material"; + material2.hideFlags = (HideFlags.HideInInspector | HideFlags.NotEditable); + GameObject gameObject = new GameObject("OptimizedTree", new Type[] + { + typeof(Tree), + typeof(MeshFilter), + typeof(MeshRenderer) + }); + gameObject.GetComponent().sharedMesh = mesh; + string path = "Assets/Tree.prefab"; + path = AssetDatabase.GenerateUniqueAssetPath(path); + UnityEngine.Object @object = PrefabUtility.CreateEmptyPrefab(path); + AssetDatabase.AddObjectToAsset(mesh, @object); + AssetDatabase.AddObjectToAsset(material, @object); + AssetDatabase.AddObjectToAsset(material2, @object); + TreeData treeData = ScriptableObject.CreateInstance(); + treeData.name = "Tree Data"; + treeData.Initialize(); + treeData.optimizedSolidMaterial = material; + treeData.optimizedCutoutMaterial = material2; + treeData.mesh = mesh; + gameObject.GetComponent().data = treeData; + AssetDatabase.AddObjectToAsset(treeData, @object); + GameObject target = PrefabUtility.ReplacePrefab(gameObject, @object, ReplacePrefabOptions.Default); + UnityEngine.Object.DestroyImmediate(gameObject, false); + GameObject gameObject2 = PrefabUtility.InstantiatePrefab(target) as GameObject; + GameObjectUtility.SetParentAndAlign(gameObject2, menuCommand.context as GameObject); + Undo.RegisterCreatedObjectUndo(gameObject2, "Create New Tree"); + Material[] materials; + treeData.UpdateMesh(gameObject2.transform.worldToLocalMatrix, out materials); + TreeEditor.AssignMaterials(gameObject2.renderer, materials, true); + Selection.activeObject = gameObject2; + } + private static TreeData GetTreeData(Tree tree) + { + if (tree == null) + { + return null; + } + return tree.data as TreeData; + } + private static void PreviewMesh(Tree tree) + { + TreeEditor.PreviewMesh(tree, true); + } + private static void PreviewMesh(Tree tree, bool callExitGUI) + { + TreeData treeData = TreeEditor.GetTreeData(tree); + if (treeData == null) + { + return; + } + Profiler.BeginSample("TreeEditor.PreviewMesh"); + Material[] materials; + treeData.PreviewMesh(tree.transform.worldToLocalMatrix, out materials); + TreeEditor.AssignMaterials(tree.renderer, materials, false); + Profiler.EndSample(); + if (callExitGUI) + { + GUIUtility.ExitGUI(); + } + } + private static void UpdateMesh(Tree tree) + { + TreeEditor.UpdateMesh(tree, true); + } + private static void AssignMaterials(Renderer renderer, Material[] materials, bool applyToPrefab) + { + if (renderer != null) + { + if (materials == null) + { + materials = new Material[0]; + } + if (applyToPrefab) + { + Renderer renderer2 = PrefabUtility.GetPrefabParent(renderer) as Renderer; + if (renderer2 != null) + { + renderer2.sharedMaterials = materials; + SerializedObject serializedObject = new SerializedObject(renderer); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_Materials"); + serializedProperty.prefabOverride = false; + serializedObject.ApplyModifiedProperties(); + } + } + else + { + renderer.sharedMaterials = materials; + } + } + } + private static void UpdateMesh(Tree tree, bool callExitGUI) + { + TreeData treeData = TreeEditor.GetTreeData(tree); + if (treeData == null) + { + return; + } + Profiler.BeginSample("TreeEditor.UpdateMesh"); + Material[] materials; + treeData.UpdateMesh(tree.transform.worldToLocalMatrix, out materials); + TreeEditor.AssignMaterials(tree.renderer, materials, true); + TreeEditor.s_SavedSourceMaterialsHash = treeData.materialHash; + Profiler.EndSample(); + if (callExitGUI) + { + GUIUtility.ExitGUI(); + } + } + [MenuItem("GameObject/3D Object/Wind Zone", false, 3002)] + private static void CreateWindZone(MenuCommand menuCommand) + { + GameObject gameObject = TreeEditor.CreateDefaultWindZone(); + GameObjectUtility.SetParentAndAlign(gameObject, menuCommand.context as GameObject); + Selection.activeObject = gameObject; + } + private static GameObject CreateDefaultWindZone() + { + GameObject gameObject = new GameObject("WindZone", new Type[] + { + typeof(WindZone) + }); + Undo.RegisterCreatedObjectUndo(gameObject, "Create Wind Zone"); + return gameObject; + } + private float FindClosestOffset(TreeData data, Matrix4x4 objMatrix, TreeNode node, Ray mouseRay, ref float rotation) + { + TreeGroup group = data.GetGroup(node.groupID); + if (group == null) + { + return 0f; + } + if (group.GetType() != typeof(TreeGroupBranch)) + { + return 0f; + } + data.ValidateReferences(); + Matrix4x4 lhs = objMatrix * node.matrix; + float num = 1f / ((float)node.spline.GetNodeCount() * 10f); + float num2 = 0f; + float num3 = 1E+07f; + Vector3 vector = Vector3.zero; + Vector3 zero = Vector3.zero; + Vector3 p = lhs.MultiplyPoint(node.spline.GetPositionAtTime(0f)); + for (float num4 = num; num4 <= 1f; num4 += num) + { + Vector3 vector2 = lhs.MultiplyPoint(node.spline.GetPositionAtTime(num4)); + float num5 = 0f; + float num6 = 0f; + vector = MathUtils.ClosestPtSegmentRay(p, vector2, mouseRay, out num5, out num6, out zero); + if (num5 < num3) + { + num2 = num4 - num + num * num6; + num3 = num5; + float radiusAtTime = node.GetRadiusAtTime(num2); + float num7 = 0f; + if (MathUtils.ClosestPtRaySphere(mouseRay, vector, radiusAtTime, ref num7, ref zero)) + { + Matrix4x4 inverse = (lhs * node.GetLocalMatrixAtTime(num2)).inverse; + Vector3 v = zero - vector; + v = inverse.MultiplyVector(v); + rotation = Mathf.Atan2(v.x, v.z) * 57.29578f; + } + } + p = vector2; + } + data.ClearReferences(); + return num2; + } + private void SelectGroup(TreeGroup group) + { + if (group == null) + { + Debug.Log("GROUP SELECTION IS NULL!"); + } + if (this.m_TreeEditorHelper.NodeHasWrongMaterial(group)) + { + TreeEditor.s_ShowCategory = 1; + } + TreeEditor.s_SelectedGroup = group; + TreeEditor.s_SelectedNode = null; + TreeEditor.s_SelectedPoint = -1; + EditorUtility.SetDirty(this.target); + Tree tree = this.target as Tree; + if (tree == null) + { + return; + } + Renderer component = tree.GetComponent(); + EditorUtility.SetSelectedWireframeHidden(component, !(TreeEditor.s_SelectedGroup is TreeGroupRoot)); + } + private void SelectNode(TreeNode node, TreeData treeData) + { + this.SelectGroup((node != null) ? treeData.GetGroup(node.groupID) : treeData.root); + TreeEditor.s_SelectedNode = node; + TreeEditor.s_SelectedPoint = -1; + } + private void DuplicateSelected(TreeData treeData) + { + this.UndoStoreSelected(TreeEditor.EditMode.Duplicate); + if (TreeEditor.s_SelectedNode != null) + { + TreeEditor.s_SelectedNode = treeData.DuplicateNode(TreeEditor.s_SelectedNode); + TreeEditor.s_SelectedGroup.Lock(); + } + else + { + this.SelectGroup(treeData.DuplicateGroup(TreeEditor.s_SelectedGroup)); + } + this.m_WantCompleteUpdate = true; + TreeEditor.UpdateMesh(this.target as Tree); + this.m_WantCompleteUpdate = false; + } + private void DeleteSelected(TreeData treeData) + { + this.UndoStoreSelected(TreeEditor.EditMode.Delete); + if (TreeEditor.s_SelectedNode != null) + { + if (TreeEditor.s_SelectedPoint >= 1) + { + if (TreeEditor.s_SelectedNode.spline.nodes.Length > 2) + { + if (TreeEditor.s_SelectedGroup.lockFlags == 0) + { + TreeEditor.s_SelectedGroup.Lock(); + } + TreeEditor.s_SelectedNode.spline.RemoveNode(TreeEditor.s_SelectedPoint); + TreeEditor.s_SelectedPoint = Mathf.Max(TreeEditor.s_SelectedPoint - 1, 0); + } + } + else + { + if (TreeEditor.s_SelectedGroup != null && TreeEditor.s_SelectedGroup.nodeIDs.Length == 1) + { + TreeEditor.s_SelectedNode = null; + this.DeleteSelected(treeData); + return; + } + treeData.DeleteNode(TreeEditor.s_SelectedNode); + TreeEditor.s_SelectedGroup.Lock(); + this.SelectGroup(TreeEditor.s_SelectedGroup); + } + } + else + { + if (TreeEditor.s_SelectedGroup != null) + { + TreeGroup group = treeData.GetGroup(TreeEditor.s_SelectedGroup.parentGroupID); + if (group == null) + { + return; + } + treeData.DeleteGroup(TreeEditor.s_SelectedGroup); + this.SelectGroup(group); + } + } + this.m_WantCompleteUpdate = true; + TreeEditor.UpdateMesh(this.target as Tree); + this.m_WantCompleteUpdate = false; + } + private void VerifySelection(TreeData treeData) + { + TreeGroup treeGroup = TreeEditor.s_SelectedGroup; + TreeNode treeNode = TreeEditor.s_SelectedNode; + if (treeGroup != null) + { + treeGroup = treeData.GetGroup(treeGroup.uniqueID); + } + if (treeNode != null) + { + treeNode = treeData.GetNode(treeNode.uniqueID); + } + if (treeGroup != treeData.root && treeGroup != null && !treeData.IsAncestor(treeData.root, treeGroup)) + { + treeGroup = null; + treeNode = null; + } + if (treeNode != null && treeData.GetGroup(treeNode.groupID) != treeGroup) + { + treeNode = null; + } + if (treeGroup == null) + { + treeGroup = treeData.root; + } + if (TreeEditor.s_SelectedGroup != null && treeGroup == TreeEditor.s_SelectedGroup) + { + return; + } + this.SelectGroup(treeGroup); + if (treeNode != null) + { + this.SelectNode(treeNode, treeData); + } + } + private bool OnCheckHotkeys(TreeData treeData, bool checkFrameSelected) + { + EventType type = Event.current.type; + if (type != EventType.ValidateCommand) + { + if (type == EventType.ExecuteCommand) + { + if ((Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") && TreeEditor.s_SelectedGroup != null && TreeEditor.s_SelectedGroup != treeData.root) + { + this.DeleteSelected(treeData); + Event.current.Use(); + } + if (Event.current.commandName == "FrameSelected" && checkFrameSelected) + { + this.FrameSelected(this.target as Tree); + Event.current.Use(); + } + if (Event.current.commandName == "UndoRedoPerformed") + { + float num = TreeEditor.GenerateMaterialHash(treeData.optimizedCutoutMaterial); + if (TreeEditor.s_CutoutMaterialHashBeforeUndo != num) + { + TreeEditor.s_CutoutMaterialHashBeforeUndo = num; + } + else + { + treeData.materialHash = TreeEditor.s_SavedSourceMaterialsHash; + this.m_StartPointRotationDirty = true; + TreeEditor.UpdateMesh(this.target as Tree); + } + Event.current.Use(); + return true; + } + if (Event.current.commandName == "CurveChangeCompleted") + { + TreeEditor.UpdateMesh(this.target as Tree); + Event.current.Use(); + return true; + } + } + } + else + { + if ((Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") && TreeEditor.s_SelectedGroup != null && TreeEditor.s_SelectedGroup != treeData.root) + { + Event.current.Use(); + } + if (Event.current.commandName == "FrameSelected" && checkFrameSelected) + { + Event.current.Use(); + } + if (Event.current.commandName == "UndoRedoPerformed") + { + Event.current.Use(); + } + } + return false; + } + private Bounds CalcBounds(TreeData treeData, Matrix4x4 objMatrix, TreeNode node) + { + Matrix4x4 matrix4x = objMatrix * node.matrix; + Bounds result; + if (treeData.GetGroup(node.groupID).GetType() == typeof(TreeGroupBranch) && node.spline != null && node.spline.nodes.Length > 0) + { + result = new Bounds(matrix4x.MultiplyPoint(node.spline.nodes[0].point), Vector3.zero); + for (int i = 1; i < node.spline.nodes.Length; i++) + { + result.Encapsulate(matrix4x.MultiplyPoint(node.spline.nodes[i].point)); + } + } + else + { + result = new Bounds(matrix4x.MultiplyPoint(Vector3.zero), Vector3.zero); + } + return result; + } + private void FrameSelected(Tree tree) + { + TreeData treeData = TreeEditor.GetTreeData(tree); + Matrix4x4 localToWorldMatrix = tree.transform.localToWorldMatrix; + Bounds bounds = new Bounds(localToWorldMatrix.MultiplyPoint(Vector3.zero), Vector3.zero); + if (TreeEditor.s_SelectedGroup != null) + { + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) + { + MeshFilter component = tree.GetComponent(); + if (component == null || TreeEditor.s_SelectedGroup.childGroupIDs.Length == 0) + { + float rootSpread = TreeEditor.s_SelectedGroup.GetRootSpread(); + bounds = new Bounds(localToWorldMatrix.MultiplyPoint(Vector3.zero), localToWorldMatrix.MultiplyVector(new Vector3(rootSpread, rootSpread, rootSpread))); + } + else + { + bounds = new Bounds(localToWorldMatrix.MultiplyPoint(component.sharedMesh.bounds.center), localToWorldMatrix.MultiplyVector(component.sharedMesh.bounds.size)); + } + } + else + { + if (TreeEditor.s_SelectedNode != null) + { + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupLeaf) && TreeEditor.s_SelectedPoint >= 0) + { + bounds = new Bounds((localToWorldMatrix * TreeEditor.s_SelectedNode.matrix).MultiplyPoint(TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint].point), Vector3.zero); + } + else + { + bounds = this.CalcBounds(treeData, localToWorldMatrix, TreeEditor.s_SelectedNode); + } + } + else + { + for (int i = 0; i < TreeEditor.s_SelectedGroup.nodeIDs.Length; i++) + { + Bounds bounds2 = this.CalcBounds(treeData, localToWorldMatrix, treeData.GetNode(TreeEditor.s_SelectedGroup.nodeIDs[i])); + if (i == 0) + { + bounds = bounds2; + } + else + { + bounds.Encapsulate(bounds2); + } + } + } + } + } + Vector3 center = bounds.center; + float size = bounds.size.magnitude + 1f; + SceneView lastActiveSceneView = SceneView.lastActiveSceneView; + if (lastActiveSceneView) + { + lastActiveSceneView.LookAt(center, lastActiveSceneView.rotation, size); + } + } + private void UndoStoreSelected(TreeEditor.EditMode mode) + { + TreeData treeData = TreeEditor.GetTreeData(this.target as Tree); + if (!treeData) + { + return; + } + UnityEngine.Object[] objectsToUndo = new UnityEngine.Object[] + { + treeData + }; + EditorUtility.SetDirty(treeData); + switch (mode) + { + case TreeEditor.EditMode.MoveNode: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Move"); + break; + case TreeEditor.EditMode.RotateNode: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Rotate"); + break; + case TreeEditor.EditMode.Freehand: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Freehand Drawing"); + break; + case TreeEditor.EditMode.Parameter: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Parameter Change"); + break; + case TreeEditor.EditMode.Everything: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Parameter Change"); + break; + case TreeEditor.EditMode.Delete: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Delete"); + break; + case TreeEditor.EditMode.CreateGroup: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Create Group"); + break; + case TreeEditor.EditMode.Duplicate: + Undo.RegisterCompleteObjectUndo(objectsToUndo, "Duplicate"); + break; + } + } + private void RepaintGUIView() + { + GUIView.current.Repaint(); + } + private void OnEnable() + { + Tree tree = this.target as Tree; + if (tree == null) + { + return; + } + TreeData treeData = TreeEditor.GetTreeData(tree); + if (treeData == null) + { + return; + } + this.m_TreeEditorHelper.OnEnable(treeData); + this.m_TreeEditorHelper.SetAnimsCallback(new UnityAction(this.RepaintGUIView)); + for (int i = 0; i < this.m_SectionAnimators.Length; i++) + { + this.m_SectionAnimators[i] = new AnimBool(TreeEditor.s_ShowCategory == i, new UnityAction(base.Repaint)); + } + Renderer component = tree.GetComponent(); + EditorUtility.SetSelectedWireframeHidden(component, !(TreeEditor.s_SelectedGroup is TreeGroupRoot)); + } + private void OnDisable() + { + Tools.s_Hidden = false; + Tree tree = this.target as Tree; + if (tree == null) + { + return; + } + Renderer component = tree.GetComponent(); + EditorUtility.SetSelectedWireframeHidden(component, false); + } + private void OnSceneGUI() + { + Tree tree = this.target as Tree; + TreeData treeData = TreeEditor.GetTreeData(tree); + if (!treeData) + { + return; + } + this.VerifySelection(treeData); + if (TreeEditor.s_SelectedGroup == null) + { + return; + } + this.OnCheckHotkeys(treeData, true); + Transform transform = tree.transform; + Matrix4x4 localToWorldMatrix = tree.transform.localToWorldMatrix; + Event current = Event.current; + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) + { + Tools.s_Hidden = false; + Handles.color = TreeEditor.s_NormalColor; + Handles.DrawWireDisc(transform.position, transform.up, treeData.root.rootSpread); + } + else + { + Tools.s_Hidden = true; + Handles.color = Handles.secondaryColor; + Handles.DrawWireDisc(transform.position, transform.up, treeData.root.rootSpread); + } + if (TreeEditor.s_SelectedGroup != null && TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupBranch)) + { + EventType eventType = current.type; + if (current.type == EventType.Ignore && current.rawType == EventType.MouseUp) + { + eventType = current.rawType; + } + Handles.DrawLine(Vector3.zero, Vector3.zero); + GL.Begin(1); + for (int i = 0; i < TreeEditor.s_SelectedGroup.nodeIDs.Length; i++) + { + TreeNode node = treeData.GetNode(TreeEditor.s_SelectedGroup.nodeIDs[i]); + TreeSpline spline = node.spline; + if (spline != null) + { + Handles.color = ((node != TreeEditor.s_SelectedNode) ? TreeEditor.s_GroupColor : TreeEditor.s_NormalColor); + Matrix4x4 matrix4x = localToWorldMatrix * node.matrix; + Vector3 v = matrix4x.MultiplyPoint(spline.GetPositionAtTime(0f)); + GL.Color(Handles.color); + for (float num = 0.01f; num <= 1f; num += 0.01f) + { + Vector3 vector = matrix4x.MultiplyPoint(spline.GetPositionAtTime(num)); + GL.Vertex(v); + GL.Vertex(vector); + v = vector; + } + } + } + GL.End(); + for (int j = 0; j < TreeEditor.s_SelectedGroup.nodeIDs.Length; j++) + { + TreeNode node2 = treeData.GetNode(TreeEditor.s_SelectedGroup.nodeIDs[j]); + TreeSpline spline2 = node2.spline; + if (spline2 != null) + { + Handles.color = ((node2 != TreeEditor.s_SelectedNode) ? TreeEditor.s_GroupColor : TreeEditor.s_NormalColor); + Matrix4x4 m = localToWorldMatrix * node2.matrix; + for (int k = 0; k < spline2.nodes.Length; k++) + { + SplineNode splineNode = spline2.nodes[k]; + Vector3 vector2 = m.MultiplyPoint(splineNode.point); + float size = HandleUtility.GetHandleSize(vector2) * 0.08f; + Handles.color = Handles.centerColor; + int keyboardControl = GUIUtility.keyboardControl; + switch (TreeEditor.editMode) + { + case TreeEditor.EditMode.MoveNode: + if (k == 0) + { + vector2 = Handles.FreeMoveHandle(vector2, Quaternion.identity, size, Vector3.zero, new Handles.DrawCapFunction(Handles.CircleCap)); + } + else + { + vector2 = Handles.FreeMoveHandle(vector2, Quaternion.identity, size, Vector3.zero, new Handles.DrawCapFunction(Handles.RectangleCap)); + } + if (eventType == EventType.MouseDown && current.type == EventType.Used && keyboardControl != GUIUtility.keyboardControl) + { + this.SelectNode(node2, treeData); + TreeEditor.s_SelectedPoint = k; + this.m_StartPointRotation = MathUtils.QuaternionFromMatrix(m) * splineNode.rot; + } + if ((eventType == EventType.MouseDown || eventType == EventType.MouseUp) && current.type == EventType.Used) + { + this.m_StartPointRotation = MathUtils.QuaternionFromMatrix(m) * splineNode.rot; + } + if (eventType == EventType.MouseUp && current.type == EventType.Used && treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + if (GUI.changed) + { + Undo.RegisterCompleteObjectUndo(treeData, "Move"); + TreeEditor.s_SelectedGroup.Lock(); + float baseAngle = node2.baseAngle; + if (k == 0) + { + TreeNode node3 = treeData.GetNode(TreeEditor.s_SelectedNode.parentID); + Ray ray = HandleUtility.GUIPointToWorldRay(current.mousePosition); + float d = 0f; + if (node3 != null) + { + TreeGroup group = treeData.GetGroup(TreeEditor.s_SelectedGroup.parentGroupID); + if (group.GetType() == typeof(TreeGroupBranch)) + { + TreeEditor.s_SelectedNode.offset = this.FindClosestOffset(treeData, localToWorldMatrix, node3, ray, ref baseAngle); + vector2 = m.MultiplyPoint(Vector3.zero); + } + else + { + if (group.GetType() == typeof(TreeGroupRoot)) + { + Vector3 vector3 = localToWorldMatrix.MultiplyPoint(Vector3.zero); + Plane plane = new Plane(localToWorldMatrix.MultiplyVector(Vector3.up), vector3); + if (plane.Raycast(ray, out d)) + { + vector2 = ray.origin + ray.direction * d; + Vector3 v2 = vector2 - vector3; + v2 = localToWorldMatrix.inverse.MultiplyVector(v2); + TreeEditor.s_SelectedNode.offset = Mathf.Clamp01(v2.magnitude / treeData.root.rootSpread); + baseAngle = Mathf.Atan2(v2.z, v2.x) * 57.29578f; + vector2 = m.MultiplyPoint(Vector3.zero); + } + else + { + vector2 = m.MultiplyPoint(splineNode.point); + } + } + } + } + } + node2.baseAngle = baseAngle; + splineNode.point = m.inverse.MultiplyPoint(vector2); + spline2.UpdateTime(); + spline2.UpdateRotations(); + TreeEditor.PreviewMesh(tree); + GUI.changed = false; + } + break; + case TreeEditor.EditMode.RotateNode: + Handles.FreeMoveHandle(vector2, Quaternion.identity, size, Vector3.zero, new Handles.DrawCapFunction(Handles.CircleCap)); + if (eventType == EventType.MouseDown && current.type == EventType.Used && keyboardControl != GUIUtility.keyboardControl) + { + this.SelectNode(node2, treeData); + TreeEditor.s_SelectedPoint = k; + this.m_GlobalToolRotation = Quaternion.identity; + this.m_TempSpline = new TreeSpline(node2.spline); + } + GUI.changed = false; + break; + case TreeEditor.EditMode.Freehand: + Handles.FreeMoveHandle(vector2, Quaternion.identity, size, Vector3.zero, new Handles.DrawCapFunction(Handles.CircleCap)); + if (eventType == EventType.MouseDown && current.type == EventType.Used && keyboardControl != GUIUtility.keyboardControl) + { + Undo.RegisterCompleteObjectUndo(treeData, "Free Hand"); + this.SelectNode(node2, treeData); + TreeEditor.s_SelectedPoint = k; + TreeEditor.s_StartPosition = vector2; + int nodeCount = Mathf.Max(2, TreeEditor.s_SelectedPoint + 1); + node2.spline.SetNodeCount(nodeCount); + current.Use(); + } + if (TreeEditor.s_SelectedPoint == k && TreeEditor.s_SelectedNode == node2 && eventType == EventType.MouseDrag) + { + Ray ray2 = HandleUtility.GUIPointToWorldRay(current.mousePosition); + Vector3 forward = Camera.current.transform.forward; + Plane plane2 = new Plane(forward, TreeEditor.s_StartPosition); + float d2 = 0f; + if (plane2.Raycast(ray2, out d2)) + { + Vector3 v3 = ray2.origin + d2 * ray2.direction; + if (TreeEditor.s_SelectedPoint == 0) + { + TreeEditor.s_SelectedPoint = 1; + } + TreeEditor.s_SelectedGroup.Lock(); + TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint].point = m.inverse.MultiplyPoint(v3); + Vector3 b = TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint].point - TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint - 1].point; + if (b.magnitude > 1f) + { + TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint].point = TreeEditor.s_SelectedNode.spline.nodes[TreeEditor.s_SelectedPoint - 1].point + b; + TreeEditor.s_SelectedPoint++; + if (TreeEditor.s_SelectedPoint >= TreeEditor.s_SelectedNode.spline.nodes.Length) + { + TreeEditor.s_SelectedNode.spline.AddPoint(m.inverse.MultiplyPoint(v3), 1.1f); + } + } + TreeEditor.s_SelectedNode.spline.UpdateTime(); + TreeEditor.s_SelectedNode.spline.UpdateRotations(); + current.Use(); + TreeEditor.PreviewMesh(tree); + } + } + break; + } + if (TreeEditor.s_SelectedPoint == k && TreeEditor.s_SelectedNode == node2 && this.m_StartPointRotationDirty) + { + spline2.UpdateTime(); + spline2.UpdateRotations(); + this.m_StartPointRotation = MathUtils.QuaternionFromMatrix(m) * splineNode.rot; + this.m_GlobalToolRotation = Quaternion.identity; + this.m_StartPointRotationDirty = false; + } + } + } + } + if (eventType == EventType.MouseUp && TreeEditor.editMode == TreeEditor.EditMode.Freehand) + { + TreeEditor.s_SelectedPoint = -1; + if (treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + } + if (TreeEditor.s_SelectedPoint > 0 && TreeEditor.editMode == TreeEditor.EditMode.MoveNode && TreeEditor.s_SelectedNode != null) + { + TreeNode treeNode = TreeEditor.s_SelectedNode; + SplineNode splineNode2 = treeNode.spline.nodes[TreeEditor.s_SelectedPoint]; + Matrix4x4 m2 = localToWorldMatrix * treeNode.matrix; + Vector3 vector4 = m2.MultiplyPoint(splineNode2.point); + Quaternion rotation = Quaternion.identity; + if (Tools.pivotRotation == PivotRotation.Local) + { + if (eventType == EventType.MouseUp || eventType == EventType.MouseDown) + { + this.m_StartPointRotation = MathUtils.QuaternionFromMatrix(m2) * splineNode2.rot; + } + rotation = this.m_StartPointRotation; + } + vector4 = this.DoPositionHandle(vector4, rotation, false); + if (GUI.changed) + { + Undo.RegisterCompleteObjectUndo(treeData, "Move"); + TreeEditor.s_SelectedGroup.Lock(); + splineNode2.point = m2.inverse.MultiplyPoint(vector4); + treeNode.spline.UpdateTime(); + treeNode.spline.UpdateRotations(); + TreeEditor.PreviewMesh(tree); + } + if (eventType == EventType.MouseUp && current.type == EventType.Used && treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + } + if (TreeEditor.s_SelectedPoint >= 0 && TreeEditor.editMode == TreeEditor.EditMode.RotateNode && TreeEditor.s_SelectedNode != null) + { + TreeNode treeNode2 = TreeEditor.s_SelectedNode; + SplineNode splineNode3 = treeNode2.spline.nodes[TreeEditor.s_SelectedPoint]; + Matrix4x4 matrix4x2 = localToWorldMatrix * treeNode2.matrix; + if (this.m_TempSpline == null) + { + this.m_TempSpline = new TreeSpline(treeNode2.spline); + } + Vector3 position = matrix4x2.MultiplyPoint(splineNode3.point); + Quaternion rotation2 = Quaternion.identity; + this.m_GlobalToolRotation = Handles.RotationHandle(this.m_GlobalToolRotation, position); + rotation2 = this.m_GlobalToolRotation; + if (GUI.changed) + { + Undo.RegisterCompleteObjectUndo(treeData, "Move"); + TreeEditor.s_SelectedGroup.Lock(); + for (int l = TreeEditor.s_SelectedPoint + 1; l < this.m_TempSpline.nodes.Length; l++) + { + Vector3 vector5 = this.m_TempSpline.nodes[l].point - splineNode3.point; + vector5 = matrix4x2.MultiplyVector(vector5); + vector5 = rotation2 * vector5; + vector5 = matrix4x2.inverse.MultiplyVector(vector5); + Vector3 point = splineNode3.point + vector5; + TreeEditor.s_SelectedNode.spline.nodes[l].point = point; + } + treeNode2.spline.UpdateTime(); + treeNode2.spline.UpdateRotations(); + TreeEditor.PreviewMesh(tree); + } + if (eventType == EventType.MouseUp && current.type == EventType.Used && treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + } + } + if (TreeEditor.s_SelectedGroup != null && TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupLeaf)) + { + for (int n = 0; n < TreeEditor.s_SelectedGroup.nodeIDs.Length; n++) + { + TreeNode node4 = treeData.GetNode(TreeEditor.s_SelectedGroup.nodeIDs[n]); + Matrix4x4 matrix4x3 = localToWorldMatrix * node4.matrix; + Vector3 vector6 = matrix4x3.MultiplyPoint(Vector3.zero); + float size2 = HandleUtility.GetHandleSize(vector6) * 0.08f; + Handles.color = Handles.centerColor; + EventType eventType2 = current.type; + int keyboardControl2 = GUIUtility.keyboardControl; + TreeEditor.EditMode editMode = TreeEditor.editMode; + if (editMode != TreeEditor.EditMode.MoveNode) + { + if (editMode == TreeEditor.EditMode.RotateNode) + { + Handles.FreeMoveHandle(vector6, Quaternion.identity, size2, Vector3.zero, new Handles.DrawCapFunction(Handles.CircleCap)); + if (eventType2 == EventType.MouseDown && current.type == EventType.Used && keyboardControl2 != GUIUtility.keyboardControl) + { + this.SelectNode(node4, treeData); + this.m_GlobalToolRotation = MathUtils.QuaternionFromMatrix(matrix4x3); + this.m_StartMatrix = matrix4x3; + this.m_StartPointRotation = node4.rotation; + this.m_LockedWorldPos = new Vector3(matrix4x3.m03, matrix4x3.m13, matrix4x3.m23); + } + if (TreeEditor.s_SelectedNode == node4) + { + eventType2 = current.GetTypeForControl(GUIUtility.hotControl); + this.m_GlobalToolRotation = Handles.RotationHandle(this.m_GlobalToolRotation, this.m_LockedWorldPos); + if (eventType2 == EventType.MouseUp && current.type == EventType.Used) + { + this.m_LockedWorldPos = new Vector3(matrix4x3.m03, matrix4x3.m13, matrix4x3.m23); + if (treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + } + if (GUI.changed) + { + TreeEditor.s_SelectedGroup.Lock(); + Quaternion lhs = Quaternion.Inverse(MathUtils.QuaternionFromMatrix(this.m_StartMatrix)); + node4.rotation = this.m_StartPointRotation * (lhs * this.m_GlobalToolRotation); + MathUtils.QuaternionNormalize(ref node4.rotation); + TreeEditor.PreviewMesh(tree); + } + } + } + } + else + { + Handles.FreeMoveHandle(vector6, Quaternion.identity, size2, Vector3.zero, new Handles.DrawCapFunction(Handles.CircleCap)); + if (eventType2 == EventType.MouseDown && current.type == EventType.Used && keyboardControl2 != GUIUtility.keyboardControl) + { + this.SelectNode(node4, treeData); + this.m_GlobalToolRotation = MathUtils.QuaternionFromMatrix(matrix4x3); + this.m_StartMatrix = matrix4x3; + this.m_StartPointRotation = node4.rotation; + this.m_LockedWorldPos = new Vector3(this.m_StartMatrix.m03, this.m_StartMatrix.m13, this.m_StartMatrix.m23); + } + if (eventType2 == EventType.MouseUp && current.type == EventType.Used && treeData.isInPreviewMode) + { + TreeEditor.UpdateMesh(tree); + } + if (GUI.changed) + { + TreeEditor.s_SelectedGroup.Lock(); + TreeNode node5 = treeData.GetNode(node4.parentID); + TreeGroup group2 = treeData.GetGroup(TreeEditor.s_SelectedGroup.parentGroupID); + Ray ray3 = HandleUtility.GUIPointToWorldRay(current.mousePosition); + float d3 = 0f; + float baseAngle2 = node4.baseAngle; + if (group2.GetType() == typeof(TreeGroupBranch)) + { + node4.offset = this.FindClosestOffset(treeData, localToWorldMatrix, node5, ray3, ref baseAngle2); + node4.baseAngle = baseAngle2; + TreeEditor.PreviewMesh(tree); + } + else + { + if (group2.GetType() == typeof(TreeGroupRoot)) + { + Vector3 vector7 = localToWorldMatrix.MultiplyPoint(Vector3.zero); + Plane plane3 = new Plane(localToWorldMatrix.MultiplyVector(Vector3.up), vector7); + if (plane3.Raycast(ray3, out d3)) + { + vector6 = ray3.origin + ray3.direction * d3; + Vector3 v4 = vector6 - vector7; + v4 = localToWorldMatrix.inverse.MultiplyVector(v4); + node4.offset = Mathf.Clamp01(v4.magnitude / treeData.root.rootSpread); + baseAngle2 = Mathf.Atan2(v4.z, v4.x) * 57.29578f; + } + node4.baseAngle = baseAngle2; + TreeEditor.PreviewMesh(tree); + } + } + } + } + } + } + } + private Vector3 DoPositionHandle(Vector3 position, Quaternion rotation, bool hide) + { + Color color = Handles.color; + Handles.color = Handles.xAxisColor; + position = Handles.Slider(position, rotation * Vector3.right); + Handles.color = Handles.yAxisColor; + position = Handles.Slider(position, rotation * Vector3.up); + Handles.color = Handles.zAxisColor; + position = Handles.Slider(position, rotation * Vector3.forward); + Handles.color = color; + return position; + } + private Rect GUIPropBegin() + { + return EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + } + private void GUIPropEnd() + { + this.GUIPropEnd(true); + } + private void GUIPropEnd(bool addSpace) + { + if (addSpace) + { + GUILayout.Space((!this.m_SectionHasCurves) ? 0f : 54f); + } + EditorGUILayout.EndHorizontal(); + } + private void GUIHandlePropertyChange(TreeEditor.PropertyType prop) + { + switch (prop) + { + case TreeEditor.PropertyType.Normal: + this.UndoStoreSelected(TreeEditor.EditMode.Parameter); + break; + case TreeEditor.PropertyType.FullUndo: + this.UndoStoreSelected(TreeEditor.EditMode.Everything); + break; + case TreeEditor.PropertyType.FullUpdate: + this.UndoStoreSelected(TreeEditor.EditMode.Parameter); + this.m_WantCompleteUpdate = true; + break; + case TreeEditor.PropertyType.FullUndoUpdate: + this.UndoStoreSelected(TreeEditor.EditMode.Everything); + this.m_WantCompleteUpdate = true; + break; + } + } + private float GUISlider(TreeEditor.PropertyType prop, string contentID, float value, float minimum, float maximum, bool hasCurve) + { + this.GUIPropBegin(); + float num = EditorGUILayout.Slider(TreeEditorHelper.GetGUIContent(contentID), value, minimum, maximum, new GUILayoutOption[0]); + if (num != value) + { + this.GUIHandlePropertyChange(prop); + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return num; + } + private int GUIIntSlider(TreeEditor.PropertyType prop, string contentID, int value, int minimum, int maximum, bool hasCurve) + { + this.GUIPropBegin(); + int num = EditorGUILayout.IntSlider(TreeEditorHelper.GetGUIContent(contentID), value, minimum, maximum, new GUILayoutOption[0]); + if (num != value) + { + this.GUIHandlePropertyChange(prop); + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return num; + } + private bool GUIToggle(TreeEditor.PropertyType prop, string contentID, bool value, bool hasCurve) + { + this.GUIPropBegin(); + bool flag = EditorGUILayout.Toggle(TreeEditorHelper.GetGUIContent(contentID), value, new GUILayoutOption[0]); + if (flag != value) + { + this.GUIHandlePropertyChange(prop); + this.m_WantCompleteUpdate = true; + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return flag; + } + private int GUIPopup(TreeEditor.PropertyType prop, string contentID, string optionsContentID, string[] optionIDs, int value, bool hasCurve) + { + this.GUIPropBegin(); + GUIContent[] array = new GUIContent[optionIDs.Length]; + for (int i = 0; i < optionIDs.Length; i++) + { + array[i] = TreeEditorHelper.GetGUIContent(optionsContentID + "." + optionIDs[i]); + } + int num = EditorGUILayout.Popup(TreeEditorHelper.GetGUIContent(contentID), value, array, new GUILayoutOption[0]); + if (num != value) + { + this.GUIHandlePropertyChange(prop); + this.m_WantCompleteUpdate = true; + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return num; + } + private Material GUIMaterialField(TreeEditor.PropertyType prop, int uniqueNodeID, string contentID, Material value, TreeEditorHelper.NodeType nodeType) + { + string uniqueID = uniqueNodeID + "_" + contentID; + this.GUIPropBegin(); + Material material = EditorGUILayout.ObjectField(TreeEditorHelper.GetGUIContent(contentID), value, typeof(Material), false, new GUILayoutOption[0]) as Material; + this.GUIPropEnd(); + bool flag = this.m_TreeEditorHelper.GUIWrongShader(uniqueID, material, nodeType); + if (material != value || flag) + { + this.GUIHandlePropertyChange(prop); + this.m_WantCompleteUpdate = true; + } + return material; + } + private UnityEngine.Object GUIObjectField(TreeEditor.PropertyType prop, string contentID, UnityEngine.Object value, Type type, bool hasCurve) + { + this.GUIPropBegin(); + UnityEngine.Object @object = EditorGUILayout.ObjectField(TreeEditorHelper.GetGUIContent(contentID), value, type, false, new GUILayoutOption[0]); + if (@object != value) + { + this.GUIHandlePropertyChange(prop); + this.m_WantCompleteUpdate = true; + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return @object; + } + private bool GUICurve(TreeEditor.PropertyType prop, AnimationCurve curve, Rect ranges) + { + bool changed = GUI.changed; + EditorGUILayout.CurveField(curve, Color.green, ranges, new GUILayoutOption[] + { + GUILayout.Width(50f) + }); + this.GUIPropEnd(false); + if (changed != GUI.changed) + { + if (GUIUtility.hotControl == 0) + { + this.m_WantCompleteUpdate = true; + } + this.GUIHandlePropertyChange(prop); + return true; + } + return false; + } + private Vector2 GUIMinMaxSlider(TreeEditor.PropertyType prop, string contentID, Vector2 value, float minimum, float maximum, bool hasCurve) + { + this.GUIPropBegin(); + Vector2 result = new Vector2(Mathf.Min(value.x, value.y), Mathf.Max(value.x, value.y)); + GUIContent gUIContent = TreeEditorHelper.GetGUIContent(contentID); + bool changed = GUI.changed; + Rect rect = GUILayoutUtility.GetRect(gUIContent, "Button"); + EditorGUI.MinMaxSlider(gUIContent, rect, ref result.x, ref result.y, minimum, maximum); + if (changed != GUI.changed) + { + this.GUIHandlePropertyChange(prop); + } + if (!hasCurve) + { + this.GUIPropEnd(); + } + return result; + } + public void InspectorHierachy(TreeData treeData, Renderer renderer) + { + if (TreeEditor.s_SelectedGroup == null) + { + Debug.Log("NO GROUP SELECTED!"); + return; + } + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + bool changed = GUI.changed; + Rect sizeRect = this.GUIPropBegin(); + this.DrawHierachy(treeData, renderer, sizeRect); + if (GUI.changed != changed) + { + this.m_WantCompleteUpdate = true; + } + this.GUIPropEnd(false); + this.GUIPropBegin(); + int num = -1; + GUILayout.BeginHorizontal(TreeEditor.styles.toolbar, new GUILayoutOption[0]); + if (GUILayout.Button(TreeEditor.styles.iconRefresh, TreeEditor.styles.toolbarButton, new GUILayoutOption[0])) + { + TreeGroupLeaf.s_TextureHullsDirty = true; + TreeEditor.UpdateMesh(this.target as Tree); + } + GUILayout.FlexibleSpace(); + GUI.enabled = TreeEditor.s_SelectedGroup.CanHaveSubGroups(); + if (GUILayout.Button(TreeEditor.styles.iconAddLeaves, TreeEditor.styles.toolbarButton, new GUILayoutOption[0])) + { + num = 0; + } + if (GUILayout.Button(TreeEditor.styles.iconAddBranches, TreeEditor.styles.toolbarButton, new GUILayoutOption[0])) + { + num = 1; + } + GUI.enabled = true; + if (TreeEditor.s_SelectedGroup == treeData.root) + { + GUI.enabled = false; + } + if (GUILayout.Button(TreeEditor.styles.iconDuplicate, TreeEditor.styles.toolbarButton, new GUILayoutOption[0])) + { + num = 3; + } + if (GUILayout.Button(TreeEditor.styles.iconTrash, TreeEditor.styles.toolbarButton, new GUILayoutOption[0])) + { + num = 2; + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + switch (num) + { + case 0: + { + this.UndoStoreSelected(TreeEditor.EditMode.CreateGroup); + TreeGroup group = treeData.AddGroup(TreeEditor.s_SelectedGroup, typeof(TreeGroupLeaf)); + this.SelectGroup(group); + this.m_WantCompleteUpdate = true; + Event.current.Use(); + break; + } + case 1: + { + this.UndoStoreSelected(TreeEditor.EditMode.CreateGroup); + TreeGroup group2 = treeData.AddGroup(TreeEditor.s_SelectedGroup, typeof(TreeGroupBranch)); + this.SelectGroup(group2); + this.m_WantCompleteUpdate = true; + Event.current.Use(); + break; + } + case 2: + this.DeleteSelected(treeData); + Event.current.Use(); + break; + case 3: + this.DuplicateSelected(treeData); + Event.current.Use(); + break; + } + this.GUIPropEnd(false); + GUILayout.EndVertical(); + EditorGUILayout.EndHorizontal(); + EditorGUILayout.Space(); + } + public void InspectorEditTools(Tree obj) + { + if (EditorUtility.IsPersistent(obj)) + { + return; + } + string[] array; + if (TreeEditor.s_SelectedGroup is TreeGroupBranch) + { + array = new string[] + { + "TreeEditor.BranchTranslate", + "TreeEditor.BranchRotate", + "TreeEditor.BranchFreeHand" + }; + } + else + { + array = new string[] + { + "TreeEditor.LeafTranslate", + "TreeEditor.LeafRotate" + }; + if (TreeEditor.editMode == TreeEditor.EditMode.Freehand) + { + TreeEditor.editMode = TreeEditor.EditMode.None; + } + } + TreeEditor.EditMode editMode = TreeEditor.editMode; + TreeEditor.editMode = (TreeEditor.EditMode)this.GUItoolbar((int)TreeEditor.editMode, TreeEditor.BuildToolbarContent(array, (int)TreeEditor.editMode)); + if (editMode != TreeEditor.editMode) + { + SceneView.RepaintAll(); + } + EditorGUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + if (TreeEditor.editMode == TreeEditor.EditMode.None) + { + GUILayout.Label("No Tool Selected", new GUILayoutOption[0]); + GUILayout.Label("Please select a tool", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + } + else + { + string uIString = TreeEditorHelper.GetUIString(array[(int)TreeEditor.editMode]); + GUILayout.Label(TreeEditorHelper.ExtractLabel(uIString), new GUILayoutOption[0]); + GUILayout.Label(TreeEditorHelper.ExtractTooltip(uIString), EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + } + EditorGUILayout.EndVertical(); + EditorGUILayout.Space(); + } + private static GUIContent[] BuildToolbarContent(string[] contentStrings, int selection) + { + GUIContent[] array = new GUIContent[contentStrings.Length]; + for (int i = 0; i < contentStrings.Length; i++) + { + string str = (selection != i) ? string.Empty : " On"; + string tooltip = TreeEditorHelper.ExtractLabel(TreeEditorHelper.GetUIString(contentStrings[i])); + array[i] = EditorGUIUtility.IconContent(contentStrings[i] + str, tooltip); + } + return array; + } + public void InspectorDistribution(TreeData treeData, TreeGroup group) + { + if (group == null) + { + return; + } + this.PrepareSpacing(true); + bool enabled = true; + if (group.lockFlags != 0) + { + enabled = false; + } + string str = "TreeEditor." + group.GetType().Name + "."; + GUI.enabled = enabled; + int num = group.seed; + group.seed = this.GUIIntSlider(TreeEditor.PropertyType.Normal, str + "GroupSeed", group.seed, 0, 999999, false); + if (group.seed != num) + { + treeData.UpdateSeed(group.uniqueID); + } + num = group.distributionFrequency; + group.distributionFrequency = this.GUIIntSlider(TreeEditor.PropertyType.FullUndo, str + "Frequency", group.distributionFrequency, 1, 100, false); + if (group.distributionFrequency != num) + { + treeData.UpdateFrequency(group.uniqueID); + } + string[] optionIDs = new string[] + { + "Random", + "Alternate", + "Opposite", + "Whorled" + }; + num = (int)group.distributionMode; + group.distributionMode = (TreeGroup.DistributionMode)this.GUIPopup(TreeEditor.PropertyType.Normal, str + "DistributionMode", "TreeEditor.DistributionModeOption", optionIDs, (int)group.distributionMode, true); + if (group.distributionMode != (TreeGroup.DistributionMode)num) + { + treeData.UpdateDistribution(group.uniqueID); + } + AnimationCurve animationCurve = group.distributionCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.distributionCurve = animationCurve; + treeData.UpdateDistribution(group.uniqueID); + } + if (group.distributionMode != TreeGroup.DistributionMode.Random) + { + float distributionTwirl = group.distributionTwirl; + group.distributionTwirl = this.GUISlider(TreeEditor.PropertyType.Normal, str + "Twirl", group.distributionTwirl, -1f, 1f, false); + if (group.distributionTwirl != distributionTwirl) + { + treeData.UpdateDistribution(group.uniqueID); + } + } + if (group.distributionMode == TreeGroup.DistributionMode.Whorled) + { + num = group.distributionNodes; + group.distributionNodes = this.GUIIntSlider(TreeEditor.PropertyType.Normal, str + "WhorledStep", group.distributionNodes, 1, 21, false); + if (group.distributionNodes != num) + { + treeData.UpdateDistribution(group.uniqueID); + } + } + group.distributionScale = this.GUISlider(TreeEditor.PropertyType.Normal, str + "GrowthScale", group.distributionScale, 0f, 1f, true); + animationCurve = group.distributionScaleCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.distributionScaleCurve = animationCurve; + } + group.distributionPitch = this.GUISlider(TreeEditor.PropertyType.Normal, str + "GrowthAngle", group.distributionPitch, 0f, 1f, true); + animationCurve = group.distributionPitchCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesB)) + { + group.distributionPitchCurve = animationCurve; + } + GUI.enabled = true; + EditorGUILayout.Space(); + } + public void InspectorAnimation(TreeData treeData, TreeGroup group) + { + if (group == null) + { + return; + } + this.PrepareSpacing(false); + string str = "TreeEditor." + group.GetType().Name + "."; + group.animationPrimary = this.GUISlider(TreeEditor.PropertyType.Normal, str + "MainWind", group.animationPrimary, 0f, 1f, false); + if (treeData.GetGroup(group.parentGroupID) != treeData.root) + { + group.animationSecondary = this.GUISlider(TreeEditor.PropertyType.Normal, str + "MainTurbulence", group.animationSecondary, 0f, 1f, false); + } + GUI.enabled = true; + if (!(group is TreeGroupBranch) || (group as TreeGroupBranch).geometryMode != TreeGroupBranch.GeometryMode.Branch) + { + group.animationEdge = this.GUISlider(TreeEditor.PropertyType.Normal, str + "EdgeTurbulence", group.animationEdge, 0f, 1f, false); + } + this.GUIPropBegin(); + if (GUILayout.Button(TreeEditorHelper.GetGUIContent("TreeEditor.WindZone.Create"), new GUILayoutOption[0])) + { + TreeEditor.CreateDefaultWindZone(); + } + this.GUIPropEnd(); + } + private int GUItoolbar(int selection, GUIContent[] names) + { + GUI.enabled = true; + bool changed = GUI.changed; + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + for (int i = 0; i < names.Length; i++) + { + GUIStyle style = new GUIStyle("ButtonMid"); + if (i == 0) + { + style = new GUIStyle("ButtonLeft"); + } + if (i == names.Length - 1) + { + style = new GUIStyle("ButtonRight"); + } + if (names[i] != null && GUILayout.Toggle(selection == i, names[i], style, new GUILayoutOption[0])) + { + selection = i; + } + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + GUI.changed = changed; + return selection; + } + private void GUIunlockbox(TreeData treeData) + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + GUIContent gUIContent = TreeEditorHelper.GetGUIContent("TreeEditor.EditingTools.WarningLabel"); + gUIContent.image = TreeEditor.styles.warningIcon.image; + GUILayout.Label(gUIContent, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUIStyle gUIStyle = new GUIStyle("minibutton"); + gUIStyle.wordWrap = true; + GUIContent gUIContent2 = TreeEditorHelper.GetGUIContent("TreeEditor.EditingTools.WarningButton"); + if (GUILayout.Button(gUIContent2, gUIStyle, new GUILayoutOption[0])) + { + treeData.UnlockGroup(TreeEditor.s_SelectedGroup); + this.m_WantCompleteUpdate = true; + } + GUILayout.EndVertical(); + } + private void PrepareSpacing(bool hasCurves) + { + this.m_SectionHasCurves = hasCurves; + EditorGUIUtility.labelWidth = (float)((!hasCurves) ? 120 : 100); + } + private bool GUIMaterialColor(Material material, string propertyID, string contentID) + { + bool result = false; + this.GUIPropBegin(); + Color color = material.GetColor(propertyID); + Color color2 = EditorGUILayout.ColorField(TreeEditorHelper.GetGUIContent(contentID), color, new GUILayoutOption[0]); + if (color2 != color) + { + Undo.RegisterCompleteObjectUndo(material, "Material"); + material.SetColor(propertyID, color2); + result = true; + } + this.GUIPropEnd(); + return result; + } + private bool GUIMaterialSlider(Material material, string propertyID, string contentID) + { + bool result = false; + this.GUIPropBegin(); + float @float = material.GetFloat(propertyID); + float num = EditorGUILayout.Slider(TreeEditorHelper.GetGUIContent(contentID), @float, 0f, 1f, new GUILayoutOption[0]); + if (num != @float) + { + Undo.RegisterCompleteObjectUndo(material, "Material"); + material.SetFloat(propertyID, num); + result = true; + } + this.GUIPropEnd(); + return result; + } + private bool GUIMaterialFloatField(Material material, string propertyID, string contentID) + { + bool flag; + float materialFloat = TreeEditor.GetMaterialFloat(material, propertyID, out flag); + if (!flag) + { + return false; + } + bool result = false; + this.GUIPropBegin(); + float num = EditorGUILayout.FloatField(TreeEditorHelper.GetGUIContent(contentID), materialFloat, new GUILayoutOption[0]); + if (num != materialFloat) + { + Undo.RegisterCompleteObjectUndo(material, "Material"); + material.SetFloat(propertyID, num); + result = true; + } + this.GUIPropEnd(); + return result; + } + private static float GetMaterialFloat(Material material, string propertyID, out bool success) + { + success = false; + if (!material.HasProperty(propertyID)) + { + return 0f; + } + success = true; + return material.GetFloat(propertyID); + } + private static float GetMaterialFloat(Material material, string propertyID) + { + bool flag; + return TreeEditor.GetMaterialFloat(material, propertyID, out flag); + } + private static float GenerateMaterialHash(Material material) + { + float num = 0f; + Color color = material.GetColor("_TranslucencyColor"); + num += color.r + color.g + color.b + color.a; + num += TreeEditor.GetMaterialFloat(material, "_Cutoff"); + num += TreeEditor.GetMaterialFloat(material, "_TranslucencyViewDependency"); + num += TreeEditor.GetMaterialFloat(material, "_ShadowStrength"); + return num + TreeEditor.GetMaterialFloat(material, "_ShadowOffsetScale"); + } + public void InspectorRoot(TreeData treeData, TreeGroupRoot group) + { + GUIContent[] expr_06 = new GUIContent[6]; + expr_06[0] = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupRoot.Distribution"); + expr_06[1] = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupRoot.Geometry"); + expr_06[2] = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupRoot.MaterialProperties"); + GUIContent[] names = expr_06; + bool enabled = GUI.enabled; + TreeEditor.BeginSettingsSection(0, names); + this.PrepareSpacing(false); + int seed = group.seed; + group.seed = this.GUIIntSlider(TreeEditor.PropertyType.Normal, "TreeEditor.TreeGroupRoot.GroupSeed", group.seed, 0, 9999999, false); + if (group.seed != seed) + { + treeData.UpdateSeed(group.uniqueID); + } + group.rootSpread = this.GUISlider(TreeEditor.PropertyType.Normal, "TreeEditor.TreeGroupRoot.AreaSpread", group.rootSpread, 0f, 10f, false); + group.groundOffset = this.GUISlider(TreeEditor.PropertyType.Normal, "TreeEditor.TreeGroupRoot.GroundOffset", group.groundOffset, 0f, 10f, false); + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(1, names); + this.PrepareSpacing(false); + group.adaptiveLODQuality = this.GUISlider(TreeEditor.PropertyType.FullUndo, "TreeEditor.TreeGroupRoot.LODQuality", group.adaptiveLODQuality, 0f, 1f, false); + group.enableAmbientOcclusion = this.GUIToggle(TreeEditor.PropertyType.FullUndo, "TreeEditor.TreeGroupRoot.AmbientOcclusion", group.enableAmbientOcclusion, false); + GUI.enabled = group.enableAmbientOcclusion; + group.aoDensity = this.GUISlider(TreeEditor.PropertyType.Normal, "TreeEditor.TreeGroupRoot.AODensity", group.aoDensity, 0f, 1f, false); + GUI.enabled = true; + TreeEditor.EndSettingsSection(); + Material optimizedCutoutMaterial = treeData.optimizedCutoutMaterial; + if (optimizedCutoutMaterial != null) + { + TreeEditor.BeginSettingsSection(2, names); + this.PrepareSpacing(false); + bool changed = GUI.changed; + bool flag = this.GUIMaterialColor(optimizedCutoutMaterial, "_TranslucencyColor", "TreeEditor.TreeGroupRoot.TranslucencyColor"); + flag |= this.GUIMaterialSlider(optimizedCutoutMaterial, "_TranslucencyViewDependency", "TreeEditor.TreeGroupRoot.TranslucencyViewDependency"); + flag |= this.GUIMaterialSlider(optimizedCutoutMaterial, "_Cutoff", "TreeEditor.TreeGroupRoot.AlphaCutoff"); + flag |= this.GUIMaterialSlider(optimizedCutoutMaterial, "_ShadowStrength", "TreeEditor.TreeGroupRoot.ShadowStrength"); + flag |= this.GUIMaterialFloatField(optimizedCutoutMaterial, "_ShadowOffsetScale", "TreeEditor.TreeGroupRoot.ShadowOffsetScale"); + if (flag) + { + TreeEditor.s_CutoutMaterialHashBeforeUndo = TreeEditor.GenerateMaterialHash(treeData.optimizedCutoutMaterial); + } + string[] optionIDs = new string[] + { + "Full", + "Half", + "Quarter", + "OneEighth", + "OneSixteenth" + }; + group.shadowTextureQuality = this.GUIPopup(TreeEditor.PropertyType.FullUpdate, "TreeEditor.TreeGroupRoot.ShadowTextureQuality", "TreeEditor.TreeGroupRoot.ShadowTextureQualityOption", optionIDs, group.shadowTextureQuality, false); + GUI.changed = changed; + TreeEditor.EndSettingsSection(); + } + GUI.enabled = enabled; + EditorGUILayout.Space(); + } + public void InspectorBranch(TreeData treeData, TreeGroupBranch group) + { + this.InspectorEditTools(this.target as Tree); + GUIContent[] names = new GUIContent[] + { + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupBranch.Distribution"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupBranch.Geometry"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupBranch.Shape"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupBranch.Fronds"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupBranch.Animation") + }; + string str = "TreeEditor.TreeGroupBranch."; + bool enabled = GUI.enabled; + if (TreeEditor.s_SelectedGroup.lockFlags != 0) + { + this.GUIunlockbox(treeData); + } + TreeEditor.BeginSettingsSection(0, names); + this.InspectorDistribution(treeData, group); + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(1, names); + this.PrepareSpacing(false); + group.lodQualityMultiplier = this.GUISlider(TreeEditor.PropertyType.Normal, str + "LODQuality", group.lodQualityMultiplier, 0f, 2f, false); + string[] optionIDs = new string[] + { + "BranchOnly", + "BranchAndFronds", + "FrondsOnly" + }; + group.geometryMode = (TreeGroupBranch.GeometryMode)this.GUIPopup(TreeEditor.PropertyType.FullUpdate, str + "GeometryMode", str + "GeometryModeOption", optionIDs, (int)group.geometryMode, false); + if (group.geometryMode != TreeGroupBranch.GeometryMode.Frond) + { + group.materialBranch = this.GUIMaterialField(TreeEditor.PropertyType.FullUpdate, group.uniqueID, str + "BranchMaterial", group.materialBranch, TreeEditorHelper.NodeType.BarkNode); + } + group.materialBreak = this.GUIMaterialField(TreeEditor.PropertyType.FullUpdate, group.uniqueID, str + "BreakMaterial", group.materialBreak, TreeEditorHelper.NodeType.BarkNode); + if (group.geometryMode != TreeGroupBranch.GeometryMode.Branch) + { + group.materialFrond = this.GUIMaterialField(TreeEditor.PropertyType.FullUpdate, group.uniqueID, str + "FrondMaterial", group.materialFrond, TreeEditorHelper.NodeType.BarkNode); + } + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(2, names); + this.PrepareSpacing(true); + GUI.enabled = (group.lockFlags == 0); + group.height = this.GUIMinMaxSlider(TreeEditor.PropertyType.Normal, str + "Length", group.height, 0.1f, 50f, false); + GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); + group.radiusMode = this.GUIToggle(TreeEditor.PropertyType.Normal, str + "IsLengthRelative", group.radiusMode, false); + GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); + group.radius = this.GUISlider(TreeEditor.PropertyType.Normal, str + "Radius", group.radius, 0.1f, 5f, true); + AnimationCurve animationCurve = group.radiusCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.radiusCurve = animationCurve; + } + GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); + group.capSmoothing = this.GUISlider(TreeEditor.PropertyType.Normal, str + "CapSmoothing", group.capSmoothing, 0f, 1f, false); + GUI.enabled = true; + EditorGUILayout.Space(); + GUI.enabled = (group.lockFlags == 0); + group.crinklyness = this.GUISlider(TreeEditor.PropertyType.Normal, str + "Crinklyness", group.crinklyness, 0f, 1f, true); + animationCurve = group.crinkCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.crinkCurve = animationCurve; + } + GUI.enabled = (group.lockFlags == 0); + group.seekBlend = this.GUISlider(TreeEditor.PropertyType.Normal, str + "SeekSunGround", group.seekBlend, 0f, 1f, true); + animationCurve = group.seekCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesB)) + { + group.seekCurve = animationCurve; + } + GUI.enabled = true; + EditorGUILayout.Space(); + GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); + group.noise = this.GUISlider(TreeEditor.PropertyType.Normal, str + "Noise", group.noise, 0f, 1f, true); + animationCurve = group.noiseCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.noiseCurve = animationCurve; + } + group.noiseScaleU = this.GUISlider(TreeEditor.PropertyType.Normal, str + "NoiseScaleU", group.noiseScaleU, 0f, 1f, false); + group.noiseScaleV = this.GUISlider(TreeEditor.PropertyType.Normal, str + "NoiseScaleV", group.noiseScaleV, 0f, 1f, false); + EditorGUILayout.Space(); + GUI.enabled = (group.geometryMode != TreeGroupBranch.GeometryMode.Frond); + if (treeData.GetGroup(group.parentGroupID) == treeData.root) + { + group.flareSize = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FlareRadius", group.flareSize, 0f, 5f, false); + group.flareHeight = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FlareHeight", group.flareHeight, 0f, 1f, false); + group.flareNoise = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FlareNoise", group.flareNoise, 0f, 1f, false); + } + else + { + group.weldHeight = this.GUISlider(TreeEditor.PropertyType.Normal, str + "WeldHeight", group.weldHeight, 0.01f, 1f, false); + group.weldSpreadTop = this.GUISlider(TreeEditor.PropertyType.Normal, str + "WeldSpreadTop", group.weldSpreadTop, 0f, 1f, false); + group.weldSpreadBottom = this.GUISlider(TreeEditor.PropertyType.Normal, str + "WeldSpreadBottom", group.weldSpreadBottom, 0f, 1f, false); + } + EditorGUILayout.Space(); + group.breakingChance = this.GUISlider(TreeEditor.PropertyType.Normal, str + "BreakChance", group.breakingChance, 0f, 1f, false); + group.breakingSpot = this.GUIMinMaxSlider(TreeEditor.PropertyType.Normal, str + "BreakLocation", group.breakingSpot, 0f, 1f, false); + TreeEditor.EndSettingsSection(); + if (group.geometryMode != TreeGroupBranch.GeometryMode.Branch) + { + TreeEditor.BeginSettingsSection(3, names); + this.PrepareSpacing(true); + group.frondCount = this.GUIIntSlider(TreeEditor.PropertyType.Normal, str + "FrondCount", group.frondCount, 1, 16, false); + group.frondWidth = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FrondWidth", group.frondWidth, 0.1f, 10f, true); + animationCurve = group.frondCurve; + if (this.GUICurve(TreeEditor.PropertyType.Normal, animationCurve, this.m_CurveRangesA)) + { + group.frondCurve = animationCurve; + } + group.frondRange = this.GUIMinMaxSlider(TreeEditor.PropertyType.Normal, str + "FrondRange", group.frondRange, 0f, 1f, false); + group.frondRotation = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FrondRotation", group.frondRotation, 0f, 1f, false); + group.frondCrease = this.GUISlider(TreeEditor.PropertyType.Normal, str + "FrondCrease", group.frondCrease, -1f, 1f, false); + GUI.enabled = true; + TreeEditor.EndSettingsSection(); + } + TreeEditor.BeginSettingsSection(4, names); + this.InspectorAnimation(treeData, group); + TreeEditor.EndSettingsSection(); + GUI.enabled = enabled; + EditorGUILayout.Space(); + } + public void InspectorLeaf(TreeData treeData, TreeGroupLeaf group) + { + this.InspectorEditTools(this.target as Tree); + GUIContent[] names = new GUIContent[] + { + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupLeaf.Distribution"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupLeaf.Geometry"), + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupLeaf.Shape"), + null, + null, + TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroupLeaf.Animation") + }; + string str = "TreeEditor.TreeGroupLeaf."; + bool enabled = GUI.enabled; + if (TreeEditor.s_SelectedGroup.lockFlags != 0) + { + this.GUIunlockbox(treeData); + } + TreeEditor.BeginSettingsSection(0, names); + this.InspectorDistribution(treeData, group); + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(1, names); + this.PrepareSpacing(false); + string[] optionIDs = new string[] + { + "Plane", + "Cross", + "TriCross", + "Billboard", + "Mesh" + }; + group.geometryMode = this.GUIPopup(TreeEditor.PropertyType.FullUpdate, str + "GeometryMode", str + "GeometryModeOption", optionIDs, group.geometryMode, false); + if (group.geometryMode != 4) + { + group.materialLeaf = this.GUIMaterialField(TreeEditor.PropertyType.FullUpdate, group.uniqueID, str + "Material", group.materialLeaf, TreeEditorHelper.NodeType.LeafNode); + } + if (group.geometryMode == 4) + { + group.instanceMesh = (this.GUIObjectField(TreeEditor.PropertyType.FullUpdate, str + "Mesh", group.instanceMesh, typeof(GameObject), false) as GameObject); + } + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(2, names); + this.PrepareSpacing(false); + group.size = this.GUIMinMaxSlider(TreeEditor.PropertyType.Normal, str + "Size", group.size, 0.1f, 2f, false); + group.perpendicularAlign = this.GUISlider(TreeEditor.PropertyType.Normal, str + "PerpendicularAlign", group.perpendicularAlign, 0f, 1f, false); + group.horizontalAlign = this.GUISlider(TreeEditor.PropertyType.Normal, str + "HorizontalAlign", group.horizontalAlign, 0f, 1f, false); + TreeEditor.EndSettingsSection(); + TreeEditor.BeginSettingsSection(5, names); + this.PrepareSpacing(false); + this.InspectorAnimation(treeData, group); + TreeEditor.EndSettingsSection(); + GUI.enabled = enabled; + EditorGUILayout.Space(); + } + public override bool UseDefaultMargins() + { + return false; + } + public override void OnInspectorGUI() + { + Tree tree = this.target as Tree; + TreeData treeData = TreeEditor.GetTreeData(tree); + if (!treeData) + { + return; + } + Renderer renderer = tree.renderer; + this.VerifySelection(treeData); + if (TreeEditor.s_SelectedGroup == null) + { + return; + } + this.m_WantCompleteUpdate = false; + EventType typeForControl = Event.current.GetTypeForControl(GUIUtility.hotControl); + if ((typeForControl == EventType.MouseUp || (typeForControl == EventType.KeyUp && Event.current.keyCode == KeyCode.Return) || (typeForControl == EventType.ExecuteCommand && Event.current.commandName == "OnLostFocus")) && treeData.isInPreviewMode) + { + this.m_WantCompleteUpdate = true; + } + if (this.OnCheckHotkeys(treeData, true)) + { + return; + } + this.m_TreeEditorHelper.RefreshAllTreeShaders(); + if (this.m_TreeEditorHelper.GUITooManyShaders()) + { + this.m_WantCompleteUpdate = true; + } + EditorGUILayout.Space(); + EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins, new GUILayoutOption[0]); + this.InspectorHierachy(treeData, renderer); + EditorGUILayout.EndVertical(); + EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + if (TreeEditor.s_SelectedGroup != null) + { + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupBranch)) + { + this.InspectorBranch(treeData, (TreeGroupBranch)TreeEditor.s_SelectedGroup); + } + else + { + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupLeaf)) + { + this.InspectorLeaf(treeData, (TreeGroupLeaf)TreeEditor.s_SelectedGroup); + } + else + { + if (TreeEditor.s_SelectedGroup.GetType() == typeof(TreeGroupRoot)) + { + this.InspectorRoot(treeData, (TreeGroupRoot)TreeEditor.s_SelectedGroup); + } + } + } + } + EditorGUILayout.EndVertical(); + if (this.m_WantedCompleteUpdateInPreviousFrame) + { + this.m_WantCompleteUpdate = true; + } + this.m_WantedCompleteUpdateInPreviousFrame = false; + if (this.m_WantCompleteUpdate) + { + GUI.changed = true; + } + if (GUI.changed) + { + if (!this.m_TreeEditorHelper.AreShadersCorrect()) + { + this.m_WantedCompleteUpdateInPreviousFrame = this.m_WantCompleteUpdate; + return; + } + if (this.m_WantCompleteUpdate) + { + TreeEditor.UpdateMesh(tree); + this.m_WantCompleteUpdate = false; + } + else + { + TreeEditor.PreviewMesh(tree); + } + } + } + private void DrawHierachy(TreeData treeData, Renderer renderer, Rect sizeRect) + { + if (TreeEditor.styles == null) + { + TreeEditor.styles = new TreeEditor.Styles(); + } + this.hierachySpread = this.hierachyNodeSize + this.hierachyNodeSpace; + this.hierachyView = sizeRect; + Event @event = new Event(Event.current); + List nodes = new List(); + this.BuildHierachyNodes(treeData, nodes, treeData.root, 0); + this.LayoutHierachyNodes(nodes, sizeRect); + float num = 16f; + Vector2 zero = Vector2.zero; + if (sizeRect.width < this.hierachyRect.width) + { + zero.y -= 16f; + } + bool changed = GUI.changed; + this.hierachyDisplayRect = GUILayoutUtility.GetRect(sizeRect.width, this.hierachyRect.height + num); + this.hierachyDisplayRect.width = sizeRect.width; + GUI.Box(this.hierachyDisplayRect, GUIContent.none, TreeEditor.styles.nodeBackground); + this.hierachyScroll = GUI.BeginScrollView(this.hierachyDisplayRect, this.hierachyScroll, this.hierachyRect, false, false); + GUI.changed = changed; + this.HandleDragHierachyNodes(treeData, nodes); + this.DrawHierachyNodes(treeData, nodes, treeData.root, zero / 2f, 1f, 1f); + if (this.dragNode != null && this.isDragging) + { + Vector2 a = Event.current.mousePosition - this.dragClickPos; + this.DrawHierachyNodes(treeData, nodes, this.dragNode.group, a + zero / 2f, 0.5f, 0.5f); + } + GUI.EndScrollView(); + MeshFilter component = renderer.GetComponent(); + if (component && component.sharedMesh && renderer) + { + int num2 = component.sharedMesh.vertices.Length; + int num3 = component.sharedMesh.triangles.Length / 3; + int num4 = renderer.sharedMaterials.Length; + Rect position = new Rect(this.hierachyDisplayRect.xMax - 80f - 4f, this.hierachyDisplayRect.yMax + zero.y - 40f - 4f, 80f, 40f); + string text = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.Stats").text; + text = text.Replace("[v]", num2.ToString()); + text = text.Replace("[t]", num3.ToString()); + text = text.Replace("[m]", num4.ToString()); + text = text.Replace(" / ", "\n"); + GUI.Label(position, text, EditorStyles.helpBox); + } + if (@event.type == EventType.ScrollWheel && Event.current.type == EventType.Used) + { + Event.current = @event; + } + } + private void BuildHierachyNodes(TreeData treeData, List nodes, TreeGroup group, int depth) + { + nodes.Add(new TreeEditor.HierachyNode + { + group = group, + pos = new Vector3(0f, (float)depth * this.hierachySpread.y, 0f) + }); + for (int i = 0; i < group.childGroupIDs.Length; i++) + { + TreeGroup group2 = treeData.GetGroup(group.childGroupIDs[i]); + this.BuildHierachyNodes(treeData, nodes, group2, depth - 1); + } + } + private void LayoutHierachyNodes(List nodes, Rect sizeRect) + { + Bounds bounds = default(Bounds); + for (int i = 0; i < nodes.Count; i++) + { + for (int j = i + 1; j < nodes.Count; j++) + { + if (nodes[i].pos.y == nodes[j].pos.y) + { + TreeEditor.HierachyNode expr_4B_cp_0 = nodes[i]; + expr_4B_cp_0.pos.x = expr_4B_cp_0.pos.x - this.hierachySpread.x * 0.5f; + nodes[j].pos.x = nodes[i].pos.x + this.hierachySpread.x; + } + } + bounds.Encapsulate(nodes[i].pos); + } + bounds.Expand(this.hierachySpread); + this.hierachyRect = new Rect(0f, 0f, bounds.size.x, bounds.size.y); + this.hierachyRect.width = Mathf.Max(this.hierachyRect.width, this.hierachyView.width); + Vector3 vector = new Vector3((this.hierachyRect.xMax + this.hierachyRect.xMin) * 0.5f, (this.hierachyRect.yMax + this.hierachyRect.yMin) * 0.5f, 0f); + vector.y += 8f; + for (int k = 0; k < nodes.Count; k++) + { + nodes[k].pos -= bounds.center; + TreeEditor.HierachyNode expr_1C3_cp_0 = nodes[k]; + expr_1C3_cp_0.pos.x = expr_1C3_cp_0.pos.x + vector.x; + TreeEditor.HierachyNode expr_1E3_cp_0 = nodes[k]; + expr_1E3_cp_0.pos.y = expr_1E3_cp_0.pos.y + vector.y; + nodes[k].rect = new Rect(nodes[k].pos.x - this.hierachyNodeSize.x * 0.5f, nodes[k].pos.y - this.hierachyNodeSize.y * 0.5f, this.hierachyNodeSize.x, this.hierachyNodeSize.y); + } + } + private void HandleDragHierachyNodes(TreeData treeData, List nodes) + { + if (this.dragNode == null) + { + this.isDragging = false; + this.dropNode = null; + } + int controlID = GUIUtility.GetControlID(FocusType.Passive); + EventType typeForControl = Event.current.GetTypeForControl(controlID); + if (typeForControl == EventType.MouseDown && Event.current.button == 0) + { + for (int i = 0; i < nodes.Count; i++) + { + if (nodes[i].rect.Contains(Event.current.mousePosition)) + { + if (!this.GetHierachyNodeVisRect(nodes[i].rect).Contains(Event.current.mousePosition)) + { + if (!(nodes[i].group is TreeGroupRoot)) + { + this.dragClickPos = Event.current.mousePosition; + this.dragNode = nodes[i]; + GUIUtility.hotControl = controlID; + Event.current.Use(); + break; + } + } + } + } + } + if (this.dragNode != null) + { + this.dropNode = null; + for (int j = 0; j < nodes.Count; j++) + { + if (nodes[j].rect.Contains(Event.current.mousePosition)) + { + TreeGroup group = this.dragNode.group; + TreeGroup group2 = nodes[j].group; + if (group2 != group) + { + if (group2.CanHaveSubGroups()) + { + if (treeData.GetGroup(group.parentGroupID) != group2) + { + if (!treeData.IsAncestor(group, group2)) + { + this.dropNode = nodes[j]; + break; + } + } + } + } + } + } + if (typeForControl == EventType.MouseMove || typeForControl == EventType.MouseDrag) + { + if ((this.dragClickPos - Event.current.mousePosition).magnitude > 10f) + { + this.isDragging = true; + } + Event.current.Use(); + } + else + { + if (typeForControl == EventType.MouseUp && GUIUtility.hotControl == controlID) + { + if (this.dropNode != null) + { + this.UndoStoreSelected(TreeEditor.EditMode.Everything); + TreeGroup group3 = this.dragNode.group; + TreeGroup group4 = this.dropNode.group; + treeData.SetGroupParent(group3, group4); + this.m_WantCompleteUpdate = true; + } + else + { + base.Repaint(); + } + this.dragNode = null; + this.dropNode = null; + GUIUtility.hotControl = 0; + Event.current.Use(); + } + } + } + } + private Rect GetHierachyNodeVisRect(Rect rect) + { + return new Rect(rect.x + rect.width - 13f - 1f, rect.y + 11f, 13f, 11f); + } + private void DrawHierachyNodes(TreeData treeData, List nodes, TreeGroup group, Vector2 offset, float alpha, float fade) + { + if (this.dragNode != null && this.isDragging && this.dragNode.group == group) + { + alpha = 0.5f; + fade = 0.75f; + } + Vector3 b = new Vector3(0f, this.hierachyNodeSize.y * 0.5f, 0f); + Vector3 b2 = new Vector3(offset.x, offset.y); + Handles.color = new Color(0f, 0f, 0f, 0.5f * alpha); + if (EditorGUIUtility.isProSkin) + { + Handles.color = new Color(0.4f, 0.4f, 0.4f, 0.5f * alpha); + } + TreeEditor.HierachyNode hierachyNode = null; + for (int i = 0; i < nodes.Count; i++) + { + if (group == nodes[i].group) + { + hierachyNode = nodes[i]; + break; + } + } + if (hierachyNode == null) + { + return; + } + for (int j = 0; j < group.childGroupIDs.Length; j++) + { + TreeGroup group2 = treeData.GetGroup(group.childGroupIDs[j]); + for (int k = 0; k < nodes.Count; k++) + { + if (nodes[k].group == group2) + { + Handles.DrawLine(hierachyNode.pos + b2 - b, nodes[k].pos + b2 + b); + } + } + } + Rect rect = hierachyNode.rect; + rect.x += offset.x; + rect.y += offset.y; + int num = 0; + if (hierachyNode == this.dropNode) + { + num = 1; + } + else + { + if (TreeEditor.s_SelectedGroup == hierachyNode.group) + { + if (TreeEditor.s_SelectedNode != null) + { + num = 1; + } + else + { + num = 1; + } + } + } + GUI.backgroundColor = new Color(1f, 1f, 1f, alpha); + GUI.contentColor = new Color(1f, 1f, 1f, alpha); + GUI.Label(rect, GUIContent.none, TreeEditor.styles.nodeBoxes[num]); + Rect position = new Rect(rect.x + rect.width / 2f - 4f, rect.y - 2f, 0f, 0f); + Rect position2 = new Rect(rect.x + rect.width / 2f - 4f, rect.y + rect.height - 2f, 0f, 0f); + Rect position3 = new Rect(rect.x + 1f, rect.yMax - 36f, 32f, 32f); + Rect position4 = new Rect(rect.xMax - 18f, rect.yMax - 18f, 16f, 16f); + Rect position5 = new Rect(rect.x, rect.y, rect.width - 2f, 16f); + bool flag = true; + int num2 = 0; + GUIContent gUIContent = new GUIContent(); + Type type = group.GetType(); + if (type == typeof(TreeGroupBranch)) + { + gUIContent = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.TreeGroupBranch"); + TreeGroupBranch treeGroupBranch = (TreeGroupBranch)group; + switch (treeGroupBranch.geometryMode) + { + case TreeGroupBranch.GeometryMode.Branch: + num2 = 1; + break; + case TreeGroupBranch.GeometryMode.BranchFrond: + num2 = 0; + break; + case TreeGroupBranch.GeometryMode.Frond: + num2 = 2; + break; + } + } + else + { + if (type == typeof(TreeGroupLeaf)) + { + gUIContent = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.TreeGroupLeaf"); + num2 = 3; + } + else + { + if (type == typeof(TreeGroupRoot)) + { + gUIContent = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.TreeGroupRoot"); + num2 = 4; + flag = false; + } + } + } + if (flag) + { + Rect hierachyNodeVisRect = this.GetHierachyNodeVisRect(rect); + GUIContent gUIContent2 = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.ShowHide"); + gUIContent2.image = TreeEditor.styles.visibilityIcons[(!group.visible) ? 1 : 0].image; + GUI.contentColor = new Color(1f, 1f, 1f, 0.7f); + if (GUI.Button(hierachyNodeVisRect, gUIContent2, GUIStyle.none)) + { + group.visible = !group.visible; + GUI.changed = true; + } + GUI.contentColor = Color.white; + } + gUIContent.image = TreeEditor.styles.nodeIcons[num2].image; + GUI.contentColor = new Color(1f, 1f, 1f, (!group.visible) ? 0.5f : 1f); + if (GUI.Button(position3, gUIContent, GUIStyle.none) || this.dragNode == hierachyNode) + { + TreeGroup treeGroup = TreeEditor.s_SelectedGroup; + this.SelectGroup(group); + if (treeGroup == TreeEditor.s_SelectedGroup) + { + Tree tree = this.target as Tree; + this.FrameSelected(tree); + } + } + GUI.contentColor = Color.white; + if (group.CanHaveSubGroups()) + { + GUI.Label(position, GUIContent.none, TreeEditor.styles.pinLabel); + } + if (flag) + { + GUIContent gUIContent3 = TreeEditorHelper.GetGUIContent("TreeEditor.Hierachy.NodeCount"); + gUIContent3.text = group.nodeIDs.Length.ToString(); + GUI.Label(position5, gUIContent3, TreeEditor.styles.nodeLabelTop); + if (this.m_TreeEditorHelper.NodeHasWrongMaterial(group)) + { + GUI.DrawTexture(position4, ConsoleWindow.iconErrorSmall); + } + else + { + if (group.lockFlags != 0) + { + GUI.DrawTexture(position4, TreeEditor.styles.warningIcon.image); + } + } + GUI.Label(position2, GUIContent.none, TreeEditor.styles.pinLabel); + } + for (int l = 0; l < group.childGroupIDs.Length; l++) + { + TreeGroup group3 = treeData.GetGroup(group.childGroupIDs[l]); + this.DrawHierachyNodes(treeData, nodes, group3, offset, alpha * fade, fade); + } + GUI.backgroundColor = Color.white; + GUI.contentColor = Color.white; + } + private static void BeginSettingsSection(int nr, GUIContent[] names) + { + GUILayout.Space(5f); + GUILayout.Label(names[nr].text, EditorStyles.boldLabel, new GUILayoutOption[0]); + } + private static void EndSettingsSection() + { + GUI.enabled = true; + GUILayout.Space(5f); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeEditorHelper.cs b/UnityEditor/TreeEditor/TreeEditorHelper.cs new file mode 100644 index 00000000..20a5e7a5 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeEditorHelper.cs @@ -0,0 +1,423 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace TreeEditor +{ + public class TreeEditorHelper + { + public enum NodeType + { + BarkNode, + LeafNode + } + private const string kDefaultBarkShaderName = "Nature/Tree Creator Bark"; + private const string kDefaultLeafShaderName = "Nature/Tree Creator Leaves Fast"; + private const string kDefaultOptimizedBarkShaderName = "Hidden/Nature/Tree Creator Bark Optimized"; + private const string kDefaultOptimizedLeafShaderName = "Hidden/Nature/Tree Creator Leaves Optimized"; + private const string kOptimizedShaderDependency = "OptimizedShader"; + private readonly Dictionary m_AnimBools = new Dictionary(); + private readonly List m_BarkShaders = new List(); + private readonly List m_LeafShaders = new List(); + private readonly HashSet m_WrongShaders = new HashSet(); + private readonly Dictionary m_SelectedShader = new Dictionary(); + private TreeData m_TreeData; + private static string s_UIText; + private static readonly Dictionary s_Dictionary = new Dictionary(); + internal static Shader DefaultOptimizedBarkShader + { + get + { + return Shader.Find("Hidden/Nature/Tree Creator Bark Optimized"); + } + } + internal static Shader DefaultOptimizedLeafShader + { + get + { + return Shader.Find("Hidden/Nature/Tree Creator Leaves Optimized"); + } + } + private static string uiText + { + get + { + if (TreeEditorHelper.s_UIText == null) + { + TreeEditorHelper.s_UIText = File.ReadAllText(EditorApplication.applicationContentsPath + "/Resources/TreeEditor_UI_Strings_EN.txt"); + } + if (TreeEditorHelper.s_UIText == null) + { + Debug.LogError("Missing asset"); + } + return TreeEditorHelper.s_UIText; + } + } + internal void SetAnimsCallback(UnityAction callback) + { + foreach (KeyValuePair current in this.m_AnimBools) + { + current.Value.valueChanged.AddListener(callback); + } + } + public void OnEnable(TreeData treeData) + { + this.m_TreeData = treeData; + } + public bool AreShadersCorrect() + { + bool flag = this.m_BarkShaders.Count + this.m_LeafShaders.Count > 2; + return this.m_WrongShaders.Count == 0 && !flag; + } + public static string GetOptimizedShaderName(Shader shader) + { + if (shader) + { + return ShaderUtil.GetDependency(shader, "OptimizedShader"); + } + return null; + } + private static bool IsTreeShader(Shader shader) + { + return TreeEditorHelper.IsTreeBarkShader(shader) || TreeEditorHelper.IsTreeLeafShader(shader); + } + public static bool IsTreeLeafShader(Shader shader) + { + return TreeEditorHelper.HasOptimizedShaderAndNameContains(shader, "leaves"); + } + public static bool IsTreeBarkShader(Shader shader) + { + return TreeEditorHelper.HasOptimizedShaderAndNameContains(shader, "bark"); + } + public bool GUITooManyShaders() + { + bool flag = this.GUITooManyShaders(TreeEditorHelper.NodeType.BarkNode); + flag |= this.GUITooManyShaders(TreeEditorHelper.NodeType.LeafNode); + if (flag) + { + this.RefreshAllTreeShaders(); + } + return flag; + } + private bool GUITooManyShaders(TreeEditorHelper.NodeType nodeType) + { + string text = nodeType.ToString(); + if (this.CheckForTooManyShaders(nodeType)) + { + this.SetAnimBool(text, true, true); + } + List shadersListForNodeType = this.GetShadersListForNodeType(nodeType); + GUIContent gUIContent = TreeEditorHelper.GetGUIContent((nodeType != TreeEditorHelper.NodeType.BarkNode) ? "TreeEditor.TreeGroup.TooManyLeafShaders" : "TreeEditor.TreeGroup.TooManyBarkShaders"); + GUIContent gUIContent2 = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroup.ChangeAllShadersOnNodesButton"); + int num = this.GUIShowError(text, shadersListForNodeType, gUIContent, gUIContent2, ConsoleWindow.iconError); + if (num >= 0) + { + Shader shader = Shader.Find(shadersListForNodeType[num]); + TreeEditorHelper.ChangeShaderOnMaterials(this.m_TreeData, shader, this.m_TreeData.root, nodeType); + this.DisableAnimBool(text); + this.RemoveSelectedIndex(text); + return true; + } + return false; + } + public bool GUIWrongShader(string uniqueID, Material value, TreeEditorHelper.NodeType nodeType) + { + GUIContent gUIContent = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroup.NotATreeShader"); + GUIContent gUIContent2 = TreeEditorHelper.GetGUIContent("TreeEditor.TreeGroup.ChangeShaderButton"); + if (TreeEditorHelper.IsMaterialCorrect(value)) + { + return false; + } + List recommendedShaders = this.GetRecommendedShaders(nodeType); + this.m_WrongShaders.Add(uniqueID); + this.SetAnimBool(uniqueID, true, true); + int num = this.GUIShowError(uniqueID, recommendedShaders, gUIContent, gUIContent2, ConsoleWindow.iconError); + if (num >= 0) + { + value.shader = Shader.Find(recommendedShaders[num]); + this.m_WrongShaders.Remove(uniqueID); + this.DisableAnimBool(uniqueID); + this.RemoveSelectedIndex(uniqueID); + return true; + } + return false; + } + private int GUIShowError(string uniqueID, List list, GUIContent message, GUIContent button, Texture2D icon) + { + int result = -1; + if (this.m_AnimBools.ContainsKey(uniqueID)) + { + if (EditorGUILayout.BeginFadeGroup(this.m_AnimBools[uniqueID].faded)) + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + message.image = icon; + GUILayout.Label(message, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + int num = EditorGUILayout.Popup(this.GetSelectedIndex(uniqueID), list.ToArray(), new GUILayoutOption[0]); + this.SetSelectedIndex(uniqueID, num); + if (GUILayout.Button(button, EditorStyles.miniButton, new GUILayoutOption[0])) + { + result = num; + } + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + EditorGUILayout.EndFadeGroup(); + } + return result; + } + public void RefreshAllTreeShaders() + { + this.m_BarkShaders.Clear(); + this.m_LeafShaders.Clear(); + TreeEditorHelper.GetAllTreeShaders(this.m_TreeData, this.m_BarkShaders, this.m_LeafShaders, this.m_TreeData.root); + } + private static void GetAllTreeShaders(TreeData treeData, List barkShaders, List leafShaders, TreeGroup group) + { + if (group is TreeGroupBranch) + { + TreeGroupBranch treeGroupBranch = group as TreeGroupBranch; + TreeEditorHelper.AddShaderFromMaterial(treeGroupBranch.materialBranch, barkShaders, leafShaders); + TreeEditorHelper.AddShaderFromMaterial(treeGroupBranch.materialBreak, barkShaders, leafShaders); + TreeEditorHelper.AddShaderFromMaterial(treeGroupBranch.materialFrond, barkShaders, leafShaders); + } + else + { + if (group is TreeGroupLeaf) + { + TreeGroupLeaf treeGroupLeaf = group as TreeGroupLeaf; + TreeEditorHelper.AddShaderFromMaterial(treeGroupLeaf.materialLeaf, barkShaders, leafShaders); + } + } + int[] childGroupIDs = group.childGroupIDs; + for (int i = 0; i < childGroupIDs.Length; i++) + { + int id = childGroupIDs[i]; + TreeGroup group2 = treeData.GetGroup(id); + TreeEditorHelper.GetAllTreeShaders(treeData, barkShaders, leafShaders, group2); + } + } + public bool NodeHasWrongMaterial(TreeGroup group) + { + bool flag = false; + if (group is TreeGroupBranch) + { + TreeGroupBranch treeGroupBranch = group as TreeGroupBranch; + flag |= !TreeEditorHelper.IsMaterialCorrect(treeGroupBranch.materialBranch); + flag |= !TreeEditorHelper.IsMaterialCorrect(treeGroupBranch.materialBreak); + flag |= !TreeEditorHelper.IsMaterialCorrect(treeGroupBranch.materialFrond); + } + else + { + if (group is TreeGroupLeaf) + { + TreeGroupLeaf treeGroupLeaf = group as TreeGroupLeaf; + flag |= !TreeEditorHelper.IsMaterialCorrect(treeGroupLeaf.materialLeaf); + } + } + return flag; + } + private static bool IsMaterialCorrect(Material material) + { + return !material || TreeEditorHelper.IsTreeShader(material.shader); + } + private List GetShadersListForNodeType(TreeEditorHelper.NodeType nodeType) + { + if (nodeType == TreeEditorHelper.NodeType.BarkNode) + { + return this.m_BarkShaders; + } + return this.m_LeafShaders; + } + private List GetShadersListOppositeToNodeType(TreeEditorHelper.NodeType nodeType) + { + if (nodeType == TreeEditorHelper.NodeType.BarkNode) + { + return this.GetShadersListForNodeType(TreeEditorHelper.NodeType.LeafNode); + } + return this.GetShadersListForNodeType(TreeEditorHelper.NodeType.BarkNode); + } + private static string GetDefaultShader(TreeEditorHelper.NodeType nodeType) + { + if (nodeType == TreeEditorHelper.NodeType.BarkNode) + { + return "Nature/Tree Creator Bark"; + } + return "Nature/Tree Creator Leaves Fast"; + } + private List GetRecommendedShaders(TreeEditorHelper.NodeType nodeType) + { + List list = new List(3); + List shadersListForNodeType = this.GetShadersListForNodeType(nodeType); + List shadersListOppositeToNodeType = this.GetShadersListOppositeToNodeType(nodeType); + if (shadersListForNodeType.Count == 1 || (shadersListForNodeType.Count == 2 && shadersListOppositeToNodeType.Count == 0)) + { + foreach (string current in shadersListForNodeType) + { + list.Add(current); + } + } + if (shadersListForNodeType.Count == 0) + { + list.Add(TreeEditorHelper.GetDefaultShader(nodeType)); + } + return list; + } + private bool CheckForTooManyShaders(TreeEditorHelper.NodeType nodeType) + { + List shadersListForNodeType = this.GetShadersListForNodeType(nodeType); + List shadersListOppositeToNodeType = this.GetShadersListOppositeToNodeType(nodeType); + return shadersListForNodeType.Count > 2 || (shadersListForNodeType.Count == 2 && shadersListOppositeToNodeType.Count > 0); + } + private static bool HasOptimizedShaderAndNameContains(Shader shader, string name) + { + return TreeEditorHelper.GetOptimizedShaderName(shader) != null && shader.name.ToLower().Contains(name); + } + private static void AddShaderFromMaterial(Material material, List barkShaders, List leafShaders) + { + if (material && material.shader) + { + Shader shader = material.shader; + if (TreeEditorHelper.IsTreeBarkShader(shader) && !barkShaders.Contains(shader.name)) + { + barkShaders.Add(shader.name); + } + else + { + if (TreeEditorHelper.IsTreeLeafShader(material.shader) && !leafShaders.Contains(shader.name)) + { + leafShaders.Add(shader.name); + } + } + } + } + private static void ChangeShaderOnMaterial(Material material, Shader shader) + { + if (material && shader) + { + material.shader = shader; + } + } + private static void ChangeShaderOnMaterials(TreeData treeData, Shader shader, TreeGroup group, TreeEditorHelper.NodeType nodeType) + { + if (group is TreeGroupBranch && nodeType == TreeEditorHelper.NodeType.BarkNode) + { + TreeGroupBranch treeGroupBranch = group as TreeGroupBranch; + TreeEditorHelper.ChangeShaderOnMaterial(treeGroupBranch.materialBranch, shader); + TreeEditorHelper.ChangeShaderOnMaterial(treeGroupBranch.materialBreak, shader); + TreeEditorHelper.ChangeShaderOnMaterial(treeGroupBranch.materialFrond, shader); + } + else + { + if (group is TreeGroupLeaf && nodeType == TreeEditorHelper.NodeType.LeafNode) + { + TreeGroupLeaf treeGroupLeaf = group as TreeGroupLeaf; + TreeEditorHelper.ChangeShaderOnMaterial(treeGroupLeaf.materialLeaf, shader); + } + } + int[] childGroupIDs = group.childGroupIDs; + for (int i = 0; i < childGroupIDs.Length; i++) + { + int id = childGroupIDs[i]; + TreeGroup group2 = treeData.GetGroup(id); + TreeEditorHelper.ChangeShaderOnMaterials(treeData, shader, group2, nodeType); + } + } + private void RemoveSelectedIndex(string contentID) + { + this.m_SelectedShader.Remove(contentID); + } + private void SetSelectedIndex(string contentID, int value) + { + if (this.m_SelectedShader.ContainsKey(contentID)) + { + this.m_SelectedShader[contentID] = value; + } + else + { + this.m_SelectedShader.Add(contentID, value); + } + } + private int GetSelectedIndex(string contentID) + { + if (!this.m_SelectedShader.ContainsKey(contentID)) + { + this.m_SelectedShader.Add(contentID, 0); + } + return this.m_SelectedShader[contentID]; + } + private void SetAnimBool(string contentID, bool target, bool value) + { + this.SetAnimBool(contentID, target); + this.m_AnimBools[contentID].value = value; + } + private void SetAnimBool(string contentID, bool target) + { + AnimBool animBool; + if (!this.m_AnimBools.ContainsKey(contentID)) + { + animBool = new AnimBool(); + this.m_AnimBools.Add(contentID, animBool); + } + else + { + animBool = this.m_AnimBools[contentID]; + } + animBool.target = target; + } + private void DisableAnimBool(string contentID) + { + if (this.m_AnimBools.ContainsKey(contentID)) + { + this.m_AnimBools[contentID].target = false; + } + } + public static GUIContent GetGUIContent(string id) + { + if (TreeEditorHelper.s_Dictionary.ContainsKey(id)) + { + return TreeEditorHelper.s_Dictionary[id]; + } + string uIString = TreeEditorHelper.GetUIString(id); + if (uIString == null) + { + return new GUIContent(id, string.Empty); + } + GUIContent gUIContent = new GUIContent(TreeEditorHelper.ExtractLabel(uIString), TreeEditorHelper.ExtractTooltip(uIString)); + TreeEditorHelper.s_Dictionary.Add(id, gUIContent); + return gUIContent; + } + public static string GetUIString(string id) + { + string text = id + ":"; + int num = TreeEditorHelper.uiText.IndexOf(text); + if (num < 0) + { + Debug.LogError("Missing definition for " + id + "!"); + return null; + } + int num2 = TreeEditorHelper.uiText.IndexOf("\n", num); + num += text.Length; + return TreeEditorHelper.uiText.Substring(num, num2 - num); + } + public static string ExtractLabel(string uiString) + { + string[] array = uiString.Split(new char[] + { + '|' + }); + return array[0].Trim(); + } + public static string ExtractTooltip(string uiString) + { + string[] array = uiString.Split(new char[] + { + '|' + }); + return array[1].Trim(); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeGroup.cs b/UnityEditor/TreeEditor/TreeGroup.cs new file mode 100644 index 00000000..8ff6b25a --- /dev/null +++ b/UnityEditor/TreeEditor/TreeGroup.cs @@ -0,0 +1,476 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeGroup + { + public enum LockFlag + { + LockPosition = 1, + LockAlignment, + LockShape = 4 + } + public enum BuildFlag + { + BuildAmbientOcclusion = 1, + BuildWeldParts + } + public enum DistributionMode + { + Random, + Alternate, + Opposite, + Whorled + } + protected static readonly bool GenerateDoubleSidedGeometry = true; + protected static readonly float GenerateBendNormalFactor = 0.4f; + protected static readonly float GenerateBendBillboardNormalFactor = 0.8f; + [SerializeField] + private int _uniqueID = -1; + public int seed = 1234; + [SerializeField] + private int _internalSeed = 1234; + [SerializeField] + internal string m_Hash; + public int distributionFrequency = 1; + public TreeGroup.DistributionMode distributionMode; + public AnimationCurve distributionCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public int distributionNodes = 5; + public float distributionTwirl; + public float distributionPitch; + public AnimationCurve distributionPitchCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public float distributionScale = 1f; + public AnimationCurve distributionScaleCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 0.3f) + }); + public bool showAnimationProps = true; + public float animationPrimary = 0.5f; + public float animationSecondary = 0.5f; + public float animationEdge = 1f; + public bool visible = true; + public int lockFlags; + public int[] nodeIDs = new int[0]; + public int parentGroupID = -1; + public int[] childGroupIDs = new int[0]; + [NonSerialized] + internal List nodes = new List(); + [NonSerialized] + internal TreeGroup parentGroup; + [NonSerialized] + internal List childGroups = new List(); + public int uniqueID + { + get + { + return this._uniqueID; + } + set + { + if (this._uniqueID == -1) + { + this._uniqueID = value; + } + } + } + public virtual float GetRadiusAtTime(TreeNode node, float t, bool includeModifications) + { + return 0f; + } + public virtual bool CanHaveSubGroups() + { + return true; + } + public void Lock() + { + if (this.lockFlags == 0) + { + for (int i = 0; i < this.nodes.Count; i++) + { + this.nodes[i].baseAngle = this.nodes[i].angle; + } + } + this.lockFlags = 7; + } + public void Unlock() + { + this.lockFlags = 0; + } + internal virtual bool HasExternalChanges() + { + return false; + } + public bool CheckExternalChanges() + { + bool flag = this.HasExternalChanges(); + for (int i = 0; i < this.childGroups.Count; i++) + { + flag |= this.childGroups[i].CheckExternalChanges(); + } + return flag; + } + public void UpdateFrequency(TreeData owner) + { + Profiler.BeginSample("UpdateFrequency"); + if (this.distributionFrequency < 1) + { + this.distributionFrequency = 1; + } + if (this.parentGroup == null) + { + this.distributionFrequency = 1; + if (this.nodes.Count < 1) + { + owner.AddNode(this, null, false); + } + } + else + { + if (this.lockFlags == 0 && this.parentGroup != null) + { + int num = 0; + for (int i = 0; i < this.parentGroup.nodes.Count; i++) + { + int num2 = Mathf.RoundToInt((float)this.distributionFrequency * this.parentGroup.nodes[i].GetScale()); + if (num2 < 1) + { + num2 = 1; + } + for (int j = 0; j < num2; j++) + { + if (num < this.nodes.Count) + { + owner.SetNodeParent(this.nodes[num], this.parentGroup.nodes[i]); + } + else + { + owner.AddNode(this, this.parentGroup.nodes[i], false); + } + num++; + } + } + if (num < this.nodes.Count) + { + List list = new List(); + for (int k = num; k < this.nodes.Count; k++) + { + list.Add(this.nodes[k]); + } + for (int l = 0; l < list.Count; l++) + { + owner.DeleteNode(list[l], false); + } + } + this.UpdateSeed(); + this.UpdateDistribution(true, false); + } + } + for (int m = 0; m < this.childGroups.Count; m++) + { + this.childGroups[m].UpdateFrequency(owner); + } + Profiler.EndSample(); + } + public void UpdateSeed() + { + TreeGroup treeGroup = this; + while (treeGroup.parentGroup != null) + { + treeGroup = treeGroup.parentGroup; + } + int num = treeGroup.seed; + this._internalSeed = num + (int)((float)this.seed * 1.21f); + for (int i = 0; i < this.nodes.Count; i++) + { + this.nodes[i].seed = num + this._internalSeed + (int)((float)i * 3.7482f); + } + for (int j = 0; j < this.childGroups.Count; j++) + { + this.childGroups[j].UpdateSeed(); + } + } + public Vector2 ComputeWindFactor(TreeNode node, float offset) + { + Vector2 result; + if (node.group.parentGroup.GetType() == typeof(TreeGroupRoot)) + { + result = new Vector2(0f, 0f); + } + else + { + result = node.parent.group.ComputeWindFactor(node.parent, node.offset); + } + float scale = node.GetScale(); + result.x += offset * offset * offset * scale * this.animationPrimary; + result.y += offset * offset * scale * this.animationSecondary; + return result; + } + private float ComputeOffset(int index, int count, float distributionSum, float distributionStep) + { + float num = 0f; + float num2 = ((float)index + 1f) / ((float)count + 1f) * distributionSum; + for (float num3 = 0f; num3 <= 1f; num3 += distributionStep) + { + num += Mathf.Clamp01(this.distributionCurve.Evaluate(num3)); + if (num >= num2) + { + return num3; + } + } + return num2 / distributionSum; + } + public float GetRootSpread() + { + TreeGroup treeGroup = this; + while (treeGroup.parentGroup != null) + { + treeGroup = treeGroup.parentGroup; + } + return treeGroup.nodes[0].size; + } + public Matrix4x4 GetRootMatrix() + { + TreeGroup treeGroup = this; + while (treeGroup.parentGroup != null) + { + treeGroup = treeGroup.parentGroup; + } + return treeGroup.nodes[0].matrix; + } + public void UpdateDistribution(bool completeUpdate, bool updateSubGroups) + { + Profiler.BeginSample("UpdateDistribution"); + UnityEngine.Random.seed = this._internalSeed; + if (completeUpdate) + { + float num = 0f; + float[] array = new float[100]; + float distributionStep = 1f / (float)array.Length; + float num2 = (float)array.Length - 1f; + for (int i = 0; i < array.Length; i++) + { + float time = (float)i / num2; + array[i] = Mathf.Clamp01(this.distributionCurve.Evaluate(time)); + num += array[i]; + } + for (int j = 0; j < this.nodes.Count; j++) + { + TreeNode treeNode = this.nodes[j]; + if (this.lockFlags == 0) + { + if (j == 0 && this.nodes.Count == 1 && (this.parentGroup == null || this.parentGroup.GetType() == typeof(TreeGroupRoot))) + { + treeNode.offset = 0f; + treeNode.baseAngle = 0f; + treeNode.pitch = 0f; + treeNode.scale = Mathf.Clamp01(this.distributionScaleCurve.Evaluate(treeNode.offset)) * this.distributionScale + (1f - this.distributionScale); + } + else + { + int num3 = 0; + int num4 = 0; + for (int k = 0; k < this.nodes.Count; k++) + { + if (this.nodes[k].parentID == treeNode.parentID) + { + if (j == k) + { + num3 = num4; + } + num4++; + } + } + switch (this.distributionMode) + { + case TreeGroup.DistributionMode.Random: + { + float offset = 0f; + float num5 = 0f; + for (int l = 0; l < 5; l++) + { + num5 = UnityEngine.Random.value * num; + } + for (int m = 0; m < array.Length; m++) + { + offset = (float)m / num2; + num5 -= array[m]; + if (num5 <= 0f) + { + break; + } + } + treeNode.baseAngle = UnityEngine.Random.value * 360f; + treeNode.offset = offset; + break; + } + case TreeGroup.DistributionMode.Alternate: + { + float num6 = this.ComputeOffset(num3, num4, num, distributionStep); + float num7 = 180f * (float)num3; + treeNode.baseAngle = num7 + num6 * this.distributionTwirl * 360f; + treeNode.offset = num6; + break; + } + case TreeGroup.DistributionMode.Opposite: + { + float num8 = this.ComputeOffset(num3 / 2, num4 / 2, num, distributionStep); + float num9 = 90f * (float)(num3 / 2) + (float)(num3 % 2) * 180f; + treeNode.baseAngle = num9 + num8 * this.distributionTwirl * 360f; + treeNode.offset = num8; + break; + } + case TreeGroup.DistributionMode.Whorled: + { + int num10 = this.distributionNodes; + int num11 = num3 % num10; + int num12 = num3 / num10; + float num13 = this.ComputeOffset(num3 / num10, num4 / num10, num, distributionStep); + float num14 = 360f / (float)num10 * (float)num11 + 180f / (float)num10 * (float)num12; + treeNode.baseAngle = num14 + num13 * this.distributionTwirl * 360f; + treeNode.offset = num13; + break; + } + } + } + } + } + } + for (int n = 0; n < this.nodes.Count; n++) + { + TreeNode treeNode2 = this.nodes[n]; + if (treeNode2.parent == null) + { + treeNode2.visible = true; + } + else + { + treeNode2.visible = treeNode2.parent.visible; + if (treeNode2.offset > treeNode2.parent.breakOffset) + { + treeNode2.visible = false; + } + } + if (this.lockFlags == 0) + { + treeNode2.angle = treeNode2.baseAngle; + treeNode2.pitch = Mathf.Clamp(this.distributionPitchCurve.Evaluate(treeNode2.offset), -1f, 1f) * -75f * this.distributionPitch; + } + else + { + treeNode2.angle = treeNode2.baseAngle; + } + treeNode2.scale = Mathf.Clamp01(this.distributionScaleCurve.Evaluate(treeNode2.offset)) * this.distributionScale + (1f - this.distributionScale); + } + if (this.parentGroup == null || this.parentGroup.GetType() == typeof(TreeGroupRoot)) + { + for (int num15 = 0; num15 < this.nodes.Count; num15++) + { + this.nodes[num15].animSeed = 0f; + } + } + else + { + for (int num16 = 0; num16 < this.nodes.Count; num16++) + { + if (this.nodes[num16].parent == null) + { + this.nodes[num16].animSeed = 0f; + } + else + { + if (this.nodes[num16].parent.animSeed == 0f) + { + this.nodes[num16].animSeed = (float)this.nodes[num16].seed / 9.78f % 1f + 0.001f; + } + else + { + this.nodes[num16].animSeed = this.nodes[num16].parent.animSeed; + } + } + } + } + if (updateSubGroups) + { + for (int num17 = 0; num17 < this.childGroups.Count; num17++) + { + this.childGroups[num17].UpdateDistribution(completeUpdate, updateSubGroups); + } + } + Profiler.EndSample(); + } + public virtual void UpdateParameters() + { + for (int i = 0; i < this.childGroups.Count; i++) + { + this.childGroups[i].UpdateParameters(); + } + } + public virtual void BuildAOSpheres(List aoSpheres) + { + Profiler.BeginSample("BuildAOSpheres"); + for (int i = 0; i < this.childGroups.Count; i++) + { + this.childGroups[i].BuildAOSpheres(aoSpheres); + } + Profiler.EndSample(); + } + public virtual void UpdateMesh(List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + for (int i = 0; i < this.childGroups.Count; i++) + { + this.childGroups[i].UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); + } + } + public virtual void UpdateMatrix() + { + } + protected static int GetMaterialIndex(Material m, List materials, bool tileV) + { + for (int i = 0; i < materials.Count; i++) + { + if (materials[i].material == m) + { + materials[i].tileV |= tileV; + return i; + } + } + materials.Add(new TreeMaterial + { + material = m, + tileV = tileV + }); + return materials.Count - 1; + } + protected static Vector4 CreateTangent(TreeNode node, Quaternion rot, Vector3 normal) + { + Vector3 vector = node.matrix.MultiplyVector(rot * new Vector3(1f, 0f, 0f)); + vector -= normal * Vector3.Dot(vector, normal); + vector.Normalize(); + return new Vector4(vector.x, vector.y, vector.z, 1f); + } + protected static float ComputeAmbientOcclusion(Vector3 pos, Vector3 nor, List aoSpheres, float aoDensity) + { + if (aoSpheres.Count == 0) + { + return 1f; + } + float num = 0f; + for (int i = 0; i < aoSpheres.Count; i++) + { + num += aoSpheres[i].PointOcclusion(pos, nor) * aoSpheres[i].density * 0.25f; + } + return 1f - Mathf.Clamp01(num) * aoDensity; + } + } +} diff --git a/UnityEditor/TreeEditor/TreeGroupBranch.cs b/UnityEditor/TreeEditor/TreeGroupBranch.cs new file mode 100644 index 00000000..9e441778 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeGroupBranch.cs @@ -0,0 +1,721 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeGroupBranch : TreeGroup + { + public enum GeometryMode + { + Branch, + BranchFrond, + Frond + } + private static float spreadMul = 5f; + public float lodQualityMultiplier = 1f; + public TreeGroupBranch.GeometryMode geometryMode; + public Material materialBranch; + public Material materialBreak; + public Material materialFrond; + public Vector2 height = new Vector2(10f, 15f); + public float radius = 0.5f; + public AnimationCurve radiusCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f, -1f, -1f), + new Keyframe(1f, 0f, -1f, -1f) + }); + public bool radiusMode = true; + public float capSmoothing; + public float crinklyness = 0.1f; + public AnimationCurve crinkCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public float seekBlend; + public AnimationCurve seekCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public float noise = 0.1f; + public AnimationCurve noiseCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public float noiseScaleU = 0.2f; + public float noiseScaleV = 0.1f; + public float flareSize; + public float flareHeight = 0.1f; + public float flareNoise = 0.3f; + public float weldHeight = 0.1f; + public float weldSpreadTop; + public float weldSpreadBottom; + public float breakingChance; + public Vector2 breakingSpot = new Vector2(0.4f, 0.6f); + public int frondCount = 1; + public float frondWidth = 1f; + public AnimationCurve frondCurve = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 1f), + new Keyframe(1f, 1f) + }); + public Vector2 frondRange = new Vector2(0.1f, 1f); + public float frondRotation; + public float frondCrease; + internal override bool HasExternalChanges() + { + List list = new List(); + if (this.geometryMode == TreeGroupBranch.GeometryMode.Branch) + { + list.Add(this.materialBranch); + if (this.breakingChance > 0f) + { + list.Add(this.materialBreak); + } + } + else + { + if (this.geometryMode == TreeGroupBranch.GeometryMode.BranchFrond) + { + list.Add(this.materialBranch); + list.Add(this.materialFrond); + if (this.breakingChance > 0f) + { + list.Add(this.materialBreak); + } + } + else + { + if (this.geometryMode == TreeGroupBranch.GeometryMode.Frond) + { + list.Add(this.materialFrond); + } + } + } + string text = InternalEditorUtility.CalculateHashForObjectsAndDependencies(list.ToArray()); + if (text != this.m_Hash) + { + this.m_Hash = text; + return true; + } + return false; + } + private Vector3 GetFlareWeldAtTime(TreeNode node, float time) + { + float scale = node.GetScale(); + float num = 0f; + float num2 = 0f; + if (this.flareHeight > 0.001f) + { + float value = (1f - time - (1f - this.flareHeight)) / this.flareHeight; + num = Mathf.Pow(Mathf.Clamp01(value), 1.5f) * scale; + } + if (this.weldHeight > 0.001f) + { + float value2 = (1f - time - (1f - this.weldHeight)) / this.weldHeight; + num2 = Mathf.Pow(Mathf.Clamp01(value2), 1.5f) * scale; + } + return new Vector3(num * this.flareSize, num2 * this.weldSpreadTop * TreeGroupBranch.spreadMul, num2 * this.weldSpreadBottom * TreeGroupBranch.spreadMul); + } + public override float GetRadiusAtTime(TreeNode node, float time, bool includeModifications) + { + if (this.geometryMode == TreeGroupBranch.GeometryMode.Frond) + { + return 0f; + } + float num = Mathf.Clamp01(this.radiusCurve.Evaluate(time)) * node.size; + float num2 = 1f - node.capRange; + if (time > num2) + { + float f = Mathf.Acos(Mathf.Clamp01((time - num2) / node.capRange)); + float num3 = Mathf.Sin(f); + num *= num3; + } + if (includeModifications) + { + Vector3 flareWeldAtTime = this.GetFlareWeldAtTime(node, time); + num += Mathf.Max(flareWeldAtTime.x, Mathf.Max(flareWeldAtTime.y, flareWeldAtTime.z) * 0.25f) * 0.1f; + } + return num; + } + public override void UpdateParameters() + { + if (this.parentGroup == null || this.parentGroup.GetType() == typeof(TreeGroupRoot)) + { + this.weldSpreadTop = 0f; + this.weldSpreadBottom = 0f; + this.animationSecondary = 0f; + } + else + { + this.flareSize = 0f; + } + float num = (this.height.y - this.height.x) / this.height.y; + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + UnityEngine.Random.seed = treeNode.seed; + float num2 = 1f; + for (int j = 0; j < 5; j++) + { + num2 = 1f - UnityEngine.Random.value * num; + } + if (this.lockFlags == 0) + { + treeNode.scale *= num2; + } + float num3 = 0f; + for (int k = 0; k < 5; k++) + { + num3 = UnityEngine.Random.value; + } + for (int l = 0; l < 5; l++) + { + treeNode.breakOffset = 1f; + if (UnityEngine.Random.value <= this.breakingChance && this.breakingChance > 0f) + { + treeNode.breakOffset = this.breakingSpot.x + (this.breakingSpot.y - this.breakingSpot.x) * num3; + if (treeNode.breakOffset < 0.01f) + { + treeNode.breakOffset = 0.01f; + } + } + } + if (!(this.parentGroup is TreeGroupRoot)) + { + treeNode.size = this.radius; + if (this.radiusMode) + { + treeNode.size *= treeNode.scale; + } + if (treeNode.parent != null && treeNode.parent.spline != null) + { + treeNode.size = Mathf.Min(treeNode.parent.group.GetRadiusAtTime(treeNode.parent, treeNode.offset, false) * 0.75f, treeNode.size); + } + } + else + { + if (this.lockFlags == 0) + { + treeNode.size = this.radius; + if (this.radiusMode) + { + treeNode.size *= treeNode.scale; + } + } + } + } + this.UpdateMatrix(); + this.UpdateSplines(); + base.UpdateParameters(); + } + public void UpdateSplines() + { + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + this.UpdateSpline(treeNode); + if (this.capSmoothing < 0.01f) + { + treeNode.capRange = 0f; + } + else + { + float num = Mathf.Clamp(this.radiusCurve.Evaluate(1f), 0f, 1f) * treeNode.size; + float approximateLength = treeNode.spline.GetApproximateLength(); + treeNode.capRange = num / approximateLength * this.capSmoothing * 2f; + } + } + } + public override void UpdateMatrix() + { + if (this.parentGroup == null) + { + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + treeNode.matrix = Matrix4x4.identity; + } + } + else + { + if (this.parentGroup is TreeGroupRoot) + { + TreeGroupRoot treeGroupRoot = this.parentGroup as TreeGroupRoot; + for (int j = 0; j < this.nodes.Count; j++) + { + TreeNode treeNode2 = this.nodes[j]; + float num = treeNode2.offset * base.GetRootSpread(); + float f = treeNode2.angle * 0.0174532924f; + Vector3 pos = new Vector3(Mathf.Cos(f) * num, -treeGroupRoot.groundOffset, Mathf.Sin(f) * num); + Quaternion q = Quaternion.Euler(treeNode2.pitch * -Mathf.Sin(f), 0f, treeNode2.pitch * Mathf.Cos(f)) * Quaternion.Euler(0f, treeNode2.angle, 0f); + treeNode2.matrix = Matrix4x4.TRS(pos, q, Vector3.one); + } + } + else + { + for (int k = 0; k < this.nodes.Count; k++) + { + TreeNode treeNode3 = this.nodes[k]; + Vector3 pos2 = default(Vector3); + Quaternion q2 = default(Quaternion); + float y = 0f; + treeNode3.parent.GetPropertiesAtTime(treeNode3.offset, out pos2, out q2, out y); + Quaternion q3 = Quaternion.Euler(90f, treeNode3.angle, 0f); + Matrix4x4 rhs = Matrix4x4.TRS(Vector3.zero, q3, Vector3.one); + Matrix4x4 rhs2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(treeNode3.pitch, 0f, 0f), Vector3.one); + treeNode3.matrix = treeNode3.parent.matrix * Matrix4x4.TRS(pos2, q2, Vector3.one) * rhs * rhs2; + Vector3 vector = treeNode3.matrix.MultiplyPoint(new Vector3(0f, y, 0f)); + treeNode3.matrix.m03 = vector.x; + treeNode3.matrix.m13 = vector.y; + treeNode3.matrix.m23 = vector.z; + } + } + } + } + public override void BuildAOSpheres(List aoSpheres) + { + float num = 0.5f; + if (this.visible) + { + bool flag = this.geometryMode != TreeGroupBranch.GeometryMode.Branch; + bool flag2 = this.geometryMode != TreeGroupBranch.GeometryMode.Frond; + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + if (treeNode.visible) + { + float scale = treeNode.GetScale(); + float num2 = treeNode.spline.GetApproximateLength(); + if (num2 < num) + { + num2 = num; + } + float a = num / num2; + float num4; + for (float num3 = 0f; num3 < 1f; num3 += Mathf.Max(a, num4 / num2)) + { + Vector3 pos = treeNode.matrix.MultiplyPoint(treeNode.spline.GetPositionAtTime(num3)); + num4 = 0f; + if (flag2) + { + num4 = this.GetRadiusAtTime(treeNode, num3, false) * 0.95f; + } + if (flag) + { + num4 = Mathf.Max(num4, 0.95f * (Mathf.Clamp01(this.frondCurve.Evaluate(num3)) * this.frondWidth * scale)); + pos.y -= num4; + } + if (num4 > 0.01f) + { + aoSpheres.Add(new TreeAOSphere(pos, num4, 1f)); + } + } + } + } + } + base.BuildAOSpheres(aoSpheres); + } + public override void UpdateMesh(List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + if (this.geometryMode == TreeGroupBranch.GeometryMode.Branch || this.geometryMode == TreeGroupBranch.GeometryMode.BranchFrond) + { + TreeGroup.GetMaterialIndex(this.materialBranch, materials, true); + if (this.breakingChance > 0f) + { + TreeGroup.GetMaterialIndex(this.materialBreak, materials, false); + } + } + if (this.geometryMode == TreeGroupBranch.GeometryMode.Frond || this.geometryMode == TreeGroupBranch.GeometryMode.BranchFrond) + { + TreeGroup.GetMaterialIndex(this.materialFrond, materials, false); + } + for (int i = 0; i < this.nodes.Count; i++) + { + this.UpdateNodeMesh(this.nodes[i], materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); + } + base.UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); + } + private void UpdateNodeMesh(TreeNode node, List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + node.triStart = tris.Count; + node.triEnd = tris.Count; + node.vertStart = verts.Count; + node.vertEnd = verts.Count; + if (!node.visible || !this.visible) + { + return; + } + Profiler.BeginSample("TreeGroupBranch.UpdateNodeMesh"); + int count = verts.Count; + float approximateLength = node.spline.GetApproximateLength(); + List list = new List(); + float adaptiveQuality2 = Mathf.Clamp01(adaptiveQuality * this.lodQualityMultiplier); + List adaptiveSamples = TreeData.GetAdaptiveSamples(this, node, adaptiveQuality2); + int adaptiveRadialSegments = TreeData.GetAdaptiveRadialSegments(this.radius, adaptiveQuality2); + TreeGroupBranch treeGroupBranch = null; + if (this.parentGroup != null && this.parentGroup.GetType() == typeof(TreeGroupBranch)) + { + treeGroupBranch = (TreeGroupBranch)this.parentGroup; + } + if (this.geometryMode == TreeGroupBranch.GeometryMode.BranchFrond || this.geometryMode == TreeGroupBranch.GeometryMode.Branch) + { + int materialIndex = TreeGroup.GetMaterialIndex(this.materialBranch, materials, true); + float num = 0f; + float num2 = 0f; + float num3 = approximateLength / (this.GetRadiusAtTime(node, 0f, false) * 3.14159274f * 2f); + bool flag = true; + if (node.parent != null && treeGroupBranch != null) + { + num2 = node.offset * node.parent.spline.GetApproximateLength(); + } + float num4 = 1f - node.capRange; + for (int i = 0; i < adaptiveSamples.Count; i++) + { + float num5 = adaptiveSamples[i]; + Vector3 positionAtTime = node.spline.GetPositionAtTime(num5); + Quaternion rotationAtTime = node.spline.GetRotationAtTime(num5); + float radiusAtTime = this.GetRadiusAtTime(node, num5, false); + Matrix4x4 m = node.matrix * Matrix4x4.TRS(positionAtTime, rotationAtTime, new Vector3(1f, 1f, 1f)); + Vector3 flareWeldAtTime = this.GetFlareWeldAtTime(node, num5); + float num6 = Mathf.Max(flareWeldAtTime.x, Mathf.Max(flareWeldAtTime.y, flareWeldAtTime.z) * 0.25f); + if (num5 <= num4) + { + adaptiveRadialSegments = TreeData.GetAdaptiveRadialSegments(radiusAtTime + num6, adaptiveQuality2); + } + if (flag) + { + if (i > 0) + { + float num7 = adaptiveSamples[i - 1]; + float num8 = num5 - num7; + float num9 = (radiusAtTime + this.GetRadiusAtTime(node, num7, false)) * 0.5f; + num += num8 * approximateLength / (num9 * 3.14159274f * 2f); + } + } + else + { + num = num2 + num5 * num3; + } + Vector2 vector = base.ComputeWindFactor(node, num5); + RingLoop ringLoop = new RingLoop(); + ringLoop.Reset(radiusAtTime, m, num, adaptiveRadialSegments); + ringLoop.SetSurfaceAngle(node.GetSurfaceAngleAtTime(num5)); + ringLoop.SetAnimationProperties(vector.x, vector.y, 0f, node.animSeed); + ringLoop.SetSpread(flareWeldAtTime.y, flareWeldAtTime.z); + ringLoop.SetNoise(this.noise * Mathf.Clamp01(this.noiseCurve.Evaluate(num5)), this.noiseScaleU * 10f, this.noiseScaleV * 10f); + ringLoop.SetFlares(flareWeldAtTime.x, this.flareNoise * 10f); + int count2 = verts.Count; + ringLoop.BuildVertices(verts); + int count3 = verts.Count; + if ((buildFlags & 2) != 0) + { + float num10 = this.weldHeight; + float num11 = Mathf.Pow(Mathf.Clamp01((1f - num5 - (1f - this.weldHeight)) / this.weldHeight), 1.5f); + float d = 1f - num11; + if (num5 < num10 && node.parent != null && node.parent.spline != null) + { + Ray ray = default(Ray); + for (int j = count2; j < count3; j++) + { + ray.origin = verts[j].pos; + ray.direction = m.MultiplyVector(-Vector3.up); + Vector3 pos = verts[j].pos; + Vector3 nor = verts[j].nor; + float num12 = -10000f; + float num13 = 100000f; + for (int k = node.parent.triStart; k < node.parent.triEnd; k++) + { + object obj = MathUtils.IntersectRayTriangle(ray, verts[tris[k].v[0]].pos, verts[tris[k].v[1]].pos, verts[tris[k].v[2]].pos, true); + if (obj != null) + { + RaycastHit raycastHit = (RaycastHit)obj; + if (Mathf.Abs(raycastHit.distance) < num13 && raycastHit.distance > num12) + { + num13 = Mathf.Abs(raycastHit.distance); + verts[j].nor = verts[tris[k].v[0]].nor * raycastHit.barycentricCoordinate.x + verts[tris[k].v[1]].nor * raycastHit.barycentricCoordinate.y + verts[tris[k].v[2]].nor * raycastHit.barycentricCoordinate.z; + verts[j].nor = verts[j].nor * num11 + nor * d; + verts[j].pos = raycastHit.point * num11 + pos * d; + } + } + } + } + } + } + list.Add(ringLoop); + if (num5 == 1f && ringLoop.radius > 0.005f) + { + RingLoop ringLoop2 = ringLoop.Clone(); + ringLoop2.radius = 0f; + ringLoop2.baseOffset += radiusAtTime / 6.28318548f; + ringLoop2.BuildVertices(verts); + list.Add(ringLoop2); + } + } + if (list.Count > 0 && list[list.Count - 1].radius > 0.025f && node.breakOffset < 1f) + { + float mappingScale = 1f / (this.radius * 3.14159274f * 2f); + float sphereFactor = 0f; + float num14 = 1f; + int mappingMode = 0; + Material m2 = this.materialBranch; + if (this.materialBreak != null) + { + m2 = this.materialBreak; + } + int materialIndex2 = TreeGroup.GetMaterialIndex(m2, materials, false); + list[list.Count - 1].Cap(sphereFactor, num14, mappingMode, mappingScale, verts, tris, materialIndex2); + } + node.triStart = tris.Count; + for (int l = 0; l < list.Count - 1; l++) + { + list[l].Connect(list[l + 1], tris, materialIndex, false, false); + } + node.triEnd = tris.Count; + list.Clear(); + } + float num15 = Mathf.Min(this.frondRange.x, this.frondRange.y); + float num16 = Mathf.Max(this.frondRange.x, this.frondRange.y); + float num17 = num15; + float num18 = num16; + num15 = Mathf.Clamp(num15, 0f, node.breakOffset); + num16 = Mathf.Clamp(num16, 0f, node.breakOffset); + if ((this.geometryMode == TreeGroupBranch.GeometryMode.BranchFrond || this.geometryMode == TreeGroupBranch.GeometryMode.Frond) && this.frondCount > 0 && num15 != num16) + { + bool flag2 = true; + bool flag3 = true; + for (int n = 0; n < adaptiveSamples.Count; n++) + { + float num19 = adaptiveSamples[n]; + if (num19 < num15) + { + adaptiveSamples.RemoveAt(n); + n--; + } + else + { + if (num19 == num15) + { + flag2 = false; + } + else + { + if (num19 == num16) + { + flag3 = false; + } + else + { + if (num19 > num16) + { + adaptiveSamples.RemoveAt(n); + n--; + } + } + } + } + } + if (flag2) + { + adaptiveSamples.Insert(0, num15); + } + if (flag3) + { + adaptiveSamples.Add(num16); + } + int materialIndex3 = TreeGroup.GetMaterialIndex(this.materialFrond, materials, false); + float num20 = 1f - node.capRange; + for (int num21 = 0; num21 < this.frondCount; num21++) + { + float num22 = this.frondCrease * 90f * 0.0174532924f; + float num23 = (this.frondRotation * 360f + (float)num21 * 180f / (float)this.frondCount - 90f) * 0.0174532924f; + float f = -num23 - num22; + float f2 = num23 - num22; + Vector3 a = new Vector3(Mathf.Sin(f), 0f, Mathf.Cos(f)); + Vector3 vector2 = new Vector3(a.z, 0f, -a.x); + Vector3 a2 = new Vector3(Mathf.Sin(f2), 0f, -Mathf.Cos(f2)); + Vector3 vector3 = new Vector3(-a2.z, 0f, a2.x); + for (int num24 = 0; num24 < adaptiveSamples.Count; num24++) + { + float num25 = adaptiveSamples[num24]; + float y = (num25 - num17) / (num18 - num17); + float timeParam = num25; + if (num25 > num20) + { + timeParam = num20; + float f3 = Mathf.Acos(Mathf.Clamp01((num25 - num20) / node.capRange)); + float num26 = Mathf.Sin(f3); + float y2 = Mathf.Cos(f3) * this.capSmoothing; + a = new Vector3(Mathf.Sin(f) * num26, y2, Mathf.Cos(f) * num26); + vector2 = new Vector3(a.z, a.y, -a.x); + a2 = new Vector3(Mathf.Sin(f2) * num26, y2, -Mathf.Cos(f2) * num26); + vector3 = new Vector3(-a2.z, a2.y, a2.x); + } + Vector3 a3 = new Vector3(0f, 0f, -1f); + Vector3 positionAtTime2 = node.spline.GetPositionAtTime(timeParam); + Quaternion rotationAtTime2 = node.spline.GetRotationAtTime(num25); + float d2 = Mathf.Clamp01(this.frondCurve.Evaluate(num25)) * this.frondWidth * node.GetScale(); + Matrix4x4 matrix4x = node.matrix * Matrix4x4.TRS(positionAtTime2, rotationAtTime2, new Vector3(1f, 1f, 1f)); + if (TreeGroup.GenerateDoubleSidedGeometry) + { + for (float num27 = -1f; num27 < 2f; num27 += 2f) + { + TreeVertex treeVertex = new TreeVertex(); + treeVertex.pos = matrix4x.MultiplyPoint(a * d2); + treeVertex.nor = matrix4x.MultiplyVector(vector2 * num27).normalized; + treeVertex.tangent = TreeGroup.CreateTangent(node, rotationAtTime2, treeVertex.nor); + treeVertex.tangent.w = -num27; + treeVertex.uv0 = new Vector2(1f, y); + TreeVertex treeVertex2 = new TreeVertex(); + treeVertex2.pos = matrix4x.MultiplyPoint(Vector3.zero); + treeVertex2.nor = matrix4x.MultiplyVector(a3 * num27).normalized; + treeVertex2.tangent = TreeGroup.CreateTangent(node, rotationAtTime2, treeVertex2.nor); + treeVertex2.tangent.w = -num27; + treeVertex2.uv0 = new Vector2(0.5f, y); + TreeVertex treeVertex3 = new TreeVertex(); + treeVertex3.pos = matrix4x.MultiplyPoint(Vector3.zero); + treeVertex3.nor = matrix4x.MultiplyVector(a3 * num27).normalized; + treeVertex3.tangent = TreeGroup.CreateTangent(node, rotationAtTime2, treeVertex3.nor); + treeVertex3.tangent.w = -num27; + treeVertex3.uv0 = new Vector2(0.5f, y); + TreeVertex treeVertex4 = new TreeVertex(); + treeVertex4.pos = matrix4x.MultiplyPoint(a2 * d2); + treeVertex4.nor = matrix4x.MultiplyVector(vector3 * num27).normalized; + treeVertex4.tangent = TreeGroup.CreateTangent(node, rotationAtTime2, treeVertex4.nor); + treeVertex4.tangent.w = -num27; + treeVertex4.uv0 = new Vector2(0f, y); + Vector2 vector4 = base.ComputeWindFactor(node, num25); + treeVertex.SetAnimationProperties(vector4.x, vector4.y, this.animationEdge, node.animSeed); + treeVertex2.SetAnimationProperties(vector4.x, vector4.y, 0f, node.animSeed); + treeVertex3.SetAnimationProperties(vector4.x, vector4.y, 0f, node.animSeed); + treeVertex4.SetAnimationProperties(vector4.x, vector4.y, this.animationEdge, node.animSeed); + verts.Add(treeVertex); + verts.Add(treeVertex2); + verts.Add(treeVertex3); + verts.Add(treeVertex4); + } + if (num24 > 0) + { + int count4 = verts.Count; + TreeTriangle treeTriangle = new TreeTriangle(materialIndex3, count4 - 4, count4 - 3, count4 - 11); + TreeTriangle treeTriangle2 = new TreeTriangle(materialIndex3, count4 - 4, count4 - 11, count4 - 12); + treeTriangle.flip(); + treeTriangle2.flip(); + TreeTriangle item = new TreeTriangle(materialIndex3, count4 - 8, count4 - 7, count4 - 15); + TreeTriangle item2 = new TreeTriangle(materialIndex3, count4 - 8, count4 - 15, count4 - 16); + tris.Add(treeTriangle); + tris.Add(treeTriangle2); + tris.Add(item); + tris.Add(item2); + TreeTriangle item3 = new TreeTriangle(materialIndex3, count4 - 2, count4 - 9, count4 - 1); + TreeTriangle item4 = new TreeTriangle(materialIndex3, count4 - 2, count4 - 10, count4 - 9); + TreeTriangle treeTriangle3 = new TreeTriangle(materialIndex3, count4 - 6, count4 - 13, count4 - 5); + TreeTriangle treeTriangle4 = new TreeTriangle(materialIndex3, count4 - 6, count4 - 14, count4 - 13); + treeTriangle3.flip(); + treeTriangle4.flip(); + tris.Add(item3); + tris.Add(item4); + tris.Add(treeTriangle3); + tris.Add(treeTriangle4); + } + } + else + { + TreeVertex treeVertex5 = new TreeVertex(); + treeVertex5.pos = matrix4x.MultiplyPoint(a * d2); + treeVertex5.nor = matrix4x.MultiplyVector(vector2).normalized; + treeVertex5.uv0 = new Vector2(0f, y); + TreeVertex treeVertex6 = new TreeVertex(); + treeVertex6.pos = matrix4x.MultiplyPoint(Vector3.zero); + treeVertex6.nor = matrix4x.MultiplyVector(Vector3.back).normalized; + treeVertex6.uv0 = new Vector2(0.5f, y); + TreeVertex treeVertex7 = new TreeVertex(); + treeVertex7.pos = matrix4x.MultiplyPoint(a2 * d2); + treeVertex7.nor = matrix4x.MultiplyVector(vector3).normalized; + treeVertex7.uv0 = new Vector2(1f, y); + Vector2 vector5 = base.ComputeWindFactor(node, num25); + treeVertex5.SetAnimationProperties(vector5.x, vector5.y, this.animationEdge, node.animSeed); + treeVertex6.SetAnimationProperties(vector5.x, vector5.y, 0f, node.animSeed); + treeVertex7.SetAnimationProperties(vector5.x, vector5.y, this.animationEdge, node.animSeed); + verts.Add(treeVertex5); + verts.Add(treeVertex6); + verts.Add(treeVertex7); + if (num24 > 0) + { + int count5 = verts.Count; + TreeTriangle item5 = new TreeTriangle(materialIndex3, count5 - 2, count5 - 3, count5 - 6); + TreeTriangle item6 = new TreeTriangle(materialIndex3, count5 - 2, count5 - 6, count5 - 5); + tris.Add(item5); + tris.Add(item6); + TreeTriangle item7 = new TreeTriangle(materialIndex3, count5 - 2, count5 - 4, count5 - 1); + TreeTriangle item8 = new TreeTriangle(materialIndex3, count5 - 2, count5 - 5, count5 - 4); + tris.Add(item7); + tris.Add(item8); + } + } + } + } + } + if ((buildFlags & 1) != 0) + { + for (int num28 = count; num28 < verts.Count; num28++) + { + verts[num28].SetAmbientOcclusion(TreeGroup.ComputeAmbientOcclusion(verts[num28].pos, verts[num28].nor, aoSpheres, aoDensity)); + } + } + node.vertEnd = verts.Count; + Profiler.EndSample(); + } + public void UpdateSpline(TreeNode node) + { + if (this.lockFlags != 0) + { + return; + } + UnityEngine.Random.seed = node.seed; + if (node.spline == null) + { + TreeSpline spline = new TreeSpline(); + node.spline = spline; + } + float num = this.height.y * node.GetScale(); + float num2 = 1f; + int num3 = (int)Mathf.Round(num / num2); + float num4 = 0f; + Quaternion quaternion = Quaternion.identity; + Vector3 vector = new Vector3(0f, 0f, 0f); + Matrix4x4 inverse = (node.matrix * base.GetRootMatrix()).inverse; + Quaternion to = MathUtils.QuaternionFromMatrix(inverse) * Quaternion.Euler(0f, node.angle, 0f); + Quaternion to2 = MathUtils.QuaternionFromMatrix(inverse) * Quaternion.Euler(-180f, node.angle, 0f); + node.spline.Reset(); + node.spline.AddPoint(vector, 0f); + for (int i = 0; i < num3; i++) + { + float num5 = num2; + if (i == num3 - 1) + { + num5 = num - num4; + } + num4 += num5; + float num6 = num4 / num; + float num7 = Mathf.Clamp(this.seekCurve.Evaluate(num6), -1f, 1f); + float t = Mathf.Clamp01(num7) * this.seekBlend; + float t2 = Mathf.Clamp01(-num7) * this.seekBlend; + quaternion = Quaternion.Slerp(quaternion, to, t); + quaternion = Quaternion.Slerp(quaternion, to2, t2); + float t3 = this.crinklyness * Mathf.Clamp01(this.crinkCurve.Evaluate(num6)); + Quaternion to3 = Quaternion.Euler(new Vector3(180f * (UnityEngine.Random.value - 0.5f), node.angle, 180f * (UnityEngine.Random.value - 0.5f))); + quaternion = Quaternion.Slerp(quaternion, to3, t3); + vector += quaternion * new Vector3(0f, num5, 0f); + node.spline.AddPoint(vector, num6); + } + node.spline.UpdateTime(); + node.spline.UpdateRotations(); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeGroupLeaf.cs b/UnityEditor/TreeEditor/TreeGroupLeaf.cs new file mode 100644 index 00000000..a40db7b3 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeGroupLeaf.cs @@ -0,0 +1,537 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditorInternal; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeGroupLeaf : TreeGroup + { + public enum GeometryMode + { + PLANE, + CROSS, + TRI_CROSS, + BILLBOARD, + MESH + } + internal static Dictionary s_TextureHulls; + internal static bool s_TextureHullsDirty; + public int geometryMode; + public Material materialLeaf; + public GameObject instanceMesh; + public Vector2 size = Vector2.one; + public float perpendicularAlign; + public float horizontalAlign; + private static Mesh cloneMesh; + private static MeshFilter cloneMeshFilter; + private static Renderer cloneRenderer; + private static Vector3[] cloneVerts; + private static Vector3[] cloneNormals; + private static Vector2[] cloneUVs; + private static Vector4[] cloneTangents; + public override bool CanHaveSubGroups() + { + return false; + } + internal override bool HasExternalChanges() + { + string text; + if (this.geometryMode == 4) + { + text = InternalEditorUtility.CalculateHashForObjectsAndDependencies(new UnityEngine.Object[] + { + this.instanceMesh + }); + } + else + { + text = InternalEditorUtility.CalculateHashForObjectsAndDependencies(new UnityEngine.Object[] + { + this.materialLeaf + }); + } + if (text != this.m_Hash) + { + this.m_Hash = text; + return true; + } + return false; + } + public override void UpdateParameters() + { + if (this.lockFlags == 0) + { + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + UnityEngine.Random.seed = treeNode.seed; + for (int j = 0; j < 5; j++) + { + treeNode.scale *= this.size.x + (this.size.y - this.size.x) * UnityEngine.Random.value; + } + for (int k = 0; k < 5; k++) + { + float x = (UnityEngine.Random.value - 0.5f) * 180f * (1f - this.perpendicularAlign); + float y = (UnityEngine.Random.value - 0.5f) * 180f * (1f - this.perpendicularAlign); + float z = 0f; + treeNode.rotation = Quaternion.Euler(x, y, z); + } + } + } + this.UpdateMatrix(); + base.UpdateParameters(); + } + public override void UpdateMatrix() + { + if (this.parentGroup == null) + { + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + treeNode.matrix = Matrix4x4.identity; + } + } + else + { + TreeGroupRoot treeGroupRoot = this.parentGroup as TreeGroupRoot; + for (int j = 0; j < this.nodes.Count; j++) + { + TreeNode treeNode2 = this.nodes[j]; + Vector3 pos = default(Vector3); + Quaternion q = default(Quaternion); + float num = 0f; + float num2 = 0f; + if (treeGroupRoot != null) + { + float num3 = treeNode2.offset * base.GetRootSpread(); + float f = treeNode2.angle * 0.0174532924f; + pos = new Vector3(Mathf.Cos(f) * num3, -treeGroupRoot.groundOffset, Mathf.Sin(f) * num3); + q = Quaternion.Euler(treeNode2.pitch * -Mathf.Sin(f), 0f, treeNode2.pitch * Mathf.Cos(f)) * Quaternion.Euler(0f, treeNode2.angle, 0f); + } + else + { + treeNode2.parent.GetPropertiesAtTime(treeNode2.offset, out pos, out q, out num); + num2 = treeNode2.parent.GetSurfaceAngleAtTime(treeNode2.offset); + } + Quaternion q2 = Quaternion.Euler(90f, treeNode2.angle, 0f); + Matrix4x4 rhs = Matrix4x4.TRS(Vector3.zero, q2, Vector3.one); + Matrix4x4 rhs2 = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(treeNode2.pitch + num2, 0f, 0f), Vector3.one); + treeNode2.matrix = treeNode2.parent.matrix * Matrix4x4.TRS(pos, q, Vector3.one) * rhs * rhs2; + treeNode2.matrix *= Matrix4x4.TRS(new Vector3(0f, 0f, 0f), treeNode2.rotation, new Vector3(1f, 1f, 1f)); + if (this.horizontalAlign > 0f) + { + Vector4 column = treeNode2.matrix.GetColumn(3); + Quaternion to = Quaternion.Euler(90f, treeNode2.angle, 0f); + Quaternion q3 = Quaternion.Slerp(MathUtils.QuaternionFromMatrix(treeNode2.matrix), to, this.horizontalAlign); + treeNode2.matrix = Matrix4x4.TRS(Vector3.zero, q3, Vector3.one); + treeNode2.matrix.SetColumn(3, column); + } + Vector3 vector; + if (this.geometryMode == 4) + { + vector = treeNode2.matrix.MultiplyPoint(new Vector3(0f, num, 0f)); + treeNode2.matrix *= Matrix4x4.Scale(new Vector3(treeNode2.scale, treeNode2.scale, treeNode2.scale)); + } + else + { + vector = treeNode2.matrix.MultiplyPoint(new Vector3(0f, num + treeNode2.scale, 0f)); + } + treeNode2.matrix.m03 = vector.x; + treeNode2.matrix.m13 = vector.y; + treeNode2.matrix.m23 = vector.z; + } + } + base.UpdateMatrix(); + } + public override void BuildAOSpheres(List aoSpheres) + { + if (this.visible) + { + float num = 0.75f; + for (int i = 0; i < this.nodes.Count; i++) + { + TreeNode treeNode = this.nodes[i]; + if (treeNode.visible) + { + Vector3 pos = treeNode.matrix.MultiplyPoint(new Vector3(0f, 0f, 0f)); + float radius = treeNode.scale * num; + aoSpheres.Add(new TreeAOSphere(pos, radius, 0.5f)); + } + } + } + base.BuildAOSpheres(aoSpheres); + } + public override void UpdateMesh(List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + if (this.geometryMode == 4) + { + if (this.instanceMesh != null) + { + TreeGroupLeaf.cloneMeshFilter = this.instanceMesh.GetComponent(); + if (TreeGroupLeaf.cloneMeshFilter != null) + { + TreeGroupLeaf.cloneMesh = TreeGroupLeaf.cloneMeshFilter.sharedMesh; + if (TreeGroupLeaf.cloneMesh != null) + { + Vector3 extents = TreeGroupLeaf.cloneMesh.bounds.extents; + float num = Mathf.Max(extents.x, extents.z) * 0.5f; + TreeGroupLeaf.cloneVerts = TreeGroupLeaf.cloneMesh.vertices; + TreeGroupLeaf.cloneNormals = TreeGroupLeaf.cloneMesh.normals; + TreeGroupLeaf.cloneUVs = TreeGroupLeaf.cloneMesh.uv; + TreeGroupLeaf.cloneTangents = TreeGroupLeaf.cloneMesh.tangents; + for (int i = 0; i < TreeGroupLeaf.cloneVerts.Length; i++) + { + Vector3[] expr_D8_cp_0 = TreeGroupLeaf.cloneVerts; + int expr_D8_cp_1 = i; + expr_D8_cp_0[expr_D8_cp_1].x = expr_D8_cp_0[expr_D8_cp_1].x / num; + Vector3[] expr_F0_cp_0 = TreeGroupLeaf.cloneVerts; + int expr_F0_cp_1 = i; + expr_F0_cp_0[expr_F0_cp_1].y = expr_F0_cp_0[expr_F0_cp_1].y / num; + Vector3[] expr_108_cp_0 = TreeGroupLeaf.cloneVerts; + int expr_108_cp_1 = i; + expr_108_cp_0[expr_108_cp_1].z = expr_108_cp_0[expr_108_cp_1].z / num; + } + } + } + if (this.instanceMesh.renderer != null) + { + Material[] sharedMaterials = this.instanceMesh.renderer.sharedMaterials; + for (int j = 0; j < sharedMaterials.Length; j++) + { + TreeGroup.GetMaterialIndex(sharedMaterials[j], materials, false); + } + } + } + } + else + { + TreeGroup.GetMaterialIndex(this.materialLeaf, materials, false); + } + for (int k = 0; k < this.nodes.Count; k++) + { + this.UpdateNodeMesh(this.nodes[k], materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); + } + TreeGroupLeaf.cloneMesh = null; + TreeGroupLeaf.cloneMeshFilter = null; + TreeGroupLeaf.cloneVerts = null; + TreeGroupLeaf.cloneNormals = null; + TreeGroupLeaf.cloneUVs = null; + TreeGroupLeaf.cloneTangents = null; + base.UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); + } + private static TreeVertex CreateBillboardVertex(TreeNode node, Quaternion billboardRotation, Vector3 normalBase, float normalFix, Vector3 tangentBase, Vector2 uv) + { + TreeVertex treeVertex = new TreeVertex(); + treeVertex.pos = node.matrix.MultiplyPoint(Vector3.zero); + treeVertex.uv0 = uv; + uv = 2f * uv - Vector2.one; + treeVertex.nor = billboardRotation * new Vector3(uv.x * node.scale, uv.y * node.scale, 0f); + treeVertex.nor.z = normalFix; + Vector3 normalized = (billboardRotation * new Vector3(uv.x * normalBase.x, uv.y * normalBase.y, normalBase.z)).normalized; + treeVertex.tangent = (tangentBase - normalized * Vector3.Dot(tangentBase, normalized)).normalized; + treeVertex.tangent.w = 0f; + return treeVertex; + } + private Vector2[] GetPlaneHullVertices(Material mat) + { + if (mat == null) + { + return null; + } + if (!mat.HasProperty("_MainTex")) + { + return null; + } + Texture mainTexture = mat.mainTexture; + if (!mainTexture) + { + return null; + } + if (TreeGroupLeaf.s_TextureHulls == null || TreeGroupLeaf.s_TextureHullsDirty) + { + TreeGroupLeaf.s_TextureHulls = new Dictionary(); + TreeGroupLeaf.s_TextureHullsDirty = false; + } + if (TreeGroupLeaf.s_TextureHulls.ContainsKey(mainTexture)) + { + return TreeGroupLeaf.s_TextureHulls[mainTexture]; + } + Vector2[] array = MeshUtility.ComputeTextureBoundingHull(mainTexture, 4); + Vector2 vector = array[1]; + array[1] = array[3]; + array[3] = vector; + TreeGroupLeaf.s_TextureHulls.Add(mainTexture, array); + return array; + } + private void UpdateNodeMesh(TreeNode node, List materials, List verts, List tris, List aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) + { + node.triStart = tris.Count; + node.triEnd = tris.Count; + node.vertStart = verts.Count; + node.vertEnd = verts.Count; + if (!node.visible || !this.visible) + { + return; + } + Profiler.BeginSample("TreeGroupLeaf.UpdateNodeMesh"); + Vector2 vector = base.ComputeWindFactor(node, node.offset); + if (this.geometryMode == 4) + { + if (TreeGroupLeaf.cloneMesh == null) + { + return; + } + if (TreeGroupLeaf.cloneVerts == null) + { + return; + } + if (TreeGroupLeaf.cloneNormals == null) + { + return; + } + if (TreeGroupLeaf.cloneTangents == null) + { + return; + } + if (TreeGroupLeaf.cloneUVs == null) + { + return; + } + Matrix4x4 localToWorldMatrix = this.instanceMesh.transform.localToWorldMatrix; + Matrix4x4 matrix4x = node.matrix * localToWorldMatrix; + int count = verts.Count; + float num = 5f; + for (int i = 0; i < TreeGroupLeaf.cloneVerts.Length; i++) + { + TreeVertex treeVertex = new TreeVertex(); + treeVertex.pos = matrix4x.MultiplyPoint(TreeGroupLeaf.cloneVerts[i]); + treeVertex.nor = matrix4x.MultiplyVector(TreeGroupLeaf.cloneNormals[i]).normalized; + treeVertex.uv0 = new Vector2(TreeGroupLeaf.cloneUVs[i].x, TreeGroupLeaf.cloneUVs[i].y); + Vector3 normalized = matrix4x.MultiplyVector(new Vector3(TreeGroupLeaf.cloneTangents[i].x, TreeGroupLeaf.cloneTangents[i].y, TreeGroupLeaf.cloneTangents[i].z)).normalized; + treeVertex.tangent = new Vector4(normalized.x, normalized.y, normalized.z, TreeGroupLeaf.cloneTangents[i].w); + float edgeFactor = TreeGroupLeaf.cloneVerts[i].magnitude / num * this.animationEdge; + treeVertex.SetAnimationProperties(vector.x, vector.y, edgeFactor, node.animSeed); + if ((buildFlags & 1) != 0) + { + treeVertex.SetAmbientOcclusion(TreeGroup.ComputeAmbientOcclusion(treeVertex.pos, treeVertex.nor, aoSpheres, aoDensity)); + } + verts.Add(treeVertex); + } + for (int j = 0; j < TreeGroupLeaf.cloneMesh.subMeshCount; j++) + { + int[] triangles = TreeGroupLeaf.cloneMesh.GetTriangles(j); + int materialIndex; + if (this.instanceMesh.renderer != null && j < this.instanceMesh.renderer.sharedMaterials.Length) + { + materialIndex = TreeGroup.GetMaterialIndex(this.instanceMesh.renderer.sharedMaterials[j], materials, false); + } + else + { + materialIndex = TreeGroup.GetMaterialIndex(null, materials, false); + } + for (int k = 0; k < triangles.Length; k += 3) + { + TreeTriangle item = new TreeTriangle(materialIndex, triangles[k] + count, triangles[k + 1] + count, triangles[k + 2] + count); + tris.Add(item); + } + } + } + else + { + if (this.geometryMode == 3) + { + Vector3 eulerAngles = node.rotation.eulerAngles; + eulerAngles.z = eulerAngles.x * 2f; + eulerAngles.x = 0f; + eulerAngles.y = 0f; + Quaternion quaternion = Quaternion.Euler(eulerAngles); + Vector3 normalBase = new Vector3(TreeGroup.GenerateBendBillboardNormalFactor, TreeGroup.GenerateBendBillboardNormalFactor, 1f); + Vector3 tangentBase = quaternion * new Vector3(1f, 0f, 0f); + float normalFix = node.scale / (TreeGroup.GenerateBendBillboardNormalFactor * TreeGroup.GenerateBendBillboardNormalFactor); + TreeVertex treeVertex2 = TreeGroupLeaf.CreateBillboardVertex(node, quaternion, normalBase, normalFix, tangentBase, new Vector2(0f, 1f)); + TreeVertex treeVertex3 = TreeGroupLeaf.CreateBillboardVertex(node, quaternion, normalBase, normalFix, tangentBase, new Vector2(0f, 0f)); + TreeVertex treeVertex4 = TreeGroupLeaf.CreateBillboardVertex(node, quaternion, normalBase, normalFix, tangentBase, new Vector2(1f, 0f)); + TreeVertex treeVertex5 = TreeGroupLeaf.CreateBillboardVertex(node, quaternion, normalBase, normalFix, tangentBase, new Vector2(1f, 1f)); + treeVertex2.SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + treeVertex3.SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + treeVertex4.SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + treeVertex5.SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + if ((buildFlags & 1) != 0) + { + Vector3 b = Vector3.right * node.scale; + Vector3 b2 = Vector3.forward * node.scale; + float num2 = TreeGroup.ComputeAmbientOcclusion(treeVertex2.pos + b, Vector3.right, aoSpheres, aoDensity); + num2 += TreeGroup.ComputeAmbientOcclusion(treeVertex2.pos - b, -Vector3.right, aoSpheres, aoDensity); + num2 += TreeGroup.ComputeAmbientOcclusion(treeVertex2.pos + b2, Vector3.forward, aoSpheres, aoDensity); + num2 += TreeGroup.ComputeAmbientOcclusion(treeVertex2.pos - b2, -Vector3.forward, aoSpheres, aoDensity); + num2 /= 4f; + treeVertex2.SetAmbientOcclusion(num2); + treeVertex3.SetAmbientOcclusion(num2); + treeVertex4.SetAmbientOcclusion(num2); + treeVertex5.SetAmbientOcclusion(num2); + } + int count2 = verts.Count; + verts.Add(treeVertex2); + verts.Add(treeVertex3); + verts.Add(treeVertex4); + verts.Add(treeVertex5); + int materialIndex2 = TreeGroup.GetMaterialIndex(this.materialLeaf, materials, false); + tris.Add(new TreeTriangle(materialIndex2, count2, count2 + 2, count2 + 1, true)); + tris.Add(new TreeTriangle(materialIndex2, count2, count2 + 3, count2 + 2, true)); + } + else + { + int num3 = 0; + switch (this.geometryMode) + { + case 0: + num3 = 1; + break; + case 1: + num3 = 2; + break; + case 2: + num3 = 3; + break; + } + int materialIndex3 = TreeGroup.GetMaterialIndex(this.materialLeaf, materials, false); + Vector2[] array = new Vector2[] + { + new Vector2(0f, 1f), + new Vector2(0f, 0f), + new Vector2(1f, 0f), + new Vector2(1f, 1f) + }; + Vector2[] array2 = this.GetPlaneHullVertices(this.materialLeaf); + if (array2 == null) + { + array2 = array; + } + float scale = node.scale; + Vector3[] array3 = new Vector3[] + { + new Vector3(-scale, 0f, -scale), + new Vector3(-scale, 0f, scale), + new Vector3(scale, 0f, scale), + new Vector3(scale, 0f, -scale) + }; + Vector3 vector2 = new Vector3(TreeGroup.GenerateBendNormalFactor, 1f - TreeGroup.GenerateBendNormalFactor, TreeGroup.GenerateBendNormalFactor); + Vector3[] expr_788 = new Vector3[4]; + int arg_7B4_0_cp_1 = 0; + Vector3 vector3 = new Vector3(-vector2.x, vector2.y, -vector2.z); + expr_788[arg_7B4_0_cp_1] = vector3.normalized; + int arg_7E2_0_cp_1 = 1; + Vector3 vector4 = new Vector3(-vector2.x, vector2.y, 0f); + expr_788[arg_7E2_0_cp_1] = vector4.normalized; + int arg_80F_0_cp_1 = 2; + Vector3 vector5 = new Vector3(vector2.x, vector2.y, 0f); + expr_788[arg_80F_0_cp_1] = vector5.normalized; + int arg_83F_0_cp_1 = 3; + Vector3 vector6 = new Vector3(vector2.x, vector2.y, -vector2.z); + expr_788[arg_83F_0_cp_1] = vector6.normalized; + Vector3[] array4 = expr_788; + for (int l = 0; l < num3; l++) + { + Quaternion quaternion2 = Quaternion.Euler(new Vector3(90f, 0f, 0f)); + int num4 = l; + if (num4 != 1) + { + if (num4 == 2) + { + quaternion2 = Quaternion.Euler(new Vector3(0f, 90f, 0f)); + } + } + else + { + quaternion2 = Quaternion.Euler(new Vector3(90f, 90f, 0f)); + } + TreeVertex[] array5 = new TreeVertex[] + { + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex() + }; + for (int m = 0; m < 4; m++) + { + array5[m].pos = node.matrix.MultiplyPoint(quaternion2 * array3[m]); + array5[m].nor = node.matrix.MultiplyVector(quaternion2 * array4[m]); + array5[m].tangent = TreeGroup.CreateTangent(node, quaternion2, array5[m].nor); + array5[m].uv0 = array2[m]; + array5[m].SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + if ((buildFlags & 1) != 0) + { + array5[m].SetAmbientOcclusion(TreeGroup.ComputeAmbientOcclusion(array5[m].pos, array5[m].nor, aoSpheres, aoDensity)); + } + } + for (int n = 0; n < 4; n++) + { + array5[n + 4].Lerp4(array5, array2[n]); + array5[n + 4].uv0 = array5[n].uv0; + array5[n + 4].uv1 = array5[n].uv1; + array5[n + 4].flag = array5[n].flag; + } + int count3 = verts.Count; + for (int num5 = 0; num5 < 4; num5++) + { + verts.Add(array5[num5 + 4]); + } + tris.Add(new TreeTriangle(materialIndex3, count3, count3 + 1, count3 + 2)); + tris.Add(new TreeTriangle(materialIndex3, count3, count3 + 2, count3 + 3)); + Vector3 inNormal = node.matrix.MultiplyVector(quaternion2 * new Vector3(0f, 1f, 0f)); + if (TreeGroup.GenerateDoubleSidedGeometry) + { + TreeVertex[] array6 = new TreeVertex[] + { + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex(), + new TreeVertex() + }; + for (int num6 = 0; num6 < 4; num6++) + { + array6[num6].pos = array5[num6].pos; + array6[num6].nor = Vector3.Reflect(array5[num6].nor, inNormal); + array6[num6].tangent = Vector3.Reflect(array5[num6].tangent, inNormal); + array6[num6].tangent.w = -1f; + array6[num6].uv0 = array5[num6].uv0; + array6[num6].SetAnimationProperties(vector.x, vector.y, this.animationEdge, node.animSeed); + if ((buildFlags & 1) != 0) + { + array6[num6].SetAmbientOcclusion(TreeGroup.ComputeAmbientOcclusion(array6[num6].pos, array6[num6].nor, aoSpheres, aoDensity)); + } + } + for (int num7 = 0; num7 < 4; num7++) + { + array6[num7 + 4].Lerp4(array6, array2[num7]); + array6[num7 + 4].uv0 = array6[num7].uv0; + array6[num7 + 4].uv1 = array6[num7].uv1; + array6[num7 + 4].flag = array6[num7].flag; + } + int count4 = verts.Count; + for (int num8 = 0; num8 < 4; num8++) + { + verts.Add(array6[num8 + 4]); + } + tris.Add(new TreeTriangle(materialIndex3, count4, count4 + 2, count4 + 1)); + tris.Add(new TreeTriangle(materialIndex3, count4, count4 + 3, count4 + 2)); + } + } + } + } + node.triEnd = tris.Count; + node.vertEnd = verts.Count; + Profiler.EndSample(); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeGroupRoot.cs b/UnityEditor/TreeEditor/TreeGroupRoot.cs new file mode 100644 index 00000000..fa20c94f --- /dev/null +++ b/UnityEditor/TreeEditor/TreeGroupRoot.cs @@ -0,0 +1,40 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeGroupRoot : TreeGroup + { + public float adaptiveLODQuality = 0.8f; + public int shadowTextureQuality = 3; + public bool enableWelding = true; + public bool enableAmbientOcclusion = true; + public bool enableMaterialOptimize = true; + public float aoDensity = 1f; + public float rootSpread = 5f; + public float groundOffset; + public Matrix4x4 rootMatrix = Matrix4x4.identity; + public void SetRootMatrix(Matrix4x4 m) + { + this.rootMatrix = m; + this.rootMatrix.m03 = 0f; + this.rootMatrix.m13 = 0f; + this.rootMatrix.m23 = 0f; + this.rootMatrix = MathUtils.OrthogonalizeMatrix(this.rootMatrix); + this.nodes[0].matrix = this.rootMatrix; + } + public override bool CanHaveSubGroups() + { + return true; + } + public override void UpdateParameters() + { + Profiler.BeginSample("UpdateParameters"); + this.nodes[0].size = this.rootSpread; + this.nodes[0].matrix = this.rootMatrix; + base.UpdateParameters(); + Profiler.EndSample(); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeMaterial.cs b/UnityEditor/TreeEditor/TreeMaterial.cs new file mode 100644 index 00000000..92432acf --- /dev/null +++ b/UnityEditor/TreeEditor/TreeMaterial.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + public class TreeMaterial + { + public Material material; + public bool tileV; + } +} diff --git a/UnityEditor/TreeEditor/TreeNode.cs b/UnityEditor/TreeEditor/TreeNode.cs new file mode 100644 index 00000000..b766bd35 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeNode.cs @@ -0,0 +1,122 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeNode + { + public TreeSpline spline; + public int seed; + public float animSeed; + public bool visible; + public int triStart; + public int triEnd; + public int vertStart; + public int vertEnd; + public float capRange; + public float breakOffset; + public float size; + public float scale; + public float offset; + public float baseAngle; + public float angle; + public float pitch; + public Quaternion rotation; + public Matrix4x4 matrix; + public int parentID; + public int groupID; + [NonSerialized] + internal TreeNode parent; + [NonSerialized] + internal TreeGroup group; + [SerializeField] + private int _uniqueID = -1; + public int uniqueID + { + get + { + return this._uniqueID; + } + set + { + if (this._uniqueID == -1) + { + this._uniqueID = value; + } + } + } + public TreeNode() + { + this.spline = null; + this.parentID = 0; + this.groupID = 0; + this.parent = null; + this.group = null; + this.seed = 1234; + this.breakOffset = 1f; + this.visible = true; + this.animSeed = 0f; + this.scale = 1f; + this.rotation = Quaternion.identity; + this.matrix = Matrix4x4.identity; + } + public float GetScale() + { + float num = 1f; + if (this.parent != null) + { + num = this.parent.GetScale(); + } + return this.scale * num; + } + public float GetSurfaceAngleAtTime(float time) + { + if (this.spline == null) + { + return 0f; + } + Vector3 positionAtTime = this.spline.GetPositionAtTime(time); + float radiusAtTime = this.group.GetRadiusAtTime(this, time, false); + float num; + if (time < 0.5f) + { + float magnitude = (this.spline.GetPositionAtTime(time + 0.01f) - positionAtTime).magnitude; + float y = this.group.GetRadiusAtTime(this, time + 0.01f, false) - radiusAtTime; + num = Mathf.Atan2(y, magnitude); + } + else + { + float magnitude2 = (positionAtTime - this.spline.GetPositionAtTime(time - 0.01f)).magnitude; + float y2 = radiusAtTime - this.group.GetRadiusAtTime(this, time - 0.01f, false); + num = Mathf.Atan2(y2, magnitude2); + } + return num * 57.29578f; + } + public float GetRadiusAtTime(float time) + { + return this.group.GetRadiusAtTime(this, time, false); + } + public void GetPropertiesAtTime(float time, out Vector3 pos, out Quaternion rot, out float rad) + { + if (this.spline == null) + { + pos = Vector3.zero; + rot = Quaternion.identity; + } + else + { + pos = this.spline.GetPositionAtTime(time); + rot = this.spline.GetRotationAtTime(time); + } + rad = this.group.GetRadiusAtTime(this, time, false); + } + public Matrix4x4 GetLocalMatrixAtTime(float time) + { + Vector3 zero = Vector3.zero; + Quaternion identity = Quaternion.identity; + float num = 0f; + this.GetPropertiesAtTime(time, out zero, out identity, out num); + return Matrix4x4.TRS(zero, identity, Vector3.one); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeSpline.cs b/UnityEditor/TreeEditor/TreeSpline.cs new file mode 100644 index 00000000..fb8f3e7a --- /dev/null +++ b/UnityEditor/TreeEditor/TreeSpline.cs @@ -0,0 +1,257 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace TreeEditor +{ + [Serializable] + public class TreeSpline + { + public SplineNode[] nodes = new SplineNode[0]; + public float tension = 0.5f; + public TreeSpline() + { + } + public TreeSpline(TreeSpline o) + { + this.nodes = new SplineNode[o.nodes.Length]; + for (int i = 0; i < o.nodes.Length; i++) + { + this.nodes[i] = new SplineNode(o.nodes[i]); + } + this.tension = o.tension; + } + private void OnDisable() + { + for (int i = 0; i < this.nodes.Length; i++) + { + } + } + public void Reset() + { + for (int i = 0; i < this.nodes.Length; i++) + { + } + this.nodes = new SplineNode[0]; + } + public int GetNodeCount() + { + return this.nodes.Length; + } + public void SetNodeCount(int c) + { + if (c < this.nodes.Length) + { + SplineNode[] array = new SplineNode[c]; + for (int i = 0; i < c; i++) + { + array[i] = this.nodes[i]; + } + for (int j = c; j < this.nodes.Length; j++) + { + } + this.nodes = array; + } + } + public void RemoveNode(int c) + { + if (c < 0 || c >= this.nodes.Length) + { + return; + } + SplineNode[] array = new SplineNode[this.nodes.Length - 1]; + int num = 0; + for (int i = 0; i < this.nodes.Length; i++) + { + if (i != c) + { + array[num] = this.nodes[i]; + num++; + } + } + this.nodes = array; + } + public SplineNode[] GetNodes() + { + return this.nodes; + } + public void AddPoint(Vector3 pos, float timeInSeconds) + { + SplineNode[] array = new SplineNode[this.nodes.Length + 1]; + for (int i = 0; i < this.nodes.Length; i++) + { + array[i] = this.nodes[i]; + } + this.nodes = array; + SplineNode splineNode = new SplineNode(pos, timeInSeconds); + this.nodes[this.nodes.Length - 1] = splineNode; + } + public float GetApproximateLength() + { + if (this.nodes.Length < 2) + { + return 0f; + } + float num = 0f; + for (int i = 1; i < this.nodes.Length; i++) + { + float magnitude = (this.nodes[i - 1].point - this.nodes[i].point).magnitude; + num += magnitude; + } + return num; + } + public void UpdateTime() + { + if (this.nodes.Length < 2) + { + return; + } + float approximateLength = this.GetApproximateLength(); + float num = 0f; + this.nodes[0].time = num; + for (int i = 1; i < this.nodes.Length; i++) + { + float magnitude = (this.nodes[i - 1].point - this.nodes[i].point).magnitude; + num += magnitude; + this.nodes[i].time = num / approximateLength; + } + } + public void UpdateRotations() + { + if (this.nodes.Length < 2) + { + return; + } + Matrix4x4 m = Matrix4x4.identity; + this.nodes[0].rot = Quaternion.identity; + this.nodes[0].tangent = new Vector3(0f, 1f, 0f); + this.nodes[0].normal = new Vector3(0f, 0f, 1f); + for (int i = 1; i < this.nodes.Length; i++) + { + Vector3 vector; + if (i == this.nodes.Length - 1) + { + vector = this.nodes[i].point - this.nodes[i - 1].point; + } + else + { + float d = Vector3.Distance(this.nodes[i].point, this.nodes[i - 1].point); + float d2 = Vector3.Distance(this.nodes[i].point, this.nodes[i + 1].point); + vector = (this.nodes[i].point - this.nodes[i - 1].point) / d + (this.nodes[i + 1].point - this.nodes[i].point) / d2; + } + vector.Normalize(); + m.SetColumn(1, vector); + if (Mathf.Abs(Vector3.Dot(vector, m.GetColumn(0))) > 0.9999f) + { + m.SetColumn(0, new Vector3(0f, 1f, 0f)); + } + Vector3 normalized = Vector3.Cross(m.GetColumn(0), vector).normalized; + m.SetColumn(2, normalized); + m = MathUtils.OrthogonalizeMatrix(m); + this.nodes[i].rot = MathUtils.QuaternionFromMatrix(m); + this.nodes[i].normal = m.GetColumn(2); + this.nodes[i].tangent = m.GetColumn(1); + if (Quaternion.Dot(this.nodes[i].rot, this.nodes[i - 1].rot) < 0f) + { + this.nodes[i].rot.x = -this.nodes[i].rot.x; + this.nodes[i].rot.y = -this.nodes[i].rot.y; + this.nodes[i].rot.z = -this.nodes[i].rot.z; + this.nodes[i].rot.w = -this.nodes[i].rot.w; + } + } + } + private Quaternion GetRotationInternal(int idxFirstpoint, float t) + { + float num = t * t; + float num2 = num * t; + Quaternion rot = this.nodes[Mathf.Max(idxFirstpoint - 1, 0)].rot; + Quaternion rot2 = this.nodes[idxFirstpoint].rot; + Quaternion rot3 = this.nodes[idxFirstpoint + 1].rot; + Quaternion rot4 = this.nodes[Mathf.Min(idxFirstpoint + 2, this.nodes.Length - 1)].rot; + Quaternion quaternion = new Quaternion(this.tension * (rot3.x - rot.x), this.tension * (rot3.y - rot.y), this.tension * (rot3.z - rot.z), this.tension * (rot3.w - rot.w)); + Quaternion quaternion2 = new Quaternion(this.tension * (rot4.x - rot2.x), this.tension * (rot4.y - rot2.y), this.tension * (rot4.z - rot2.z), this.tension * (rot4.w - rot2.w)); + float num3 = 2f * num2 - 3f * num + 1f; + float num4 = -2f * num2 + 3f * num; + float num5 = num2 - 2f * num + t; + float num6 = num2 - num; + Quaternion result = default(Quaternion); + result.x = num3 * rot2.x + num4 * rot3.x + num5 * quaternion.x + num6 * quaternion2.x; + result.y = num3 * rot2.y + num4 * rot3.y + num5 * quaternion.y + num6 * quaternion2.y; + result.z = num3 * rot2.z + num4 * rot3.z + num5 * quaternion.z + num6 * quaternion2.z; + result.w = num3 * rot2.w + num4 * rot3.w + num5 * quaternion.w + num6 * quaternion2.w; + float num7 = Mathf.Sqrt(result.x * result.x + result.y * result.y + result.z * result.z + result.w * result.w); + result.x /= num7; + result.y /= num7; + result.z /= num7; + result.w /= num7; + return result; + } + private Vector3 GetPositionInternal(int idxFirstpoint, float t) + { + float num = t * t; + float num2 = num * t; + Vector3 point = this.nodes[Mathf.Max(idxFirstpoint - 1, 0)].point; + Vector3 point2 = this.nodes[idxFirstpoint].point; + Vector3 point3 = this.nodes[idxFirstpoint + 1].point; + Vector3 point4 = this.nodes[Mathf.Min(idxFirstpoint + 2, this.nodes.Length - 1)].point; + Vector3 a = this.tension * (point3 - point); + Vector3 a2 = this.tension * (point4 - point2); + float d = 2f * num2 - 3f * num + 1f; + float d2 = -2f * num2 + 3f * num; + float d3 = num2 - 2f * num + t; + float d4 = num2 - num; + return d * point2 + d2 * point3 + d3 * a + d4 * a2; + } + public Quaternion GetRotationAtTime(float timeParam) + { + if (this.nodes.Length < 2) + { + return Quaternion.identity; + } + if (timeParam <= this.nodes[0].time) + { + return this.nodes[0].rot; + } + if (timeParam >= this.nodes[this.nodes.Length - 1].time) + { + return this.nodes[this.nodes.Length - 1].rot; + } + int i; + for (i = 1; i < this.nodes.Length; i++) + { + if (this.nodes[i].time > timeParam) + { + break; + } + } + int num = i - 1; + float t = (timeParam - this.nodes[num].time) / (this.nodes[num + 1].time - this.nodes[num].time); + return this.GetRotationInternal(num, t); + } + public Vector3 GetPositionAtTime(float timeParam) + { + if (this.nodes.Length < 2) + { + return Vector3.zero; + } + if (timeParam <= this.nodes[0].time) + { + return this.nodes[0].point; + } + if (timeParam >= this.nodes[this.nodes.Length - 1].time) + { + return this.nodes[this.nodes.Length - 1].point; + } + int i; + for (i = 1; i < this.nodes.Length; i++) + { + if (this.nodes[i].time > timeParam) + { + break; + } + } + int num = i - 1; + float t = (timeParam - this.nodes[num].time) / (this.nodes[num + 1].time - this.nodes[num].time); + return this.GetPositionInternal(num, t); + } + } +} diff --git a/UnityEditor/TreeEditor/TreeTriangle.cs b/UnityEditor/TreeEditor/TreeTriangle.cs new file mode 100644 index 00000000..2c05f220 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeTriangle.cs @@ -0,0 +1,43 @@ +using System; +namespace TreeEditor +{ + public class TreeTriangle + { + public bool tileV; + public bool isBillboard; + public bool isCutout = true; + public int materialIndex = -1; + public int[] v = new int[3]; + public TreeTriangle(int material, int v0, int v1, int v2) + { + this.materialIndex = material; + this.v[0] = v0; + this.v[1] = v1; + this.v[2] = v2; + } + public TreeTriangle(int material, int v0, int v1, int v2, bool isBillboard) + { + this.isBillboard = isBillboard; + this.materialIndex = material; + this.v[0] = v0; + this.v[1] = v1; + this.v[2] = v2; + } + public TreeTriangle(int material, int v0, int v1, int v2, bool isBillboard, bool tileV, bool isCutout) + { + this.tileV = tileV; + this.isBillboard = isBillboard; + this.isCutout = isCutout; + this.materialIndex = material; + this.v[0] = v0; + this.v[1] = v1; + this.v[2] = v2; + } + public void flip() + { + int num = this.v[0]; + this.v[0] = this.v[1]; + this.v[1] = num; + } + } +} diff --git a/UnityEditor/TreeEditor/TreeVertex.cs b/UnityEditor/TreeEditor/TreeVertex.cs new file mode 100644 index 00000000..63018c97 --- /dev/null +++ b/UnityEditor/TreeEditor/TreeVertex.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +namespace TreeEditor +{ + public class TreeVertex + { + public Vector3 pos; + public Vector3 nor; + public Vector4 tangent = new Vector4(1f, 0f, 0f, 1f); + public Vector2 uv0; + public Vector2 uv1 = new Vector2(0f, 0f); + public Color color = new Color(0f, 0f, 0f, 1f); + public bool flag; + public void SetAnimationProperties(float primaryFactor, float secondaryFactor, float edgeFactor, float phase) + { + this.color.r = phase; + this.color.g = edgeFactor; + this.uv1.x = primaryFactor; + this.uv1.y = secondaryFactor; + } + public void SetAmbientOcclusion(float ao) + { + this.color.a = ao; + } + public void Lerp4(TreeVertex[] tv, Vector2 factor) + { + this.pos = Vector3.Lerp(Vector3.Lerp(tv[1].pos, tv[2].pos, factor.x), Vector3.Lerp(tv[0].pos, tv[3].pos, factor.x), factor.y); + this.nor = Vector3.Lerp(Vector3.Lerp(tv[1].nor, tv[2].nor, factor.x), Vector3.Lerp(tv[0].nor, tv[3].nor, factor.x), factor.y).normalized; + this.tangent = Vector4.Lerp(Vector4.Lerp(tv[1].tangent, tv[2].tangent, factor.x), Vector4.Lerp(tv[0].tangent, tv[3].tangent, factor.x), factor.y); + Vector3 vector = new Vector3(this.tangent.x, this.tangent.y, this.tangent.z); + vector.Normalize(); + this.tangent.x = vector.x; + this.tangent.y = vector.y; + this.tangent.z = vector.z; + this.color = Color.Lerp(Color.Lerp(tv[1].color, tv[2].color, factor.x), Color.Lerp(tv[0].color, tv[3].color, factor.x), factor.y); + } + } +} diff --git a/UnityEditor/UnityEditor.AnimatedValues/AnimBool.cs b/UnityEditor/UnityEditor.AnimatedValues/AnimBool.cs new file mode 100644 index 00000000..7acad34a --- /dev/null +++ b/UnityEditor/UnityEditor.AnimatedValues/AnimBool.cs @@ -0,0 +1,43 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.AnimatedValues +{ + [Serializable] + public class AnimBool : BaseAnimValue + { + [SerializeField] + private float m_Value; + public float faded + { + get + { + this.GetValue(); + return this.m_Value; + } + } + public AnimBool() : base(false) + { + } + public AnimBool(bool value) : base(value) + { + } + public AnimBool(UnityAction callback) : base(false, callback) + { + } + public AnimBool(bool value, UnityAction callback) : base(value, callback) + { + } + protected override bool GetValue() + { + float num = (!base.target) ? 1f : 0f; + float to = 1f - num; + this.m_Value = Mathf.Lerp(num, to, base.lerpPosition); + return this.m_Value > 0.5f; + } + public float Fade(float from, float to) + { + return Mathf.Lerp(from, to, this.faded); + } + } +} diff --git a/UnityEditor/UnityEditor.AnimatedValues/AnimFloat.cs b/UnityEditor/UnityEditor.AnimatedValues/AnimFloat.cs new file mode 100644 index 00000000..984bd31f --- /dev/null +++ b/UnityEditor/UnityEditor.AnimatedValues/AnimFloat.cs @@ -0,0 +1,23 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.AnimatedValues +{ + [Serializable] + public class AnimFloat : BaseAnimValue + { + [SerializeField] + private float m_Value; + public AnimFloat(float value) : base(value) + { + } + public AnimFloat(float value, UnityAction callback) : base(value, callback) + { + } + protected override float GetValue() + { + this.m_Value = Mathf.Lerp(base.start, base.target, base.lerpPosition); + return this.m_Value; + } + } +} diff --git a/UnityEditor/UnityEditor.AnimatedValues/AnimQuaternion.cs b/UnityEditor/UnityEditor.AnimatedValues/AnimQuaternion.cs new file mode 100644 index 00000000..e119c53f --- /dev/null +++ b/UnityEditor/UnityEditor.AnimatedValues/AnimQuaternion.cs @@ -0,0 +1,23 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.AnimatedValues +{ + [Serializable] + public class AnimQuaternion : BaseAnimValue + { + [SerializeField] + private Quaternion m_Value; + public AnimQuaternion(Quaternion value) : base(value) + { + } + public AnimQuaternion(Quaternion value, UnityAction callback) : base(value, callback) + { + } + protected override Quaternion GetValue() + { + this.m_Value = Quaternion.Slerp(base.start, base.target, base.lerpPosition); + return this.m_Value; + } + } +} diff --git a/UnityEditor/UnityEditor.AnimatedValues/AnimVector3.cs b/UnityEditor/UnityEditor.AnimatedValues/AnimVector3.cs new file mode 100644 index 00000000..cb7b2db7 --- /dev/null +++ b/UnityEditor/UnityEditor.AnimatedValues/AnimVector3.cs @@ -0,0 +1,26 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.AnimatedValues +{ + [Serializable] + public class AnimVector3 : BaseAnimValue + { + [SerializeField] + private Vector3 m_Value; + public AnimVector3() : base(Vector3.zero) + { + } + public AnimVector3(Vector3 value) : base(value) + { + } + public AnimVector3(Vector3 value, UnityAction callback) : base(value, callback) + { + } + protected override Vector3 GetValue() + { + this.m_Value = Vector3.Lerp(base.start, base.target, base.lerpPosition); + return this.m_Value; + } + } +} diff --git a/UnityEditor/UnityEditor.AnimatedValues/BaseAnimValue.cs b/UnityEditor/UnityEditor.AnimatedValues/BaseAnimValue.cs new file mode 100644 index 00000000..cc8d35e9 --- /dev/null +++ b/UnityEditor/UnityEditor.AnimatedValues/BaseAnimValue.cs @@ -0,0 +1,141 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.AnimatedValues +{ + public abstract class BaseAnimValue + { + private T m_Start; + [SerializeField] + private T m_Target; + private double m_LastTime; + private double m_LerpPosition = 1.0; + public float speed = 2f; + [NonSerialized] + public UnityEvent valueChanged; + private bool m_Animating; + public bool isAnimating + { + get + { + return this.m_Animating; + } + } + protected float lerpPosition + { + get + { + double num = 1.0 - this.m_LerpPosition; + double num2 = 1.0 - num * num * num * num; + return (float)num2; + } + } + protected T start + { + get + { + return this.m_Start; + } + } + public T target + { + get + { + return this.m_Target; + } + set + { + if (!this.m_Target.Equals(value)) + { + this.BeginAnimating(value, this.value); + } + } + } + public T value + { + get + { + return this.GetValue(); + } + set + { + this.StopAnim(value); + } + } + protected BaseAnimValue(T value) + { + this.m_Start = value; + this.m_Target = value; + this.valueChanged = new UnityEvent(); + } + protected BaseAnimValue(T value, UnityAction callback) + { + this.m_Start = value; + this.m_Target = value; + this.valueChanged = new UnityEvent(); + this.valueChanged.AddListener(callback); + } + private static T2 Clamp(T2 val, T2 min, T2 max) where T2 : IComparable + { + if (val.CompareTo(min) < 0) + { + return min; + } + if (val.CompareTo(max) > 0) + { + return max; + } + return val; + } + protected void BeginAnimating(T newTarget, T newStart) + { + this.m_Start = newStart; + this.m_Target = newTarget; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + this.m_Animating = true; + this.m_LastTime = EditorApplication.timeSinceStartup; + this.m_LerpPosition = 0.0; + } + private void Update() + { + if (!this.m_Animating) + { + return; + } + this.UpdateLerpPosition(); + if (this.valueChanged != null) + { + this.valueChanged.Invoke(); + } + if (this.lerpPosition >= 1f) + { + this.m_Animating = false; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + } + private void UpdateLerpPosition() + { + double timeSinceStartup = EditorApplication.timeSinceStartup; + double num = timeSinceStartup - this.m_LastTime; + this.m_LerpPosition = BaseAnimValue.Clamp(this.m_LerpPosition + num * (double)this.speed, 0.0, 1.0); + this.m_LastTime = timeSinceStartup; + } + protected void StopAnim(T newValue) + { + bool flag = false; + if ((!newValue.Equals(this.GetValue()) || this.m_LerpPosition < 1.0) && this.valueChanged != null) + { + flag = true; + } + this.m_Target = newValue; + this.m_Start = newValue; + this.m_LerpPosition = 1.0; + this.m_Animating = false; + if (flag) + { + this.valueChanged.Invoke(); + } + } + protected abstract T GetValue(); + } +} diff --git a/UnityEditor/UnityEditor.Callbacks/DidReloadScripts.cs b/UnityEditor/UnityEditor.Callbacks/DidReloadScripts.cs new file mode 100644 index 00000000..cc074b5d --- /dev/null +++ b/UnityEditor/UnityEditor.Callbacks/DidReloadScripts.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Callbacks +{ + public sealed class DidReloadScripts : CallbackOrderAttribute + { + public DidReloadScripts() + { + this.m_CallbackOrder = 1; + } + public DidReloadScripts(int callbackOrder) + { + this.m_CallbackOrder = callbackOrder; + } + } +} diff --git a/UnityEditor/UnityEditor.Callbacks/OnOpenAssetAttribute.cs b/UnityEditor/UnityEditor.Callbacks/OnOpenAssetAttribute.cs new file mode 100644 index 00000000..055d9e0b --- /dev/null +++ b/UnityEditor/UnityEditor.Callbacks/OnOpenAssetAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Callbacks +{ + public sealed class OnOpenAssetAttribute : CallbackOrderAttribute + { + public OnOpenAssetAttribute() + { + this.m_CallbackOrder = 1; + } + public OnOpenAssetAttribute(int callbackOrder) + { + this.m_CallbackOrder = callbackOrder; + } + } +} diff --git a/UnityEditor/UnityEditor.Callbacks/PostProcessBuildAttribute.cs b/UnityEditor/UnityEditor.Callbacks/PostProcessBuildAttribute.cs new file mode 100644 index 00000000..83e22339 --- /dev/null +++ b/UnityEditor/UnityEditor.Callbacks/PostProcessBuildAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Callbacks +{ + public sealed class PostProcessBuildAttribute : CallbackOrderAttribute + { + public PostProcessBuildAttribute() + { + this.m_CallbackOrder = 1; + } + public PostProcessBuildAttribute(int callbackOrder) + { + this.m_CallbackOrder = callbackOrder; + } + } +} diff --git a/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs b/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs new file mode 100644 index 00000000..113a033e --- /dev/null +++ b/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Callbacks +{ + public sealed class PostProcessSceneAttribute : CallbackOrderAttribute + { + public PostProcessSceneAttribute() + { + this.m_CallbackOrder = 1; + } + public PostProcessSceneAttribute(int callbackOrder) + { + this.m_CallbackOrder = callbackOrder; + } + } +} diff --git a/UnityEditor/UnityEditor.Events/UnityEventTools.cs b/UnityEditor/UnityEditor.Events/UnityEventTools.cs new file mode 100644 index 00000000..2b330fae --- /dev/null +++ b/UnityEditor/UnityEditor.Events/UnityEventTools.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor.Events +{ + public static class UnityEventTools + { + public static void AddPersistentListener(UnityEventBase unityEvent) + { + unityEvent.AddPersistentListener(); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, int index) + { + unityEvent.RemovePersistentListener(index); + } + public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) + { + unityEvent.AddPersistentListener(call); + } + public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) + { + unityEvent.AddPersistentListener(call); + } + public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) + { + unityEvent.AddPersistentListener(call); + } + public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) + { + unityEvent.AddPersistentListener(call); + } + public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) + { + unityEvent.AddPersistentListener(call); + } + public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) + { + unityEvent.RegisterPersistentListener(index, call); + } + public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) + { + unityEvent.RegisterPersistentListener(index, call); + } + public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) + { + unityEvent.RegisterPersistentListener(index, call); + } + public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) + { + unityEvent.RegisterPersistentListener(index, call); + } + public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) + { + unityEvent.RegisterPersistentListener(index, call); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.RemovePersistentListener(call.Target as UnityEngine.Object, call.Method); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.RemovePersistentListener(call.Target as UnityEngine.Object, call.Method); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.RemovePersistentListener(call.Target as UnityEngine.Object, call.Method); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.RemovePersistentListener(call.Target as UnityEngine.Object, call.Method); + } + public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.RemovePersistentListener(call.Target as UnityEngine.Object, call.Method); + } + public static void UnregisterPersistentListener(UnityEventBase unityEvent, int index) + { + unityEvent.UnregisterPersistentListener(index); + } + public static void AddVoidPersistentListener(UnityEventBase unityEvent, UnityAction call) + { + unityEvent.AddVoidPersistentListener(call); + } + public static void RegisterVoidPersistentListener(UnityEventBase unityEvent, int index, UnityAction call) + { + unityEvent.RegisterVoidPersistentListener(index, call); + } + public static void AddIntPersistentListener(UnityEventBase unityEvent, UnityAction call, int argument) + { + unityEvent.AddIntPersistentListener(call, argument); + } + public static void RegisterIntPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, int argument) + { + unityEvent.RegisterIntPersistentListener(index, call, argument); + } + public static void AddFloatPersistentListener(UnityEventBase unityEvent, UnityAction call, float argument) + { + unityEvent.AddFloatPersistentListener(call, argument); + } + public static void RegisterFloatPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, float argument) + { + unityEvent.RegisterFloatPersistentListener(index, call, argument); + } + public static void AddBoolPersistentListener(UnityEventBase unityEvent, UnityAction call, bool argument) + { + unityEvent.AddBoolPersistentListener(call, argument); + } + public static void RegisterBoolPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, bool argument) + { + unityEvent.RegisterBoolPersistentListener(index, call, argument); + } + public static void AddStringPersistentListener(UnityEventBase unityEvent, UnityAction call, string argument) + { + unityEvent.AddStringPersistentListener(call, argument); + } + public static void RegisterStringPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, string argument) + { + unityEvent.RegisterStringPersistentListener(index, call, argument); + } + public static void AddObjectPersistentListener(UnityEventBase unityEvent, UnityAction call, T argument) where T : UnityEngine.Object + { + unityEvent.AddObjectPersistentListener(call, argument); + } + public static void RegisterObjectPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, T argument) where T : UnityEngine.Object + { + unityEvent.RegisterObjectPersistentListener(index, call, argument); + } + } +} diff --git a/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs new file mode 100644 index 00000000..6fd74818 --- /dev/null +++ b/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using UnityEditorInternal; +namespace UnityEditor.LinuxStandalone +{ + internal class LinuxStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider + { + public bool platformHasPrecompiledLibIl2Cpp + { + get + { + return false; + } + } + public override bool emitNullChecks + { + get + { + return false; + } + } + public override bool enableStackTraces + { + get + { + return false; + } + } + public override string nativeLibraryFileName + { + get + { + return "libUserAssembly.so"; + } + } + public LinuxStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder) : base(target, Path.Combine(dataFolder, "Libraries")) + { + } + public override INativeCompiler CreateNativeCompiler() + { + BuildTarget target = this.target; + ICompilerSettings settings; + if (target != BuildTarget.StandaloneLinux) + { + if (target != BuildTarget.StandaloneLinux64) + { + throw new Exception("Not sure how to handle Linux universal yet..."); + } + settings = new GccCompilerSettingsx86_64(); + } + else + { + settings = new GccCompilerSettingsx86(); + } + return new GccCompiler(settings); + } + } +} diff --git a/UnityEditor/UnityEditor.Macros/MacroEvaluator.cs b/UnityEditor/UnityEditor.Macros/MacroEvaluator.cs new file mode 100644 index 00000000..c9b4fd3b --- /dev/null +++ b/UnityEditor/UnityEditor.Macros/MacroEvaluator.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityScript.Scripting; +namespace UnityEditor.Macros +{ + public static class MacroEvaluator + { + private class EditorEvaluationDomainProvider : SimpleEvaluationDomainProvider + { + private static readonly string[] DefaultImports = new string[] + { + "UnityEditor", + "UnityEngine" + }; + public EditorEvaluationDomainProvider() : base(MacroEvaluator.EditorEvaluationDomainProvider.DefaultImports) + { + } + public override Assembly[] GetAssemblyReferences() + { + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + IEnumerable second = + from a in loadedAssemblies.SelectMany((Assembly a) => a.GetReferencedAssemblies()) + select MacroEvaluator.EditorEvaluationDomainProvider.TryToLoad(a) into a + where a != null + select a; + return loadedAssemblies.Concat(second).ToArray(); + } + private static Assembly TryToLoad(AssemblyName a) + { + Assembly result; + try + { + result = Assembly.Load(a); + } + catch (Exception) + { + result = null; + } + return result; + } + } + private static readonly EvaluationContext EditorEvaluationContext = new EvaluationContext(new MacroEvaluator.EditorEvaluationDomainProvider()); + public static string Eval(string macro) + { + if (macro.StartsWith("ExecuteMethod: ")) + { + return MacroEvaluator.ExecuteMethodThroughReflection(macro); + } + object obj = Evaluator.Eval(MacroEvaluator.EditorEvaluationContext, macro); + return (obj != null) ? obj.ToString() : "Null"; + } + private static string ExecuteMethodThroughReflection(string macro) + { + Regex regex = new Regex("ExecuteMethod: (?.*)\\.(?.*)"); + Match match = regex.Match(macro); + string typename = match.Groups["type"].ToString(); + string text = match.Groups["method"].ToString(); + Type type = ( + from a in EditorAssemblies.loadedAssemblies + select a.GetType(typename, false) into t + where t != null + select t).First(); + MethodInfo method = type.GetMethod(text, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method == null) + { + throw new ArgumentException(string.Format("cannot find method {0} in type {1}", text, typename)); + } + if (method.GetParameters().Length > 0) + { + throw new ArgumentException("You can only invoke static methods with no arguments"); + } + object obj = method.Invoke(null, new object[0]); + return (obj != null) ? obj.ToString() : "Null"; + } + } +} diff --git a/UnityEditor/UnityEditor.Macros/MethodEvaluator.cs b/UnityEditor/UnityEditor.Macros/MethodEvaluator.cs new file mode 100644 index 00000000..7be79409 --- /dev/null +++ b/UnityEditor/UnityEditor.Macros/MethodEvaluator.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +namespace UnityEditor.Macros +{ + public static class MethodEvaluator + { + public class AssemblyResolver + { + private readonly string _assemblyDirectory; + public AssemblyResolver(string assemblyDirectory) + { + this._assemblyDirectory = assemblyDirectory; + } + public Assembly AssemblyResolve(object sender, ResolveEventArgs args) + { + string str = args.Name.Split(new char[] + { + ',' + })[0]; + string text = Path.Combine(this._assemblyDirectory, str + ".dll"); + if (File.Exists(text)) + { + return Assembly.LoadFrom(text); + } + return null; + } + } + public static object Eval(string assemblyFile, string typeName, string methodName, Type[] paramTypes, object[] args) + { + string directoryName = Path.GetDirectoryName(assemblyFile); + MethodEvaluator.AssemblyResolver @object = new MethodEvaluator.AssemblyResolver(directoryName); + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(@object.AssemblyResolve); + object result; + try + { + Assembly assembly = Assembly.LoadFrom(assemblyFile); + MethodInfo method = assembly.GetType(typeName, true).GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, paramTypes, null); + if (method == null) + { + throw new ArgumentException(string.Format("Method {0}.{1}({2}) not found in assembly {3}!", new object[] + { + typeName, + methodName, + MethodEvaluator.ToCommaSeparatedString(paramTypes), + assembly.FullName + })); + } + result = method.Invoke(null, args); + } + finally + { + AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(@object.AssemblyResolve); + } + return result; + } + private static string ToCommaSeparatedString(IEnumerable items) + { + return string.Join(", ", ( + from o in items + select o.ToString()).ToArray()); + } + } +} diff --git a/UnityEditor/UnityEditor.Modules/BuildLaunchPlayerArgs.cs b/UnityEditor/UnityEditor.Modules/BuildLaunchPlayerArgs.cs new file mode 100644 index 00000000..51f079de --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/BuildLaunchPlayerArgs.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor.Modules +{ + internal struct BuildLaunchPlayerArgs + { + public BuildTarget target; + public string playerPackage; + public string installPath; + public string productName; + public BuildOptions options; + } +} diff --git a/UnityEditor/UnityEditor.Modules/BuildPostProcessArgs.cs b/UnityEditor/UnityEditor.Modules/BuildPostProcessArgs.cs new file mode 100644 index 00000000..c584e0c4 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/BuildPostProcessArgs.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor.Modules +{ + internal struct BuildPostProcessArgs + { + public BuildTarget target; + public string stagingArea; + public string stagingAreaData; + public string stagingAreaDataManaged; + public string playerPackage; + public string installPath; + public string companyName; + public string productName; + public Guid productGUID; + public BuildOptions options; + internal RuntimeClassRegistry usedClassRegistry; + } +} diff --git a/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs b/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs new file mode 100644 index 00000000..bb646684 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEditor.Modules +{ + internal abstract class DefaultPlayerSettingsEditorExtension : ISettingEditorExtension + { + public virtual void OnEnable(PlayerSettingsEditor settingsEditor) + { + } + public virtual bool HasPublishSection() + { + return true; + } + public virtual void PublishSectionGUI(float h, float midWidth, float maxWidth) + { + } + public virtual bool HasIdentificationGUI() + { + return false; + } + public virtual void IdentificationSectionGUI() + { + } + public virtual void ConfigurationSectionGUI() + { + } + public virtual bool SupportsOrientation() + { + return false; + } + public virtual void SplashSectionGUI() + { + } + } +} diff --git a/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs b/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs new file mode 100644 index 00000000..128dab55 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IBuildPostprocessor + { + void LaunchPlayer(BuildLaunchPlayerArgs args); + void PostProcess(BuildPostProcessArgs args); + bool SupportsInstallInBuildFolder(); + string GetExtension(); + string[] FindPluginFilesToCopy(string basePluginFolder, out bool shouldRetainStructure); + } +} diff --git a/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs b/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs new file mode 100644 index 00000000..7c08d6c2 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IPlatformSupportModule + { + string TargetName + { + get; + } + string JamTarget + { + get; + } + IBuildPostprocessor CreateBuildPostprocessor(); + ISettingEditorExtension CreateSettingsEditorExtension(); + IPreferenceWindowExtension CreatePreferenceWindowExtension(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/IPreferenceWindowExtension.cs b/UnityEditor/UnityEditor.Modules/IPreferenceWindowExtension.cs new file mode 100644 index 00000000..af0026a2 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IPreferenceWindowExtension.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IPreferenceWindowExtension + { + void ReadPreferences(); + void WritePreferences(); + bool HasExternalApplications(); + void ShowExternalApplications(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs b/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs new file mode 100644 index 00000000..7b161981 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface ISettingEditorExtension + { + void OnEnable(PlayerSettingsEditor settingsEditor); + bool HasPublishSection(); + void PublishSectionGUI(float h, float midWidth, float maxWidth); + bool HasIdentificationGUI(); + void IdentificationSectionGUI(); + void ConfigurationSectionGUI(); + bool SupportsOrientation(); + void SplashSectionGUI(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/ModuleManager.cs b/UnityEditor/UnityEditor.Modules/ModuleManager.cs new file mode 100644 index 00000000..ec4a2b42 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/ModuleManager.cs @@ -0,0 +1,469 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using Unity.DataContract; +using UnityEditor.Utils; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Modules +{ + internal static class ModuleManager + { + [NonSerialized] + private static List s_PlatformModules; + [NonSerialized] + private static List s_EditorModules; + [NonSerialized] + private static IPackageManagerModule s_PackageManager; + internal static IPackageManagerModule packageManager + { + get + { + ModuleManager.Initialize(); + return ModuleManager.s_PackageManager; + } + } + private static List platformSupportModules + { + get + { + ModuleManager.Initialize(); + if (ModuleManager.s_PlatformModules == null) + { + ModuleManager.RegisterPlatformSupportModules(); + } + return ModuleManager.s_PlatformModules; + } + } + private static List editorModules + { + get + { + if (ModuleManager.s_EditorModules == null) + { + return new List(); + } + return ModuleManager.s_EditorModules; + } + } + internal static bool IsRegisteredModule(string file) + { + return ModuleManager.s_PackageManager != null && ModuleManager.s_PackageManager.GetType().Assembly.Location.NormalizePath() == file.NormalizePath(); + } + internal static bool IsPlatformSupportLoaded(string target) + { + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return true; + } + } + return false; + } + internal static void Initialize() + { + if (ModuleManager.s_PackageManager == null) + { + ModuleManager.RegisterPackageManager(); + ModuleManager.LoadUnityExtensions(); + } + } + private static string CombinePaths(params string[] paths) + { + if (paths == null) + { + throw new ArgumentNullException("paths"); + } + if (paths.Length == 1) + { + return paths[0]; + } + StringBuilder stringBuilder = new StringBuilder(paths[0]); + for (int i = 1; i < paths.Length; i++) + { + stringBuilder.AppendFormat("{0}{1}", "/", paths[i]); + } + return stringBuilder.ToString(); + } + private static string RemapDllLocation(string dllLocation) + { + string fileName = Path.GetFileName(dllLocation); + string directoryName = Path.GetDirectoryName(dllLocation); + string text = ModuleManager.CombinePaths(new string[] + { + directoryName, + "Standalone", + fileName + }); + if (File.Exists(text)) + { + return text; + } + return dllLocation; + } + private static void LoadUnityExtensions() + { + ModuleManager.LoadUnityExtensionsWithPM(); + } + private static void LoadUnityExtensionsWithPM() + { + foreach (Unity.DataContract.PackageInfo current in ModuleManager.s_PackageManager.unityExtensions) + { + Console.WriteLine("Setting {0} v{1} for Unity v{2} to {3}", new object[] + { + current.name, + current.version, + current.unityVersion, + current.basePath + }); + foreach (KeyValuePair current2 in + from f in current.files + where f.Value.type == PackageFileType.Dll + select f) + { + string text = Path.Combine(current.basePath, current2.Key).NormalizePath(); + if (!File.Exists(text)) + { + UnityEngine.Debug.LogWarning(string.Format("Missing assembly \t{0} for {1}. Extension support may be incomplete.", current2.Key, current.name)); + } + else + { + if (!string.IsNullOrEmpty(current2.Value.guid)) + { + InternalEditorUtility.RegisterExtensionDll(text, current2.Value.guid); + } + else + { + InternalEditorUtility.SetupCustomDll(Path.GetFileName(text), text); + } + } + } + ModuleManager.s_PackageManager.LoadPackage(current); + } + } + internal static void InitializePlatformSupportModules() + { + ModuleManager.Initialize(); + ModuleManager.RegisterPlatformSupportModules(); + } + internal static void Shutdown() + { + if (ModuleManager.s_PackageManager != null) + { + ModuleManager.s_PackageManager.Shutdown(true); + } + ModuleManager.s_PackageManager = null; + ModuleManager.s_PlatformModules = null; + ModuleManager.s_EditorModules = null; + } + private static void RegisterPackageManager() + { + ModuleManager.s_EditorModules = new List(); + try + { + Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => null != a.GetType("Unity.PackageManager.PackageManager")); + if (assembly != null && ModuleManager.InitializePackageManager(assembly, null)) + { + return; + } + } + catch (Exception arg) + { + Console.WriteLine("Error enumerating assemblies looking for package manager. {0}", arg); + } + Type type = ( + from a in AppDomain.CurrentDomain.GetAssemblies() + where a.GetName().Name == "Unity.Locator" + select a.GetType("Unity.PackageManager.Locator")).FirstOrDefault(); + try + { + type.InvokeMember("Scan", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] + { + new string[] + { + FileUtil.NiceWinPath(EditorApplication.applicationContentsPath) + }, + Application.unityVersion + }); + } + catch (Exception arg2) + { + Console.WriteLine("Error scanning for packages. {0}", arg2); + return; + } + Unity.DataContract.PackageInfo packageInfo; + try + { + packageInfo = (type.InvokeMember("GetPackageManager", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new string[] + { + Application.unityVersion + }) as Unity.DataContract.PackageInfo); + if (packageInfo == null) + { + Console.WriteLine("No package manager found!"); + return; + } + } + catch (Exception arg3) + { + Console.WriteLine("Error scanning for packages. {0}", arg3); + return; + } + try + { + ModuleManager.InitializePackageManager(packageInfo); + } + catch (Exception arg4) + { + Console.WriteLine("Error initializing package manager. {0}", arg4); + } + if (ModuleManager.s_PackageManager != null) + { + ModuleManager.s_PackageManager.CheckForUpdates(); + } + } + private static bool InitializePackageManager(Unity.DataContract.PackageInfo package) + { + string text = ( + from x in package.files + where x.Value.type == PackageFileType.Dll + select x.Key).FirstOrDefault(); + if (text == null || !File.Exists(Path.Combine(package.basePath, text))) + { + return false; + } + InternalEditorUtility.SetPlatformPath(package.basePath); + Assembly assembly = InternalEditorUtility.LoadAssemblyWrapper(Path.GetFileName(text), Path.Combine(package.basePath, text)); + return ModuleManager.InitializePackageManager(assembly, package); + } + private static bool InitializePackageManager(Assembly assembly, Unity.DataContract.PackageInfo package) + { + ModuleManager.s_PackageManager = AssemblyHelper.FindImplementors(assembly).FirstOrDefault(); + if (ModuleManager.s_PackageManager == null) + { + return false; + } + string location = assembly.Location; + if (package != null) + { + InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); + } + else + { + package = new Unity.DataContract.PackageInfo + { + basePath = Path.GetDirectoryName(location) + }; + } + ModuleManager.s_PackageManager.moduleInfo = package; + ModuleManager.s_PackageManager.editorInstallPath = EditorApplication.applicationContentsPath; + ModuleManager.s_PackageManager.unityVersion = new PackageVersion(Application.unityVersion); + ModuleManager.s_PackageManager.Initialize(); + foreach (Unity.DataContract.PackageInfo current in ModuleManager.s_PackageManager.playbackEngines) + { + BuildTarget buildTarget = BuildTarget.StandaloneWindows; + try + { + buildTarget = (BuildTarget)((int)Enum.Parse(typeof(BuildTarget), current.name)); + } + catch + { + UnityEngine.Debug.LogWarning(string.Format("Couldn't find build target for {0}", current.name)); + continue; + } + Console.WriteLine("Setting {0} v{1} for Unity v{2} to {3}", new object[] + { + buildTarget, + current.version, + current.unityVersion, + current.basePath + }); + foreach (KeyValuePair current2 in + from f in current.files + where f.Value.type == PackageFileType.Dll + select f) + { + string path = Path.Combine(current.basePath, current2.Key).NormalizePath(); + if (!File.Exists(path)) + { + UnityEngine.Debug.LogWarning(string.Format("Missing assembly \t{0} for {1}. Player support may be incomplete.", current.basePath, current.name)); + } + else + { + InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); + } + } + BuildPipeline.SetPlaybackEngineDirectory(buildTarget, BuildOptions.None, current.basePath); + InternalEditorUtility.SetPlatformPath(current.basePath); + ModuleManager.s_PackageManager.LoadPackage(current); + } + return true; + } + private static void RegisterPlatformSupportModules() + { + Console.WriteLine("Registering platform support modules:"); + Stopwatch stopwatch = Stopwatch.StartNew(); + ModuleManager.s_PlatformModules = ModuleManager.RegisterModulesFromLoadedAssemblies(new Func>(ModuleManager.RegisterPlatformSupportModulesFromAssembly)).ToList(); + stopwatch.Stop(); + Console.WriteLine("Registered platform support modules in: " + stopwatch.Elapsed.TotalSeconds + "s."); + } + private static IEnumerable RegisterModulesFromLoadedAssemblies(Func> processAssembly) + { + if (processAssembly == null) + { + throw new ArgumentNullException("processAssembly"); + } + return AppDomain.CurrentDomain.GetAssemblies().Aggregate(new List(), delegate(List list, Assembly assembly) + { + try + { + IEnumerable enumerable = processAssembly(assembly); + if (enumerable != null && enumerable.Any()) + { + list.AddRange(enumerable); + } + } + catch (Exception ex) + { + Console.WriteLine("Error while registering modules from " + assembly.FullName + ": " + ex.Message); + } + return list; + }); + } + internal static IEnumerable RegisterPlatformSupportModulesFromAssembly(Assembly assembly) + { + return AssemblyHelper.FindImplementors(assembly); + } + private static IEnumerable RegisterEditorModulesFromAssembly(Assembly assembly) + { + return AssemblyHelper.FindImplementors(assembly); + } + internal static List GetJamTargets() + { + List list = new List(); + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + list.Add(current.JamTarget); + } + return list; + } + internal static IBuildPostprocessor GetBuildPostProcessor(string target) + { + if (target == null) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreateBuildPostprocessor(); + } + } + return null; + } + internal static IBuildPostprocessor GetBuildPostProcessor(BuildTarget target) + { + return ModuleManager.GetBuildPostProcessor(ModuleManager.GetTargetStringFromBuildTarget(target)); + } + internal static ISettingEditorExtension GetEditorSettingsExtension(string target) + { + if (string.IsNullOrEmpty(target)) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreateSettingsEditorExtension(); + } + } + return null; + } + internal static List GetPreferenceWindowExtensions() + { + List list = new List(); + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + IPreferenceWindowExtension preferenceWindowExtension = current.CreatePreferenceWindowExtension(); + if (preferenceWindowExtension != null) + { + list.Add(preferenceWindowExtension); + } + } + return list; + } + internal static string GetTargetStringFromBuildTarget(BuildTarget target) + { + switch (target) + { + case BuildTarget.iPhone: + return "iOS"; + case BuildTarget.PS3: + return "PS3"; + case BuildTarget.XBOX360: + return "Xbox360"; + case BuildTarget.Android: + return "Android"; + case BuildTarget.MetroPlayer: + return "Metro"; + case BuildTarget.WP8Player: + return "WP8"; + case BuildTarget.BB10: + return "BlackBerry"; + case BuildTarget.Tizen: + return "Tizen"; + case BuildTarget.PSP2: + return "PSP2"; + case BuildTarget.PS4: + return "PS4"; + case BuildTarget.PSM: + return "PSM"; + case BuildTarget.XboxOne: + return "XboxOne"; + case BuildTarget.SamsungTV: + return "SamsungTV"; + } + return null; + } + internal static string GetTargetStringFromBuildTargetGroup(BuildTargetGroup target) + { + switch (target) + { + case BuildTargetGroup.iPhone: + return "iOS"; + case BuildTargetGroup.PS3: + return "PS3"; + case BuildTargetGroup.XBOX360: + return "Xbox360"; + case BuildTargetGroup.Android: + return "Android"; + case BuildTargetGroup.Metro: + return "Metro"; + case BuildTargetGroup.WP8: + return "WP8"; + case BuildTargetGroup.BB10: + return "BlackBerry"; + case BuildTargetGroup.Tizen: + return "Tizen"; + case BuildTargetGroup.PSP2: + return "PSP2"; + case BuildTargetGroup.PS4: + return "PS4"; + case BuildTargetGroup.PSM: + return "PSM"; + case BuildTargetGroup.XboxOne: + return "XboxOne"; + case BuildTargetGroup.SamsungTV: + return "SamsungTV"; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs new file mode 100644 index 00000000..e7e886ed --- /dev/null +++ b/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; +using UnityEditorInternal; +namespace UnityEditor.OSXStandalone +{ + internal class OSXStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider + { + private readonly bool m_DevelopmentBuild; + public override bool emitNullChecks + { + get + { + return this.m_DevelopmentBuild; + } + } + public override bool enableStackTraces + { + get + { + return this.m_DevelopmentBuild; + } + } + public override string nativeLibraryFileName + { + get + { + return "UserAssembly.dylib"; + } + } + public OSXStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder, bool developmentBuild) : base(target, Path.Combine(dataFolder, "Libraries")) + { + this.m_DevelopmentBuild = developmentBuild; + } + public override INativeCompiler CreateNativeCompiler() + { + BuildTarget target = this.target; + if (target != BuildTarget.StandaloneOSXIntel) + { + throw new Exception("This OSX arch isn't supported yet. " + this.target); + } + ICompilerSettings settings = new ClangCompilerSettingsx86(); + return new ClangCompiler(settings); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs new file mode 100644 index 00000000..a0d2e9b1 --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs @@ -0,0 +1,13 @@ +using System; +using UnityEditorInternal; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreateAnimatorController : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + AnimatorController o = AnimatorController.CreateAnimatorControllerAtPath(pathName); + ProjectWindowUtil.ShowCreatedAsset(o); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateFolder.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateFolder.cs new file mode 100644 index 00000000..20193ffa --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateFolder.cs @@ -0,0 +1,15 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreateFolder : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + string guid = AssetDatabase.CreateFolder(Path.GetDirectoryName(pathName), Path.GetFileName(pathName)); + UnityEngine.Object o = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(UnityEngine.Object)); + ProjectWindowUtil.ShowCreatedAsset(o); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateNewAsset.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateNewAsset.cs new file mode 100644 index 00000000..65b1715a --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateNewAsset.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreateNewAsset : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + AssetDatabase.CreateAsset(EditorUtility.InstanceIDToObject(instanceId), AssetDatabase.GenerateUniqueAssetPath(pathName)); + ProjectWindowUtil.FrameObjectInProjectWindow(instanceId); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreatePrefab.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreatePrefab.cs new file mode 100644 index 00000000..dcf6e533 --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreatePrefab.cs @@ -0,0 +1,13 @@ +using System; +using UnityEngine; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreatePrefab : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + UnityEngine.Object o = PrefabUtility.CreateEmptyPrefab(pathName); + ProjectWindowUtil.ShowCreatedAsset(o); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateScriptAsset.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateScriptAsset.cs new file mode 100644 index 00000000..94aafb18 --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateScriptAsset.cs @@ -0,0 +1,13 @@ +using System; +using UnityEngine; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreateScriptAsset : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + UnityEngine.Object o = ProjectWindowUtil.CreateScriptAssetFromTemplate(pathName, resourceFile); + ProjectWindowUtil.ShowCreatedAsset(o); + } + } +} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/EndNameEditAction.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/EndNameEditAction.cs new file mode 100644 index 00000000..dc870cfa --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/EndNameEditAction.cs @@ -0,0 +1,17 @@ +using System; +using UnityEngine; +namespace UnityEditor.ProjectWindowCallback +{ + public abstract class EndNameEditAction : ScriptableObject + { + public virtual void OnEnable() + { + base.hideFlags = HideFlags.HideAndDontSave; + } + public abstract void Action(int instanceId, string pathName, string resourceFile); + public virtual void CleanUp() + { + UnityEngine.Object.DestroyImmediate(this); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs new file mode 100644 index 00000000..2fab9535 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.Utils; +using UnityEngineInternal; +namespace UnityEditor.Scripting.Compilers +{ + internal class BooCompiler : MonoScriptCompilerBase + { + public BooCompiler(MonoIsland island) : base(island) + { + } + protected override Program StartCompiler() + { + List list = new List + { + "-debug", + "-target:library", + "-out:" + this._island._output, + "-x-type-inference-rule-attribute:" + typeof(TypeInferenceRuleAttribute) + }; + list.Add("-debug"); + string[] references = this._island._references; + for (int i = 0; i < references.Length; i++) + { + string fileName = references[i]; + list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); + } + string[] defines = this._island._defines; + for (int j = 0; j < defines.Length; j++) + { + string str = defines[j]; + list.Add("-define:" + str); + } + string[] files = this._island._files; + for (int k = 0; k < files.Length; k++) + { + string fileName2 = files[k]; + list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); + } + string compiler = Path.Combine(base.GetProfileDirectory(), "booc.exe"); + return base.StartCompiler(this._island._target, compiler, list); + } + protected override CompilerOutputParserBase CreateOutputParser() + { + return new BooCompilerOutputParser(); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs new file mode 100644 index 00000000..506323bd --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs @@ -0,0 +1,17 @@ +using System; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class BooCompilerOutputParser : CompilerOutputParserBase + { + private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*[BU]C(?W|E)(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture); + protected override string GetErrorIdentifier() + { + return "E"; + } + protected override Regex GetOutputRegex() + { + return BooCompilerOutputParser.sCompilerOutput; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs new file mode 100644 index 00000000..aff96244 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs @@ -0,0 +1,33 @@ +using Boo.Lang.Compiler.Ast; +using Boo.Lang.Parser; +using System; +using System.Linq; +namespace UnityEditor.Scripting.Compilers +{ + internal class BooLanguage : SupportedLanguage + { + public override string GetExtensionICanCompile() + { + return "boo"; + } + public override string GetLanguageName() + { + return "Boo"; + } + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + { + return new BooCompiler(island); + } + public override string GetNamespace(string fileName) + { + try + { + return BooParser.ParseFile(fileName).get_Modules().First().get_Namespace().get_Name(); + } + catch + { + } + return base.GetNamespace(fileName); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs new file mode 100644 index 00000000..7bdda0d4 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs @@ -0,0 +1,91 @@ +using ICSharpCode.NRefactory; +using ICSharpCode.NRefactory.Ast; +using ICSharpCode.NRefactory.Visitors; +using System; +using System.Collections.Generic; +using System.IO; +namespace UnityEditor.Scripting.Compilers +{ + internal class CSharpLanguage : SupportedLanguage + { + private class VisitorData + { + public string TargetClassName; + public Stack CurrentNamespaces; + public string DiscoveredNamespace; + public VisitorData() + { + this.CurrentNamespaces = new Stack(); + } + } + private class NamespaceVisitor : AbstractAstVisitor + { + public override object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data) + { + CSharpLanguage.VisitorData visitorData = (CSharpLanguage.VisitorData)data; + visitorData.CurrentNamespaces.Push(namespaceDeclaration.Name); + namespaceDeclaration.AcceptChildren(this, visitorData); + visitorData.CurrentNamespaces.Pop(); + return null; + } + public override object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) + { + CSharpLanguage.VisitorData visitorData = (CSharpLanguage.VisitorData)data; + if (typeDeclaration.Name == visitorData.TargetClassName) + { + string text = string.Empty; + foreach (string current in visitorData.CurrentNamespaces) + { + if (text == string.Empty) + { + text = current; + } + else + { + text = current + "." + text; + } + } + visitorData.DiscoveredNamespace = text; + } + return null; + } + } + public override string GetExtensionICanCompile() + { + return "cs"; + } + public override string GetLanguageName() + { + return "CSharp"; + } + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + { + if (!buildingForEditor && targetPlatform.ToString().Contains("MetroPlayer") && (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCore || (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCorePartially && !island._output.Contains("Assembly-CSharp-firstpass.dll")))) + { + return new MicrosoftCSharpCompiler(island); + } + return new MonoCSharpCompiler(island); + } + public override string GetNamespace(string fileName) + { + using (IParser parser = ParserFactory.CreateParser(fileName)) + { + parser.Parse(); + try + { + CSharpLanguage.NamespaceVisitor visitor = new CSharpLanguage.NamespaceVisitor(); + CSharpLanguage.VisitorData visitorData = new CSharpLanguage.VisitorData + { + TargetClassName = Path.GetFileNameWithoutExtension(fileName) + }; + parser.CompilationUnit.AcceptVisitor(visitor, visitorData); + return (!string.IsNullOrEmpty(visitorData.DiscoveredNamespace)) ? visitorData.DiscoveredNamespace : string.Empty; + } + catch + { + } + } + return string.Empty; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs new file mode 100644 index 00000000..74928f32 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +namespace UnityEditor.Scripting.Compilers +{ + internal class Cil2AsOutputParser : UnityScriptCompilerOutputParser + { + [DebuggerHidden] + public override IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) + { + Cil2AsOutputParser.c__Iterator5 c__Iterator = new Cil2AsOutputParser.c__Iterator5(); + c__Iterator.errorOutput = errorOutput; + c__Iterator.<$>errorOutput = errorOutput; + Cil2AsOutputParser.c__Iterator5 expr_15 = c__Iterator; + expr_15.$PC = -2; + return expr_15; + } + private static CompilerMessage CompilerErrorFor(StringBuilder currentErrorBuffer) + { + return new CompilerMessage + { + message = currentErrorBuffer.ToString() + }; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CommandLineFormatter.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CommandLineFormatter.cs new file mode 100644 index 00000000..153c2062 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CommandLineFormatter.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor.Scripting.Compilers +{ + internal static class CommandLineFormatter + { + private static readonly Regex UnsafeCharsWindows = new Regex("[^A-Za-z0-9\\_\\-\\.\\:\\,\\/\\@\\\\]"); + private static readonly Regex UnescapeableChars = new Regex("[\\x00-\\x08\\x10-\\x1a\\x1c-\\x1f\\x7f\\xff]"); + private static readonly Regex Quotes = new Regex("\""); + public static string EscapeCharsQuote(string input) + { + if (input.IndexOf('\'') == -1) + { + return "'" + input + "'"; + } + if (input.IndexOf('"') == -1) + { + return "\"" + input + "\""; + } + return null; + } + public static string PrepareFileName(string input) + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + return CommandLineFormatter.EscapeCharsQuote(input); + } + return CommandLineFormatter.EscapeCharsWindows(input); + } + public static string EscapeCharsWindows(string input) + { + if (input.Length == 0) + { + return "\"\""; + } + if (CommandLineFormatter.UnescapeableChars.IsMatch(input)) + { + Debug.LogWarning("Cannot escape control characters in string"); + return "\"\""; + } + if (CommandLineFormatter.UnsafeCharsWindows.IsMatch(input)) + { + return "\"" + CommandLineFormatter.Quotes.Replace(input, "\"\"") + "\""; + } + return input; + } + internal static string GenerateResponseFile(IEnumerable arguments) + { + string uniqueTempPathInProject = FileUtil.GetUniqueTempPathInProject(); + using (StreamWriter streamWriter = new StreamWriter(uniqueTempPathInProject)) + { + foreach (string current in + from a in arguments + where a != null + select a) + { + streamWriter.WriteLine(current); + } + } + return uniqueTempPathInProject; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs new file mode 100644 index 00000000..90be8211 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal struct CompilerMessage + { + public string message; + public string file; + public int line; + public int column; + public CompilerMessageType type; + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessageType.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessageType.cs new file mode 100644 index 00000000..b2c7d01b --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessageType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal enum CompilerMessageType + { + Error, + Warning + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs new file mode 100644 index 00000000..8e62079f --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal abstract class CompilerOutputParserBase + { + protected static CompilerMessage CreateInternalCompilerErrorMessage(string[] compileroutput) + { + CompilerMessage result; + result.file = string.Empty; + result.message = string.Join("\n", compileroutput); + result.type = CompilerMessageType.Error; + result.line = 0; + result.column = 0; + result.message = "Internal compiler error. See the console log for more information. output was:" + result.message; + return result; + } + protected internal static CompilerMessage CreateCompilerMessageFromMatchedRegex(string line, Match m, string erroridentifier) + { + CompilerMessage result; + result.file = m.Groups["filename"].Value; + result.message = line; + result.line = int.Parse(m.Groups["line"].Value); + result.column = int.Parse(m.Groups["column"].Value); + result.type = ((!(m.Groups["type"].Value == erroridentifier)) ? CompilerMessageType.Warning : CompilerMessageType.Error); + return result; + } + public virtual IEnumerable Parse(string[] errorOutput, bool compilationHadFailure) + { + return this.Parse(errorOutput, new string[0], compilationHadFailure); + } + public virtual IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) + { + bool flag = false; + List list = new List(); + Regex outputRegex = this.GetOutputRegex(); + for (int i = 0; i < errorOutput.Length; i++) + { + string text = errorOutput[i]; + string input = (text.Length <= 1000) ? text : text.Substring(0, 100); + Match match = outputRegex.Match(input); + if (match.Success) + { + CompilerMessage item = CompilerOutputParserBase.CreateCompilerMessageFromMatchedRegex(text, match, this.GetErrorIdentifier()); + if (item.type == CompilerMessageType.Error) + { + flag = true; + } + list.Add(item); + } + } + if (compilationHadFailure && !flag) + { + list.Add(CompilerOutputParserBase.CreateInternalCompilerErrorMessage(errorOutput)); + } + return list; + } + protected abstract string GetErrorIdentifier(); + protected abstract Regex GetOutputRegex(); + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs new file mode 100644 index 00000000..55a2f179 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs @@ -0,0 +1,17 @@ +using System; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class FlexCompilerOutputParser : CompilerOutputParserBase + { + private static Regex sCompilerOutput = new Regex("(?.*)\\((?\\d+)\\)\\: col\\: (?\\d+) (?Warning|Error): (?.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + protected override Regex GetOutputRegex() + { + return FlexCompilerOutputParser.sCompilerOutput; + } + protected override string GetErrorIdentifier() + { + return "Error"; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs new file mode 100644 index 00000000..d71b6a6d --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +namespace UnityEditor.Scripting.Compilers +{ + internal class GendarmeOutputParser : UnityScriptCompilerOutputParser + { + public override IEnumerable Parse(string[] errorOutput, bool compilationHadFailure) + { + throw new ArgumentException("Gendarme Output Parser needs standard out"); + } + [DebuggerHidden] + public override IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) + { + GendarmeOutputParser.c__Iterator6 c__Iterator = new GendarmeOutputParser.c__Iterator6(); + c__Iterator.standardOutput = standardOutput; + c__Iterator.<$>standardOutput = standardOutput; + GendarmeOutputParser.c__Iterator6 expr_15 = c__Iterator; + expr_15.$PC = -2; + return expr_15; + } + private static CompilerMessage CompilerErrorFor(GendarmeRuleData gendarmeRuleData) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine(gendarmeRuleData.Problem); + stringBuilder.AppendLine(gendarmeRuleData.Details); + stringBuilder.AppendLine(string.IsNullOrEmpty(gendarmeRuleData.Location) ? string.Format("{0} at line : {1}", gendarmeRuleData.Source, gendarmeRuleData.Line) : gendarmeRuleData.Location); + string message = stringBuilder.ToString(); + return new CompilerMessage + { + message = message, + file = gendarmeRuleData.File, + line = gendarmeRuleData.Line, + column = 1 + }; + } + private static GendarmeRuleData GetGendarmeRuleDataFor(IList output, int index) + { + GendarmeRuleData gendarmeRuleData = new GendarmeRuleData(); + for (int i = index; i < output.Count; i++) + { + string text = output[i]; + if (text.StartsWith("Problem:")) + { + gendarmeRuleData.Problem = text.Substring(text.LastIndexOf("Problem:", StringComparison.Ordinal) + "Problem:".Length); + } + else + { + if (text.StartsWith("* Details")) + { + gendarmeRuleData.Details = text; + } + else + { + if (text.StartsWith("* Source")) + { + gendarmeRuleData.IsAssemblyError = false; + gendarmeRuleData.Source = text; + gendarmeRuleData.Line = GendarmeOutputParser.GetLineNumberFrom(text); + gendarmeRuleData.File = GendarmeOutputParser.GetFileNameFrome(text); + } + else + { + if (text.StartsWith("* Severity")) + { + gendarmeRuleData.Severity = text; + } + else + { + if (text.StartsWith("* Location")) + { + gendarmeRuleData.IsAssemblyError = true; + gendarmeRuleData.Location = text; + } + else + { + if (!text.StartsWith("* Target")) + { + gendarmeRuleData.LastIndex = i; + break; + } + gendarmeRuleData.Target = text; + } + } + } + } + } + } + return gendarmeRuleData; + } + private static string GetFileNameFrome(string currentLine) + { + int num = currentLine.LastIndexOf("* Source:") + "* Source:".Length; + int num2 = currentLine.IndexOf("("); + if (num != -1 && num2 != -1) + { + return currentLine.Substring(num, num2 - num).Trim(); + } + return string.Empty; + } + private static int GetLineNumberFrom(string currentLine) + { + int num = currentLine.IndexOf("(") + 2; + int num2 = currentLine.IndexOf(")"); + if (num != -1 && num2 != -1) + { + return int.Parse(currentLine.Substring(num, num2 - num)); + } + return 0; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeRuleData.cs b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeRuleData.cs new file mode 100644 index 00000000..4a79f36e --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeRuleData.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal class GendarmeRuleData + { + public int LastIndex; + public int Line; + public string File = string.Empty; + public string Problem; + public string Details; + public string Severity; + public string Source; + public string Location; + public string Target; + public bool IsAssemblyError; + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/Il2CppOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/Il2CppOutputParser.cs new file mode 100644 index 00000000..f1c33173 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/Il2CppOutputParser.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class Il2CppOutputParser : CompilerOutputParserBase + { + private const string _errorIdentifier = "IL2CPP error"; + private static readonly Regex sErrorRegexWithSourceInformation = new Regex("\\s*(?.*) in (?.*):(?\\d+)"); + public override IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) + { + List list = new List(); + for (int i = 0; i < standardOutput.Length; i++) + { + string text = standardOutput[i]; + if (text.StartsWith("IL2CPP error")) + { + string text2 = string.Empty; + int num = 0; + StringBuilder stringBuilder = new StringBuilder(); + Match match = Il2CppOutputParser.sErrorRegexWithSourceInformation.Match(text); + if (match.Success) + { + text2 = match.Groups["filename"].Value; + num = int.Parse(match.Groups["line"].Value); + stringBuilder.AppendFormat("{0} in {1}:{2}", match.Groups["message"].Value, Path.GetFileName(text2), num); + } + else + { + stringBuilder.Append(text); + } + if (i + 1 < standardOutput.Length && standardOutput[i + 1].StartsWith("Additional information:")) + { + stringBuilder.AppendFormat("{0}{1}", Environment.NewLine, standardOutput[i + 1]); + i++; + } + list.Add(new CompilerMessage + { + file = text2, + line = num, + message = stringBuilder.ToString() + }); + } + } + return list; + } + protected override string GetErrorIdentifier() + { + return "IL2CPP error"; + } + protected override Regex GetOutputRegex() + { + return Il2CppOutputParser.sErrorRegexWithSourceInformation; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs new file mode 100644 index 00000000..79127f83 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs @@ -0,0 +1,261 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using UnityEditor.Utils; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Scripting.Compilers +{ + internal class MicrosoftCSharpCompiler : ScriptCompilerBase + { + internal static string WindowsDirectory + { + get + { + return Environment.GetEnvironmentVariable("windir"); + } + } + internal static string ProgramFilesDirectory + { + get + { + string environmentVariable = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); + string result; + if (Directory.Exists(environmentVariable)) + { + result = environmentVariable; + } + else + { + UnityEngine.Debug.Log("Env variables ProgramFiles(x86) & ProgramFiles didn't exist, trying hard coded paths"); + string fullPath = Path.GetFullPath(MicrosoftCSharpCompiler.WindowsDirectory + "\\..\\.."); + string text = fullPath + "Program Files (x86)"; + string text2 = fullPath + "Program Files"; + if (Directory.Exists(text)) + { + result = text; + } + else + { + if (!Directory.Exists(text2)) + { + throw new Exception(string.Concat(new string[] + { + "Path '", + text, + "' or '", + text2, + "' doesn't exist." + })); + } + result = text2; + } + } + return result; + } + } + public MicrosoftCSharpCompiler(MonoIsland island) : base(island) + { + } + internal static string GetNETCoreFrameworkReferencesDirectory(MetroSDK metroSDK) + { + switch (metroSDK) + { + case MetroSDK.SDK80: + return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\.NETCore\\v4.5"; + case MetroSDK.SDK81: + return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\.NETCore\\v4.5.1"; + case MetroSDK.PhoneSDK81: + return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\WindowsPhoneApp\\v8.1"; + default: + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + } + } + private string[] GetNETMetroAssemblies(MetroSDK metroSDK) + { + return Directory.GetFiles(MicrosoftCSharpCompiler.GetNETCoreFrameworkReferencesDirectory(metroSDK), "*.dll"); + } + private string GetNetMetroAssemblyInfoWindows80() + { + return string.Join("\r\n", new string[] + { + "using System;", + " using System.Reflection;", + "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\".NETCore,Version=v4.5\", FrameworkDisplayName = \".NET for Windows Store apps\")]" + }); + } + private string GetNetMetroAssemblyInfoWindows81() + { + return string.Join("\r\n", new string[] + { + "using System;", + " using System.Reflection;", + "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\".NETCore,Version=v4.5.1\", FrameworkDisplayName = \".NET for Windows Store apps (Windows 8.1)\")]" + }); + } + private string GetNetMetroAssemblyInfoWindowsPhone81() + { + return string.Join("\r\n", new string[] + { + "using System;", + " using System.Reflection;", + "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\"WindowsPhoneApp,Version=v8.1\", FrameworkDisplayName = \"Windows Phone 8.1\")]" + }); + } + private void FillNETCoreCompilerOptions(MetroSDK metroSDK, List arguments, ref string argsPrefix) + { + argsPrefix = "/noconfig "; + arguments.Add("/nostdlib+"); + arguments.Add("/define:NETFX_CORE"); + string platformAssemblyPath = MicrosoftCSharpCompiler.GetPlatformAssemblyPath(metroSDK); + string arg; + switch (metroSDK) + { + case MetroSDK.SDK80: + arg = "8.0"; + break; + case MetroSDK.SDK81: + arg = "8.1"; + break; + case MetroSDK.PhoneSDK81: + arg = "Phone 8.1"; + break; + default: + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + } + if (!File.Exists(platformAssemblyPath)) + { + throw new Exception(string.Format("'{0}' not found, do you have Windows {1} SDK installed?", platformAssemblyPath, arg)); + } + arguments.Add("/reference:\"" + platformAssemblyPath + "\""); + string[] nETMetroAssemblies = this.GetNETMetroAssemblies(metroSDK); + for (int i = 0; i < nETMetroAssemblies.Length; i++) + { + string str = nETMetroAssemblies[i]; + arguments.Add("/reference:\"" + str + "\""); + } + string text; + string contents; + switch (metroSDK) + { + case MetroSDK.SDK80: + text = Path.Combine(Path.GetTempPath(), ".NETCore,Version=v4.5.AssemblyAttributes.cs"); + contents = this.GetNetMetroAssemblyInfoWindows80(); + break; + case MetroSDK.SDK81: + text = Path.Combine(Path.GetTempPath(), ".NETCore,Version=v4.5.1.AssemblyAttributes.cs"); + contents = this.GetNetMetroAssemblyInfoWindows81(); + break; + case MetroSDK.PhoneSDK81: + text = Path.Combine(Path.GetTempPath(), "WindowsPhoneApp,Version=v8.1.AssemblyAttributes.cs"); + contents = this.GetNetMetroAssemblyInfoWindowsPhone81(); + break; + default: + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + } + if (File.Exists(text)) + { + File.Delete(text); + } + File.WriteAllText(text, contents); + arguments.Add(text); + string text2 = Path.Combine(BuildPipeline.GetPlaybackEngineDirectory(this._island._target, BuildOptions.None), "Managed\\WinRTLegacy.dll"); + arguments.Add("/reference:\"" + text2.Replace('/', '\\') + "\""); + } + private Program StartCompilerImpl(List arguments, string argsPrefix) + { + string[] references = this._island._references; + for (int i = 0; i < references.Length; i++) + { + string fileName = references[i]; + arguments.Add("/reference:" + ScriptCompilerBase.PrepareFileName(fileName)); + } + string[] defines = this._island._defines; + for (int j = 0; j < defines.Length; j++) + { + string str = defines[j]; + arguments.Add("/define:" + str); + } + string[] files = this._island._files; + for (int k = 0; k < files.Length; k++) + { + string fileName2 = files[k]; + arguments.Add(ScriptCompilerBase.PrepareFileName(fileName2).Replace('/', '\\')); + } + string text = Path.Combine(MicrosoftCSharpCompiler.WindowsDirectory, "Microsoft.NET\\Framework\\v4.0.30319\\Csc.exe"); + if (!File.Exists(text)) + { + throw new Exception("'" + text + "' not found, either .NET 4.5 is not installed or your OS is not Windows 8/8.1."); + } + base.AddCustomResponseFileIfPresent(arguments, "csc.rsp"); + string str2 = CommandLineFormatter.GenerateResponseFile(arguments); + ProcessStartInfo si = new ProcessStartInfo + { + Arguments = argsPrefix + "@" + str2, + FileName = text, + CreateNoWindow = true + }; + Program program = new Program(si); + program.Start(); + return program; + } + protected override Program StartCompiler() + { + string str = ScriptCompilerBase.PrepareFileName(this._island._output); + List list = new List + { + "/target:library", + "/nowarn:0169", + "/out:" + str + }; + list.InsertRange(0, new string[] + { + "/debug:pdbonly", + "/optimize+" + }); + string empty = string.Empty; + if (base.CompilingForMetro() && (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCore || PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCorePartially)) + { + this.FillNETCoreCompilerOptions(EditorUserBuildSettings.metroSDK, list, ref empty); + } + return this.StartCompilerImpl(list, empty); + } + protected override string[] GetStreamContainingCompilerMessages() + { + return base.GetStandardOutput(); + } + protected override CompilerOutputParserBase CreateOutputParser() + { + return new MicrosoftCSharpCompilerOutputParser(); + } + protected static string GetPlatformAssemblyPath(MetroSDK metroSDK) + { + string text; + string path; + switch (metroSDK) + { + case MetroSDK.SDK80: + text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0", "InstallationFolder"); + path = "Windows Kits\\8.0"; + break; + case MetroSDK.SDK81: + text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.1", "InstallationFolder"); + path = "Windows Kits\\8.1"; + break; + case MetroSDK.PhoneSDK81: + text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\WindowsPhoneApp\\v8.1", "InstallationFolder"); + path = "Windows Phone Kits\\8.1"; + break; + default: + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + } + if (text == null) + { + string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + text = Path.Combine(folderPath, path); + } + return Path.Combine(text, "References\\CommonConfiguration\\Neutral\\Windows.winmd"); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompilerOutputParser.cs new file mode 100644 index 00000000..7e7e31ca --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompilerOutputParser.cs @@ -0,0 +1,17 @@ +using System; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class MicrosoftCSharpCompilerOutputParser : CompilerOutputParserBase + { + private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*(?warning|error)\\s*(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + protected override Regex GetOutputRegex() + { + return MicrosoftCSharpCompilerOutputParser.sCompilerOutput; + } + protected override string GetErrorIdentifier() + { + return "error"; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs new file mode 100644 index 00000000..2797f9cf --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using UnityEditor.Utils; +namespace UnityEditor.Scripting.Compilers +{ + internal class MonoCSharpCompiler : MonoScriptCompilerBase + { + public MonoCSharpCompiler(MonoIsland island) : base(island) + { + } + protected override Program StartCompiler() + { + List list = new List + { + "-debug", + "-target:library", + "-nowarn:0169", + "-out:" + ScriptCompilerBase.PrepareFileName(this._island._output) + }; + string[] references = this._island._references; + for (int i = 0; i < references.Length; i++) + { + string fileName = references[i]; + list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); + } + string[] defines = this._island._defines; + for (int j = 0; j < defines.Length; j++) + { + string str = defines[j]; + list.Add("-define:" + str); + } + string[] files = this._island._files; + for (int k = 0; k < files.Length; k++) + { + string fileName2 = files[k]; + list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); + } + string[] additionalReferences = this.GetAdditionalReferences(); + for (int l = 0; l < additionalReferences.Length; l++) + { + string path = additionalReferences[l]; + string text = Path.Combine(base.GetProfileDirectory(), path); + if (File.Exists(text)) + { + list.Add("-r:" + ScriptCompilerBase.PrepareFileName(text)); + } + } + return base.StartCompiler(this._island._target, this.GetCompilerPath(list), list); + } + private string[] GetAdditionalReferences() + { + return new string[] + { + "System.Runtime.Serialization.dll", + "System.Xml.Linq.dll" + }; + } + private string GetCompilerPath(List arguments) + { + string profileDirectory = base.GetProfileDirectory(); + string[] array = new string[] + { + "smcs", + "gmcs", + "mcs" + }; + for (int i = 0; i < array.Length; i++) + { + string str = array[i]; + string text = Path.Combine(profileDirectory, str + ".exe"); + if (File.Exists(text)) + { + return text; + } + } + throw new ApplicationException("Unable to find csharp compiler in " + profileDirectory); + } + protected override CompilerOutputParserBase CreateOutputParser() + { + return new MonoCSharpCompilerOutputParser(); + } + public static string[] Compile(string[] sources, string[] references, string[] defines, string outputFile) + { + MonoIsland island = new MonoIsland(BuildTarget.StandaloneWindows, "unity", sources, references, defines, outputFile); + string[] result; + using (MonoCSharpCompiler monoCSharpCompiler = new MonoCSharpCompiler(island)) + { + monoCSharpCompiler.BeginCompiling(); + while (!monoCSharpCompiler.Poll()) + { + Thread.Sleep(50); + } + result = ( + from cm in monoCSharpCompiler.GetCompilerMessages() + select cm.message).ToArray(); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs new file mode 100644 index 00000000..c6ee3ab1 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs @@ -0,0 +1,17 @@ +using System; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class MonoCSharpCompilerOutputParser : CompilerOutputParserBase + { + private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*(?warning|error)\\s*(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + protected override Regex GetOutputRegex() + { + return MonoCSharpCompilerOutputParser.sCompilerOutput; + } + protected override string GetErrorIdentifier() + { + return "error"; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs new file mode 100644 index 00000000..a0cb2458 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.Utils; +namespace UnityEditor.Scripting.Compilers +{ + internal abstract class MonoScriptCompilerBase : ScriptCompilerBase + { + protected MonoScriptCompilerBase(MonoIsland island) : base(island) + { + } + protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments) + { + return this.StartCompiler(target, compiler, arguments, true); + } + protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments, bool setMonoEnvironmentVariables) + { + base.AddCustomResponseFileIfPresent(arguments, Path.GetFileNameWithoutExtension(compiler) + ".rsp"); + string str = CommandLineFormatter.GenerateResponseFile(arguments); + string monoInstallation = MonoInstallationFinder.GetMonoInstallation(); + ManagedProgram managedProgram = new ManagedProgram(monoInstallation, this._island._classlib_profile, compiler, " @" + str, setMonoEnvironmentVariables); + managedProgram.Start(); + return managedProgram; + } + protected string GetProfileDirectory() + { + return MonoInstallationFinder.GetProfileDirectory(this._island._target, this._island._classlib_profile); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs new file mode 100644 index 00000000..b3089c12 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditor.Scripting.Compilers +{ + internal abstract class ScriptCompilerBase : IDisposable + { + private Program process; + private string _responseFile; + protected MonoIsland _island; + protected ScriptCompilerBase(MonoIsland island) + { + this._island = island; + } + protected abstract Program StartCompiler(); + protected abstract CompilerOutputParserBase CreateOutputParser(); + protected string[] GetErrorOutput() + { + return this.process.GetErrorOutput(); + } + protected string[] GetStandardOutput() + { + return this.process.GetStandardOutput(); + } + protected bool CompilingForMetro() + { + return this._island._target == BuildTarget.MetroPlayer; + } + public void BeginCompiling() + { + if (this.process != null) + { + throw new InvalidOperationException("Compilation has already begun!"); + } + this.process = this.StartCompiler(); + } + public virtual void Dispose() + { + if (this.process != null) + { + this.process.Dispose(); + this.process = null; + } + if (this._responseFile != null) + { + File.Delete(this._responseFile); + this._responseFile = null; + } + } + public virtual bool Poll() + { + return this.process == null || this.process.HasExited; + } + protected void AddCustomResponseFileIfPresent(List arguments, string responseFileName) + { + string text = Path.Combine("Assets", responseFileName); + if (!File.Exists(text)) + { + return; + } + arguments.Add("@" + text); + } + protected string GenerateResponseFile(List arguments) + { + this._responseFile = CommandLineFormatter.GenerateResponseFile(arguments); + return this._responseFile; + } + protected static string PrepareFileName(string fileName) + { + return CommandLineFormatter.PrepareFileName(fileName); + } + public virtual CompilerMessage[] GetCompilerMessages() + { + if (!this.Poll()) + { + Debug.LogWarning("Compile process is not finished yet. This should not happen."); + } + this.DumpStreamOutputToLog(); + return this.CreateOutputParser().Parse(this.GetStreamContainingCompilerMessages(), this.CompilationHadFailure()).ToArray(); + } + protected bool CompilationHadFailure() + { + return this.process.ExitCode != 0; + } + protected virtual string[] GetStreamContainingCompilerMessages() + { + return this.GetErrorOutput(); + } + private void DumpStreamOutputToLog() + { + bool flag = this.CompilationHadFailure(); + string[] errorOutput = this.GetErrorOutput(); + if (flag || errorOutput.Length != 0) + { + Console.WriteLine(string.Empty); + Console.WriteLine("-----Compiler Commandline Arguments:"); + this.process.LogProcessStartInfo(); + string[] standardOutput = this.GetStandardOutput(); + Console.WriteLine(string.Concat(new object[] + { + "-----CompilerOutput:-stdout--exitcode: ", + this.process.ExitCode, + "--compilationhadfailure: ", + flag, + "--outfile: ", + this._island._output + })); + string[] array = standardOutput; + for (int i = 0; i < array.Length; i++) + { + string value = array[i]; + Console.WriteLine(value); + } + Console.WriteLine("-----CompilerOutput:-stderr----------"); + string[] array2 = errorOutput; + for (int j = 0; j < array2.Length; j++) + { + string value2 = array2[j]; + Console.WriteLine(value2); + } + Console.WriteLine("-----EndCompilerOutput---------------"); + } + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs new file mode 100644 index 00000000..b314915c --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal abstract class SupportedLanguage + { + public abstract string GetExtensionICanCompile(); + public abstract string GetLanguageName(); + public abstract ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform); + public virtual string GetNamespace(string fileName) + { + return string.Empty; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs new file mode 100644 index 00000000..40db7af2 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using UnityEditor.Utils; +using UnityEngineInternal; +namespace UnityEditor.Scripting.Compilers +{ + internal class UnityScriptCompiler : MonoScriptCompilerBase + { + private static readonly Regex UnityEditorPattern = new Regex("UnityEditor\\.dll$", RegexOptions.ExplicitCapture); + public UnityScriptCompiler(MonoIsland island) : base(island) + { + } + protected override CompilerOutputParserBase CreateOutputParser() + { + return new UnityScriptCompilerOutputParser(); + } + protected override Program StartCompiler() + { + List list = new List + { + "-debug", + "-target:library", + "-i:UnityEngine", + "-i:System.Collections", + "-base:UnityEngine.MonoBehaviour", + "-nowarn:BCW0016", + "-nowarn:BCW0003", + "-method:Main", + "-out:" + this._island._output, + "-x-type-inference-rule-attribute:" + typeof(TypeInferenceRuleAttribute) + }; + if (this.StrictBuildTarget()) + { + list.Add("-pragmas:strict,downcast"); + } + string[] defines = this._island._defines; + for (int i = 0; i < defines.Length; i++) + { + string str = defines[i]; + list.Add("-define:" + str); + } + string[] references = this._island._references; + for (int j = 0; j < references.Length; j++) + { + string fileName = references[j]; + list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); + } + bool flag = Array.Exists(this._island._references, new Predicate(UnityScriptCompiler.UnityEditorPattern.IsMatch)); + if (flag) + { + list.Add("-i:UnityEditor"); + } + else + { + if (!BuildPipeline.IsUnityScriptEvalSupported(this._island._target)) + { + list.Add(string.Format("-disable-eval:eval is not supported on the current build target ({0}).", this._island._target)); + } + } + string[] files = this._island._files; + for (int k = 0; k < files.Length; k++) + { + string fileName2 = files[k]; + list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); + } + string compiler = Path.Combine(base.GetProfileDirectory(), "us.exe"); + return base.StartCompiler(this._island._target, compiler, list); + } + private bool StrictBuildTarget() + { + return Array.IndexOf(this._island._defines, "ENABLE_DUCK_TYPING") == -1; + } + protected override string[] GetStreamContainingCompilerMessages() + { + return base.GetStandardOutput(); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompilerOutputParser.cs new file mode 100644 index 00000000..c7514303 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompilerOutputParser.cs @@ -0,0 +1,17 @@ +using System; +using System.Text.RegularExpressions; +namespace UnityEditor.Scripting.Compilers +{ + internal class UnityScriptCompilerOutputParser : CompilerOutputParserBase + { + private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*[BU]C(?W|E)(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture); + protected override string GetErrorIdentifier() + { + return "E"; + } + protected override Regex GetOutputRegex() + { + return UnityScriptCompilerOutputParser.sCompilerOutput; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs new file mode 100644 index 00000000..198c3efc --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal class UnityScriptLanguage : SupportedLanguage + { + public override string GetExtensionICanCompile() + { + return "js"; + } + public override string GetLanguageName() + { + return "UnityScript"; + } + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + { + return new UnityScriptCompiler(island); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs b/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs new file mode 100644 index 00000000..b27effed --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor.Utils; +namespace UnityEditor.Scripting.Serialization +{ + internal static class Weaver + { + public static bool ShouldWeave(string name) + { + return !name.Contains("Boo.") && !name.Contains("Mono.") && !name.Contains("System") && name.EndsWith(".dll"); + } + public static void WeaveAssembliesInFolder(string folder, string playerPackage) + { + string unityEngine = Path.Combine(folder, "UnityEngine.dll"); + foreach (string current in + from f in Directory.GetFiles(folder) + where Weaver.ShouldWeave(Path.GetFileName(f)) + select f) + { + Weaver.WeaveInto(current, current, unityEngine, playerPackage); + } + } + public static void WeaveInto(string assemblyPath, string destPath, string unityEngine, string playerPackage) + { + string arguments = Weaver.CommandLineArgsFor(assemblyPath, destPath, unityEngine); + using (ManagedProgram managedProgram = Weaver.SerializationWeaverProgramWith(arguments, playerPackage)) + { + try + { + managedProgram.Start(); + } + catch + { + managedProgram.LogProcessStartInfo(); + throw new Exception("Could not start SerializationWeaver.exe"); + } + managedProgram.WaitForExit(); + if (managedProgram.ExitCode != 0) + { + throw new Exception("Failed running SerializationWeaver. output was: " + managedProgram.GetAllOutput()); + } + } + } + private static string CommandLineArgsFor(string assemblyPath, string destPath, string unityEngine) + { + return string.Concat(new string[] + { + assemblyPath, + " ", + Path.GetDirectoryName(destPath), + " -unity-engine=\"", + unityEngine, + "\"" + }); + } + private static ManagedProgram SerializationWeaverProgramWith(string arguments, string playerPackage) + { + return Weaver.ManagedProgramFor(playerPackage + "/SerializationWeaver/SerializationWeaver.exe", arguments); + } + private static ManagedProgram ManagedProgramFor(string exe, string arguments) + { + return new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, arguments); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/ManagedProgram.cs b/UnityEditor/UnityEditor.Scripting/ManagedProgram.cs new file mode 100644 index 00000000..9c83e012 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/ManagedProgram.cs @@ -0,0 +1,64 @@ +using System; +using System.Diagnostics; +using System.IO; +using UnityEditor.Scripting.Compilers; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditor.Scripting +{ + internal class ManagedProgram : Program + { + public ManagedProgram(string monodistribution, string profile, string executable, string arguments) : this(monodistribution, profile, executable, arguments, true) + { + } + public ManagedProgram(string monodistribution, string profile, string executable, string arguments, bool setMonoEnvironmentVariables) + { + string text = ManagedProgram.PathCombine(new string[] + { + monodistribution, + "bin", + "mono" + }); + string value = ManagedProgram.PathCombine(new string[] + { + monodistribution, + "lib", + "mono", + profile + }); + if (Application.platform == RuntimePlatform.WindowsEditor) + { + text = CommandLineFormatter.PrepareFileName(text + ".exe"); + } + ProcessStartInfo processStartInfo = new ProcessStartInfo + { + Arguments = CommandLineFormatter.PrepareFileName(executable) + " " + arguments, + CreateNoWindow = true, + FileName = text, + RedirectStandardError = true, + RedirectStandardOutput = true, + WorkingDirectory = Application.dataPath + "/..", + UseShellExecute = false + }; + if (setMonoEnvironmentVariables) + { + processStartInfo.EnvironmentVariables["MONO_PATH"] = value; + processStartInfo.EnvironmentVariables["MONO_CFG_DIR"] = ManagedProgram.PathCombine(new string[] + { + monodistribution, + "etc" + }); + } + this._process.StartInfo = processStartInfo; + } + private static string PathCombine(params string[] parts) + { + string text = parts[0]; + for (int i = 1; i < parts.Length; i++) + { + text = Path.Combine(text, parts[i]); + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/MonoIsland.cs b/UnityEditor/UnityEditor.Scripting/MonoIsland.cs new file mode 100644 index 00000000..be85a31d --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/MonoIsland.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEditor.Scripting +{ + internal struct MonoIsland + { + public readonly BuildTarget _target; + public readonly string _classlib_profile; + public readonly string[] _files; + public readonly string[] _references; + public readonly string[] _defines; + public readonly string _output; + public MonoIsland(BuildTarget target, string classlib_profile, string[] files, string[] references, string[] defines, string output) + { + this._target = target; + this._classlib_profile = classlib_profile; + this._files = files; + this._references = references; + this._defines = defines; + this._output = output; + } + public string GetExtensionOfSourceFiles() + { + return ScriptCompilers.GetExtensionOfSourceFile(this._files[0]); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs b/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs new file mode 100644 index 00000000..1a8495c5 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Scripting +{ + internal class PragmaFixing30 + { + private static void FixJavaScriptPragmas() + { + string[] array = PragmaFixing30.CollectBadFiles(); + if (array.Length == 0) + { + return; + } + if (!InternalEditorUtility.inBatchMode) + { + PragmaFixingWindow.ShowWindow(array); + } + else + { + PragmaFixing30.FixFiles(array); + } + } + public static void FixFiles(string[] filesToFix) + { + for (int i = 0; i < filesToFix.Length; i++) + { + string text = filesToFix[i]; + try + { + PragmaFixing30.FixPragmasInFile(text); + } + catch (Exception ex) + { + UnityEngine.Debug.LogError("Failed to fix pragmas in file '" + text + "'.\n" + ex.Message); + } + } + } + private static bool FileNeedsPragmaFixing(string fileName) + { + return PragmaFixing30.CheckOrFixPragmas(fileName, true); + } + private static void FixPragmasInFile(string fileName) + { + PragmaFixing30.CheckOrFixPragmas(fileName, false); + } + private static bool CheckOrFixPragmas(string fileName, bool onlyCheck) + { + string text = File.ReadAllText(fileName); + StringBuilder sb = new StringBuilder(text); + PragmaFixing30.LooseComments(sb); + Match match = PragmaFixing30.PragmaMatch(sb, "strict"); + if (!match.Success) + { + return false; + } + bool success = PragmaFixing30.PragmaMatch(sb, "downcast").Success; + bool success2 = PragmaFixing30.PragmaMatch(sb, "implicit").Success; + if (success && success2) + { + return false; + } + if (!onlyCheck) + { + PragmaFixing30.DoFixPragmasInFile(fileName, text, match.Index + match.Length, success, success2); + } + return true; + } + private static void DoFixPragmasInFile(string fileName, string oldText, int fixPos, bool hasDowncast, bool hasImplicit) + { + string text = string.Empty; + string str = (!PragmaFixing30.HasWinLineEndings(oldText)) ? "\n" : "\r\n"; + if (!hasImplicit) + { + text = text + str + "#pragma implicit"; + } + if (!hasDowncast) + { + text = text + str + "#pragma downcast"; + } + File.WriteAllText(fileName, oldText.Insert(fixPos, text)); + } + private static bool HasWinLineEndings(string text) + { + return text.IndexOf("\r\n") != -1; + } + [DebuggerHidden] + private static IEnumerable SearchRecursive(string dir, string mask) + { + PragmaFixing30.c__Iterator4 c__Iterator = new PragmaFixing30.c__Iterator4(); + c__Iterator.dir = dir; + c__Iterator.mask = mask; + c__Iterator.<$>dir = dir; + c__Iterator.<$>mask = mask; + PragmaFixing30.c__Iterator4 expr_23 = c__Iterator; + expr_23.$PC = -2; + return expr_23; + } + private static void LooseComments(StringBuilder sb) + { + Regex regex = new Regex("//"); + foreach (Match match in regex.Matches(sb.ToString())) + { + int index = match.Index; + while (index < sb.Length && sb[index] != '\n' && sb[index] != '\r') + { + sb[index++] = ' '; + } + } + } + private static Match PragmaMatch(StringBuilder sb, string pragma) + { + return new Regex("#\\s*pragma\\s*" + pragma).Match(sb.ToString()); + } + private static string[] CollectBadFiles() + { + List list = new List(); + foreach (string current in PragmaFixing30.SearchRecursive(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "*.js")) + { + try + { + if (PragmaFixing30.FileNeedsPragmaFixing(current)) + { + list.Add(current); + } + } + catch (Exception ex) + { + UnityEngine.Debug.LogError("Failed to fix pragmas in file '" + current + "'.\n" + ex.Message); + } + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs b/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs new file mode 100644 index 00000000..e60ea62e --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Scripting.Compilers; +namespace UnityEditor.Scripting +{ + internal static class ScriptCompilers + { + private static List _supportedLanguages; + static ScriptCompilers() + { + ScriptCompilers._supportedLanguages = new List(); + foreach (Type current in new List + { + typeof(CSharpLanguage), + typeof(BooLanguage), + typeof(UnityScriptLanguage) + }) + { + ScriptCompilers._supportedLanguages.Add((SupportedLanguage)Activator.CreateInstance(current)); + } + } + internal static SupportedLanguageStruct[] GetSupportedLanguageStructs() + { + return ( + from lang in ScriptCompilers._supportedLanguages + select new SupportedLanguageStruct + { + extension = lang.GetExtensionICanCompile(), + languageName = lang.GetLanguageName() + }).ToArray(); + } + internal static string GetNamespace(string file) + { + if (string.IsNullOrEmpty(file)) + { + throw new ArgumentException("Invalid file"); + } + string extensionOfSourceFile = ScriptCompilers.GetExtensionOfSourceFile(file); + foreach (SupportedLanguage current in ScriptCompilers._supportedLanguages) + { + if (current.GetExtensionICanCompile() == extensionOfSourceFile) + { + return current.GetNamespace(file); + } + } + throw new ApplicationException("Unable to find a suitable compiler"); + } + internal static ScriptCompilerBase CreateCompilerInstance(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + { + if (island._files.Length == 0) + { + throw new ArgumentException("Cannot compile MonoIsland with no files"); + } + foreach (SupportedLanguage current in ScriptCompilers._supportedLanguages) + { + if (current.GetExtensionICanCompile() == island.GetExtensionOfSourceFiles()) + { + return current.CreateCompiler(island, buildingForEditor, targetPlatform); + } + } + throw new ApplicationException("Unable to find a suitable compiler"); + } + public static string GetExtensionOfSourceFile(string file) + { + string text = Path.GetExtension(file).ToLower(); + return text.Substring(1); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/SupportedLanguageStruct.cs b/UnityEditor/UnityEditor.Scripting/SupportedLanguageStruct.cs new file mode 100644 index 00000000..b518503f --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/SupportedLanguageStruct.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Scripting +{ + internal struct SupportedLanguageStruct + { + public string extension; + public string languageName; + } +} diff --git a/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs b/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs new file mode 100644 index 00000000..e7af954b --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; +namespace UnityEditor.Sprites +{ + public struct AtlasSettings + { + public TextureFormat format; + public TextureUsageMode usageMode; + public ColorSpace colorSpace; + public int compressionQuality; + public FilterMode filterMode; + public int maxWidth; + public int maxHeight; + public uint paddingPower; + public int anisoLevel; + public bool generateMipMaps; + } +} diff --git a/UnityEditor/UnityEditor.Sprites/DataUtility.cs b/UnityEditor/UnityEditor.Sprites/DataUtility.cs new file mode 100644 index 00000000..4301e5cb --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/DataUtility.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Sprites +{ + public sealed class DataUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetSpriteTexture(Sprite sprite, bool getAtlasData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector2[] GetSpriteMesh(Sprite sprite, bool getAtlasData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector2[] GetSpriteUVs(Sprite sprite, bool getAtlasData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ushort[] GetSpriteIndices(Sprite sprite, bool getAtlasData); + internal static void GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) + { + DataUtility.INTERNAL_CALL_GenerateOutline(texture, ref rect, detail, alphaTolerance, holeDetection, out paths); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_GenerateOutline(Texture2D texture, ref Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void GenerateOutlineFromSprite(Sprite sprite, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); + } +} diff --git a/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs b/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs new file mode 100644 index 00000000..6570f3a9 --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor.Sprites +{ + internal class DefaultPackerPolicy : IPackerPolicy + { + protected class Entry + { + public Sprite sprite; + public AtlasSettings settings; + public string atlasName; + public SpritePackingMode packingMode; + public int anisoLevel; + } + private const uint kDefaultPaddingPower = 2u; + protected virtual string TagPrefix + { + get + { + return "[TIGHT]"; + } + } + protected virtual bool AllowTightWhenTagged + { + get + { + return true; + } + } + public virtual int GetVersion() + { + return 1; + } + public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) + { + List list = new List(); + for (int i = 0; i < textureImporterInstanceIDs.Length; i++) + { + int instanceID = textureImporterInstanceIDs[i]; + TextureImporter textureImporter = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; + TextureImportInstructions textureImportInstructions = new TextureImportInstructions(); + textureImporter.ReadTextureImportInstructions(textureImportInstructions, target); + TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); + textureImporter.ReadTextureSettings(textureImporterSettings); + Sprite[] array = ( + from x in AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath) + select x as Sprite into x + where x != null + select x).ToArray(); + Sprite[] array2 = array; + for (int j = 0; j < array2.Length; j++) + { + Sprite sprite = array2[j]; + DefaultPackerPolicy.Entry entry = new DefaultPackerPolicy.Entry(); + entry.sprite = sprite; + entry.settings.format = textureImportInstructions.desiredFormat; + entry.settings.usageMode = textureImportInstructions.usageMode; + entry.settings.colorSpace = textureImportInstructions.colorSpace; + entry.settings.compressionQuality = textureImportInstructions.compressionQuality; + entry.settings.filterMode = ((!Enum.IsDefined(typeof(FilterMode), textureImporter.filterMode)) ? FilterMode.Bilinear : textureImporter.filterMode); + entry.settings.maxWidth = 2048; + entry.settings.maxHeight = 2048; + entry.settings.generateMipMaps = textureImporter.mipmapEnabled; + if (textureImporter.mipmapEnabled) + { + entry.settings.paddingPower = 2u; + } + entry.atlasName = this.ParseAtlasName(textureImporter.spritePackingTag); + entry.packingMode = this.GetPackingMode(textureImporter.spritePackingTag, textureImporterSettings.spriteMeshType); + entry.anisoLevel = textureImporter.anisoLevel; + list.Add(entry); + } + Resources.UnloadAsset(textureImporter); + } + IEnumerable> enumerable = + from e in list + group e by e.atlasName; + foreach (IGrouping current in enumerable) + { + int num = 0; + IEnumerable> enumerable2 = + from t in current + group t by t.settings; + foreach (IGrouping current2 in enumerable2) + { + string text = current.Key; + if (enumerable2.Count>() > 1) + { + text += string.Format(" (Group {0})", num); + } + AtlasSettings key = current2.Key; + key.anisoLevel = 1; + if (key.generateMipMaps) + { + foreach (DefaultPackerPolicy.Entry current3 in current2) + { + if (current3.anisoLevel > key.anisoLevel) + { + key.anisoLevel = current3.anisoLevel; + } + } + } + job.AddAtlas(text, key); + foreach (DefaultPackerPolicy.Entry current4 in current2) + { + job.AssignToAtlas(text, current4.sprite, current4.packingMode, SpritePackingRotation.None); + } + num++; + } + } + } + protected bool IsTagPrefixed(string packingTag) + { + packingTag = packingTag.Trim(); + return packingTag.Length >= this.TagPrefix.Length && packingTag.Substring(0, this.TagPrefix.Length) == this.TagPrefix; + } + private string ParseAtlasName(string packingTag) + { + string text = packingTag.Trim(); + if (this.IsTagPrefixed(text)) + { + text = text.Substring(this.TagPrefix.Length).Trim(); + } + return (text.Length != 0) ? text : "(unnamed)"; + } + private SpritePackingMode GetPackingMode(string packingTag, SpriteMeshType meshType) + { + if (meshType == SpriteMeshType.Tight && this.IsTagPrefixed(packingTag) == this.AllowTightWhenTagged) + { + return SpritePackingMode.Tight; + } + return SpritePackingMode.Rectangle; + } + } +} diff --git a/UnityEditor/UnityEditor.Sprites/IPackerPolicy.cs b/UnityEditor/UnityEditor.Sprites/IPackerPolicy.cs new file mode 100644 index 00000000..9f55541a --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/IPackerPolicy.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Sprites +{ + public interface IPackerPolicy + { + void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs); + int GetVersion(); + } +} diff --git a/UnityEditor/UnityEditor.Sprites/Packer.cs b/UnityEditor/UnityEditor.Sprites/Packer.cs new file mode 100644 index 00000000..64c1434b --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/Packer.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor.Sprites +{ + public sealed class Packer + { + public enum Execution + { + Normal, + ForceRegroup + } + public static string kDefaultPolicy = typeof(DefaultPackerPolicy).Name; + private static string[] m_policies = null; + private static string m_selectedPolicy = null; + private static Dictionary m_policyTypeCache = null; + public static string[] Policies + { + get + { + Packer.RegenerateList(); + return Packer.m_policies; + } + } + public static string SelectedPolicy + { + get + { + Packer.RegenerateList(); + return Packer.m_selectedPolicy; + } + set + { + Packer.RegenerateList(); + if (value == null) + { + throw new ArgumentNullException(); + } + if (!Packer.m_policies.Contains(value)) + { + throw new ArgumentException("Specified policy {0} is not in the policy list.", value); + } + Packer.SetSelectedPolicy(value); + } + } + public static extern string[] atlasNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private static void SetSelectedPolicy(string value) + { + Packer.m_selectedPolicy = value; + PlayerSettings.spritePackerPolicy = Packer.m_selectedPolicy; + } + private static void RegenerateList() + { + if (Packer.m_policies != null) + { + return; + } + List list = new List(); + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + Assembly[] array = assemblies; + for (int i = 0; i < array.Length; i++) + { + Assembly assembly = array[i]; + try + { + Type[] types = assembly.GetTypes(); + Type[] array2 = types; + for (int j = 0; j < array2.Length; j++) + { + Type type = array2[j]; + if (typeof(IPackerPolicy).IsAssignableFrom(type) && type != typeof(IPackerPolicy)) + { + list.Add(type); + } + } + } + catch (Exception) + { + Debug.Log(string.Format("SpritePacker failed to get types from {0}.", assembly.FullName)); + } + } + Packer.m_policies = ( + from t in list + select t.Name).ToArray(); + Packer.m_policyTypeCache = new Dictionary(); + foreach (Type current in list) + { + if (Packer.m_policyTypeCache.ContainsKey(current.Name)) + { + Type type2 = Packer.m_policyTypeCache[current.Name]; + Debug.LogError(string.Format("Duplicate Sprite Packer policies found: {0} and {1}. Please rename one.", current.FullName, type2.FullName)); + } + else + { + Packer.m_policyTypeCache[current.Name] = current; + } + } + Packer.m_selectedPolicy = ((!string.IsNullOrEmpty(PlayerSettings.spritePackerPolicy)) ? PlayerSettings.spritePackerPolicy : Packer.kDefaultPolicy); + if (!Packer.m_policies.Contains(Packer.m_selectedPolicy)) + { + Packer.SetSelectedPolicy(Packer.kDefaultPolicy); + } + } + internal static string GetSelectedPolicyId() + { + Packer.RegenerateList(); + Type type = Packer.m_policyTypeCache[Packer.m_selectedPolicy]; + IPackerPolicy packerPolicy = Activator.CreateInstance(type) as IPackerPolicy; + return string.Format("{0}::{1}", type.AssemblyQualifiedName, packerPolicy.GetVersion()); + } + internal static void ExecuteSelectedPolicy(BuildTarget target, int[] textureImporterInstanceIDs) + { + Packer.RegenerateList(); + Analytics.Event("SpritePacker", "ExecuteSelectedPolicy", target.ToString(), textureImporterInstanceIDs.Length); + Type type = Packer.m_policyTypeCache[Packer.m_selectedPolicy]; + IPackerPolicy packerPolicy = Activator.CreateInstance(type) as IPackerPolicy; + packerPolicy.OnGroupAtlases(target, new PackerJob(), textureImporterInstanceIDs); + } + internal static void SaveUnappliedTextureImporterSettings() + { + InspectorWindow[] allInspectorWindows = InspectorWindow.GetAllInspectorWindows(); + for (int i = 0; i < allInspectorWindows.Length; i++) + { + InspectorWindow inspectorWindow = allInspectorWindows[i]; + ActiveEditorTracker tracker = inspectorWindow.GetTracker(); + Editor[] activeEditors = tracker.activeEditors; + for (int j = 0; j < activeEditors.Length; j++) + { + Editor editor = activeEditors[j]; + TextureImporterInspector textureImporterInspector = editor as TextureImporterInspector; + if (!(textureImporterInspector == null)) + { + if (textureImporterInspector.HasModified()) + { + TextureImporter textureImporter = textureImporterInspector.target as TextureImporter; + if (EditorUtility.DisplayDialog("Unapplied import settings", "Unapplied import settings for '" + textureImporter.assetPath + "'", "Apply", "Revert")) + { + textureImporterInspector.ApplyAndImport(); + } + } + } + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D[] GetTexturesForAtlas(string atlasName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RebuildAtlasCacheIfNeeded(BuildTarget target, [DefaultValue("false")] bool displayProgressBar, [DefaultValue("Execution.Normal")] Packer.Execution execution); + [ExcludeFromDocs] + public static void RebuildAtlasCacheIfNeeded(BuildTarget target, bool displayProgressBar) + { + Packer.Execution execution = Packer.Execution.Normal; + Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); + } + [ExcludeFromDocs] + public static void RebuildAtlasCacheIfNeeded(BuildTarget target) + { + Packer.Execution execution = Packer.Execution.Normal; + bool displayProgressBar = false; + Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetAtlasDataForSprite(Sprite sprite, out string atlasName, [Writable] out Texture2D atlasTexture); + } +} diff --git a/UnityEditor/UnityEditor.Sprites/PackerJob.cs b/UnityEditor/UnityEditor.Sprites/PackerJob.cs new file mode 100644 index 00000000..2b8744ec --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/PackerJob.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Sprites +{ + public sealed class PackerJob + { + internal PackerJob() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddAtlas(string atlasName, AtlasSettings settings); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AssignToAtlas(string atlasName, Sprite sprite, SpritePackingMode packingMode, SpritePackingRotation packingRotation); + } +} diff --git a/UnityEditor/UnityEditor.Sprites/PackerWindow.cs b/UnityEditor/UnityEditor.Sprites/PackerWindow.cs new file mode 100644 index 00000000..d03837c2 --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/PackerWindow.cs @@ -0,0 +1,308 @@ +using System; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Sprites +{ + internal class PackerWindow : SpriteUtilityWindow + { + private struct Edge + { + public ushort v0; + public ushort v1; + public Edge(ushort a, ushort b) + { + this.v0 = a; + this.v1 = b; + } + public override bool Equals(object obj) + { + PackerWindow.Edge edge = (PackerWindow.Edge)obj; + return (this.v0 == edge.v0 && this.v1 == edge.v1) || (this.v0 == edge.v1 && this.v1 == edge.v0); + } + public override int GetHashCode() + { + return ((int)this.v0 << 16 | (int)this.v1) ^ ((int)this.v1 << 16 | (int)this.v0).GetHashCode(); + } + } + private static string[] s_AtlasNamesEmpty = new string[] + { + "Sprite atlas cache is empty" + }; + private string[] m_AtlasNames = PackerWindow.s_AtlasNamesEmpty; + private int m_SelectedAtlas; + private static string[] s_PageNamesEmpty = new string[0]; + private string[] m_PageNames = PackerWindow.s_PageNamesEmpty; + private int m_SelectedPage; + private Sprite m_SelectedSprite; + private void OnEnable() + { + base.minSize = new Vector2(400f, 256f); + base.title = EditorGUIUtility.TextContent("SpritePackerWindow.WindowTitle").text; + this.Reset(); + Analytics.Event("SpritePacker", "Window", "OnEnable", 1); + } + private void Reset() + { + this.RefreshAtlasNameList(); + this.RefreshAtlasPageList(); + this.m_SelectedAtlas = 0; + this.m_SelectedPage = 0; + this.m_SelectedSprite = null; + } + private void RefreshAtlasNameList() + { + this.m_AtlasNames = Packer.atlasNames; + if (this.m_SelectedAtlas >= this.m_AtlasNames.Length) + { + this.m_SelectedAtlas = 0; + } + } + private void RefreshAtlasPageList() + { + if (this.m_AtlasNames.Length > 0) + { + string atlasName = this.m_AtlasNames[this.m_SelectedAtlas]; + Texture2D[] texturesForAtlas = Packer.GetTexturesForAtlas(atlasName); + this.m_PageNames = new string[texturesForAtlas.Length]; + for (int i = 0; i < texturesForAtlas.Length; i++) + { + this.m_PageNames[i] = string.Format("Page {0}", i + 1); + } + } + else + { + this.m_PageNames = PackerWindow.s_PageNamesEmpty; + } + if (this.m_SelectedPage >= this.m_PageNames.Length) + { + this.m_SelectedPage = 0; + } + } + private void OnAtlasNameListChanged() + { + if (this.m_AtlasNames.Length > 0) + { + string[] atlasNames = Packer.atlasNames; + string text = this.m_AtlasNames[this.m_SelectedAtlas]; + string value = (atlasNames.Length > this.m_SelectedAtlas) ? atlasNames[this.m_SelectedAtlas] : null; + if (text.Equals(value)) + { + this.RefreshAtlasNameList(); + this.RefreshAtlasPageList(); + this.m_SelectedSprite = null; + return; + } + } + this.Reset(); + } + private bool ValidateProGUI() + { + if (!Application.HasAdvancedLicense()) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Sprite packing is only supported in Unity Pro.", new GUILayoutOption[0]); + EditorGUILayout.EndHorizontal(); + return false; + } + return true; + } + private bool ValidateIsPackingEnabled() + { + if (EditorSettings.spritePackerMode == SpritePackerMode.Disabled) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Sprite packing is disabled. Enable it in Project EditorSettings.", new GUILayoutOption[0]); + EditorGUILayout.EndHorizontal(); + return false; + } + return true; + } + private void DoToolbarGUI() + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(Application.isPlaying); + if (GUILayout.Button("Pack", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + Packer.RebuildAtlasCacheIfNeeded(EditorUserBuildSettings.activeBuildTarget, true); + this.m_SelectedSprite = null; + this.RefreshAtlasPageList(); + this.RefreshState(); + } + else + { + EditorGUI.BeginDisabledGroup(Packer.SelectedPolicy == Packer.kDefaultPolicy); + if (GUILayout.Button("Repack", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + Packer.RebuildAtlasCacheIfNeeded(EditorUserBuildSettings.activeBuildTarget, true, Packer.Execution.ForceRegroup); + this.m_SelectedSprite = null; + this.RefreshAtlasPageList(); + this.RefreshState(); + } + EditorGUI.EndDisabledGroup(); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.m_AtlasNames.Length == 0); + GUILayout.Space(16f); + GUILayout.Label("View atlas:", new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + this.m_SelectedAtlas = EditorGUILayout.Popup(this.m_SelectedAtlas, this.m_AtlasNames, EditorStyles.toolbarPopup, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.RefreshAtlasPageList(); + this.m_SelectedSprite = null; + } + EditorGUI.BeginChangeCheck(); + this.m_SelectedPage = EditorGUILayout.Popup(this.m_SelectedPage, this.m_PageNames, EditorStyles.toolbarPopup, new GUILayoutOption[] + { + GUILayout.Width(70f) + }); + if (EditorGUI.EndChangeCheck()) + { + this.m_SelectedSprite = null; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginChangeCheck(); + string[] policies = Packer.Policies; + int num = Array.IndexOf(policies, Packer.SelectedPolicy); + num = EditorGUILayout.Popup(num, policies, EditorStyles.toolbarPopup, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + Packer.SelectedPolicy = policies[num]; + } + EditorGUILayout.EndHorizontal(); + } + private void OnSelectionChange() + { + if (Selection.activeObject == null) + { + return; + } + Sprite sprite = Selection.activeObject as Sprite; + if (sprite != this.m_SelectedSprite) + { + if (sprite != null) + { + string selAtlasName; + Texture2D selAtlasTexture; + Packer.GetAtlasDataForSprite(sprite, out selAtlasName, out selAtlasTexture); + int num = this.m_AtlasNames.ToList().FindIndex((string s) => selAtlasName == s); + if (num == -1) + { + return; + } + int num2 = Packer.GetTexturesForAtlas(selAtlasName).ToList().FindIndex((Texture2D t) => selAtlasTexture == t); + if (num2 == -1) + { + return; + } + this.m_SelectedAtlas = num; + this.m_SelectedPage = num2; + this.RefreshAtlasPageList(); + } + this.m_SelectedSprite = sprite; + base.Repaint(); + } + } + private void RefreshState() + { + string[] atlasNames = Packer.atlasNames; + if (!atlasNames.SequenceEqual(this.m_AtlasNames)) + { + if (atlasNames.Length == 0) + { + this.Reset(); + return; + } + this.OnAtlasNameListChanged(); + } + if (this.m_AtlasNames.Length == 0) + { + base.SetNewTexture(null); + return; + } + if (this.m_SelectedAtlas >= this.m_AtlasNames.Length) + { + this.m_SelectedAtlas = 0; + } + string atlasName = this.m_AtlasNames[this.m_SelectedAtlas]; + Texture2D[] texturesForAtlas = Packer.GetTexturesForAtlas(atlasName); + if (this.m_SelectedPage >= texturesForAtlas.Length) + { + this.m_SelectedPage = 0; + } + base.SetNewTexture(texturesForAtlas[this.m_SelectedPage]); + } + public void OnGUI() + { + if (!this.ValidateProGUI()) + { + return; + } + if (!this.ValidateIsPackingEnabled()) + { + return; + } + Matrix4x4 matrix = Handles.matrix; + base.InitStyles(); + this.RefreshState(); + Rect rect = EditorGUILayout.BeginHorizontal(GUIContent.none, EditorStyles.toolbar, new GUILayoutOption[0]); + this.DoToolbarGUI(); + GUILayout.FlexibleSpace(); + bool enabled = GUI.enabled; + GUI.enabled = (this.m_AtlasNames.Length > 0); + base.DoAlphaZoomToolbarGUI(); + GUI.enabled = enabled; + EditorGUILayout.EndHorizontal(); + if (this.m_Texture == null) + { + return; + } + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_TextureViewRect = new Rect(0f, rect.yMax, base.position.width - 16f, base.position.height - 16f - rect.height); + GUILayout.FlexibleSpace(); + base.DoTextureGUI(); + string text = string.Format("{1}x{2}, {0}", TextureUtil.GetTextureFormatString(this.m_Texture.format), this.m_Texture.width, this.m_Texture.height); + EditorGUI.DropShadowLabel(new Rect(this.m_TextureViewRect.x, this.m_TextureViewRect.y + 10f, this.m_TextureViewRect.width, 20f), text); + EditorGUILayout.EndHorizontal(); + Handles.matrix = matrix; + } + private void DrawLineUtility(Vector2 from, Vector2 to) + { + SpriteEditorUtility.DrawLine(new Vector3(from.x * (float)this.m_Texture.width + 1f / this.m_Zoom, from.y * (float)this.m_Texture.height + 1f / this.m_Zoom, 0f), new Vector3(to.x * (float)this.m_Texture.width + 1f / this.m_Zoom, to.y * (float)this.m_Texture.height + 1f / this.m_Zoom, 0f)); + } + private PackerWindow.Edge[] FindUniqueEdges(ushort[] indices) + { + PackerWindow.Edge[] array = new PackerWindow.Edge[indices.Length]; + int num = indices.Length / 3; + for (int i = 0; i < num; i++) + { + array[i * 3] = new PackerWindow.Edge(indices[i * 3], indices[i * 3 + 1]); + array[i * 3 + 1] = new PackerWindow.Edge(indices[i * 3 + 1], indices[i * 3 + 2]); + array[i * 3 + 2] = new PackerWindow.Edge(indices[i * 3 + 2], indices[i * 3]); + } + return ( + from x in array + group x by x into x + where x.Count() == 1 + select x.First()).ToArray(); + } + protected override void DrawGizmos() + { + if (this.m_SelectedSprite != null && this.m_Texture != null) + { + Vector2[] spriteUVs = DataUtility.GetSpriteUVs(this.m_SelectedSprite, true); + ushort[] spriteIndices = DataUtility.GetSpriteIndices(this.m_SelectedSprite, true); + PackerWindow.Edge[] array = this.FindUniqueEdges(spriteIndices); + SpriteEditorUtility.BeginLines(new Color(0.3921f, 0.5843f, 0.9294f, 0.75f)); + PackerWindow.Edge[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + PackerWindow.Edge edge = array2[i]; + this.DrawLineUtility(spriteUVs[(int)edge.v0], spriteUVs[(int)edge.v1]); + } + SpriteEditorUtility.EndLines(); + } + } + } +} diff --git a/UnityEditor/UnityEditor.Sprites/TightPackerPolicy.cs b/UnityEditor/UnityEditor.Sprites/TightPackerPolicy.cs new file mode 100644 index 00000000..442c0f3b --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/TightPackerPolicy.cs @@ -0,0 +1,21 @@ +using System; +namespace UnityEditor.Sprites +{ + internal class TightPackerPolicy : DefaultPackerPolicy + { + protected override string TagPrefix + { + get + { + return "[RECT]"; + } + } + protected override bool AllowTightWhenTagged + { + get + { + return false; + } + } + } +} diff --git a/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs b/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs new file mode 100644 index 00000000..4c2509ef --- /dev/null +++ b/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor.Utils +{ + internal class MonoInstallationFinder + { + public static string GetFrameWorksFolder() + { + if (Application.platform == RuntimePlatform.WindowsEditor) + { + return Path.GetDirectoryName(EditorApplication.applicationPath) + "/Data/"; + } + if (Application.platform == RuntimePlatform.OSXEditor) + { + return EditorApplication.applicationPath + "/Contents/Frameworks/"; + } + return Path.GetDirectoryName(EditorApplication.applicationPath) + "/Data/"; + } + public static string GetProfileDirectory(BuildTarget target, string profile) + { + string monoInstallation = MonoInstallationFinder.GetMonoInstallation(); + return Path.Combine(monoInstallation, "lib/mono/" + profile); + } + public static string GetMonoInstallation() + { + return MonoInstallationFinder.GetMonoInstallation("Mono"); + } + public static string GetMonoInstallation(string monoName) + { + return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), monoName); + } + } +} diff --git a/UnityEditor/UnityEditor.Utils/Paths.cs b/UnityEditor/UnityEditor.Utils/Paths.cs new file mode 100644 index 00000000..47e05449 --- /dev/null +++ b/UnityEditor/UnityEditor.Utils/Paths.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.IO; +namespace UnityEditor.Utils +{ + internal static class Paths + { + public static string Combine(params string[] components) + { + if (components.Length < 1) + { + throw new ArgumentException("At least one component must be provided!"); + } + string text = components[0]; + for (int i = 1; i < components.Length; i++) + { + text = Path.Combine(text, components[i]); + } + return text; + } + public static string[] Split(string path) + { + List list = new List(path.Split(new char[] + { + Path.DirectorySeparatorChar + })); + int i = 0; + while (i < list.Count) + { + list[i] = list[i].Trim(); + if (list[i].Equals(string.Empty)) + { + list.RemoveAt(i); + } + else + { + i++; + } + } + return list.ToArray(); + } + public static string GetFileOrFolderName(string path) + { + string result; + if (File.Exists(path)) + { + result = Path.GetFileName(path); + } + else + { + if (!Directory.Exists(path)) + { + throw new ArgumentException("Target '" + path + "' does not exist."); + } + string[] array = Paths.Split(path); + result = array[array.Length - 1]; + } + return result; + } + public static string CreateTempDirectory() + { + string tempFileName = Path.GetTempFileName(); + File.Delete(tempFileName); + Directory.CreateDirectory(tempFileName); + return tempFileName; + } + public static string NormalizePath(this string path) + { + if (Path.DirectorySeparatorChar == '\\') + { + return path.Replace('/', Path.DirectorySeparatorChar); + } + return path.Replace('\\', Path.DirectorySeparatorChar); + } + } +} diff --git a/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs b/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs new file mode 100644 index 00000000..ab90e67c --- /dev/null +++ b/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs @@ -0,0 +1,85 @@ +using System; +using UnityEngine; +namespace UnityEditor.Utils +{ + internal class PerformanceChecks + { + private static string[] kShadersWithMobileVariants = new string[] + { + "VertexLit", + "Diffuse", + "Bumped Diffuse", + "Bumped Specular", + "Particles/Additive", + "Particles/VertexLit Blended", + "Particles/Alpha Blended", + "Particles/Multiply", + "RenderFX/Skybox" + }; + private static bool IsMobileBuildTarget(BuildTarget target) + { + return target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.Tizen; + } + private static string FormattedTextContent(string localeString, params string[] args) + { + GUIContent gUIContent = EditorGUIUtility.TextContent(localeString); + return string.Format(gUIContent.text, args); + } + public static string CheckMaterial(Material mat, BuildTarget buildTarget) + { + if (mat == null || mat.shader == null) + { + return null; + } + string shaderName = mat.shader.name; + int lOD = ShaderUtil.GetLOD(mat.shader); + bool flag = Array.Exists(PerformanceChecks.kShadersWithMobileVariants, (string s) => s == shaderName); + bool flag2 = PerformanceChecks.IsMobileBuildTarget(buildTarget); + if (buildTarget == BuildTarget.Android && ShaderUtil.HasClip(mat.shader)) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderWithClipAndroid", new string[0]); + } + if (flag) + { + if (flag2 && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1f, 1f, 1f, 1f)) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUsesWhiteColor", new string[] + { + "Mobile/" + shaderName + }); + } + if (flag2 && shaderName.StartsWith("Particles/")) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderHasMobileVariant", new string[] + { + "Mobile/" + shaderName + }); + } + if (shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderMobileSkybox", new string[] + { + "Mobile/Skybox" + }); + } + } + if (lOD >= 300 && flag2 && !shaderName.StartsWith("Mobile/")) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderExpensive", new string[0]); + } + if (shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) + { + Color color = mat.GetColor("_Emission"); + if (color.r >= 0.5f && color.g >= 0.5f && color.b >= 0.5f) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUseUnlit", new string[0]); + } + } + if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") == null) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderNoNormalMap", new string[0]); + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor.Utils/ProcessOutputStreamReader.cs b/UnityEditor/UnityEditor.Utils/ProcessOutputStreamReader.cs new file mode 100644 index 00000000..f4eeb82b --- /dev/null +++ b/UnityEditor/UnityEditor.Utils/ProcessOutputStreamReader.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; +namespace UnityEditor.Utils +{ + internal class ProcessOutputStreamReader + { + private readonly Func hostProcessExited; + private readonly StreamReader stream; + internal List lines; + private Thread thread; + internal ProcessOutputStreamReader(Process p, StreamReader stream) : this(() => p.HasExited, stream) + { + } + internal ProcessOutputStreamReader(Func hostProcessExited, StreamReader stream) + { + this.hostProcessExited = hostProcessExited; + this.stream = stream; + this.lines = new List(); + this.thread = new Thread(new ThreadStart(this.ThreadFunc)); + this.thread.Start(); + } + private void ThreadFunc() + { + if (this.hostProcessExited()) + { + return; + } + while (this.stream.BaseStream != null) + { + string text = this.stream.ReadLine(); + if (text == null) + { + return; + } + List obj = this.lines; + Monitor.Enter(obj); + try + { + this.lines.Add(text); + } + finally + { + Monitor.Exit(obj); + } + } + } + internal string[] GetOutput() + { + if (this.hostProcessExited()) + { + this.thread.Join(); + } + List obj = this.lines; + Monitor.Enter(obj); + string[] result; + try + { + result = this.lines.ToArray(); + } + finally + { + Monitor.Exit(obj); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor.Utils/Program.cs b/UnityEditor/UnityEditor.Utils/Program.cs new file mode 100644 index 00000000..07e3969a --- /dev/null +++ b/UnityEditor/UnityEditor.Utils/Program.cs @@ -0,0 +1,163 @@ +using System; +using System.Collections; +using System.Diagnostics; +using System.IO; +using System.Text; +namespace UnityEditor.Utils +{ + internal class Program : IDisposable + { + private ProcessOutputStreamReader _stdout; + private ProcessOutputStreamReader _stderr; + private Stream _stdin; + public Process _process; + public bool HasExited + { + get + { + if (this._process == null) + { + throw new InvalidOperationException("You cannot call HasExited before calling Start"); + } + bool result; + try + { + result = this._process.HasExited; + } + catch (InvalidOperationException) + { + result = true; + } + return result; + } + } + public int ExitCode + { + get + { + return this._process.ExitCode; + } + } + public int Id + { + get + { + return this._process.Id; + } + } + protected Program() + { + this._process = new Process(); + } + public Program(ProcessStartInfo si) : this() + { + this._process.StartInfo = si; + } + public void Start() + { + this._process.StartInfo.RedirectStandardInput = true; + this._process.StartInfo.RedirectStandardError = true; + this._process.StartInfo.RedirectStandardOutput = true; + this._process.StartInfo.UseShellExecute = false; + this._process.Start(); + this._stdout = new ProcessOutputStreamReader(this._process, this._process.StandardOutput); + this._stderr = new ProcessOutputStreamReader(this._process, this._process.StandardError); + this._stdin = this._process.StandardInput.BaseStream; + } + public ProcessStartInfo GetProcessStartInfo() + { + return this._process.StartInfo; + } + public void LogProcessStartInfo() + { + if (this._process != null) + { + Program.LogProcessStartInfo(this._process.StartInfo); + } + else + { + Console.WriteLine("Failed to retrieve process startInfo"); + } + } + private static void LogProcessStartInfo(ProcessStartInfo si) + { + Console.WriteLine("Filename: " + si.FileName); + Console.WriteLine("Arguments: " + si.Arguments); + foreach (DictionaryEntry dictionaryEntry in si.EnvironmentVariables) + { + if (dictionaryEntry.Key.ToString().StartsWith("MONO")) + { + Console.WriteLine("{0}: {1}", dictionaryEntry.Key, dictionaryEntry.Value); + } + } + int num = si.Arguments.IndexOf("Temp/UnityTempFile"); + Console.WriteLine("index: " + num); + if (num > 0) + { + string text = si.Arguments.Substring(num); + Console.WriteLine("Responsefile: " + text + " Contents: "); + Console.WriteLine(File.ReadAllText(text)); + } + } + public string GetAllOutput() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("stdout;"); + string[] standardOutput = this.GetStandardOutput(); + for (int i = 0; i < standardOutput.Length; i++) + { + string value = standardOutput[i]; + stringBuilder.AppendLine(value); + } + stringBuilder.AppendLine("stderr:"); + string[] errorOutput = this.GetErrorOutput(); + for (int j = 0; j < errorOutput.Length; j++) + { + string value2 = errorOutput[j]; + stringBuilder.AppendLine(value2); + } + return stringBuilder.ToString(); + } + public void Dispose() + { + if (!this.HasExited) + { + this._process.Kill(); + this._process.WaitForExit(); + } + this._process.Dispose(); + } + public Stream GetStandardInput() + { + return this._stdin; + } + public string[] GetStandardOutput() + { + return this._stdout.GetOutput(); + } + public string GetStandardOutputAsString() + { + string[] standardOutput = this.GetStandardOutput(); + StringBuilder stringBuilder = new StringBuilder(string.Empty); + string[] array = standardOutput; + for (int i = 0; i < array.Length; i++) + { + string value = array[i]; + stringBuilder.AppendLine(value); + } + return stringBuilder.ToString(); + } + public string[] GetErrorOutput() + { + return this._stderr.GetOutput(); + } + public void WaitForExit() + { + this._process.WaitForExit(); + } + public bool WaitForExit(int milliseconds) + { + return this._process.WaitForExit(milliseconds); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/Asset.cs b/UnityEditor/UnityEditor.VersionControl/Asset.cs new file mode 100644 index 00000000..cc0eb12d --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/Asset.cs @@ -0,0 +1,204 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class Asset + { + [Flags] + public enum States + { + None = 0, + Local = 1, + Synced = 2, + OutOfSync = 4, + Missing = 8, + CheckedOutLocal = 16, + CheckedOutRemote = 32, + DeletedLocal = 64, + DeletedRemote = 128, + AddedLocal = 256, + AddedRemote = 512, + Conflicted = 1024, + LockedLocal = 2048, + LockedRemote = 4096, + Updating = 8192, + ReadOnly = 16384, + MetaFile = 32768 + } + private string m_guid; + internal bool IsUnderVersionControl + { + get + { + return this.IsState(Asset.States.Synced) || this.IsState(Asset.States.OutOfSync) || this.IsState(Asset.States.AddedLocal); + } + } + public string prettyPath + { + get + { + return this.path; + } + } + public extern Asset.States state + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string path + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isFolder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool readOnly + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isMeta + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool locked + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string fullName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isInCurrentProject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Asset(string clientPath) + { + this.InternalCreateFromString(clientPath); + } + internal static bool IsState(Asset.States isThisState, Asset.States partOfThisState) + { + return (isThisState & partOfThisState) != Asset.States.None; + } + public bool IsState(Asset.States state) + { + return Asset.IsState(this.state, state); + } + public bool IsOneOfStates(Asset.States[] states) + { + for (int i = 0; i < states.Length; i++) + { + Asset.States states2 = states[i]; + if ((this.state & states2) != Asset.States.None) + { + return true; + } + } + return false; + } + public void Edit() + { + UnityEngine.Object @object = this.Load(); + if (@object != null) + { + AssetDatabase.OpenAsset(@object); + } + } + public UnityEngine.Object Load() + { + if (this.state == Asset.States.DeletedLocal || this.isMeta) + { + return null; + } + return AssetDatabase.LoadAssetAtPath(this.path, typeof(UnityEngine.Object)); + } + internal static string StateToString(Asset.States state) + { + if (Asset.IsState(state, Asset.States.AddedLocal)) + { + return "Added Local"; + } + if (Asset.IsState(state, Asset.States.AddedRemote)) + { + return "Added Remote"; + } + if (Asset.IsState(state, Asset.States.CheckedOutLocal) && !Asset.IsState(state, Asset.States.LockedLocal)) + { + return "Checked Out Local"; + } + if (Asset.IsState(state, Asset.States.CheckedOutRemote) && !Asset.IsState(state, Asset.States.LockedRemote)) + { + return "Checked Out Remote"; + } + if (Asset.IsState(state, Asset.States.Conflicted)) + { + return "Conflicted"; + } + if (Asset.IsState(state, Asset.States.DeletedLocal)) + { + return "Deleted Local"; + } + if (Asset.IsState(state, Asset.States.DeletedRemote)) + { + return "Deleted Remote"; + } + if (Asset.IsState(state, Asset.States.Local)) + { + return "Local"; + } + if (Asset.IsState(state, Asset.States.LockedLocal)) + { + return "Locked Local"; + } + if (Asset.IsState(state, Asset.States.LockedRemote)) + { + return "Locked Remote"; + } + if (Asset.IsState(state, Asset.States.OutOfSync)) + { + return "Out Of Sync"; + } + return string.Empty; + } + internal string StateToString() + { + return Asset.StateToString(this.state); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreateFromString(string clientPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Asset() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsChildOf(Asset other); + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/AssetList.cs b/UnityEditor/UnityEditor.VersionControl/AssetList.cs new file mode 100644 index 00000000..dc1dc083 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/AssetList.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor.VersionControl +{ + public class AssetList : List + { + public AssetList() + { + } + public AssetList(AssetList src) + { + } + public AssetList Filter(bool includeFolder, params Asset.States[] states) + { + AssetList assetList = new AssetList(); + if (!includeFolder && (states == null || states.Length == 0)) + { + return assetList; + } + foreach (Asset current in this) + { + if (current.isFolder) + { + if (includeFolder) + { + assetList.Add(current); + } + } + else + { + if (current.IsOneOfStates(states)) + { + assetList.Add(current); + } + } + } + return assetList; + } + public int FilterCount(bool includeFolder, params Asset.States[] states) + { + int num = 0; + if (!includeFolder && states == null) + { + return this.Count; + } + foreach (Asset current in this) + { + if (current.isFolder) + { + num++; + } + else + { + if (current.IsOneOfStates(states)) + { + num++; + } + } + } + return num; + } + public AssetList FilterChildren() + { + AssetList assetList = new AssetList(); + assetList.AddRange(this); + foreach (Asset asset in this) + { + assetList.RemoveAll((Asset p) => p.IsChildOf(asset)); + } + return assetList; + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs b/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs new file mode 100644 index 00000000..0a8d94c8 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class ChangeSet + { + private IntPtr m_thisDummy; + public extern string description + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string id + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public ChangeSet() + { + this.InternalCreate(); + } + public ChangeSet(string description) + { + this.InternalCreateFromString(description); + } + public ChangeSet(string description, string revision) + { + this.InternalCreateFromStringString(description, revision); + } + public ChangeSet(ChangeSet other) + { + this.InternalCopyConstruct(other); + } + ~ChangeSet() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCopyConstruct(ChangeSet other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreateFromString(string description); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreateFromStringString(string description, string changeSetID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/ChangeSets.cs b/UnityEditor/UnityEditor.VersionControl/ChangeSets.cs new file mode 100644 index 00000000..eaeb899e --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/ChangeSets.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor.VersionControl +{ + public class ChangeSets : List + { + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/CheckoutMode.cs b/UnityEditor/UnityEditor.VersionControl/CheckoutMode.cs new file mode 100644 index 00000000..4a481528 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/CheckoutMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum CheckoutMode + { + Asset = 1, + Meta = 2, + Both = 3 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/CommandContext.cs b/UnityEditor/UnityEditor.VersionControl/CommandContext.cs new file mode 100644 index 00000000..7899abc1 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/CommandContext.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + internal enum CommandContext + { + Global = 1 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/CompletionAction.cs b/UnityEditor/UnityEditor.VersionControl/CompletionAction.cs new file mode 100644 index 00000000..c133b53a --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/CompletionAction.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor.VersionControl +{ + public enum CompletionAction + { + UpdatePendingWindow = 1, + OnChangeContentsPendingWindow, + OnIncomingPendingWindow, + OnChangeSetsPendingWindow, + OnGotLatestPendingWindow, + OnSubmittedChangeWindow, + OnAddedChangeWindow + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/ConfigField.cs b/UnityEditor/UnityEditor.VersionControl/ConfigField.cs new file mode 100644 index 00000000..a6046a42 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/ConfigField.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class ConfigField + { + private IntPtr m_thisDummy; + private string m_guid; + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string label + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string description + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isRequired + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isPassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~ConfigField() + { + this.Dispose(); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/CustomCommand.cs b/UnityEditor/UnityEditor.VersionControl/CustomCommand.cs new file mode 100644 index 00000000..5b912b6c --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/CustomCommand.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + internal sealed class CustomCommand + { + private IntPtr m_thisDummy; + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string label + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern CommandContext context + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Task StartTask(); + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/FileMode.cs b/UnityEditor/UnityEditor.VersionControl/FileMode.cs new file mode 100644 index 00000000..75d170b3 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/FileMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum FileMode + { + None = 0, + Binary = 1, + Text = 2 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/MergeMethod.cs b/UnityEditor/UnityEditor.VersionControl/MergeMethod.cs new file mode 100644 index 00000000..c2888b87 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/MergeMethod.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum MergeMethod + { + MergeNone = 0, + MergeAll = 1, + MergeNonConflicting = 2 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/Message.cs b/UnityEditor/UnityEditor.VersionControl/Message.cs new file mode 100644 index 00000000..66115bf4 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/Message.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class Message + { + [Flags] + public enum Severity + { + Data = 0, + Verbose = 1, + Info = 2, + Warning = 3, + Error = 4 + } + private IntPtr m_thisDummy; + public extern Message.Severity severity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string message + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public void Show() + { + Message.Info(this.message); + } + private static void Info(string message) + { + Debug.Log("Version control:\n" + message); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Message() + { + this.Dispose(); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/OnlineState.cs b/UnityEditor/UnityEditor.VersionControl/OnlineState.cs new file mode 100644 index 00000000..83f1d4b4 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/OnlineState.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum OnlineState + { + Updating = 0, + Online = 1, + Offline = 2 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/Plugin.cs b/UnityEditor/UnityEditor.VersionControl/Plugin.cs new file mode 100644 index 00000000..382e06f8 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/Plugin.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class Plugin + { + private IntPtr m_thisDummy; + private string m_guid; + public static extern Plugin[] availablePlugins + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ConfigField[] configFields + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Plugin() + { + this.Dispose(); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/Provider.cs b/UnityEditor/UnityEditor.VersionControl/Provider.cs new file mode 100644 index 00000000..ae0e694b --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/Provider.cs @@ -0,0 +1,544 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class Provider + { + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isActive + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool requiresNetwork + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool hasChangelistSupport + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isVersioningFolders + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern OnlineState onlineState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string offlineReason + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Task activeTask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern Texture2D overlayAtlas + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern CustomCommand[] customCommands + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static Asset CacheStatus(string assetPath) + { + return Provider.Internal_CacheStatus(assetPath); + } + public static Task Status(AssetList assets) + { + return Provider.Internal_Status(assets.ToArray(), true); + } + public static Task Status(Asset asset) + { + return Provider.Internal_Status(new Asset[] + { + asset + }, true); + } + public static Task Status(AssetList assets, bool recursively) + { + return Provider.Internal_Status(assets.ToArray(), recursively); + } + public static Task Status(Asset asset, bool recursively) + { + return Provider.Internal_Status(new Asset[] + { + asset + }, recursively); + } + public static Task Status(string[] assets) + { + return Provider.Internal_StatusStrings(assets, true); + } + public static Task Status(string[] assets, bool recursively) + { + return Provider.Internal_StatusStrings(assets, recursively); + } + public static Task Status(string asset) + { + return Provider.Internal_StatusStrings(new string[] + { + asset + }, true); + } + public static Task Status(string asset, bool recursively) + { + return Provider.Internal_StatusStrings(new string[] + { + asset + }, recursively); + } + public static Task Move(string from, string to) + { + return Provider.Internal_MoveAsStrings(from, to); + } + public static bool CheckoutIsValid(AssetList assets) + { + return Provider.Internal_CheckoutIsValid(assets.ToArray()); + } + public static Task Checkout(AssetList assets, CheckoutMode mode) + { + return Provider.Internal_Checkout(assets.ToArray(), mode); + } + public static Task Checkout(string[] assets, CheckoutMode mode) + { + return Provider.Internal_CheckoutStrings(assets, mode); + } + public static Task Checkout(UnityEngine.Object[] assets, CheckoutMode mode) + { + AssetList assetList = new AssetList(); + for (int i = 0; i < assets.Length; i++) + { + UnityEngine.Object assetObject = assets[i]; + string assetPath = AssetDatabase.GetAssetPath(assetObject); + Asset assetByPath = Provider.GetAssetByPath(assetPath); + assetList.Add(assetByPath); + } + return Provider.Internal_Checkout(assetList.ToArray(), mode); + } + public static bool CheckoutIsValid(Asset asset) + { + return Provider.Internal_CheckoutIsValid(new Asset[] + { + asset + }); + } + public static Task Checkout(Asset asset, CheckoutMode mode) + { + return Provider.Internal_Checkout(new Asset[] + { + asset + }, mode); + } + public static Task Checkout(string asset, CheckoutMode mode) + { + return Provider.Internal_CheckoutStrings(new string[] + { + asset + }, mode); + } + public static Task Checkout(UnityEngine.Object asset, CheckoutMode mode) + { + string assetPath = AssetDatabase.GetAssetPath(asset); + Asset assetByPath = Provider.GetAssetByPath(assetPath); + return Provider.Internal_Checkout(new Asset[] + { + assetByPath + }, mode); + } + internal static bool PromptAndCheckoutIfNeeded(string[] assets, string promptIfCheckoutIsNeeded) + { + return Provider.Internal_PromptAndCheckoutIfNeeded(assets, promptIfCheckoutIsNeeded); + } + public static Task Delete(string assetProjectPath) + { + return Provider.Internal_DeleteAtProjectPath(assetProjectPath); + } + public static Task Delete(AssetList assets) + { + return Provider.Internal_Delete(assets.ToArray()); + } + public static Task Delete(Asset asset) + { + return Provider.Internal_Delete(new Asset[] + { + asset + }); + } + public static bool AddIsValid(AssetList assets) + { + return Provider.Internal_AddIsValid(assets.ToArray()); + } + public static Task Add(AssetList assets, bool recursive) + { + return Provider.Internal_Add(assets.ToArray(), recursive); + } + public static Task Add(Asset asset, bool recursive) + { + return Provider.Internal_Add(new Asset[] + { + asset + }, recursive); + } + public static bool DeleteChangeSetsIsValid(ChangeSets changesets) + { + return Provider.Internal_DeleteChangeSetsIsValid(changesets.ToArray()); + } + public static Task DeleteChangeSets(ChangeSets changesets) + { + return Provider.Internal_DeleteChangeSets(changesets.ToArray()); + } + internal static Task RevertChangeSets(ChangeSets changesets, RevertMode mode) + { + return Provider.Internal_RevertChangeSets(changesets.ToArray(), mode); + } + public static bool SubmitIsValid(ChangeSet changeset, AssetList assets) + { + return Provider.Internal_SubmitIsValid(changeset, (assets == null) ? null : assets.ToArray()); + } + public static Task Submit(ChangeSet changeset, AssetList list, string description, bool saveOnly) + { + return Provider.Internal_Submit(changeset, (list == null) ? null : list.ToArray(), description, saveOnly); + } + public static bool DiffIsValid(AssetList assets) + { + Asset[] assets2 = assets.ToArray(); + return Provider.Internal_DiffIsValid(assets2); + } + public static Task DiffHead(AssetList assets, bool includingMetaFiles) + { + return Provider.Internal_DiffHead(assets.ToArray(), includingMetaFiles); + } + public static bool ResolveIsValid(AssetList assets) + { + Asset[] assets2 = assets.ToArray(); + return Provider.Internal_ResolveIsValid(assets2); + } + public static Task Resolve(AssetList assets, ResolveMethod resolveMethod) + { + return Provider.Internal_Resolve(assets.ToArray(), resolveMethod); + } + public static Task Merge(AssetList assets, MergeMethod method) + { + return Provider.Internal_Merge(assets.ToArray(), method); + } + public static bool LockIsValid(AssetList assets) + { + return Provider.Internal_LockIsValid(assets.ToArray()); + } + public static bool LockIsValid(Asset asset) + { + return Provider.Internal_LockIsValid(new Asset[] + { + asset + }); + } + public static bool UnlockIsValid(AssetList assets) + { + return Provider.Internal_UnlockIsValid(assets.ToArray()); + } + public static bool UnlockIsValid(Asset asset) + { + return Provider.Internal_UnlockIsValid(new Asset[] + { + asset + }); + } + public static Task Lock(AssetList assets, bool locked) + { + return Provider.Internal_Lock(assets.ToArray(), locked); + } + public static Task Lock(Asset asset, bool locked) + { + return Provider.Internal_Lock(new Asset[] + { + asset + }, locked); + } + public static bool RevertIsValid(AssetList assets, RevertMode mode) + { + return Provider.Internal_RevertIsValid(assets.ToArray(), mode); + } + public static Task Revert(AssetList assets, RevertMode mode) + { + return Provider.Internal_Revert(assets.ToArray(), mode); + } + public static bool RevertIsValid(Asset asset, RevertMode mode) + { + return Provider.Internal_RevertIsValid(new Asset[] + { + asset + }, mode); + } + public static Task Revert(Asset asset, RevertMode mode) + { + return Provider.Internal_Revert(new Asset[] + { + asset + }, mode); + } + public static bool GetLatestIsValid(AssetList assets) + { + return Provider.Internal_GetLatestIsValid(assets.ToArray()); + } + public static bool GetLatestIsValid(Asset asset) + { + return Provider.Internal_GetLatestIsValid(new Asset[] + { + asset + }); + } + public static Task GetLatest(AssetList assets) + { + return Provider.Internal_GetLatest(assets.ToArray()); + } + public static Task GetLatest(Asset asset) + { + return Provider.Internal_GetLatest(new Asset[] + { + asset + }); + } + internal static Task SetFileMode(AssetList assets, FileMode mode) + { + return Provider.Internal_SetFileMode(assets.ToArray(), mode); + } + internal static Task SetFileMode(string[] assets, FileMode mode) + { + return Provider.Internal_SetFileModeStrings(assets, mode); + } + public static Task ChangeSetDescription(ChangeSet changeset) + { + return Provider.Internal_ChangeSetDescription(changeset); + } + public static Task ChangeSetStatus(ChangeSet changeset) + { + return Provider.Internal_ChangeSetStatus(changeset); + } + public static Task ChangeSetStatus(string changesetID) + { + ChangeSet changeset = new ChangeSet(string.Empty, changesetID); + return Provider.Internal_ChangeSetStatus(changeset); + } + public static Task IncomingChangeSetAssets(ChangeSet changeset) + { + return Provider.Internal_IncomingChangeSetAssets(changeset); + } + public static Task IncomingChangeSetAssets(string changesetID) + { + ChangeSet changeset = new ChangeSet(string.Empty, changesetID); + return Provider.Internal_IncomingChangeSetAssets(changeset); + } + public static Task ChangeSetMove(AssetList assets, ChangeSet changeset) + { + return Provider.Internal_ChangeSetMove(assets.ToArray(), changeset); + } + public static Task ChangeSetMove(Asset asset, ChangeSet changeset) + { + return Provider.Internal_ChangeSetMove(new Asset[] + { + asset + }, changeset); + } + public static Task ChangeSetMove(AssetList assets, string changesetID) + { + ChangeSet target = new ChangeSet(string.Empty, changesetID); + return Provider.Internal_ChangeSetMove(assets.ToArray(), target); + } + public static Task ChangeSetMove(Asset asset, string changesetID) + { + ChangeSet target = new ChangeSet(string.Empty, changesetID); + return Provider.Internal_ChangeSetMove(new Asset[] + { + asset + }, target); + } + public static AssetList GetAssetListFromSelection() + { + AssetList assetList = new AssetList(); + Asset[] array = Provider.Internal_GetAssetArrayFromSelection(); + Asset[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Asset item = array2[i]; + assetList.Add(item); + } + return assetList; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect GetAtlasRectForState(int state); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Plugin GetActivePlugin(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ConfigField[] GetActiveConfigFields(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsCustomCommandEnabled(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Asset Internal_CacheStatus(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Status(Asset[] assets, bool recursively); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_StatusStrings(string[] assetsProjectPaths, bool recursively); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_StatusAbsolutePath(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_CheckoutIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Checkout(Asset[] assets, CheckoutMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_CheckoutStrings(string[] assets, CheckoutMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_PromptAndCheckoutIfNeeded(string[] assets, string promptIfCheckoutIsNeeded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Delete(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DeleteAtProjectPath(string assetProjectPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_MoveAsStrings(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_AddIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Add(Asset[] assets, bool recursive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_DeleteChangeSetsIsValid(ChangeSet[] changes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DeleteChangeSets(ChangeSet[] changesets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_RevertChangeSets(ChangeSet[] changesets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_SubmitIsValid(ChangeSet changeset, Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Submit(ChangeSet changeset, Asset[] assets, string description, bool saveOnly); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_DiffIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DiffHead(Asset[] assets, bool includingMetaFiles); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_ResolveIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Resolve(Asset[] assets, ResolveMethod resolveMethod); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Merge(Asset[] assets, MergeMethod method); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_LockIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_UnlockIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Lock(Asset[] assets, bool locked); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_RevertIsValid(Asset[] assets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Revert(Asset[] assets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_GetLatestIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_GetLatest(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_SetFileMode(Asset[] assets, FileMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_SetFileModeStrings(string[] assets, FileMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetDescription(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetStatus(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task ChangeSets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetMove(Asset[] assets, ChangeSet target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task Incoming(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_IncomingChangeSetAssets(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsOpenForEdit(Asset asset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task UpdateSettings(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Asset GetAssetByPath(string unityPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Asset GetAssetByGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Asset[] Internal_GetAssetArrayFromSelection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GenerateID(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearCache(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InvalidateCache(); + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/ResolveMethod.cs b/UnityEditor/UnityEditor.VersionControl/ResolveMethod.cs new file mode 100644 index 00000000..3e276bea --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/ResolveMethod.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum ResolveMethod + { + UseMine = 1, + UseTheirs = 2, + UseMerged = 3 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/RevertMode.cs b/UnityEditor/UnityEditor.VersionControl/RevertMode.cs new file mode 100644 index 00000000..0cfdf77c --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/RevertMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + [Flags] + public enum RevertMode + { + Normal = 0, + Unchanged = 1, + KeepModifications = 2 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/SubmitResult.cs b/UnityEditor/UnityEditor.VersionControl/SubmitResult.cs new file mode 100644 index 00000000..03afacfe --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/SubmitResult.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VersionControl +{ + public enum SubmitResult + { + OK = 1, + Error, + ConflictingFiles = 4, + UnaddedFiles = 8 + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/Task.cs b/UnityEditor/UnityEditor.VersionControl/Task.cs new file mode 100644 index 00000000..8fcdc744 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/Task.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + public sealed class Task + { + private IntPtr m_thisDummy; + public AssetList assetList + { + get + { + AssetList assetList = new AssetList(); + Asset[] array = this.Internal_GetAssetList(); + Asset[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Asset item = array2[i]; + assetList.Add(item); + } + return assetList; + } + } + public ChangeSets changeSets + { + get + { + ChangeSets changeSets = new ChangeSets(); + ChangeSet[] array = this.Internal_GetChangeSets(); + ChangeSet[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + ChangeSet item = array2[i]; + changeSets.Add(item); + } + return changeSets; + } + } + public extern int userIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string description + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool success + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int secondsSpent + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int progressPct + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string progressMessage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int resultCode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Message[] messages + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Wait(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetCompletionAction(CompletionAction action); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Asset[] Internal_GetAssetList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern ChangeSet[] Internal_GetChangeSets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Message[] Internal_GetMessages(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Task() + { + this.Dispose(); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/WindowChange.cs b/UnityEditor/UnityEditor.VersionControl/WindowChange.cs new file mode 100644 index 00000000..a0faa198 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/WindowChange.cs @@ -0,0 +1,379 @@ +using System; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + internal class WindowChange : EditorWindow + { + private const int kSubmitNotStartedResultCode = 256; + private const int kSubmitRunningResultCode = 0; + private const string c_defaultDescription = ""; + private ListControl submitList = new ListControl(); + private AssetList assetList = new AssetList(); + private ChangeSet changeSet = new ChangeSet(); + private string description = string.Empty; + private bool allowSubmit; + private Task taskStatus; + private Task taskDesc; + private Task taskStat; + private Task taskSubmit; + private Task taskAdd; + private int submitResultCode = 256; + private string submitErrorMessage; + public void OnEnable() + { + base.position = new Rect(100f, 100f, 700f, 395f); + base.minSize = new Vector2(700f, 395f); + this.submitList.ReadOnly = true; + this.taskStatus = null; + this.taskDesc = null; + this.taskStat = null; + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + } + public static void Open(AssetList list, bool submit) + { + WindowChange.Open(null, list, submit); + } + public static void Open(ChangeSet change, AssetList assets, bool submit) + { + WindowChange window = EditorWindow.GetWindow(true, "Version Control Changeset"); + window.allowSubmit = submit; + window.DoOpen(change, assets); + } + private void DoOpen(ChangeSet change, AssetList assets) + { + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + this.changeSet = change; + this.description = string.Empty; + this.assetList = null; + if (change == null) + { + this.taskStatus = Provider.Status(assets); + } + else + { + this.taskDesc = Provider.ChangeSetDescription(change); + this.taskStat = Provider.ChangeSetStatus(change); + } + } + private void RefreshList() + { + this.submitList.Clear(); + foreach (Asset current in this.assetList) + { + this.submitList.Add(null, current.prettyPath, current); + } + if (this.assetList.Count == 0) + { + ChangeSet changeSet = new ChangeSet("empty change list"); + ListItem listItem = this.submitList.Add(null, changeSet.description, changeSet); + listItem.Dummy = true; + } + this.submitList.Refresh(); + base.Repaint(); + } + internal static void OnSubmitted(Task task) + { + WindowChange[] array = Resources.FindObjectsOfTypeAll(typeof(WindowChange)) as WindowChange[]; + if (array.Length == 0) + { + return; + } + WindowChange windowChange = array[0]; + windowChange.assetList = task.assetList; + windowChange.submitResultCode = task.resultCode; + windowChange.submitErrorMessage = null; + if ((task.resultCode & 2) != 0) + { + string empty = string.Empty; + Message[] messages = task.messages; + for (int i = 0; i < messages.Length; i++) + { + Message message = messages[i]; + if (message.severity == Message.Severity.Error) + { + WindowChange expr_77 = windowChange; + expr_77.submitErrorMessage = expr_77.submitErrorMessage + empty + message.message; + } + } + } + if ((task.resultCode & 3) != 0) + { + WindowPending.UpdateAllWindows(); + } + windowChange.RefreshList(); + } + internal static void OnAdded(Task task) + { + WindowChange[] array = Resources.FindObjectsOfTypeAll(typeof(WindowChange)) as WindowChange[]; + if (array.Length == 0) + { + return; + } + WindowChange windowChange = array[0]; + windowChange.taskSubmit = null; + windowChange.submitResultCode = 256; + windowChange.submitErrorMessage = null; + windowChange.taskAdd = null; + windowChange.taskStatus = Provider.Status(windowChange.assetList, false); + windowChange.assetList = null; + WindowPending.UpdateAllWindows(); + } + private void OnGUI() + { + if ((this.submitResultCode & 4) != 0) + { + this.OnConflictingFilesGUI(); + } + else + { + if ((this.submitResultCode & 8) != 0) + { + this.OnUnaddedFilesGUI(); + } + else + { + if ((this.submitResultCode & 2) != 0) + { + this.OnErrorGUI(); + } + else + { + this.OnSubmitGUI(); + } + } + } + } + private void OnSubmitGUI() + { + bool flag = this.submitResultCode != 256; + if (flag) + { + GUI.enabled = false; + } + GUILayout.Label("Description", EditorStyles.boldLabel, new GUILayoutOption[0]); + if (this.taskStatus != null && this.taskStatus.resultCode != 0) + { + this.assetList = this.taskStatus.assetList.Filter(true, new Asset.States[] + { + Asset.States.CheckedOutLocal, + Asset.States.DeletedLocal, + Asset.States.AddedLocal + }); + this.RefreshList(); + this.taskStatus = null; + } + else + { + if (this.taskDesc != null && this.taskDesc.resultCode != 0) + { + this.description = ((this.taskDesc.text.Length <= 0) ? string.Empty : this.taskDesc.text); + if (this.description.Trim() == "") + { + this.description = string.Empty; + } + this.taskDesc = null; + } + else + { + if (this.taskStat != null && this.taskStat.resultCode != 0) + { + this.assetList = this.taskStat.assetList; + this.RefreshList(); + this.taskStat = null; + } + } + } + Task task = (this.taskStatus == null || this.taskStatus.resultCode != 0) ? ((this.taskDesc == null || this.taskDesc.resultCode != 0) ? ((this.taskStat == null || this.taskStat.resultCode != 0) ? this.taskSubmit : this.taskStat) : this.taskDesc) : this.taskStatus; + GUI.enabled = ((this.taskDesc == null || this.taskDesc.resultCode != 0) && this.submitResultCode == 256); + this.description = EditorGUILayout.TextArea(this.description, new GUILayoutOption[] + { + GUILayout.Height(150f) + }).Trim(); + GUI.enabled = true; + GUILayout.Label("Files", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect screenRect = new Rect(6f, 206f, base.position.width - 12f, base.position.height - 248f); + GUILayout.BeginArea(screenRect); + GUILayout.Box(string.Empty, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + GUILayout.EndArea(); + this.submitList.OnGUI(new Rect(screenRect.x + 2f, screenRect.y + 2f, screenRect.width - 4f, screenRect.height - 4f), true); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (this.submitResultCode == 256) + { + if (task != null) + { + GUIContent gUIContent = GUIContent.Temp("Getting info"); + gUIContent.image = WindowPending.StatusWheel.image; + GUILayout.Label(gUIContent, new GUILayoutOption[0]); + gUIContent.image = null; + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Cancel", new GUILayoutOption[0])) + { + base.Close(); + } + GUI.enabled = (task == null && !string.IsNullOrEmpty(this.description)); + if (Provider.hasChangelistSupport && GUILayout.Button("Save", new GUILayoutOption[0])) + { + this.Save(false); + } + if (this.allowSubmit) + { + bool enabled = GUI.enabled; + GUI.enabled = (this.assetList != null && this.assetList.Count > 0 && !string.IsNullOrEmpty(this.description)); + if (GUILayout.Button("Submit", new GUILayoutOption[0])) + { + this.Save(true); + } + GUI.enabled = enabled; + } + } + else + { + bool flag2 = (this.submitResultCode & 1) != 0; + GUI.enabled = flag2; + string text = string.Empty; + if (flag2) + { + text = "Finished successfully"; + } + else + { + if (task != null) + { + GUILayout.Label(WindowPending.StatusWheel, new GUILayoutOption[0]); + text = task.progressMessage; + if (text.Length == 0) + { + text = "Running..."; + } + } + } + GUILayout.Label(text, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Close", new GUILayoutOption[0])) + { + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + base.Close(); + } + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + GUILayout.Space(12f); + if (task != null) + { + base.Repaint(); + } + } + private void OnErrorGUI() + { + GUILayout.Label("Submit failed", EditorStyles.boldLabel, new GUILayoutOption[0]); + string text = string.Empty; + if (!string.IsNullOrEmpty(this.submitErrorMessage)) + { + text = this.submitErrorMessage + "\n"; + } + text += "See console for details. You can get more details by increasing log level in EditorSettings."; + GUILayout.Label(text, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Close", new GUILayoutOption[0])) + { + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + base.Close(); + WindowPending.UpdateAllWindows(); + } + GUILayout.EndHorizontal(); + } + private void OnConflictingFilesGUI() + { + string text = string.Empty; + foreach (Asset current in this.assetList) + { + if (current.IsState(Asset.States.Conflicted)) + { + text = text + current.prettyPath + "\n"; + } + } + GUILayout.Label("Conflicting files", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("Some files need to be resolved before submitting:", new GUILayoutOption[0]); + GUI.enabled = false; + GUILayout.TextArea(text, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + GUI.enabled = true; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Close", new GUILayoutOption[0])) + { + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + base.Close(); + } + GUILayout.EndHorizontal(); + } + private void OnUnaddedFilesGUI() + { + AssetList assetList = new AssetList(); + string text = string.Empty; + foreach (Asset current in this.assetList) + { + if (!current.IsState(Asset.States.OutOfSync) && !current.IsState(Asset.States.Synced) && !current.IsState(Asset.States.AddedLocal)) + { + text = text + current.prettyPath + "\n"; + assetList.Add(current); + } + } + GUILayout.Label("Files to add", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("Some additional files need to be added:", new GUILayoutOption[0]); + GUI.enabled = false; + GUILayout.TextArea(text, new GUILayoutOption[0]); + GUI.enabled = true; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Add files", new GUILayoutOption[0])) + { + this.taskAdd = Provider.Add(assetList, false); + this.taskAdd.SetCompletionAction(CompletionAction.OnAddedChangeWindow); + } + if (GUILayout.Button("Abort", new GUILayoutOption[0])) + { + this.taskSubmit = null; + this.submitResultCode = 256; + this.submitErrorMessage = null; + base.Close(); + } + GUILayout.EndHorizontal(); + } + private void Save(bool submit) + { + if (this.description.Trim() == string.Empty) + { + Debug.LogError("Version control: Please enter a valid change description"); + return; + } + EditorApplication.SaveAssets(); + this.taskSubmit = Provider.Submit(this.changeSet, this.assetList, this.description, !submit); + this.submitResultCode = 0; + this.submitErrorMessage = null; + this.taskSubmit.SetCompletionAction(CompletionAction.OnSubmittedChangeWindow); + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/WindowPending.cs b/UnityEditor/UnityEditor.VersionControl/WindowPending.cs new file mode 100644 index 00000000..38c17d7f --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/WindowPending.cs @@ -0,0 +1,500 @@ +using System; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + internal class WindowPending : EditorWindow + { + internal class Styles + { + public GUIStyle box = "CN Box"; + public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; + } + private const float k_ResizerHeight = 17f; + private const float k_MinIncomingAreaHeight = 50f; + private const float k_BottomBarHeight = 17f; + private static WindowPending.Styles s_Styles; + private static Texture2D submittedIcon; + private static Texture2D changeIcon; + private Texture2D syncIcon; + private Texture2D refreshIcon; + private GUIStyle header; + [SerializeField] + private ListControl pendingList; + [SerializeField] + private ListControl incomingList; + private bool m_ShowIncoming; + private float s_ToolbarButtonsWidth; + private static GUIContent[] sStatusWheel; + private static bool s_DidReload; + internal static GUIContent StatusWheel + { + get + { + if (WindowPending.sStatusWheel == null) + { + WindowPending.sStatusWheel = new GUIContent[12]; + for (int i = 0; i < 12; i++) + { + GUIContent gUIContent = new GUIContent(); + gUIContent.image = EditorGUIUtility.LoadIcon("WaitSpin" + i.ToString("00")); + gUIContent.image.hideFlags = HideFlags.HideAndDontSave; + gUIContent.image.name = "Spinner"; + WindowPending.sStatusWheel[i] = gUIContent; + } + } + int num = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10f, 11.99f); + return WindowPending.sStatusWheel[num]; + } + } + private void InitStyles() + { + if (WindowPending.s_Styles == null) + { + WindowPending.s_Styles = new WindowPending.Styles(); + } + } + private void OnEnable() + { + base.title = "UnityEditor.VersionControl"; + if (this.pendingList == null) + { + this.pendingList = new ListControl(); + } + ListControl expr_27 = this.pendingList; + expr_27.ExpandEvent = (ListControl.ExpandDelegate)Delegate.Combine(expr_27.ExpandEvent, new ListControl.ExpandDelegate(this.OnExpand)); + ListControl expr_4E = this.pendingList; + expr_4E.DragEvent = (ListControl.DragDelegate)Delegate.Combine(expr_4E.DragEvent, new ListControl.DragDelegate(this.OnDrop)); + this.pendingList.MenuDefault = "CONTEXT/Pending"; + this.pendingList.MenuFolder = "CONTEXT/Change"; + this.pendingList.DragAcceptOnly = true; + if (this.incomingList == null) + { + this.incomingList = new ListControl(); + } + ListControl expr_B7 = this.incomingList; + expr_B7.ExpandEvent = (ListControl.ExpandDelegate)Delegate.Combine(expr_B7.ExpandEvent, new ListControl.ExpandDelegate(this.OnExpandIncoming)); + this.UpdateWindow(); + } + public void OnSelectionChange() + { + if (!base.hasFocus) + { + this.pendingList.Sync(); + base.Repaint(); + } + } + private void OnDrop(ChangeSet targetItem) + { + AssetList selectedAssets = this.pendingList.SelectedAssets; + Task task = Provider.ChangeSetMove(selectedAssets, targetItem); + task.SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private void OnExpand(ChangeSet change, ListItem item) + { + if (!Provider.isActive) + { + return; + } + Task task = Provider.ChangeSetStatus(change); + task.userIdentifier = item.Identifier; + task.SetCompletionAction(CompletionAction.OnChangeContentsPendingWindow); + if (!item.HasChildren) + { + Asset asset = new Asset("Updating..."); + ListItem listItem = this.pendingList.Add(item, asset.prettyPath, asset); + listItem.Dummy = true; + this.pendingList.Refresh(false); + base.Repaint(); + } + } + private void OnExpandIncoming(ChangeSet change, ListItem item) + { + if (!Provider.isActive) + { + return; + } + Task task = Provider.IncomingChangeSetAssets(change); + task.userIdentifier = item.Identifier; + task.SetCompletionAction(CompletionAction.OnChangeContentsPendingWindow); + if (!item.HasChildren) + { + Asset asset = new Asset("Updating..."); + ListItem listItem = this.incomingList.Add(item, asset.prettyPath, asset); + listItem.Dummy = true; + this.incomingList.Refresh(false); + base.Repaint(); + } + } + private void UpdateWindow() + { + if (!Provider.isActive) + { + this.pendingList.Clear(); + base.Repaint(); + return; + } + Task task = Provider.ChangeSets(); + task.SetCompletionAction(CompletionAction.OnChangeSetsPendingWindow); + Task task2 = Provider.Incoming(); + task2.SetCompletionAction(CompletionAction.OnIncomingPendingWindow); + } + private void OnGotLatest(Task t) + { + this.UpdateWindow(); + } + private static void OnVCTaskCompletedEvent(Task task, CompletionAction completionAction) + { + WindowPending[] array = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; + WindowPending[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + WindowPending windowPending = array2[i]; + if (completionAction == CompletionAction.UpdatePendingWindow) + { + windowPending.UpdateWindow(); + } + else + { + if (completionAction == CompletionAction.OnChangeContentsPendingWindow) + { + windowPending.OnChangeContents(task); + } + else + { + if (completionAction == CompletionAction.OnIncomingPendingWindow) + { + windowPending.OnIncoming(task); + } + else + { + if (completionAction == CompletionAction.OnChangeSetsPendingWindow) + { + windowPending.OnChangeSets(task); + } + else + { + if (completionAction == CompletionAction.OnGotLatestPendingWindow) + { + windowPending.OnGotLatest(task); + } + } + } + } + } + } + if (completionAction == CompletionAction.OnSubmittedChangeWindow) + { + WindowChange.OnSubmitted(task); + } + else + { + if (completionAction == CompletionAction.OnAddedChangeWindow) + { + WindowChange.OnAdded(task); + } + } + task.Dispose(); + } + public static void OnStatusUpdated() + { + } + public static void UpdateAllWindows() + { + WindowPending[] array = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; + WindowPending[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + WindowPending windowPending = array2[i]; + windowPending.UpdateWindow(); + } + } + public static void CloseAllWindows() + { + WindowPending[] array = Resources.FindObjectsOfTypeAll(typeof(WindowPending)) as WindowPending[]; + WindowPending windowPending = (array.Length <= 0) ? null : array[0]; + if (windowPending != null) + { + windowPending.Close(); + } + } + private void OnIncoming(Task task) + { + this.CreateStaticResources(); + this.PopulateListControl(this.incomingList, task, WindowPending.submittedIcon); + } + private void OnChangeSets(Task task) + { + this.CreateStaticResources(); + this.PopulateListControl(this.pendingList, task, WindowPending.changeIcon); + } + private void PopulateListControl(ListControl list, Task task, Texture2D icon) + { + ChangeSets changeSets = task.changeSets; + ListItem listItem = list.Root.FirstChild; + while (listItem != null) + { + ChangeSet cs = listItem.Item as ChangeSet; + if (changeSets.Find((ChangeSet elm) => elm.id == cs.id) == null) + { + ListItem listItem2 = listItem; + listItem = listItem.Next; + list.Root.Remove(listItem2); + } + else + { + listItem = listItem.Next; + } + } + foreach (ChangeSet current in changeSets) + { + ListItem listItem3 = list.GetChangeSetItem(current); + if (listItem3 != null) + { + listItem3.Item = current; + } + else + { + listItem3 = list.Add(null, current.description, current); + } + listItem3.Exclusive = true; + listItem3.CanAccept = true; + listItem3.Icon = icon; + } + list.Refresh(); + base.Repaint(); + } + private void OnChangeContents(Task task) + { + ListItem listItem = this.pendingList.FindItemWithIdentifier(task.userIdentifier); + ListItem listItem2 = (listItem != null) ? listItem : this.incomingList.FindItemWithIdentifier(task.userIdentifier); + if (listItem2 == null) + { + return; + } + ListControl listControl = (listItem != null) ? this.pendingList : this.incomingList; + listItem2.RemoveAll(); + AssetList assetList = task.assetList; + if (assetList.Count == 0) + { + ListItem listItem3 = listControl.Add(listItem2, "Empty change list", null); + listItem3.Dummy = true; + } + else + { + foreach (Asset current in assetList) + { + listControl.Add(listItem2, current.prettyPath, current); + } + } + listControl.Refresh(false); + base.Repaint(); + } + private void OnGUI() + { + this.InitStyles(); + if (!WindowPending.s_DidReload) + { + WindowPending.s_DidReload = true; + this.UpdateWindow(); + } + this.CreateResources(); + Event current = Event.current; + float fixedHeight = EditorStyles.toolbar.fixedHeight; + GUILayout.BeginArea(new Rect(0f, 0f, base.position.width, fixedHeight)); + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + int num = (this.incomingList.Root != null) ? this.incomingList.Root.ChildCount : 0; + this.m_ShowIncoming = !GUILayout.Toggle(!this.m_ShowIncoming, "Outgoing", EditorStyles.toolbarButton, new GUILayoutOption[0]); + GUIContent content = GUIContent.Temp("Incoming" + ((num != 0) ? (" (" + num.ToString() + ")") : string.Empty)); + this.m_ShowIncoming = GUILayout.Toggle(this.m_ShowIncoming, content, EditorStyles.toolbarButton, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginDisabledGroup(Provider.activeTask != null); + CustomCommand[] customCommands = Provider.customCommands; + for (int i = 0; i < customCommands.Length; i++) + { + CustomCommand customCommand = customCommands[i]; + if (customCommand.context == CommandContext.Global && GUILayout.Button(customCommand.label, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + customCommand.StartTask(); + } + } + EditorGUI.EndDisabledGroup(); + bool flag = Mathf.FloorToInt(base.position.width - this.s_ToolbarButtonsWidth) > 0; + if (flag && GUILayout.Button("Settings", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + EditorApplication.ExecuteMenuItem("Edit/Project Settings/Editor"); + EditorWindow.FocusWindowIfItsOpen(); + GUIUtility.ExitGUI(); + } + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, 0.5f); + bool flag2 = GUILayout.Button(this.refreshIcon, EditorStyles.toolbarButton, new GUILayoutOption[0]); + GUI.color = color; + if (current.isKey && GUIUtility.keyboardControl == 0 && current.type == EventType.KeyDown && current.keyCode == KeyCode.F5) + { + flag2 = true; + current.Use(); + } + if (flag2) + { + Provider.InvalidateCache(); + if (Provider.isActive && Provider.onlineState == OnlineState.Online) + { + Task task = Provider.ChangeSets(); + task.SetCompletionAction(CompletionAction.OnChangeSetsPendingWindow); + Task task2 = Provider.Incoming(); + task2.SetCompletionAction(CompletionAction.OnIncomingPendingWindow); + } + else + { + Provider.UpdateSettings(); + } + } + GUILayout.EndArea(); + Rect rect = new Rect(0f, fixedHeight, base.position.width, base.position.height - fixedHeight - 17f); + bool flag3 = false; + GUILayout.EndHorizontal(); + if (!Provider.isActive) + { + Color color2 = GUI.color; + GUI.color = new Color(0.8f, 0.5f, 0.5f); + rect.height = fixedHeight; + GUILayout.BeginArea(rect); + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + string text = "DISABLED"; + if (Provider.enabled) + { + if (Provider.onlineState == OnlineState.Updating) + { + GUI.color = new Color(0.8f, 0.8f, 0.5f); + text = "CONNECTING..."; + } + else + { + text = "OFFLINE"; + } + } + GUILayout.Label(text, EditorStyles.miniLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + rect.y += rect.height; + if (!string.IsNullOrEmpty(Provider.offlineReason)) + { + GUI.Label(rect, Provider.offlineReason); + } + GUI.color = color2; + flag3 = false; + } + else + { + if (this.m_ShowIncoming) + { + flag3 |= this.incomingList.OnGUI(rect, base.hasFocus); + } + else + { + flag3 |= this.pendingList.OnGUI(rect, base.hasFocus); + } + rect.y += rect.height; + rect.height = 17f; + GUI.Label(rect, GUIContent.none, WindowPending.s_Styles.bottomBarBg); + GUIContent content2 = new GUIContent("Apply All Incoming Changes"); + Vector2 vector = EditorStyles.miniButton.CalcSize(content2); + Rect rect2 = new Rect(rect.x, rect.y - 2f, rect.width - vector.x - 5f, rect.height); + WindowPending.ProgressGUI(rect2, Provider.activeTask, false); + if (this.m_ShowIncoming) + { + Rect position = rect; + position.width = vector.x; + position.height = vector.y; + position.y = rect.y + 2f; + position.x = base.position.width - vector.x - 5f; + EditorGUI.BeginDisabledGroup(this.incomingList.Size == 0); + if (GUI.Button(position, content2, EditorStyles.miniButton)) + { + Asset item = new Asset(string.Empty); + Task latest = Provider.GetLatest(new AssetList + { + item + }); + latest.SetCompletionAction(CompletionAction.OnGotLatestPendingWindow); + } + EditorGUI.EndDisabledGroup(); + } + } + if (flag3) + { + base.Repaint(); + } + } + internal static bool ProgressGUI(Rect rect, Task activeTask, bool descriptionTextFirst) + { + if (activeTask != null && (activeTask.progressPct != -1 || activeTask.secondsSpent != -1 || activeTask.progressMessage.Length != 0)) + { + string text = activeTask.progressMessage; + Rect position = rect; + GUIContent statusWheel = WindowPending.StatusWheel; + position.width = position.height; + position.x += 4f; + position.y += 4f; + GUI.Label(position, statusWheel); + rect.x += position.width + 4f; + text = ((text.Length != 0) ? text : activeTask.description); + if (activeTask.progressPct == -1) + { + rect.width -= position.width + 4f; + rect.y += 4f; + GUI.Label(rect, text, EditorStyles.miniLabel); + } + else + { + rect.width = 120f; + EditorGUI.ProgressBar(rect, (float)activeTask.progressPct, text); + } + return true; + } + return false; + } + private void CreateResources() + { + if (this.refreshIcon == null) + { + this.refreshIcon = EditorGUIUtility.LoadIcon("Refresh"); + this.refreshIcon.hideFlags = HideFlags.HideAndDontSave; + this.refreshIcon.name = "RefreshIcon"; + } + if (WindowPending.submittedIcon == null) + { + } + if (this.header == null) + { + this.header = "OL Title"; + } + this.CreateStaticResources(); + if (this.s_ToolbarButtonsWidth == 0f) + { + this.s_ToolbarButtonsWidth = EditorStyles.toolbarButton.CalcSize(new GUIContent("Incoming (xx)")).x; + this.s_ToolbarButtonsWidth += EditorStyles.toolbarButton.CalcSize(new GUIContent("Outgoing")).x; + this.s_ToolbarButtonsWidth += EditorStyles.toolbarButton.CalcSize(new GUIContent("Settings")).x; + this.s_ToolbarButtonsWidth += EditorStyles.toolbarButton.CalcSize(new GUIContent(this.refreshIcon)).x; + } + } + private void CreateStaticResources() + { + if (this.syncIcon == null) + { + this.syncIcon = EditorGUIUtility.LoadIcon("vcs_sync"); + this.syncIcon.hideFlags = HideFlags.HideAndDontSave; + this.syncIcon.name = "SyncIcon"; + } + if (WindowPending.changeIcon == null) + { + WindowPending.changeIcon = EditorGUIUtility.LoadIcon("vcs_change"); + WindowPending.changeIcon.hideFlags = HideFlags.HideAndDontSave; + WindowPending.changeIcon.name = "ChangeIcon"; + } + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs b/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs new file mode 100644 index 00000000..e1f29e15 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs @@ -0,0 +1,166 @@ +using System; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + internal class WindowResolve : EditorWindow + { + private ListControl resolveList = new ListControl(); + private AssetList assetList = new AssetList(); + private bool cancelled; + public void OnEnable() + { + base.position = new Rect(100f, 100f, 650f, 330f); + base.minSize = new Vector2(650f, 330f); + } + public void OnDisable() + { + if (!this.cancelled) + { + WindowPending.UpdateAllWindows(); + } + } + public static void Open(ChangeSet change) + { + Task task = Provider.ChangeSetStatus(change); + task.Wait(); + WindowResolve window = WindowResolve.GetWindow(); + window.DoOpen(task.assetList); + } + public static void Open(AssetList assets) + { + Task task = Provider.Status(assets); + task.Wait(); + WindowResolve window = WindowResolve.GetWindow(); + window.DoOpen(task.assetList); + } + private static WindowResolve GetWindow() + { + return EditorWindow.GetWindow(true, "Version Control Resolve"); + } + private void DoOpen(AssetList resolve) + { + bool includeFolder = true; + this.assetList = resolve.Filter(includeFolder, new Asset.States[] + { + Asset.States.Conflicted + }); + this.RefreshList(); + } + private void RefreshList() + { + this.resolveList.Clear(); + bool flag = true; + foreach (Asset current in this.assetList) + { + ListItem item = this.resolveList.Add(null, current.prettyPath, current); + if (flag) + { + this.resolveList.SelectedSet(item); + flag = false; + } + else + { + this.resolveList.SelectedAdd(item); + } + } + if (this.assetList.Count == 0) + { + ChangeSet changeSet = new ChangeSet("no files to resolve"); + ListItem listItem = this.resolveList.Add(null, changeSet.description, changeSet); + listItem.Dummy = true; + } + this.resolveList.Refresh(); + base.Repaint(); + } + private void OnGUI() + { + this.cancelled = false; + GUILayout.Label("Conflicting files to resolve", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect screenRect = new Rect(6f, 40f, base.position.width - 12f, base.position.height - 112f); + GUILayout.BeginArea(screenRect); + GUILayout.Box(string.Empty, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + GUILayout.EndArea(); + bool flag = this.resolveList.OnGUI(new Rect(screenRect.x + 2f, screenRect.y + 2f, screenRect.width - 4f, screenRect.height - 4f), true); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.enabled = (this.assetList.Count > 0); + GUILayout.Label("Resolve selection by:", new GUILayoutOption[0]); + if (GUILayout.Button("using local version", new GUILayoutOption[0])) + { + AssetList selectedAssets = this.resolveList.SelectedAssets; + Provider.Resolve(selectedAssets, ResolveMethod.UseMine).Wait(); + AssetDatabase.Refresh(); + base.Close(); + } + if (GUILayout.Button("using incoming version", new GUILayoutOption[0])) + { + AssetList selectedAssets2 = this.resolveList.SelectedAssets; + Provider.Resolve(selectedAssets2, ResolveMethod.UseTheirs).Wait(); + AssetDatabase.Refresh(); + base.Close(); + } + MergeMethod mergeMethod = MergeMethod.MergeNone; + if (GUILayout.Button("merging", new GUILayoutOption[0])) + { + mergeMethod = MergeMethod.MergeAll; + } + if (GUILayout.Button("merging non-conflicts", new GUILayoutOption[0])) + { + mergeMethod = MergeMethod.MergeNonConflicting; + } + if (mergeMethod != MergeMethod.MergeNone) + { + Task task = Provider.Merge(this.resolveList.SelectedAssets, mergeMethod); + task.Wait(); + if (task.success) + { + task = Provider.Resolve(task.assetList, ResolveMethod.UseMerged); + task.Wait(); + if (task.success) + { + task = Provider.Status(this.assetList); + task.Wait(); + this.DoOpen(task.assetList); + if (task.success && this.assetList.Count == 0) + { + base.Close(); + } + } + else + { + EditorUtility.DisplayDialog("Error resolving", "Error during resolve of files. Inspect log for details", "Close"); + AssetDatabase.Refresh(); + } + } + else + { + EditorUtility.DisplayDialog("Error merging", "Error during merge of files. Inspect log for details", "Close"); + AssetDatabase.Refresh(); + } + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.Space(12f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = true; + if (GUILayout.Button("Cancel", new GUILayoutOption[0])) + { + this.cancelled = true; + base.Close(); + } + GUILayout.EndHorizontal(); + GUILayout.Space(12f); + if (flag) + { + base.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor.VersionControl/WindowRevert.cs b/UnityEditor/UnityEditor.VersionControl/WindowRevert.cs new file mode 100644 index 00000000..d95904e5 --- /dev/null +++ b/UnityEditor/UnityEditor.VersionControl/WindowRevert.cs @@ -0,0 +1,103 @@ +using System; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor.VersionControl +{ + internal class WindowRevert : EditorWindow + { + private ListControl revertList = new ListControl(); + private AssetList assetList = new AssetList(); + public void OnEnable() + { + base.position = new Rect(100f, 100f, 700f, 230f); + base.minSize = new Vector2(700f, 230f); + this.revertList.ReadOnly = true; + } + public static void Open(ChangeSet change) + { + Task task = Provider.ChangeSetStatus(change); + task.Wait(); + WindowRevert.GetWindow().DoOpen(task.assetList); + } + public static void Open(AssetList assets) + { + Task task = Provider.Status(assets); + task.Wait(); + AssetList revert = task.assetList.Filter(true, new Asset.States[] + { + Asset.States.CheckedOutLocal, + Asset.States.DeletedLocal, + Asset.States.AddedLocal, + Asset.States.Missing + }); + WindowRevert.GetWindow().DoOpen(revert); + } + private static WindowRevert GetWindow() + { + return EditorWindow.GetWindow(true, "Version Control Revert"); + } + private void DoOpen(AssetList revert) + { + this.assetList = revert; + this.RefreshList(); + } + private void RefreshList() + { + this.revertList.Clear(); + foreach (Asset current in this.assetList) + { + this.revertList.Add(null, current.prettyPath, current); + } + if (this.assetList.Count == 0) + { + ChangeSet changeSet = new ChangeSet("no files to revert"); + ListItem listItem = this.revertList.Add(null, changeSet.description, changeSet); + listItem.Dummy = true; + } + this.revertList.Refresh(); + base.Repaint(); + } + private void OnGUI() + { + GUILayout.Label("Revert Files", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect screenRect = new Rect(6f, 40f, base.position.width - 12f, base.position.height - 82f); + GUILayout.BeginArea(screenRect); + GUILayout.Box(string.Empty, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + GUILayout.EndArea(); + this.revertList.OnGUI(new Rect(screenRect.x + 2f, screenRect.y + 2f, screenRect.width - 4f, screenRect.height - 4f), true); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Cancel", new GUILayoutOption[0])) + { + base.Close(); + } + if (this.assetList.Count > 0 && GUILayout.Button("Revert", new GUILayoutOption[0])) + { + foreach (Asset current in this.assetList) + { + if (current.path == EditorApplication.currentScene) + { + if (!EditorUtility.DisplayDialog("Revert open scene?", "You are about to revert your currently open scene:\n\n" + EditorApplication.currentScene + "\n\nContinuing will remove all unsaved changes.", "Continue", "Cancel")) + { + base.Close(); + return; + } + break; + } + } + Provider.Revert(this.assetList, RevertMode.Normal).Wait(); + WindowPending.UpdateAllWindows(); + AssetDatabase.Refresh(); + base.Close(); + } + GUILayout.EndHorizontal(); + GUILayout.Space(12f); + } + } +} diff --git a/UnityEditor/UnityEditor.VisualStudioIntegration/DefaultSolutionSynchronizationSettings.cs b/UnityEditor/UnityEditor.VisualStudioIntegration/DefaultSolutionSynchronizationSettings.cs new file mode 100644 index 00000000..cb04f140 --- /dev/null +++ b/UnityEditor/UnityEditor.VisualStudioIntegration/DefaultSolutionSynchronizationSettings.cs @@ -0,0 +1,170 @@ +using System; +namespace UnityEditor.VisualStudioIntegration +{ + internal class DefaultSolutionSynchronizationSettings : ISolutionSynchronizationSettings + { + public virtual int VisualStudioVersion + { + get + { + return 9; + } + } + public virtual string SolutionTemplate + { + get + { + return string.Join("\r\n", new string[] + { + "Microsoft Visual Studio Solution File, Format Version {0}", + "# Visual Studio 2008", + string.Empty, + "{1}", + "Global", + "\tGlobalSection(SolutionConfigurationPlatforms) = preSolution", + "\t\tDebug|Any CPU = Debug|Any CPU", + "\t\tRelease|Any CPU = Release|Any CPU", + "\tEndGlobalSection", + "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution", + "{2}", + "\tEndGlobalSection", + "\tGlobalSection(SolutionProperties) = preSolution", + "\t\tHideSolutionNode = FALSE", + "\tEndGlobalSection", + "\t{3}", + "EndGlobal", + string.Empty + }); + } + } + public virtual string SolutionProjectEntryTemplate + { + get + { + return string.Join("\r\n", new string[] + { + "Project(\"{{{0}}}\") = \"{1}\", \"{2}\", \"{{{3}}}\"", + "EndProject" + }); + } + } + public virtual string SolutionProjectConfigurationTemplate + { + get + { + return string.Join("\r\n", new string[] + { + "\t\t{{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", + "\t\t{{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", + "\t\t{{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", + "\t\t{{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU" + }); + } + } + public virtual string EditorAssemblyPath + { + get + { + return "/Managed/UnityEditor.dll"; + } + } + public virtual string EngineAssemblyPath + { + get + { + return "/Managed/UnityEngine.dll"; + } + } + public virtual string MonoLibFolder + { + get + { + return this.FrameworksPath() + "/Mono/lib/mono/unity/"; + } + } + public virtual string[] Defines + { + get + { + return new string[0]; + } + } + public virtual string GetProjectHeaderTemplate(ScriptingLanguage language) + { + return string.Join("\r\n", new string[] + { + "", + "", + " ", + "\tDebug", + "\tAnyCPU", + "\t{1}", + "\t2.0", + "\t{{{2}}}", + "\tLibrary", + "\tProperties", + "\t", + "\t{7}", + "\tv3.5", + "\t512", + "\tAssets", + " ", + " ", + "\ttrue", + "\tfull", + "\tfalse", + "\tTemp\\bin\\Debug\\", + "\tDEBUG;TRACE;{5}", + "\tprompt", + "\t4", + "\t0169", + " ", + " ", + "\tpdbonly", + "\ttrue", + "\tTemp\\bin\\Release\\", + "\tTRACE", + "\tprompt", + "\t4", + "\t0169", + " ", + " ", + "\t", + " ", + "\t", + "\t", + "\t", + "\t {3}", + "\t", + "\t", + "\t {4}", + "\t", + " ", + " ", + string.Empty + }); + } + public virtual string GetProjectFooterTemplate(ScriptingLanguage language) + { + return string.Join("\r\n", new string[] + { + " ", + " ", + " ", + " {0}", + "", + string.Empty + }); + } + protected virtual string FrameworksPath() + { + return string.Empty; + } + } +} diff --git a/UnityEditor/UnityEditor.VisualStudioIntegration/ISolutionSynchronizationSettings.cs b/UnityEditor/UnityEditor.VisualStudioIntegration/ISolutionSynchronizationSettings.cs new file mode 100644 index 00000000..7328f83b --- /dev/null +++ b/UnityEditor/UnityEditor.VisualStudioIntegration/ISolutionSynchronizationSettings.cs @@ -0,0 +1,41 @@ +using System; +namespace UnityEditor.VisualStudioIntegration +{ + internal interface ISolutionSynchronizationSettings + { + int VisualStudioVersion + { + get; + } + string SolutionTemplate + { + get; + } + string SolutionProjectEntryTemplate + { + get; + } + string SolutionProjectConfigurationTemplate + { + get; + } + string EditorAssemblyPath + { + get; + } + string EngineAssemblyPath + { + get; + } + string MonoLibFolder + { + get; + } + string[] Defines + { + get; + } + string GetProjectHeaderTemplate(ScriptingLanguage language); + string GetProjectFooterTemplate(ScriptingLanguage language); + } +} diff --git a/UnityEditor/UnityEditor.VisualStudioIntegration/ScriptingLanguage.cs b/UnityEditor/UnityEditor.VisualStudioIntegration/ScriptingLanguage.cs new file mode 100644 index 00000000..69b236ac --- /dev/null +++ b/UnityEditor/UnityEditor.VisualStudioIntegration/ScriptingLanguage.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.VisualStudioIntegration +{ + internal enum ScriptingLanguage + { + None, + Boo, + CSharp, + UnityScript + } +} diff --git a/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionGuidGenerator.cs b/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionGuidGenerator.cs new file mode 100644 index 00000000..418d632c --- /dev/null +++ b/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionGuidGenerator.cs @@ -0,0 +1,48 @@ +using System; +using System.Security.Cryptography; +using System.Text; +namespace UnityEditor.VisualStudioIntegration +{ + public static class SolutionGuidGenerator + { + public static string GuidForProject(string projectName) + { + return SolutionGuidGenerator.ComputeGuidHashFor(projectName + "salt"); + } + public static string GuidForSolution(string projectName) + { + return SolutionGuidGenerator.ComputeGuidHashFor(projectName); + } + private static string ComputeGuidHashFor(string input) + { + byte[] bs = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); + return SolutionGuidGenerator.HashAsGuid(SolutionGuidGenerator.HashToString(bs)); + } + private static string HashAsGuid(string hash) + { + string text = string.Concat(new string[] + { + hash.Substring(0, 8), + "-", + hash.Substring(8, 4), + "-", + hash.Substring(12, 4), + "-", + hash.Substring(16, 4), + "-", + hash.Substring(20, 12) + }); + return text.ToUpper(); + } + private static string HashToString(byte[] bs) + { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < bs.Length; i++) + { + byte b = bs[i]; + stringBuilder.Append(b.ToString("x2")); + } + return stringBuilder.ToString(); + } + } +} diff --git a/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionSynchronizer.cs b/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionSynchronizer.cs new file mode 100644 index 00000000..3c85b6c8 --- /dev/null +++ b/UnityEditor/UnityEditor.VisualStudioIntegration/SolutionSynchronizer.cs @@ -0,0 +1,547 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using UnityEditor.Scripting; +using UnityEditorInternal; +namespace UnityEditor.VisualStudioIntegration +{ + internal class SolutionSynchronizer + { + public static readonly ISolutionSynchronizationSettings DefaultSynchronizationSettings = new DefaultSolutionSynchronizationSettings(); + private static readonly string WindowsNewline = "\r\n"; + private static readonly Dictionary SupportedExtensions = new Dictionary + { + + { + ".cs", + ScriptingLanguage.CSharp + }, + + { + ".js", + ScriptingLanguage.UnityScript + }, + + { + ".boo", + ScriptingLanguage.Boo + }, + + { + ".xml", + ScriptingLanguage.None + }, + + { + ".shader", + ScriptingLanguage.None + }, + + { + ".compute", + ScriptingLanguage.None + }, + + { + ".cginc", + ScriptingLanguage.None + }, + + { + ".glslinc", + ScriptingLanguage.None + }, + + { + ".txt", + ScriptingLanguage.None + }, + + { + ".fnt", + ScriptingLanguage.None + }, + + { + ".cd", + ScriptingLanguage.None + }, + + { + "cs", + ScriptingLanguage.CSharp + }, + + { + "js", + ScriptingLanguage.UnityScript + }, + + { + "boo", + ScriptingLanguage.Boo + }, + + { + "xml", + ScriptingLanguage.None + }, + + { + "shader", + ScriptingLanguage.None + }, + + { + "compute", + ScriptingLanguage.None + }, + + { + "cginc", + ScriptingLanguage.None + }, + + { + "glslinc", + ScriptingLanguage.None + }, + + { + "txt", + ScriptingLanguage.None + }, + + { + "fnt", + ScriptingLanguage.None + }, + + { + "cd", + ScriptingLanguage.None + } + }; + private static readonly Dictionary ProjectExtensions = new Dictionary + { + + { + ScriptingLanguage.Boo, + ".booproj" + }, + + { + ScriptingLanguage.CSharp, + ".csproj" + }, + + { + ScriptingLanguage.UnityScript, + ".unityproj" + }, + + { + ScriptingLanguage.None, + ".csproj" + } + }; + private static readonly Regex _MonoDevelopPropertyHeader = new Regex("^\\s*GlobalSection\\(MonoDevelopProperties.*\\)"); + public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; + private readonly string _projectDirectory; + private readonly ISolutionSynchronizationSettings _settings; + private readonly string _projectName; + private readonly string vsstub = "-vs"; + private Dictionary _pathCache; + private static readonly string DefaultMonoDevelopSolutionProperties = string.Join("\r\n", new string[] + { + "GlobalSection(MonoDevelopProperties) = preSolution", + "\t\tStartupItem = Assembly-CSharp.csproj", + "\t\tPolicies = $0", + "\t\t$0.TextStylePolicy = $1", + "\t\t$1.inheritsSet = null", + "\t\t$1.scope = text/x-csharp", + "\t\t$0.CSharpFormattingPolicy = $2", + "\t\t$2.inheritsSet = Mono", + "\t\t$2.inheritsScope = text/x-csharp", + "\t\t$2.scope = text/x-csharp", + "\t\t$0.TextStylePolicy = $3", + "\t\t$3.FileWidth = 120", + "\t\t$3.TabWidth = 4", + "\t\t$3.IndentWidth = 4", + "\t\t$3.EolMarker = Unix", + "\t\t$3.inheritsSet = Mono", + "\t\t$3.inheritsScope = text/plain", + "\t\t$3.scope = text/plain", + "\tEndGlobalSection" + }); + public static readonly Regex scriptReferenceExpression = new Regex("^Library.ScriptAssemblies.(?Assembly-(?[^-]+)(?-Editor)?(?-firstpass)?).dll$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public SolutionSynchronizer(string projectDirectory, ISolutionSynchronizationSettings settings) + { + this._projectDirectory = projectDirectory; + this._settings = settings; + this._projectName = Path.GetFileName(this._projectDirectory); + this._pathCache = new Dictionary(); + } + public SolutionSynchronizer(string projectDirectory) : this(projectDirectory, SolutionSynchronizer.DefaultSynchronizationSettings) + { + } + public bool ShouldFileBePartOfSolution(string file) + { + string extension = Path.GetExtension(file); + return extension == ".dll" || SolutionSynchronizer.SupportedExtensions.ContainsKey(extension); + } + public bool ProjectExists(MonoIsland island) + { + return File.Exists(this.ProjectFile(island, false)); + } + public bool SolutionExists() + { + return File.Exists(this.SolutionFile(false)); + } + private static void DumpIsland(MonoIsland island) + { + Console.WriteLine("{0} ({1})", island._output, island._classlib_profile); + Console.WriteLine("Files: "); + Console.WriteLine(string.Join("\n", island._files)); + Console.WriteLine("References: "); + Console.WriteLine(string.Join("\n", island._references)); + Console.WriteLine(string.Empty); + } + public bool SyncIfNeeded(IEnumerable affectedFiles) + { + if (this.SolutionExists() && affectedFiles.Any(new Func(this.ShouldFileBePartOfSolution))) + { + this.Sync(); + return true; + } + return false; + } + public void Sync() + { + IEnumerable enumerable = + from i in InternalEditorUtility.GetMonoIslands() + where 0 < i._files.Length + select i; + string otherAssetsProjectPart = this.GenerateAllAssetProjectPart(); + this.SyncSolution(enumerable); + foreach (MonoIsland current in enumerable) + { + this.SyncProject(current, otherAssetsProjectPart); + } + } + private string GenerateAllAssetProjectPart() + { + StringBuilder stringBuilder = new StringBuilder(); + string[] allAssetPaths = AssetDatabase.GetAllAssetPaths(); + for (int i = 0; i < allAssetPaths.Length; i++) + { + string text = allAssetPaths[i]; + string extension = Path.GetExtension(text); + if (SolutionSynchronizer.SupportedExtensions.ContainsKey(extension) && SolutionSynchronizer.SupportedExtensions[extension] == ScriptingLanguage.None) + { + stringBuilder.AppendFormat(" {1}", this.EscapedRelativePathFor(text), SolutionSynchronizer.WindowsNewline); + } + } + return stringBuilder.ToString(); + } + private void SyncProject(MonoIsland island, string otherAssetsProjectPart) + { + SolutionSynchronizer.SyncFileIfNotChanged(this.ProjectFile(island, false), this.ProjectText(island, false, otherAssetsProjectPart)); + SolutionSynchronizer.SyncFileIfNotChanged(this.ProjectFile(island, true), this.ProjectText(island, true, otherAssetsProjectPart)); + } + private static void SyncFileIfNotChanged(string filename, string newContents) + { + if (File.Exists(filename) && newContents == File.ReadAllText(filename)) + { + return; + } + File.WriteAllText(filename, newContents); + } + private string ProjectText(MonoIsland island, bool forVisualStudio, string allAssetsProject) + { + StringBuilder stringBuilder = new StringBuilder(this.ProjectHeader(island)); + List list = new List(); + List list2 = new List(); + string[] files = island._files; + for (int i = 0; i < files.Length; i++) + { + string text = files[i]; + string b = Path.GetExtension(text).ToLower(); + string text2 = (!Path.IsPathRooted(text)) ? Path.Combine(this._projectDirectory, text) : text; + if (".dll" != b) + { + string arg = "Compile"; + stringBuilder.AppendFormat(" <{0} Include=\"{1}\" />{2}", arg, this.EscapedRelativePathFor(text2), SolutionSynchronizer.WindowsNewline); + } + else + { + list.Add(text2); + } + } + stringBuilder.Append(allAssetsProject); + foreach (string current in list.Union(island._references)) + { + if (!current.EndsWith("/UnityEditor.dll") && !current.EndsWith("/UnityEngine.dll") && !current.EndsWith("\\UnityEditor.dll") && !current.EndsWith("\\UnityEngine.dll")) + { + Match match; + if ((match = SolutionSynchronizer.scriptReferenceExpression.Match(current)) != null && match.Success && (!forVisualStudio || (int)Enum.Parse(typeof(ScriptingLanguage), match.Groups["language"].Value, true) == 2)) + { + list2.Add(match); + } + else + { + string text3 = (!Path.IsPathRooted(current)) ? Path.Combine(this._projectDirectory, current) : current; + if (AssemblyHelper.IsManagedAssembly(text3)) + { + if (!AssemblyHelper.IsInternalAssembly(text3)) + { + text3 = text3.Replace("\\", "/"); + text3 = text3.Replace("\\\\", "/"); + stringBuilder.AppendFormat(" {1}", Path.GetFileNameWithoutExtension(text3), SolutionSynchronizer.WindowsNewline); + stringBuilder.AppendFormat(" {0}{1}", text3, SolutionSynchronizer.WindowsNewline); + stringBuilder.AppendFormat(" {0}", SolutionSynchronizer.WindowsNewline); + } + } + } + } + } + if (0 < list2.Count) + { + stringBuilder.AppendLine(" "); + stringBuilder.AppendLine(" "); + foreach (Match current2 in list2) + { + string text4 = current2.Groups["project"].Value; + if (forVisualStudio) + { + text4 += this.vsstub; + } + stringBuilder.AppendFormat(" {2}", text4, SolutionSynchronizer.GetProjectExtension((ScriptingLanguage)((int)Enum.Parse(typeof(ScriptingLanguage), current2.Groups["language"].Value, true))), SolutionSynchronizer.WindowsNewline); + stringBuilder.AppendFormat(" {{{0}}}", this.ProjectGuid(Path.Combine("Temp", current2.Groups["project"].Value + ".dll")), SolutionSynchronizer.WindowsNewline); + stringBuilder.AppendFormat(" {0}", text4, SolutionSynchronizer.WindowsNewline); + stringBuilder.AppendLine(" "); + } + } + stringBuilder.Append(this.ProjectFooter(island)); + return stringBuilder.ToString(); + } + private string GetProperDirectoryCapitalization(DirectoryInfo dirInfo) + { + if (dirInfo.FullName == this._projectDirectory) + { + return dirInfo.FullName; + } + if (this._pathCache.ContainsKey(dirInfo.FullName)) + { + return this._pathCache[dirInfo.FullName]; + } + DirectoryInfo parent = dirInfo.Parent; + if (parent == null) + { + return dirInfo.FullName.ToUpperInvariant(); + } + string text = Path.Combine(this.GetProperDirectoryCapitalization(parent), parent.GetDirectories().First((DirectoryInfo dir) => dir.Name.Equals(dirInfo.Name, StringComparison.OrdinalIgnoreCase)).Name); + this._pathCache[dirInfo.FullName] = text; + return text; + } + public string ProjectFile(MonoIsland island, bool forVisualStudio) + { + ScriptingLanguage key = SolutionSynchronizer.SupportedExtensions[island.GetExtensionOfSourceFiles()]; + string arg = (!forVisualStudio) ? string.Empty : this.vsstub; + return Path.Combine(this._projectDirectory, string.Format("{0}{1}{2}", Path.GetFileNameWithoutExtension(island._output), arg, SolutionSynchronizer.ProjectExtensions[key])); + } + internal string SolutionFile(bool onlyCSharp) + { + string arg = (!onlyCSharp) ? string.Empty : "-csharp"; + return Path.Combine(this._projectDirectory, string.Format("{0}{1}.sln", this._projectName, arg)); + } + private string AssetsFolder() + { + return Path.Combine(this._projectDirectory, "Assets"); + } + private string ProjectHeader(MonoIsland island) + { + string text = "4.0"; + string text2 = "10.0.20506"; + ScriptingLanguage language = SolutionSynchronizer.SupportedExtensions[island.GetExtensionOfSourceFiles()]; + if (this._settings.VisualStudioVersion == 9) + { + text = "3.5"; + text2 = "9.0.21022"; + } + return string.Format(this._settings.GetProjectHeaderTemplate(language), new object[] + { + text, + text2, + this.ProjectGuid(island._output), + this._settings.EngineAssemblyPath, + this._settings.EditorAssemblyPath, + string.Join(";", this._settings.Defines.Union(island._defines).ToArray()), + SolutionSynchronizer.MSBuildNamespaceUri, + Path.GetFileNameWithoutExtension(island._output) + }); + } + private void SyncSolution(IEnumerable islands) + { + SolutionSynchronizer.SyncFileIfNotChanged(this.SolutionFile(false), this.SolutionText(islands, false)); + SolutionSynchronizer.SyncFileIfNotChanged(this.SolutionFile(true), this.SolutionText(islands, true)); + } + private string SolutionText(IEnumerable islands, bool onlyCSharp) + { + string text = "11.00"; + if (this._settings.VisualStudioVersion == 9) + { + text = "10.00"; + } + IEnumerable enumerable = + from i in islands + where !onlyCSharp || ScriptingLanguage.CSharp == SolutionSynchronizer.SupportedExtensions[i.GetExtensionOfSourceFiles()] + select i; + string projectEntries = this.GetProjectEntries(enumerable, onlyCSharp); + string text2 = string.Join(SolutionSynchronizer.WindowsNewline, ( + from i in enumerable + select this.GetProjectActiveConfigurations(this.ProjectGuid(i._output))).ToArray()); + return string.Format(this._settings.SolutionTemplate, new object[] + { + text, + projectEntries, + text2, + this.ReadExistingMonoDevelopSolutionProperties() + }); + } + private string GetProjectEntries(IEnumerable islands, bool forVisualStudio) + { + IEnumerable source = + from i in islands + select string.Format(SolutionSynchronizer.DefaultSynchronizationSettings.SolutionProjectEntryTemplate, new object[] + { + this.SolutionGuid(), + this._projectName, + Path.GetFileName(this.ProjectFile(i, forVisualStudio)), + this.ProjectGuid(i._output) + }); + return string.Join(SolutionSynchronizer.WindowsNewline, source.ToArray()); + } + private string GetProjectActiveConfigurations(string projectGuid) + { + return string.Format(SolutionSynchronizer.DefaultSynchronizationSettings.SolutionProjectConfigurationTemplate, projectGuid); + } + private string EscapedRelativePathFor(FileSystemInfo file) + { + return this.EscapedRelativePathFor(file.FullName); + } + private string EscapedRelativePathFor(string file) + { + string value = this._projectDirectory.Replace("/", "\\"); + file = file.Replace("/", "\\"); + return SecurityElement.Escape((!file.StartsWith(value)) ? file : file.Substring(this._projectDirectory.Length + 1)); + } + private string ProjectGuid(string assembly) + { + return SolutionGuidGenerator.GuidForProject(this._projectName + Path.GetFileNameWithoutExtension(assembly)); + } + private string SolutionGuid() + { + return SolutionGuidGenerator.GuidForSolution(this._projectName); + } + private string ProjectFooter(MonoIsland island) + { + ScriptingLanguage language = SolutionSynchronizer.SupportedExtensions[island.GetExtensionOfSourceFiles()]; + return string.Format(this._settings.GetProjectFooterTemplate(language), this.ReadExistingMonoDevelopProjectProperties(island)); + } + private string ReadExistingMonoDevelopSolutionProperties() + { + if (!this.SolutionExists()) + { + return SolutionSynchronizer.DefaultMonoDevelopSolutionProperties; + } + string[] array; + try + { + array = File.ReadAllLines(this.SolutionFile(false)); + } + catch (IOException) + { + string defaultMonoDevelopSolutionProperties = SolutionSynchronizer.DefaultMonoDevelopSolutionProperties; + return defaultMonoDevelopSolutionProperties; + } + StringBuilder stringBuilder = new StringBuilder(); + bool flag = false; + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text = array2[i]; + if (SolutionSynchronizer._MonoDevelopPropertyHeader.IsMatch(text)) + { + flag = true; + } + if (flag) + { + stringBuilder.AppendFormat("{0}{1}", text, SolutionSynchronizer.WindowsNewline); + if (text.Contains("EndGlobalSection")) + { + flag = false; + } + } + } + if (0 < stringBuilder.Length) + { + return stringBuilder.ToString(); + } + return SolutionSynchronizer.DefaultMonoDevelopSolutionProperties; + } + private string ReadExistingMonoDevelopProjectProperties(MonoIsland island) + { + if (!this.ProjectExists(island)) + { + return string.Empty; + } + XmlDocument xmlDocument = new XmlDocument(); + XmlNamespaceManager xmlNamespaceManager; + try + { + xmlDocument.Load(this.ProjectFile(island, false)); + xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable); + xmlNamespaceManager.AddNamespace("msb", SolutionSynchronizer.MSBuildNamespaceUri); + } + catch (Exception ex) + { + if (ex is IOException || ex is XmlException) + { + string empty = string.Empty; + return empty; + } + throw; + } + XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/msb:Project/msb:ProjectExtensions", xmlNamespaceManager); + if (xmlNodeList.Count == 0) + { + return string.Empty; + } + StringBuilder stringBuilder = new StringBuilder(); + foreach (XmlNode xmlNode in xmlNodeList) + { + stringBuilder.AppendLine(xmlNode.OuterXml); + } + return stringBuilder.ToString(); + } + [Obsolete("Use AssemblyHelper.IsManagedAssembly")] + public static bool IsManagedAssembly(string file) + { + return AssemblyHelper.IsManagedAssembly(file); + } + public static string GetProjectExtension(ScriptingLanguage language) + { + if (!SolutionSynchronizer.ProjectExtensions.ContainsKey(language)) + { + throw new ArgumentException("Unsupported language", "language"); + } + return SolutionSynchronizer.ProjectExtensions[language]; + } + } +} diff --git a/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs new file mode 100644 index 00000000..19707149 --- /dev/null +++ b/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using UnityEditorInternal; +namespace UnityEditor.WindowsStandalone +{ + internal class WindowsStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider + { + private readonly bool m_DevelopmentBuild; + public override bool emitNullChecks + { + get + { + return this.m_DevelopmentBuild; + } + } + public override bool enableStackTraces + { + get + { + return this.m_DevelopmentBuild; + } + } + public override string nativeLibraryFileName + { + get + { + return "UserAssembly.dll"; + } + } + public override string staticLibraryExtension + { + get + { + return "lib"; + } + } + internal WindowsStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder, bool developmentBuild) : base(target, Path.Combine(dataFolder, "Libraries")) + { + this.m_DevelopmentBuild = developmentBuild; + } + public override INativeCompiler CreateNativeCompiler() + { + BuildTarget target = this.target; + ICompilerSettings settings; + if (target != BuildTarget.StandaloneWindows) + { + if (target != BuildTarget.StandaloneWindows64) + { + throw new ArgumentException("Unexpected target: " + this.target); + } + settings = new MSVCCompilerSettingsx64(); + } + else + { + settings = new MSVCCompilerSettingsx86(); + } + return new MSVCCompiler(settings, base.GetFileInPackageOrDefault("libil2cpp/include/libil2cpp.def")); + } + } +} diff --git a/UnityEditor/UnityEditor.csproj b/UnityEditor/UnityEditor.csproj new file mode 100644 index 00000000..6e78a15b --- /dev/null +++ b/UnityEditor/UnityEditor.csproj @@ -0,0 +1,1098 @@ + + + + {A273AAF0-2CB5-491E-9C0D-D66717004282} + Debug + AnyCPU + Library + UnityEditor + v4.0 + 4 + + + + AnyCPU + + + bin\Debug\ + true + full + false + + + bin\Release\ + true + pdbonly + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/UnityEditor/UnityEditor/AInfo.cs b/UnityEditor/UnityEditor/AInfo.cs new file mode 100644 index 00000000..7f75f7c4 --- /dev/null +++ b/UnityEditor/UnityEditor/AInfo.cs @@ -0,0 +1,60 @@ +using System; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AInfo : IComparable, IEquatable + { + public enum Flags + { + kHasIcon = 1, + kHasGizmo + } + public bool m_IconEnabled; + public bool m_GizmoEnabled; + public int m_ClassID; + public string m_ScriptClass; + public string m_DisplayText; + public int m_Flags; + public AInfo(bool gizmoEnabled, bool iconEnabled, int flags, int classID, string scriptClass) + { + this.m_GizmoEnabled = gizmoEnabled; + this.m_IconEnabled = iconEnabled; + this.m_ClassID = classID; + this.m_ScriptClass = scriptClass; + this.m_Flags = flags; + if (this.m_ScriptClass == string.Empty) + { + this.m_DisplayText = BaseObjectTools.ClassIDToString(this.m_ClassID); + } + else + { + this.m_DisplayText = this.m_ScriptClass; + } + } + private bool IsBitSet(byte b, int pos) + { + return ((int)b & 1 << pos) != 0; + } + public bool HasGizmo() + { + return (this.m_Flags & 2) > 0; + } + public bool HasIcon() + { + return (this.m_Flags & 1) > 0; + } + public int CompareTo(object obj) + { + AInfo aInfo = obj as AInfo; + if (aInfo != null) + { + return this.m_DisplayText.CompareTo(aInfo.m_DisplayText); + } + throw new ArgumentException("Object is not an AInfo"); + } + public bool Equals(AInfo other) + { + return this.m_ClassID == other.m_ClassID && this.m_ScriptClass == other.m_ScriptClass; + } + } +} diff --git a/UnityEditor/UnityEditor/ASCommitWindow.cs b/UnityEditor/UnityEditor/ASCommitWindow.cs new file mode 100644 index 00000000..8d4b445c --- /dev/null +++ b/UnityEditor/UnityEditor/ASCommitWindow.cs @@ -0,0 +1,1411 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASCommitWindow + { + private class Constants + { + public GUIStyle box = "OL Box"; + public GUIStyle entrySelected = "ServerUpdateChangesetOn"; + public GUIStyle serverChangeCount = "ServerChangeCount"; + public GUIStyle title = "OL title"; + public GUIStyle element = "OL elem"; + public GUIStyle header = "OL header"; + public GUIStyle button = "Button"; + public GUIStyle serverUpdateInfo = "ServerUpdateInfo"; + public GUIStyle wwText = "AS TextArea"; + public GUIStyle errorLabel = "ErrorLabel"; + public GUIStyle dropDown = "MiniPullDown"; + public GUIStyle bigButton = "LargeButton"; + } + private const int listLenghts = 20; + private const int widthToHideButtons = 432; + private bool wasHidingButtons; + private bool resetKeyboardControl; + private static ASCommitWindow.Constants constants; + private ParentViewState pv1state = new ParentViewState(); + private ParentViewState pv2state = new ParentViewState(); + private bool pv1hasSelection; + private bool pv2hasSelection; + private bool somethingDiscardableSelected; + private bool mySelection; + private string[] commitMessageList; + private string[] dropDownMenuItems = new string[] + { + string.Empty, + string.Empty, + "Compare", + "Compare Binary", + string.Empty, + "Discard" + }; + private string[] guidsToTransferToTheRightSide; + private string dragTitle = string.Empty; + private Vector2 iconSize = new Vector2(16f, 16f); + private SplitterState horSplit = new SplitterState(new float[] + { + 50f, + 50f + }, new int[] + { + 50, + 50 + }, null); + private SplitterState vertSplit = new SplitterState(new float[] + { + 60f, + 30f + }, new int[] + { + 32, + 64 + }, null); + internal string description = string.Empty; + private string totalChanges; + private ASMainWindow parentWin; + private bool initialUpdate; + private Vector2 scrollPos = Vector2.zero; + internal bool lastTransferMovedDependencies; + internal int lastRevertSelectionChanged = -1; + internal int showReinitedWarning = -1; + private static List s_AssetGuids; + private static string s_Callback; + public ASCommitWindow(ASMainWindow parentWin, string[] guidsToTransfer) + { + this.guidsToTransferToTheRightSide = guidsToTransfer; + this.parentWin = parentWin; + this.initialUpdate = true; + } + internal void AssetItemsToParentViews() + { + this.pv1state.Clear(); + this.pv2state.Clear(); + this.pv1state.AddAssetItems(this.parentWin.sharedCommits); + this.pv1state.AddAssetItems(this.parentWin.sharedDeletedItems); + this.pv1state.lv = new ListViewState(0); + this.pv2state.lv = new ListViewState(0); + this.pv1state.SetLineCount(); + this.pv2state.SetLineCount(); + if (this.pv1state.lv.totalRows == 0) + { + this.parentWin.Reinit(); + return; + } + this.pv1state.selectedItems = new bool[this.pv1state.lv.totalRows]; + this.pv2state.selectedItems = new bool[this.pv1state.lv.totalRows]; + int num = 0; + for (int i = 0; i < this.parentWin.sharedCommits.Length; i++) + { + if (this.parentWin.sharedCommits[i].assetIsDir != 0) + { + num++; + } + } + for (int j = 0; j < this.parentWin.sharedDeletedItems.Length; j++) + { + if (this.parentWin.sharedDeletedItems[j].assetIsDir != 0) + { + num++; + } + } + this.totalChanges = (this.pv1state.lv.totalRows - this.pv1state.GetFoldersCount() + num).ToString() + " Local Changes"; + this.GetPersistedData(); + } + internal void Reinit(bool lastActionsResult) + { + this.parentWin.sharedCommits = ASCommitWindow.GetCommits(); + this.parentWin.sharedDeletedItems = AssetServer.GetLocalDeletedItems(); + AssetServer.ClearRefreshCommit(); + this.AssetItemsToParentViews(); + } + internal void Update() + { + this.SetPersistedData(); + this.AssetItemsToParentViews(); + this.GetPersistedData(); + } + internal void CommitFinished(bool actionResult) + { + if (actionResult) + { + AssetServer.ClearCommitPersistentData(); + this.parentWin.Reinit(); + } + else + { + this.parentWin.Repaint(); + } + } + internal void InitiateReinit() + { + if (this.parentWin.CommitNeedsRefresh()) + { + if (!this.initialUpdate) + { + this.SetPersistedData(); + } + else + { + this.initialUpdate = false; + } + this.Reinit(true); + } + else + { + if (this.initialUpdate) + { + this.AssetItemsToParentViews(); + this.initialUpdate = false; + } + else + { + this.SetPersistedData(); + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBReinitCommitWindow"); + AssetServer.DoRefreshAssetsOnNextTick(); + } + } + } + private void GetPersistedData() + { + this.description = AssetServer.GetLastCommitMessage(); + string[] commitSelectionGUIDs; + if (this.guidsToTransferToTheRightSide != null && this.guidsToTransferToTheRightSide.Length != 0) + { + commitSelectionGUIDs = this.guidsToTransferToTheRightSide; + this.guidsToTransferToTheRightSide = null; + } + else + { + commitSelectionGUIDs = AssetServer.GetCommitSelectionGUIDs(); + } + int i = 0; + ParentViewFolder[] folders = this.pv1state.folders; + for (int j = 0; j < folders.Length; j++) + { + ParentViewFolder parentViewFolder = folders[j]; + this.pv1state.selectedItems[i++] = (((IList)commitSelectionGUIDs).Contains(parentViewFolder.guid) && AssetServer.IsGUIDValid(parentViewFolder.guid) != 0); + ParentViewFile[] files = parentViewFolder.files; + for (int k = 0; k < files.Length; k++) + { + ParentViewFile parentViewFile = files[k]; + this.pv1state.selectedItems[i++] = (((IList)commitSelectionGUIDs).Contains(parentViewFile.guid) && AssetServer.IsGUIDValid(parentViewFile.guid) != 0); + } + } + this.DoTransferAll(this.pv1state, this.pv2state, this.pv1state.selectedFolder, this.pv1state.selectedFile); + this.commitMessageList = InternalEditorUtility.GetEditorSettingsList("ASCommitMsgs", 20); + for (i = 0; i < this.commitMessageList.Length; i++) + { + this.commitMessageList[i] = this.commitMessageList[i].Replace('/', '?').Replace('%', '?'); + } + } + private void SetPersistedData() + { + AssetServer.SetLastCommitMessage(this.description); + this.AddToCommitMessageHistory(this.description); + List list = new List(); + ParentViewFolder[] folders = this.pv2state.folders; + for (int i = 0; i < folders.Length; i++) + { + ParentViewFolder parentViewFolder = folders[i]; + if (AssetServer.IsGUIDValid(parentViewFolder.guid) != 0) + { + list.Add(parentViewFolder.guid); + } + ParentViewFile[] files = parentViewFolder.files; + for (int j = 0; j < files.Length; j++) + { + ParentViewFile parentViewFile = files[j]; + if (AssetServer.IsGUIDValid(parentViewFile.guid) != 0) + { + list.Add(parentViewFile.guid); + } + } + } + AssetServer.SetCommitSelectionGUIDs(list.ToArray()); + } + internal void OnClose() + { + this.SetPersistedData(); + } + private List GetSelectedItems() + { + this.pv1hasSelection = this.pv1state.HasTrue(); + this.pv2hasSelection = this.pv2state.HasTrue(); + List parentViewSelectedItems = ASCommitWindow.GetParentViewSelectedItems((!this.pv2hasSelection) ? this.pv1state : this.pv2state, true, false); + parentViewSelectedItems.Remove(AssetServer.GetRootGUID()); + return parentViewSelectedItems; + } + private void MySelectionToGlobalSelection() + { + this.mySelection = true; + this.somethingDiscardableSelected = ASCommitWindow.SomethingDiscardableSelected((!this.pv2hasSelection) ? this.pv1state : this.pv2state); + List selectedItems = this.GetSelectedItems(); + if (selectedItems.Count > 0) + { + AssetServer.SetSelectionFromGUID(selectedItems[0]); + } + } + internal static bool DoShowDiff(List selectedAssets, bool binary) + { + List list = new List(); + List list2 = new List(); + for (int i = 0; i < selectedAssets.Count; i++) + { + int ver = -1; + int num = AssetServer.GetWorkingItemChangeset(selectedAssets[i]); + num = AssetServer.GetServerItemChangeset(selectedAssets[i], num); + if (AssetServer.IsItemDeleted(selectedAssets[i])) + { + ver = -2; + } + if (num == -1) + { + num = -2; + } + list.Add(selectedAssets[i]); + list2.Add(new CompareInfo(num, ver, (!binary) ? 0 : 1, (!binary) ? 1 : 0)); + } + if (list.Count != 0) + { + AssetServer.CompareFiles(list.ToArray(), list2.ToArray()); + return true; + } + return false; + } + internal static bool IsDiscardableAsset(string guid, ChangeFlags changeFlags) + { + return AssetServer.IsConstantGUID(guid) == 0 || (!ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Created) && !ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Undeleted)); + } + internal static List GetParentViewSelectedItems(ParentViewState state, bool includeFolders, bool excludeUndiscardableOnes) + { + List list = new List(); + int num = 0; + for (int i = 0; i < state.folders.Length; i++) + { + ParentViewFolder parentViewFolder = state.folders[i]; + bool flag = true; + bool flag2 = true; + int num2 = num++; + int count = list.Count; + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + if (state.selectedItems[num]) + { + if (!excludeUndiscardableOnes || ASCommitWindow.IsDiscardableAsset(parentViewFolder.files[j].guid, parentViewFolder.files[j].changeFlags)) + { + list.Add(parentViewFolder.files[j].guid); + flag = false; + } + } + else + { + flag2 = false; + } + num++; + } + if (includeFolders && state.selectedItems[num2] && (flag || flag2) && AssetServer.IsGUIDValid(parentViewFolder.guid) != 0 && count <= list.Count) + { + list.Insert(count, parentViewFolder.guid); + } + } + return list; + } + internal static void DoRevert(List assetGuids, string callback) + { + if (assetGuids.Count == 0) + { + return; + } + ASCommitWindow.s_AssetGuids = assetGuids; + ASCommitWindow.s_Callback = callback; + AssetServer.SetAfterActionFinishedCallback("ASCommitWindow", "DoRevertAfterDialog"); + AssetServer.ShowDialogOnNextTick("Discard changes", "Are you really sure you want to discard selected changes?", "Discard", "Cancel"); + } + internal static void DoRevertAfterDialog(bool result) + { + if (result) + { + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", ASCommitWindow.s_Callback); + AssetServer.DoUpdateWithoutConflictResolutionOnNextTick(ASCommitWindow.s_AssetGuids.ToArray()); + } + } + internal static bool MarkSelected(ParentViewState activeState, List guids) + { + int num = 0; + bool flag = false; + ParentViewFolder[] folders = activeState.folders; + for (int i = 0; i < folders.Length; i++) + { + ParentViewFolder parentViewFolder = folders[i]; + bool flag2 = guids.Contains(parentViewFolder.guid); + activeState.selectedItems[num++] = flag2; + flag |= flag2; + ParentViewFile[] files = parentViewFolder.files; + for (int j = 0; j < files.Length; j++) + { + ParentViewFile parentViewFile = files[j]; + flag2 = guids.Contains(parentViewFile.guid); + activeState.selectedItems[num++] = flag2; + flag |= flag2; + } + } + return flag; + } + internal static AssetsItem[] GetCommits() + { + return AssetServer.BuildAllExportPackageAssetListAssetsItems(); + } + internal void AddToCommitMessageHistory(string description) + { + if (description.Trim() != string.Empty) + { + if (ArrayUtility.Contains(this.commitMessageList, description)) + { + ArrayUtility.Remove(ref this.commitMessageList, description); + } + ArrayUtility.Insert(ref this.commitMessageList, 0, description); + InternalEditorUtility.SaveEditorSettingsList("ASCommitMsgs", this.commitMessageList, 20); + } + } + internal static bool ShowDiscardWarning() + { + return EditorUtility.DisplayDialog("Discard changes", "More items will be discarded then initially selected. Dependencies of selected items where all marked in commit window. Please review.", "Discard", "Cancel"); + } + internal bool CanCommit() + { + return this.pv2state.folders.Length != 0; + } + internal string[] GetItemsToCommit() + { + List list = new List(); + for (int i = 0; i < this.pv2state.folders.Length; i++) + { + ParentViewFolder parentViewFolder = this.pv2state.folders[i]; + if (AssetServer.IsGUIDValid(parentViewFolder.guid) != 0) + { + list.Add(parentViewFolder.guid); + } + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + if (AssetServer.IsGUIDValid(parentViewFolder.files[j].guid) != 0) + { + list.Add(parentViewFolder.files[j].guid); + } + } + } + return list.ToArray(); + } + internal void DoCommit() + { + if (AssetServer.GetRefreshCommit()) + { + this.SetPersistedData(); + this.InitiateReinit(); + this.showReinitedWarning = 2; + this.parentWin.Repaint(); + GUIUtility.ExitGUI(); + } + if (this.description == string.Empty && !EditorUtility.DisplayDialog("Commit without description", "Are you sure you want to commit with empty commit description message?", "Commit", "Cancel")) + { + return; + } + string[] itemsToCommit = this.GetItemsToCommit(); + this.SetPersistedData(); + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBCommitFinished"); + AssetServer.DoCommitOnNextTick(this.description, itemsToCommit); + GUIUtility.ExitGUI(); + } + private bool TransferDependentParentFolders(ref List guidsOfFoldersToRemove, string guid, bool leftToRight) + { + bool result = false; + if (leftToRight) + { + while (AssetServer.IsGUIDValid(guid = AssetServer.GetParentGUID(guid, -1)) != 0) + { + if (!ASCommitWindow.AllFolderWouldBeMovedAnyway((!leftToRight) ? this.pv2state : this.pv1state, guid)) + { + int num = ASCommitWindow.IndexOfFolderWithGUID(this.pv1state.folders, guid); + int num2 = ASCommitWindow.IndexOfFolderWithGUID(this.pv2state.folders, guid); + if (num != -1 || num2 != -1) + { + if (num != -1 && num2 == -1) + { + ChangeFlags changeFlags = this.pv1state.folders[num].changeFlags; + if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Undeleted) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Created) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Moved)) + { + ArrayUtility.Add(ref this.pv2state.folders, this.pv1state.folders[num].CloneWithoutFiles()); + result = true; + if (this.pv1state.folders[num].files.Length == 0) + { + this.AddFolderToRemove(ref guidsOfFoldersToRemove, this.pv1state.folders[num].guid); + } + } + } + } + } + } + } + else + { + ChangeFlags changeFlags2 = this.pv1state.folders[ASCommitWindow.IndexOfFolderWithGUID(this.pv1state.folders, guid)].changeFlags; + if (!ASCommitWindow.HasFlag(changeFlags2, ChangeFlags.Undeleted) && !ASCommitWindow.HasFlag(changeFlags2, ChangeFlags.Created) && !ASCommitWindow.HasFlag(changeFlags2, ChangeFlags.Moved)) + { + return false; + } + for (int i = 0; i < this.pv2state.folders.Length; i++) + { + string guid2 = this.pv2state.folders[i].guid; + if (AssetServer.GetParentGUID(guid2, -1) == guid) + { + int num3 = ASCommitWindow.IndexOfFolderWithGUID(this.pv1state.folders, guid2); + if (num3 != -1) + { + ArrayUtility.AddRange(ref this.pv1state.folders[num3].files, this.pv2state.folders[i].files); + } + else + { + ArrayUtility.Add(ref this.pv1state.folders, this.pv2state.folders[i]); + } + this.AddFolderToRemove(ref guidsOfFoldersToRemove, guid2); + this.TransferDependentParentFolders(ref guidsOfFoldersToRemove, guid2, leftToRight); + result = true; + } + } + } + return result; + } + private bool TransferDeletedDependentParentFolders(ref List guidsOfFoldersToRemove, string guid, bool leftToRight) + { + bool flag = false; + ParentViewState parentViewState = (!leftToRight) ? this.pv2state : this.pv1state; + ParentViewState parentViewState2 = (!leftToRight) ? this.pv1state : this.pv2state; + if (leftToRight) + { + for (int i = 0; i < parentViewState.folders.Length; i++) + { + ParentViewFolder parentViewFolder = parentViewState.folders[i]; + if (AssetServer.GetParentGUID(parentViewFolder.guid, -1) == guid) + { + if (!ASCommitWindow.AllFolderWouldBeMovedAnyway(parentViewState, parentViewFolder.guid)) + { + if (!ASCommitWindow.HasFlag(parentViewFolder.changeFlags, ChangeFlags.Deleted)) + { + Debug.LogError("Folder of nested deleted folders marked as not deleted (" + parentViewFolder.name + ")"); + return false; + } + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + if (!ASCommitWindow.HasFlag(parentViewFolder.files[j].changeFlags, ChangeFlags.Deleted)) + { + Debug.LogError("File of nested deleted folder is marked as not deleted (" + parentViewFolder.files[j].name + ")"); + return false; + } + } + flag |= this.TransferDeletedDependentParentFolders(ref guidsOfFoldersToRemove, parentViewFolder.guid, leftToRight); + int num = ASCommitWindow.IndexOfFolderWithGUID(parentViewState2.folders, parentViewFolder.guid); + if (num == -1) + { + ArrayUtility.Add(ref parentViewState2.folders, parentViewFolder); + } + this.AddFolderToRemove(ref guidsOfFoldersToRemove, parentViewFolder.guid); + flag = true; + } + } + } + } + else + { + while (AssetServer.IsGUIDValid(guid = AssetServer.GetParentGUID(guid, -1)) != 0) + { + int num2 = ASCommitWindow.IndexOfFolderWithGUID(this.pv2state.folders, guid); + if (num2 == -1) + { + break; + } + if (ASCommitWindow.HasFlag(this.pv2state.folders[num2].changeFlags, ChangeFlags.Deleted)) + { + ArrayUtility.Add(ref this.pv1state.folders, this.pv2state.folders[num2]); + flag = true; + this.AddFolderToRemove(ref guidsOfFoldersToRemove, this.pv2state.folders[num2].guid); + } + } + } + return flag; + } + private bool DoTransfer(ref ParentViewFolder[] foldersFrom, ref ParentViewFolder[] foldersTo, int folder, int file, ref List guidsOfFoldersToRemove, bool leftToRight) + { + ParentViewFolder parentViewFolder = foldersFrom[folder]; + ParentViewFolder parentViewFolder2 = null; + string name = parentViewFolder.name; + bool flag = false; + bool flag2 = false; + if (file == -1) + { + this.AddFolderToRemove(ref guidsOfFoldersToRemove, foldersFrom[folder].guid); + int num = ParentViewState.IndexOf(foldersTo, name); + if (num != -1) + { + parentViewFolder2 = foldersTo[num]; + ArrayUtility.AddRange(ref parentViewFolder2.files, parentViewFolder.files); + } + else + { + ArrayUtility.Add(ref foldersTo, parentViewFolder); + flag2 = true; + if (!ASCommitWindow.HasFlag(parentViewFolder.changeFlags, ChangeFlags.Deleted)) + { + flag = this.TransferDependentParentFolders(ref guidsOfFoldersToRemove, parentViewFolder.guid, leftToRight); + } + else + { + flag = this.TransferDeletedDependentParentFolders(ref guidsOfFoldersToRemove, parentViewFolder.guid, leftToRight); + } + } + } + else + { + int num2 = ParentViewState.IndexOf(foldersTo, name); + if (num2 == -1) + { + if (ASCommitWindow.HasFlag(parentViewFolder.files[file].changeFlags, ChangeFlags.Deleted) && ASCommitWindow.HasFlag(parentViewFolder.changeFlags, ChangeFlags.Deleted)) + { + ArrayUtility.Add(ref foldersTo, parentViewFolder); + this.AddFolderToRemove(ref guidsOfFoldersToRemove, parentViewFolder.guid); + num2 = foldersTo.Length - 1; + if (!ASCommitWindow.AllFolderWouldBeMovedAnyway((!leftToRight) ? this.pv2state : this.pv1state, parentViewFolder.guid)) + { + flag = true; + } + flag |= this.TransferDeletedDependentParentFolders(ref guidsOfFoldersToRemove, parentViewFolder.guid, leftToRight); + } + else + { + ArrayUtility.Add(ref foldersTo, parentViewFolder.CloneWithoutFiles()); + num2 = foldersTo.Length - 1; + flag = this.TransferDependentParentFolders(ref guidsOfFoldersToRemove, parentViewFolder.guid, leftToRight); + } + flag2 = true; + } + parentViewFolder2 = foldersTo[num2]; + ArrayUtility.Add(ref parentViewFolder2.files, parentViewFolder.files[file]); + ArrayUtility.RemoveAt(ref parentViewFolder.files, file); + if (parentViewFolder.files.Length == 0) + { + this.AddFolderToRemove(ref guidsOfFoldersToRemove, foldersFrom[folder].guid); + } + } + if (parentViewFolder2 != null) + { + Array.Sort(parentViewFolder2.files, new Comparison(ParentViewState.CompareViewFile)); + } + if (flag2) + { + Array.Sort(foldersTo, new Comparison(ParentViewState.CompareViewFolder)); + } + return flag; + } + private bool MarkDependantFiles(ParentViewState pvState) + { + string[] array = new string[0]; + bool result = false; + if (pvState == this.pv1state) + { + array = AssetServer.CollectAllDependencies(ASCommitWindow.GetParentViewSelectedItems(this.pv1state, false, false).ToArray()); + if (array.Length != 0) + { + int i = 1; + int num = 0; + while (i < pvState.lv.totalRows) + { + int j = 0; + while (j < pvState.folders[num].files.Length) + { + if (!pvState.selectedItems[i]) + { + for (int k = 0; k < array.Length; k++) + { + if (array[k] == pvState.folders[num].files[j].guid) + { + pvState.selectedItems[i] = true; + result = true; + break; + } + } + } + j++; + i++; + } + num++; + i++; + } + } + } + return result; + } + private void DoTransferAll(ParentViewState pvState, ParentViewState anotherPvState, int selFolder, int selFile) + { + List list = new List(); + bool flag = this.MarkDependantFiles(pvState); + int i = pvState.lv.totalRows - 1; + for (int j = pvState.folders.Length - 1; j >= 0; j--) + { + ParentViewFolder parentViewFolder = pvState.folders[j]; + bool flag2 = false; + for (int k = parentViewFolder.files.Length - 1; k >= -1; k--) + { + if (!list.Contains(parentViewFolder.guid) && pvState.selectedItems[i]) + { + if (k != -1 || !flag2) + { + flag |= this.DoTransfer(ref pvState.folders, ref anotherPvState.folders, j, k, ref list, pvState == this.pv1state); + } + flag2 = true; + } + i--; + } + } + for (i = pvState.folders.Length - 1; i >= 0; i--) + { + if (list.Contains(pvState.folders[i].guid)) + { + list.Remove(pvState.folders[i].guid); + ArrayUtility.RemoveAt(ref pvState.folders, i); + } + } + this.pv1state.SetLineCount(); + this.pv2state.SetLineCount(); + this.pv1state.ClearSelection(); + this.pv2state.ClearSelection(); + pvState.selectedFile = -1; + pvState.selectedFolder = -1; + AssetServer.SetSelectionFromGUID(string.Empty); + this.lastTransferMovedDependencies = flag; + } + private static bool AnyOfTheParentsIsSelected(ref ParentViewState pvState, string guid) + { + string text = guid; + while (AssetServer.IsGUIDValid(text = AssetServer.GetParentGUID(text, -1)) != 0) + { + if (ASCommitWindow.AllFolderWouldBeMovedAnyway(pvState, text)) + { + return true; + } + } + return false; + } + public static bool MarkAllFolderDependenciesForDiscarding(ParentViewState pvState, ParentViewState anotherPvState) + { + bool result = false; + bool flag = false; + int num = 0; + List list = new List(); + for (int i = 0; i < pvState.folders.Length; i++) + { + ParentViewFolder parentViewFolder = pvState.folders[i]; + if (ASCommitWindow.HasFlag(parentViewFolder.changeFlags, ChangeFlags.Deleted)) + { + bool flag2 = false; + for (int j = 1; j <= parentViewFolder.files.Length; j++) + { + if (pvState.selectedItems[num + j]) + { + flag2 = true; + pvState.selectedItems[num] = true; + list.Add(parentViewFolder.guid); + break; + } + } + if (pvState.selectedItems[num] || flag2) + { + string text = parentViewFolder.guid; + while (AssetServer.IsGUIDValid(text = AssetServer.GetParentGUID(text, -1)) != 0) + { + int num2 = ASCommitWindow.IndexOfFolderWithGUID(pvState.folders, text); + if (num2 == -1) + { + break; + } + num2 = ASCommitWindow.FolderIndexToTotalIndex(pvState.folders, num2); + if (!pvState.selectedItems[num2] && ASCommitWindow.HasFlag(pvState.folders[num2].changeFlags, ChangeFlags.Deleted)) + { + pvState.selectedItems[num2] = true; + list.Add(text); + result = true; + } + } + } + } + else + { + if (!ASCommitWindow.AllFolderWouldBeMovedAnyway(pvState, parentViewFolder.guid)) + { + if (ASCommitWindow.AnyOfTheParentsIsSelected(ref pvState, parentViewFolder.guid)) + { + pvState.selectedItems[num] = true; + list.Add(parentViewFolder.guid); + for (int k = 1; k <= parentViewFolder.files.Length; k++) + { + pvState.selectedItems[num + k] = true; + } + result = true; + } + } + else + { + for (int l = 1; l <= parentViewFolder.files.Length; l++) + { + if (!pvState.selectedItems[num + l]) + { + pvState.selectedItems[num + l] = true; + } + } + list.Add(parentViewFolder.guid); + } + } + num += 1 + pvState.folders[i].files.Length; + } + if (anotherPvState != null) + { + for (int m = 0; m < anotherPvState.folders.Length; m++) + { + ParentViewFolder parentViewFolder2 = anotherPvState.folders[m]; + if (ASCommitWindow.AnyOfTheParentsIsSelected(ref pvState, parentViewFolder2.guid)) + { + list.Add(parentViewFolder2.guid); + } + } + for (int n = anotherPvState.folders.Length - 1; n >= 0; n--) + { + if (list.Contains(anotherPvState.folders[n].guid)) + { + ParentViewFolder parentViewFolder3 = anotherPvState.folders[n]; + int num3 = ASCommitWindow.FolderSelectionIndexFromGUID(pvState.folders, parentViewFolder3.guid); + if (num3 != -1) + { + ParentViewFolder parentViewFolder4 = pvState.folders[num3]; + int length = pvState.lv.totalRows - num3 - 1 - parentViewFolder4.files.Length; + int num4 = num3 + 1 + parentViewFolder4.files.Length; + Array.Copy(pvState.selectedItems, num4, pvState.selectedItems, num4 + parentViewFolder3.files.Length, length); + ArrayUtility.AddRange(ref parentViewFolder4.files, parentViewFolder3.files); + for (int num5 = 1; num5 <= parentViewFolder4.files.Length; num5++) + { + pvState.selectedItems[num3 + num5] = true; + } + Array.Sort(parentViewFolder4.files, new Comparison(ParentViewState.CompareViewFile)); + } + else + { + num3 = 0; + for (int num6 = 0; num6 < pvState.folders.Length; num6++) + { + if (ParentViewState.CompareViewFolder(pvState.folders[num3], parentViewFolder3) > 0) + { + break; + } + num3 += 1 + pvState.folders[num6].files.Length; + } + int length2 = pvState.lv.totalRows - num3; + int num7 = num3; + Array.Copy(pvState.selectedItems, num7, pvState.selectedItems, num7 + 1 + parentViewFolder3.files.Length, length2); + ArrayUtility.Add(ref pvState.folders, parentViewFolder3); + for (int num8 = 0; num8 <= parentViewFolder3.files.Length; num8++) + { + pvState.selectedItems[num3 + num8] = true; + } + flag = true; + } + ArrayUtility.RemoveAt(ref anotherPvState.folders, n); + result = true; + } + } + anotherPvState.SetLineCount(); + } + pvState.SetLineCount(); + if (flag) + { + Array.Sort(pvState.folders, new Comparison(ParentViewState.CompareViewFolder)); + } + return result; + } + private static bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) + { + return (flagToCheck & flags) != ChangeFlags.None; + } + private void DoSelectionChange() + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + List list = new List(Selection.objects.Length); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + if (hierarchyProperty.Find(@object.GetInstanceID(), null)) + { + list.Add(hierarchyProperty.guid); + } + } + if (this.pv1hasSelection) + { + this.pv1hasSelection = ASCommitWindow.MarkSelected(this.pv1state, list); + } + if (!this.pv1hasSelection) + { + if (this.pv2hasSelection) + { + this.pv2hasSelection = ASCommitWindow.MarkSelected(this.pv2state, list); + } + if (!this.pv2hasSelection) + { + this.pv1hasSelection = ASCommitWindow.MarkSelected(this.pv1state, list); + if (!this.pv1hasSelection) + { + this.pv2hasSelection = ASCommitWindow.MarkSelected(this.pv2state, list); + } + } + } + } + internal void OnSelectionChange() + { + if (!this.mySelection) + { + this.DoSelectionChange(); + this.parentWin.Repaint(); + } + else + { + this.mySelection = false; + } + this.somethingDiscardableSelected = ASCommitWindow.SomethingDiscardableSelected((!this.pv2hasSelection) ? this.pv1state : this.pv2state); + } + public static bool SomethingDiscardableSelected(ParentViewState st) + { + int num = 0; + ParentViewFolder[] folders = st.folders; + for (int i = 0; i < folders.Length; i++) + { + ParentViewFolder parentViewFolder = folders[i]; + if (st.selectedItems[num++]) + { + return true; + } + ParentViewFile[] files = parentViewFolder.files; + for (int j = 0; j < files.Length; j++) + { + ParentViewFile parentViewFile = files[j]; + if (st.selectedItems[num++] && ASCommitWindow.IsDiscardableAsset(parentViewFile.guid, parentViewFile.changeFlags)) + { + return true; + } + } + } + return false; + } + private static bool AllFolderWouldBeMovedAnyway(ParentViewState pvState, string guid) + { + int num = 0; + for (int i = 0; i < pvState.folders.Length; i++) + { + if (pvState.folders[i].guid == guid) + { + bool flag = true; + bool flag2 = true; + bool flag3 = pvState.selectedItems[num++]; + for (int j = 0; j < pvState.folders[i].files.Length; j++) + { + if (pvState.selectedItems[num++]) + { + flag = false; + } + else + { + flag2 = false; + } + } + return flag3 && (flag2 || flag); + } + num += 1 + pvState.folders[i].files.Length; + } + return false; + } + private bool DoShowMyDiff(bool binary) + { + return ASCommitWindow.DoShowDiff(ASCommitWindow.GetParentViewSelectedItems((!this.pv2hasSelection) ? this.pv1state : this.pv2state, false, false), binary); + } + private void DoMyRevert(bool afterMarkingDependencies) + { + if (!afterMarkingDependencies) + { + List selectedItems = this.GetSelectedItems(); + bool flag; + if (this.pv2hasSelection) + { + flag = ASCommitWindow.MarkAllFolderDependenciesForDiscarding(this.pv2state, this.pv1state); + } + else + { + flag = ASCommitWindow.MarkAllFolderDependenciesForDiscarding(this.pv1state, this.pv2state); + } + if (flag) + { + this.MySelectionToGlobalSelection(); + } + List selectedItems2 = this.GetSelectedItems(); + if (selectedItems.Count != selectedItems2.Count) + { + flag = true; + } + this.lastRevertSelectionChanged = ((!flag) ? -1 : 1); + } + if (afterMarkingDependencies || this.lastRevertSelectionChanged == -1) + { + this.SetPersistedData(); + ASCommitWindow.DoRevert(ASCommitWindow.GetParentViewSelectedItems((!this.pv2hasSelection) ? this.pv1state : this.pv2state, true, true), "CBReinitCommitWindow"); + } + } + private void MenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + this.description = this.commitMessageList[selected]; + this.resetKeyboardControl = true; + this.parentWin.Repaint(); + } + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string text = this.dropDownMenuItems[selected]; + switch (text) + { + case "Compare": + this.DoShowMyDiff(false); + break; + case "Compare Binary": + this.DoShowMyDiff(true); + break; + case "Discard": + this.DoMyRevert(false); + break; + case ">>>": + this.DoTransferAll(this.pv1state, this.pv2state, this.pv1state.selectedFolder, this.pv1state.selectedFile); + break; + case "<<<": + this.DoTransferAll(this.pv2state, this.pv1state, this.pv2state.selectedFolder, this.pv2state.selectedFile); + break; + } + } + } + private static int IndexOfFolderWithGUID(ParentViewFolder[] folders, string guid) + { + for (int i = 0; i < folders.Length; i++) + { + if (folders[i].guid == guid) + { + return i; + } + } + return -1; + } + private static int FolderIndexToTotalIndex(ParentViewFolder[] folders, int folderIndex) + { + int num = 0; + for (int i = 0; i < folderIndex; i++) + { + num += folders[i].files.Length + 1; + } + return num; + } + private static int FolderSelectionIndexFromGUID(ParentViewFolder[] folders, string guid) + { + int num = 0; + for (int i = 0; i < folders.Length; i++) + { + if (guid == folders[i].guid) + { + return num; + } + num += 1 + folders[i].files.Length; + } + return -1; + } + private void AddFolderToRemove(ref List guidsOfFoldersToRemove, string guid) + { + if (!guidsOfFoldersToRemove.Contains(guid)) + { + guidsOfFoldersToRemove.Add(guid); + } + } + private bool ParentViewGUI(ParentViewState pvState, ParentViewState anotherPvState, ref bool hasSelection) + { + bool flag = false; + EditorGUIUtility.SetIconSize(this.iconSize); + ListViewState lv = pvState.lv; + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + int row = lv.row; + int num = -1; + int num2 = -1; + bool flag2 = false; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(lv, (ListViewOptions)12, this.dragTitle, GUIStyle.none, new GUILayoutOption[0])) + { + if (num == -1 && !pvState.IndexToFolderAndFile(listViewElement.row, ref num, ref num2)) + { + flag = true; + break; + } + if (GUIUtility.keyboardControl == lv.ID && Event.current.type == EventType.KeyDown && actionKey) + { + Event.current.Use(); + } + ParentViewFolder parentViewFolder = pvState.folders[num]; + if (pvState.selectedItems[listViewElement.row] && Event.current.type == EventType.Repaint) + { + ASCommitWindow.constants.entrySelected.Draw(listViewElement.position, false, false, false, false); + } + if (ListViewGUILayout.HasMouseUp(listViewElement.position)) + { + if (!shift && !actionKey) + { + flag2 |= ListViewGUILayout.MultiSelection(row, pvState.lv.row, ref pvState.initialSelectedItem, ref pvState.selectedItems); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position)) + { + if (Event.current.clickCount == 2) + { + this.DoShowMyDiff(false); + GUIUtility.ExitGUI(); + } + else + { + if (!pvState.selectedItems[listViewElement.row] || shift || actionKey) + { + flag2 |= ListViewGUILayout.MultiSelection(row, listViewElement.row, ref pvState.initialSelectedItem, ref pvState.selectedItems); + } + pvState.selectedFile = num2; + pvState.selectedFolder = num; + lv.row = listViewElement.row; + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position, 1)) + { + if (!pvState.selectedItems[listViewElement.row]) + { + flag2 = true; + pvState.ClearSelection(); + pvState.selectedItems[listViewElement.row] = true; + pvState.selectedFile = num2; + pvState.selectedFolder = num; + lv.row = listViewElement.row; + } + this.dropDownMenuItems[0] = ((pvState != this.pv1state) ? "<<<" : ">>>"); + GUIUtility.hotControl = 0; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, this.dropDownMenuItems, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + Event.current.Use(); + } + } + } + ChangeFlags changeFlags; + if (num2 != -1) + { + Texture2D texture2D = AssetDatabase.GetCachedIcon(parentViewFolder.name + "/" + parentViewFolder.files[num2].name) as Texture2D; + if (texture2D == null) + { + texture2D = InternalEditorUtility.GetIconForFile(parentViewFolder.files[num2].name); + } + GUILayout.Label(new GUIContent(parentViewFolder.files[num2].name, texture2D), ASCommitWindow.constants.element, new GUILayoutOption[0]); + changeFlags = parentViewFolder.files[num2].changeFlags; + } + else + { + GUILayout.Label(parentViewFolder.name, ASCommitWindow.constants.header, new GUILayoutOption[0]); + changeFlags = parentViewFolder.changeFlags; + } + GUIContent gUIContent = null; + if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Undeleted) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Created)) + { + gUIContent = ASMainWindow.badgeNew; + } + else + { + if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Deleted)) + { + gUIContent = ASMainWindow.badgeDelete; + } + else + { + if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Renamed) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Moved)) + { + gUIContent = ASMainWindow.badgeMove; + } + } + } + if (gUIContent != null && Event.current.type == EventType.Repaint) + { + Rect position2 = new Rect(listViewElement.position.x + listViewElement.position.width - (float)gUIContent.image.width - 5f, listViewElement.position.y + listViewElement.position.height / 2f - (float)(gUIContent.image.height / 2), (float)gUIContent.image.width, (float)gUIContent.image.height); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUIStyle.none.Draw(position2, gUIContent, false, false, false, false); + EditorGUIUtility.SetIconSize(this.iconSize); + } + pvState.NextFileFolder(ref num, ref num2); + } + if (!flag) + { + if (GUIUtility.keyboardControl == lv.ID) + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + for (int i = 0; i < pvState.selectedItems.Length; i++) + { + pvState.selectedItems[i] = true; + } + flag2 = true; + Event.current.Use(); + } + } + } + if (lv.customDraggedFromID != 0 && lv.customDraggedFromID == anotherPvState.lv.ID) + { + this.DoTransferAll(anotherPvState, pvState, pvState.selectedFolder, pvState.selectedFile); + } + if (GUIUtility.keyboardControl == lv.ID && !actionKey) + { + if (lv.selectionChanged) + { + flag2 |= ListViewGUILayout.MultiSelection(row, lv.row, ref pvState.initialSelectedItem, ref pvState.selectedItems); + if (!pvState.IndexToFolderAndFile(lv.row, ref pvState.selectedFolder, ref pvState.selectedFile)) + { + flag = true; + } + } + else + { + if (pvState.selectedFolder != -1 && Event.current.type == EventType.KeyDown && GUIUtility.keyboardControl == lv.ID && Event.current.keyCode == KeyCode.Return) + { + this.DoTransferAll(pvState, anotherPvState, pvState.selectedFolder, pvState.selectedFile); + ListViewGUILayout.MultiSelection(row, lv.row, ref pvState.initialSelectedItem, ref pvState.selectedItems); + pvState.IndexToFolderAndFile(lv.row, ref pvState.selectedFolder, ref pvState.selectedFile); + Event.current.Use(); + flag = true; + } + } + } + if (lv.selectionChanged || flag2) + { + if (pvState.IndexToFolderAndFile(lv.row, ref num, ref num2)) + { + this.dragTitle = ((num2 != -1) ? pvState.folders[num].files[num2].name : pvState.folders[num].name); + } + anotherPvState.ClearSelection(); + anotherPvState.lv.row = -1; + anotherPvState.selectedFile = -1; + anotherPvState.selectedFolder = -1; + this.MySelectionToGlobalSelection(); + } + } + EditorGUIUtility.SetIconSize(Vector2.zero); + return !flag; + } + internal bool DoGUI() + { + bool enabled = GUI.enabled; + if (ASCommitWindow.constants == null) + { + ASCommitWindow.constants = new ASCommitWindow.Constants(); + } + if (this.resetKeyboardControl) + { + this.resetKeyboardControl = false; + GUIUtility.keyboardControl = 0; + } + bool flag = this.parentWin.position.width <= 432f; + if (Event.current.type == EventType.Layout) + { + this.wasHidingButtons = flag; + } + else + { + if (flag != this.wasHidingButtons) + { + GUIUtility.ExitGUI(); + } + } + SplitterGUILayout.BeginHorizontalSplit(this.horSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASCommitWindow.constants.box, new GUILayoutOption[0]); + GUILayout.Label(this.totalChanges, ASCommitWindow.constants.title, new GUILayoutOption[0]); + if (!this.ParentViewGUI(this.pv1state, this.pv2state, ref this.pv1hasSelection)) + { + return true; + } + GUILayout.EndVertical(); + SplitterGUILayout.BeginVerticalSplit(this.vertSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASCommitWindow.constants.box, new GUILayoutOption[0]); + GUILayout.Label("Changeset", ASCommitWindow.constants.title, new GUILayoutOption[0]); + if (!this.ParentViewGUI(this.pv2state, this.pv1state, ref this.pv2hasSelection)) + { + return true; + } + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Commit Message", ASCommitWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (this.commitMessageList.Length > 0) + { + GUIContent content = new GUIContent("Recent"); + Rect rect = GUILayoutUtility.GetRect(content, ASCommitWindow.constants.dropDown, null); + if (GUI.Button(rect, content, ASCommitWindow.constants.dropDown)) + { + GUIUtility.hotControl = 0; + string[] array = new string[this.commitMessageList.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = ((this.commitMessageList[i].Length <= 200) ? this.commitMessageList[i] : (this.commitMessageList[i].Substring(0, 200) + " ... ")); + } + EditorUtility.DisplayCustomMenu(rect, array, null, new EditorUtility.SelectMenuItemFunction(this.MenuClick), null); + Event.current.Use(); + } + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(ASCommitWindow.constants.box, new GUILayoutOption[0]); + this.scrollPos = EditorGUILayout.BeginVerticalScrollView(this.scrollPos, new GUILayoutOption[0]); + this.description = EditorGUILayout.TextArea(this.description, ASCommitWindow.constants.wwText, new GUILayoutOption[0]); + EditorGUILayout.EndScrollView(); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + SplitterGUILayout.EndVerticalSplit(); + SplitterGUILayout.EndHorizontalSplit(); + if (!flag) + { + GUILayout.Label("Please drag files you want to commit to Changeset and fill in commit description", new GUILayoutOption[0]); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (!this.pv1hasSelection && !this.pv2hasSelection) + { + GUI.enabled = false; + } + if (!flag && GUILayout.Button("Compare", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + this.DoShowMyDiff(false); + GUIUtility.ExitGUI(); + } + bool enabled2 = GUI.enabled; + if (!this.somethingDiscardableSelected) + { + GUI.enabled = false; + } + if (GUILayout.Button((!flag) ? "Discard Selected Changes" : "Discard", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + this.DoMyRevert(false); + GUIUtility.ExitGUI(); + } + GUI.enabled = enabled2; + GUILayout.FlexibleSpace(); + GUI.enabled = (this.pv1hasSelection && enabled); + if (GUILayout.Button((!flag) ? ">>>" : ">", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + this.DoTransferAll(this.pv1state, this.pv2state, this.pv1state.selectedFolder, this.pv1state.selectedFile); + } + GUI.enabled = (this.pv2hasSelection && enabled); + if (GUILayout.Button((!flag) ? "<<<" : "<", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + this.DoTransferAll(this.pv2state, this.pv1state, this.pv2state.selectedFolder, this.pv2state.selectedFile); + } + GUI.enabled = (this.pv1state.lv.totalRows != 0 && enabled); + if (GUILayout.Button("Add All", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + int j = 0; + while (j < this.pv1state.selectedItems.Length) + { + this.pv1state.selectedItems[j++] = true; + } + this.DoTransferAll(this.pv1state, this.pv2state, this.pv1state.selectedFolder, this.pv1state.selectedFile); + } + GUI.enabled = (this.pv2state.lv.totalRows != 0 && enabled); + if (GUILayout.Button("Remove All", ASCommitWindow.constants.button, new GUILayoutOption[0])) + { + int k = 0; + while (k < this.pv2state.selectedItems.Length) + { + this.pv2state.selectedItems[k++] = true; + } + this.DoTransferAll(this.pv2state, this.pv1state, this.pv2state.selectedFolder, this.pv2state.selectedFile); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (!this.CanCommit()) + { + GUI.enabled = false; + } + if (GUILayout.Button("Commit", ASCommitWindow.constants.bigButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + this.DoCommit(); + } + GUI.enabled = enabled; + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.KeypadEnter && Application.platform == RuntimePlatform.OSXEditor && this.CanCommit()) + { + this.DoCommit(); + } + GUILayout.EndHorizontal(); + if (AssetServer.GetAssetServerError() != string.Empty) + { + GUILayout.Space(10f); + GUILayout.Label(AssetServer.GetAssetServerError(), ASCommitWindow.constants.errorLabel, new GUILayoutOption[0]); + GUILayout.Space(10f); + } + GUILayout.Space(10f); + if (this.lastRevertSelectionChanged == 0) + { + this.lastRevertSelectionChanged = -1; + if (ASCommitWindow.ShowDiscardWarning()) + { + this.DoMyRevert(true); + } + } + if (this.lastRevertSelectionChanged > 0) + { + if (Event.current.type == EventType.Repaint) + { + this.lastRevertSelectionChanged--; + } + this.parentWin.Repaint(); + } + if (this.showReinitedWarning == 0) + { + EditorUtility.DisplayDialog("Commits updated", "Commits had to be updated to reflect latest changes", "OK", string.Empty); + this.showReinitedWarning = -1; + } + if (this.showReinitedWarning > 0) + { + if (Event.current.type == EventType.Repaint) + { + this.showReinitedWarning--; + } + this.parentWin.Repaint(); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ASConfigWindow.cs b/UnityEditor/UnityEditor/ASConfigWindow.cs new file mode 100644 index 00000000..16d1c390 --- /dev/null +++ b/UnityEditor/UnityEditor/ASConfigWindow.cs @@ -0,0 +1,346 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASConfigWindow + { + private const int listLenghts = 20; + private static ASMainWindow.Constants constants; + private ListViewState serversLv = new ListViewState(0); + private ListViewState projectsLv = new ListViewState(0); + private string serverAddress = string.Empty; + private string projectName = string.Empty; + private string userName = string.Empty; + private string password = string.Empty; + private string port = string.Empty; + private bool resetKeyboardControl; + private string[] projectsList; + private string[] serversList; + private PListConfig plc; + private ASMainWindow parentWin; + public ASConfigWindow(ASMainWindow parent) + { + this.parentWin = parent; + this.LoadConfig(); + } + private void LoadConfig() + { + PListConfig pListConfig = new PListConfig("Library/ServerPreferences.plist"); + this.serverAddress = pListConfig["Maint Server"]; + this.userName = pListConfig["Maint UserName"]; + this.port = pListConfig["Maint port number"]; + this.projectName = pListConfig["Maint project name"]; + this.password = ASEditorBackend.GetPassword(this.serverAddress, this.userName); + if (this.port != string.Empty && this.port != 10733.ToString()) + { + this.serverAddress = this.serverAddress + ":" + this.port; + } + this.serversList = InternalEditorUtility.GetEditorSettingsList("ASServer", 20); + this.serversLv.totalRows = this.serversList.Length; + if (ArrayUtility.Contains(this.serversList, this.serverAddress)) + { + this.serversLv.row = ArrayUtility.IndexOf(this.serversList, this.serverAddress); + } + } + private void GetUserAndPassword() + { + string user = ASEditorBackend.GetUser(this.serverAddress); + if (user != string.Empty) + { + this.userName = user; + } + user = ASEditorBackend.GetPassword(this.serverAddress, user); + if (user != string.Empty) + { + this.password = user; + } + } + private void GetDefaultPListConfig() + { + this.plc = new PListConfig("Library/ServerPreferences.plist"); + this.plc["Maint Server"] = string.Empty; + this.plc["Maint UserName"] = string.Empty; + this.plc["Maint database name"] = string.Empty; + this.plc["Maint port number"] = string.Empty; + this.plc["Maint project name"] = string.Empty; + this.plc["Maint Password"] = string.Empty; + if (this.plc["Maint settings type"] == string.Empty) + { + this.plc["Maint settings type"] = "manual"; + } + if (this.plc["Maint Timeout"] == string.Empty) + { + this.plc["Maint Timeout"] = "5"; + } + if (this.plc["Maint Connection Settings"] == string.Empty) + { + this.plc["Maint Connection Settings"] = string.Empty; + } + } + private void DoShowProjects() + { + int num = 10733; + string text = this.serverAddress; + if (text.IndexOf(":") > 0) + { + int.TryParse(text.Substring(text.IndexOf(":") + 1), out num); + text = text.Substring(0, text.IndexOf(":")); + } + AssetServer.AdminSetCredentials(text, num, this.userName, this.password); + MaintDatabaseRecord[] array = AssetServer.AdminRefreshDatabases(); + if (array != null) + { + this.projectsList = new string[array.Length]; + for (int i = 0; i < array.Length; i++) + { + this.projectsList[i] = array[i].name; + } + this.projectsLv.totalRows = array.Length; + this.GetDefaultPListConfig(); + this.plc["Maint Server"] = text; + this.plc["Maint UserName"] = this.userName; + this.plc["Maint port number"] = this.port; + this.plc.Save(); + ASEditorBackend.SetPassword(text, this.userName, this.password); + ASEditorBackend.AddUser(this.serverAddress, this.userName); + } + else + { + this.projectsLv.totalRows = 0; + } + } + private void ClearConfig() + { + if (EditorUtility.DisplayDialog("Clear Configuration", "Are you sure you want to disconnect from Asset Server project and clear all configuration values?", "Clear", "Cancel")) + { + this.plc = new PListConfig("Library/ServerPreferences.plist"); + this.plc.Clear(); + this.plc.Save(); + this.LoadConfig(); + this.projectsLv.totalRows = 0; + ASEditorBackend.InitializeMaintBinding(); + this.resetKeyboardControl = true; + } + } + private void DoConnect() + { + AssetServer.RemoveMaintErrorsFromConsole(); + int num = 10733; + string text = this.serverAddress; + if (text.IndexOf(":") > 0) + { + int.TryParse(text.Substring(text.IndexOf(":") + 1), out num); + text = text.Substring(0, text.IndexOf(":")); + } + this.port = num.ToString(); + string databaseName = AssetServer.GetDatabaseName(text, this.userName, this.password, this.port, this.projectName); + this.GetDefaultPListConfig(); + this.plc["Maint Server"] = text; + this.plc["Maint UserName"] = this.userName; + this.plc["Maint database name"] = databaseName; + this.plc["Maint port number"] = this.port; + this.plc["Maint project name"] = this.projectName; + this.plc.Save(); + if (ArrayUtility.Contains(this.serversList, this.serverAddress)) + { + ArrayUtility.Remove(ref this.serversList, this.serverAddress); + } + ArrayUtility.Insert(ref this.serversList, 0, this.serverAddress); + ASEditorBackend.AddUser(this.serverAddress, this.userName); + ASEditorBackend.SetPassword(this.serverAddress, this.userName, this.password); + InternalEditorUtility.SaveEditorSettingsList("ASServer", this.serversList, 20); + if (databaseName != string.Empty) + { + ASEditorBackend.InitializeMaintBinding(); + this.parentWin.Reinit(); + GUIUtility.ExitGUI(); + } + else + { + this.parentWin.NeedsSetup = true; + this.parentWin.Repaint(); + } + } + private void ServersPopup() + { + if (this.serversList.Length > 0) + { + int num = EditorGUILayout.Popup(-1, this.serversList, ASConfigWindow.constants.dropDown, new GUILayoutOption[] + { + GUILayout.MaxWidth(18f) + }); + if (num >= 0) + { + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = 0; + this.resetKeyboardControl = true; + this.serverAddress = this.serversList[num]; + this.parentWin.Repaint(); + } + } + } + private void DoConfigGUI() + { + bool enabled = GUI.enabled; + bool changed = GUI.changed; + GUI.changed = false; + bool flag = false; + bool flag2 = false; + Event current = Event.current; + if (current.type == EventType.KeyDown) + { + bool flag3; + if (Application.platform == RuntimePlatform.OSXEditor) + { + flag3 = (current.character == '\n' || current.character == '\u0003' || current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter); + } + else + { + if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) + { + current.Use(); + } + flag3 = (current.character == '\n' || current.character == '\u0003'); + } + if (flag3) + { + string nameOfFocusedControl = GUI.GetNameOfFocusedControl(); + if (nameOfFocusedControl != null) + { + if (ASConfigWindow.<>f__switch$mapB == null) + { + ASConfigWindow.<>f__switch$mapB = new Dictionary(2) + { + + { + "password", + 0 + }, + + { + "project", + 1 + } + }; + } + int num; + if (ASConfigWindow.<>f__switch$mapB.TryGetValue(nameOfFocusedControl, out num)) + { + if (num == 0) + { + flag = true; + goto IL_141; + } + if (num == 1) + { + flag2 = true; + goto IL_141; + } + } + } + current.Use(); + } + } + IL_141: + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.serverAddress = EditorGUILayout.TextField("Server", this.serverAddress, new GUILayoutOption[0]); + this.ServersPopup(); + GUILayout.EndHorizontal(); + if (GUI.changed) + { + this.GetUserAndPassword(); + } + GUI.changed |= changed; + this.userName = EditorGUILayout.TextField("User Name", this.userName, new GUILayoutOption[0]); + GUI.SetNextControlName("password"); + this.password = EditorGUILayout.PasswordField("Password", this.password, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.userName != string.Empty && this.password != string.Empty && this.serverAddress != string.Empty && enabled); + if (GUILayout.Button("Show Projects", new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + }) || (flag && GUI.enabled)) + { + this.DoShowProjects(); + this.projectName = string.Empty; + EditorGUI.FocusTextInControl("project"); + } + bool enabled2 = GUI.enabled; + GUI.enabled = enabled; + if (GUILayout.Button("Clear Configuration", new GUILayoutOption[0])) + { + this.ClearConfig(); + } + GUI.enabled = enabled2; + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + changed = GUI.changed; + GUI.changed = false; + GUI.SetNextControlName("project"); + this.projectName = EditorGUILayout.TextField("Project Name", this.projectName, new GUILayoutOption[0]); + GUI.changed |= changed; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.userName != string.Empty && this.password != string.Empty && this.serverAddress != string.Empty && this.projectName != string.Empty && enabled); + if (GUILayout.Button("Connect", ASConfigWindow.constants.bigButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + }) || (flag2 && GUI.enabled)) + { + this.DoConnect(); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + } + private void DoProjectsGUI() + { + GUILayout.BeginVertical(ASConfigWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Label("Projects on Server", ASConfigWindow.constants.title, new GUILayoutOption[0]); + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.projectsLv, ASConfigWindow.constants.background, new GUILayoutOption[0])) + { + if (listViewElement.row == this.projectsLv.row && Event.current.type == EventType.Repaint) + { + ASConfigWindow.constants.entrySelected.Draw(listViewElement.position, false, false, false, false); + } + GUILayout.Label(this.projectsList[listViewElement.row], ASConfigWindow.constants.element, new GUILayoutOption[0]); + } + if (this.projectsLv.selectionChanged) + { + this.projectName = this.projectsList[this.projectsLv.row]; + } + GUILayout.EndVertical(); + } + public bool DoGUI() + { + if (ASConfigWindow.constants == null) + { + ASConfigWindow.constants = new ASMainWindow.Constants(); + } + if (this.resetKeyboardControl) + { + this.resetKeyboardControl = false; + GUIUtility.keyboardControl = 0; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(ASConfigWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Box("Server Connection", ASConfigWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASConfigWindow.constants.contentBox, new GUILayoutOption[0]); + this.DoConfigGUI(); + if (AssetServer.GetAssetServerError() != string.Empty) + { + GUILayout.Space(10f); + GUILayout.Label(AssetServer.GetAssetServerError(), ASConfigWindow.constants.errorLabel, new GUILayoutOption[0]); + GUILayout.Space(10f); + } + GUILayout.EndVertical(); + GUILayout.EndVertical(); + this.DoProjectsGUI(); + GUILayout.EndHorizontal(); + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ASEditorBackend.cs b/UnityEditor/UnityEditor/ASEditorBackend.cs new file mode 100644 index 00000000..317deb12 --- /dev/null +++ b/UnityEditor/UnityEditor/ASEditorBackend.cs @@ -0,0 +1,290 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class ASEditorBackend + { + public const string kServerSettingsFile = "Library/ServerPreferences.plist"; + public const string kUserName = "Maint UserName"; + public const string kPassword = "Maint Password"; + public const string kTimeout = "Maint Timeout"; + public const string kSettingsType = "Maint settings type"; + public const string kConnectionSettings = "Maint Connection Settings"; + public const string kPortNumber = "Maint port number"; + public const string kServer = "Maint Server"; + public const string kDatabaseName = "Maint database name"; + public const string kProjectName = "Maint project name"; + public const int kDefaultServerPort = 10733; + public static ASMainWindow asMainWin; + private static string s_TestingConflictResClass; + private static string s_TestingConflictResFunction; + public static ASMainWindow ASWin + { + get + { + return (!(ASEditorBackend.asMainWin != null)) ? EditorWindow.GetWindowDontShow() : ASEditorBackend.asMainWin; + } + } + public static void DoAS() + { + if (!ASEditorBackend.ASWin.Error) + { + ASEditorBackend.ASWin.Show(); + ASEditorBackend.ASWin.Focus(); + } + } + public static void ShowASConflictResolutionsWindow(string[] conflicting) + { + ASEditorBackend.ASWin.ShowConflictResolutions(conflicting); + } + public static void CommitItemsChanged() + { + if (ASEditorBackend.asMainWin != null || (ASEditorBackend.asMainWin == null && Resources.FindObjectsOfTypeAll(typeof(ASMainWindow)).Length != 0)) + { + ASEditorBackend.ASWin.CommitItemsChanged(); + } + } + public static void CBReinitCommitWindow(int actionResult) + { + if (ASEditorBackend.ASWin.asCommitWin != null) + { + ASEditorBackend.ASWin.asCommitWin.Reinit(actionResult != 0); + } + } + public static void CBCommitFinished(int actionResult) + { + if (ASEditorBackend.ASWin.asCommitWin != null) + { + ASEditorBackend.ASWin.asCommitWin.CommitFinished(actionResult != 0); + } + } + public static void CBOverviewsCommitFinished(int actionResult) + { + if (ASEditorBackend.ASWin != null) + { + ASEditorBackend.ASWin.CommitFinished(actionResult != 0); + } + } + public static void CBReinitOnSuccess(int actionResult) + { + if (actionResult != 0) + { + ASEditorBackend.ASWin.Reinit(); + } + else + { + ASEditorBackend.ASWin.Repaint(); + } + } + public static void CBReinitASMainWindow() + { + ASEditorBackend.ASWin.Reinit(); + } + public static void CBDoDiscardChanges(int actionResult) + { + ASEditorBackend.ASWin.DoDiscardChanges(actionResult != 0); + } + public static void CBInitUpdatePage(int actionResult) + { + ASEditorBackend.ASWin.InitUpdatePage(actionResult != 0); + } + public static void CBInitHistoryPage(int actionResult) + { + ASEditorBackend.ASWin.InitHistoryPage(actionResult != 0); + } + public static void CBInitOverviewPage(int actionResult) + { + ASEditorBackend.ASWin.InitOverviewPage(actionResult != 0); + } + public static bool SettingsIfNeeded() + { + return ASEditorBackend.InitializeMaintBinding(); + } + public static bool SettingsAreValid() + { + PListConfig pListConfig = new PListConfig("Library/ServerPreferences.plist"); + string text = pListConfig["Maint UserName"]; + string text2 = pListConfig["Maint Server"]; + string text3 = pListConfig["Maint database name"]; + string text4 = pListConfig["Maint Timeout"]; + string text5 = pListConfig["Maint port number"]; + return text.Length != 0 && text2.Length != 0 && text3.Length != 0 && text4.Length != 0 && text5.Length != 0; + } + internal static string GetPassword(string server, string user) + { + string key = "ASPassword::" + server + "::" + user; + return EditorPrefs.GetString(key, string.Empty); + } + internal static void SetPassword(string server, string user, string password) + { + string key = "ASPassword::" + server + "::" + user; + EditorPrefs.SetString(key, password); + } + internal static void AddUser(string server, string user) + { + string key = "ASUser::" + server; + EditorPrefs.SetString(key, user); + } + internal static string GetUser(string server) + { + string key = "ASUser::" + server; + return EditorPrefs.GetString(key, string.Empty); + } + public static bool InitializeMaintBinding() + { + PListConfig pListConfig = new PListConfig("Library/ServerPreferences.plist"); + string text = pListConfig["Maint UserName"]; + string text2 = pListConfig["Maint Server"]; + string text3 = pListConfig["Maint project name"]; + string text4 = pListConfig["Maint database name"]; + string text5 = pListConfig["Maint port number"]; + int timeout; + if (!int.TryParse(pListConfig["Maint Timeout"], out timeout)) + { + timeout = 5; + } + if (text2.Length == 0 || text3.Length == 0 || text4.Length == 0 || text.Length == 0) + { + AssetServer.SetProjectName(string.Empty); + return false; + } + AssetServer.SetProjectName(string.Format("{0} @ {1}", text3, text2)); + string connectionString = string.Concat(new string[] + { + "host='", + text2, + "' user='", + text, + "' password='", + ASEditorBackend.GetPassword(text2, text), + "' dbname='", + text4, + "' port='", + text5, + "' sslmode=disable ", + pListConfig["Maint Connection Settings"] + }); + AssetServer.Initialize(text, connectionString, timeout); + return true; + } + public static void Testing_SetActionFinishedCallback(string klass, string name) + { + AssetServer.SaveString("s_TestingClass", klass); + AssetServer.SaveString("s_TestingFunction", name); + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "Testing_DummyCallback"); + } + private static void Testing_DummyCallback(bool success) + { + ASEditorBackend.Testing_Invoke(AssetServer.GetAndRemoveString("s_TestingClass"), AssetServer.GetAndRemoveString("s_TestingFunction"), new object[] + { + success + }); + } + private static void Testing_SetExceptionHandler(string exceptionHandlerClass, string exceptionHandlerFunction) + { + AssetServer.SaveString("s_ExceptionHandlerClass", exceptionHandlerClass); + AssetServer.SaveString("s_ExceptionHandlerFunction", exceptionHandlerFunction); + } + private static void Testing_Invoke(string klass, string method, params object[] prms) + { + try + { + AppDomain currentDomain = AppDomain.CurrentDomain; + Assembly[] assemblies = currentDomain.GetAssemblies(); + for (int i = 0; i < assemblies.Length; i++) + { + Assembly assembly = assemblies[i]; + if (assembly.GetName().Name != "UnityEditor" && assembly.GetName().Name != "UnityEngine") + { + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + for (int j = 0; j < typesFromAssembly.Length; j++) + { + Type type = typesFromAssembly[j]; + if (type.Name == klass) + { + type.InvokeMember(method, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, prms); + } + } + } + } + } + catch (Exception ex) + { + if (ex.InnerException != null && ex.InnerException.GetType() == typeof(ExitGUIException)) + { + throw ex; + } + ASEditorBackend.Testing_Invoke(AssetServer.GetString("s_ExceptionHandlerClass"), AssetServer.GetString("s_ExceptionHandlerFunction"), new object[] + { + ex + }); + } + } + public static void Testing_SetActiveDatabase(string host, int port, string projectName, string dbName, string user, string pwd) + { + PListConfig pListConfig = new PListConfig("Library/ServerPreferences.plist"); + pListConfig["Maint Server"] = host; + pListConfig["Maint UserName"] = user; + pListConfig["Maint database name"] = dbName; + pListConfig["Maint port number"] = port.ToString(); + pListConfig["Maint project name"] = projectName; + pListConfig["Maint Password"] = string.Empty; + pListConfig["Maint settings type"] = "manual"; + pListConfig["Maint Timeout"] = "5"; + pListConfig["Maint Connection Settings"] = string.Empty; + pListConfig.Save(); + } + public static bool Testing_SetupDatabase(string host, int port, string adminUser, string adminPwd, string user, string pwd, string projectName) + { + AssetServer.AdminSetCredentials(host, port, adminUser, adminPwd); + MaintDatabaseRecord[] array = AssetServer.AdminRefreshDatabases(); + if (array == null) + { + return false; + } + MaintDatabaseRecord[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + MaintDatabaseRecord maintDatabaseRecord = array2[i]; + if (maintDatabaseRecord.name == projectName) + { + AssetServer.AdminDeleteDB(projectName); + } + } + if (AssetServer.AdminCreateDB(projectName) == 0) + { + return false; + } + string databaseName = AssetServer.GetDatabaseName(host, adminUser, adminPwd, port.ToString(), projectName); + if (!AssetServer.AdminSetUserEnabled(databaseName, user, user, string.Empty, 1)) + { + return false; + } + ASEditorBackend.Testing_SetActiveDatabase(host, port, projectName, databaseName, user, pwd); + return true; + } + public static string[] Testing_GetAllDatabaseNames() + { + MaintDatabaseRecord[] array = AssetServer.AdminRefreshDatabases(); + string[] array2 = new string[array.Length]; + for (int i = 0; i < array.Length; i++) + { + array2[i] = array[i].name; + } + return array2; + } + public static void Testing_SetConflictResolutionFunction(string klass, string fn) + { + ASEditorBackend.s_TestingConflictResClass = klass; + ASEditorBackend.s_TestingConflictResFunction = fn; + } + public static void Testing_DummyConflictResolutionFunction(string[] conflicting) + { + ASEditorBackend.Testing_Invoke(ASEditorBackend.s_TestingConflictResClass, ASEditorBackend.s_TestingConflictResFunction, new object[] + { + conflicting + }); + } + } +} diff --git a/UnityEditor/UnityEditor/ASHistoryFileView.cs b/UnityEditor/UnityEditor/ASHistoryFileView.cs new file mode 100644 index 00000000..45f82d73 --- /dev/null +++ b/UnityEditor/UnityEditor/ASHistoryFileView.cs @@ -0,0 +1,1099 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASHistoryFileView + { + public enum SelectionType + { + None, + All, + Items, + DeletedItemsRoot, + DeletedItems + } + private class Styles + { + public GUIStyle foldout = "IN Foldout"; + public GUIStyle insertion = "PR Insertion"; + public GUIStyle label = "PR Label"; + public GUIStyle ping = new GUIStyle("PR Ping"); + public GUIStyle toolbarButton = "ToolbarButton"; + public Styles() + { + this.ping.overflow.left = -2; + this.ping.overflow.right = -21; + this.ping.padding.left = 48; + this.ping.padding.right = 0; + } + } + private int[] m_ExpandedArray = new int[0]; + public Vector2 m_ScrollPosition; + private static float m_RowHeight = 16f; + private float m_FoldoutSize = 14f; + private float m_Indent = 16f; + private float m_BaseIndent = 16f; + private float m_SpaceAtTheTop = ASHistoryFileView.m_RowHeight + 6f; + private static int ms_FileViewHash = "FileView".GetHashCode(); + private int m_FileViewControlID = -1; + private static bool OSX = Application.platform == RuntimePlatform.OSXEditor; + private ASHistoryFileView.SelectionType m_SelType; + private bool m_DeletedItemsToggle; + private DeletedAsset[] m_DeletedItems; + private bool m_DeletedItemsInitialized; + private ParentViewState m_DelPVstate = new ParentViewState(); + private Rect m_ScreenRect; + private static ASHistoryFileView.Styles ms_Styles = null; + private GUIContent[] dropDownMenuItems = new GUIContent[] + { + new GUIContent("Recover") + }; + public ASHistoryFileView.SelectionType SelType + { + get + { + return this.m_SelType; + } + set + { + if (this.m_SelType == ASHistoryFileView.SelectionType.DeletedItems && value != ASHistoryFileView.SelectionType.DeletedItems) + { + for (int i = 0; i < this.m_DelPVstate.selectedItems.Length; i++) + { + this.m_DelPVstate.selectedItems[i] = false; + } + } + this.m_SelType = value; + } + } + private bool DeletedItemsToggle + { + get + { + return this.m_DeletedItemsToggle; + } + set + { + this.m_DeletedItemsToggle = value; + if (this.m_DeletedItemsToggle && !this.m_DeletedItemsInitialized) + { + this.SetupDeletedItems(); + } + } + } + public ASHistoryFileView() + { + this.m_DelPVstate.lv = new ListViewState(0); + this.m_DelPVstate.lv.totalRows = 0; + } + private void SetupDeletedItems() + { + this.m_DeletedItems = AssetServer.GetServerDeletedItems(); + this.m_DelPVstate.Clear(); + this.m_DelPVstate.lv = new ListViewState(0); + this.m_DelPVstate.AddAssetItems(this.m_DeletedItems); + this.m_DelPVstate.AddAssetItems(AssetServer.GetLocalDeletedItems()); + this.m_DelPVstate.SetLineCount(); + this.m_DelPVstate.selectedItems = new bool[this.m_DelPVstate.lv.totalRows]; + this.m_DeletedItemsInitialized = true; + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + if (selected == 0) + { + this.DoRecover(); + } + } + } + public void SelectDeletedItem(string guid) + { + this.SelType = ASHistoryFileView.SelectionType.DeletedItems; + this.DeletedItemsToggle = true; + int num = 0; + for (int i = 0; i < this.m_DelPVstate.folders.Length; i++) + { + ParentViewFolder parentViewFolder = this.m_DelPVstate.folders[i]; + this.m_DelPVstate.selectedItems[num] = false; + if (parentViewFolder.guid == guid) + { + this.m_DelPVstate.selectedItems[num] = true; + this.ScrollToDeletedItem(num); + return; + } + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + num++; + this.m_DelPVstate.selectedItems[num] = false; + if (parentViewFolder.files[j].guid == guid) + { + this.m_DelPVstate.selectedItems[num] = true; + this.ScrollToDeletedItem(num); + return; + } + } + num++; + } + } + public void DoRecover() + { + string[] selectedDeletedItemGUIDs = this.GetSelectedDeletedItemGUIDs(); + Dictionary dictionary = new Dictionary(); + int num = 0; + for (int i = 0; i < selectedDeletedItemGUIDs.Length; i++) + { + for (int j = 0; j < this.m_DeletedItems.Length; j++) + { + if (this.m_DeletedItems[j].guid == selectedDeletedItemGUIDs[i]) + { + dictionary[this.m_DeletedItems[j].guid] = j; + break; + } + } + } + DeletedAsset[] array = new DeletedAsset[dictionary.Count]; + while (dictionary.Count != 0) + { + DeletedAsset deletedAsset = null; + foreach (KeyValuePair current in dictionary) + { + deletedAsset = this.m_DeletedItems[current.Value]; + if (!dictionary.ContainsKey(deletedAsset.parent)) + { + array[num++] = deletedAsset; + break; + } + } + dictionary.Remove(deletedAsset.guid); + } + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBReinitASMainWindow"); + AssetServer.DoRecoverOnNextTick(array); + } + public string[] GetSelectedDeletedItemGUIDs() + { + List list = new List(); + int num = 0; + for (int i = 0; i < this.m_DelPVstate.folders.Length; i++) + { + ParentViewFolder parentViewFolder = this.m_DelPVstate.folders[i]; + if (this.m_DelPVstate.selectedItems[num]) + { + list.Add(parentViewFolder.guid); + } + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + num++; + if (this.m_DelPVstate.selectedItems[num]) + { + list.Add(parentViewFolder.files[j].guid); + } + } + num++; + } + return list.ToArray(); + } + public string[] GetAllDeletedItemGUIDs() + { + if (!this.m_DeletedItemsInitialized) + { + this.SetupDeletedItems(); + } + string[] array = new string[this.m_DeletedItems.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = this.m_DeletedItems[i].guid; + } + return array; + } + public void FilterItems(string filterText) + { + } + private int ControlIDForProperty(HierarchyProperty property) + { + if (property != null) + { + return property.row + 10000000; + } + return -1; + } + private void SetExpanded(int instanceID, bool expand) + { + Hashtable hashtable = new Hashtable(); + for (int i = 0; i < this.m_ExpandedArray.Length; i++) + { + hashtable.Add(this.m_ExpandedArray[i], null); + } + if (expand != hashtable.Contains(instanceID)) + { + if (expand) + { + hashtable.Add(instanceID, null); + } + else + { + hashtable.Remove(instanceID); + } + this.m_ExpandedArray = new int[hashtable.Count]; + int num = 0; + foreach (int num2 in hashtable.Keys) + { + this.m_ExpandedArray[num] = num2; + num++; + } + } + InternalEditorUtility.expandedProjectWindowItems = this.m_ExpandedArray; + } + private void SetExpandedRecurse(int instanceID, bool expand) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, this.m_ExpandedArray)) + { + this.SetExpanded(instanceID, expand); + int depth = hierarchyProperty.depth; + while (hierarchyProperty.Next(null) && hierarchyProperty.depth > depth) + { + this.SetExpanded(hierarchyProperty.instanceID, expand); + } + } + } + private void SelectionClick(HierarchyProperty property) + { + if (EditorGUI.actionKey) + { + ArrayList arrayList = new ArrayList(); + arrayList.AddRange(Selection.objects); + if (arrayList.Contains(property.pptrValue)) + { + arrayList.Remove(property.pptrValue); + } + else + { + arrayList.Add(property.pptrValue); + } + Selection.objects = (arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); + } + else + { + if (Event.current.shift) + { + HierarchyProperty firstSelected = this.GetFirstSelected(); + HierarchyProperty lastSelected = this.GetLastSelected(); + if (!firstSelected.isValid) + { + Selection.activeObject = property.pptrValue; + return; + } + HierarchyProperty hierarchyProperty; + HierarchyProperty hierarchyProperty2; + if (property.row > lastSelected.row) + { + hierarchyProperty = firstSelected; + hierarchyProperty2 = property; + } + else + { + hierarchyProperty = property; + hierarchyProperty2 = lastSelected; + } + ArrayList arrayList2 = new ArrayList(); + arrayList2.Add(hierarchyProperty.pptrValue); + while (hierarchyProperty.Next(this.m_ExpandedArray)) + { + arrayList2.Add(hierarchyProperty.pptrValue); + if (hierarchyProperty.instanceID == hierarchyProperty2.instanceID) + { + break; + } + } + Selection.objects = (arrayList2.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); + } + else + { + Selection.activeObject = property.pptrValue; + } + } + this.SelType = ASHistoryFileView.SelectionType.Items; + this.FrameObject(Selection.activeObject); + } + private HierarchyProperty GetActiveSelected() + { + return this.GetFirstSelected(); + } + private HierarchyProperty GetFirstSelected() + { + int num = 1000000000; + HierarchyProperty result = null; + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(@object.GetInstanceID(), this.m_ExpandedArray) && hierarchyProperty.row < num) + { + num = hierarchyProperty.row; + result = hierarchyProperty; + } + } + return result; + } + private HierarchyProperty GetLast() + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + int count = hierarchyProperty.CountRemaining(this.m_ExpandedArray); + hierarchyProperty.Reset(); + if (hierarchyProperty.Skip(count, this.m_ExpandedArray)) + { + return hierarchyProperty; + } + return null; + } + private HierarchyProperty GetFirst() + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Next(this.m_ExpandedArray)) + { + return hierarchyProperty; + } + return null; + } + private void OpenAssetSelection() + { + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + if (AssetDatabase.Contains(instanceID)) + { + AssetDatabase.OpenAsset(instanceID); + } + } + } + private HierarchyProperty GetLastSelected() + { + int num = -1; + HierarchyProperty result = null; + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(@object.GetInstanceID(), this.m_ExpandedArray) && hierarchyProperty.row > num) + { + num = hierarchyProperty.row; + result = hierarchyProperty; + } + } + return result; + } + private void AllProjectKeyboard() + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode == KeyCode.DownArrow) + { + if (this.GetFirst() != null) + { + Selection.activeObject = this.GetFirst().pptrValue; + this.FrameObject(Selection.activeObject); + this.SelType = ASHistoryFileView.SelectionType.Items; + Event.current.Use(); + } + } + } + private void AssetViewKeyboard() + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_1B4; + case KeyCode.KeypadEquals: + case KeyCode.Insert: + IL_45: + if (keyCode != KeyCode.Return) + { + return; + } + goto IL_1B4; + case KeyCode.UpArrow: + { + Event.current.Use(); + HierarchyProperty firstSelected = this.GetFirstSelected(); + if (firstSelected != null) + { + if (firstSelected.instanceID == this.GetFirst().instanceID) + { + this.SelType = ASHistoryFileView.SelectionType.All; + Selection.objects = new UnityEngine.Object[0]; + this.ScrollTo(0f); + } + else + { + if (firstSelected.Previous(this.m_ExpandedArray)) + { + UnityEngine.Object pptrValue = firstSelected.pptrValue; + this.SelectionClick(firstSelected); + this.FrameObject(pptrValue); + } + } + } + goto IL_3F9; + } + case KeyCode.DownArrow: + { + Event.current.Use(); + HierarchyProperty lastSelected = this.GetLastSelected(); + if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) + { + this.OpenAssetSelection(); + GUIUtility.ExitGUI(); + } + else + { + if (lastSelected != null) + { + if (lastSelected.instanceID == this.GetLast().instanceID) + { + this.SelType = ASHistoryFileView.SelectionType.DeletedItemsRoot; + Selection.objects = new UnityEngine.Object[0]; + this.ScrollToDeletedItem(-1); + } + else + { + if (lastSelected.Next(this.m_ExpandedArray)) + { + UnityEngine.Object pptrValue2 = lastSelected.pptrValue; + this.SelectionClick(lastSelected); + this.FrameObject(pptrValue2); + } + } + } + } + goto IL_3F9; + } + case KeyCode.RightArrow: + { + HierarchyProperty activeSelected = this.GetActiveSelected(); + if (activeSelected != null) + { + this.SetExpanded(activeSelected.instanceID, true); + } + goto IL_3F9; + } + case KeyCode.LeftArrow: + { + HierarchyProperty activeSelected2 = this.GetActiveSelected(); + if (activeSelected2 != null) + { + this.SetExpanded(activeSelected2.instanceID, false); + } + goto IL_3F9; + } + case KeyCode.Home: + if (this.GetFirst() != null) + { + Selection.activeObject = this.GetFirst().pptrValue; + this.FrameObject(Selection.activeObject); + } + goto IL_3F9; + case KeyCode.End: + if (this.GetLast() != null) + { + Selection.activeObject = this.GetLast().pptrValue; + this.FrameObject(Selection.activeObject); + } + goto IL_3F9; + case KeyCode.PageUp: + Event.current.Use(); + if (ASHistoryFileView.OSX) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y - this.m_ScreenRect.height; + if (this.m_ScrollPosition.y < 0f) + { + this.m_ScrollPosition.y = 0f; + } + } + else + { + HierarchyProperty hierarchyProperty = this.GetFirstSelected(); + if (hierarchyProperty != null) + { + int num = 0; + while ((float)num < this.m_ScreenRect.height / ASHistoryFileView.m_RowHeight) + { + if (!hierarchyProperty.Previous(this.m_ExpandedArray)) + { + hierarchyProperty = this.GetFirst(); + break; + } + num++; + } + UnityEngine.Object pptrValue3 = hierarchyProperty.pptrValue; + this.SelectionClick(hierarchyProperty); + this.FrameObject(pptrValue3); + } + else + { + if (this.GetFirst() != null) + { + Selection.activeObject = this.GetFirst().pptrValue; + this.FrameObject(Selection.activeObject); + } + } + } + goto IL_3F9; + case KeyCode.PageDown: + Event.current.Use(); + if (ASHistoryFileView.OSX) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y + this.m_ScreenRect.height; + } + else + { + HierarchyProperty hierarchyProperty2 = this.GetLastSelected(); + if (hierarchyProperty2 != null) + { + int num2 = 0; + while ((float)num2 < this.m_ScreenRect.height / ASHistoryFileView.m_RowHeight) + { + if (!hierarchyProperty2.Next(this.m_ExpandedArray)) + { + hierarchyProperty2 = this.GetLast(); + break; + } + num2++; + } + UnityEngine.Object pptrValue4 = hierarchyProperty2.pptrValue; + this.SelectionClick(hierarchyProperty2); + this.FrameObject(pptrValue4); + } + else + { + if (this.GetLast() != null) + { + Selection.activeObject = this.GetLast().pptrValue; + this.FrameObject(Selection.activeObject); + } + } + } + goto IL_3F9; + } + goto IL_45; + IL_1B4: + if (Application.platform == RuntimePlatform.WindowsEditor) + { + this.OpenAssetSelection(); + GUIUtility.ExitGUI(); + } + IL_3F9: + Event.current.Use(); + } + private void DeletedItemsRootKeyboard(ASHistoryWindow parentWin) + { + switch (Event.current.keyCode) + { + case KeyCode.UpArrow: + this.SelType = ASHistoryFileView.SelectionType.Items; + if (this.GetLast() != null) + { + Selection.activeObject = this.GetLast().pptrValue; + this.FrameObject(Selection.activeObject); + } + break; + case KeyCode.DownArrow: + if (this.m_DelPVstate.selectedItems.Length > 0 && this.DeletedItemsToggle) + { + this.SelType = ASHistoryFileView.SelectionType.DeletedItems; + this.m_DelPVstate.selectedItems[0] = true; + this.m_DelPVstate.lv.row = 0; + this.ScrollToDeletedItem(0); + } + break; + case KeyCode.RightArrow: + this.DeletedItemsToggle = true; + break; + case KeyCode.LeftArrow: + this.DeletedItemsToggle = false; + break; + default: + return; + } + if (this.SelType != ASHistoryFileView.SelectionType.Items) + { + parentWin.DoLocalSelectionChange(); + } + Event.current.Use(); + } + private void DeletedItemsKeyboard(ASHistoryWindow parentWin) + { + int row = this.m_DelPVstate.lv.row; + int num = row; + if (!this.DeletedItemsToggle) + { + return; + } + switch (Event.current.keyCode) + { + case KeyCode.UpArrow: + if (num > 0) + { + num--; + } + else + { + this.SelType = ASHistoryFileView.SelectionType.DeletedItemsRoot; + this.ScrollToDeletedItem(-1); + parentWin.DoLocalSelectionChange(); + } + goto IL_1AE; + case KeyCode.DownArrow: + if (num < this.m_DelPVstate.lv.totalRows - 1) + { + num++; + } + goto IL_1AE; + case KeyCode.Home: + num = 0; + goto IL_1AE; + case KeyCode.End: + num = this.m_DelPVstate.lv.totalRows - 1; + goto IL_1AE; + case KeyCode.PageUp: + if (ASHistoryFileView.OSX) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y - this.m_ScreenRect.height; + if (this.m_ScrollPosition.y < 0f) + { + this.m_ScrollPosition.y = 0f; + } + } + else + { + num -= (int)(this.m_ScreenRect.height / ASHistoryFileView.m_RowHeight); + if (num < 0) + { + num = 0; + } + } + goto IL_1AE; + case KeyCode.PageDown: + if (ASHistoryFileView.OSX) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y + this.m_ScreenRect.height; + } + else + { + num += (int)(this.m_ScreenRect.height / ASHistoryFileView.m_RowHeight); + if (num > this.m_DelPVstate.lv.totalRows - 1) + { + num = this.m_DelPVstate.lv.totalRows - 1; + } + } + goto IL_1AE; + } + return; + IL_1AE: + Event.current.Use(); + if (num != row) + { + this.m_DelPVstate.lv.row = num; + ListViewShared.MultiSelection(null, row, num, ref this.m_DelPVstate.initialSelectedItem, ref this.m_DelPVstate.selectedItems); + this.ScrollToDeletedItem(num); + parentWin.DoLocalSelectionChange(); + } + } + private void ScrollToDeletedItem(int index) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + float num = this.m_SpaceAtTheTop + (float)hierarchyProperty.CountRemaining(this.m_ExpandedArray) * ASHistoryFileView.m_RowHeight + 6f; + if (index == -1) + { + this.ScrollTo(num); + } + else + { + this.ScrollTo(num + (float)(index + 1) * ASHistoryFileView.m_RowHeight); + } + } + private void KeyboardGUI(ASHistoryWindow parentWin) + { + if (Event.current.GetTypeForControl(this.m_FileViewControlID) != EventType.KeyDown || this.m_FileViewControlID != GUIUtility.keyboardControl) + { + return; + } + switch (this.SelType) + { + case ASHistoryFileView.SelectionType.All: + this.AllProjectKeyboard(); + break; + case ASHistoryFileView.SelectionType.Items: + this.AssetViewKeyboard(); + break; + case ASHistoryFileView.SelectionType.DeletedItemsRoot: + this.DeletedItemsRootKeyboard(parentWin); + break; + case ASHistoryFileView.SelectionType.DeletedItems: + this.DeletedItemsKeyboard(parentWin); + break; + } + } + private bool FrameObject(UnityEngine.Object target) + { + if (target == null) + { + return false; + } + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(target.GetInstanceID(), null)) + { + while (hierarchyProperty.Parent()) + { + this.SetExpanded(hierarchyProperty.instanceID, true); + } + } + hierarchyProperty.Reset(); + if (hierarchyProperty.Find(target.GetInstanceID(), this.m_ExpandedArray)) + { + this.ScrollTo(ASHistoryFileView.m_RowHeight * (float)hierarchyProperty.row + this.m_SpaceAtTheTop); + return true; + } + return false; + } + private void ScrollTo(float scrollTop) + { + float min = scrollTop - this.m_ScreenRect.height + ASHistoryFileView.m_RowHeight; + this.m_ScrollPosition.y = Mathf.Clamp(this.m_ScrollPosition.y, min, scrollTop); + } + public void DoDeletedItemsGUI(ASHistoryWindow parentWin, Rect theRect, GUIStyle s, float offset, float endOffset, bool focused) + { + Event current = Event.current; + Texture2D image = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + offset += 3f; + Rect position = new Rect(this.m_Indent, offset, theRect.width - this.m_Indent, ASHistoryFileView.m_RowHeight); + if (current.type == EventType.MouseDown && position.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = this.m_FileViewControlID; + this.SelType = ASHistoryFileView.SelectionType.DeletedItemsRoot; + this.ScrollToDeletedItem(-1); + parentWin.DoLocalSelectionChange(); + } + position.width -= position.x; + position.x = 0f; + GUIContent gUIContent = new GUIContent("Deleted Assets"); + gUIContent.image = image; + int left = (int)this.m_BaseIndent; + s.padding.left = left; + if (current.type == EventType.Repaint) + { + s.Draw(position, gUIContent, false, false, this.SelType == ASHistoryFileView.SelectionType.DeletedItemsRoot, focused); + } + Rect position2 = new Rect(this.m_BaseIndent - this.m_FoldoutSize, offset, this.m_FoldoutSize, ASHistoryFileView.m_RowHeight); + if (!this.m_DeletedItemsInitialized || this.m_DelPVstate.lv.totalRows != 0) + { + this.DeletedItemsToggle = GUI.Toggle(position2, this.DeletedItemsToggle, GUIContent.none, ASHistoryFileView.ms_Styles.foldout); + } + offset += ASHistoryFileView.m_RowHeight; + if (!this.DeletedItemsToggle) + { + return; + } + int row = this.m_DelPVstate.lv.row; + int num = 0; + int num2 = -1; + int num3 = -1; + int num4 = 0; + while (offset <= endOffset && num4 < this.m_DelPVstate.lv.totalRows) + { + if (offset + ASHistoryFileView.m_RowHeight >= 0f) + { + if (num2 == -1) + { + this.m_DelPVstate.IndexToFolderAndFile(num4, ref num2, ref num3); + } + position = new Rect(0f, offset, (float)Screen.width, ASHistoryFileView.m_RowHeight); + ParentViewFolder parentViewFolder = this.m_DelPVstate.folders[num2]; + if (current.type == EventType.MouseDown && position.Contains(current.mousePosition)) + { + if (current.button != 1 || this.SelType != ASHistoryFileView.SelectionType.DeletedItems || !this.m_DelPVstate.selectedItems[num]) + { + GUIUtility.keyboardControl = this.m_FileViewControlID; + this.SelType = ASHistoryFileView.SelectionType.DeletedItems; + this.m_DelPVstate.lv.row = num; + ListViewShared.MultiSelection(null, row, this.m_DelPVstate.lv.row, ref this.m_DelPVstate.initialSelectedItem, ref this.m_DelPVstate.selectedItems); + this.ScrollToDeletedItem(num); + parentWin.DoLocalSelectionChange(); + } + if (current.button == 1 && this.SelType == ASHistoryFileView.SelectionType.DeletedItems) + { + GUIUtility.hotControl = 0; + Rect position3 = new Rect(current.mousePosition.x, current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position3, this.dropDownMenuItems, -1, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + } + Event.current.Use(); + } + if (num3 != -1) + { + gUIContent.text = parentViewFolder.files[num3].name; + gUIContent.image = InternalEditorUtility.GetIconForFile(parentViewFolder.files[num3].name); + left = (int)(this.m_BaseIndent + this.m_Indent * 2f); + } + else + { + gUIContent.text = parentViewFolder.name; + gUIContent.image = image; + left = (int)(this.m_BaseIndent + this.m_Indent); + } + s.padding.left = left; + if (Event.current.type == EventType.Repaint) + { + s.Draw(position, gUIContent, false, false, this.m_DelPVstate.selectedItems[num], focused); + } + this.m_DelPVstate.NextFileFolder(ref num2, ref num3); + num++; + } + num4++; + offset += ASHistoryFileView.m_RowHeight; + } + } + public void DoGUI(ASHistoryWindow parentWin, Rect theRect, bool focused) + { + if (ASHistoryFileView.ms_Styles == null) + { + ASHistoryFileView.ms_Styles = new ASHistoryFileView.Styles(); + } + this.m_ScreenRect = theRect; + Hashtable hashtable = new Hashtable(); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + hashtable.Add(@object.GetInstanceID(), null); + } + this.m_FileViewControlID = GUIUtility.GetControlID(ASHistoryFileView.ms_FileViewHash, FocusType.Native); + this.KeyboardGUI(parentWin); + focused &= (GUIUtility.keyboardControl == this.m_FileViewControlID); + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + int num = hierarchyProperty.CountRemaining(this.m_ExpandedArray); + int num2 = (!this.DeletedItemsToggle) ? 0 : this.m_DelPVstate.lv.totalRows; + Rect viewRect = new Rect(0f, 0f, 1f, (float)(num + 2 + num2) * ASHistoryFileView.m_RowHeight + 16f); + this.m_ScrollPosition = GUI.BeginScrollView(this.m_ScreenRect, this.m_ScrollPosition, viewRect); + theRect.width = ((viewRect.height <= this.m_ScreenRect.height) ? theRect.width : (theRect.width - 18f)); + int num3 = Mathf.RoundToInt(this.m_ScrollPosition.y - 6f - ASHistoryFileView.m_RowHeight) / Mathf.RoundToInt(ASHistoryFileView.m_RowHeight); + if (num3 > num) + { + num3 = num; + } + else + { + if (num3 < 0) + { + num3 = 0; + this.m_ScrollPosition.y = 0f; + } + } + GUIContent gUIContent = new GUIContent(); + Event current = Event.current; + GUIStyle gUIStyle = new GUIStyle(ASHistoryFileView.ms_Styles.label); + Texture2D image = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + float num4 = (float)num3 * ASHistoryFileView.m_RowHeight + 3f; + float num5 = this.m_ScreenRect.height + this.m_ScrollPosition.y; + Rect position = new Rect(0f, num4, theRect.width, ASHistoryFileView.m_RowHeight); + if (current.type == EventType.MouseDown && position.Contains(current.mousePosition)) + { + this.SelType = ASHistoryFileView.SelectionType.All; + GUIUtility.keyboardControl = this.m_FileViewControlID; + this.ScrollTo(0f); + parentWin.DoLocalSelectionChange(); + current.Use(); + } + gUIContent = new GUIContent("Entire Project"); + gUIContent.image = image; + int left = (int)this.m_BaseIndent; + gUIStyle.padding.left = 3; + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(position, gUIContent, false, false, this.SelType == ASHistoryFileView.SelectionType.All, focused); + } + num4 += ASHistoryFileView.m_RowHeight + 3f; + hierarchyProperty.Reset(); + hierarchyProperty.Skip(num3, this.m_ExpandedArray); + while (hierarchyProperty.Next(this.m_ExpandedArray) && num4 <= num5) + { + int instanceID = hierarchyProperty.instanceID; + position = new Rect(0f, num4, theRect.width, ASHistoryFileView.m_RowHeight); + if (Event.current.type == EventType.Repaint) + { + gUIContent.text = hierarchyProperty.name; + gUIContent.image = hierarchyProperty.icon; + left = (int)(this.m_BaseIndent + this.m_Indent * (float)hierarchyProperty.depth); + gUIStyle.padding.left = left; + bool on = hashtable.Contains(instanceID); + gUIStyle.Draw(position, gUIContent, false, false, on, focused); + } + if (hierarchyProperty.hasChildren) + { + bool flag = hierarchyProperty.IsExpanded(this.m_ExpandedArray); + GUI.changed = false; + Rect position2 = new Rect(this.m_BaseIndent + this.m_Indent * (float)hierarchyProperty.depth - this.m_FoldoutSize, num4, this.m_FoldoutSize, ASHistoryFileView.m_RowHeight); + flag = GUI.Toggle(position2, flag, GUIContent.none, ASHistoryFileView.ms_Styles.foldout); + if (GUI.changed) + { + if (Event.current.alt) + { + this.SetExpandedRecurse(instanceID, flag); + } + else + { + this.SetExpanded(instanceID, flag); + } + } + } + if (current.type == EventType.MouseDown && Event.current.button == 0 && position.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = this.m_FileViewControlID; + if (Event.current.clickCount == 2) + { + AssetDatabase.OpenAsset(instanceID); + GUIUtility.ExitGUI(); + } + else + { + if (position.Contains(current.mousePosition)) + { + this.SelectionClick(hierarchyProperty); + } + } + current.Use(); + } + num4 += ASHistoryFileView.m_RowHeight; + } + num4 += 3f; + this.DoDeletedItemsGUI(parentWin, theRect, gUIStyle, num4, num5, focused); + GUI.EndScrollView(); + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.MouseUp) + { + if (GUIUtility.hotControl == this.m_FileViewControlID) + { + if (this.m_ScreenRect.Contains(current.mousePosition)) + { + Selection.activeObject = null; + } + GUIUtility.hotControl = 0; + current.Use(); + } + } + } + else + { + if (current.button == 0 && this.m_ScreenRect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = this.m_FileViewControlID; + current.Use(); + } + } + this.HandleFraming(); + } + private void HandleFraming() + { + if ((Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) && Event.current.commandName == "FrameSelected") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.DoFramingMindSelectionType(); + } + HandleUtility.Repaint(); + Event.current.Use(); + } + } + private void DoFramingMindSelectionType() + { + switch (this.m_SelType) + { + case ASHistoryFileView.SelectionType.All: + this.ScrollTo(0f); + break; + case ASHistoryFileView.SelectionType.Items: + this.FrameObject(Selection.activeObject); + break; + case ASHistoryFileView.SelectionType.DeletedItemsRoot: + this.ScrollToDeletedItem(-1); + break; + case ASHistoryFileView.SelectionType.DeletedItems: + this.ScrollToDeletedItem(this.m_DelPVstate.lv.row); + break; + } + } + private List GetOneFolderImplicitSelection(HierarchyProperty property, Hashtable selection, bool rootSelected, ref bool retHasSelectionInside, out bool eof) + { + int depth = property.depth; + bool flag = false; + bool flag2 = false; + eof = false; + List list = new List(); + List list2 = new List(); + List list3 = new List(); + do + { + if (property.depth > depth) + { + list3.AddRange(this.GetOneFolderImplicitSelection(property, selection, rootSelected || flag2, ref flag, out eof)); + } + if (depth != property.depth || eof) + { + break; + } + if (rootSelected && !flag) + { + list.Add(property.instanceID); + } + if (selection.Contains(property.instanceID)) + { + list2.Add(property.instanceID); + flag = true; + flag2 = true; + } + else + { + flag2 = false; + } + eof = !property.Next(null); + } + while (!eof); + retHasSelectionInside |= flag; + List list4 = (rootSelected && !flag) ? list : list2; + list4.AddRange(list3); + return list4; + } + public string[] GetImplicitProjectViewSelection() + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + bool flag = false; + if (!hierarchyProperty.Next(null)) + { + return new string[0]; + } + Hashtable hashtable = new Hashtable(); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + hashtable.Add(@object.GetInstanceID(), null); + } + bool flag2; + List oneFolderImplicitSelection = this.GetOneFolderImplicitSelection(hierarchyProperty, hashtable, false, ref flag, out flag2); + string[] array = new string[oneFolderImplicitSelection.Count]; + for (int j = 0; j < array.Length; j++) + { + array[j] = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(oneFolderImplicitSelection[j])); + } + return array; + } + } +} diff --git a/UnityEditor/UnityEditor/ASHistoryWindow.cs b/UnityEditor/UnityEditor/ASHistoryWindow.cs new file mode 100644 index 00000000..8214e097 --- /dev/null +++ b/UnityEditor/UnityEditor/ASHistoryWindow.cs @@ -0,0 +1,1084 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASHistoryWindow + { + internal class Constants + { + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle lvHeader = "OL title"; + public GUIStyle button = "Button"; + public GUIStyle label = "PR Label"; + public GUIStyle descriptionLabel = "Label"; + public GUIStyle entryEven = "CN EntryBackEven"; + public GUIStyle entryOdd = "CN EntryBackOdd"; + public GUIStyle boldLabel = "BoldLabel"; + public GUIStyle foldout = "IN Foldout"; + public GUIStyle ping = new GUIStyle("PR Ping"); + public Constants() + { + this.ping.overflow.left = -2; + this.ping.overflow.right = -21; + this.ping.padding.left = 48; + this.ping.padding.right = 0; + } + } + [Serializable] + private class GUIHistoryListItem + { + public GUIContent colAuthor; + public GUIContent colRevision; + public GUIContent colDate; + public GUIContent colDescription; + public ParentViewState assets; + public int totalLineCount; + public bool[] boldAssets; + public int height; + public bool inFilter; + public int collapsedItemCount; + public int startShowingFrom; + } + private const int kFirst = -999999; + private const int kLast = 999999; + private const int kUncollapsedItemsCount = 5; + private static ASHistoryWindow.Constants ms_Style = null; + private static int ms_HistoryControlHash = "HistoryControl".GetHashCode(); + private SplitterState m_HorSplit = new SplitterState(new float[] + { + 30f, + 70f + }, new int[] + { + 60, + 100 + }, null); + private static Vector2 ms_IconSize = new Vector2(16f, 16f); + private bool m_NextSelectionMine; + private ASHistoryWindow.GUIHistoryListItem[] m_GUIItems; + private int m_TotalHeight; + private Vector2 m_ScrollPos = Vector2.zero; + private bool m_SplittersOk; + private int m_RowHeight = 16; + private int m_HistoryControlID = -1; + private int m_ChangesetSelectionIndex = -1; + private int m_AssetSelectionIndex = -1; + private int m_ChangeLogSelectionRev = -1; + private bool m_BinaryDiff; + private int m_Rev1ForCustomDiff = -1; + private int m_ScrollViewHeight; + private string m_ChangeLogSelectionGUID = string.Empty; + private string m_ChangeLogSelectionAssetName = string.Empty; + private string m_SelectedPath = string.Empty; + private string m_SelectedGUID = string.Empty; + private bool m_FolderSelected; + private bool m_InRevisionSelectMode; + private static GUIContent emptyGUIContent = new GUIContent(); + private GUIContent[] m_DropDownMenuItems = new GUIContent[] + { + EditorGUIUtility.TextContent("Show History"), + ASHistoryWindow.emptyGUIContent, + EditorGUIUtility.TextContent("Compare to Local"), + EditorGUIUtility.TextContent("Compare Binary to Local"), + ASHistoryWindow.emptyGUIContent, + EditorGUIUtility.TextContent("Compare to Another Revision"), + EditorGUIUtility.TextContent("Compare Binary to Another Revision"), + ASHistoryWindow.emptyGUIContent, + EditorGUIUtility.TextContent("Download This File") + }; + private GUIContent[] m_DropDownChangesetMenuItems = new GUIContent[] + { + EditorGUIUtility.TextContent("Revert Entire Project to This Changeset") + }; + private EditorWindow m_ParentWindow; + private Changeset[] m_Changesets; + private ASHistoryFileView m_FileViewWin = new ASHistoryFileView(); + private int ChangeLogSelectionRev + { + get + { + return this.m_ChangeLogSelectionRev; + } + set + { + this.m_ChangeLogSelectionRev = value; + if (this.m_InRevisionSelectMode) + { + this.FinishShowCustomDiff(); + } + } + } + public ASHistoryWindow(EditorWindow parent) + { + this.m_ParentWindow = parent; + ASEditorBackend.SettingsIfNeeded(); + if (Selection.objects.Length != 0) + { + this.m_FileViewWin.SelType = ASHistoryFileView.SelectionType.Items; + } + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + switch (selected) + { + case 0: + this.ShowAssetsHistory(); + break; + case 2: + this.DoShowDiff(false, this.ChangeLogSelectionRev, -1); + break; + case 3: + this.DoShowDiff(true, this.ChangeLogSelectionRev, -1); + break; + case 5: + this.DoShowCustomDiff(false); + break; + case 6: + this.DoShowCustomDiff(true); + break; + case 8: + this.DownloadFile(); + break; + } + } + } + private void DownloadFile() + { + if (this.ChangeLogSelectionRev < 0 || this.m_ChangeLogSelectionGUID == string.Empty) + { + return; + } + if (EditorUtility.DisplayDialog("Download file", string.Concat(new string[] + { + "Are you sure you want to download '", + this.m_ChangeLogSelectionAssetName, + "' from revision ", + this.ChangeLogSelectionRev.ToString(), + " and lose all changes?" + }), "Download", "Cancel")) + { + AssetServer.DoRevertOnNextTick(this.ChangeLogSelectionRev, this.m_ChangeLogSelectionGUID); + } + } + private void ShowAssetsHistory() + { + if (AssetServer.IsAssetAvailable(this.m_ChangeLogSelectionGUID) != 0) + { + string[] selectionFromGUIDs = new string[] + { + this.m_ChangeLogSelectionGUID + }; + this.m_FileViewWin.SelType = ASHistoryFileView.SelectionType.Items; + AssetServer.SetSelectionFromGUIDs(selectionFromGUIDs); + } + else + { + this.m_FileViewWin.SelectDeletedItem(this.m_ChangeLogSelectionGUID); + this.DoLocalSelectionChange(); + } + } + private void ChangesetContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + if (selected == 0) + { + this.DoRevertProject(); + } + } + } + private void DoRevertProject() + { + if (this.ChangeLogSelectionRev > 0) + { + ASEditorBackend.ASWin.RevertProject(this.ChangeLogSelectionRev, this.m_Changesets); + } + } + private int MarkBoldItemsBySelection(ASHistoryWindow.GUIHistoryListItem item) + { + List list = new List(); + ParentViewState assets = item.assets; + int num = -1; + int num2 = 0; + if (Selection.instanceIDs.Length == 0) + { + return 0; + } + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + list.Add(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(instanceID))); + } + for (int j = 0; j < assets.folders.Length; j++) + { + ParentViewFolder parentViewFolder = assets.folders[j]; + if (list.Contains(parentViewFolder.guid)) + { + item.boldAssets[num2] = true; + if (num == -1) + { + num = num2; + } + } + num2++; + for (int k = 0; k < parentViewFolder.files.Length; k++) + { + if (list.Contains(parentViewFolder.files[k].guid)) + { + item.boldAssets[num2] = true; + if (num == -1) + { + num = num2; + } + } + num2++; + } + } + return num; + } + private int CheckParentViewInFilterAndMarkBoldItems(ASHistoryWindow.GUIHistoryListItem item, string text) + { + ParentViewState assets = item.assets; + int num = -1; + int num2 = 0; + for (int i = 0; i < assets.folders.Length; i++) + { + ParentViewFolder parentViewFolder = assets.folders[i]; + if (parentViewFolder.name.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) != -1) + { + item.boldAssets[num2] = true; + if (num == -1) + { + num = num2; + } + } + num2++; + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + if (parentViewFolder.files[j].name.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) != -1) + { + item.boldAssets[num2] = true; + if (num == -1) + { + num = num2; + } + } + num2++; + } + } + return num; + } + private void MarkBoldItemsByGUID(string guid) + { + for (int i = 0; i < this.m_GUIItems.Length; i++) + { + ASHistoryWindow.GUIHistoryListItem gUIHistoryListItem = this.m_GUIItems[i]; + ParentViewState assets = gUIHistoryListItem.assets; + int num = 0; + gUIHistoryListItem.boldAssets = new bool[assets.GetLineCount()]; + for (int j = 0; j < assets.folders.Length; j++) + { + ParentViewFolder parentViewFolder = assets.folders[j]; + if (parentViewFolder.guid == guid) + { + gUIHistoryListItem.boldAssets[num] = true; + } + num++; + for (int k = 0; k < parentViewFolder.files.Length; k++) + { + if (parentViewFolder.files[k].guid == guid) + { + gUIHistoryListItem.boldAssets[num] = true; + } + num++; + } + } + } + } + public void FilterItems(bool recreateGUIItems) + { + this.m_TotalHeight = 0; + if (this.m_Changesets == null || this.m_Changesets.Length == 0) + { + this.m_GUIItems = null; + return; + } + if (recreateGUIItems) + { + this.m_GUIItems = new ASHistoryWindow.GUIHistoryListItem[this.m_Changesets.Length]; + } + string filterText = ((ASMainWindow)this.m_ParentWindow).m_SearchField.FilterText; + bool flag = filterText.Trim() == string.Empty; + for (int i = 0; i < this.m_Changesets.Length; i++) + { + if (recreateGUIItems) + { + this.m_GUIItems[i] = new ASHistoryWindow.GUIHistoryListItem(); + this.m_GUIItems[i].colAuthor = new GUIContent(this.m_Changesets[i].owner); + this.m_GUIItems[i].colRevision = new GUIContent(this.m_Changesets[i].changeset.ToString()); + this.m_GUIItems[i].colDate = new GUIContent(this.m_Changesets[i].date); + this.m_GUIItems[i].colDescription = new GUIContent(this.m_Changesets[i].message); + this.m_GUIItems[i].assets = new ParentViewState(); + this.m_GUIItems[i].assets.AddAssetItems(this.m_Changesets[i]); + this.m_GUIItems[i].totalLineCount = this.m_GUIItems[i].assets.GetLineCount(); + this.m_GUIItems[i].height = this.m_RowHeight * (1 + this.m_GUIItems[i].totalLineCount) + 20 + (int)ASHistoryWindow.ms_Style.descriptionLabel.CalcHeight(this.m_GUIItems[i].colDescription, 3.40282347E+38f); + } + this.m_GUIItems[i].boldAssets = new bool[this.m_GUIItems[i].assets.GetLineCount()]; + int num = (!flag) ? this.CheckParentViewInFilterAndMarkBoldItems(this.m_GUIItems[i], filterText) : this.MarkBoldItemsBySelection(this.m_GUIItems[i]); + this.m_GUIItems[i].inFilter = (flag || num != -1 || this.m_GUIItems[i].colDescription.text.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0 || this.m_GUIItems[i].colRevision.text.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0 || this.m_GUIItems[i].colAuthor.text.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0 || this.m_GUIItems[i].colDate.text.IndexOf(filterText, StringComparison.InvariantCultureIgnoreCase) >= 0); + if (recreateGUIItems && this.m_GUIItems[i].totalLineCount > 5) + { + this.m_GUIItems[i].collapsedItemCount = this.m_GUIItems[i].totalLineCount - 5 + 1; + this.m_GUIItems[i].height = this.m_RowHeight * 6 + 20 + (int)ASHistoryWindow.ms_Style.descriptionLabel.CalcHeight(this.m_GUIItems[i].colDescription, 3.40282347E+38f); + } + this.m_GUIItems[i].startShowingFrom = 0; + if (this.m_GUIItems[i].collapsedItemCount != 0 && this.m_GUIItems[i].totalLineCount > 5 && num >= 4) + { + if (num + 5 - 1 > this.m_GUIItems[i].totalLineCount) + { + this.m_GUIItems[i].startShowingFrom = this.m_GUIItems[i].totalLineCount - 5 + 1; + } + else + { + this.m_GUIItems[i].startShowingFrom = num; + } + } + if (this.m_GUIItems[i].inFilter) + { + this.m_TotalHeight += this.m_GUIItems[i].height; + } + } + } + private void UncollapseListItem(ref ASHistoryWindow.GUIHistoryListItem item) + { + int num = (item.collapsedItemCount - 1) * this.m_RowHeight; + item.collapsedItemCount = 0; + item.startShowingFrom = 0; + item.height += num; + this.m_TotalHeight += num; + } + private void ClearLV() + { + this.m_Changesets = new Changeset[0]; + this.m_TotalHeight = 5; + } + public void DoLocalSelectionChange() + { + if (this.m_NextSelectionMine) + { + this.m_NextSelectionMine = false; + return; + } + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + string[] array = new string[0]; + switch (this.m_FileViewWin.SelType) + { + case ASHistoryFileView.SelectionType.All: + if (Selection.objects.Length != 0) + { + Selection.objects = new UnityEngine.Object[0]; + this.m_NextSelectionMine = true; + } + this.m_SelectedPath = string.Empty; + this.m_SelectedGUID = string.Empty; + this.ClearLV(); + break; + case ASHistoryFileView.SelectionType.Items: + if (filtered.Length < 1) + { + this.m_SelectedPath = string.Empty; + this.m_SelectedGUID = string.Empty; + this.ClearLV(); + return; + } + this.m_SelectedPath = AssetDatabase.GetAssetPath(filtered[0]); + this.m_SelectedGUID = AssetDatabase.AssetPathToGUID(this.m_SelectedPath); + array = this.m_FileViewWin.GetImplicitProjectViewSelection(); + break; + case ASHistoryFileView.SelectionType.DeletedItemsRoot: + if (Selection.objects.Length != 0) + { + Selection.objects = new UnityEngine.Object[0]; + this.m_NextSelectionMine = true; + } + array = this.m_FileViewWin.GetAllDeletedItemGUIDs(); + if (array.Length == 0) + { + this.ClearLV(); + return; + } + break; + case ASHistoryFileView.SelectionType.DeletedItems: + if (Selection.objects.Length != 0) + { + Selection.objects = new UnityEngine.Object[0]; + this.m_NextSelectionMine = true; + } + array = this.m_FileViewWin.GetSelectedDeletedItemGUIDs(); + break; + } + this.m_Changesets = AssetServer.GetHistorySelected(array); + if (this.m_Changesets != null) + { + this.FilterItems(true); + } + else + { + this.ClearLV(); + } + if (array != null && this.m_GUIItems != null && array.Length == 1) + { + this.MarkBoldItemsByGUID(this.m_SelectedGUID); + } + this.m_ParentWindow.Repaint(); + } + public void OnSelectionChange() + { + if (Selection.objects.Length != 0) + { + this.m_FileViewWin.SelType = ASHistoryFileView.SelectionType.Items; + } + this.DoLocalSelectionChange(); + } + private void DoShowDiff(bool binary, int ver1, int ver2) + { + List list = new List(); + List list2 = new List(); + if (ver2 == -1 && AssetDatabase.GUIDToAssetPath(this.m_ChangeLogSelectionGUID) == string.Empty) + { + Debug.Log("Cannot compare asset " + this.m_ChangeLogSelectionAssetName + " to local version because it does not exists."); + return; + } + list.Add(this.m_ChangeLogSelectionGUID); + list2.Add(new CompareInfo(ver1, ver2, (!binary) ? 0 : 1, (!binary) ? 1 : 0)); + Debug.Log(string.Concat(new string[] + { + "Comparing asset ", + this.m_ChangeLogSelectionAssetName, + " revisions ", + ver1.ToString(), + " and ", + (ver2 != -1) ? ver2.ToString() : "Local" + })); + AssetServer.CompareFiles(list.ToArray(), list2.ToArray()); + } + private void DoShowCustomDiff(bool binary) + { + this.ShowAssetsHistory(); + this.m_InRevisionSelectMode = true; + this.m_BinaryDiff = binary; + this.m_Rev1ForCustomDiff = this.ChangeLogSelectionRev; + } + private void FinishShowCustomDiff() + { + if (this.m_Rev1ForCustomDiff != this.ChangeLogSelectionRev) + { + this.DoShowDiff(this.m_BinaryDiff, this.m_Rev1ForCustomDiff, this.ChangeLogSelectionRev); + } + else + { + Debug.Log("You chose to compare to the same revision."); + } + this.m_InRevisionSelectMode = false; + } + private void CancelShowCustomDiff() + { + this.m_InRevisionSelectMode = false; + } + private bool IsComparableAssetSelected() + { + return !this.m_FolderSelected && this.m_ChangeLogSelectionGUID != string.Empty; + } + private void DrawBadge(Rect offset, ChangeFlags flags, GUIStyle style, GUIContent content, float textColWidth) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + GUIContent gUIContent = null; + if (this.HasFlag(flags, ChangeFlags.Undeleted) || this.HasFlag(flags, ChangeFlags.Created)) + { + gUIContent = ASMainWindow.badgeNew; + } + else + { + if (this.HasFlag(flags, ChangeFlags.Deleted)) + { + gUIContent = ASMainWindow.badgeDelete; + } + else + { + if (this.HasFlag(flags, ChangeFlags.Renamed) || this.HasFlag(flags, ChangeFlags.Moved)) + { + gUIContent = ASMainWindow.badgeMove; + } + } + } + if (gUIContent != null) + { + float x = style.CalcSize(content).x; + float left; + if (x > textColWidth - (float)gUIContent.image.width) + { + left = offset.xMax - (float)gUIContent.image.width - 5f; + } + else + { + left = textColWidth - (float)gUIContent.image.width; + } + Rect position = new Rect(left, offset.y + offset.height / 2f - (float)(gUIContent.image.height / 2), (float)gUIContent.image.width, (float)gUIContent.image.height); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUIStyle.none.Draw(position, gUIContent, false, false, false, false); + EditorGUIUtility.SetIconSize(ASHistoryWindow.ms_IconSize); + } + } + private bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) + { + return (flagToCheck & flags) != ChangeFlags.None; + } + private void ClearItemSelection() + { + this.m_ChangeLogSelectionGUID = string.Empty; + this.m_ChangeLogSelectionAssetName = string.Empty; + this.m_FolderSelected = false; + this.m_AssetSelectionIndex = -1; + } + private void DrawParentView(Rect r, ref ASHistoryWindow.GUIHistoryListItem item, int changesetIndex, bool hasFocus) + { + ParentViewState assets = item.assets; + GUIContent gUIContent = new GUIContent(); + Texture2D image = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + Event current = Event.current; + hasFocus &= (this.m_HistoryControlID == GUIUtility.keyboardControl); + r.height = (float)this.m_RowHeight; + r.y += 3f; + int num = -1; + int num2 = (item.collapsedItemCount == 0) ? item.totalLineCount : 4; + num2 += item.startShowingFrom; + for (int i = 0; i < assets.folders.Length; i++) + { + ParentViewFolder parentViewFolder = assets.folders[i]; + gUIContent.text = parentViewFolder.name; + gUIContent.image = image; + num++; + if (num == num2) + { + break; + } + if (num >= item.startShowingFrom) + { + GUIStyle label = ASHistoryWindow.ms_Style.label; + if (current.type == EventType.MouseDown && r.Contains(current.mousePosition)) + { + if (this.ChangeLogSelectionRev == this.m_Changesets[changesetIndex].changeset && this.m_ChangeLogSelectionGUID == parentViewFolder.guid && EditorGUI.actionKey) + { + this.ClearItemSelection(); + } + else + { + this.ChangeLogSelectionRev = this.m_Changesets[changesetIndex].changeset; + this.m_ChangeLogSelectionGUID = parentViewFolder.guid; + this.m_ChangeLogSelectionAssetName = parentViewFolder.name; + this.m_FolderSelected = true; + this.m_AssetSelectionIndex = num; + } + this.m_ChangesetSelectionIndex = changesetIndex; + GUIUtility.keyboardControl = this.m_HistoryControlID; + ((ASMainWindow)this.m_ParentWindow).m_SearchToShow = ASMainWindow.ShowSearchField.HistoryList; + if (current.clickCount == 2) + { + this.ShowAssetsHistory(); + GUIUtility.ExitGUI(); + } + else + { + if (current.button == 1) + { + GUIUtility.hotControl = 0; + r = new Rect(current.mousePosition.x, current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(r, this.m_DropDownMenuItems, -1, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + } + } + this.DoScroll(); + current.Use(); + } + bool flag = this.ChangeLogSelectionRev == this.m_Changesets[changesetIndex].changeset && this.m_ChangeLogSelectionGUID == parentViewFolder.guid; + if (item.boldAssets[num] && !flag) + { + GUI.Label(r, string.Empty, ASHistoryWindow.ms_Style.ping); + } + if (Event.current.type == EventType.Repaint) + { + label.Draw(r, gUIContent, false, false, flag, hasFocus); + this.DrawBadge(r, parentViewFolder.changeFlags, label, gUIContent, GUIClip.visibleRect.width - 150f); + } + r.y += (float)this.m_RowHeight; + } + ASHistoryWindow.ms_Style.label.padding.left += 16; + ASHistoryWindow.ms_Style.boldLabel.padding.left += 16; + try + { + for (int j = 0; j < parentViewFolder.files.Length; j++) + { + num++; + if (num == num2) + { + break; + } + if (num >= item.startShowingFrom) + { + GUIStyle label = ASHistoryWindow.ms_Style.label; + if (current.type == EventType.MouseDown && r.Contains(current.mousePosition)) + { + if (this.ChangeLogSelectionRev == this.m_Changesets[changesetIndex].changeset && this.m_ChangeLogSelectionGUID == parentViewFolder.files[j].guid && EditorGUI.actionKey) + { + this.ClearItemSelection(); + } + else + { + this.ChangeLogSelectionRev = this.m_Changesets[changesetIndex].changeset; + this.m_ChangeLogSelectionGUID = parentViewFolder.files[j].guid; + this.m_ChangeLogSelectionAssetName = parentViewFolder.files[j].name; + this.m_FolderSelected = false; + this.m_AssetSelectionIndex = num; + } + this.m_ChangesetSelectionIndex = changesetIndex; + GUIUtility.keyboardControl = this.m_HistoryControlID; + ((ASMainWindow)this.m_ParentWindow).m_SearchToShow = ASMainWindow.ShowSearchField.HistoryList; + if (current.clickCount == 2) + { + if (this.IsComparableAssetSelected() && this.m_SelectedGUID == this.m_ChangeLogSelectionGUID) + { + this.DoShowDiff(false, this.ChangeLogSelectionRev, -1); + } + else + { + this.ShowAssetsHistory(); + GUIUtility.ExitGUI(); + } + } + else + { + if (current.button == 1) + { + GUIUtility.hotControl = 0; + r = new Rect(current.mousePosition.x, current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(r, this.m_DropDownMenuItems, -1, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + } + } + this.DoScroll(); + current.Use(); + } + gUIContent.text = parentViewFolder.files[j].name; + gUIContent.image = InternalEditorUtility.GetIconForFile(parentViewFolder.files[j].name); + bool flag2 = this.ChangeLogSelectionRev == this.m_Changesets[changesetIndex].changeset && this.m_ChangeLogSelectionGUID == parentViewFolder.files[j].guid; + if (item.boldAssets[num] && !flag2) + { + GUI.Label(r, string.Empty, ASHistoryWindow.ms_Style.ping); + } + if (Event.current.type == EventType.Repaint) + { + label.Draw(r, gUIContent, false, false, flag2, hasFocus); + this.DrawBadge(r, parentViewFolder.files[j].changeFlags, label, gUIContent, GUIClip.visibleRect.width - 150f); + } + r.y += (float)this.m_RowHeight; + } + } + if (num == num2) + { + break; + } + } + finally + { + ASHistoryWindow.ms_Style.label.padding.left -= 16; + ASHistoryWindow.ms_Style.boldLabel.padding.left -= 16; + } + } + if ((num == num2 || num2 >= item.totalLineCount) && item.collapsedItemCount != 0) + { + r.x += 19f; + if (GUI.Button(r, item.collapsedItemCount.ToString() + " more...", ASHistoryWindow.ms_Style.foldout)) + { + GUIUtility.keyboardControl = this.m_HistoryControlID; + this.UncollapseListItem(ref item); + } + } + } + private int FindFirstUnfilteredItem(int fromIndex, int direction) + { + int num = fromIndex; + while (num >= 0 && num < this.m_GUIItems.Length) + { + if (this.m_GUIItems[num].inFilter) + { + return num; + } + num += direction; + } + return -1; + } + private void MoveSelection(int steps) + { + if (this.m_ChangeLogSelectionGUID == string.Empty) + { + int num = (int)Mathf.Sign((float)steps); + steps = Mathf.Abs(steps); + for (int i = 0; i < steps; i++) + { + int num2 = this.FindFirstUnfilteredItem(this.m_ChangesetSelectionIndex + num, num); + if (num2 == -1) + { + break; + } + this.m_ChangesetSelectionIndex = num2; + } + this.ChangeLogSelectionRev = this.m_Changesets[this.m_ChangesetSelectionIndex].changeset; + } + else + { + this.m_AssetSelectionIndex += steps; + if (this.m_AssetSelectionIndex < this.m_GUIItems[this.m_ChangesetSelectionIndex].startShowingFrom) + { + this.m_AssetSelectionIndex = this.m_GUIItems[this.m_ChangesetSelectionIndex].startShowingFrom; + } + else + { + int lineCount = this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.GetLineCount(); + if (this.m_AssetSelectionIndex >= 4 + this.m_GUIItems[this.m_ChangesetSelectionIndex].startShowingFrom && this.m_GUIItems[this.m_ChangesetSelectionIndex].collapsedItemCount != 0) + { + this.UncollapseListItem(ref this.m_GUIItems[this.m_ChangesetSelectionIndex]); + } + if (this.m_AssetSelectionIndex >= lineCount) + { + this.m_AssetSelectionIndex = lineCount - 1; + } + } + int num3 = 0; + int num4 = 0; + if (this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.IndexToFolderAndFile(this.m_AssetSelectionIndex, ref num3, ref num4)) + { + if (num4 == -1) + { + this.m_ChangeLogSelectionGUID = this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.folders[num3].guid; + } + else + { + this.m_ChangeLogSelectionGUID = this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.folders[num3].files[num4].guid; + } + } + } + } + private void HandleWebLikeKeyboard() + { + Event current = Event.current; + if (current.GetTypeForControl(this.m_HistoryControlID) == EventType.KeyDown && this.m_GUIItems.Length != 0) + { + KeyCode keyCode = current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_71; + case KeyCode.KeypadEquals: + case KeyCode.Insert: + IL_64: + if (keyCode != KeyCode.Return) + { + return; + } + goto IL_71; + case KeyCode.UpArrow: + this.MoveSelection(-1); + goto IL_2A3; + case KeyCode.DownArrow: + this.MoveSelection(1); + goto IL_2A3; + case KeyCode.RightArrow: + if (this.m_ChangeLogSelectionGUID == string.Empty && this.m_GUIItems.Length > 0) + { + this.m_ChangeLogSelectionGUID = this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.folders[0].guid; + this.m_ChangeLogSelectionAssetName = this.m_GUIItems[this.m_ChangesetSelectionIndex].assets.folders[0].name; + this.m_FolderSelected = true; + this.m_AssetSelectionIndex = 0; + } + goto IL_2A3; + case KeyCode.LeftArrow: + this.m_ChangeLogSelectionGUID = string.Empty; + goto IL_2A3; + case KeyCode.Home: + if (this.m_ChangeLogSelectionGUID == string.Empty) + { + int num = this.FindFirstUnfilteredItem(0, 1); + if (num != -1) + { + this.m_ChangesetSelectionIndex = num; + } + this.ChangeLogSelectionRev = this.m_Changesets[this.m_ChangesetSelectionIndex].changeset; + } + else + { + this.MoveSelection(-999999); + } + goto IL_2A3; + case KeyCode.End: + if (this.m_ChangeLogSelectionGUID == string.Empty) + { + int num2 = this.FindFirstUnfilteredItem(this.m_GUIItems.Length - 1, -1); + if (num2 != -1) + { + this.m_ChangesetSelectionIndex = num2; + } + this.ChangeLogSelectionRev = this.m_Changesets[this.m_ChangesetSelectionIndex].changeset; + } + else + { + this.MoveSelection(999999); + } + goto IL_2A3; + case KeyCode.PageUp: + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_ScrollPos.y = this.m_ScrollPos.y - (float)this.m_ScrollViewHeight; + if (this.m_ScrollPos.y < 0f) + { + this.m_ScrollPos.y = 0f; + } + } + else + { + this.MoveSelection(-Mathf.RoundToInt((float)(this.m_ScrollViewHeight / this.m_RowHeight))); + } + goto IL_2A3; + case KeyCode.PageDown: + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_ScrollPos.y = this.m_ScrollPos.y + (float)this.m_ScrollViewHeight; + } + else + { + this.MoveSelection(Mathf.RoundToInt((float)(this.m_ScrollViewHeight / this.m_RowHeight))); + } + goto IL_2A3; + } + goto IL_64; + IL_71: + if (this.IsComparableAssetSelected()) + { + this.DoShowDiff(false, this.ChangeLogSelectionRev, -1); + } + IL_2A3: + this.DoScroll(); + current.Use(); + } + } + private void WebLikeHistory(bool hasFocus) + { + if (this.m_Changesets == null) + { + this.m_Changesets = new Changeset[0]; + } + if (this.m_GUIItems == null) + { + return; + } + this.m_HistoryControlID = GUIUtility.GetControlID(ASHistoryWindow.ms_HistoryControlHash, FocusType.Native); + this.HandleWebLikeKeyboard(); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(this.m_HistoryControlID); + if (typeForControl == EventType.ValidateCommand) + { + current.Use(); + return; + } + GUILayout.Space(1f); + this.m_ScrollPos = GUILayout.BeginScrollView(this.m_ScrollPos, new GUILayoutOption[0]); + int num = 0; + GUILayoutUtility.GetRect(1f, (float)(this.m_TotalHeight - 1)); + if ((current.type == EventType.Repaint || current.type == EventType.MouseDown || current.type == EventType.MouseUp) && this.m_GUIItems != null) + { + for (int i = 0; i < this.m_Changesets.Length; i++) + { + if (this.m_GUIItems[i].inFilter) + { + if ((float)(num + this.m_GUIItems[i].height) > GUIClip.visibleRect.y && (float)num < GUIClip.visibleRect.yMax) + { + float num2 = ASHistoryWindow.ms_Style.descriptionLabel.CalcHeight(this.m_GUIItems[i].colDescription, 3.40282347E+38f); + Rect rect; + if (current.type == EventType.Repaint) + { + if (this.ChangeLogSelectionRev == this.m_Changesets[i].changeset && Event.current.type == EventType.Repaint) + { + rect = new Rect(0f, (float)num, GUIClip.visibleRect.width, (float)(this.m_GUIItems[i].height - 10)); + ASHistoryWindow.ms_Style.selected.Draw(rect, false, false, false, false); + } + rect = new Rect(0f, (float)(num + 3), GUIClip.visibleRect.width, (float)this.m_GUIItems[i].height); + GUI.Label(rect, this.m_GUIItems[i].colAuthor, ASHistoryWindow.ms_Style.boldLabel); + rect = new Rect(GUIClip.visibleRect.width - 160f, (float)(num + 3), 60f, (float)this.m_GUIItems[i].height); + GUI.Label(rect, this.m_GUIItems[i].colRevision, ASHistoryWindow.ms_Style.boldLabel); + rect.x += 60f; + rect.width = 100f; + GUI.Label(rect, this.m_GUIItems[i].colDate, ASHistoryWindow.ms_Style.boldLabel); + rect.x = (float)ASHistoryWindow.ms_Style.boldLabel.margin.left; + rect.y += (float)this.m_RowHeight; + rect.width = GUIClip.visibleRect.width; + rect.height = num2; + GUI.Label(rect, this.m_GUIItems[i].colDescription, ASHistoryWindow.ms_Style.descriptionLabel); + rect.y += num2; + } + rect = new Rect(0f, (float)num + num2 + (float)this.m_RowHeight, GUIClip.visibleRect.width, (float)this.m_GUIItems[i].height - num2 - (float)this.m_RowHeight); + this.DrawParentView(rect, ref this.m_GUIItems[i], i, hasFocus); + if (current.type == EventType.MouseDown) + { + rect = new Rect(0f, (float)num, GUIClip.visibleRect.width, (float)(this.m_GUIItems[i].height - 10)); + if (rect.Contains(current.mousePosition)) + { + this.ChangeLogSelectionRev = this.m_Changesets[i].changeset; + this.m_ChangesetSelectionIndex = i; + GUIUtility.keyboardControl = this.m_HistoryControlID; + ((ASMainWindow)this.m_ParentWindow).m_SearchToShow = ASMainWindow.ShowSearchField.HistoryList; + if (current.button == 1) + { + GUIUtility.hotControl = 0; + rect = new Rect(current.mousePosition.x, current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(rect, this.m_DropDownChangesetMenuItems, -1, new EditorUtility.SelectMenuItemFunction(this.ChangesetContextMenuClick), null); + Event.current.Use(); + } + this.DoScroll(); + current.Use(); + } + } + } + num += this.m_GUIItems[i].height; + } + } + } + else + { + if (this.m_GUIItems == null) + { + GUILayout.Label(EditorGUIUtility.TextContent("This item is not yet committed to the Asset Server"), new GUILayoutOption[0]); + } + } + if (Event.current.type == EventType.Repaint) + { + this.m_ScrollViewHeight = (int)GUIClip.visibleRect.height; + } + GUILayout.EndScrollView(); + } + private void DoScroll() + { + int num = 0; + int i; + for (i = 0; i < this.m_ChangesetSelectionIndex; i++) + { + if (this.m_GUIItems[i].inFilter) + { + num += this.m_GUIItems[i].height; + } + } + float num2; + float min; + if (this.m_ChangeLogSelectionGUID != string.Empty) + { + num2 = (float)(num + (2 + this.m_AssetSelectionIndex) * this.m_RowHeight + 5); + min = num2 - (float)this.m_ScrollViewHeight + (float)this.m_RowHeight; + } + else + { + num2 = (float)num; + min = num2 - (float)this.m_ScrollViewHeight + (float)this.m_GUIItems[i].height - 10f; + } + this.m_ScrollPos.y = Mathf.Clamp(this.m_ScrollPos.y, min, num2); + } + public bool DoGUI(bool hasFocus) + { + bool enabled = GUI.enabled; + if (ASHistoryWindow.ms_Style == null) + { + ASHistoryWindow.ms_Style = new ASHistoryWindow.Constants(); + ASHistoryWindow.ms_Style.entryEven = new GUIStyle(ASHistoryWindow.ms_Style.entryEven); + ASHistoryWindow.ms_Style.entryEven.padding.left = 3; + ASHistoryWindow.ms_Style.entryOdd = new GUIStyle(ASHistoryWindow.ms_Style.entryOdd); + ASHistoryWindow.ms_Style.entryOdd.padding.left = 3; + ASHistoryWindow.ms_Style.label = new GUIStyle(ASHistoryWindow.ms_Style.label); + ASHistoryWindow.ms_Style.boldLabel = new GUIStyle(ASHistoryWindow.ms_Style.boldLabel); + ASHistoryWindow.ms_Style.label.padding.left = 3; + ASHistoryWindow.ms_Style.boldLabel.padding.left = 3; + ASHistoryWindow.ms_Style.boldLabel.padding.top = 0; + ASHistoryWindow.ms_Style.boldLabel.padding.bottom = 0; + this.DoLocalSelectionChange(); + } + EditorGUIUtility.SetIconSize(ASHistoryWindow.ms_IconSize); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.CancelShowCustomDiff(); + Event.current.Use(); + } + SplitterGUILayout.BeginHorizontalSplit(this.m_HorSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(0f, 0f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + this.m_FileViewWin.DoGUI(this, rect, hasFocus); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + this.WebLikeHistory(hasFocus); + GUILayout.EndVertical(); + SplitterGUILayout.EndHorizontalSplit(); + if (Event.current.type == EventType.Repaint) + { + Handles.color = Color.black; + Handles.DrawLine(new Vector3((float)(this.m_HorSplit.realSizes[0] - 1), rect.y, 0f), new Vector3((float)(this.m_HorSplit.realSizes[0] - 1), rect.yMax, 0f)); + Handles.DrawLine(new Vector3(0f, rect.yMax, 0f), new Vector3((float)Screen.width, rect.yMax, 0f)); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.enabled = (this.m_FileViewWin.SelType == ASHistoryFileView.SelectionType.DeletedItems && enabled); + if (GUILayout.Button(EditorGUIUtility.TextContent("Recover"), ASHistoryWindow.ms_Style.button, new GUILayoutOption[0])) + { + this.m_FileViewWin.DoRecover(); + } + GUILayout.FlexibleSpace(); + if (this.m_InRevisionSelectMode) + { + GUI.enabled = enabled; + GUILayout.Label(EditorGUIUtility.TextContent("Select revision to compare to"), ASHistoryWindow.ms_Style.boldLabel, new GUILayoutOption[0]); + } + GUILayout.Space(10f); + GUI.enabled = (this.IsComparableAssetSelected() && enabled); + if (GUILayout.Button(EditorGUIUtility.TextContent("Compare to Local Version"), ASHistoryWindow.ms_Style.button, new GUILayoutOption[0])) + { + this.DoShowDiff(false, this.ChangeLogSelectionRev, -1); + GUIUtility.ExitGUI(); + } + GUI.enabled = (this.ChangeLogSelectionRev > 0 && this.m_ChangeLogSelectionGUID != string.Empty && enabled); + if (GUILayout.Button(EditorGUIUtility.TextContent("Download Selected File"), ASHistoryWindow.ms_Style.button, new GUILayoutOption[0])) + { + this.DownloadFile(); + } + GUILayout.Space(10f); + GUI.enabled = (this.ChangeLogSelectionRev > 0 && enabled); + if (GUILayout.Button((this.ChangeLogSelectionRev <= 0) ? "Revert Entire Project" : ("Revert Entire Project to " + this.ChangeLogSelectionRev), ASHistoryWindow.ms_Style.button, new GUILayoutOption[0])) + { + this.DoRevertProject(); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + if (!this.m_SplittersOk && Event.current.type == EventType.Repaint) + { + this.m_SplittersOk = true; + HandleUtility.Repaint(); + } + EditorGUIUtility.SetIconSize(Vector2.zero); + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ASMainWindow.cs b/UnityEditor/UnityEditor/ASMainWindow.cs new file mode 100644 index 00000000..3105bddb --- /dev/null +++ b/UnityEditor/UnityEditor/ASMainWindow.cs @@ -0,0 +1,1496 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ASMainWindow : EditorWindow, IHasCustomMenu + { + internal class Constants + { + public GUIStyle background = "OL Box"; + public GUIStyle groupBox; + public GUIStyle groupBoxNoMargin; + public GUIStyle contentBox = "GroupBox"; + public GUIStyle entrySelected = "ServerUpdateChangesetOn"; + public GUIStyle entryNormal = "ServerUpdateChangeset"; + public GUIStyle element = "OL elem"; + public GUIStyle header = "OL header"; + public GUIStyle title = "OL Title"; + public GUIStyle columnHeader = "OL Title"; + public GUIStyle serverUpdateLog = "ServerUpdateLog"; + public GUIStyle serverUpdateInfo = "ServerUpdateInfo"; + public GUIStyle smallButton = "Button"; + public GUIStyle errorLabel = "ErrorLabel"; + public GUIStyle miniButton = "MiniButton"; + public GUIStyle button = "Button"; + public GUIStyle largeButton = "ButtonMid"; + public GUIStyle bigButton = "LargeButton"; + public GUIStyle entryEven = "CN EntryBackEven"; + public GUIStyle entryOdd = "CN EntryBackOdd"; + public GUIStyle dropDown = "MiniPullDown"; + public GUIStyle toggle = "Toggle"; + public Vector2 toggleSize; + public Constants() + { + this.groupBoxNoMargin = new GUIStyle(); + this.groupBox = new GUIStyle(); + this.groupBox.margin = new RectOffset(10, 10, 10, 10); + this.contentBox = new GUIStyle(this.contentBox); + this.contentBox.margin = new RectOffset(0, 0, 0, 0); + this.contentBox.overflow = new RectOffset(0, 1, 0, 1); + this.contentBox.padding = new RectOffset(8, 8, 7, 7); + this.title = new GUIStyle(this.title); + RectOffset arg_202_0 = this.title.padding; + int num = this.contentBox.padding.left + 2; + this.title.padding.right = num; + arg_202_0.left = num; + this.background = new GUIStyle(this.background); + this.background.padding.top = 1; + } + } + public enum ShowSearchField + { + None, + ProjectView, + HistoryList + } + internal enum Page + { + NotInitialized = -1, + Overview, + Update, + Commit, + History, + ServerConfig, + Admin + } + [Serializable] + public class SearchField + { + private string m_FilterText = string.Empty; + private bool m_Show; + public string FilterText + { + get + { + return this.m_FilterText; + } + } + public bool Show + { + get + { + return this.m_Show; + } + set + { + this.m_Show = value; + } + } + public bool DoGUI() + { + GUI.SetNextControlName("SearchFilter"); + string text = EditorGUILayout.ToolbarSearchField(this.m_FilterText, new GUILayoutOption[0]); + if (this.m_FilterText != text) + { + this.m_FilterText = text; + return true; + } + return false; + } + } + private const ASMainWindow.Page lastMainPage = ASMainWindow.Page.Commit; + private static ASMainWindow.Constants constants = null; + public static GUIContent badgeDelete = EditorGUIUtility.IconContent("AS Badge Delete"); + public static GUIContent badgeMove = EditorGUIUtility.IconContent("AS Badge Move"); + public static GUIContent badgeNew = EditorGUIUtility.IconContent("AS Badge New"); + public AssetsItem[] sharedCommits; + public AssetsItem[] sharedDeletedItems; + public Changeset[] sharedChangesets; + private GUIContent[] changesetContents; + public ASMainWindow.ShowSearchField m_ShowSearch; + public ASMainWindow.ShowSearchField m_SearchToShow = ASMainWindow.ShowSearchField.HistoryList; + public ASMainWindow.SearchField m_SearchField = new ASMainWindow.SearchField(); + private string[] pageTitles = new string[] + { + "Overview", + "Update", + "Commit", + string.Empty + }; + private string[] dropDownMenuItems = new string[] + { + "Connection", + string.Empty, + "Show History", + "Discard Changes", + string.Empty, + "Server Administration" + }; + private string[] unconfiguredDropDownMenuItems = new string[] + { + "Connection", + string.Empty, + "Server Administration" + }; + private string[] commitDropDownMenuItems = new string[] + { + "Commit", + string.Empty, + "Compare", + "Compare Binary", + string.Empty, + "Discard" + }; + private bool needsSetup = true; + private string connectionString = string.Empty; + private int maxNickLength = 1; + private bool showSmallWindow; + private int widthToHideButtons = 591; + private bool wasHidingButtons; + private ASMainWindow.Page selectedPage = ASMainWindow.Page.NotInitialized; + private ListViewState lv = new ListViewState(0); + private ParentViewState pv = new ParentViewState(); + internal ASHistoryWindow asHistoryWin; + internal ASUpdateWindow asUpdateWin; + internal ASCommitWindow asCommitWin; + internal ASServerAdminWindow asAdminWin; + internal ASConfigWindow asConfigWin; + private bool error; + private bool isInitialUpdate; + private Vector2 iconSize = new Vector2(16f, 16f); + private SplitterState splitter = new SplitterState(new float[] + { + 50f, + 50f + }, new int[] + { + 80, + 80 + }, null); + private bool committing; + private bool selectionChangedWhileCommitting; + private string commitMessage = string.Empty; + private bool pvHasSelection; + private bool somethingDiscardableSelected; + private bool mySelection; + private bool focusCommitMessage; + private int lastRevertSelectionChanged = -1; + private bool m_CheckedMaint; + public bool NeedsSetup + { + get + { + return this.needsSetup; + } + set + { + this.needsSetup = value; + } + } + public bool Error + { + get + { + return this.error; + } + } + public ASMainWindow() + { + base.position = new Rect(50f, 50f, 800f, 600f); + } + public void LogError(string errorStr) + { + Debug.LogError(errorStr); + AssetServer.SetAssetServerError(errorStr, false); + this.error = true; + } + private void Awake() + { + this.pv.lv = new ListViewState(0); + this.isInitialUpdate = true; + } + private void NotifyClosingCommit() + { + if (this.asCommitWin != null) + { + this.asCommitWin.OnClose(); + } + } + private void OnDestroy() + { + this.sharedCommits = null; + this.sharedDeletedItems = null; + this.sharedChangesets = null; + this.changesetContents = null; + if (this.selectedPage == ASMainWindow.Page.Commit) + { + this.NotifyClosingCommit(); + } + } + private void DoSelectionChange() + { + if (this.committing) + { + this.selectionChangedWhileCommitting = true; + return; + } + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + List list = new List(Selection.objects.Length); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + if (hierarchyProperty.Find(@object.GetInstanceID(), null)) + { + list.Add(hierarchyProperty.guid); + } + } + this.pvHasSelection = ASCommitWindow.MarkSelected(this.pv, list); + } + private void OnSelectionChange() + { + switch (this.selectedPage) + { + case ASMainWindow.Page.Overview: + if (!this.mySelection) + { + this.DoSelectionChange(); + base.Repaint(); + } + else + { + this.mySelection = false; + } + this.somethingDiscardableSelected = ASCommitWindow.SomethingDiscardableSelected(this.pv); + break; + case ASMainWindow.Page.Update: + this.asUpdateWin.OnSelectionChange(); + break; + case ASMainWindow.Page.Commit: + this.asCommitWin.OnSelectionChange(); + break; + case ASMainWindow.Page.History: + this.asHistoryWin.OnSelectionChange(); + break; + } + } + internal void Reinit() + { + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + base.Repaint(); + } + public void DoDiscardChanges(bool lastActionsResult) + { + List list = new List(); + bool flag = false; + if (flag) + { + list.AddRange(AssetServer.CollectDeepSelection()); + } + else + { + list.AddRange(AssetServer.GetAllRootGUIDs()); + list.AddRange(AssetServer.CollectAllChildren(AssetServer.GetRootGUID(), AssetServer.GetAllRootGUIDs())); + } + if (list.Count == 0) + { + list.AddRange(AssetServer.GetAllRootGUIDs()); + } + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBReinitOnSuccess"); + AssetServer.DoUpdateWithoutConflictResolutionOnNextTick(list.ToArray()); + } + private bool WordWrappedLabelButton(string label, string buttonText) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(label, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + bool result = GUILayout.Button(buttonText, new GUILayoutOption[] + { + GUILayout.Width(110f) + }); + GUILayout.EndHorizontal(); + return result; + } + private bool ToolbarToggle(bool pressed, string title, GUIStyle style) + { + bool changed = GUI.changed; + GUI.changed = false; + GUILayout.Toggle(pressed, title, style, new GUILayoutOption[0]); + if (GUI.changed) + { + return true; + } + GUI.changed |= changed; + return false; + } + private bool RightButton(string title) + { + return this.RightButton(title, ASMainWindow.constants.smallButton); + } + private bool RightButton(string title, GUIStyle style) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + bool result = GUILayout.Button(title, style, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + return result; + } + public void ShowConflictResolutions(string[] conflicting) + { + if (this.asUpdateWin == null) + { + this.LogError("Found unexpected conflicts. Please use Bug Reporter to report a bug."); + return; + } + this.asUpdateWin.ShowConflictResolutions(conflicting); + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + if (!this.needsSetup) + { + menu.AddItem(new GUIContent("Refresh"), false, new GenericMenu.MenuFunction(this.ActionRefresh)); + menu.AddSeparator(string.Empty); + } + menu.AddItem(new GUIContent("Connection"), false, new GenericMenu.MenuFunction2(this.ActionSwitchPage), ASMainWindow.Page.ServerConfig); + menu.AddSeparator(string.Empty); + if (!this.needsSetup) + { + menu.AddItem(new GUIContent("Show History"), false, new GenericMenu.MenuFunction2(this.ActionSwitchPage), ASMainWindow.Page.History); + menu.AddItem(new GUIContent("Discard Changes"), false, new GenericMenu.MenuFunction(this.ActionDiscardChanges)); + menu.AddSeparator(string.Empty); + } + menu.AddItem(new GUIContent("Server Administration"), false, new GenericMenu.MenuFunction2(this.ActionSwitchPage), ASMainWindow.Page.Admin); + } + public bool UpdateNeedsRefresh() + { + return this.sharedChangesets == null || AssetServer.GetRefreshUpdate(); + } + public bool CommitNeedsRefresh() + { + return this.sharedCommits == null || this.sharedDeletedItems == null || AssetServer.GetRefreshCommit(); + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string text = this.dropDownMenuItems[selected]; + switch (text) + { + case "Connection": + this.ActionSwitchPage(ASMainWindow.Page.ServerConfig); + break; + case "Show History": + this.ActionSwitchPage(ASMainWindow.Page.History); + break; + case "Discard Changes": + this.ActionDiscardChanges(); + break; + case "Server Administration": + this.ActionSwitchPage(ASMainWindow.Page.Admin); + break; + } + } + } + private void CommitContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string text = this.commitDropDownMenuItems[selected]; + switch (text) + { + case "Commit": + this.StartCommitting(); + break; + case "Compare": + ASCommitWindow.DoShowDiff(ASCommitWindow.GetParentViewSelectedItems(this.pv, false, false), false); + break; + case "Compare Binary": + ASCommitWindow.DoShowDiff(ASCommitWindow.GetParentViewSelectedItems(this.pv, false, false), true); + break; + case "Discard": + this.DoMyRevert(false); + break; + } + } + } + public void CommitItemsChanged() + { + this.InitCommits(); + this.DisplayedItemsChanged(); + if (this.selectedPage == ASMainWindow.Page.Commit) + { + this.asCommitWin.Update(); + } + base.Repaint(); + } + public void RevertProject(int toRevision, Changeset[] changesets) + { + AssetServer.SetStickyChangeset(toRevision); + this.asUpdateWin = new ASUpdateWindow(this, changesets); + this.asUpdateWin.SetSelectedRevisionLine(0); + this.asUpdateWin.DoUpdate(false); + this.selectedPage = ASMainWindow.Page.Update; + } + public void ShowHistory() + { + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + this.isInitialUpdate = false; + this.SwitchSelectedPage(ASMainWindow.Page.History); + } + private void ActionRefresh() + { + switch (this.selectedPage) + { + case ASMainWindow.Page.Overview: + AssetServer.CheckForServerUpdates(); + this.InitiateRefreshAssetsAndUpdateStatusWithCallback("CBInitOverviewPage"); + break; + case ASMainWindow.Page.Update: + AssetServer.CheckForServerUpdates(); + if (this.UpdateNeedsRefresh()) + { + this.InitiateUpdateStatusWithCallback("CBInitUpdatePage"); + } + break; + case ASMainWindow.Page.Commit: + this.asCommitWin.InitiateReinit(); + break; + case ASMainWindow.Page.History: + AssetServer.CheckForServerUpdates(); + if (this.UpdateNeedsRefresh()) + { + this.InitiateUpdateStatusWithCallback("CBInitHistoryPage"); + } + break; + default: + this.Reinit(); + break; + } + } + private void ActionSwitchPage(object page) + { + this.SwitchSelectedPage((ASMainWindow.Page)((int)page)); + } + private void ActionDiscardChanges() + { + if (EditorUtility.DisplayDialog("Discard all changes", "Are you sure you want to discard all local changes made in the project?", "Discard", "Cancel")) + { + AssetServer.RemoveMaintErrorsFromConsole(); + if (!ASEditorBackend.SettingsIfNeeded()) + { + Debug.Log("Asset Server connection for current project is not set up"); + this.error = true; + return; + } + this.error = false; + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBDoDiscardChanges"); + AssetServer.DoUpdateStatusOnNextTick(); + } + } + private void SwitchSelectedPage(ASMainWindow.Page page) + { + ASMainWindow.Page page2 = this.selectedPage; + this.selectedPage = page; + this.SelectedPageChanged(); + if (this.error) + { + this.selectedPage = page2; + this.error = false; + } + } + private void InitiateUpdateStatusWithCallback(string callbackName) + { + if (!ASEditorBackend.SettingsIfNeeded()) + { + Debug.Log("Asset Server connection for current project is not set up"); + this.error = true; + return; + } + this.error = false; + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", callbackName); + AssetServer.DoUpdateStatusOnNextTick(); + } + private void InitiateRefreshAssetsWithCallback(string callbackName) + { + if (!ASEditorBackend.SettingsIfNeeded()) + { + Debug.Log("Asset Server connection for current project is not set up"); + this.error = true; + return; + } + this.error = false; + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", callbackName); + AssetServer.DoRefreshAssetsOnNextTick(); + } + private void InitiateRefreshAssetsAndUpdateStatusWithCallback(string callbackName) + { + if (!ASEditorBackend.SettingsIfNeeded()) + { + Debug.Log("Asset Server connection for current project is not set up"); + this.error = true; + return; + } + this.error = false; + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", callbackName); + AssetServer.DoRefreshAssetsAndUpdateStatusOnNextTick(); + } + private void SelectedPageChanged() + { + AssetServer.ClearAssetServerError(); + if (this.committing) + { + this.CancelCommit(); + } + switch (this.selectedPage) + { + case ASMainWindow.Page.Overview: + if (ASEditorBackend.SettingsAreValid()) + { + AssetServer.CheckForServerUpdates(); + if (this.UpdateNeedsRefresh()) + { + this.InitiateUpdateStatusWithCallback("CBInitOverviewPage"); + } + else + { + this.InitOverviewPage(true); + } + } + else + { + this.connectionString = "Asset Server connection for current project is not set up"; + this.sharedChangesets = new Changeset[0]; + this.changesetContents = new GUIContent[0]; + this.needsSetup = true; + } + break; + case ASMainWindow.Page.Update: + this.InitUpdatePage(true); + break; + case ASMainWindow.Page.Commit: + this.asCommitWin = new ASCommitWindow(this, (!this.pvHasSelection) ? null : ASCommitWindow.GetParentViewSelectedItems(this.pv, true, false).ToArray()); + this.asCommitWin.InitiateReinit(); + break; + case ASMainWindow.Page.History: + this.pageTitles[3] = "History"; + this.InitHistoryPage(true); + break; + case ASMainWindow.Page.ServerConfig: + this.pageTitles[3] = "Connection"; + this.asConfigWin = new ASConfigWindow(this); + break; + case ASMainWindow.Page.Admin: + this.pageTitles[3] = "Administration"; + this.asAdminWin = new ASServerAdminWindow(this); + if (this.error) + { + return; + } + break; + } + } + public void InitUpdatePage(bool lastActionsResult) + { + if (!lastActionsResult) + { + this.Reinit(); + return; + } + if (this.UpdateNeedsRefresh()) + { + this.GetUpdates(); + } + if (this.sharedChangesets == null) + { + this.Reinit(); + return; + } + this.asUpdateWin = new ASUpdateWindow(this, this.sharedChangesets); + this.asUpdateWin.SetSelectedRevisionLine(0); + } + private void InitCommits() + { + if (this.CommitNeedsRefresh()) + { + if (AssetServer.GetAssetServerError() == string.Empty) + { + this.sharedCommits = ASCommitWindow.GetCommits(); + this.sharedDeletedItems = AssetServer.GetLocalDeletedItems(); + } + else + { + this.sharedCommits = new AssetsItem[0]; + this.sharedDeletedItems = new AssetsItem[0]; + } + } + this.pv.Clear(); + this.pv.AddAssetItems(this.sharedCommits); + this.pv.AddAssetItems(this.sharedDeletedItems); + this.pv.SetLineCount(); + this.pv.selectedItems = new bool[this.pv.lv.totalRows]; + this.pv.initialSelectedItem = -1; + AssetServer.ClearRefreshCommit(); + } + private void GetUpdates() + { + AssetServer.ClearAssetServerError(); + this.sharedChangesets = AssetServer.GetNewItems(); + Array.Reverse(this.sharedChangesets); + this.changesetContents = null; + this.maxNickLength = 1; + AssetServer.ClearRefreshUpdate(); + if (AssetServer.GetAssetServerError() != string.Empty) + { + this.sharedChangesets = null; + } + } + public void DisplayedItemsChanged() + { + float[] array = new float[2]; + bool flag = this.sharedChangesets != null && this.sharedChangesets.Length != 0; + bool flag2 = this.pv.lv.totalRows != 0; + if ((flag && flag2) || (!flag && !flag2)) + { + array[0] = (array[1] = 0.5f); + } + else + { + array[0] = (float)((!flag) ? 0 : 1); + array[1] = (float)((!flag2) ? 0 : 1); + } + this.splitter = new SplitterState(array, new int[] + { + 80, + 80 + }, null); + this.DoSelectionChange(); + } + public void InitOverviewPage(bool lastActionsResult) + { + if (!lastActionsResult) + { + this.needsSetup = true; + this.sharedChangesets = null; + this.sharedCommits = null; + this.sharedDeletedItems = null; + return; + } + PListConfig pListConfig = new PListConfig("Library/ServerPreferences.plist"); + this.connectionString = string.Concat(new string[] + { + pListConfig["Maint UserName"], + " @ ", + pListConfig["Maint Server"], + " : ", + pListConfig["Maint project name"] + }); + if (this.UpdateNeedsRefresh()) + { + this.GetUpdates(); + } + this.needsSetup = (this.sharedChangesets == null || AssetServer.HasConnectionError()); + this.InitCommits(); + this.DisplayedItemsChanged(); + } + public void InitHistoryPage(bool lastActionsResult) + { + if (!lastActionsResult) + { + this.Reinit(); + return; + } + this.asHistoryWin = new ASHistoryWindow(this); + if (this.asHistoryWin == null) + { + this.Reinit(); + return; + } + } + private void OverviewPageGUI() + { + bool enabled = GUI.enabled; + this.showSmallWindow = (base.position.width <= (float)this.widthToHideButtons); + if (Event.current.type == EventType.Layout) + { + this.wasHidingButtons = this.showSmallWindow; + } + else + { + if (this.showSmallWindow != this.wasHidingButtons) + { + GUIUtility.ExitGUI(); + } + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (!this.showSmallWindow) + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + this.ShortServerInfo(); + if (this.needsSetup) + { + GUI.enabled = false; + } + this.OtherServerCommands(); + GUI.enabled = enabled; + this.ServerAdministration(); + GUI.enabled = (!this.needsSetup && enabled); + GUILayout.EndVertical(); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Width((base.position.width - 30f) / 2f) + }); + } + else + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + } + GUI.enabled = (!this.needsSetup && enabled); + SplitterGUILayout.BeginVerticalSplit(this.splitter, new GUILayoutOption[0]); + this.ShortUpdateList(); + this.ShortCommitList(); + SplitterGUILayout.EndVerticalSplit(); + GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); + GUI.enabled = enabled; + } + private void OtherServerCommands() + { + GUILayout.BeginVertical(ASMainWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Label("Asset Server Actions", ASMainWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[0]); + if (this.WordWrappedLabelButton("Browse the complete history of the project", "Show History")) + { + this.SwitchSelectedPage(ASMainWindow.Page.History); + GUIUtility.ExitGUI(); + } + GUILayout.Space(5f); + if (this.WordWrappedLabelButton("Discard all local changes you made to the project", "Discard Changes")) + { + this.ActionDiscardChanges(); + } + GUILayout.EndVertical(); + GUILayout.EndVertical(); + } + private void ShortServerInfo() + { + GUILayout.BeginVertical(ASMainWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Label("Current Project", ASMainWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[0]); + if (this.WordWrappedLabelButton(this.connectionString, "Connection")) + { + this.SwitchSelectedPage(ASMainWindow.Page.ServerConfig); + } + if (AssetServer.GetAssetServerError() != string.Empty) + { + GUILayout.Space(10f); + GUILayout.Label(AssetServer.GetAssetServerError(), ASMainWindow.constants.errorLabel, new GUILayoutOption[0]); + } + GUILayout.EndVertical(); + GUILayout.EndVertical(); + } + private void ServerAdministration() + { + GUILayout.BeginVertical(ASMainWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Label("Asset Server Administration", ASMainWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[0]); + if (this.WordWrappedLabelButton("Create and administer Asset Server projects", "Administration")) + { + this.SwitchSelectedPage(ASMainWindow.Page.Admin); + GUIUtility.ExitGUI(); + } + GUILayout.EndVertical(); + GUILayout.EndVertical(); + } + private bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) + { + return (flagToCheck & flags) != ChangeFlags.None; + } + private void MySelectionToGlobalSelection() + { + this.mySelection = true; + List parentViewSelectedItems = ASCommitWindow.GetParentViewSelectedItems(this.pv, true, false); + parentViewSelectedItems.Remove(AssetServer.GetRootGUID()); + if (parentViewSelectedItems.Count > 0) + { + AssetServer.SetSelectionFromGUID(parentViewSelectedItems[0]); + } + this.pvHasSelection = this.pv.HasTrue(); + this.somethingDiscardableSelected = ASCommitWindow.SomethingDiscardableSelected(this.pv); + } + private void DoCommitParentView() + { + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + int row = this.pv.lv.row; + int num = -1; + int num2 = -1; + bool flag = false; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.pv.lv, ASMainWindow.constants.background, new GUILayoutOption[0])) + { + if (GUIUtility.keyboardControl == this.pv.lv.ID && Event.current.type == EventType.KeyDown && actionKey) + { + Event.current.Use(); + } + if (num == -1 && !this.pv.IndexToFolderAndFile(listViewElement.row, ref num, ref num2)) + { + break; + } + ParentViewFolder parentViewFolder = this.pv.folders[num]; + if (this.pv.selectedItems[listViewElement.row] && Event.current.type == EventType.Repaint) + { + ASMainWindow.constants.entrySelected.Draw(listViewElement.position, false, false, false, false); + } + if (!this.committing) + { + if (ListViewGUILayout.HasMouseUp(listViewElement.position)) + { + if (!shift && !actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, this.pv.lv.row, ref this.pv.initialSelectedItem, ref this.pv.selectedItems); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position)) + { + if (Event.current.clickCount == 2) + { + ASCommitWindow.DoShowDiff(ASCommitWindow.GetParentViewSelectedItems(this.pv, false, false), false); + GUIUtility.ExitGUI(); + } + else + { + if (!this.pv.selectedItems[listViewElement.row] || shift || actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.pv.initialSelectedItem, ref this.pv.selectedItems); + } + this.pv.selectedFile = num2; + this.pv.selectedFolder = num; + this.pv.lv.row = listViewElement.row; + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position, 1)) + { + if (!this.pv.selectedItems[listViewElement.row]) + { + flag = true; + this.pv.ClearSelection(); + this.pv.selectedItems[listViewElement.row] = true; + this.pv.selectedFile = num2; + this.pv.selectedFolder = num; + this.pv.lv.row = listViewElement.row; + } + GUIUtility.hotControl = 0; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, this.commitDropDownMenuItems, null, new EditorUtility.SelectMenuItemFunction(this.CommitContextMenuClick), null); + Event.current.Use(); + } + } + } + } + ChangeFlags changeFlags; + if (num2 != -1) + { + Texture2D texture2D = AssetDatabase.GetCachedIcon(parentViewFolder.name + "/" + parentViewFolder.files[num2].name) as Texture2D; + if (texture2D == null) + { + texture2D = InternalEditorUtility.GetIconForFile(parentViewFolder.files[num2].name); + } + GUILayout.Label(new GUIContent(parentViewFolder.files[num2].name, texture2D), ASMainWindow.constants.element, new GUILayoutOption[0]); + changeFlags = parentViewFolder.files[num2].changeFlags; + } + else + { + GUILayout.Label(parentViewFolder.name, ASMainWindow.constants.header, new GUILayoutOption[0]); + changeFlags = parentViewFolder.changeFlags; + } + GUIContent gUIContent = null; + if (this.HasFlag(changeFlags, ChangeFlags.Undeleted) || this.HasFlag(changeFlags, ChangeFlags.Created)) + { + gUIContent = ASMainWindow.badgeNew; + } + else + { + if (this.HasFlag(changeFlags, ChangeFlags.Deleted)) + { + gUIContent = ASMainWindow.badgeDelete; + } + else + { + if (this.HasFlag(changeFlags, ChangeFlags.Renamed) || this.HasFlag(changeFlags, ChangeFlags.Moved)) + { + gUIContent = ASMainWindow.badgeMove; + } + } + } + if (gUIContent != null && Event.current.type == EventType.Repaint) + { + Rect position2 = new Rect(listViewElement.position.x + listViewElement.position.width - (float)gUIContent.image.width - 5f, listViewElement.position.y + listViewElement.position.height / 2f - (float)(gUIContent.image.height / 2), (float)gUIContent.image.width, (float)gUIContent.image.height); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUIStyle.none.Draw(position2, gUIContent, false, false, false, false); + EditorGUIUtility.SetIconSize(this.iconSize); + } + this.pv.NextFileFolder(ref num, ref num2); + } + if (!this.committing) + { + if (GUIUtility.keyboardControl == this.pv.lv.ID) + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + for (int i = 0; i < this.pv.selectedItems.Length; i++) + { + this.pv.selectedItems[i] = true; + } + flag = true; + Event.current.Use(); + } + } + } + if (GUIUtility.keyboardControl == this.pv.lv.ID && !actionKey && this.pv.lv.selectionChanged) + { + flag |= ListViewGUILayout.MultiSelection(row, this.pv.lv.row, ref this.pv.initialSelectedItem, ref this.pv.selectedItems); + this.pv.IndexToFolderAndFile(this.pv.lv.row, ref this.pv.selectedFolder, ref this.pv.selectedFile); + } + if (this.pv.lv.selectionChanged || flag) + { + this.MySelectionToGlobalSelection(); + } + } + } + private void DoCommit() + { + if (this.commitMessage == string.Empty && !EditorUtility.DisplayDialog("Commit without description", "Are you sure you want to commit with empty commit description message?", "Commit", "Cancel")) + { + GUIUtility.ExitGUI(); + } + bool refreshCommit = AssetServer.GetRefreshCommit(); + ASCommitWindow aSCommitWindow = new ASCommitWindow(this, ASCommitWindow.GetParentViewSelectedItems(this.pv, true, false).ToArray()); + aSCommitWindow.InitiateReinit(); + if ((refreshCommit || aSCommitWindow.lastTransferMovedDependencies) && ((!refreshCommit && !EditorUtility.DisplayDialog("Committing with dependencies", "Assets selected for committing have dependencies that will also be committed. Press Details to view full changeset", "Commit", "Details")) || refreshCommit)) + { + this.committing = false; + this.selectedPage = ASMainWindow.Page.Commit; + aSCommitWindow.description = this.commitMessage; + if (refreshCommit) + { + aSCommitWindow.showReinitedWarning = 1; + } + this.asCommitWin = aSCommitWindow; + base.Repaint(); + GUIUtility.ExitGUI(); + return; + } + string[] itemsToCommit = aSCommitWindow.GetItemsToCommit(); + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBOverviewsCommitFinished"); + AssetServer.DoCommitOnNextTick(this.commitMessage, itemsToCommit); + AssetServer.SetLastCommitMessage(this.commitMessage); + aSCommitWindow.AddToCommitMessageHistory(this.commitMessage); + this.committing = false; + GUIUtility.ExitGUI(); + } + private void StartCommitting() + { + this.committing = true; + this.commitMessage = string.Empty; + this.selectionChangedWhileCommitting = false; + this.focusCommitMessage = true; + } + internal void CommitFinished(bool actionResult) + { + if (actionResult) + { + AssetServer.ClearCommitPersistentData(); + this.InitOverviewPage(true); + } + else + { + base.Repaint(); + } + } + private void CancelCommit() + { + this.committing = false; + if (this.selectionChangedWhileCommitting) + { + this.DoSelectionChange(); + } + } + private void DoMyRevert(bool afterMarkingDependencies) + { + if (!afterMarkingDependencies) + { + List parentViewSelectedItems = ASCommitWindow.GetParentViewSelectedItems(this.pv, true, false); + if (ASCommitWindow.MarkAllFolderDependenciesForDiscarding(this.pv, null)) + { + this.lastRevertSelectionChanged = 2; + this.MySelectionToGlobalSelection(); + } + else + { + this.lastRevertSelectionChanged = -1; + } + List parentViewSelectedItems2 = ASCommitWindow.GetParentViewSelectedItems(this.pv, true, false); + if (parentViewSelectedItems.Count != parentViewSelectedItems2.Count) + { + this.lastRevertSelectionChanged = 2; + } + } + if (afterMarkingDependencies || this.lastRevertSelectionChanged == -1) + { + ASCommitWindow.DoRevert(ASCommitWindow.GetParentViewSelectedItems(this.pv, true, true), "CBInitOverviewPage"); + } + } + private void ShortCommitList() + { + bool enabled = GUI.enabled; + GUILayout.BeginVertical((!this.showSmallWindow) ? ASMainWindow.constants.groupBox : ASMainWindow.constants.groupBoxNoMargin, new GUILayoutOption[0]); + GUILayout.Label("Local Changes", ASMainWindow.constants.title, new GUILayoutOption[0]); + if (this.pv.lv.totalRows == 0) + { + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + GUILayout.Label("Nothing to commit", new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + else + { + this.DoCommitParentView(); + GUILayout.BeginHorizontal(ASMainWindow.constants.contentBox, new GUILayoutOption[0]); + Event current = Event.current; + if (!this.committing) + { + GUI.enabled = (this.pvHasSelection && enabled); + if (GUILayout.Button("Compare", ASMainWindow.constants.smallButton, new GUILayoutOption[0])) + { + ASCommitWindow.DoShowDiff(ASCommitWindow.GetParentViewSelectedItems(this.pv, false, false), false); + GUIUtility.ExitGUI(); + } + bool enabled2 = GUI.enabled; + if (!this.somethingDiscardableSelected) + { + GUI.enabled = false; + } + if (GUILayout.Button("Discard", ASMainWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.DoMyRevert(false); + GUIUtility.ExitGUI(); + } + GUI.enabled = enabled2; + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Commit...", ASMainWindow.constants.smallButton, new GUILayoutOption[0]) || (this.pvHasSelection && current.type == EventType.KeyDown && current.keyCode == KeyCode.Return)) + { + this.StartCommitting(); + current.Use(); + } + if (current.type == EventType.KeyDown && (current.character == '\n' || current.character == '\u0003')) + { + current.Use(); + } + GUI.enabled = enabled; + if (GUILayout.Button("Details", ASMainWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.SwitchSelectedPage(ASMainWindow.Page.Commit); + base.Repaint(); + GUIUtility.ExitGUI(); + } + } + else + { + if (current.type == EventType.KeyDown) + { + KeyCode keyCode = current.keyCode; + if (keyCode != KeyCode.Return) + { + if (keyCode != KeyCode.Escape) + { + if (current.character == '\n' || current.character == '\u0003') + { + current.Use(); + } + } + else + { + this.CancelCommit(); + current.Use(); + } + } + else + { + this.DoCommit(); + current.Use(); + } + } + GUI.SetNextControlName("commitMessage"); + this.commitMessage = EditorGUILayout.TextField(this.commitMessage, new GUILayoutOption[0]); + if (GUILayout.Button("Commit", ASMainWindow.constants.smallButton, new GUILayoutOption[] + { + GUILayout.Width(60f) + })) + { + this.DoCommit(); + } + if (GUILayout.Button("Cancel", ASMainWindow.constants.smallButton, new GUILayoutOption[] + { + GUILayout.Width(60f) + })) + { + this.CancelCommit(); + } + if (this.focusCommitMessage) + { + EditorGUI.FocusTextInControl("commitMessage"); + this.focusCommitMessage = false; + base.Repaint(); + } + } + GUILayout.EndHorizontal(); + } + GUILayout.EndVertical(); + if (this.lastRevertSelectionChanged == 0) + { + this.lastRevertSelectionChanged = -1; + if (ASCommitWindow.ShowDiscardWarning()) + { + this.DoMyRevert(true); + } + } + if (this.lastRevertSelectionChanged > 0) + { + this.lastRevertSelectionChanged--; + base.Repaint(); + } + } + private void ShortUpdateList() + { + GUILayout.BeginVertical((!this.showSmallWindow) ? ASMainWindow.constants.groupBox : ASMainWindow.constants.groupBoxNoMargin, new GUILayoutOption[0]); + GUILayout.Label("Updates on Server", ASMainWindow.constants.title, new GUILayoutOption[0]); + if (this.sharedChangesets == null) + { + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + GUILayout.Label("Could not retrieve changes", new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + else + { + if (this.sharedChangesets.Length == 0) + { + GUILayout.BeginVertical(ASMainWindow.constants.contentBox, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + GUILayout.Label("You are up to date", new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + else + { + this.lv.totalRows = this.sharedChangesets.Length; + int num = (int)ASMainWindow.constants.entryNormal.CalcHeight(new GUIContent("X"), 100f); + ASMainWindow.constants.serverUpdateLog.alignment = TextAnchor.MiddleLeft; + ASMainWindow.constants.serverUpdateInfo.alignment = TextAnchor.MiddleLeft; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv, ASMainWindow.constants.background, new GUILayoutOption[0])) + { + Rect rect = GUILayoutUtility.GetRect(GUIClip.visibleRect.width, (float)num, new GUILayoutOption[] + { + GUILayout.MinHeight((float)num) + }); + Rect position = rect; + position.x += 1f; + position.y += 1f; + if (listViewElement.row % 2 == 0) + { + if (Event.current.type == EventType.Repaint) + { + ASMainWindow.constants.entryEven.Draw(position, false, false, false, false); + } + position.y += rect.height; + if (Event.current.type == EventType.Repaint) + { + ASMainWindow.constants.entryOdd.Draw(position, false, false, false, false); + } + } + position = rect; + position.width -= (float)(this.maxNickLength + 25); + position.x += 10f; + GUI.Button(position, this.changesetContents[listViewElement.row], ASMainWindow.constants.serverUpdateLog); + position = rect; + position.x += position.width - (float)this.maxNickLength - 5f; + GUI.Label(position, this.sharedChangesets[listViewElement.row].owner, ASMainWindow.constants.serverUpdateInfo); + } + ASMainWindow.constants.serverUpdateLog.alignment = TextAnchor.UpperLeft; + ASMainWindow.constants.serverUpdateInfo.alignment = TextAnchor.UpperLeft; + GUILayout.BeginHorizontal(ASMainWindow.constants.contentBox, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Update", ASMainWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.selectedPage = ASMainWindow.Page.Update; + this.InitUpdatePage(true); + this.asUpdateWin.DoUpdate(false); + } + if (GUILayout.Button("Details", ASMainWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.SwitchSelectedPage(ASMainWindow.Page.Update); + base.Repaint(); + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + } + } + GUILayout.EndVertical(); + } + private void DoSelectedPageGUI() + { + switch (this.selectedPage) + { + case ASMainWindow.Page.Overview: + this.OverviewPageGUI(); + break; + case ASMainWindow.Page.Update: + if (this.asUpdateWin != null && this.asUpdateWin != null) + { + this.asUpdateWin.DoGUI(); + } + break; + case ASMainWindow.Page.Commit: + if (this.asCommitWin != null && this.asCommitWin != null) + { + this.asCommitWin.DoGUI(); + } + break; + case ASMainWindow.Page.History: + if (this.asHistoryWin != null && !this.asHistoryWin.DoGUI(this.m_Parent.hasFocus)) + { + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + GUIUtility.ExitGUI(); + } + break; + case ASMainWindow.Page.ServerConfig: + if (this.asConfigWin != null && !this.asConfigWin.DoGUI()) + { + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + GUIUtility.ExitGUI(); + } + break; + case ASMainWindow.Page.Admin: + if (this.asAdminWin != null && !this.asAdminWin.DoGUI()) + { + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + GUIUtility.ExitGUI(); + } + break; + } + } + private void SetShownSearchField(ASMainWindow.ShowSearchField newShow) + { + EditorGUI.FocusTextInControl("SearchFilter"); + this.m_SearchField.Show = false; + this.m_ShowSearch = newShow; + this.m_SearchField.Show = true; + this.asHistoryWin.FilterItems(false); + } + private void DoSearchToggle(ASMainWindow.ShowSearchField field) + { + if (this.selectedPage == ASMainWindow.Page.History) + { + if (this.m_SearchField.DoGUI()) + { + this.asHistoryWin.FilterItems(false); + } + GUILayout.Space(10f); + } + } + private bool IsLastOne(int f, int fl, ParentViewState st) + { + return st.folders.Length - 1 == f && st.folders[f].files.Length - 1 == fl; + } + private void OnGUI() + { + if (EditorSettings.externalVersionControl != ExternalVersionControl.Disabled && EditorSettings.externalVersionControl != ExternalVersionControl.AssetServer) + { + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label("Asset Server is disabled when external version control is used. Go to 'Edit -> Project Settings -> Editor' to re-enable it.", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + return; + } + if (ASMainWindow.constants == null) + { + ASMainWindow.constants = new ASMainWindow.Constants(); + } + if (!this.m_CheckedMaint && Event.current.type != EventType.Layout) + { + if (!InternalEditorUtility.HasMaint()) + { + base.Close(); + GUIUtility.ExitGUI(); + } + this.m_CheckedMaint = true; + } + if (this.maxNickLength == 1 && this.sharedChangesets != null) + { + for (int i = 0; i < this.sharedChangesets.Length; i++) + { + int num = (int)ASMainWindow.constants.serverUpdateInfo.CalcSize(new GUIContent(this.sharedChangesets[i].owner)).x; + if (num > this.maxNickLength) + { + this.maxNickLength = num; + } + } + this.changesetContents = new GUIContent[this.sharedChangesets.Length]; + ParentViewState parentViewState = new ParentViewState(); + for (int j = 0; j < this.changesetContents.Length; j++) + { + int num2 = 15; + Changeset changeset = this.sharedChangesets[j]; + string text = changeset.message.Split(new char[] + { + '\n' + })[0]; + text = ((text.Length >= 45) ? (text.Substring(0, 42) + "...") : text); + string text2 = string.Format("[{0} {1}] {2}", changeset.date, changeset.owner, text); + num2--; + parentViewState.Clear(); + parentViewState.AddAssetItems(changeset); + for (int k = 0; k < parentViewState.folders.Length; k++) + { + if (--num2 == 0 && !this.IsLastOne(k, 0, parentViewState)) + { + text2 += "\n(and more...)"; + break; + } + text2 = text2 + "\n" + parentViewState.folders[k].name; + for (int l = 0; l < parentViewState.folders[k].files.Length; l++) + { + if (--num2 == 0 && !this.IsLastOne(k, l, parentViewState)) + { + text2 += "\n(and more...)"; + break; + } + text2 = text2 + "\n\t" + parentViewState.folders[k].files[l].name; + } + if (num2 == 0) + { + break; + } + } + this.changesetContents[j] = new GUIContent(this.sharedChangesets[j].message.Split(new char[] + { + '\n' + })[0], text2); + } + if (this.maxNickLength == 1) + { + this.maxNickLength = 0; + } + } + if (AssetServer.IsControllerBusy() != 0) + { + base.Repaint(); + return; + } + if (this.isInitialUpdate) + { + this.isInitialUpdate = false; + this.SwitchSelectedPage(ASMainWindow.Page.Overview); + } + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "Find") + { + this.SetShownSearchField(this.m_SearchToShow); + Event.current.Use(); + } + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + int num3 = -1; + bool enabled = GUI.enabled; + if (this.ToolbarToggle(this.selectedPage == ASMainWindow.Page.Overview, this.pageTitles[0], EditorStyles.toolbarButton)) + { + num3 = 0; + } + GUI.enabled = (!this.needsSetup && this.sharedChangesets != null && this.sharedChangesets.Length != 0 && enabled); + if (this.ToolbarToggle(this.selectedPage == ASMainWindow.Page.Update, this.pageTitles[1], EditorStyles.toolbarButton)) + { + num3 = 1; + } + GUI.enabled = (!this.needsSetup && this.pv.lv.totalRows != 0 && enabled); + if (this.selectedPage > ASMainWindow.Page.Commit) + { + if (this.ToolbarToggle(this.selectedPage == ASMainWindow.Page.Commit, this.pageTitles[2], EditorStyles.toolbarButton)) + { + num3 = 2; + } + GUI.enabled = enabled; + if (this.ToolbarToggle(this.selectedPage > ASMainWindow.Page.Commit, this.pageTitles[3], EditorStyles.toolbarButton)) + { + num3 = 3; + } + } + else + { + if (this.ToolbarToggle(this.selectedPage == ASMainWindow.Page.Commit, this.pageTitles[2], EditorStyles.toolbarButton)) + { + num3 = 2; + } + GUI.enabled = enabled; + } + if (num3 != -1 && num3 != (int)this.selectedPage) + { + if (this.selectedPage == ASMainWindow.Page.Commit) + { + this.NotifyClosingCommit(); + } + if (num3 <= 2) + { + this.SwitchSelectedPage((ASMainWindow.Page)num3); + GUIUtility.ExitGUI(); + } + } + GUILayout.FlexibleSpace(); + if (this.selectedPage == ASMainWindow.Page.History) + { + this.DoSearchToggle(ASMainWindow.ShowSearchField.HistoryList); + } + if (!this.needsSetup) + { + switch (this.selectedPage) + { + case ASMainWindow.Page.Overview: + case ASMainWindow.Page.Update: + case ASMainWindow.Page.History: + if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.ActionRefresh(); + GUIUtility.ExitGUI(); + } + break; + } + } + GUILayout.EndHorizontal(); + EditorGUIUtility.SetIconSize(this.iconSize); + this.DoSelectedPageGUI(); + EditorGUIUtility.SetIconSize(Vector2.zero); + if (Event.current.type == EventType.ContextClick) + { + GUIUtility.hotControl = 0; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, (!this.needsSetup) ? this.dropDownMenuItems : this.unconfiguredDropDownMenuItems, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + Event.current.Use(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ASRefreshState.cs b/UnityEditor/UnityEditor/ASRefreshState.cs new file mode 100644 index 00000000..16ed2f08 --- /dev/null +++ b/UnityEditor/UnityEditor/ASRefreshState.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum ASRefreshState + { + RefreshUpdate = 1, + RefreshCommit + } +} diff --git a/UnityEditor/UnityEditor/ASServerAdminWindow.cs b/UnityEditor/UnityEditor/ASServerAdminWindow.cs new file mode 100644 index 00000000..a98fab8d --- /dev/null +++ b/UnityEditor/UnityEditor/ASServerAdminWindow.cs @@ -0,0 +1,493 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASServerAdminWindow + { + private enum Action + { + Main, + CreateUser, + SetPassword, + CreateProject, + ModifyUser + } + private const int listLenghts = 20; + private static ASMainWindow.Constants constants; + private ListViewState lv; + private ListViewState lv2; + private SplitterState lvSplit = new SplitterState(new float[] + { + 5f, + 50f, + 50f, + 150f + }, new int[] + { + 20, + 70, + 70, + 100 + }, null); + private MaintDatabaseRecord[] databases; + private MaintUserRecord[] users; + private ASMainWindow parentWin; + private bool splittersOk; + private bool resetKeyboardControl; + private ASServerAdminWindow.Action currAction; + private string[] servers; + private string server = string.Empty; + private string user = string.Empty; + private string password = string.Empty; + private string nPassword1 = string.Empty; + private string nPassword2 = string.Empty; + private string nProjectName = string.Empty; + private string nTemplateProjectName = string.Empty; + private string nFullName = string.Empty; + private string nUserName = string.Empty; + private string nEmail = string.Empty; + private bool projectSelected; + private bool userSelected; + private bool isConnected; + public ASServerAdminWindow(ASMainWindow parentWin) + { + this.lv = new ListViewState(0); + this.lv2 = new ListViewState(0); + this.parentWin = parentWin; + this.servers = InternalEditorUtility.GetEditorSettingsList("ASServer", 20); + this.server = EditorPrefs.GetString("ASAdminServer"); + this.user = "admin"; + } + private void ServersPopup() + { + if (this.servers.Length > 0) + { + int num = EditorGUILayout.Popup(-1, this.servers, ASServerAdminWindow.constants.dropDown, new GUILayoutOption[] + { + GUILayout.MaxWidth(18f) + }); + if (num >= 0) + { + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = 0; + this.resetKeyboardControl = true; + this.server = this.servers[num]; + this.parentWin.Repaint(); + } + } + } + private bool WordWrappedLabelButton(string label, string buttonText) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(label, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + bool result = GUILayout.Button(buttonText, new GUILayoutOption[] + { + GUILayout.Width(100f) + }); + GUILayout.EndHorizontal(); + return result; + } + private bool CanPerformCurrentAction() + { + switch (this.currAction) + { + case ASServerAdminWindow.Action.Main: + return this.server != string.Empty && this.user != string.Empty; + case ASServerAdminWindow.Action.CreateUser: + { + bool flag = true; + for (int i = 0; i < this.nUserName.Length; i++) + { + char c = this.nUserName[i]; + if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '-' && c != '_') + { + flag = false; + break; + } + } + return this.nFullName != string.Empty && this.nUserName != string.Empty && this.nPassword1 != string.Empty && this.nPassword1 == this.nPassword2 && flag; + } + case ASServerAdminWindow.Action.SetPassword: + return this.nPassword1 != string.Empty && this.nPassword1 == this.nPassword2; + case ASServerAdminWindow.Action.CreateProject: + return this.nProjectName != string.Empty; + case ASServerAdminWindow.Action.ModifyUser: + return this.nFullName != string.Empty; + default: + return false; + } + } + private void PerformCurrentAction() + { + switch (this.currAction) + { + case ASServerAdminWindow.Action.Main: + this.currAction = ASServerAdminWindow.Action.Main; + this.DoConnect(); + Event.current.Use(); + break; + case ASServerAdminWindow.Action.CreateUser: + AssetServer.AdminCreateUser(this.nUserName, this.nFullName, this.nEmail, this.nPassword1); + this.currAction = ASServerAdminWindow.Action.Main; + if (this.lv.row > -1) + { + this.DoGetUsers(); + } + Event.current.Use(); + break; + case ASServerAdminWindow.Action.SetPassword: + AssetServer.AdminChangePassword(this.users[this.lv2.row].userName, this.nPassword1); + this.currAction = ASServerAdminWindow.Action.Main; + Event.current.Use(); + break; + case ASServerAdminWindow.Action.CreateProject: + if (AssetServer.AdminCreateDB(this.nProjectName, this.nTemplateProjectName) != 0) + { + this.DoRefreshDatabases(); + for (int i = 0; i < this.databases.Length; i++) + { + if (this.databases[i].name == this.nProjectName) + { + this.lv.row = i; + this.DoGetUsers(); + break; + } + } + } + this.currAction = ASServerAdminWindow.Action.Main; + Event.current.Use(); + break; + case ASServerAdminWindow.Action.ModifyUser: + AssetServer.AdminModifyUserInfo(this.databases[this.lv.row].dbName, this.users[this.lv2.row].userName, this.nFullName, this.nEmail); + this.currAction = ASServerAdminWindow.Action.Main; + if (this.lv.row > -1) + { + this.DoGetUsers(); + } + Event.current.Use(); + break; + } + } + private void ActionBox() + { + bool enabled = GUI.enabled; + switch (this.currAction) + { + case ASServerAdminWindow.Action.Main: + if (!this.isConnected) + { + GUI.enabled = false; + } + if (this.WordWrappedLabelButton("Want to create a new project?", "Create")) + { + this.nProjectName = string.Empty; + this.nTemplateProjectName = string.Empty; + this.currAction = ASServerAdminWindow.Action.CreateProject; + } + if (this.WordWrappedLabelButton("Want to create a new user?", "New User")) + { + this.nPassword1 = (this.nPassword2 = string.Empty); + this.nFullName = (this.nUserName = (this.nEmail = string.Empty)); + this.currAction = ASServerAdminWindow.Action.CreateUser; + } + GUI.enabled = (this.isConnected && this.userSelected && enabled); + if (this.WordWrappedLabelButton("Need to change user password?", "Set Password")) + { + this.nPassword1 = (this.nPassword2 = string.Empty); + this.currAction = ASServerAdminWindow.Action.SetPassword; + } + if (this.WordWrappedLabelButton("Need to change user information?", "Edit")) + { + this.nFullName = this.users[this.lv2.row].fullName; + this.nEmail = this.users[this.lv2.row].email; + this.currAction = ASServerAdminWindow.Action.ModifyUser; + } + GUI.enabled = (this.isConnected && this.projectSelected && enabled); + if (this.WordWrappedLabelButton("Duplicate selected project", "Copy Project")) + { + this.nProjectName = string.Empty; + this.nTemplateProjectName = this.databases[this.lv.row].name; + this.currAction = ASServerAdminWindow.Action.CreateProject; + } + if (this.WordWrappedLabelButton("Delete selected project", "Delete Project") && EditorUtility.DisplayDialog("Delete project", "Are you sure you want to delete project " + this.databases[this.lv.row].name + "? This operation cannot be undone!", "Delete", "Cancel") && AssetServer.AdminDeleteDB(this.databases[this.lv.row].name) != 0) + { + this.DoRefreshDatabases(); + GUIUtility.ExitGUI(); + } + GUI.enabled = (this.isConnected && this.userSelected && enabled); + if (this.WordWrappedLabelButton("Delete selected user", "Delete User") && EditorUtility.DisplayDialog("Delete user", "Are you sure you want to delete user " + this.users[this.lv2.row].userName + "? This operation cannot be undone!", "Delete", "Cancel") && AssetServer.AdminDeleteUser(this.users[this.lv2.row].userName) != 0) + { + if (this.lv.row > -1) + { + this.DoGetUsers(); + } + GUIUtility.ExitGUI(); + } + GUI.enabled = enabled; + break; + case ASServerAdminWindow.Action.CreateUser: + this.nFullName = EditorGUILayout.TextField("Full Name:", this.nFullName, new GUILayoutOption[0]); + this.nEmail = EditorGUILayout.TextField("Email Address:", this.nEmail, new GUILayoutOption[0]); + GUILayout.Space(5f); + this.nUserName = EditorGUILayout.TextField("User Name:", this.nUserName, new GUILayoutOption[0]); + GUILayout.Space(5f); + this.nPassword1 = EditorGUILayout.PasswordField("Password:", this.nPassword1, new GUILayoutOption[0]); + this.nPassword2 = EditorGUILayout.PasswordField("Repeat Password:", this.nPassword2, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.CanPerformCurrentAction() && enabled); + if (GUILayout.Button("Create User", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.PerformCurrentAction(); + } + GUI.enabled = enabled; + if (GUILayout.Button("Cancel", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.currAction = ASServerAdminWindow.Action.Main; + } + GUILayout.EndHorizontal(); + break; + case ASServerAdminWindow.Action.SetPassword: + GUILayout.Label("Setting password for user: " + this.users[this.lv2.row].userName, ASServerAdminWindow.constants.title, new GUILayoutOption[0]); + GUILayout.Space(5f); + this.nPassword1 = EditorGUILayout.PasswordField("Password:", this.nPassword1, new GUILayoutOption[0]); + this.nPassword2 = EditorGUILayout.PasswordField("Repeat Password:", this.nPassword2, new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.CanPerformCurrentAction() && enabled); + if (GUILayout.Button("Change Password", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.PerformCurrentAction(); + } + GUI.enabled = enabled; + if (GUILayout.Button("Cancel", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.currAction = ASServerAdminWindow.Action.Main; + } + GUILayout.EndHorizontal(); + break; + case ASServerAdminWindow.Action.CreateProject: + this.nProjectName = EditorGUILayout.TextField("Project Name:", this.nProjectName, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.CanPerformCurrentAction() && enabled); + if (GUILayout.Button((!(this.nTemplateProjectName == string.Empty)) ? ("Copy " + this.nTemplateProjectName) : "Create Project", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.PerformCurrentAction(); + } + GUI.enabled = enabled; + if (GUILayout.Button("Cancel", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.currAction = ASServerAdminWindow.Action.Main; + } + GUILayout.EndHorizontal(); + break; + case ASServerAdminWindow.Action.ModifyUser: + this.nFullName = EditorGUILayout.TextField("Full Name:", this.nFullName, new GUILayoutOption[0]); + this.nEmail = EditorGUILayout.TextField("Email Address:", this.nEmail, new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.CanPerformCurrentAction() && enabled); + if (GUILayout.Button("Change", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.PerformCurrentAction(); + } + GUI.enabled = enabled; + if (GUILayout.Button("Cancel", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.currAction = ASServerAdminWindow.Action.Main; + } + GUILayout.EndHorizontal(); + break; + } + } + private void DoRefreshDatabases() + { + MaintDatabaseRecord[] array = AssetServer.AdminRefreshDatabases(); + if (array != null) + { + this.databases = array; + this.isConnected = true; + } + else + { + this.databases = new MaintDatabaseRecord[0]; + this.lv2.totalRows = 0; + } + this.lv.row = -1; + this.lv.totalRows = this.databases.Length; + this.lv2.totalRows = 0; + this.users = new MaintUserRecord[0]; + } + private void DoConnect() + { + EditorPrefs.SetString("ASAdminServer", this.server); + this.userSelected = false; + this.isConnected = false; + this.projectSelected = false; + this.lv.row = -1; + this.lv2.row = -1; + this.lv.totalRows = 0; + this.lv2.totalRows = 0; + int port = 10733; + string text; + if (this.server.IndexOf(":") > 0) + { + int.TryParse(this.server.Substring(this.server.IndexOf(":") + 1), out port); + text = this.server.Substring(0, this.server.IndexOf(":")); + } + else + { + text = this.server; + } + AssetServer.AdminSetCredentials(text, port, this.user, this.password); + this.DoRefreshDatabases(); + } + private void DoGetUsers() + { + MaintUserRecord[] array = AssetServer.AdminGetUsers(this.databases[this.lv.row].dbName); + if (array != null) + { + this.users = array; + } + else + { + this.users = new MaintUserRecord[0]; + } + this.lv2.totalRows = this.users.Length; + this.lv2.row = -1; + } + public bool DoGUI() + { + bool enabled = GUI.enabled; + if (ASServerAdminWindow.constants == null) + { + ASServerAdminWindow.constants = new ASMainWindow.Constants(); + ASServerAdminWindow.constants.toggleSize = ASServerAdminWindow.constants.toggle.CalcSize(new GUIContent("X")); + } + if (this.resetKeyboardControl) + { + this.resetKeyboardControl = false; + GUIUtility.keyboardControl = 0; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(ASServerAdminWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Box("Server Connection", ASServerAdminWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASServerAdminWindow.constants.contentBox, new GUILayoutOption[0]); + Event current = Event.current; + if (current.type == EventType.KeyDown && current.keyCode == KeyCode.Return && this.CanPerformCurrentAction()) + { + this.PerformCurrentAction(); + } + if (current.type == EventType.KeyDown && current.keyCode == KeyCode.Escape && this.currAction != ASServerAdminWindow.Action.Main) + { + this.currAction = ASServerAdminWindow.Action.Main; + current.Use(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.server = EditorGUILayout.TextField("Server Address:", this.server, new GUILayoutOption[0]); + this.ServersPopup(); + GUILayout.EndHorizontal(); + this.user = EditorGUILayout.TextField("User Name:", this.user, new GUILayoutOption[0]); + this.password = EditorGUILayout.PasswordField("Password:", this.password, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.CanPerformCurrentAction() && enabled); + if (GUILayout.Button("Connect", ASServerAdminWindow.constants.smallButton, new GUILayoutOption[0])) + { + this.PerformCurrentAction(); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + if (AssetServer.GetAssetServerError() != string.Empty) + { + GUILayout.Label(AssetServer.GetAssetServerError(), ASServerAdminWindow.constants.errorLabel, new GUILayoutOption[0]); + } + GUILayout.EndVertical(); + GUILayout.EndVertical(); + GUILayout.BeginVertical(ASServerAdminWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Box("Admin Actions", ASServerAdminWindow.constants.title, new GUILayoutOption[0]); + GUILayout.BeginVertical(ASServerAdminWindow.constants.contentBox, new GUILayoutOption[0]); + this.ActionBox(); + GUILayout.EndVertical(); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(ASServerAdminWindow.constants.groupBox, new GUILayoutOption[0]); + GUILayout.Box("Project", ASServerAdminWindow.constants.title, new GUILayoutOption[0]); + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv, ASServerAdminWindow.constants.background, new GUILayoutOption[0])) + { + if (listViewElement.row == this.lv.row && Event.current.type == EventType.Repaint) + { + ASServerAdminWindow.constants.entrySelected.Draw(listViewElement.position, false, false, false, false); + } + GUILayout.Label(this.databases[listViewElement.row].name, new GUILayoutOption[0]); + } + if (this.lv.selectionChanged) + { + if (this.lv.row > -1) + { + this.projectSelected = true; + } + this.currAction = ASServerAdminWindow.Action.Main; + this.DoGetUsers(); + } + GUILayout.EndVertical(); + GUILayout.BeginVertical(ASServerAdminWindow.constants.groupBox, new GUILayoutOption[0]); + SplitterGUILayout.BeginHorizontalSplit(this.lvSplit, new GUILayoutOption[0]); + GUILayout.Box(string.Empty, ASServerAdminWindow.constants.columnHeader, new GUILayoutOption[0]); + GUILayout.Box("User", ASServerAdminWindow.constants.columnHeader, new GUILayoutOption[0]); + GUILayout.Box("Full Name", ASServerAdminWindow.constants.columnHeader, new GUILayoutOption[0]); + GUILayout.Box("Email", ASServerAdminWindow.constants.columnHeader, new GUILayoutOption[0]); + SplitterGUILayout.EndHorizontalSplit(); + int left = EditorStyles.label.margin.left; + foreach (ListViewElement listViewElement2 in ListViewGUILayout.ListView(this.lv2, ASServerAdminWindow.constants.background, new GUILayoutOption[0])) + { + if (listViewElement2.row == this.lv2.row && Event.current.type == EventType.Repaint) + { + ASServerAdminWindow.constants.entrySelected.Draw(listViewElement2.position, false, false, false, false); + } + bool flag = this.users[listViewElement2.row].enabled != 0; + bool flag2 = GUI.Toggle(new Rect(listViewElement2.position.x + 2f, listViewElement2.position.y - 1f, ASServerAdminWindow.constants.toggleSize.x, ASServerAdminWindow.constants.toggleSize.y), flag, string.Empty); + GUILayout.Space(ASServerAdminWindow.constants.toggleSize.x); + if (flag != flag2 && AssetServer.AdminSetUserEnabled(this.databases[this.lv.row].dbName, this.users[listViewElement2.row].userName, this.users[listViewElement2.row].fullName, this.users[listViewElement2.row].email, (!flag2) ? 0 : 1)) + { + this.users[listViewElement2.row].enabled = ((!flag2) ? 0 : 1); + } + GUILayout.Label(this.users[listViewElement2.row].userName, new GUILayoutOption[] + { + GUILayout.Width((float)(this.lvSplit.realSizes[1] - left)) + }); + GUILayout.Label(this.users[listViewElement2.row].fullName, new GUILayoutOption[] + { + GUILayout.Width((float)(this.lvSplit.realSizes[2] - left)) + }); + GUILayout.Label(this.users[listViewElement2.row].email, new GUILayoutOption[0]); + } + if (this.lv2.selectionChanged) + { + if (this.lv2.row > -1) + { + this.userSelected = true; + } + if (this.currAction == ASServerAdminWindow.Action.SetPassword) + { + this.currAction = ASServerAdminWindow.Action.Main; + } + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + if (!this.splittersOk && Event.current.type == EventType.Repaint) + { + this.splittersOk = true; + this.parentWin.Repaint(); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs b/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs new file mode 100644 index 00000000..7093a4d3 --- /dev/null +++ b/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs @@ -0,0 +1,698 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASUpdateConflictResolveWindow + { + private class Constants + { + public GUIStyle ButtonLeft = "ButtonLeft"; + public GUIStyle ButtonMiddle = "ButtonMid"; + public GUIStyle ButtonRight = "ButtonRight"; + public GUIStyle EntrySelected = "ServerUpdateChangesetOn"; + public GUIStyle EntryNormal = "ServerUpdateInfo"; + public GUIStyle lvHeader = "OL title"; + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle background = "OL Box"; + public GUIStyle button = "Button"; + public GUIStyle bigButton = "LargeButton"; + } + private ListViewState lv1 = new ListViewState(); + private ListViewState lv2 = new ListViewState(); + private bool[] selectedLV1Items; + private bool[] selectedLV2Items; + private bool[] deletionConflict; + private int initialSelectedLV1Item = -1; + private int initialSelectedLV2Item = -1; + private bool lv1HasSelection; + private bool lv2HasSelection; + private SplitterState lvHeaderSplit1 = new SplitterState(new float[] + { + 20f, + 80f + }, new int[] + { + 100, + 100 + }, null); + private SplitterState lvHeaderSplit2 = new SplitterState(new float[] + { + 20f, + 80f + }, new int[] + { + 100, + 100 + }, null); + private static string[] conflictButtonTexts = new string[] + { + "Skip Asset", + "Discard My Changes", + "Ignore Server Changes", + "Merge", + "Unresolved" + }; + private static string[] nameConflictButtonTexts = new string[] + { + "Rename Local Asset", + "Rename Server Asset" + }; + private string[] dropDownMenuItems = new string[] + { + "Compare", + "Compare Binary" + }; + private string[] downloadConflicts = new string[0]; + private string[] nameConflicts = new string[0]; + private string[] dConflictPaths = new string[0]; + private string[] dNamingPaths = new string[0]; + private DownloadResolution[] downloadResolutions = new DownloadResolution[0]; + private NameConflictResolution[] namingResolutions = new NameConflictResolution[0]; + private int downloadConflictsToResolve; + private bool showDownloadConflicts; + private bool showNamingConflicts; + private bool mySelection; + private bool enableContinueButton; + private bool enableMergeButton = true; + private bool splittersOk; + private Vector2 iconSize = new Vector2(16f, 16f); + private ASUpdateConflictResolveWindow.Constants constants; + private string[] downloadResolutionString = new string[] + { + "Unresolved", + "Skip Asset", + "Discard My Changes", + "Ignore Server Changes", + "Merge" + }; + private string[] namingResolutionString = new string[] + { + "Unresolved", + "Rename Local Asset", + "Rename Server Asset" + }; + public ASUpdateConflictResolveWindow(string[] conflicting) + { + this.downloadConflictsToResolve = 0; + ArrayList arrayList = new ArrayList(); + ArrayList arrayList2 = new ArrayList(); + ArrayList arrayList3 = new ArrayList(); + ArrayList arrayList4 = new ArrayList(); + for (int i = 0; i < conflicting.Length; i++) + { + AssetStatus statusGUID = AssetServer.GetStatusGUID(conflicting[i]); + if (statusGUID == AssetStatus.Conflict) + { + arrayList.Add(conflicting[i]); + DownloadResolution downloadResolution = AssetServer.GetDownloadResolution(conflicting[i]); + arrayList2.Add(downloadResolution); + if (downloadResolution == DownloadResolution.Unresolved) + { + this.downloadConflictsToResolve++; + } + } + if (AssetServer.GetPathNameConflict(conflicting[i]) != null && statusGUID != AssetStatus.ServerOnly) + { + arrayList4.Add(conflicting[i]); + NameConflictResolution nameConflictResolution = AssetServer.GetNameConflictResolution(conflicting[i]); + arrayList3.Add(nameConflictResolution); + if (nameConflictResolution == NameConflictResolution.Unresolved) + { + this.downloadConflictsToResolve++; + } + } + } + this.downloadConflicts = (arrayList.ToArray(typeof(string)) as string[]); + this.downloadResolutions = (arrayList2.ToArray(typeof(DownloadResolution)) as DownloadResolution[]); + this.namingResolutions = (arrayList3.ToArray(typeof(NameConflictResolution)) as NameConflictResolution[]); + this.nameConflicts = (arrayList4.ToArray(typeof(string)) as string[]); + this.enableContinueButton = (this.downloadConflictsToResolve == 0); + this.dConflictPaths = new string[this.downloadConflicts.Length]; + this.deletionConflict = new bool[this.downloadConflicts.Length]; + for (int j = 0; j < this.downloadConflicts.Length; j++) + { + if (AssetServer.HasDeletionConflict(this.downloadConflicts[j])) + { + this.dConflictPaths[j] = ParentViewFolder.MakeNiceName(AssetServer.GetDeletedItemPathAndName(this.downloadConflicts[j])); + this.deletionConflict[j] = true; + } + else + { + this.dConflictPaths[j] = ParentViewFolder.MakeNiceName(AssetServer.GetAssetPathName(this.downloadConflicts[j])); + this.deletionConflict[j] = false; + } + } + this.dNamingPaths = new string[this.nameConflicts.Length]; + for (int k = 0; k < this.nameConflicts.Length; k++) + { + this.dNamingPaths[k] = ParentViewFolder.MakeNiceName(AssetServer.GetAssetPathName(this.nameConflicts[k])); + } + this.showDownloadConflicts = (this.downloadConflicts.Length > 0); + this.showNamingConflicts = (this.nameConflicts.Length > 0); + this.lv1.totalRows = this.downloadConflicts.Length; + this.lv2.totalRows = this.nameConflicts.Length; + this.selectedLV1Items = new bool[this.downloadConflicts.Length]; + this.selectedLV2Items = new bool[this.nameConflicts.Length]; + this.DoSelectionChange(); + } + public string[] GetDownloadConflicts() + { + return this.downloadConflicts; + } + public string[] GetNameConflicts() + { + return this.nameConflicts; + } + public bool CanContinue() + { + return this.enableContinueButton; + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string text = this.dropDownMenuItems[selected]; + if (text != null) + { + if (ASUpdateConflictResolveWindow.<>f__switch$mapE == null) + { + ASUpdateConflictResolveWindow.<>f__switch$mapE = new Dictionary(2) + { + + { + "Compare", + 0 + }, + + { + "Compare Binary", + 1 + } + }; + } + int num; + if (ASUpdateConflictResolveWindow.<>f__switch$mapE.TryGetValue(text, out num)) + { + if (num != 0) + { + if (num == 1) + { + this.DoShowDiff(true); + } + } + else + { + this.DoShowDiff(false); + } + } + } + } + } + private void ResolveSelectedDownloadConflicts(DownloadResolution res) + { + int num = -1; + bool flag = false; + for (int i = 0; i < this.downloadConflicts.Length; i++) + { + if (this.selectedLV1Items[i]) + { + string guid = this.downloadConflicts[i]; + if (res == DownloadResolution.Merge && (AssetServer.AssetIsBinaryByGUID(guid) || AssetServer.IsItemDeleted(guid))) + { + flag = true; + } + else + { + if (res != DownloadResolution.Unresolved) + { + if (AssetServer.GetDownloadResolution(guid) == DownloadResolution.Unresolved) + { + this.downloadConflictsToResolve--; + } + } + else + { + this.downloadConflictsToResolve++; + } + this.downloadResolutions[i] = res; + AssetServer.SetDownloadResolution(guid, res); + num = ((num != -1) ? -2 : i); + } + } + } + this.enableContinueButton = (this.downloadConflictsToResolve == 0); + if (num >= 0) + { + this.selectedLV1Items[num] = false; + if (num < this.selectedLV1Items.Length - 1) + { + this.selectedLV1Items[num + 1] = true; + } + } + this.enableMergeButton = this.AtLeastOneSelectedAssetCanBeMerged(); + if (flag) + { + EditorUtility.DisplayDialog("Some conflicting changes cannot be merged", "Notice that not all selected changes where selected for merging. This happened because not all of them can be merged (e.g. assets are binary or deleted).", "OK"); + } + } + private void ResolveSelectedNamingConflicts(NameConflictResolution res) + { + if (res != NameConflictResolution.Unresolved) + { + for (int i = 0; i < this.nameConflicts.Length; i++) + { + if (this.selectedLV2Items[i]) + { + string guid = this.nameConflicts[i]; + if (AssetServer.GetNameConflictResolution(guid) == NameConflictResolution.Unresolved) + { + this.downloadConflictsToResolve--; + } + this.namingResolutions[i] = res; + AssetServer.SetNameConflictResolution(guid, res); + } + } + this.enableContinueButton = (this.downloadConflictsToResolve == 0); + } + } + private bool DoShowDiff(bool binary) + { + List list = new List(); + List list2 = new List(); + for (int i = 0; i < this.selectedLV1Items.Length; i++) + { + if (this.selectedLV1Items[i]) + { + int serverItemChangeset = AssetServer.GetServerItemChangeset(this.downloadConflicts[i], -1); + int ver = (!AssetServer.HasDeletionConflict(this.downloadConflicts[i])) ? -1 : -2; + list.Add(this.downloadConflicts[i]); + list2.Add(new CompareInfo(serverItemChangeset, ver, (!binary) ? 0 : 1, (!binary) ? 1 : 0)); + } + } + if (list.Count != 0) + { + AssetServer.CompareFiles(list.ToArray(), list2.ToArray()); + return true; + } + return false; + } + private string[] GetSelectedGUIDs() + { + List list = new List(); + for (int i = 0; i < this.downloadConflicts.Length; i++) + { + if (this.selectedLV1Items[i]) + { + list.Add(this.downloadConflicts[i]); + } + } + return list.ToArray(); + } + private string[] GetSelectedNamingGUIDs() + { + List list = new List(); + for (int i = 0; i < this.nameConflicts.Length; i++) + { + if (this.selectedLV2Items[i]) + { + list.Add(this.nameConflicts[i]); + } + } + return list.ToArray(); + } + private bool HasTrue(ref bool[] array) + { + for (int i = 0; i < array.Length; i++) + { + if (array[i]) + { + return true; + } + } + return false; + } + private void DoSelectionChange() + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + List list = new List(Selection.objects.Length); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + if (hierarchyProperty.Find(@object.GetInstanceID(), null)) + { + list.Add(hierarchyProperty.guid); + } + } + for (int j = 0; j < this.downloadConflicts.Length; j++) + { + this.selectedLV1Items[j] = list.Contains(this.downloadConflicts[j]); + } + for (int k = 0; k < this.nameConflicts.Length; k++) + { + this.selectedLV2Items[k] = list.Contains(this.nameConflicts[k]); + } + this.lv1HasSelection = this.HasTrue(ref this.selectedLV1Items); + this.lv2HasSelection = this.HasTrue(ref this.selectedLV2Items); + this.enableMergeButton = this.AtLeastOneSelectedAssetCanBeMerged(); + } + public void OnSelectionChange(ASUpdateWindow parentWin) + { + if (!this.mySelection) + { + this.DoSelectionChange(); + parentWin.Repaint(); + } + else + { + this.mySelection = false; + } + } + private bool AtLeastOneSelectedAssetCanBeMerged() + { + for (int i = 0; i < this.downloadConflicts.Length; i++) + { + if (this.selectedLV1Items[i] && !AssetServer.AssetIsBinaryByGUID(this.downloadConflicts[i]) && !AssetServer.IsItemDeleted(this.downloadConflicts[i])) + { + return true; + } + } + return false; + } + private void DoDownloadConflictsGUI() + { + bool enabled = GUI.enabled; + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("The following assets have been changed both on the server and in the local project.\nPlease select a conflict resolution for each before continuing the update.", new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.lv1HasSelection && enabled); + if (GUILayout.Button(ASUpdateConflictResolveWindow.conflictButtonTexts[0], this.constants.ButtonLeft, new GUILayoutOption[0])) + { + this.ResolveSelectedDownloadConflicts(DownloadResolution.SkipAsset); + } + if (GUILayout.Button(ASUpdateConflictResolveWindow.conflictButtonTexts[1], this.constants.ButtonMiddle, new GUILayoutOption[0])) + { + this.ResolveSelectedDownloadConflicts(DownloadResolution.TrashMyChanges); + } + if (GUILayout.Button(ASUpdateConflictResolveWindow.conflictButtonTexts[2], this.constants.ButtonMiddle, new GUILayoutOption[0])) + { + this.ResolveSelectedDownloadConflicts(DownloadResolution.TrashServerChanges); + } + if (!this.enableMergeButton) + { + GUI.enabled = false; + } + if (GUILayout.Button(ASUpdateConflictResolveWindow.conflictButtonTexts[3], this.constants.ButtonRight, new GUILayoutOption[0])) + { + this.ResolveSelectedDownloadConflicts(DownloadResolution.Merge); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + SplitterGUILayout.BeginHorizontalSplit(this.lvHeaderSplit1, new GUILayoutOption[0]); + GUILayout.Box("Action", this.constants.lvHeader, new GUILayoutOption[0]); + GUILayout.Box("Asset", this.constants.lvHeader, new GUILayoutOption[0]); + SplitterGUILayout.EndHorizontalSplit(); + int row = this.lv1.row; + bool flag = false; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv1, this.constants.background, new GUILayoutOption[0])) + { + if (GUIUtility.keyboardControl == this.lv1.ID && Event.current.type == EventType.KeyDown && actionKey) + { + Event.current.Use(); + } + if (this.selectedLV1Items[listViewElement.row] && Event.current.type == EventType.Repaint) + { + this.constants.selected.Draw(listViewElement.position, false, false, false, false); + } + if (ListViewGUILayout.HasMouseUp(listViewElement.position)) + { + if (!shift && !actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, this.lv1.row, ref this.initialSelectedLV1Item, ref this.selectedLV1Items); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position)) + { + if (Event.current.clickCount == 2 && !AssetServer.AssetIsDir(this.downloadConflicts[listViewElement.row])) + { + this.DoShowDiff(false); + GUIUtility.ExitGUI(); + } + else + { + if (!this.selectedLV1Items[listViewElement.row] || shift || actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.initialSelectedLV1Item, ref this.selectedLV1Items); + } + this.lv1.row = listViewElement.row; + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position, 1)) + { + if (!this.selectedLV1Items[listViewElement.row]) + { + flag = true; + for (int i = 0; i < this.selectedLV1Items.Length; i++) + { + this.selectedLV1Items[i] = false; + } + this.lv1.selectionChanged = true; + this.selectedLV1Items[listViewElement.row] = true; + this.lv1.row = listViewElement.row; + } + GUIUtility.hotControl = 0; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, this.dropDownMenuItems, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + Event.current.Use(); + } + } + } + GUILayout.Label(this.downloadResolutionString[(int)this.downloadResolutions[listViewElement.row]], new GUILayoutOption[] + { + GUILayout.Width((float)this.lvHeaderSplit1.realSizes[0]), + GUILayout.Height(18f) + }); + if (this.deletionConflict[listViewElement.row] && Event.current.type == EventType.Repaint) + { + GUIContent badgeDelete = ASMainWindow.badgeDelete; + Rect position2 = new Rect(listViewElement.position.x + (float)this.lvHeaderSplit1.realSizes[0] - (float)badgeDelete.image.width - 5f, listViewElement.position.y + listViewElement.position.height / 2f - (float)(badgeDelete.image.height / 2), (float)badgeDelete.image.width, (float)badgeDelete.image.height); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUIStyle.none.Draw(position2, badgeDelete, false, false, false, false); + EditorGUIUtility.SetIconSize(this.iconSize); + } + GUILayout.Label(new GUIContent(this.dConflictPaths[listViewElement.row], (!AssetServer.AssetIsDir(this.downloadConflicts[listViewElement.row])) ? InternalEditorUtility.GetIconForFile(this.dConflictPaths[listViewElement.row]) : EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName)), new GUILayoutOption[] + { + GUILayout.Width((float)this.lvHeaderSplit1.realSizes[1]), + GUILayout.Height(18f) + }); + } + GUILayout.EndVertical(); + if (GUIUtility.keyboardControl == this.lv1.ID) + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + for (int j = 0; j < this.selectedLV1Items.Length; j++) + { + this.selectedLV1Items[j] = true; + } + flag = true; + Event.current.Use(); + } + } + if (this.lv1.selectionChanged && !actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, this.lv1.row, ref this.initialSelectedLV1Item, ref this.selectedLV1Items); + } + else + { + if (GUIUtility.keyboardControl == this.lv1.ID && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && !AssetServer.AssetIsDir(this.downloadConflicts[this.lv1.row])) + { + this.DoShowDiff(false); + GUIUtility.ExitGUI(); + } + } + } + if (this.lv1.selectionChanged || flag) + { + this.mySelection = true; + AssetServer.SetSelectionFromGUIDs(this.GetSelectedGUIDs()); + this.lv1HasSelection = this.HasTrue(ref this.selectedLV1Items); + this.enableMergeButton = this.AtLeastOneSelectedAssetCanBeMerged(); + } + } + private void DoNamingConflictsGUI() + { + bool enabled = GUI.enabled; + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.Label("The following assets have the same name as an existing asset on the server.\nPlease select which one to rename before continuing the update.", new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = (this.lv2HasSelection && enabled); + if (GUILayout.Button(ASUpdateConflictResolveWindow.nameConflictButtonTexts[0], this.constants.ButtonLeft, new GUILayoutOption[0])) + { + this.ResolveSelectedNamingConflicts(NameConflictResolution.RenameLocal); + } + if (GUILayout.Button(ASUpdateConflictResolveWindow.nameConflictButtonTexts[1], this.constants.ButtonRight, new GUILayoutOption[0])) + { + this.ResolveSelectedNamingConflicts(NameConflictResolution.RenameRemote); + } + GUI.enabled = enabled; + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + SplitterGUILayout.BeginHorizontalSplit(this.lvHeaderSplit2, new GUILayoutOption[0]); + GUILayout.Box("Action", this.constants.lvHeader, new GUILayoutOption[0]); + GUILayout.Box("Asset", this.constants.lvHeader, new GUILayoutOption[0]); + SplitterGUILayout.EndHorizontalSplit(); + int row = this.lv2.row; + bool flag = false; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv2, this.constants.background, new GUILayoutOption[0])) + { + if (GUIUtility.keyboardControl == this.lv2.ID && Event.current.type == EventType.KeyDown && actionKey) + { + Event.current.Use(); + } + if (this.selectedLV2Items[listViewElement.row] && Event.current.type == EventType.Repaint) + { + this.constants.selected.Draw(listViewElement.position, false, false, false, false); + } + if (ListViewGUILayout.HasMouseUp(listViewElement.position)) + { + if (!shift && !actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, this.lv2.row, ref this.initialSelectedLV2Item, ref this.selectedLV2Items); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position)) + { + if (!this.selectedLV2Items[listViewElement.row] || shift || actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.initialSelectedLV2Item, ref this.selectedLV2Items); + } + this.lv2.row = listViewElement.row; + } + } + GUILayout.Label(this.namingResolutionString[(int)this.namingResolutions[listViewElement.row]], new GUILayoutOption[] + { + GUILayout.Width((float)this.lvHeaderSplit2.realSizes[0]), + GUILayout.Height(18f) + }); + GUILayout.Label(new GUIContent(this.dNamingPaths[listViewElement.row], (!AssetServer.AssetIsDir(this.nameConflicts[listViewElement.row])) ? InternalEditorUtility.GetIconForFile(this.dNamingPaths[listViewElement.row]) : EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName)), new GUILayoutOption[] + { + GUILayout.Width((float)this.lvHeaderSplit2.realSizes[1]), + GUILayout.Height(18f) + }); + } + GUILayout.EndVertical(); + if (GUIUtility.keyboardControl == this.lv2.ID) + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + for (int i = 0; i < this.selectedLV2Items.Length; i++) + { + this.selectedLV2Items[i] = true; + } + flag = true; + Event.current.Use(); + } + } + if (this.lv2.selectionChanged && !actionKey) + { + flag |= ListViewGUILayout.MultiSelection(row, this.lv2.row, ref this.initialSelectedLV2Item, ref this.selectedLV2Items); + } + } + if (this.lv2.selectionChanged || flag) + { + this.mySelection = true; + AssetServer.SetSelectionFromGUIDs(this.GetSelectedNamingGUIDs()); + this.lv2HasSelection = this.HasTrue(ref this.selectedLV2Items); + } + } + public bool DoGUI(ASUpdateWindow parentWin) + { + if (this.constants == null) + { + this.constants = new ASUpdateConflictResolveWindow.Constants(); + } + bool enabled = GUI.enabled; + EditorGUIUtility.SetIconSize(this.iconSize); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (this.showDownloadConflicts) + { + this.DoDownloadConflictsGUI(); + } + if (this.showNamingConflicts) + { + this.DoNamingConflictsGUI(); + } + GUILayout.EndVertical(); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.enabled = (this.lv1HasSelection && enabled); + if (GUILayout.Button("Compare", this.constants.button, new GUILayoutOption[0])) + { + if (!this.DoShowDiff(false)) + { + Debug.Log("No differences found"); + } + GUIUtility.ExitGUI(); + } + GUI.enabled = enabled; + GUILayout.FlexibleSpace(); + GUI.enabled = (parentWin.CanContinue && enabled); + if (GUILayout.Button("Continue", this.constants.bigButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + parentWin.DoUpdate(true); + return false; + } + GUI.enabled = enabled; + if (GUILayout.Button("Cancel", this.constants.bigButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + return false; + } + GUILayout.EndHorizontal(); + if (!this.splittersOk && Event.current.type == EventType.Repaint) + { + this.splittersOk = true; + parentWin.Repaint(); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ASUpdateWindow.cs b/UnityEditor/UnityEditor/ASUpdateWindow.cs new file mode 100644 index 00000000..c146a7db --- /dev/null +++ b/UnityEditor/UnityEditor/ASUpdateWindow.cs @@ -0,0 +1,548 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ASUpdateWindow + { + internal class Constants + { + public GUIStyle box = "OL Box"; + public GUIStyle entrySelected = "ServerUpdateChangesetOn"; + public GUIStyle entryNormal = "ServerUpdateChangeset"; + public GUIStyle serverUpdateLog = "ServerUpdateLog"; + public GUIStyle serverChangeCount = "ServerChangeCount"; + public GUIStyle title = "OL title"; + public GUIStyle element = "OL elem"; + public GUIStyle header = "OL header"; + public GUIStyle serverUpdateInfo = "ServerUpdateInfo"; + public GUIStyle button = "Button"; + public GUIStyle errorLabel = "ErrorLabel"; + public GUIStyle bigButton = "LargeButton"; + public GUIStyle wwText = "AS TextArea"; + public GUIStyle entryEven = "CN EntryBackEven"; + public GUIStyle entryOdd = "CN EntryBackOdd"; + } + private ASUpdateWindow.Constants constants; + private ASUpdateConflictResolveWindow asResolveWin; + private ASMainWindow parentWin; + private string[] dropDownMenuItems = new string[] + { + "Compare", + "Compare Binary" + }; + private Changeset[] changesets; + private Vector2 iconSize = new Vector2(16f, 16f); + private string[] messageFirstLines; + private int maxNickLength; + private string selectedGUID = string.Empty; + private bool isDirSelected; + private ListViewState lv; + private ParentViewState pv = new ParentViewState(); + private SplitterState horSplit = new SplitterState(new float[] + { + 50f, + 50f + }, new int[] + { + 50, + 50 + }, null); + private SplitterState vertSplit = new SplitterState(new float[] + { + 60f, + 30f + }, new int[] + { + 32, + 32 + }, null); + private string totalUpdates; + private bool showingConflicts; + public bool ShowingConflicts + { + get + { + return this.showingConflicts; + } + } + public bool CanContinue + { + get + { + return this.asResolveWin.CanContinue(); + } + } + public ASUpdateWindow(ASMainWindow parentWin, Changeset[] changesets) + { + this.changesets = changesets; + this.parentWin = parentWin; + this.lv = new ListViewState(changesets.Length, 5); + this.pv.lv = new ListViewState(0, 5); + this.messageFirstLines = new string[changesets.Length]; + for (int i = 0; i < changesets.Length; i++) + { + this.messageFirstLines[i] = changesets[i].message.Split(new char[] + { + '\n' + })[0]; + } + this.totalUpdates = changesets.Length.ToString() + ((changesets.Length != 1) ? " Updates" : " Update"); + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string text = this.dropDownMenuItems[selected]; + if (text != null) + { + if (ASUpdateWindow.<>f__switch$mapF == null) + { + ASUpdateWindow.<>f__switch$mapF = new Dictionary(2) + { + + { + "Compare", + 0 + }, + + { + "Compare Binary", + 1 + } + }; + } + int num; + if (ASUpdateWindow.<>f__switch$mapF.TryGetValue(text, out num)) + { + if (num != 0) + { + if (num == 1) + { + this.DoShowDiff(true); + } + } + else + { + this.DoShowDiff(false); + } + } + } + } + } + private void DoSelectionChange() + { + if (this.lv.row != -1) + { + string firstSelected = this.GetFirstSelected(); + if (firstSelected != string.Empty) + { + this.selectedGUID = firstSelected; + } + if (AssetServer.IsGUIDValid(this.selectedGUID) != 0) + { + int num = 0; + this.pv.lv.row = -1; + ParentViewFolder[] folders = this.pv.folders; + for (int i = 0; i < folders.Length; i++) + { + ParentViewFolder parentViewFolder = folders[i]; + if (parentViewFolder.guid == this.selectedGUID) + { + this.pv.lv.row = num; + return; + } + num++; + ParentViewFile[] files = parentViewFolder.files; + for (int j = 0; j < files.Length; j++) + { + ParentViewFile parentViewFile = files[j]; + if (parentViewFile.guid == this.selectedGUID) + { + this.pv.lv.row = num; + return; + } + num++; + } + } + } + else + { + this.pv.lv.row = -1; + } + } + } + private string GetFirstSelected() + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + return (filtered.Length == 0) ? string.Empty : AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(filtered[0])); + } + public void OnSelectionChange() + { + if (this.showingConflicts) + { + this.asResolveWin.OnSelectionChange(this); + } + else + { + this.DoSelectionChange(); + this.parentWin.Repaint(); + } + } + public int GetSelectedRevisionNumber() + { + return (this.pv.lv.row <= this.lv.totalRows - 1 && this.lv.row >= 0) ? this.changesets[this.lv.row].changeset : -1; + } + public void SetSelectedRevisionLine(int selIndex) + { + if (selIndex >= this.lv.totalRows) + { + this.pv.Clear(); + this.lv.row = -1; + } + else + { + this.lv.row = selIndex; + this.pv.Clear(); + this.pv.AddAssetItems(this.changesets[selIndex]); + this.pv.SetLineCount(); + } + this.pv.lv.scrollPos = Vector2.zero; + this.pv.lv.row = -1; + this.pv.selectedFolder = -1; + this.pv.selectedFile = -1; + this.DoSelectionChange(); + } + public string[] GetGUIDs() + { + List list = new List(); + if (this.lv.row < 0) + { + return null; + } + for (int i = this.lv.row; i < this.lv.totalRows; i++) + { + for (int j = 0; j < this.changesets[i].items.Length; j++) + { + if (!list.Contains(this.changesets[i].items[j].guid)) + { + list.Add(this.changesets[i].items[j].guid); + } + } + } + return list.ToArray(); + } + public bool DoUpdate(bool afterResolvingConflicts) + { + AssetServer.RemoveMaintErrorsFromConsole(); + if (!ASEditorBackend.SettingsIfNeeded()) + { + return true; + } + this.showingConflicts = false; + AssetServer.SetAfterActionFinishedCallback("ASEditorBackend", "CBReinitOnSuccess"); + AssetServer.DoUpdateOnNextTick(!afterResolvingConflicts, "ShowASConflictResolutionsWindow"); + return true; + } + public void ShowConflictResolutions(string[] conflicting) + { + this.asResolveWin = new ASUpdateConflictResolveWindow(conflicting); + this.showingConflicts = true; + } + private bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) + { + return (flagToCheck & flags) != ChangeFlags.None; + } + private void DoSelect(int folderI, int fileI, int row) + { + this.pv.selectedFile = fileI; + this.pv.selectedFolder = folderI; + this.pv.lv.row = row; + this.pv.lv.selectionChanged = true; + if (fileI == -1) + { + if (folderI != -1) + { + this.selectedGUID = this.pv.folders[folderI].guid; + this.isDirSelected = true; + } + else + { + this.selectedGUID = string.Empty; + this.isDirSelected = false; + } + } + else + { + this.selectedGUID = this.pv.folders[folderI].files[fileI].guid; + this.isDirSelected = false; + } + } + public void UpdateGUI() + { + SplitterGUILayout.BeginHorizontalSplit(this.horSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(this.constants.box, new GUILayoutOption[0]); + GUILayout.Label(this.totalUpdates, this.constants.title, new GUILayoutOption[0]); + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv, GUIStyle.none, new GUILayoutOption[0])) + { + Rect position = listViewElement.position; + position.x += 1f; + position.y += 1f; + if (Event.current.type == EventType.Repaint) + { + if (listViewElement.row % 2 == 0) + { + this.constants.entryEven.Draw(position, false, false, false, false); + } + else + { + this.constants.entryOdd.Draw(position, false, false, false, false); + } + } + GUILayout.BeginVertical((listViewElement.row != this.lv.row) ? this.constants.entryNormal : this.constants.entrySelected, new GUILayoutOption[0]); + GUILayout.Label(this.messageFirstLines[listViewElement.row], this.constants.serverUpdateLog, new GUILayoutOption[] + { + GUILayout.MinWidth(50f) + }); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(this.changesets[listViewElement.row].changeset.ToString() + " " + this.changesets[listViewElement.row].date, this.constants.serverUpdateInfo, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + }); + GUILayout.Label(this.changesets[listViewElement.row].owner, this.constants.serverUpdateInfo, new GUILayoutOption[] + { + GUILayout.Width((float)this.maxNickLength) + }); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + if (this.lv.selectionChanged) + { + this.SetSelectedRevisionLine(this.lv.row); + } + GUILayout.EndVertical(); + SplitterGUILayout.BeginVerticalSplit(this.vertSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(this.constants.box, new GUILayoutOption[0]); + GUILayout.Label("Changeset", this.constants.title, new GUILayoutOption[0]); + int num = -1; + int num2 = -1; + foreach (ListViewElement listViewElement2 in ListViewGUILayout.ListView(this.pv.lv, GUIStyle.none, new GUILayoutOption[0])) + { + if (num == -1 && !this.pv.IndexToFolderAndFile(listViewElement2.row, ref num, ref num2)) + { + return; + } + ParentViewFolder parentViewFolder = this.pv.folders[num]; + if (ListViewGUILayout.HasMouseDown(listViewElement2.position)) + { + if (Event.current.clickCount == 2) + { + if (!this.isDirSelected && this.selectedGUID != string.Empty) + { + this.DoShowDiff(false); + GUIUtility.ExitGUI(); + } + } + else + { + this.pv.lv.scrollPos = ListViewShared.ListViewScrollToRow(this.pv.lv.ilvState, listViewElement2.row); + this.DoSelect(num, num2, listViewElement2.row); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement2.position, 1)) + { + if (this.lv.row != listViewElement2.row) + { + this.DoSelect(num, num2, listViewElement2.row); + } + if (!this.isDirSelected && this.selectedGUID != string.Empty) + { + GUIUtility.hotControl = 0; + Rect position2 = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position2, this.dropDownMenuItems, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), null); + Event.current.Use(); + } + } + } + if (listViewElement2.row == this.pv.lv.row && Event.current.type == EventType.Repaint) + { + this.constants.entrySelected.Draw(listViewElement2.position, false, false, false, false); + } + ChangeFlags changeFlags; + if (num2 != -1) + { + Texture2D texture2D = AssetDatabase.GetCachedIcon(parentViewFolder.name + "/" + parentViewFolder.files[num2].name) as Texture2D; + if (texture2D == null) + { + texture2D = InternalEditorUtility.GetIconForFile(parentViewFolder.files[num2].name); + } + GUILayout.Label(new GUIContent(parentViewFolder.files[num2].name, texture2D), this.constants.element, new GUILayoutOption[0]); + changeFlags = parentViewFolder.files[num2].changeFlags; + } + else + { + GUILayout.Label(parentViewFolder.name, this.constants.header, new GUILayoutOption[0]); + changeFlags = parentViewFolder.changeFlags; + } + GUIContent gUIContent = null; + if (this.HasFlag(changeFlags, ChangeFlags.Undeleted) || this.HasFlag(changeFlags, ChangeFlags.Created)) + { + gUIContent = ASMainWindow.badgeNew; + } + else + { + if (this.HasFlag(changeFlags, ChangeFlags.Deleted)) + { + gUIContent = ASMainWindow.badgeDelete; + } + else + { + if (this.HasFlag(changeFlags, ChangeFlags.Renamed) || this.HasFlag(changeFlags, ChangeFlags.Moved)) + { + gUIContent = ASMainWindow.badgeMove; + } + } + } + if (gUIContent != null && Event.current.type == EventType.Repaint) + { + Rect position3 = new Rect(listViewElement2.position.x + listViewElement2.position.width - (float)gUIContent.image.width - 5f, listViewElement2.position.y + listViewElement2.position.height / 2f - (float)(gUIContent.image.height / 2), (float)gUIContent.image.width, (float)gUIContent.image.height); + EditorGUIUtility.SetIconSize(Vector2.zero); + GUIStyle.none.Draw(position3, gUIContent, false, false, false, false); + EditorGUIUtility.SetIconSize(this.iconSize); + } + this.pv.NextFileFolder(ref num, ref num2); + } + if (this.pv.lv.selectionChanged && this.selectedGUID != string.Empty) + { + if (this.selectedGUID != AssetServer.GetRootGUID()) + { + AssetServer.SetSelectionFromGUID(this.selectedGUID); + } + else + { + AssetServer.SetSelectionFromGUID(string.Empty); + } + } + if (GUIUtility.keyboardControl == this.pv.lv.ID && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && !this.isDirSelected && this.selectedGUID != string.Empty) + { + this.DoShowDiff(false); + GUIUtility.ExitGUI(); + } + GUILayout.EndVertical(); + GUILayout.BeginVertical(this.constants.box, new GUILayoutOption[0]); + GUILayout.Label("Update Message", this.constants.title, new GUILayoutOption[0]); + GUILayout.TextArea((this.lv.row < 0) ? string.Empty : this.changesets[this.lv.row].message, this.constants.wwText, new GUILayoutOption[0]); + GUILayout.EndVertical(); + SplitterGUILayout.EndVerticalSplit(); + SplitterGUILayout.EndHorizontalSplit(); + } + private bool DoShowDiff(bool binary) + { + List list = new List(); + List list2 = new List(); + int num; + if (AssetServer.IsItemDeleted(this.selectedGUID)) + { + num = -2; + } + else + { + num = AssetServer.GetWorkingItemChangeset(this.selectedGUID); + num = AssetServer.GetServerItemChangeset(this.selectedGUID, num); + } + int serverItemChangeset = AssetServer.GetServerItemChangeset(this.selectedGUID, -1); + int ver = (serverItemChangeset != -1) ? serverItemChangeset : -2; + list.Add(this.selectedGUID); + list2.Add(new CompareInfo(num, ver, (!binary) ? 0 : 1, (!binary) ? 1 : 0)); + if (list.Count != 0) + { + AssetServer.CompareFiles(list.ToArray(), list2.ToArray()); + return true; + } + return false; + } + public void Repaint() + { + this.parentWin.Repaint(); + } + public bool DoGUI() + { + bool enabled = GUI.enabled; + if (this.constants == null) + { + this.constants = new ASUpdateWindow.Constants(); + this.maxNickLength = 1; + for (int i = 0; i < this.changesets.Length; i++) + { + int num = (int)this.constants.serverUpdateInfo.CalcSize(new GUIContent(this.changesets[i].owner)).x; + if (num > this.maxNickLength) + { + this.maxNickLength = num; + } + } + } + EditorGUIUtility.SetIconSize(this.iconSize); + if (this.showingConflicts) + { + if (!this.asResolveWin.DoGUI(this)) + { + this.showingConflicts = false; + } + } + else + { + this.UpdateGUI(); + } + EditorGUIUtility.SetIconSize(Vector2.zero); + if (!this.showingConflicts) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.enabled = (!this.isDirSelected && this.selectedGUID != string.Empty && enabled); + if (GUILayout.Button("Compare", this.constants.button, new GUILayoutOption[0])) + { + this.DoShowDiff(false); + GUIUtility.ExitGUI(); + } + GUI.enabled = enabled; + GUILayout.FlexibleSpace(); + if (this.changesets.Length == 0) + { + GUI.enabled = false; + } + if (GUILayout.Button("Update", this.constants.bigButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + if (this.changesets.Length == 0) + { + Debug.Log("Nothing to update."); + } + else + { + this.DoUpdate(false); + } + this.parentWin.Repaint(); + GUIUtility.ExitGUI(); + } + if (this.changesets.Length == 0) + { + GUI.enabled = enabled; + } + GUILayout.EndHorizontal(); + if (AssetServer.GetAssetServerError() != string.Empty) + { + GUILayout.Space(10f); + GUILayout.Label(AssetServer.GetAssetServerError(), this.constants.errorLabel, new GUILayoutOption[0]); + GUILayout.Space(10f); + } + } + GUILayout.Space(10f); + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/AboutWindow.cs b/UnityEditor/UnityEditor/AboutWindow.cs new file mode 100644 index 00000000..4368d68c --- /dev/null +++ b/UnityEditor/UnityEditor/AboutWindow.cs @@ -0,0 +1,181 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AboutWindow : EditorWindow + { + private const string kSpecialThanksNames = "Thanks to Forest 'Yoggy' Johnson, Graham McAllister, David Janik-Jones, Raimund Schumacher, Alan J. Dickins and Emil 'Humus' Persson"; + private static GUIContent s_MonoLogo; + private static GUIContent s_AgeiaLogo; + private static GUIContent s_UnityLogo; + private static GUIContent s_Header; + private readonly string kCreditsNames = string.Join(", ", AboutWindowNames.names); + private float m_TextYPos = 120f; + private float m_TextInitialYPos = 120f; + private float m_TotalCreditsHeight = float.PositiveInfinity; + private double m_LastScrollUpdate; + private bool m_ShowDetailedVersion; + private int m_InternalCodeProgress; + private static void ShowAboutWindow() + { + AboutWindow windowWithRect = EditorWindow.GetWindowWithRect(new Rect(100f, 100f, 570f, 340f), true, "About Unity"); + windowWithRect.position = new Rect(100f, 100f, 570f, 340f); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + } + private static void LoadLogos() + { + if (AboutWindow.s_MonoLogo != null) + { + return; + } + AboutWindow.s_MonoLogo = EditorGUIUtility.IconContent("MonoLogo"); + AboutWindow.s_AgeiaLogo = EditorGUIUtility.IconContent("AgeiaLogo"); + AboutWindow.s_UnityLogo = EditorGUIUtility.IconContent("UnityLogo"); + AboutWindow.s_Header = EditorGUIUtility.IconContent("AboutWindow.MainHeader"); + } + public void OnEnable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.UpdateScroll)); + this.m_LastScrollUpdate = EditorApplication.timeSinceStartup; + } + public void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.UpdateScroll)); + } + public void UpdateScroll() + { + double num = EditorApplication.timeSinceStartup - this.m_LastScrollUpdate; + this.m_TextYPos -= 40f * (float)num; + if (this.m_TextYPos < -this.m_TotalCreditsHeight) + { + this.m_TextYPos = this.m_TextInitialYPos; + } + base.Repaint(); + this.m_LastScrollUpdate = EditorApplication.timeSinceStartup; + } + public void OnGUI() + { + AboutWindow.LoadLogos(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AboutWindow.s_UnityLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(AboutWindow.s_Header, GUIStyle.none, new GUILayoutOption[0]); + this.ListenForSecretCodes(); + this.m_ShowDetailedVersion |= Event.current.alt; + if (this.m_ShowDetailedVersion) + { + int unityVersionDate = InternalEditorUtility.GetUnityVersionDate(); + DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); + string unityBuildBranch = InternalEditorUtility.GetUnityBuildBranch(); + string text = string.Empty; + if (unityBuildBranch.Length > 0) + { + text = "Branch: " + unityBuildBranch; + } + EditorGUILayout.SelectableLabel(string.Concat(new string[] + { + "Version ", + InternalEditorUtility.GetFullUnityVersion(), + "\n", + string.Format("{0:r}", dateTime.AddSeconds((double)unityVersionDate)), + "\n", + text + }), new GUILayoutOption[] + { + GUILayout.Width(400f), + GUILayout.Height(42f) + }); + this.m_TextInitialYPos = 108f; + } + else + { + GUILayout.Label("Version " + Application.unityVersion, new GUILayoutOption[0]); + } + if (Event.current.type == EventType.ValidateCommand) + { + return; + } + GUILayout.Space(4f); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUI.BeginGroup(GUILayoutUtility.GetRect(10f, this.m_TextInitialYPos)); + float width = base.position.width - 10f; + float num = EditorStyles.wordWrappedLabel.CalcHeight(GUIContent.Temp(this.kCreditsNames), width); + Rect position = new Rect(5f, this.m_TextYPos, width, num); + GUI.Label(position, this.kCreditsNames, EditorStyles.wordWrappedLabel); + float num2 = EditorStyles.wordWrappedMiniLabel.CalcHeight(GUIContent.Temp("Thanks to Forest 'Yoggy' Johnson, Graham McAllister, David Janik-Jones, Raimund Schumacher, Alan J. Dickins and Emil 'Humus' Persson"), width); + Rect position2 = new Rect(5f, this.m_TextYPos + num, width, num2); + GUI.Label(position2, "Thanks to Forest 'Yoggy' Johnson, Graham McAllister, David Janik-Jones, Raimund Schumacher, Alan J. Dickins and Emil 'Humus' Persson", EditorStyles.wordWrappedMiniLabel); + GUI.EndGroup(); + this.m_TotalCreditsHeight = num + num2; + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(AboutWindow.s_MonoLogo, new GUILayoutOption[0]); + GUILayout.Label("Scripting powered by The Mono Project.\n\n(c) 2011 Novell, Inc.", "MiniLabel", new GUILayoutOption[] + { + GUILayout.Width(200f) + }); + GUILayout.Label(AboutWindow.s_AgeiaLogo, new GUILayoutOption[0]); + GUILayout.Label("Physics powered by PhysX.\n\n(c) 2011 NVIDIA Corporation.", "MiniLabel", new GUILayoutOption[] + { + GUILayout.Width(200f) + }); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label("\n" + InternalEditorUtility.GetUnityCopyright(), "MiniLabel", new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.Space(10f); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(InternalEditorUtility.GetLicenseInfo(), "AboutWindowLicenseLabel", new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + } + private void ListenForSecretCodes() + { + if (Event.current.type != EventType.KeyDown || Event.current.character == '\0') + { + return; + } + if (this.SecretCodeHasBeenTyped("internal", ref this.m_InternalCodeProgress)) + { + bool flag = !EditorPrefs.GetBool("InternalMode", false); + EditorPrefs.SetBool("InternalMode", flag); + base.ShowNotification(new GUIContent("Internal Mode " + ((!flag) ? "Off" : "On"))); + InternalEditorUtility.RequestScriptReload(); + } + } + private bool SecretCodeHasBeenTyped(string code, ref int characterProgress) + { + if (characterProgress < 0 || characterProgress >= code.Length || code[characterProgress] != Event.current.character) + { + characterProgress = 0; + } + if (code[characterProgress] == Event.current.character) + { + characterProgress++; + if (characterProgress >= code.Length) + { + characterProgress = 0; + return true; + } + } + return false; + } + } +} diff --git a/UnityEditor/UnityEditor/AboutWindowNames.cs b/UnityEditor/UnityEditor/AboutWindowNames.cs new file mode 100644 index 00000000..357cc780 --- /dev/null +++ b/UnityEditor/UnityEditor/AboutWindowNames.cs @@ -0,0 +1,645 @@ +using System; +namespace UnityEditor +{ + internal static class AboutWindowNames + { + public static readonly string[] names = new string[] + { + "Adam Buckner", + "Adam Dials", + "Adam Gutterman", + "Adriano Carlos Verona", + "Agnieszka Loza", + "Akouvi Ahoomey", + "Aleksander Grigorenko", + "Aleksandr Dubinskiy", + "Alex Lian", + "Alex McCredie", + "Alex Mclean", + "Alex Thibodeau", + "Alex Tyrer", + "Alexander Brooke", + "Alexandra Mariner", + "Alexey Abramychev", + "Alexey Orlov", + "Alfonso Ortiz Palma Junco", + "Allen Foo", + "Amanda Rush", + "Amir Ebrahimi", + "Anders Jensen", + "Anders Peter Kierbye Johansen", + "Andre Gauthier", + "Andrea Kramm", + "Andreas Hansen", + "Andreia Gaita", + "Andrew Donnell", + "Andrew Innes", + "Andrew Kasbari", + "Andrew Tang", + "Andrey Shvets", + "Andrius Keidonas", + "Andrius Kuznecovas", + "Andy Brammall", + "Andy Keener", + "Andy Stark", + "Andy Touch", + "Angelo Ferro", + "Anitha Kathirvel", + "Ann Byrdal Michaelsen", + "Ante Ilic", + "Anthony Yakovlev", + "Antony Douglas", + "Antti Nieminen", + "Antti Tapaninen", + "Aras Pranckevičius", + "Artiom Koshelev", + "Arturo Nunez", + "Audrius Sabaliauskas", + "Aurimas Cernius", + "Aurimas Gasiulis", + "Aurore Dimopoulos", + "Aya Yoshizaki", + "Bas Smit", + "Beau Folsom", + "Bee Ling Chua", + "Ben Pitt", + "Ben Stoneman", + "Benjamin Quorning", + "Benoit Sevigny", + "Beomhee Kang", + "Bertrand Carton", + "Beth Thomas", + "Biran Mccoy", + "Bjørn Göttler", + "Bo S. Mortensen", + "Bobby Billingsley", + "Bobo Bo", + "Boram Kim", + "Brad Robel-Forrest", + "Brett Bibby", + "Brett Seyler", + "Brian Christian Richardt", + "Brian E. Wilson", + "Brian Gershon", + "Brian Hu", + "Caitlyn Meeks", + "Carl Callewaert", + "Catherine Proulx", + "Cathy Yates", + "Cecilie Mosfeldt", + "Charles Hinshaw", + "Charlotte Kaas Larsen", + "Chethan Ramachandran", + "Chida Chaemchaeng", + "Chongho Byun", + "Chris Figueroa", + "Chris Migleo", + "Christian Bell Bastlund", + "Christophe Riccio", + "Christophe Souchard", + "Christopher Gonzales", + "Christopher Owen Hamilton", + "Christopher Pope", + "Christopher Roblee", + "Chuan Xin Lim", + "Claude Comeau", + "Claus Petersen", + "Corey Johnson", + "Craig Matthew Blum", + "Damien Colin Simper", + "Dan Adams", + "Dana Greene", + "Dana Ramnarine", + "Daniel Bratcher", + "Daniel Collin", + "Daniel Dyer", + "Daniel Hobley", + "Daniel Tan", + "Darren Williams", + "Dave Hampson", + "Dave Shorter", + "Davey Jackson", + "David Berger", + "David Berkan", + "David Della Rocca", + "David Geoffroy", + "David Hampson", + "David Helgason", + "David Liew", + "David Llewelyn", + "David Oh", + "David Rogers", + "David Takahashi", + "Denis Simuntis", + "Dennis DeRyke", + "Dmitriy Mindra", + "Dmitry Onishchenko", + "Dmitry Shtainer", + "Dominic Laflamme", + "Domiykas Kiauleikis", + "Donaira Tamulynaitė", + "Dorthe Hietala", + "Dzmitry Roznouski", + "Edward Blais", + "Edward Epstein", + "Edward Yablonsky", + "Ekaterina Kalygina", + "Elena Savinova", + "Elizabeth Rankich", + "Ellen Liew", + "Elliot Solomon", + "Elly Ahn", + "Elmir Jagudin", + "Elvira Brodovska", + "Elvis Alistar", + "Emil Johansen", + "Emilliza Gutierrez", + "Emily Emanuel", + "Emma Butler", + "Emmanuel Horckmanns", + "Eric Hwang", + "Erik Hemming", + "Erik Juhl", + "Erin Baker", + "Erland Körner", + "Esben Ask Meincke", + "Ethan Vosburgh", + "Evan Spytma", + "Evon Siok Yee Low", + "Ezra Nuite", + "Fini Faria Alring", + "Florian Penzkofer", + "Francis Lauzon Duranceau", + "Frank Jonsson", + "Fredrik von Renteln", + "Freyr Helgason", + "Gabriele Farina", + "Gediminas Petrikas", + "Graham Dunnett", + "Graham Laverty", + "Graham Reeves", + "Gukhwan Ji", + "Hanna Yi", + "Harry Chng", + "Heidi Therkildsen", + "Heikki Sandstrom", + "Heikki Tunkelo", + "Heine Meineche Fusager", + "Helen Vergel de Dios", + "Helene Prevost Jensen", + "Henrik Nielsen", + "Hindu Buddharaju", + "Hiroki Omae", + "HoMin Lee", + "Hugh Longworth", + "Hui Xiumo", + "Hwan-hee Kim", + "Hólmfríður Eygló Arndal Gunnarsdóttir", + "Iain Stevens-Guille", + "Ian Davids", + "Ian Dundore", + "Ian Dunlap", + "Ieva Ramanauskaite", + "Ignas Ziberkas", + "Igor Fil", + "Igor Kozyrenko", + "Ilya Komendantov", + "Ilya Turshatov", + "Isabelle Jacquinot", + "Jaakko Lukkari", + "Jack Kieran Paine", + "Jaehyun Kang", + "Jakob Hunsballe", + "Jalmari Raippalinna", + "James Bouckley", + "James Cho", + "James Kim", + "Jan Marguc", + "Janet Qiu", + "Janne Alanen", + "Janne Nikula", + "Jarkko Rajamaki", + "Jarko Vihriala", + "Jason Chen", + "Jason Parks", + "Jay Clei Garcia dos Santos", + "Jean Christophe Cimetiere", + "Jeanne Dieu", + "Jed Ritchey", + "Jeff Aydelotte", + "Jeff Hemenway", + "Jenny Lim", + "Jens Andersen", + "Jens Fursund", + "Jeremy Martin", + "Jesper Mortensen", + "Jessica Qian", + "Jessika Jackson", + "Jiaqing Wang", + "Jiawei Ma", + "Jinho Mang", + "Jinjeong Lee", + "Jinn Kim", + "Jiwon Yu", + "Jiyuan Liao", + "Jo Ryall", + "Joachim Ante", + "Joana Koyte", + "JoAnna Matthisen", + "Jocelyn Cai", + "Joe Robins", + "Joe Santos", + "Joel Packer", + "Joen Joensen", + "Johana Riquier", + "Johaness Reuben Jozni Bin Ahmad Zaini", + "Johannes Linke", + "John Cheng", + "John Edgar Congote Calle", + "John Fallon", + "John Goodale", + "Jonas Christian Drewsen", + "Jonas Echterhoff", + "Jonas Meyer", + "Jonas Törnquist", + "Jonas Minnberg", + "Jonas Uosis", + "Jonathan Chambers", + "Jonathan Oster Dano", + "Jookyung Hyun", + "Joonsoo Ryu", + "Joseph Walters", + "Josh Naylor", + "Joshua Peterson", + "Juan Sebastian Muñoz", + "Juha Kiili", + "Juho Makinen", + "Juho Oravainen", + "Jukka Arvo", + "Julia Balashova", + "Julie Eickhof", + "Julie Fu Chen Yap", + "Julius Miknevičius", + "Julius Trinkunas", + "Jung mi Kim", + "Junghwa (Elisa) Choi", + "Jussi Laakkonen", + "Jussi Venho", + "Justin Kruger", + "Justinas Daugmaudis", + "Kamio Chambless", + "Karen Booth", + "Karen Gold", + "Karen Riskær Jørgensen", + "Karolis Norkunas", + "Karsten Nielsen", + "Kaspar Daugaard", + "Kasper Amstrup Andersen", + "Kasper Storm Engelstoft", + "Katherine Overmeyer", + "Katrine Hegnsborg Bruun", + "Kazimieras Semaška", + "Keigo Ando", + "Keijiro Takahashi", + "Keli Hlöðversson", + "Kelly Sandvig", + "Kelvin Lo", + "Kent Buenaventura", + "Kevin Ashman", + "Kevin Robertson", + "Kia Skouw Christensen", + "Kiersten Petesch", + "Kim Moon-soo", + "Kim Steen Riber", + "Kimberly Villaron", + "Kimberly Bailey", + "Kimberly Verde", + "Kimi Wang", + "Kirsten Duvall", + "Kirsten Marie Brochorst Gronborg", + "Kjartan Olafsson", + "Kornel Mikes", + "Kristian Mandrup", + "Kristian Mork", + "Kristjan B. Halfdanarson", + "Kristyna Paskova", + "Kuba Cupisz", + "Lars \"Kroll\" Kristensen", + "Lars Mølgård Nielsen", + "Lars Runov", + "Lasse Järvensivu", + "Lasse Makholm", + "Leena Kuitunen", + "Leena Viitanen", + "Leo Yaik Shiin Paan", + "Leon Jun", + "Leonardo Carneiro", + "Levi Bard", + "Li Jiajia", + "Liang Zhao", + "Liming Zhang", + "Loreta Dilnike", + "Louise Skaarup", + "Luc Vo Van", + "Lucas Meijer", + "Lukas Dapkus", + "Lukasz Paczkowski", + "Lárus Ólafsson", + "Madelaine Fouts", + "Mads Kiilerich", + "Mads Kjellerup", + "Mads Nyholm", + "Maj-Brit Jo Arnested", + "Makoto Itoh", + "Makoto Sugano", + "Mantas Puida", + "Marc Cinq Mars", + "Marc Eric Quesnel", + "Marco Alvarado", + "Marco Trivellato", + "Marcus Lim", + "Marek Turski", + "Maria Marcano", + "Marina Øster", + "Marius Raustys", + "Mark Choi", + "Mark Harkness", + "Mark Schoennagel", + "Mark T. Morrison", + "Markus Lorenz Wiedemann", + "Martin Gjaldbæk", + "Martin Nielsen", + "Martin Sternevald", + "Martin Stjernholk Vium", + "Martin Troels Eberhardt", + "Marvin Kharrazi", + "Massimiliano Mantione", + "Massimo Caterino", + "Mathieu Muller", + "Matt Reynolds", + "Matthew Fini", + "Matti Savolainen", + "Melvin Chay", + "Melvyn May", + "Michael Birk", + "Michael Edmonds", + "Michael Herring", + "Michael Krarup Nielsen", + "Michael Lyashenko", + "Mickey Maher", + "Mika Kuusisto", + "Mika Patiala", + "Mike Geig", + "Mikkel \"Frecle\" Fredborg", + "Mikko Lehtinen", + "Mikko Mononen", + "Mikko Strandborg", + "Mindaugas Steponavičius", + "Minsu Andrew Park", + "Mira Cho", + "Mircea Marghidanu", + "Monika Madrid", + "Morrissey Williams", + "Morten Abildgaard", + "Morten Sommer", + "Na'Tosha Bard", + "Natalia Sviridova", + "Natasha Marin O'Brien", + "Nathan Hanners", + "Navin Kumar Chaudhary", + "Nevin Eronde", + "Ngak Koon Lee", + "Ngozi Watts", + "Nicholas Francis", + "Nick Jovic", + "Nicky Ahn", + "Nicola Evans", + "Nicolaj Schweitz", + "Nikkolai Davenport", + "Nikolay Trusov", + "Nikoline Simone Sonja Hogh", + "Nobuyuki Kobayashi", + "Ole Ciliox", + "Oleg Pridiuk", + "Oleksiy Yakovenko", + "Olexiy Zakharov", + "Olly Nicholson", + "Oren Tversky", + "Oscar Pett", + "Palaniyandi Jawahar", + "Patrick Bell", + "Patrick Curry", + "Patrick Williamson", + "Paul Dunning", + "Paul Tham", + "Pauli Ojanen", + "Paulius Liekis", + "Paulius Puodziunas", + "Peden Fitzhugh", + "Peijun Zhu", + "Pekka Aakko", + "Pekka Palmu", + "Pengfei Zhang", + "Pernille Hansen", + "Peter Ejby Dahl Jensen", + "Peter Kuhn", + "Peter Lee", + "Peter Long", + "Pete Moss", + "Peter Schmitz", + "Petri Nordlund", + "Phil McJunkins", + "Philip Cosgrave", + "Philippe Jean", + "Phil McJunkins", + "Pierre Paul Giroux", + "Pietro De Nicola", + "Povilas Kanapickas", + "Povilas Staskus", + "Pyry Haulos", + "Qiang Zhang", + "Qing Feng", + "Ralph Hauwert", + "Randy Spong", + "Rasmus \"Razu\" Boserup", + "Rasmus Møller Selsmark", + "Rebekah Tay Xiao Ping", + "Reina Shah", + "Renaldas \"ReJ\" Zioma", + "René Damm", + "Ricardo Arango", + "Rich Skorski", + "Richard Sykes", + "Rickard Andersson", + "Rita Turkowski", + "Roald Høyer-Hansen", + "Rob Fairchild", + "Robert Brackenridge", + "Robert Cassidy", + "Robert Cupisz", + "Robert Lanciault", + "Robert Oates", + "Rodrigo B. de Oliveira", + "Rodrigo Lopez-carrillo", + "Rolandas Cinevskis", + "Rolf Peter Ingemar Holst", + "Roman Glushchenko", + "Roman Menyakin", + "Ronnie (Seyoon) Jang", + "Rune Skovbo Johansen", + "Ruslan Grigoryev", + "Rustum bin Dzil Qamar", + "Ryan Hintze", + "Ryan N. Burke", + "Rytis Bieliūnas", + "Sakari Pitkänen", + "Salley Chan", + "Sam Bickley", + "Samantha Kalman", + "Sampsa Jaatinen", + "Sanjay Mistry", + "Sara Cannon", + "Sara Wallman", + "Scott Bilas", + "Scott Flynn", + "Sean Baggaley", + "Sean Riley", + "Segrel Koskentausta", + "Seiya Ishibashi", + "Sergej Kravcenko", + "Sergey Dankevich", + "Sergii Tsegelnyk", + "Sergio Gómez", + "Shanti Zachariah", + "Shaun Hewitt", + "Shawn White", + "Shiin Paan Leo Yaik", + "Shin Hyung Park", + "Shinobu Toyoda", + "Shirlynn Lee", + "Sho Someya", + "Shouguan Lin", + "Siew Hong Joyce Law", + "Silvia Rasheva", + "Silviu Ionescu", + "Simon Holm Nielsen", + "Sin Jin Chia", + "Skjalm Arrøe", + "Sonny Myette", + "Steen Lund", + "Stefan Sandberg", + "Stefan Schubert", + "Steffen Toksvig", + "Sten Selander", + "Stephanie Chen", + "Stephanie Hurlburt", + "Stephen Dunning", + "Stephen Palmer", + "Steven Mcknight", + "Stine Munkesø Kjærbøll", + "Stuart Merry", + "Suhail Dutta", + "Susan Anderson", + "Surath Chatterji", + "Susan Zurilgen", + "Søren Christiansen", + "Takashi Jona", + "Takashi Nayuki", + "Tao Wang", + "Tatsuhiko Yamamura", + "Tautvydas Žilys", + "Tec Liu", + "Tero Heino", + "Terry Hendrix II", + "Thomas Bentzen", + "Thomas Cho", + "Thomas Fejerskov Klindt", + "Thomas Golzen", + "Thomas Grové", + "Thomas Hagen Johansen", + "Thomas Harkjær Petersen", + "Thomas Klindt", + "Thomas Kristiansen", + "Thomas Svaerke", + "Tiantao Wu", + "Tibor Hencz", + "Tim Cannell", + "Tim Kang", + "Timo Vehvilainen", + "Timothy Cooper", + "Todd Carr", + "Todd Hooper", + "Todd Rutherford", + "Tom Eklof", + "Tom Higgins", + "Tomas Dirvanauskas", + "Tomas Jakubauskas", + "Tomasz Paszek", + "Tom Eklof", + "Tony Garcia", + "Tony Sun", + "Torben Jeppesen", + "Toshiyuki Mori", + "Tracy Erickson", + "Tricia Gray", + "Tuomas Peronvuo", + "Tuomas Rinta", + "Tze Bun Ng", + "Ugnius Dovidauskas", + "Ursula Beck", + "Vadim Kuzmenko", + "Valdemar Bučilko", + "Valentin Simonov", + "Valerie Cisco", + "Veli-Pekka Kokkonen", + "Venkatesh Subramaniam Pillai", + "Veselin Efremov", + "Vibe Herlitschek", + "Vicky Zhang", + "Victor Suhak", + "Vijay Michael Joseph", + "Vilius Prakapas", + "Ville Orkas", + "Ville Vaten", + "Ville Vihma", + "Vilmantas Balasevičius", + "Vincent Zhang", + "Viraf Zack", + "Vitaly Veligursky", + "Vlatko Duvnjak", + "Vytautas Šaltenis", + "Ward Vuillemot", + "Wayne Johnson", + "Wendy Tan", + "Weronika Węglińska", + "Will Corwin", + "Will Goldstone", + "William Hugo Yang", + "William Nilsson", + "Xavier Bougouin", + "Xiangyu Deng", + "Xiao Ling Yao", + "Xin Zhang", + "Yan Drugalya", + "Yasuyuki Kamata", + "Yelena Danziger", + "Yohei Tanaka", + "Yohei Yanase", + "Yoo Kyoung Lee", + "Young ho Lee", + "Younghee Cho", + "Youngho Hahm", + "Yuan Kuan Seng", + "Yuanxing Cai", + "Yue Liu", + "Yukimi Shimura", + "Yunkyu Choi", + "Yury Habets", + "Yusuke Ebata", + "Zachary Zadell", + "Zbignev Monkevic", + "Zhenping Guo", + "Zhonglei Yang" + }; + } +} diff --git a/UnityEditor/UnityEditor/ActiveEditorTracker.cs b/UnityEditor/UnityEditor/ActiveEditorTracker.cs new file mode 100644 index 00000000..39f84b5a --- /dev/null +++ b/UnityEditor/UnityEditor/ActiveEditorTracker.cs @@ -0,0 +1,108 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + public sealed class ActiveEditorTracker + { + private MonoReloadableIntPtrClear m_Property; + public extern Editor[] activeEditors + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isDirty + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isLocked + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern InspectorMode inspectorMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasComponentsWhichCannotBeMultiEdited + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static ActiveEditorTracker sharedTracker + { + get + { + ActiveEditorTracker activeEditorTracker = new ActiveEditorTracker(); + ActiveEditorTracker.SetupSharedTracker(activeEditorTracker); + return activeEditorTracker; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ActiveEditorTracker(); + public override bool Equals(object o) + { + ActiveEditorTracker activeEditorTracker = o as ActiveEditorTracker; + return this.m_Property.m_IntPtr == activeEditorTracker.m_Property.m_IntPtr; + } + public override int GetHashCode() + { + return this.m_Property.m_IntPtr.GetHashCode(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Dispose(); + ~ActiveEditorTracker() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Destroy(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetVisible(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetVisible(int index, int visible); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearDirty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RebuildIfNecessary(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ForceRebuild(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void VerifyModifiedMonoBehaviours(); + [Obsolete("Use Editor.CreateEditor instead")] + public static Editor MakeCustomEditor(UnityEngine.Object obj) + { + return Editor.CreateEditor(obj); + } + public static bool HasCustomEditor(UnityEngine.Object obj) + { + return CustomEditorAttributes.FindCustomEditorType(obj, false) != null; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetupSharedTracker(ActiveEditorTracker sharedTracker); + } +} diff --git a/UnityEditor/UnityEditor/AddComponentWindow.cs b/UnityEditor/UnityEditor/AddComponentWindow.cs new file mode 100644 index 00000000..7a73a54d --- /dev/null +++ b/UnityEditor/UnityEditor/AddComponentWindow.cs @@ -0,0 +1,849 @@ +using System; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [InitializeOnLoad] + internal class AddComponentWindow : EditorWindow + { + internal enum Language + { + JavaScript, + CSharp, + Boo + } + private class Element : IComparable + { + public int level; + public GUIContent content; + public string name + { + get + { + return this.content.text; + } + } + public int CompareTo(object o) + { + return this.name.CompareTo((o as AddComponentWindow.Element).name); + } + } + private class ComponentElement : AddComponentWindow.Element + { + public string typeName; + public string menuPath; + public ComponentElement(int level, string name, string menuPath, string commandString) + { + this.level = level; + this.typeName = name.Replace(" ", string.Empty); + this.menuPath = menuPath; + if (commandString.StartsWith("SCRIPT")) + { + int instanceID = int.Parse(commandString.Substring(6)); + UnityEngine.Object obj = EditorUtility.InstanceIDToObject(instanceID); + Texture miniThumbnail = AssetPreview.GetMiniThumbnail(obj); + this.content = new GUIContent(name, miniThumbnail); + } + else + { + int classID = int.Parse(commandString); + this.content = new GUIContent(name, AssetPreview.GetMiniTypeThumbnailFromClassID(classID)); + } + } + } + [Serializable] + private class GroupElement : AddComponentWindow.Element + { + public Vector2 scroll; + public int selectedIndex; + public GroupElement(int level, string name) + { + this.level = level; + this.content = new GUIContent(name); + } + } + private class NewScriptElement : AddComponentWindow.GroupElement + { + private const string kResourcesTemplatePath = "Resources/ScriptTemplates"; + private char[] kInvalidPathChars = new char[] + { + '<', + '>', + ':', + '"', + '|', + '?', + '*', + '\0' + }; + private char[] kPathSepChars = new char[] + { + '/', + '\\' + }; + private string m_Directory = string.Empty; + private string extension + { + get + { + switch (AddComponentWindow.s_Lang) + { + case AddComponentWindow.Language.JavaScript: + return "js"; + case AddComponentWindow.Language.CSharp: + return "cs"; + case AddComponentWindow.Language.Boo: + return "boo"; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + private string templatePath + { + get + { + string path = Path.Combine(EditorApplication.applicationContentsPath, "Resources/ScriptTemplates"); + switch (AddComponentWindow.s_Lang) + { + case AddComponentWindow.Language.JavaScript: + return Path.Combine(path, "80-Javascript-NewBehaviourScript.js.txt"); + case AddComponentWindow.Language.CSharp: + return Path.Combine(path, "81-C# Script-NewBehaviourScript.cs.txt"); + case AddComponentWindow.Language.Boo: + return Path.Combine(path, "82-Boo Script-NewBehaviourScript.boo.txt"); + default: + throw new ArgumentOutOfRangeException(); + } + } + } + public NewScriptElement() : base(1, "New Script") + { + } + public void OnGUI() + { + GUILayout.Label("Name", EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.FocusTextInControl("NewScriptName"); + GUI.SetNextControlName("NewScriptName"); + AddComponentWindow.className = EditorGUILayout.TextField(AddComponentWindow.className, new GUILayoutOption[0]); + EditorGUILayout.Space(); + AddComponentWindow.Language language = (AddComponentWindow.Language)EditorGUILayout.EnumPopup("Language", AddComponentWindow.s_Lang, new GUILayoutOption[0]); + if (language != AddComponentWindow.s_Lang) + { + AddComponentWindow.s_Lang = language; + EditorPrefs.SetInt("NewScriptLanguage", (int)language); + } + EditorGUILayout.Space(); + bool flag = this.CanCreate(); + if (!flag && AddComponentWindow.className != string.Empty) + { + GUILayout.Label(this.GetError(), EditorStyles.helpBox, new GUILayoutOption[0]); + } + GUILayout.FlexibleSpace(); + EditorGUI.BeginDisabledGroup(!flag); + if (GUILayout.Button("Create and Add", new GUILayoutOption[0])) + { + this.Create(); + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.Space(); + } + public bool CanCreate() + { + return AddComponentWindow.className.Length > 0 && !File.Exists(this.TargetPath()) && !this.ClassAlreadyExists() && !this.ClassNameIsInvalid() && !this.InvalidTargetPath(); + } + private string GetError() + { + string result = string.Empty; + if (AddComponentWindow.className != string.Empty) + { + if (File.Exists(this.TargetPath())) + { + result = "A script called \"" + AddComponentWindow.className + "\" already exists at that path."; + } + else + { + if (this.ClassAlreadyExists()) + { + result = "A class called \"" + AddComponentWindow.className + "\" already exists."; + } + else + { + if (this.ClassNameIsInvalid()) + { + result = "The script name may only consist of a-z, A-Z, 0-9, _."; + } + else + { + if (this.InvalidTargetPath()) + { + result = "The folder path contains invalid characters."; + } + } + } + } + } + return result; + } + public void Create() + { + if (!this.CanCreate()) + { + return; + } + this.CreateScript(); + GameObject[] gameObjects = AddComponentWindow.gameObjects; + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject gameObject = gameObjects[i]; + MonoScript monoScript = AssetDatabase.LoadAssetAtPath(this.TargetPath(), typeof(MonoScript)) as MonoScript; + monoScript.SetScriptTypeWasJustCreatedFromComponentMenu(); + InternalEditorUtility.AddScriptComponentUnchecked(gameObject, monoScript); + } + AddComponentWindow.s_AddComponentWindow.Close(); + } + private bool InvalidTargetPath() + { + return this.m_Directory.IndexOfAny(this.kInvalidPathChars) >= 0 || this.TargetDir().Split(this.kPathSepChars, StringSplitOptions.None).Contains(string.Empty); + } + public string TargetPath() + { + return Path.Combine(this.TargetDir(), AddComponentWindow.className + "." + this.extension); + } + private string TargetDir() + { + return Path.Combine("Assets", this.m_Directory.Trim(this.kPathSepChars)); + } + private bool ClassNameIsInvalid() + { + return !CodeGenerator.IsValidLanguageIndependentIdentifier(AddComponentWindow.className); + } + private bool ClassExists(string className) + { + return AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetType(className, false) != null); + } + private bool ClassAlreadyExists() + { + return !(AddComponentWindow.className == string.Empty) && this.ClassExists(AddComponentWindow.className); + } + private void CreateScript() + { + ProjectWindowUtil.CreateScriptAssetFromTemplate(this.TargetPath(), this.templatePath); + AssetDatabase.Refresh(); + } + } + private class Styles + { + public GUIStyle header = new GUIStyle(EditorStyles.inspectorBig); + public GUIStyle componentButton = new GUIStyle("PR Label"); + public GUIStyle groupButton; + public GUIStyle background = "grey_border"; + public GUIStyle previewBackground = "PopupCurveSwatchBackground"; + public GUIStyle previewHeader = new GUIStyle(EditorStyles.label); + public GUIStyle previewText = new GUIStyle(EditorStyles.wordWrappedLabel); + public GUIStyle rightArrow = "AC RightArrow"; + public GUIStyle leftArrow = "AC LeftArrow"; + public Styles() + { + this.header.font = EditorStyles.boldLabel.font; + this.componentButton.alignment = TextAnchor.MiddleLeft; + this.componentButton.padding.left -= 15; + this.componentButton.fixedHeight = 20f; + this.groupButton = new GUIStyle(this.componentButton); + this.groupButton.padding.left += 17; + this.previewText.padding.left += 3; + this.previewText.padding.right += 3; + this.previewHeader.padding.left++; + this.previewHeader.padding.right += 3; + this.previewHeader.padding.top += 3; + this.previewHeader.padding.bottom += 2; + } + } + private const int kHeaderHeight = 30; + private const int kWindowHeight = 320; + private const int kHelpHeight = 0; + private const string kLanguageEditorPrefName = "NewScriptLanguage"; + private const string kComponentSearch = "ComponentSearchString"; + private const string kSearchHeader = "Search"; + private static AddComponentWindow.Styles s_Styles; + private static AddComponentWindow s_AddComponentWindow; + private static long s_LastClosedTime; + internal static AddComponentWindow.Language s_Lang; + private static bool s_DirtyList; + private string m_ClassName = string.Empty; + private GameObject[] m_GameObjects; + private AddComponentWindow.Element[] m_Tree; + private AddComponentWindow.Element[] m_SearchResultTree; + private List m_Stack = new List(); + private float m_Anim = 1f; + private int m_AnimTarget = 1; + private long m_LastTime; + private bool m_ScrollToSelected; + private string m_Search = string.Empty; + internal static string className + { + get + { + return AddComponentWindow.s_AddComponentWindow.m_ClassName; + } + set + { + AddComponentWindow.s_AddComponentWindow.m_ClassName = value; + } + } + internal static GameObject[] gameObjects + { + get + { + return AddComponentWindow.s_AddComponentWindow.m_GameObjects; + } + } + private bool hasSearch + { + get + { + return !string.IsNullOrEmpty(this.m_Search); + } + } + private AddComponentWindow.GroupElement activeParent + { + get + { + return this.m_Stack[this.m_Stack.Count - 2 + this.m_AnimTarget]; + } + } + private AddComponentWindow.Element[] activeTree + { + get + { + return (!this.hasSearch) ? this.m_Tree : this.m_SearchResultTree; + } + } + private AddComponentWindow.Element activeElement + { + get + { + if (this.activeTree == null) + { + return null; + } + List children = this.GetChildren(this.activeTree, this.activeParent); + if (children.Count == 0) + { + return null; + } + return children[this.activeParent.selectedIndex]; + } + } + static AddComponentWindow() + { + AddComponentWindow.s_DirtyList = true; + } + private void OnEnable() + { + AddComponentWindow.s_AddComponentWindow = this; + AddComponentWindow.s_Lang = (AddComponentWindow.Language)EditorPrefs.GetInt("NewScriptLanguage", 1); + this.m_Search = EditorPrefs.GetString("ComponentSearchString", string.Empty); + } + private void OnDisable() + { + AddComponentWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + AddComponentWindow.s_AddComponentWindow = null; + } + private static InspectorWindow FirstInspectorWithGameObject() + { + foreach (InspectorWindow current in InspectorWindow.GetInspectors()) + { + if (current.GetInspectedObject() is GameObject) + { + return current; + } + } + return null; + } + internal static bool ValidateAddComponentMenuItem() + { + return AddComponentWindow.FirstInspectorWithGameObject() != null; + } + internal static void ExecuteAddComponentMenuItem() + { + InspectorWindow inspectorWindow = AddComponentWindow.FirstInspectorWithGameObject(); + if (inspectorWindow != null) + { + inspectorWindow.SendEvent(EditorGUIUtility.CommandEvent("OpenAddComponentDropdown")); + } + } + internal static bool Show(Rect rect, GameObject[] gos) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AddComponentWindow)); + if (array.Length > 0) + { + ((EditorWindow)array[0]).Close(); + return false; + } + long num = DateTime.Now.Ticks / 10000L; + if (num >= AddComponentWindow.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (AddComponentWindow.s_AddComponentWindow == null) + { + AddComponentWindow.s_AddComponentWindow = ScriptableObject.CreateInstance(); + } + AddComponentWindow.s_AddComponentWindow.Init(rect); + AddComponentWindow.s_AddComponentWindow.m_GameObjects = gos; + return true; + } + return false; + } + private void Init(Rect buttonRect) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + this.CreateComponentTree(); + base.ShowAsDropDown(buttonRect, new Vector2(buttonRect.width, 320f)); + base.Focus(); + this.m_Parent.AddToAuxWindowList(); + base.wantsMouseMove = true; + } + private void CreateComponentTree() + { + string[] submenus = Unsupported.GetSubmenus("Component"); + string[] submenusCommands = Unsupported.GetSubmenusCommands("Component"); + List list = new List(); + List list2 = new List(); + for (int i = 0; i < submenus.Length; i++) + { + if (!(submenusCommands[i] == "ADD")) + { + string text = submenus[i]; + string[] array = text.Split(new char[] + { + '/' + }); + while (array.Length - 1 < list.Count) + { + list.RemoveAt(list.Count - 1); + } + while (list.Count > 0 && array[list.Count - 1] != list[list.Count - 1]) + { + list.RemoveAt(list.Count - 1); + } + while (array.Length - 1 > list.Count) + { + list2.Add(new AddComponentWindow.GroupElement(list.Count, array[list.Count])); + list.Add(array[list.Count]); + } + list2.Add(new AddComponentWindow.ComponentElement(list.Count, array[array.Length - 1], text, submenusCommands[i])); + } + } + list2.Add(new AddComponentWindow.NewScriptElement()); + this.m_Tree = list2.ToArray(); + if (this.m_Stack.Count == 0) + { + this.m_Stack.Add(this.m_Tree[0] as AddComponentWindow.GroupElement); + } + else + { + AddComponentWindow.GroupElement groupElement = this.m_Tree[0] as AddComponentWindow.GroupElement; + int level = 0; + while (true) + { + AddComponentWindow.GroupElement groupElement2 = this.m_Stack[level]; + this.m_Stack[level] = groupElement; + this.m_Stack[level].selectedIndex = groupElement2.selectedIndex; + this.m_Stack[level].scroll = groupElement2.scroll; + level++; + if (level == this.m_Stack.Count) + { + break; + } + List children = this.GetChildren(this.activeTree, groupElement); + AddComponentWindow.Element element = children.FirstOrDefault((AddComponentWindow.Element c) => c.name == this.m_Stack[level].name); + if (element != null && element is AddComponentWindow.GroupElement) + { + groupElement = (element as AddComponentWindow.GroupElement); + } + else + { + while (this.m_Stack.Count > level) + { + this.m_Stack.RemoveAt(level); + } + } + } + } + AddComponentWindow.s_DirtyList = false; + this.RebuildSearch(); + } + internal void OnGUI() + { + if (AddComponentWindow.s_Styles == null) + { + AddComponentWindow.s_Styles = new AddComponentWindow.Styles(); + } + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, AddComponentWindow.s_Styles.background); + if (AddComponentWindow.s_DirtyList) + { + this.CreateComponentTree(); + } + this.HandleKeyboard(); + GUILayout.Space(7f); + if (!(this.activeParent is AddComponentWindow.NewScriptElement)) + { + EditorGUI.FocusTextInControl("ComponentSearch"); + } + Rect rect = GUILayoutUtility.GetRect(10f, 20f); + rect.x += 8f; + rect.width -= 16f; + GUI.SetNextControlName("ComponentSearch"); + EditorGUI.BeginDisabledGroup(this.activeParent is AddComponentWindow.NewScriptElement); + string text = EditorGUI.SearchField(rect, this.m_Search); + EditorGUI.EndDisabledGroup(); + if (text != this.m_Search) + { + this.m_Search = text; + EditorPrefs.SetString("ComponentSearchString", this.m_Search); + this.RebuildSearch(); + } + this.ListGUI(this.activeTree, this.m_Anim, this.GetElementRelative(0), this.GetElementRelative(-1)); + if (this.m_Anim < 1f) + { + this.ListGUI(this.activeTree, this.m_Anim + 1f, this.GetElementRelative(-1), this.GetElementRelative(-2)); + } + if (this.m_Anim != (float)this.m_AnimTarget && Event.current.type == EventType.Repaint) + { + long ticks = DateTime.Now.Ticks; + float num = (float)(ticks - this.m_LastTime) / 1E+07f; + this.m_LastTime = ticks; + this.m_Anim = Mathf.MoveTowards(this.m_Anim, (float)this.m_AnimTarget, num * 4f); + if (this.m_AnimTarget == 0 && this.m_Anim == 0f) + { + this.m_Anim = 1f; + this.m_AnimTarget = 1; + this.m_Stack.RemoveAt(this.m_Stack.Count - 1); + } + base.Repaint(); + } + } + private void HandleKeyboard() + { + Event current = Event.current; + if (current.type == EventType.KeyDown) + { + if (this.activeParent is AddComponentWindow.NewScriptElement) + { + if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) + { + (this.activeParent as AddComponentWindow.NewScriptElement).Create(); + current.Use(); + GUIUtility.ExitGUI(); + } + if (current.keyCode == KeyCode.Escape) + { + this.GoToParent(); + current.Use(); + } + } + else + { + if (current.keyCode == KeyCode.DownArrow) + { + this.activeParent.selectedIndex++; + this.activeParent.selectedIndex = Mathf.Min(this.activeParent.selectedIndex, this.GetChildren(this.activeTree, this.activeParent).Count - 1); + this.m_ScrollToSelected = true; + current.Use(); + } + if (current.keyCode == KeyCode.UpArrow) + { + this.activeParent.selectedIndex--; + this.activeParent.selectedIndex = Mathf.Max(this.activeParent.selectedIndex, 0); + this.m_ScrollToSelected = true; + current.Use(); + } + if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) + { + this.GoToChild(this.activeElement, true); + current.Use(); + } + if (!this.hasSearch) + { + if (current.keyCode == KeyCode.LeftArrow || current.keyCode == KeyCode.Backspace) + { + this.GoToParent(); + current.Use(); + } + if (current.keyCode == KeyCode.RightArrow) + { + this.GoToChild(this.activeElement, false); + current.Use(); + } + if (current.keyCode == KeyCode.Escape) + { + base.Close(); + current.Use(); + } + } + } + } + } + private void RebuildSearch() + { + if (!this.hasSearch) + { + this.m_SearchResultTree = null; + if (this.m_Stack[this.m_Stack.Count - 1].name == "Search") + { + this.m_Stack.Clear(); + this.m_Stack.Add(this.m_Tree[0] as AddComponentWindow.GroupElement); + } + this.m_AnimTarget = 1; + this.m_LastTime = DateTime.Now.Ticks; + this.m_ClassName = "NewBehaviourScript"; + return; + } + this.m_ClassName = this.m_Search; + string[] array = this.m_Search.ToLower().Split(new char[] + { + ' ' + }); + List list = new List(); + List list2 = new List(); + AddComponentWindow.Element[] tree = this.m_Tree; + for (int i = 0; i < tree.Length; i++) + { + AddComponentWindow.Element element = tree[i]; + if (element is AddComponentWindow.ComponentElement) + { + string text = element.name.ToLower().Replace(" ", string.Empty); + bool flag = true; + bool flag2 = false; + for (int j = 0; j < array.Length; j++) + { + string value = array[j]; + if (!text.Contains(value)) + { + flag = false; + break; + } + if (j == 0 && text.StartsWith(value)) + { + flag2 = true; + } + } + if (flag) + { + if (flag2) + { + list.Add(element); + } + else + { + list2.Add(element); + } + } + } + } + list.Sort(); + list2.Sort(); + List list3 = new List(); + list3.Add(new AddComponentWindow.GroupElement(0, "Search")); + list3.AddRange(list); + list3.AddRange(list2); + list3.Add(this.m_Tree[this.m_Tree.Length - 1]); + this.m_SearchResultTree = list3.ToArray(); + this.m_Stack.Clear(); + this.m_Stack.Add(this.m_SearchResultTree[0] as AddComponentWindow.GroupElement); + if (this.GetChildren(this.activeTree, this.activeParent).Count >= 1) + { + this.activeParent.selectedIndex = 0; + } + else + { + this.activeParent.selectedIndex = -1; + } + } + private AddComponentWindow.GroupElement GetElementRelative(int rel) + { + int num = this.m_Stack.Count + rel - 1; + if (num < 0) + { + return null; + } + return this.m_Stack[num]; + } + private void GoToParent() + { + if (this.m_Stack.Count > 1) + { + this.m_AnimTarget = 0; + this.m_LastTime = DateTime.Now.Ticks; + } + } + private void GoToChild(AddComponentWindow.Element e, bool addIfComponent) + { + if (e is AddComponentWindow.NewScriptElement && !this.hasSearch) + { + this.m_ClassName = AssetDatabase.GenerateUniqueAssetPath((e as AddComponentWindow.NewScriptElement).TargetPath()); + this.m_ClassName = Path.GetFileNameWithoutExtension(this.m_ClassName); + } + if (e is AddComponentWindow.ComponentElement) + { + if (addIfComponent) + { + EditorApplication.ExecuteMenuItemOnGameObjects(((AddComponentWindow.ComponentElement)e).menuPath, this.m_GameObjects); + base.Close(); + } + } + else + { + if (!this.hasSearch || e is AddComponentWindow.NewScriptElement) + { + this.m_LastTime = DateTime.Now.Ticks; + if (this.m_AnimTarget == 0) + { + this.m_AnimTarget = 1; + } + else + { + if (this.m_Anim == 1f) + { + this.m_Anim = 0f; + this.m_Stack.Add(e as AddComponentWindow.GroupElement); + } + } + } + } + } + private void ListGUI(AddComponentWindow.Element[] tree, float anim, AddComponentWindow.GroupElement parent, AddComponentWindow.GroupElement grandParent) + { + anim = Mathf.Floor(anim) + Mathf.SmoothStep(0f, 1f, Mathf.Repeat(anim, 1f)); + Rect position = base.position; + position.x = base.position.width * (1f - anim) + 1f; + position.y = 30f; + position.height -= 30f; + position.width -= 2f; + GUILayout.BeginArea(position); + Rect rect = GUILayoutUtility.GetRect(10f, 25f); + string name = parent.name; + GUI.Label(rect, name, AddComponentWindow.s_Styles.header); + if (grandParent != null) + { + Rect position2 = new Rect(rect.x + 4f, rect.y + 7f, 13f, 13f); + if (Event.current.type == EventType.Repaint) + { + AddComponentWindow.s_Styles.leftArrow.Draw(position2, false, false, false, false); + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + this.GoToParent(); + Event.current.Use(); + } + } + if (parent is AddComponentWindow.NewScriptElement) + { + (parent as AddComponentWindow.NewScriptElement).OnGUI(); + } + else + { + this.ListGUI(tree, parent); + } + GUILayout.EndArea(); + } + private void ListGUI(AddComponentWindow.Element[] tree, AddComponentWindow.GroupElement parent) + { + parent.scroll = GUILayout.BeginScrollView(parent.scroll, new GUILayoutOption[0]); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + List children = this.GetChildren(tree, parent); + Rect rect = default(Rect); + for (int i = 0; i < children.Count; i++) + { + AddComponentWindow.Element element = children[i]; + Rect rect2 = GUILayoutUtility.GetRect(16f, 20f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if ((Event.current.type == EventType.MouseMove || Event.current.type == EventType.MouseDown) && parent.selectedIndex != i && rect2.Contains(Event.current.mousePosition)) + { + parent.selectedIndex = i; + base.Repaint(); + } + bool flag = false; + if (i == parent.selectedIndex) + { + flag = true; + rect = rect2; + } + if (Event.current.type == EventType.Repaint) + { + GUIStyle gUIStyle = (!(element is AddComponentWindow.ComponentElement)) ? AddComponentWindow.s_Styles.groupButton : AddComponentWindow.s_Styles.componentButton; + gUIStyle.Draw(rect2, element.content, false, false, flag, flag); + if (!(element is AddComponentWindow.ComponentElement)) + { + Rect position = new Rect(rect2.x + rect2.width - 13f, rect2.y + 4f, 13f, 13f); + AddComponentWindow.s_Styles.rightArrow.Draw(position, false, false, false, false); + } + } + if (Event.current.type == EventType.MouseDown && rect2.Contains(Event.current.mousePosition)) + { + Event.current.Use(); + parent.selectedIndex = i; + this.GoToChild(element, true); + } + } + EditorGUIUtility.SetIconSize(Vector2.zero); + GUILayout.EndScrollView(); + if (this.m_ScrollToSelected && Event.current.type == EventType.Repaint) + { + this.m_ScrollToSelected = false; + Rect lastRect = GUILayoutUtility.GetLastRect(); + if (rect.yMax - lastRect.height > parent.scroll.y) + { + parent.scroll.y = rect.yMax - lastRect.height; + base.Repaint(); + } + if (rect.y < parent.scroll.y) + { + parent.scroll.y = rect.y; + base.Repaint(); + } + } + } + private List GetChildren(AddComponentWindow.Element[] tree, AddComponentWindow.Element parent) + { + List list = new List(); + int num = -1; + int i; + for (i = 0; i < tree.Length; i++) + { + if (tree[i] == parent) + { + num = parent.level + 1; + i++; + break; + } + } + if (num == -1) + { + return list; + } + while (i < tree.Length) + { + AddComponentWindow.Element element = tree[i]; + if (element.level < num) + { + break; + } + if (element.level <= num || this.hasSearch) + { + list.Add(element); + } + i++; + } + return list; + } + } +} diff --git a/UnityEditor/UnityEditor/AlphabeticalSort.cs b/UnityEditor/UnityEditor/AlphabeticalSort.cs new file mode 100644 index 00000000..8a915150 --- /dev/null +++ b/UnityEditor/UnityEditor/AlphabeticalSort.cs @@ -0,0 +1,33 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class AlphabeticalSort : BaseHierarchySort + { + private const string kDefaultSorting = "AlphabeticalSorting"; + private GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("AlphabeticalSorting"), "Alphabetical Order"); + public override GUIContent content + { + get + { + return this.m_Content; + } + } + public override int Compare(GameObject lhs, GameObject rhs) + { + if (lhs == rhs) + { + return 0; + } + if (lhs == null) + { + return -1; + } + if (rhs == null) + { + return 1; + } + return EditorUtility.NaturalCompareObjectNames(lhs, rhs); + } + } +} diff --git a/UnityEditor/UnityEditor/Analytics.cs b/UnityEditor/UnityEditor/Analytics.cs new file mode 100644 index 00000000..213510b3 --- /dev/null +++ b/UnityEditor/UnityEditor/Analytics.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class Analytics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Track(string page); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Event(string category, string action, string label, int value); + } +} diff --git a/UnityEditor/UnityEditor/AnchoredJoint2DEditor.cs b/UnityEditor/UnityEditor/AnchoredJoint2DEditor.cs new file mode 100644 index 00000000..2b14d645 --- /dev/null +++ b/UnityEditor/UnityEditor/AnchoredJoint2DEditor.cs @@ -0,0 +1,57 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AnchoredJoint2D), true)] + internal class AnchoredJoint2DEditor : Joint2DEditorBase + { + private const float k_SnapDistance = 0.13f; + private AnchoredJoint2D anchorJoint2D; + public void OnSceneGUI() + { + this.anchorJoint2D = (AnchoredJoint2D)this.target; + Vector3 vector = Joint2DEditorBase.TransformPoint(this.anchorJoint2D.transform, this.anchorJoint2D.anchor); + Vector3 vector2 = this.anchorJoint2D.connectedAnchor; + if (this.anchorJoint2D.connectedBody) + { + vector2 = Joint2DEditorBase.TransformPoint(this.anchorJoint2D.connectedBody.transform, vector2); + } + Vector3 vector3 = vector + (vector2 - vector).normalized * HandleUtility.GetHandleSize(vector) * 0.1f; + Handles.color = Color.green; + Handles.DrawAAPolyLine(new Vector3[] + { + vector3, + vector2 + }); + if (base.HandleAnchor(ref vector2, true)) + { + vector2 = this.SnapToSprites(vector2); + vector2 = Joint2DEditorBase.SnapToPoint(vector2, vector, 0.13f); + if (this.anchorJoint2D.connectedBody) + { + vector2 = Joint2DEditorBase.InverseTransformPoint(this.anchorJoint2D.connectedBody.transform, vector2); + } + Undo.RecordObject(this.anchorJoint2D, "Move Connected Anchor"); + this.anchorJoint2D.connectedAnchor = vector2; + } + if (base.HandleAnchor(ref vector, false)) + { + vector = this.SnapToSprites(vector); + vector = Joint2DEditorBase.SnapToPoint(vector, vector2, 0.13f); + Undo.RecordObject(this.anchorJoint2D, "Move Anchor"); + this.anchorJoint2D.anchor = Joint2DEditorBase.InverseTransformPoint(this.anchorJoint2D.transform, vector); + } + } + private Vector3 SnapToSprites(Vector3 position) + { + SpriteRenderer component = this.anchorJoint2D.GetComponent(); + position = Joint2DEditorBase.SnapToSprite(component, position, 0.13f); + if (this.anchorJoint2D.connectedBody) + { + component = this.anchorJoint2D.connectedBody.GetComponent(); + position = Joint2DEditorBase.SnapToSprite(component, position, 0.13f); + } + return position; + } + } +} diff --git a/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs b/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs new file mode 100644 index 00000000..b7779961 --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + public enum AndroidBuildSubtarget + { + Generic, + DXT, + PVRTC, + ATC, + ETC, + ETC2, + ASTC + } +} diff --git a/UnityEditor/UnityEditor/AndroidPreferredInstallLocation.cs b/UnityEditor/UnityEditor/AndroidPreferredInstallLocation.cs new file mode 100644 index 00000000..984cd881 --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidPreferredInstallLocation.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum AndroidPreferredInstallLocation + { + Auto, + PreferExternal, + ForceInternal + } +} diff --git a/UnityEditor/UnityEditor/AndroidSdkRoot.cs b/UnityEditor/UnityEditor/AndroidSdkRoot.cs new file mode 100644 index 00000000..6fb12ed6 --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidSdkRoot.cs @@ -0,0 +1,84 @@ +using Microsoft.Win32; +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class AndroidSdkRoot + { + private static string GuessPerPlatform() + { + RuntimePlatform platform = Application.platform; + if (platform != RuntimePlatform.OSXEditor) + { + if (platform != RuntimePlatform.WindowsEditor) + { + return string.Empty; + } + string text = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Android SDK Tools", "Path", string.Empty).ToString(); + if (!string.IsNullOrEmpty(text)) + { + return text; + } + text = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Android SDK Tools", "Path", string.Empty).ToString(); + if (!string.IsNullOrEmpty(text)) + { + return text; + } + text = Environment.GetEnvironmentVariable("ProgramFiles"); + if (!string.IsNullOrEmpty(text)) + { + return text; + } + } + else + { + string environmentVariable = Environment.GetEnvironmentVariable("HOME"); + if (!string.IsNullOrEmpty(environmentVariable)) + { + return environmentVariable; + } + } + return string.Empty; + } + internal static string Browse(string sdkPath) + { + string defaultName = string.Empty; + if (Application.platform == RuntimePlatform.OSXEditor) + { + defaultName = "android-sdk-mac_x86"; + } + string title = "Select Android SDK root folder"; + string text = sdkPath; + if (string.IsNullOrEmpty(text)) + { + try + { + text = AndroidSdkRoot.GuessPerPlatform(); + } + catch (Exception value) + { + Console.WriteLine("Exception while trying to guess Android SDK location"); + Console.WriteLine(value); + } + } + while (true) + { + sdkPath = EditorUtility.OpenFolderPanel(title, text, defaultName); + if (sdkPath.Length == 0) + { + break; + } + if (AndroidSdkRoot.IsSdkDir(sdkPath)) + { + return sdkPath; + } + } + return string.Empty; + } + internal static bool IsSdkDir(string path) + { + return Directory.Exists(Path.Combine(path, "platform-tools")); + } + } +} diff --git a/UnityEditor/UnityEditor/AndroidSdkVersions.cs b/UnityEditor/UnityEditor/AndroidSdkVersions.cs new file mode 100644 index 00000000..2633377b --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidSdkVersions.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + public enum AndroidSdkVersions + { + AndroidApiLevel9 = 9, + AndroidApiLevel10, + AndroidApiLevel11, + AndroidApiLevel12, + AndroidApiLevel13, + AndroidApiLevel14, + AndroidApiLevel15, + AndroidApiLevel16, + AndroidApiLevel17, + AndroidApiLevel18, + AndroidApiLevel19 + } +} diff --git a/UnityEditor/UnityEditor/AndroidShowActivityIndicatorOnLoading.cs b/UnityEditor/UnityEditor/AndroidShowActivityIndicatorOnLoading.cs new file mode 100644 index 00000000..70cd8a1d --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidShowActivityIndicatorOnLoading.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum AndroidShowActivityIndicatorOnLoading + { + Large, + InversedLarge, + Small, + InversedSmall, + DontShow = -1 + } +} diff --git a/UnityEditor/UnityEditor/AndroidSplashScreenScale.cs b/UnityEditor/UnityEditor/AndroidSplashScreenScale.cs new file mode 100644 index 00000000..4598e743 --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidSplashScreenScale.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum AndroidSplashScreenScale + { + Center, + ScaleToFit, + ScaleToFill + } +} diff --git a/UnityEditor/UnityEditor/AndroidTargetDevice.cs b/UnityEditor/UnityEditor/AndroidTargetDevice.cs new file mode 100644 index 00000000..40698d4a --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidTargetDevice.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum AndroidTargetDevice + { + FAT, + ARMv6, + Emulator, + ARMv7, + x86 + } +} diff --git a/UnityEditor/UnityEditor/AnimationClipCurveData.cs b/UnityEditor/UnityEditor/AnimationClipCurveData.cs new file mode 100644 index 00000000..7a2883fd --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationClipCurveData.cs @@ -0,0 +1,28 @@ +using System; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class AnimationClipCurveData + { + public string path; + public Type type; + public string propertyName; + public AnimationCurve curve; + internal int classID; + internal int scriptInstanceID; + public AnimationClipCurveData() + { + } + public AnimationClipCurveData(EditorCurveBinding binding) + { + this.path = binding.path; + this.type = binding.type; + this.propertyName = binding.propertyName; + this.curve = null; + this.classID = binding.m_ClassID; + this.scriptInstanceID = binding.m_ScriptInstanceID; + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationClipEditor.cs b/UnityEditor/UnityEditor/AnimationClipEditor.cs new file mode 100644 index 00000000..4823ece2 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationClipEditor.cs @@ -0,0 +1,1208 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AnimationClip))] + internal class AnimationClipEditor : Editor + { + private class Styles + { + public GUIContent StartFrame = EditorGUIUtility.TextContent("AnimationClipEditor.StartFrame"); + public GUIContent EndFrame = EditorGUIUtility.TextContent("AnimationClipEditor.EndFrame"); + public GUIContent LoopTime = EditorGUIUtility.TextContent("AnimationClipEditor.LoopTime"); + public GUIContent LoopPose = EditorGUIUtility.TextContent("AnimationClipEditor.LoopPose"); + public GUIContent LoopCycleOffset = EditorGUIUtility.TextContent("AnimationClipEditor.LoopCycleOffset"); + public GUIContent MotionCurves = EditorGUIUtility.TextContent("AnimationClipEditor.MotionCurves"); + public GUIContent BakeIntoPoseOrientation = EditorGUIUtility.TextContent("AnimationClipEditor.BakeIntoPoseOrientation"); + public GUIContent OrientationOffsetY = EditorGUIUtility.TextContent("AnimationClipEditor.OrientationOffsetY"); + public GUIContent BasedUponOrientation = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponOrientation"); + public GUIContent BasedUponStartOrientation = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponStartOrientation"); + public GUIContent[] BasedUponRotationHumanOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponRotation.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponRotationHuman.BodyOrientation") + }; + public GUIContent[] BasedUponRotationOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponRotation.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponRotation.RootNodeRotation") + }; + public GUIContent BakeIntoPosePositionY = EditorGUIUtility.TextContent("AnimationClipEditor.BakeIntoPosePositionY"); + public GUIContent PositionOffsetY = EditorGUIUtility.TextContent("AnimationClipEditor.PositionOffsetY"); + public GUIContent BasedUponPositionY = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionY"); + public GUIContent BasedUponStartPositionY = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponStartPositionY"); + public GUIContent[] BasedUponPositionYHumanOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionY.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionHuman.CenterOfMass"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionYHuman.Feet") + }; + public GUIContent[] BasedUponPositionYOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionY.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPosition.RootNodePosition") + }; + public GUIContent BakeIntoPosePositionXZ = EditorGUIUtility.TextContent("AnimationClipEditor.BakeIntoPosePositionXZ"); + public GUIContent BasedUponPositionXZ = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionXZ"); + public GUIContent BasedUponStartPositionXZ = EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponStartPositionXZ"); + public GUIContent[] BasedUponPositionXZHumanOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionXZ.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionHuman.CenterOfMass") + }; + public GUIContent[] BasedUponPositionXZOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPositionXZ.Original"), + EditorGUIUtility.TextContent("AnimationClipEditor.BasedUponPosition.RootNodePosition") + }; + public GUIContent Mirror = EditorGUIUtility.TextContent("AnimationClipEditor.Mirror"); + public GUIContent Curves = EditorGUIUtility.TextContent("AnimationClipEditor.Curves"); + public GUIContent Mask = EditorGUIUtility.TextContent("AnimationClipEditor.Mask"); + public GUIContent AddEventContent = EditorGUIUtility.IconContent("Animation.AddEvent"); + } + private const int kSamplesPerSecond = 60; + private const int kPose = 0; + private const int kRotation = 1; + private const int kHeight = 2; + private const int kPosition = 3; + private static AnimationClipEditor.Styles styles; + private static GUIContent s_GreenLightIcon = EditorGUIUtility.IconContent("lightMeter/greenLight"); + private static GUIContent s_LightRimIcon = EditorGUIUtility.IconContent("lightMeter/lightRim"); + private static GUIContent s_OrangeLightIcon = EditorGUIUtility.IconContent("lightMeter/orangeLight"); + private static GUIContent s_RedLightIcon = EditorGUIUtility.IconContent("lightMeter/redLight"); + private static string s_LoopMeterStr = "LoopMeter"; + private static int s_LoopMeterHint = AnimationClipEditor.s_LoopMeterStr.GetHashCode(); + private static string s_LoopOrientationMeterStr = "LoopOrientationMeter"; + private static int s_LoopOrientationMeterHint = AnimationClipEditor.s_LoopOrientationMeterStr.GetHashCode(); + private static string s_LoopPositionYMeterStr = "LoopPostionYMeter"; + private static int s_LoopPositionYMeterHint = AnimationClipEditor.s_LoopPositionYMeterStr.GetHashCode(); + private static string s_LoopPositionXZMeterStr = "LoopPostionXZMeter"; + private static int s_LoopPositionXZMeterHint = AnimationClipEditor.s_LoopPositionXZMeterStr.GetHashCode(); + public static float s_EventTimelineMax = 1.05f; + private AnimationClipInfoProperties m_ClipInfo; + private AnimationClip m_Clip; + private AnimatorController m_Controller; + private StateMachine m_StateMachine; + private State m_State; + private AvatarPreview m_AvatarPreview; + private TimeArea m_TimeArea; + private TimeArea m_EventTimeArea; + private bool m_DraggingRange; + private bool m_DraggingRangeBegin; + private bool m_DraggingRangeEnd; + private bool m_LoopTime; + private bool m_LoopBlend; + private bool m_LoopBlendOrientation; + private bool m_LoopBlendPositionY; + private bool m_LoopBlendPositionXZ; + private float m_StartFrame; + private float m_StopFrame = 1f; + private AvatarMask m_Mask; + private AvatarMaskInspector m_MaskInspector; + private string[] m_ReferenceTransformPaths; + private bool m_ShowCurves; + private EventManipulationHandler m_EventManipulationHandler; + private bool m_ShowEvents; + private bool m_MaskFoldout; + private Vector2[][][] m_QualityCurves = new Vector2[4][][]; + private bool m_DirtyQualityCurves; + private static GUIContent prevKeyContent = EditorGUIUtility.IconContent("Animation.PrevKey"); + private static GUIContent nextKeyContent = EditorGUIUtility.IconContent("Animation.NextKey"); + private static GUIContent addKeyframeContent = EditorGUIUtility.IconContent("Animation.AddKeyframe"); + public string[] takeNames + { + get; + set; + } + public int takeIndex + { + get; + set; + } + public string[] referenceTransformPaths + { + get + { + return this.m_ReferenceTransformPaths; + } + set + { + this.m_ReferenceTransformPaths = value; + } + } + private void UpdateEventsPopupClipInfo(AnimationClipInfoProperties info) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); + AnimationEventPopup animationEventPopup = (array.Length <= 0) ? null : ((AnimationEventPopup)array[0]); + if (animationEventPopup && animationEventPopup.clipInfo == this.m_ClipInfo) + { + animationEventPopup.clipInfo = info; + } + } + public void ShowRange(AnimationClipInfoProperties info) + { + this.UpdateEventsPopupClipInfo(info); + this.m_ClipInfo = info; + info.AssignToPreviewClip(this.m_Clip); + } + private void InitController() + { + if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) + { + if (this.m_Controller == null) + { + this.m_Controller = new AnimatorController(); + this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.AddLayer("preview"); + this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + if (this.m_ClipInfo != null) + { + this.InitMask(); + this.m_Controller.SetLayerMask(0, this.m_Mask); + } + } + if (this.m_State == null) + { + this.m_State = this.m_StateMachine.AddState("preview"); + this.m_State.SetAnimationClip(this.m_Clip); + this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; + this.m_State.hideFlags = HideFlags.DontSave; + } + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + if (AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) + { + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + } + } + } + internal override void OnHeaderIconGUI(Rect iconRect) + { + bool flag = AssetPreview.IsLoadingAssetPreview(this.target.GetInstanceID()); + Texture2D texture2D = AssetPreview.GetAssetPreview(this.target); + if (!texture2D) + { + if (flag) + { + base.Repaint(); + } + texture2D = AssetPreview.GetMiniThumbnail(this.target); + } + GUI.DrawTexture(iconRect, texture2D); + } + internal override void OnHeaderTitleGUI(Rect titleRect, string header) + { + if (this.m_ClipInfo != null) + { + this.m_ClipInfo.name = EditorGUI.DelayedTextField(titleRect, this.m_ClipInfo.name, null, EditorStyles.textField); + } + else + { + base.OnHeaderTitleGUI(titleRect, header); + } + } + internal override void OnHeaderControlsGUI() + { + if (this.m_ClipInfo != null && this.takeNames != null && this.takeNames.Length > 1) + { + EditorGUIUtility.labelWidth = 80f; + this.takeIndex = EditorGUILayout.Popup("Source Take", this.takeIndex, this.takeNames, new GUILayoutOption[0]); + } + else + { + base.OnHeaderControlsGUI(); + } + } + private void DestroyController() + { + if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) + { + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); + } + UnityEngine.Object.DestroyImmediate(this.m_Controller); + UnityEngine.Object.DestroyImmediate(this.m_State); + this.m_Controller = null; + this.m_StateMachine = null; + this.m_State = null; + } + private void SetPreviewAvatar() + { + this.DestroyController(); + this.InitController(); + } + private void Init() + { + if (AnimationClipEditor.styles == null) + { + AnimationClipEditor.styles = new AnimationClipEditor.Styles(); + } + if (this.m_AvatarPreview == null) + { + this.m_AvatarPreview = new AvatarPreview(null, this.target as Motion); + this.m_AvatarPreview.OnAvatarChangeFunc = new AvatarPreview.OnAvatarChange(this.SetPreviewAvatar); + this.m_AvatarPreview.fps = Mathf.RoundToInt((this.target as AnimationClip).frameRate); + this.m_AvatarPreview.ShowIKOnFeetButton = (this.target as Motion).isHumanMotion; + } + } + private void InitMask() + { + if (this.m_Mask == null) + { + this.m_Mask = new AvatarMask(); + this.m_MaskInspector = (AvatarMaskInspector)Editor.CreateEditor(this.m_Mask); + this.m_MaskInspector.canImport = false; + if (this.m_ClipInfo != null) + { + this.m_MaskInspector.clipInfo = this.m_ClipInfo; + } + if (this.m_Mask.transformCount == 0) + { + this.SetTransformMaskFromReference(); + } + } + } + private void SetTransformMaskFromReference() + { + AvatarMaskUtility.UpdateTransformMask(this.m_Mask, this.m_ReferenceTransformPaths, null); + } + private bool IsMaskUpToDate() + { + if (this.m_Mask.transformCount != this.m_ReferenceTransformPaths.Length) + { + return false; + } + for (int i = 0; i < this.m_ReferenceTransformPaths.Length; i++) + { + if (this.m_Mask.GetTransformPath(i) != this.m_ReferenceTransformPaths[i]) + { + return false; + } + } + return true; + } + private void OnEnable() + { + if (AnimationClipEditor.styles == null) + { + AnimationClipEditor.styles = new AnimationClipEditor.Styles(); + } + this.m_Clip = (this.target as AnimationClip); + if (this.m_TimeArea == null) + { + this.m_TimeArea = new TimeArea(true); + this.m_TimeArea.hRangeLocked = false; + this.m_TimeArea.vRangeLocked = true; + this.m_TimeArea.hSlider = true; + this.m_TimeArea.vSlider = false; + this.m_TimeArea.hRangeMin = this.m_Clip.startTime; + this.m_TimeArea.hRangeMax = this.m_Clip.stopTime; + this.m_TimeArea.margin = 10f; + this.m_TimeArea.scaleWithWindow = true; + this.m_TimeArea.SetShownHRangeInsideMargins(this.m_Clip.startTime, this.m_Clip.stopTime); + this.m_TimeArea.hTicks.SetTickModulosForFrameRate(this.m_Clip.frameRate); + this.m_TimeArea.ignoreScrollWheelUntilClicked = true; + } + this.m_TimeArea.OnEnable(); + if (this.m_EventTimeArea == null) + { + this.m_EventTimeArea = new TimeArea(true); + this.m_EventTimeArea.hRangeLocked = true; + this.m_EventTimeArea.vRangeLocked = true; + this.m_EventTimeArea.hSlider = false; + this.m_EventTimeArea.vSlider = false; + this.m_EventTimeArea.hRangeMin = 0f; + this.m_EventTimeArea.hRangeMax = AnimationClipEditor.s_EventTimelineMax; + this.m_EventTimeArea.margin = 10f; + this.m_EventTimeArea.scaleWithWindow = true; + this.m_EventTimeArea.SetShownHRangeInsideMargins(0f, AnimationClipEditor.s_EventTimelineMax); + this.m_EventTimeArea.hTicks.SetTickModulosForFrameRate(60f); + this.m_EventTimeArea.ignoreScrollWheelUntilClicked = true; + } + this.m_EventTimeArea.OnEnable(); + if (this.m_EventManipulationHandler == null) + { + this.m_EventManipulationHandler = new EventManipulationHandler(this.m_EventTimeArea); + } + } + private void OnDisable() + { + this.DestroyController(); + if (this.m_AvatarPreview != null) + { + this.m_AvatarPreview.OnDestroy(); + } + if (this.m_MaskInspector) + { + UnityEngine.Object.DestroyImmediate(this.m_MaskInspector); + } + if (this.m_Mask) + { + UnityEngine.Object.DestroyImmediate(this.m_Mask); + } + } + public override bool HasPreviewGUI() + { + this.Init(); + return this.m_AvatarPreview != null; + } + public override void OnPreviewSettings() + { + this.m_AvatarPreview.DoPreviewSettings(); + } + private void CalculateQualityCurves() + { + for (int i = 0; i < 4; i++) + { + this.m_QualityCurves[i] = new Vector2[2][]; + } + for (int j = 0; j < 2; j++) + { + float num = Mathf.Clamp(this.m_ClipInfo.firstFrame / this.m_Clip.frameRate, this.m_Clip.startTime, this.m_Clip.stopTime); + float num2 = Mathf.Clamp(this.m_ClipInfo.lastFrame / this.m_Clip.frameRate, this.m_Clip.startTime, this.m_Clip.stopTime); + float fixedTime = (j != 0) ? num : num2; + float num3 = (j != 0) ? num : 0f; + float num4 = (j != 0) ? this.m_Clip.length : num2; + int num5 = Mathf.FloorToInt(num3 * 60f); + int num6 = Mathf.CeilToInt(num4 * 60f); + this.m_QualityCurves[0][j] = new Vector2[num6 - num5 + 1]; + this.m_QualityCurves[1][j] = new Vector2[num6 - num5 + 1]; + this.m_QualityCurves[2][j] = new Vector2[num6 - num5 + 1]; + this.m_QualityCurves[3][j] = new Vector2[num6 - num5 + 1]; + QualityCurvesTime time = default(QualityCurvesTime); + time.fixedTime = fixedTime; + time.variableEndStart = num3; + time.variableEndEnd = num4; + time.q = j; + MuscleClipEditorUtilities.CalculateQualityCurves(this.m_Clip, time, this.m_QualityCurves[0][j], this.m_QualityCurves[1][j], this.m_QualityCurves[2][j], this.m_QualityCurves[3][j]); + } + this.m_DirtyQualityCurves = false; + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + bool flag = Event.current.type == EventType.Repaint; + this.InitController(); + if (flag) + { + this.m_AvatarPreview.timeControl.Update(); + } + AnimationClip animationClip = this.target as AnimationClip; + AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(animationClip); + this.m_AvatarPreview.timeControl.loop = true; + if (flag && this.m_AvatarPreview.PreviewObject != null) + { + if (this.m_AvatarPreview.Animator != null) + { + if (this.m_State != null) + { + this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; + } + float normalizedTime = (this.m_AvatarPreview.timeControl.currentTime - animationClipSettings.startTime) / (animationClipSettings.stopTime - animationClipSettings.startTime); + this.m_AvatarPreview.Animator.Play(0, 0, normalizedTime); + this.m_AvatarPreview.Animator.Update(this.m_AvatarPreview.timeControl.deltaTime); + } + else + { + this.m_AvatarPreview.PreviewObject.SampleAnimation(animationClip, this.m_AvatarPreview.timeControl.currentTime); + } + } + this.m_AvatarPreview.DoAvatarPreview(r, background); + } + public void ClipRangeGUI(ref float startFrame, ref float stopFrame, out bool changedStart, out bool changedStop) + { + changedStart = false; + changedStop = false; + this.m_DraggingRangeBegin = false; + this.m_DraggingRangeEnd = false; + bool flag = startFrame + 0.01f < this.m_Clip.startTime * this.m_Clip.frameRate || startFrame - 0.01f > this.m_Clip.stopTime * this.m_Clip.frameRate || stopFrame + 0.01f < this.m_Clip.startTime * this.m_Clip.frameRate || stopFrame - 0.01f > this.m_Clip.stopTime * this.m_Clip.frameRate; + bool flag2 = false; + if (flag) + { + GUILayout.BeginHorizontal(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label("The clip range is outside of the range of the source take.", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(5f); + if (GUILayout.Button("Clamp Range", new GUILayoutOption[0])) + { + flag2 = true; + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + Rect rect = GUILayoutUtility.GetRect(10f, 33f); + GUI.Label(rect, string.Empty, "TE Toolbar"); + if (Event.current.type == EventType.Repaint) + { + this.m_TimeArea.rect = rect; + } + this.m_TimeArea.BeginViewGUI(); + this.m_TimeArea.EndViewGUI(); + rect.height -= 15f; + int controlID = GUIUtility.GetControlID(3126789, FocusType.Passive); + int controlID2 = GUIUtility.GetControlID(3126789, FocusType.Passive); + GUI.BeginGroup(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f)); + float num = -1f; + rect.y = num; + rect.x = num; + float num2 = this.m_TimeArea.FrameToPixel(startFrame, this.m_Clip.frameRate, rect); + float num3 = this.m_TimeArea.FrameToPixel(stopFrame, this.m_Clip.frameRate, rect); + GUI.Label(new Rect(num2, rect.y, num3 - num2, rect.height), string.Empty, EditorStyles.selectionRect); + this.m_TimeArea.TimeRuler(rect, this.m_Clip.frameRate); + float num4 = this.m_TimeArea.TimeToPixel(this.m_AvatarPreview.timeControl.currentTime, rect) - 0.5f; + Handles.color = new Color(1f, 0f, 0f, 0.5f); + Handles.DrawLine(new Vector2(num4, rect.yMin), new Vector2(num4, rect.yMax)); + Handles.DrawLine(new Vector2(num4 + 1f, rect.yMin), new Vector2(num4 + 1f, rect.yMax)); + Handles.color = Color.white; + EditorGUI.BeginDisabledGroup(flag); + float num5 = startFrame / this.m_Clip.frameRate; + if (this.m_TimeArea.BrowseRuler(rect, controlID, ref num5, 0f, false, "TL InPoint") != TimeArea.TimeRulerDragMode.None) + { + startFrame = num5 * this.m_Clip.frameRate; + startFrame = MathUtils.RoundBasedOnMinimumDifference(startFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); + changedStart = true; + } + float num6 = stopFrame / this.m_Clip.frameRate; + if (this.m_TimeArea.BrowseRuler(rect, controlID2, ref num6, 0f, false, "TL OutPoint") != TimeArea.TimeRulerDragMode.None) + { + stopFrame = num6 * this.m_Clip.frameRate; + stopFrame = MathUtils.RoundBasedOnMinimumDifference(stopFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); + changedStop = true; + } + EditorGUI.EndDisabledGroup(); + if (GUIUtility.hotControl == controlID) + { + changedStart = true; + } + if (GUIUtility.hotControl == controlID2) + { + changedStop = true; + } + GUI.EndGroup(); + EditorGUI.BeginDisabledGroup(flag); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + startFrame = EditorGUILayout.FloatField(AnimationClipEditor.styles.StartFrame, startFrame, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + changedStart = true; + } + GUILayout.FlexibleSpace(); + EditorGUI.BeginChangeCheck(); + stopFrame = EditorGUILayout.FloatField(AnimationClipEditor.styles.EndFrame, stopFrame, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + changedStop = true; + } + EditorGUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + changedStart |= flag2; + changedStop |= flag2; + if (changedStart) + { + startFrame = Mathf.Clamp(startFrame, this.m_Clip.startTime * this.m_Clip.frameRate, Mathf.Clamp(stopFrame, startFrame + 0.1f, this.m_Clip.stopTime * this.m_Clip.frameRate)); + } + if (changedStop) + { + stopFrame = Mathf.Clamp(stopFrame, startFrame + 0.1f, this.m_Clip.stopTime * this.m_Clip.frameRate); + } + if (changedStart || changedStop) + { + if (!this.m_DraggingRange) + { + this.m_DraggingRangeBegin = true; + } + this.m_DraggingRange = true; + } + else + { + if (this.m_DraggingRange && GUIUtility.hotControl == 0 && Event.current.type == EventType.Repaint) + { + this.m_DraggingRangeEnd = true; + this.m_DraggingRange = false; + this.m_DirtyQualityCurves = true; + base.Repaint(); + } + } + GUILayout.Space(10f); + } + private string GetStatsText() + { + string text = string.Empty; + bool flag = base.targets.Length == 1 && (this.target as Motion).isHumanMotion; + if (flag) + { + text += "Average Velocity: "; + text += this.m_Clip.averageSpeed.ToString("0.000"); + text += "\nAverage Angular Y Speed: "; + text += (this.m_Clip.averageAngularSpeed * 180f / 3.14159274f).ToString("0.0"); + text += " deg/s"; + } + if (this.m_ClipInfo == null) + { + AnimationClipStats animationClipStats = default(AnimationClipStats); + animationClipStats.Reset(); + for (int i = 0; i < base.targets.Length; i++) + { + AnimationClip animationClip = base.targets[i] as AnimationClip; + if (animationClip != null) + { + AnimationClipStats animationClipStats2 = AnimationUtility.GetAnimationClipStats(animationClip); + animationClipStats.Combine(animationClipStats2); + } + } + if (text.Length != 0) + { + text += '\n'; + } + float num = (float)animationClipStats.constantCurves / (float)animationClipStats.totalCurves * 100f; + float num2 = (float)animationClipStats.denseCurves / (float)animationClipStats.totalCurves * 100f; + float num3 = (float)animationClipStats.streamCurves / (float)animationClipStats.totalCurves * 100f; + text += string.Format("Curves Pos: {0} Rot: {1} Scale: {2} Muscles: {3} Generic: {4} PPtr: {5}\n", new object[] + { + animationClipStats.positionCurves, + animationClipStats.rotationCurves, + animationClipStats.scaleCurves, + animationClipStats.muscleCurves, + animationClipStats.genericCurves, + animationClipStats.pptrCurves + }); + text += string.Format("Curves Total: {0}, Constant: {1} ({2}%) Dense: {3} ({4}%) Stream: {5} ({6}%)\n", new object[] + { + animationClipStats.totalCurves, + animationClipStats.constantCurves, + num.ToString("0.0"), + animationClipStats.denseCurves, + num2.ToString("0.0"), + animationClipStats.streamCurves, + num3.ToString("0.0") + }); + text += EditorUtility.FormatBytes(animationClipStats.size); + } + return text; + } + private float GetClipLength() + { + if (this.m_ClipInfo == null) + { + return this.m_Clip.length; + } + return (this.m_ClipInfo.lastFrame - this.m_ClipInfo.firstFrame) / this.m_Clip.frameRate; + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + public override void OnInspectorGUI() + { + this.Init(); + EditorGUIUtility.labelWidth = 50f; + EditorGUIUtility.fieldWidth = 30f; + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(true); + GUILayout.Label("Length", EditorStyles.miniLabel, new GUILayoutOption[] + { + GUILayout.Width(46f) + }); + GUILayout.Label(this.GetClipLength().ToString("0.000"), EditorStyles.miniLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(this.m_Clip.frameRate + " FPS", EditorStyles.miniLabel, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + if (this.m_Clip.isAnimatorMotion) + { + this.MuscleClipGUI(); + } + else + { + this.AnimationClipGUI(); + } + } + private void AnimationClipGUI() + { + if (this.m_ClipInfo != null) + { + float firstFrame = this.m_ClipInfo.firstFrame; + float lastFrame = this.m_ClipInfo.lastFrame; + bool flag = false; + bool flag2 = false; + this.ClipRangeGUI(ref firstFrame, ref lastFrame, out flag, out flag2); + if (flag) + { + this.m_ClipInfo.firstFrame = firstFrame; + } + if (flag2) + { + this.m_ClipInfo.lastFrame = lastFrame; + } + this.m_AvatarPreview.timeControl.startTime = firstFrame / this.m_Clip.frameRate; + this.m_AvatarPreview.timeControl.stopTime = lastFrame / this.m_Clip.frameRate; + } + else + { + this.m_AvatarPreview.timeControl.startTime = 0f; + this.m_AvatarPreview.timeControl.stopTime = this.m_Clip.length; + } + EditorGUIUtility.labelWidth = 0f; + EditorGUIUtility.fieldWidth = 0f; + if (this.m_ClipInfo != null) + { + this.m_ClipInfo.loop = EditorGUILayout.Toggle("Add Loop Frame", this.m_ClipInfo.loop, new GUILayoutOption[0]); + } + EditorGUI.BeginChangeCheck(); + int num = (int)((this.m_ClipInfo == null) ? this.m_Clip.wrapMode : ((WrapMode)this.m_ClipInfo.wrapMode)); + num = (int)((WrapModeFixed)EditorGUILayout.EnumPopup("Wrap Mode", (WrapModeFixed)num, new GUILayoutOption[0])); + if (EditorGUI.EndChangeCheck()) + { + if (this.m_ClipInfo != null) + { + this.m_ClipInfo.wrapMode = num; + } + else + { + this.m_Clip.wrapMode = (WrapMode)num; + } + } + } + private void CurveGUI() + { + if (this.m_ClipInfo == null) + { + return; + } + if (this.m_AvatarPreview.timeControl.currentTime == float.NegativeInfinity) + { + this.m_AvatarPreview.timeControl.Update(); + } + float normalizedTime = this.m_AvatarPreview.timeControl.normalizedTime; + for (int i = 0; i < this.m_ClipInfo.GetCurveCount(); i++) + { + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(GUIContent.none, "OL Minus", new GUILayoutOption[] + { + GUILayout.Width(17f) + })) + { + this.m_ClipInfo.RemoveCurve(i); + } + else + { + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(125f) + }); + string curveName = this.m_ClipInfo.GetCurveName(i); + string text = EditorGUILayout.DelayedTextField(curveName, null, EditorStyles.textField, new GUILayoutOption[0]); + if (curveName != text) + { + this.m_ClipInfo.SetCurveName(i, text); + } + AnimationCurve animationCurve = this.m_ClipInfo.GetCurve(i); + int length = animationCurve.length; + bool flag = false; + int num = length - 1; + for (int j = 0; j < length; j++) + { + if (Mathf.Abs(animationCurve.keys[j].time - normalizedTime) < 0.0001f) + { + flag = true; + num = j; + break; + } + if (animationCurve.keys[j].time > normalizedTime) + { + num = j; + break; + } + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(AnimationClipEditor.prevKeyContent, new GUILayoutOption[0]) && num > 0) + { + num--; + this.m_AvatarPreview.timeControl.normalizedTime = animationCurve.keys[num].time; + } + if (GUILayout.Button(AnimationClipEditor.nextKeyContent, new GUILayoutOption[0])) + { + if (flag && num < length - 1) + { + num++; + } + this.m_AvatarPreview.timeControl.normalizedTime = animationCurve.keys[num].time; + } + EditorGUI.BeginDisabledGroup(!flag); + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + EditorGUI.kFloatFieldFormatString = "n3"; + float num2 = animationCurve.Evaluate(normalizedTime); + float num3 = EditorGUILayout.FloatField(num2, new GUILayoutOption[] + { + GUILayout.Width(60f) + }); + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + EditorGUI.EndDisabledGroup(); + bool flag2 = false; + if (num2 != num3) + { + if (flag) + { + animationCurve.RemoveKey(num); + } + flag2 = true; + } + EditorGUI.BeginDisabledGroup(flag); + if (GUILayout.Button(AnimationClipEditor.addKeyframeContent, new GUILayoutOption[0])) + { + flag2 = true; + } + EditorGUI.EndDisabledGroup(); + if (flag2) + { + animationCurve.AddKey(new Keyframe + { + time = normalizedTime, + value = num3, + inTangent = 0f, + outTangent = 0f + }); + } + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + animationCurve = EditorGUILayout.CurveField(animationCurve, new GUILayoutOption[] + { + GUILayout.Height(40f) + }); + Rect lastRect = GUILayoutUtility.GetLastRect(); + length = animationCurve.length; + Handles.color = Color.red; + Handles.DrawLine(new Vector3(lastRect.x + normalizedTime * lastRect.width, lastRect.y, 0f), new Vector3(lastRect.x + normalizedTime * lastRect.width, lastRect.y + lastRect.height, 0f)); + for (int k = 0; k < length; k++) + { + float time = animationCurve.keys[k].time; + Handles.color = Color.white; + Handles.DrawLine(new Vector3(lastRect.x + time * lastRect.width, lastRect.y + lastRect.height - 10f, 0f), new Vector3(lastRect.x + time * lastRect.width, lastRect.y + lastRect.height, 0f)); + } + this.m_ClipInfo.SetCurve(i, animationCurve); + } + GUILayout.EndHorizontal(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(GUIContent.none, "OL Plus", new GUILayoutOption[] + { + GUILayout.Width(17f) + })) + { + this.m_ClipInfo.AddCurve(); + } + GUILayout.EndHorizontal(); + } + private void EventsGUI() + { + if (this.m_ClipInfo == null) + { + return; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(AnimationClipEditor.styles.AddEventContent, new GUILayoutOption[] + { + GUILayout.Width(25f) + })) + { + this.m_ClipInfo.AddEvent(this.m_AvatarPreview.timeControl.normalizedTime); + this.m_EventManipulationHandler.SelectEvent(this.m_ClipInfo.GetEvents(), this.m_ClipInfo.GetEventCount() - 1, this.m_ClipInfo); + } + Rect rect = GUILayoutUtility.GetRect(10f, 33f); + rect.xMin += 5f; + rect.xMax -= 4f; + GUI.Label(rect, string.Empty, "TE Toolbar"); + if (Event.current.type == EventType.Repaint) + { + this.m_EventTimeArea.rect = rect; + } + rect.height -= 15f; + this.m_EventTimeArea.TimeRuler(rect, 100f); + GUI.BeginGroup(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f)); + Rect rect2 = new Rect(-1f, -1f, rect.width, rect.height); + AnimationEvent[] events = this.m_ClipInfo.GetEvents(); + if (this.m_EventManipulationHandler.HandleEventManipulation(rect2, ref events, this.m_ClipInfo)) + { + this.m_ClipInfo.SetEvents(events); + } + float num = this.m_EventTimeArea.TimeToPixel(this.m_AvatarPreview.timeControl.normalizedTime, rect2) - 0.5f; + Handles.color = new Color(1f, 0f, 0f, 0.5f); + Handles.DrawLine(new Vector2(num, rect2.yMin), new Vector2(num, rect2.yMax)); + Handles.DrawLine(new Vector2(num + 1f, rect2.yMin), new Vector2(num + 1f, rect2.yMax)); + Handles.color = Color.white; + GUI.EndGroup(); + GUILayout.EndHorizontal(); + this.m_EventManipulationHandler.DrawInstantTooltip(rect); + } + private void MuscleClipGUI() + { + EditorGUI.BeginChangeCheck(); + this.InitController(); + AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(this.m_Clip); + bool isHumanMotion = (this.target as Motion).isHumanMotion; + bool flag = isHumanMotion && AnimationUtility.HasMotionCurves(this.m_Clip); + this.m_StartFrame = ((!this.m_DraggingRange) ? (animationClipSettings.startTime * this.m_Clip.frameRate) : this.m_StartFrame); + this.m_StopFrame = ((!this.m_DraggingRange) ? (animationClipSettings.stopTime * this.m_Clip.frameRate) : this.m_StopFrame); + bool flag2 = false; + bool flag3 = false; + if (this.m_ClipInfo != null) + { + if (isHumanMotion) + { + if (this.m_DirtyQualityCurves) + { + this.CalculateQualityCurves(); + } + if (this.m_QualityCurves[0] == null && Event.current.type == EventType.Repaint) + { + this.m_DirtyQualityCurves = true; + base.Repaint(); + } + } + this.ClipRangeGUI(ref this.m_StartFrame, ref this.m_StopFrame, out flag2, out flag3); + } + float num = this.m_StartFrame / this.m_Clip.frameRate; + float num2 = this.m_StopFrame / this.m_Clip.frameRate; + if (!this.m_DraggingRange) + { + animationClipSettings.startTime = num; + animationClipSettings.stopTime = num2; + } + this.m_AvatarPreview.timeControl.startTime = num; + this.m_AvatarPreview.timeControl.stopTime = num2; + if (flag2) + { + this.m_AvatarPreview.timeControl.nextCurrentTime = num; + } + if (flag3) + { + this.m_AvatarPreview.timeControl.nextCurrentTime = num2; + } + EditorGUIUtility.labelWidth = 0f; + EditorGUIUtility.fieldWidth = 0f; + MuscleClipQualityInfo muscleClipQualityInfo = MuscleClipEditorUtilities.GetMuscleClipQualityInfo(this.m_Clip, num, num2); + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + this.LoopToggle(controlRect, AnimationClipEditor.styles.LoopTime, ref animationClipSettings.loopTime); + EditorGUI.BeginDisabledGroup(!animationClipSettings.loopTime); + EditorGUI.indentLevel++; + Rect controlRect2 = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + this.LoopToggle(controlRect2, AnimationClipEditor.styles.LoopPose, ref animationClipSettings.loopBlend); + animationClipSettings.cycleOffset = EditorGUILayout.FloatField(AnimationClipEditor.styles.LoopCycleOffset, animationClipSettings.cycleOffset, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + EditorGUI.EndDisabledGroup(); + EditorGUILayout.Space(); + bool flag4 = isHumanMotion && (flag2 || flag3); + if (!flag) + { + GUILayout.Label("Root Transform Rotation", EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + Rect controlRect3 = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + this.LoopToggle(controlRect3, AnimationClipEditor.styles.BakeIntoPoseOrientation, ref animationClipSettings.loopBlendOrientation); + int num3 = (!animationClipSettings.keepOriginalOrientation) ? 1 : 0; + num3 = EditorGUILayout.Popup((!animationClipSettings.loopBlendOrientation) ? AnimationClipEditor.styles.BasedUponStartOrientation : AnimationClipEditor.styles.BasedUponOrientation, num3, (!isHumanMotion) ? AnimationClipEditor.styles.BasedUponRotationOpt : AnimationClipEditor.styles.BasedUponRotationHumanOpt, new GUILayoutOption[0]); + animationClipSettings.keepOriginalOrientation = (num3 == 0); + if (flag4) + { + EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + } + else + { + animationClipSettings.orientationOffsetY = EditorGUILayout.FloatField(AnimationClipEditor.styles.OrientationOffsetY, animationClipSettings.orientationOffsetY, new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + GUILayout.Label("Root Transform Position (Y)", EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + Rect controlRect4 = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + this.LoopToggle(controlRect4, AnimationClipEditor.styles.BakeIntoPosePositionY, ref animationClipSettings.loopBlendPositionY); + if (isHumanMotion) + { + int num4; + if (animationClipSettings.keepOriginalPositionY) + { + num4 = 0; + } + else + { + if (animationClipSettings.heightFromFeet) + { + num4 = 2; + } + else + { + num4 = 1; + } + } + num4 = EditorGUILayout.Popup((!animationClipSettings.loopBlendPositionY) ? AnimationClipEditor.styles.BasedUponPositionY : AnimationClipEditor.styles.BasedUponStartPositionY, num4, AnimationClipEditor.styles.BasedUponPositionYHumanOpt, new GUILayoutOption[0]); + if (num4 == 0) + { + animationClipSettings.keepOriginalPositionY = true; + animationClipSettings.heightFromFeet = false; + } + else + { + if (num4 == 1) + { + animationClipSettings.keepOriginalPositionY = false; + animationClipSettings.heightFromFeet = false; + } + else + { + animationClipSettings.keepOriginalPositionY = false; + animationClipSettings.heightFromFeet = true; + } + } + } + else + { + int num5 = (!animationClipSettings.keepOriginalPositionY) ? 1 : 0; + num5 = EditorGUILayout.Popup((!animationClipSettings.loopBlendPositionY) ? AnimationClipEditor.styles.BasedUponPositionY : AnimationClipEditor.styles.BasedUponStartPositionY, num5, AnimationClipEditor.styles.BasedUponPositionYOpt, new GUILayoutOption[0]); + animationClipSettings.keepOriginalPositionY = (num5 == 0); + } + if (flag4) + { + EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + } + else + { + animationClipSettings.level = EditorGUILayout.FloatField(AnimationClipEditor.styles.PositionOffsetY, animationClipSettings.level, new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + GUILayout.Label("Root Transform Position (XZ)", EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + Rect controlRect5 = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + this.LoopToggle(controlRect5, AnimationClipEditor.styles.BakeIntoPosePositionXZ, ref animationClipSettings.loopBlendPositionXZ); + int num6 = (!animationClipSettings.keepOriginalPositionXZ) ? 1 : 0; + num6 = EditorGUILayout.Popup((!animationClipSettings.loopBlendPositionXZ) ? AnimationClipEditor.styles.BasedUponPositionXZ : AnimationClipEditor.styles.BasedUponStartPositionXZ, num6, (!isHumanMotion) ? AnimationClipEditor.styles.BasedUponPositionXZOpt : AnimationClipEditor.styles.BasedUponPositionXZHumanOpt, new GUILayoutOption[0]); + animationClipSettings.keepOriginalPositionXZ = (num6 == 0); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + if (isHumanMotion) + { + this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag2, flag3, this.m_QualityCurves[0]); + this.LoopQualityLampAndCurve(controlRect3, muscleClipQualityInfo.loopOrientation, AnimationClipEditor.s_LoopOrientationMeterHint, flag2, flag3, this.m_QualityCurves[1]); + this.LoopQualityLampAndCurve(controlRect4, muscleClipQualityInfo.loopPositionY, AnimationClipEditor.s_LoopPositionYMeterHint, flag2, flag3, this.m_QualityCurves[2]); + this.LoopQualityLampAndCurve(controlRect5, muscleClipQualityInfo.loopPositionXZ, AnimationClipEditor.s_LoopPositionXZMeterHint, flag2, flag3, this.m_QualityCurves[3]); + } + } + if (isHumanMotion) + { + if (flag) + { + this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag2, flag3, this.m_QualityCurves[0]); + } + animationClipSettings.mirror = EditorGUILayout.Toggle(AnimationClipEditor.styles.Mirror, animationClipSettings.mirror, new GUILayoutOption[0]); + } + if (flag) + { + EditorGUILayout.Space(); + GUILayout.Label(AnimationClipEditor.styles.MotionCurves, EditorStyles.label, new GUILayoutOption[0]); + } + string statsText = this.GetStatsText(); + if (statsText != string.Empty) + { + GUILayout.Label(statsText, EditorStyles.helpBox, new GUILayoutOption[0]); + } + EditorGUILayout.Space(); + if (this.m_ClipInfo != null) + { + this.InitMask(); + this.m_MaskInspector.showBody = isHumanMotion; + int indentLevel = EditorGUI.indentLevel; + bool changed = GUI.changed; + this.m_MaskFoldout = EditorGUILayout.Foldout(this.m_MaskFoldout, AnimationClipEditor.styles.Mask); + GUI.changed = changed; + if (this.m_ClipInfo.maskType == ClipAnimationMaskType.CreateFromThisModel && !this.IsMaskUpToDate()) + { + GUILayout.BeginHorizontal(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label("Mask does not match hierarchy. Animation might not import correctly", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(5f); + if (GUILayout.Button("Fix Mask", new GUILayoutOption[0])) + { + this.SetTransformMaskFromReference(); + this.m_ClipInfo.MaskToClip(this.m_Mask); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + if (this.m_MaskFoldout) + { + EditorGUI.indentLevel++; + this.m_MaskInspector.OnInspectorGUI(); + } + EditorGUI.indentLevel = indentLevel; + } + bool flag5 = InternalEditorUtility.HasPro(); + if (flag5 && this.m_ClipInfo != null) + { + bool changed = GUI.changed; + this.m_ShowCurves = EditorGUILayout.Foldout(this.m_ShowCurves, AnimationClipEditor.styles.Curves); + GUI.changed = changed; + if (this.m_ShowCurves) + { + this.CurveGUI(); + } + } + if (this.m_ClipInfo != null) + { + bool changed = GUI.changed; + this.m_ShowEvents = EditorGUILayout.Foldout(this.m_ShowEvents, "Events"); + GUI.changed = changed; + if (this.m_ShowEvents) + { + this.EventsGUI(); + } + } + if (this.m_DraggingRangeBegin) + { + this.m_LoopTime = animationClipSettings.loopTime; + this.m_LoopBlend = animationClipSettings.loopBlend; + this.m_LoopBlendOrientation = animationClipSettings.loopBlendOrientation; + this.m_LoopBlendPositionY = animationClipSettings.loopBlendPositionY; + this.m_LoopBlendPositionXZ = animationClipSettings.loopBlendPositionXZ; + animationClipSettings.loopTime = false; + animationClipSettings.loopBlend = false; + animationClipSettings.loopBlendOrientation = false; + animationClipSettings.loopBlendPositionY = false; + animationClipSettings.loopBlendPositionXZ = false; + animationClipSettings.startTime = 0f; + animationClipSettings.stopTime = this.m_Clip.length; + AnimationUtility.SetAnimationClipSettingsNoDirty(this.m_Clip, animationClipSettings); + this.DestroyController(); + } + if (this.m_DraggingRangeEnd) + { + animationClipSettings.loopTime = this.m_LoopTime; + animationClipSettings.loopBlend = this.m_LoopBlend; + animationClipSettings.loopBlendOrientation = this.m_LoopBlendOrientation; + animationClipSettings.loopBlendPositionY = this.m_LoopBlendPositionY; + animationClipSettings.loopBlendPositionXZ = this.m_LoopBlendPositionXZ; + } + if ((EditorGUI.EndChangeCheck() || this.m_DraggingRangeEnd) && !this.m_DraggingRange) + { + Undo.RegisterCompleteObjectUndo(this.m_Clip, "Muscle Clip Edit"); + AnimationUtility.SetAnimationClipSettingsNoDirty(this.m_Clip, animationClipSettings); + EditorUtility.SetDirty(this.m_Clip); + this.DestroyController(); + } + } + private void LoopToggle(Rect r, GUIContent content, ref bool val) + { + if (!this.m_DraggingRange) + { + val = EditorGUI.Toggle(r, content, val); + } + else + { + EditorGUI.LabelField(r, content, GUIContent.none); + EditorGUI.BeginDisabledGroup(true); + EditorGUI.Toggle(r, " ", false); + EditorGUI.EndDisabledGroup(); + } + } + private void LoopQualityLampAndCurve(Rect position, float value, int lightMeterHint, bool changedStart, bool changedStop, Vector2[][] curves) + { + if (this.m_ClipInfo == null) + { + return; + } + GUIStyle gUIStyle = new GUIStyle(EditorStyles.miniLabel); + gUIStyle.alignment = TextAnchor.MiddleRight; + Rect position2 = position; + position2.xMax -= 20f; + position2.xMin += EditorGUIUtility.labelWidth; + GUI.Label(position2, "loop match", gUIStyle); + Event current = Event.current; + int controlID = GUIUtility.GetControlID(lightMeterHint, FocusType.Native, position); + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.Repaint) + { + Rect position3 = position; + float num = (22f - position3.height) / 2f; + position3.y -= num; + position3.xMax += num; + position3.height = 22f; + position3.xMin = position3.xMax - 22f; + if (value < 0.33f) + { + GUI.DrawTexture(position3, AnimationClipEditor.s_RedLightIcon.image); + } + else + { + if (value < 0.66f) + { + GUI.DrawTexture(position3, AnimationClipEditor.s_OrangeLightIcon.image); + } + else + { + GUI.DrawTexture(position3, AnimationClipEditor.s_GreenLightIcon.image); + } + } + GUI.DrawTexture(position3, AnimationClipEditor.s_LightRimIcon.image); + } + if (changedStart || changedStop) + { + Rect rect = position; + rect.y += rect.height + 1f; + rect.height = 18f; + GUI.color = new Color(0f, 0f, 0f, EditorGUIUtility.isProSkin ? 0.3f : 0.8f); + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + rect = new RectOffset(-1, -1, -1, -1).Add(rect); + if (!EditorGUIUtility.isProSkin) + { + GUI.color = new Color(0.3529412f, 0.3529412f, 0.3529412f, 1f); + } + else + { + GUI.color = new Color(0.254901975f, 0.254901975f, 0.254901975f, 1f); + } + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = Color.white; + GUI.BeginGroup(rect); + Matrix4x4 drawingToViewMatrix = this.m_TimeArea.drawingToViewMatrix; + drawingToViewMatrix.m00 = rect.width / this.m_TimeArea.shownArea.width; + drawingToViewMatrix.m11 = rect.height - 1f; + drawingToViewMatrix.m03 = -this.m_TimeArea.shownArea.x * rect.width / this.m_TimeArea.shownArea.width; + drawingToViewMatrix.m13 = 0f; + Vector2[] array = curves[(!changedStart) ? 1 : 0]; + Vector3[] array2 = new Vector3[array.Length]; + Color[] array3 = new Color[array.Length]; + Color color = new Color(1f, 0.3f, 0.3f); + Color color2 = new Color(1f, 0.8f, 0f); + Color color3 = new Color(0f, 1f, 0f); + for (int i = 0; i < array2.Length; i++) + { + array2[i] = array[i]; + array2[i] = drawingToViewMatrix.MultiplyPoint3x4(array2[i]); + if (1f - array[i].y < 0.33f) + { + array3[i] = color; + } + else + { + if (1f - array[i].y < 0.66f) + { + array3[i] = color2; + } + else + { + array3[i] = color3; + } + } + } + Handles.DrawAAPolyLine(array3, array2); + GUI.color = new Color(0.3f, 0.6f, 1f); + float x = drawingToViewMatrix.MultiplyPoint3x4(new Vector3(((!changedStart) ? this.m_StopFrame : this.m_StartFrame) / this.m_Clip.frameRate, 0f, 0f)).x; + GUI.DrawTexture(new Rect(x, 0f, 1f, rect.height), EditorGUIUtility.whiteTexture); + x = drawingToViewMatrix.MultiplyPoint3x4(new Vector3(((!changedStart) ? this.m_StartFrame : this.m_StopFrame) / this.m_Clip.frameRate, 0f, 0f)).x; + GUI.DrawTexture(new Rect(x, 0f, 1f, rect.height), EditorGUIUtility.whiteTexture); + GUI.color = Color.white; + GUI.EndGroup(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs b/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs new file mode 100644 index 00000000..74cb9a5c --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs @@ -0,0 +1,543 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AnimationClipInfoProperties + { + private SerializedProperty m_Property; + public string name + { + get + { + return this.Get("name").stringValue; + } + set + { + this.Get("name").stringValue = value; + } + } + public string takeName + { + get + { + return this.Get("takeName").stringValue; + } + set + { + this.Get("takeName").stringValue = value; + } + } + public float firstFrame + { + get + { + return this.Get("firstFrame").floatValue; + } + set + { + this.Get("firstFrame").floatValue = value; + } + } + public float lastFrame + { + get + { + return this.Get("lastFrame").floatValue; + } + set + { + this.Get("lastFrame").floatValue = value; + } + } + public int wrapMode + { + get + { + return this.Get("wrapMode").intValue; + } + set + { + this.Get("wrapMode").intValue = value; + } + } + public bool loop + { + get + { + return this.Get("loop").boolValue; + } + set + { + this.Get("loop").boolValue = value; + } + } + public float orientationOffsetY + { + get + { + return this.Get("orientationOffsetY").floatValue; + } + set + { + this.Get("orientationOffsetY").floatValue = value; + } + } + public float level + { + get + { + return this.Get("level").floatValue; + } + set + { + this.Get("level").floatValue = value; + } + } + public float cycleOffset + { + get + { + return this.Get("cycleOffset").floatValue; + } + set + { + this.Get("cycleOffset").floatValue = value; + } + } + public bool loopTime + { + get + { + return this.Get("loopTime").boolValue; + } + set + { + this.Get("loopTime").boolValue = value; + } + } + public bool loopBlend + { + get + { + return this.Get("loopBlend").boolValue; + } + set + { + this.Get("loopBlend").boolValue = value; + } + } + public bool loopBlendOrientation + { + get + { + return this.Get("loopBlendOrientation").boolValue; + } + set + { + this.Get("loopBlendOrientation").boolValue = value; + } + } + public bool loopBlendPositionY + { + get + { + return this.Get("loopBlendPositionY").boolValue; + } + set + { + this.Get("loopBlendPositionY").boolValue = value; + } + } + public bool loopBlendPositionXZ + { + get + { + return this.Get("loopBlendPositionXZ").boolValue; + } + set + { + this.Get("loopBlendPositionXZ").boolValue = value; + } + } + public bool keepOriginalOrientation + { + get + { + return this.Get("keepOriginalOrientation").boolValue; + } + set + { + this.Get("keepOriginalOrientation").boolValue = value; + } + } + public bool keepOriginalPositionY + { + get + { + return this.Get("keepOriginalPositionY").boolValue; + } + set + { + this.Get("keepOriginalPositionY").boolValue = value; + } + } + public bool keepOriginalPositionXZ + { + get + { + return this.Get("keepOriginalPositionXZ").boolValue; + } + set + { + this.Get("keepOriginalPositionXZ").boolValue = value; + } + } + public bool heightFromFeet + { + get + { + return this.Get("heightFromFeet").boolValue; + } + set + { + this.Get("heightFromFeet").boolValue = value; + } + } + public bool mirror + { + get + { + return this.Get("mirror").boolValue; + } + set + { + this.Get("mirror").boolValue = value; + } + } + public ClipAnimationMaskType maskType + { + get + { + return (ClipAnimationMaskType)this.Get("maskType").intValue; + } + set + { + this.Get("maskType").intValue = (int)value; + } + } + public SerializedProperty maskTypeProperty + { + get + { + return this.Get("maskType"); + } + } + public AvatarMask maskSource + { + get + { + return this.Get("maskSource").objectReferenceValue as AvatarMask; + } + set + { + this.Get("maskSource").objectReferenceValue = value; + } + } + public SerializedProperty maskSourceProperty + { + get + { + return this.Get("maskSource"); + } + } + public AnimationClipInfoProperties(SerializedProperty prop) + { + this.m_Property = prop; + } + private SerializedProperty Get(string property) + { + return this.m_Property.FindPropertyRelative(property); + } + public void MaskFromClip(AvatarMask mask) + { + SerializedProperty serializedProperty = this.Get("bodyMask"); + if (serializedProperty != null && serializedProperty.isArray) + { + for (int i = 0; i < mask.humanoidBodyPartCount; i++) + { + mask.SetHumanoidBodyPartActive(i, serializedProperty.GetArrayElementAtIndex(i).intValue != 0); + } + } + SerializedProperty serializedProperty2 = this.Get("transformMask"); + if (serializedProperty2 != null && serializedProperty2.isArray) + { + if (serializedProperty2.arraySize > 0 && mask.transformCount != serializedProperty2.arraySize) + { + mask.transformCount = serializedProperty2.arraySize; + } + int arraySize = serializedProperty2.arraySize; + for (int j = 0; j < arraySize; j++) + { + SerializedProperty serializedProperty3 = serializedProperty2.GetArrayElementAtIndex(j).FindPropertyRelative("m_Path"); + SerializedProperty serializedProperty4 = serializedProperty2.GetArrayElementAtIndex(j).FindPropertyRelative("m_Weight"); + mask.SetTransformPath(j, serializedProperty3.stringValue); + mask.SetTransformActive(j, (double)serializedProperty4.floatValue > 0.5); + } + } + } + public void MaskToClip(AvatarMask mask) + { + SerializedProperty serializedProperty = this.Get("bodyMask"); + if (serializedProperty != null && serializedProperty.isArray) + { + for (int i = 0; i < mask.humanoidBodyPartCount; i++) + { + if (i >= serializedProperty.arraySize) + { + serializedProperty.InsertArrayElementAtIndex(i); + } + serializedProperty.GetArrayElementAtIndex(i).intValue = ((!mask.GetHumanoidBodyPartActive(i)) ? 0 : 1); + } + } + SerializedProperty serializedProperty2 = this.Get("transformMask"); + ModelImporter.UpdateTransformMask(mask, serializedProperty2); + } + public void ClearCurves() + { + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.ClearArray(); + } + } + public int GetCurveCount() + { + int result = 0; + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + result = serializedProperty.arraySize; + } + return result; + } + public string GetCurveName(int index) + { + string result = string.Empty; + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + result = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("name").stringValue; + } + return result; + } + public void SetCurveName(int index, string name) + { + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("name").stringValue = name; + } + } + public AnimationCurve GetCurve(int index) + { + AnimationCurve result = null; + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + result = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("curve").animationCurveValue; + } + return result; + } + public void SetCurve(int index, AnimationCurve curve) + { + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("curve").animationCurveValue = curve; + } + } + public void AddCurve() + { + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.InsertArrayElementAtIndex(serializedProperty.arraySize); + serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1).FindPropertyRelative("name").stringValue = "Curve"; + serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1).FindPropertyRelative("curve").animationCurveValue = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, 0f), + new Keyframe(1f, 0f) + }); + } + } + public void RemoveCurve(int index) + { + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.DeleteArrayElementAtIndex(index); + } + } + public AnimationEvent GetEvent(int index) + { + AnimationEvent animationEvent = new AnimationEvent(); + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + if (index < serializedProperty.arraySize) + { + animationEvent.floatParameter = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("floatParameter").floatValue; + animationEvent.functionName = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("functionName").stringValue; + animationEvent.intParameter = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("intParameter").intValue; + animationEvent.objectReferenceParameter = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("objectReferenceParameter").objectReferenceValue; + animationEvent.stringParameter = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("data").stringValue; + animationEvent.time = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("time").floatValue; + } + else + { + Debug.LogWarning("Invalid Event Index"); + } + } + return animationEvent; + } + public void SetEvent(int index, AnimationEvent animationEvent) + { + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + if (index < serializedProperty.arraySize) + { + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("floatParameter").floatValue = animationEvent.floatParameter; + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("functionName").stringValue = animationEvent.functionName; + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("intParameter").intValue = animationEvent.intParameter; + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("objectReferenceParameter").objectReferenceValue = animationEvent.objectReferenceParameter; + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("data").stringValue = animationEvent.stringParameter; + serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("time").floatValue = animationEvent.time; + } + else + { + Debug.LogWarning("Invalid Event Index"); + } + } + } + public void ClearEvents() + { + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.ClearArray(); + } + } + public int GetEventCount() + { + int result = 0; + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + result = serializedProperty.arraySize; + } + return result; + } + public void AddEvent(float time) + { + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.InsertArrayElementAtIndex(serializedProperty.arraySize); + serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1).FindPropertyRelative("functionName").stringValue = "NewEvent"; + serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1).FindPropertyRelative("time").floatValue = time; + } + } + public void RemoveEvent(int index) + { + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.DeleteArrayElementAtIndex(index); + } + } + public void SetEvents(AnimationEvent[] newEvents) + { + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.ClearArray(); + for (int i = 0; i < newEvents.Length; i++) + { + AnimationEvent animationEvent = newEvents[i]; + serializedProperty.InsertArrayElementAtIndex(serializedProperty.arraySize); + this.SetEvent(serializedProperty.arraySize - 1, animationEvent); + } + } + } + public AnimationEvent[] GetEvents() + { + AnimationEvent[] array = new AnimationEvent[this.GetEventCount()]; + SerializedProperty serializedProperty = this.Get("events"); + if (serializedProperty != null && serializedProperty.isArray) + { + for (int i = 0; i < this.GetEventCount(); i++) + { + array[i] = this.GetEvent(i); + } + } + return array; + } + public void AssignToPreviewClip(AnimationClip clip) + { + AnimationUtility.SetAnimationClipSettingsNoDirty(clip, new AnimationClipSettings + { + startTime = this.firstFrame / clip.frameRate, + stopTime = this.lastFrame / clip.frameRate, + orientationOffsetY = this.orientationOffsetY, + level = this.level, + cycleOffset = this.cycleOffset, + loopTime = this.loopTime, + loopBlend = this.loopBlend, + loopBlendOrientation = this.loopBlendOrientation, + loopBlendPositionY = this.loopBlendPositionY, + loopBlendPositionXZ = this.loopBlendPositionXZ, + keepOriginalOrientation = this.keepOriginalOrientation, + keepOriginalPositionY = this.keepOriginalPositionY, + keepOriginalPositionXZ = this.keepOriginalPositionXZ, + heightFromFeet = this.heightFromFeet, + mirror = this.mirror + }); + } + private float FixPrecisionErrors(float f) + { + float num = Mathf.Round(f); + if (Mathf.Abs(f - num) < 0.0001f) + { + return num; + } + return f; + } + public void ExtractFromPreviewClip(AnimationClip clip) + { + AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(clip); + if (this.firstFrame / clip.frameRate != animationClipSettings.startTime) + { + this.firstFrame = this.FixPrecisionErrors(animationClipSettings.startTime * clip.frameRate); + } + if (this.lastFrame / clip.frameRate != animationClipSettings.stopTime) + { + this.lastFrame = this.FixPrecisionErrors(animationClipSettings.stopTime * clip.frameRate); + } + this.orientationOffsetY = animationClipSettings.orientationOffsetY; + this.level = animationClipSettings.level; + this.cycleOffset = animationClipSettings.cycleOffset; + this.loopTime = animationClipSettings.loopTime; + this.loopBlend = animationClipSettings.loopBlend; + this.loopBlendOrientation = animationClipSettings.loopBlendOrientation; + this.loopBlendPositionY = animationClipSettings.loopBlendPositionY; + this.loopBlendPositionXZ = animationClipSettings.loopBlendPositionXZ; + this.keepOriginalOrientation = animationClipSettings.keepOriginalOrientation; + this.keepOriginalPositionY = animationClipSettings.keepOriginalPositionY; + this.keepOriginalPositionXZ = animationClipSettings.keepOriginalPositionXZ; + this.heightFromFeet = animationClipSettings.heightFromFeet; + this.mirror = animationClipSettings.mirror; + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationClipSettings.cs b/UnityEditor/UnityEditor/AnimationClipSettings.cs new file mode 100644 index 00000000..64500a05 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationClipSettings.cs @@ -0,0 +1,22 @@ +using System; +namespace UnityEditor +{ + public sealed class AnimationClipSettings + { + public float startTime; + public float stopTime; + public float orientationOffsetY; + public float level; + public float cycleOffset; + public bool loopTime; + public bool loopBlend; + public bool loopBlendOrientation; + public bool loopBlendPositionY; + public bool loopBlendPositionXZ; + public bool keepOriginalOrientation; + public bool keepOriginalPositionY; + public bool keepOriginalPositionXZ; + public bool heightFromFeet; + public bool mirror; + } +} diff --git a/UnityEditor/UnityEditor/AnimationClipStats.cs b/UnityEditor/UnityEditor/AnimationClipStats.cs new file mode 100644 index 00000000..aacc03fa --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationClipStats.cs @@ -0,0 +1,46 @@ +using System; +namespace UnityEditor +{ + internal struct AnimationClipStats + { + public int size; + public int positionCurves; + public int rotationCurves; + public int scaleCurves; + public int muscleCurves; + public int genericCurves; + public int pptrCurves; + public int totalCurves; + public int constantCurves; + public int denseCurves; + public int streamCurves; + public void Reset() + { + this.size = 0; + this.positionCurves = 0; + this.rotationCurves = 0; + this.scaleCurves = 0; + this.muscleCurves = 0; + this.genericCurves = 0; + this.pptrCurves = 0; + this.totalCurves = 0; + this.constantCurves = 0; + this.denseCurves = 0; + this.streamCurves = 0; + } + public void Combine(AnimationClipStats other) + { + this.size += other.size; + this.positionCurves += other.positionCurves; + this.rotationCurves += other.rotationCurves; + this.scaleCurves += other.scaleCurves; + this.muscleCurves += other.muscleCurves; + this.genericCurves += other.genericCurves; + this.pptrCurves += other.pptrCurves; + this.totalCurves += other.totalCurves; + this.constantCurves += other.constantCurves; + this.denseCurves += other.denseCurves; + this.streamCurves += other.streamCurves; + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationCurveContextMenu.cs b/UnityEditor/UnityEditor/AnimationCurveContextMenu.cs new file mode 100644 index 00000000..098fd527 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationCurveContextMenu.cs @@ -0,0 +1,51 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class AnimationCurveContextMenu + { + private SerializedProperty m_Prop1; + private SerializedProperty m_Prop2; + private SerializedProperty m_Scalar; + private ParticleSystemCurveEditor m_ParticleSystemCurveEditor; + private Rect m_CurveRanges; + private AnimationCurveContextMenu(SerializedProperty prop1, SerializedProperty prop2, SerializedProperty scalar, Rect curveRanges, ParticleSystemCurveEditor owner) + { + this.m_Prop1 = prop1; + this.m_Prop2 = prop2; + this.m_Scalar = scalar; + this.m_ParticleSystemCurveEditor = owner; + this.m_CurveRanges = curveRanges; + } + internal static void Show(Rect position, SerializedProperty property, SerializedProperty property2, SerializedProperty scalar, Rect curveRanges, ParticleSystemCurveEditor curveEditor) + { + GUIContent content = new GUIContent("Copy"); + GUIContent content2 = new GUIContent("Paste"); + GenericMenu genericMenu = new GenericMenu(); + bool flag = property != null && property2 != null; + bool flag2 = (flag && ParticleSystemClipboard.HasDoubleAnimationCurve()) || (!flag && ParticleSystemClipboard.HasSingleAnimationCurve()); + AnimationCurveContextMenu @object = new AnimationCurveContextMenu(property, property2, scalar, curveRanges, curveEditor); + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction(@object.Copy)); + if (flag2) + { + genericMenu.AddItem(content2, false, new GenericMenu.MenuFunction(@object.Paste)); + } + else + { + genericMenu.AddDisabledItem(content2); + } + genericMenu.DropDown(position); + } + private void Copy() + { + AnimationCurve animCurve = (this.m_Prop1 == null) ? null : this.m_Prop1.animationCurveValue; + AnimationCurve animCurve2 = (this.m_Prop2 == null) ? null : this.m_Prop2.animationCurveValue; + float scalar = (this.m_Scalar == null) ? 1f : this.m_Scalar.floatValue; + ParticleSystemClipboard.CopyAnimationCurves(animCurve, animCurve2, scalar); + } + private void Paste() + { + ParticleSystemClipboard.PasteAnimationCurves(this.m_Prop1, this.m_Prop2, this.m_Scalar, this.m_CurveRanges, this.m_ParticleSystemCurveEditor); + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationEditor.cs b/UnityEditor/UnityEditor/AnimationEditor.cs new file mode 100644 index 00000000..b5b464bc --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationEditor.cs @@ -0,0 +1,83 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Animation))] + internal class AnimationEditor : Editor + { + private static int s_BoxHash = "AnimationBoundsEditorHash".GetHashCode(); + private BoxEditor m_BoxEditor = new BoxEditor(false, AnimationEditor.s_BoxHash); + private int m_PrePreviewAnimationArraySize = -1; + private SerializedProperty m_UserAABB; + public void OnEnable() + { + this.m_UserAABB = base.serializedObject.FindProperty("m_UserAABB"); + this.m_PrePreviewAnimationArraySize = -1; + this.m_BoxEditor.OnEnable(); + } + public void OnDisable() + { + this.m_BoxEditor.OnDisable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + SerializedProperty serializedProperty = base.serializedObject.FindProperty("m_Animation"); + EditorGUILayout.PropertyField(serializedProperty, true, new GUILayoutOption[0]); + int objectReferenceInstanceIDValue = serializedProperty.objectReferenceInstanceIDValue; + SerializedProperty serializedProperty2 = base.serializedObject.FindProperty("m_Animations"); + int arraySize = serializedProperty2.arraySize; + if (ObjectSelector.isVisible && this.m_PrePreviewAnimationArraySize == -1) + { + this.m_PrePreviewAnimationArraySize = arraySize; + } + if (this.m_PrePreviewAnimationArraySize != -1) + { + int num = (arraySize <= 0) ? -1 : serializedProperty2.GetArrayElementAtIndex(arraySize - 1).objectReferenceInstanceIDValue; + if (num != objectReferenceInstanceIDValue) + { + serializedProperty2.arraySize = this.m_PrePreviewAnimationArraySize; + } + if (!ObjectSelector.isVisible) + { + this.m_PrePreviewAnimationArraySize = -1; + } + } + Editor.DrawPropertiesExcluding(base.serializedObject, new string[] + { + "m_Animation", + "m_UserAABB" + }); + Animation animation = (Animation)this.target; + if (animation && animation.cullingType == AnimationCullingType.BasedOnUserBounds) + { + EditorGUILayout.PropertyField(this.m_UserAABB, new GUIContent("Bounds"), new GUILayoutOption[0]); + if (GUI.changed) + { + EditorUtility.SetDirty(this.target); + } + } + base.serializedObject.ApplyModifiedProperties(); + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + public void OnSceneGUI() + { + Animation animation = (Animation)this.target; + if (animation && (animation.cullingType == AnimationCullingType.BasedOnClipBounds || animation.cullingType == AnimationCullingType.BasedOnUserBounds)) + { + this.m_BoxEditor.SetAlwaysDisplayHandles(animation.cullingType == AnimationCullingType.BasedOnUserBounds); + Bounds localBounds = animation.localBounds; + Vector3 center = localBounds.center; + Vector3 size = localBounds.size; + if (this.m_BoxEditor.OnSceneGUI(animation.transform, Handles.s_BoundingBoxHandleColor, ref center, ref size)) + { + Undo.RecordObject(animation, "Modified Animation bounds"); + animation.localBounds = new Bounds(center, size); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationEventPopup.cs b/UnityEditor/UnityEditor/AnimationEventPopup.cs new file mode 100644 index 00000000..88100e72 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationEventPopup.cs @@ -0,0 +1,573 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class AnimationEventPopup : EditorWindow + { + public const string kLogicGraphEventFunction = "LogicGraphEvent"; + private const string kAmbiguousPostFix = " (Function Is Ambiguous)"; + private const string kNotSupportedPostFix = " (Function Not Supported)"; + private const string kNoneSelected = "(No Function Selected)"; + private GameObject m_Root; + private AnimationClip m_Clip; + private int m_EventIndex; + private string m_LogicEventName; + private AnimationClipInfoProperties m_ClipInfo; + private EditorWindow m_Owner; + public AnimationClipInfoProperties clipInfo + { + get + { + return this.m_ClipInfo; + } + set + { + this.m_ClipInfo = value; + } + } + private int eventIndex + { + get + { + return this.m_EventIndex; + } + set + { + if (this.m_EventIndex != value) + { + this.m_LogicEventName = string.Empty; + } + this.m_EventIndex = value; + } + } + internal static void InitWindow(AnimationEventPopup popup) + { + popup.minSize = new Vector2(400f, 140f); + popup.maxSize = new Vector2(400f, 140f); + popup.title = EditorGUIUtility.TextContent("UnityEditor.AnimationEventPopup").text; + } + internal static void Edit(GameObject root, AnimationClip clip, int index, EditorWindow owner) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); + AnimationEventPopup animationEventPopup = (array.Length <= 0) ? null : ((AnimationEventPopup)array[0]); + if (animationEventPopup == null) + { + animationEventPopup = EditorWindow.GetWindow(true); + AnimationEventPopup.InitWindow(animationEventPopup); + } + animationEventPopup.m_Root = root; + animationEventPopup.m_Clip = clip; + animationEventPopup.eventIndex = index; + animationEventPopup.m_Owner = owner; + animationEventPopup.Repaint(); + } + internal static void Edit(AnimationClipInfoProperties clipInfo, int index) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); + AnimationEventPopup animationEventPopup = (array.Length <= 0) ? null : ((AnimationEventPopup)array[0]); + if (animationEventPopup == null) + { + animationEventPopup = EditorWindow.GetWindow(true); + AnimationEventPopup.InitWindow(animationEventPopup); + } + animationEventPopup.m_Root = null; + animationEventPopup.m_Clip = null; + animationEventPopup.m_ClipInfo = clipInfo; + animationEventPopup.eventIndex = index; + animationEventPopup.Repaint(); + } + internal static void UpdateSelection(GameObject root, AnimationClip clip, int index, EditorWindow owner) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); + AnimationEventPopup animationEventPopup = (array.Length <= 0) ? null : ((AnimationEventPopup)array[0]); + if (animationEventPopup == null) + { + return; + } + animationEventPopup.m_Root = root; + animationEventPopup.m_Clip = clip; + animationEventPopup.eventIndex = index; + animationEventPopup.m_Owner = owner; + animationEventPopup.Repaint(); + } + internal static int Create(GameObject root, AnimationClip clip, float time, EditorWindow owner) + { + AnimationEvent animationEvent = new AnimationEvent(); + animationEvent.time = time; + AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(clip); + int num = AnimationEventPopup.InsertAnimationEvent(ref animationEvents, clip, animationEvent); + AnimationEventPopup window = EditorWindow.GetWindow(true); + AnimationEventPopup.InitWindow(window); + window.m_Root = root; + window.m_Clip = clip; + window.eventIndex = num; + window.m_Owner = owner; + return num; + } + internal static void ClosePopup() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); + AnimationEventPopup animationEventPopup = (array.Length <= 0) ? null : ((AnimationEventPopup)array[0]); + if (animationEventPopup != null) + { + animationEventPopup.Close(); + } + } + public static string FormatEvent(GameObject root, AnimationEvent evt) + { + if (string.IsNullOrEmpty(evt.functionName)) + { + return "(No Function Selected)"; + } + if (AnimationEventPopup.IsLogicGraphEvent(evt)) + { + return AnimationEventPopup.FormatLogicGraphEvent(evt); + } + if (!AnimationEventPopup.IsSupportedMethodName(evt.functionName)) + { + return evt.functionName + " (Function Not Supported)"; + } + MonoBehaviour[] components = root.GetComponents(); + for (int i = 0; i < components.Length; i++) + { + MonoBehaviour monoBehaviour = components[i]; + if (!(monoBehaviour == null)) + { + Type type = monoBehaviour.GetType(); + if (type != typeof(MonoBehaviour) && (type.BaseType == null || !(type.BaseType.Name == "GraphBehaviour"))) + { + MethodInfo method = type.GetMethod(evt.functionName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + IEnumerable paramTypes = + from p in method.GetParameters() + select p.ParameterType; + return evt.functionName + AnimationEventPopup.FormatEventArguments(paramTypes, evt); + } + } + } + } + return evt.functionName + " (Function Not Supported)"; + } + private static string FormatLogicGraphEvent(AnimationEvent evt) + { + return "LogicGraphEvent" + AnimationEventPopup.FormatEventArguments(new Type[] + { + typeof(string) + }, evt); + } + private static bool IsSupportedMethodName(string name) + { + return !(name == "Main") && !(name == "Start") && !(name == "Awake") && !(name == "Update"); + } + private static string FormatEventArguments(IEnumerable paramTypes, AnimationEvent evt) + { + if (!paramTypes.Any()) + { + return " ( )"; + } + if (paramTypes.Count() > 1) + { + return " (Function Not Supported)"; + } + Type type = paramTypes.First(); + if (type == typeof(string)) + { + return " ( \"" + evt.stringParameter + "\" )"; + } + if (type == typeof(float)) + { + return " ( " + evt.floatParameter + " )"; + } + if (type == typeof(int)) + { + return " ( " + evt.intParameter + " )"; + } + if (type == typeof(int)) + { + return " ( " + evt.intParameter + " )"; + } + if (type.IsEnum) + { + return string.Concat(new string[] + { + " ( ", + type.Name, + ".", + Enum.GetName(type, evt.intParameter), + " )" + }); + } + if (type == typeof(AnimationEvent)) + { + return string.Concat(new object[] + { + " ( ", + evt.floatParameter, + " / ", + evt.intParameter, + " / \"", + evt.stringParameter, + "\" / ", + (!(evt.objectReferenceParameter == null)) ? evt.objectReferenceParameter.name : "null", + " )" + }); + } + if (type.IsSubclassOf(typeof(UnityEngine.Object)) || type == typeof(UnityEngine.Object)) + { + return " ( " + ((!(evt.objectReferenceParameter == null)) ? evt.objectReferenceParameter.name : "null") + " )"; + } + return " (Function Not Supported)"; + } + private static void CollectSupportedMethods(GameObject root, out List supportedMethods, out List supportedMethodsParameter) + { + supportedMethods = new List(); + supportedMethodsParameter = new List(); + MonoBehaviour[] components = root.GetComponents(); + HashSet hashSet = new HashSet(); + MonoBehaviour[] array = components; + for (int i = 0; i < array.Length; i++) + { + MonoBehaviour monoBehaviour = array[i]; + if (!(monoBehaviour == null)) + { + Type type = monoBehaviour.GetType(); + while (type != typeof(MonoBehaviour) && type != null) + { + MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + for (int j = 0; j < methods.Length; j++) + { + MethodInfo methodInfo = methods[j]; + string name = methodInfo.Name; + if (AnimationEventPopup.IsSupportedMethodName(name)) + { + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (parameters.Length <= 1) + { + if (parameters.Length == 1) + { + Type parameterType = parameters[0].ParameterType; + if (parameterType != typeof(string) && parameterType != typeof(float) && parameterType != typeof(int) && parameterType != typeof(AnimationEvent) && parameterType != typeof(UnityEngine.Object) && !parameterType.IsSubclassOf(typeof(UnityEngine.Object)) && !parameterType.IsEnum) + { + goto IL_160; + } + supportedMethodsParameter.Add(parameterType); + } + else + { + supportedMethodsParameter.Add(null); + } + if (supportedMethods.Contains(name)) + { + hashSet.Add(name); + } + supportedMethods.Add(name); + } + } + IL_160:; + } + type = type.BaseType; + } + } + } + foreach (string current in hashSet) + { + for (int k = 0; k < supportedMethods.Count; k++) + { + if (supportedMethods[k].Equals(current)) + { + supportedMethods.RemoveAt(k); + supportedMethodsParameter.RemoveAt(k); + k--; + } + } + } + } + internal static int InsertAnimationEvent(ref AnimationEvent[] events, AnimationClip clip, AnimationEvent evt) + { + Undo.RegisterCompleteObjectUndo(clip, "Add Event"); + int num = events.Length; + for (int i = 0; i < events.Length; i++) + { + if (events[i].time > evt.time) + { + num = i; + break; + } + } + ArrayUtility.Insert(ref events, num, evt); + AnimationUtility.SetAnimationEvents(clip, events); + events = AnimationUtility.GetAnimationEvents(clip); + if (events[num].time != evt.time || events[num].functionName != events[num].functionName) + { + Debug.LogError("Failed insertion"); + } + return num; + } + public void OnGUI() + { + AnimationEvent[] array = null; + if (this.m_Clip != null) + { + array = AnimationUtility.GetAnimationEvents(this.m_Clip); + } + else + { + if (this.m_ClipInfo != null) + { + array = this.m_ClipInfo.GetEvents(); + } + } + if (array == null || this.eventIndex < 0 || this.eventIndex >= array.Length) + { + return; + } + GUI.changed = false; + AnimationEvent animationEvent = array[this.eventIndex]; + if (this.m_Root) + { + List list; + List list2; + AnimationEventPopup.CollectSupportedMethods(this.m_Root, out list, out list2); + List list3 = new List(list.Count); + for (int i = 0; i < list.Count; i++) + { + string str = " ( )"; + if (list2[i] != null) + { + if (list2[i] == typeof(float)) + { + str = " ( float )"; + } + else + { + if (list2[i] == typeof(int)) + { + str = " ( int )"; + } + else + { + str = string.Format(" ( {0} )", list2[i].Name); + } + } + } + list3.Add(list[i] + str); + } + int count = list.Count; + int num = list.IndexOf(animationEvent.functionName); + if (num == -1) + { + num = list.Count; + list.Add(animationEvent.functionName); + if (string.IsNullOrEmpty(animationEvent.functionName)) + { + list3.Add("(No Function Selected)"); + } + else + { + list3.Add(animationEvent.functionName + " (Function Not Supported)"); + } + list2.Add(null); + } + EditorGUIUtility.labelWidth = 130f; + int num2 = num; + num = EditorGUILayout.Popup("Function: ", num, list3.ToArray(), new GUILayoutOption[0]); + if (num2 != num && num != -1 && num != count) + { + animationEvent.functionName = list[num]; + animationEvent.stringParameter = ((!AnimationEventPopup.IsLogicGraphEvent(animationEvent)) ? string.Empty : AnimationEventPopup.GetEventNameForLogicGraphEvent(array, animationEvent)); + } + Type type = list2[num]; + if (type != null) + { + EditorGUILayout.Space(); + if (type == typeof(AnimationEvent)) + { + EditorGUILayout.PrefixLabel("Event Data"); + } + else + { + EditorGUILayout.PrefixLabel("Parameters"); + } + if (AnimationEventPopup.IsLogicGraphEvent(animationEvent)) + { + this.DoEditLogicGraphEventParameters(animationEvent); + } + else + { + AnimationEventPopup.DoEditRegularParameters(animationEvent, type); + } + } + } + else + { + animationEvent.functionName = EditorGUILayout.TextField(new GUIContent("Function"), animationEvent.functionName, new GUILayoutOption[0]); + AnimationEventPopup.DoEditRegularParameters(animationEvent, typeof(AnimationEvent)); + } + if (GUI.changed) + { + if (this.m_Clip != null) + { + Undo.RegisterCompleteObjectUndo(this.m_Clip, "Animation Event Change"); + AnimationUtility.SetAnimationEvents(this.m_Clip, array); + } + else + { + if (this.m_ClipInfo != null) + { + this.m_ClipInfo.SetEvent(this.m_EventIndex, animationEvent); + } + } + } + } + private static bool EscapePressed() + { + return Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; + } + private static bool EnterPressed() + { + return Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return; + } + private void DoEditLogicGraphEventParameters(AnimationEvent evt) + { + if (string.IsNullOrEmpty(this.m_LogicEventName)) + { + this.m_LogicEventName = evt.stringParameter; + } + bool flag = AnimationEventPopup.EnterPressed(); + this.m_LogicEventName = EditorGUILayout.TextField("Event name", this.m_LogicEventName, new GUILayoutOption[0]); + if (this.m_LogicEventName == evt.stringParameter || this.m_LogicEventName.Trim() == string.Empty) + { + return; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Set", EditorStyles.miniButton, new GUILayoutOption[0]) || flag) + { + AnimationEventPopup.RenameAllReferencesToTheLogicGraphAnimationEventInCurrentScene(this.m_Root.GetComponent(typeof(Animation)) as Animation, evt.stringParameter, this.m_LogicEventName); + evt.stringParameter = this.m_LogicEventName; + this.LogicGraphEventParameterEditingDone(evt); + GUI.changed = true; + } + if (GUILayout.Button("Cancel", EditorStyles.miniButton, new GUILayoutOption[0]) || AnimationEventPopup.EscapePressed()) + { + this.LogicGraphEventParameterEditingDone(evt); + } + GUILayout.EndHorizontal(); + } + private static void RenameAllReferencesToTheLogicGraphAnimationEventInCurrentScene(Animation animation, string oldName, string newName) + { + Assembly assembly = ( + from asm in AppDomain.CurrentDomain.GetAssemblies() + where asm.GetName().Name == "UnityEditor.Graphs.LogicGraph" + select asm).FirstOrDefault(); + if (assembly == null) + { + throw new Exception("Could not find the logic graph assembly in loaded assemblies."); + } + Type type = assembly.GetType("UnityEngine.Graphs.LogicGraph.OnAnimationEventNode"); + if (type == null) + { + throw new Exception("Failed to find type 'OnAnimationEventNode'."); + } + MethodInfo method = type.GetMethod("AnimationEventNameChanged"); + if (method == null) + { + throw new Exception("Could not find 'AnimationEventNameChanged' method."); + } + method.Invoke(null, new object[] + { + animation, + oldName, + newName + }); + } + private void LogicGraphEventParameterEditingDone(AnimationEvent evt) + { + GUIUtility.keyboardControl = 0; + this.m_LogicEventName = string.Empty; + Event.current.Use(); + } + private static void DoEditRegularParameters(AnimationEvent evt, Type selectedParameter) + { + if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(float)) + { + evt.floatParameter = EditorGUILayout.FloatField("Float", evt.floatParameter, new GUILayoutOption[0]); + } + if (selectedParameter.IsEnum) + { + evt.intParameter = AnimationEventPopup.EnumPopup("Enum", selectedParameter, evt.intParameter); + } + else + { + if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(int)) + { + evt.intParameter = EditorGUILayout.IntField("Int", evt.intParameter, new GUILayoutOption[0]); + } + } + if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(string)) + { + evt.stringParameter = EditorGUILayout.TextField("String", evt.stringParameter, new GUILayoutOption[0]); + } + if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object)) + { + Type type = typeof(UnityEngine.Object); + if (selectedParameter != typeof(AnimationEvent)) + { + type = selectedParameter; + } + bool allowSceneObjects = false; + evt.objectReferenceParameter = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(type.Name), evt.objectReferenceParameter, type, allowSceneObjects, new GUILayoutOption[0]); + } + } + private static string GetEventNameForLogicGraphEvent(IEnumerable events, AnimationEvent animEvent) + { + for (int i = 1; i < 1000; i++) + { + string name = "LogicGraphEvent" + i; + if (!events.Any((AnimationEvent evt) => AnimationEventPopup.IsLogicGraphEvent(evt) && evt.stringParameter == name)) + { + string text = "LogicGraphEvent" + i; + animEvent.stringParameter = text; + return text; + } + } + return string.Empty; + } + private static void AddLogicGraphEventFunction(List methods, List parameters) + { + methods.Insert(0, "LogicGraphEvent"); + parameters.Insert(0, typeof(string)); + } + private static bool IsLogicGraphEvent(AnimationEvent evt) + { + return evt.functionName == "LogicGraphEvent"; + } + public static int EnumPopup(string label, Type enumType, int selected) + { + if (!enumType.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] names = Enum.GetNames(enumType); + int num = Array.IndexOf(names, Enum.GetName(enumType, selected)); + num = EditorGUILayout.Popup(label, num, names, EditorStyles.popup, new GUILayoutOption[0]); + if (num == -1) + { + return selected; + } + Enum value = (Enum)Enum.Parse(enumType, names[num]); + return Convert.ToInt32(value); + } + private void OnDestroy() + { + if (this.m_Owner) + { + this.m_Owner.Focus(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationEventTimeLine.cs b/UnityEditor/UnityEditor/AnimationEventTimeLine.cs new file mode 100644 index 00000000..1f5cdaa5 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationEventTimeLine.cs @@ -0,0 +1,318 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class AnimationEventTimeLine + { + public class EventComparer : IComparer + { + int IComparer.Compare(object objX, object objY) + { + AnimationEvent animationEvent = (AnimationEvent)objX; + AnimationEvent animationEvent2 = (AnimationEvent)objY; + float time = animationEvent.time; + float time2 = animationEvent2.time; + if (time != time2) + { + return (int)Mathf.Sign(time - time2); + } + int hashCode = animationEvent.GetHashCode(); + int hashCode2 = animationEvent2.GetHashCode(); + return hashCode - hashCode2; + } + } + private class EventLineContextMenuObject + { + public GameObject m_Animated; + public AnimationClip m_Clip; + public float m_Time; + public int m_Index; + public EventLineContextMenuObject(GameObject animated, AnimationClip clip, float time, int index) + { + this.m_Animated = animated; + this.m_Clip = clip; + this.m_Time = time; + this.m_Index = index; + } + } + [NonSerialized] + private AnimationEvent[] m_EventsAtMouseDown; + [NonSerialized] + private float[] m_EventTimes; + private bool[] m_EventsSelected; + private bool m_DirtyTooltip; + private int m_HoverEvent = -1; + private string m_InstantTooltipText; + private Vector2 m_InstantTooltipPoint = Vector2.zero; + private EditorWindow m_Owner; + public AnimationEventTimeLine(EditorWindow owner) + { + this.m_Owner = owner; + } + public void AddEvent(AnimationWindowState state) + { + float time = (float)state.m_Frame / state.frameRate; + int index = AnimationEventPopup.Create(state.m_RootGameObject, state.m_ActiveAnimationClip, time, this.m_Owner); + this.Select(state.m_ActiveAnimationClip, index); + } + public void DeselectAll() + { + this.m_EventsSelected = null; + } + private void Select(AnimationClip clip, int index) + { + this.m_EventsSelected = new bool[AnimationUtility.GetAnimationEvents(clip).Length]; + this.m_EventsSelected[index] = true; + } + public void EventLineGUI(Rect rect, AnimationSelection selection, AnimationWindowState state, CurveEditor curveEditor) + { + AnimationClip activeAnimationClip = state.m_ActiveAnimationClip; + GameObject rootGameObject = state.m_RootGameObject; + GUI.BeginGroup(rect); + Color color = GUI.color; + Rect rect2 = new Rect(0f, 0f, rect.width, rect.height); + float time = (float)Mathf.RoundToInt(state.PixelToTime(Event.current.mousePosition.x, rect) * state.frameRate) / state.frameRate; + if (activeAnimationClip != null) + { + AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(activeAnimationClip); + Texture image = EditorGUIUtility.IconContent("Animation.EventMarker").image; + Rect[] array = new Rect[animationEvents.Length]; + Rect[] array2 = new Rect[animationEvents.Length]; + int num = 1; + int num2 = 0; + for (int i = 0; i < animationEvents.Length; i++) + { + AnimationEvent animationEvent = animationEvents[i]; + if (num2 == 0) + { + num = 1; + while (i + num < animationEvents.Length && animationEvents[i + num].time == animationEvent.time) + { + num++; + } + num2 = num; + } + num2--; + float num3 = Mathf.Floor(state.FrameToPixel(animationEvent.time * activeAnimationClip.frameRate, rect)); + int num4 = 0; + if (num > 1) + { + float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(state.FrameDeltaToPixel(rect) - (float)(image.width * 2))); + num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2))); + } + Rect rect3 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height); + array[i] = rect3; + array2[i] = rect3; + } + if (this.m_DirtyTooltip) + { + if (this.m_HoverEvent >= 0 && this.m_HoverEvent < array.Length) + { + this.m_InstantTooltipText = AnimationEventPopup.FormatEvent(rootGameObject, animationEvents[this.m_HoverEvent]); + this.m_InstantTooltipPoint = new Vector2(array[this.m_HoverEvent].xMin + (float)((int)(array[this.m_HoverEvent].width / 2f)) + rect.x - 30f, rect.yMax); + } + this.m_DirtyTooltip = false; + } + if (this.m_EventsSelected == null || this.m_EventsSelected.Length != animationEvents.Length) + { + this.m_EventsSelected = new bool[animationEvents.Length]; + AnimationEventPopup.ClosePopup(); + } + Vector2 zero = Vector2.zero; + int num6; + float num7; + float num8; + HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref this.m_EventsSelected, null, out num6, out zero, out num7, out num8, GUIStyleX.none); + if (highLevelEvent != HighLevelEvent.None) + { + switch (highLevelEvent) + { + case HighLevelEvent.DoubleClick: + if (num6 != -1) + { + AnimationEventPopup.Edit(rootGameObject, selection.clip, num6, this.m_Owner); + } + else + { + this.EventLineContextMenuAdd(new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, time, -1)); + } + break; + case HighLevelEvent.ContextClick: + { + GenericMenu genericMenu = new GenericMenu(); + AnimationEventTimeLine.EventLineContextMenuObject userData = new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, animationEvents[num6].time, num6); + genericMenu.AddItem(new GUIContent("Edit Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuEdit), userData); + genericMenu.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData); + genericMenu.AddItem(new GUIContent("Delete Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData); + genericMenu.ShowAsContext(); + this.m_InstantTooltipText = null; + this.m_DirtyTooltip = true; + state.Repaint(); + break; + } + case HighLevelEvent.BeginDrag: + this.m_EventsAtMouseDown = animationEvents; + this.m_EventTimes = new float[animationEvents.Length]; + for (int j = 0; j < animationEvents.Length; j++) + { + this.m_EventTimes[j] = animationEvents[j].time; + } + break; + case HighLevelEvent.Drag: + { + for (int k = animationEvents.Length - 1; k >= 0; k--) + { + if (this.m_EventsSelected[k]) + { + AnimationEvent animationEvent2 = this.m_EventsAtMouseDown[k]; + animationEvent2.time = this.m_EventTimes[k] + zero.x * state.PixelDeltaToTime(rect); + animationEvent2.time = Mathf.Max(0f, animationEvent2.time); + animationEvent2.time = (float)Mathf.RoundToInt(animationEvent2.time * activeAnimationClip.frameRate) / activeAnimationClip.frameRate; + } + } + int[] array3 = new int[this.m_EventsSelected.Length]; + for (int l = 0; l < array3.Length; l++) + { + array3[l] = l; + } + Array.Sort(this.m_EventsAtMouseDown, array3, new AnimationEventTimeLine.EventComparer()); + bool[] array4 = (bool[])this.m_EventsSelected.Clone(); + float[] array5 = (float[])this.m_EventTimes.Clone(); + for (int m = 0; m < array3.Length; m++) + { + this.m_EventsSelected[m] = array4[array3[m]]; + this.m_EventTimes[m] = array5[array3[m]]; + } + Undo.RegisterCompleteObjectUndo(activeAnimationClip, "Move Event"); + AnimationUtility.SetAnimationEvents(activeAnimationClip, this.m_EventsAtMouseDown); + this.m_DirtyTooltip = true; + break; + } + case HighLevelEvent.Delete: + this.DeleteEvents(activeAnimationClip, this.m_EventsSelected); + break; + case HighLevelEvent.SelectionChanged: + curveEditor.SelectNone(); + if (num6 != -1) + { + AnimationEventPopup.UpdateSelection(rootGameObject, selection.clip, num6, this.m_Owner); + } + break; + } + } + this.CheckRectsOnMouseMove(rect, animationEvents, array); + } + if (Event.current.type == EventType.ContextClick && rect2.Contains(Event.current.mousePosition) && selection.EnsureClipPresence()) + { + Event.current.Use(); + GenericMenu genericMenu2 = new GenericMenu(); + genericMenu2.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, time, -1)); + genericMenu2.ShowAsContext(); + } + GUI.color = color; + GUI.EndGroup(); + } + public void DrawInstantTooltip(Rect position) + { + if (this.m_InstantTooltipText != null && this.m_InstantTooltipText != string.Empty) + { + GUIStyle gUIStyle = "AnimationEventTooltip"; + Vector2 vector = gUIStyle.CalcSize(new GUIContent(this.m_InstantTooltipText)); + Rect position2 = new Rect(this.m_InstantTooltipPoint.x - 10f, this.m_InstantTooltipPoint.y + 24f, vector.x, vector.y); + if (position2.xMax > position.width) + { + position2.x = position.width - position2.width; + } + GUI.Label(position2, this.m_InstantTooltipText, gUIStyle); + position2 = new Rect(this.m_InstantTooltipPoint.x - 3f, this.m_InstantTooltipPoint.y, 7f, 25f); + GUI.Label(position2, string.Empty, "AnimationEventTooltipArrow"); + } + } + private void DeleteEvents(AnimationClip clip, bool[] deleteIndices) + { + bool flag = false; + List list = new List(AnimationUtility.GetAnimationEvents(clip)); + for (int i = list.Count - 1; i >= 0; i--) + { + if (deleteIndices[i]) + { + list.RemoveAt(i); + flag = true; + } + } + if (flag) + { + AnimationEventPopup.ClosePopup(); + Undo.RegisterCompleteObjectUndo(clip, "Delete Event"); + AnimationUtility.SetAnimationEvents(clip, list.ToArray()); + this.m_EventsSelected = new bool[list.Count]; + this.m_DirtyTooltip = true; + } + } + public void EventLineContextMenuAdd(object obj) + { + AnimationEventTimeLine.EventLineContextMenuObject eventLineContextMenuObject = (AnimationEventTimeLine.EventLineContextMenuObject)obj; + int num = AnimationEventPopup.Create(eventLineContextMenuObject.m_Animated, eventLineContextMenuObject.m_Clip, eventLineContextMenuObject.m_Time, this.m_Owner); + this.Select(eventLineContextMenuObject.m_Clip, num); + this.m_EventsSelected = new bool[AnimationUtility.GetAnimationEvents(eventLineContextMenuObject.m_Clip).Length]; + this.m_EventsSelected[num] = true; + } + public void EventLineContextMenuEdit(object obj) + { + AnimationEventTimeLine.EventLineContextMenuObject eventLineContextMenuObject = (AnimationEventTimeLine.EventLineContextMenuObject)obj; + AnimationEventPopup.Edit(eventLineContextMenuObject.m_Animated, eventLineContextMenuObject.m_Clip, eventLineContextMenuObject.m_Index, this.m_Owner); + this.Select(eventLineContextMenuObject.m_Clip, eventLineContextMenuObject.m_Index); + } + public void EventLineContextMenuDelete(object obj) + { + AnimationEventTimeLine.EventLineContextMenuObject eventLineContextMenuObject = (AnimationEventTimeLine.EventLineContextMenuObject)obj; + AnimationClip clip = eventLineContextMenuObject.m_Clip; + if (clip == null) + { + return; + } + int index = eventLineContextMenuObject.m_Index; + if (this.m_EventsSelected[index]) + { + this.DeleteEvents(clip, this.m_EventsSelected); + } + else + { + bool[] array = new bool[this.m_EventsSelected.Length]; + array[index] = true; + this.DeleteEvents(clip, array); + } + } + private void CheckRectsOnMouseMove(Rect eventLineRect, AnimationEvent[] events, Rect[] hitRects) + { + Vector2 mousePosition = Event.current.mousePosition; + bool flag = false; + if (events.Length == hitRects.Length) + { + for (int i = hitRects.Length - 1; i >= 0; i--) + { + if (hitRects[i].Contains(mousePosition)) + { + flag = true; + if (this.m_HoverEvent != i) + { + this.m_HoverEvent = i; + this.m_InstantTooltipText = events[this.m_HoverEvent].functionName; + this.m_InstantTooltipPoint = new Vector2(hitRects[this.m_HoverEvent].xMin + (float)((int)(hitRects[this.m_HoverEvent].width / 2f)) + eventLineRect.x, eventLineRect.yMax); + this.m_DirtyTooltip = true; + } + } + } + } + if (!flag) + { + this.m_HoverEvent = -1; + this.m_InstantTooltipText = string.Empty; + } + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationHierarchyData.cs b/UnityEditor/UnityEditor/AnimationHierarchyData.cs new file mode 100644 index 00000000..a64295a1 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationHierarchyData.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections; +using UnityEngine; +namespace UnityEditor +{ + internal class AnimationHierarchyData + { + public AnimationWindow animationWindow; + public AnimationSelection animationSelection; + public FoldoutObjectState[] states; + public SerializedStringTable expandedFoldouts + { + get + { + return this.animationWindow.expandedFoldouts; + } + set + { + this.animationWindow.expandedFoldouts = value; + } + } + public bool showAllProperties + { + get + { + return this.animationWindow.showAllProperties; + } + } + public GameObject animated + { + get + { + return this.animationSelection.animatedObject; + } + } + public AnimationClip clip + { + get + { + return this.animationSelection.clip; + } + } + public Hashtable animatedCurves + { + get + { + return this.animationSelection.animatedCurves; + } + } + public Hashtable leftoverCurves + { + get + { + return this.animationSelection.leftoverCurves; + } + } + public Hashtable animatedPaths + { + get + { + return this.animationSelection.animatedPaths; + } + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationMode.cs b/UnityEditor/UnityEditor/AnimationMode.cs new file mode 100644 index 00000000..110dcaa7 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationMode.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class AnimationMode + { + private static Color s_AnimatedPropertyColorLight = new Color(1f, 0.65f, 0.6f, 1f); + private static Color s_AnimatedPropertyColorDark = new Color(1f, 0.55f, 0.5f, 1f); + public static Color animatedPropertyColor + { + get + { + return (!EditorGUIUtility.isProSkin) ? AnimationMode.s_AnimatedPropertyColorLight : AnimationMode.s_AnimatedPropertyColorDark; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsPropertyAnimated(UnityEngine.Object target, string propertyPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopAnimationMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool InAnimationMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StartAnimationMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BeginSampling(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void EndSampling(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SampleAnimationClip(GameObject gameObject, AnimationClip clip, float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AddPropertyModification(EditorCurveBinding binding, PropertyModification modification, bool keepPrefabOverride); + } +} diff --git a/UnityEditor/UnityEditor/AnimationSelection.cs b/UnityEditor/UnityEditor/AnimationSelection.cs new file mode 100644 index 00000000..6bb843e8 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationSelection.cs @@ -0,0 +1,503 @@ +using System; +using System.Collections; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class AnimationSelection + { + private AnimationWindow m_AnimationWindow; + private int m_AnimatedObjectIndex; + private GameObject[] m_AnimatedOptions; + private AnimationClip m_Clip; + private bool m_ClipCanceled; + private FoldoutTree[] m_Trees = new FoldoutTree[0]; + private Hashtable m_AnimatedCurves; + private Hashtable m_AnimatedPaths; + private Hashtable m_LeftoverCurves; + public AnimationWindow animationWindow + { + get + { + return this.m_AnimationWindow; + } + } + public int animatedObjectIndex + { + get + { + return this.m_AnimatedObjectIndex; + } + } + public GameObject animatedObject + { + get + { + return this.animatedOptions[this.m_AnimatedObjectIndex]; + } + } + public GameObject avatarRootObject + { + get + { + if (this.animatedObject) + { + Animator component = this.animatedObject.GetComponent(); + if (component) + { + Transform avatarRoot = component.avatarRoot; + if (avatarRoot) + { + return avatarRoot.gameObject; + } + } + } + return this.animatedObject; + } + } + public GameObject[] animatedOptions + { + get + { + return this.m_AnimatedOptions; + } + } + public bool hasAnimationComponent + { + get + { + return this.animatedObject.GetComponent() != null || this.animatedObject.GetComponent() != null; + } + } + public AnimationClip clip + { + get + { + return this.m_Clip; + } + } + public int clipIndex + { + get + { + return this.GetIndexOfClip(this.m_Clip); + } + } + public bool CanClipAndGameObjectBeEdited + { + get + { + return !(this.m_Clip == null) && (this.m_Clip.hideFlags & HideFlags.NotEditable) == HideFlags.None && this.GameObjectIsAnimatable; + } + } + public bool GameObjectIsAnimatable + { + get + { + return !(this.animatedObject == null) && (this.animatedObject.hideFlags & HideFlags.NotEditable) == HideFlags.None && !EditorUtility.IsPersistent(this.animatedObject); + } + } + public FoldoutTree[] trees + { + get + { + return this.m_Trees; + } + } + public Hashtable animatedCurves + { + get + { + if (this.m_AnimatedCurves == null) + { + this.SetAnimationCurves(); + } + return this.m_AnimatedCurves; + } + } + public Hashtable animatedPaths + { + get + { + if (this.m_AnimatedPaths == null) + { + this.SetAnimationCurves(); + } + return this.m_AnimatedPaths; + } + } + public Hashtable leftoverCurves + { + get + { + return this.m_LeftoverCurves; + } + } + public AnimationSelection(GameObject[] animatedOptions, SerializedStringTable chosenAnimated, SerializedStringTable chosenClip, AnimationWindow editor) + { + this.m_AnimationWindow = editor; + this.m_AnimatedOptions = animatedOptions; + string stringArrayHashCode = AnimationSelection.GetStringArrayHashCode(this.GetAnimatedObjectNames()); + if (!chosenAnimated.Contains(stringArrayHashCode)) + { + chosenAnimated.Set(stringArrayHashCode, animatedOptions.Length - 1); + } + this.m_AnimatedObjectIndex = chosenAnimated.Get(stringArrayHashCode); + this.RefreshChosenClip(chosenClip); + } + public GameObject ShownRoot() + { + if (this.trees.Length < 1) + { + return null; + } + return this.trees[0].rootGameObject; + } + private AnimationClip GetClipAtIndex(int index) + { + if (!this.hasAnimationComponent) + { + return null; + } + AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); + if (index == -1) + { + return null; + } + if (index >= animationClips.Length) + { + return null; + } + return animationClips[index]; + } + private int GetIndexOfClip(AnimationClip clip) + { + if (this.hasAnimationComponent) + { + AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); + for (int i = 0; i < animationClips.Length; i++) + { + if (animationClips[i] == clip) + { + return i; + } + } + } + return -1; + } + private void RefreshChosenClip(SerializedStringTable chosenClip) + { + if (this.hasAnimationComponent) + { + string stringArrayHashCode = AnimationSelection.GetStringArrayHashCode(this.GetClipNames()); + if (!chosenClip.Contains(stringArrayHashCode)) + { + this.m_Clip = null; + AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); + for (int i = 0; i < animationClips.Length; i++) + { + if (animationClips[i] != null) + { + this.m_Clip = animationClips[i]; + break; + } + } + } + else + { + this.m_Clip = this.GetClipAtIndex(chosenClip.Get(stringArrayHashCode)); + } + } + } + private void SetAnimationCurves() + { + this.m_AnimatedCurves = new Hashtable(); + this.m_AnimatedPaths = new Hashtable(); + this.m_LeftoverCurves = new Hashtable(); + if (this.clip != null) + { + EditorCurveBinding[] curveBindings = AnimationUtility.GetCurveBindings(this.clip); + EditorCurveBinding[] array = curveBindings; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding editorCurveBinding = array[i]; + int curveID = CurveUtility.GetCurveID(this.clip, editorCurveBinding); + this.m_AnimatedCurves[curveID] = true; + if (!this.CheckIfPropertyExists(editorCurveBinding)) + { + this.m_LeftoverCurves[editorCurveBinding] = editorCurveBinding; + } + else + { + this.m_AnimatedPaths[CurveUtility.GetPathAndTypeID(editorCurveBinding.path, editorCurveBinding.type)] = true; + string text = editorCurveBinding.path; + while (true) + { + int hashCode = text.GetHashCode(); + if (this.m_AnimatedPaths.Contains(hashCode)) + { + break; + } + this.m_AnimatedPaths[hashCode] = true; + if (text.Length == 0) + { + break; + } + int num = text.LastIndexOf('/'); + if (num > 0) + { + text = text.Substring(0, num); + } + else + { + text = string.Empty; + } + } + } + } + } + } + private bool CheckIfPropertyExists(EditorCurveBinding data) + { + return AnimationUtility.GetEditorCurveValueType(this.animatedObject, data) != null; + } + public void Refresh() + { + this.SetAnimationCurves(); + FoldoutTree[] trees = this.trees; + for (int i = 0; i < trees.Length; i++) + { + FoldoutTree foldoutTree = trees[i]; + foldoutTree.Refresh(this.GetAnimationHierarchyData(foldoutTree)); + } + } + public static void OnGUISelection(AnimationSelection animSel) + { + if (animSel == null) + { + bool enabled = GUI.enabled; + GUI.enabled = false; + GUILayout.Label(string.Empty, EditorStyles.toolbarPopup, new GUILayoutOption[0]); + GUI.enabled = enabled; + return; + } + animSel.m_ClipCanceled = false; + bool flag = false; + string[] clipMenuContent = animSel.GetClipMenuContent(); + int clipIndex = animSel.clipIndex; + int num = EditorGUILayout.Popup(clipIndex, clipMenuContent, EditorStyles.toolbarPopup, new GUILayoutOption[0]); + if (num != clipIndex) + { + AnimationClip animationClip = animSel.GetClipAtIndex(num); + if (animationClip == null) + { + animationClip = animSel.CreateNewClip(); + } + if (animationClip != null) + { + animSel.ChooseClip(animationClip); + flag = true; + } + } + if (flag) + { + GUI.changed = true; + animSel.animationWindow.ReEnterAnimationMode(); + animSel.Refresh(); + } + } + public static string GetStringArrayHashCode(string[] array) + { + string text = string.Empty; + for (int i = 0; i < array.Length; i++) + { + string str = array[i]; + text = text + "|" + str; + } + return text; + } + public static string GetObjectListHashCode(GameObject[] animatedOptions) + { + string[] array = new string[animatedOptions.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = animatedOptions[i].name; + } + return AnimationSelection.GetStringArrayHashCode(array); + } + public string[] GetClipNames() + { + string[] array; + if (this.hasAnimationComponent) + { + AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); + array = new string[animationClips.Length]; + for (int i = 0; i < animationClips.Length; i++) + { + array[i] = CurveUtility.GetClipName(animationClips[i]); + } + } + else + { + array = new string[0]; + } + return array; + } + public string[] GetClipMenuContent() + { + string[] array; + if (this.hasAnimationComponent) + { + string[] clipNames = this.GetClipNames(); + array = ((!this.animationWindow.state.IsEditable) ? new string[clipNames.Length] : new string[clipNames.Length + 2]); + for (int i = 0; i < clipNames.Length; i++) + { + array[i] = clipNames[i]; + } + } + else + { + array = new string[1]; + } + if (this.animationWindow.state.IsEditable) + { + array[array.Length - 1] = "[Create New Clip]"; + } + return array; + } + public string[] GetAnimatedObjectNames() + { + string[] array = new string[this.animatedOptions.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = this.animatedOptions[i].name; + } + return array; + } + public AnimationHierarchyData GetAnimationHierarchyData(FoldoutTree tree) + { + return new AnimationHierarchyData + { + animationWindow = this.m_AnimationWindow, + animationSelection = this, + states = tree.states + }; + } + public void AddTree(FoldoutTree tree) + { + Array.Resize(ref this.m_Trees, this.m_Trees.Length + 1); + this.trees[this.trees.Length - 1] = tree; + } + public bool EnsureClipPresence() + { + if (this.clip == null) + { + if (this.m_ClipCanceled) + { + return false; + } + Vector2 s_EditorScreenPointOffset = GUIUtility.s_EditorScreenPointOffset; + AnimationClip animationClip = this.CreateNewClip(); + GUIUtility.s_EditorScreenPointOffset = s_EditorScreenPointOffset; + if (!(animationClip != null)) + { + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = 0; + this.m_ClipCanceled = true; + return false; + } + this.ChooseClip(animationClip); + this.Refresh(); + } + return true; + } + internal static AnimationClip AllocateAndSetupClip(bool useAnimator) + { + AnimationClip animationClip = new AnimationClip(); + if (useAnimator) + { + AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(animationClip); + animationClipSettings.loopTime = true; + AnimationUtility.SetAnimationClipSettingsNoDirty(animationClip, animationClipSettings); + AnimationUtility.SetAnimationType(animationClip, ModelImporterAnimationType.Generic); + } + return animationClip; + } + private AnimationClip CreateNewClip() + { + bool flag = this.animatedObject.GetComponent() != null || this.animatedObject.GetComponent() == null; + string message = string.Format("Create a new animation for the game object '{0}':", this.animatedObject.name); + string text = EditorUtility.SaveFilePanelInProject("Create New Animation", "New Animation", "anim", message, ProjectWindowUtil.GetActiveFolderPath()); + if (text == string.Empty) + { + return null; + } + AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(flag); + AssetDatabase.CreateAsset(animationClip, text); + this.m_AnimationWindow.EndAnimationMode(); + if (flag) + { + return AnimationSelection.AddClipToAnimatorComponent(this.animatedObject, animationClip); + } + return this.AddClipToAnimationComponent(animationClip); + } + public static AnimationClip AddClipToAnimatorComponent(GameObject animatedObject, AnimationClip newClip) + { + Animator animator = animatedObject.GetComponent(); + if (animator == null) + { + animator = animatedObject.AddComponent(); + } + AnimatorController animatorController = AnimatorController.GetEffectiveAnimatorController(animator); + if (!(animatorController == null)) + { + AnimatorController.AddAnimationClipToController(animatorController, newClip); + return newClip; + } + animatorController = AnimatorController.CreateAnimatorControllerForClip(newClip, animatedObject); + AnimatorController.SetAnimatorController(animator, animatorController); + if (animatorController != null) + { + return newClip; + } + return null; + } + private AnimationClip AddClipToAnimationComponent(AnimationClip newClip) + { + if (this.animatedObject.GetComponent() == null) + { + Animation animation = this.animatedObject.AddComponent(typeof(Animation)) as Animation; + animation.clip = newClip; + } + AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); + Array.Resize(ref animationClips, animationClips.Length + 1); + animationClips[animationClips.Length - 1] = newClip; + AnimationUtility.SetAnimationClips(this.animatedObject.animation, animationClips); + return newClip; + } + private void ChooseClip(AnimationClip newClip) + { + this.ChooseClip(newClip, this.GetIndexOfClip(newClip)); + } + private void ChooseClip(AnimationClip newClip, int newClipIndex) + { + this.m_Clip = newClip; + this.m_AnimationWindow.chosenClip.Set(AnimationSelection.GetStringArrayHashCode(this.GetClipNames()), newClipIndex); + this.m_AnimationWindow.state.m_ActiveAnimationClip = this.m_Clip; + } + public void DrawRightIcon(Texture image, Color color, float width) + { + Color color2 = GUI.color; + GUI.color = color; + Rect iconRect = this.m_AnimationWindow.GetIconRect(width); + iconRect.width = (float)image.width; + GUI.DrawTexture(iconRect, image, ScaleMode.ScaleToFit, true, 1f); + GUI.color = color2; + } + public static string GetPath(Transform t) + { + return AnimationUtility.CalculateTransformPath(t, t.root); + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationUtility.cs b/UnityEditor/UnityEditor/AnimationUtility.cs new file mode 100644 index 00000000..3b27e890 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationUtility.cs @@ -0,0 +1,178 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class AnimationUtility + { + public enum CurveModifiedType + { + CurveDeleted, + CurveModified, + ClipModified + } + public delegate void OnCurveWasModified(AnimationClip clip, EditorCurveBinding binding, AnimationUtility.CurveModifiedType deleted); + public static AnimationUtility.OnCurveWasModified onCurveWasModified; + [Obsolete("GetAnimationClips(Animation) is deprecated. Use GetAnimationClips(GameObject) instead.")] + public static AnimationClip[] GetAnimationClips(Animation component) + { + return AnimationUtility.GetAnimationClips(component.gameObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimationClip[] GetAnimationClips(GameObject gameObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnimationClips(Animation animation, AnimationClip[] clips); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern EditorCurveBinding[] GetAnimatableBindings(GameObject targetObject, GameObject root); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetFloatValue(GameObject root, EditorCurveBinding binding, out float data); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Type GetEditorCurveValueType(GameObject root, EditorCurveBinding binding); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetObjectReferenceValue(GameObject root, EditorCurveBinding binding, out UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetAnimatedObject(GameObject gameObject, EditorCurveBinding binding); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Type PropertyModificationToEditorCurveBinding(PropertyModification modification, GameObject gameObject, out EditorCurveBinding binding); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern EditorCurveBinding[] GetCurveBindings(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern EditorCurveBinding[] GetObjectReferenceCurveBindings(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ObjectReferenceKeyframe[] GetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding, ObjectReferenceKeyframe[] keyframes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimationCurve GetEditorCurve(AnimationClip clip, EditorCurveBinding binding); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetEditorCurve(AnimationClip clip, EditorCurveBinding binding, AnimationCurve curve); + private static void Internal_CallAnimationClipAwake(AnimationClip clip) + { + if (AnimationUtility.onCurveWasModified != null) + { + AnimationUtility.onCurveWasModified(clip, default(EditorCurveBinding), AnimationUtility.CurveModifiedType.ClipModified); + } + } + public static void SetEditorCurve(AnimationClip clip, EditorCurveBinding binding, AnimationCurve curve) + { + AnimationUtility.Internal_SetEditorCurve(clip, binding, curve); + if (AnimationUtility.onCurveWasModified != null) + { + AnimationUtility.onCurveWasModified(clip, binding, (curve == null) ? AnimationUtility.CurveModifiedType.CurveDeleted : AnimationUtility.CurveModifiedType.CurveModified); + } + } + public static void SetObjectReferenceCurve(AnimationClip clip, EditorCurveBinding binding, ObjectReferenceKeyframe[] keyframes) + { + AnimationUtility.Internal_SetObjectReferenceCurve(clip, binding, keyframes); + if (AnimationUtility.onCurveWasModified != null) + { + AnimationUtility.onCurveWasModified(clip, binding, (keyframes == null) ? AnimationUtility.CurveModifiedType.CurveDeleted : AnimationUtility.CurveModifiedType.CurveModified); + } + } + [Obsolete("GetAllCurves is deprecated. Use GetCurveBindings and GetObjectReferenceCurveBindings instead."), ExcludeFromDocs] + public static AnimationClipCurveData[] GetAllCurves(AnimationClip clip) + { + bool includeCurveData = true; + return AnimationUtility.GetAllCurves(clip, includeCurveData); + } + public static AnimationClipCurveData[] GetAllCurves(AnimationClip clip, [DefaultValue("true")] bool includeCurveData) + { + EditorCurveBinding[] curveBindings = AnimationUtility.GetCurveBindings(clip); + AnimationClipCurveData[] array = new AnimationClipCurveData[curveBindings.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = new AnimationClipCurveData(curveBindings[i]); + if (includeCurveData) + { + array[i].curve = AnimationUtility.GetEditorCurve(clip, curveBindings[i]); + } + } + return array; + } + [Obsolete("This overload is deprecated. Use the one with EditorCurveBinding instead.")] + public static bool GetFloatValue(GameObject root, string relativePath, Type type, string propertyName, out float data) + { + return AnimationUtility.GetFloatValue(root, EditorCurveBinding.FloatCurve(relativePath, type, propertyName), out data); + } + [Obsolete("This overload is deprecated. Use the one with EditorCurveBinding instead.")] + public static void SetEditorCurve(AnimationClip clip, string relativePath, Type type, string propertyName, AnimationCurve curve) + { + AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(relativePath, type, propertyName), curve); + } + [Obsolete("This overload is deprecated. Use the one with EditorCurveBinding instead.")] + public static AnimationCurve GetEditorCurve(AnimationClip clip, string relativePath, Type type, string propertyName) + { + return AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(relativePath, type, propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimationEvent[] GetAnimationEvents(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnimationEvents(AnimationClip clip, AnimationEvent[] events); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CalculateTransformPath(Transform targetTransform, Transform root); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimationClipSettings GetAnimationClipSettings(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetAnimationClipSettings(AnimationClip clip, AnimationClipSettings srcClipInfo); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetAnimationClipSettingsNoDirty(AnimationClip clip, AnimationClipSettings srcClipInfo); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsValidPolynomialCurve(AnimationCurve curve); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ConstrainToPolynomialCurve(AnimationCurve curve); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CurveSupportsProcedural(AnimationCurve curve); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern ModelImporterAnimationType GetAnimationType(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnimationType(AnimationClip clip, ModelImporterAnimationType type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AnimationClipStats GetAnimationClipStats(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasMotionCurves(AnimationClip clip); + [Obsolete("Use AnimationMode.InAnimationMode instead")] + public static bool InAnimationMode() + { + return AnimationMode.InAnimationMode(); + } + [Obsolete("Use AnimationMode.StartAnimationmode instead")] + public static void StartAnimationMode(UnityEngine.Object[] objects) + { + Debug.LogWarning("AnimationUtility.StartAnimationMode is deprecated. Use AnimationMode.StartAnimationMode with the new APIs. The objects passed to this function will no longer be reverted automatically. See AnimationMode.AddPropertyModification"); + AnimationMode.StartAnimationMode(); + } + [Obsolete("Use AnimationMode.StopAnimationMode instead")] + public static void StopAnimationMode() + { + AnimationMode.StopAnimationMode(); + } + } +} diff --git a/UnityEditor/UnityEditor/AnimationWindow.cs b/UnityEditor/UnityEditor/AnimationWindow.cs new file mode 100644 index 00000000..40dc87f9 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimationWindow.cs @@ -0,0 +1,1603 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AnimationWindow : EditorWindow, TimeUpdater, CurveUpdater + { + internal class Styles + { + public Texture2D pointIcon = EditorGUIUtility.LoadIcon("animationkeyframe"); + public GUIContent playContent = EditorGUIUtility.IconContent("Animation.Play"); + public GUIContent recordContent = EditorGUIUtility.IconContent("Animation.Record"); + public GUIContent prevKeyContent = EditorGUIUtility.IconContent("Animation.PrevKey"); + public GUIContent nextKeyContent = EditorGUIUtility.IconContent("Animation.NextKey"); + public GUIContent addKeyframeContent = EditorGUIUtility.IconContent("Animation.AddKeyframe"); + public GUIContent addEventContent = EditorGUIUtility.IconContent("Animation.AddEvent"); + public GUIStyle curveEditorBackground = "AnimationCurveEditorBackground"; + public GUIStyle eventBackground = "AnimationEventBackground"; + public GUIStyle keyframeBackground = "AnimationKeyframeBackground"; + public GUIStyle rowOdd = "AnimationRowEven"; + public GUIStyle rowEven = "AnimationRowOdd"; + public GUIStyle TimelineTick = "AnimationTimelineTick"; + public GUIStyle miniToolbar = new GUIStyle(EditorStyles.toolbar); + public GUIStyle miniToolbarButton = new GUIStyle(EditorStyles.toolbarButton); + public GUIStyle toolbarLabel = new GUIStyle(EditorStyles.toolbarPopup); + public Styles() + { + this.toolbarLabel.normal.background = null; + this.miniToolbarButton.padding.top = 0; + this.miniToolbarButton.padding.bottom = 3; + } + } + internal const int kTickRulerDistMin = 3; + internal const int kTickRulerDistFull = 80; + internal const int kTickRulerDistLabel = 40; + internal const float kTickRulerHeightMax = 0.7f; + internal const float kTickRulerFatThreshold = 0.5f; + internal const int kIntFieldWidth = 35; + internal const int kButtonWidth = 30; + internal const int kAnimationHeight = 15; + internal const int kTimeRulerHeight = 17; + internal const int kEventLineHeight = 18; + internal const int kKeyframeLineHeight = 15; + internal const int kHierarchyLeftMargin = 2; + internal const int kHierarchyFieldWidth = 45; + internal const int kHierarchyIconWidth = 11; + internal const int kHierarchyIconButtonWidth = 22; + internal const int kHierarchyIconHeight = 11; + internal const int kHierarchyGameobjectHeight = 15; + internal const int kHierarchyComponentHeight = 15; + internal const int kHierarchyPropertyHeight = 12; + internal const int kHierarchyAnimationSpacingHeight = 15; + internal const int kFoldoutArrowWidth = 15; + internal const int kIconWidth = 10; + internal const int kSliderThickness = 15; + internal const int kSamplesLabelWidth = 45; + internal const float kCurveEditorPlayheadAlpha = 0.6f; + private static List s_AnimationWindows = new List(); + private static bool s_LastShowCurveEditor; + internal static int vPosition; + internal static bool kEvenRow; + internal static int s_StartDragFrame = 0; + internal static PrefColor kEulerXColor = new PrefColor("Testing/EulerX", 1f, 0f, 1f, 1f); + internal static PrefColor kEulerYColor = new PrefColor("Testing/EulerY", 1f, 1f, 0f, 1f); + internal static PrefColor kEulerZColor = new PrefColor("Testing/EulerZ", 0f, 1f, 1f, 1f); + internal static PrefColor kAnimatedColor = new PrefColor("Testing/AnimatedObject", 0f, 0f, 0f, 0.3f); + internal static PrefKey kAnimationPrevFrame = new PrefKey("Animation/Previous Frame", ","); + internal static PrefKey kAnimationNextFrame = new PrefKey("Animation/Next Frame", "."); + internal static PrefKey kAnimationPrevKeyframe = new PrefKey("Animation/Previous Keyframe", "&,"); + internal static PrefKey kAnimationNextKeyframe = new PrefKey("Animation/Next Keyframe", "&."); + internal static PrefKey kAnimationRecordKeyframe = new PrefKey("Animation/Record Keyframe", "k"); + internal static PrefKey kAnimationShowCurvesToggle = new PrefKey("Animation/Show curves", "c"); + [SerializeField] + private SerializedStringTable m_ExpandedFoldouts; + [SerializeField] + private SerializedStringTable m_ChosenAnimated; + [SerializeField] + private SerializedStringTable m_ChosenClip; + [SerializeField] + private bool m_ShowAllProperties = true; + [SerializeField] + private AnimationEventTimeLine m_AnimationEventTimeLine; + private AnimationWindowHierarchy m_Hierarchy; + private DopeSheetEditor m_DopeSheetEditor; + private CurveEditor m_CurveEditor; + public static AnimationSelection[] m_Selected; + [NonSerialized] + private CurveState[] m_ShownProperties = new CurveState[0]; + [NonSerialized] + private bool[] m_SelectedProperties = new bool[0]; + private int[] m_EditedCurves = new int[0]; + private Vector2 m_PropertyViewScroll; + private bool m_CurveEditorToggleChanged; + private bool m_AutoRecord; + private bool m_PlayFromNoMode; + private float m_PrevRealTime; + private CurveMenuManager m_MenuManager; + private bool m_PerformFrameSelectedOnCurveEditor = true; + private bool m_PerformFrameSelectedOnCurveEditorHorizontally; + internal static AnimationWindow.Styles ms_Styles; + private SplitterState m_HorizontalSplitter; + private float indentToContent + { + get + { + return 2f + EditorGUI.indent + 15f; + } + } + [SerializeField] + public AnimationWindowState state + { + get; + set; + } + public SerializedStringTable expandedFoldouts + { + get + { + return this.m_ExpandedFoldouts; + } + set + { + this.m_ExpandedFoldouts = value; + } + } + public SerializedStringTable chosenAnimated + { + get + { + return this.m_ChosenAnimated; + } + set + { + this.m_ChosenAnimated = value; + } + } + public SerializedStringTable chosenClip + { + get + { + return this.m_ChosenClip; + } + set + { + this.m_ChosenClip = value; + } + } + public bool showAllProperties + { + get + { + return this.m_ShowAllProperties; + } + } + public float time + { + get + { + return this.state.FrameToTime((float)this.state.m_Frame); + } + } + public float timeFloor + { + get + { + return this.state.FrameToTimeFloor((float)this.state.m_Frame); + } + } + public float timeCeiling + { + get + { + return this.state.FrameToTimeCeiling((float)this.state.m_Frame); + } + } + public static List GetAllAnimationWindows() + { + return AnimationWindow.s_AnimationWindows; + } + internal Rect GetFoldoutRect(float width) + { + return new Rect(2f, (float)AnimationWindow.vPosition, width - 2f - 22f, 15f); + } + internal Rect GetFoldoutTextRect(float width) + { + float indentToContent = this.indentToContent; + return new Rect(indentToContent, (float)AnimationWindow.vPosition, width - indentToContent - 22f, 15f); + } + internal Vector2 GetPropertyPos(float width) + { + return new Vector2(this.indentToContent + 10f, (float)AnimationWindow.vPosition); + } + internal Rect GetPropertyLabelRect(float width) + { + return this.GetPropertyLabelRect(width, this.indentToContent + 10f); + } + internal Rect GetPropertyLabelRect(float width, float pixelIndent) + { + return new Rect(pixelIndent, (float)(AnimationWindow.vPosition - 3), width - pixelIndent - 22f - 45f - 15f, 14f); + } + internal Rect GetPropertySelectionRect(float width) + { + return new Rect(0f, (float)AnimationWindow.vPosition, width - 22f - 45f - 15f, 12f); + } + internal Rect GetFieldRect(float width) + { + return new Rect(width - 22f - 45f - 5f, (float)AnimationWindow.vPosition, 45f, 12f); + } + internal Rect GetIconRect(float width) + { + return new Rect(width - 22f + 2f, (float)AnimationWindow.vPosition, 11f, 12f); + } + internal Rect GetIconButtonRect(float width) + { + return new Rect(width - 22f, (float)AnimationWindow.vPosition, 22f, 12f); + } + internal void DrawRowBackground(int width, int height) + { + this.DrawRowBackground(width, height, false); + } + internal void DrawRowBackground(int width, int height, bool selected) + { + AnimationWindow.kEvenRow = !AnimationWindow.kEvenRow; + GUIStyle gUIStyle = (!AnimationWindow.kEvenRow) ? AnimationWindow.ms_Styles.rowOdd : AnimationWindow.ms_Styles.rowEven; + gUIStyle.Draw(new Rect(0f, (float)AnimationWindow.vPosition, (float)width, (float)height), false, false, selected, false); + } + public void SetDirtyCurves() + { + this.state.m_CurveEditorIsDirty = true; + } + private void ToggleAnimationMode() + { + if (AnimationMode.InAnimationMode()) + { + this.EndAnimationMode(); + } + else + { + this.BeginAnimationMode(true); + } + if (Toolbar.get != null) + { + Toolbar.get.Repaint(); + } + } + public bool EnsureAnimationMode() + { + return AnimationMode.InAnimationMode() || this.BeginAnimationMode(true); + } + public void ReEnterAnimationMode() + { + if (AnimationMode.InAnimationMode()) + { + int frame = this.state.m_Frame; + this.EndAnimationMode(); + this.state.m_Frame = frame; + this.BeginAnimationMode(false); + } + } + public bool AllHaveClips() + { + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + if (animationSelection.clip == null) + { + return false; + } + } + return true; + } + public static bool EnsureAllHaveClips() + { + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + if (!animationSelection.EnsureClipPresence()) + { + return false; + } + } + return true; + } + public bool SelectionIsActive() + { + return AnimationWindow.m_Selected != null && AnimationWindow.m_Selected.Length != 0 && AnimationWindow.m_Selected[0] != null && !(AnimationWindow.m_Selected[0].clip == null); + } + public bool BeginAnimationMode(bool askUserIfMissingClips) + { + if (AnimationWindow.m_Selected.Length == 0 || !AnimationWindow.m_Selected[0].GameObjectIsAnimatable) + { + return false; + } + if (!askUserIfMissingClips && !this.AllHaveClips()) + { + return false; + } + if (askUserIfMissingClips && !AnimationWindow.EnsureAllHaveClips()) + { + return false; + } + List list = new List(); + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + UnityEngine.Object gameObject = animationSelection.animatedObject.transform.root.gameObject; + if (!list.Contains(gameObject)) + { + list.Add(gameObject); + } + } + AnimationMode.StartAnimationMode(); + this.ResampleAnimation(); + this.SetAutoRecordMode(true); + this.SetDirtyCurves(); + Tools.RepaintAllToolViews(); + return true; + } + public void EndAnimationMode() + { + if (!AnimationMode.InAnimationMode()) + { + return; + } + if (this.state.m_AnimationIsPlaying) + { + this.Stop(); + } + this.state.m_Frame = 0; + AnimationMode.StopAnimationMode(); + this.SetDirtyCurves(); + Tools.RepaintAllToolViews(); + } + private void SetPlayMode(bool play) + { + if (play != this.state.m_AnimationIsPlaying) + { + if (this.state.m_AnimationIsPlaying) + { + this.Stop(); + } + else + { + this.Play(); + } + } + } + private void Play() + { + bool playFromNoMode = !AnimationMode.InAnimationMode(); + if (!this.EnsureAnimationMode()) + { + return; + } + this.m_PlayFromNoMode = playFromNoMode; + this.state.m_PlayTime = Mathf.Max(new float[] + { + 0f, + this.state.minTime, + this.state.GetTimeSeconds() + }); + this.state.m_AnimationIsPlaying = true; + this.m_PrevRealTime = Time.realtimeSinceStartup; + } + private void Stop() + { + this.state.m_Frame = Mathf.RoundToInt(this.state.m_PlayTime * this.state.frameRate); + this.state.m_AnimationIsPlaying = false; + if (this.m_PlayFromNoMode) + { + this.EndAnimationMode(); + } + else + { + this.ReEnterAnimationMode(); + } + this.m_PlayFromNoMode = false; + } + private void Update() + { + if (this.state == null) + { + return; + } + if (this.state.m_AnimationIsPlaying) + { + if (!this.SelectionIsActive()) + { + return; + } + float num = Time.realtimeSinceStartup - this.m_PrevRealTime; + float num2 = 0f; + float length = this.state.m_ActiveAnimationClip.length; + this.state.m_PlayTime += num; + if (this.state.m_PlayTime > length) + { + this.state.m_PlayTime = num2; + } + this.state.m_PlayTime = Mathf.Clamp(this.state.m_PlayTime, num2, length); + this.m_PrevRealTime = Time.realtimeSinceStartup; + this.state.m_Frame = Mathf.RoundToInt(this.state.m_PlayTime * this.state.frameRate); + this.ResampleAnimation(); + base.Repaint(); + } + if (this.m_DopeSheetEditor != null && this.m_DopeSheetEditor.m_SpritePreviewLoading) + { + base.Repaint(); + } + } + private void Next() + { + List list = (!this.state.m_ShowCurveEditor) ? this.state.allCurves : this.state.activeCurves; + this.state.m_PlayTime = this.state.SnapToFrame(AnimationWindowUtility.GetNextKeyframeTime(list.ToArray(), this.state.FrameToTime((float)this.state.m_Frame), this.state.frameRate)); + this.state.m_Frame = this.state.TimeToFrameFloor(this.state.m_PlayTime); + this.PreviewFrame(this.state.m_Frame); + } + private void Prev() + { + List list = (!this.state.m_ShowCurveEditor) ? this.state.allCurves : this.state.activeCurves; + this.state.m_PlayTime = this.state.SnapToFrame(AnimationWindowUtility.GetPreviousKeyframeTime(list.ToArray(), this.state.FrameToTime((float)this.state.m_Frame), this.state.frameRate)); + this.state.m_Frame = this.state.TimeToFrameFloor(this.state.m_PlayTime); + this.PreviewFrame(this.state.m_Frame); + } + public void PreviewFrame(int frame) + { + if (!this.EnsureAnimationMode()) + { + return; + } + this.state.m_Frame = frame; + this.ResampleAnimation(); + } + private void UndoRedoPerformed() + { + if (AnimationMode.InAnimationMode()) + { + this.PreviewFrame(this.state.m_Frame); + } + this.SetDirtyCurves(); + base.Repaint(); + } + public bool GetAutoRecordMode() + { + return this.m_AutoRecord; + } + private UndoPropertyModification[] PostprocessAnimationRecordingModifications(UndoPropertyModification[] modifications) + { + return AnimationRecording.Process(this.state, modifications); + } + public void SetAutoRecordMode(bool record) + { + if (this.m_AutoRecord != record) + { + if (record) + { + record = AnimationWindow.EnsureAllHaveClips(); + Undo.postprocessModifications = (Undo.PostprocessModifications)Delegate.Combine(Undo.postprocessModifications, new Undo.PostprocessModifications(this.PostprocessAnimationRecordingModifications)); + } + else + { + Undo.postprocessModifications = (Undo.PostprocessModifications)Delegate.Remove(Undo.postprocessModifications, new Undo.PostprocessModifications(this.PostprocessAnimationRecordingModifications)); + } + this.m_AutoRecord = record; + if (this.m_AutoRecord) + { + this.EnsureAnimationMode(); + } + } + } + private bool IsLinked(CurveState state, bool onlyLinkEuler) + { + return state.type == typeof(Transform) && (!onlyLinkEuler || state.propertyName.StartsWith("localEulerAngles.")); + } + private bool AnyPropertiesSelected() + { + bool[] selectedProperties = this.m_SelectedProperties; + for (int i = 0; i < selectedProperties.Length; i++) + { + bool flag = selectedProperties[i]; + if (flag) + { + return true; + } + } + return false; + } + private void InitSelection() + { + this.ClearShownProperties(); + this.GenerateAnimationSelections(); + this.EvaluateFramerate(); + this.SetDirtyCurves(); + if (this.state.m_ActiveAnimationClip != null || this.state.m_ActiveGameObject != null) + { + base.Repaint(); + } + } + private void RefreshAnimationSelections() + { + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + animationSelection.Refresh(); + } + } + private AnimationSelection GetOrAddAnimationSelectionWithObjects(GameObject[] animatedOptions, List animSelected) + { + AnimationSelection animationSelection = null; + string objectListHashCode = AnimationSelection.GetObjectListHashCode(animatedOptions); + foreach (AnimationSelection current in animSelected) + { + if (AnimationSelection.GetObjectListHashCode(current.animatedOptions) == objectListHashCode) + { + animationSelection = current; + break; + } + } + if (animationSelection == null) + { + animationSelection = new AnimationSelection(animatedOptions, this.m_ChosenAnimated, this.m_ChosenClip, this); + animSelected.Add(animationSelection); + } + return animationSelection; + } + private GameObject[] GetAllParents(Transform tr) + { + List list = new List(); + list.Add(tr.gameObject); + while (tr != tr.root) + { + tr = tr.parent; + list.Add(tr.gameObject); + } + list.Reverse(); + return list.ToArray(); + } + private GameObject[] GetAnimationComponentsInAllParents(Transform tr) + { + List list = new List(); + while (true) + { + if (tr.animation || tr.GetComponent()) + { + list.Add(tr.gameObject); + } + if (tr == tr.root) + { + break; + } + tr = tr.parent; + } + list.Reverse(); + return list.ToArray(); + } + private GameObject[] GetTrackedGameObjects() + { + List list = new List(); + if (AnimationWindow.m_Selected.Length > 0) + { + FoldoutTree foldoutTree = AnimationWindow.m_Selected[0].trees[0]; + for (int i = 0; i < foldoutTree.states.Length; i++) + { + GameObject obj = foldoutTree.states[i].obj; + if (obj != null) + { + list.Add(obj); + } + } + } + return list.ToArray(); + } + private void GenerateAnimationSelections() + { + bool flag = AnimationMode.InAnimationMode(); + bool flag2 = false; + int frame = this.state.m_Frame; + this.EndAnimationMode(); + List list = new List(); + GameObject gameObject = (!(Selection.activeGameObject != null)) ? this.state.m_ActiveGameObject : Selection.activeGameObject; + Transform transform = (!gameObject) ? null : gameObject.transform; + if (transform == null) + { + transform = ((!(this.state.m_RootGameObject != null)) ? null : this.state.m_RootGameObject.transform); + this.state.m_ActiveGameObject = this.state.m_RootGameObject; + this.state.refresh = AnimationWindowState.RefreshType.Everything; + } + if (transform != null) + { + GameObject[] array = this.GetAnimationComponentsInAllParents(transform); + if (array.Length == 0) + { + array = this.GetAllParents(transform); + } + AnimationSelection orAddAnimationSelectionWithObjects = this.GetOrAddAnimationSelectionWithObjects(array, list); + if (AnimationWindow.m_Selected != null) + { + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + if (animationSelection.animatedObject == orAddAnimationSelectionWithObjects.animatedObject) + { + flag2 = true; + } + } + } + FoldoutTree tree = new FoldoutTree(transform, this.m_ExpandedFoldouts); + orAddAnimationSelectionWithObjects.AddTree(tree); + } + AnimationWindow.m_Selected = list.ToArray(); + if (AnimationWindow.m_Selected != null && AnimationWindow.m_Selected.Length > 0) + { + if (Selection.activeGameObject != null) + { + this.state.m_ActiveGameObject = Selection.activeGameObject; + } + this.state.m_ActiveAnimationClip = AnimationWindow.m_Selected[0].clip; + this.state.m_RootGameObject = AnimationWindow.m_Selected[0].avatarRootObject; + this.state.m_AnimatedGameObject = AnimationWindow.m_Selected[0].animatedObject; + } + else + { + this.state.m_ActiveAnimationClip = null; + this.state.m_RootGameObject = null; + this.state.m_AnimatedGameObject = null; + this.state.m_ActiveGameObject = null; + this.state.refresh = AnimationWindowState.RefreshType.Everything; + } + if (flag && flag2) + { + this.state.m_Frame = frame; + this.BeginAnimationMode(false); + } + if (!flag2) + { + AnimationEventPopup.ClosePopup(); + this.m_AnimationEventTimeLine.DeselectAll(); + } + } + public void UpdateFrame(int frame) + { + if (this.state.m_AnimationIsPlaying || !AnimationMode.InAnimationMode()) + { + return; + } + this.PreviewFrame(frame); + } + public void UpdateTime(float time) + { + if (this.state.m_AnimationIsPlaying || !AnimationMode.InAnimationMode()) + { + return; + } + this.state.m_Frame = Mathf.RoundToInt(this.state.TimeToFrame(time)); + this.PreviewFrame(this.state.m_Frame); + } + public void UpdateCurves(List curveIds, string undoText) + { + for (int i = 0; i < this.m_ShownProperties.Length; i++) + { + CurveState curveState = this.m_ShownProperties[i]; + if (curveIds.Contains(curveState.GetID())) + { + if (!curveState.animated) + { + curveState.animationSelection.EnsureClipPresence(); + } + if (curveState.clip == null) + { + Debug.LogError("clip is null"); + } + curveState.SaveCurve(curveState.curve); + } + } + this.SetDirtyCurves(); + } + private void ResampleAnimation() + { + if (!this.EnsureAnimationMode()) + { + return; + } + Undo.FlushUndoRecordObjects(); + AnimationMode.BeginSampling(); + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + AnimationClip clip = animationSelection.clip; + if (!(clip == null)) + { + GameObject animatedObject = animationSelection.animatedObject; + if (!(animatedObject == null)) + { + AnimationMode.SampleAnimationClip(animatedObject, clip, this.state.GetTimeSeconds()); + } + } + } + AnimationMode.EndSampling(); + SceneView.RepaintAll(); + } + private bool EvaluateFramerate() + { + if (AnimationWindow.m_Selected.Length == 0) + { + this.state.frameRate = Mathf.Abs(this.state.frameRate); + return true; + } + float num = Mathf.Abs(this.state.frameRate); + int num2 = 0; + float a = 0f; + bool flag = true; + AnimationSelection[] selected = AnimationWindow.m_Selected; + for (int i = 0; i < selected.Length; i++) + { + AnimationSelection animationSelection = selected[i]; + if (animationSelection.clip != null) + { + a = Mathf.Max(a, animationSelection.clip.length); + if (num2 == 0) + { + num2 = Mathf.RoundToInt(animationSelection.clip.frameRate); + } + else + { + if (animationSelection.clip.frameRate != (float)num2) + { + flag = false; + break; + } + } + } + } + if (num2 == 0) + { + num2 = 60; + } + if (!flag) + { + this.state.frameRate = -num; + return false; + } + if (this.state.frameRate != (float)num2) + { + this.state.frameRate = (float)num2; + } + float num3 = this.state.frameRate / num; + this.state.m_Frame = Mathf.RoundToInt(num3 * (float)this.state.m_Frame); + this.m_CurveEditor.hTicks.SetTickModulosForFrameRate(this.state.frameRate); + return true; + } + private void ClearShownProperties() + { + this.m_ShownProperties = new CurveState[0]; + this.m_EditedCurves = new int[0]; + this.m_SelectedProperties = new bool[0]; + this.m_CurveEditor.animationCurves = new CurveWrapper[0]; + CurveRendererCache.ClearCurveRendererCache(); + } + public void RefreshShownCurves(bool forceUpdate) + { + this.state.m_CurveEditorIsDirty = false; + if (!this.SelectionIsActive()) + { + this.ClearShownProperties(); + return; + } + if (this.state.m_ShowCurveEditor || forceUpdate) + { + this.SetupEditorCurvesHack(); + } + else + { + this.ClearShownProperties(); + } + this.EvaluateFramerate(); + this.m_CurveEditor.invSnap = this.state.frameRate; + bool flag = this.AnyPropertiesSelected(); + CurveWrapper[] array = new CurveWrapper[this.m_EditedCurves.Length]; + for (int i = 0; i < array.Length; i++) + { + CurveState curveState = this.m_ShownProperties[this.m_EditedCurves[i]]; + array[i] = new CurveWrapper(); + array[i].id = curveState.GetID(); + if (this.IsLinked(curveState, true)) + { + array[i].groupId = curveState.GetGroupID(); + } + else + { + array[i].groupId = -1; + } + array[i].color = curveState.color; + array[i].hidden = (flag && !this.m_SelectedProperties[this.m_EditedCurves[i]]); + if (array[i].readOnly) + { + array[i].color.a = 0.3f; + } + array[i].renderer = CurveRendererCache.GetCurveRenderer(curveState.clip, curveState.curveBinding); + array[i].renderer.SetWrap((!curveState.clip.isLooping) ? WrapMode.Once : WrapMode.Loop); + array[i].renderer.SetCustomRange(0f, curveState.clip.length); + } + this.m_CurveEditor.animationCurves = array; + if (AnimationMode.InAnimationMode() && GUI.changed) + { + this.ResampleAnimation(); + } + } + public void SetupEditorCurvesHack() + { + if (this.SelectionIsActive()) + { + List list = new List(); + List activeCurves = this.state.activeCurves; + foreach (AnimationWindowCurve current in activeCurves) + { + if (!current.isPPtrCurve) + { + CurveState curveState = new CurveState(current.binding); + curveState.animationSelection = AnimationWindow.m_Selected[0]; + curveState.animated = true; + curveState.color = CurveUtility.GetPropertyColor(curveState.curveBinding.propertyName); + list.Add(curveState); + } + } + this.m_ShownProperties = list.ToArray(); + this.m_EditedCurves = new int[this.m_ShownProperties.Length]; + for (int i = 0; i < this.m_EditedCurves.Length; i++) + { + this.m_EditedCurves[i] = i; + } + } + else + { + this.m_EditedCurves = new int[0]; + this.m_ShownProperties = new CurveState[0]; + } + } + private void FrameSelected() + { + this.m_PerformFrameSelectedOnCurveEditor = true; + } + private void DopeSheetGUI(Rect position) + { + this.m_DopeSheetEditor.rect = position; + position.height -= 15f; + this.m_DopeSheetEditor.RecalculateBounds(); + this.m_DopeSheetEditor.BeginViewGUI(); + this.m_DopeSheetEditor.OnGUI(position, this.state.m_hierarchyState.scrollPos * -1f); + Rect position2 = new Rect(position.xMax, position.yMin, 16f, position.height); + float bottomValue = Mathf.Max(this.m_DopeSheetEditor.contentHeight, position.height); + this.state.m_hierarchyState.scrollPos.y = GUI.VerticalScrollbar(position2, this.state.m_hierarchyState.scrollPos.y, position.height, 0f, bottomValue); + this.m_DopeSheetEditor.EndViewGUI(); + } + public void TimeLineGUI(Rect rect, bool onlyDopesheetLines, bool sparseLines, bool resetKeyboardControl) + { + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition) && resetKeyboardControl) + { + GUIUtility.keyboardControl = 0; + } + Color color = GUI.color; + GUI.BeginGroup(rect); + rect.x = 0f; + rect.y = 0f; + if (Event.current.type != EventType.Repaint) + { + GUI.EndGroup(); + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + Color backgroundColor = GUI.backgroundColor; + if (sparseLines) + { + this.m_CurveEditor.hTicks.SetTickStrengths((float)this.m_CurveEditor.settings.hTickStyle.distMin, (float)this.m_CurveEditor.settings.hTickStyle.distFull, true); + } + else + { + this.m_CurveEditor.hTicks.SetTickStrengths(3f, 80f, true); + } + Color color2 = this.m_CurveEditor.settings.hTickStyle.color; + color2.a = 0.75f; + float num = rect.width / this.state.frameSpan; + float minFrame = this.state.minFrame; + for (int i = 0; i < this.m_CurveEditor.hTicks.tickLevels; i++) + { + float num2 = this.m_CurveEditor.hTicks.GetStrengthOfLevel(i) * 0.9f; + float[] ticksAtLevel = this.m_CurveEditor.hTicks.GetTicksAtLevel(i, true); + for (int j = 0; j < ticksAtLevel.Length; j++) + { + if (ticksAtLevel[j] >= 0f) + { + int num3 = Mathf.RoundToInt(ticksAtLevel[j] * this.state.frameRate); + float num4 = 17f * Mathf.Min(1f, num2) * 0.7f; + float x = ((float)num3 - minFrame) * num; + if (!onlyDopesheetLines) + { + GL.Color(new Color(1f, 1f, 1f, num2 / 0.5f) * color2); + GL.Vertex(new Vector3(x, 17f - num4 + 0.5f, 0f)); + GL.Vertex(new Vector3(x, 16.5f, 0f)); + } + if (onlyDopesheetLines) + { + GL.Color(new Color(1f, 1f, 1f, num2 / 0.5f) * 0.37f); + GL.Vertex(new Vector3(x, rect.yMin, 0f)); + GL.Vertex(new Vector3(x, rect.yMax, 0f)); + } + else + { + GL.Color(new Color(1f, 1f, 1f, num2 / 0.5f) * 0.4f); + GL.Vertex(new Vector3(x, rect.yMin + 17f + 18f, 0f)); + GL.Vertex(new Vector3(x, rect.yMax, 0f)); + } + } + } + } + GL.End(); + if (!onlyDopesheetLines) + { + int length = ((int)this.state.frameRate).ToString().Length; + int levelWithMinSeparation = this.m_CurveEditor.hTicks.GetLevelWithMinSeparation(40f); + float[] ticksAtLevel2 = this.m_CurveEditor.hTicks.GetTicksAtLevel(levelWithMinSeparation, false); + for (int k = 0; k < ticksAtLevel2.Length; k++) + { + if (ticksAtLevel2[k] >= 0f) + { + int num5 = Mathf.RoundToInt(ticksAtLevel2[k] * this.state.frameRate); + float num6 = Mathf.Floor(this.state.FrameToPixel((float)num5, rect)); + string text = this.state.FormatFrame(num5, length); + GUI.Label(new Rect(num6 + 3f, -3f, 40f, 20f), text, AnimationWindow.ms_Styles.TimelineTick); + } + } + } + GUI.EndGroup(); + GUI.backgroundColor = backgroundColor; + GUI.color = color; + } + private void SecondaryTickMarksGUI(Rect rect) + { + GUI.BeginGroup(rect); + if (Event.current.type != EventType.Repaint) + { + GUI.EndGroup(); + return; + } + this.m_CurveEditor.hTicks.SetTickStrengths((float)this.m_CurveEditor.settings.hTickStyle.distMin, (float)this.m_CurveEditor.settings.hTickStyle.distFull, false); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + for (int i = 0; i < this.m_CurveEditor.hTicks.tickLevels; i++) + { + float strengthOfLevel = this.m_CurveEditor.hTicks.GetStrengthOfLevel(i); + GL.Color(this.m_CurveEditor.settings.hTickStyle.color * new Color(1f, 1f, 1f, strengthOfLevel) * new Color(1f, 1f, 1f, 0.75f)); + float[] ticksAtLevel = this.m_CurveEditor.hTicks.GetTicksAtLevel(i, true); + for (int j = 0; j < ticksAtLevel.Length; j++) + { + if (ticksAtLevel[j] >= 0f) + { + int num = Mathf.RoundToInt(ticksAtLevel[j] * this.state.frameRate); + GL.Vertex(new Vector2(this.state.FrameToPixel((float)num, rect), 0f)); + GL.Vertex(new Vector2(this.state.FrameToPixel((float)num, rect), rect.height)); + } + } + } + GL.End(); + GUI.EndGroup(); + } + public void OnGUI() + { + if (this.state.AnimatorIsOptimized) + { + GUILayout.Label("Editing optimized game object hierarchy is not supported.\nPlease select a game object that does not have 'Optimize Game Objects' applied.", new GUILayoutOption[0]); + return; + } + this.state.OnGUI(); + this.InitAllViews(); + if (this.state.m_ActiveGameObject == null) + { + AnimationWindow.m_Selected = null; + this.state.m_ShowCurveEditor = false; + } + if (AnimationWindow.m_Selected == null) + { + this.OnSelectionChange(); + } + if (AnimationWindow.m_Selected.Length == 0) + { + this.EndAnimationMode(); + } + if (this.state == null) + { + return; + } + if (this.m_CurveEditorToggleChanged) + { + this.m_CurveEditorToggleChanged = false; + this.state.m_ShowCurveEditor = !this.state.m_ShowCurveEditor; + this.HandleEmptyCurveEditor(); + } + this.state.timeArea = ((!this.state.m_ShowCurveEditor) ? this.m_DopeSheetEditor : this.m_CurveEditor); + if (this.state.m_CurveEditorIsDirty) + { + CurveRendererCache.ClearCurveRendererCache(); + this.RefreshShownCurves(false); + if (AnimationMode.InAnimationMode()) + { + this.ResampleAnimation(); + } + } + if (this.m_PerformFrameSelectedOnCurveEditor) + { + if (this.state.m_ShowCurveEditor) + { + this.m_CurveEditor.FrameSelected(this.m_PerformFrameSelectedOnCurveEditorHorizontally, true); + } + this.m_PerformFrameSelectedOnCurveEditor = false; + this.m_PerformFrameSelectedOnCurveEditorHorizontally = false; + } + int num = this.m_HorizontalSplitter.realSizes[0]; + Rect rect = new Rect((float)num, 0f, base.position.width - (float)num, base.position.height); + Rect rect2 = new Rect((float)num, 0f, rect.width - 15f, 17f); + Rect rect3 = new Rect((float)num, rect2.yMax, rect.width - 15f, 18f); + Rect area = new Rect((float)num, rect2.yMin, rect.width - 15f, rect3.yMax); + float width = (!this.state.m_ShowCurveEditor) ? (rect.width - 15f) : rect.width; + Rect rect4 = new Rect((float)num, rect3.yMax, width, rect.height - 17f - 18f); + Rect position = (!this.state.m_ShowCurveEditor) ? rect4 : default(Rect); + Rect rect5 = (!this.state.m_ShowCurveEditor) ? new Rect((float)num, rect4.yMax, rect4.width, 0f) : rect4; + Rect rect6 = (!this.state.m_ShowCurveEditor) ? rect5 : new Rect(rect5.xMin, rect5.yMin, rect5.width, rect5.height - 15f); + Rect position2 = new Rect((float)num, 0f, rect.width - 15f, rect.height - rect5.height - 15f); + this.m_CurveEditor.rect = rect5; + if (AnimationWindow.ms_Styles == null) + { + AnimationWindow.ms_Styles = new AnimationWindow.Styles(); + } + Handles.lighting = false; + if (!AnimationMode.InAnimationMode()) + { + this.SetAutoRecordMode(false); + this.state.m_Frame = 0; + } + GUI.changed = false; + AnimationWindow.vPosition = 0; + AnimationWindow.kEvenRow = true; + SplitterGUILayout.BeginHorizontalSplit(this.m_HorizontalSplitter, new GUILayoutOption[0]); + EditorGUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.MaxWidth((float)num) + }); + GUI.changed = false; + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[] + { + GUILayout.Width((float)num) + }); + EditorGUI.BeginDisabledGroup(!this.state.m_ActiveGameObject || this.state.IsPrefab); + if (this.m_PlayFromNoMode) + { + bool flag = GUILayout.Toggle(false, AnimationWindow.ms_Styles.recordContent, EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (flag) + { + this.Stop(); + this.ToggleAnimationMode(); + } + } + else + { + Color color = GUI.color; + if (AnimationMode.InAnimationMode()) + { + GUI.color = color * AnimationMode.animatedPropertyColor; + } + bool flag2 = GUILayout.Toggle(AnimationMode.InAnimationMode(), AnimationWindow.ms_Styles.recordContent, EditorStyles.toolbarButton, new GUILayoutOption[0]); + GUI.color = color; + if (flag2 != AnimationMode.InAnimationMode()) + { + this.ToggleAnimationMode(); + } + GUI.color = color; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.state.IsPrefab); + this.SetPlayMode(GUILayout.Toggle(this.state.m_AnimationIsPlaying, AnimationWindow.ms_Styles.playContent, EditorStyles.toolbarButton, new GUILayoutOption[0])); + GUILayout.FlexibleSpace(); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!this.state.m_ActiveGameObject || !this.state.m_ActiveAnimationClip || this.state.IsPrefab); + if (GUILayout.Button(AnimationWindow.ms_Styles.prevKeyContent, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.Prev(); + } + if (GUILayout.Button(AnimationWindow.ms_Styles.nextKeyContent, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.Next(); + } + int num2 = EditorGUILayout.IntField(this.state.m_Frame, EditorStyles.toolbarTextField, new GUILayoutOption[] + { + GUILayout.Width(35f) + }); + num2 = Mathf.Max(0, num2); + if (num2 != this.state.m_Frame) + { + this.PreviewFrame(num2); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + if ((GUILayout.Button(AnimationWindow.ms_Styles.addKeyframeContent, EditorStyles.toolbarButton, new GUILayoutOption[0]) || AnimationWindow.kAnimationRecordKeyframe.activated) && this.EnsureAnimationMode()) + { + AnimationWindowUtility.AddSelectedKeyframes(this.state, this.state.time); + } + if (GUILayout.Button(AnimationWindow.ms_Styles.addEventContent, EditorStyles.toolbarButton, new GUILayoutOption[0]) && AnimationWindow.m_Selected.Length > 0) + { + AnimationSelection animationSelection = AnimationWindow.m_Selected[0]; + if (animationSelection.EnsureClipPresence()) + { + this.m_CurveEditor.SelectNone(); + this.m_AnimationEventTimeLine.AddEvent(this.state); + this.SetDirtyCurves(); + } + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[] + { + GUILayout.Width((float)(num + 1)) + }); + GUI.changed = false; + AnimationSelection animSel = (AnimationWindow.m_Selected.Length <= 0) ? null : AnimationWindow.m_Selected[0]; + AnimationSelection.OnGUISelection(animSel); + EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); + Rect rect7 = GUILayoutUtility.GetRect(0f, 0f, AnimationWindow.ms_Styles.toolbarLabel, new GUILayoutOption[] + { + GUILayout.Width(45f) + }); + rect7.width += 10f; + GUI.Label(rect7, "Samples", AnimationWindow.ms_Styles.toolbarLabel); + EditorGUI.BeginChangeCheck(); + int num3 = EditorGUILayout.IntField((int)this.state.frameRate, EditorStyles.toolbarTextField, new GUILayoutOption[] + { + GUILayout.Width(35f) + }); + if (EditorGUI.EndChangeCheck()) + { + this.state.frameRate = (float)num3; + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + GUILayoutUtility.GetRect((float)num, base.position.height - 17f - 18f - 15f); + if (AnimationWindow.m_Selected.Length > 0) + { + this.HierarchyGUI(num, (int)rect4.height - 15); + } + Handles.color = ((!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f) : new Color(0.15f, 0.15f, 0.15f)); + Handles.DrawLine(new Vector2((float)num, 35f), new Vector2((float)num, (float)((int)rect4.height - 15 + 35))); + Color color2 = GUI.color; + GUI.color = new Color(0.95f, 0.95f, 0.95f, 1f); + EditorGUILayout.BeginHorizontal(AnimationWindow.ms_Styles.miniToolbar, new GUILayoutOption[] + { + GUILayout.Width((float)(num + 1)), + GUILayout.MinHeight(15f) + }); + GUILayout.FlexibleSpace(); + EditorGUI.BeginDisabledGroup(this.state.m_ActiveAnimationClip == null); + EditorGUI.BeginChangeCheck(); + GUILayout.Toggle(!this.state.m_ShowCurveEditor, "Dope Sheet", AnimationWindow.ms_Styles.miniToolbarButton, new GUILayoutOption[] + { + GUILayout.Width(80f) + }); + GUILayout.Toggle(this.state.m_ShowCurveEditor, "Curves", AnimationWindow.ms_Styles.miniToolbarButton, new GUILayoutOption[] + { + GUILayout.Width(80f) + }); + if (EditorGUI.EndChangeCheck()) + { + this.m_CurveEditorToggleChanged = true; + } + EditorGUI.EndDisabledGroup(); + GUI.color = color2; + EditorGUILayout.EndHorizontal(); + EditorGUILayout.EndVertical(); + GUIUtility.GetControlID(3487653, FocusType.Passive); + GUI.changed = false; + EditorGUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + EditorGUILayout.BeginHorizontal("Toolbar", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + GUI.Label(rect3, GUIContent.none, AnimationWindow.ms_Styles.eventBackground); + this.TimeLineGUI(rect3, true, true, false); + if (this.state.m_ShowCurveEditor) + { + GUI.Label(this.m_CurveEditor.drawRect, GUIContent.none, AnimationWindow.ms_Styles.curveEditorBackground); + } + this.m_CurveEditor.rect = rect5; + this.m_CurveEditor.hRangeLocked = Event.current.shift; + this.m_CurveEditor.vRangeLocked = EditorGUI.actionKey; + GUI.changed = false; + if (this.state.maxFrame < this.state.minFrame + 5f) + { + this.m_CurveEditor.SetShownHRange(this.state.minTime, this.state.minTime + 5f / this.state.frameRate); + } + this.m_CurveEditor.vSlider = this.state.m_ShowCurveEditor; + this.m_CurveEditor.hSlider = this.state.m_ShowCurveEditor; + this.m_CurveEditor.BeginViewGUI(); + this.m_CurveEditor.GridGUI(); + if (this.state.m_ShowCurveEditor) + { + if (this.state.m_ActiveAnimationClip != null) + { + AnimationWindow.DrawEndOfClip(rect6, this.state.TimeToPixel(this.state.m_ActiveAnimationClip.length) + rect6.xMin); + } + this.HandlePlayhead((float)num, rect6, 0.6f); + EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); + this.m_CurveEditor.CurveGUI(); + EditorGUI.EndDisabledGroup(); + } + this.m_CurveEditor.EndViewGUI(); + this.TimeLineGUI(rect2, false, false, true); + if (this.state.m_ActiveAnimationClip != null) + { + AnimationWindow.DrawEndOfClip(rect2, this.state.TimeToPixel(this.state.m_ActiveAnimationClip.length) + rect2.xMin); + } + this.HandlePlayhead((float)num, rect2); + if (AnimationWindow.m_Selected.Length > 0) + { + EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + this.HandlePlayhead((float)num, rect3); + this.m_AnimationEventTimeLine.EventLineGUI(rect3, AnimationWindow.m_Selected[0], this.state, this.m_CurveEditor); + EditorGUI.EndDisabledGroup(); + } + if (!this.state.m_ShowCurveEditor) + { + this.DopeSheetGUI(position); + this.m_CurveEditor.SetShownHRange(this.state.minTime, this.state.maxTime); + } + if (AnimationWindow.m_Selected.Length > 0 && Event.current.button == 0) + { + EditorGUI.BeginChangeCheck(); + int num4 = Mathf.RoundToInt(GUI.HorizontalSlider(position2, (float)this.state.m_Frame, this.state.minFrame, this.state.maxFrame, GUIStyle.none, GUIStyle.none)); + if (position2.Contains(Event.current.mousePosition) && Event.current.type == EventType.MouseUp) + { + num4 = Mathf.RoundToInt(this.state.TimeToFrame(this.state.PixelToTime(Event.current.mousePosition.x - (float)num, false))); + } + num4 = Mathf.Max(0, num4); + if (EditorGUI.EndChangeCheck()) + { + this.PreviewFrame(num4); + } + } + if (this.m_ShownProperties == null) + { + Debug.LogError("m_ShownProperties is null"); + } + else + { + if (this.m_CurveEditor.animationCurves.Length != this.m_EditedCurves.Length) + { + Debug.LogError(string.Concat(new object[] + { + "animationCurves and m_EditedCurves not same length! (", + this.m_CurveEditor.animationCurves.Length, + " vs ", + this.m_EditedCurves.Length, + ")" + })); + } + else + { + if (AnimationWindow.m_Selected.Length > 0 && AnimationWindow.m_Selected[0] != null && this.m_ShownProperties.Length > 0) + { + int num5 = 0; + for (int i = 0; i < this.m_EditedCurves.Length; i++) + { + if (this.m_CurveEditor.animationCurves[i] == null) + { + Debug.LogError("Curve " + i + " is null"); + } + CurveState curveState = this.m_ShownProperties[this.m_EditedCurves[i]]; + if (this.m_CurveEditor.animationCurves[i].changed) + { + this.m_CurveEditor.animationCurves[i].changed = false; + num5++; + if (this.EnsureAnimationMode()) + { + curveState.SaveCurve(this.m_CurveEditor.animationCurves[i].curve); + } + } + } + if (num5 > 0) + { + this.SetDirtyCurves(); + } + } + } + } + EditorGUILayout.EndVertical(); + SplitterGUILayout.EndHorizontalSplit(); + this.HandleZoomingOutsideTimearea(area); + this.AnimationControls(); + Rect position3 = base.position; + position3.x = 0f; + position3.y = 0f; + if (Event.current.type == EventType.MouseDown && position3.Contains(Event.current.mousePosition) && Event.current.button == 0 && !Event.current.shift && !Event.current.control) + { + GUIUtility.keyboardControl = 0; + if (Event.current.mousePosition.x < (float)num && Event.current.mousePosition.y > 32f) + { + for (int j = 0; j < this.m_SelectedProperties.Length; j++) + { + this.m_SelectedProperties[j] = false; + } + this.SetDirtyCurves(); + } + Event.current.Use(); + } + this.m_AnimationEventTimeLine.DrawInstantTooltip(base.position); + } + public static void DrawEndOfClip(Rect rect, float endOfClipPixel) + { + Rect rect2 = new Rect(Mathf.Max(endOfClipPixel, rect.xMin), rect.yMin, rect.width, rect.height); + Vector3[] array = new Vector3[] + { + new Vector3(rect2.xMin, rect2.yMin), + new Vector3(rect2.xMax, rect2.yMin), + new Vector3(rect2.xMax, rect2.yMax), + new Vector3(rect2.xMin, rect2.yMax) + }; + Color color = (!EditorGUIUtility.isProSkin) ? Color.gray.AlphaMultiplied(0.42f) : Color.black.AlphaMultiplied(0.32f); + Color color2 = (!EditorGUIUtility.isProSkin) ? Color.white.RGBMultiplied(0.4f) : Color.white.RGBMultiplied(0.32f); + AnimationWindow.DrawRect(array, color); + AnimationWindow.DrawLine(array[0], array[3] + new Vector3(0f, -1f, 0f), color2); + } + private void HandlePlayhead(float hierarchyWidth, Rect r) + { + this.HandlePlayhead(hierarchyWidth, r, 1f); + } + private void HandlePlayhead(float hierarchyWidth, Rect r, float alpha) + { + if (AnimationMode.InAnimationMode() && (float)this.state.m_Frame >= this.state.minFrame - 1f && (float)this.state.m_Frame < this.state.maxFrame) + { + float num = this.state.TimeToPixel(this.state.GetTimeSeconds(), false) + hierarchyWidth; + if (r.xMin < num) + { + AnimationWindow.DrawPlayHead(new Vector2(num, r.yMin), new Vector2(num, r.yMax), alpha); + } + } + } + public static void DrawPlayHead(Vector2 start, Vector2 end, float alpha) + { + AnimationWindow.DrawLine(start, end, Color.red.AlphaMultiplied(alpha)); + } + private static void DrawLine(Vector2 p1, Vector2 p2, Color color) + { + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(color); + GL.Vertex(p1); + GL.Vertex(p2); + GL.End(); + GL.PopMatrix(); + } + private static void DrawRect(Vector3[] corners, Color color) + { + if (corners.Length != 4) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(7); + GL.Color(color); + GL.Vertex(corners[0]); + GL.Vertex(corners[1]); + GL.Vertex(corners[2]); + GL.Vertex(corners[3]); + GL.End(); + GL.PopMatrix(); + } + private void HandleZoomingOutsideTimearea(Rect area) + { + if (this.state.m_ShowCurveEditor) + { + this.m_CurveEditor.HandleZoomAndPanEvents(area); + } + else + { + this.m_DopeSheetEditor.HandleZoomAndPanEvents(area); + } + } + private void HandleEmptyCurveEditor() + { + if (this.state.m_ShowCurveEditor && this.state.activeCurves.Count == 0 && this.state.dopelines.Count > 0) + { + this.state.SelectHierarchyItem(this.state.dopelines[0], false, false); + } + } + private void InitAllViews() + { + if (this.m_Hierarchy == null) + { + this.m_Hierarchy = new AnimationWindowHierarchy(this.state, this, new Rect(0f, 0f, 1f, 1f)); + } + if (this.m_DopeSheetEditor == null) + { + this.m_DopeSheetEditor = new DopeSheetEditor(this.state, this); + } + if (this.m_AnimationEventTimeLine == null) + { + this.m_AnimationEventTimeLine = new AnimationEventTimeLine(this); + } + } + private void HierarchyGUI(int hierarchyWidth, int hierarchyHeight) + { + if (GUI.changed) + { + this.RefreshAnimationSelections(); + } + Rect position = new Rect(0f, 35f, (float)hierarchyWidth, (float)hierarchyHeight); + this.m_Hierarchy.OnGUI(position, this); + EditorGUIUtility.SetIconSize(Vector2.zero); + } + private void DebugTime(string str, float timeA, float timeB) + { + Debug.Log(str + " took " + (timeB - timeA)); + } + public void OnSelectionChange() + { + if (this.state != null && Selection.activeGameObject && Selection.activeGameObject != this.state.m_ActiveGameObject) + { + this.m_PerformFrameSelectedOnCurveEditorHorizontally = true; + this.FrameSelected(); + } + this.InitSelection(); + } + private void SetGridColors() + { + CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); + curveEditorSettings.hTickStyle.distMin = 30; + curveEditorSettings.hTickStyle.distFull = 80; + curveEditorSettings.hTickStyle.distLabel = 0; + if (EditorGUIUtility.isProSkin) + { + curveEditorSettings.vTickStyle.color = new Color(1f, 1f, 1f, curveEditorSettings.vTickStyle.color.a); + curveEditorSettings.vTickStyle.labelColor = new Color(1f, 1f, 1f, curveEditorSettings.vTickStyle.labelColor.a); + } + curveEditorSettings.vTickStyle.distMin = 15; + curveEditorSettings.vTickStyle.distFull = 40; + curveEditorSettings.vTickStyle.distLabel = 30; + curveEditorSettings.vTickStyle.stubs = true; + curveEditorSettings.hRangeMin = 0f; + curveEditorSettings.hRangeLocked = false; + curveEditorSettings.vRangeLocked = false; + this.m_CurveEditor.settings = curveEditorSettings; + } + private void AnimationControls() + { + Event current = Event.current; + EventType type = current.type; + if (type != EventType.KeyDown) + { + if (type != EventType.KeyUp) + { + } + } + else + { + if (AnimationWindow.kAnimationPrevFrame.activated) + { + this.PreviewFrame(Mathf.Max(0, this.state.m_Frame - 1)); + current.Use(); + } + if (AnimationWindow.kAnimationNextFrame.activated) + { + this.PreviewFrame(this.state.m_Frame + 1); + current.Use(); + } + if (AnimationWindow.kAnimationPrevKeyframe.activated) + { + this.Prev(); + current.Use(); + } + if (AnimationWindow.kAnimationNextKeyframe.activated) + { + this.Next(); + current.Use(); + } + if (AnimationWindow.kAnimationRecordKeyframe.activated) + { + AnimationWindowUtility.AddSelectedKeyframes(this.state, this.state.time); + current.Use(); + } + if (AnimationWindow.kAnimationShowCurvesToggle.activated) + { + this.m_CurveEditorToggleChanged = true; + current.Use(); + } + } + } + public void Awake() + { + if (this.state == null) + { + this.state = new AnimationWindowState(); + this.state.m_ShowCurveEditor = false; + this.state.m_AnimationWindow = this; + } + this.state.timeArea = null; + base.minSize = new Vector2(400f, 200f); + this.m_HorizontalSplitter = new SplitterState(new float[] + { + 250f, + 10000f + }, new int[] + { + 250, + 150 + }, null); + this.m_HorizontalSplitter.realSizes[0] = 300; + base.wantsMouseMove = true; + AnimationWindow.m_Selected = new AnimationSelection[0]; + if (this.m_ExpandedFoldouts == null) + { + this.m_ExpandedFoldouts = new SerializedStringTable(); + } + if (this.m_ChosenAnimated == null) + { + this.m_ChosenAnimated = new SerializedStringTable(); + } + if (this.m_ChosenClip == null) + { + this.m_ChosenClip = new SerializedStringTable(); + } + this.m_CurveEditor = new CurveEditor(new Rect(base.position.x, base.position.y, 500f, 200f), new CurveWrapper[0], false); + this.SetGridColors(); + this.m_CurveEditor.m_TimeUpdater = this; + this.m_CurveEditor.m_DefaultBounds = new Bounds(new Vector3(1f, 1f, 0f), new Vector3(2f, 1000f, 0f)); + this.m_CurveEditor.SetShownHRangeInsideMargins(0f, 2f); + this.m_CurveEditor.hTicks.SetTickModulosForFrameRate(this.state.frameRate); + this.InitAllViews(); + this.InitSelection(); + } + public void OnEnable() + { + AnimationWindow.s_AnimationWindows.Add(this); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + if (this.state != null) + { + this.state.OnEnable(this); + } + AnimationWindowState expr_48 = this.state; + expr_48.m_OnHierarchySelectionChanged = (Action)Delegate.Combine(expr_48.m_OnHierarchySelectionChanged, new Action(this.FrameSelected)); + if (AnimationWindow.m_Selected == null) + { + return; + } + if (this.m_CurveEditor != null) + { + this.m_CurveEditor.m_TimeUpdater = this; + this.SetGridColors(); + this.m_CurveEditor.OnEnable(); + } + if (this.m_AutoRecord) + { + Undo.postprocessModifications = (Undo.PostprocessModifications)Delegate.Combine(Undo.postprocessModifications, new Undo.PostprocessModifications(this.PostprocessAnimationRecordingModifications)); + } + this.state.m_ShowCurveEditor = AnimationWindow.s_LastShowCurveEditor; + this.SetDirtyCurves(); + } + public void OnDisable() + { + AnimationWindow.s_AnimationWindows.Remove(this); + if (this.state != null) + { + this.state.OnDisable(); + } + AnimationWindow.s_LastShowCurveEditor = this.state.m_ShowCurveEditor; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + Undo.postprocessModifications = (Undo.PostprocessModifications)Delegate.Remove(Undo.postprocessModifications, new Undo.PostprocessModifications(this.PostprocessAnimationRecordingModifications)); + AnimationWindowState expr_78 = this.state; + expr_78.m_OnHierarchySelectionChanged = (Action)Delegate.Remove(expr_78.m_OnHierarchySelectionChanged, new Action(this.FrameSelected)); + this.m_CurveEditor.OnDisable(); + } + public void OnDestroy() + { + this.EndAnimationMode(); + AnimationEventPopup.ClosePopup(); + CurveRendererCache.ClearCurveRendererCache(); + if (this.m_DopeSheetEditor != null) + { + this.m_DopeSheetEditor.OnDestroy(); + } + } + public void DrawClipsInSceneView() + { + } + } +} diff --git a/UnityEditor/UnityEditor/AnimatorInspector.cs b/UnityEditor/UnityEditor/AnimatorInspector.cs new file mode 100644 index 00000000..4677ddb4 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimatorInspector.cs @@ -0,0 +1,50 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Animator))] + internal class AnimatorInspector : Editor + { + private SerializedProperty m_Controller; + private SerializedProperty m_Avatar; + private SerializedProperty m_ApplyRootMotion; + private SerializedProperty m_UpdateMode; + private SerializedProperty m_CullingMode; + private void OnEnable() + { + this.m_Controller = base.serializedObject.FindProperty("m_Controller"); + this.m_Avatar = base.serializedObject.FindProperty("m_Avatar"); + this.m_ApplyRootMotion = base.serializedObject.FindProperty("m_ApplyRootMotion"); + this.m_UpdateMode = base.serializedObject.FindProperty("m_UpdateMode"); + this.m_CullingMode = base.serializedObject.FindProperty("m_CullingMode"); + } + public override void OnInspectorGUI() + { + bool flag = base.targets.Length > 1; + Animator animator = this.target as Animator; + base.serializedObject.UpdateIfDirtyOrScript(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_Controller, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorApplication.RepaintAnimationWindow(); + } + EditorGUILayout.PropertyField(this.m_Avatar, new GUILayoutOption[0]); + if (animator.supportsOnAnimatorMove && !flag) + { + EditorGUILayout.LabelField("Apply Root Motion", "Handled by Script", new GUILayoutOption[0]); + } + else + { + EditorGUILayout.PropertyField(this.m_ApplyRootMotion, new GUILayoutOption[0]); + } + EditorGUILayout.PropertyField(this.m_UpdateMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CullingMode, new GUILayoutOption[0]); + if (!flag) + { + EditorGUILayout.HelpBox(animator.GetStats(), MessageType.Info, true); + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs b/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs new file mode 100644 index 00000000..be505007 --- /dev/null +++ b/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs @@ -0,0 +1,94 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AnimatorOverrideController))] + internal class AnimatorOverrideControllerInspector : Editor + { + private SerializedProperty m_Controller; + private AnimationClipPair[] m_Clips; + private ReorderableList m_ClipList; + private void OnEnable() + { + AnimatorOverrideController animatorOverrideController = this.target as AnimatorOverrideController; + this.m_Controller = base.serializedObject.FindProperty("m_Controller"); + if (this.m_ClipList == null) + { + this.m_ClipList = new ReorderableList(animatorOverrideController.clips, typeof(AnimationClipPair), false, true, false, false); + this.m_ClipList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawClipElement); + this.m_ClipList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawClipHeader); + this.m_ClipList.elementHeight = 16f; + } + AnimatorOverrideController expr_8B = animatorOverrideController; + expr_8B.OnOverrideControllerDirty = (AnimatorOverrideController.OnOverrideControllerDirtyCallback)Delegate.Combine(expr_8B.OnOverrideControllerDirty, new AnimatorOverrideController.OnOverrideControllerDirtyCallback(base.Repaint)); + } + private void OnDisable() + { + AnimatorOverrideController animatorOverrideController = this.target as AnimatorOverrideController; + AnimatorOverrideController expr_0D = animatorOverrideController; + expr_0D.OnOverrideControllerDirty = (AnimatorOverrideController.OnOverrideControllerDirtyCallback)Delegate.Remove(expr_0D.OnOverrideControllerDirty, new AnimatorOverrideController.OnOverrideControllerDirtyCallback(base.Repaint)); + } + public override void OnInspectorGUI() + { + bool flag = base.targets.Length > 1; + bool flag2 = false; + base.serializedObject.UpdateIfDirtyOrScript(); + AnimatorOverrideController animatorOverrideController = this.target as AnimatorOverrideController; + RuntimeAnimatorController runtimeAnimatorController = (!this.m_Controller.hasMultipleDifferentValues) ? animatorOverrideController.runtimeAnimatorController : null; + EditorGUI.BeginChangeCheck(); + runtimeAnimatorController = (EditorGUILayout.ObjectField("Controller", runtimeAnimatorController, typeof(AnimatorController), false, new GUILayoutOption[0]) as RuntimeAnimatorController); + if (EditorGUI.EndChangeCheck()) + { + for (int i = 0; i < base.targets.Length; i++) + { + AnimatorOverrideController animatorOverrideController2 = base.targets[i] as AnimatorOverrideController; + animatorOverrideController2.runtimeAnimatorController = runtimeAnimatorController; + } + flag2 = true; + } + EditorGUI.BeginDisabledGroup(this.m_Controller == null || (flag && this.m_Controller.hasMultipleDifferentValues) || runtimeAnimatorController == null); + EditorGUI.BeginChangeCheck(); + this.m_Clips = animatorOverrideController.clips; + this.m_ClipList.list = this.m_Clips; + this.m_ClipList.DoLayoutList(); + if (EditorGUI.EndChangeCheck()) + { + for (int j = 0; j < base.targets.Length; j++) + { + AnimatorOverrideController animatorOverrideController3 = base.targets[j] as AnimatorOverrideController; + animatorOverrideController3.clips = this.m_Clips; + } + flag2 = true; + } + EditorGUI.EndDisabledGroup(); + if (flag2) + { + animatorOverrideController.PerformOverrideClipListCleanup(); + } + } + private void DrawClipElement(Rect rect, int index, bool selected, bool focused) + { + AnimationClip originalClip = this.m_Clips[index].originalClip; + AnimationClip animationClip = this.m_Clips[index].overrideClip; + rect.xMax /= 2f; + GUI.Label(rect, originalClip.name, EditorStyles.label); + rect.xMin = rect.xMax; + rect.xMax *= 2f; + EditorGUI.BeginChangeCheck(); + animationClip = (EditorGUI.ObjectField(rect, string.Empty, animationClip, typeof(AnimationClip), false) as AnimationClip); + if (EditorGUI.EndChangeCheck()) + { + this.m_Clips[index].overrideClip = animationClip; + } + } + private void DrawClipHeader(Rect rect) + { + rect.xMax /= 2f; + GUI.Label(rect, "Original", EditorStyles.label); + rect.xMin = rect.xMax; + rect.xMax *= 2f; + GUI.Label(rect, "Override", EditorStyles.label); + } + } +} diff --git a/UnityEditor/UnityEditor/Annotation.cs b/UnityEditor/UnityEditor/Annotation.cs new file mode 100644 index 00000000..607ef1ca --- /dev/null +++ b/UnityEditor/UnityEditor/Annotation.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + internal struct Annotation + { + public int iconEnabled; + public int gizmoEnabled; + public int flags; + public int classID; + public string scriptClass; + } +} diff --git a/UnityEditor/UnityEditor/AnnotationUtility.cs b/UnityEditor/UnityEditor/AnnotationUtility.cs new file mode 100644 index 00000000..7962a666 --- /dev/null +++ b/UnityEditor/UnityEditor/AnnotationUtility.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class AnnotationUtility + { + internal static extern bool use3dGizmos + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool showGrid + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern float iconSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Annotation[] GetAnnotations(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Annotation[] GetRecentlyChangedAnnotations(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetNameOfCurrentSetup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetGizmoEnabled(int classID, string scriptClass, int gizmoEnabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetIconEnabled(int classID, string scriptClass, int iconEnabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string[] GetPresetList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void LoadPreset(string presetName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SavePreset(string presetName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DeletePreset(string presetName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ResetToFactorySettings(); + } +} diff --git a/UnityEditor/UnityEditor/AnnotationWindow.cs b/UnityEditor/UnityEditor/AnnotationWindow.cs new file mode 100644 index 00000000..78880fa7 --- /dev/null +++ b/UnityEditor/UnityEditor/AnnotationWindow.cs @@ -0,0 +1,546 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AnnotationWindow : EditorWindow + { + private class Styles + { + public GUIStyle toolbar = "toolbar"; + public GUIStyle toggle = "OL Toggle"; + public GUIStyle listEvenBg = "ObjectPickerResultsOdd"; + public GUIStyle listOddBg = "ObjectPickerResultsEven"; + public GUIStyle listSectionHeaderBg = "ObjectPickerResultsEven"; + public GUIStyle background = "grey_border"; + public GUIStyle seperator = "sv_iconselector_sep"; + public GUIStyle iconDropDown = "IN dropdown"; + public GUIStyle listTextStyle; + public GUIStyle listHeaderStyle; + public GUIStyle texelWorldSizeStyle; + public GUIStyle columnHeaderStyle; + public Styles() + { + this.listTextStyle = new GUIStyle(EditorStyles.label); + this.listTextStyle.alignment = TextAnchor.MiddleLeft; + this.listTextStyle.padding.left = 10; + this.listHeaderStyle = new GUIStyle(EditorStyles.boldLabel); + this.listHeaderStyle.padding.left = 5; + this.texelWorldSizeStyle = new GUIStyle(EditorStyles.label); + this.texelWorldSizeStyle.alignment = TextAnchor.UpperRight; + this.texelWorldSizeStyle.font = EditorStyles.miniLabel.font; + this.texelWorldSizeStyle.fontSize = EditorStyles.miniLabel.fontSize; + this.texelWorldSizeStyle.padding.right = 0; + this.columnHeaderStyle = new GUIStyle(EditorStyles.miniLabel); + } + } + private const float scrollBarWidth = 14f; + private const float listElementHeight = 18f; + private const float gizmoRightAlign = 23f; + private const float iconRightAlign = 64f; + private const float frameWidth = 1f; + private const float k_AnimDuration = 0.4f; + private const int maxShowRecent = 5; + private const string textGizmoVisible = "Show/Hide Gizmo"; + private const float exponentStart = -3f; + private const float exponentRange = 3f; + private const string kAlwaysFullSizeText = "Always Full Size"; + private const string kHideAllIconsText = "Hide All Icons"; + private static bool s_Debug; + private static AnnotationWindow s_AnnotationWindow; + private static long s_LastClosedTime; + private static AnnotationWindow.Styles m_Styles; + private List m_RecentAnnotations; + private List m_BuiltinAnnotations; + private List m_ScriptAnnotations; + private Vector2 m_ScrollPosition; + private bool m_SyncWithState; + private string m_LastScriptThatHasShownTheIconSelector; + private List m_MonoScriptIconsChanged; + private GUIContent iconToggleContent = new GUIContent(string.Empty, "Show/Hide Icon"); + private GUIContent iconSelectContent = new GUIContent(string.Empty, "Select Icon"); + private GUIContent icon3dGizmoContent = new GUIContent("3D Gizmos"); + private GUIContent showGridContent = new GUIContent("Show Grid"); + private bool m_IsGameView; + private AnnotationWindow() + { + base.hideFlags = HideFlags.DontSave; + } + private static float ConvertTexelWorldSizeTo01(float texelWorldSize) + { + if (texelWorldSize == -1f) + { + return 1f; + } + if (texelWorldSize == 0f) + { + return 0f; + } + return (Mathf.Log10(texelWorldSize) - -3f) / 3f; + } + private static float Convert01ToTexelWorldSize(float value01) + { + if (value01 <= 0f) + { + return 0f; + } + return Mathf.Pow(10f, -3f + 3f * value01); + } + private static string ConvertTexelWorldSizeToString(float texelWorldSize) + { + if (texelWorldSize == -1f) + { + return "Always Full Size"; + } + if (texelWorldSize == 0f) + { + return "Hide All Icons"; + } + float num = texelWorldSize * 32f; + int numberOfDecimalsForMinimumDifference = MathUtils.GetNumberOfDecimalsForMinimumDifference(num * 0.1f); + return num.ToString("N" + numberOfDecimalsForMinimumDifference); + } + public void MonoScriptIconChanged(MonoScript monoScript) + { + if (monoScript == null) + { + return; + } + bool flag = true; + foreach (MonoScript current in this.m_MonoScriptIconsChanged) + { + if (current.GetInstanceID() == monoScript.GetInstanceID()) + { + flag = false; + } + } + if (flag) + { + this.m_MonoScriptIconsChanged.Add(monoScript); + } + } + public static void IconChanged() + { + if (AnnotationWindow.s_AnnotationWindow != null) + { + AnnotationWindow.s_AnnotationWindow.IconHasChanged(); + } + } + private float GetTopSectionHeight() + { + return 50f; + } + private void OnEnable() + { + } + private void OnDisable() + { + foreach (MonoScript current in this.m_MonoScriptIconsChanged) + { + MonoImporter.CopyMonoScriptIconToImporters(current); + } + AnnotationWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + AnnotationWindow.s_AnnotationWindow = null; + } + internal static bool ShowAtPosition(Rect buttonRect, bool isGameView) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= AnnotationWindow.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (AnnotationWindow.s_AnnotationWindow == null) + { + AnnotationWindow.s_AnnotationWindow = ScriptableObject.CreateInstance(); + } + AnnotationWindow.s_AnnotationWindow.Init(buttonRect, isGameView); + return true; + } + return false; + } + private void Init(Rect buttonRect, bool isGameView) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + this.m_MonoScriptIconsChanged = new List(); + this.m_SyncWithState = true; + this.m_IsGameView = isGameView; + this.SyncToState(); + float num = 2f + this.GetTopSectionHeight() + this.DrawNormalList(false, 100f, 0f, 10000f); + num = Mathf.Min(num, 900f); + Vector2 windowSize = new Vector2(270f, num); + base.ShowAsDropDown(buttonRect, windowSize); + } + private void IconHasChanged() + { + if (string.IsNullOrEmpty(this.m_LastScriptThatHasShownTheIconSelector)) + { + return; + } + foreach (AInfo current in this.m_ScriptAnnotations) + { + if (current.m_ScriptClass == this.m_LastScriptThatHasShownTheIconSelector && !current.m_IconEnabled) + { + current.m_IconEnabled = true; + this.SetIconState(current); + break; + } + } + base.Repaint(); + } + private void Cancel() + { + base.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + } + private AInfo GetAInfo(int classID, string scriptClass) + { + if (scriptClass != string.Empty) + { + return this.m_ScriptAnnotations.Find((AInfo o) => o.m_ScriptClass == scriptClass); + } + return this.m_BuiltinAnnotations.Find((AInfo o) => o.m_ClassID == classID); + } + private void SyncToState() + { + Annotation[] annotations = AnnotationUtility.GetAnnotations(); + string text = string.Empty; + if (AnnotationWindow.s_Debug) + { + text += "AnnotationWindow: SyncToState\n"; + } + this.m_BuiltinAnnotations = new List(); + this.m_ScriptAnnotations = new List(); + for (int i = 0; i < annotations.Length; i++) + { + if (AnnotationWindow.s_Debug) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + " same as below: icon ", + annotations[i].iconEnabled, + " gizmo ", + annotations[i].gizmoEnabled, + "\n" + }); + } + bool gizmoEnabled = annotations[i].gizmoEnabled == 1; + bool iconEnabled = annotations[i].iconEnabled == 1; + AInfo aInfo = new AInfo(gizmoEnabled, iconEnabled, annotations[i].flags, annotations[i].classID, annotations[i].scriptClass); + if (aInfo.m_ScriptClass == string.Empty) + { + this.m_BuiltinAnnotations.Add(aInfo); + if (AnnotationWindow.s_Debug) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + " ", + BaseObjectTools.ClassIDToString(aInfo.m_ClassID), + ": icon ", + aInfo.m_IconEnabled, + " gizmo ", + aInfo.m_GizmoEnabled, + "\n" + }); + } + } + else + { + this.m_ScriptAnnotations.Add(aInfo); + if (AnnotationWindow.s_Debug) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + " ", + annotations[i].scriptClass, + ": icon ", + aInfo.m_IconEnabled, + " gizmo ", + aInfo.m_GizmoEnabled, + "\n" + }); + } + } + } + this.m_BuiltinAnnotations.Sort(); + this.m_ScriptAnnotations.Sort(); + this.m_RecentAnnotations = new List(); + Annotation[] recentlyChangedAnnotations = AnnotationUtility.GetRecentlyChangedAnnotations(); + int num = 0; + while (num < recentlyChangedAnnotations.Length && num < 5) + { + AInfo aInfo2 = this.GetAInfo(recentlyChangedAnnotations[num].classID, recentlyChangedAnnotations[num].scriptClass); + if (aInfo2 != null) + { + this.m_RecentAnnotations.Add(aInfo2); + } + num++; + } + this.m_SyncWithState = false; + if (AnnotationWindow.s_Debug) + { + Debug.Log(text); + } + } + internal void OnGUI() + { + if (Event.current.type == EventType.Layout) + { + return; + } + if (AnnotationWindow.m_Styles == null) + { + AnnotationWindow.m_Styles = new AnnotationWindow.Styles(); + } + if (this.m_SyncWithState) + { + this.SyncToState(); + } + float topSectionHeight = this.GetTopSectionHeight(); + this.DrawTopSection(topSectionHeight); + this.DrawAnnotationList(topSectionHeight, base.position.height - topSectionHeight); + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, AnnotationWindow.m_Styles.background); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.Cancel(); + } + } + private void DrawTopSection(float topSectionHeight) + { + GUI.Label(new Rect(1f, 0f, base.position.width - 2f, topSectionHeight), string.Empty, EditorStyles.inspectorBig); + float num = 7f; + float num2 = 11f; + float num3 = num; + Rect position = new Rect(num2 - 2f, num3, 80f, 20f); + AnnotationUtility.use3dGizmos = GUI.Toggle(position, AnnotationUtility.use3dGizmos, this.icon3dGizmoContent); + float iconSize = AnnotationUtility.iconSize; + if (AnnotationWindow.s_Debug) + { + Rect position2 = new Rect(0f, num3 + 10f, base.position.width - num2, 20f); + GUI.Label(position2, AnnotationWindow.ConvertTexelWorldSizeToString(iconSize), AnnotationWindow.m_Styles.texelWorldSizeStyle); + } + EditorGUI.BeginDisabledGroup(!AnnotationUtility.use3dGizmos); + float num4 = 160f; + float num5 = AnnotationWindow.ConvertTexelWorldSizeTo01(iconSize); + Rect position3 = new Rect(base.position.width - num2 - num4, num3, num4, 20f); + num5 = GUI.HorizontalSlider(position3, num5, 0f, 1f); + if (GUI.changed) + { + AnnotationUtility.iconSize = AnnotationWindow.Convert01ToTexelWorldSize(num5); + SceneView.RepaintAll(); + } + EditorGUI.EndDisabledGroup(); + num3 += 20f; + EditorGUI.BeginDisabledGroup(this.m_IsGameView); + position = new Rect(num2 - 2f, num3, 80f, 20f); + AnnotationUtility.showGrid = GUI.Toggle(position, AnnotationUtility.showGrid, this.showGridContent); + EditorGUI.EndDisabledGroup(); + } + private void DrawAnnotationList(float startY, float height) + { + Rect position = new Rect(1f, startY + 1f, base.position.width - 2f, height - 1f - 1f); + float num = this.DrawNormalList(false, 0f, 0f, 100000f); + Rect viewRect = new Rect(0f, 0f, 1f, num); + bool flag = num > position.height; + float num2 = position.width; + if (flag) + { + num2 -= 14f; + } + this.m_ScrollPosition = GUI.BeginScrollView(position, this.m_ScrollPosition, viewRect); + this.DrawNormalList(true, num2, this.m_ScrollPosition.y - 18f, this.m_ScrollPosition.y + num); + GUI.EndScrollView(); + } + private void Flip(ref bool even) + { + even = !even; + } + private float DrawNormalList(bool doDraw, float listElementWidth, float startY, float endY) + { + bool flag = true; + float y = 0f; + bool flag2 = false; + y = this.DrawListSection(y, "Recently Changed", this.m_RecentAnnotations, doDraw, listElementWidth, startY, endY, ref flag, true, ref flag2); + y = this.DrawListSection(y, "Scripts", this.m_ScriptAnnotations, doDraw, listElementWidth, startY, endY, ref flag, false, ref flag2); + return this.DrawListSection(y, "Built-in Components", this.m_BuiltinAnnotations, doDraw, listElementWidth, startY, endY, ref flag, false, ref flag2); + } + private float DrawListSection(float y, string sectionHeader, List listElements, bool doDraw, float listElementWidth, float startY, float endY, ref bool even, bool useSeperator, ref bool headerDrawn) + { + float num = y; + if (listElements.Count > 0) + { + if (doDraw) + { + Rect position = new Rect(1f, num, listElementWidth - 2f, 30f); + this.Flip(ref even); + GUIStyle style = (!even) ? AnnotationWindow.m_Styles.listOddBg : AnnotationWindow.m_Styles.listEvenBg; + GUI.Label(position, GUIContent.Temp(string.Empty), style); + } + num += 10f; + if (doDraw) + { + this.DrawListHeader(sectionHeader, new Rect(3f, num, listElementWidth, 20f), ref headerDrawn); + } + num += 20f; + for (int i = 0; i < listElements.Count; i++) + { + this.Flip(ref even); + if (num > startY && num < endY) + { + Rect rect = new Rect(1f, num, listElementWidth - 2f, 18f); + if (doDraw) + { + this.DrawListElement(rect, even, listElements[i]); + } + } + num += 18f; + } + if (useSeperator) + { + float num2 = 6f; + if (doDraw) + { + GUIStyle style2 = (!even) ? AnnotationWindow.m_Styles.listOddBg : AnnotationWindow.m_Styles.listEvenBg; + GUI.Label(new Rect(1f, num, listElementWidth - 2f, num2), GUIContent.Temp(string.Empty), style2); + GUI.Label(new Rect(10f, num + 3f, listElementWidth - 15f, 3f), GUIContent.Temp(string.Empty), AnnotationWindow.m_Styles.seperator); + } + num += num2; + } + } + return num; + } + private void DrawListHeader(string header, Rect rect, ref bool headerDrawn) + { + GUI.Label(rect, GUIContent.Temp(header), AnnotationWindow.m_Styles.listHeaderStyle); + if (!headerDrawn) + { + headerDrawn = true; + GUI.color = new Color(1f, 1f, 1f, 0.65f); + Rect position = rect; + position.y += -10f; + position.x = rect.width - 32f; + GUI.Label(position, "gizmo", AnnotationWindow.m_Styles.columnHeaderStyle); + position.x = rect.width - 64f; + GUI.Label(position, "icon", AnnotationWindow.m_Styles.columnHeaderStyle); + GUI.color = Color.white; + } + } + private void DrawListElement(Rect rect, bool even, AInfo ainfo) + { + if (ainfo == null) + { + Debug.LogError("DrawListElement: AInfo not valid!"); + return; + } + float num = 17f; + float a = 0.3f; + bool changed = GUI.changed; + bool enabled = GUI.enabled; + Color color = GUI.color; + GUI.changed = false; + GUI.enabled = true; + GUIStyle style = (!even) ? AnnotationWindow.m_Styles.listOddBg : AnnotationWindow.m_Styles.listEvenBg; + GUI.Label(rect, GUIContent.Temp(string.Empty), style); + Rect position = rect; + position.width = rect.width - 64f - 22f; + GUI.Label(position, ainfo.m_DisplayText, AnnotationWindow.m_Styles.listTextStyle); + float num2 = 16f; + Rect rect2 = new Rect(rect.width - 64f, rect.y + (rect.height - num2) * 0.5f, num2, num2); + Texture texture = null; + if (ainfo.m_ScriptClass != string.Empty) + { + texture = EditorGUIUtility.GetIconForObject(EditorGUIUtility.GetScript(ainfo.m_ScriptClass)); + Rect position2 = rect2; + position2.x += 18f; + position2.y += 1f; + position2.width = 1f; + position2.height = 12f; + if (!EditorGUIUtility.isProSkin) + { + GUI.color = new Color(0f, 0f, 0f, 0.33f); + } + else + { + GUI.color = new Color(1f, 1f, 1f, 0.13f); + } + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + GUI.color = Color.white; + Rect rect3 = rect2; + rect3.x += 18f; + rect3.y = rect3.y; + rect3.width = 9f; + if (GUI.Button(rect3, this.iconSelectContent, AnnotationWindow.m_Styles.iconDropDown)) + { + UnityEngine.Object script = EditorGUIUtility.GetScript(ainfo.m_ScriptClass); + if (script != null) + { + this.m_LastScriptThatHasShownTheIconSelector = ainfo.m_ScriptClass; + if (IconSelector.ShowAtPosition(script, rect3, true)) + { + IconSelector.SetMonoScriptIconChangedCallback(new IconSelector.MonoScriptIconChangedCallback(this.MonoScriptIconChanged)); + GUIUtility.ExitGUI(); + } + } + } + } + else + { + if (ainfo.HasIcon()) + { + texture = AssetPreview.GetMiniTypeThumbnailFromClassID(ainfo.m_ClassID); + } + } + if (texture != null) + { + if (!ainfo.m_IconEnabled) + { + GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, a); + string tooltip = string.Empty; + } + this.iconToggleContent.image = texture; + if (GUI.Button(rect2, this.iconToggleContent, GUIStyle.none)) + { + ainfo.m_IconEnabled = !ainfo.m_IconEnabled; + this.SetIconState(ainfo); + } + GUI.color = color; + } + if (GUI.changed) + { + this.SetIconState(ainfo); + GUI.changed = false; + } + GUI.enabled = true; + GUI.color = color; + if (ainfo.HasGizmo()) + { + string tooltip = "Show/Hide Gizmo"; + Rect position3 = new Rect(rect.width - 23f, rect.y + (rect.height - num) * 0.5f, num, num); + ainfo.m_GizmoEnabled = GUI.Toggle(position3, ainfo.m_GizmoEnabled, new GUIContent(string.Empty, tooltip), AnnotationWindow.m_Styles.toggle); + if (GUI.changed) + { + this.SetGizmoState(ainfo); + } + } + GUI.enabled = enabled; + GUI.changed = changed; + GUI.color = color; + } + private void SetIconState(AInfo ainfo) + { + AnnotationUtility.SetIconEnabled(ainfo.m_ClassID, ainfo.m_ScriptClass, (!ainfo.m_IconEnabled) ? 0 : 1); + SceneView.RepaintAll(); + } + private void SetGizmoState(AInfo ainfo) + { + AnnotationUtility.SetGizmoEnabled(ainfo.m_ClassID, ainfo.m_ScriptClass, (!ainfo.m_GizmoEnabled) ? 0 : 1); + SceneView.RepaintAll(); + } + } +} diff --git a/UnityEditor/UnityEditor/ApiCompatibilityLevel.cs b/UnityEditor/UnityEditor/ApiCompatibilityLevel.cs new file mode 100644 index 00000000..a5b9353e --- /dev/null +++ b/UnityEditor/UnityEditor/ApiCompatibilityLevel.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum ApiCompatibilityLevel + { + NET_2_0 = 1, + NET_2_0_Subset + } +} diff --git a/UnityEditor/UnityEditor/AppStatusBar.cs b/UnityEditor/UnityEditor/AppStatusBar.cs new file mode 100644 index 00000000..4c02a64b --- /dev/null +++ b/UnityEditor/UnityEditor/AppStatusBar.cs @@ -0,0 +1,125 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AppStatusBar : GUIView + { + private static AppStatusBar s_AppStatusBar; + private static GUIContent[] s_StatusWheel; + private string m_LastMiniMemoryOverview = string.Empty; + private static GUIStyle background; + private static GUIStyle resize; + private void OnEnable() + { + AppStatusBar.s_AppStatusBar = this; + AppStatusBar.s_StatusWheel = new GUIContent[12]; + for (int i = 0; i < 12; i++) + { + AppStatusBar.s_StatusWheel[i] = EditorGUIUtility.IconContent("WaitSpin" + i.ToString("00")); + } + } + public static void StatusChanged() + { + if (AppStatusBar.s_AppStatusBar) + { + AppStatusBar.s_AppStatusBar.Repaint(); + } + } + private void OnInspectorUpdate() + { + string miniMemoryOverview = ProfilerDriver.miniMemoryOverview; + if (Unsupported.IsDeveloperBuild() && this.m_LastMiniMemoryOverview != miniMemoryOverview) + { + this.m_LastMiniMemoryOverview = miniMemoryOverview; + base.Repaint(); + } + } + private void OnGUI() + { + ConsoleWindow.LoadIcons(); + if (AppStatusBar.background == null) + { + AppStatusBar.background = "AppToolbar"; + AppStatusBar.resize = "WindowResizeMac"; + } + if (EditorApplication.isPlayingOrWillChangePlaymode) + { + GUI.color = HostView.kPlayModeDarken; + } + if (Event.current.type == EventType.Repaint) + { + AppStatusBar.background.Draw(new Rect(0f, 0f, base.position.width, base.position.height), false, false, false, false); + if (ContainerWindow.macEditor) + { + AppStatusBar.resize.Draw(new Rect(base.position.width - AppStatusBar.resize.fixedWidth, base.position.height - AppStatusBar.resize.fixedHeight, AppStatusBar.resize.fixedWidth, AppStatusBar.resize.fixedHeight), false, false, false, false); + } + } + bool isCompiling = EditorApplication.isCompiling; + GUILayout.Space(2f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(2f); + string statusText = LogEntries.GetStatusText(); + if (statusText != null) + { + int statusMask = LogEntries.GetStatusMask(); + GUIStyle statusStyleForErrorMode = ConsoleWindow.GetStatusStyleForErrorMode(statusMask); + GUILayout.Label(ConsoleWindow.GetIconForErrorMode(statusMask, false), statusStyleForErrorMode, new GUILayoutOption[0]); + GUILayout.Space(2f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(2f); + if (isCompiling) + { + GUILayout.Label(statusText, statusStyleForErrorMode, new GUILayoutOption[] + { + GUILayout.MaxWidth((float)(Screen.width - 52)) + }); + } + else + { + GUILayout.Label(statusText, statusStyleForErrorMode, new GUILayoutOption[0]); + } + GUILayout.FlexibleSpace(); + GUILayout.EndVertical(); + if (Event.current.type == EventType.MouseDown) + { + Event.current.Use(); + LogEntries.ClickStatusBar(Event.current.clickCount); + GUIUtility.ExitGUI(); + } + } + GUILayout.EndHorizontal(); + if (Event.current.type == EventType.Repaint) + { + float num = base.position.width - 24f; + if (AsyncProgressBar.isShowing) + { + num -= 143f; + EditorGUI.ProgressBar(new Rect(num, 0f, 140f, 19f), AsyncProgressBar.progress, AsyncProgressBar.progressInfo); + } + if (isCompiling) + { + int num2 = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10f, 11.99f); + GUI.Label(new Rect(base.position.width - 24f, 0f, (float)AppStatusBar.s_StatusWheel[num2].image.width, (float)AppStatusBar.s_StatusWheel[num2].image.height), AppStatusBar.s_StatusWheel[num2], GUIStyle.none); + } + if (Unsupported.IsBleedingEdgeBuild()) + { + Color color = GUI.color; + GUI.color = Color.yellow; + GUI.Label(new Rect(num - 310f, 0f, 310f, 19f), "THIS IS AN UNTESTED BLEEDINGEDGE UNITY BUILD"); + GUI.color = color; + } + else + { + if (Unsupported.IsDeveloperBuild()) + { + GUI.Label(new Rect(num - 200f, 0f, 200f, 19f), this.m_LastMiniMemoryOverview, EditorStyles.progressBarText); + EditorGUIUtility.CleanCache(this.m_LastMiniMemoryOverview); + } + } + } + base.DoWindowDecorationEnd(); + EditorGUI.ShowRepaints(); + } + } +} diff --git a/UnityEditor/UnityEditor/ArrayUtility.cs b/UnityEditor/UnityEditor/ArrayUtility.cs new file mode 100644 index 00000000..e86d6ac4 --- /dev/null +++ b/UnityEditor/UnityEditor/ArrayUtility.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections; +using System.Collections.Generic; +namespace UnityEditor +{ + public sealed class ArrayUtility + { + public static void Add(ref T[] array, T item) + { + Array.Resize(ref array, array.Length + 1); + array[array.Length - 1] = item; + } + public static bool ArrayEquals(T[] lhs, T[] rhs) + { + if (lhs.Length != rhs.Length) + { + return false; + } + for (int i = 0; i < lhs.Length; i++) + { + if (!lhs[i].Equals(rhs[i])) + { + return false; + } + } + return true; + } + public static void AddRange(ref T[] array, T[] items) + { + int num = array.Length; + Array.Resize(ref array, array.Length + items.Length); + for (int i = 0; i < items.Length; i++) + { + array[num + i] = items[i]; + } + } + public static void Insert(ref T[] array, int index, T item) + { + ArrayList arrayList = new ArrayList(); + arrayList.AddRange(array); + arrayList.Insert(index, item); + array = (arrayList.ToArray(typeof(T)) as T[]); + } + public static void Remove(ref T[] array, T item) + { + List list = new List(array); + list.Remove(item); + array = list.ToArray(); + } + public static List FindAll(T[] array, Predicate match) + { + List list = new List(array); + return list.FindAll(match); + } + public static T Find(T[] array, Predicate match) + { + List list = new List(array); + return list.Find(match); + } + public static int FindIndex(T[] array, Predicate match) + { + List list = new List(array); + return list.FindIndex(match); + } + public static int IndexOf(T[] array, T value) + { + List list = new List(array); + return list.IndexOf(value); + } + public static int LastIndexOf(T[] array, T value) + { + List list = new List(array); + return list.LastIndexOf(value); + } + public static void RemoveAt(ref T[] array, int index) + { + List list = new List(array); + list.RemoveAt(index); + array = list.ToArray(); + } + public static bool Contains(T[] array, T item) + { + List list = new List(array); + return list.Contains(item); + } + public static void Clear(ref T[] array) + { + Array.Clear(array, 0, array.Length); + Array.Resize(ref array, 0); + } + } +} diff --git a/UnityEditor/UnityEditor/AspectRatio.cs b/UnityEditor/UnityEditor/AspectRatio.cs new file mode 100644 index 00000000..ab90e277 --- /dev/null +++ b/UnityEditor/UnityEditor/AspectRatio.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum AspectRatio + { + AspectOthers, + Aspect4by3, + Aspect5by4, + Aspect16by10, + Aspect16by9 + } +} diff --git a/UnityEditor/UnityEditor/AssembleEditorSkin.cs b/UnityEditor/UnityEditor/AssembleEditorSkin.cs new file mode 100644 index 00000000..f344b4be --- /dev/null +++ b/UnityEditor/UnityEditor/AssembleEditorSkin.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor +{ + internal class AssembleEditorSkin : EditorWindow + { + public static void DoIt() + { + EditorApplication.ExecuteMenuItem("Tools/Regenerate Editor Skins Now"); + } + private static void RegenerateAllIconsWithMipLevels() + { + GenerateIconsWithMipLevels.GenerateAllIconsWithMipLevels(); + } + private static void RegenerateSelectedIconsWithMipLevels() + { + GenerateIconsWithMipLevels.GenerateSelectedIconsWithMips(); + } + } +} diff --git a/UnityEditor/UnityEditor/AssembliesShippedWithWebPlayerProvider.cs b/UnityEditor/UnityEditor/AssembliesShippedWithWebPlayerProvider.cs new file mode 100644 index 00000000..2790536d --- /dev/null +++ b/UnityEditor/UnityEditor/AssembliesShippedWithWebPlayerProvider.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEditor +{ + internal static class AssembliesShippedWithWebPlayerProvider + { + public static string[] ProvideAsArray() + { + return new string[] + { + "mscorlib.dll", + "System.dll", + "System.Core.dll", + "Mono.Security.dll" + }; + } + } +} diff --git a/UnityEditor/UnityEditor/AssemblyHelper.cs b/UnityEditor/UnityEditor/AssemblyHelper.cs new file mode 100644 index 00000000..0ff15361 --- /dev/null +++ b/UnityEditor/UnityEditor/AssemblyHelper.cs @@ -0,0 +1,347 @@ +using Mono.Cecil; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditor.Modules; +using UnityEngine; +namespace UnityEditor +{ + public class AssemblyHelper + { + private const int kDefaultDepth = 10; + public static void CheckForAssemblyFileNameMismatch(string assemblyPath) + { + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assemblyPath); + string text = AssemblyHelper.ExtractInternalAssemblyName(assemblyPath); + if (fileNameWithoutExtension != text) + { + UnityEngine.Debug.LogWarning(string.Concat(new string[] + { + "Assembly '", + text, + "' has non matching file name: '", + Path.GetFileName(assemblyPath), + "'. This can cause build issues on some platforms." + })); + } + } + public static bool IsTypeInEditorAssembly(Type t) + { + return t.Assembly.GetCustomAttributes(true).Any((object x) => x is AssemblyIsEditorAssembly); + } + public static string[] GetNamesOfAssembliesLoadedInCurrentDomain() + { + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + List list = new List(); + Assembly[] array = assemblies; + for (int i = 0; i < array.Length; i++) + { + Assembly assembly = array[i]; + try + { + list.Add(assembly.Location); + } + catch (NotSupportedException) + { + } + } + return list.ToArray(); + } + public static Assembly FindLoadedAssemblyWithName(string s) + { + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + Assembly[] array = assemblies; + for (int i = 0; i < array.Length; i++) + { + Assembly assembly = array[i]; + try + { + if (assembly.Location.Contains(s)) + { + return assembly; + } + } + catch (NotSupportedException) + { + } + } + return null; + } + public static string ExtractInternalAssemblyName(string path) + { + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(path); + return assemblyDefinition.Name.Name; + } + private static AssemblyDefinition GetAssemblyDefinitionCached(string path, Dictionary cache) + { + if (cache.ContainsKey(path)) + { + return cache[path]; + } + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(path); + cache[path] = assemblyDefinition; + return assemblyDefinition; + } + private static bool IgnoreAssembly(string assemblyPath, BuildTarget target) + { + if (target != BuildTarget.MetroPlayer) + { + if (target == BuildTarget.WP8Player) + { + if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("Microsoft.") != -1) + { + return true; + } + } + } + else + { + if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("WinRTLegacy.dll") != -1) + { + return true; + } + } + return AssemblyHelper.IsInternalAssembly(assemblyPath); + } + private static void AddReferencedAssembliesRecurse(string assemblyPath, List alreadyFoundAssemblies, string[] allAssemblyPaths, string[] foldersToSearch, Dictionary cache, BuildTarget target) + { + if (AssemblyHelper.IgnoreAssembly(assemblyPath, target)) + { + return; + } + AssemblyDefinition assemblyDefinitionCached = AssemblyHelper.GetAssemblyDefinitionCached(assemblyPath, cache); + if (assemblyDefinitionCached == null) + { + throw new ArgumentException("Referenced Assembly " + Path.GetFileName(assemblyPath) + " could not be found!"); + } + if (alreadyFoundAssemblies.IndexOf(assemblyPath) != -1) + { + return; + } + alreadyFoundAssemblies.Add(assemblyPath); + foreach (AssemblyNameReference current in assemblyDefinitionCached.MainModule.AssemblyReferences) + { + if (!(current.Name == "BridgeInterface")) + { + if (!(current.Name == "WinRTBridge")) + { + if (!(current.Name == "UnityEngineProxy")) + { + if (!AssemblyHelper.IgnoreAssembly(current.Name + ".dll", target)) + { + string text = AssemblyHelper.FindAssemblyName(current.FullName, current.Name, allAssemblyPaths, foldersToSearch, cache); + if (text == string.Empty) + { + throw new ArgumentException(string.Format("The Assembly {0} is referenced by {1}. But the dll is not allowed to be included or could not be found.", current.Name, assemblyDefinitionCached.MainModule.Assembly.Name.Name)); + } + AssemblyHelper.AddReferencedAssembliesRecurse(text, alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache, target); + } + } + } + } + } + } + private static string FindAssemblyName(string fullName, string name, string[] allAssemblyPaths, string[] foldersToSearch, Dictionary cache) + { + for (int i = 0; i < allAssemblyPaths.Length; i++) + { + AssemblyDefinition assemblyDefinitionCached = AssemblyHelper.GetAssemblyDefinitionCached(allAssemblyPaths[i], cache); + if (assemblyDefinitionCached.MainModule.Assembly.Name.Name == name) + { + return allAssemblyPaths[i]; + } + } + for (int j = 0; j < foldersToSearch.Length; j++) + { + string path = foldersToSearch[j]; + string text = Path.Combine(path, name + ".dll"); + if (File.Exists(text)) + { + return text; + } + } + return string.Empty; + } + public static string[] FindAssembliesReferencedBy(string[] paths, string[] foldersToSearch, BuildTarget target) + { + List list = new List(); + Dictionary cache = new Dictionary(); + for (int i = 0; i < paths.Length; i++) + { + AssemblyHelper.AddReferencedAssembliesRecurse(paths[i], list, paths, foldersToSearch, cache, target); + } + for (int j = 0; j < paths.Length; j++) + { + list.Remove(paths[j]); + } + return list.ToArray(); + } + public static string[] FindAssembliesReferencedBy(string path, string[] foldersToSearch, BuildTarget target) + { + return AssemblyHelper.FindAssembliesReferencedBy(new string[] + { + path + }, foldersToSearch, target); + } + private static bool IsTypeMonoBehaviourOrScriptableObject(AssemblyDefinition assembly, TypeReference type) + { + if (type == null) + { + return false; + } + if (type.FullName == "System.Object") + { + return false; + } + Assembly assembly2 = null; + if (type.Scope.Name == "UnityEngine") + { + assembly2 = typeof(MonoBehaviour).Assembly; + } + else + { + if (type.Scope.Name == "UnityEditor") + { + assembly2 = typeof(EditorWindow).Assembly; + } + } + if (assembly2 != null) + { + Type type2 = assembly2.GetType(type.FullName); + if (type2 == typeof(MonoBehaviour) || type2.IsSubclassOf(typeof(MonoBehaviour))) + { + return true; + } + if (type2 == typeof(ScriptableObject) || type2.IsSubclassOf(typeof(ScriptableObject))) + { + return true; + } + } + TypeDefinition typeDefinition = null; + try + { + typeDefinition = type.Resolve(); + } + catch (AssemblyResolutionException) + { + } + return typeDefinition != null && AssemblyHelper.IsTypeMonoBehaviourOrScriptableObject(assembly, typeDefinition.BaseType); + } + public static void ExtractAllClassesThatInheritMonoBehaviourAndScriptableObject(string path, out string[] classNamesArray, out string[] classNameSpacesArray) + { + List list = new List(); + List list2 = new List(); + ReaderParameters readerParameters = new ReaderParameters(); + DefaultAssemblyResolver defaultAssemblyResolver = new DefaultAssemblyResolver(); + defaultAssemblyResolver.AddSearchDirectory(Path.GetDirectoryName(path)); + readerParameters.AssemblyResolver = defaultAssemblyResolver; + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(path, readerParameters); + foreach (ModuleDefinition current in assemblyDefinition.Modules) + { + foreach (TypeDefinition current2 in current.Types) + { + TypeReference baseType = current2.BaseType; + if (AssemblyHelper.IsTypeMonoBehaviourOrScriptableObject(assemblyDefinition, baseType)) + { + list.Add(current2.Name); + list2.Add(current2.Namespace); + } + } + } + classNamesArray = list.ToArray(); + classNameSpacesArray = list2.ToArray(); + } + public static AssemblyTypeInfoGenerator.ClassInfo[] ExtractAssemblyTypeInfo(string assemblyPathName) + { + AssemblyTypeInfoGenerator assemblyTypeInfoGenerator = new AssemblyTypeInfoGenerator(assemblyPathName); + assemblyTypeInfoGenerator.GatherClassInfo(); + return assemblyTypeInfoGenerator.ClassInfoArray; + } + internal static Type[] GetTypesFromAssembly(Assembly assembly) + { + if (assembly == null) + { + return new Type[0]; + } + Type[] result; + try + { + result = assembly.GetTypes(); + } + catch (ReflectionTypeLoadException) + { + result = new Type[0]; + } + return result; + } + [DebuggerHidden] + internal static IEnumerable FindImplementors(Assembly assembly) where T : class + { + AssemblyHelper.c__Iterator0 c__Iterator = new AssemblyHelper.c__Iterator0(); + c__Iterator.assembly = assembly; + c__Iterator.<$>assembly = assembly; + AssemblyHelper.c__Iterator0 expr_15 = c__Iterator; + expr_15.$PC = -2; + return expr_15; + } + public static bool IsManagedAssembly(string file) + { + if (!".dll".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) + { + return false; + } + try + { + using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + BinaryReader binaryReader = new BinaryReader(stream); + stream.Position = 60L; + uint num = binaryReader.ReadUInt32(); + stream.Position = (long)((ulong)(num + 232u)); + return 0uL != binaryReader.ReadUInt64(); + } + } + catch + { + } + return false; + } + public static bool IsInternalAssembly(string file) + { + return ModuleManager.IsRegisteredModule(file); + } + internal static ICollection FindAssemblies(string basePath) + { + return AssemblyHelper.FindAssemblies(basePath, 10); + } + internal static ICollection FindAssemblies(string basePath, int maxDepth) + { + List list = new List(); + if (maxDepth == 0) + { + return list; + } + try + { + DirectoryInfo directoryInfo = new DirectoryInfo(basePath); + list.AddRange( + from file in directoryInfo.GetFiles() + where AssemblyHelper.IsManagedAssembly(file.FullName) + select file.FullName); + DirectoryInfo[] directories = directoryInfo.GetDirectories(); + for (int i = 0; i < directories.Length; i++) + { + DirectoryInfo directoryInfo2 = directories[i]; + list.AddRange(AssemblyHelper.FindAssemblies(directoryInfo2.FullName, maxDepth - 1)); + } + } + catch (Exception) + { + } + return list; + } + } +} diff --git a/UnityEditor/UnityEditor/AssemblyReferenceChecker.cs b/UnityEditor/UnityEditor/AssemblyReferenceChecker.cs new file mode 100644 index 00000000..7b9a0482 --- /dev/null +++ b/UnityEditor/UnityEditor/AssemblyReferenceChecker.cs @@ -0,0 +1,179 @@ +using Mono.Cecil; +using Mono.Cecil.Cil; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +namespace UnityEditor +{ + internal class AssemblyReferenceChecker + { + private HashSet referencedMethods = new HashSet(); + private HashSet referencedTypes = new HashSet(); + private HashSet definedMethods = new HashSet(); + private HashSet assemblyDefinitions = new HashSet(); + private HashSet assemblyFileNames = new HashSet(); + private DateTime startTime = DateTime.MinValue; + private void CollectReferencesFromRootsRecursive(string dir, IEnumerable roots, bool ignoreSystemDlls) + { + foreach (string current in roots) + { + string fileName = Path.Combine(dir, current); + if (!this.assemblyFileNames.Contains(current)) + { + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(fileName); + if (!ignoreSystemDlls || !this.IsiPhoneIgnoredSystemDll(assemblyDefinition.Name.Name)) + { + this.assemblyFileNames.Add(current); + this.assemblyDefinitions.Add(assemblyDefinition); + foreach (AssemblyNameReference current2 in assemblyDefinition.MainModule.AssemblyReferences) + { + string text = current2.Name + ".dll"; + if (!this.assemblyFileNames.Contains(text)) + { + this.CollectReferencesFromRootsRecursive(dir, new string[] + { + text + }, ignoreSystemDlls); + } + } + } + } + } + } + public void CollectReferencesFromRoots(string dir, IEnumerable roots, bool withMethods, float progressValue, bool ignoreSystemDlls) + { + this.CollectReferencesFromRootsRecursive(dir, roots, ignoreSystemDlls); + AssemblyDefinition[] array = this.assemblyDefinitions.ToArray(); + this.referencedTypes = MonoAOTRegistration.BuildReferencedTypeList(array); + if (withMethods) + { + this.CollectReferencedMethods(array, this.referencedMethods, this.definedMethods, progressValue); + } + } + public void CollectReferences(string path, bool withMethods, float progressValue, bool ignoreSystemDlls) + { + this.assemblyDefinitions = new HashSet(); + string[] array = (!Directory.Exists(path)) ? new string[0] : Directory.GetFiles(path); + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text = array2[i]; + if (!(Path.GetExtension(text) != ".dll")) + { + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(text); + if (!ignoreSystemDlls || !this.IsiPhoneIgnoredSystemDll(assemblyDefinition.Name.Name)) + { + this.assemblyFileNames.Add(Path.GetFileName(text)); + this.assemblyDefinitions.Add(assemblyDefinition); + } + } + } + AssemblyDefinition[] array3 = this.assemblyDefinitions.ToArray(); + this.referencedTypes = MonoAOTRegistration.BuildReferencedTypeList(array3); + if (withMethods) + { + this.CollectReferencedMethods(array3, this.referencedMethods, this.definedMethods, progressValue); + } + } + private void CollectReferencedMethods(AssemblyDefinition[] definitions, HashSet referencedMethods, HashSet definedMethods, float progressValue) + { + for (int i = 0; i < definitions.Length; i++) + { + AssemblyDefinition assemblyDefinition = definitions[i]; + foreach (TypeDefinition current in assemblyDefinition.MainModule.Types) + { + this.CollectReferencedMethods(current, referencedMethods, definedMethods, progressValue); + } + } + } + private void CollectReferencedMethods(TypeDefinition typ, HashSet referencedMethods, HashSet definedMethods, float progressValue) + { + this.DisplayProgress(progressValue); + foreach (TypeDefinition current in typ.NestedTypes) + { + this.CollectReferencedMethods(current, referencedMethods, definedMethods, progressValue); + } + foreach (MethodDefinition current2 in typ.Methods) + { + if (current2.HasBody) + { + foreach (Instruction current3 in current2.Body.Instructions) + { + if (OpCodes.Call == current3.OpCode) + { + referencedMethods.Add(current3.Operand.ToString()); + } + } + definedMethods.Add(current2.ToString()); + } + } + } + private void DisplayProgress(float progressValue) + { + TimeSpan timeSpan = DateTime.Now - this.startTime; + string[] array = new string[] + { + "Fetching assembly references", + "Building list of referenced assemblies..." + }; + if (timeSpan.TotalMilliseconds >= 100.0) + { + if (EditorUtility.DisplayCancelableProgressBar(array[0], array[1], progressValue)) + { + throw new OperationCanceledException(); + } + this.startTime = DateTime.Now; + } + } + public bool HasReferenceToMethod(string methodName) + { + return this.referencedMethods.Any((string item) => item.Contains(methodName)); + } + public bool HasDefinedMethod(string methodName) + { + return this.definedMethods.Any((string item) => item.Contains(methodName)); + } + public bool HasReferenceToType(string typeName) + { + return this.referencedTypes.Any((string item) => item.StartsWith(typeName)); + } + public AssemblyDefinition[] GetAssemblyDefinitions() + { + return this.assemblyDefinitions.ToArray(); + } + public string[] GetAssemblyFileNames() + { + return this.assemblyFileNames.ToArray(); + } + public string WhoReferencesClass(string klass, bool ignoreSystemDlls) + { + foreach (AssemblyDefinition current in this.assemblyDefinitions) + { + if (!ignoreSystemDlls || !this.IsiPhoneIgnoredSystemDll(current.Name.Name)) + { + AssemblyDefinition[] assemblies = new AssemblyDefinition[] + { + current + }; + HashSet source = MonoAOTRegistration.BuildReferencedTypeList(assemblies); + if (source.Any((string item) => item.StartsWith(klass))) + { + return current.Name.Name; + } + } + } + return null; + } + private bool IsiPhoneIgnoredSystemDll(string name) + { + return name.StartsWith("System") || name.Equals("UnityEngine") || name.Equals("Mono.Posix"); + } + public static bool GetScriptsHaveMouseEvents(string path) + { + AssemblyReferenceChecker assemblyReferenceChecker = new AssemblyReferenceChecker(); + assemblyReferenceChecker.CollectReferences(path, true, 0f, true); + return assemblyReferenceChecker.HasDefinedMethod("OnMouse"); + } + } +} diff --git a/UnityEditor/UnityEditor/AssemblyReloadEvents.cs b/UnityEditor/UnityEditor/AssemblyReloadEvents.cs new file mode 100644 index 00000000..559d936a --- /dev/null +++ b/UnityEditor/UnityEditor/AssemblyReloadEvents.cs @@ -0,0 +1,21 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssemblyReloadEvents + { + public static void OnBeforeAssemblyReload() + { + Security.ClearVerifiedAssemblies(); + InternalEditorUtility.AuxWindowManager_OnAssemblyReload(); + } + public static void OnAfterAssemblyReload() + { + foreach (ProjectBrowser current in ProjectBrowser.GetAllProjectBrowsers()) + { + current.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs b/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs new file mode 100644 index 00000000..13706483 --- /dev/null +++ b/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs @@ -0,0 +1,180 @@ +using Mono.Cecil; +using Mono.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Linq; +namespace UnityEditor +{ + public class AssemblyTypeInfoGenerator + { + public struct FieldInfo + { + public string name; + public string type; + } + public struct ClassInfo + { + public string name; + public AssemblyTypeInfoGenerator.FieldInfo[] fields; + } + private AssemblyDefinition assembly_; + private List classes_ = new List(); + public AssemblyTypeInfoGenerator.ClassInfo[] ClassInfoArray + { + get + { + return this.classes_.ToArray(); + } + } + public AssemblyTypeInfoGenerator(string assembly) + { + this.assembly_ = AssemblyDefinition.ReadAssembly(assembly); + } + private string GetFullTypeName(TypeReference type) + { + return type.FullName.Replace('/', '+').Replace('<', '[').Replace('>', ']'); + } + private TypeReference ResolveGenericInstanceType(TypeReference typeToResolve, Dictionary genericInstanceTypeMap) + { + ArrayType arrayType = typeToResolve as ArrayType; + if (arrayType != null) + { + typeToResolve = new ArrayType(this.ResolveGenericInstanceType(arrayType.ElementType, genericInstanceTypeMap), arrayType.Rank); + } + while (genericInstanceTypeMap.ContainsKey(typeToResolve)) + { + typeToResolve = genericInstanceTypeMap[typeToResolve]; + } + if (typeToResolve.IsGenericInstance) + { + GenericInstanceType genericInstanceType = (GenericInstanceType)typeToResolve; + typeToResolve = this.MakeGenericInstance(genericInstanceType.ElementType, genericInstanceType.GenericArguments, genericInstanceTypeMap); + } + return typeToResolve; + } + private void AddType(TypeReference typeRef, Dictionary genericInstanceTypeMap) + { + if (this.classes_.Any((AssemblyTypeInfoGenerator.ClassInfo x) => x.name == this.GetFullTypeName(typeRef))) + { + return; + } + TypeDefinition typeDefinition; + try + { + typeDefinition = typeRef.Resolve(); + } + catch (AssemblyResolutionException) + { + return; + } + if (typeRef.IsGenericInstance) + { + Collection genericArguments = ((GenericInstanceType)typeRef).GenericArguments; + Collection genericParameters = typeDefinition.GenericParameters; + for (int i = 0; i < genericArguments.Count; i++) + { + if (genericParameters[i] != genericArguments[i]) + { + genericInstanceTypeMap[genericParameters[i]] = genericArguments[i]; + } + } + } + AssemblyTypeInfoGenerator.ClassInfo item = default(AssemblyTypeInfoGenerator.ClassInfo); + item.name = this.GetFullTypeName(typeRef); + item.fields = this.GetFields(typeDefinition, typeRef.IsGenericInstance, genericInstanceTypeMap); + this.classes_.Add(item); + this.AddNestedTypes(typeDefinition, genericInstanceTypeMap); + this.AddBaseType(typeRef, genericInstanceTypeMap); + } + private void AddNestedTypes(TypeDefinition type, Dictionary genericInstanceTypeMap) + { + foreach (TypeDefinition current in type.NestedTypes) + { + this.AddType(current, genericInstanceTypeMap); + } + } + private void AddBaseType(TypeReference typeRef, Dictionary genericInstanceTypeMap) + { + TypeReference typeReference = typeRef.Resolve().BaseType; + if (typeReference != null) + { + if (typeRef.IsGenericInstance && typeReference.IsGenericInstance) + { + GenericInstanceType genericInstanceType = (GenericInstanceType)typeReference; + typeReference = this.MakeGenericInstance(genericInstanceType.ElementType, genericInstanceType.GenericArguments, genericInstanceTypeMap); + } + this.AddType(typeReference, genericInstanceTypeMap); + } + } + private TypeReference MakeGenericInstance(TypeReference genericClass, IEnumerable arguments, Dictionary genericInstanceTypeMap) + { + GenericInstanceType genericInstanceType = new GenericInstanceType(genericClass); + foreach (TypeReference current in + from x in arguments + select this.ResolveGenericInstanceType(x, genericInstanceTypeMap)) + { + genericInstanceType.GenericArguments.Add(current); + } + return genericInstanceType; + } + private AssemblyTypeInfoGenerator.FieldInfo[] GetFields(TypeDefinition type, bool isGenericInstance, Dictionary genericInstanceTypeMap) + { + List list = new List(); + foreach (FieldDefinition current in type.Fields) + { + AssemblyTypeInfoGenerator.FieldInfo? fieldInfo = this.GetFieldInfo(type, current, isGenericInstance, genericInstanceTypeMap); + if (fieldInfo.HasValue) + { + list.Add(fieldInfo.Value); + } + } + return list.ToArray(); + } + private AssemblyTypeInfoGenerator.FieldInfo? GetFieldInfo(TypeDefinition type, FieldDefinition field, bool isDeclaringTypeGenericInstance, Dictionary genericInstanceTypeMap) + { + if (field.IsStatic) + { + return null; + } + if (field.IsInitOnly) + { + return null; + } + if ((ushort)(field.Attributes & FieldAttributes.NotSerialized) != 0) + { + return null; + } + bool flag = field.CustomAttributes.Any((CustomAttribute ca) => ca.AttributeType.Name == "SerializeField"); + if (!field.IsPublic && !flag) + { + return null; + } + AssemblyTypeInfoGenerator.FieldInfo value = default(AssemblyTypeInfoGenerator.FieldInfo); + value.name = field.Name; + TypeReference type2; + if (isDeclaringTypeGenericInstance) + { + type2 = this.ResolveGenericInstanceType(field.FieldType, genericInstanceTypeMap); + } + else + { + type2 = field.FieldType; + } + value.type = this.GetFullTypeName(type2); + return new AssemblyTypeInfoGenerator.FieldInfo?(value); + } + public void GatherClassInfo() + { + foreach (ModuleDefinition current in this.assembly_.Modules) + { + foreach (TypeDefinition current2 in current.Types) + { + if (!(current2.Name == "")) + { + this.AddType(current2, new Dictionary()); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetDatabase.cs b/UnityEditor/UnityEditor/AssetDatabase.cs new file mode 100644 index 00000000..4636d8c1 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetDatabase.cs @@ -0,0 +1,362 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEditor +{ + public sealed class AssetDatabase + { + internal static extern bool isLocked + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static string[] FindAssets(string filter) + { + return AssetDatabase.FindAssets(filter, null); + } + public static string[] FindAssets(string filter, string[] searchInFolders) + { + SearchFilter searchFilter = new SearchFilter(); + SearchUtility.ParseSearchString(filter, searchFilter); + if (searchInFolders != null) + { + searchFilter.folders = searchInFolders; + } + return AssetDatabase.FindAssets(searchFilter); + } + private static string[] FindAssets(SearchFilter searchFilter) + { + if (searchFilter.folders != null && searchFilter.folders.Length > 0) + { + return AssetDatabase.SearchInFolders(searchFilter); + } + return AssetDatabase.SearchAllAssets(searchFilter); + } + private static string[] SearchAllAssets(SearchFilter searchFilter) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(searchFilter); + hierarchyProperty.Reset(); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + list.Add(hierarchyProperty.guid); + } + return list.ToArray(); + } + private static string[] SearchInFolders(SearchFilter searchFilter) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + List list = new List(); + string[] folders = searchFilter.folders; + for (int i = 0; i < folders.Length; i++) + { + string text = folders[i]; + hierarchyProperty.SetSearchFilter(new SearchFilter()); + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(text); + if (hierarchyProperty.Find(mainAssetInstanceID, null)) + { + hierarchyProperty.SetSearchFilter(searchFilter); + int depth = hierarchyProperty.depth; + int[] expanded = null; + while (hierarchyProperty.NextWithDepthCheck(expanded, depth + 1)) + { + list.Add(hierarchyProperty.guid); + } + } + else + { + Debug.LogWarning("AssetDatabase.FindAssets: Folder not found: '" + text + "'"); + } + } + return list.ToArray(); + } + public static bool Contains(UnityEngine.Object obj) + { + return AssetDatabase.Contains(obj.GetInstanceID()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Contains(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CreateFolder(string parentFolder, string newFolderName); + public static bool IsMainAsset(UnityEngine.Object obj) + { + return AssetDatabase.IsMainAsset(obj.GetInstanceID()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsMainAsset(int instanceID); + public static bool IsSubAsset(UnityEngine.Object obj) + { + return AssetDatabase.IsSubAsset(obj.GetInstanceID()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsSubAsset(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GenerateUniqueAssetPath(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StartAssetEditing(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopAssetEditing(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string ValidateMoveAsset(string oldPath, string newPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string MoveAsset(string oldPath, string newPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string RenameAsset(string pathName, string newName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool MoveAssetToTrash(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DeleteAsset(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ImportAsset(string path, [DefaultValue("ImportAssetOptions.Default")] ImportAssetOptions options); + [ExcludeFromDocs] + public static void ImportAsset(string path) + { + ImportAssetOptions options = ImportAssetOptions.Default; + AssetDatabase.ImportAsset(path, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CopyAsset(string path, string newPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool WriteImportSettingsIfDirty(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CreateAsset(UnityEngine.Object asset, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AddObjectToAsset(UnityEngine.Object objectToAdd, string assetPath); + public static void AddObjectToAsset(UnityEngine.Object objectToAdd, UnityEngine.Object assetObject) + { + AssetDatabase.AddObjectToAsset_OBJ_Internal(objectToAdd, assetObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void AddObjectToAsset_OBJ_Internal(UnityEngine.Object newAsset, UnityEngine.Object sameAssetFile); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAssetPath(UnityEngine.Object assetObject); + public static string GetAssetPath(int instanceID) + { + return AssetDatabase.GetAssetPathFromInstanceID(instanceID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string GetAssetPathFromInstanceID(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetMainAssetInstanceID(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAssetOrScenePath(UnityEngine.Object assetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetTextMetaDataPathFromAssetPath(string path); + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object LoadAssetAtPath(string assetPath, Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object LoadMainAssetAtPath(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object[] LoadAllAssetRepresentationsAtPath(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object[] LoadAllAssetsAtPath(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAllAssetPaths(); + [Obsolete("Please use AssetDatabase.Refresh instead", true)] + public static void RefreshDelayed(ImportAssetOptions options) + { + } + [Obsolete("Please use AssetDatabase.Refresh instead", true)] + public static void RefreshDelayed() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Refresh([DefaultValue("ImportAssetOptions.Default")] ImportAssetOptions options); + [ExcludeFromDocs] + public static void Refresh() + { + ImportAssetOptions options = ImportAssetOptions.Default; + AssetDatabase.Refresh(options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool OpenAsset(int instanceID, [DefaultValue("-1")] int lineNumber); + [ExcludeFromDocs] + public static bool OpenAsset(int instanceID) + { + int lineNumber = -1; + return AssetDatabase.OpenAsset(instanceID, lineNumber); + } + [ExcludeFromDocs] + public static bool OpenAsset(UnityEngine.Object target) + { + int lineNumber = -1; + return AssetDatabase.OpenAsset(target, lineNumber); + } + public static bool OpenAsset(UnityEngine.Object target, [DefaultValue("-1")] int lineNumber) + { + return target && AssetDatabase.OpenAsset(target.GetInstanceID(), lineNumber); + } + public static bool OpenAsset(UnityEngine.Object[] objects) + { + bool result = true; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object target = objects[i]; + if (!AssetDatabase.OpenAsset(target)) + { + result = false; + } + } + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string AssetPathToGUID(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GUIDToAssetPath(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetAssetHashFromPath(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetInstanceIDFromGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SaveAssets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture GetCachedIcon(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLabels(UnityEngine.Object obj, string[] labels); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_GetAllLabels(out string[] labels, out float[] scores); + internal static Dictionary GetAllLabels() + { + string[] array; + float[] array2; + AssetDatabase.INTERNAL_GetAllLabels(out array, out array2); + Dictionary dictionary = new Dictionary(array.Length); + for (int i = 0; i < array.Length; i++) + { + dictionary[array[i]] = array2[i]; + } + return dictionary; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetLabels(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearLabels(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string[] MatchLabelsPartial(UnityEngine.Object obj, string partial); + private static string[] GetDependencies(string pathName) + { + return AssetDatabase.GetDependencies(new string[] + { + pathName + }); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetDependencies(string[] pathNames); + public static void ExportPackage(string assetPathName, string fileName) + { + AssetDatabase.ExportPackage(new string[] + { + assetPathName + }, fileName, ExportPackageOptions.Default); + } + public static void ExportPackage(string assetPathName, string fileName, ExportPackageOptions flags) + { + AssetDatabase.ExportPackage(new string[] + { + assetPathName + }, fileName, flags); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExportPackage(string[] assetPathNames, string fileName, [DefaultValue("ExportPackageOptions.Default")] ExportPackageOptions flags); + [ExcludeFromDocs] + public static void ExportPackage(string[] assetPathNames, string fileName) + { + ExportPackageOptions flags = ExportPackageOptions.Default; + AssetDatabase.ExportPackage(assetPathNames, fileName, flags); + } + public static void ImportPackage(string packagePath, bool interactive) + { + string packageIconPath; + AssetsItem[] array = AssetServer.ImportPackageStep1(packagePath, out packageIconPath); + if (array == null) + { + return; + } + if (interactive) + { + PackageImport.ShowImportPackage(packagePath, array, packageIconPath); + } + else + { + AssetServer.ImportPackageStep2(array); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetUniquePathNameAtSelectedPath(string fileName); + public static bool IsOpenForEdit(UnityEngine.Object assetObject) + { + string assetOrScenePath = AssetDatabase.GetAssetOrScenePath(assetObject); + return AssetDatabase.IsOpenForEdit(assetOrScenePath); + } + public static bool IsOpenForEdit(string assetPath) + { + string empty = string.Empty; + return AssetDatabase.IsOpenForEdit(assetPath, out empty); + } + public static bool IsOpenForEdit(UnityEngine.Object assetObject, out string message) + { + string assetOrScenePath = AssetDatabase.GetAssetOrScenePath(assetObject); + return AssetDatabase.IsOpenForEdit(assetOrScenePath, out message); + } + public static bool IsOpenForEdit(string assetPath, out string message) + { + return AssetModificationProcessorInternal.IsOpenForEdit(assetPath, out message); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetBuiltinExtraResource(Type type, string path); + public static T GetBuiltinExtraResource(string path) where T : UnityEngine.Object + { + return (T)((object)AssetDatabase.GetBuiltinExtraResource(typeof(T), path)); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetDeleteResult.cs b/UnityEditor/UnityEditor/AssetDeleteResult.cs new file mode 100644 index 00000000..ec6fefe6 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetDeleteResult.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum AssetDeleteResult + { + DidNotDelete = 0, + FailedDelete = 1, + DidDelete = 2 + } +} diff --git a/UnityEditor/UnityEditor/AssetImporter.cs b/UnityEditor/UnityEditor/AssetImporter.cs new file mode 100644 index 00000000..50d26f9c --- /dev/null +++ b/UnityEditor/UnityEditor/AssetImporter.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public class AssetImporter : UnityEngine.Object + { + public extern string assetPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ulong assetTimeStamp + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string userData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetImporter GetAtPath(string path); + } +} diff --git a/UnityEditor/UnityEditor/AssetImporterInspector.cs b/UnityEditor/UnityEditor/AssetImporterInspector.cs new file mode 100644 index 00000000..b43b41aa --- /dev/null +++ b/UnityEditor/UnityEditor/AssetImporterInspector.cs @@ -0,0 +1,217 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class AssetImporterInspector : Editor + { + private ulong m_AssetTimeStamp; + private bool m_MightHaveModified; + internal Editor m_AssetEditor; + internal Editor assetEditor + { + get + { + return this.m_AssetEditor; + } + } + internal override string targetTitle + { + get + { + return this.assetEditor.targetTitle + " Import Settings"; + } + } + internal override int referenceTargetIndex + { + get + { + return base.referenceTargetIndex; + } + set + { + base.referenceTargetIndex = value; + this.assetEditor.referenceTargetIndex = value; + } + } + internal override IPreviewable Preview + { + get + { + if (!this.useAssetDrawPreview) + { + return base.Preview; + } + if (this.m_Preview == null) + { + return this.assetEditor ?? base.Preview; + } + return this.m_Preview; + } + } + protected virtual bool useAssetDrawPreview + { + get + { + return true; + } + } + internal virtual bool showImportedObject + { + get + { + return true; + } + } + internal override void OnHeaderIconGUI(Rect iconRect) + { + this.assetEditor.OnHeaderIconGUI(iconRect); + } + internal override SerializedObject GetSerializedObjectInternal() + { + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = SerializedObject.LoadFromCache(base.GetInstanceID()); + } + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(base.targets); + } + return this.m_SerializedObject; + } + public void OnDisable() + { + AssetImporter assetImporter = this.target as AssetImporter; + if (Unsupported.IsDestroyScriptableObject(this) && this.m_MightHaveModified && assetImporter != null && !InternalEditorUtility.ignoreInspectorChanges && this.HasModified() && !this.AssetWasUpdated()) + { + string message = "Unapplied import settings for '" + assetImporter.assetPath + "'"; + if (base.targets.Length > 1) + { + message = "Unapplied import settings for '" + base.targets.Length + "' files"; + } + if (EditorUtility.DisplayDialog("Unapplied import settings", message, "Apply", "Revert")) + { + this.Apply(); + this.m_MightHaveModified = false; + AssetImporterInspector.ImportAssets(this.GetAssetPaths()); + } + } + if (this.m_SerializedObject != null && this.m_SerializedObject.hasModifiedProperties) + { + this.m_SerializedObject.Cache(base.GetInstanceID()); + this.m_SerializedObject = null; + } + } + internal virtual void Awake() + { + this.ResetTimeStamp(); + this.ResetValues(); + } + private string[] GetAssetPaths() + { + UnityEngine.Object[] targets = base.targets; + string[] array = new string[targets.Length]; + for (int i = 0; i < targets.Length; i++) + { + AssetImporter assetImporter = targets[i] as AssetImporter; + array[i] = assetImporter.assetPath; + } + return array; + } + internal virtual void ResetValues() + { + base.serializedObject.SetIsDifferentCacheDirty(); + base.serializedObject.Update(); + } + internal virtual bool HasModified() + { + return base.serializedObject.hasModifiedProperties; + } + internal virtual void Apply() + { + base.serializedObject.ApplyModifiedPropertiesWithoutUndo(); + } + internal bool AssetWasUpdated() + { + AssetImporter assetImporter = this.target as AssetImporter; + if (this.m_AssetTimeStamp == 0uL) + { + this.ResetTimeStamp(); + } + return assetImporter != null && this.m_AssetTimeStamp != assetImporter.assetTimeStamp; + } + internal void ResetTimeStamp() + { + AssetImporter assetImporter = this.target as AssetImporter; + if (assetImporter != null) + { + this.m_AssetTimeStamp = assetImporter.assetTimeStamp; + } + } + internal void ApplyAndImport() + { + this.Apply(); + this.m_MightHaveModified = false; + AssetImporterInspector.ImportAssets(this.GetAssetPaths()); + this.ResetValues(); + } + private static void ImportAssets(string[] paths) + { + for (int i = 0; i < paths.Length; i++) + { + string path = paths[i]; + AssetDatabase.WriteImportSettingsIfDirty(path); + } + try + { + AssetDatabase.StartAssetEditing(); + for (int j = 0; j < paths.Length; j++) + { + string path2 = paths[j]; + AssetDatabase.ImportAsset(path2); + } + } + finally + { + AssetDatabase.StopAssetEditing(); + } + } + protected void ApplyRevertGUI() + { + this.m_MightHaveModified = true; + EditorGUILayout.Space(); + bool enabled = GUI.enabled; + GUI.enabled = (this.HasModified() && enabled); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Revert", new GUILayoutOption[0])) + { + this.m_MightHaveModified = false; + this.ResetTimeStamp(); + this.ResetValues(); + if (this.HasModified()) + { + Debug.LogError("Importer reports modified values after reset."); + } + } + bool flag = false; + if (GUILayout.Button("Apply", new GUILayoutOption[0])) + { + this.ApplyAndImport(); + flag = true; + } + if (this.AssetWasUpdated() && Event.current.type != EventType.Layout) + { + this.ResetTimeStamp(); + this.ResetValues(); + base.Repaint(); + } + GUILayout.EndHorizontal(); + GUI.enabled = enabled; + if (flag) + { + GUIUtility.ExitGUI(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs b/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs new file mode 100644 index 00000000..506f8304 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs @@ -0,0 +1,74 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class AssetImporterTabbedEditor : AssetImporterInspector + { + protected Type[] m_SubEditorTypes; + protected string[] m_SubEditorNames; + private int m_ActiveEditorIndex; + private AssetImporterInspector m_ActiveEditor; + public AssetImporterInspector activeEditor + { + get + { + return this.m_ActiveEditor; + } + } + internal virtual void OnEnable() + { + this.m_ActiveEditorIndex = EditorPrefs.GetInt(base.GetType().Name + "ActiveEditorIndex", 0); + if (this.m_ActiveEditor == null) + { + this.m_ActiveEditor = (Editor.CreateEditor(base.targets, this.m_SubEditorTypes[this.m_ActiveEditorIndex]) as AssetImporterInspector); + } + } + private void OnDestroy() + { + AssetImporterInspector activeEditor = this.activeEditor; + if (activeEditor != null) + { + this.m_ActiveEditor = null; + UnityEngine.Object.DestroyImmediate(activeEditor); + } + } + public override void OnInspectorGUI() + { + if (this.m_ActiveEditor.m_AssetEditor == null) + { + this.m_ActiveEditor.m_AssetEditor = base.assetEditor; + } + EditorGUI.BeginDisabledGroup(false); + GUI.enabled = true; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginChangeCheck(); + this.m_ActiveEditorIndex = GUILayout.Toolbar(this.m_ActiveEditorIndex, this.m_SubEditorNames, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetInt(base.GetType().Name + "ActiveEditorIndex", this.m_ActiveEditorIndex); + AssetImporterInspector activeEditor = this.activeEditor; + this.m_ActiveEditor = null; + UnityEngine.Object.DestroyImmediate(activeEditor); + this.m_ActiveEditor = (Editor.CreateEditor(base.targets, this.m_SubEditorTypes[this.m_ActiveEditorIndex]) as AssetImporterInspector); + this.m_ActiveEditor.m_AssetEditor = base.assetEditor; + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + this.activeEditor.OnInspectorGUI(); + } + public override void OnPreviewSettings() + { + this.activeEditor.OnPreviewSettings(); + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.activeEditor.OnInteractivePreviewGUI(r, background); + } + public override bool HasPreviewGUI() + { + return !(this.activeEditor == null) && this.activeEditor.HasPreviewGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetInspector.cs b/UnityEditor/UnityEditor/AssetInspector.cs new file mode 100644 index 00000000..17c1a477 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetInspector.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetInspector + { + private static AssetInspector s_Instance; + private GUIContent[] m_Menu = new GUIContent[] + { + EditorGUIUtility.TextContent("Show Diff"), + EditorGUIUtility.TextContent("Show History"), + EditorGUIUtility.TextContent("Discard") + }; + private GUIContent[] m_UnmodifiedMenu = new GUIContent[] + { + EditorGUIUtility.TextContent("Show History") + }; + private AssetInspector() + { + } + internal static bool IsAssetServerSetUp() + { + return InternalEditorUtility.HasMaint() && ASEditorBackend.SettingsAreValid(); + } + private bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) + { + return (flagToCheck & flags) != ChangeFlags.None; + } + public static AssetInspector Get() + { + if (AssetInspector.s_Instance == null) + { + AssetInspector.s_Instance = new AssetInspector(); + } + return AssetInspector.s_Instance; + } + private string AddChangesetFlag(string str, string strToAdd) + { + if (str != string.Empty) + { + str += ", "; + str += strToAdd; + } + else + { + str = strToAdd; + } + return str; + } + private string GetGUID() + { + if (Selection.objects.Length == 0) + { + return string.Empty; + } + return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(Selection.objects[0])); + } + private void DoShowDiff(string guid) + { + List list = new List(); + List list2 = new List(); + int workingItemChangeset = AssetServer.GetWorkingItemChangeset(guid); + list.Add(guid); + list2.Add(new CompareInfo(workingItemChangeset, -1, 0, 1)); + Debug.Log("Comparing asset revisions " + workingItemChangeset.ToString() + " and Local"); + AssetServer.CompareFiles(list.ToArray(), list2.ToArray()); + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if ((bool)userData && selected == 0) + { + selected = 1; + } + switch (selected) + { + case 0: + this.DoShowDiff(this.GetGUID()); + break; + case 1: + ASEditorBackend.DoAS(); + ASEditorBackend.ASWin.ShowHistory(); + break; + case 2: + if (!ASEditorBackend.SettingsIfNeeded()) + { + Debug.Log("Asset Server connection for current project is not set up"); + } + if (EditorUtility.DisplayDialog("Discard changes", "Are you sure you want to discard local changes of selected asset?", "Discard", "Cancel")) + { + AssetServer.DoUpdateWithoutConflictResolutionOnNextTick(new string[] + { + this.GetGUID() + }); + } + break; + } + } + private ChangeFlags GetChangeFlags() + { + string gUID = this.GetGUID(); + if (gUID == string.Empty) + { + return ChangeFlags.None; + } + return AssetServer.GetChangeFlags(gUID); + } + private string GetModificationString(ChangeFlags flags) + { + string text = string.Empty; + if (this.HasFlag(flags, ChangeFlags.Undeleted)) + { + text = this.AddChangesetFlag(text, "undeleted"); + } + if (this.HasFlag(flags, ChangeFlags.Modified)) + { + text = this.AddChangesetFlag(text, "modified"); + } + if (this.HasFlag(flags, ChangeFlags.Renamed)) + { + text = this.AddChangesetFlag(text, "renamed"); + } + if (this.HasFlag(flags, ChangeFlags.Moved)) + { + text = this.AddChangesetFlag(text, "moved"); + } + if (this.HasFlag(flags, ChangeFlags.Created)) + { + text = this.AddChangesetFlag(text, "created"); + } + return text; + } + public void OnAssetStatusGUI(Rect r, int id, UnityEngine.Object target, GUIStyle style) + { + if (target == null) + { + return; + } + ChangeFlags changeFlags = this.GetChangeFlags(); + string modificationString = this.GetModificationString(changeFlags); + GUIContent content; + if (modificationString == string.Empty) + { + content = EditorGUIUtility.TextContent("Asset is unchanged"); + } + else + { + content = new GUIContent("Locally " + modificationString); + } + if (EditorGUI.DoToggle(r, id, false, content, style)) + { + GUIUtility.hotControl = 0; + r = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(r, (!(modificationString == string.Empty)) ? this.m_Menu : this.m_UnmodifiedMenu, -1, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), modificationString == string.Empty); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetModificationProcessor.cs b/UnityEditor/UnityEditor/AssetModificationProcessor.cs new file mode 100644 index 00000000..bc3baebc --- /dev/null +++ b/UnityEditor/UnityEditor/AssetModificationProcessor.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + public class AssetModificationProcessor + { + } +} diff --git a/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs b/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs new file mode 100644 index 00000000..20b4afc4 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs @@ -0,0 +1,334 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetModificationProcessorInternal + { + private enum FileMode + { + Binary, + Text + } + private static IEnumerable assetModificationProcessors; + internal static MethodInfo[] isOpenForEditMethods; + private static IEnumerable AssetModificationProcessors + { + get + { + if (AssetModificationProcessorInternal.assetModificationProcessors == null) + { + List list = new List(); + list.AddRange(EditorAssemblies.SubclassesOf(typeof(AssetModificationProcessor))); + list.AddRange(EditorAssemblies.SubclassesOf(typeof(global::AssetModificationProcessor))); + AssetModificationProcessorInternal.assetModificationProcessors = list.ToArray(); + } + return AssetModificationProcessorInternal.assetModificationProcessors; + } + } + private static bool CheckArgumentTypes(Type[] types, MethodInfo method) + { + ParameterInfo[] parameters = method.GetParameters(); + if (types.Length != parameters.Length) + { + Debug.LogWarning(string.Concat(new string[] + { + "Parameter count did not match. Expected: ", + types.Length.ToString(), + " Got: ", + parameters.Length.ToString(), + " in ", + method.DeclaringType.ToString(), + ".", + method.Name + })); + return false; + } + int num = 0; + for (int i = 0; i < types.Length; i++) + { + Type type = types[i]; + ParameterInfo parameterInfo = parameters[num]; + if (type != parameterInfo.ParameterType) + { + Debug.LogWarning(string.Concat(new object[] + { + "Parameter type mismatch at parameter ", + num, + ". Expected: ", + type.ToString(), + " Got: ", + parameterInfo.ParameterType.ToString(), + " in ", + method.DeclaringType.ToString(), + ".", + method.Name + })); + return false; + } + num++; + } + return true; + } + private static bool CheckArgumentTypesAndReturnType(Type[] types, MethodInfo method, Type returnType) + { + if (returnType != method.ReturnType) + { + Debug.LogWarning(string.Concat(new string[] + { + "Return type mismatch. Expected: ", + returnType.ToString(), + " Got: ", + method.ReturnType.ToString(), + " in ", + method.DeclaringType.ToString(), + ".", + method.Name + })); + return false; + } + return AssetModificationProcessorInternal.CheckArgumentTypes(types, method); + } + private static bool CheckArguments(object[] args, MethodInfo method) + { + Type[] array = new Type[args.Length]; + for (int i = 0; i < args.Length; i++) + { + array[i] = args[i].GetType(); + } + return AssetModificationProcessorInternal.CheckArgumentTypes(array, method); + } + private static bool CheckArgumentsAndReturnType(object[] args, MethodInfo method, Type returnType) + { + Type[] array = new Type[args.Length]; + for (int i = 0; i < args.Length; i++) + { + array[i] = args[i].GetType(); + } + return AssetModificationProcessorInternal.CheckArgumentTypesAndReturnType(array, method, returnType); + } + private static void OnWillCreateAsset(string path) + { + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("OnWillCreateAsset", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + object[] array = new object[] + { + path + }; + if (AssetModificationProcessorInternal.CheckArguments(array, method)) + { + method.Invoke(null, array); + } + } + } + } + private static void FileModeChanged(string[] assets, UnityEditor.VersionControl.FileMode mode) + { + if (Provider.enabled && Provider.PromptAndCheckoutIfNeeded(assets, string.Empty)) + { + Provider.SetFileMode(assets, mode); + } + } + private static void OnWillSaveAssets(string[] assets, out string[] assetsThatShouldBeSaved, out string[] assetsThatShouldBeReverted, int explicitlySaveScene) + { + assetsThatShouldBeReverted = new string[0]; + assetsThatShouldBeSaved = assets; + bool flag = assets.Length > 0 && EditorPrefs.GetBool("VerifySavingAssets", false) && InternalEditorUtility.isHumanControllingUs; + if (explicitlySaveScene != 0 && assets.Length == 1 && assets[0].EndsWith(".unity")) + { + flag = false; + } + if (flag) + { + AssetSaveDialog.ShowWindow(assets, out assetsThatShouldBeSaved); + } + else + { + assetsThatShouldBeSaved = assets; + } + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("OnWillSaveAssets", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + object[] array = new object[] + { + assetsThatShouldBeSaved + }; + if (AssetModificationProcessorInternal.CheckArguments(array, method)) + { + string[] array2 = (string[])method.Invoke(null, array); + if (array2 != null) + { + assetsThatShouldBeSaved = array2; + } + } + } + } + if (assetsThatShouldBeSaved == null) + { + return; + } + List list = new List(); + string[] array3 = assetsThatShouldBeSaved; + for (int i = 0; i < array3.Length; i++) + { + string text = array3[i]; + if (!AssetDatabase.IsOpenForEdit(text)) + { + list.Add(text); + } + } + assets = list.ToArray(); + if (assets.Length != 0 && !Provider.PromptAndCheckoutIfNeeded(assets, string.Empty)) + { + Debug.LogError("Could not checkout the following files in version control before saving: " + string.Join(", ", assets)); + assetsThatShouldBeSaved = new string[0]; + return; + } + } + private static void RequireTeamLicense() + { + if (!InternalEditorUtility.HasMaint()) + { + throw new MethodAccessException("Requires team license"); + } + } + private static AssetMoveResult OnWillMoveAsset(string fromPath, string toPath, string[] newPaths, string[] NewMetaPaths) + { + AssetMoveResult assetMoveResult = AssetMoveResult.DidNotMove; + if (!InternalEditorUtility.HasMaint()) + { + return assetMoveResult; + } + assetMoveResult = AssetModificationHook.OnWillMoveAsset(fromPath, toPath); + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("OnWillMoveAsset", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + AssetModificationProcessorInternal.RequireTeamLicense(); + object[] array = new object[] + { + fromPath, + toPath + }; + if (AssetModificationProcessorInternal.CheckArgumentsAndReturnType(array, method, assetMoveResult.GetType())) + { + assetMoveResult |= (AssetMoveResult)((int)method.Invoke(null, array)); + } + } + } + return assetMoveResult; + } + private static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions options) + { + AssetDeleteResult assetDeleteResult = AssetDeleteResult.DidNotDelete; + if (!InternalEditorUtility.HasMaint()) + { + return assetDeleteResult; + } + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("OnWillDeleteAsset", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + AssetModificationProcessorInternal.RequireTeamLicense(); + object[] array = new object[] + { + assetPath, + options + }; + if (AssetModificationProcessorInternal.CheckArgumentsAndReturnType(array, method, assetDeleteResult.GetType())) + { + assetDeleteResult |= (AssetDeleteResult)((int)method.Invoke(null, array)); + } + } + } + if (assetDeleteResult != AssetDeleteResult.DidNotDelete) + { + return assetDeleteResult; + } + assetDeleteResult = AssetModificationHook.OnWillDeleteAsset(assetPath, options); + return assetDeleteResult; + } + internal static MethodInfo[] GetIsOpenForEditMethods() + { + if (AssetModificationProcessorInternal.isOpenForEditMethods == null) + { + List list = new List(); + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("IsOpenForEdit", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + AssetModificationProcessorInternal.RequireTeamLicense(); + string empty = string.Empty; + bool flag = false; + Type[] types = new Type[] + { + empty.GetType(), + empty.GetType().MakeByRefType() + }; + if (AssetModificationProcessorInternal.CheckArgumentTypesAndReturnType(types, method, flag.GetType())) + { + list.Add(method); + } + } + } + AssetModificationProcessorInternal.isOpenForEditMethods = list.ToArray(); + } + return AssetModificationProcessorInternal.isOpenForEditMethods; + } + internal static bool IsOpenForEdit(string assetPath, out string message) + { + message = string.Empty; + if (string.IsNullOrEmpty(assetPath)) + { + return true; + } + bool flag = true; + flag &= AssetModificationHook.IsOpenForEdit(assetPath, out message); + MethodInfo[] array = AssetModificationProcessorInternal.GetIsOpenForEditMethods(); + for (int i = 0; i < array.Length; i++) + { + MethodInfo methodInfo = array[i]; + object[] array2 = new object[] + { + assetPath, + message + }; + if (!(bool)methodInfo.Invoke(null, array2)) + { + message = (array2[1] as string); + return false; + } + } + return flag; + } + internal static void OnStatusUpdated() + { + WindowPending.OnStatusUpdated(); + foreach (Type current in AssetModificationProcessorInternal.AssetModificationProcessors) + { + MethodInfo method = current.GetMethod("OnStatusUpdated", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + AssetModificationProcessorInternal.RequireTeamLicense(); + object[] array = new object[0]; + if (AssetModificationProcessorInternal.CheckArgumentsAndReturnType(array, method, typeof(void))) + { + method.Invoke(null, array); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetMoveResult.cs b/UnityEditor/UnityEditor/AssetMoveResult.cs new file mode 100644 index 00000000..00462853 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetMoveResult.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum AssetMoveResult + { + DidNotMove = 0, + FailedMove = 1, + DidMove = 2 + } +} diff --git a/UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs b/UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs new file mode 100644 index 00000000..4fa74181 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AssetOrGameObjectTreeViewDragging : TreeViewDragging + { + private readonly HierarchyType m_HierarchyType; + public bool allowDragBetween + { + get; + set; + } + public AssetOrGameObjectTreeViewDragging(TreeView treeView, HierarchyType hierarchyType) : base(treeView) + { + this.allowDragBetween = false; + this.m_HierarchyType = hierarchyType; + } + public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) + { + DragAndDrop.PrepareStartDrag(); + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + draggedItemIDs = this.m_TreeView.SortIDsInVisiblityOrder(draggedItemIDs); + } + DragAndDrop.objectReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedItem.id, draggedItemIDs); + DragAndDrop.paths = ProjectWindowUtil.GetDragAndDropPaths(draggedItem.id, draggedItemIDs); + if (DragAndDrop.objectReferences.Length > 1) + { + DragAndDrop.StartDrag(""); + } + else + { + string dragAndDropTitle = ObjectNames.GetDragAndDropTitle(InternalEditorUtility.GetObjectFromInstanceID(draggedItem.id)); + DragAndDrop.StartDrag(dragAndDropTitle); + } + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + if (this.m_HierarchyType == HierarchyType.Assets) + { + if (parentItem == null || !hierarchyProperty.Find(parentItem.id, null)) + { + hierarchyProperty = null; + } + return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + } + if (this.allowDragBetween) + { + if (dropPos == TreeViewDragging.DropPosition.Above || targetItem == null || !hierarchyProperty.Find(targetItem.id, null)) + { + hierarchyProperty = null; + } + } + else + { + if (dropPos == TreeViewDragging.DropPosition.Above || parentItem == null || !hierarchyProperty.Find(parentItem.id, null)) + { + hierarchyProperty = null; + } + } + InternalEditorUtility.HierarchyDropMode hierarchyDropMode = InternalEditorUtility.HierarchyDropMode.kHierarchyDragNormal; + if (this.allowDragBetween) + { + hierarchyDropMode = ((dropPos != TreeViewDragging.DropPosition.Upon) ? InternalEditorUtility.HierarchyDropMode.kHierarchyDropBetween : InternalEditorUtility.HierarchyDropMode.kHierarchyDropUpon); + } + if (parentItem != null && parentItem == targetItem && dropPos != TreeViewDragging.DropPosition.Above) + { + hierarchyDropMode |= InternalEditorUtility.HierarchyDropMode.kHierarchyDropAfterParent; + } + return InternalEditorUtility.HierarchyWindowDrag(hierarchyProperty, perform, hierarchyDropMode); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs b/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs new file mode 100644 index 00000000..0e58a342 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs @@ -0,0 +1,282 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetPostprocessingInternal + { + internal class CompareAssetImportPriority : IComparer + { + int IComparer.Compare(object xo, object yo) + { + int postprocessOrder = ((AssetPostprocessor)xo).GetPostprocessOrder(); + int postprocessOrder2 = ((AssetPostprocessor)yo).GetPostprocessOrder(); + return postprocessOrder.CompareTo(postprocessOrder2); + } + } + internal class PostprocessStack + { + internal ArrayList m_ImportProcessors; + } + private static ArrayList m_PostprocessStack; + private static ArrayList m_ImportProcessors; + private static void LogPostProcessorMissingDefaultConstructor(Type type) + { + Debug.LogError(string.Format("{0} requires a default constructor to be used as an asset post processor", type.ToString())); + } + private static void PostprocessAllAssets(string[] importedAssets, string[] addedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPathAssets) + { + object[] parameters = new object[] + { + importedAssets, + deletedAssets, + movedAssets, + movedFromPathAssets + }; + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + MethodInfo method = current.GetMethod("OnPostprocessAllAssets", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + method.Invoke(null, parameters); + } + } + SyncVS.PostprocessSyncProject(importedAssets, addedAssets, deletedAssets, movedAssets, movedFromPathAssets); + } + internal static void CallOnGeneratedCSProjectFiles() + { + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + MethodInfo method = current.GetMethod("OnGeneratedCSProjectFiles", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + object[] parameters = new object[0]; + method.Invoke(null, parameters); + } + } + } + private static void InitPostprocessors(string pathName) + { + AssetPostprocessingInternal.m_ImportProcessors = new ArrayList(); + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + try + { + AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor; + assetPostprocessor.assetPath = pathName; + AssetPostprocessingInternal.m_ImportProcessors.Add(assetPostprocessor); + } + catch (MissingMethodException) + { + AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current); + } + catch (Exception exception) + { + Debug.LogException(exception); + } + } + AssetPostprocessingInternal.m_ImportProcessors.Sort(new AssetPostprocessingInternal.CompareAssetImportPriority()); + AssetPostprocessingInternal.PostprocessStack postprocessStack = new AssetPostprocessingInternal.PostprocessStack(); + postprocessStack.m_ImportProcessors = AssetPostprocessingInternal.m_ImportProcessors; + if (AssetPostprocessingInternal.m_PostprocessStack == null) + { + AssetPostprocessingInternal.m_PostprocessStack = new ArrayList(); + } + AssetPostprocessingInternal.m_PostprocessStack.Add(postprocessStack); + } + private static void CleanupPostprocessors() + { + if (AssetPostprocessingInternal.m_PostprocessStack != null) + { + AssetPostprocessingInternal.m_PostprocessStack.RemoveAt(AssetPostprocessingInternal.m_PostprocessStack.Count - 1); + if (AssetPostprocessingInternal.m_PostprocessStack.Count != 0) + { + AssetPostprocessingInternal.PostprocessStack postprocessStack = (AssetPostprocessingInternal.PostprocessStack)AssetPostprocessingInternal.m_PostprocessStack[AssetPostprocessingInternal.m_PostprocessStack.Count - 1]; + AssetPostprocessingInternal.m_ImportProcessors = postprocessStack.m_ImportProcessors; + } + } + } + private static uint[] GetMeshProcessorVersions() + { + List list = new List(); + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + try + { + AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor; + Type type = assetPostprocessor.GetType(); + bool flag = type.GetMethod("OnPreprocessModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + bool flag2 = type.GetMethod("OnProcessMeshAssingModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + bool flag3 = type.GetMethod("OnPostprocessModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + uint version = assetPostprocessor.GetVersion(); + if (version != 0u && (flag || flag2 || flag3)) + { + list.Add(version); + } + } + catch (MissingMethodException) + { + AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current); + } + catch (Exception exception) + { + Debug.LogException(exception); + } + } + return list.ToArray(); + } + private static void PreprocessMesh(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessModel", null); + } + } + private static Material ProcessMeshAssignMaterial(Renderer renderer, Material material) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + material, + renderer + }; + object obj = AttributeHelper.InvokeMemberIfAvailable(target, "OnAssignMaterialModel", args); + if (obj as Material) + { + return obj as Material; + } + } + return null; + } + private static bool ProcessMeshHasAssignMaterial() + { + foreach (AssetPostprocessor assetPostprocessor in AssetPostprocessingInternal.m_ImportProcessors) + { + if (assetPostprocessor.GetType().GetMethod("OnAssignMaterialModel", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null) + { + return true; + } + } + return false; + } + private static void PostprocessMesh(GameObject gameObject) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + gameObject + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessModel", args); + } + } + private static void PostprocessGameObjectWithUserProperties(GameObject go, string[] prop_names, object[] prop_values) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + go, + prop_names, + prop_values + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessGameObjectWithUserProperties", args); + } + } + private static uint[] GetTextureProcessorVersions() + { + List list = new List(); + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + try + { + AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor; + Type type = assetPostprocessor.GetType(); + bool flag = type.GetMethod("OnPreprocessTexture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + bool flag2 = type.GetMethod("OnPostprocessTexture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + uint version = assetPostprocessor.GetVersion(); + if (version != 0u && (flag || flag2)) + { + list.Add(version); + } + } + catch (MissingMethodException) + { + AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current); + } + catch (Exception exception) + { + Debug.LogException(exception); + } + } + return list.ToArray(); + } + private static void PreprocessTexture(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessTexture", null); + } + } + private static void PostprocessTexture(Texture2D tex, string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + tex + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessTexture", args); + } + } + private static uint[] GetAudioProcessorVersions() + { + List list = new List(); + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + try + { + AssetPostprocessor assetPostprocessor = Activator.CreateInstance(current) as AssetPostprocessor; + Type type = assetPostprocessor.GetType(); + bool flag = type.GetMethod("OnPreprocessAudio", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + bool flag2 = type.GetMethod("OnPostprocessAudio", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null; + uint version = assetPostprocessor.GetVersion(); + if (version != 0u && (flag || flag2)) + { + list.Add(version); + } + } + catch (MissingMethodException) + { + AssetPostprocessingInternal.LogPostProcessorMissingDefaultConstructor(current); + } + catch (Exception exception) + { + Debug.LogException(exception); + } + } + return list.ToArray(); + } + private static void PreprocessAudio(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessAudio", null); + } + } + private static void PostprocessAudio(AudioClip tex, string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + tex + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAudio", args); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetPostprocessor.cs b/UnityEditor/UnityEditor/AssetPostprocessor.cs new file mode 100644 index 00000000..b9b2eed5 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetPostprocessor.cs @@ -0,0 +1,67 @@ +using System; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public class AssetPostprocessor + { + private string m_PathName; + public string assetPath + { + get + { + return this.m_PathName; + } + set + { + this.m_PathName = value; + } + } + public AssetImporter assetImporter + { + get + { + return AssetImporter.GetAtPath(this.assetPath); + } + } + [Obsolete("To set or get the preview, call EditorUtility.SetAssetPreview or AssetPreview.GetAssetPreview instead", true)] + public Texture2D preview + { + get + { + return null; + } + set + { + } + } + [ExcludeFromDocs] + public void LogWarning(string warning) + { + UnityEngine.Object context = null; + this.LogWarning(warning, context); + } + public void LogWarning(string warning, [DefaultValue("null")] UnityEngine.Object context) + { + Debug.LogWarning(warning, context); + } + [ExcludeFromDocs] + public void LogError(string warning) + { + UnityEngine.Object context = null; + this.LogError(warning, context); + } + public void LogError(string warning, [DefaultValue("null")] UnityEngine.Object context) + { + Debug.LogError(warning, context); + } + public virtual uint GetVersion() + { + return 0u; + } + public virtual int GetPostprocessOrder() + { + return 0; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetPreview.cs b/UnityEditor/UnityEditor/AssetPreview.cs new file mode 100644 index 00000000..cfdbcf01 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetPreview.cs @@ -0,0 +1,79 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class AssetPreview + { + private const int kSharedClientID = 0; + public static Texture2D GetAssetPreview(UnityEngine.Object asset) + { + if (asset != null) + { + return AssetPreview.GetAssetPreview(asset.GetInstanceID()); + } + return null; + } + internal static Texture2D GetAssetPreview(int instanceID) + { + return AssetPreview.GetAssetPreview(instanceID, 0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D GetAssetPreview(int instanceID, int clientID); + public static bool IsLoadingAssetPreview(int instanceID) + { + return AssetPreview.IsLoadingAssetPreview(instanceID, 0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsLoadingAssetPreview(int instanceID, int clientID); + public static bool IsLoadingAssetPreviews() + { + return AssetPreview.IsLoadingAssetPreviews(0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsLoadingAssetPreviews(int clientID); + internal static bool HasAnyNewPreviewTexturesAvailable() + { + return AssetPreview.HasAnyNewPreviewTexturesAvailable(0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasAnyNewPreviewTexturesAvailable(int clientID); + internal static void SetPreviewTextureCacheSize(int size) + { + AssetPreview.SetPreviewTextureCacheSize(size, 0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPreviewTextureCacheSize(int size, int clientID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ClearTemporaryAssetPreviews(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DeletePreviewTextureManagerByID(int clientID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetMiniThumbnail(UnityEngine.Object obj); + public static Texture2D GetMiniTypeThumbnail(Type type) + { + return AssetPreview.INTERNAL_GetMiniTypeThumbnailFromType(type); + } + internal static Texture2D GetMiniTypeThumbnail(UnityEngine.Object obj) + { + return AssetPreview.INTERNAL_GetMiniTypeThumbnailFromObject(obj); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D GetMiniTypeThumbnailFromClassID(int classID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D INTERNAL_GetMiniTypeThumbnailFromObject(UnityEngine.Object monoObj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D INTERNAL_GetMiniTypeThumbnailFromType(Type type); + } +} diff --git a/UnityEditor/UnityEditor/AssetPreviewUpdater.cs b/UnityEditor/UnityEditor/AssetPreviewUpdater.cs new file mode 100644 index 00000000..e55213ad --- /dev/null +++ b/UnityEditor/UnityEditor/AssetPreviewUpdater.cs @@ -0,0 +1,39 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetPreviewUpdater + { + public static Texture2D CreatePreviewForAsset(UnityEngine.Object obj, UnityEngine.Object[] subAssets, string assetPath) + { + if (obj == null) + { + return null; + } + Type type = CustomEditorAttributes.FindCustomEditorType(obj, false); + if (type == null) + { + return null; + } + MethodInfo method = type.GetMethod("RenderStaticPreview"); + if (method == null) + { + Debug.LogError("Fail to find RenderStaticPreview base method"); + return null; + } + if (method.DeclaringType == typeof(Editor)) + { + return null; + } + Editor editor = Editor.CreateEditor(obj); + if (editor == null) + { + return null; + } + Texture2D result = editor.RenderStaticPreview(assetPath, subAssets, 128, 128); + UnityEngine.Object.DestroyImmediate(editor); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetSaveDialog.cs b/UnityEditor/UnityEditor/AssetSaveDialog.cs new file mode 100644 index 00000000..3e1031bd --- /dev/null +++ b/UnityEditor/UnityEditor/AssetSaveDialog.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetSaveDialog : EditorWindow + { + private class Styles + { + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle box = "OL Box"; + public GUIStyle button = "LargeButton"; + public GUIContent saveSelected = EditorGUIUtility.TextContent("SaveAssetDialog.SaveSelected"); + public GUIContent saveAll = EditorGUIUtility.TextContent("SaveAssetDialog.SaveAll"); + public GUIContent dontSave = EditorGUIUtility.TextContent("SaveAssetDialog.DontSave"); + public GUIContent close = EditorGUIUtility.TextContent("SaveAssetDialog.Close"); + public float buttonWidth; + public Styles() + { + this.buttonWidth = Mathf.Max(Mathf.Max(this.button.CalcSize(this.saveSelected).x, this.button.CalcSize(this.saveAll).x), this.button.CalcSize(this.dontSave).x); + } + } + private static AssetSaveDialog.Styles s_Styles; + private List m_Assets; + private List m_AssetsToSave; + private ListViewState m_LV = new ListViewState(); + private int m_InitialSelectedItem = -1; + private bool[] m_SelectedItems; + private List m_Content; + private void SetAssets(string[] assets) + { + this.m_Assets = new List(assets); + this.RebuildLists(true); + this.m_AssetsToSave = new List(); + } + public static void ShowWindow(string[] inAssets, out string[] assetsThatShouldBeSaved) + { + int num = 0; + for (int i = 0; i < inAssets.Length; i++) + { + string text = inAssets[i]; + if (text.EndsWith("meta")) + { + num++; + } + } + int num2 = inAssets.Length - num; + if (num2 == 0) + { + assetsThatShouldBeSaved = inAssets; + return; + } + string[] array = new string[num2]; + string[] array2 = new string[num]; + num2 = 0; + num = 0; + for (int j = 0; j < inAssets.Length; j++) + { + string text2 = inAssets[j]; + if (text2.EndsWith("meta")) + { + array2[num++] = text2; + } + else + { + array[num2++] = text2; + } + } + AssetSaveDialog windowDontShow = EditorWindow.GetWindowDontShow(); + windowDontShow.title = EditorGUIUtility.TextContent("SaveAssetDialog.Title").text; + windowDontShow.SetAssets(array); + windowDontShow.ShowUtility(); + windowDontShow.ShowModal(); + assetsThatShouldBeSaved = new string[windowDontShow.m_AssetsToSave.Count + num]; + windowDontShow.m_AssetsToSave.CopyTo(assetsThatShouldBeSaved, 0); + array2.CopyTo(assetsThatShouldBeSaved, windowDontShow.m_AssetsToSave.Count); + } + public static GUIContent GetContentForAsset(string path) + { + Texture cachedIcon = AssetDatabase.GetCachedIcon(path); + if (path.StartsWith("Library/")) + { + path = ObjectNames.NicifyVariableName(AssetDatabase.LoadMainAssetAtPath(path).name); + } + if (path.StartsWith("Assets/")) + { + path = path.Substring(7); + } + return new GUIContent(path, cachedIcon); + } + private void HandleKeyboard() + { + } + private void OnGUI() + { + if (AssetSaveDialog.s_Styles == null) + { + AssetSaveDialog.s_Styles = new AssetSaveDialog.Styles(); + base.minSize = new Vector2(500f, 300f); + base.position = new Rect(base.position.x, base.position.y, base.minSize.x, base.minSize.y); + } + this.HandleKeyboard(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.Label("Unity is about to save the following modified files. Unsaved changes will be lost!", new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + int row = this.m_LV.row; + int num = 0; + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.m_LV, AssetSaveDialog.s_Styles.box, new GUILayoutOption[0])) + { + if (this.m_SelectedItems[listViewElement.row] && Event.current.type == EventType.Repaint) + { + Rect position = listViewElement.position; + position.x += 1f; + position.y += 1f; + position.width -= 1f; + position.height -= 1f; + AssetSaveDialog.s_Styles.selected.Draw(position, false, false, false, false); + } + GUILayout.Label(this.m_Content[listViewElement.row], new GUILayoutOption[0]); + if (ListViewGUILayout.HasMouseUp(listViewElement.position)) + { + Event.current.command = true; + Event.current.control = true; + ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.m_InitialSelectedItem, ref this.m_SelectedItems); + } + if (this.m_SelectedItems[listViewElement.row]) + { + num++; + } + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + if (GUILayout.Button(AssetSaveDialog.s_Styles.close, AssetSaveDialog.s_Styles.button, new GUILayoutOption[] + { + GUILayout.Width(AssetSaveDialog.s_Styles.buttonWidth) + })) + { + this.CloseWindow(); + } + GUILayout.FlexibleSpace(); + GUI.enabled = (num > 0); + bool flag = num == this.m_Assets.Count; + if (GUILayout.Button(AssetSaveDialog.s_Styles.dontSave, AssetSaveDialog.s_Styles.button, new GUILayoutOption[] + { + GUILayout.Width(AssetSaveDialog.s_Styles.buttonWidth) + })) + { + this.IgnoreSelectedAssets(); + } + if (GUILayout.Button((!flag) ? AssetSaveDialog.s_Styles.saveSelected : AssetSaveDialog.s_Styles.saveAll, AssetSaveDialog.s_Styles.button, new GUILayoutOption[] + { + GUILayout.Width(AssetSaveDialog.s_Styles.buttonWidth) + })) + { + this.SaveSelectedAssets(); + } + if (this.m_Assets.Count == 0) + { + this.CloseWindow(); + } + GUI.enabled = true; + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + } + private void Cancel() + { + base.Close(); + GUIUtility.ExitGUI(); + } + private void CloseWindow() + { + base.Close(); + GUIUtility.ExitGUI(); + } + private void SaveSelectedAssets() + { + List list = new List(); + for (int i = 0; i < this.m_SelectedItems.Length; i++) + { + if (this.m_SelectedItems[i]) + { + this.m_AssetsToSave.Add(this.m_Assets[i]); + } + else + { + list.Add(this.m_Assets[i]); + } + } + this.m_Assets = list; + this.RebuildLists(false); + } + private void IgnoreSelectedAssets() + { + List list = new List(); + for (int i = 0; i < this.m_SelectedItems.Length; i++) + { + if (!this.m_SelectedItems[i]) + { + list.Add(this.m_Assets[i]); + } + } + this.m_Assets = list; + this.RebuildLists(false); + if (this.m_Assets.Count == 0) + { + this.CloseWindow(); + } + } + private void RebuildLists(bool selected) + { + this.m_LV.totalRows = this.m_Assets.Count; + this.m_SelectedItems = new bool[this.m_Assets.Count]; + this.m_Content = new List(this.m_Assets.Count); + for (int i = 0; i < this.m_Assets.Count; i++) + { + this.m_SelectedItems[i] = selected; + this.m_Content.Add(AssetSaveDialog.GetContentForAsset(this.m_Assets[i])); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetServer.cs b/UnityEditor/UnityEditor/AssetServer.cs new file mode 100644 index 00000000..b0007e42 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetServer.cs @@ -0,0 +1,362 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + internal sealed class AssetServer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AssetStatus GetStatus(UnityEngine.Object asset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AssetStatus GetStatusGUID(string guidString); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern ChangeFlags GetChangeFlags(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DoUpdateWithoutConflictResolutionOnNextTick(string[] guids); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ShowDialogOnNextTick(string title, string text, string button1, string button2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string[] UpdateGetConflicts(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool UpdateSetResolutions(string[] guids, DownloadResolution[] resolutions); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool UpdateStartDownload(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool UpdateComplete(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool UpdateAbort(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CommitBegin(string changeDescription, string[] candidates); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CommitStartUpload(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float UpdateGetDownloadProgress(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float CommitGetUploadProgress(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetProgressText(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CommitComplete(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CommitAbort(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAssetServerError(string error, bool isConnectionError); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAssetServerError(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearAssetServerError(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasConnectionError(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool RevertVersion(string assetGUID, int version); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool RecoverDeleted(string assetGUID, int version, string name, string parentGUID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CompareFiles(string[] guids, CompareInfo[] selection); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAllRootGUIDs(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetRootGUID(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] CollectAllChildren(string guid, string[] collection); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAssetPathName(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemoveMaintErrorsFromConsole(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern DownloadResolution GetDownloadResolution(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetPathNameConflict(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasDeletionConflict(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern NameConflictResolution GetNameConflictResolution(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDownloadResolution(string guid, DownloadResolution res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDownloadResolutionInt(string guid, int res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNameConflictResolution(string guid, NameConflictResolution res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string UnityGUID(int a, int b, int c, int d); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies, [DefaultValue("true")] bool includeUnmodified, [DefaultValue("false")] bool includeNameConflicts); + [ExcludeFromDocs] + public static string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies, bool includeUnmodified) + { + bool includeNameConflicts = false; + return AssetServer.BuildExportPackageAssetListGUIDs(guids, dependencies, includeUnmodified, includeNameConflicts); + } + [ExcludeFromDocs] + public static string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies) + { + bool includeNameConflicts = false; + bool includeUnmodified = true; + return AssetServer.BuildExportPackageAssetListGUIDs(guids, dependencies, includeUnmodified, includeNameConflicts); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies, [DefaultValue("true")] bool includeUnmodified, [DefaultValue("false")] bool includeNameConflicts); + [ExcludeFromDocs] + public static AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies, bool includeUnmodified) + { + bool includeNameConflicts = false; + return AssetServer.BuildExportPackageAssetListAssetsItems(guids, dependencies, includeUnmodified, includeNameConflicts); + } + [ExcludeFromDocs] + public static AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies) + { + bool includeNameConflicts = false; + bool includeUnmodified = true; + return AssetServer.BuildExportPackageAssetListAssetsItems(guids, dependencies, includeUnmodified, includeNameConflicts); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetsItem[] BuildAllExportPackageAssetListAssetsItems(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExportPackage(string[] guids, string fileName); + private static AssetsItem[] ImportPackageStep1(string packagePath) + { + string text; + return AssetServer.ImportPackageStep1(packagePath, out text); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetsItem[] ImportPackageStep1(string packagePath, out string packageIconPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ImportPackageStep2(AssetsItem[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetsItem[] GetLocalDeletedItems(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsItemDeleted(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetDeletedItemPathAndName(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Changeset[] GetHistorySelected(string[] guids); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Changeset[] GetHistory([DefaultValue("-1")] int downToRevision); + [ExcludeFromDocs] + public static Changeset[] GetHistory() + { + int downToRevision = -1; + return AssetServer.GetHistory(downToRevision); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Changeset[] GetNewItems(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetProjectName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Initialize(string userName, string connectionString, int timeout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] CollectSelection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] CollectDeepSelection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AssetIsDir(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoUpdateOnNextTick(bool forceShowConflictResolutions, string backendFunctionForConflictResolutions); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoCommitOnNextTick(string description, string[] guids); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoUpdateStatusOnNextTick(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoRefreshAssetsOnNextTick(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoRefreshAssetsAndUpdateStatusOnNextTick(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetDatabaseName(string server, string user, string password, string port, string projectName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetParentGUID(string itemGUID, int changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern DeletedAsset[] GetServerDeletedItems(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoRecoverOnNextTick(DeletedAsset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DoRevertOnNextTick(int changeset, string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStickyChangeset(int changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AdminSetCredentials(string server, int port, string user, string password); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MaintDatabaseRecord[] AdminRefreshDatabases(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MaintUserRecord[] AdminGetUsers(string databaseName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AdminChangePassword(string userName, string newPassword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AdminCreateDB(string newProjectName, [DefaultValue("\"\"")] string copyFromProjectName); + [ExcludeFromDocs] + public static int AdminCreateDB(string newProjectName) + { + string empty = string.Empty; + return AssetServer.AdminCreateDB(newProjectName, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AdminDeleteDB(string projectName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AdminCreateUser(string userName, string userFullName, string userEmail, string userPassword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AdminDeleteUser(string userName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AdminSetUserEnabled(string databaseName, string userName, string fullName, string email, int enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AdminModifyUserInfo(string databaseName, string userName, string fullName, string email); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int IsGUIDValid(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetServerItemChangeset(string guid, int changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetWorkingItemChangeset(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AssetIsBinaryByGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int IsAssetBinary(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] CollectAllDependencies(string[] selection); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetLastCommitMessage(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLastCommitMessage(string message); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetCommitSelectionGUIDs(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetCommitSelectionGUIDs(string[] guids); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearCommitPersistentData(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int IsControllerBusy(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetLastControllerActionResult(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAfterActionFinishedCallback(string className, string functionName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSelectionFromGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int IsAssetAvailable(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSelectionFromGUIDs(string[] guids); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetRefreshUpdate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetRefreshCommit(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearRefreshUpdate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearRefreshCommit(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CheckForServerUpdates(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetCachesInitialized(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int IsConstantGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SaveString(string strName, string strValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAndRemoveString(string strName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetString(string strName); + } +} diff --git a/UnityEditor/UnityEditor/AssetServerConfig.cs b/UnityEditor/UnityEditor/AssetServerConfig.cs new file mode 100644 index 00000000..5add0613 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetServerConfig.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetServerConfig + { + private Dictionary fileContents; + private string fileName; + private static Regex sKeyTag = new Regex("([^<]+)"); + private static Regex sValueTag = new Regex("([^<]+)"); + public string connectionSettings + { + get + { + return this.fileContents["Maint Connection Settings"]; + } + set + { + this.fileContents["Maint Connection Settings"] = value; + } + } + public string server + { + get + { + return this.fileContents["Maint Server"]; + } + set + { + this.fileContents["Maint Server"] = value; + } + } + public int portNumber + { + get + { + return int.Parse(this.fileContents["Maint port number"]); + } + set + { + this.fileContents["Maint port number"] = value.ToString(); + } + } + public float timeout + { + get + { + return float.Parse(this.fileContents["Maint Timeout"]); + } + set + { + this.fileContents["Maint Timeout"] = value.ToString(); + } + } + public string userName + { + get + { + return this.fileContents["Maint UserName"]; + } + set + { + this.fileContents["Maint UserName"] = value; + } + } + public string dbName + { + get + { + return this.fileContents["Maint database name"]; + } + set + { + this.fileContents["Maint database name"] = value; + } + } + public string projectName + { + get + { + return this.fileContents["Maint project name"]; + } + set + { + this.fileContents["Maint project name"] = value; + } + } + public string settingsType + { + get + { + return this.fileContents["Maint settings type"]; + } + set + { + this.fileContents["Maint settings type"] = value; + } + } + public AssetServerConfig() + { + this.fileContents = new Dictionary(); + this.fileName = Application.dataPath + "/../Library/ServerPreferences.plist"; + try + { + using (StreamReader streamReader = new StreamReader(this.fileName)) + { + string key = ".unkown"; + string input; + while ((input = streamReader.ReadLine()) != null) + { + Match match = AssetServerConfig.sKeyTag.Match(input); + if (match.Success) + { + key = match.Groups[1].Value; + } + match = AssetServerConfig.sValueTag.Match(input); + if (match.Success) + { + this.fileContents[key] = match.Groups[1].Value; + } + } + } + } + catch (Exception ex) + { + Debug.Log("Could not read asset server configuration: " + ex.Message); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStatus.cs b/UnityEditor/UnityEditor/AssetStatus.cs new file mode 100644 index 00000000..39d705c6 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStatus.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + public enum AssetStatus + { + Calculating = -1, + ClientOnly, + ServerOnly, + Unchanged, + Conflict, + Same, + NewVersionAvailable, + NewLocalVersion, + RestoredFromTrash, + Ignored, + BadState + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreAsset.cs b/UnityEditor/UnityEditor/AssetStoreAsset.cs new file mode 100644 index 00000000..6f3c7905 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreAsset.cs @@ -0,0 +1,113 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public sealed class AssetStoreAsset + { + internal class PreviewInfo + { + public string packageName; + public string packageShortUrl; + public int packageSize; + public string packageVersion; + public int packageRating; + public int packageAssetCount; + public bool isPurchased; + public bool isDownloadable; + public string publisherName; + public string encryptionKey; + public string packageUrl; + public float buildProgress; + public float downloadProgress; + public string categoryName; + } + public int id; + public string name; + public string displayName; + public string staticPreviewURL; + public string dynamicPreviewURL; + public string className; + public string price; + public int packageID; + internal AssetStoreAsset.PreviewInfo previewInfo; + public Texture2D previewImage; + internal AssetBundleCreateRequest previewBundleRequest; + internal AssetBundle previewBundle; + internal UnityEngine.Object previewAsset; + internal bool disposed; + public UnityEngine.Object Preview + { + get + { + if (this.previewAsset != null) + { + return this.previewAsset; + } + return this.previewImage; + } + } + public bool HasLivePreview + { + get + { + return this.previewAsset != null; + } + } + internal string DebugString + { + get + { + string text = string.Format("id: {0}\nname: {1}\nstaticPreviewURL: {2}\ndynamicPreviewURL: {3}\nclassName: {4}\nprice: {5}\npackageID: {6}", new object[] + { + this.id, + this.name ?? "N/A", + this.staticPreviewURL ?? "N/A", + this.dynamicPreviewURL ?? "N/A", + this.className ?? "N/A", + this.price, + this.packageID + }); + if (this.previewInfo != null) + { + text += string.Format("previewInfo {{\n packageName: {0}\n packageShortUrl: {1}\n packageSize: {2}\n packageVersion: {3}\n packageRating: {4}\n packageAssetCount: {5}\n isPurchased: {6}\n isDownloadable: {7}\n publisherName: {8}\n encryptionKey: {9}\n packageUrl: {10}\n buildProgress: {11}\n downloadProgress: {12}\n categoryName: {13}\n}}", new object[] + { + this.previewInfo.packageName ?? "N/A", + this.previewInfo.packageShortUrl ?? "N/A", + this.previewInfo.packageSize, + this.previewInfo.packageVersion ?? "N/A", + this.previewInfo.packageRating, + this.previewInfo.packageAssetCount, + this.previewInfo.isPurchased, + this.previewInfo.isDownloadable, + this.previewInfo.publisherName ?? "N/A", + this.previewInfo.encryptionKey ?? "N/A", + this.previewInfo.packageUrl ?? "N/A", + this.previewInfo.buildProgress, + this.previewInfo.downloadProgress, + this.previewInfo.categoryName ?? "N/A" + }); + } + return text; + } + } + public AssetStoreAsset() + { + this.disposed = false; + } + public void Dispose() + { + if (this.previewImage != null) + { + UnityEngine.Object.DestroyImmediate(this.previewImage); + this.previewImage = null; + } + if (this.previewBundle != null) + { + this.previewBundle.Unload(true); + this.previewBundle = null; + this.previewAsset = null; + } + this.disposed = true; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreAssetInspector.cs b/UnityEditor/UnityEditor/AssetStoreAssetInspector.cs new file mode 100644 index 00000000..d0fc2054 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreAssetInspector.cs @@ -0,0 +1,553 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AssetStoreAssetInspector))] + internal class AssetStoreAssetInspector : Editor + { + private class Styles + { + public GUIStyle link = new GUIStyle(EditorStyles.label); + public GUIContent assetStoreLogo = EditorGUIUtility.IconContent("WelcomeScreen.AssetStoreLogo"); + public Styles() + { + this.link.normal.textColor = new Color(0.26f, 0.51f, 0.75f, 1f); + } + } + internal enum PaymentAvailability + { + BasketNotEmpty, + ServiceDisabled, + AnonymousUser, + Ok + } + private static AssetStoreAssetInspector s_SharedAssetStoreAssetInspector; + private static AssetStoreAssetInspector.Styles styles; + private Vector2 pos; + private bool packageInfoShown = true; + internal static string s_PurchaseMessage = string.Empty; + internal static string s_PaymentMethodCard = string.Empty; + internal static string s_PaymentMethodExpire = string.Empty; + internal static string s_PriceText = string.Empty; + private static GUIContent[] sStatusWheel; + internal static AssetStoreAssetInspector.PaymentAvailability m_PaymentAvailability; + private int lastAssetID; + private EditorWrapper m_PreviewEditor; + private UnityEngine.Object m_PreviewObject; + public static AssetStoreAssetInspector Instance + { + get + { + if (AssetStoreAssetInspector.s_SharedAssetStoreAssetInspector == null) + { + AssetStoreAssetInspector.s_SharedAssetStoreAssetInspector = ScriptableObject.CreateInstance(); + AssetStoreAssetInspector.s_SharedAssetStoreAssetInspector.hideFlags = HideFlags.HideAndDontSave; + } + return AssetStoreAssetInspector.s_SharedAssetStoreAssetInspector; + } + } + public static bool OfflineNoticeEnabled + { + get; + set; + } + internal static AssetStoreAssetInspector.PaymentAvailability paymentAvailability + { + get + { + if (AssetStoreClient.LoggedOut()) + { + AssetStoreAssetInspector.m_PaymentAvailability = AssetStoreAssetInspector.PaymentAvailability.AnonymousUser; + } + return AssetStoreAssetInspector.m_PaymentAvailability; + } + set + { + if (AssetStoreClient.LoggedOut()) + { + AssetStoreAssetInspector.m_PaymentAvailability = AssetStoreAssetInspector.PaymentAvailability.AnonymousUser; + } + else + { + AssetStoreAssetInspector.m_PaymentAvailability = value; + } + } + } + private EditorWrapper previewEditor + { + get + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + return null; + } + UnityEngine.Object preview = firstAsset.Preview; + if (preview == null) + { + return null; + } + if (preview != this.m_PreviewObject) + { + this.m_PreviewObject = preview; + if (this.m_PreviewEditor != null) + { + this.m_PreviewEditor.Dispose(); + } + this.m_PreviewEditor = EditorWrapper.Make(this.m_PreviewObject, EditorFeatures.PreviewGUI); + } + return this.m_PreviewEditor; + } + } + private static GUIContent StatusWheel + { + get + { + if (AssetStoreAssetInspector.sStatusWheel == null) + { + AssetStoreAssetInspector.sStatusWheel = new GUIContent[12]; + for (int i = 0; i < 12; i++) + { + GUIContent gUIContent = new GUIContent(); + gUIContent.image = EditorGUIUtility.LoadIcon("WaitSpin" + i.ToString("00")); + AssetStoreAssetInspector.sStatusWheel[i] = gUIContent; + } + } + int num = (int)Mathf.Repeat(Time.realtimeSinceStartup * 10f, 11.99f); + return AssetStoreAssetInspector.sStatusWheel[num]; + } + } + public void OnDownloadProgress(string id, string message, int bytes, int total) + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + return; + } + AssetStoreAsset.PreviewInfo previewInfo = firstAsset.previewInfo; + if (previewInfo == null) + { + return; + } + if (firstAsset.packageID.ToString() != id) + { + return; + } + if ((message == "downloading" || message == "connecting") && !AssetStoreAssetInspector.OfflineNoticeEnabled) + { + previewInfo.downloadProgress = (float)bytes / (float)total; + } + else + { + previewInfo.downloadProgress = -1f; + } + base.Repaint(); + } + public void Update() + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + bool flag = firstAsset != null && firstAsset.previewInfo != null && (firstAsset.previewInfo.buildProgress >= 0f || firstAsset.previewInfo.downloadProgress >= 0f); + if ((firstAsset == null && this.lastAssetID != 0) || (firstAsset != null && this.lastAssetID != firstAsset.id) || flag) + { + this.lastAssetID = ((firstAsset != null) ? firstAsset.id : 0); + base.Repaint(); + } + if (firstAsset != null && firstAsset.previewBundle != null) + { + firstAsset.previewBundle.Unload(false); + firstAsset.previewBundle = null; + base.Repaint(); + } + } + public override void OnInspectorGUI() + { + if (AssetStoreAssetInspector.styles == null) + { + AssetStoreAssetInspector.s_SharedAssetStoreAssetInspector = this; + AssetStoreAssetInspector.styles = new AssetStoreAssetInspector.Styles(); + } + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + AssetStoreAsset.PreviewInfo previewInfo = null; + if (firstAsset != null) + { + previewInfo = firstAsset.previewInfo; + } + if (firstAsset != null) + { + this.target.name = string.Format("Asset Store: {0}", firstAsset.name); + } + else + { + this.target.name = "Asset Store"; + } + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + bool enabled = GUI.enabled; + GUI.enabled = (firstAsset != null && firstAsset.packageID != 0); + if (AssetStoreAssetInspector.OfflineNoticeEnabled) + { + Color color = GUI.color; + GUI.color = Color.yellow; + GUILayout.Label("Network is offline", new GUILayoutOption[0]); + GUI.color = color; + } + if (firstAsset != null) + { + string label = (firstAsset.className != null) ? firstAsset.className.Split(new char[] + { + ' ' + }, 2)[0] : string.Empty; + bool flag = firstAsset.id == -firstAsset.packageID; + if (flag) + { + label = "Package"; + } + if (firstAsset.HasLivePreview) + { + label = firstAsset.Preview.GetType().Name; + } + EditorGUILayout.LabelField("Type", label, new GUILayoutOption[0]); + if (flag) + { + this.packageInfoShown = true; + } + else + { + EditorGUILayout.Separator(); + this.packageInfoShown = EditorGUILayout.Foldout(this.packageInfoShown, "Part of package"); + } + if (this.packageInfoShown) + { + EditorGUILayout.LabelField("Name", (previewInfo != null) ? previewInfo.packageName : "-", new GUILayoutOption[0]); + EditorGUILayout.LabelField("Version", (previewInfo != null) ? previewInfo.packageVersion : "-", new GUILayoutOption[0]); + string label2 = (previewInfo != null) ? ((firstAsset.price == null || !(firstAsset.price != string.Empty)) ? "free" : firstAsset.price) : "-"; + EditorGUILayout.LabelField("Price", label2, new GUILayoutOption[0]); + string label3 = (previewInfo == null || previewInfo.packageRating < 0) ? "-" : (previewInfo.packageRating.ToString() + " of 5"); + EditorGUILayout.LabelField("Rating", label3, new GUILayoutOption[0]); + EditorGUILayout.LabelField("Size", (previewInfo != null) ? AssetStoreAssetInspector.intToSizeString(previewInfo.packageSize) : "-", new GUILayoutOption[0]); + string label4 = (previewInfo == null || previewInfo.packageAssetCount < 0) ? "-" : previewInfo.packageAssetCount.ToString(); + EditorGUILayout.LabelField("Asset count", label4, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Web page"); + bool flag2 = previewInfo != null && previewInfo.packageShortUrl != null && previewInfo.packageShortUrl != string.Empty; + bool enabled2 = GUI.enabled; + GUI.enabled = flag2; + if (GUILayout.Button((!flag2) ? EditorGUIUtility.TempContent("-") : new GUIContent(previewInfo.packageShortUrl, "View in browser"), AssetStoreAssetInspector.styles.link, new GUILayoutOption[0])) + { + Application.OpenURL(previewInfo.packageShortUrl); + } + if (GUI.enabled) + { + EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); + } + GUI.enabled = enabled2; + GUILayout.EndHorizontal(); + EditorGUILayout.LabelField("Publisher", (previewInfo != null) ? previewInfo.publisherName : "-", new GUILayoutOption[0]); + } + if (firstAsset.id != 0) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + string text; + if (previewInfo != null && previewInfo.isDownloadable) + { + text = "Import package"; + } + else + { + text = "Buy for " + firstAsset.price; + } + bool enabled3 = GUI.enabled; + bool flag3 = previewInfo != null && previewInfo.buildProgress >= 0f; + bool flag4 = previewInfo != null && previewInfo.downloadProgress >= 0f; + if (flag3 || flag4 || previewInfo == null) + { + text = string.Empty; + GUI.enabled = false; + } + if (GUILayout.Button(text, new GUILayoutOption[] + { + GUILayout.Height(40f), + GUILayout.Width(120f) + })) + { + if (previewInfo.isDownloadable) + { + this.ImportPackage(firstAsset); + } + else + { + this.InitiateBuySelected(); + } + GUIUtility.ExitGUI(); + } + if (Event.current.type == EventType.Repaint) + { + Rect lastRect = GUILayoutUtility.GetLastRect(); + lastRect.height -= 4f; + float width = lastRect.width; + lastRect.width = lastRect.height; + lastRect.y += 2f; + lastRect.x += 2f; + if (flag3 || flag4) + { + lastRect.width = width - lastRect.height - 4f; + lastRect.x += lastRect.height; + EditorGUI.ProgressBar(lastRect, (!flag4) ? previewInfo.buildProgress : previewInfo.downloadProgress, (!flag4) ? "Building" : "Downloading"); + } + } + GUI.enabled = enabled3; + GUILayout.Space(4f); + if (GUILayout.Button("Open Asset Store", new GUILayoutOption[] + { + GUILayout.Height(40f), + GUILayout.Width(120f) + })) + { + AssetStoreAssetInspector.OpenItemInAssetStore(firstAsset); + GUIUtility.ExitGUI(); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + GUILayout.FlexibleSpace(); + } + EditorWrapper previewEditor = this.previewEditor; + if (previewEditor != null && firstAsset != null && firstAsset.HasLivePreview) + { + previewEditor.OnAssetStoreInspectorGUI(); + } + GUI.enabled = enabled; + EditorGUILayout.EndVertical(); + } + public static void OpenItemInAssetStore(AssetStoreAsset activeAsset) + { + if (activeAsset.id != 0) + { + AssetStore.Open(string.Format("content/{0}?assetID={1}", activeAsset.packageID, activeAsset.id)); + Analytics.Track(string.Format("/AssetStore/ViewInStore/{0}/{1}", activeAsset.packageID, activeAsset.id)); + } + } + private static string intToSizeString(int inValue) + { + if (inValue < 0) + { + return "unknown"; + } + float num = (float)inValue; + string[] array = new string[] + { + "TB", + "GB", + "MB", + "KB", + "Bytes" + }; + int num2 = array.Length - 1; + while (num > 1000f && num2 >= 0) + { + num /= 1000f; + num2--; + } + if (num2 < 0) + { + return ""; + } + return string.Format("{0:#.##} {1}", num, array[num2]); + } + public override bool HasPreviewGUI() + { + return this.target != null && AssetStoreAssetSelection.Count != 0; + } + public void OnEnable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + AssetStoreUtils.RegisterDownloadDelegate(this); + } + public void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + if (this.m_PreviewEditor != null) + { + this.m_PreviewEditor.Dispose(); + this.m_PreviewEditor = null; + } + if (this.m_PreviewObject != null) + { + this.m_PreviewObject = null; + } + AssetStoreUtils.UnRegisterDownloadDelegate(this); + } + public override void OnPreviewSettings() + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + return; + } + EditorWrapper previewEditor = this.previewEditor; + if (previewEditor != null && firstAsset.HasLivePreview) + { + previewEditor.OnPreviewSettings(); + } + } + public override string GetInfoString() + { + EditorWrapper previewEditor = this.previewEditor; + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + return "No item selected"; + } + if (previewEditor != null && firstAsset.HasLivePreview) + { + return previewEditor.GetInfoString(); + } + return string.Empty; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (this.m_PreviewObject == null) + { + return; + } + EditorWrapper previewEditor = this.previewEditor; + if (previewEditor != null && this.m_PreviewObject is AnimationClip) + { + previewEditor.OnPreviewGUI(r, background); + } + else + { + this.OnInteractivePreviewGUI(r, background); + } + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + EditorWrapper previewEditor = this.previewEditor; + if (previewEditor != null) + { + previewEditor.OnInteractivePreviewGUI(r, background); + } + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset != null && !firstAsset.HasLivePreview && !string.IsNullOrEmpty(firstAsset.dynamicPreviewURL)) + { + GUIContent statusWheel = AssetStoreAssetInspector.StatusWheel; + r.y += (r.height - (float)statusWheel.image.height) / 2f; + r.x += (r.width - (float)statusWheel.image.width) / 2f; + GUI.Label(r, AssetStoreAssetInspector.StatusWheel); + base.Repaint(); + } + } + public override GUIContent GetPreviewTitle() + { + return GUIContent.Temp("Asset Store Preview"); + } + private void InitiateBuySelected(bool firstAttempt) + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + EditorUtility.DisplayDialog("No asset selected", "Please select asset before buying a package", "ok"); + } + else + { + if (AssetStoreAssetInspector.paymentAvailability == AssetStoreAssetInspector.PaymentAvailability.AnonymousUser) + { + if (AssetStoreClient.LoggedIn()) + { + AssetStoreAssetSelection.RefreshFromServer(delegate + { + this.InitiateBuySelected(false); + }); + } + else + { + if (firstAttempt) + { + this.LoginAndInitiateBuySelected(); + } + } + } + else + { + if (AssetStoreAssetInspector.paymentAvailability == AssetStoreAssetInspector.PaymentAvailability.ServiceDisabled) + { + if (firstAsset.previewInfo == null) + { + return; + } + AssetStore.Open(string.Format("content/{0}/directpurchase", firstAsset.packageID)); + } + else + { + if (AssetStoreAssetInspector.paymentAvailability == AssetStoreAssetInspector.PaymentAvailability.BasketNotEmpty) + { + if (firstAsset.previewInfo == null) + { + return; + } + if (firstAttempt) + { + AssetStoreAssetSelection.RefreshFromServer(delegate + { + this.InitiateBuySelected(false); + }); + } + else + { + AssetStore.Open(string.Format("content/{0}/basketpurchase", firstAsset.packageID)); + } + } + else + { + AssetStoreInstaBuyWindow.ShowAssetStoreInstaBuyWindow(firstAsset, AssetStoreAssetInspector.s_PurchaseMessage, AssetStoreAssetInspector.s_PaymentMethodCard, AssetStoreAssetInspector.s_PaymentMethodExpire, AssetStoreAssetInspector.s_PriceText); + } + } + } + } + } + private void InitiateBuySelected() + { + this.InitiateBuySelected(true); + } + private void LoginAndInitiateBuySelected() + { + AssetStoreLoginWindow.Login("Please login to the Asset Store in order to get payment information about the package.", delegate(string errorMessage) + { + if (errorMessage != null) + { + return; + } + AssetStoreAssetSelection.RefreshFromServer(delegate + { + this.InitiateBuySelected(false); + }); + }); + } + private void ImportPackage(AssetStoreAsset asset) + { + if (AssetStoreAssetInspector.paymentAvailability == AssetStoreAssetInspector.PaymentAvailability.AnonymousUser) + { + this.LoginAndImport(asset); + } + else + { + AssetStoreInstaBuyWindow.ShowAssetStoreInstaBuyWindowBuilding(asset); + } + } + private void LoginAndImport(AssetStoreAsset asset) + { + AssetStoreLoginWindow.Login("Please login to the Asset Store in order to get download information for the package.", delegate(string errorMessage) + { + if (errorMessage != null) + { + return; + } + AssetStoreAssetSelection.RefreshFromServer(delegate + { + AssetStoreInstaBuyWindow.ShowAssetStoreInstaBuyWindowBuilding(asset); + }); + }); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreAssetSelection.cs b/UnityEditor/UnityEditor/AssetStoreAssetSelection.cs new file mode 100644 index 00000000..63b93eaa --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreAssetSelection.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal static class AssetStoreAssetSelection + { + public delegate void AssetsRefreshed(); + internal static Dictionary s_SelectedAssets; + public static int Count + { + get + { + return (AssetStoreAssetSelection.s_SelectedAssets != null) ? AssetStoreAssetSelection.s_SelectedAssets.Count : 0; + } + } + public static bool Empty + { + get + { + return AssetStoreAssetSelection.s_SelectedAssets == null || AssetStoreAssetSelection.s_SelectedAssets.Count == 0; + } + } + public static void AddAsset(AssetStoreAsset searchResult, Texture2D placeholderPreviewImage) + { + if (placeholderPreviewImage != null) + { + searchResult.previewImage = AssetStoreAssetSelection.ScaleImage(placeholderPreviewImage, 256, 256); + } + searchResult.previewInfo = null; + searchResult.previewBundleRequest = null; + if (!string.IsNullOrEmpty(searchResult.dynamicPreviewURL) && searchResult.previewBundle == null) + { + searchResult.disposed = false; + AsyncHTTPClient client = new AsyncHTTPClient(searchResult.dynamicPreviewURL); + client.doneCallback = delegate(AsyncHTTPClient c) + { + if (!client.IsSuccess()) + { + Console.WriteLine("Error downloading dynamic preview: " + client.text); + searchResult.dynamicPreviewURL = null; + AssetStoreAssetSelection.DownloadStaticPreview(searchResult); + return; + } + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (searchResult.disposed || firstAsset == null || searchResult.id != firstAsset.id) + { + return; + } + try + { + AssetBundleCreateRequest cr = AssetBundle.CreateFromMemory(c.bytes); + cr.DisableCompatibilityChecks(); + searchResult.previewBundleRequest = cr; + EditorApplication.CallbackFunction callback = null; + double startTime = EditorApplication.timeSinceStartup; + callback = delegate + { + AssetStoreUtils.UpdatePreloading(); + if (!cr.isDone) + { + double timeSinceStartup = EditorApplication.timeSinceStartup; + if (timeSinceStartup - startTime > 10.0) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, callback); + Console.WriteLine("Timed out fetch live preview bundle " + (searchResult.dynamicPreviewURL ?? "")); + } + return; + } + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, callback); + AssetStoreAsset firstAsset2 = AssetStoreAssetSelection.GetFirstAsset(); + if (!searchResult.disposed && firstAsset2 != null && searchResult.id == firstAsset2.id) + { + searchResult.previewBundle = cr.assetBundle; + if (cr.assetBundle == null || cr.assetBundle.mainAsset == null) + { + searchResult.dynamicPreviewURL = null; + AssetStoreAssetSelection.DownloadStaticPreview(searchResult); + } + else + { + searchResult.previewAsset = searchResult.previewBundle.mainAsset; + } + } + }; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, callback); + } + catch (Exception ex) + { + Console.Write(ex.Message); + Debug.Log(ex.Message); + } + }; + client.Begin(); + } + else + { + if (!string.IsNullOrEmpty(searchResult.staticPreviewURL)) + { + AssetStoreAssetSelection.DownloadStaticPreview(searchResult); + } + } + AssetStoreAssetSelection.AddAssetInternal(searchResult); + AssetStoreAssetSelection.RefreshFromServer(null); + } + internal static void AddAssetInternal(AssetStoreAsset searchResult) + { + if (AssetStoreAssetSelection.s_SelectedAssets == null) + { + AssetStoreAssetSelection.s_SelectedAssets = new Dictionary(); + } + AssetStoreAssetSelection.s_SelectedAssets[searchResult.id] = searchResult; + } + private static void DownloadStaticPreview(AssetStoreAsset searchResult) + { + AsyncHTTPClient client = new AsyncHTTPClient(searchResult.staticPreviewURL); + client.doneCallback = delegate(AsyncHTTPClient c) + { + if (!client.IsSuccess()) + { + Console.WriteLine("Error downloading static preview: " + client.text); + return; + } + Texture2D texture = c.texture; + Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false, true); + AssetStorePreviewManager.ScaleImage(texture2D.width, texture2D.height, texture, texture2D, null); + searchResult.previewImage = texture2D; + UnityEngine.Object.DestroyImmediate(texture); + AssetStoreAssetInspector.Instance.Repaint(); + }; + client.Begin(); + } + public static void RefreshFromServer(AssetStoreAssetSelection.AssetsRefreshed callback) + { + if (AssetStoreAssetSelection.s_SelectedAssets.Count == 0) + { + return; + } + List list = new List(); + foreach (KeyValuePair current in AssetStoreAssetSelection.s_SelectedAssets) + { + list.Add(current.Value); + } + AssetStoreClient.AssetsInfo(list, delegate(AssetStoreAssetsInfo results) + { + AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.ServiceDisabled; + if (results.error != null && results.error != string.Empty) + { + Console.WriteLine("Error performing Asset Store Info search: " + results.error); + AssetStoreAssetInspector.OfflineNoticeEnabled = true; + if (callback != null) + { + callback(); + } + return; + } + AssetStoreAssetInspector.OfflineNoticeEnabled = false; + if (results.status == AssetStoreAssetsInfo.Status.Ok) + { + AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.Ok; + } + else + { + if (results.status == AssetStoreAssetsInfo.Status.BasketNotEmpty) + { + AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.BasketNotEmpty; + } + else + { + if (results.status == AssetStoreAssetsInfo.Status.AnonymousUser) + { + AssetStoreAssetInspector.paymentAvailability = AssetStoreAssetInspector.PaymentAvailability.AnonymousUser; + } + } + } + AssetStoreAssetInspector.s_PurchaseMessage = results.message; + AssetStoreAssetInspector.s_PaymentMethodCard = results.paymentMethodCard; + AssetStoreAssetInspector.s_PaymentMethodExpire = results.paymentMethodExpire; + AssetStoreAssetInspector.s_PriceText = results.priceText; + AssetStoreAssetInspector.Instance.Repaint(); + if (callback != null) + { + callback(); + } + }); + } + private static Texture2D ScaleImage(Texture2D source, int w, int h) + { + if (source.width % 4 != 0) + { + return null; + } + Texture2D texture2D = new Texture2D(w, h, TextureFormat.RGB24, false, true); + Color[] pixels = texture2D.GetPixels(0); + double num = 1.0 / (double)w; + double num2 = 1.0 / (double)h; + double num3 = 0.0; + double num4 = 0.0; + int num5 = 0; + for (int i = 0; i < h; i++) + { + int j = 0; + while (j < w) + { + pixels[num5] = source.GetPixelBilinear((float)num3, (float)num4); + num3 += num; + j++; + num5++; + } + num3 = 0.0; + num4 += num2; + } + texture2D.SetPixels(pixels, 0); + texture2D.Apply(); + return texture2D; + } + public static bool ContainsAsset(int id) + { + return AssetStoreAssetSelection.s_SelectedAssets != null && AssetStoreAssetSelection.s_SelectedAssets.ContainsKey(id); + } + public static void Clear() + { + if (AssetStoreAssetSelection.s_SelectedAssets == null) + { + return; + } + foreach (KeyValuePair current in AssetStoreAssetSelection.s_SelectedAssets) + { + current.Value.Dispose(); + } + AssetStoreAssetSelection.s_SelectedAssets.Clear(); + } + public static AssetStoreAsset GetFirstAsset() + { + if (AssetStoreAssetSelection.s_SelectedAssets == null) + { + return null; + } + Dictionary.Enumerator enumerator = AssetStoreAssetSelection.s_SelectedAssets.GetEnumerator(); + if (!enumerator.MoveNext()) + { + return null; + } + KeyValuePair current = enumerator.Current; + return current.Value; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreAssetsInfo.cs b/UnityEditor/UnityEditor/AssetStoreAssetsInfo.cs new file mode 100644 index 00000000..83da8d27 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreAssetsInfo.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AssetStoreAssetsInfo : AssetStoreResultBase + { + internal enum Status + { + BasketNotEmpty, + ServiceDisabled, + AnonymousUser, + Ok + } + internal AssetStoreAssetsInfo.Status status; + internal Dictionary assets = new Dictionary(); + internal bool paymentTokenAvailable; + internal string paymentMethodCard; + internal string paymentMethodExpire; + internal float price; + internal float vat; + internal string currency; + internal string priceText; + internal string vatText; + internal string message; + internal AssetStoreAssetsInfo(AssetStoreResultBase.Callback c, List assets) : base(c) + { + foreach (AssetStoreAsset current in assets) + { + this.assets[current.id] = current; + } + } + protected override void Parse(Dictionary dict) + { + Dictionary dictionary = dict["purchase_info"].AsDict(true); + string a = dictionary["status"].AsString(true); + if (a == "basket-not-empty") + { + this.status = AssetStoreAssetsInfo.Status.BasketNotEmpty; + } + else + { + if (a == "service-disabled") + { + this.status = AssetStoreAssetsInfo.Status.ServiceDisabled; + } + else + { + if (a == "user-anonymous") + { + this.status = AssetStoreAssetsInfo.Status.AnonymousUser; + } + else + { + if (a == "ok") + { + this.status = AssetStoreAssetsInfo.Status.Ok; + } + } + } + } + this.paymentTokenAvailable = dictionary["payment_token_available"].AsBool(); + if (dictionary.ContainsKey("payment_method_card")) + { + this.paymentMethodCard = dictionary["payment_method_card"].AsString(true); + } + if (dictionary.ContainsKey("payment_method_expire")) + { + this.paymentMethodExpire = dictionary["payment_method_expire"].AsString(true); + } + this.price = dictionary["price"].AsFloat(true); + this.vat = dictionary["vat"].AsFloat(true); + this.priceText = dictionary["price_text"].AsString(true); + this.vatText = dictionary["vat_text"].AsString(true); + this.currency = dictionary["currency"].AsString(true); + this.message = ((!dictionary.ContainsKey("message")) ? null : dictionary["message"].AsString(true)); + List list = dict["results"].AsList(true); + foreach (JSONValue current in list) + { + int key; + if (current["id"].IsString()) + { + key = int.Parse(current["id"].AsString()); + } + else + { + key = (int)current["id"].AsFloat(); + } + AssetStoreAsset assetStoreAsset; + if (this.assets.TryGetValue(key, out assetStoreAsset)) + { + if (assetStoreAsset.previewInfo == null) + { + assetStoreAsset.previewInfo = new AssetStoreAsset.PreviewInfo(); + } + AssetStoreAsset.PreviewInfo previewInfo = assetStoreAsset.previewInfo; + assetStoreAsset.className = current["class_names"].AsString(true).Trim(); + previewInfo.packageName = current["package_name"].AsString(true).Trim(); + previewInfo.packageShortUrl = current["short_url"].AsString(true).Trim(); + assetStoreAsset.price = ((!current.ContainsKey("price_text")) ? null : current["price_text"].AsString(true).Trim()); + previewInfo.packageSize = int.Parse((!current.Get("package_size").IsNull()) ? current["package_size"].AsString(true) : "-1"); + assetStoreAsset.packageID = int.Parse(current["package_id"].AsString()); + previewInfo.packageVersion = current["package_version"].AsString(); + previewInfo.packageRating = int.Parse((!current.Get("rating").IsNull() && current["rating"].AsString(true).Length != 0) ? current["rating"].AsString(true) : "-1"); + previewInfo.packageAssetCount = int.Parse((!current["package_asset_count"].IsNull()) ? current["package_asset_count"].AsString(true) : "-1"); + previewInfo.isPurchased = (current.ContainsKey("purchased") && current["purchased"].AsBool(true)); + previewInfo.isDownloadable = (previewInfo.isPurchased || assetStoreAsset.price == null); + previewInfo.publisherName = current["publisher_name"].AsString(true).Trim(); + previewInfo.packageUrl = ((!current.Get("package_url").IsNull()) ? current["package_url"].AsString(true) : string.Empty); + previewInfo.encryptionKey = ((!current.Get("encryption_key").IsNull()) ? current["encryption_key"].AsString(true) : string.Empty); + previewInfo.categoryName = ((!current.Get("category_name").IsNull()) ? current["category_name"].AsString(true) : string.Empty); + previewInfo.buildProgress = -1f; + previewInfo.downloadProgress = -1f; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreClient.cs b/UnityEditor/UnityEditor/AssetStoreClient.cs new file mode 100644 index 00000000..182b9c40 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreClient.cs @@ -0,0 +1,455 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetStoreClient + { + internal enum LoginState + { + LOGGED_OUT, + IN_PROGRESS, + LOGGED_IN, + LOGIN_ERROR + } + internal struct SearchCount + { + public string name; + public int offset; + public int limit; + } + public delegate void DoneCallback(AssetStoreResponse response); + public delegate void DoneLoginCallback(string errorMessage); + private const string kUnauthSessionID = "26c4202eb475d02864b40827dfff11a14657aa41"; + private static string s_AssetStoreUrl; + private static string s_AssetStoreSearchUrl; + private static AssetStoreClient.LoginState sLoginState; + private static string sLoginErrorMessage; + public static string LoginErrorMessage + { + get + { + return AssetStoreClient.sLoginErrorMessage; + } + } + private static string VersionParams + { + get + { + return "unityversion=" + Uri.EscapeDataString(Application.unityVersion) + "&skip_terms=1"; + } + } + private static string AssetStoreUrl + { + get + { + if (AssetStoreClient.s_AssetStoreUrl == null) + { + AssetStoreClient.s_AssetStoreUrl = AssetStoreUtils.GetAssetStoreUrl(); + } + return AssetStoreClient.s_AssetStoreUrl; + } + } + private static string AssetStoreSearchUrl + { + get + { + if (AssetStoreClient.s_AssetStoreSearchUrl == null) + { + AssetStoreClient.s_AssetStoreSearchUrl = AssetStoreUtils.GetAssetStoreSearchUrl(); + } + return AssetStoreClient.s_AssetStoreSearchUrl; + } + } + private static string SavedSessionID + { + get + { + if (AssetStoreClient.RememberSession) + { + return EditorPrefs.GetString("kharma.sessionid", string.Empty); + } + return string.Empty; + } + set + { + EditorPrefs.SetString("kharma.sessionid", value); + } + } + public static bool HasSavedSessionID + { + get + { + return !string.IsNullOrEmpty(AssetStoreClient.SavedSessionID); + } + } + internal static string ActiveSessionID + { + get + { + if (AssetStoreContext.SessionHasString("kharma.active_sessionid")) + { + return AssetStoreContext.SessionGetString("kharma.active_sessionid"); + } + return string.Empty; + } + set + { + AssetStoreContext.SessionSetString("kharma.active_sessionid", value); + } + } + public static bool HasActiveSessionID + { + get + { + return !string.IsNullOrEmpty(AssetStoreClient.ActiveSessionID); + } + } + private static string ActiveOrUnauthSessionID + { + get + { + string activeSessionID = AssetStoreClient.ActiveSessionID; + if (activeSessionID == string.Empty) + { + return "26c4202eb475d02864b40827dfff11a14657aa41"; + } + return activeSessionID; + } + } + public static bool RememberSession + { + get + { + return EditorPrefs.GetString("kharma.remember_session") == "1"; + } + set + { + EditorPrefs.SetString("kharma.remember_session", (!value) ? "0" : "1"); + } + } + static AssetStoreClient() + { + ServicePointManager.ServerCertificateValidationCallback = ((object obj, X509Certificate x509Certificate, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors) => true); + } + private static string APIUrl(string path) + { + return string.Format("{0}/api{2}.json?{1}", AssetStoreClient.AssetStoreUrl, AssetStoreClient.VersionParams, path); + } + private static string APISearchUrl(string path) + { + return string.Format("{0}/public-api{2}.json?{1}", AssetStoreClient.AssetStoreSearchUrl, AssetStoreClient.VersionParams, path); + } + private static string GetToken() + { + return InternalEditorUtility.GetAuthToken(); + } + public static bool LoggedIn() + { + return !string.IsNullOrEmpty(AssetStoreClient.ActiveSessionID); + } + public static bool LoggedOut() + { + return string.IsNullOrEmpty(AssetStoreClient.ActiveSessionID); + } + public static bool LoginError() + { + return AssetStoreClient.sLoginState == AssetStoreClient.LoginState.LOGIN_ERROR; + } + public static bool LoginInProgress() + { + return AssetStoreClient.sLoginState == AssetStoreClient.LoginState.IN_PROGRESS; + } + internal static void LoginWithCredentials(string username, string password, bool rememberMe, AssetStoreClient.DoneLoginCallback callback) + { + if (AssetStoreClient.sLoginState == AssetStoreClient.LoginState.IN_PROGRESS) + { + Debug.LogError("Tried to login with credentials while already in progress of logging in"); + return; + } + AssetStoreClient.sLoginState = AssetStoreClient.LoginState.IN_PROGRESS; + AssetStoreClient.RememberSession = rememberMe; + string text = AssetStoreClient.AssetStoreUrl + "/login?skip_terms=1"; + AssetStoreClient.sLoginErrorMessage = null; + AsyncHTTPClient asyncHTTPClient = new AsyncHTTPClient(text.Replace("http://", "https://")); + asyncHTTPClient.postData = "user=" + username + "&pass=" + password; + asyncHTTPClient.header["X-Unity-Session"] = "26c4202eb475d02864b40827dfff11a14657aa41" + AssetStoreClient.GetToken(); + asyncHTTPClient.doneCallback = AssetStoreClient.WrapLoginCallback(callback); + asyncHTTPClient.Begin(); + } + internal static void LoginWithRememberedSession(AssetStoreClient.DoneLoginCallback callback) + { + if (AssetStoreClient.sLoginState == AssetStoreClient.LoginState.IN_PROGRESS) + { + Debug.LogError("Tried to login with remembered session while already in progress of logging in"); + return; + } + AssetStoreClient.sLoginState = AssetStoreClient.LoginState.IN_PROGRESS; + if (!AssetStoreClient.RememberSession) + { + AssetStoreClient.SavedSessionID = string.Empty; + } + string toUrl = AssetStoreClient.AssetStoreUrl + "/login?skip_terms=1&reuse_session=" + AssetStoreClient.SavedSessionID; + AssetStoreClient.sLoginErrorMessage = null; + AsyncHTTPClient asyncHTTPClient = new AsyncHTTPClient(toUrl); + asyncHTTPClient.header["X-Unity-Session"] = "26c4202eb475d02864b40827dfff11a14657aa41" + AssetStoreClient.GetToken(); + asyncHTTPClient.doneCallback = AssetStoreClient.WrapLoginCallback(callback); + asyncHTTPClient.Begin(); + } + private static AsyncHTTPClient.DoneCallback WrapLoginCallback(AssetStoreClient.DoneLoginCallback callback) + { + return delegate(AsyncHTTPClient job) + { + string text = job.text; + if (!job.IsSuccess()) + { + AssetStoreClient.sLoginState = AssetStoreClient.LoginState.LOGIN_ERROR; + AssetStoreClient.sLoginErrorMessage = ((job.responseCode < 200 || job.responseCode >= 300) ? "Failed to login - please retry" : text); + } + else + { + if (text.StartsWith(" param, AssetStoreClient.DoneCallback callback) + { + AsyncHTTPClient asyncHTTPClient = new AsyncHTTPClient(url); + asyncHTTPClient.header["X-Unity-Session"] = AssetStoreClient.ActiveOrUnauthSessionID + AssetStoreClient.GetToken(); + asyncHTTPClient.postDictionary = param; + asyncHTTPClient.doneCallback = AssetStoreClient.WrapJsonCallback(callback); + asyncHTTPClient.Begin(); + return asyncHTTPClient; + } + private static AsyncHTTPClient CreateJSONRequestPost(string url, string postData, AssetStoreClient.DoneCallback callback) + { + AsyncHTTPClient asyncHTTPClient = new AsyncHTTPClient(url); + asyncHTTPClient.header["X-Unity-Session"] = AssetStoreClient.ActiveOrUnauthSessionID + AssetStoreClient.GetToken(); + asyncHTTPClient.postData = postData; + asyncHTTPClient.doneCallback = AssetStoreClient.WrapJsonCallback(callback); + asyncHTTPClient.Begin(); + return asyncHTTPClient; + } + private static AsyncHTTPClient CreateJSONRequestDelete(string url, AssetStoreClient.DoneCallback callback) + { + AsyncHTTPClient asyncHTTPClient = new AsyncHTTPClient(url, "DELETE"); + asyncHTTPClient.header["X-Unity-Session"] = AssetStoreClient.ActiveOrUnauthSessionID + AssetStoreClient.GetToken(); + asyncHTTPClient.doneCallback = AssetStoreClient.WrapJsonCallback(callback); + asyncHTTPClient.Begin(); + return asyncHTTPClient; + } + private static AsyncHTTPClient.DoneCallback WrapJsonCallback(AssetStoreClient.DoneCallback callback) + { + return delegate(AsyncHTTPClient job) + { + if (job.IsDone()) + { + try + { + AssetStoreResponse response = AssetStoreClient.ParseContent(job); + callback(response); + } + catch (Exception ex) + { + Debug.Log("Uncaught exception in async net callback: " + ex.Message); + Debug.Log(ex.StackTrace); + } + } + }; + } + private static AssetStoreResponse ParseContent(AsyncHTTPClient job) + { + AssetStoreResponse assetStoreResponse = new AssetStoreResponse(); + assetStoreResponse.job = job; + assetStoreResponse.dict = null; + assetStoreResponse.ok = false; + AsyncHTTPClient.State state = job.state; + string text = job.text; + if (!AsyncHTTPClient.IsSuccess(state)) + { + Console.WriteLine(text); + return assetStoreResponse; + } + string text2; + string str; + assetStoreResponse.dict = AssetStoreClient.ParseJSON(text, out text2, out str); + if (text2 == "error") + { + Debug.LogError("Request error (" + text2 + "): " + str); + return assetStoreResponse; + } + assetStoreResponse.ok = true; + return assetStoreResponse; + } + private static Dictionary ParseJSON(string content, out string status, out string message) + { + message = null; + status = null; + JSONValue jSONValue; + try + { + JSONParser jSONParser = new JSONParser(content); + jSONValue = jSONParser.Parse(); + } + catch (JSONParseException ex) + { + Debug.Log("Error parsing server reply: " + content); + Debug.Log(ex.Message); + Dictionary result = null; + return result; + } + Dictionary dictionary; + try + { + dictionary = jSONValue.AsDict(true); + if (dictionary == null) + { + Debug.Log("Error parsing server message: " + content); + Dictionary result = null; + return result; + } + if (dictionary.ContainsKey("result") && dictionary["result"].IsDict()) + { + dictionary = dictionary["result"].AsDict(true); + } + if (dictionary.ContainsKey("message")) + { + message = dictionary["message"].AsString(true); + } + if (dictionary.ContainsKey("status")) + { + status = dictionary["status"].AsString(true); + } + else + { + if (dictionary.ContainsKey("error")) + { + status = dictionary["error"].AsString(true); + if (status == string.Empty) + { + status = "ok"; + } + } + else + { + status = "ok"; + } + } + } + catch (JSONTypeException ex2) + { + Debug.Log("Error parsing server reply. " + content); + Debug.Log(ex2.Message); + Dictionary result = null; + return result; + } + return dictionary; + } + internal static AsyncHTTPClient SearchAssets(string searchString, string[] requiredClassNames, string[] assetLabels, List counts, AssetStoreResultBase.Callback callback) + { + string text = string.Empty; + string text2 = string.Empty; + string text3 = string.Empty; + string text4 = string.Empty; + foreach (AssetStoreClient.SearchCount current in counts) + { + text = text + text4 + current.offset; + text2 = text2 + text4 + current.limit; + text3 = text3 + text4 + current.name; + text4 = ","; + } + if (Array.Exists(requiredClassNames, (string a) => a.Equals("MonoScript", StringComparison.OrdinalIgnoreCase))) + { + Array.Resize(ref requiredClassNames, requiredClassNames.Length + 1); + requiredClassNames[requiredClassNames.Length - 1] = "Script"; + } + string url = string.Format("{0}&q={1}&c={2}&l={3}&O={4}&N={5}&G={6}", new object[] + { + AssetStoreClient.APISearchUrl("/search/assets"), + Uri.EscapeDataString(searchString), + Uri.EscapeDataString(string.Join(",", requiredClassNames)), + Uri.EscapeDataString(string.Join(",", assetLabels)), + text, + text2, + text3 + }); + AssetStoreSearchResults r = new AssetStoreSearchResults(callback); + return AssetStoreClient.CreateJSONRequest(url, delegate(AssetStoreResponse ar) + { + r.Parse(ar); + }); + } + internal static AsyncHTTPClient AssetsInfo(List assets, AssetStoreResultBase.Callback callback) + { + string text = AssetStoreClient.APIUrl("/assets/list"); + foreach (AssetStoreAsset current in assets) + { + text = text + "&id=" + current.id.ToString(); + } + AssetStoreAssetsInfo r = new AssetStoreAssetsInfo(callback, assets); + return AssetStoreClient.CreateJSONRequest(text, delegate(AssetStoreResponse ar) + { + r.Parse(ar); + }); + } + internal static AsyncHTTPClient DirectPurchase(int packageID, string password, AssetStoreResultBase.Callback callback) + { + string url = AssetStoreClient.APIUrl(string.Format("/purchase/direct/{0}", packageID.ToString())); + PurchaseResult r = new PurchaseResult(callback); + Dictionary dictionary = new Dictionary(); + dictionary["password"] = password; + return AssetStoreClient.CreateJSONRequestPost(url, dictionary, delegate(AssetStoreResponse ar) + { + r.Parse(ar); + }); + } + internal static AsyncHTTPClient BuildPackage(AssetStoreAsset asset, AssetStoreResultBase.Callback callback) + { + string url = AssetStoreClient.APIUrl("/content/download/" + asset.packageID.ToString()); + BuildPackageResult r = new BuildPackageResult(asset, callback); + return AssetStoreClient.CreateJSONRequest(url, delegate(AssetStoreResponse ar) + { + r.Parse(ar); + }); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreContext.cs b/UnityEditor/UnityEditor/AssetStoreContext.cs new file mode 100644 index 00000000..9ed0c100 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreContext.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class AssetStoreContext : ScriptableObject + { + private static Regex standardPackageRe = new Regex("/Standard Packages/(Character\\ Controller|Glass\\ Refraction\\ \\(Pro\\ Only\\)|Image\\ Effects\\ \\(Pro\\ Only\\)|Light\\ Cookies|Light\\ Flares|Particles|Physic\\ Materials|Projectors|Scripts|Standard\\ Assets\\ \\(Mobile\\)|Skyboxes|Terrain\\ Assets|Toon\\ Shading|Tree\\ Creator|Water\\ \\(Basic\\)|Water\\ \\(Pro\\ Only\\))\\.unitypackage$", RegexOptions.IgnoreCase); + private static Regex generatedIDRe = new Regex("^\\{(.*)\\}$"); + private static Regex invalidPathChars = new Regex("[^a-zA-Z0-9() _-]"); + public bool docked; + public string initialOpenURL; + public AssetStoreWindow window; + private WebScriptObject JS + { + get + { + return this.window.scriptObject; + } + } + public WebScriptObject packages + { + get + { + WebScriptObject packageList = this.GetPackageList(); + return packageList.Get("results"); + } + } + private AssetStoreContext() + { + } + public string GetInitialOpenURL() + { + if (this.initialOpenURL != null) + { + string result = this.initialOpenURL; + this.initialOpenURL = null; + return result; + } + return string.Empty; + } + public string GetAuthToken() + { + return InternalEditorUtility.GetAuthToken(); + } + public int[] GetLicenseFlags() + { + return InternalEditorUtility.GetLicenseFlags(); + } + public void Download(WebScriptObject package, WebScriptObject downloadInfo) + { + string url = downloadInfo.Get("url"); + string key = downloadInfo.Get("key"); + string package_id = downloadInfo.Get("id"); + string package_name = package.Get("title"); + string publisher_name = package.Get("publisher.label"); + string category_name = package.Get("category.label"); + AssetStoreContext.Download(package_id, url, key, package_name, publisher_name, category_name, null); + } + public static string[] PackageStorePath(string publisher_name, string category_name, string package_name, string package_id, string url) + { + string[] array = new string[] + { + publisher_name, + category_name, + package_name + }; + for (int i = 0; i < 3; i++) + { + array[i] = AssetStoreContext.invalidPathChars.Replace(array[i], string.Empty); + } + if (array[2] == string.Empty) + { + array[2] = AssetStoreContext.invalidPathChars.Replace(package_id, string.Empty); + } + if (array[2] == string.Empty) + { + array[2] = AssetStoreContext.invalidPathChars.Replace(url, string.Empty); + } + return array; + } + public static void Download(string package_id, string url, string key, string package_name, string publisher_name, string category_name, AssetStoreUtils.DownloadDoneCallback doneCallback) + { + string[] destination = AssetStoreContext.PackageStorePath(publisher_name, category_name, package_name, package_id, url); + JSONValue jSONValue = JSONParser.SimpleParse(AssetStoreUtils.CheckDownload(package_id, url, destination, key)); + if (jSONValue.Get("in_progress").AsBool(true)) + { + Debug.Log("Will not download " + package_name + ". Download is already in progress."); + return; + } + string a = jSONValue.Get("download.url").AsString(true); + string a2 = jSONValue.Get("download.key").AsString(true); + bool resumeOK = a == url && a2 == key; + JSONValue value = default(JSONValue); + value["url"] = url; + value["key"] = key; + JSONValue jSONValue2 = default(JSONValue); + jSONValue2["download"] = value; + AssetStoreUtils.Download(package_id, url, destination, key, jSONValue2.ToString(), resumeOK, doneCallback); + } + public string GetString(string key) + { + return EditorPrefs.GetString(key); + } + public int GetInt(string key) + { + return EditorPrefs.GetInt(key); + } + public float GetFloat(string key) + { + return EditorPrefs.GetFloat(key); + } + public void SetString(string key, string value) + { + EditorPrefs.SetString(key, value); + } + public void SetInt(string key, int value) + { + EditorPrefs.SetInt(key, value); + } + public void SetFloat(string key, float value) + { + EditorPrefs.SetFloat(key, value); + } + public bool HasKey(string key) + { + return EditorPrefs.HasKey(key); + } + public void DeleteKey(string key) + { + EditorPrefs.DeleteKey(key); + } + private bool IsBuiltinStandardAsset(string path) + { + return AssetStoreContext.standardPackageRe.IsMatch(path); + } + public WebScriptObject GetPackageList() + { + Dictionary dictionary = new Dictionary(); + WebScriptObject webScriptObject = this.JS.ParseJSON("{}"); + WebScriptObject webScriptObject2 = this.JS.ParseJSON("[]"); + PackageInfo[] packageList = PackageInfo.GetPackageList(); + PackageInfo[] array = packageList; + for (int i = 0; i < array.Length; i++) + { + PackageInfo packageInfo = array[i]; + WebScriptObject webScriptObject3; + if (packageInfo.jsonInfo == string.Empty) + { + webScriptObject3 = this.JS.ParseJSON("{}"); + webScriptObject3.Set("title", Path.GetFileNameWithoutExtension(packageInfo.packagePath)); + webScriptObject3.Set("id", "{" + packageInfo.packagePath + "}"); + if (this.IsBuiltinStandardAsset(packageInfo.packagePath)) + { + webScriptObject3.Set("publisher", this.JS.ParseJSON("{\"label\": \"Unity Technologies\",\"id\": \"1\"}")); + webScriptObject3.Set("category", this.JS.ParseJSON("{\"label\": \"Prefab Packages\",\"id\": \"4\"}")); + webScriptObject3.Set("version", "3.5.0.0"); + webScriptObject3.Set("version_id", "-1"); + } + } + else + { + webScriptObject3 = this.JS.ParseJSON(packageInfo.jsonInfo); + if (webScriptObject3.Get("id") == null) + { + WebScriptObject webScriptObject4 = webScriptObject3.Get("link"); + if (webScriptObject4 != null) + { + webScriptObject3.Set("id", webScriptObject4.Get("id")); + } + else + { + webScriptObject3.Set("id", "{" + packageInfo.packagePath + "}"); + } + } + } + string key = webScriptObject3.Get("id"); + webScriptObject3.Set("local_icon", packageInfo.iconURL); + webScriptObject3.Set("local_path", packageInfo.packagePath); + if (!dictionary.ContainsKey(key) || dictionary[key].Get("version_id") == null || (webScriptObject3.Get("version_id") != null && dictionary[key].Get("version_id") <= webScriptObject3.Get("version_id"))) + { + dictionary[key] = webScriptObject3; + } + } + int num = 0; + foreach (KeyValuePair current in dictionary) + { + webScriptObject2.Set(num++, current.Value); + } + webScriptObject.Set("results", webScriptObject2); + return webScriptObject; + } + public int GetSkinIndex() + { + return (!EditorGUIUtility.isProSkin) ? 0 : 1; + } + public bool GetDockedStatus() + { + return this.docked; + } + public bool OpenPackage(string id) + { + return this.OpenPackage(id, "default"); + } + public bool OpenPackage(string id, string action) + { + return AssetStoreContext.OpenPackageInternal(id); + } + public static bool OpenPackageInternal(string id) + { + Match match = AssetStoreContext.generatedIDRe.Match(id); + if (match.Success && File.Exists(match.Groups[1].Value)) + { + AssetDatabase.ImportPackage(match.Groups[1].Value, true); + return true; + } + PackageInfo[] packageList = PackageInfo.GetPackageList(); + for (int i = 0; i < packageList.Length; i++) + { + PackageInfo packageInfo = packageList[i]; + if (packageInfo.jsonInfo != string.Empty) + { + JSONValue jSONValue = JSONParser.SimpleParse(packageInfo.jsonInfo); + string text = (!jSONValue.Get("id").IsNull()) ? jSONValue["id"].AsString(true) : null; + if (text != null && text == id && File.Exists(packageInfo.packagePath)) + { + AssetDatabase.ImportPackage(packageInfo.packagePath, true); + return true; + } + } + } + Debug.LogError("Unknown package ID " + id); + return false; + } + public void MakeMenu(WebScriptObject contextMenu) + { + this.MakeMenu(contextMenu, 0f, 0f); + } + public void MakeMenu(WebScriptObject contextMenu, float deltaX, float deltaY) + { + WebScriptObject webScriptObject = contextMenu.Get("commands"); + int num = webScriptObject.Get("length"); + string[] array = new string[num]; + string[] array2 = new string[num]; + for (int i = 0; i < webScriptObject.Get("length"); i++) + { + WebScriptObject webScriptObject2 = webScriptObject.Get(i); + array[i] = webScriptObject2.Get("label"); + array2[i] = webScriptObject2.Get("action"); + } + Vector2 mousePosition = Event.current.mousePosition; + Rect position = new Rect(mousePosition.x + deltaX, mousePosition.y + deltaY, 0f, 0f); + EditorUtility.DisplayCustomMenu(position, array, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), array2); + } + public void OpenBrowser(string url) + { + Application.OpenURL(url); + } + private void ContextMenuClick(object userData, string[] options, int selected) + { + if (selected >= 0) + { + string[] array = userData as string[]; + this.JS.EvalJavaScript(array[selected]); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SessionSetString(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string SessionGetString(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SessionRemoveString(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SessionHasString(string key); + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs b/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs new file mode 100644 index 00000000..cb1b47a6 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs @@ -0,0 +1,488 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetStoreInstaBuyWindow : EditorWindow + { + private enum PurchaseStatus + { + Init, + InProgress, + Declined, + Complete, + StartBuild, + Building, + Downloading + } + private const int kStandardHeight = 160; + private const double kBuildPollInterval = 2.0; + private const int kMaxPolls = 150; + private static GUIContent s_AssetStoreLogo; + private string m_Password = string.Empty; + private AssetStoreAsset m_Asset; + private string m_Message = string.Empty; + private AssetStoreInstaBuyWindow.PurchaseStatus m_Purchasing; + private double m_NextAllowedBuildRequestTime; + private int m_BuildAttempts; + private string m_PurchaseMessage; + private string m_PaymentMethodCard; + private string m_PaymentMethodExpire; + private string m_PriceText; + public static AssetStoreInstaBuyWindow ShowAssetStoreInstaBuyWindow(AssetStoreAsset asset, string purchaseMessage, string paymentMethodCard, string paymentMethodExpire, string priceText) + { + AssetStoreInstaBuyWindow windowWithRect = EditorWindow.GetWindowWithRect(new Rect(100f, 100f, 400f, 160f), true, "Buy package from Asset Store"); + if (windowWithRect.m_Purchasing != AssetStoreInstaBuyWindow.PurchaseStatus.Init) + { + EditorUtility.DisplayDialog("Download in progress", "There is already a package download in progress. You can only have one download running at a time", "Close"); + return windowWithRect; + } + windowWithRect.position = new Rect(100f, 100f, 400f, 160f); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + windowWithRect.m_Asset = asset; + windowWithRect.m_Password = string.Empty; + windowWithRect.m_Message = string.Empty; + windowWithRect.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Init; + windowWithRect.m_NextAllowedBuildRequestTime = 0.0; + windowWithRect.m_BuildAttempts = 0; + windowWithRect.m_PurchaseMessage = purchaseMessage; + windowWithRect.m_PaymentMethodCard = paymentMethodCard; + windowWithRect.m_PaymentMethodExpire = paymentMethodExpire; + windowWithRect.m_PriceText = priceText; + Analytics.Track(string.Format("/AssetStore/ShowInstaBuy/{0}/{1}", windowWithRect.m_Asset.packageID, windowWithRect.m_Asset.id)); + return windowWithRect; + } + public static void ShowAssetStoreInstaBuyWindowBuilding(AssetStoreAsset asset) + { + AssetStoreInstaBuyWindow assetStoreInstaBuyWindow = AssetStoreInstaBuyWindow.ShowAssetStoreInstaBuyWindow(asset, string.Empty, string.Empty, string.Empty, string.Empty); + if (assetStoreInstaBuyWindow.m_Purchasing != AssetStoreInstaBuyWindow.PurchaseStatus.Init) + { + EditorUtility.DisplayDialog("Download in progress", "There is already a package download in progress. You can only have one download running at a time", "Close"); + return; + } + assetStoreInstaBuyWindow.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.StartBuild; + assetStoreInstaBuyWindow.m_BuildAttempts = 1; + asset.previewInfo.buildProgress = 0f; + Analytics.Track(string.Format("/AssetStore/ShowInstaFree/{0}/{1}", assetStoreInstaBuyWindow.m_Asset.packageID, assetStoreInstaBuyWindow.m_Asset.id)); + } + private static void LoadLogos() + { + if (AssetStoreInstaBuyWindow.s_AssetStoreLogo != null) + { + return; + } + AssetStoreInstaBuyWindow.s_AssetStoreLogo = EditorGUIUtility.IconContent("WelcomeScreen.AssetStoreLogo"); + } + public void OnInspectorUpdate() + { + if (this.m_Purchasing == AssetStoreInstaBuyWindow.PurchaseStatus.StartBuild && this.m_NextAllowedBuildRequestTime <= EditorApplication.timeSinceStartup) + { + this.m_NextAllowedBuildRequestTime = EditorApplication.timeSinceStartup + 2.0; + this.BuildPackage(); + } + } + private void OnEnable() + { + AssetStoreUtils.RegisterDownloadDelegate(this); + } + public void OnDisable() + { + AssetStoreAsset.PreviewInfo previewInfo = (this.m_Asset != null) ? this.m_Asset.previewInfo : null; + if (previewInfo != null) + { + previewInfo.downloadProgress = -1f; + previewInfo.buildProgress = -1f; + } + AssetStoreUtils.UnRegisterDownloadDelegate(this); + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Init; + } + public void OnDownloadProgress(string id, string message, int bytes, int total) + { + AssetStoreAsset.PreviewInfo previewInfo = (this.m_Asset != null) ? this.m_Asset.previewInfo : null; + if (previewInfo == null || this.m_Asset.packageID.ToString() != id) + { + return; + } + if (message == "downloading" || message == "connecting") + { + previewInfo.downloadProgress = (float)bytes / (float)total; + } + else + { + previewInfo.downloadProgress = -1f; + } + base.Repaint(); + } + public void OnGUI() + { + AssetStoreInstaBuyWindow.LoadLogos(); + if (this.m_Asset == null) + { + return; + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(10f); + switch (this.m_Purchasing) + { + case AssetStoreInstaBuyWindow.PurchaseStatus.Init: + this.PasswordGUI(); + break; + case AssetStoreInstaBuyWindow.PurchaseStatus.InProgress: + if (this.m_Purchasing == AssetStoreInstaBuyWindow.PurchaseStatus.InProgress) + { + GUI.enabled = false; + } + this.PasswordGUI(); + break; + case AssetStoreInstaBuyWindow.PurchaseStatus.Declined: + this.PurchaseDeclinedGUI(); + break; + case AssetStoreInstaBuyWindow.PurchaseStatus.Complete: + this.PurchaseSuccessGUI(); + break; + case AssetStoreInstaBuyWindow.PurchaseStatus.StartBuild: + case AssetStoreInstaBuyWindow.PurchaseStatus.Building: + case AssetStoreInstaBuyWindow.PurchaseStatus.Downloading: + this.DownloadingGUI(); + break; + } + GUILayout.EndVertical(); + } + private void PasswordGUI() + { + AssetStoreAsset.PreviewInfo previewInfo = this.m_Asset.previewInfo; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AssetStoreInstaBuyWindow.s_AssetStoreLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Complete purchase by entering your AssetStore password", EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag = this.m_PurchaseMessage != null && this.m_PurchaseMessage != string.Empty; + bool flag2 = this.m_Message != null && this.m_Message != string.Empty; + float num = (float)(160 + ((!flag) ? 0 : 20) + ((!flag2) ? 0 : 20)); + if (num != base.position.height) + { + base.position = new Rect(base.position.x, base.position.y, base.position.width, num); + } + if (flag) + { + GUILayout.Label(this.m_PurchaseMessage, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + if (flag2) + { + Color color = GUI.color; + GUI.color = Color.red; + GUILayout.Label(this.m_Message, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUI.color = color; + } + GUILayout.Label("Package: " + previewInfo.packageName, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + string text = string.Format("Credit card: {0} (expires {1})", this.m_PaymentMethodCard, this.m_PaymentMethodExpire); + GUILayout.Label(text, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Space(8f); + EditorGUILayout.LabelField("Amount", this.m_PriceText, new GUILayoutOption[0]); + this.m_Password = EditorGUILayout.PasswordField("Password", this.m_Password, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(8f); + if (GUILayout.Button("Just put to basket...", new GUILayoutOption[0])) + { + AssetStore.Open(string.Format("content/{0}/basketpurchase", this.m_Asset.packageID)); + Analytics.Track(string.Format("/AssetStore/PutToBasket/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_Asset = null; + base.Close(); + GUIUtility.ExitGUI(); + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Cancel", new GUILayoutOption[0])) + { + Analytics.Track(string.Format("/AssetStore/CancelInstaBuy/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_Asset = null; + base.Close(); + GUIUtility.ExitGUI(); + } + GUILayout.Space(5f); + if (GUILayout.Button("Complete purchase", new GUILayoutOption[0])) + { + this.CompletePurchase(); + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + } + private void PurchaseSuccessGUI() + { + AssetStoreAsset.PreviewInfo previewInfo = this.m_Asset.previewInfo; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AssetStoreInstaBuyWindow.s_AssetStoreLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Purchase completed succesfully", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("You will receive a receipt in your email soon.", new GUILayoutOption[0]); + bool flag = this.m_Message != null && this.m_Message != string.Empty; + float num = (float)(160 + ((!flag) ? 0 : 20)); + if (num != base.position.height) + { + base.position = new Rect(base.position.x, base.position.y, base.position.width, num); + } + if (flag) + { + GUILayout.Label(this.m_Message, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + GUILayout.Label("Package: " + previewInfo.packageName, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(8f); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Close", new GUILayoutOption[0])) + { + Analytics.Track(string.Format("/AssetStore/PurchaseOk/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_Asset = null; + base.Close(); + } + GUILayout.Space(5f); + if (GUILayout.Button("Import package", new GUILayoutOption[0])) + { + Analytics.Track(string.Format("/AssetStore/PurchaseOkImport/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_BuildAttempts = 1; + this.m_Asset.previewInfo.buildProgress = 0f; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.StartBuild; + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + } + private void DownloadingGUI() + { + AssetStoreAsset.PreviewInfo previewInfo = this.m_Asset.previewInfo; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AssetStoreInstaBuyWindow.s_AssetStoreLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + string text = "Importing"; + GUILayout.Label(text, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("Package: " + previewInfo.packageName, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Label(" ", new GUILayoutOption[0]); + if (Event.current.type == EventType.Repaint) + { + Rect lastRect = GUILayoutUtility.GetLastRect(); + lastRect.height += 1f; + bool flag = previewInfo.downloadProgress >= 0f; + EditorGUI.ProgressBar(lastRect, (!flag) ? previewInfo.buildProgress : previewInfo.downloadProgress, (!flag) ? "Building" : "Downloading"); + } + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Abort", new GUILayoutOption[0])) + { + base.Close(); + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + } + private void PurchaseDeclinedGUI() + { + AssetStoreAsset.PreviewInfo previewInfo = this.m_Asset.previewInfo; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AssetStoreInstaBuyWindow.s_AssetStoreLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Purchase declined", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("No money has been drawn from you credit card", new GUILayoutOption[0]); + bool flag = this.m_Message != null && this.m_Message != string.Empty; + float num = (float)(160 + ((!flag) ? 0 : 20)); + if (num != base.position.height) + { + base.position = new Rect(base.position.x, base.position.y, base.position.width, num); + } + if (flag) + { + GUILayout.Label(this.m_Message, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + GUILayout.Label("Package: " + previewInfo.packageName, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(8f); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Close", new GUILayoutOption[0])) + { + Analytics.Track(string.Format("/AssetStore/DeclinedAbort/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_Asset = null; + base.Close(); + } + GUILayout.Space(5f); + if (GUILayout.Button("Put to basket", new GUILayoutOption[0])) + { + AssetStore.Open(string.Format("content/{0}/basketpurchase", this.m_Asset.packageID)); + Analytics.Track(string.Format("/AssetStore/DeclinedPutToBasket/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + this.m_Asset = null; + base.Close(); + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + } + private void CompletePurchase() + { + this.m_Message = string.Empty; + string password = this.m_Password; + this.m_Password = string.Empty; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.InProgress; + AssetStoreClient.DirectPurchase(this.m_Asset.packageID, password, delegate(PurchaseResult result) + { + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Init; + if (result.error != null) + { + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Declined; + this.m_Message = "An error occured while completing you purhase."; + base.Close(); + } + string text = null; + switch (result.status) + { + case PurchaseResult.Status.BasketNotEmpty: + this.m_Message = "Something else has been put in our Asset Store basket while doing this purchase."; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Declined; + break; + case PurchaseResult.Status.ServiceDisabled: + this.m_Message = "Single click purchase has been disabled while doing this purchase."; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Declined; + break; + case PurchaseResult.Status.AnonymousUser: + this.m_Message = "You have been logged out from somewhere else while doing this purchase."; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Declined; + break; + case PurchaseResult.Status.PasswordMissing: + this.m_Message = result.message; + base.Repaint(); + break; + case PurchaseResult.Status.PasswordWrong: + this.m_Message = result.message; + base.Repaint(); + break; + case PurchaseResult.Status.PurchaseDeclined: + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Declined; + if (result.message != null) + { + this.m_Message = result.message; + } + base.Repaint(); + break; + case PurchaseResult.Status.Ok: + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Complete; + if (result.message != null) + { + this.m_Message = result.message; + } + base.Repaint(); + break; + } + if (text != null) + { + EditorUtility.DisplayDialog("Purchase failed", text + " This purchase has been cancelled.", "Add this item to basket", "Cancel"); + } + }); + Analytics.Track(string.Format("/AssetStore/InstaBuy/{0}/{1}", this.m_Asset.packageID, this.m_Asset.id)); + } + private void BuildPackage() + { + AssetStoreAsset.PreviewInfo previewInfo = this.m_Asset.previewInfo; + if (previewInfo == null) + { + return; + } + if (this.m_BuildAttempts++ > 150) + { + EditorUtility.DisplayDialog("Building timed out", "Timed out during building of package", "Close"); + base.Close(); + return; + } + previewInfo.downloadProgress = -1f; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Building; + AssetStoreClient.BuildPackage(this.m_Asset, delegate(BuildPackageResult result) + { + if (this == null) + { + return; + } + if (result.error != null) + { + Debug.Log(result.error); + if (EditorUtility.DisplayDialog("Error building package", "The server was unable to build the package. Please re-import.", "Ok")) + { + base.Close(); + } + return; + } + if (this.m_Asset == null || this.m_Purchasing != AssetStoreInstaBuyWindow.PurchaseStatus.Building || result.packageID != this.m_Asset.packageID) + { + base.Close(); + } + string packageUrl = result.asset.previewInfo.packageUrl; + if (packageUrl != null && packageUrl != string.Empty) + { + this.DownloadPackage(); + } + else + { + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.StartBuild; + } + base.Repaint(); + }); + } + private void DownloadPackage() + { + AssetStoreAsset.PreviewInfo item = this.m_Asset.previewInfo; + this.m_Purchasing = AssetStoreInstaBuyWindow.PurchaseStatus.Downloading; + item.downloadProgress = 0f; + item.buildProgress = -1f; + AssetStoreContext.Download(this.m_Asset.packageID.ToString(), item.packageUrl, item.encryptionKey, item.packageName, item.publisherName, item.categoryName, delegate(string id, string status, int bytes, int total) + { + if (this == null) + { + return; + } + item.downloadProgress = -1f; + if (status != "ok") + { + Debug.LogError(string.Format("Error downloading package {0} ({1})", item.packageName, id)); + Debug.LogError(status); + this.Close(); + return; + } + if (this.m_Asset == null || this.m_Purchasing != AssetStoreInstaBuyWindow.PurchaseStatus.Downloading || id != this.m_Asset.packageID.ToString()) + { + this.Close(); + } + if (!AssetStoreContext.OpenPackageInternal(id)) + { + Debug.LogError(string.Format("Error importing package {0} ({1})", item.packageName, id)); + } + this.Close(); + }); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreLoginWindow.cs b/UnityEditor/UnityEditor/AssetStoreLoginWindow.cs new file mode 100644 index 00000000..b0811e33 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreLoginWindow.cs @@ -0,0 +1,213 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetStoreLoginWindow : EditorWindow + { + private class Styles + { + public GUIStyle link = new GUIStyle(EditorStyles.miniLabel); + public Styles() + { + this.link.normal.textColor = new Color(0.26f, 0.51f, 0.75f, 1f); + } + } + public delegate void LoginCallback(string errorMessage); + private const float kBaseHeight = 110f; + private static AssetStoreLoginWindow.Styles styles; + private static GUIContent s_AssetStoreLogo; + private string m_LoginReason; + private string m_LoginRemoteMessage; + private string m_Username = string.Empty; + private string m_Password = string.Empty; + private AssetStoreLoginWindow.LoginCallback m_LoginCallback; + public static bool IsLoggedIn + { + get + { + return AssetStoreClient.HasActiveSessionID; + } + } + public static void Login(string loginReason, AssetStoreLoginWindow.LoginCallback callback) + { + if (AssetStoreClient.HasActiveSessionID) + { + AssetStoreClient.Logout(); + } + if (!AssetStoreClient.RememberSession || !AssetStoreClient.HasSavedSessionID) + { + AssetStoreLoginWindow.ShowAssetStoreLoginWindow(loginReason, callback); + return; + } + AssetStoreClient.LoginWithRememberedSession(delegate(string errorMessage) + { + if (string.IsNullOrEmpty(errorMessage)) + { + callback(errorMessage); + } + else + { + AssetStoreLoginWindow.ShowAssetStoreLoginWindow(loginReason, callback); + } + }); + } + public static void Logout() + { + AssetStoreClient.Logout(); + } + public static void ShowAssetStoreLoginWindow(string loginReason, AssetStoreLoginWindow.LoginCallback callback) + { + AssetStoreLoginWindow windowWithRect = EditorWindow.GetWindowWithRect(new Rect(100f, 100f, 360f, 140f), true, "Login to Asset Store"); + windowWithRect.position = new Rect(100f, 100f, windowWithRect.position.width, windowWithRect.position.height); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + windowWithRect.m_Password = string.Empty; + windowWithRect.m_LoginCallback = callback; + windowWithRect.m_LoginReason = loginReason; + windowWithRect.m_LoginRemoteMessage = null; + Analytics.Track("/AssetStore/Login"); + } + private static void LoadLogos() + { + if (AssetStoreLoginWindow.s_AssetStoreLogo != null) + { + return; + } + AssetStoreLoginWindow.s_AssetStoreLogo = new GUIContent(string.Empty); + } + public void OnDisable() + { + if (this.m_LoginCallback != null) + { + this.m_LoginCallback(this.m_LoginRemoteMessage); + } + this.m_LoginCallback = null; + this.m_Password = null; + } + public void OnGUI() + { + if (AssetStoreLoginWindow.styles == null) + { + AssetStoreLoginWindow.styles = new AssetStoreLoginWindow.Styles(); + } + AssetStoreLoginWindow.LoadLogos(); + if (AssetStoreClient.LoginInProgress() || AssetStoreClient.LoggedIn()) + { + GUI.enabled = false; + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.Label(AssetStoreLoginWindow.s_AssetStoreLogo, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(6f); + GUILayout.Label(this.m_LoginReason, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + Rect lastRect = GUILayoutUtility.GetLastRect(); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(6f); + Rect lastRect2 = new Rect(0f, 0f, 0f, 0f); + if (this.m_LoginRemoteMessage != null) + { + Color color = GUI.color; + GUI.color = Color.red; + GUILayout.Label(this.m_LoginRemoteMessage, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUI.color = color; + lastRect2 = GUILayoutUtility.GetLastRect(); + } + float num = lastRect.height + lastRect2.height + 110f; + if (Event.current.type == EventType.Repaint && num != base.position.height) + { + base.position = new Rect(base.position.x, base.position.y, base.position.width, num); + base.Repaint(); + } + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.SetNextControlName("username"); + this.m_Username = EditorGUILayout.TextField("Username", this.m_Username, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_Password = EditorGUILayout.PasswordField("Password", this.m_Password, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (GUILayout.Button(new GUIContent("Forgot?", "Reset your password"), AssetStoreLoginWindow.styles.link, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + Application.OpenURL("https://accounts.unity3d.com/password/new"); + } + EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); + GUILayout.EndHorizontal(); + bool rememberSession = AssetStoreClient.RememberSession; + bool flag = EditorGUILayout.Toggle("Remember me", rememberSession, new GUILayoutOption[0]); + if (flag != rememberSession) + { + AssetStoreClient.RememberSession = flag; + } + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(8f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Create account", new GUILayoutOption[0])) + { + AssetStore.Open("createuser/"); + this.m_LoginRemoteMessage = "Cancelled - create user"; + base.Close(); + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Cancel", new GUILayoutOption[0])) + { + this.m_LoginRemoteMessage = "Cancelled"; + base.Close(); + } + GUILayout.Space(5f); + if (GUILayout.Button("Login", new GUILayoutOption[0])) + { + this.DoLogin(); + base.Repaint(); + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + GUILayout.EndVertical(); + if (Event.current.Equals(Event.KeyboardEvent("return"))) + { + this.DoLogin(); + base.Repaint(); + } + if (this.m_Username == string.Empty) + { + EditorGUI.FocusTextInControl("username"); + } + } + private void DoLogin() + { + this.m_LoginRemoteMessage = null; + if (AssetStoreClient.HasActiveSessionID) + { + AssetStoreClient.Logout(); + } + AssetStoreClient.LoginWithCredentials(this.m_Username, this.m_Password, AssetStoreClient.RememberSession, delegate(string errorMessage) + { + this.m_LoginRemoteMessage = errorMessage; + if (errorMessage == null) + { + base.Close(); + } + else + { + base.Repaint(); + } + }); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStorePreviewManager.cs b/UnityEditor/UnityEditor/AssetStorePreviewManager.cs new file mode 100644 index 00000000..0be8fff4 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStorePreviewManager.cs @@ -0,0 +1,345 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class AssetStorePreviewManager + { + public class CachedAssetStoreImage + { + private const double kFadeTime = 0.5; + public Texture2D image; + public double lastUsed; + public double lastFetched; + public int requestedWidth; + public string label; + internal AsyncHTTPClient client; + public Color color + { + get + { + return Color.Lerp(new Color(1f, 1f, 1f, 0f), new Color(1f, 1f, 1f, 1f), Mathf.Min(1f, (float)((EditorApplication.timeSinceStartup - this.lastFetched) / 0.5))); + } + } + } + private const double kQueryDelay = 0.2; + private const int kMaxConcurrentDownloads = 15; + private const int kMaxConvertionsPerTick = 1; + private static AssetStorePreviewManager s_SharedAssetStorePreviewManager; + private static RenderTexture s_RenderTexture; + private Dictionary m_CachedAssetStoreImages; + private int m_MaxCachedAssetStoreImages = 10; + private int m_Aborted; + private int m_Success; + internal int Requested; + internal int CacheHit; + private int m_CacheRemove; + private int m_ConvertedThisTick; + private AssetStorePreviewManager.CachedAssetStoreImage m_DummyItem = new AssetStorePreviewManager.CachedAssetStoreImage(); + private PreviewRenderUtility m_PreviewUtility; + private static bool s_NeedsRepaint; + internal static AssetStorePreviewManager Instance + { + get + { + if (AssetStorePreviewManager.s_SharedAssetStorePreviewManager == null) + { + AssetStorePreviewManager.s_SharedAssetStorePreviewManager = new AssetStorePreviewManager(); + AssetStorePreviewManager.s_SharedAssetStorePreviewManager.m_DummyItem.lastUsed = -1.0; + } + return AssetStorePreviewManager.s_SharedAssetStorePreviewManager; + } + } + private static Dictionary CachedAssetStoreImages + { + get + { + if (AssetStorePreviewManager.Instance.m_CachedAssetStoreImages == null) + { + AssetStorePreviewManager.Instance.m_CachedAssetStoreImages = new Dictionary(); + } + return AssetStorePreviewManager.Instance.m_CachedAssetStoreImages; + } + } + public static int MaxCachedImages + { + get + { + return AssetStorePreviewManager.Instance.m_MaxCachedAssetStoreImages; + } + set + { + AssetStorePreviewManager.Instance.m_MaxCachedAssetStoreImages = value; + } + } + public static bool CacheFull + { + get + { + return AssetStorePreviewManager.CachedAssetStoreImages.Count >= AssetStorePreviewManager.MaxCachedImages; + } + } + public static int Downloading + { + get + { + int num = 0; + foreach (KeyValuePair current in AssetStorePreviewManager.CachedAssetStoreImages) + { + if (current.Value.client != null) + { + num++; + } + } + return num; + } + } + private AssetStorePreviewManager() + { + } + public static string StatsString() + { + return string.Format("Reqs: {0}, Ok: {1}, Abort: {2}, CacheDel: {3}, Cache: {4}/{5}, CacheHit: {6}", new object[] + { + AssetStorePreviewManager.Instance.Requested, + AssetStorePreviewManager.Instance.m_Success, + AssetStorePreviewManager.Instance.m_Aborted, + AssetStorePreviewManager.Instance.m_CacheRemove, + AssetStorePreviewManager.CachedAssetStoreImages.Count, + AssetStorePreviewManager.Instance.m_MaxCachedAssetStoreImages, + AssetStorePreviewManager.Instance.CacheHit + }); + } + public static AssetStorePreviewManager.CachedAssetStoreImage TextureFromUrl(string url, string label, int textureSize, GUIStyle labelStyle, GUIStyle iconStyle, bool onlyCached) + { + if (string.IsNullOrEmpty(url)) + { + return AssetStorePreviewManager.Instance.m_DummyItem; + } + bool flag = true; + AssetStorePreviewManager.CachedAssetStoreImage cachedAssetStoreImage; + if (AssetStorePreviewManager.CachedAssetStoreImages.TryGetValue(url, out cachedAssetStoreImage)) + { + cachedAssetStoreImage.lastUsed = EditorApplication.timeSinceStartup; + bool flag2 = cachedAssetStoreImage.requestedWidth == textureSize; + bool flag3 = cachedAssetStoreImage.image != null && cachedAssetStoreImage.image.width == textureSize; + bool flag4 = cachedAssetStoreImage.requestedWidth == -1; + if ((flag3 || flag2 || onlyCached) && !flag4) + { + AssetStorePreviewManager.Instance.CacheHit++; + bool flag5 = cachedAssetStoreImage.client != null; + bool flag6 = cachedAssetStoreImage.label == null; + bool flag7 = flag5 || flag6; + bool flag8 = AssetStorePreviewManager.Instance.m_ConvertedThisTick > 1; + AssetStorePreviewManager.s_NeedsRepaint = (AssetStorePreviewManager.s_NeedsRepaint || flag8); + return (!flag7 && !flag8) ? AssetStorePreviewManager.RenderEntry(cachedAssetStoreImage, labelStyle, iconStyle) : cachedAssetStoreImage; + } + flag = false; + if (AssetStorePreviewManager.Downloading >= 15) + { + return (!(cachedAssetStoreImage.image == null)) ? cachedAssetStoreImage : AssetStorePreviewManager.Instance.m_DummyItem; + } + } + else + { + if (onlyCached || AssetStorePreviewManager.Downloading >= 15) + { + return AssetStorePreviewManager.Instance.m_DummyItem; + } + cachedAssetStoreImage = new AssetStorePreviewManager.CachedAssetStoreImage(); + cachedAssetStoreImage.image = null; + cachedAssetStoreImage.lastUsed = EditorApplication.timeSinceStartup; + } + if (cachedAssetStoreImage.image == null) + { + cachedAssetStoreImage.lastFetched = EditorApplication.timeSinceStartup; + } + cachedAssetStoreImage.requestedWidth = textureSize; + cachedAssetStoreImage.label = label; + AsyncHTTPClient asyncHTTPClient = AssetStorePreviewManager.SetupTextureDownload(cachedAssetStoreImage, url, "previewSize-" + textureSize); + AssetStorePreviewManager.ExpireCacheEntries(); + if (flag) + { + AssetStorePreviewManager.CachedAssetStoreImages.Add(url, cachedAssetStoreImage); + } + asyncHTTPClient.Begin(); + AssetStorePreviewManager.Instance.Requested++; + return cachedAssetStoreImage; + } + private static AsyncHTTPClient SetupTextureDownload(AssetStorePreviewManager.CachedAssetStoreImage cached, string url, string tag) + { + AsyncHTTPClient client = new AsyncHTTPClient(url); + cached.client = client; + client.tag = tag; + client.doneCallback = delegate(AsyncHTTPClient c) + { + cached.client = null; + if (!client.IsSuccess()) + { + if (client.state != AsyncHTTPClient.State.ABORTED) + { + string text = string.Concat(new string[] + { + "error ", + client.text, + " ", + client.state.ToString(), + " '", + url, + "'" + }); + if (ObjectListArea.s_Debug) + { + Debug.LogError(text); + } + else + { + Console.Write(text); + } + } + else + { + AssetStorePreviewManager.Instance.m_Aborted++; + } + return; + } + if (cached.image != null) + { + UnityEngine.Object.DestroyImmediate(cached.image); + } + cached.image = c.texture; + AssetStorePreviewManager.s_NeedsRepaint = true; + AssetStorePreviewManager.Instance.m_Success++; + }; + return client; + } + private static void ExpireCacheEntries() + { + while (AssetStorePreviewManager.CacheFull) + { + string key = null; + AssetStorePreviewManager.CachedAssetStoreImage cachedAssetStoreImage = null; + foreach (KeyValuePair current in AssetStorePreviewManager.CachedAssetStoreImages) + { + if (cachedAssetStoreImage == null || cachedAssetStoreImage.lastUsed > current.Value.lastUsed) + { + cachedAssetStoreImage = current.Value; + key = current.Key; + } + } + AssetStorePreviewManager.CachedAssetStoreImages.Remove(key); + AssetStorePreviewManager.Instance.m_CacheRemove++; + if (cachedAssetStoreImage == null) + { + Debug.LogError("Null entry found while removing cache entry"); + break; + } + if (cachedAssetStoreImage.client != null) + { + cachedAssetStoreImage.client.Abort(); + cachedAssetStoreImage.client = null; + } + if (cachedAssetStoreImage.image != null) + { + UnityEngine.Object.DestroyImmediate(cachedAssetStoreImage.image); + } + } + } + private static AssetStorePreviewManager.CachedAssetStoreImage RenderEntry(AssetStorePreviewManager.CachedAssetStoreImage cached, GUIStyle labelStyle, GUIStyle iconStyle) + { + if (cached.label == null || cached.image == null) + { + return cached; + } + Texture2D image = cached.image; + cached.image = new Texture2D(cached.requestedWidth, cached.requestedWidth, TextureFormat.RGB24, false, true); + AssetStorePreviewManager.ScaleImage(cached.requestedWidth, cached.requestedWidth, image, cached.image, iconStyle); + UnityEngine.Object.DestroyImmediate(image); + cached.label = null; + AssetStorePreviewManager.Instance.m_ConvertedThisTick++; + return cached; + } + internal static void ScaleImage(int w, int h, Texture2D inimage, Texture2D outimage, GUIStyle bgStyle) + { + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState(); + if (AssetStorePreviewManager.s_RenderTexture != null && (AssetStorePreviewManager.s_RenderTexture.width != w || AssetStorePreviewManager.s_RenderTexture.height != h)) + { + UnityEngine.Object.DestroyImmediate(AssetStorePreviewManager.s_RenderTexture); + AssetStorePreviewManager.s_RenderTexture = null; + } + if (AssetStorePreviewManager.s_RenderTexture == null) + { + AssetStorePreviewManager.s_RenderTexture = RenderTexture.GetTemporary(w, h, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + AssetStorePreviewManager.s_RenderTexture.hideFlags = HideFlags.HideAndDontSave; + } + RenderTexture renderTexture = AssetStorePreviewManager.s_RenderTexture; + RenderTexture.active = renderTexture; + Rect rect = new Rect(0f, 0f, (float)w, (float)h); + EditorGUIUtility.SetRenderTextureNoViewport(renderTexture); + GL.LoadOrtho(); + GL.LoadPixelMatrix(0f, (float)w, (float)h, 0f); + ShaderUtil.rawViewportRect = new Rect(0f, 0f, (float)w, (float)h); + ShaderUtil.rawScissorRect = new Rect(0f, 0f, (float)w, (float)h); + GL.Clear(true, true, new Color(0f, 0f, 0f, 0f)); + Rect screenRect = rect; + if (inimage.width > inimage.height) + { + float num = screenRect.height * ((float)inimage.height / (float)inimage.width); + screenRect.height = (float)((int)num); + screenRect.y += (float)((int)(num * 0.5f)); + } + else + { + if (inimage.width < inimage.height) + { + float num2 = screenRect.width * ((float)inimage.width / (float)inimage.height); + screenRect.width = (float)((int)num2); + screenRect.x += (float)((int)(num2 * 0.5f)); + } + } + if (bgStyle != null && bgStyle.normal != null && bgStyle.normal.background != null) + { + Graphics.DrawTexture(rect, bgStyle.normal.background); + } + Graphics.DrawTexture(screenRect, inimage); + outimage.ReadPixels(rect, 0, 0, false); + outimage.Apply(); + outimage.hideFlags = HideFlags.HideAndDontSave; + savedRenderTargetState.Restore(); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + } + public static bool CheckRepaint() + { + bool result = AssetStorePreviewManager.s_NeedsRepaint; + AssetStorePreviewManager.s_NeedsRepaint = false; + return result; + } + public static void AbortSize(int size) + { + AsyncHTTPClient.AbortByTag("previewSize-" + size.ToString()); + foreach (KeyValuePair current in AssetStorePreviewManager.CachedAssetStoreImages) + { + if (current.Value.requestedWidth == size) + { + current.Value.requestedWidth = -1; + current.Value.client = null; + } + } + } + public static void AbortOlderThan(double timestamp) + { + foreach (KeyValuePair current in AssetStorePreviewManager.CachedAssetStoreImages) + { + AssetStorePreviewManager.CachedAssetStoreImage value = current.Value; + if (value.lastUsed < timestamp && value.client != null) + { + value.requestedWidth = -1; + value.client.Abort(); + value.client = null; + } + } + AssetStorePreviewManager.Instance.m_ConvertedThisTick = 0; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreResponse.cs b/UnityEditor/UnityEditor/AssetStoreResponse.cs new file mode 100644 index 00000000..d030d00f --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreResponse.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AssetStoreResponse + { + internal AsyncHTTPClient job; + public Dictionary dict; + public bool ok; + public bool failed + { + get + { + return !this.ok; + } + } + public string message + { + get + { + if (this.dict == null || !this.dict.ContainsKey("message")) + { + return null; + } + return this.dict["message"].AsString(true); + } + } + private static string EncodeString(string str) + { + str = str.Replace("\"", "\\\""); + str = str.Replace("\\", "\\\\"); + str = str.Replace("\b", "\\b"); + str = str.Replace("\f", "\\f"); + str = str.Replace("\n", "\\n"); + str = str.Replace("\r", "\\r"); + str = str.Replace("\t", "\\t"); + return str; + } + public override string ToString() + { + string text = "{"; + string text2 = string.Empty; + foreach (KeyValuePair current in this.dict) + { + string text3 = text; + text = string.Concat(new object[] + { + text3, + text2, + '"', + AssetStoreResponse.EncodeString(current.Key), + "\" : ", + current.Value.ToString() + }); + text2 = ", "; + } + return text + "}"; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreResultBase.cs b/UnityEditor/UnityEditor/AssetStoreResultBase.cs new file mode 100644 index 00000000..b97bfe8e --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreResultBase.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal abstract class AssetStoreResultBase where Derived : class + { + public delegate void Callback(Derived res); + private AssetStoreResultBase.Callback callback; + public string error; + public string warnings; + public AssetStoreResultBase(AssetStoreResultBase.Callback cb) + { + this.callback = cb; + this.warnings = string.Empty; + } + public void Parse(AssetStoreResponse response) + { + if (response.job.IsSuccess()) + { + if (response.job.responseCode >= 300) + { + this.error = string.Format("HTTP status code {0}", response.job.responseCode); + } + else + { + if (response.dict.ContainsKey("error")) + { + this.error = response.dict["error"].AsString(true); + } + else + { + this.Parse(response.dict); + } + } + } + else + { + string str = (response.job != null) ? ((response.job.url != null) ? response.job.url : "null") : "nulljob"; + this.error = "Error receiving response from server on url '" + str + "': " + (response.job.text ?? "n/a"); + } + this.callback(this as Derived); + } + protected abstract void Parse(Dictionary dict); + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreSearchResults.cs b/UnityEditor/UnityEditor/AssetStoreSearchResults.cs new file mode 100644 index 00000000..f03ac8b5 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreSearchResults.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AssetStoreSearchResults : AssetStoreResultBase + { + internal struct Group + { + public List assets; + public int totalFound; + public string label; + public string name; + public int offset; + public int limit; + public static AssetStoreSearchResults.Group Create() + { + return new AssetStoreSearchResults.Group + { + assets = new List(), + label = string.Empty, + name = string.Empty, + offset = 0, + limit = -1 + }; + } + } + internal List groups = new List(); + public AssetStoreSearchResults(AssetStoreResultBase.Callback c) : base(c) + { + } + protected override void Parse(Dictionary dict) + { + foreach (JSONValue current in dict["groups"].AsList(true)) + { + AssetStoreSearchResults.Group item = AssetStoreSearchResults.Group.Create(); + this.ParseList(current, ref item); + this.groups.Add(item); + } + JSONValue jSONValue = dict["query"]["offsets"]; + List list = dict["query"]["limits"].AsList(true); + int num = 0; + foreach (JSONValue current2 in jSONValue.AsList(true)) + { + AssetStoreSearchResults.Group value = this.groups[num]; + value.offset = (int)current2.AsFloat(true); + value.limit = (int)list[num].AsFloat(true); + this.groups[num] = value; + num++; + } + } + private static string StripExtension(string path) + { + if (path == null) + { + return null; + } + int num = path.LastIndexOf("."); + return (num >= 0) ? path.Substring(0, num) : path; + } + private void ParseList(JSONValue matches, ref AssetStoreSearchResults.Group group) + { + List assets = group.assets; + if (matches.ContainsKey("error")) + { + this.error = matches["error"].AsString(true); + } + if (matches.ContainsKey("warnings")) + { + this.warnings = matches["warnings"].AsString(true); + } + if (matches.ContainsKey("name")) + { + group.name = matches["name"].AsString(true); + } + if (matches.ContainsKey("label")) + { + group.label = matches["label"].AsString(true); + } + group.label = (group.label ?? group.name); + if (matches.ContainsKey("total_found")) + { + group.totalFound = (int)matches["total_found"].AsFloat(true); + } + if (matches.ContainsKey("matches")) + { + foreach (JSONValue current in matches["matches"].AsList(true)) + { + AssetStoreAsset assetStoreAsset = new AssetStoreAsset(); + if (current.ContainsKey("id") && current.ContainsKey("name") && current.ContainsKey("package_id")) + { + assetStoreAsset.id = (int)current["id"].AsFloat(); + assetStoreAsset.name = current["name"].AsString(); + assetStoreAsset.displayName = AssetStoreSearchResults.StripExtension(assetStoreAsset.name); + assetStoreAsset.packageID = (int)current["package_id"].AsFloat(); + if (current.ContainsKey("static_preview_url")) + { + assetStoreAsset.staticPreviewURL = current["static_preview_url"].AsString(); + } + if (current.ContainsKey("dynamic_preview_url")) + { + assetStoreAsset.dynamicPreviewURL = current["dynamic_preview_url"].AsString(); + } + assetStoreAsset.className = ((!current.ContainsKey("class_name")) ? string.Empty : current["class_name"].AsString()); + if (current.ContainsKey("price")) + { + assetStoreAsset.price = current["price"].AsString(); + } + assets.Add(assetStoreAsset); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreUtils.cs b/UnityEditor/UnityEditor/AssetStoreUtils.cs new file mode 100644 index 00000000..f2ad88a6 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreUtils.cs @@ -0,0 +1,91 @@ +using System; +using System.Globalization; +using System.IO; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + internal sealed class AssetStoreUtils + { + public delegate void DownloadDoneCallback(string package_id, string message, int bytes, int total); + private const string kAssetStoreUrl = "https://shawarma.unity3d.com"; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Download(string id, string url, string[] destination, string key, string jsonData, bool resumeOK, [DefaultValue("null")] AssetStoreUtils.DownloadDoneCallback doneCallback); + [ExcludeFromDocs] + public static void Download(string id, string url, string[] destination, string key, string jsonData, bool resumeOK) + { + AssetStoreUtils.DownloadDoneCallback doneCallback = null; + AssetStoreUtils.Download(id, url, destination, key, jsonData, resumeOK, doneCallback); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CheckDownload(string id, string url, string[] destination, string key); + private static void HexStringToByteArray(string hex, byte[] array, int offset) + { + if (offset + array.Length * 2 > hex.Length) + { + throw new ArgumentException("Hex string too short"); + } + for (int i = 0; i < array.Length; i++) + { + string s = hex.Substring(i * 2 + offset, 2); + array[i] = byte.Parse(s, NumberStyles.HexNumber); + } + } + public static void DecryptFile(string inputFile, string outputFile, string keyIV) + { + byte[] array = new byte[32]; + byte[] array2 = new byte[16]; + AssetStoreUtils.HexStringToByteArray(keyIV, array, 0); + AssetStoreUtils.HexStringToByteArray(keyIV, array2, 64); + FileStream fileStream = File.Open(inputFile, FileMode.Open); + FileStream fileStream2 = File.Open(outputFile, FileMode.CreateNew); + AesManaged aesManaged = new AesManaged(); + aesManaged.Key = array; + aesManaged.IV = array2; + CryptoStream cryptoStream = new CryptoStream(fileStream, aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV), CryptoStreamMode.Read); + try + { + byte[] array3 = new byte[40960]; + int count; + while ((count = cryptoStream.Read(array3, 0, array3.Length)) > 0) + { + fileStream2.Write(array3, 0, count); + } + } + finally + { + cryptoStream.Close(); + fileStream.Close(); + fileStream2.Close(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterDownloadDelegate(ScriptableObject d); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnRegisterDownloadDelegate(ScriptableObject d); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetLoaderPath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UpdatePreloading(); + public static string GetOfflinePath() + { + return EditorApplication.applicationContentsPath + "/Resources/offline.html"; + } + public static string GetAssetStoreUrl() + { + return "https://shawarma.unity3d.com"; + } + public static string GetAssetStoreSearchUrl() + { + return AssetStoreUtils.GetAssetStoreUrl().Replace("https", "http"); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetStoreWindow.cs b/UnityEditor/UnityEditor/AssetStoreWindow.cs new file mode 100644 index 00000000..341fa3cc --- /dev/null +++ b/UnityEditor/UnityEditor/AssetStoreWindow.cs @@ -0,0 +1,240 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetStoreWindow : EditorWindow, IHasCustomMenu + { + private WebView webView; + private AssetStoreContext contextScriptObject; + private bool isProSkin; + private bool isDocked; + private bool isOffline; + private MouseCursor m_SavedCursor; + private int m_SavedCursorCountHack; + private Vector2 minUndockedSize; + private Vector2 minDockedSize; + internal WebScriptObject scriptObject + { + get + { + return this.webView.windowScriptObject; + } + } + private AssetStoreWindow() + { + Resolution currentResolution = Screen.currentResolution; + int num = (currentResolution.width < 1024) ? currentResolution.width : 1024; + int num2 = (currentResolution.height < 896) ? (currentResolution.height - 96) : 800; + int num3 = (currentResolution.width - num) / 2; + int num4 = (currentResolution.height - num2) / 2; + base.position = new Rect((float)num3, (float)num4, (float)num, (float)num2); + } + public static void OpenURL(string url) + { + AssetStoreWindow assetStoreWindow = AssetStoreWindow.Init(); + assetStoreWindow.InvokeJSMethod("document.AssetStore", "openURL", new object[] + { + url + }); + assetStoreWindow.CreateContextObject(); + assetStoreWindow.contextScriptObject.initialOpenURL = url; + } + public static AssetStoreWindow Init() + { + AssetStoreWindow window = EditorWindow.GetWindow(); + Resolution currentResolution = Screen.currentResolution; + int num = (currentResolution.width < 1024) ? currentResolution.width : 1024; + int num2 = (currentResolution.height < 896) ? (currentResolution.height - 96) : 800; + window.minUndockedSize = new Vector2((float)num, (float)num2); + window.minDockedSize = new Vector2(512f, 256f); + window.minSize = ((!window.docked) ? window.minUndockedSize : window.minDockedSize); + window.maxSize = new Vector2(2048f, 2048f); + window.Show(); + window.m_SavedCursor = MouseCursor.Arrow; + return window; + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Reload"), false, new GenericMenu.MenuFunction(this.Reload)); + } + public void Logout() + { + this.InvokeJSMethod("document.AssetStore.login", "logout", new object[0]); + } + public void Reload() + { + if (this.isOffline) + { + this.InitWebView(); + } + else + { + this.isProSkin = EditorGUIUtility.isProSkin; + this.isDocked = base.docked; + this.InvokeJSMethod("location", "reload", new object[] + { + true + }); + } + } + private void CreateContextObject() + { + if (this.contextScriptObject == null) + { + this.contextScriptObject = ScriptableObject.CreateInstance(); + this.contextScriptObject.hideFlags = HideFlags.HideAndDontSave; + this.contextScriptObject.window = this; + } + } + private void SetContextObject() + { + this.CreateContextObject(); + this.contextScriptObject.docked = base.docked; + this.webView.windowScriptObject.Set("context", this.contextScriptObject); + } + private void InitWebView() + { + this.isProSkin = EditorGUIUtility.isProSkin; + this.isDocked = base.docked; + this.isOffline = false; + if (!this.webView) + { + this.webView = ScriptableObject.CreateInstance(); + this.webView.InitWebView((int)base.position.width, (int)base.position.height, false); + this.webView.hideFlags = HideFlags.HideAndDontSave; + this.webView.LoadFile(AssetStoreUtils.GetLoaderPath()); + } + else + { + this.webView.LoadFile(AssetStoreUtils.GetLoaderPath()); + } + this.webView.SetDelegateObject(this); + base.wantsMouseMove = true; + } + private void OnLoadError(string frameName) + { + if (!this.webView) + { + return; + } + if (this.isOffline) + { + Debug.LogError("Unexpected error: Failed to load offline Asset Store page"); + return; + } + this.isOffline = true; + this.webView.LoadFile(AssetStoreUtils.GetOfflinePath()); + } + private void OnEnable() + { + AssetStoreUtils.RegisterDownloadDelegate(this); + } + public void OnDisable() + { + AssetStoreUtils.UnRegisterDownloadDelegate(this); + } + private void InvokeJSMethod(string objectName, string name, params object[] args) + { + if (!this.webView) + { + return; + } + WebScriptObject webScriptObject = this.webView.windowScriptObject.Get(objectName); + if (webScriptObject == null) + { + return; + } + webScriptObject.InvokeMethodArray(name, args); + } + private void OnGUI() + { + if (!this.webView) + { + this.InitWebView(); + } + EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, base.position.width, base.position.height), this.m_SavedCursor); + if (Event.current.type == EventType.Layout) + { + if (this.webView && this.isProSkin != EditorGUIUtility.isProSkin) + { + this.isProSkin = EditorGUIUtility.isProSkin; + this.InvokeJSMethod("document.AssetStore", "refreshSkinIndex", new object[0]); + base.Repaint(); + } + this.UpdateDockStatusIfNeeded(); + } + this.webView.DoGUI(new Rect(0f, 0f, base.position.width, base.position.height)); + } + private void UpdateDockStatusIfNeeded() + { + if (this.isDocked != base.docked) + { + base.minSize = ((!base.docked) ? this.minUndockedSize : this.minDockedSize); + this.isDocked = base.docked; + if (this.contextScriptObject != null) + { + this.contextScriptObject.docked = base.docked; + this.InvokeJSMethod("document.AssetStore", "updateDockStatus", new object[0]); + } + base.Repaint(); + } + } + private void OnReceiveTitle(string iTitle, string frameName) + { + base.title = iTitle; + this.SetContextObject(); + } + private void OnFocus() + { + if (this.webView) + { + this.webView.Focus(); + } + } + private void OnLostFocus() + { + if (this.webView) + { + this.webView.UnFocus(); + } + } + public void OnDestroy() + { + UnityEngine.Object.DestroyImmediate(this.webView); + if (this.contextScriptObject != null) + { + this.contextScriptObject.window = null; + } + } + public void OnDownloadProgress(string id, string message, int bytes, int total) + { + this.InvokeJSMethod("document.AssetStore.pkgs", "OnDownloadProgress", new object[] + { + id, + message, + bytes, + total + }); + } + private void OnWebViewDirty() + { + base.Repaint(); + } + private void SetCursor(int cursor) + { + if (cursor != (int)this.m_SavedCursor) + { + if (cursor != 0 || this.m_SavedCursorCountHack-- <= 0) + { + this.m_SavedCursorCountHack = 1; + this.m_SavedCursor = (MouseCursor)cursor; + base.Repaint(); + } + } + else + { + this.m_SavedCursorCountHack = 1; + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetsItem.cs b/UnityEditor/UnityEditor/AssetsItem.cs new file mode 100644 index 00000000..9ff4ce5c --- /dev/null +++ b/UnityEditor/UnityEditor/AssetsItem.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class AssetsItem + { + public string guid; + public string parentGuid; + public string pathName; + public string message; + public string exportedAssetPath; + public string guidFolder; + public int enabled; + public int assetIsDir; + public int changeFlags; + public string previewPath; + public int exists; + } +} diff --git a/UnityEditor/UnityEditor/AssetsTreeViewDataSource.cs b/UnityEditor/UnityEditor/AssetsTreeViewDataSource.cs new file mode 100644 index 00000000..a16e2489 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetsTreeViewDataSource.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.ProjectWindowCallback; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetsTreeViewDataSource : LazyTreeViewDataSource + { + internal class SemiNumericDisplayNameListComparer : IComparer + { + public int Compare(TreeViewItem x, TreeViewItem y) + { + if (x == y) + { + return 0; + } + if (x == null) + { + return -1; + } + if (y == null) + { + return 1; + } + return EditorUtility.NaturalCompare(x.displayName, y.displayName); + } + } + private class FolderTreeItem : TreeViewItem + { + public FolderTreeItem(int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) + { + } + } + private class NonFolderTreeItem : TreeViewItem + { + public NonFolderTreeItem(int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) + { + } + } + private const HierarchyType k_HierarchyType = HierarchyType.Assets; + private readonly int m_RootInstanceID; + public bool foldersOnly + { + get; + set; + } + public bool foldersFirst + { + get; + set; + } + public AssetsTreeViewDataSource(TreeView treeView, int rootInstanceID, bool showRootNode, bool rootNodeIsCollapsable) : base(treeView) + { + this.m_RootInstanceID = rootInstanceID; + this.showRootNode = showRootNode; + base.rootIsCollapsable = rootNodeIsCollapsable; + } + private static string CreateDisplayName(int instanceID) + { + return Path.GetFileNameWithoutExtension(AssetDatabase.GetAssetPath(instanceID)); + } + public override void FetchData() + { + int depth = 0; + this.m_RootItem = new TreeViewItem(this.m_RootInstanceID, depth, null, AssetsTreeViewDataSource.CreateDisplayName(this.m_RootInstanceID)); + if (!base.showRootNode) + { + this.SetExpanded(this.m_RootItem, true); + } + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.Reset(); + if (!hierarchyProperty.Find(this.m_RootInstanceID, null)) + { + Debug.LogError("Root Asset with id " + this.m_RootInstanceID + " not found!!"); + } + int num = hierarchyProperty.depth + ((!base.showRootNode) ? 1 : 0); + int[] expanded = base.expandedIDs.ToArray(); + Texture2D icon = EditorGUIUtility.FindTexture(EditorResourcesUtility.emptyFolderIconName); + this.m_VisibleRows = new List(); + while (hierarchyProperty.NextWithDepthCheck(expanded, num)) + { + if (!this.foldersOnly || hierarchyProperty.isFolder) + { + depth = hierarchyProperty.depth - num; + TreeViewItem treeViewItem; + if (hierarchyProperty.isFolder) + { + treeViewItem = new AssetsTreeViewDataSource.FolderTreeItem(hierarchyProperty.instanceID, depth, null, hierarchyProperty.name); + } + else + { + treeViewItem = new AssetsTreeViewDataSource.NonFolderTreeItem(hierarchyProperty.instanceID, depth, null, hierarchyProperty.name); + } + if (hierarchyProperty.isFolder && !hierarchyProperty.hasChildren) + { + treeViewItem.icon = icon; + } + else + { + treeViewItem.icon = hierarchyProperty.icon; + } + if (hierarchyProperty.hasChildren) + { + treeViewItem.AddChild(null); + } + this.m_VisibleRows.Add(treeViewItem); + } + } + TreeViewUtility.SetChildParentReferences(this.m_VisibleRows, this.m_RootItem); + if (this.foldersFirst) + { + AssetsTreeViewDataSource.FoldersFirstRecursive(this.m_RootItem); + this.m_VisibleRows.Clear(); + base.GetVisibleItemsRecursive(this.m_RootItem, this.m_VisibleRows); + } + this.m_NeedRefreshVisibleFolders = false; + bool revealSelectionAndFrameLastSelected = false; + this.m_TreeView.SetSelection(Selection.instanceIDs, revealSelectionAndFrameLastSelected); + } + private static void FoldersFirstRecursive(TreeViewItem item) + { + if (!item.hasChildren) + { + return; + } + TreeViewItem[] array = item.children.ToArray(); + for (int i = 0; i < item.children.Count; i++) + { + if (array[i] != null) + { + if (array[i] is AssetsTreeViewDataSource.NonFolderTreeItem) + { + for (int j = i + 1; j < array.Length; j++) + { + if (array[j] is AssetsTreeViewDataSource.FolderTreeItem) + { + TreeViewItem treeViewItem = array[j]; + int length = j - i; + Array.Copy(array, i, array, i + 1, length); + array[i] = treeViewItem; + break; + } + } + } + AssetsTreeViewDataSource.FoldersFirstRecursive(array[i]); + } + } + item.children = new List(array); + } + protected override HashSet GetParentsAbove(int id) + { + HashSet hashSet = new HashSet(); + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(id, null)) + { + while (hierarchyProperty.Parent()) + { + hashSet.Add(hierarchyProperty.instanceID); + } + } + return hashSet; + } + protected override HashSet GetParentsBelow(int id) + { + HashSet hashSet = new HashSet(); + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(id, null)) + { + hashSet.Add(id); + int depth = hierarchyProperty.depth; + while (hierarchyProperty.Next(null) && hierarchyProperty.depth > depth) + { + if (hierarchyProperty.hasChildren) + { + hashSet.Add(hierarchyProperty.instanceID); + } + } + } + return hashSet; + } + public override void OnExpandedStateChanged() + { + InternalEditorUtility.expandedProjectWindowItems = base.expandedIDs.ToArray(); + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + return (!hierarchyProperty.Find(item.id, null) || hierarchyProperty.isMainRepresentation) && item.parent != null; + } + protected CreateAssetUtility GetCreateAssetUtility() + { + return this.m_TreeView.state.createAssetUtility; + } + public int GetInsertAfterItemIDForNewItem(string newName, TreeViewItem parentItem, bool isCreatingNewFolder, bool foldersFirst) + { + if (!parentItem.hasChildren) + { + return parentItem.id; + } + int result = parentItem.id; + for (int i = 0; i < parentItem.children.Count; i++) + { + int id = parentItem.children[i].id; + bool flag = parentItem.children[i] is AssetsTreeViewDataSource.FolderTreeItem; + if (foldersFirst && flag && !isCreatingNewFolder) + { + result = id; + } + else + { + if (foldersFirst && !flag && isCreatingNewFolder) + { + break; + } + string assetPath = AssetDatabase.GetAssetPath(id); + if (EditorUtility.NaturalCompare(Path.GetFileNameWithoutExtension(assetPath), newName) > 0) + { + break; + } + result = id; + } + } + return result; + } + public override void InsertFakeItem(int id, int parentID, string name, Texture2D icon) + { + bool isCreatingNewFolder = this.GetCreateAssetUtility().endAction is DoCreateFolder; + TreeViewItem treeViewItem = this.FindItem(id); + if (treeViewItem != null) + { + Debug.LogError(string.Concat(new object[] + { + "Cannot insert fake Item because id is not unique ", + id, + " Item already there: ", + treeViewItem.displayName + })); + return; + } + if (this.FindItem(parentID) != null) + { + this.SetExpanded(parentID, true); + List visibleRows = this.GetVisibleRows(); + int indexOfID = TreeView.GetIndexOfID(visibleRows, parentID); + TreeViewItem treeViewItem2; + if (indexOfID >= 0) + { + treeViewItem2 = visibleRows[indexOfID]; + } + else + { + treeViewItem2 = this.m_RootItem; + } + int num = treeViewItem2.depth + ((treeViewItem2 != this.m_RootItem) ? 1 : 0); + this.m_FakeItem = new TreeViewItem(id, num, treeViewItem2, name); + this.m_FakeItem.icon = icon; + int insertAfterItemIDForNewItem = this.GetInsertAfterItemIDForNewItem(name, treeViewItem2, isCreatingNewFolder, this.foldersFirst); + int num2 = TreeView.GetIndexOfID(visibleRows, insertAfterItemIDForNewItem); + if (num2 >= 0) + { + while (++num2 < visibleRows.Count) + { + if (visibleRows[num2].depth <= num) + { + break; + } + } + if (num2 < visibleRows.Count) + { + visibleRows.Insert(num2, this.m_FakeItem); + } + else + { + visibleRows.Add(this.m_FakeItem); + } + } + else + { + if (visibleRows.Count > 0) + { + visibleRows.Insert(0, this.m_FakeItem); + } + else + { + visibleRows.Add(this.m_FakeItem); + } + } + this.m_NeedRefreshVisibleFolders = false; + this.m_TreeView.Frame(this.m_FakeItem.id, true, false); + this.m_TreeView.Repaint(); + } + else + { + Debug.LogError("No parent Item found"); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetsTreeViewGUI.cs b/UnityEditor/UnityEditor/AssetsTreeViewGUI.cs new file mode 100644 index 00000000..23bde104 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetsTreeViewGUI.cs @@ -0,0 +1,110 @@ +using System; +using UnityEditor.ProjectWindowCallback; +using UnityEditor.VersionControl; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetsTreeViewGUI : TreeViewGUI + { + private const float k_IconOverlayPadding = 7f; + private static bool s_VCEnabled; + public AssetsTreeViewGUI(TreeView treeView) : base(treeView) + { + base.iconOverlayGUI = (Action)Delegate.Combine(base.iconOverlayGUI, new Action(this.OnIconOverlayGUI)); + this.k_TopRowMargin = 4f; + } + public override void BeginRowGUI() + { + AssetsTreeViewGUI.s_VCEnabled = Provider.isActive; + float num = (!AssetsTreeViewGUI.s_VCEnabled) ? 0f : 7f; + base.iconRightPadding = num; + base.iconLeftPadding = num; + base.BeginRowGUI(); + } + protected CreateAssetUtility GetCreateAssetUtility() + { + return this.m_TreeView.state.createAssetUtility; + } + protected virtual bool IsCreatingNewAsset(int instanceID) + { + return this.GetCreateAssetUtility().IsCreatingNewAsset() && this.IsRenaming(instanceID); + } + protected override void ClearRenameAndNewNodeState() + { + this.GetCreateAssetUtility().Clear(); + base.ClearRenameAndNewNodeState(); + } + protected override void RenameEnded() + { + string name = (!string.IsNullOrEmpty(base.GetRenameOverlay().name)) ? base.GetRenameOverlay().name : base.GetRenameOverlay().originalName; + int userData = base.GetRenameOverlay().userData; + bool flag = this.GetCreateAssetUtility().IsCreatingNewAsset(); + bool userAcceptedRename = base.GetRenameOverlay().userAcceptedRename; + if (userAcceptedRename) + { + if (flag) + { + this.GetCreateAssetUtility().EndNewAssetCreation(name); + } + else + { + ObjectNames.SetNameSmartWithInstanceID(userData, name); + } + } + } + protected override void SyncFakeItem() + { + if (!this.m_TreeView.data.HasFakeItem() && this.GetCreateAssetUtility().IsCreatingNewAsset()) + { + int instanceID = AssetDatabase.LoadAssetAtPath(this.GetCreateAssetUtility().folder, typeof(UnityEngine.Object)).GetInstanceID(); + this.m_TreeView.data.InsertFakeItem(this.GetCreateAssetUtility().instanceID, instanceID, this.GetCreateAssetUtility().originalName, this.GetCreateAssetUtility().icon); + } + if (this.m_TreeView.data.HasFakeItem() && !this.GetCreateAssetUtility().IsCreatingNewAsset()) + { + this.m_TreeView.data.RemoveFakeItem(); + } + } + public virtual void BeginCreateNewAsset(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile) + { + this.ClearRenameAndNewNodeState(); + this.GetCreateAssetUtility().BeginNewAssetCreation(instanceID, endAction, pathName, icon, resourceFile); + this.SyncFakeItem(); + if (!base.GetRenameOverlay().BeginRename(this.GetCreateAssetUtility().originalName, instanceID, 0f)) + { + Debug.LogError("Rename not started (when creating new asset)"); + } + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item == null) + { + return null; + } + Texture texture = null; + if (this.IsCreatingNewAsset(item.id)) + { + texture = this.GetCreateAssetUtility().icon; + } + if (texture == null) + { + texture = item.icon; + } + if (texture == null && item.id != 0) + { + string assetPath = AssetDatabase.GetAssetPath(item.id); + texture = AssetDatabase.GetCachedIcon(assetPath); + } + return texture; + } + private void OnIconOverlayGUI(TreeViewItem item, Rect overlayRect) + { + if (AssetsTreeViewGUI.s_VCEnabled && AssetDatabase.IsMainAsset(item.id)) + { + string assetPath = AssetDatabase.GetAssetPath(item.id); + string guid = AssetDatabase.AssetPathToGUID(assetPath); + ProjectHooks.OnProjectWindowItem(guid, overlayRect); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AsyncHTTPClient.cs b/UnityEditor/UnityEditor/AsyncHTTPClient.cs new file mode 100644 index 00000000..4a7a0368 --- /dev/null +++ b/UnityEditor/UnityEditor/AsyncHTTPClient.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + internal sealed class AsyncHTTPClient + { + internal enum State + { + INIT, + CONNECTING, + CONNECTED, + UPLOADING, + DOWNLOADING, + CONFIRMING, + DONE_OK, + DONE_FAILED, + ABORTED, + TIMEOUT + } + public delegate void DoneCallback(AsyncHTTPClient client); + public delegate void StatusCallback(AsyncHTTPClient.State status, int bytesDone, int bytesTotal); + private delegate void RequestProgressCallback(AsyncHTTPClient.State status, int downloaded, int totalSize); + private delegate void RequestDoneCallback(AsyncHTTPClient.State status, int httpStatus); + private IntPtr m_Handle; + public AsyncHTTPClient.StatusCallback statusCallback; + public AsyncHTTPClient.DoneCallback doneCallback; + private string m_ToUrl; + private string m_FromData; + private string m_Method; + public Dictionary header; + public string url + { + get + { + return this.m_ToUrl; + } + } + public string text + { + get + { + UTF8Encoding uTF8Encoding = new UTF8Encoding(); + byte[] bytes = this.bytes; + if (bytes == null) + { + return null; + } + return uTF8Encoding.GetString(bytes); + } + } + public byte[] bytes + { + get + { + return AsyncHTTPClient.GetBytesByHandle(this.m_Handle); + } + } + public Texture2D texture + { + get + { + return AsyncHTTPClient.GetTextureByHandle(this.m_Handle); + } + } + public AsyncHTTPClient.State state + { + get; + private set; + } + public int responseCode + { + get; + private set; + } + public string tag + { + get; + set; + } + public string postData + { + set + { + this.m_FromData = value; + if (this.m_Method == string.Empty) + { + this.m_Method = "POST"; + } + if (!this.header.ContainsKey("Content-Type")) + { + this.header["Content-Type"] = "application/x-www-form-urlencoded"; + } + } + } + public Dictionary postDictionary + { + set + { + this.postData = string.Join("&", ( + from kv in value + select this.EscapeLong(kv.Key) + "=" + this.EscapeLong(kv.Value)).ToArray()); + } + } + public AsyncHTTPClient(string _toUrl) + { + this.m_ToUrl = _toUrl; + this.m_FromData = null; + this.m_Method = string.Empty; + this.state = AsyncHTTPClient.State.INIT; + this.header = new Dictionary(StringComparer.OrdinalIgnoreCase); + this.m_Handle = (IntPtr)0; + this.tag = string.Empty; + this.statusCallback = null; + } + public AsyncHTTPClient(string _toUrl, string _method) + { + this.m_ToUrl = _toUrl; + this.m_FromData = null; + this.m_Method = _method; + this.state = AsyncHTTPClient.State.INIT; + this.header = new Dictionary(StringComparer.OrdinalIgnoreCase); + this.m_Handle = (IntPtr)0; + this.tag = string.Empty; + this.statusCallback = null; + } + public void Abort() + { + this.state = AsyncHTTPClient.State.ABORTED; + AsyncHTTPClient.AbortByHandle(this.m_Handle); + } + public bool IsAborted() + { + return this.state == AsyncHTTPClient.State.ABORTED; + } + public bool IsDone() + { + return AsyncHTTPClient.IsDone(this.state); + } + public static bool IsDone(AsyncHTTPClient.State state) + { + switch (state) + { + case AsyncHTTPClient.State.DONE_OK: + case AsyncHTTPClient.State.DONE_FAILED: + case AsyncHTTPClient.State.ABORTED: + case AsyncHTTPClient.State.TIMEOUT: + return true; + default: + return false; + } + } + public bool IsSuccess() + { + return this.state == AsyncHTTPClient.State.DONE_OK; + } + public static bool IsSuccess(AsyncHTTPClient.State state) + { + return state == AsyncHTTPClient.State.DONE_OK; + } + public void Begin() + { + if (this.IsAborted()) + { + this.state = AsyncHTTPClient.State.ABORTED; + return; + } + if (this.m_Method == string.Empty) + { + this.m_Method = "GET"; + } + string[] headers = ( + from kv in this.header + select string.Format("{0}: {1}", kv.Key, kv.Value)).ToArray(); + this.m_Handle = AsyncHTTPClient.SubmitClientRequest(this.tag, this.m_ToUrl, headers, this.m_Method, this.m_FromData, new AsyncHTTPClient.RequestDoneCallback(this.Done), new AsyncHTTPClient.RequestProgressCallback(this.Progress)); + } + private void Done(AsyncHTTPClient.State status, int i_ResponseCode) + { + this.state = status; + this.responseCode = i_ResponseCode; + if (this.doneCallback != null) + { + this.doneCallback(this); + } + this.m_Handle = (IntPtr)0; + } + private void Progress(AsyncHTTPClient.State status, int bytesDone, int bytesTotal) + { + this.state = status; + if (this.statusCallback != null) + { + this.statusCallback(status, bytesDone, bytesTotal); + } + } + private string EscapeLong(string v) + { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < v.Length; i += 32766) + { + stringBuilder.Append(Uri.EscapeDataString(v.Substring(i, (v.Length - i <= 32766) ? (v.Length - i) : 32766))); + } + return stringBuilder.ToString(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate, [DefaultValue("null")] AsyncHTTPClient.RequestProgressCallback progressDelegate); + [ExcludeFromDocs] + private static IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate) + { + AsyncHTTPClient.RequestProgressCallback progressDelegate = null; + return AsyncHTTPClient.SubmitClientRequest(tag, url, headers, method, data, doneDelegate, progressDelegate); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern byte[] GetBytesByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D GetTextureByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AbortByTag(string tag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void AbortByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CurlRequestCheck(); + } +} diff --git a/UnityEditor/UnityEditor/AsyncProgressBar.cs b/UnityEditor/UnityEditor/AsyncProgressBar.cs new file mode 100644 index 00000000..62e00956 --- /dev/null +++ b/UnityEditor/UnityEditor/AsyncProgressBar.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class AsyncProgressBar + { + public static extern float progress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string progressInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isShowing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Display(string progressInfo, float progress); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Clear(); + } +} diff --git a/UnityEditor/UnityEditor/AttachProfilerUI.cs b/UnityEditor/UnityEditor/AttachProfilerUI.cs new file mode 100644 index 00000000..552da8c7 --- /dev/null +++ b/UnityEditor/UnityEditor/AttachProfilerUI.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal struct AttachProfilerUI + { + private GUIContent m_CurrentProfiler; + private int[] m_ConnectionGuids; + private Rect m_ButtonScreenRect; + private static string kEnterIPText = ""; + private static GUIContent ms_NotificationMessage; + private static string kiOSOverUSB = "iOS profiler over USB"; + private void SelectProfilerClick(object userData, string[] options, int selected) + { + if (selected < this.m_ConnectionGuids.Length) + { + int connectedProfiler = this.m_ConnectionGuids[selected]; + ProfilerDriver.connectedProfiler = connectedProfiler; + } + else + { + if (options[selected] == AttachProfilerUI.kEnterIPText) + { + ProfilerIPWindow.Show(this.m_ButtonScreenRect); + } + else + { + if (options[selected] == AttachProfilerUI.kiOSOverUSB) + { + ProfilerDriver.DirectURLConnect("iproxy://"); + } + else + { + AttachProfilerUI.DirectIPConnect(options[selected]); + } + } + } + } + public bool IsEditor() + { + return ProfilerDriver.IsConnectionEditor(); + } + public string GetConnectedProfiler() + { + return ProfilerDriver.GetConnectionIdentifier(ProfilerDriver.connectedProfiler); + } + public static void DirectIPConnect(string ip) + { + ConsoleWindow.ShowConsoleWindow(true); + AttachProfilerUI.ms_NotificationMessage = new GUIContent("Connecting to IP...(this can take a while)"); + ProfilerDriver.DirectIPConnect(ip); + AttachProfilerUI.ms_NotificationMessage = null; + } + public void OnGUILayout(EditorWindow window) + { + if (this.m_CurrentProfiler == null) + { + this.m_CurrentProfiler = EditorGUIUtility.TextContent("Profiler.CurrentProfiler"); + } + Rect rect = GUILayoutUtility.GetRect(this.m_CurrentProfiler, EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(100f) + }); + this.OnGUI(rect, this.m_CurrentProfiler); + if (AttachProfilerUI.ms_NotificationMessage != null) + { + window.ShowNotification(AttachProfilerUI.ms_NotificationMessage); + } + else + { + window.RemoveNotification(); + } + } + public void OnGUI(Rect connectRect, GUIContent profilerLabel) + { + if (!EditorGUI.ButtonMouseDown(connectRect, profilerLabel, FocusType.Native, EditorStyles.toolbarDropDown)) + { + return; + } + int connectedProfiler = ProfilerDriver.connectedProfiler; + this.m_ConnectionGuids = ProfilerDriver.GetAvailableProfilers(); + int num = this.m_ConnectionGuids.Length; + int[] array = new int[1]; + List list = new List(); + List list2 = new List(); + for (int i = 0; i < num; i++) + { + int num2 = this.m_ConnectionGuids[i]; + string text = ProfilerDriver.GetConnectionIdentifier(num2); + bool flag = ProfilerDriver.IsIdentifierConnectable(num2); + bool flag2 = ProfilerDriver.IsIdentifierOnLocalhost(num2) && text.Contains("MetroPlayerX"); + if (flag2) + { + flag = false; + } + list.Add(flag); + if (!flag) + { + if (flag2) + { + text += " (Localhost prohibited)"; + } + else + { + text += " (Version mismatch)"; + } + } + list2.Add(text); + if (num2 == connectedProfiler) + { + array[0] = i; + } + } + string lastIPString = ProfilerIPWindow.GetLastIPString(); + if (!string.IsNullOrEmpty(lastIPString)) + { + if (connectedProfiler == 65261) + { + array[0] = num; + } + list2.Add(lastIPString); + list.Add(true); + } + if (Application.platform == RuntimePlatform.OSXEditor) + { + if (connectedProfiler == 65262) + { + array[0] = num; + } + list2.Add(AttachProfilerUI.kiOSOverUSB); + list.Add(true); + } + list2.Add(AttachProfilerUI.kEnterIPText); + list.Add(true); + this.m_ButtonScreenRect = GUIUtility.GUIToScreenRect(connectRect); + EditorUtility.DisplayCustomMenu(connectRect, list2.ToArray(), list.ToArray(), array, new EditorUtility.SelectMenuItemFunction(this.SelectProfilerClick), null); + } + } +} diff --git a/UnityEditor/UnityEditor/AttributeHelper.cs b/UnityEditor/UnityEditor/AttributeHelper.cs new file mode 100644 index 00000000..1fa92a77 --- /dev/null +++ b/UnityEditor/UnityEditor/AttributeHelper.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class AttributeHelper + { + private struct MonoGizmoMethod + { + public MethodInfo drawGizmo; + public Type drawnType; + public int options; + } + private struct MonoMenuItem + { + public string menuItem; + public string execute; + public string validate; + public int priority; + public int index; + public Type type; + } + internal class CompareMenuIndex : IComparer + { + int IComparer.Compare(object xo, object yo) + { + AttributeHelper.MonoMenuItem monoMenuItem = (AttributeHelper.MonoMenuItem)xo; + AttributeHelper.MonoMenuItem monoMenuItem2 = (AttributeHelper.MonoMenuItem)yo; + if (monoMenuItem.priority != monoMenuItem2.priority) + { + return monoMenuItem.priority.CompareTo(monoMenuItem2.priority); + } + return monoMenuItem.index.CompareTo(monoMenuItem2.index); + } + } + private static AttributeHelper.MonoGizmoMethod[] ExtractGizmos(Assembly assembly) + { + ArrayList arrayList = new ArrayList(); + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + for (int j = 0; j < methods.GetLength(0); j++) + { + MethodInfo methodInfo = methods[j]; + object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DrawGizmo), false); + object[] array2 = customAttributes; + for (int k = 0; k < array2.Length; k++) + { + DrawGizmo drawGizmo = (DrawGizmo)array2[k]; + ParameterInfo[] parameters = methodInfo.GetParameters(); + if (parameters.Length != 2) + { + Debug.LogWarning(string.Format("Method {0}.{1} is marked with the DrawGizmo attribute but does not take parameters (ComponentType, GizmoType) so will be ignored.", methodInfo.DeclaringType.FullName, methodInfo.Name)); + } + else + { + AttributeHelper.MonoGizmoMethod monoGizmoMethod = default(AttributeHelper.MonoGizmoMethod); + if (drawGizmo.drawnType == null) + { + monoGizmoMethod.drawnType = parameters[0].ParameterType; + } + else + { + if (!parameters[0].ParameterType.IsAssignableFrom(drawGizmo.drawnType)) + { + Debug.LogWarning(string.Format("Method {0}.{1} is marked with the DrawGizmo attribute but the component type it applies to could not be determined.", methodInfo.DeclaringType.FullName, methodInfo.Name)); + goto IL_194; + } + monoGizmoMethod.drawnType = drawGizmo.drawnType; + } + if (parameters[1].ParameterType != typeof(GizmoType) && parameters[1].ParameterType != typeof(int)) + { + Debug.LogWarning(string.Format("Method {0}.{1} is marked with the DrawGizmo attribute but does not take a second parameter of type GizmoType so will be ignored.", methodInfo.DeclaringType.FullName, methodInfo.Name)); + } + else + { + monoGizmoMethod.drawGizmo = methodInfo; + monoGizmoMethod.options = (int)drawGizmo.drawOptions; + arrayList.Add(monoGizmoMethod); + } + } + IL_194:; + } + } + } + AttributeHelper.MonoGizmoMethod[] array3 = new AttributeHelper.MonoGizmoMethod[arrayList.Count]; + int num = 0; + foreach (AttributeHelper.MonoGizmoMethod monoGizmoMethod2 in arrayList) + { + array3[num++] = monoGizmoMethod2; + } + return array3; + } + private static AttributeHelper.MonoMenuItem[] ExtractMenuCommands(Assembly assembly) + { + bool @bool = EditorPrefs.GetBool("InternalMode", false); + Hashtable hashtable = new Hashtable(); + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + for (int j = 0; j < methods.GetLength(0); j++) + { + MethodInfo methodInfo = methods[j]; + object[] customAttributes = methodInfo.GetCustomAttributes(typeof(MenuItem), false); + object[] array2 = customAttributes; + int k = 0; + while (k < array2.Length) + { + MenuItem menuItem = (MenuItem)array2[k]; + AttributeHelper.MonoMenuItem monoMenuItem = default(AttributeHelper.MonoMenuItem); + if (hashtable[menuItem.menuItem] != null) + { + monoMenuItem = (AttributeHelper.MonoMenuItem)hashtable[menuItem.menuItem]; + } + if (!menuItem.menuItem.StartsWith("internal:", StringComparison.Ordinal)) + { + monoMenuItem.menuItem = menuItem.menuItem; + goto IL_E7; + } + if (@bool) + { + monoMenuItem.menuItem = menuItem.menuItem.Substring(9); + goto IL_E7; + } + IL_147: + k++; + continue; + IL_E7: + monoMenuItem.type = type; + if (menuItem.validate) + { + monoMenuItem.validate = methodInfo.Name; + } + else + { + monoMenuItem.execute = methodInfo.Name; + monoMenuItem.index = j; + monoMenuItem.priority = menuItem.priority; + } + hashtable[menuItem.menuItem] = monoMenuItem; + goto IL_147; + } + } + } + AttributeHelper.MonoMenuItem[] array3 = new AttributeHelper.MonoMenuItem[hashtable.Count]; + int num = 0; + foreach (AttributeHelper.MonoMenuItem monoMenuItem2 in hashtable.Values) + { + array3[num++] = monoMenuItem2; + } + Array.Sort(array3, new AttributeHelper.CompareMenuIndex()); + return array3; + } + private static AttributeHelper.MonoMenuItem[] ExtractContextMenu(Type klass) + { + Hashtable hashtable = new Hashtable(); + MethodInfo[] methods = klass.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + for (int i = 0; i < methods.GetLength(0); i++) + { + MethodInfo methodInfo = methods[i]; + object[] customAttributes = methodInfo.GetCustomAttributes(typeof(ContextMenu), false); + object[] array = customAttributes; + for (int j = 0; j < array.Length; j++) + { + ContextMenu contextMenu = (ContextMenu)array[j]; + AttributeHelper.MonoMenuItem monoMenuItem = default(AttributeHelper.MonoMenuItem); + if (hashtable[contextMenu.menuItem] != null) + { + monoMenuItem = (AttributeHelper.MonoMenuItem)hashtable[contextMenu.menuItem]; + } + monoMenuItem.menuItem = contextMenu.menuItem; + monoMenuItem.type = klass; + monoMenuItem.execute = methodInfo.Name; + hashtable[contextMenu.menuItem] = monoMenuItem; + } + } + AttributeHelper.MonoMenuItem[] array2 = new AttributeHelper.MonoMenuItem[hashtable.Count]; + int num = 0; + foreach (AttributeHelper.MonoMenuItem monoMenuItem2 in hashtable.Values) + { + array2[num++] = monoMenuItem2; + } + return array2; + } + private static string GetComponentMenuName(Type klass) + { + object[] customAttributes = klass.GetCustomAttributes(typeof(AddComponentMenu), false); + if (customAttributes.Length > 0) + { + AddComponentMenu addComponentMenu = (AddComponentMenu)customAttributes[0]; + return addComponentMenu.componentMenu; + } + return null; + } + private static int GetComponentMenuOrdering(Type klass) + { + object[] customAttributes = klass.GetCustomAttributes(typeof(AddComponentMenu), false); + if (customAttributes.Length > 0) + { + AddComponentMenu addComponentMenu = (AddComponentMenu)customAttributes[0]; + return addComponentMenu.componentOrder; + } + return 0; + } + internal static ArrayList FindEditorClassesWithAttribute(Type attrib) + { + ArrayList arrayList = new ArrayList(); + foreach (Type current in EditorAssemblies.loadedTypes) + { + if (current.GetCustomAttributes(attrib, false).Length != 0) + { + arrayList.Add(current); + } + } + return arrayList; + } + internal static void InvokeStaticMethod(Type type, string methodName, object[] arguments) + { + MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + method.Invoke(null, arguments); + } + } + internal static void InvokeMethod(Type type, string methodName, object[] arguments) + { + MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + method.Invoke(null, arguments); + } + } + internal static object InvokeMemberIfAvailable(object target, string methodName, object[] args) + { + MethodInfo method = target.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + return method.Invoke(target, args); + } + return null; + } + internal static bool GameObjectContainsAttribute(GameObject go, Type attributeType) + { + Component[] components = go.GetComponents(typeof(MonoBehaviour)); + for (int i = 0; i < components.Length; i++) + { + Component component = components[i]; + if (!(component == null)) + { + Type type = component.GetType(); + if (type.GetCustomAttributes(attributeType, true).Length > 0) + { + return true; + } + } + } + return false; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioChorusFilterEditor.cs b/UnityEditor/UnityEditor/AudioChorusFilterEditor.cs new file mode 100644 index 00000000..5dfaf5d6 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioChorusFilterEditor.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioChorusFilter))] + internal class AudioChorusFilterEditor : Editor + { + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.OnInspectorGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioClipInspector.cs b/UnityEditor/UnityEditor/AudioClipInspector.cs new file mode 100644 index 00000000..e9669f1b --- /dev/null +++ b/UnityEditor/UnityEditor/AudioClipInspector.cs @@ -0,0 +1,330 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioClip))] + internal class AudioClipInspector : Editor + { + private AudioClip m_PlayingClip; + private Vector2 m_Position = Vector2.zero; + private GUIView m_GUI; + private static GUIStyle s_PreButton; + private static Rect m_wantedRect; + private static bool m_bAutoPlay; + private static bool m_bLoop = false; + private static bool m_bPlayFirst; + private static GUIContent[] s_PlayIcons = new GUIContent[2]; + private static GUIContent[] s_AutoPlayIcons = new GUIContent[2]; + private static GUIContent[] s_LoopIcons = new GUIContent[2]; + private static Texture2D s_DefaultIcon; + private bool playing + { + get + { + return this.m_PlayingClip != null; + } + } + public override void OnInspectorGUI() + { + } + private static void Init() + { + if (AudioClipInspector.s_PreButton != null) + { + return; + } + AudioClipInspector.s_PreButton = "preButton"; + AudioClipInspector.m_bAutoPlay = EditorPrefs.GetBool("AutoPlayAudio", false); + AudioClipInspector.m_bLoop = false; + AudioClipInspector.s_AutoPlayIcons[0] = EditorGUIUtility.IconContent("preAudioAutoPlayOff", "Turn Auto Play on"); + AudioClipInspector.s_AutoPlayIcons[1] = EditorGUIUtility.IconContent("preAudioAutoPlayOn", "Turn Auto Play off"); + AudioClipInspector.s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff", "Play"); + AudioClipInspector.s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn", "Stop"); + AudioClipInspector.s_LoopIcons[0] = EditorGUIUtility.IconContent("preAudioLoopOff", "Loop on"); + AudioClipInspector.s_LoopIcons[1] = EditorGUIUtility.IconContent("preAudioLoopOn", "Loop off"); + AudioClipInspector.s_DefaultIcon = EditorGUIUtility.LoadIcon("Profiler.Audio"); + } + public void OnDisable() + { + AudioUtil.StopAllClips(); + AudioUtil.ClearWaveForm(this.target as AudioClip); + EditorPrefs.SetBool("AutoPlayAudio", AudioClipInspector.m_bAutoPlay); + } + public void OnEnable() + { + AudioClipInspector.m_bAutoPlay = EditorPrefs.GetBool("AutoPlayAudio", false); + if (AudioClipInspector.m_bAutoPlay) + { + AudioClipInspector.m_bPlayFirst = true; + } + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + AudioImporter audioImporter = AssetImporter.GetAtPath(assetPath) as AudioImporter; + if (!audioImporter) + { + return null; + } + AudioClip audioClip = this.target as AudioClip; + Texture2D[] array = new Texture2D[audioClip.channels]; + for (int i = 0; i < audioClip.channels; i++) + { + array[i] = AudioUtil.GetWaveForm(audioClip, audioImporter, i, (float)width, (float)(height / audioClip.channels)); + } + return AudioClipInspector.CombineWaveForms(array); + } + public override bool HasPreviewGUI() + { + return base.targets != null; + } + public override void OnPreviewSettings() + { + if (AudioClipInspector.s_DefaultIcon == null) + { + AudioClipInspector.Init(); + } + AudioClip audioClip = this.target as AudioClip; + EditorGUI.BeginDisabledGroup(AudioUtil.IsMovieAudio(audioClip)); + bool flag = base.targets.Length > 1; + EditorGUI.BeginDisabledGroup(flag); + AudioClipInspector.m_bAutoPlay = (!flag && AudioClipInspector.m_bAutoPlay); + AudioClipInspector.m_bAutoPlay = (PreviewGUI.CycleButton((!AudioClipInspector.m_bAutoPlay) ? 0 : 1, AudioClipInspector.s_AutoPlayIcons) != 0); + EditorGUI.EndDisabledGroup(); + bool bLoop = AudioClipInspector.m_bLoop; + AudioClipInspector.m_bLoop = (PreviewGUI.CycleButton((!AudioClipInspector.m_bLoop) ? 0 : 1, AudioClipInspector.s_LoopIcons) != 0); + if (bLoop != AudioClipInspector.m_bLoop && this.playing) + { + AudioUtil.LoopClip(audioClip, AudioClipInspector.m_bLoop); + } + EditorGUI.BeginDisabledGroup(flag && !this.playing); + bool flag2 = PreviewGUI.CycleButton((!this.playing) ? 0 : 1, AudioClipInspector.s_PlayIcons) != 0; + if (flag2 != this.playing) + { + if (flag2) + { + AudioUtil.PlayClip(audioClip, 0, AudioClipInspector.m_bLoop); + this.m_PlayingClip = audioClip; + } + else + { + AudioUtil.StopAllClips(); + this.m_PlayingClip = null; + } + } + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (AudioClipInspector.s_DefaultIcon == null) + { + AudioClipInspector.Init(); + } + AudioClip audioClip = this.target as AudioClip; + Event current = Event.current; + if (current.type != EventType.Repaint && current.type != EventType.Layout && current.type != EventType.Used) + { + int num = AudioUtil.GetSampleCount(audioClip) / (int)r.width; + switch (current.type) + { + case EventType.MouseDown: + case EventType.MouseDrag: + if (r.Contains(current.mousePosition) && !AudioUtil.IsMovieAudio(audioClip)) + { + if (this.m_PlayingClip != audioClip) + { + AudioUtil.StopAllClips(); + AudioUtil.PlayClip(audioClip, 0, AudioClipInspector.m_bLoop); + this.m_PlayingClip = audioClip; + } + AudioUtil.SetClipSamplePosition(audioClip, num * (int)current.mousePosition.x); + current.Use(); + } + break; + } + return; + } + if (Event.current.type == EventType.Repaint) + { + background.Draw(r, false, false, false, false); + } + int channelCount = AudioUtil.GetChannelCount(audioClip); + AudioClipInspector.m_wantedRect = new Rect(r.x, r.y, r.width, r.height); + float num2 = AudioClipInspector.m_wantedRect.width / audioClip.length; + if (!AudioUtil.HasPreview(audioClip) && (AudioUtil.IsMOD(audioClip) || AudioUtil.IsMovieAudio(audioClip))) + { + float num3 = (r.height <= 150f) ? (r.y + r.height / 2f - 25f) : (r.y + r.height / 2f - 10f); + if (r.width > 64f) + { + if (AudioUtil.IsMOD(audioClip)) + { + EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), string.Format("Module file with " + AudioUtil.GetMODChannelCount(audioClip) + " channels.", new object[0])); + } + else + { + if (AudioUtil.IsMovieAudio(audioClip)) + { + if (r.width > 450f) + { + EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), "Audio is attached to a movie. To audition the sound, play the movie."); + } + else + { + EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), "Audio is attached to a movie."); + EditorGUI.DropShadowLabel(new Rect(r.x, num3 + 10f, r.width, 20f), "To audition the sound, play the movie."); + } + } + else + { + EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), "Can not show PCM data for this file"); + } + } + } + if (this.m_PlayingClip == audioClip) + { + float clipPosition = AudioUtil.GetClipPosition(audioClip); + TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)(clipPosition * 1000f)); + EditorGUI.DropShadowLabel(new Rect(AudioClipInspector.m_wantedRect.x, AudioClipInspector.m_wantedRect.y, AudioClipInspector.m_wantedRect.width, 20f), string.Format("Playing - {0:00}:{1:00}.{2:000}", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds)); + } + } + else + { + PreviewGUI.BeginScrollView(AudioClipInspector.m_wantedRect, this.m_Position, AudioClipInspector.m_wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); + Texture2D texture2D; + if (r.width < 100f) + { + texture2D = AssetPreview.GetAssetPreview(audioClip); + } + else + { + texture2D = AudioUtil.GetWaveFormFast(audioClip, 1, 0, audioClip.samples, r.width, r.height); + } + if (texture2D == null) + { + GUI.DrawTexture(new Rect + { + x = (AudioClipInspector.m_wantedRect.width - (float)AudioClipInspector.s_DefaultIcon.width) / 2f + AudioClipInspector.m_wantedRect.x, + y = (AudioClipInspector.m_wantedRect.height - (float)AudioClipInspector.s_DefaultIcon.height) / 2f + AudioClipInspector.m_wantedRect.y, + width = (float)AudioClipInspector.s_DefaultIcon.width, + height = (float)AudioClipInspector.s_DefaultIcon.height + }, AudioClipInspector.s_DefaultIcon); + base.Repaint(); + } + else + { + GUI.DrawTexture(new Rect(AudioClipInspector.m_wantedRect.x, AudioClipInspector.m_wantedRect.y, AudioClipInspector.m_wantedRect.width, AudioClipInspector.m_wantedRect.height), texture2D); + } + for (int i = 0; i < channelCount; i++) + { + if (channelCount > 1 && r.width > 64f) + { + Rect position = new Rect(AudioClipInspector.m_wantedRect.x + 5f, AudioClipInspector.m_wantedRect.y + AudioClipInspector.m_wantedRect.height / (float)channelCount * (float)i, 30f, 20f); + EditorGUI.DropShadowLabel(position, "ch " + (i + 1).ToString()); + } + } + if (this.m_PlayingClip == audioClip) + { + float clipPosition2 = AudioUtil.GetClipPosition(audioClip); + TimeSpan timeSpan2 = new TimeSpan(0, 0, 0, 0, (int)(clipPosition2 * 1000f)); + GUI.DrawTexture(new Rect(AudioClipInspector.m_wantedRect.x + (float)((int)(num2 * clipPosition2)), AudioClipInspector.m_wantedRect.y, 2f, AudioClipInspector.m_wantedRect.height), EditorGUIUtility.whiteTexture); + if (r.width > 64f) + { + EditorGUI.DropShadowLabel(new Rect(AudioClipInspector.m_wantedRect.x, AudioClipInspector.m_wantedRect.y, AudioClipInspector.m_wantedRect.width, 20f), string.Format("{0:00}:{1:00}.{2:000}", timeSpan2.Minutes, timeSpan2.Seconds, timeSpan2.Milliseconds)); + } + else + { + EditorGUI.DropShadowLabel(new Rect(AudioClipInspector.m_wantedRect.x, AudioClipInspector.m_wantedRect.y, AudioClipInspector.m_wantedRect.width, 20f), string.Format("{0:00}:{1:00}", timeSpan2.Minutes, timeSpan2.Seconds)); + } + if (!AudioUtil.IsClipPlaying(audioClip)) + { + this.m_PlayingClip = null; + } + } + PreviewGUI.EndScrollView(); + } + if (AudioClipInspector.m_bPlayFirst) + { + AudioUtil.PlayClip(audioClip, 0, AudioClipInspector.m_bLoop); + this.m_PlayingClip = audioClip; + AudioClipInspector.m_bPlayFirst = false; + } + if (this.playing) + { + GUIView.current.Repaint(); + } + } + private static Texture2D CombineWaveForms(Texture2D[] waveForms) + { + if (waveForms.Length == 1) + { + return waveForms[0]; + } + int width = waveForms[0].width; + int num = 0; + for (int i = 0; i < waveForms.Length; i++) + { + Texture2D texture2D = waveForms[i]; + num += texture2D.height; + } + Texture2D texture2D2 = new Texture2D(width, num, TextureFormat.ARGB32, false); + int num2 = 0; + for (int j = 0; j < waveForms.Length; j++) + { + Texture2D texture2D3 = waveForms[j]; + num2 += texture2D3.height; + texture2D2.SetPixels(0, num - num2, width, texture2D3.height, texture2D3.GetPixels()); + UnityEngine.Object.DestroyImmediate(texture2D3); + } + texture2D2.Apply(); + return texture2D2; + } + public override string GetInfoString() + { + AudioClip clip = this.target as AudioClip; + int channelCount = AudioUtil.GetChannelCount(clip); + string text = (channelCount != 1) ? ((channelCount != 2) ? ((channelCount - 1).ToString() + ".1") : "Stereo") : "Mono"; + string text2 = string.Empty; + if (AudioUtil.GetClipType(clip) != AudioType.MPEG) + { + text2 = string.Concat(new object[] + { + AudioUtil.GetBitsPerSample(clip), + " bit, ", + AudioUtil.GetFrequency(clip), + " Hz, ", + text, + ", " + }); + } + else + { + text2 = string.Concat(new object[] + { + AudioUtil.GetFrequency(clip), + " Hz, ", + text, + ", " + }); + } + TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)AudioUtil.GetDuration(clip)); + if ((uint)AudioUtil.GetDuration(clip) == 4294967295u) + { + text2 += "Unlimited"; + } + else + { + text2 += string.Format("{0:00}:{1:00}.{2:000}", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); + } + text2 += ", "; + text2 += EditorUtility.FormatBytes(AudioUtil.GetSoundSize(clip)); + string text3 = text2; + return string.Concat(new object[] + { + text3, + " (", + AudioUtil.GetClipType(clip), + ")" + }); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioDistortionFilterEditor.cs b/UnityEditor/UnityEditor/AudioDistortionFilterEditor.cs new file mode 100644 index 00000000..6a25084d --- /dev/null +++ b/UnityEditor/UnityEditor/AudioDistortionFilterEditor.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioDistortionFilter))] + internal class AudioDistortionFilterEditor : Editor + { + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.OnInspectorGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioEchoFilterEditor.cs b/UnityEditor/UnityEditor/AudioEchoFilterEditor.cs new file mode 100644 index 00000000..1f0e6910 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioEchoFilterEditor.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioEchoFilter))] + internal class AudioEchoFilterEditor : Editor + { + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.OnInspectorGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioFilterGUI.cs b/UnityEditor/UnityEditor/AudioFilterGUI.cs new file mode 100644 index 00000000..9cc3eeb0 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioFilterGUI.cs @@ -0,0 +1,46 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioFilterGUI + { + private EditorGUI.VUMeterData[] dataOut; + public void DrawAudioFilterGUI(MonoBehaviour behaviour) + { + int customFilterChannelCount = AudioUtil.GetCustomFilterChannelCount(behaviour); + if (customFilterChannelCount > 0) + { + if (this.dataOut == null) + { + this.dataOut = new EditorGUI.VUMeterData[customFilterChannelCount]; + } + double num = (double)AudioUtil.GetCustomFilterProcessTime(behaviour) / 1000000.0; + float num2 = (float)num / ((float)AudioSettings.outputSampleRate / 1024f / (float)customFilterChannelCount); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(13f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + EditorGUILayout.Space(); + for (int i = 0; i < customFilterChannelCount; i++) + { + EditorGUILayout.VUMeterHorizontal(AudioUtil.GetCustomFilterMaxOut(behaviour, i), ref this.dataOut[i], new GUILayoutOption[] + { + GUILayout.MinWidth(50f), + GUILayout.Height(5f) + }); + } + GUILayout.EndVertical(); + Color color = GUI.color; + GUI.color = new Color(num2, 1f - num2, 0f, 1f); + GUILayout.Box(string.Format("{0:00.00}ms", num), new GUILayoutOption[] + { + GUILayout.MinWidth(40f), + GUILayout.Height(20f) + }); + GUI.color = color; + GUILayout.EndHorizontal(); + EditorGUILayout.Space(); + GUIView.current.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioHighPassFilterEditor.cs b/UnityEditor/UnityEditor/AudioHighPassFilterEditor.cs new file mode 100644 index 00000000..6c086756 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioHighPassFilterEditor.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioHighPassFilter))] + internal class AudioHighPassFilterEditor : Editor + { + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.OnInspectorGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioImporter.cs b/UnityEditor/UnityEditor/AudioImporter.cs new file mode 100644 index 00000000..c9094477 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporter.cs @@ -0,0 +1,172 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class AudioImporter : AssetImporter + { + public extern AudioImporterFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] + public AudioImporterChannels channels + { + get + { + return AudioImporterChannels.Automatic; + } + set + { + } + } + public extern int compressionBitrate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Setting/Getting decompressOnLoad is deprecated. Use AudioImporter.loadType instead.", true)] + private bool decompressOnLoad + { + get + { + return this.loadType == AudioImporterLoadType.DecompressOnLoad; + } + set + { + this.loadType = ((!value) ? AudioImporterLoadType.CompressedInMemory : AudioImporterLoadType.DecompressOnLoad); + } + } + public extern bool threeD + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool forceToMono + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hardware + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AudioImporterLoadType loadType + { + get + { + return (AudioImporterLoadType)this.Internal_GetLoadType(); + } + set + { + this.Internal_SetLoadType((int)value); + } + } + public extern bool loopable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern int durationMS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int frequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int origChannelCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool origIsCompressible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool origIsMonoForcable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int defaultBitrate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal AudioType origType + { + get + { + return (AudioType)this.Internal_GetType(); + } + } + internal extern int origFileSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetLoadType(int flag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetLoadType(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void updateOrigData(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetMinBitrate(int type); + internal int minBitrate(AudioType type) + { + return this.Internal_GetMinBitrate((int)type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetMaxBitrate(int type); + internal int maxBitrate(AudioType type) + { + return this.Internal_GetMaxBitrate((int)type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetType(); + } +} diff --git a/UnityEditor/UnityEditor/AudioImporterChannels.cs b/UnityEditor/UnityEditor/AudioImporterChannels.cs new file mode 100644 index 00000000..cfd36624 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporterChannels.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] + public enum AudioImporterChannels + { + Automatic, + Mono, + Stereo + } +} diff --git a/UnityEditor/UnityEditor/AudioImporterFormat.cs b/UnityEditor/UnityEditor/AudioImporterFormat.cs new file mode 100644 index 00000000..c36c6907 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporterFormat.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum AudioImporterFormat + { + Native = -1, + Compressed + } +} diff --git a/UnityEditor/UnityEditor/AudioImporterInspector.cs b/UnityEditor/UnityEditor/AudioImporterInspector.cs new file mode 100644 index 00000000..768c8435 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporterInspector.cs @@ -0,0 +1,219 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioImporter))] + internal class AudioImporterInspector : AssetImporterInspector + { + private AudioImporterFormat m_format; + private int m_compressionBitrate; + private AudioImporterLoadType m_loadType; + private bool m_3D; + private bool m_Hardware; + private bool m_Loopable; + private bool m_ForceToMono; + private int m_durationMS; + private int m_origchannels; + private bool m_iscompressible; + private AudioType m_type; + private int m_maxbitrate; + private int m_minbitrate; + private AudioType m_compressedType; + private static string[] formatLabels = new string[2]; + internal override bool HasModified() + { + AudioImporter audioImporter = this.target as AudioImporter; + return audioImporter.format != this.m_format || audioImporter.compressionBitrate != this.m_compressionBitrate || audioImporter.loadType != this.m_loadType || audioImporter.threeD != this.m_3D || audioImporter.forceToMono != this.m_ForceToMono || audioImporter.hardware != this.m_Hardware || audioImporter.loopable != this.m_Loopable; + } + internal override void ResetValues() + { + AudioImporter audioImporter = this.target as AudioImporter; + this.m_format = audioImporter.format; + this.m_loadType = audioImporter.loadType; + this.m_compressionBitrate = audioImporter.compressionBitrate; + this.m_3D = audioImporter.threeD; + this.m_ForceToMono = audioImporter.forceToMono; + this.m_Hardware = audioImporter.hardware; + this.m_Loopable = audioImporter.loopable; + audioImporter.updateOrigData(); + this.m_durationMS = audioImporter.durationMS; + this.m_origchannels = audioImporter.origChannelCount; + this.m_iscompressible = audioImporter.origIsCompressible; + this.m_type = audioImporter.origType; + if (this.m_durationMS != 0) + { + this.m_compressedType = AudioUtil.GetPlatformConversionType(this.m_type, BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget), AudioImporterFormat.Compressed); + } + this.m_minbitrate = audioImporter.minBitrate(this.m_compressedType) / 1000; + this.m_maxbitrate = audioImporter.maxBitrate(this.m_compressedType) / 1000; + } + internal override void Apply() + { + AudioImporter audioImporter = this.target as AudioImporter; + audioImporter.format = this.m_format; + audioImporter.loadType = this.m_loadType; + audioImporter.compressionBitrate = this.m_compressionBitrate; + audioImporter.threeD = this.m_3D; + audioImporter.forceToMono = this.m_ForceToMono; + audioImporter.hardware = this.m_Hardware; + audioImporter.loopable = this.m_Loopable; + } + public override void OnInspectorGUI() + { + BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); + AudioImporter audioImporter = this.target as AudioImporter; + if (audioImporter != null) + { + BuildTargetGroup buildTargetGroup2 = buildTargetGroup; + if (buildTargetGroup2 != BuildTargetGroup.FlashPlayer) + { + if (buildTargetGroup2 != BuildTargetGroup.PSP2) + { + EditorGUI.BeginDisabledGroup(this.m_type == AudioType.MPEG || this.m_type == AudioType.OGGVORBIS || !this.m_iscompressible); + AudioImporterInspector.formatLabels[0] = "Native (" + this.m_type + ")"; + AudioImporterInspector.formatLabels[1] = "Compressed (" + this.m_compressedType + ")"; + int num = EditorGUILayout.Popup("Audio Format", (int)(this.m_format + 1), AudioImporterInspector.formatLabels, new GUILayoutOption[0]); + this.m_format = (AudioImporterFormat)(num - 1); + EditorGUI.EndDisabledGroup(); + this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); + bool flag = this.m_origchannels > 1 && (audioImporter.origIsMonoForcable || (this.m_format == AudioImporterFormat.Compressed && this.m_iscompressible)); + EditorGUI.BeginDisabledGroup(!flag); + this.m_ForceToMono = EditorGUILayout.Toggle("Force to mono", this.m_ForceToMono, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (this.m_format == AudioImporterFormat.Compressed) + { + string[] displayedOptions = new string[] + { + "Decompress on load", + "Compressed in memory", + "Stream from disc" + }; + this.m_loadType = (AudioImporterLoadType)EditorGUILayout.Popup("Load type", (int)this.m_loadType, displayedOptions, new GUILayoutOption[0]); + } + else + { + string[] displayedOptions = new string[] + { + "Load into memory", + "Stream from disc" + }; + int num2 = Mathf.Clamp(this.m_loadType - AudioImporterLoadType.CompressedInMemory, 0, 1); + EditorGUI.BeginChangeCheck(); + num2 = EditorGUILayout.Popup("Load type", num2, displayedOptions, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_loadType = num2 + AudioImporterLoadType.CompressedInMemory; + } + } + EditorGUI.BeginDisabledGroup(buildTargetGroup != BuildTargetGroup.iPhone || this.m_format != AudioImporterFormat.Compressed); + this.m_Hardware = EditorGUILayout.Toggle("Hardware decoding", this.m_Hardware, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!this.m_iscompressible || (this.m_compressedType != AudioType.MPEG && this.m_compressedType != AudioType.XMA) || this.m_format != AudioImporterFormat.Compressed); + this.m_Loopable = EditorGUILayout.Toggle(new GUIContent("Gapless looping", "Perform special MPEG encoding and stretch to loop the sound perfectly"), this.m_Loopable, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (this.m_durationMS != 0) + { + EditorGUI.BeginDisabledGroup(this.m_format != AudioImporterFormat.Compressed); + int compressionBitrate; + if (buildTargetGroup == BuildTargetGroup.XBOX360) + { + compressionBitrate = (56 + 2 * this.GetQualityGUI()) * 1000; + } + else + { + compressionBitrate = this.GetBitRateGUI(audioImporter) * 1000; + } + if (GUI.changed) + { + this.m_compressionBitrate = compressionBitrate; + } + EditorGUI.EndDisabledGroup(); + } + else + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Unity failed to import this audio file. Try to reimport.", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + } + else + { + GUI.enabled = (this.m_type != AudioType.MPEG && this.m_type != AudioType.OGGVORBIS && this.m_iscompressible); + AudioImporterInspector.formatLabels[0] = "Native (" + this.m_type + ")"; + AudioImporterInspector.formatLabels[1] = "Compressed (" + this.m_compressedType + ")"; + int num3 = EditorGUILayout.Popup("Audio Format", (int)(this.m_format + 1), AudioImporterInspector.formatLabels, new GUILayoutOption[0]); + this.m_format = (AudioImporterFormat)(num3 - 1); + GUI.enabled = true; + this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); + if (this.m_format == AudioImporterFormat.Compressed) + { + string[] displayedOptions2 = new string[] + { + "Decompress on load", + "Compressed in memory", + "Stream from disc" + }; + this.m_loadType = (AudioImporterLoadType)EditorGUILayout.Popup("Load type", (int)this.m_loadType, displayedOptions2, new GUILayoutOption[0]); + } + else + { + string[] displayedOptions2 = new string[] + { + "Load into memory", + "Stream from disc" + }; + int num4 = Mathf.Clamp(this.m_loadType - AudioImporterLoadType.CompressedInMemory, 0, 1); + EditorGUI.BeginChangeCheck(); + num4 = EditorGUILayout.Popup("Load type", num4, displayedOptions2, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_loadType = num4 + AudioImporterLoadType.CompressedInMemory; + } + } + GUI.enabled = (this.m_iscompressible && (this.m_compressedType == AudioType.MPEG || this.m_compressedType == AudioType.XMA || this.m_compressedType == AudioType.VAG) && this.m_format == AudioImporterFormat.Compressed); + this.m_Loopable = EditorGUILayout.Toggle(new GUIContent("Looping", "Encode file for looping"), this.m_Loopable, new GUILayoutOption[0]); + GUI.enabled = true; + if (this.m_durationMS == 0) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Unity failed to import this audio file. Try to reimport.", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + } + } + else + { + this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); + } + } + GUI.enabled = true; + GUI.changed = false; + base.ApplyRevertGUI(); + if (GUI.changed) + { + GUIUtility.ExitGUI(); + } + } + private int GetBitRateGUI(AudioImporter importer) + { + int num = (this.m_compressionBitrate >= 0) ? (this.m_compressionBitrate / 1000) : (importer.defaultBitrate / 1000); + int result = EditorGUILayout.IntSlider("Compression (kbps)", num, this.m_minbitrate, this.m_maxbitrate, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (this.m_format == AudioImporterFormat.Compressed) + { + float num2 = (float)this.m_durationMS / 1000f; + int bytes = (int)(num2 * ((float)num * 1000f / 4f)); + GUILayout.Label(string.Format("New file size : {0:000}", EditorUtility.FormatBytes(bytes)), new GUILayoutOption[0]); + } + GUILayout.EndHorizontal(); + return result; + } + private int GetQualityGUI() + { + float num = (this.m_compressionBitrate >= 0) ? (((float)this.m_compressionBitrate / 1000f - 56f) / 2f) : 50f; + int value = (int)Math.Round((double)num); + return EditorGUILayout.IntSlider("XMA Quality (1-100)", value, 1, 100, new GUILayoutOption[0]); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioImporterLoadType.cs b/UnityEditor/UnityEditor/AudioImporterLoadType.cs new file mode 100644 index 00000000..f89ed361 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporterLoadType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum AudioImporterLoadType + { + DecompressOnLoad, + CompressedInMemory, + StreamFromDisc + } +} diff --git a/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs b/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs new file mode 100644 index 00000000..31ced499 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs @@ -0,0 +1,41 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioLowPassFilter))] + internal class AudioLowPassFilterInspector : Editor + { + private SerializedProperty m_LowpassResonanceQ; + private SerializedProperty m_CutoffFrequency; + private SerializedProperty m_LowpassLevelCustomCurve; + private void OnEnable() + { + this.m_LowpassResonanceQ = base.serializedObject.FindProperty("m_LowpassResonanceQ"); + this.m_CutoffFrequency = base.serializedObject.FindProperty("m_CutoffFrequency"); + this.m_LowpassLevelCustomCurve = base.serializedObject.FindProperty("lowpassLevelCustomCurve"); + } + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + AudioSourceInspector.AnimProp(new GUIContent("Cutoff Frequency"), this.m_LowpassLevelCustomCurve, 22000f, 0f); + if (EditorGUI.EndChangeCheck()) + { + AnimationCurve animationCurveValue = this.m_LowpassLevelCustomCurve.animationCurveValue; + if (animationCurveValue.length > 0) + { + this.m_CutoffFrequency.floatValue = Mathf.Lerp(22000f, 0f, animationCurveValue.keys[0].value); + } + } + EditorGUILayout.PropertyField(this.m_LowpassResonanceQ, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioReverbFilterEditor.cs b/UnityEditor/UnityEditor/AudioReverbFilterEditor.cs new file mode 100644 index 00000000..e65fed92 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioReverbFilterEditor.cs @@ -0,0 +1,76 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioReverbFilter))] + internal class AudioReverbFilterEditor : Editor + { + private SerializedProperty m_ReverbPreset; + private SerializedProperty m_DryLevel; + private SerializedProperty m_Room; + private SerializedProperty m_RoomHF; + private SerializedProperty m_RoomLF; + private SerializedProperty m_DecayTime; + private SerializedProperty m_DecayHFRatio; + private SerializedProperty m_ReflectionsLevel; + private SerializedProperty m_ReflectionsDelay; + private SerializedProperty m_ReverbLevel; + private SerializedProperty m_ReverbDelay; + private SerializedProperty m_HFReference; + private SerializedProperty m_LFReference; + private SerializedProperty m_Diffusion; + private SerializedProperty m_Density; + private void OnEnable() + { + this.m_ReverbPreset = base.serializedObject.FindProperty("m_ReverbPreset"); + this.m_DryLevel = base.serializedObject.FindProperty("m_DryLevel"); + this.m_Room = base.serializedObject.FindProperty("m_Room"); + this.m_RoomHF = base.serializedObject.FindProperty("m_RoomHF"); + this.m_RoomLF = base.serializedObject.FindProperty("m_RoomLF"); + this.m_DecayTime = base.serializedObject.FindProperty("m_DecayTime"); + this.m_DecayHFRatio = base.serializedObject.FindProperty("m_DecayHFRatio"); + this.m_ReflectionsLevel = base.serializedObject.FindProperty("m_ReflectionsLevel"); + this.m_ReflectionsDelay = base.serializedObject.FindProperty("m_ReflectionsDelay"); + this.m_ReverbLevel = base.serializedObject.FindProperty("m_ReverbLevel"); + this.m_ReverbDelay = base.serializedObject.FindProperty("m_ReverbDelay"); + this.m_HFReference = base.serializedObject.FindProperty("m_HFReference"); + this.m_LFReference = base.serializedObject.FindProperty("m_LFReference"); + this.m_Diffusion = base.serializedObject.FindProperty("m_Diffusion"); + this.m_Density = base.serializedObject.FindProperty("m_Density"); + } + public override void OnInspectorGUI() + { + if (!Application.HasAdvancedLicense()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent content = new GUIContent("This is only available in the Pro version of Unity."); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + base.serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_ReverbPreset, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + base.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.BeginDisabledGroup(this.m_ReverbPreset.enumValueIndex != 27 || this.m_ReverbPreset.hasMultipleDifferentValues); + EditorGUILayout.Slider(this.m_DryLevel, -10000f, 0f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Room, -10000f, 0f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_RoomHF, -10000f, 0f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_RoomLF, -10000f, 0f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_DecayTime, 0.1f, 20f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_DecayHFRatio, 0.1f, 2f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReflectionsLevel, -10000f, 1000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReflectionsDelay, 0f, 0.3f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReverbLevel, -10000f, 2000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReverbDelay, 0f, 0.1f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_HFReference, 1000f, 20000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_LFReference, 20f, 1000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Diffusion, 0f, 100f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Density, 0f, 100f, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioReverbZoneEditor.cs b/UnityEditor/UnityEditor/AudioReverbZoneEditor.cs new file mode 100644 index 00000000..0866f3f0 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioReverbZoneEditor.cs @@ -0,0 +1,100 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioReverbZone))] + internal class AudioReverbZoneEditor : Editor + { + private SerializedProperty m_MinDistance; + private SerializedProperty m_MaxDistance; + private SerializedProperty m_ReverbPreset; + private SerializedProperty m_Room; + private SerializedProperty m_RoomHF; + private SerializedProperty m_RoomLF; + private SerializedProperty m_DecayTime; + private SerializedProperty m_DecayHFRatio; + private SerializedProperty m_Reflections; + private SerializedProperty m_ReflectionsDelay; + private SerializedProperty m_Reverb; + private SerializedProperty m_ReverbDelay; + private SerializedProperty m_HFReference; + private SerializedProperty m_LFReference; + private SerializedProperty m_RoomRolloffFactor; + private SerializedProperty m_Diffusion; + private SerializedProperty m_Density; + private void OnEnable() + { + this.m_MinDistance = base.serializedObject.FindProperty("m_MinDistance"); + this.m_MaxDistance = base.serializedObject.FindProperty("m_MaxDistance"); + this.m_ReverbPreset = base.serializedObject.FindProperty("m_ReverbPreset"); + this.m_Room = base.serializedObject.FindProperty("m_Room"); + this.m_RoomHF = base.serializedObject.FindProperty("m_RoomHF"); + this.m_RoomLF = base.serializedObject.FindProperty("m_RoomLF"); + this.m_DecayTime = base.serializedObject.FindProperty("m_DecayTime"); + this.m_DecayHFRatio = base.serializedObject.FindProperty("m_DecayHFRatio"); + this.m_Reflections = base.serializedObject.FindProperty("m_Reflections"); + this.m_ReflectionsDelay = base.serializedObject.FindProperty("m_ReflectionsDelay"); + this.m_Reverb = base.serializedObject.FindProperty("m_Reverb"); + this.m_ReverbDelay = base.serializedObject.FindProperty("m_ReverbDelay"); + this.m_HFReference = base.serializedObject.FindProperty("m_HFReference"); + this.m_LFReference = base.serializedObject.FindProperty("m_LFReference"); + this.m_RoomRolloffFactor = base.serializedObject.FindProperty("m_RoomRolloffFactor"); + this.m_Diffusion = base.serializedObject.FindProperty("m_Diffusion"); + this.m_Density = base.serializedObject.FindProperty("m_Density"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_MinDistance, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MaxDistance, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_ReverbPreset, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + base.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.BeginDisabledGroup(this.m_ReverbPreset.enumValueIndex != 27 || this.m_ReverbPreset.hasMultipleDifferentValues); + EditorGUILayout.IntSlider(this.m_Room, -10000, 0, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_RoomHF, -10000, 0, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_RoomLF, -10000, 0, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_DecayTime, 0.1f, 20f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_DecayHFRatio, 0.1f, 2f, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_Reflections, -10000, 1000, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReflectionsDelay, 0f, 0.3f, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_Reverb, -10000, 2000, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ReverbDelay, 0f, 0.1f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_HFReference, 1000f, 20000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_LFReference, 20f, 1000f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_RoomRolloffFactor, 0f, 10f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Diffusion, 0f, 100f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Density, 0f, 100f, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + base.serializedObject.ApplyModifiedProperties(); + } + private void OnSceneGUI() + { + AudioReverbZone audioReverbZone = (AudioReverbZone)this.target; + Color color = Handles.color; + if (audioReverbZone.enabled) + { + Handles.color = new Color(0.5f, 0.7f, 1f, 0.5f); + } + else + { + Handles.color = new Color(0.3f, 0.4f, 0.6f, 0.5f); + } + Vector3 position = audioReverbZone.transform.position; + EditorGUI.BeginChangeCheck(); + float minDistance = Handles.RadiusHandle(Quaternion.identity, position, audioReverbZone.minDistance, true); + float maxDistance = Handles.RadiusHandle(Quaternion.identity, position, audioReverbZone.maxDistance, true); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObject(audioReverbZone, "Reverb Distance"); + audioReverbZone.minDistance = minDistance; + audioReverbZone.maxDistance = maxDistance; + } + Handles.color = color; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioSourceInspector.cs b/UnityEditor/UnityEditor/AudioSourceInspector.cs new file mode 100644 index 00000000..36397b0b --- /dev/null +++ b/UnityEditor/UnityEditor/AudioSourceInspector.cs @@ -0,0 +1,650 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioSource))] + internal class AudioSourceInspector : Editor + { + private class AudioCurveWrapper + { + public AudioSourceInspector.AudioCurveType type; + public GUIContent legend; + public int id; + public Color color; + public SerializedProperty curveProp; + public int rangeMin; + public int rangeMax; + public AudioCurveWrapper(AudioSourceInspector.AudioCurveType type, string legend, int id, Color color, SerializedProperty curveProp, int rangeMin, int rangeMax) + { + this.type = type; + this.legend = new GUIContent(legend); + this.id = id; + this.color = color; + this.curveProp = curveProp; + this.rangeMin = rangeMin; + this.rangeMax = rangeMax; + } + } + private enum AudioCurveType + { + Volume, + Pan, + Lowpass, + Spread + } + internal class Styles + { + public GUIStyle labelStyle = "ProfilerBadge"; + public GUIContent rolloffLabel = new GUIContent("Volume Rolloff", "Which type of rolloff curve to use"); + public string controlledByCurveLabel = "Controlled by curve"; + public GUIContent panLevelLabel = new GUIContent("Pan Level", "Sets how much the 3d position affects the pan and attenuation of the sound. If PanLevel is 0, 3D panning and attenuation is ignored."); + public GUIContent spreadLabel = new GUIContent("Spread", "Sets the spread of a 3d sound in speaker space."); + } + private const int kRolloffCurveID = 0; + private const int kPanLevelCurveID = 1; + private const int kSpreadCurveID = 2; + private const int kLowPassCurveID = 3; + internal const float kMaxCutoffFrequency = 22000f; + private const float EPSILON = 0.0001f; + private SerializedProperty m_AudioClip; + private SerializedProperty m_PlayOnAwake; + private SerializedProperty m_Volume; + private SerializedProperty m_Pitch; + private SerializedProperty m_Loop; + private SerializedProperty m_Mute; + private SerializedProperty m_Priority; + private SerializedProperty m_PanLevel; + private SerializedProperty m_DopplerLevel; + private SerializedProperty m_MinDistance; + private SerializedProperty m_MaxDistance; + private SerializedProperty m_Pan2D; + private SerializedProperty m_RolloffMode; + private SerializedProperty m_BypassEffects; + private SerializedProperty m_BypassListenerEffects; + private SerializedProperty m_BypassReverbZones; + private SerializedObject m_LowpassObject; + private SerializedProperty m_CutoffFrequency; + private AudioSourceInspector.AudioCurveWrapper[] m_AudioCurves; + private CurveEditor m_CurveEditor; + private Vector3 m_LastListenerPosition; + private static CurveEditorSettings m_CurveEditorSettings = new CurveEditorSettings(); + internal static Color kRolloffCurveColor = new Color(0.9f, 0.3f, 0.2f, 1f); + internal static Color kPanLevelCurveColor = new Color(0.25f, 0.7f, 0.2f, 1f); + internal static Color kSpreadCurveColor = new Color(0.25f, 0.55f, 0.95f, 1f); + internal static Color kLowPassCurveColor = new Color(0.8f, 0.25f, 0.9f, 1f); + internal bool[] m_SelectedCurves = new bool[0]; + private bool m_Expanded3D; + private bool m_Expanded2D; + private static AudioSourceInspector.Styles ms_Styles; + private void OnEnable() + { + this.m_AudioClip = base.serializedObject.FindProperty("m_audioClip"); + this.m_PlayOnAwake = base.serializedObject.FindProperty("m_PlayOnAwake"); + this.m_Volume = base.serializedObject.FindProperty("m_Volume"); + this.m_Pitch = base.serializedObject.FindProperty("m_Pitch"); + this.m_Loop = base.serializedObject.FindProperty("Loop"); + this.m_Mute = base.serializedObject.FindProperty("Mute"); + this.m_Priority = base.serializedObject.FindProperty("Priority"); + this.m_DopplerLevel = base.serializedObject.FindProperty("DopplerLevel"); + this.m_MinDistance = base.serializedObject.FindProperty("MinDistance"); + this.m_MaxDistance = base.serializedObject.FindProperty("MaxDistance"); + this.m_Pan2D = base.serializedObject.FindProperty("Pan2D"); + this.m_RolloffMode = base.serializedObject.FindProperty("rolloffMode"); + this.m_BypassEffects = base.serializedObject.FindProperty("BypassEffects"); + this.m_BypassListenerEffects = base.serializedObject.FindProperty("BypassListenerEffects"); + this.m_BypassReverbZones = base.serializedObject.FindProperty("BypassReverbZones"); + this.m_AudioCurves = new AudioSourceInspector.AudioCurveWrapper[] + { + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Volume, "Volume", 0, AudioSourceInspector.kRolloffCurveColor, base.serializedObject.FindProperty("rolloffCustomCurve"), 0, 1), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Pan, "Pan", 1, AudioSourceInspector.kPanLevelCurveColor, base.serializedObject.FindProperty("panLevelCustomCurve"), 0, 1), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Spread, "Spread", 2, AudioSourceInspector.kSpreadCurveColor, base.serializedObject.FindProperty("spreadCustomCurve"), 0, 1), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Lowpass, "Low-Pass", 3, AudioSourceInspector.kLowPassCurveColor, null, 0, 1) + }; + AudioSourceInspector.m_CurveEditorSettings.hRangeMin = 0f; + AudioSourceInspector.m_CurveEditorSettings.vRangeMin = 0f; + AudioSourceInspector.m_CurveEditorSettings.vRangeMax = 1f; + AudioSourceInspector.m_CurveEditorSettings.hRangeMax = 1f; + AudioSourceInspector.m_CurveEditorSettings.vSlider = false; + AudioSourceInspector.m_CurveEditorSettings.hSlider = false; + TickStyle tickStyle = new TickStyle(); + tickStyle.color = new Color(0f, 0f, 0f, 0.15f); + tickStyle.distLabel = 30; + AudioSourceInspector.m_CurveEditorSettings.hTickStyle = tickStyle; + TickStyle tickStyle2 = new TickStyle(); + tickStyle2.color = new Color(0f, 0f, 0f, 0.15f); + tickStyle2.distLabel = 20; + AudioSourceInspector.m_CurveEditorSettings.vTickStyle = tickStyle2; + this.m_CurveEditor = new CurveEditor(new Rect(0f, 0f, 1000f, 100f), new CurveWrapper[0], false); + this.m_CurveEditor.settings = AudioSourceInspector.m_CurveEditorSettings; + this.m_CurveEditor.margin = 25f; + this.m_CurveEditor.SetShownHRangeInsideMargins(0f, 1f); + this.m_CurveEditor.SetShownVRangeInsideMargins(0f, 1f); + this.m_CurveEditor.ignoreScrollWheelUntilClicked = true; + this.m_LastListenerPosition = AudioUtil.GetListenerPos(); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.m_Expanded2D = EditorPrefs.GetBool("AudioSourceExpanded2D", this.m_Expanded2D); + this.m_Expanded3D = EditorPrefs.GetBool("AudioSourceExpanded3D", this.m_Expanded3D); + } + private void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + EditorPrefs.SetBool("AudioSourceExpanded2D", this.m_Expanded2D); + EditorPrefs.SetBool("AudioSourceExpanded3D", this.m_Expanded3D); + } + private CurveWrapper[] GetCurveWrapperArray() + { + List list = new List(); + AudioSourceInspector.AudioCurveWrapper[] audioCurves = this.m_AudioCurves; + for (int i = 0; i < audioCurves.Length; i++) + { + AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = audioCurves[i]; + if (audioCurveWrapper.curveProp != null) + { + AnimationCurve animationCurve = audioCurveWrapper.curveProp.animationCurveValue; + bool flag; + if (audioCurveWrapper.type == AudioSourceInspector.AudioCurveType.Volume) + { + AudioRolloffMode enumValueIndex = (AudioRolloffMode)this.m_RolloffMode.enumValueIndex; + if (this.m_RolloffMode.hasMultipleDifferentValues) + { + flag = false; + } + else + { + if (enumValueIndex == AudioRolloffMode.Custom) + { + flag = !audioCurveWrapper.curveProp.hasMultipleDifferentValues; + } + else + { + flag = (!this.m_MinDistance.hasMultipleDifferentValues && !this.m_MaxDistance.hasMultipleDifferentValues); + if (enumValueIndex == AudioRolloffMode.Linear) + { + animationCurve = AnimationCurve.Linear(this.m_MinDistance.floatValue / this.m_MaxDistance.floatValue, 1f, 1f, 0f); + } + else + { + if (enumValueIndex == AudioRolloffMode.Logarithmic) + { + animationCurve = AudioSourceInspector.Logarithmic(this.m_MinDistance.floatValue / this.m_MaxDistance.floatValue, 1f, 1f); + } + } + } + } + } + else + { + flag = !audioCurveWrapper.curveProp.hasMultipleDifferentValues; + } + if (flag) + { + if (animationCurve.length == 0) + { + Debug.LogError(audioCurveWrapper.legend.text + " curve has no keys!"); + } + else + { + list.Add(this.GetCurveWrapper(animationCurve, audioCurveWrapper)); + } + } + } + } + return list.ToArray(); + } + private CurveWrapper GetCurveWrapper(AnimationCurve curve, AudioSourceInspector.AudioCurveWrapper audioCurve) + { + float num = EditorGUIUtility.isProSkin ? 1f : 0.9f; + Color b = new Color(num, num, num, 1f); + CurveWrapper curveWrapper = new CurveWrapper(); + curveWrapper.id = audioCurve.id; + curveWrapper.groupId = -1; + curveWrapper.color = audioCurve.color * b; + curveWrapper.hidden = false; + curveWrapper.readOnly = false; + curveWrapper.renderer = new NormalCurveRenderer(curve); + curveWrapper.renderer.SetCustomRange(0f, 1f); + curveWrapper.getAxisUiScalarsCallback = new CurveWrapper.GetAxisScalarsCallback(this.GetAxisScalars); + return curveWrapper; + } + public Vector2 GetAxisScalars() + { + return new Vector2(this.m_MaxDistance.floatValue, 1f); + } + private static float LogarithmicValue(float distance, float minDistance, float rolloffScale) + { + if (distance > minDistance && rolloffScale != 1f) + { + distance -= minDistance; + distance *= rolloffScale; + distance += minDistance; + } + if (distance < 1E-06f) + { + distance = 1E-06f; + } + return minDistance / distance; + } + private static AnimationCurve Logarithmic(float timeStart, float timeEnd, float logBase) + { + List list = new List(); + float num = 2f; + timeStart = Mathf.Max(timeStart, 0.0001f); + float value; + float num3; + float num4; + for (float num2 = timeStart; num2 < timeEnd; num2 *= num) + { + value = AudioSourceInspector.LogarithmicValue(num2, timeStart, logBase); + num3 = num2 / 50f; + num4 = (AudioSourceInspector.LogarithmicValue(num2 + num3, timeStart, logBase) - AudioSourceInspector.LogarithmicValue(num2 - num3, timeStart, logBase)) / (num3 * 2f); + list.Add(new Keyframe(num2, value, num4, num4)); + } + value = AudioSourceInspector.LogarithmicValue(timeEnd, timeStart, logBase); + num3 = timeEnd / 50f; + num4 = (AudioSourceInspector.LogarithmicValue(timeEnd + num3, timeStart, logBase) - AudioSourceInspector.LogarithmicValue(timeEnd - num3, timeStart, logBase)) / (num3 * 2f); + list.Add(new Keyframe(timeEnd, value, num4, num4)); + return new AnimationCurve(list.ToArray()); + } + internal void InitStyles() + { + if (AudioSourceInspector.ms_Styles == null) + { + AudioSourceInspector.ms_Styles = new AudioSourceInspector.Styles(); + } + } + private void Update() + { + Vector3 listenerPos = AudioUtil.GetListenerPos(); + if ((this.m_LastListenerPosition - listenerPos).sqrMagnitude > 0.0001f) + { + this.m_LastListenerPosition = listenerPos; + base.Repaint(); + } + } + private void UndoRedoPerformed() + { + this.m_CurveEditor.animationCurves = this.GetCurveWrapperArray(); + } + private void HandleLowPassFilter() + { + AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = this.m_AudioCurves[3]; + AudioLowPassFilter[] array = new AudioLowPassFilter[base.targets.Length]; + for (int i = 0; i < base.targets.Length; i++) + { + array[i] = ((AudioSource)base.targets[i]).GetComponent(); + if (array[i] == null) + { + this.m_LowpassObject = null; + audioCurveWrapper.curveProp = null; + this.m_CutoffFrequency = null; + return; + } + } + if (audioCurveWrapper.curveProp == null) + { + this.m_LowpassObject = new SerializedObject(array); + this.m_CutoffFrequency = this.m_LowpassObject.FindProperty("m_CutoffFrequency"); + audioCurveWrapper.curveProp = this.m_LowpassObject.FindProperty("lowpassLevelCustomCurve"); + } + } + public override void OnInspectorGUI() + { + bool updateWrappers = false; + this.InitStyles(); + base.serializedObject.Update(); + if (this.m_LowpassObject != null) + { + this.m_LowpassObject.Update(); + } + this.HandleLowPassFilter(); + AudioSourceInspector.AudioCurveWrapper[] audioCurves = this.m_AudioCurves; + for (int i = 0; i < audioCurves.Length; i++) + { + AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = audioCurves[i]; + CurveWrapper curveWrapperById = this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id); + if (audioCurveWrapper.curveProp != null) + { + AnimationCurve animationCurveValue = audioCurveWrapper.curveProp.animationCurveValue; + if (curveWrapperById == null != audioCurveWrapper.curveProp.hasMultipleDifferentValues) + { + updateWrappers = true; + } + else + { + if (curveWrapperById != null) + { + if (curveWrapperById.curve.length == 0) + { + updateWrappers = true; + } + else + { + if (animationCurveValue.length >= 1 && animationCurveValue.keys[0].value != curveWrapperById.curve.keys[0].value) + { + updateWrappers = true; + } + } + } + } + } + else + { + if (curveWrapperById != null) + { + updateWrappers = true; + } + } + } + this.UpdateWrappersAndLegend(ref updateWrappers); + EditorGUILayout.PropertyField(this.m_AudioClip, new GUILayoutOption[0]); + if (!this.m_AudioClip.hasMultipleDifferentValues && this.m_AudioClip.objectReferenceValue != null) + { + string t; + if (AudioUtil.Is3D(this.m_AudioClip.objectReferenceValue as AudioClip)) + { + t = "This is a 3D Sound."; + } + else + { + t = "This is a 2D Sound."; + } + EditorGUILayout.LabelField(EditorGUIUtility.blankContent, EditorGUIUtility.TempContent(t), EditorStyles.helpBox, new GUILayoutOption[0]); + } + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_Mute, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BypassEffects, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BypassListenerEffects, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BypassReverbZones, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PlayOnAwake, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Loop, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.IntSlider(this.m_Priority, 0, 256, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.Slider(this.m_Volume, 0f, 1f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Pitch, -3f, 3f, new GUILayoutOption[0]); + EditorGUILayout.Space(); + this.m_Expanded3D = EditorGUILayout.Foldout(this.m_Expanded3D, "3D Sound Settings"); + if (this.m_Expanded3D) + { + EditorGUI.indentLevel++; + this.Audio3DGUI(updateWrappers); + EditorGUI.indentLevel--; + } + this.m_Expanded2D = EditorGUILayout.Foldout(this.m_Expanded2D, "2D Sound Settings"); + if (this.m_Expanded2D) + { + EditorGUI.indentLevel++; + this.Audio2DGUI(); + EditorGUI.indentLevel--; + } + base.serializedObject.ApplyModifiedProperties(); + if (this.m_LowpassObject != null) + { + this.m_LowpassObject.ApplyModifiedProperties(); + } + } + private static void SetRolloffToTarget(SerializedProperty property, UnityEngine.Object target) + { + property.SetToValueOfTarget(target); + property.serializedObject.FindProperty("rolloffMode").SetToValueOfTarget(target); + property.serializedObject.ApplyModifiedProperties(); + EditorUtility.ForceReloadInspectors(); + } + private void Audio3DGUI(bool updateWrappers) + { + EditorGUILayout.Slider(this.m_DopplerLevel, 0f, 5f, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + if (this.m_RolloffMode.hasMultipleDifferentValues || (this.m_RolloffMode.enumValueIndex == 2 && this.m_AudioCurves[0].curveProp.hasMultipleDifferentValues)) + { + EditorGUILayout.TargetChoiceField(this.m_AudioCurves[0].curveProp, AudioSourceInspector.ms_Styles.rolloffLabel, new TargetChoiceHandler.TargetChoiceMenuFunction(AudioSourceInspector.SetRolloffToTarget), new GUILayoutOption[0]); + } + else + { + EditorGUILayout.PropertyField(this.m_RolloffMode, AudioSourceInspector.ms_Styles.rolloffLabel, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + if (this.m_RolloffMode.enumValueIndex != 2) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_MinDistance, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_MinDistance.floatValue = Mathf.Clamp(this.m_MinDistance.floatValue, 0f, this.m_MaxDistance.floatValue / 1.01f); + } + } + else + { + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.LabelField(this.m_MinDistance.displayName, AudioSourceInspector.ms_Styles.controlledByCurveLabel, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + } + EditorGUI.indentLevel--; + } + AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.panLevelLabel, this.m_AudioCurves[1].curveProp, 0f, 1f); + AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spreadLabel, this.m_AudioCurves[2].curveProp, 0f, 360f); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_MaxDistance, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_MaxDistance.floatValue = Mathf.Min(Mathf.Max(Mathf.Max(this.m_MaxDistance.floatValue, 0.01f), this.m_MinDistance.floatValue * 1.01f), 1000000f); + } + if (EditorGUI.EndChangeCheck()) + { + updateWrappers = true; + } + Rect aspectRect = GUILayoutUtility.GetAspectRect(1.333f, GUI.skin.textField); + aspectRect.xMin += EditorGUI.indent; + if (Event.current.type != EventType.Layout && Event.current.type != EventType.Used) + { + this.m_CurveEditor.rect = new Rect(aspectRect.x, aspectRect.y, aspectRect.width, aspectRect.height); + } + this.UpdateWrappersAndLegend(ref updateWrappers); + GUI.Label(this.m_CurveEditor.drawRect, GUIContent.none, "TextField"); + this.m_CurveEditor.hRangeLocked = Event.current.shift; + this.m_CurveEditor.vRangeLocked = EditorGUI.actionKey; + this.m_CurveEditor.OnGUI(); + if (base.targets.Length == 1) + { + AudioSource audioSource = (AudioSource)this.target; + AudioListener x = (AudioListener)UnityEngine.Object.FindObjectOfType(typeof(AudioListener)); + if (x != null) + { + float magnitude = (AudioUtil.GetListenerPos() - audioSource.transform.position).magnitude; + this.DrawLabel("Listener", magnitude, aspectRect); + } + } + this.DrawLegend(); + AudioSourceInspector.AudioCurveWrapper[] audioCurves = this.m_AudioCurves; + for (int i = 0; i < audioCurves.Length; i++) + { + AudioSourceInspector.AudioCurveWrapper audioCurveWrapper = audioCurves[i]; + if (this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id) != null && this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).changed) + { + AnimationCurve curve = this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).curve; + if (curve.length > 0) + { + audioCurveWrapper.curveProp.animationCurveValue = curve; + this.m_CurveEditor.getCurveWrapperById(audioCurveWrapper.id).changed = false; + if (audioCurveWrapper.type == AudioSourceInspector.AudioCurveType.Volume) + { + this.m_RolloffMode.enumValueIndex = 2; + } + if (audioCurveWrapper.type == AudioSourceInspector.AudioCurveType.Lowpass && audioCurveWrapper.curveProp.animationCurveValue.length == 1) + { + Keyframe keyframe = audioCurveWrapper.curveProp.animationCurveValue.keys[0]; + this.m_CutoffFrequency.floatValue = (1f - keyframe.value) * 22000f; + } + } + } + } + } + private void UpdateWrappersAndLegend(ref bool updateWrappers) + { + if (updateWrappers) + { + this.m_CurveEditor.animationCurves = this.GetCurveWrapperArray(); + this.SyncShownCurvesToLegend(this.GetShownAudioCurves()); + updateWrappers = false; + } + } + private void DrawLegend() + { + List list = new List(); + List shownAudioCurves = this.GetShownAudioCurves(); + Rect rect = GUILayoutUtility.GetRect(10f, 20f); + rect.x += 4f + EditorGUI.indent; + rect.width -= 8f + EditorGUI.indent; + int num = Mathf.Min(75, Mathf.FloorToInt(rect.width / (float)shownAudioCurves.Count)); + for (int i = 0; i < shownAudioCurves.Count; i++) + { + list.Add(new Rect(rect.x + (float)(num * i), rect.y, (float)num, rect.height)); + } + bool flag = false; + if (shownAudioCurves.Count != this.m_SelectedCurves.Length) + { + this.m_SelectedCurves = new bool[shownAudioCurves.Count]; + flag = true; + } + if (EditorGUIExt.DragSelection(list.ToArray(), ref this.m_SelectedCurves, GUIStyle.none) || flag) + { + bool flag2 = false; + for (int j = 0; j < shownAudioCurves.Count; j++) + { + if (this.m_SelectedCurves[j]) + { + flag2 = true; + } + } + if (!flag2) + { + for (int k = 0; k < shownAudioCurves.Count; k++) + { + this.m_SelectedCurves[k] = true; + } + } + this.SyncShownCurvesToLegend(shownAudioCurves); + } + for (int l = 0; l < shownAudioCurves.Count; l++) + { + EditorGUI.DrawLegend(list[l], shownAudioCurves[l].color, shownAudioCurves[l].legend.text, this.m_SelectedCurves[l]); + if (shownAudioCurves[l].curveProp.hasMultipleDifferentValues) + { + GUI.Button(new Rect(list[l].x, list[l].y + 20f, list[l].width, 20f), "Different"); + } + } + } + private void Audio2DGUI() + { + EditorGUILayout.Slider(this.m_Pan2D, -1f, 1f, new GUILayoutOption[0]); + } + private List GetShownAudioCurves() + { + return ( + from f in this.m_AudioCurves + where this.m_CurveEditor.getCurveWrapperById(f.id) != null + select f).ToList(); + } + private void SyncShownCurvesToLegend(List curves) + { + if (curves.Count != this.m_SelectedCurves.Length) + { + return; + } + for (int i = 0; i < curves.Count; i++) + { + this.m_CurveEditor.getCurveWrapperById(curves[i].id).hidden = !this.m_SelectedCurves[i]; + } + this.m_CurveEditor.animationCurves = this.m_CurveEditor.animationCurves; + } + private void DrawLabel(string label, float value, Rect r) + { + Vector2 vector = AudioSourceInspector.ms_Styles.labelStyle.CalcSize(new GUIContent(label)); + vector.x += 2f; + Vector2 vector2 = this.m_CurveEditor.DrawingToViewTransformPoint(new Vector2(value / this.m_MaxDistance.floatValue, 0f)); + Vector2 vector3 = this.m_CurveEditor.DrawingToViewTransformPoint(new Vector2(value / this.m_MaxDistance.floatValue, 1f)); + GUI.BeginGroup(r); + Color color = Handles.color; + Handles.color = new Color(1f, 0f, 0f, 0.3f); + Handles.DrawLine(new Vector3(vector2.x, vector2.y, 0f), new Vector3(vector3.x, vector3.y, 0f)); + Handles.DrawLine(new Vector3(vector2.x + 1f, vector2.y, 0f), new Vector3(vector3.x + 1f, vector3.y, 0f)); + Handles.color = color; + GUI.Label(new Rect(Mathf.Floor(vector3.x - vector.x / 2f), 2f, vector.x, 15f), label, AudioSourceInspector.ms_Styles.labelStyle); + GUI.EndGroup(); + } + internal static void AnimProp(GUIContent label, SerializedProperty prop, float min, float max) + { + if (prop.hasMultipleDifferentValues) + { + EditorGUILayout.TargetChoiceField(prop, label, new GUILayoutOption[0]); + return; + } + AnimationCurve animationCurveValue = prop.animationCurveValue; + if (animationCurveValue == null) + { + Debug.LogError(label.text + " curve is null!"); + return; + } + if (animationCurveValue.length == 0) + { + Debug.LogError(label.text + " curve has no keys!"); + return; + } + if (animationCurveValue.length != 1) + { + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.LabelField(label.text, "Controlled by Curve", new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + } + else + { + float num = Mathf.Lerp(min, max, animationCurveValue.keys[0].value); + num = MathUtils.DiscardLeastSignificantDecimal(num); + EditorGUI.BeginChangeCheck(); + if (max > min) + { + num = EditorGUILayout.Slider(label, num, min, max, new GUILayoutOption[0]); + } + else + { + num = EditorGUILayout.Slider(label, num, max, min, new GUILayoutOption[0]); + } + if (EditorGUI.EndChangeCheck()) + { + Keyframe key = animationCurveValue.keys[0]; + key.time = 0f; + key.value = Mathf.InverseLerp(min, max, num); + animationCurveValue.MoveKey(0, key); + } + } + prop.animationCurveValue = animationCurveValue; + } + private void OnSceneGUI() + { + AudioSource audioSource = (AudioSource)this.target; + Color color = Handles.color; + if (audioSource.enabled) + { + Handles.color = new Color(0.5f, 0.7f, 1f, 0.5f); + } + else + { + Handles.color = new Color(0.3f, 0.4f, 0.6f, 0.5f); + } + Vector3 position = audioSource.transform.position; + EditorGUI.BeginChangeCheck(); + float minDistance = Handles.RadiusHandle(Quaternion.identity, position, audioSource.minDistance, true); + float maxDistance = Handles.RadiusHandle(Quaternion.identity, position, audioSource.maxDistance, true); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObject(audioSource, "AudioSource Distance"); + audioSource.minDistance = minDistance; + audioSource.maxDistance = maxDistance; + } + Handles.color = color; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioUtil.cs b/UnityEditor/UnityEditor/AudioUtil.cs new file mode 100644 index 00000000..6d41ab1f --- /dev/null +++ b/UnityEditor/UnityEditor/AudioUtil.cs @@ -0,0 +1,143 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + internal sealed class AudioUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PlayClip(AudioClip clip, [DefaultValue("0")] int startSample, [DefaultValue("false")] bool loop); + [ExcludeFromDocs] + public static void PlayClip(AudioClip clip, int startSample) + { + bool loop = false; + AudioUtil.PlayClip(clip, startSample, loop); + } + [ExcludeFromDocs] + public static void PlayClip(AudioClip clip) + { + bool loop = false; + int startSample = 0; + AudioUtil.PlayClip(clip, startSample, loop); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopClip(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PauseClip(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResumeClip(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoopClip(AudioClip clip, bool on); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsClipPlaying(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopAllClips(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetClipPosition(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetClipSamplePosition(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetClipSamplePosition(AudioClip clip, int iSamplePosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetSampleCount(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetChannelCount(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetBitRate(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetBitsPerSample(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrequency(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetSoundSize(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetWaveForm(AudioClip clip, AudioImporter importer, int channel, float width, float height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetWaveFormFast(AudioClip clip, int channel, int fromSample, int toSample, float width, float height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearWaveForm(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasPreview(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsCompressed(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsStreamed(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double GetDuration(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFMODMemoryAllocated(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetFMODCPUUsage(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Is3D(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsMovieAudio(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsMOD(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetMODChannelCount(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimationCurve GetLowpassCurve(AudioLowPassFilter lowPassFilter); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector3 GetListenerPos(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UpdateAudio(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetListenerTransform(Transform t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AudioType GetClipType(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AudioType GetPlatformConversionType(AudioType inType, BuildTargetGroup targetGroup, AudioImporterFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HaveAudioCallback(MonoBehaviour behaviour); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetCustomFilterChannelCount(MonoBehaviour behaviour); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetCustomFilterProcessTime(MonoBehaviour behaviour); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetCustomFilterMaxIn(MonoBehaviour behaviour, int channel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetCustomFilterMaxOut(MonoBehaviour behaviour, int channel); + } +} diff --git a/UnityEditor/UnityEditor/AvatarAutoMapper.cs b/UnityEditor/UnityEditor/AvatarAutoMapper.cs new file mode 100644 index 00000000..5efce2e4 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarAutoMapper.cs @@ -0,0 +1,1095 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + internal class AvatarAutoMapper + { + private enum Side + { + None, + Left, + Right + } + private struct BoneMappingItem + { + public int parent; + public int bone; + public int minStep; + public int maxStep; + public float lengthRatio; + public Vector3 dir; + public AvatarAutoMapper.Side side; + public bool optional; + public bool alwaysInclude; + public string[] keywords; + private int[] children; + public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Vector3 dir, AvatarAutoMapper.Side side, bool optional, bool alwaysInclude, params string[] keywords) + { + this.parent = parent; + this.bone = bone; + this.minStep = minStep; + this.maxStep = maxStep; + this.lengthRatio = lengthRatio; + this.dir = dir; + this.side = side; + this.optional = optional; + this.alwaysInclude = alwaysInclude; + this.keywords = keywords; + this.children = null; + } + public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, AvatarAutoMapper.Side side, bool optional, bool alwaysInclude, params string[] keywords) + { + this = new AvatarAutoMapper.BoneMappingItem(parent, bone, minStep, maxStep, lengthRatio, Vector3.zero, side, optional, alwaysInclude, keywords); + } + public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, Vector3 dir, AvatarAutoMapper.Side side, params string[] keywords) + { + this = new AvatarAutoMapper.BoneMappingItem(parent, bone, minStep, maxStep, lengthRatio, dir, side, false, false, keywords); + } + public BoneMappingItem(int parent, int bone, int minStep, int maxStep, float lengthRatio, AvatarAutoMapper.Side side, params string[] keywords) + { + this = new AvatarAutoMapper.BoneMappingItem(parent, bone, minStep, maxStep, lengthRatio, Vector3.zero, side, false, false, keywords); + } + public int[] GetChildren(AvatarAutoMapper.BoneMappingItem[] mappingData) + { + if (this.children == null) + { + List list = new List(); + for (int i = 0; i < mappingData.Length; i++) + { + if (mappingData[i].parent == this.bone) + { + list.Add(i); + } + } + this.children = list.ToArray(); + } + return this.children; + } + } + private class BoneMatch : IComparable + { + public AvatarAutoMapper.BoneMatch parent; + public List children = new List(); + public bool doMap; + public AvatarAutoMapper.BoneMappingItem item; + public Transform bone; + public float score; + public float siblingScore; + public List debugTracker = new List(); + public AvatarAutoMapper.BoneMatch humanBoneParent + { + get + { + AvatarAutoMapper.BoneMatch boneMatch = this.parent; + while (boneMatch.parent != null && boneMatch.item.bone < 0) + { + boneMatch = boneMatch.parent; + } + return boneMatch; + } + } + public float totalSiblingScore + { + get + { + return this.score + this.siblingScore; + } + } + public BoneMatch(AvatarAutoMapper.BoneMatch parent, Transform bone, AvatarAutoMapper.BoneMappingItem item) + { + this.parent = parent; + this.bone = bone; + this.item = item; + } + public int CompareTo(AvatarAutoMapper.BoneMatch other) + { + if (other == null) + { + return 1; + } + return other.totalSiblingScore.CompareTo(this.totalSiblingScore); + } + } + private struct QueuedBone + { + public Transform bone; + public int level; + public QueuedBone(Transform bone, int level) + { + this.bone = bone; + this.level = level; + } + } + private const string kLeftMatch = "(^|.*[ \\.:_-])[lL]($|[ \\.:_-].*)"; + private const string kRightMatch = "(^|.*[ \\.:_-])[rR]($|[ \\.:_-].*)"; + private static bool kDebug = false; + private static string[] kShoulderKeywords = new string[] + { + "shoulder", + "collar", + "clavicle" + }; + private static string[] kUpperArmKeywords = new string[] + { + "up" + }; + private static string[] kLowerArmKeywords = new string[] + { + "lo", + "fore", + "elbow" + }; + private static string[] kHandKeywords = new string[] + { + "hand", + "wrist" + }; + private static string[] kUpperLegKeywords = new string[] + { + "up", + "thigh" + }; + private static string[] kLowerLegKeywords = new string[] + { + "lo", + "calf", + "knee", + "shin" + }; + private static string[] kFootKeywords = new string[] + { + "foot", + "ankle" + }; + private static string[] kToeKeywords = new string[] + { + "toe", + "!end", + "!top", + "!nub" + }; + private static string[] kNeckKeywords = new string[] + { + "neck" + }; + private static string[] kHeadKeywords = new string[] + { + "head" + }; + private static string[] kJawKeywords = new string[] + { + "jaw", + "open", + "!teeth", + "!tongue", + "!pony", + "!braid", + "!end", + "!top", + "!nub" + }; + private static string[] kEyeKeywords = new string[] + { + "eye", + "ball", + "!brow", + "!lid", + "!pony", + "!braid", + "!end", + "!top", + "!nub" + }; + private static string[] kThumbKeywords = new string[] + { + "thu", + "!palm", + "!wrist", + "!end", + "!top", + "!nub" + }; + private static string[] kIndexFingerKeywords = new string[] + { + "ind", + "point", + "!palm", + "!wrist", + "!end", + "!top", + "!nub" + }; + private static string[] kMiddleFingerKeywords = new string[] + { + "mid", + "long", + "!palm", + "!wrist", + "!end", + "!top", + "!nub" + }; + private static string[] kRingFingerKeywords = new string[] + { + "rin", + "!palm", + "!wrist", + "!end", + "!top", + "!nub" + }; + private static string[] kLittleFingerKeywords = new string[] + { + "lit", + "pin", + "!palm", + "!wrist", + "!end", + "!top", + "!nub" + }; + private static AvatarAutoMapper.BoneMappingItem[] s_MappingDataBody = new AvatarAutoMapper.BoneMappingItem[] + { + new AvatarAutoMapper.BoneMappingItem(-1, 0, 1, 3, 0f, AvatarAutoMapper.Side.None, new string[0]), + new AvatarAutoMapper.BoneMappingItem(0, 2, 1, 2, 0f, Vector3.right, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kUpperLegKeywords), + new AvatarAutoMapper.BoneMappingItem(2, 4, 1, 2, 3f, -Vector3.up, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kLowerLegKeywords), + new AvatarAutoMapper.BoneMappingItem(4, 6, 1, 2, 1f, -Vector3.up, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kFootKeywords), + new AvatarAutoMapper.BoneMappingItem(6, 20, 1, 2, 0.5f, Vector3.forward, AvatarAutoMapper.Side.Right, true, true, AvatarAutoMapper.kToeKeywords), + new AvatarAutoMapper.BoneMappingItem(0, 7, 1, 3, 0f, Vector3.up, AvatarAutoMapper.Side.None, new string[0]), + new AvatarAutoMapper.BoneMappingItem(7, 8, 0, 3, 1.4f, Vector3.up, AvatarAutoMapper.Side.None, true, false, new string[0]), + new AvatarAutoMapper.BoneMappingItem(8, 12, 1, 3, 0f, Vector3.right, AvatarAutoMapper.Side.Right, true, false, AvatarAutoMapper.kShoulderKeywords), + new AvatarAutoMapper.BoneMappingItem(12, 14, 0, 2, 0.5f, Vector3.right, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kUpperArmKeywords), + new AvatarAutoMapper.BoneMappingItem(14, 16, 1, 2, 2f, Vector3.right, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kLowerArmKeywords), + new AvatarAutoMapper.BoneMappingItem(16, 18, 1, 2, 1f, Vector3.right, AvatarAutoMapper.Side.Right, AvatarAutoMapper.kHandKeywords), + new AvatarAutoMapper.BoneMappingItem(8, 9, 1, 3, 1.8f, Vector3.up, AvatarAutoMapper.Side.None, true, false, AvatarAutoMapper.kNeckKeywords), + new AvatarAutoMapper.BoneMappingItem(9, 10, 0, 2, 0.3f, Vector3.up, AvatarAutoMapper.Side.None, AvatarAutoMapper.kHeadKeywords), + new AvatarAutoMapper.BoneMappingItem(10, 23, 1, 2, 0f, Vector3.forward, AvatarAutoMapper.Side.None, true, false, AvatarAutoMapper.kJawKeywords), + new AvatarAutoMapper.BoneMappingItem(10, 22, 1, 2, 0f, new Vector3(1f, 1f, 1f), AvatarAutoMapper.Side.Right, true, false, AvatarAutoMapper.kEyeKeywords), + new AvatarAutoMapper.BoneMappingItem(18, -2, 1, 2, 0f, new Vector3(1f, -1f, 2f), AvatarAutoMapper.Side.Right, true, false, AvatarAutoMapper.kThumbKeywords), + new AvatarAutoMapper.BoneMappingItem(18, -3, 1, 2, 0f, new Vector3(3f, 0f, 1f), AvatarAutoMapper.Side.Right, true, false, AvatarAutoMapper.kIndexFingerKeywords) + }; + private static AvatarAutoMapper.BoneMappingItem[] s_LeftMappingDataHand = new AvatarAutoMapper.BoneMappingItem[] + { + new AvatarAutoMapper.BoneMappingItem(-2, -1, 1, 2, 0f, AvatarAutoMapper.Side.None, new string[0]), + new AvatarAutoMapper.BoneMappingItem(-1, 24, 1, 3, 0f, new Vector3(2f, 0f, 1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kThumbKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 27, 1, 3, 0f, new Vector3(4f, 0f, 1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kIndexFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 30, 1, 3, 0f, new Vector3(4f, 0f, 0f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kMiddleFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 33, 1, 3, 0f, new Vector3(4f, 0f, -1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kRingFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 36, 1, 3, 0f, new Vector3(4f, 0f, -2f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kLittleFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(24, 25, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(27, 28, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(30, 31, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(33, 34, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(36, 37, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(25, 26, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(28, 29, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(31, 32, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(34, 35, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(37, 38, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]) + }; + private static AvatarAutoMapper.BoneMappingItem[] s_RightMappingDataHand = new AvatarAutoMapper.BoneMappingItem[] + { + new AvatarAutoMapper.BoneMappingItem(-2, -1, 1, 2, 0f, AvatarAutoMapper.Side.None, new string[0]), + new AvatarAutoMapper.BoneMappingItem(-1, 39, 1, 3, 0f, new Vector3(2f, 0f, 1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kThumbKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 42, 1, 3, 0f, new Vector3(4f, 0f, 1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kIndexFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 45, 1, 3, 0f, new Vector3(4f, 0f, 0f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kMiddleFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 48, 1, 3, 0f, new Vector3(4f, 0f, -1f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kRingFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(-1, 51, 1, 3, 0f, new Vector3(4f, 0f, -2f), AvatarAutoMapper.Side.None, AvatarAutoMapper.kLittleFingerKeywords), + new AvatarAutoMapper.BoneMappingItem(39, 40, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(42, 43, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(45, 46, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(48, 49, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(51, 52, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(40, 41, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(43, 44, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(46, 47, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(49, 50, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]), + new AvatarAutoMapper.BoneMappingItem(52, 53, 1, 1, 0f, AvatarAutoMapper.Side.None, false, true, new string[0]) + }; + private static bool s_DidPerformInit = false; + private Dictionary m_ValidBones; + private bool m_TreatDummyBonesAsReal; + private Quaternion m_Orientation; + private int m_MappingIndexOffset; + private AvatarAutoMapper.BoneMappingItem[] m_MappingData; + private Dictionary m_BoneHasKeywordDict; + private Dictionary m_BoneHasBadKeywordDict; + private Dictionary m_BoneMatchDict; + public AvatarAutoMapper(Dictionary validBones) + { + this.m_BoneHasKeywordDict = new Dictionary(); + this.m_BoneHasBadKeywordDict = new Dictionary(); + this.m_BoneMatchDict = new Dictionary(); + this.m_ValidBones = validBones; + } + private static int GetLeftBoneIndexFromRight(int rightIndex) + { + if (rightIndex < 0) + { + return rightIndex; + } + if (rightIndex < 54) + { + string text = Enum.GetName(typeof(HumanBodyBones), rightIndex); + text = text.Replace("Right", "Left"); + return (int)Enum.Parse(typeof(HumanBodyBones), text); + } + return rightIndex + 24 - 39; + } + public static void InitGlobalMappingData() + { + if (AvatarAutoMapper.s_DidPerformInit) + { + return; + } + List list = new List(AvatarAutoMapper.s_MappingDataBody); + int count = list.Count; + for (int i = 0; i < count; i++) + { + AvatarAutoMapper.BoneMappingItem boneMappingItem = list[i]; + if (boneMappingItem.side == AvatarAutoMapper.Side.Right) + { + int leftBoneIndexFromRight = AvatarAutoMapper.GetLeftBoneIndexFromRight(boneMappingItem.bone); + int leftBoneIndexFromRight2 = AvatarAutoMapper.GetLeftBoneIndexFromRight(boneMappingItem.parent); + list.Add(new AvatarAutoMapper.BoneMappingItem(leftBoneIndexFromRight2, leftBoneIndexFromRight, boneMappingItem.minStep, boneMappingItem.maxStep, boneMappingItem.lengthRatio, new Vector3(-boneMappingItem.dir.x, boneMappingItem.dir.y, boneMappingItem.dir.z), AvatarAutoMapper.Side.Left, boneMappingItem.optional, boneMappingItem.alwaysInclude, boneMappingItem.keywords)); + } + } + AvatarAutoMapper.s_MappingDataBody = list.ToArray(); + for (int j = 0; j < AvatarAutoMapper.s_MappingDataBody.Length; j++) + { + AvatarAutoMapper.s_MappingDataBody[j].GetChildren(AvatarAutoMapper.s_MappingDataBody); + } + for (int k = 0; k < AvatarAutoMapper.s_LeftMappingDataHand.Length; k++) + { + AvatarAutoMapper.s_LeftMappingDataHand[k].GetChildren(AvatarAutoMapper.s_LeftMappingDataHand); + } + for (int l = 0; l < AvatarAutoMapper.s_RightMappingDataHand.Length; l++) + { + AvatarAutoMapper.s_RightMappingDataHand[l].GetChildren(AvatarAutoMapper.s_RightMappingDataHand); + } + AvatarAutoMapper.s_DidPerformInit = true; + } + public static Dictionary MapBones(Transform root, Dictionary validBones) + { + AvatarAutoMapper avatarAutoMapper = new AvatarAutoMapper(validBones); + return avatarAutoMapper.MapBones(root); + } + public Dictionary MapBones(Transform root) + { + AvatarAutoMapper.InitGlobalMappingData(); + Dictionary dictionary = new Dictionary(); + this.m_Orientation = Quaternion.identity; + this.m_MappingData = AvatarAutoMapper.s_MappingDataBody; + this.m_MappingIndexOffset = 0; + this.m_BoneMatchDict.Clear(); + AvatarAutoMapper.BoneMatch boneMatch = new AvatarAutoMapper.BoneMatch(null, root, this.m_MappingData[0]); + this.m_TreatDummyBonesAsReal = false; + this.MapBonesFromRootDown(boneMatch, dictionary); + if (dictionary.Count < 15) + { + this.m_TreatDummyBonesAsReal = true; + this.MapBonesFromRootDown(boneMatch, dictionary); + } + if (dictionary.ContainsKey(1) && dictionary.ContainsKey(2) && dictionary.ContainsKey(13) && dictionary.ContainsKey(14)) + { + this.m_Orientation = AvatarSetupTool.AvatarComputeOrientation(dictionary[1].position, dictionary[2].position, dictionary[13].position, dictionary[14].position); + if (Vector3.Angle(this.m_Orientation * Vector3.up, Vector3.up) > 20f || Vector3.Angle(this.m_Orientation * Vector3.forward, Vector3.forward) > 20f) + { + if (AvatarAutoMapper.kDebug) + { + Debug.Log("*** Mapping with new computed orientation"); + } + dictionary.Clear(); + this.m_BoneMatchDict.Clear(); + this.MapBonesFromRootDown(boneMatch, dictionary); + } + } + bool flag = !this.m_ValidBones.ContainsKey(root) || !this.m_ValidBones[root]; + if (flag && dictionary.Count > 0 && dictionary.ContainsKey(0)) + { + while (true) + { + Transform parent = dictionary[0].parent; + if (!(parent != null) || !(parent != boneMatch.bone) || !this.m_ValidBones.ContainsKey(parent) || !this.m_ValidBones[parent]) + { + break; + } + dictionary[0] = parent; + } + } + int num = 3; + Quaternion orientation = this.m_Orientation; + if (dictionary.ContainsKey(17)) + { + Transform transform = dictionary[15]; + Transform transform2 = dictionary[17]; + this.m_Orientation = Quaternion.FromToRotation(orientation * -Vector3.right, transform2.position - transform.position) * orientation; + this.m_MappingData = AvatarAutoMapper.s_LeftMappingDataHand; + this.m_MappingIndexOffset = 24; + this.m_BoneMatchDict.Clear(); + AvatarAutoMapper.BoneMatch rootMatch = new AvatarAutoMapper.BoneMatch(null, transform, this.m_MappingData[0]); + this.m_TreatDummyBonesAsReal = true; + int count = dictionary.Count; + this.MapBonesFromRootDown(rootMatch, dictionary); + if (dictionary.Count < count + num) + { + for (int i = 24; i <= 38; i++) + { + dictionary.Remove(i); + } + } + } + if (dictionary.ContainsKey(18)) + { + Transform transform3 = dictionary[16]; + Transform transform4 = dictionary[18]; + this.m_Orientation = Quaternion.FromToRotation(orientation * Vector3.right, transform4.position - transform3.position) * orientation; + this.m_MappingData = AvatarAutoMapper.s_RightMappingDataHand; + this.m_MappingIndexOffset = 39; + this.m_BoneMatchDict.Clear(); + AvatarAutoMapper.BoneMatch rootMatch2 = new AvatarAutoMapper.BoneMatch(null, transform3, this.m_MappingData[0]); + this.m_TreatDummyBonesAsReal = true; + int count2 = dictionary.Count; + this.MapBonesFromRootDown(rootMatch2, dictionary); + if (dictionary.Count < count2 + num) + { + for (int j = 39; j <= 53; j++) + { + dictionary.Remove(j); + } + } + } + return dictionary; + } + private void MapBonesFromRootDown(AvatarAutoMapper.BoneMatch rootMatch, Dictionary mapping) + { + List list = this.RecursiveFindPotentialBoneMatches(rootMatch, this.m_MappingData[0], true); + if (list != null && list.Count > 0) + { + if (AvatarAutoMapper.kDebug) + { + this.EvaluateBoneMatch(list[0], true); + } + this.ApplyMapping(list[0], mapping); + } + } + private void ApplyMapping(AvatarAutoMapper.BoneMatch match, Dictionary mapping) + { + if (match.doMap) + { + mapping[match.item.bone] = match.bone; + } + foreach (AvatarAutoMapper.BoneMatch current in match.children) + { + this.ApplyMapping(current, mapping); + } + } + private string GetStrippedAndNiceBoneName(Transform bone) + { + string[] array = bone.name.Split(new char[] + { + ':' + }); + return ObjectNames.NicifyVariableName(array[array.Length - 1]); + } + private int BoneHasBadKeyword(Transform bone, params string[] keywords) + { + string key = bone.GetInstanceID() + ":" + string.Concat(keywords); + if (this.m_BoneHasBadKeywordDict.ContainsKey(key)) + { + return this.m_BoneHasBadKeywordDict[key]; + } + int num = 0; + Transform parent = bone.parent; + while (parent.parent != null && this.m_ValidBones.ContainsKey(parent) && !this.m_ValidBones[parent]) + { + parent = parent.parent; + } + string text = this.GetStrippedAndNiceBoneName(parent).ToLower(); + for (int i = 0; i < keywords.Length; i++) + { + string text2 = keywords[i]; + if (text2[0] != '!' && text.Contains(text2)) + { + num = -20; + this.m_BoneHasBadKeywordDict[key] = num; + return num; + } + } + text = this.GetStrippedAndNiceBoneName(bone).ToLower(); + for (int j = 0; j < keywords.Length; j++) + { + string text3 = keywords[j]; + if (text3[0] == '!' && text.Contains(text3.Substring(1))) + { + num = -1000; + this.m_BoneHasBadKeywordDict[key] = num; + return num; + } + } + this.m_BoneHasBadKeywordDict[key] = num; + return num; + } + private int BoneHasKeyword(Transform bone, params string[] keywords) + { + string key = bone.GetInstanceID() + ":" + string.Concat(keywords); + if (this.m_BoneHasKeywordDict.ContainsKey(key)) + { + return this.m_BoneHasKeywordDict[key]; + } + int num = 0; + string text = this.GetStrippedAndNiceBoneName(bone).ToLower(); + for (int i = 0; i < keywords.Length; i++) + { + string text2 = keywords[i]; + if (text2[0] != '!' && text.Contains(text2)) + { + num = 20; + this.m_BoneHasKeywordDict[key] = num; + return num; + } + } + this.m_BoneHasKeywordDict[key] = num; + return num; + } + private bool MatchesSideKeywords(string boneName, bool left) + { + return boneName.ToLower().Contains((!left) ? "right" : "left") || Regex.Match(boneName, (!left) ? "(^|.*[ \\.:_-])[rR]($|[ \\.:_-].*)" : "(^|.*[ \\.:_-])[lL]($|[ \\.:_-].*)").Length > 0; + } + private int GetBoneSideMatchPoints(AvatarAutoMapper.BoneMatch match) + { + string name = match.bone.name; + if (match.item.side == AvatarAutoMapper.Side.None && (this.MatchesSideKeywords(name, false) || this.MatchesSideKeywords(name, true))) + { + return -1000; + } + bool flag = match.item.side == AvatarAutoMapper.Side.Left; + if (this.MatchesSideKeywords(name, flag)) + { + return 15; + } + if (this.MatchesSideKeywords(name, !flag)) + { + return -1000; + } + return 0; + } + private int GetMatchKey(AvatarAutoMapper.BoneMatch parentMatch, Transform t, AvatarAutoMapper.BoneMappingItem goalItem) + { + int num = goalItem.bone; + num += t.GetInstanceID() * 1000; + if (parentMatch != null) + { + num += parentMatch.bone.GetInstanceID() * 1000000; + if (parentMatch.parent != null) + { + num += parentMatch.parent.bone.GetInstanceID() * 1000000000; + } + } + return num; + } + private List RecursiveFindPotentialBoneMatches(AvatarAutoMapper.BoneMatch parentMatch, AvatarAutoMapper.BoneMappingItem goalItem, bool confirmedChoice) + { + List list = new List(); + Queue queue = new Queue(); + queue.Enqueue(new AvatarAutoMapper.QueuedBone(parentMatch.bone, 0)); + while (queue.Count > 0) + { + AvatarAutoMapper.QueuedBone queuedBone = queue.Dequeue(); + Transform bone = queuedBone.bone; + if (queuedBone.level >= goalItem.minStep && (this.m_TreatDummyBonesAsReal || this.m_ValidBones == null || (this.m_ValidBones.ContainsKey(bone) && this.m_ValidBones[bone]))) + { + int matchKey = this.GetMatchKey(parentMatch, bone, goalItem); + AvatarAutoMapper.BoneMatch boneMatch; + if (this.m_BoneMatchDict.ContainsKey(matchKey)) + { + boneMatch = this.m_BoneMatchDict[matchKey]; + } + else + { + boneMatch = new AvatarAutoMapper.BoneMatch(parentMatch, bone, goalItem); + this.EvaluateBoneMatch(boneMatch, false); + this.m_BoneMatchDict[matchKey] = boneMatch; + } + if (boneMatch.score > 0f || AvatarAutoMapper.kDebug) + { + list.Add(boneMatch); + } + } + if (queuedBone.level < goalItem.maxStep) + { + foreach (Transform transform in bone) + { + if (this.m_ValidBones == null || this.m_ValidBones.ContainsKey(transform)) + { + if (!this.m_TreatDummyBonesAsReal && this.m_ValidBones != null && !this.m_ValidBones[transform]) + { + queue.Enqueue(new AvatarAutoMapper.QueuedBone(transform, queuedBone.level)); + } + else + { + queue.Enqueue(new AvatarAutoMapper.QueuedBone(transform, queuedBone.level + 1)); + } + } + } + } + } + if (list.Count == 0) + { + return null; + } + list.Sort(); + if (list[0].score <= 0f) + { + return null; + } + if (AvatarAutoMapper.kDebug && confirmedChoice) + { + this.DebugMatchChoice(list); + } + while (list.Count > 3) + { + list.RemoveAt(list.Count - 1); + } + list.TrimExcess(); + return list; + } + private string GetNameOfBone(int boneIndex) + { + if (boneIndex < 0) + { + return string.Empty + boneIndex; + } + return string.Empty + (HumanBodyBones)boneIndex; + } + private string GetMatchString(AvatarAutoMapper.BoneMatch match) + { + return this.GetNameOfBone(match.item.bone) + ":" + ((!(match.bone == null)) ? match.bone.name : "null"); + } + private void DebugMatchChoice(List matches) + { + string text = this.GetNameOfBone(matches[0].item.bone) + " preferred order: "; + for (int i = 0; i < matches.Count; i++) + { + string text2 = text; + text = string.Concat(new string[] + { + text2, + matches[i].bone.name, + " (", + matches[i].score.ToString("0.0"), + " / ", + matches[i].totalSiblingScore.ToString("0.0"), + "), " + }); + } + foreach (AvatarAutoMapper.BoneMatch current in matches) + { + string text2 = text; + text = string.Concat(new string[] + { + text2, + "\n Match ", + current.bone.name, + " (", + current.score.ToString("0.0"), + " / ", + current.totalSiblingScore.ToString("0.0"), + "):" + }); + foreach (string current2 in current.debugTracker) + { + text = text + "\n - " + current2; + } + } + Debug.Log(text); + } + private AvatarAutoMapper.BoneMappingItem GetBoneMappingItem(int bone) + { + AvatarAutoMapper.BoneMappingItem[] mappingData = this.m_MappingData; + for (int i = 0; i < mappingData.Length; i++) + { + AvatarAutoMapper.BoneMappingItem result = mappingData[i]; + if (result.bone == bone) + { + return result; + } + } + return default(AvatarAutoMapper.BoneMappingItem); + } + private bool IsParentOfOther(Transform knownCommonParent, Transform potentialParent, Transform potentialChild) + { + Transform transform = potentialChild; + while (transform != knownCommonParent) + { + if (transform == potentialParent) + { + return true; + } + if (transform == knownCommonParent) + { + return false; + } + transform = transform.parent; + } + return false; + } + private bool ShareTransformPath(Transform commonParent, Transform childA, Transform childB) + { + return this.IsParentOfOther(commonParent, childA, childB) || this.IsParentOfOther(commonParent, childB, childA); + } + private List GetBestChildMatches(AvatarAutoMapper.BoneMatch parentMatch, List> childMatchesLists) + { + List list = new List(); + if (childMatchesLists.Count == 1) + { + list.Add(childMatchesLists[0][0]); + return list; + } + int[] array = new int[childMatchesLists.Count]; + float num; + array = this.GetBestChildMatchChoices(parentMatch, childMatchesLists, array, out num); + for (int i = 0; i < array.Length; i++) + { + if (array[i] >= 0) + { + list.Add(childMatchesLists[i][array[i]]); + } + } + return list; + } + private int[] GetBestChildMatchChoices(AvatarAutoMapper.BoneMatch parentMatch, List> childMatchesLists, int[] choices, out float score) + { + List list = new List(); + for (int i = 0; i < choices.Length; i++) + { + if (choices[i] >= 0) + { + list.Clear(); + list.Add(i); + for (int j = i + 1; j < choices.Length; j++) + { + if (choices[j] >= 0) + { + if (this.ShareTransformPath(parentMatch.bone, childMatchesLists[i][choices[i]].bone, childMatchesLists[j][choices[j]].bone)) + { + list.Add(j); + } + } + } + if (list.Count > 1) + { + break; + } + } + } + if (list.Count <= 1) + { + score = 0f; + for (int k = 0; k < choices.Length; k++) + { + if (choices[k] >= 0) + { + score += childMatchesLists[k][choices[k]].totalSiblingScore; + } + } + return choices; + } + float num = 0f; + int[] result = choices; + for (int l = 0; l < list.Count; l++) + { + int[] array = new int[choices.Length]; + Array.Copy(choices, array, choices.Length); + for (int m = 0; m < list.Count; m++) + { + if (l != m) + { + if (list[m] >= array.Length) + { + Debug.LogError(string.Concat(new object[] + { + "sharedIndices[j] (", + list[m], + ") >= altChoices.Length (", + array.Length, + ")" + })); + } + if (list[m] >= childMatchesLists.Count) + { + Debug.LogError(string.Concat(new object[] + { + "sharedIndices[j] (", + list[m], + ") >= childMatchesLists.Count (", + childMatchesLists.Count, + ")" + })); + } + if (array[list[m]] < childMatchesLists[list[m]].Count - 1) + { + array[list[m]]++; + } + else + { + array[list[m]] = -1; + } + } + } + float num2; + array = this.GetBestChildMatchChoices(parentMatch, childMatchesLists, array, out num2); + if (num2 > num) + { + num = num2; + result = array; + } + } + score = num; + return result; + } + private void EvaluateBoneMatch(AvatarAutoMapper.BoneMatch match, bool confirmedChoice) + { + match.score = 0f; + match.siblingScore = 0f; + List> list = new List>(); + int num = 0; + int[] children = match.item.GetChildren(this.m_MappingData); + for (int i = 0; i < children.Length; i++) + { + int num2 = children[i]; + AvatarAutoMapper.BoneMappingItem goalItem = this.m_MappingData[num2]; + if (goalItem.parent == match.item.bone) + { + num++; + List list2 = this.RecursiveFindPotentialBoneMatches(match, goalItem, confirmedChoice); + if (list2 != null && list2.Count != 0) + { + list.Add(list2); + } + } + } + bool flag = match.bone == match.humanBoneParent.bone; + int num3 = 0; + if (list.Count > 0) + { + match.children = this.GetBestChildMatches(match, list); + foreach (AvatarAutoMapper.BoneMatch current in match.children) + { + if (AvatarAutoMapper.kDebug && confirmedChoice) + { + this.EvaluateBoneMatch(current, confirmedChoice); + } + num3++; + match.score += current.score; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.AddRange(current.debugTracker); + } + if (current.bone == match.bone && current.item.bone >= 0) + { + flag = true; + } + } + } + if (!match.item.optional || !flag) + { + this.ScoreBoneMatch(match); + } + if (match.item.dir != Vector3.zero) + { + Vector3 dir = match.item.dir; + if (this.m_MappingIndexOffset >= 24 && this.m_MappingIndexOffset < 39) + { + dir.x *= -1f; + } + Vector3 vector = (match.bone.position - match.humanBoneParent.bone.position).normalized; + vector = Quaternion.Inverse(this.m_Orientation) * vector; + float num4 = Vector3.Dot(vector, dir) * (float)((!match.item.optional) ? 10 : 5); + match.siblingScore += num4; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + "* ", + num4, + ": ", + this.GetMatchString(match), + " matched dir (", + (match.bone.position - match.humanBoneParent.bone.position).normalized, + " , ", + dir, + ")" + })); + } + if (num4 > 0f) + { + match.score += 10f; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + 10, + ": ", + this.GetMatchString(match), + " matched dir (", + (match.bone.position - match.humanBoneParent.bone.position).normalized, + " , ", + dir, + ")" + })); + } + } + } + if (this.m_MappingIndexOffset == 0) + { + int boneSideMatchPoints = this.GetBoneSideMatchPoints(match); + if (match.parent.item.side == AvatarAutoMapper.Side.None || boneSideMatchPoints < 0) + { + match.siblingScore += (float)boneSideMatchPoints; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + "* ", + boneSideMatchPoints, + ": ", + this.GetMatchString(match), + " matched side" + })); + } + } + } + if (match.score > 0f) + { + if (match.item.optional && !flag) + { + match.score += 5f; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + 5, + ": ", + this.GetMatchString(match), + " optional bone is included" + })); + } + } + if (num == 0 && match.bone.childCount > 0) + { + match.score += 1f; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + 1, + ": ", + this.GetMatchString(match), + " has dummy child bone" + })); + } + } + if (match.item.lengthRatio != 0f) + { + float num5 = Vector3.Distance(match.bone.position, match.humanBoneParent.bone.position); + if (num5 == 0f && match.bone != match.humanBoneParent.bone) + { + match.score -= 1000f; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + -1000, + ": ", + this.GetMatchString(match.humanBoneParent), + " has zero length" + })); + } + } + float num6 = Vector3.Distance(match.humanBoneParent.bone.position, match.humanBoneParent.humanBoneParent.bone.position); + if (num6 > 0f) + { + float num7 = Mathf.Log(num5 / num6, 2f); + float num8 = Mathf.Log(match.item.lengthRatio, 2f); + float num9 = 10f * Mathf.Clamp(1f - 0.6f * Mathf.Abs(num7 - num8), 0f, 1f); + match.score += num9; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + num9, + ": parent ", + this.GetMatchString(match.humanBoneParent), + " matched lengthRatio - ", + num5, + " / ", + num6, + " = ", + num5 / num6, + " (", + num7, + ") goal: ", + match.item.lengthRatio, + " (", + num8, + ")" + })); + } + } + } + } + if (match.item.bone >= 0 && (!match.item.optional || !flag)) + { + match.doMap = true; + } + } + private void ScoreBoneMatch(AvatarAutoMapper.BoneMatch match) + { + int num = this.BoneHasBadKeyword(match.bone, match.item.keywords); + match.score += (float)num; + if (AvatarAutoMapper.kDebug && num != 0) + { + match.debugTracker.Add(string.Concat(new object[] + { + num, + ": ", + this.GetMatchString(match), + " matched bad keywords" + })); + } + if (num < 0) + { + return; + } + int num2 = this.BoneHasKeyword(match.bone, match.item.keywords); + match.score += (float)num2; + if (AvatarAutoMapper.kDebug && num2 != 0) + { + match.debugTracker.Add(string.Concat(new object[] + { + num2, + ": ", + this.GetMatchString(match), + " matched keywords" + })); + } + if (match.item.keywords.Length == 0 && match.item.alwaysInclude) + { + match.score += 1f; + if (AvatarAutoMapper.kDebug) + { + match.debugTracker.Add(string.Concat(new object[] + { + 1, + ": ", + this.GetMatchString(match), + " always-include point" + })); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarColliderEditor.cs b/UnityEditor/UnityEditor/AvatarColliderEditor.cs new file mode 100644 index 00000000..44b5125b --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarColliderEditor.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + internal class AvatarColliderEditor : AvatarSubEditor + { + } +} diff --git a/UnityEditor/UnityEditor/AvatarControl.cs b/UnityEditor/UnityEditor/AvatarControl.cs new file mode 100644 index 00000000..08ffcc22 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarControl.cs @@ -0,0 +1,222 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class AvatarControl + { + private class Styles + { + public GUIContent[] Silhouettes = new GUIContent[] + { + EditorGUIUtility.IconContent("AvatarInspector/BodySilhouette"), + EditorGUIUtility.IconContent("AvatarInspector/HeadZoomSilhouette"), + EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoomSilhouette"), + EditorGUIUtility.IconContent("AvatarInspector/RightHandZoomSilhouette") + }; + public GUIContent[,] BodyPart; + public GUILayoutOption ButtonSize; + public Styles() + { + GUIContent[,] expr_49 = new GUIContent[4, 9]; + expr_49[0, 1] = EditorGUIUtility.IconContent("AvatarInspector/Torso"); + expr_49[0, 2] = EditorGUIUtility.IconContent("AvatarInspector/Head"); + expr_49[0, 3] = EditorGUIUtility.IconContent("AvatarInspector/LeftArm"); + expr_49[0, 4] = EditorGUIUtility.IconContent("AvatarInspector/LeftFingers"); + expr_49[0, 5] = EditorGUIUtility.IconContent("AvatarInspector/RightArm"); + expr_49[0, 6] = EditorGUIUtility.IconContent("AvatarInspector/RightFingers"); + expr_49[0, 7] = EditorGUIUtility.IconContent("AvatarInspector/LeftLeg"); + expr_49[0, 8] = EditorGUIUtility.IconContent("AvatarInspector/RightLeg"); + expr_49[1, 2] = EditorGUIUtility.IconContent("AvatarInspector/HeadZoom"); + expr_49[2, 4] = EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoom"); + expr_49[3, 6] = EditorGUIUtility.IconContent("AvatarInspector/RightHandZoom"); + this.BodyPart = expr_49; + this.ButtonSize = GUILayout.MaxWidth(120f); + base..ctor(); + } + } + public enum BodyPartColor + { + Off, + Green, + Red, + IKGreen = 4, + IKRed = 8 + } + public delegate AvatarControl.BodyPartColor BodyPartFeedback(BodyPart bodyPart); + private static AvatarControl.Styles s_Styles; + private static Vector2[,] s_BonePositions; + private static AvatarControl.Styles styles + { + get + { + if (AvatarControl.s_Styles == null) + { + AvatarControl.s_Styles = new AvatarControl.Styles(); + } + return AvatarControl.s_Styles; + } + } + static AvatarControl() + { + AvatarControl.s_BonePositions = new Vector2[4, HumanTrait.BoneCount]; + int num = 0; + AvatarControl.s_BonePositions[num, 0] = new Vector2(0f, 0.08f); + AvatarControl.s_BonePositions[num, 1] = new Vector2(0.16f, 0.01f); + AvatarControl.s_BonePositions[num, 2] = new Vector2(-0.16f, 0.01f); + AvatarControl.s_BonePositions[num, 3] = new Vector2(0.21f, -0.4f); + AvatarControl.s_BonePositions[num, 4] = new Vector2(-0.21f, -0.4f); + AvatarControl.s_BonePositions[num, 5] = new Vector2(0.23f, -0.8f); + AvatarControl.s_BonePositions[num, 6] = new Vector2(-0.23f, -0.8f); + AvatarControl.s_BonePositions[num, 7] = new Vector2(0f, 0.25f); + AvatarControl.s_BonePositions[num, 8] = new Vector2(0f, 0.43f); + AvatarControl.s_BonePositions[num, 9] = new Vector2(0f, 0.66f); + AvatarControl.s_BonePositions[num, 10] = new Vector2(0f, 0.76f); + AvatarControl.s_BonePositions[num, 11] = new Vector2(0.14f, 0.6f); + AvatarControl.s_BonePositions[num, 12] = new Vector2(-0.14f, 0.6f); + AvatarControl.s_BonePositions[num, 13] = new Vector2(0.3f, 0.57f); + AvatarControl.s_BonePositions[num, 14] = new Vector2(-0.3f, 0.57f); + AvatarControl.s_BonePositions[num, 15] = new Vector2(0.48f, 0.3f); + AvatarControl.s_BonePositions[num, 16] = new Vector2(-0.48f, 0.3f); + AvatarControl.s_BonePositions[num, 17] = new Vector2(0.66f, 0.03f); + AvatarControl.s_BonePositions[num, 18] = new Vector2(-0.66f, 0.03f); + AvatarControl.s_BonePositions[num, 19] = new Vector2(0.25f, -0.89f); + AvatarControl.s_BonePositions[num, 20] = new Vector2(-0.25f, -0.89f); + num = 1; + AvatarControl.s_BonePositions[num, 9] = new Vector2(-0.2f, -0.62f); + AvatarControl.s_BonePositions[num, 10] = new Vector2(-0.15f, -0.3f); + AvatarControl.s_BonePositions[num, 21] = new Vector2(0.63f, 0.16f); + AvatarControl.s_BonePositions[num, 22] = new Vector2(0.15f, 0.16f); + AvatarControl.s_BonePositions[num, 23] = new Vector2(0.45f, -0.4f); + num = 2; + AvatarControl.s_BonePositions[num, 24] = new Vector2(-0.35f, 0.11f); + AvatarControl.s_BonePositions[num, 27] = new Vector2(0.19f, 0.11f); + AvatarControl.s_BonePositions[num, 30] = new Vector2(0.22f, 0f); + AvatarControl.s_BonePositions[num, 33] = new Vector2(0.16f, -0.12f); + AvatarControl.s_BonePositions[num, 36] = new Vector2(0.09f, -0.23f); + AvatarControl.s_BonePositions[num, 26] = new Vector2(-0.03f, 0.33f); + AvatarControl.s_BonePositions[num, 29] = new Vector2(0.65f, 0.16f); + AvatarControl.s_BonePositions[num, 32] = new Vector2(0.74f, 0f); + AvatarControl.s_BonePositions[num, 35] = new Vector2(0.66f, -0.14f); + AvatarControl.s_BonePositions[num, 38] = new Vector2(0.45f, -0.25f); + for (int i = 0; i < 5; i++) + { + AvatarControl.s_BonePositions[num, 25 + i * 3] = Vector2.Lerp(AvatarControl.s_BonePositions[num, 24 + i * 3], AvatarControl.s_BonePositions[num, 26 + i * 3], 0.58f); + } + num = 3; + for (int j = 0; j < 15; j++) + { + AvatarControl.s_BonePositions[num, 24 + j + 15] = Vector2.Scale(AvatarControl.s_BonePositions[num - 1, 24 + j], new Vector2(-1f, 1f)); + } + } + public static int ShowBoneMapping(int shownBodyView, AvatarControl.BodyPartFeedback bodyPartCallback, AvatarSetupTool.BoneWrapper[] bones, SerializedObject serializedObject, AvatarMappingEditor editor) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (AvatarControl.styles.Silhouettes[shownBodyView].image) + { + Rect rect = GUILayoutUtility.GetRect(AvatarControl.styles.Silhouettes[shownBodyView], GUIStyle.none, new GUILayoutOption[] + { + GUILayout.MaxWidth((float)AvatarControl.styles.Silhouettes[shownBodyView].image.width) + }); + AvatarControl.DrawBodyParts(rect, shownBodyView, bodyPartCallback); + for (int i = 0; i < bones.Length; i++) + { + AvatarControl.DrawBone(shownBodyView, i, rect, bones[i], serializedObject, editor); + } + } + else + { + GUILayout.Label("texture missing,\nfix me!", new GUILayoutOption[0]); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + string[] array = new string[] + { + "Body", + "Head", + "Left Hand", + "Right Hand" + }; + lastRect.x += 5f; + lastRect.width = 70f; + lastRect.yMin = lastRect.yMax - 69f; + lastRect.height = 16f; + for (int j = 0; j < array.Length; j++) + { + if (GUI.Toggle(lastRect, shownBodyView == j, array[j], EditorStyles.miniButton)) + { + shownBodyView = j; + } + lastRect.y += 16f; + } + return shownBodyView; + } + public static void DrawBodyParts(Rect rect, int shownBodyView, AvatarControl.BodyPartFeedback bodyPartCallback) + { + GUI.color = new Color(0.2f, 0.2f, 0.2f, 1f); + if (AvatarControl.styles.Silhouettes[shownBodyView] != null) + { + GUI.DrawTexture(rect, AvatarControl.styles.Silhouettes[shownBodyView].image); + } + for (int i = 1; i < 9; i++) + { + AvatarControl.DrawBodyPart(shownBodyView, i, rect, bodyPartCallback((BodyPart)i)); + } + } + protected static void DrawBodyPart(int shownBodyView, int i, Rect rect, AvatarControl.BodyPartColor bodyPartColor) + { + if (AvatarControl.styles.BodyPart[shownBodyView, i] != null && AvatarControl.styles.BodyPart[shownBodyView, i].image != null) + { + if ((bodyPartColor & AvatarControl.BodyPartColor.Green) == AvatarControl.BodyPartColor.Green) + { + GUI.color = Color.green; + } + else + { + if ((bodyPartColor & AvatarControl.BodyPartColor.Red) == AvatarControl.BodyPartColor.Red) + { + GUI.color = Color.red; + } + else + { + GUI.color = Color.gray; + } + } + GUI.DrawTexture(rect, AvatarControl.styles.BodyPart[shownBodyView, i].image); + GUI.color = Color.white; + } + } + public static List GetViewsThatContainBone(int bone) + { + List list = new List(); + if (bone < 0 || bone >= HumanTrait.BoneCount) + { + return list; + } + for (int i = 0; i < 4; i++) + { + if (AvatarControl.s_BonePositions[i, bone] != Vector2.zero) + { + list.Add(i); + } + } + return list; + } + protected static void DrawBone(int shownBodyView, int i, Rect rect, AvatarSetupTool.BoneWrapper bone, SerializedObject serializedObject, AvatarMappingEditor editor) + { + if (AvatarControl.s_BonePositions[shownBodyView, i] == Vector2.zero) + { + return; + } + Vector2 b = AvatarControl.s_BonePositions[shownBodyView, i]; + b.y *= -1f; + b.Scale(new Vector2(rect.width * 0.5f, rect.height * 0.5f)); + b = rect.center + b; + int num = 19; + Rect rect2 = new Rect(b.x - (float)num * 0.5f, b.y - (float)num * 0.5f, (float)num, (float)num); + bone.BoneDotGUI(rect2, i, true, true, serializedObject, editor); + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarEditor.cs b/UnityEditor/UnityEditor/AvatarEditor.cs new file mode 100644 index 00000000..cb980f7c --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarEditor.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Avatar))] + internal class AvatarEditor : Editor + { + private class Styles + { + public GUIContent[] tabs = new GUIContent[] + { + EditorGUIUtility.TextContent("Mapping"), + EditorGUIUtility.TextContent("Muscles") + }; + public GUIContent editCharacter = EditorGUIUtility.TextContent("Configure Avatar"); + public GUIContent reset = EditorGUIUtility.TextContent("Reset"); + } + private enum EditMode + { + NotEditing, + Starting, + Editing, + Stopping + } + [Serializable] + protected class SceneStateCache + { + public SceneView view; + public SceneView.SceneViewState state; + } + private const int sMappingTab = 0; + private const int sMuscleTab = 1; + private const int sHandleTab = 2; + private const int sColliderTab = 3; + private const int sDefaultTab = 0; + private static AvatarEditor.Styles s_Styles; + protected int m_TabIndex; + internal GameObject m_GameObject; + internal Dictionary m_ModelBones; + private AvatarEditor.EditMode m_EditMode; + internal bool m_CameFromImportSettings; + private bool m_SwitchToEditMode; + internal static bool s_EditImmediatelyOnNextOpen; + protected bool m_InspectorLocked; + protected List m_SceneStates; + private AvatarMuscleEditor m_MuscleEditor; + private AvatarHandleEditor m_HandleEditor; + private AvatarColliderEditor m_ColliderEditor; + private AvatarMappingEditor m_MappingEditor; + private string m_UserFileName; + private static AvatarEditor.Styles styles + { + get + { + if (AvatarEditor.s_Styles == null) + { + AvatarEditor.s_Styles = new AvatarEditor.Styles(); + } + return AvatarEditor.s_Styles; + } + } + internal Avatar avatar + { + get + { + return this.target as Avatar; + } + } + protected AvatarSubEditor editor + { + get + { + switch (this.m_TabIndex) + { + case 1: + return this.m_MuscleEditor; + case 2: + return this.m_HandleEditor; + case 3: + return this.m_ColliderEditor; + } + return this.m_MappingEditor; + } + set + { + switch (this.m_TabIndex) + { + case 1: + this.m_MuscleEditor = (value as AvatarMuscleEditor); + return; + case 2: + this.m_HandleEditor = (value as AvatarHandleEditor); + return; + case 3: + this.m_ColliderEditor = (value as AvatarColliderEditor); + return; + } + this.m_MappingEditor = (value as AvatarMappingEditor); + } + } + public GameObject prefab + { + get + { + string assetPath = AssetDatabase.GetAssetPath(this.target); + return AssetDatabase.LoadMainAssetAtPath(assetPath) as GameObject; + } + } + internal override SerializedObject GetSerializedObjectInternal() + { + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = SerializedObject.LoadFromCache(base.GetInstanceID()); + } + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.target))); + } + return this.m_SerializedObject; + } + private void OnEnable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + this.m_SwitchToEditMode = false; + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + this.m_ModelBones = AvatarSetupTool.GetModelBones(this.m_GameObject.transform, false, null); + this.editor.Enable(this); + } + else + { + if (this.m_EditMode == AvatarEditor.EditMode.NotEditing) + { + this.editor = null; + if (AvatarEditor.s_EditImmediatelyOnNextOpen) + { + this.m_CameFromImportSettings = true; + AvatarEditor.s_EditImmediatelyOnNextOpen = false; + } + } + } + } + private void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + if (this.m_SerializedObject != null) + { + this.m_SerializedObject.Cache(base.GetInstanceID()); + this.m_SerializedObject = null; + } + } + private void OnDestroy() + { + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + this.SwitchToAssetMode(); + } + } + private void ShowOriginalObject() + { + UnityEngine.Object activeObject; + if (this.m_CameFromImportSettings) + { + string assetPath = AssetDatabase.GetAssetPath(this.target); + activeObject = AssetDatabase.LoadMainAssetAtPath(assetPath); + } + else + { + activeObject = this.target; + } + Selection.activeObject = activeObject; + } + protected void CreateEditor() + { + switch (this.m_TabIndex) + { + case 1: + this.editor = ScriptableObject.CreateInstance(); + goto IL_62; + case 2: + this.editor = ScriptableObject.CreateInstance(); + goto IL_62; + case 3: + this.editor = ScriptableObject.CreateInstance(); + goto IL_62; + } + this.editor = ScriptableObject.CreateInstance(); + IL_62: + this.editor.hideFlags = HideFlags.HideAndDontSave; + this.editor.Enable(this); + } + protected void DestroyEditor() + { + this.editor.OnDestroy(); + this.editor = null; + } + public override bool UseDefaultMargins() + { + return false; + } + public override void OnInspectorGUI() + { + GUI.enabled = true; + EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins, new GUILayoutOption[0]); + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + this.EditingGUI(); + } + else + { + if (!this.m_CameFromImportSettings) + { + this.EditButtonGUI(); + } + else + { + if (this.m_EditMode == AvatarEditor.EditMode.NotEditing && Event.current.type == EventType.Repaint) + { + this.m_SwitchToEditMode = true; + } + } + } + EditorGUILayout.EndVertical(); + } + private void EditButtonGUI() + { + if (this.avatar == null || !this.avatar.isHuman) + { + return; + } + string assetPath = AssetDatabase.GetAssetPath(this.avatar); + ModelImporter x = AssetImporter.GetAtPath(assetPath) as ModelImporter; + if (x == null) + { + return; + } + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(AvatarEditor.styles.editCharacter, new GUILayoutOption[] + { + GUILayout.Width(120f) + }) && EditorApplication.SaveCurrentSceneIfUserWantsTo()) + { + this.SwitchToEditMode(); + GUIUtility.ExitGUI(); + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + } + private void EditingGUI() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + int num = this.m_TabIndex; + bool enabled = GUI.enabled; + GUI.enabled = (!(this.avatar == null) && this.avatar.isHuman); + num = GUILayout.Toolbar(num, AvatarEditor.styles.tabs, new GUILayoutOption[0]); + GUI.enabled = enabled; + if (num != this.m_TabIndex) + { + this.DestroyEditor(); + this.m_TabIndex = num; + this.CreateEditor(); + } + GUILayout.EndHorizontal(); + this.editor.OnInspectorGUI(); + } + public void OnSceneGUI() + { + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + this.editor.OnSceneGUI(); + } + } + internal void SwitchToEditMode() + { + this.m_EditMode = AvatarEditor.EditMode.Starting; + this.ChangeInspectorLock(true); + this.m_UserFileName = EditorApplication.currentScene; + EditorApplication.NewScene(); + this.m_GameObject = (UnityEngine.Object.Instantiate(this.prefab) as GameObject); + if (base.serializedObject.FindProperty("m_OptimizeGameObjects").boolValue) + { + AnimatorUtility.DeoptimizeTransformHierarchy(this.m_GameObject); + } + Animator component = this.m_GameObject.GetComponent(); + if (component != null && component.runtimeAnimatorController == null) + { + AnimatorController animatorController = new AnimatorController(); + animatorController.hideFlags = HideFlags.DontSave; + animatorController.AddLayer("preview"); + component.runtimeAnimatorController = animatorController; + } + Dictionary modelBones = AvatarSetupTool.GetModelBones(this.m_GameObject.transform, true, null); + AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(base.serializedObject, modelBones); + this.m_ModelBones = AvatarSetupTool.GetModelBones(this.m_GameObject.transform, false, humanBones); + Selection.activeObject = this.m_GameObject; + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow)); + for (int i = 0; i < array.Length; i++) + { + SceneHierarchyWindow sceneHierarchyWindow = (SceneHierarchyWindow)array[i]; + sceneHierarchyWindow.SetExpandedRecursive(this.m_GameObject.GetInstanceID(), true); + } + this.CreateEditor(); + this.m_EditMode = AvatarEditor.EditMode.Editing; + this.m_SceneStates = new List(); + foreach (SceneView sceneView in SceneView.sceneViews) + { + this.m_SceneStates.Add(new AvatarEditor.SceneStateCache + { + state = new SceneView.SceneViewState(sceneView.m_SceneViewState), + view = sceneView + }); + sceneView.m_SceneViewState.showFlares = false; + sceneView.m_SceneViewState.showMaterialUpdate = false; + sceneView.m_SceneViewState.showFog = false; + sceneView.m_SceneViewState.showSkybox = false; + sceneView.FrameSelected(); + } + } + internal void SwitchToAssetMode() + { + foreach (AvatarEditor.SceneStateCache current in this.m_SceneStates) + { + if (!(current.view == null)) + { + current.view.m_SceneViewState.showFog = current.state.showFog; + current.view.m_SceneViewState.showFlares = current.state.showFlares; + current.view.m_SceneViewState.showMaterialUpdate = current.state.showMaterialUpdate; + current.view.m_SceneViewState.showSkybox = current.state.showSkybox; + } + } + this.m_EditMode = AvatarEditor.EditMode.Stopping; + this.DestroyEditor(); + if (!EditorApplication.isUpdating && !Unsupported.IsDestroyScriptableObject(this)) + { + string currentScene = EditorApplication.currentScene; + if (currentScene.Length <= 0) + { + if (this.m_UserFileName.Length > 0) + { + EditorApplication.OpenScene(this.m_UserFileName); + } + else + { + EditorApplication.NewScene(); + } + } + } + else + { + if (Unsupported.IsDestroyScriptableObject(this)) + { + EditorApplication.CallbackFunction CleanUpSceneOnDestroy = null; + string userFileName = this.m_UserFileName; + CleanUpSceneOnDestroy = delegate + { + string currentScene2 = EditorApplication.currentScene; + if (currentScene2.Length <= 0) + { + if (userFileName.Length > 0) + { + EditorApplication.OpenScene(userFileName); + } + else + { + EditorApplication.NewScene(); + } + } + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, CleanUpSceneOnDestroy); + }; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, CleanUpSceneOnDestroy); + } + } + this.ChangeInspectorLock(this.m_InspectorLocked); + this.m_GameObject = null; + this.m_ModelBones = null; + this.ShowOriginalObject(); + if (!this.m_CameFromImportSettings) + { + this.m_EditMode = AvatarEditor.EditMode.NotEditing; + } + } + private void ChangeInspectorLock(bool locked) + { + InspectorWindow[] allInspectorWindows = InspectorWindow.GetAllInspectorWindows(); + for (int i = 0; i < allInspectorWindows.Length; i++) + { + InspectorWindow inspectorWindow = allInspectorWindows[i]; + ActiveEditorTracker tracker = inspectorWindow.GetTracker(); + Editor[] activeEditors = tracker.activeEditors; + for (int j = 0; j < activeEditors.Length; j++) + { + Editor x = activeEditors[j]; + if (x == this) + { + this.m_InspectorLocked = inspectorWindow.isLocked; + inspectorWindow.isLocked = locked; + } + } + } + } + public void Update() + { + if (this.m_SwitchToEditMode) + { + this.m_SwitchToEditMode = false; + this.SwitchToEditMode(); + EditorApplication.RequestRepaintAllViews(); + } + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + if (this.m_GameObject == null || this.m_ModelBones == null) + { + this.SwitchToAssetMode(); + } + else + { + if (EditorApplication.isPlaying) + { + this.SwitchToAssetMode(); + } + else + { + if (this.m_ModelBones != null) + { + foreach (KeyValuePair current in this.m_ModelBones) + { + if (current.Key == null) + { + this.SwitchToAssetMode(); + break; + } + } + } + } + } + } + } + public bool HasFrameBounds() + { + foreach (KeyValuePair current in this.m_ModelBones) + { + if (current.Key == Selection.activeTransform) + { + return true; + } + } + return false; + } + public Bounds OnGetFrameBounds() + { + Transform activeTransform = Selection.activeTransform; + Bounds result = new Bounds(activeTransform.position, new Vector3(0f, 0f, 0f)); + foreach (Transform transform in activeTransform) + { + result.Encapsulate(transform.position); + } + if (activeTransform.parent) + { + result.Encapsulate(activeTransform.parent.position); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarHandleEditor.cs b/UnityEditor/UnityEditor/AvatarHandleEditor.cs new file mode 100644 index 00000000..b256432c --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarHandleEditor.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + internal class AvatarHandleEditor : AvatarSubEditor + { + } +} diff --git a/UnityEditor/UnityEditor/AvatarMappingEditor.cs b/UnityEditor/UnityEditor/AvatarMappingEditor.cs new file mode 100644 index 00000000..7b27f98c --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarMappingEditor.cs @@ -0,0 +1,769 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class AvatarMappingEditor : AvatarSubEditor + { + internal class Styles + { + public GUIContent[] BodyPartMapping = new GUIContent[] + { + EditorGUIUtility.TextContent("Avatar"), + EditorGUIUtility.TextContent("Body"), + EditorGUIUtility.TextContent("Head"), + EditorGUIUtility.TextContent("Left Arm"), + EditorGUIUtility.TextContent("Left Fingers"), + EditorGUIUtility.TextContent("Right Arm"), + EditorGUIUtility.TextContent("Right Fingers"), + EditorGUIUtility.TextContent("Left Leg"), + EditorGUIUtility.TextContent("Right Leg") + }; + public GUIContent RequiredBone = EditorGUIUtility.TextContent("Optional Bones"); + public GUIContent DoneCharacter = EditorGUIUtility.TextContent("Done"); + public GUIContent mapping = EditorGUIUtility.TextContent("Mapping"); + public GUIContent clearMapping = EditorGUIUtility.TextContent("Clear"); + public GUIContent autoMapping = EditorGUIUtility.TextContent("Automap"); + public GUIContent loadMapping = EditorGUIUtility.TextContent("Load"); + public GUIContent saveMapping = EditorGUIUtility.TextContent("Save"); + public GUIContent pose = EditorGUIUtility.TextContent("Pose"); + public GUIContent resetPose = EditorGUIUtility.TextContent("Reset"); + public GUIContent sampleBindPose = EditorGUIUtility.TextContent("Sample Bind-Pose"); + public GUIContent enforceTPose = EditorGUIUtility.TextContent("Enforce T-Pose"); + public GUIContent ShowError = EditorGUIUtility.TextContent("Show Error (s)..."); + public GUIContent CloseError = EditorGUIUtility.TextContent("Close Error (s)"); + public GUIContent dotFill = EditorGUIUtility.IconContent("AvatarInspector/DotFill"); + public GUIContent dotFrame = EditorGUIUtility.IconContent("AvatarInspector/DotFrame"); + public GUIContent dotFrameDotted = EditorGUIUtility.IconContent("AvatarInspector/DotFrameDotted"); + public GUIContent dotSelection = EditorGUIUtility.IconContent("AvatarInspector/DotSelection"); + public GUIStyle box = new GUIStyle("box"); + public GUIStyle toolbar = "TE Toolbar"; + public GUIStyle toolbarDropDown = "TE ToolbarDropDown"; + public GUIStyle errorLabel = new GUIStyle(EditorStyles.wordWrappedMiniLabel); + public Styles() + { + this.box.padding = new RectOffset(0, 0, 0, 0); + this.box.margin = new RectOffset(0, 0, 0, 0); + this.errorLabel.normal.textColor = new Color(0.6f, 0f, 0f, 1f); + } + } + private static AvatarMappingEditor.Styles s_Styles; + protected bool[] m_BodyPartToggle; + protected bool[] m_BodyPartFoldout; + protected int m_BodyView; + [SerializeField] + protected AvatarSetupTool.BoneWrapper[] m_Bones; + internal static int s_SelectedBoneIndex = -1; + protected bool m_HasSkinnedMesh; + protected int[][] m_BodyPartHumanBone = new int[][] + { + new int[] + { + -1 + }, + new int[] + { + 0, + 7, + 8 + }, + new int[] + { + 9, + 10, + 21, + 22, + 23 + }, + new int[] + { + 11, + 13, + 15, + 17 + }, + new int[] + { + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38 + }, + new int[] + { + 12, + 14, + 16, + 18 + }, + new int[] + { + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53 + }, + new int[] + { + 1, + 3, + 5, + 19 + }, + new int[] + { + 2, + 4, + 6, + 20 + } + }; + private Vector2 m_FoldoutScroll = Vector2.zero; + internal static AvatarMappingEditor.Styles styles + { + get + { + if (AvatarMappingEditor.s_Styles == null) + { + AvatarMappingEditor.s_Styles = new AvatarMappingEditor.Styles(); + } + return AvatarMappingEditor.s_Styles; + } + } + public AvatarMappingEditor() + { + if (AvatarSetupTool.sHumanParent.Length != HumanTrait.BoneCount) + { + throw new Exception("Avatar's Human parent list is out of sync"); + } + this.m_BodyPartToggle = new bool[9]; + this.m_BodyPartFoldout = new bool[9]; + for (int i = 0; i < 9; i++) + { + this.m_BodyPartToggle[i] = false; + this.m_BodyPartFoldout[i] = true; + } + } + public override void Enable(AvatarEditor inspector) + { + base.Enable(inspector); + this.Init(); + } + protected void Init() + { + if (base.gameObject == null) + { + return; + } + if (this.m_Bones == null) + { + this.m_Bones = AvatarSetupTool.GetHumanBones(base.serializedObject, base.modelBones); + } + this.ValidateMapping(); + this.m_HasSkinnedMesh = (base.gameObject.GetComponentInChildren() != null); + this.InitPose(); + SceneView.RepaintAll(); + } + protected override void ResetValues() + { + base.ResetValues(); + this.ResetBones(); + this.Init(); + } + protected void ResetBones() + { + for (int i = 0; i < this.m_Bones.Length; i++) + { + this.m_Bones[i].Reset(base.serializedObject, base.modelBones); + } + } + protected bool IsValidHuman() + { + Animator component = base.gameObject.GetComponent(); + if (component == null) + { + return false; + } + Avatar avatar = component.avatar; + return avatar != null && avatar.isHuman; + } + protected void InitPose() + { + if (this.IsValidHuman()) + { + Animator component = base.gameObject.GetComponent(); + component.WriteDefaultPose(); + AvatarSetupTool.TransferDescriptionToPose(base.serializedObject, base.root); + } + } + protected void ValidateMapping() + { + for (int i = 0; i < this.m_Bones.Length; i++) + { + string error; + this.m_Bones[i].state = this.GetBoneState(i, out error); + this.m_Bones[i].error = error; + } + } + private void EnableBodyParts(bool[] toggles, params int[] parts) + { + for (int i = 0; i < this.m_BodyPartToggle.Length; i++) + { + toggles[i] = false; + } + for (int j = 0; j < parts.Length; j++) + { + int num = parts[j]; + toggles[num] = true; + } + } + private void HandleBodyView(int bodyView) + { + if (bodyView == 0) + { + this.EnableBodyParts(this.m_BodyPartToggle, new int[] + { + 1, + 3, + 5, + 7, + 8 + }); + } + if (bodyView == 1) + { + this.EnableBodyParts(this.m_BodyPartToggle, new int[] + { + 2 + }); + } + if (bodyView == 2) + { + this.EnableBodyParts(this.m_BodyPartToggle, new int[] + { + 4 + }); + } + if (bodyView == 3) + { + this.EnableBodyParts(this.m_BodyPartToggle, new int[] + { + 6 + }); + } + } + public override void OnInspectorGUI() + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "UndoRedoPerformed") + { + AvatarSetupTool.TransferPoseToDescription(base.serializedObject, base.root); + for (int i = 0; i < this.m_Bones.Length; i++) + { + this.m_Bones[i].Serialize(base.serializedObject); + } + } + this.UpdateSelectedBone(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + GUILayout.BeginVertical(string.Empty, "TE NodeBackground", new GUILayoutOption[0]); + this.m_BodyView = AvatarControl.ShowBoneMapping(this.m_BodyView, new AvatarControl.BodyPartFeedback(this.IsValidBodyPart), this.m_Bones, base.serializedObject, this); + this.HandleBodyView(this.m_BodyView); + GUILayout.EndVertical(); + this.m_FoldoutScroll = GUILayout.BeginScrollView(this.m_FoldoutScroll, AvatarMappingEditor.styles.box, new GUILayoutOption[] + { + GUILayout.MinHeight(80f), + GUILayout.MaxHeight(500f), + GUILayout.ExpandHeight(true) + }); + this.DisplayFoldout(); + GUILayout.FlexibleSpace(); + GUILayout.EndScrollView(); + if (EditorGUI.EndChangeCheck()) + { + this.ValidateMapping(); + SceneView.RepaintAll(); + } + this.DisplayMappingButtons(); + GUILayout.EndVertical(); + if (GUIUtility.hotControl == 0) + { + this.TransferPoseIfChanged(); + } + base.ApplyRevertGUI(); + } + protected void DebugPoseButtons() + { + if (GUILayout.Button("Default Pose", new GUILayoutOption[0]) && this.IsValidHuman()) + { + Animator component = base.gameObject.GetComponent(); + component.WriteDefaultPose(); + } + if (GUILayout.Button("Description Pose", new GUILayoutOption[0])) + { + AvatarSetupTool.TransferDescriptionToPose(base.serializedObject, base.root); + } + } + protected void TransferPoseIfChanged() + { + GameObject[] gameObjects = Selection.gameObjects; + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject gameObject = gameObjects[i]; + if (this.TransformChanged(gameObject.transform)) + { + AvatarSetupTool.TransferPoseToDescription(base.serializedObject, base.root); + this.m_Inspector.Repaint(); + break; + } + } + } + protected void DisplayMappingButtons() + { + GUILayout.BeginHorizontal(string.Empty, AvatarMappingEditor.styles.toolbar, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + Rect rect = GUILayoutUtility.GetRect(AvatarMappingEditor.styles.mapping, AvatarMappingEditor.styles.toolbarDropDown); + if (GUI.Button(rect, AvatarMappingEditor.styles.mapping, AvatarMappingEditor.styles.toolbarDropDown)) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(AvatarMappingEditor.styles.clearMapping, false, new GenericMenu.MenuFunction(this.ClearMapping)); + genericMenu.AddItem(AvatarMappingEditor.styles.autoMapping, false, new GenericMenu.MenuFunction(this.PerformAutoMapping)); + genericMenu.AddItem(AvatarMappingEditor.styles.loadMapping, false, new GenericMenu.MenuFunction(this.ApplyTemplate)); + genericMenu.AddItem(AvatarMappingEditor.styles.saveMapping, false, new GenericMenu.MenuFunction(this.SaveHumanTemplate)); + genericMenu.DropDown(rect); + } + rect = GUILayoutUtility.GetRect(AvatarMappingEditor.styles.pose, AvatarMappingEditor.styles.toolbarDropDown); + if (GUI.Button(rect, AvatarMappingEditor.styles.pose, AvatarMappingEditor.styles.toolbarDropDown)) + { + GenericMenu genericMenu2 = new GenericMenu(); + genericMenu2.AddItem(AvatarMappingEditor.styles.resetPose, false, new GenericMenu.MenuFunction(this.CopyPrefabPose)); + if (this.m_HasSkinnedMesh) + { + genericMenu2.AddItem(AvatarMappingEditor.styles.sampleBindPose, false, new GenericMenu.MenuFunction(this.SampleBindPose)); + } + else + { + genericMenu2.AddItem(AvatarMappingEditor.styles.sampleBindPose, false, null); + } + genericMenu2.AddItem(AvatarMappingEditor.styles.enforceTPose, false, new GenericMenu.MenuFunction(this.MakePoseValid)); + genericMenu2.DropDown(rect); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + protected void CopyPrefabPose() + { + AvatarSetupTool.CopyPose(base.gameObject, base.prefab); + AvatarSetupTool.TransferPoseToDescription(base.serializedObject, base.root); + this.m_Inspector.Repaint(); + } + protected void SampleBindPose() + { + AvatarSetupTool.SampleBindPose(base.gameObject); + AvatarSetupTool.TransferPoseToDescription(base.serializedObject, base.root); + this.m_Inspector.Repaint(); + } + protected void MakePoseValid() + { + AvatarSetupTool.MakePoseValid(this.m_Bones); + AvatarSetupTool.TransferPoseToDescription(base.serializedObject, base.root); + this.m_Inspector.Repaint(); + } + protected void PerformAutoMapping() + { + this.AutoMapping(); + this.ValidateMapping(); + SceneView.RepaintAll(); + } + protected void AutoMapping() + { + Dictionary dictionary = AvatarAutoMapper.MapBones(base.gameObject.transform, base.modelBones); + foreach (KeyValuePair current in dictionary) + { + AvatarSetupTool.BoneWrapper boneWrapper = this.m_Bones[current.Key]; + boneWrapper.bone = current.Value; + boneWrapper.Serialize(base.serializedObject); + } + } + protected void ClearMapping() + { + if (base.serializedObject != null) + { + Undo.RegisterCompleteObjectUndo(this, "Clear Mapping"); + AvatarSetupTool.ClearHumanBoneArray(base.serializedObject); + this.ResetBones(); + this.ValidateMapping(); + SceneView.RepaintAll(); + } + } + protected Vector4 QuaternionToVector4(Quaternion rot) + { + return new Vector4(rot.x, rot.y, rot.z, rot.w); + } + protected Quaternion Vector4ToQuaternion(Vector4 rot) + { + return new Quaternion(rot.x, rot.y, rot.z, rot.w); + } + protected bool IsAnyBodyPartActive() + { + for (int i = 1; i < this.m_BodyPartToggle.Length; i++) + { + if (this.m_BodyPartToggle[i]) + { + return true; + } + } + return false; + } + private void UpdateSelectedBone() + { + int num = AvatarMappingEditor.s_SelectedBoneIndex; + if (AvatarMappingEditor.s_SelectedBoneIndex < 0 || AvatarMappingEditor.s_SelectedBoneIndex >= this.m_Bones.Length || this.m_Bones[AvatarMappingEditor.s_SelectedBoneIndex].bone != Selection.activeTransform) + { + AvatarMappingEditor.s_SelectedBoneIndex = -1; + if (Selection.activeTransform != null) + { + for (int i = 0; i < this.m_Bones.Length; i++) + { + if (this.m_Bones[i].bone == Selection.activeTransform) + { + AvatarMappingEditor.s_SelectedBoneIndex = i; + break; + } + } + } + } + if (AvatarMappingEditor.s_SelectedBoneIndex != num) + { + List viewsThatContainBone = AvatarControl.GetViewsThatContainBone(AvatarMappingEditor.s_SelectedBoneIndex); + if (viewsThatContainBone.Count > 0 && !viewsThatContainBone.Contains(this.m_BodyView)) + { + this.m_BodyView = viewsThatContainBone[0]; + } + } + } + protected void DisplayFoldout() + { + Dictionary modelBones = base.modelBones; + EditorGUIUtility.SetIconSize(Vector2.one * 16f); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.color = Color.grey; + GUILayout.Label(AvatarMappingEditor.styles.dotFrameDotted.image, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUI.color = Color.white; + GUILayout.Label("Optional Bone", new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + EditorGUILayout.EndHorizontal(); + for (int i = 1; i < this.m_BodyPartToggle.Length; i++) + { + if (this.m_BodyPartToggle[i]) + { + this.m_BodyPartFoldout[i] = GUILayout.Toggle(this.m_BodyPartFoldout[i], AvatarMappingEditor.styles.BodyPartMapping[i], EditorStyles.foldout, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + if (this.m_BodyPartFoldout[i]) + { + for (int j = 0; j < this.m_BodyPartHumanBone[i].Length; j++) + { + int num = this.m_BodyPartHumanBone[i][j]; + if (num != -1) + { + AvatarSetupTool.BoneWrapper boneWrapper = this.m_Bones[num]; + string text = boneWrapper.humanBoneName; + if (i == 5 || i == 6 || i == 8) + { + text = text.Replace("Right", string.Empty); + } + if (i == 3 || i == 4 || i == 7) + { + text = text.Replace("Left", string.Empty); + } + text = ObjectNames.NicifyVariableName(text); + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + Rect selectRect = controlRect; + selectRect.width -= 15f; + boneWrapper.HandleClickSelection(selectRect, num); + boneWrapper.BoneDotGUI(new Rect(controlRect.x + EditorGUI.indent, controlRect.y - 1f, 19f, 19f), num, false, false, base.serializedObject, this); + controlRect.xMin += 19f; + Transform transform = EditorGUI.ObjectField(controlRect, new GUIContent(text), boneWrapper.bone, typeof(Transform), true) as Transform; + if (transform != boneWrapper.bone) + { + Undo.RegisterCompleteObjectUndo(this, "Avatar mapping modified"); + boneWrapper.bone = transform; + boneWrapper.Serialize(base.serializedObject); + if (transform != null && !modelBones.ContainsKey(transform)) + { + modelBones[transform] = true; + } + } + if (!string.IsNullOrEmpty(boneWrapper.error)) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(EditorGUI.indent + 19f + 4f); + GUILayout.Label(boneWrapper.error, AvatarMappingEditor.s_Styles.errorLabel, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + } + } + } + EditorGUI.indentLevel--; + } + } + EditorGUIUtility.SetIconSize(Vector2.zero); + } + private bool TransformChanged(Transform tr) + { + SerializedProperty serializedProperty = AvatarSetupTool.FindSkeletonBone(base.serializedObject, tr, false, false); + if (serializedProperty != null) + { + SerializedProperty serializedProperty2 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sPosition); + if (serializedProperty2 != null && serializedProperty2.vector3Value != tr.localPosition) + { + return true; + } + SerializedProperty serializedProperty3 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sRotation); + if (serializedProperty3 != null && serializedProperty3.quaternionValue != tr.localRotation) + { + return true; + } + SerializedProperty serializedProperty4 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sScale); + if (serializedProperty4 != null && serializedProperty4.vector3Value != tr.localScale) + { + return true; + } + } + return false; + } + protected BoneState GetBoneState(int i, out string error) + { + error = string.Empty; + AvatarSetupTool.BoneWrapper bone = this.m_Bones[i]; + if (bone.bone == null) + { + return BoneState.None; + } + AvatarSetupTool.BoneWrapper boneWrapper = this.m_Bones[AvatarSetupTool.GetFirstHumanBoneAncestor(this.m_Bones, i)]; + if (i == 0 && bone.bone.parent == null) + { + error = bone.messageName + " cannot be the root transform"; + return BoneState.InvalidHierarchy; + } + if (boneWrapper.bone != null && !bone.bone.IsChildOf(boneWrapper.bone)) + { + error = bone.messageName + " is not a child of " + boneWrapper.messageName + "."; + return BoneState.InvalidHierarchy; + } + if (i != 23 && boneWrapper.bone != null && boneWrapper.bone != bone.bone && (bone.bone.position - boneWrapper.bone.position).sqrMagnitude < 1.401298E-45f) + { + error = bone.messageName + " has bone length of zero."; + return BoneState.BoneLenghtIsZero; + } + IEnumerable source = + from f in this.m_Bones + where f.bone == bone.bone + select f; + if (source.Count() > 1) + { + error = bone.messageName + " is also assigned to "; + bool flag = true; + for (int j = 0; j < this.m_Bones.Length; j++) + { + if (i != j && this.m_Bones[i].bone == this.m_Bones[j].bone) + { + if (flag) + { + flag = false; + } + else + { + error += ", "; + } + error += ObjectNames.NicifyVariableName(this.m_Bones[j].humanBoneName); + } + } + error += "."; + return BoneState.Duplicate; + } + return BoneState.Valid; + } + protected AvatarControl.BodyPartColor IsValidBodyPart(BodyPart bodyPart) + { + AvatarControl.BodyPartColor bodyPartColor = AvatarControl.BodyPartColor.Off; + bool flag = false; + if (bodyPart != BodyPart.LeftFingers && bodyPart != BodyPart.RightFingers) + { + for (int i = 0; i < this.m_BodyPartHumanBone[(int)bodyPart].Length; i++) + { + if (this.m_BodyPartHumanBone[(int)bodyPart][i] != -1) + { + BoneState state = this.m_Bones[this.m_BodyPartHumanBone[(int)bodyPart][i]].state; + flag |= (state == BoneState.Valid); + if (HumanTrait.RequiredBone(this.m_BodyPartHumanBone[(int)bodyPart][i]) && state == BoneState.None) + { + return AvatarControl.BodyPartColor.Red; + } + if (state != BoneState.Valid && state != BoneState.None) + { + return AvatarControl.BodyPartColor.Red; + } + } + } + } + else + { + bool flag2 = true; + int num = 3; + for (int j = 0; j < this.m_BodyPartHumanBone[(int)bodyPart].Length / num; j++) + { + bool flag3 = false; + int num2 = j * num; + for (int k = num - 1; k >= 0; k--) + { + bool flag4 = this.m_Bones[this.m_BodyPartHumanBone[(int)bodyPart][num2 + k]].state == BoneState.Valid; + flag2 &= flag4; + if (flag3) + { + if (!flag4) + { + return (AvatarControl.BodyPartColor)10; + } + } + else + { + flag |= (flag3 = (!flag3 && flag4)); + } + } + } + bodyPartColor = ((!flag2) ? AvatarControl.BodyPartColor.IKRed : AvatarControl.BodyPartColor.IKGreen); + } + if (!flag) + { + return AvatarControl.BodyPartColor.IKRed; + } + return AvatarControl.BodyPartColor.Green | bodyPartColor; + } + private HumanTemplate OpenHumanTemplate() + { + string text = "Assets/"; + string text2 = EditorUtility.OpenFilePanel("Open Human Template", text, "ht"); + if (text2 == string.Empty) + { + return null; + } + string projectRelativePath = FileUtil.GetProjectRelativePath(text2); + HumanTemplate humanTemplate = AssetDatabase.LoadMainAssetAtPath(projectRelativePath) as HumanTemplate; + if (humanTemplate == null && EditorUtility.DisplayDialog("Human Template not found in project", "Import asset '" + text2 + "' into project", "Yes", "No")) + { + string text3 = text + FileUtil.GetLastPathNameComponent(text2); + text3 = AssetDatabase.GenerateUniqueAssetPath(text3); + FileUtil.CopyFileOrDirectory(text2, text3); + AssetDatabase.Refresh(); + humanTemplate = (AssetDatabase.LoadMainAssetAtPath(text3) as HumanTemplate); + if (humanTemplate == null) + { + Debug.Log(string.Concat(new string[] + { + "Failed importing file '", + text2, + "' to '", + text3, + "'" + })); + } + } + return humanTemplate; + } + public static bool MatchName(string transformName, string boneName) + { + string text = ":"; + char[] separator = text.ToCharArray(); + string[] array = transformName.Split(separator); + string[] array2 = boneName.Split(separator); + return transformName == boneName || (array.Length > 1 && array[1] == boneName) || (array2.Length > 1 && transformName == array2[1]) || (array.Length > 1 && array2.Length > 1 && array[1] == array2[1]); + } + protected void ApplyTemplate() + { + Undo.RegisterCompleteObjectUndo(this, "Apply Template"); + HumanTemplate humanTemplate = this.OpenHumanTemplate(); + if (humanTemplate == null) + { + return; + } + for (int i = 0; i < this.m_Bones.Length; i++) + { + string boneName = humanTemplate.Find(this.m_Bones[i].humanBoneName); + if (boneName.Length > 0) + { + Transform bone = base.modelBones.Keys.First((Transform f) => AvatarMappingEditor.MatchName(f.name, boneName)); + this.m_Bones[i].bone = bone; + } + else + { + this.m_Bones[i].bone = null; + } + this.m_Bones[i].Serialize(base.serializedObject); + } + this.ValidateMapping(); + SceneView.RepaintAll(); + } + private void SaveHumanTemplate() + { + string message = string.Format("Create a new human template", new object[0]); + string text = EditorUtility.SaveFilePanelInProject("Create New Human Template", "New Human Template", "ht", message); + if (text == string.Empty) + { + return; + } + HumanTemplate humanTemplate = new HumanTemplate(); + humanTemplate.ClearTemplate(); + for (int i = 0; i < this.m_Bones.Length; i++) + { + if (this.m_Bones[i].bone != null) + { + humanTemplate.Insert(this.m_Bones[i].humanBoneName, this.m_Bones[i].bone.name); + } + } + AssetDatabase.CreateAsset(humanTemplate, text); + } + public override void OnSceneGUI() + { + if (AvatarMappingEditor.s_Styles == null) + { + return; + } + AvatarSkeletonDrawer.DrawSkeleton(base.root, base.modelBones, this.m_Bones); + if (GUIUtility.hotControl == 0) + { + this.TransferPoseIfChanged(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarMaskInspector.cs b/UnityEditor/UnityEditor/AvatarMaskInspector.cs new file mode 100644 index 00000000..140b3b1e --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarMaskInspector.cs @@ -0,0 +1,440 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AvatarMask))] + internal class AvatarMaskInspector : Editor + { + private class Styles + { + public GUIContent MaskDefinition = EditorGUIUtility.TextContent("AvatarMaskEditor.MaskDefinition"); + public GUIContent[] MaskDefinitionOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("AvatarMaskEditor.CreateFromThisModel"), + EditorGUIUtility.TextContent("AvatarMaskEditor.CopyFromOther") + }; + public GUIContent BodyMask = EditorGUIUtility.TextContent("AvatarMaskEditor.BodyMask"); + public GUIContent TransformMask = EditorGUIUtility.TextContent("AvatarMaskEditor.TransformMask"); + } + private struct NodeInfo + { + public bool m_Expanded; + public bool m_Show; + public bool m_Enabled; + public int m_ParentIndex; + public List m_ChildIndices; + public int m_Depth; + } + private static AvatarMaskInspector.Styles styles = new AvatarMaskInspector.Styles(); + protected bool[] m_BodyPartToggle; + private bool m_ShowBodyMask = true; + private bool m_BodyMaskFoldout; + private bool m_CanImport = true; + private SerializedProperty m_AnimationType; + private AnimationClipInfoProperties m_ClipInfo; + private AvatarMaskInspector.NodeInfo[] m_NodeInfos; + private Avatar m_RefAvatar; + private ModelImporter m_RefImporter; + private bool m_TransformMaskFoldout; + private string[] m_HumanTransform; + public bool canImport + { + get + { + return this.m_CanImport; + } + set + { + this.m_CanImport = value; + } + } + public AnimationClipInfoProperties clipInfo + { + get + { + return this.m_ClipInfo; + } + set + { + this.m_ClipInfo = value; + if (this.m_ClipInfo != null) + { + this.m_ClipInfo.MaskFromClip(this.target as AvatarMask); + SerializedObject serializedObject = this.m_ClipInfo.maskTypeProperty.serializedObject; + this.m_AnimationType = serializedObject.FindProperty("m_AnimationType"); + } + else + { + this.m_AnimationType = null; + } + } + } + private ModelImporterAnimationType animationType + { + get + { + if (this.m_AnimationType != null) + { + return (ModelImporterAnimationType)this.m_AnimationType.intValue; + } + return ModelImporterAnimationType.None; + } + } + public bool showBody + { + get + { + return this.m_ShowBodyMask; + } + set + { + this.m_ShowBodyMask = value; + } + } + public string[] humanTransforms + { + get + { + if (this.animationType == ModelImporterAnimationType.Human && this.clipInfo != null) + { + if (this.m_HumanTransform == null) + { + SerializedObject serializedObject = this.clipInfo.maskTypeProperty.serializedObject; + ModelImporter modelImporter = serializedObject.targetObject as ModelImporter; + this.m_HumanTransform = AvatarMaskUtility.GetAvatarHumanTransform(serializedObject, modelImporter.transformPaths); + } + } + else + { + this.m_HumanTransform = null; + } + return this.m_HumanTransform; + } + } + private void OnEnable() + { + AvatarMask avatarMask = this.target as AvatarMask; + this.m_BodyPartToggle = new bool[avatarMask.humanoidBodyPartCount]; + } + public override void OnInspectorGUI() + { + EditorGUI.BeginChangeCheck(); + bool flag = false; + if (this.clipInfo != null) + { + EditorGUI.BeginChangeCheck(); + int num = (int)this.clipInfo.maskType; + EditorGUI.showMixedValue = this.clipInfo.maskTypeProperty.hasMultipleDifferentValues; + num = EditorGUILayout.Popup(AvatarMaskInspector.styles.MaskDefinition, num, AvatarMaskInspector.styles.MaskDefinitionOpt, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.clipInfo.maskType = (ClipAnimationMaskType)num; + this.UpdateMask(this.clipInfo.maskType); + } + flag = (this.clipInfo.maskType == ClipAnimationMaskType.CopyFromOther); + } + if (flag) + { + this.CopyFromOtherGUI(); + } + bool enabled = GUI.enabled; + GUI.enabled = !flag; + this.OnBodyInspectorGUI(); + this.OnTransformInspectorGUI(); + GUI.enabled = enabled; + if (EditorGUI.EndChangeCheck() && this.clipInfo != null) + { + this.clipInfo.MaskToClip(this.target as AvatarMask); + } + } + protected void CopyFromOtherGUI() + { + if (this.clipInfo == null) + { + return; + } + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.clipInfo.maskSourceProperty, GUIContent.Temp("Source"), new GUILayoutOption[0]); + AvatarMask x = this.clipInfo.maskSourceProperty.objectReferenceValue as AvatarMask; + if (EditorGUI.EndChangeCheck() && x != null) + { + this.UpdateMask(this.clipInfo.maskType); + } + EditorGUILayout.EndHorizontal(); + } + private void UpdateMask(ClipAnimationMaskType maskType) + { + if (this.clipInfo == null) + { + return; + } + if (maskType == ClipAnimationMaskType.CreateFromThisModel) + { + SerializedObject serializedObject = this.clipInfo.maskTypeProperty.serializedObject; + ModelImporter modelImporter = serializedObject.targetObject as ModelImporter; + AvatarMask mask = this.target as AvatarMask; + AvatarMaskUtility.UpdateTransformMask(mask, modelImporter.transformPaths, this.humanTransforms); + this.FillNodeInfos(mask); + } + else + { + if (maskType == ClipAnimationMaskType.CopyFromOther) + { + AvatarMask avatarMask = this.clipInfo.maskSourceProperty.objectReferenceValue as AvatarMask; + if (avatarMask != null) + { + AvatarMask avatarMask2 = this.target as AvatarMask; + avatarMask2.Copy(avatarMask); + this.FillNodeInfos(avatarMask2); + } + } + } + } + public void OnBodyInspectorGUI() + { + if (this.m_ShowBodyMask) + { + bool changed = GUI.changed; + this.m_BodyMaskFoldout = EditorGUILayout.Foldout(this.m_BodyMaskFoldout, AvatarMaskInspector.styles.BodyMask); + GUI.changed = changed; + if (this.m_BodyMaskFoldout) + { + AvatarMask avatarMask = this.target as AvatarMask; + for (int i = 0; i < avatarMask.humanoidBodyPartCount; i++) + { + this.m_BodyPartToggle[i] = avatarMask.GetHumanoidBodyPartActive(i); + } + this.m_BodyPartToggle = BodyMaskEditor.Show(this.m_BodyPartToggle, avatarMask.humanoidBodyPartCount); + bool flag = false; + for (int j = 0; j < avatarMask.humanoidBodyPartCount; j++) + { + flag |= (avatarMask.GetHumanoidBodyPartActive(j) != this.m_BodyPartToggle[j]); + } + if (flag) + { + Undo.RegisterCompleteObjectUndo(avatarMask, "Body Mask Edit"); + for (int k = 0; k < avatarMask.humanoidBodyPartCount; k++) + { + avatarMask.SetHumanoidBodyPartActive(k, this.m_BodyPartToggle[k]); + } + EditorUtility.SetDirty(avatarMask); + } + } + } + } + public void OnTransformInspectorGUI() + { + AvatarMask avatarMask = this.target as AvatarMask; + float left = 0f; + float top = 0f; + float num = 0f; + float bottom = 0f; + bool changed = GUI.changed; + this.m_TransformMaskFoldout = EditorGUILayout.Foldout(this.m_TransformMaskFoldout, AvatarMaskInspector.styles.TransformMask); + GUI.changed = changed; + if (this.m_TransformMaskFoldout) + { + if (this.canImport) + { + this.ImportAvatarReference(); + } + if (this.m_NodeInfos == null || avatarMask.transformCount != this.m_NodeInfos.Length) + { + this.FillNodeInfos(avatarMask); + } + this.ComputeShownElements(); + GUILayout.Space(1f); + int indentLevel = EditorGUI.indentLevel; + int transformCount = avatarMask.transformCount; + for (int i = 1; i < transformCount; i++) + { + if (this.m_NodeInfos[i].m_Show) + { + string transformPath = avatarMask.GetTransformPath(i); + string[] array = transformPath.Split(new char[] + { + '/' + }); + string text = array[array.Length - 1]; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.indentLevel = this.m_NodeInfos[i].m_Depth + 1; + EditorGUI.BeginChangeCheck(); + Rect rect = GUILayoutUtility.GetRect(15f, 15f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayoutUtility.GetRect(10f, 15f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + rect.x += 15f; + bool enabled = GUI.enabled; + GUI.enabled = this.m_NodeInfos[i].m_Enabled; + bool flag = Event.current.button == 1; + avatarMask.SetTransformActive(i, GUI.Toggle(rect, avatarMask.GetTransformActive(i), string.Empty)); + GUI.enabled = enabled; + if (EditorGUI.EndChangeCheck() && !flag) + { + this.CheckChildren(avatarMask, i, avatarMask.GetTransformActive(i)); + } + if (this.m_NodeInfos[i].m_ChildIndices.Count > 0) + { + this.m_NodeInfos[i].m_Expanded = EditorGUILayout.Foldout(this.m_NodeInfos[i].m_Expanded, text); + } + else + { + EditorGUILayout.LabelField(text, new GUILayoutOption[0]); + } + if (i == 1) + { + top = rect.yMin; + left = rect.xMin; + } + else + { + if (i == transformCount - 1) + { + bottom = rect.yMax; + } + } + num = Mathf.Max(num, GUILayoutUtility.GetLastRect().xMax); + GUILayout.EndHorizontal(); + } + } + EditorGUI.indentLevel = indentLevel; + } + Rect rect2 = Rect.MinMaxRect(left, top, num, bottom); + if (Event.current != null && Event.current.type == EventType.MouseUp && Event.current.button == 1 && rect2.Contains(Event.current.mousePosition)) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Select all"), false, new GenericMenu.MenuFunction(this.SelectAll)); + genericMenu.AddItem(new GUIContent("Deselect all"), false, new GenericMenu.MenuFunction(this.DeselectAll)); + genericMenu.ShowAsContext(); + Event.current.Use(); + } + } + private void SetAllTransformActive(bool active) + { + for (int i = 0; i < this.m_NodeInfos.Length; i++) + { + if (this.m_NodeInfos[i].m_Enabled) + { + (this.target as AvatarMask).SetTransformActive(i, active); + } + } + if (this.clipInfo != null) + { + this.clipInfo.MaskToClip(this.target as AvatarMask); + } + } + private void SelectAll() + { + this.SetAllTransformActive(true); + } + private void DeselectAll() + { + this.SetAllTransformActive(false); + } + private void ImportAvatarReference() + { + EditorGUI.BeginChangeCheck(); + this.m_RefAvatar = (EditorGUILayout.ObjectField("Use skeleton from", this.m_RefAvatar, typeof(Avatar), true, new GUILayoutOption[0]) as Avatar); + if (EditorGUI.EndChangeCheck()) + { + this.m_RefImporter = (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.m_RefAvatar)) as ModelImporter); + } + if (this.m_RefImporter != null && GUILayout.Button("Import skeleton", new GUILayoutOption[0])) + { + AvatarMaskUtility.UpdateTransformMask(this.target as AvatarMask, this.m_RefImporter.transformPaths, null); + } + } + private void FillNodeInfos(AvatarMask mask) + { + this.m_NodeInfos = new AvatarMaskInspector.NodeInfo[mask.transformCount]; + for (int i = 1; i < this.m_NodeInfos.Length; i++) + { + string fullPath = mask.GetTransformPath(i); + if (this.humanTransforms != null) + { + this.m_NodeInfos[i].m_Enabled = (ArrayUtility.FindIndex(this.humanTransforms, (string s) => fullPath == s) == -1); + } + else + { + this.m_NodeInfos[i].m_Enabled = true; + } + this.m_NodeInfos[i].m_Expanded = true; + this.m_NodeInfos[i].m_ParentIndex = -1; + this.m_NodeInfos[i].m_ChildIndices = new List(); + AvatarMaskInspector.NodeInfo[] arg_F6_0_cp_0 = this.m_NodeInfos; + int arg_F6_0_cp_1 = i; + int arg_F6_1; + if (i == 0) + { + arg_F6_1 = 0; + } + else + { + arg_F6_1 = fullPath.Count((char f) => f == '/'); + } + arg_F6_0_cp_0[arg_F6_0_cp_1].m_Depth = arg_F6_1; + string text = string.Empty; + int num = fullPath.LastIndexOf('/'); + if (num > 0) + { + text = fullPath.Substring(0, num); + } + int transformCount = mask.transformCount; + for (int j = 0; j < transformCount; j++) + { + string transformPath = mask.GetTransformPath(j); + if (text != string.Empty && transformPath == text) + { + this.m_NodeInfos[i].m_ParentIndex = j; + } + if (transformPath.StartsWith(fullPath)) + { + if (transformPath.Count((char f) => f == '/') == this.m_NodeInfos[i].m_Depth + 1) + { + this.m_NodeInfos[i].m_ChildIndices.Add(j); + } + } + } + } + } + private void ComputeShownElements() + { + for (int i = 0; i < this.m_NodeInfos.Length; i++) + { + if (this.m_NodeInfos[i].m_ParentIndex == -1) + { + this.ComputeShownElements(i, true); + } + } + } + private void ComputeShownElements(int currentIndex, bool show) + { + this.m_NodeInfos[currentIndex].m_Show = show; + bool show2 = show && this.m_NodeInfos[currentIndex].m_Expanded; + foreach (int current in this.m_NodeInfos[currentIndex].m_ChildIndices) + { + this.ComputeShownElements(current, show2); + } + } + private void CheckChildren(AvatarMask mask, int index, bool value) + { + foreach (int current in this.m_NodeInfos[index].m_ChildIndices) + { + if (this.m_NodeInfos[current].m_Enabled) + { + mask.SetTransformActive(current, value); + } + this.CheckChildren(mask, current, value); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarMaskUtility.cs b/UnityEditor/UnityEditor/AvatarMaskUtility.cs new file mode 100644 index 00000000..215ab91b --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarMaskUtility.cs @@ -0,0 +1,73 @@ +using System; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AvatarMaskUtility + { + private static string sHuman = "m_HumanDescription.m_Human"; + private static string sBoneName = "m_BoneName"; + public static string[] GetAvatarHumanTransform(SerializedObject so, string[] refTransformsPath) + { + SerializedProperty serializedProperty = so.FindProperty(AvatarMaskUtility.sHuman); + if (serializedProperty == null || !serializedProperty.isArray) + { + return null; + } + string[] humanTransforms = new string[0]; + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative(AvatarMaskUtility.sBoneName); + ArrayUtility.Add(ref humanTransforms, serializedProperty2.stringValue); + } + return AvatarMaskUtility.TokeniseHumanTransformsPath(refTransformsPath, humanTransforms); + } + public static void UpdateTransformMask(AvatarMask mask, string[] refTransformsPath, string[] humanTransforms) + { + AvatarMaskUtility.c__AnonStorey50 c__AnonStorey = new AvatarMaskUtility.c__AnonStorey50(); + c__AnonStorey.refTransformsPath = refTransformsPath; + mask.Reset(); + mask.transformCount = c__AnonStorey.refTransformsPath.Length; + int i; + for (i = 0; i < c__AnonStorey.refTransformsPath.Length; i++) + { + mask.SetTransformPath(i, c__AnonStorey.refTransformsPath[i]); + bool value = humanTransforms == null || ArrayUtility.FindIndex(humanTransforms, (string s) => c__AnonStorey.refTransformsPath[i] == s) != -1; + mask.SetTransformActive(i, value); + } + } + private static string[] TokeniseHumanTransformsPath(string[] refTransformsPath, string[] humanTransforms) + { + AvatarMaskUtility.c__AnonStorey52 c__AnonStorey = new AvatarMaskUtility.c__AnonStorey52(); + c__AnonStorey.humanTransforms = humanTransforms; + if (c__AnonStorey.humanTransforms == null) + { + return null; + } + string[] array = new string[] + { + string.Empty + }; + int i; + for (i = 0; i < c__AnonStorey.humanTransforms.Length; i++) + { + int num = ArrayUtility.FindIndex(refTransformsPath, (string s) => c__AnonStorey.humanTransforms[i] == FileUtil.GetLastPathNameComponent(s)); + if (num != -1) + { + int index = array.Length; + string path = refTransformsPath[num]; + while (path.Length > 0) + { + int num2 = ArrayUtility.FindIndex(array, (string s) => path == s); + if (num2 == -1) + { + ArrayUtility.Insert(ref array, index, path); + } + int num3 = path.LastIndexOf('/'); + path = path.Substring(0, (num3 == -1) ? 0 : num3); + } + } + } + return array; + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarMuscleEditor.cs b/UnityEditor/UnityEditor/AvatarMuscleEditor.cs new file mode 100644 index 00000000..58479ee7 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarMuscleEditor.cs @@ -0,0 +1,899 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class AvatarMuscleEditor : AvatarSubEditor + { + private class Styles + { + public GUIContent[] muscleBodyGroup = new GUIContent[] + { + EditorGUIUtility.TextContent("Body"), + EditorGUIUtility.TextContent("Head"), + EditorGUIUtility.TextContent("Left Arm"), + EditorGUIUtility.TextContent("Left Fingers"), + EditorGUIUtility.TextContent("Right Arm"), + EditorGUIUtility.TextContent("Right Fingers"), + EditorGUIUtility.TextContent("Left Leg"), + EditorGUIUtility.TextContent("Right Leg") + }; + public GUIContent[] muscleTypeGroup = new GUIContent[] + { + EditorGUIUtility.TextContent("Open Close"), + EditorGUIUtility.TextContent("Left Right"), + EditorGUIUtility.TextContent("Roll Left Right"), + EditorGUIUtility.TextContent("In Out"), + EditorGUIUtility.TextContent("Roll In Out"), + EditorGUIUtility.TextContent("Finger Open Close"), + EditorGUIUtility.TextContent("Finger In Out") + }; + public GUIContent armTwist = EditorGUIUtility.TextContent("Upper Arm Twist"); + public GUIContent foreArmTwist = EditorGUIUtility.TextContent("Lower Arm Twist"); + public GUIContent upperLegTwist = EditorGUIUtility.TextContent("Upper Leg Twist"); + public GUIContent legTwist = EditorGUIUtility.TextContent("Lower Leg Twist"); + public GUIContent armStretch = EditorGUIUtility.TextContent("Arm Stretch"); + public GUIContent legStretch = EditorGUIUtility.TextContent("Leg Stretch"); + public GUIContent feetSpacing = EditorGUIUtility.TextContent("Feet Spacing"); + public GUIStyle box = new GUIStyle("OL box noexpand"); + public GUIStyle title = new GUIStyle("OL TITLE"); + public GUIStyle toolbar = "TE Toolbar"; + public GUIStyle toolbarDropDown = "TE ToolbarDropDown"; + public GUIContent muscle = EditorGUIUtility.TextContent("Muscles"); + public GUIContent resetMuscle = EditorGUIUtility.TextContent("Reset"); + public Styles() + { + this.box.padding = new RectOffset(0, 0, 4, 4); + } + } + private const string sMinX = "m_Limit.m_Min.x"; + private const string sMinY = "m_Limit.m_Min.y"; + private const string sMinZ = "m_Limit.m_Min.z"; + private const string sMaxX = "m_Limit.m_Max.x"; + private const string sMaxY = "m_Limit.m_Max.y"; + private const string sMaxZ = "m_Limit.m_Max.z"; + private const string sModified = "m_Limit.m_Modified"; + private const string sArmTwist = "m_HumanDescription.m_ArmTwist"; + private const string sForeArmTwist = "m_HumanDescription.m_ForeArmTwist"; + private const string sUpperLegTwist = "m_HumanDescription.m_UpperLegTwist"; + private const string sLegTwist = "m_HumanDescription.m_LegTwist"; + private const string sArmStretch = "m_HumanDescription.m_ArmStretch"; + private const string sLegStretch = "m_HumanDescription.m_LegStretch"; + private const string sFeetSpacing = "m_HumanDescription.m_FeetSpacing"; + private const float sMuscleMin = -180f; + private const float sMuscleMax = 180f; + private const float kPreviewWidth = 80f; + private const float kNumberWidth = 38f; + private const float kLineHeight = 16f; + private static AvatarMuscleEditor.Styles s_Styles; + protected int[][] m_Muscles = new int[][] + { + new int[] + { + 0, + 1, + 2, + 3, + 4, + 5 + }, + new int[] + { + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + }, + new int[] + { + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42 + }, + new int[] + { + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 60, + 61, + 62, + 63, + 64, + 65, + 66, + 67, + 68, + 69, + 70, + 71 + }, + new int[] + { + 43, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51 + }, + new int[] + { + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 91 + }, + new int[] + { + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25 + }, + new int[] + { + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33 + } + }; + protected int[][] m_MasterMuscle = new int[][] + { + new int[] + { + 0, + 3, + 6, + 9, + 18, + 21, + 23, + 26, + 29, + 31, + 34, + 36, + 39, + 41, + 43, + 45, + 48, + 50 + }, + new int[] + { + 1, + 4, + 7, + 10 + }, + new int[] + { + 2, + 5, + 8, + 11 + }, + new int[] + { + 19, + 24, + 27, + 32, + 35, + 37, + 42, + 44, + 46, + 51 + }, + new int[] + { + 20, + 22, + 28, + 30, + 38, + 40, + 47, + 49 + }, + new int[] + { + 52, + 54, + 55, + 56, + 58, + 59, + 60, + 62, + 63, + 64, + 66, + 67, + 68, + 70, + 71, + 72, + 74, + 75, + 76, + 78, + 79, + 80, + 82, + 83, + 84, + 86, + 87, + 88, + 90, + 91 + }, + new int[] + { + 53, + 57, + 61, + 65, + 69, + 73, + 77, + 81, + 85, + 89 + } + }; + private bool[] m_MuscleBodyGroupToggle; + private bool[] m_MuscleToggle; + private int m_FocusedMuscle; + [SerializeField] + private float[] m_MuscleValue; + [SerializeField] + private float[] m_MuscleMasterValue; + [SerializeField] + protected float m_ArmTwistFactor; + [SerializeField] + protected float m_ForeArmTwistFactor; + [SerializeField] + protected float m_UpperLegTwistFactor; + [SerializeField] + protected float m_LegTwistFactor; + [SerializeField] + protected float m_ArmStretchFactor; + [SerializeField] + protected float m_LegStretchFactor; + [SerializeField] + protected float m_FeetSpacingFactor; + private string[] m_MuscleName; + private int m_MuscleCount; + private SerializedProperty[] m_MuscleMin; + private SerializedProperty[] m_MuscleMax; + [SerializeField] + private float[] m_MuscleMinEdit; + [SerializeField] + private float[] m_MuscleMaxEdit; + private SerializedProperty[] m_Modified; + private SerializedProperty m_ArmTwistProperty; + private SerializedProperty m_ForeArmTwistProperty; + private SerializedProperty m_UpperLegTwistProperty; + private SerializedProperty m_LegTwistProperty; + private SerializedProperty m_ArmStretchProperty; + private SerializedProperty m_LegStretchProperty; + private SerializedProperty m_FeetSpacingProperty; + protected AvatarSetupTool.BoneWrapper[] m_Bones; + private static AvatarMuscleEditor.Styles styles + { + get + { + if (AvatarMuscleEditor.s_Styles == null) + { + AvatarMuscleEditor.s_Styles = new AvatarMuscleEditor.Styles(); + } + return AvatarMuscleEditor.s_Styles; + } + } + private static Rect GetSettingsRect(Rect wholeWidthRect) + { + wholeWidthRect.xMin += 83f; + wholeWidthRect.width -= 4f; + return wholeWidthRect; + } + private static Rect GetSettingsRect() + { + return AvatarMuscleEditor.GetSettingsRect(GUILayoutUtility.GetRect(10f, 16f)); + } + private static Rect GetPreviewRect(Rect wholeWidthRect) + { + wholeWidthRect.width = 71f; + wholeWidthRect.x += 5f; + wholeWidthRect.height = 16f; + return wholeWidthRect; + } + private void HeaderGUI(string h1, string h2) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(h1, AvatarMuscleEditor.styles.title, new GUILayoutOption[] + { + GUILayout.Width(80f) + }); + GUILayout.Label(h2, AvatarMuscleEditor.styles.title, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + GUILayout.EndHorizontal(); + } + private static float PreviewSlider(Rect position, float val) + { + val = GUI.HorizontalSlider(AvatarMuscleEditor.GetPreviewRect(position), val, -1f, 1f); + if (val > -0.1f && val < 0.1f) + { + val = 0f; + } + return val; + } + internal void ResetValuesFromProperties() + { + this.m_ArmTwistFactor = this.m_ArmTwistProperty.floatValue; + this.m_ForeArmTwistFactor = this.m_ForeArmTwistProperty.floatValue; + this.m_UpperLegTwistFactor = this.m_UpperLegTwistProperty.floatValue; + this.m_LegTwistFactor = this.m_LegTwistProperty.floatValue; + this.m_ArmStretchFactor = this.m_ArmStretchProperty.floatValue; + this.m_LegStretchFactor = this.m_LegStretchProperty.floatValue; + this.m_FeetSpacingFactor = this.m_FeetSpacingProperty.floatValue; + for (int i = 0; i < this.m_Bones.Length; i++) + { + if (this.m_Modified[i] != null) + { + bool boolValue = this.m_Modified[i].boolValue; + int num = HumanTrait.MuscleFromBone(i, 0); + int num2 = HumanTrait.MuscleFromBone(i, 1); + int num3 = HumanTrait.MuscleFromBone(i, 2); + if (num != -1) + { + this.m_MuscleMinEdit[num] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMin(num) : this.m_MuscleMin[num].floatValue); + this.m_MuscleMaxEdit[num] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMax(num) : this.m_MuscleMax[num].floatValue); + } + if (num2 != -1) + { + this.m_MuscleMinEdit[num2] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMin(num2) : this.m_MuscleMin[num2].floatValue); + this.m_MuscleMaxEdit[num2] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMax(num2) : this.m_MuscleMax[num2].floatValue); + } + if (num3 != -1) + { + this.m_MuscleMinEdit[num3] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMin(num3) : this.m_MuscleMin[num3].floatValue); + this.m_MuscleMaxEdit[num3] = ((!boolValue) ? HumanTrait.GetMuscleDefaultMax(num3) : this.m_MuscleMax[num3].floatValue); + } + } + } + } + internal void InitializeProperties() + { + this.m_ArmTwistProperty = base.serializedObject.FindProperty("m_HumanDescription.m_ArmTwist"); + this.m_ForeArmTwistProperty = base.serializedObject.FindProperty("m_HumanDescription.m_ForeArmTwist"); + this.m_UpperLegTwistProperty = base.serializedObject.FindProperty("m_HumanDescription.m_UpperLegTwist"); + this.m_LegTwistProperty = base.serializedObject.FindProperty("m_HumanDescription.m_LegTwist"); + this.m_ArmStretchProperty = base.serializedObject.FindProperty("m_HumanDescription.m_ArmStretch"); + this.m_LegStretchProperty = base.serializedObject.FindProperty("m_HumanDescription.m_LegStretch"); + this.m_FeetSpacingProperty = base.serializedObject.FindProperty("m_HumanDescription.m_FeetSpacing"); + for (int i = 0; i < this.m_Bones.Length; i++) + { + SerializedProperty serializedProperty = this.m_Bones[i].GetSerializedProperty(base.serializedObject, false); + if (serializedProperty != null) + { + this.m_Modified[i] = serializedProperty.FindPropertyRelative("m_Limit.m_Modified"); + int num = HumanTrait.MuscleFromBone(i, 0); + int num2 = HumanTrait.MuscleFromBone(i, 1); + int num3 = HumanTrait.MuscleFromBone(i, 2); + if (num != -1) + { + this.m_MuscleMin[num] = serializedProperty.FindPropertyRelative("m_Limit.m_Min.x"); + this.m_MuscleMax[num] = serializedProperty.FindPropertyRelative("m_Limit.m_Max.x"); + } + if (num2 != -1) + { + this.m_MuscleMin[num2] = serializedProperty.FindPropertyRelative("m_Limit.m_Min.y"); + this.m_MuscleMax[num2] = serializedProperty.FindPropertyRelative("m_Limit.m_Max.y"); + } + if (num3 != -1) + { + this.m_MuscleMin[num3] = serializedProperty.FindPropertyRelative("m_Limit.m_Min.z"); + this.m_MuscleMax[num3] = serializedProperty.FindPropertyRelative("m_Limit.m_Max.z"); + } + } + } + } + internal void Initialize() + { + if (this.m_Bones == null) + { + this.m_Bones = AvatarSetupTool.GetHumanBones(base.serializedObject, base.modelBones); + } + this.m_FocusedMuscle = -1; + this.m_MuscleBodyGroupToggle = new bool[this.m_Muscles.Length]; + for (int i = 0; i < this.m_Muscles.Length; i++) + { + this.m_MuscleBodyGroupToggle[i] = false; + } + this.m_MuscleName = HumanTrait.MuscleName; + for (int j = 0; j < this.m_MuscleName.Length; j++) + { + if (this.m_MuscleName[j].StartsWith("Right")) + { + this.m_MuscleName[j] = this.m_MuscleName[j].Substring(5).Trim(); + } + if (this.m_MuscleName[j].StartsWith("Left")) + { + this.m_MuscleName[j] = this.m_MuscleName[j].Substring(4).Trim(); + } + } + this.m_MuscleCount = HumanTrait.MuscleCount; + this.m_MuscleToggle = new bool[this.m_MuscleCount]; + this.m_MuscleValue = new float[this.m_MuscleCount]; + this.m_MuscleMin = new SerializedProperty[this.m_MuscleCount]; + this.m_MuscleMax = new SerializedProperty[this.m_MuscleCount]; + this.m_MuscleMinEdit = new float[this.m_MuscleCount]; + this.m_MuscleMaxEdit = new float[this.m_MuscleCount]; + for (int k = 0; k < this.m_MuscleCount; k++) + { + this.m_MuscleToggle[k] = false; + this.m_MuscleValue[k] = 0f; + this.m_MuscleMin[k] = null; + this.m_MuscleMin[k] = null; + } + this.m_Modified = new SerializedProperty[this.m_Bones.Length]; + for (int l = 0; l < this.m_Bones.Length; l++) + { + this.m_Modified[l] = null; + } + this.InitializeProperties(); + this.ResetValuesFromProperties(); + this.m_MuscleMasterValue = new float[this.m_MasterMuscle.Length]; + for (int m = 0; m < this.m_MasterMuscle.Length; m++) + { + this.m_MuscleMasterValue[m] = 0f; + } + } + public override void Enable(AvatarEditor inspector) + { + base.Enable(inspector); + this.Initialize(); + this.WritePose(); + } + public override void OnInspectorGUI() + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "UndoRedoPerformed") + { + this.WritePose(); + } + EditorGUI.BeginDisabledGroup(!base.avatarAsset.isHuman); + EditorGUIUtility.labelWidth = 110f; + EditorGUIUtility.fieldWidth = 40f; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + this.MuscleGroupGUI(); + EditorGUILayout.Space(); + this.MuscleGUI(); + EditorGUILayout.Space(); + this.PropertiesGUI(); + GUILayout.EndVertical(); + GUILayout.Space(1f); + GUILayout.EndHorizontal(); + this.DisplayMuscleButtons(); + base.ApplyRevertGUI(); + EditorGUI.EndDisabledGroup(); + } + protected void DisplayMuscleButtons() + { + GUILayout.BeginHorizontal(string.Empty, AvatarMuscleEditor.styles.toolbar, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + Rect rect = GUILayoutUtility.GetRect(AvatarMuscleEditor.styles.muscle, AvatarMuscleEditor.styles.toolbarDropDown); + if (GUI.Button(rect, AvatarMuscleEditor.styles.muscle, AvatarMuscleEditor.styles.toolbarDropDown)) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(AvatarMuscleEditor.styles.resetMuscle, false, new GenericMenu.MenuFunction(this.ResetMuscleToDefault)); + genericMenu.DropDown(rect); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + protected override void ResetValues() + { + base.serializedObject.Update(); + this.ResetValuesFromProperties(); + } + protected void ResetMuscleToDefault() + { + Avatar avatar = null; + if (base.gameObject != null) + { + Animator animator = base.gameObject.GetComponent(typeof(Animator)) as Animator; + avatar = animator.avatar; + } + for (int i = 0; i < this.m_MuscleCount; i++) + { + float muscleDefaultMin = HumanTrait.GetMuscleDefaultMin(i); + float muscleDefaultMax = HumanTrait.GetMuscleDefaultMax(i); + if (this.m_MuscleMin[i] != null && this.m_MuscleMax[i] != null) + { + this.m_MuscleMin[i].floatValue = (this.m_MuscleMinEdit[i] = muscleDefaultMin); + this.m_MuscleMax[i].floatValue = (this.m_MuscleMaxEdit[i] = muscleDefaultMax); + } + int num = HumanTrait.BoneFromMuscle(i); + if (this.m_Modified[num] != null && num != -1) + { + this.m_Modified[num].boolValue = false; + } + if (avatar != null) + { + avatar.SetMuscleMinMax(i, muscleDefaultMin, muscleDefaultMax); + } + } + this.WritePose(); + } + protected void UpdateAvatarParameter(HumanParameter parameterId, float value) + { + if (base.gameObject != null) + { + Animator animator = base.gameObject.GetComponent(typeof(Animator)) as Animator; + Avatar avatar = animator.avatar; + avatar.SetParameter((int)parameterId, value); + } + } + protected bool UpdateMuscle(int muscleId, float min, float max) + { + Undo.RegisterCompleteObjectUndo(this, "Updated muscle range"); + this.m_MuscleMin[muscleId].floatValue = min; + this.m_MuscleMax[muscleId].floatValue = max; + int num = HumanTrait.BoneFromMuscle(muscleId); + if (num != -1) + { + this.m_Modified[num].boolValue = true; + } + this.m_FocusedMuscle = muscleId; + if (base.gameObject != null) + { + Animator animator = base.gameObject.GetComponent(typeof(Animator)) as Animator; + Avatar avatar = animator.avatar; + avatar.SetMuscleMinMax(muscleId, min, max); + } + SceneView.RepaintAll(); + return base.gameObject != null; + } + protected void MuscleGroupGUI() + { + bool flag = false; + this.HeaderGUI("Preview", "Muscle Group Preview"); + GUILayout.BeginVertical(AvatarMuscleEditor.styles.box, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(10f, 16f); + Rect settingsRect = AvatarMuscleEditor.GetSettingsRect(rect); + Rect previewRect = AvatarMuscleEditor.GetPreviewRect(rect); + if (GUI.Button(previewRect, "Reset All", EditorStyles.miniButton)) + { + for (int i = 0; i < this.m_MuscleMasterValue.Length; i++) + { + this.m_MuscleMasterValue[i] = 0f; + } + for (int j = 0; j < this.m_MuscleValue.Length; j++) + { + this.m_MuscleValue[j] = 0f; + } + flag = true; + } + GUI.Label(settingsRect, "Reset All Preview Values", EditorStyles.label); + for (int k = 0; k < this.m_MasterMuscle.Length; k++) + { + Rect rect2 = GUILayoutUtility.GetRect(10f, 16f); + Rect settingsRect2 = AvatarMuscleEditor.GetSettingsRect(rect2); + float num = this.m_MuscleMasterValue[k]; + this.m_MuscleMasterValue[k] = AvatarMuscleEditor.PreviewSlider(rect2, this.m_MuscleMasterValue[k]); + if (this.m_MuscleMasterValue[k] != num) + { + Undo.RegisterCompleteObjectUndo(this, "Muscle preview"); + for (int l = 0; l < this.m_MasterMuscle[k].Length; l++) + { + if (this.m_MasterMuscle[k][l] != -1) + { + this.m_MuscleValue[this.m_MasterMuscle[k][l]] = this.m_MuscleMasterValue[k]; + } + } + } + flag |= (this.m_MuscleMasterValue[k] != num && base.gameObject != null); + GUI.Label(settingsRect2, AvatarMuscleEditor.styles.muscleTypeGroup[k], EditorStyles.label); + } + GUILayout.EndVertical(); + if (flag) + { + this.WritePose(); + } + } + protected void MuscleGUI() + { + bool flag = false; + this.HeaderGUI("Preview", "Per-Muscle Settings"); + GUILayout.BeginVertical(AvatarMuscleEditor.styles.box, new GUILayoutOption[0]); + for (int i = 0; i < this.m_MuscleBodyGroupToggle.Length; i++) + { + Rect rect = GUILayoutUtility.GetRect(10f, 16f); + Rect settingsRect = AvatarMuscleEditor.GetSettingsRect(rect); + this.m_MuscleBodyGroupToggle[i] = GUI.Toggle(settingsRect, this.m_MuscleBodyGroupToggle[i], AvatarMuscleEditor.styles.muscleBodyGroup[i], EditorStyles.foldout); + if (this.m_MuscleBodyGroupToggle[i]) + { + for (int j = 0; j < this.m_Muscles[i].Length; j++) + { + int num = this.m_Muscles[i][j]; + if (num != -1 && this.m_MuscleMin[num] != null && this.m_MuscleMax[num] != null) + { + bool flag2 = this.m_MuscleToggle[num]; + rect = GUILayoutUtility.GetRect(10f, (!flag2) ? 16f : 32f); + settingsRect = AvatarMuscleEditor.GetSettingsRect(rect); + settingsRect.xMin += 15f; + settingsRect.height = 16f; + this.m_MuscleToggle[num] = GUI.Toggle(settingsRect, this.m_MuscleToggle[num], this.m_MuscleName[num], EditorStyles.foldout); + float num2 = AvatarMuscleEditor.PreviewSlider(rect, this.m_MuscleValue[num]); + if (this.m_MuscleValue[num] != num2) + { + Undo.RegisterCompleteObjectUndo(this, "Muscle preview"); + this.m_FocusedMuscle = num; + this.m_MuscleValue[num] = num2; + flag |= (base.gameObject != null); + } + if (flag2) + { + bool flag3 = false; + settingsRect.xMin += 15f; + settingsRect.y += 16f; + Rect position = settingsRect; + if (settingsRect.width > 160f) + { + Rect position2 = settingsRect; + position2.width = 38f; + EditorGUI.BeginChangeCheck(); + this.m_MuscleMinEdit[num] = EditorGUI.FloatField(position2, this.m_MuscleMinEdit[num]); + flag3 |= EditorGUI.EndChangeCheck(); + position2.x = settingsRect.xMax - 38f; + EditorGUI.BeginChangeCheck(); + this.m_MuscleMaxEdit[num] = EditorGUI.FloatField(position2, this.m_MuscleMaxEdit[num]); + flag3 |= EditorGUI.EndChangeCheck(); + position.xMin += 43f; + position.xMax -= 43f; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.MinMaxSlider(position, ref this.m_MuscleMinEdit[num], ref this.m_MuscleMaxEdit[num], -180f, 180f); + flag3 |= EditorGUI.EndChangeCheck(); + if (flag3) + { + this.m_MuscleMinEdit[num] = Mathf.Clamp(this.m_MuscleMinEdit[num], -180f, 0f); + this.m_MuscleMaxEdit[num] = Mathf.Clamp(this.m_MuscleMaxEdit[num], 0f, 180f); + flag |= this.UpdateMuscle(num, this.m_MuscleMinEdit[num], this.m_MuscleMaxEdit[num]); + } + } + } + } + } + } + GUILayout.EndVertical(); + if (flag) + { + this.WritePose(); + } + } + protected void PropertiesGUI() + { + bool flag = false; + this.HeaderGUI(string.Empty, "Additional Settings"); + GUILayout.BeginVertical(AvatarMuscleEditor.styles.box, new GUILayoutOption[0]); + this.m_ArmTwistFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.armTwist, this.m_ArmTwistFactor, 0f, 1f); + if (this.m_ArmTwistProperty.floatValue != this.m_ArmTwistFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Upper arm twist"); + this.m_ArmTwistProperty.floatValue = this.m_ArmTwistFactor; + this.UpdateAvatarParameter(HumanParameter.UpperArmTwist, this.m_ArmTwistFactor); + flag = true; + } + this.m_ForeArmTwistFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.foreArmTwist, this.m_ForeArmTwistFactor, 0f, 1f); + if (this.m_ForeArmTwistProperty.floatValue != this.m_ForeArmTwistFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Lower arm twist"); + this.m_ForeArmTwistProperty.floatValue = this.m_ForeArmTwistFactor; + this.UpdateAvatarParameter(HumanParameter.LowerArmTwist, this.m_ForeArmTwistFactor); + flag = true; + } + this.m_UpperLegTwistFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.upperLegTwist, this.m_UpperLegTwistFactor, 0f, 1f); + if (this.m_UpperLegTwistProperty.floatValue != this.m_UpperLegTwistFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Upper leg twist"); + this.m_UpperLegTwistProperty.floatValue = this.m_UpperLegTwistFactor; + this.UpdateAvatarParameter(HumanParameter.UpperLegTwist, this.m_UpperLegTwistFactor); + flag = true; + } + this.m_LegTwistFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.legTwist, this.m_LegTwistFactor, 0f, 1f); + if (this.m_LegTwistProperty.floatValue != this.m_LegTwistFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Lower leg twist"); + this.m_LegTwistProperty.floatValue = this.m_LegTwistFactor; + this.UpdateAvatarParameter(HumanParameter.LowerLegTwist, this.m_LegTwistFactor); + flag = true; + } + this.m_ArmStretchFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.armStretch, this.m_ArmStretchFactor, 0f, 1f); + if (this.m_ArmStretchProperty.floatValue != this.m_ArmStretchFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Arm stretch"); + this.m_ArmStretchProperty.floatValue = this.m_ArmStretchFactor; + this.UpdateAvatarParameter(HumanParameter.ArmStretch, this.m_ArmStretchFactor); + flag = true; + } + this.m_LegStretchFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.legStretch, this.m_LegStretchFactor, 0f, 1f); + if (this.m_LegStretchProperty.floatValue != this.m_LegStretchFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Leg stretch"); + this.m_LegStretchProperty.floatValue = this.m_LegStretchFactor; + this.UpdateAvatarParameter(HumanParameter.LegStretch, this.m_LegStretchFactor); + flag = true; + } + this.m_FeetSpacingFactor = EditorGUI.Slider(AvatarMuscleEditor.GetSettingsRect(), AvatarMuscleEditor.styles.feetSpacing, this.m_FeetSpacingFactor, 0f, 1f); + if (this.m_FeetSpacingProperty.floatValue != this.m_FeetSpacingFactor) + { + Undo.RegisterCompleteObjectUndo(this, "Feet spacing"); + this.m_FeetSpacingProperty.floatValue = this.m_FeetSpacingFactor; + this.UpdateAvatarParameter(HumanParameter.FeetSpacing, this.m_FeetSpacingFactor); + flag = true; + } + GUILayout.EndVertical(); + if (flag) + { + this.WritePose(); + } + } + protected void WritePose() + { + if (base.gameObject) + { + Animator animator = base.gameObject.GetComponent(typeof(Animator)) as Animator; + if (animator != null) + { + Avatar avatar = animator.avatar; + if (avatar != null && avatar.isValid && avatar.isHuman) + { + AvatarUtility.SetHumanPose(animator, this.m_MuscleValue); + SceneView.RepaintAll(); + } + } + } + } + public void DrawMuscleHandle(Transform t, int humanId) + { + Animator animator = base.gameObject.GetComponent(typeof(Animator)) as Animator; + Avatar avatar = animator.avatar; + int num = HumanTrait.MuscleFromBone(humanId, 0); + int num2 = HumanTrait.MuscleFromBone(humanId, 1); + int num3 = HumanTrait.MuscleFromBone(humanId, 2); + float axisLength = avatar.GetAxisLength(humanId); + Quaternion quaternion = avatar.GetPreRotation(humanId); + Quaternion quaternion2 = avatar.GetPostRotation(humanId); + quaternion = t.parent.rotation * quaternion; + quaternion2 = t.rotation * quaternion2; + Color b = new Color(1f, 1f, 1f, 0.5f); + Quaternion zYRoll = avatar.GetZYRoll(humanId, Vector3.zero); + Vector3 limitSign = avatar.GetLimitSign(humanId); + Vector3 vector = quaternion2 * Vector3.right; + Vector3 p = t.position + vector * axisLength; + Handles.color = Color.white; + Handles.DrawLine(t.position, p); + if (num != -1) + { + Quaternion zYPostQ = avatar.GetZYPostQ(humanId, t.parent.rotation, t.rotation); + float num4 = this.m_MuscleMinEdit[num]; + float num5 = this.m_MuscleMaxEdit[num]; + vector = quaternion2 * Vector3.right; + Vector3 vector2 = zYPostQ * Vector3.forward; + Handles.color = Color.black; + Vector3 vector3 = t.position + vector * axisLength * 0.75f; + vector = quaternion2 * Vector3.right * limitSign.x; + Quaternion rotation = Quaternion.AngleAxis(num4, vector); + vector2 = rotation * vector2; + Handles.color = Color.yellow; + Handles.color = Handles.xAxisColor * b; + Handles.DrawSolidArc(vector3, vector, vector2, num5 - num4, axisLength * 0.25f); + vector2 = quaternion2 * Vector3.forward; + Handles.color = Handles.centerColor; + Handles.DrawLine(vector3, vector3 + vector2 * axisLength * 0.25f); + } + if (num2 != -1) + { + float num6 = this.m_MuscleMinEdit[num2]; + float num7 = this.m_MuscleMaxEdit[num2]; + vector = quaternion * Vector3.up * limitSign.y; + Vector3 vector2 = quaternion * zYRoll * Vector3.right; + Handles.color = Color.black; + Quaternion rotation2 = Quaternion.AngleAxis(num6, vector); + vector2 = rotation2 * vector2; + Handles.color = Color.yellow; + Handles.color = Handles.yAxisColor * b; + Handles.DrawSolidArc(t.position, vector, vector2, num7 - num6, axisLength * 0.25f); + } + if (num3 != -1) + { + float num8 = this.m_MuscleMinEdit[num3]; + float num9 = this.m_MuscleMaxEdit[num3]; + vector = quaternion * Vector3.forward * limitSign.z; + Vector3 vector2 = quaternion * zYRoll * Vector3.right; + Handles.color = Color.black; + Quaternion rotation3 = Quaternion.AngleAxis(num8, vector); + vector2 = rotation3 * vector2; + Handles.color = Color.yellow; + Handles.color = Handles.zAxisColor * b; + Handles.DrawSolidArc(t.position, vector, vector2, num9 - num8, axisLength * 0.25f); + } + } + public override void OnSceneGUI() + { + AvatarSkeletonDrawer.DrawSkeleton(base.root, base.modelBones); + if (base.gameObject == null) + { + return; + } + Animator x = base.gameObject.GetComponent(typeof(Animator)) as Animator; + if (this.m_FocusedMuscle == -1 || x == null) + { + return; + } + int num = HumanTrait.BoneFromMuscle(this.m_FocusedMuscle); + if (num != -1) + { + this.DrawMuscleHandle(this.m_Bones[num].bone, num); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarPreview.cs b/UnityEditor/UnityEditor/AvatarPreview.cs new file mode 100644 index 00000000..b2560def --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarPreview.cs @@ -0,0 +1,797 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AvatarPreview + { + private class Styles + { + public GUIContent speedScale = EditorGUIUtility.IconContent("SpeedScale", "Changes animation preview speed"); + public GUIContent pivot = EditorGUIUtility.IconContent("AvatarPivot", "Displays avatar's pivot and mass center"); + public GUIContent ik = new GUIContent("IK", "Activates feet IK preview"); + public GUIContent avatarIcon = EditorGUIUtility.IconContent("Avatar Icon", "Changes the model to use for previewing."); + public GUIStyle preButton = "preButton"; + public GUIStyle preSlider = "preSlider"; + public GUIStyle preSliderThumb = "preSliderThumb"; + public GUIStyle preLabel = "preLabel"; + } + private enum PreviewPopupOptions + { + Auto, + DefaultModel, + Other + } + public delegate void OnAvatarChange(); + private const string kIkPref = "AvatarpreviewShowIK"; + private const string kReferencePref = "AvatarpreviewShowReference"; + private const string kSpeedPref = "AvatarpreviewSpeed"; + private const float kTimeControlRectHeight = 21f; + private const int kPreviewLayer = 31; + private const string s_PreviewStr = "Preview"; + private const float kFloorFadeDuration = 0.2f; + private const float kFloorScale = 5f; + private const float kFloorScaleSmall = 0.2f; + private const float kFloorTextureScale = 4f; + private const float kFloorAlpha = 0.5f; + private const float kFloorShadowAlpha = 0.3f; + private AvatarPreview.OnAvatarChange m_OnAvatarChangeFunc; + public TimeControl timeControl; + public int fps = 60; + private Material m_FloorMaterial; + private Material m_FloorMaterialSmall; + private Material m_ShadowMaskMaterial; + private Material m_ShadowPlaneMaterial; + private PreviewRenderUtility m_PreviewUtility; + private GameObject m_PreviewInstance; + private GameObject m_ReferenceInstance; + private GameObject m_DirectionInstance; + private GameObject m_PivotInstance; + private GameObject m_RootInstance; + private float m_BoundingVolumeScale; + private Motion m_SourcePreviewMotion; + private Animator m_SourceScenePreviewAnimator; + private int m_PreviewHint = "Preview".GetHashCode(); + private Texture2D m_FloorTexture; + private Mesh m_FloorPlane; + private bool m_ShowReference; + private bool m_IKOnFeet; + private bool m_ShowIKOnFeetButton = true; + private bool m_IsValid; + private int m_ModelSelectorId = GUIUtility.GetPermanentControlID(); + private float m_PrevFloorHeight; + private float m_NextFloorHeight; + private Vector2 m_PreviewDir = new Vector2(120f, -20f); + private static AvatarPreview.Styles s_Styles; + private float m_LastNormalizedTime = -1000f; + private float m_LastStartTime = -1000f; + private float m_LastStopTime = -1000f; + private bool m_NextTargetIsForward = true; + public AvatarPreview.OnAvatarChange OnAvatarChangeFunc + { + set + { + this.m_OnAvatarChangeFunc = value; + } + } + public bool IKOnFeet + { + get + { + return this.m_IKOnFeet; + } + } + public bool ShowIKOnFeetButton + { + get + { + return this.m_ShowIKOnFeetButton; + } + set + { + this.m_ShowIKOnFeetButton = value; + } + } + public Animator Animator + { + get + { + return (!(this.m_PreviewInstance != null)) ? null : (this.m_PreviewInstance.GetComponent(typeof(Animator)) as Animator); + } + } + public GameObject PreviewObject + { + get + { + return this.m_PreviewInstance; + } + } + public ModelImporterAnimationType animationClipType + { + get + { + return AvatarPreview.GetAnimationType(this.m_SourcePreviewMotion); + } + } + public AvatarPreview(Animator previewObjectInScene, Motion objectOnSameAsset) + { + this.InitInstance(previewObjectInScene, objectOnSameAsset); + } + private void SetPreviewCharacterEnabled(bool enabled, bool showReference) + { + if (this.m_PreviewInstance != null) + { + GameObjectInspector.SetEnabledRecursive(this.m_PreviewInstance, enabled); + } + GameObjectInspector.SetEnabledRecursive(this.m_ReferenceInstance, showReference && enabled); + GameObjectInspector.SetEnabledRecursive(this.m_DirectionInstance, showReference && enabled); + GameObjectInspector.SetEnabledRecursive(this.m_PivotInstance, showReference && enabled); + GameObjectInspector.SetEnabledRecursive(this.m_RootInstance, showReference && enabled); + } + private static AnimationClip GetFirstAnimationClipFromMotion(Motion motion) + { + AnimationClip animationClip = motion as AnimationClip; + if (animationClip) + { + return animationClip; + } + BlendTree blendTree = motion as BlendTree; + if (blendTree) + { + AnimationClip[] animationClipsFlattened = blendTree.GetAnimationClipsFlattened(); + if (animationClipsFlattened.Length > 0) + { + return animationClipsFlattened[0]; + } + } + return null; + } + public static ModelImporterAnimationType GetAnimationType(GameObject go) + { + Animator component = go.GetComponent(); + if (component) + { + Avatar avatar = (!(component != null)) ? null : component.avatar; + if (avatar && avatar.isHuman) + { + return ModelImporterAnimationType.Human; + } + return ModelImporterAnimationType.Generic; + } + else + { + if (go.GetComponent() != null) + { + return ModelImporterAnimationType.Legacy; + } + return ModelImporterAnimationType.None; + } + } + public static ModelImporterAnimationType GetAnimationType(Motion motion) + { + AnimationClip firstAnimationClipFromMotion = AvatarPreview.GetFirstAnimationClipFromMotion(motion); + if (firstAnimationClipFromMotion) + { + return AnimationUtility.GetAnimationType(firstAnimationClipFromMotion); + } + return ModelImporterAnimationType.None; + } + public static bool IsValidPreviewGameObject(GameObject target, ModelImporterAnimationType requiredClipType) + { + if (target != null && !target.activeSelf) + { + Debug.LogWarning("Can't preview inactive object, using fallback object"); + } + return target != null && target.activeSelf && GameObjectInspector.HasRenderablePartsRecurse(target) && AvatarPreview.GetAnimationType(target) == requiredClipType; + } + public static GameObject FindBestFittingRenderableGameObjectFromModelAsset(UnityEngine.Object asset, ModelImporterAnimationType animationType) + { + if (asset == null) + { + return null; + } + ModelImporter modelImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(asset)) as ModelImporter; + if (modelImporter == null) + { + return null; + } + string assetPath = modelImporter.CalculateBestFittingPreviewGameObject(); + GameObject gameObject = AssetDatabase.LoadMainAssetAtPath(assetPath) as GameObject; + if (AvatarPreview.IsValidPreviewGameObject(gameObject, animationType)) + { + return gameObject; + } + return null; + } + private static GameObject CalculatePreviewGameObject(Animator selectedAnimator, Motion motion, ModelImporterAnimationType animationType) + { + AnimationClip firstAnimationClipFromMotion = AvatarPreview.GetFirstAnimationClipFromMotion(motion); + GameObject gameObject = AvatarPreviewSelection.GetPreview(animationType); + if (AvatarPreview.IsValidPreviewGameObject(gameObject, animationType)) + { + return gameObject; + } + if (selectedAnimator != null && AvatarPreview.IsValidPreviewGameObject(selectedAnimator.gameObject, animationType)) + { + return selectedAnimator.gameObject; + } + gameObject = AvatarPreview.FindBestFittingRenderableGameObjectFromModelAsset(firstAnimationClipFromMotion, animationType); + if (gameObject != null) + { + return gameObject; + } + if (animationType == ModelImporterAnimationType.Human) + { + return AvatarPreview.GetHumanoidFallback(); + } + if (animationType == ModelImporterAnimationType.Generic) + { + return AvatarPreview.GetGenericAnimationFallback(); + } + return null; + } + private static GameObject GetGenericAnimationFallback() + { + return (GameObject)EditorGUIUtility.Load("Avatar/DefaultGeneric.fbx"); + } + private static GameObject GetHumanoidFallback() + { + return (GameObject)EditorGUIUtility.Load("Avatar/DefaultAvatar.fbx"); + } + private void InitInstance(Animator scenePreviewObject, Motion motion) + { + this.m_SourcePreviewMotion = motion; + this.m_SourceScenePreviewAnimator = scenePreviewObject; + if (this.m_PreviewInstance == null) + { + GameObject gameObject = AvatarPreview.CalculatePreviewGameObject(scenePreviewObject, motion, this.animationClipType); + this.m_IsValid = (gameObject != null && gameObject != AvatarPreview.GetGenericAnimationFallback()); + if (gameObject != null) + { + this.m_PreviewInstance = (GameObject)EditorUtility.InstantiateRemoveAllNonAnimationComponents(gameObject, Vector3.zero, Quaternion.identity); + Bounds bounds = new Bounds(this.m_PreviewInstance.transform.position, Vector3.zero); + GameObjectInspector.GetRenderableBoundsRecurse(ref bounds, this.m_PreviewInstance); + this.m_BoundingVolumeScale = Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)); + GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_PreviewInstance); + if (this.Animator) + { + this.Animator.enabled = false; + this.Animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; + this.Animator.applyRootMotion = true; + this.Animator.logWarnings = false; + this.Animator.fireEvents = false; + } + } + } + if (this.timeControl == null) + { + this.timeControl = new TimeControl(); + } + if (this.m_ReferenceInstance == null) + { + GameObject original = (GameObject)EditorGUIUtility.Load("Avatar/dial_flat.prefab"); + this.m_ReferenceInstance = (GameObject)UnityEngine.Object.Instantiate(original, Vector3.zero, Quaternion.identity); + GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_ReferenceInstance); + } + if (this.m_DirectionInstance == null) + { + GameObject original2 = (GameObject)EditorGUIUtility.Load("Avatar/arrow.fbx"); + this.m_DirectionInstance = (GameObject)UnityEngine.Object.Instantiate(original2, Vector3.zero, Quaternion.identity); + GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_DirectionInstance); + } + if (this.m_PivotInstance == null) + { + GameObject original3 = (GameObject)EditorGUIUtility.Load("Avatar/root.fbx"); + this.m_PivotInstance = (GameObject)UnityEngine.Object.Instantiate(original3, Vector3.zero, Quaternion.identity); + GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_PivotInstance); + } + if (this.m_RootInstance == null) + { + GameObject original4 = (GameObject)EditorGUIUtility.Load("Avatar/root.fbx"); + this.m_RootInstance = (GameObject)UnityEngine.Object.Instantiate(original4, Vector3.zero, Quaternion.identity); + GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_RootInstance); + } + this.m_IKOnFeet = EditorPrefs.GetBool("AvatarpreviewShowIK", false); + this.m_ShowReference = EditorPrefs.GetBool("AvatarpreviewShowReference", true); + this.timeControl.playbackSpeed = EditorPrefs.GetFloat("AvatarpreviewSpeed", 1f); + this.SetPreviewCharacterEnabled(false, false); + } + private void Init() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(true); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + this.m_PreviewUtility.m_Camera.cullingMask = -2147483648; + } + if (AvatarPreview.s_Styles == null) + { + AvatarPreview.s_Styles = new AvatarPreview.Styles(); + } + if (this.m_FloorPlane == null) + { + this.m_FloorPlane = (Resources.GetBuiltinResource(typeof(Mesh), "New-Plane.fbx") as Mesh); + } + if (this.m_FloorTexture == null) + { + this.m_FloorTexture = (Texture2D)EditorGUIUtility.Load("Avatar/Textures/AvatarFloor.png"); + } + if (this.m_FloorMaterial == null) + { + Shader shader = EditorGUIUtility.LoadRequired("Previews/PreviewPlaneWithShadow.shader") as Shader; + this.m_FloorMaterial = new Material(shader); + this.m_FloorMaterial.mainTexture = this.m_FloorTexture; + this.m_FloorMaterial.mainTextureScale = Vector2.one * 5f * 4f; + this.m_FloorMaterial.SetVector("_Alphas", new Vector4(0.5f, 0.3f, 0f, 0f)); + this.m_FloorMaterial.hideFlags = HideFlags.DontSave; + this.m_FloorMaterialSmall = new Material(this.m_FloorMaterial); + this.m_FloorMaterialSmall.mainTextureScale = Vector2.one * 0.2f * 4f; + this.m_FloorMaterialSmall.hideFlags = HideFlags.DontSave; + } + if (this.m_ShadowMaskMaterial == null) + { + Shader shader2 = EditorGUIUtility.LoadRequired("Previews/PreviewShadowMask.shader") as Shader; + this.m_ShadowMaskMaterial = new Material(shader2); + this.m_ShadowMaskMaterial.hideFlags = HideFlags.DontSave; + } + if (this.m_ShadowPlaneMaterial == null) + { + Shader shader3 = EditorGUIUtility.LoadRequired("Previews/PreviewShadowPlaneClip.shader") as Shader; + this.m_ShadowPlaneMaterial = new Material(shader3); + this.m_ShadowPlaneMaterial.hideFlags = HideFlags.DontSave; + } + } + public void OnDestroy() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + UnityEngine.Object.DestroyImmediate(this.m_PreviewInstance); + UnityEngine.Object.DestroyImmediate(this.m_FloorMaterial); + UnityEngine.Object.DestroyImmediate(this.m_FloorMaterialSmall); + UnityEngine.Object.DestroyImmediate(this.m_ShadowMaskMaterial); + UnityEngine.Object.DestroyImmediate(this.m_ShadowPlaneMaterial); + UnityEngine.Object.DestroyImmediate(this.m_ReferenceInstance); + UnityEngine.Object.DestroyImmediate(this.m_RootInstance); + UnityEngine.Object.DestroyImmediate(this.m_PivotInstance); + UnityEngine.Object.DestroyImmediate(this.m_DirectionInstance); + if (this.timeControl != null) + { + this.timeControl.OnDisable(); + } + } + public void DoSelectionChange() + { + this.m_OnAvatarChangeFunc(); + } + private float PreviewSlider(float val, float snapThreshold) + { + val = GUILayout.HorizontalSlider(val, 0.1f, 2f, AvatarPreview.s_Styles.preSlider, AvatarPreview.s_Styles.preSliderThumb, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + }); + if (val > 0.25f - snapThreshold && val < 0.25f + snapThreshold) + { + val = 0.25f; + } + else + { + if (val > 0.5f - snapThreshold && val < 0.5f + snapThreshold) + { + val = 0.5f; + } + else + { + if (val > 0.75f - snapThreshold && val < 0.75f + snapThreshold) + { + val = 0.75f; + } + else + { + if (val > 1f - snapThreshold && val < 1f + snapThreshold) + { + val = 1f; + } + else + { + if (val > 1.25f - snapThreshold && val < 1.25f + snapThreshold) + { + val = 1.25f; + } + else + { + if (val > 1.5f - snapThreshold && val < 1.5f + snapThreshold) + { + val = 1.5f; + } + else + { + if (val > 1.75f - snapThreshold && val < 1.75f + snapThreshold) + { + val = 1.75f; + } + } + } + } + } + } + } + return val; + } + public void DoPreviewSettings() + { + this.Init(); + if (this.m_ShowIKOnFeetButton) + { + EditorGUI.BeginChangeCheck(); + this.m_IKOnFeet = GUILayout.Toggle(this.m_IKOnFeet, AvatarPreview.s_Styles.ik, AvatarPreview.s_Styles.preButton, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("AvatarpreviewShowIK", this.m_IKOnFeet); + } + } + EditorGUI.BeginChangeCheck(); + this.m_ShowReference = GUILayout.Toggle(this.m_ShowReference, AvatarPreview.s_Styles.pivot, AvatarPreview.s_Styles.preButton, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("AvatarpreviewShowReference", this.m_ShowReference); + } + GUILayout.Box(AvatarPreview.s_Styles.speedScale, AvatarPreview.s_Styles.preLabel, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + this.timeControl.playbackSpeed = this.PreviewSlider(this.timeControl.playbackSpeed, 0.03f); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetFloat("AvatarpreviewSpeed", this.timeControl.playbackSpeed); + } + GUILayout.Label(this.timeControl.playbackSpeed.ToString("f2"), AvatarPreview.s_Styles.preLabel, new GUILayoutOption[0]); + } + private RenderTexture RenderPreviewShadowmap(Light light, float scale, Vector3 center, Vector3 floorPos, out Matrix4x4 outShadowMatrix) + { + Camera camera = this.m_PreviewUtility.m_Camera; + camera.orthographic = true; + camera.orthographicSize = scale * 2f; + camera.nearClipPlane = 1f * scale; + camera.farClipPlane = 25f * scale; + camera.transform.rotation = light.transform.rotation; + camera.transform.position = center - light.transform.forward * (scale * 5.5f); + CameraClearFlags clearFlags = camera.clearFlags; + camera.clearFlags = CameraClearFlags.Color; + Color backgroundColor = camera.backgroundColor; + camera.backgroundColor = new Color(0f, 0f, 0f, 0f); + RenderTexture targetTexture = camera.targetTexture; + RenderTexture temporary = RenderTexture.GetTemporary(256, 256, 16); + temporary.isPowerOfTwo = true; + temporary.wrapMode = TextureWrapMode.Clamp; + temporary.filterMode = FilterMode.Bilinear; + camera.targetTexture = temporary; + this.SetPreviewCharacterEnabled(true, false); + this.m_PreviewUtility.m_Camera.Render(); + RenderTexture.active = temporary; + GL.PushMatrix(); + GL.LoadOrtho(); + this.m_ShadowMaskMaterial.SetPass(0); + GL.Begin(7); + GL.Vertex3(0f, 0f, -99f); + GL.Vertex3(1f, 0f, -99f); + GL.Vertex3(1f, 1f, -99f); + GL.Vertex3(0f, 1f, -99f); + GL.End(); + GL.LoadProjectionMatrix(camera.projectionMatrix); + GL.LoadIdentity(); + GL.MultMatrix(camera.worldToCameraMatrix); + this.m_ShadowPlaneMaterial.SetPass(0); + GL.Begin(7); + float num = 5f * scale; + GL.Vertex(floorPos + new Vector3(-num, 0f, -num)); + GL.Vertex(floorPos + new Vector3(num, 0f, -num)); + GL.Vertex(floorPos + new Vector3(num, 0f, num)); + GL.Vertex(floorPos + new Vector3(-num, 0f, num)); + GL.End(); + GL.PopMatrix(); + Matrix4x4 lhs = Matrix4x4.TRS(new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f)); + outShadowMatrix = lhs * camera.projectionMatrix * camera.worldToCameraMatrix; + camera.orthographic = false; + camera.clearFlags = clearFlags; + camera.backgroundColor = backgroundColor; + camera.targetTexture = targetTexture; + return temporary; + } + public Texture DoRenderPreview(Rect previewRect, GUIStyle background) + { + this.m_PreviewUtility.BeginPreview(previewRect, background); + Quaternion quaternion; + Vector3 vector; + Quaternion quaternion2; + Vector3 vector2; + Vector3 pivotPos; + float num; + if (this.Animator && this.Animator.isHuman) + { + quaternion = this.Animator.rootRotation; + vector = this.Animator.rootPosition; + quaternion2 = this.Animator.bodyRotation; + vector2 = this.Animator.bodyPosition; + pivotPos = this.Animator.pivotPosition; + num = this.Animator.humanScale; + } + else + { + if (this.Animator && this.Animator.hasRootMotion) + { + quaternion = this.Animator.rootRotation; + vector = this.Animator.rootPosition; + quaternion2 = Quaternion.identity; + vector2 = GameObjectInspector.GetRenderableCenterRecurse(this.m_PreviewInstance, 2, 8); + pivotPos = Vector3.zero; + num = this.m_BoundingVolumeScale / 2f; + } + else + { + quaternion = Quaternion.identity; + vector = Vector3.zero; + quaternion2 = Quaternion.identity; + vector2 = GameObjectInspector.GetRenderableCenterRecurse(this.m_PreviewInstance, 2, 8); + pivotPos = Vector3.zero; + num = this.m_BoundingVolumeScale / 2f; + } + } + bool oldFog = this.SetupPreviewLightingAndFx(); + Vector3 forward = quaternion2 * Vector3.forward; + forward[1] = 0f; + Quaternion directionRot = Quaternion.LookRotation(forward); + Vector3 directionPos = vector; + Quaternion pivotRot = quaternion; + this.PositionPreviewObjects(pivotRot, pivotPos, quaternion2, vector2, directionRot, quaternion, vector, directionPos, num); + bool flag = Mathf.Abs(this.m_NextFloorHeight - this.m_PrevFloorHeight) > num * 0.01f; + float num3; + float num4; + if (flag) + { + float num2 = (this.m_NextFloorHeight >= this.m_PrevFloorHeight) ? 0.8f : 0.2f; + num3 = ((this.timeControl.normalizedTime >= num2) ? this.m_NextFloorHeight : this.m_PrevFloorHeight); + num4 = Mathf.Clamp01(Mathf.Abs(this.timeControl.normalizedTime - num2) / 0.2f); + } + else + { + num3 = this.m_PrevFloorHeight; + num4 = 1f; + } + Quaternion identity = Quaternion.identity; + Vector3 position = new Vector3(0f, 0f, 0f); + position = this.m_ReferenceInstance.transform.position; + position.y = num3; + Matrix4x4 matrix; + RenderTexture renderTexture = this.RenderPreviewShadowmap(this.m_PreviewUtility.m_Light[0], num, vector2, position, out matrix); + this.m_PreviewUtility.m_Camera.nearClipPlane = 1f * num; + this.m_PreviewUtility.m_Camera.farClipPlane = 25f * num; + Quaternion rotation = Quaternion.Euler(-this.m_PreviewDir.y, -this.m_PreviewDir.x, 0f); + Vector3 position2 = rotation * (Vector3.forward * -5.5f * num) + vector2; + this.m_PreviewUtility.m_Camera.transform.position = position2; + this.m_PreviewUtility.m_Camera.transform.rotation = rotation; + position.y = num3; + Material floorMaterial = this.m_FloorMaterial; + floorMaterial.mainTextureOffset = -floorMaterial.mainTextureScale * 0.5f - new Vector2(position.x, position.z) / num * 0.1f * 4f; + floorMaterial.SetTexture("_ShadowTexture", renderTexture); + floorMaterial.SetMatrix("_ShadowTextureMatrix", matrix); + floorMaterial.SetVector("_Alphas", new Vector4(0.5f * num4, 0.3f * num4, 0f, 0f)); + Matrix4x4 matrix2 = Matrix4x4.TRS(position, identity, Vector3.one * num * 5f); + Graphics.DrawMesh(this.m_FloorPlane, matrix2, floorMaterial, 31, this.m_PreviewUtility.m_Camera, 0); + if (flag) + { + bool flag2 = this.m_NextFloorHeight > this.m_PrevFloorHeight; + float num5 = (!flag2) ? this.m_PrevFloorHeight : this.m_NextFloorHeight; + float from = (!flag2) ? this.m_NextFloorHeight : this.m_PrevFloorHeight; + float num6 = ((num5 != num3) ? 1f : (1f - num4)) * Mathf.InverseLerp(from, num5, vector.y); + position.y = num5; + Material floorMaterialSmall = this.m_FloorMaterialSmall; + floorMaterialSmall.mainTextureOffset = -floorMaterialSmall.mainTextureScale * 0.5f - new Vector2(position.x, position.z) / num * 0.1f * 4f; + floorMaterialSmall.SetTexture("_ShadowTexture", renderTexture); + floorMaterialSmall.SetMatrix("_ShadowTextureMatrix", matrix); + floorMaterialSmall.SetVector("_Alphas", new Vector4(0.5f * num6, 0f, 0f, 0f)); + Matrix4x4 matrix3 = Matrix4x4.TRS(position, identity, Vector3.one * num * 0.2f); + Graphics.DrawMesh(this.m_FloorPlane, matrix3, floorMaterialSmall, 31, this.m_PreviewUtility.m_Camera, 0); + } + this.SetPreviewCharacterEnabled(true, this.m_ShowReference); + this.m_PreviewUtility.m_Camera.Render(); + this.SetPreviewCharacterEnabled(false, false); + AvatarPreview.TeardownPreviewLightingAndFx(oldFog); + RenderTexture.ReleaseTemporary(renderTexture); + return this.m_PreviewUtility.EndPreview(); + } + private bool SetupPreviewLightingAndFx() + { + this.m_PreviewUtility.m_Light[0].intensity = 0.7f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.7f; + Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + return fog; + } + private static void TeardownPreviewLightingAndFx(bool oldFog) + { + Unsupported.SetRenderSettingsUseFogNoDirty(oldFog); + InternalEditorUtility.RemoveCustomLighting(); + } + private void PositionPreviewObjects(Quaternion pivotRot, Vector3 pivotPos, Quaternion bodyRot, Vector3 bodyPos, Quaternion directionRot, Quaternion rootRot, Vector3 rootPos, Vector3 directionPos, float scale) + { + this.m_ReferenceInstance.transform.position = rootPos; + this.m_ReferenceInstance.transform.rotation = rootRot; + this.m_ReferenceInstance.transform.localScale = Vector3.one * scale * 1.25f; + this.m_DirectionInstance.transform.position = directionPos; + this.m_DirectionInstance.transform.rotation = directionRot; + this.m_DirectionInstance.transform.localScale = Vector3.one * scale * 2f; + this.m_PivotInstance.transform.position = pivotPos; + this.m_PivotInstance.transform.rotation = pivotRot; + this.m_PivotInstance.transform.localScale = Vector3.one * scale * 0.1f; + this.m_RootInstance.transform.position = bodyPos; + this.m_RootInstance.transform.rotation = bodyRot; + this.m_RootInstance.transform.localScale = Vector3.one * scale * 0.25f; + if (this.Animator) + { + float normalizedTime = this.timeControl.normalizedTime; + float num = this.timeControl.deltaTime / (this.timeControl.stopTime - this.timeControl.startTime); + if (normalizedTime - num < 0f || normalizedTime - num >= 1f) + { + this.m_PrevFloorHeight = this.m_NextFloorHeight; + } + if (this.m_LastNormalizedTime != -1000f && this.timeControl.startTime == this.m_LastStartTime && this.timeControl.stopTime == this.m_LastStopTime) + { + float num2 = normalizedTime - num - this.m_LastNormalizedTime; + if (num2 > 0.5f) + { + num2 -= 1f; + } + else + { + if (num2 < -0.5f) + { + num2 += 1f; + } + } + if (Mathf.Abs(num2) > Mathf.Max(0.0001f, Mathf.Abs(num * 0.1f))) + { + Debug.LogError(string.Concat(new object[] + { + "Reported delta does not match with progression of time. Check that the OnInteractivePreviewGUI function only updates the Animator on Repaint events.\nlastNormalTime: ", + this.m_LastNormalizedTime, + ", normalizedDelta: ", + num, + ", expectedNormalizedTime: ", + Mathf.Repeat(this.m_LastNormalizedTime + num, 1f), + ", normalizedTime: ", + normalizedTime, + ", difference: ", + num2 + })); + } + } + this.m_LastNormalizedTime = normalizedTime; + this.m_LastStartTime = this.timeControl.startTime; + this.m_LastStopTime = this.timeControl.stopTime; + if (this.m_NextTargetIsForward) + { + this.m_NextFloorHeight = this.Animator.targetPosition.y; + } + else + { + this.m_PrevFloorHeight = this.Animator.targetPosition.y; + } + this.m_NextTargetIsForward = !this.m_NextTargetIsForward; + this.Animator.SetTarget(AvatarTarget.Root, (float)((!this.m_NextTargetIsForward) ? 0 : 1)); + } + } + public void DoAvatarPreviewDrag(EventType type) + { + if (type == EventType.DragUpdated) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Link; + } + else + { + if (type == EventType.DragPerform) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Link; + GameObject gameObject = DragAndDrop.objectReferences[0] as GameObject; + if (gameObject && AvatarPreview.GetAnimationType(gameObject) == this.animationClipType) + { + DragAndDrop.AcceptDrag(); + this.SetPreview(gameObject); + } + } + } + } + public void AvatarTimeControlGUI(Rect rect) + { + Rect rect2 = rect; + rect2.height = 21f; + this.timeControl.DoTimeControl(rect2); + rect.y = rect.yMax - 20f; + float num = this.timeControl.currentTime - this.timeControl.startTime; + EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y, rect.width, 20f), string.Format("{0,2}:{1:00} ({2:000.0%})", (int)num, this.Repeat(Mathf.FloorToInt(num * (float)this.fps), this.fps), this.timeControl.normalizedTime)); + } + public void DoAvatarPreview(Rect rect, GUIStyle background) + { + this.Init(); + Rect position = new Rect(rect.xMax - 16f, rect.yMax - 16f, 16f, 16f); + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none)) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Auto"), false, new GenericMenu.MenuFunction2(this.SetPreviewAvatarOption), AvatarPreview.PreviewPopupOptions.Auto); + genericMenu.AddItem(new GUIContent("Unity Model"), false, new GenericMenu.MenuFunction2(this.SetPreviewAvatarOption), AvatarPreview.PreviewPopupOptions.DefaultModel); + genericMenu.AddItem(new GUIContent("Other..."), false, new GenericMenu.MenuFunction2(this.SetPreviewAvatarOption), AvatarPreview.PreviewPopupOptions.Other); + genericMenu.ShowAsContext(); + } + Rect rect2 = rect; + rect2.yMin += 21f; + rect2.height = Mathf.Max(rect2.height, 64f); + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, rect2); + int controlID = GUIUtility.GetControlID(this.m_PreviewHint, FocusType.Native, rect2); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.Repaint && this.m_IsValid) + { + Texture image = this.DoRenderPreview(rect2, background); + GUI.DrawTexture(rect2, image, ScaleMode.StretchToFill, false); + } + this.AvatarTimeControlGUI(rect); + GUI.DrawTexture(position, AvatarPreview.s_Styles.avatarIcon.image); + if (!this.m_IsValid) + { + Rect position2 = rect2; + position2.yMax -= position2.height / 2f - 16f; + EditorGUI.DropShadowLabel(position2, "No model is available for preview.\nPlease drag a model into this Preview Area."); + } + this.DoAvatarPreviewDrag(typeForControl); + if (current.type == EventType.ExecuteCommand) + { + string commandName = current.commandName; + if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == this.m_ModelSelectorId) + { + this.SetPreview(ObjectSelector.GetCurrentObject() as GameObject); + current.Use(); + } + } + } + private void SetPreviewAvatarOption(object obj) + { + AvatarPreview.PreviewPopupOptions previewPopupOptions = (AvatarPreview.PreviewPopupOptions)((int)obj); + if (previewPopupOptions == AvatarPreview.PreviewPopupOptions.Auto) + { + this.SetPreview(null); + } + else + { + if (previewPopupOptions == AvatarPreview.PreviewPopupOptions.DefaultModel) + { + this.SetPreview(AvatarPreview.GetHumanoidFallback()); + } + else + { + if (previewPopupOptions == AvatarPreview.PreviewPopupOptions.Other) + { + ObjectSelector.get.Show(null, typeof(GameObject), null, false); + ObjectSelector.get.objectSelectorID = this.m_ModelSelectorId; + } + } + } + } + private void SetPreview(GameObject gameObject) + { + AvatarPreviewSelection.SetPreview(this.animationClipType, gameObject); + UnityEngine.Object.DestroyImmediate(this.m_PreviewInstance); + this.InitInstance(this.m_SourceScenePreviewAnimator, this.m_SourcePreviewMotion); + if (this.m_OnAvatarChangeFunc != null) + { + this.m_OnAvatarChangeFunc(); + } + } + private int Repeat(int t, int length) + { + return (t % length + length) % length; + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarPreviewSelection.cs b/UnityEditor/UnityEditor/AvatarPreviewSelection.cs new file mode 100644 index 00000000..341fa888 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarPreviewSelection.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class AvatarPreviewSelection : ScriptableSingleton + { + [SerializeField] + private GameObject[] m_PreviewModels; + private void Awake() + { + int num = 4; + if (this.m_PreviewModels == null || this.m_PreviewModels.Length != num) + { + this.m_PreviewModels = new GameObject[num]; + } + } + public static void SetPreview(ModelImporterAnimationType type, GameObject go) + { + if (!Enum.IsDefined(typeof(ModelImporterAnimationType), type)) + { + return; + } + if (ScriptableSingleton.instance.m_PreviewModels[(int)type] != go) + { + ScriptableSingleton.instance.m_PreviewModels[(int)type] = go; + ScriptableSingleton.instance.Save(false); + } + } + public static GameObject GetPreview(ModelImporterAnimationType type) + { + if (!Enum.IsDefined(typeof(ModelImporterAnimationType), type)) + { + return null; + } + return ScriptableSingleton.instance.m_PreviewModels[(int)type]; + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarSetupTool.cs b/UnityEditor/UnityEditor/AvatarSetupTool.cs new file mode 100644 index 00000000..7661d8c4 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarSetupTool.cs @@ -0,0 +1,1319 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal static class AvatarSetupTool + { + [Serializable] + internal class BoneWrapper + { + public const int kIconSize = 19; + private static string sHumanName = "m_HumanName"; + private static string sBoneName = "m_BoneName"; + private string m_HumanBoneName; + public string error = string.Empty; + public Transform bone; + public BoneState state; + private static Color kBoneValid = new Color(0f, 0.75f, 0f, 1f); + private static Color kBoneInvalid = new Color(1f, 0.3f, 0.25f, 1f); + private static Color kBoneInactive = Color.gray; + private static Color kBoneSelected = new Color(0.4f, 0.7f, 1f, 1f); + private static Color kBoneDrop = new Color(0.1f, 0.7f, 1f, 1f); + public string humanBoneName + { + get + { + return this.m_HumanBoneName; + } + } + public string messageName + { + get + { + return ObjectNames.NicifyVariableName(this.m_HumanBoneName) + " Transform '" + ((!this.bone) ? "None" : this.bone.name) + "'"; + } + } + public BoneWrapper(string humanBoneName, SerializedObject serializedObject, Dictionary bones) + { + this.m_HumanBoneName = humanBoneName; + this.Reset(serializedObject, bones); + } + public void Reset(SerializedObject serializedObject, Dictionary bones) + { + this.bone = null; + SerializedProperty serializedProperty = this.GetSerializedProperty(serializedObject, false); + if (serializedProperty != null) + { + string boneName = serializedProperty.FindPropertyRelative(AvatarSetupTool.BoneWrapper.sBoneName).stringValue; + this.bone = bones.Keys.FirstOrDefault((Transform b) => b != null && b.name == boneName); + } + this.state = BoneState.Valid; + } + public void Serialize(SerializedObject serializedObject) + { + if (this.bone == null) + { + this.DeleteSerializedProperty(serializedObject); + } + else + { + SerializedProperty serializedProperty = this.GetSerializedProperty(serializedObject, true); + if (serializedProperty != null) + { + serializedProperty.FindPropertyRelative(AvatarSetupTool.BoneWrapper.sBoneName).stringValue = this.bone.name; + } + } + } + protected void DeleteSerializedProperty(SerializedObject serializedObject) + { + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sHuman); + if (serializedProperty == null || !serializedProperty.isArray) + { + return; + } + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative(AvatarSetupTool.BoneWrapper.sHumanName); + if (serializedProperty2.stringValue == this.humanBoneName) + { + serializedProperty.DeleteArrayElementAtIndex(i); + break; + } + } + } + public SerializedProperty GetSerializedProperty(SerializedObject serializedObject, bool createIfMissing) + { + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sHuman); + if (serializedProperty == null || !serializedProperty.isArray) + { + return null; + } + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative(AvatarSetupTool.BoneWrapper.sHumanName); + if (serializedProperty2.stringValue == this.humanBoneName) + { + return serializedProperty.GetArrayElementAtIndex(i); + } + } + if (createIfMissing) + { + serializedProperty.arraySize++; + SerializedProperty arrayElementAtIndex = serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1); + if (arrayElementAtIndex != null) + { + arrayElementAtIndex.FindPropertyRelative(AvatarSetupTool.BoneWrapper.sHumanName).stringValue = this.humanBoneName; + return arrayElementAtIndex; + } + } + return null; + } + public void BoneDotGUI(Rect rect, int boneIndex, bool doClickSelect, bool doDragDrop, SerializedObject serializedObject, AvatarMappingEditor editor) + { + int controlID = GUIUtility.GetControlID(FocusType.Passive, rect); + if (doClickSelect) + { + this.HandleClickSelection(rect, boneIndex); + } + if (doDragDrop) + { + this.HandleDragDrop(rect, boneIndex, controlID, serializedObject, editor); + } + Color color = GUI.color; + if (AvatarMappingEditor.s_SelectedBoneIndex == boneIndex) + { + GUI.color = AvatarSetupTool.BoneWrapper.kBoneSelected; + GUI.DrawTexture(rect, AvatarMappingEditor.styles.dotSelection.image); + } + if (DragAndDrop.activeControlID == controlID) + { + GUI.color = AvatarSetupTool.BoneWrapper.kBoneDrop; + } + else + { + if (this.state == BoneState.Valid) + { + GUI.color = AvatarSetupTool.BoneWrapper.kBoneValid; + } + else + { + if (this.state == BoneState.None) + { + GUI.color = AvatarSetupTool.BoneWrapper.kBoneInactive; + } + else + { + GUI.color = AvatarSetupTool.BoneWrapper.kBoneInvalid; + } + } + } + Texture image; + if (HumanTrait.RequiredBone(boneIndex)) + { + image = AvatarMappingEditor.styles.dotFrame.image; + } + else + { + image = AvatarMappingEditor.styles.dotFrameDotted.image; + } + GUI.DrawTexture(rect, image); + if (this.bone != null || DragAndDrop.activeControlID == controlID) + { + GUI.DrawTexture(rect, AvatarMappingEditor.styles.dotFill.image); + } + GUI.color = color; + } + public void HandleClickSelection(Rect selectRect, int boneIndex) + { + Event current = Event.current; + if (current.type == EventType.MouseDown && selectRect.Contains(current.mousePosition)) + { + AvatarMappingEditor.s_SelectedBoneIndex = boneIndex; + Selection.activeTransform = this.bone; + if (this.bone != null) + { + EditorGUIUtility.PingObject(this.bone); + } + current.Use(); + } + } + private void HandleDragDrop(Rect dropRect, int boneIndex, int id, SerializedObject serializedObject, AvatarMappingEditor editor) + { + EventType type = Event.current.type; + EventType eventType = type; + if (eventType != EventType.DragUpdated && eventType != EventType.DragPerform) + { + if (eventType == EventType.DragExited) + { + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + } + } + else + { + if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object @object = (objectReferences.Length != 1) ? null : objectReferences[0]; + if (@object != null && ((!(@object is Transform) && !(@object is GameObject)) || EditorUtility.IsPersistent(@object))) + { + @object = null; + } + if (@object != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (type == EventType.DragPerform) + { + Undo.RegisterCompleteObjectUndo(editor, "Avatar mapping modified"); + if (@object is GameObject) + { + this.bone = (@object as GameObject).transform; + } + else + { + this.bone = (@object as Transform); + } + this.Serialize(serializedObject); + GUI.changed = true; + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = 0; + } + else + { + DragAndDrop.activeControlID = id; + } + Event.current.Use(); + } + } + } + } + } + private class BonePoseData + { + public Vector3 direction = Vector3.zero; + public bool compareInGlobalSpace; + public float maxAngle; + public int[] childIndices; + public Vector3 planeNormal = Vector3.zero; + public BonePoseData(Vector3 dir, bool globalSpace, float maxAngleDiff) + { + this.direction = ((!(dir == Vector3.zero)) ? dir.normalized : dir); + this.compareInGlobalSpace = globalSpace; + this.maxAngle = maxAngleDiff; + } + public BonePoseData(Vector3 dir, bool globalSpace, float maxAngleDiff, int[] children) : this(dir, globalSpace, maxAngleDiff) + { + this.childIndices = children; + } + public BonePoseData(Vector3 dir, bool globalSpace, float maxAngleDiff, Vector3 planeNormal, int[] children) : this(dir, globalSpace, maxAngleDiff, children) + { + this.planeNormal = planeNormal; + } + } + private class TransformHierarchySorter : IComparer + { + public int Compare(Transform a, Transform b) + { + while (!(a == null)) + { + if (b == null) + { + return 1; + } + a = a.parent; + b = b.parent; + } + if (b == null) + { + return 0; + } + return -1; + } + } + private class SkinTransformHierarchySorter : IComparer + { + public int Compare(SkinnedMeshRenderer skinA, SkinnedMeshRenderer skinB) + { + Transform transform = skinA.transform; + Transform transform2 = skinB.transform; + while (!(transform == null)) + { + if (transform2 == null) + { + return 1; + } + transform = transform.parent; + transform2 = transform2.parent; + } + if (transform2 == null) + { + return 0; + } + return -1; + } + } + private static string sHuman = "m_HumanDescription.m_Human"; + internal static string sSkeleton = "m_HumanDescription.m_Skeleton"; + internal static string sName = "m_Name"; + internal static string sPosition = "m_Position"; + internal static string sRotation = "m_Rotation"; + internal static string sScale = "m_Scale"; + internal static string sTransformModified = "m_TransformModified"; + internal static int[] sHumanParent = new int[] + { + 0, + 0, + 0, + 1, + 2, + 3, + 4, + 0, + 7, + 8, + 9, + 8, + 8, + 11, + 12, + 13, + 14, + 15, + 16, + 5, + 6, + 10, + 10, + 10, + 17, + 24, + 25, + 17, + 27, + 28, + 17, + 30, + 31, + 17, + 33, + 34, + 17, + 36, + 37, + 18, + 39, + 40, + 18, + 42, + 43, + 18, + 45, + 46, + 18, + 48, + 49, + 18, + 51, + 52 + }; + private static AvatarSetupTool.BonePoseData[] sBonePoses = new AvatarSetupTool.BonePoseData[] + { + new AvatarSetupTool.BonePoseData(Vector3.up, true, 15f), + new AvatarSetupTool.BonePoseData(new Vector3(-0.05f, -1f, 0f), true, 15f), + new AvatarSetupTool.BonePoseData(new Vector3(0.05f, -1f, 0f), true, 15f), + new AvatarSetupTool.BonePoseData(new Vector3(-0.05f, -1f, -0.15f), true, 20f), + new AvatarSetupTool.BonePoseData(new Vector3(0.05f, -1f, -0.15f), true, 20f), + new AvatarSetupTool.BonePoseData(new Vector3(-0.05f, 0f, 1f), true, 20f, Vector3.up, null), + new AvatarSetupTool.BonePoseData(new Vector3(0.05f, 0f, 1f), true, 20f, Vector3.up, null), + new AvatarSetupTool.BonePoseData(Vector3.up, true, 30f, new int[] + { + 8, + 9, + 10 + }), + new AvatarSetupTool.BonePoseData(Vector3.up, true, 30f, new int[] + { + 9, + 10 + }), + new AvatarSetupTool.BonePoseData(Vector3.up, true, 30f), + null, + new AvatarSetupTool.BonePoseData(-Vector3.right, true, 20f), + new AvatarSetupTool.BonePoseData(Vector3.right, true, 20f), + new AvatarSetupTool.BonePoseData(-Vector3.right, true, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, true, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, true, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, true, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 10f, Vector3.forward, new int[] + { + 30 + }), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 10f, Vector3.forward, new int[] + { + 45 + }), + null, + null, + null, + null, + null, + new AvatarSetupTool.BonePoseData(new Vector3(-1f, 0f, 1f), false, 10f), + new AvatarSetupTool.BonePoseData(new Vector3(-1f, 0f, 1f), false, 5f), + new AvatarSetupTool.BonePoseData(new Vector3(-1f, 0f, 1f), false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(-Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(new Vector3(1f, 0f, 1f), false, 10f), + new AvatarSetupTool.BonePoseData(new Vector3(1f, 0f, 1f), false, 5f), + new AvatarSetupTool.BonePoseData(new Vector3(1f, 0f, 1f), false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 10f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f), + new AvatarSetupTool.BonePoseData(Vector3.right, false, 5f) + }; + public static Dictionary GetModelBones(Transform root, bool includeAll, AvatarSetupTool.BoneWrapper[] humanBones) + { + if (root == null) + { + return null; + } + Dictionary dictionary = new Dictionary(); + List list = new List(); + if (!includeAll) + { + SkinnedMeshRenderer[] componentsInChildren = root.GetComponentsInChildren(); + SkinnedMeshRenderer[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + SkinnedMeshRenderer skinnedMeshRenderer = array[i]; + Transform[] bones = skinnedMeshRenderer.bones; + bool[] array2 = new bool[bones.Length]; + BoneWeight[] boneWeights = skinnedMeshRenderer.sharedMesh.boneWeights; + BoneWeight[] array3 = boneWeights; + for (int j = 0; j < array3.Length; j++) + { + BoneWeight boneWeight = array3[j]; + if (boneWeight.weight0 != 0f) + { + array2[boneWeight.boneIndex0] = true; + } + if (boneWeight.weight1 != 0f) + { + array2[boneWeight.boneIndex1] = true; + } + if (boneWeight.weight2 != 0f) + { + array2[boneWeight.boneIndex2] = true; + } + if (boneWeight.weight3 != 0f) + { + array2[boneWeight.boneIndex3] = true; + } + } + for (int k = 0; k < bones.Length; k++) + { + if (array2[k] && !list.Contains(bones[k])) + { + list.Add(bones[k]); + } + } + } + AvatarSetupTool.DetermineIsActualBone(root, dictionary, list, false, humanBones); + } + if (dictionary.Count < HumanTrait.RequiredBoneCount) + { + dictionary.Clear(); + list.Clear(); + AvatarSetupTool.DetermineIsActualBone(root, dictionary, list, true, humanBones); + } + return dictionary; + } + private static bool DetermineIsActualBone(Transform tr, Dictionary bones, List skinnedBones, bool includeAll, AvatarSetupTool.BoneWrapper[] humanBones) + { + bool flag = includeAll; + bool flag2 = false; + bool flag3 = false; + int num = 0; + foreach (Transform tr2 in tr) + { + if (AvatarSetupTool.DetermineIsActualBone(tr2, bones, skinnedBones, includeAll, humanBones)) + { + num++; + } + } + if (num > 0) + { + flag2 = true; + } + if (num > 1) + { + flag = true; + } + if (!flag && skinnedBones.Contains(tr)) + { + flag = true; + } + if (!flag) + { + Component[] components = tr.GetComponents(); + if (components.Length > 1) + { + Component[] array = components; + for (int i = 0; i < array.Length; i++) + { + Component component = array[i]; + if (component is Renderer && !(component is SkinnedMeshRenderer)) + { + Bounds bounds = (component as Renderer).bounds; + bounds.extents = bounds.size; + if (tr.childCount == 0 && tr.parent && bounds.Contains(tr.parent.position)) + { + if (tr.parent.GetComponent() != null) + { + flag = true; + } + else + { + flag3 = true; + } + } + else + { + if (bounds.Contains(tr.position)) + { + flag = true; + } + } + } + } + } + } + if (!flag && humanBones != null) + { + for (int j = 0; j < humanBones.Length; j++) + { + AvatarSetupTool.BoneWrapper boneWrapper = humanBones[j]; + if (tr == boneWrapper.bone) + { + flag = true; + break; + } + } + } + if (flag) + { + bones[tr] = true; + } + else + { + if (flag2) + { + if (!bones.ContainsKey(tr)) + { + bones[tr] = false; + } + } + else + { + if (flag3) + { + bones[tr.parent] = true; + } + } + } + return bones.ContainsKey(tr); + } + public static int GetFirstHumanBoneAncestor(AvatarSetupTool.BoneWrapper[] bones, int boneIndex) + { + boneIndex = AvatarSetupTool.sHumanParent[boneIndex]; + while (bones[boneIndex].bone == null && boneIndex != 0) + { + boneIndex = AvatarSetupTool.sHumanParent[boneIndex]; + } + return boneIndex; + } + public static int GetHumanBoneChild(AvatarSetupTool.BoneWrapper[] bones, int boneIndex) + { + for (int i = 0; i < AvatarSetupTool.sHumanParent.Length; i++) + { + if (AvatarSetupTool.sHumanParent[i] == boneIndex) + { + return i; + } + } + return -1; + } + public static AvatarSetupTool.BoneWrapper[] GetHumanBones(SerializedObject serializedObject, Dictionary actualBones) + { + string[] boneName = HumanTrait.BoneName; + AvatarSetupTool.BoneWrapper[] array = new AvatarSetupTool.BoneWrapper[boneName.Length]; + for (int i = 0; i < boneName.Length; i++) + { + array[i] = new AvatarSetupTool.BoneWrapper(boneName[i], serializedObject, actualBones); + } + return array; + } + public static void ClearAll(SerializedObject serializedObject) + { + AvatarSetupTool.ClearHumanBoneArray(serializedObject); + AvatarSetupTool.ClearSkeletonBoneArray(serializedObject); + } + public static void ClearHumanBoneArray(SerializedObject serializedObject) + { + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sHuman); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.ClearArray(); + } + } + public static void ClearSkeletonBoneArray(SerializedObject serializedObject) + { + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sSkeleton); + if (serializedProperty != null && serializedProperty.isArray) + { + serializedProperty.ClearArray(); + } + } + public static void AutoSetupOnInstance(GameObject modelPrefab, SerializedObject modelImporterSerializedObject) + { + GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab) as GameObject; + gameObject.hideFlags = HideFlags.HideAndDontSave; + AvatarSetupTool.AutoSetup(modelPrefab, gameObject, modelImporterSerializedObject); + UnityEngine.Object.DestroyImmediate(gameObject); + } + public static bool IsPoseValidOnInstance(GameObject modelPrefab, SerializedObject modelImporterSerializedObject) + { + GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab) as GameObject; + gameObject.hideFlags = HideFlags.HideAndDontSave; + Dictionary modelBones = AvatarSetupTool.GetModelBones(gameObject.transform, false, null); + AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(modelImporterSerializedObject, modelBones); + AvatarSetupTool.TransferDescriptionToPose(modelImporterSerializedObject, gameObject.transform); + bool result = AvatarSetupTool.IsPoseValid(humanBones); + UnityEngine.Object.DestroyImmediate(gameObject); + return result; + } + public static void AutoSetup(GameObject modelPrefab, GameObject modelInstance, SerializedObject modelImporterSerializedObject) + { + SerializedProperty serializedProperty = modelImporterSerializedObject.FindProperty(AvatarSetupTool.sHuman); + if (serializedProperty == null || !serializedProperty.isArray) + { + return; + } + AvatarSetupTool.ClearHumanBoneArray(modelImporterSerializedObject); + AvatarSetupTool.SampleBindPose(modelInstance); + Dictionary modelBones = AvatarSetupTool.GetModelBones(modelInstance.transform, false, null); + Dictionary dictionary = AvatarAutoMapper.MapBones(modelInstance.transform, modelBones); + AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(modelImporterSerializedObject, modelBones); + for (int i = 0; i < humanBones.Length; i++) + { + AvatarSetupTool.BoneWrapper boneWrapper = humanBones[i]; + if (dictionary.ContainsKey(i)) + { + boneWrapper.bone = dictionary[i]; + } + else + { + boneWrapper.bone = null; + } + boneWrapper.Serialize(modelImporterSerializedObject); + } + float poseError = AvatarSetupTool.GetPoseError(humanBones); + AvatarSetupTool.CopyPose(modelInstance, modelPrefab); + float poseError2 = AvatarSetupTool.GetPoseError(humanBones); + if (poseError < poseError2) + { + AvatarSetupTool.SampleBindPose(modelInstance); + } + AvatarSetupTool.MakePoseValid(humanBones); + AvatarSetupTool.TransferPoseToDescription(modelImporterSerializedObject, modelInstance.transform); + } + public static bool TestAndValidateAutoSetup(GameObject modelAsset) + { + if (modelAsset == null) + { + Debug.LogError("GameObject is null"); + return false; + } + if (PrefabUtility.GetPrefabType(modelAsset) != PrefabType.ModelPrefab) + { + Debug.LogError(modelAsset.name + ": GameObject is not a ModelPrefab", modelAsset); + return false; + } + if (modelAsset.transform.parent != null) + { + Debug.LogError(modelAsset.name + ": GameObject is not the root", modelAsset); + return false; + } + string assetPath = AssetDatabase.GetAssetPath(modelAsset); + ModelImporter modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter; + if (modelImporter == null) + { + Debug.LogError(modelAsset.name + ": Could not load ModelImporter (path:" + assetPath + ")", modelAsset); + return false; + } + SerializedObject serializedObject = new SerializedObject(modelImporter); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_AnimationType"); + if (serializedProperty == null) + { + Debug.LogError(modelAsset.name + ": Could not find property m_AnimationType on ModelImporter", modelAsset); + return false; + } + serializedProperty.intValue = 2; + AvatarSetupTool.ClearAll(serializedObject); + serializedObject.ApplyModifiedProperties(); + AssetDatabase.ImportAsset(assetPath); + serializedProperty.intValue = 3; + AvatarSetupTool.AutoSetupOnInstance(modelAsset, serializedObject); + serializedObject.ApplyModifiedProperties(); + AssetDatabase.ImportAsset(assetPath); + Avatar avatar = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Avatar)) as Avatar; + if (avatar == null) + { + Debug.LogError(modelAsset.name + ": Did not find Avatar after reimport with CreateAvatar enabled", modelAsset); + return false; + } + if (!avatar.isHuman) + { + Debug.LogError(modelAsset.name + ": Avatar is not valid after reimport", modelAsset); + return false; + } + if (!AvatarSetupTool.IsPoseValidOnInstance(modelAsset, serializedObject)) + { + Debug.LogError(modelAsset.name + ": Avatar has invalid pose after reimport", modelAsset); + return false; + } + string str = assetPath.Substring(0, assetPath.Length - Path.GetExtension(assetPath).Length); + string text = str + ".ht"; + HumanTemplate humanTemplate = AssetDatabase.LoadMainAssetAtPath(text) as HumanTemplate; + if (humanTemplate == null) + { + Debug.LogWarning(modelAsset.name + ": Didn't find template at path " + text); + } + else + { + List list = null; + string path = str + ".ignore"; + if (File.Exists(path)) + { + list = new List(File.ReadAllLines(path)); + } + GameObject gameObject = UnityEngine.Object.Instantiate(modelAsset) as GameObject; + gameObject.hideFlags = HideFlags.HideAndDontSave; + Dictionary modelBones = AvatarSetupTool.GetModelBones(gameObject.transform, false, null); + AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(serializedObject, modelBones); + bool flag = false; + for (int i = 0; i < humanBones.Length; i++) + { + if (list == null || !list.Contains(humanBones[i].humanBoneName)) + { + string text2 = humanTemplate.Find(humanBones[i].humanBoneName); + string text3 = (!(humanBones[i].bone == null)) ? humanBones[i].bone.name : string.Empty; + if (!AvatarMappingEditor.MatchName(text3, text2)) + { + flag = true; + Debug.LogError(string.Concat(new string[] + { + modelAsset.name, + ": Avatar has bone ", + humanBones[i].humanBoneName, + " mapped to \"", + text3, + "\" but expected \"", + text2, + "\"" + }), modelAsset); + } + } + } + UnityEngine.Object.DestroyImmediate(gameObject); + if (flag) + { + return false; + } + } + return true; + } + public static void DebugTransformTree(Transform tr, Dictionary bones, int level) + { + string str = " "; + if (bones.ContainsKey(tr)) + { + if (bones[tr]) + { + str = "* "; + } + else + { + str = ". "; + } + } + Debug.Log(" ".Substring(0, level * 2) + str + tr.name + "\n\n"); + foreach (Transform tr2 in tr) + { + AvatarSetupTool.DebugTransformTree(tr2, bones, level + 1); + } + } + public static SerializedProperty FindSkeletonBone(SerializedObject serializedObject, Transform t, bool createMissing, bool isRoot) + { + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sSkeleton); + if (serializedProperty == null || !serializedProperty.isArray) + { + return null; + } + return AvatarSetupTool.FindSkeletonBone(serializedProperty, t, createMissing, isRoot); + } + public static SerializedProperty FindSkeletonBone(SerializedProperty skeletonBoneArray, Transform t, bool createMissing, bool isRoot) + { + if (isRoot && skeletonBoneArray.arraySize > 0) + { + SerializedProperty arrayElementAtIndex = skeletonBoneArray.GetArrayElementAtIndex(0); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative(AvatarSetupTool.sName); + if (serializedProperty.stringValue == t.name) + { + return arrayElementAtIndex; + } + } + else + { + for (int i = 1; i < skeletonBoneArray.arraySize; i++) + { + SerializedProperty arrayElementAtIndex2 = skeletonBoneArray.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty2 = arrayElementAtIndex2.FindPropertyRelative(AvatarSetupTool.sName); + if (serializedProperty2.stringValue == t.name) + { + return arrayElementAtIndex2; + } + } + } + if (createMissing) + { + skeletonBoneArray.arraySize++; + SerializedProperty arrayElementAtIndex3 = skeletonBoneArray.GetArrayElementAtIndex(skeletonBoneArray.arraySize - 1); + if (arrayElementAtIndex3 != null) + { + arrayElementAtIndex3.FindPropertyRelative(AvatarSetupTool.sName).stringValue = t.name; + arrayElementAtIndex3.FindPropertyRelative(AvatarSetupTool.sPosition).vector3Value = t.localPosition; + arrayElementAtIndex3.FindPropertyRelative(AvatarSetupTool.sRotation).quaternionValue = t.localRotation; + arrayElementAtIndex3.FindPropertyRelative(AvatarSetupTool.sScale).vector3Value = t.localScale; + arrayElementAtIndex3.FindPropertyRelative(AvatarSetupTool.sTransformModified).boolValue = true; + return arrayElementAtIndex3; + } + } + return null; + } + public static void CopyPose(GameObject go, GameObject source) + { + AvatarSetupTool.CopyPose(go.transform, source.transform); + } + private static void CopyPose(Transform t, Transform source) + { + t.localPosition = source.localPosition; + t.localRotation = source.localRotation; + t.localScale = source.localScale; + foreach (Transform transform in t) + { + Transform transform2 = source.FindChild(transform.name); + if (transform2) + { + AvatarSetupTool.CopyPose(transform, transform2); + } + } + } + public static void GetBindPoseBonePositionRotation(Matrix4x4 skinMatrix, Matrix4x4 boneMatrix, Transform bone, out Vector3 position, out Quaternion rotation) + { + Matrix4x4 matrix4x = skinMatrix * boneMatrix.inverse; + Vector3 lhs = new Vector3(matrix4x.m00, matrix4x.m10, matrix4x.m20); + Vector3 vector = new Vector3(matrix4x.m01, matrix4x.m11, matrix4x.m21); + Vector3 vector2 = new Vector3(matrix4x.m02, matrix4x.m12, matrix4x.m22); + Vector3 a = new Vector3(matrix4x.m03, matrix4x.m13, matrix4x.m23); + float magnitude = vector2.magnitude; + float num = Mathf.Abs(bone.lossyScale.z); + position = a * (num / magnitude); + if (Vector3.Dot(Vector3.Cross(lhs, vector), vector2) >= 0f) + { + rotation = Quaternion.LookRotation(vector2, vector); + } + else + { + rotation = Quaternion.LookRotation(-vector2, -vector); + } + } + public static void SampleBindPose(GameObject go) + { + List list = new List(go.GetComponentsInChildren()); + list.Sort(new AvatarSetupTool.SkinTransformHierarchySorter()); + foreach (SkinnedMeshRenderer current in list) + { + Matrix4x4 localToWorldMatrix = current.transform.localToWorldMatrix; + List list2 = new List(current.bones); + Vector3[] array = new Vector3[list2.Count]; + for (int i = 0; i < list2.Count; i++) + { + array[i] = list2[i].localPosition; + } + Dictionary dictionary = new Dictionary(); + foreach (Transform current2 in list2) + { + dictionary[current2] = current2.parent; + current2.parent = null; + } + for (int j = 0; j < list2.Count; j++) + { + Vector3 position; + Quaternion rotation; + AvatarSetupTool.GetBindPoseBonePositionRotation(localToWorldMatrix, current.sharedMesh.bindposes[j], list2[j], out position, out rotation); + list2[j].position = position; + list2[j].rotation = rotation; + } + foreach (Transform current3 in list2) + { + current3.parent = dictionary[current3]; + } + for (int k = 0; k < list2.Count; k++) + { + list2[k].localPosition = array[k]; + } + } + } + public static void ShowBindPose(SkinnedMeshRenderer skin) + { + Matrix4x4 localToWorldMatrix = skin.transform.localToWorldMatrix; + for (int i = 0; i < skin.bones.Length; i++) + { + Vector3 vector; + Quaternion rotation; + AvatarSetupTool.GetBindPoseBonePositionRotation(localToWorldMatrix, skin.sharedMesh.bindposes[i], skin.bones[i], out vector, out rotation); + float handleSize = HandleUtility.GetHandleSize(vector); + Handles.color = Handles.xAxisColor; + Handles.DrawLine(vector, vector + rotation * Vector3.right * 0.3f * handleSize); + Handles.color = Handles.yAxisColor; + Handles.DrawLine(vector, vector + rotation * Vector3.up * 0.3f * handleSize); + Handles.color = Handles.zAxisColor; + Handles.DrawLine(vector, vector + rotation * Vector3.forward * 0.3f * handleSize); + } + } + public static void TransferPoseToDescription(SerializedObject serializedObject, Transform root) + { + SkeletonBone[] skeletonBones = new SkeletonBone[0]; + if (root) + { + AvatarSetupTool.TransferPoseToDescription(serializedObject, root, true, ref skeletonBones); + } + SerializedProperty serializedProperty = serializedObject.FindProperty(AvatarSetupTool.sSkeleton); + ModelImporter.UpdateSkeletonPose(skeletonBones, serializedProperty); + } + private static void TransferPoseToDescription(SerializedObject serializedObject, Transform transform, bool isRoot, ref SkeletonBone[] skeletonBones) + { + ArrayUtility.Add(ref skeletonBones, new SkeletonBone + { + name = transform.name, + position = transform.localPosition, + rotation = transform.localRotation, + scale = transform.localScale, + transformModified = 1 + }); + foreach (Transform transform2 in transform) + { + AvatarSetupTool.TransferPoseToDescription(serializedObject, transform2, false, ref skeletonBones); + } + } + public static void TransferDescriptionToPose(SerializedObject serializedObject, Transform root) + { + if (root != null) + { + AvatarSetupTool.TransferDescriptionToPose(serializedObject, root, true); + } + } + private static void TransferDescriptionToPose(SerializedObject serializedObject, Transform transform, bool isRoot) + { + SerializedProperty serializedProperty = AvatarSetupTool.FindSkeletonBone(serializedObject, transform, false, isRoot); + if (serializedProperty != null) + { + SerializedProperty serializedProperty2 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sTransformModified); + if (serializedProperty2.boolValue) + { + SerializedProperty serializedProperty3 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sPosition); + SerializedProperty serializedProperty4 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sRotation); + SerializedProperty serializedProperty5 = serializedProperty.FindPropertyRelative(AvatarSetupTool.sScale); + transform.localPosition = serializedProperty3.vector3Value; + transform.localRotation = serializedProperty4.quaternionValue; + transform.localScale = serializedProperty5.vector3Value; + } + } + foreach (Transform transform2 in transform) + { + AvatarSetupTool.TransferDescriptionToPose(serializedObject, transform2, false); + } + } + public static bool IsPoseValid(AvatarSetupTool.BoneWrapper[] bones) + { + return AvatarSetupTool.GetPoseError(bones) == 0f; + } + public static float GetPoseError(AvatarSetupTool.BoneWrapper[] bones) + { + Quaternion avatarOrientation = AvatarSetupTool.AvatarComputeOrientation(bones); + float num = 0f; + for (int i = 0; i < AvatarSetupTool.sBonePoses.Length; i++) + { + num += AvatarSetupTool.GetBoneAlignmentError(bones, avatarOrientation, i); + } + return num + AvatarSetupTool.GetCharacterPositionError(bones); + } + public static void MakePoseValid(AvatarSetupTool.BoneWrapper[] bones) + { + Quaternion avatarOrientation = AvatarSetupTool.AvatarComputeOrientation(bones); + for (int i = 0; i < AvatarSetupTool.sBonePoses.Length; i++) + { + AvatarSetupTool.MakeBoneAlignmentValid(bones, avatarOrientation, i); + if (i == 0) + { + avatarOrientation = AvatarSetupTool.AvatarComputeOrientation(bones); + } + } + AvatarSetupTool.MakeCharacterPositionValid(bones); + } + public static float GetBoneAlignmentError(AvatarSetupTool.BoneWrapper[] bones, Quaternion avatarOrientation, int boneIndex) + { + if (boneIndex < 0 || boneIndex >= AvatarSetupTool.sBonePoses.Length) + { + return 0f; + } + AvatarSetupTool.BoneWrapper boneWrapper = bones[boneIndex]; + AvatarSetupTool.BonePoseData bonePoseData = AvatarSetupTool.sBonePoses[boneIndex]; + if (boneWrapper.bone == null || bonePoseData == null) + { + return 0f; + } + if (boneIndex == 0) + { + float num = Vector3.Angle(avatarOrientation * Vector3.right, Vector3.right); + float num2 = Vector3.Angle(avatarOrientation * Vector3.up, Vector3.up); + float num3 = Vector3.Angle(avatarOrientation * Vector3.forward, Vector3.forward); + return Mathf.Max(0f, Mathf.Max(new float[] + { + num, + num2, + num3 + }) - bonePoseData.maxAngle); + } + Vector3 vector = AvatarSetupTool.GetBoneAlignmentDirection(bones, avatarOrientation, boneIndex); + if (vector == Vector3.zero) + { + return 0f; + } + Quaternion rotationSpace = AvatarSetupTool.GetRotationSpace(bones, avatarOrientation, boneIndex); + Vector3 to = rotationSpace * bonePoseData.direction; + if (bonePoseData.planeNormal != Vector3.zero) + { + vector = Vector3.ProjectOnPlane(vector, rotationSpace * bonePoseData.planeNormal); + } + return Mathf.Max(0f, Vector3.Angle(vector, to) - bonePoseData.maxAngle); + } + public static void MakeBoneAlignmentValid(AvatarSetupTool.BoneWrapper[] bones, Quaternion avatarOrientation, int boneIndex) + { + if (boneIndex < 0 || boneIndex >= AvatarSetupTool.sBonePoses.Length || boneIndex >= bones.Length) + { + return; + } + AvatarSetupTool.BoneWrapper boneWrapper = bones[boneIndex]; + AvatarSetupTool.BonePoseData bonePoseData = AvatarSetupTool.sBonePoses[boneIndex]; + if (boneWrapper.bone == null || bonePoseData == null) + { + return; + } + if (boneIndex == 0) + { + float num = Vector3.Angle(avatarOrientation * Vector3.right, Vector3.right); + float num2 = Vector3.Angle(avatarOrientation * Vector3.up, Vector3.up); + float num3 = Vector3.Angle(avatarOrientation * Vector3.forward, Vector3.forward); + if (num > bonePoseData.maxAngle || num2 > bonePoseData.maxAngle || num3 > bonePoseData.maxAngle) + { + boneWrapper.bone.rotation = Quaternion.Inverse(avatarOrientation) * boneWrapper.bone.rotation; + } + return; + } + Vector3 vector = AvatarSetupTool.GetBoneAlignmentDirection(bones, avatarOrientation, boneIndex); + if (vector == Vector3.zero) + { + return; + } + Quaternion rotationSpace = AvatarSetupTool.GetRotationSpace(bones, avatarOrientation, boneIndex); + Vector3 vector2 = rotationSpace * bonePoseData.direction; + if (bonePoseData.planeNormal != Vector3.zero) + { + vector = Vector3.ProjectOnPlane(vector, rotationSpace * bonePoseData.planeNormal); + } + float num4 = Vector3.Angle(vector, vector2); + if (num4 > bonePoseData.maxAngle * 0.99f) + { + Quaternion quaternion = Quaternion.FromToRotation(vector, vector2); + Transform transform = null; + Quaternion rotation = Quaternion.identity; + if (boneIndex == 1 || boneIndex == 3) + { + transform = bones[5].bone; + } + if (boneIndex == 2 || boneIndex == 4) + { + transform = bones[6].bone; + } + if (transform != null) + { + rotation = transform.rotation; + } + float t = Mathf.Clamp01(1.05f - bonePoseData.maxAngle / num4); + quaternion = Quaternion.Slerp(Quaternion.identity, quaternion, t); + boneWrapper.bone.rotation = quaternion * boneWrapper.bone.rotation; + if (transform != null) + { + transform.rotation = rotation; + } + } + } + private static Quaternion GetRotationSpace(AvatarSetupTool.BoneWrapper[] bones, Quaternion avatarOrientation, int boneIndex) + { + Quaternion lhs = Quaternion.identity; + AvatarSetupTool.BonePoseData bonePoseData = AvatarSetupTool.sBonePoses[boneIndex]; + if (!bonePoseData.compareInGlobalSpace) + { + int num = AvatarSetupTool.sHumanParent[boneIndex]; + AvatarSetupTool.BonePoseData bonePoseData2 = AvatarSetupTool.sBonePoses[num]; + if (bones[num].bone != null && bonePoseData2 != null) + { + Vector3 boneAlignmentDirection = AvatarSetupTool.GetBoneAlignmentDirection(bones, avatarOrientation, num); + if (boneAlignmentDirection != Vector3.zero) + { + Vector3 fromDirection = avatarOrientation * bonePoseData2.direction; + lhs = Quaternion.FromToRotation(fromDirection, boneAlignmentDirection); + } + } + } + return lhs * avatarOrientation; + } + private static Vector3 GetBoneAlignmentDirection(AvatarSetupTool.BoneWrapper[] bones, Quaternion avatarOrientation, int boneIndex) + { + if (AvatarSetupTool.sBonePoses[boneIndex] == null) + { + return Vector3.zero; + } + AvatarSetupTool.BoneWrapper boneWrapper = bones[boneIndex]; + AvatarSetupTool.BonePoseData bonePoseData = AvatarSetupTool.sBonePoses[boneIndex]; + int num = -1; + if (bonePoseData.childIndices != null) + { + int[] childIndices = bonePoseData.childIndices; + for (int i = 0; i < childIndices.Length; i++) + { + int num2 = childIndices[i]; + if (bones[num2].bone != null) + { + num = num2; + break; + } + } + } + else + { + num = AvatarSetupTool.GetHumanBoneChild(bones, boneIndex); + } + Vector3 vector; + if (num >= 0 && bones[num] != null && bones[num].bone != null) + { + AvatarSetupTool.BoneWrapper boneWrapper2 = bones[num]; + vector = boneWrapper2.bone.position - boneWrapper.bone.position; + } + else + { + if (boneWrapper.bone.childCount != 1) + { + return Vector3.zero; + } + vector = Vector3.zero; + IEnumerator enumerator = boneWrapper.bone.GetEnumerator(); + try + { + if (enumerator.MoveNext()) + { + Transform transform = (Transform)enumerator.Current; + vector = transform.position - boneWrapper.bone.position; + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + } + return vector.normalized; + } + public static Quaternion AvatarComputeOrientation(AvatarSetupTool.BoneWrapper[] bones) + { + Transform bone = bones[1].bone; + Transform bone2 = bones[2].bone; + Transform bone3 = bones[13].bone; + Transform bone4 = bones[14].bone; + if (bone != null && bone2 != null && bone3 != null && bone4 != null) + { + return AvatarSetupTool.AvatarComputeOrientation(bone.position, bone2.position, bone3.position, bone4.position); + } + return Quaternion.identity; + } + public static Quaternion AvatarComputeOrientation(Vector3 leftUpLeg, Vector3 rightUpLeg, Vector3 leftArm, Vector3 rightArm) + { + Vector3 a = Vector3.Normalize(rightUpLeg - leftUpLeg); + Vector3 b = Vector3.Normalize(rightArm - leftArm); + Vector3 lhs = Vector3.Normalize(a + b); + bool flag = Mathf.Abs(lhs.x * lhs.y) < 0.05f && Mathf.Abs(lhs.y * lhs.z) < 0.05f && Mathf.Abs(lhs.z * lhs.x) < 0.05f; + Vector3 b2 = (leftUpLeg + rightUpLeg) * 0.5f; + Vector3 a2 = (leftArm + rightArm) * 0.5f; + Vector3 vector = Vector3.Normalize(a2 - b2); + if (flag) + { + int index = 0; + for (int i = 1; i < 3; i++) + { + if (Mathf.Abs(vector[i]) > Mathf.Abs(vector[index])) + { + index = i; + } + } + float value = Mathf.Sign(vector[index]); + vector = Vector3.zero; + vector[index] = value; + } + Vector3 vector2 = Vector3.Cross(lhs, vector); + if (vector2 == Vector3.zero || vector == Vector3.zero) + { + return Quaternion.identity; + } + return Quaternion.LookRotation(vector2, vector); + } + private static float GetCharacterPositionError(AvatarSetupTool.BoneWrapper[] bones) + { + float result; + AvatarSetupTool.GetCharacterPositionAdjustVector(bones, out result); + return result; + } + private static void MakeCharacterPositionValid(AvatarSetupTool.BoneWrapper[] bones) + { + float num; + Vector3 characterPositionAdjustVector = AvatarSetupTool.GetCharacterPositionAdjustVector(bones, out num); + if (characterPositionAdjustVector != Vector3.zero) + { + bones[0].bone.position += characterPositionAdjustVector; + } + } + private static Vector3 GetCharacterPositionAdjustVector(AvatarSetupTool.BoneWrapper[] bones, out float error) + { + error = 0f; + Transform bone = bones[1].bone; + Transform bone2 = bones[2].bone; + if (bone == null || bone2 == null) + { + return Vector3.zero; + } + Vector3 vector = (bone.position + bone2.position) * 0.5f; + bool flag = true; + Transform bone3 = bones[19].bone; + Transform bone4 = bones[20].bone; + if (bone3 == null || bone4 == null) + { + flag = false; + bone3 = bones[5].bone; + bone4 = bones[6].bone; + } + if (bone3 == null || bone4 == null) + { + return Vector3.zero; + } + Vector3 vector2 = (bone3.position + bone4.position) * 0.5f; + float num = vector.y - vector2.y; + if (num <= 0f) + { + return Vector3.zero; + } + Vector3 zero = Vector3.zero; + if (vector2.y < 0f || vector2.y > num * ((!flag) ? 0.3f : 0.1f)) + { + float num2 = vector.y - num * ((!flag) ? 1.13f : 1.03f); + zero.y = -num2; + } + if (Mathf.Abs(vector.x) > 0.01f * num) + { + zero.x = -vector.x; + } + if (Mathf.Abs(vector.z) > 0.2f * num) + { + zero.z = -vector.z; + } + error = zero.magnitude * 100f / num; + return zero; + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarSkeletonDrawer.cs b/UnityEditor/UnityEditor/AvatarSkeletonDrawer.cs new file mode 100644 index 00000000..14dd2f79 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarSkeletonDrawer.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class AvatarSkeletonDrawer + { + private static bool sPoseError; + private static Color kSkeletonColor = new Color(0.403921574f, 0.403921574f, 0.403921574f, 0.25f); + private static Color kDummyColor = new Color(0.235294119f, 0.235294119f, 0.235294119f, 0.25f); + private static Color kHumanColor = new Color(0f, 0.8235294f, 0.2901961f, 0.25f); + private static Color kErrorColor = new Color(1f, 0f, 0f, 0.25f); + private static Color kErrorMessageColor = new Color(1f, 0f, 0f, 0.75f); + private static Color kSelectedColor = new Color(0.5019608f, 0.7529412f, 1f, 0.15f); + public static void DrawSkeleton(Transform reference, Dictionary actualBones) + { + AvatarSkeletonDrawer.DrawSkeleton(reference, actualBones, null); + } + public static void DrawSkeleton(Transform reference, Dictionary actualBones, AvatarSetupTool.BoneWrapper[] bones) + { + if (reference == null || actualBones == null) + { + return; + } + AvatarSkeletonDrawer.sPoseError = false; + Bounds bounds = default(Bounds); + Renderer[] componentsInChildren = reference.root.GetComponentsInChildren(); + if (componentsInChildren != null) + { + Renderer[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + Renderer renderer = array[i]; + bounds.Encapsulate(renderer.bounds.min); + bounds.Encapsulate(renderer.bounds.max); + } + } + Quaternion orientation = Quaternion.identity; + if (bones != null) + { + orientation = AvatarSetupTool.AvatarComputeOrientation(bones); + } + AvatarSkeletonDrawer.DrawSkeletonSubTree(actualBones, bones, orientation, reference, bounds); + Camera current = Camera.current; + if (AvatarSkeletonDrawer.sPoseError && current != null) + { + GUIStyle gUIStyle = new GUIStyle(GUI.skin.label); + gUIStyle.normal.textColor = Color.red; + gUIStyle.wordWrap = false; + gUIStyle.alignment = TextAnchor.MiddleLeft; + gUIStyle.fontSize = 20; + GUIContent content = new GUIContent("Character is not in T pose"); + Rect rect = GUILayoutUtility.GetRect(content, gUIStyle); + rect.x = 30f; + rect.y = 30f; + Handles.BeginGUI(); + GUI.Label(rect, content, gUIStyle); + Handles.EndGUI(); + } + } + private static bool DrawSkeletonSubTree(Dictionary actualBones, AvatarSetupTool.BoneWrapper[] bones, Quaternion orientation, Transform tr, Bounds bounds) + { + if (!actualBones.ContainsKey(tr)) + { + return false; + } + int num = 0; + foreach (Transform tr2 in tr) + { + if (AvatarSkeletonDrawer.DrawSkeletonSubTree(actualBones, bones, orientation, tr2, bounds)) + { + num++; + } + } + if (!actualBones[tr] && num <= 1) + { + return false; + } + int num2 = -1; + if (bones != null) + { + for (int i = 0; i < bones.Length; i++) + { + if (bones[i].bone == tr) + { + num2 = i; + break; + } + } + } + bool flag = AvatarSetupTool.GetBoneAlignmentError(bones, orientation, num2) > 0f; + AvatarSkeletonDrawer.sPoseError |= flag; + if (flag) + { + AvatarSkeletonDrawer.DrawPoseError(tr, bounds); + Handles.color = AvatarSkeletonDrawer.kErrorColor; + } + else + { + if (num2 != -1) + { + Handles.color = AvatarSkeletonDrawer.kHumanColor; + } + else + { + if (!actualBones[tr]) + { + Handles.color = AvatarSkeletonDrawer.kDummyColor; + } + else + { + Handles.color = AvatarSkeletonDrawer.kSkeletonColor; + } + } + } + Handles.DoBoneHandle(tr, actualBones); + if (Selection.activeObject == tr) + { + Handles.color = AvatarSkeletonDrawer.kSelectedColor; + Handles.DoBoneHandle(tr, actualBones); + } + return true; + } + private static void DrawPoseError(Transform node, Bounds bounds) + { + Camera current = Camera.current; + if (current) + { + GUIStyle gUIStyle = new GUIStyle(GUI.skin.label); + gUIStyle.normal.textColor = Color.red; + gUIStyle.wordWrap = false; + gUIStyle.alignment = TextAnchor.MiddleLeft; + Vector3 position = node.position; + Vector3 vector = node.position + Vector3.up * 0.2f; + if (node.position.x <= node.root.position.x) + { + vector.x = bounds.min.x; + } + else + { + vector.x = bounds.max.x; + } + GUIContent content = new GUIContent(node.name); + Rect position2 = HandleUtility.WorldPointToSizedRect(vector, content, gUIStyle); + position2.x += 2f; + if (node.position.x > node.root.position.x) + { + position2.x -= position2.width; + } + Handles.BeginGUI(); + position2.y -= gUIStyle.CalcSize(content).y / 4f; + GUI.Label(position2, content, gUIStyle); + Handles.EndGUI(); + Handles.color = AvatarSkeletonDrawer.kErrorMessageColor; + Handles.DrawLine(position, vector); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarSubEditor.cs b/UnityEditor/UnityEditor/AvatarSubEditor.cs new file mode 100644 index 00000000..359b0952 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarSubEditor.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class AvatarSubEditor : ScriptableObject + { + protected AvatarEditor m_Inspector; + protected GameObject gameObject + { + get + { + return this.m_Inspector.m_GameObject; + } + } + protected GameObject prefab + { + get + { + return this.m_Inspector.prefab; + } + } + protected Dictionary modelBones + { + get + { + return this.m_Inspector.m_ModelBones; + } + } + protected Transform root + { + get + { + return (!(this.gameObject == null)) ? this.gameObject.transform : null; + } + } + protected SerializedObject serializedObject + { + get + { + return this.m_Inspector.serializedObject; + } + } + protected Avatar avatarAsset + { + get + { + return this.m_Inspector.avatar; + } + } + private static void DoWriteAllAssets() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(UnityEngine.Object)); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + UnityEngine.Object @object = array2[i]; + if (AssetDatabase.Contains(@object)) + { + EditorUtility.SetDirty(@object); + } + } + EditorApplication.SaveAssets(); + } + public virtual void Enable(AvatarEditor inspector) + { + this.m_Inspector = inspector; + } + public virtual void OnDestroy() + { + if (this.HasModified()) + { + AssetImporter atPath = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.avatarAsset)); + if (atPath) + { + if (EditorUtility.DisplayDialog("Unapplied import settings", "Unapplied import settings for '" + atPath.assetPath + "'", "Apply", "Revert")) + { + this.ApplyAndImport(); + } + else + { + this.ResetValues(); + } + } + } + } + public virtual void OnInspectorGUI() + { + } + public virtual void OnSceneGUI() + { + } + protected bool HasModified() + { + return this.serializedObject.hasModifiedProperties; + } + protected virtual void ResetValues() + { + this.serializedObject.Update(); + } + protected void Apply() + { + this.serializedObject.ApplyModifiedProperties(); + } + public void ApplyAndImport() + { + this.Apply(); + string assetPath = AssetDatabase.GetAssetPath(this.avatarAsset); + AssetDatabase.ImportAsset(assetPath); + this.ResetValues(); + } + protected void ApplyRevertGUI() + { + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!this.HasModified()); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Revert", new GUILayoutOption[0])) + { + this.ResetValues(); + if (this.HasModified()) + { + Debug.LogError("Avatar tool reports modified values after reset."); + } + } + if (GUILayout.Button("Apply", new GUILayoutOption[0])) + { + this.ApplyAndImport(); + } + EditorGUI.EndDisabledGroup(); + if (GUILayout.Button("Done", new GUILayoutOption[0])) + { + this.m_Inspector.SwitchToAssetMode(); + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + } + } +} diff --git a/UnityEditor/UnityEditor/AvatarUtility.cs b/UnityEditor/UnityEditor/AvatarUtility.cs new file mode 100644 index 00000000..e32594c2 --- /dev/null +++ b/UnityEditor/UnityEditor/AvatarUtility.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class AvatarUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetHumanPose(Animator animator, float[] dof); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void HumanGetColliderTransform(Avatar avatar, int index, TransformX boneX, out TransformX colliderX); + } +} diff --git a/UnityEditor/UnityEditor/BaseHierarchySort.cs b/UnityEditor/UnityEditor/BaseHierarchySort.cs new file mode 100644 index 00000000..0ce313ad --- /dev/null +++ b/UnityEditor/UnityEditor/BaseHierarchySort.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + public abstract class BaseHierarchySort : IComparer + { + public virtual GUIContent content + { + get + { + return null; + } + } + public virtual int Compare(GameObject lhs, GameObject rhs) + { + return 0; + } + } +} diff --git a/UnityEditor/UnityEditor/BaseProjectWindow.cs b/UnityEditor/UnityEditor/BaseProjectWindow.cs new file mode 100644 index 00000000..817fc6c3 --- /dev/null +++ b/UnityEditor/UnityEditor/BaseProjectWindow.cs @@ -0,0 +1,1997 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEditor.ProjectWindowCallback; +using UnityEditorInternal; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class BaseProjectWindow : SearchableEditorWindow + { + private class DropData + { + public int[] expandedArrayBeforeDrag; + public int lastControlID; + public int dropOnControlID; + public int dropPreviousControlID; + public double expandItemBeginTimer; + } + internal class Styles + { + public GUIStyle foldout = "IN Foldout"; + public GUIStyle insertion = "PR Insertion"; + public GUIStyle label = "PR Label"; + public GUIStyle hiLabel = "HI Label"; + public GUIStyle ping = "PR Ping"; + } + private enum NameEditMode + { + None, + Found, + Renaming, + PreImportNaming + } + private const double kDropExpandTimeout = 0.7; + private const float kFoldoutSize = 14f; + private const float kIndent = 16f; + private const float kBaseIndent = 17f; + private static float m_RowHeight = 16f; + private static float m_DropNextToAreaHeight = 6f; + [SerializeField] + private int[] m_ExpandedArray = new int[0]; + private bool m_ProjectViewInternalSelectionChange; + public Vector2 m_ScrollPosition; + public Vector2 m_ScrollPositionFiltered; + [NonSerialized] + private Rect m_ScreenRect; + private PingData m_Ping = new PingData(); + private float m_FocusTime; + private List m_CurrentDragSelectionIDs = new List(); + private BaseProjectWindow.DropData m_DropData; + private bool m_StillWantsNameEditing; + private static Color[] s_HierarchyColors = new Color[] + { + Color.black, + new Color(0f, 0.15f, 0.51f, 1f), + new Color(0.25f, 0.05f, 0.05f, 1f), + Color.black, + Color.white, + new Color(0.67f, 0.76f, 1f), + new Color(1f, 0.71f, 0.71f, 1f), + Color.white + }; + private static Color[] s_DarkColors = new Color[] + { + new Color(0.705f, 0.705f, 0.705f, 1f), + new Color(0.3f, 0.5f, 0.85f, 1f), + new Color(0.7f, 0.4f, 0.4f, 1f), + new Color(0.705f, 0.705f, 0.705f, 1f), + Color.white, + new Color(0.67f, 0.76f, 1f), + new Color(1f, 0.71f, 0.71f, 1f), + Color.white + }; + private Rect m_NameEditRect = new Rect(0f, 0f, 1f, 1f); + private string m_NameEditString = string.Empty; + private int m_EditNameInstanceID; + private BaseProjectWindow.NameEditMode m_RealEditNameMode; + private EndNameEditAction m_EndNameEditAction; + private string m_NewAssetFolder; + private string m_NewAssetName; + private Texture2D m_NewAssetIcon; + private string m_NewAssetExtension; + private int m_NewAssetIndent; + private int m_NewAssetSortInstanceID; + private string m_NewAssetResourceFile; + private bool m_DidSelectSearchResult; + private bool m_NeedsRelayout; + private int m_FrameAfterRelayout; + private FilteredHierarchy m_FilteredHierarchy; + private static BaseProjectWindow.Styles ms_Styles; + private float IconWidth + { + get + { + return (float)((this.m_HierarchyType != HierarchyType.Assets) ? -3 : 14); + } + } + private BaseProjectWindow.NameEditMode m_EditNameMode + { + get + { + return this.m_RealEditNameMode; + } + set + { + if (value == this.m_RealEditNameMode) + { + return; + } + this.m_RealEditNameMode = value; + } + } + private GUIStyle labelStyle + { + get + { + return (this.m_HierarchyType != HierarchyType.Assets) ? BaseProjectWindow.ms_Styles.hiLabel : BaseProjectWindow.ms_Styles.label; + } + } + public IHierarchyProperty GetNewHierarchyProperty() + { + if (this.m_FilteredHierarchy == null) + { + this.m_FilteredHierarchy = new FilteredHierarchy(this.m_HierarchyType); + this.m_FilteredHierarchy.searchFilter = SearchableEditorWindow.CreateFilter(this.m_SearchFilter, this.m_SearchMode); + } + return FilteredHierarchyProperty.CreateHierarchyPropertyForFilter(this.m_FilteredHierarchy); + } + private void SetExpanded(int instanceID, bool expand) + { + Hashtable hashtable = new Hashtable(); + for (int i = 0; i < this.m_ExpandedArray.Length; i++) + { + hashtable.Add(this.m_ExpandedArray[i], null); + } + if (expand != hashtable.Contains(instanceID)) + { + if (expand) + { + hashtable.Add(instanceID, null); + } + else + { + hashtable.Remove(instanceID); + } + this.m_ExpandedArray = new int[hashtable.Count]; + int num = 0; + foreach (int num2 in hashtable.Keys) + { + this.m_ExpandedArray[num] = num2; + num++; + } + } + if (this.m_HierarchyType == HierarchyType.Assets) + { + InternalEditorUtility.expandedProjectWindowItems = this.m_ExpandedArray; + } + } + public void SetExpandedRecurse(int instanceID, bool expand) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + if (hierarchyProperty.Find(instanceID, this.m_ExpandedArray)) + { + this.SetExpanded(instanceID, expand); + int depth = hierarchyProperty.depth; + while (hierarchyProperty.Next(null) && hierarchyProperty.depth > depth) + { + this.SetExpanded(hierarchyProperty.instanceID, expand); + } + } + } + private void OnFocus() + { + this.m_FocusTime = Time.realtimeSinceStartup; + } + private void OnLostFocus() + { + this.m_StillWantsNameEditing = false; + this.EndNameEditing(); + } + public override void OnEnable() + { + base.OnEnable(); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + } + public override void OnDisable() + { + base.OnDisable(); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + } + private IHierarchyProperty GetFirstSelected() + { + int num = 1000000000; + IHierarchyProperty result = null; + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray) && newHierarchyProperty.row < num) + { + num = newHierarchyProperty.row; + result = newHierarchyProperty; + } + } + return result; + } + private void OnProjectChange() + { + if (this.m_HierarchyType == HierarchyType.Assets) + { + this.CancelNameEditing(); + if (this.m_FilteredHierarchy != null) + { + this.m_FilteredHierarchy.ResultsChanged(); + } + base.Repaint(); + } + } + private void OnSelectionChange() + { + if (Selection.activeInstanceID != this.m_EditNameInstanceID) + { + this.EndNameEditing(); + } + this.m_StillWantsNameEditing = false; + this.RevealObjects(Selection.instanceIDs); + if (this.m_ProjectViewInternalSelectionChange) + { + this.m_ProjectViewInternalSelectionChange = false; + } + else + { + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + this.FrameObject(Selection.activeInstanceID); + } + } + base.Repaint(); + } + private void OnHierarchyChange() + { + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + this.EndNameEditing(); + if (this.m_FilteredHierarchy != null) + { + this.m_FilteredHierarchy.ResultsChanged(); + } + base.Repaint(); + } + } + private IHierarchyProperty GetLastSelected() + { + int num = -1; + IHierarchyProperty result = null; + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray) && newHierarchyProperty.row > num) + { + num = newHierarchyProperty.row; + result = newHierarchyProperty; + } + } + return result; + } + private IHierarchyProperty GetActiveSelected() + { + return this.GetFirstSelected(); + } + private IHierarchyProperty GetLast() + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + int num = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); + if (num == 0) + { + return null; + } + newHierarchyProperty.Reset(); + if (newHierarchyProperty.Skip(num, this.m_ExpandedArray)) + { + return newHierarchyProperty; + } + return null; + } + private IHierarchyProperty GetFirst() + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Next(this.m_ExpandedArray)) + { + return newHierarchyProperty; + } + return null; + } + private void OpenAssetSelection() + { + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + if (AssetDatabase.Contains(instanceID)) + { + AssetDatabase.OpenAsset(instanceID); + } + } + } + internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + { + int num = 0; + if (this.m_DidSelectSearchResult && this.GetFirstSelected() != null) + { + num = this.GetFirstSelected().instanceID; + } + base.SetSearchFilter(searchFilter, searchMode, setAll); + if (this.m_FilteredHierarchy == null) + { + this.GetNewHierarchyProperty(); + } + this.m_FilteredHierarchy.searchFilter = SearchableEditorWindow.CreateFilter(searchFilter, searchMode); + if (this.m_DidSelectSearchResult) + { + if (searchFilter == string.Empty) + { + this.m_DidSelectSearchResult = false; + this.m_NeedsRelayout = true; + } + if (num != 0) + { + this.FrameObject(num, false); + } + } + } + internal override void ClickedSearchField() + { + this.EndNameEditing(); + } + private void ProjectWindowTitle() + { + GUILayout.BeginHorizontal("Toolbar", new GUILayoutOption[0]); + if (this.m_HierarchyType == HierarchyType.Assets) + { + this.CreateAssetPopup(); + GUILayout.Space(6f); + } + else + { + this.CreateGameObjectPopup(); + GUILayout.Space(6f); + } + if (this.m_FilteredHierarchy == null) + { + this.GetNewHierarchyProperty(); + } + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + if (Event.current.GetTypeForControl(controlID) == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + case KeyCode.UpArrow: + case KeyCode.DownArrow: + goto IL_C2; + case KeyCode.KeypadEquals: + IL_9F: + if (keyCode != KeyCode.Return) + { + goto IL_C8; + } + goto IL_C2; + case KeyCode.RightArrow: + case KeyCode.LeftArrow: + if (!base.hasSearchFilter) + { + EditorGUILayout.EndHorizontal(); + return; + } + goto IL_C8; + } + goto IL_9F; + IL_C2: + EditorGUILayout.EndHorizontal(); + return; + } + IL_C8: + GUILayout.FlexibleSpace(); + base.SearchFieldGUI(); + GUILayout.EndHorizontal(); + } + private void SearchResultPathGUI() + { + if (!base.hasSearchFilter) + { + return; + } + EditorGUILayout.BeginVertical(EditorStyles.inspectorBig, new GUILayoutOption[0]); + GUILayout.Label("Path:", new GUILayoutOption[0]); + IHierarchyProperty activeSelected = this.GetActiveSelected(); + if (activeSelected != null) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + hierarchyProperty.Find(activeSelected.instanceID, null); + do + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(hierarchyProperty.icon, new GUILayoutOption[0]); + GUILayout.Label(hierarchyProperty.name, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + } + while (hierarchyProperty.Parent()); + } + EditorGUILayout.EndVertical(); + GUILayout.Space(0f); + } + private void OnGUI() + { + if (BaseProjectWindow.ms_Styles == null) + { + BaseProjectWindow.ms_Styles = new BaseProjectWindow.Styles(); + } + this.ProjectWindowTitle(); + Rect rect = GUILayoutUtility.GetRect(0f, (float)Screen.width, 0f, (float)Screen.height); + if (this.m_HierarchyType == HierarchyType.Assets && AssetDatabase.isLocked) + { + Debug.LogError("Repainting while performing asset operations!"); + GUILayout.Label("Performing Asset operations", new GUILayoutOption[0]); + return; + } + this.m_ScreenRect = rect; + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + this.HierarchyView(); + this.SearchResultPathGUI(); + EditorGUIUtility.SetIconSize(Vector2.zero); + if (Event.current.type == EventType.Repaint && this.m_NeedsRelayout) + { + this.m_NeedsRelayout = false; + if (this.m_FrameAfterRelayout != 0) + { + this.FrameObject(this.m_FrameAfterRelayout); + this.m_FrameAfterRelayout = 0; + } + } + } + private void EndNameEditing() + { + BaseProjectWindow.NameEditMode editNameMode = this.m_EditNameMode; + if (editNameMode == BaseProjectWindow.NameEditMode.Renaming) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + ObjectNames.SetNameSmartWithInstanceID(this.m_EditNameInstanceID, this.m_NameEditString); + return; + } + if (editNameMode != BaseProjectWindow.NameEditMode.PreImportNaming) + { + return; + } + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + if (this.m_NameEditString == string.Empty) + { + this.m_NameEditString = this.m_NewAssetName; + } + ProjectWindowUtil.EndNameEditAction(this.m_EndNameEditAction, this.m_EditNameInstanceID, this.m_NewAssetFolder + "/" + this.m_NameEditString + this.m_NewAssetExtension, this.m_NewAssetResourceFile); + this.m_EndNameEditAction = null; + } + private void CancelNameEditing() + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + this.m_EndNameEditAction = null; + } + private void BeginNameEditing(int instanceID) + { + if (this.NamingAsset()) + { + this.EndNameEditing(); + } + if (base.hasSearchFilter) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + return; + } + IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + hierarchyProperty.Find(instanceID, null); + if (hierarchyProperty.isValid) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.Renaming; + this.m_EditNameInstanceID = instanceID; + EditorGUI.s_RecycledEditor.content.text = hierarchyProperty.name; + EditorGUI.s_RecycledEditor.SelectAll(); + } + else + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + } + } + private void OnPlayModeStateChanged() + { + this.EndNameEditing(); + } + internal void BeginPreimportedNameEditing(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile) + { + if (this.NamingAsset()) + { + this.EndNameEditing(); + } + this.m_EndNameEditAction = endAction; + if (!pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) + { + pathName = AssetDatabase.GetUniquePathNameAtSelectedPath(pathName); + } + else + { + pathName = AssetDatabase.GenerateUniqueAssetPath(pathName); + } + this.m_NewAssetFolder = Path.GetDirectoryName(pathName); + this.m_NewAssetIcon = icon; + this.m_NewAssetName = Path.GetFileNameWithoutExtension(pathName); + this.m_NewAssetExtension = Path.GetExtension(pathName); + this.m_NewAssetIndent = 0; + this.m_NewAssetSortInstanceID = 0; + this.m_NewAssetResourceFile = resourceFile; + Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); + if (base.hasSearchFilter) + { + this.m_SearchFilter = string.Empty; + this.m_SearchMode = SearchableEditorWindow.SearchMode.All; + } + int instanceID2 = AssetDatabase.LoadAssetAtPath(this.m_NewAssetFolder, typeof(UnityEngine.Object)).GetInstanceID(); + this.RevealObject(instanceID2); + this.SetExpanded(instanceID2, true); + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + newHierarchyProperty.Reset(); + float num = 0f; + if (!this.m_NewAssetFolder.Equals("assets", StringComparison.CurrentCultureIgnoreCase)) + { + while (newHierarchyProperty.Next(this.m_ExpandedArray)) + { + string assetPath = AssetDatabase.GetAssetPath(newHierarchyProperty.instanceID); + num += BaseProjectWindow.m_RowHeight; + if (string.Equals(assetPath, this.m_NewAssetFolder, StringComparison.CurrentCultureIgnoreCase)) + { + num = this.FindPositionInsideDir(newHierarchyProperty, num); + break; + } + } + } + else + { + num = this.FindPositionInsideDir(newHierarchyProperty, num); + } + float left = 17f + 16f * (float)this.m_NewAssetIndent + this.IconWidth; + this.m_NameEditRect = new Rect(left, num, 100f, BaseProjectWindow.m_RowHeight); + float num2 = num; + float min = num2 - base.position.height + 20f + BaseProjectWindow.m_RowHeight; + this.m_ScrollPosition.y = Mathf.Clamp(this.m_ScrollPosition.y, min, num2); + this.m_EditNameMode = BaseProjectWindow.NameEditMode.PreImportNaming; + this.m_EditNameInstanceID = instanceID; + EditorGUI.s_RecycledEditor.content.text = (this.m_NameEditString = this.m_NewAssetName); + EditorGUI.s_RecycledEditor.SelectAll(); + } + private float FindPositionInsideDir(IHierarchyProperty property, float yPos) + { + this.m_NewAssetIndent = property.depth + 1; + string text = this.m_NewAssetFolder + "/"; + while (property.Next(this.m_ExpandedArray)) + { + string assetPath = AssetDatabase.GetAssetPath(property.instanceID); + string text2 = assetPath + "/"; + if (text2.Length < text.Length || !text2.Substring(0, text.Length).Equals(text, StringComparison.CurrentCultureIgnoreCase)) + { + this.m_NewAssetSortInstanceID = property.instanceID; + break; + } + if (this.m_NewAssetFolder.Equals(Path.GetDirectoryName(assetPath), StringComparison.CurrentCultureIgnoreCase) && EditorUtility.NaturalCompare(Path.GetFileNameWithoutExtension(assetPath), this.m_NewAssetName) > 0) + { + this.m_NewAssetIndent = property.depth; + this.m_NewAssetSortInstanceID = property.instanceID; + break; + } + yPos += BaseProjectWindow.m_RowHeight; + } + return yPos; + } + private bool NamingAsset() + { + return this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming || this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming; + } + private void EditName() + { + if (!this.NamingAsset()) + { + return; + } + Event current = Event.current; + if (current.type == EventType.KeyDown) + { + if (current.keyCode == KeyCode.Escape) + { + current.Use(); + this.CancelNameEditing(); + } + if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) + { + current.Use(); + this.EndNameEditing(); + GUIUtility.ExitGUI(); + } + } + GUI.changed = false; + GUIUtility.GetControlID(67897456, FocusType.Passive); + GUI.SetNextControlName("ProjectWindowRenameField"); + EditorGUI.FocusTextInControl("ProjectWindowRenameField"); + GUIStyle textField = EditorStyles.textField; + EditorStyles.s_Current.m_TextField = "PR TextField"; + this.m_NameEditRect.xMax = GUIClip.visibleRect.width; + Rect nameEditRect = this.m_NameEditRect; + this.m_NameEditString = EditorGUI.TextField(nameEditRect, this.m_NameEditString); + EditorStyles.s_Current.m_TextField = textField; + if (current.type == EventType.ScrollWheel) + { + current.Use(); + } + } + private void HierarchyView() + { + if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.KeyDown) + { + this.m_StillWantsNameEditing = false; + } + bool hasFocus = this.m_Parent.hasFocus; + Hashtable hashtable = new Hashtable(); + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int num = instanceIDs[i]; + hashtable.Add(num, null); + } + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + int num2 = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); + newHierarchyProperty.Reset(); + Rect viewRect = new Rect(0f, 0f, 1f, (float)num2 * BaseProjectWindow.m_RowHeight); + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming) + { + viewRect.height += BaseProjectWindow.m_RowHeight; + } + int num3; + if (base.hasSearchFilter) + { + this.m_ScrollPositionFiltered = GUI.BeginScrollView(this.m_ScreenRect, this.m_ScrollPositionFiltered, viewRect); + num3 = Mathf.RoundToInt(this.m_ScrollPositionFiltered.y) / Mathf.RoundToInt(BaseProjectWindow.m_RowHeight); + } + else + { + this.m_ScrollPosition = GUI.BeginScrollView(this.m_ScreenRect, this.m_ScrollPosition, viewRect); + num3 = Mathf.RoundToInt(this.m_ScrollPosition.y) / Mathf.RoundToInt(BaseProjectWindow.m_RowHeight); + } + this.EditName(); + if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) + { + this.ExecuteCommandGUI(); + if (Event.current.type == EventType.ValidateCommand) + { + GUI.EndScrollView(); + return; + } + } + this.KeyboardGUI(); + if (Event.current.type == EventType.Layout) + { + GUI.EndScrollView(); + return; + } + int num4 = this.ControlIDForProperty(null); + bool flag = false; + float num5 = (float)num3 * BaseProjectWindow.m_RowHeight; + float num6 = this.m_ScreenRect.height + num5 + 16f; + newHierarchyProperty.Skip(num3, this.m_ExpandedArray); + bool flag2 = false; + Rect position = new Rect(0f, 0f, 0f, 0f); + Vector2 mousePosition = Event.current.mousePosition; + GUIContent gUIContent = new GUIContent(); + Event current = Event.current; + int activeInstanceID = Selection.activeInstanceID; + if (!this.NamingAsset()) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; + } + GUIStyle labelStyle = this.labelStyle; + Color[] array = (!EditorGUIUtility.isProSkin) ? BaseProjectWindow.s_HierarchyColors : BaseProjectWindow.s_DarkColors; + while (newHierarchyProperty.Next(this.m_ExpandedArray) && num5 <= num6) + { + Rect rect = new Rect(0f, num5, GUIClip.visibleRect.width, BaseProjectWindow.m_RowHeight); + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming && !flag && newHierarchyProperty.instanceID == this.m_NewAssetSortInstanceID) + { + flag = true; + num5 += BaseProjectWindow.m_RowHeight; + rect = new Rect(0f, num5, GUIClip.visibleRect.width, BaseProjectWindow.m_RowHeight); + this.DrawPreImportedIcon(num5); + } + int instanceID = newHierarchyProperty.instanceID; + int num7 = this.ControlIDForProperty(newHierarchyProperty); + float num8 = 17f + 16f * (float)newHierarchyProperty.depth; + if ((current.type == EventType.MouseUp || current.type == EventType.KeyDown) && activeInstanceID == instanceID && Selection.instanceIDs.Length == 1) + { + this.m_NameEditString = newHierarchyProperty.name; + this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); + this.m_EditNameInstanceID = instanceID; + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.None && newHierarchyProperty.isMainRepresentation) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.Found; + } + } + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming && this.m_EditNameInstanceID == instanceID) + { + this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); + } + if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) + { + this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); + this.m_EditNameInstanceID = instanceID; + this.m_NameEditString = newHierarchyProperty.name; + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.None && newHierarchyProperty.isMainRepresentation) + { + this.m_EditNameMode = BaseProjectWindow.NameEditMode.Found; + } + } + if (Event.current.type == EventType.Repaint) + { + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + int colorCode = newHierarchyProperty.colorCode; + Color textColor = array[colorCode & 3]; + Color textColor2 = array[(colorCode & 3) + 4]; + if (colorCode >= 4) + { + textColor.a = (textColor2.a = 0.6f); + } + else + { + textColor.a = (textColor2.a = 1f); + } + labelStyle.normal.textColor = textColor; + labelStyle.focused.textColor = textColor; + labelStyle.hover.textColor = textColor; + labelStyle.active.textColor = textColor; + labelStyle.onNormal.textColor = textColor2; + labelStyle.onHover.textColor = textColor2; + labelStyle.onActive.textColor = textColor2; + labelStyle.onFocused.textColor = textColor2; + } + bool flag3 = this.m_DropData != null && this.m_DropData.dropPreviousControlID == num7; + bool flag4 = this.m_DropData != null && this.m_DropData.dropOnControlID == num7; + gUIContent.text = newHierarchyProperty.name; + gUIContent.image = newHierarchyProperty.icon; + labelStyle.padding.left = (int)num8; + bool flag5 = this.m_CurrentDragSelectionIDs.Contains(instanceID); + bool on = (this.m_CurrentDragSelectionIDs.Count == 0 && hashtable.Contains(instanceID)) || flag5 || (flag5 && (current.control || current.shift) && hashtable.Contains(instanceID)) || (flag5 && hashtable.Contains(instanceID) && hashtable.Contains(this.m_CurrentDragSelectionIDs)); + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming && instanceID == this.m_EditNameInstanceID) + { + gUIContent.text = string.Empty; + on = false; + } + labelStyle.Draw(rect, gUIContent, flag4, flag4, on, hasFocus); + if (flag3) + { + flag2 = true; + position = new Rect(rect.x + num8, rect.y - BaseProjectWindow.m_RowHeight, rect.width - num8, rect.height); + } + } + Rect rect2 = rect; + rect2.x += num8; + rect2.width -= num8; + if (this.m_HierarchyType == HierarchyType.Assets) + { + ProjectHooks.OnProjectWindowItem(newHierarchyProperty.guid, rect2); + if (EditorApplication.projectWindowItemOnGUI != null) + { + EditorApplication.projectWindowItemOnGUI(newHierarchyProperty.guid, rect2); + } + } + if (this.m_HierarchyType == HierarchyType.GameObjects && EditorApplication.hierarchyWindowItemOnGUI != null) + { + EditorApplication.hierarchyWindowItemOnGUI(newHierarchyProperty.instanceID, rect2); + } + if (newHierarchyProperty.hasChildren && !base.hasSearchFilter) + { + bool flag6 = newHierarchyProperty.IsExpanded(this.m_ExpandedArray); + GUI.changed = false; + Rect position2 = new Rect(17f + 16f * (float)newHierarchyProperty.depth - 14f, num5, 14f, BaseProjectWindow.m_RowHeight); + flag6 = GUI.Toggle(position2, flag6, GUIContent.none, BaseProjectWindow.ms_Styles.foldout); + if (GUI.changed) + { + this.EndNameEditing(); + if (Event.current.alt) + { + this.SetExpandedRecurse(instanceID, flag6); + } + else + { + this.SetExpanded(instanceID, flag6); + } + } + } + if (current.type == EventType.MouseDown && Event.current.button == 0 && rect.Contains(Event.current.mousePosition)) + { + if (Event.current.clickCount == 2) + { + AssetDatabase.OpenAsset(instanceID); + if (this.m_HierarchyType != HierarchyType.Assets && SceneView.lastActiveSceneView != null) + { + SceneView.lastActiveSceneView.FrameSelected(); + } + GUIUtility.ExitGUI(); + } + else + { + this.EndNameEditing(); + this.m_CurrentDragSelectionIDs = this.GetSelection(newHierarchyProperty, true); + GUIUtility.hotControl = num7; + GUIUtility.keyboardControl = 0; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), num7); + dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; + } + current.Use(); + } + else + { + if (current.type == EventType.MouseDrag && GUIUtility.hotControl == num7) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), num7); + if (dragAndDropDelay2.CanStartDrag()) + { + this.StartDrag(newHierarchyProperty); + GUIUtility.hotControl = 0; + } + current.Use(); + } + else + { + if (current.type == EventType.MouseUp && GUIUtility.hotControl == num7) + { + if (rect.Contains(current.mousePosition)) + { + if (newHierarchyProperty.isMainRepresentation && Selection.activeInstanceID == newHierarchyProperty.instanceID && Time.realtimeSinceStartup - this.m_FocusTime > 0.5f && !EditorGUIUtility.HasHolddownKeyModifiers(current)) + { + this.m_StillWantsNameEditing = true; + EditorApplication.CallDelayed(new EditorApplication.CallbackFunction(this.BeginMouseEditing), 0.5f); + } + else + { + this.SelectionClick(newHierarchyProperty); + } + GUIUtility.hotControl = 0; + } + this.m_CurrentDragSelectionIDs.Clear(); + current.Use(); + } + else + { + if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) + { + current.Use(); + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + this.SelectionClickContextMenu(newHierarchyProperty); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupCopy"), false, new GenericMenu.MenuFunction(this.CopyGO)); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupPaste"), false, new GenericMenu.MenuFunction(this.PasteGO)); + genericMenu.AddSeparator(string.Empty); + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Found && !base.hasSearchFilter) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupRename"), false, new GenericMenu.MenuFunction2(this.RenameGO), newHierarchyProperty.pptrValue); + } + else + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupRename")); + } + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDuplicate"), false, new GenericMenu.MenuFunction(this.DuplicateGO)); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDelete"), false, new GenericMenu.MenuFunction(this.DeleteGO)); + genericMenu.AddSeparator(string.Empty); + UnityEngine.Object prefab = PrefabUtility.GetPrefabParent(newHierarchyProperty.pptrValue); + if (prefab != null) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab"), false, delegate + { + Selection.activeObject = prefab; + EditorGUIUtility.PingObject(prefab.GetInstanceID()); + }); + } + else + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab")); + } + genericMenu.ShowAsContext(); + } + } + else + { + if (current.type == EventType.DragUpdated || current.type == EventType.DragPerform) + { + Rect rect3 = rect; + rect3.yMin -= BaseProjectWindow.m_DropNextToAreaHeight * 2f; + if (rect3.Contains(mousePosition)) + { + if (mousePosition.y - rect.y < BaseProjectWindow.m_DropNextToAreaHeight * 0.5f) + { + this.DragElement(newHierarchyProperty, false); + } + else + { + this.DragElement(newHierarchyProperty, true); + } + GUIUtility.hotControl = 0; + } + } + } + } + } + } + num5 += BaseProjectWindow.m_RowHeight; + } + if (flag2) + { + GUIStyle insertion = BaseProjectWindow.ms_Styles.insertion; + if (current.type == EventType.Repaint) + { + insertion.Draw(position, false, false, false, false); + } + } + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming && this.m_NewAssetSortInstanceID == 0) + { + this.DrawPreImportedIcon(num5 + 16f); + } + this.HandlePing(); + GUI.EndScrollView(); + EventType type = current.type; + switch (type) + { + case EventType.DragUpdated: + if (this.m_SearchFilter == string.Empty) + { + this.DragElement(null, true); + } + else + { + if (this.m_DropData == null) + { + this.m_DropData = new BaseProjectWindow.DropData(); + } + this.m_DropData.dropOnControlID = 0; + this.m_DropData.dropPreviousControlID = 0; + } + return; + case EventType.DragPerform: + this.m_CurrentDragSelectionIDs.Clear(); + this.DragElement(null, true); + return; + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + IL_CB2: + switch (type) + { + case EventType.MouseDown: + if (current.button == 0 && this.m_ScreenRect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = num4; + Selection.activeObject = null; + this.EndNameEditing(); + current.Use(); + } + return; + case EventType.MouseUp: + if (GUIUtility.hotControl == num4) + { + GUIUtility.hotControl = 0; + current.Use(); + } + return; + case EventType.MouseMove: + case EventType.MouseDrag: + return; + case EventType.KeyDown: + if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Found && (((current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) && Application.platform == RuntimePlatform.OSXEditor) || (current.keyCode == KeyCode.F2 && Application.platform == RuntimePlatform.WindowsEditor))) + { + this.BeginNameEditing(Selection.activeInstanceID); + current.Use(); + } + return; + default: + return; + } + break; + case EventType.DragExited: + this.m_CurrentDragSelectionIDs.Clear(); + this.DragCleanup(true); + return; + case EventType.ContextClick: + if (this.m_HierarchyType == HierarchyType.Assets && this.m_ScreenRect.Contains(current.mousePosition)) + { + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/", null); + current.Use(); + } + return; + } + goto IL_CB2; + } + private void HandlePing() + { + this.m_Ping.HandlePing(); + if (this.m_Ping.isPinging) + { + base.Repaint(); + } + } + private void DrawPreImportedIcon(float offset) + { + if (Event.current.type == EventType.Repaint && this.m_NewAssetIcon) + { + BaseProjectWindow.ms_Styles.label.padding.left = 0; + BaseProjectWindow.ms_Styles.label.Draw(new Rect((float)(this.m_NewAssetIndent * 16) + 17f, offset - 16f, 16f, 16f), EditorGUIUtility.TempContent(this.m_NewAssetIcon), 0); + } + } + private void CopyGO() + { + Unsupported.CopyGameObjectsToPasteboard(); + } + private void PasteGO() + { + Unsupported.PasteGameObjectsFromPasteboard(); + } + private void DuplicateGO() + { + Unsupported.DuplicateGameObjectsUsingPasteboard(); + } + private void RenameGO(object obj) + { + GameObject activeObject = (GameObject)obj; + Selection.activeObject = activeObject; + this.BeginNameEditing(Selection.activeInstanceID); + base.Repaint(); + } + private void DeleteGO() + { + Unsupported.DeleteGameObjectSelection(); + } + private void BeginMouseEditing() + { + if (this.m_StillWantsNameEditing) + { + this.BeginNameEditing(Selection.activeInstanceID); + } + base.Repaint(); + } + private void StartDrag(IHierarchyProperty property) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = this.GetDragAndDropObjects(property.pptrValue); + DragAndDrop.paths = this.GetDragAndDropPaths(property.instanceID); + if (DragAndDrop.objectReferences.Length > 1) + { + DragAndDrop.StartDrag(""); + } + else + { + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(property.pptrValue)); + } + } + private void DragCleanup(bool revertExpanded) + { + if (this.m_DropData != null) + { + if (this.m_DropData.expandedArrayBeforeDrag != null && revertExpanded) + { + this.m_ExpandedArray = this.m_DropData.expandedArrayBeforeDrag; + } + this.m_DropData = null; + base.Repaint(); + } + } + private void DragElement(IHierarchyProperty property, bool dropOnTopOfElement) + { + if (Event.current.type == EventType.DragPerform) + { + IHierarchyProperty hierarchyProperty = property; + DragAndDropVisualMode dragAndDropVisualMode = DragAndDropVisualMode.None; + if (dropOnTopOfElement) + { + dragAndDropVisualMode = this.DoDrag(hierarchyProperty, true); + } + if (dragAndDropVisualMode == DragAndDropVisualMode.None && property != null) + { + hierarchyProperty = this.GetParentProperty(hierarchyProperty); + dragAndDropVisualMode = this.DoDrag(hierarchyProperty, true); + } + if (dragAndDropVisualMode != DragAndDropVisualMode.None) + { + DragAndDrop.AcceptDrag(); + this.DragCleanup(false); + ArrayList arrayList = new ArrayList(); + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + for (int i = 0; i < objectReferences.Length; i++) + { + UnityEngine.Object @object = objectReferences[i]; + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty != null && @object != null && newHierarchyProperty.Find(@object.GetInstanceID(), null)) + { + IHierarchyProperty parentProperty = this.GetParentProperty(newHierarchyProperty); + if (parentProperty != null && (hierarchyProperty == null || parentProperty.pptrValue == hierarchyProperty.pptrValue)) + { + arrayList.Add(@object); + } + } + } + if (arrayList.Count > 0) + { + Selection.objects = (UnityEngine.Object[])arrayList.ToArray(typeof(UnityEngine.Object)); + this.RevealObjects(Selection.instanceIDs); + this.FrameObject(Selection.activeInstanceID); + } + GUIUtility.ExitGUI(); + } + else + { + this.DragCleanup(true); + } + } + else + { + if (this.m_DropData == null) + { + this.m_DropData = new BaseProjectWindow.DropData(); + } + this.m_DropData.dropOnControlID = 0; + this.m_DropData.dropPreviousControlID = 0; + int num = this.ControlIDForProperty(property); + if (num != this.m_DropData.lastControlID) + { + this.m_DropData.lastControlID = this.ControlIDForProperty(property); + this.m_DropData.expandItemBeginTimer = (double)Time.realtimeSinceStartup; + } + bool flag = (double)Time.realtimeSinceStartup - this.m_DropData.expandItemBeginTimer > 0.7; + if (property != null && property.hasChildren && flag && !property.IsExpanded(this.m_ExpandedArray)) + { + if (this.m_DropData.expandedArrayBeforeDrag == null) + { + this.m_DropData.expandedArrayBeforeDrag = this.m_ExpandedArray; + } + this.SetExpanded(property.instanceID, true); + } + DragAndDropVisualMode dragAndDropVisualMode2 = DragAndDropVisualMode.None; + if (dropOnTopOfElement) + { + dragAndDropVisualMode2 = this.DoDrag(property, false); + } + if (dragAndDropVisualMode2 != DragAndDropVisualMode.None) + { + this.m_DropData.dropOnControlID = num; + DragAndDrop.visualMode = dragAndDropVisualMode2; + } + else + { + if (property != null && this.m_SearchFilter == string.Empty) + { + IHierarchyProperty parentProperty2 = this.GetParentProperty(property); + dragAndDropVisualMode2 = this.DoDrag(parentProperty2, false); + if (dragAndDropVisualMode2 != DragAndDropVisualMode.None) + { + this.m_DropData.dropPreviousControlID = num; + this.m_DropData.dropOnControlID = this.ControlIDForProperty(parentProperty2); + DragAndDrop.visualMode = dragAndDropVisualMode2; + } + } + } + base.Repaint(); + } + Event.current.Use(); + } + private DragAndDropVisualMode DoDrag(IHierarchyProperty property, bool perform) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + if (property == null || !hierarchyProperty.Find(property.instanceID, null)) + { + hierarchyProperty = null; + } + if (this.HandleSpriteDragIntoHierarchy(property, perform)) + { + return DragAndDropVisualMode.Link; + } + if (this.m_HierarchyType == HierarchyType.Assets) + { + return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + } + return InternalEditorUtility.HierarchyWindowDrag(hierarchyProperty, perform, InternalEditorUtility.HierarchyDropMode.kHierarchyDragNormal); + } + private bool HandleSpriteDragIntoHierarchy(IHierarchyProperty property, bool perform) + { + Sprite[] spritesFromDraggedObjects = SpriteUtility.GetSpritesFromDraggedObjects(); + if (spritesFromDraggedObjects.Length == 1) + { + return SpriteUtility.HandleSingleSpriteDragIntoHierarchy(property, spritesFromDraggedObjects[0], perform); + } + return spritesFromDraggedObjects.Length > 1 && SpriteUtility.HandleMultipleSpritesDragIntoHierarchy(property, spritesFromDraggedObjects, perform); + } + private IHierarchyProperty GetPreviousParentProperty(IHierarchyProperty property) + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Find(property.instanceID, this.m_ExpandedArray) && newHierarchyProperty.Previous(this.m_ExpandedArray)) + { + return this.GetParentProperty(newHierarchyProperty); + } + return null; + } + private IHierarchyProperty GetParentProperty(IHierarchyProperty property) + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Find(property.instanceID, this.m_ExpandedArray) && newHierarchyProperty.Parent()) + { + int instanceID = newHierarchyProperty.instanceID; + newHierarchyProperty.Reset(); + if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray)) + { + return newHierarchyProperty; + } + } + return null; + } + private int ControlIDForProperty(IHierarchyProperty property) + { + if (property != null) + { + return property.instanceID + 10000000; + } + return -1; + } + private string[] GetDragAndDropPaths(int dragged) + { + string assetPath = AssetDatabase.GetAssetPath(dragged); + if (this.m_HierarchyType != HierarchyType.Assets) + { + return new string[0]; + } + ArrayList arrayList = new ArrayList(); + arrayList.AddRange(BaseProjectWindow.GetMainSelectedPaths()); + if (arrayList.Contains(assetPath)) + { + return arrayList.ToArray(typeof(string)) as string[]; + } + return new string[] + { + assetPath + }; + } + private UnityEngine.Object[] GetDragAndDropObjects(UnityEngine.Object dragged) + { + ArrayList arrayList = new ArrayList(); + arrayList.AddRange(this.GetSelectedReferences()); + if (arrayList.Contains(dragged)) + { + return arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]; + } + return new UnityEngine.Object[] + { + dragged + }; + } + private UnityEngine.Object[] GetSelectedReferences() + { + ArrayList arrayList = new ArrayList(); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + if (AssetDatabase.Contains(@object) != (this.m_HierarchyType == HierarchyType.GameObjects)) + { + arrayList.Add(@object); + } + } + return arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]; + } + private static string[] GetMainSelectedPaths() + { + ArrayList arrayList = new ArrayList(); + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + if (AssetDatabase.IsMainAsset(instanceID)) + { + string assetPath = AssetDatabase.GetAssetPath(instanceID); + arrayList.Add(assetPath); + } + } + return arrayList.ToArray(typeof(string)) as string[]; + } + private void ExecuteCommandGUIHierarchy() + { + bool flag = Event.current.type == EventType.ExecuteCommand; + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + if (flag) + { + Unsupported.DeleteGameObjectSelection(); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Duplicate") + { + if (flag) + { + Unsupported.DuplicateGameObjectsUsingPasteboard(); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Copy") + { + if (flag) + { + Unsupported.CopyGameObjectsToPasteboard(); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Paste") + { + if (flag) + { + Unsupported.PasteGameObjectsFromPasteboard(); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "SelectAll") + { + if (flag) + { + this.SelectAll(); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + } + } + } + } + } + internal static void DuplicateSelectedAssets() + { + AssetDatabase.Refresh(); + UnityEngine.Object[] objects = Selection.objects; + bool flag = true; + UnityEngine.Object[] array = objects; + for (int i = 0; i < array.Length; i++) + { + UnityEngine.Object @object = array[i]; + AnimationClip animationClip = @object as AnimationClip; + if (animationClip == null || (animationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None || !AssetDatabase.Contains(animationClip)) + { + flag = false; + } + } + ArrayList arrayList = new ArrayList(); + bool flag2 = false; + if (flag) + { + UnityEngine.Object[] array2 = objects; + for (int j = 0; j < array2.Length; j++) + { + UnityEngine.Object object2 = array2[j]; + AnimationClip animationClip2 = object2 as AnimationClip; + if (animationClip2 != null && (animationClip2.hideFlags & HideFlags.NotEditable) != HideFlags.None) + { + string path = AssetDatabase.GetAssetPath(object2); + path = Path.Combine(Path.GetDirectoryName(path), animationClip2.name) + ".anim"; + string text = AssetDatabase.GenerateUniqueAssetPath(path); + AnimationClip animationClip3 = new AnimationClip(); + EditorUtility.CopySerialized(animationClip2, animationClip3); + AssetDatabase.CreateAsset(animationClip3, text); + arrayList.Add(text); + } + } + } + else + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + UnityEngine.Object[] array3 = filtered; + for (int k = 0; k < array3.Length; k++) + { + UnityEngine.Object assetObject = array3[k]; + string assetPath = AssetDatabase.GetAssetPath(assetObject); + string text2 = AssetDatabase.GenerateUniqueAssetPath(assetPath); + if (text2.Length != 0) + { + flag2 |= !AssetDatabase.CopyAsset(assetPath, text2); + } + else + { + flag2 |= true; + } + if (!flag2) + { + arrayList.Add(text2); + } + } + } + AssetDatabase.Refresh(); + UnityEngine.Object[] array4 = new UnityEngine.Object[arrayList.Count]; + for (int l = 0; l < arrayList.Count; l++) + { + array4[l] = AssetDatabase.LoadMainAssetAtPath(arrayList[l] as string); + } + Selection.objects = array4; + } + private void ExecuteCommandGUIProject() + { + bool flag = Event.current.type == EventType.ExecuteCommand; + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + Event.current.Use(); + if (flag) + { + bool askIfSure = Event.current.commandName == "SoftDelete"; + BaseProjectWindow.DeleteSelectedAssets(askIfSure); + } + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Duplicate") + { + if (flag) + { + Event.current.Use(); + BaseProjectWindow.DuplicateSelectedAssets(); + GUIUtility.ExitGUI(); + } + else + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + if (filtered.Length != 0) + { + Event.current.Use(); + } + } + } + else + { + if (Event.current.commandName == "FocusProjectWindow") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.FrameObject(Selection.activeInstanceID); + Event.current.Use(); + base.Focus(); + GUIUtility.ExitGUI(); + } + else + { + Event.current.Use(); + } + } + else + { + if (Event.current.commandName == "SelectAll") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.SelectAll(); + } + Event.current.Use(); + } + } + } + } + } + internal static void DeleteSelectedAssets(bool askIfSure) + { + string[] mainSelectedPaths = BaseProjectWindow.GetMainSelectedPaths(); + if (mainSelectedPaths.Length == 0) + { + return; + } + if (askIfSure) + { + string text = "Delete selected asset"; + if (mainSelectedPaths.Length > 1) + { + text += "s"; + } + text += "?"; + if (!EditorUtility.DisplayDialog(text, "You cannot undo this action.", "Delete", "Cancel")) + { + return; + } + } + AssetDatabase.StartAssetEditing(); + string[] array = mainSelectedPaths; + for (int i = 0; i < array.Length; i++) + { + string path = array[i]; + AssetDatabase.MoveAssetToTrash(path); + } + AssetDatabase.StopAssetEditing(); + } + private void SelectAll() + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + List list = new List(); + while (newHierarchyProperty.Next(this.m_ExpandedArray)) + { + list.Add(newHierarchyProperty.instanceID); + } + Selection.instanceIDs = list.ToArray(); + } + internal void PingTargetObject(int targetInstanceID) + { + if (targetInstanceID == 0) + { + return; + } + if (BaseProjectWindow.ms_Styles == null) + { + BaseProjectWindow.ms_Styles = new BaseProjectWindow.Styles(); + } + if (this.FrameObject(targetInstanceID)) + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + int num = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); + IHierarchyProperty newHierarchyProperty2 = this.GetNewHierarchyProperty(); + if (newHierarchyProperty2.Find(targetInstanceID, this.m_ExpandedArray)) + { + int row = newHierarchyProperty2.row; + float top = BaseProjectWindow.m_RowHeight * (float)row; + this.m_Ping.m_TimeStart = Time.realtimeSinceStartup; + this.m_Ping.m_PingStyle = BaseProjectWindow.ms_Styles.ping; + float num2 = ((float)num * BaseProjectWindow.m_RowHeight <= this.m_ScreenRect.height) ? 0f : -16f; + this.m_Ping.m_AvailableWidth = base.position.width + num2; + GUIContent pingContent = new GUIContent(newHierarchyProperty2.name, newHierarchyProperty2.icon); + Vector2 vector = BaseProjectWindow.ms_Styles.ping.CalcSize(pingContent); + vector.y += 3f; + this.m_Ping.m_ContentRect = new Rect(17f + 16f * (float)newHierarchyProperty2.depth, top, vector.x, vector.y); + this.m_Ping.m_ContentDraw = delegate(Rect r) + { + this.DrawPingContent(r, pingContent); + }; + base.Repaint(); + return; + } + } + targetInstanceID = InternalEditorUtility.GetGameObjectInstanceIDFromComponent(targetInstanceID); + if (targetInstanceID != 0) + { + this.PingTargetObject(targetInstanceID); + } + } + private void DrawPingContent(Rect rect, GUIContent content) + { + GUIStyle labelStyle = this.labelStyle; + labelStyle.padding.left = 0; + labelStyle.Draw(rect, content, false, false, false, false); + } + private void ExecuteCommandGUI() + { + if (this.m_HierarchyType == HierarchyType.Assets) + { + this.ExecuteCommandGUIProject(); + } + else + { + this.ExecuteCommandGUIHierarchy(); + } + if (Event.current.commandName == "FrameSelected") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.FrameObject(Selection.activeInstanceID); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Find") + { + if (Event.current.type == EventType.ExecuteCommand) + { + base.FocusSearchField(); + } + Event.current.Use(); + } + } + } + public void SelectPrevious() + { + IHierarchyProperty firstSelected = this.GetFirstSelected(); + if (firstSelected != null) + { + if (firstSelected.Previous(this.m_ExpandedArray)) + { + this.FrameObject(firstSelected.instanceID); + this.SelectionClick(firstSelected); + } + } + else + { + if (this.GetLast() != null) + { + Selection.activeInstanceID = this.GetLast().instanceID; + this.FrameObject(Selection.activeInstanceID); + } + } + } + public void SelectNext() + { + IHierarchyProperty lastSelected = this.GetLastSelected(); + if (lastSelected != null) + { + if (lastSelected.Next(this.m_ExpandedArray)) + { + this.SelectionClick(lastSelected); + this.FrameObject(lastSelected.instanceID); + } + } + else + { + if (this.GetFirst() != null) + { + Selection.activeInstanceID = this.GetFirst().instanceID; + this.FrameObject(Selection.activeInstanceID); + } + } + } + private void KeyboardGUI() + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + if (Event.current.GetTypeForControl(controlID) != EventType.KeyDown) + { + return; + } + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_353; + case KeyCode.KeypadEquals: + case KeyCode.Insert: + IL_5E: + if (keyCode != KeyCode.Return) + { + return; + } + goto IL_353; + case KeyCode.UpArrow: + Event.current.Use(); + this.SelectPrevious(); + return; + case KeyCode.DownArrow: + Event.current.Use(); + if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) + { + this.OpenAssetSelection(); + GUIUtility.ExitGUI(); + } + else + { + this.SelectNext(); + } + return; + case KeyCode.RightArrow: + { + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + this.SetExpanded(instanceIDs[i], true); + } + Event.current.Use(); + return; + } + case KeyCode.LeftArrow: + { + int[] instanceIDs2 = Selection.instanceIDs; + for (int j = 0; j < instanceIDs2.Length; j++) + { + this.SetExpanded(instanceIDs2[j], false); + } + Event.current.Use(); + return; + } + case KeyCode.Home: + if (this.GetFirst() != null) + { + Selection.activeObject = this.GetFirst().pptrValue; + this.FrameObject(Selection.activeInstanceID); + } + return; + case KeyCode.End: + if (this.GetLast() != null) + { + Selection.activeObject = this.GetLast().pptrValue; + this.FrameObject(Selection.activeInstanceID); + } + return; + case KeyCode.PageUp: + Event.current.Use(); + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y - this.m_ScreenRect.height; + if (this.m_ScrollPosition.y < 0f) + { + this.m_ScrollPosition.y = 0f; + } + } + else + { + IHierarchyProperty hierarchyProperty = this.GetFirstSelected(); + if (hierarchyProperty != null) + { + int num = 0; + while ((float)num < this.m_ScreenRect.height / BaseProjectWindow.m_RowHeight) + { + if (!hierarchyProperty.Previous(this.m_ExpandedArray)) + { + hierarchyProperty = this.GetFirst(); + break; + } + num++; + } + int instanceID = hierarchyProperty.instanceID; + this.SelectionClick(hierarchyProperty); + this.FrameObject(instanceID); + } + else + { + if (this.GetFirst() != null) + { + Selection.activeObject = this.GetFirst().pptrValue; + this.FrameObject(Selection.activeInstanceID); + } + } + } + return; + case KeyCode.PageDown: + Event.current.Use(); + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_ScrollPosition.y = this.m_ScrollPosition.y + this.m_ScreenRect.height; + } + else + { + IHierarchyProperty hierarchyProperty2 = this.GetLastSelected(); + if (hierarchyProperty2 != null) + { + int num2 = 0; + while ((float)num2 < this.m_ScreenRect.height / BaseProjectWindow.m_RowHeight) + { + if (!hierarchyProperty2.Next(this.m_ExpandedArray)) + { + hierarchyProperty2 = this.GetLast(); + break; + } + num2++; + } + int instanceID2 = hierarchyProperty2.instanceID; + this.SelectionClick(hierarchyProperty2); + this.FrameObject(instanceID2); + } + else + { + if (this.GetLast() != null) + { + Selection.activeObject = this.GetLast().pptrValue; + this.FrameObject(Selection.activeInstanceID); + } + } + } + return; + } + goto IL_5E; + IL_353: + if (Application.platform == RuntimePlatform.WindowsEditor) + { + this.OpenAssetSelection(); + GUIUtility.ExitGUI(); + } + } + private bool RevealObject(int targetInstanceID) + { + return this.RevealObject(targetInstanceID, true); + } + private bool RevealObject(int targetInstanceID, bool allowClearSearchFilter) + { + IHierarchyProperty hierarchyProperty = this.GetNewHierarchyProperty(); + if (hierarchyProperty.Find(targetInstanceID, null)) + { + while (hierarchyProperty.Parent()) + { + this.SetExpanded(hierarchyProperty.instanceID, true); + } + return true; + } + if (allowClearSearchFilter) + { + hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + if (hierarchyProperty.Find(targetInstanceID, null)) + { + base.ClearSearchFilter(); + return this.RevealObject(targetInstanceID, true); + } + } + return false; + } + private void RevealObjects(int[] targetInstanceIDs) + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + int[] array = newHierarchyProperty.FindAllAncestors(targetInstanceIDs); + for (int i = 0; i < array.Length; i++) + { + this.SetExpanded(array[i], true); + } + } + internal bool FrameObject(int targetInstanceID) + { + return this.FrameObject(targetInstanceID, true); + } + internal bool FrameObject(int targetInstanceID, bool allowClearSearchFilter) + { + IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); + if (this.m_NeedsRelayout) + { + this.m_FrameAfterRelayout = targetInstanceID; + return newHierarchyProperty.Find(targetInstanceID, this.m_ExpandedArray); + } + this.RevealObject(targetInstanceID, allowClearSearchFilter); + newHierarchyProperty = this.GetNewHierarchyProperty(); + if (newHierarchyProperty.Find(targetInstanceID, this.m_ExpandedArray)) + { + int row = newHierarchyProperty.row; + float num = BaseProjectWindow.m_RowHeight * (float)row; + float min = num - this.m_ScreenRect.height + BaseProjectWindow.m_RowHeight; + if (!base.hasSearchFilter) + { + this.m_ScrollPosition.y = Mathf.Clamp(this.m_ScrollPosition.y, min, num); + } + else + { + this.m_ScrollPositionFiltered.y = Mathf.Clamp(this.m_ScrollPositionFiltered.y, min, num); + } + base.Repaint(); + return true; + } + return false; + } + private void SelectionClickContextMenu(IHierarchyProperty property) + { + if (!Selection.Contains(property.instanceID)) + { + Selection.activeInstanceID = property.instanceID; + } + } + private List GetSelection(IHierarchyProperty property, bool mouseDown) + { + List list = new List(); + if (EditorGUI.actionKey) + { + list.AddRange(Selection.instanceIDs); + if (list.Contains(property.instanceID)) + { + list.Remove(property.instanceID); + } + else + { + list.Add(property.instanceID); + } + return list; + } + if (!Event.current.shift) + { + if (mouseDown) + { + list.AddRange(Selection.instanceIDs); + if (list.Contains(property.instanceID)) + { + return list; + } + list.Clear(); + } + list.Add(property.instanceID); + return list; + } + IHierarchyProperty firstSelected = this.GetFirstSelected(); + IHierarchyProperty lastSelected = this.GetLastSelected(); + if (firstSelected == null || !firstSelected.isValid) + { + list.Add(property.instanceID); + return list; + } + IHierarchyProperty hierarchyProperty; + IHierarchyProperty hierarchyProperty2; + if (property.row > lastSelected.row) + { + hierarchyProperty = firstSelected; + hierarchyProperty2 = property; + } + else + { + hierarchyProperty = property; + hierarchyProperty2 = lastSelected; + } + list.Add(hierarchyProperty.instanceID); + while (hierarchyProperty.Next(this.m_ExpandedArray)) + { + list.Add(hierarchyProperty.instanceID); + if (hierarchyProperty.instanceID == hierarchyProperty2.instanceID) + { + break; + } + } + return list; + } + private void SelectionClick(IHierarchyProperty property) + { + List selection = this.GetSelection(property, false); + if (selection.Count == 1) + { + Selection.activeInstanceID = selection[0]; + } + else + { + Selection.instanceIDs = selection.ToArray(); + } + this.m_ProjectViewInternalSelectionChange = true; + if (base.hasSearchFilter) + { + this.m_DidSelectSearchResult = true; + this.m_NeedsRelayout = true; + } + } + private void CreateAssetPopup() + { + GUIContent content = new GUIContent("Create"); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.toolbarDropDown, null); + if (Event.current.type == EventType.Repaint) + { + EditorStyles.toolbarDropDown.Draw(rect, content, false, false, false, false); + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = 0; + EditorUtility.DisplayPopupMenu(rect, "Assets/Create", null); + Event.current.Use(); + } + } + private void CreateGameObjectPopup() + { + GUIContent content = new GUIContent("Create"); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.toolbarDropDown, null); + if (Event.current.type == EventType.Repaint) + { + EditorStyles.toolbarDropDown.Draw(rect, content, false, false, false, false); + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = 0; + EditorUtility.DisplayPopupMenu(rect, "GameObject/Create Other", null); + Event.current.Use(); + } + } + private void Awake() + { + if (this.m_HierarchyType == HierarchyType.Assets) + { + this.m_ExpandedArray = InternalEditorUtility.expandedProjectWindowItems; + } + } + public new void Show() + { + this.Awake(); + base.Show(); + } + } +} diff --git a/UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs b/UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs new file mode 100644 index 00000000..59101db1 --- /dev/null +++ b/UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum BlackBerryBuildSubtarget + { + Generic, + PVRTC, + ATC, + ETC + } +} diff --git a/UnityEditor/UnityEditor/BlackBerryBuildType.cs b/UnityEditor/UnityEditor/BlackBerryBuildType.cs new file mode 100644 index 00000000..c71f95af --- /dev/null +++ b/UnityEditor/UnityEditor/BlackBerryBuildType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum BlackBerryBuildType + { + Debug, + Submission + } +} diff --git a/UnityEditor/UnityEditor/BlendTreeInspector.cs b/UnityEditor/UnityEditor/BlendTreeInspector.cs new file mode 100644 index 00000000..772d5af8 --- /dev/null +++ b/UnityEditor/UnityEditor/BlendTreeInspector.cs @@ -0,0 +1,1693 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CustomEditor(typeof(BlendTree))] + internal class BlendTreeInspector : Editor + { + private class Styles + { + public readonly GUIStyle background = "MeBlendBackground"; + public readonly GUIStyle triangleLeft = "MeBlendTriangleLeft"; + public readonly GUIStyle triangleRight = "MeBlendTriangleRight"; + public readonly GUIStyle blendPosition = "MeBlendPosition"; + public GUIStyle clickDragFloatFieldLeft = new GUIStyle(EditorStyles.miniTextField); + public GUIStyle clickDragFloatFieldRight = new GUIStyle(EditorStyles.miniTextField); + public GUIStyle clickDragFloatLabelLeft = new GUIStyle(EditorStyles.miniLabel); + public GUIStyle clickDragFloatLabelRight = new GUIStyle(EditorStyles.miniLabel); + public GUIStyle headerIcon = new GUIStyle(); + public GUIStyle errorStyle = new GUIStyle(EditorStyles.wordWrappedLabel); + public GUIContent speedIcon = new GUIContent(EditorGUIUtility.IconContent("SpeedScale")); + public GUIContent mirrorIcon = new GUIContent(EditorGUIUtility.IconContent("Mirror")); + public Texture2D pointIcon = EditorGUIUtility.LoadIcon("blendKey"); + public Texture2D pointIconSelected = EditorGUIUtility.LoadIcon("blendKeySelected"); + public Texture2D pointIconOverlay = EditorGUIUtility.LoadIcon("blendKeyOverlay"); + public Texture2D samplerIcon = EditorGUIUtility.LoadIcon("blendSampler"); + public Styles() + { + this.errorStyle.alignment = TextAnchor.MiddleCenter; + this.speedIcon.tooltip = "Changes animation speed."; + this.mirrorIcon.tooltip = "Mirror animation."; + this.headerIcon.alignment = TextAnchor.MiddleCenter; + this.clickDragFloatFieldLeft.alignment = TextAnchor.MiddleLeft; + this.clickDragFloatFieldRight.alignment = TextAnchor.MiddleRight; + this.clickDragFloatLabelLeft.alignment = TextAnchor.MiddleLeft; + this.clickDragFloatLabelRight.alignment = TextAnchor.MiddleRight; + } + } + private enum ChildPropertyToCompute + { + Threshold, + PositionX, + PositionY + } + private delegate float GetFloatFromMotion(Motion motion, float mirrorMultiplier); + private const int kVisResolution = 64; + private static BlendTreeInspector.Styles styles; + internal static AnimatorController currentController = null; + internal static Animator currentAnimator = null; + internal static BlendTree parentBlendTree = null; + internal static Action blendTreeHierarchyChanged = null; + internal static Action blendParameterInputChanged = null; + private readonly int m_BlendAnimationID = "BlendAnimationIDHash".GetHashCode(); + private readonly int m_ClickDragFloatID = "ClickDragFloatIDHash".GetHashCode(); + private ReorderableList m_ReorderableList; + private SerializedProperty m_Childs; + private SerializedProperty m_BlendParameter; + private SerializedProperty m_BlendParameterY; + private BlendTree m_BlendTree; + private SerializedProperty m_UseAutomaticThresholds; + private SerializedProperty m_MinThreshold; + private SerializedProperty m_MaxThreshold; + private SerializedProperty m_Name; + private SerializedProperty m_BlendType; + private AnimBool m_ShowGraph = new AnimBool(); + private AnimBool m_ShowCompute = new AnimBool(); + private AnimBool m_ShowAdjust = new AnimBool(); + private bool m_ShowGraphValue; + private bool m_HierarchyChanged; + private string m_PrevBlendValueName = string.Empty; + private string m_PrevBlendValueYName = string.Empty; + private float[] m_Weights; + private bool m_DirtyVisualization = true; + private Texture2D m_BlendTex; + private List m_WeightTexs = new List(); + private string m_WarningMessage; + private PreviewBlendTree m_PreviewBlendTree; + private VisualizationBlendTree m_VisBlendTree; + [NonSerialized] + private GameObject m_VisInstance; + private static bool s_ClickDragFloatDragged; + private static float s_ClickDragFloatDistance; + private Rect m_BlendRect; + private int m_SelectedPoint = -1; + private bool s_DraggingPoint; + private static Color s_VisBgColor = EditorGUIUtility.isProSkin ? new Color(0.2f, 0.2f, 0.2f) : new Color(0.95f, 0.95f, 1f); + private static Color s_VisWeightColor = EditorGUIUtility.isProSkin ? new Color(0.65f, 0.75f, 1f, 0.65f) : new Color(0.5f, 0.6f, 0.9f, 0.8f); + private static Color s_VisWeightShapeColor = EditorGUIUtility.isProSkin ? new Color(0.4f, 0.65f, 1f, 0.12f) : new Color(0.4f, 0.65f, 1f, 0.15f); + private static Color s_VisWeightLineColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.6f) : new Color(0f, 0f, 0f, 0.3f); + private static Color s_VisPointColor = EditorGUIUtility.isProSkin ? new Color(0.5f, 0.7f, 1f) : new Color(0.5f, 0.7f, 1f); + private static Color s_VisPointEmptyColor = EditorGUIUtility.isProSkin ? new Color(0.6f, 0.6f, 0.6f) : new Color(0.8f, 0.8f, 0.8f); + private static Color s_VisPointOverlayColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.4f) : new Color(0f, 0f, 0f, 0.2f); + private static Color s_VisSamplerColor = EditorGUIUtility.isProSkin ? new Color(1f, 0.4f, 0.4f) : new Color(1f, 0.4f, 0.4f); + private int kNumCirclePoints = 20; + private int ParameterCount + { + get + { + return (this.m_BlendType.intValue <= 0) ? 1 : 2; + } + } + public void OnEnable() + { + this.m_Name = base.serializedObject.FindProperty("m_Name"); + this.m_BlendParameter = base.serializedObject.FindProperty("m_BlendParameter"); + this.m_BlendParameterY = base.serializedObject.FindProperty("m_BlendParameterY"); + this.m_UseAutomaticThresholds = base.serializedObject.FindProperty("m_UseAutomaticThresholds"); + this.m_MinThreshold = base.serializedObject.FindProperty("m_MinThreshold"); + this.m_MaxThreshold = base.serializedObject.FindProperty("m_MaxThreshold"); + this.m_BlendType = base.serializedObject.FindProperty("m_BlendType"); + this.m_DirtyVisualization = true; + } + private void Init() + { + if (BlendTreeInspector.styles == null) + { + BlendTreeInspector.styles = new BlendTreeInspector.Styles(); + } + if (this.m_BlendTree == null) + { + this.m_BlendTree = (this.target as BlendTree); + } + if (BlendTreeInspector.styles == null) + { + BlendTreeInspector.styles = new BlendTreeInspector.Styles(); + } + if (this.m_PreviewBlendTree == null) + { + this.m_PreviewBlendTree = new PreviewBlendTree(); + } + if (this.m_VisBlendTree == null) + { + this.m_VisBlendTree = new VisualizationBlendTree(); + } + if (this.m_Childs == null) + { + this.m_Childs = base.serializedObject.FindProperty("m_Childs"); + this.m_ReorderableList = new ReorderableList(base.serializedObject, this.m_Childs); + this.m_ReorderableList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawHeader); + this.m_ReorderableList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawChild); + this.m_ReorderableList.onReorderCallback = new ReorderableList.ReorderCallbackDelegate(this.EndDragChild); + this.m_ReorderableList.onAddDropdownCallback = new ReorderableList.AddDropdownCallbackDelegate(this.AddButton); + this.m_ReorderableList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveButton); + if (this.m_BlendType.intValue == 0) + { + this.SortByThreshold(); + } + this.m_ShowGraphValue = (this.m_Childs.arraySize >= 2); + this.m_ShowGraph.value = this.m_ShowGraphValue; + this.m_ShowAdjust.value = this.AllMotions(); + this.m_ShowCompute.value = !this.m_UseAutomaticThresholds.boolValue; + this.m_ShowGraph.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowAdjust.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowCompute.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + this.m_PreviewBlendTree.Init(this.m_BlendTree, BlendTreeInspector.currentAnimator); + if (this.m_VisInstance == null) + { + GameObject original = (GameObject)EditorGUIUtility.Load("Avatar/DefaultAvatar.fbx"); + this.m_VisInstance = (GameObject)EditorUtility.InstantiateRemoveAllNonAnimationComponents(original, Vector3.zero, Quaternion.identity); + BlendTreeInspector.InitInstantiatedPreviewRecursive(this.m_VisInstance); + Renderer[] componentsInChildren = this.m_VisInstance.GetComponentsInChildren(); + for (int i = 0; i < componentsInChildren.Length; i++) + { + Renderer renderer = componentsInChildren[i]; + renderer.enabled = false; + } + } + this.m_VisBlendTree.Init(this.m_BlendTree, this.m_VisInstance.GetComponent()); + } + private static void InitInstantiatedPreviewRecursive(GameObject go) + { + go.hideFlags = HideFlags.HideAndDontSave; + foreach (Transform transform in go.transform) + { + BlendTreeInspector.InitInstantiatedPreviewRecursive(transform.gameObject); + } + } + internal override void OnHeaderIconGUI(Rect iconRect) + { + Texture2D miniThumbnail = AssetPreview.GetMiniThumbnail(this.target); + GUI.Label(iconRect, miniThumbnail); + } + internal override void OnHeaderTitleGUI(Rect titleRect, string header) + { + base.serializedObject.Update(); + Rect position = titleRect; + position.height = 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_Name.hasMultipleDifferentValues; + string text = EditorGUI.DelayedTextField(position, this.m_Name.stringValue, null, EditorStyles.textField); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck() && !string.IsNullOrEmpty(text)) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object obj = targets[i]; + ObjectNames.SetNameSmart(obj, text); + } + this.m_HierarchyChanged = true; + } + base.serializedObject.ApplyModifiedProperties(); + } + internal override void OnHeaderControlsGUI() + { + EditorGUIUtility.labelWidth = 80f; + base.serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_BlendType, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_DirtyVisualization = true; + } + base.serializedObject.ApplyModifiedProperties(); + } + private void ParameterGUI() + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (this.ParameterCount == 1) + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameter")); + } + else + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameters")); + } + List list = new List(); + string blendParameter = this.m_BlendTree.blendParameter; + string blendParameterY = this.m_BlendTree.blendParameterY; + int num = 0; + int num2 = 0; + if (BlendTreeInspector.currentController != null) + { + for (int i = 0; i < BlendTreeInspector.currentController.parameterCount; i++) + { + if (BlendTreeInspector.currentController.GetParameterType(i) == AnimatorControllerParameterType.Float) + { + string parameterName = BlendTreeInspector.currentController.GetParameterName(i); + if (parameterName == blendParameter) + { + num = list.Count; + } + if (parameterName == blendParameterY) + { + num2 = list.Count; + } + list.Add(parameterName); + } + } + } + bool flag = false; + int num3 = EditorGUILayout.Popup(num, list.ToArray(), new GUILayoutOption[0]); + if (num3 != num) + { + this.m_BlendParameter.stringValue = list[num3]; + } + if (this.m_PrevBlendValueName != blendParameter) + { + this.m_PrevBlendValueName = blendParameter; + flag = true; + } + if (this.ParameterCount > 1) + { + int num4 = EditorGUILayout.Popup(num2, list.ToArray(), new GUILayoutOption[0]); + if (num4 != num2) + { + this.m_BlendParameterY.stringValue = list[num4]; + } + if (this.m_PrevBlendValueYName != blendParameterY) + { + this.m_PrevBlendValueYName = blendParameterY; + flag = true; + } + } + if (flag) + { + this.m_PreviewBlendTree.ResetStateMachine(); + this.m_VisBlendTree.Reset(); + this.m_DirtyVisualization = true; + } + EditorGUILayout.EndHorizontal(); + } + public override void OnInspectorGUI() + { + this.Init(); + base.serializedObject.Update(); + this.ParameterGUI(); + this.m_ShowGraphValue = (this.m_Childs.arraySize >= 2); + this.m_ShowGraph.target = this.m_ShowGraphValue; + this.m_UseAutomaticThresholds = base.serializedObject.FindProperty("m_UseAutomaticThresholds"); + GUI.enabled = true; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowGraph.faded)) + { + if (this.ParameterCount == 1) + { + this.BlendGraph(EditorGUILayout.GetControlRect(false, 40f, BlendTreeInspector.styles.background, new GUILayoutOption[0])); + this.ThresholdValues(); + } + else + { + GUILayout.Space(1f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect aspectRect = GUILayoutUtility.GetAspectRect(1f, new GUILayoutOption[] + { + GUILayout.MaxWidth(235f) + }); + GUI.Label(new Rect(aspectRect.x - 1f, aspectRect.y - 1f, aspectRect.width + 2f, aspectRect.height + 2f), GUIContent.none, EditorStyles.textField); + GUI.BeginGroup(aspectRect); + aspectRect.x = 0f; + aspectRect.y = 0f; + this.BlendGraph2D(aspectRect); + GUI.EndGroup(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + GUILayout.Space(5f); + } + EditorGUILayout.EndFadeGroup(); + if (this.m_ReorderableList != null) + { + this.m_ReorderableList.DoLayoutList(); + } + if (this.m_ShowGraphValue) + { + GUILayout.Space(10f); + this.AutoCompute(); + } + base.serializedObject.ApplyModifiedProperties(); + this.DoHierarchyChangedCallback(); + } + private void SetMinMaxThresholds() + { + float num = float.PositiveInfinity; + float num2 = float.NegativeInfinity; + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); + num = ((serializedProperty.floatValue >= num) ? num : serializedProperty.floatValue); + num2 = ((serializedProperty.floatValue <= num2) ? num2 : serializedProperty.floatValue); + } + this.m_MinThreshold.floatValue = ((this.m_Childs.arraySize <= 0) ? 0f : num); + this.m_MaxThreshold.floatValue = ((this.m_Childs.arraySize <= 0) ? 1f : num2); + } + private void ThresholdValues() + { + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + Rect position = controlRect; + Rect position2 = controlRect; + position.width /= 4f; + position2.width /= 4f; + position2.x = controlRect.x + controlRect.width - position2.width; + float num = this.m_MinThreshold.floatValue; + float num2 = this.m_MaxThreshold.floatValue; + EditorGUI.BeginChangeCheck(); + num = this.ClickDragFloat(position, num); + num2 = this.ClickDragFloat(position2, num2, true); + if (EditorGUI.EndChangeCheck()) + { + if (this.m_Childs.arraySize >= 2) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(0); + SerializedProperty arrayElementAtIndex2 = this.m_Childs.GetArrayElementAtIndex(this.m_Childs.arraySize - 1); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); + SerializedProperty serializedProperty2 = arrayElementAtIndex2.FindPropertyRelative("m_Threshold"); + serializedProperty.floatValue = Mathf.Min(num, num2); + serializedProperty2.floatValue = Mathf.Max(num, num2); + } + if (!this.m_UseAutomaticThresholds.boolValue) + { + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty arrayElementAtIndex3 = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty3 = arrayElementAtIndex3.FindPropertyRelative("m_Threshold"); + float t = Mathf.InverseLerp(this.m_MinThreshold.floatValue, this.m_MaxThreshold.floatValue, serializedProperty3.floatValue); + serializedProperty3.floatValue = Mathf.Lerp(Mathf.Min(num, num2), Mathf.Max(num, num2), t); + } + } + this.m_MinThreshold.floatValue = Mathf.Min(num, num2); + this.m_MaxThreshold.floatValue = Mathf.Max(num, num2); + } + } + public float ClickDragFloat(Rect position, float value) + { + return this.ClickDragFloat(position, value, false); + } + public float ClickDragFloat(Rect position, float value, bool alignRight) + { + string allowedletters = "inftynaeINFTYNAE0123456789.,-"; + int controlID = GUIUtility.GetControlID(this.m_ClickDragFloatID, FocusType.Keyboard, position); + Event current = Event.current; + switch (current.type) + { + case EventType.MouseDown: + if (GUIUtility.keyboardControl != controlID || !EditorGUIUtility.editingTextField) + { + if (position.Contains(current.mousePosition)) + { + current.Use(); + BlendTreeInspector.s_ClickDragFloatDragged = false; + BlendTreeInspector.s_ClickDragFloatDistance = 0f; + GUIUtility.hotControl = controlID; + GUIUtility.keyboardControl = controlID; + EditorGUIUtility.editingTextField = false; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + current.Use(); + if (position.Contains(current.mousePosition) && !BlendTreeInspector.s_ClickDragFloatDragged) + { + EditorGUIUtility.editingTextField = true; + } + else + { + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = 0; + BlendTreeInspector.s_ClickDragFloatDragged = false; + } + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && !EditorGUIUtility.editingTextField) + { + BlendTreeInspector.s_ClickDragFloatDistance += Mathf.Abs(HandleUtility.niceMouseDelta); + if (BlendTreeInspector.s_ClickDragFloatDistance >= 5f) + { + BlendTreeInspector.s_ClickDragFloatDragged = true; + value += HandleUtility.niceMouseDelta * 0.03f; + value = MathUtils.RoundBasedOnMinimumDifference(value, 0.03f); + GUI.changed = true; + } + current.Use(); + } + break; + } + GUIStyle style = (GUIUtility.keyboardControl != controlID || !EditorGUIUtility.editingTextField) ? ((!alignRight) ? BlendTreeInspector.styles.clickDragFloatLabelLeft : BlendTreeInspector.styles.clickDragFloatLabelRight) : ((!alignRight) ? BlendTreeInspector.styles.clickDragFloatFieldLeft : BlendTreeInspector.styles.clickDragFloatFieldRight); + if (GUIUtility.keyboardControl == controlID) + { + string text; + if (!EditorGUI.s_RecycledEditor.IsEditingControl(controlID)) + { + text = (EditorGUI.s_RecycledCurrentEditingString = value.ToString("g7")); + } + else + { + text = EditorGUI.s_RecycledCurrentEditingString; + if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") + { + text = value.ToString("g7"); + } + } + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, position, text, style, allowedletters, out flag, false, false, false); + if (flag) + { + GUI.changed = true; + EditorGUI.s_RecycledCurrentEditingString = text; + string a = text.ToLower(); + if (a == "inf" || a == "infinity") + { + value = float.PositiveInfinity; + } + else + { + if (a == "-inf" || a == "-infinity") + { + value = float.NegativeInfinity; + } + else + { + text = text.Replace(',', '.'); + if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out value)) + { + value = (EditorGUI.s_RecycledCurrentEditingFloat = 0f); + return value; + } + if (float.IsNaN(value)) + { + value = 0f; + } + EditorGUI.s_RecycledCurrentEditingFloat = value; + } + } + } + } + else + { + string text = value.ToString("g7"); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, position, text, style, allowedletters, out flag, false, false, false); + } + return value; + } + private void BlendGraph(Rect area) + { + area.xMin += 1f; + area.xMax -= 1f; + int controlID = GUIUtility.GetControlID(this.m_BlendAnimationID, FocusType.Passive); + int arraySize = this.m_Childs.arraySize; + float[] array = new float[arraySize]; + for (int i = 0; i < arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); + array[i] = serializedProperty.floatValue; + } + float num = Mathf.Min(array); + float num2 = Mathf.Max(array); + for (int j = 0; j < array.Length; j++) + { + array[j] = area.x + Mathf.InverseLerp(num, num2, array[j]) * area.width; + } + string blendParameter = this.m_BlendTree.blendParameter; + float num3 = area.x + Mathf.InverseLerp(num, num2, this.m_BlendTree.GetInputBlendValue(blendParameter)) * area.width; + Rect position = new Rect(num3 - 4f, area.y, 9f, 42f); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + this.m_ReorderableList.index = -1; + this.m_ReorderableList.index = -1; + float num4 = Mathf.InverseLerp(0f, area.width, current.mousePosition.x - 4f); + num4 = Mathf.Lerp(num, num2, num4); + this.m_BlendTree.SetInputBlendValue(blendParameter, num4); + if (BlendTreeInspector.parentBlendTree) + { + BlendTreeInspector.parentBlendTree.SetInputBlendValue(blendParameter, num4); + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(BlendTreeInspector.parentBlendTree); + } + } + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(this.m_BlendTree); + } + } + else + { + if (area.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + GUIUtility.keyboardControl = controlID; + float x = current.mousePosition.x; + float num5 = float.PositiveInfinity; + for (int k = 0; k < array.Length; k++) + { + float num6 = (k != 0) ? array[k - 1] : array[k]; + float num7 = (k != array.Length - 1) ? array[k + 1] : array[k]; + if (Mathf.Abs(x - array[k]) < num5 && x < num7 && x > num6) + { + num5 = Mathf.Abs(x - array[k]); + this.m_ReorderableList.index = k; + } + } + this.m_UseAutomaticThresholds.boolValue = false; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + current.Use(); + GUIUtility.hotControl = 0; + this.m_ReorderableList.index = -1; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + current.Use(); + if (this.m_ReorderableList.index == -1) + { + float num8 = Mathf.InverseLerp(0f, area.width, current.mousePosition.x - 4f); + num8 = Mathf.Lerp(num, num2, num8); + this.m_BlendTree.SetInputBlendValue(blendParameter, num8); + if (BlendTreeInspector.parentBlendTree) + { + BlendTreeInspector.parentBlendTree.SetInputBlendValue(blendParameter, num8); + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(BlendTreeInspector.parentBlendTree); + } + } + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(this.m_BlendTree); + } + } + else + { + float t = Mathf.InverseLerp(0f, area.width, current.mousePosition.x); + t = Mathf.Lerp(num, num2, t); + SerializedProperty arrayElementAtIndex2 = this.m_Childs.GetArrayElementAtIndex(this.m_ReorderableList.index); + SerializedProperty serializedProperty2 = arrayElementAtIndex2.FindPropertyRelative("m_Threshold"); + SerializedProperty serializedProperty3 = (this.m_ReorderableList.index > 0) ? this.m_Childs.GetArrayElementAtIndex(this.m_ReorderableList.index - 1) : arrayElementAtIndex2; + SerializedProperty serializedProperty4 = (this.m_ReorderableList.index != this.m_Childs.arraySize - 1) ? this.m_Childs.GetArrayElementAtIndex(this.m_ReorderableList.index + 1) : arrayElementAtIndex2; + SerializedProperty serializedProperty5 = serializedProperty3.FindPropertyRelative("m_Threshold"); + SerializedProperty serializedProperty6 = serializedProperty4.FindPropertyRelative("m_Threshold"); + float num9 = (num2 - num) / area.width; + float x2 = current.delta.x; + serializedProperty2.floatValue += x2 * num9; + if (serializedProperty2.floatValue < serializedProperty5.floatValue && this.m_ReorderableList.index != 0) + { + this.m_Childs.MoveArrayElement(this.m_ReorderableList.index, this.m_ReorderableList.index - 1); + this.m_ReorderableList.index--; + } + if (serializedProperty2.floatValue > serializedProperty6.floatValue && this.m_ReorderableList.index < this.m_Childs.arraySize - 1) + { + this.m_Childs.MoveArrayElement(this.m_ReorderableList.index, this.m_ReorderableList.index + 1); + this.m_ReorderableList.index++; + } + float num10 = 3f * ((num2 - num) / area.width); + if (serializedProperty2.floatValue - serializedProperty5.floatValue <= num10) + { + serializedProperty2.floatValue = serializedProperty5.floatValue; + } + else + { + if (serializedProperty6.floatValue - serializedProperty2.floatValue <= num10) + { + serializedProperty2.floatValue = serializedProperty6.floatValue; + } + } + } + } + break; + case EventType.Repaint: + BlendTreeInspector.styles.background.Draw(area, GUIContent.none, false, false, false, false); + if (this.m_Childs.arraySize >= 2) + { + for (int l = 0; l < array.Length; l++) + { + float min = (l != 0) ? array[l - 1] : array[l]; + float max = (l != array.Length - 1) ? array[l + 1] : array[l]; + bool selected = this.m_ReorderableList.index == l; + this.DrawAnimation(array[l], min, max, selected, area); + } + Color color = Handles.color; + Handles.color = new Color(0f, 0f, 0f, 0.25f); + Handles.DrawLine(new Vector3(area.x, area.y + area.height, 0f), new Vector3(area.x + area.width, area.y + area.height, 0f)); + Handles.color = color; + BlendTreeInspector.styles.blendPosition.Draw(position, GUIContent.none, false, false, false, false); + } + else + { + GUI.Label(area, EditorGUIUtility.TempContent("Please Add Motion Fields or Blend Trees"), BlendTreeInspector.styles.errorStyle); + } + break; + } + } + private void UpdateBlendVisualization() + { + Vector2[] activeMotionPositions = this.GetActiveMotionPositions(); + if (this.m_BlendTex == null) + { + this.m_BlendTex = new Texture2D(64, 64, TextureFormat.RGBA32, false); + this.m_BlendTex.hideFlags = HideFlags.DontSave; + this.m_BlendTex.wrapMode = TextureWrapMode.Clamp; + } + while (this.m_WeightTexs.Count < activeMotionPositions.Length) + { + Texture2D texture2D = new Texture2D(64, 64, TextureFormat.RGBA32, false); + texture2D.wrapMode = TextureWrapMode.Clamp; + texture2D.hideFlags = HideFlags.DontSave; + this.m_WeightTexs.Add(texture2D); + } + while (this.m_WeightTexs.Count > activeMotionPositions.Length) + { + UnityEngine.Object.DestroyImmediate(this.m_WeightTexs[this.m_WeightTexs.Count - 1]); + this.m_WeightTexs.RemoveAt(this.m_WeightTexs.Count - 1); + } + if (GUIUtility.hotControl == 0) + { + this.m_BlendRect = this.Get2DBlendRect(this.GetMotionPositions()); + } + this.m_VisBlendTree.Reset(); + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + Texture2D[] array = this.m_WeightTexs.ToArray(); + if (GUIUtility.hotControl != 0 && this.m_ReorderableList.index >= 0) + { + int[] motionToActiveMotionIndices = this.GetMotionToActiveMotionIndices(); + for (int i = 0; i < array.Length; i++) + { + if (motionToActiveMotionIndices[this.m_ReorderableList.index] != i) + { + array[i] = null; + } + } + } + BlendTreePreviewUtility.CalculateBlendTexture(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).nameHash, this.m_BlendTex, array, this.m_BlendRect); + stopwatch.Stop(); + this.m_DirtyVisualization = false; + } + private Vector2[] GetMotionPositions() + { + int arraySize = this.m_Childs.arraySize; + Vector2[] array = new Vector2[arraySize]; + for (int i = 0; i < arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Position"); + array[i] = serializedProperty.vector2Value; + } + return array; + } + private Vector2[] GetActiveMotionPositions() + { + List list = new List(); + int arraySize = this.m_Childs.arraySize; + for (int i = 0; i < arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Motion"); + if (serializedProperty.objectReferenceValue != null) + { + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("m_Position"); + list.Add(serializedProperty2.vector2Value); + } + } + return list.ToArray(); + } + private int[] GetMotionToActiveMotionIndices() + { + int arraySize = this.m_Childs.arraySize; + int[] array = new int[arraySize]; + int num = 0; + for (int i = 0; i < arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Motion"); + if (serializedProperty.objectReferenceValue == null) + { + array[i] = -1; + } + else + { + array[i] = num; + num++; + } + } + return array; + } + private Rect Get2DBlendRect(Vector2[] points) + { + Vector2 vector = Vector2.zero; + float num = 0f; + if (this.m_BlendType.intValue == 3) + { + Vector2 a = points[0]; + Vector2 b = points[0]; + for (int i = 1; i < points.Length; i++) + { + b.x = Mathf.Max(b.x, points[i].x); + b.y = Mathf.Max(b.y, points[i].y); + a.x = Mathf.Min(a.x, points[i].x); + a.y = Mathf.Min(a.y, points[i].y); + } + vector = (a + b) * 0.5f; + num = Mathf.Max(b.x - a.x, b.y - a.y) * 0.5f; + } + else + { + for (int j = 0; j < points.Length; j++) + { + num = Mathf.Max(num, points[j].x); + num = Mathf.Max(num, -points[j].x); + num = Mathf.Max(num, points[j].y); + num = Mathf.Max(num, -points[j].y); + } + } + if (num == 0f) + { + num = 1f; + } + num *= 1.35f; + return new Rect(vector.x - num, vector.y - num, num * 2f, num * 2f); + } + private float ConvertFloat(float input, float fromMin, float fromMax, float toMin, float toMax) + { + float num = (input - fromMin) / (fromMax - fromMin); + return toMin * (1f - num) + toMax * num; + } + private void BlendGraph2D(Rect area) + { + if (this.m_DirtyVisualization) + { + this.UpdateBlendVisualization(); + this.ValidatePositions(); + } + Vector2[] motionPositions = this.GetMotionPositions(); + int[] motionToActiveMotionIndices = this.GetMotionToActiveMotionIndices(); + Vector2 vector = new Vector2(this.m_BlendRect.xMin, this.m_BlendRect.yMin); + Vector2 vector2 = new Vector2(this.m_BlendRect.xMax, this.m_BlendRect.yMax); + for (int i = 0; i < motionPositions.Length; i++) + { + motionPositions[i].x = this.ConvertFloat(motionPositions[i].x, vector.x, vector2.x, area.xMin, area.xMax); + motionPositions[i].y = this.ConvertFloat(motionPositions[i].y, vector.y, vector2.y, area.yMax, area.yMin); + } + string blendParameter = this.m_BlendTree.blendParameter; + string blendParameterY = this.m_BlendTree.blendParameterY; + float num = this.m_BlendTree.GetInputBlendValue(blendParameter); + float num2 = this.m_BlendTree.GetInputBlendValue(blendParameterY); + int num3 = this.GetActiveMotionPositions().Length; + if (this.m_Weights == null || num3 != this.m_Weights.Length) + { + this.m_Weights = new float[num3]; + } + BlendTreePreviewUtility.CalculateRootBlendTreeChildWeights(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).nameHash, this.m_Weights, num, num2); + num = area.x + Mathf.InverseLerp(vector.x, vector2.x, num) * area.width; + num2 = area.y + (1f - Mathf.InverseLerp(vector.y, vector2.y, num2)) * area.height; + Rect position = new Rect(num - 5f, num2 - 5f, 11f, 11f); + int controlID = GUIUtility.GetControlID(this.m_BlendAnimationID, FocusType.Native); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + this.m_SelectedPoint = -1; + } + else + { + if (area.Contains(current.mousePosition)) + { + this.m_ReorderableList.index = -1; + for (int j = 0; j < motionPositions.Length; j++) + { + Rect rect = new Rect(motionPositions[j].x - 4f, motionPositions[j].y - 4f, 9f, 9f); + if (rect.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + this.m_SelectedPoint = j; + this.m_ReorderableList.index = j; + } + } + current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + current.Use(); + GUIUtility.hotControl = 0; + this.s_DraggingPoint = false; + for (int k = 0; k < motionPositions.Length; k++) + { + if (this.m_SelectedPoint == k) + { + this.m_DirtyVisualization = true; + } + } + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + if (this.m_SelectedPoint == -1) + { + Vector2 vector3; + vector3.x = this.ConvertFloat(current.mousePosition.x, area.xMin, area.xMax, vector.x, vector2.x); + vector3.y = this.ConvertFloat(current.mousePosition.y, area.yMax, area.yMin, vector.y, vector2.y); + this.m_BlendTree.SetInputBlendValue(blendParameter, vector3.x); + this.m_BlendTree.SetInputBlendValue(blendParameterY, vector3.y); + if (BlendTreeInspector.parentBlendTree) + { + BlendTreeInspector.parentBlendTree.SetInputBlendValue(blendParameter, vector3.x); + BlendTreeInspector.parentBlendTree.SetInputBlendValue(blendParameterY, vector3.y); + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(BlendTreeInspector.parentBlendTree); + } + } + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(this.m_BlendTree); + } + current.Use(); + } + else + { + for (int l = 0; l < motionPositions.Length; l++) + { + if (this.m_SelectedPoint == l) + { + Vector2 vector2Value; + vector2Value.x = this.ConvertFloat(current.mousePosition.x, area.xMin, area.xMax, vector.x, vector2.x); + vector2Value.y = this.ConvertFloat(current.mousePosition.y, area.yMax, area.yMin, vector.y, vector2.y); + float minDifference = (vector2.x - vector.x) / area.width; + vector2Value.x = MathUtils.RoundBasedOnMinimumDifference(vector2Value.x, minDifference); + vector2Value.y = MathUtils.RoundBasedOnMinimumDifference(vector2Value.y, minDifference); + vector2Value.x = Mathf.Clamp(vector2Value.x, -10000f, 10000f); + vector2Value.y = Mathf.Clamp(vector2Value.y, -10000f, 10000f); + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(l); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Position"); + serializedProperty.vector2Value = vector2Value; + current.Use(); + this.m_DirtyVisualization = true; + this.s_DraggingPoint = true; + } + } + } + } + break; + case EventType.Repaint: + GUI.color = BlendTreeInspector.s_VisBgColor; + GUI.DrawTexture(area, EditorGUIUtility.whiteTexture); + if (this.m_ReorderableList.index < 0) + { + Color color = BlendTreeInspector.s_VisWeightColor; + color.a *= 0.75f; + GUI.color = color; + GUI.DrawTexture(area, this.m_BlendTex); + } + else + { + if (motionToActiveMotionIndices[this.m_ReorderableList.index] >= 0) + { + GUI.color = BlendTreeInspector.s_VisWeightColor; + GUI.DrawTexture(area, this.m_WeightTexs[motionToActiveMotionIndices[this.m_ReorderableList.index]]); + } + } + GUI.color = Color.white; + if (!this.s_DraggingPoint) + { + for (int m = 0; m < motionPositions.Length; m++) + { + if (motionToActiveMotionIndices[m] >= 0) + { + this.DrawWeightShape(motionPositions[m], this.m_Weights[motionToActiveMotionIndices[m]], 0); + } + } + for (int n = 0; n < motionPositions.Length; n++) + { + if (motionToActiveMotionIndices[n] >= 0) + { + this.DrawWeightShape(motionPositions[n], this.m_Weights[motionToActiveMotionIndices[n]], 1); + } + } + } + for (int num4 = 0; num4 < motionPositions.Length; num4++) + { + Rect position2 = new Rect(motionPositions[num4].x - 6f, motionPositions[num4].y - 6f, 13f, 13f); + bool flag = this.m_ReorderableList.index == num4; + if (motionToActiveMotionIndices[num4] < 0) + { + GUI.color = BlendTreeInspector.s_VisPointEmptyColor; + } + else + { + GUI.color = BlendTreeInspector.s_VisPointColor; + } + GUI.DrawTexture(position2, (!flag) ? BlendTreeInspector.styles.pointIcon : BlendTreeInspector.styles.pointIconSelected); + if (flag) + { + GUI.color = BlendTreeInspector.s_VisPointOverlayColor; + GUI.DrawTexture(position2, BlendTreeInspector.styles.pointIconOverlay); + } + } + if (!this.s_DraggingPoint) + { + GUI.color = BlendTreeInspector.s_VisSamplerColor; + GUI.DrawTexture(position, BlendTreeInspector.styles.samplerIcon); + } + GUI.color = Color.white; + break; + } + if (this.m_ReorderableList.index >= 0 && motionToActiveMotionIndices[this.m_ReorderableList.index] < 0) + { + this.ShowHelp(area, EditorGUIUtility.TempContent("The selected child has no Motion assigned.")); + } + else + { + if (this.m_WarningMessage != null) + { + this.ShowHelp(area, EditorGUIUtility.TempContent(this.m_WarningMessage)); + } + } + } + private void ShowHelp(Rect area, GUIContent content) + { + float height = EditorStyles.helpBox.CalcHeight(content, area.width); + GUI.Label(new Rect(area.x, area.y, area.width, height), content, EditorStyles.helpBox); + } + private void ValidatePositions() + { + this.m_WarningMessage = null; + Vector2[] motionPositions = this.GetMotionPositions(); + bool flag = this.m_BlendRect.width == 0f || this.m_BlendRect.height == 0f; + for (int i = 0; i < motionPositions.Length; i++) + { + int num = 0; + while (num < i && !flag) + { + if (((motionPositions[i] - motionPositions[num]) / this.m_BlendRect.height).sqrMagnitude < 0.0001f) + { + flag = true; + break; + } + num++; + } + } + if (flag) + { + this.m_WarningMessage = "Two or more of the positions are too close to each other."; + return; + } + if (this.m_BlendType.intValue == 1) + { + List list = ( + from e in motionPositions + where e != Vector2.zero + select Mathf.Atan2(e.y, e.x) into e + orderby e + select e).ToList(); + float num2 = 0f; + float num3 = 180f; + for (int j = 0; j < list.Count; j++) + { + float num4 = list[(j + 1) % list.Count] - list[j]; + if (j == list.Count - 1) + { + num4 += 6.28318548f; + } + if (num4 > num2) + { + num2 = num4; + } + if (num4 < num3) + { + num3 = num4; + } + } + if (num2 * 57.29578f >= 180f) + { + this.m_WarningMessage = "Simple Directional blend should have motions with directions less than 180 degrees apart."; + } + else + { + if (num3 * 57.29578f < 2f) + { + this.m_WarningMessage = "Simple Directional blend should not have multiple motions in almost the same direction."; + } + } + } + else + { + if (this.m_BlendType.intValue == 2) + { + bool flag2 = false; + for (int k = 0; k < motionPositions.Length; k++) + { + if (motionPositions[k] == Vector2.zero) + { + flag2 = true; + break; + } + } + if (!flag2) + { + this.m_WarningMessage = "Freeform Directional blend should have one motion at position (0,0) to avoid discontinuities."; + } + } + } + } + private void DrawWeightShape(Vector2 point, float weight, int pass) + { + if (weight <= 0f) + { + return; + } + point.x = Mathf.Round(point.x); + point.y = Mathf.Round(point.y); + float num = 20f * Mathf.Sqrt(weight); + Vector3[] array = new Vector3[this.kNumCirclePoints + 2]; + for (int i = 0; i < this.kNumCirclePoints; i++) + { + float num2 = (float)i / (float)this.kNumCirclePoints; + array[i + 1] = new Vector3(point.x + 0.5f, point.y + 0.5f, 0f) + new Vector3(Mathf.Sin(num2 * 2f * 3.14159274f), Mathf.Cos(num2 * 2f * 3.14159274f), 0f) * num; + } + array[0] = (array[this.kNumCirclePoints + 1] = (array[1] + array[this.kNumCirclePoints]) * 0.5f); + if (pass == 0) + { + Handles.color = BlendTreeInspector.s_VisWeightShapeColor; + Handles.DrawSolidDisc(point + new Vector2(0.5f, 0.5f), -Vector3.forward, num); + } + else + { + Handles.color = BlendTreeInspector.s_VisWeightLineColor; + Handles.DrawAAPolyLine(array); + } + } + private void DrawAnimation(float val, float min, float max, bool selected, Rect area) + { + float y = area.y; + Rect position = new Rect(min, y, val - min, area.height); + Rect position2 = new Rect(val, y, max - val, area.height); + BlendTreeInspector.styles.triangleLeft.Draw(position, selected, selected, false, false); + BlendTreeInspector.styles.triangleRight.Draw(position2, selected, selected, false, false); + area.height -= 1f; + Color color = Handles.color; + Color color2 = (!selected) ? new Color(1f, 1f, 1f, 0.4f) : new Color(1f, 1f, 1f, 0.6f); + Handles.color = color2; + if (selected) + { + Handles.DrawLine(new Vector3(val, y, 0f), new Vector3(val, y + area.height, 0f)); + } + Vector3[] points = new Vector3[] + { + new Vector3(min, y + area.height, 0f), + new Vector3(val, y, 0f) + }; + Handles.DrawAAPolyLine(points); + points = new Vector3[] + { + new Vector3(val, y, 0f), + new Vector3(max, y + area.height, 0f) + }; + Handles.DrawAAPolyLine(points); + Handles.color = color; + } + public void EndDragChild(ReorderableList list) + { + List list2 = new List(); + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(i); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); + list2.Add(serializedProperty.floatValue); + } + list2.Sort(); + for (int j = 0; j < this.m_Childs.arraySize; j++) + { + SerializedProperty arrayElementAtIndex2 = this.m_Childs.GetArrayElementAtIndex(j); + SerializedProperty serializedProperty2 = arrayElementAtIndex2.FindPropertyRelative("m_Threshold"); + serializedProperty2.floatValue = list2[j]; + } + base.serializedObject.ApplyModifiedProperties(); + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + private void DrawHeader(Rect headerRect) + { + headerRect.xMin += 14f; + headerRect.y += 1f; + headerRect.height = 16f; + Rect[] rowRects = this.GetRowRects(headerRect, this.ParameterCount); + int num = 0; + rowRects[num].xMin = rowRects[num].xMin - 14f; + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Motion"), EditorStyles.label); + num++; + if (this.m_Childs.arraySize >= 1) + { + if (this.m_BlendType.intValue == 0) + { + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Threshold"), EditorStyles.label); + num++; + } + else + { + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos X"), EditorStyles.label); + num++; + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos Y"), EditorStyles.label); + num++; + } + GUI.Label(rowRects[num], BlendTreeInspector.styles.speedIcon, BlendTreeInspector.styles.headerIcon); + num++; + GUI.Label(rowRects[num], BlendTreeInspector.styles.mirrorIcon, BlendTreeInspector.styles.headerIcon); + } + } + public void AddButton(Rect rect, ReorderableList list) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Add Motion Field"), false, new GenericMenu.MenuFunction(this.AddChildAnimation)); + genericMenu.AddItem(EditorGUIUtility.TempContent("New Blend Tree"), false, new GenericMenu.MenuFunction(this.AddBlendTreeCallback)); + genericMenu.Popup(rect, 0); + } + public void RemoveButton(ReorderableList list) + { + this.m_Childs.DeleteArrayElementAtIndex(list.index); + if (list.index >= this.m_Childs.arraySize) + { + list.index = this.m_Childs.arraySize - 1; + } + this.SetMinMaxThresholds(); + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + private Rect[] GetRowRects(Rect r, int parameterCount) + { + Rect[] array = new Rect[3 + parameterCount]; + float num = r.width; + float num2 = 16f; + num -= num2; + num -= (float)(24 + 4 * (parameterCount - 1)); + float num3 = (float)Mathf.FloorToInt(num * 0.2f); + float num4 = num - num3 * (float)(parameterCount + 1); + float num5 = r.x; + int num6 = 0; + array[num6] = new Rect(num5, r.y, num4, r.height); + num5 += num4 + 8f; + num6++; + for (int i = 0; i < parameterCount; i++) + { + array[num6] = new Rect(num5, r.y, num3, r.height); + num5 += num3 + 4f; + num6++; + } + num5 += 4f; + array[num6] = new Rect(num5, r.y, num3, r.height); + num5 += num3 + 8f; + num6++; + array[num6] = new Rect(num5, r.y, num2, r.height); + return array; + } + public void DrawChild(Rect r, int index, bool isActive, bool isFocused) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(index); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Motion"); + r.y += 1f; + r.height = 16f; + Rect[] rowRects = this.GetRowRects(r, this.ParameterCount); + int num = 0; + EditorGUI.BeginChangeCheck(); + Motion motion = this.m_BlendTree.GetMotion(index); + EditorGUI.PropertyField(rowRects[num], serializedProperty, GUIContent.none); + num++; + if (EditorGUI.EndChangeCheck()) + { + if (motion is BlendTree && motion != serializedProperty.objectReferenceValue as Motion) + { + if (EditorUtility.DisplayDialog("Changing BlendTree will delete previous BlendTree", "You cannot undo this action.", "Delete", "Cancel")) + { + MecanimUtilities.DestroyBlendTreeRecursive(motion as BlendTree); + } + else + { + serializedProperty.objectReferenceValue = motion; + } + } + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + if (this.ParameterCount == 1) + { + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); + EditorGUI.BeginDisabledGroup(this.m_UseAutomaticThresholds.boolValue); + float floatValue = serializedProperty2.floatValue; + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(rowRects[num], floatValue.ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.textField); + num++; + if (EditorGUI.EndChangeCheck() && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out floatValue)) + { + serializedProperty2.floatValue = floatValue; + base.serializedObject.ApplyModifiedProperties(); + this.m_BlendTree.SortChildren(); + this.SetMinMaxThresholds(); + GUI.changed = true; + } + EditorGUI.EndDisabledGroup(); + } + else + { + SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("m_Position"); + Vector2 vector2Value = serializedProperty3.vector2Value; + for (int i = 0; i < 2; i++) + { + EditorGUI.BeginChangeCheck(); + string s2 = EditorGUI.DelayedTextField(rowRects[num], vector2Value[i].ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.textField); + num++; + float value; + if (EditorGUI.EndChangeCheck() && float.TryParse(s2, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out value)) + { + vector2Value[i] = Mathf.Clamp(value, -10000f, 10000f); + serializedProperty3.vector2Value = vector2Value; + base.serializedObject.ApplyModifiedProperties(); + this.m_DirtyVisualization = true; + GUI.changed = true; + } + } + } + if (serializedProperty.objectReferenceValue is AnimationClip) + { + SerializedProperty property = arrayElementAtIndex.FindPropertyRelative("m_TimeScale"); + EditorGUI.PropertyField(rowRects[num], property, GUIContent.none); + } + else + { + EditorGUI.BeginDisabledGroup(true); + EditorGUI.IntField(rowRects[num], 1); + EditorGUI.EndDisabledGroup(); + } + num++; + if (serializedProperty.objectReferenceValue is AnimationClip && (serializedProperty.objectReferenceValue as AnimationClip).isHumanMotion) + { + SerializedProperty serializedProperty4 = arrayElementAtIndex.FindPropertyRelative("m_Mirror"); + EditorGUI.PropertyField(rowRects[num], serializedProperty4, GUIContent.none); + SerializedProperty serializedProperty5 = arrayElementAtIndex.FindPropertyRelative("m_CycleOffset"); + serializedProperty5.floatValue = ((!serializedProperty4.boolValue) ? 0f : 0.5f); + } + else + { + EditorGUI.BeginDisabledGroup(true); + EditorGUI.Toggle(rowRects[num], false); + EditorGUI.EndDisabledGroup(); + } + } + private bool AllMotions() + { + bool flag = true; + int num = 0; + while (num < this.m_Childs.arraySize && flag) + { + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(num).FindPropertyRelative("m_Motion"); + flag = (serializedProperty.objectReferenceValue is AnimationClip); + num++; + } + return flag; + } + private void AutoCompute() + { + if (this.ParameterCount == 1) + { + EditorGUILayout.PropertyField(this.m_UseAutomaticThresholds, EditorGUIUtility.TempContent("Automate Thresholds"), new GUILayoutOption[0]); + this.m_ShowCompute.target = !this.m_UseAutomaticThresholds.boolValue; + } + else + { + this.m_ShowCompute.target = true; + } + this.m_ShowAdjust.target = this.AllMotions(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowCompute.faded)) + { + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + GUIContent label = (this.ParameterCount != 1) ? EditorGUIUtility.TempContent("Compute Positions") : EditorGUIUtility.TempContent("Compute Thresholds"); + rect = EditorGUI.PrefixLabel(rect, 0, label); + if (EditorGUI.ButtonMouseDown(rect, EditorGUIUtility.TempContent("Select"), FocusType.Passive, EditorStyles.popup)) + { + GenericMenu genericMenu = new GenericMenu(); + if (this.ParameterCount == 1) + { + this.AddComputeMenuItems(genericMenu, string.Empty, BlendTreeInspector.ChildPropertyToCompute.Threshold); + } + else + { + genericMenu.AddItem(new GUIContent("Velocity XZ"), false, new GenericMenu.MenuFunction(this.ComputePositionsFromVelocity)); + genericMenu.AddItem(new GUIContent("Speed And Angular Speed"), false, new GenericMenu.MenuFunction(this.ComputePositionsFromSpeedAndAngularSpeed)); + this.AddComputeMenuItems(genericMenu, "X Position From/", BlendTreeInspector.ChildPropertyToCompute.PositionX); + this.AddComputeMenuItems(genericMenu, "Y Position From/", BlendTreeInspector.ChildPropertyToCompute.PositionY); + } + genericMenu.DropDown(rect); + } + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowAdjust.faded)) + { + Rect rect2 = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect2 = EditorGUI.PrefixLabel(rect2, 0, EditorGUIUtility.TempContent("Adjust Time Scale")); + if (EditorGUI.ButtonMouseDown(rect2, EditorGUIUtility.TempContent("Select"), FocusType.Passive, EditorStyles.popup)) + { + GenericMenu genericMenu2 = new GenericMenu(); + genericMenu2.AddItem(new GUIContent("Homogeneous Speed"), false, new GenericMenu.MenuFunction(this.ComputeTimeScaleFromSpeed)); + genericMenu2.AddItem(new GUIContent("Reset Time Scale"), false, new GenericMenu.MenuFunction(this.ResetTimeScale)); + genericMenu2.DropDown(rect2); + } + } + EditorGUILayout.EndFadeGroup(); + } + private void AddComputeMenuItems(GenericMenu menu, string menuItemPrefix, BlendTreeInspector.ChildPropertyToCompute prop) + { + menu.AddItem(new GUIContent(menuItemPrefix + "Speed"), false, new GenericMenu.MenuFunction2(this.ComputeFromSpeed), prop); + menu.AddItem(new GUIContent(menuItemPrefix + "Velocity X"), false, new GenericMenu.MenuFunction2(this.ComputeFromVelocityX), prop); + menu.AddItem(new GUIContent(menuItemPrefix + "Velocity Y"), false, new GenericMenu.MenuFunction2(this.ComputeFromVelocityY), prop); + menu.AddItem(new GUIContent(menuItemPrefix + "Velocity Z"), false, new GenericMenu.MenuFunction2(this.ComputeFromVelocityZ), prop); + menu.AddItem(new GUIContent(menuItemPrefix + "Angular Speed (Rad)"), false, new GenericMenu.MenuFunction2(this.ComputeFromAngularSpeedRadians), prop); + menu.AddItem(new GUIContent(menuItemPrefix + "Angular Speed (Deg)"), false, new GenericMenu.MenuFunction2(this.ComputeFromAngularSpeedDegrees), prop); + } + private void ComputeFromSpeed(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.apparentSpeed, prop); + } + private void ComputeFromVelocityX(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.x * mirrorMultiplier, prop); + } + private void ComputeFromVelocityY(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.y, prop); + } + private void ComputeFromVelocityZ(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.z, prop); + } + private void ComputeFromAngularSpeedDegrees(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.averageAngularSpeed * 180f / 3.14159274f * mirrorMultiplier, prop); + } + private void ComputeFromAngularSpeedRadians(object obj) + { + BlendTreeInspector.ChildPropertyToCompute prop = (BlendTreeInspector.ChildPropertyToCompute)((int)obj); + this.ComputeProperty((Motion m, float mirrorMultiplier) => m.averageAngularSpeed * mirrorMultiplier, prop); + } + private void ComputeProperty(BlendTreeInspector.GetFloatFromMotion func, BlendTreeInspector.ChildPropertyToCompute prop) + { + this.m_UseAutomaticThresholds.boolValue = false; + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion"); + SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Mirror"); + Motion motion = serializedProperty.objectReferenceValue as Motion; + if (motion != null) + { + float num = func(motion, (float)((!serializedProperty2.boolValue) ? 1 : -1)); + if (prop == BlendTreeInspector.ChildPropertyToCompute.Threshold) + { + SerializedProperty serializedProperty3 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Threshold"); + serializedProperty3.floatValue = num; + } + else + { + SerializedProperty serializedProperty4 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Position"); + Vector2 vector2Value = serializedProperty4.vector2Value; + if (prop == BlendTreeInspector.ChildPropertyToCompute.PositionX) + { + vector2Value.x = num; + } + else + { + vector2Value.y = num; + } + serializedProperty4.vector2Value = vector2Value; + } + } + } + this.m_SerializedObject.ApplyModifiedProperties(); + if (prop == BlendTreeInspector.ChildPropertyToCompute.Threshold) + { + this.SortByThreshold(); + this.SetMinMaxThreshold(); + } + this.m_DirtyVisualization = true; + } + private void ComputePositionsFromVelocity() + { + this.ComputeFromVelocityX(BlendTreeInspector.ChildPropertyToCompute.PositionX); + this.ComputeFromVelocityZ(BlendTreeInspector.ChildPropertyToCompute.PositionY); + } + private void ComputePositionsFromSpeedAndAngularSpeed() + { + this.ComputeFromAngularSpeedRadians(BlendTreeInspector.ChildPropertyToCompute.PositionX); + this.ComputeFromSpeed(BlendTreeInspector.ChildPropertyToCompute.PositionY); + } + private void ComputeTimeScaleFromSpeed() + { + float apparentSpeed = this.m_BlendTree.apparentSpeed; + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion"); + AnimationClip animationClip = serializedProperty.objectReferenceValue as AnimationClip; + if (animationClip != null) + { + if (animationClip.isAnimatorMotion) + { + if (animationClip.apparentSpeed < 1.401298E-45f) + { + UnityEngine.Debug.LogWarning("Could not adjust time scale for " + animationClip.name + " because it has no speed"); + } + else + { + SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_TimeScale"); + serializedProperty2.floatValue = apparentSpeed / animationClip.apparentSpeed; + } + } + else + { + UnityEngine.Debug.LogWarning("Could not adjust time scale for " + animationClip.name + " because it is not a muscle clip"); + } + } + } + this.m_SerializedObject.ApplyModifiedProperties(); + } + private void ResetTimeScale() + { + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion"); + AnimationClip animationClip = serializedProperty.objectReferenceValue as AnimationClip; + if (animationClip != null && animationClip.isAnimatorMotion) + { + SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_TimeScale"); + serializedProperty2.floatValue = 1f; + } + } + this.m_SerializedObject.ApplyModifiedProperties(); + } + private void SortByThreshold() + { + this.m_SerializedObject.Update(); + for (int i = 0; i < this.m_Childs.arraySize; i++) + { + float num = float.PositiveInfinity; + int num2 = -1; + for (int j = i; j < this.m_Childs.arraySize; j++) + { + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(j); + float floatValue = arrayElementAtIndex.FindPropertyRelative("m_Threshold").floatValue; + if (floatValue < num) + { + num = floatValue; + num2 = j; + } + } + if (num2 != i) + { + this.m_Childs.MoveArrayElement(num2, i); + } + } + this.m_SerializedObject.ApplyModifiedProperties(); + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + private void SetMinMaxThreshold() + { + this.m_SerializedObject.Update(); + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(0).FindPropertyRelative("m_Threshold"); + SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(this.m_Childs.arraySize - 1).FindPropertyRelative("m_Threshold"); + this.m_MinThreshold.floatValue = Mathf.Min(serializedProperty.floatValue, serializedProperty2.floatValue); + this.m_MaxThreshold.floatValue = Mathf.Max(serializedProperty.floatValue, serializedProperty2.floatValue); + this.m_SerializedObject.ApplyModifiedProperties(); + } + private void AddChildAnimation() + { + Undo.RegisterCompleteObjectUndo(this.m_BlendTree, "Child animation added"); + this.m_BlendTree.AddAnimationClip(null); + this.SetNewThresholdAndPosition(this.m_BlendTree.childCount - 1); + this.m_ReorderableList.index = this.m_Childs.arraySize - 1; + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + private void AddBlendTreeCallback() + { + Undo.RegisterCompleteObjectUndo(this.m_BlendTree, "Child blendtree added"); + BlendTree blendTree = this.m_BlendTree.AddNewBlendTree(); + blendTree.name = "Blend Tree"; + blendTree.blendParameter = this.m_BlendTree.blendParameter; + this.SetNewThresholdAndPosition(this.m_BlendTree.childCount - 1); + this.m_ReorderableList.index = this.m_Childs.arraySize - 1; + this.m_HierarchyChanged = true; + this.m_DirtyVisualization = true; + } + private void SetNewThresholdAndPosition(int index) + { + base.serializedObject.Update(); + if (!this.m_UseAutomaticThresholds.boolValue) + { + float floatValue3; + if (this.m_Childs.arraySize >= 3 && index == this.m_Childs.arraySize - 1) + { + float floatValue = this.m_Childs.GetArrayElementAtIndex(index - 2).FindPropertyRelative("m_Threshold").floatValue; + float floatValue2 = this.m_Childs.GetArrayElementAtIndex(index - 1).FindPropertyRelative("m_Threshold").floatValue; + floatValue3 = floatValue2 + (floatValue2 - floatValue); + } + else + { + if (this.m_Childs.arraySize == 1) + { + floatValue3 = 0f; + } + else + { + floatValue3 = this.m_Childs.GetArrayElementAtIndex(this.m_Childs.arraySize - 1).FindPropertyRelative("m_Threshold").floatValue + 1f; + } + } + SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(index).FindPropertyRelative("m_Threshold"); + serializedProperty.floatValue = floatValue3; + this.SetMinMaxThresholds(); + } + Vector2 vector = Vector2.zero; + if (this.m_Childs.arraySize >= 1) + { + Vector2 center = this.m_BlendRect.center; + Vector2[] motionPositions = this.GetMotionPositions(); + float num = this.m_BlendRect.width * 0.07f; + for (int i = 0; i < 24; i++) + { + bool flag = true; + int num2 = 0; + while (num2 < motionPositions.Length && flag) + { + if (num2 != index && Vector2.Distance(motionPositions[num2], vector) < num) + { + flag = false; + } + num2++; + } + if (flag) + { + break; + } + float f = (float)(i * 15) * 0.0174532924f; + vector = center + new Vector2(-Mathf.Cos(f), Mathf.Sin(f)) * 0.37f * this.m_BlendRect.width; + vector.x = MathUtils.RoundBasedOnMinimumDifference(vector.x, this.m_BlendRect.width * 0.005f); + vector.y = MathUtils.RoundBasedOnMinimumDifference(vector.y, this.m_BlendRect.width * 0.005f); + } + } + SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(index).FindPropertyRelative("m_Position"); + serializedProperty2.vector2Value = vector; + base.serializedObject.ApplyModifiedProperties(); + } + public override bool HasPreviewGUI() + { + return this.m_PreviewBlendTree != null && this.m_PreviewBlendTree.HasPreviewGUI(); + } + public override void OnPreviewSettings() + { + if (this.m_PreviewBlendTree != null) + { + this.m_PreviewBlendTree.OnPreviewSettings(); + } + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + if (this.m_PreviewBlendTree != null) + { + this.m_PreviewBlendTree.OnInteractivePreviewGUI(r, background); + } + } + public void OnDisable() + { + if (this.m_PreviewBlendTree != null) + { + this.m_PreviewBlendTree.OnDisable(); + } + } + public void OnDestroy() + { + if (this.m_PreviewBlendTree != null) + { + this.m_PreviewBlendTree.OnDestroy(); + } + if (this.m_VisBlendTree != null) + { + this.m_VisBlendTree.Destroy(); + } + if (this.m_VisInstance != null) + { + UnityEngine.Object.DestroyImmediate(this.m_VisInstance); + } + for (int i = 0; i < this.m_WeightTexs.Count; i++) + { + UnityEngine.Object.DestroyImmediate(this.m_WeightTexs[i]); + } + if (this.m_BlendTex != null) + { + UnityEngine.Object.DestroyImmediate(this.m_BlendTex); + } + } + public void DoHierarchyChangedCallback() + { + if (this.m_HierarchyChanged && BlendTreeInspector.blendTreeHierarchyChanged != null) + { + BlendTreeInspector.blendTreeHierarchyChanged(this.m_BlendTree); + } + this.m_HierarchyChanged = false; + } + } +} diff --git a/UnityEditor/UnityEditor/BodyMaskEditor.cs b/UnityEditor/UnityEditor/BodyMaskEditor.cs new file mode 100644 index 00000000..88bcfb8f --- /dev/null +++ b/UnityEditor/UnityEditor/BodyMaskEditor.cs @@ -0,0 +1,138 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class BodyMaskEditor + { + private class Styles + { + public GUIContent UnityDude = EditorGUIUtility.IconContent("AvatarInspector/BodySIlhouette"); + public GUIContent PickingTexture = EditorGUIUtility.IconContent("AvatarInspector/BodyPartPicker"); + public GUIContent[] BodyPart = new GUIContent[] + { + EditorGUIUtility.IconContent("AvatarInspector/MaskEditor_Root"), + EditorGUIUtility.IconContent("AvatarInspector/Torso"), + EditorGUIUtility.IconContent("AvatarInspector/Head"), + EditorGUIUtility.IconContent("AvatarInspector/LeftLeg"), + EditorGUIUtility.IconContent("AvatarInspector/RightLeg"), + EditorGUIUtility.IconContent("AvatarInspector/LeftArm"), + EditorGUIUtility.IconContent("AvatarInspector/RightArm"), + EditorGUIUtility.IconContent("AvatarInspector/LeftFingers"), + EditorGUIUtility.IconContent("AvatarInspector/RightFingers"), + EditorGUIUtility.IconContent("AvatarInspector/LeftFeetIk"), + EditorGUIUtility.IconContent("AvatarInspector/RightFeetIk"), + EditorGUIUtility.IconContent("AvatarInspector/LeftFingersIk"), + EditorGUIUtility.IconContent("AvatarInspector/RightFingersIk") + }; + } + private static BodyMaskEditor.Styles styles = new BodyMaskEditor.Styles(); + protected static Color[] m_MaskBodyPartPicker = new Color[] + { + new Color(1f, 0.5647059f, 0f), + new Color(0f, 0.68235296f, 0.9411765f), + new Color(0.670588255f, 0.627451f, 0f), + new Color(0f, 1f, 1f), + new Color(0.968627453f, 0.5921569f, 0.4745098f), + new Color(0f, 1f, 0f), + new Color(0.3372549f, 0.454901963f, 0.7254902f), + new Color(1f, 1f, 0f), + new Color(0.509803951f, 0.7921569f, 0.6117647f), + new Color(0.321568638f, 0.321568638f, 0.321568638f), + new Color(1f, 0.4509804f, 0.4509804f), + new Color(0.623529434f, 0.623529434f, 0.623529434f), + new Color(0.7921569f, 0.7921569f, 0.7921569f), + new Color(0.396078438f, 0.396078438f, 0.396078438f) + }; + private static string sAvatarBodyMaskStr = "AvatarMask"; + private static int s_Hint = BodyMaskEditor.sAvatarBodyMaskStr.GetHashCode(); + public static bool[] Show(bool[] bodyPartToggle, int count) + { + if (BodyMaskEditor.styles.UnityDude.image) + { + Rect rect = GUILayoutUtility.GetRect(BodyMaskEditor.styles.UnityDude, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.MaxWidth((float)BodyMaskEditor.styles.UnityDude.image.width) + }); + rect.x += ((float)Screen.width - rect.width) / 2f; + Color color = GUI.color; + if (bodyPartToggle[0]) + { + GUI.color = Color.green; + } + else + { + GUI.color = Color.red; + } + if (BodyMaskEditor.styles.BodyPart[0].image) + { + GUI.DrawTexture(rect, BodyMaskEditor.styles.BodyPart[0].image); + } + GUI.color = new Color(0.2f, 0.2f, 0.2f, 1f); + GUI.DrawTexture(rect, BodyMaskEditor.styles.UnityDude.image); + for (int i = 1; i < count; i++) + { + if (bodyPartToggle[i]) + { + GUI.color = Color.green; + } + else + { + GUI.color = Color.red; + } + if (BodyMaskEditor.styles.BodyPart[i].image) + { + GUI.DrawTexture(rect, BodyMaskEditor.styles.BodyPart[i].image); + } + } + GUI.color = color; + BodyMaskEditor.DoPicking(rect, bodyPartToggle, count); + } + return bodyPartToggle; + } + protected static void DoPicking(Rect rect, bool[] bodyPartToggle, int count) + { + if (BodyMaskEditor.styles.PickingTexture.image) + { + int controlID = GUIUtility.GetControlID(BodyMaskEditor.s_Hint, FocusType.Native, rect); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.MouseDown) + { + if (rect.Contains(current.mousePosition)) + { + current.Use(); + int x = (int)current.mousePosition.x - (int)rect.x; + int y = BodyMaskEditor.styles.UnityDude.image.height - ((int)current.mousePosition.y - (int)rect.y); + Texture2D texture2D = BodyMaskEditor.styles.PickingTexture.image as Texture2D; + Color pixel = texture2D.GetPixel(x, y); + bool flag = false; + for (int i = 0; i < count; i++) + { + if (BodyMaskEditor.m_MaskBodyPartPicker[i] == pixel) + { + GUI.changed = true; + bodyPartToggle[i] = !bodyPartToggle[i]; + flag = true; + } + } + if (!flag) + { + bool flag2 = false; + int num = 0; + while (num < count && !flag2) + { + flag2 = bodyPartToggle[num]; + num++; + } + for (int j = 0; j < count; j++) + { + bodyPartToggle[j] = !flag2; + } + GUI.changed = true; + } + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/BodyPart.cs b/UnityEditor/UnityEditor/BodyPart.cs new file mode 100644 index 00000000..ffc9cf77 --- /dev/null +++ b/UnityEditor/UnityEditor/BodyPart.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + public enum BodyPart + { + None = -1, + Avatar, + Body, + Head, + LeftArm, + LeftFingers, + RightArm, + RightFingers, + LeftLeg, + RightLeg, + Last + } +} diff --git a/UnityEditor/UnityEditor/BoneState.cs b/UnityEditor/UnityEditor/BoneState.cs new file mode 100644 index 00000000..e8e57e6e --- /dev/null +++ b/UnityEditor/UnityEditor/BoneState.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum BoneState + { + None, + NotFound, + Duplicate, + InvalidHierarchy, + BoneLenghtIsZero, + Valid + } +} diff --git a/UnityEditor/UnityEditor/BoxCollider2DEditor.cs b/UnityEditor/UnityEditor/BoxCollider2DEditor.cs new file mode 100644 index 00000000..bc785d8d --- /dev/null +++ b/UnityEditor/UnityEditor/BoxCollider2DEditor.cs @@ -0,0 +1,53 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(BoxCollider2D))] + internal class BoxCollider2DEditor : Collider2DEditorBase + { + private static readonly int s_BoxHash = "BoxCollider2DEditor".GetHashCode(); + private readonly BoxEditor m_BoxEditor = new BoxEditor(true, BoxCollider2DEditor.s_BoxHash, true); + protected SerializedProperty m_Center; + protected SerializedProperty m_Size; + public override void OnEnable() + { + base.OnEnable(); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Size = base.serializedObject.FindProperty("m_Size"); + this.m_BoxEditor.OnEnable(); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + base.InspectorEditButtonGUI(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Size, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + base.CheckColliderErrorState(); + } + public override void OnDisable() + { + base.OnDisable(); + this.m_BoxEditor.OnDisable(); + } + public void OnSceneGUI() + { + if (!base.editingCollider) + { + return; + } + BoxCollider2D boxCollider2D = (BoxCollider2D)this.target; + Vector3 v = boxCollider2D.center; + Vector3 v2 = boxCollider2D.size; + if (this.m_BoxEditor.OnSceneGUI(boxCollider2D.transform, Handles.s_ColliderHandleColor, ref v, ref v2)) + { + Undo.RecordObject(boxCollider2D, "Modify collider"); + boxCollider2D.center = v; + boxCollider2D.size = v2; + } + } + } +} diff --git a/UnityEditor/UnityEditor/BoxColliderEditor.cs b/UnityEditor/UnityEditor/BoxColliderEditor.cs new file mode 100644 index 00000000..7ccfe90d --- /dev/null +++ b/UnityEditor/UnityEditor/BoxColliderEditor.cs @@ -0,0 +1,57 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(BoxCollider))] + internal class BoxColliderEditor : Collider3DEditorBase + { + private static readonly int s_BoxHash = "BoxColliderEditor".GetHashCode(); + private SerializedProperty m_Center; + private SerializedProperty m_Size; + private readonly BoxEditor m_BoxEditor = new BoxEditor(true, BoxColliderEditor.s_BoxHash); + public override void OnEnable() + { + base.OnEnable(); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Size = base.serializedObject.FindProperty("m_Size"); + this.m_BoxEditor.OnEnable(); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + } + public override void OnDisable() + { + base.OnDisable(); + this.m_BoxEditor.OnDisable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + base.InspectorEditButtonGUI(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Size, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public void OnSceneGUI() + { + if (!base.editingCollider) + { + return; + } + BoxCollider boxCollider = (BoxCollider)this.target; + Vector3 center = boxCollider.center; + Vector3 size = boxCollider.size; + Color color = Handles.s_ColliderHandleColor; + if (!boxCollider.enabled) + { + color = Handles.s_ColliderHandleColorDisabled; + } + if (this.m_BoxEditor.OnSceneGUI(boxCollider.transform, color, ref center, ref size)) + { + Undo.RecordObject(boxCollider, "Modified Box Collider"); + boxCollider.center = center; + boxCollider.size = size; + } + } + } +} diff --git a/UnityEditor/UnityEditor/BoxEditor.cs b/UnityEditor/UnityEditor/BoxEditor.cs new file mode 100644 index 00000000..6d7a6e46 --- /dev/null +++ b/UnityEditor/UnityEditor/BoxEditor.cs @@ -0,0 +1,282 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class BoxEditor + { + private const float kViewAngleThreshold = 0.05235988f; + private int m_ControlIdHint; + private int m_HandleControlID; + private bool m_UseLossyScale; + private bool m_AlwaysDisplayHandles; + private bool m_DisableZaxis; + public BoxEditor(bool useLossyScale, int controlIdHint) + { + this.m_UseLossyScale = useLossyScale; + this.m_ControlIdHint = controlIdHint; + } + public BoxEditor(bool useLossyScale, int controlIdHint, bool disableZaxis) + { + this.m_UseLossyScale = useLossyScale; + this.m_ControlIdHint = controlIdHint; + this.m_DisableZaxis = disableZaxis; + } + public void OnEnable() + { + this.m_HandleControlID = -1; + } + public void OnDisable() + { + } + public void SetAlwaysDisplayHandles(bool enable) + { + this.m_AlwaysDisplayHandles = enable; + } + public bool OnSceneGUI(Transform transform, Color color, ref Vector3 center, ref Vector3 size) + { + return this.OnSceneGUI(transform, color, true, ref center, ref size); + } + public bool OnSceneGUI(Transform transform, Color color, bool handlesOnly, ref Vector3 center, ref Vector3 size) + { + if (this.m_UseLossyScale) + { + Matrix4x4 transform2 = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); + size.Scale(transform.lossyScale); + center = transform.TransformPoint(center); + center = transform2.inverse.MultiplyPoint(center); + bool result = this.OnSceneGUI(transform2, color, handlesOnly, ref center, ref size); + center = transform2.MultiplyPoint(center); + center = transform.InverseTransformPoint(center); + size.Scale(new Vector3(1f / transform.lossyScale.x, 1f / transform.lossyScale.y, 1f / transform.lossyScale.z)); + return result; + } + return this.OnSceneGUI(transform.localToWorldMatrix, color, handlesOnly, ref center, ref size); + } + public bool OnSceneGUI(Matrix4x4 transform, Color color, bool handlesOnly, ref Vector3 center, ref Vector3 size) + { + bool flag = GUIUtility.hotControl == this.m_HandleControlID; + if (!this.m_AlwaysDisplayHandles && !flag) + { + for (int i = 0; i < 6; i++) + { + GUIUtility.GetControlID(this.m_ControlIdHint, FocusType.Keyboard); + } + return false; + } + Color color2 = Handles.color; + Handles.color = color; + Vector3 b = center - size * 0.5f; + Vector3 a = center + size * 0.5f; + Matrix4x4 matrix = Handles.matrix; + Handles.matrix = transform; + int hotControl = GUIUtility.hotControl; + if (!handlesOnly) + { + this.DrawWireframeBox((a - b) * 0.5f + b, a - b); + } + this.MidpointHandles(ref b, ref a, Handles.matrix); + if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) + { + this.m_HandleControlID = GUIUtility.hotControl; + } + bool changed = GUI.changed; + if (changed) + { + center = (a + b) * 0.5f; + size = a - b; + } + Handles.color = color2; + Handles.matrix = matrix; + return changed; + } + public void DrawWireframeBox(Vector3 center, Vector3 siz) + { + Vector3 vector = siz * 0.5f; + Vector3[] array = new Vector3[] + { + center + new Vector3(-vector.x, -vector.y, -vector.z), + center + new Vector3(-vector.x, vector.y, -vector.z), + center + new Vector3(vector.x, vector.y, -vector.z), + center + new Vector3(vector.x, -vector.y, -vector.z), + center + new Vector3(-vector.x, -vector.y, -vector.z), + center + new Vector3(-vector.x, -vector.y, vector.z), + center + new Vector3(-vector.x, vector.y, vector.z), + center + new Vector3(vector.x, vector.y, vector.z), + center + new Vector3(vector.x, -vector.y, vector.z), + center + new Vector3(-vector.x, -vector.y, vector.z) + }; + Handles.DrawPolyLine(array); + Handles.DrawLine(array[1], array[6]); + Handles.DrawLine(array[2], array[7]); + Handles.DrawLine(array[3], array[8]); + } + private void MidpointHandles(ref Vector3 minPos, ref Vector3 maxPos, Matrix4x4 transform) + { + Vector3 vector = new Vector3(1f, 0f, 0f); + Vector3 localTangent = new Vector3(0f, 1f, 0f); + Vector3 vector2 = new Vector3(0f, 0f, 1f); + Vector3 vector3 = (maxPos + minPos) * 0.5f; + Vector3 localPos = new Vector3(maxPos.x, vector3.y, vector3.z); + maxPos.x = this.MidpointHandle(localPos, localTangent, vector2, transform).x; + localPos = new Vector3(minPos.x, vector3.y, vector3.z); + minPos.x = this.MidpointHandle(localPos, localTangent, -vector2, transform).x; + localPos = new Vector3(vector3.x, maxPos.y, vector3.z); + maxPos.y = this.MidpointHandle(localPos, vector, -vector2, transform).y; + localPos = new Vector3(vector3.x, minPos.y, vector3.z); + minPos.y = this.MidpointHandle(localPos, vector, vector2, transform).y; + if (!this.m_DisableZaxis) + { + localPos = new Vector3(vector3.x, vector3.y, maxPos.z); + maxPos.z = this.MidpointHandle(localPos, localTangent, -vector, transform).z; + localPos = new Vector3(vector3.x, vector3.y, minPos.z); + minPos.z = this.MidpointHandle(localPos, localTangent, vector, transform).z; + } + } + private Vector3 MidpointHandle(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform) + { + Color color = Handles.color; + float num = 1f; + this.AdjustMidpointHandleColor(localPos, localTangent, localBinormal, transform, num); + int controlID = GUIUtility.GetControlID(this.m_ControlIdHint, FocusType.Keyboard); + if (num > 0f) + { + Vector3 normalized = Vector3.Cross(localTangent, localBinormal).normalized; + localPos = Slider1D.Do(controlID, localPos, normalized, HandleUtility.GetHandleSize(localPos) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), SnapSettings.scale); + } + Handles.color = color; + return localPos; + } + private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, float alphaFactor) + { + Vector3 b = transform.MultiplyPoint(localPos); + Vector3 lhs = transform.MultiplyVector(localTangent); + Vector3 rhs = transform.MultiplyVector(localBinormal); + Vector3 normalized = Vector3.Cross(lhs, rhs).normalized; + float num; + if (Camera.current.isOrthoGraphic) + { + num = Vector3.Dot(-Camera.current.transform.forward, normalized); + } + else + { + num = Vector3.Dot((Camera.current.transform.position - b).normalized, normalized); + } + if (num < -0.0001f) + { + alphaFactor *= Handles.backfaceAlphaMultiplier; + } + if (alphaFactor < 1f) + { + Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor); + } + } + private void EdgeHandles(ref Vector3 minPos, ref Vector3 maxPos, Matrix4x4 transform) + { + Vector3 vector = new Vector3(1f, 0f, 0f); + Vector3 vector2 = new Vector3(0f, 1f, 0f); + Vector3 vector3 = new Vector3(0f, 0f, 1f); + float z = (minPos.z + maxPos.z) * 0.5f; + Vector3 handlePos = new Vector3(minPos.x, minPos.y, z); + Vector3 vector4 = this.EdgeHandle(handlePos, vector, -vector, -vector2, transform); + minPos.x = vector4.x; + minPos.y = vector4.y; + handlePos = new Vector3(minPos.x, maxPos.y, z); + vector4 = this.EdgeHandle(handlePos, vector, -vector, vector2, transform); + minPos.x = vector4.x; + maxPos.y = vector4.y; + handlePos = new Vector3(maxPos.x, maxPos.y, z); + vector4 = this.EdgeHandle(handlePos, vector, vector, vector2, transform); + maxPos.x = vector4.x; + maxPos.y = vector4.y; + handlePos = new Vector3(maxPos.x, minPos.y, z); + vector4 = this.EdgeHandle(handlePos, vector, vector, -vector2, transform); + maxPos.x = vector4.x; + minPos.y = vector4.y; + float y = (minPos.y + maxPos.y) * 0.5f; + Vector3 handlePos2 = new Vector3(minPos.x, y, minPos.z); + Vector3 vector5 = this.EdgeHandle(handlePos2, vector2, -vector, -vector3, transform); + minPos.x = vector5.x; + minPos.z = vector5.z; + handlePos2 = new Vector3(minPos.x, y, maxPos.z); + vector5 = this.EdgeHandle(handlePos2, vector2, -vector, vector3, transform); + minPos.x = vector5.x; + maxPos.z = vector5.z; + handlePos2 = new Vector3(maxPos.x, y, maxPos.z); + vector5 = this.EdgeHandle(handlePos2, vector2, vector, vector3, transform); + maxPos.x = vector5.x; + maxPos.z = vector5.z; + handlePos2 = new Vector3(maxPos.x, y, minPos.z); + vector5 = this.EdgeHandle(handlePos2, vector2, vector, -vector3, transform); + maxPos.x = vector5.x; + minPos.z = vector5.z; + float x = (minPos.x + maxPos.x) * 0.5f; + Vector3 handlePos3 = new Vector3(x, minPos.y, minPos.z); + Vector3 vector6 = this.EdgeHandle(handlePos3, vector2, -vector2, -vector3, transform); + minPos.y = vector6.y; + minPos.z = vector6.z; + handlePos3 = new Vector3(x, minPos.y, maxPos.z); + vector6 = this.EdgeHandle(handlePos3, vector2, -vector2, vector3, transform); + minPos.y = vector6.y; + maxPos.z = vector6.z; + handlePos3 = new Vector3(x, maxPos.y, maxPos.z); + vector6 = this.EdgeHandle(handlePos3, vector2, vector2, vector3, transform); + maxPos.y = vector6.y; + maxPos.z = vector6.z; + handlePos3 = new Vector3(x, maxPos.y, minPos.z); + vector6 = this.EdgeHandle(handlePos3, vector2, vector2, -vector3, transform); + maxPos.y = vector6.y; + minPos.z = vector6.z; + } + private Vector3 EdgeHandle(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, Matrix4x4 transform) + { + Color color = Handles.color; + bool flag = true; + if (Camera.current) + { + Vector3 b = Handles.matrix.inverse.MultiplyPoint(Camera.current.transform.position); + Vector3 normalized = (handlePos - b).normalized; + Vector3 lhs = Vector3.Cross(slideDir1, slideDir2); + float f = Vector3.Dot(lhs, normalized); + if (Mathf.Acos(Mathf.Abs(f)) > 1.51843643f) + { + flag = false; + } + } + float num = (!flag) ? 0f : 1f; + this.AdjustEdgeHandleColor(handlePos, slideDir1, slideDir2, transform, num); + int controlID = GUIUtility.GetControlID(this.m_ControlIdHint, FocusType.Keyboard); + if (num > 0f) + { + handlePos = Slider2D.Do(controlID, handlePos, handleDir, slideDir1, slideDir2, HandleUtility.GetHandleSize(handlePos) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), SnapSettings.scale, true); + } + Handles.color = color; + return handlePos; + } + private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 slideDir2, Matrix4x4 transform, float alphaFactor) + { + Vector3 inPoint = transform.MultiplyPoint(handlePos); + Vector3 normalized = transform.MultiplyVector(slideDir1).normalized; + Vector3 normalized2 = transform.MultiplyVector(slideDir2).normalized; + bool flag; + if (Camera.current.isOrthoGraphic) + { + flag = (Vector3.Dot(-Camera.current.transform.forward, normalized) < 0f && Vector3.Dot(-Camera.current.transform.forward, normalized2) < 0f); + } + else + { + Plane plane = new Plane(normalized, inPoint); + Plane plane2 = new Plane(normalized2, inPoint); + flag = (!plane.GetSide(Camera.current.transform.position) && !plane2.GetSide(Camera.current.transform.position)); + } + if (flag) + { + alphaFactor *= Handles.backfaceAlphaMultiplier; + } + if (alphaFactor < 1f) + { + Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * alphaFactor); + } + } + } +} diff --git a/UnityEditor/UnityEditor/Brush.cs b/UnityEditor/UnityEditor/Brush.cs new file mode 100644 index 00000000..e45f981e --- /dev/null +++ b/UnityEditor/UnityEditor/Brush.cs @@ -0,0 +1,110 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class Brush + { + internal const int kMinBrushSize = 3; + private float[] m_Strength; + private int m_Size; + private Texture2D m_Brush; + private Texture2D m_Preview; + private Projector m_BrushProjector; + public bool Load(Texture2D brushTex, int size) + { + if (this.m_Brush == brushTex && size == this.m_Size && this.m_Strength != null) + { + return true; + } + if (brushTex != null) + { + float num = (float)size; + this.m_Size = size; + this.m_Strength = new float[this.m_Size * this.m_Size]; + if (this.m_Size > 3) + { + for (int i = 0; i < this.m_Size; i++) + { + for (int j = 0; j < this.m_Size; j++) + { + this.m_Strength[i * this.m_Size + j] = brushTex.GetPixelBilinear(((float)j + 0.5f) / num, (float)i / num).a; + } + } + } + else + { + for (int k = 0; k < this.m_Strength.Length; k++) + { + this.m_Strength[k] = 1f; + } + } + UnityEngine.Object.DestroyImmediate(this.m_Preview); + this.m_Preview = new Texture2D(this.m_Size, this.m_Size, TextureFormat.ARGB32, false); + this.m_Preview.hideFlags = HideFlags.HideAndDontSave; + this.m_Preview.wrapMode = TextureWrapMode.Repeat; + this.m_Preview.filterMode = FilterMode.Point; + Color[] array = new Color[this.m_Size * this.m_Size]; + for (int l = 0; l < array.Length; l++) + { + array[l] = new Color(1f, 1f, 1f, this.m_Strength[l]); + } + this.m_Preview.SetPixels(0, 0, this.m_Size, this.m_Size, array, 0); + this.m_Preview.Apply(); + if (this.m_BrushProjector == null) + { + this.CreatePreviewBrush(); + } + this.m_BrushProjector.material.mainTexture = this.m_Preview; + this.m_Brush = brushTex; + return true; + } + this.m_Strength = new float[1]; + this.m_Strength[0] = 1f; + this.m_Size = 1; + return false; + } + public float GetStrengthInt(int ix, int iy) + { + ix = Mathf.Clamp(ix, 0, this.m_Size - 1); + iy = Mathf.Clamp(iy, 0, this.m_Size - 1); + return this.m_Strength[iy * this.m_Size + ix]; + } + public void Dispose() + { + if (this.m_BrushProjector) + { + UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.material.shader); + UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.material); + UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.gameObject); + this.m_BrushProjector = null; + } + UnityEngine.Object.DestroyImmediate(this.m_Preview); + this.m_Preview = null; + } + public Projector GetPreviewProjector() + { + return this.m_BrushProjector; + } + private void CreatePreviewBrush() + { + GameObject gameObject = EditorUtility.CreateGameObjectWithHideFlags("TerrainInspectorBrushPreview", HideFlags.HideAndDontSave, new Type[] + { + typeof(Projector) + }); + this.m_BrushProjector = (gameObject.GetComponent(typeof(Projector)) as Projector); + this.m_BrushProjector.enabled = false; + this.m_BrushProjector.nearClipPlane = -1000f; + this.m_BrushProjector.farClipPlane = 1000f; + this.m_BrushProjector.orthographic = true; + this.m_BrushProjector.orthographicSize = 10f; + this.m_BrushProjector.transform.Rotate(90f, 0f, 0f); + Material material = new Material("Shader \"Hidden/Terrain Brush Preview\" {\nProperties {\n\t_MainTex (\"Main\", 2D) = \"gray\" { TexGen ObjectLinear }\n\t_CutoutTex (\"Cutout\", 2D) = \"black\" { TexGen ObjectLinear }\n}\nSubshader {\n\tZWrite Off\n\tOffset -1, -1\n\tFog { Mode Off }\n\tAlphaTest Greater 0\n\tColorMask RGB\n\tPass\n\t{\n\t\tBlend SrcAlpha OneMinusSrcAlpha\n\t\tSetTexture [_MainTex]\n\t\t{\n\t\t\tconstantColor (.2,.7,1,.5)\n\t\t\tcombine constant, texture * constant\n\t\t\tMatrix [_Projector]\n\t\t}\n\n\t\tSetTexture [_CutoutTex]\n\t\t{\n\t\t\tcombine previous, previous * texture\n\t\t\tMatrix [_Projector]\n\t\t}\n\t}\n}\n}"); + material.shader.hideFlags = HideFlags.HideAndDontSave; + material.hideFlags = HideFlags.HideAndDontSave; + material.SetTexture("_CutoutTex", (Texture2D)EditorGUIUtility.Load(EditorResourcesUtility.brushesPath + "brush_cutout.png")); + this.m_BrushProjector.material = material; + this.m_BrushProjector.enabled = false; + } + } +} diff --git a/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs b/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs new file mode 100644 index 00000000..6b36bec3 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum BuildAssetBundleOptions + { + CollectDependencies = 1048576, + CompleteAssets = 2097152, + DisableWriteTypeTree = 67108864, + DeterministicAssetBundle = 268435456, + UncompressedAssetBundle = 2048 + } +} diff --git a/UnityEditor/UnityEditor/BuildOptions.cs b/UnityEditor/UnityEditor/BuildOptions.cs new file mode 100644 index 00000000..790c4c04 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildOptions.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum BuildOptions + { + None = 0, + Development = 1, + AutoRunPlayer = 4, + ShowBuiltPlayer = 8, + BuildAdditionalStreamedScenes = 16, + AcceptExternalModificationsToPlayer = 32, + InstallInBuildFolder = 64, + WebPlayerOfflineDeployment = 128, + ConnectWithProfiler = 256, + AllowDebugging = 512, + SymlinkLibraries = 1024, + UncompressedAssetBundle = 2048, + StripDebugSymbols = 0, + CompressTextures = 0, + ConnectToHost = 4096, + DeployOnline = 8192, + EnableHeadlessMode = 16384, + Il2CPP = 65536 + } +} diff --git a/UnityEditor/UnityEditor/BuildPackageResult.cs b/UnityEditor/UnityEditor/BuildPackageResult.cs new file mode 100644 index 00000000..c4d8f8c0 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildPackageResult.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class BuildPackageResult : AssetStoreResultBase + { + internal AssetStoreAsset asset; + internal int packageID; + internal BuildPackageResult(AssetStoreAsset asset, AssetStoreResultBase.Callback c) : base(c) + { + this.asset = asset; + this.packageID = -1; + } + protected override void Parse(Dictionary dict) + { + dict = dict["download"].AsDict(); + this.packageID = int.Parse(dict["id"].AsString()); + if (this.packageID != this.asset.packageID) + { + Debug.LogError("Got asset store server build result from mismatching package"); + return; + } + this.asset.previewInfo.packageUrl = ((!dict.ContainsKey("url")) ? string.Empty : dict["url"].AsString(true)); + this.asset.previewInfo.encryptionKey = ((!dict.ContainsKey("key")) ? string.Empty : dict["key"].AsString(true)); + this.asset.previewInfo.buildProgress = ((!dict["progress"].IsFloat()) ? float.Parse(dict["progress"].AsString(true)) : dict["progress"].AsFloat(true)) / 100f; + } + } +} diff --git a/UnityEditor/UnityEditor/BuildPipeline.cs b/UnityEditor/UnityEditor/BuildPipeline.cs new file mode 100644 index 00000000..2e6b534d --- /dev/null +++ b/UnityEditor/UnityEditor/BuildPipeline.cs @@ -0,0 +1,226 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class BuildPipeline + { + public static extern bool isBuildingPlayer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern BuildTargetGroup GetBuildTargetGroup(BuildTarget platform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetBuildTargetGroupDisplayName(BuildTargetGroup targetPlatformGroup); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PushAssetDependencies(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PopAssetDependencies(); + private static void LogBuildExceptionAndExit(string buildFunctionName, Exception exception) + { + Debug.LogError(string.Format("Internal Error in {0}:", buildFunctionName)); + Debug.LogException(exception); + EditorApplication.Exit(1); + } + public static string BuildPlayer(string[] levels, string locationPathName, BuildTarget target, BuildOptions options) + { + string result; + try + { + uint num; + result = BuildPipeline.BuildPlayerInternal(levels, locationPathName, target, options, out num); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildPlayer", exception); + result = string.Empty; + } + return result; + } + [ExcludeFromDocs] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target) + { + BuildOptions options = BuildOptions.None; + return BuildPipeline.BuildStreamedSceneAssetBundle(levels, locationPath, target, options); + } + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, [DefaultValue("0")] BuildOptions options) + { + return BuildPipeline.BuildPlayer(levels, locationPath, target, options | BuildOptions.BuildAdditionalStreamedScenes); + } + [ExcludeFromDocs] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc) + { + BuildOptions options = BuildOptions.None; + return BuildPipeline.BuildStreamedSceneAssetBundle(levels, locationPath, target, out crc, options); + } + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc, [DefaultValue("0")] BuildOptions options) + { + crc = 0u; + string result; + try + { + result = BuildPipeline.BuildPlayerInternal(levels, locationPath, target, options | BuildOptions.BuildAdditionalStreamedScenes, out crc); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildStreamedSceneAssetBundle", exception); + result = string.Empty; + } + return result; + } + private static string BuildPlayerInternal(string[] levels, string locationPathName, BuildTarget target, BuildOptions options, out uint crc) + { + crc = 0u; + if (!InternalEditorUtility.HasPro()) + { + Debug.LogError("Building Player from editor scripts requires Unity PRO"); + return "Building Player from editor scripts requires Unity PRO"; + } + if ((BuildOptions.EnableHeadlessMode & options) != BuildOptions.None && (BuildOptions.Development & options) != BuildOptions.None) + { + return "Unsupported build setting: cannot build headless development player"; + } + return BuildPipeline.BuildPlayerInternalNoCheck(levels, locationPathName, target, options, false, out crc); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string BuildPlayerInternalNoCheck(string[] levels, string locationPathName, BuildTarget target, BuildOptions options, bool delayToAfterScriptReload, out uint crc); + [ExcludeFromDocs] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, BuildAssetBundleOptions assetBundleOptions) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, assetBundleOptions, targetPlatform); + } + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + { + uint num; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out num, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out crc, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out crc, assetBundleOptions, targetPlatform); + } + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + { + crc = 0u; + bool result; + try + { + result = BuildPipeline.BuildAssetBundleInternal(mainAsset, assets, null, pathName, assetBundleOptions, targetPlatform, out crc); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundle", exception); + result = false; + } + return result; + } + [ExcludeFromDocs] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions, targetPlatform); + } + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + { + uint num; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out num, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions, targetPlatform); + } + [ExcludeFromDocs] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions, targetPlatform); + } + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + { + crc = 0u; + bool result; + try + { + result = BuildPipeline.BuildAssetBundleInternal(null, assets, assetNames, pathName, assetBundleOptions, targetPlatform, out crc); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundleExplicitAssetNames", exception); + result = false; + } + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool BuildAssetBundleInternal(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform, out uint crc); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool LicenseCheck(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsBuildTargetSupported(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetBuildTargetAdvancedLicenseName(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPlaybackEngineDirectory(BuildTarget target, BuildOptions options); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPlaybackEngineDirectory(BuildTarget target, BuildOptions options, string playbackEngineDirectory); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetBuildToolsDirectory(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetMonoBinDirectory(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetMonoLibDirectory(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetMonoProfileLibDirectory(BuildTarget target, string profile); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetBuildTargetGroupName(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsUnityScriptEvalSupported(BuildTarget target); + } +} diff --git a/UnityEditor/UnityEditor/BuildPlayerWindow.cs b/UnityEditor/UnityEditor/BuildPlayerWindow.cs new file mode 100644 index 00000000..c48304b4 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildPlayerWindow.cs @@ -0,0 +1,1760 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEditor.Modules; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class BuildPlayerWindow : EditorWindow + { + public class SceneSorter : IComparer + { + int IComparer.Compare(object x, object y) + { + return new CaseInsensitiveComparer().Compare(y, x); + } + } + public class BuildPlatform + { + public string name; + public GUIContent title; + public Texture2D smallIcon; + public BuildTargetGroup targetGroup; + public bool forceShowTarget; + public BuildTarget DefaultTarget + { + get + { + switch (this.targetGroup) + { + case BuildTargetGroup.Standalone: + return BuildTarget.StandaloneWindows; + case BuildTargetGroup.WebPlayer: + return BuildTarget.WebPlayer; + case BuildTargetGroup.iPhone: + return BuildTarget.iPhone; + case BuildTargetGroup.PS3: + return BuildTarget.PS3; + case BuildTargetGroup.XBOX360: + return BuildTarget.XBOX360; + case BuildTargetGroup.Android: + return BuildTarget.Android; + case BuildTargetGroup.GLESEmu: + return BuildTarget.StandaloneGLESEmu; + case BuildTargetGroup.NaCl: + return BuildTarget.NaCl; + case BuildTargetGroup.FlashPlayer: + return BuildTarget.FlashPlayer; + case BuildTargetGroup.Metro: + return BuildTarget.MetroPlayer; + case BuildTargetGroup.WP8: + return BuildTarget.WP8Player; + case BuildTargetGroup.BB10: + return BuildTarget.BB10; + case BuildTargetGroup.Tizen: + return BuildTarget.Tizen; + case BuildTargetGroup.PSP2: + return BuildTarget.PSP2; + case BuildTargetGroup.PS4: + return BuildTarget.PS4; + case BuildTargetGroup.PSM: + return BuildTarget.PSM; + case BuildTargetGroup.XboxOne: + return BuildTarget.XboxOne; + case BuildTargetGroup.SamsungTV: + return BuildTarget.SamsungTV; + } + return (BuildTarget)(-1); + } + } + public BuildPlatform(string locTitle, BuildTargetGroup targetGroup, bool forceShowTarget) + { + this.targetGroup = targetGroup; + this.name = BuildPipeline.GetBuildTargetGroupName(this.DefaultTarget); + this.title = EditorGUIUtility.TextContent(locTitle); + this.smallIcon = (EditorGUIUtility.IconContent(locTitle + ".Small").image as Texture2D); + this.forceShowTarget = forceShowTarget; + } + } + private class BuildPlatforms + { + public BuildPlayerWindow.BuildPlatform[] buildPlatforms; + public BuildTarget[] standaloneSubtargets; + public GUIContent[] standaloneSubtargetStrings; + public SCEBuildSubtarget[] sceSubtargets = new SCEBuildSubtarget[] + { + SCEBuildSubtarget.PCHosted, + SCEBuildSubtarget.HddTitle, + SCEBuildSubtarget.BluRayTitle + }; + public GUIContent[] sceSubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetPCHosted"), + EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetHddTitle"), + EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetBluRayTitle") + }; + public PSP2BuildSubtarget[] psp2Subtargets = new PSP2BuildSubtarget[] + { + PSP2BuildSubtarget.PCHosted, + PSP2BuildSubtarget.Package + }; + public GUIContent[] psp2SubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtargetPCHosted"), + EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtargetPackage") + }; + public FlashBuildSubtarget[] flashBuildSubtargets = new FlashBuildSubtarget[] + { + FlashBuildSubtarget.Flash11dot2, + FlashBuildSubtarget.Flash11dot3, + FlashBuildSubtarget.Flash11dot4, + FlashBuildSubtarget.Flash11dot5, + FlashBuildSubtarget.Flash11dot6, + FlashBuildSubtarget.Flash11dot7, + FlashBuildSubtarget.Flash11dot8 + }; + public GUIContent[] flashBuildSubtargetString = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot2"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot3"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot4"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot5"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot6"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot7"), + EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot8") + }; + public MetroBuildType[] metroBuildTypes = new MetroBuildType[] + { + MetroBuildType.VisualStudioCpp, + MetroBuildType.VisualStudioCSharp + }; + public GUIContent[] metroBuildTypeStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.MetroBuildTypeVisualStudioCpp"), + EditorGUIUtility.TextContent("BuildSettings.MetroBuildTypeVisualStudioCSharp") + }; + public MetroSDK[] metroSDKs = new MetroSDK[] + { + MetroSDK.SDK80, + MetroSDK.SDK81, + MetroSDK.PhoneSDK81, + MetroSDK.UniversalSDK81 + }; + public GUIContent[] metroSDKStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.MetroSDK80"), + EditorGUIUtility.TextContent("BuildSettings.MetroSDK81"), + EditorGUIUtility.TextContent("BuildSettings.MetroPhoneSDK81"), + EditorGUIUtility.TextContent("BuildSettings.MetroUniversalSDK81") + }; + public MetroBuildAndRunDeployTarget[] metroBuildAndRunDeployTargets = new MetroBuildAndRunDeployTarget[] + { + MetroBuildAndRunDeployTarget.LocalMachine, + MetroBuildAndRunDeployTarget.WindowsPhone, + MetroBuildAndRunDeployTarget.LocalMachineAndWindowsPhone + }; + public GUIContent[] metroBuildAndRunDeployTargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.DeployTargetLocalMachine"), + EditorGUIUtility.TextContent("BuildSettings.DeployTargetWindowsPhone"), + EditorGUIUtility.TextContent("BuildSettings.DeployTargetBoth") + }; + public XboxBuildSubtarget[] xboxBuildSubtargets = new XboxBuildSubtarget[] + { + XboxBuildSubtarget.Development, + XboxBuildSubtarget.Master, + XboxBuildSubtarget.Debug + }; + public GUIContent[] xboxBuildSubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetDevelopment"), + EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetMaster"), + EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetDebug") + }; + public XboxRunMethod[] xboxRunMethods = new XboxRunMethod[] + { + XboxRunMethod.HDD, + XboxRunMethod.DiscEmuFast, + XboxRunMethod.DiscEmuAccurate + }; + public GUIContent[] xboxRunMethodStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodHDD"), + EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodDiscEmuFast"), + EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodDiscEmuAccurate") + }; + public AndroidBuildSubtarget[] androidBuildSubtargets = new AndroidBuildSubtarget[] + { + AndroidBuildSubtarget.Generic, + AndroidBuildSubtarget.DXT, + AndroidBuildSubtarget.PVRTC, + AndroidBuildSubtarget.ATC, + AndroidBuildSubtarget.ETC, + AndroidBuildSubtarget.ETC2, + AndroidBuildSubtarget.ASTC + }; + public GUIContent[] androidBuildSubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetGeneric"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetDXT"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetPVRTC"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetATC"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetETC"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetETC2"), + EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetASTC") + }; + public BlackBerryBuildSubtarget[] blackberryBuildSubtargets = new BlackBerryBuildSubtarget[] + { + BlackBerryBuildSubtarget.Generic, + BlackBerryBuildSubtarget.PVRTC, + BlackBerryBuildSubtarget.ATC, + BlackBerryBuildSubtarget.ETC + }; + public GUIContent[] blackberryBuildSubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetGeneric"), + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetPVRTC"), + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetATC"), + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetETC") + }; + public BlackBerryBuildType[] blackberryBuildTypes = new BlackBerryBuildType[] + { + BlackBerryBuildType.Debug, + BlackBerryBuildType.Submission + }; + public GUIContent[] blackberryBuildTypeStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildTypeDebug"), + EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildTypeSubmission") + }; + public TizenBuildSubtarget[] tizenBuildSubtargets = new TizenBuildSubtarget[] + { + TizenBuildSubtarget.Generic, + TizenBuildSubtarget.ATC, + TizenBuildSubtarget.ETC + }; + public GUIContent[] tizenBuildSubtargetStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetGeneric"), + EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetATC"), + EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetETC") + }; + internal BuildPlatforms() + { + this.buildPlatforms = new List + { + new BuildPlayerWindow.BuildPlatform("BuildSettings.Web", BuildTargetGroup.WebPlayer, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.Standalone", BuildTargetGroup.Standalone, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.iPhone", BuildTargetGroup.iPhone, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.Android", BuildTargetGroup.Android, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.BlackBerry", BuildTargetGroup.BB10, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.Tizen", BuildTargetGroup.Tizen, false), + new BuildPlayerWindow.BuildPlatform("BuildSettings.XBox360", BuildTargetGroup.XBOX360, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.XboxOne", BuildTargetGroup.XboxOne, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.PS3", BuildTargetGroup.PS3, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.PSP2", BuildTargetGroup.PSP2, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.PS4", BuildTargetGroup.PS4, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.PSM", BuildTargetGroup.PSM, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.StandaloneGLESEmu", BuildTargetGroup.GLESEmu, false), + new BuildPlayerWindow.BuildPlatform("BuildSettings.FlashPlayer", BuildTargetGroup.FlashPlayer, false), + new BuildPlayerWindow.BuildPlatform("BuildSettings.Metro", BuildTargetGroup.Metro, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.WP8", BuildTargetGroup.WP8, true), + new BuildPlayerWindow.BuildPlatform("BuildSettings.NaCl", BuildTargetGroup.NaCl, false), + new BuildPlayerWindow.BuildPlatform("BuildSettings.SamsungTV", BuildTargetGroup.SamsungTV, false) + }.ToArray(); + List list = new List(); + list.Add(BuildTarget.StandaloneWindows); + list.Add(BuildTarget.StandaloneOSXIntel); + list.Add(BuildTarget.StandaloneLinux); + List list2 = new List(); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneWindows")); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneOSXIntel")); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneLinux")); + this.standaloneSubtargets = list.ToArray(); + this.standaloneSubtargetStrings = list2.ToArray(); + } + public string GetBuildTargetDisplayName(BuildTarget target) + { + BuildPlayerWindow.BuildPlatform[] array = this.buildPlatforms; + for (int i = 0; i < array.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array[i]; + if (buildPlatform.DefaultTarget == target) + { + return buildPlatform.title.text; + } + } + if (target == BuildTarget.WebPlayerStreamed) + { + return this.BuildPlatformFromTargetGroup(BuildTargetGroup.WebPlayer).title.text; + } + for (int j = 0; j < this.standaloneSubtargets.Length; j++) + { + if (this.standaloneSubtargets[j] == BuildPlayerWindow.BuildPlatforms.DefaultTargetForPlatform(target)) + { + return this.standaloneSubtargetStrings[j].text; + } + } + return "Unsupported Target"; + } + public static Dictionary GetArchitecturesForPlatform(BuildTarget target) + { + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + goto IL_B6; + case (BuildTarget)3: + IL_1A: + switch (target) + { + case BuildTarget.StandaloneLinux64: + case BuildTarget.StandaloneLinuxUniversal: + goto IL_78; + case BuildTarget.WP8Player: + IL_33: + switch (target) + { + case BuildTarget.StandaloneLinux: + goto IL_78; + case BuildTarget.StandaloneWindows64: + goto IL_4D; + } + return null; + case BuildTarget.StandaloneOSXIntel64: + goto IL_B6; + } + goto IL_33; + IL_78: + return new Dictionary + { + + { + EditorGUIUtility.TextContent("x86"), + BuildTarget.StandaloneLinux + }, + + { + EditorGUIUtility.TextContent("x86_64"), + BuildTarget.StandaloneLinux64 + }, + + { + EditorGUIUtility.TextContent("x86 + x86_64 (Universal)"), + BuildTarget.StandaloneLinuxUniversal + } + }; + case BuildTarget.StandaloneWindows: + goto IL_4D; + } + goto IL_1A; + IL_4D: + return new Dictionary + { + + { + EditorGUIUtility.TextContent("x86"), + BuildTarget.StandaloneWindows + }, + + { + EditorGUIUtility.TextContent("x86_64"), + BuildTarget.StandaloneWindows64 + } + }; + IL_B6: + return new Dictionary + { + + { + EditorGUIUtility.TextContent("x86"), + BuildTarget.StandaloneOSXIntel + }, + + { + EditorGUIUtility.TextContent("x86_64"), + BuildTarget.StandaloneOSXIntel64 + }, + + { + EditorGUIUtility.TextContent("Universal"), + BuildTarget.StandaloneOSXUniversal + } + }; + } + public static BuildTarget DefaultTargetForPlatform(BuildTarget target) + { + switch (target) + { + case BuildTarget.StandaloneLinux: + case BuildTarget.StandaloneLinux64: + case BuildTarget.StandaloneLinuxUniversal: + return BuildTarget.StandaloneLinux; + case BuildTarget.FlashPlayer: + case (BuildTarget)20: + case (BuildTarget)22: + case (BuildTarget)23: + IL_37: + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + return BuildTarget.StandaloneOSXIntel; + case BuildTarget.StandaloneWindows: + return BuildTarget.StandaloneWindows; + } + return target; + case BuildTarget.StandaloneWindows64: + return BuildTarget.StandaloneWindows; + case BuildTarget.MetroPlayer: + return BuildTarget.MetroPlayer; + case BuildTarget.WP8Player: + return BuildTarget.WP8Player; + case BuildTarget.StandaloneOSXIntel64: + return BuildTarget.StandaloneOSXIntel; + } + goto IL_37; + } + public int BuildPlatformIndexFromTargetGroup(BuildTargetGroup group) + { + for (int i = 0; i < this.buildPlatforms.Length; i++) + { + if (group == this.buildPlatforms[i].targetGroup) + { + return i; + } + } + return -1; + } + public BuildPlayerWindow.BuildPlatform BuildPlatformFromTargetGroup(BuildTargetGroup group) + { + int num = this.BuildPlatformIndexFromTargetGroup(group); + return (num == -1) ? null : this.buildPlatforms[num]; + } + } + private class Styles + { + public const float kButtonWidth = 110f; + private const string kShopURL = "https://store.unity3d.com/shop/"; + private const string kDownloadURL = "http://unity3d.com/unity/download/"; + private const string kMailURL = "mailto:sales@unity3d.com"; + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle box = "OL Box"; + public GUIStyle title = "OL title"; + public GUIStyle evenRow = "CN EntryBackEven"; + public GUIStyle oddRow = "CN EntryBackOdd"; + public GUIStyle platformSelector = "PlayerSettingsPlatform"; + public GUIStyle toggle = "Toggle"; + public GUIStyle levelString = "PlayerSettingsLevel"; + public GUIStyle levelStringCounter = new GUIStyle("Label"); + public Vector2 toggleSize; + public GUIContent noSessionDialogText = EditorGUIUtility.TextContent("UploadingBuildsMonitor.NoSessionDialogText"); + public GUIContent platformTitle = EditorGUIUtility.TextContent("BuildSettings.PlatformTitle"); + public GUIContent switchPlatform = EditorGUIUtility.TextContent("BuildSettings.SwitchPlatform"); + public GUIContent build = EditorGUIUtility.TextContent("BuildSettings.Build"); + public GUIContent export = EditorGUIUtility.TextContent("BuildSettings.Export"); + public GUIContent buildAndRun = EditorGUIUtility.TextContent("BuildSettings.BuildAndRun"); + public GUIContent scenesInBuild = EditorGUIUtility.TextContent("BuildSettings.ScenesInBuild"); + public Texture2D activePlatformIcon = EditorGUIUtility.IconContent("BuildSettings.SelectedIcon").image as Texture2D; + public GUIContent[,] notLicensedMessages; + private GUIContent[,] buildTargetNotInstalled; + public GUIContent sceTarget; + public GUIContent psp2Target; + public GUIContent flashTarget; + public GUIContent metroBuildType; + public GUIContent metroSDK; + public GUIContent metroBuildAndRunDeployTarget; + public GUIContent standaloneTarget; + public GUIContent architecture; + public GUIContent webPlayerStreamed; + public GUIContent webPlayerOfflineDeployment; + public GUIContent debugBuild; + public GUIContent profileBuild; + public GUIContent allowDebugging; + public GUIContent createProject; + public GUIContent symlinkiOSLibraries; + public GUIContent xboxBuildSubtarget; + public GUIContent xboxRunMethod; + public GUIContent androidBuildSubtarget; + public GUIContent explicitNullChecks; + public GUIContent enableHeadlessMode; + public GUIContent blackberryBuildSubtarget; + public GUIContent blackberryBuildType; + public GUIContent tizenBuildSubtarget; + public Styles() + { + GUIContent[,] expr_128 = new GUIContent[17, 3]; + expr_128[0, 0] = EditorGUIUtility.TextContent("BuildSettings.NoWeb"); + expr_128[0, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWebButton"); + expr_128[0, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[1, 0] = EditorGUIUtility.TextContent("BuildSettings.NoStandalone"); + expr_128[1, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWebButton"); + expr_128[1, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[2, 0] = EditorGUIUtility.TextContent("BuildSettings.NoiPhone"); + expr_128[2, 1] = EditorGUIUtility.TextContent("BuildSettings.NoiPhoneButton"); + expr_128[2, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[3, 0] = EditorGUIUtility.TextContent("BuildSettings.NoAndroid"); + expr_128[3, 1] = EditorGUIUtility.TextContent("BuildSettings.NoAndroidButton"); + expr_128[3, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[4, 0] = EditorGUIUtility.TextContent("BuildSettings.NoBB10"); + expr_128[4, 1] = EditorGUIUtility.TextContent("BuildSettings.NoBB10Button"); + expr_128[4, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[5, 0] = EditorGUIUtility.TextContent("BuildSettings.NoTizen"); + expr_128[5, 1] = EditorGUIUtility.TextContent("BuildSettings.NoTizenButton"); + expr_128[5, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[6, 0] = EditorGUIUtility.TextContent("BuildSettings.NoXBox360"); + expr_128[6, 1] = EditorGUIUtility.TextContent("BuildSettings.NoXBox360Button"); + expr_128[6, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[7, 0] = EditorGUIUtility.TextContent("BuildSettings.NoXboxOne"); + expr_128[7, 1] = EditorGUIUtility.TextContent("BuildSettings.NoXboxOneButton"); + expr_128[7, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[8, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPS3"); + expr_128[8, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPS3Button"); + expr_128[8, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[9, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPSP2"); + expr_128[9, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPSP2Button"); + expr_128[9, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[10, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPS4"); + expr_128[10, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPS4Button"); + expr_128[10, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[11, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPSM"); + expr_128[11, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPSMButton"); + expr_128[11, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[12, 0] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmu"); + expr_128[12, 1] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmuButton"); + expr_128[12, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[13, 0] = EditorGUIUtility.TextContent("BuildSettings.NoFlash"); + expr_128[13, 1] = EditorGUIUtility.TextContent("BuildSettings.NoFlashButton"); + expr_128[13, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[14, 0] = EditorGUIUtility.TextContent("BuildSettings.NoMetro"); + expr_128[14, 1] = EditorGUIUtility.TextContent("BuildSettings.NoMetroButton"); + expr_128[14, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[15, 0] = EditorGUIUtility.TextContent("BuildSettings.NoWP8"); + expr_128[15, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWP8Button"); + expr_128[15, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[16, 0] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTV"); + expr_128[16, 1] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTVButton"); + expr_128[16, 2] = new GUIContent("https://store.unity3d.com/shop/"); + this.notLicensedMessages = expr_128; + GUIContent[,] expr_4E4 = new GUIContent[17, 3]; + expr_4E4[0, 0] = EditorGUIUtility.TextContent("BuildSettings.WebNotInstalled"); + expr_4E4[0, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[1, 0] = EditorGUIUtility.TextContent("BuildSettings.StandaloneNotInstalled"); + expr_4E4[1, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[2, 0] = EditorGUIUtility.TextContent("BuildSettings.iPhoneNotInstalled"); + expr_4E4[2, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[3, 0] = EditorGUIUtility.TextContent("BuildSettings.AndroidNotInstalled"); + expr_4E4[3, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[4, 0] = EditorGUIUtility.TextContent("BuildSettings.BlackBerryNotInstalled"); + expr_4E4[4, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[5, 0] = EditorGUIUtility.TextContent("BuildSettings.TizenNotInstalled"); + expr_4E4[5, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[6, 0] = EditorGUIUtility.TextContent("BuildSettings.XBOX360NotInstalled"); + expr_4E4[6, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[7, 0] = EditorGUIUtility.TextContent("BuildSettings.XboxOneNotInstalled"); + expr_4E4[7, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[8, 0] = EditorGUIUtility.TextContent("BuildSettings.PS3NotInstalled"); + expr_4E4[8, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[9, 0] = EditorGUIUtility.TextContent("BuildSettings.PSP2NotInstalled"); + expr_4E4[9, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[10, 0] = EditorGUIUtility.TextContent("BuildSettings.PS4NotInstalled"); + expr_4E4[10, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[11, 0] = EditorGUIUtility.TextContent("BuildSettings.PSMNotInstalled"); + expr_4E4[11, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[12, 0] = EditorGUIUtility.TextContent("BuildSettings.GLESEmuNotInstalled"); + expr_4E4[12, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[13, 0] = EditorGUIUtility.TextContent("BuildSettings.FlashNotInstalled"); + expr_4E4[13, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[14, 0] = EditorGUIUtility.TextContent("BuildSettings.MetroNotInstalled"); + expr_4E4[14, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[15, 0] = EditorGUIUtility.TextContent("BuildSettings.WP8NotInstalled"); + expr_4E4[15, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4E4[16, 0] = EditorGUIUtility.TextContent("BuildSettings.SamsungTVNotInstalled"); + expr_4E4[16, 2] = new GUIContent("http://unity3d.com/unity/download/"); + this.buildTargetNotInstalled = expr_4E4; + this.sceTarget = EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtarget"); + this.psp2Target = EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtarget"); + this.flashTarget = EditorGUIUtility.TextContent("BuildSettings.FlashBuildSubtarget"); + this.metroBuildType = EditorGUIUtility.TextContent("BuildSettings.MetroBuildType"); + this.metroSDK = EditorGUIUtility.TextContent("BuildSettings.MetroSDK"); + this.metroBuildAndRunDeployTarget = EditorGUIUtility.TextContent("BuildSettings.MetroBuildAndRunDeployTarget"); + this.standaloneTarget = EditorGUIUtility.TextContent("BuildSettings.StandaloneTarget"); + this.architecture = EditorGUIUtility.TextContent("BuildSettings.Architecture"); + this.webPlayerStreamed = EditorGUIUtility.TextContent("BuildSettings.WebPlayerStreamed"); + this.webPlayerOfflineDeployment = EditorGUIUtility.TextContent("BuildSettings.WebPlayerOfflineDeployment"); + this.debugBuild = EditorGUIUtility.TextContent("BuildSettings.DebugBuild"); + this.profileBuild = EditorGUIUtility.TextContent("BuildSettings.ConnectProfiler"); + this.allowDebugging = EditorGUIUtility.TextContent("BuildSettings.AllowDebugging"); + this.createProject = EditorGUIUtility.TextContent("BuildSettings.ExportAndroidProject"); + this.symlinkiOSLibraries = EditorGUIUtility.TextContent("BuildSettings.SymlinkiOSLibraries"); + this.xboxBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtarget"); + this.xboxRunMethod = EditorGUIUtility.TextContent("BuildSettings.XboxRunMethod"); + this.androidBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtarget"); + this.explicitNullChecks = EditorGUIUtility.TextContent("BuildSettings.ExplicitNullChecks"); + this.enableHeadlessMode = EditorGUIUtility.TextContent("BuildSettings.EnableHeadlessMode"); + this.blackberryBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtarget"); + this.blackberryBuildType = EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildType"); + this.tizenBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtarget"); + base..ctor(); + this.levelStringCounter.alignment = TextAnchor.MiddleRight; + } + public GUIContent GetTargetNotInstalled(int index, int item) + { + if (index >= this.buildTargetNotInstalled.GetLength(0)) + { + index = 0; + } + return this.buildTargetNotInstalled[index, item]; + } + public GUIContent GetDownloadErrorForTarget(BuildTarget target) + { + return null; + } + } + private class ScenePostprocessor : AssetPostprocessor + { + private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) + { + EditorBuildSettingsScene[] scenes = EditorBuildSettings.scenes; + for (int i = 0; i < movedAssets.Length; i++) + { + string path = movedAssets[i]; + if (Path.GetExtension(path) == ".unity") + { + EditorBuildSettingsScene[] array = scenes; + for (int j = 0; j < array.Length; j++) + { + EditorBuildSettingsScene editorBuildSettingsScene = array[j]; + if (editorBuildSettingsScene.path.ToLower() == movedFromPath[i].ToLower()) + { + editorBuildSettingsScene.path = path; + } + } + } + } + EditorBuildSettings.scenes = scenes; + } + } + private const string kAssetsFolder = "Assets/"; + private const string kEditorBuildSettingsPath = "ProjectSettings/EditorBuildSettings.asset"; + private static BuildPlayerWindow.BuildPlatforms s_BuildPlatforms; + private ListViewState lv = new ListViewState(); + private bool[] selectedLVItems = new bool[0]; + private bool[] selectedBeforeDrag; + private int initialSelectedLVItem = -1; + private Vector2 scrollPosition = new Vector2(0f, 0f); + private static BuildPlayerWindow.Styles styles; + public BuildPlayerWindow() + { + base.position = new Rect(50f, 50f, 540f, 530f); + base.minSize = new Vector2(550f, 580f); + base.title = "Build Settings"; + } + private static void ShowBuildPlayerWindow() + { + EditorUserBuildSettings.selectedBuildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); + EditorWindow.GetWindow(true, "Build Settings"); + } + private static void BuildPlayerAndRun() + { + if (!BuildPlayerWindow.BuildPlayerWithDefaultSettings(false, BuildOptions.AutoRunPlayer)) + { + BuildPlayerWindow.ShowBuildPlayerWindow(); + } + } + private static void BuildPlayerAndSelect() + { + if (!BuildPlayerWindow.BuildPlayerWithDefaultSettings(false, BuildOptions.ShowBuiltPlayer)) + { + BuildPlayerWindow.ShowBuildPlayerWindow(); + } + } + private static bool EnsureLoggedInAndBuild(bool askForBuildLocation, BuildOptions forceOptions) + { + if (string.IsNullOrEmpty(UploadingBuildsMonitor.GetActiveSessionID())) + { + AssetStoreLoginWindow.Login(BuildPlayerWindow.styles.noSessionDialogText.text, delegate(string errorMessage) + { + if (string.IsNullOrEmpty(errorMessage)) + { + BuildPlayerWindow.BuildPlayerWithDefaultSettings(askForBuildLocation, forceOptions, false); + } + else + { + Debug.LogError(errorMessage); + } + }); + return false; + } + return true; + } + private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, BuildOptions forceOptions) + { + return BuildPlayerWindow.BuildPlayerWithDefaultSettings(askForBuildLocation, forceOptions, true); + } + private static bool IsMetroPlayer(BuildTarget target) + { + return target == BuildTarget.MetroPlayer; + } + private static bool IsWP8Player(BuildTarget target) + { + return target == BuildTarget.WP8Player; + } + private static bool IsIl2cppBuild() + { + int num = 0; + PlayerSettings.GetPropertyOptionalInt("ScriptingBackend", ref num, EditorUserBuildSettings.selectedBuildTargetGroup); + return num == 1; + } + private static ScriptingImplementation GetDefaultNonIl2cppBackend() + { + return ScriptingImplementation.Mono2x; + } + private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, BuildOptions forceOptions, bool first) + { + if (first && EditorUserBuildSettings.webPlayerDeployOnline && !BuildPlayerWindow.EnsureLoggedInAndBuild(askForBuildLocation, forceOptions)) + { + return false; + } + BuildPlayerWindow.InitBuildPlatforms(); + BuildTarget buildTarget = BuildPlayerWindow.CalculateSelectedBuildTarget(); + if (!BuildPipeline.IsBuildTargetSupported(buildTarget)) + { + return false; + } + if (Unsupported.IsBleedingEdgeBuild()) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("This version of Unity is a BleedingEdge build that has not seen any manual testing."); + stringBuilder.AppendLine("You should consider this build unstable."); + stringBuilder.AppendLine("We strongly recommend that you use a normal version of Unity instead."); + if (EditorUtility.DisplayDialog("BleedingEdge Build", stringBuilder.ToString(), "Cancel", "OK")) + { + return false; + } + } + if (buildTarget == BuildTarget.BB10 && (forceOptions & BuildOptions.AutoRunPlayer) != BuildOptions.None && (string.IsNullOrEmpty(PlayerSettings.BlackBerry.authorId) || string.IsNullOrEmpty(PlayerSettings.BlackBerry.deviceAddress) || string.IsNullOrEmpty(PlayerSettings.BlackBerry.devicePassword))) + { + Debug.LogError(EditorGUIUtility.TextContent("BuildSettings.BlackBerryValidationFailed").text); + return false; + } + string text = string.Empty; + bool flag = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget) && (Unsupported.IsDeveloperBuild() || BuildPlayerWindow.IsMetroPlayer(buildTarget) || BuildPlayerWindow.IsWP8Player(buildTarget)); + if (!flag) + { + if (EditorUserBuildSettings.selectedBuildTargetGroup == BuildTargetGroup.WebPlayer && EditorUserBuildSettings.webPlayerDeployOnline) + { + text = Path.Combine(Path.Combine(Path.GetTempPath(), "Unity"), "UDNBuild"); + try + { + Directory.CreateDirectory(text); + } + catch (Exception) + { + } + if (!Directory.Exists(text)) + { + Debug.LogError(string.Format("Failed to create temporary build directory at {0}", text)); + return false; + } + text = text.Replace('\\', '/'); + } + else + { + if (askForBuildLocation && !BuildPlayerWindow.PickBuildLocation(buildTarget)) + { + return false; + } + text = EditorUserBuildSettings.GetBuildLocation(buildTarget); + } + if (text.Length == 0) + { + return false; + } + if (!askForBuildLocation) + { + switch (InternalEditorUtility.BuildCanBeAppended(buildTarget, text)) + { + case CanAppendBuild.Yes: + EditorUserBuildSettings.appendProject = true; + break; + case CanAppendBuild.No: + if (!BuildPlayerWindow.PickBuildLocation(buildTarget)) + { + return false; + } + text = EditorUserBuildSettings.GetBuildLocation(buildTarget); + if (text.Length == 0 || !Directory.Exists(FileUtil.DeleteLastPathNameComponent(text))) + { + return false; + } + break; + } + } + } + ArrayList arrayList = new ArrayList(); + EditorBuildSettingsScene[] scenes = EditorBuildSettings.scenes; + EditorBuildSettingsScene[] array = scenes; + for (int i = 0; i < array.Length; i++) + { + EditorBuildSettingsScene editorBuildSettingsScene = array[i]; + if (editorBuildSettingsScene.enabled) + { + arrayList.Add(editorBuildSettingsScene.path); + } + } + string[] levels = arrayList.ToArray(typeof(string)) as string[]; + BuildOptions buildOptions = forceOptions; + bool development = EditorUserBuildSettings.development; + if (development) + { + buildOptions |= BuildOptions.Development; + } + if (EditorUserBuildSettings.allowDebugging && development) + { + buildOptions |= BuildOptions.AllowDebugging; + } + if (EditorUserBuildSettings.symlinkLibraries) + { + buildOptions |= BuildOptions.SymlinkLibraries; + } + if (EditorUserBuildSettings.appendProject) + { + buildOptions |= BuildOptions.AcceptExternalModificationsToPlayer; + } + if (EditorUserBuildSettings.webPlayerDeployOnline) + { + buildOptions |= BuildOptions.DeployOnline; + } + if (EditorUserBuildSettings.webPlayerOfflineDeployment) + { + buildOptions |= BuildOptions.WebPlayerOfflineDeployment; + } + if (EditorUserBuildSettings.enableHeadlessMode) + { + buildOptions |= BuildOptions.EnableHeadlessMode; + } + if (EditorUserBuildSettings.connectProfiler && (development || buildTarget == BuildTarget.MetroPlayer || buildTarget == BuildTarget.WP8Player)) + { + buildOptions |= BuildOptions.ConnectWithProfiler; + } + if (flag) + { + buildOptions |= BuildOptions.InstallInBuildFolder; + } + bool delayToAfterScriptReload = false; + if (EditorUserBuildSettings.activeBuildTarget != buildTarget) + { + if (!EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget)) + { + Debug.LogError(string.Format("Could not switch to build target '{0}'.", BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(buildTarget))); + return false; + } + if (EditorApplication.isCompiling) + { + delayToAfterScriptReload = true; + } + } + uint num = 0u; + string text2 = BuildPipeline.BuildPlayerInternalNoCheck(levels, text, buildTarget, buildOptions, delayToAfterScriptReload, out num); + return text2.Length == 0; + } + private void ActiveScenesGUI() + { + int num = 0; + int row = this.lv.row; + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + Event current = Event.current; + Rect rect = GUILayoutUtility.GetRect(BuildPlayerWindow.styles.scenesInBuild, BuildPlayerWindow.styles.title); + ArrayList arrayList = new ArrayList(EditorBuildSettings.scenes); + this.lv.totalRows = arrayList.Count; + if (this.selectedLVItems.Length != arrayList.Count) + { + Array.Resize(ref this.selectedLVItems, arrayList.Count); + } + int[] array = new int[arrayList.Count]; + for (int i = 0; i < array.Length; i++) + { + EditorBuildSettingsScene editorBuildSettingsScene = (EditorBuildSettingsScene)arrayList[i]; + array[i] = num; + if (editorBuildSettingsScene.enabled) + { + num++; + } + } + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.lv, (ListViewOptions)3, BuildPlayerWindow.styles.box, new GUILayoutOption[0])) + { + EditorBuildSettingsScene editorBuildSettingsScene2 = (EditorBuildSettingsScene)arrayList[listViewElement.row]; + bool flag = File.Exists(editorBuildSettingsScene2.path); + EditorGUI.BeginDisabledGroup(!flag); + bool flag2 = this.selectedLVItems[listViewElement.row]; + if (flag2 && current.type == EventType.Repaint) + { + BuildPlayerWindow.styles.selected.Draw(listViewElement.position, false, false, false, false); + } + if (!flag) + { + editorBuildSettingsScene2.enabled = false; + } + Rect position = new Rect(listViewElement.position.x + 4f, listViewElement.position.y, BuildPlayerWindow.styles.toggleSize.x, BuildPlayerWindow.styles.toggleSize.y); + EditorGUI.BeginChangeCheck(); + editorBuildSettingsScene2.enabled = GUI.Toggle(position, editorBuildSettingsScene2.enabled, string.Empty); + if (EditorGUI.EndChangeCheck() && flag2) + { + for (int j = 0; j < arrayList.Count; j++) + { + if (this.selectedLVItems[j]) + { + ((EditorBuildSettingsScene)arrayList[j]).enabled = editorBuildSettingsScene2.enabled; + } + } + } + GUILayout.Space(BuildPlayerWindow.styles.toggleSize.x); + string text = editorBuildSettingsScene2.path; + if (text.StartsWith("Assets/")) + { + text = text.Substring("Assets/".Length); + } + Rect rect2 = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(text), BuildPlayerWindow.styles.levelString); + if (Event.current.type == EventType.Repaint) + { + BuildPlayerWindow.styles.levelString.Draw(rect2, EditorGUIUtility.TempContent(text), false, false, flag2, false); + } + GUILayout.Label((!editorBuildSettingsScene2.enabled) ? string.Empty : array[listViewElement.row].ToString(), BuildPlayerWindow.styles.levelStringCounter, new GUILayoutOption[] + { + GUILayout.MaxWidth(36f) + }); + EditorGUI.EndDisabledGroup(); + if (ListViewGUILayout.HasMouseUp(listViewElement.position) && !shift && !actionKey) + { + if (!shift && !actionKey) + { + ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.initialSelectedLVItem, ref this.selectedLVItems); + } + } + else + { + if (ListViewGUILayout.HasMouseDown(listViewElement.position)) + { + if (!this.selectedLVItems[listViewElement.row] || shift || actionKey) + { + ListViewGUILayout.MultiSelection(row, listViewElement.row, ref this.initialSelectedLVItem, ref this.selectedLVItems); + } + this.lv.row = listViewElement.row; + this.selectedBeforeDrag = new bool[this.selectedLVItems.Length]; + this.selectedLVItems.CopyTo(this.selectedBeforeDrag, 0); + this.selectedBeforeDrag[this.lv.row] = true; + } + } + } + GUI.Label(rect, BuildPlayerWindow.styles.scenesInBuild, BuildPlayerWindow.styles.title); + if (GUIUtility.keyboardControl == this.lv.ID) + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + for (int i = 0; i < this.selectedLVItems.Length; i++) + { + this.selectedLVItems[i] = true; + } + this.lv.selectionChanged = true; + Event.current.Use(); + GUIUtility.ExitGUI(); + } + } + } + if (this.lv.selectionChanged) + { + ListViewGUILayout.MultiSelection(row, this.lv.row, ref this.initialSelectedLVItem, ref this.selectedLVItems); + } + if (this.lv.fileNames != null) + { + Array.Sort(this.lv.fileNames); + int num2 = 0; + for (int i = 0; i < this.lv.fileNames.Length; i++) + { + if (this.lv.fileNames[i].EndsWith("unity")) + { + EditorBuildSettingsScene editorBuildSettingsScene3 = new EditorBuildSettingsScene(); + editorBuildSettingsScene3.path = FileUtil.GetProjectRelativePath(this.lv.fileNames[i]); + if (editorBuildSettingsScene3.path == string.Empty) + { + editorBuildSettingsScene3.path = this.lv.fileNames[i]; + } + editorBuildSettingsScene3.enabled = true; + arrayList.Insert(this.lv.draggedTo + num2++, editorBuildSettingsScene3); + } + } + if (num2 != 0) + { + Array.Resize(ref this.selectedLVItems, arrayList.Count); + for (int i = 0; i < this.selectedLVItems.Length; i++) + { + this.selectedLVItems[i] = (i >= this.lv.draggedTo && i < this.lv.draggedTo + num2); + } + } + this.lv.draggedTo = -1; + } + if (this.lv.draggedTo != -1) + { + ArrayList arrayList2 = new ArrayList(); + int num3 = 0; + int i = 0; + while (i < this.selectedLVItems.Length) + { + if (this.selectedBeforeDrag[i]) + { + arrayList2.Add(arrayList[num3]); + arrayList.RemoveAt(num3); + num3--; + if (this.lv.draggedTo >= i) + { + this.lv.draggedTo--; + } + } + i++; + num3++; + } + this.lv.draggedTo = ((this.lv.draggedTo <= arrayList.Count && this.lv.draggedTo >= 0) ? this.lv.draggedTo : arrayList.Count); + arrayList.InsertRange(this.lv.draggedTo, arrayList2); + for (i = 0; i < this.selectedLVItems.Length; i++) + { + this.selectedLVItems[i] = (i >= this.lv.draggedTo && i < this.lv.draggedTo + arrayList2.Count); + } + } + if (current.type == EventType.KeyDown && (current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete)) + { + int num3 = 0; + int i = 0; + while (i < this.selectedLVItems.Length) + { + if (this.selectedLVItems[i]) + { + arrayList.RemoveAt(num3); + num3--; + } + this.selectedLVItems[i] = false; + i++; + num3++; + } + this.lv.row = -1; + current.Use(); + } + EditorBuildSettings.scenes = (arrayList.ToArray(typeof(EditorBuildSettingsScene)) as EditorBuildSettingsScene[]); + } + private void AddCurrentScene() + { + string currentScene = EditorApplication.currentScene; + if (currentScene.Length == 0) + { + EditorApplication.SaveCurrentSceneIfUserWantsToForce(); + currentScene = EditorApplication.currentScene; + } + if (currentScene.Length != 0) + { + EditorBuildSettings.scenes = (new ArrayList(EditorBuildSettings.scenes) + { + new EditorBuildSettingsScene + { + path = currentScene, + enabled = true + } + }.ToArray(typeof(EditorBuildSettingsScene)) as EditorBuildSettingsScene[]); + } + base.Repaint(); + GUIUtility.ExitGUI(); + } + private static BuildTarget CalculateSelectedBuildTarget() + { + BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; + BuildTargetGroup buildTargetGroup = selectedBuildTargetGroup; + if (buildTargetGroup == BuildTargetGroup.Standalone) + { + return EditorUserBuildSettings.selectedStandaloneTarget; + } + if (buildTargetGroup == BuildTargetGroup.WebPlayer) + { + return (!EditorUserBuildSettings.webPlayerStreamed) ? BuildTarget.WebPlayer : BuildTarget.WebPlayerStreamed; + } + if (BuildPlayerWindow.s_BuildPlatforms == null) + { + throw new Exception("Build platforms are not initialized."); + } + BuildPlayerWindow.BuildPlatform buildPlatform = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformFromTargetGroup(selectedBuildTargetGroup); + if (buildPlatform == null) + { + throw new Exception("Could not find build platform for target group " + selectedBuildTargetGroup); + } + return buildPlatform.DefaultTarget; + } + private void ActiveBuildTargetsGUI() + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(255f) + }); + GUILayout.Label(BuildPlayerWindow.styles.platformTitle, BuildPlayerWindow.styles.title, new GUILayoutOption[0]); + this.scrollPosition = GUILayout.BeginScrollView(this.scrollPosition, "OL Box"); + for (int i = 0; i < 2; i++) + { + bool flag = i == 0; + bool flag2 = false; + BuildPlayerWindow.BuildPlatform[] buildPlatforms = BuildPlayerWindow.s_BuildPlatforms.buildPlatforms; + for (int j = 0; j < buildPlatforms.Length; j++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = buildPlatforms[j]; + if (BuildPlayerWindow.IsBuildTargetGroupSupported(buildPlatform.DefaultTarget) == flag) + { + if (BuildPlayerWindow.IsBuildTargetGroupSupported(buildPlatform.DefaultTarget) || buildPlatform.forceShowTarget) + { + this.ShowOption(buildPlatform, buildPlatform.title, (!flag2) ? BuildPlayerWindow.styles.oddRow : BuildPlayerWindow.styles.evenRow); + flag2 = !flag2; + } + } + } + GUI.contentColor = Color.white; + } + GUILayout.EndScrollView(); + GUILayout.EndVertical(); + GUILayout.Space(10f); + BuildTarget buildTarget = BuildPlayerWindow.CalculateSelectedBuildTarget(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.enabled = (BuildPipeline.IsBuildTargetSupported(buildTarget) && BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget) != BuildPipeline.GetBuildTargetGroup(buildTarget)); + if (GUILayout.Button(BuildPlayerWindow.styles.switchPlatform, new GUILayoutOption[] + { + GUILayout.Width(110f) + })) + { + EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget); + } + GUI.enabled = BuildPipeline.IsBuildTargetSupported(buildTarget); + if (GUILayout.Button(new GUIContent("Player Settings..."), new GUILayoutOption[] + { + GUILayout.Width(110f) + })) + { + Selection.activeObject = Unsupported.GetSerializedAssetInterfaceSingleton("PlayerSettings"); + } + GUILayout.EndHorizontal(); + GUI.enabled = true; + GUILayout.EndVertical(); + } + private void ShowOption(BuildPlayerWindow.BuildPlatform bp, GUIContent title, GUIStyle background) + { + Rect rect = GUILayoutUtility.GetRect(50f, 36f); + rect.x += 1f; + rect.y += 1f; + bool flag = BuildPipeline.LicenseCheck(bp.DefaultTarget); + GUI.contentColor = new Color(1f, 1f, 1f, (!flag) ? 0.7f : 1f); + bool flag2 = EditorUserBuildSettings.selectedBuildTargetGroup == bp.targetGroup; + if (Event.current.type == EventType.Repaint) + { + background.Draw(rect, GUIContent.none, false, false, flag2, false); + GUI.Label(new Rect(rect.x + 3f, rect.y + 3f, 32f, 32f), title.image, GUIStyle.none); + if (BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget) == bp.targetGroup) + { + GUI.Label(new Rect(rect.xMax - (float)BuildPlayerWindow.styles.activePlatformIcon.width - 8f, rect.y + 3f + (float)((32 - BuildPlayerWindow.styles.activePlatformIcon.height) / 2), (float)BuildPlayerWindow.styles.activePlatformIcon.width, (float)BuildPlayerWindow.styles.activePlatformIcon.height), BuildPlayerWindow.styles.activePlatformIcon, GUIStyle.none); + } + } + if (GUI.Toggle(rect, flag2, title.text, BuildPlayerWindow.styles.platformSelector) && EditorUserBuildSettings.selectedBuildTargetGroup != bp.targetGroup) + { + EditorUserBuildSettings.selectedBuildTargetGroup = bp.targetGroup; + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(InspectorWindow)); + for (int i = 0; i < array.Length; i++) + { + InspectorWindow inspectorWindow = array[i] as InspectorWindow; + if (inspectorWindow != null) + { + inspectorWindow.Repaint(); + } + } + } + } + private void OnGUI() + { + if (BuildPlayerWindow.styles == null) + { + BuildPlayerWindow.styles = new BuildPlayerWindow.Styles(); + BuildPlayerWindow.styles.toggleSize = BuildPlayerWindow.styles.toggle.CalcSize(new GUIContent("X")); + this.lv.rowHeight = (int)BuildPlayerWindow.styles.levelString.CalcHeight(new GUIContent("X"), 100f); + } + BuildPlayerWindow.InitBuildPlatforms(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + string empty = string.Empty; + bool flag = !AssetDatabase.IsOpenForEdit("ProjectSettings/EditorBuildSettings.asset", out empty); + EditorGUI.BeginDisabledGroup(flag); + this.ActiveScenesGUI(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (flag) + { + GUI.enabled = true; + if (Provider.enabled && GUILayout.Button("Checkout", new GUILayoutOption[0])) + { + Asset assetByPath = Provider.GetAssetByPath("ProjectSettings/EditorBuildSettings.asset"); + Task task = Provider.Checkout(new AssetList + { + assetByPath + }, CheckoutMode.Both); + task.SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + GUILayout.Label(empty, new GUILayoutOption[0]); + GUI.enabled = false; + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Add Current", new GUILayoutOption[0])) + { + this.AddCurrentScene(); + } + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Height(301f) + }); + this.ActiveBuildTargetsGUI(); + GUILayout.Space(10f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + this.ShowBuildTargetSettings(); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.EndVertical(); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + } + private static BuildTarget RestoreLastKnownPlatformsBuildTarget(BuildPlayerWindow.BuildPlatform bp) + { + BuildTargetGroup targetGroup = bp.targetGroup; + if (targetGroup == BuildTargetGroup.Standalone) + { + return EditorUserBuildSettings.selectedStandaloneTarget; + } + if (targetGroup != BuildTargetGroup.WebPlayer) + { + return bp.DefaultTarget; + } + return (!EditorUserBuildSettings.webPlayerStreamed) ? BuildTarget.WebPlayer : BuildTarget.WebPlayerStreamed; + } + private static void InitBuildPlatforms() + { + if (BuildPlayerWindow.s_BuildPlatforms == null) + { + BuildPlayerWindow.s_BuildPlatforms = new BuildPlayerWindow.BuildPlatforms(); + BuildPlayerWindow.RepairSelectedBuildTargetGroup(); + } + } + internal static List GetValidPlatforms() + { + BuildPlayerWindow.InitBuildPlatforms(); + List list = new List(); + BuildPlayerWindow.BuildPlatform[] buildPlatforms = BuildPlayerWindow.s_BuildPlatforms.buildPlatforms; + for (int i = 0; i < buildPlatforms.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = buildPlatforms[i]; + if (buildPlatform.targetGroup == BuildTargetGroup.Standalone || BuildPipeline.IsBuildTargetSupported(buildPlatform.DefaultTarget)) + { + list.Add(buildPlatform); + } + } + return list; + } + internal static bool IsBuildTargetGroupSupported(BuildTarget target) + { + return target == BuildTarget.StandaloneWindows || BuildPipeline.IsBuildTargetSupported(target); + } + internal static bool IsXboxBuildSubtargetDevelopment(XboxBuildSubtarget target) + { + return target != XboxBuildSubtarget.Master; + } + private static void RepairSelectedBuildTargetGroup() + { + BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; + if (selectedBuildTargetGroup == BuildTargetGroup.Unknown || BuildPlayerWindow.s_BuildPlatforms == null || BuildPlayerWindow.s_BuildPlatforms.BuildPlatformIndexFromTargetGroup(selectedBuildTargetGroup) < 0) + { + EditorUserBuildSettings.selectedBuildTargetGroup = BuildTargetGroup.WebPlayer; + } + } + private void ShowBuildTargetSettings() + { + EditorGUIUtility.labelWidth = Mathf.Min(180f, (base.position.width - 265f) * 0.47f); + BuildTarget buildTarget = BuildPlayerWindow.CalculateSelectedBuildTarget(); + BuildPlayerWindow.BuildPlatform buildPlatform = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformFromTargetGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + GUILayout.Space(18f); + Rect rect = GUILayoutUtility.GetRect(50f, 36f); + rect.x += 1f; + GUI.Label(new Rect(rect.x + 3f, rect.y + 3f, 32f, 32f), buildPlatform.title.image, GUIStyle.none); + GUI.Toggle(rect, false, buildPlatform.title.text, BuildPlayerWindow.styles.platformSelector); + GUILayout.Space(10f); + if (!string.IsNullOrEmpty(ModuleManager.GetTargetStringFromBuildTarget(buildTarget)) && ModuleManager.GetBuildPostProcessor(buildTarget) == null) + { + GUILayout.Label("No " + BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(buildTarget) + " module loaded.", new GUILayoutOption[0]); + if (GUILayout.Button("Module Manager", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + InternalEditorUtility.ShowPackageManagerWindow(); + } + BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); + return; + } + GUIContent downloadErrorForTarget = BuildPlayerWindow.styles.GetDownloadErrorForTarget(buildTarget); + if (downloadErrorForTarget != null) + { + GUILayout.Label(downloadErrorForTarget, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); + return; + } + if (!BuildPipeline.LicenseCheck(buildTarget)) + { + int num = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformIndexFromTargetGroup(buildPlatform.targetGroup); + GUILayout.Label(BuildPlayerWindow.styles.notLicensedMessages[num, 0], EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (BuildPlayerWindow.styles.notLicensedMessages[num, 1].text.Length != 0 && GUILayout.Button(BuildPlayerWindow.styles.notLicensedMessages[num, 1], new GUILayoutOption[0])) + { + Application.OpenURL(BuildPlayerWindow.styles.notLicensedMessages[num, 2].text); + } + GUILayout.EndHorizontal(); + BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); + return; + } + GUI.changed = false; + switch (buildPlatform.targetGroup) + { + case BuildTargetGroup.Standalone: + { + BuildTarget selectedStandaloneTarget = EditorUserBuildSettings.selectedStandaloneTarget; + int num2 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargets, BuildPlayerWindow.BuildPlatforms.DefaultTargetForPlatform(selectedStandaloneTarget))); + int num3 = EditorGUILayout.Popup(BuildPlayerWindow.styles.standaloneTarget, num2, BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargetStrings, new GUILayoutOption[0]); + Dictionary architecturesForPlatform = BuildPlayerWindow.BuildPlatforms.GetArchitecturesForPlatform(selectedStandaloneTarget); + BuildTarget buildTarget2; + if (num3 == num2 && architecturesForPlatform != null) + { + GUIContent[] array = new List(architecturesForPlatform.Keys).ToArray(); + int num4 = 0; + if (num3 == num2) + { + foreach (KeyValuePair current in architecturesForPlatform) + { + if (current.Value == selectedStandaloneTarget) + { + num4 = Math.Max(0, Array.IndexOf(array, current.Key)); + break; + } + } + } + num4 = EditorGUILayout.Popup(BuildPlayerWindow.styles.architecture, num4, array, new GUILayoutOption[0]); + buildTarget2 = architecturesForPlatform[array[num4]]; + } + else + { + buildTarget2 = BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargets[num3]; + if (BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget) == BuildTargetGroup.Standalone) + { + EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget2); + } + } + EditorUserBuildSettings.selectedStandaloneTarget = buildTarget2; + break; + } + case BuildTargetGroup.WebPlayer: + { + EditorUserBuildSettings.webPlayerDeployOnline = false; + GUI.enabled = BuildPipeline.LicenseCheck(BuildTarget.WebPlayerStreamed); + bool webPlayerStreamed = EditorGUILayout.Toggle(BuildPlayerWindow.styles.webPlayerStreamed, EditorUserBuildSettings.webPlayerStreamed, new GUILayoutOption[0]); + if (GUI.changed) + { + EditorUserBuildSettings.webPlayerStreamed = webPlayerStreamed; + } + bool enabled = GUI.enabled; + if (EditorUserBuildSettings.webPlayerDeployOnline) + { + GUI.enabled = false; + } + EditorUserBuildSettings.webPlayerOfflineDeployment = EditorGUILayout.Toggle(BuildPlayerWindow.styles.webPlayerOfflineDeployment, EditorUserBuildSettings.webPlayerOfflineDeployment, new GUILayoutOption[0]); + GUI.enabled = enabled; + break; + } + case BuildTargetGroup.iPhone: + if (Application.platform == RuntimePlatform.OSXEditor) + { + EditorUserBuildSettings.symlinkLibraries = EditorGUILayout.Toggle(BuildPlayerWindow.styles.symlinkiOSLibraries, EditorUserBuildSettings.symlinkLibraries, new GUILayoutOption[0]); + } + EditorUserBuildSettings.appendProject = false; + break; + case BuildTargetGroup.PS3: + { + int num5 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.sceSubtargets, EditorUserBuildSettings.sceBuildSubtarget); + if (num5 == -1) + { + num5 = 0; + } + num5 = EditorGUILayout.Popup(BuildPlayerWindow.styles.sceTarget, num5, BuildPlayerWindow.s_BuildPlatforms.sceSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.sceBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.sceSubtargets[num5]; + break; + } + case BuildTargetGroup.XBOX360: + { + int num6 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargets, EditorUserBuildSettings.xboxBuildSubtarget); + if (num6 == -1) + { + num6 = 0; + } + num6 = EditorGUILayout.Popup(BuildPlayerWindow.styles.xboxBuildSubtarget, num6, BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.xboxBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargets[num6]; + num6 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.xboxRunMethods, EditorUserBuildSettings.xboxRunMethod); + if (num6 == -1) + { + num6 = 0; + } + num6 = EditorGUILayout.Popup(BuildPlayerWindow.styles.xboxRunMethod, num6, BuildPlayerWindow.s_BuildPlatforms.xboxRunMethodStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.xboxRunMethod = BuildPlayerWindow.s_BuildPlatforms.xboxRunMethods[num6]; + break; + } + case BuildTargetGroup.Android: + { + int num7 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargets, EditorUserBuildSettings.androidBuildSubtarget); + if (num7 == -1) + { + num7 = 0; + } + num7 = EditorGUILayout.Popup(BuildPlayerWindow.styles.androidBuildSubtarget, num7, BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.androidBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargets[num7]; + bool flag = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget); + bool arg_632_0 = EditorUserBuildSettings.appendProject; + bool flag2 = !flag; + GUI.enabled = flag2; + EditorUserBuildSettings.appendProject = (arg_632_0 & flag2); + EditorUserBuildSettings.appendProject = EditorGUILayout.Toggle(BuildPlayerWindow.styles.createProject, EditorUserBuildSettings.appendProject, new GUILayoutOption[0]); + GUI.enabled = true; + break; + } + case BuildTargetGroup.FlashPlayer: + { + int num8 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargets, EditorUserBuildSettings.flashBuildSubtarget); + if (num8 == -1) + { + num8 = 0; + } + num8 = EditorGUILayout.Popup(BuildPlayerWindow.styles.flashTarget, num8, BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargetString, new GUILayoutOption[0]); + EditorUserBuildSettings.flashBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargets[num8]; + break; + } + case BuildTargetGroup.Metro: + { + int num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroBuildTypes, EditorUserBuildSettings.metroBuildType)); + num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroBuildType, num9, BuildPlayerWindow.s_BuildPlatforms.metroBuildTypeStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.metroBuildType = BuildPlayerWindow.s_BuildPlatforms.metroBuildTypes[num9]; + num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroSDKs, EditorUserBuildSettings.metroSDK)); + num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroSDK, num9, BuildPlayerWindow.s_BuildPlatforms.metroSDKStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.metroSDK = BuildPlayerWindow.s_BuildPlatforms.metroSDKs[num9]; + GUI.enabled = (EditorUserBuildSettings.metroSDK == MetroSDK.UniversalSDK81); + num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargets, EditorUserBuildSettings.metroBuildAndRunDeployTarget)); + num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroBuildAndRunDeployTarget, num9, BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.metroBuildAndRunDeployTarget = BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargets[num9]; + GUI.enabled = true; + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("BuildSettings.MetroDebugging"), new GUILayoutOption[0]); + GUI.enabled = (EditorUserBuildSettings.metroBuildType == MetroBuildType.VisualStudioCSharp || EditorUserBuildSettings.metroBuildType == MetroBuildType.VisualStudioCSharpDX); + EditorUserBuildSettings.metroGenerateReferenceProjects = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("BuildSettings.MetroGenerateReferenceProjects"), EditorUserBuildSettings.metroGenerateReferenceProjects, new GUILayoutOption[0]); + GUI.enabled = true; + break; + } + case BuildTargetGroup.BB10: + { + int num10 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargets, EditorUserBuildSettings.blackberryBuildSubtarget); + if (num10 == -1) + { + num10 = 0; + } + num10 = EditorGUILayout.Popup(BuildPlayerWindow.styles.blackberryBuildSubtarget, num10, BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.blackberryBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargets[num10]; + num10 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypes, EditorUserBuildSettings.blackberryBuildType); + if (num10 == -1) + { + num10 = 0; + } + num10 = EditorGUILayout.Popup(BuildPlayerWindow.styles.blackberryBuildType, num10, BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypeStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.blackberryBuildType = BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypes[num10]; + GUI.enabled = true; + break; + } + case BuildTargetGroup.Tizen: + { + int num11 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargets, EditorUserBuildSettings.tizenBuildSubtarget); + if (num11 == -1) + { + num11 = 0; + } + num11 = EditorGUILayout.Popup(BuildPlayerWindow.styles.tizenBuildSubtarget, num11, BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.tizenBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargets[num11]; + GUI.enabled = true; + break; + } + case BuildTargetGroup.PSP2: + { + int num12 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.psp2Subtargets, EditorUserBuildSettings.psp2BuildSubtarget); + if (num12 == -1) + { + num12 = 0; + } + num12 = EditorGUILayout.Popup(BuildPlayerWindow.styles.psp2Target, num12, BuildPlayerWindow.s_BuildPlatforms.psp2SubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.psp2BuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.psp2Subtargets[num12]; + break; + } + case BuildTargetGroup.PS4: + { + int num13 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.sceSubtargets, EditorUserBuildSettings.sceBuildSubtarget); + if (num13 == -1) + { + num13 = 0; + } + num13 = EditorGUILayout.Popup(BuildPlayerWindow.styles.sceTarget, num13, BuildPlayerWindow.s_BuildPlatforms.sceSubtargetStrings, new GUILayoutOption[0]); + EditorUserBuildSettings.sceBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.sceSubtargets[num13]; + break; + } + } + GUI.enabled = true; + bool flag3 = true; + bool enableBuildAndRunButton = false; + bool flag4 = buildTarget != BuildTarget.PS3 && buildTarget != BuildTarget.PSP2 && buildTarget != BuildTarget.PS4 && buildTarget != BuildTarget.PSM && buildTarget != BuildTarget.FlashPlayer && buildTarget != BuildTarget.NaCl && !BuildPlayerWindow.IsMetroPlayer(buildTarget) && !BuildPlayerWindow.IsWP8Player(buildTarget); + bool flag5 = buildTarget == BuildTarget.XBOX360 || buildTarget == BuildTarget.PS3 || buildTarget == BuildTarget.PSP2 || buildTarget == BuildTarget.PS4 || buildTarget == BuildTarget.PSM; + bool flag6 = (buildTarget == BuildTarget.StandaloneLinux || buildTarget == BuildTarget.StandaloneLinux64 || buildTarget == BuildTarget.StandaloneLinuxUniversal) && Application.HasProLicense(); + bool canInstallInBuildFolder = false; + if ((BuildPlayerWindow.IsMetroPlayer(buildTarget) || BuildPlayerWindow.IsWP8Player(buildTarget)) && !InternalEditorUtility.RunningUnderWindows8()) + { + flag3 = false; + GUILayout.Label(EditorGUIUtility.TextContent("BuildSettings.NoWindows8"), EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + if (BuildPipeline.IsBuildTargetSupported(buildTarget)) + { + bool flag7 = buildTarget == BuildTarget.PS3 && EditorUserBuildSettings.sceBuildSubtarget != SCEBuildSubtarget.PCHosted; + bool flag8 = buildTarget == BuildTarget.PS4 && EditorUserBuildSettings.sceBuildSubtarget != SCEBuildSubtarget.PCHosted; + bool flag9 = buildTarget == BuildTarget.PSP2 && EditorUserBuildSettings.psp2BuildSubtarget != PSP2BuildSubtarget.PCHosted; + bool flag10 = flag7 || flag8 || flag9; + bool flag11 = buildTarget == BuildTarget.PSP2 || BuildTarget.PS4 == buildTarget; + bool flag12 = buildTarget != BuildTarget.FlashPlayer && buildTarget != BuildTarget.NaCl && !BuildPlayerWindow.IsWP8Player(buildTarget); + bool flag13 = !flag10; + GUI.enabled = flag13; + BuildTargetGroup targetGroup = buildPlatform.targetGroup; + if (targetGroup != BuildTargetGroup.XBOX360) + { + EditorUserBuildSettings.development = EditorGUILayout.Toggle(BuildPlayerWindow.styles.debugBuild, EditorUserBuildSettings.development, new GUILayoutOption[0]); + } + else + { + EditorUserBuildSettings.development = BuildPlayerWindow.IsXboxBuildSubtargetDevelopment(EditorUserBuildSettings.xboxBuildSubtarget); + } + bool development = EditorUserBuildSettings.development; + GUI.enabled = (flag13 && development); + GUI.enabled = (GUI.enabled && InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(buildTarget)); + GUI.enabled = (GUI.enabled && buildPlatform.targetGroup != BuildTargetGroup.WebPlayer); + if (flag12) + { + if (!GUI.enabled) + { + if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(buildTarget)) + { + BuildPlayerWindow.styles.profileBuild.tooltip = "Pro Version for selected platform is needed for profiling"; + } + else + { + if (!development) + { + BuildPlayerWindow.styles.profileBuild.tooltip = "Profiling only enabled in Development Player"; + } + else + { + if (buildPlatform.targetGroup == BuildTargetGroup.WebPlayer) + { + BuildPlayerWindow.styles.profileBuild.tooltip = "Autoconnect not available from webplayer. Manually connect in Profiler"; + } + } + } + } + else + { + BuildPlayerWindow.styles.profileBuild.tooltip = string.Empty; + } + EditorUserBuildSettings.connectProfiler = EditorGUILayout.Toggle(BuildPlayerWindow.styles.profileBuild, EditorUserBuildSettings.connectProfiler, new GUILayoutOption[0]); + } + GUI.enabled = (flag13 && development); + if (flag4) + { + bool enabled2 = GUI.enabled; + GUI.enabled = (buildTarget != BuildTarget.iPhone || !BuildPlayerWindow.IsIl2cppBuild()); + BuildPlayerWindow.styles.allowDebugging.tooltip = string.Empty; + if (!GUI.enabled) + { + BuildPlayerWindow.styles.allowDebugging.tooltip = "Debugging projects that target the IL2CPP scripting backend is not supported"; + } + EditorUserBuildSettings.allowDebugging = EditorGUILayout.Toggle(BuildPlayerWindow.styles.allowDebugging, EditorUserBuildSettings.allowDebugging, new GUILayoutOption[0]); + GUI.enabled = enabled2; + } + if (flag5) + { + GUI.enabled = (!flag13 || !development); + if (!GUI.enabled) + { + EditorUserBuildSettings.explicitNullChecks = true; + } + EditorUserBuildSettings.explicitNullChecks = EditorGUILayout.Toggle(BuildPlayerWindow.styles.explicitNullChecks, EditorUserBuildSettings.explicitNullChecks, new GUILayoutOption[0]); + } + GUI.enabled = !development; + if (flag6) + { + EditorUserBuildSettings.enableHeadlessMode = EditorGUILayout.Toggle(BuildPlayerWindow.styles.enableHeadlessMode, EditorUserBuildSettings.enableHeadlessMode && !development, new GUILayoutOption[0]); + } + GUI.enabled = true; + GUILayout.FlexibleSpace(); + canInstallInBuildFolder = (!flag10 && Unsupported.IsDeveloperBuild() && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget)); + if (flag3) + { + enableBuildAndRunButton = ((!flag10 && !EditorUserBuildSettings.installInBuildFolder) || flag11); + } + } + else + { + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + int index = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformIndexFromTargetGroup(buildPlatform.targetGroup); + GUILayout.Label(BuildPlayerWindow.styles.GetTargetNotInstalled(index, 0), new GUILayoutOption[0]); + if (BuildPlayerWindow.styles.GetTargetNotInstalled(index, 1) != null && GUILayout.Button(BuildPlayerWindow.styles.GetTargetNotInstalled(index, 1), new GUILayoutOption[0])) + { + Application.OpenURL(BuildPlayerWindow.styles.GetTargetNotInstalled(index, 2).text); + } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + BuildPlayerWindow.GUIBuildButtons(flag3, enableBuildAndRunButton, canInstallInBuildFolder, buildPlatform); + } + private static void GUIBuildButtons(bool enableBuildButton, bool enableBuildAndRunButton, bool canInstallInBuildFolder, BuildPlayerWindow.BuildPlatform platform) + { + GUILayout.FlexibleSpace(); + if (canInstallInBuildFolder) + { + EditorUserBuildSettings.installInBuildFolder = GUILayout.Toggle(EditorUserBuildSettings.installInBuildFolder, "Install in Builds folder\n(for debugging with source code)", new GUILayoutOption[0]); + } + else + { + EditorUserBuildSettings.installInBuildFolder = false; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (platform.targetGroup == BuildTargetGroup.Android && EditorUserBuildSettings.appendProject) + { + enableBuildAndRunButton = false; + } + GUIContent content = BuildPlayerWindow.styles.build; + if (platform.targetGroup == BuildTargetGroup.Android && EditorUserBuildSettings.appendProject) + { + content = BuildPlayerWindow.styles.export; + } + if (platform.targetGroup == BuildTargetGroup.iPhone && Application.platform != RuntimePlatform.OSXEditor) + { + enableBuildAndRunButton = false; + } + GUI.enabled = enableBuildButton; + if (GUILayout.Button(content, new GUILayoutOption[] + { + GUILayout.Width(110f) + })) + { + BuildPlayerWindow.BuildPlayerWithDefaultSettings(true, BuildOptions.ShowBuiltPlayer); + GUIUtility.ExitGUI(); + } + GUI.enabled = enableBuildAndRunButton; + if (GUILayout.Button(BuildPlayerWindow.styles.buildAndRun, new GUILayoutOption[] + { + GUILayout.Width(110f) + })) + { + BuildPlayerWindow.BuildPlayerWithDefaultSettings(true, BuildOptions.AutoRunPlayer); + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + } + private static bool PickBuildLocation(BuildTarget target) + { + string buildLocation = EditorUserBuildSettings.GetBuildLocation(target); + if (target == BuildTarget.Android && EditorUserBuildSettings.appendProject) + { + string title = "Export Google Android Project"; + string location = EditorUtility.SaveFolderPanel(title, buildLocation, string.Empty); + EditorUserBuildSettings.SetBuildLocation(target, location); + return true; + } + string extensionForBuildTarget = PostprocessBuildPlayer.GetExtensionForBuildTarget(target); + string directory = FileUtil.DeleteLastPathNameComponent(buildLocation); + string lastPathNameComponent = FileUtil.GetLastPathNameComponent(buildLocation); + string title2 = "Build " + BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(target); + string text = EditorUtility.SaveBuildPanel(target, title2, directory, lastPathNameComponent, extensionForBuildTarget); + if (text == string.Empty) + { + return false; + } + if (extensionForBuildTarget != string.Empty && FileUtil.GetPathExtension(text).ToLower() != extensionForBuildTarget) + { + text = text + '.' + extensionForBuildTarget; + } + string lastPathNameComponent2 = FileUtil.GetLastPathNameComponent(text); + if (lastPathNameComponent2 == string.Empty) + { + return false; + } + string path = (!(extensionForBuildTarget != string.Empty)) ? text : FileUtil.DeleteLastPathNameComponent(text); + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + if (target == BuildTarget.iPhone && Application.platform != RuntimePlatform.OSXEditor && !BuildPlayerWindow.FolderIsEmpty(text) && !BuildPlayerWindow.UserWantsToDeleteFiles(text)) + { + return false; + } + EditorUserBuildSettings.SetBuildLocation(target, text); + return true; + } + private static bool FolderIsEmpty(string path) + { + return !Directory.Exists(path) || (Directory.GetDirectories(path).Length == 0 && Directory.GetFiles(path).Length == 0); + } + private static bool UserWantsToDeleteFiles(string path) + { + string message = "WARNING: all files and folders located in target folder: '" + path + "' will be deleted by build process."; + return EditorUtility.DisplayDialog("Deleting existing files", message, "OK", "Cancel"); + } + private static bool MetroAndWP8BuildRequirementsMet(out GUIContent msg) + { + if (!InternalEditorUtility.RunningUnderWindows8()) + { + msg = EditorGUIUtility.TextContent("BuildSettings.NoWindows8"); + return false; + } + msg = null; + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/BuildTarget.cs b/UnityEditor/UnityEditor/BuildTarget.cs new file mode 100644 index 00000000..57642cec --- /dev/null +++ b/UnityEditor/UnityEditor/BuildTarget.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEditor +{ + public enum BuildTarget + { + WebPlayer = 6, + WebPlayerStreamed, + StandaloneOSXIntel = 4, + StandaloneOSXIntel64 = 27, + StandaloneOSXUniversal = 2, + StandaloneWindows = 5, + iPhone = 9, + PS3, + XBOX360, + Android = 13, + StandaloneGLESEmu, + NaCl = 16, + StandaloneLinux, + StandaloneLinux64 = 24, + StandaloneLinuxUniversal, + FlashPlayer = 18, + StandaloneWindows64, + MetroPlayer = 21, + WP8Player = 26, + BB10 = 28, + BlackBerry = 28, + Tizen, + PSP2, + PS4, + PSM, + XboxOne, + SamsungTV + } +} diff --git a/UnityEditor/UnityEditor/BuildTargetGroup.cs b/UnityEditor/UnityEditor/BuildTargetGroup.cs new file mode 100644 index 00000000..e11d327e --- /dev/null +++ b/UnityEditor/UnityEditor/BuildTargetGroup.cs @@ -0,0 +1,27 @@ +using System; +namespace UnityEditor +{ + public enum BuildTargetGroup + { + Unknown, + Standalone, + WebPlayer, + iPhone = 4, + PS3, + XBOX360, + Android, + GLESEmu = 9, + NaCl = 11, + FlashPlayer, + Metro = 14, + WP8, + BB10, + BlackBerry = 16, + Tizen, + PSP2, + PS4, + PSM, + XboxOne, + SamsungTV + } +} diff --git a/UnityEditor/UnityEditor/BuildUploadCompletedWindow.cs b/UnityEditor/UnityEditor/BuildUploadCompletedWindow.cs new file mode 100644 index 00000000..adac2506 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildUploadCompletedWindow.cs @@ -0,0 +1,379 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class BuildUploadCompletedWindow : EditorWindow + { + public enum SocialNetwork + { + LinkedIn, + Facebook, + Twitter, + GooglePlus, + UnityDeveloperNetwork + } + private class Styles + { + public const float kWindowX = 100f; + public const float kWindowY = 100f; + public const float kWindowWidth = 470f; + public const float kWindowHeight = 170f; + public const float kWindowPadding = 5f; + public const float kBottomButtonWidth = 120f; + public const float kBottomButtonHeight = 20f; + public const float kIconSpacing = 10f; + public const float kIconSpacingRight = 5f; + public const float kLogoAreaWidth = 150f; + public const float kLogoAreaHeight = 150f; + public const float kCopyLabelIndentation = 4f; + public const float kCopyLabelConfirmDelay = 3f; + public const float kTextPaddingBottom = 4f; + public const int kMaxCopyLabelLength = 33; + public GUIStyle m_CopyLabelStyle; + public Texture2D m_FontColorTexture; + public Styles() + { + this.m_CopyLabelStyle = new GUIStyle(EditorStyles.label); + this.m_CopyLabelStyle.name = "CopyLabel"; + GUIStyle arg_43_0 = this.m_CopyLabelStyle; + RectOffset rectOffset = new RectOffset(0, 0, 0, 0); + this.m_CopyLabelStyle.padding = rectOffset; + arg_43_0.margin = rectOffset; + this.m_FontColorTexture = new Texture2D(1, 1); + this.m_FontColorTexture.SetPixels(new Color[] + { + EditorStyles.label.onNormal.textColor, + EditorStyles.label.onNormal.textColor + }); + this.m_FontColorTexture.Apply(); + } + } + private class Content + { + public const string kUDNStatusURL = "http://forum.unity3d.com"; + public const string kUDNPlayerControlPanelURL = "http://forum.unity3d.com"; + public GUIContent m_UDNLogo = EditorGUIUtility.IconContent("SocialNetworks.UDNLogo"); + public GUIContent m_LinkedInShare = EditorGUIUtility.IconContent("SocialNetworks.LinkedInShare"); + public GUIContent m_FacebookShare = EditorGUIUtility.IconContent("SocialNetworks.FacebookShare"); + public GUIContent m_Tweet = EditorGUIUtility.IconContent("SocialNetworks.Tweet"); + public GUIContent m_OpenInBrowser = EditorGUIUtility.IconContent("SocialNetworks.UDNOpen"); + public GUIContent m_PasteboardIcon = EditorGUIUtility.IconContent("Clipboard"); + public GUIContent m_WindowTitleSuccess = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.WindowTitleSuccess"); + public GUIContent m_TextHeaderSuccess = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.TextHeaderSuccess"); + public GUIContent m_MainTextSuccess = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.MainTextSuccess"); + public GUIContent m_WindowTitleFailure = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.WindowTitleFailure"); + public GUIContent m_TextHeaderFailure = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.TextHeaderFailure"); + public GUIContent m_MainTextFailureRecoverable = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.MainTextFailureRecoverable"); + public GUIContent m_MainTextFailureCritical = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.MainTextFailureCritical"); + public GUIContent m_FailurePreLinkAssistText = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.FailurePreLinkAssistText"); + public GUIContent m_UDNStatusLinkText = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.UDNStatusLinkText"); + public GUIContent m_FailurePostLinkAssistText = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.FailurePostLinkAssistText"); + public GUIContent m_ShareMessage = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.ShareMessage"); + public GUIContent m_CopyToClipboardMessage = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.CopyToClipboardMessage"); + public GUIContent m_DidCopyToClipboardMessage = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.DidCopyToClipboardMessage"); + public GUIContent m_CancelButton = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.CancelButton"); + public GUIContent m_FixButton = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.FixButton"); + public GUIContent m_CloseButton = EditorGUIUtility.TextContent("BuildUploadCompletedWindow.CloseButton"); + } + private static BuildUploadCompletedWindow.Styles s_Styles; + private static BuildUploadCompletedWindow.Content s_Content; + private bool m_Success; + private bool m_RecoverableError; + private string m_URL = string.Empty; + private string m_ShortURL = string.Empty; + private string m_ErrorMessage = string.Empty; + private double m_CopyLabelConfirmStart; + private float m_CopyLabelConfirmAlpha; + public static void LaunchSuccess(string url) + { + BuildUploadCompletedWindow buildUploadCompletedWindow = BuildUploadCompletedWindow.Launch(); + buildUploadCompletedWindow.title = BuildUploadCompletedWindow.s_Content.m_WindowTitleSuccess.text; + buildUploadCompletedWindow.m_Success = true; + buildUploadCompletedWindow.m_URL = url; + buildUploadCompletedWindow.m_ShortURL = BuildUploadCompletedWindow.ShortenURL(url); + } + public static void LaunchFailureCritical(string message) + { + BuildUploadCompletedWindow.LaunchFailure(message).m_RecoverableError = false; + } + public static void LaunchFailureRecoverable(string message) + { + BuildUploadCompletedWindow.LaunchFailure(message).m_RecoverableError = true; + } + private static BuildUploadCompletedWindow LaunchFailure(string message) + { + BuildUploadCompletedWindow buildUploadCompletedWindow = BuildUploadCompletedWindow.Launch(); + buildUploadCompletedWindow.title = BuildUploadCompletedWindow.s_Content.m_WindowTitleFailure.text; + buildUploadCompletedWindow.m_Success = false; + buildUploadCompletedWindow.m_ErrorMessage = message; + return buildUploadCompletedWindow; + } + private static BuildUploadCompletedWindow Launch() + { + BuildUploadCompletedWindow window = EditorWindow.GetWindow(true); + window.position = new Rect(100f, 100f, 470f, 170f); + window.minSize = new Vector2(470f, 170f); + window.maxSize = new Vector2(470f, 170f); + return window; + } + public static string ShortenURL(string url) + { + return url; + } + public static string GetShareURL(string url, string title, BuildUploadCompletedWindow.SocialNetwork network) + { + switch (network) + { + case BuildUploadCompletedWindow.SocialNetwork.LinkedIn: + return string.Format("http://www.linkedin.com/shareArticle?title={0}&source=%3A%2F%2Funity3d.com&url={1}", WWW.EscapeURL(title), WWW.EscapeURL(url)); + case BuildUploadCompletedWindow.SocialNetwork.Facebook: + return string.Format("http://www.facebook.com/sharer.php?t={0}&u={1}", WWW.EscapeURL(title), WWW.EscapeURL(url)); + case BuildUploadCompletedWindow.SocialNetwork.Twitter: + return string.Format("http://twitter.com/share?text={0}+{1}+%23unity3d", WWW.EscapeURL(title), WWW.EscapeURL(url)); + default: + throw new ArgumentException(string.Format("Social network {0} not supported", network)); + } + } + private bool LinkLabel(GUIContent content) + { + bool flag = !string.IsNullOrEmpty(content.text); + Rect position; + if (flag) + { + GUILayout.Label(content, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + position = GUILayoutUtility.GetLastRect(); + } + else + { + position = GUILayoutUtility.GetRect((float)content.image.width, (float)content.image.height); + } + EditorGUIUtility.AddCursorRect(position, MouseCursor.Link); + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + if (flag) + { + GUI.DrawTexture(new Rect(position.x, position.y + position.height - 3f, position.width, 1f), BuildUploadCompletedWindow.s_Styles.m_FontColorTexture); + } + else + { + GUI.DrawTexture(position, content.image); + } + } + } + else + { + if (position.Contains(Event.current.mousePosition)) + { + Event.current.Use(); + return true; + } + } + return false; + } + private void CopyLabel(string content, string copyMessage) + { + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.Space(4f); + GUILayout.Label(new GUIContent((content.Length <= 33) ? content : (content.Substring(0, 33) + "...")), BuildUploadCompletedWindow.s_Styles.m_CopyLabelStyle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + Rect lastRect = GUILayoutUtility.GetLastRect(); + GUILayout.Space(10f); + GUILayout.Label(new GUIContent(BuildUploadCompletedWindow.s_Content.m_PasteboardIcon.image), GUIStyle.none, new GUILayoutOption[] + { + GUILayout.Width((float)BuildUploadCompletedWindow.s_Content.m_PasteboardIcon.image.width), + GUILayout.Height((float)BuildUploadCompletedWindow.s_Content.m_PasteboardIcon.image.height) + }); + lastRect = new Rect(lastRect.x, lastRect.y, lastRect.width + (float)BuildUploadCompletedWindow.s_Content.m_PasteboardIcon.image.width + 10f, Mathf.Max(lastRect.height, (float)BuildUploadCompletedWindow.s_Content.m_PasteboardIcon.image.height)); + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + if (lastRect.Contains(Event.current.mousePosition)) + { + GUI.tooltip = BuildUploadCompletedWindow.s_Content.m_CopyToClipboardMessage.text; + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(lastRect.x, lastRect.y)); + GUI.s_ToolTipRect = new Rect(vector.x, vector.y, lastRect.width, lastRect.height); + } + if (this.m_CopyLabelConfirmAlpha > 0f && Event.current.type == EventType.Repaint) + { + lastRect = new Rect(lastRect.x, lastRect.y + lastRect.height - 1f, lastRect.width, lastRect.height); + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, this.m_CopyLabelConfirmAlpha); + EditorStyles.miniLabel.Draw(lastRect, new GUIContent(copyMessage), false, false, false, false); + GUI.color = color; + } + } + } + else + { + if (lastRect.Contains(Event.current.mousePosition)) + { + GUIUtility.systemCopyBuffer = content; + this.m_CopyLabelConfirmStart = EditorApplication.timeSinceStartup; + this.m_CopyLabelConfirmAlpha = 1f; + Event.current.Use(); + } + } + GUILayout.EndHorizontal(); + } + private void Update() + { + if (this.m_CopyLabelConfirmStart != 0.0 && EditorApplication.timeSinceStartup - this.m_CopyLabelConfirmStart > 3.0) + { + this.m_CopyLabelConfirmAlpha = 1f - (float)(EditorApplication.timeSinceStartup - this.m_CopyLabelConfirmStart - 3.0); + if (this.m_CopyLabelConfirmAlpha <= 0f) + { + this.m_CopyLabelConfirmAlpha = 0f; + this.m_CopyLabelConfirmStart = 0.0; + } + base.Repaint(); + } + } + private void OnGUI() + { + if (BuildUploadCompletedWindow.s_Styles == null) + { + BuildUploadCompletedWindow.s_Styles = new BuildUploadCompletedWindow.Styles(); + } + if (BuildUploadCompletedWindow.s_Content == null) + { + BuildUploadCompletedWindow.s_Content = new BuildUploadCompletedWindow.Content(); + } + GUILayout.BeginArea(new Rect(5f, 5f, (float)Screen.width - 10f, (float)Screen.height - 10f)); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(150f, 150f); + if (Event.current.type == EventType.Repaint) + { + GUI.DrawTexture(new Rect(rect.x, rect.y, (float)BuildUploadCompletedWindow.s_Content.m_UDNLogo.image.width, (float)BuildUploadCompletedWindow.s_Content.m_UDNLogo.image.height), BuildUploadCompletedWindow.s_Content.m_UDNLogo.image); + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (this.m_Success) + { + this.OnSuccessGUI(); + } + else + { + this.OnFailureGUI(); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } + private void OnFailureGUI() + { + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_TextHeaderFailure.text, EditorStyles.boldLabel, new GUILayoutOption[0]); + if (this.m_RecoverableError) + { + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_MainTextFailureRecoverable.text + ":", EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Label(this.m_ErrorMessage, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + else + { + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_MainTextFailureCritical.text + ":", EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Label(this.m_ErrorMessage, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_FailurePreLinkAssistText.text, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + if (this.LinkLabel(BuildUploadCompletedWindow.s_Content.m_UDNStatusLinkText)) + { + Application.OpenURL("http://forum.unity3d.com"); + } + GUILayout.EndHorizontal(); + GUILayout.Space(-8f); + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_FailurePostLinkAssistText, new GUILayoutOption[0]); + } + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (this.m_RecoverableError) + { + if (GUILayout.Button(BuildUploadCompletedWindow.s_Content.m_CancelButton, new GUILayoutOption[] + { + GUILayout.Width(120f), + GUILayout.Height(20f) + })) + { + base.Close(); + } + if (GUILayout.Button(BuildUploadCompletedWindow.s_Content.m_FixButton, new GUILayoutOption[] + { + GUILayout.Width(120f), + GUILayout.Height(20f) + })) + { + Application.OpenURL("http://forum.unity3d.com"); + base.Close(); + } + } + else + { + if (GUILayout.Button(BuildUploadCompletedWindow.s_Content.m_CloseButton.text, new GUILayoutOption[] + { + GUILayout.Width(120f), + GUILayout.Height(20f) + })) + { + base.Close(); + } + } + GUILayout.EndHorizontal(); + } + private void OnSuccessGUI() + { + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_TextHeaderSuccess.text, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label(BuildUploadCompletedWindow.s_Content.m_MainTextSuccess.text, EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.Space(4f); + this.CopyLabel(this.m_ShortURL, BuildUploadCompletedWindow.s_Content.m_DidCopyToClipboardMessage.text); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (this.LinkLabel(BuildUploadCompletedWindow.s_Content.m_OpenInBrowser)) + { + Application.OpenURL(this.m_URL); + } + GUILayout.Space(10f); + if (this.LinkLabel(BuildUploadCompletedWindow.s_Content.m_Tweet)) + { + Application.OpenURL(BuildUploadCompletedWindow.GetShareURL(this.m_ShortURL, BuildUploadCompletedWindow.s_Content.m_ShareMessage.text, BuildUploadCompletedWindow.SocialNetwork.Twitter)); + } + GUILayout.Space(10f); + if (this.LinkLabel(BuildUploadCompletedWindow.s_Content.m_LinkedInShare)) + { + Application.OpenURL(BuildUploadCompletedWindow.GetShareURL(this.m_ShortURL, BuildUploadCompletedWindow.s_Content.m_ShareMessage.text, BuildUploadCompletedWindow.SocialNetwork.LinkedIn)); + } + GUILayout.Space(10f); + if (this.LinkLabel(BuildUploadCompletedWindow.s_Content.m_FacebookShare)) + { + Application.OpenURL(BuildUploadCompletedWindow.GetShareURL(this.m_ShortURL, BuildUploadCompletedWindow.s_Content.m_ShareMessage.text, BuildUploadCompletedWindow.SocialNetwork.Facebook)); + } + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(BuildUploadCompletedWindow.s_Content.m_CloseButton.text, new GUILayoutOption[] + { + GUILayout.Width(120f), + GUILayout.Height(20f) + })) + { + base.Close(); + } + GUILayout.EndHorizontal(); + } + } +} diff --git a/UnityEditor/UnityEditor/BuildVerifier.cs b/UnityEditor/UnityEditor/BuildVerifier.cs new file mode 100644 index 00000000..a5858006 --- /dev/null +++ b/UnityEditor/UnityEditor/BuildVerifier.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Xml.XPath; +using UnityEngine; +namespace UnityEditor +{ + internal class BuildVerifier + { + private Dictionary> m_UnsupportedAssemblies; + private static BuildVerifier ms_Inst; + protected BuildVerifier() + { + this.m_UnsupportedAssemblies = new Dictionary>(); + string text = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath, "Resources"), "BuildVerification.xml"); + XPathDocument xPathDocument = new XPathDocument(text); + XPathNavigator xPathNavigator = xPathDocument.CreateNavigator(); + xPathNavigator.MoveToFirstChild(); + XPathNodeIterator xPathNodeIterator = xPathNavigator.SelectChildren("assembly", string.Empty); + while (xPathNodeIterator.MoveNext()) + { + string attribute = xPathNodeIterator.Current.GetAttribute("name", string.Empty); + if (attribute == null || attribute.Length < 1) + { + throw new ApplicationException(string.Format("Failed to load {0}, name attribute is empty", text)); + } + string text2 = xPathNodeIterator.Current.GetAttribute("platform", string.Empty); + if (text2 == null || text2.Length < 1) + { + text2 = "*"; + } + if (!this.m_UnsupportedAssemblies.ContainsKey(text2)) + { + this.m_UnsupportedAssemblies.Add(text2, new HashSet()); + } + this.m_UnsupportedAssemblies[text2].Add(attribute); + } + } + protected void VerifyBuildInternal(BuildTarget target, string managedDllFolder) + { + string[] files = Directory.GetFiles(managedDllFolder); + for (int i = 0; i < files.Length; i++) + { + string text = files[i]; + if (text.EndsWith(".dll")) + { + string fileName = Path.GetFileName(text); + if (!this.VerifyAssembly(target, fileName)) + { + Debug.LogWarning(string.Format("{0} assembly is referenced by user code, but is not supported on {1} platform. Various failures might follow.", fileName, target.ToString())); + } + } + } + } + protected bool VerifyAssembly(BuildTarget target, string assembly) + { + return (!this.m_UnsupportedAssemblies.ContainsKey("*") || !this.m_UnsupportedAssemblies["*"].Contains(assembly)) && (!this.m_UnsupportedAssemblies.ContainsKey(target.ToString()) || !this.m_UnsupportedAssemblies[target.ToString()].Contains(assembly)); + } + public static void VerifyBuild(BuildTarget target, string managedDllFolder) + { + if (BuildVerifier.ms_Inst == null) + { + BuildVerifier.ms_Inst = new BuildVerifier(); + } + BuildVerifier.ms_Inst.VerifyBuildInternal(target, managedDllFolder); + } + } +} diff --git a/UnityEditor/UnityEditor/BuiltinResource.cs b/UnityEditor/UnityEditor/BuiltinResource.cs new file mode 100644 index 00000000..b17ebaf8 --- /dev/null +++ b/UnityEditor/UnityEditor/BuiltinResource.cs @@ -0,0 +1,11 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + internal sealed class BuiltinResource + { + public string m_Name; + public int m_InstanceID; + } +} diff --git a/UnityEditor/UnityEditor/BumpMapSettingsFixingWindow.cs b/UnityEditor/UnityEditor/BumpMapSettingsFixingWindow.cs new file mode 100644 index 00000000..49b8fda0 --- /dev/null +++ b/UnityEditor/UnityEditor/BumpMapSettingsFixingWindow.cs @@ -0,0 +1,78 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class BumpMapSettingsFixingWindow : EditorWindow + { + private class Styles + { + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle box = "OL Box"; + public GUIStyle button = "LargeButton"; + public GUIContent overviewText = EditorGUIUtility.TextContent("BumpMapSettingsFixingWindow.overviewText"); + } + private static BumpMapSettingsFixingWindow.Styles s_Styles; + private ListViewState m_LV = new ListViewState(); + private string[] m_Paths; + public BumpMapSettingsFixingWindow() + { + base.title = "NormalMap settings"; + } + public static void ShowWindow(string[] paths) + { + BumpMapSettingsFixingWindow window = EditorWindow.GetWindow(true); + window.SetPaths(paths); + window.ShowUtility(); + } + public void SetPaths(string[] paths) + { + this.m_Paths = paths; + this.m_LV.totalRows = paths.Length; + } + private void OnGUI() + { + if (BumpMapSettingsFixingWindow.s_Styles == null) + { + BumpMapSettingsFixingWindow.s_Styles = new BumpMapSettingsFixingWindow.Styles(); + base.minSize = new Vector2(400f, 300f); + base.position = new Rect(base.position.x, base.position.y, base.minSize.x, base.minSize.y); + } + GUILayout.Space(5f); + GUILayout.Label(BumpMapSettingsFixingWindow.s_Styles.overviewText, new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.m_LV, BumpMapSettingsFixingWindow.s_Styles.box, new GUILayoutOption[0])) + { + if (listViewElement.row == this.m_LV.row && Event.current.type == EventType.Repaint) + { + BumpMapSettingsFixingWindow.s_Styles.selected.Draw(listViewElement.position, false, false, false, false); + } + GUILayout.Label(this.m_Paths[listViewElement.row], new GUILayoutOption[0]); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Fix now", BumpMapSettingsFixingWindow.s_Styles.button, new GUILayoutOption[0])) + { + InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(1); + base.Close(); + } + if (GUILayout.Button("Ignore", BumpMapSettingsFixingWindow.s_Styles.button, new GUILayoutOption[0])) + { + InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); + base.Close(); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + } + private void OnDestroy() + { + InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); + } + } +} diff --git a/UnityEditor/UnityEditor/CacheServerPreferences.cs b/UnityEditor/UnityEditor/CacheServerPreferences.cs new file mode 100644 index 00000000..b5dce192 --- /dev/null +++ b/UnityEditor/UnityEditor/CacheServerPreferences.cs @@ -0,0 +1,87 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class CacheServerPreferences + { + private enum ConnectionState + { + Unknown, + Success, + Failure + } + private static bool s_PrefsLoaded; + private static CacheServerPreferences.ConnectionState s_ConnectionState; + private static bool s_CacheServerEnabled; + private static string s_CacheServerIPAddress; + public static void ReadPreferences() + { + CacheServerPreferences.s_CacheServerIPAddress = EditorPrefs.GetString("CacheServerIPAddress", CacheServerPreferences.s_CacheServerIPAddress); + CacheServerPreferences.s_CacheServerEnabled = EditorPrefs.GetBool("CacheServerEnabled"); + } + public static void WritePreferences() + { + EditorPrefs.SetString("CacheServerIPAddress", CacheServerPreferences.s_CacheServerIPAddress); + EditorPrefs.SetBool("CacheServerEnabled", CacheServerPreferences.s_CacheServerEnabled); + } + [PreferenceItem("Cache Server")] + public static void OnGUI() + { + GUILayout.Space(10f); + if (!InternalEditorUtility.HasMaint()) + { + GUILayout.Label(EditorGUIUtility.TempContent("You need to have an Asset Server license to use the cache server.", EditorGUIUtility.GetHelpIcon(MessageType.Warning)), EditorStyles.helpBox, new GUILayoutOption[0]); + } + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasMaint()); + if (!CacheServerPreferences.s_PrefsLoaded) + { + CacheServerPreferences.ReadPreferences(); + CacheServerPreferences.s_PrefsLoaded = true; + } + EditorGUI.BeginChangeCheck(); + CacheServerPreferences.s_CacheServerEnabled = EditorGUILayout.Toggle("Use Cache Server", CacheServerPreferences.s_CacheServerEnabled, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!CacheServerPreferences.s_CacheServerEnabled); + CacheServerPreferences.s_CacheServerIPAddress = EditorGUILayout.TextField("IP Address", CacheServerPreferences.s_CacheServerIPAddress, new GUILayoutOption[0]); + if (GUI.changed) + { + CacheServerPreferences.s_ConnectionState = CacheServerPreferences.ConnectionState.Unknown; + } + GUILayout.Space(5f); + if (GUILayout.Button("Check Connection", new GUILayoutOption[] + { + GUILayout.Width(150f) + })) + { + if (InternalEditorUtility.CanConnectToCacheServer()) + { + CacheServerPreferences.s_ConnectionState = CacheServerPreferences.ConnectionState.Success; + } + else + { + CacheServerPreferences.s_ConnectionState = CacheServerPreferences.ConnectionState.Failure; + } + } + GUILayout.Space(-25f); + CacheServerPreferences.ConnectionState connectionState = CacheServerPreferences.s_ConnectionState; + if (connectionState != CacheServerPreferences.ConnectionState.Success) + { + if (connectionState == CacheServerPreferences.ConnectionState.Failure) + { + EditorGUILayout.HelpBox("Connection failed.", MessageType.Warning, false); + } + } + else + { + EditorGUILayout.HelpBox("Connection successful.", MessageType.Info, false); + } + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + CacheServerPreferences.WritePreferences(); + CacheServerPreferences.ReadPreferences(); + } + EditorGUI.EndDisabledGroup(); + } + } +} diff --git a/UnityEditor/UnityEditor/CallbackOrderAttribute.cs b/UnityEditor/UnityEditor/CallbackOrderAttribute.cs new file mode 100644 index 00000000..7e4f07ee --- /dev/null +++ b/UnityEditor/UnityEditor/CallbackOrderAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor +{ + public abstract class CallbackOrderAttribute : Attribute + { + protected int m_CallbackOrder; + internal int callbackOrder + { + get + { + return this.m_CallbackOrder; + } + } + } +} diff --git a/UnityEditor/UnityEditor/CameraEditor.cs b/UnityEditor/UnityEditor/CameraEditor.cs new file mode 100644 index 00000000..1fc69d3e --- /dev/null +++ b/UnityEditor/UnityEditor/CameraEditor.cs @@ -0,0 +1,368 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Camera))] + internal class CameraEditor : Editor + { + private enum ProjectionType + { + Perspective, + Orthographic + } + private const float kPreviewWindowOffset = 10f; + private const float kPreviewNormalizedSize = 0.2f; + private SerializedProperty m_ClearFlags; + private SerializedProperty m_BackgroundColor; + private SerializedProperty m_NormalizedViewPortRect; + private SerializedProperty m_NearClip; + private SerializedProperty m_FarClip; + private SerializedProperty m_FieldOfView; + private SerializedProperty m_Orthographic; + private SerializedProperty m_OrthographicSize; + private SerializedProperty m_Depth; + private SerializedProperty m_CullingMask; + private SerializedProperty m_RenderingPath; + private SerializedProperty m_OcclusionCulling; + private SerializedProperty m_TargetTexture; + private SerializedProperty m_HDR; + private AnimBool m_ShowBGColorOptions = new AnimBool(); + private AnimBool m_ShowOrthoOptions = new AnimBool(); + private AnimBool m_ShowDeferredWarning = new AnimBool(); + private Camera m_PreviewCamera; + private static readonly Color kGizmoCamera = new Color(0.9137255f, 0.9137255f, 0.9137255f, 0.5019608f); + private GUIContent m_ClipingPlanesLabel = new GUIContent("Clipping Planes"); + private GUIContent m_NearClipPlaneLabel = new GUIContent("Near"); + private GUIContent m_FarClipPlaneLabel = new GUIContent("Far"); + private GUIContent m_ViewportLabel = new GUIContent("Viewport Rect"); + private Camera camera + { + get + { + return this.target as Camera; + } + } + private bool deferredWarningValue + { + get + { + return !InternalEditorUtility.HasPro() && (this.camera.renderingPath == RenderingPath.DeferredLighting || (PlayerSettings.renderingPath == RenderingPath.DeferredLighting && this.camera.renderingPath == RenderingPath.UsePlayerSettings)); + } + } + private Camera previewCamera + { + get + { + if (this.m_PreviewCamera == null) + { + this.m_PreviewCamera = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, new Type[] + { + typeof(Camera) + }).GetComponent(); + } + this.m_PreviewCamera.enabled = false; + return this.m_PreviewCamera; + } + } + public void OnEnable() + { + this.m_ClearFlags = base.serializedObject.FindProperty("m_ClearFlags"); + this.m_BackgroundColor = base.serializedObject.FindProperty("m_BackGroundColor"); + this.m_NormalizedViewPortRect = base.serializedObject.FindProperty("m_NormalizedViewPortRect"); + this.m_NearClip = base.serializedObject.FindProperty("near clip plane"); + this.m_FarClip = base.serializedObject.FindProperty("far clip plane"); + this.m_FieldOfView = base.serializedObject.FindProperty("field of view"); + this.m_Orthographic = base.serializedObject.FindProperty("orthographic"); + this.m_OrthographicSize = base.serializedObject.FindProperty("orthographic size"); + this.m_Depth = base.serializedObject.FindProperty("m_Depth"); + this.m_CullingMask = base.serializedObject.FindProperty("m_CullingMask"); + this.m_RenderingPath = base.serializedObject.FindProperty("m_RenderingPath"); + this.m_OcclusionCulling = base.serializedObject.FindProperty("m_OcclusionCulling"); + this.m_TargetTexture = base.serializedObject.FindProperty("m_TargetTexture"); + this.m_HDR = base.serializedObject.FindProperty("m_HDR"); + Camera camera = (Camera)this.target; + this.m_ShowBGColorOptions.value = (!this.m_ClearFlags.hasMultipleDifferentValues && (camera.clearFlags == CameraClearFlags.Color || camera.clearFlags == CameraClearFlags.Skybox)); + this.m_ShowOrthoOptions.value = camera.orthographic; + this.m_ShowDeferredWarning.value = this.deferredWarningValue; + this.m_ShowBGColorOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowOrthoOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowDeferredWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + private void OnDisable() + { + this.m_ShowBGColorOptions.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_ShowOrthoOptions.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_ShowDeferredWarning.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Camera camera = (Camera)this.target; + this.m_ShowBGColorOptions.target = (!this.m_ClearFlags.hasMultipleDifferentValues && (camera.clearFlags == CameraClearFlags.Color || camera.clearFlags == CameraClearFlags.Skybox)); + this.m_ShowOrthoOptions.target = (!this.m_Orthographic.hasMultipleDifferentValues && camera.orthographic); + this.m_ShowDeferredWarning.target = this.deferredWarningValue; + EditorGUILayout.PropertyField(this.m_ClearFlags, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBGColorOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_BackgroundColor, new GUIContent("Background", "Camera clears the screen to this color before rendering."), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]); + EditorGUILayout.Space(); + CameraEditor.ProjectionType projectionType = (!this.m_Orthographic.boolValue) ? CameraEditor.ProjectionType.Perspective : CameraEditor.ProjectionType.Orthographic; + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_Orthographic.hasMultipleDifferentValues; + projectionType = (CameraEditor.ProjectionType)EditorGUILayout.EnumPopup("Projection", projectionType, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_Orthographic.boolValue = (projectionType == CameraEditor.ProjectionType.Orthographic); + } + if (!this.m_Orthographic.hasMultipleDifferentValues) + { + if (EditorGUILayout.BeginFadeGroup(this.m_ShowOrthoOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_OrthographicSize, new GUIContent("Size"), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowOrthoOptions.faded)) + { + EditorGUILayout.Slider(this.m_FieldOfView, 1f, 179f, new GUIContent("Field of View"), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + } + Rect controlRect = EditorGUILayout.GetControlRect(true, 32f, new GUILayoutOption[0]); + controlRect.height = 16f; + GUI.Label(controlRect, this.m_ClipingPlanesLabel); + controlRect.xMin += EditorGUIUtility.labelWidth - 1f; + EditorGUIUtility.labelWidth = 32f; + EditorGUI.PropertyField(controlRect, this.m_NearClip, this.m_NearClipPlaneLabel); + controlRect.y += 16f; + EditorGUI.PropertyField(controlRect, this.m_FarClip, this.m_FarClipPlaneLabel); + EditorGUIUtility.labelWidth = 0f; + EditorGUILayout.PropertyField(this.m_NormalizedViewPortRect, this.m_ViewportLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_Depth, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_RenderingPath, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowDeferredWarning.faded)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("CameraEditor.DeferredProOnly"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.PropertyField(this.m_TargetTexture, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_OcclusionCulling, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_HDR, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public void OnOverlayGUI(UnityEngine.Object target, SceneView sceneView) + { + if (target == null) + { + return; + } + Camera camera = (Camera)target; + Vector2 sizeOfMainGameView = GameView.GetSizeOfMainGameView(); + if (sizeOfMainGameView.x < 0f) + { + sizeOfMainGameView.x = sceneView.position.width; + sizeOfMainGameView.y = sceneView.position.height; + } + Rect rect = camera.rect; + sizeOfMainGameView.x *= Mathf.Max(rect.width, 0f); + sizeOfMainGameView.y *= Mathf.Max(rect.height, 0f); + if (sizeOfMainGameView.x <= 0f || sizeOfMainGameView.y <= 0f) + { + return; + } + float num = sizeOfMainGameView.x / sizeOfMainGameView.y; + sizeOfMainGameView.y = 0.2f * sceneView.position.height; + sizeOfMainGameView.x = sizeOfMainGameView.y * num; + if (sizeOfMainGameView.y > sceneView.position.height * 0.5f) + { + sizeOfMainGameView.y = sceneView.position.height * 0.5f; + sizeOfMainGameView.x = sizeOfMainGameView.y * num; + } + if (sizeOfMainGameView.x > sceneView.position.width * 0.5f) + { + sizeOfMainGameView.x = sceneView.position.width * 0.5f; + sizeOfMainGameView.y = sizeOfMainGameView.x / num; + } + Rect rect2 = GUILayoutUtility.GetRect(sizeOfMainGameView.x, sizeOfMainGameView.y); + rect2.y = sceneView.position.height - rect2.y - rect2.height + 1f; + if (Event.current.type == EventType.Repaint) + { + this.previewCamera.CopyFrom(camera); + this.previewCamera.targetTexture = null; + this.previewCamera.pixelRect = rect2; + Handles.EmitGUIGeometryForCamera(camera, this.previewCamera); + this.previewCamera.Render(); + } + } + private static float GetGameViewAspectRatio(Camera fallbackCamera) + { + Vector2 sizeOfMainGameView = GameView.GetSizeOfMainGameView(); + if (sizeOfMainGameView.x < 0f) + { + sizeOfMainGameView.x = (float)Screen.width; + sizeOfMainGameView.y = (float)Screen.height; + } + return sizeOfMainGameView.x / sizeOfMainGameView.y; + } + private static float GetFrustumAspectRatio(Camera camera) + { + Rect rect = camera.rect; + if (rect.width <= 0f || rect.height <= 0f) + { + return -1f; + } + float num = rect.width / rect.height; + return CameraEditor.GetGameViewAspectRatio(camera) * num; + } + private static bool GetFrustum(Camera camera, Vector3[] near, Vector3[] far, out float frustumAspect) + { + frustumAspect = CameraEditor.GetFrustumAspectRatio(camera); + if (frustumAspect < 0f) + { + return false; + } + float num3; + float num4; + float num5; + float num6; + if (!camera.isOrthoGraphic) + { + float num = Mathf.Tan(camera.fieldOfView * 0.0174532924f * 0.5f); + float num2 = num * frustumAspect; + num3 = num2 * camera.farClipPlane; + num4 = num * camera.farClipPlane; + num5 = num2 * camera.nearClipPlane; + num6 = num * camera.nearClipPlane; + } + else + { + float num = camera.orthographicSize; + float num2 = num * frustumAspect; + num3 = num2; + num4 = num; + num5 = num2; + num6 = num; + } + Matrix4x4 matrix4x = Matrix4x4.TRS(camera.transform.position, camera.transform.rotation, Vector3.one); + if (far != null) + { + far[0] = new Vector3(-num3, -num4, camera.farClipPlane); + far[1] = new Vector3(-num3, num4, camera.farClipPlane); + far[2] = new Vector3(num3, num4, camera.farClipPlane); + far[3] = new Vector3(num3, -num4, camera.farClipPlane); + for (int i = 0; i < 4; i++) + { + far[i] = matrix4x.MultiplyPoint(far[i]); + } + } + if (near != null) + { + near[0] = new Vector3(-num5, -num6, camera.nearClipPlane); + near[1] = new Vector3(-num5, num6, camera.nearClipPlane); + near[2] = new Vector3(num5, num6, camera.nearClipPlane); + near[3] = new Vector3(num5, -num6, camera.nearClipPlane); + for (int j = 0; j < 4; j++) + { + near[j] = matrix4x.MultiplyPoint(near[j]); + } + } + return true; + } + private static void RenderGizmo(Camera camera) + { + Vector3[] array = new Vector3[4]; + Vector3[] array2 = new Vector3[4]; + float num; + if (CameraEditor.GetFrustum(camera, array, array2, out num)) + { + Color color = Handles.color; + Handles.color = CameraEditor.kGizmoCamera; + for (int i = 0; i < 4; i++) + { + Handles.DrawLine(array[i], array[(i + 1) % 4]); + Handles.DrawLine(array2[i], array2[(i + 1) % 4]); + Handles.DrawLine(array[i], array2[i]); + } + Handles.color = color; + } + } + private static bool IsViewPortRectValidToRender(Rect normalizedViewPortRect) + { + return normalizedViewPortRect.width > 0f && normalizedViewPortRect.height > 0f && normalizedViewPortRect.x < 1f && normalizedViewPortRect.xMax > 0f && normalizedViewPortRect.y < 1f && normalizedViewPortRect.yMax > 0f; + } + public void OnSceneGUI() + { + Camera camera = (Camera)this.target; + if (!CameraEditor.IsViewPortRectValidToRender(camera.rect)) + { + return; + } + SceneViewOverlay.Window(new GUIContent("Camera Preview"), new SceneViewOverlay.WindowFunction(this.OnOverlayGUI), -100, this.target, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + Color color = Handles.color; + Color color2 = CameraEditor.kGizmoCamera; + color2.a *= 2f; + Handles.color = color2; + Vector3[] array = new Vector3[4]; + float num; + if (!CameraEditor.GetFrustum(camera, null, array, out num)) + { + return; + } + Vector3 vector = array[0]; + Vector3 vector2 = array[1]; + Vector3 vector3 = array[2]; + Vector3 vector4 = array[3]; + bool changed = GUI.changed; + Vector3 vector5 = Vector3.Lerp(vector, vector3, 0.5f); + float num2 = -1f; + Vector3 a = CameraEditor.MidPointPositionSlider(vector2, vector3, camera.transform.up); + if (!GUI.changed) + { + a = CameraEditor.MidPointPositionSlider(vector, vector4, -camera.transform.up); + } + if (GUI.changed) + { + num2 = (a - vector5).magnitude; + } + GUI.changed = false; + a = CameraEditor.MidPointPositionSlider(vector4, vector3, camera.transform.right); + if (!GUI.changed) + { + a = CameraEditor.MidPointPositionSlider(vector, vector2, -camera.transform.right); + } + if (GUI.changed) + { + num2 = (a - vector5).magnitude / num; + } + if (num2 >= 0f) + { + Undo.RecordObject(camera, "Adjust Camera"); + if (camera.orthographic) + { + camera.orthographicSize = num2; + } + else + { + Vector3 a2 = vector5 + camera.transform.up * num2; + camera.fieldOfView = Vector3.Angle(camera.transform.forward, a2 - camera.transform.position) * 2f; + } + changed = true; + } + GUI.changed = changed; + Handles.color = color; + } + private static Vector3 MidPointPositionSlider(Vector3 position1, Vector3 position2, Vector3 direction) + { + Vector3 position3 = Vector3.Lerp(position1, position2, 0.5f); + return Handles.Slider(position3, direction, HandleUtility.GetHandleSize(position3) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + } + } +} diff --git a/UnityEditor/UnityEditor/CanEditMultipleObjects.cs b/UnityEditor/UnityEditor/CanEditMultipleObjects.cs new file mode 100644 index 00000000..2bd7e9dd --- /dev/null +++ b/UnityEditor/UnityEditor/CanEditMultipleObjects.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + public sealed class CanEditMultipleObjects : Attribute + { + } +} diff --git a/UnityEditor/UnityEditor/CanvasEditor.cs b/UnityEditor/UnityEditor/CanvasEditor.cs new file mode 100644 index 00000000..d88871cf --- /dev/null +++ b/UnityEditor/UnityEditor/CanvasEditor.cs @@ -0,0 +1,193 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Canvas))] + internal class CanvasEditor : Editor + { + private enum PixelPerfect + { + Inherit, + On, + Off + } + private SerializedProperty m_RenderMode; + private SerializedProperty m_Camera; + private SerializedProperty m_PixelPerfect; + private SerializedProperty m_PixelPerfectOverride; + private SerializedProperty m_PlaneDistance; + private SerializedProperty m_SortingLayerID; + private SerializedProperty m_SortingOrder; + private SerializedProperty m_OverrideSorting; + private AnimBool m_OverlayMode; + private AnimBool m_CameraMode; + private AnimBool m_WorldMode; + private AnimBool m_SortingOverride; + private GUIContent eventCamera = new GUIContent("Event Camera", "The Camera which the events are triggered through. This is used to determine clicking and hover positions if the Canvas is in World Space render mode."); + private GUIContent renderCamera = new GUIContent("Render Camera", "The Camera which will render the canvas. This is also the camera used to send events."); + private GUIContent sortingOrder = new GUIContent("Sort Order", "The order in which Screen Space - Overlay canvas will render"); + private static string s_RootAndNestedMessage = "Cannot multi-edit root Canvas together with nested Canvas."; + private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingLayer"); + private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingOrder"); + private bool m_AllNested; + private bool m_AllRoot; + private bool m_AllOverlay; + private bool m_NoneOverlay; + private CanvasEditor.PixelPerfect pixelPerfect; + private void OnEnable() + { + this.m_RenderMode = base.serializedObject.FindProperty("m_RenderMode"); + this.m_Camera = base.serializedObject.FindProperty("m_Camera"); + this.m_PixelPerfect = base.serializedObject.FindProperty("m_PixelPerfect"); + this.m_PlaneDistance = base.serializedObject.FindProperty("m_PlaneDistance"); + this.m_SortingLayerID = base.serializedObject.FindProperty("m_SortingLayerID"); + this.m_SortingOrder = base.serializedObject.FindProperty("m_SortingOrder"); + this.m_OverrideSorting = base.serializedObject.FindProperty("m_OverrideSorting"); + this.m_PixelPerfectOverride = base.serializedObject.FindProperty("m_OverridePixelPerfect"); + this.m_OverlayMode = new AnimBool(this.m_RenderMode.intValue == 0); + this.m_OverlayMode.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_CameraMode = new AnimBool(this.m_RenderMode.intValue == 1); + this.m_CameraMode.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_WorldMode = new AnimBool(this.m_RenderMode.intValue == 2); + this.m_WorldMode.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_SortingOverride = new AnimBool(this.m_OverrideSorting.boolValue); + this.m_SortingOverride.valueChanged.AddListener(new UnityAction(base.Repaint)); + if (this.m_PixelPerfectOverride.boolValue) + { + this.pixelPerfect = ((!this.m_PixelPerfect.boolValue) ? CanvasEditor.PixelPerfect.Off : CanvasEditor.PixelPerfect.On); + } + else + { + this.pixelPerfect = CanvasEditor.PixelPerfect.Inherit; + } + this.m_AllNested = true; + this.m_AllRoot = true; + this.m_AllOverlay = true; + this.m_NoneOverlay = true; + for (int i = 0; i < base.targets.Length; i++) + { + Canvas canvas = base.targets[i] as Canvas; + if (canvas.transform.parent == null) + { + this.m_AllNested = false; + } + else + { + if (canvas.transform.parent.GetComponentInParent() == null) + { + this.m_AllNested = false; + } + else + { + this.m_AllRoot = false; + } + } + if (canvas.renderMode == RenderMode.ScreenSpaceOverlay) + { + this.m_NoneOverlay = false; + } + else + { + this.m_AllOverlay = false; + } + } + } + private void OnDisable() + { + this.m_OverlayMode.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_CameraMode.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_WorldMode.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_SortingOverride.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + if (this.m_AllRoot) + { + EditorGUILayout.PropertyField(this.m_RenderMode, new GUILayoutOption[0]); + this.m_OverlayMode.target = (this.m_RenderMode.intValue == 0); + this.m_CameraMode.target = (this.m_RenderMode.intValue == 1); + this.m_WorldMode.target = (this.m_RenderMode.intValue == 2); + EditorGUI.indentLevel++; + if (EditorGUILayout.BeginFadeGroup(this.m_OverlayMode.faded)) + { + EditorGUILayout.PropertyField(this.m_PixelPerfect, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.sortingOrder, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_CameraMode.faded)) + { + EditorGUILayout.PropertyField(this.m_PixelPerfect, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Camera, this.renderCamera, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PlaneDistance, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_WorldMode.faded)) + { + EditorGUILayout.PropertyField(this.m_Camera, this.eventCamera, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + } + else + { + if (this.m_AllNested) + { + EditorGUI.BeginChangeCheck(); + this.pixelPerfect = (CanvasEditor.PixelPerfect)EditorGUILayout.EnumPopup("Pixel Perfect", this.pixelPerfect, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (this.pixelPerfect == CanvasEditor.PixelPerfect.Inherit) + { + this.m_PixelPerfectOverride.boolValue = false; + } + else + { + if (this.pixelPerfect == CanvasEditor.PixelPerfect.Off) + { + this.m_PixelPerfectOverride.boolValue = true; + this.m_PixelPerfect.boolValue = false; + } + else + { + this.m_PixelPerfectOverride.boolValue = true; + this.m_PixelPerfect.boolValue = true; + } + } + } + EditorGUILayout.PropertyField(this.m_OverrideSorting, new GUILayoutOption[0]); + this.m_SortingOverride.target = this.m_OverrideSorting.boolValue; + if (EditorGUILayout.BeginFadeGroup(this.m_SortingOverride.faded)) + { + if (this.m_AllOverlay) + { + EditorGUILayout.PropertyField(this.m_SortingOrder, this.sortingOrder, new GUILayoutOption[0]); + } + else + { + if (this.m_NoneOverlay) + { + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + } + } + } + EditorGUILayout.EndFadeGroup(); + } + else + { + GUILayout.Label(CanvasEditor.s_RootAndNestedMessage, EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/CapsuleColliderEditor.cs b/UnityEditor/UnityEditor/CapsuleColliderEditor.cs new file mode 100644 index 00000000..27559980 --- /dev/null +++ b/UnityEditor/UnityEditor/CapsuleColliderEditor.cs @@ -0,0 +1,137 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(CapsuleCollider))] + internal class CapsuleColliderEditor : Collider3DEditorBase + { + private SerializedProperty m_Center; + private SerializedProperty m_Radius; + private SerializedProperty m_Height; + private SerializedProperty m_Direction; + private int m_HandleControlID; + public override void OnEnable() + { + base.OnEnable(); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_Height = base.serializedObject.FindProperty("m_Height"); + this.m_Direction = base.serializedObject.FindProperty("m_Direction"); + this.m_HandleControlID = -1; + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + base.InspectorEditButtonGUI(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Direction, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public void OnSceneGUI() + { + bool flag = GUIUtility.hotControl == this.m_HandleControlID; + CapsuleCollider capsuleCollider = (CapsuleCollider)this.target; + Color color = Handles.color; + if (capsuleCollider.enabled) + { + Handles.color = Handles.s_ColliderHandleColor; + } + else + { + Handles.color = Handles.s_ColliderHandleColorDisabled; + } + bool enabled = GUI.enabled; + if (!base.editingCollider && !flag) + { + GUI.enabled = false; + Handles.color = new Color(1f, 0f, 0f, 0.001f); + } + Vector3 capsuleExtents = ColliderUtil.GetCapsuleExtents(capsuleCollider); + float num = capsuleExtents.y + 2f * capsuleExtents.x; + float x = capsuleExtents.x; + Matrix4x4 matrix = ColliderUtil.CalculateCapsuleTransform(capsuleCollider); + int hotControl = GUIUtility.hotControl; + Vector3 vector = Vector3.up * num * 0.5f; + float num2 = CapsuleColliderEditor.SizeHandle(vector, Vector3.up, matrix, true); + if (!GUI.changed) + { + num2 = CapsuleColliderEditor.SizeHandle(-vector, Vector3.down, matrix, true); + } + if (GUI.changed) + { + float num3 = num / capsuleCollider.height; + capsuleCollider.height += num2 / num3; + } + num2 = CapsuleColliderEditor.SizeHandle(Vector3.left * x, Vector3.left, matrix, true); + if (!GUI.changed) + { + num2 = CapsuleColliderEditor.SizeHandle(-Vector3.left * x, -Vector3.left, matrix, true); + } + if (!GUI.changed) + { + num2 = CapsuleColliderEditor.SizeHandle(Vector3.forward * x, Vector3.forward, matrix, true); + } + if (!GUI.changed) + { + num2 = CapsuleColliderEditor.SizeHandle(-Vector3.forward * x, -Vector3.forward, matrix, true); + } + if (GUI.changed) + { + float num4 = Mathf.Max(capsuleExtents.z / capsuleCollider.radius, capsuleExtents.x / capsuleCollider.radius); + capsuleCollider.radius += num2 / num4; + } + if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) + { + this.m_HandleControlID = GUIUtility.hotControl; + } + if (GUI.changed) + { + Undo.RecordObject(capsuleCollider, "Modified Box Collider"); + capsuleCollider.radius = Mathf.Max(capsuleCollider.radius, 1E-05f); + capsuleCollider.height = Mathf.Max(capsuleCollider.height, 1E-05f); + } + Handles.color = color; + GUI.enabled = enabled; + } + private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x4 matrix, bool isEdgeHandle) + { + Vector3 vector = matrix.MultiplyVector(localPullDir); + Vector3 vector2 = matrix.MultiplyPoint(localPos); + float handleSize = HandleUtility.GetHandleSize(vector2); + bool changed = GUI.changed; + GUI.changed = false; + Color color = Handles.color; + float num = 0f; + if (isEdgeHandle) + { + num = Mathf.Cos(0.7853982f); + } + float num2; + if (Camera.current.isOrthoGraphic) + { + num2 = Vector3.Dot(-Camera.current.transform.forward, vector); + } + else + { + num2 = Vector3.Dot((Camera.current.transform.position - vector2).normalized, vector); + } + if (num2 < -num) + { + Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier); + } + Vector3 point = Handles.Slider(vector2, vector, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + float result = 0f; + if (GUI.changed) + { + result = HandleUtility.PointOnLineParameter(point, vector2, vector); + } + GUI.changed |= changed; + Handles.color = color; + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/ChangeFlags.cs b/UnityEditor/UnityEditor/ChangeFlags.cs new file mode 100644 index 00000000..52db9e01 --- /dev/null +++ b/UnityEditor/UnityEditor/ChangeFlags.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor +{ + [Flags] + internal enum ChangeFlags + { + None = 0, + Modified = 1, + Renamed = 2, + Moved = 4, + Deleted = 8, + Undeleted = 16, + Created = 32 + } +} diff --git a/UnityEditor/UnityEditor/Changeset.cs b/UnityEditor/UnityEditor/Changeset.cs new file mode 100644 index 00000000..f67637be --- /dev/null +++ b/UnityEditor/UnityEditor/Changeset.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + internal sealed class Changeset + { + public int changeset; + public string message; + public string date; + public string owner; + public ChangesetItem[] items; + } +} diff --git a/UnityEditor/UnityEditor/ChangesetItem.cs b/UnityEditor/UnityEditor/ChangesetItem.cs new file mode 100644 index 00000000..25bab3c1 --- /dev/null +++ b/UnityEditor/UnityEditor/ChangesetItem.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + internal sealed class ChangesetItem + { + public string fullPath; + public string guid; + public string assetOperations; + public int assetIsDir; + public ChangeFlags changeFlags; + internal static int Compare(ChangesetItem p1, ChangesetItem p2) + { + return string.Compare(p1.fullPath, p2.fullPath, true); + } + } +} diff --git a/UnityEditor/UnityEditor/CharacterControllerEditor.cs b/UnityEditor/UnityEditor/CharacterControllerEditor.cs new file mode 100644 index 00000000..a903b37b --- /dev/null +++ b/UnityEditor/UnityEditor/CharacterControllerEditor.cs @@ -0,0 +1,147 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(CharacterController))] + internal class CharacterControllerEditor : Editor + { + private SerializedProperty m_Height; + private SerializedProperty m_Radius; + private SerializedProperty m_SlopeLimit; + private SerializedProperty m_StepOffset; + private SerializedProperty m_SkinWidth; + private SerializedProperty m_MinMoveDistance; + private SerializedProperty m_Center; + private SerializedProperty m_Direction; + private int m_HandleControlID; + public void OnEnable() + { + this.m_Height = base.serializedObject.FindProperty("m_Height"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_SlopeLimit = base.serializedObject.FindProperty("m_SlopeLimit"); + this.m_StepOffset = base.serializedObject.FindProperty("m_StepOffset"); + this.m_SkinWidth = base.serializedObject.FindProperty("m_SkinWidth"); + this.m_MinMoveDistance = base.serializedObject.FindProperty("m_MinMoveDistance"); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_HandleControlID = -1; + } + public void OnDisable() + { + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_SlopeLimit, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_StepOffset, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SkinWidth, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MinMoveDistance, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public void OnSceneGUI() + { + bool flag = GUIUtility.hotControl == this.m_HandleControlID; + CharacterController characterController = (CharacterController)this.target; + Color color = Handles.color; + if (characterController.enabled) + { + Handles.color = Handles.s_ColliderHandleColor; + } + else + { + Handles.color = Handles.s_ColliderHandleColorDisabled; + } + bool enabled = GUI.enabled; + if (!Event.current.shift && !flag) + { + GUI.enabled = false; + Handles.color = new Color(1f, 0f, 0f, 0.001f); + } + float num = characterController.height * characterController.transform.lossyScale.y; + float num2 = characterController.radius * Mathf.Max(characterController.transform.lossyScale.x, characterController.transform.lossyScale.z); + num = Mathf.Max(num, num2 * 2f); + Matrix4x4 matrix = Matrix4x4.TRS(characterController.transform.TransformPoint(characterController.center), Quaternion.identity, Vector3.one); + int hotControl = GUIUtility.hotControl; + Vector3 vector = Vector3.up * num * 0.5f; + float num3 = CharacterControllerEditor.SizeHandle(vector, Vector3.up, matrix, true); + if (!GUI.changed) + { + num3 = CharacterControllerEditor.SizeHandle(-vector, Vector3.down, matrix, true); + } + if (GUI.changed) + { + Undo.RecordObject(characterController, "Character Controller Resize"); + float num4 = num / characterController.height; + characterController.height += num3 / num4; + } + num3 = CharacterControllerEditor.SizeHandle(Vector3.left * num2, Vector3.left, matrix, true); + if (!GUI.changed) + { + num3 = CharacterControllerEditor.SizeHandle(-Vector3.left * num2, -Vector3.left, matrix, true); + } + if (!GUI.changed) + { + num3 = CharacterControllerEditor.SizeHandle(Vector3.forward * num2, Vector3.forward, matrix, true); + } + if (!GUI.changed) + { + num3 = CharacterControllerEditor.SizeHandle(-Vector3.forward * num2, -Vector3.forward, matrix, true); + } + if (GUI.changed) + { + Undo.RecordObject(characterController, "Character Controller Resize"); + float num5 = num2 / characterController.radius; + characterController.radius += num3 / num5; + } + if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) + { + this.m_HandleControlID = GUIUtility.hotControl; + } + if (GUI.changed) + { + characterController.radius = Mathf.Max(characterController.radius, 1E-05f); + characterController.height = Mathf.Max(characterController.height, 1E-05f); + } + Handles.color = color; + GUI.enabled = enabled; + } + private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x4 matrix, bool isEdgeHandle) + { + Vector3 vector = matrix.MultiplyVector(localPullDir); + Vector3 vector2 = matrix.MultiplyPoint(localPos); + float handleSize = HandleUtility.GetHandleSize(vector2); + bool changed = GUI.changed; + GUI.changed = false; + Color color = Handles.color; + float num = 0f; + if (isEdgeHandle) + { + num = Mathf.Cos(0.7853982f); + } + float num2; + if (Camera.current.isOrthoGraphic) + { + num2 = Vector3.Dot(-Camera.current.transform.forward, vector); + } + else + { + num2 = Vector3.Dot((Camera.current.transform.position - vector2).normalized, vector); + } + if (num2 < -num) + { + Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier); + } + Vector3 point = Handles.Slider(vector2, vector, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + float result = 0f; + if (GUI.changed) + { + result = HandleUtility.PointOnLineParameter(point, vector2, vector); + } + GUI.changed |= changed; + Handles.color = color; + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/CircleCollider2DEditor.cs b/UnityEditor/UnityEditor/CircleCollider2DEditor.cs new file mode 100644 index 00000000..42b3eeb5 --- /dev/null +++ b/UnityEditor/UnityEditor/CircleCollider2DEditor.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(CircleCollider2D))] + internal class CircleCollider2DEditor : Collider2DEditorBase + { + private int m_HandleControlID; + protected SerializedProperty m_Center; + protected SerializedProperty m_Radius; + public override void OnEnable() + { + base.OnEnable(); + this.m_HandleControlID = -1; + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + base.InspectorEditButtonGUI(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + base.CheckColliderErrorState(); + } + public void OnSceneGUI() + { + bool flag = GUIUtility.hotControl == this.m_HandleControlID; + CircleCollider2D circleCollider2D = (CircleCollider2D)this.target; + Color color = Handles.color; + Handles.color = Handles.s_ColliderHandleColor; + bool enabled = GUI.enabled; + if (!base.editingCollider && !flag) + { + GUI.enabled = false; + Handles.color = new Color(0f, 0f, 0f, 0.001f); + } + Vector3 lossyScale = circleCollider2D.transform.lossyScale; + float num = Mathf.Max(Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.y)), Mathf.Abs(lossyScale.z)); + float num2 = num * circleCollider2D.radius; + num2 = Mathf.Abs(num2); + num2 = Mathf.Max(num2, 1E-05f); + Vector3 position = circleCollider2D.transform.TransformPoint(circleCollider2D.center); + int hotControl = GUIUtility.hotControl; + float num3 = Handles.RadiusHandle(Quaternion.identity, position, num2, true); + if (GUI.changed) + { + Undo.RecordObject(circleCollider2D, "Adjust Radius"); + circleCollider2D.radius = num3 * 1f / num; + } + if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) + { + this.m_HandleControlID = GUIUtility.hotControl; + } + Handles.color = color; + GUI.enabled = enabled; + } + } +} diff --git a/UnityEditor/UnityEditor/ClampVelocityModuleUI.cs b/UnityEditor/UnityEditor/ClampVelocityModuleUI.cs new file mode 100644 index 00000000..0d268832 --- /dev/null +++ b/UnityEditor/UnityEditor/ClampVelocityModuleUI.cs @@ -0,0 +1,85 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ClampVelocityModuleUI : ModuleUI + { + private class Texts + { + public GUIContent x = new GUIContent("X"); + public GUIContent y = new GUIContent("Y"); + public GUIContent z = new GUIContent("Z"); + public GUIContent dampen = new GUIContent("Dampen", "Controls how much the velocity that exceeds the velocity limit should be dampened. A value of 0.5 will dampen the exceeding velocity by 50%."); + public GUIContent magnitude = new GUIContent(" Speed", "The speed limit of particles over the particle lifetime."); + public GUIContent separateAxis = new GUIContent("Separate Axis", "If enabled, you can control the velocity limit separately for each axis."); + public GUIContent space = new GUIContent(" Space", "Specifies if the velocity values are in local space (rotated with the transform) or world space."); + public string[] spaces = new string[] + { + "Local", + "World" + }; + } + private SerializedMinMaxCurve m_X; + private SerializedMinMaxCurve m_Y; + private SerializedMinMaxCurve m_Z; + private SerializedMinMaxCurve m_Magnitude; + private SerializedProperty m_SeparateAxis; + private SerializedProperty m_InWorldSpace; + private SerializedProperty m_Dampen; + private static ClampVelocityModuleUI.Texts s_Texts; + public ClampVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ClampVelocityModule", displayName) + { + this.m_ToolTip = "Controls the velocity limit and damping of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_X != null) + { + return; + } + if (ClampVelocityModuleUI.s_Texts == null) + { + ClampVelocityModuleUI.s_Texts = new ClampVelocityModuleUI.Texts(); + } + this.m_X = new SerializedMinMaxCurve(this, ClampVelocityModuleUI.s_Texts.x, "x", ModuleUI.kUseSignedRange); + this.m_Y = new SerializedMinMaxCurve(this, ClampVelocityModuleUI.s_Texts.y, "y", ModuleUI.kUseSignedRange); + this.m_Z = new SerializedMinMaxCurve(this, ClampVelocityModuleUI.s_Texts.z, "z", ModuleUI.kUseSignedRange); + this.m_Magnitude = new SerializedMinMaxCurve(this, ClampVelocityModuleUI.s_Texts.magnitude, "magnitude"); + this.m_SeparateAxis = base.GetProperty("separateAxis"); + this.m_InWorldSpace = base.GetProperty("inWorldSpace"); + this.m_Dampen = base.GetProperty("dampen"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + EditorGUI.BeginChangeCheck(); + bool flag = ModuleUI.GUIToggle(ClampVelocityModuleUI.s_Texts.separateAxis, this.m_SeparateAxis); + if (EditorGUI.EndChangeCheck()) + { + if (flag) + { + this.m_Magnitude.RemoveCurveFromEditor(); + } + else + { + this.m_X.RemoveCurveFromEditor(); + this.m_Y.RemoveCurveFromEditor(); + this.m_Z.RemoveCurveFromEditor(); + } + } + if (flag) + { + base.GUITripleMinMaxCurve(GUIContent.none, ClampVelocityModuleUI.s_Texts.x, this.m_X, ClampVelocityModuleUI.s_Texts.y, this.m_Y, ClampVelocityModuleUI.s_Texts.z, this.m_Z, null); + ModuleUI.GUIBoolAsPopup(ClampVelocityModuleUI.s_Texts.space, this.m_InWorldSpace, ClampVelocityModuleUI.s_Texts.spaces); + } + else + { + ModuleUI.GUIMinMaxCurve(ClampVelocityModuleUI.s_Texts.magnitude, this.m_Magnitude); + } + ModuleUI.GUIFloat(ClampVelocityModuleUI.s_Texts.dampen, this.m_Dampen); + } + public override void UpdateCullingSupportedString(ref string text) + { + text += "\n\tLimit velocity is enabled."; + } + } +} diff --git a/UnityEditor/UnityEditor/ClipAnimationMaskType.cs b/UnityEditor/UnityEditor/ClipAnimationMaskType.cs new file mode 100644 index 00000000..7fb70d01 --- /dev/null +++ b/UnityEditor/UnityEditor/ClipAnimationMaskType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum ClipAnimationMaskType + { + CreateFromThisModel, + CopyFromOther + } +} diff --git a/UnityEditor/UnityEditor/ClothInspector.cs b/UnityEditor/UnityEditor/ClothInspector.cs new file mode 100644 index 00000000..574a3cba --- /dev/null +++ b/UnityEditor/UnityEditor/ClothInspector.cs @@ -0,0 +1,738 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(SkinnedCloth))] + internal class ClothInspector : Editor + { + private enum RectSelectionMode + { + Replace, + Add, + Substract + } + private enum ToolMode + { + Select, + Paint, + Settings + } + private const int clothToolID = 1200; + private bool[] m_Selection; + private bool[] m_RectSelection; + private int m_MouseOver = -1; + private int m_DrawMode = 1; + private int m_MeshVerticesPerSelectionVertex; + private Mesh m_SelectionMesh; + private Mesh m_VertexMesh; + private Vector3[] m_LastVertices; + private Vector2 m_SelectStartPoint; + private Vector2 m_SelectMousePoint; + private bool m_RectSelecting; + private bool m_DidSelect; + private bool m_PaintMaxDistanceEnabled; + private bool m_PaintMaxDistanceBiasEnabled; + private bool m_PaintCollisionSphereRadiusEnabled; + private bool m_PaintCollisionSphereDistanceEnabled; + private float m_PaintMaxDistance = 0.2f; + private float m_PaintMaxDistanceBias; + private float m_PaintCollisionSphereRadius = 0.5f; + private float m_PaintCollisionSphereDistance; + private static Material s_SelectionMaterial = null; + private ClothInspector.RectSelectionMode m_RectSelectionMode = ClothInspector.RectSelectionMode.Add; + private static ClothInspector.ToolMode s_ToolMode = ClothInspector.ToolMode.Settings; + private static int maxVertices; + private static GUIContent[] s_ToolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("ClothInspector.SelectTool", "Select vertices and edit their cloth coefficients in the inspector."), + EditorGUIUtility.IconContent("ClothInspector.PaintTool", "Paint cloth coefficients on to vertices."), + EditorGUIUtility.IconContent("ClothInspector.SettingsTool", "Set cloth options.") + }; + private static GUIContent s_ViewIcon = EditorGUIUtility.IconContent("ClothInspector.ViewValue", "Visualize this vertex coefficient value in the scene view."); + private static GUIContent s_PaintIcon = EditorGUIUtility.IconContent("ClothInspector.PaintValue", "Change this vertex coefficient value by painting in the scene view."); + private bool SelectionMeshDirty() + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + SkinnedMeshRenderer component = skinnedCloth.GetComponent(); + Vector3[] vertices = skinnedCloth.vertices; + Quaternion rotation = component.actualRootBone.rotation; + Vector3 position = component.actualRootBone.position; + for (int i = 0; i < this.m_LastVertices.Length; i++) + { + if (this.m_LastVertices[i] != rotation * vertices[i] + position) + { + return true; + } + } + return false; + } + private void GenerateSelectionMesh() + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + SkinnedMeshRenderer component = skinnedCloth.GetComponent(); + Vector3[] vertices = skinnedCloth.vertices; + if (this.m_SelectionMesh != null) + { + UnityEngine.Object.DestroyImmediate(this.m_SelectionMesh); + } + this.m_SelectionMesh = new Mesh(); + this.m_SelectionMesh.hideFlags |= HideFlags.DontSave; + CombineInstance[] array = new CombineInstance[vertices.Length]; + this.m_MeshVerticesPerSelectionVertex = this.m_VertexMesh.vertices.Length; + this.m_LastVertices = new Vector3[vertices.Length]; + Quaternion rotation = component.actualRootBone.rotation; + Vector3 position = component.actualRootBone.position; + int num = 0; + while (num < vertices.Length && num < ClothInspector.maxVertices) + { + this.m_LastVertices[num] = rotation * vertices[num] + position; + array[num].mesh = this.m_VertexMesh; + array[num].transform = Matrix4x4.TRS(this.m_LastVertices[num], Quaternion.identity, 0.015f * Vector3.one); + num++; + } + this.m_SelectionMesh.CombineMeshes(array); + this.SetupMeshColors(); + } + private void OnEnable() + { + if (ClothInspector.s_SelectionMaterial == null) + { + ClothInspector.s_SelectionMaterial = (EditorGUIUtility.LoadRequired("SceneView/VertexSelectionMaterial.mat") as Material); + } + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + this.m_Selection = new bool[coefficients.Length]; + this.m_RectSelection = new bool[coefficients.Length]; + this.m_VertexMesh = (Mesh)Resources.GetBuiltinResource(typeof(Mesh), "Cube.fbx"); + ClothInspector.maxVertices = 65536 / this.m_VertexMesh.vertices.Length; + if (skinnedCloth.vertices.Length >= ClothInspector.maxVertices) + { + Debug.LogWarning("The mesh has too many vertices to be able to edit all skin coefficients. Only the first " + ClothInspector.maxVertices + " vertices will be displayed"); + } + this.GenerateSelectionMesh(); + } + private float GetCoefficient(ClothSkinningCoefficient coefficient) + { + switch (this.m_DrawMode) + { + case 1: + return coefficient.maxDistance; + case 2: + return coefficient.maxDistanceBias; + case 3: + return coefficient.collisionSphereRadius; + case 4: + return coefficient.collisionSphereDistance; + default: + return 0f; + } + } + private void SetupMeshColors() + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + Color[] array = new Color[this.m_SelectionMesh.vertices.Length]; + float num = 0f; + float num2 = 0f; + for (int i = 0; i < coefficients.Length; i++) + { + float coefficient = this.GetCoefficient(coefficients[i]); + if (coefficient < num) + { + num = coefficient; + } + if (coefficient > num2) + { + num2 = coefficient; + } + } + int num3 = 0; + while (num3 < coefficients.Length && num3 < ClothInspector.maxVertices) + { + for (int j = 0; j < this.m_MeshVerticesPerSelectionVertex; j++) + { + bool flag = this.m_Selection[num3]; + if (this.m_RectSelecting) + { + switch (this.m_RectSelectionMode) + { + case ClothInspector.RectSelectionMode.Replace: + flag = this.m_RectSelection[num3]; + break; + case ClothInspector.RectSelectionMode.Add: + flag |= this.m_RectSelection[num3]; + break; + case ClothInspector.RectSelectionMode.Substract: + flag = (flag && !this.m_RectSelection[num3]); + break; + } + } + Color color; + if (flag) + { + color = Color.red; + } + else + { + float num4; + if (num2 - num != 0f) + { + num4 = (this.GetCoefficient(coefficients[num3]) - num) / (num2 - num); + } + else + { + num4 = 0.5f; + } + if (num4 < 0.5f) + { + color = Color.Lerp(Color.green, Color.yellow, 2f * num4); + } + else + { + color = Color.Lerp(Color.yellow, Color.blue, 2f * num4 - 1f); + } + } + array[num3 * this.m_MeshVerticesPerSelectionVertex + j] = color; + } + num3++; + } + this.m_SelectionMesh.colors = array; + } + private void OnDisable() + { + UnityEngine.Object.DestroyImmediate(this.m_SelectionMesh); + } + private float CoefficientField(string label, float value, bool enabled, int mode) + { + bool enabled2 = GUI.enabled; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Toggle(this.m_DrawMode == mode, ClothInspector.s_ViewIcon, "MiniButton", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + this.m_DrawMode = mode; + this.SetupMeshColors(); + } + GUI.enabled = enabled; + float result = EditorGUILayout.FloatField(label, value, new GUILayoutOption[0]); + GUI.enabled = enabled2; + GUILayout.EndHorizontal(); + return result; + } + private float PaintField(string label, float value, ref bool enabled, int mode) + { + bool enabled2 = GUI.enabled; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Toggle(this.m_DrawMode == mode, ClothInspector.s_ViewIcon, "MiniButton", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + this.m_DrawMode = mode; + this.SetupMeshColors(); + } + enabled = GUILayout.Toggle(enabled, ClothInspector.s_PaintIcon, "MiniButton", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUI.enabled = enabled; + float result = EditorGUILayout.FloatField(label, value, new GUILayoutOption[0]); + GUI.enabled = enabled2; + GUILayout.EndHorizontal(); + return result; + } + private void SelectionGUI() + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + Vector3[] vertices = skinnedCloth.vertices; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Select All", new GUILayoutOption[0])) + { + for (int i = 0; i < vertices.Length; i++) + { + this.m_Selection[i] = true; + } + this.SetupMeshColors(); + SceneView.RepaintAll(); + } + if (GUILayout.Button("Select None", new GUILayoutOption[0])) + { + for (int j = 0; j < vertices.Length; j++) + { + this.m_Selection[j] = false; + } + this.SetupMeshColors(); + SceneView.RepaintAll(); + } + float num = 0f; + float num2 = 0f; + float num3 = 0f; + float num4 = 0f; + int num5 = 0; + for (int k = 0; k < coefficients.Length; k++) + { + if (this.m_Selection[k]) + { + num += coefficients[k].maxDistance; + num2 += coefficients[k].maxDistanceBias; + num3 += coefficients[k].collisionSphereRadius; + num4 += coefficients[k].collisionSphereDistance; + num5++; + } + } + GUILayout.Label(num5 + " selected", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + if (num5 > 0) + { + num /= (float)num5; + num2 /= (float)num5; + num3 /= (float)num5; + num4 /= (float)num5; + } + float num6 = this.CoefficientField("max Distance", num, num5 > 0, 1); + float num7 = this.CoefficientField("distance bias", num2, num5 > 0, 2); + float num8 = this.CoefficientField("collsionSphereRadius", num3, num5 > 0, 3); + float num9 = this.CoefficientField("collisionSphereDistance", num4, num5 > 0, 4); + num7 = Mathf.Clamp(num7, -1f, 1f); + if (num6 != num) + { + for (int l = 0; l < coefficients.Length; l++) + { + if (this.m_Selection[l]) + { + coefficients[l].maxDistance = num6; + } + } + skinnedCloth.coefficients = coefficients; + this.SetupMeshColors(); + } + if (num7 != num2) + { + for (int m = 0; m < coefficients.Length; m++) + { + if (this.m_Selection[m]) + { + coefficients[m].maxDistanceBias = num7; + } + } + skinnedCloth.coefficients = coefficients; + this.SetupMeshColors(); + } + if (num8 != num3) + { + for (int n = 0; n < coefficients.Length; n++) + { + if (this.m_Selection[n]) + { + coefficients[n].collisionSphereRadius = num8; + } + } + skinnedCloth.coefficients = coefficients; + this.SetupMeshColors(); + } + if (num9 != num4) + { + for (int num10 = 0; num10 < coefficients.Length; num10++) + { + if (this.m_Selection[num10]) + { + coefficients[num10].collisionSphereDistance = num9; + } + } + skinnedCloth.coefficients = coefficients; + this.SetupMeshColors(); + } + } + private void PaintGUI() + { + this.m_PaintMaxDistance = this.PaintField("max Distance", this.m_PaintMaxDistance, ref this.m_PaintMaxDistanceEnabled, 1); + this.m_PaintMaxDistanceBias = this.PaintField("distance bias", this.m_PaintMaxDistanceBias, ref this.m_PaintMaxDistanceBiasEnabled, 2); + this.m_PaintMaxDistanceBias = Mathf.Clamp(this.m_PaintMaxDistanceBias, -1f, 1f); + this.m_PaintCollisionSphereRadius = this.PaintField("collsionSphereRadius", this.m_PaintCollisionSphereRadius, ref this.m_PaintCollisionSphereRadiusEnabled, 3); + this.m_PaintCollisionSphereDistance = this.PaintField("collisionSphereDistance", this.m_PaintCollisionSphereDistance, ref this.m_PaintCollisionSphereDistanceEnabled, 4); + } + public override void OnInspectorGUI() + { + ClothInspector.ToolMode toolMode = ClothInspector.s_ToolMode; + if (Tools.current != Tool.None) + { + ClothInspector.s_ToolMode = ClothInspector.ToolMode.Settings; + } + ClothInspector.s_ToolMode = (ClothInspector.ToolMode)GUILayout.Toolbar((int)ClothInspector.s_ToolMode, ClothInspector.s_ToolIcons, new GUILayoutOption[0]); + if (ClothInspector.s_ToolMode != toolMode) + { + GUIUtility.keyboardControl = 0; + if (ClothInspector.s_ToolMode != ClothInspector.ToolMode.Settings) + { + Tools.current = Tool.None; + } + SceneView.RepaintAll(); + this.SetupMeshColors(); + } + switch (ClothInspector.s_ToolMode) + { + case ClothInspector.ToolMode.Select: + this.SelectionGUI(); + break; + case ClothInspector.ToolMode.Paint: + this.PaintGUI(); + break; + case ClothInspector.ToolMode.Settings: + base.DrawDefaultInspector(); + break; + } + } + private int GetMouseVertex(Event e) + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + SkinnedMeshRenderer component = skinnedCloth.GetComponent(); + Vector3[] normals = skinnedCloth.normals; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + Ray ray = HandleUtility.GUIPointToWorldRay(e.mousePosition); + float num = 1000f; + int result = -1; + Quaternion rotation = component.actualRootBone.rotation; + bool flag = false; + if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.renderMode == DrawCameraMode.Wireframe) + { + flag = true; + } + for (int i = 0; i < coefficients.Length; i++) + { + Vector3 lhs = this.m_LastVertices[i] - ray.origin; + float sqrMagnitude = Vector3.Cross(lhs, ray.direction).sqrMagnitude; + if ((Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f || flag) && sqrMagnitude < num && sqrMagnitude < 0.00250000018f) + { + num = sqrMagnitude; + result = i; + } + } + return result; + } + private void DrawVertices() + { + if (this.SelectionMeshDirty()) + { + this.GenerateSelectionMesh(); + } + for (int i = 0; i < ClothInspector.s_SelectionMaterial.passCount; i++) + { + ClothInspector.s_SelectionMaterial.SetPass(i); + Graphics.DrawMeshNow(this.m_SelectionMesh, Matrix4x4.identity); + } + if (this.m_MouseOver != -1) + { + Matrix4x4 matrix = Matrix4x4.TRS(this.m_LastVertices[this.m_MouseOver], Quaternion.identity, 0.02f * Vector3.one); + ClothInspector.s_SelectionMaterial.color = this.m_SelectionMesh.colors[this.m_MouseOver * this.m_MeshVerticesPerSelectionVertex]; + for (int j = 0; j < ClothInspector.s_SelectionMaterial.passCount; j++) + { + ClothInspector.s_SelectionMaterial.SetPass(j); + Graphics.DrawMeshNow(this.m_VertexMesh, matrix); + } + ClothInspector.s_SelectionMaterial.color = Color.white; + } + } + private bool UpdateRectSelection() + { + bool result = false; + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + SkinnedMeshRenderer component = skinnedCloth.GetComponent(); + Vector3[] normals = skinnedCloth.normals; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + float x = Mathf.Min(this.m_SelectStartPoint.x, this.m_SelectMousePoint.x); + float x2 = Mathf.Max(this.m_SelectStartPoint.x, this.m_SelectMousePoint.x); + float y = Mathf.Min(this.m_SelectStartPoint.y, this.m_SelectMousePoint.y); + float y2 = Mathf.Max(this.m_SelectStartPoint.y, this.m_SelectMousePoint.y); + Ray ray = HandleUtility.GUIPointToWorldRay(new Vector2(x, y)); + Ray ray2 = HandleUtility.GUIPointToWorldRay(new Vector2(x2, y)); + Ray ray3 = HandleUtility.GUIPointToWorldRay(new Vector2(x, y2)); + Ray ray4 = HandleUtility.GUIPointToWorldRay(new Vector2(x2, y2)); + Plane plane = new Plane(ray2.origin + ray2.direction, ray.origin + ray.direction, ray.origin); + Plane plane2 = new Plane(ray3.origin + ray3.direction, ray4.origin + ray4.direction, ray4.origin); + Plane plane3 = new Plane(ray.origin + ray.direction, ray3.origin + ray3.direction, ray3.origin); + Plane plane4 = new Plane(ray4.origin + ray4.direction, ray2.origin + ray2.direction, ray2.origin); + Quaternion rotation = component.actualRootBone.rotation; + bool flag = false; + if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.renderMode == DrawCameraMode.Wireframe) + { + flag = true; + } + for (int i = 0; i < coefficients.Length; i++) + { + Vector3 inPt = this.m_LastVertices[i]; + bool flag2 = Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f; + bool flag3 = plane.GetSide(inPt) && plane2.GetSide(inPt) && plane3.GetSide(inPt) && plane4.GetSide(inPt); + flag3 = (flag3 && (flag || flag2)); + if (this.m_RectSelection[i] != flag3) + { + this.m_RectSelection[i] = flag3; + result = true; + } + } + return result; + } + private void ApplyRectSelection() + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + for (int i = 0; i < coefficients.Length; i++) + { + switch (this.m_RectSelectionMode) + { + case ClothInspector.RectSelectionMode.Replace: + this.m_Selection[i] = this.m_RectSelection[i]; + break; + case ClothInspector.RectSelectionMode.Add: + this.m_Selection[i] |= this.m_RectSelection[i]; + break; + case ClothInspector.RectSelectionMode.Substract: + this.m_Selection[i] = (this.m_Selection[i] && !this.m_RectSelection[i]); + break; + } + } + } + private bool RectSelectionModeFromEvent() + { + Event current = Event.current; + ClothInspector.RectSelectionMode rectSelectionMode = ClothInspector.RectSelectionMode.Replace; + if (current.shift) + { + rectSelectionMode = ClothInspector.RectSelectionMode.Add; + } + if (current.alt) + { + rectSelectionMode = ClothInspector.RectSelectionMode.Substract; + } + if (this.m_RectSelectionMode != rectSelectionMode) + { + this.m_RectSelectionMode = rectSelectionMode; + return true; + } + return false; + } + internal void SendCommandsOnModifierKeys() + { + SceneView.lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent("ModifierKeysChanged")); + } + private void SelectionPreSceneGUI(int id) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.MouseDown: + { + if (current.alt || current.control || current.command || current.button != 0) + { + return; + } + GUIUtility.hotControl = id; + int mouseVertex = this.GetMouseVertex(current); + if (mouseVertex != -1) + { + if (current.shift) + { + this.m_Selection[mouseVertex] = !this.m_Selection[mouseVertex]; + } + else + { + for (int i = 0; i < this.m_Selection.Length; i++) + { + this.m_Selection[i] = false; + } + this.m_Selection[mouseVertex] = true; + } + this.m_DidSelect = true; + this.SetupMeshColors(); + base.Repaint(); + } + else + { + this.m_DidSelect = false; + } + this.m_SelectStartPoint = current.mousePosition; + current.Use(); + return; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == id && current.button == 0) + { + GUIUtility.hotControl = 0; + if (this.m_RectSelecting) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendCommandsOnModifierKeys)); + this.m_RectSelecting = false; + this.RectSelectionModeFromEvent(); + this.ApplyRectSelection(); + } + else + { + if (!this.m_DidSelect && !current.alt && !current.control && !current.command) + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + for (int j = 0; j < coefficients.Length; j++) + { + this.m_Selection[j] = false; + } + } + } + this.SetupMeshColors(); + base.Repaint(); + } + return; + case EventType.MouseMove: + IL_26: + if (typeForControl != EventType.ExecuteCommand) + { + return; + } + if (this.m_RectSelecting && current.commandName == "ModifierKeysChanged" && (this.RectSelectionModeFromEvent() || this.UpdateRectSelection())) + { + this.SetupMeshColors(); + } + return; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + if (!this.m_RectSelecting && (current.mousePosition - this.m_SelectStartPoint).magnitude > 2f && !current.alt && !current.control && !current.command) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendCommandsOnModifierKeys)); + this.m_RectSelecting = true; + this.RectSelectionModeFromEvent(); + this.SetupMeshColors(); + } + if (this.m_RectSelecting) + { + this.m_SelectMousePoint = new Vector2(Mathf.Max(current.mousePosition.x, 0f), Mathf.Max(current.mousePosition.y, 0f)); + if (this.RectSelectionModeFromEvent() || this.UpdateRectSelection()) + { + this.SetupMeshColors(); + } + current.Use(); + } + } + return; + } + goto IL_26; + } + private void PaintPreSceneGUI(int id) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(id); + if (typeForControl == EventType.MouseDown || typeForControl == EventType.MouseDrag) + { + SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; + ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + if (GUIUtility.hotControl != id && (current.alt || current.control || current.command || current.button != 0)) + { + return; + } + if (typeForControl == EventType.MouseDown) + { + GUIUtility.hotControl = id; + } + int mouseVertex = this.GetMouseVertex(current); + if (mouseVertex != -1) + { + bool flag = false; + if (this.m_PaintMaxDistanceEnabled && coefficients[mouseVertex].maxDistance != this.m_PaintMaxDistance) + { + coefficients[mouseVertex].maxDistance = this.m_PaintMaxDistance; + flag = true; + } + if (this.m_PaintMaxDistanceBiasEnabled && coefficients[mouseVertex].maxDistanceBias != this.m_PaintMaxDistanceBias) + { + coefficients[mouseVertex].maxDistanceBias = this.m_PaintMaxDistanceBias; + flag = true; + } + if (this.m_PaintCollisionSphereRadiusEnabled && coefficients[mouseVertex].collisionSphereRadius != this.m_PaintCollisionSphereRadius) + { + coefficients[mouseVertex].collisionSphereRadius = this.m_PaintCollisionSphereRadius; + flag = true; + } + if (this.m_PaintCollisionSphereDistanceEnabled && coefficients[mouseVertex].collisionSphereDistance != this.m_PaintCollisionSphereDistance) + { + coefficients[mouseVertex].collisionSphereDistance = this.m_PaintCollisionSphereDistance; + flag = true; + } + if (flag) + { + skinnedCloth.coefficients = coefficients; + this.SetupMeshColors(); + base.Repaint(); + } + } + current.Use(); + } + else + { + if (typeForControl == EventType.MouseUp && GUIUtility.hotControl == id && current.button == 0) + { + GUIUtility.hotControl = 0; + current.Use(); + } + } + } + public void OnPreSceneGUI() + { + if (ClothInspector.s_ToolMode == ClothInspector.ToolMode.Settings) + { + return; + } + Handles.BeginGUI(); + int controlID = GUIUtility.GetControlID(FocusType.Passive); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl != EventType.MouseMove) + { + if (typeForControl == EventType.Layout) + { + HandleUtility.AddDefaultControl(controlID); + } + } + else + { + int mouseOver = this.m_MouseOver; + this.m_MouseOver = this.GetMouseVertex(current); + if (this.m_MouseOver != mouseOver) + { + SceneView.RepaintAll(); + } + } + ClothInspector.ToolMode toolMode = ClothInspector.s_ToolMode; + if (toolMode != ClothInspector.ToolMode.Select) + { + if (toolMode == ClothInspector.ToolMode.Paint) + { + this.PaintPreSceneGUI(controlID); + } + } + else + { + this.SelectionPreSceneGUI(controlID); + } + Handles.EndGUI(); + } + public void OnSceneGUI() + { + if (ClothInspector.s_ToolMode == ClothInspector.ToolMode.Settings) + { + return; + } + if (Event.current.type == EventType.Repaint) + { + this.DrawVertices(); + } + Handles.BeginGUI(); + if (this.m_RectSelecting && ClothInspector.s_ToolMode == ClothInspector.ToolMode.Select && Event.current.type == EventType.Repaint) + { + EditorStyles.selectionRect.Draw(EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint), GUIContent.none, false, false, false, false); + } + Handles.EndGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/CodeStrippingUtils.cs b/UnityEditor/UnityEditor/CodeStrippingUtils.cs new file mode 100644 index 00000000..27121e51 --- /dev/null +++ b/UnityEditor/UnityEditor/CodeStrippingUtils.cs @@ -0,0 +1,223 @@ +using Mono.Cecil; +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class CodeStrippingUtils + { + public static readonly string[] NativeClassBlackList = new string[] + { + "PreloadData", + "Material", + "Cubemap", + "Texture3D", + "RenderTexture" + }; + private static readonly string[] s_UserAssemblies = new string[] + { + "Assembly-CSharp.dll", + "Assembly-CSharp-firstpass.dll", + "Assembly-UnityScript.dll", + "Assembly-UnityScript-firstpass.dll" + }; + public static void WriteModuleAndClassRegistrationFile(string strippedAssemblyDir, string outputDir, RuntimeClassRegistry rcr) + { + HashSet hashSet = (PlayerSettings.strippingLevel != StrippingLevel.Disabled) ? CodeStrippingUtils.GenerateNativeClassList(rcr, strippedAssemblyDir, CodeStrippingUtils.GetUserAssemblies(strippedAssemblyDir)) : null; + if (hashSet != null) + { + CodeStrippingUtils.ExcludeModuleManagers(ref hashSet); + } + HashSet nativeModules = (hashSet != null) ? CodeStrippingUtils.GetRequiredStrippableModules(hashSet) : CodeStrippingUtils.GetAllStrippableModules(); + string file = Path.Combine(outputDir, "UnityClassRegistration.cpp"); + CodeStrippingUtils.WriteModuleAndClassRegistrationFile(file, nativeModules, hashSet); + } + private static HashSet GetClassNames(IEnumerable classIds) + { + HashSet hashSet = new HashSet(); + foreach (int current in classIds) + { + hashSet.Add(BaseObjectTools.ClassIDToString(current)); + } + return hashSet; + } + private static HashSet GetAllStrippableModules() + { + return new HashSet(); + } + private static HashSet GetRequiredStrippableModules(HashSet nativeClasses) + { + return new HashSet(); + } + private static void ExcludeModuleManagers(ref HashSet nativeClasses) + { + } + private static HashSet GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies) + { + HashSet hashSet = CodeStrippingUtils.CollectNativeClassListFromRoots(directory, rootAssemblies); + string[] nativeClassBlackList = CodeStrippingUtils.NativeClassBlackList; + for (int i = 0; i < nativeClassBlackList.Length; i++) + { + string item = nativeClassBlackList[i]; + hashSet.Add(item); + } + foreach (string current in rcr.GetAllNativeClassesIncludingManagersAsString()) + { + int num = BaseObjectTools.StringToClassID(current); + if (num != -1 && !BaseObjectTools.IsBaseObject(num)) + { + hashSet.Add(current); + } + } + return hashSet; + } + private static HashSet CollectNativeClassListFromRoots(string directory, string[] rootAssemblies) + { + HashSet hashSet = new HashSet(); + HashSet hashSet2 = CodeStrippingUtils.CollectManagedTypeReferencesFromRoots(directory, rootAssemblies); + foreach (string current in hashSet2) + { + int num = BaseObjectTools.StringToClassID(current); + if (num != -1 && !BaseObjectTools.IsBaseObject(num)) + { + hashSet.Add(current); + } + } + return hashSet; + } + private static HashSet CollectManagedTypeReferencesFromRoots(string directory, string[] rootAssemblies) + { + HashSet hashSet = new HashSet(); + AssemblyReferenceChecker assemblyReferenceChecker = new AssemblyReferenceChecker(); + bool withMethods = false; + bool ignoreSystemDlls = false; + assemblyReferenceChecker.CollectReferencesFromRoots(directory, rootAssemblies, withMethods, 0f, ignoreSystemDlls); + string[] assemblyFileNames = assemblyReferenceChecker.GetAssemblyFileNames(); + AssemblyDefinition[] assemblyDefinitions = assemblyReferenceChecker.GetAssemblyDefinitions(); + AssemblyDefinition[] array = assemblyDefinitions; + for (int i = 0; i < array.Length; i++) + { + AssemblyDefinition assemblyDefinition = array[i]; + foreach (TypeDefinition current in assemblyDefinition.MainModule.Types) + { + if (current.Namespace.StartsWith("UnityEngine") && (current.Fields.Count > 0 || current.Methods.Count > 0 || current.Properties.Count > 0)) + { + string name = current.Name; + hashSet.Add(name); + } + } + } + AssemblyDefinition assemblyDefinition2 = null; + for (int j = 0; j < assemblyFileNames.Length; j++) + { + if (assemblyFileNames[j] == "UnityEngine.dll") + { + assemblyDefinition2 = assemblyDefinitions[j]; + } + } + AssemblyDefinition[] array2 = assemblyDefinitions; + for (int k = 0; k < array2.Length; k++) + { + AssemblyDefinition assemblyDefinition3 = array2[k]; + if (assemblyDefinition3 != assemblyDefinition2) + { + foreach (TypeReference current2 in assemblyDefinition3.MainModule.GetTypeReferences()) + { + if (current2.Namespace.StartsWith("UnityEngine")) + { + string name2 = current2.Name; + hashSet.Add(name2); + } + } + } + } + return hashSet; + } + private static void WriteStaticallyLinkedModuleRegistration(TextWriter w, HashSet nativeModules, HashSet nativeClasses) + { + w.WriteLine("struct ClassRegistrationContext;"); + w.WriteLine("void InvokeRegisterStaticallyLinkedModuleClasses(ClassRegistrationContext& context)"); + w.WriteLine("{"); + if (nativeClasses == null) + { + w.WriteLine("\tvoid RegisterStaticallyLinkedModuleClasses(ClassRegistrationContext&);"); + w.WriteLine("\tRegisterStaticallyLinkedModuleClasses(context);"); + } + else + { + w.WriteLine("\t// Do nothing (we're in stripping mode)"); + } + w.WriteLine("}"); + w.WriteLine(); + w.WriteLine("void RegisterStaticallyLinkedModulesGranular()"); + w.WriteLine("{"); + foreach (string current in nativeModules) + { + w.WriteLine("\tvoid RegisterModule_" + current + "();"); + w.WriteLine("\tRegisterModule_" + current + "();"); + w.WriteLine(); + } + w.WriteLine("}"); + } + private static void WriteModuleAndClassRegistrationFile(string file, HashSet nativeModules, HashSet nativeClasses) + { + using (TextWriter textWriter = new StreamWriter(file)) + { + CodeStrippingUtils.WriteStaticallyLinkedModuleRegistration(textWriter, nativeModules, nativeClasses); + textWriter.WriteLine(); + textWriter.WriteLine("void RegisterAllClasses()"); + textWriter.WriteLine("{"); + if (nativeClasses == null) + { + textWriter.WriteLine("\tvoid RegisterAllClassesGranular();"); + textWriter.WriteLine("\tRegisterAllClassesGranular();"); + } + else + { + textWriter.WriteLine(string.Format("\t//Total: {0} classes", nativeClasses.Count)); + int num = 0; + foreach (string current in nativeClasses) + { + textWriter.WriteLine(string.Format("\t//{0}. {1}", num, current)); + if (current == "MasterServerInterface") + { + textWriter.WriteLine("\t//Skipping"); + } + else + { + if (current == "NetworkManager") + { + textWriter.WriteLine("\t//Skipping"); + } + else + { + textWriter.WriteLine(string.Format("\tvoid RegisterClass_{0}();", current)); + textWriter.WriteLine(string.Format("\tRegisterClass_{0}();", current)); + } + } + textWriter.WriteLine(); + num++; + } + } + textWriter.WriteLine("}"); + textWriter.Close(); + } + } + private static string[] GetUserAssemblies(string strippedAssemblyDir) + { + List list = new List(); + string[] array = CodeStrippingUtils.s_UserAssemblies; + for (int i = 0; i < array.Length; i++) + { + string assemblyName = array[i]; + list.AddRange(CodeStrippingUtils.GetAssembliesInDirectory(strippedAssemblyDir, assemblyName)); + } + return list.ToArray(); + } + private static IEnumerable GetAssembliesInDirectory(string strippedAssemblyDir, string assemblyName) + { + return Directory.GetFiles(strippedAssemblyDir, assemblyName, SearchOption.TopDirectoryOnly); + } + } +} diff --git a/UnityEditor/UnityEditor/Collider2DEditorBase.cs b/UnityEditor/UnityEditor/Collider2DEditorBase.cs new file mode 100644 index 00000000..3628d895 --- /dev/null +++ b/UnityEditor/UnityEditor/Collider2DEditorBase.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class Collider2DEditorBase : ColliderEditorBase + { + protected SerializedProperty m_Material; + protected SerializedProperty m_IsTrigger; + public virtual void OnEnable() + { + this.m_Material = base.serializedObject.FindProperty("m_Material"); + this.m_IsTrigger = base.serializedObject.FindProperty("m_IsTrigger"); + } + public virtual void OnDisable() + { + base.editingCollider = false; + } + protected void BeginColliderInspector() + { + base.serializedObject.Update(); + EditorGUI.BeginDisabledGroup(base.targets.Length > 1); + base.InspectorEditButtonGUI(); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + } + protected void EndColliderInspector() + { + base.serializedObject.ApplyModifiedProperties(); + } + protected void CheckColliderErrorState() + { + ColliderErrorState2D errorState = (this.target as Collider2D).errorState; + if (errorState != ColliderErrorState2D.NoShapes) + { + if (errorState == ColliderErrorState2D.RemovedShapes) + { + EditorGUILayout.HelpBox("The collider created collision shape(s) but some were removed as they failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling.", MessageType.Warning); + } + } + else + { + EditorGUILayout.HelpBox("The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling.", MessageType.Warning); + } + } + } +} diff --git a/UnityEditor/UnityEditor/Collider3DEditorBase.cs b/UnityEditor/UnityEditor/Collider3DEditorBase.cs new file mode 100644 index 00000000..2e5527f4 --- /dev/null +++ b/UnityEditor/UnityEditor/Collider3DEditorBase.cs @@ -0,0 +1,26 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class Collider3DEditorBase : ColliderEditorBase + { + protected SerializedProperty m_Material; + protected SerializedProperty m_IsTrigger; + public virtual void OnEnable() + { + this.m_Material = base.serializedObject.FindProperty("m_Material"); + this.m_IsTrigger = base.serializedObject.FindProperty("m_IsTrigger"); + } + public virtual void OnDisable() + { + base.editingCollider = false; + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/ColliderEditorBase.cs b/UnityEditor/UnityEditor/ColliderEditorBase.cs new file mode 100644 index 00000000..59bd4ca0 --- /dev/null +++ b/UnityEditor/UnityEditor/ColliderEditorBase.cs @@ -0,0 +1,136 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ColliderEditorBase : Editor + { + private const float k_EditColliderbuttonWidth = 22f; + private const float k_EditColliderbuttonHeight = 22f; + private const float k_SpaceBetweenLabelAndButton = 5f; + protected static ColliderEditorBase s_ActiveColliderEditor; + private static GUIStyle s_EditColliderButtonStyle; + private Tool m_PreviousTool; + private bool m_EditingCollider; + public bool editingCollider + { + get + { + if (Tools.current != Tool.None && this.m_EditingCollider) + { + this.editingCollider = false; + } + return this.m_EditingCollider; + } + set + { + if (!this.m_EditingCollider && value) + { + if (ColliderEditorBase.s_ActiveColliderEditor != null) + { + ColliderEditorBase.s_ActiveColliderEditor.editingCollider = false; + } + ColliderEditorBase.s_ActiveColliderEditor = this; + this.m_PreviousTool = Tools.current; + Tools.current = Tool.None; + this.OnEditStart(); + } + else + { + if (this.m_EditingCollider && !value) + { + Tools.current = ((this.m_PreviousTool == Tool.None) ? Tool.Move : this.m_PreviousTool); + ColliderEditorBase.s_ActiveColliderEditor = null; + this.OnEditEnd(); + } + } + this.m_EditingCollider = value; + } + } + protected virtual void OnEditStart() + { + } + protected virtual void OnEditEnd() + { + } + protected void InspectorEditButtonGUI() + { + if (ColliderEditorBase.s_EditColliderButtonStyle == null) + { + ColliderEditorBase.s_EditColliderButtonStyle = new GUIStyle("Button"); + ColliderEditorBase.s_EditColliderButtonStyle.padding = new RectOffset(0, 0, 0, 0); + ColliderEditorBase.s_EditColliderButtonStyle.margin = new RectOffset(0, 0, 0, 0); + } + Rect controlRect = EditorGUILayout.GetControlRect(true, 22f, new GUILayoutOption[0]); + Rect position = new Rect(controlRect.xMin + EditorGUIUtility.labelWidth, controlRect.yMin, 22f, 22f); + GUIContent content = new GUIContent("Edit Collider"); + Vector2 vector = GUI.skin.label.CalcSize(content); + Rect position2 = new Rect(position.xMax + 5f, controlRect.yMin + (controlRect.height - vector.y) * 0.5f, vector.x, controlRect.height); + EditorGUI.BeginChangeCheck(); + this.editingCollider = GUI.Toggle(position, this.editingCollider, EditorGUIUtility.IconContent("EditCollider"), ColliderEditorBase.s_EditColliderButtonStyle); + GUI.Label(position2, "Edit Collider"); + if (EditorGUI.EndChangeCheck()) + { + this.EditModeChanged(); + } + } + private void EditModeChanged() + { + if (this.editingCollider && SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !ColliderEditorBase.ColliderSeenByCamera(SceneView.lastActiveSceneView.camera, this.target)) + { + SceneView.lastActiveSceneView.Frame(ColliderEditorBase.GetColliderBounds(this.target)); + } + SceneView.RepaintAll(); + } + private static bool ColliderSeenByCamera(Camera camera, UnityEngine.Object collider) + { + return ColliderEditorBase.AnyPointSeenByCamera(camera, ColliderEditorBase.GetColliderVertices(collider)); + } + private static Vector3[] GetColliderVertices(UnityEngine.Object collider) + { + return ColliderEditorBase.BoundsToVertices(ColliderEditorBase.GetColliderBounds(collider)); + } + private static Bounds GetColliderBounds(UnityEngine.Object collider) + { + if (collider is Collider2D) + { + return (collider as Collider2D).bounds; + } + if (collider is Collider) + { + return (collider as Collider).bounds; + } + return default(Bounds); + } + private static Vector3[] BoundsToVertices(Bounds bounds) + { + return new Vector3[] + { + new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), + new Vector3(bounds.min.x, bounds.min.y, bounds.max.z), + new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), + new Vector3(bounds.min.x, bounds.max.y, bounds.max.z), + new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), + new Vector3(bounds.max.x, bounds.min.y, bounds.max.z), + new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), + new Vector3(bounds.max.x, bounds.max.y, bounds.max.z) + }; + } + private static bool AnyPointSeenByCamera(Camera camera, Vector3[] points) + { + for (int i = 0; i < points.Length; i++) + { + Vector3 point = points[i]; + if (ColliderEditorBase.PointSeenByCamera(camera, point)) + { + return true; + } + } + return false; + } + private static bool PointSeenByCamera(Camera camera, Vector3 point) + { + Vector3 vector = camera.WorldToViewportPoint(point); + return vector.x > 0f && vector.x < 1f && vector.y > 0f && vector.y < 1f; + } + } +} diff --git a/UnityEditor/UnityEditor/ColliderUtil.cs b/UnityEditor/UnityEditor/ColliderUtil.cs new file mode 100644 index 00000000..e7d756ae --- /dev/null +++ b/UnityEditor/UnityEditor/ColliderUtil.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class ColliderUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector3 GetCapsuleExtents(CapsuleCollider cc); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Matrix4x4 CalculateCapsuleTransform(CapsuleCollider cc); + } +} diff --git a/UnityEditor/UnityEditor/CollisionModuleUI.cs b/UnityEditor/UnityEditor/CollisionModuleUI.cs new file mode 100644 index 00000000..900e820a --- /dev/null +++ b/UnityEditor/UnityEditor/CollisionModuleUI.cs @@ -0,0 +1,391 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class CollisionModuleUI : ModuleUI + { + private enum CollisionTypes + { + Plane, + World + } + private enum PlaneVizType + { + Grid, + Solid + } + private class Texts + { + public GUIContent lifetimeLoss = new GUIContent("Lifetime Loss", "When particle collides, it will lose this fraction of its Start Lifetime"); + public GUIContent planes = new GUIContent("Planes", "Planes are defined by assigning a reference to a transform. This transform can be any transform in the scene and can be animated. Multiple planes can be used. Note: the Y-axis is used as the plane normal."); + public GUIContent createPlane = new GUIContent(string.Empty, "Create an empty GameObject and assign it as a plane."); + public GUIContent minKillSpeed = new GUIContent("Min Kill Speed", "When particles collide and their speed is lower than this value, they are killed."); + public GUIContent dampen = new GUIContent("Dampen", "When particle collides, it will lose this fraction of its speed. Unless this is set to 0.0, particle will become slower after collision."); + public GUIContent bounce = new GUIContent("Bounce", "When particle collides, the bounce is scaled with this value. The bounce is the upwards motion in the plane normal direction."); + public GUIContent particleRadius = new GUIContent("Particle Radius", "The estimated size of a particle when colliding (to avoid clipping with collision shape."); + public GUIContent visualization = new GUIContent("Visualization", "Only used for visualizing the planes: Wireframe or Solid."); + public GUIContent scalePlane = new GUIContent("Scale Plane", "Resizes the visualization planes."); + public GUIContent collidesWith = new GUIContent("Collides With", "Collides the particles with colliders included in the layermask."); + public GUIContent quality = new GUIContent("Collision Quality", "Quality of world collisions. Medium and low quality are approximate and may leak particles."); + public string[] qualitySettings = new string[] + { + "High", + "Medium", + "Low" + }; + public GUIContent voxelSize = new GUIContent("Voxel Size", "Size of voxels in the collision cache."); + public GUIContent collisionMessages = new GUIContent("Send Collision Messages", "Send collision callback messages."); + } + private const int k_MaxNumPlanes = 6; + private string[] m_PlaneVizTypeNames = new string[] + { + "Grid", + "Solid" + }; + private SerializedProperty m_Type; + private SerializedProperty[] m_Planes = new SerializedProperty[6]; + private SerializedProperty m_Dampen; + private SerializedProperty m_Bounce; + private SerializedProperty m_LifetimeLossOnCollision; + private SerializedProperty m_MinKillSpeed; + private SerializedProperty m_ParticleRadius; + private SerializedProperty m_CollidesWith; + private SerializedProperty m_Quality; + private SerializedProperty m_VoxelSize; + private SerializedProperty m_CollisionMessages; + private CollisionModuleUI.PlaneVizType m_PlaneVisualizationType = CollisionModuleUI.PlaneVizType.Solid; + private SerializedProperty[] m_ShownPlanes; + private float m_ScaleGrid = 1f; + private static Transform m_SelectedTransform; + private static CollisionModuleUI.Texts s_Texts; + public CollisionModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "CollisionModule", displayName) + { + this.m_ToolTip = "Allows you to specify multiple collision planes that the particle can collide with."; + } + protected override void Init() + { + if (this.m_Type != null) + { + return; + } + this.m_Type = base.GetProperty("type"); + List list = new List(); + for (int i = 0; i < this.m_Planes.Length; i++) + { + this.m_Planes[i] = base.GetProperty("plane" + i); + Assert.That(this.m_Planes[i] != null); + if (i == 0 || this.m_Planes[i].objectReferenceValue != null) + { + list.Add(this.m_Planes[i]); + } + } + this.m_ShownPlanes = list.ToArray(); + this.m_Dampen = base.GetProperty("dampen"); + this.m_Bounce = base.GetProperty("bounce"); + this.m_LifetimeLossOnCollision = base.GetProperty("energyLossOnCollision"); + this.m_MinKillSpeed = base.GetProperty("minKillSpeed"); + this.m_ParticleRadius = base.GetProperty("particleRadius"); + this.m_PlaneVisualizationType = (CollisionModuleUI.PlaneVizType)EditorPrefs.GetInt("PlaneColisionVizType", 1); + this.m_ScaleGrid = EditorPrefs.GetFloat("ScalePlaneColision", 1f); + this.m_CollidesWith = base.GetProperty("collidesWith"); + this.m_Quality = base.GetProperty("quality"); + this.m_VoxelSize = base.GetProperty("voxelSize"); + this.m_CollisionMessages = base.GetProperty("collisionMessages"); + this.SyncVisualization(); + } + protected override void SetVisibilityState(ModuleUI.VisibilityState newState) + { + base.SetVisibilityState(newState); + if (newState != ModuleUI.VisibilityState.VisibleAndFoldedOut) + { + Tools.s_Hidden = false; + CollisionModuleUI.m_SelectedTransform = null; + ParticleEffectUtils.ClearPlanes(); + } + else + { + this.SyncVisualization(); + } + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (CollisionModuleUI.s_Texts == null) + { + CollisionModuleUI.s_Texts = new CollisionModuleUI.Texts(); + } + string[] options = new string[] + { + "Planes", + "World" + }; + CollisionModuleUI.CollisionTypes collisionTypes = (CollisionModuleUI.CollisionTypes)ModuleUI.GUIPopup(string.Empty, this.m_Type, options); + if (collisionTypes == CollisionModuleUI.CollisionTypes.Plane) + { + this.DoListOfPlanesGUI(); + EditorGUI.BeginChangeCheck(); + this.m_PlaneVisualizationType = (CollisionModuleUI.PlaneVizType)ModuleUI.GUIPopup(CollisionModuleUI.s_Texts.visualization, (int)this.m_PlaneVisualizationType, this.m_PlaneVizTypeNames); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetInt("PlaneColisionVizType", (int)this.m_PlaneVisualizationType); + if (this.m_PlaneVisualizationType == CollisionModuleUI.PlaneVizType.Solid) + { + this.SyncVisualization(); + } + else + { + ParticleEffectUtils.ClearPlanes(); + } + } + EditorGUI.BeginChangeCheck(); + this.m_ScaleGrid = ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.scalePlane, this.m_ScaleGrid, "f2"); + if (EditorGUI.EndChangeCheck()) + { + this.m_ScaleGrid = Mathf.Max(0f, this.m_ScaleGrid); + EditorPrefs.SetFloat("ScalePlaneColision", this.m_ScaleGrid); + this.SyncVisualization(); + } + } + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.dampen, this.m_Dampen); + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.bounce, this.m_Bounce); + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.lifetimeLoss, this.m_LifetimeLossOnCollision); + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.minKillSpeed, this.m_MinKillSpeed); + if (collisionTypes != CollisionModuleUI.CollisionTypes.World) + { + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.particleRadius, this.m_ParticleRadius); + } + if (collisionTypes == CollisionModuleUI.CollisionTypes.World) + { + ModuleUI.GUILayerMask(CollisionModuleUI.s_Texts.collidesWith, this.m_CollidesWith); + ModuleUI.GUIPopup(CollisionModuleUI.s_Texts.quality, this.m_Quality, CollisionModuleUI.s_Texts.qualitySettings); + if (this.m_Quality.intValue > 0) + { + ModuleUI.GUIFloat(CollisionModuleUI.s_Texts.voxelSize, this.m_VoxelSize); + } + } + ModuleUI.GUIToggle(CollisionModuleUI.s_Texts.collisionMessages, this.m_CollisionMessages); + } + protected override void OnModuleEnable() + { + base.OnModuleEnable(); + this.SyncVisualization(); + } + protected override void OnModuleDisable() + { + base.OnModuleDisable(); + ParticleEffectUtils.ClearPlanes(); + } + private void SyncVisualization() + { + if (!base.enabled) + { + return; + } + if (this.m_PlaneVisualizationType != CollisionModuleUI.PlaneVizType.Solid) + { + return; + } + for (int i = 0; i < this.m_ShownPlanes.Length; i++) + { + UnityEngine.Object objectReferenceValue = this.m_ShownPlanes[i].objectReferenceValue; + if (!(objectReferenceValue == null)) + { + Transform transform = objectReferenceValue as Transform; + if (!(transform == null)) + { + GameObject plane = ParticleEffectUtils.GetPlane(i); + plane.transform.position = transform.position; + plane.transform.rotation = transform.rotation; + plane.transform.localScale = new Vector3(this.m_ScaleGrid, this.m_ScaleGrid, this.m_ScaleGrid); + } + } + } + } + private static GameObject CreateEmptyGameObject(string name, ParticleSystem parentOfGameObject) + { + GameObject gameObject = new GameObject(name); + if (gameObject) + { + if (parentOfGameObject) + { + gameObject.transform.parent = parentOfGameObject.transform; + } + return gameObject; + } + return null; + } + private void DoListOfPlanesGUI() + { + int num = base.GUIListOfFloatObjectToggleFields(CollisionModuleUI.s_Texts.planes, this.m_ShownPlanes, null, CollisionModuleUI.s_Texts.createPlane, true); + if (num >= 0) + { + GameObject gameObject = CollisionModuleUI.CreateEmptyGameObject("Plane Transform " + (num + 1), this.m_ParticleSystemUI.m_ParticleSystem); + gameObject.transform.localPosition = new Vector3(0f, 0f, (float)(10 + num)); + gameObject.transform.localEulerAngles = new Vector3(-90f, 0f, 0f); + this.m_ShownPlanes[num].objectReferenceValue = gameObject; + this.SyncVisualization(); + } + Rect rect = GUILayoutUtility.GetRect(0f, 16f); + rect.x = rect.xMax - 24f - 5f; + rect.width = 12f; + if (this.m_ShownPlanes.Length > 1 && ModuleUI.MinusButton(rect)) + { + this.m_ShownPlanes[this.m_ShownPlanes.Length - 1].objectReferenceValue = null; + List list = new List(this.m_ShownPlanes); + list.RemoveAt(list.Count - 1); + this.m_ShownPlanes = list.ToArray(); + } + if (this.m_ShownPlanes.Length < 6) + { + rect.x += 17f; + if (ModuleUI.PlusButton(rect)) + { + List list2 = new List(this.m_ShownPlanes); + list2.Add(this.m_Planes[list2.Count]); + this.m_ShownPlanes = list2.ToArray(); + } + } + } + public override void OnSceneGUI(ParticleSystem s, InitialModuleUI initial) + { + Event current = Event.current; + EventType eventType = current.type; + if (current.type == EventType.Ignore && current.rawType == EventType.MouseUp) + { + eventType = current.rawType; + } + Color color = Handles.color; + Color color2 = new Color(1f, 1f, 1f, 0.5f); + Handles.color = color2; + if (this.m_Type.intValue == 0) + { + for (int i = 0; i < this.m_ShownPlanes.Length; i++) + { + UnityEngine.Object objectReferenceValue = this.m_ShownPlanes[i].objectReferenceValue; + if (objectReferenceValue != null) + { + Transform transform = objectReferenceValue as Transform; + if (transform != null) + { + Vector3 position = transform.position; + Quaternion rotation = transform.rotation; + Vector3 axis = rotation * Vector3.right; + Vector3 normal = rotation * Vector3.up; + Vector3 axis2 = rotation * Vector3.forward; + if (object.ReferenceEquals(CollisionModuleUI.m_SelectedTransform, transform)) + { + Tools.s_Hidden = true; + EditorGUI.BeginChangeCheck(); + if (Tools.current == Tool.Move) + { + transform.position = Handles.PositionHandle(position, rotation); + } + else + { + if (Tools.current == Tool.Rotate) + { + transform.rotation = Handles.RotationHandle(rotation, position); + } + } + if (EditorGUI.EndChangeCheck()) + { + if (this.m_PlaneVisualizationType == CollisionModuleUI.PlaneVizType.Solid) + { + GameObject plane = ParticleEffectUtils.GetPlane(i); + plane.transform.position = position; + plane.transform.rotation = rotation; + plane.transform.localScale = new Vector3(this.m_ScaleGrid, this.m_ScaleGrid, this.m_ScaleGrid); + } + ParticleSystemEditorUtils.PerformCompleteResimulation(); + } + } + else + { + int keyboardControl = GUIUtility.keyboardControl; + float size = HandleUtility.GetHandleSize(position) * 0.06f; + Handles.FreeMoveHandle(position, Quaternion.identity, size, Vector3.zero, new Handles.DrawCapFunction(Handles.RectangleCap)); + if (eventType == EventType.MouseDown && current.type == EventType.Used && keyboardControl != GUIUtility.keyboardControl) + { + CollisionModuleUI.m_SelectedTransform = transform; + eventType = EventType.Used; + } + } + if (this.m_PlaneVisualizationType == CollisionModuleUI.PlaneVizType.Grid) + { + Color color3 = Handles.s_ColliderHandleColor * 0.9f; + if (!base.enabled) + { + color3 = new Color(0.7f, 0.7f, 0.7f, 0.7f); + } + this.DrawGrid(position, axis, axis2, normal, color3, i); + } + else + { + this.DrawSolidPlane(position, rotation, i); + } + } + else + { + Debug.LogError("Not a transform: " + objectReferenceValue.GetType()); + } + } + } + } + Handles.color = color; + } + private void DrawSolidPlane(Vector3 pos, Quaternion rot, int planeIndex) + { + } + private void DrawGrid(Vector3 pos, Vector3 axis1, Vector3 axis2, Vector3 normal, Color color, int planeIndex) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + if (color.a > 0f) + { + GL.Begin(1); + float num = 10f; + num *= this.m_ScaleGrid; + int num2 = (int)num; + num2 = Mathf.Clamp(num2, 10, 40); + if (num2 % 2 == 0) + { + num2++; + } + float d = num * 0.5f; + float d2 = num / (float)(num2 - 1); + Vector3 b = axis1 * num; + Vector3 b2 = axis2 * num; + Vector3 a = axis1 * d2; + Vector3 a2 = axis2 * d2; + Vector3 a3 = pos - axis1 * d - axis2 * d; + for (int i = 0; i < num2; i++) + { + if (i % 2 == 0) + { + GL.Color(color * 0.7f); + } + else + { + GL.Color(color); + } + GL.Vertex(a3 + (float)i * a); + GL.Vertex(a3 + (float)i * a + b2); + GL.Vertex(a3 + (float)i * a2); + GL.Vertex(a3 + (float)i * a2 + b); + } + GL.Color(color); + GL.Vertex(pos); + GL.Vertex(pos + normal); + GL.End(); + } + } + public override void UpdateCullingSupportedString(ref string text) + { + text += "\n\tCollision is enabled."; + } + } +} diff --git a/UnityEditor/UnityEditor/ColorByVelocityModuleUI.cs b/UnityEditor/UnityEditor/ColorByVelocityModuleUI.cs new file mode 100644 index 00000000..166c0f60 --- /dev/null +++ b/UnityEditor/UnityEditor/ColorByVelocityModuleUI.cs @@ -0,0 +1,41 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ColorByVelocityModuleUI : ModuleUI + { + private class Texts + { + public GUIContent color = new GUIContent("Color", "Controls the color of each particle based on its speed."); + public GUIContent velocityRange = new GUIContent("Speed Range", "Remaps speed in the defined range to a color."); + } + private static ColorByVelocityModuleUI.Texts s_Texts; + private SerializedMinMaxGradient m_Gradient; + private SerializedProperty m_Range; + private SerializedProperty m_Scale; + public ColorByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ColorBySpeedModule", displayName) + { + this.m_ToolTip = "Controls the color of each particle based on its speed."; + } + protected override void Init() + { + if (this.m_Gradient != null) + { + return; + } + this.m_Gradient = new SerializedMinMaxGradient(this); + this.m_Gradient.m_AllowColor = false; + this.m_Gradient.m_AllowRandomBetweenTwoColors = false; + this.m_Range = base.GetProperty("range"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (ColorByVelocityModuleUI.s_Texts == null) + { + ColorByVelocityModuleUI.s_Texts = new ColorByVelocityModuleUI.Texts(); + } + base.GUIMinMaxGradient(ColorByVelocityModuleUI.s_Texts.color, this.m_Gradient); + ModuleUI.GUIMinMaxRange(ColorByVelocityModuleUI.s_Texts.velocityRange, this.m_Range); + } + } +} diff --git a/UnityEditor/UnityEditor/ColorModuleUI.cs b/UnityEditor/UnityEditor/ColorModuleUI.cs new file mode 100644 index 00000000..f259f2ef --- /dev/null +++ b/UnityEditor/UnityEditor/ColorModuleUI.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ColorModuleUI : ModuleUI + { + private class Texts + { + public GUIContent color = new GUIContent("Color", "Controls the color of each particle during its lifetime."); + } + private static ColorModuleUI.Texts s_Texts; + private SerializedMinMaxGradient m_Gradient; + private SerializedProperty m_Scale; + public ColorModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ColorModule", displayName) + { + this.m_ToolTip = "Controls the color of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_Gradient != null) + { + return; + } + this.m_Gradient = new SerializedMinMaxGradient(this); + this.m_Gradient.m_AllowColor = false; + this.m_Gradient.m_AllowRandomBetweenTwoColors = false; + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (ColorModuleUI.s_Texts == null) + { + ColorModuleUI.s_Texts = new ColorModuleUI.Texts(); + } + base.GUIMinMaxGradient(ColorModuleUI.s_Texts.color, this.m_Gradient); + } + } +} diff --git a/UnityEditor/UnityEditor/ColorPicker.cs b/UnityEditor/UnityEditor/ColorPicker.cs new file mode 100644 index 00000000..0597bc43 --- /dev/null +++ b/UnityEditor/UnityEditor/ColorPicker.cs @@ -0,0 +1,1020 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ColorPicker : EditorWindow + { + private enum ColorBoxMode + { + SV_H, + HV_S, + HS_V, + BG_R, + BR_G, + RG_B, + EyeDropper + } + private enum SliderMode + { + RGB, + HSV + } + private class Styles + { + public GUIStyle pickerBox = "ColorPickerBox"; + public GUIStyle thumb2D = "ColorPicker2DThumb"; + public GUIStyle thumbHoriz = "ColorPickerHorizThumb"; + public GUIStyle thumbVert = "ColorPickerVertThumb"; + public GUIStyle headerLine = "IN Title"; + public GUIStyle colorPickerBox = "ColorPickerBox"; + public GUIStyle background = "ColorPickerBackground"; + public GUIContent eyeDropper = EditorGUIUtility.IconContent("EyeDropper.Large"); + public GUIContent colorCycle = EditorGUIUtility.IconContent("ColorPicker.CycleColor"); + public GUIContent colorToggle = EditorGUIUtility.TextContent("ColorPicker.ColorFoldout"); + public GUIContent sliderToggle = EditorGUIUtility.TextContent("ColorPicker.SliderFoldout"); + public GUIContent presetsToggle = new GUIContent("Presets"); + public GUIContent sliderCycle = EditorGUIUtility.IconContent("ColorPicker.CycleSlider"); + } + private const int kHueRes = 64; + private const int kColorBoxSize = 8; + private const int kEyeDropperHeight = 95; + private const int kSlidersHeight = 82; + private const int kColorBoxHeight = 162; + private const int kPresetsHeight = 300; + private static ColorPicker s_SharedColorPicker; + [SerializeField] + private Color m_Color = Color.black; + [SerializeField] + private Color m_OriginalColor; + [SerializeField] + private float m_R; + [SerializeField] + private float m_G; + [SerializeField] + private float m_B; + [SerializeField] + private float m_H; + [SerializeField] + private float m_S; + [SerializeField] + private float m_V; + [SerializeField] + private float m_A = 1f; + [SerializeField] + private float m_ColorSliderSize = 4f; + [SerializeField] + private Texture2D m_ColorSlider; + [SerializeField] + private float m_SliderValue; + [SerializeField] + private Color[] m_Colors; + [SerializeField] + private Texture2D m_ColorBox; + private static int s_Slider2Dhash = "Slider2D".GetHashCode(); + [SerializeField] + private bool m_ShowColors = true; + [SerializeField] + private bool m_ShowSliders = true; + [SerializeField] + private bool m_ShowPresets = true; + [SerializeField] + private bool m_IsOSColorPicker; + [SerializeField] + private bool m_resetKeyboardControl; + [SerializeField] + private bool m_ShowAlpha = true; + private Texture2D m_RTexture; + private float m_RTextureG = -1f; + private float m_RTextureB = -1f; + private Texture2D m_GTexture; + private float m_GTextureR = -1f; + private float m_GTextureB = -1f; + private Texture2D m_BTexture; + private float m_BTextureR = -1f; + private float m_BTextureG = -1f; + [SerializeField] + private Texture2D m_HueTexture; + private float m_HueTextureS = -1f; + private float m_HueTextureV = -1f; + [SerializeField] + private Texture2D m_SatTexture; + private float m_SatTextureH = -1f; + private float m_SatTextureV = -1f; + [SerializeField] + private Texture2D m_ValTexture; + private float m_ValTextureH = -1f; + private float m_ValTextureS = -1f; + [SerializeField] + private int m_TextureColorSliderMode = -1; + [SerializeField] + private Vector2 m_LastConstantValues = new Vector2(-1f, -1f); + [NonSerialized] + private int m_TextureColorBoxMode = -1; + [SerializeField] + private float m_LastConstant = -1f; + [SerializeField] + private ContainerWindow m_TrackingWindow; + [SerializeField] + private ColorPicker.ColorBoxMode m_ColorBoxMode = ColorPicker.ColorBoxMode.BG_R; + [SerializeField] + private ColorPicker.ColorBoxMode m_OldColorBoxMode; + [SerializeField] + private ColorPicker.SliderMode m_SliderMode = ColorPicker.SliderMode.HSV; + [SerializeField] + private Texture2D m_AlphaTexture; + private float m_OldAlpha = -1f; + [SerializeField] + private GUIView m_DelegateView; + [SerializeField] + private int m_ModalUndoGroup = -1; + private PresetLibraryEditor m_ColorLibraryEditor; + private PresetLibraryEditorState m_ColorLibraryEditorState; + private static ColorPicker.Styles styles; + public static string presetsEditorPrefID + { + get + { + return "Color"; + } + } + private bool colorChanged + { + get; + set; + } + public static bool visible + { + get + { + return ColorPicker.s_SharedColorPicker != null; + } + } + public static Color color + { + get + { + return ColorPicker.get.m_Color; + } + set + { + ColorPicker.get.SetColor(value); + } + } + public static ColorPicker get + { + get + { + if (!ColorPicker.s_SharedColorPicker) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(ColorPicker)); + if (array != null && array.Length > 0) + { + ColorPicker.s_SharedColorPicker = (ColorPicker)array[0]; + } + if (!ColorPicker.s_SharedColorPicker) + { + ColorPicker.s_SharedColorPicker = ScriptableObject.CreateInstance(); + ColorPicker.s_SharedColorPicker.wantsMouseMove = true; + } + } + return ColorPicker.s_SharedColorPicker; + } + } + public string currentPresetLibrary + { + get + { + this.InitIfNeeded(); + return this.m_ColorLibraryEditor.currentLibraryWithoutExtension; + } + set + { + this.InitIfNeeded(); + this.m_ColorLibraryEditor.currentLibraryWithoutExtension = value; + } + } + public ColorPicker() + { + base.hideFlags = HideFlags.DontSave; + this.m_ShowSliders = (EditorPrefs.GetInt("CPSliderShow", 1) != 0); + this.m_SliderMode = (ColorPicker.SliderMode)EditorPrefs.GetInt("CPSliderMode", 0); + this.m_ShowColors = (EditorPrefs.GetInt("CPColorShow", 1) != 0); + this.m_ColorBoxMode = (ColorPicker.ColorBoxMode)EditorPrefs.GetInt("CPColorMode", 0); + this.m_IsOSColorPicker = EditorPrefs.GetBool("UseOSColorPicker"); + this.m_ShowPresets = (EditorPrefs.GetInt("CPPresetsShow", 1) != 0); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.PollOSColorPicker)); + EditorGUIUtility.editingTextField = true; + } + private void OnSelectionChange() + { + this.m_resetKeyboardControl = true; + base.Repaint(); + } + private void RGBToHSV() + { + EditorGUIUtility.RGBToHSV(new Color(this.m_R, this.m_G, this.m_B, 1f), out this.m_H, out this.m_S, out this.m_V); + } + private void HSVToRGB() + { + Color color = EditorGUIUtility.HSVToRGB(this.m_H, this.m_S, this.m_V); + this.m_R = color.r; + this.m_G = color.g; + this.m_B = color.b; + } + private static void swap(ref float f1, ref float f2) + { + float num = f1; + f1 = f2; + f2 = num; + } + private Vector2 Slider2D(Rect rect, Vector2 value, Vector2 maxvalue, Vector2 minvalue, GUIStyle backStyle, GUIStyle thumbStyle) + { + if (backStyle == null) + { + return value; + } + if (thumbStyle == null) + { + return value; + } + int controlID = GUIUtility.GetControlID(ColorPicker.s_Slider2Dhash, FocusType.Native); + if (maxvalue.x < minvalue.x) + { + ColorPicker.swap(ref maxvalue.x, ref minvalue.x); + } + if (maxvalue.y < minvalue.y) + { + ColorPicker.swap(ref maxvalue.y, ref minvalue.y); + } + float num = (thumbStyle.fixedHeight != 0f) ? thumbStyle.fixedHeight : ((float)thumbStyle.padding.vertical); + float num2 = (thumbStyle.fixedWidth != 0f) ? thumbStyle.fixedWidth : ((float)thumbStyle.padding.horizontal); + Vector2 vector = new Vector2((rect.width - (float)(backStyle.padding.right + backStyle.padding.left) - num2 * 2f) / (maxvalue.x - minvalue.x), (rect.height - (float)(backStyle.padding.top + backStyle.padding.bottom) - num * 2f) / (maxvalue.y - minvalue.y)); + Rect position = new Rect(rect.x + value.x * vector.x + num2 / 2f + (float)backStyle.padding.left - minvalue.x * vector.x, rect.y + value.y * vector.y + num / 2f + (float)backStyle.padding.top - minvalue.y * vector.y, num2, num); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (rect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = controlID; + value.x = (current.mousePosition.x - rect.x - num2 - (float)backStyle.padding.left) / vector.x + minvalue.x; + value.y = (current.mousePosition.y - rect.y - num - (float)backStyle.padding.top) / vector.y + minvalue.y; + GUI.changed = true; + Event.current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + value.x = (current.mousePosition.x - rect.x - num2 - (float)backStyle.padding.left) / vector.x + minvalue.x; + value.y = (current.mousePosition.y - rect.y - num - (float)backStyle.padding.top) / vector.y + minvalue.y; + value.x = Mathf.Clamp(value.x, minvalue.x, maxvalue.x); + value.y = Mathf.Clamp(value.y, minvalue.y, maxvalue.y); + GUI.changed = true; + Event.current.Use(); + } + break; + case EventType.Repaint: + backStyle.Draw(rect, GUIContent.none, controlID); + thumbStyle.Draw(position, GUIContent.none, controlID); + break; + } + return value; + } + private void RGBSliders() + { + bool changed = GUI.changed; + GUI.changed = false; + this.m_RTexture = ColorPicker.Update1DSlider(this.m_RTexture, 8, this.m_G, this.m_B, ref this.m_RTextureG, ref this.m_RTextureB, 0, false); + this.m_GTexture = ColorPicker.Update1DSlider(this.m_GTexture, 8, this.m_R, this.m_B, ref this.m_GTextureR, ref this.m_GTextureB, 1, false); + this.m_BTexture = ColorPicker.Update1DSlider(this.m_BTexture, 8, this.m_R, this.m_G, ref this.m_BTextureR, ref this.m_BTextureG, 2, false); + float num = (float)((int)Mathf.Round(this.m_R * 255f)); + float num2 = (float)((int)Mathf.Round(this.m_G * 255f)); + float num3 = (float)((int)Mathf.Round(this.m_B * 255f)); + num = this.TexturedSlider(this.m_RTexture, "R", num, 0f, 255f); + num2 = this.TexturedSlider(this.m_GTexture, "G", num2, 0f, 255f); + num3 = this.TexturedSlider(this.m_BTexture, "B", num3, 0f, 255f); + if (GUI.changed) + { + this.m_R = num / 255f; + this.m_G = num2 / 255f; + this.m_B = num3 / 255f; + this.RGBToHSV(); + } + GUI.changed |= changed; + } + private static Texture2D Update1DSlider(Texture2D tex, int xSize, float const1, float const2, ref float oldConst1, ref float oldConst2, int idx, bool hsvSpace) + { + if (!tex || const1 != oldConst1 || const2 != oldConst2) + { + if (!tex) + { + tex = ColorPicker.MakeTexture(xSize, 2); + } + Color[] array = new Color[xSize * 2]; + Color black = Color.black; + Color black2 = Color.black; + switch (idx) + { + case 0: + black = new Color(0f, const1, const2, 1f); + black2 = new Color(1f, 0f, 0f, 0f); + break; + case 1: + black = new Color(const1, 0f, const2, 1f); + black2 = new Color(0f, 1f, 0f, 0f); + break; + case 2: + black = new Color(const1, const2, 0f, 1f); + black2 = new Color(0f, 0f, 1f, 0f); + break; + case 3: + black = new Color(0f, 0f, 0f, 1f); + black2 = new Color(1f, 1f, 1f, 0f); + break; + } + ColorPicker.FillArea(xSize, 2, array, black, black2, new Color(0f, 0f, 0f, 0f)); + if (hsvSpace) + { + ColorPicker.HSVToRGBArray(array); + } + oldConst1 = const1; + oldConst2 = const2; + tex.SetPixels(array); + tex.Apply(); + } + return tex; + } + private float TexturedSlider(Texture2D background, string text, float val, float min, float max) + { + Rect rect = GUILayoutUtility.GetRect(16f, 16f, GUI.skin.label); + GUI.Label(new Rect(rect.x, rect.y - 1f, 20f, 16f), text); + rect.x += 14f; + rect.width -= 50f; + if (Event.current.type == EventType.Repaint) + { + Rect screenRect = new Rect(rect.x + 1f, rect.y + 2f, rect.width - 2f, rect.height - 4f); + Graphics.DrawTexture(screenRect, background, new Rect(0.5f / (float)background.width, 0.5f / (float)background.height, 1f - 1f / (float)background.width, 1f - 1f / (float)background.height), 0, 0, 0, 0, Color.grey); + } + int controlID = GUIUtility.GetControlID(869045, EditorGUIUtility.native, base.position); + bool changed = GUI.changed; + GUI.changed = false; + val = GUI.HorizontalSlider(new Rect(rect.x, rect.y + 1f, rect.width, rect.height - 2f), val, min, max, ColorPicker.styles.pickerBox, ColorPicker.styles.thumbHoriz); + if (GUI.changed && EditorGUI.s_RecycledEditor.IsEditingControl(controlID)) + { + EditorGUI.s_RecycledEditor.EndEditing(); + } + Rect position = new Rect(rect.xMax + 6f, rect.y, 30f, 16f); + val = (float)((int)EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, new Rect(0f, 0f, 0f, 0f), controlID, val, EditorGUI.kIntFieldFormatString, EditorStyles.numberField, false)); + val = Mathf.Clamp(val, min, max); + GUI.changed |= changed; + return val; + } + private void HSVSliders() + { + bool changed = GUI.changed; + GUI.changed = false; + this.m_HueTexture = ColorPicker.Update1DSlider(this.m_HueTexture, 64, 1f, 1f, ref this.m_HueTextureS, ref this.m_HueTextureV, 0, true); + this.m_SatTexture = ColorPicker.Update1DSlider(this.m_SatTexture, 8, this.m_H, Mathf.Max(this.m_V, 0.2f), ref this.m_SatTextureH, ref this.m_SatTextureV, 1, true); + this.m_ValTexture = ColorPicker.Update1DSlider(this.m_ValTexture, 8, this.m_H, this.m_S, ref this.m_ValTextureH, ref this.m_ValTextureS, 2, true); + float num = (float)((int)Mathf.Round(this.m_H * 359f)); + float num2 = (float)((int)Mathf.Round(this.m_S * 255f)); + float num3 = (float)((int)Mathf.Round(this.m_V * 255f)); + num = this.TexturedSlider(this.m_HueTexture, "H", num, 0f, 359f); + num2 = this.TexturedSlider(this.m_SatTexture, "S", num2, 0f, 255f); + num3 = this.TexturedSlider(this.m_ValTexture, "V", num3, 0f, 255f); + if (GUI.changed) + { + this.m_H = num / 359f; + this.m_S = num2 / 255f; + this.m_V = num3 / 255f; + this.HSVToRGB(); + } + GUI.changed |= changed; + } + private static void FillArea(int xSize, int ySize, Color[] retval, Color topLeftColor, Color rightGradient, Color downGradient) + { + Color b = new Color(0f, 0f, 0f, 0f); + Color b2 = new Color(0f, 0f, 0f, 0f); + if (xSize > 1) + { + b = rightGradient / (float)(xSize - 1); + } + if (ySize > 1) + { + b2 = downGradient / (float)(ySize - 1); + } + Color color = topLeftColor; + int num = 0; + for (int i = 0; i < ySize; i++) + { + Color color2 = color; + for (int j = 0; j < xSize; j++) + { + retval[num++] = color2; + color2 += b; + } + color += b2; + } + } + private static void HSVToRGBArray(Color[] colors) + { + int num = colors.Length; + for (int i = 0; i < num; i++) + { + Color color = colors[i]; + Color color2 = EditorGUIUtility.HSVToRGB(color.r, color.g, color.b); + color2.a = color.a; + colors[i] = color2; + } + } + private void DrawColorSlider(Rect colorSliderRect, Vector2 constantValues) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (this.m_ColorBoxMode != (ColorPicker.ColorBoxMode)this.m_TextureColorSliderMode) + { + int num = (int)this.m_ColorSliderSize; + int num2; + if (this.m_ColorBoxMode == ColorPicker.ColorBoxMode.SV_H) + { + num2 = 64; + } + else + { + num2 = (int)this.m_ColorSliderSize; + } + if (this.m_ColorSlider == null) + { + this.m_ColorSlider = ColorPicker.MakeTexture(num, num2); + } + if (this.m_ColorSlider.width != num || this.m_ColorSlider.height != num2) + { + this.m_ColorSlider.Resize(num, num2); + } + } + if (this.m_ColorBoxMode != (ColorPicker.ColorBoxMode)this.m_TextureColorSliderMode || constantValues != this.m_LastConstantValues) + { + Color[] pixels = this.m_ColorSlider.GetPixels(0); + int width = this.m_ColorSlider.width; + int height = this.m_ColorSlider.height; + switch (this.m_ColorBoxMode) + { + case ColorPicker.ColorBoxMode.SV_H: + ColorPicker.FillArea(width, height, pixels, new Color(0f, 1f, 1f, 1f), new Color(0f, 0f, 0f, 0f), new Color(1f, 0f, 0f, 0f)); + ColorPicker.HSVToRGBArray(pixels); + break; + case ColorPicker.ColorBoxMode.HV_S: + ColorPicker.FillArea(width, height, pixels, new Color(this.m_H, 0f, Mathf.Max(this.m_V, 0.3f), 1f), new Color(0f, 0f, 0f, 0f), new Color(0f, 1f, 0f, 0f)); + ColorPicker.HSVToRGBArray(pixels); + break; + case ColorPicker.ColorBoxMode.HS_V: + ColorPicker.FillArea(width, height, pixels, new Color(this.m_H, this.m_S, 0f, 1f), new Color(0f, 0f, 0f, 0f), new Color(0f, 0f, 1f, 0f)); + ColorPicker.HSVToRGBArray(pixels); + break; + case ColorPicker.ColorBoxMode.BG_R: + ColorPicker.FillArea(width, height, pixels, new Color(0f, this.m_G, this.m_B, 1f), new Color(0f, 0f, 0f, 0f), new Color(1f, 0f, 0f, 0f)); + break; + case ColorPicker.ColorBoxMode.BR_G: + ColorPicker.FillArea(width, height, pixels, new Color(this.m_R, 0f, this.m_B, 1f), new Color(0f, 0f, 0f, 0f), new Color(0f, 1f, 0f, 0f)); + break; + case ColorPicker.ColorBoxMode.RG_B: + ColorPicker.FillArea(width, height, pixels, new Color(this.m_R, this.m_G, 0f, 1f), new Color(0f, 0f, 0f, 0f), new Color(0f, 0f, 1f, 0f)); + break; + } + this.m_ColorSlider.SetPixels(pixels, 0); + this.m_ColorSlider.Apply(true); + } + Graphics.DrawTexture(colorSliderRect, this.m_ColorSlider, new Rect(0.5f / (float)this.m_ColorSlider.width, 0.5f / (float)this.m_ColorSlider.height, 1f - 1f / (float)this.m_ColorSlider.width, 1f - 1f / (float)this.m_ColorSlider.height), 0, 0, 0, 0, Color.grey); + } + public static Texture2D MakeTexture(int width, int height) + { + return new Texture2D(width, height, TextureFormat.ARGB32, false) + { + hideFlags = HideFlags.HideAndDontSave, + wrapMode = TextureWrapMode.Clamp, + hideFlags = HideFlags.DontSave + }; + } + private void DrawColorSpaceBox(Rect colorBoxRect, float constantValue) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (this.m_ColorBoxMode != (ColorPicker.ColorBoxMode)this.m_TextureColorBoxMode) + { + int num = 8; + int num2; + if (this.m_ColorBoxMode == ColorPicker.ColorBoxMode.HV_S || this.m_ColorBoxMode == ColorPicker.ColorBoxMode.HS_V) + { + num2 = 64; + } + else + { + num2 = 8; + } + if (this.m_ColorBox == null) + { + this.m_ColorBox = ColorPicker.MakeTexture(num2, num); + } + if (this.m_ColorBox.width != num2 || this.m_ColorBox.height != num) + { + this.m_ColorBox.Resize(num2, num); + } + } + if (this.m_ColorBoxMode != (ColorPicker.ColorBoxMode)this.m_TextureColorBoxMode || this.m_LastConstant != constantValue) + { + this.m_Colors = this.m_ColorBox.GetPixels(0); + int width = this.m_ColorBox.width; + int height = this.m_ColorBox.height; + switch (this.m_ColorBoxMode) + { + case ColorPicker.ColorBoxMode.SV_H: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(this.m_H, 0f, 0f, 1f), new Color(0f, 1f, 0f, 0f), new Color(0f, 0f, 1f, 0f)); + ColorPicker.HSVToRGBArray(this.m_Colors); + break; + case ColorPicker.ColorBoxMode.HV_S: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(0f, this.m_S, 0f, 1f), new Color(1f, 0f, 0f, 0f), new Color(0f, 0f, 1f, 0f)); + ColorPicker.HSVToRGBArray(this.m_Colors); + break; + case ColorPicker.ColorBoxMode.HS_V: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(0f, 0f, this.m_V, 1f), new Color(1f, 0f, 0f, 0f), new Color(0f, 1f, 0f, 0f)); + ColorPicker.HSVToRGBArray(this.m_Colors); + break; + case ColorPicker.ColorBoxMode.BG_R: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(this.m_R, 0f, 0f, 1f), new Color(0f, 0f, 1f, 0f), new Color(0f, 1f, 0f, 0f)); + break; + case ColorPicker.ColorBoxMode.BR_G: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(0f, this.m_G, 0f, 1f), new Color(0f, 0f, 1f, 0f), new Color(1f, 0f, 0f, 0f)); + break; + case ColorPicker.ColorBoxMode.RG_B: + ColorPicker.FillArea(width, height, this.m_Colors, new Color(0f, 0f, this.m_B, 1f), new Color(1f, 0f, 0f, 0f), new Color(0f, 1f, 0f, 0f)); + break; + } + this.m_ColorBox.SetPixels(this.m_Colors, 0); + this.m_ColorBox.Apply(true); + this.m_LastConstant = constantValue; + this.m_TextureColorBoxMode = (int)this.m_ColorBoxMode; + } + Graphics.DrawTexture(colorBoxRect, this.m_ColorBox, new Rect(0.5f / (float)this.m_ColorBox.width, 0.5f / (float)this.m_ColorBox.height, 1f - 1f / (float)this.m_ColorBox.width, 1f - 1f / (float)this.m_ColorBox.height), 0, 0, 0, 0, Color.grey); + } + private void InitIfNeeded() + { + if (ColorPicker.styles == null) + { + ColorPicker.styles = new ColorPicker.Styles(); + } + if (this.m_ColorLibraryEditorState == null) + { + this.m_ColorLibraryEditorState = new PresetLibraryEditorState(ColorPicker.presetsEditorPrefID); + this.m_ColorLibraryEditorState.TransferEditorPrefsState(true); + } + if (this.m_ColorLibraryEditor == null) + { + ScriptableObjectSaveLoadHelper helper = new ScriptableObjectSaveLoadHelper("colors", SaveType.Text); + this.m_ColorLibraryEditor = new PresetLibraryEditor(helper, this.m_ColorLibraryEditorState, new Action(this.PresetClickedCallback)); + this.m_ColorLibraryEditor.previewAspect = 1f; + this.m_ColorLibraryEditor.minMaxPreviewHeight = new Vector2(14f, 14f); + this.m_ColorLibraryEditor.settingsMenuRightMargin = 2f; + this.m_ColorLibraryEditor.useOnePixelOverlappedGrid = true; + this.m_ColorLibraryEditor.alwaysShowScrollAreaHorizontalLines = false; + this.m_ColorLibraryEditor.marginsForGrid = new RectOffset(0, 0, 0, 0); + this.m_ColorLibraryEditor.marginsForList = new RectOffset(0, 5, 2, 2); + } + } + private void PresetClickedCallback(int clickCount, object presetObject) + { + Color color = (Color)presetObject; + this.SetColor(color); + this.colorChanged = true; + } + private void DoColorSwatchAndEyedropper() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(ColorPicker.styles.eyeDropper, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.Width(40f), + GUILayout.ExpandWidth(false) + })) + { + EyeDropper.Start(this.m_Parent); + this.m_ColorBoxMode = ColorPicker.ColorBoxMode.EyeDropper; + GUIUtility.ExitGUI(); + } + Color color = new Color(this.m_R, this.m_G, this.m_B, this.m_A); + Rect rect = GUILayoutUtility.GetRect(20f, 20f, 20f, 20f, ColorPicker.styles.colorPickerBox, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + EditorGUIUtility.DrawColorSwatch(rect, color, this.m_ShowAlpha); + if (Event.current.type == EventType.Repaint) + { + ColorPicker.styles.pickerBox.Draw(rect, GUIContent.none, false, false, false, false); + } + GUILayout.EndHorizontal(); + } + private void DoColorSpaceGUI() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_ShowColors = GUILayout.Toggle(this.m_ShowColors, ColorPicker.styles.colorToggle, EditorStyles.foldout, new GUILayoutOption[0]); + GUI.enabled = this.m_ShowColors; + if (GUILayout.Button(ColorPicker.styles.colorCycle, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + this.m_OldColorBoxMode = (this.m_ColorBoxMode = (this.m_ColorBoxMode + 1) % ColorPicker.ColorBoxMode.EyeDropper); + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + if (this.m_ShowColors) + { + bool changed = GUI.changed; + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.ExpandHeight(false) + }); + Rect aspectRect = GUILayoutUtility.GetAspectRect(1f, ColorPicker.styles.pickerBox, new GUILayoutOption[] + { + GUILayout.MinWidth(64f), + GUILayout.MinHeight(64f), + GUILayout.MaxWidth(256f), + GUILayout.MaxHeight(256f) + }); + EditorGUILayout.Space(); + Rect rect = GUILayoutUtility.GetRect(8f, 32f, 64f, 128f, ColorPicker.styles.pickerBox); + rect.height = aspectRect.height; + GUILayout.EndHorizontal(); + GUI.changed = false; + switch (this.m_ColorBoxMode) + { + case ColorPicker.ColorBoxMode.SV_H: + this.Slider3D(aspectRect, rect, ref this.m_S, ref this.m_V, ref this.m_H, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.HSVToRGB(); + } + break; + case ColorPicker.ColorBoxMode.HV_S: + this.Slider3D(aspectRect, rect, ref this.m_H, ref this.m_V, ref this.m_S, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.HSVToRGB(); + } + break; + case ColorPicker.ColorBoxMode.HS_V: + this.Slider3D(aspectRect, rect, ref this.m_H, ref this.m_S, ref this.m_V, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.HSVToRGB(); + } + break; + case ColorPicker.ColorBoxMode.BG_R: + this.Slider3D(aspectRect, rect, ref this.m_B, ref this.m_G, ref this.m_R, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.RGBToHSV(); + } + break; + case ColorPicker.ColorBoxMode.BR_G: + this.Slider3D(aspectRect, rect, ref this.m_B, ref this.m_R, ref this.m_G, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.RGBToHSV(); + } + break; + case ColorPicker.ColorBoxMode.RG_B: + this.Slider3D(aspectRect, rect, ref this.m_R, ref this.m_G, ref this.m_B, ColorPicker.styles.pickerBox, ColorPicker.styles.thumb2D, ColorPicker.styles.thumbVert); + if (GUI.changed) + { + this.RGBToHSV(); + } + break; + case ColorPicker.ColorBoxMode.EyeDropper: + EyeDropper.DrawPreview(Rect.MinMaxRect(aspectRect.x, aspectRect.y, rect.xMax, aspectRect.yMax)); + break; + } + GUI.changed |= changed; + } + } + private void DoColorSliders() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_ShowSliders = GUILayout.Toggle(this.m_ShowSliders, ColorPicker.styles.sliderToggle, EditorStyles.foldout, new GUILayoutOption[0]); + GUI.enabled = this.m_ShowSliders; + if (GUILayout.Button(ColorPicker.styles.sliderCycle, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + this.m_SliderMode = (this.m_SliderMode + 1) % (ColorPicker.SliderMode)2; + GUI.changed = true; + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + if (this.m_ShowSliders) + { + ColorPicker.SliderMode sliderMode = this.m_SliderMode; + if (sliderMode != ColorPicker.SliderMode.RGB) + { + if (sliderMode == ColorPicker.SliderMode.HSV) + { + this.HSVSliders(); + } + } + else + { + this.RGBSliders(); + } + if (this.m_ShowAlpha) + { + this.m_AlphaTexture = ColorPicker.Update1DSlider(this.m_AlphaTexture, 8, 0f, 0f, ref this.m_OldAlpha, ref this.m_OldAlpha, 3, false); + this.m_A = this.TexturedSlider(this.m_AlphaTexture, "A", Mathf.Round(this.m_A * 255f), 0f, 255f) / 255f; + } + } + } + private void DoPresetsGUI() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + this.m_ShowPresets = GUILayout.Toggle(this.m_ShowPresets, ColorPicker.styles.presetsToggle, EditorStyles.foldout, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetInt("CPPresetsShow", (!this.m_ShowPresets) ? 0 : 1); + } + GUILayout.Space(17f); + GUILayout.EndHorizontal(); + if (this.m_ShowPresets) + { + GUILayout.Space(-18f); + Rect rect = GUILayoutUtility.GetRect(0f, Mathf.Clamp(this.m_ColorLibraryEditor.contentHeight, 20f, 250f)); + this.m_ColorLibraryEditor.OnGUI(rect, this.m_Color); + } + } + private void OnGUI() + { + this.InitIfNeeded(); + if (this.m_resetKeyboardControl) + { + GUIUtility.keyboardControl = 0; + this.m_resetKeyboardControl = false; + } + EventType type = Event.current.type; + if (type == EventType.ExecuteCommand) + { + string commandName = Event.current.commandName; + switch (commandName) + { + case "EyeDropperUpdate": + base.Repaint(); + break; + case "EyeDropperClicked": + { + Color lastPickedColor = EyeDropper.GetLastPickedColor(); + this.m_R = lastPickedColor.r; + this.m_G = lastPickedColor.g; + this.m_B = lastPickedColor.b; + this.RGBToHSV(); + this.m_ColorBoxMode = this.m_OldColorBoxMode; + this.m_Color = new Color(this.m_R, this.m_G, this.m_B, this.m_A); + this.SendEvent(true); + break; + } + case "EyeDropperCancelled": + base.Repaint(); + this.m_ColorBoxMode = this.m_OldColorBoxMode; + break; + } + } + EditorGUIUtility.labelWidth = 15f; + EditorGUIUtility.fieldWidth = 30f; + Rect rect = EditorGUILayout.BeginVertical(ColorPicker.styles.background, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + GUILayout.Space(10f); + this.DoColorSwatchAndEyedropper(); + GUILayout.Space(10f); + this.DoColorSpaceGUI(); + GUILayout.Space(10f); + this.DoColorSliders(); + GUILayout.Space(10f); + if (EditorGUI.EndChangeCheck()) + { + this.colorChanged = true; + } + this.DoPresetsGUI(); + if (this.colorChanged) + { + EditorPrefs.SetInt("CPSliderShow", (!this.m_ShowSliders) ? 0 : 1); + EditorPrefs.SetInt("CPSliderMode", (int)this.m_SliderMode); + EditorPrefs.SetInt("CPColorShow", (!this.m_ShowColors) ? 0 : 1); + EditorPrefs.SetInt("CPColorMode", (int)this.m_ColorBoxMode); + } + if (this.colorChanged) + { + this.colorChanged = false; + this.m_Color = new Color(this.m_R, this.m_G, this.m_B, this.m_A); + this.SendEvent(true); + } + EditorGUILayout.EndVertical(); + if (rect.height > 0f) + { + this.SetHeight(rect.height); + } + if (Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.Return) + { + if (keyCode == KeyCode.Escape) + { + Undo.RevertAllDownToGroup(this.m_ModalUndoGroup); + this.m_Color = this.m_OriginalColor; + this.SendEvent(false); + base.Close(); + GUIUtility.ExitGUI(); + return; + } + if (keyCode != KeyCode.KeypadEnter) + { + return; + } + } + base.Close(); + } + } + private void SetHeight(float newHeight) + { + if (newHeight == base.position.height) + { + return; + } + base.minSize = new Vector2(193f, newHeight); + base.maxSize = new Vector2(193f, newHeight); + } + private void Slider3D(Rect boxPos, Rect sliderPos, ref float x, ref float y, ref float z, GUIStyle box, GUIStyle thumb2D, GUIStyle thumbHoriz) + { + Rect colorBoxRect = boxPos; + colorBoxRect.x += 1f; + colorBoxRect.y += 1f; + colorBoxRect.width -= 2f; + colorBoxRect.height -= 2f; + this.DrawColorSpaceBox(colorBoxRect, z); + Vector2 value = new Vector2(x, 1f - y); + value = this.Slider2D(boxPos, value, new Vector2(0f, 0f), new Vector2(1f, 1f), box, thumb2D); + x = value.x; + y = 1f - value.y; + Rect colorSliderRect = new Rect(sliderPos.x + 1f, sliderPos.y + 1f, sliderPos.width - 2f, sliderPos.height - 2f); + this.DrawColorSlider(colorSliderRect, new Vector2(x, y)); + z = GUI.VerticalSlider(sliderPos, z, 1f, 0f, box, thumbHoriz); + } + private void SendEvent(bool exitGUI) + { + if (this.m_DelegateView) + { + Event e = EditorGUIUtility.CommandEvent("ColorPickerChanged"); + if (!this.m_IsOSColorPicker) + { + base.Repaint(); + } + this.m_DelegateView.SendEvent(e); + if (!this.m_IsOSColorPicker && exitGUI) + { + GUIUtility.ExitGUI(); + } + } + } + public void SetColor(Color c) + { + if (this.m_IsOSColorPicker) + { + OSColorPicker.color = c; + } + else + { + if (this.m_Color.r == c.r && this.m_Color.g == c.g && this.m_Color.b == c.b && this.m_Color.a == c.a) + { + return; + } + this.m_resetKeyboardControl = true; + this.m_Color = c; + this.m_R = c.r; + this.m_G = c.g; + this.m_B = c.b; + this.RGBToHSV(); + this.m_A = c.a; + base.Repaint(); + } + } + public static void Show(GUIView viewToUpdate, Color col) + { + ColorPicker.Show(viewToUpdate, col, true); + } + public static void Show(GUIView viewToUpdate, Color col, bool showAlpha) + { + ColorPicker.get.m_DelegateView = viewToUpdate; + ColorPicker.color = col; + ColorPicker.get.m_OriginalColor = col; + ColorPicker.get.m_ShowAlpha = showAlpha; + ColorPicker.get.m_ModalUndoGroup = Undo.GetCurrentGroup(); + if (ColorPicker.get.m_IsOSColorPicker) + { + OSColorPicker.Show(showAlpha); + } + else + { + ColorPicker get = ColorPicker.get; + get.title = "Color"; + float x = (float)EditorPrefs.GetInt("CPickerWidth", (int)get.position.width); + float y = (float)EditorPrefs.GetInt("CPickerHeight", (int)get.position.height); + get.minSize = new Vector2(x, y); + get.maxSize = new Vector2(x, y); + get.ShowAuxWindow(); + } + } + private void PollOSColorPicker() + { + if (this.m_IsOSColorPicker) + { + if (!OSColorPicker.visible || Application.platform != RuntimePlatform.OSXEditor) + { + UnityEngine.Object.DestroyImmediate(this); + } + else + { + Color color = OSColorPicker.color; + if (this.m_Color != color) + { + this.m_Color = color; + this.SendEvent(true); + } + } + } + } + public void OnDestroy() + { + Undo.CollapseUndoOperations(this.m_ModalUndoGroup); + if (this.m_ColorSlider) + { + UnityEngine.Object.DestroyImmediate(this.m_ColorSlider); + } + if (this.m_ColorBox) + { + UnityEngine.Object.DestroyImmediate(this.m_ColorBox); + } + if (this.m_RTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_RTexture); + } + if (this.m_GTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_GTexture); + } + if (this.m_BTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_BTexture); + } + if (this.m_HueTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_HueTexture); + } + if (this.m_SatTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_SatTexture); + } + if (this.m_ValTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_ValTexture); + } + if (this.m_AlphaTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_AlphaTexture); + } + ColorPicker.s_SharedColorPicker = null; + if (this.m_IsOSColorPicker) + { + OSColorPicker.Close(); + } + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.PollOSColorPicker)); + if (this.m_ColorLibraryEditorState != null) + { + this.m_ColorLibraryEditorState.TransferEditorPrefsState(false); + } + if (this.m_ColorLibraryEditor != null) + { + this.m_ColorLibraryEditor.UnloadUsedLibraries(); + } + EditorPrefs.SetInt("CPickerWidth", (int)base.position.width); + EditorPrefs.SetInt("CPickerHeight", (int)base.position.height); + } + } +} diff --git a/UnityEditor/UnityEditor/ColorPresetLibrary.cs b/UnityEditor/UnityEditor/ColorPresetLibrary.cs new file mode 100644 index 00000000..aa59aac4 --- /dev/null +++ b/UnityEditor/UnityEditor/ColorPresetLibrary.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ColorPresetLibrary : PresetLibrary + { + [Serializable] + private class ColorPreset + { + [SerializeField] + private string m_Name; + [SerializeField] + private Color m_Color; + public Color color + { + get + { + return this.m_Color; + } + set + { + this.m_Color = value; + } + } + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public ColorPreset(Color preset, string presetName) + { + this.color = preset; + this.name = presetName; + } + public ColorPreset(Color preset, Color preset2, string presetName) + { + this.color = preset; + this.name = presetName; + } + } + public const int kSwatchSize = 14; + public const int kMiniSwatchSize = 8; + [SerializeField] + private List m_Presets = new List(); + private Texture2D m_ColorSwatch; + private Texture2D m_ColorSwatchTriangular; + private Texture2D m_MiniColorSwatchTriangular; + private Texture2D m_CheckerBoard; + private void OnDestroy() + { + if (this.m_ColorSwatch != null) + { + UnityEngine.Object.DestroyImmediate(this.m_ColorSwatch); + } + if (this.m_ColorSwatchTriangular != null) + { + UnityEngine.Object.DestroyImmediate(this.m_ColorSwatchTriangular); + } + if (this.m_MiniColorSwatchTriangular != null) + { + UnityEngine.Object.DestroyImmediate(this.m_MiniColorSwatchTriangular); + } + if (this.m_CheckerBoard != null) + { + UnityEngine.Object.DestroyImmediate(this.m_CheckerBoard); + } + } + public override int Count() + { + return this.m_Presets.Count; + } + public override object GetPreset(int index) + { + return this.m_Presets[index].color; + } + public override void Add(object presetObject, string presetName) + { + Color preset = (Color)presetObject; + this.m_Presets.Add(new ColorPresetLibrary.ColorPreset(preset, presetName)); + } + public override void Replace(int index, object newPresetObject) + { + Color color = (Color)newPresetObject; + this.m_Presets[index].color = color; + } + public override void Remove(int index) + { + this.m_Presets.RemoveAt(index); + } + public override void Move(int index, int destIndex, bool insertAfterDestIndex) + { + PresetLibraryHelpers.MoveListItem(this.m_Presets, index, destIndex, insertAfterDestIndex); + } + public override void Draw(Rect rect, int index) + { + this.DrawInternal(rect, this.m_Presets[index].color); + } + public override void Draw(Rect rect, object presetObject) + { + this.DrawInternal(rect, (Color)presetObject); + } + private void Init() + { + if (this.m_ColorSwatch == null) + { + this.m_ColorSwatch = ColorPresetLibrary.CreateColorSwatchWithBorder(14, 14, false); + } + if (this.m_ColorSwatchTriangular == null) + { + this.m_ColorSwatchTriangular = ColorPresetLibrary.CreateColorSwatchWithBorder(14, 14, true); + } + if (this.m_MiniColorSwatchTriangular == null) + { + this.m_MiniColorSwatchTriangular = ColorPresetLibrary.CreateColorSwatchWithBorder(8, 8, true); + } + if (this.m_CheckerBoard == null) + { + this.m_CheckerBoard = GradientEditor.CreateCheckerTexture(2, 2, 3, new Color(0.8f, 0.8f, 0.8f), new Color(0.5f, 0.5f, 0.5f)); + } + } + private void DrawInternal(Rect rect, Color preset) + { + this.Init(); + Color color = GUI.color; + if ((int)rect.height == 14) + { + if (preset.a > 0.97f) + { + this.RenderSolidSwatch(rect, preset); + } + else + { + this.RenderSwatchWithAlpha(rect, preset, this.m_ColorSwatchTriangular); + } + } + else + { + this.RenderSwatchWithAlpha(rect, preset, this.m_MiniColorSwatchTriangular); + } + GUI.color = color; + } + private void RenderSolidSwatch(Rect rect, Color preset) + { + GUI.color = preset; + GUI.DrawTexture(rect, this.m_ColorSwatch); + } + private void RenderSwatchWithAlpha(Rect rect, Color preset, Texture2D swatchTexture) + { + Rect position = new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f); + GUI.color = Color.white; + Rect texCoords = new Rect(0f, 0f, position.width / (float)this.m_CheckerBoard.width, position.height / (float)this.m_CheckerBoard.height); + GUI.DrawTextureWithTexCoords(position, this.m_CheckerBoard, texCoords, false); + GUI.color = preset; + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = new Color(preset.r, preset.g, preset.b, 1f); + GUI.DrawTexture(rect, swatchTexture); + } + public override string GetName(int index) + { + return this.m_Presets[index].name; + } + public override void SetName(int index, string presetName) + { + this.m_Presets[index].name = presetName; + } + public void CreateDebugColors() + { + for (int i = 0; i < 2000; i++) + { + this.m_Presets.Add(new ColorPresetLibrary.ColorPreset(new Color(UnityEngine.Random.Range(0.2f, 1f), UnityEngine.Random.Range(0.2f, 1f), UnityEngine.Random.Range(0.2f, 1f), 1f), "Preset Color " + i)); + } + } + private static Texture2D CreateColorSwatchWithBorder(int width, int height, bool triangular) + { + Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false); + texture2D.hideFlags = HideFlags.HideAndDontSave; + Color[] array = new Color[width * height]; + Color color = new Color(1f, 1f, 1f, 0f); + if (triangular) + { + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width; j++) + { + if (i < width - j) + { + array[j + i * width] = Color.white; + } + else + { + array[j + i * width] = color; + } + } + } + } + else + { + for (int k = 0; k < height * width; k++) + { + array[k] = Color.white; + } + } + for (int l = 0; l < width; l++) + { + array[l] = Color.black; + } + for (int m = 0; m < width; m++) + { + array[(height - 1) * width + m] = Color.black; + } + for (int n = 0; n < height; n++) + { + array[n * width] = Color.black; + } + for (int num = 0; num < height; num++) + { + array[num * width + width - 1] = Color.black; + } + texture2D.SetPixels(array); + texture2D.Apply(); + return texture2D; + } + } +} diff --git a/UnityEditor/UnityEditor/ColorPresetLibraryEditor.cs b/UnityEditor/UnityEditor/ColorPresetLibraryEditor.cs new file mode 100644 index 00000000..36bdcb39 --- /dev/null +++ b/UnityEditor/UnityEditor/ColorPresetLibraryEditor.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(ColorPresetLibrary))] + internal class ColorPresetLibraryEditor : Editor + { + private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; + public void OnEnable() + { + this.m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(this.target, "Color Preset Library", new Action(this.OnEditButtonClicked)); + this.m_GenericPresetLibraryInspector.useOnePixelOverlappedGrid = true; + this.m_GenericPresetLibraryInspector.maxShowNumPresets = 2000; + } + public void OnDestroy() + { + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnDestroy(); + } + } + public override void OnInspectorGUI() + { + this.m_GenericPresetLibraryInspector.itemViewMode = PresetLibraryEditorState.GetItemViewMode(ColorPicker.presetsEditorPrefID); + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnInspectorGUI(); + } + } + private void OnEditButtonClicked(string libraryPath) + { + ColorPicker.Show(GUIView.current, Color.white); + ColorPicker.get.currentPresetLibrary = libraryPath; + } + } +} diff --git a/UnityEditor/UnityEditor/ColumnView.cs b/UnityEditor/UnityEditor/ColumnView.cs new file mode 100644 index 00000000..499a1a71 --- /dev/null +++ b/UnityEditor/UnityEditor/ColumnView.cs @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ColumnView + { + public class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle selected = "PR Label"; + public Texture2D categoryArrowIcon = EditorStyles.foldout.normal.background; + } + public delegate void ObjectColumnFunction(object value); + public delegate object ObjectColumnGetDataFunction(object value); + private static ColumnView.Styles s_Styles; + private readonly List m_ListViewStates; + private readonly List m_CachedSelectedIndices; + private Vector2 m_ScrollPosition; + private string m_SearchText = string.Empty; + public float columnWidth = 150f; + public int minimumNumberOfColumns = 1; + private int m_ColumnToFocusKeyboard = -1; + public string searchText + { + get + { + return this.m_SearchText; + } + } + public bool isSearching + { + get + { + return this.searchText != string.Empty; + } + } + public ColumnView() + { + this.m_ListViewStates = new List(); + this.m_CachedSelectedIndices = new List(); + } + private static void InitStyles() + { + if (ColumnView.s_Styles == null) + { + ColumnView.s_Styles = new ColumnView.Styles(); + } + } + public void SetSelected(int column, int selectionIndex) + { + if (this.m_ListViewStates.Count == column) + { + this.m_ListViewStates.Add(new ListViewState()); + } + if (this.m_CachedSelectedIndices.Count == column) + { + this.m_CachedSelectedIndices.Add(-1); + } + this.m_CachedSelectedIndices[column] = selectionIndex; + this.m_ListViewStates[column].row = selectionIndex; + } + public void SetKeyboardFocusColumn(int column) + { + this.m_ColumnToFocusKeyboard = column; + } + public void OnGUI(List elements, ColumnView.ObjectColumnFunction previewColumnFunction) + { + this.OnGUI(elements, previewColumnFunction, null, null, null); + } + public void OnGUI(List elements, ColumnView.ObjectColumnFunction previewColumnFunction, ColumnView.ObjectColumnFunction selectedSearchItemFunction, ColumnView.ObjectColumnFunction selectedRegularItemFunction, ColumnView.ObjectColumnGetDataFunction getDataForDraggingFunction) + { + ColumnView.InitStyles(); + this.m_ScrollPosition = GUILayout.BeginScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + List list = elements; + int i = 0; + object obj; + do + { + if (this.m_ListViewStates.Count == i) + { + this.m_ListViewStates.Add(new ListViewState()); + } + if (this.m_CachedSelectedIndices.Count == i) + { + this.m_CachedSelectedIndices.Add(-1); + } + ListViewState listViewState = this.m_ListViewStates[i]; + listViewState.totalRows = list.Count; + if (i == 0) + { + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.MaxWidth(this.columnWidth) + }); + } + int num = this.m_CachedSelectedIndices[i]; + num = this.DoListColumn(listViewState, list, i, num, (i != 0) ? null : selectedSearchItemFunction, selectedRegularItemFunction, getDataForDraggingFunction); + if (Event.current.type == EventType.Layout && this.m_ColumnToFocusKeyboard == i) + { + this.m_ColumnToFocusKeyboard = -1; + GUIUtility.keyboardControl = listViewState.ID; + if (listViewState.row == -1 && list.Count != 0) + { + num = (listViewState.row = 0); + } + } + if (i == 0) + { + if (this.isSearching) + { + KeyCode keyCode = ColumnView.StealImportantListviewKeys(); + if (keyCode != KeyCode.None) + { + ListViewShared.SendKey(this.m_ListViewStates[0], keyCode); + } + } + this.m_SearchText = EditorGUILayout.ToolbarSearchField(this.m_SearchText, new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + if (num >= list.Count) + { + num = -1; + } + if (Event.current.type == EventType.Layout && this.m_CachedSelectedIndices[i] != num && this.m_ListViewStates.Count > i + 1) + { + int index = i + 1; + int count = this.m_ListViewStates.Count - (i + 1); + this.m_ListViewStates.RemoveRange(index, count); + this.m_CachedSelectedIndices.RemoveRange(index, count); + } + this.m_CachedSelectedIndices[i] = num; + obj = ((num <= -1) ? null : list[num].value); + list = (obj as List); + i++; + } + while (list != null); + while (i < this.minimumNumberOfColumns) + { + this.DoDummyColumn(); + i++; + } + ColumnView.DoPreviewColumn(obj, previewColumnFunction); + GUILayout.EndHorizontal(); + GUILayout.EndScrollView(); + } + private static void DoItemSelectedEvent(ColumnView.ObjectColumnFunction selectedRegularItemFunction, object value) + { + if (selectedRegularItemFunction != null) + { + selectedRegularItemFunction(value); + } + Event.current.Use(); + } + private void DoSearchItemSelectedEvent(ColumnView.ObjectColumnFunction selectedSearchItemFunction, object value) + { + this.m_SearchText = string.Empty; + ColumnView.DoItemSelectedEvent(selectedSearchItemFunction, value); + } + private void DoDummyColumn() + { + GUILayout.Box(GUIContent.none, ColumnView.s_Styles.background, new GUILayoutOption[] + { + GUILayout.Width(this.columnWidth + 1f) + }); + } + private static void DoPreviewColumn(object selectedObject, ColumnView.ObjectColumnFunction previewColumnFunction) + { + GUILayout.BeginVertical(ColumnView.s_Styles.background, new GUILayoutOption[0]); + if (previewColumnFunction != null) + { + previewColumnFunction(selectedObject); + } + GUILayout.EndVertical(); + } + private int DoListColumn(ListViewState listView, List columnViewElements, int columnIndex, int selectedIndex, ColumnView.ObjectColumnFunction selectedSearchItemFunction, ColumnView.ObjectColumnFunction selectedRegularItemFunction, ColumnView.ObjectColumnGetDataFunction getDataForDraggingFunction) + { + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && listView.row > -1) + { + if (this.isSearching && selectedSearchItemFunction != null) + { + this.DoSearchItemSelectedEvent(selectedSearchItemFunction, columnViewElements[selectedIndex].value); + } + if (!this.isSearching && GUIUtility.keyboardControl == listView.ID && selectedRegularItemFunction != null) + { + ColumnView.DoItemSelectedEvent(selectedRegularItemFunction, columnViewElements[selectedIndex].value); + } + } + if (GUIUtility.keyboardControl == listView.ID && Event.current.type == EventType.KeyDown && !this.isSearching) + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.RightArrow) + { + if (keyCode == KeyCode.LeftArrow) + { + this.m_ColumnToFocusKeyboard = columnIndex - 1; + Event.current.Use(); + } + } + else + { + this.m_ColumnToFocusKeyboard = columnIndex + 1; + Event.current.Use(); + } + } + foreach (ListViewElement element in ListViewGUILayout.ListView(listView, ColumnView.s_Styles.background, new GUILayoutOption[] + { + GUILayout.Width(this.columnWidth) + })) + { + ColumnViewElement columnViewElement = columnViewElements[element.row]; + if (element.row == listView.row && Event.current.type == EventType.Repaint) + { + Rect position = element.position; + position.x += 1f; + position.y += 1f; + ColumnView.s_Styles.selected.Draw(position, false, true, true, GUIUtility.keyboardControl == listView.ID); + } + GUILayout.Label(columnViewElement.name, new GUILayoutOption[0]); + if (columnViewElement.value is List) + { + Rect position2 = element.position; + position2.x = position2.xMax - (float)ColumnView.s_Styles.categoryArrowIcon.width - 5f; + position2.y += 2f; + GUI.Label(position2, ColumnView.s_Styles.categoryArrowIcon); + } + this.DoDoubleClick(element, columnViewElement, selectedSearchItemFunction, selectedRegularItemFunction); + ColumnView.DoDragAndDrop(listView, element, columnViewElements, getDataForDraggingFunction); + } + if (Event.current.type == EventType.Layout) + { + selectedIndex = listView.row; + } + return selectedIndex; + } + private static void DoDragAndDrop(ListViewState listView, ListViewElement element, List columnViewElements, ColumnView.ObjectColumnGetDataFunction getDataForDraggingFunction) + { + if (GUIUtility.hotControl == listView.ID && Event.current.type == EventType.MouseDown && element.position.Contains(Event.current.mousePosition) && Event.current.button == 0) + { + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), listView.ID); + dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; + } + if (GUIUtility.hotControl == listView.ID && Event.current.type == EventType.MouseDrag && GUIClip.visibleRect.Contains(Event.current.mousePosition)) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), listView.ID); + if (dragAndDropDelay2.CanStartDrag()) + { + object obj = (getDataForDraggingFunction != null) ? getDataForDraggingFunction(columnViewElements[listView.row].value) : null; + if (obj == null) + { + return; + } + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + DragAndDrop.paths = null; + DragAndDrop.SetGenericData("CustomDragData", obj); + DragAndDrop.StartDrag(columnViewElements[listView.row].name); + Event.current.Use(); + } + } + } + private void DoDoubleClick(ListViewElement element, ColumnViewElement columnViewElement, ColumnView.ObjectColumnFunction selectedSearchItemFunction, ColumnView.ObjectColumnFunction selectedRegularItemFunction) + { + if (Event.current.type == EventType.MouseDown && element.position.Contains(Event.current.mousePosition) && Event.current.button == 0 && Event.current.clickCount == 2) + { + if (this.isSearching) + { + this.DoSearchItemSelectedEvent(selectedSearchItemFunction, columnViewElement.value); + } + else + { + ColumnView.DoItemSelectedEvent(selectedRegularItemFunction, columnViewElement.value); + } + } + } + private static KeyCode StealImportantListviewKeys() + { + if (Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode == KeyCode.UpArrow || keyCode == KeyCode.DownArrow || keyCode == KeyCode.PageUp || keyCode == KeyCode.PageDown) + { + Event.current.Use(); + return keyCode; + } + } + return KeyCode.None; + } + } +} diff --git a/UnityEditor/UnityEditor/ColumnViewElement.cs b/UnityEditor/UnityEditor/ColumnViewElement.cs new file mode 100644 index 00000000..38261026 --- /dev/null +++ b/UnityEditor/UnityEditor/ColumnViewElement.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + internal class ColumnViewElement + { + public string name; + public object value; + public ColumnViewElement(string name, object value) + { + this.name = name; + this.value = value; + } + } +} diff --git a/UnityEditor/UnityEditor/CompareInfo.cs b/UnityEditor/UnityEditor/CompareInfo.cs new file mode 100644 index 00000000..554a0226 --- /dev/null +++ b/UnityEditor/UnityEditor/CompareInfo.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + internal struct CompareInfo + { + public int left; + public int right; + public int convert_binary; + public int autodetect_binary; + public CompareInfo(int ver1, int ver2, int binary, int abinary) + { + this.left = ver1; + this.right = ver2; + this.convert_binary = binary; + this.autodetect_binary = abinary; + } + } +} diff --git a/UnityEditor/UnityEditor/ConsoleWindow.cs b/UnityEditor/UnityEditor/ConsoleWindow.cs new file mode 100644 index 00000000..5ea7d656 --- /dev/null +++ b/UnityEditor/UnityEditor/ConsoleWindow.cs @@ -0,0 +1,465 @@ +using System; +using System.Globalization; +using System.Text; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ConsoleWindow : EditorWindow, IHasCustomMenu + { + internal class Constants + { + public static bool ms_Loaded; + public static GUIStyle Box; + public static GUIStyle Button; + public static GUIStyle MiniButton; + public static GUIStyle MiniButtonLeft; + public static GUIStyle MiniButtonMiddle; + public static GUIStyle MiniButtonRight; + public static GUIStyle LogStyle; + public static GUIStyle WarningStyle; + public static GUIStyle ErrorStyle; + public static GUIStyle EvenBackground; + public static GUIStyle OddBackground; + public static GUIStyle MessageStyle; + public static GUIStyle StatusError; + public static GUIStyle StatusWarn; + public static GUIStyle StatusLog; + public static GUIStyle Toolbar; + public static GUIStyle CountBadge; + public static void Init() + { + if (ConsoleWindow.Constants.ms_Loaded) + { + return; + } + ConsoleWindow.Constants.ms_Loaded = true; + ConsoleWindow.Constants.Box = "CN Box"; + ConsoleWindow.Constants.Button = "Button"; + ConsoleWindow.Constants.MiniButton = "ToolbarButton"; + ConsoleWindow.Constants.MiniButtonLeft = "ToolbarButton"; + ConsoleWindow.Constants.MiniButtonMiddle = "ToolbarButton"; + ConsoleWindow.Constants.MiniButtonRight = "ToolbarButton"; + ConsoleWindow.Constants.Toolbar = "Toolbar"; + ConsoleWindow.Constants.LogStyle = "CN EntryInfo"; + ConsoleWindow.Constants.WarningStyle = "CN EntryWarn"; + ConsoleWindow.Constants.ErrorStyle = "CN EntryError"; + ConsoleWindow.Constants.EvenBackground = "CN EntryBackEven"; + ConsoleWindow.Constants.OddBackground = "CN EntryBackodd"; + ConsoleWindow.Constants.MessageStyle = "CN Message"; + ConsoleWindow.Constants.StatusError = "CN StatusError"; + ConsoleWindow.Constants.StatusWarn = "CN StatusWarn"; + ConsoleWindow.Constants.StatusLog = "CN StatusInfo"; + ConsoleWindow.Constants.CountBadge = "CN CountBadge"; + } + } + private enum Mode + { + Error = 1, + Assert, + Log = 4, + Fatal = 16, + DontPreprocessCondition = 32, + AssetImportError = 64, + AssetImportWarning = 128, + ScriptingError = 256, + ScriptingWarning = 512, + ScriptingLog = 1024, + ScriptCompileError = 2048, + ScriptCompileWarning = 4096, + StickyError = 8192, + MayIgnoreLineNumber = 16384, + ReportBug = 32768, + DisplayPreviousErrorInStatusBar = 65536, + ScriptingException = 131072, + DontExtractStacktrace = 262144, + ShouldClearOnPlay = 524288, + GraphCompileError = 1048576 + } + private enum ConsoleFlags + { + Collapse = 1, + ClearOnPlay, + ErrorPause = 4, + Verbose = 8, + StopForAssert = 16, + StopForError = 32, + Autoscroll = 64, + LogLevelLog = 128, + LogLevelWarning = 256, + LogLevelError = 512 + } + private const int m_RowHeight = 32; + private ListViewState m_ListView; + private string m_ActiveText = string.Empty; + private int m_ActiveInstanceID; + private bool m_DevBuild; + private Vector2 m_TextScroll = Vector2.zero; + private SplitterState spl = new SplitterState(new float[] + { + 70f, + 30f + }, new int[] + { + 32, + 32 + }, null); + private static bool ms_LoadedIcons; + internal static Texture2D iconInfo; + internal static Texture2D iconWarn; + internal static Texture2D iconError; + internal static Texture2D iconInfoSmall; + internal static Texture2D iconWarnSmall; + internal static Texture2D iconErrorSmall; + internal static Texture2D iconInfoMono; + internal static Texture2D iconWarnMono; + internal static Texture2D iconErrorMono; + private int ms_LVHeight; + private static ConsoleWindow ms_ConsoleWindow; + public ConsoleWindow() + { + base.position = new Rect(200f, 200f, 800f, 400f); + this.m_ListView = new ListViewState(0, 32); + } + private static void ShowConsoleWindowImmediate() + { + ConsoleWindow.ShowConsoleWindow(true); + } + public static void ShowConsoleWindow(bool immediate) + { + if (ConsoleWindow.ms_ConsoleWindow == null) + { + ConsoleWindow.ms_ConsoleWindow = ScriptableObject.CreateInstance(); + ConsoleWindow.ms_ConsoleWindow.Show(immediate); + ConsoleWindow.ms_ConsoleWindow.Focus(); + } + else + { + ConsoleWindow.ms_ConsoleWindow.Show(immediate); + ConsoleWindow.ms_ConsoleWindow.Focus(); + } + } + internal static void LoadIcons() + { + if (ConsoleWindow.ms_LoadedIcons) + { + return; + } + ConsoleWindow.ms_LoadedIcons = true; + ConsoleWindow.iconInfo = EditorGUIUtility.LoadIcon("console.infoicon"); + ConsoleWindow.iconWarn = EditorGUIUtility.LoadIcon("console.warnicon"); + ConsoleWindow.iconError = EditorGUIUtility.LoadIcon("console.erroricon"); + ConsoleWindow.iconInfoSmall = EditorGUIUtility.LoadIcon("console.infoicon.sml"); + ConsoleWindow.iconWarnSmall = EditorGUIUtility.LoadIcon("console.warnicon.sml"); + ConsoleWindow.iconErrorSmall = EditorGUIUtility.LoadIcon("console.erroricon.sml"); + ConsoleWindow.iconInfoMono = EditorGUIUtility.LoadIcon("console.infoicon.sml"); + ConsoleWindow.iconWarnMono = EditorGUIUtility.LoadIcon("console.warnicon.inactive.sml"); + ConsoleWindow.iconErrorMono = EditorGUIUtility.LoadIcon("console.erroricon.inactive.sml"); + ConsoleWindow.Constants.Init(); + } + public static void LogChanged() + { + if (ConsoleWindow.ms_ConsoleWindow == null) + { + return; + } + ConsoleWindow.ms_ConsoleWindow.DoLogChanged(); + } + public void DoLogChanged() + { + ConsoleWindow.ms_ConsoleWindow.Repaint(); + } + private void OnEnable() + { + ConsoleWindow.ms_ConsoleWindow = this; + this.m_DevBuild = Unsupported.IsDeveloperBuild(); + } + private void OnDisable() + { + if (ConsoleWindow.ms_ConsoleWindow == this) + { + ConsoleWindow.ms_ConsoleWindow = null; + } + } + private static bool HasMode(int mode, ConsoleWindow.Mode modeToCheck) + { + return (mode & (int)modeToCheck) != 0; + } + private bool HasFlag(ConsoleWindow.ConsoleFlags flags) + { + return (LogEntries.consoleFlags & (int)flags) != 0; + } + private void SetFlag(ConsoleWindow.ConsoleFlags flags, bool val) + { + LogEntries.SetConsoleFlag((int)flags, val); + } + internal static Texture2D GetIconForErrorMode(int mode, bool large) + { + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)1050963)) + { + return (!large) ? ConsoleWindow.iconErrorSmall : ConsoleWindow.iconError; + } + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)4736)) + { + return (!large) ? ConsoleWindow.iconWarnSmall : ConsoleWindow.iconWarn; + } + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)1028)) + { + return (!large) ? ConsoleWindow.iconInfoSmall : ConsoleWindow.iconInfo; + } + return null; + } + internal static GUIStyle GetStyleForErrorMode(int mode) + { + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)1050963)) + { + return ConsoleWindow.Constants.ErrorStyle; + } + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)4736)) + { + return ConsoleWindow.Constants.WarningStyle; + } + return ConsoleWindow.Constants.LogStyle; + } + internal static GUIStyle GetStatusStyleForErrorMode(int mode) + { + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)1050963)) + { + return ConsoleWindow.Constants.StatusError; + } + if (ConsoleWindow.HasMode(mode, (ConsoleWindow.Mode)4736)) + { + return ConsoleWindow.Constants.StatusWarn; + } + return ConsoleWindow.Constants.StatusLog; + } + private static string ContextString(LogEntry entry) + { + StringBuilder stringBuilder = new StringBuilder(); + if (ConsoleWindow.HasMode(entry.mode, ConsoleWindow.Mode.Error)) + { + stringBuilder.Append("Error "); + } + else + { + if (ConsoleWindow.HasMode(entry.mode, ConsoleWindow.Mode.Log)) + { + stringBuilder.Append("Log "); + } + else + { + stringBuilder.Append("Assert "); + } + } + stringBuilder.Append("in file: "); + stringBuilder.Append(entry.file); + stringBuilder.Append(" at line: "); + stringBuilder.Append(entry.line); + if (entry.errorNum != 0) + { + stringBuilder.Append(" and errorNum: "); + stringBuilder.Append(entry.errorNum); + } + return stringBuilder.ToString(); + } + private static string GetFirstLine(string s) + { + int num = s.IndexOf("\n"); + return (num == -1) ? s : s.Substring(0, num); + } + private static string GetFirstTwoLines(string s) + { + int num = s.IndexOf("\n"); + if (num != -1) + { + num = s.IndexOf("\n", num + 1); + if (num != -1) + { + return s.Substring(0, num); + } + } + return s; + } + private void SetActiveEntry(LogEntry entry) + { + if (entry != null) + { + this.m_ActiveText = entry.condition; + if (this.m_ActiveInstanceID != entry.instanceID) + { + this.m_ActiveInstanceID = entry.instanceID; + if (entry.instanceID != 0) + { + EditorGUIUtility.PingObject(entry.instanceID); + } + } + } + else + { + this.m_ActiveText = string.Empty; + this.m_ActiveInstanceID = 0; + this.m_ListView.row = -1; + } + } + private static void ShowConsoleRow(int row) + { + ConsoleWindow.ShowConsoleWindow(false); + if (ConsoleWindow.ms_ConsoleWindow) + { + ConsoleWindow.ms_ConsoleWindow.m_ListView.row = row; + ConsoleWindow.ms_ConsoleWindow.m_ListView.selectionChanged = true; + ConsoleWindow.ms_ConsoleWindow.Repaint(); + } + } + private void OnGUI() + { + Event current = Event.current; + ConsoleWindow.LoadIcons(); + GUILayout.BeginHorizontal(ConsoleWindow.Constants.Toolbar, new GUILayoutOption[0]); + if (GUILayout.Button("Clear", ConsoleWindow.Constants.MiniButton, new GUILayoutOption[0])) + { + LogEntries.Clear(); + GUIUtility.keyboardControl = 0; + } + int count = LogEntries.GetCount(); + if (this.m_ListView.totalRows != count && this.m_ListView.scrollPos.y >= (float)(this.m_ListView.rowHeight * this.m_ListView.totalRows - this.ms_LVHeight)) + { + this.m_ListView.scrollPos.y = (float)(count * 32 - this.ms_LVHeight); + } + EditorGUILayout.Space(); + bool flag = this.HasFlag(ConsoleWindow.ConsoleFlags.Collapse); + this.SetFlag(ConsoleWindow.ConsoleFlags.Collapse, GUILayout.Toggle(flag, "Collapse", ConsoleWindow.Constants.MiniButtonLeft, new GUILayoutOption[0])); + bool flag2 = flag != this.HasFlag(ConsoleWindow.ConsoleFlags.Collapse); + if (flag2) + { + this.m_ListView.row = -1; + this.m_ListView.scrollPos.y = (float)(LogEntries.GetCount() * 32); + } + this.SetFlag(ConsoleWindow.ConsoleFlags.ClearOnPlay, GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.ClearOnPlay), "Clear on Play", ConsoleWindow.Constants.MiniButtonMiddle, new GUILayoutOption[0])); + this.SetFlag(ConsoleWindow.ConsoleFlags.ErrorPause, GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.ErrorPause), "Error Pause", ConsoleWindow.Constants.MiniButtonRight, new GUILayoutOption[0])); + EditorGUILayout.Space(); + if (this.m_DevBuild) + { + GUILayout.FlexibleSpace(); + this.SetFlag(ConsoleWindow.ConsoleFlags.StopForAssert, GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.StopForAssert), "Stop for Assert", ConsoleWindow.Constants.MiniButtonLeft, new GUILayoutOption[0])); + this.SetFlag(ConsoleWindow.ConsoleFlags.StopForError, GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.StopForError), "Stop for Error", ConsoleWindow.Constants.MiniButtonRight, new GUILayoutOption[0])); + } + GUILayout.FlexibleSpace(); + int num = 0; + int num2 = 0; + int num3 = 0; + LogEntries.GetCountsByType(ref num, ref num2, ref num3); + bool val = GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.LogLevelLog), new GUIContent((num3 > 999) ? "999+" : num3.ToString(), (num3 <= 0) ? ConsoleWindow.iconInfoMono : ConsoleWindow.iconInfoSmall), ConsoleWindow.Constants.MiniButtonRight, new GUILayoutOption[0]); + bool val2 = GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.LogLevelWarning), new GUIContent((num2 > 999) ? "999+" : num2.ToString(), (num2 <= 0) ? ConsoleWindow.iconWarnMono : ConsoleWindow.iconWarnSmall), ConsoleWindow.Constants.MiniButtonMiddle, new GUILayoutOption[0]); + bool val3 = GUILayout.Toggle(this.HasFlag(ConsoleWindow.ConsoleFlags.LogLevelError), new GUIContent((num > 999) ? "999+" : num.ToString(), (num <= 0) ? ConsoleWindow.iconErrorMono : ConsoleWindow.iconErrorSmall), ConsoleWindow.Constants.MiniButtonLeft, new GUILayoutOption[0]); + this.SetFlag(ConsoleWindow.ConsoleFlags.LogLevelLog, val); + this.SetFlag(ConsoleWindow.ConsoleFlags.LogLevelWarning, val2); + this.SetFlag(ConsoleWindow.ConsoleFlags.LogLevelError, val3); + GUILayout.EndHorizontal(); + this.m_ListView.totalRows = LogEntries.StartGettingEntries(); + SplitterGUILayout.BeginVerticalSplit(this.spl, new GUILayoutOption[0]); + EditorGUIUtility.SetIconSize(new Vector2(32f, 32f)); + GUIContent gUIContent = new GUIContent(); + int controlID = GUIUtility.GetControlID(FocusType.Native); + try + { + bool flag3 = false; + bool flag4 = this.HasFlag(ConsoleWindow.ConsoleFlags.Collapse); + foreach (ListViewElement listViewElement in ListViewGUI.ListView(this.m_ListView, ConsoleWindow.Constants.Box, new GUILayoutOption[0])) + { + if (current.type == EventType.MouseDown && current.button == 0 && listViewElement.position.Contains(current.mousePosition)) + { + if (current.clickCount == 2) + { + LogEntries.OpenEntryFile(this.m_ListView.row); + } + flag3 = true; + } + if (current.type == EventType.Repaint) + { + int mode = 0; + string text = null; + LogEntries.GetFirstTwoLinesEntryTextAndModeInternal(listViewElement.row, ref mode, ref text); + GUIStyle gUIStyle = (listViewElement.row % 2 != 0) ? ConsoleWindow.Constants.EvenBackground : ConsoleWindow.Constants.OddBackground; + gUIStyle.Draw(listViewElement.position, false, false, this.m_ListView.row == listViewElement.row, false); + gUIContent.text = text; + GUIStyle styleForErrorMode = ConsoleWindow.GetStyleForErrorMode(mode); + styleForErrorMode.Draw(listViewElement.position, gUIContent, controlID, this.m_ListView.row == listViewElement.row); + if (flag4) + { + Rect position = listViewElement.position; + gUIContent.text = LogEntries.GetEntryCount(listViewElement.row).ToString(CultureInfo.InvariantCulture); + Vector2 vector = ConsoleWindow.Constants.CountBadge.CalcSize(gUIContent); + position.xMin = position.xMax - vector.x; + position.yMin += (position.yMax - position.yMin - vector.y) * 0.5f; + position.x -= 5f; + GUI.Label(position, gUIContent, ConsoleWindow.Constants.CountBadge); + } + } + } + if (flag3 && this.m_ListView.scrollPos.y >= (float)(this.m_ListView.rowHeight * this.m_ListView.totalRows - this.ms_LVHeight)) + { + this.m_ListView.scrollPos.y = (float)(this.m_ListView.rowHeight * this.m_ListView.totalRows - this.ms_LVHeight - 1); + } + if (this.m_ListView.totalRows == 0 || this.m_ListView.row >= this.m_ListView.totalRows || this.m_ListView.row < 0) + { + if (this.m_ActiveText.Length != 0) + { + this.SetActiveEntry(null); + } + } + else + { + LogEntry logEntry = new LogEntry(); + LogEntries.GetEntryInternal(this.m_ListView.row, logEntry); + this.SetActiveEntry(logEntry); + LogEntries.GetEntryInternal(this.m_ListView.row, logEntry); + if (this.m_ListView.selectionChanged || !this.m_ActiveText.Equals(logEntry.condition)) + { + this.SetActiveEntry(logEntry); + } + } + if (GUIUtility.keyboardControl == this.m_ListView.ID && current.type == EventType.KeyDown && current.keyCode == KeyCode.Return && this.m_ListView.row != 0) + { + LogEntries.OpenEntryFile(this.m_ListView.row); + Event.current.Use(); + } + if (current.type != EventType.Layout && ListViewGUI.ilvState.rectHeight != 1) + { + this.ms_LVHeight = ListViewGUI.ilvState.rectHeight; + } + } + finally + { + LogEntries.EndGettingEntries(); + EditorGUIUtility.SetIconSize(Vector2.zero); + } + this.m_TextScroll = GUILayout.BeginScrollView(this.m_TextScroll, ConsoleWindow.Constants.Box); + float minHeight = ConsoleWindow.Constants.MessageStyle.CalcHeight(GUIContent.Temp(this.m_ActiveText), base.position.width); + EditorGUILayout.SelectableLabel(this.m_ActiveText, ConsoleWindow.Constants.MessageStyle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true), + GUILayout.MinHeight(minHeight) + }); + GUILayout.EndScrollView(); + SplitterGUILayout.EndVerticalSplit(); + if ((current.type == EventType.ValidateCommand || current.type == EventType.ExecuteCommand) && current.commandName == "Copy" && this.m_ActiveText != string.Empty) + { + if (current.type == EventType.ExecuteCommand) + { + EditorGUIUtility.systemCopyBuffer = this.m_ActiveText; + } + current.Use(); + } + } + public void AddItemsToMenu(GenericMenu menu) + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + menu.AddItem(new GUIContent("Open Player Log"), false, new GenericMenu.MenuFunction(InternalEditorUtility.OpenPlayerConsole)); + } + menu.AddItem(new GUIContent("Open Editor Log"), false, new GenericMenu.MenuFunction(InternalEditorUtility.OpenEditorConsole)); + } + } +} diff --git a/UnityEditor/UnityEditor/ContainerWindow.cs b/UnityEditor/UnityEditor/ContainerWindow.cs new file mode 100644 index 00000000..422f0ffd --- /dev/null +++ b/UnityEditor/UnityEditor/ContainerWindow.cs @@ -0,0 +1,656 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + internal sealed class ContainerWindow : ScriptableObject + { + private const float kButtonWidth = 13f; + private const float kButtonHeight = 13f; + private const float kButtonSpacing = 3f; + private const float kButtonTop = 0f; + private const float kBorderSize = 4f; + private const float kTitleHeight = 24f; + private const float kMacCornerSize = 16f; + [SerializeField] + private MonoReloadableIntPtr m_WindowPtr; + [SerializeField] + private Rect m_PixelRect; + [SerializeField] + private int m_ShowMode; + [SerializeField] + private string m_Title = string.Empty; + [SerializeField] + private View m_MainView; + [SerializeField] + private Vector2 m_MinSize = new Vector2(120f, 80f); + [SerializeField] + private Vector2 m_MaxSize = new Vector2(4000f, 4000f); + internal bool m_DontSaveToLayout; + private static List s_AllWindows = new List(); + internal static GUIStyle s_ButtonClose; + internal static GUIStyle s_ButtonMin; + internal static GUIStyle s_ButtonMax; + internal static GUIStyle s_ButtonCloseActive; + internal static GUIStyle s_ButtonMinActive; + internal static GUIStyle s_ButtonMaxActive; + internal static GUIStyle s_ButtonInactive; + internal static GUIStyle s_WindowResize; + [SerializeField] + private List[] edges = new List[9]; + [SerializeField] + private SnapEdge m_Left; + [SerializeField] + private SnapEdge m_Right; + [SerializeField] + private SnapEdge m_Top; + [SerializeField] + private SnapEdge m_Bottom; + private static Vector2 s_DragStartMousePos; + private static Vector2 s_LastDragMousePos; + internal ShowMode showMode + { + get + { + return (ShowMode)this.m_ShowMode; + } + } + public extern bool maximized + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Rect position + { + get + { + Rect result; + this.INTERNAL_get_position(out result); + return result; + } + set + { + this.INTERNAL_set_position(ref value); + } + } + public string title + { + get + { + return this.m_Title; + } + set + { + this.m_Title = value; + this.Internal_SetTitle(value); + } + } + public static ContainerWindow[] windows + { + get + { + ContainerWindow.s_AllWindows.Clear(); + ContainerWindow.GetOrderedWindowList(); + return ContainerWindow.s_AllWindows.ToArray(); + } + } + public View mainView + { + get + { + return this.m_MainView; + } + set + { + this.m_MainView = value; + this.m_MainView.SetWindowRecurse(this); + this.m_MainView.position = new Rect(0f, 0f, this.position.width, this.position.height); + this.m_MinSize = value.minSize; + this.m_MaxSize = value.maxSize; + } + } + internal static bool macEditor + { + get + { + return Application.platform == RuntimePlatform.OSXEditor; + } + } + public ContainerWindow() + { + base.hideFlags = HideFlags.DontSave; + this.m_PixelRect = new Rect(0f, 0f, 400f, 300f); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAlpha(float alpha); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetInvisible(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetIsDragging(bool dragging); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsZoomed(); + internal void ShowPopup() + { + this.m_ShowMode = 1; + this.Internal_Show(this.m_PixelRect, this.m_ShowMode, this.m_MinSize, this.m_MaxSize); + if (this.m_MainView) + { + this.m_MainView.SetWindowRecurse(this); + } + this.Internal_SetTitle(this.m_Title); + this.Save(); + this.Internal_BringLiveAfterCreation(false, false); + } + public void Show(ShowMode showMode, bool loadPosition, bool displayImmediately) + { + if (showMode == ShowMode.AuxWindow) + { + showMode = ShowMode.Utility; + } + if (showMode == ShowMode.Utility || showMode == ShowMode.PopupMenu) + { + this.m_DontSaveToLayout = true; + } + this.m_ShowMode = (int)showMode; + if (showMode != ShowMode.PopupMenu) + { + this.Load(loadPosition); + } + this.Internal_Show(this.m_PixelRect, this.m_ShowMode, this.m_MinSize, this.m_MaxSize); + if (this.m_MainView) + { + this.m_MainView.SetWindowRecurse(this); + } + this.Internal_SetTitle(this.m_Title); + this.Internal_BringLiveAfterCreation(displayImmediately, true); + if (this == null) + { + return; + } + this.position = this.FitWindowRectToScreen(this.m_PixelRect, false, false); + this.mainView.position = new Rect(0f, 0f, this.m_PixelRect.width, this.m_PixelRect.height); + this.mainView.Reflow(); + this.Save(); + } + public void OnEnable() + { + if (this.m_MainView) + { + this.m_MainView.Initialize(this); + } + } + public void SetMinMaxSizes(Vector2 min, Vector2 max) + { + this.m_MinSize = min; + this.m_MaxSize = max; + Rect position = this.position; + Rect position2 = position; + position2.width = Mathf.Clamp(position.width, min.x, max.x); + position2.height = Mathf.Clamp(position.height, min.y, max.y); + if (position2.width != position.width || position2.height != position.height) + { + this.position = position2; + } + this.Internal_SetMinMaxSizes(min, max); + } + private void Internal_SetMinMaxSizes(Vector2 minSize, Vector2 maxSize) + { + ContainerWindow.INTERNAL_CALL_Internal_SetMinMaxSizes(this, ref minSize, ref maxSize); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetMinMaxSizes(ContainerWindow self, ref Vector2 minSize, ref Vector2 maxSize); + private void Internal_Show(Rect r, int showMode, Vector2 minSize, Vector2 maxSize) + { + ContainerWindow.INTERNAL_CALL_Internal_Show(this, ref r, showMode, ref minSize, ref maxSize); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Show(ContainerWindow self, ref Rect r, int showMode, ref Vector2 minSize, ref Vector2 maxSize); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_BringLiveAfterCreation(bool displayImmediately, bool setFocus); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetFreezeDisplay(bool freeze); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DisplayAllViews(); + internal void InternalCloseWindow() + { + this.Save(); + if (this.m_MainView) + { + if (this.m_MainView is GUIView) + { + ((GUIView)this.m_MainView).RemoveFromAuxWindowList(); + } + UnityEngine.Object.DestroyImmediate(this.m_MainView, true); + this.m_MainView = null; + } + UnityEngine.Object.DestroyImmediate(this, true); + } + public void Close() + { + this.Save(); + this.InternalClose(); + UnityEngine.Object.DestroyImmediate(this, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Minimize(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ToggleMaximize(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void MoveInFrontOf(ContainerWindow other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void MoveBehindOf(ContainerWindow other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InternalClose(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void OnDestroy(); + internal bool IsNotDocked() + { + return this.m_ShowMode == 2 || this.m_ShowMode == 5 || (this.mainView as SplitView != null && this.mainView.children.Length == 1 && this.mainView.children.Length == 1 && this.mainView.children[0] is DockArea && ((DockArea)this.mainView.children[0]).m_Panes.Count == 1); + } + private string NotDockedWindowID() + { + if (this.IsNotDocked()) + { + HostView hostView = this.mainView as HostView; + if (hostView == null) + { + if (!(this.mainView is SplitView)) + { + return this.mainView.GetType().ToString(); + } + hostView = (HostView)this.mainView.children[0]; + } + return (this.m_ShowMode != 2 && this.m_ShowMode != 5) ? ((DockArea)this.mainView.children[0]).m_Panes[0].GetType().ToString() : hostView.actualView.GetType().ToString(); + } + return null; + } + public void Save() + { + if (this.m_ShowMode != 4 && this.IsNotDocked() && !this.IsZoomed()) + { + string str = this.NotDockedWindowID(); + EditorPrefs.SetFloat(str + "x", this.m_PixelRect.x); + EditorPrefs.SetFloat(str + "y", this.m_PixelRect.y); + EditorPrefs.SetFloat(str + "w", this.m_PixelRect.width); + EditorPrefs.SetFloat(str + "h", this.m_PixelRect.height); + } + } + private void Load(bool loadPosition) + { + if (this.m_ShowMode != 4 && this.IsNotDocked()) + { + string str = this.NotDockedWindowID(); + Rect pixelRect = this.m_PixelRect; + if (loadPosition) + { + pixelRect.x = EditorPrefs.GetFloat(str + "x", this.m_PixelRect.x); + pixelRect.y = EditorPrefs.GetFloat(str + "y", this.m_PixelRect.y); + } + pixelRect.width = Mathf.Max(EditorPrefs.GetFloat(str + "w", this.m_PixelRect.width), this.m_MinSize.x); + pixelRect.height = Mathf.Max(EditorPrefs.GetFloat(str + "h", this.m_PixelRect.height), this.m_MinSize.y); + this.m_PixelRect = pixelRect; + } + } + internal void OnResize() + { + if (this.mainView == null) + { + return; + } + this.mainView.position = new Rect(0f, 0f, this.position.width, this.position.height); + this.mainView.Reflow(); + this.Save(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_position(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_position(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTitle(string title); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void GetOrderedWindowList(); + internal void AddToWindowList() + { + ContainerWindow.s_AllWindows.Add(this); + } + public Vector2 WindowToScreenPoint(Vector2 windowPoint) + { + Vector2 b; + this.Internal_GetTopleftScreenPosition(out b); + return windowPoint + b; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_GetTopleftScreenPosition(out Vector2 pos); + internal string DebugHierarchy() + { + return this.mainView.DebugHierarchy(0); + } + internal Rect GetDropDownRect(Rect buttonRect, Vector2 minSize, Vector2 maxSize, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + return PopupLocationHelper.GetDropDownRect(buttonRect, minSize, maxSize, this, locationPriorityOrder); + } + internal Rect GetDropDownRect(Rect buttonRect, Vector2 minSize, Vector2 maxSize) + { + return PopupLocationHelper.GetDropDownRect(buttonRect, minSize, maxSize, this); + } + internal Rect FitPopupWindowRectToScreen(Rect rect, float minimumHeight) + { + float num = 0f; + if (Application.platform == RuntimePlatform.OSXEditor) + { + num = 10f; + } + float b = minimumHeight + num; + Rect rect2 = rect; + rect2.height = Mathf.Min(rect2.height, 900f); + rect2.height += num; + rect2 = this.FitWindowRectToScreen(rect2, true, true); + float num2 = Mathf.Max(rect2.yMax - rect.y, b); + rect2.y = rect2.yMax - num2; + rect2.height = num2 - num; + return rect2; + } + internal Rect FitWindowRectToScreen(Rect r, bool forceCompletelyVisible, bool useMouseScreen) + { + return ContainerWindow.INTERNAL_CALL_FitWindowRectToScreen(this, ref r, forceCompletelyVisible, useMouseScreen); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_FitWindowRectToScreen(ContainerWindow self, ref Rect r, bool forceCompletelyVisible, bool useMouseScreen); + internal static Rect FitRectToScreen(Rect defaultRect, bool forceCompletelyVisible, bool useMouseScreen) + { + return ContainerWindow.INTERNAL_CALL_FitRectToScreen(ref defaultRect, forceCompletelyVisible, useMouseScreen); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_FitRectToScreen(ref Rect defaultRect, bool forceCompletelyVisible, bool useMouseScreen); + private static void InitIcons() + { + if (ContainerWindow.macEditor) + { + ContainerWindow.s_ButtonClose = "WinBtnCloseMac"; + ContainerWindow.s_ButtonMin = "WinBtnMinMac"; + ContainerWindow.s_ButtonMax = "WinBtnMaxMac"; + ContainerWindow.s_ButtonCloseActive = "WinBtnCloseActiveMac"; + ContainerWindow.s_ButtonMinActive = "WinBtnMinActiveMac"; + ContainerWindow.s_ButtonMaxActive = "WinBtnMaxActiveMac"; + ContainerWindow.s_ButtonInactive = "WinBtnInactiveMac"; + ContainerWindow.s_WindowResize = "WindowResizeMac"; + } + else + { + ContainerWindow.s_ButtonClose = "WinBtnCloseWin"; + ContainerWindow.s_ButtonMin = "WinBtnMinWin"; + ContainerWindow.s_ButtonMax = "WinBtnMaxWin"; + } + } + public void HandleEdgesEnd(Rect windowPosition) + { + bool flag = Mathf.Abs(windowPosition.xMax - this.position.width) < 2f; + bool flag2 = Mathf.Abs(windowPosition.yMax - this.position.height) < 2f; + if (Event.current.type == EventType.Repaint && ContainerWindow.macEditor && (this.m_MinSize == Vector2.zero || this.m_MinSize != this.m_MaxSize) && flag2 && flag) + { + if (ContainerWindow.s_WindowResize == null) + { + ContainerWindow.InitIcons(); + } + ContainerWindow.s_WindowResize.Draw(new Rect(windowPosition.width - ContainerWindow.s_WindowResize.fixedWidth, windowPosition.height - ContainerWindow.s_WindowResize.fixedHeight, ContainerWindow.s_WindowResize.fixedWidth, ContainerWindow.s_WindowResize.fixedHeight), false, false, false, false); + } + } + public void HandleEdgesStart(Rect windowPosition) + { + bool left = windowPosition.x == 0f; + bool flag = windowPosition.y == 0f; + bool flag2 = Mathf.Abs(windowPosition.xMax - this.position.width) < 2f; + bool bottom = Mathf.Abs(windowPosition.yMax - this.position.height) < 2f; + ContainerWindow.InitIcons(); + if (ContainerWindow.macEditor) + { + if (flag2 && flag && this.showMode != ShowMode.Utility && this.showMode != ShowMode.PopupMenu) + { + GUIView focusedView = GUIView.focusedView; + GUIStyle style; + GUIStyle style2; + GUIStyle style3; + if (focusedView && focusedView.window == this) + { + style = ContainerWindow.s_ButtonClose; + style2 = ContainerWindow.s_ButtonMin; + style3 = ContainerWindow.s_ButtonMax; + } + else + { + style2 = (style = (style3 = ContainerWindow.s_ButtonInactive)); + } + if (GUI.Button(new Rect(windowPosition.width - 13f - 4f, 0f, 13f, 13f), GUIContent.none, style)) + { + this.Close(); + } + if (GUI.Button(new Rect(windowPosition.width - 26f - 3f - 4f, 0f, 13f, 13f), GUIContent.none, style2)) + { + this.Minimize(); + GUIUtility.ExitGUI(); + } + if (GUI.Button(new Rect(windowPosition.width - 39f - 6f - 4f, 0f, 13f, 13f), GUIContent.none, style3)) + { + this.ToggleMaximize(); + } + } + this.DragWindowEdgesMac(left, flag, flag2, bottom, windowPosition); + } + else + { + if (flag2 && flag && this.showMode != ShowMode.Utility && this.showMode != ShowMode.PopupMenu) + { + if (GUI.Button(new Rect(windowPosition.width - 13f - 4f, 0f, 13f, 13f), GUIContent.none, ContainerWindow.s_ButtonClose)) + { + this.Close(); + } + if (GUI.Button(new Rect(windowPosition.width - 26f - 3f - 4f, 0f, 13f, 13f), GUIContent.none, ContainerWindow.s_ButtonMax)) + { + this.ToggleMaximize(); + } + } + if (!this.maximized) + { + this.DragWindowEdgesWin(left, flag, flag2, bottom, windowPosition); + } + } + } + private void SetupWindowEdges() + { + Rect position = this.position; + if (this.m_Left == null) + { + this.m_Left = new SnapEdge(this, SnapEdge.EdgeDir.Left, position.xMin, position.yMin, position.yMax); + this.m_Right = new SnapEdge(this, SnapEdge.EdgeDir.Right, position.xMax, position.yMin, position.yMax); + this.m_Top = new SnapEdge(this, SnapEdge.EdgeDir.Up, position.yMin, position.xMin, position.xMax); + this.m_Bottom = new SnapEdge(this, SnapEdge.EdgeDir.Down, position.yMax, position.xMin, position.xMax); + for (int i = 0; i < 9; i++) + { + this.edges[i] = new List(); + } + this.edges[0].Add(this.m_Top); + this.edges[0].Add(this.m_Left); + this.edges[1].Add(this.m_Top); + this.edges[2].Add(this.m_Top); + this.edges[2].Add(this.m_Right); + this.edges[3].Add(this.m_Left); + this.edges[4].Add(this.m_Left); + this.edges[4].Add(this.m_Right); + this.edges[4].Add(this.m_Top); + this.edges[4].Add(this.m_Bottom); + this.edges[5].Add(this.m_Right); + this.edges[6].Add(this.m_Bottom); + this.edges[6].Add(this.m_Left); + this.edges[7].Add(this.m_Bottom); + this.edges[8].Add(this.m_Bottom); + this.edges[8].Add(this.m_Right); + } + this.m_Left.pos = position.xMin; + this.m_Left.start = position.yMin; + this.m_Left.end = position.yMax; + this.m_Right.pos = position.xMax; + this.m_Right.start = position.yMin; + this.m_Right.end = position.yMax; + this.m_Top.pos = position.yMin; + this.m_Top.start = position.xMin; + this.m_Top.end = position.xMax; + this.m_Bottom.pos = position.yMax; + this.m_Bottom.start = position.xMin; + this.m_Bottom.end = position.xMax; + } + private void DragWindowEdgesMac(bool left, bool top, bool right, bool bottom, Rect windowPosition) + { + this.SetupWindowEdges(); + Rect position = this.position; + GUI.changed = false; + int changedDirs = 0; + if (top && this.showMode != ShowMode.Utility && this.showMode != ShowMode.PopupMenu) + { + this.DragEdges(new Rect(0f, 0f, windowPosition.width, 24f), this.edges[4], new Vector2(position.xMin, position.yMin), true, true, MouseCursor.Arrow, ref changedDirs, false); + } + if (bottom && right) + { + this.DragEdges(new Rect(windowPosition.width - 16f, windowPosition.height - 16f, 16f, 16f), this.edges[8], new Vector2(position.xMin, position.yMin), true, true, MouseCursor.Arrow, ref changedDirs, false); + } + if (GUI.changed) + { + this.ClampEdgeSizes(changedDirs); + Rect rect = new Rect(this.m_Left.pos, this.m_Top.pos, this.m_Right.pos - this.m_Left.pos, this.m_Bottom.pos - this.m_Top.pos); + rect = this.FitWindowRectToScreen(rect, false, false); + this.position = rect; + } + } + private void DragWindowEdgesWin(bool left, bool top, bool right, bool bottom, Rect windowPosition) + { + if (top && this.showMode != ShowMode.Utility && this.showMode != ShowMode.PopupMenu) + { + this.SetupWindowEdges(); + GUI.changed = false; + int changedDirs = 0; + Rect position = this.position; + this.DragEdges(new Rect(0f, 0f, windowPosition.width, 24f), this.edges[4], new Vector2(position.xMin, position.yMin), true, true, MouseCursor.Arrow, ref changedDirs, true); + if (GUI.changed) + { + this.ClampEdgeSizes(changedDirs); + this.position = new Rect(this.m_Left.pos, this.m_Top.pos, this.m_Right.pos - this.m_Left.pos, this.m_Bottom.pos - this.m_Top.pos); + } + } + } + private void ClampEdgeSizes(int changedDirs) + { + Vector2 minSize = this.m_MinSize; + Vector2 maxSize = this.m_MaxSize; + float num = this.m_Right.pos - this.m_Left.pos; + float num2 = this.m_Bottom.pos - this.m_Top.pos; + float num3 = Mathf.Clamp(num, minSize.x, maxSize.x); + float num4 = Mathf.Clamp(num2, minSize.y, maxSize.y); + if (num != num3) + { + if ((changedDirs & 1) != 0) + { + this.m_Left.pos = this.m_Right.pos - num3; + } + else + { + this.m_Right.pos = this.m_Left.pos + num3; + } + } + if (num2 != num4) + { + if ((changedDirs & 8) != 0) + { + this.m_Top.pos = this.m_Bottom.pos - num4; + } + else + { + this.m_Bottom.pos = this.m_Top.pos + num4; + } + } + } + private void DragEdges(Rect position, IEnumerable edges, Vector2 windowPosition, bool allowHorizontal, bool allowVertical, MouseCursor cursor, ref int changedEdges, bool windowMove) + { + int controlID = GUIUtility.GetControlID(FocusType.Passive); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && GUIUtility.hotControl == 0 && current.button == 0) + { + GUIUtility.hotControl = controlID; + this.SetIsDragging(true); + Event.current.Use(); + ContainerWindow.s_LastDragMousePos = GUIUtility.GUIToScreenPoint(current.mousePosition); + ContainerWindow.s_DragStartMousePos = ContainerWindow.s_LastDragMousePos; + foreach (SnapEdge current2 in edges) + { + current2.startDragPos = current2.pos; + current2.startDragStart = current2.start; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + this.SetIsDragging(false); + Event.current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 a = GUIUtility.GUIToScreenPoint(current.mousePosition); + Vector2 offset = a - ContainerWindow.s_LastDragMousePos; + ContainerWindow.s_LastDragMousePos = a; + if (!windowMove) + { + offset = a - ContainerWindow.s_DragStartMousePos; + } + if (!allowHorizontal) + { + offset.x = 0f; + } + if (!allowVertical) + { + offset.y = 0f; + } + GUI.changed = true; + foreach (SnapEdge current3 in edges) + { + current3.ApplyOffset(offset, ref changedEdges, windowMove); + } + } + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(position, cursor); + break; + } + } + } +} diff --git a/UnityEditor/UnityEditor/CreateAssetUtility.cs b/UnityEditor/UnityEditor/CreateAssetUtility.cs new file mode 100644 index 00000000..136719ca --- /dev/null +++ b/UnityEditor/UnityEditor/CreateAssetUtility.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using UnityEditor.ProjectWindowCallback; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class CreateAssetUtility + { + [SerializeField] + private EndNameEditAction m_EndAction; + [SerializeField] + private int m_InstanceID; + [SerializeField] + private string m_Path = string.Empty; + [SerializeField] + private Texture2D m_Icon; + [SerializeField] + private string m_ResourceFile; + public int instanceID + { + get + { + return this.m_InstanceID; + } + } + public Texture2D icon + { + get + { + return this.m_Icon; + } + } + public string folder + { + get + { + return Path.GetDirectoryName(this.m_Path); + } + } + public string extension + { + get + { + return Path.GetExtension(this.m_Path); + } + } + public string originalName + { + get + { + return Path.GetFileNameWithoutExtension(this.m_Path); + } + } + public EndNameEditAction endAction + { + get + { + return this.m_EndAction; + } + } + public void Clear() + { + this.m_EndAction = null; + this.m_InstanceID = 0; + this.m_Path = string.Empty; + this.m_Icon = null; + this.m_ResourceFile = string.Empty; + } + public void BeginNewAssetCreation(int instanceID, EndNameEditAction newAssetEndAction, string pathName, Texture2D icon, string newAssetResourceFile) + { + if (!pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) + { + pathName = AssetDatabase.GetUniquePathNameAtSelectedPath(pathName); + } + else + { + pathName = AssetDatabase.GenerateUniqueAssetPath(pathName); + } + this.m_InstanceID = instanceID; + this.m_Path = pathName; + this.m_Icon = icon; + this.m_EndAction = newAssetEndAction; + this.m_ResourceFile = newAssetResourceFile; + Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); + } + public void EndNewAssetCreation(string name) + { + string pathName = this.folder + "/" + name + this.extension; + EndNameEditAction endAction = this.m_EndAction; + int instanceID = this.m_InstanceID; + string resourceFile = this.m_ResourceFile; + this.Clear(); + ProjectWindowUtil.EndNameEditAction(endAction, instanceID, pathName, resourceFile); + } + public bool IsCreatingNewAsset() + { + return !string.IsNullOrEmpty(this.m_Path); + } + } +} diff --git a/UnityEditor/UnityEditor/CreateBuiltinWindows.cs b/UnityEditor/UnityEditor/CreateBuiltinWindows.cs new file mode 100644 index 00000000..f4d513a0 --- /dev/null +++ b/UnityEditor/UnityEditor/CreateBuiltinWindows.cs @@ -0,0 +1,70 @@ +using System; +using UnityEditor.Sprites; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class CreateBuiltinWindows + { + [MenuItem("Window/Scene %1", false, 2000)] + private static void ShowSceneView() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Game %2", false, 2001)] + private static void ShowGameView() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Inspector %3", false, 2002)] + private static void ShowInspector() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Hierarchy %4", false, 2003)] + private static void ShowNewHierarchy() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Project %5", false, 2004)] + private static void ShowProject() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Animation %6", false, 2006)] + private static void ShowAnimationWindow() + { + EditorWindow.GetWindow(); + } + private static void ShowProfilerWindow() + { + EditorWindow.GetWindow(); + } + private static void ShowVersionControl() + { + if (EditorSettings.externalVersionControl == ExternalVersionControl.AssetServer) + { + ASEditorBackend.DoAS(); + } + else + { + EditorWindow.GetWindow(); + } + } + [MenuItem("Window/Sprite Packer", false, 2014)] + private static void ShowSpritePackerWindow() + { + EditorWindow.GetWindow(); + } + [MenuItem("Window/Sprite Packer", true)] + private static bool ValidateShowSpritePackerWindow() + { + return Application.HasAdvancedLicense(); + } + [MenuItem("Window/Console %#c", false, 2200)] + private static void ShowConsole() + { + EditorWindow.GetWindow(); + } + } +} diff --git a/UnityEditor/UnityEditor/CrossCompileOptions.cs b/UnityEditor/UnityEditor/CrossCompileOptions.cs new file mode 100644 index 00000000..55d180ab --- /dev/null +++ b/UnityEditor/UnityEditor/CrossCompileOptions.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + [Flags] + internal enum CrossCompileOptions + { + Dynamic = 0, + FastICall = 1, + Static = 2, + Debugging = 4, + ExplicitNullChecks = 8, + LoadSymbols = 16 + } +} diff --git a/UnityEditor/UnityEditor/CubemapTextureInspector.cs b/UnityEditor/UnityEditor/CubemapTextureInspector.cs new file mode 100644 index 00000000..348d4578 --- /dev/null +++ b/UnityEditor/UnityEditor/CubemapTextureInspector.cs @@ -0,0 +1,234 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Cubemap))] + internal class CubemapTextureInspector : Editor + { + private const int kTextureSize = 64; + private static string[] kSizes = new string[] + { + "16", + "32", + "64", + "128", + "256", + "512", + "1024", + "2048" + }; + private static int[] kSizesValues = new int[] + { + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048 + }; + private PreviewRenderUtility m_PreviewUtility; + private Texture2D[] images; + private Material m_Material; + private Mesh m_Mesh; + public Vector2 previewDir = new Vector2(0f, 0f); + public void OnEnable() + { + this.InitTexturesFromCubemap(); + } + public void OnDisable() + { + if (this.images != null) + { + for (int i = 0; i < 6; i++) + { + if (!EditorUtility.IsPersistent(this.images[i])) + { + UnityEngine.Object.DestroyImmediate(this.images[i]); + } + } + } + this.images = null; + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + if (this.m_Material) + { + UnityEngine.Object.DestroyImmediate(this.m_Material.shader, true); + UnityEngine.Object.DestroyImmediate(this.m_Material, true); + this.m_Material = null; + } + } + private void InitTexturesFromCubemap() + { + Cubemap cubemap = this.target as Cubemap; + if (cubemap != null) + { + if (this.images == null) + { + this.images = new Texture2D[6]; + } + for (int i = 0; i < 6; i++) + { + if (this.images[i] && !EditorUtility.IsPersistent(this.images[i])) + { + UnityEngine.Object.DestroyImmediate(this.images[i]); + } + if (TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i)) + { + this.images[i] = TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i); + } + else + { + this.images[i] = new Texture2D(64, 64, TextureFormat.ARGB32, false); + this.images[i].hideFlags = HideFlags.HideAndDontSave; + TextureUtil.CopyCubemapFaceIntoTexture(cubemap, (CubemapFace)i, this.images[i]); + } + } + } + } + public override void OnInspectorGUI() + { + if (this.images == null) + { + this.InitTexturesFromCubemap(); + } + EditorGUIUtility.labelWidth = 50f; + Cubemap cubemap = this.target as Cubemap; + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Right\n(+X)", CubemapFace.PositiveX); + this.ShowFace("Left\n(-X)", CubemapFace.NegativeX); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Top\n(+Y)", CubemapFace.PositiveY); + this.ShowFace("Bottom\n(-Y)", CubemapFace.NegativeY); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Front\n(+Z)", CubemapFace.PositiveZ); + this.ShowFace("Back\n(-Z)", CubemapFace.NegativeZ); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + EditorGUIUtility.labelWidth = 0f; + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + int num = TextureUtil.GetGLWidth(cubemap); + num = EditorGUILayout.IntPopup("Face size", num, CubemapTextureInspector.kSizes, CubemapTextureInspector.kSizesValues, new GUILayoutOption[0]); + int num2 = TextureUtil.CountMipmaps(cubemap); + bool useMipmap = EditorGUILayout.Toggle("MipMaps", num2 > 1, new GUILayoutOption[0]); + bool flag = TextureUtil.GetLinearSampled(cubemap); + flag = EditorGUILayout.Toggle("Linear", flag, new GUILayoutOption[0]); + bool flag2 = TextureUtil.IsCubemapReadable(cubemap); + flag2 = EditorGUILayout.Toggle("Readable", flag2, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (TextureUtil.ReformatCubemap(ref cubemap, num, num, cubemap.format, useMipmap, flag)) + { + this.InitTexturesFromCubemap(); + } + TextureUtil.MarkCubemapReadable(cubemap, flag2); + cubemap.Apply(); + } + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + private void ShowFace(string label, CubemapFace face) + { + Cubemap cubemapRef = this.target as Cubemap; + GUI.changed = false; + Texture2D texture2D = (Texture2D)CubemapTextureInspector.ObjectField(label, this.images[(int)face], typeof(Texture2D), false, new GUILayoutOption[0]); + if (GUI.changed) + { + TextureUtil.CopyTextureIntoCubemapFace(texture2D, cubemapRef, face); + this.images[(int)face] = texture2D; + } + } + public static UnityEngine.Object ObjectField(string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect position = GUILayoutUtility.GetRect(EditorGUIUtility.labelWidth, 32f, EditorStyles.label, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUI.Label(position, label, EditorStyles.label); + position = GUILayoutUtility.GetAspectRect(1f, EditorStyles.objectField, new GUILayoutOption[] + { + GUILayout.Width(64f) + }); + UnityEngine.Object result = EditorGUI.ObjectField(position, obj, objType, allowSceneObjects); + GUILayout.EndHorizontal(); + return result; + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + this.m_Material = new Material("Shader \"Hidden/CubemapInspector\" {\n Properties {\n\t _MainTex (\"\", Cube) = \"\" { TexGen CubeReflect }\n }\n SubShader {\n Tags { \"ForceSupported\" = \"True\" } \n\t Pass { SetTexture[_MainTex] { matrix [_CubemapRotation] combine texture } }\n }\n Fallback Off\n }"); + this.m_Material.hideFlags = HideFlags.HideAndDontSave; + this.m_Material.shader.hideFlags = HideFlags.HideAndDontSave; + this.m_Material.mainTexture = (this.target as Texture); + } + if (this.m_Mesh == null) + { + GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + if (transform.name == "sphere") + { + this.m_Mesh = ((MeshFilter)transform.GetComponent(typeof(MeshFilter))).sharedMesh; + } + } + } + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + GUI.enabled = true; + this.InitPreview(); + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Cubemap preview requires\nrender texture support"); + } + return; + } + this.InitPreview(); + this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 3f; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + Quaternion quaternion = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); + this.m_Material.SetMatrix("_CubemapRotation", Matrix4x4.TRS(Vector3.zero, quaternion, Vector3.one)); + this.m_PreviewUtility.DrawMesh(this.m_Mesh, Vector3.zero, quaternion, this.m_Material, 0); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + } +} diff --git a/UnityEditor/UnityEditor/CurveEditor.cs b/UnityEditor/UnityEditor/CurveEditor.cs new file mode 100644 index 00000000..88de14e3 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveEditor.cs @@ -0,0 +1,2517 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class CurveEditor : TimeArea, CurveUpdater + { + private class SavedCurve + { + public class SavedKeyFrame : IComparable + { + public Keyframe key; + public CurveWrapper.SelectionMode selected; + public SavedKeyFrame(Keyframe key, CurveWrapper.SelectionMode selected) + { + this.key = key; + this.selected = selected; + } + public int CompareTo(object _other) + { + CurveEditor.SavedCurve.SavedKeyFrame savedKeyFrame = (CurveEditor.SavedCurve.SavedKeyFrame)_other; + float num = this.key.time - savedKeyFrame.key.time; + return (num >= 0f) ? ((num <= 0f) ? 0 : 1) : -1; + } + } + public int curveId; + public List keys; + } + private struct KeyFrameCopy + { + public float time; + public float value; + public float inTangent; + public float outTangent; + public int idx; + public int selectionIdx; + public KeyFrameCopy(int idx, int selectionIdx, Keyframe source) + { + this.idx = idx; + this.selectionIdx = selectionIdx; + this.time = source.time; + this.value = source.value; + this.inTangent = source.inTangent; + this.outTangent = source.outTangent; + } + } + internal new class Styles + { + public Texture2D pointIcon = EditorGUIUtility.LoadIcon("curvekeyframe"); + public Texture2D pointIconSelected = EditorGUIUtility.LoadIcon("curvekeyframeselected"); + public Texture2D pointIconSelectedOverlay = EditorGUIUtility.LoadIcon("curvekeyframeselectedoverlay"); + public Texture2D pointIconSemiSelectedOverlay = EditorGUIUtility.LoadIcon("curvekeyframesemiselectedoverlay"); + public GUIStyle none = new GUIStyle(); + public GUIStyle labelTickMarksY = "CurveEditorLabelTickMarks"; + public GUIStyle labelTickMarksX; + public GUIStyle selectionRect = "SelectionRect"; + public GUIStyle dragLabel = "ProfilerBadge"; + public GUIStyle axisLabelNumberField = new GUIStyle(EditorStyles.miniTextField); + public Styles() + { + this.axisLabelNumberField.alignment = TextAnchor.UpperRight; + this.labelTickMarksY.contentOffset = Vector2.zero; + this.labelTickMarksX = new GUIStyle(this.labelTickMarksY); + this.labelTickMarksX.clipping = TextClipping.Overflow; + } + } + internal enum PickMode + { + None, + Click, + Marquee + } + public delegate void CallbackFunction(); + private const float kMaxPickDistSqr = 64f; + private const float kExactPickDistSqr = 16f; + private const float kCurveTimeEpsilon = 1E-05f; + [NonSerialized] + private CurveWrapper[] m_AnimationCurves; + private static int s_SelectKeyHash = "SelectKeys".GetHashCode(); + public CurveEditor.CallbackFunction curvesUpdated; + private List m_DrawOrder = new List(); + internal TimeUpdater m_TimeUpdater; + internal Bounds m_DefaultBounds = new Bounds(new Vector3(0.5f, 0.5f, 0f), new Vector3(1f, 1f, 0f)); + private Color m_TangentColor = new Color(1f, 1f, 1f, 0.5f); + public float invSnap; + private CurveMenuManager m_MenuManager; + private static int s_TangentControlIDHash = "s_TangentControlIDHash".GetHashCode(); + private List m_Selection = new List(); + [NonSerialized] + private List m_DisplayedSelection; + private CurveSelection m_SelectedTangentPoint; + private List s_SelectionBackup; + private float s_TimeRangeSelectionStart; + private float s_TimeRangeSelectionEnd; + private bool s_TimeRangeSelectionActive; + private Bounds m_Bounds = new Bounds(Vector3.zero, Vector3.zero); + private List m_CurveBackups; + private CurveWrapper m_DraggingKey; + private Vector2 m_DraggedCoord; + private Vector2 m_MoveCoord; + private Vector2 m_PreviousDrawPointCenter; + internal CurveEditor.Styles ms_Styles; + private Vector2 s_StartMouseDragPosition; + private Vector2 s_EndMouseDragPosition; + private Vector2 s_StartKeyDragPosition; + private float s_StartClickedTime; + private CurveEditor.PickMode s_PickMode; + private string m_AxisLabelFormat = "n1"; + private CurveWrapper[] m_DraggingCurveOrRegion; + public bool hasSelection + { + get + { + return this.m_Selection.Count != 0; + } + } + public CurveWrapper[] animationCurves + { + get + { + if (this.m_AnimationCurves == null) + { + this.m_AnimationCurves = new CurveWrapper[0]; + } + return this.m_AnimationCurves; + } + set + { + this.m_AnimationCurves = value; + for (int i = 0; i < this.m_AnimationCurves.Length; i++) + { + this.m_AnimationCurves[i].listIndex = i; + } + this.SyncDrawOrder(); + this.SyncSelection(); + this.ValidateCurveList(); + } + } + public float activeTime + { + set + { + if (this.m_TimeUpdater != null) + { + this.m_TimeUpdater.UpdateTime(value); + } + } + } + public Color tangentColor + { + get + { + return this.m_TangentColor; + } + set + { + this.m_TangentColor = value; + } + } + internal List selectedCurves + { + get + { + return this.m_Selection; + } + } + public override Bounds drawingBounds + { + get + { + return this.m_Bounds; + } + } + public CurveEditor(Rect rect, CurveWrapper[] curves, bool minimalGUI) : base(minimalGUI) + { + base.rect = rect; + this.animationCurves = curves; + float[] tickModulos = new float[] + { + 1E-07f, + 5E-07f, + 1E-06f, + 5E-06f, + 1E-05f, + 5E-05f, + 0.0001f, + 0.0005f, + 0.001f, + 0.005f, + 0.01f, + 0.05f, + 0.1f, + 0.5f, + 1f, + 5f, + 10f, + 50f, + 100f, + 500f, + 1000f, + 5000f, + 10000f, + 50000f, + 100000f, + 500000f, + 1000000f, + 5000000f, + 1E+07f + }; + base.hTicks = new TickHandler(); + base.hTicks.SetTickModulos(tickModulos); + base.vTicks = new TickHandler(); + base.vTicks.SetTickModulos(tickModulos); + base.margin = 40f; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public bool GetTopMostCurveID(out int curveID) + { + if (this.m_DrawOrder.Count > 0) + { + curveID = this.m_DrawOrder[this.m_DrawOrder.Count - 1]; + return true; + } + curveID = -1; + return false; + } + private void SyncDrawOrder() + { + if (this.m_DrawOrder.Count == 0) + { + this.m_DrawOrder = ( + from cw in this.m_AnimationCurves + select cw.id).ToList(); + return; + } + List list = new List(this.m_AnimationCurves.Length); + for (int i = 0; i < this.m_DrawOrder.Count; i++) + { + int num = this.m_DrawOrder[i]; + for (int j = 0; j < this.m_AnimationCurves.Length; j++) + { + if (this.m_AnimationCurves[j].id == num) + { + list.Add(num); + break; + } + } + } + this.m_DrawOrder = list; + if (this.m_DrawOrder.Count == this.m_AnimationCurves.Length) + { + return; + } + for (int k = 0; k < this.m_AnimationCurves.Length; k++) + { + int id = this.m_AnimationCurves[k].id; + bool flag = false; + for (int l = 0; l < this.m_DrawOrder.Count; l++) + { + if (this.m_DrawOrder[l] == id) + { + flag = true; + break; + } + } + if (!flag) + { + this.m_DrawOrder.Add(id); + } + } + if (this.m_DrawOrder.Count != this.m_AnimationCurves.Length) + { + this.m_DrawOrder = ( + from cw in this.m_AnimationCurves + select cw.id).ToList(); + } + } + public CurveWrapper getCurveWrapperById(int id) + { + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (curveWrapper.id == id) + { + return curveWrapper; + } + } + return null; + } + private void ApplySettings() + { + base.hRangeLocked = base.settings.hRangeLocked; + base.vRangeLocked = base.settings.vRangeLocked; + base.hRangeMin = base.settings.hRangeMin; + base.hRangeMax = base.settings.hRangeMax; + base.vRangeMin = base.settings.vRangeMin; + base.vRangeMax = base.settings.vRangeMax; + base.scaleWithWindow = base.settings.scaleWithWindow; + base.hSlider = base.settings.hSlider; + base.vSlider = base.settings.vSlider; + this.RecalculateBounds(); + } + internal void ClearDisplayedSelection() + { + this.m_DisplayedSelection = null; + } + public void OnDisable() + { + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + private void UndoRedoPerformed() + { + this.SelectNone(); + } + private void ValidateCurveList() + { + for (int i = 0; i < this.m_AnimationCurves.Length; i++) + { + CurveWrapper curveWrapper = this.m_AnimationCurves[i]; + int regionId = curveWrapper.regionId; + if (regionId >= 0) + { + if (i == this.m_AnimationCurves.Length - 1) + { + Debug.LogError("Region has only one curve last! Regions should be added as two curves after each other with same regionId"); + return; + } + CurveWrapper curveWrapper2 = this.m_AnimationCurves[++i]; + int regionId2 = curveWrapper2.regionId; + if (regionId != regionId2) + { + Debug.LogError(string.Concat(new object[] + { + "Regions should be added as two curves after each other with same regionId: ", + regionId, + " != ", + regionId2 + })); + return; + } + } + } + if (this.m_DrawOrder.Count != this.m_AnimationCurves.Length) + { + Debug.LogError(string.Concat(new object[] + { + "DrawOrder and AnimationCurves mismatch: DrawOrder ", + this.m_DrawOrder.Count, + ", AnimationCurves: ", + this.m_AnimationCurves.Length + })); + return; + } + int count = this.m_DrawOrder.Count; + for (int j = 0; j < count; j++) + { + int id = this.m_DrawOrder[j]; + int regionId3 = this.getCurveWrapperById(id).regionId; + if (regionId3 >= 0) + { + if (j == count - 1) + { + Debug.LogError("Region has only one curve last! Regions should be added as two curves after each other with same regionId"); + return; + } + int id2 = this.m_DrawOrder[++j]; + int regionId4 = this.getCurveWrapperById(id2).regionId; + if (regionId3 != regionId4) + { + Debug.LogError(string.Concat(new object[] + { + "DrawOrder: Regions not added correctly after each other. RegionIds: ", + regionId3, + " , ", + regionId4 + })); + return; + } + } + } + } + private void UpdateTangentsFromSelection() + { + foreach (CurveSelection current in this.m_Selection) + { + CurveUtility.UpdateTangentsFromModeSurrounding(current.curveWrapper.curve, current.key); + } + } + private void SyncSelection() + { + this.Init(); + List list = new List(this.m_Selection.Count); + foreach (CurveSelection current in this.m_Selection) + { + CurveWrapper curveWrapper = current.curveWrapper; + if (curveWrapper != null && (!curveWrapper.hidden || curveWrapper.groupId != -1)) + { + curveWrapper.selected = CurveWrapper.SelectionMode.Selected; + list.Add(current); + } + } + this.m_Selection = list; + this.RecalculateBounds(); + } + public void RecalculateBounds() + { + this.m_Bounds = this.m_DefaultBounds; + if (this.animationCurves != null && (base.hRangeMin == float.NegativeInfinity || base.hRangeMax == float.PositiveInfinity || base.vRangeMin == float.NegativeInfinity || base.vRangeMax == float.PositiveInfinity)) + { + bool flag = false; + CurveWrapper[] animationCurves = this.animationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (!curveWrapper.hidden) + { + if (curveWrapper.curve.length != 0) + { + if (!flag) + { + this.m_Bounds = curveWrapper.renderer.GetBounds(); + flag = true; + } + else + { + this.m_Bounds.Encapsulate(curveWrapper.renderer.GetBounds()); + } + } + } + } + } + if (base.hRangeMin != float.NegativeInfinity) + { + this.m_Bounds.min = new Vector3(base.hRangeMin, this.m_Bounds.min.y, this.m_Bounds.min.z); + } + if (base.hRangeMax != float.PositiveInfinity) + { + this.m_Bounds.max = new Vector3(base.hRangeMax, this.m_Bounds.max.y, this.m_Bounds.max.z); + } + if (base.vRangeMin != float.NegativeInfinity) + { + this.m_Bounds.min = new Vector3(this.m_Bounds.min.x, base.vRangeMin, this.m_Bounds.min.z); + } + if (base.vRangeMax != float.PositiveInfinity) + { + this.m_Bounds.max = new Vector3(this.m_Bounds.max.y, base.vRangeMax, this.m_Bounds.max.z); + } + this.m_Bounds.size = new Vector3(Mathf.Max(this.m_Bounds.size.x, 0.1f), Mathf.Max(this.m_Bounds.size.y, 0.1f), 0f); + } + public void FrameSelected(bool horizontally, bool vertically) + { + Bounds bounds = default(Bounds); + if (!this.hasSelection) + { + bounds = this.drawingBounds; + if (bounds.size == Vector3.zero) + { + return; + } + } + else + { + bounds = new Bounds(new Vector2(this.m_Selection[0].keyframe.time, this.m_Selection[0].keyframe.value), Vector2.zero); + foreach (CurveSelection current in this.m_Selection) + { + bounds.Encapsulate(new Vector2(current.curve[current.key].time, current.curve[current.key].value)); + if (current.key - 1 >= 0) + { + bounds.Encapsulate(new Vector2(current.curve[current.key - 1].time, current.curve[current.key - 1].value)); + } + if (current.key + 1 < current.curve.length) + { + bounds.Encapsulate(new Vector2(current.curve[current.key + 1].time, current.curve[current.key + 1].value)); + } + } + bounds.size = new Vector3(Mathf.Max(bounds.size.x, 0.1f), Mathf.Max(bounds.size.y, 0.1f), 0f); + } + if (horizontally) + { + base.SetShownHRangeInsideMargins(bounds.min.x, bounds.max.x); + } + if (vertically) + { + base.SetShownVRangeInsideMargins(bounds.min.y, bounds.max.y); + } + } + public void UpdateCurves(List curveIds, string undoText) + { + foreach (int current in curveIds) + { + CurveWrapper curveFromID = this.GetCurveFromID(current); + curveFromID.changed = true; + } + if (this.curvesUpdated != null) + { + this.curvesUpdated(); + } + } + internal CurveWrapper GetCurveFromID(int curveID) + { + if (this.m_AnimationCurves == null) + { + return null; + } + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (curveWrapper.id == curveID) + { + return curveWrapper; + } + } + return null; + } + private void Init() + { + if (this.m_Selection != null && this.hasSelection && this.m_Selection[0].m_Host == null) + { + foreach (CurveSelection current in this.m_Selection) + { + current.m_Host = this; + } + } + } + internal void InitStyles() + { + if (this.ms_Styles == null) + { + this.ms_Styles = new CurveEditor.Styles(); + } + } + public void OnGUI() + { + base.BeginViewGUI(); + this.GridGUI(); + this.CurveGUI(); + base.EndViewGUI(); + } + public void CurveGUI() + { + this.InitStyles(); + GUI.BeginGroup(base.drawRect); + this.Init(); + GUIUtility.GetControlID(CurveEditor.s_SelectKeyHash, FocusType.Passive); + Color white = Color.white; + GUI.backgroundColor = white; + GUI.contentColor = white; + Color color = GUI.color; + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.KeyDown: + if ((current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete) && this.hasSelection) + { + this.DeleteSelectedPoints(); + current.Use(); + } + goto IL_30C; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_65: + switch (type) + { + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + { + bool flag = current.type == EventType.ExecuteCommand; + string commandName = current.commandName; + switch (commandName) + { + case "Delete": + if (this.hasSelection) + { + if (flag) + { + this.DeleteSelectedPoints(); + } + current.Use(); + } + break; + case "FrameSelected": + if (flag) + { + this.FrameSelected(true, true); + } + current.Use(); + break; + case "SelectAll": + if (flag) + { + this.SelectAll(); + } + current.Use(); + break; + } + goto IL_30C; + } + case EventType.DragExited: + goto IL_30C; + case EventType.ContextClick: + { + CurveSelection curveSelection = this.FindNearest(); + if (curveSelection != null) + { + List list = new List(); + bool flag2 = false; + foreach (CurveSelection current2 in this.m_Selection) + { + list.Add(new KeyIdentifier(current2.curveWrapper.renderer, current2.curveID, current2.key)); + if (current2.curveID == curveSelection.curveID && current2.key == curveSelection.key) + { + flag2 = true; + } + } + if (!flag2) + { + list.Clear(); + list.Add(new KeyIdentifier(curveSelection.curveWrapper.renderer, curveSelection.curveID, curveSelection.key)); + this.m_Selection.Clear(); + this.m_Selection.Add(curveSelection); + } + this.m_MenuManager = new CurveMenuManager(this); + GenericMenu genericMenu = new GenericMenu(); + string text; + if (list.Count > 1) + { + text = "Delete Keys"; + } + else + { + text = "Delete Key"; + } + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.DeleteKeys), list); + genericMenu.AddSeparator(string.Empty); + this.m_MenuManager.AddTangentMenuItems(genericMenu, list); + genericMenu.ShowAsContext(); + Event.current.Use(); + } + goto IL_30C; + } + default: + goto IL_30C; + } + break; + case EventType.Repaint: + this.DrawCurves(this.animationCurves); + goto IL_30C; + } + goto IL_65; + IL_30C: + bool changed = GUI.changed; + GUI.changed = false; + GUI.color = color; + this.DragTangents(); + this.EditAxisLabels(); + this.SelectPoints(); + if (GUI.changed) + { + this.RecalcSecondarySelection(); + this.RecalcCurveSelection(); + } + GUI.changed = false; + Vector2 moveCoord = this.MovePoints(); + if (GUI.changed && this.m_DraggingKey != null) + { + this.activeTime = moveCoord.x + this.s_StartClickedTime; + this.m_MoveCoord = moveCoord; + } + GUI.changed = changed; + GUI.color = color; + GUI.EndGroup(); + } + private void RecalcCurveSelection() + { + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + curveWrapper.selected = CurveWrapper.SelectionMode.None; + } + foreach (CurveSelection current in this.m_Selection) + { + current.curveWrapper.selected = ((!current.semiSelected) ? CurveWrapper.SelectionMode.Selected : CurveWrapper.SelectionMode.SemiSelected); + } + } + private void RecalcSecondarySelection() + { + List list = new List(); + foreach (CurveSelection current in this.m_Selection) + { + CurveWrapper curveWrapper = current.curveWrapper; + int groupId = current.curveWrapper.groupId; + if (groupId != -1 && !current.semiSelected) + { + list.Add(current); + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper2 = animationCurves[i]; + if (curveWrapper2.groupId == groupId && curveWrapper2 != curveWrapper) + { + list.Add(new CurveSelection(curveWrapper2.id, this, current.key) + { + semiSelected = true + }); + } + } + } + else + { + list.Add(current); + } + } + list.Sort(); + int j = 0; + while (j < list.Count - 1) + { + CurveSelection curveSelection = list[j]; + CurveSelection curveSelection2 = list[j + 1]; + if (curveSelection.curveID == curveSelection2.curveID && curveSelection.key == curveSelection2.key) + { + if (!curveSelection.semiSelected || !curveSelection2.semiSelected) + { + curveSelection.semiSelected = false; + } + list.RemoveAt(j + 1); + } + else + { + j++; + } + } + this.m_Selection = list; + } + private void DragTangents() + { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(CurveEditor.s_TangentControlIDHash, FocusType.Passive); + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0 && !current.alt) + { + this.m_SelectedTangentPoint = null; + float num = 64f; + Vector2 mousePosition = Event.current.mousePosition; + foreach (CurveSelection current2 in this.m_Selection) + { + Keyframe keyframe = current2.keyframe; + if (CurveUtility.GetKeyTangentMode(keyframe, 0) == TangentMode.Editable) + { + CurveSelection curveSelection = new CurveSelection(current2.curveID, this, current2.key, CurveSelection.SelectionType.InTangent); + float sqrMagnitude = (base.DrawingToViewTransformPoint(this.GetPosition(curveSelection)) - mousePosition).sqrMagnitude; + if (sqrMagnitude <= num) + { + this.m_SelectedTangentPoint = curveSelection; + num = sqrMagnitude; + } + } + if (CurveUtility.GetKeyTangentMode(keyframe, 1) == TangentMode.Editable) + { + CurveSelection curveSelection2 = new CurveSelection(current2.curveID, this, current2.key, CurveSelection.SelectionType.OutTangent); + float sqrMagnitude2 = (base.DrawingToViewTransformPoint(this.GetPosition(curveSelection2)) - mousePosition).sqrMagnitude; + if (sqrMagnitude2 <= num) + { + this.m_SelectedTangentPoint = curveSelection2; + num = sqrMagnitude2; + } + } + } + if (this.m_SelectedTangentPoint != null) + { + GUIUtility.hotControl = controlID; + this.activeTime = this.m_SelectedTangentPoint.keyframe.time; + current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 mousePositionInDrawing = base.mousePositionInDrawing; + CurveSelection selectedTangentPoint = this.m_SelectedTangentPoint; + Keyframe keyframe2 = selectedTangentPoint.keyframe; + if (selectedTangentPoint.type == CurveSelection.SelectionType.InTangent) + { + Vector2 vector = mousePositionInDrawing - new Vector2(keyframe2.time, keyframe2.value); + if (vector.x < -0.0001f) + { + keyframe2.inTangent = vector.y / vector.x; + } + else + { + keyframe2.inTangent = float.PositiveInfinity; + } + CurveUtility.SetKeyTangentMode(ref keyframe2, 0, TangentMode.Editable); + if (!CurveUtility.GetKeyBroken(keyframe2)) + { + keyframe2.outTangent = keyframe2.inTangent; + CurveUtility.SetKeyTangentMode(ref keyframe2, 1, TangentMode.Editable); + } + } + else + { + if (selectedTangentPoint.type == CurveSelection.SelectionType.OutTangent) + { + Vector2 vector2 = mousePositionInDrawing - new Vector2(keyframe2.time, keyframe2.value); + if (vector2.x > 0.0001f) + { + keyframe2.outTangent = vector2.y / vector2.x; + } + else + { + keyframe2.outTangent = float.PositiveInfinity; + } + CurveUtility.SetKeyTangentMode(ref keyframe2, 1, TangentMode.Editable); + if (!CurveUtility.GetKeyBroken(keyframe2)) + { + keyframe2.inTangent = keyframe2.outTangent; + CurveUtility.SetKeyTangentMode(ref keyframe2, 0, TangentMode.Editable); + } + } + } + selectedTangentPoint.key = selectedTangentPoint.curve.MoveKey(selectedTangentPoint.key, keyframe2); + CurveUtility.UpdateTangentsFromModeSurrounding(selectedTangentPoint.curveWrapper.curve, selectedTangentPoint.key); + selectedTangentPoint.curveWrapper.changed = true; + Event.current.Use(); + } + break; + } + } + private void DeleteSelectedPoints() + { + for (int i = this.m_Selection.Count - 1; i >= 0; i--) + { + CurveSelection curveSelection = this.m_Selection[i]; + CurveWrapper curveWrapper = curveSelection.curveWrapper; + if (base.settings.allowDeleteLastKeyInCurve || curveWrapper.curve.keys.Length != 1) + { + curveWrapper.curve.RemoveKey(curveSelection.key); + CurveUtility.UpdateTangentsFromMode(curveWrapper.curve); + curveWrapper.changed = true; + } + } + this.SelectNone(); + } + private void DeleteKeys(object obj) + { + List list = (List)obj; + List list2 = new List(); + for (int i = list.Count - 1; i >= 0; i--) + { + if (base.settings.allowDeleteLastKeyInCurve || list[i].curve.keys.Length != 1) + { + list[i].curve.RemoveKey(list[i].key); + CurveUtility.UpdateTangentsFromMode(list[i].curve); + list2.Add(list[i].curveId); + } + } + string undoText; + if (list.Count > 1) + { + undoText = "Delete Keys"; + } + else + { + undoText = "Delete Key"; + } + this.UpdateCurves(list2, undoText); + this.SelectNone(); + } + private float ClampVerticalValue(float value, int curveID) + { + value = Mathf.Clamp(value, base.vRangeMin, base.vRangeMax); + CurveWrapper curveFromID = this.GetCurveFromID(curveID); + if (curveFromID != null) + { + value = Mathf.Clamp(value, curveFromID.vRangeMin, curveFromID.vRangeMax); + } + return value; + } + public void UpdateCurvesFromPoints(Vector2 movement) + { + this.m_DisplayedSelection = new List(); + foreach (CurveEditor.SavedCurve current in this.m_CurveBackups) + { + List list = new List(current.keys.Count); + int num; + int num2; + int num3; + if (movement.x <= 0f) + { + num = 0; + num2 = current.keys.Count; + num3 = 1; + } + else + { + num = current.keys.Count - 1; + num2 = -1; + num3 = -1; + } + for (int num4 = num; num4 != num2; num4 += num3) + { + CurveEditor.SavedCurve.SavedKeyFrame savedKeyFrame = current.keys[num4]; + if (savedKeyFrame.selected != CurveWrapper.SelectionMode.None) + { + savedKeyFrame = new CurveEditor.SavedCurve.SavedKeyFrame(savedKeyFrame.key, savedKeyFrame.selected); + savedKeyFrame.key.time = Mathf.Clamp(savedKeyFrame.key.time + movement.x, base.hRangeMin, base.hRangeMax); + if (savedKeyFrame.selected == CurveWrapper.SelectionMode.Selected) + { + savedKeyFrame.key.value = this.ClampVerticalValue(savedKeyFrame.key.value + movement.y, current.curveId); + } + for (int i = list.Count - 1; i >= 0; i--) + { + if (Mathf.Abs(list[i].key.time - savedKeyFrame.key.time) < 1E-05f) + { + list.RemoveAt(i); + } + } + } + list.Add(new CurveEditor.SavedCurve.SavedKeyFrame(savedKeyFrame.key, savedKeyFrame.selected)); + } + list.Sort(); + Keyframe[] array = new Keyframe[list.Count]; + for (int j = 0; j < list.Count; j++) + { + CurveEditor.SavedCurve.SavedKeyFrame savedKeyFrame2 = list[j]; + array[j] = savedKeyFrame2.key; + if (savedKeyFrame2.selected != CurveWrapper.SelectionMode.None) + { + CurveSelection curveSelection = new CurveSelection(current.curveId, this, j); + if (savedKeyFrame2.selected == CurveWrapper.SelectionMode.SemiSelected) + { + curveSelection.semiSelected = true; + } + this.m_DisplayedSelection.Add(curveSelection); + } + } + CurveWrapper curveFromID = this.GetCurveFromID(current.curveId); + curveFromID.curve.keys = array; + curveFromID.changed = true; + } + this.UpdateTangentsFromSelection(); + } + private float SnapTime(float t) + { + if (EditorGUI.actionKey) + { + int levelWithMinSeparation = base.hTicks.GetLevelWithMinSeparation(5f); + float periodOfLevel = base.hTicks.GetPeriodOfLevel(levelWithMinSeparation); + t = Mathf.Round(t / periodOfLevel) * periodOfLevel; + } + else + { + if (this.invSnap != 0f) + { + t = Mathf.Round(t * this.invSnap) / this.invSnap; + } + } + return t; + } + private float SnapValue(float v) + { + if (EditorGUI.actionKey) + { + int levelWithMinSeparation = base.vTicks.GetLevelWithMinSeparation(5f); + float periodOfLevel = base.vTicks.GetPeriodOfLevel(levelWithMinSeparation); + v = Mathf.Round(v / periodOfLevel) * periodOfLevel; + } + return v; + } + private Vector2 GetGUIPoint(Vector3 point) + { + return HandleUtility.WorldToGUIPoint(base.DrawingToViewTransformPoint(point)); + } + private int OnlyOneEditableCurve() + { + int result = -1; + int num = 0; + for (int i = 0; i < this.m_AnimationCurves.Length; i++) + { + CurveWrapper curveWrapper = this.m_AnimationCurves[i]; + if (!curveWrapper.hidden && !curveWrapper.readOnly) + { + num++; + result = i; + } + } + if (num == 1) + { + return result; + } + return -1; + } + private int GetCurveAtPosition(Vector2 position, out Vector2 closestPointOnCurve) + { + Vector2 v = base.DrawingToViewTransformPoint(position); + int num = (int)Mathf.Sqrt(64f); + float num2 = 64f; + int result = -1; + closestPointOnCurve = Vector3.zero; + for (int i = this.m_DrawOrder.Count - 1; i >= 0; i--) + { + CurveWrapper curveWrapperById = this.getCurveWrapperById(this.m_DrawOrder[i]); + if (!curveWrapperById.hidden && !curveWrapperById.readOnly) + { + Vector2 vector; + vector.x = position.x - (float)num / base.scale.x; + vector.y = curveWrapperById.renderer.EvaluateCurveSlow(vector.x); + vector = base.DrawingToViewTransformPoint(vector); + for (int j = -num; j < num; j++) + { + Vector2 vector2; + vector2.x = position.x + (float)(j + 1) / base.scale.x; + vector2.y = curveWrapperById.renderer.EvaluateCurveSlow(vector2.x); + vector2 = base.DrawingToViewTransformPoint(vector2); + float num3 = HandleUtility.DistancePointLine(v, vector, vector2); + num3 *= num3; + if (num3 < num2) + { + num2 = num3; + result = curveWrapperById.listIndex; + closestPointOnCurve = HandleUtility.ProjectPointLine(v, vector, vector2); + } + vector = vector2; + } + } + } + closestPointOnCurve = base.ViewToDrawingTransformPoint(closestPointOnCurve); + return result; + } + private void CreateKeyFromClick(object obj) + { + List curveIds = this.CreateKeyFromClick((Vector2)obj); + this.UpdateCurves(curveIds, "Add Key"); + } + private List CreateKeyFromClick(Vector2 position) + { + List list = new List(); + int num = this.OnlyOneEditableCurve(); + if (num >= 0) + { + float x = position.x; + CurveWrapper curveWrapper = this.m_AnimationCurves[num]; + if (curveWrapper.curve.keys.Length == 0 || x < curveWrapper.curve.keys[0].time || x > curveWrapper.curve.keys[curveWrapper.curve.keys.Length - 1].time) + { + this.CreateKeyFromClick(num, position); + list.Add(curveWrapper.id); + return list; + } + } + Vector2 vector; + int curveAtPosition = this.GetCurveAtPosition(position, out vector); + this.CreateKeyFromClick(curveAtPosition, vector.x); + if (curveAtPosition >= 0) + { + list.Add(this.m_AnimationCurves[curveAtPosition].id); + } + return list; + } + private void CreateKeyFromClick(int curveIndex, float time) + { + time = Mathf.Clamp(time, base.settings.hRangeMin, base.settings.hRangeMax); + if (curveIndex >= 0) + { + CurveSelection curveSelection = null; + CurveWrapper curveWrapper = this.m_AnimationCurves[curveIndex]; + if (curveWrapper.groupId == -1) + { + curveSelection = this.AddKeyAtTime(curveWrapper, time); + } + else + { + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper2 = animationCurves[i]; + if (curveWrapper2.groupId == curveWrapper.groupId) + { + CurveSelection curveSelection2 = this.AddKeyAtTime(curveWrapper2, time); + if (curveWrapper2.id == curveWrapper.id) + { + curveSelection = curveSelection2; + } + } + } + } + if (curveSelection != null) + { + this.m_Selection = new List(1); + this.m_Selection.Add(curveSelection); + this.RecalcSecondarySelection(); + } + else + { + this.SelectNone(); + } + } + } + private void CreateKeyFromClick(int curveIndex, Vector2 position) + { + position.x = Mathf.Clamp(position.x, base.settings.hRangeMin, base.settings.hRangeMax); + if (curveIndex >= 0) + { + CurveSelection curveSelection = null; + CurveWrapper curveWrapper = this.m_AnimationCurves[curveIndex]; + if (curveWrapper.groupId == -1) + { + curveSelection = this.AddKeyAtPosition(curveWrapper, position); + } + else + { + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper2 = animationCurves[i]; + if (curveWrapper2.groupId == curveWrapper.groupId) + { + if (curveWrapper2.id == curveWrapper.id) + { + curveSelection = this.AddKeyAtPosition(curveWrapper2, position); + } + else + { + this.AddKeyAtTime(curveWrapper2, position.x); + } + } + } + } + if (curveSelection != null) + { + this.m_Selection = new List(1); + this.m_Selection.Add(curveSelection); + this.RecalcSecondarySelection(); + } + else + { + this.SelectNone(); + } + } + } + private CurveSelection AddKeyAtTime(CurveWrapper cw, float time) + { + time = this.SnapTime(time); + float num; + if (this.invSnap != 0f) + { + num = 0.5f / this.invSnap; + } + else + { + num = 0.0001f; + } + if (CurveUtility.HaveKeysInRange(cw.curve, time - num, time + num)) + { + return null; + } + float num2 = cw.renderer.EvaluateCurveDeltaSlow(time); + float value = this.ClampVerticalValue(this.SnapValue(cw.renderer.EvaluateCurveSlow(time)), cw.id); + Keyframe key = new Keyframe(time, value, num2, num2); + return this.AddKeyframeAndSelect(key, cw); + } + private CurveSelection AddKeyAtPosition(CurveWrapper cw, Vector2 position) + { + position.x = this.SnapTime(position.x); + float num; + if (this.invSnap != 0f) + { + num = 0.5f / this.invSnap; + } + else + { + num = 0.0001f; + } + if (CurveUtility.HaveKeysInRange(cw.curve, position.x - num, position.x + num)) + { + return null; + } + float num2 = 0f; + Keyframe key = new Keyframe(position.x, this.SnapValue(position.y), num2, num2); + return this.AddKeyframeAndSelect(key, cw); + } + private CurveSelection AddKeyframeAndSelect(Keyframe key, CurveWrapper cw) + { + int num = cw.curve.AddKey(key); + CurveUtility.SetKeyModeFromContext(cw.curve, num); + CurveUtility.UpdateTangentsFromModeSurrounding(cw.curve, num); + CurveSelection result = new CurveSelection(cw.id, this, num); + cw.selected = CurveWrapper.SelectionMode.Selected; + cw.changed = true; + this.activeTime = key.time; + return result; + } + private CurveSelection FindNearest() + { + Vector2 mousePosition = Event.current.mousePosition; + int num = -1; + int keyIndex = -1; + float num2 = 64f; + for (int i = this.m_DrawOrder.Count - 1; i >= 0; i--) + { + CurveWrapper curveWrapperById = this.getCurveWrapperById(this.m_DrawOrder[i]); + if (!curveWrapperById.readOnly && !curveWrapperById.hidden) + { + for (int j = 0; j < curveWrapperById.curve.keys.Length; j++) + { + Keyframe keyframe = curveWrapperById.curve.keys[j]; + float sqrMagnitude = (this.GetGUIPoint(new Vector2(keyframe.time, keyframe.value)) - mousePosition).sqrMagnitude; + if (sqrMagnitude <= 16f) + { + return new CurveSelection(curveWrapperById.id, this, j); + } + if (sqrMagnitude < num2) + { + num = curveWrapperById.id; + keyIndex = j; + num2 = sqrMagnitude; + } + } + if (i == this.m_DrawOrder.Count - 1 && num >= 0) + { + num2 = 16f; + } + } + } + if (num >= 0) + { + return new CurveSelection(num, this, keyIndex); + } + return null; + } + public void SelectNone() + { + this.m_Selection = new List(); + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + curveWrapper.selected = CurveWrapper.SelectionMode.None; + } + } + public void SelectAll() + { + int num = 0; + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (!curveWrapper.hidden) + { + num += curveWrapper.curve.length; + } + } + this.m_Selection = new List(num); + CurveWrapper[] animationCurves2 = this.m_AnimationCurves; + for (int j = 0; j < animationCurves2.Length; j++) + { + CurveWrapper curveWrapper2 = animationCurves2[j]; + curveWrapper2.selected = CurveWrapper.SelectionMode.Selected; + for (int k = 0; k < curveWrapper2.curve.length; k++) + { + this.m_Selection.Add(new CurveSelection(curveWrapper2.id, this, k)); + } + } + } + public bool IsDraggingCurveOrRegion() + { + return this.m_DraggingCurveOrRegion != null; + } + public bool IsDraggingCurve(CurveWrapper cw) + { + return this.m_DraggingCurveOrRegion != null && this.m_DraggingCurveOrRegion.Length == 1 && this.m_DraggingCurveOrRegion[0] == cw; + } + public bool IsDraggingRegion(CurveWrapper cw1, CurveWrapper cw2) + { + return this.m_DraggingCurveOrRegion != null && this.m_DraggingCurveOrRegion.Length == 2 && (this.m_DraggingCurveOrRegion[0] == cw1 || this.m_DraggingCurveOrRegion[0] == cw2); + } + private bool HandleCurveAndRegionMoveToFrontOnMouseDown(ref Vector2 timeValue, ref CurveWrapper[] curves) + { + Vector2 vector; + int curveAtPosition = this.GetCurveAtPosition(base.mousePositionInDrawing, out vector); + if (curveAtPosition >= 0) + { + this.MoveCurveToFront(this.m_AnimationCurves[curveAtPosition].id); + timeValue = base.mousePositionInDrawing; + curves = new CurveWrapper[] + { + this.m_AnimationCurves[curveAtPosition] + }; + return true; + } + for (int i = this.m_DrawOrder.Count - 1; i >= 0; i--) + { + CurveWrapper curveWrapperById = this.getCurveWrapperById(this.m_DrawOrder[i]); + if (curveWrapperById != null) + { + if (!curveWrapperById.hidden) + { + if (curveWrapperById.curve.length != 0) + { + CurveWrapper curveWrapper = null; + if (i > 0) + { + curveWrapper = this.getCurveWrapperById(this.m_DrawOrder[i - 1]); + } + if (this.IsRegion(curveWrapperById, curveWrapper)) + { + float y = base.mousePositionInDrawing.y; + float x = base.mousePositionInDrawing.x; + float num = curveWrapperById.renderer.EvaluateCurveSlow(x); + float num2 = curveWrapper.renderer.EvaluateCurveSlow(x); + if (num > num2) + { + float num3 = num; + num = num2; + num2 = num3; + } + if (y >= num && y <= num2) + { + timeValue = base.mousePositionInDrawing; + curves = new CurveWrapper[] + { + curveWrapperById, + curveWrapper + }; + this.MoveCurveToFront(curveWrapperById.id); + return true; + } + i--; + } + } + } + } + } + return false; + } + private void SelectPoints() + { + int controlID = GUIUtility.GetControlID(897560, FocusType.Passive); + Event current = Event.current; + bool shift = current.shift; + EventType typeForControl = current.GetTypeForControl(controlID); + switch (typeForControl) + { + case EventType.MouseDown: + if (current.clickCount == 2 && current.button == 0) + { + this.CreateKeyFromClick(base.mousePositionInDrawing); + } + else + { + if (current.button == 0) + { + CurveSelection curveSelection = this.FindNearest(); + if (curveSelection == null || curveSelection.semiSelected) + { + if (!shift) + { + this.SelectNone(); + } + Vector2 zero = Vector2.zero; + CurveWrapper[] array = null; + this.HandleCurveAndRegionMoveToFrontOnMouseDown(ref zero, ref array); + GUIUtility.hotControl = controlID; + this.s_EndMouseDragPosition = (this.s_StartMouseDragPosition = current.mousePosition); + this.s_PickMode = CurveEditor.PickMode.Click; + } + else + { + this.MoveCurveToFront(curveSelection.curveID); + this.activeTime = curveSelection.keyframe.time; + this.s_StartKeyDragPosition = new Vector2(curveSelection.keyframe.time, curveSelection.keyframe.value); + if (shift) + { + List list = new List(this.m_Selection); + if (this.m_Selection.IndexOf(curveSelection) == -1) + { + list.Add(curveSelection); + list.Sort(); + } + this.m_Selection = list; + } + else + { + if (this.m_Selection.IndexOf(curveSelection) == -1) + { + this.m_Selection = new List(1); + this.m_Selection.Add(curveSelection); + } + } + } + GUI.changed = true; + HandleUtility.Repaint(); + } + } + goto IL_3D0; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + this.s_PickMode = CurveEditor.PickMode.None; + Event.current.Use(); + } + goto IL_3D0; + case EventType.MouseMove: + IL_39: + if (typeForControl == EventType.Layout) + { + HandleUtility.AddDefaultControl(controlID); + goto IL_3D0; + } + if (typeForControl != EventType.ContextClick) + { + goto IL_3D0; + } + if (base.drawRect.Contains(GUIClip.Unclip(Event.current.mousePosition))) + { + Vector2 vector; + int curveAtPosition = this.GetCurveAtPosition(base.mousePositionInDrawing, out vector); + if (curveAtPosition >= 0) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Add Key"), false, new GenericMenu.MenuFunction2(this.CreateKeyFromClick), base.mousePositionInDrawing); + genericMenu.ShowAsContext(); + Event.current.Use(); + } + } + goto IL_3D0; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + this.s_EndMouseDragPosition = current.mousePosition; + if (this.s_PickMode == CurveEditor.PickMode.Click) + { + this.s_PickMode = CurveEditor.PickMode.Marquee; + if (shift) + { + this.s_SelectionBackup = new List(this.m_Selection); + } + else + { + this.s_SelectionBackup = new List(); + } + } + else + { + Rect rect = EditorGUIExt.FromToRect(this.s_StartMouseDragPosition, current.mousePosition); + List list2 = new List(this.s_SelectionBackup); + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (!curveWrapper.readOnly && !curveWrapper.hidden) + { + int num = 0; + Keyframe[] keys = curveWrapper.curve.keys; + for (int j = 0; j < keys.Length; j++) + { + Keyframe keyframe = keys[j]; + if (rect.Contains(this.GetGUIPoint(new Vector2(keyframe.time, keyframe.value)))) + { + list2.Add(new CurveSelection(curveWrapper.id, this, num)); + this.MoveCurveToFront(curveWrapper.id); + } + num++; + } + } + } + list2.Sort(); + this.m_Selection = list2; + GUI.changed = true; + } + current.Use(); + } + goto IL_3D0; + } + goto IL_39; + IL_3D0: + if (this.s_PickMode == CurveEditor.PickMode.Marquee) + { + GUI.Label(EditorGUIExt.FromToRect(this.s_StartMouseDragPosition, this.s_EndMouseDragPosition), GUIContent.none, this.ms_Styles.selectionRect); + } + } + private void EditAxisLabels() + { + int controlID = GUIUtility.GetControlID(18975602, FocusType.Keyboard); + List list = new List(); + Vector2 axisUiScalars = this.GetAxisUiScalars(list); + if (axisUiScalars.y < 0f || list.Count <= 0 || list[0].setAxisUiScalarsCallback == null) + { + return; + } + Rect rect = new Rect(0f, base.topmargin - 8f, base.leftmargin - 4f, 16f); + Rect position = rect; + position.y -= rect.height; + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0) + { + if (position.Contains(Event.current.mousePosition) && GUIUtility.hotControl == 0) + { + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = controlID; + GUI.changed = true; + current.Use(); + } + if (!rect.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = 0; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + float num = Mathf.Clamp01(Mathf.Max(axisUiScalars.y, Mathf.Pow(Mathf.Abs(axisUiScalars.y), 0.5f)) * 0.01f); + axisUiScalars.y += HandleUtility.niceMouseDelta * num; + if (axisUiScalars.y < 0.001f) + { + axisUiScalars.y = 0.001f; + } + this.SetAxisUiScalars(axisUiScalars, list); + current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == 0) + { + EditorGUIUtility.AddCursorRect(position, MouseCursor.SlideArrow); + } + break; + } + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + EditorGUI.kFloatFieldFormatString = this.m_AxisLabelFormat; + float num2 = EditorGUI.FloatField(rect, axisUiScalars.y, this.ms_Styles.axisLabelNumberField); + if (axisUiScalars.y != num2) + { + this.SetAxisUiScalars(new Vector2(axisUiScalars.x, num2), list); + } + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + } + public void BeginTimeRangeSelection(float time, bool addToSelection) + { + if (this.s_TimeRangeSelectionActive) + { + Debug.LogError("BeginTimeRangeSelection can only be called once"); + return; + } + this.s_TimeRangeSelectionActive = true; + this.s_TimeRangeSelectionEnd = time; + this.s_TimeRangeSelectionStart = time; + if (addToSelection) + { + this.s_SelectionBackup = new List(this.m_Selection); + } + else + { + this.s_SelectionBackup = new List(); + } + } + public void TimeRangeSelectTo(float time) + { + if (!this.s_TimeRangeSelectionActive) + { + Debug.LogError("TimeRangeSelectTo can only be called after BeginTimeRangeSelection"); + return; + } + this.s_TimeRangeSelectionEnd = time; + this.m_Selection = new List(this.s_SelectionBackup); + float num = Mathf.Min(this.s_TimeRangeSelectionStart, this.s_TimeRangeSelectionEnd); + float num2 = Mathf.Max(this.s_TimeRangeSelectionStart, this.s_TimeRangeSelectionEnd); + CurveWrapper[] animationCurves = this.m_AnimationCurves; + for (int i = 0; i < animationCurves.Length; i++) + { + CurveWrapper curveWrapper = animationCurves[i]; + if (!curveWrapper.readOnly && !curveWrapper.hidden) + { + int num3 = 0; + Keyframe[] keys = curveWrapper.curve.keys; + for (int j = 0; j < keys.Length; j++) + { + Keyframe keyframe = keys[j]; + if (keyframe.time >= num && keyframe.time < num2) + { + this.m_Selection.Add(new CurveSelection(curveWrapper.id, this, num3)); + } + num3++; + } + } + } + this.m_Selection.Sort(); + this.RecalcSecondarySelection(); + this.RecalcCurveSelection(); + } + public void EndTimeRangeSelection() + { + if (!this.s_TimeRangeSelectionActive) + { + Debug.LogError("EndTimeRangeSelection can only be called after BeginTimeRangeSelection"); + return; + } + this.s_TimeRangeSelectionStart = (this.s_TimeRangeSelectionEnd = 0f); + this.s_TimeRangeSelectionActive = false; + } + public void CancelTimeRangeSelection() + { + if (!this.s_TimeRangeSelectionActive) + { + Debug.LogError("CancelTimeRangeSelection can only be called after BeginTimeRangeSelection"); + return; + } + this.m_Selection = this.s_SelectionBackup; + this.s_TimeRangeSelectionActive = false; + } + public void DrawTimeRange() + { + if (this.s_TimeRangeSelectionActive && Event.current.type == EventType.Repaint) + { + float x = Mathf.Min(this.s_TimeRangeSelectionStart, this.s_TimeRangeSelectionEnd); + float x2 = Mathf.Max(this.s_TimeRangeSelectionStart, this.s_TimeRangeSelectionEnd); + float x3 = this.GetGUIPoint(new Vector3(x, 0f, 0f)).x; + float x4 = this.GetGUIPoint(new Vector3(x2, 0f, 0f)).x; + GUI.Label(new Rect(x3, -10000f, x4 - x3, 20000f), GUIContent.none, this.ms_Styles.selectionRect); + } + } + private void SetupKeyOrCurveDragging(Vector2 timeValue, CurveWrapper cw, int id, Vector2 mousePos) + { + this.m_DraggedCoord = timeValue; + this.m_DraggingKey = cw; + GUIUtility.hotControl = id; + this.MakeCurveBackups(); + this.s_StartMouseDragPosition = mousePos; + this.activeTime = timeValue.x; + this.s_StartClickedTime = timeValue.x; + } + public Vector2 MovePoints() + { + int controlID = GUIUtility.GetControlID(FocusType.Passive); + if (!this.hasSelection && !base.settings.allowDraggingCurvesAndRegions) + { + return Vector2.zero; + } + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0) + { + foreach (CurveSelection current2 in this.m_Selection) + { + if (!current2.curveWrapper.hidden) + { + if ((base.DrawingToViewTransformPoint(this.GetPosition(current2)) - current.mousePosition).sqrMagnitude <= 64f) + { + this.SetupKeyOrCurveDragging(new Vector2(current2.keyframe.time, current2.keyframe.value), current2.curveWrapper, controlID, current.mousePosition); + break; + } + } + } + if (base.settings.allowDraggingCurvesAndRegions && this.m_DraggingKey == null) + { + Vector2 zero = Vector2.zero; + CurveWrapper[] array = null; + if (this.HandleCurveAndRegionMoveToFrontOnMouseDown(ref zero, ref array)) + { + CurveWrapper[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + CurveWrapper curveWrapper = array2[i]; + for (int j = 0; j < curveWrapper.curve.keys.Length; j++) + { + this.m_Selection.Add(new CurveSelection(curveWrapper.id, this, j)); + } + this.MoveCurveToFront(curveWrapper.id); + } + this.SetupKeyOrCurveDragging(zero, array[0], controlID, current.mousePosition); + this.m_DraggingCurveOrRegion = array; + } + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + this.ResetDragging(); + GUI.changed = true; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 lhs = current.mousePosition - this.s_StartMouseDragPosition; + Vector3 v; + if (this.m_DraggingCurveOrRegion != null) + { + lhs.x = 0f; + v = base.ViewToDrawingTransformVector(lhs); + v.y = this.SnapValue(v.y + this.s_StartKeyDragPosition.y) - this.s_StartKeyDragPosition.y; + } + else + { + if (current.shift) + { + if (Mathf.Abs(lhs.x) > Mathf.Abs(lhs.y)) + { + lhs.y = 0f; + v = base.ViewToDrawingTransformVector(lhs); + v.x = this.SnapTime(v.x + this.s_StartKeyDragPosition.x) - this.s_StartKeyDragPosition.x; + } + else + { + lhs.x = 0f; + v = base.ViewToDrawingTransformVector(lhs); + v.y = this.SnapValue(v.y + this.s_StartKeyDragPosition.y) - this.s_StartKeyDragPosition.y; + } + } + else + { + v = base.ViewToDrawingTransformVector(lhs); + v.x = this.SnapTime(v.x + this.s_StartKeyDragPosition.x) - this.s_StartKeyDragPosition.x; + v.y = this.SnapValue(v.y + this.s_StartKeyDragPosition.y) - this.s_StartKeyDragPosition.y; + } + } + this.UpdateCurvesFromPoints(v); + GUI.changed = true; + current.Use(); + return v; + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == controlID && current.keyCode == KeyCode.Escape) + { + this.UpdateCurvesFromPoints(Vector2.zero); + this.ResetDragging(); + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + if (this.m_DraggingCurveOrRegion != null) + { + EditorGUIUtility.AddCursorRect(new Rect(current.mousePosition.x - 10f, current.mousePosition.y - 10f, 20f, 20f), MouseCursor.ResizeVertical); + } + break; + } + return Vector2.zero; + } + private void ResetDragging() + { + if (this.m_DraggingCurveOrRegion != null) + { + this.SelectNone(); + } + GUIUtility.hotControl = 0; + this.m_DraggingKey = null; + this.m_DraggingCurveOrRegion = null; + this.m_DisplayedSelection = null; + this.m_MoveCoord = Vector2.zero; + } + internal void MakeCurveBackups() + { + this.m_CurveBackups = new List(); + int num = -1; + CurveEditor.SavedCurve savedCurve = null; + for (int i = 0; i < this.m_Selection.Count; i++) + { + CurveSelection curveSelection = this.m_Selection[i]; + if (curveSelection.curveID != num) + { + savedCurve = new CurveEditor.SavedCurve(); + num = (savedCurve.curveId = curveSelection.curveID); + Keyframe[] keys = curveSelection.curve.keys; + savedCurve.keys = new List(keys.Length); + Keyframe[] array = keys; + for (int j = 0; j < array.Length; j++) + { + Keyframe key = array[j]; + savedCurve.keys.Add(new CurveEditor.SavedCurve.SavedKeyFrame(key, CurveWrapper.SelectionMode.None)); + } + this.m_CurveBackups.Add(savedCurve); + } + savedCurve.keys[curveSelection.key].selected = ((!curveSelection.semiSelected) ? CurveWrapper.SelectionMode.Selected : CurveWrapper.SelectionMode.SemiSelected); + } + } + private Vector2 GetPosition(CurveSelection selection) + { + Keyframe keyframe = selection.keyframe; + Vector2 vector = new Vector2(keyframe.time, keyframe.value); + float d = 50f; + if (selection.type == CurveSelection.SelectionType.InTangent) + { + Vector2 vector2 = new Vector2(1f, keyframe.inTangent); + if (keyframe.inTangent == float.PositiveInfinity) + { + vector2 = new Vector2(0f, -1f); + } + vector2 = base.NormalizeInViewSpace(vector2); + return vector - vector2 * d; + } + if (selection.type == CurveSelection.SelectionType.OutTangent) + { + Vector2 vector3 = new Vector2(1f, keyframe.outTangent); + if (keyframe.outTangent == float.PositiveInfinity) + { + vector3 = new Vector2(0f, -1f); + } + vector3 = base.NormalizeInViewSpace(vector3); + return vector + vector3 * d; + } + return vector; + } + private void MoveCurveToFront(int curveID) + { + int count = this.m_DrawOrder.Count; + for (int i = 0; i < count; i++) + { + if (this.m_DrawOrder[i] == curveID) + { + int regionId = this.getCurveWrapperById(curveID).regionId; + if (regionId >= 0) + { + int num = 0; + int num2 = -1; + if (i - 1 >= 0) + { + int num3 = this.m_DrawOrder[i - 1]; + if (regionId == this.getCurveWrapperById(num3).regionId) + { + num2 = num3; + num = -1; + } + } + if (i + 1 < count && num2 < 0) + { + int num4 = this.m_DrawOrder[i + 1]; + if (regionId == this.getCurveWrapperById(num4).regionId) + { + num2 = num4; + num = 0; + } + } + if (num2 >= 0) + { + this.m_DrawOrder.RemoveRange(i + num, 2); + this.m_DrawOrder.Add(num2); + this.m_DrawOrder.Add(curveID); + this.ValidateCurveList(); + return; + } + Debug.LogError("Unhandled region"); + } + else + { + if (i == count - 1) + { + return; + } + this.m_DrawOrder.RemoveAt(i); + this.m_DrawOrder.Add(curveID); + this.ValidateCurveList(); + return; + } + } + } + } + private bool IsCurveSelected(CurveWrapper cw) + { + return cw != null && cw.selected != CurveWrapper.SelectionMode.None; + } + private bool IsRegionCurveSelected(CurveWrapper cw1, CurveWrapper cw2) + { + return this.IsCurveSelected(cw1) || this.IsCurveSelected(cw2); + } + private bool IsRegion(CurveWrapper cw1, CurveWrapper cw2) + { + return cw1 != null && cw2 != null && cw1.regionId >= 0 && cw1.regionId == cw2.regionId; + } + private void DrawCurvesAndRegion(CurveWrapper cw1, CurveWrapper cw2, List selection, bool hasFocus) + { + this.DrawRegion(cw1, cw2, hasFocus); + this.DrawCurveAndPoints(cw1, (!this.IsCurveSelected(cw1)) ? null : selection, hasFocus); + this.DrawCurveAndPoints(cw2, (!this.IsCurveSelected(cw2)) ? null : selection, hasFocus); + } + private void DrawCurveAndPoints(CurveWrapper cw, List selection, bool hasFocus) + { + this.DrawCurve(cw, hasFocus); + this.DrawPointsOnCurve(cw, selection, hasFocus); + } + private bool ShouldCurveHaveFocus(int indexIntoDrawOrder, CurveWrapper cw1, CurveWrapper cw2) + { + bool result = false; + if (indexIntoDrawOrder == this.m_DrawOrder.Count - 1) + { + result = true; + } + else + { + if (this.hasSelection) + { + result = (this.IsCurveSelected(cw1) || this.IsCurveSelected(cw2)); + } + } + return result; + } + private void DrawCurves(CurveWrapper[] curves) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + List list = (this.m_DisplayedSelection == null) ? this.m_Selection : this.m_DisplayedSelection; + for (int i = 0; i < this.m_DrawOrder.Count; i++) + { + CurveWrapper curveWrapperById = this.getCurveWrapperById(this.m_DrawOrder[i]); + if (curveWrapperById != null) + { + if (!curveWrapperById.hidden) + { + if (curveWrapperById.curve.length != 0) + { + CurveWrapper cw = null; + if (i < this.m_DrawOrder.Count - 1) + { + cw = this.getCurveWrapperById(this.m_DrawOrder[i + 1]); + } + if (this.IsRegion(curveWrapperById, cw)) + { + i++; + bool hasFocus = this.ShouldCurveHaveFocus(i, curveWrapperById, cw); + this.DrawCurvesAndRegion(curveWrapperById, cw, (!this.IsRegionCurveSelected(curveWrapperById, cw)) ? null : list, hasFocus); + } + else + { + bool hasFocus2 = this.ShouldCurveHaveFocus(i, curveWrapperById, null); + this.DrawCurveAndPoints(curveWrapperById, (!this.IsCurveSelected(curveWrapperById)) ? null : list, hasFocus2); + } + } + } + } + } + if (this.m_DraggingCurveOrRegion != null) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + GL.Color(this.m_TangentColor * new Color(1f, 1f, 1f, 0.75f)); + foreach (CurveSelection current in list) + { + if (!current.semiSelected) + { + Vector2 position = this.GetPosition(current); + if (CurveUtility.GetKeyTangentMode(current.keyframe, 0) == TangentMode.Editable && current.keyframe.time != current.curve.keys[0].time) + { + Vector2 position2 = this.GetPosition(new CurveSelection(current.curveID, this, current.key, CurveSelection.SelectionType.InTangent)); + this.DrawLine(position2, position); + } + if (CurveUtility.GetKeyTangentMode(current.keyframe, 1) == TangentMode.Editable && current.keyframe.time != current.curve.keys[current.curve.keys.Length - 1].time) + { + Vector2 position3 = this.GetPosition(new CurveSelection(current.curveID, this, current.key, CurveSelection.SelectionType.OutTangent)); + this.DrawLine(position, position3); + } + } + } + GL.End(); + GUI.color = this.m_TangentColor; + foreach (CurveSelection current2 in list) + { + if (!current2.semiSelected) + { + if (CurveUtility.GetKeyTangentMode(current2.keyframe, 0) == TangentMode.Editable && current2.keyframe.time != current2.curve.keys[0].time) + { + Vector2 position4 = this.GetPosition(new CurveSelection(current2.curveID, this, current2.key, CurveSelection.SelectionType.InTangent)); + this.DrawPoint(position4.x, position4.y, this.ms_Styles.pointIcon); + } + if (CurveUtility.GetKeyTangentMode(current2.keyframe, 1) == TangentMode.Editable && current2.keyframe.time != current2.curve.keys[current2.curve.keys.Length - 1].time) + { + Vector2 position5 = this.GetPosition(new CurveSelection(current2.curveID, this, current2.key, CurveSelection.SelectionType.OutTangent)); + this.DrawPoint(position5.x, position5.y, this.ms_Styles.pointIcon); + } + } + } + if (this.m_DraggingKey != null) + { + float num = base.vRangeMin; + float num2 = base.vRangeMax; + num = Mathf.Max(num, this.m_DraggingKey.vRangeMin); + num2 = Mathf.Min(num2, this.m_DraggingKey.vRangeMax); + Vector2 lhs = this.m_DraggedCoord + this.m_MoveCoord; + lhs.x = Mathf.Clamp(lhs.x, base.hRangeMin, base.hRangeMax); + lhs.y = Mathf.Clamp(lhs.y, num, num2); + Vector2 vector = base.DrawingToViewTransformPoint(lhs); + int numberOfDecimalsForMinimumDifference; + if (this.invSnap != 0f) + { + numberOfDecimalsForMinimumDifference = MathUtils.GetNumberOfDecimalsForMinimumDifference(1f / this.invSnap); + } + else + { + numberOfDecimalsForMinimumDifference = MathUtils.GetNumberOfDecimalsForMinimumDifference(base.shownArea.width / base.drawRect.width); + } + int numberOfDecimalsForMinimumDifference2 = MathUtils.GetNumberOfDecimalsForMinimumDifference(base.shownArea.height / base.drawRect.height); + Vector2 vector2 = (this.m_DraggingKey.getAxisUiScalarsCallback == null) ? Vector2.one : this.m_DraggingKey.getAxisUiScalarsCallback(); + if (vector2.x >= 0f) + { + lhs.x *= vector2.x; + } + if (vector2.y >= 0f) + { + lhs.y *= vector2.y; + } + GUIContent content = new GUIContent(string.Format("{0}, {1}", lhs.x.ToString("N" + numberOfDecimalsForMinimumDifference), lhs.y.ToString("N" + numberOfDecimalsForMinimumDifference2))); + Vector2 vector3 = this.ms_Styles.dragLabel.CalcSize(content); + EditorGUI.DoDropShadowLabel(new Rect(vector.x, vector.y - vector3.y, vector3.x, vector3.y), content, this.ms_Styles.dragLabel, 0.3f); + } + } + private static List CreateRegion(CurveWrapper minCurve, CurveWrapper maxCurve, float deltaTime) + { + List list = new List(); + List list2 = new List(); + float num; + for (num = deltaTime; num <= 1f; num += deltaTime) + { + list2.Add(num); + } + if (num != 1f) + { + list2.Add(1f); + } + Keyframe[] keys = maxCurve.curve.keys; + for (int i = 0; i < keys.Length; i++) + { + Keyframe keyframe = keys[i]; + if (keyframe.time > 0f && keyframe.time < 1f) + { + list2.Add(keyframe.time - 0.0001f); + list2.Add(keyframe.time); + list2.Add(keyframe.time + 0.0001f); + } + } + Keyframe[] keys2 = minCurve.curve.keys; + for (int j = 0; j < keys2.Length; j++) + { + Keyframe keyframe2 = keys2[j]; + if (keyframe2.time > 0f && keyframe2.time < 1f) + { + list2.Add(keyframe2.time - 0.0001f); + list2.Add(keyframe2.time); + list2.Add(keyframe2.time + 0.0001f); + } + } + list2.Sort(); + Vector3 vector = new Vector3(0f, maxCurve.renderer.EvaluateCurveSlow(0f), 0f); + Vector3 vector2 = new Vector3(0f, minCurve.renderer.EvaluateCurveSlow(0f), 0f); + for (int k = 0; k < list2.Count; k++) + { + float num2 = list2[k]; + Vector3 vector3 = new Vector3(num2, maxCurve.renderer.EvaluateCurveSlow(num2), 0f); + Vector3 vector4 = new Vector3(num2, minCurve.renderer.EvaluateCurveSlow(num2), 0f); + if (vector.y >= vector2.y && vector3.y >= vector4.y) + { + list.Add(vector); + list.Add(vector4); + list.Add(vector2); + list.Add(vector); + list.Add(vector3); + list.Add(vector4); + } + else + { + if (vector.y <= vector2.y && vector3.y <= vector4.y) + { + list.Add(vector2); + list.Add(vector3); + list.Add(vector); + list.Add(vector2); + list.Add(vector4); + list.Add(vector3); + } + else + { + Vector2 zero = Vector2.zero; + if (Mathf.LineIntersection(vector, vector3, vector2, vector4, ref zero)) + { + list.Add(vector); + list.Add(zero); + list.Add(vector2); + list.Add(vector3); + list.Add(zero); + list.Add(vector4); + } + else + { + Debug.Log("Error: No intersection found! There should be one..."); + } + } + } + vector = vector3; + vector2 = vector4; + } + return list; + } + public void DrawRegion(CurveWrapper curve1, CurveWrapper curve2, bool hasFocus) + { + float deltaTime = 1f / (base.rect.width / 10f); + List list = CurveEditor.CreateRegion(curve1, curve2, deltaTime); + Color color = curve1.color; + for (int i = 0; i < list.Count; i++) + { + list[i] = base.drawingToViewMatrix.MultiplyPoint(list[i]); + } + if (this.IsDraggingRegion(curve1, curve2)) + { + color = Color.Lerp(color, Color.black, 0.1f); + color.a = 0.4f; + } + else + { + if (base.settings.useFocusColors && !hasFocus) + { + color *= 0.4f; + color.a = 0.1f; + } + else + { + color *= 1f; + color.a = 0.4f; + } + } + Shader.SetGlobalColor("_HandleColor", color); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(4); + int num = list.Count / 3; + for (int j = 0; j < num; j++) + { + GL.Color(color); + GL.Vertex(list[j * 3]); + GL.Vertex(list[j * 3 + 1]); + GL.Vertex(list[j * 3 + 2]); + } + GL.End(); + } + private void DrawCurve(CurveWrapper cw, bool hasFocus) + { + CurveRenderer renderer = cw.renderer; + Color color = cw.color; + if (this.IsDraggingCurve(cw) || cw.selected == CurveWrapper.SelectionMode.Selected) + { + color = Color.Lerp(color, Color.white, 0.3f); + } + else + { + if (base.settings.useFocusColors && !hasFocus) + { + color *= 0.5f; + color.a = 0.8f; + } + } + Rect shownArea = base.shownArea; + renderer.DrawCurve(shownArea.xMin, shownArea.xMax, color, base.drawingToViewMatrix, base.settings.wrapColor); + } + private void DrawPointsOnCurve(CurveWrapper cw, List selected, bool hasFocus) + { + this.m_PreviousDrawPointCenter = new Vector2(-3.40282347E+38f, -3.40282347E+38f); + if (selected == null) + { + Color color = cw.color; + if (base.settings.useFocusColors && !hasFocus) + { + color *= 0.5f; + } + GUI.color = color; + Keyframe[] keys = cw.curve.keys; + for (int i = 0; i < keys.Length; i++) + { + Keyframe keyframe = keys[i]; + this.DrawPoint(keyframe.time, keyframe.value, this.ms_Styles.pointIcon); + } + } + else + { + Color color2 = Color.Lerp(cw.color, Color.white, 0.2f); + GUI.color = color2; + int num = 0; + while (num < selected.Count && selected[num].curveID != cw.id) + { + num++; + } + int num2 = 0; + Keyframe[] keys2 = cw.curve.keys; + for (int j = 0; j < keys2.Length; j++) + { + Keyframe keyframe2 = keys2[j]; + if (num < selected.Count && selected[num].key == num2 && selected[num].curveID == cw.id) + { + Vector3 vector = base.DrawingToViewTransformPoint(new Vector3(keyframe2.time, keyframe2.value, 0f)); + vector = new Vector3(Mathf.Floor(vector.x), Mathf.Floor(vector.y), 0f); + Rect position = new Rect(vector.x - 4f, vector.y - 4f, (float)this.ms_Styles.pointIcon.width, (float)this.ms_Styles.pointIcon.height); + GUI.Label(position, this.ms_Styles.pointIconSelected, this.ms_Styles.none); + GUI.color = Color.white; + if (!selected[num].semiSelected) + { + GUI.Label(position, this.ms_Styles.pointIconSelectedOverlay, this.ms_Styles.none); + } + else + { + GUI.Label(position, this.ms_Styles.pointIconSemiSelectedOverlay, this.ms_Styles.none); + } + GUI.color = color2; + num++; + } + else + { + this.DrawPoint(keyframe2.time, keyframe2.value, this.ms_Styles.pointIcon); + } + num2++; + } + GUI.color = Color.white; + } + } + private void DrawPoint(float x, float y, Texture2D icon) + { + Vector3 vector = base.DrawingToViewTransformPoint(new Vector3(x, y, 0f)); + vector = new Vector3(Mathf.Floor(vector.x), Mathf.Floor(vector.y), 0f); + Rect position = new Rect(vector.x - 4f, vector.y - 4f, (float)this.ms_Styles.pointIcon.width, (float)this.ms_Styles.pointIcon.height); + Vector2 center = position.center; + if ((center - this.m_PreviousDrawPointCenter).magnitude > 8f) + { + GUI.Label(position, icon, GUIStyleX.none); + this.m_PreviousDrawPointCenter = center; + } + } + private void DrawLine(Vector2 lhs, Vector2 rhs) + { + GL.Vertex(base.DrawingToViewTransformPoint(new Vector3(lhs.x, lhs.y, 0f))); + GL.Vertex(base.DrawingToViewTransformPoint(new Vector3(rhs.x, rhs.y, 0f))); + } + private Vector2 GetAxisUiScalars(List curvesWithSameParameterSpace) + { + if (this.m_Selection.Count <= 1) + { + if (this.m_DrawOrder.Count > 0) + { + CurveWrapper curveWrapperById = this.getCurveWrapperById(this.m_DrawOrder[this.m_DrawOrder.Count - 1]); + if (curveWrapperById.getAxisUiScalarsCallback != null) + { + if (curvesWithSameParameterSpace != null) + { + curvesWithSameParameterSpace.Add(curveWrapperById); + } + return curveWrapperById.getAxisUiScalarsCallback(); + } + } + return Vector2.one; + } + Vector2 result = new Vector2(-1f, -1f); + if (this.m_Selection.Count > 1) + { + bool flag = true; + bool flag2 = true; + Vector2 vector = Vector2.one; + for (int i = 0; i < this.m_Selection.Count; i++) + { + CurveWrapper curveWrapper = this.m_Selection[i].curveWrapper; + if (curveWrapper.getAxisUiScalarsCallback != null) + { + Vector2 vector2 = curveWrapper.getAxisUiScalarsCallback(); + if (i == 0) + { + vector = vector2; + } + else + { + if (Mathf.Abs(vector2.x - vector.x) > 1E-05f) + { + flag = false; + } + if (Mathf.Abs(vector2.y - vector.y) > 1E-05f) + { + flag2 = false; + } + vector = vector2; + } + if (curvesWithSameParameterSpace != null) + { + curvesWithSameParameterSpace.Add(curveWrapper); + } + } + } + if (flag) + { + result.x = vector.x; + } + if (flag2) + { + result.y = vector.y; + } + } + return result; + } + private void SetAxisUiScalars(Vector2 newScalars, List curvesInSameSpace) + { + foreach (CurveWrapper current in curvesInSameSpace) + { + Vector2 newAxisScalars = current.getAxisUiScalarsCallback(); + if (newScalars.x >= 0f) + { + newAxisScalars.x = newScalars.x; + } + if (newScalars.y >= 0f) + { + newAxisScalars.y = newScalars.y; + } + if (current.setAxisUiScalarsCallback != null) + { + current.setAxisUiScalarsCallback(newAxisScalars); + } + } + } + public void GridGUI() + { + GUI.BeginGroup(base.drawRect); + if (Event.current.type != EventType.Repaint) + { + GUI.EndGroup(); + return; + } + this.InitStyles(); + Color color = GUI.color; + Vector2 axisUiScalars = this.GetAxisUiScalars(null); + Rect shownArea = base.shownArea; + base.hTicks.SetRanges(shownArea.xMin * axisUiScalars.x, shownArea.xMax * axisUiScalars.x, base.drawRect.xMin, base.drawRect.xMax); + base.vTicks.SetRanges(shownArea.yMin * axisUiScalars.y, shownArea.yMax * axisUiScalars.y, base.drawRect.yMin, base.drawRect.yMax); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + base.hTicks.SetTickStrengths((float)base.settings.hTickStyle.distMin, (float)base.settings.hTickStyle.distFull, false); + float num; + float num2; + if (base.settings.hTickStyle.stubs) + { + num = shownArea.yMin; + num2 = shownArea.yMin - 40f / base.scale.y; + } + else + { + num = Mathf.Max(shownArea.yMin, base.vRangeMin); + num2 = Mathf.Min(shownArea.yMax, base.vRangeMax); + } + for (int i = 0; i < base.hTicks.tickLevels; i++) + { + float strengthOfLevel = base.hTicks.GetStrengthOfLevel(i); + if (strengthOfLevel > 0f) + { + GL.Color(base.settings.hTickStyle.color * new Color(1f, 1f, 1f, strengthOfLevel) * new Color(1f, 1f, 1f, 0.75f)); + float[] ticksAtLevel = base.hTicks.GetTicksAtLevel(i, true); + for (int j = 0; j < ticksAtLevel.Length; j++) + { + ticksAtLevel[j] /= axisUiScalars.x; + if (ticksAtLevel[j] > base.hRangeMin && ticksAtLevel[j] < base.hRangeMax) + { + this.DrawLine(new Vector2(ticksAtLevel[j], num), new Vector2(ticksAtLevel[j], num2)); + } + } + } + } + GL.Color(base.settings.hTickStyle.color * new Color(1f, 1f, 1f, 1f) * new Color(1f, 1f, 1f, 0.75f)); + if (base.hRangeMin != float.NegativeInfinity) + { + this.DrawLine(new Vector2(base.hRangeMin, num), new Vector2(base.hRangeMin, num2)); + } + if (base.hRangeMax != float.PositiveInfinity) + { + this.DrawLine(new Vector2(base.hRangeMax, num), new Vector2(base.hRangeMax, num2)); + } + base.vTicks.SetTickStrengths((float)base.settings.vTickStyle.distMin, (float)base.settings.vTickStyle.distFull, false); + if (base.settings.vTickStyle.stubs) + { + num = shownArea.xMin; + num2 = shownArea.xMin + 40f / base.scale.x; + } + else + { + num = Mathf.Max(shownArea.xMin, base.hRangeMin); + num2 = Mathf.Min(shownArea.xMax, base.hRangeMax); + } + for (int k = 0; k < base.vTicks.tickLevels; k++) + { + float strengthOfLevel2 = base.vTicks.GetStrengthOfLevel(k); + if (strengthOfLevel2 > 0f) + { + GL.Color(base.settings.vTickStyle.color * new Color(1f, 1f, 1f, strengthOfLevel2) * new Color(1f, 1f, 1f, 0.75f)); + float[] ticksAtLevel2 = base.vTicks.GetTicksAtLevel(k, true); + for (int l = 0; l < ticksAtLevel2.Length; l++) + { + ticksAtLevel2[l] /= axisUiScalars.y; + if (ticksAtLevel2[l] > base.vRangeMin && ticksAtLevel2[l] < base.vRangeMax) + { + this.DrawLine(new Vector2(num, ticksAtLevel2[l]), new Vector2(num2, ticksAtLevel2[l])); + } + } + } + } + GL.Color(base.settings.vTickStyle.color * new Color(1f, 1f, 1f, 1f) * new Color(1f, 1f, 1f, 0.75f)); + if (base.vRangeMin != float.NegativeInfinity) + { + this.DrawLine(new Vector2(num, base.vRangeMin), new Vector2(num2, base.vRangeMin)); + } + if (base.vRangeMax != float.PositiveInfinity) + { + this.DrawLine(new Vector2(num, base.vRangeMax), new Vector2(num2, base.vRangeMax)); + } + GL.End(); + if (base.settings.showAxisLabels) + { + if (base.settings.hTickStyle.distLabel > 0 && axisUiScalars.x > 0f) + { + GUI.color = base.settings.hTickStyle.labelColor; + int levelWithMinSeparation = base.hTicks.GetLevelWithMinSeparation((float)base.settings.hTickStyle.distLabel); + int numberOfDecimalsForMinimumDifference = MathUtils.GetNumberOfDecimalsForMinimumDifference(base.hTicks.GetPeriodOfLevel(levelWithMinSeparation)); + float[] ticksAtLevel3 = base.hTicks.GetTicksAtLevel(levelWithMinSeparation, false); + float[] array = (float[])ticksAtLevel3.Clone(); + float y = Mathf.Floor(base.drawRect.height); + for (int m = 0; m < ticksAtLevel3.Length; m++) + { + array[m] /= axisUiScalars.x; + if (array[m] >= base.hRangeMin && array[m] <= base.hRangeMax) + { + Vector2 vector = base.DrawingToViewTransformPoint(new Vector2(array[m], 0f)); + vector = new Vector2(Mathf.Floor(vector.x), y); + float num3 = ticksAtLevel3[m]; + TextAnchor textAnchor; + Rect position; + if (base.settings.hTickStyle.centerLabel) + { + textAnchor = TextAnchor.UpperCenter; + position = new Rect(vector.x, vector.y - 16f - base.settings.hTickLabelOffset, 1f, 16f); + } + else + { + textAnchor = TextAnchor.UpperLeft; + position = new Rect(vector.x, vector.y - 16f - base.settings.hTickLabelOffset, 50f, 16f); + } + if (this.ms_Styles.labelTickMarksX.alignment != textAnchor) + { + this.ms_Styles.labelTickMarksX.alignment = textAnchor; + } + GUI.Label(position, num3.ToString("n" + numberOfDecimalsForMinimumDifference) + base.settings.hTickStyle.unit, this.ms_Styles.labelTickMarksX); + } + } + } + if (base.settings.vTickStyle.distLabel > 0 && axisUiScalars.y > 0f) + { + GUI.color = base.settings.vTickStyle.labelColor; + int levelWithMinSeparation2 = base.vTicks.GetLevelWithMinSeparation((float)base.settings.vTickStyle.distLabel); + float[] ticksAtLevel4 = base.vTicks.GetTicksAtLevel(levelWithMinSeparation2, false); + float[] array2 = (float[])ticksAtLevel4.Clone(); + int numberOfDecimalsForMinimumDifference2 = MathUtils.GetNumberOfDecimalsForMinimumDifference(base.vTicks.GetPeriodOfLevel(levelWithMinSeparation2)); + string text = "n" + numberOfDecimalsForMinimumDifference2; + this.m_AxisLabelFormat = text; + float width = 35f; + if (!base.settings.vTickStyle.stubs && ticksAtLevel4.Length > 1) + { + float num4 = ticksAtLevel4[1]; + float num5 = ticksAtLevel4[ticksAtLevel4.Length - 1]; + string text2 = num4.ToString(text) + base.settings.vTickStyle.unit; + string text3 = num5.ToString(text) + base.settings.vTickStyle.unit; + width = Mathf.Max(this.ms_Styles.labelTickMarksY.CalcSize(new GUIContent(text2)).x, this.ms_Styles.labelTickMarksY.CalcSize(new GUIContent(text3)).x) + 6f; + } + for (int n = 0; n < ticksAtLevel4.Length; n++) + { + array2[n] /= axisUiScalars.y; + if (array2[n] >= base.vRangeMin && array2[n] <= base.vRangeMax) + { + Vector2 vector2 = base.DrawingToViewTransformPoint(new Vector2(0f, array2[n])); + vector2 = new Vector2(vector2.x, Mathf.Floor(vector2.y)); + float num6 = ticksAtLevel4[n]; + Rect position2; + if (base.settings.vTickStyle.centerLabel) + { + position2 = new Rect(0f, vector2.y - 8f, base.leftmargin - 4f, 16f); + } + else + { + position2 = new Rect(0f, vector2.y - 13f, width, 16f); + } + GUI.Label(position2, num6.ToString(text) + base.settings.vTickStyle.unit, this.ms_Styles.labelTickMarksY); + } + } + } + } + GUI.color = color; + GUI.EndGroup(); + } + } +} diff --git a/UnityEditor/UnityEditor/CurveEditorSettings.cs b/UnityEditor/UnityEditor/CurveEditorSettings.cs new file mode 100644 index 00000000..45cba386 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveEditorSettings.cs @@ -0,0 +1,165 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class CurveEditorSettings + { + private TickStyle m_HTickStyle = new TickStyle(); + private TickStyle m_VTickStyle = new TickStyle(); + private bool m_HRangeLocked; + private bool m_VRangeLocked; + private float m_HRangeMin = float.NegativeInfinity; + private float m_HRangeMax = float.PositiveInfinity; + private float m_VRangeMin = float.NegativeInfinity; + private float m_VRangeMax = float.PositiveInfinity; + public float hTickLabelOffset; + public Color wrapColor = new Color(1f, 1f, 1f, 0.5f); + public bool useFocusColors; + public bool showAxisLabels = true; + public bool allowDraggingCurvesAndRegions = true; + public bool allowDeleteLastKeyInCurve; + private bool m_ScaleWithWindow = true; + private bool m_HSlider = true; + private bool m_VSlider = true; + internal TickStyle hTickStyle + { + get + { + return this.m_HTickStyle; + } + set + { + this.m_HTickStyle = value; + } + } + internal TickStyle vTickStyle + { + get + { + return this.m_VTickStyle; + } + set + { + this.m_VTickStyle = value; + } + } + internal bool hRangeLocked + { + get + { + return this.m_HRangeLocked; + } + set + { + this.m_HRangeLocked = value; + } + } + internal bool vRangeLocked + { + get + { + return this.m_VRangeLocked; + } + set + { + this.m_VRangeLocked = value; + } + } + public float hRangeMin + { + get + { + return this.m_HRangeMin; + } + set + { + this.m_HRangeMin = value; + } + } + public float hRangeMax + { + get + { + return this.m_HRangeMax; + } + set + { + this.m_HRangeMax = value; + } + } + public float vRangeMin + { + get + { + return this.m_VRangeMin; + } + set + { + this.m_VRangeMin = value; + } + } + public float vRangeMax + { + get + { + return this.m_VRangeMax; + } + set + { + this.m_VRangeMax = value; + } + } + public bool hasUnboundedRanges + { + get + { + return this.m_HRangeMin == float.NegativeInfinity || this.m_HRangeMax == float.PositiveInfinity || this.m_VRangeMin == float.NegativeInfinity || this.m_VRangeMax == float.PositiveInfinity; + } + } + internal bool scaleWithWindow + { + get + { + return this.m_ScaleWithWindow; + } + set + { + this.m_ScaleWithWindow = value; + } + } + public bool hSlider + { + get + { + return this.m_HSlider; + } + set + { + this.m_HSlider = value; + } + } + public bool vSlider + { + get + { + return this.m_VSlider; + } + set + { + this.m_VSlider = value; + } + } + public CurveEditorSettings() + { + if (EditorGUIUtility.isProSkin) + { + this.wrapColor = new Color(0.65f, 0.65f, 0.65f, 0.5f); + } + else + { + this.wrapColor = new Color(1f, 1f, 1f, 0.5f); + } + } + } +} diff --git a/UnityEditor/UnityEditor/CurveEditorWindow.cs b/UnityEditor/UnityEditor/CurveEditorWindow.cs new file mode 100644 index 00000000..97f734a9 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveEditorWindow.cs @@ -0,0 +1,532 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class CurveEditorWindow : EditorWindow + { + internal class Styles + { + public GUIStyle curveEditorBackground = "PopupCurveEditorBackground"; + public GUIStyle miniToolbarPopup = "MiniToolbarPopup"; + public GUIStyle miniToolbarButton = "MiniToolbarButtonLeft"; + public GUIStyle curveSwatch = "PopupCurveEditorSwatch"; + public GUIStyle curveSwatchArea = "PopupCurveSwatchBackground"; + public GUIStyle curveWrapPopup = "PopupCurveDropdown"; + } + private const int kPresetsHeight = 46; + private static CurveEditorWindow s_SharedCurveEditor; + private CurveEditor m_CurveEditor; + private AnimationCurve m_Curve; + private Color m_Color; + private CurvePresetsContentsForPopupWindow m_CurvePresets; + private GUIContent m_GUIContent = new GUIContent(); + [SerializeField] + private GUIView delegateView; + internal static CurveEditorWindow.Styles ms_Styles; + public static CurveEditorWindow instance + { + get + { + if (!CurveEditorWindow.s_SharedCurveEditor) + { + CurveEditorWindow.s_SharedCurveEditor = ScriptableObject.CreateInstance(); + } + return CurveEditorWindow.s_SharedCurveEditor; + } + } + public string currentPresetLibrary + { + get + { + this.InitCurvePresets(); + return this.m_CurvePresets.currentPresetLibrary; + } + set + { + this.InitCurvePresets(); + this.m_CurvePresets.currentPresetLibrary = value; + } + } + public static AnimationCurve curve + { + get + { + return CurveEditorWindow.instance.m_Curve; + } + set + { + if (value == null) + { + CurveEditorWindow.instance.m_Curve = null; + } + else + { + CurveEditorWindow.instance.m_Curve = value; + CurveEditorWindow.instance.RefreshShownCurves(); + } + } + } + public static Color color + { + get + { + return CurveEditorWindow.instance.m_Color; + } + set + { + CurveEditorWindow.instance.m_Color = value; + CurveEditorWindow.instance.RefreshShownCurves(); + } + } + public static bool visible + { + get + { + return CurveEditorWindow.s_SharedCurveEditor != null; + } + } + private CurveLibraryType curveLibraryType + { + get + { + if (this.m_CurveEditor.settings.hasUnboundedRanges) + { + return CurveLibraryType.Unbounded; + } + return CurveLibraryType.NormalizedZeroToOne; + } + } + private void OnEnable() + { + CurveEditorWindow.s_SharedCurveEditor = this; + this.Init(null); + this.m_CurveEditor.OnEnable(); + } + private void Init(CurveEditorSettings settings) + { + this.m_CurveEditor = new CurveEditor(this.GetCurveEditorRect(), this.GetCurveWrapperArray(), true); + this.m_CurveEditor.curvesUpdated = new CurveEditor.CallbackFunction(this.UpdateCurve); + this.m_CurveEditor.scaleWithWindow = true; + this.m_CurveEditor.margin = 40f; + if (settings != null) + { + this.m_CurveEditor.settings = settings; + } + this.m_CurveEditor.settings.hTickLabelOffset = 10f; + bool horizontally = true; + bool vertically = true; + if (this.m_CurveEditor.settings.hRangeMin != float.NegativeInfinity && this.m_CurveEditor.settings.hRangeMax != float.PositiveInfinity) + { + this.m_CurveEditor.SetShownHRangeInsideMargins(this.m_CurveEditor.settings.hRangeMin, this.m_CurveEditor.settings.hRangeMax); + horizontally = false; + } + if (this.m_CurveEditor.settings.vRangeMin != float.NegativeInfinity && this.m_CurveEditor.settings.vRangeMax != float.PositiveInfinity) + { + this.m_CurveEditor.SetShownVRangeInsideMargins(this.m_CurveEditor.settings.vRangeMin, this.m_CurveEditor.settings.vRangeMax); + vertically = false; + } + this.m_CurveEditor.FrameSelected(horizontally, vertically); + } + private bool GetNormalizationRect(out Rect normalizationRect) + { + normalizationRect = default(Rect); + if (this.m_CurveEditor.settings.hasUnboundedRanges) + { + return false; + } + normalizationRect = new Rect(this.m_CurveEditor.settings.hRangeMin, this.m_CurveEditor.settings.vRangeMin, this.m_CurveEditor.settings.hRangeMax - this.m_CurveEditor.settings.hRangeMin, this.m_CurveEditor.settings.vRangeMax - this.m_CurveEditor.settings.vRangeMin); + return true; + } + private static Keyframe[] CopyAndScaleCurveKeys(Keyframe[] orgKeys, Rect rect, bool realToNormalized) + { + if (rect.width == 0f || rect.height == 0f || float.IsInfinity(rect.width) || float.IsInfinity(rect.height)) + { + Debug.LogError("CopyAndScaleCurve: Invalid scale: " + rect); + return orgKeys; + } + Keyframe[] array = new Keyframe[orgKeys.Length]; + if (realToNormalized) + { + for (int i = 0; i < array.Length; i++) + { + array[i].time = (orgKeys[i].time - rect.xMin) / rect.width; + array[i].value = (orgKeys[i].value - rect.yMin) / rect.height; + } + } + else + { + for (int j = 0; j < array.Length; j++) + { + array[j].time = orgKeys[j].time * rect.width + rect.xMin; + array[j].value = orgKeys[j].value * rect.height + rect.yMin; + } + } + return array; + } + private void InitCurvePresets() + { + if (this.m_CurvePresets == null) + { + Action presetSelectedCallback = delegate(AnimationCurve presetCurve) + { + this.ValidateCurveLibraryTypeAndScale(); + Rect rect; + if (this.GetNormalizationRect(out rect)) + { + bool realToNormalized = false; + this.m_Curve.keys = CurveEditorWindow.CopyAndScaleCurveKeys(presetCurve.keys, rect, realToNormalized); + } + else + { + this.m_Curve.keys = presetCurve.keys; + } + this.m_Curve.postWrapMode = presetCurve.postWrapMode; + this.m_Curve.preWrapMode = presetCurve.preWrapMode; + this.m_CurveEditor.SelectNone(); + this.RefreshShownCurves(); + this.SendEvent("CurveChanged", true); + }; + AnimationCurve animCurve = null; + this.m_CurvePresets = new CurvePresetsContentsForPopupWindow(animCurve, this.curveLibraryType, presetSelectedCallback); + this.m_CurvePresets.InitIfNeeded(); + } + } + private void OnDestroy() + { + this.m_CurvePresets.GetPresetLibraryEditor().UnloadUsedLibraries(); + } + private void OnDisable() + { + this.m_CurveEditor.OnDisable(); + if (CurveEditorWindow.s_SharedCurveEditor == this) + { + CurveEditorWindow.s_SharedCurveEditor = null; + } + else + { + if (!this.Equals(CurveEditorWindow.s_SharedCurveEditor)) + { + throw new ApplicationException("s_SharedCurveEditor does not equal this"); + } + } + } + private void RefreshShownCurves() + { + this.m_CurveEditor.animationCurves = this.GetCurveWrapperArray(); + } + public void Show(GUIView viewToUpdate, CurveEditorSettings settings) + { + this.delegateView = viewToUpdate; + this.Init(settings); + base.ShowAuxWindow(); + base.title = "Curve"; + base.minSize = new Vector2(240f, 286f); + base.maxSize = new Vector2(10000f, 10000f); + } + private CurveWrapper[] GetCurveWrapperArray() + { + if (this.m_Curve == null) + { + return new CurveWrapper[0]; + } + CurveWrapper curveWrapper = new CurveWrapper(); + curveWrapper.id = "Curve".GetHashCode(); + curveWrapper.groupId = -1; + curveWrapper.color = this.m_Color; + curveWrapper.hidden = false; + curveWrapper.readOnly = false; + curveWrapper.renderer = new NormalCurveRenderer(this.m_Curve); + curveWrapper.renderer.SetWrap(this.m_Curve.preWrapMode, this.m_Curve.postWrapMode); + return new CurveWrapper[] + { + curveWrapper + }; + } + private Rect GetCurveEditorRect() + { + return new Rect(0f, 0f, base.position.width, base.position.height - 46f); + } + internal static Keyframe[] GetLinearKeys() + { + Keyframe[] array = new Keyframe[] + { + new Keyframe(0f, 0f, 1f, 1f), + new Keyframe(1f, 1f, 1f, 1f) + }; + for (int i = 0; i < 2; i++) + { + CurveUtility.SetKeyBroken(ref array[i], false); + CurveUtility.SetKeyTangentMode(ref array[i], 0, TangentMode.Smooth); + CurveUtility.SetKeyTangentMode(ref array[i], 1, TangentMode.Smooth); + } + return array; + } + internal static Keyframe[] GetLinearMirrorKeys() + { + Keyframe[] array = new Keyframe[] + { + new Keyframe(0f, 1f, -1f, -1f), + new Keyframe(1f, 0f, -1f, -1f) + }; + for (int i = 0; i < 2; i++) + { + CurveUtility.SetKeyBroken(ref array[i], false); + CurveUtility.SetKeyTangentMode(ref array[i], 0, TangentMode.Smooth); + CurveUtility.SetKeyTangentMode(ref array[i], 1, TangentMode.Smooth); + } + return array; + } + internal static Keyframe[] GetEaseInKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 0f, 0f, 0f), + new Keyframe(1f, 1f, 2f, 2f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetEaseInMirrorKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 1f, -2f, -2f), + new Keyframe(1f, 0f, 0f, 0f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetEaseOutKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 0f, 2f, 2f), + new Keyframe(1f, 1f, 0f, 0f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetEaseOutMirrorKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 1f, 0f, 0f), + new Keyframe(1f, 0f, -2f, -2f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetEaseInOutKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 0f, 0f, 0f), + new Keyframe(1f, 1f, 0f, 0f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetEaseInOutMirrorKeys() + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, 1f, 0f, 0f), + new Keyframe(1f, 0f, 0f, 0f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static Keyframe[] GetConstantKeys(float value) + { + Keyframe[] result = new Keyframe[] + { + new Keyframe(0f, value, 0f, 0f), + new Keyframe(1f, value, 0f, 0f) + }; + CurveEditorWindow.SetSmoothEditable(ref result); + return result; + } + internal static void SetSmoothEditable(ref Keyframe[] keys) + { + for (int i = 0; i < keys.Length; i++) + { + CurveUtility.SetKeyBroken(ref keys[i], false); + CurveUtility.SetKeyTangentMode(ref keys[i], 0, TangentMode.Editable); + CurveUtility.SetKeyTangentMode(ref keys[i], 1, TangentMode.Editable); + } + } + private void OnGUI() + { + bool flag = Event.current.type == EventType.MouseUp; + if (this.delegateView == null) + { + this.m_Curve = null; + } + if (CurveEditorWindow.ms_Styles == null) + { + CurveEditorWindow.ms_Styles = new CurveEditorWindow.Styles(); + } + this.m_CurveEditor.rect = this.GetCurveEditorRect(); + this.m_CurveEditor.hRangeLocked = Event.current.shift; + this.m_CurveEditor.vRangeLocked = EditorGUI.actionKey; + GUI.changed = false; + GUI.Label(this.m_CurveEditor.drawRect, GUIContent.none, CurveEditorWindow.ms_Styles.curveEditorBackground); + this.m_CurveEditor.BeginViewGUI(); + this.m_CurveEditor.GridGUI(); + this.m_CurveEditor.CurveGUI(); + this.DoWrapperPopups(); + this.m_CurveEditor.EndViewGUI(); + GUI.Box(new Rect(0f, base.position.height - 46f, base.position.width, 46f), string.Empty, CurveEditorWindow.ms_Styles.curveSwatchArea); + Color color = this.m_Color; + color.a *= 0.6f; + float num = base.position.height - 46f + 10.5f; + this.InitCurvePresets(); + CurvePresetLibrary currentLib = this.m_CurvePresets.GetPresetLibraryEditor().GetCurrentLib(); + if (currentLib != null) + { + for (int i = 0; i < currentLib.Count(); i++) + { + Rect rect = new Rect(45f + 45f * (float)i, num, 40f, 25f); + this.m_GUIContent.tooltip = currentLib.GetName(i); + if (GUI.Button(rect, this.m_GUIContent, CurveEditorWindow.ms_Styles.curveSwatch)) + { + AnimationCurve animationCurve = currentLib.GetPreset(i) as AnimationCurve; + this.m_Curve.keys = animationCurve.keys; + this.m_Curve.postWrapMode = animationCurve.postWrapMode; + this.m_Curve.preWrapMode = animationCurve.preWrapMode; + this.m_CurveEditor.SelectNone(); + this.SendEvent("CurveChanged", true); + } + if (Event.current.type == EventType.Repaint) + { + currentLib.Draw(rect, i); + } + if (rect.xMax > base.position.width - 90f) + { + break; + } + } + } + Rect rect2 = new Rect(25f, num + 5f, 20f, 20f); + this.PresetDropDown(rect2); + if (Event.current.type == EventType.Used && flag) + { + this.DoUpdateCurve(false); + this.SendEvent("CurveChangeCompleted", true); + } + else + { + if (Event.current.type != EventType.Layout && Event.current.type != EventType.Repaint) + { + this.DoUpdateCurve(true); + } + } + } + private void PresetDropDown(Rect rect) + { + if (EditorGUI.ButtonMouseDown(rect, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText) && this.m_Curve != null) + { + if (this.m_CurvePresets == null) + { + Debug.LogError("Curve presets error"); + return; + } + this.ValidateCurveLibraryTypeAndScale(); + AnimationCurve animationCurve = new AnimationCurve(); + Rect rect2; + if (this.GetNormalizationRect(out rect2)) + { + bool realToNormalized = true; + animationCurve.keys = CurveEditorWindow.CopyAndScaleCurveKeys(this.m_Curve.keys, rect2, realToNormalized); + } + else + { + animationCurve = new AnimationCurve(this.m_Curve.keys); + } + animationCurve.postWrapMode = this.m_Curve.postWrapMode; + animationCurve.preWrapMode = this.m_Curve.preWrapMode; + this.m_CurvePresets.curveToSaveAsPreset = animationCurve; + PopupWindow.Show(rect, this.m_CurvePresets); + } + } + private void ValidateCurveLibraryTypeAndScale() + { + Rect rect; + if (this.GetNormalizationRect(out rect)) + { + if (this.curveLibraryType != CurveLibraryType.NormalizedZeroToOne) + { + Debug.LogError("When having a normalize rect we should be using curve library type: NormalizedZeroToOne (normalizationRect: " + rect + ")"); + } + } + else + { + if (this.curveLibraryType != CurveLibraryType.Unbounded) + { + Debug.LogError("When NOT having a normalize rect we should be using library type: Unbounded"); + } + } + } + public void UpdateCurve() + { + this.DoUpdateCurve(false); + } + private void DoUpdateCurve(bool exitGUI) + { + if (this.m_CurveEditor.animationCurves.Length > 0 && this.m_CurveEditor.animationCurves[0] != null && this.m_CurveEditor.animationCurves[0].changed) + { + this.m_CurveEditor.animationCurves[0].changed = false; + this.SendEvent("CurveChanged", exitGUI); + } + } + private void DoWrapperPopups() + { + if (this.m_Curve != null && this.m_Curve.length >= 2) + { + Color contentColor = GUI.contentColor; + GUI.contentColor = Color.white; + float num = 60f; + Keyframe keyframe = this.m_Curve.keys[0]; + Vector3 lhs = new Vector3(keyframe.time, keyframe.value); + lhs = this.m_CurveEditor.DrawingToViewTransformPoint(lhs); + Rect position = new Rect(lhs.x - num - 6f, lhs.y, num, 17f); + WrapMode wrapMode = (this.m_Curve == null) ? WrapMode.Default : this.m_Curve.preWrapMode; + wrapMode = (WrapMode)EditorGUI.EnumPopup(position, (WrapModeFixedCurve)wrapMode, CurveEditorWindow.ms_Styles.curveWrapPopup); + if (this.m_Curve != null && wrapMode != this.m_Curve.preWrapMode) + { + this.m_Curve.preWrapMode = wrapMode; + this.RefreshShownCurves(); + this.SendEvent("CurveChanged", true); + } + keyframe = this.m_Curve.keys[this.m_Curve.length - 1]; + lhs = new Vector3(keyframe.time, keyframe.value); + lhs = this.m_CurveEditor.DrawingToViewTransformPoint(lhs); + position = new Rect(lhs.x + 6f, lhs.y, num, 17f); + wrapMode = ((this.m_Curve == null) ? WrapMode.Default : this.m_Curve.postWrapMode); + wrapMode = (WrapMode)EditorGUI.EnumPopup(position, (WrapModeFixedCurve)wrapMode, CurveEditorWindow.ms_Styles.curveWrapPopup); + if (this.m_Curve != null && wrapMode != this.m_Curve.postWrapMode) + { + this.m_Curve.postWrapMode = wrapMode; + this.RefreshShownCurves(); + this.SendEvent("CurveChanged", true); + } + GUI.contentColor = contentColor; + } + } + private void SendEvent(string eventName, bool exitGUI) + { + if (this.delegateView) + { + Event e = EditorGUIUtility.CommandEvent(eventName); + base.Repaint(); + this.delegateView.SendEvent(e); + if (exitGUI) + { + GUIUtility.ExitGUI(); + } + } + GUI.changed = true; + } + } +} diff --git a/UnityEditor/UnityEditor/CurveLibraryType.cs b/UnityEditor/UnityEditor/CurveLibraryType.cs new file mode 100644 index 00000000..4c6abaea --- /dev/null +++ b/UnityEditor/UnityEditor/CurveLibraryType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum CurveLibraryType + { + Unbounded, + NormalizedZeroToOne + } +} diff --git a/UnityEditor/UnityEditor/CurveMenuManager.cs b/UnityEditor/UnityEditor/CurveMenuManager.cs new file mode 100644 index 00000000..a4809503 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveMenuManager.cs @@ -0,0 +1,253 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class CurveMenuManager + { + private CurveUpdater updater; + public CurveMenuManager(CurveUpdater updater) + { + this.updater = updater; + } + public void AddTangentMenuItems(GenericMenu menu, List keyList) + { + bool flag = keyList.Count > 0; + bool on = flag; + bool on2 = flag; + bool on3 = flag; + bool on4 = flag; + bool flag2 = flag; + bool flag3 = flag; + bool flag4 = flag; + bool flag5 = flag; + bool flag6 = flag; + bool flag7 = flag; + foreach (KeyIdentifier current in keyList) + { + Keyframe keyframe = current.keyframe; + TangentMode keyTangentMode = CurveUtility.GetKeyTangentMode(keyframe, 0); + TangentMode keyTangentMode2 = CurveUtility.GetKeyTangentMode(keyframe, 1); + bool keyBroken = CurveUtility.GetKeyBroken(keyframe); + if (keyTangentMode != TangentMode.Smooth || keyTangentMode2 != TangentMode.Smooth) + { + on = false; + } + if (keyBroken || keyTangentMode != TangentMode.Editable || keyTangentMode2 != TangentMode.Editable) + { + on2 = false; + } + if (keyBroken || keyTangentMode != TangentMode.Editable || keyframe.inTangent != 0f || keyTangentMode2 != TangentMode.Editable || keyframe.outTangent != 0f) + { + on3 = false; + } + if (!keyBroken) + { + on4 = false; + } + if (!keyBroken || keyTangentMode != TangentMode.Editable) + { + flag2 = false; + } + if (!keyBroken || keyTangentMode != TangentMode.Linear) + { + flag3 = false; + } + if (!keyBroken || keyTangentMode != TangentMode.Stepped) + { + flag4 = false; + } + if (!keyBroken || keyTangentMode2 != TangentMode.Editable) + { + flag5 = false; + } + if (!keyBroken || keyTangentMode2 != TangentMode.Linear) + { + flag6 = false; + } + if (!keyBroken || keyTangentMode2 != TangentMode.Stepped) + { + flag7 = false; + } + } + if (flag) + { + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupAuto"), on, new GenericMenu.MenuFunction2(this.SetSmooth), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupFreeSmooth"), on2, new GenericMenu.MenuFunction2(this.SetEditable), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupFlat"), on3, new GenericMenu.MenuFunction2(this.SetFlat), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupBroken"), on4, new GenericMenu.MenuFunction2(this.SetBroken), keyList); + menu.AddSeparator(string.Empty); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Free"), flag2, new GenericMenu.MenuFunction2(this.SetLeftEditable), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Linear"), flag3, new GenericMenu.MenuFunction2(this.SetLeftLinear), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Constant"), flag4, new GenericMenu.MenuFunction2(this.SetLeftConstant), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Free"), flag5, new GenericMenu.MenuFunction2(this.SetRightEditable), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Linear"), flag6, new GenericMenu.MenuFunction2(this.SetRightLinear), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Constant"), flag7, new GenericMenu.MenuFunction2(this.SetRightConstant), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Free"), flag5 && flag2, new GenericMenu.MenuFunction2(this.SetBothEditable), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Linear"), flag6 && flag3, new GenericMenu.MenuFunction2(this.SetBothLinear), keyList); + menu.AddItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Constant"), flag7 && flag4, new GenericMenu.MenuFunction2(this.SetBothConstant), keyList); + } + else + { + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupAuto")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupFreeSmooth")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupFlat")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupBroken")); + menu.AddSeparator(string.Empty); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Free")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Linear")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupLeftTangent/Constant")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Free")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Linear")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupRightTangent/Constant")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Free")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Linear")); + menu.AddDisabledItem(EditorGUIUtility.TextContent("CurveKeyPopupBothTangents/Constant")); + } + } + public void SetSmooth(object keysToSet) + { + this.SetBoth(TangentMode.Smooth, (List)keysToSet); + } + public void SetEditable(object keysToSet) + { + this.SetBoth(TangentMode.Editable, (List)keysToSet); + } + public void SetFlat(object keysToSet) + { + this.SetBoth(TangentMode.Editable, (List)keysToSet); + this.Flatten((List)keysToSet); + } + public void SetBoth(TangentMode mode, List keysToSet) + { + List list = new List(); + foreach (KeyIdentifier current in keysToSet) + { + AnimationCurve curve = current.curve; + Keyframe keyframe = current.keyframe; + CurveUtility.SetKeyBroken(ref keyframe, false); + CurveUtility.SetKeyTangentMode(ref keyframe, 1, mode); + CurveUtility.SetKeyTangentMode(ref keyframe, 0, mode); + if (mode == TangentMode.Editable) + { + float num = CurveUtility.CalculateSmoothTangent(keyframe); + keyframe.inTangent = num; + keyframe.outTangent = num; + } + curve.MoveKey(current.key, keyframe); + CurveUtility.UpdateTangentsFromModeSurrounding(curve, current.key); + list.Add(current.curveId); + } + this.updater.UpdateCurves(list, "Set Tangents"); + } + public void Flatten(List keysToSet) + { + List list = new List(); + foreach (KeyIdentifier current in keysToSet) + { + AnimationCurve curve = current.curve; + Keyframe keyframe = current.keyframe; + keyframe.inTangent = 0f; + keyframe.outTangent = 0f; + curve.MoveKey(current.key, keyframe); + CurveUtility.UpdateTangentsFromModeSurrounding(curve, current.key); + list.Add(current.curveId); + } + this.updater.UpdateCurves(list, "Set Tangents"); + } + public void SetBroken(object _keysToSet) + { + List list = (List)_keysToSet; + List list2 = new List(); + foreach (KeyIdentifier current in list) + { + AnimationCurve curve = current.curve; + Keyframe keyframe = current.keyframe; + CurveUtility.SetKeyBroken(ref keyframe, true); + if (CurveUtility.GetKeyTangentMode(keyframe, 1) == TangentMode.Smooth) + { + CurveUtility.SetKeyTangentMode(ref keyframe, 1, TangentMode.Editable); + } + if (CurveUtility.GetKeyTangentMode(keyframe, 0) == TangentMode.Smooth) + { + CurveUtility.SetKeyTangentMode(ref keyframe, 0, TangentMode.Editable); + } + curve.MoveKey(current.key, keyframe); + CurveUtility.UpdateTangentsFromModeSurrounding(curve, current.key); + list2.Add(current.curveId); + } + this.updater.UpdateCurves(list2, "Set Tangents"); + } + public void SetLeftEditable(object keysToSet) + { + this.SetTangent(0, TangentMode.Editable, (List)keysToSet); + } + public void SetLeftLinear(object keysToSet) + { + this.SetTangent(0, TangentMode.Linear, (List)keysToSet); + } + public void SetLeftConstant(object keysToSet) + { + this.SetTangent(0, TangentMode.Stepped, (List)keysToSet); + } + public void SetRightEditable(object keysToSet) + { + this.SetTangent(1, TangentMode.Editable, (List)keysToSet); + } + public void SetRightLinear(object keysToSet) + { + this.SetTangent(1, TangentMode.Linear, (List)keysToSet); + } + public void SetRightConstant(object keysToSet) + { + this.SetTangent(1, TangentMode.Stepped, (List)keysToSet); + } + public void SetBothEditable(object keysToSet) + { + this.SetTangent(2, TangentMode.Editable, (List)keysToSet); + } + public void SetBothLinear(object keysToSet) + { + this.SetTangent(2, TangentMode.Linear, (List)keysToSet); + } + public void SetBothConstant(object keysToSet) + { + this.SetTangent(2, TangentMode.Stepped, (List)keysToSet); + } + public void SetTangent(int leftRight, TangentMode mode, List keysToSet) + { + List list = new List(); + foreach (KeyIdentifier current in keysToSet) + { + AnimationCurve curve = current.curve; + Keyframe keyframe = current.keyframe; + CurveUtility.SetKeyBroken(ref keyframe, true); + if (leftRight == 2) + { + CurveUtility.SetKeyTangentMode(ref keyframe, 0, mode); + CurveUtility.SetKeyTangentMode(ref keyframe, 1, mode); + } + else + { + CurveUtility.SetKeyTangentMode(ref keyframe, leftRight, mode); + if (CurveUtility.GetKeyTangentMode(keyframe, 1 - leftRight) == TangentMode.Smooth) + { + CurveUtility.SetKeyTangentMode(ref keyframe, 1 - leftRight, TangentMode.Editable); + } + } + if (mode == TangentMode.Stepped && (leftRight == 0 || leftRight == 2)) + { + keyframe.inTangent = float.PositiveInfinity; + } + if (mode == TangentMode.Stepped && (leftRight == 1 || leftRight == 2)) + { + keyframe.outTangent = float.PositiveInfinity; + } + curve.MoveKey(current.key, keyframe); + CurveUtility.UpdateTangentsFromModeSurrounding(curve, current.key); + list.Add(current.curveId); + } + this.updater.UpdateCurves(list, "Set Tangents"); + } + } +} diff --git a/UnityEditor/UnityEditor/CurvePresetLibrary.cs b/UnityEditor/UnityEditor/CurvePresetLibrary.cs new file mode 100644 index 00000000..c04fd50b --- /dev/null +++ b/UnityEditor/UnityEditor/CurvePresetLibrary.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class CurvePresetLibrary : PresetLibrary + { + [Serializable] + private class CurvePreset + { + [SerializeField] + private string m_Name; + [SerializeField] + private AnimationCurve m_Curve; + public AnimationCurve curve + { + get + { + return this.m_Curve; + } + set + { + this.m_Curve = value; + } + } + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public CurvePreset(AnimationCurve preset, string presetName) + { + this.curve = preset; + this.name = presetName; + } + public CurvePreset(AnimationCurve preset, AnimationCurve preset2, string presetName) + { + this.curve = preset; + this.name = presetName; + } + } + [SerializeField] + private List m_Presets = new List(); + public override int Count() + { + return this.m_Presets.Count; + } + public override object GetPreset(int index) + { + return this.m_Presets[index].curve; + } + public override void Add(object presetObject, string presetName) + { + AnimationCurve animationCurve = presetObject as AnimationCurve; + if (animationCurve == null) + { + Debug.LogError("Wrong type used in CurvePresetLibrary"); + return; + } + AnimationCurve animationCurve2 = new AnimationCurve(animationCurve.keys); + animationCurve2.preWrapMode = animationCurve.preWrapMode; + animationCurve2.postWrapMode = animationCurve.postWrapMode; + this.m_Presets.Add(new CurvePresetLibrary.CurvePreset(animationCurve2, presetName)); + } + public override void Replace(int index, object newPresetObject) + { + AnimationCurve animationCurve = newPresetObject as AnimationCurve; + if (animationCurve == null) + { + Debug.LogError("Wrong type used in CurvePresetLibrary"); + return; + } + AnimationCurve animationCurve2 = new AnimationCurve(animationCurve.keys); + animationCurve2.preWrapMode = animationCurve.preWrapMode; + animationCurve2.postWrapMode = animationCurve.postWrapMode; + this.m_Presets[index].curve = animationCurve2; + } + public override void Remove(int index) + { + this.m_Presets.RemoveAt(index); + } + public override void Move(int index, int destIndex, bool insertAfterDestIndex) + { + PresetLibraryHelpers.MoveListItem(this.m_Presets, index, destIndex, insertAfterDestIndex); + } + public override void Draw(Rect rect, int index) + { + this.DrawInternal(rect, this.m_Presets[index].curve); + } + public override void Draw(Rect rect, object presetObject) + { + this.DrawInternal(rect, presetObject as AnimationCurve); + } + private void DrawInternal(Rect rect, AnimationCurve animCurve) + { + if (animCurve == null) + { + return; + } + EditorGUIUtility.DrawCurveSwatch(rect, animCurve, null, new Color(0.8f, 0.8f, 0.8f, 1f), EditorGUI.kCurveBGColor); + } + public override string GetName(int index) + { + return this.m_Presets[index].name; + } + public override void SetName(int index, string presetName) + { + this.m_Presets[index].name = presetName; + } + } +} diff --git a/UnityEditor/UnityEditor/CurvePresetLibraryEditor.cs b/UnityEditor/UnityEditor/CurvePresetLibraryEditor.cs new file mode 100644 index 00000000..73d8e172 --- /dev/null +++ b/UnityEditor/UnityEditor/CurvePresetLibraryEditor.cs @@ -0,0 +1,96 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(CurvePresetLibrary))] + internal class CurvePresetLibraryEditor : Editor + { + private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; + private CurveLibraryType m_CurveLibraryType; + public void OnEnable() + { + string assetPath = AssetDatabase.GetAssetPath(this.target.GetInstanceID()); + this.m_CurveLibraryType = this.GetCurveLibraryTypeFromExtension(Path.GetExtension(assetPath).TrimStart(new char[] + { + '.' + })); + this.m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(this.target, this.GetHeader(), new Action(this.OnEditButtonClicked)); + this.m_GenericPresetLibraryInspector.presetSize = new Vector2(72f, 20f); + this.m_GenericPresetLibraryInspector.lineSpacing = 5f; + } + public void OnDestroy() + { + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnDestroy(); + } + } + public override void OnInspectorGUI() + { + string basePrefText = CurvePresetsContentsForPopupWindow.GetBasePrefText(this.m_CurveLibraryType); + this.m_GenericPresetLibraryInspector.itemViewMode = PresetLibraryEditorState.GetItemViewMode(basePrefText); + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnInspectorGUI(); + } + } + private void OnEditButtonClicked(string libraryPath) + { + Rect curveRanges = this.GetCurveRanges(); + CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); + if (curveRanges.width > 0f && curveRanges.height > 0f && curveRanges.width != float.PositiveInfinity && curveRanges.height != float.PositiveInfinity) + { + curveEditorSettings.hRangeMin = curveRanges.xMin; + curveEditorSettings.hRangeMax = curveRanges.xMax; + curveEditorSettings.vRangeMin = curveRanges.yMin; + curveEditorSettings.vRangeMax = curveRanges.yMax; + } + CurveEditorWindow.curve = new AnimationCurve(); + CurveEditorWindow.color = new Color(0f, 0.8f, 0f); + CurveEditorWindow.instance.Show(GUIView.current, curveEditorSettings); + CurveEditorWindow.instance.currentPresetLibrary = libraryPath; + } + private string GetHeader() + { + CurveLibraryType curveLibraryType = this.m_CurveLibraryType; + if (curveLibraryType == CurveLibraryType.Unbounded) + { + return "Curve Preset Library"; + } + if (curveLibraryType != CurveLibraryType.NormalizedZeroToOne) + { + return "Curve Preset Library ?"; + } + return "Curve Preset Library (Normalized 0 - 1)"; + } + private Rect GetCurveRanges() + { + CurveLibraryType curveLibraryType = this.m_CurveLibraryType; + if (curveLibraryType == CurveLibraryType.Unbounded) + { + return default(Rect); + } + if (curveLibraryType != CurveLibraryType.NormalizedZeroToOne) + { + return default(Rect); + } + return new Rect(0f, 0f, 1f, 1f); + } + private CurveLibraryType GetCurveLibraryTypeFromExtension(string extension) + { + string curveLibraryExtension = PresetLibraryLocations.GetCurveLibraryExtension(true); + string curveLibraryExtension2 = PresetLibraryLocations.GetCurveLibraryExtension(false); + if (extension.Equals(curveLibraryExtension, StringComparison.OrdinalIgnoreCase)) + { + return CurveLibraryType.NormalizedZeroToOne; + } + if (extension.Equals(curveLibraryExtension2, StringComparison.OrdinalIgnoreCase)) + { + return CurveLibraryType.Unbounded; + } + Debug.LogError("Extension not recognized!"); + return CurveLibraryType.NormalizedZeroToOne; + } + } +} diff --git a/UnityEditor/UnityEditor/CurvePresetsContentsForPopupWindow.cs b/UnityEditor/UnityEditor/CurvePresetsContentsForPopupWindow.cs new file mode 100644 index 00000000..ba650aab --- /dev/null +++ b/UnityEditor/UnityEditor/CurvePresetsContentsForPopupWindow.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class CurvePresetsContentsForPopupWindow : PopupWindowContent + { + private PresetLibraryEditor m_CurveLibraryEditor; + private PresetLibraryEditorState m_CurveLibraryEditorState; + private AnimationCurve m_Curve; + private CurveLibraryType m_CurveLibraryType; + private bool m_WantsToClose; + private Action m_PresetSelectedCallback; + public AnimationCurve curveToSaveAsPreset + { + get + { + return this.m_Curve; + } + set + { + this.m_Curve = value; + } + } + public string currentPresetLibrary + { + get + { + this.InitIfNeeded(); + return this.m_CurveLibraryEditor.currentLibraryWithoutExtension; + } + set + { + this.InitIfNeeded(); + this.m_CurveLibraryEditor.currentLibraryWithoutExtension = value; + } + } + public CurvePresetsContentsForPopupWindow(AnimationCurve animCurve, CurveLibraryType curveLibraryType, Action presetSelectedCallback) + { + this.m_CurveLibraryType = curveLibraryType; + this.m_Curve = animCurve; + this.m_PresetSelectedCallback = presetSelectedCallback; + } + public static string GetBasePrefText(CurveLibraryType curveLibraryType) + { + return CurvePresetsContentsForPopupWindow.GetExtension(curveLibraryType); + } + private static string GetExtension(CurveLibraryType curveLibraryType) + { + if (curveLibraryType == CurveLibraryType.Unbounded) + { + return PresetLibraryLocations.GetCurveLibraryExtension(false); + } + if (curveLibraryType != CurveLibraryType.NormalizedZeroToOne) + { + Debug.LogError("Enum not handled!"); + return "curves"; + } + return PresetLibraryLocations.GetCurveLibraryExtension(true); + } + public override void OnClose() + { + this.m_CurveLibraryEditorState.TransferEditorPrefsState(false); + } + public PresetLibraryEditor GetPresetLibraryEditor() + { + return this.m_CurveLibraryEditor; + } + public void InitIfNeeded() + { + if (this.m_CurveLibraryEditorState == null) + { + this.m_CurveLibraryEditorState = new PresetLibraryEditorState(CurvePresetsContentsForPopupWindow.GetBasePrefText(this.m_CurveLibraryType)); + this.m_CurveLibraryEditorState.TransferEditorPrefsState(true); + } + if (this.m_CurveLibraryEditor == null) + { + ScriptableObjectSaveLoadHelper helper = new ScriptableObjectSaveLoadHelper(CurvePresetsContentsForPopupWindow.GetExtension(this.m_CurveLibraryType), SaveType.Text); + this.m_CurveLibraryEditor = new PresetLibraryEditor(helper, this.m_CurveLibraryEditorState, new Action(this.ItemClickedCallback)); + PresetLibraryEditor expr_6E = this.m_CurveLibraryEditor; + expr_6E.addDefaultPresets = (Action)Delegate.Combine(expr_6E.addDefaultPresets, new Action(this.AddDefaultPresetsToLibrary)); + PresetLibraryEditor expr_95 = this.m_CurveLibraryEditor; + expr_95.presetsWasReordered = (Action)Delegate.Combine(expr_95.presetsWasReordered, new Action(this.OnPresetsWasReordered)); + this.m_CurveLibraryEditor.previewAspect = 4f; + this.m_CurveLibraryEditor.minMaxPreviewHeight = new Vector2(24f, 24f); + this.m_CurveLibraryEditor.showHeader = true; + } + } + private void OnPresetsWasReordered() + { + InternalEditorUtility.RepaintAllViews(); + } + public override void OnGUI(Rect rect) + { + this.InitIfNeeded(); + this.m_CurveLibraryEditor.OnGUI(rect, this.m_Curve); + if (this.m_WantsToClose) + { + base.editorWindow.Close(); + } + } + private void ItemClickedCallback(int clickCount, object presetObject) + { + AnimationCurve animationCurve = presetObject as AnimationCurve; + if (animationCurve == null) + { + Debug.LogError("Incorrect object passed " + presetObject); + } + this.m_PresetSelectedCallback(animationCurve); + } + public override Vector2 GetWindowSize() + { + return new Vector2(240f, 330f); + } + private void AddDefaultPresetsToLibrary(PresetLibrary presetLibrary) + { + CurvePresetLibrary curvePresetLibrary = presetLibrary as CurvePresetLibrary; + if (curvePresetLibrary == null) + { + Debug.Log("Incorrect preset library, should be a CurvePresetLibrary but was a " + presetLibrary.GetType()); + return; + } + foreach (AnimationCurve current in new List + { + new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), + new AnimationCurve(CurveEditorWindow.GetLinearKeys()), + new AnimationCurve(CurveEditorWindow.GetEaseInKeys()), + new AnimationCurve(CurveEditorWindow.GetEaseOutKeys()), + new AnimationCurve(CurveEditorWindow.GetEaseInOutKeys()) + }) + { + curvePresetLibrary.Add(current, string.Empty); + } + } + } +} diff --git a/UnityEditor/UnityEditor/CurveRenderer.cs b/UnityEditor/UnityEditor/CurveRenderer.cs new file mode 100644 index 00000000..d06564eb --- /dev/null +++ b/UnityEditor/UnityEditor/CurveRenderer.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +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); + } +} diff --git a/UnityEditor/UnityEditor/CurveRendererCache.cs b/UnityEditor/UnityEditor/CurveRendererCache.cs new file mode 100644 index 00000000..22aa861b --- /dev/null +++ b/UnityEditor/UnityEditor/CurveRendererCache.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections; +using UnityEngine; +namespace UnityEditor +{ + internal class CurveRendererCache + { + private static Hashtable m_CombiRenderers = new Hashtable(); + private static Hashtable m_NormalRenderers = new Hashtable(); + public static void ClearCurveRendererCache() + { + CurveRendererCache.m_CombiRenderers = new Hashtable(); + CurveRendererCache.m_NormalRenderers = new Hashtable(); + } + public static CurveRenderer GetCurveRenderer(AnimationClip clip, EditorCurveBinding curveBinding) + { + if (curveBinding.type == typeof(Transform) && curveBinding.propertyName.StartsWith("localEulerAngles.")) + { + int curveIndexFromName = RotationCurveInterpolation.GetCurveIndexFromName(curveBinding.propertyName); + string key = CurveUtility.GetCurveGroupID(clip, curveBinding).ToString(); + EulerCurveCombinedRenderer eulerCurveCombinedRenderer = (EulerCurveCombinedRenderer)CurveRendererCache.m_CombiRenderers[key]; + if (eulerCurveCombinedRenderer == null) + { + eulerCurveCombinedRenderer = new EulerCurveCombinedRenderer(AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "m_LocalRotation.x")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "m_LocalRotation.y")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "m_LocalRotation.z")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "m_LocalRotation.w")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "localEulerAngles.x")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "localEulerAngles.y")), AnimationUtility.GetEditorCurve(clip, EditorCurveBinding.FloatCurve(curveBinding.path, typeof(Transform), "localEulerAngles.z"))); + CurveRendererCache.m_CombiRenderers.Add(key, eulerCurveCombinedRenderer); + } + return new EulerCurveRenderer(curveIndexFromName, eulerCurveCombinedRenderer); + } + string key2 = CurveUtility.GetCurveID(clip, curveBinding).ToString(); + NormalCurveRenderer normalCurveRenderer = (NormalCurveRenderer)CurveRendererCache.m_NormalRenderers[key2]; + if (normalCurveRenderer == null) + { + normalCurveRenderer = new NormalCurveRenderer(AnimationUtility.GetEditorCurve(clip, curveBinding)); + CurveRendererCache.m_NormalRenderers.Add(key2, normalCurveRenderer); + } + return normalCurveRenderer; + } + } +} diff --git a/UnityEditor/UnityEditor/CurveSelection.cs b/UnityEditor/UnityEditor/CurveSelection.cs new file mode 100644 index 00000000..57855ae2 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveSelection.cs @@ -0,0 +1,111 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class CurveSelection : IComparable + { + internal enum SelectionType + { + Key, + InTangent, + OutTangent, + Count + } + [NonSerialized] + internal CurveEditor m_Host; + private int m_CurveID; + private int m_Key = -1; + internal bool semiSelected; + internal CurveSelection.SelectionType type; + internal CurveWrapper curveWrapper + { + get + { + return this.m_Host.GetCurveFromID(this.m_CurveID); + } + } + internal AnimationCurve curve + { + get + { + return this.curveWrapper.curve; + } + } + public int curveID + { + get + { + return this.m_CurveID; + } + set + { + this.m_CurveID = value; + } + } + public int key + { + get + { + return this.m_Key; + } + set + { + this.m_Key = value; + } + } + internal Keyframe keyframe + { + get + { + if (this.validKey()) + { + return this.curve[this.m_Key]; + } + return default(Keyframe); + } + } + internal CurveSelection(int curveID, CurveEditor host, int keyIndex) + { + this.m_CurveID = curveID; + this.m_Host = host; + this.m_Key = keyIndex; + this.type = CurveSelection.SelectionType.Key; + } + internal CurveSelection(int curveID, CurveEditor host, int keyIndex, CurveSelection.SelectionType t) + { + this.m_CurveID = curveID; + this.m_Host = host; + this.m_Key = keyIndex; + this.type = t; + } + internal bool validKey() + { + return this.curve != null && this.m_Key >= 0 && this.m_Key < this.curve.length; + } + public int CompareTo(object _other) + { + CurveSelection curveSelection = (CurveSelection)_other; + int num = this.curveID - curveSelection.curveID; + if (num != 0) + { + return num; + } + num = this.key - curveSelection.key; + if (num != 0) + { + return num; + } + return this.type - curveSelection.type; + } + public override bool Equals(object _other) + { + CurveSelection curveSelection = (CurveSelection)_other; + return curveSelection.curveID == this.curveID && curveSelection.key == this.key && curveSelection.type == this.type; + } + public override int GetHashCode() + { + return (int)(this.curveID * 729 + this.key * 27 + this.type); + } + } +} diff --git a/UnityEditor/UnityEditor/CurveState.cs b/UnityEditor/UnityEditor/CurveState.cs new file mode 100644 index 00000000..6b026955 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveState.cs @@ -0,0 +1,120 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class CurveState + { + private EditorCurveBinding m_CurveBinding; + private bool m_Animated; + public AnimationSelection animationSelection; + public Color color; + public Vector2 guiPosition; + public bool even; + public Type type + { + get + { + return this.m_CurveBinding.type; + } + set + { + this.m_CurveBinding.type = value; + } + } + public string propertyName + { + get + { + return this.m_CurveBinding.propertyName; + } + set + { + this.m_CurveBinding.propertyName = value; + } + } + public string path + { + get + { + return this.m_CurveBinding.path; + } + set + { + this.m_CurveBinding.path = value; + } + } + public EditorCurveBinding curveBinding + { + get + { + return this.m_CurveBinding; + } + set + { + this.m_CurveBinding = value; + } + } + public bool animated + { + get + { + return this.m_Animated; + } + set + { + this.m_Animated = value; + } + } + public AnimationCurve curve + { + get + { + CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.clip, this.m_CurveBinding); + return curveRenderer.GetCurve(); + } + } + public AnimationClip clip + { + get + { + return this.animationSelection.clip; + } + } + public CurveState(EditorCurveBinding binding) + { + this.m_CurveBinding = binding; + } + public void SaveCurve(AnimationCurve animationCurve) + { + Undo.RegisterCompleteObjectUndo(this.clip, "Edit Curve"); + QuaternionCurveTangentCalculation.UpdateTangentsFromMode(animationCurve, this.clip, this.m_CurveBinding); + AnimationUtility.SetEditorCurve(this.clip, this.m_CurveBinding, animationCurve); + } + public int GetID() + { + return CurveUtility.GetCurveID(this.clip, this.m_CurveBinding); + } + public int GetGroupID() + { + return CurveUtility.GetCurveGroupID(this.clip, this.m_CurveBinding); + } + public float GetSampledOrCurveValue(float time) + { + if (this.animated) + { + CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.clip, this.m_CurveBinding); + if (curveRenderer == null) + { + Debug.LogError("The renderer is null!"); + } + return curveRenderer.EvaluateCurveSlow(time); + } + float result; + if (!AnimationUtility.GetFloatValue(this.animationSelection.animatedObject, this.m_CurveBinding, out result)) + { + result = float.PositiveInfinity; + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/CurveUpdater.cs b/UnityEditor/UnityEditor/CurveUpdater.cs new file mode 100644 index 00000000..1dd5246a --- /dev/null +++ b/UnityEditor/UnityEditor/CurveUpdater.cs @@ -0,0 +1,9 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + internal interface CurveUpdater + { + void UpdateCurves(List curveIds, string undoText); + } +} diff --git a/UnityEditor/UnityEditor/CurveUtility.cs b/UnityEditor/UnityEditor/CurveUtility.cs new file mode 100644 index 00000000..88dc1814 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveUtility.cs @@ -0,0 +1,384 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal static class CurveUtility + { + private const int kBrokenMask = 1; + private const int kLeftTangentMask = 6; + private const int kRightTangentMask = 24; + private static Texture2D iconKey; + private static Texture2D iconCurve; + private static Texture2D iconNone; + public static int GetPathAndTypeID(string path, Type type) + { + return path.GetHashCode() * 27 ^ type.GetHashCode(); + } + public static int GetCurveID(AnimationClip clip, EditorCurveBinding curveData) + { + int num = (!(clip == null)) ? clip.GetInstanceID() : 0; + return num * 19603 ^ curveData.path.GetHashCode() * 729 ^ curveData.type.GetHashCode() * 27 ^ curveData.propertyName.GetHashCode(); + } + public static int GetCurveGroupID(AnimationClip clip, EditorCurveBinding curveData) + { + if (curveData.type != typeof(Transform)) + { + return -1; + } + int num = (!(clip == null)) ? clip.GetInstanceID() : 0; + string text = curveData.propertyName.Substring(0, curveData.propertyName.Length - 1); + return num * 19603 ^ curveData.path.GetHashCode() * 729 ^ curveData.type.GetHashCode() * 27 ^ text.GetHashCode(); + } + public static Texture2D GetIconCurve() + { + if (CurveUtility.iconCurve == null) + { + CurveUtility.iconCurve = EditorGUIUtility.LoadIcon("animationanimated"); + } + return CurveUtility.iconCurve; + } + public static Texture2D GetIconKey() + { + if (CurveUtility.iconKey == null) + { + CurveUtility.iconKey = EditorGUIUtility.LoadIcon("animationkeyframe"); + } + return CurveUtility.iconKey; + } + public static bool HaveKeysInRange(AnimationCurve curve, float beginTime, float endTime) + { + for (int i = curve.length - 1; i >= 0; i--) + { + if (curve[i].time >= beginTime && curve[i].time < endTime) + { + return true; + } + } + return false; + } + public static void RemoveKeysInRange(AnimationCurve curve, float beginTime, float endTime) + { + for (int i = curve.length - 1; i >= 0; i--) + { + if (curve[i].time >= beginTime && curve[i].time < endTime) + { + curve.RemoveKey(i); + } + } + } + public static void UpdateTangentsFromMode(AnimationCurve curve) + { + for (int i = 0; i < curve.length; i++) + { + CurveUtility.UpdateTangentsFromMode(curve, i); + } + } + private static float CalculateLinearTangent(AnimationCurve curve, int index, int toIndex) + { + return (curve[index].value - curve[toIndex].value) / (curve[index].time - curve[toIndex].time); + } + private static void UpdateTangentsFromMode(AnimationCurve curve, int index) + { + if (index < 0 || index >= curve.length) + { + return; + } + Keyframe key = curve[index]; + if (CurveUtility.GetKeyTangentMode(key, 0) == TangentMode.Linear && index >= 1) + { + key.inTangent = CurveUtility.CalculateLinearTangent(curve, index, index - 1); + curve.MoveKey(index, key); + } + if (CurveUtility.GetKeyTangentMode(key, 1) == TangentMode.Linear && index + 1 < curve.length) + { + key.outTangent = CurveUtility.CalculateLinearTangent(curve, index, index + 1); + curve.MoveKey(index, key); + } + if (CurveUtility.GetKeyTangentMode(key, 0) == TangentMode.Smooth || CurveUtility.GetKeyTangentMode(key, 1) == TangentMode.Smooth) + { + curve.SmoothTangents(index, 0f); + } + } + public static void UpdateTangentsFromModeSurrounding(AnimationCurve curve, int index) + { + CurveUtility.UpdateTangentsFromMode(curve, index - 2); + CurveUtility.UpdateTangentsFromMode(curve, index - 1); + CurveUtility.UpdateTangentsFromMode(curve, index); + CurveUtility.UpdateTangentsFromMode(curve, index + 1); + CurveUtility.UpdateTangentsFromMode(curve, index + 2); + } + public static float CalculateSmoothTangent(Keyframe key) + { + if (key.inTangent == float.PositiveInfinity) + { + key.inTangent = 0f; + } + if (key.outTangent == float.PositiveInfinity) + { + key.outTangent = 0f; + } + return (key.outTangent + key.inTangent) * 0.5f; + } + public static void SetKeyBroken(ref Keyframe key, bool broken) + { + if (broken) + { + key.tangentMode |= 1; + } + else + { + key.tangentMode &= -2; + } + } + public static bool GetKeyBroken(Keyframe key) + { + return (key.tangentMode & 1) != 0; + } + public static void SetKeyTangentMode(ref Keyframe key, int leftRight, TangentMode mode) + { + if (leftRight == 0) + { + key.tangentMode &= -7; + key.tangentMode |= (int)((int)mode << 1); + } + else + { + key.tangentMode &= -25; + key.tangentMode |= (int)((int)mode << 3); + } + if (CurveUtility.GetKeyTangentMode(key, leftRight) != mode) + { + Debug.Log("bug"); + } + } + public static TangentMode GetKeyTangentMode(Keyframe key, int leftRight) + { + if (leftRight == 0) + { + return (TangentMode)((key.tangentMode & 6) >> 1); + } + return (TangentMode)((key.tangentMode & 24) >> 3); + } + public static void SetKeyModeFromContext(AnimationCurve curve, int keyIndex) + { + Keyframe key = curve[keyIndex]; + bool flag = false; + if (keyIndex > 0 && CurveUtility.GetKeyBroken(curve[keyIndex - 1])) + { + flag = true; + } + if (keyIndex < curve.length - 1 && CurveUtility.GetKeyBroken(curve[keyIndex + 1])) + { + flag = true; + } + CurveUtility.SetKeyBroken(ref key, flag); + if (flag) + { + if (keyIndex > 0) + { + CurveUtility.SetKeyTangentMode(ref key, 0, CurveUtility.GetKeyTangentMode(curve[keyIndex - 1], 1)); + } + if (keyIndex < curve.length - 1) + { + CurveUtility.SetKeyTangentMode(ref key, 1, CurveUtility.GetKeyTangentMode(curve[keyIndex + 1], 0)); + } + } + else + { + TangentMode mode = TangentMode.Smooth; + if (keyIndex > 0 && CurveUtility.GetKeyTangentMode(curve[keyIndex - 1], 1) != TangentMode.Smooth) + { + mode = TangentMode.Editable; + } + if (keyIndex < curve.length - 1 && CurveUtility.GetKeyTangentMode(curve[keyIndex + 1], 0) != TangentMode.Smooth) + { + mode = TangentMode.Editable; + } + CurveUtility.SetKeyTangentMode(ref key, 0, mode); + CurveUtility.SetKeyTangentMode(ref key, 1, mode); + } + curve.MoveKey(keyIndex, key); + } + public static string GetClipName(AnimationClip clip) + { + if (clip == null) + { + return "[No Clip]"; + } + string text = clip.name; + if ((clip.hideFlags & HideFlags.NotEditable) != HideFlags.None) + { + text += " (Read-Only)"; + } + return text; + } + public static Color GetBalancedColor(Color c) + { + return new Color(0.15f + 0.75f * c.r, 0.2f + 0.6f * c.g, 0.1f + 0.9f * c.b); + } + public static Color GetPropertyColor(string name) + { + Color result = Color.white; + int num = 0; + if (name.StartsWith("m_LocalPosition")) + { + num = 1; + } + if (name.StartsWith("localEulerAngles")) + { + num = 2; + } + if (name.StartsWith("m_LocalScale")) + { + num = 3; + } + if (num == 1) + { + if (name.EndsWith(".x")) + { + result = Handles.xAxisColor; + } + else + { + if (name.EndsWith(".y")) + { + result = Handles.yAxisColor; + } + else + { + if (name.EndsWith(".z")) + { + result = Handles.zAxisColor; + } + } + } + } + else + { + if (num == 2) + { + if (name.EndsWith(".x")) + { + result = AnimationWindow.kEulerXColor; + } + else + { + if (name.EndsWith(".y")) + { + result = AnimationWindow.kEulerYColor; + } + else + { + if (name.EndsWith(".z")) + { + result = AnimationWindow.kEulerZColor; + } + } + } + } + else + { + if (num == 3) + { + if (name.EndsWith(".x")) + { + result = CurveUtility.GetBalancedColor(new Color(0.7f, 0.4f, 0.4f)); + } + else + { + if (name.EndsWith(".y")) + { + result = CurveUtility.GetBalancedColor(new Color(0.4f, 0.7f, 0.4f)); + } + else + { + if (name.EndsWith(".z")) + { + result = CurveUtility.GetBalancedColor(new Color(0.4f, 0.4f, 0.7f)); + } + } + } + } + else + { + if (name.EndsWith(".x")) + { + result = Handles.xAxisColor; + } + else + { + if (name.EndsWith(".y")) + { + result = Handles.yAxisColor; + } + else + { + if (name.EndsWith(".z")) + { + result = Handles.zAxisColor; + } + else + { + if (name.EndsWith(".w")) + { + result = new Color(1f, 0.5f, 0f); + } + else + { + if (name.EndsWith(".r")) + { + result = CurveUtility.GetBalancedColor(Color.red); + } + else + { + if (name.EndsWith(".g")) + { + result = CurveUtility.GetBalancedColor(Color.green); + } + else + { + if (name.EndsWith(".b")) + { + result = CurveUtility.GetBalancedColor(Color.blue); + } + else + { + if (name.EndsWith(".a")) + { + result = CurveUtility.GetBalancedColor(Color.yellow); + } + else + { + if (name.EndsWith(".width")) + { + result = CurveUtility.GetBalancedColor(Color.blue); + } + else + { + if (name.EndsWith(".height")) + { + result = CurveUtility.GetBalancedColor(Color.yellow); + } + else + { + float num2 = 6.28318548f * (float)(name.GetHashCode() % 1000); + num2 -= Mathf.Floor(num2); + result = CurveUtility.GetBalancedColor(EditorGUIUtility.HSVToRGB(num2, 1f, 1f)); + } + } + } + } + } + } + } + } + } + } + } + } + } + result.a = 1f; + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/CurveWrapper.cs b/UnityEditor/UnityEditor/CurveWrapper.cs new file mode 100644 index 00000000..a4a0d6f1 --- /dev/null +++ b/UnityEditor/UnityEditor/CurveWrapper.cs @@ -0,0 +1,59 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class CurveWrapper + { + internal enum SelectionMode + { + None, + Selected, + SemiSelected + } + public delegate Vector2 GetAxisScalarsCallback(); + public delegate void SetAxisScalarsCallback(Vector2 newAxisScalars); + private CurveRenderer m_Renderer; + public int id; + public int groupId; + public int regionId; + public Color color; + public bool readOnly; + public bool hidden; + public CurveWrapper.GetAxisScalarsCallback getAxisUiScalarsCallback; + public CurveWrapper.SetAxisScalarsCallback setAxisUiScalarsCallback; + public bool changed; + public CurveWrapper.SelectionMode selected; + public int listIndex; + public float vRangeMin = float.NegativeInfinity; + public float vRangeMax = float.PositiveInfinity; + public CurveRenderer renderer + { + get + { + return this.m_Renderer; + } + set + { + this.m_Renderer = value; + } + } + public AnimationCurve curve + { + get + { + return this.renderer.GetCurve(); + } + } + public CurveWrapper() + { + this.id = 0; + this.groupId = -1; + this.regionId = -1; + this.hidden = false; + this.readOnly = false; + this.listIndex = -1; + this.getAxisUiScalarsCallback = null; + this.setAxisUiScalarsCallback = null; + } + } +} diff --git a/UnityEditor/UnityEditor/CustomEditor.cs b/UnityEditor/UnityEditor/CustomEditor.cs new file mode 100644 index 00000000..4950c39e --- /dev/null +++ b/UnityEditor/UnityEditor/CustomEditor.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public sealed class CustomEditor : Attribute + { + internal Type m_InspectedType; + internal bool m_EditorForChildClasses; + public CustomEditor(Type inspectedType) + { + if (inspectedType == null) + { + Debug.LogError("Failed to load CustomEditor inspected type"); + } + this.m_InspectedType = inspectedType; + this.m_EditorForChildClasses = false; + } + public CustomEditor(Type inspectedType, bool editorForChildClasses) + { + if (inspectedType == null) + { + Debug.LogError("Failed to load CustomEditor inspected type"); + } + this.m_InspectedType = inspectedType; + this.m_EditorForChildClasses = editorForChildClasses; + } + } +} diff --git a/UnityEditor/UnityEditor/CustomEditorAttributes.cs b/UnityEditor/UnityEditor/CustomEditorAttributes.cs new file mode 100644 index 00000000..33600dc6 --- /dev/null +++ b/UnityEditor/UnityEditor/CustomEditorAttributes.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class CustomEditorAttributes + { + private class MonoEditorType + { + public Type m_InspectedType; + public Type m_InspectorType; + public bool m_EditorForChildClasses; + } + private static readonly List kSCustomEditors = new List(); + private static readonly List kSCustomMultiEditors = new List(); + private static bool s_Initialized; + internal static Type FindCustomEditorType(UnityEngine.Object o, bool multiEdit) + { + return CustomEditorAttributes.FindCustomEditorTypeByType(o.GetType(), multiEdit); + } + internal static Type FindCustomEditorTypeByType(Type type, bool multiEdit) + { + if (!CustomEditorAttributes.s_Initialized) + { + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = loadedAssemblies.Length - 1; i >= 0; i--) + { + CustomEditorAttributes.Rebuild(loadedAssemblies[i]); + } + CustomEditorAttributes.s_Initialized = true; + } + List source = (!multiEdit) ? CustomEditorAttributes.kSCustomEditors : CustomEditorAttributes.kSCustomMultiEditors; + Type inspected; + for (inspected = type; inspected != null; inspected = inspected.BaseType) + { + CustomEditorAttributes.MonoEditorType monoEditorType; + if (type == inspected) + { + monoEditorType = source.FirstOrDefault((CustomEditorAttributes.MonoEditorType x) => inspected == x.m_InspectedType); + } + else + { + monoEditorType = source.FirstOrDefault((CustomEditorAttributes.MonoEditorType x) => inspected == x.m_InspectedType && x.m_EditorForChildClasses); + } + if (monoEditorType != null) + { + return monoEditorType.m_InspectorType; + } + } + return null; + } + internal static void Rebuild(Assembly assembly) + { + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + object[] customAttributes = type.GetCustomAttributes(typeof(CustomEditor), false); + object[] array2 = customAttributes; + for (int j = 0; j < array2.Length; j++) + { + CustomEditor customEditor = (CustomEditor)array2[j]; + CustomEditorAttributes.MonoEditorType monoEditorType = new CustomEditorAttributes.MonoEditorType(); + if (customEditor.m_InspectedType == null) + { + Debug.Log("Can't load custom inspector " + type.Name + " because the inspected type is null."); + } + else + { + if (!type.IsSubclassOf(typeof(Editor))) + { + if (!(type.FullName == "TweakMode") || !type.IsEnum || !(customEditor.m_InspectedType.FullName == "BloomAndFlares")) + { + Debug.LogWarning(type.Name + " uses the CustomEditor attribute but does not inherit from Editor.\nYou must inherit from Editor. See the Editor class script documentation."); + } + } + else + { + monoEditorType.m_InspectedType = customEditor.m_InspectedType; + monoEditorType.m_InspectorType = type; + monoEditorType.m_EditorForChildClasses = customEditor.m_EditorForChildClasses; + CustomEditorAttributes.kSCustomEditors.Add(monoEditorType); + if (type.GetCustomAttributes(typeof(CanEditMultipleObjects), false).Length > 0) + { + CustomEditorAttributes.kSCustomMultiEditors.Add(monoEditorType); + } + } + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/CustomPreviewAttribute.cs b/UnityEditor/UnityEditor/CustomPreviewAttribute.cs new file mode 100644 index 00000000..3a136838 --- /dev/null +++ b/UnityEditor/UnityEditor/CustomPreviewAttribute.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] + public sealed class CustomPreviewAttribute : Attribute + { + internal Type m_Type; + public CustomPreviewAttribute(Type type) + { + this.m_Type = type; + } + } +} diff --git a/UnityEditor/UnityEditor/CustomPropertyDrawer.cs b/UnityEditor/UnityEditor/CustomPropertyDrawer.cs new file mode 100644 index 00000000..2e8c5be6 --- /dev/null +++ b/UnityEditor/UnityEditor/CustomPropertyDrawer.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public sealed class CustomPropertyDrawer : Attribute + { + internal Type m_Type; + internal bool m_UseForChildren; + public CustomPropertyDrawer(Type type) + { + this.m_Type = type; + } + public CustomPropertyDrawer(Type type, bool useForChildren) + { + this.m_Type = type; + this.m_UseForChildren = useForChildren; + } + } +} diff --git a/UnityEditor/UnityEditor/D3D9FullscreenMode.cs b/UnityEditor/UnityEditor/D3D9FullscreenMode.cs new file mode 100644 index 00000000..58f66c94 --- /dev/null +++ b/UnityEditor/UnityEditor/D3D9FullscreenMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum D3D9FullscreenMode + { + ExclusiveMode, + FullscreenWindow + } +} diff --git a/UnityEditor/UnityEditor/DebugUtils.cs b/UnityEditor/UnityEditor/DebugUtils.cs new file mode 100644 index 00000000..00da9841 --- /dev/null +++ b/UnityEditor/UnityEditor/DebugUtils.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + internal class DebugUtils + { + internal static string ListToString(IEnumerable list) + { + if (list == null) + { + return "[null list]"; + } + string text = "["; + int num = 0; + foreach (T current in list) + { + if (num != 0) + { + text += ", "; + } + if (current != null) + { + text += current.ToString(); + } + else + { + text += "'null'"; + } + num++; + } + text += "]"; + if (num == 0) + { + return "[empty list]"; + } + return string.Concat(new object[] + { + "(", + num, + ") ", + text + }); + } + } +} diff --git a/UnityEditor/UnityEditor/DecoratorDrawer.cs b/UnityEditor/UnityEditor/DecoratorDrawer.cs new file mode 100644 index 00000000..a8ff142d --- /dev/null +++ b/UnityEditor/UnityEditor/DecoratorDrawer.cs @@ -0,0 +1,23 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public abstract class DecoratorDrawer : GUIDrawer + { + internal PropertyAttribute m_Attribute; + public PropertyAttribute attribute + { + get + { + return this.m_Attribute; + } + } + public virtual void OnGUI(Rect position) + { + } + public virtual float GetHeight() + { + return 16f; + } + } +} diff --git a/UnityEditor/UnityEditor/DeleteWindowLayout.cs b/UnityEditor/UnityEditor/DeleteWindowLayout.cs new file mode 100644 index 00000000..c9a08eb6 --- /dev/null +++ b/UnityEditor/UnityEditor/DeleteWindowLayout.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class DeleteWindowLayout : EditorWindow + { + internal string[] m_Paths; + private Vector2 m_ScrollPos; + private void InitializePaths() + { + string[] files = Directory.GetFiles(WindowLayout.layoutsPreferencesPath); + ArrayList arrayList = new ArrayList(); + string[] array = files; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + string fileName = Path.GetFileName(text); + if (Path.GetExtension(fileName) == ".wlt") + { + arrayList.Add(text); + } + } + this.m_Paths = (arrayList.ToArray(typeof(string)) as string[]); + } + private void OnGUI() + { + if (this.m_Paths == null) + { + this.InitializePaths(); + } + this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, "OL Box", new GUILayoutOption[0]); + string[] paths = this.m_Paths; + for (int i = 0; i < paths.Length; i++) + { + string path = paths[i]; + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path); + if (GUILayout.Button(fileNameWithoutExtension, new GUILayoutOption[0])) + { + if (Toolbar.lastLoadedLayoutName == fileNameWithoutExtension) + { + Toolbar.lastLoadedLayoutName = null; + } + File.Delete(path); + InternalEditorUtility.ReloadWindowLayoutMenu(); + this.InitializePaths(); + } + } + EditorGUILayout.EndScrollView(); + } + } +} diff --git a/UnityEditor/UnityEditor/DeletedAsset.cs b/UnityEditor/UnityEditor/DeletedAsset.cs new file mode 100644 index 00000000..2509e99b --- /dev/null +++ b/UnityEditor/UnityEditor/DeletedAsset.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + internal sealed class DeletedAsset + { + public int changeset; + public string guid; + public string parent; + public string name; + public string fullPath; + public string date; + public int assetIsDir; + internal static int Compare(DeletedAsset p1, DeletedAsset p2) + { + return (p1.changeset <= p2.changeset) ? ((p1.changeset >= p2.changeset) ? string.Compare(p1.fullPath, p2.fullPath, true) : 1) : -1; + } + } +} diff --git a/UnityEditor/UnityEditor/DetailMeshRenderMode.cs b/UnityEditor/UnityEditor/DetailMeshRenderMode.cs new file mode 100644 index 00000000..9f10e4ae --- /dev/null +++ b/UnityEditor/UnityEditor/DetailMeshRenderMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum DetailMeshRenderMode + { + VertexLit, + Grass + } +} diff --git a/UnityEditor/UnityEditor/DetailMeshWizard.cs b/UnityEditor/UnityEditor/DetailMeshWizard.cs new file mode 100644 index 00000000..2fc67fa9 --- /dev/null +++ b/UnityEditor/UnityEditor/DetailMeshWizard.cs @@ -0,0 +1,115 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DetailMeshWizard : TerrainWizard + { + public GameObject m_Detail; + public float m_NoiseSpread; + public float m_RandomWidth; + public float m_RandomHeight; + public Color m_HealthyColor; + public Color m_DryColor; + public DetailMeshRenderMode m_RenderMode; + private int m_PrototypeIndex = -1; + public void OnEnable() + { + base.minSize = new Vector2(400f, 400f); + } + internal void InitializeDefaults(Terrain terrain, int index) + { + this.m_Terrain = terrain; + this.m_PrototypeIndex = index; + DetailPrototype detailPrototype; + if (this.m_PrototypeIndex == -1) + { + detailPrototype = new DetailPrototype(); + } + else + { + detailPrototype = this.m_Terrain.terrainData.detailPrototypes[this.m_PrototypeIndex]; + } + this.m_Detail = detailPrototype.prototype; + this.m_NoiseSpread = detailPrototype.noiseSpread; + this.m_RandomWidth = detailPrototype.maxWidth - 1f; + this.m_RandomHeight = detailPrototype.maxHeight - 1f; + this.m_HealthyColor = detailPrototype.healthyColor; + this.m_DryColor = detailPrototype.dryColor; + switch (detailPrototype.renderMode) + { + case DetailRenderMode.GrassBillboard: + Debug.LogError("Detail meshes can't be rendered as billboards"); + this.m_RenderMode = DetailMeshRenderMode.Grass; + break; + case DetailRenderMode.VertexLit: + this.m_RenderMode = DetailMeshRenderMode.VertexLit; + break; + case DetailRenderMode.Grass: + this.m_RenderMode = DetailMeshRenderMode.Grass; + break; + } + this.OnWizardUpdate(); + } + private void DoApply() + { + if (base.terrainData == null) + { + return; + } + DetailPrototype[] array = this.m_Terrain.terrainData.detailPrototypes; + if (this.m_PrototypeIndex == -1) + { + DetailPrototype[] array2 = new DetailPrototype[array.Length + 1]; + Array.Copy(array, 0, array2, 0, array.Length); + this.m_PrototypeIndex = array.Length; + array = array2; + array[this.m_PrototypeIndex] = new DetailPrototype(); + } + array[this.m_PrototypeIndex].renderMode = DetailRenderMode.VertexLit; + array[this.m_PrototypeIndex].usePrototypeMesh = true; + array[this.m_PrototypeIndex].prototype = this.m_Detail; + array[this.m_PrototypeIndex].prototypeTexture = null; + array[this.m_PrototypeIndex].noiseSpread = this.m_NoiseSpread; + array[this.m_PrototypeIndex].minWidth = 1f - this.m_RandomWidth; + array[this.m_PrototypeIndex].maxWidth = 1f + this.m_RandomWidth; + array[this.m_PrototypeIndex].minHeight = 1f - this.m_RandomHeight; + array[this.m_PrototypeIndex].maxHeight = 1f + this.m_RandomHeight; + array[this.m_PrototypeIndex].healthyColor = this.m_HealthyColor; + array[this.m_PrototypeIndex].dryColor = this.m_DryColor; + if (this.m_RenderMode == DetailMeshRenderMode.Grass) + { + array[this.m_PrototypeIndex].renderMode = DetailRenderMode.Grass; + } + else + { + array[this.m_PrototypeIndex].renderMode = DetailRenderMode.VertexLit; + } + this.m_Terrain.terrainData.detailPrototypes = array; + EditorUtility.SetDirty(this.m_Terrain); + } + private void OnWizardCreate() + { + this.DoApply(); + } + private void OnWizardOtherButton() + { + this.DoApply(); + } + internal override void OnWizardUpdate() + { + base.OnWizardUpdate(); + if (this.m_Detail == null) + { + base.errorString = "Please assign a detail prefab"; + base.isValid = false; + } + else + { + if (this.m_PrototypeIndex != -1) + { + this.DoApply(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/DetailPainter.cs b/UnityEditor/UnityEditor/DetailPainter.cs new file mode 100644 index 00000000..a2ed30ec --- /dev/null +++ b/UnityEditor/UnityEditor/DetailPainter.cs @@ -0,0 +1,58 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DetailPainter + { + public int size; + public float opacity; + public float targetStrength; + public Brush brush; + public TerrainData terrainData; + public TerrainTool tool; + public bool randomizeDetails; + public bool clearSelectedOnly; + public void Paint(float xCenterNormalized, float yCenterNormalized, int detailIndex) + { + if (detailIndex >= this.terrainData.detailPrototypes.Length) + { + return; + } + int num = Mathf.FloorToInt(xCenterNormalized * (float)this.terrainData.detailWidth); + int num2 = Mathf.FloorToInt(yCenterNormalized * (float)this.terrainData.detailHeight); + int num3 = Mathf.RoundToInt((float)this.size) / 2; + int num4 = Mathf.RoundToInt((float)this.size) % 2; + int num5 = Mathf.Clamp(num - num3, 0, this.terrainData.detailWidth - 1); + int num6 = Mathf.Clamp(num2 - num3, 0, this.terrainData.detailHeight - 1); + int num7 = Mathf.Clamp(num + num3 + num4, 0, this.terrainData.detailWidth); + int num8 = Mathf.Clamp(num2 + num3 + num4, 0, this.terrainData.detailHeight); + int num9 = num7 - num5; + int num10 = num8 - num6; + int[] array = new int[] + { + detailIndex + }; + if (this.targetStrength < 0f && !this.clearSelectedOnly) + { + array = this.terrainData.GetSupportedLayers(num5, num6, num9, num10); + } + for (int i = 0; i < array.Length; i++) + { + int[,] detailLayer = this.terrainData.GetDetailLayer(num5, num6, num9, num10, array[i]); + for (int j = 0; j < num10; j++) + { + for (int k = 0; k < num9; k++) + { + int ix = num5 + k - (num - num3 + num4); + int iy = num6 + j - (num2 - num3 + num4); + float t = this.opacity * this.brush.GetStrengthInt(ix, iy); + float to = this.targetStrength; + float num11 = Mathf.Lerp((float)detailLayer[j, k], to, t); + detailLayer[j, k] = Mathf.RoundToInt(num11 - 0.5f + UnityEngine.Random.value); + } + } + this.terrainData.SetDetailLayer(num5, num6, array[i], detailLayer); + } + } + } +} diff --git a/UnityEditor/UnityEditor/DetailTextureWizard.cs b/UnityEditor/UnityEditor/DetailTextureWizard.cs new file mode 100644 index 00000000..5d13839b --- /dev/null +++ b/UnityEditor/UnityEditor/DetailTextureWizard.cs @@ -0,0 +1,104 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DetailTextureWizard : TerrainWizard + { + public Texture2D m_DetailTexture; + public float m_MinWidth; + public float m_MaxWidth; + public float m_MinHeight; + public float m_MaxHeight; + public float m_NoiseSpread; + public Color m_HealthyColor; + public Color m_DryColor; + public bool m_Billboard; + private int m_PrototypeIndex = -1; + public void OnEnable() + { + base.minSize = new Vector2(400f, 400f); + } + internal void InitializeDefaults(Terrain terrain, int index) + { + this.m_Terrain = terrain; + this.m_PrototypeIndex = index; + DetailPrototype detailPrototype; + if (this.m_PrototypeIndex == -1) + { + detailPrototype = new DetailPrototype(); + detailPrototype.renderMode = DetailRenderMode.GrassBillboard; + } + else + { + detailPrototype = this.m_Terrain.terrainData.detailPrototypes[this.m_PrototypeIndex]; + } + this.m_DetailTexture = detailPrototype.prototypeTexture; + this.m_MinWidth = detailPrototype.minWidth; + this.m_MaxWidth = detailPrototype.maxWidth; + this.m_MinHeight = detailPrototype.minHeight; + this.m_MaxHeight = detailPrototype.maxHeight; + this.m_NoiseSpread = detailPrototype.noiseSpread; + this.m_HealthyColor = detailPrototype.healthyColor; + this.m_DryColor = detailPrototype.dryColor; + this.m_Billboard = (detailPrototype.renderMode == DetailRenderMode.GrassBillboard); + this.OnWizardUpdate(); + } + private void DoApply() + { + if (base.terrainData == null) + { + return; + } + DetailPrototype[] array = this.m_Terrain.terrainData.detailPrototypes; + if (this.m_PrototypeIndex == -1) + { + DetailPrototype[] array2 = new DetailPrototype[array.Length + 1]; + Array.Copy(array, 0, array2, 0, array.Length); + this.m_PrototypeIndex = array.Length; + array = array2; + array[this.m_PrototypeIndex] = new DetailPrototype(); + } + array[this.m_PrototypeIndex].prototype = null; + array[this.m_PrototypeIndex].prototypeTexture = this.m_DetailTexture; + array[this.m_PrototypeIndex].minWidth = this.m_MinWidth; + array[this.m_PrototypeIndex].maxWidth = this.m_MaxWidth; + array[this.m_PrototypeIndex].minHeight = this.m_MinHeight; + array[this.m_PrototypeIndex].maxHeight = this.m_MaxHeight; + array[this.m_PrototypeIndex].noiseSpread = this.m_NoiseSpread; + array[this.m_PrototypeIndex].healthyColor = this.m_HealthyColor; + array[this.m_PrototypeIndex].dryColor = this.m_DryColor; + array[this.m_PrototypeIndex].renderMode = ((!this.m_Billboard) ? DetailRenderMode.Grass : DetailRenderMode.GrassBillboard); + array[this.m_PrototypeIndex].usePrototypeMesh = false; + this.m_Terrain.terrainData.detailPrototypes = array; + EditorUtility.SetDirty(this.m_Terrain); + } + private void OnWizardCreate() + { + this.DoApply(); + } + private void OnWizardOtherButton() + { + this.DoApply(); + } + internal override void OnWizardUpdate() + { + this.m_MinHeight = Mathf.Max(0f, this.m_MinHeight); + this.m_MaxHeight = Mathf.Max(this.m_MinHeight, this.m_MaxHeight); + this.m_MinWidth = Mathf.Max(0f, this.m_MinWidth); + this.m_MaxWidth = Mathf.Max(this.m_MinWidth, this.m_MaxWidth); + base.OnWizardUpdate(); + if (this.m_DetailTexture == null) + { + base.errorString = "Please assign a detail texture"; + base.isValid = false; + } + else + { + if (this.m_PrototypeIndex != -1) + { + this.DoApply(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/DistanceJoint2DEditor.cs b/UnityEditor/UnityEditor/DistanceJoint2DEditor.cs new file mode 100644 index 00000000..1f59c68a --- /dev/null +++ b/UnityEditor/UnityEditor/DistanceJoint2DEditor.cs @@ -0,0 +1,25 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(DistanceJoint2D))] + internal class DistanceJoint2DEditor : AnchoredJoint2DEditor + { + public new void OnSceneGUI() + { + DistanceJoint2D distanceJoint2D = (DistanceJoint2D)this.target; + if (!distanceJoint2D.enabled) + { + return; + } + Vector3 anchor = Joint2DEditorBase.TransformPoint(distanceJoint2D.transform, distanceJoint2D.anchor); + Vector3 vector = distanceJoint2D.connectedAnchor; + if (distanceJoint2D.connectedBody) + { + vector = Joint2DEditorBase.TransformPoint(distanceJoint2D.connectedBody.transform, vector); + } + Joint2DEditorBase.DrawDistanceGizmo(anchor, vector, distanceJoint2D.distance); + base.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/DockArea.cs b/UnityEditor/UnityEditor/DockArea.cs new file mode 100644 index 00000000..3dcf1388 --- /dev/null +++ b/UnityEditor/UnityEditor/DockArea.cs @@ -0,0 +1,685 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class DockArea : HostView, IDropArea + { + internal const float kTabHeight = 17f; + internal const float kDockHeight = 39f; + private const float kSideBorders = 2f; + private const float kBottomBorders = 2f; + private const float kWindowButtonsWidth = 40f; + private static int s_PlaceholderPos; + private static EditorWindow s_DragPane; + internal static DockArea s_OriginalDragSource; + private static Vector2 s_StartDragPosition; + private static int s_DragMode; + internal static View s_IgnoreDockingForView; + private static DropInfo s_DropInfo; + [SerializeField] + internal List m_Panes = new List(); + [SerializeField] + internal int m_Selected; + [SerializeField] + internal int m_LastSelected; + [NonSerialized] + internal GUIStyle tabStyle; + public int selected + { + get + { + return this.m_Selected; + } + set + { + if (this.m_Selected == value) + { + return; + } + this.m_Selected = value; + if (this.m_Selected >= 0 && this.m_Selected < this.m_Panes.Count) + { + base.actualView = this.m_Panes[this.m_Selected]; + } + } + } + private Rect tabRect + { + get + { + return new Rect(0f, 0f, base.position.width, 17f); + } + } + public DockArea() + { + if (this.m_Panes != null && this.m_Panes.Count != 0) + { + Debug.LogError("m_Panes is filled in DockArea constructor."); + } + } + private void RemoveNullWindows() + { + List list = new List(); + foreach (EditorWindow current in this.m_Panes) + { + if (current != null) + { + list.Add(current); + } + } + this.m_Panes = list; + } + public new void OnDestroy() + { + if (base.hasFocus) + { + base.Invoke("OnLostFocus"); + } + base.actualView = null; + foreach (EditorWindow current in this.m_Panes) + { + UnityEngine.Object.DestroyImmediate(current, true); + } + base.OnDestroy(); + } + public new void OnEnable() + { + if (this.m_Panes != null && this.m_Panes.Count > this.m_Selected) + { + base.actualView = this.m_Panes[this.m_Selected]; + } + base.OnEnable(); + } + public void AddTab(EditorWindow pane) + { + this.AddTab(this.m_Panes.Count, pane); + } + public void AddTab(int idx, EditorWindow pane) + { + base.DeregisterSelectedPane(true); + this.m_Panes.Insert(idx, pane); + this.m_ActualView = pane; + this.m_Panes[idx] = pane; + this.m_Selected = idx; + base.RegisterSelectedPane(); + base.Repaint(); + } + public void RemoveTab(EditorWindow pane) + { + this.RemoveTab(pane, true); + } + public void RemoveTab(EditorWindow pane, bool killIfEmpty) + { + if (this.m_ActualView == pane) + { + base.DeregisterSelectedPane(true); + } + int num = this.m_Panes.IndexOf(pane); + if (num == -1) + { + Debug.LogError("Unable to remove Pane - it's not IN the window"); + return; + } + this.m_Panes.Remove(pane); + if (num == this.m_Selected) + { + if (this.m_LastSelected >= this.m_Panes.Count - 1) + { + this.m_LastSelected = this.m_Panes.Count - 1; + } + this.m_Selected = this.m_LastSelected; + if (this.m_Selected > -1) + { + this.m_ActualView = this.m_Panes[this.m_Selected]; + } + } + else + { + if (num < this.m_Selected) + { + this.m_Selected--; + } + } + base.Repaint(); + pane.m_Parent = null; + if (killIfEmpty) + { + this.KillIfEmpty(); + } + base.RegisterSelectedPane(); + } + private void KillIfEmpty() + { + if (this.m_Panes.Count != 0) + { + return; + } + if (base.parent == null) + { + base.window.InternalCloseWindow(); + return; + } + SplitView splitView = base.parent as SplitView; + ICleanuppable cleanuppable = base.parent as ICleanuppable; + splitView.RemoveChildNice(this); + UnityEngine.Object.DestroyImmediate(this, true); + if (cleanuppable != null) + { + cleanuppable.Cleanup(); + } + } + public DropInfo DragOver(EditorWindow window, Vector2 mouseScreenPosition) + { + Rect screenPosition = base.screenPosition; + screenPosition.height = 39f; + if (screenPosition.Contains(mouseScreenPosition)) + { + if (this.background == null) + { + this.background = "hostview"; + } + Rect rect = this.background.margin.Remove(base.screenPosition); + Vector2 mousePos = mouseScreenPosition - new Vector2(rect.x, rect.y); + Rect tabRect = this.tabRect; + int tabAtMousePos = this.GetTabAtMousePos(mousePos, tabRect); + float tabWidth = this.GetTabWidth(tabRect.width); + if (DockArea.s_PlaceholderPos != tabAtMousePos) + { + base.Repaint(); + DockArea.s_PlaceholderPos = tabAtMousePos; + } + return new DropInfo(this) + { + type = DropInfo.Type.Tab, + rect = new Rect(mousePos.x - tabWidth * 0.25f + rect.x, tabRect.y + rect.y, tabWidth, tabRect.height) + }; + } + return null; + } + public bool PerformDrop(EditorWindow w, DropInfo info, Vector2 screenPos) + { + DockArea.s_OriginalDragSource.RemoveTab(w, DockArea.s_OriginalDragSource != this); + int num = (DockArea.s_PlaceholderPos <= this.m_Panes.Count) ? DockArea.s_PlaceholderPos : this.m_Panes.Count; + this.AddTab(num, w); + this.selected = num; + return true; + } + public void OnGUI() + { + base.ClearBackground(); + EditorGUIUtility.ResetGUIState(); + SplitView splitView = base.parent as SplitView; + if (Event.current.type == EventType.Repaint && splitView) + { + View child = this; + while (splitView) + { + int controlID = splitView.controlID; + if (controlID == GUIUtility.hotControl || GUIUtility.hotControl == 0) + { + int num = splitView.IndexOfChild(child); + if (splitView.vertical) + { + if (num != 0) + { + EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, base.position.width, 5f), MouseCursor.SplitResizeUpDown, controlID); + } + if (num != splitView.children.Length - 1) + { + EditorGUIUtility.AddCursorRect(new Rect(0f, base.position.height - 5f, base.position.width, 5f), MouseCursor.SplitResizeUpDown, controlID); + } + } + else + { + if (num != 0) + { + EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, 5f, base.position.height), MouseCursor.SplitResizeLeftRight, controlID); + } + if (num != splitView.children.Length - 1) + { + EditorGUIUtility.AddCursorRect(new Rect(base.position.width - 5f, 0f, 5f, base.position.height), MouseCursor.SplitResizeLeftRight, controlID); + } + } + } + child = splitView; + splitView = (splitView.parent as SplitView); + } + splitView = (base.parent as SplitView); + } + bool flag = false; + if (base.window.mainView.GetType() != typeof(MainWindow)) + { + flag = true; + if (base.windowPosition.y == 0f) + { + this.background = "dockareaStandalone"; + } + else + { + this.background = "dockarea"; + } + } + else + { + this.background = "dockarea"; + } + if (splitView) + { + Event @event = new Event(Event.current); + @event.mousePosition += new Vector2(base.position.x, base.position.y); + splitView.SplitGUI(@event); + if (@event.type == EventType.Used) + { + Event.current.Use(); + } + } + GUIStyle style = "dockareaoverlay"; + Rect position = this.background.margin.Remove(new Rect(0f, 0f, base.position.width, base.position.height)); + position.x = (float)this.background.margin.left; + position.y = (float)this.background.margin.top; + Rect windowPosition = base.windowPosition; + float num2 = 2f; + if (windowPosition.x == 0f) + { + position.x -= num2; + position.width += num2; + } + if (windowPosition.xMax == base.window.position.width) + { + position.width += num2; + } + if (windowPosition.yMax == base.window.position.height) + { + position.height += ((!flag) ? 2f : 2f); + } + GUI.Box(position, GUIContent.none, this.background); + if (this.tabStyle == null) + { + this.tabStyle = "dragtab"; + } + this.DragTab(new Rect(position.x + 1f, position.y, position.width - 40f, 17f), this.tabStyle); + this.tabStyle = "dragtab"; + base.ShowGenericMenu(); + base.DoWindowDecorationStart(); + if (this.m_Panes.Count > 0) + { + if (this.m_Panes[this.selected] is GameView) + { + GUI.Box(position, GUIContent.none, style); + } + DockArea.BeginOffsetArea(new Rect(position.x + 2f, position.y + 17f, position.width - 4f, position.height - 17f - 2f), GUIContent.none, "TabWindowBackground"); + Vector2 vector = GUIUtility.GUIToScreenPoint(Vector2.zero); + Rect pos = base.borderSize.Remove(base.position); + pos.x = vector.x; + pos.y = vector.y; + this.m_Panes[this.selected].m_Pos = pos; + EditorGUIUtility.ResetGUIState(); + try + { + base.Invoke("OnGUI"); + } + catch (TargetInvocationException ex) + { + throw ex.InnerException; + } + EditorGUIUtility.ResetGUIState(); + if (base.actualView != null && base.actualView.m_FadeoutTime != 0f && Event.current != null && Event.current.type == EventType.Repaint) + { + base.actualView.DrawNotification(); + } + DockArea.EndOffsetArea(); + } + base.DoWindowDecorationEnd(); + GUI.Box(position, GUIContent.none, style); + EditorGUI.ShowRepaints(); + Highlighter.ControlHighlightGUI(this); + } + private void Maximize(object userData) + { + EditorWindow win = (EditorWindow)userData; + WindowLayout.Maximize(win); + } + private void Close(object userData) + { + ((EditorWindow)userData).Close(); + } + protected override void AddDefaultItemsToMenu(GenericMenu menu, EditorWindow view) + { + if (menu.GetItemCount() != 0) + { + menu.AddSeparator(string.Empty); + } + if (base.parent.window.showMode == ShowMode.MainWindow) + { + menu.AddItem(EditorGUIUtility.TextContent("DockAreaMaximize"), !(base.parent is SplitView), new GenericMenu.MenuFunction2(this.Maximize), view); + } + else + { + menu.AddDisabledItem(EditorGUIUtility.TextContent("DockAreaMaximize")); + } + menu.AddItem(EditorGUIUtility.TextContent("DockAreaCloseTab"), false, new GenericMenu.MenuFunction2(this.Close), view); + menu.AddSeparator(string.Empty); + Type[] paneTypes = base.GetPaneTypes(); + GUIContent gUIContent = EditorGUIUtility.TextContent("DockAreaAddTab"); + Type[] array = paneTypes; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + if (type != null) + { + GUIContent gUIContent2 = new GUIContent(EditorGUIUtility.TextContent(type.ToString())); + gUIContent2.text = gUIContent.text + "/" + gUIContent2.text; + menu.AddItem(gUIContent2, false, new GenericMenu.MenuFunction2(this.AddTabToHere), type); + } + } + } + private void AddTabToHere(object userData) + { + EditorWindow pane = (EditorWindow)ScriptableObject.CreateInstance((Type)userData); + this.AddTab(pane); + } + public static void EndOffsetArea() + { + if (Event.current.type == EventType.Used) + { + return; + } + GUILayoutUtility.EndLayoutGroup(); + GUI.EndGroup(); + } + public static void BeginOffsetArea(Rect screenRect, GUIContent content, GUIStyle style) + { + GUILayoutGroup gUILayoutGroup = EditorGUILayoutUtilityInternal.BeginLayoutArea(style, typeof(GUILayoutGroup)); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUILayoutGroup.resetCoords = false; + gUILayoutGroup.minWidth = (gUILayoutGroup.maxWidth = screenRect.width + 1f); + gUILayoutGroup.minHeight = (gUILayoutGroup.maxHeight = screenRect.height + 2f); + gUILayoutGroup.rect = Rect.MinMaxRect(-1f, -1f, gUILayoutGroup.rect.xMax, gUILayoutGroup.rect.yMax - 10f); + } + GUI.BeginGroup(screenRect, content, style); + } + private float GetTabWidth(float width) + { + int num = this.m_Panes.Count; + if (DockArea.s_DropInfo != null && object.ReferenceEquals(DockArea.s_DropInfo.dropArea, this)) + { + num++; + } + if (this.m_Panes.IndexOf(DockArea.s_DragPane) != -1) + { + num--; + } + return Mathf.Min(width / (float)num, 100f); + } + private int GetTabAtMousePos(Vector2 mousePos, Rect position) + { + return (int)Mathf.Min((mousePos.x - position.xMin) / this.GetTabWidth(position.width), 100f); + } + internal override void Initialize(ContainerWindow win) + { + base.Initialize(win); + this.RemoveNullWindows(); + foreach (EditorWindow current in this.m_Panes) + { + current.m_Parent = this; + } + } + private static void CheckDragWindowExists() + { + if (DockArea.s_DragMode == 1 && !PaneDragTab.get.m_Window) + { + DockArea.s_OriginalDragSource.RemoveTab(DockArea.s_DragPane); + UnityEngine.Object.DestroyImmediate(DockArea.s_DragPane); + PaneDragTab.get.Close(); + GUIUtility.hotControl = 0; + DockArea.ResetDragVars(); + } + } + private void DragTab(Rect pos, GUIStyle tabStyle) + { + int controlID = GUIUtility.GetControlID(FocusType.Passive); + float tabWidth = this.GetTabWidth(pos.width); + Event current = Event.current; + if (DockArea.s_DragMode != 0 && GUIUtility.hotControl == 0) + { + PaneDragTab.get.Close(); + DockArea.ResetDragVars(); + } + EventType typeForControl = current.GetTypeForControl(controlID); + switch (typeForControl) + { + case EventType.MouseDown: + if (pos.Contains(current.mousePosition) && GUIUtility.hotControl == 0) + { + int tabAtMousePos = this.GetTabAtMousePos(current.mousePosition, pos); + if (tabAtMousePos < this.m_Panes.Count) + { + switch (current.button) + { + case 0: + if (tabAtMousePos != this.selected) + { + this.selected = tabAtMousePos; + } + GUIUtility.hotControl = controlID; + DockArea.s_StartDragPosition = current.mousePosition; + DockArea.s_DragMode = 0; + current.Use(); + break; + case 2: + this.m_Panes[tabAtMousePos].Close(); + current.Use(); + break; + } + } + } + goto IL_6B9; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(current.mousePosition); + if (DockArea.s_DragMode != 0) + { + DockArea.s_DragMode = 0; + PaneDragTab.get.Close(); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(DockArea.CheckDragWindowExists)); + if (DockArea.s_DropInfo != null && DockArea.s_DropInfo.dropArea != null) + { + DockArea.s_DropInfo.dropArea.PerformDrop(DockArea.s_DragPane, DockArea.s_DropInfo, vector); + } + else + { + EditorWindow editorWindow = DockArea.s_DragPane; + DockArea.ResetDragVars(); + this.RemoveTab(editorWindow); + Rect position = editorWindow.position; + position.x = vector.x - position.width * 0.5f; + position.y = vector.y - position.height * 0.5f; + if (Application.platform == RuntimePlatform.WindowsEditor) + { + position.y = Mathf.Max(InternalEditorUtility.GetBoundsOfDesktopAtPoint(vector).y, position.y); + } + EditorWindow.CreateNewWindowForEditorWindow(editorWindow, false, false); + editorWindow.position = editorWindow.m_Parent.window.FitWindowRectToScreen(position, true, true); + GUIUtility.hotControl = 0; + GUIUtility.ExitGUI(); + } + DockArea.ResetDragVars(); + } + GUIUtility.hotControl = 0; + current.Use(); + } + goto IL_6B9; + case EventType.MouseMove: + case EventType.KeyDown: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_6E: + if (typeForControl != EventType.ContextClick) + { + goto IL_6B9; + } + if (pos.Contains(current.mousePosition) && GUIUtility.hotControl == 0) + { + int tabAtMousePos2 = this.GetTabAtMousePos(current.mousePosition, pos); + if (tabAtMousePos2 < this.m_Panes.Count) + { + base.PopupGenericMenu(this.m_Panes[tabAtMousePos2], new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f)); + } + } + goto IL_6B9; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 vector2 = current.mousePosition - DockArea.s_StartDragPosition; + current.Use(); + Rect screenPosition = base.screenPosition; + if (DockArea.s_DragMode == 0 && vector2.sqrMagnitude > 99f) + { + DockArea.s_DragMode = 1; + DockArea.s_PlaceholderPos = this.selected; + DockArea.s_DragPane = this.m_Panes[this.selected]; + if (this.m_Panes.Count == 1) + { + DockArea.s_IgnoreDockingForView = this; + } + else + { + DockArea.s_IgnoreDockingForView = null; + } + DockArea.s_OriginalDragSource = this; + PaneDragTab.get.content = DockArea.s_DragPane.cachedTitleContent; + base.Internal_SetAsActiveWindow(); + PaneDragTab.get.GrabThumbnail(); + PaneDragTab.get.Show(new Rect(pos.x + screenPosition.x + tabWidth * (float)this.selected, pos.y + screenPosition.y, tabWidth, pos.height), GUIUtility.GUIToScreenPoint(current.mousePosition)); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(DockArea.CheckDragWindowExists)); + GUIUtility.ExitGUI(); + } + if (DockArea.s_DragMode == 1) + { + DropInfo dropInfo = null; + ContainerWindow[] windows = ContainerWindow.windows; + Vector2 vector3 = GUIUtility.GUIToScreenPoint(current.mousePosition); + ContainerWindow inFrontOf = null; + ContainerWindow[] array = windows; + for (int i = 0; i < array.Length; i++) + { + ContainerWindow containerWindow = array[i]; + View[] allChildren = containerWindow.mainView.allChildren; + for (int j = 0; j < allChildren.Length; j++) + { + View view = allChildren[j]; + IDropArea dropArea = view as IDropArea; + if (dropArea != null) + { + dropInfo = dropArea.DragOver(DockArea.s_DragPane, vector3); + } + if (dropInfo != null) + { + break; + } + } + if (dropInfo != null) + { + inFrontOf = containerWindow; + break; + } + } + if (dropInfo == null) + { + dropInfo = new DropInfo(null); + } + if (dropInfo.type != DropInfo.Type.Tab) + { + DockArea.s_PlaceholderPos = -1; + } + DockArea.s_DropInfo = dropInfo; + if (PaneDragTab.get.m_Window) + { + PaneDragTab.get.SetDropInfo(dropInfo, vector3, inFrontOf); + } + } + } + goto IL_6B9; + case EventType.Repaint: + { + float num = pos.xMin; + int num2 = 0; + if (base.actualView) + { + for (int k = 0; k < this.m_Panes.Count; k++) + { + if (!(DockArea.s_DragPane == this.m_Panes[k])) + { + if (DockArea.s_DropInfo != null && object.ReferenceEquals(DockArea.s_DropInfo.dropArea, this) && DockArea.s_PlaceholderPos == num2) + { + num += tabWidth; + } + Rect rect = new Rect(num, pos.yMin, tabWidth, pos.height); + float num3 = Mathf.Round(rect.x); + Rect position2 = new Rect(num3, rect.y, Mathf.Round(rect.x + rect.width) - num3, rect.height); + tabStyle.Draw(position2, this.m_Panes[k].cachedTitleContent, false, false, k == this.selected, base.hasFocus); + num += tabWidth; + num2++; + } + } + } + else + { + Rect rect2 = new Rect(num, pos.yMin, tabWidth, pos.height); + float num4 = Mathf.Round(rect2.x); + Rect position3 = new Rect(num4, rect2.y, Mathf.Round(rect2.x + rect2.width) - num4, rect2.height); + tabStyle.Draw(position3, "Failed to load", false, false, true, false); + } + goto IL_6B9; + } + } + goto IL_6E; + IL_6B9: + this.selected = Mathf.Clamp(this.selected, 0, this.m_Panes.Count - 1); + } + protected override RectOffset GetBorderSize() + { + if (!base.window) + { + return new RectOffset(); + } + RectOffset rectOffset = new RectOffset(); + Rect windowPosition = base.windowPosition; + if (windowPosition.xMin != 0f) + { + rectOffset.left += 2; + } + if (windowPosition.xMax != base.window.position.width) + { + rectOffset.right += 2; + } + rectOffset.top = 17; + bool flag = base.windowPosition.y == 0f; + bool flag2 = windowPosition.yMax == base.window.position.height; + rectOffset.bottom = 4; + if (flag2) + { + rectOffset.bottom -= 2; + } + if (flag) + { + rectOffset.bottom += 3; + } + return rectOffset; + } + private static void ResetDragVars() + { + DockArea.s_DragPane = null; + DockArea.s_DropInfo = null; + DockArea.s_PlaceholderPos = -1; + DockArea.s_DragMode = 0; + DockArea.s_OriginalDragSource = null; + } + } +} diff --git a/UnityEditor/UnityEditor/DoubleCurve.cs b/UnityEditor/UnityEditor/DoubleCurve.cs new file mode 100644 index 00000000..655dd9e2 --- /dev/null +++ b/UnityEditor/UnityEditor/DoubleCurve.cs @@ -0,0 +1,70 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class DoubleCurve + { + [SerializeField] + private AnimationCurve m_MinCurve; + [SerializeField] + private AnimationCurve m_MaxCurve; + [SerializeField] + private bool m_SignedRange; + public AnimationCurve minCurve + { + get + { + return this.m_MinCurve; + } + set + { + this.m_MinCurve = value; + } + } + public AnimationCurve maxCurve + { + get + { + return this.m_MaxCurve; + } + set + { + this.m_MaxCurve = value; + } + } + public bool signedRange + { + get + { + return this.m_SignedRange; + } + set + { + this.m_SignedRange = value; + } + } + public DoubleCurve(AnimationCurve minCurve, AnimationCurve maxCurve, bool signedRange) + { + if (minCurve != null) + { + AnimationCurve animationCurve = new AnimationCurve(minCurve.keys); + this.m_MinCurve = animationCurve; + } + if (maxCurve != null) + { + AnimationCurve animationCurve = new AnimationCurve(maxCurve.keys); + this.m_MaxCurve = animationCurve; + } + else + { + Debug.LogError("Ensure that maxCurve is not null when creating a double curve. The minCurve can be null for single curves"); + } + this.m_SignedRange = signedRange; + } + public bool IsSingleCurve() + { + return this.minCurve == null || this.minCurve.length == 0; + } + } +} diff --git a/UnityEditor/UnityEditor/DoubleCurvePresetLibrary.cs b/UnityEditor/UnityEditor/DoubleCurvePresetLibrary.cs new file mode 100644 index 00000000..d63ac7b6 --- /dev/null +++ b/UnityEditor/UnityEditor/DoubleCurvePresetLibrary.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class DoubleCurvePresetLibrary : PresetLibrary + { + [Serializable] + private class DoubleCurvePreset + { + [SerializeField] + private string m_Name; + [SerializeField] + private DoubleCurve m_DoubleCurve; + public DoubleCurve doubleCurve + { + get + { + return this.m_DoubleCurve; + } + set + { + this.m_DoubleCurve = value; + } + } + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public DoubleCurvePreset(DoubleCurve doubleCurvePreset, string presetName) + { + this.doubleCurve = doubleCurvePreset; + this.name = presetName; + } + } + [SerializeField] + private List m_Presets = new List(); + private readonly Rect kUnsignedRange = new Rect(0f, 0f, 1f, 1f); + private readonly Rect kSignedRange = new Rect(0f, -1f, 1f, 2f); + public override int Count() + { + return this.m_Presets.Count; + } + public override object GetPreset(int index) + { + return this.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; + } + this.m_Presets.Add(new DoubleCurvePresetLibrary.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; + } + this.m_Presets[index].doubleCurve = doubleCurve; + } + public override void Remove(int index) + { + this.m_Presets.RemoveAt(index); + } + public override void Move(int index, int destIndex, bool insertAfterDestIndex) + { + PresetLibraryHelpers.MoveListItem(this.m_Presets, index, destIndex, insertAfterDestIndex); + } + public override void Draw(Rect rect, int index) + { + this.DrawInternal(rect, this.m_Presets[index].doubleCurve); + } + public override void Draw(Rect rect, object presetObject) + { + this.DrawInternal(rect, presetObject as DoubleCurve); + } + private void DrawInternal(Rect rect, DoubleCurve doubleCurve) + { + if (doubleCurve == null) + { + Debug.Log("DoubleCurve is null"); + return; + } + EditorGUIUtility.DrawRegionSwatch(rect, doubleCurve.maxCurve, doubleCurve.minCurve, new Color(0.8f, 0.8f, 0.8f, 1f), EditorGUI.kCurveBGColor, (!doubleCurve.signedRange) ? this.kUnsignedRange : this.kSignedRange); + } + public override string GetName(int index) + { + return this.m_Presets[index].name; + } + public override void SetName(int index, string presetName) + { + this.m_Presets[index].name = presetName; + } + } +} diff --git a/UnityEditor/UnityEditor/DoubleCurvePresetLibraryEditor.cs b/UnityEditor/UnityEditor/DoubleCurvePresetLibraryEditor.cs new file mode 100644 index 00000000..34bf5885 --- /dev/null +++ b/UnityEditor/UnityEditor/DoubleCurvePresetLibraryEditor.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(DoubleCurvePresetLibrary))] + internal class DoubleCurvePresetLibraryEditor : Editor + { + private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; + public void OnEnable() + { + string assetPath = AssetDatabase.GetAssetPath(this.target.GetInstanceID()); + this.m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(this.target, this.GetHeader(assetPath), null); + this.m_GenericPresetLibraryInspector.presetSize = new Vector2(72f, 20f); + this.m_GenericPresetLibraryInspector.lineSpacing = 5f; + } + private string GetHeader(string filePath) + { + return "Particle Curve Preset Library"; + } + public void OnDestroy() + { + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnDestroy(); + } + } + public override void OnInspectorGUI() + { + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnInspectorGUI(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/DoubleCurvePresetsContentsForPopupWindow.cs b/UnityEditor/UnityEditor/DoubleCurvePresetsContentsForPopupWindow.cs new file mode 100644 index 00000000..117f2fa9 --- /dev/null +++ b/UnityEditor/UnityEditor/DoubleCurvePresetsContentsForPopupWindow.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class DoubleCurvePresetsContentsForPopupWindow : PopupWindowContent + { + private PresetLibraryEditor m_CurveLibraryEditor; + private PresetLibraryEditorState m_CurveLibraryEditorState; + private DoubleCurve m_DoubleCurve; + private bool m_WantsToClose; + private Action m_PresetSelectedCallback; + public DoubleCurve doubleCurveToSave + { + get + { + return this.m_DoubleCurve; + } + set + { + this.m_DoubleCurve = value; + } + } + public DoubleCurvePresetsContentsForPopupWindow(DoubleCurve doubleCurveToSave, Action presetSelectedCallback) + { + this.m_DoubleCurve = doubleCurveToSave; + this.m_PresetSelectedCallback = presetSelectedCallback; + } + public override void OnClose() + { + this.m_CurveLibraryEditorState.TransferEditorPrefsState(false); + } + public PresetLibraryEditor GetPresetLibraryEditor() + { + return this.m_CurveLibraryEditor; + } + private bool IsSingleCurve(DoubleCurve doubleCurve) + { + return doubleCurve.minCurve == null || doubleCurve.minCurve.length == 0; + } + private string GetEditorPrefBaseName() + { + return PresetLibraryLocations.GetParticleCurveLibraryExtension(this.m_DoubleCurve.IsSingleCurve(), this.m_DoubleCurve.signedRange); + } + public void InitIfNeeded() + { + if (this.m_CurveLibraryEditorState == null) + { + this.m_CurveLibraryEditorState = new PresetLibraryEditorState(this.GetEditorPrefBaseName()); + this.m_CurveLibraryEditorState.TransferEditorPrefsState(true); + } + if (this.m_CurveLibraryEditor == null) + { + string particleCurveLibraryExtension = PresetLibraryLocations.GetParticleCurveLibraryExtension(this.m_DoubleCurve.IsSingleCurve(), this.m_DoubleCurve.signedRange); + ScriptableObjectSaveLoadHelper helper = new ScriptableObjectSaveLoadHelper(particleCurveLibraryExtension, SaveType.Text); + this.m_CurveLibraryEditor = new PresetLibraryEditor(helper, this.m_CurveLibraryEditorState, new Action(this.ItemClickedCallback)); + PresetLibraryEditor expr_7B = this.m_CurveLibraryEditor; + expr_7B.addDefaultPresets = (Action)Delegate.Combine(expr_7B.addDefaultPresets, new Action(this.AddDefaultPresetsToLibrary)); + this.m_CurveLibraryEditor.presetsWasReordered = new Action(this.PresetsWasReordered); + this.m_CurveLibraryEditor.previewAspect = 4f; + this.m_CurveLibraryEditor.minMaxPreviewHeight = new Vector2(24f, 24f); + this.m_CurveLibraryEditor.showHeader = true; + } + } + private void PresetsWasReordered() + { + InspectorWindow.RepaintAllInspectors(); + } + public override void OnGUI(Rect rect) + { + this.InitIfNeeded(); + this.m_CurveLibraryEditor.OnGUI(rect, this.m_DoubleCurve); + if (this.m_WantsToClose) + { + base.editorWindow.Close(); + } + } + private void ItemClickedCallback(int clickCount, object presetObject) + { + DoubleCurve doubleCurve = presetObject as DoubleCurve; + if (doubleCurve == null) + { + Debug.LogError("Incorrect object passed " + presetObject); + } + this.m_PresetSelectedCallback(doubleCurve); + } + public override Vector2 GetWindowSize() + { + return new Vector2(240f, 330f); + } + private void AddDefaultPresetsToLibrary(PresetLibrary presetLibrary) + { + DoubleCurvePresetLibrary doubleCurvePresetLibrary = presetLibrary as DoubleCurvePresetLibrary; + if (doubleCurvePresetLibrary == null) + { + Debug.Log("Incorrect preset library, should be a DoubleCurvePresetLibrary but was a " + presetLibrary.GetType()); + return; + } + bool signedRange = this.m_DoubleCurve.signedRange; + List list = new List(); + if (this.IsSingleCurve(this.m_DoubleCurve)) + { + list = DoubleCurvePresetsContentsForPopupWindow.GetUnsignedSingleCurveDefaults(signedRange); + } + else + { + if (signedRange) + { + list = DoubleCurvePresetsContentsForPopupWindow.GetSignedDoubleCurveDefaults(); + } + else + { + list = DoubleCurvePresetsContentsForPopupWindow.GetUnsignedDoubleCurveDefaults(); + } + } + foreach (DoubleCurve current in list) + { + doubleCurvePresetLibrary.Add(current, string.Empty); + } + } + private static List GetUnsignedSingleCurveDefaults(bool signedRange) + { + return new List + { + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetLinearKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetLinearMirrorKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInMirrorKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseOutKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseOutMirrorKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInOutKeys()), signedRange), + new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInOutMirrorKeys()), signedRange) + }; + } + private static List GetUnsignedDoubleCurveDefaults() + { + return new List + { + new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(0f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), false) + }; + } + private static List GetSignedDoubleCurveDefaults() + { + return new List + { + new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(-1f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), true) + }; + } + } +} diff --git a/UnityEditor/UnityEditor/DownloadResolution.cs b/UnityEditor/UnityEditor/DownloadResolution.cs new file mode 100644 index 00000000..469d6723 --- /dev/null +++ b/UnityEditor/UnityEditor/DownloadResolution.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + internal enum DownloadResolution + { + Unresolved, + SkipAsset, + TrashMyChanges, + TrashServerChanges, + Merge + } +} diff --git a/UnityEditor/UnityEditor/DragAndDrop.cs b/UnityEditor/UnityEditor/DragAndDrop.cs new file mode 100644 index 00000000..f613c165 --- /dev/null +++ b/UnityEditor/UnityEditor/DragAndDrop.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class DragAndDrop + { + private static Hashtable ms_GenericData; + public static extern UnityEngine.Object[] objectReferences + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string[] paths + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern DragAndDropVisualMode visualMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int activeControlID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static bool HandleDelayedDrag(Rect position, int id, UnityEngine.Object objectToDrag) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && current.clickCount == 1 && current.button == 0 && (Application.platform != RuntimePlatform.OSXEditor || !current.control)) + { + GUIUtility.hotControl = id; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + dragAndDropDelay.mouseDownPosition = current.mousePosition; + return true; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + if (dragAndDropDelay2.CanStartDrag()) + { + GUIUtility.hotControl = 0; + DragAndDrop.PrepareStartDrag(); + UnityEngine.Object[] objectReferences = new UnityEngine.Object[] + { + objectToDrag + }; + DragAndDrop.objectReferences = objectReferences; + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(objectToDrag)); + return true; + } + } + break; + } + return false; + } + public static void PrepareStartDrag() + { + DragAndDrop.ms_GenericData = null; + DragAndDrop.PrepareStartDrag_Internal(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void PrepareStartDrag_Internal(); + public static void StartDrag(string title) + { + if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag) + { + DragAndDrop.StartDrag_Internal(title); + } + else + { + Debug.LogError("Drags can only be started from MouseDown or MouseDrag events"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void StartDrag_Internal(string title); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AcceptDrag(); + public static object GetGenericData(string type) + { + if (DragAndDrop.ms_GenericData != null && DragAndDrop.ms_GenericData.Contains(type)) + { + return DragAndDrop.ms_GenericData[type]; + } + return null; + } + public static void SetGenericData(string type, object data) + { + if (DragAndDrop.ms_GenericData == null) + { + DragAndDrop.ms_GenericData = new Hashtable(); + } + DragAndDrop.ms_GenericData[type] = data; + } + } +} diff --git a/UnityEditor/UnityEditor/DragAndDropDelay.cs b/UnityEditor/UnityEditor/DragAndDropDelay.cs new file mode 100644 index 00000000..1ee2f06d --- /dev/null +++ b/UnityEditor/UnityEditor/DragAndDropDelay.cs @@ -0,0 +1,13 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DragAndDropDelay + { + public Vector2 mouseDownPosition; + public bool CanStartDrag() + { + return Vector2.Distance(this.mouseDownPosition, Event.current.mousePosition) > 6f; + } + } +} diff --git a/UnityEditor/UnityEditor/DragAndDropVisualMode.cs b/UnityEditor/UnityEditor/DragAndDropVisualMode.cs new file mode 100644 index 00000000..634b985d --- /dev/null +++ b/UnityEditor/UnityEditor/DragAndDropVisualMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum DragAndDropVisualMode + { + None, + Copy, + Link, + Move = 16, + Generic = 4, + Rejected = 32 + } +} diff --git a/UnityEditor/UnityEditor/DragRectGUI.cs b/UnityEditor/UnityEditor/DragRectGUI.cs new file mode 100644 index 00000000..61f6340a --- /dev/null +++ b/UnityEditor/UnityEditor/DragRectGUI.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DragRectGUI + { + private static int dragRectHash = "DragRect".GetHashCode(); + private static int s_DragCandidateState = 0; + private static float s_DragSensitivity = 1f; + public static int DragRect(Rect position, int value, int minValue, int maxValue) + { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(DragRectGUI.dragRectHash, FocusType.Passive, position); + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && current.button == 0) + { + GUIUtility.hotControl = controlID; + DragRectGUI.s_DragCandidateState = 1; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && DragRectGUI.s_DragCandidateState != 0) + { + GUIUtility.hotControl = 0; + DragRectGUI.s_DragCandidateState = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + int num = DragRectGUI.s_DragCandidateState; + if (num == 1) + { + value += (int)(HandleUtility.niceMouseDelta * DragRectGUI.s_DragSensitivity); + GUI.changed = true; + current.Use(); + if (value < minValue) + { + value = minValue; + } + else + { + if (value > maxValue) + { + value = maxValue; + } + } + } + } + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(position, MouseCursor.SlideArrow); + break; + } + return value; + } + } +} diff --git a/UnityEditor/UnityEditor/DrawCameraMode.cs b/UnityEditor/UnityEditor/DrawCameraMode.cs new file mode 100644 index 00000000..6e4deccf --- /dev/null +++ b/UnityEditor/UnityEditor/DrawCameraMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum DrawCameraMode + { + Normal = -1, + Textured, + Wireframe, + TexturedWire, + RenderPaths, + LightmapResolution + } +} diff --git a/UnityEditor/UnityEditor/DrawGizmo.cs b/UnityEditor/UnityEditor/DrawGizmo.cs new file mode 100644 index 00000000..bc4f57f5 --- /dev/null +++ b/UnityEditor/UnityEditor/DrawGizmo.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + public sealed class DrawGizmo : Attribute + { + public Type drawnType; + public GizmoType drawOptions; + public DrawGizmo(GizmoType gizmo) + { + this.drawOptions = gizmo; + } + public DrawGizmo(GizmoType gizmo, Type drawnGizmoType) + { + this.drawnType = drawnGizmoType; + this.drawOptions = gizmo; + } + } +} diff --git a/UnityEditor/UnityEditor/DrawGridParameters.cs b/UnityEditor/UnityEditor/DrawGridParameters.cs new file mode 100644 index 00000000..e4d89067 --- /dev/null +++ b/UnityEditor/UnityEditor/DrawGridParameters.cs @@ -0,0 +1,14 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct DrawGridParameters + { + public Vector3 pivot; + public Color color; + public float size; + public float alphaX; + public float alphaY; + public float alphaZ; + } +} diff --git a/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs b/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs new file mode 100644 index 00000000..4afe9d95 --- /dev/null +++ b/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs @@ -0,0 +1,17 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [InitializeOnLoad] + internal class DrivenRectTransformUndo + { + static DrivenRectTransformUndo() + { + Undo.willFlushUndoRecord = (Undo.WillFlushUndoRecord)Delegate.Combine(Undo.willFlushUndoRecord, new Undo.WillFlushUndoRecord(DrivenRectTransformUndo.ForceUpdateCanvases)); + } + private static void ForceUpdateCanvases() + { + Canvas.ForceUpdateCanvases(); + } + } +} diff --git a/UnityEditor/UnityEditor/DropInfo.cs b/UnityEditor/UnityEditor/DropInfo.cs new file mode 100644 index 00000000..29068cc5 --- /dev/null +++ b/UnityEditor/UnityEditor/DropInfo.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DropInfo + { + internal enum Type + { + Tab, + Pane, + Window + } + public IDropArea dropArea; + public object userData; + public DropInfo.Type type = DropInfo.Type.Window; + public Rect rect; + public DropInfo(IDropArea source) + { + this.dropArea = source; + } + } +} diff --git a/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs b/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs new file mode 100644 index 00000000..883e6a6c --- /dev/null +++ b/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs @@ -0,0 +1,56 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(EdgeCollider2D))] + internal class EdgeCollider2DEditor : Collider2DEditorBase + { + private PolygonEditorUtility m_PolyUtility = new PolygonEditorUtility(); + private bool m_ShowColliderInfo; + public override void OnEnable() + { + base.OnEnable(); + } + public override void OnInspectorGUI() + { + base.BeginColliderInspector(); + this.ColliderInfoGUI(); + base.EndColliderInspector(); + base.CheckColliderErrorState(); + } + private void ColliderInfoGUI() + { + EditorGUI.BeginDisabledGroup(base.targets.Length != 1); + this.m_ShowColliderInfo = EditorGUILayout.Foldout(this.m_ShowColliderInfo, "Collider Info"); + if (this.m_ShowColliderInfo) + { + EdgeCollider2D edgeCollider2D = base.targets[0] as EdgeCollider2D; + if (edgeCollider2D) + { + int pointCount = edgeCollider2D.pointCount; + string label = (!GUI.enabled) ? "---" : (string.Empty + pointCount); + EditorGUI.indentLevel++; + EditorGUILayout.LabelField("Vertices", label, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + } + EditorGUI.EndDisabledGroup(); + } + protected override void OnEditStart() + { + this.m_PolyUtility.StartEditing(this.target as Collider2D); + } + protected override void OnEditEnd() + { + this.m_PolyUtility.StopEditing(); + } + public void OnSceneGUI() + { + if (!base.editingCollider) + { + return; + } + this.m_PolyUtility.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/Editor.cs b/UnityEditor/UnityEditor/Editor.cs new file mode 100644 index 00000000..82ff50cf --- /dev/null +++ b/UnityEditor/UnityEditor/Editor.cs @@ -0,0 +1,562 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public class Editor : ScriptableObject, IPreviewable + { + private class Styles + { + public GUIStyle inspectorBig = new GUIStyle(EditorStyles.inspectorBig); + public GUIStyle inspectorBigInner = new GUIStyle("IN BigTitle inner"); + public GUIStyle centerStyle = new GUIStyle(); + public Styles() + { + this.centerStyle.alignment = TextAnchor.MiddleCenter; + this.inspectorBig.padding.bottom--; + } + } + private const float kImageSectionWidth = 44f; + internal const float kLineHeight = 16f; + private static Editor.Styles s_Styles; + private UnityEngine.Object[] m_Targets; + private int m_IsDirty; + private int m_ReferenceTargetIndex; + private PropertyHandlerCache m_PropertyHandlerCache = new PropertyHandlerCache(); + internal IPreviewable m_Preview; + internal SerializedObject m_SerializedObject; + private OptimizedGUIBlock m_OptimizedBlock; + internal InspectorMode m_InspectorMode; + internal bool hideInspector; + internal static bool m_AllowMultiObjectAccess = true; + internal virtual IPreviewable Preview + { + get + { + if (this.m_Preview == null) + { + ObjectPreview objectPreview = new ObjectPreview(); + objectPreview.Initialize(this.targets); + this.m_Preview = objectPreview; + } + return this.m_Preview; + } + } + internal PropertyHandlerCache propertyHandlerCache + { + get + { + return this.m_PropertyHandlerCache; + } + } + internal bool canEditMultipleObjects + { + get + { + return base.GetType().GetCustomAttributes(typeof(CanEditMultipleObjects), false).Length > 0; + } + } + public UnityEngine.Object target + { + get + { + return this.m_Targets[this.referenceTargetIndex]; + } + set + { + throw new InvalidOperationException("You can't set the target on an editor."); + } + } + public UnityEngine.Object[] targets + { + get + { + if (!Editor.m_AllowMultiObjectAccess) + { + Debug.LogError("The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead."); + } + return this.m_Targets; + } + } + internal virtual int referenceTargetIndex + { + get + { + return Mathf.Clamp(this.m_ReferenceTargetIndex, 0, this.m_Targets.Length - 1); + } + set + { + this.m_ReferenceTargetIndex = (Math.Abs(value * this.m_Targets.Length) + value) % this.m_Targets.Length; + } + } + internal virtual string targetTitle + { + get + { + if (this.m_Targets.Length == 1 || !Editor.m_AllowMultiObjectAccess) + { + return this.target.name; + } + return string.Concat(new object[] + { + this.m_Targets.Length, + " ", + ObjectNames.NicifyVariableName(ObjectNames.GetClassName(this.target)), + "s" + }); + } + } + public SerializedObject serializedObject + { + get + { + if (!Editor.m_AllowMultiObjectAccess) + { + Debug.LogError("The serializedObject should not be used inside OnSceneGUI or OnPreviewGUI. Use the target property directly instead."); + } + return this.GetSerializedObjectInternal(); + } + } + internal bool isInspectorDirty + { + get + { + return this.m_IsDirty != 0; + } + set + { + this.m_IsDirty = ((!value) ? 0 : 1); + } + } + internal static bool DoDrawDefaultInspector(SerializedObject obj) + { + EditorGUI.BeginChangeCheck(); + obj.Update(); + SerializedProperty iterator = obj.GetIterator(); + bool enterChildren = true; + while (iterator.NextVisible(enterChildren)) + { + EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); + enterChildren = false; + } + obj.ApplyModifiedProperties(); + return EditorGUI.EndChangeCheck(); + } + internal bool DoDrawDefaultInspector() + { + return Editor.DoDrawDefaultInspector(this.serializedObject); + } + public void DrawHeader() + { + if (EditorGUIUtility.hierarchyMode) + { + this.DrawHeaderFromInsideHierarchy(); + } + else + { + this.OnHeaderGUI(); + } + } + protected virtual void OnHeaderGUI() + { + Editor.DrawHeaderGUI(this, this.targetTitle); + } + internal virtual void OnHeaderControlsGUI() + { + GUILayoutUtility.GetRect(10f, 10f, 16f, 16f, EditorStyles.layerMaskField); + GUILayout.FlexibleSpace(); + bool flag = true; + if (!(this is AssetImporterInspector)) + { + if (!AssetDatabase.IsMainAsset(this.targets[0])) + { + flag = false; + } + AssetImporter atPath = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.targets[0])); + if (atPath && atPath.GetType() != typeof(AssetImporter)) + { + flag = false; + } + } + if (flag && GUILayout.Button("Open", EditorStyles.miniButton, new GUILayoutOption[0])) + { + if (this is AssetImporterInspector) + { + AssetDatabase.OpenAsset((this as AssetImporterInspector).assetEditor.targets); + } + else + { + AssetDatabase.OpenAsset(this.targets); + } + GUIUtility.ExitGUI(); + } + } + internal virtual void OnHeaderIconGUI(Rect iconRect) + { + if (Editor.s_Styles == null) + { + Editor.s_Styles = new Editor.Styles(); + } + Texture2D texture2D = null; + if (!this.HasPreviewGUI()) + { + bool flag = AssetPreview.IsLoadingAssetPreview(this.target.GetInstanceID()); + texture2D = AssetPreview.GetAssetPreview(this.target); + if (!texture2D) + { + if (flag) + { + this.Repaint(); + } + texture2D = AssetPreview.GetMiniThumbnail(this.target); + } + } + if (this.HasPreviewGUI()) + { + this.OnPreviewGUI(iconRect, Editor.s_Styles.inspectorBigInner); + } + else + { + if (texture2D) + { + GUI.Label(iconRect, texture2D, Editor.s_Styles.centerStyle); + } + } + } + internal virtual void OnHeaderTitleGUI(Rect titleRect, string header) + { + titleRect.yMin -= 2f; + titleRect.yMax += 2f; + GUI.Label(titleRect, header, EditorStyles.largeLabel); + } + internal virtual void DrawHeaderHelpAndSettingsGUI(Rect r) + { + if (EditorGUI.s_HelpIcon == null) + { + EditorGUI.s_HelpIcon = EditorGUIUtility.IconContent("_Help"); + EditorGUI.s_TitleSettingsIcon = EditorGUIUtility.IconContent("_Popup"); + } + UnityEngine.Object target = this.target; + EditorGUI.HelpIconButton(new Rect(r.xMax - 36f, r.y + 5f, 14f, 14f), target); + EditorGUI.BeginDisabledGroup(!this.IsEnabled()); + Rect position = new Rect(r.xMax - 18f, r.y + 5f, 14f, 14f); + if (EditorGUI.ButtonMouseDown(position, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) + { + EditorUtility.DisplayObjectContextMenu(position, this.targets, 0); + } + EditorGUI.EndDisabledGroup(); + } + private void DrawHeaderFromInsideHierarchy() + { + GUIStyle style = GUILayoutUtility.current.topLevel.style; + EditorGUILayout.EndVertical(); + this.OnHeaderGUI(); + EditorGUILayout.BeginVertical(style, new GUILayoutOption[0]); + } + internal static Rect DrawHeaderGUI(Editor editor, string header) + { + if (Editor.s_Styles == null) + { + Editor.s_Styles = new Editor.Styles(); + } + GUILayout.BeginHorizontal(Editor.s_Styles.inspectorBig, new GUILayoutOption[0]); + GUILayout.Space(38f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(19f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (editor) + { + editor.OnHeaderControlsGUI(); + } + else + { + EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + } + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + float width = lastRect.width; + Rect rect = new Rect(lastRect.x + 6f, lastRect.y + 6f, 32f, 32f); + if (editor) + { + editor.OnHeaderIconGUI(rect); + } + else + { + GUI.Label(rect, AssetPreview.GetMiniTypeThumbnail(typeof(UnityEngine.Object)), Editor.s_Styles.centerStyle); + } + Rect rect2 = new Rect(lastRect.x + 44f, lastRect.y + 6f, width - 44f - 38f - 4f, 16f); + if (editor) + { + editor.OnHeaderTitleGUI(rect2, header); + } + else + { + GUI.Label(rect2, header, EditorStyles.largeLabel); + } + if (editor) + { + editor.DrawHeaderHelpAndSettingsGUI(lastRect); + } + Event current = Event.current; + if (editor != null && !editor.IsEnabled() && current.type == EventType.MouseDown && current.button == 1 && lastRect.Contains(current.mousePosition)) + { + EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), editor.targets, 0); + current.Use(); + } + return lastRect; + } + public virtual void DrawPreview(Rect previewArea) + { + ObjectPreview.DrawPreview(this, previewArea, this.targets); + } + internal virtual bool IsEnabled() + { + UnityEngine.Object[] targets = this.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + if ((@object.hideFlags & HideFlags.NotEditable) != HideFlags.None) + { + return false; + } + if (EditorUtility.IsPersistent(@object) && !AssetDatabase.IsOpenForEdit(@object)) + { + return false; + } + } + return true; + } + internal bool IsOpenForEdit() + { + string text; + return this.IsOpenForEdit(out text); + } + internal bool IsOpenForEdit(out string message) + { + message = string.Empty; + UnityEngine.Object[] targets = this.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + if (EditorUtility.IsPersistent(@object) && !AssetDatabase.IsOpenForEdit(@object, out message)) + { + return false; + } + } + return true; + } + public virtual bool UseDefaultMargins() + { + return true; + } + public void Initialize(UnityEngine.Object[] targets) + { + throw new InvalidOperationException("You shouldn't call Initialize for Editors"); + } + public bool MoveNextTarget() + { + this.referenceTargetIndex++; + return this.referenceTargetIndex < this.targets.Length; + } + public void ResetTarget() + { + this.referenceTargetIndex = 0; + } + [ExcludeFromDocs] + public static Editor CreateEditor(UnityEngine.Object obj) + { + Type editorType = null; + return Editor.CreateEditor(obj, editorType); + } + public static Editor CreateEditor(UnityEngine.Object obj, [DefaultValue("null")] Type editorType) + { + return Editor.CreateEditor(new UnityEngine.Object[] + { + obj + }, editorType); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Editor CreateEditor(UnityEngine.Object[] objects, [DefaultValue("null")] Type editorType); + [ExcludeFromDocs] + public static Editor CreateEditor(UnityEngine.Object[] objects) + { + Type editorType = null; + return Editor.CreateEditor(objects, editorType); + } + internal virtual SerializedObject GetSerializedObjectInternal() + { + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(this.targets); + } + return this.m_SerializedObject; + } + private void CleanupPropertyEditor() + { + if (this.m_OptimizedBlock != null) + { + this.m_OptimizedBlock.Dispose(); + this.m_OptimizedBlock = null; + } + if (this.m_SerializedObject != null) + { + this.m_SerializedObject.Dispose(); + this.m_SerializedObject = null; + } + } + private void OnDisableINTERNAL() + { + this.CleanupPropertyEditor(); + } + internal void OnForceReloadInspector() + { + if (this.m_SerializedObject != null) + { + this.m_SerializedObject.SetIsDifferentCacheDirty(); + } + } + internal bool GetOptimizedGUIBlockImplementation(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) + { + if (this.m_OptimizedBlock == null) + { + this.m_OptimizedBlock = new OptimizedGUIBlock(); + } + block = this.m_OptimizedBlock; + if (!isVisible) + { + height = 0f; + return true; + } + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(this.targets); + } + else + { + this.m_SerializedObject.Update(); + } + this.m_SerializedObject.inspectorMode = this.m_InspectorMode; + SerializedProperty iterator = this.m_SerializedObject.GetIterator(); + height = 2f; + bool enterChildren = true; + while (iterator.NextVisible(enterChildren)) + { + height += EditorGUI.GetPropertyHeight(iterator, null, true) + 2f; + enterChildren = false; + } + if (height == 2f) + { + height = 0f; + } + return true; + } + internal bool OptimizedInspectorGUIImplementation(Rect contentRect) + { + SerializedProperty iterator = this.m_SerializedObject.GetIterator(); + bool enterChildren = true; + bool enabled = GUI.enabled; + contentRect.xMin += 14f; + contentRect.xMax -= 4f; + contentRect.y += 2f; + while (iterator.NextVisible(enterChildren)) + { + contentRect.height = EditorGUI.GetPropertyHeight(iterator, null, false); + EditorGUI.indentLevel = iterator.depth; + enterChildren = EditorGUI.PropertyField(contentRect, iterator); + contentRect.y += contentRect.height + 2f; + } + GUI.enabled = enabled; + return this.m_SerializedObject.ApplyModifiedProperties(); + } + protected internal static void DrawPropertiesExcluding(SerializedObject obj, params string[] propertyToExclude) + { + SerializedProperty iterator = obj.GetIterator(); + int num = 0; + bool enterChildren = true; + while (iterator.NextVisible(enterChildren)) + { + enterChildren = false; + if (num < propertyToExclude.Length && iterator.name == propertyToExclude[num]) + { + num++; + } + else + { + EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); + } + } + } + public bool DrawDefaultInspector() + { + return this.DoDrawDefaultInspector(); + } + public virtual void OnInspectorGUI() + { + this.DrawDefaultInspector(); + } + public virtual bool RequiresConstantRepaint() + { + return false; + } + internal void InternalSetTargets(UnityEngine.Object[] t) + { + this.m_Targets = t; + } + internal void InternalSetHidden(bool hidden) + { + this.hideInspector = hidden; + } + internal virtual bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) + { + block = null; + height = -1f; + return false; + } + internal virtual bool OnOptimizedInspectorGUI(Rect contentRect) + { + Debug.LogError("Not supported"); + return false; + } + public void Repaint() + { + InspectorWindow.RepaintAllInspectors(); + } + public virtual bool HasPreviewGUI() + { + return this.Preview.HasPreviewGUI(); + } + public virtual GUIContent GetPreviewTitle() + { + return this.Preview.GetPreviewTitle(); + } + public virtual Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + return null; + } + public virtual void OnPreviewGUI(Rect r, GUIStyle background) + { + this.Preview.OnPreviewGUI(r, background); + } + public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.OnPreviewGUI(r, background); + } + public virtual void OnPreviewSettings() + { + this.Preview.OnPreviewSettings(); + } + public virtual string GetInfoString() + { + return this.Preview.GetInfoString(); + } + internal virtual void OnAssetStoreInspectorGUI() + { + } + } +} diff --git a/UnityEditor/UnityEditor/EditorApplication.cs b/UnityEditor/UnityEditor/EditorApplication.cs new file mode 100644 index 00000000..791bc1ab --- /dev/null +++ b/UnityEditor/UnityEditor/EditorApplication.cs @@ -0,0 +1,298 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class EditorApplication + { + public delegate void ProjectWindowItemCallback(string guid, Rect selectionRect); + public delegate void HierarchyWindowItemCallback(int instanceID, Rect selectionRect); + public delegate void CallbackFunction(); + public static EditorApplication.ProjectWindowItemCallback projectWindowItemOnGUI; + public static EditorApplication.HierarchyWindowItemCallback hierarchyWindowItemOnGUI; + public static EditorApplication.CallbackFunction update; + public static EditorApplication.CallbackFunction delayCall; + public static EditorApplication.CallbackFunction hierarchyWindowChanged; + public static EditorApplication.CallbackFunction projectWindowChanged; + public static EditorApplication.CallbackFunction searchChanged; + internal static EditorApplication.CallbackFunction assetLabelsChanged; + public static EditorApplication.CallbackFunction modifierKeysChanged; + public static EditorApplication.CallbackFunction playmodeStateChanged; + internal static EditorApplication.CallbackFunction globalEventHandler; + internal static EditorApplication.CallbackFunction windowsReordered; + private static EditorApplication.CallbackFunction delayedCallback; + private static float s_DelayedCallbackTime; + public static extern string currentScene + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool isPlayingOrWillChangePlaymode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isPaused + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool isCompiling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isUpdating + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string applicationContentsPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string applicationPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern UnityEngine.Object tagManager + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern double timeSinceStartup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void NewScene(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool OpenScene(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenSceneAdditive(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SaveScene([DefaultValue("\"\"")] string path, [DefaultValue("false")] bool saveAsCopy); + [ExcludeFromDocs] + public static bool SaveScene(string path) + { + bool saveAsCopy = false; + return EditorApplication.SaveScene(path, saveAsCopy); + } + [ExcludeFromDocs] + public static bool SaveScene() + { + bool saveAsCopy = false; + string empty = string.Empty; + return EditorApplication.SaveScene(empty, saveAsCopy); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SaveCurrentSceneIfUserWantsTo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool SaveCurrentSceneIfUserWantsToForce(); + public static void OpenProject(string projectPath, params string[] args) + { + EditorApplication.OpenProjectInternal(projectPath, args); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void OpenProjectInternal(string projectPath, string[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SaveAssets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Step(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LockReloadAssemblies(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ExecuteMenuItem(string menuItemPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool ExecuteMenuItemOnGameObjects(string menuItemPath, GameObject[] objects); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool ExecuteMenuItemWithTemporaryContext(string menuItemPath, UnityEngine.Object[] objects); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnlockReloadAssemblies(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Exit(int returnValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetSceneRepaintDirty(); + public static void RepaintProjectWindow() + { + foreach (ProjectBrowser current in ProjectBrowser.GetAllProjectBrowsers()) + { + current.Repaint(); + } + } + public static void RepaintAnimationWindow() + { + foreach (AnimationWindow current in AnimationWindow.GetAllAnimationWindows()) + { + current.Repaint(); + } + } + public static void RepaintHierarchyWindow() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow)); + for (int i = 0; i < array.Length; i++) + { + SceneHierarchyWindow sceneHierarchyWindow = (SceneHierarchyWindow)array[i]; + sceneHierarchyWindow.Repaint(); + } + } + public static void DirtyHierarchyWindowSorting() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow)); + for (int i = 0; i < array.Length; i++) + { + SceneHierarchyWindow sceneHierarchyWindow = (SceneHierarchyWindow)array[i]; + sceneHierarchyWindow.DirtySortingMethods(); + } + } + private static void Internal_CallUpdateFunctions() + { + if (EditorApplication.update != null) + { + EditorApplication.update(); + } + } + private static void Internal_CallDelayFunctions() + { + EditorApplication.CallbackFunction callbackFunction = EditorApplication.delayCall; + EditorApplication.delayCall = null; + if (callbackFunction != null) + { + callbackFunction(); + } + } + private static void Internal_SwitchSkin() + { + EditorGUIUtility.Internal_SwitchSkin(); + } + internal static void RequestRepaintAllViews() + { + EditorApplication.Internal_RepaintAllViews(); + } + private static void Internal_RepaintAllViews() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(GUIView)); + for (int i = 0; i < array.Length; i++) + { + GUIView gUIView = (GUIView)array[i]; + gUIView.Repaint(); + } + } + private static void Internal_CallHierarchyWindowHasChanged() + { + if (EditorApplication.hierarchyWindowChanged != null) + { + EditorApplication.hierarchyWindowChanged(); + } + } + private static void Internal_CallProjectWindowHasChanged() + { + if (EditorApplication.projectWindowChanged != null) + { + EditorApplication.projectWindowChanged(); + } + } + internal static void Internal_CallSearchHasChanged() + { + if (EditorApplication.searchChanged != null) + { + EditorApplication.searchChanged(); + } + } + internal static void Internal_CallAssetLabelsHaveChanged() + { + if (EditorApplication.assetLabelsChanged != null) + { + EditorApplication.assetLabelsChanged(); + } + } + internal static void CallDelayed(EditorApplication.CallbackFunction function, float timeFromNow) + { + EditorApplication.delayedCallback = function; + EditorApplication.s_DelayedCallbackTime = Time.realtimeSinceStartup + timeFromNow; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(EditorApplication.CheckCallDelayed)); + } + private static void CheckCallDelayed() + { + if (Time.realtimeSinceStartup > EditorApplication.s_DelayedCallbackTime) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(EditorApplication.CheckCallDelayed)); + EditorApplication.delayedCallback(); + } + } + private static void Internal_PlaymodeStateChanged() + { + if (EditorApplication.playmodeStateChanged != null) + { + EditorApplication.playmodeStateChanged(); + } + } + private static void Internal_CallKeyboardModifiersChanged() + { + if (EditorApplication.modifierKeysChanged != null) + { + EditorApplication.modifierKeysChanged(); + } + } + private static void Internal_CallWindowsReordered() + { + if (EditorApplication.windowsReordered != null) + { + EditorApplication.windowsReordered(); + } + } + private static void Internal_CallGlobalEventHandler() + { + if (EditorApplication.globalEventHandler != null) + { + EditorApplication.globalEventHandler(); + } + WindowLayout.MaximizeKeyHandler(); + Event.current = null; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Beep(); + } +} diff --git a/UnityEditor/UnityEditor/EditorApplicationLayout.cs b/UnityEditor/UnityEditor/EditorApplicationLayout.cs new file mode 100644 index 00000000..a06cab5c --- /dev/null +++ b/UnityEditor/UnityEditor/EditorApplicationLayout.cs @@ -0,0 +1,66 @@ +using System; +namespace UnityEditor +{ + internal class EditorApplicationLayout + { + private static GameView m_GameView; + private static View m_RootSplit; + internal static bool IsInitializingPlaymodeLayout() + { + return EditorApplicationLayout.m_GameView != null; + } + internal static void SetPlaymodeLayout() + { + EditorApplicationLayout.InitPlaymodeLayout(); + EditorApplicationLayout.FinalizePlaymodeLayout(); + } + internal static void SetStopmodeLayout() + { + WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(false); + Toolbar.RepaintToolbar(); + } + internal static void SetPausemodeLayout() + { + EditorApplicationLayout.SetStopmodeLayout(); + } + internal static void InitPlaymodeLayout() + { + EditorApplicationLayout.m_GameView = (WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true) as GameView); + if (EditorApplicationLayout.m_GameView == null) + { + return; + } + if (EditorApplicationLayout.m_GameView.maximizeOnPlay) + { + DockArea dockArea = EditorApplicationLayout.m_GameView.m_Parent as DockArea; + if (dockArea != null) + { + ContainerWindow window = dockArea.actualView.m_Parent.window; + if (!window.maximized) + { + EditorApplicationLayout.m_RootSplit = WindowLayout.MaximizePrepare(dockArea.actualView); + } + } + } + EditorApplicationLayout.m_GameView.m_Parent.SetAsStartView(); + Toolbar.RepaintToolbar(); + } + internal static void FinalizePlaymodeLayout() + { + if (EditorApplicationLayout.m_GameView != null) + { + if (EditorApplicationLayout.m_RootSplit != null) + { + WindowLayout.MaximizePresent(EditorApplicationLayout.m_GameView, EditorApplicationLayout.m_RootSplit); + } + EditorApplicationLayout.m_GameView.m_Parent.ClearStartView(); + } + EditorApplicationLayout.Clear(); + } + private static void Clear() + { + EditorApplicationLayout.m_RootSplit = null; + EditorApplicationLayout.m_GameView = null; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorAssemblies.cs b/UnityEditor/UnityEditor/EditorAssemblies.cs new file mode 100644 index 00000000..05252f4a --- /dev/null +++ b/UnityEditor/UnityEditor/EditorAssemblies.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal static class EditorAssemblies + { + internal static Assembly[] loadedAssemblies + { + get; + private set; + } + internal static IEnumerable loadedTypes + { + get + { + return EditorAssemblies.loadedAssemblies.SelectMany((Assembly assembly) => AssemblyHelper.GetTypesFromAssembly(assembly)); + } + } + internal static IEnumerable SubclassesOf(Type parent) + { + return + from klass in EditorAssemblies.loadedTypes + where klass.IsSubclassOf(parent) + select klass; + } + private static void SetLoadedEditorAssemblies(Assembly[] assemblies) + { + EditorAssemblies.loadedAssemblies = assemblies; + EditorAssemblies.RunClassConstructors(); + } + private static void RunClassConstructors() + { + foreach (Type current in EditorAssemblies.loadedTypes) + { + if (current.IsDefined(typeof(InitializeOnLoadAttribute), false)) + { + try + { + RuntimeHelpers.RunClassConstructor(current.TypeHandle); + } + catch (TypeInitializationException ex) + { + Debug.LogError(ex.InnerException); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/EditorBehaviorMode.cs b/UnityEditor/UnityEditor/EditorBehaviorMode.cs new file mode 100644 index 00000000..1f4b1d18 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorBehaviorMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum EditorBehaviorMode + { + Mode3D, + Mode2D + } +} diff --git a/UnityEditor/UnityEditor/EditorBuildSettings.cs b/UnityEditor/UnityEditor/EditorBuildSettings.cs new file mode 100644 index 00000000..1b27923d --- /dev/null +++ b/UnityEditor/UnityEditor/EditorBuildSettings.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorBuildSettings + { + public static extern EditorBuildSettingsScene[] scenes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorBuildSettingsScene.cs b/UnityEditor/UnityEditor/EditorBuildSettingsScene.cs new file mode 100644 index 00000000..80a6a20a --- /dev/null +++ b/UnityEditor/UnityEditor/EditorBuildSettingsScene.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class EditorBuildSettingsScene : IComparable + { + private int m_Enabled; + private string m_Path; + public bool enabled + { + get + { + return this.m_Enabled != 0; + } + set + { + this.m_Enabled = ((!value) ? 0 : 1); + } + } + public string path + { + get + { + return this.m_Path; + } + set + { + this.m_Path = value.Replace("\\", "/"); + } + } + public EditorBuildSettingsScene(string path, bool enable) + { + this.m_Path = path.Replace("\\", "/"); + this.enabled = enable; + } + public EditorBuildSettingsScene() + { + } + public int CompareTo(object obj) + { + if (obj is EditorBuildSettingsScene) + { + EditorBuildSettingsScene editorBuildSettingsScene = (EditorBuildSettingsScene)obj; + return editorBuildSettingsScene.m_Path.CompareTo(this.m_Path); + } + throw new ArgumentException("object is not a EditorBuildSettingsScene"); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorCache.cs b/UnityEditor/UnityEditor/EditorCache.cs new file mode 100644 index 00000000..1f0c0da6 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorCache.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class EditorCache : IDisposable + { + private Dictionary m_EditorCache; + private Dictionary m_UsedEditors; + private EditorFeatures m_Requirements; + public EditorWrapper this[UnityEngine.Object o] + { + get + { + this.m_UsedEditors[o] = true; + if (this.m_EditorCache.ContainsKey(o)) + { + return this.m_EditorCache[o]; + } + EditorWrapper editorWrapper = EditorWrapper.Make(o, this.m_Requirements); + if (editorWrapper == null) + { + return null; + } + EditorWrapper editorWrapper2 = editorWrapper; + this.m_EditorCache[o] = editorWrapper2; + return editorWrapper2; + } + } + public EditorCache() : this(EditorFeatures.None) + { + } + public EditorCache(EditorFeatures requirements) + { + this.m_Requirements = requirements; + this.m_EditorCache = new Dictionary(); + this.m_UsedEditors = new Dictionary(); + } + public void CleanupUntouchedEditors() + { + List list = new List(); + foreach (UnityEngine.Object current in this.m_EditorCache.Keys) + { + if (!this.m_UsedEditors.ContainsKey(current)) + { + list.Add(current); + } + } + if (this.m_EditorCache != null) + { + foreach (UnityEngine.Object current2 in list) + { + this.m_EditorCache[current2].Dispose(); + this.m_EditorCache.Remove(current2); + } + } + this.m_UsedEditors.Clear(); + } + public void CleanupAllEditors() + { + this.m_UsedEditors.Clear(); + this.CleanupUntouchedEditors(); + } + public void Dispose() + { + this.CleanupAllEditors(); + GC.SuppressFinalize(this); + } + ~EditorCache() + { + Debug.LogError("Failed to dispose EditorCache."); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorCurveBinding.cs b/UnityEditor/UnityEditor/EditorCurveBinding.cs new file mode 100644 index 00000000..387ea381 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorCurveBinding.cs @@ -0,0 +1,74 @@ +using System; +namespace UnityEditor +{ + public struct EditorCurveBinding + { + public string path; + private Type m_type; + public string propertyName; + private int m_isPPtrCurve; + internal int m_ClassID; + internal int m_ScriptInstanceID; + public bool isPPtrCurve + { + get + { + return this.m_isPPtrCurve != 0; + } + } + public Type type + { + get + { + return this.m_type; + } + set + { + this.m_type = value; + this.m_ClassID = 0; + this.m_ScriptInstanceID = 0; + } + } + public override int GetHashCode() + { + return this.path.GetHashCode() ^ this.type.GetHashCode() << 2 ^ this.propertyName.GetHashCode() << 4; + } + public override bool Equals(object other) + { + if (!(other is EditorCurveBinding)) + { + return false; + } + EditorCurveBinding rhs = (EditorCurveBinding)other; + return this == rhs; + } + public static EditorCurveBinding FloatCurve(string inPath, Type inType, string inPropertyName) + { + return new EditorCurveBinding + { + path = inPath, + type = inType, + propertyName = inPropertyName, + m_isPPtrCurve = 0 + }; + } + public static EditorCurveBinding PPtrCurve(string inPath, Type inType, string inPropertyName) + { + return new EditorCurveBinding + { + path = inPath, + type = inType, + propertyName = inPropertyName, + m_isPPtrCurve = 1 + }; + } + public static bool operator ==(EditorCurveBinding lhs, EditorCurveBinding rhs) + { + return (lhs.m_ClassID == 0 || rhs.m_ClassID == 0 || (lhs.m_ClassID == rhs.m_ClassID && lhs.m_ScriptInstanceID == rhs.m_ScriptInstanceID)) && (lhs.path == rhs.path && lhs.type == rhs.type && lhs.propertyName == rhs.propertyName) && lhs.m_isPPtrCurve == rhs.m_isPPtrCurve; + } + public static bool operator !=(EditorCurveBinding lhs, EditorCurveBinding rhs) + { + return !(lhs == rhs); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorExtensionMethods.cs b/UnityEditor/UnityEditor/EditorExtensionMethods.cs new file mode 100644 index 00000000..f6980c67 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorExtensionMethods.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal static class EditorExtensionMethods + { + internal static bool MainActionKeyForControl(this Event evt, int controlId) + { + if (GUIUtility.keyboardControl != controlId) + { + return false; + } + bool flag = evt.alt || evt.shift || evt.command || evt.control; + if (evt.type == EventType.KeyDown && evt.character == ' ' && !flag) + { + evt.Use(); + return false; + } + return evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter) && !flag; + } + internal static bool IsArrayOrList(this Type listType) + { + return listType.IsArray || (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)); + } + internal static Type GetArrayOrListElementType(this Type listType) + { + if (listType.IsArray) + { + return listType.GetElementType(); + } + if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)) + { + return listType.GetGenericArguments()[0]; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorFeatures.cs b/UnityEditor/UnityEditor/EditorFeatures.cs new file mode 100644 index 00000000..7a5e9818 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorFeatures.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [Flags] + internal enum EditorFeatures + { + None = 0, + PreviewGUI = 1, + OnSceneDrag = 4 + } +} diff --git a/UnityEditor/UnityEditor/EditorGUI.cs b/UnityEditor/UnityEditor/EditorGUI.cs new file mode 100644 index 00000000..c0470cef --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUI.cs @@ -0,0 +1,5367 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class EditorGUI + { + internal class RecycledTextEditor : TextEditor + { + internal static bool s_ActuallyEditing; + internal static bool s_AllowContextCutOrPaste = true; + internal bool IsEditingControl(int id) + { + return GUIUtility.keyboardControl == id && this.controlID == id && EditorGUI.RecycledTextEditor.s_ActuallyEditing && GUIView.current.hasFocus; + } + public virtual void BeginEditing(int id, string text, Rect position, GUIStyle style, bool multiline, bool passwordField) + { + if (this.IsEditingControl(id)) + { + return; + } + if (EditorGUI.activeEditor != null) + { + EditorGUI.activeEditor.EndEditing(); + } + EditorGUI.activeEditor = this; + this.controlID = id; + GUIContent arg_3B_0 = this.content; + EditorGUI.s_OriginalText = text; + arg_3B_0.text = text; + this.multiline = multiline; + this.style = style; + this.position = position; + this.isPasswordField = passwordField; + EditorGUI.RecycledTextEditor.s_ActuallyEditing = true; + this.scrollOffset = Vector2.zero; + UnityEditor.Undo.IncrementCurrentGroup(); + } + public virtual void EndEditing() + { + if (EditorGUI.activeEditor == this) + { + EditorGUI.activeEditor = null; + } + this.controlID = 0; + EditorGUI.RecycledTextEditor.s_ActuallyEditing = false; + EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = true; + UnityEditor.Undo.IncrementCurrentGroup(); + } + } + internal sealed class DelayedTextEditor : EditorGUI.RecycledTextEditor + { + private int controlThatHadFocus; + private int messageControl; + internal string controlThatHadFocusValue = string.Empty; + private GUIView viewThatHadFocus; + private int controlThatLostFocus; + private bool m_IgnoreBeginGUI; + public void BeginGUI() + { + if (this.m_IgnoreBeginGUI) + { + return; + } + if (GUIUtility.keyboardControl == this.controlID) + { + this.controlThatHadFocus = GUIUtility.keyboardControl; + this.controlThatHadFocusValue = this.content.text; + this.viewThatHadFocus = GUIView.current; + } + else + { + this.controlThatHadFocus = 0; + } + } + public void EndGUI(EventType type) + { + int num = 0; + if (this.controlThatLostFocus != 0) + { + this.messageControl = this.controlThatLostFocus; + this.controlThatLostFocus = 0; + } + if (this.controlThatHadFocus != 0 && this.controlThatHadFocus != GUIUtility.keyboardControl) + { + num = this.controlThatHadFocus; + this.controlThatHadFocus = 0; + } + if (num != 0) + { + this.messageControl = num; + this.m_IgnoreBeginGUI = true; + this.viewThatHadFocus.SendEvent(EditorGUIUtility.CommandEvent("DelayedControlShouldCommit")); + this.m_IgnoreBeginGUI = false; + this.messageControl = 0; + } + } + public override void EndEditing() + { + base.EndEditing(); + this.messageControl = 0; + } + public string OnGUI(int id, string value, out bool changed) + { + Event current = Event.current; + if (current.type == EventType.ExecuteCommand && current.commandName == "DelayedControlShouldCommit" && id == this.messageControl) + { + changed = (value != this.controlThatHadFocusValue); + current.Use(); + return this.controlThatHadFocusValue; + } + changed = false; + return value; + } + } + internal sealed class PopupMenuEvent + { + public string commandName; + public GUIView receiver; + public PopupMenuEvent(string cmd, GUIView v) + { + this.commandName = cmd; + this.receiver = v; + } + public void SendEvent() + { + if (this.receiver) + { + this.receiver.SendEvent(EditorGUIUtility.CommandEvent(this.commandName)); + } + else + { + Debug.LogError("BUG: We don't have a receiver set up, please report"); + } + } + } + internal sealed class PopupCallbackInfo + { + internal const string kPopupMenuChangedMessage = "PopupMenuChanged"; + public static EditorGUI.PopupCallbackInfo instance; + private int m_ControlID; + private int m_SelectedIndex; + private GUIView m_SourceView; + public PopupCallbackInfo(int controlID) + { + this.m_ControlID = controlID; + this.m_SourceView = GUIView.current; + } + public static int GetSelectedValueForControl(int controlID, int selected) + { + Event current = Event.current; + if (current.type == EventType.ExecuteCommand && current.commandName == "PopupMenuChanged") + { + if (EditorGUI.PopupCallbackInfo.instance == null) + { + Debug.LogError("Popup menu has no instance"); + return selected; + } + if (EditorGUI.PopupCallbackInfo.instance.m_ControlID == controlID) + { + selected = EditorGUI.PopupCallbackInfo.instance.m_SelectedIndex; + EditorGUI.PopupCallbackInfo.instance = null; + GUI.changed = true; + current.Use(); + } + } + return selected; + } + internal void SetEnumValueDelegate(object userData, string[] options, int selected) + { + this.m_SelectedIndex = selected; + if (this.m_SourceView) + { + this.m_SourceView.SendEvent(EditorGUIUtility.CommandEvent("PopupMenuChanged")); + } + } + } + internal struct VUMeterData + { + public float lastValue; + public float peakValue; + public Texture2D texture; + public float peakValueTime; + public bool IsDone() + { + return this.lastValue == 0f && this.peakValue == 0f; + } + } + internal delegate UnityEngine.Object ObjectFieldValidator(UnityEngine.Object[] references, Type objType, SerializedProperty property); + private const double kFoldoutExpandTimeout = 0.7; + private const float kDragSensitivity = 0.03f; + internal const float kMiniLabelW = 13f; + internal const float kLabelW = 80f; + internal const float kSpacing = 5f; + internal const float kSpacingSubLabel = 2f; + internal const float kSliderMinW = 60f; + internal const float kSliderMaxW = 100f; + internal const float kSingleLineHeight = 16f; + internal const float kStructHeaderLineHeight = 16f; + internal const float kObjectFieldThumbnailHeight = 64f; + private const float kIndentPerLevel = 15f; + internal const int kControlVerticalSpacing = 2; + private const int kInspTitlebarIconWidth = 16; + private const int kInspTitlebarToggleWidth = 16; + private const int kInspTitlebarSpacing = 2; + private const float VU_SPLIT = 0.9f; + private static EditorGUI.RecycledTextEditor activeEditor; + internal static EditorGUI.DelayedTextEditor s_DelayedTextEditor = new EditorGUI.DelayedTextEditor(); + internal static EditorGUI.RecycledTextEditor s_RecycledEditor = new EditorGUI.RecycledTextEditor(); + internal static string s_OriginalText = string.Empty; + internal static string s_RecycledCurrentEditingString; + internal static float s_RecycledCurrentEditingFloat; + internal static int s_RecycledCurrentEditingInt; + private static bool bKeyEventActive = false; + internal static bool s_DragToPosition = true; + internal static bool s_Dragged = false; + internal static bool s_PostPoneMove = false; + internal static bool s_SelectAllOnMouseUp = true; + private static double s_FoldoutDestTime; + private static int s_DragUpdatedOverID = 0; + private static bool s_WasBoldDefaultFont; + private static int s_FoldoutHash = "Foldout".GetHashCode(); + private static int s_TagFieldHash = "s_TagFieldHash".GetHashCode(); + private static int s_PPtrHash = "s_PPtrHash".GetHashCode(); + private static int s_ObjectFieldHash = "s_ObjectFieldHash".GetHashCode(); + private static int s_ToggleHash = "s_ToggleHash".GetHashCode(); + private static int s_ColorHash = "s_ColorHash".GetHashCode(); + private static int s_CurveHash = "s_CurveHash".GetHashCode(); + private static int s_LayerMaskField = "s_LayerMaskField".GetHashCode(); + private static int s_MaskField = "s_MaskField".GetHashCode(); + private static int s_GenericField = "s_GenericField".GetHashCode(); + private static int s_PopupHash = "EditorPopup".GetHashCode(); + private static int s_KeyEventFieldHash = "KeyEventField".GetHashCode(); + private static int s_TextFieldHash = "EditorTextField".GetHashCode(); + private static int s_SearchFieldHash = "EditorSearchField".GetHashCode(); + private static int s_TextAreaHash = "EditorTextField".GetHashCode(); + private static int s_PasswordFieldHash = "PasswordField".GetHashCode(); + private static int s_FloatFieldHash = "EditorTextField".GetHashCode(); + private static int s_DelayedTextFieldHash = "DelayedEditorTextField".GetHashCode(); + private static int s_ArraySizeFieldHash = "ArraySizeField".GetHashCode(); + private static int s_SliderHash = "EditorSlider".GetHashCode(); + private static int s_SliderKnobHash = "EditorSliderKnob".GetHashCode(); + private static int s_MinMaxSliderHash = "EditorMinMaxSlider".GetHashCode(); + private static int s_TitlebarHash = "GenericTitlebar".GetHashCode(); + private static int s_ProgressBarHash = "s_ProgressBarHash".GetHashCode(); + private static int s_SelectableLabelHash = "s_SelectableLabel".GetHashCode(); + private static int s_SortingLayerFieldHash = "s_SortingLayerFieldHash".GetHashCode(); + private static int s_DragCandidateState = 0; + private static float kDragDeadzone = 16f; + private static Vector2 s_DragStartPos; + private static float s_DragStartValue = 0f; + private static int s_DragStartIntValue = 0; + private static float s_DragSensitivity = 0f; + internal static string kFloatFieldFormatString = "g7"; + internal static string kIntFieldFormatString = "#######0"; + internal static int ms_IndentLevel = 0; + private static float[] s_Vector2Floats = new float[2]; + private static GUIContent[] s_XYLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y") + }; + private static float[] s_Vector3Floats = new float[3]; + private static GUIContent[] s_XYZLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y"), + new GUIContent("Z") + }; + private static float[] s_Vector4Floats = new float[4]; + private static GUIContent[] s_XYZWLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y"), + new GUIContent("Z"), + new GUIContent("W") + }; + private static GUIContent[] s_WHLabels = new GUIContent[] + { + new GUIContent("W"), + new GUIContent("H") + }; + private static int s_ColorPickID; + private static int s_CurveID; + internal static Color kCurveColor = Color.green; + internal static Color kCurveBGColor = new Color(0.337f, 0.337f, 0.337f, 1f); + internal static GUIContent s_HelpIcon; + internal static GUIContent s_TitleSettingsIcon; + private static GUIContent s_PropertyFieldTempContent = new GUIContent(); + private static GUIContent s_IconDropDown; + private static Material s_IconTextureInactive; + internal static GUIContent s_PrefixLabel = new GUIContent(null); + internal static Rect s_PrefixTotalRect; + internal static Rect s_PrefixRect; + internal static GUIStyle s_PrefixStyle; + private static bool s_ShowMixedValue; + private static GUIContent s_MixedValueContent = new GUIContent("—", "Mixed Values"); + private static Color s_MixedValueContentColor = new Color(1f, 1f, 1f, 0.5f); + private static Color s_MixedValueContentColorTemp = Color.white; + private static Stack s_PropertyStack = new Stack(); + private static Stack s_EnabledStack = new Stack(); + private static Stack s_ChangedStack = new Stack(); + private static SerializedProperty s_PendingPropertyKeyboardHandling = null; + private static SerializedProperty s_PendingPropertyDelete = null; + private static Material tmp; + private static Texture2D s_Texture; + private static int s_LastThickness; + internal static bool s_CollectingToolTips; + private static readonly int s_GradientHash = "s_GradientHash".GetHashCode(); + private static int s_GradientID; + private static int s_ButtonMouseDownHash = "ButtonMouseDown".GetHashCode(); + private static int s_MouseDeltaReaderHash = "MouseDeltaReader".GetHashCode(); + private static Vector2 s_MouseDeltaReaderLastPos; + private static Texture2D s_VerticalVUTexture; + private static Texture2D s_HorizontalVUTexture; + public static bool showMixedValue + { + get + { + return EditorGUI.s_ShowMixedValue; + } + set + { + EditorGUI.s_ShowMixedValue = value; + } + } + internal static GUIContent mixedValueContent + { + get + { + return EditorGUI.s_MixedValueContent; + } + } + public static bool actionKey + { + get + { + if (Event.current == null) + { + return false; + } + if (Application.platform == RuntimePlatform.OSXEditor) + { + return Event.current.command; + } + return Event.current.control; + } + } + public static int indentLevel + { + get + { + return EditorGUI.ms_IndentLevel; + } + set + { + EditorGUI.ms_IndentLevel = value; + } + } + internal static float indent + { + get + { + return (float)EditorGUI.indentLevel * 15f; + } + } + internal static Material alphaMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewAlphaMaterial.mat") as Material; + } + } + internal static Material transparentMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewTransparentMaterial.mat") as Material; + } + } + internal static Material gammaCorrectTransparentMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewGammaCorrectTransparentMaterial.mat") as Material; + } + } + internal static Texture2D transparentCheckerTexture + { + get + { + if (EditorGUIUtility.isProSkin) + { + return EditorGUIUtility.LoadRequired("Previews/Textures/textureCheckerDark.png") as Texture2D; + } + return EditorGUIUtility.LoadRequired("Previews/Textures/textureChecker.png") as Texture2D; + } + } + internal static Material lightmapRGBMMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewEncodedLightmapRGBMMaterial.mat") as Material; + } + } + internal static Material lightmapDoubleLDRMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewEncodedLightmapDoubleLDRMaterial.mat") as Material; + } + } + internal static Material normalmapMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewEncodedNormalsMaterial.mat") as Material; + } + } + internal static Material gammaCorrectMaterial + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewGammaCorrectMaterial.mat") as Material; + } + } + internal static Material gammaCorrectMaterialNoClip + { + get + { + return EditorGUIUtility.LoadRequired("Previews/PreviewGammaCorrectNoClip.mat") as Material; + } + } + internal static bool isCollectingTooltips + { + get + { + return EditorGUI.s_CollectingToolTips; + } + set + { + EditorGUI.s_CollectingToolTips = value; + } + } + internal static void BeginHandleMixedValueContentColor() + { + EditorGUI.s_MixedValueContentColorTemp = GUI.contentColor; + GUI.contentColor = ((!EditorGUI.showMixedValue) ? GUI.contentColor : (GUI.contentColor * EditorGUI.s_MixedValueContentColor)); + } + internal static void EndHandleMixedValueContentColor() + { + GUI.contentColor = EditorGUI.s_MixedValueContentColorTemp; + } + internal static bool IsEditingTextField() + { + return EditorGUI.RecycledTextEditor.s_ActuallyEditing; + } + internal static void EndEditingActiveTextField() + { + if (EditorGUI.activeEditor != null) + { + EditorGUI.activeEditor.EndEditing(); + } + } + public static void FocusTextInControl(string name) + { + GUI.FocusControl(name); + EditorGUIUtility.editingTextField = true; + } + internal static void ClearStacks() + { + EditorGUI.s_EnabledStack.Clear(); + EditorGUI.s_ChangedStack.Clear(); + EditorGUI.s_PropertyStack.Clear(); + ScriptAttributeUtility.s_DrawerStack.Clear(); + } + public static void BeginDisabledGroup(bool disabled) + { + EditorGUI.s_EnabledStack.Push(GUI.enabled); + GUI.enabled &= !disabled; + } + public static void EndDisabledGroup() + { + GUI.enabled = EditorGUI.s_EnabledStack.Pop(); + } + public static void BeginChangeCheck() + { + EditorGUI.s_ChangedStack.Push(GUI.changed); + GUI.changed = false; + } + public static bool EndChangeCheck() + { + bool changed = GUI.changed; + GUI.changed |= EditorGUI.s_ChangedStack.Pop(); + return changed; + } + private static void ShowTextEditorPopupMenu() + { + GenericMenu genericMenu = new GenericMenu(); + if (EditorGUI.s_RecycledEditor.hasSelection && !EditorGUI.s_RecycledEditor.isPasswordField) + { + if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Cut", GUIView.current).SendEvent)); + } + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Copy", GUIView.current).SendEvent)); + } + else + { + if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut")); + } + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy")); + } + if (EditorGUI.s_RecycledEditor.CanPaste() && EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Paste"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Paste", GUIView.current).SendEvent)); + } + genericMenu.ShowAsContext(); + } + internal static void BeginCollectTooltips() + { + EditorGUI.isCollectingTooltips = true; + } + internal static void EndCollectTooltips() + { + EditorGUI.isCollectingTooltips = false; + } + public static void DropShadowLabel(Rect position, string text) + { + EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), "PreOverlayLabel", 0.6f); + } + public static void DropShadowLabel(Rect position, GUIContent content) + { + EditorGUI.DoDropShadowLabel(position, content, "PreOverlayLabel", 0.6f); + } + public static void DropShadowLabel(Rect position, string text, GUIStyle style) + { + EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), style, 0.6f); + } + public static void DropShadowLabel(Rect position, GUIContent content, GUIStyle style) + { + EditorGUI.DoDropShadowLabel(position, content, style, 0.6f); + } + internal static void DoDropShadowLabel(Rect position, GUIContent content, GUIStyle style, float shadowOpa) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + EditorGUI.DrawLabelShadow(position, content, style, shadowOpa); + style.Draw(position, content, false, false, false, false); + } + internal static void DrawLabelShadow(Rect position, GUIContent content, GUIStyle style, float shadowOpa) + { + Color color = GUI.color; + Color contentColor = GUI.contentColor; + Color backgroundColor = GUI.backgroundColor; + GUI.contentColor = new Color(0f, 0f, 0f, 0f); + style.Draw(position, content, false, false, false, false); + position.y += 1f; + GUI.backgroundColor = new Color(0f, 0f, 0f, 0f); + GUI.contentColor = contentColor; + EditorGUI.Draw4(position, content, 1f, GUI.color.a * shadowOpa, style); + EditorGUI.Draw4(position, content, 2f, GUI.color.a * shadowOpa * 0.42f, style); + GUI.color = color; + GUI.backgroundColor = backgroundColor; + } + private static void Draw4(Rect position, GUIContent content, float offset, float alpha, GUIStyle style) + { + GUI.color = new Color(0f, 0f, 0f, alpha); + position.y -= offset; + style.Draw(position, content, false, false, false, false); + position.y += offset * 2f; + style.Draw(position, content, false, false, false, false); + position.y -= offset; + position.x -= offset; + style.Draw(position, content, false, false, false, false); + position.x += offset * 2f; + style.Draw(position, content, false, false, false, false); + } + internal static string DoTextField(EditorGUI.RecycledTextEditor editor, int id, Rect position, string text, GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField) + { + Event current = Event.current; + string result = text; + if (text == null) + { + text = string.Empty; + } + if (EditorGUI.showMixedValue) + { + text = string.Empty; + } + if (GUIUtility.keyboardControl == id && GUIView.current.hasFocus && Event.current.type != EventType.Layout) + { + if (editor.IsEditingControl(id)) + { + editor.position = position; + editor.style = style; + editor.controlID = id; + editor.multiline = multiline; + editor.isPasswordField = passwordField; + editor.ClampPos(); + editor.UpdateScrollOffsetIfNeeded(); + } + else + { + if (EditorGUIUtility.editingTextField) + { + editor.BeginEditing(id, text, position, style, multiline, passwordField); + if (GUI.skin.settings.cursorColor.a > 0f) + { + editor.SelectAll(); + } + } + } + } + if (editor.controlID == id && GUIUtility.keyboardControl != id) + { + editor.controlID = 0; + } + bool flag = false; + string text2 = editor.content.text; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && current.button == 0) + { + if (editor.IsEditingControl(id)) + { + if (Event.current.clickCount == 2 && GUI.skin.settings.doubleClickSelectsWord) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + editor.SelectCurrentWord(); + editor.MouseDragSelectsWholeWords(true); + editor.DblClickSnap(TextEditor.DblClickSnapping.WORDS); + EditorGUI.s_DragToPosition = false; + } + else + { + if (Event.current.clickCount == 3 && GUI.skin.settings.tripleClickSelectsLine) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + editor.SelectCurrentParagraph(); + editor.MouseDragSelectsWholeWords(true); + editor.DblClickSnap(TextEditor.DblClickSnapping.PARAGRAPHS); + EditorGUI.s_DragToPosition = false; + } + else + { + editor.MoveCursorToPosition(Event.current.mousePosition); + EditorGUI.s_SelectAllOnMouseUp = false; + } + } + } + else + { + GUIUtility.keyboardControl = id; + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.MoveCursorToPosition(Event.current.mousePosition); + if (GUI.skin.settings.cursorColor.a > 0f) + { + EditorGUI.s_SelectAllOnMouseUp = true; + } + } + GUIUtility.hotControl = id; + current.Use(); + } + goto IL_923; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + if (EditorGUI.s_Dragged && EditorGUI.s_DragToPosition) + { + editor.MoveSelectionToAltCursor(); + flag = true; + } + else + { + if (EditorGUI.s_PostPoneMove) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + } + else + { + if (EditorGUI.s_SelectAllOnMouseUp) + { + if (GUI.skin.settings.cursorColor.a > 0f) + { + editor.SelectAll(); + } + EditorGUI.s_SelectAllOnMouseUp = false; + } + } + } + editor.MouseDragSelectsWholeWords(false); + EditorGUI.s_DragToPosition = true; + EditorGUI.s_Dragged = false; + EditorGUI.s_PostPoneMove = false; + if (current.button == 0) + { + GUIUtility.hotControl = 0; + current.Use(); + } + } + goto IL_923; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_130: + switch (typeForControl) + { + case EventType.ValidateCommand: + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + switch (commandName) + { + case "Cut": + case "Copy": + if (editor.hasSelection) + { + current.Use(); + } + break; + case "Paste": + if (editor.CanPaste()) + { + current.Use(); + } + break; + case "SelectAll": + current.Use(); + break; + case "UndoRedoPerformed": + editor.content.text = text; + current.Use(); + break; + } + } + goto IL_923; + case EventType.ExecuteCommand: + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + switch (commandName) + { + case "OnLostFocus": + if (EditorGUI.activeEditor != null) + { + EditorGUI.activeEditor.EndEditing(); + } + current.Use(); + break; + case "Cut": + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.Cut(); + flag = true; + break; + case "Copy": + editor.Copy(); + current.Use(); + break; + case "Paste": + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.Paste(); + flag = true; + break; + case "SelectAll": + editor.SelectAll(); + current.Use(); + break; + } + } + goto IL_923; + case EventType.DragExited: + goto IL_923; + case EventType.ContextClick: + if (position.Contains(current.mousePosition)) + { + if (!editor.IsEditingControl(id)) + { + GUIUtility.keyboardControl = id; + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.MoveCursorToPosition(Event.current.mousePosition); + } + EditorGUI.ShowTextEditorPopupMenu(); + Event.current.Use(); + } + goto IL_923; + default: + goto IL_923; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + if (!current.shift && editor.hasSelection && EditorGUI.s_DragToPosition) + { + editor.MoveAltCursorToPosition(Event.current.mousePosition); + } + else + { + if (current.shift) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + } + else + { + editor.SelectToPosition(Event.current.mousePosition); + } + EditorGUI.s_DragToPosition = false; + EditorGUI.s_SelectAllOnMouseUp = false; + } + EditorGUI.s_Dragged = true; + current.Use(); + } + goto IL_923; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) + { + char character = current.character; + if (editor.IsEditingControl(id) && editor.HandleKeyEvent(current)) + { + current.Use(); + flag = true; + } + else + { + if (current.keyCode == KeyCode.Escape) + { + if (editor.IsEditingControl(id)) + { + if (style == EditorStyles.toolbarSearchField || style == EditorStyles.searchField) + { + EditorGUI.s_OriginalText = string.Empty; + } + editor.content.text = EditorGUI.s_OriginalText; + editor.EndEditing(); + flag = true; + } + } + else + { + if (character == '\n' || character == '\u0003') + { + if (!editor.IsEditingControl(id)) + { + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.SelectAll(); + } + else + { + if (multiline && !current.alt && !current.shift && !current.control) + { + editor.Insert(character); + flag = true; + goto IL_923; + } + editor.EndEditing(); + } + current.Use(); + } + else + { + if (character == '\t' || current.keyCode == KeyCode.Tab) + { + if (multiline && editor.IsEditingControl(id)) + { + bool flag2 = !current.alt && !current.shift && !current.control && character == '\t'; + if (flag2) + { + editor.Insert(character); + flag = true; + } + } + } + else + { + if (character != '\u0019' && character != '\u001b') + { + if (editor.IsEditingControl(id)) + { + bool flag3 = (allowedletters == null || allowedletters.IndexOf(character) != -1) && character != '\0'; + if (flag3) + { + editor.Insert(character); + flag = true; + } + else + { + if (Input.compositionString != string.Empty) + { + editor.ReplaceSelection(string.Empty); + flag = true; + } + current.Use(); + } + } + } + } + } + } + } + } + goto IL_923; + case EventType.Repaint: + { + string text3; + if (editor.IsEditingControl(id)) + { + text3 = ((!passwordField) ? editor.content.text : string.Empty.PadRight(editor.content.text.Length, '*')); + } + else + { + if (EditorGUI.showMixedValue) + { + text3 = EditorGUI.s_MixedValueContent.text; + } + else + { + text3 = ((!passwordField) ? text : string.Empty.PadRight(text.Length, '*')); + } + } + if (GUIUtility.hotControl == 0) + { + EditorGUIUtility.AddCursorRect(position, MouseCursor.Text); + } + if (!editor.IsEditingControl(id)) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUIUtility.TempContent(text3), id, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + editor.DrawCursor(text3); + } + goto IL_923; + } + } + goto IL_130; + IL_923: + if (GUIUtility.keyboardControl == id) + { + GUIUtility.textFieldInput = true; + } + changed = false; + if (flag) + { + changed = (text2 != editor.content.text); + current.Use(); + } + if (changed) + { + GUI.changed = true; + return editor.content.text; + } + EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = true; + return result; + } + internal static Event KeyEventField(Rect position, Event evt) + { + return EditorGUI.DoKeyEventField(position, evt, GUI.skin.textField); + } + internal static Event DoKeyEventField(Rect position, Event _event, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_KeyEventFieldHash, FocusType.Native, position); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + GUIUtility.hotControl = controlID; + current.Use(); + if (EditorGUI.bKeyEventActive) + { + EditorGUI.bKeyEventActive = false; + } + else + { + EditorGUI.bKeyEventActive = true; + } + } + return _event; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = controlID; + current.Use(); + } + return _event; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == controlID && EditorGUI.bKeyEventActive) + { + if (current.character == '\0' && ((current.alt && (current.keyCode == KeyCode.AltGr || current.keyCode == KeyCode.LeftAlt || current.keyCode == KeyCode.RightAlt)) || (current.control && (current.keyCode == KeyCode.LeftControl || current.keyCode == KeyCode.RightControl)) || (current.command && (current.keyCode == KeyCode.LeftCommand || current.keyCode == KeyCode.RightCommand || current.keyCode == KeyCode.LeftWindows || current.keyCode == KeyCode.RightWindows)) || (current.shift && (current.keyCode == KeyCode.LeftShift || current.keyCode == KeyCode.RightShift || current.keyCode == KeyCode.None)))) + { + return _event; + } + EditorGUI.bKeyEventActive = false; + GUI.changed = true; + GUIUtility.hotControl = 0; + Event result = new Event(current); + current.Use(); + return result; + } + break; + case EventType.Repaint: + if (EditorGUI.bKeyEventActive) + { + GUIContent content = EditorGUIUtility.TempContent("[Please press a key]"); + style.Draw(position, content, controlID); + } + else + { + string t = InternalEditorUtility.TextifyEvent(_event); + style.Draw(position, EditorGUIUtility.TempContent(t), controlID); + } + break; + } + return _event; + } + internal static bool DoObjectFoldout(int id, Rect position, UnityEngine.Object[] targetObjs, bool foldout) + { + int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; + position.xMin -= (float)num; + bool enabled = GUI.enabled; + GUI.enabled = true; + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + if (current.button == 1 && targetObjs[0] != null) + { + EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); + current.Use(); + } + else + { + if (current.button == 0 && (Application.platform != RuntimePlatform.OSXEditor || !current.control)) + { + GUIUtility.hotControl = id; + GUIUtility.keyboardControl = id; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + dragAndDropDelay.mouseDownPosition = current.mousePosition; + current.Use(); + } + } + } + goto IL_36B; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + GUIUtility.hotControl = 0; + current.Use(); + if (position.Contains(current.mousePosition)) + { + GUI.changed = true; + foldout = !foldout; + } + } + goto IL_36B; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Repaint: + case EventType.Layout: + IL_7E: + if (typeForControl != EventType.ContextClick) + { + goto IL_36B; + } + if (position.Contains(current.mousePosition) && targetObjs[0] != null) + { + EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); + current.Use(); + } + goto IL_36B; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + if (dragAndDropDelay2.CanStartDrag()) + { + GUIUtility.hotControl = 0; + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = targetObjs; + if (targetObjs.Length > 1) + { + DragAndDrop.StartDrag(""); + } + else + { + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(targetObjs[0])); + } + } + current.Use(); + } + goto IL_36B; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) + { + if (current.keyCode == KeyCode.LeftArrow) + { + foldout = false; + current.Use(); + } + if (current.keyCode == KeyCode.RightArrow) + { + foldout = true; + current.Use(); + } + } + goto IL_36B; + case EventType.DragUpdated: + if (EditorGUI.s_DragUpdatedOverID == id) + { + if (position.Contains(current.mousePosition)) + { + if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) + { + foldout = true; + HandleUtility.Repaint(); + } + } + else + { + EditorGUI.s_DragUpdatedOverID = 0; + } + } + else + { + if (position.Contains(current.mousePosition)) + { + EditorGUI.s_DragUpdatedOverID = id; + EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; + } + } + if (position.Contains(current.mousePosition)) + { + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, false); + Event.current.Use(); + } + goto IL_36B; + case EventType.DragPerform: + if (position.Contains(current.mousePosition)) + { + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, true); + DragAndDrop.AcceptDrag(); + Event.current.Use(); + } + goto IL_36B; + } + goto IL_7E; + IL_36B: + GUI.enabled = enabled; + return foldout; + } + internal static void LabelFieldInternal(Rect position, GUIContent label, GUIContent label2, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Passive, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + if (Event.current.type == EventType.Repaint) + { + style.Draw(position, label2, controlID); + } + } + public static bool Toggle(Rect position, bool value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.IndentedRect(position), controlID, value, GUIContent.none, EditorStyles.toggle); + } + public static bool Toggle(Rect position, string label, bool value) + { + return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value); + } + public static bool Toggle(Rect position, bool value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(position, controlID, value, GUIContent.none, style); + } + public static bool Toggle(Rect position, string label, bool value, GUIStyle style) + { + return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value, style); + } + public static bool Toggle(Rect position, GUIContent label, bool value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, EditorStyles.toggle); + } + public static bool Toggle(Rect position, GUIContent label, bool value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, style); + } + internal static bool ToggleLeftInternal(Rect position, GUIContent label, bool value, GUIStyle labelStyle) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.IndentedRect(position); + Rect labelPosition = EditorGUI.IndentedRect(position); + labelPosition.xMin += 13f; + EditorGUI.HandlePrefixLabel(position, labelPosition, label, controlID, labelStyle); + return EditorGUIInternal.DoToggleForward(position2, controlID, value, GUIContent.none, EditorStyles.toggle); + } + internal static bool DoToggle(Rect position, int id, bool value, GUIContent content, GUIStyle style) + { + return EditorGUIInternal.DoToggleForward(position, id, value, content, style); + } + internal static string TextFieldInternal(Rect position, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, false, false); + return text; + } + internal static string TextFieldInternal(Rect position, GUIContent label, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.PrefixLabel(position, controlID, label), text, style, null, out flag, false, false, false); + return text; + } + internal static string ToolbarSearchField(int id, Rect position, string text, bool showWithPopupArrow) + { + Rect position2 = position; + position2.width -= 14f; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position2, text, (!showWithPopupArrow) ? EditorStyles.toolbarSearchField : EditorStyles.toolbarSearchFieldPopup, null, out flag, false, false, false); + Rect position3 = position; + position3.x += position.width - 14f; + position3.width = 14f; + if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.toolbarSearchFieldCancelButtonEmpty : EditorStyles.toolbarSearchFieldCancelButton) && text != string.Empty) + { + text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); + GUIUtility.keyboardControl = 0; + } + return text; + } + internal static string ToolbarSearchField(Rect position, string[] searchModes, ref int searchMode, string text) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); + return EditorGUI.ToolbarSearchField(controlID, position, searchModes, ref searchMode, text); + } + internal static string ToolbarSearchField(int id, Rect position, string[] searchModes, ref int searchMode, string text) + { + bool flag = searchModes != null; + if (flag) + { + searchMode = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(id, searchMode); + Rect rect = position; + rect.width = 20f; + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(id); + EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(searchModes), searchMode, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) + { + Event.current.Use(); + } + } + } + text = EditorGUI.ToolbarSearchField(id, position, text, flag); + if (flag && text == string.Empty && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && Event.current.type == EventType.Repaint) + { + position.width -= 14f; + EditorGUI.BeginDisabledGroup(true); + EditorStyles.toolbarSearchFieldPopup.Draw(position, EditorGUIUtility.TempContent(searchModes[searchMode]), id, false); + EditorGUI.EndDisabledGroup(); + } + return text; + } + internal static string SearchField(Rect position, string text) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); + Rect position2 = position; + position2.width -= 15f; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, position2, text, EditorStyles.searchField, null, out flag, false, false, false); + Rect position3 = position; + position3.x += position.width - 15f; + position3.width = 15f; + if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.searchFieldCancelButtonEmpty : EditorStyles.searchFieldCancelButton) && text != string.Empty) + { + text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); + GUIUtility.keyboardControl = 0; + } + return text; + } + internal static string ScrollableTextAreaInternal(Rect position, string text, ref Vector2 scrollPosition, GUIStyle style) + { + if (Event.current.type == EventType.Layout) + { + return text; + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); + float height = style.CalcHeight(GUIContent.Temp(text), position.width); + Rect rect = new Rect(0f, 0f, position.width, height); + Vector2 contentOffset = style.contentOffset; + if (position.height < rect.height) + { + Rect position2 = position; + position2.width = GUI.skin.verticalScrollbar.fixedWidth; + position2.height -= 2f; + position2.y += 1f; + position2.x = position.x + position.width - position2.width; + position.width -= position2.width; + height = style.CalcHeight(GUIContent.Temp(text), position.width); + rect = new Rect(0f, 0f, position.width, height); + if (position.Contains(Event.current.mousePosition) && Event.current.type == EventType.ScrollWheel) + { + float value = scrollPosition.y + Event.current.delta.y * 10f; + scrollPosition.y = Mathf.Clamp(value, 0f, rect.height); + Event.current.Use(); + } + scrollPosition.y = GUI.VerticalScrollbar(position2, scrollPosition.y, position.height, 0f, rect.height); + if (!EditorGUI.s_RecycledEditor.IsEditingControl(controlID)) + { + style.contentOffset -= scrollPosition; + style.Internal_clipOffset = scrollPosition; + } + else + { + EditorGUI.s_RecycledEditor.scrollOffset.y = scrollPosition.y; + } + } + EventType type = Event.current.type; + bool flag; + string result = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + if (type != Event.current.type) + { + scrollPosition = EditorGUI.s_RecycledEditor.scrollOffset; + } + style.contentOffset = contentOffset; + style.Internal_clipOffset = Vector2.zero; + return result; + } + internal static string TextAreaInternal(Rect position, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + return text; + } + internal static void SelectableLabelInternal(Rect position, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SelectableLabelHash, FocusType.Keyboard, position); + Event current = Event.current; + if (GUIUtility.keyboardControl == controlID && current.GetTypeForControl(controlID) == EventType.KeyDown) + { + KeyCode keyCode = current.keyCode; + switch (keyCode) + { + case KeyCode.UpArrow: + case KeyCode.DownArrow: + case KeyCode.RightArrow: + case KeyCode.LeftArrow: + case KeyCode.Home: + case KeyCode.End: + case KeyCode.PageUp: + case KeyCode.PageDown: + goto IL_A0; + case KeyCode.Insert: + IL_64: + if (keyCode != KeyCode.Space) + { + if (current.character != '\t') + { + current.Use(); + } + goto IL_A0; + } + GUIUtility.hotControl = 0; + GUIUtility.keyboardControl = 0; + goto IL_A0; + } + goto IL_64; + } + IL_A0: + if (current.type == EventType.ExecuteCommand && (current.commandName == "Paste" || current.commandName == "Cut") && GUIUtility.keyboardControl == controlID) + { + current.Use(); + } + Color cursorColor = GUI.skin.settings.cursorColor; + GUI.skin.settings.cursorColor = new Color(0f, 0f, 0f, 0f); + EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = false; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + GUI.skin.settings.cursorColor = cursorColor; + } + public static string DoPasswordField(int id, Rect position, string password, GUIStyle style) + { + bool flag; + return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, password, style, null, out flag, false, false, true); + } + public static string DoPasswordField(int id, Rect position, GUIContent label, string password, GUIStyle style) + { + bool flag; + return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, EditorGUI.PrefixLabel(position, id, label), password, style, null, out flag, false, false, true); + } + internal static string PasswordFieldInternal(Rect position, string password, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoPasswordField(controlID, EditorGUI.IndentedRect(position), password, style); + } + internal static string PasswordFieldInternal(Rect position, GUIContent label, string password, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoPasswordField(controlID, position, label, password, style); + } + internal static float FloatFieldInternal(Rect position, float value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kFloatFieldFormatString, style, false); + } + internal static float FloatFieldInternal(Rect position, GUIContent label, float value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kFloatFieldFormatString, style, true); + } + private static float CalculateFloatDragSensitivity(float value) + { + if (float.IsInfinity(value) || float.IsNaN(value)) + { + return 0f; + } + return Mathf.Max(1f, Mathf.Pow(Mathf.Abs(value), 0.5f)) * 0.03f; + } + private static float CalculateIntDragSensitivity(int value) + { + return Mathf.Max(1f, Mathf.Pow(Mathf.Abs((float)value), 0.5f) * 0.03f); + } + private static void DragNumberValue(Rect dragHotZone, int id, bool isFloat, ref float floatVal, ref int intVal, float dragSensitivity) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (dragHotZone.Contains(current.mousePosition) && current.button == 0) + { + GUIUtility.hotControl = id; + if (EditorGUI.activeEditor != null) + { + EditorGUI.activeEditor.EndEditing(); + } + current.Use(); + GUIUtility.keyboardControl = id; + EditorGUI.s_DragCandidateState = 1; + EditorGUI.s_DragStartValue = floatVal; + EditorGUI.s_DragStartIntValue = intVal; + EditorGUI.s_DragStartPos = current.mousePosition; + EditorGUI.s_DragSensitivity = dragSensitivity; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && EditorGUI.s_DragCandidateState != 0) + { + GUIUtility.hotControl = 0; + EditorGUI.s_DragCandidateState = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + int num = EditorGUI.s_DragCandidateState; + if (num != 1) + { + if (num == 2) + { + if (isFloat) + { + floatVal += HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity; + floatVal = MathUtils.RoundBasedOnMinimumDifference(floatVal, EditorGUI.s_DragSensitivity); + } + else + { + intVal += Mathf.RoundToInt(HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity); + } + GUI.changed = true; + current.Use(); + } + } + else + { + if ((Event.current.mousePosition - EditorGUI.s_DragStartPos).sqrMagnitude > EditorGUI.kDragDeadzone) + { + EditorGUI.s_DragCandidateState = 2; + GUIUtility.keyboardControl = id; + } + current.Use(); + } + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape && EditorGUI.s_DragCandidateState != 0) + { + floatVal = EditorGUI.s_DragStartValue; + intVal = EditorGUI.s_DragStartIntValue; + GUI.changed = true; + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(dragHotZone, MouseCursor.SlideArrow); + break; + } + } + internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable) + { + return EditorGUI.DoFloatField(editor, position, dragHotZone, id, value, formatString, style, draggable, (Event.current.GetTypeForControl(id) != EventType.MouseDown) ? 0f : EditorGUI.CalculateFloatDragSensitivity(EditorGUI.s_DragStartValue)); + } + internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + { + int num = 0; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, true, ref value, ref num, formatString, style, draggable, dragSensitivity); + return value; + } + internal static int DoIntField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, int value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + { + float num = 0f; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, false, ref num, ref value, formatString, style, draggable, dragSensitivity); + return value; + } + internal static void DoNumberField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, bool isFloat, ref float floatVal, ref int intVal, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + { + string allowedletters = (!isFloat) ? "0123456789-" : "inftynaeINFTYNAE0123456789.,-"; + if (draggable) + { + EditorGUI.DragNumberValue(dragHotZone, id, isFloat, ref floatVal, ref intVal, dragSensitivity); + } + Event current = Event.current; + string text; + if (GUIUtility.keyboardControl == id || (current.type == EventType.MouseDown && current.button == 0 && position.Contains(current.mousePosition))) + { + if (!editor.IsEditingControl(id)) + { + text = (EditorGUI.s_RecycledCurrentEditingString = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString))); + } + else + { + text = EditorGUI.s_RecycledCurrentEditingString; + if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") + { + text = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString)); + } + } + } + else + { + text = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString)); + } + if (GUIUtility.keyboardControl == id) + { + bool flag; + text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); + if (flag) + { + GUI.changed = true; + EditorGUI.s_RecycledCurrentEditingString = text; + if (isFloat) + { + string a = text.ToLower(); + if (a == "inf" || a == "infinity") + { + floatVal = float.PositiveInfinity; + } + else + { + if (a == "-inf" || a == "-infinity") + { + floatVal = float.NegativeInfinity; + } + else + { + text = text.Replace(',', '.'); + if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out floatVal)) + { + floatVal = (EditorGUI.s_RecycledCurrentEditingFloat = 0f); + return; + } + if (float.IsNaN(floatVal)) + { + floatVal = 0f; + } + EditorGUI.s_RecycledCurrentEditingFloat = floatVal; + } + } + } + else + { + if (!int.TryParse(text, out intVal)) + { + intVal = (EditorGUI.s_RecycledCurrentEditingInt = 0); + return; + } + EditorGUI.s_RecycledCurrentEditingInt = intVal; + } + } + } + else + { + bool flag; + text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); + } + } + internal static int ArraySizeField(Rect position, GUIContent label, int value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ArraySizeFieldHash, FocusType.Keyboard, position); + return EditorGUI.ArraySizeField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, style); + } + internal static int ArraySizeField(Rect position, int id, int value, GUIStyle style) + { + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(position, id, value.ToString(EditorGUI.kIntFieldFormatString), "0123456789-", style); + if (EditorGUI.EndChangeCheck()) + { + try + { + value = int.Parse(s, CultureInfo.InvariantCulture.NumberFormat); + } + catch (FormatException) + { + } + } + return value; + } + internal static string DelayedTextField(Rect position, string value, string allowedLetters, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_DelayedTextFieldHash, FocusType.Keyboard, position); + return EditorGUI.DelayedTextField(position, controlID, value, allowedLetters, style); + } + internal static string DelayedTextField(Rect position, int id, string value, string allowedLetters, GUIStyle style) + { + string text; + if (GUIUtility.keyboardControl == id) + { + if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) + { + text = (EditorGUI.s_RecycledCurrentEditingString = value); + } + else + { + text = EditorGUI.s_RecycledCurrentEditingString; + } + Event current = Event.current; + if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") + { + text = value; + } + } + else + { + text = value; + } + bool changed = GUI.changed; + bool flag; + text = EditorGUI.s_DelayedTextEditor.OnGUI(id, text, out flag); + GUI.changed = false; + if (!flag) + { + text = EditorGUI.DoTextField(EditorGUI.s_DelayedTextEditor, id, position, text, style, allowedLetters, out flag, false, false, false); + GUI.changed = false; + if (GUIUtility.keyboardControl == id) + { + if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) + { + if (value != text) + { + GUI.changed = true; + value = text; + } + } + else + { + EditorGUI.s_RecycledCurrentEditingString = text; + } + } + } + else + { + GUI.changed = true; + value = text; + } + GUI.changed |= changed; + return value; + } + internal static int IntFieldInternal(Rect position, int value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kIntFieldFormatString, style, false, EditorGUI.CalculateIntDragSensitivity(value)); + } + internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kIntFieldFormatString, style, true, EditorGUI.CalculateIntDragSensitivity(value)); + } + public static float Slider(Rect position, float value, float leftValue, float rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, value, leftValue, rightValue, EditorGUI.kFloatFieldFormatString); + } + public static float Slider(Rect position, string label, float value, float leftValue, float rightValue) + { + return EditorGUI.Slider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + } + public static float Slider(Rect position, GUIContent label, float value, float leftValue, float rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return EditorGUI.DoSlider(EditorGUI.PrefixLabel(position, controlID, label), EditorGUIUtility.DragZoneRect(position), controlID, value, leftValue, rightValue, EditorGUI.kFloatFieldFormatString); + } + internal static float PowerSlider(Rect position, float sliderValue, float min, float max, float power) + { + float leftValue = EditorGUI.PowPreserveSign(min, 1f / power); + float rightValue = EditorGUI.PowPreserveSign(max, 1f / power); + float num = EditorGUI.PowPreserveSign(sliderValue, 1f / power); + EditorGUI.BeginChangeCheck(); + num = GUI.HorizontalSlider(position, num, leftValue, rightValue); + num = EditorGUI.PowPreserveSign(num, power); + if (!EditorGUI.EndChangeCheck()) + { + num = sliderValue; + } + return num; + } + internal static float PowerSlider(Rect position, string label, float sliderValue, float min, float max, float power) + { + return EditorGUI.PowerSlider(position, EditorGUIUtility.TempContent(label), sliderValue, min, max, power); + } + internal static float PowerSlider(Rect position, GUIContent label, float sliderValue, float min, float max, float power) + { + position = EditorGUI.PrefixLabel(position, 46389, label); + return EditorGUI.PowerSlider(position, sliderValue, min, max, power); + } + private static float PowPreserveSign(float f, float p) + { + float num = Mathf.Pow(Mathf.Abs(f), p); + return (f >= 0f) ? num : (-num); + } + private static void DoPropertyContextMenu(SerializedProperty property) + { + GenericMenu genericMenu = new GenericMenu(); + SerializedProperty serializedProperty = property.serializedObject.FindProperty(property.propertyPath); + ScriptAttributeUtility.GetHandler(property).AddMenuItems(property, genericMenu); + if (property.hasMultipleDifferentValues && !property.hasVisibleChildren) + { + TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, serializedProperty, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); + } + if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("Revert Value to Prefab"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.SetPrefabOverride), serializedProperty); + } + if (property.propertyPath.LastIndexOf(']') == property.propertyPath.Length - 1) + { + if (genericMenu.GetItemCount() > 0) + { + genericMenu.AddSeparator(string.Empty); + } + genericMenu.AddItem(EditorGUIUtility.TextContent("Duplicate Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DuplicateArrayElement), serializedProperty); + genericMenu.AddItem(EditorGUIUtility.TextContent("Delete Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DeleteArrayElement), serializedProperty); + } + if (Event.current.shift) + { + if (genericMenu.GetItemCount() > 0) + { + genericMenu.AddSeparator(string.Empty); + } + genericMenu.AddItem(EditorGUIUtility.TextContent("Print Property Path"), false, delegate(object e) + { + Debug.Log(((SerializedProperty)e).propertyPath); + }, serializedProperty); + } + Event.current.Use(); + if (genericMenu.GetItemCount() == 0) + { + return; + } + genericMenu.ShowAsContext(); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue) + { + EditorGUI.Slider(position, property, leftValue, rightValue, property.displayName); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, string label) + { + EditorGUI.Slider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + float floatValue = EditorGUI.Slider(position, label, property.floatValue, leftValue, rightValue); + if (EditorGUI.EndChangeCheck()) + { + property.floatValue = floatValue; + } + EditorGUI.EndProperty(); + } + public static int IntSlider(Rect position, int value, int leftValue, int rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + } + public static int IntSlider(Rect position, string label, int value, int leftValue, int rightValue) + { + return EditorGUI.IntSlider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + } + public static int IntSlider(Rect position, GUIContent label, int value, int leftValue, int rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.PrefixLabel(position, controlID, label), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue) + { + EditorGUI.IntSlider(position, property, leftValue, rightValue, property.displayName); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, string label) + { + EditorGUI.IntSlider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.IntSlider(position, label, property.intValue, leftValue, rightValue); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + EditorGUI.EndProperty(); + } + private static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString) + { + float num = position.width; + if (num >= 65f + EditorGUIUtility.fieldWidth) + { + float num2 = num - 5f - EditorGUIUtility.fieldWidth; + EditorGUI.BeginChangeCheck(); + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderKnobHash, FocusType.Native, position); + if (GUIUtility.keyboardControl == id && !EditorGUI.s_RecycledEditor.IsEditingControl(id)) + { + GUIUtility.keyboardControl = controlID; + } + value = GUI.Slider(new Rect(position.x, position.y, num2, position.height), value, 0f, left, right, GUI.skin.horizontalSlider, (!EditorGUI.showMixedValue) ? GUI.skin.horizontalSliderThumb : "SliderMixed", true, controlID); + if (GUIUtility.keyboardControl == controlID || GUIUtility.hotControl == controlID) + { + GUIUtility.keyboardControl = id; + } + if (GUIUtility.keyboardControl == id && Event.current.type == EventType.KeyDown && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && (Event.current.keyCode == KeyCode.LeftArrow || Event.current.keyCode == KeyCode.RightArrow)) + { + float num3 = MathUtils.GetClosestPowerOfTen(Mathf.Abs((right - left) * 0.01f)); + if (formatString == EditorGUI.kIntFieldFormatString && num3 < 1f) + { + num3 = 1f; + } + if (Event.current.shift) + { + num3 *= 10f; + } + if (Event.current.keyCode == KeyCode.LeftArrow) + { + value -= num3 * 0.5001f; + } + else + { + value += num3 * 0.5001f; + } + value = MathUtils.RoundToMultipleOf(value, num3); + GUI.changed = true; + Event.current.Use(); + } + if (EditorGUI.EndChangeCheck()) + { + float minDifference = (right - left) / (num2 - (float)GUI.skin.horizontalSlider.padding.horizontal - GUI.skin.horizontalSliderThumb.fixedWidth); + value = MathUtils.RoundBasedOnMinimumDifference(value, minDifference); + if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) + { + EditorGUI.s_RecycledEditor.EndEditing(); + } + } + value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, new Rect(position.x + num2 + 5f, position.y, EditorGUIUtility.fieldWidth, position.height), dragZonePosition, id, value, formatString, EditorStyles.numberField, true); + } + else + { + num = Mathf.Min(EditorGUIUtility.fieldWidth, num); + position.x = position.xMax - num; + position.width = num; + value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, dragZonePosition, id, value, formatString, EditorStyles.numberField, true); + } + value = Mathf.Clamp(value, Mathf.Min(left, right), Mathf.Max(left, right)); + return value; + } + public static void MinMaxSlider(GUIContent label, Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native); + EditorGUI.DoMinMaxSlider(EditorGUI.PrefixLabel(position, controlID, label), controlID, ref minValue, ref maxValue, minLimit, maxLimit); + } + public static void MinMaxSlider(Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + EditorGUI.DoMinMaxSlider(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native), ref minValue, ref maxValue, minLimit, maxLimit); + } + private static void DoMinMaxSlider(Rect position, int id, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + float num = maxValue - minValue; + EditorGUI.BeginChangeCheck(); + EditorGUIExt.DoMinMaxSlider(position, id, ref minValue, ref num, minLimit, maxLimit, minLimit, maxLimit, GUI.skin.horizontalSlider, EditorStyles.minMaxHorizontalSliderThumb, true); + if (EditorGUI.EndChangeCheck()) + { + maxValue = minValue + num; + } + } + private static int PopupInternal(Rect position, string label, int selectedIndex, string[] displayedOptions, GUIStyle style) + { + return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + } + private static int PopupInternal(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position); + return EditorGUI.DoPopup(EditorGUI.PrefixLabel(position, controlID, label), controlID, selectedIndex, displayedOptions, style); + } + private static void Popup(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.BeginChangeCheck(); + int enumValueIndex = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.enumValueIndex : -1, EditorGUIUtility.TempContent(property.enumDisplayNames)); + if (EditorGUI.EndChangeCheck()) + { + property.enumValueIndex = enumValueIndex; + } + } + internal static void Popup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.intValue : -1, displayedOptions); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + EditorGUI.EndProperty(); + } + private static Enum EnumPopupInternal(Rect position, GUIContent label, Enum selected, GUIStyle style) + { + Type type = selected.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] names = Enum.GetNames(type); + int num = Array.IndexOf(names, Enum.GetName(type, selected)); + num = EditorGUI.Popup(position, label, num, EditorGUIUtility.TempContent(( + from x in names + select ObjectNames.NicifyVariableName(x)).ToArray()), style); + if (num < 0 || num >= names.Length) + { + return selected; + } + return (Enum)Enum.Parse(type, names[num]); + } + private static int IntPopupInternal(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style) + { + int num; + if (optionValues != null) + { + num = 0; + while (num < optionValues.Length && selectedValue != optionValues[num]) + { + num++; + } + } + else + { + num = selectedValue; + } + num = EditorGUI.PopupInternal(position, label, num, displayedOptions, style); + if (optionValues == null) + { + return num; + } + if (num < 0 || num >= optionValues.Length) + { + return selectedValue; + } + return optionValues[num]; + } + internal static void IntPopupInternal(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.IntPopupInternal(position, label, property.intValue, displayedOptions, optionValues, EditorStyles.popup); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + EditorGUI.EndProperty(); + } + internal static int DoPopup(Rect position, int controlID, int selected, GUIContent[] popupValues, GUIStyle style) + { + selected = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, selected); + GUIContent gUIContent = null; + if (gUIContent == null) + { + if (EditorGUI.showMixedValue) + { + gUIContent = EditorGUI.s_MixedValueContent; + } + else + { + if (selected < 0 || selected >= popupValues.Length) + { + gUIContent = GUIContent.none; + } + else + { + gUIContent = popupValues[selected]; + } + } + } + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(controlID)) + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + position.y = position.y - (float)(selected * 16) - 19f; + } + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); + EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + current.Use(); + } + return selected; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_6A: + if (type != EventType.MouseDown) + { + return selected; + } + if (current.button == 0 && position.Contains(current.mousePosition)) + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + position.y = position.y - (float)(selected * 16) - 19f; + } + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); + EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + GUIUtility.keyboardControl = controlID; + current.Use(); + } + return selected; + case EventType.Repaint: + { + Font font = style.font; + if (font && EditorGUIUtility.GetBoldDefaultFont() && font == EditorStyles.miniFont) + { + style.font = EditorStyles.miniBoldFont; + } + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, gUIContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + style.font = font; + return selected; + } + } + goto IL_6A; + } + internal static string TagFieldInternal(Rect position, string tag, GUIStyle style) + { + position = EditorGUI.IndentedRect(position); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + Event current = Event.current; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + string[] tags = InternalEditorUtility.tags; + if (selectedValueForControl >= tags.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; + Selection.activeObject = EditorApplication.tagManager; + } + else + { + tag = tags[selectedValueForControl]; + } + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + string[] tags2 = InternalEditorUtility.tags; + int i; + for (i = 0; i < tags2.Length; i++) + { + if (tags2[i] == tag) + { + break; + } + } + ArrayUtility.Add(ref tags2, string.Empty); + ArrayUtility.Add(ref tags2, "Add Tag..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); + return tag; + } + if (Event.current.type == EventType.Repaint) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, (!EditorGUI.showMixedValue) ? EditorGUIUtility.TempContent(tag) : EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + return tag; + } + internal static string TagFieldInternal(Rect position, GUIContent label, string tag, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + string[] tags = InternalEditorUtility.tags; + if (selectedValueForControl >= tags.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; + Selection.activeObject = EditorApplication.tagManager; + } + else + { + tag = tags[selectedValueForControl]; + } + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + string[] tags2 = InternalEditorUtility.tags; + int i; + for (i = 0; i < tags2.Length; i++) + { + if (tags2[i] == tag) + { + break; + } + } + ArrayUtility.Add(ref tags2, string.Empty); + ArrayUtility.Add(ref tags2, "Add Tag..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); + return tag; + } + if (Event.current.type == EventType.Repaint) + { + style.Draw(position, EditorGUIUtility.TempContent(tag), controlID, false); + } + return tag; + } + internal static int LayerFieldInternal(Rect position, GUIContent label, int layer, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + bool changed = GUI.changed; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + if (selectedValueForControl >= InternalEditorUtility.layers.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Layers"; + Selection.activeObject = EditorApplication.tagManager; + GUI.changed = changed; + } + else + { + int num = 0; + for (int i = 0; i < 32; i++) + { + if (InternalEditorUtility.GetLayerName(i).Length != 0) + { + if (num == selectedValueForControl) + { + layer = i; + break; + } + num++; + } + } + } + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + int num2 = 0; + for (int j = 0; j < 32; j++) + { + if (InternalEditorUtility.GetLayerName(j).Length != 0) + { + if (j == layer) + { + break; + } + num2++; + } + } + string[] layers = InternalEditorUtility.layers; + ArrayUtility.Add(ref layers, string.Empty); + ArrayUtility.Add(ref layers, "Add Layer..."); + EditorGUI.DoPopup(position, controlID, num2, EditorGUIUtility.TempContent(layers), style); + Event.current.Use(); + return layer; + } + if (current.type == EventType.Repaint) + { + style.Draw(position, EditorGUIUtility.TempContent(InternalEditorUtility.GetLayerName(layer)), controlID, false); + } + return layer; + } + internal static int MaskFieldInternal(Rect position, GUIContent label, int mask, string[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + return MaskFieldGUI.DoMaskField(position, controlID, mask, displayedOptions, style); + } + internal static int MaskFieldInternal(Rect position, int mask, string[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + return MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), controlID, mask, displayedOptions, style); + } + internal static Enum EnumMaskFieldInternal(Rect position, GUIContent label, Enum enumValue, GUIStyle style) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + return Enum.Parse(enumValue.GetType(), MaskFieldGUI.DoMaskField(position2, controlID, Convert.ToInt32(enumValue), flagNames, style).ToString()) as Enum; + } + internal static Enum EnumMaskFieldInternal(Rect position, Enum enumValue, GUIStyle style) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style); + return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + } + internal static Enum EnumMaskField(Rect position, Enum enumValue, GUIStyle style, out int changedFlags, out bool changedToValue) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style, out changedFlags, out changedToValue); + return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + } + public static void ObjectField(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.ObjectField(position, property, null, label, EditorStyles.objectField); + } + public static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label) + { + EditorGUI.ObjectField(position, property, objType, label, EditorStyles.objectField); + } + internal static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.ObjectFieldInternal(position, property, objType, label, style); + EditorGUI.EndProperty(); + } + private static void ObjectFieldInternal(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PPtrHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + bool allowSceneObjects = false; + if (property != null) + { + UnityEngine.Object targetObject = property.serializedObject.targetObject; + if (targetObject != null && !EditorUtility.IsPersistent(targetObject)) + { + allowSceneObjects = true; + } + } + EditorGUI.DoObjectField(position, position, controlID, null, null, property, null, allowSceneObjects, style); + } + public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + return EditorGUI.DoObjectField(EditorGUI.IndentedRect(position), EditorGUI.IndentedRect(position), controlID, obj, objType, null, null, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, true); + } + public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType) + { + return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, true); + } + public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + if (EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f) + { + float num = Mathf.Min(position.width, position.height); + position.height = num; + position.xMin = position.xMax - num; + } + return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType) + { + return EditorGUI.ObjectField(position, label, obj, objType, true); + } + internal static UnityEngine.Object ValidateObjectFieldAssignment(UnityEngine.Object[] references, Type objType, SerializedProperty property) + { + if (references.Length > 0) + { + bool flag = references[0] != null && references[0].GetType() == typeof(Texture2D); + if (objType == typeof(Sprite) && flag) + { + return SpriteUtility.TextureToSprite(references[0] as Texture2D); + } + if (property != null) + { + if ((property.type == "PPtr" || property.type == "PPtr<$Sprite>") && flag) + { + return SpriteUtility.TextureToSprite(references[0] as Texture2D); + } + if (references[0] != null && property.ValidateObjectReferenceValue(references[0])) + { + return references[0]; + } + if (property.type == "vector" && flag) + { + return SpriteUtility.TextureToSprite(references[0] as Texture2D); + } + } + else + { + if (references[0] != null && references[0].GetType() == typeof(GameObject) && typeof(Component).IsAssignableFrom(objType)) + { + GameObject gameObject = (GameObject)references[0]; + references = gameObject.GetComponents(typeof(Component)); + } + UnityEngine.Object[] array = references; + for (int i = 0; i < array.Length; i++) + { + UnityEngine.Object @object = array[i]; + if (@object != null && objType.IsAssignableFrom(@object.GetType())) + { + return @object; + } + } + } + } + return null; + } + private static UnityEngine.Object HandleTextureToSprite(Texture2D tex) + { + UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); + for (int i = 0; i < array.Length; i++) + { + if (array[i].GetType() == typeof(Sprite)) + { + return array[i]; + } + } + return tex; + } + public static Rect IndentedRect(Rect source) + { + float indent = EditorGUI.indent; + return new Rect(source.x + indent, source.y, source.width - indent, source.height); + } + public static Vector2 Vector2Field(Rect position, string label, Vector2 value) + { + return EditorGUI.Vector2Field(position, EditorGUIUtility.TempContent(label), value); + } + public static Vector2 Vector2Field(Rect position, GUIContent label, Vector2 value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + return EditorGUI.Vector2Field(position, value); + } + private static Vector2 Vector2Field(Rect position, Vector2 value) + { + EditorGUI.s_Vector2Floats[0] = value.x; + EditorGUI.s_Vector2Floats[1] = value.y; + position.height = 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector2Floats[0]; + value.y = EditorGUI.s_Vector2Floats[1]; + } + return value; + } + public static Vector3 Vector3Field(Rect position, string label, Vector3 value) + { + return EditorGUI.Vector3Field(position, EditorGUIUtility.TempContent(label), value); + } + public static Vector3 Vector3Field(Rect position, GUIContent label, Vector3 value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + position.height = 16f; + return EditorGUI.Vector3Field(position, value); + } + private static Vector3 Vector3Field(Rect position, Vector3 value) + { + EditorGUI.s_Vector3Floats[0] = value.x; + EditorGUI.s_Vector3Floats[1] = value.y; + EditorGUI.s_Vector3Floats[2] = value.z; + position.height = 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYZLabels, EditorGUI.s_Vector3Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector3Floats[0]; + value.y = EditorGUI.s_Vector3Floats[1]; + value.z = EditorGUI.s_Vector3Floats[2]; + } + return value; + } + private static void Vector2Field(Rect position, SerializedProperty property, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); + } + private static void Vector3Field(Rect position, SerializedProperty property, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + } + private static void Vector4Field(Rect position, SerializedProperty property, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 4); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZWLabels, serializedProperty); + } + public static Vector4 Vector4Field(Rect position, string label, Vector4 value) + { + EditorGUI.s_Vector4Floats[0] = value.x; + EditorGUI.s_Vector4Floats[1] = value.y; + EditorGUI.s_Vector4Floats[2] = value.z; + EditorGUI.s_Vector4Floats[3] = value.w; + position.height = 16f; + GUI.Label(EditorGUI.IndentedRect(position), label, EditorStyles.label); + position.y += 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.indentLevel++; + EditorGUI.MultiFloatField(position, EditorGUI.s_XYZWLabels, EditorGUI.s_Vector4Floats); + EditorGUI.indentLevel--; + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector4Floats[0]; + value.y = EditorGUI.s_Vector4Floats[1]; + value.z = EditorGUI.s_Vector4Floats[2]; + value.w = EditorGUI.s_Vector4Floats[3]; + } + return value; + } + public static Rect RectField(Rect position, Rect value) + { + position.height = 16f; + EditorGUI.s_Vector2Floats[0] = value.x; + EditorGUI.s_Vector2Floats[1] = value.y; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector2Floats[0]; + value.y = EditorGUI.s_Vector2Floats[1]; + } + position.y += 16f; + EditorGUI.s_Vector2Floats[0] = value.width; + EditorGUI.s_Vector2Floats[1] = value.height; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_WHLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.width = EditorGUI.s_Vector2Floats[0]; + value.height = EditorGUI.s_Vector2Floats[1]; + } + return value; + } + public static Rect RectField(Rect position, string label, Rect value) + { + return EditorGUI.RectField(position, EditorGUIUtility.TempContent(label), value); + } + public static Rect RectField(Rect position, GUIContent label, Rect value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + return EditorGUI.RectField(position, value); + } + private static void RectField(Rect position, SerializedProperty property, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); + position.y += 16f; + EditorGUI.MultiPropertyField(position, EditorGUI.s_WHLabels, serializedProperty); + } + private static Rect DrawBoundsFieldLabelsAndAdjustPositionForValues(Rect position, bool drawOutside) + { + if (drawOutside) + { + position.xMin -= 50f; + } + GUI.Label(EditorGUI.IndentedRect(position), "Center:", EditorStyles.label); + position.y += 16f; + GUI.Label(EditorGUI.IndentedRect(position), "Extents:", EditorStyles.label); + position.y -= 16f; + position.xMin += 50f; + return position; + } + public static Bounds BoundsField(Rect position, Bounds value) + { + return EditorGUI.BoundsField(position, GUIContent.none, value); + } + public static Bounds BoundsField(Rect position, GUIContent label, Bounds value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) + { + position.y += 16f; + } + position.height = 16f; + position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); + value.center = EditorGUI.Vector3Field(position, value.center); + position.y += 16f; + value.extents = EditorGUI.Vector3Field(position, value.extents); + return value; + } + private static void BoundsField(Rect position, SerializedProperty property, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) + { + position.y += 16f; + } + position.height = 16f; + position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + serializedProperty.NextVisible(true); + position.y += 16f; + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + } + public static void MultiFloatField(Rect position, GUIContent label, GUIContent[] subLabels, float[] values) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); + position.height = 16f; + EditorGUI.MultiFloatField(position, subLabels, values); + } + public static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values) + { + EditorGUI.MultiFloatField(position, subLabels, values, 13f); + } + internal static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values, float labelWidth) + { + int num = values.Length; + float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; + Rect position2 = new Rect(position); + position2.width = num2; + float labelWidth2 = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = 0; + for (int i = 0; i < values.Length; i++) + { + values[i] = EditorGUI.FloatField(position2, subLabels[i], values[i]); + position2.x += num2 + 2f; + } + EditorGUIUtility.labelWidth = labelWidth2; + EditorGUI.indentLevel = indentLevel; + } + public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, GUIContent label) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); + position.height = 16f; + EditorGUI.MultiPropertyField(position, subLabels, valuesIterator); + } + public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator) + { + EditorGUI.MultiPropertyField(position, subLabels, valuesIterator, 13f, null); + } + internal static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, float labelWidth, bool[] disabledMask) + { + int num = subLabels.Length; + float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; + Rect position2 = new Rect(position); + position2.width = num2; + float labelWidth2 = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = 0; + for (int i = 0; i < subLabels.Length; i++) + { + if (disabledMask != null) + { + EditorGUI.BeginDisabledGroup(disabledMask[i]); + } + EditorGUI.PropertyField(position2, valuesIterator, subLabels[i]); + if (disabledMask != null) + { + EditorGUI.EndDisabledGroup(); + } + position2.x += num2 + 2f; + valuesIterator.NextVisible(false); + } + EditorGUIUtility.labelWidth = labelWidth2; + EditorGUI.indentLevel = indentLevel; + } + internal static int CycleButton(Rect position, int selected, GUIContent[] options, GUIStyle style) + { + if (selected >= options.Length || selected < 0) + { + selected = 0; + GUI.changed = true; + } + if (GUI.Button(position, options[selected], style)) + { + selected++; + GUI.changed = true; + if (selected >= options.Length) + { + selected = 0; + } + } + return selected; + } + public static Color ColorField(Rect position, Color value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.IndentedRect(position), controlID, value, true, true); + } + internal static Color ColorField(Rect position, Color value, bool showEyedropper, bool showAlpha) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(position, controlID, value, showEyedropper, showAlpha); + } + public static Color ColorField(Rect position, string label, Color value) + { + return EditorGUI.ColorField(position, EditorGUIUtility.TempContent(label), value); + } + public static Color ColorField(Rect position, GUIContent label, Color value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, true, true); + } + internal static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, showEyedropper, showAlpha); + } + private static Color DoColorField(Rect position, int id, Color value, bool showEyedropper, bool showAlpha) + { + Event current = Event.current; + GUIStyle colorField = EditorStyles.colorField; + Color result = value; + value = ((!EditorGUI.showMixedValue) ? value : Color.white); + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(id)) + { + Event.current.Use(); + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, showAlpha); + GUIUtility.ExitGUI(); + } + return result; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_47: + if (typeForControl == EventType.ValidateCommand) + { + if (current.commandName == "UndoRedoPerformed" && GUIUtility.keyboardControl == id && ColorPicker.visible) + { + ColorPicker.color = value; + } + return result; + } + if (typeForControl == EventType.ExecuteCommand) + { + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + switch (commandName) + { + case "EyeDropperUpdate": + HandleUtility.Repaint(); + break; + case "EyeDropperClicked": + { + GUI.changed = true; + HandleUtility.Repaint(); + Color lastPickedColor = EyeDropper.GetLastPickedColor(); + lastPickedColor.a = value.a; + EditorGUI.s_ColorPickID = 0; + return lastPickedColor; + } + case "EyeDropperCancelled": + HandleUtility.Repaint(); + EditorGUI.s_ColorPickID = 0; + break; + case "ColorPickerChanged": + GUI.changed = true; + HandleUtility.Repaint(); + return ColorPicker.color; + } + } + return result; + } + if (typeForControl != EventType.MouseDown) + { + return result; + } + if (showEyedropper) + { + position.width -= 20f; + } + if (position.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = id; + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, showAlpha); + GUIUtility.ExitGUI(); + } + if (showEyedropper) + { + position.width += 20f; + if (position.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = id; + EyeDropper.Start(GUIView.current); + EditorGUI.s_ColorPickID = id; + GUIUtility.ExitGUI(); + } + } + return result; + case EventType.Repaint: + { + Rect position2; + if (showEyedropper) + { + position2 = colorField.padding.Remove(position); + } + else + { + position2 = position; + } + if (showEyedropper && EditorGUI.s_ColorPickID == id) + { + Color pickedColor = EyeDropper.GetPickedColor(); + pickedColor.a = value.a; + EditorGUIUtility.DrawColorSwatch(position2, pickedColor, showAlpha); + } + else + { + EditorGUIUtility.DrawColorSwatch(position2, value, showAlpha); + } + if (showEyedropper) + { + colorField.Draw(position, GUIContent.none, id); + } + else + { + EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); + } + return result; + } + } + goto IL_47; + } + public static AnimationCurve CurveField(Rect position, AnimationCurve value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, EditorGUI.kCurveColor, default(Rect), null); + } + public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value) + { + return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value); + } + public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, EditorGUI.kCurveColor, default(Rect), null); + } + public static AnimationCurve CurveField(Rect position, AnimationCurve value, Color color, Rect ranges) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, color, ranges, null); + } + public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value, Color color, Rect ranges) + { + return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value, color, ranges); + } + public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value, Color color, Rect ranges) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, color, ranges, null); + } + public static void CurveField(Rect position, SerializedProperty value, Color color, Rect ranges) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoCurveField(position, controlID, null, color, ranges, value); + } + private static void SetCurveEditorWindowCurve(AnimationCurve value, SerializedProperty property, Color color) + { + if (property != null) + { + CurveEditorWindow.curve = ((!property.hasMultipleDifferentValues) ? property.animationCurveValue : new AnimationCurve()); + } + else + { + CurveEditorWindow.curve = value; + } + CurveEditorWindow.color = color; + } + private static AnimationCurve DoCurveField(Rect position, int id, AnimationCurve value, Color color, Rect ranges, SerializedProperty property) + { + Event current = Event.current; + position.width = Mathf.Max(position.width, 2f); + position.height = Mathf.Max(position.height, 2f); + if (GUIUtility.keyboardControl == id && Event.current.type != EventType.Layout) + { + if (EditorGUI.s_CurveID != id) + { + EditorGUI.s_CurveID = id; + if (CurveEditorWindow.visible) + { + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + } + } + else + { + if (CurveEditorWindow.visible && Event.current.type == EventType.Repaint) + { + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + CurveEditorWindow.instance.Repaint(); + } + } + } + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(id)) + { + EditorGUI.s_CurveID = id; + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + current.Use(); + GUIUtility.ExitGUI(); + } + return value; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_D3: + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(current.mousePosition)) + { + EditorGUI.s_CurveID = id; + GUIUtility.keyboardControl = id; + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + current.Use(); + GUIUtility.ExitGUI(); + } + return value; + } + if (typeForControl != EventType.ExecuteCommand) + { + return value; + } + if (EditorGUI.s_CurveID == id) + { + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUI.<>f__switch$map3 == null) + { + EditorGUI.<>f__switch$map3 = new Dictionary(1) + { + + { + "CurveChanged", + 0 + } + }; + } + int num; + if (EditorGUI.<>f__switch$map3.TryGetValue(commandName, out num)) + { + if (num == 0) + { + GUI.changed = true; + AnimationCurvePreviewCache.ClearCache(); + HandleUtility.Repaint(); + if (property != null) + { + property.animationCurveValue = CurveEditorWindow.curve; + if (property.hasMultipleDifferentValues) + { + Debug.LogError("AnimationCurve SerializedProperty hasMultipleDifferentValues is true after writing."); + } + } + return CurveEditorWindow.curve; + } + } + } + } + return value; + case EventType.Repaint: + { + Rect position2 = position; + position2.y += 1f; + position2.height -= 1f; + if (ranges != default(Rect)) + { + EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor, ranges); + } + else + { + EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor); + } + EditorStyles.colorPickerBox.Draw(position2, GUIContent.none, id, false); + return value; + } + } + goto IL_D3; + } + private static void ShowCurvePopup(GUIView viewToUpdate, Rect ranges) + { + CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); + if (ranges.width > 0f && ranges.height > 0f && ranges.width != float.PositiveInfinity && ranges.height != float.PositiveInfinity) + { + curveEditorSettings.hRangeMin = ranges.xMin; + curveEditorSettings.hRangeMax = ranges.xMax; + curveEditorSettings.vRangeMin = ranges.yMin; + curveEditorSettings.vRangeMax = ranges.yMax; + } + CurveEditorWindow.instance.Show(GUIView.current, curveEditorSettings); + } + private static bool ValidTargetForIconSelection(UnityEngine.Object[] targets) + { + return (targets[0] as MonoScript || targets[0] as GameObject) && targets.Length == 1; + } + internal static void ObjectIconDropDown(Rect position, UnityEngine.Object[] targets, bool showLabelIcons, Texture2D nullIcon, SerializedProperty iconProperty) + { + if (EditorGUI.s_IconTextureInactive == null) + { + EditorGUI.s_IconTextureInactive = (Material)EditorGUIUtility.LoadRequired("Inspectors/InactiveGUI.mat"); + } + if (Event.current.type == EventType.Repaint) + { + Texture2D texture2D = null; + if (!iconProperty.hasMultipleDifferentValues) + { + texture2D = AssetPreview.GetMiniThumbnail(targets[0]); + } + if (texture2D == null) + { + texture2D = nullIcon; + } + Vector2 vector = new Vector2(position.width, position.height); + if (texture2D) + { + vector.x = Mathf.Min((float)texture2D.width, vector.x); + vector.y = Mathf.Min((float)texture2D.height, vector.y); + } + Rect rect = new Rect(position.x + position.width / 2f - vector.x / 2f, position.y + position.height / 2f - vector.y / 2f, vector.x, vector.y); + GameObject gameObject = targets[0] as GameObject; + bool flag = gameObject && !EditorUtility.IsPersistent(targets[0]) && (!gameObject.activeSelf || !gameObject.activeInHierarchy); + if (flag) + { + Graphics.DrawTexture(rect, texture2D, new Rect(0f, 0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 1f), EditorGUI.s_IconTextureInactive); + } + else + { + GUI.DrawTexture(rect, texture2D); + } + if (EditorGUI.ValidTargetForIconSelection(targets)) + { + if (EditorGUI.s_IconDropDown == null) + { + EditorGUI.s_IconDropDown = EditorGUIUtility.IconContent("Icon Dropdown"); + } + GUIStyle.none.Draw(new Rect(Mathf.Max(position.x + 2f, rect.x - 6f), rect.yMax - rect.height * 0.2f, 13f, 8f), EditorGUI.s_IconDropDown, false, false, false, false); + } + } + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none) && EditorGUI.ValidTargetForIconSelection(targets) && IconSelector.ShowAtPosition(targets[0], position, showLabelIcons)) + { + GUIUtility.ExitGUI(); + } + } + public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object targetObj) + { + return EditorGUI.InspectorTitlebar(position, foldout, new UnityEngine.Object[] + { + targetObj + }); + } + public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object[] targetObjs) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + if (EditorGUI.s_TitleSettingsIcon == null) + { + EditorGUI.s_TitleSettingsIcon = EditorGUIUtility.IconContent("_Popup"); + } + GUIStyle inspectorTitlebar = EditorStyles.inspectorTitlebar; + GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText; + Rect rect = new Rect(position.x + (float)inspectorTitlebar.padding.left, position.y + (float)inspectorTitlebar.padding.top, 16f, 16f); + Rect rect2 = new Rect(position.xMax - (float)inspectorTitlebar.padding.right - 2f - 16f, rect.y, 16f, 16f); + Rect position2 = new Rect(rect.xMax + 2f + 2f + 16f, rect.y, 100f, rect.height); + position2.xMax = rect2.xMin - 2f; + int num = -1; + for (int i = 0; i < targetObjs.Length; i++) + { + UnityEngine.Object target = targetObjs[i]; + int objectEnabled = EditorUtility.GetObjectEnabled(target); + if (num == -1) + { + num = objectEnabled; + } + else + { + if (num != objectEnabled) + { + num = -2; + } + } + } + if (num != -1) + { + bool flag = AnimationMode.IsPropertyAnimated(targetObjs[0], "m_Enabled"); + bool flag2 = num != 0; + EditorGUI.showMixedValue = (num == -2); + Rect position3 = rect; + position3.x = rect.xMax + 2f; + EditorGUI.BeginChangeCheck(); + Color color = GUI.color; + if (flag) + { + GUI.color = AnimationMode.animatedPropertyColor; + } + int controlID2 = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + flag2 = EditorGUIInternal.DoToggleForward(position3, controlID2, flag2, GUIContent.none, EditorStyles.toggle); + if (flag) + { + GUI.color = color; + } + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(targetObjs, ((!flag2) ? "Disable" : "Enable") + " Component" + ((targetObjs.Length <= 1) ? string.Empty : "s")); + for (int j = 0; j < targetObjs.Length; j++) + { + UnityEngine.Object target2 = targetObjs[j]; + EditorUtility.SetObjectEnabled(target2, flag2); + } + } + EditorGUI.showMixedValue = false; + } + Rect position4 = rect2; + position4.x -= 18f; + if (EditorGUI.HelpIconButton(position4, targetObjs[0])) + { + position2.xMax = position4.xMin - 2f; + } + Event current = Event.current; + Texture2D i2 = null; + if (current.type == EventType.Repaint) + { + i2 = AssetPreview.GetMiniThumbnail(targetObjs[0]); + } + if (EditorGUI.ButtonMouseDown(rect, EditorGUIUtility.TempContent(i2), FocusType.Passive, GUIStyle.none) && targetObjs[0] as MonoScript != null && IconSelector.ShowAtPosition(targetObjs[0], rect, true)) + { + GUIUtility.ExitGUI(); + } + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + inspectorTitlebar.Draw(position, GUIContent.none, controlID, foldout); + position = inspectorTitlebar.padding.Remove(position); + inspectorTitlebarText.Draw(position2, EditorGUIUtility.TempContent(ObjectNames.GetInspectorTitle(targetObjs[0])), controlID, foldout); + inspectorTitlebarText.Draw(rect2, EditorGUI.s_TitleSettingsIcon, controlID, foldout); + } + } + else + { + if (rect2.Contains(current.mousePosition)) + { + EditorUtility.DisplayObjectContextMenu(rect2, targetObjs, 0); + current.Use(); + } + } + return EditorGUI.DoObjectFoldout(controlID, position, targetObjs, foldout); + } + internal static bool HelpIconButton(Rect position, UnityEngine.Object obj) + { + if (EditorGUI.s_HelpIcon == null) + { + EditorGUI.s_HelpIcon = EditorGUIUtility.IconContent("_Help"); + } + bool flag = Unsupported.IsDeveloperBuild(); + bool defaultToMonoBehaviour = !flag || obj.GetType().Assembly.ToString().StartsWith("Assembly-"); + bool flag2 = Help.HasHelpForObject(obj, defaultToMonoBehaviour); + if (flag2 || flag) + { + Color color = GUI.color; + GUIContent gUIContent = new GUIContent(EditorGUI.s_HelpIcon); + string niceHelpNameForObject = Help.GetNiceHelpNameForObject(obj, defaultToMonoBehaviour); + if (flag && !flag2) + { + GUI.color = Color.yellow; + bool flag3 = obj is MonoBehaviour; + string arg = ((!flag3) ? "sealed partial class-" : "script-") + niceHelpNameForObject; + gUIContent.tooltip = string.Format("Could not find Reference page for {0} ({1}).\nDocs for this object is missing or all docs are missing.\nThis warning only shows up in development builds.", niceHelpNameForObject, arg); + } + else + { + gUIContent.tooltip = string.Format("Open Reference for {0}.", niceHelpNameForObject); + } + if (GUI.Button(position, gUIContent, EditorStyles.inspectorTitlebarText)) + { + Help.ShowHelpForObject(obj); + } + GUI.color = color; + return true; + } + return false; + } + internal static bool FoldoutInternal(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, GUIStyle style) + { + Rect rect = position; + if (EditorGUIUtility.hierarchyMode) + { + int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; + position.xMin -= (float)num; + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + EventType eventType = Event.current.type; + if (!GUI.enabled && GUIClip.enabled && (Event.current.rawType == EventType.MouseDown || Event.current.rawType == EventType.MouseDrag || Event.current.rawType == EventType.MouseUp)) + { + eventType = Event.current.rawType; + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition) && Event.current.button == 0) + { + int num2 = controlID; + GUIUtility.hotControl = num2; + GUIUtility.keyboardControl = num2; + Event.current.Use(); + } + return foldout; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + Rect rect2 = position; + if (!toggleOnLabelClick) + { + rect2.width = (float)style.padding.left; + rect2.x += EditorGUI.indent; + } + if (rect2.Contains(Event.current.mousePosition)) + { + GUI.changed = true; + return !foldout; + } + } + return foldout; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Layout: + IL_D8: + if (eventType2 != EventType.DragExited) + { + return foldout; + } + if (EditorGUI.s_DragUpdatedOverID == controlID) + { + EditorGUI.s_DragUpdatedOverID = 0; + Event.current.Use(); + } + return foldout; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Event.current.Use(); + } + return foldout; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == controlID) + { + KeyCode keyCode = Event.current.keyCode; + if ((keyCode == KeyCode.LeftArrow && foldout) || (keyCode == KeyCode.RightArrow && !foldout)) + { + foldout = !foldout; + GUI.changed = true; + Event.current.Use(); + } + } + return foldout; + case EventType.Repaint: + { + EditorStyles.foldoutSelected.Draw(position, GUIContent.none, controlID, EditorGUI.s_DragUpdatedOverID == controlID); + Rect position2 = new Rect(position.x + EditorGUI.indent, position.y, EditorGUIUtility.labelWidth - EditorGUI.indent, position.height); + if (EditorGUI.showMixedValue && !foldout) + { + style.Draw(position2, content, controlID, foldout); + EditorGUI.BeginHandleMixedValueContentColor(); + Rect position3 = rect; + position3.xMin += EditorGUIUtility.labelWidth; + EditorStyles.label.Draw(position3, EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position2, content, controlID, foldout); + } + return foldout; + } + case EventType.DragUpdated: + if (EditorGUI.s_DragUpdatedOverID == controlID) + { + if (position.Contains(Event.current.mousePosition)) + { + if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) + { + foldout = true; + Event.current.Use(); + } + } + else + { + EditorGUI.s_DragUpdatedOverID = 0; + } + } + else + { + if (position.Contains(Event.current.mousePosition)) + { + EditorGUI.s_DragUpdatedOverID = controlID; + EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; + Event.current.Use(); + } + } + return foldout; + } + goto IL_D8; + } + public static void ProgressBar(Rect position, float value, string text) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ProgressBarHash, EditorGUIUtility.native, position); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.Repaint) + { + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + Rect position2 = new Rect(position); + value = Mathf.Clamp01(value); + position2.width *= value; + EditorStyles.progressBarBar.Draw(position2, false, false, false, false); + EditorStyles.progressBarText.Draw(position, text, false, false, false, false); + } + } + public static void HelpBox(Rect position, string message, MessageType type) + { + GUI.Label(position, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type)), EditorStyles.helpBox); + } + internal static bool LabelHasContent(GUIContent label) + { + return label == null || label.text != string.Empty || label.image != null; + } + private static void DrawTextDebugHelpers(Rect labelPosition) + { + Color color = GUI.color; + GUI.color = Color.white; + GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.y, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); + GUI.color = Color.cyan; + GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.yMax - 4f, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); + GUI.color = color; + } + internal static void HandlePrefixLabelInternal(Rect totalPosition, Rect labelPosition, GUIContent label, int id, GUIStyle style) + { + if (id == 0 && label != null) + { + EditorGUI.s_PrefixLabel.text = label.text; + EditorGUI.s_PrefixLabel.image = label.image; + EditorGUI.s_PrefixLabel.tooltip = label.tooltip; + EditorGUI.s_PrefixTotalRect = totalPosition; + EditorGUI.s_PrefixRect = labelPosition; + EditorGUI.s_PrefixStyle = style; + return; + } + if (Highlighter.searchMode == HighlightSearchMode.PrefixLabel || Highlighter.searchMode == HighlightSearchMode.Auto) + { + Highlighter.Handle(totalPosition, label.text); + } + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + labelPosition.width += 1f; + style.DrawPrefixLabel(labelPosition, label, id); + } + } + else + { + if (Event.current.button == 0 && labelPosition.Contains(Event.current.mousePosition)) + { + if (EditorGUIUtility.CanHaveKeyboardFocus(id)) + { + GUIUtility.keyboardControl = id; + } + EditorGUIUtility.editingTextField = false; + HandleUtility.Repaint(); + } + } + EditorGUI.s_PrefixLabel.text = null; + } + public static Rect PrefixLabel(Rect totalPosition, GUIContent label) + { + return EditorGUI.PrefixLabel(totalPosition, 0, label); + } + public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label) + { + if (!EditorGUI.LabelHasContent(label)) + { + return EditorGUI.IndentedRect(totalPosition); + } + Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); + Rect result = new Rect(totalPosition.x + EditorGUIUtility.labelWidth, totalPosition.y, totalPosition.width - EditorGUIUtility.labelWidth, totalPosition.height); + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, EditorStyles.label); + return result; + } + internal static Rect MultiFieldPrefixLabel(Rect totalPosition, int id, GUIContent label, int columns) + { + if (!EditorGUI.LabelHasContent(label)) + { + return EditorGUI.IndentedRect(totalPosition); + } + if (EditorGUIUtility.wideMode) + { + Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); + Rect result = totalPosition; + result.xMin += EditorGUIUtility.labelWidth; + if (columns > 1) + { + labelPosition.width -= 1f; + result.xMin -= 1f; + } + if (columns == 2) + { + float num = (result.width - 4f) / 3f; + result.xMax -= num + 2f; + } + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id); + return result; + } + Rect labelPosition2 = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, totalPosition.width - EditorGUI.indent, 16f); + Rect result2 = totalPosition; + result2.xMin += EditorGUI.indent + 15f; + result2.yMin += 16f; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition2, label, id); + return result2; + } + public static GUIContent BeginProperty(Rect totalPosition, GUIContent label, SerializedProperty property) + { + Highlighter.HighlightIdentifier(totalPosition, property.propertyPath); + if (EditorGUI.s_PendingPropertyKeyboardHandling != null) + { + EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); + } + EditorGUI.s_PendingPropertyKeyboardHandling = property; + if (property == null) + { + string message = ((label != null) ? (label.text + ": ") : string.Empty) + "SerializedProperty is null"; + EditorGUI.HelpBox(totalPosition, "null", MessageType.Error); + throw new NullReferenceException(message); + } + EditorGUI.s_PropertyFieldTempContent.text = ((label != null) ? label.text : property.displayName); + EditorGUI.s_PropertyFieldTempContent.tooltip = ((!EditorGUI.isCollectingTooltips) ? null : ((label != null) ? label.tooltip : property.tooltip)); + string tooltip = ScriptAttributeUtility.GetHandler(property).tooltip; + if (tooltip != null) + { + EditorGUI.s_PropertyFieldTempContent.tooltip = tooltip; + } + EditorGUI.s_PropertyFieldTempContent.image = ((label != null) ? label.image : null); + if (Event.current.alt && property.serializedObject.inspectorMode != InspectorMode.Normal) + { + GUIContent arg_12F_0 = EditorGUI.s_PropertyFieldTempContent; + string propertyPath = property.propertyPath; + EditorGUI.s_PropertyFieldTempContent.text = propertyPath; + arg_12F_0.tooltip = propertyPath; + } + bool boldDefaultFont = EditorGUIUtility.GetBoldDefaultFont(); + if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) + { + EditorGUIUtility.SetBoldDefaultFont(property.prefabOverride); + } + EditorGUI.s_PropertyStack.Push(new PropertyGUIData(property, totalPosition, boldDefaultFont, GUI.enabled, GUI.color)); + EditorGUI.showMixedValue = property.hasMultipleDifferentValues; + if (property.isAnimated) + { + Color animatedPropertyColor = AnimationMode.animatedPropertyColor; + animatedPropertyColor.a *= GUI.color.a; + GUI.color = animatedPropertyColor; + } + GUI.enabled &= property.editable; + return EditorGUI.s_PropertyFieldTempContent; + } + public static void EndProperty() + { + EditorGUI.showMixedValue = false; + PropertyGUIData propertyGUIData = EditorGUI.s_PropertyStack.Pop(); + if (Event.current.type == EventType.ContextClick && propertyGUIData.totalPosition.Contains(Event.current.mousePosition)) + { + EditorGUI.DoPropertyContextMenu(propertyGUIData.property); + } + EditorGUIUtility.SetBoldDefaultFont(propertyGUIData.wasBoldDefaultFont); + GUI.enabled = propertyGUIData.wasEnabled; + GUI.color = propertyGUIData.color; + if (EditorGUI.s_PendingPropertyKeyboardHandling != null) + { + EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); + } + if (EditorGUI.s_PendingPropertyDelete != null && EditorGUI.s_PropertyStack.Count == 0) + { + if (EditorGUI.s_PendingPropertyDelete.propertyPath == propertyGUIData.property.propertyPath) + { + propertyGUIData.property.DeleteCommand(); + } + else + { + EditorGUI.s_PendingPropertyDelete.DeleteCommand(); + } + EditorGUI.s_PendingPropertyDelete = null; + } + } + private static void DoPropertyFieldKeyboardHandling(SerializedProperty property) + { + if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) + { + if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete")) + { + if (Event.current.type == EventType.ExecuteCommand) + { + EditorGUI.s_PendingPropertyDelete = property.Copy(); + } + Event.current.Use(); + } + if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && Event.current.commandName == "Duplicate") + { + if (Event.current.type == EventType.ExecuteCommand) + { + property.DuplicateCommand(); + } + Event.current.Use(); + } + } + EditorGUI.s_PendingPropertyKeyboardHandling = null; + } + internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.LayerMaskField(position, property, label, EditorStyles.layerMaskField); + } + internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_LayerMaskField, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + if (current.type == EventType.Repaint) + { + if (EditorGUI.showMixedValue) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position, EditorGUIUtility.TempContent(property.layerMaskStringValue), controlID, false); + } + } + else + { + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + SerializedProperty userData = property.serializedObject.FindProperty(property.propertyPath); + EditorUtility.DisplayCustomMenu(position, property.GetLayerMaskNames(), (!property.hasMultipleDifferentValues) ? property.GetLayerMaskSelectedIndex() : new int[0], new EditorUtility.SelectMenuItemFunction(EditorGUI.SetLayerMaskValueDelegate), userData); + Event.current.Use(); + } + } + } + internal static void SetLayerMaskValueDelegate(object userData, string[] options, int selected) + { + SerializedProperty serializedProperty = (SerializedProperty)userData; + serializedProperty.ToggleLayerMaskAtIndex(selected); + serializedProperty.serializedObject.ApplyModifiedProperties(); + } + internal static void ShowRepaints() + { + if (Unsupported.IsDeveloperBuild()) + { + Color backgroundColor = GUI.backgroundColor; + GUI.backgroundColor = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); + GUI.Label(new Rect(0f, 0f, 10f, 10f), string.Empty, GUI.skin.button); + GUI.backgroundColor = backgroundColor; + } + } + internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.s_Texture) + { + EditorGUI.s_Texture = new Texture2D(1, thickness + 2); + EditorGUI.s_Texture.hideFlags = HideFlags.HideAndDontSave; + } + if (thickness != EditorGUI.s_LastThickness) + { + EditorGUI.s_Texture.Resize(1, thickness + 2, TextureFormat.ARGB32, false); + Color[] array = new Color[thickness + 2]; + for (int i = 1; i <= thickness; i++) + { + array[i] = new Color(1f, 1f, 1f, 1f); + } + array[0] = (array[thickness + 1] = new Color(1f, 1f, 1f, 0f)); + EditorGUI.s_Texture.SetPixels(array); + EditorGUI.s_Texture.Apply(); + EditorGUI.s_LastThickness = thickness; + } + EditorGUI.DrawBezier(from, to, fromTangent, toTangent, thickness, color, EditorGUI.s_Texture); + } + internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color, Texture tex) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.tmp) + { + EditorGUI.tmp = new Material("Shader \"GuiShader\" {\n\tProperties {\t\t_Color (\",\", Color) = (1,1,1,1)\n\t\t_Tex (\",\", Any) = \"white\" {}\n\t}\tSubShader { Pass {\n\t\tTags { \"ForceSupported\" = \"True\" } \n \t\tZTest Always Cull Off ZWrite Off Lighting Off Color [_Color] \t\tBlend SrcAlpha OneMinusSrcAlpha \t\tSetTexture [_Tex] { combine texture * previous }\t}}\n}"); + EditorGUI.tmp.hideFlags = HideFlags.HideAndDontSave; + EditorGUI.tmp.shader.hideFlags = HideFlags.HideAndDontSave; + } + EditorGUI.tmp.SetTexture("_Tex", tex); + EditorGUI.tmp.SetColor("_Color", color); + EditorGUI.tmp.SetPass(0); + } + internal static void DrawTextureAlphaInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) + { + EditorGUI.DrawPreviewTextureInternal(position, image, EditorGUI.alphaMaterial, scaleMode, imageAspect); + } + internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) + { + if (imageAspect == 0f && image == null) + { + Debug.LogError("Please specify an image or a imageAspect"); + return; + } + if (imageAspect == 0f) + { + imageAspect = (float)image.width / (float)image.height; + } + EditorGUI.DrawTransparencyCheckerTexture(position, scaleMode, imageAspect); + if (image != null) + { + Material mat = (QualitySettings.activeColorSpace != ColorSpace.Linear || TextureUtil.GetLinearSampled(image)) ? EditorGUI.transparentMaterial : EditorGUI.gammaCorrectTransparentMaterial; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + } + internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode scaleMode, float imageAspect) + { + Rect position2 = default(Rect); + Rect rect = default(Rect); + GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref position2, ref rect); + GUI.DrawTextureWithTexCoords(position2, EditorGUI.transparentCheckerTexture, new Rect(position2.width * -0.5f / (float)EditorGUI.transparentCheckerTexture.width, position2.height * -0.5f / (float)EditorGUI.transparentCheckerTexture.height, position2.width / (float)EditorGUI.transparentCheckerTexture.width, position2.height / (float)EditorGUI.transparentCheckerTexture.height), false); + } + internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) + { + if (Event.current.type == EventType.Repaint) + { + if (imageAspect == 0f) + { + imageAspect = (float)image.width / (float)image.height; + } + if (mat == null) + { + mat = EditorGUI.GetMaterialForSpecialTexture(image); + } + if (mat == null) + { + GUI.DrawTexture(position, image, scaleMode, false, imageAspect); + return; + } + Rect screenRect = default(Rect); + Rect sourceRect = default(Rect); + GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref screenRect, ref sourceRect); + Texture2D texture2D = image as Texture2D; + if (texture2D != null && TextureUtil.GetUsageMode(image) == TextureUsageMode.AlwaysPadded) + { + sourceRect.width *= (float)texture2D.width / (float)TextureUtil.GetGLWidth(texture2D); + sourceRect.height *= (float)texture2D.height / (float)TextureUtil.GetGLHeight(texture2D); + } + Graphics.DrawTexture(screenRect, image, sourceRect, 0, 0, 0, 0, GUI.color, mat); + } + } + internal static Material GetMaterialForSpecialTexture(Texture t) + { + if (!t) + { + return null; + } + TextureUsageMode usageMode = TextureUtil.GetUsageMode(t); + if (usageMode == TextureUsageMode.LightmapRGBM) + { + return EditorGUI.lightmapRGBMMaterial; + } + if (usageMode == TextureUsageMode.LightmapDoubleLDR) + { + return EditorGUI.lightmapDoubleLDRMaterial; + } + if (usageMode == TextureUsageMode.NormalmapPlain || usageMode == TextureUsageMode.NormalmapDXT5nm) + { + return EditorGUI.normalmapMaterial; + } + if (TextureUtil.IsAlphaOnlyTextureFormat(TextureUtil.GetTextureFormat(t))) + { + return EditorGUI.alphaMaterial; + } + if (QualitySettings.activeColorSpace == ColorSpace.Linear && !TextureUtil.GetLinearSampled(t)) + { + return EditorGUI.gammaCorrectMaterial; + } + return null; + } + private static void SetExpandedRecurse(SerializedProperty property, bool expanded) + { + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.isExpanded = expanded; + int depth = serializedProperty.depth; + while (serializedProperty.NextVisible(true) && serializedProperty.depth > depth) + { + if (serializedProperty.hasVisibleChildren) + { + serializedProperty.isExpanded = expanded; + } + } + } + internal static float GetSinglePropertyHeight(SerializedProperty property, GUIContent label) + { + if (property == null) + { + return 16f; + } + SerializedPropertyType propertyType = property.propertyType; + if (propertyType == SerializedPropertyType.Vector3 || propertyType == SerializedPropertyType.Vector2) + { + return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 16f; + } + if (propertyType == SerializedPropertyType.Rect) + { + return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 32f; + } + if (propertyType == SerializedPropertyType.Bounds) + { + return (EditorGUI.LabelHasContent(label) ? 16f : 0f) + 32f; + } + return 16f; + } + internal static float GetPropertyHeightInternal(SerializedProperty property, GUIContent label, bool includeChildren) + { + return ScriptAttributeUtility.GetHandler(property).GetHeight(property, label, includeChildren); + } + internal static bool HasVisibleChildFields(SerializedProperty property) + { + switch (property.propertyType) + { + case SerializedPropertyType.Vector2: + case SerializedPropertyType.Vector3: + case SerializedPropertyType.Rect: + case SerializedPropertyType.Bounds: + return false; + } + return property.hasVisibleChildren; + } + internal static bool PropertyFieldInternal(Rect position, SerializedProperty property, GUIContent label, bool includeChildren) + { + return ScriptAttributeUtility.GetHandler(property).OnGUI(position, property, label, includeChildren); + } + internal static bool DefaultPropertyField(Rect position, SerializedProperty property, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + SerializedPropertyType propertyType = property.propertyType; + bool flag = false; + if (!EditorGUI.HasVisibleChildFields(property)) + { + switch (propertyType) + { + case SerializedPropertyType.Integer: + { + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.IntField(position, label, property.intValue); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + break; + } + case SerializedPropertyType.Boolean: + { + EditorGUI.BeginChangeCheck(); + bool boolValue = EditorGUI.Toggle(position, label, property.boolValue); + if (EditorGUI.EndChangeCheck()) + { + property.boolValue = boolValue; + } + break; + } + case SerializedPropertyType.Float: + { + EditorGUI.BeginChangeCheck(); + float floatValue = EditorGUI.FloatField(position, label, property.floatValue); + if (EditorGUI.EndChangeCheck()) + { + property.floatValue = floatValue; + } + break; + } + case SerializedPropertyType.String: + { + EditorGUI.BeginChangeCheck(); + string stringValue = EditorGUI.TextField(position, label, property.stringValue); + if (EditorGUI.EndChangeCheck()) + { + property.stringValue = stringValue; + } + break; + } + case SerializedPropertyType.Color: + { + EditorGUI.BeginChangeCheck(); + Color colorValue = EditorGUI.ColorField(position, label, property.colorValue); + if (EditorGUI.EndChangeCheck()) + { + property.colorValue = colorValue; + } + break; + } + case SerializedPropertyType.ObjectReference: + EditorGUI.ObjectFieldInternal(position, property, null, label, EditorStyles.objectField); + break; + case SerializedPropertyType.LayerMask: + EditorGUI.LayerMaskField(position, property, label); + break; + case SerializedPropertyType.Enum: + EditorGUI.Popup(position, property, label); + break; + case SerializedPropertyType.Vector2: + EditorGUI.Vector2Field(position, property, label); + break; + case SerializedPropertyType.Vector3: + EditorGUI.Vector3Field(position, property, label); + break; + case SerializedPropertyType.Vector4: + EditorGUI.Vector4Field(position, property, label); + break; + case SerializedPropertyType.Rect: + EditorGUI.RectField(position, property, label); + break; + case SerializedPropertyType.ArraySize: + { + EditorGUI.BeginChangeCheck(); + int intValue2 = EditorGUI.ArraySizeField(position, label, property.intValue, EditorStyles.numberField); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue2; + } + break; + } + case SerializedPropertyType.Character: + { + char[] value = new char[] + { + (char)property.intValue + }; + bool changed = GUI.changed; + GUI.changed = false; + string text = EditorGUI.TextField(position, label, new string(value)); + if (GUI.changed) + { + if (text.Length == 1) + { + property.intValue = (int)text[0]; + } + else + { + GUI.changed = false; + } + } + GUI.changed |= changed; + break; + } + case SerializedPropertyType.AnimationCurve: + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, EditorGUI.kCurveColor, default(Rect), property); + break; + } + case SerializedPropertyType.Bounds: + EditorGUI.BoundsField(position, property, label); + break; + case SerializedPropertyType.Gradient: + { + int controlID2 = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID2, label), controlID2, null, property); + break; + } + default: + { + int controlID3 = GUIUtility.GetControlID(EditorGUI.s_GenericField, FocusType.Keyboard, position); + EditorGUI.PrefixLabel(position, controlID3, label); + break; + } + } + } + else + { + Event @event = new Event(Event.current); + flag = property.isExpanded; + EditorGUI.BeginDisabledGroup(!property.editable); + GUIStyle style = (DragAndDrop.activeControlID != -10) ? EditorStyles.foldout : EditorStyles.foldoutPreDrop; + bool flag2 = EditorGUI.Foldout(position, flag, EditorGUI.s_PropertyFieldTempContent, true, style); + EditorGUI.EndDisabledGroup(); + if (flag2 != flag) + { + if (Event.current.alt) + { + EditorGUI.SetExpandedRecurse(property, flag2); + } + else + { + property.isExpanded = flag2; + } + } + flag = flag2; + int s_LastControlID = EditorGUIUtility.s_LastControlID; + EventType type = @event.type; + if (type != EventType.DragUpdated && type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + } + } + else + { + if (position.Contains(@event.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object[] array = new UnityEngine.Object[1]; + bool flag3 = false; + UnityEngine.Object[] array2 = objectReferences; + for (int i = 0; i < array2.Length; i++) + { + UnityEngine.Object @object = array2[i]; + array[0] = @object; + UnityEngine.Object object2 = EditorGUI.ValidateObjectFieldAssignment(array, null, property); + if (object2 != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (@event.type == EventType.DragPerform) + { + property.AppendFoldoutPPtrValue(object2); + flag3 = true; + DragAndDrop.activeControlID = 0; + } + else + { + DragAndDrop.activeControlID = s_LastControlID; + } + } + } + if (flag3) + { + GUI.changed = true; + DragAndDrop.AcceptDrag(); + } + } + } + } + EditorGUI.EndProperty(); + return flag; + } + internal static void DrawLegend(Rect position, Color color, string label, bool enabled) + { + position = new Rect(position.x + 2f, position.y + 2f, position.width - 2f, position.height - 2f); + Color backgroundColor = GUI.backgroundColor; + if (enabled) + { + GUI.backgroundColor = color; + } + else + { + GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0.45f); + } + GUI.Label(position, label, "ProfilerPaneSubLabel"); + GUI.backgroundColor = backgroundColor; + } + internal static void SortingLayerField(Rect position, GUIContent label, SerializedProperty layerID, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SortingLayerFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + int[] sortingLayerUniqueIDs = InternalEditorUtility.sortingLayerUniqueIDs; + if (selectedValueForControl >= sortingLayerUniqueIDs.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "SortingLayers"; + Selection.activeObject = EditorApplication.tagManager; + } + else + { + layerID.intValue = sortingLayerUniqueIDs[selectedValueForControl]; + } + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + int[] sortingLayerUniqueIDs2 = InternalEditorUtility.sortingLayerUniqueIDs; + string[] sortingLayerNames = InternalEditorUtility.sortingLayerNames; + int i; + for (i = 0; i < sortingLayerUniqueIDs2.Length; i++) + { + if (sortingLayerUniqueIDs2[i] == layerID.intValue) + { + break; + } + } + ArrayUtility.Add(ref sortingLayerNames, string.Empty); + ArrayUtility.Add(ref sortingLayerNames, "Add Sorting Layer..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(sortingLayerNames), style); + } + else + { + if (Event.current.type == EventType.Repaint) + { + GUIContent content; + if (layerID.hasMultipleDifferentValues) + { + content = EditorGUI.mixedValueContent; + } + else + { + content = EditorGUIUtility.TempContent(InternalEditorUtility.GetSortingLayerNameFromUniqueID(layerID.intValue)); + } + EditorGUI.showMixedValue = layerID.hasMultipleDifferentValues; + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, content, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + EditorGUI.showMixedValue = false; + } + } + } + internal static Gradient GradientField(Rect position, Gradient gradient) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(position, controlID, gradient, null); + } + internal static Gradient GradientField(string label, Rect position, Gradient gradient) + { + return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, gradient); + } + internal static Gradient GradientField(GUIContent label, Rect position, Gradient gradient) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, gradient, null); + } + internal static Gradient GradientField(Rect position, SerializedProperty gradient) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(position, controlID, null, gradient); + } + internal static Gradient GradientField(string label, Rect position, SerializedProperty property) + { + return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, property); + } + internal static Gradient GradientField(GUIContent label, Rect position, SerializedProperty property) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, property); + } + internal static Gradient DoGradientField(Rect position, int id, Gradient value, SerializedProperty property) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id && (current.keyCode == KeyCode.Space || current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter)) + { + Event.current.Use(); + Gradient newGradient = (property == null) ? value : property.gradientValue; + GradientPicker.Show(newGradient); + GUIUtility.ExitGUI(); + } + return value; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_28: + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(current.mousePosition)) + { + if (current.button == 0) + { + EditorGUI.s_GradientID = id; + GUIUtility.keyboardControl = id; + Gradient newGradient2 = (property == null) ? value : property.gradientValue; + GradientPicker.Show(newGradient2); + GUIUtility.ExitGUI(); + } + else + { + if (current.button == 1 && property != null) + { + GradientContextMenu.Show(property); + } + } + } + return value; + } + if (typeForControl != EventType.ExecuteCommand) + { + return value; + } + if (EditorGUI.s_GradientID == id) + { + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUI.<>f__switch$map4 == null) + { + EditorGUI.<>f__switch$map4 = new Dictionary(1) + { + + { + "GradientPickerChanged", + 0 + } + }; + } + int num; + if (EditorGUI.<>f__switch$map4.TryGetValue(commandName, out num)) + { + if (num == 0) + { + GUI.changed = true; + GradientPreviewCache.ClearCache(); + HandleUtility.Repaint(); + if (property != null) + { + property.gradientValue = GradientPicker.gradient; + } + return GradientPicker.gradient; + } + } + } + } + return value; + case EventType.Repaint: + { + Rect position2 = new Rect(position.x + 1f, position.y + 1f, position.width - 2f, position.height - 2f); + if (property != null) + { + GradientEditor.DrawGradientSwatch(position2, property, Color.white); + } + else + { + GradientEditor.DrawGradientSwatch(position2, value, Color.white); + } + EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); + return value; + } + } + goto IL_28; + } + internal static bool ButtonMouseDown(Rect position, GUIContent content, FocusType fType, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ButtonMouseDownHash, fType, position); + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == controlID && current.character == ' ') + { + Event.current.Use(); + return true; + } + return false; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_32: + if (type != EventType.MouseDown) + { + return false; + } + if (position.Contains(current.mousePosition) && current.button == 0) + { + Event.current.Use(); + return true; + } + return false; + case EventType.Repaint: + if (EditorGUI.showMixedValue) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position, content, controlID, false); + } + return false; + } + goto IL_32; + } + internal static bool IconButton(int id, Rect position, GUIContent content, GUIStyle style) + { + GUIUtility.CheckOnGUI(); + switch (Event.current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = id; + Event.current.Use(); + return true; + } + return false; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + return position.Contains(Event.current.mousePosition); + } + return false; + case EventType.MouseDrag: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = id; + Event.current.Use(); + return true; + } + break; + case EventType.Repaint: + style.Draw(position, content, id); + break; + } + return false; + } + internal static Vector2 MouseDeltaReader(Rect position, bool activated) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MouseDeltaReaderHash, FocusType.Passive, position); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (activated && GUIUtility.hotControl == 0 && position.Contains(current.mousePosition) && current.button == 0) + { + GUIUtility.hotControl = controlID; + GUIUtility.keyboardControl = 0; + EditorGUI.s_MouseDeltaReaderLastPos = GUIClip.Unclip(current.mousePosition); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 a = GUIClip.Unclip(current.mousePosition); + Vector2 result = a - EditorGUI.s_MouseDeltaReaderLastPos; + EditorGUI.s_MouseDeltaReaderLastPos = a; + current.Use(); + return result; + } + break; + } + return Vector2.zero; + } + internal static void GameViewSizePopup(Rect buttonRect, GameViewSizeGroupType groupType, int selectedIndex, Action itemClickedCallback, GUIStyle guiStyle) + { + GameViewSizeGroup group = ScriptableSingleton.instance.GetGroup(groupType); + string t; + if (selectedIndex >= 0 && selectedIndex < group.GetTotalCount()) + { + t = group.GetGameViewSize(selectedIndex).displayText; + } + else + { + t = string.Empty; + } + if (EditorGUI.ButtonMouseDown(buttonRect, GUIContent.Temp(t), FocusType.Passive, guiStyle)) + { + IFlexibleMenuItemProvider itemProvider = new GameViewSizesMenuItemProvider(groupType); + FlexibleMenu windowContent = new FlexibleMenu(itemProvider, selectedIndex, new GameViewSizesMenuModifyItemUI(), itemClickedCallback); + PopupWindow.Show(buttonRect, windowContent); + } + } + public static void DrawRect(Rect rect, Color color) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color2 = GUI.color; + GUI.color *= color; + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = color2; + } + internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects) + { + return EditorGUI.DoObjectField(position, dropRect, id, obj, objType, property, validator, allowSceneObjects, EditorStyles.objectField); + } + internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) + { + if (validator == null) + { + validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); + } + Event current = Event.current; + EventType eventType = current.type; + if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + { + eventType = Event.current.rawType; + } + bool flag = EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f; + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + if (!flag) + { + EditorGUIUtility.SetIconSize(new Vector2(12f, 12f)); + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) + { + if (current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete) + { + if (property != null) + { + property.objectReferenceValue = null; + } + else + { + obj = null; + } + GUI.changed = true; + current.Use(); + } + if (current.MainActionKeyForControl(id)) + { + ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); + ObjectSelector.get.objectSelectorID = id; + current.Use(); + GUIUtility.ExitGUI(); + } + } + goto IL_63A; + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Layout: + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + IL_CA: + if (eventType2 != EventType.MouseDown) + { + goto IL_63A; + } + if (Event.current.button != 0) + { + goto IL_63A; + } + if (position.Contains(Event.current.mousePosition)) + { + Rect rect; + if (flag) + { + rect = new Rect(position.xMax - 32f, position.yMax - 14f, 32f, 14f); + } + else + { + rect = new Rect(position.xMax - 15f, position.y, 15f, position.height); + } + EditorGUIUtility.editingTextField = false; + if (rect.Contains(Event.current.mousePosition)) + { + if (GUI.enabled) + { + GUIUtility.keyboardControl = id; + ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); + ObjectSelector.get.objectSelectorID = id; + current.Use(); + GUIUtility.ExitGUI(); + } + } + else + { + UnityEngine.Object @object = (property == null) ? obj : property.objectReferenceValue; + Component component = @object as Component; + if (component) + { + @object = component.gameObject; + } + if (EditorGUI.showMixedValue) + { + @object = null; + } + if (Event.current.clickCount == 1) + { + GUIUtility.keyboardControl = id; + if (@object) + { + EditorGUIUtility.PingObject(@object); + } + current.Use(); + } + else + { + if (Event.current.clickCount == 2) + { + if (@object) + { + AssetDatabase.OpenAsset(@object); + GUIUtility.ExitGUI(); + } + current.Use(); + } + } + } + } + goto IL_63A; + case EventType.Repaint: + { + GUIContent gUIContent; + if (EditorGUI.showMixedValue) + { + gUIContent = EditorGUI.s_MixedValueContent; + } + else + { + if (property != null) + { + gUIContent = EditorGUIUtility.TempContent(property.objectReferenceStringValue, AssetPreview.GetMiniThumbnail(property.objectReferenceValue)); + obj = property.objectReferenceValue; + if (obj != null) + { + UnityEngine.Object[] references = new UnityEngine.Object[] + { + obj + }; + if (validator(references, objType, property) == null) + { + gUIContent = EditorGUIUtility.TempContent("Type mismatch"); + } + } + } + else + { + gUIContent = EditorGUIUtility.ObjectContent(obj, objType); + } + } + if (flag) + { + GUIStyle objectFieldThumb = EditorStyles.objectFieldThumb; + objectFieldThumb.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); + if (obj != null && !EditorGUI.showMixedValue) + { + bool flag2 = obj is Cubemap; + Rect position2 = objectFieldThumb.padding.Remove(position); + if (flag2) + { + position2.x += (position2.width - (float)gUIContent.image.width) / 2f; + position2.y += (position2.height - (float)gUIContent.image.width) / 2f; + GUIStyle.none.Draw(position2, gUIContent.image, false, false, false, false); + } + else + { + Texture2D texture2D = gUIContent.image as Texture2D; + if (texture2D != null && texture2D.alphaIsTransparency) + { + EditorGUI.DrawTextureTransparent(position2, texture2D); + } + else + { + EditorGUI.DrawPreviewTexture(position2, gUIContent.image); + } + } + } + else + { + GUIStyle gUIStyle = objectFieldThumb.name + "Overlay"; + EditorGUI.BeginHandleMixedValueContentColor(); + gUIStyle.Draw(position, gUIContent, id); + EditorGUI.EndHandleMixedValueContentColor(); + } + GUIStyle gUIStyle2 = objectFieldThumb.name + "Overlay2"; + gUIStyle2.Draw(position, EditorGUIUtility.TempContent("Select"), id); + } + else + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, gUIContent, id, DragAndDrop.activeControlID == id); + EditorGUI.EndHandleMixedValueContentColor(); + } + goto IL_63A; + } + case EventType.DragUpdated: + case EventType.DragPerform: + if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object object2 = validator(objectReferences, objType, property); + if (object2 != null && !allowSceneObjects && !EditorUtility.IsPersistent(object2)) + { + object2 = null; + } + if (object2 != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (eventType == EventType.DragPerform) + { + if (property != null) + { + property.objectReferenceValue = object2; + } + else + { + obj = object2; + } + GUI.changed = true; + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = 0; + } + else + { + DragAndDrop.activeControlID = id; + } + Event.current.Use(); + } + } + goto IL_63A; + case EventType.ExecuteCommand: + { + string commandName = current.commandName; + if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == id && GUIUtility.keyboardControl == id) + { + UnityEngine.Object[] references2 = new UnityEngine.Object[] + { + ObjectSelector.GetCurrentObject() + }; + UnityEngine.Object object3 = validator(references2, objType, property); + if (property != null) + { + property.objectReferenceValue = object3; + } + GUI.changed = true; + current.Use(); + return object3; + } + goto IL_63A; + } + case EventType.DragExited: + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + goto IL_63A; + } + goto IL_CA; + IL_63A: + EditorGUIUtility.SetIconSize(iconSize); + return obj; + } + internal static UnityEngine.Object DoDropField(Rect position, int id, Type objType, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) + { + if (validator == null) + { + validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); + } + Event current = Event.current; + EventType eventType = current.type; + if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + { + eventType = Event.current.rawType; + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.Repaint: + style.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); + goto IL_144; + case EventType.Layout: + IL_6B: + if (eventType2 != EventType.DragExited) + { + goto IL_144; + } + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + goto IL_144; + case EventType.DragUpdated: + case EventType.DragPerform: + if (position.Contains(Event.current.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object @object = validator(objectReferences, objType, null); + if (@object != null && !allowSceneObjects && !EditorUtility.IsPersistent(@object)) + { + @object = null; + } + if (@object != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (eventType == EventType.DragPerform) + { + GUI.changed = true; + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = 0; + Event.current.Use(); + return @object; + } + DragAndDrop.activeControlID = id; + Event.current.Use(); + } + } + goto IL_144; + } + goto IL_6B; + IL_144: + return null; + } + internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.TargetChoiceField(position, property, label, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); + } + internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label, TargetChoiceHandler.TargetChoiceMenuFunction func) + { + EditorGUI.BeginProperty(position, label, property); + position = EditorGUI.PrefixLabel(position, 0, label); + EditorGUI.BeginHandleMixedValueContentColor(); + if (GUI.Button(position, EditorGUI.mixedValueContent, EditorStyles.popup)) + { + GenericMenu genericMenu = new GenericMenu(); + TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, property, func); + genericMenu.DropDown(position); + } + EditorGUI.EndHandleMixedValueContentColor(); + EditorGUI.EndProperty(); + } + internal static void VUMeterHorizontal(Rect position, float value, ref EditorGUI.VUMeterData data) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.s_HorizontalVUTexture) + { + EditorGUI.s_HorizontalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureHorizontal"); + } + Color color = GUI.color; + Color contentColor = GUI.contentColor; + Color backgroundColor = GUI.backgroundColor; + if (value < data.lastValue) + { + value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7f); + } + else + { + value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2f); + data.peakValue = value; + data.peakValueTime = Time.realtimeSinceStartup; + } + if (value > 1.11111116f) + { + value = 1.11111116f; + } + if (data.peakValue > 1.11111116f) + { + data.peakValue = 1.11111116f; + } + GUI.contentColor = new Color(0f, 0f, 0f, 0f); + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + float num = position.width * (value * 0.9f) - 2f; + if (num < 2f) + { + num = 2f; + } + Rect position2 = new Rect(position.x + 1f, position.y + 1f, num, position.height - 2f); + Rect texCoords = new Rect(0f, 0f, value * 0.9f, 1f); + GUI.DrawTextureWithTexCoords(position2, EditorGUI.s_HorizontalVUTexture, texCoords); + GUI.color = Color.white; + num = position.width * (data.peakValue * 0.9f) - 2f; + if (num < 2f) + { + num = 2f; + } + position2 = new Rect(position.x + num, position.y + 1f, 1f, position.height - 2f); + if (Time.realtimeSinceStartup - data.peakValueTime < 1f) + { + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + } + GUI.backgroundColor = backgroundColor; + GUI.color = color; + GUI.contentColor = contentColor; + data.lastValue = value; + } + internal static void VUMeterVertical(Rect position, float value, ref EditorGUI.VUMeterData data) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.s_VerticalVUTexture) + { + EditorGUI.s_VerticalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureVertical"); + } + Color color = GUI.color; + Color contentColor = GUI.contentColor; + Color backgroundColor = GUI.backgroundColor; + if (value < data.lastValue) + { + value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7f); + } + else + { + value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2f); + data.peakValue = value; + data.peakValueTime = Time.realtimeSinceStartup; + } + if (value > 1.11111116f) + { + value = 1.11111116f; + } + if (data.peakValue > 1.11111116f) + { + data.peakValue = 1.11111116f; + } + GUI.contentColor = new Color(0f, 0f, 0f, 0f); + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + float num = position.height * (value * 0.9f) - 2f; + if (num < 2f) + { + num = 2f; + } + Rect position2 = new Rect(position.x + 1f, position.y + position.height - num, position.width - 2f, num); + Rect texCoords = new Rect(0f, 0f, 1f, value * 0.9f); + GUI.DrawTextureWithTexCoords(position2, EditorGUI.s_VerticalVUTexture, texCoords); + GUI.color = Color.white; + num = position.height * (data.peakValue * 0.9f) - 2f; + if (num < 2f) + { + num = 2f; + } + position2 = new Rect(position.x + 1f, position.y + position.height - num, position.width - 2f, 1f); + if (Time.realtimeSinceStartup - data.peakValueTime < 1f) + { + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + } + GUI.backgroundColor = backgroundColor; + GUI.color = color; + GUI.contentColor = contentColor; + data.lastValue = value; + } + [ExcludeFromDocs] + public static void LabelField(Rect position, string label) + { + GUIStyle label2 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2); + } + public static void LabelField(Rect position, string label, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.LabelField(position, GUIContent.none, EditorGUIUtility.TempContent(label), style); + } + [ExcludeFromDocs] + public static void LabelField(Rect position, GUIContent label) + { + GUIStyle label2 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2); + } + public static void LabelField(Rect position, GUIContent label, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.LabelField(position, GUIContent.none, label, style); + } + [ExcludeFromDocs] + public static void LabelField(Rect position, string label, string label2) + { + GUIStyle label3 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2, label3); + } + public static void LabelField(Rect position, string label, string label2, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent(label2), style); + } + [ExcludeFromDocs] + public static void LabelField(Rect position, GUIContent label, GUIContent label2) + { + GUIStyle label3 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2, label3); + } + public static void LabelField(Rect position, GUIContent label, GUIContent label2, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.LabelFieldInternal(position, label, label2, style); + } + [ExcludeFromDocs] + public static bool ToggleLeft(Rect position, string label, bool value) + { + GUIStyle label2 = EditorStyles.label; + return EditorGUI.ToggleLeft(position, label, value, label2); + } + public static bool ToggleLeft(Rect position, string label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) + { + return EditorGUI.ToggleLeft(position, EditorGUIUtility.TempContent(label), value, labelStyle); + } + [ExcludeFromDocs] + public static bool ToggleLeft(Rect position, GUIContent label, bool value) + { + GUIStyle label2 = EditorStyles.label; + return EditorGUI.ToggleLeft(position, label, value, label2); + } + public static bool ToggleLeft(Rect position, GUIContent label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) + { + return EditorGUI.ToggleLeftInternal(position, label, value, labelStyle); + } + [ExcludeFromDocs] + public static string TextField(Rect position, string text) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, text, textField); + } + public static string TextField(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.TextFieldInternal(position, text, style); + } + [ExcludeFromDocs] + public static string TextField(Rect position, string label, string text) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, label, text, textField); + } + public static string TextField(Rect position, string label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.TextField(position, EditorGUIUtility.TempContent(label), text, style); + } + [ExcludeFromDocs] + public static string TextField(Rect position, GUIContent label, string text) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, label, text, textField); + } + public static string TextField(Rect position, GUIContent label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.TextFieldInternal(position, label, text, style); + } + [ExcludeFromDocs] + public static string TextArea(Rect position, string text) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextArea(position, text, textField); + } + public static string TextArea(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.TextAreaInternal(position, text, style); + } + [ExcludeFromDocs] + public static void SelectableLabel(Rect position, string text) + { + GUIStyle label = EditorStyles.label; + EditorGUI.SelectableLabel(position, text, label); + } + public static void SelectableLabel(Rect position, string text, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.SelectableLabelInternal(position, text, style); + } + [ExcludeFromDocs] + public static string PasswordField(Rect position, string password) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, password, textField); + } + public static string PasswordField(Rect position, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.PasswordFieldInternal(position, password, style); + } + [ExcludeFromDocs] + public static string PasswordField(Rect position, string label, string password) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, label, password, textField); + } + public static string PasswordField(Rect position, string label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.PasswordField(position, EditorGUIUtility.TempContent(label), password, style); + } + [ExcludeFromDocs] + public static string PasswordField(Rect position, GUIContent label, string password) + { + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, label, password, textField); + } + public static string PasswordField(Rect position, GUIContent label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + { + return EditorGUI.PasswordFieldInternal(position, label, password, style); + } + [ExcludeFromDocs] + public static float FloatField(Rect position, float value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, value, numberField); + } + public static float FloatField(Rect position, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.FloatFieldInternal(position, value, style); + } + [ExcludeFromDocs] + public static float FloatField(Rect position, string label, float value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, label, value, numberField); + } + public static float FloatField(Rect position, string label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.FloatField(position, EditorGUIUtility.TempContent(label), value, style); + } + [ExcludeFromDocs] + public static float FloatField(Rect position, GUIContent label, float value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, label, value, numberField); + } + public static float FloatField(Rect position, GUIContent label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.FloatFieldInternal(position, label, value, style); + } + [ExcludeFromDocs] + public static int IntField(Rect position, int value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, value, numberField); + } + public static int IntField(Rect position, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.IntFieldInternal(position, value, style); + } + [ExcludeFromDocs] + public static int IntField(Rect position, string label, int value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, label, value, numberField); + } + public static int IntField(Rect position, string label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.IntField(position, EditorGUIUtility.TempContent(label), value, style); + } + [ExcludeFromDocs] + public static int IntField(Rect position, GUIContent label, int value) + { + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, label, value, numberField); + } + public static int IntField(Rect position, GUIContent label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.IntFieldInternal(position, label, value, style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, int selectedIndex, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, displayedOptions, style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.PopupInternal(position, label, selectedIndex, displayedOptions, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, selected, popup); + } + public static Enum EnumPopup(Rect position, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumPopup(position, GUIContent.none, selected, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, string label, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, label, selected, popup); + } + public static Enum EnumPopup(Rect position, string label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumPopup(position, EditorGUIUtility.TempContent(label), selected, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, GUIContent label, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, label, selected, popup); + } + public static Enum EnumPopup(Rect position, GUIContent label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumPopupInternal(position, label, selected, style); + } + [ExcludeFromDocs] + public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); + } + public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); + } + [ExcludeFromDocs] + public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); + } + public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, displayedOptions, optionValues, style); + } + [ExcludeFromDocs] + public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); + } + public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.IntPopupInternal(position, label, selectedValue, displayedOptions, optionValues, style); + } + [ExcludeFromDocs] + public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues) + { + GUIContent label = null; + EditorGUI.IntPopup(position, property, displayedOptions, optionValues, label); + } + public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("null")] GUIContent label) + { + EditorGUI.IntPopupInternal(position, property, displayedOptions, optionValues, label); + } + [ExcludeFromDocs] + public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); + } + public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.IntPopupInternal(position, EditorGUIUtility.TempContent(label), selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); + } + [ExcludeFromDocs] + public static string TagField(Rect position, string tag) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, tag, popup); + } + public static string TagField(Rect position, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(string.Empty), tag, style); + } + [ExcludeFromDocs] + public static string TagField(Rect position, string label, string tag) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, label, tag, popup); + } + public static string TagField(Rect position, string label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(label), tag, style); + } + [ExcludeFromDocs] + public static string TagField(Rect position, GUIContent label, string tag) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, label, tag, popup); + } + public static string TagField(Rect position, GUIContent label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.TagFieldInternal(position, label, tag, style); + } + [ExcludeFromDocs] + public static int LayerField(Rect position, int layer) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, layer, popup); + } + public static int LayerField(Rect position, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.LayerFieldInternal(position, GUIContent.none, layer, style); + } + [ExcludeFromDocs] + public static int LayerField(Rect position, string label, int layer) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, label, layer, popup); + } + public static int LayerField(Rect position, string label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.LayerFieldInternal(position, EditorGUIUtility.TempContent(label), layer, style); + } + [ExcludeFromDocs] + public static int LayerField(Rect position, GUIContent label, int layer) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, label, layer, popup); + } + public static int LayerField(Rect position, GUIContent label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.LayerFieldInternal(position, label, layer, style); + } + [ExcludeFromDocs] + public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); + } + public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.MaskFieldInternal(position, label, mask, displayedOptions, style); + } + [ExcludeFromDocs] + public static int MaskField(Rect position, string label, int mask, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); + } + public static int MaskField(Rect position, string label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.MaskFieldInternal(position, GUIContent.Temp(label), mask, displayedOptions, style); + } + [ExcludeFromDocs] + public static int MaskField(Rect position, int mask, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, mask, displayedOptions, popup); + } + public static int MaskField(Rect position, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.MaskFieldInternal(position, mask, displayedOptions, style); + } + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, label, enumValue, popup); + } + public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumMaskFieldInternal(position, label, enumValue, style); + } + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, string label, Enum enumValue) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, label, enumValue, popup); + } + public static Enum EnumMaskField(Rect position, string label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumMaskFieldInternal(position, EditorGUIUtility.TempContent(label), enumValue, style); + } + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, Enum enumValue) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, enumValue, popup); + } + public static Enum EnumMaskField(Rect position, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumMaskFieldInternal(position, enumValue, style); + } + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, string content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, foldout2); + } + public static bool Foldout(Rect position, bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), false, style); + } + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); + } + public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), toggleOnLabelClick, style); + } + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, GUIContent content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, foldout2); + } + public static bool Foldout(Rect position, bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUI.FoldoutInternal(position, foldout, content, false, style); + } + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); + } + public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUI.FoldoutInternal(position, foldout, content, toggleOnLabelClick, style); + } + [ExcludeFromDocs] + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, int id) + { + GUIStyle label2 = EditorStyles.label; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); + } + [ExcludeFromDocs] + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label) + { + GUIStyle label2 = EditorStyles.label; + int id = 0; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); + } + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, [DefaultValue("0")] int id, [DefaultValue("EditorStyles.label")] GUIStyle style) + { + EditorGUI.HandlePrefixLabelInternal(totalPosition, labelPosition, label, id, style); + } + [ExcludeFromDocs] + public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scaleMode) + { + float imageAspect = 0f; + EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawTextureAlpha(Rect position, Texture image) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); + } + public static void DrawTextureAlpha(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + { + EditorGUI.DrawTextureAlphaInternal(position, image, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode) + { + float imageAspect = 0f; + EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawTextureTransparent(Rect position, Texture image) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); + } + public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + { + EditorGUI.DrawTextureTransparentInternal(position, image, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode) + { + float imageAspect = 0f; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + Material mat = null; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + public static void DrawPreviewTexture(Rect position, Texture image, [DefaultValue("null")] Material mat, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + { + EditorGUI.DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + bool includeChildren = true; + return EditorGUI.GetPropertyHeight(property, label, includeChildren); + } + [ExcludeFromDocs] + public static float GetPropertyHeight(SerializedProperty property) + { + bool includeChildren = true; + GUIContent label = null; + return EditorGUI.GetPropertyHeight(property, label, includeChildren); + } + public static float GetPropertyHeight(SerializedProperty property, [DefaultValue("null")] GUIContent label, [DefaultValue("true")] bool includeChildren) + { + return EditorGUI.GetPropertyHeightInternal(property, label, includeChildren); + } + [ExcludeFromDocs] + public static bool PropertyField(Rect position, SerializedProperty property) + { + bool includeChildren = false; + return EditorGUI.PropertyField(position, property, includeChildren); + } + public static bool PropertyField(Rect position, SerializedProperty property, [DefaultValue("false")] bool includeChildren) + { + return EditorGUI.PropertyFieldInternal(position, property, null, includeChildren); + } + [ExcludeFromDocs] + public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label) + { + bool includeChildren = false; + return EditorGUI.PropertyField(position, property, label, includeChildren); + } + public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label, [DefaultValue("false")] bool includeChildren) + { + return EditorGUI.PropertyFieldInternal(position, property, label, includeChildren); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorGUIExt.cs b/UnityEditor/UnityEditor/EditorGUIExt.cs new file mode 100644 index 00000000..00a9a249 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUIExt.cs @@ -0,0 +1,824 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class EditorGUIExt + { + private class Styles + { + public GUIStyle selectionRect = "SelectionRect"; + } + private class MinMaxSliderState + { + public float dragStartPos; + public float dragStartValue; + public float dragStartSize; + public float dragStartValuesPerPixel; + public float dragStartLimit; + public float dragEndLimit; + public int whereWeDrag = -1; + } + private enum DragSelectionState + { + None, + DragSelecting, + Dragging + } + private static EditorGUIExt.Styles ms_Styles = new EditorGUIExt.Styles(); + private static int repeatButtonHash = "repeatButton".GetHashCode(); + private static float nextScrollStepTime = 0f; + private static int firstScrollWait = 250; + private static int scrollWait = 30; + private static int scrollControlID; + private static EditorGUIExt.MinMaxSliderState s_MinMaxSliderState; + private static int kFirstScrollWait = 250; + private static int kScrollWait = 30; + private static DateTime s_NextScrollStepTime = DateTime.Now; + private static Vector2 s_MouseDownPos = Vector2.zero; + private static EditorGUIExt.DragSelectionState s_MultiSelectDragSelection = EditorGUIExt.DragSelectionState.None; + private static Vector2 s_StartSelectPos = Vector2.zero; + private static List s_SelectionBackup = null; + private static List s_LastFrameSelections = null; + internal static int s_MinMaxSliderHash = "MinMaxSlider".GetHashCode(); + private static bool adding = false; + private static bool[] initSelections; + private static int initIndex = 0; + private static bool DoRepeatButton(Rect position, GUIContent content, GUIStyle style, FocusType focusType) + { + int controlID = GUIUtility.GetControlID(EditorGUIExt.repeatButtonHash, focusType, position); + EventType typeForControl = Event.current.GetTypeForControl(controlID); + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = controlID; + Event.current.Use(); + } + return false; + } + if (typeForControl != EventType.MouseUp) + { + if (typeForControl != EventType.Repaint) + { + return false; + } + style.Draw(position, content, controlID); + return controlID == GUIUtility.hotControl && position.Contains(Event.current.mousePosition); + } + else + { + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + return position.Contains(Event.current.mousePosition); + } + return false; + } + } + private static bool ScrollerRepeatButton(int scrollerID, Rect rect, GUIStyle style) + { + bool result = false; + if (EditorGUIExt.DoRepeatButton(rect, GUIContent.none, style, FocusType.Passive)) + { + bool flag = EditorGUIExt.scrollControlID != scrollerID; + EditorGUIExt.scrollControlID = scrollerID; + if (flag) + { + result = true; + EditorGUIExt.nextScrollStepTime = Time.realtimeSinceStartup + 0.001f * (float)EditorGUIExt.firstScrollWait; + } + else + { + if (Time.realtimeSinceStartup >= EditorGUIExt.nextScrollStepTime) + { + result = true; + EditorGUIExt.nextScrollStepTime = Time.realtimeSinceStartup + 0.001f * (float)EditorGUIExt.scrollWait; + } + } + if (Event.current.type == EventType.Repaint) + { + HandleUtility.Repaint(); + } + } + return result; + } + public static void MinMaxScroller(Rect position, int id, ref float value, ref float size, float visualStart, float visualEnd, float startLimit, float endLimit, GUIStyle slider, GUIStyle thumb, GUIStyle leftButton, GUIStyle rightButton, bool horiz) + { + float num; + if (horiz) + { + num = size * 10f / position.width; + } + else + { + num = size * 10f / position.height; + } + Rect position2; + Rect rect; + Rect rect2; + if (horiz) + { + position2 = new Rect(position.x + leftButton.fixedWidth, position.y, position.width - leftButton.fixedWidth - rightButton.fixedWidth, position.height); + rect = new Rect(position.x, position.y, leftButton.fixedWidth, position.height); + rect2 = new Rect(position.xMax - rightButton.fixedWidth, position.y, rightButton.fixedWidth, position.height); + } + else + { + position2 = new Rect(position.x, position.y + leftButton.fixedHeight, position.width, position.height - leftButton.fixedHeight - rightButton.fixedHeight); + rect = new Rect(position.x, position.y, position.width, leftButton.fixedHeight); + rect2 = new Rect(position.x, position.yMax - rightButton.fixedHeight, position.width, rightButton.fixedHeight); + } + float num2 = Mathf.Min(visualStart, value); + float num3 = Mathf.Max(visualEnd, value + size); + EditorGUIExt.MinMaxSlider(position2, ref value, ref size, num2, num3, num2, num3, slider, thumb, horiz); + bool flag = false; + if (Event.current.type == EventType.MouseUp) + { + flag = true; + } + if (EditorGUIExt.ScrollerRepeatButton(id, rect, leftButton)) + { + value -= num * ((visualStart >= visualEnd) ? -1f : 1f); + } + if (EditorGUIExt.ScrollerRepeatButton(id, rect2, rightButton)) + { + value += num * ((visualStart >= visualEnd) ? -1f : 1f); + } + if (flag && Event.current.type == EventType.Used) + { + EditorGUIExt.scrollControlID = 0; + } + if (startLimit < endLimit) + { + value = Mathf.Clamp(value, startLimit, endLimit - size); + } + else + { + value = Mathf.Clamp(value, endLimit, startLimit - size); + } + } + public static void MinMaxSlider(Rect position, ref float value, ref float size, float visualStart, float visualEnd, float startLimit, float endLimit, GUIStyle slider, GUIStyle thumb, bool horiz) + { + EditorGUIExt.DoMinMaxSlider(position, GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive), ref value, ref size, visualStart, visualEnd, startLimit, endLimit, slider, thumb, horiz); + } + internal static void DoMinMaxSlider(Rect position, int id, ref float value, ref float size, float visualStart, float visualEnd, float startLimit, float endLimit, GUIStyle slider, GUIStyle thumb, bool horiz) + { + Event current = Event.current; + bool flag = size == 0f; + float num = Mathf.Min(visualStart, visualEnd); + float num2 = Mathf.Max(visualStart, visualEnd); + float num3 = Mathf.Min(startLimit, endLimit); + float num4 = Mathf.Max(startLimit, endLimit); + EditorGUIExt.MinMaxSliderState minMaxSliderState = EditorGUIExt.s_MinMaxSliderState; + if (GUIUtility.hotControl == id && minMaxSliderState != null) + { + num = minMaxSliderState.dragStartLimit; + num3 = minMaxSliderState.dragStartLimit; + num2 = minMaxSliderState.dragEndLimit; + num4 = minMaxSliderState.dragEndLimit; + } + float num5 = 0f; + float num6 = Mathf.Clamp(value, num, num2); + float num7 = Mathf.Clamp(value + size, num, num2) - num6; + float num8 = (float)((visualStart <= visualEnd) ? 1 : -1); + if (slider == null || thumb == null) + { + return; + } + float num10; + Rect position2; + Rect rect; + Rect rect2; + float num11; + if (horiz) + { + float num9 = (thumb.fixedWidth == 0f) ? ((float)thumb.padding.horizontal) : thumb.fixedWidth; + num10 = (position.width - (float)slider.padding.horizontal - num9) / (num2 - num); + position2 = new Rect((num6 - num) * num10 + position.x + (float)slider.padding.left, position.y + (float)slider.padding.top, num7 * num10 + num9, position.height - (float)slider.padding.vertical); + rect = new Rect(position2.x, position2.y, (float)thumb.padding.left, position2.height); + rect2 = new Rect(position2.xMax - (float)thumb.padding.right, position2.y, (float)thumb.padding.right, position2.height); + num11 = current.mousePosition.x - position.x; + } + else + { + float num12 = (thumb.fixedHeight == 0f) ? ((float)thumb.padding.vertical) : thumb.fixedHeight; + num10 = (position.height - (float)slider.padding.vertical - num12) / (num2 - num); + position2 = new Rect(position.x + (float)slider.padding.left, (num6 - num) * num10 + position.y + (float)slider.padding.top, position.width - (float)slider.padding.horizontal, num7 * num10 + num12); + rect = new Rect(position2.x, position2.y, position2.width, (float)thumb.padding.top); + rect2 = new Rect(position2.x, position2.yMax - (float)thumb.padding.bottom, position2.width, (float)thumb.padding.bottom); + num11 = current.mousePosition.y - position.y; + } + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (!position.Contains(current.mousePosition) || num - num2 == 0f) + { + return; + } + if (minMaxSliderState == null) + { + minMaxSliderState = (EditorGUIExt.s_MinMaxSliderState = new EditorGUIExt.MinMaxSliderState()); + } + if (position2.Contains(current.mousePosition)) + { + minMaxSliderState.dragStartPos = num11; + minMaxSliderState.dragStartValue = value; + minMaxSliderState.dragStartSize = size; + minMaxSliderState.dragStartValuesPerPixel = num10; + minMaxSliderState.dragStartLimit = startLimit; + minMaxSliderState.dragEndLimit = endLimit; + if (rect.Contains(current.mousePosition)) + { + minMaxSliderState.whereWeDrag = 1; + } + else + { + if (rect2.Contains(current.mousePosition)) + { + minMaxSliderState.whereWeDrag = 2; + } + else + { + minMaxSliderState.whereWeDrag = 0; + } + } + GUIUtility.hotControl = id; + current.Use(); + return; + } + if (slider == GUIStyle.none) + { + return; + } + if (size != 0f && flag) + { + if (horiz) + { + if (num11 > position2.xMax - position.x) + { + value += size * num8 * 0.9f; + } + else + { + value -= size * num8 * 0.9f; + } + } + else + { + if (num11 > position2.yMax - position.y) + { + value += size * num8 * 0.9f; + } + else + { + value -= size * num8 * 0.9f; + } + } + minMaxSliderState.whereWeDrag = 0; + GUI.changed = true; + EditorGUIExt.s_NextScrollStepTime = DateTime.Now.AddMilliseconds((double)EditorGUIExt.kFirstScrollWait); + float num13 = (!horiz) ? current.mousePosition.y : current.mousePosition.x; + float num14 = (!horiz) ? position2.y : position2.x; + minMaxSliderState.whereWeDrag = ((num13 <= num14) ? 3 : 4); + } + else + { + if (horiz) + { + value = (num11 - position2.width * 0.5f) / num10 + num - size * 0.5f; + } + else + { + value = (num11 - position2.height * 0.5f) / num10 + num - size * 0.5f; + } + minMaxSliderState.dragStartPos = num11; + minMaxSliderState.dragStartValue = value; + minMaxSliderState.dragStartSize = size; + minMaxSliderState.whereWeDrag = 0; + GUI.changed = true; + } + GUIUtility.hotControl = id; + value = Mathf.Clamp(value, num3, num4 - size); + current.Use(); + return; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + current.Use(); + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + { + if (GUIUtility.hotControl != id) + { + return; + } + float num15 = (num11 - minMaxSliderState.dragStartPos) / minMaxSliderState.dragStartValuesPerPixel; + switch (minMaxSliderState.whereWeDrag) + { + case 0: + value = Mathf.Clamp(minMaxSliderState.dragStartValue + num15, num3, num4 - size); + break; + case 1: + value = minMaxSliderState.dragStartValue + num15; + size = minMaxSliderState.dragStartSize - num15; + if (value < num3) + { + size -= num3 - value; + value = num3; + } + if (size < num5) + { + value -= num5 - size; + size = num5; + } + break; + case 2: + size = minMaxSliderState.dragStartSize + num15; + if (value + size > num4) + { + size = num4 - value; + } + if (size < num5) + { + size = num5; + } + break; + } + GUI.changed = true; + current.Use(); + break; + } + case EventType.Repaint: + { + slider.Draw(position, GUIContent.none, id); + thumb.Draw(position2, GUIContent.none, id); + if (GUIUtility.hotControl != id || !position.Contains(current.mousePosition) || num - num2 == 0f) + { + return; + } + if (position2.Contains(current.mousePosition)) + { + if (minMaxSliderState != null && (minMaxSliderState.whereWeDrag == 3 || minMaxSliderState.whereWeDrag == 4)) + { + GUIUtility.hotControl = 0; + } + return; + } + if (DateTime.Now < EditorGUIExt.s_NextScrollStepTime) + { + return; + } + float num13 = (!horiz) ? current.mousePosition.y : current.mousePosition.x; + float num14 = (!horiz) ? position2.y : position2.x; + int num16 = (num13 <= num14) ? 3 : 4; + if (num16 != minMaxSliderState.whereWeDrag) + { + return; + } + if (size != 0f && flag) + { + if (horiz) + { + if (num11 > position2.xMax - position.x) + { + value += size * num8 * 0.9f; + } + else + { + value -= size * num8 * 0.9f; + } + } + else + { + if (num11 > position2.yMax - position.y) + { + value += size * num8 * 0.9f; + } + else + { + value -= size * num8 * 0.9f; + } + } + minMaxSliderState.whereWeDrag = -1; + GUI.changed = true; + } + value = Mathf.Clamp(value, num3, num4 - size); + EditorGUIExt.s_NextScrollStepTime = DateTime.Now.AddMilliseconds((double)EditorGUIExt.kScrollWait); + break; + } + } + } + public static bool DragSelection(Rect[] positions, ref bool[] selections, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(34553287, FocusType.Keyboard); + Event current = Event.current; + int num = -1; + for (int i = positions.Length - 1; i >= 0; i--) + { + if (positions[i].Contains(current.mousePosition)) + { + num = i; + break; + } + } + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0 && num >= 0) + { + GUIUtility.keyboardControl = 0; + bool flag = false; + if (selections[num]) + { + int num2 = 0; + bool[] array = selections; + for (int j = 0; j < array.Length; j++) + { + bool flag2 = array[j]; + if (flag2) + { + num2++; + if (num2 > 1) + { + break; + } + } + } + if (num2 == 1) + { + flag = true; + } + } + if (!current.shift && !EditorGUI.actionKey) + { + for (int k = 0; k < positions.Length; k++) + { + selections[k] = false; + } + } + EditorGUIExt.initIndex = num; + EditorGUIExt.initSelections = (bool[])selections.Clone(); + EditorGUIExt.adding = true; + if ((current.shift || EditorGUI.actionKey) && selections[num]) + { + EditorGUIExt.adding = false; + } + selections[num] = (!flag && EditorGUIExt.adding); + GUIUtility.hotControl = controlID; + current.Use(); + return true; + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + if (num < 0) + { + Rect rect = new Rect(positions[0].x, positions[0].y - 200f, positions[0].width, 200f); + if (rect.Contains(current.mousePosition)) + { + num = 0; + } + rect.y = positions[positions.Length - 1].yMax; + if (rect.Contains(current.mousePosition)) + { + num = selections.Length - 1; + } + } + if (num < 0) + { + return false; + } + int num3 = Mathf.Min(EditorGUIExt.initIndex, num); + int num4 = Mathf.Max(EditorGUIExt.initIndex, num); + for (int l = 0; l < selections.Length; l++) + { + if (l >= num3 && l <= num4) + { + selections[l] = EditorGUIExt.adding; + } + else + { + selections[l] = EditorGUIExt.initSelections[l]; + } + } + current.Use(); + return true; + } + break; + case EventType.Repaint: + for (int m = 0; m < positions.Length; m++) + { + style.Draw(positions[m], GUIContent.none, controlID, selections[m]); + } + break; + } + return false; + } + private static bool Any(bool[] selections) + { + for (int i = 0; i < selections.Length; i++) + { + if (selections[i]) + { + return true; + } + } + return false; + } + public static HighLevelEvent MultiSelection(Rect rect, Rect[] positions, GUIContent content, Rect[] hitPositions, ref bool[] selections, bool[] readOnly, out int clickedIndex, out Vector2 offset, out float startSelect, out float endSelect, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(41623453, FocusType.Keyboard); + Event current = Event.current; + offset = Vector2.zero; + clickedIndex = -1; + startSelect = (endSelect = 0f); + if (current.type == EventType.Used) + { + return HighLevelEvent.None; + } + bool flag = false; + if (GUIUtility.keyboardControl == controlID) + { + flag = true; + } + else + { + selections = new bool[selections.Length]; + } + EventType typeForControl = current.GetTypeForControl(controlID); + EventType eventType = typeForControl; + switch (eventType) + { + case EventType.MouseDown: + { + if (current.button != 0) + { + return HighLevelEvent.None; + } + GUIUtility.hotControl = controlID; + GUIUtility.keyboardControl = controlID; + EditorGUIExt.s_StartSelectPos = current.mousePosition; + int indexUnderMouse = EditorGUIExt.GetIndexUnderMouse(hitPositions, readOnly); + if (Event.current.clickCount == 2 && indexUnderMouse >= 0) + { + for (int i = 0; i < selections.Length; i++) + { + selections[i] = false; + } + selections[indexUnderMouse] = true; + current.Use(); + clickedIndex = indexUnderMouse; + return HighLevelEvent.DoubleClick; + } + if (indexUnderMouse >= 0) + { + if (!current.shift && !EditorGUI.actionKey && !selections[indexUnderMouse]) + { + for (int j = 0; j < hitPositions.Length; j++) + { + selections[j] = false; + } + } + if (current.shift || EditorGUI.actionKey) + { + selections[indexUnderMouse] = !selections[indexUnderMouse]; + } + else + { + selections[indexUnderMouse] = true; + } + EditorGUIExt.s_MouseDownPos = current.mousePosition; + EditorGUIExt.s_MultiSelectDragSelection = EditorGUIExt.DragSelectionState.None; + current.Use(); + clickedIndex = indexUnderMouse; + return HighLevelEvent.SelectionChanged; + } + bool flag2; + if (!current.shift && !EditorGUI.actionKey) + { + for (int k = 0; k < hitPositions.Length; k++) + { + selections[k] = false; + } + flag2 = true; + } + else + { + flag2 = false; + } + EditorGUIExt.s_SelectionBackup = new List(selections); + EditorGUIExt.s_LastFrameSelections = new List(selections); + EditorGUIExt.s_MultiSelectDragSelection = EditorGUIExt.DragSelectionState.DragSelecting; + current.Use(); + return (!flag2) ? HighLevelEvent.None : HighLevelEvent.SelectionChanged; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + if (EditorGUIExt.s_StartSelectPos != current.mousePosition) + { + current.Use(); + } + if (EditorGUIExt.s_MultiSelectDragSelection != EditorGUIExt.DragSelectionState.None) + { + EditorGUIExt.s_MultiSelectDragSelection = EditorGUIExt.DragSelectionState.None; + EditorGUIExt.s_SelectionBackup = null; + EditorGUIExt.s_LastFrameSelections = null; + return HighLevelEvent.EndDrag; + } + clickedIndex = EditorGUIExt.GetIndexUnderMouse(hitPositions, readOnly); + if (current.clickCount == 1) + { + return HighLevelEvent.Click; + } + } + return HighLevelEvent.None; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_96: + switch (eventType) + { + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + if (flag) + { + bool flag3 = current.type == EventType.ExecuteCommand; + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUIExt.<>f__switch$map9 == null) + { + EditorGUIExt.<>f__switch$map9 = new Dictionary(1) + { + + { + "Delete", + 0 + } + }; + } + int num; + if (EditorGUIExt.<>f__switch$map9.TryGetValue(commandName, out num)) + { + if (num == 0) + { + current.Use(); + if (flag3) + { + return HighLevelEvent.Delete; + } + } + } + } + } + return HighLevelEvent.None; + case EventType.DragExited: + return HighLevelEvent.None; + case EventType.ContextClick: + { + int indexUnderMouse = EditorGUIExt.GetIndexUnderMouse(hitPositions, readOnly); + if (indexUnderMouse >= 0) + { + clickedIndex = indexUnderMouse; + GUIUtility.keyboardControl = controlID; + current.Use(); + return HighLevelEvent.ContextClick; + } + return HighLevelEvent.None; + } + default: + return HighLevelEvent.None; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl != controlID) + { + return HighLevelEvent.None; + } + if (EditorGUIExt.s_MultiSelectDragSelection == EditorGUIExt.DragSelectionState.DragSelecting) + { + float num2 = Mathf.Min(EditorGUIExt.s_StartSelectPos.x, current.mousePosition.x); + float num3 = Mathf.Max(EditorGUIExt.s_StartSelectPos.x, current.mousePosition.x); + EditorGUIExt.s_SelectionBackup.CopyTo(selections); + for (int l = 0; l < hitPositions.Length; l++) + { + if (!selections[l]) + { + float num4 = hitPositions[l].x + hitPositions[l].width * 0.5f; + if (num4 >= num2 && num4 <= num3) + { + selections[l] = true; + } + } + } + current.Use(); + startSelect = num2; + endSelect = num3; + bool flag4 = false; + for (int m = 0; m < selections.Length; m++) + { + if (selections[m] != EditorGUIExt.s_LastFrameSelections[m]) + { + flag4 = true; + EditorGUIExt.s_LastFrameSelections[m] = selections[m]; + } + } + return (!flag4) ? HighLevelEvent.None : HighLevelEvent.SelectionChanged; + } + offset = current.mousePosition - EditorGUIExt.s_MouseDownPos; + current.Use(); + if (EditorGUIExt.s_MultiSelectDragSelection == EditorGUIExt.DragSelectionState.None) + { + EditorGUIExt.s_MultiSelectDragSelection = EditorGUIExt.DragSelectionState.Dragging; + return HighLevelEvent.BeginDrag; + } + return HighLevelEvent.Drag; + case EventType.KeyDown: + if (flag && (current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete)) + { + current.Use(); + return HighLevelEvent.Delete; + } + return HighLevelEvent.None; + case EventType.Repaint: + { + if (GUIUtility.hotControl == controlID && EditorGUIExt.s_MultiSelectDragSelection == EditorGUIExt.DragSelectionState.DragSelecting) + { + float num5 = Mathf.Min(EditorGUIExt.s_StartSelectPos.x, current.mousePosition.x); + float num6 = Mathf.Max(EditorGUIExt.s_StartSelectPos.x, current.mousePosition.x); + Rect position = new Rect(0f, 0f, rect.width, rect.height); + position.x = num5; + position.width = num6 - num5; + if (position.width != 0f) + { + GUI.Box(position, string.Empty, EditorGUIExt.ms_Styles.selectionRect); + } + } + Color color = GUI.color; + for (int n = 0; n < positions.Length; n++) + { + if (readOnly != null && readOnly[n]) + { + GUI.color = color * new Color(0.9f, 0.9f, 0.9f, 0.5f); + } + else + { + if (selections[n]) + { + GUI.color = color * new Color(0.3f, 0.55f, 0.95f, 1f); + } + else + { + GUI.color = color * new Color(0.9f, 0.9f, 0.9f, 1f); + } + } + style.Draw(positions[n], content, controlID, selections[n]); + } + GUI.color = color; + return HighLevelEvent.None; + } + } + goto IL_96; + } + private static int GetIndexUnderMouse(Rect[] hitPositions, bool[] readOnly) + { + Vector2 mousePosition = Event.current.mousePosition; + for (int i = hitPositions.Length - 1; i >= 0; i--) + { + if ((readOnly == null || !readOnly[i]) && hitPositions[i].Contains(mousePosition)) + { + return i; + } + } + return -1; + } + internal static Rect FromToRect(Vector2 start, Vector2 end) + { + Rect result = new Rect(start.x, start.y, end.x - start.x, end.y - start.y); + if (result.width < 0f) + { + result.x += result.width; + result.width = -result.width; + } + if (result.height < 0f) + { + result.y += result.height; + result.height = -result.height; + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorGUIInternal.cs b/UnityEditor/UnityEditor/EditorGUIInternal.cs new file mode 100644 index 00000000..7095be38 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUIInternal.cs @@ -0,0 +1,57 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class EditorGUIInternal : GUI + { + internal static Rect GetTooltipRect() + { + return GUI.tooltipRect; + } + internal static string GetMouseTooltip() + { + return GUI.mouseTooltip; + } + internal static bool DoToggleForward(Rect position, int id, bool value, GUIContent content, GUIStyle style) + { + Event current = Event.current; + if (current.MainActionKeyForControl(id)) + { + value = !value; + current.Use(); + GUI.changed = true; + } + if (EditorGUI.showMixedValue) + { + style = EditorStyles.toggleMixed; + } + EventType type = current.type; + bool flag = current.type == EventType.MouseDown && current.button != 0; + if (flag) + { + current.type = EventType.Ignore; + } + bool result = GUI.DoToggle(position, id, !EditorGUI.showMixedValue && value, content, style.m_Ptr); + if (flag) + { + current.type = type; + } + else + { + if (current.type != type) + { + GUIUtility.keyboardControl = id; + } + } + return result; + } + internal static Vector2 DoBeginScrollViewForward(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background) + { + return GUI.DoBeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); + } + internal static void BeginWindowsForward(int skinMode, int editorWindowInstanceID) + { + GUI.BeginWindows(skinMode, editorWindowInstanceID); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorGUILayout.cs b/UnityEditor/UnityEditor/EditorGUILayout.cs new file mode 100644 index 00000000..fad66454 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUILayout.cs @@ -0,0 +1,1260 @@ +using System; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class EditorGUILayout + { + internal const float kPlatformTabWidth = 30f; + internal static Rect s_LastRect; + internal static SavedBool s_SelectedDefault = new SavedBool("Platform.ShownDefaultTab", true); + internal static float kLabelFloatMinW + { + get + { + return EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5f; + } + } + internal static float kLabelFloatMaxW + { + get + { + return EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5f; + } + } + public static void LabelField(string label, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(GUIContent.none, EditorGUIUtility.TempContent(label), EditorStyles.label, options); + } + public static void LabelField(string label, GUIStyle style, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(GUIContent.none, EditorGUIUtility.TempContent(label), style, options); + } + public static void LabelField(GUIContent label, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(GUIContent.none, label, EditorStyles.label, options); + } + public static void LabelField(GUIContent label, GUIStyle style, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(GUIContent.none, label, style, options); + } + public static void LabelField(string label, string label2, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(new GUIContent(label), EditorGUIUtility.TempContent(label2), EditorStyles.label, options); + } + public static void LabelField(string label, string label2, GUIStyle style, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(new GUIContent(label), EditorGUIUtility.TempContent(label2), style, options); + } + public static void LabelField(GUIContent label, GUIContent label2, params GUILayoutOption[] options) + { + EditorGUILayout.LabelField(label, label2, EditorStyles.label, options); + } + public static void LabelField(GUIContent label, GUIContent label2, GUIStyle style, params GUILayoutOption[] options) + { + if (!style.wordWrap) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, options); + EditorGUI.LabelField(position, label, label2, style); + } + else + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(label, style); + Rect rect = GUILayoutUtility.GetRect(label2, style, options); + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUI.LabelField(rect, label2, style); + EditorGUI.indentLevel = indentLevel; + EditorGUILayout.EndHorizontal(); + } + } + public static bool Toggle(bool value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetToggleRect(false, options); + return EditorGUI.Toggle(position, value); + } + public static bool Toggle(string label, bool value, params GUILayoutOption[] options) + { + return EditorGUILayout.Toggle(EditorGUIUtility.TempContent(label), value, options); + } + public static bool Toggle(GUIContent label, bool value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetToggleRect(true, options); + return EditorGUI.Toggle(position, label, value); + } + public static bool Toggle(bool value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetToggleRect(false, options); + return EditorGUI.Toggle(position, value, style); + } + public static bool Toggle(string label, bool value, GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.Toggle(EditorGUIUtility.TempContent(label), value, style, options); + } + public static bool Toggle(GUIContent label, bool value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetToggleRect(true, options); + return EditorGUI.Toggle(position, label, value, style); + } + public static bool ToggleLeft(string label, bool value, params GUILayoutOption[] options) + { + return EditorGUILayout.ToggleLeft(EditorGUIUtility.TempContent(label), value, options); + } + public static bool ToggleLeft(GUIContent label, bool value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, options); + return EditorGUI.ToggleLeft(position, label, value); + } + public static bool ToggleLeft(string label, bool value, GUIStyle labelStyle, params GUILayoutOption[] options) + { + return EditorGUILayout.ToggleLeft(EditorGUIUtility.TempContent(label), value, labelStyle, options); + } + public static bool ToggleLeft(GUIContent label, bool value, GUIStyle labelStyle, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, options); + return EditorGUI.ToggleLeft(position, label, value, labelStyle); + } + public static string TextField(string text, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.textField, options); + return EditorGUI.TextField(position, text); + } + public static string TextField(string text, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.TextField(position, text, style); + } + public static string TextField(string label, string text, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.textField, options); + return EditorGUI.TextField(position, label, text); + } + public static string TextField(string label, string text, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.TextField(position, label, text, style); + } + public static string TextField(GUIContent label, string text, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.textField, options); + return EditorGUI.TextField(position, label, text); + } + public static string TextField(GUIContent label, string text, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.TextField(position, label, text, style); + } + internal static string ToolbarSearchField(string text, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(0f, EditorGUILayout.kLabelFloatMaxW * 1.5f, 16f, 16f, EditorStyles.toolbarSearchField, options); + int num = 0; + return EditorGUI.ToolbarSearchField(position, null, ref num, text); + } + internal static string ToolbarSearchField(string text, string[] searchModes, ref int searchMode, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(0f, EditorGUILayout.kLabelFloatMaxW * 1.5f, 16f, 16f, EditorStyles.toolbarSearchField, options); + return EditorGUI.ToolbarSearchField(position, searchModes, ref searchMode, text); + } + internal static string DelayedTextField(string value, string allowedLetters, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.textField, options); + return EditorGUI.DelayedTextField(position, value, allowedLetters, style); + } + public static string TextArea(string text, params GUILayoutOption[] options) + { + return EditorGUILayout.TextArea(text, EditorStyles.textField, options); + } + public static string TextArea(string text, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(text), style, options); + return EditorGUI.TextArea(position, text, style); + } + public static void SelectableLabel(string text, params GUILayoutOption[] options) + { + EditorGUILayout.SelectableLabel(text, EditorStyles.label, options); + } + public static void SelectableLabel(string text, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 32f, style, options); + EditorGUI.SelectableLabel(position, text, style); + } + internal static Event KeyEventField(Event e, params GUILayoutOption[] options) + { + GUIContent content = EditorGUIUtility.TempContent("[Please press a key]"); + Rect rect = GUILayoutUtility.GetRect(content, GUI.skin.textField, options); + return EditorGUI.KeyEventField(rect, e); + } + public static string PasswordField(string password, params GUILayoutOption[] options) + { + return EditorGUILayout.PasswordField(password, EditorStyles.textField, options); + } + public static string PasswordField(string password, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.PasswordField(position, password, style); + } + public static string PasswordField(string label, string password, params GUILayoutOption[] options) + { + return EditorGUILayout.PasswordField(EditorGUIUtility.TempContent(label), password, EditorStyles.textField, options); + } + public static string PasswordField(string label, string password, GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.PasswordField(EditorGUIUtility.TempContent(label), password, style, options); + } + public static string PasswordField(GUIContent label, string password, params GUILayoutOption[] options) + { + return EditorGUILayout.PasswordField(label, password, EditorStyles.textField, options); + } + public static string PasswordField(GUIContent label, string password, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.PasswordField(position, label, password, style); + } + internal static void VUMeterHorizontal(float value, ref EditorGUI.VUMeterData data, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options); + EditorGUI.VUMeterHorizontal(position, value, ref data); + } + public static float FloatField(float value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options); + return EditorGUI.FloatField(position, value); + } + public static float FloatField(float value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.FloatField(position, value, style); + } + public static float FloatField(string label, float value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.numberField, options); + return EditorGUI.FloatField(position, label, value); + } + public static float FloatField(string label, float value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.FloatField(position, label, value, style); + } + public static float FloatField(GUIContent label, float value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.numberField, options); + return EditorGUI.FloatField(position, label, value); + } + public static float FloatField(GUIContent label, float value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.FloatField(position, label, value, style); + } + public static int IntField(int value, params GUILayoutOption[] options) + { + return EditorGUILayout.IntField(value, EditorStyles.numberField, options); + } + public static int IntField(int value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.IntField(position, value, style); + } + public static int IntField(string label, int value, params GUILayoutOption[] options) + { + return EditorGUILayout.IntField(label, value, EditorStyles.numberField, options); + } + public static int IntField(string label, int value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.IntField(position, label, value, style); + } + public static int IntField(GUIContent label, int value, params GUILayoutOption[] options) + { + return EditorGUILayout.IntField(label, value, EditorStyles.numberField, options); + } + public static int IntField(GUIContent label, int value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.IntField(position, label, value, style); + } + public static float Slider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + return EditorGUI.Slider(position, value, leftValue, rightValue); + } + public static float Slider(string label, float value, float leftValue, float rightValue, params GUILayoutOption[] options) + { + return EditorGUILayout.Slider(EditorGUIUtility.TempContent(label), value, leftValue, rightValue, options); + } + public static float Slider(GUIContent label, float value, float leftValue, float rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + return EditorGUI.Slider(position, label, value, leftValue, rightValue); + } + public static void Slider(SerializedProperty property, float leftValue, float rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + EditorGUI.Slider(position, property, leftValue, rightValue); + } + public static void Slider(SerializedProperty property, float leftValue, float rightValue, string label, params GUILayoutOption[] options) + { + EditorGUILayout.Slider(property, leftValue, rightValue, EditorGUIUtility.TempContent(label), options); + } + public static void Slider(SerializedProperty property, float leftValue, float rightValue, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + EditorGUI.Slider(position, property, leftValue, rightValue, label); + } + internal static float PowerSlider(float sliderValue, float min, float max, float power, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + return EditorGUI.PowerSlider(position, sliderValue, min, max, power); + } + public static int IntSlider(int value, int leftValue, int rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + return EditorGUI.IntSlider(position, value, leftValue, rightValue); + } + public static int IntSlider(string label, int value, int leftValue, int rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + return EditorGUI.IntSlider(position, label, value, leftValue, rightValue); + } + public static int IntSlider(GUIContent label, int value, int leftValue, int rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + return EditorGUI.IntSlider(position, label, value, leftValue, rightValue); + } + public static void IntSlider(SerializedProperty property, int leftValue, int rightValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + EditorGUI.IntSlider(position, property, leftValue, rightValue, property.displayName); + } + public static void IntSlider(SerializedProperty property, int leftValue, int rightValue, string label, params GUILayoutOption[] options) + { + EditorGUILayout.IntSlider(property, leftValue, rightValue, EditorGUIUtility.TempContent(label), options); + } + public static void IntSlider(SerializedProperty property, int leftValue, int rightValue, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + EditorGUI.IntSlider(position, property, leftValue, rightValue, label); + } + public static void MinMaxSlider(ref float minValue, ref float maxValue, float minLimit, float maxLimit, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); + EditorGUI.MinMaxSlider(position, ref minValue, ref maxValue, minLimit, maxLimit); + } + public static void MinMaxSlider(GUIContent label, ref float minValue, ref float maxValue, float minLimit, float maxLimit, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + EditorGUI.MinMaxSlider(label, position, ref minValue, ref maxValue, minLimit, maxLimit); + } + public static int Popup(int selectedIndex, string[] displayedOptions, params GUILayoutOption[] options) + { + return EditorGUILayout.Popup(selectedIndex, displayedOptions, EditorStyles.popup, options); + } + public static int Popup(int selectedIndex, string[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.Popup(position, selectedIndex, displayedOptions, style); + } + public static int Popup(int selectedIndex, GUIContent[] displayedOptions, params GUILayoutOption[] options) + { + return EditorGUILayout.Popup(selectedIndex, displayedOptions, EditorStyles.popup, options); + } + public static int Popup(int selectedIndex, GUIContent[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.Popup(position, selectedIndex, displayedOptions, style); + } + public static int Popup(string label, int selectedIndex, string[] displayedOptions, params GUILayoutOption[] options) + { + return EditorGUILayout.Popup(label, selectedIndex, displayedOptions, EditorStyles.popup, options); + } + public static int Popup(string label, int selectedIndex, string[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, style); + } + public static int Popup(GUIContent label, int selectedIndex, GUIContent[] displayedOptions, params GUILayoutOption[] options) + { + return EditorGUILayout.Popup(label, selectedIndex, displayedOptions, EditorStyles.popup, options); + } + public static int Popup(GUIContent label, int selectedIndex, GUIContent[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, style); + } + internal static void Popup(SerializedProperty property, GUIContent[] displayedOptions, params GUILayoutOption[] options) + { + EditorGUILayout.Popup(property, displayedOptions, null, options); + } + internal static void Popup(SerializedProperty property, GUIContent[] displayedOptions, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + EditorGUI.Popup(position, property, displayedOptions, label); + } + public static Enum EnumPopup(Enum selected, params GUILayoutOption[] options) + { + return EditorGUILayout.EnumPopup(selected, EditorStyles.popup, options); + } + public static Enum EnumPopup(Enum selected, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.EnumPopup(position, selected, style); + } + public static Enum EnumPopup(string label, Enum selected, params GUILayoutOption[] options) + { + return EditorGUILayout.EnumPopup(label, selected, EditorStyles.popup, options); + } + public static Enum EnumPopup(string label, Enum selected, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.EnumPopup(position, GUIContent.Temp(label), selected, style); + } + public static Enum EnumPopup(GUIContent label, Enum selected, params GUILayoutOption[] options) + { + return EditorGUILayout.EnumPopup(label, selected, EditorStyles.popup, options); + } + public static Enum EnumPopup(GUIContent label, Enum selected, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.EnumPopup(position, label, selected, style); + } + public static int IntPopup(int selectedValue, string[] displayedOptions, int[] optionValues, params GUILayoutOption[] options) + { + return EditorGUILayout.IntPopup(selectedValue, displayedOptions, optionValues, EditorStyles.popup, options); + } + public static int IntPopup(int selectedValue, string[] displayedOptions, int[] optionValues, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, style); + } + public static int IntPopup(int selectedValue, GUIContent[] displayedOptions, int[] optionValues, params GUILayoutOption[] options) + { + return EditorGUILayout.IntPopup(selectedValue, displayedOptions, optionValues, EditorStyles.popup, options); + } + public static int IntPopup(int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, displayedOptions, optionValues, style); + } + public static int IntPopup(string label, int selectedValue, string[] displayedOptions, int[] optionValues, params GUILayoutOption[] options) + { + return EditorGUILayout.IntPopup(label, selectedValue, displayedOptions, optionValues, EditorStyles.popup, options); + } + public static int IntPopup(string label, int selectedValue, string[] displayedOptions, int[] optionValues, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, style); + } + public static int IntPopup(GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, params GUILayoutOption[] options) + { + return EditorGUILayout.IntPopup(label, selectedValue, displayedOptions, optionValues, EditorStyles.popup, options); + } + public static int IntPopup(GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, style); + } + public static void IntPopup(SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, params GUILayoutOption[] options) + { + EditorGUILayout.IntPopup(property, displayedOptions, optionValues, null, options); + } + public static void IntPopup(SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + EditorGUI.IntPopup(position, property, displayedOptions, optionValues, label); + } + [Obsolete("This function is obsolete and the style is not used.")] + public static void IntPopup(SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label, GUIStyle style, params GUILayoutOption[] options) + { + EditorGUILayout.IntPopup(property, displayedOptions, optionValues, label, options); + } + public static string TagField(string tag, params GUILayoutOption[] options) + { + return EditorGUILayout.TagField(tag, EditorStyles.popup, options); + } + public static string TagField(string tag, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.TagField(position, tag, style); + } + public static string TagField(string label, string tag, params GUILayoutOption[] options) + { + return EditorGUILayout.TagField(EditorGUIUtility.TempContent(label), tag, EditorStyles.popup, options); + } + public static string TagField(string label, string tag, GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.TagField(EditorGUIUtility.TempContent(label), tag, style, options); + } + public static string TagField(GUIContent label, string tag, params GUILayoutOption[] options) + { + return EditorGUILayout.TagField(label, tag, EditorStyles.popup, options); + } + public static string TagField(GUIContent label, string tag, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.TagField(position, label, tag, style); + } + public static int LayerField(int layer, params GUILayoutOption[] options) + { + return EditorGUILayout.LayerField(layer, EditorStyles.popup, options); + } + public static int LayerField(int layer, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.LayerField(position, layer, style); + } + public static int LayerField(string label, int layer, params GUILayoutOption[] options) + { + return EditorGUILayout.LayerField(EditorGUIUtility.TempContent(label), layer, EditorStyles.popup, options); + } + public static int LayerField(string label, int layer, GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.LayerField(EditorGUIUtility.TempContent(label), layer, style, options); + } + public static int LayerField(GUIContent label, int layer, params GUILayoutOption[] options) + { + return EditorGUILayout.LayerField(label, layer, EditorStyles.popup, options); + } + public static int LayerField(GUIContent label, int layer, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.LayerField(position, label, layer, style); + } + public static int MaskField(GUIContent label, int mask, string[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.MaskField(position, label, mask, displayedOptions, style); + } + public static int MaskField(string label, int mask, string[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.MaskField(position, label, mask, displayedOptions, style); + } + public static int MaskField(GUIContent label, int mask, string[] displayedOptions, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + return EditorGUI.MaskField(position, label, mask, displayedOptions, EditorStyles.popup); + } + public static int MaskField(string label, int mask, string[] displayedOptions, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + return EditorGUI.MaskField(position, label, mask, displayedOptions, EditorStyles.popup); + } + public static int MaskField(int mask, string[] displayedOptions, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.MaskField(position, mask, displayedOptions, style); + } + public static int MaskField(int mask, string[] displayedOptions, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.popup, options); + return EditorGUI.MaskField(position, mask, displayedOptions, EditorStyles.popup); + } + public static Enum EnumMaskField(GUIContent label, Enum enumValue, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.EnumMaskField(position, label, enumValue, style); + } + public static Enum EnumMaskField(string label, Enum enumValue, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.EnumMaskField(position, label, enumValue, style); + } + public static Enum EnumMaskField(GUIContent label, Enum enumValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + return EditorGUI.EnumMaskField(position, label, enumValue, EditorStyles.popup); + } + public static Enum EnumMaskField(string label, Enum enumValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.popup, options); + return EditorGUI.EnumMaskField(position, label, enumValue, EditorStyles.popup); + } + public static Enum EnumMaskField(Enum enumValue, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.EnumMaskField(position, enumValue, style); + } + public static Enum EnumMaskField(Enum enumValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.popup, options); + return EditorGUI.EnumMaskField(position, enumValue, EditorStyles.popup); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(UnityEngine.Object obj, Type objType, params GUILayoutOption[] options) + { + return EditorGUILayout.ObjectField(obj, objType, true, options); + } + public static UnityEngine.Object ObjectField(UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, options); + return EditorGUI.ObjectField(position, obj, objType, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(string label, UnityEngine.Object obj, Type objType, params GUILayoutOption[] options) + { + return EditorGUILayout.ObjectField(label, obj, objType, true, options); + } + public static UnityEngine.Object ObjectField(string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) + { + return EditorGUILayout.ObjectField(EditorGUIUtility.TempContent(label), obj, objType, allowSceneObjects, options); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(GUIContent label, UnityEngine.Object obj, Type objType, params GUILayoutOption[] options) + { + return EditorGUILayout.ObjectField(label, obj, objType, true, options); + } + public static UnityEngine.Object ObjectField(GUIContent label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) + { + float height = (!EditorGUIUtility.HasObjectThumbnail(objType)) ? 16f : 64f; + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, height, options); + return EditorGUI.ObjectField(position, label, obj, objType, allowSceneObjects); + } + public static Vector2 Vector2Field(string label, Vector2 value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f, EditorStyles.numberField, options); + return EditorGUI.Vector2Field(position, label, value); + } + public static Vector2 Vector2Field(GUIContent label, Vector2 value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f, EditorStyles.numberField, options); + return EditorGUI.Vector2Field(position, label, value); + } + public static Vector3 Vector3Field(string label, Vector3 value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f, EditorStyles.numberField, options); + return EditorGUI.Vector3Field(position, label, value); + } + public static Vector3 Vector3Field(GUIContent label, Vector3 value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f, EditorStyles.numberField, options); + return EditorGUI.Vector3Field(position, label, value); + } + public static Vector4 Vector4Field(string label, Vector4 value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 32f, EditorStyles.numberField, options); + return EditorGUI.Vector4Field(position, label, value); + } + public static Rect RectField(Rect value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 32f, EditorStyles.numberField, options); + return EditorGUI.RectField(position, value); + } + public static Rect RectField(string label, Rect value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 32f, EditorStyles.numberField, options); + return EditorGUI.RectField(position, label, value); + } + public static Rect RectField(GUIContent label, Rect value, params GUILayoutOption[] options) + { + bool flag = EditorGUI.LabelHasContent(label); + float height = ((flag && !EditorGUIUtility.wideMode) ? 16f : 0f) + 32f; + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(flag, height, EditorStyles.numberField, options); + return EditorGUI.RectField(position, label, value); + } + public static Bounds BoundsField(Bounds value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 32f, EditorStyles.numberField, options); + return EditorGUI.BoundsField(position, value); + } + public static Bounds BoundsField(string label, Bounds value, params GUILayoutOption[] options) + { + return EditorGUILayout.BoundsField(new GUIContent(label), value, options); + } + public static Bounds BoundsField(GUIContent label, Bounds value, params GUILayoutOption[] options) + { + bool flag = EditorGUI.LabelHasContent(label); + float height = (flag ? 16f : 0f) + 32f; + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(flag, height, EditorStyles.numberField, options); + return EditorGUI.BoundsField(position, label, value); + } + internal static int CycleButton(int selected, GUIContent[] options, GUIStyle style) + { + if (GUILayout.Button(options[selected], style, new GUILayoutOption[0])) + { + selected++; + if (selected >= options.Length) + { + selected = 0; + } + } + return selected; + } + public static Color ColorField(Color value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.colorField, options); + return EditorGUI.ColorField(position, value); + } + public static Color ColorField(string label, Color value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.ColorField(position, label, value); + } + public static Color ColorField(GUIContent label, Color value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.ColorField(position, label, value); + } + public static AnimationCurve CurveField(AnimationCurve value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, value); + } + public static AnimationCurve CurveField(string label, AnimationCurve value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, label, value); + } + public static AnimationCurve CurveField(GUIContent label, AnimationCurve value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, label, value); + } + public static AnimationCurve CurveField(AnimationCurve value, Color color, Rect ranges, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, value, color, ranges); + } + public static AnimationCurve CurveField(string label, AnimationCurve value, Color color, Rect ranges, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, label, value, color, ranges); + } + public static AnimationCurve CurveField(GUIContent label, AnimationCurve value, Color color, Rect ranges, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); + return EditorGUI.CurveField(position, label, value, color, ranges); + } + private static void CurveField(SerializedProperty value, Color color, Rect ranges, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.colorField, options); + EditorGUI.CurveField(position, value, color, ranges); + } + public static bool InspectorTitlebar(bool foldout, UnityEngine.Object targetObj) + { + return EditorGUI.InspectorTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), foldout, targetObj); + } + public static bool InspectorTitlebar(bool foldout, UnityEngine.Object[] targetObjs) + { + return EditorGUI.InspectorTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), foldout, targetObjs); + } + internal static bool FoldoutInternal(bool foldout, GUIContent content, GUIStyle style) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUIUtility.fieldWidth, 16f, 16f, style); + return EditorGUI.Foldout(position, foldout, content, style); + } + internal static void ObjectField(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.objectField, options); + EditorGUI.ObjectField(position, property, label); + } + internal static void LayerMaskField(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, options); + EditorGUI.LayerMaskField(position, property, label); + } + public static void HelpBox(string message, MessageType type) + { + EditorGUILayout.LabelField(GUIContent.none, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type)), EditorStyles.helpBox, new GUILayoutOption[0]); + } + public static void HelpBox(string message, MessageType type, bool wide) + { + EditorGUILayout.LabelField((!wide) ? EditorGUIUtility.blankContent : GUIContent.none, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type)), EditorStyles.helpBox, new GUILayoutOption[0]); + } + internal static void PrefixLabelInternal(GUIContent label, GUIStyle followingStyle, GUIStyle labelStyle) + { + float num = (float)followingStyle.margin.left; + if (!EditorGUI.LabelHasContent(label)) + { + GUILayoutUtility.GetRect(EditorGUI.indent - num, 16f, followingStyle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + return; + } + Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.labelWidth - num, 16f, followingStyle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + rect.xMin += EditorGUI.indent; + EditorGUI.HandlePrefixLabel(rect, rect, label, 0, labelStyle); + } + public static void Space() + { + GUILayoutUtility.GetRect(6f, 6f); + } + public static void Separator() + { + EditorGUILayout.Space(); + } + public static bool BeginToggleGroup(string label, bool toggle) + { + return EditorGUILayout.BeginToggleGroup(EditorGUIUtility.TempContent(label), toggle); + } + public static bool BeginToggleGroup(GUIContent label, bool toggle) + { + toggle = EditorGUILayout.ToggleLeft(label, toggle, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!toggle); + GUILayout.BeginVertical(new GUILayoutOption[0]); + return toggle; + } + public static void EndToggleGroup() + { + GUILayout.EndVertical(); + EditorGUI.EndDisabledGroup(); + } + public static Rect BeginHorizontal(params GUILayoutOption[] options) + { + return EditorGUILayout.BeginHorizontal(GUIContent.none, GUIStyle.none, options); + } + public static Rect BeginHorizontal(GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginHorizontal(GUIContent.none, style, options); + } + internal static Rect BeginHorizontal(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayoutUtility.BeginGroup("GUILayout.EndVertical"); + GUILayoutGroup gUILayoutGroup = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); + gUILayoutGroup.isVertical = false; + if (style != GUIStyle.none || content != GUIContent.none) + { + GUI.Box(gUILayoutGroup.rect, GUIContent.none, style); + } + return gUILayoutGroup.rect; + } + public static void EndHorizontal() + { + GUILayout.EndHorizontal(); + } + public static Rect BeginVertical(params GUILayoutOption[] options) + { + return EditorGUILayout.BeginVertical(GUIContent.none, GUIStyle.none, options); + } + public static Rect BeginVertical(GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginVertical(GUIContent.none, style, options); + } + internal static Rect BeginVertical(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayoutUtility.BeginGroup("GUILayout.EndVertical"); + GUILayoutGroup gUILayoutGroup = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); + gUILayoutGroup.isVertical = true; + if (style != GUIStyle.none || content != GUIContent.none) + { + GUI.Box(gUILayoutGroup.rect, GUIContent.none, style); + } + return gUILayoutGroup.rect; + } + public static void EndVertical() + { + GUILayout.EndVertical(); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginScrollView(scrollPosition, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginScrollView(scrollPosition, false, false, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) + { + string name = style.name; + GUIStyle gUIStyle = GUI.skin.FindStyle(name + "VerticalScrollbar"); + if (gUIStyle == null) + { + gUIStyle = GUI.skin.verticalScrollbar; + } + GUIStyle gUIStyle2 = GUI.skin.FindStyle(name + "HorizontalScrollbar"); + if (gUIStyle2 == null) + { + gUIStyle2 = GUI.skin.horizontalScrollbar; + } + return EditorGUILayout.BeginScrollView(scrollPosition, false, false, gUIStyle2, gUIStyle, style, options); + } + internal static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + GUIScrollGroup gUIScrollGroup = (GUIScrollGroup)GUILayoutUtility.BeginLayoutGroup(background, null, typeof(GUIScrollGroup)); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUIScrollGroup.resetCoords = true; + gUIScrollGroup.isVertical = true; + gUIScrollGroup.stretchWidth = 1; + gUIScrollGroup.stretchHeight = 1; + gUIScrollGroup.verticalScrollbar = verticalScrollbar; + gUIScrollGroup.horizontalScrollbar = horizontalScrollbar; + gUIScrollGroup.ApplyOptions(options); + } + return EditorGUIInternal.DoBeginScrollViewForward(gUIScrollGroup.rect, scrollPosition, new Rect(0f, 0f, gUIScrollGroup.clientWidth, gUIScrollGroup.clientHeight), alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); + } + internal static Vector2 BeginVerticalScrollView(Vector2 scrollPosition, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginVerticalScrollView(scrollPosition, false, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); + } + internal static Vector2 BeginVerticalScrollView(Vector2 scrollPosition, bool alwaysShowVertical, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + GUIScrollGroup gUIScrollGroup = (GUIScrollGroup)GUILayoutUtility.BeginLayoutGroup(background, null, typeof(GUIScrollGroup)); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUIScrollGroup.resetCoords = true; + gUIScrollGroup.isVertical = true; + gUIScrollGroup.stretchWidth = 1; + gUIScrollGroup.stretchHeight = 1; + gUIScrollGroup.verticalScrollbar = verticalScrollbar; + gUIScrollGroup.horizontalScrollbar = GUIStyle.none; + gUIScrollGroup.allowHorizontalScroll = false; + gUIScrollGroup.ApplyOptions(options); + } + return EditorGUIInternal.DoBeginScrollViewForward(gUIScrollGroup.rect, scrollPosition, new Rect(0f, 0f, gUIScrollGroup.clientWidth, gUIScrollGroup.clientHeight), false, alwaysShowVertical, GUI.skin.horizontalScrollbar, verticalScrollbar, background); + } + internal static Vector2 BeginHorizontalScrollView(Vector2 scrollPosition, params GUILayoutOption[] options) + { + return EditorGUILayout.BeginHorizontalScrollView(scrollPosition, false, GUI.skin.horizontalScrollbar, GUI.skin.scrollView, options); + } + internal static Vector2 BeginHorizontalScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, GUIStyle horizontalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + GUIScrollGroup gUIScrollGroup = (GUIScrollGroup)GUILayoutUtility.BeginLayoutGroup(background, null, typeof(GUIScrollGroup)); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUIScrollGroup.resetCoords = true; + gUIScrollGroup.isVertical = true; + gUIScrollGroup.stretchWidth = 1; + gUIScrollGroup.stretchHeight = 1; + gUIScrollGroup.verticalScrollbar = GUIStyle.none; + gUIScrollGroup.horizontalScrollbar = horizontalScrollbar; + gUIScrollGroup.allowHorizontalScroll = true; + gUIScrollGroup.allowVerticalScroll = false; + gUIScrollGroup.ApplyOptions(options); + } + return EditorGUIInternal.DoBeginScrollViewForward(gUIScrollGroup.rect, scrollPosition, new Rect(0f, 0f, gUIScrollGroup.clientWidth, gUIScrollGroup.clientHeight), alwaysShowHorizontal, false, horizontalScrollbar, GUI.skin.verticalScrollbar, background); + } + public static void EndScrollView() + { + GUILayout.EndScrollView(true); + } + internal static void EndScrollView(bool handleScrollWheel) + { + GUILayout.EndScrollView(handleScrollWheel); + } + public static bool PropertyField(SerializedProperty property, params GUILayoutOption[] options) + { + return EditorGUILayout.PropertyField(property, null, false, options); + } + public static bool PropertyField(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) + { + return EditorGUILayout.PropertyField(property, label, false, options); + } + public static bool PropertyField(SerializedProperty property, bool includeChildren, params GUILayoutOption[] options) + { + return EditorGUILayout.PropertyField(property, null, includeChildren, options); + } + public static bool PropertyField(SerializedProperty property, GUIContent label, bool includeChildren, params GUILayoutOption[] options) + { + return ScriptAttributeUtility.GetHandler(property).OnGUILayout(property, label, includeChildren, options); + } + public static Rect GetControlRect(params GUILayoutOption[] options) + { + return EditorGUILayout.GetControlRect(true, 16f, EditorStyles.layerMaskField, options); + } + public static Rect GetControlRect(bool hasLabel, params GUILayoutOption[] options) + { + return EditorGUILayout.GetControlRect(hasLabel, 16f, EditorStyles.layerMaskField, options); + } + public static Rect GetControlRect(bool hasLabel, float height, params GUILayoutOption[] options) + { + return EditorGUILayout.GetControlRect(hasLabel, height, EditorStyles.layerMaskField, options); + } + public static Rect GetControlRect(bool hasLabel, float height, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayoutUtility.GetRect((!hasLabel) ? EditorGUIUtility.fieldWidth : EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, height, height, style, options); + } + internal static Rect GetSliderRect(bool hasLabel, params GUILayoutOption[] options) + { + return GUILayoutUtility.GetRect((!hasLabel) ? EditorGUIUtility.fieldWidth : EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW + 5f + 100f, 16f, 16f, EditorStyles.numberField, options); + } + internal static Rect GetToggleRect(bool hasLabel, params GUILayoutOption[] options) + { + float num = 10f - EditorGUIUtility.fieldWidth; + return GUILayoutUtility.GetRect((!hasLabel) ? (EditorGUIUtility.fieldWidth + num) : (EditorGUILayout.kLabelFloatMinW + num), EditorGUILayout.kLabelFloatMaxW + num, 16f, 16f, EditorStyles.numberField, options); + } + public static bool BeginFadeGroup(float value) + { + if (value == 0f) + { + return false; + } + if (value == 1f) + { + return true; + } + GUILayoutFadeGroup gUILayoutFadeGroup = (GUILayoutFadeGroup)GUILayoutUtility.BeginLayoutGroup(GUIStyle.none, null, typeof(GUILayoutFadeGroup)); + gUILayoutFadeGroup.isVertical = true; + gUILayoutFadeGroup.resetCoords = true; + gUILayoutFadeGroup.fadeValue = value; + gUILayoutFadeGroup.wasGUIEnabled = GUI.enabled; + gUILayoutFadeGroup.guiColor = GUI.color; + if (value != 0f && value != 1f && Event.current.type == EventType.MouseDown) + { + Event.current.Use(); + } + EditorGUIUtility.LockContextWidth(); + GUI.BeginGroup(gUILayoutFadeGroup.rect); + return value != 0f; + } + public static void EndFadeGroup() + { + GUILayoutFadeGroup gUILayoutFadeGroup = EditorGUILayoutUtilityInternal.topLevel as GUILayoutFadeGroup; + if (gUILayoutFadeGroup != null) + { + GUI.EndGroup(); + EditorGUIUtility.UnlockContextWidth(); + GUI.enabled = gUILayoutFadeGroup.wasGUIEnabled; + GUI.color = gUILayoutFadeGroup.guiColor; + GUILayoutUtility.EndGroup("GUILayout.EndVertical"); + GUILayoutUtility.EndLayoutGroup(); + } + } + internal static int BeginPlatformGrouping(BuildPlayerWindow.BuildPlatform[] platforms, GUIContent defaultTab) + { + int num = -1; + for (int i = 0; i < platforms.Length; i++) + { + if (platforms[i].targetGroup == EditorUserBuildSettings.selectedBuildTargetGroup) + { + num = i; + } + } + if (num == -1) + { + EditorGUILayout.s_SelectedDefault.value = true; + num = 0; + } + int num2 = (defaultTab != null) ? ((!EditorGUILayout.s_SelectedDefault.value) ? num : -1) : num; + bool enabled = GUI.enabled; + GUI.enabled = true; + EditorGUI.BeginChangeCheck(); + Rect rect = EditorGUILayout.BeginVertical(GUI.skin.box, new GUILayoutOption[0]); + rect.width -= 1f; + int num3 = platforms.Length; + int num4 = 18; + GUIStyle toolbarButton = EditorStyles.toolbarButton; + if (defaultTab != null && GUI.Toggle(new Rect(rect.x, rect.y, rect.width - (float)num3 * 30f, (float)num4), num2 == -1, defaultTab, toolbarButton)) + { + num2 = -1; + } + for (int j = 0; j < num3; j++) + { + Rect position; + if (defaultTab != null) + { + position = new Rect(rect.xMax - (float)(num3 - j) * 30f, rect.y, 30f, (float)num4); + } + else + { + int num5 = Mathf.RoundToInt((float)j * rect.width / (float)num3); + int num6 = Mathf.RoundToInt((float)(j + 1) * rect.width / (float)num3); + position = new Rect(rect.x + (float)num5, rect.y, (float)(num6 - num5), (float)num4); + } + if (GUI.Toggle(position, num2 == j, platforms[j].smallIcon, toolbarButton)) + { + num2 = j; + } + } + GUILayoutUtility.GetRect(10f, (float)num4); + GUI.enabled = enabled; + if (EditorGUI.EndChangeCheck()) + { + if (defaultTab == null) + { + EditorUserBuildSettings.selectedBuildTargetGroup = platforms[num2].targetGroup; + } + else + { + if (num2 < 0) + { + EditorGUILayout.s_SelectedDefault.value = true; + } + else + { + EditorUserBuildSettings.selectedBuildTargetGroup = platforms[num2].targetGroup; + EditorGUILayout.s_SelectedDefault.value = false; + } + } + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(BuildPlayerWindow)); + for (int k = 0; k < array.Length; k++) + { + BuildPlayerWindow buildPlayerWindow = array[k] as BuildPlayerWindow; + if (buildPlayerWindow != null) + { + buildPlayerWindow.Repaint(); + } + } + } + return num2; + } + internal static void EndPlatformGrouping() + { + EditorGUILayout.EndVertical(); + } + internal static void MultiSelectionObjectTitleBar(UnityEngine.Object[] objects) + { + string text = objects[0].name + " (" + ObjectNames.NicifyVariableName(ObjectNames.GetTypeName(objects[0])) + ")"; + if (objects.Length > 1) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + " and ", + objects.Length - 1, + " other", + (objects.Length <= 2) ? string.Empty : "s" + }); + } + GUILayoutOption[] options = new GUILayoutOption[] + { + GUILayout.Height(16f) + }; + GUILayout.Label(EditorGUIUtility.TempContent(text, AssetPreview.GetMiniThumbnail(objects[0])), EditorStyles.boldLabel, options); + } + internal static bool BitToggleField(string label, SerializedProperty bitFieldProperty, int flag) + { + bool flag2 = (bitFieldProperty.intValue & flag) != 0; + bool flag3 = (bitFieldProperty.hasMultipleDifferentValuesBitwise & flag) != 0; + EditorGUI.showMixedValue = flag3; + EditorGUI.BeginChangeCheck(); + flag2 = EditorGUILayout.Toggle(label, flag2, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (flag3) + { + flag2 = true; + } + flag3 = false; + int index = -1; + for (int i = 0; i < 32; i++) + { + if ((1 << i & flag) != 0) + { + index = i; + break; + } + } + bitFieldProperty.SetBitAtIndexForAllTargetsImmediate(index, flag2); + } + EditorGUI.showMixedValue = false; + return flag2 && !flag3; + } + internal static void SortingLayerField(GUIContent label, SerializedProperty layerID, GUIStyle style) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, new GUILayoutOption[0]); + EditorGUI.SortingLayerField(position, label, layerID, style); + } + internal static Gradient GradientField(Gradient value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(position, value); + } + internal static Gradient GradientField(string label, Gradient value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(label, position, value); + } + internal static Gradient GradientField(GUIContent label, Gradient value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(label, position, value); + } + internal static Gradient GradientField(SerializedProperty value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(position, value); + } + internal static Gradient GradientField(string label, SerializedProperty value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(label, position, value); + } + internal static Gradient GradientField(GUIContent label, SerializedProperty value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); + return EditorGUI.GradientField(label, position, value); + } + internal static bool IconButton(int id, GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return EditorGUI.IconButton(id, GUILayoutUtility.GetRect(content, style, options), content, style); + } + internal static void GameViewSizePopup(GameViewSizeGroupType groupType, int selectedIndex, Action itemClickedCallback, GUIStyle style, params GUILayoutOption[] options) + { + Rect controlRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + EditorGUI.GameViewSizePopup(controlRect, groupType, selectedIndex, itemClickedCallback, style); + } + internal static void TargetChoiceField(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) + { + EditorGUILayout.TargetChoiceField(property, label, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget), options); + } + internal static void TargetChoiceField(SerializedProperty property, GUIContent label, TargetChoiceHandler.TargetChoiceMenuFunction func, params GUILayoutOption[] options) + { + Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.popup, options); + EditorGUI.TargetChoiceField(rect, property, label, func); + } + [ExcludeFromDocs] + public static bool Foldout(bool foldout, string content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUILayout.Foldout(foldout, content, foldout2); + } + public static bool Foldout(bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUILayout.Foldout(foldout, EditorGUIUtility.TempContent(content), style); + } + [ExcludeFromDocs] + public static bool Foldout(bool foldout, GUIContent content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUILayout.Foldout(foldout, content, foldout2); + } + public static bool Foldout(bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUILayout.FoldoutInternal(foldout, content, style); + } + [ExcludeFromDocs] + public static void PrefixLabel(string label) + { + GUIStyle followingStyle = "Button"; + EditorGUILayout.PrefixLabel(label, followingStyle); + } + public static void PrefixLabel(string label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, EditorStyles.label); + } + public static void PrefixLabel(string label, GUIStyle followingStyle, GUIStyle labelStyle) + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, labelStyle); + } + [ExcludeFromDocs] + public static void PrefixLabel(GUIContent label) + { + GUIStyle followingStyle = "Button"; + EditorGUILayout.PrefixLabel(label, followingStyle); + } + public static void PrefixLabel(GUIContent label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) + { + EditorGUILayout.PrefixLabel(label, followingStyle, EditorStyles.label); + } + public static void PrefixLabel(GUIContent label, GUIStyle followingStyle, GUIStyle labelStyle) + { + EditorGUILayout.PrefixLabelInternal(label, followingStyle, labelStyle); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorGUILayoutUtilityInternal.cs b/UnityEditor/UnityEditor/EditorGUILayoutUtilityInternal.cs new file mode 100644 index 00000000..76afffd8 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUILayoutUtilityInternal.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class EditorGUILayoutUtilityInternal : GUILayoutUtility + { + internal static GUILayoutGroup topLevel + { + get + { + return GUILayoutUtility.topLevel; + } + } + internal static GUILayoutGroup BeginLayoutArea(GUIStyle style, Type LayoutType) + { + return GUILayoutUtility.DoBeginLayoutArea(style, LayoutType); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorGUIUtility.cs b/UnityEditor/UnityEditor/EditorGUIUtility.cs new file mode 100644 index 00000000..a52a8cf6 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorGUIUtility.cs @@ -0,0 +1,1082 @@ +using System; +using System.Collections; +using System.IO; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEditor +{ + public sealed class EditorGUIUtility : GUIUtility + { + internal static int s_FontIsBold; + private static Texture2D s_InfoIcon; + private static Texture2D s_WarningIcon; + private static Texture2D s_ErrorIcon; + internal static Color kDarkViewBackground; + private static GUIContent s_ObjectContent; + private static GUIContent s_Text; + private static GUIContent s_Image; + private static GUIContent s_TextImage; + private static GUIContent s_BlankContent; + private static GUIStyle s_WhiteTextureStyle; + private static GUIStyle s_BasicTextureStyle; + private static Hashtable s_TextGUIContents; + private static Hashtable s_IconGUIContents; + private static Hashtable s_ScriptInfos; + internal static int s_LastControlID; + private static bool s_HierarchyMode; + internal static bool s_WideMode; + private static float s_ContextWidth; + private static float s_LabelWidth; + private static float s_FieldWidth; + public static FocusType native; + public static float singleLineHeight + { + get + { + return 16f; + } + } + public static float standardVerticalSpacing + { + get + { + return 2f; + } + } + public static bool isProSkin + { + get + { + return EditorGUIUtility.skinIndex == 1; + } + } + internal static extern int skinIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Texture2D whiteTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static Texture2D infoIcon + { + get + { + if (EditorGUIUtility.s_InfoIcon == null) + { + EditorGUIUtility.s_InfoIcon = EditorGUIUtility.LoadIcon("console.infoicon"); + } + return EditorGUIUtility.s_InfoIcon; + } + } + internal static Texture2D warningIcon + { + get + { + if (EditorGUIUtility.s_WarningIcon == null) + { + EditorGUIUtility.s_WarningIcon = EditorGUIUtility.LoadIcon("console.warnicon"); + } + return EditorGUIUtility.s_WarningIcon; + } + } + internal static Texture2D errorIcon + { + get + { + if (EditorGUIUtility.s_ErrorIcon == null) + { + EditorGUIUtility.s_ErrorIcon = EditorGUIUtility.LoadIcon("console.erroricon"); + } + return EditorGUIUtility.s_ErrorIcon; + } + } + internal static GUIContent blankContent + { + get + { + return EditorGUIUtility.s_BlankContent; + } + } + internal static GUIStyle whiteTextureStyle + { + get + { + if (EditorGUIUtility.s_WhiteTextureStyle == null) + { + EditorGUIUtility.s_WhiteTextureStyle = new GUIStyle(); + EditorGUIUtility.s_WhiteTextureStyle.normal.background = EditorGUIUtility.whiteTexture; + } + return EditorGUIUtility.s_WhiteTextureStyle; + } + } + public static bool editingTextField + { + get + { + return EditorGUI.RecycledTextEditor.s_ActuallyEditing; + } + set + { + EditorGUI.RecycledTextEditor.s_ActuallyEditing = value; + } + } + public static bool hierarchyMode + { + get + { + return EditorGUIUtility.s_HierarchyMode; + } + set + { + EditorGUIUtility.s_HierarchyMode = value; + } + } + public static bool wideMode + { + get + { + return EditorGUIUtility.s_WideMode; + } + set + { + EditorGUIUtility.s_WideMode = value; + } + } + internal static float contextWidth + { + get + { + if (EditorGUIUtility.s_ContextWidth > 0f) + { + return EditorGUIUtility.s_ContextWidth; + } + return EditorGUIUtility.CalcContextWidth(); + } + } + public static float currentViewWidth + { + get + { + return GUIView.current.position.width; + } + } + public static float labelWidth + { + get + { + if (EditorGUIUtility.s_LabelWidth > 0f) + { + return EditorGUIUtility.s_LabelWidth; + } + if (EditorGUIUtility.s_HierarchyMode) + { + return Mathf.Max(EditorGUIUtility.contextWidth * 0.45f - 40f, 120f); + } + return 150f; + } + set + { + EditorGUIUtility.s_LabelWidth = value; + } + } + public static float fieldWidth + { + get + { + if (EditorGUIUtility.s_FieldWidth > 0f) + { + return EditorGUIUtility.s_FieldWidth; + } + return 50f; + } + set + { + EditorGUIUtility.s_FieldWidth = value; + } + } + public static extern string systemCopyBuffer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static EventType magnifyGestureEventType + { + get + { + return (EventType)1000; + } + } + internal static EventType swipeGestureEventType + { + get + { + return (EventType)1001; + } + } + internal static EventType rotateGestureEventType + { + get + { + return (EventType)1002; + } + } + static EditorGUIUtility() + { + EditorGUIUtility.s_FontIsBold = -1; + EditorGUIUtility.kDarkViewBackground = new Color(0.22f, 0.22f, 0.22f, 0f); + EditorGUIUtility.s_ObjectContent = new GUIContent(); + EditorGUIUtility.s_Text = new GUIContent(); + EditorGUIUtility.s_Image = new GUIContent(); + EditorGUIUtility.s_TextImage = new GUIContent(); + EditorGUIUtility.s_BlankContent = new GUIContent(" "); + EditorGUIUtility.s_TextGUIContents = new Hashtable(); + EditorGUIUtility.s_IconGUIContents = new Hashtable(); + EditorGUIUtility.s_ScriptInfos = null; + EditorGUIUtility.s_LastControlID = 0; + EditorGUIUtility.s_HierarchyMode = false; + EditorGUIUtility.s_WideMode = false; + EditorGUIUtility.s_ContextWidth = 0f; + EditorGUIUtility.s_LabelWidth = 0f; + EditorGUIUtility.s_FieldWidth = 0f; + EditorGUIUtility.native = FocusType.Keyboard; + GUISkin.m_SkinChanged = (GUISkin.SkinChangedDelegate)Delegate.Combine(GUISkin.m_SkinChanged, new GUISkin.SkinChangedDelegate(EditorGUIUtility.SkinChanged)); + } + internal static GUIContent TextContent(string name) + { + if (name == null) + { + name = string.Empty; + } + GUIContent gUIContent = (GUIContent)EditorGUIUtility.s_TextGUIContents[name]; + if (gUIContent == null) + { + if (EditorGUIUtility.s_ScriptInfos == null) + { + EditorGUIUtility.LoadScriptInfos(); + } + gUIContent = (GUIContent)EditorGUIUtility.s_ScriptInfos[name]; + if (gUIContent == null) + { + gUIContent = new GUIContent(name); + } + gUIContent.image = EditorGUIUtility.LoadIconForSkin(name, EditorGUIUtility.skinIndex); + EditorGUIUtility.s_TextGUIContents[name] = gUIContent; + } + return gUIContent; + } + internal static GUIContent[] GetTextContentsForEnum(Type type) + { + Array values = Enum.GetValues(type); + string[] names = Enum.GetNames(type); + int num = 0; + foreach (int num2 in values) + { + if (num2 < 0) + { + Debug.LogError("Enum may not be smaller than zero"); + GUIContent[] result = null; + return result; + } + if (num2 > 512) + { + Debug.LogError("Largest value in enum may not be larger than 512"); + GUIContent[] result = null; + return result; + } + num = ((num2 <= num) ? num : num2); + } + GUIContent[] array = new GUIContent[num + 1]; + for (int i = 0; i < names.Length; i++) + { + int num3 = (int)values.GetValue(i); + string text = type.Name + "." + names[i]; + array[num3] = EditorGUIUtility.TextContent(text); + if (text == array[num3].text) + { + Debug.LogError("enum name is not found in localization file: " + text); + } + } + return array; + } + public static GUIContent IconContent(string name) + { + GUIContent gUIContent = (GUIContent)EditorGUIUtility.s_IconGUIContents[name]; + if (gUIContent == null) + { + if (EditorGUIUtility.s_ScriptInfos == null) + { + EditorGUIUtility.LoadScriptInfos(); + } + GUIContent gUIContent2 = (GUIContent)EditorGUIUtility.s_ScriptInfos[name]; + gUIContent = new GUIContent(); + if (gUIContent2 != null) + { + gUIContent.tooltip = gUIContent2.tooltip; + } + gUIContent.image = EditorGUIUtility.LoadIconRequired(name); + EditorGUIUtility.s_IconGUIContents[name] = gUIContent; + } + return gUIContent; + } + internal static Texture2D LoadIconRequired(string name) + { + Texture2D texture2D = EditorGUIUtility.LoadIcon(name); + if (!texture2D) + { + Debug.LogError(string.Concat(new string[] + { + "Unable to load '", + EditorResourcesUtility.iconsPath, + name, + "' nor '", + EditorResourcesUtility.generatedIconsPath, + name, + "'" + })); + } + return texture2D; + } + internal static Texture2D LoadIcon(string name) + { + return EditorGUIUtility.LoadIconForSkin(name, EditorGUIUtility.skinIndex); + } + private static Texture2D LoadGeneratedIconOrNormalIcon(string name) + { + Texture2D texture2D = EditorGUIUtility.Load(EditorResourcesUtility.generatedIconsPath + name + ".asset") as Texture2D; + if (!texture2D) + { + texture2D = (EditorGUIUtility.Load(EditorResourcesUtility.iconsPath + name + ".png") as Texture2D); + } + return texture2D; + } + internal static Texture2D LoadIconForSkin(string name, int skinIndex) + { + if (string.IsNullOrEmpty(name)) + { + return null; + } + if (skinIndex == 0) + { + return EditorGUIUtility.LoadGeneratedIconOrNormalIcon(name); + } + string text = "d_" + Path.GetFileName(name); + string directoryName = Path.GetDirectoryName(name); + if (!string.IsNullOrEmpty(directoryName)) + { + text = string.Format("{0}/{1}", directoryName, text); + } + Texture2D texture2D = EditorGUIUtility.LoadGeneratedIconOrNormalIcon(text); + if (!texture2D) + { + texture2D = EditorGUIUtility.LoadGeneratedIconOrNormalIcon(name); + } + return texture2D; + } + public static GUIContent IconContent(string name, string tooltip) + { + GUIContent gUIContent = EditorGUIUtility.IconContent(name); + gUIContent.tooltip = tooltip; + return gUIContent; + } + internal static void Internal_SwitchSkin() + { + EditorGUIUtility.skinIndex = 1 - EditorGUIUtility.skinIndex; + } + public static GUIContent ObjectContent(UnityEngine.Object obj, Type type) + { + if (obj) + { + EditorGUIUtility.s_ObjectContent.text = obj.name; + EditorGUIUtility.s_ObjectContent.image = AssetPreview.GetMiniThumbnail(obj); + } + else + { + string arg; + if (type == null) + { + arg = ""; + } + else + { + if (type.Namespace != null) + { + arg = type.ToString().Substring(type.Namespace.ToString().Length + 1); + } + else + { + arg = type.ToString(); + } + } + EditorGUIUtility.s_ObjectContent.text = string.Format("None ({0})", arg); + EditorGUIUtility.s_ObjectContent.image = AssetPreview.GetMiniTypeThumbnail(type); + } + return EditorGUIUtility.s_ObjectContent; + } + internal static GUIContent TempContent(string t) + { + EditorGUIUtility.s_Text.text = t; + return EditorGUIUtility.s_Text; + } + internal static GUIContent TempContent(Texture i) + { + EditorGUIUtility.s_Image.image = i; + return EditorGUIUtility.s_Image; + } + internal static GUIContent TempContent(string t, Texture i) + { + EditorGUIUtility.s_TextImage.image = i; + EditorGUIUtility.s_TextImage.text = t; + return EditorGUIUtility.s_TextImage; + } + internal static GUIContent[] TempContent(string[] texts) + { + GUIContent[] array = new GUIContent[texts.Length]; + for (int i = 0; i < texts.Length; i++) + { + array[i] = new GUIContent(texts[i]); + } + return array; + } + internal static bool HasHolddownKeyModifiers(Event evt) + { + return evt.shift | evt.control | evt.alt | evt.command; + } + public static bool HasObjectThumbnail(Type objType) + { + return objType != null && (objType.IsSubclassOf(typeof(Texture)) || objType == typeof(Texture)); + } + public static void SetIconSize(Vector2 size) + { + EditorGUIUtility.INTERNAL_CALL_SetIconSize(ref size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetIconSize(ref Vector2 size); + public static Vector2 GetIconSize() + { + Vector2 result; + EditorGUIUtility.Internal_GetIconSize(out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetIconSize(out Vector2 size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern UnityEngine.Object GetScript(string scriptClass); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetIconForObject(UnityEngine.Object obj, Texture2D icon); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D GetIconForObject(UnityEngine.Object obj); + internal static Texture2D GetHelpIcon(MessageType type) + { + switch (type) + { + case MessageType.Info: + return EditorGUIUtility.infoIcon; + case MessageType.Warning: + return EditorGUIUtility.warningIcon; + case MessageType.Error: + return EditorGUIUtility.errorIcon; + default: + return null; + } + } + internal static GUIStyle GetBasicTextureStyle(Texture2D tex) + { + if (EditorGUIUtility.s_BasicTextureStyle == null) + { + EditorGUIUtility.s_BasicTextureStyle = new GUIStyle(); + } + EditorGUIUtility.s_BasicTextureStyle.normal.background = tex; + return EditorGUIUtility.s_BasicTextureStyle; + } + private static void LoadScriptInfos() + { + string text = File.ReadAllText(EditorApplication.applicationContentsPath + "/Resources/UI_Strings_EN.txt"); + EditorGUIUtility.s_ScriptInfos = new Hashtable(); + char[] separator = new char[] + { + ':', + '|' + }; + string[] array = text.Split(new char[] + { + '\n' + }); + for (int i = 0; i < array.Length; i++) + { + string text2 = array[i]; + if (!text2.StartsWith("//")) + { + string[] array2 = text2.Split(separator); + switch (array2.Length) + { + case 0: + case 1: + break; + case 2: + EditorGUIUtility.s_ScriptInfos[array2[0]] = new GUIContent(array2[1].Trim().Replace("\\n", "\n")); + break; + case 3: + EditorGUIUtility.s_ScriptInfos[array2[0]] = new GUIContent(array2[1].Trim().Replace("\\n", "\n"), array2[2].Trim().Replace("\\n", "\n")); + break; + default: + Debug.LogError("Error in Tooltips: Too many strings in line beginning with '" + array2[0] + "'"); + break; + } + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D FindTexture(string name); + public static GUISkin GetBuiltinSkin(EditorSkin skin) + { + return GUIUtility.GetBuiltinSkin((int)skin); + } + public static UnityEngine.Object LoadRequired(string path) + { + UnityEngine.Object @object = EditorGUIUtility.Load(path, typeof(UnityEngine.Object)); + if (!@object) + { + Debug.LogError("Unable to find required resource at 'Editor Default Resources/" + path + "'"); + } + return @object; + } + public static UnityEngine.Object Load(string path) + { + return EditorGUIUtility.Load(path, typeof(UnityEngine.Object)); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + private static UnityEngine.Object Load(string filename, Type type) + { + UnityEngine.Object @object = AssetDatabase.LoadAssetAtPath("Assets/Editor Default Resources/" + filename, type); + if (@object != null) + { + return @object; + } + return EditorGUIUtility.GetEditorAssetBundle().Load(filename, type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern UnityEngine.Object GetBuiltinExtraResource(Type type, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern BuiltinResource[] GetBuiltinResourceList(int classID); + public static void PingObject(UnityEngine.Object obj) + { + if (obj != null) + { + EditorGUIUtility.PingObject(obj.GetInstanceID()); + } + } + public static void PingObject(int targetInstanceID) + { + foreach (SceneHierarchyWindow current in SceneHierarchyWindow.GetAllSceneHierarchyWindows()) + { + bool ping = true; + current.FrameObject(targetInstanceID, ping); + } + foreach (ProjectBrowser current2 in ProjectBrowser.GetAllProjectBrowsers()) + { + bool ping2 = true; + current2.FrameObject(targetInstanceID, ping2); + } + } + internal static void MoveFocusAndScroll(bool forward) + { + int keyboardControl = GUIUtility.keyboardControl; + EditorGUIUtility.Internal_MoveKeyboardFocus(forward); + if (keyboardControl != GUIUtility.keyboardControl) + { + EditorGUIUtility.RefreshScrollPosition(); + } + } + internal static void RefreshScrollPosition() + { + GUI.ScrollViewState topScrollView = GUI.GetTopScrollView(); + Rect position; + if (topScrollView != null && EditorGUIUtility.Internal_GetKeyboardRect(GUIUtility.keyboardControl, out position)) + { + topScrollView.ScrollTo(position); + } + } + internal static void ScrollForTabbing(bool forward) + { + GUI.ScrollViewState topScrollView = GUI.GetTopScrollView(); + Rect position; + if (topScrollView != null && EditorGUIUtility.Internal_GetKeyboardRect(EditorGUIUtility.Internal_GetNextKeyboardControlID(forward), out position)) + { + topScrollView.ScrollTo(position); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_GetKeyboardRect(int id, out Rect rect); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_MoveKeyboardFocus(bool forward); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetNextKeyboardControlID(bool forward); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AssetBundle GetEditorAssetBundle(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetRenderTextureNoViewport(RenderTexture rt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetVisibleLayers(int layers); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetLockedLayers(int layers); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsGizmosAllowedForObject(UnityEngine.Object obj); + internal static void ResetGUIState() + { + GUI.skin = null; + Color white = Color.white; + GUI.contentColor = white; + GUI.backgroundColor = white; + GUI.color = ((!EditorApplication.isPlayingOrWillChangePlaymode) ? Color.white : HostView.kPlayModeDarken); + GUI.enabled = true; + GUI.changed = false; + EditorGUI.indentLevel = 0; + EditorGUI.ClearStacks(); + EditorGUIUtility.fieldWidth = 0f; + EditorGUIUtility.labelWidth = 0f; + EditorGUIUtility.SetBoldDefaultFont(false); + EditorGUIUtility.UnlockContextWidth(); + EditorGUIUtility.hierarchyMode = false; + EditorGUIUtility.wideMode = false; + ScriptAttributeUtility.propertyHandlerCache = null; + } + public static void RenderGameViewCameras(Rect cameraRect, bool gizmos, bool gui) + { + EditorGUIUtility.INTERNAL_CALL_RenderGameViewCameras(ref cameraRect, gizmos, gui); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_RenderGameViewCameras(ref Rect cameraRect, bool gizmos, bool gui); + [Obsolete("Use version without the statsRect (it is not used anymore)")] + public static void RenderGameViewCameras(Rect cameraRect, Rect statsRect, bool gizmos, bool gui) + { + EditorGUIUtility.RenderGameViewCameras(cameraRect, gizmos, gui); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void QueueGameViewInputEvent(Event evt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetDefaultFont(Font font); + private static GUIStyle GetStyle(string styleName) + { + GUIStyle gUIStyle = GUI.skin.FindStyle(styleName); + if (gUIStyle == null) + { + gUIStyle = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle(styleName); + } + if (gUIStyle == null) + { + Debug.Log("Missing built-in guistyle " + styleName); + gUIStyle = GUISkin.error; + } + return gUIStyle; + } + internal static void HandleControlID(int id) + { + EditorGUIUtility.s_LastControlID = id; + if (EditorGUI.s_PrefixLabel.text != null) + { + EditorGUI.HandlePrefixLabel(EditorGUI.s_PrefixTotalRect, EditorGUI.s_PrefixRect, EditorGUI.s_PrefixLabel, EditorGUIUtility.s_LastControlID, EditorGUI.s_PrefixStyle); + } + } + private static float CalcContextWidth() + { + float num = GUIClip.GetTopRect().width; + if (num < 1f || num >= 40000f) + { + num = EditorGUIUtility.currentViewWidth; + } + return num; + } + internal static void LockContextWidth() + { + EditorGUIUtility.s_ContextWidth = EditorGUIUtility.CalcContextWidth(); + } + internal static void UnlockContextWidth() + { + EditorGUIUtility.s_ContextWidth = 0f; + } + [Obsolete("LookLikeControls and LookLikeInspector modes are deprecated. Use EditorGUIUtility.labelWidth and EditorGUIUtility.fieldWidth to control label and field widths."), ExcludeFromDocs] + public static void LookLikeControls(float labelWidth) + { + float fieldWidth = 0f; + EditorGUIUtility.LookLikeControls(labelWidth, fieldWidth); + } + [ExcludeFromDocs] + public static void LookLikeControls() + { + float fieldWidth = 0f; + float labelWidth = 0f; + EditorGUIUtility.LookLikeControls(labelWidth, fieldWidth); + } + public static void LookLikeControls([DefaultValue("0")] float labelWidth, [DefaultValue("0")] float fieldWidth) + { + EditorGUIUtility.fieldWidth = fieldWidth; + EditorGUIUtility.labelWidth = labelWidth; + } + [Obsolete("LookLikeControls and LookLikeInspector modes are deprecated.")] + public static void LookLikeInspector() + { + EditorGUIUtility.fieldWidth = 0f; + EditorGUIUtility.labelWidth = 0f; + } + internal static void SkinChanged() + { + EditorStyles.UpdateSkinCache(); + } + internal static Rect DragZoneRect(Rect position) + { + return new Rect(position.x, position.y, EditorGUIUtility.labelWidth, position.height); + } + internal static void SetBoldDefaultFont(bool isBold) + { + int num = (!isBold) ? 0 : 1; + if (num != EditorGUIUtility.s_FontIsBold) + { + EditorGUIUtility.SetDefaultFont((!isBold) ? EditorStyles.standardFont : EditorStyles.boldFont); + EditorGUIUtility.s_FontIsBold = num; + } + } + internal static bool GetBoldDefaultFont() + { + return EditorGUIUtility.s_FontIsBold == 1; + } + public static Event CommandEvent(string commandName) + { + Event @event = new Event(); + EditorGUIUtility.Internal_SetupEventValues(@event); + @event.type = EventType.ExecuteCommand; + @event.commandName = commandName; + return @event; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetupEventValues(object evt); + public static void DrawColorSwatch(Rect position, Color color) + { + EditorGUIUtility.DrawColorSwatch(position, color, true); + } + internal static void DrawColorSwatch(Rect position, Color color, bool showAlpha) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color2 = GUI.color; + float a = (float)((!GUI.enabled) ? 2 : 1); + GUI.color = ((!EditorGUI.showMixedValue) ? new Color(color.r, color.g, color.b, a) : (new Color(0.82f, 0.82f, 0.82f, a) * color2)); + GUIStyle whiteTextureStyle = EditorGUIUtility.whiteTextureStyle; + whiteTextureStyle.Draw(position, false, false, false, false); + if (!EditorGUI.showMixedValue) + { + if (showAlpha) + { + GUI.color = new Color(0f, 0f, 0f, a); + float num = Mathf.Clamp(position.height * 0.2f, 2f, 20f); + position.yMin = position.yMax - num; + whiteTextureStyle.Draw(position, false, false, false, false); + GUI.color = new Color(1f, 1f, 1f, a); + position.width *= Mathf.Clamp01(color.a); + whiteTextureStyle.Draw(position, false, false, false, false); + } + } + else + { + EditorGUI.BeginHandleMixedValueContentColor(); + whiteTextureStyle.Draw(position, EditorGUI.mixedValueContent, false, false, false, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + GUI.color = color2; + } + public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor) + { + EditorGUIUtility.DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, false, default(Rect)); + } + public static void DrawCurveSwatch(Rect position, AnimationCurve curve, SerializedProperty property, Color color, Color bgColor, Rect curveRanges) + { + EditorGUIUtility.DrawCurveSwatchInternal(position, curve, null, property, null, color, bgColor, true, curveRanges); + } + public static void DrawRegionSwatch(Rect position, SerializedProperty property, SerializedProperty property2, Color color, Color bgColor, Rect curveRanges) + { + EditorGUIUtility.DrawCurveSwatchInternal(position, null, null, property, property2, color, bgColor, true, curveRanges); + } + public static void DrawRegionSwatch(Rect position, AnimationCurve curve, AnimationCurve curve2, Color color, Color bgColor, Rect curveRanges) + { + EditorGUIUtility.DrawCurveSwatchInternal(position, curve, curve2, null, null, color, bgColor, true, curveRanges); + } + private static void DrawCurveSwatchInternal(Rect position, AnimationCurve curve, AnimationCurve curve2, SerializedProperty property, SerializedProperty property2, Color color, Color bgColor, bool useCurveRanges, Rect curveRanges) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + int previewWidth = (int)position.width; + int previewHeight = (int)position.height; + Color color2 = GUI.color; + GUI.color = bgColor; + GUIStyle gUIStyle = EditorGUIUtility.whiteTextureStyle; + gUIStyle.Draw(position, false, false, false, false); + GUI.color = color2; + if (property != null && property.hasMultipleDifferentValues) + { + EditorGUI.BeginHandleMixedValueContentColor(); + GUI.Label(position, EditorGUI.mixedValueContent, "PreOverlayLabel"); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + Texture2D texture2D = null; + if (property != null) + { + if (property2 == null) + { + texture2D = ((!useCurveRanges) ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, color) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, color, curveRanges)); + } + else + { + texture2D = ((!useCurveRanges) ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, property2, color) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, property, property2, color, curveRanges)); + } + } + else + { + if (curve != null) + { + if (curve2 == null) + { + texture2D = ((!useCurveRanges) ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, color) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, color, curveRanges)); + } + else + { + texture2D = ((!useCurveRanges) ? AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, curve2, color) : AnimationCurvePreviewCache.GetPreview(previewWidth, previewHeight, curve, curve2, color, curveRanges)); + } + } + } + gUIStyle = EditorGUIUtility.GetBasicTextureStyle(texture2D); + position.width = (float)texture2D.width; + position.height = (float)texture2D.height; + gUIStyle.Draw(position, false, false, false, false); + } + } + public static void RGBToHSV(Color rgbColor, out float H, out float S, out float V) + { + if (rgbColor.b > rgbColor.g && rgbColor.b > rgbColor.r) + { + EditorGUIUtility.RGBToHSVHelper(4f, rgbColor.b, rgbColor.r, rgbColor.g, out H, out S, out V); + } + else + { + if (rgbColor.g > rgbColor.r) + { + EditorGUIUtility.RGBToHSVHelper(2f, rgbColor.g, rgbColor.b, rgbColor.r, out H, out S, out V); + } + else + { + EditorGUIUtility.RGBToHSVHelper(0f, rgbColor.r, rgbColor.g, rgbColor.b, out H, out S, out V); + } + } + } + private static void RGBToHSVHelper(float offset, float dominantcolor, float colorone, float colortwo, out float H, out float S, out float V) + { + V = dominantcolor; + if (V != 0f) + { + float num; + if (colorone > colortwo) + { + num = colortwo; + } + else + { + num = colorone; + } + float num2 = V - num; + if (num2 != 0f) + { + S = num2 / V; + H = offset + (colorone - colortwo) / num2; + } + else + { + S = 0f; + H = offset + (colorone - colortwo); + } + H /= 6f; + if (H < 0f) + { + H += 1f; + } + } + else + { + S = 0f; + H = 0f; + } + } + public static Color HSVToRGB(float H, float S, float V) + { + Color white = Color.white; + if (S == 0f) + { + white.r = V; + white.g = V; + white.b = V; + } + else + { + if (V == 0f) + { + white.r = 0f; + white.g = 0f; + white.b = 0f; + } + else + { + white.r = 0f; + white.g = 0f; + white.b = 0f; + float num = H * 6f; + int num2 = (int)Mathf.Floor(num); + float num3 = num - (float)num2; + float num4 = V * (1f - S); + float num5 = V * (1f - S * num3); + float num6 = V * (1f - S * (1f - num3)); + int num7 = num2; + switch (num7 + 1) + { + case 0: + white.r = V; + white.g = num4; + white.b = num5; + break; + case 1: + white.r = V; + white.g = num6; + white.b = num4; + break; + case 2: + white.r = num5; + white.g = V; + white.b = num4; + break; + case 3: + white.r = num4; + white.g = V; + white.b = num6; + break; + case 4: + white.r = num4; + white.g = num5; + white.b = V; + break; + case 5: + white.r = num6; + white.g = num4; + white.b = V; + break; + case 6: + white.r = V; + white.g = num4; + white.b = num5; + break; + case 7: + white.r = V; + white.g = num6; + white.b = num4; + break; + } + white.r = Mathf.Clamp(white.r, 0f, 1f); + white.g = Mathf.Clamp(white.g, 0f, 1f); + white.b = Mathf.Clamp(white.b, 0f, 1f); + } + } + return white; + } + public static void AddCursorRect(Rect position, MouseCursor mouse) + { + EditorGUIUtility.AddCursorRect(position, mouse, 0); + } + public static void AddCursorRect(Rect position, MouseCursor mouse, int controlID) + { + if (Event.current.type == EventType.Repaint) + { + Rect rect = GUIClip.Unclip(position); + Rect topmostRect = GUIClip.topmostRect; + Rect r = Rect.MinMaxRect(Mathf.Max(rect.x, topmostRect.x), Mathf.Max(rect.y, topmostRect.y), Mathf.Min(rect.xMax, topmostRect.xMax), Mathf.Min(rect.yMax, topmostRect.yMax)); + if (r.width <= 0f || r.height <= 0f) + { + return; + } + EditorGUIUtility.Internal_AddCursorRect(r, mouse, controlID); + } + } + private static void Internal_AddCursorRect(Rect r, MouseCursor m, int controlID) + { + EditorGUIUtility.INTERNAL_CALL_Internal_AddCursorRect(ref r, m, controlID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_AddCursorRect(ref Rect r, MouseCursor m, int controlID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void CleanCache(string text); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetSearchIndexOfControlIDList(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSearchIndexOfControlIDList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CanHaveKeyboardFocus(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetWantsMouseJumping(int wantz); + public static void ShowObjectPicker(UnityEngine.Object obj, bool allowSceneObjects, string searchFilter, int controlID) where T : UnityEngine.Object + { + Type typeFromHandle = typeof(T); + ObjectSelector.get.Show(obj, typeFromHandle, null, allowSceneObjects); + ObjectSelector.get.objectSelectorID = controlID; + ObjectSelector.get.searchFilter = searchFilter; + } + public static UnityEngine.Object GetObjectPickerObject() + { + return ObjectSelector.GetCurrentObject(); + } + public static int GetObjectPickerControlID() + { + return ObjectSelector.get.objectSelectorID; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorLook.cs b/UnityEditor/UnityEditor/EditorLook.cs new file mode 100644 index 00000000..d511f717 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorLook.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + internal enum EditorLook + { + Uninitialized, + LikeControls, + LikeInspector + } +} diff --git a/UnityEditor/UnityEditor/EditorMaterialUtility.cs b/UnityEditor/UnityEditor/EditorMaterialUtility.cs new file mode 100644 index 00000000..e7f15c39 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorMaterialUtility.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorMaterialUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetDefaultTextures(Material material, bool overrideSetTextures); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetShaderDefaults(Shader shader, string[] name, Texture[] textures); + } +} diff --git a/UnityEditor/UnityEditor/EditorPrefs.cs b/UnityEditor/UnityEditor/EditorPrefs.cs new file mode 100644 index 00000000..ca0cdfb4 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorPrefs.cs @@ -0,0 +1,67 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class EditorPrefs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetInt(string key, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetInt(string key, [DefaultValue("0")] int defaultValue); + [ExcludeFromDocs] + public static int GetInt(string key) + { + int defaultValue = 0; + return EditorPrefs.GetInt(key, defaultValue); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetFloat(string key, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetFloat(string key, [DefaultValue("0.0F")] float defaultValue); + [ExcludeFromDocs] + public static float GetFloat(string key) + { + float defaultValue = 0f; + return EditorPrefs.GetFloat(key, defaultValue); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetString(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetString(string key, [DefaultValue("\"\"")] string defaultValue); + [ExcludeFromDocs] + public static string GetString(string key) + { + string empty = string.Empty; + return EditorPrefs.GetString(key, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetBool(string key, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetBool(string key, [DefaultValue("false")] bool defaultValue); + [ExcludeFromDocs] + public static bool GetBool(string key) + { + bool defaultValue = false; + return EditorPrefs.GetBool(key, defaultValue); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasKey(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteKey(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteAll(); + } +} diff --git a/UnityEditor/UnityEditor/EditorSettings.cs b/UnityEditor/UnityEditor/EditorSettings.cs new file mode 100644 index 00000000..3be1c7d2 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorSettings.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorSettings : UnityEngine.Object + { + public static extern string unityRemoteDevice + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string externalVersionControl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern SerializationMode serializationMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string webSecurityEmulationHostUrl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern EditorBehaviorMode defaultBehaviorMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern SpritePackerMode spritePackerMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorSettingsInspector.cs b/UnityEditor/UnityEditor/EditorSettingsInspector.cs new file mode 100644 index 00000000..9fd47bee --- /dev/null +++ b/UnityEditor/UnityEditor/EditorSettingsInspector.cs @@ -0,0 +1,374 @@ +using System; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(EditorSettings))] + internal class EditorSettingsInspector : Editor + { + private struct PopupElement + { + public readonly bool requiresTeamLicense; + public readonly bool requiresProLicense; + public readonly GUIContent content; + public bool Enabled + { + get + { + return (!this.requiresTeamLicense || InternalEditorUtility.HasMaint()) && (!this.requiresProLicense || InternalEditorUtility.HasPro()); + } + } + public PopupElement(string content, bool requiresTeamLicense, bool requiresProLicense) + { + this.content = new GUIContent(content); + this.requiresTeamLicense = requiresTeamLicense; + this.requiresProLicense = requiresProLicense; + } + } + private EditorSettingsInspector.PopupElement[] vcDefaultPopupList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement(ExternalVersionControl.Disabled, false, false), + new EditorSettingsInspector.PopupElement(ExternalVersionControl.Generic, false, false), + new EditorSettingsInspector.PopupElement(ExternalVersionControl.AssetServer, true, false) + }; + private EditorSettingsInspector.PopupElement[] vcPopupList; + private EditorSettingsInspector.PopupElement[] serializationPopupList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("Mixed", false, false), + new EditorSettingsInspector.PopupElement("Force Binary", false, false), + new EditorSettingsInspector.PopupElement("Force Text", false, false) + }; + private EditorSettingsInspector.PopupElement[] remoteDeviceList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("None", false, false), + new EditorSettingsInspector.PopupElement("Any Android Device", false, false), + new EditorSettingsInspector.PopupElement("Any iOS Device", false, false) + }; + private EditorSettingsInspector.PopupElement[] behaviorPopupList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("3D", false, false), + new EditorSettingsInspector.PopupElement("2D", false, false) + }; + private EditorSettingsInspector.PopupElement[] spritePackerPopupList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("Disabled", false, false), + new EditorSettingsInspector.PopupElement("Enabled For Builds", false, false), + new EditorSettingsInspector.PopupElement("Always Enabled", false, false) + }; + private string[] logLevelPopupList = new string[] + { + "Verbose", + "Info", + "Notice", + "Fatal" + }; + public void OnEnable() + { + Plugin[] availablePlugins = Plugin.availablePlugins; + this.vcPopupList = new EditorSettingsInspector.PopupElement[availablePlugins.Length + this.vcDefaultPopupList.Length]; + Array.Copy(this.vcDefaultPopupList, this.vcPopupList, this.vcDefaultPopupList.Length); + int num = 0; + int i = this.vcDefaultPopupList.Length; + while (i < this.vcPopupList.Length) + { + this.vcPopupList[i] = new EditorSettingsInspector.PopupElement(availablePlugins[num].name, true, false); + i++; + num++; + } + } + public override void OnInspectorGUI() + { + bool enabled = GUI.enabled; + this.ShowUnityRemoteGUI(enabled); + GUILayout.Space(10f); + GUI.enabled = true; + GUILayout.Label("Version Control", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.enabled = enabled; + ExternalVersionControl selvc = EditorSettings.externalVersionControl; + int num = Array.FindIndex(this.vcPopupList, (EditorSettingsInspector.PopupElement cand) => cand.content.text == selvc); + if (num < 0) + { + num = 0; + } + GUIContent content = new GUIContent(this.vcPopupList[num].content); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Mode")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.vcPopupList, num, new GenericMenu.MenuFunction2(this.SetVersionControlSystem)); + } + if (this.VersionControlSystemHasGUI()) + { + GUI.enabled = true; + bool enabled2 = false; + if (EditorSettings.externalVersionControl == ExternalVersionControl.AssetServer) + { + EditorUserSettings.SetConfigValue("vcUsername", EditorGUILayout.TextField("User", EditorUserSettings.GetConfigValue("vcUsername"), new GUILayoutOption[0])); + EditorUserSettings.SetConfigValue("vcPassword", EditorGUILayout.PasswordField("Password", EditorUserSettings.GetConfigValue("vcPassword"), new GUILayoutOption[0])); + } + else + { + if (!(EditorSettings.externalVersionControl == ExternalVersionControl.Generic)) + { + if (!(EditorSettings.externalVersionControl == ExternalVersionControl.Disabled)) + { + ConfigField[] activeConfigFields = Provider.GetActiveConfigFields(); + enabled2 = true; + ConfigField[] array = activeConfigFields; + for (int i = 0; i < array.Length; i++) + { + ConfigField configField = array[i]; + string configValue = EditorUserSettings.GetConfigValue(configField.name); + string text; + if (configField.isPassword) + { + text = EditorGUILayout.PasswordField(configField.label, configValue, new GUILayoutOption[0]); + } + else + { + text = EditorGUILayout.TextField(configField.label, configValue, new GUILayoutOption[0]); + } + if (text != configValue) + { + EditorUserSettings.SetConfigValue(configField.name, text); + } + if (configField.isRequired && string.IsNullOrEmpty(text)) + { + enabled2 = false; + } + } + } + } + } + string logLevel = EditorUserSettings.GetConfigValue("vcSharedLogLevel"); + int num2 = Array.FindIndex(this.logLevelPopupList, (string item) => item.ToLower() == logLevel); + if (num2 == -1) + { + logLevel = "info"; + } + int num3 = EditorGUILayout.Popup("Log Level", Math.Abs(num2), this.logLevelPopupList, new GUILayoutOption[0]); + if (num3 != num2) + { + EditorUserSettings.SetConfigValue("vcSharedLogLevel", this.logLevelPopupList[num3].ToLower()); + } + GUI.enabled = enabled; + string label = "Connected"; + if (Provider.onlineState == OnlineState.Updating) + { + label = "Connecting..."; + } + else + { + if (Provider.onlineState == OnlineState.Offline) + { + label = "Disconnected"; + } + } + EditorGUILayout.LabelField("Status", label, new GUILayoutOption[0]); + if (Provider.onlineState != OnlineState.Online && !string.IsNullOrEmpty(Provider.offlineReason)) + { + GUI.enabled = false; + GUILayout.TextArea(Provider.offlineReason, new GUILayoutOption[0]); + GUI.enabled = enabled; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = enabled2; + if (GUILayout.Button("Connect", EditorStyles.miniButton, new GUILayoutOption[0])) + { + Provider.UpdateSettings(); + } + GUILayout.EndHorizontal(); + EditorUserSettings.AutomaticAdd = EditorGUILayout.Toggle("Automatic add", EditorUserSettings.AutomaticAdd, new GUILayoutOption[0]); + if (Provider.requiresNetwork) + { + bool flag = EditorGUILayout.Toggle("Work Offline", EditorUserSettings.WorkOffline, new GUILayoutOption[0]); + if (flag != EditorUserSettings.WorkOffline) + { + if (flag && !EditorUtility.DisplayDialog("Confirm working offline", "Working offline and making changes to your assets means that you will have to manually integrate changes back into version control using your standard version control client before you stop working offline in Unity. Make sure you know what you are doing.", "Work offline", "Cancel")) + { + flag = false; + } + EditorUserSettings.WorkOffline = flag; + EditorApplication.RequestRepaintAllViews(); + } + } + GUI.enabled = enabled; + this.DrawOverlayDescriptions(); + } + GUILayout.Space(10f); + GUILayout.Label("WWW Security Emulation", EditorStyles.boldLabel, new GUILayoutOption[0]); + string text2 = EditorGUILayout.TextField("Host URL", EditorSettings.webSecurityEmulationHostUrl, new GUILayoutOption[0]); + if (text2 != EditorSettings.webSecurityEmulationHostUrl) + { + EditorSettings.webSecurityEmulationHostUrl = text2; + } + GUILayout.Space(10f); + GUI.enabled = true; + GUILayout.Label("Asset Serialization", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.enabled = enabled; + content = new GUIContent(this.serializationPopupList[(int)EditorSettings.serializationMode].content); + rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Mode")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.serializationPopupList, (int)EditorSettings.serializationMode, new GenericMenu.MenuFunction2(this.SetAssetSerializationMode)); + } + GUILayout.Space(10f); + GUI.enabled = true; + GUILayout.Label("Default Behavior Mode", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.enabled = enabled; + int num4 = Mathf.Clamp((int)EditorSettings.defaultBehaviorMode, 0, this.behaviorPopupList.Length - 1); + content = new GUIContent(this.behaviorPopupList[num4].content); + rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Mode")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.behaviorPopupList, num4, new GenericMenu.MenuFunction2(this.SetDefaultBehaviorMode)); + } + GUILayout.Space(10f); + GUI.enabled = true; + GUILayout.Label("Sprite Packer", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.enabled = enabled; + num4 = Mathf.Clamp((int)EditorSettings.spritePackerMode, 0, this.spritePackerPopupList.Length - 1); + content = new GUIContent(this.spritePackerPopupList[num4].content); + rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Mode")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.spritePackerPopupList, num4, new GenericMenu.MenuFunction2(this.SetSpritePackerMode)); + } + } + private void ShowUnityRemoteGUI(bool editorEnabled) + { + GUI.enabled = true; + GUILayout.Label("Unity Remote", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.enabled = editorEnabled; + string unityRemoteDevice = EditorSettings.unityRemoteDevice; + int num = 0; + for (int i = 0; i < this.remoteDeviceList.Length; i++) + { + if (this.remoteDeviceList[i].content.text == unityRemoteDevice) + { + num = i; + } + } + GUIContent content = new GUIContent(this.remoteDeviceList[num].content); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Device")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.remoteDeviceList, num, new GenericMenu.MenuFunction2(this.SetUnityRemoteDevice)); + } + } + private void DrawOverlayDescriptions() + { + Texture2D overlayAtlas = Provider.overlayAtlas; + if (overlayAtlas == null) + { + return; + } + GUILayout.Space(10f); + GUILayout.Label("Overlay legends", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.DrawOverlayDescription(Asset.States.Local); + this.DrawOverlayDescription(Asset.States.OutOfSync); + this.DrawOverlayDescription(Asset.States.CheckedOutLocal); + this.DrawOverlayDescription(Asset.States.CheckedOutRemote); + this.DrawOverlayDescription(Asset.States.DeletedLocal); + this.DrawOverlayDescription(Asset.States.DeletedRemote); + this.DrawOverlayDescription(Asset.States.AddedLocal); + this.DrawOverlayDescription(Asset.States.AddedRemote); + this.DrawOverlayDescription(Asset.States.Conflicted); + this.DrawOverlayDescription(Asset.States.LockedLocal); + this.DrawOverlayDescription(Asset.States.LockedRemote); + } + private void DrawOverlayDescription(Asset.States state) + { + Rect atlasRectForState = Provider.GetAtlasRectForState((int)state); + if (atlasRectForState.width == 0f) + { + return; + } + Texture2D overlayAtlas = Provider.overlayAtlas; + if (overlayAtlas == null) + { + return; + } + GUILayout.Label(" " + Asset.StateToString(state), EditorStyles.miniLabel, new GUILayoutOption[0]); + Rect lastRect = GUILayoutUtility.GetLastRect(); + lastRect.width = 16f; + GUI.DrawTextureWithTexCoords(lastRect, overlayAtlas, atlasRectForState); + } + private void DoPopup(Rect popupRect, EditorSettingsInspector.PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func) + { + GenericMenu genericMenu = new GenericMenu(); + for (int i = 0; i < elements.Length; i++) + { + EditorSettingsInspector.PopupElement popupElement = elements[i]; + if (popupElement.Enabled) + { + genericMenu.AddItem(popupElement.content, i == selectedIndex, func, i); + } + else + { + genericMenu.AddDisabledItem(popupElement.content); + } + } + genericMenu.DropDown(popupRect); + } + private bool VersionControlSystemHasGUI() + { + ExternalVersionControl d = EditorSettings.externalVersionControl; + return d != ExternalVersionControl.Disabled && d != ExternalVersionControl.AutoDetect && d != ExternalVersionControl.AssetServer && d != ExternalVersionControl.Generic; + } + private void SetVersionControlSystem(object data) + { + int num = (int)data; + if (num < 0 && num >= this.vcPopupList.Length) + { + return; + } + EditorSettingsInspector.PopupElement popupElement = this.vcPopupList[num]; + string externalVersionControl = EditorSettings.externalVersionControl; + EditorSettings.externalVersionControl = popupElement.content.text; + Provider.UpdateSettings(); + AssetDatabase.Refresh(); + if (externalVersionControl != popupElement.content.text) + { + if (popupElement.content.text == ExternalVersionControl.AssetServer || popupElement.content.text == ExternalVersionControl.Disabled || popupElement.content.text == ExternalVersionControl.Generic) + { + WindowPending.CloseAllWindows(); + } + else + { + ASMainWindow[] array = Resources.FindObjectsOfTypeAll(typeof(ASMainWindow)) as ASMainWindow[]; + ASMainWindow aSMainWindow = (array.Length <= 0) ? null : array[0]; + if (aSMainWindow != null) + { + aSMainWindow.Close(); + } + } + } + } + private void SetAssetSerializationMode(object data) + { + int serializationMode = (int)data; + EditorSettings.serializationMode = (SerializationMode)serializationMode; + } + private void SetUnityRemoteDevice(object data) + { + EditorSettings.unityRemoteDevice = this.remoteDeviceList[(int)data].content.text; + } + private void SetDefaultBehaviorMode(object data) + { + int defaultBehaviorMode = (int)data; + EditorSettings.defaultBehaviorMode = (EditorBehaviorMode)defaultBehaviorMode; + } + private void SetSpritePackerMode(object data) + { + int spritePackerMode = (int)data; + EditorSettings.spritePackerMode = (SpritePackerMode)spritePackerMode; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorSkin.cs b/UnityEditor/UnityEditor/EditorSkin.cs new file mode 100644 index 00000000..b167e2f3 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorSkin.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum EditorSkin + { + Game, + Inspector, + Scene + } +} diff --git a/UnityEditor/UnityEditor/EditorStyles.cs b/UnityEditor/UnityEditor/EditorStyles.cs new file mode 100644 index 00000000..fa4e4e70 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorStyles.cs @@ -0,0 +1,631 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorStyles + { + internal GUIStyle m_Label; + private GUIStyle m_MiniLabel; + private GUIStyle m_LargeLabel; + private GUIStyle m_BoldLabel; + private GUIStyle m_MiniBoldLabel; + private GUIStyle m_WordWrappedLabel; + private GUIStyle m_WordWrappedMiniLabel; + private GUIStyle m_WhiteLabel; + private GUIStyle m_WhiteMiniLabel; + private GUIStyle m_WhiteLargeLabel; + private GUIStyle m_WhiteBoldLabel; + private GUIStyle m_RadioButton; + private GUIStyle m_MiniButton; + private GUIStyle m_MiniButtonLeft; + private GUIStyle m_MiniButtonMid; + private GUIStyle m_MiniButtonRight; + internal GUIStyle m_TextField; + internal GUIStyle m_TextArea; + private GUIStyle m_MiniTextField; + private GUIStyle m_NumberField; + private GUIStyle m_Popup; + private GUIStyle m_ObjectField; + private GUIStyle m_ObjectFieldThumb; + private GUIStyle m_ColorField; + private GUIStyle m_LayerMaskField; + private GUIStyle m_Toggle; + private GUIStyle m_ToggleMixed; + private GUIStyle m_Foldout; + private GUIStyle m_FoldoutPreDrop; + private GUIStyle m_ToggleGroup; + internal Font m_StandardFont; + internal Font m_BoldFont; + internal Font m_MiniFont; + internal Font m_MiniBoldFont; + private GUIStyle m_Toolbar; + private GUIStyle m_ToolbarButton; + private GUIStyle m_ToolbarPopup; + private GUIStyle m_ToolbarDropDown; + private GUIStyle m_ToolbarTextField; + private GUIStyle m_InspectorDefaultMargins; + private GUIStyle m_InspectorFullWidthMargins; + private GUIStyle m_ToolbarSearchField; + private GUIStyle m_ToolbarSearchFieldPopup; + private GUIStyle m_ToolbarSearchFieldCancelButton; + private GUIStyle m_ToolbarSearchFieldCancelButtonEmpty; + private GUIStyle m_ColorPickerBox; + private GUIStyle m_InspectorBig; + private GUIStyle m_InspectorTitlebar; + private GUIStyle m_InspectorTitlebarText; + private GUIStyle m_FoldoutSelected; + private GUIStyle m_NotificationText; + private GUIStyle m_NotificationBackground; + private GUIStyle m_HelpBox; + private GUIStyle m_AssetLabel; + private GUIStyle m_AssetLabelPartial; + private GUIStyle m_AssetLabelIcon; + private GUIStyle m_SearchField; + private GUIStyle m_SearchFieldCancelButton; + private GUIStyle m_SearchFieldCancelButtonEmpty; + private GUIStyle m_SelectionRect; + private GUIStyle m_MinMaxHorizontalSliderThumb; + private GUIStyle m_ProgressBarBar; + private GUIStyle m_ProgressBarText; + private GUIStyle m_ProgressBarBack; + internal static EditorStyles s_Current; + private static EditorStyles[] s_CachedStyles = new EditorStyles[2]; + public static GUIStyle label + { + get + { + return EditorStyles.s_Current.m_Label; + } + } + public static GUIStyle miniLabel + { + get + { + return EditorStyles.s_Current.m_MiniLabel; + } + } + public static GUIStyle largeLabel + { + get + { + return EditorStyles.s_Current.m_LargeLabel; + } + } + public static GUIStyle boldLabel + { + get + { + return EditorStyles.s_Current.m_BoldLabel; + } + } + public static GUIStyle miniBoldLabel + { + get + { + return EditorStyles.s_Current.m_MiniBoldLabel; + } + } + public static GUIStyle wordWrappedLabel + { + get + { + return EditorStyles.s_Current.m_WordWrappedLabel; + } + } + public static GUIStyle wordWrappedMiniLabel + { + get + { + return EditorStyles.s_Current.m_WordWrappedMiniLabel; + } + } + public static GUIStyle whiteLabel + { + get + { + return EditorStyles.s_Current.m_WhiteLabel; + } + } + public static GUIStyle whiteMiniLabel + { + get + { + return EditorStyles.s_Current.m_WhiteMiniLabel; + } + } + public static GUIStyle whiteLargeLabel + { + get + { + return EditorStyles.s_Current.m_WhiteLargeLabel; + } + } + public static GUIStyle whiteBoldLabel + { + get + { + return EditorStyles.s_Current.m_WhiteBoldLabel; + } + } + public static GUIStyle radioButton + { + get + { + return EditorStyles.s_Current.m_RadioButton; + } + } + public static GUIStyle miniButton + { + get + { + return EditorStyles.s_Current.m_MiniButton; + } + } + public static GUIStyle miniButtonLeft + { + get + { + return EditorStyles.s_Current.m_MiniButtonLeft; + } + } + public static GUIStyle miniButtonMid + { + get + { + return EditorStyles.s_Current.m_MiniButtonMid; + } + } + public static GUIStyle miniButtonRight + { + get + { + return EditorStyles.s_Current.m_MiniButtonRight; + } + } + public static GUIStyle textField + { + get + { + return EditorStyles.s_Current.m_TextField; + } + } + public static GUIStyle textArea + { + get + { + return EditorStyles.s_Current.m_TextArea; + } + } + public static GUIStyle miniTextField + { + get + { + return EditorStyles.s_Current.m_MiniTextField; + } + } + public static GUIStyle numberField + { + get + { + return EditorStyles.s_Current.m_NumberField; + } + } + public static GUIStyle popup + { + get + { + return EditorStyles.s_Current.m_Popup; + } + } + [Obsolete("structHeadingLabel is deprecated, use EditorStyles.label instead.")] + public static GUIStyle structHeadingLabel + { + get + { + return EditorStyles.s_Current.m_Label; + } + } + public static GUIStyle objectField + { + get + { + return EditorStyles.s_Current.m_ObjectField; + } + } + public static GUIStyle objectFieldThumb + { + get + { + return EditorStyles.s_Current.m_ObjectFieldThumb; + } + } + public static GUIStyle colorField + { + get + { + return EditorStyles.s_Current.m_ColorField; + } + } + public static GUIStyle layerMaskField + { + get + { + return EditorStyles.s_Current.m_LayerMaskField; + } + } + public static GUIStyle toggle + { + get + { + return EditorStyles.s_Current.m_Toggle; + } + } + internal static GUIStyle toggleMixed + { + get + { + return EditorStyles.s_Current.m_ToggleMixed; + } + } + public static GUIStyle foldout + { + get + { + return EditorStyles.s_Current.m_Foldout; + } + } + public static GUIStyle foldoutPreDrop + { + get + { + return EditorStyles.s_Current.m_FoldoutPreDrop; + } + } + public static GUIStyle toggleGroup + { + get + { + return EditorStyles.s_Current.m_ToggleGroup; + } + } + public static Font standardFont + { + get + { + return EditorStyles.s_Current.m_StandardFont; + } + } + public static Font boldFont + { + get + { + return EditorStyles.s_Current.m_BoldFont; + } + } + public static Font miniFont + { + get + { + return EditorStyles.s_Current.m_MiniFont; + } + } + public static Font miniBoldFont + { + get + { + return EditorStyles.s_Current.m_MiniBoldFont; + } + } + public static GUIStyle toolbar + { + get + { + return EditorStyles.s_Current.m_Toolbar; + } + } + public static GUIStyle toolbarButton + { + get + { + return EditorStyles.s_Current.m_ToolbarButton; + } + } + public static GUIStyle toolbarPopup + { + get + { + return EditorStyles.s_Current.m_ToolbarPopup; + } + } + public static GUIStyle toolbarDropDown + { + get + { + return EditorStyles.s_Current.m_ToolbarDropDown; + } + } + public static GUIStyle toolbarTextField + { + get + { + return EditorStyles.s_Current.m_ToolbarTextField; + } + } + public static GUIStyle inspectorDefaultMargins + { + get + { + return EditorStyles.s_Current.m_InspectorDefaultMargins; + } + } + public static GUIStyle inspectorFullWidthMargins + { + get + { + return EditorStyles.s_Current.m_InspectorFullWidthMargins; + } + } + internal static GUIStyle toolbarSearchField + { + get + { + return EditorStyles.s_Current.m_ToolbarSearchField; + } + } + internal static GUIStyle toolbarSearchFieldPopup + { + get + { + return EditorStyles.s_Current.m_ToolbarSearchFieldPopup; + } + } + internal static GUIStyle toolbarSearchFieldCancelButton + { + get + { + return EditorStyles.s_Current.m_ToolbarSearchFieldCancelButton; + } + } + internal static GUIStyle toolbarSearchFieldCancelButtonEmpty + { + get + { + return EditorStyles.s_Current.m_ToolbarSearchFieldCancelButtonEmpty; + } + } + internal static GUIStyle colorPickerBox + { + get + { + return EditorStyles.s_Current.m_ColorPickerBox; + } + } + internal static GUIStyle inspectorBig + { + get + { + return EditorStyles.s_Current.m_InspectorBig; + } + } + internal static GUIStyle inspectorTitlebar + { + get + { + return EditorStyles.s_Current.m_InspectorTitlebar; + } + } + internal static GUIStyle inspectorTitlebarText + { + get + { + return EditorStyles.s_Current.m_InspectorTitlebarText; + } + } + internal static GUIStyle foldoutSelected + { + get + { + return EditorStyles.s_Current.m_FoldoutSelected; + } + } + internal static GUIStyle notificationText + { + get + { + return EditorStyles.s_Current.m_NotificationText; + } + } + internal static GUIStyle notificationBackground + { + get + { + return EditorStyles.s_Current.m_NotificationBackground; + } + } + internal static GUIStyle helpBox + { + get + { + return EditorStyles.s_Current.m_HelpBox; + } + } + internal static GUIStyle assetLabel + { + get + { + return EditorStyles.s_Current.m_AssetLabel; + } + } + internal static GUIStyle assetLabelPartial + { + get + { + return EditorStyles.s_Current.m_AssetLabelPartial; + } + } + internal static GUIStyle assetLabelIcon + { + get + { + return EditorStyles.s_Current.m_AssetLabelIcon; + } + } + internal static GUIStyle searchField + { + get + { + return EditorStyles.s_Current.m_SearchField; + } + } + internal static GUIStyle searchFieldCancelButton + { + get + { + return EditorStyles.s_Current.m_SearchFieldCancelButton; + } + } + internal static GUIStyle searchFieldCancelButtonEmpty + { + get + { + return EditorStyles.s_Current.m_SearchFieldCancelButtonEmpty; + } + } + internal static GUIStyle selectionRect + { + get + { + return EditorStyles.s_Current.m_SelectionRect; + } + } + internal static GUIStyle minMaxHorizontalSliderThumb + { + get + { + return EditorStyles.s_Current.m_MinMaxHorizontalSliderThumb; + } + } + internal static GUIStyle progressBarBack + { + get + { + return EditorStyles.s_Current.m_ProgressBarBack; + } + } + internal static GUIStyle progressBarBar + { + get + { + return EditorStyles.s_Current.m_ProgressBarBar; + } + } + internal static GUIStyle progressBarText + { + get + { + return EditorStyles.s_Current.m_ProgressBarText; + } + } + internal static void UpdateSkinCache() + { + EditorStyles.UpdateSkinCache(EditorGUIUtility.skinIndex); + } + internal static void UpdateSkinCache(int skinIndex) + { + if (GUIUtility.s_SkinMode == 0) + { + return; + } + if (EditorStyles.s_CachedStyles[skinIndex] == null) + { + EditorStyles.s_CachedStyles[skinIndex] = new EditorStyles(); + EditorStyles.s_CachedStyles[skinIndex].InitSharedStyles(); + } + EditorStyles.s_Current = EditorStyles.s_CachedStyles[skinIndex]; + EditorGUIUtility.s_FontIsBold = -1; + EditorGUIUtility.SetBoldDefaultFont(false); + } + private void InitSharedStyles() + { + this.m_ColorPickerBox = this.GetStyle("ColorPickerBox"); + this.m_InspectorBig = this.GetStyle("In BigTitle"); + this.m_MiniLabel = this.GetStyle("miniLabel"); + this.m_LargeLabel = this.GetStyle("LargeLabel"); + this.m_BoldLabel = this.GetStyle("BoldLabel"); + this.m_MiniBoldLabel = this.GetStyle("MiniBoldLabel"); + this.m_WordWrappedLabel = this.GetStyle("WordWrappedLabel"); + this.m_WordWrappedMiniLabel = this.GetStyle("WordWrappedMiniLabel"); + this.m_WhiteLabel = this.GetStyle("WhiteLabel"); + this.m_WhiteMiniLabel = this.GetStyle("WhiteMiniLabel"); + this.m_WhiteLargeLabel = this.GetStyle("WhiteLargeLabel"); + this.m_WhiteBoldLabel = this.GetStyle("WhiteBoldLabel"); + this.m_MiniTextField = this.GetStyle("MiniTextField"); + this.m_RadioButton = this.GetStyle("Radio"); + this.m_MiniButton = this.GetStyle("miniButton"); + this.m_MiniButtonLeft = this.GetStyle("miniButtonLeft"); + this.m_MiniButtonMid = this.GetStyle("miniButtonMid"); + this.m_MiniButtonRight = this.GetStyle("miniButtonRight"); + this.m_Toolbar = this.GetStyle("toolbar"); + this.m_ToolbarButton = this.GetStyle("toolbarbutton"); + this.m_ToolbarPopup = this.GetStyle("toolbarPopup"); + this.m_ToolbarDropDown = this.GetStyle("toolbarDropDown"); + this.m_ToolbarTextField = this.GetStyle("toolbarTextField"); + this.m_ToolbarSearchField = this.GetStyle("ToolbarSeachTextField"); + this.m_ToolbarSearchFieldPopup = this.GetStyle("ToolbarSeachTextFieldPopup"); + this.m_ToolbarSearchFieldCancelButton = this.GetStyle("ToolbarSeachCancelButton"); + this.m_ToolbarSearchFieldCancelButtonEmpty = this.GetStyle("ToolbarSeachCancelButtonEmpty"); + this.m_SearchField = this.GetStyle("SearchTextField"); + this.m_SearchFieldCancelButton = this.GetStyle("SearchCancelButton"); + this.m_SearchFieldCancelButtonEmpty = this.GetStyle("SearchCancelButtonEmpty"); + this.m_HelpBox = this.GetStyle("HelpBox"); + this.m_AssetLabel = this.GetStyle("AssetLabel"); + this.m_AssetLabelPartial = this.GetStyle("AssetLabel Partial"); + this.m_AssetLabelIcon = this.GetStyle("AssetLabel Icon"); + this.m_SelectionRect = this.GetStyle("selectionRect"); + this.m_MinMaxHorizontalSliderThumb = this.GetStyle("MinMaxHorizontalSliderThumb"); + this.m_BoldFont = this.GetStyle("BoldLabel").font; + this.m_StandardFont = this.GetStyle("Label").font; + this.m_MiniFont = this.GetStyle("MiniLabel").font; + this.m_MiniBoldFont = this.GetStyle("MiniBoldLabel").font; + this.m_ProgressBarBack = this.GetStyle("ProgressBarBack"); + this.m_ProgressBarBar = this.GetStyle("ProgressBarBar"); + this.m_ProgressBarText = this.GetStyle("ProgressBarText"); + this.m_FoldoutPreDrop = this.GetStyle("FoldoutPreDrop"); + this.m_InspectorTitlebar = this.GetStyle("IN Title"); + this.m_InspectorTitlebarText = this.GetStyle("IN TitleText"); + this.m_ToggleGroup = this.GetStyle("BoldToggle"); + this.m_NotificationText = this.GetStyle("NotificationText"); + this.m_NotificationBackground = this.GetStyle("NotificationBackground"); + this.m_Popup = (this.m_LayerMaskField = this.GetStyle("MiniPopup")); + this.m_TextField = (this.m_NumberField = this.GetStyle("textField")); + this.m_Label = this.GetStyle("ControlLabel"); + this.m_ObjectField = this.GetStyle("ObjectField"); + this.m_ObjectFieldThumb = this.GetStyle("ObjectFieldThumb"); + this.m_Toggle = this.GetStyle("Toggle"); + this.m_ToggleMixed = this.GetStyle("ToggleMixed"); + this.m_ColorField = this.GetStyle("ColorField"); + this.m_Foldout = this.GetStyle("Foldout"); + this.m_FoldoutSelected = GUIStyle.none; + this.m_TextArea = new GUIStyle(this.m_TextField); + this.m_TextArea.wordWrap = true; + this.m_InspectorDefaultMargins = new GUIStyle(); + this.m_InspectorDefaultMargins.padding = new RectOffset(14, 4, 0, 0); + this.m_InspectorFullWidthMargins = new GUIStyle(); + this.m_InspectorFullWidthMargins.padding = new RectOffset(5, 4, 0, 0); + } + private GUIStyle GetStyle(string styleName) + { + GUIStyle gUIStyle = GUI.skin.FindStyle(styleName); + if (gUIStyle == null) + { + gUIStyle = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle(styleName); + } + if (gUIStyle == null) + { + Debug.LogError("Missing built-in guistyle " + styleName); + gUIStyle = GUISkin.error; + } + return gUIStyle; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorUpdateWindow.cs b/UnityEditor/UnityEditor/EditorUpdateWindow.cs new file mode 100644 index 00000000..5bb44a4e --- /dev/null +++ b/UnityEditor/UnityEditor/EditorUpdateWindow.cs @@ -0,0 +1,136 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class EditorUpdateWindow : EditorWindow + { + private static GUIContent s_UnityLogo; + private static GUIContent s_Title; + private static GUIContent s_TextHasUpdate; + private static GUIContent s_TextUpToDate; + private static GUIContent s_CheckForNewUpdatesText; + private static string s_ErrorString; + private static string s_LatestVersionString; + private static string s_LatestVersionMessage; + private static string s_UpdateURL; + private static bool s_HasUpdate; + private static bool s_HasConnectionError; + private static bool s_ShowAtStartup; + private Vector2 m_ScrollPos; + private static void ShowEditorErrorWindow(string errorString) + { + EditorUpdateWindow.LoadResources(); + EditorUpdateWindow.s_ErrorString = errorString; + EditorUpdateWindow.s_HasConnectionError = true; + EditorUpdateWindow.s_HasUpdate = false; + EditorUpdateWindow.ShowWindow(); + } + private static void ShowEditorUpdateWindow(string latestVersionString, string latestVersionMessage, string updateURL) + { + EditorUpdateWindow.LoadResources(); + EditorUpdateWindow.s_LatestVersionString = latestVersionString; + EditorUpdateWindow.s_LatestVersionMessage = latestVersionMessage; + EditorUpdateWindow.s_UpdateURL = updateURL; + EditorUpdateWindow.s_HasConnectionError = false; + EditorUpdateWindow.s_HasUpdate = (updateURL.Length > 0); + EditorUpdateWindow.ShowWindow(); + } + private static void ShowWindow() + { + EditorWindow.GetWindowWithRect(typeof(EditorUpdateWindow), new Rect(100f, 100f, 570f, 400f), true, EditorUpdateWindow.s_Title.text); + } + private static void LoadResources() + { + if (EditorUpdateWindow.s_UnityLogo != null) + { + return; + } + EditorUpdateWindow.s_ShowAtStartup = EditorPrefs.GetBool("EditorUpdateShowAtStartup", true); + EditorUpdateWindow.s_Title = EditorGUIUtility.TextContent("EditorUpdateWindow.Title"); + EditorUpdateWindow.s_UnityLogo = EditorGUIUtility.IconContent("UnityLogo"); + EditorUpdateWindow.s_TextHasUpdate = EditorGUIUtility.TextContent("EditorUpdateWindow.TextHasUpdate"); + EditorUpdateWindow.s_TextUpToDate = EditorGUIUtility.TextContent("EditorUpdateWindow.TextUpToDate"); + EditorUpdateWindow.s_CheckForNewUpdatesText = EditorGUIUtility.TextContent("EditorUpdateWindow.CheckForNewUpdatesText"); + } + public void OnGUI() + { + EditorUpdateWindow.LoadResources(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUI.Box(new Rect(13f, 8f, (float)EditorUpdateWindow.s_UnityLogo.image.width, (float)EditorUpdateWindow.s_UnityLogo.image.height), EditorUpdateWindow.s_UnityLogo, GUIStyle.none); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(120f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (EditorUpdateWindow.s_HasConnectionError) + { + GUILayout.Label(EditorUpdateWindow.s_ErrorString, "WordWrappedLabel", new GUILayoutOption[] + { + GUILayout.Width(405f) + }); + } + else + { + if (EditorUpdateWindow.s_HasUpdate) + { + GUILayout.Label(string.Format(EditorUpdateWindow.s_TextHasUpdate.text, InternalEditorUtility.GetFullUnityVersion(), EditorUpdateWindow.s_LatestVersionString), "WordWrappedLabel", new GUILayoutOption[] + { + GUILayout.Width(300f) + }); + GUILayout.Space(20f); + this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, new GUILayoutOption[] + { + GUILayout.Width(405f), + GUILayout.Height(200f) + }); + GUILayout.Label(EditorUpdateWindow.s_LatestVersionMessage, "WordWrappedLabel", new GUILayoutOption[0]); + EditorGUILayout.EndScrollView(); + GUILayout.Space(20f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Download new version", new GUILayoutOption[] + { + GUILayout.Width(200f) + })) + { + Help.BrowseURL(EditorUpdateWindow.s_UpdateURL); + } + if (GUILayout.Button("Skip new version", new GUILayoutOption[] + { + GUILayout.Width(200f) + })) + { + EditorPrefs.SetString("EditorUpdateSkipVersionString", EditorUpdateWindow.s_LatestVersionString); + base.Close(); + } + GUILayout.EndHorizontal(); + } + else + { + GUILayout.Label(string.Format(EditorUpdateWindow.s_TextUpToDate.text, Application.unityVersion), "WordWrappedLabel", new GUILayoutOption[] + { + GUILayout.Width(405f) + }); + } + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.Space(8f); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Height(20f) + }); + GUILayout.FlexibleSpace(); + GUI.changed = false; + EditorUpdateWindow.s_ShowAtStartup = GUILayout.Toggle(EditorUpdateWindow.s_ShowAtStartup, EditorUpdateWindow.s_CheckForNewUpdatesText, new GUILayoutOption[0]); + if (GUI.changed) + { + EditorPrefs.SetBool("EditorUpdateShowAtStartup", EditorUpdateWindow.s_ShowAtStartup); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + } +} diff --git a/UnityEditor/UnityEditor/EditorUserBuildSettings.cs b/UnityEditor/UnityEditor/EditorUserBuildSettings.cs new file mode 100644 index 00000000..e8146915 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorUserBuildSettings.cs @@ -0,0 +1,281 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorUserBuildSettings + { + public static Action activeBuildTargetChanged; + public static extern BuildTargetGroup selectedBuildTargetGroup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern BuildTarget selectedStandaloneTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern FlashBuildSubtarget flashBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PSP2BuildSubtarget psp2BuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern SCEBuildSubtarget sceBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool explicitNullChecks + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enableHeadlessMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern XboxBuildSubtarget xboxBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern XboxRunMethod xboxRunMethod + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidBuildSubtarget androidBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern BuildTarget selectedMetroTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern MetroBuildType metroBuildType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern MetroSDK metroSDK + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern MetroBuildAndRunDeployTarget metroBuildAndRunDeployTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool metroGenerateReferenceProjects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern BlackBerryBuildSubtarget blackberryBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern BlackBerryBuildType blackberryBuildType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern TizenBuildSubtarget tizenBuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool webPlayerStreamed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool webPlayerOfflineDeployment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool webPlayerDeployOnline + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern BuildTarget activeBuildTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] activeScriptCompilationDefines + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool development + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool connectProfiler + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool allowDebugging + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool appendProject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool symlinkLibraries + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool installInBuildFolder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SwitchActiveBuildTarget(BuildTarget target); + internal static void Internal_ActiveBuildTargetChanged() + { + if (EditorUserBuildSettings.activeBuildTargetChanged != null) + { + EditorUserBuildSettings.activeBuildTargetChanged(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetBuildLocation(BuildTarget target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetBuildLocation(BuildTarget target, string location); + } +} diff --git a/UnityEditor/UnityEditor/EditorUserSettings.cs b/UnityEditor/UnityEditor/EditorUserSettings.cs new file mode 100644 index 00000000..cac46898 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorUserSettings.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class EditorUserSettings : UnityEngine.Object + { + public static extern bool AutomaticAdd + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool WorkOffline + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool DebugCmd + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool DebugOut + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool DebugCom + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetConfigValue(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetConfigValue(string name, string value); + } +} diff --git a/UnityEditor/UnityEditor/EditorUtility.cs b/UnityEditor/UnityEditor/EditorUtility.cs new file mode 100644 index 00000000..bde5e053 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorUtility.cs @@ -0,0 +1,355 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditor.Scripting.Compilers; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class EditorUtility + { + public delegate void SelectMenuItemFunction(object userData, string[] options, int selected); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RevealInFinder(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDirty(UnityEngine.Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetDirtyIndex(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsDirty(int instanceID); + public static bool LoadWindowLayout(string path) + { + bool newProjectLayoutWasCreated = false; + return WindowLayout.LoadWindowLayout(path, newProjectLayoutWasCreated); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsPersistent(UnityEngine.Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DisplayDialog(string title, string message, string ok, [DefaultValue("\"\"")] string cancel); + [ExcludeFromDocs] + public static bool DisplayDialog(string title, string message, string ok) + { + string empty = string.Empty; + return EditorUtility.DisplayDialog(title, message, ok, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int DisplayDialogComplex(string title, string message, string ok, string cancel, string alt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string OpenFilePanel(string title, string directory, string extension); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string SaveFilePanel(string title, string directory, string defaultName, string extension); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string SaveBuildPanel(BuildTarget target, string title, string directory, string defaultName, string extension); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int NaturalCompare(string a, string b); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int NaturalCompareObjectNames(UnityEngine.Object a, UnityEngine.Object b); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string OpenFolderPanel(string title, string folder, string defaultName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string SaveFolderPanel(string title, string folder, string defaultName); + public static string SaveFilePanelInProject(string title, string defaultName, string extension, string message) + { + return EditorUtility.Internal_SaveFilePanelInProject(title, defaultName, extension, message, "Assets"); + } + public static string SaveFilePanelInProject(string title, string defaultName, string extension, string message, string path) + { + return EditorUtility.Internal_SaveFilePanelInProject(title, defaultName, extension, message, path); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_SaveFilePanelInProject(string title, string defaultName, string extension, string message, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool WarnPrefab(UnityEngine.Object target, string title, string warning, string okButton); + [Obsolete("use AssetDatabase.LoadAssetAtPath"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object FindAsset(string path, Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object InstanceIDToObject(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CompressTexture(Texture2D texture, TextureFormat format, int quality); + public static void CompressTexture(Texture2D texture, TextureFormat format, TextureCompressionQuality quality) + { + EditorUtility.CompressTexture(texture, format, (int)quality); + } + private static void CompressTexture(Texture2D texture, TextureFormat format) + { + EditorUtility.CompressTexture(texture, format, TextureCompressionQuality.Normal); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string InvokeDiffTool(string leftTitle, string leftFile, string rightTitle, string rightFile, string ancestorTitle, string ancestorFile); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopySerialized(UnityEngine.Object source, UnityEngine.Object dest); + [Obsolete("Use AssetDatabase.GetAssetPath")] + public static string GetAssetPath(UnityEngine.Object asset) + { + return AssetDatabase.GetAssetPath(asset); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object[] CollectDependencies(UnityEngine.Object[] roots); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object[] CollectDeepHierarchy(UnityEngine.Object[] roots); + internal static UnityEngine.Object InstantiateRemoveAllNonAnimationComponents(UnityEngine.Object original, Vector3 position, Quaternion rotation) + { + if (original == null) + { + throw new ArgumentException("The prefab you want to instantiate is null."); + } + return EditorUtility.Internal_InstantiateRemoveAllNonAnimationComponentsSingle(original, position, rotation); + } + private static UnityEngine.Object Internal_InstantiateRemoveAllNonAnimationComponentsSingle(UnityEngine.Object data, Vector3 pos, Quaternion rot) + { + return EditorUtility.INTERNAL_CALL_Internal_InstantiateRemoveAllNonAnimationComponentsSingle(data, ref pos, ref rot); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern UnityEngine.Object INTERNAL_CALL_Internal_InstantiateRemoveAllNonAnimationComponentsSingle(UnityEngine.Object data, ref Vector3 pos, ref Quaternion rot); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnloadUnusedAssets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnloadUnusedAssetsIgnoreManagedReferences(); + [Obsolete("Use BuildPipeline.BuildAssetBundle instead")] + public static bool BuildResourceFile(UnityEngine.Object[] selection, string pathName) + { + return BuildPipeline.BuildAssetBundle(null, selection, pathName, BuildAssetBundleOptions.CompleteAssets); + } + internal static void Internal_DisplayPopupMenu(Rect position, string menuItemPath, UnityEngine.Object context, int contextUserData) + { + EditorUtility.INTERNAL_CALL_Internal_DisplayPopupMenu(ref position, menuItemPath, context, contextUserData); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DisplayPopupMenu(ref Rect position, string menuItemPath, UnityEngine.Object context, int contextUserData); + public static void DisplayPopupMenu(Rect position, string menuItemPath, MenuCommand command) + { + if (menuItemPath == "CONTEXT" || menuItemPath == "CONTEXT/" || menuItemPath == "CONTEXT\\") + { + bool flag = false; + if (command == null) + { + flag = true; + } + if (command != null && command.context == null) + { + flag = true; + } + if (flag) + { + Debug.LogError("DisplayPopupMenu: invalid arguments: using CONTEXT requires a valid MenuCommand object. If you want a custom context menu then try using the GenericMenu."); + return; + } + } + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); + position.x = vector.x; + position.y = vector.y; + EditorUtility.Internal_DisplayPopupMenu(position, menuItemPath, (command != null) ? command.context : null, (command != null) ? command.userData : 0); + EditorUtility.ResetMouseDown(); + } + internal static void DisplayObjectContextMenu(Rect position, UnityEngine.Object context, int contextUserData) + { + EditorUtility.DisplayObjectContextMenu(position, new UnityEngine.Object[] + { + context + }, contextUserData); + } + internal static void DisplayObjectContextMenu(Rect position, UnityEngine.Object[] context, int contextUserData) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); + position.x = vector.x; + position.y = vector.y; + EditorUtility.Internal_DisplayObjectContextMenu(position, context, contextUserData); + EditorUtility.ResetMouseDown(); + } + internal static void Internal_DisplayObjectContextMenu(Rect position, UnityEngine.Object[] context, int contextUserData) + { + EditorUtility.INTERNAL_CALL_Internal_DisplayObjectContextMenu(ref position, context, contextUserData); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DisplayObjectContextMenu(ref Rect position, UnityEngine.Object[] context, int contextUserData); + public static void DisplayCustomMenu(Rect position, GUIContent[] options, int selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + int[] selected2 = new int[] + { + selected + }; + string[] array = new string[options.Length]; + for (int i = 0; i < options.Length; i++) + { + array[i] = options[i].text; + } + EditorUtility.DisplayCustomMenu(position, array, selected2, callback, userData); + } + internal static void DisplayCustomMenu(Rect position, string[] options, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); + position.x = vector.x; + position.y = vector.y; + int[] array = new int[options.Length]; + for (int i = 0; i < options.Length; i++) + { + array[i] = 1; + } + EditorUtility.Internal_DisplayCustomMenu(position, options, array, selected, callback, userData); + EditorUtility.ResetMouseDown(); + } + internal static void DisplayCustomMenu(Rect position, string[] options, bool[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); + position.x = vector.x; + position.y = vector.y; + int[] array = new int[options.Length]; + for (int i = 0; i < options.Length; i++) + { + array[i] = ((!enabled[i]) ? 0 : 1); + } + EditorUtility.Internal_DisplayCustomMenu(position, options, array, selected, callback, userData); + EditorUtility.ResetMouseDown(); + } + private static void Internal_DisplayCustomMenu(Rect screenPosition, string[] options, int[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + EditorUtility.INTERNAL_CALL_Internal_DisplayCustomMenu(ref screenPosition, options, enabled, selected, callback, userData); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DisplayCustomMenu(ref Rect screenPosition, string[] options, int[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData); + internal static void ResetMouseDown() + { + Tools.s_ButtonDown = -1; + GUIUtility.hotControl = 0; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetTemporarilyAllowIndieRenderTexture(bool allow); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FocusProjectWindow(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string FormatBytes(int bytes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DisplayProgressBar(string title, string info, float progress); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DisplayCancelableProgressBar(string title, string info, float progress); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearProgressBar(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetObjectEnabled(UnityEngine.Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetObjectEnabled(UnityEngine.Object target, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSelectedWireframeHidden(Renderer renderer, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ForceReloadInspectors(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ForceRebuildInspectors(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ExtractOggFile(UnityEngine.Object obj, string path); + public static GameObject CreateGameObjectWithHideFlags(string name, HideFlags flags, params Type[] components) + { + GameObject gameObject = EditorUtility.Internal_CreateGameObjectWithHideFlags(name, flags); + gameObject.AddComponent(typeof(Transform)); + for (int i = 0; i < components.Length; i++) + { + Type componentType = components[i]; + gameObject.AddComponent(componentType); + } + return gameObject; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern GameObject Internal_CreateGameObjectWithHideFlags(string name, HideFlags flags); + public static string[] CompileCSharp(string[] sources, string[] references, string[] defines, string outputFile) + { + return MonoCSharpCompiler.Compile(sources, references, defines, outputFile); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenWithDefaultApp(string fileName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool MetroCreateTestCertificate(string path, string publisher, string password, bool overwrite); + [Obsolete("Use PrefabUtility.InstantiatePrefab")] + public static UnityEngine.Object InstantiatePrefab(UnityEngine.Object target) + { + return PrefabUtility.InstantiatePrefab(target); + } + [Obsolete("Use PrefabUtility.ReplacePrefab")] + public static GameObject ReplacePrefab(GameObject go, UnityEngine.Object targetPrefab, ReplacePrefabOptions options) + { + return PrefabUtility.ReplacePrefab(go, targetPrefab, options); + } + [Obsolete("Use PrefabUtility.ReplacePrefab")] + public static GameObject ReplacePrefab(GameObject go, UnityEngine.Object targetPrefab) + { + return PrefabUtility.ReplacePrefab(go, targetPrefab, ReplacePrefabOptions.Default); + } + [Obsolete("Use PrefabUtility.CreateEmptyPrefab")] + public static UnityEngine.Object CreateEmptyPrefab(string path) + { + return PrefabUtility.CreateEmptyPrefab(path); + } + [Obsolete("Use PrefabUtility.CreateEmptyPrefab")] + public static bool ReconnectToLastPrefab(GameObject go) + { + return PrefabUtility.ReconnectToLastPrefab(go); + } + [Obsolete("Use PrefabUtility.GetPrefabType")] + public static PrefabType GetPrefabType(UnityEngine.Object target) + { + return PrefabUtility.GetPrefabType(target); + } + [Obsolete("Use PrefabUtility.GetPrefabParent")] + public static UnityEngine.Object GetPrefabParent(UnityEngine.Object source) + { + return PrefabUtility.GetPrefabParent(source); + } + [Obsolete("Use PrefabUtility.FindPrefabRoot")] + public static GameObject FindPrefabRoot(GameObject source) + { + return PrefabUtility.FindPrefabRoot(source); + } + [Obsolete("Use PrefabUtility.ResetToPrefabState")] + public static bool ResetToPrefabState(UnityEngine.Object source) + { + return PrefabUtility.ResetToPrefabState(source); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetCameraAnimateMaterials(Camera camera, bool animate); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetInvalidFilenameChars(); + } +} diff --git a/UnityEditor/UnityEditor/EditorWindow.cs b/UnityEditor/UnityEditor/EditorWindow.cs new file mode 100644 index 00000000..82c25d5f --- /dev/null +++ b/UnityEditor/UnityEditor/EditorWindow.cs @@ -0,0 +1,779 @@ +using System; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public class EditorWindow : ScriptableObject + { + private const double kWarningFadeoutWait = 4.0; + private const double kWarningFadeoutTime = 1.0; + [HideInInspector, SerializeField] + private bool m_AutoRepaintOnSceneChange; + [HideInInspector, SerializeField] + private Vector2 m_MinSize = new Vector2(100f, 100f); + [HideInInspector, SerializeField] + private Vector2 m_MaxSize = new Vector2(4000f, 4000f); + [HideInInspector, SerializeField] + internal string m_Title; + [HideInInspector, SerializeField] + private int m_DepthBufferBits; + [HideInInspector, SerializeField] + private int m_AntiAlias; + [HideInInspector, SerializeField] + internal Rect m_Pos = new Rect(0f, 0f, 320f, 240f); + [NonSerialized] + private GUIContent m_CachedTitleContent; + private Rect m_GameViewRect; + private bool m_DontClearBackground; + private bool m_WantsMouseMove; + [NonSerialized] + internal HostView m_Parent; + internal GUIContent m_Notification; + private Vector2 m_NotificationSize; + internal float m_FadeoutTime; + public bool wantsMouseMove + { + get + { + return this.m_WantsMouseMove; + } + set + { + this.m_WantsMouseMove = value; + this.MakeParentsSettingsMatchMe(); + } + } + internal bool dontClearBackground + { + get + { + return this.m_DontClearBackground; + } + set + { + this.m_DontClearBackground = value; + if (this.m_Parent && this.m_Parent.actualView == this) + { + this.m_Parent.backgroundValid = false; + } + } + } + public bool autoRepaintOnSceneChange + { + get + { + return this.m_AutoRepaintOnSceneChange; + } + set + { + this.m_AutoRepaintOnSceneChange = value; + this.MakeParentsSettingsMatchMe(); + } + } + public bool maximized + { + get + { + return WindowLayout.IsMaximized(this); + } + set + { + bool flag = WindowLayout.IsMaximized(this); + if (value != flag) + { + if (value) + { + WindowLayout.Maximize(this); + } + else + { + WindowLayout.Unmaximize(this); + } + } + } + } + internal bool hasFocus + { + get + { + return this.m_Parent && this.m_Parent.actualView == this; + } + } + internal bool docked + { + get + { + return this.m_Parent != null && this.m_Parent.window != null && !this.m_Parent.window.IsNotDocked(); + } + } + public static EditorWindow focusedWindow + { + get + { + HostView hostView = GUIView.focusedView as HostView; + if (hostView != null) + { + return hostView.actualView; + } + return null; + } + } + public static EditorWindow mouseOverWindow + { + get + { + HostView hostView = GUIView.mouseOverView as HostView; + if (hostView != null) + { + return hostView.actualView; + } + return null; + } + } + public Vector2 minSize + { + get + { + return this.m_MinSize; + } + set + { + this.m_MinSize = value; + this.MakeParentsSettingsMatchMe(); + } + } + public Vector2 maxSize + { + get + { + return this.m_MaxSize; + } + set + { + this.m_MaxSize = value; + this.MakeParentsSettingsMatchMe(); + } + } + public string title + { + get + { + return this.m_Title; + } + set + { + this.m_Title = value; + this.m_CachedTitleContent = null; + if (this.m_Parent && this.m_Parent.window && this.m_Parent.window.mainView == this.m_Parent) + { + this.m_Parent.window.title = this.m_Title; + } + } + } + internal GUIContent cachedTitleContent + { + get + { + if (this.m_CachedTitleContent == null) + { + this.m_CachedTitleContent = EditorGUIUtility.TextContent(this.m_Title); + } + return this.m_CachedTitleContent; + } + } + public int depthBufferBits + { + get + { + return this.m_DepthBufferBits; + } + set + { + this.m_DepthBufferBits = value; + } + } + public int antiAlias + { + get + { + return this.m_AntiAlias; + } + set + { + this.m_AntiAlias = value; + } + } + public Rect position + { + get + { + return this.m_Pos; + } + set + { + this.m_Pos = value; + if (this.m_Parent) + { + DockArea dockArea = this.m_Parent as DockArea; + if (!dockArea) + { + this.m_Parent.window.position = value; + } + else + { + if (!dockArea || (dockArea.parent && dockArea.m_Panes.Count == 1 && !dockArea.parent.parent)) + { + dockArea.window.position = dockArea.borderSize.Add(value); + } + else + { + dockArea.RemoveTab(this); + EditorWindow.CreateNewWindowForEditorWindow(this, true, true); + } + } + } + } + } + public EditorWindow() + { + this.title = base.GetType().ToString(); + base.hideFlags = HideFlags.DontSave; + } + public void BeginWindows() + { + EditorGUIInternal.BeginWindowsForward(1, base.GetInstanceID()); + } + public void EndWindows() + { + GUI.EndWindows(); + } + internal virtual void OnResized() + { + } + internal void CheckForWindowRepaint() + { + double timeSinceStartup = EditorApplication.timeSinceStartup; + if (timeSinceStartup < (double)this.m_FadeoutTime) + { + return; + } + if (timeSinceStartup > (double)this.m_FadeoutTime + 1.0) + { + this.RemoveNotification(); + return; + } + this.Repaint(); + } + public void ShowNotification(GUIContent notification) + { + this.m_Notification = new GUIContent(notification); + EditorStyles.notificationText.CalcMinMaxWidth(this.m_Notification, out this.m_NotificationSize.y, out this.m_NotificationSize.x); + this.m_NotificationSize.y = EditorStyles.notificationText.CalcHeight(this.m_Notification, this.m_NotificationSize.x); + if (this.m_FadeoutTime == 0f) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.CheckForWindowRepaint)); + } + this.m_FadeoutTime = (float)(EditorApplication.timeSinceStartup + 4.0); + } + public void RemoveNotification() + { + if (this.m_FadeoutTime == 0f) + { + return; + } + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.CheckForWindowRepaint)); + this.m_Notification = null; + this.m_FadeoutTime = 0f; + } + internal void DrawNotification() + { + Vector2 notificationSize = this.m_NotificationSize; + float num = this.position.width - (float)EditorStyles.notificationText.margin.horizontal; + float num2 = this.position.height - (float)EditorStyles.notificationText.margin.vertical - 20f; + if (num < this.m_NotificationSize.x) + { + float num3 = num / this.m_NotificationSize.x; + notificationSize.x *= num3; + notificationSize.y = EditorStyles.notificationText.CalcHeight(this.m_Notification, notificationSize.x); + } + if (notificationSize.y > num2) + { + notificationSize.y = num2; + } + Rect position = new Rect((this.position.width - notificationSize.x) * 0.5f, 20f + (this.position.height - 20f - notificationSize.y) * 0.7f, notificationSize.x, notificationSize.y); + double timeSinceStartup = EditorApplication.timeSinceStartup; + if (timeSinceStartup > (double)this.m_FadeoutTime) + { + GUI.color = new Color(1f, 1f, 1f, 1f - (float)((timeSinceStartup - (double)this.m_FadeoutTime) / 1.0)); + } + GUI.Label(position, GUIContent.none, EditorStyles.notificationBackground); + EditorGUI.DoDropShadowLabel(position, this.m_Notification, EditorStyles.notificationText, 0.3f); + } + internal int GetNumTabs() + { + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea) + { + return dockArea.m_Panes.Count; + } + return 0; + } + internal bool ShowNextTabIfPossible() + { + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea) + { + int num = dockArea.m_Panes.IndexOf(this); + num = (num + 1) % dockArea.m_Panes.Count; + if (dockArea.selected != num) + { + dockArea.selected = num; + dockArea.Repaint(); + return true; + } + } + return false; + } + public void ShowTab() + { + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea) + { + int num = dockArea.m_Panes.IndexOf(this); + if (dockArea.selected != num) + { + dockArea.selected = num; + } + } + this.Repaint(); + } + public void Focus() + { + if (this.m_Parent) + { + this.ShowTab(); + this.m_Parent.Focus(); + } + } + internal void MakeParentsSettingsMatchMe() + { + if (!this.m_Parent || this.m_Parent.actualView != this) + { + return; + } + this.m_Parent.autoRepaintOnSceneChange = this.m_AutoRepaintOnSceneChange; + bool flag = this.m_Parent.antiAlias != this.m_AntiAlias || this.m_Parent.depthBufferBits != this.m_DepthBufferBits; + this.m_Parent.antiAlias = this.m_AntiAlias; + this.m_Parent.depthBufferBits = this.m_DepthBufferBits; + this.m_Parent.SetInternalGameViewRect(this.m_GameViewRect); + this.m_Parent.wantsMouseMove = this.m_WantsMouseMove; + Vector2 b = new Vector2((float)(this.m_Parent.borderSize.left + this.m_Parent.borderSize.right), (float)(this.m_Parent.borderSize.top + this.m_Parent.borderSize.bottom)); + this.m_Parent.SetMinMaxSizes(this.minSize + b, this.maxSize + b); + if (flag) + { + this.m_Parent.RecreateContext(); + } + } + public void ShowUtility() + { + this.ShowWithMode(ShowMode.Utility); + } + public void ShowPopup() + { + if (this.m_Parent == null) + { + ContainerWindow containerWindow = ScriptableObject.CreateInstance(); + containerWindow.title = this.title; + HostView hostView = ScriptableObject.CreateInstance(); + hostView.actualView = this; + Rect position = this.m_Parent.borderSize.Add(new Rect(this.position.x, this.position.y, this.position.width, this.position.height)); + containerWindow.position = position; + containerWindow.mainView = hostView; + this.MakeParentsSettingsMatchMe(); + containerWindow.ShowPopup(); + } + } + internal void ShowWithMode(ShowMode mode) + { + if (this.m_Parent == null) + { + SavedGUIState savedGUIState = SavedGUIState.Create(); + ContainerWindow containerWindow = ScriptableObject.CreateInstance(); + containerWindow.title = this.title; + HostView hostView = ScriptableObject.CreateInstance(); + hostView.actualView = this; + Rect position = this.m_Parent.borderSize.Add(new Rect(this.position.x, this.position.y, this.position.width, this.position.height)); + containerWindow.position = position; + containerWindow.mainView = hostView; + this.MakeParentsSettingsMatchMe(); + containerWindow.Show(mode, true, false); + savedGUIState.ApplyAndForget(); + } + } + public void ShowAsDropDown(Rect buttonRect, Vector2 windowSize) + { + this.ShowAsDropDown(buttonRect, windowSize, null); + } + internal void ShowAsDropDown(Rect buttonRect, Vector2 windowSize, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + this.position = this.ShowAsDropDownFitToScreen(buttonRect, windowSize, locationPriorityOrder); + this.ShowWithMode(ShowMode.PopupMenu); + this.position = this.ShowAsDropDownFitToScreen(buttonRect, windowSize, locationPriorityOrder); + this.minSize = new Vector2(this.position.width, this.position.height); + this.maxSize = new Vector2(this.position.width, this.position.height); + if (EditorWindow.focusedWindow != this) + { + this.Focus(); + } + this.m_Parent.AddToAuxWindowList(); + this.m_Parent.window.m_DontSaveToLayout = true; + } + internal Rect ShowAsDropDownFitToScreen(Rect buttonRect, Vector2 windowSize, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + if (this.m_Parent == null) + { + return new Rect(buttonRect.x, buttonRect.yMax, windowSize.x, windowSize.y); + } + return this.m_Parent.window.GetDropDownRect(buttonRect, windowSize, windowSize, locationPriorityOrder); + } + [ExcludeFromDocs] + public void Show() + { + bool immediateDisplay = false; + this.Show(immediateDisplay); + } + public void Show([DefaultValue("false")] bool immediateDisplay) + { + if (this.m_Parent == null) + { + EditorWindow.CreateNewWindowForEditorWindow(this, true, immediateDisplay); + } + } + public void ShowAuxWindow() + { + this.ShowWithMode(ShowMode.AuxWindow); + this.Focus(); + this.m_Parent.AddToAuxWindowList(); + } + internal void ShowModal() + { + this.ShowWithMode(ShowMode.AuxWindow); + this.MakeModal(this.m_Parent.window); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MakeModal(ContainerWindow win); + [ExcludeFromDocs] + public static EditorWindow GetWindow(Type t, bool utility, string title) + { + bool focus = true; + return EditorWindow.GetWindow(t, utility, title, focus); + } + [ExcludeFromDocs] + public static EditorWindow GetWindow(Type t, bool utility) + { + bool focus = true; + string title = null; + return EditorWindow.GetWindow(t, utility, title, focus); + } + [ExcludeFromDocs] + public static EditorWindow GetWindow(Type t) + { + bool focus = true; + string title = null; + bool utility = false; + return EditorWindow.GetWindow(t, utility, title, focus); + } + public static EditorWindow GetWindow(Type t, [DefaultValue("false")] bool utility, [DefaultValue("null")] string title, [DefaultValue("true")] bool focus) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(t); + EditorWindow editorWindow = (array.Length <= 0) ? null : ((EditorWindow)array[0]); + if (!editorWindow) + { + editorWindow = (ScriptableObject.CreateInstance(t) as EditorWindow); + if (title != null) + { + editorWindow.title = title; + } + if (utility) + { + editorWindow.ShowUtility(); + } + else + { + editorWindow.Show(); + } + } + else + { + if (focus) + { + editorWindow.Show(); + editorWindow.Focus(); + } + } + return editorWindow; + } + public static T GetWindow() where T : EditorWindow + { + return EditorWindow.GetWindow(false, null, true); + } + public static T GetWindow(bool utility) where T : EditorWindow + { + return EditorWindow.GetWindow(utility, null, true); + } + public static T GetWindow(bool utility, string title) where T : EditorWindow + { + return EditorWindow.GetWindow(utility, title, true); + } + public static T GetWindow(string title) where T : EditorWindow + { + return EditorWindow.GetWindow(title, true); + } + public static T GetWindow(string title, bool focus) where T : EditorWindow + { + return EditorWindow.GetWindow(false, title, focus); + } + public static T GetWindow(bool utility, string title, bool focus) where T : EditorWindow + { + return EditorWindow.GetWindow(typeof(T), utility, title, focus) as T; + } + public static T GetWindow(params Type[] desiredDockNextTo) where T : EditorWindow + { + return EditorWindow.GetWindow(null, true, desiredDockNextTo); + } + public static T GetWindow(string title, params Type[] desiredDockNextTo) where T : EditorWindow + { + return EditorWindow.GetWindow(title, true, desiredDockNextTo); + } + public static T GetWindow(string title, bool focus, params Type[] desiredDockNextTo) where T : EditorWindow + { + T[] array = Resources.FindObjectsOfTypeAll(typeof(T)) as T[]; + T t = (array.Length <= 0) ? ((T)((object)null)) : array[0]; + if (t != null) + { + if (focus) + { + t.Focus(); + } + return t; + } + t = ScriptableObject.CreateInstance(); + if (title != null) + { + t.title = title; + } + Type desired; + for (int i = 0; i < desiredDockNextTo.Length; i++) + { + desired = desiredDockNextTo[i]; + ContainerWindow[] windows = ContainerWindow.windows; + for (int j = 0; j < windows.Length; j++) + { + ContainerWindow containerWindow = windows[j]; + View[] allChildren = containerWindow.mainView.allChildren; + for (int k = 0; k < allChildren.Length; k++) + { + View view = allChildren[k]; + DockArea dockArea = view as DockArea; + if (!(dockArea == null)) + { + if (dockArea.m_Panes.Any((EditorWindow pane) => pane.GetType() == desired)) + { + dockArea.AddTab(t); + return t; + } + } + } + } + } + t.Show(); + return t; + } + public static void FocusWindowIfItsOpen(Type t) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(t); + EditorWindow editorWindow = (array.Length <= 0) ? null : (array[0] as EditorWindow); + if (editorWindow) + { + editorWindow.Focus(); + } + } + public static void FocusWindowIfItsOpen() where T : EditorWindow + { + EditorWindow.FocusWindowIfItsOpen(typeof(T)); + } + internal void RemoveFromDockArea() + { + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea) + { + dockArea.RemoveTab(this, true); + } + } + [ExcludeFromDocs] + public static EditorWindow GetWindowWithRect(Type t, Rect rect, bool utility) + { + string title = null; + return EditorWindow.GetWindowWithRect(t, rect, utility, title); + } + [ExcludeFromDocs] + public static EditorWindow GetWindowWithRect(Type t, Rect rect) + { + string title = null; + bool utility = false; + return EditorWindow.GetWindowWithRect(t, rect, utility, title); + } + public static EditorWindow GetWindowWithRect(Type t, Rect rect, [DefaultValue("false")] bool utility, [DefaultValue("null")] string title) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(t); + EditorWindow editorWindow = (array.Length <= 0) ? null : ((EditorWindow)array[0]); + if (!editorWindow) + { + editorWindow = (ScriptableObject.CreateInstance(t) as EditorWindow); + editorWindow.minSize = new Vector2(rect.width, rect.height); + editorWindow.maxSize = new Vector2(rect.width, rect.height); + editorWindow.position = rect; + if (title != null) + { + editorWindow.title = title; + } + if (utility) + { + editorWindow.ShowUtility(); + } + else + { + editorWindow.Show(); + } + } + else + { + editorWindow.Focus(); + } + return editorWindow; + } + public static T GetWindowWithRect(Rect rect) where T : EditorWindow + { + return EditorWindow.GetWindowWithRect(rect, false, null, true); + } + public static T GetWindowWithRect(Rect rect, bool utility) where T : EditorWindow + { + return EditorWindow.GetWindowWithRect(rect, utility, null, true); + } + public static T GetWindowWithRect(Rect rect, bool utility, string title) where T : EditorWindow + { + return EditorWindow.GetWindowWithRect(rect, utility, title, true); + } + public static T GetWindowWithRect(Rect rect, bool utility, string title, bool focus) where T : EditorWindow + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(T)); + T result; + if (array.Length > 0) + { + result = (T)((object)array[0]); + if (focus) + { + result.Focus(); + } + } + else + { + result = ScriptableObject.CreateInstance(); + result.minSize = new Vector2(rect.width, rect.height); + result.maxSize = new Vector2(rect.width, rect.height); + result.position = rect; + if (title != null) + { + result.title = title; + } + if (utility) + { + result.ShowUtility(); + } + else + { + result.Show(); + } + } + return result; + } + internal static T GetWindowDontShow() where T : EditorWindow + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(T)); + return (array.Length <= 0) ? ScriptableObject.CreateInstance() : ((T)((object)array[0])); + } + public void Close() + { + if (WindowLayout.IsMaximized(this)) + { + WindowLayout.Unmaximize(this); + } + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea) + { + dockArea.RemoveTab(this, true); + } + else + { + this.m_Parent.window.Close(); + } + UnityEngine.Object.DestroyImmediate(this, true); + } + public void Repaint() + { + if (this.m_Parent && this.m_Parent.actualView == this) + { + this.m_Parent.Repaint(); + } + } + internal void RepaintImmediately() + { + if (this.m_Parent && this.m_Parent.actualView == this) + { + this.m_Parent.RepaintImmediately(); + } + } + internal Rect GetCurrentGameViewRect() + { + return this.m_GameViewRect; + } + internal void SetInternalGameViewRect(Rect rect) + { + this.m_GameViewRect = rect; + this.MakeParentsSettingsMatchMe(); + } + public bool SendEvent(Event e) + { + return this.m_Parent.SendEvent(e); + } + internal static void CreateNewWindowForEditorWindow(EditorWindow window, bool loadPosition, bool showImmediately) + { + EditorWindow.CreateNewWindowForEditorWindow(window, new Vector2(window.position.x, window.position.y), loadPosition, showImmediately); + } + internal static void CreateNewWindowForEditorWindow(EditorWindow window, Vector2 screenPosition, bool loadPosition, bool showImmediately) + { + ContainerWindow containerWindow = ScriptableObject.CreateInstance(); + SplitView splitView = ScriptableObject.CreateInstance(); + containerWindow.mainView = splitView; + DockArea dockArea = ScriptableObject.CreateInstance(); + splitView.AddChild(dockArea); + dockArea.AddTab(window); + Rect position = window.m_Parent.borderSize.Add(new Rect(screenPosition.x, screenPosition.y, window.position.width, window.position.height)); + containerWindow.position = position; + splitView.position = new Rect(0f, 0f, position.width, position.height); + containerWindow.Show(ShowMode.NormalWindow, loadPosition, showImmediately); + containerWindow.OnResize(); + } + [ContextMenu("Add Scene")] + internal void AddSceneTab() + { + } + [ContextMenu("Add Game")] + internal void AddGameTab() + { + } + } +} diff --git a/UnityEditor/UnityEditor/EditorWrapper.cs b/UnityEditor/UnityEditor/EditorWrapper.cs new file mode 100644 index 00000000..e659f96d --- /dev/null +++ b/UnityEditor/UnityEditor/EditorWrapper.cs @@ -0,0 +1,106 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class EditorWrapper : IDisposable + { + public delegate void VoidDelegate(SceneView sceneView); + private Editor editor; + public EditorWrapper.VoidDelegate OnSceneDrag; + public string name + { + get + { + return this.editor.target.name; + } + } + private EditorWrapper() + { + } + public bool HasPreviewGUI() + { + return this.editor.HasPreviewGUI(); + } + public void OnPreviewSettings() + { + this.editor.OnPreviewSettings(); + } + public void OnPreviewGUI(Rect position, GUIStyle background) + { + this.editor.OnPreviewGUI(position, background); + } + public void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + if (this.editor != null) + { + this.editor.OnInteractivePreviewGUI(r, background); + } + } + internal void OnAssetStoreInspectorGUI() + { + if (this.editor != null) + { + this.editor.OnAssetStoreInspectorGUI(); + } + } + public string GetInfoString() + { + return this.editor.GetInfoString(); + } + public static EditorWrapper Make(UnityEngine.Object obj, EditorFeatures requirements) + { + EditorWrapper editorWrapper = new EditorWrapper(); + if (editorWrapper.Init(obj, requirements)) + { + return editorWrapper; + } + editorWrapper.Dispose(); + return null; + } + private bool Init(UnityEngine.Object obj, EditorFeatures requirements) + { + this.editor = Editor.CreateEditor(obj); + if (this.editor == null) + { + return false; + } + if ((requirements & EditorFeatures.PreviewGUI) > EditorFeatures.None && !this.editor.HasPreviewGUI()) + { + return false; + } + Type type = this.editor.GetType(); + MethodInfo method = type.GetMethod("OnSceneDrag", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + this.OnSceneDrag = (EditorWrapper.VoidDelegate)Delegate.CreateDelegate(typeof(EditorWrapper.VoidDelegate), this.editor, method); + } + else + { + if ((requirements & EditorFeatures.OnSceneDrag) > EditorFeatures.None) + { + return false; + } + this.OnSceneDrag = new EditorWrapper.VoidDelegate(this.DefaultOnSceneDrag); + } + return true; + } + private void DefaultOnSceneDrag(SceneView sceneView) + { + } + public void Dispose() + { + if (this.editor != null) + { + this.OnSceneDrag = null; + UnityEngine.Object.DestroyImmediate(this.editor); + this.editor = null; + } + GC.SuppressFinalize(this); + } + ~EditorWrapper() + { + Debug.LogError("Failed to dispose EditorWrapper."); + } + } +} diff --git a/UnityEditor/UnityEditor/EmissionModuleUI.cs b/UnityEditor/UnityEditor/EmissionModuleUI.cs new file mode 100644 index 00000000..9690484c --- /dev/null +++ b/UnityEditor/UnityEditor/EmissionModuleUI.cs @@ -0,0 +1,136 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class EmissionModuleUI : ModuleUI + { + private enum EmissionTypes + { + Time, + Distance + } + private class Texts + { + public GUIContent rate = new GUIContent("Rate", "The number of particles emitted per second (Time) or per distance unit (Distance)"); + public GUIContent burst = new GUIContent("Bursts", "Emission of extra particles at specific times during the duration of the system."); + } + private const int k_MaxNumBursts = 4; + private SerializedProperty m_Type; + public SerializedMinMaxCurve m_Rate; + private SerializedProperty[] m_BurstTime = new SerializedProperty[4]; + private SerializedProperty[] m_BurstParticleCount = new SerializedProperty[4]; + private SerializedProperty m_BurstCount; + private string[] m_GuiNames = new string[] + { + "Time", + "Distance" + }; + private static EmissionModuleUI.Texts s_Texts; + public EmissionModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "EmissionModule", displayName) + { + this.m_ToolTip = "Emission of the emitter. This controls the rate at which particles are emitted as well as burst emissions."; + } + protected override void Init() + { + if (EmissionModuleUI.s_Texts == null) + { + EmissionModuleUI.s_Texts = new EmissionModuleUI.Texts(); + } + if (this.m_BurstCount != null) + { + return; + } + this.m_Type = base.GetProperty("m_Type"); + this.m_Rate = new SerializedMinMaxCurve(this, EmissionModuleUI.s_Texts.rate, "rate"); + this.m_Rate.m_AllowRandom = false; + this.m_BurstTime[0] = base.GetProperty("time0"); + this.m_BurstTime[1] = base.GetProperty("time1"); + this.m_BurstTime[2] = base.GetProperty("time2"); + this.m_BurstTime[3] = base.GetProperty("time3"); + this.m_BurstParticleCount[0] = base.GetProperty("cnt0"); + this.m_BurstParticleCount[1] = base.GetProperty("cnt1"); + this.m_BurstParticleCount[2] = base.GetProperty("cnt2"); + this.m_BurstParticleCount[3] = base.GetProperty("cnt3"); + this.m_BurstCount = base.GetProperty("m_BurstCount"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + ModuleUI.GUIMinMaxCurve(EmissionModuleUI.s_Texts.rate, this.m_Rate); + ModuleUI.GUIPopup(GUIContent.none, this.m_Type, this.m_GuiNames); + if (this.m_Type.intValue != 1) + { + this.DoBurstGUI(s); + } + } + private void DoBurstGUI(ParticleSystem s) + { + EditorGUILayout.Space(); + Rect controlRect = ModuleUI.GetControlRect(13); + GUI.Label(controlRect, EmissionModuleUI.s_Texts.burst, ParticleSystemStyles.Get().label); + float num = 20f; + float num2 = 40f; + float num3 = (num2 + num) * 2f + num - 1f; + float num4 = controlRect.width - num3; + num4 = Mathf.Min(num4, EditorGUIUtility.labelWidth); + int num5 = this.m_BurstCount.intValue; + Rect position = new Rect(controlRect.x + num4, controlRect.y, num3, 3f); + GUI.Label(position, GUIContent.none, ParticleSystemStyles.Get().line); + Rect controlRect2 = new Rect(controlRect.x + num + num4, controlRect.y, num2 + num, controlRect.height); + GUI.Label(controlRect2, "Time", ParticleSystemStyles.Get().label); + controlRect2.x += num + num2; + GUI.Label(controlRect2, "Particles", ParticleSystemStyles.Get().label); + position.y += 12f; + GUI.Label(position, GUIContent.none, ParticleSystemStyles.Get().line); + float duration = s.duration; + int num6 = num5; + for (int i = 0; i < num5; i++) + { + SerializedProperty serializedProperty = this.m_BurstTime[i]; + SerializedProperty serializedProperty2 = this.m_BurstParticleCount[i]; + controlRect = ModuleUI.GetControlRect(13); + controlRect2 = new Rect(controlRect.x + num4, controlRect.y, num + num2, controlRect.height); + float num7 = ModuleUI.FloatDraggable(controlRect2, serializedProperty, 1f, num, "n2"); + if (num7 < 0f) + { + serializedProperty.floatValue = 0f; + } + if (num7 > duration) + { + serializedProperty.floatValue = duration; + } + int intValue = serializedProperty2.intValue; + controlRect2.x += controlRect2.width; + serializedProperty2.intValue = ModuleUI.IntDraggable(controlRect2, null, intValue, num); + if (i == num5 - 1) + { + controlRect2.x = position.xMax - 12f; + if (ModuleUI.MinusButton(controlRect2)) + { + num5--; + } + } + } + if (num5 < 4) + { + controlRect2 = ModuleUI.GetControlRect(13); + controlRect2.xMin = controlRect2.xMax - 12f; + if (ModuleUI.PlusButton(controlRect2)) + { + num5++; + } + } + if (num5 != num6) + { + this.m_BurstCount.intValue = num5; + } + } + public override void UpdateCullingSupportedString(ref string text) + { + this.Init(); + if (this.m_Type.intValue == 1) + { + text += "\n\tEmission is distance based."; + } + } + } +} diff --git a/UnityEditor/UnityEditor/Empty.cs b/UnityEditor/UnityEditor/Empty.cs new file mode 100644 index 00000000..5144aaf1 --- /dev/null +++ b/UnityEditor/UnityEditor/Empty.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + internal class Empty + { + internal static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) + { + } + internal static bool OnOpenAsset(int instanceID, int line) + { + return false; + } + } +} diff --git a/UnityEditor/UnityEditor/EulerCurveCombinedRenderer.cs b/UnityEditor/UnityEditor/EulerCurveCombinedRenderer.cs new file mode 100644 index 00000000..779cbf21 --- /dev/null +++ b/UnityEditor/UnityEditor/EulerCurveCombinedRenderer.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class EulerCurveCombinedRenderer + { + private const int kSegmentResolution = 40; + private const float epsilon = 0.001f; + private AnimationCurve quaternionX; + private AnimationCurve quaternionY; + private AnimationCurve quaternionZ; + private AnimationCurve quaternionW; + private AnimationCurve eulerX; + private AnimationCurve eulerY; + private AnimationCurve eulerZ; + private SortedDictionary points; + private float cachedEvaluationTime = float.PositiveInfinity; + private Vector3 cachedEvaluationValue; + private float cachedRangeStart = float.PositiveInfinity; + private float cachedRangeEnd = float.NegativeInfinity; + private Vector3 refEuler; + private float m_CustomRangeStart; + private float m_CustomRangeEnd; + private WrapMode preWrapMode = WrapMode.Once; + private WrapMode postWrapMode = WrapMode.Once; + private float rangeStart + { + get + { + return (this.m_CustomRangeStart != 0f || this.m_CustomRangeEnd != 0f || this.eulerX.length <= 0) ? this.m_CustomRangeStart : this.eulerX.keys[0].time; + } + } + private float rangeEnd + { + get + { + return (this.m_CustomRangeStart != 0f || this.m_CustomRangeEnd != 0f || this.eulerX.length <= 0) ? this.m_CustomRangeEnd : this.eulerX.keys[this.eulerX.length - 1].time; + } + } + public EulerCurveCombinedRenderer(AnimationCurve quaternionX, AnimationCurve quaternionY, AnimationCurve quaternionZ, AnimationCurve quaternionW, AnimationCurve eulerX, AnimationCurve eulerY, AnimationCurve eulerZ) + { + this.quaternionX = quaternionX; + this.quaternionY = quaternionY; + this.quaternionZ = quaternionZ; + this.quaternionW = quaternionW; + this.eulerX = ((eulerX != null) ? eulerX : new AnimationCurve()); + this.eulerY = ((eulerY != null) ? eulerY : new AnimationCurve()); + this.eulerZ = ((eulerZ != null) ? eulerZ : new AnimationCurve()); + } + public AnimationCurve GetCurveOfComponent(int component) + { + switch (component) + { + case 0: + return this.eulerX; + case 1: + return this.eulerY; + case 2: + return this.eulerZ; + default: + return null; + } + } + public float RangeStart() + { + return this.rangeStart; + } + public float RangeEnd() + { + return this.rangeEnd; + } + public WrapMode PreWrapMode() + { + return this.preWrapMode; + } + public WrapMode PostWrapMode() + { + return this.postWrapMode; + } + public void SetWrap(WrapMode wrap) + { + this.preWrapMode = wrap; + this.postWrapMode = wrap; + } + public void SetWrap(WrapMode preWrap, WrapMode postWrap) + { + this.preWrapMode = preWrap; + this.postWrapMode = postWrap; + } + public void SetCustomRange(float start, float end) + { + this.m_CustomRangeStart = start; + this.m_CustomRangeEnd = end; + } + private Vector3 GetValues(float time, bool keyReference) + { + if (this.quaternionX == null) + { + Debug.LogError("X curve is null!"); + } + if (this.quaternionY == null) + { + Debug.LogError("Y curve is null!"); + } + if (this.quaternionZ == null) + { + Debug.LogError("Z curve is null!"); + } + if (this.quaternionW == null) + { + Debug.LogError("W curve is null!"); + } + Quaternion q = this.EvaluateQuaternionCurvesDirectly(time); + if (keyReference) + { + this.refEuler = this.EvaluateEulerCurvesDirectly(time); + } + this.refEuler = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(q, this.refEuler); + return this.refEuler; + } + private Quaternion EvaluateQuaternionCurvesDirectly(float time) + { + return new Quaternion(this.quaternionX.Evaluate(time), this.quaternionY.Evaluate(time), this.quaternionZ.Evaluate(time), this.quaternionW.Evaluate(time)); + } + private Vector3 EvaluateEulerCurvesDirectly(float time) + { + return new Vector3(this.eulerX.Evaluate(time), this.eulerY.Evaluate(time), this.eulerZ.Evaluate(time)); + } + private void CalculateCurves(float minTime, float maxTime) + { + this.points = new SortedDictionary(); + float[,] array = NormalCurveRenderer.CalculateRanges(minTime, maxTime, this.rangeStart, this.rangeEnd, this.preWrapMode, this.postWrapMode); + for (int i = 0; i < array.GetLength(0); i++) + { + this.AddPoints(array[i, 0], array[i, 1]); + } + } + private void AddPoints(float minTime, float maxTime) + { + AnimationCurve animationCurve = this.quaternionX; + if (animationCurve.length == 0) + { + return; + } + if (animationCurve[0].time >= minTime) + { + Vector3 values = this.GetValues(animationCurve[0].time, true); + this.points[this.rangeStart] = values; + this.points[animationCurve[0].time] = values; + } + if (animationCurve[animationCurve.length - 1].time <= maxTime) + { + Vector3 values2 = this.GetValues(animationCurve[animationCurve.length - 1].time, true); + this.points[animationCurve[animationCurve.length - 1].time] = values2; + this.points[this.rangeEnd] = values2; + } + for (int i = 0; i < animationCurve.length - 1; i++) + { + if (animationCurve[i + 1].time >= minTime && animationCurve[i].time <= maxTime) + { + float num = animationCurve[i].time; + this.points[num] = this.GetValues(num, true); + for (float num2 = 1f; num2 <= 20f; num2 += 1f) + { + num = Mathf.Lerp(this.quaternionX[i].time, animationCurve[i + 1].time, (num2 - 0.001f) / 40f); + this.points[num] = this.GetValues(num, false); + } + num = animationCurve[i + 1].time; + this.points[num] = this.GetValues(num, true); + for (float num3 = 1f; num3 <= 20f; num3 += 1f) + { + num = Mathf.Lerp(animationCurve[i].time, animationCurve[i + 1].time, 1f - (num3 - 0.001f) / 40f); + this.points[num] = this.GetValues(num, false); + } + } + } + } + public float EvaluateCurveDeltaSlow(float time, int component) + { + if (this.quaternionX == null) + { + return 0f; + } + return (this.EvaluateCurveSlow(time + 0.001f, component) - this.EvaluateCurveSlow(time - 0.001f, component)) / 0.002f; + } + public float EvaluateCurveSlow(float time, int component) + { + if (this.GetCurveOfComponent(component).length == 1) + { + return this.GetCurveOfComponent(component)[0].value; + } + if (time == this.cachedEvaluationTime) + { + return this.cachedEvaluationValue[component]; + } + if (time < this.cachedRangeStart || time > this.cachedRangeEnd) + { + this.CalculateCurves(this.rangeStart, this.rangeEnd); + this.cachedRangeStart = float.NegativeInfinity; + this.cachedRangeEnd = float.PositiveInfinity; + } + float[] array = new float[this.points.Count]; + Vector3[] array2 = new Vector3[this.points.Count]; + int num = 0; + foreach (KeyValuePair current in this.points) + { + array[num] = current.Key; + array2[num] = current.Value; + num++; + } + for (int i = 0; i < array.Length - 1; i++) + { + if (time < array[i + 1]) + { + float t = Mathf.InverseLerp(array[i], array[i + 1], time); + this.cachedEvaluationValue = Vector3.Lerp(array2[i], array2[i + 1], t); + this.cachedEvaluationTime = time; + return this.cachedEvaluationValue[component]; + } + } + if (array2.Length > 0) + { + return array2[array2.Length - 1][component]; + } + Debug.LogError("List of euler curve points is empty, probably caused by lack of euler curve key synching"); + return 0f; + } + public void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, int component, Color wrapColor) + { + if (minTime < this.cachedRangeStart || maxTime > this.cachedRangeEnd) + { + this.CalculateCurves(minTime, maxTime); + if (minTime <= this.rangeStart && maxTime >= this.rangeEnd) + { + this.cachedRangeStart = float.NegativeInfinity; + this.cachedRangeEnd = float.PositiveInfinity; + } + else + { + this.cachedRangeStart = minTime; + this.cachedRangeEnd = maxTime; + } + } + List list = new List(); + foreach (KeyValuePair current in this.points) + { + list.Add(new Vector3(current.Key, current.Value[component])); + } + NormalCurveRenderer.DrawCurveWrapped(minTime, maxTime, this.rangeStart, this.rangeEnd, this.preWrapMode, this.postWrapMode, color, transform, list.ToArray(), wrapColor); + } + public Bounds GetBounds(float minTime, float maxTime, int component) + { + this.CalculateCurves(minTime, maxTime); + float num = float.PositiveInfinity; + float num2 = float.NegativeInfinity; + foreach (KeyValuePair current in this.points) + { + if (current.Value[component] > num2) + { + num2 = current.Value[component]; + } + if (current.Value[component] < num) + { + num = current.Value[component]; + } + } + if (num == float.PositiveInfinity) + { + num = 0f; + num2 = 0f; + } + return new Bounds(new Vector3((maxTime + minTime) * 0.5f, (num2 + num) * 0.5f, 0f), new Vector3(maxTime - minTime, num2 - num, 0f)); + } + } +} diff --git a/UnityEditor/UnityEditor/EulerCurveRenderer.cs b/UnityEditor/UnityEditor/EulerCurveRenderer.cs new file mode 100644 index 00000000..4566f92f --- /dev/null +++ b/UnityEditor/UnityEditor/EulerCurveRenderer.cs @@ -0,0 +1,59 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class EulerCurveRenderer : CurveRenderer + { + private int component; + private EulerCurveCombinedRenderer renderer; + public EulerCurveRenderer(int component, EulerCurveCombinedRenderer renderer) + { + this.component = component; + this.renderer = renderer; + } + public AnimationCurve GetCurve() + { + return this.renderer.GetCurveOfComponent(this.component); + } + public float RangeStart() + { + return this.renderer.RangeStart(); + } + public float RangeEnd() + { + return this.renderer.RangeEnd(); + } + public void SetWrap(WrapMode wrap) + { + this.renderer.SetWrap(wrap); + } + public void SetWrap(WrapMode preWrapMode, WrapMode postWrapMode) + { + this.renderer.SetWrap(preWrapMode, postWrapMode); + } + public void SetCustomRange(float start, float end) + { + this.renderer.SetCustomRange(start, end); + } + public float EvaluateCurveSlow(float time) + { + return this.renderer.EvaluateCurveSlow(time, this.component); + } + public float EvaluateCurveDeltaSlow(float time) + { + return this.renderer.EvaluateCurveDeltaSlow(time, this.component); + } + public void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, Color wrapColor) + { + this.renderer.DrawCurve(minTime, maxTime, color, transform, this.component, wrapColor); + } + public Bounds GetBounds() + { + return this.GetBounds(this.renderer.RangeStart(), this.renderer.RangeEnd()); + } + public Bounds GetBounds(float minTime, float maxTime) + { + return this.renderer.GetBounds(minTime, maxTime, this.component); + } + } +} diff --git a/UnityEditor/UnityEditor/EventManipulationHandler.cs b/UnityEditor/UnityEditor/EventManipulationHandler.cs new file mode 100644 index 00000000..31856dd6 --- /dev/null +++ b/UnityEditor/UnityEditor/EventManipulationHandler.cs @@ -0,0 +1,222 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class EventManipulationHandler + { + private class EventModificationContextMenuObjet + { + public AnimationClipInfoProperties m_Info; + public float m_Time; + public int m_Index; + public EventModificationContextMenuObjet(AnimationClipInfoProperties info, float time, int index) + { + this.m_Info = info; + this.m_Time = time; + this.m_Index = index; + } + } + private Rect[] m_EventRects = new Rect[0]; + private static AnimationEvent[] m_EventsAtMouseDown; + private static float[] m_EventTimes; + private int m_HoverEvent = -1; + private string m_InstantTooltipText; + private Vector2 m_InstantTooltipPoint = Vector2.zero; + private bool[] m_EventsSelected; + private TimeArea m_Timeline; + public EventManipulationHandler(TimeArea timeArea) + { + this.m_Timeline = timeArea; + } + public void SelectEvent(AnimationEvent[] events, int index, AnimationClipInfoProperties clipInfo) + { + this.m_EventsSelected = new bool[events.Length]; + this.m_EventsSelected[index] = true; + AnimationEventPopup.Edit(clipInfo, index); + } + public bool HandleEventManipulation(Rect rect, ref AnimationEvent[] events, AnimationClipInfoProperties clipInfo) + { + Texture image = EditorGUIUtility.IconContent("Animation.EventMarker").image; + bool result = false; + Rect[] array = new Rect[events.Length]; + Rect[] array2 = new Rect[events.Length]; + int num = 1; + int num2 = 0; + for (int i = 0; i < events.Length; i++) + { + AnimationEvent animationEvent = events[i]; + if (num2 == 0) + { + num = 1; + while (i + num < events.Length && events[i + num].time == animationEvent.time) + { + num++; + } + num2 = num; + } + num2--; + float num3 = Mathf.Floor(this.m_Timeline.TimeToPixel(animationEvent.time, rect)); + int num4 = 0; + if (num > 1) + { + float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(1f / this.m_Timeline.PixelDeltaToTime(rect) - (float)(image.width * 2))); + num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2))); + } + Rect rect2 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height); + array[i] = rect2; + array2[i] = rect2; + } + this.m_EventRects = new Rect[array.Length]; + for (int j = 0; j < array.Length; j++) + { + this.m_EventRects[j] = new Rect(array[j].x + rect.x, array[j].y + rect.y, array[j].width, array[j].height); + } + if (this.m_EventsSelected == null || this.m_EventsSelected.Length != events.Length || this.m_EventsSelected.Length == 0) + { + this.m_EventsSelected = new bool[events.Length]; + AnimationEventPopup.ClosePopup(); + } + Vector2 zero = Vector2.zero; + int num6; + float num7; + float num8; + HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref this.m_EventsSelected, null, out num6, out zero, out num7, out num8, GUIStyleX.none); + if (highLevelEvent != HighLevelEvent.None) + { + switch (highLevelEvent) + { + case HighLevelEvent.ContextClick: + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), new EventManipulationHandler.EventModificationContextMenuObjet(clipInfo, events[num6].time, num6)); + genericMenu.AddItem(new GUIContent("Delete Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), new EventManipulationHandler.EventModificationContextMenuObjet(clipInfo, events[num6].time, num6)); + genericMenu.ShowAsContext(); + this.m_InstantTooltipText = null; + break; + } + case HighLevelEvent.BeginDrag: + EventManipulationHandler.m_EventsAtMouseDown = events; + EventManipulationHandler.m_EventTimes = new float[events.Length]; + for (int k = 0; k < events.Length; k++) + { + EventManipulationHandler.m_EventTimes[k] = events[k].time; + } + break; + case HighLevelEvent.Drag: + { + for (int l = events.Length - 1; l >= 0; l--) + { + if (this.m_EventsSelected[l]) + { + AnimationEvent animationEvent2 = EventManipulationHandler.m_EventsAtMouseDown[l]; + animationEvent2.time = Mathf.Clamp01(EventManipulationHandler.m_EventTimes[l] + zero.x / rect.width); + } + } + int[] array3 = new int[this.m_EventsSelected.Length]; + for (int m = 0; m < array3.Length; m++) + { + array3[m] = m; + } + Array.Sort(EventManipulationHandler.m_EventsAtMouseDown, array3, new AnimationEventTimeLine.EventComparer()); + bool[] array4 = (bool[])this.m_EventsSelected.Clone(); + float[] array5 = (float[])EventManipulationHandler.m_EventTimes.Clone(); + for (int n = 0; n < array3.Length; n++) + { + this.m_EventsSelected[n] = array4[array3[n]]; + EventManipulationHandler.m_EventTimes[n] = array5[array3[n]]; + } + events = EventManipulationHandler.m_EventsAtMouseDown; + result = true; + break; + } + case HighLevelEvent.Delete: + result = this.DeleteEvents(ref events, this.m_EventsSelected); + break; + case HighLevelEvent.SelectionChanged: + if (num6 >= 0) + { + AnimationEventPopup.Edit(clipInfo, num6); + } + else + { + AnimationEventPopup.ClosePopup(); + } + break; + } + } + this.CheckRectsOnMouseMove(rect, events, array); + return result; + } + public void EventLineContextMenuAdd(object obj) + { + EventManipulationHandler.EventModificationContextMenuObjet eventModificationContextMenuObjet = (EventManipulationHandler.EventModificationContextMenuObjet)obj; + eventModificationContextMenuObjet.m_Info.AddEvent(eventModificationContextMenuObjet.m_Time); + this.SelectEvent(eventModificationContextMenuObjet.m_Info.GetEvents(), eventModificationContextMenuObjet.m_Info.GetEventCount() - 1, eventModificationContextMenuObjet.m_Info); + } + public void EventLineContextMenuDelete(object obj) + { + EventManipulationHandler.EventModificationContextMenuObjet eventModificationContextMenuObjet = (EventManipulationHandler.EventModificationContextMenuObjet)obj; + eventModificationContextMenuObjet.m_Info.RemoveEvent(eventModificationContextMenuObjet.m_Index); + } + private void CheckRectsOnMouseMove(Rect eventLineRect, AnimationEvent[] events, Rect[] hitRects) + { + Vector2 mousePosition = Event.current.mousePosition; + bool flag = false; + this.m_InstantTooltipText = string.Empty; + if (events.Length == hitRects.Length) + { + for (int i = hitRects.Length - 1; i >= 0; i--) + { + if (hitRects[i].Contains(mousePosition)) + { + flag = true; + if (this.m_HoverEvent != i) + { + this.m_HoverEvent = i; + this.m_InstantTooltipText = events[this.m_HoverEvent].functionName; + this.m_InstantTooltipPoint = new Vector2(hitRects[this.m_HoverEvent].xMin + (float)((int)(hitRects[this.m_HoverEvent].width / 2f)) + eventLineRect.x, eventLineRect.yMax); + } + } + } + } + if (!flag) + { + this.m_HoverEvent = -1; + } + } + public void DrawInstantTooltip(Rect window) + { + if (this.m_InstantTooltipText != null && this.m_InstantTooltipText != string.Empty) + { + GUIStyle gUIStyle = "AnimationEventTooltip"; + Vector2 vector = gUIStyle.CalcSize(new GUIContent(this.m_InstantTooltipText)); + Rect position = new Rect(this.m_InstantTooltipPoint.x - vector.x * 0.5f + 30f, this.m_InstantTooltipPoint.y + 24f, vector.x, vector.y); + if (position.xMax > window.width) + { + position.x = window.width - position.width; + } + GUI.Label(position, this.m_InstantTooltipText, gUIStyle); + position = new Rect(this.m_InstantTooltipPoint.x - 30f, this.m_InstantTooltipPoint.y, 7f, 25f); + GUI.Label(position, string.Empty, "AnimationEventTooltipArrow"); + } + } + private bool DeleteEvents(ref AnimationEvent[] eventList, bool[] deleteIndices) + { + bool flag = false; + for (int i = eventList.Length - 1; i >= 0; i--) + { + if (deleteIndices[i]) + { + ArrayUtility.RemoveAt(ref eventList, i); + flag = true; + } + } + if (flag) + { + AnimationEventPopup.ClosePopup(); + this.m_EventsSelected = new bool[eventList.Length]; + } + return flag; + } + } +} diff --git a/UnityEditor/UnityEditor/ExportPackageOptions.cs b/UnityEditor/UnityEditor/ExportPackageOptions.cs new file mode 100644 index 00000000..302758ed --- /dev/null +++ b/UnityEditor/UnityEditor/ExportPackageOptions.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum ExportPackageOptions + { + Default = 0, + Interactive = 1, + Recurse = 2, + IncludeDependencies = 4, + IncludeLibraryAssets = 8 + } +} diff --git a/UnityEditor/UnityEditor/ExportRawHeightmap.cs b/UnityEditor/UnityEditor/ExportRawHeightmap.cs new file mode 100644 index 00000000..e5c665d4 --- /dev/null +++ b/UnityEditor/UnityEditor/ExportRawHeightmap.cs @@ -0,0 +1,112 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class ExportRawHeightmap : TerrainWizard + { + internal enum Depth + { + Bit8 = 1, + Bit16 + } + internal enum ByteOrder + { + Mac = 1, + Windows + } + public ExportRawHeightmap.Depth m_Depth = ExportRawHeightmap.Depth.Bit16; + public ExportRawHeightmap.ByteOrder m_ByteOrder = ExportRawHeightmap.ByteOrder.Mac; + public void OnEnable() + { + base.minSize = new Vector2(400f, 200f); + } + internal void OnWizardCreate() + { + if (this.m_Terrain == null) + { + base.isValid = false; + base.errorString = "Terrain does not exist"; + } + string text = EditorUtility.SaveFilePanel("Save Raw Heightmap", string.Empty, "terrain", "raw"); + if (text != string.Empty) + { + this.WriteRaw(text); + } + } + internal override void OnWizardUpdate() + { + base.OnWizardUpdate(); + if (base.terrainData) + { + base.helpString = string.Concat(new object[] + { + "Width ", + base.terrainData.heightmapWidth, + "\nHeight ", + base.terrainData.heightmapHeight + }); + } + } + private void WriteRaw(string path) + { + int heightmapWidth = base.terrainData.heightmapWidth; + int heightmapHeight = base.terrainData.heightmapHeight; + float[,] heights = base.terrainData.GetHeights(0, 0, heightmapWidth, heightmapHeight); + byte[] array = new byte[heightmapWidth * heightmapHeight * (int)this.m_Depth]; + if (this.m_Depth == ExportRawHeightmap.Depth.Bit16) + { + float num = 65536f; + for (int i = 0; i < heightmapHeight; i++) + { + for (int j = 0; j < heightmapWidth; j++) + { + int num2 = j + i * heightmapWidth; + int value = Mathf.RoundToInt(heights[i, j] * num); + ushort value2 = (ushort)Mathf.Clamp(value, 0, 65535); + byte[] bytes = BitConverter.GetBytes(value2); + if (this.m_ByteOrder == ExportRawHeightmap.ByteOrder.Mac == BitConverter.IsLittleEndian) + { + array[num2 * 2] = bytes[1]; + array[num2 * 2 + 1] = bytes[0]; + } + else + { + array[num2 * 2] = bytes[0]; + array[num2 * 2 + 1] = bytes[1]; + } + } + } + } + else + { + float num3 = 256f; + for (int k = 0; k < heightmapHeight; k++) + { + for (int l = 0; l < heightmapWidth; l++) + { + int num4 = l + k * heightmapWidth; + int value3 = Mathf.RoundToInt(heights[k, l] * num3); + byte b = (byte)Mathf.Clamp(value3, 0, 255); + array[num4] = b; + } + } + } + FileStream fileStream = new FileStream(path, FileMode.Create); + fileStream.Write(array, 0, array.Length); + fileStream.Close(); + } + private new void InitializeDefaults(Terrain terrain) + { + this.m_Terrain = terrain; + base.helpString = string.Concat(new object[] + { + "Width ", + terrain.terrainData.heightmapWidth, + " Height ", + terrain.terrainData.heightmapHeight + }); + this.OnWizardUpdate(); + } + } +} diff --git a/UnityEditor/UnityEditor/ExposablePopupMenu.cs b/UnityEditor/UnityEditor/ExposablePopupMenu.cs new file mode 100644 index 00000000..369970f1 --- /dev/null +++ b/UnityEditor/UnityEditor/ExposablePopupMenu.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ExposablePopupMenu + { + public class ItemData + { + public GUIContent m_GUIContent; + public GUIStyle m_Style; + public bool m_On; + public bool m_Enabled; + public object m_UserData; + public float m_Width; + public ItemData(GUIContent content, GUIStyle style, bool on, bool enabled, object userData) + { + this.m_GUIContent = content; + this.m_Style = style; + this.m_On = on; + this.m_Enabled = enabled; + this.m_UserData = userData; + } + } + public class PopupButtonData + { + public GUIContent m_GUIContent; + public GUIStyle m_Style; + public PopupButtonData(GUIContent content, GUIStyle style) + { + this.m_GUIContent = content; + this.m_Style = style; + } + } + internal class PopUpMenu + { + private static List m_Data; + private static ExposablePopupMenu m_Caller; + internal static void Show(Rect activatorRect, List buttonData, ExposablePopupMenu caller) + { + ExposablePopupMenu.PopUpMenu.m_Data = buttonData; + ExposablePopupMenu.PopUpMenu.m_Caller = caller; + GenericMenu genericMenu = new GenericMenu(); + foreach (ExposablePopupMenu.ItemData current in ExposablePopupMenu.PopUpMenu.m_Data) + { + if (current.m_Enabled) + { + genericMenu.AddItem(current.m_GUIContent, current.m_On, new GenericMenu.MenuFunction2(ExposablePopupMenu.PopUpMenu.SelectionCallback), current); + } + else + { + genericMenu.AddDisabledItem(current.m_GUIContent); + } + } + genericMenu.DropDown(activatorRect); + } + private static void SelectionCallback(object userData) + { + ExposablePopupMenu.ItemData item = (ExposablePopupMenu.ItemData)userData; + ExposablePopupMenu.PopUpMenu.m_Caller.SelectionChanged(item); + ExposablePopupMenu.PopUpMenu.m_Caller = null; + ExposablePopupMenu.PopUpMenu.m_Data = null; + } + } + private List m_Items; + private float m_WidthOfButtons; + private float m_ItemSpacing; + private ExposablePopupMenu.PopupButtonData m_PopupButtonData; + private float m_WidthOfPopup; + private float m_MinWidthOfPopup; + private Action m_SelectionChangedCallback; + public void Init(List items, float itemSpacing, float minWidthOfPopup, ExposablePopupMenu.PopupButtonData popupButtonData, Action selectionChangedCallback) + { + this.m_Items = items; + this.m_ItemSpacing = itemSpacing; + this.m_PopupButtonData = popupButtonData; + this.m_SelectionChangedCallback = selectionChangedCallback; + this.m_MinWidthOfPopup = minWidthOfPopup; + this.CalcWidths(); + } + public float OnGUI(Rect rect) + { + if (rect.width >= this.m_WidthOfButtons && rect.width > this.m_MinWidthOfPopup) + { + Rect position = rect; + foreach (ExposablePopupMenu.ItemData current in this.m_Items) + { + position.width = current.m_Width; + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginDisabledGroup(!current.m_Enabled); + GUI.Toggle(position, current.m_On, current.m_GUIContent, current.m_Style); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + this.SelectionChanged(current); + GUIUtility.ExitGUI(); + } + position.x += current.m_Width + this.m_ItemSpacing; + } + return this.m_WidthOfButtons; + } + if (this.m_WidthOfPopup < rect.width) + { + rect.width = this.m_WidthOfPopup; + } + if (EditorGUI.ButtonMouseDown(rect, this.m_PopupButtonData.m_GUIContent, FocusType.Passive, this.m_PopupButtonData.m_Style)) + { + ExposablePopupMenu.PopUpMenu.Show(rect, this.m_Items, this); + } + return this.m_WidthOfPopup; + } + private void CalcWidths() + { + this.m_WidthOfButtons = 0f; + foreach (ExposablePopupMenu.ItemData current in this.m_Items) + { + current.m_Width = current.m_Style.CalcSize(current.m_GUIContent).x; + this.m_WidthOfButtons += current.m_Width; + } + this.m_WidthOfButtons += (float)(this.m_Items.Count - 1) * this.m_ItemSpacing; + Vector2 vector = this.m_PopupButtonData.m_Style.CalcSize(this.m_PopupButtonData.m_GUIContent); + vector.x += 3f; + this.m_WidthOfPopup = vector.x; + } + private void SelectionChanged(ExposablePopupMenu.ItemData item) + { + if (this.m_SelectionChangedCallback != null) + { + this.m_SelectionChangedCallback(item); + } + else + { + Debug.LogError("Callback is null"); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ExposeTransformEditor.cs b/UnityEditor/UnityEditor/ExposeTransformEditor.cs new file mode 100644 index 00000000..f77273c9 --- /dev/null +++ b/UnityEditor/UnityEditor/ExposeTransformEditor.cs @@ -0,0 +1,61 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ExposeTransformEditor + { + private ReorderableList m_ExtraExposedTransformList; + private string[] m_TransformPaths; + private SerializedProperty m_ExtraExposedTransformPaths; + public void OnEnable(string[] transformPaths, SerializedObject serializedObject) + { + this.m_TransformPaths = transformPaths; + this.m_ExtraExposedTransformPaths = serializedObject.FindProperty("m_ExtraExposedTransformPaths"); + if (this.m_ExtraExposedTransformList == null) + { + this.m_ExtraExposedTransformList = new ReorderableList(serializedObject, this.m_ExtraExposedTransformPaths, false, true, true, true); + this.m_ExtraExposedTransformList.onAddDropdownCallback = new ReorderableList.AddDropdownCallbackDelegate(this.AddTransformPathInList); + this.m_ExtraExposedTransformList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveTransformPathInList); + this.m_ExtraExposedTransformList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawTransformPathElement); + this.m_ExtraExposedTransformList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawTransformPathListHeader); + this.m_ExtraExposedTransformList.elementHeight = 16f; + } + } + public void OnGUI() + { + this.m_ExtraExposedTransformList.DoLayoutList(); + } + private void TransformPathSelected(object userData, string[] options, int selected) + { + string b = options[selected]; + for (int i = 0; i < this.m_ExtraExposedTransformPaths.arraySize; i++) + { + string stringValue = this.m_ExtraExposedTransformPaths.GetArrayElementAtIndex(i).stringValue; + if (stringValue == b) + { + return; + } + } + this.m_ExtraExposedTransformPaths.InsertArrayElementAtIndex(this.m_ExtraExposedTransformPaths.arraySize); + this.m_ExtraExposedTransformPaths.GetArrayElementAtIndex(this.m_ExtraExposedTransformPaths.arraySize - 1).stringValue = options[selected]; + } + private void AddTransformPathInList(Rect rect, ReorderableList list) + { + EditorUtility.DisplayCustomMenu(rect, this.m_TransformPaths, null, new EditorUtility.SelectMenuItemFunction(this.TransformPathSelected), null); + } + private void RemoveTransformPathInList(ReorderableList list) + { + this.m_ExtraExposedTransformPaths.DeleteArrayElementAtIndex(list.index); + } + private void DrawTransformPathElement(Rect rect, int index, bool selected, bool focused) + { + string stringValue = this.m_ExtraExposedTransformPaths.GetArrayElementAtIndex(index).stringValue; + GUI.Label(rect, stringValue.Substring(stringValue.LastIndexOf("/") + 1), EditorStyles.label); + } + private void DrawTransformPathListHeader(Rect rect) + { + GUI.Label(rect, "Extra Transforms to Expose", EditorStyles.label); + } + } +} diff --git a/UnityEditor/UnityEditor/ExternalForcesModuleUI.cs b/UnityEditor/UnityEditor/ExternalForcesModuleUI.cs new file mode 100644 index 00000000..f4df9858 --- /dev/null +++ b/UnityEditor/UnityEditor/ExternalForcesModuleUI.cs @@ -0,0 +1,42 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ExternalForcesModuleUI : ModuleUI + { + private class Texts + { + public GUIContent multiplier = new GUIContent("Multiplier", "Used to scale the force applied to this particle system."); + } + private SerializedProperty m_Multiplier; + private static ExternalForcesModuleUI.Texts s_Texts; + public ExternalForcesModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ExternalForcesModule", displayName) + { + this.m_ToolTip = "Controls the wind zones that each particle is affected by."; + } + protected override void Init() + { + if (this.m_Multiplier != null) + { + return; + } + if (ExternalForcesModuleUI.s_Texts == null) + { + ExternalForcesModuleUI.s_Texts = new ExternalForcesModuleUI.Texts(); + } + this.m_Multiplier = base.GetProperty("multiplier"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (ExternalForcesModuleUI.s_Texts == null) + { + ExternalForcesModuleUI.s_Texts = new ExternalForcesModuleUI.Texts(); + } + ModuleUI.GUIFloat(ExternalForcesModuleUI.s_Texts.multiplier, this.m_Multiplier); + } + public override void UpdateCullingSupportedString(ref string text) + { + text += "\n\tExternal Forces is enabled."; + } + } +} diff --git a/UnityEditor/UnityEditor/ExternalVersionControl.cs b/UnityEditor/UnityEditor/ExternalVersionControl.cs new file mode 100644 index 00000000..91ce0661 --- /dev/null +++ b/UnityEditor/UnityEditor/ExternalVersionControl.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEditor +{ + public struct ExternalVersionControl + { + private string m_Value; + public static readonly string Disabled = "Hidden Meta Files"; + public static readonly string AutoDetect = "Auto detect"; + public static readonly string Generic = "Visible Meta Files"; + public static readonly string AssetServer = "Asset Server"; + public ExternalVersionControl(string value) + { + this.m_Value = value; + } + public override string ToString() + { + return this.m_Value; + } + public static implicit operator string(ExternalVersionControl d) + { + return d.ToString(); + } + public static implicit operator ExternalVersionControl(string d) + { + return new ExternalVersionControl(d); + } + } +} diff --git a/UnityEditor/UnityEditor/EyeDropper.cs b/UnityEditor/UnityEditor/EyeDropper.cs new file mode 100644 index 00000000..cc6c7939 --- /dev/null +++ b/UnityEditor/UnityEditor/EyeDropper.cs @@ -0,0 +1,153 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class EyeDropper : GUIView + { + private class Styles + { + public GUIStyle eyeDropperHorizontalLine = "EyeDropperHorizontalLine"; + public GUIStyle eyeDropperVerticalLine = "EyeDropperVerticalLine"; + public GUIStyle eyeDropperPickedPixel = "EyeDropperPickedPixel"; + } + private const int kPixelSize = 10; + private const int kDummyWindowSize = 10000; + internal static Color s_LastPickedColor; + private GUIView m_DelegateView; + private Texture2D m_Preview; + private static EyeDropper s_Instance; + private static Vector2 s_PickCoordinates = Vector2.zero; + private static EyeDropper.Styles styles; + private static EyeDropper get + { + get + { + if (!EyeDropper.s_Instance) + { + ScriptableObject.CreateInstance(); + } + return EyeDropper.s_Instance; + } + } + private EyeDropper() + { + EyeDropper.s_Instance = this; + } + public static void Start(GUIView viewToUpdate) + { + EyeDropper.get.Show(viewToUpdate); + } + private void Show(GUIView sourceView) + { + this.m_DelegateView = sourceView; + ContainerWindow containerWindow = ScriptableObject.CreateInstance(); + containerWindow.m_DontSaveToLayout = true; + containerWindow.title = "EyeDropper"; + containerWindow.hideFlags = HideFlags.DontSave; + containerWindow.mainView = this; + containerWindow.Show(ShowMode.PopupMenu, true, false); + base.AddToAuxWindowList(); + containerWindow.SetInvisible(); + base.SetMinMaxSizes(new Vector2(0f, 0f), new Vector2(10000f, 10000f)); + containerWindow.position = new Rect(-5000f, -5000f, 10000f, 10000f); + base.wantsMouseMove = true; + base.StealMouseCapture(); + } + public static Color GetPickedColor() + { + return InternalEditorUtility.ReadScreenPixel(EyeDropper.s_PickCoordinates, 1, 1)[0]; + } + public static Color GetLastPickedColor() + { + return EyeDropper.s_LastPickedColor; + } + public static void DrawPreview(Rect position) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (EyeDropper.styles == null) + { + EyeDropper.styles = new EyeDropper.Styles(); + } + Texture2D texture2D = EyeDropper.get.m_Preview; + int num = (int)Mathf.Ceil(position.width / 10f); + int num2 = (int)Mathf.Ceil(position.height / 10f); + if (texture2D == null) + { + texture2D = (EyeDropper.get.m_Preview = ColorPicker.MakeTexture(num, num2)); + texture2D.filterMode = FilterMode.Point; + } + if (texture2D.width != num || texture2D.height != num2) + { + texture2D.Resize(num, num2); + } + Vector2 a = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); + Vector2 pixelPos = a - new Vector2((float)(num / 2), (float)(num2 / 2)); + texture2D.SetPixels(InternalEditorUtility.ReadScreenPixel(pixelPos, num, num2), 0); + texture2D.Apply(true); + Graphics.DrawTexture(position, texture2D); + float num3 = position.width / (float)num; + GUIStyle gUIStyle = EyeDropper.styles.eyeDropperVerticalLine; + for (float num4 = position.x; num4 < position.xMax; num4 += num3) + { + Rect position2 = new Rect(Mathf.Round(num4), position.y, num3, position.height); + gUIStyle.Draw(position2, false, false, false, false); + } + float num5 = position.height / (float)num2; + gUIStyle = EyeDropper.styles.eyeDropperHorizontalLine; + for (float num6 = position.y; num6 < position.yMax; num6 += num5) + { + Rect position3 = new Rect(position.x, Mathf.Floor(num6), position.width, num5); + gUIStyle.Draw(position3, false, false, false, false); + } + Rect position4 = new Rect((a.x - pixelPos.x) * num3 + position.x, (a.y - pixelPos.y) * num5 + position.y, num3, num5); + EyeDropper.styles.eyeDropperPickedPixel.Draw(position4, false, false, false, false); + } + private void OnGUI() + { + switch (Event.current.type) + { + case EventType.MouseDown: + if (Event.current.button == 0) + { + EyeDropper.s_PickCoordinates = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); + EyeDropper.s_LastPickedColor = EyeDropper.GetPickedColor(); + base.window.Close(); + this.SendEvent("EyeDropperClicked"); + } + break; + case EventType.MouseMove: + EyeDropper.s_PickCoordinates = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); + base.StealMouseCapture(); + this.SendEvent("EyeDropperUpdate"); + break; + case EventType.KeyDown: + if (Event.current.keyCode == KeyCode.Escape) + { + base.window.Close(); + this.SendEvent("EyeDropperCancelled"); + } + break; + } + } + private void SendEvent(string eventName) + { + if (this.m_DelegateView) + { + Event e = EditorGUIUtility.CommandEvent(eventName); + this.m_DelegateView.SendEvent(e); + GUIUtility.ExitGUI(); + } + } + public new void OnDestroy() + { + if (this.m_Preview) + { + UnityEngine.Object.DestroyImmediate(this.m_Preview); + } + } + } +} diff --git a/UnityEditor/UnityEditor/FallbackEditorWindow.cs b/UnityEditor/UnityEditor/FallbackEditorWindow.cs new file mode 100644 index 00000000..cbb80605 --- /dev/null +++ b/UnityEditor/UnityEditor/FallbackEditorWindow.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class FallbackEditorWindow : EditorWindow + { + private FallbackEditorWindow() + { + base.title = "Failed to load"; + } + private void OnEnable() + { + base.title = "Failed to load"; + } + private void OnGUI() + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label("EditorWindow could not be loaded because the script is not found in the project", "WordWrapLabel", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.EndVertical(); + } + } +} diff --git a/UnityEditor/UnityEditor/FilePathAttribute.cs b/UnityEditor/UnityEditor/FilePathAttribute.cs new file mode 100644 index 00000000..220ebe46 --- /dev/null +++ b/UnityEditor/UnityEditor/FilePathAttribute.cs @@ -0,0 +1,40 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Class)] + internal class FilePathAttribute : Attribute + { + public enum Location + { + PreferencesFolder, + ProjectFolder + } + public string filepath + { + get; + set; + } + public FilePathAttribute(string relativePath, FilePathAttribute.Location location) + { + if (string.IsNullOrEmpty(relativePath)) + { + Debug.LogError("Invalid relative path! (its null or empty)"); + return; + } + if (relativePath[0] == '/') + { + relativePath = relativePath.Substring(1); + } + if (location == FilePathAttribute.Location.PreferencesFolder) + { + this.filepath = InternalEditorUtility.unityPreferencesFolder + "/" + relativePath; + } + else + { + this.filepath = relativePath; + } + } + } +} diff --git a/UnityEditor/UnityEditor/FileUtil.cs b/UnityEditor/UnityEditor/FileUtil.cs new file mode 100644 index 00000000..5906dfc9 --- /dev/null +++ b/UnityEditor/UnityEditor/FileUtil.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + public sealed class FileUtil + { + internal static ArrayList ReadAllText(string path) + { + ArrayList arrayList = new ArrayList(); + using (StreamReader streamReader = File.OpenText(FileUtil.NiceWinPath(path))) + { + string value = string.Empty; + while ((value = streamReader.ReadLine()) != null) + { + arrayList.Add(value); + } + } + return arrayList; + } + internal static void WriteAllText(string path, ArrayList strings) + { + StreamWriter streamWriter = new StreamWriter(FileUtil.NiceWinPath(path)); + foreach (string value in strings) + { + streamWriter.WriteLine(value); + } + streamWriter.Close(); + } + internal static void ReplaceText(string path, params string[] input) + { + ArrayList arrayList = FileUtil.ReadAllText(path); + for (int i = 0; i < input.Length; i += 2) + { + for (int j = 0; j < arrayList.Count; j++) + { + string text = (string)arrayList[j]; + arrayList[j] = text.Replace(input[i], input[i + 1]); + } + } + FileUtil.WriteAllText(path, arrayList); + } + internal static bool ReplaceTextRegex(string path, params string[] input) + { + bool result = false; + ArrayList arrayList = FileUtil.ReadAllText(path); + for (int i = 0; i < input.Length; i += 2) + { + for (int j = 0; j < arrayList.Count; j++) + { + string text = (string)arrayList[j]; + arrayList[j] = Regex.Replace(text, input[i], input[i + 1]); + if (text != (string)arrayList[j]) + { + result = true; + } + } + } + FileUtil.WriteAllText(path, arrayList); + return result; + } + internal static bool AppendTextAfter(string path, string find, string append) + { + bool result = false; + ArrayList arrayList = FileUtil.ReadAllText(path); + for (int i = 0; i < arrayList.Count; i++) + { + if (((string)arrayList[i]).IndexOf(find) > -1) + { + arrayList.Insert(i + 1, append); + result = true; + break; + } + } + FileUtil.WriteAllText(path, arrayList); + return result; + } + internal static void CopyDirectoryRecursive(string source, string target) + { + FileUtil.CopyDirectoryRecursive(source, target, false, false); + } + internal static void CopyDirectoryRecursiveIgnoreMeta(string source, string target) + { + FileUtil.CopyDirectoryRecursive(source, target, false, true); + } + internal static void CopyDirectoryRecursive(string source, string target, bool overwrite) + { + FileUtil.CopyDirectoryRecursive(source, target, overwrite, false); + } + internal static void CopyDirectory(string source, string target, bool overwrite) + { + FileUtil.CopyDirectoryFiltered(source, target, overwrite, (string f) => true, false); + } + internal static void CopyDirectoryRecursive(string source, string target, bool overwrite, bool ignoreMeta) + { + FileUtil.CopyDirectoryRecursiveFiltered(source, target, overwrite, (!ignoreMeta) ? null : "\\.meta$"); + } + internal static void CopyDirectoryRecursiveForPostprocess(string source, string target, bool overwrite) + { + FileUtil.CopyDirectoryRecursiveFiltered(source, target, overwrite, ".*/\\.+|\\.meta$"); + } + internal static void CopyDirectoryRecursiveFiltered(string source, string target, bool overwrite, string regExExcludeFilter) + { + FileUtil.CopyDirectoryFiltered(source, target, overwrite, regExExcludeFilter, true); + } + internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive) + { + Regex exclude = null; + try + { + if (regExExcludeFilter != null) + { + exclude = new Regex(regExExcludeFilter); + } + } + catch (ArgumentException) + { + Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files."); + return; + } + Func includeCallback = (string file) => exclude == null || !exclude.IsMatch(file); + FileUtil.CopyDirectoryFiltered(source, target, overwrite, includeCallback, recursive); + } + internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, Func includeCallback, bool recursive) + { + if (!Directory.Exists(target)) + { + Directory.CreateDirectory(target); + overwrite = false; + } + string[] files = Directory.GetFiles(source); + for (int i = 0; i < files.Length; i++) + { + string text = files[i]; + if (includeCallback(text)) + { + string fileName = Path.GetFileName(text); + string to = Path.Combine(target, fileName); + FileUtil.UnityFileCopy(text, to, overwrite); + } + } + if (!recursive) + { + return; + } + string[] directories = Directory.GetDirectories(source); + for (int j = 0; j < directories.Length; j++) + { + string text2 = directories[j]; + if (includeCallback(text2)) + { + string fileName2 = Path.GetFileName(text2); + FileUtil.CopyDirectoryFiltered(Path.Combine(source, fileName2), Path.Combine(target, fileName2), overwrite, includeCallback, recursive); + } + } + } + internal static void UnityDirectoryDelete(string path) + { + FileUtil.UnityDirectoryDelete(path, false); + } + internal static void UnityDirectoryDelete(string path, bool recursive) + { + Directory.Delete(FileUtil.NiceWinPath(path), recursive); + } + internal static void MoveFileIfExists(string src, string dst) + { + if (File.Exists(src)) + { + FileUtil.DeleteFileOrDirectory(dst); + FileUtil.MoveFileOrDirectory(src, dst); + File.SetLastWriteTime(dst, DateTime.Now); + } + } + internal static void CopyFileIfExists(string src, string dst, bool overwrite) + { + if (File.Exists(src)) + { + FileUtil.UnityFileCopy(src, dst, overwrite); + } + } + internal static void UnityFileCopy(string from, string to, bool overwrite) + { + File.Copy(FileUtil.NiceWinPath(from), FileUtil.NiceWinPath(to), overwrite); + } + internal static string NiceWinPath(string unityPath) + { + return (Application.platform != RuntimePlatform.WindowsEditor) ? unityPath : unityPath.Replace("/", "\\"); + } + internal static string UnityGetFileNameWithoutExtension(string path) + { + return Path.GetFileNameWithoutExtension(path.Replace("//", "\\\\")).Replace("\\\\", "//"); + } + internal static string UnityGetFileName(string path) + { + return Path.GetFileName(path.Replace("//", "\\\\")).Replace("\\\\", "//"); + } + internal static string UnityGetDirectoryName(string path) + { + return Path.GetDirectoryName(path.Replace("//", "\\\\")).Replace("\\\\", "//"); + } + internal static void UnityFileCopy(string from, string to) + { + FileUtil.UnityFileCopy(from, to, false); + } + internal static void CreateOrCleanDirectory(string dir) + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, true); + } + Directory.CreateDirectory(dir); + } + internal static string RemovePathPrefix(string fullPath, string prefix) + { + string[] array = fullPath.Split(new char[] + { + Path.DirectorySeparatorChar + }); + string[] array2 = prefix.Split(new char[] + { + Path.DirectorySeparatorChar + }); + int num = 0; + if (array[0] == string.Empty) + { + num = 1; + } + while (num < array.Length && num < array2.Length && array[num] == array2[num]) + { + num++; + } + if (num == array.Length) + { + return string.Empty; + } + return string.Join(Path.DirectorySeparatorChar.ToString(), array, num, array.Length - num); + } + internal static string CombinePaths(params string[] paths) + { + if (paths == null) + { + return string.Empty; + } + return string.Join(Path.DirectorySeparatorChar.ToString(), paths); + } + internal static List GetAllFilesRecursive(string path) + { + List files = new List(); + FileUtil.WalkFilesystemRecursively(path, delegate(string p) + { + files.Add(p); + }, (string p) => true); + return files; + } + internal static void WalkFilesystemRecursively(string path, Action fileCallback, Func directoryCallback) + { + string[] files = Directory.GetFiles(path); + for (int i = 0; i < files.Length; i++) + { + string obj = files[i]; + fileCallback(obj); + } + string[] directories = Directory.GetDirectories(path); + for (int j = 0; j < directories.Length; j++) + { + string text = directories[j]; + if (directoryCallback(text)) + { + FileUtil.WalkFilesystemRecursively(text, fileCallback, directoryCallback); + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DeleteFileOrDirectory(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyFileOrDirectory(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyFileOrDirectoryFollowSymlinks(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MoveFileOrDirectory(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUniqueTempPathInProject(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetActualPathName(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetProjectRelativePath(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetLastPathNameComponent(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string DeleteLastPathNameComponent(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPathExtension(string path); + public static void ReplaceFile(string src, string dst) + { + if (File.Exists(dst)) + { + FileUtil.DeleteFileOrDirectory(dst); + } + FileUtil.CopyFileOrDirectory(src, dst); + } + public static void ReplaceDirectory(string src, string dst) + { + if (Directory.Exists(dst)) + { + FileUtil.DeleteFileOrDirectory(dst); + } + FileUtil.CopyFileOrDirectory(src, dst); + } + } +} diff --git a/UnityEditor/UnityEditor/FilteredHierarchy.cs b/UnityEditor/UnityEditor/FilteredHierarchy.cs new file mode 100644 index 00000000..1e4f3702 --- /dev/null +++ b/UnityEditor/UnityEditor/FilteredHierarchy.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class FilteredHierarchy + { + public class FilterResult + { + public int instanceID; + public string name; + public bool hasChildren; + public int colorCode; + public bool isMainRepresentation; + public bool hasFullPreviewImage; + public IconDrawStyle iconDrawStyle; + public bool isFolder; + public HierarchyType type; + private Texture2D m_Icon; + public Texture2D icon + { + get + { + if (this.m_Icon == null && this.type == HierarchyType.Assets) + { + string assetPath = AssetDatabase.GetAssetPath(this.instanceID); + if (assetPath != null) + { + return AssetDatabase.GetCachedIcon(assetPath) as Texture2D; + } + } + return this.m_Icon; + } + set + { + this.m_Icon = value; + } + } + public string guid + { + get + { + if (this.type == HierarchyType.Assets) + { + string assetPath = AssetDatabase.GetAssetPath(this.instanceID); + if (assetPath != null) + { + return AssetDatabase.AssetPathToGUID(assetPath); + } + } + return null; + } + } + } + private SearchFilter m_SearchFilter = new SearchFilter(); + private FilteredHierarchy.FilterResult[] m_Results = new FilteredHierarchy.FilterResult[0]; + private FilteredHierarchy.FilterResult[] m_VisibleItems = new FilteredHierarchy.FilterResult[0]; + private HierarchyType m_HierarchyType; + public HierarchyType hierarchyType + { + get + { + return this.m_HierarchyType; + } + } + public FilteredHierarchy.FilterResult[] results + { + get + { + if (this.m_VisibleItems.Length > 0) + { + return this.m_VisibleItems; + } + return this.m_Results; + } + } + public SearchFilter searchFilter + { + get + { + return this.m_SearchFilter; + } + set + { + if (this.m_SearchFilter.SetNewFilter(value)) + { + this.ResultsChanged(); + } + } + } + public bool foldersFirst + { + get; + set; + } + public FilteredHierarchy(HierarchyType type) + { + this.m_HierarchyType = type; + } + public void SetResults(int[] instanceIDs) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + hierarchyProperty.Reset(); + Array.Resize(ref this.m_Results, instanceIDs.Length); + for (int i = 0; i < instanceIDs.Length; i++) + { + if (hierarchyProperty.Find(instanceIDs[i], null)) + { + this.CopyPropertyData(ref this.m_Results[i], hierarchyProperty); + } + } + } + private void CopyPropertyData(ref FilteredHierarchy.FilterResult result, HierarchyProperty property) + { + if (result == null) + { + result = new FilteredHierarchy.FilterResult(); + } + result.instanceID = property.instanceID; + result.name = property.name; + result.hasChildren = property.hasChildren; + result.colorCode = property.colorCode; + result.isMainRepresentation = property.isMainRepresentation; + result.hasFullPreviewImage = property.hasFullPreviewImage; + result.iconDrawStyle = property.iconDrawStyle; + result.isFolder = property.isFolder; + result.type = this.hierarchyType; + if (!property.isMainRepresentation) + { + result.icon = property.icon; + } + else + { + if (property.isFolder && !property.hasChildren) + { + result.icon = EditorGUIUtility.FindTexture(EditorResourcesUtility.emptyFolderIconName); + } + else + { + result.icon = null; + } + } + } + private void SearchAllAssets(HierarchyProperty property) + { + int num = property.CountRemaining(null); + num = Mathf.Min(num, 3000); + property.Reset(); + int num2 = this.m_Results.Length; + Array.Resize(ref this.m_Results, this.m_Results.Length + num); + while (property.Next(null) && num2 < this.m_Results.Length) + { + this.CopyPropertyData(ref this.m_Results[num2], property); + num2++; + } + } + private void SearchInFolders(HierarchyProperty property) + { + List list = new List(); + string[] baseFolders = ProjectWindowUtil.GetBaseFolders(this.m_SearchFilter.folders); + string[] array = baseFolders; + for (int i = 0; i < array.Length; i++) + { + string assetPath = array[i]; + property.SetSearchFilter(new SearchFilter()); + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(assetPath); + if (property.Find(mainAssetInstanceID, null)) + { + property.SetSearchFilter(this.m_SearchFilter); + int depth = property.depth; + int[] expanded = null; + while (property.NextWithDepthCheck(expanded, depth + 1)) + { + FilteredHierarchy.FilterResult item = new FilteredHierarchy.FilterResult(); + this.CopyPropertyData(ref item, property); + list.Add(item); + } + } + } + this.m_Results = list.ToArray(); + } + private void FolderBrowsing(HierarchyProperty property) + { + List list = new List(); + string[] folders = this.m_SearchFilter.folders; + for (int i = 0; i < folders.Length; i++) + { + string assetPath = folders[i]; + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(assetPath); + if (property.Find(mainAssetInstanceID, null)) + { + int depth = property.depth; + int[] array = new int[] + { + mainAssetInstanceID + }; + while (property.Next(array)) + { + if (property.depth <= depth) + { + break; + } + FilteredHierarchy.FilterResult item = new FilteredHierarchy.FilterResult(); + this.CopyPropertyData(ref item, property); + list.Add(item); + if (property.hasChildren && !property.isFolder) + { + Array.Resize(ref array, array.Length + 1); + array[array.Length - 1] = property.instanceID; + } + } + } + } + this.m_Results = list.ToArray(); + } + private void AddResults(HierarchyProperty property) + { + switch (this.m_SearchFilter.GetState()) + { + case SearchFilter.State.EmptySearchFilter: + break; + case SearchFilter.State.FolderBrowsing: + this.FolderBrowsing(property); + break; + case SearchFilter.State.SearchingInAllAssets: + this.SearchAllAssets(property); + break; + case SearchFilter.State.SearchingInFolders: + this.SearchInFolders(property); + break; + case SearchFilter.State.SearchingInAssetStore: + break; + default: + Debug.LogError("Unhandled enum!"); + break; + } + } + public void ResultsChanged() + { + this.m_Results = new FilteredHierarchy.FilterResult[0]; + if (this.m_SearchFilter.GetState() != SearchFilter.State.EmptySearchFilter) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); + hierarchyProperty.SetSearchFilter(this.m_SearchFilter); + this.AddResults(hierarchyProperty); + if (this.m_SearchFilter.IsSearching()) + { + Array.Sort(this.m_Results, (FilteredHierarchy.FilterResult result1, FilteredHierarchy.FilterResult result2) => EditorUtility.NaturalCompare(result1.name, result2.name)); + } + if (this.foldersFirst) + { + for (int i = 0; i < this.m_Results.Length; i++) + { + if (!this.m_Results[i].isFolder) + { + for (int j = i + 1; j < this.m_Results.Length; j++) + { + if (this.m_Results[j].isFolder) + { + FilteredHierarchy.FilterResult filterResult = this.m_Results[j]; + int length = j - i; + Array.Copy(this.m_Results, i, this.m_Results, i + 1, length); + this.m_Results[i] = filterResult; + break; + } + } + } + } + } + } + else + { + if (this.m_HierarchyType == HierarchyType.GameObjects) + { + HierarchyProperty hierarchyProperty2 = new HierarchyProperty(HierarchyType.GameObjects); + hierarchyProperty2.SetSearchFilter(this.m_SearchFilter); + } + } + } + public void RefreshVisibleItems(List expandedInstanceIDs) + { + bool flag = this.m_SearchFilter.IsSearching(); + List list = new List(); + for (int i = 0; i < this.m_Results.Length; i++) + { + list.Add(this.m_Results[i]); + if (this.m_Results[i].isMainRepresentation && this.m_Results[i].hasChildren && !this.m_Results[i].isFolder) + { + bool flag2 = expandedInstanceIDs.IndexOf(this.m_Results[i].instanceID) >= 0 || flag; + int num = this.AddSubItemsOfMainRepresentation(i, (!flag2) ? null : list); + i += num; + } + } + this.m_VisibleItems = list.ToArray(); + } + public List GetSubAssetInstanceIDs(int mainAssetInstanceID) + { + for (int i = 0; i < this.m_Results.Length; i++) + { + if (this.m_Results[i].instanceID == mainAssetInstanceID) + { + List list = new List(); + int num = i + 1; + while (num < this.m_Results.Length && !this.m_Results[num].isMainRepresentation) + { + list.Add(this.m_Results[num].instanceID); + num++; + } + return list; + } + } + Debug.LogError("Not main rep " + mainAssetInstanceID); + return new List(); + } + public int AddSubItemsOfMainRepresentation(int mainRepresentionIndex, List visibleItems) + { + int num = 0; + int num2 = mainRepresentionIndex + 1; + while (num2 < this.m_Results.Length && !this.m_Results[num2].isMainRepresentation) + { + if (visibleItems != null) + { + visibleItems.Add(this.m_Results[num2]); + } + num2++; + num++; + } + return num; + } + } +} diff --git a/UnityEditor/UnityEditor/FilteredHierarchyProperty.cs b/UnityEditor/UnityEditor/FilteredHierarchyProperty.cs new file mode 100644 index 00000000..55da20ad --- /dev/null +++ b/UnityEditor/UnityEditor/FilteredHierarchyProperty.cs @@ -0,0 +1,178 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class FilteredHierarchyProperty : IHierarchyProperty + { + private FilteredHierarchy m_Hierarchy; + private int m_Position = -1; + public int instanceID + { + get + { + return this.m_Hierarchy.results[this.m_Position].instanceID; + } + } + public UnityEngine.Object pptrValue + { + get + { + return EditorUtility.InstanceIDToObject(this.instanceID); + } + } + public string name + { + get + { + return this.m_Hierarchy.results[this.m_Position].name; + } + } + public bool hasChildren + { + get + { + return this.m_Hierarchy.results[this.m_Position].hasChildren; + } + } + public bool isMainRepresentation + { + get + { + return this.m_Hierarchy.results[this.m_Position].isMainRepresentation; + } + } + public bool hasFullPreviewImage + { + get + { + return this.m_Hierarchy.results[this.m_Position].hasFullPreviewImage; + } + } + public IconDrawStyle iconDrawStyle + { + get + { + return this.m_Hierarchy.results[this.m_Position].iconDrawStyle; + } + } + public bool isFolder + { + get + { + return this.m_Hierarchy.results[this.m_Position].isFolder; + } + } + public int depth + { + get + { + return 0; + } + } + public int row + { + get + { + return this.m_Position; + } + } + public int colorCode + { + get + { + return this.m_Hierarchy.results[this.m_Position].colorCode; + } + } + public string guid + { + get + { + return this.m_Hierarchy.results[this.m_Position].guid; + } + } + public bool isValid + { + get + { + return this.m_Hierarchy.results != null && this.m_Position < this.m_Hierarchy.results.Length && this.m_Position >= 0; + } + } + public Texture2D icon + { + get + { + return this.m_Hierarchy.results[this.m_Position].icon; + } + } + public int[] ancestors + { + get + { + return new int[0]; + } + } + public FilteredHierarchyProperty(FilteredHierarchy filter) + { + this.m_Hierarchy = filter; + } + public static IHierarchyProperty CreateHierarchyPropertyForFilter(FilteredHierarchy filteredHierarchy) + { + if (filteredHierarchy.searchFilter.GetState() != SearchFilter.State.EmptySearchFilter) + { + return new FilteredHierarchyProperty(filteredHierarchy); + } + return new HierarchyProperty(filteredHierarchy.hierarchyType); + } + public void Reset() + { + this.m_Position = -1; + } + public bool IsExpanded(int[] expanded) + { + return false; + } + public bool Next(int[] expanded) + { + this.m_Position++; + return this.m_Position < this.m_Hierarchy.results.Length; + } + public bool NextWithDepthCheck(int[] expanded, int minDepth) + { + return this.Next(expanded); + } + public bool Previous(int[] expanded) + { + this.m_Position--; + return this.m_Position >= 0; + } + public bool Parent() + { + return false; + } + public bool Find(int _instanceID, int[] expanded) + { + this.Reset(); + while (this.Next(expanded)) + { + if (this.instanceID == _instanceID) + { + return true; + } + } + return false; + } + public int[] FindAllAncestors(int[] instanceIDs) + { + return new int[0]; + } + public bool Skip(int count, int[] expanded) + { + this.m_Position += count; + return this.m_Position < this.m_Hierarchy.results.Length; + } + public int CountRemaining(int[] expanded) + { + return this.m_Hierarchy.results.Length - this.m_Position - 1; + } + } +} diff --git a/UnityEditor/UnityEditor/FlashBuildSubtarget.cs b/UnityEditor/UnityEditor/FlashBuildSubtarget.cs new file mode 100644 index 00000000..35e3dffc --- /dev/null +++ b/UnityEditor/UnityEditor/FlashBuildSubtarget.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + public enum FlashBuildSubtarget + { + Flash11dot2, + Flash11dot3, + Flash11dot4, + Flash11dot5, + Flash11dot6, + Flash11dot7, + Flash11dot8 + } +} diff --git a/UnityEditor/UnityEditor/FlattenHeightmap.cs b/UnityEditor/UnityEditor/FlattenHeightmap.cs new file mode 100644 index 00000000..6aa93129 --- /dev/null +++ b/UnityEditor/UnityEditor/FlattenHeightmap.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEditor +{ + internal class FlattenHeightmap : TerrainWizard + { + public float height; + internal override void OnWizardUpdate() + { + if (base.terrainData) + { + base.helpString = string.Concat(new object[] + { + this.height, + " meters (", + this.height / base.terrainData.size.y * 100f, + "%)" + }); + } + } + private void OnWizardCreate() + { + Undo.RegisterCompleteObjectUndo(base.terrainData, "Flatten Heightmap"); + HeightmapFilters.Flatten(base.terrainData, this.height / base.terrainData.size.y); + } + } +} diff --git a/UnityEditor/UnityEditor/FlexibleMenu.cs b/UnityEditor/UnityEditor/FlexibleMenu.cs new file mode 100644 index 00000000..efdb5e7f --- /dev/null +++ b/UnityEditor/UnityEditor/FlexibleMenu.cs @@ -0,0 +1,296 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class FlexibleMenu : PopupWindowContent + { + private class Styles + { + public GUIStyle menuItem = "MenuItem"; + public GUIContent plusButtonText = new GUIContent(string.Empty, "Add New Item"); + } + internal static class ItemContextMenu + { + private static FlexibleMenu s_Caller; + public static void Show(int itemIndex, FlexibleMenu caller) + { + FlexibleMenu.ItemContextMenu.s_Caller = caller; + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Edit..."), false, new GenericMenu.MenuFunction2(FlexibleMenu.ItemContextMenu.Edit), itemIndex); + genericMenu.AddItem(new GUIContent("Delete"), false, new GenericMenu.MenuFunction2(FlexibleMenu.ItemContextMenu.Delete), itemIndex); + genericMenu.ShowAsContext(); + GUIUtility.ExitGUI(); + } + private static void Delete(object userData) + { + int index = (int)userData; + FlexibleMenu.ItemContextMenu.s_Caller.DeleteItem(index); + } + private static void Edit(object userData) + { + int showEditWindowForIndex = (int)userData; + FlexibleMenu.ItemContextMenu.s_Caller.m_ShowEditWindowForIndex = showEditWindowForIndex; + } + } + private const float lineHeight = 18f; + private const float seperatorHeight = 8f; + private const float leftMargin = 25f; + private static FlexibleMenu.Styles s_Styles; + private IFlexibleMenuItemProvider m_ItemProvider; + private FlexibleMenuModifyItemUI m_ModifyItemUI; + private readonly Action m_ItemClickedCallback; + private Vector2 m_ScrollPosition = Vector2.zero; + private bool m_ShowAddNewPresetItem = true; + private int m_ShowEditWindowForIndex = -1; + private int m_HoverIndex; + private int[] m_SeperatorIndices; + private float m_MaxTextWidth = -1f; + private int maxIndex + { + get + { + return (!this.m_ShowAddNewPresetItem) ? (this.m_ItemProvider.Count() - 1) : this.m_ItemProvider.Count(); + } + } + public int selectedIndex + { + get; + set; + } + public FlexibleMenu(IFlexibleMenuItemProvider itemProvider, int selectionIndex, FlexibleMenuModifyItemUI modifyItemUi, Action itemClickedCallback) + { + this.m_ItemProvider = itemProvider; + this.m_ModifyItemUI = modifyItemUi; + this.m_ItemClickedCallback = itemClickedCallback; + this.m_SeperatorIndices = this.m_ItemProvider.GetSeperatorIndices(); + this.selectedIndex = selectionIndex; + } + public override Vector2 GetWindowSize() + { + return this.CalcSize(); + } + private bool IsDeleteModiferPressed() + { + return Event.current.alt; + } + private bool AllowDeleteClick(int index) + { + return this.IsDeleteModiferPressed() && this.m_ItemProvider.IsModificationAllowed(index) && GUIUtility.hotControl == 0; + } + public override void OnGUI(Rect rect) + { + if (FlexibleMenu.s_Styles == null) + { + FlexibleMenu.s_Styles = new FlexibleMenu.Styles(); + } + Event current = Event.current; + Rect viewRect = new Rect(0f, 0f, 1f, this.CalcSize().y); + this.m_ScrollPosition = GUI.BeginScrollView(rect, this.m_ScrollPosition, viewRect); + float num = 0f; + for (int i = 0; i <= this.maxIndex; i++) + { + int num2 = i + 1000000; + Rect rect2 = new Rect(0f, num, rect.width, 18f); + bool flag = Array.IndexOf(this.m_SeperatorIndices, i) >= 0; + if (this.m_ShowAddNewPresetItem && i == this.m_ItemProvider.Count()) + { + this.CreateNewItemButton(rect2); + } + else + { + if (this.m_ShowEditWindowForIndex == i) + { + this.m_ShowEditWindowForIndex = -1; + this.EditExistingItem(rect2, i); + } + EventType type = current.type; + switch (type) + { + case EventType.MouseDown: + if (current.button == 0 && rect2.Contains(current.mousePosition)) + { + GUIUtility.hotControl = num2; + if (!this.IsDeleteModiferPressed() && current.clickCount == 1) + { + GUIUtility.hotControl = 0; + this.SelectItem(i); + base.editorWindow.Close(); + current.Use(); + } + } + goto IL_373; + case EventType.MouseUp: + if (GUIUtility.hotControl == num2) + { + GUIUtility.hotControl = 0; + if (current.button == 0 && rect2.Contains(current.mousePosition) && this.AllowDeleteClick(i)) + { + this.DeleteItem(i); + current.Use(); + } + } + goto IL_373; + case EventType.MouseMove: + if (rect2.Contains(current.mousePosition)) + { + if (this.m_HoverIndex != i) + { + this.m_HoverIndex = i; + this.Repaint(); + } + } + else + { + if (this.m_HoverIndex == i) + { + this.m_HoverIndex = -1; + this.Repaint(); + } + } + goto IL_373; + case EventType.MouseDrag: + case EventType.KeyDown: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_109: + if (type != EventType.ContextClick) + { + goto IL_373; + } + if (rect2.Contains(current.mousePosition)) + { + current.Use(); + if (this.m_ItemProvider.IsModificationAllowed(i)) + { + FlexibleMenu.ItemContextMenu.Show(i, this); + } + } + goto IL_373; + case EventType.Repaint: + { + bool isHover = false; + if (this.m_HoverIndex == i) + { + if (rect2.Contains(current.mousePosition)) + { + isHover = true; + } + else + { + this.m_HoverIndex = -1; + } + } + if (this.m_ModifyItemUI.IsShowing()) + { + isHover = (this.m_ItemProvider.GetItem(i) == this.m_ModifyItemUI.m_Object); + } + FlexibleMenu.s_Styles.menuItem.Draw(rect2, GUIContent.Temp(this.m_ItemProvider.GetName(i)), isHover, false, i == this.selectedIndex, false); + if (flag) + { + Rect rect3 = new Rect(rect2.x + 4f, rect2.y + rect2.height + 4f, rect2.width - 8f, 1f); + FlexibleMenu.DrawRect(rect3, (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.32f, 0.32f, 0.32f, 1.333f)); + } + if (this.AllowDeleteClick(i)) + { + EditorGUIUtility.AddCursorRect(rect2, MouseCursor.ArrowMinus); + } + goto IL_373; + } + } + goto IL_109; + IL_373: + num += 18f; + if (flag) + { + num += 8f; + } + } + } + GUI.EndScrollView(); + } + private void SelectItem(int index) + { + this.selectedIndex = index; + if (this.m_ItemClickedCallback != null && index >= 0) + { + this.m_ItemClickedCallback(index, this.m_ItemProvider.GetItem(index)); + } + } + private Vector2 CalcSize() + { + float y = (float)(this.maxIndex + 1) * 18f + (float)this.m_SeperatorIndices.Length * 8f; + if (this.m_MaxTextWidth < 0f) + { + this.m_MaxTextWidth = Math.Max(200f, this.CalcWidth()); + } + return new Vector2(this.m_MaxTextWidth, y); + } + private void ClearCachedWidth() + { + this.m_MaxTextWidth = -1f; + } + private float CalcWidth() + { + if (FlexibleMenu.s_Styles == null) + { + FlexibleMenu.s_Styles = new FlexibleMenu.Styles(); + } + float num = 0f; + for (int i = 0; i < this.m_ItemProvider.Count(); i++) + { + float x = FlexibleMenu.s_Styles.menuItem.CalcSize(GUIContent.Temp(this.m_ItemProvider.GetName(i))).x; + num = Mathf.Max(x, num); + } + return num + 6f; + } + private void Repaint() + { + HandleUtility.Repaint(); + } + private void CreateNewItemButton(Rect itemRect) + { + Rect rect = new Rect(itemRect.x + 25f, itemRect.y, 15f, 15f); + if (GUI.Button(rect, FlexibleMenu.s_Styles.plusButtonText, "OL Plus")) + { + rect.y -= 15f; + this.m_ModifyItemUI.Init(FlexibleMenuModifyItemUI.MenuType.Add, this.m_ItemProvider.Create(), delegate(object obj) + { + this.ClearCachedWidth(); + int index = this.m_ItemProvider.Add(obj); + this.SelectItem(index); + EditorApplication.RequestRepaintAllViews(); + }); + PopupWindow.Show(rect, this.m_ModifyItemUI); + } + } + private void EditExistingItem(Rect itemRect, int index) + { + itemRect.y -= itemRect.height; + itemRect.x += itemRect.width; + this.m_ModifyItemUI.Init(FlexibleMenuModifyItemUI.MenuType.Edit, this.m_ItemProvider.GetItem(index), delegate(object obj) + { + this.ClearCachedWidth(); + this.m_ItemProvider.Replace(index, obj); + EditorApplication.RequestRepaintAllViews(); + }); + PopupWindow.Show(itemRect, this.m_ModifyItemUI); + } + private void DeleteItem(int index) + { + this.ClearCachedWidth(); + this.m_ItemProvider.Remove(index); + this.selectedIndex = Mathf.Clamp(this.selectedIndex, 0, this.m_ItemProvider.Count() - 1); + } + public static void DrawRect(Rect rect, Color color) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color2 = GUI.color; + GUI.color *= color; + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = color2; + } + } +} diff --git a/UnityEditor/UnityEditor/FlexibleMenuModifyItemUI.cs b/UnityEditor/UnityEditor/FlexibleMenuModifyItemUI.cs new file mode 100644 index 00000000..d6c2a682 --- /dev/null +++ b/UnityEditor/UnityEditor/FlexibleMenuModifyItemUI.cs @@ -0,0 +1,46 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class FlexibleMenuModifyItemUI : PopupWindowContent + { + public enum MenuType + { + Add, + Edit + } + protected FlexibleMenuModifyItemUI.MenuType m_MenuType; + public object m_Object; + protected Action m_AcceptedCallback; + private bool m_IsInitialized; + public override void OnClose() + { + this.m_Object = null; + this.m_AcceptedCallback = null; + this.m_IsInitialized = false; + EditorApplication.RequestRepaintAllViews(); + } + public void Init(FlexibleMenuModifyItemUI.MenuType menuType, object obj, Action acceptedCallback) + { + this.m_MenuType = menuType; + this.m_Object = obj; + this.m_AcceptedCallback = acceptedCallback; + this.m_IsInitialized = true; + } + public void Accepted() + { + if (this.m_AcceptedCallback != null) + { + this.m_AcceptedCallback(this.m_Object); + } + else + { + Debug.LogError("Missing callback. Did you remember to call Init ?"); + } + } + public bool IsShowing() + { + return this.m_IsInitialized; + } + } +} diff --git a/UnityEditor/UnityEditor/FlowLayout.cs b/UnityEditor/UnityEditor/FlowLayout.cs new file mode 100644 index 00000000..48a3f20d --- /dev/null +++ b/UnityEditor/UnityEditor/FlowLayout.cs @@ -0,0 +1,172 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class FlowLayout : GUILayoutGroup + { + private struct LineInfo + { + public float minSize; + public float maxSize; + public float start; + public float size; + public int topBorder; + public int bottomBorder; + public int expandSize; + } + private int m_Lines; + private FlowLayout.LineInfo[] m_LineInfo; + public override void CalcWidth() + { + bool flag = this.minWidth != 0f; + base.CalcWidth(); + if (!this.isVertical) + { + if (!flag) + { + this.minWidth = 0f; + foreach (GUILayoutEntry current in this.entries) + { + this.minWidth = Mathf.Max(this.childMinWidth, current.minWidth); + } + } + } + } + public override void SetHorizontal(float x, float width) + { + base.SetHorizontal(x, width); + if (this.resetCoords) + { + x = 0f; + } + if (this.isVertical) + { + Debug.LogError("Wordwrapped vertical group. Don't. Just Don't"); + } + else + { + this.m_Lines = 0; + float num = 0f; + foreach (GUILayoutEntry current in this.entries) + { + if (current.rect.xMax - num > x + width) + { + num = current.rect.x - (float)current.margin.left; + this.m_Lines++; + } + current.SetHorizontal(current.rect.x - num, current.rect.width); + current.rect.y = (float)this.m_Lines; + } + this.m_Lines++; + } + } + public override void CalcHeight() + { + if (this.entries.Count == 0) + { + this.maxHeight = (this.minHeight = 0f); + return; + } + this.childMinHeight = (this.childMaxHeight = 0f); + int top = 0; + int bottom = 0; + this.stretchableCountY = 0; + if (!this.isVertical) + { + this.m_LineInfo = new FlowLayout.LineInfo[this.m_Lines]; + for (int i = 0; i < this.m_Lines; i++) + { + this.m_LineInfo[i].topBorder = 10000; + this.m_LineInfo[i].bottomBorder = 10000; + } + foreach (GUILayoutEntry current in this.entries) + { + current.CalcHeight(); + int num = (int)current.rect.y; + this.m_LineInfo[num].minSize = Mathf.Max(current.minHeight, this.m_LineInfo[num].minSize); + this.m_LineInfo[num].maxSize = Mathf.Max(current.maxHeight, this.m_LineInfo[num].maxSize); + this.m_LineInfo[num].topBorder = Mathf.Min(current.margin.top, this.m_LineInfo[num].topBorder); + this.m_LineInfo[num].bottomBorder = Mathf.Min(current.margin.bottom, this.m_LineInfo[num].bottomBorder); + } + for (int j = 0; j < this.m_Lines; j++) + { + this.childMinHeight += this.m_LineInfo[j].minSize; + this.childMaxHeight += this.m_LineInfo[j].maxSize; + } + for (int k = 1; k < this.m_Lines; k++) + { + float num2 = (float)Mathf.Max(this.m_LineInfo[k - 1].bottomBorder, this.m_LineInfo[k].topBorder); + this.childMinHeight += num2; + this.childMaxHeight += num2; + } + top = this.m_LineInfo[0].topBorder; + bottom = this.m_LineInfo[this.m_LineInfo.Length - 1].bottomBorder; + } + this.margin.top = top; + this.margin.bottom = bottom; + float num4; + float num3 = num4 = 0f; + this.minHeight = Mathf.Max(this.minHeight, this.childMinHeight + num4 + num3); + if (this.maxHeight == 0f) + { + this.stretchHeight += this.stretchableCountY + ((!base.style.stretchHeight) ? 0 : 1); + this.maxHeight = this.childMaxHeight + num4 + num3; + } + else + { + this.stretchHeight = 0; + } + this.maxHeight = Mathf.Max(this.maxHeight, this.minHeight); + } + public override void SetVertical(float y, float height) + { + if (this.entries.Count == 0) + { + base.SetVertical(y, height); + return; + } + if (this.isVertical) + { + base.SetVertical(y, height); + } + else + { + if (this.resetCoords) + { + y = 0f; + } + float num = y - (float)this.margin.top; + float num2 = y + (float)this.margin.vertical; + float num3 = num2 - this.spacing * (float)(this.m_Lines - 1); + float t = 0f; + if (this.childMinHeight != this.childMaxHeight) + { + t = Mathf.Clamp((num3 - this.childMinHeight) / (this.childMaxHeight - this.childMinHeight), 0f, 1f); + } + float num4 = num; + for (int i = 0; i < this.m_Lines; i++) + { + if (i > 0) + { + num4 += (float)Mathf.Max(this.m_LineInfo[i].topBorder, this.m_LineInfo[i - 1].bottomBorder); + } + this.m_LineInfo[i].start = num4; + this.m_LineInfo[i].size = Mathf.Lerp(this.m_LineInfo[i].minSize, this.m_LineInfo[i].maxSize, t); + num4 += this.m_LineInfo[i].size + this.spacing; + } + foreach (GUILayoutEntry current in this.entries) + { + FlowLayout.LineInfo lineInfo = this.m_LineInfo[(int)current.rect.y]; + if (current.stretchHeight != 0) + { + current.SetVertical(lineInfo.start + (float)current.margin.top, lineInfo.size - (float)current.margin.vertical); + } + else + { + current.SetVertical(lineInfo.start + (float)current.margin.top, Mathf.Clamp(lineInfo.size - (float)current.margin.vertical, current.minHeight, current.maxHeight)); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/FoldoutComponentState.cs b/UnityEditor/UnityEditor/FoldoutComponentState.cs new file mode 100644 index 00000000..492a98ff --- /dev/null +++ b/UnityEditor/UnityEditor/FoldoutComponentState.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class FoldoutComponentState + { + private UnityEngine.Object m_Object; + private bool m_Expanded; + private bool m_Animated; + private CurveState[] m_CurveStates; + public UnityEngine.Object obj + { + get + { + return this.m_Object; + } + set + { + this.m_Object = value; + } + } + public bool expanded + { + get + { + return this.m_Expanded; + } + } + public bool animated + { + get + { + return this.m_Animated; + } + } + public CurveState[] curveStates + { + get + { + return this.m_CurveStates; + } + } + public FoldoutComponentState(UnityEngine.Object obj, SerializedStringTable expandedFoldouts, Transform tr, int level) + { + this.m_Object = obj; + if (level == 0 && this.m_Object.GetType() == typeof(Transform)) + { + this.m_Expanded = true; + } + else + { + if (expandedFoldouts.Contains(this.GetString(tr))) + { + this.m_Expanded = true; + } + } + } + public string GetString(Transform tr) + { + return AnimationSelection.GetPath(tr) + "/:" + ObjectNames.GetInspectorTitle(this.obj); + } + public void Expand(AnimationHierarchyData data, Transform tr, int level) + { + this.m_Expanded = true; + if (level > 0 || this.m_Object.GetType() != typeof(Transform)) + { + data.expandedFoldouts.Set(this.GetString(tr)); + } + data.animationWindow.SetDirtyCurves(); + } + public void Collapse(AnimationHierarchyData data, Transform tr, int level) + { + this.m_Expanded = false; + this.Hide(data, tr, level); + if (level > 0 || this.m_Object.GetType() != typeof(Transform)) + { + data.expandedFoldouts.Remove(this.GetString(tr)); + } + data.animationWindow.SetDirtyCurves(); + } + public void Hide(AnimationHierarchyData data, Transform tr, int level) + { + this.m_CurveStates = null; + } + public void RefreshAnimatedState(AnimationHierarchyData data, Transform tr) + { + this.m_Animated = false; + string path = AnimationUtility.CalculateTransformPath(tr, data.animated.transform); + foreach (int num in data.animatedPaths.Keys) + { + if (num == CurveUtility.GetPathAndTypeID(path, this.obj.GetType())) + { + this.m_Animated = true; + break; + } + } + } + public void AddChildCurvesToList(List curves, AnimationHierarchyData data) + { + if (!this.expanded) + { + return; + } + CurveState[] curveStates = this.curveStates; + for (int i = 0; i < curveStates.Length; i++) + { + CurveState curveState = curveStates[i]; + if (curveState.animated || data.animationWindow.showAllProperties) + { + curves.Add(curveState); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/FoldoutObjectState.cs b/UnityEditor/UnityEditor/FoldoutObjectState.cs new file mode 100644 index 00000000..1b045629 --- /dev/null +++ b/UnityEditor/UnityEditor/FoldoutObjectState.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class FoldoutObjectState + { + private GameObject m_Object; + private bool m_Expanded; + private bool m_Animated; + public FoldoutComponentState[] m_Components; + private int[] m_Children; + public GameObject obj + { + get + { + return this.m_Object; + } + } + public bool expanded + { + get + { + return this.m_Expanded; + } + } + public bool animated + { + get + { + return this.m_Animated; + } + } + public FoldoutComponentState[] components + { + get + { + return this.m_Components; + } + } + public int[] children + { + get + { + return this.m_Children; + } + } + public FoldoutObjectState(GameObject obj, List states, SerializedStringTable expandedFoldouts, int level) + { + this.m_Object = obj; + states.Add(this); + if (level == 0) + { + this.m_Expanded = true; + } + else + { + if (expandedFoldouts.Contains(AnimationSelection.GetPath(obj.transform))) + { + this.m_Expanded = true; + } + } + List list = new List(); + foreach (Transform transform in obj.transform) + { + list.Add(states.Count); + new FoldoutObjectState(transform.gameObject, states, expandedFoldouts, level + 1); + } + this.m_Children = list.ToArray(); + } + public void Expand(AnimationHierarchyData data, int level) + { + this.m_Expanded = true; + if (level > 0) + { + data.expandedFoldouts.Set(AnimationSelection.GetPath(this.obj.transform)); + } + data.animationWindow.SetDirtyCurves(); + } + public void Collapse(AnimationHierarchyData data, int level) + { + this.m_Expanded = false; + this.Hide(data, level); + if (level > 0) + { + data.expandedFoldouts.Remove(AnimationSelection.GetPath(this.obj.transform)); + } + data.animationWindow.SetDirtyCurves(); + } + public void Hide(AnimationHierarchyData data, int level) + { + if (this.m_Components != null) + { + FoldoutComponentState[] components = this.m_Components; + for (int i = 0; i < components.Length; i++) + { + FoldoutComponentState foldoutComponentState = components[i]; + if (foldoutComponentState.expanded) + { + foldoutComponentState.Hide(data, this.obj.transform, level); + } + } + } + int[] children = this.children; + for (int j = 0; j < children.Length; j++) + { + int num = children[j]; + if (data.states[num].expanded) + { + data.states[num].Hide(data, level + 1); + } + } + } + public void RefreshAnimatedState(AnimationHierarchyData data) + { + this.m_Animated = false; + string text = AnimationUtility.CalculateTransformPath(this.obj.transform, data.animated.transform); + foreach (int num in data.animatedPaths.Keys) + { + if (num == text.GetHashCode()) + { + this.m_Animated = true; + } + } + } + public void AddChildCurvesToList(List curves, AnimationHierarchyData data) + { + if (!this.expanded) + { + return; + } + FoldoutComponentState[] components = this.components; + for (int i = 0; i < components.Length; i++) + { + FoldoutComponentState foldoutComponentState = components[i]; + foldoutComponentState.AddChildCurvesToList(curves, data); + } + int[] children = this.children; + for (int j = 0; j < children.Length; j++) + { + int num = children[j]; + data.states[num].AddChildCurvesToList(curves, data); + } + } + } +} diff --git a/UnityEditor/UnityEditor/FoldoutTree.cs b/UnityEditor/UnityEditor/FoldoutTree.cs new file mode 100644 index 00000000..f79dc03b --- /dev/null +++ b/UnityEditor/UnityEditor/FoldoutTree.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class FoldoutTree + { + private bool m_Locked; + private FoldoutObjectState[] m_States; + public bool locked + { + get + { + return this.m_Locked; + } + set + { + this.m_Locked = value; + } + } + public FoldoutObjectState[] states + { + get + { + return this.m_States; + } + } + public FoldoutObjectState root + { + get + { + return this.states[0]; + } + } + public GameObject rootGameObject + { + get + { + return this.root.obj; + } + } + public Transform rootTransform + { + get + { + return this.root.obj.transform; + } + } + public FoldoutTree(Transform tr, SerializedStringTable expandedFoldouts) + { + List list = new List(); + new FoldoutObjectState(tr.gameObject, list, expandedFoldouts, 0); + this.m_States = list.ToArray(); + } + public void Refresh(AnimationHierarchyData data) + { + } + } +} diff --git a/UnityEditor/UnityEditor/FontInspector.cs b/UnityEditor/UnityEditor/FontInspector.cs new file mode 100644 index 00000000..ee6256bd --- /dev/null +++ b/UnityEditor/UnityEditor/FontInspector.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Font))] + internal class FontInspector : Editor + { + public override void OnInspectorGUI() + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + if (@object.hideFlags == HideFlags.NotEditable) + { + return; + } + } + base.DrawDefaultInspector(); + } + } +} diff --git a/UnityEditor/UnityEditor/FontRenderingMode.cs b/UnityEditor/UnityEditor/FontRenderingMode.cs new file mode 100644 index 00000000..cd5aacda --- /dev/null +++ b/UnityEditor/UnityEditor/FontRenderingMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum FontRenderingMode + { + Smooth, + HintedSmooth, + HintedRaster, + OSDefault + } +} diff --git a/UnityEditor/UnityEditor/FontTextureCase.cs b/UnityEditor/UnityEditor/FontTextureCase.cs new file mode 100644 index 00000000..f8522b9b --- /dev/null +++ b/UnityEditor/UnityEditor/FontTextureCase.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum FontTextureCase + { + Dynamic = -2, + Unicode, + ASCII, + ASCIIUpperCase, + ASCIILowerCase, + CustomSet + } +} diff --git a/UnityEditor/UnityEditor/ForceModuleUI.cs b/UnityEditor/UnityEditor/ForceModuleUI.cs new file mode 100644 index 00000000..85253be5 --- /dev/null +++ b/UnityEditor/UnityEditor/ForceModuleUI.cs @@ -0,0 +1,72 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ForceModuleUI : ModuleUI + { + private class Texts + { + public GUIContent x = new GUIContent("X"); + public GUIContent y = new GUIContent("Y"); + public GUIContent z = new GUIContent("Z"); + public GUIContent randomizePerFrame = new GUIContent("Randomize", "Randomize force every frame. Only available when using random between two constants or random between two curves."); + public GUIContent space = new GUIContent("Space", "Specifies if the force values are in local space (rotated with the transform) or world space."); + public string[] spaces = new string[] + { + "Local", + "World" + }; + } + private SerializedMinMaxCurve m_X; + private SerializedMinMaxCurve m_Y; + private SerializedMinMaxCurve m_Z; + private SerializedProperty m_RandomizePerFrame; + private SerializedProperty m_InWorldSpace; + private static ForceModuleUI.Texts s_Texts; + public ForceModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ForceModule", displayName) + { + this.m_ToolTip = "Controls the force of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_X != null) + { + return; + } + if (ForceModuleUI.s_Texts == null) + { + ForceModuleUI.s_Texts = new ForceModuleUI.Texts(); + } + this.m_X = new SerializedMinMaxCurve(this, ForceModuleUI.s_Texts.x, "x", ModuleUI.kUseSignedRange); + this.m_Y = new SerializedMinMaxCurve(this, ForceModuleUI.s_Texts.y, "y", ModuleUI.kUseSignedRange); + this.m_Z = new SerializedMinMaxCurve(this, ForceModuleUI.s_Texts.z, "z", ModuleUI.kUseSignedRange); + this.m_RandomizePerFrame = base.GetProperty("randomizePerFrame"); + this.m_InWorldSpace = base.GetProperty("inWorldSpace"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (ForceModuleUI.s_Texts == null) + { + ForceModuleUI.s_Texts = new ForceModuleUI.Texts(); + } + MinMaxCurveState state = this.m_X.state; + base.GUITripleMinMaxCurve(GUIContent.none, ForceModuleUI.s_Texts.x, this.m_X, ForceModuleUI.s_Texts.y, this.m_Y, ForceModuleUI.s_Texts.z, this.m_Z, this.m_RandomizePerFrame); + ModuleUI.GUIBoolAsPopup(ForceModuleUI.s_Texts.space, this.m_InWorldSpace, ForceModuleUI.s_Texts.spaces); + EditorGUI.BeginDisabledGroup(state != MinMaxCurveState.k_TwoScalars && state != MinMaxCurveState.k_TwoCurves); + ModuleUI.GUIToggle(ForceModuleUI.s_Texts.randomizePerFrame, this.m_RandomizePerFrame); + EditorGUI.EndDisabledGroup(); + } + public override void UpdateCullingSupportedString(ref string text) + { + this.Init(); + if (!this.m_X.SupportsProcedural() || !this.m_Y.SupportsProcedural() || !this.m_Z.SupportsProcedural()) + { + text += "\n\tLifetime force curves use too many keys."; + } + if (this.m_RandomizePerFrame.boolValue) + { + text += "\n\tLifetime force curves use random per frame."; + } + } + } +} diff --git a/UnityEditor/UnityEditor/GUIDrawer.cs b/UnityEditor/UnityEditor/GUIDrawer.cs new file mode 100644 index 00000000..f2f74ae1 --- /dev/null +++ b/UnityEditor/UnityEditor/GUIDrawer.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + public abstract class GUIDrawer + { + } +} diff --git a/UnityEditor/UnityEditor/GUILayoutFadeGroup.cs b/UnityEditor/UnityEditor/GUILayoutFadeGroup.cs new file mode 100644 index 00000000..42f85cde --- /dev/null +++ b/UnityEditor/UnityEditor/GUILayoutFadeGroup.cs @@ -0,0 +1,17 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class GUILayoutFadeGroup : GUILayoutGroup + { + public float fadeValue; + public bool wasGUIEnabled; + public Color guiColor; + public override void CalcHeight() + { + base.CalcHeight(); + this.minHeight *= this.fadeValue; + this.maxHeight *= this.fadeValue; + } + } +} diff --git a/UnityEditor/UnityEditor/GUISlideGroup.cs b/UnityEditor/UnityEditor/GUISlideGroup.cs new file mode 100644 index 00000000..509a48b6 --- /dev/null +++ b/UnityEditor/UnityEditor/GUISlideGroup.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class GUISlideGroup + { + private class SlideGroupInternal : GUILayoutGroup + { + private int m_ID; + private GUISlideGroup m_Owner; + internal Rect m_FinalRect; + public void SetID(GUISlideGroup owner, int id) + { + this.m_ID = id; + this.m_Owner = owner; + } + public override void SetHorizontal(float x, float width) + { + this.m_FinalRect.x = x; + this.m_FinalRect.width = width; + base.SetHorizontal(x, width); + } + public override void SetVertical(float y, float height) + { + this.m_FinalRect.y = y; + this.m_FinalRect.height = height; + Rect rect = new Rect(this.rect.x, y, this.rect.width, height); + bool flag; + rect = this.m_Owner.GetRect(this.m_ID, rect, out flag); + if (flag) + { + base.SetHorizontal(rect.x, rect.width); + } + base.SetVertical(rect.y, rect.height); + } + } + private const float kLerp = 0.1f; + private const float kSnap = 0.5f; + internal static GUISlideGroup current; + private Dictionary animIDs = new Dictionary(); + public void Begin() + { + if (GUISlideGroup.current != null) + { + Debug.LogError("You cannot nest animGroups"); + return; + } + GUISlideGroup.current = this; + } + public void End() + { + GUISlideGroup.current = null; + } + public void Reset() + { + GUISlideGroup.current = null; + this.animIDs.Clear(); + } + public Rect BeginHorizontal(int id, params GUILayoutOption[] options) + { + GUISlideGroup.SlideGroupInternal slideGroupInternal = (GUISlideGroup.SlideGroupInternal)GUILayoutUtility.BeginLayoutGroup(GUIStyle.none, options, typeof(GUISlideGroup.SlideGroupInternal)); + slideGroupInternal.SetID(this, id); + slideGroupInternal.isVertical = false; + return slideGroupInternal.m_FinalRect; + } + public void EndHorizontal() + { + GUILayoutUtility.EndLayoutGroup(); + } + public Rect GetRect(int id, Rect r) + { + if (Event.current.type != EventType.Repaint) + { + return r; + } + bool flag; + return this.GetRect(id, r, out flag); + } + private Rect GetRect(int id, Rect r, out bool changed) + { + if (!this.animIDs.ContainsKey(id)) + { + this.animIDs.Add(id, r); + changed = false; + return r; + } + Rect rect = this.animIDs[id]; + if (rect.y != r.y || rect.height != r.height || rect.x != r.x || rect.width != r.width) + { + float t = 0.1f; + if (Mathf.Abs(rect.y - r.y) > 0.5f) + { + r.y = Mathf.Lerp(rect.y, r.y, t); + } + if (Mathf.Abs(rect.height - r.height) > 0.5f) + { + r.height = Mathf.Lerp(rect.height, r.height, t); + } + if (Mathf.Abs(rect.x - r.x) > 0.5f) + { + r.x = Mathf.Lerp(rect.x, r.x, t); + } + if (Mathf.Abs(rect.width - r.width) > 0.5f) + { + r.width = Mathf.Lerp(rect.width, r.width, t); + } + this.animIDs[id] = r; + changed = true; + HandleUtility.Repaint(); + } + else + { + changed = false; + } + return r; + } + } +} diff --git a/UnityEditor/UnityEditor/GUIStyleX.cs b/UnityEditor/UnityEditor/GUIStyleX.cs new file mode 100644 index 00000000..733da57a --- /dev/null +++ b/UnityEditor/UnityEditor/GUIStyleX.cs @@ -0,0 +1,9 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GUIStyleX + { + public static GUIStyle none = new GUIStyle(); + } +} diff --git a/UnityEditor/UnityEditor/GUIView.cs b/UnityEditor/UnityEditor/GUIView.cs new file mode 100644 index 00000000..b96483c3 --- /dev/null +++ b/UnityEditor/UnityEditor/GUIView.cs @@ -0,0 +1,240 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + internal class GUIView : View + { + private int m_DepthBufferBits; + private int m_AntiAlias; + private bool m_WantsMouseMove; + private bool m_AutoRepaintOnSceneChange; + private bool m_BackgroundValid; + public bool wantsMouseMove + { + get + { + return this.m_WantsMouseMove; + } + set + { + this.m_WantsMouseMove = value; + this.Internal_SetWantsMouseMove(this.m_WantsMouseMove); + } + } + internal bool backgroundValid + { + get + { + return this.m_BackgroundValid; + } + set + { + this.m_BackgroundValid = value; + } + } + public bool autoRepaintOnSceneChange + { + get + { + return this.m_AutoRepaintOnSceneChange; + } + set + { + this.m_AutoRepaintOnSceneChange = value; + this.Internal_SetAutoRepaint(this.m_AutoRepaintOnSceneChange); + } + } + public int depthBufferBits + { + get + { + return this.m_DepthBufferBits; + } + set + { + this.m_DepthBufferBits = value; + } + } + public int antiAlias + { + get + { + return this.m_AntiAlias; + } + set + { + this.m_AntiAlias = value; + } + } + public static extern GUIView current + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern GUIView focusedView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern GUIView mouseOverView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasFocus + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool mouseRayInvisible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Init(int depthBits, int antiAlias); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Recreate(int depthBits, int antiAlias); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Close(); + internal bool SendEvent(Event e) + { + int num = SavedGUIState.Internal_GetGUIDepth(); + bool result; + if (num > 0) + { + SavedGUIState savedGUIState = SavedGUIState.Create(); + result = this.Internal_SendEvent(e); + savedGUIState.ApplyAndForget(); + } + else + { + result = this.Internal_SendEvent(e); + } + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_SendEvent(Event e); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddToAuxWindowList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveFromAuxWindowList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + protected extern void Internal_SetAsActiveWindow(); + protected override void SetWindow(ContainerWindow win) + { + base.SetWindow(win); + this.Internal_Init(this.m_DepthBufferBits, this.m_AntiAlias); + if (win) + { + this.Internal_SetWindow(win); + } + this.Internal_SetAutoRepaint(this.m_AutoRepaintOnSceneChange); + this.Internal_SetPosition(base.windowPosition); + this.Internal_SetWantsMouseMove(this.m_WantsMouseMove); + this.m_BackgroundValid = false; + } + internal void RecreateContext() + { + this.Internal_Recreate(this.m_DepthBufferBits, this.m_AntiAlias); + this.m_BackgroundValid = false; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetWantsMouseMove(bool wantIt); + public void SetInternalGameViewRect(Rect rect) + { + GUIView.INTERNAL_CALL_SetInternalGameViewRect(this, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetInternalGameViewRect(GUIView self, ref Rect rect); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAsStartView(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearStartView(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetAutoRepaint(bool doit); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetWindow(ContainerWindow win); + protected override void SetPosition(Rect newPos) + { + Rect windowPosition = base.windowPosition; + base.SetPosition(newPos); + if (windowPosition == base.windowPosition) + { + this.Internal_SetPosition(base.windowPosition); + return; + } + this.Repaint(); + this.Internal_SetPosition(base.windowPosition); + this.m_BackgroundValid = false; + } + private void Internal_SetPosition(Rect windowPosition) + { + GUIView.INTERNAL_CALL_Internal_SetPosition(this, ref windowPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetPosition(GUIView self, ref Rect windowPosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Focus(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Repaint(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RepaintImmediately(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MakeVistaDWMHappyDance(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void StealMouseCapture(); + public new void OnDestroy() + { + this.Internal_Close(); + base.OnDestroy(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void ClearKeyboardControl(); + internal void DoWindowDecorationStart() + { + if (base.window != null) + { + base.window.HandleEdgesStart(base.windowPosition); + } + } + internal void DoWindowDecorationEnd() + { + if (base.window != null) + { + base.window.HandleEdgesEnd(base.windowPosition); + } + } + } +} diff --git a/UnityEditor/UnityEditor/GameObjectInspector.cs b/UnityEditor/UnityEditor/GameObjectInspector.cs new file mode 100644 index 00000000..5c8af7c3 --- /dev/null +++ b/UnityEditor/UnityEditor/GameObjectInspector.cs @@ -0,0 +1,754 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(GameObject))] + internal class GameObjectInspector : Editor + { + private class Styles + { + public GUIContent goIcon = EditorGUIUtility.IconContent("GameObject Icon"); + public GUIContent typelessIcon = EditorGUIUtility.IconContent("Prefab Icon"); + public GUIContent prefabIcon = EditorGUIUtility.IconContent("PrefabNormal Icon"); + public GUIContent modelIcon = EditorGUIUtility.IconContent("PrefabModel Icon"); + public GUIContent dataTemplateIcon = EditorGUIUtility.IconContent("PrefabNormal Icon"); + public GUIContent dropDownIcon = EditorGUIUtility.IconContent("Icon Dropdown"); + public float staticFieldToggleWidth = EditorStyles.toggle.CalcSize(EditorGUIUtility.TempContent("Static")).x + 6f; + public float tagFieldWidth = EditorStyles.boldLabel.CalcSize(EditorGUIUtility.TempContent("Tag")).x; + public float layerFieldWidth = EditorStyles.boldLabel.CalcSize(EditorGUIUtility.TempContent("Layer")).x; + public float navLayerFieldWidth = EditorStyles.boldLabel.CalcSize(EditorGUIUtility.TempContent("Nav Layer")).x; + public GUIStyle staticDropdown = "StaticDropdown"; + public GUIStyle instanceManagementInfo = new GUIStyle(EditorStyles.helpBox); + public GUIContent goTypeLabelMultiple = new GUIContent("Multiple"); + public GUIContent[] goTypeLabel = new GUIContent[] + { + null, + EditorGUIUtility.TextContent("GameObjectTypePrefab"), + EditorGUIUtility.TextContent("GameObjectTypeModel"), + EditorGUIUtility.TextContent("GameObjectTypePrefab"), + EditorGUIUtility.TextContent("GameObjectTypeModel"), + EditorGUIUtility.TextContent("GameObjectTypeMissing"), + EditorGUIUtility.TextContent("GameObjectTypeDisconnectedPrefab"), + EditorGUIUtility.TextContent("GameObjectTypeDisconnectedModel") + }; + public Styles() + { + GUIStyle gUIStyle = "MiniButtonMid"; + this.instanceManagementInfo.padding = gUIStyle.padding; + this.instanceManagementInfo.alignment = gUIStyle.alignment; + } + } + private const float kTop = 4f; + private const float kTop2 = 24f; + private const float kTop3 = 44f; + private const float kIconSize = 24f; + private const float kLeft = 52f; + private const float kToggleSize = 14f; + private const int kPreviewLayer = 31; + private SerializedProperty m_Name; + private SerializedProperty m_IsActive; + private SerializedProperty m_Layer; + private SerializedProperty m_Tag; + private SerializedProperty m_StaticEditorFlags; + private SerializedProperty m_Icon; + private static GameObjectInspector.Styles s_styles; + private Vector2 previewDir; + private PreviewRenderUtility m_PreviewUtility; + private List m_PreviewInstances; + private bool m_HasInstance; + private bool m_AllOfSamePrefabType = true; + public static GameObject dragObject; + private GameObjectInspector() + { + if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) + { + this.previewDir = new Vector2(0f, 0f); + } + else + { + this.previewDir = new Vector2(120f, -20f); + } + } + public void OnEnable() + { + this.m_Name = base.serializedObject.FindProperty("m_Name"); + this.m_IsActive = base.serializedObject.FindProperty("m_IsActive"); + this.m_Layer = base.serializedObject.FindProperty("m_Layer"); + this.m_Tag = base.serializedObject.FindProperty("m_TagString"); + this.m_StaticEditorFlags = base.serializedObject.FindProperty("m_StaticEditorFlags"); + this.m_Icon = base.serializedObject.FindProperty("m_Icon"); + this.CalculatePrefabStatus(); + } + private void CalculatePrefabStatus() + { + this.m_HasInstance = false; + this.m_AllOfSamePrefabType = true; + PrefabType prefabType = PrefabUtility.GetPrefabType(base.targets[0] as GameObject); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + GameObject target = (GameObject)targets[i]; + PrefabType prefabType2 = PrefabUtility.GetPrefabType(target); + if (prefabType2 != prefabType) + { + this.m_AllOfSamePrefabType = false; + } + if (prefabType2 != PrefabType.None && prefabType2 != PrefabType.Prefab && prefabType2 != PrefabType.ModelPrefab) + { + this.m_HasInstance = true; + } + } + } + private void OnDisable() + { + } + private static bool ShowMixedStaticEditorFlags(StaticEditorFlags mask) + { + uint num = 0u; + uint num2 = 0u; + foreach (object current in Enum.GetValues(typeof(StaticEditorFlags))) + { + num2 += 1u; + if ((mask & (StaticEditorFlags)((int)current)) > (StaticEditorFlags)0) + { + num += 1u; + } + } + return num > 0u && num != num2; + } + protected override void OnHeaderGUI() + { + Rect rect = GUILayoutUtility.GetRect(0f, (float)((!this.m_HasInstance) ? 40 : 60)); + this.DrawInspector(rect); + } + public override void OnInspectorGUI() + { + } + internal bool DrawInspector(Rect contentRect) + { + if (GameObjectInspector.s_styles == null) + { + GameObjectInspector.s_styles = new GameObjectInspector.Styles(); + } + base.serializedObject.Update(); + GameObject gameObject = this.target as GameObject; + EditorGUIUtility.labelWidth = 52f; + bool enabled = GUI.enabled; + GUI.enabled = true; + GUI.Label(new Rect(contentRect.x, contentRect.y, contentRect.width, contentRect.height + 3f), GUIContent.none, EditorStyles.inspectorBig); + GUI.enabled = enabled; + float width = contentRect.width; + float y = contentRect.y; + GUIContent gUIContent = null; + PrefabType prefabType = PrefabType.None; + if (this.m_AllOfSamePrefabType) + { + prefabType = PrefabUtility.GetPrefabType(gameObject); + switch (prefabType) + { + case PrefabType.None: + gUIContent = GameObjectInspector.s_styles.goIcon; + break; + case PrefabType.Prefab: + case PrefabType.PrefabInstance: + case PrefabType.DisconnectedPrefabInstance: + gUIContent = GameObjectInspector.s_styles.prefabIcon; + break; + case PrefabType.ModelPrefab: + case PrefabType.ModelPrefabInstance: + case PrefabType.DisconnectedModelPrefabInstance: + gUIContent = GameObjectInspector.s_styles.modelIcon; + break; + case PrefabType.MissingPrefabInstance: + gUIContent = GameObjectInspector.s_styles.prefabIcon; + break; + } + } + else + { + gUIContent = GameObjectInspector.s_styles.typelessIcon; + } + EditorGUI.ObjectIconDropDown(new Rect(3f, 4f + y, 24f, 24f), base.targets, true, gUIContent.image as Texture2D, this.m_Icon); + EditorGUI.BeginDisabledGroup(prefabType == PrefabType.ModelPrefab); + EditorGUI.PropertyField(new Rect(34f, 4f + y, 14f, 14f), this.m_IsActive, GUIContent.none); + float num = GameObjectInspector.s_styles.staticFieldToggleWidth + 15f; + float width2 = width - 52f - num - 5f; + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_Name.hasMultipleDifferentValues; + string name = EditorGUI.DelayedTextField(new Rect(52f, 4f + y + 1f, width2, 16f), gameObject.name, null, EditorStyles.textField); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + ObjectNames.SetNameSmart(@object as GameObject, name); + } + } + Rect rect = new Rect(width - num, 4f + y, GameObjectInspector.s_styles.staticFieldToggleWidth, 16f); + EditorGUI.BeginProperty(rect, GUIContent.none, this.m_StaticEditorFlags); + EditorGUI.BeginChangeCheck(); + Rect position = rect; + EditorGUI.showMixedValue |= GameObjectInspector.ShowMixedStaticEditorFlags((StaticEditorFlags)this.m_StaticEditorFlags.intValue); + Event current = Event.current; + EventType type = current.type; + bool flag = current.type == EventType.MouseDown && current.button != 0; + if (flag) + { + current.type = EventType.Ignore; + } + bool flagValue = EditorGUI.ToggleLeft(position, "Static", gameObject.isStatic); + if (flag) + { + current.type = type; + } + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + SceneModeUtility.SetStaticFlags(base.targets, -1, flagValue); + base.serializedObject.SetIsDifferentCacheDirty(); + } + EditorGUI.EndProperty(); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_StaticEditorFlags.hasMultipleDifferentValues; + int changedFlags; + bool flagValue2; + EditorGUI.EnumMaskField(new Rect(rect.x + GameObjectInspector.s_styles.staticFieldToggleWidth, rect.y, 10f, 14f), GameObjectUtility.GetStaticEditorFlags(gameObject), GameObjectInspector.s_styles.staticDropdown, out changedFlags, out flagValue2); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + SceneModeUtility.SetStaticFlags(base.targets, changedFlags, flagValue2); + base.serializedObject.SetIsDifferentCacheDirty(); + } + float num2 = 4f; + float num3 = 4f; + EditorGUIUtility.fieldWidth = (width - num2 - 52f - GameObjectInspector.s_styles.layerFieldWidth - num3) / 2f; + string tag = null; + try + { + tag = gameObject.tag; + } + catch (Exception) + { + tag = "Undefined"; + } + EditorGUIUtility.labelWidth = GameObjectInspector.s_styles.tagFieldWidth; + Rect rect2 = new Rect(52f - EditorGUIUtility.labelWidth, 24f + y, EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth, 16f); + EditorGUI.BeginProperty(rect2, GUIContent.none, this.m_Tag); + EditorGUI.BeginChangeCheck(); + string text = EditorGUI.TagField(rect2, EditorGUIUtility.TempContent("Tag"), tag); + if (EditorGUI.EndChangeCheck()) + { + this.m_Tag.stringValue = text; + Undo.RecordObjects(base.targets, "Change Tag of " + this.targetTitle); + UnityEngine.Object[] targets2 = base.targets; + for (int j = 0; j < targets2.Length; j++) + { + UnityEngine.Object object2 = targets2[j]; + (object2 as GameObject).tag = text; + } + } + EditorGUI.EndProperty(); + EditorGUIUtility.labelWidth = GameObjectInspector.s_styles.layerFieldWidth; + rect2 = new Rect(52f + EditorGUIUtility.fieldWidth + num2, 24f + y, EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth, 16f); + EditorGUI.BeginProperty(rect2, GUIContent.none, this.m_Layer); + EditorGUI.BeginChangeCheck(); + int num4 = EditorGUI.LayerField(rect2, EditorGUIUtility.TempContent("Layer"), gameObject.layer); + if (EditorGUI.EndChangeCheck()) + { + GameObjectUtility.ShouldIncludeChildren shouldIncludeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(base.targets.OfType(), "Change Layer", "Do you want to set layer to " + InternalEditorUtility.GetLayerName(num4) + " for all child objects as well?"); + if (shouldIncludeChildren != GameObjectUtility.ShouldIncludeChildren.Cancel) + { + this.m_Layer.intValue = num4; + this.SetLayer(num4, shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); + } + } + EditorGUI.EndProperty(); + if (this.m_HasInstance && !EditorApplication.isPlayingOrWillChangePlaymode) + { + float num5 = (width - 52f - 5f) / 3f; + Rect position2 = new Rect(52f + num5 * 0f, 44f + y, num5, 15f); + Rect position3 = new Rect(52f + num5 * 1f, 44f + y, num5, 15f); + Rect position4 = new Rect(52f + num5 * 2f, 44f + y, num5, 15f); + Rect position5 = new Rect(52f, 44f + y, num5 * 3f, 15f); + GUIContent gUIContent2 = (base.targets.Length <= 1) ? GameObjectInspector.s_styles.goTypeLabel[(int)prefabType] : GameObjectInspector.s_styles.goTypeLabelMultiple; + if (gUIContent2 != null) + { + float x = GUI.skin.label.CalcSize(gUIContent2).x; + if (prefabType == PrefabType.DisconnectedModelPrefabInstance || prefabType == PrefabType.MissingPrefabInstance || prefabType == PrefabType.DisconnectedPrefabInstance) + { + GUI.contentColor = GUI.skin.GetStyle("CN StatusWarn").normal.textColor; + if (prefabType == PrefabType.MissingPrefabInstance) + { + GUI.Label(new Rect(52f, 44f + y, width - 52f - 5f, 18f), gUIContent2, EditorStyles.whiteLabel); + } + else + { + GUI.Label(new Rect(52f - x - 5f, 44f + y, width - 52f - 5f, 18f), gUIContent2, EditorStyles.whiteLabel); + } + GUI.contentColor = Color.white; + } + else + { + Rect position6 = new Rect(52f - x - 5f, 44f + y, x, 18f); + GUI.Label(position6, gUIContent2); + } + } + if (base.targets.Length > 1) + { + GUI.Label(position5, "Instance Management Disabled", GameObjectInspector.s_styles.instanceManagementInfo); + } + else + { + if (prefabType != PrefabType.MissingPrefabInstance && GUI.Button(position2, "Select", "MiniButtonLeft")) + { + Selection.activeObject = PrefabUtility.GetPrefabParent(this.target); + EditorGUIUtility.PingObject(Selection.activeObject); + } + if ((prefabType == PrefabType.DisconnectedModelPrefabInstance || prefabType == PrefabType.DisconnectedPrefabInstance) && GUI.Button(position3, "Revert", "MiniButtonMid")) + { + Undo.RegisterFullObjectHierarchyUndo(gameObject, "Revert to prefab"); + PrefabUtility.ReconnectToLastPrefab(gameObject); + PrefabUtility.RevertPrefabInstance(gameObject); + this.CalculatePrefabStatus(); + Undo.RegisterCreatedObjectUndo(gameObject, "Reconnect prefab"); + GUIUtility.ExitGUI(); + } + bool enabled2 = GUI.enabled; + GUI.enabled = (GUI.enabled && !AnimationMode.InAnimationMode()); + if ((prefabType == PrefabType.ModelPrefabInstance || prefabType == PrefabType.PrefabInstance) && GUI.Button(position3, "Revert", "MiniButtonMid")) + { + Undo.RegisterFullObjectHierarchyUndo(gameObject, "Revert Prefab Instance"); + PrefabUtility.RevertPrefabInstance(gameObject); + this.CalculatePrefabStatus(); + GUIUtility.ExitGUI(); + } + if (prefabType == PrefabType.PrefabInstance || prefabType == PrefabType.DisconnectedPrefabInstance) + { + GameObject gameObject2 = PrefabUtility.FindValidUploadPrefabInstanceRoot(gameObject); + GUI.enabled = (gameObject2 != null && !AnimationMode.InAnimationMode()); + if (GUI.Button(position4, "Apply", "MiniButtonRight")) + { + UnityEngine.Object prefabParent = PrefabUtility.GetPrefabParent(gameObject2); + string assetPath = AssetDatabase.GetAssetPath(prefabParent); + bool flag2 = Provider.PromptAndCheckoutIfNeeded(new string[] + { + assetPath + }, "The version control requires you to checkout the prefab before applying changes."); + if (flag2) + { + PrefabUtility.ReplacePrefab(gameObject2, prefabParent, ReplacePrefabOptions.ConnectToPrefab); + this.CalculatePrefabStatus(); + GUIUtility.ExitGUI(); + } + } + } + GUI.enabled = enabled2; + if ((prefabType == PrefabType.DisconnectedModelPrefabInstance || prefabType == PrefabType.ModelPrefabInstance) && GUI.Button(position4, "Open", "MiniButtonRight")) + { + AssetDatabase.OpenAsset(PrefabUtility.GetPrefabParent(this.target)); + GUIUtility.ExitGUI(); + } + } + } + EditorGUI.EndDisabledGroup(); + base.serializedObject.ApplyModifiedProperties(); + return true; + } + private UnityEngine.Object[] GetObjects(bool includeChildren) + { + return SceneModeUtility.GetObjects(base.targets, includeChildren); + } + private void SetLayer(int layer, bool includeChildren) + { + UnityEngine.Object[] objects = this.GetObjects(includeChildren); + Undo.RecordObjects(objects, "Change Layer of " + this.targetTitle); + UnityEngine.Object[] array = objects; + for (int i = 0; i < array.Length; i++) + { + GameObject gameObject = (GameObject)array[i]; + gameObject.layer = layer; + } + } + public static void InitInstantiatedPreviewRecursive(GameObject go) + { + go.hideFlags = HideFlags.HideAndDontSave; + go.layer = 31; + foreach (Transform transform in go.transform) + { + GameObjectInspector.InitInstantiatedPreviewRecursive(transform.gameObject); + } + } + public static void SetEnabledRecursive(GameObject go, bool enabled) + { + Renderer[] componentsInChildren = go.GetComponentsInChildren(); + for (int i = 0; i < componentsInChildren.Length; i++) + { + Renderer renderer = componentsInChildren[i]; + renderer.enabled = enabled; + } + } + private void CreatePreviewInstances() + { + this.DestroyPreviewInstances(); + if (this.m_PreviewInstances == null) + { + this.m_PreviewInstances = new List(base.targets.Length); + } + for (int i = 0; i < base.targets.Length; i++) + { + GameObject gameObject = EditorUtility.InstantiateRemoveAllNonAnimationComponents(base.targets[i], Vector3.zero, Quaternion.identity) as GameObject; + GameObjectInspector.InitInstantiatedPreviewRecursive(gameObject); + Animator animator = gameObject.GetComponent(typeof(Animator)) as Animator; + if (animator) + { + animator.enabled = false; + animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; + animator.logWarnings = false; + animator.fireEvents = false; + } + GameObjectInspector.SetEnabledRecursive(gameObject, false); + this.m_PreviewInstances.Add(gameObject); + } + } + private void DestroyPreviewInstances() + { + if (this.m_PreviewInstances == null || this.m_PreviewInstances.Count == 0) + { + return; + } + foreach (GameObject current in this.m_PreviewInstances) + { + UnityEngine.Object.DestroyImmediate(current); + } + this.m_PreviewInstances.Clear(); + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(true); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + this.m_PreviewUtility.m_Camera.cullingMask = -2147483648; + this.CreatePreviewInstances(); + } + } + public void OnDestroy() + { + this.DestroyPreviewInstances(); + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + } + public static bool HasRenderablePartsRecurse(GameObject go) + { + MeshRenderer exists = go.GetComponent(typeof(MeshRenderer)) as MeshRenderer; + MeshFilter meshFilter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; + if (exists && meshFilter && meshFilter.sharedMesh) + { + return true; + } + SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent(typeof(SkinnedMeshRenderer)) as SkinnedMeshRenderer; + if (skinnedMeshRenderer && skinnedMeshRenderer.sharedMesh) + { + return true; + } + SpriteRenderer spriteRenderer = go.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer; + if (spriteRenderer && spriteRenderer.sprite) + { + return true; + } + foreach (Transform transform in go.transform) + { + if (GameObjectInspector.HasRenderablePartsRecurse(transform.gameObject)) + { + return true; + } + } + return false; + } + public static void GetRenderableBoundsRecurse(ref Bounds bounds, GameObject go) + { + MeshRenderer meshRenderer = go.GetComponent(typeof(MeshRenderer)) as MeshRenderer; + MeshFilter meshFilter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; + if (meshRenderer && meshFilter && meshFilter.sharedMesh) + { + if (bounds.extents == Vector3.zero) + { + bounds = meshRenderer.bounds; + } + else + { + bounds.Encapsulate(meshRenderer.bounds); + } + } + SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent(typeof(SkinnedMeshRenderer)) as SkinnedMeshRenderer; + if (skinnedMeshRenderer && skinnedMeshRenderer.sharedMesh) + { + if (bounds.extents == Vector3.zero) + { + bounds = skinnedMeshRenderer.bounds; + } + else + { + bounds.Encapsulate(skinnedMeshRenderer.bounds); + } + } + SpriteRenderer spriteRenderer = go.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer; + if (spriteRenderer && spriteRenderer.sprite) + { + if (bounds.extents == Vector3.zero) + { + bounds = spriteRenderer.bounds; + } + else + { + bounds.Encapsulate(spriteRenderer.bounds); + } + } + foreach (Transform transform in go.transform) + { + GameObjectInspector.GetRenderableBoundsRecurse(ref bounds, transform.gameObject); + } + } + private static float GetRenderableCenterRecurse(ref Vector3 center, GameObject go, int depth, int minDepth, int maxDepth) + { + if (depth > maxDepth) + { + return 0f; + } + float num = 0f; + if (depth > minDepth) + { + MeshRenderer meshRenderer = go.GetComponent(typeof(MeshRenderer)) as MeshRenderer; + MeshFilter x = go.GetComponent(typeof(MeshFilter)) as MeshFilter; + SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent(typeof(SkinnedMeshRenderer)) as SkinnedMeshRenderer; + SpriteRenderer spriteRenderer = go.GetComponent(typeof(SpriteRenderer)) as SpriteRenderer; + if (meshRenderer == null && x == null && skinnedMeshRenderer == null && spriteRenderer == null) + { + num = 1f; + center += go.transform.position; + } + else + { + if (meshRenderer != null && x != null) + { + if (Vector3.Distance(meshRenderer.bounds.center, go.transform.position) < 0.01f) + { + num = 1f; + center += go.transform.position; + } + } + else + { + if (skinnedMeshRenderer != null) + { + if (Vector3.Distance(skinnedMeshRenderer.bounds.center, go.transform.position) < 0.01f) + { + num = 1f; + center += go.transform.position; + } + } + else + { + if (spriteRenderer != null && Vector3.Distance(spriteRenderer.bounds.center, go.transform.position) < 0.01f) + { + num = 1f; + center += go.transform.position; + } + } + } + } + } + depth++; + foreach (Transform transform in go.transform) + { + num += GameObjectInspector.GetRenderableCenterRecurse(ref center, transform.gameObject, depth, minDepth, maxDepth); + } + return num; + } + public static Vector3 GetRenderableCenterRecurse(GameObject go, int minDepth, int maxDepth) + { + Vector3 vector = Vector3.zero; + float renderableCenterRecurse = GameObjectInspector.GetRenderableCenterRecurse(ref vector, go, 0, minDepth, maxDepth); + if (renderableCenterRecurse > 0f) + { + vector /= renderableCenterRecurse; + } + else + { + vector = go.transform.position; + } + return vector; + } + public override bool HasPreviewGUI() + { + return EditorUtility.IsPersistent(this.target) && this.HasStaticPreview(); + } + private bool HasStaticPreview() + { + if (base.targets.Length > 1) + { + return true; + } + if (this.target == null) + { + return false; + } + GameObject gameObject = this.target as GameObject; + Camera exists = gameObject.GetComponent(typeof(Camera)) as Camera; + return exists || GameObjectInspector.HasRenderablePartsRecurse(gameObject); + } + public override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + GUI.enabled = true; + this.InitPreview(); + } + private void DoRenderPreview() + { + GameObject gameObject = this.m_PreviewInstances[this.referenceTargetIndex]; + Bounds bounds = new Bounds(gameObject.transform.position, Vector3.zero); + GameObjectInspector.GetRenderableBoundsRecurse(ref bounds, gameObject); + float num = Mathf.Max(bounds.extents.magnitude, 0.0001f); + float num2 = num * 3.8f; + Quaternion quaternion = Quaternion.Euler(-this.previewDir.y, -this.previewDir.x, 0f); + Vector3 position = bounds.center - quaternion * (Vector3.forward * num2); + this.m_PreviewUtility.m_Camera.transform.position = position; + this.m_PreviewUtility.m_Camera.transform.rotation = quaternion; + this.m_PreviewUtility.m_Camera.nearClipPlane = num2 - num * 1.1f; + this.m_PreviewUtility.m_Camera.farClipPlane = num2 + num * 1.1f; + this.m_PreviewUtility.m_Light[0].intensity = 0.7f; + this.m_PreviewUtility.m_Light[0].transform.rotation = quaternion * Quaternion.Euler(40f, 40f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.7f; + this.m_PreviewUtility.m_Light[1].transform.rotation = quaternion * Quaternion.Euler(340f, 218f, 177f); + Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + GameObjectInspector.SetEnabledRecursive(gameObject, true); + this.m_PreviewUtility.m_Camera.Render(); + GameObjectInspector.SetEnabledRecursive(gameObject, false); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + InternalEditorUtility.RemoveCustomLighting(); + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!this.HasStaticPreview() || !ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + this.InitPreview(); + this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float)width, (float)height)); + this.DoRenderPreview(); + return this.m_PreviewUtility.EndStaticPreview(); + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Preview requires\nrender texture support"); + } + return; + } + this.InitPreview(); + this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + this.DoRenderPreview(); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + public void OnSceneDrag(SceneView sceneView) + { + GameObject gameObject = this.target as GameObject; + PrefabType prefabType = PrefabUtility.GetPrefabType(gameObject); + if (prefabType != PrefabType.Prefab && prefabType != PrefabType.ModelPrefab) + { + return; + } + Event current = Event.current; + EventType type = current.type; + if (type != EventType.DragUpdated) + { + if (type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + if (GameObjectInspector.dragObject) + { + UnityEngine.Object.DestroyImmediate(GameObjectInspector.dragObject, false); + HandleUtility.ignoreRaySnapObjects = null; + GameObjectInspector.dragObject = null; + current.Use(); + } + } + } + else + { + GameObjectInspector.dragObject.hideFlags = HideFlags.None; + Undo.RegisterCreatedObjectUndo(GameObjectInspector.dragObject, "Place " + GameObjectInspector.dragObject.name); + EditorUtility.SetDirty(GameObjectInspector.dragObject); + DragAndDrop.AcceptDrag(); + Selection.activeObject = GameObjectInspector.dragObject; + HandleUtility.ignoreRaySnapObjects = null; + EditorWindow.mouseOverWindow.Focus(); + GameObjectInspector.dragObject = null; + current.Use(); + } + } + else + { + if (GameObjectInspector.dragObject == null) + { + GameObjectInspector.dragObject = (GameObject)PrefabUtility.InstantiatePrefab(PrefabUtility.FindPrefabRoot(gameObject)); + HandleUtility.ignoreRaySnapObjects = GameObjectInspector.dragObject.GetComponentsInChildren(); + GameObjectInspector.dragObject.hideFlags = HideFlags.HideInHierarchy; + GameObjectInspector.dragObject.name = gameObject.name; + } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + object obj = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(current.mousePosition)); + if (obj != null) + { + RaycastHit raycastHit = (RaycastHit)obj; + float d = 0f; + if (Tools.pivotMode == PivotMode.Center) + { + float num = HandleUtility.CalcRayPlaceOffset(HandleUtility.ignoreRaySnapObjects, raycastHit.normal); + if (num != float.PositiveInfinity) + { + d = Vector3.Dot(GameObjectInspector.dragObject.transform.position, raycastHit.normal) - num; + } + } + GameObjectInspector.dragObject.transform.position = Matrix4x4.identity.MultiplyPoint(raycastHit.point + raycastHit.normal * d); + } + else + { + GameObjectInspector.dragObject.transform.position = HandleUtility.GUIPointToWorldRay(current.mousePosition).GetPoint(10f); + } + if (sceneView.in2DMode) + { + Vector3 position = GameObjectInspector.dragObject.transform.position; + position.z = PrefabUtility.FindPrefabRoot(gameObject).transform.position.z; + GameObjectInspector.dragObject.transform.position = position; + } + current.Use(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs b/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs new file mode 100644 index 00000000..ff042914 --- /dev/null +++ b/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class GameObjectTreeViewDataSource : LazyTreeViewDataSource + { + public class ComparerData + { + public BaseHierarchySort comparerImpl; + public bool comparerImplementsCompare = true; + } + private const double k_LongFetchTime = 0.05; + private const double k_FetchDelta = 0.1; + private const int k_MaxDelayedFetch = 5; + private const HierarchyType k_HierarchyType = HierarchyType.GameObjects; + private readonly int m_RootInstanceID; + private string m_SearchString = string.Empty; + private int m_SearchMode; + private double m_LastFetchTime; + private int m_DelayedFetches; + public GameObjectTreeViewDataSource.ComparerData compareData = new GameObjectTreeViewDataSource.ComparerData(); + public string searchString + { + get + { + return this.m_SearchString; + } + set + { + this.m_SearchString = value; + } + } + public int searchMode + { + get + { + return this.m_SearchMode; + } + set + { + this.m_SearchMode = value; + } + } + public bool isFetchAIssue + { + get + { + return this.m_DelayedFetches >= 5; + } + } + public GameObjectTreeViewDataSource(TreeView treeView, int rootInstanceID, bool showRootNode, bool rootNodeIsCollapsable) : base(treeView) + { + this.m_RootInstanceID = rootInstanceID; + this.showRootNode = showRootNode; + base.rootIsCollapsable = rootNodeIsCollapsable; + } + public int GetLastRootItemID() + { + TreeViewItem treeViewItem = this.m_VisibleRows[this.m_VisibleRows.Count - 1]; + if (treeViewItem != null) + { + while (treeViewItem.parent != null) + { + if (!base.showRootNode && treeViewItem.parent.id == this.m_RootInstanceID) + { + break; + } + treeViewItem = treeViewItem.parent; + } + } + return treeViewItem.id; + } + public override void FetchData() + { + int depth = 0; + double timeSinceStartup = EditorApplication.timeSinceStartup; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + hierarchyProperty.Reset(); + if (this.m_RootInstanceID != 0) + { + bool flag = hierarchyProperty.Find(this.m_RootInstanceID, null); + string displayName = (!flag) ? "RootOfSceneHierarchy" : hierarchyProperty.name; + this.m_RootItem = new GameObjectTreeViewItem(this.m_RootInstanceID, depth, null, displayName); + if (!flag) + { + Debug.LogError("Root gameobject with id " + this.m_RootInstanceID + " not found!!"); + } + } + else + { + this.m_RootItem = new GameObjectTreeViewItem(this.m_RootInstanceID, depth, null, "RootOfSceneHierarchy"); + } + if (!base.showRootNode) + { + this.SetExpanded(this.m_RootItem, true); + } + bool flag2 = !string.IsNullOrEmpty(this.m_SearchString); + if (flag2) + { + hierarchyProperty.SetSearchFilter(this.m_SearchString, this.m_SearchMode); + } + this.m_VisibleRows = this.CalcVisibleItems(hierarchyProperty, flag2); + TreeViewUtility.SetChildParentReferences(this.m_VisibleRows, this.m_RootItem); + if (this.compareData.comparerImpl != null && this.compareData.comparerImplementsCompare) + { + this.SortVisibleRows(); + } + double timeSinceStartup2 = EditorApplication.timeSinceStartup; + double num = timeSinceStartup2 - timeSinceStartup; + double num2 = timeSinceStartup2 - this.m_LastFetchTime; + if (num2 > 0.1 && num > 0.05) + { + this.m_DelayedFetches++; + } + else + { + this.m_DelayedFetches = 0; + } + this.m_LastFetchTime = timeSinceStartup; + this.m_NeedRefreshVisibleFolders = false; + this.m_TreeView.SetSelection(Selection.instanceIDs, false); + } + private List CalcVisibleItems(HierarchyProperty property, bool hasSearchString) + { + int depth = property.depth; + int[] expanded = base.expandedIDs.ToArray(); + List list = new List(); + while (property.NextWithDepthCheck(expanded, depth)) + { + int adjustedItemDepth = this.GetAdjustedItemDepth(hasSearchString, depth, property.depth); + GameObjectTreeViewItem item = this.CreateTreeViewItem(property, hasSearchString, adjustedItemDepth, true); + list.Add(item); + } + return list; + } + private GameObjectTreeViewItem CreateTreeViewItem(HierarchyProperty property, bool hasSearchString, int depth, bool shouldDisplay) + { + GameObjectTreeViewItem gameObjectTreeViewItem = new GameObjectTreeViewItem(property.instanceID, depth, null, property.name); + gameObjectTreeViewItem.colorCode = property.colorCode; + gameObjectTreeViewItem.objectPPTR = property.pptrValue; + gameObjectTreeViewItem.shouldDisplay = shouldDisplay; + if (!hasSearchString && property.hasChildren) + { + gameObjectTreeViewItem.AddChild(null); + } + return gameObjectTreeViewItem; + } + private int GetAdjustedItemDepth(bool hasSearchString, int minDepth, int adjPropertyDepth) + { + return (!hasSearchString) ? (adjPropertyDepth - minDepth) : 0; + } + protected override HashSet GetParentsAbove(int id) + { + HashSet hashSet = new HashSet(); + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + if (hierarchyProperty.Find(id, null)) + { + while (hierarchyProperty.Parent()) + { + hashSet.Add(hierarchyProperty.instanceID); + } + } + return hashSet; + } + protected override HashSet GetParentsBelow(int id) + { + HashSet hashSet = new HashSet(); + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + if (hierarchyProperty.Find(id, null)) + { + hashSet.Add(id); + int depth = hierarchyProperty.depth; + while (hierarchyProperty.Next(null) && hierarchyProperty.depth > depth) + { + if (hierarchyProperty.hasChildren) + { + hashSet.Add(hierarchyProperty.instanceID); + } + } + } + return hashSet; + } + private void SortVisibleRows() + { + this.SortChildrenRecursively(this.m_RootItem, this.compareData.comparerImpl); + this.m_VisibleRows.Clear(); + this.RebuildVisibilityTree(this.m_RootItem, this.m_VisibleRows); + } + private void SortChildrenRecursively(TreeViewItem item, BaseHierarchySort comparer) + { + if (item == null || !item.hasChildren) + { + return; + } + item.children = item.children.OrderBy((TreeViewItem x) => (x as GameObjectTreeViewItem).objectPPTR as GameObject, comparer).ToList(); + for (int i = 0; i < item.children.Count; i++) + { + this.SortChildrenRecursively(item.children[i], comparer); + } + } + private void RebuildVisibilityTree(TreeViewItem item, List visibleItems) + { + if (item == null || !item.hasChildren) + { + return; + } + for (int i = 0; i < item.children.Count; i++) + { + if (item.children[i] != null) + { + visibleItems.Add(item.children[i]); + this.RebuildVisibilityTree(item.children[i], visibleItems); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs b/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs new file mode 100644 index 00000000..be7da923 --- /dev/null +++ b/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs @@ -0,0 +1,114 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GameObjectTreeViewGUI : TreeViewGUI + { + private enum GameObjectColorType + { + Normal, + Prefab, + BrokenPrefab, + Count + } + internal class GameObjectStyles + { + public GUIStyle disabledLabel = new GUIStyle("PR DisabledLabel"); + public GUIStyle prefabLabel = new GUIStyle("PR PrefabLabel"); + public GUIStyle disabledPrefabLabel = new GUIStyle("PR DisabledPrefabLabel"); + public GUIStyle brokenPrefabLabel = new GUIStyle("PR BrokenPrefabLabel"); + public GUIStyle disabledBrokenPrefabLabel = new GUIStyle("PR DisabledBrokenPrefabLabel"); + public GameObjectStyles() + { + this.disabledLabel.alignment = TextAnchor.MiddleLeft; + this.prefabLabel.alignment = TextAnchor.MiddleLeft; + this.disabledPrefabLabel.alignment = TextAnchor.MiddleLeft; + this.brokenPrefabLabel.alignment = TextAnchor.MiddleLeft; + this.disabledBrokenPrefabLabel.alignment = TextAnchor.MiddleLeft; + } + } + protected static GameObjectTreeViewGUI.GameObjectStyles s_GOStyles; + public GameObjectTreeViewGUI(TreeView treeView, bool useHorizontalScroll) : base(treeView, useHorizontalScroll) + { + this.k_IconWidth = 0f; + this.k_TopRowMargin = 4f; + } + protected override void InitStyles() + { + base.InitStyles(); + if (GameObjectTreeViewGUI.s_GOStyles == null) + { + GameObjectTreeViewGUI.s_GOStyles = new GameObjectTreeViewGUI.GameObjectStyles(); + } + } + protected override void RenameEnded() + { + string text = (!string.IsNullOrEmpty(base.GetRenameOverlay().name)) ? base.GetRenameOverlay().name : base.GetRenameOverlay().originalName; + int userData = base.GetRenameOverlay().userData; + bool userAcceptedRename = base.GetRenameOverlay().userAcceptedRename; + if (userAcceptedRename) + { + ObjectNames.SetNameSmartWithInstanceID(userData, text); + TreeViewItem treeViewItem = this.m_TreeView.data.FindItem(userData); + if (treeViewItem != null) + { + treeViewItem.displayName = text; + } + } + } + protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + if (!isPinging) + { + float contentIndent = this.GetContentIndent(item); + rect.x += contentIndent; + rect.width -= contentIndent; + } + GameObjectTreeViewItem gameObjectTreeViewItem = item as GameObjectTreeViewItem; + int colorCode = gameObjectTreeViewItem.colorCode; + if (string.IsNullOrEmpty(item.displayName)) + { + if (gameObjectTreeViewItem.objectPPTR != null) + { + gameObjectTreeViewItem.displayName = gameObjectTreeViewItem.objectPPTR.name; + } + else + { + gameObjectTreeViewItem.displayName = "deleted gameobject"; + } + } + GUIStyle gUIStyle = TreeViewGUI.s_Styles.lineStyle; + if (!gameObjectTreeViewItem.shouldDisplay) + { + gUIStyle = GameObjectTreeViewGUI.s_GOStyles.disabledLabel; + } + else + { + if ((colorCode & 3) == 0) + { + gUIStyle = ((colorCode >= 4) ? GameObjectTreeViewGUI.s_GOStyles.disabledLabel : TreeViewGUI.s_Styles.lineStyle); + } + else + { + if ((colorCode & 3) == 1) + { + gUIStyle = ((colorCode >= 4) ? GameObjectTreeViewGUI.s_GOStyles.disabledPrefabLabel : GameObjectTreeViewGUI.s_GOStyles.prefabLabel); + } + else + { + if ((colorCode & 3) == 2) + { + gUIStyle = ((colorCode >= 4) ? GameObjectTreeViewGUI.s_GOStyles.disabledBrokenPrefabLabel : GameObjectTreeViewGUI.s_GOStyles.brokenPrefabLabel); + } + } + } + } + gUIStyle.padding.left = (int)this.k_SpaceBetweenIconAndText; + gUIStyle.Draw(rect, gameObjectTreeViewItem.displayName, false, false, selected, focused); + } + protected override Texture GetIconForNode(TreeViewItem item) + { + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/GameObjectTreeViewItem.cs b/UnityEditor/UnityEditor/GameObjectTreeViewItem.cs new file mode 100644 index 00000000..abab7cc9 --- /dev/null +++ b/UnityEditor/UnityEditor/GameObjectTreeViewItem.cs @@ -0,0 +1,69 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GameObjectTreeViewItem : TreeViewItem + { + private int m_ColorCode; + private UnityEngine.Object m_ObjectPPTR; + private bool m_ShouldDisplay; + public override string displayName + { + get + { + if (string.IsNullOrEmpty(base.displayName)) + { + if (this.m_ObjectPPTR != null) + { + this.displayName = this.objectPPTR.name; + } + else + { + this.displayName = "deleted gameobject"; + } + } + return base.displayName; + } + set + { + base.displayName = value; + } + } + public virtual int colorCode + { + get + { + return this.m_ColorCode; + } + set + { + this.m_ColorCode = value; + } + } + public virtual UnityEngine.Object objectPPTR + { + get + { + return this.m_ObjectPPTR; + } + set + { + this.m_ObjectPPTR = value; + } + } + public virtual bool shouldDisplay + { + get + { + return this.m_ShouldDisplay; + } + set + { + this.m_ShouldDisplay = value; + } + } + public GameObjectTreeViewItem(int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) + { + } + } +} diff --git a/UnityEditor/UnityEditor/GameObjectUtility.cs b/UnityEditor/UnityEditor/GameObjectUtility.cs new file mode 100644 index 00000000..5fdf960d --- /dev/null +++ b/UnityEditor/UnityEditor/GameObjectUtility.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class GameObjectUtility + { + internal enum ShouldIncludeChildren + { + HasNoChildren = -1, + IncludeChildren, + DontIncludeChildren, + Cancel + } + internal static bool ContainsStatic(GameObject[] objects) + { + if (objects == null || objects.Length == 0) + { + return false; + } + for (int i = 0; i < objects.Length; i++) + { + if (objects[i] != null && objects[i].isStatic) + { + return true; + } + } + return false; + } + internal static bool HasChildren(IEnumerable gameObjects) + { + return gameObjects.Any((GameObject go) => go.transform.childCount > 0); + } + internal static GameObjectUtility.ShouldIncludeChildren DisplayUpdateChildrenDialogIfNeeded(IEnumerable gameObjects, string title, string message) + { + if (!GameObjectUtility.HasChildren(gameObjects)) + { + return GameObjectUtility.ShouldIncludeChildren.HasNoChildren; + } + return (GameObjectUtility.ShouldIncludeChildren)EditorUtility.DisplayDialogComplex(title, message, "Yes, change children", "No, this object only", "Cancel"); + } + public static void SetParentAndAlign(GameObject child, GameObject parent) + { + if (parent == null) + { + return; + } + child.transform.SetParent(parent.transform, false); + RectTransform rectTransform = child.transform as RectTransform; + if (rectTransform) + { + rectTransform.anchoredPosition = Vector2.zero; + Vector3 localPosition = rectTransform.localPosition; + localPosition.z = 0f; + rectTransform.localPosition = localPosition; + } + else + { + child.transform.localPosition = Vector3.zero; + } + child.transform.localRotation = Quaternion.identity; + child.transform.localScale = Vector3.one; + child.layer = parent.layer; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern StaticEditorFlags GetStaticEditorFlags(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AreStaticEditorFlagsSet(GameObject go, StaticEditorFlags flags); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticEditorFlags(GameObject go, StaticEditorFlags flags); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshLayer(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshLayerFromName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNavMeshLayer(GameObject go, int layer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetNavMeshLayerNames(); + [Obsolete("use AnimatorUtility.OptimizeTransformHierarchy instead.")] + private static void OptimizeTransformHierarchy(GameObject go) + { + AnimatorUtility.OptimizeTransformHierarchy(go, null); + } + [Obsolete("use AnimatorUtility.DeoptimizeTransformHierarchy instead.")] + private static void DeoptimizeTransformHierarchy(GameObject go) + { + AnimatorUtility.DeoptimizeTransformHierarchy(go); + } + } +} diff --git a/UnityEditor/UnityEditor/GameView.cs b/UnityEditor/UnityEditor/GameView.cs new file mode 100644 index 00000000..4d7d8a08 --- /dev/null +++ b/UnityEditor/UnityEditor/GameView.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + internal class GameView : EditorWindow + { + private const int kToolbarHeight = 17; + private const int kBorderSize = 5; + [SerializeField] + private bool m_MaximizeOnPlay; + [SerializeField] + private bool m_Gizmos; + [SerializeField] + private bool m_Stats; + [SerializeField] + private int[] m_SelectedSizes = new int[0]; + private int m_SizeChangeID = -2147483648; + private GUIContent gizmosContent = new GUIContent("Gizmos"); + private static GUIStyle s_GizmoButtonStyle; + private static GUIStyle s_ResolutionWarningStyle; + private static List s_GameViews = new List(); + private static GameView s_LastFocusedGameView = null; + private static Rect s_MainGameViewRect = new Rect(0f, 0f, 640f, 480f); + private Vector2 m_ShownResolution = Vector2.zero; + private AnimBool m_ResolutionTooLargeWarning = new AnimBool(false); + public bool maximizeOnPlay + { + get + { + return this.m_MaximizeOnPlay; + } + set + { + this.m_MaximizeOnPlay = value; + } + } + private int selectedSizeIndex + { + get + { + return this.m_SelectedSizes[(int)GameView.currentSizeGroupType]; + } + set + { + this.m_SelectedSizes[(int)GameView.currentSizeGroupType] = value; + } + } + private static GameViewSizeGroupType currentSizeGroupType + { + get + { + return ScriptableSingleton.instance.currentGroupType; + } + } + private GameViewSize currentGameViewSize + { + get + { + return ScriptableSingleton.instance.currentGroup.GetGameViewSize(this.selectedSizeIndex); + } + } + private Rect gameViewRenderRect + { + get + { + return new Rect(0f, 17f, base.position.width, base.position.height - 17f); + } + } + public GameView() + { + base.depthBufferBits = 32; + base.antiAlias = -1; + base.autoRepaintOnSceneChange = true; + } + public void OnValidate() + { + this.EnsureSelectedSizeAreValid(); + } + public void OnEnable() + { + this.EnsureSelectedSizeAreValid(); + base.dontClearBackground = true; + GameView.s_GameViews.Add(this); + this.m_ResolutionTooLargeWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ResolutionTooLargeWarning.speed = 0.3f; + } + public void OnDisable() + { + GameView.s_GameViews.Remove(this); + this.m_ResolutionTooLargeWarning.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.DoDelayedGameViewChanged)); + } + internal static GameView GetMainGameView() + { + if (GameView.s_LastFocusedGameView == null && GameView.s_GameViews != null && GameView.s_GameViews.Count > 0) + { + GameView.s_LastFocusedGameView = GameView.s_GameViews[0]; + } + return GameView.s_LastFocusedGameView; + } + public static void RepaintAll() + { + if (GameView.s_GameViews == null) + { + return; + } + foreach (GameView current in GameView.s_GameViews) + { + current.Repaint(); + } + } + internal static Vector2 GetSizeOfMainGameView() + { + Rect mainGameViewRenderRect = GameView.GetMainGameViewRenderRect(); + return new Vector2(mainGameViewRenderRect.width, mainGameViewRenderRect.height); + } + internal static Rect GetMainGameViewRenderRect() + { + GameView mainGameView = GameView.GetMainGameView(); + if (mainGameView != null) + { + GameView.s_MainGameViewRect = mainGameView.GetConstrainedGameViewRenderRect(); + } + return GameView.s_MainGameViewRect; + } + private void GameViewAspectWasChanged() + { + base.SetInternalGameViewRect(GameView.GetConstrainedGameViewRenderRect(this.gameViewRenderRect, this.selectedSizeIndex)); + EditorApplication.SetSceneRepaintDirty(); + } + private void OnFocus() + { + GameView.s_LastFocusedGameView = this; + InternalEditorUtility.OnGameViewFocus(true); + } + private void OnLostFocus() + { + if (!EditorApplicationLayout.IsInitializingPlaymodeLayout()) + { + Unsupported.SetAllowCursorLock(false); + Unsupported.SetAllowCursorHide(false); + } + InternalEditorUtility.OnGameViewFocus(false); + } + private void DelayedGameViewChanged() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.DoDelayedGameViewChanged)); + } + private void DoDelayedGameViewChanged() + { + this.GameViewAspectWasChanged(); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.DoDelayedGameViewChanged)); + } + internal override void OnResized() + { + this.DelayedGameViewChanged(); + } + private void EnsureSelectedSizeAreValid() + { + int num = Enum.GetNames(typeof(GameViewSizeGroupType)).Length; + if (this.m_SelectedSizes.Length != num) + { + Array.Resize(ref this.m_SelectedSizes, num); + } + IEnumerator enumerator = Enum.GetValues(typeof(GameViewSizeGroupType)).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + GameViewSizeGroupType gameViewSizeGroupType = (GameViewSizeGroupType)((int)enumerator.Current); + GameViewSizeGroup group = ScriptableSingleton.instance.GetGroup(gameViewSizeGroupType); + int num2 = (int)gameViewSizeGroupType; + this.m_SelectedSizes[num2] = Mathf.Clamp(this.m_SelectedSizes[num2], 0, group.GetTotalCount() - 1); + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + } + public bool IsShowingGizmos() + { + return this.m_Gizmos; + } + private void OnSelectionChange() + { + if (this.m_Gizmos) + { + base.Repaint(); + } + } + internal static Rect GetConstrainedGameViewRenderRect(Rect renderRect, int sizeIndex) + { + bool flag; + return GameView.GetConstrainedGameViewRenderRect(renderRect, sizeIndex, out flag); + } + internal static Rect GetConstrainedGameViewRenderRect(Rect renderRect, int sizeIndex, out bool fitsInsideRect) + { + return GameViewSizes.GetConstrainedRect(renderRect, GameView.currentSizeGroupType, sizeIndex, out fitsInsideRect); + } + internal Rect GetConstrainedGameViewRenderRect() + { + if (this.m_Parent == null) + { + return GameView.s_MainGameViewRect; + } + this.m_Pos = this.m_Parent.borderSize.Remove(this.m_Parent.position); + return GameView.GetConstrainedGameViewRenderRect(this.gameViewRenderRect, this.selectedSizeIndex); + } + private void SelectionCallback(int indexClicked, object objectSelected) + { + if (indexClicked != this.selectedSizeIndex) + { + this.selectedSizeIndex = indexClicked; + base.dontClearBackground = true; + this.GameViewAspectWasChanged(); + } + } + private void DoToolbarGUI() + { + ScriptableSingleton.instance.RefreshStandaloneAndWebplayerDefaultSizes(); + if (ScriptableSingleton.instance.GetChangeID() != this.m_SizeChangeID) + { + this.EnsureSelectedSizeAreValid(); + this.m_SizeChangeID = ScriptableSingleton.instance.GetChangeID(); + } + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + EditorGUILayout.GameViewSizePopup(GameView.currentSizeGroupType, this.selectedSizeIndex, new Action(this.SelectionCallback), EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(160f) + }); + GUILayout.FlexibleSpace(); + this.m_MaximizeOnPlay = GUILayout.Toggle(this.m_MaximizeOnPlay, "Maximize on Play", EditorStyles.toolbarButton, new GUILayoutOption[0]); + this.m_Stats = GUILayout.Toggle(this.m_Stats, "Stats", EditorStyles.toolbarButton, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(this.gizmosContent, GameView.s_GizmoButtonStyle); + Rect position = new Rect(rect.xMax - (float)GameView.s_GizmoButtonStyle.border.right, rect.y, (float)GameView.s_GizmoButtonStyle.border.right, rect.height); + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none)) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + if (AnnotationWindow.ShowAtPosition(last, true)) + { + GUIUtility.ExitGUI(); + } + } + this.m_Gizmos = GUI.Toggle(rect, this.m_Gizmos, this.gizmosContent, GameView.s_GizmoButtonStyle); + GUILayout.EndHorizontal(); + } + private void OnGUI() + { + if (GameView.s_GizmoButtonStyle == null) + { + GameView.s_GizmoButtonStyle = "GV Gizmo DropDown"; + GameView.s_ResolutionWarningStyle = new GUIStyle("PreOverlayLabel"); + GameView.s_ResolutionWarningStyle.alignment = TextAnchor.UpperLeft; + GameView.s_ResolutionWarningStyle.padding = new RectOffset(6, 6, 1, 1); + } + this.DoToolbarGUI(); + Rect gameViewRenderRect = this.gameViewRenderRect; + bool fitsInsideRect; + Rect constrainedGameViewRenderRect = GameView.GetConstrainedGameViewRenderRect(gameViewRenderRect, this.selectedSizeIndex, out fitsInsideRect); + Rect rect = GUIClip.Unclip(constrainedGameViewRenderRect); + base.SetInternalGameViewRect(rect); + EditorGUIUtility.AddCursorRect(constrainedGameViewRenderRect, MouseCursor.CustomCursor); + EventType type = Event.current.type; + if (type == EventType.MouseDown && gameViewRenderRect.Contains(Event.current.mousePosition)) + { + Unsupported.SetAllowCursorLock(true); + Unsupported.SetAllowCursorHide(true); + } + else + { + if (type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + Unsupported.SetAllowCursorLock(false); + } + } + if (type == EventType.Repaint) + { + if (!this.currentGameViewSize.isFreeAspectRatio || !InternalEditorUtility.HasFullscreenCamera()) + { + GUI.Box(gameViewRenderRect, GUIContent.none, "GameViewBackground"); + } + Vector2 s_EditorScreenPointOffset = GUIUtility.s_EditorScreenPointOffset; + GUIUtility.s_EditorScreenPointOffset = Vector2.zero; + SavedGUIState savedGUIState = SavedGUIState.Create(); + EditorGUIUtility.RenderGameViewCameras(rect, this.m_Gizmos, true); + savedGUIState.ApplyAndForget(); + GUIUtility.s_EditorScreenPointOffset = s_EditorScreenPointOffset; + } + else + { + if (type != EventType.Layout && type != EventType.Used) + { + if (WindowLayout.s_MaximizeKey.activated && (!EditorApplication.isPlaying || EditorApplication.isPaused)) + { + return; + } + bool flag = constrainedGameViewRenderRect.Contains(Event.current.mousePosition); + if (Event.current.rawType == EventType.MouseDown && !flag) + { + return; + } + Event.current.mousePosition = new Vector2(Event.current.mousePosition.x - constrainedGameViewRenderRect.x, Event.current.mousePosition.y - constrainedGameViewRenderRect.y); + EditorGUIUtility.QueueGameViewInputEvent(Event.current); + bool flag2 = true; + if (Event.current.rawType == EventType.MouseUp && !flag) + { + flag2 = false; + } + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + flag2 = false; + } + if (flag2) + { + Event.current.Use(); + } + else + { + Event.current.mousePosition = new Vector2(Event.current.mousePosition.x + constrainedGameViewRenderRect.x, Event.current.mousePosition.y + constrainedGameViewRenderRect.y); + } + } + } + this.ShowResolutionWarning(new Rect(gameViewRenderRect.x, gameViewRenderRect.y, 200f, 20f), fitsInsideRect, constrainedGameViewRenderRect.size); + if (this.m_Stats) + { + GameViewGUI.GameViewStatsGUI(); + } + } + private void ShowResolutionWarning(Rect position, bool fitsInsideRect, Vector2 shownSize) + { + if (!fitsInsideRect && shownSize != this.m_ShownResolution) + { + this.m_ShownResolution = shownSize; + this.m_ResolutionTooLargeWarning.value = true; + } + if (fitsInsideRect && this.m_ShownResolution != Vector2.zero) + { + this.m_ShownResolution = Vector2.zero; + this.m_ResolutionTooLargeWarning.value = false; + } + this.m_ResolutionTooLargeWarning.target = (!fitsInsideRect && !EditorApplication.isPlaying); + if (this.m_ResolutionTooLargeWarning.faded > 0f) + { + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, Mathf.Clamp01(this.m_ResolutionTooLargeWarning.faded * 2f)); + EditorGUI.DropShadowLabel(position, string.Format("Using resolution {0}x{1}", shownSize.x, shownSize.y), GameView.s_ResolutionWarningStyle); + GUI.color = color; + } + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewGUI.cs b/UnityEditor/UnityEditor/GameViewGUI.cs new file mode 100644 index 00000000..541cf394 --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewGUI.cs @@ -0,0 +1,118 @@ +using System; +using System.Text; +using UnityEngine; +namespace UnityEditor +{ + internal class GameViewGUI + { + private static int m_FrameCounter; + private static float m_ClientTimeAccumulator; + private static float m_RenderTimeAccumulator; + private static float m_MaxTimeAccumulator; + private static float m_ClientFrameTime; + private static float m_RenderFrameTime; + private static float m_MaxFrameTime; + private static GUIStyle s_SectionHeaderStyle; + private static GUIStyle sectionHeaderStyle + { + get + { + if (GameViewGUI.s_SectionHeaderStyle == null) + { + GameViewGUI.s_SectionHeaderStyle = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene).GetStyle("BoldLabel"); + } + return GameViewGUI.s_SectionHeaderStyle; + } + } + private static string FormatNumber(int num) + { + if (num < 1000) + { + return num.ToString(); + } + if (num < 1000000) + { + return ((double)num * 0.001).ToString("f1") + "k"; + } + return ((double)num * 1E-06).ToString("f1") + "M"; + } + private static void UpdateFrameTime() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + float frameTime = UnityStats.frameTime; + float renderTime = UnityStats.renderTime; + GameViewGUI.m_ClientTimeAccumulator += frameTime; + GameViewGUI.m_RenderTimeAccumulator += renderTime; + GameViewGUI.m_MaxTimeAccumulator += Mathf.Max(frameTime, renderTime); + GameViewGUI.m_FrameCounter++; + bool flag = GameViewGUI.m_ClientFrameTime == 0f && GameViewGUI.m_RenderFrameTime == 0f; + bool flag2 = GameViewGUI.m_FrameCounter > 30 || GameViewGUI.m_ClientTimeAccumulator > 0.3f || GameViewGUI.m_RenderTimeAccumulator > 0.3f; + if (flag || flag2) + { + GameViewGUI.m_ClientFrameTime = GameViewGUI.m_ClientTimeAccumulator / (float)GameViewGUI.m_FrameCounter; + GameViewGUI.m_RenderFrameTime = GameViewGUI.m_RenderTimeAccumulator / (float)GameViewGUI.m_FrameCounter; + GameViewGUI.m_MaxFrameTime = GameViewGUI.m_MaxTimeAccumulator / (float)GameViewGUI.m_FrameCounter; + } + if (flag2) + { + GameViewGUI.m_ClientTimeAccumulator = 0f; + GameViewGUI.m_RenderTimeAccumulator = 0f; + GameViewGUI.m_MaxTimeAccumulator = 0f; + GameViewGUI.m_FrameCounter = 0; + } + } + public static void GameViewStatsGUI() + { + GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); + GUI.color = new Color(1f, 1f, 1f, 0.75f); + float num = 300f; + float num2 = 200f; + int num3 = Network.connections.Length; + if (num3 != 0) + { + num2 += 220f; + } + GUILayout.BeginArea(new Rect((float)Screen.width - num - 10f, 27f, num, num2), "Statistics", GUI.skin.window); + GUILayout.Label("Graphics:", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); + GameViewGUI.UpdateFrameTime(); + string text = string.Format("{0:F1} FPS ({1:F1}ms)", 1f / Mathf.Max(GameViewGUI.m_MaxFrameTime, 1E-05f), GameViewGUI.m_MaxFrameTime * 1000f); + GUI.Label(new Rect(170f, 19f, 120f, 20f), text); + int usedTextureMemorySize = UnityStats.usedTextureMemorySize; + int renderTextureBytes = UnityStats.renderTextureBytes; + int screenBytes = UnityStats.screenBytes; + int vboTotalBytes = UnityStats.vboTotalBytes; + int bytes = screenBytes + renderTextureBytes; + int bytes2 = screenBytes + Mathf.Max(usedTextureMemorySize, renderTextureBytes) + vboTotalBytes; + StringBuilder stringBuilder = new StringBuilder(400); + stringBuilder.Append(string.Format(" Main Thread: {0:F1}ms Renderer: {1:F1}ms\n", GameViewGUI.m_ClientFrameTime * 1000f, GameViewGUI.m_RenderFrameTime * 1000f)); + stringBuilder.Append(string.Format(" Draw Calls: {0} \tSaved by batching: {1} \n", UnityStats.drawCalls, UnityStats.batchedDrawCalls - UnityStats.batches)); + stringBuilder.Append(string.Format(" Tris: {0} \tVerts: {1} \n", GameViewGUI.FormatNumber(UnityStats.triangles), GameViewGUI.FormatNumber(UnityStats.vertices))); + stringBuilder.Append(string.Format(" Used Textures: {0} - {1}\n", UnityStats.usedTextureCount, EditorUtility.FormatBytes(usedTextureMemorySize))); + stringBuilder.Append(string.Format(" Render Textures: {0} - {1} \tswitches: {2}\n", UnityStats.renderTextureCount, EditorUtility.FormatBytes(renderTextureBytes), UnityStats.renderTextureChanges)); + stringBuilder.Append(string.Format(" Screen: {0} - {1}\n", UnityStats.screenRes, EditorUtility.FormatBytes(screenBytes))); + stringBuilder.Append(string.Format(" VRAM usage: {0} to {1} (of {2})\n", EditorUtility.FormatBytes(bytes), EditorUtility.FormatBytes(bytes2), EditorUtility.FormatBytes(SystemInfo.graphicsMemorySize * 1024 * 1024))); + stringBuilder.Append(string.Format(" VBO Total: {0} - {1}\n", UnityStats.vboTotal, EditorUtility.FormatBytes(vboTotalBytes))); + stringBuilder.Append(string.Format(" Shadow Casters: {0} \n", UnityStats.shadowCasters)); + stringBuilder.Append(string.Format(" Visible Skinned Meshes: {0} \t Animations: {1}", UnityStats.visibleSkinnedMeshes, UnityStats.visibleAnimations)); + GUILayout.Label(stringBuilder.ToString(), new GUILayoutOption[0]); + if (num3 != 0) + { + GUILayout.Label("Network:", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + for (int i = 0; i < num3; i++) + { + GUILayout.Label(UnityStats.GetNetworkStats(i), new GUILayoutOption[0]); + } + GUILayout.EndHorizontal(); + } + else + { + GUILayout.Label("Network: (no players connected)", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); + } + GUILayout.EndArea(); + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewSize.cs b/UnityEditor/UnityEditor/GameViewSize.cs new file mode 100644 index 00000000..2c820ee4 --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSize.cs @@ -0,0 +1,188 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class GameViewSize + { + private const int kMaxBaseTextLength = 40; + private const int kMinResolution = 10; + private const int kMinAspect = 0; + private const int kMaxResolutionOrAspect = 99999; + [SerializeField] + private string m_BaseText; + [SerializeField] + private GameViewSizeType m_SizeType; + [SerializeField] + private int m_Width; + [SerializeField] + private int m_Height; + [NonSerialized] + private string m_CachedDisplayText; + public string baseText + { + get + { + return this.m_BaseText; + } + set + { + this.m_BaseText = value; + if (this.m_BaseText.Length > 40) + { + this.m_BaseText = this.m_BaseText.Substring(0, 40); + } + this.Changed(); + } + } + public GameViewSizeType sizeType + { + get + { + return this.m_SizeType; + } + set + { + this.m_SizeType = value; + this.Clamp(); + this.Changed(); + } + } + public int width + { + get + { + return this.m_Width; + } + set + { + this.m_Width = value; + this.Clamp(); + this.Changed(); + } + } + public int height + { + get + { + return this.m_Height; + } + set + { + this.m_Height = value; + this.Clamp(); + this.Changed(); + } + } + public bool isFreeAspectRatio + { + get + { + return this.width == 0; + } + } + public float aspectRatio + { + get + { + if (this.height == 0) + { + return 0f; + } + return (float)this.width / (float)this.height; + } + } + public string displayText + { + get + { + string arg_1C_0; + if ((arg_1C_0 = this.m_CachedDisplayText) == null) + { + arg_1C_0 = (this.m_CachedDisplayText = this.ComposeDisplayString()); + } + return arg_1C_0; + } + } + private string sizeText + { + get + { + if (this.sizeType == GameViewSizeType.AspectRatio) + { + return string.Format("{0}:{1}", this.width, this.height); + } + if (this.sizeType == GameViewSizeType.FixedResolution) + { + return string.Format("{0}x{1}", this.width, this.height); + } + Debug.LogError("Unhandled game view size type"); + return string.Empty; + } + } + public GameViewSize(GameViewSizeType type, int width, int height, string baseText) + { + this.sizeType = type; + this.width = width; + this.height = height; + this.baseText = baseText; + } + public GameViewSize(GameViewSize other) + { + this.Set(other); + } + private void Clamp() + { + int width = this.m_Width; + int height = this.m_Height; + int min = 0; + GameViewSizeType sizeType = this.sizeType; + if (sizeType != GameViewSizeType.AspectRatio) + { + if (sizeType != GameViewSizeType.FixedResolution) + { + Debug.LogError("Unhandled enum!"); + } + else + { + min = 10; + } + } + else + { + min = 0; + } + this.m_Width = Mathf.Clamp(this.m_Width, min, 99999); + this.m_Height = Mathf.Clamp(this.m_Height, min, 99999); + if (this.m_Width != width || this.m_Height != height) + { + this.Changed(); + } + } + public void Set(GameViewSize other) + { + this.sizeType = other.sizeType; + this.width = other.width; + this.height = other.height; + this.baseText = other.baseText; + this.Changed(); + } + private string ComposeDisplayString() + { + if (this.width == 0 && this.height == 0) + { + return this.baseText; + } + if (string.IsNullOrEmpty(this.baseText)) + { + return this.sizeText; + } + return this.baseText + " (" + this.sizeText + ")"; + } + private void Changed() + { + this.m_CachedDisplayText = null; + ScriptableSingleton.instance.Changed(); + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizeGroup.cs b/UnityEditor/UnityEditor/GameViewSizeGroup.cs new file mode 100644 index 00000000..95e14ba9 --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizeGroup.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class GameViewSizeGroup + { + [NonSerialized] + private List m_Builtin = new List(); + [SerializeField] + private List m_Custom = new List(); + public GameViewSize GetGameViewSize(int index) + { + if (index < this.m_Builtin.Count) + { + return this.m_Builtin[index]; + } + index -= this.m_Builtin.Count; + if (index >= 0 && index < this.m_Custom.Count) + { + return this.m_Custom[index]; + } + Debug.LogError(string.Concat(new object[] + { + "Invalid index ", + index + this.m_Builtin.Count, + " ", + this.m_Builtin.Count, + " ", + this.m_Custom.Count + })); + return new GameViewSize(GameViewSizeType.AspectRatio, 0, 0, string.Empty); + } + public string[] GetDisplayTexts() + { + List list = new List(); + foreach (GameViewSize current in this.m_Builtin) + { + list.Add(current.displayText); + } + foreach (GameViewSize current2 in this.m_Custom) + { + list.Add(current2.displayText); + } + return list.ToArray(); + } + public int GetTotalCount() + { + return this.m_Builtin.Count + this.m_Custom.Count; + } + public int GetBuiltinCount() + { + return this.m_Builtin.Count; + } + public int GetCustomCount() + { + return this.m_Custom.Count; + } + public void AddBuiltinSizes(params GameViewSize[] sizes) + { + for (int i = 0; i < sizes.Length; i++) + { + this.AddBuiltinSize(sizes[i]); + } + } + public void AddBuiltinSize(GameViewSize size) + { + this.m_Builtin.Add(size); + ScriptableSingleton.instance.Changed(); + } + public void AddCustomSizes(params GameViewSize[] sizes) + { + for (int i = 0; i < sizes.Length; i++) + { + this.AddCustomSize(sizes[i]); + } + } + public void AddCustomSize(GameViewSize size) + { + this.m_Custom.Add(size); + ScriptableSingleton.instance.Changed(); + } + public void RemoveCustomSize(int index) + { + int num = this.TotalIndexToCustomIndex(index); + if (num >= 0 && num < this.m_Custom.Count) + { + this.m_Custom.RemoveAt(num); + ScriptableSingleton.instance.Changed(); + } + else + { + Debug.LogError(string.Concat(new object[] + { + "Invalid index ", + index, + " ", + this.m_Builtin.Count, + " ", + this.m_Custom.Count + })); + } + } + public bool IsCustomSize(int index) + { + return index >= this.m_Builtin.Count; + } + public int TotalIndexToCustomIndex(int index) + { + return index - this.m_Builtin.Count; + } + public int IndexOf(GameViewSize view) + { + int num = this.m_Builtin.IndexOf(view); + if (num >= 0) + { + return num; + } + return this.m_Custom.IndexOf(view); + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizeGroupType.cs b/UnityEditor/UnityEditor/GameViewSizeGroupType.cs new file mode 100644 index 00000000..dcca2ec4 --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizeGroupType.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditor +{ + public enum GameViewSizeGroupType + { + Standalone, + WebPlayer, + iOS, + Android, + PS3, + Xbox360, + BB10, + Tizen, + WP8 + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizeType.cs b/UnityEditor/UnityEditor/GameViewSizeType.cs new file mode 100644 index 00000000..8caf085f --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizeType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum GameViewSizeType + { + AspectRatio, + FixedResolution + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizes.cs b/UnityEditor/UnityEditor/GameViewSizes.cs new file mode 100644 index 00000000..b241061c --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizes.cs @@ -0,0 +1,470 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [FilePath("GameViewSizes.asset", FilePathAttribute.Location.PreferencesFolder)] + internal class GameViewSizes : ScriptableSingleton + { + [SerializeField] + private GameViewSizeGroup m_Standalone = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_WebPlayer = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_iOS = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_Android = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_XBox360 = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_PS3 = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_BB10 = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_Tizen = new GameViewSizeGroup(); + [SerializeField] + private GameViewSizeGroup m_WP8 = new GameViewSizeGroup(); + [NonSerialized] + private GameViewSize m_Remote; + [NonSerialized] + private Vector2 m_LastStandaloneScreenSize = new Vector2(-1f, -1f); + [NonSerialized] + private Vector2 m_LastWebPlayerScreenSize = new Vector2(-1f, -1f); + [NonSerialized] + private Vector2 m_LastRemoteScreenSize = new Vector2(-1f, -1f); + [NonSerialized] + private int m_ChangeID; + [NonSerialized] + private static GameViewSizeGroupType s_GameViewSizeGroupType; + public GameViewSizeGroupType currentGroupType + { + get + { + return GameViewSizes.s_GameViewSizeGroupType; + } + } + public GameViewSizeGroup currentGroup + { + get + { + return this.GetGroup(GameViewSizes.s_GameViewSizeGroupType); + } + } + static GameViewSizes() + { + GameViewSizes.RefreshGameViewSizeGroupType(); + EditorUserBuildSettings.activeBuildTargetChanged = (Action)Delegate.Combine(EditorUserBuildSettings.activeBuildTargetChanged, delegate + { + GameViewSizes.RefreshGameViewSizeGroupType(); + }); + } + public GameViewSizeGroup GetGroup(GameViewSizeGroupType gameViewSizeGroupType) + { + this.InitBuiltinGroups(); + switch (gameViewSizeGroupType) + { + case GameViewSizeGroupType.Standalone: + return this.m_Standalone; + case GameViewSizeGroupType.WebPlayer: + return this.m_WebPlayer; + case GameViewSizeGroupType.iOS: + return this.m_iOS; + case GameViewSizeGroupType.Android: + return this.m_Android; + case GameViewSizeGroupType.PS3: + return this.m_PS3; + case GameViewSizeGroupType.Xbox360: + return this.m_XBox360; + case GameViewSizeGroupType.BB10: + return this.m_BB10; + case GameViewSizeGroupType.Tizen: + return this.m_Tizen; + case GameViewSizeGroupType.WP8: + return this.m_WP8; + default: + Debug.LogError("Unhandled group enum! " + gameViewSizeGroupType); + return this.m_Standalone; + } + } + public void SaveToHDD() + { + bool saveAsText = true; + this.Save(saveAsText); + } + public bool IsDefaultStandaloneScreenSize(GameViewSizeGroupType gameViewSizeGroupType, int index) + { + return gameViewSizeGroupType == GameViewSizeGroupType.Standalone && this.GetDefaultStandaloneIndex() == index; + } + public bool IsDefaultWebPlayerScreenSize(GameViewSizeGroupType gameViewSizeGroupType, int index) + { + return gameViewSizeGroupType == GameViewSizeGroupType.WebPlayer && this.GetDefaultWebPlayerIndex() == index; + } + public bool IsRemoteScreenSize(GameViewSizeGroupType gameViewSizeGroupType, int index) + { + return this.GetGroup(gameViewSizeGroupType).IndexOf(this.m_Remote) == index; + } + public int GetDefaultStandaloneIndex() + { + return this.m_Standalone.GetBuiltinCount() - 1; + } + public int GetDefaultWebPlayerIndex() + { + return this.m_WebPlayer.GetBuiltinCount() - 1; + } + public void RefreshStandaloneAndWebplayerDefaultSizes() + { + if (InternalEditorUtility.defaultScreenWidth != this.m_LastStandaloneScreenSize.x || InternalEditorUtility.defaultScreenHeight != this.m_LastStandaloneScreenSize.y) + { + this.m_LastStandaloneScreenSize = new Vector2(InternalEditorUtility.defaultScreenWidth, InternalEditorUtility.defaultScreenHeight); + this.RefreshStandaloneDefaultScreenSize((int)this.m_LastStandaloneScreenSize.x, (int)this.m_LastStandaloneScreenSize.y); + } + if (InternalEditorUtility.defaultWebScreenWidth != this.m_LastWebPlayerScreenSize.x || InternalEditorUtility.defaultWebScreenHeight != this.m_LastWebPlayerScreenSize.y) + { + this.m_LastWebPlayerScreenSize = new Vector2(InternalEditorUtility.defaultWebScreenWidth, InternalEditorUtility.defaultWebScreenHeight); + this.RefreshWebPlayerDefaultScreenSize((int)this.m_LastWebPlayerScreenSize.x, (int)this.m_LastWebPlayerScreenSize.y); + } + if (InternalEditorUtility.remoteScreenWidth != this.m_LastRemoteScreenSize.x || InternalEditorUtility.remoteScreenHeight != this.m_LastRemoteScreenSize.y) + { + this.m_LastRemoteScreenSize = new Vector2(InternalEditorUtility.remoteScreenWidth, InternalEditorUtility.remoteScreenHeight); + this.RefreshRemoteScreenSize((int)this.m_LastRemoteScreenSize.x, (int)this.m_LastRemoteScreenSize.y); + } + } + public void RefreshStandaloneDefaultScreenSize(int width, int height) + { + GameViewSize gameViewSize = this.m_Standalone.GetGameViewSize(this.GetDefaultStandaloneIndex()); + gameViewSize.height = height; + gameViewSize.width = width; + this.Changed(); + } + public void RefreshWebPlayerDefaultScreenSize(int width, int height) + { + GameViewSize gameViewSize = this.m_WebPlayer.GetGameViewSize(this.GetDefaultWebPlayerIndex()); + gameViewSize.height = height; + gameViewSize.width = width; + this.Changed(); + } + public void RefreshRemoteScreenSize(int width, int height) + { + this.m_Remote.width = width; + this.m_Remote.height = height; + if (width > 0 && height > 0) + { + this.m_Remote.baseText = "Remote"; + } + else + { + this.m_Remote.baseText = "Remote (Not Connected)"; + } + this.Changed(); + } + public void Changed() + { + this.m_ChangeID++; + } + public int GetChangeID() + { + return this.m_ChangeID; + } + private void InitBuiltinGroups() + { + bool flag = this.m_Standalone.GetBuiltinCount() > 0; + if (flag) + { + return; + } + this.m_Remote = new GameViewSize(GameViewSizeType.FixedResolution, 0, 0, "Remote (Not Connected)"); + GameViewSize gameViewSize = new GameViewSize(GameViewSizeType.AspectRatio, 0, 0, "Free Aspect"); + GameViewSize gameViewSize2 = new GameViewSize(GameViewSizeType.AspectRatio, 5, 4, string.Empty); + GameViewSize gameViewSize3 = new GameViewSize(GameViewSizeType.AspectRatio, 4, 3, string.Empty); + GameViewSize gameViewSize4 = new GameViewSize(GameViewSizeType.AspectRatio, 3, 2, string.Empty); + GameViewSize gameViewSize5 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 10, string.Empty); + GameViewSize gameViewSize6 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 9, string.Empty); + GameViewSize gameViewSize7 = new GameViewSize(GameViewSizeType.FixedResolution, 0, 0, "Standalone"); + GameViewSize gameViewSize8 = new GameViewSize(GameViewSizeType.FixedResolution, 0, 0, "Web"); + GameViewSize gameViewSize9 = new GameViewSize(GameViewSizeType.FixedResolution, 320, 480, "iPhone Tall"); + GameViewSize gameViewSize10 = new GameViewSize(GameViewSizeType.FixedResolution, 480, 320, "iPhone Wide"); + GameViewSize gameViewSize11 = new GameViewSize(GameViewSizeType.FixedResolution, 640, 960, "iPhone 4 Tall"); + GameViewSize gameViewSize12 = new GameViewSize(GameViewSizeType.FixedResolution, 960, 640, "iPhone 4 Wide"); + GameViewSize gameViewSize13 = new GameViewSize(GameViewSizeType.FixedResolution, 768, 1024, "iPad Tall"); + GameViewSize gameViewSize14 = new GameViewSize(GameViewSizeType.FixedResolution, 1024, 768, "iPad Wide"); + GameViewSize gameViewSize15 = new GameViewSize(GameViewSizeType.AspectRatio, 9, 16, "iPhone 5 Tall"); + GameViewSize gameViewSize16 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 9, "iPhone 5 Wide"); + GameViewSize gameViewSize17 = new GameViewSize(GameViewSizeType.AspectRatio, 2, 3, "iPhone Tall"); + GameViewSize gameViewSize18 = new GameViewSize(GameViewSizeType.AspectRatio, 3, 2, "iPhone Wide"); + GameViewSize gameViewSize19 = new GameViewSize(GameViewSizeType.AspectRatio, 3, 4, "iPad Tall"); + GameViewSize gameViewSize20 = new GameViewSize(GameViewSizeType.AspectRatio, 4, 3, "iPad Wide"); + GameViewSize gameViewSize21 = new GameViewSize(GameViewSizeType.FixedResolution, 320, 480, "HVGA Portrait"); + GameViewSize gameViewSize22 = new GameViewSize(GameViewSizeType.FixedResolution, 480, 320, "HVGA Landscape"); + GameViewSize gameViewSize23 = new GameViewSize(GameViewSizeType.FixedResolution, 480, 800, "WVGA Portrait"); + GameViewSize gameViewSize24 = new GameViewSize(GameViewSizeType.FixedResolution, 800, 480, "WVGA Landscape"); + GameViewSize gameViewSize25 = new GameViewSize(GameViewSizeType.FixedResolution, 480, 854, "FWVGA Portrait"); + GameViewSize gameViewSize26 = new GameViewSize(GameViewSizeType.FixedResolution, 854, 480, "FWVGA Landscape"); + GameViewSize gameViewSize27 = new GameViewSize(GameViewSizeType.FixedResolution, 600, 1024, "WSVGA Portrait"); + GameViewSize gameViewSize28 = new GameViewSize(GameViewSizeType.FixedResolution, 1024, 600, "WSVGA Landscape"); + GameViewSize gameViewSize29 = new GameViewSize(GameViewSizeType.FixedResolution, 800, 1280, "WXGA Portrait"); + GameViewSize gameViewSize30 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 800, "WXGA Landscape"); + GameViewSize gameViewSize31 = new GameViewSize(GameViewSizeType.AspectRatio, 2, 3, "3:2 Portrait"); + GameViewSize gameViewSize32 = new GameViewSize(GameViewSizeType.AspectRatio, 3, 2, "3:2 Landscape"); + GameViewSize gameViewSize33 = new GameViewSize(GameViewSizeType.AspectRatio, 10, 16, "16:10 Portrait"); + GameViewSize gameViewSize34 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 10, "16:10 Landscape"); + GameViewSize gameViewSize35 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 720, "720p (16:9)"); + GameViewSize gameViewSize36 = new GameViewSize(GameViewSizeType.FixedResolution, 1920, 1080, "1080p (16:9)"); + GameViewSize gameViewSize37 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 720, "720p (16:9)"); + GameViewSize gameViewSize38 = new GameViewSize(GameViewSizeType.FixedResolution, 720, 576, "576p (4:3)"); + GameViewSize gameViewSize39 = new GameViewSize(GameViewSizeType.FixedResolution, 1024, 576, "576p (16:9)"); + GameViewSize gameViewSize40 = new GameViewSize(GameViewSizeType.FixedResolution, 640, 480, "480p (4:3)"); + GameViewSize gameViewSize41 = new GameViewSize(GameViewSizeType.FixedResolution, 853, 480, "480p (16:9)"); + GameViewSize gameViewSize42 = new GameViewSize(GameViewSizeType.FixedResolution, 720, 1280, "Touch Phone Portrait"); + GameViewSize gameViewSize43 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 720, "Touch Phone Landscape"); + GameViewSize gameViewSize44 = new GameViewSize(GameViewSizeType.FixedResolution, 720, 720, "Keyboard Phone"); + GameViewSize gameViewSize45 = new GameViewSize(GameViewSizeType.FixedResolution, 600, 1024, "Playbook Portrait"); + GameViewSize gameViewSize46 = new GameViewSize(GameViewSizeType.FixedResolution, 1024, 600, "Playbook Landscape"); + GameViewSize gameViewSize47 = new GameViewSize(GameViewSizeType.AspectRatio, 9, 16, "9:16 Portrait"); + GameViewSize gameViewSize48 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 9, "16:9 Landscape"); + GameViewSize gameViewSize49 = new GameViewSize(GameViewSizeType.AspectRatio, 1, 1, "1:1"); + GameViewSize gameViewSize50 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 720, "16:9 Landscape"); + GameViewSize gameViewSize51 = new GameViewSize(GameViewSizeType.FixedResolution, 720, 1280, "9:16 Portrait"); + GameViewSize gameViewSize52 = new GameViewSize(GameViewSizeType.FixedResolution, 480, 800, "WVGA Portrait"); + GameViewSize gameViewSize53 = new GameViewSize(GameViewSizeType.FixedResolution, 800, 480, "WVGA Landscape"); + GameViewSize gameViewSize54 = new GameViewSize(GameViewSizeType.FixedResolution, 768, 1280, "WXGA Portrait"); + GameViewSize gameViewSize55 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 768, "WXGA Landscape"); + GameViewSize gameViewSize56 = new GameViewSize(GameViewSizeType.FixedResolution, 720, 1280, "720p Portrait"); + GameViewSize gameViewSize57 = new GameViewSize(GameViewSizeType.FixedResolution, 1280, 720, "720p Landscape"); + GameViewSize gameViewSize58 = new GameViewSize(GameViewSizeType.AspectRatio, 9, 15, "WVGA Portrait"); + GameViewSize gameViewSize59 = new GameViewSize(GameViewSizeType.AspectRatio, 15, 9, "WVGA Landscape"); + GameViewSize gameViewSize60 = new GameViewSize(GameViewSizeType.AspectRatio, 9, 15, "WXGA Portrait"); + GameViewSize gameViewSize61 = new GameViewSize(GameViewSizeType.AspectRatio, 15, 9, "WXGA Landscape"); + GameViewSize gameViewSize62 = new GameViewSize(GameViewSizeType.AspectRatio, 9, 16, "720p Portrait"); + GameViewSize gameViewSize63 = new GameViewSize(GameViewSizeType.AspectRatio, 16, 9, "720p Landscape"); + this.m_WP8.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize52, + gameViewSize58, + gameViewSize53, + gameViewSize59, + gameViewSize54, + gameViewSize60, + gameViewSize55, + gameViewSize61, + gameViewSize56, + gameViewSize62, + gameViewSize57, + gameViewSize63 + }); + this.m_Standalone.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize2, + gameViewSize3, + gameViewSize4, + gameViewSize5, + gameViewSize6, + gameViewSize7 + }); + this.m_WebPlayer.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize2, + gameViewSize3, + gameViewSize4, + gameViewSize5, + gameViewSize6, + gameViewSize8 + }); + this.m_PS3.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize3, + gameViewSize6, + gameViewSize5, + gameViewSize36, + gameViewSize37, + gameViewSize38, + gameViewSize39, + gameViewSize40, + gameViewSize41 + }); + this.m_XBox360.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize3, + gameViewSize6, + gameViewSize5, + gameViewSize35 + }); + this.m_iOS.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize9, + gameViewSize10, + gameViewSize11, + gameViewSize12, + gameViewSize13, + gameViewSize14, + gameViewSize15, + gameViewSize16, + gameViewSize17, + gameViewSize18, + gameViewSize19, + gameViewSize20 + }); + this.m_Android.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + this.m_Remote, + gameViewSize21, + gameViewSize22, + gameViewSize23, + gameViewSize24, + gameViewSize25, + gameViewSize26, + gameViewSize27, + gameViewSize28, + gameViewSize29, + gameViewSize30, + gameViewSize31, + gameViewSize32, + gameViewSize33, + gameViewSize34 + }); + this.m_BB10.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize42, + gameViewSize43, + gameViewSize44, + gameViewSize45, + gameViewSize46, + gameViewSize47, + gameViewSize48, + gameViewSize49 + }); + this.m_Tizen.AddBuiltinSizes(new GameViewSize[] + { + gameViewSize, + gameViewSize50, + gameViewSize51 + }); + } + private static void RefreshDerivedGameViewSize(GameViewSizeGroupType groupType, int gameViewSizeIndex, GameViewSize gameViewSize) + { + if (ScriptableSingleton.instance.IsDefaultStandaloneScreenSize(groupType, gameViewSizeIndex)) + { + gameViewSize.width = (int)InternalEditorUtility.defaultScreenWidth; + gameViewSize.height = (int)InternalEditorUtility.defaultScreenHeight; + } + else + { + if (ScriptableSingleton.instance.IsDefaultWebPlayerScreenSize(groupType, gameViewSizeIndex)) + { + gameViewSize.width = (int)InternalEditorUtility.defaultWebScreenWidth; + gameViewSize.height = (int)InternalEditorUtility.defaultWebScreenHeight; + } + else + { + if (ScriptableSingleton.instance.IsRemoteScreenSize(groupType, gameViewSizeIndex)) + { + if (InternalEditorUtility.remoteScreenWidth <= 0f || InternalEditorUtility.remoteScreenHeight <= 0f) + { + gameViewSize.sizeType = GameViewSizeType.AspectRatio; + int num = 0; + gameViewSize.height = num; + gameViewSize.width = num; + } + else + { + gameViewSize.sizeType = GameViewSizeType.FixedResolution; + gameViewSize.width = (int)InternalEditorUtility.remoteScreenWidth; + gameViewSize.height = (int)InternalEditorUtility.remoteScreenHeight; + } + } + } + } + } + public static Rect GetConstrainedRect(Rect startRect, GameViewSizeGroupType groupType, int gameViewSizeIndex, out bool fitsInsideRect) + { + fitsInsideRect = true; + Rect result = startRect; + GameViewSize gameViewSize = ScriptableSingleton.instance.GetGroup(groupType).GetGameViewSize(gameViewSizeIndex); + GameViewSizes.RefreshDerivedGameViewSize(groupType, gameViewSizeIndex, gameViewSize); + if (gameViewSize.isFreeAspectRatio) + { + return startRect; + } + float num = 0f; + GameViewSizeType sizeType = gameViewSize.sizeType; + bool flag; + if (sizeType != GameViewSizeType.AspectRatio) + { + if (sizeType != GameViewSizeType.FixedResolution) + { + Debug.LogError("Unhandled enum"); + return startRect; + } + if ((float)gameViewSize.height > startRect.height || (float)gameViewSize.width > startRect.width) + { + num = gameViewSize.aspectRatio; + flag = true; + fitsInsideRect = false; + } + else + { + result.height = (float)gameViewSize.height; + result.width = (float)gameViewSize.width; + flag = false; + } + } + else + { + num = gameViewSize.aspectRatio; + flag = true; + } + if (flag) + { + result.height = ((result.width / num <= startRect.height) ? (result.width / num) : startRect.height); + result.width = result.height * num; + } + result.height = Mathf.Clamp(result.height, 0f, startRect.height); + result.width = Mathf.Clamp(result.width, 0f, startRect.width); + result.y = startRect.height * 0.5f - result.height * 0.5f + startRect.y; + result.x = startRect.width * 0.5f - result.width * 0.5f + startRect.x; + result.width = Mathf.Floor(result.width + 0.5f); + result.height = Mathf.Floor(result.height + 0.5f); + result.x = Mathf.Floor(result.x + 0.5f); + result.y = Mathf.Floor(result.y + 0.5f); + return result; + } + private static void RefreshGameViewSizeGroupType() + { + BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); + GameViewSizes.s_GameViewSizeGroupType = GameViewSizes.BuildTargetGroupToGameViewSizeGroup(buildTargetGroup); + } + public static GameViewSizeGroupType BuildTargetGroupToGameViewSizeGroup(BuildTargetGroup buildTargetGroup) + { + switch (buildTargetGroup) + { + case BuildTargetGroup.Standalone: + return GameViewSizeGroupType.Standalone; + case BuildTargetGroup.WebPlayer: + case BuildTargetGroup.FlashPlayer: + return GameViewSizeGroupType.WebPlayer; + case BuildTargetGroup.iPhone: + return GameViewSizeGroupType.iOS; + case BuildTargetGroup.PS3: + return GameViewSizeGroupType.PS3; + case BuildTargetGroup.XBOX360: + return GameViewSizeGroupType.Xbox360; + case BuildTargetGroup.Android: + return GameViewSizeGroupType.Android; + case BuildTargetGroup.WP8: + return GameViewSizeGroupType.WP8; + case BuildTargetGroup.BB10: + return GameViewSizeGroupType.BB10; + case BuildTargetGroup.Tizen: + return GameViewSizeGroupType.Tizen; + } + return GameViewSizeGroupType.Standalone; + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizesMenuItemProvider.cs b/UnityEditor/UnityEditor/GameViewSizesMenuItemProvider.cs new file mode 100644 index 00000000..8dd31f0a --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizesMenuItemProvider.cs @@ -0,0 +1,99 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GameViewSizesMenuItemProvider : IFlexibleMenuItemProvider + { + private readonly GameViewSizeGroup m_GameViewSizeGroup; + public GameViewSizesMenuItemProvider(GameViewSizeGroupType gameViewSizeGroupType) + { + this.m_GameViewSizeGroup = ScriptableSingleton.instance.GetGroup(gameViewSizeGroupType); + } + public int Count() + { + return this.m_GameViewSizeGroup.GetTotalCount(); + } + public object GetItem(int index) + { + return this.m_GameViewSizeGroup.GetGameViewSize(index); + } + public int Add(object obj) + { + GameViewSize gameViewSize = GameViewSizesMenuItemProvider.CastToGameViewSize(obj); + if (gameViewSize == null) + { + return -1; + } + this.m_GameViewSizeGroup.AddCustomSize(gameViewSize); + ScriptableSingleton.instance.SaveToHDD(); + return this.Count() - 1; + } + public void Replace(int index, object obj) + { + GameViewSize gameViewSize = GameViewSizesMenuItemProvider.CastToGameViewSize(obj); + if (gameViewSize == null) + { + return; + } + if (index < this.m_GameViewSizeGroup.GetBuiltinCount()) + { + Debug.LogError("Only custom game view sizes can be changed"); + return; + } + GameViewSize gameViewSize2 = this.m_GameViewSizeGroup.GetGameViewSize(index); + if (gameViewSize2 != null) + { + gameViewSize2.Set(gameViewSize); + ScriptableSingleton.instance.SaveToHDD(); + } + } + public void Remove(int index) + { + if (index < this.m_GameViewSizeGroup.GetBuiltinCount()) + { + Debug.LogError("Only custom game view sizes can be changed"); + return; + } + this.m_GameViewSizeGroup.RemoveCustomSize(index); + ScriptableSingleton.instance.SaveToHDD(); + } + public object Create() + { + return new GameViewSize(GameViewSizeType.FixedResolution, 0, 0, string.Empty); + } + public void Move(int index, int destIndex, bool insertAfterDestIndex) + { + Debug.LogError("Missing impl"); + } + public string GetName(int index) + { + GameViewSize gameViewSize = this.m_GameViewSizeGroup.GetGameViewSize(index); + if (gameViewSize != null) + { + return gameViewSize.displayText; + } + return string.Empty; + } + public bool IsModificationAllowed(int index) + { + return this.m_GameViewSizeGroup.IsCustomSize(index); + } + public int[] GetSeperatorIndices() + { + return new int[] + { + this.m_GameViewSizeGroup.GetBuiltinCount() - 1 + }; + } + private static GameViewSize CastToGameViewSize(object obj) + { + GameViewSize result = obj as GameViewSize; + if (obj == null) + { + Debug.LogError("Incorrect input"); + return null; + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/GameViewSizesMenuModifyItemUI.cs b/UnityEditor/UnityEditor/GameViewSizesMenuModifyItemUI.cs new file mode 100644 index 00000000..2002473b --- /dev/null +++ b/UnityEditor/UnityEditor/GameViewSizesMenuModifyItemUI.cs @@ -0,0 +1,134 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GameViewSizesMenuModifyItemUI : FlexibleMenuModifyItemUI + { + private class Styles + { + public GUIContent headerAdd = new GUIContent("Add"); + public GUIContent headerEdit = new GUIContent("Edit"); + public GUIContent typeName = new GUIContent("Type"); + public GUIContent widthHeightText = new GUIContent("Width & Height"); + public GUIContent optionalText = new GUIContent("Label"); + public GUIContent ok = new GUIContent("OK"); + public GUIContent cancel = new GUIContent("Cancel"); + public GUIContent[] typeNames = new GUIContent[] + { + new GUIContent("Aspect Ratio"), + new GUIContent("Fixed Resolution") + }; + } + private static GameViewSizesMenuModifyItemUI.Styles s_Styles; + private GameViewSize m_GameViewSize; + public override void OnClose() + { + this.m_GameViewSize = null; + base.OnClose(); + } + public override Vector2 GetWindowSize() + { + return new Vector2(230f, 140f); + } + public override void OnGUI(Rect rect) + { + if (GameViewSizesMenuModifyItemUI.s_Styles == null) + { + GameViewSizesMenuModifyItemUI.s_Styles = new GameViewSizesMenuModifyItemUI.Styles(); + } + GameViewSize gameViewSize = this.m_Object as GameViewSize; + if (gameViewSize == null) + { + Debug.LogError("Invalid object"); + return; + } + if (this.m_GameViewSize == null) + { + this.m_GameViewSize = new GameViewSize(gameViewSize); + } + bool flag = this.m_GameViewSize.width > 0 && this.m_GameViewSize.height > 0; + GUILayout.Space(3f); + GUILayout.Label((this.m_MenuType != FlexibleMenuModifyItemUI.MenuType.Add) ? GameViewSizesMenuModifyItemUI.s_Styles.headerEdit : GameViewSizesMenuModifyItemUI.s_Styles.headerAdd, EditorStyles.boldLabel, new GUILayoutOption[0]); + Rect rect2 = GUILayoutUtility.GetRect(1f, 1f); + FlexibleMenu.DrawRect(rect2, (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.32f, 0.32f, 0.32f, 1.333f)); + GUILayout.Space(4f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(GameViewSizesMenuModifyItemUI.s_Styles.optionalText, new GUILayoutOption[] + { + GUILayout.Width(90f) + }); + GUILayout.Space(10f); + this.m_GameViewSize.baseText = EditorGUILayout.TextField(this.m_GameViewSize.baseText, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(GameViewSizesMenuModifyItemUI.s_Styles.typeName, new GUILayoutOption[] + { + GUILayout.Width(90f) + }); + GUILayout.Space(10f); + this.m_GameViewSize.sizeType = (GameViewSizeType)EditorGUILayout.Popup((int)this.m_GameViewSize.sizeType, GameViewSizesMenuModifyItemUI.s_Styles.typeNames, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(GameViewSizesMenuModifyItemUI.s_Styles.widthHeightText, new GUILayoutOption[] + { + GUILayout.Width(90f) + }); + GUILayout.Space(10f); + this.m_GameViewSize.width = EditorGUILayout.IntField(this.m_GameViewSize.width, new GUILayoutOption[0]); + GUILayout.Space(5f); + this.m_GameViewSize.height = EditorGUILayout.IntField(this.m_GameViewSize.height, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + float num = 10f; + float cropWidth = rect.width - 2f * num; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(num); + GUILayout.FlexibleSpace(); + string text = this.m_GameViewSize.displayText; + EditorGUI.BeginDisabledGroup(string.IsNullOrEmpty(text)); + if (string.IsNullOrEmpty(text)) + { + text = "Result"; + } + else + { + text = this.GetCroppedText(text, cropWidth, EditorStyles.label); + } + GUILayout.Label(GUIContent.Temp(text), EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + GUILayout.FlexibleSpace(); + GUILayout.Space(num); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + if (GUILayout.Button(GameViewSizesMenuModifyItemUI.s_Styles.cancel, new GUILayoutOption[0])) + { + base.editorWindow.Close(); + } + EditorGUI.BeginDisabledGroup(!flag); + if (GUILayout.Button(GameViewSizesMenuModifyItemUI.s_Styles.ok, new GUILayoutOption[0])) + { + gameViewSize.Set(this.m_GameViewSize); + base.Accepted(); + base.editorWindow.Close(); + } + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + } + private string GetCroppedText(string fullText, float cropWidth, GUIStyle style) + { + int numCharactersThatFitWithinWidth = style.GetNumCharactersThatFitWithinWidth(fullText, cropWidth); + if (numCharactersThatFitWithinWidth == -1) + { + return fullText; + } + if (numCharactersThatFitWithinWidth > 1 && numCharactersThatFitWithinWidth != fullText.Length) + { + return fullText.Substring(0, numCharactersThatFitWithinWidth - 1) + "…"; + } + return fullText; + } + } +} diff --git a/UnityEditor/UnityEditor/GccCompiler.cs b/UnityEditor/UnityEditor/GccCompiler.cs new file mode 100644 index 00000000..5d50b6ab --- /dev/null +++ b/UnityEditor/UnityEditor/GccCompiler.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +namespace UnityEditor +{ + internal class GccCompiler : NativeCompiler + { + private readonly ICompilerSettings m_Settings; + protected override string objectFileExtension + { + get + { + return "o"; + } + } + public GccCompiler(ICompilerSettings settings) + { + this.m_Settings = settings; + } + private void Compile(string file, string includePaths) + { + string arguments = string.Format(" -c {0} -O0 -Wno-unused-value -Wno-invalid-offsetof -fvisibility=hidden -fno-rtti {1} {2} -o {3}", new object[] + { + this.m_Settings.MachineSpecification, + includePaths, + file, + base.ObjectFileFor(file) + }); + base.Execute(arguments, this.m_Settings.CompilerPath); + } + public override void CompileDynamicLibrary(string outFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths) + { + string[] array = sources.ToArray(); + string includeDirs = includePaths.Aggregate(string.Empty, (string current, string sourceDir) => current + "-I" + sourceDir + " "); + string empty = string.Empty; + string text = NativeCompiler.Aggregate(libraryPaths.Union(this.m_Settings.LibPaths), "-L", " "); + NativeCompiler.ParallelFor(array, delegate(string file) + { + this.Compile(file, includeDirs); + }); + string arg_F7_1 = this.m_Settings.LinkerPath; + string[] expr_8E = new string[4]; + expr_8E[0] = string.Format("-shared {0} -o {1}", this.m_Settings.MachineSpecification, outFile); + expr_8E[1] = array.Where(new Func(NativeCompiler.IsSourceFile)).Select(new Func(base.ObjectFileFor)).Aggregate((string buff, string s) => buff + " " + s); + expr_8E[2] = text; + expr_8E[3] = empty; + base.ExecuteCommand(arg_F7_1, expr_8E); + } + } +} diff --git a/UnityEditor/UnityEditor/GccCompilerSettingsx86.cs b/UnityEditor/UnityEditor/GccCompilerSettingsx86.cs new file mode 100644 index 00000000..fbd39874 --- /dev/null +++ b/UnityEditor/UnityEditor/GccCompilerSettingsx86.cs @@ -0,0 +1,35 @@ +using System; +namespace UnityEditor +{ + internal class GccCompilerSettingsx86 : ICompilerSettings + { + public string[] LibPaths + { + get + { + return new string[0]; + } + } + public string CompilerPath + { + get + { + return "/usr/bin/g++"; + } + } + public string LinkerPath + { + get + { + return this.CompilerPath; + } + } + public string MachineSpecification + { + get + { + return "-m32"; + } + } + } +} diff --git a/UnityEditor/UnityEditor/GccCompilerSettingsx86_64.cs b/UnityEditor/UnityEditor/GccCompilerSettingsx86_64.cs new file mode 100644 index 00000000..986101d5 --- /dev/null +++ b/UnityEditor/UnityEditor/GccCompilerSettingsx86_64.cs @@ -0,0 +1,35 @@ +using System; +namespace UnityEditor +{ + internal class GccCompilerSettingsx86_64 : ICompilerSettings + { + public string[] LibPaths + { + get + { + return new string[0]; + } + } + public string CompilerPath + { + get + { + return "/usr/bin/g++"; + } + } + public string LinkerPath + { + get + { + return this.CompilerPath; + } + } + public string MachineSpecification + { + get + { + return "-m64"; + } + } + } +} diff --git a/UnityEditor/UnityEditor/GenericInspector.cs b/UnityEditor/UnityEditor/GenericInspector.cs new file mode 100644 index 00000000..38b278e9 --- /dev/null +++ b/UnityEditor/UnityEditor/GenericInspector.cs @@ -0,0 +1,76 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GenericInspector : Editor + { + private AudioFilterGUI m_AudioFilterGUI; + internal override bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) + { + bool optimizedGUIBlockImplementation = base.GetOptimizedGUIBlockImplementation(isDirty, isVisible, out block, out height); + return (!(this.target is MonoBehaviour) || !AudioUtil.HaveAudioCallback(this.target as MonoBehaviour) || AudioUtil.GetCustomFilterChannelCount(this.target as MonoBehaviour) <= 0) && !this.IsMissingMonoBehaviourTarget() && optimizedGUIBlockImplementation; + } + internal override void OnHeaderIconGUI(Rect iconRect) + { + if (this.target.GetType() != typeof(GUISkin) && this.target.GetType().IsSubclassOf(typeof(ScriptableObject))) + { + Texture2D image = EditorGUIUtility.IconContent("ScriptableObject Icon").image as Texture2D; + GUI.Label(iconRect, image); + } + else + { + base.OnHeaderIconGUI(iconRect); + } + } + internal override bool OnOptimizedInspectorGUI(Rect contentRect) + { + return base.OptimizedInspectorGUIImplementation(contentRect); + } + public bool MissingMonoBehaviourGUI() + { + base.serializedObject.Update(); + SerializedProperty serializedProperty = base.serializedObject.FindProperty("m_Script"); + if (serializedProperty == null) + { + return false; + } + EditorGUILayout.PropertyField(serializedProperty, new GUILayoutOption[0]); + MonoScript monoScript = serializedProperty.objectReferenceValue as MonoScript; + bool flag = true; + if (monoScript != null && monoScript.GetScriptTypeWasJustCreatedFromComponentMenu()) + { + flag = false; + } + if (flag) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("GenericInspector.ScriptIsInvalid"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, true); + } + if (base.serializedObject.ApplyModifiedProperties()) + { + EditorUtility.ForceRebuildInspectors(); + } + return true; + } + private bool IsMissingMonoBehaviourTarget() + { + return this.target.GetType() == typeof(MonoBehaviour) || this.target.GetType() == typeof(ScriptableObject); + } + public override void OnInspectorGUI() + { + if (this.IsMissingMonoBehaviourTarget() && this.MissingMonoBehaviourGUI()) + { + return; + } + base.OnInspectorGUI(); + if (this.target is MonoBehaviour && AudioUtil.HaveAudioCallback(this.target as MonoBehaviour) && AudioUtil.GetCustomFilterChannelCount(this.target as MonoBehaviour) > 0) + { + if (this.m_AudioFilterGUI == null) + { + this.m_AudioFilterGUI = new AudioFilterGUI(); + } + this.m_AudioFilterGUI.DrawAudioFilterGUI(this.target as MonoBehaviour); + } + } + } +} diff --git a/UnityEditor/UnityEditor/GenericMenu.cs b/UnityEditor/UnityEditor/GenericMenu.cs new file mode 100644 index 00000000..fd6e0007 --- /dev/null +++ b/UnityEditor/UnityEditor/GenericMenu.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections; +using UnityEngine; +namespace UnityEditor +{ + public sealed class GenericMenu + { + private sealed class MenuItem + { + public GUIContent content; + public bool on; + public GenericMenu.MenuFunction func; + public GenericMenu.MenuFunction2 func2; + public object userData; + public MenuItem(GUIContent _content, bool _on, GenericMenu.MenuFunction _func) + { + this.content = _content; + this.on = _on; + this.func = _func; + } + public MenuItem(GUIContent _content, bool _on, GenericMenu.MenuFunction2 _func, object _userData) + { + this.content = _content; + this.on = _on; + this.func2 = _func; + this.userData = _userData; + } + } + public delegate void MenuFunction(); + public delegate void MenuFunction2(object userData); + private ArrayList menuItems = new ArrayList(); + public void AddItem(GUIContent content, bool on, GenericMenu.MenuFunction func) + { + this.menuItems.Add(new GenericMenu.MenuItem(content, on, func)); + } + public void AddItem(GUIContent content, bool on, GenericMenu.MenuFunction2 func, object userData) + { + this.menuItems.Add(new GenericMenu.MenuItem(content, on, func, userData)); + } + public void AddDisabledItem(GUIContent content) + { + this.menuItems.Add(new GenericMenu.MenuItem(content, false, null)); + } + public void AddSeparator(string path) + { + this.menuItems.Add(new GenericMenu.MenuItem(new GUIContent(path), false, null)); + } + public int GetItemCount() + { + return this.menuItems.Count; + } + public void ShowAsContext() + { + this.DropDown(new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 0f, 0f)); + } + public void DropDown(Rect position) + { + string[] array = new string[this.menuItems.Count]; + bool[] array2 = new bool[this.menuItems.Count]; + ArrayList arrayList = new ArrayList(); + for (int i = 0; i < this.menuItems.Count; i++) + { + GenericMenu.MenuItem menuItem = (GenericMenu.MenuItem)this.menuItems[i]; + array[i] = menuItem.content.text; + array2[i] = (menuItem.func != null || menuItem.func2 != null); + if (menuItem.on) + { + arrayList.Add(i); + } + } + EditorUtility.DisplayCustomMenu(position, array, array2, (int[])arrayList.ToArray(typeof(int)), new EditorUtility.SelectMenuItemFunction(this.CatchMenu), null); + } + internal void Popup(Rect position, int selectedIndex) + { + if (Application.platform == RuntimePlatform.WindowsEditor) + { + this.DropDown(position); + return; + } + this.DropDown(position); + } + private void CatchMenu(object userData, string[] options, int selected) + { + GenericMenu.MenuItem menuItem = (GenericMenu.MenuItem)this.menuItems[selected]; + if (menuItem.func2 != null) + { + menuItem.func2(menuItem.userData); + } + else + { + if (menuItem.func != null) + { + menuItem.func(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/GenericPresetLibraryInspector.cs b/UnityEditor/UnityEditor/GenericPresetLibraryInspector.cs new file mode 100644 index 00000000..cf4479ae --- /dev/null +++ b/UnityEditor/UnityEditor/GenericPresetLibraryInspector.cs @@ -0,0 +1,186 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class GenericPresetLibraryInspector where T : ScriptableObject + { + private readonly ScriptableObjectSaveLoadHelper m_SaveLoadHelper; + private readonly UnityEngine.Object m_Target; + private readonly string m_Header; + private readonly VerticalGrid m_Grid; + private readonly Action m_EditButtonClickedCallback; + private static GUIStyle s_EditButtonStyle; + private float m_LastRepaintedWidth = -1f; + public int maxShowNumPresets + { + get; + set; + } + public Vector2 presetSize + { + get; + set; + } + public float lineSpacing + { + get; + set; + } + public string extension + { + get + { + return this.m_SaveLoadHelper.fileExtensionWithoutDot; + } + } + public bool useOnePixelOverlappedGrid + { + get; + set; + } + public RectOffset marginsForList + { + get; + set; + } + public RectOffset marginsForGrid + { + get; + set; + } + public PresetLibraryEditorState.ItemViewMode itemViewMode + { + get; + set; + } + public GenericPresetLibraryInspector(UnityEngine.Object target, string header, Action editButtonClicked) + { + this.m_Target = target; + this.m_Header = header; + this.m_EditButtonClickedCallback = editButtonClicked; + string assetPath = AssetDatabase.GetAssetPath(this.m_Target.GetInstanceID()); + string text = Path.GetExtension(assetPath); + if (!string.IsNullOrEmpty(text)) + { + text = text.TrimStart(new char[] + { + '.' + }); + } + this.m_SaveLoadHelper = new ScriptableObjectSaveLoadHelper(text, SaveType.Text); + this.m_Grid = new VerticalGrid(); + this.maxShowNumPresets = 49; + this.presetSize = new Vector2(14f, 14f); + this.lineSpacing = 1f; + this.useOnePixelOverlappedGrid = false; + this.marginsForList = new RectOffset(10, 10, 5, 5); + this.marginsForGrid = new RectOffset(10, 10, 5, 5); + this.itemViewMode = PresetLibraryEditorState.ItemViewMode.List; + } + public void OnDestroy() + { + ScriptableSingleton.instance.UnloadAllLibrariesFor(this.m_SaveLoadHelper); + } + public void OnInspectorGUI() + { + if (GenericPresetLibraryInspector.s_EditButtonStyle == null) + { + GenericPresetLibraryInspector.s_EditButtonStyle = new GUIStyle(EditorStyles.miniButton); + GenericPresetLibraryInspector.s_EditButtonStyle.margin.top = 7; + } + string assetPath = AssetDatabase.GetAssetPath(this.m_Target.GetInstanceID()); + string text = Path.ChangeExtension(assetPath, null); + bool flag = text.Contains("/Editor/"); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(this.m_Header, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (flag && this.m_EditButtonClickedCallback != null && GUILayout.Button("Edit...", GenericPresetLibraryInspector.s_EditButtonStyle, new GUILayoutOption[0]) && this.m_EditButtonClickedCallback != null) + { + this.m_EditButtonClickedCallback(text); + } + GUILayout.EndHorizontal(); + GUILayout.Space(6f); + if (!flag) + { + GUIContent content = new GUIContent("Preset libraries should be placed in an 'Editor' folder.", EditorGUIUtility.warningIcon); + GUILayout.Label(content, EditorStyles.helpBox, new GUILayoutOption[0]); + } + this.DrawPresets(text); + } + private void DrawPresets(string libraryPath) + { + if (GUIClip.visibleRect.width > 0f) + { + this.m_LastRepaintedWidth = GUIClip.visibleRect.width; + } + if (this.m_LastRepaintedWidth < 0f) + { + GUILayoutUtility.GetRect(1f, 1f); + HandleUtility.Repaint(); + return; + } + PresetLibrary presetLibrary = ScriptableSingleton.instance.GetLibrary(this.m_SaveLoadHelper, libraryPath) as PresetLibrary; + if (presetLibrary == null) + { + Debug.Log("Could not load preset library '" + libraryPath + "'"); + return; + } + this.SetupGrid(this.m_LastRepaintedWidth, presetLibrary.Count(), this.itemViewMode); + int num = Mathf.Min(presetLibrary.Count(), this.maxShowNumPresets); + int num2 = presetLibrary.Count() - num; + float num3 = this.m_Grid.CalcRect(num - 1, 0f).yMax + ((num2 <= 0) ? 0f : 20f); + Rect rect = GUILayoutUtility.GetRect(1f, num3); + float num4 = this.presetSize.x + 6f; + for (int i = 0; i < num; i++) + { + Rect rect2 = this.m_Grid.CalcRect(i, rect.y); + Rect rect3 = new Rect(rect2.x, rect2.y, this.presetSize.x, this.presetSize.y); + presetLibrary.Draw(rect3, i); + if (this.itemViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + Rect position = new Rect(rect2.x + num4, rect2.y, rect2.width - num4, rect2.height); + string name = presetLibrary.GetName(i); + GUI.Label(position, name); + } + } + if (num2 > 0) + { + Rect position2 = new Rect(this.m_Grid.CalcRect(0, 0f).x, rect.y + num3 - 20f, rect.width, 20f); + GUI.Label(position2, string.Format("+ {0} more...", num2)); + } + } + private void SetupGrid(float availableWidth, int itemCount, PresetLibraryEditorState.ItemViewMode presetsViewMode) + { + this.m_Grid.useFixedHorizontalSpacing = this.useOnePixelOverlappedGrid; + this.m_Grid.fixedHorizontalSpacing = (float)((!this.useOnePixelOverlappedGrid) ? 0 : -1); + if (presetsViewMode != PresetLibraryEditorState.ItemViewMode.Grid) + { + if (presetsViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + this.m_Grid.fixedWidth = availableWidth; + this.m_Grid.topMargin = (float)this.marginsForList.top; + this.m_Grid.bottomMargin = (float)this.marginsForList.bottom; + this.m_Grid.leftMargin = (float)this.marginsForList.left; + this.m_Grid.rightMargin = (float)this.marginsForList.right; + this.m_Grid.verticalSpacing = this.lineSpacing; + this.m_Grid.minHorizontalSpacing = 0f; + this.m_Grid.itemSize = new Vector2(availableWidth - this.m_Grid.leftMargin, this.presetSize.y); + this.m_Grid.InitNumRowsAndColumns(itemCount, 2147483647); + } + } + else + { + this.m_Grid.fixedWidth = availableWidth; + this.m_Grid.topMargin = (float)this.marginsForGrid.top; + this.m_Grid.bottomMargin = (float)this.marginsForGrid.bottom; + this.m_Grid.leftMargin = (float)this.marginsForGrid.left; + this.m_Grid.rightMargin = (float)this.marginsForGrid.right; + this.m_Grid.verticalSpacing = ((!this.useOnePixelOverlappedGrid) ? this.lineSpacing : -1f); + this.m_Grid.minHorizontalSpacing = 8f; + this.m_Grid.itemSize = this.presetSize; + this.m_Grid.InitNumRowsAndColumns(itemCount, 2147483647); + } + } + } +} diff --git a/UnityEditor/UnityEditor/GizmoType.cs b/UnityEditor/UnityEditor/GizmoType.cs new file mode 100644 index 00000000..857a7431 --- /dev/null +++ b/UnityEditor/UnityEditor/GizmoType.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum GizmoType + { + Active = 8, + SelectedOrChild = 16, + NotSelected = 2, + Selected = 4, + Pickable = 1 + } +} diff --git a/UnityEditor/UnityEditor/GradientContextMenu.cs b/UnityEditor/UnityEditor/GradientContextMenu.cs new file mode 100644 index 00000000..ecc55e79 --- /dev/null +++ b/UnityEditor/UnityEditor/GradientContextMenu.cs @@ -0,0 +1,40 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class GradientContextMenu + { + private SerializedProperty m_Prop1; + private GradientContextMenu(SerializedProperty prop1) + { + this.m_Prop1 = prop1; + } + internal static void Show(SerializedProperty prop) + { + GUIContent content = new GUIContent("Copy"); + GUIContent content2 = new GUIContent("Paste"); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction(new GradientContextMenu(prop).Copy)); + if (ParticleSystemClipboard.HasSingleGradient()) + { + genericMenu.AddItem(content2, false, new GenericMenu.MenuFunction(new GradientContextMenu(prop).Paste)); + } + else + { + genericMenu.AddDisabledItem(content2); + } + genericMenu.ShowAsContext(); + } + private void Copy() + { + Gradient gradient = (this.m_Prop1 == null) ? null : this.m_Prop1.gradientValue; + ParticleSystemClipboard.CopyGradient(gradient, null); + } + private void Paste() + { + ParticleSystemClipboard.PasteGradient(this.m_Prop1, null); + GradientPreviewCache.ClearCache(); + } + } +} diff --git a/UnityEditor/UnityEditor/GradientEditor.cs b/UnityEditor/UnityEditor/GradientEditor.cs new file mode 100644 index 00000000..2e1a242c --- /dev/null +++ b/UnityEditor/UnityEditor/GradientEditor.cs @@ -0,0 +1,565 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class GradientEditor + { + private class Styles + { + public GUIStyle upSwatch = "Grad Up Swatch"; + public GUIStyle upSwatchOverlay = "Grad Up Swatch Overlay"; + public GUIStyle downSwatch = "Grad Down Swatch"; + public GUIStyle downSwatchOverlay = "Grad Down Swatch Overlay"; + public GUIContent alphaText = new GUIContent("Alpha"); + public GUIContent colorText = new GUIContent("Color"); + public GUIContent locationText = new GUIContent("Location"); + public GUIContent percentText = new GUIContent("%"); + private static GUIStyle GetStyle(string name) + { + GUISkin gUISkin = (GUISkin)EditorGUIUtility.LoadRequired("GradientEditor.GUISkin"); + return gUISkin.GetStyle(name); + } + } + public class Swatch + { + public float m_Time; + public Color m_Value; + public bool m_IsAlpha; + public Swatch(float time, Color value, bool isAlpha) + { + this.m_Time = time; + this.m_Value = value; + this.m_IsAlpha = isAlpha; + } + } + private const int k_PreviewWidth = 256; + private const int k_MaxNumKeys = 8; + private static GradientEditor.Styles s_Styles; + private static Texture2D s_BackgroundTexture; + private List m_RGBSwatches; + private List m_AlphaSwatches; + [NonSerialized] + private GradientEditor.Swatch m_SelectedSwatch; + private Texture2D m_PreviewTex; + private bool m_TextureDirty = true; + private Gradient m_Gradient; + private int m_NumSteps; + public Gradient target + { + get + { + return this.m_Gradient; + } + } + public void Clear() + { + if (this.m_PreviewTex != null) + { + UnityEngine.Object.DestroyImmediate(this.m_PreviewTex); + } + } + public void Init(Gradient gradient, int numSteps) + { + this.m_Gradient = gradient; + this.m_TextureDirty = true; + this.m_NumSteps = numSteps; + this.BuildArrays(); + if (this.m_RGBSwatches.Count > 0) + { + this.m_SelectedSwatch = this.m_RGBSwatches[0]; + } + } + private float GetTime(float actualTime) + { + actualTime = Mathf.Clamp01(actualTime); + if (this.m_NumSteps > 1) + { + float num = 1f / (float)(this.m_NumSteps - 1); + int num2 = Mathf.RoundToInt(actualTime / num); + return (float)num2 / (float)(this.m_NumSteps - 1); + } + return actualTime; + } + public static Texture2D CreateGradientTexture(Gradient gradient) + { + Texture2D texture2D = new Texture2D(256, 2, TextureFormat.ARGB32, false); + texture2D.wrapMode = TextureWrapMode.Clamp; + texture2D.hideFlags = HideFlags.HideAndDontSave; + GradientEditor.RefreshPreview(gradient, texture2D); + return texture2D; + } + public static void RefreshPreview(Gradient gradient, Texture2D preview) + { + Color[] array = new Color[512]; + for (int i = 0; i < 256; i++) + { + array[i] = (array[i + 256] = gradient.Evaluate((float)i / 256f)); + } + preview.SetPixels(array); + preview.Apply(); + } + private void BuildTexture() + { + if (this.m_PreviewTex == null) + { + this.m_PreviewTex = GradientEditor.CreateGradientTexture(this.m_Gradient); + } + else + { + GradientEditor.RefreshPreview(this.m_Gradient, this.m_PreviewTex); + } + this.m_TextureDirty = false; + } + private void BuildArrays() + { + if (this.m_Gradient == null) + { + return; + } + GradientColorKey[] colorKeys = this.m_Gradient.colorKeys; + this.m_RGBSwatches = new List(colorKeys.Length); + for (int i = 0; i < colorKeys.Length; i++) + { + Color color = colorKeys[i].color; + color.a = 1f; + this.m_RGBSwatches.Add(new GradientEditor.Swatch(colorKeys[i].time, color, false)); + } + GradientAlphaKey[] alphaKeys = this.m_Gradient.alphaKeys; + this.m_AlphaSwatches = new List(alphaKeys.Length); + for (int j = 0; j < alphaKeys.Length; j++) + { + float alpha = alphaKeys[j].alpha; + this.m_AlphaSwatches.Add(new GradientEditor.Swatch(alphaKeys[j].time, new Color(alpha, alpha, alpha, 1f), true)); + } + } + public static void DrawGradientWithBackground(Rect position, Texture2D gradientTexture) + { + Rect position2 = new Rect(position.x + 1f, position.y + 1f, position.width - 2f, position.height - 2f); + Texture2D backgroundTexture = GradientEditor.GetBackgroundTexture(); + Rect texCoords = new Rect(0f, 0f, position2.width / (float)backgroundTexture.width, position2.height / (float)backgroundTexture.height); + GUI.DrawTextureWithTexCoords(position2, backgroundTexture, texCoords, false); + if (gradientTexture != null) + { + GUI.DrawTexture(position2, gradientTexture, ScaleMode.StretchToFill, true); + } + GUI.Label(position, GUIContent.none, EditorStyles.colorPickerBox); + } + public void OnGUI(Rect position) + { + if (GradientEditor.s_Styles == null) + { + GradientEditor.s_Styles = new GradientEditor.Styles(); + } + float num = 16f; + float num2 = 30f; + float num3 = position.height - 2f * num - num2; + position.height = num; + this.ShowSwatchArray(position, this.m_AlphaSwatches, true); + position.y += num; + if (Event.current.type == EventType.Repaint) + { + position.height = num3; + if (this.m_TextureDirty) + { + this.BuildTexture(); + } + GradientEditor.DrawGradientWithBackground(position, this.m_PreviewTex); + } + position.y += num3; + position.height = num; + this.ShowSwatchArray(position, this.m_RGBSwatches, false); + if (this.m_SelectedSwatch != null) + { + position.y += num; + position.height = num2; + position.y += 10f; + float num4 = 45f; + float num5 = 60f; + float num6 = 20f; + float labelWidth = 50f; + float num7 = num5 + num6 + num5 + num4; + Rect position2 = position; + position2.height = 18f; + position2.x += 17f; + position2.width -= num7; + EditorGUIUtility.labelWidth = labelWidth; + if (this.m_SelectedSwatch.m_IsAlpha) + { + EditorGUIUtility.fieldWidth = 30f; + EditorGUI.BeginChangeCheck(); + float num8 = (float)EditorGUI.IntSlider(position2, GradientEditor.s_Styles.alphaText, (int)(this.m_SelectedSwatch.m_Value.r * 255f), 0, 255) / 255f; + if (EditorGUI.EndChangeCheck()) + { + num8 = Mathf.Clamp01(num8); + this.m_SelectedSwatch.m_Value.r = (this.m_SelectedSwatch.m_Value.g = (this.m_SelectedSwatch.m_Value.b = num8)); + this.AssignBack(); + HandleUtility.Repaint(); + } + } + else + { + EditorGUI.BeginChangeCheck(); + this.m_SelectedSwatch.m_Value = EditorGUI.ColorField(position2, GradientEditor.s_Styles.colorText, this.m_SelectedSwatch.m_Value, true, false); + if (EditorGUI.EndChangeCheck()) + { + this.AssignBack(); + HandleUtility.Repaint(); + } + } + position2.x += position2.width + num6; + position2.width = num4 + num5; + EditorGUIUtility.labelWidth = num5; + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + EditorGUI.kFloatFieldFormatString = "f1"; + EditorGUI.BeginChangeCheck(); + float value = EditorGUI.FloatField(position2, GradientEditor.s_Styles.locationText, this.m_SelectedSwatch.m_Time * 100f) / 100f; + if (EditorGUI.EndChangeCheck()) + { + this.m_SelectedSwatch.m_Time = Mathf.Clamp(value, 0f, 1f); + this.AssignBack(); + } + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + position2.x += position2.width; + position2.width = 20f; + GUI.Label(position2, GradientEditor.s_Styles.percentText); + } + } + private void ShowSwatchArray(Rect position, List swatches, bool isAlpha) + { + int controlID = GUIUtility.GetControlID(652347689, FocusType.Passive); + Event current = Event.current; + float time = this.GetTime((Event.current.mousePosition.x - position.x) / position.width); + Vector2 point = new Vector3(position.x + time * position.width, Event.current.mousePosition.y); + EventType typeForControl = current.GetTypeForControl(controlID); + switch (typeForControl) + { + case EventType.MouseDown: + { + Rect rect = position; + rect.xMin -= 10f; + rect.xMax += 10f; + if (rect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = controlID; + current.Use(); + if (swatches.Contains(this.m_SelectedSwatch) && !this.m_SelectedSwatch.m_IsAlpha && this.CalcSwatchRect(position, this.m_SelectedSwatch).Contains(current.mousePosition)) + { + if (current.clickCount == 2) + { + GUIUtility.keyboardControl = controlID; + ColorPicker.Show(GUIView.current, this.m_SelectedSwatch.m_Value, false); + GUIUtility.ExitGUI(); + } + } + else + { + bool flag = false; + foreach (GradientEditor.Swatch current2 in swatches) + { + if (this.CalcSwatchRect(position, current2).Contains(point)) + { + flag = true; + this.m_SelectedSwatch = current2; + break; + } + } + if (!flag) + { + if (swatches.Count < 8) + { + Color value = this.m_Gradient.Evaluate(time); + if (isAlpha) + { + value = new Color(value.a, value.a, value.a, 1f); + } + else + { + value.a = 1f; + } + this.m_SelectedSwatch = new GradientEditor.Swatch(time, value, isAlpha); + swatches.Add(this.m_SelectedSwatch); + this.AssignBack(); + } + else + { + Debug.LogWarning(string.Concat(new object[] + { + "Max ", + 8, + " color keys and ", + 8, + " alpha keys are allowed in a gradient." + })); + } + } + } + } + return; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + if (!swatches.Contains(this.m_SelectedSwatch)) + { + this.m_SelectedSwatch = null; + } + this.RemoveDuplicateOverlappingSwatches(); + } + return; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_9B: + if (typeForControl == EventType.ValidateCommand) + { + if (current.commandName == "Delete") + { + Event.current.Use(); + } + return; + } + if (typeForControl != EventType.ExecuteCommand) + { + return; + } + if (current.commandName == "ColorPickerChanged") + { + GUI.changed = true; + this.m_SelectedSwatch.m_Value = ColorPicker.color; + this.AssignBack(); + HandleUtility.Repaint(); + } + else + { + if (current.commandName == "Delete" && swatches.Count > 1) + { + swatches.Remove(this.m_SelectedSwatch); + this.AssignBack(); + HandleUtility.Repaint(); + } + } + return; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && this.m_SelectedSwatch != null) + { + current.Use(); + if (current.mousePosition.y + 5f < position.y || current.mousePosition.y - 5f > position.yMax) + { + if (swatches.Count > 1) + { + swatches.Remove(this.m_SelectedSwatch); + this.AssignBack(); + return; + } + } + else + { + if (!swatches.Contains(this.m_SelectedSwatch)) + { + swatches.Add(this.m_SelectedSwatch); + } + } + this.m_SelectedSwatch.m_Time = time; + this.AssignBack(); + } + return; + case EventType.KeyDown: + if (current.keyCode == KeyCode.Delete) + { + if (this.m_SelectedSwatch != null) + { + List list; + if (this.m_SelectedSwatch.m_IsAlpha) + { + list = this.m_AlphaSwatches; + } + else + { + list = this.m_RGBSwatches; + } + if (list.Count > 1) + { + list.Remove(this.m_SelectedSwatch); + this.AssignBack(); + HandleUtility.Repaint(); + } + } + current.Use(); + } + return; + case EventType.Repaint: + { + bool flag2 = false; + foreach (GradientEditor.Swatch current3 in swatches) + { + if (this.m_SelectedSwatch == current3) + { + flag2 = true; + } + else + { + this.DrawSwatch(position, current3, !isAlpha); + } + } + if (flag2 && this.m_SelectedSwatch != null) + { + this.DrawSwatch(position, this.m_SelectedSwatch, !isAlpha); + } + return; + } + } + goto IL_9B; + } + private void DrawSwatch(Rect totalPos, GradientEditor.Swatch s, bool upwards) + { + Color backgroundColor = GUI.backgroundColor; + Rect position = this.CalcSwatchRect(totalPos, s); + GUI.backgroundColor = s.m_Value; + GUIStyle gUIStyle = (!upwards) ? GradientEditor.s_Styles.downSwatch : GradientEditor.s_Styles.upSwatch; + GUIStyle gUIStyle2 = (!upwards) ? GradientEditor.s_Styles.downSwatchOverlay : GradientEditor.s_Styles.upSwatchOverlay; + gUIStyle.Draw(position, false, false, this.m_SelectedSwatch == s, false); + GUI.backgroundColor = backgroundColor; + gUIStyle2.Draw(position, false, false, this.m_SelectedSwatch == s, false); + } + private Rect CalcSwatchRect(Rect totalRect, GradientEditor.Swatch s) + { + float time = s.m_Time; + return new Rect(totalRect.x + Mathf.Round(totalRect.width * time) - 5f, totalRect.y, 10f, totalRect.height); + } + private int SwatchSort(GradientEditor.Swatch lhs, GradientEditor.Swatch rhs) + { + if (lhs.m_Time == rhs.m_Time && lhs == this.m_SelectedSwatch) + { + return -1; + } + if (lhs.m_Time == rhs.m_Time && rhs == this.m_SelectedSwatch) + { + return 1; + } + return lhs.m_Time.CompareTo(rhs.m_Time); + } + private void AssignBack() + { + this.m_RGBSwatches.Sort((GradientEditor.Swatch a, GradientEditor.Swatch b) => this.SwatchSort(a, b)); + GradientColorKey[] array = new GradientColorKey[this.m_RGBSwatches.Count]; + for (int i = 0; i < this.m_RGBSwatches.Count; i++) + { + array[i].color = this.m_RGBSwatches[i].m_Value; + array[i].time = this.m_RGBSwatches[i].m_Time; + } + this.m_AlphaSwatches.Sort((GradientEditor.Swatch a, GradientEditor.Swatch b) => this.SwatchSort(a, b)); + GradientAlphaKey[] array2 = new GradientAlphaKey[this.m_AlphaSwatches.Count]; + for (int j = 0; j < this.m_AlphaSwatches.Count; j++) + { + array2[j].alpha = this.m_AlphaSwatches[j].m_Value.r; + array2[j].time = this.m_AlphaSwatches[j].m_Time; + } + this.m_Gradient.colorKeys = array; + this.m_Gradient.alphaKeys = array2; + this.m_TextureDirty = true; + GUI.changed = true; + } + private void RemoveDuplicateOverlappingSwatches() + { + bool flag = false; + for (int i = 1; i < this.m_RGBSwatches.Count; i++) + { + if (Mathf.Approximately(this.m_RGBSwatches[i - 1].m_Time, this.m_RGBSwatches[i].m_Time)) + { + this.m_RGBSwatches.RemoveAt(i); + i--; + flag = true; + } + } + for (int j = 1; j < this.m_AlphaSwatches.Count; j++) + { + if (Mathf.Approximately(this.m_AlphaSwatches[j - 1].m_Time, this.m_AlphaSwatches[j].m_Time)) + { + this.m_AlphaSwatches.RemoveAt(j); + j--; + flag = true; + } + } + if (flag) + { + this.AssignBack(); + } + } + public static Texture2D GetBackgroundTexture() + { + if (GradientEditor.s_BackgroundTexture == null) + { + GradientEditor.s_BackgroundTexture = GradientEditor.CreateCheckerTexture(32, 4, 4, Color.white, new Color(0.7f, 0.7f, 0.7f)); + } + return GradientEditor.s_BackgroundTexture; + } + public static Texture2D CreateCheckerTexture(int numCols, int numRows, int cellPixelWidth, Color col1, Color col2) + { + int num = numRows * cellPixelWidth; + int num2 = numCols * cellPixelWidth; + Texture2D texture2D = new Texture2D(num2, num, TextureFormat.ARGB32, false); + texture2D.hideFlags = HideFlags.HideAndDontSave; + Color[] array = new Color[num2 * num]; + for (int i = 0; i < numRows; i++) + { + for (int j = 0; j < numCols; j++) + { + for (int k = 0; k < cellPixelWidth; k++) + { + for (int l = 0; l < cellPixelWidth; l++) + { + array[(i * cellPixelWidth + k) * num2 + j * cellPixelWidth + l] = (((i + j) % 2 != 0) ? col2 : col1); + } + } + } + } + texture2D.SetPixels(array); + texture2D.Apply(); + return texture2D; + } + public static void DrawGradientSwatch(Rect position, Gradient gradient, Color bgColor) + { + GradientEditor.DrawGradientSwatchInternal(position, gradient, null, bgColor); + } + public static void DrawGradientSwatch(Rect position, SerializedProperty property, Color bgColor) + { + GradientEditor.DrawGradientSwatchInternal(position, null, property, bgColor); + } + private static void DrawGradientSwatchInternal(Rect position, Gradient gradient, SerializedProperty property, Color bgColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Texture2D backgroundTexture = GradientEditor.GetBackgroundTexture(); + if (backgroundTexture != null) + { + Color color = GUI.color; + GUI.color = bgColor; + GUIStyle basicTextureStyle = EditorGUIUtility.GetBasicTextureStyle(backgroundTexture); + basicTextureStyle.Draw(position, false, false, false, false); + GUI.color = color; + } + Texture2D texture2D; + if (property != null) + { + texture2D = GradientPreviewCache.GetPropertyPreview(property); + } + else + { + texture2D = GradientPreviewCache.GetGradientPreview(gradient); + } + if (texture2D == null) + { + Debug.Log("Warning: Could not create preview for gradient"); + return; + } + GUIStyle basicTextureStyle2 = EditorGUIUtility.GetBasicTextureStyle(texture2D); + basicTextureStyle2.Draw(position, false, false, false, false); + } + } +} diff --git a/UnityEditor/UnityEditor/GradientPicker.cs b/UnityEditor/UnityEditor/GradientPicker.cs new file mode 100644 index 00000000..828d08ed --- /dev/null +++ b/UnityEditor/UnityEditor/GradientPicker.cs @@ -0,0 +1,228 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class GradientPicker : EditorWindow + { + private const int k_DefaultNumSteps = 0; + private static GradientPicker s_GradientPicker; + private GradientEditor m_GradientEditor; + private PresetLibraryEditor m_GradientLibraryEditor; + [SerializeField] + private PresetLibraryEditorState m_GradientLibraryEditorState; + private Gradient m_Gradient; + private GUIView m_DelegateView; + public static string presetsEditorPrefID + { + get + { + return "Gradient"; + } + } + private bool gradientChanged + { + get; + set; + } + public static GradientPicker instance + { + get + { + if (!GradientPicker.s_GradientPicker) + { + Debug.LogError("Gradient Picker not initalized, did you call Show first?"); + } + return GradientPicker.s_GradientPicker; + } + } + public string currentPresetLibrary + { + get + { + this.InitIfNeeded(); + return this.m_GradientLibraryEditor.currentLibraryWithoutExtension; + } + set + { + this.InitIfNeeded(); + this.m_GradientLibraryEditor.currentLibraryWithoutExtension = value; + } + } + public static bool visible + { + get + { + return GradientPicker.s_GradientPicker != null; + } + } + public static Gradient gradient + { + get + { + if (GradientPicker.s_GradientPicker != null) + { + return GradientPicker.s_GradientPicker.m_Gradient; + } + return null; + } + } + private GradientPicker() + { + base.hideFlags = HideFlags.DontSave; + } + public static void Show(Gradient newGradient) + { + GUIView current = GUIView.current; + if (GradientPicker.s_GradientPicker == null) + { + GradientPicker.s_GradientPicker = (GradientPicker)EditorWindow.GetWindow(typeof(GradientPicker), true, "Gradient Editor", false); + Vector2 minSize = new Vector2(360f, 224f); + Vector2 maxSize = new Vector2(1900f, 3000f); + GradientPicker.s_GradientPicker.minSize = minSize; + GradientPicker.s_GradientPicker.maxSize = maxSize; + GradientPicker.s_GradientPicker.wantsMouseMove = true; + GradientPicker.s_GradientPicker.ShowAuxWindow(); + } + else + { + GradientPicker.s_GradientPicker.Repaint(); + } + GradientPicker.s_GradientPicker.m_DelegateView = current; + GradientPicker.s_GradientPicker.Init(newGradient); + } + private void Init(Gradient newGradient) + { + this.m_Gradient = newGradient; + if (this.m_GradientEditor != null) + { + this.m_GradientEditor.Init(newGradient, 0); + } + base.Repaint(); + } + private void SetGradientData(Gradient gradient) + { + this.m_Gradient.colorKeys = gradient.colorKeys; + this.m_Gradient.alphaKeys = gradient.alphaKeys; + this.Init(this.m_Gradient); + } + public void OnEnable() + { + } + public void OnDisable() + { + if (this.m_GradientLibraryEditorState != null) + { + this.m_GradientLibraryEditorState.TransferEditorPrefsState(false); + } + if (this.m_GradientEditor != null) + { + this.m_GradientEditor.Clear(); + } + GradientPicker.s_GradientPicker = null; + } + public void OnDestroy() + { + this.m_GradientLibraryEditor.UnloadUsedLibraries(); + } + private void OnPlayModeStateChanged() + { + base.Close(); + } + private void InitIfNeeded() + { + if (this.m_GradientEditor == null) + { + this.m_GradientEditor = new GradientEditor(); + this.m_GradientEditor.Init(this.m_Gradient, 0); + } + if (this.m_GradientLibraryEditorState == null) + { + this.m_GradientLibraryEditorState = new PresetLibraryEditorState(GradientPicker.presetsEditorPrefID); + this.m_GradientLibraryEditorState.TransferEditorPrefsState(true); + } + if (this.m_GradientLibraryEditor == null) + { + ScriptableObjectSaveLoadHelper helper = new ScriptableObjectSaveLoadHelper("gradients", SaveType.Text); + this.m_GradientLibraryEditor = new PresetLibraryEditor(helper, this.m_GradientLibraryEditorState, new Action(this.PresetClickedCallback)); + this.m_GradientLibraryEditor.showHeader = true; + this.m_GradientLibraryEditor.minMaxPreviewHeight = new Vector2(14f, 14f); + } + } + private void PresetClickedCallback(int clickCount, object presetObject) + { + Gradient gradient = presetObject as Gradient; + if (gradient == null) + { + Debug.LogError("Incorrect object passed " + presetObject); + } + GradientPicker.SetCurrentGradient(gradient); + this.gradientChanged = true; + } + public void OnGUI() + { + if (this.m_Gradient == null) + { + return; + } + this.InitIfNeeded(); + float num = Mathf.Min(base.position.height, 120f); + float num2 = 10f; + float height = base.position.height - num - num2; + Rect position = new Rect(10f, 10f, base.position.width - 20f, num - 20f); + Rect rect = new Rect(0f, num + num2, base.position.width, height); + EditorGUI.DrawRect(new Rect(rect.x, rect.y - 1f, rect.width, 1f), new Color(0f, 0f, 0f, 0.3f)); + EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, 1f), new Color(1f, 1f, 1f, 0.1f)); + EditorGUI.BeginChangeCheck(); + this.m_GradientEditor.OnGUI(position); + if (EditorGUI.EndChangeCheck()) + { + this.gradientChanged = true; + } + this.m_GradientLibraryEditor.OnGUI(rect, this.m_Gradient); + if (this.gradientChanged) + { + this.gradientChanged = false; + this.SendEvent(true); + } + } + private void SendEvent(bool exitGUI) + { + if (this.m_DelegateView) + { + Event e = EditorGUIUtility.CommandEvent("GradientPickerChanged"); + base.Repaint(); + this.m_DelegateView.SendEvent(e); + if (exitGUI) + { + GUIUtility.ExitGUI(); + } + } + } + public static void SetCurrentGradient(Gradient gradient) + { + if (GradientPicker.s_GradientPicker == null) + { + return; + } + GradientPicker.s_GradientPicker.SetGradientData(gradient); + GUI.changed = true; + } + public static void CloseWindow() + { + if (GradientPicker.s_GradientPicker == null) + { + return; + } + GradientPicker.s_GradientPicker.Close(); + GUIUtility.ExitGUI(); + } + public static void RepaintWindow() + { + if (GradientPicker.s_GradientPicker == null) + { + return; + } + GradientPicker.s_GradientPicker.Repaint(); + } + } +} diff --git a/UnityEditor/UnityEditor/GradientPresetLibrary.cs b/UnityEditor/UnityEditor/GradientPresetLibrary.cs new file mode 100644 index 00000000..aae4557e --- /dev/null +++ b/UnityEditor/UnityEditor/GradientPresetLibrary.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class GradientPresetLibrary : PresetLibrary + { + [Serializable] + private class GradientPreset + { + [SerializeField] + private string m_Name; + [SerializeField] + private Gradient m_Gradient; + public Gradient gradient + { + get + { + return this.m_Gradient; + } + set + { + this.m_Gradient = value; + } + } + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public GradientPreset(Gradient preset, string presetName) + { + this.gradient = preset; + this.name = presetName; + } + } + [SerializeField] + private List m_Presets = new List(); + public override int Count() + { + return this.m_Presets.Count; + } + public override object GetPreset(int index) + { + return this.m_Presets[index].gradient; + } + public override void Add(object presetObject, string presetName) + { + Gradient gradient = presetObject as Gradient; + if (gradient == null) + { + Debug.LogError("Wrong type used in GradientPresetLibrary"); + return; + } + Gradient gradient2 = new Gradient(); + gradient2.alphaKeys = gradient.alphaKeys; + gradient2.colorKeys = gradient.colorKeys; + this.m_Presets.Add(new GradientPresetLibrary.GradientPreset(gradient2, presetName)); + } + public override void Replace(int index, object newPresetObject) + { + Gradient gradient = newPresetObject as Gradient; + if (gradient == null) + { + Debug.LogError("Wrong type used in GradientPresetLibrary"); + return; + } + Gradient gradient2 = new Gradient(); + gradient2.alphaKeys = gradient.alphaKeys; + gradient2.colorKeys = gradient.colorKeys; + this.m_Presets[index].gradient = gradient2; + } + public override void Remove(int index) + { + this.m_Presets.RemoveAt(index); + } + public override void Move(int index, int destIndex, bool insertAfterDestIndex) + { + PresetLibraryHelpers.MoveListItem(this.m_Presets, index, destIndex, insertAfterDestIndex); + } + public override void Draw(Rect rect, int index) + { + this.DrawInternal(rect, this.m_Presets[index].gradient); + } + public override void Draw(Rect rect, object presetObject) + { + this.DrawInternal(rect, presetObject as Gradient); + } + private void DrawInternal(Rect rect, Gradient gradient) + { + if (gradient == null) + { + return; + } + GradientEditor.DrawGradientWithBackground(rect, GradientPreviewCache.GetGradientPreview(gradient)); + } + public override string GetName(int index) + { + return this.m_Presets[index].name; + } + public override void SetName(int index, string presetName) + { + this.m_Presets[index].name = presetName; + } + public void DebugCreateTonsOfPresets() + { + int num = 150; + string arg = "Preset_"; + for (int i = 0; i < num; i++) + { + List list = new List(); + int num2 = UnityEngine.Random.Range(3, 8); + for (int j = 0; j < num2; j++) + { + list.Add(new GradientColorKey(new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value), UnityEngine.Random.value)); + } + List list2 = new List(); + int num3 = UnityEngine.Random.Range(3, 8); + for (int k = 0; k < num3; k++) + { + list2.Add(new GradientAlphaKey(UnityEngine.Random.value, UnityEngine.Random.value)); + } + this.Add(new Gradient + { + colorKeys = list.ToArray(), + alphaKeys = list2.ToArray() + }, arg + (i + 1)); + } + } + } +} diff --git a/UnityEditor/UnityEditor/GradientPresetLibraryEditor.cs b/UnityEditor/UnityEditor/GradientPresetLibraryEditor.cs new file mode 100644 index 00000000..f28b8e52 --- /dev/null +++ b/UnityEditor/UnityEditor/GradientPresetLibraryEditor.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(GradientPresetLibrary))] + internal class GradientPresetLibraryEditor : Editor + { + private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; + public void OnEnable() + { + this.m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(this.target, "Gradient Preset Library", new Action(this.OnEditButtonClicked)); + this.m_GenericPresetLibraryInspector.presetSize = new Vector2(72f, 16f); + this.m_GenericPresetLibraryInspector.lineSpacing = 4f; + } + public void OnDestroy() + { + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnDestroy(); + } + } + public override void OnInspectorGUI() + { + this.m_GenericPresetLibraryInspector.itemViewMode = PresetLibraryEditorState.GetItemViewMode("Gradient"); + if (this.m_GenericPresetLibraryInspector != null) + { + this.m_GenericPresetLibraryInspector.OnInspectorGUI(); + } + } + private void OnEditButtonClicked(string libraryPath) + { + GradientPicker.Show(new Gradient()); + GradientPicker.instance.currentPresetLibrary = libraryPath; + } + } +} diff --git a/UnityEditor/UnityEditor/HandleUtility.cs b/UnityEditor/UnityEditor/HandleUtility.cs new file mode 100644 index 00000000..4adad741 --- /dev/null +++ b/UnityEditor/UnityEditor/HandleUtility.cs @@ -0,0 +1,658 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class HandleUtility + { + private sealed class SavedCamera + { + private float near; + private float far; + private Rect pixelRect; + private Vector3 pos; + private Quaternion rot; + private CameraClearFlags clearFlags; + private int cullingMask; + private float fov; + private float orthographicSize; + private bool isOrtho; + internal SavedCamera(Camera source) + { + this.near = source.nearClipPlane; + this.far = source.farClipPlane; + this.pixelRect = source.pixelRect; + this.pos = source.transform.position; + this.rot = source.transform.rotation; + this.clearFlags = source.clearFlags; + this.cullingMask = source.cullingMask; + this.fov = source.fieldOfView; + this.orthographicSize = source.orthographicSize; + this.isOrtho = source.orthographic; + } + internal void Restore(Camera dest) + { + dest.nearClipPlane = this.near; + dest.farClipPlane = this.far; + dest.pixelRect = this.pixelRect; + dest.transform.position = this.pos; + dest.transform.rotation = this.rot; + dest.clearFlags = this.clearFlags; + dest.fieldOfView = this.fov; + dest.orthographicSize = this.orthographicSize; + dest.orthographic = this.isOrtho; + dest.cullingMask = this.cullingMask; + } + } + internal const float kPickDistance = 5f; + private const float kHandleSize = 80f; + private static bool s_UseYSign = false; + private static bool s_UseYSignZoom = false; + private static Vector3[] points = new Vector3[] + { + Vector3.zero, + Vector3.zero, + Vector3.zero, + Vector3.zero, + Vector3.zero + }; + private static int s_NearestControl; + private static float s_NearestDistance; + internal static float s_CustomPickDistance = 5f; + private static Material s_HandleMaterial; + private static Material s_HandleWireMaterial; + private static Material s_HandleWireMaterial2D; + private static Stack s_SavedCameras = new Stack(); + internal static Transform[] ignoreRaySnapObjects = null; + public static float acceleration + { + get + { + return (float)((!Event.current.shift) ? 1 : 4) * ((!Event.current.alt) ? 1f : 0.25f); + } + } + public static float niceMouseDelta + { + get + { + Vector2 delta = Event.current.delta; + delta.y = -delta.y; + if (Mathf.Abs(Mathf.Abs(delta.x) - Mathf.Abs(delta.y)) / Mathf.Max(Mathf.Abs(delta.x), Mathf.Abs(delta.y)) > 0.1f) + { + if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y)) + { + HandleUtility.s_UseYSign = false; + } + else + { + HandleUtility.s_UseYSign = true; + } + } + if (HandleUtility.s_UseYSign) + { + return Mathf.Sign(delta.y) * delta.magnitude * HandleUtility.acceleration; + } + return Mathf.Sign(delta.x) * delta.magnitude * HandleUtility.acceleration; + } + } + public static float niceMouseDeltaZoom + { + get + { + Vector2 vector = -Event.current.delta; + if (Mathf.Abs(Mathf.Abs(vector.x) - Mathf.Abs(vector.y)) / Mathf.Max(Mathf.Abs(vector.x), Mathf.Abs(vector.y)) > 0.1f) + { + if (Mathf.Abs(vector.x) > Mathf.Abs(vector.y)) + { + HandleUtility.s_UseYSignZoom = false; + } + else + { + HandleUtility.s_UseYSignZoom = true; + } + } + if (HandleUtility.s_UseYSignZoom) + { + return Mathf.Sign(vector.y) * vector.magnitude * HandleUtility.acceleration; + } + return Mathf.Sign(vector.x) * vector.magnitude * HandleUtility.acceleration; + } + } + public static int nearestControl + { + get + { + return (HandleUtility.s_NearestDistance > 5f) ? 0 : HandleUtility.s_NearestControl; + } + set + { + HandleUtility.s_NearestControl = value; + } + } + public static Material handleMaterial + { + get + { + if (!HandleUtility.s_HandleMaterial) + { + HandleUtility.s_HandleMaterial = (Material)EditorGUIUtility.Load("SceneView/Handles.mat"); + } + return HandleUtility.s_HandleMaterial; + } + } + internal static Material handleWireMaterial + { + get + { + if (!HandleUtility.s_HandleWireMaterial) + { + HandleUtility.s_HandleWireMaterial = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat"); + HandleUtility.s_HandleWireMaterial2D = (Material)EditorGUIUtility.LoadRequired("SceneView/2DHandleLines.mat"); + } + return (!Camera.current) ? HandleUtility.s_HandleWireMaterial2D : HandleUtility.s_HandleWireMaterial; + } + } + public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPosition, Vector3 constraintDir) + { + srcPosition = Handles.matrix.MultiplyPoint(srcPosition); + constraintDir = Handles.matrix.MultiplyVector(constraintDir); + float num = 1f; + Vector3 forward = Camera.current.transform.forward; + if (Vector3.Dot(constraintDir, forward) < 0f) + { + num = -1f; + } + Vector3 vector = constraintDir; + vector.y = -vector.y; + Camera current = Camera.current; + Vector2 vector2 = current.WorldToScreenPoint(srcPosition); + Vector2 vector3 = current.WorldToScreenPoint(srcPosition + constraintDir * num); + Vector2 x = dest; + Vector2 x2 = src; + if (vector2 == vector3) + { + return 0f; + } + x.y = -x.y; + x2.y = -x2.y; + float parametrization = HandleUtility.GetParametrization(x2, vector2, vector3); + float parametrization2 = HandleUtility.GetParametrization(x, vector2, vector3); + return (parametrization2 - parametrization) * num; + } + internal static float GetParametrization(Vector2 x0, Vector2 x1, Vector2 x2) + { + return -(Vector2.Dot(x1 - x0, x2 - x1) / (x2 - x1).sqrMagnitude); + } + public static float PointOnLineParameter(Vector3 point, Vector3 linePoint, Vector3 lineDirection) + { + return Vector3.Dot(lineDirection, point - linePoint) / lineDirection.sqrMagnitude; + } + public static Vector3 ProjectPointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd) + { + Vector3 rhs = point - lineStart; + Vector3 vector = lineEnd - lineStart; + float magnitude = vector.magnitude; + Vector3 vector2 = vector; + if (magnitude > 1E-06f) + { + vector2 /= magnitude; + } + float num = Vector3.Dot(vector2, rhs); + num = Mathf.Clamp(num, 0f, magnitude); + return lineStart + vector2 * num; + } + public static float DistancePointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd) + { + return Vector3.Magnitude(HandleUtility.ProjectPointLine(point, lineStart, lineEnd) - point); + } + public static float DistancePointBezier(Vector3 point, Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent) + { + return HandleUtility.INTERNAL_CALL_DistancePointBezier(ref point, ref startPosition, ref endPosition, ref startTangent, ref endTangent); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_DistancePointBezier(ref Vector3 point, ref Vector3 startPosition, ref Vector3 endPosition, ref Vector3 startTangent, ref Vector3 endTangent); + public static float DistanceToLine(Vector3 p1, Vector3 p2) + { + p1 = HandleUtility.WorldToGUIPoint(p1); + p2 = HandleUtility.WorldToGUIPoint(p2); + Vector2 mousePosition = Event.current.mousePosition; + float num = HandleUtility.DistancePointLine(mousePosition, p1, p2); + if (num < 0f) + { + num = 0f; + } + return num; + } + public static float DistanceToCircle(Vector3 position, float radius) + { + Vector2 a = HandleUtility.WorldToGUIPoint(position); + Camera current = Camera.current; + Vector2 b = Vector2.zero; + if (current) + { + b = HandleUtility.WorldToGUIPoint(position + current.transform.right * radius); + radius = (a - b).magnitude; + } + float magnitude = (a - Event.current.mousePosition).magnitude; + if (magnitude < radius) + { + return 0f; + } + return magnitude - radius; + } + public static float DistanceToRectangle(Vector3 position, Quaternion rotation, float size) + { + Vector3 b = rotation * new Vector3(size, 0f, 0f); + Vector3 b2 = rotation * new Vector3(0f, size, 0f); + HandleUtility.points[0] = HandleUtility.WorldToGUIPoint(position + b + b2); + HandleUtility.points[1] = HandleUtility.WorldToGUIPoint(position + b - b2); + HandleUtility.points[2] = HandleUtility.WorldToGUIPoint(position - b - b2); + HandleUtility.points[3] = HandleUtility.WorldToGUIPoint(position - b + b2); + HandleUtility.points[4] = HandleUtility.points[0]; + Vector2 mousePosition = Event.current.mousePosition; + bool flag = false; + int num = 4; + for (int i = 0; i < 5; i++) + { + if (HandleUtility.points[i].y > mousePosition.y != HandleUtility.points[num].y > mousePosition.y && mousePosition.x < (HandleUtility.points[num].x - HandleUtility.points[i].x) * (mousePosition.y - HandleUtility.points[i].y) / (HandleUtility.points[num].y - HandleUtility.points[i].y) + HandleUtility.points[i].x) + { + flag = !flag; + } + num = i; + } + if (!flag) + { + float num2 = -1f; + num = 1; + for (int j = 0; j < 4; j++) + { + float num3 = HandleUtility.DistancePointToLineSegment(mousePosition, HandleUtility.points[j], HandleUtility.points[num++]); + if (num3 < num2 || num2 < 0f) + { + num2 = num3; + } + } + return num2; + } + return 0f; + } + public static float DistancePointToLine(Vector2 p, Vector2 a, Vector2 b) + { + return Mathf.Abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / (b - a).magnitude; + } + public static float DistancePointToLineSegment(Vector2 p, Vector2 a, Vector2 b) + { + float sqrMagnitude = (b - a).sqrMagnitude; + if ((double)sqrMagnitude == 0.0) + { + return (p - a).magnitude; + } + float num = Vector2.Dot(p - a, b - a) / sqrMagnitude; + if ((double)num < 0.0) + { + return (p - a).magnitude; + } + if ((double)num > 1.0) + { + return (p - b).magnitude; + } + Vector2 b2 = a + num * (b - a); + return (p - b2).magnitude; + } + public static float DistanceToDisc(Vector3 center, Vector3 normal, float radius) + { + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + return HandleUtility.DistanceToArc(center, normal, from, 360f, radius); + } + public static Vector3 ClosestPointToDisc(Vector3 center, Vector3 normal, float radius) + { + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + return HandleUtility.ClosestPointToArc(center, normal, from, 360f, radius); + } + public static float DistanceToArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + Vector3[] dest = new Vector3[60]; + Handles.SetDiscSectionPoints(dest, 60, center, normal, from, angle, radius); + return HandleUtility.DistanceToPolyLine(dest); + } + public static Vector3 ClosestPointToArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + Vector3[] array = new Vector3[60]; + Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); + return HandleUtility.ClosestPointToPolyLine(array); + } + public static float DistanceToPolyLine(params Vector3[] points) + { + float num = HandleUtility.DistanceToLine(points[0], points[1]); + for (int i = 2; i < points.Length; i++) + { + float num2 = HandleUtility.DistanceToLine(points[i - 1], points[i]); + if (num2 < num) + { + num = num2; + } + } + return num; + } + public static Vector3 ClosestPointToPolyLine(params Vector3[] vertices) + { + float num = HandleUtility.DistanceToLine(vertices[0], vertices[1]); + int num2 = 0; + for (int i = 2; i < vertices.Length; i++) + { + float num3 = HandleUtility.DistanceToLine(vertices[i - 1], vertices[i]); + if (num3 < num) + { + num = num3; + num2 = i - 1; + } + } + Vector3 vector = vertices[num2]; + Vector3 vector2 = vertices[num2 + 1]; + Vector2 v = Event.current.mousePosition - HandleUtility.WorldToGUIPoint(vector); + Vector2 v2 = HandleUtility.WorldToGUIPoint(vector2) - HandleUtility.WorldToGUIPoint(vector); + float magnitude = v2.magnitude; + float num4 = Vector3.Dot(v2, v); + if (magnitude > 1E-06f) + { + num4 /= magnitude * magnitude; + } + num4 = Mathf.Clamp01(num4); + return Vector3.Lerp(vector, vector2, num4); + } + public static void AddControl(int controlId, float distance) + { + if (distance < HandleUtility.s_CustomPickDistance && distance > 5f) + { + distance = 5f; + } + if (distance <= HandleUtility.s_NearestDistance) + { + HandleUtility.s_NearestDistance = distance; + HandleUtility.s_NearestControl = controlId; + } + } + public static void AddDefaultControl(int controlId) + { + HandleUtility.AddControl(controlId, 5f); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CameraNeedsToRenderIntoRT(Camera camera); + private static void BeginHandles() + { + Handles.Init(); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + HandleUtility.s_NearestControl = 0; + HandleUtility.s_NearestDistance = 5f; + } + Handles.lighting = true; + Handles.color = Color.white; + HandleUtility.s_CustomPickDistance = 5f; + Handles.Internal_SetCurrentCamera(null); + EditorGUI.s_DelayedTextEditor.BeginGUI(); + } + private static void SetViewInfo(Vector2 screenPosition) + { + GUIUtility.s_EditorScreenPointOffset = screenPosition; + } + private static void EndHandles() + { + EventType type = Event.current.type; + if (type != EventType.Layout) + { + GUIUtility.s_HasKeyboardFocus = false; + GUIUtility.s_EditorScreenPointOffset = Vector2.zero; + } + EditorGUI.s_DelayedTextEditor.EndGUI(type); + } + public static float GetHandleSize(Vector3 position) + { + Camera current = Camera.current; + position = Handles.matrix.MultiplyPoint(position); + if (current) + { + Transform transform = current.transform; + Vector3 position2 = transform.position; + float z = Vector3.Dot(position - position2, transform.TransformDirection(new Vector3(0f, 0f, 1f))); + Vector3 a = current.WorldToScreenPoint(position2 + transform.TransformDirection(new Vector3(0f, 0f, z))); + Vector3 b = current.WorldToScreenPoint(position2 + transform.TransformDirection(new Vector3(1f, 0f, z))); + float magnitude = (a - b).magnitude; + return 80f / Mathf.Max(magnitude, 0.0001f); + } + return 20f; + } + public static Vector2 WorldToGUIPoint(Vector3 world) + { + world = Handles.matrix.MultiplyPoint(world); + Camera current = Camera.current; + if (current) + { + Vector2 absolutePos = current.WorldToScreenPoint(world); + absolutePos.y = (float)Screen.height - absolutePos.y; + return GUIClip.Clip(absolutePos); + } + return new Vector2(world.x, world.y); + } + public static Ray GUIPointToWorldRay(Vector2 position) + { + if (!Camera.current) + { + Debug.LogError("Unable to convert GUI point to world ray if a camera has not been set up!"); + return new Ray(Vector3.zero, Vector3.forward); + } + Vector2 vector = GUIClip.Unclip(position); + vector.y = (float)Screen.height - vector.y; + Camera current = Camera.current; + return current.ScreenPointToRay(new Vector2(vector.x, vector.y)); + } + public static Rect WorldPointToSizedRect(Vector3 position, GUIContent content, GUIStyle style) + { + Vector2 vector = HandleUtility.WorldToGUIPoint(position); + Vector2 vector2 = style.CalcSize(content); + Rect rect = new Rect(vector.x, vector.y, vector2.x, vector2.y); + switch (style.alignment) + { + case TextAnchor.UpperCenter: + rect.xMin -= rect.width * 0.5f; + break; + case TextAnchor.UpperRight: + rect.xMin -= rect.width; + break; + case TextAnchor.MiddleLeft: + rect.yMin -= rect.height * 0.5f; + break; + case TextAnchor.MiddleCenter: + rect.xMin -= rect.width * 0.5f; + rect.yMin -= rect.height * 0.5f; + break; + case TextAnchor.MiddleRight: + rect.xMin -= rect.width; + rect.yMin -= rect.height * 0.5f; + break; + case TextAnchor.LowerLeft: + rect.yMin -= rect.height * 0.5f; + break; + case TextAnchor.LowerCenter: + rect.xMin -= rect.width * 0.5f; + rect.yMin -= rect.height; + break; + case TextAnchor.LowerRight: + rect.xMin -= rect.width; + rect.yMin -= rect.height; + break; + } + return style.padding.Add(rect); + } + public static GameObject[] PickRectObjects(Rect rect) + { + return HandleUtility.PickRectObjects(rect, true); + } + public static GameObject[] PickRectObjects(Rect rect, bool selectPrefabRootsOnly) + { + Camera current = Camera.current; + rect.x /= current.pixelWidth; + rect.width /= current.pixelWidth; + rect.y /= current.pixelHeight; + rect.height /= current.pixelHeight; + return HandleUtility.Internal_PickRectObjects(current, rect, selectPrefabRootsOnly); + } + internal static GameObject[] Internal_PickRectObjects(Camera cam, Rect rect, bool selectPrefabRoots) + { + return HandleUtility.INTERNAL_CALL_Internal_PickRectObjects(cam, ref rect, selectPrefabRoots); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GameObject[] INTERNAL_CALL_Internal_PickRectObjects(Camera cam, ref Rect rect, bool selectPrefabRoots); + internal static bool FindNearestVertex(Vector2 screenPoint, Transform[] objectsToSearch, out Vector3 vertex) + { + Camera current = Camera.current; + screenPoint.y = current.pixelRect.yMax - screenPoint.y; + return HandleUtility.Internal_FindNearestVertex(current, screenPoint, objectsToSearch, HandleUtility.ignoreRaySnapObjects, out vertex); + } + private static bool Internal_FindNearestVertex(Camera cam, Vector2 point, Transform[] objectsToSearch, Transform[] ignoreObjects, out Vector3 vertex) + { + return HandleUtility.INTERNAL_CALL_Internal_FindNearestVertex(cam, ref point, objectsToSearch, ignoreObjects, out vertex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_FindNearestVertex(Camera cam, ref Vector2 point, Transform[] objectsToSearch, Transform[] ignoreObjects, out Vector3 vertex); + public static GameObject PickGameObject(Vector2 position, bool selectPrefabRoot) + { + Camera current = Camera.current; + int cullingMask = current.cullingMask; + position = GUIClip.Unclip(position); + position.y = (float)Screen.height - position.y - current.pixelRect.yMin; + GameObject gameObject = HandleUtility.Internal_PickClosestGO(current, cullingMask, position); + if (!gameObject || !selectPrefabRoot) + { + return gameObject; + } + GameObject gameObject2 = HandleUtility.FindSelectionBase(gameObject) ?? gameObject; + Transform activeTransform = Selection.activeTransform; + GameObject y = (!activeTransform) ? null : (HandleUtility.FindSelectionBase(activeTransform.gameObject) ?? activeTransform.gameObject); + if (gameObject2 == y) + { + return gameObject; + } + return gameObject2; + } + private static GameObject FindSelectionBase(GameObject go) + { + Transform y = null; + PrefabType prefabType = PrefabUtility.GetPrefabType(go); + if (prefabType == PrefabType.PrefabInstance || prefabType == PrefabType.ModelPrefabInstance) + { + y = PrefabUtility.FindPrefabRoot(go).transform; + } + Transform transform = go.transform; + while (transform != null) + { + if (transform == y) + { + return transform.gameObject; + } + if (AttributeHelper.GameObjectContainsAttribute(transform.gameObject, typeof(SelectionBaseAttribute))) + { + return transform.gameObject; + } + transform = transform.parent; + } + return null; + } + internal static GameObject Internal_PickClosestGO(Camera cam, int layers, Vector2 position) + { + return HandleUtility.INTERNAL_CALL_Internal_PickClosestGO(cam, layers, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GameObject INTERNAL_CALL_Internal_PickClosestGO(Camera cam, int layers, ref Vector2 position); + public static void PushCamera(Camera camera) + { + HandleUtility.s_SavedCameras.Push(new HandleUtility.SavedCamera(camera)); + } + public static void PopCamera(Camera camera) + { + HandleUtility.SavedCamera savedCamera = (HandleUtility.SavedCamera)HandleUtility.s_SavedCameras.Pop(); + savedCamera.Restore(camera); + } + public static object RaySnap(Ray ray) + { + RaycastHit[] array = Physics.RaycastAll(ray, float.PositiveInfinity, Camera.current.cullingMask); + float num = float.PositiveInfinity; + int num2 = -1; + if (HandleUtility.ignoreRaySnapObjects != null) + { + for (int i = 0; i < array.Length; i++) + { + if (!array[i].collider.isTrigger && array[i].distance < num) + { + bool flag = false; + for (int j = 0; j < HandleUtility.ignoreRaySnapObjects.Length; j++) + { + if (array[i].transform == HandleUtility.ignoreRaySnapObjects[j]) + { + flag = true; + break; + } + } + if (!flag) + { + num = array[i].distance; + num2 = i; + } + } + } + } + else + { + for (int k = 0; k < array.Length; k++) + { + if (array[k].distance < num) + { + num = array[k].distance; + num2 = k; + } + } + } + if (num2 >= 0) + { + return array[num2]; + } + return null; + } + internal static float CalcRayPlaceOffset(Transform[] objects, Vector3 normal) + { + return HandleUtility.INTERNAL_CALL_CalcRayPlaceOffset(objects, ref normal); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_CalcRayPlaceOffset(Transform[] objects, ref Vector3 normal); + public static void Repaint() + { + HandleUtility.Internal_Repaint(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Repaint(); + internal static bool IntersectRayMesh(Ray ray, Mesh mesh, Matrix4x4 matrix, out RaycastHit hit) + { + return HandleUtility.INTERNAL_CALL_IntersectRayMesh(ref ray, mesh, ref matrix, out hit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_IntersectRayMesh(ref Ray ray, Mesh mesh, ref Matrix4x4 matrix, out RaycastHit hit); + } +} diff --git a/UnityEditor/UnityEditor/Handles.cs b/UnityEditor/UnityEditor/Handles.cs new file mode 100644 index 00000000..ab91878d --- /dev/null +++ b/UnityEditor/UnityEditor/Handles.cs @@ -0,0 +1,1618 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class Handles + { + private enum PlaneHandle + { + xzPlane, + xyPlane, + yzPlane + } + internal enum FilterMode + { + Off, + ShowFiltered, + ShowRest + } + public delegate void DrawCapFunction(int controlID, Vector3 position, Quaternion rotation, float size); + private const float k_BoneThickness = 0.08f; + private const int kMaxDottedLineVertices = 1000; + private static Vector3[] verts = new Vector3[] + { + Vector3.zero, + Vector3.zero, + Vector3.zero, + Vector3.zero + }; + private static bool s_FreeMoveMode = false; + private static Vector3 s_PlanarHandlesOctant = Vector3.one; + internal static PrefColor s_XAxisColor = new PrefColor("Scene/X Axis", 0.858823538f, 0.243137255f, 0.113725491f, 0.93f); + internal static PrefColor s_YAxisColor = new PrefColor("Scene/Y Axis", 0.6039216f, 0.9529412f, 0.282352954f, 0.93f); + internal static PrefColor s_ZAxisColor = new PrefColor("Scene/Z Axis", 0.227450982f, 0.478431374f, 0.972549f, 0.93f); + internal static PrefColor s_CenterColor = new PrefColor("Scene/Center Axis", 0.8f, 0.8f, 0.8f, 0.93f); + internal static PrefColor s_SelectedColor = new PrefColor("Scene/Selected Axis", 0.9647059f, 0.9490196f, 0.196078435f, 0.89f); + internal static PrefColor s_SecondaryColor = new PrefColor("Scene/Guide Line", 0.5f, 0.5f, 0.5f, 0.2f); + internal static Color staticColor = new Color(0.5f, 0.5f, 0.5f, 0f); + internal static float staticBlend = 0.6f; + internal static float backfaceAlphaMultiplier = 0.2f; + internal static Color s_ColliderHandleColor = new Color(145f, 244f, 139f, 210f) / 255f; + internal static Color s_ColliderHandleColorDisabled = new Color(84f, 200f, 77f, 140f) / 255f; + internal static Color s_BoundingBoxHandleColor = new Color(255f, 255f, 255f, 150f) / 255f; + internal static int s_SliderHash = "SliderHash".GetHashCode(); + internal static int s_Slider2DHash = "Slider2DHash".GetHashCode(); + internal static int s_FreeRotateHandleHash = "FreeRotateHandleHash".GetHashCode(); + internal static int s_RadiusHandleHash = "RadiusHandleHash".GetHashCode(); + internal static int s_xAxisMoveHandleHash = "xAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_yAxisMoveHandleHash = "yAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_zAxisMoveHandleHash = "xAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_FreeMoveHandleHash = "FreeMoveHandleHash".GetHashCode(); + internal static int s_xzAxisMoveHandleHash = "xzAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_xyAxisMoveHandleHash = "xyAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_yzAxisMoveHandleHash = "yzAxisFreeMoveHandleHash".GetHashCode(); + internal static int s_ScaleSliderHash = "ScaleSliderHash".GetHashCode(); + internal static int s_ScaleValueHandleHash = "ScaleValueHandleHash".GetHashCode(); + internal static int s_DiscHash = "DiscHash".GetHashCode(); + internal static int s_ButtonHash = "ButtonHash".GetHashCode(); + private static bool s_Lighting = true; + private static Color s_Color; + internal static Matrix4x4 s_Matrix = Matrix4x4.identity; + internal static Matrix4x4 s_InverseMatrix = Matrix4x4.identity; + private static Vector3[] s_RectangleCapPointsCache = new Vector3[5]; + internal static Mesh s_CubeMesh; + internal static Mesh s_SphereMesh; + internal static Mesh s_ConeMesh; + internal static Mesh s_CylinderMesh; + internal static Mesh s_QuadMesh; + private static bool currentlyDragging + { + get + { + return GUIUtility.hotControl != 0; + } + } + public static Color xAxisColor + { + get + { + return Handles.s_XAxisColor; + } + } + public static Color yAxisColor + { + get + { + return Handles.s_YAxisColor; + } + } + public static Color zAxisColor + { + get + { + return Handles.s_ZAxisColor; + } + } + public static Color centerColor + { + get + { + return Handles.s_CenterColor; + } + } + public static Color selectedColor + { + get + { + return Handles.s_SelectedColor; + } + } + public static Color secondaryColor + { + get + { + return Handles.s_SecondaryColor; + } + } + public static bool lighting + { + get + { + return Handles.s_Lighting; + } + set + { + Handles.s_Lighting = value; + } + } + public static Color color + { + get + { + return Handles.s_Color; + } + set + { + Handles.s_Color = value; + } + } + public static Matrix4x4 matrix + { + get + { + return Handles.s_Matrix; + } + set + { + Handles.s_Matrix = value; + Handles.s_InverseMatrix = value.inverse; + } + } + public static Matrix4x4 inverseMatrix + { + get + { + return Handles.s_InverseMatrix; + } + } + public Camera currentCamera + { + get + { + return Camera.current; + } + set + { + Handles.Internal_SetCurrentCamera(value); + } + } + internal static Color realHandleColor + { + get + { + return Handles.s_Color * new Color(1f, 1f, 1f, 0.5f) + ((!Handles.s_Lighting) ? new Color(0f, 0f, 0f, 0f) : new Color(0f, 0f, 0f, 0.5f)); + } + } + internal static float DistanceToPolygone(Vector3[] vertices) + { + return HandleUtility.DistanceToPolyLine(vertices); + } + internal static void DoBoneHandle(Transform target) + { + Handles.DoBoneHandle(target, null); + } + internal static void DoBoneHandle(Transform target, Dictionary validBones) + { + int hashCode = target.name.GetHashCode(); + Event current = Event.current; + bool flag = false; + if (validBones != null) + { + foreach (Transform key in target) + { + if (validBones.ContainsKey(key)) + { + flag = true; + break; + } + } + } + Vector3 position = target.position; + List list = new List(); + if (!flag && target.parent != null) + { + list.Add(target.position + (target.position - target.parent.position) * 0.4f); + } + else + { + foreach (Transform transform in target) + { + if (validBones == null || validBones.ContainsKey(transform)) + { + list.Add(transform.position); + } + } + } + for (int i = 0; i < list.Count; i++) + { + Vector3 vector = list[i]; + switch (current.GetTypeForControl(hashCode)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == hashCode && current.button == 0) || (GUIUtility.keyboardControl == hashCode && current.button == 2)) + { + int num = hashCode; + GUIUtility.keyboardControl = num; + GUIUtility.hotControl = num; + if (current.shift) + { + UnityEngine.Object[] objects = Selection.objects; + if (!ArrayUtility.Contains(objects, target)) + { + ArrayUtility.Add(ref objects, target); + Selection.objects = objects; + } + } + else + { + Selection.activeObject = target; + } + EditorGUIUtility.PingObject(target); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == hashCode && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == hashCode) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = new UnityEngine.Object[] + { + target + }; + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(target)); + current.Use(); + } + break; + case EventType.Repaint: + { + float num2 = Vector3.Magnitude(vector - position); + if (num2 > 0f) + { + float num3 = num2 * 0.08f; + if (flag) + { + Handles.DrawBone(vector, position, num3); + } + else + { + Handles.SphereCap(hashCode, position, target.rotation, num3 * 5f); + } + } + break; + } + case EventType.Layout: + { + float num4 = Vector3.Magnitude(vector - position); + float radius = num4 * 0.08f; + Vector3[] boneVertices = Handles.GetBoneVertices(vector, position, radius); + HandleUtility.AddControl(hashCode, Handles.DistanceToPolygone(boneVertices)); + break; + } + } + } + } + internal static void DrawBone(Vector3 endPoint, Vector3 basePoint, float size) + { + Vector3[] boneVertices = Handles.GetBoneVertices(endPoint, basePoint, size); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(4); + GL.Color(Handles.s_Color); + for (int i = 0; i < 3; i++) + { + GL.Vertex(boneVertices[i * 6]); + GL.Vertex(boneVertices[i * 6 + 1]); + GL.Vertex(boneVertices[i * 6 + 2]); + GL.Vertex(boneVertices[i * 6 + 3]); + GL.Vertex(boneVertices[i * 6 + 4]); + GL.Vertex(boneVertices[i * 6 + 5]); + } + GL.End(); + GL.Begin(1); + GL.Color(Handles.s_Color * new Color(1f, 1f, 1f, 0f) + new Color(0f, 0f, 0f, 1f)); + for (int j = 0; j < 3; j++) + { + GL.Vertex(boneVertices[j * 6]); + GL.Vertex(boneVertices[j * 6 + 1]); + GL.Vertex(boneVertices[j * 6 + 1]); + GL.Vertex(boneVertices[j * 6 + 2]); + } + GL.End(); + } + internal static Vector3[] GetBoneVertices(Vector3 endPoint, Vector3 basePoint, float radius) + { + Vector3 lhs = Vector3.Normalize(endPoint - basePoint); + Vector3 vector = Vector3.Cross(lhs, Vector3.up); + if (Vector3.SqrMagnitude(vector) < 0.1f) + { + vector = Vector3.Cross(lhs, Vector3.right); + } + vector.Normalize(); + Vector3 a = Vector3.Cross(lhs, vector); + Vector3[] array = new Vector3[18]; + float num = 0f; + for (int i = 0; i < 3; i++) + { + float num2 = Mathf.Cos(num); + float num3 = Mathf.Sin(num); + float num4 = Mathf.Cos(num + 2.09439516f); + float num5 = Mathf.Sin(num + 2.09439516f); + Vector3 vector2 = basePoint + vector * (num2 * radius) + a * (num3 * radius); + Vector3 vector3 = basePoint + vector * (num4 * radius) + a * (num5 * radius); + array[i * 6] = endPoint; + array[i * 6 + 1] = vector2; + array[i * 6 + 2] = vector3; + array[i * 6 + 3] = basePoint; + array[i * 6 + 4] = vector3; + array[i * 6 + 5] = vector2; + num += 2.09439516f; + } + return array; + } + internal static Vector3 DoConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) + { + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + float num = radiusAngleRange.x; + float num2 = radiusAngleRange.y; + float num3 = radiusAngleRange.z; + num2 = Mathf.Max(0f, num2); + bool changed = GUI.changed; + num3 = Handles.SizeSlider(position, vector, num3); + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + num = Handles.SizeSlider(position, vector2, num); + num = Handles.SizeSlider(position, -vector2, num); + num = Handles.SizeSlider(position, vector3, num); + num = Handles.SizeSlider(position, -vector3, num); + if (GUI.changed) + { + num = Mathf.Max(0f, num); + } + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + float num4 = Mathf.Min(1000f, Mathf.Abs(num3 * Mathf.Tan(0.0174532924f * num2)) + num); + num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); + if (GUI.changed) + { + num2 = Mathf.Clamp(57.29578f * Mathf.Atan((num4 - num) / Mathf.Abs(num3)), 0f, 90f); + } + GUI.changed |= changed; + if (num > 0f) + { + Handles.DrawWireDisc(position, vector, num); + } + if (num4 > 0f) + { + Handles.DrawWireDisc(position + num3 * vector, vector, num4); + } + Handles.DrawLine(position + vector2 * num, position + vector * num3 + vector2 * num4); + Handles.DrawLine(position - vector2 * num, position + vector * num3 - vector2 * num4); + Handles.DrawLine(position + vector3 * num, position + vector * num3 + vector3 * num4); + Handles.DrawLine(position - vector3 * num, position + vector * num3 - vector3 * num4); + return new Vector3(num, num2, num3); + } + internal static Vector2 DoConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) + { + float num = angleAndRange.x; + float num2 = angleAndRange.y; + float num3 = num2 * rangeScale; + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + bool changed = GUI.changed; + GUI.changed = false; + num3 = Handles.SizeSlider(position, vector, num3); + if (GUI.changed) + { + num2 = Mathf.Max(0f, num3 / rangeScale); + } + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + float num4 = num3 * Mathf.Tan(0.0174532924f * num / 2f) * angleScale; + num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); + if (GUI.changed) + { + num = Mathf.Clamp(57.29578f * Mathf.Atan(num4 / (num3 * angleScale)) * 2f, 0f, 179f); + } + GUI.changed |= changed; + if (!handlesOnly) + { + Handles.DrawLine(position, position + vector * num3 + vector2 * num4); + Handles.DrawLine(position, position + vector * num3 - vector2 * num4); + Handles.DrawLine(position, position + vector * num3 + vector3 * num4); + Handles.DrawLine(position, position + vector * num3 - vector3 * num4); + Handles.DrawWireDisc(position + num3 * vector, vector, num4); + } + return new Vector2(num, num2); + } + private static float SizeSlider(Vector3 p, Vector3 d, float r) + { + Vector3 vector = p + d * r; + float handleSize = HandleUtility.GetHandleSize(vector); + bool changed = GUI.changed; + GUI.changed = false; + vector = Handles.Slider(vector, d, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + if (GUI.changed) + { + r = Vector3.Dot(vector - p, d); + } + GUI.changed |= changed; + return r; + } + public static Vector3 DoPositionHandle(Vector3 position, Quaternion rotation) + { + Event current = Event.current; + switch (current.type) + { + case EventType.KeyDown: + if (current.keyCode == KeyCode.V && !Handles.currentlyDragging) + { + Handles.s_FreeMoveMode = true; + } + break; + case EventType.KeyUp: + position = Handles.DoPositionHandle_Internal(position, rotation); + if (current.keyCode == KeyCode.V && !current.shift && !Handles.currentlyDragging) + { + Handles.s_FreeMoveMode = false; + } + return position; + case EventType.Layout: + if (!Handles.currentlyDragging && !Tools.vertexDragging) + { + Handles.s_FreeMoveMode = current.shift; + } + break; + } + return Handles.DoPositionHandle_Internal(position, rotation); + } + private static Vector3 DoPositionHandle_Internal(Vector3 position, Quaternion rotation) + { + float handleSize = HandleUtility.GetHandleSize(position); + Color color = Handles.color; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("xAxis"); + position = Handles.Slider(position, rotation * Vector3.right, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.x); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("yAxis"); + position = Handles.Slider(position, rotation * Vector3.up, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.y); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("zAxis"); + position = Handles.Slider(position, rotation * Vector3.forward, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.z); + if (Handles.s_FreeMoveMode) + { + Handles.color = Handles.centerColor; + GUI.SetNextControlName("FreeMoveAxis"); + position = Handles.FreeMoveHandle(position, rotation, handleSize * 0.15f, SnapSettings.move, new Handles.DrawCapFunction(Handles.RectangleCap)); + } + else + { + position = Handles.DoPlanarHandle(Handles.PlaneHandle.xzPlane, position, rotation, handleSize * 0.25f); + position = Handles.DoPlanarHandle(Handles.PlaneHandle.xyPlane, position, rotation, handleSize * 0.25f); + position = Handles.DoPlanarHandle(Handles.PlaneHandle.yzPlane, position, rotation, handleSize * 0.25f); + } + Handles.color = color; + return position; + } + private static Vector3 DoPlanarHandle(Handles.PlaneHandle planeID, Vector3 position, Quaternion rotation, float handleSize) + { + int num = 0; + int num2 = 0; + int hint = 0; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + switch (planeID) + { + case Handles.PlaneHandle.xzPlane: + num = 0; + num2 = 2; + Handles.color = ((!flag) ? Handles.yAxisColor : Handles.staticColor); + hint = Handles.s_xzAxisMoveHandleHash; + break; + case Handles.PlaneHandle.xyPlane: + num = 0; + num2 = 1; + Handles.color = ((!flag) ? Handles.zAxisColor : Handles.staticColor); + hint = Handles.s_xyAxisMoveHandleHash; + break; + case Handles.PlaneHandle.yzPlane: + num = 1; + num2 = 2; + Handles.color = ((!flag) ? Handles.xAxisColor : Handles.staticColor); + hint = Handles.s_yzAxisMoveHandleHash; + break; + } + int index = 3 - num2 - num; + Color color = Handles.color; + Matrix4x4 matrix4x = Matrix4x4.TRS(position, rotation, Vector3.one); + Vector3 normalized; + if (Camera.current.orthographic) + { + normalized = matrix4x.inverse.MultiplyVector(SceneView.currentDrawingSceneView.cameraTargetRotation * -Vector3.forward).normalized; + } + else + { + normalized = matrix4x.inverse.MultiplyPoint(SceneView.currentDrawingSceneView.camera.transform.position).normalized; + } + int controlID = GUIUtility.GetControlID(hint, FocusType.Keyboard); + if (Mathf.Abs(normalized[index]) < 0.05f && GUIUtility.hotControl != controlID) + { + Handles.color = color; + return position; + } + if (!Handles.currentlyDragging) + { + Handles.s_PlanarHandlesOctant[num] = (float)((normalized[num] >= -0.01f) ? 1 : -1); + Handles.s_PlanarHandlesOctant[num2] = (float)((normalized[num2] >= -0.01f) ? 1 : -1); + } + Vector3 vector = Handles.s_PlanarHandlesOctant; + vector[index] = 0f; + vector = rotation * (vector * handleSize * 0.5f); + Vector3 vector2 = Vector3.zero; + Vector3 vector3 = Vector3.zero; + Vector3 vector4 = Vector3.zero; + vector2[num] = 1f; + vector3[num2] = 1f; + vector4[index] = 1f; + vector2 = rotation * vector2; + vector3 = rotation * vector3; + vector4 = rotation * vector4; + Handles.verts[0] = position + vector + (vector2 + vector3) * handleSize * 0.5f; + Handles.verts[1] = position + vector + (-vector2 + vector3) * handleSize * 0.5f; + Handles.verts[2] = position + vector + (-vector2 - vector3) * handleSize * 0.5f; + Handles.verts[3] = position + vector + (vector2 - vector3) * handleSize * 0.5f; + Handles.DrawSolidRectangleWithOutline(Handles.verts, new Color(Handles.color.r, Handles.color.g, Handles.color.b, 0.1f), new Color(0f, 0f, 0f, 0f)); + position = Handles.Slider2D(controlID, position, vector, vector4, vector2, vector3, handleSize * 0.5f, new Handles.DrawCapFunction(Handles.RectangleCap), new Vector2(SnapSettings.move[num], SnapSettings.move[num2])); + Handles.color = color; + return position; + } + internal static float DoRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) + { + float num = 90f; + Vector3[] array = new Vector3[] + { + rotation * Vector3.right, + rotation * Vector3.up, + rotation * Vector3.forward, + rotation * -Vector3.right, + rotation * -Vector3.up, + rotation * -Vector3.forward + }; + Vector3 vector; + if (Camera.current.orthographic) + { + vector = Camera.current.transform.forward; + if (!handlesOnly) + { + Handles.DrawWireDisc(position, vector, radius); + for (int i = 0; i < 3; i++) + { + Vector3 normalized = Vector3.Cross(array[i], vector).normalized; + Handles.DrawTwoShadedWireDisc(position, array[i], normalized, 180f, radius); + } + } + } + else + { + vector = position - Camera.current.transform.position; + float sqrMagnitude = vector.sqrMagnitude; + float num2 = radius * radius; + float num3 = num2 * num2 / sqrMagnitude; + float num4 = num3 / num2; + if (num4 < 1f) + { + float num5 = Mathf.Sqrt(num2 - num3); + num = Mathf.Atan2(num5, Mathf.Sqrt(num3)) * 57.29578f; + if (!handlesOnly) + { + Handles.DrawWireDisc(position - num2 * vector / sqrMagnitude, vector, num5); + } + } + else + { + num = -1000f; + } + if (!handlesOnly) + { + for (int j = 0; j < 3; j++) + { + if (num4 < 1f) + { + float num6 = Vector3.Angle(vector, array[j]); + num6 = 90f - Mathf.Min(num6, 180f - num6); + float num7 = Mathf.Tan(num6 * 0.0174532924f); + float num8 = Mathf.Sqrt(num3 + num7 * num7 * num3) / radius; + if (num8 < 1f) + { + float num9 = Mathf.Asin(num8) * 57.29578f; + Vector3 vector2 = Vector3.Cross(array[j], vector).normalized; + vector2 = Quaternion.AngleAxis(num9, array[j]) * vector2; + Handles.DrawTwoShadedWireDisc(position, array[j], vector2, (90f - num9) * 2f, radius); + } + else + { + Handles.DrawTwoShadedWireDisc(position, array[j], radius); + } + } + else + { + Handles.DrawTwoShadedWireDisc(position, array[j], radius); + } + } + } + } + Color color = Handles.color; + for (int k = 0; k < 6; k++) + { + int controlID = GUIUtility.GetControlID(Handles.s_RadiusHandleHash, FocusType.Keyboard); + float num10 = Vector3.Angle(array[k], -vector); + if ((num10 > 5f && num10 < 175f) || GUIUtility.hotControl == controlID) + { + Color color2 = color; + if (num10 > num + 5f) + { + color2.a = Mathf.Clamp01(Handles.backfaceAlphaMultiplier * color.a * 2f); + } + else + { + color2.a = Mathf.Clamp01(color.a * 2f); + } + Handles.color = color2; + Vector3 vector3 = position + radius * array[k]; + bool changed = GUI.changed; + GUI.changed = false; + vector3 = Slider1D.Do(controlID, vector3, array[k], HandleUtility.GetHandleSize(vector3) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + if (GUI.changed) + { + radius = Vector3.Distance(vector3, position); + } + GUI.changed |= changed; + } + } + Handles.color = color; + return radius; + } + internal static Vector2 DoRectHandles(Quaternion rotation, Vector3 position, Vector2 size) + { + Vector3 b = rotation * Vector3.forward; + Vector3 vector = rotation * Vector3.up; + Vector3 vector2 = rotation * Vector3.right; + float num = 0.5f * size.x; + float num2 = 0.5f * size.y; + Vector3 vector3 = position + vector * num2 + vector2 * num; + Vector3 vector4 = position - vector * num2 + vector2 * num; + Vector3 vector5 = position - vector * num2 - vector2 * num; + Vector3 vector6 = position + vector * num2 - vector2 * num; + Handles.DrawLine(vector3, vector4); + Handles.DrawLine(vector4, vector5); + Handles.DrawLine(vector5, vector6); + Handles.DrawLine(vector6, vector3); + Color color = Handles.color; + color.a = Mathf.Clamp01(color.a * 2f); + Handles.color = color; + num2 = Handles.SizeSlider(position, vector, num2); + num2 = Handles.SizeSlider(position, -vector, num2); + num = Handles.SizeSlider(position, vector2, num); + num = Handles.SizeSlider(position, -vector2, num); + if ((Tools.current != Tool.Move && Tools.current != Tool.Scale) || Tools.pivotRotation != PivotRotation.Local) + { + Handles.DrawLine(position, position + b); + } + size.x = 2f * num; + size.y = 2f * num2; + return size; + } + public static Quaternion DoRotationHandle(Quaternion rotation, Vector3 position) + { + float handleSize = HandleUtility.GetHandleSize(position); + Color color = Handles.color; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.right, handleSize, true, SnapSettings.rotation); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.up, handleSize, true, SnapSettings.rotation); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.forward, handleSize, true, SnapSettings.rotation); + if (!flag) + { + Handles.color = Handles.centerColor; + rotation = Handles.Disc(rotation, position, Camera.current.transform.forward, handleSize * 1.1f, false, 0f); + rotation = Handles.FreeRotateHandle(rotation, position, handleSize); + } + Handles.color = color; + return rotation; + } + public static Vector3 DoScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) + { + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.x = Handles.ScaleSlider(scale.x, position, rotation * Vector3.right, rotation, size, SnapSettings.scale); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.y = Handles.ScaleSlider(scale.y, position, rotation * Vector3.up, rotation, size, SnapSettings.scale); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.z = Handles.ScaleSlider(scale.z, position, rotation * Vector3.forward, rotation, size, SnapSettings.scale); + Handles.color = Handles.centerColor; + EditorGUI.BeginChangeCheck(); + float num = Handles.ScaleValueHandle(scale.x, position, rotation, size, new Handles.DrawCapFunction(Handles.CubeCap), SnapSettings.scale); + if (EditorGUI.EndChangeCheck()) + { + float num2 = num / scale.x; + scale.x = num; + scale.y *= num2; + scale.z *= num2; + } + return scale; + } + internal static float DoSimpleRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool hemisphere) + { + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + bool changed = GUI.changed; + GUI.changed = false; + radius = Handles.SizeSlider(position, vector, radius); + if (!hemisphere) + { + radius = Handles.SizeSlider(position, -vector, radius); + } + if (GUI.changed) + { + radius = Mathf.Max(0f, radius); + } + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + radius = Handles.SizeSlider(position, vector2, radius); + radius = Handles.SizeSlider(position, -vector2, radius); + radius = Handles.SizeSlider(position, vector3, radius); + radius = Handles.SizeSlider(position, -vector3, radius); + if (GUI.changed) + { + radius = Mathf.Max(0f, radius); + } + GUI.changed |= changed; + if (radius > 0f) + { + Handles.DrawWireDisc(position, vector, radius); + Handles.DrawWireArc(position, vector2, -vector3, (float)((!hemisphere) ? 360 : 180), radius); + Handles.DrawWireArc(position, vector3, vector2, (float)((!hemisphere) ? 360 : 180), radius); + } + return radius; + } + public static Vector3 PositionHandle(Vector3 position, Quaternion rotation) + { + return Handles.DoPositionHandle(position, rotation); + } + public static Quaternion RotationHandle(Quaternion rotation, Vector3 position) + { + return Handles.DoRotationHandle(rotation, position); + } + public static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) + { + return Handles.DoScaleHandle(scale, position, rotation, size); + } + public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) + { + return Handles.DoRadiusHandle(rotation, position, radius, handlesOnly); + } + public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius) + { + return Handles.DoRadiusHandle(rotation, position, radius, false); + } + internal static Vector2 ConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) + { + return Handles.DoConeHandle(rotation, position, angleAndRange, angleScale, rangeScale, handlesOnly); + } + internal static Vector3 ConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) + { + return Handles.DoConeFrustrumHandle(rotation, position, radiusAngleRange); + } + public static Vector3 Slider(Vector3 position, Vector3 direction) + { + return Handles.Slider(position, direction, HandleUtility.GetHandleSize(position), new Handles.DrawCapFunction(Handles.ArrowCap), -1f); + } + public static Vector3 Slider(Vector3 position, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_SliderHash, FocusType.Keyboard); + return Slider1D.Do(controlID, position, direction, size, drawFunc, snap); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + return UnityEditorInternal.Slider2D.Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); + return UnityEditorInternal.Slider2D.Do(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(id, handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + return UnityEditorInternal.Slider2D.Do(id, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap) + { + bool drawHelper = false; + return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap, [DefaultValue("false")] bool drawHelper) + { + int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); + return Handles.Slider2D(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); + } + public static Quaternion FreeRotateHandle(Quaternion rotation, Vector3 position, float size) + { + int controlID = GUIUtility.GetControlID(Handles.s_FreeRotateHandleHash, FocusType.Keyboard); + return FreeRotate.Do(controlID, rotation, position, size); + } + public static Vector3 FreeMoveHandle(Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.DrawCapFunction capFunc) + { + int controlID = GUIUtility.GetControlID(Handles.s_FreeMoveHandleHash, FocusType.Keyboard); + return FreeMove.Do(controlID, position, rotation, size, snap, capFunc); + } + public static float ScaleSlider(float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_ScaleSliderHash, FocusType.Keyboard); + return SliderScale.DoAxis(controlID, scale, position, direction, rotation, size, snap); + } + public static float ScaleValueHandle(float value, Vector3 position, Quaternion rotation, float size, Handles.DrawCapFunction capFunc, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_ScaleValueHandleHash, FocusType.Keyboard); + return SliderScale.DoCenter(controlID, value, position, rotation, size, capFunc, snap); + } + public static Quaternion Disc(Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_DiscHash, FocusType.Keyboard); + return UnityEditorInternal.Disc.Do(controlID, rotation, position, axis, size, cutoffPlane, snap); + } + public static bool Button(Vector3 position, Quaternion direction, float size, float pickSize, Handles.DrawCapFunction capFunc) + { + int controlID = GUIUtility.GetControlID(Handles.s_ButtonHash, FocusType.Passive); + return UnityEditorInternal.Button.Do(controlID, position, direction, size, pickSize, capFunc); + } + internal static void SetupIgnoreRaySnapObjects() + { + HandleUtility.ignoreRaySnapObjects = Selection.GetTransforms((SelectionMode)10); + } + public static float SnapValue(float val, float snap) + { + if (EditorGUI.actionKey && snap > 0f) + { + return Mathf.Round(val / snap) * snap; + } + return val; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawCameraWithGrid(Camera cam, int renderMode, ref DrawGridParameters gridParam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawCamera(Camera cam, int renderMode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_FinishDrawingCamera(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_ClearCamera(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Internal_SetCurrentCamera(Camera cam); + internal static void SetSceneViewColors(Color wire, Color wireOverlay, Color active, Color selected) + { + Handles.INTERNAL_CALL_SetSceneViewColors(ref wire, ref wireOverlay, ref active, ref selected); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetSceneViewColors(ref Color wire, ref Color wireOverlay, ref Color active, ref Color selected); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraFx(Camera cam, bool fx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraFlares(Camera cam, bool flares); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraSkybox(Camera cam, bool skybox); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetCameraOnlyDrawMesh(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetupCamera(Camera cam); + internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, float radius) + { + Color color = Handles.color; + Color color2 = color; + color.a *= Handles.backfaceAlphaMultiplier; + Handles.color = color; + Handles.DrawWireDisc(position, axis, radius); + Handles.color = color2; + } + internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, Vector3 from, float degrees, float radius) + { + Handles.DrawWireArc(position, axis, from, degrees, radius); + Color color = Handles.color; + Color color2 = color; + color.a *= Handles.backfaceAlphaMultiplier; + Handles.color = color; + Handles.DrawWireArc(position, axis, from, degrees - 360f, radius); + Handles.color = color2; + } + internal static Matrix4x4 StartCapDraw(Vector3 position, Quaternion rotation, float size) + { + Shader.SetGlobalColor("_HandleColor", Handles.realHandleColor); + Shader.SetGlobalFloat("_HandleSize", size); + Matrix4x4 matrix4x = Handles.matrix * Matrix4x4.TRS(position, rotation, Vector3.one); + Shader.SetGlobalMatrix("_ObjectToWorld", matrix4x); + HandleUtility.handleMaterial.SetPass(0); + return matrix4x; + } + public static void CubeCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Graphics.DrawMeshNow(Handles.s_CubeMesh, Handles.StartCapDraw(position, rotation, size)); + } + public static void SphereCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Graphics.DrawMeshNow(Handles.s_SphereMesh, Handles.StartCapDraw(position, rotation, size)); + } + public static void ConeCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Graphics.DrawMeshNow(Handles.s_ConeMesh, Handles.StartCapDraw(position, rotation, size)); + } + public static void CylinderCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Graphics.DrawMeshNow(Handles.s_CylinderMesh, Handles.StartCapDraw(position, rotation, size)); + } + public static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.RectangleCap(controlID, position, rotation, new Vector2(size, size)); + } + internal static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, Vector2 size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Vector3 b = rotation * new Vector3(size.x, 0f, 0f); + Vector3 b2 = rotation * new Vector3(0f, size.y, 0f); + Handles.s_RectangleCapPointsCache[0] = position + b + b2; + Handles.s_RectangleCapPointsCache[1] = position + b - b2; + Handles.s_RectangleCapPointsCache[2] = position - b - b2; + Handles.s_RectangleCapPointsCache[3] = position - b + b2; + Handles.s_RectangleCapPointsCache[4] = position + b + b2; + Handles.DrawPolyLine(Handles.s_RectangleCapPointsCache); + } + public static void SelectionFrame(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Handles.StartCapDraw(position, rotation, size); + Vector3 b = rotation * new Vector3(size, 0f, 0f); + Vector3 b2 = rotation * new Vector3(0f, size, 0f); + Vector3 vector = position - b + b2; + Vector3 vector2 = position + b + b2; + Vector3 vector3 = position + b - b2; + Vector3 vector4 = position - b - b2; + Handles.DrawLine(vector, vector2); + Handles.DrawLine(vector2, vector3); + Handles.DrawLine(vector3, vector4); + Handles.DrawLine(vector4, vector); + } + public static void DotCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + position = Handles.matrix.MultiplyPoint(position); + Vector3 b = Camera.current.transform.right * size; + Vector3 b2 = Camera.current.transform.up * size; + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.99f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(7); + GL.Color(c); + GL.Vertex(position + b + b2); + GL.Vertex(position + b - b2); + GL.Vertex(position - b - b2); + GL.Vertex(position - b + b2); + GL.End(); + } + public static void CircleCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Handles.StartCapDraw(position, rotation, size); + Vector3 normal = rotation * new Vector3(0f, 0f, 1f); + Handles.DrawWireDisc(position, normal, size); + } + public static void ArrowCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Vector3 vector = rotation * Vector3.forward; + Handles.ConeCap(controlID, position + vector * size, Quaternion.LookRotation(vector), size * 0.2f); + Handles.DrawLine(position, position + vector * size * 0.9f); + } + [Obsolete("DrawCylinder has been renamed to CylinderCap.")] + public static void DrawCylinder(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.CylinderCap(controlID, position, rotation, size); + } + [Obsolete("DrawSphere has been renamed to SphereCap.")] + public static void DrawSphere(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.SphereCap(controlID, position, rotation, size); + } + [Obsolete("DrawRectangle has been renamed to RectangleCap.")] + public static void DrawRectangle(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.RectangleCap(controlID, position, rotation, size); + } + [Obsolete("DrawCube has been renamed to CubeCap.")] + public static void DrawCube(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.CubeCap(controlID, position, rotation, size); + } + [Obsolete("DrawArrow has been renamed to ArrowCap.")] + public static void DrawArrow(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.ArrowCap(controlID, position, rotation, size); + } + [Obsolete("DrawCone has been renamed to ConeCap.")] + public static void DrawCone(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.ConeCap(controlID, position, rotation, size); + } + public static void DrawLine(Vector3 p1, Vector3 p2) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + GL.Vertex(p1); + GL.Vertex(p2); + GL.End(); + GL.PopMatrix(); + } + public static void DrawPolyLine(params Vector3[] points) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + for (int i = 1; i < points.Length; i++) + { + GL.Vertex(points[i]); + GL.Vertex(points[i - 1]); + } + GL.End(); + GL.PopMatrix(); + } + public static void DrawDottedLine(Vector3 p1, Vector3 p2, float screenSpaceSize) + { + Camera current = Camera.current; + if (!current || Event.current.type != EventType.Repaint) + { + return; + } + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + Vector3 vector = current.WorldToScreenPoint(p1); + Vector3 vector2 = current.WorldToScreenPoint(p2); + float num = Vector2.Distance(vector, vector2); + int num2 = Mathf.CeilToInt(num / screenSpaceSize); + num2 = Mathf.Min(num2, 1000); + screenSpaceSize = num / (float)num2; + for (int i = 0; i < num2; i += 2) + { + GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)i * screenSpaceSize / num))); + GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)(i + 1) * screenSpaceSize / num))); + } + GL.End(); + GL.PopMatrix(); + } + internal static void DrawAAPolyLine(Color[] colors, Vector3[] points) + { + Handles.DoDrawAAPolyLine(colors, points, -1, null, 2f, 0.75f); + } + internal static void DrawAAPolyLine(float width, Color[] colors, Vector3[] points) + { + Handles.DoDrawAAPolyLine(colors, points, -1, null, width, 0.75f); + } + public static void DrawAAPolyLine(params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, null, 2f, 0.75f); + } + public static void DrawAAPolyLine(float width, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, null, width, 0.75f); + } + public static void DrawAAPolyLine(Texture2D lineTex, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, lineTex, (float)(lineTex.height / 2), 0.99f); + } + public static void DrawAAPolyLine(float width, int actualNumberOfPoints, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, actualNumberOfPoints, null, width, 0.75f); + } + public static void DrawAAPolyLine(Texture2D lineTex, float width, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, lineTex, width, 0.99f); + } + private static void DoDrawAAPolyLine(Color[] colors, Vector3[] points, int actualNumberOfPoints, Texture2D lineTex, float width, float alpha) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + Color color = new Color(1f, 1f, 1f, alpha); + if (colors != null) + { + for (int i = 0; i < colors.Length; i++) + { + colors[i] *= color; + } + } + else + { + color *= Handles.s_Color; + } + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + Handles.Internal_DrawAAPolyLine(colors, points, color, actualNumberOfPoints, lineTex, width); + GL.PopMatrix(); + } + private static void Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width) + { + Handles.INTERNAL_CALL_Internal_DrawAAPolyLine(colors, points, ref defaultColor, actualNumberOfPoints, texture, width); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, ref Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width); + public static void DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + Handles.Internal_DrawBezier(startPosition, endPosition, startTangent, endTangent, color, texture, width); + GL.PopMatrix(); + } + private static void Internal_DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) + { + Handles.INTERNAL_CALL_Internal_DrawBezier(ref startPosition, ref endPosition, ref startTangent, ref endTangent, ref color, texture, width); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawBezier(ref Vector3 startPosition, ref Vector3 endPosition, ref Vector3 startTangent, ref Vector3 endTangent, ref Color color, Texture2D texture, float width); + public static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) + { + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + Handles.DrawWireArc(center, normal, from, 360f, radius); + } + public static void DrawWireArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + Vector3[] array = new Vector3[60]; + Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); + Handles.DrawPolyLine(array); + } + public static void DrawSolidRectangleWithOutline(Vector3[] verts, Color faceColor, Color outlineColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + if (faceColor.a > 0f) + { + Color c = faceColor * Handles.color; + GL.Begin(4); + for (int i = 0; i < 2; i++) + { + GL.Color(c); + GL.Vertex(verts[i * 2]); + GL.Vertex(verts[i * 2 + 1]); + GL.Vertex(verts[(i * 2 + 2) % 4]); + GL.Vertex(verts[i * 2]); + GL.Vertex(verts[(i * 2 + 2) % 4]); + GL.Vertex(verts[i * 2 + 1]); + } + GL.End(); + } + if (outlineColor.a > 0f) + { + Color c2 = outlineColor * Handles.color; + GL.Begin(1); + GL.Color(c2); + for (int j = 0; j < 4; j++) + { + GL.Vertex(verts[j]); + GL.Vertex(verts[(j + 1) % 4]); + } + GL.End(); + } + GL.PopMatrix(); + } + public static void DrawSolidDisc(Vector3 center, Vector3 normal, float radius) + { + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + Handles.DrawSolidArc(center, normal, from, 360f, radius); + } + public static void DrawSolidArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Vector3[] array = new Vector3[60]; + Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); + Shader.SetGlobalColor("_HandleColor", Handles.color * new Color(1f, 1f, 1f, 0.5f)); + Shader.SetGlobalFloat("_HandleSize", 1f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(4); + for (int i = 1; i < array.Length; i++) + { + GL.Color(Handles.color); + GL.Vertex(center); + GL.Vertex(array[i - 1]); + GL.Vertex(array[i]); + GL.Vertex(center); + GL.Vertex(array[i]); + GL.Vertex(array[i - 1]); + } + GL.End(); + GL.PopMatrix(); + } + internal static void SetDiscSectionPoints(Vector3[] dest, int count, Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + from.Normalize(); + Quaternion rotation = Quaternion.AngleAxis(angle / (float)(count - 1), normal); + Vector3 vector = from * radius; + for (int i = 0; i < count; i++) + { + dest[i] = center + vector; + vector = rotation * vector; + } + } + internal static void Init() + { + if (!Handles.s_CubeMesh) + { + GameObject gameObject = (GameObject)EditorGUIUtility.Load("SceneView/HandlesGO.fbx"); + if (!gameObject) + { + Debug.Log("ARGH - We couldn't find SceneView/HandlesGO.fbx"); + } + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + string name = transform.name; + switch (name) + { + case "Cube": + Handles.s_CubeMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + break; + case "Sphere": + Handles.s_SphereMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + break; + case "Cone": + Handles.s_ConeMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + break; + case "Cylinder": + Handles.s_CylinderMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + break; + case "Quad": + Handles.s_QuadMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + break; + } + } + if (Application.platform == RuntimePlatform.WindowsEditor) + { + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Bold.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small Bold.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Big.ttf")); + } + } + } + private static void ReplaceFontForWindows(Font font) + { + if (font.name.Contains("Bold")) + { + font.fontNames = new string[] + { + "Verdana Bold", + "Tahoma Bold" + }; + } + else + { + font.fontNames = new string[] + { + "Verdana", + "Tahoma" + }; + } + font.hideFlags = HideFlags.HideAndDontSave; + } + public static void Label(Vector3 position, string text) + { + Handles.Label(position, EditorGUIUtility.TempContent(text), GUI.skin.label); + } + public static void Label(Vector3 position, Texture image) + { + Handles.Label(position, EditorGUIUtility.TempContent(image), GUI.skin.label); + } + public static void Label(Vector3 position, GUIContent content) + { + Handles.Label(position, content, GUI.skin.label); + } + public static void Label(Vector3 position, string text, GUIStyle style) + { + Handles.Label(position, EditorGUIUtility.TempContent(text), style); + } + public static void Label(Vector3 position, GUIContent content, GUIStyle style) + { + Handles.BeginGUI(); + GUI.Label(HandleUtility.WorldPointToSizedRect(position, content, style), content, style); + Handles.EndGUI(); + } + internal static Rect GetCameraRect(Rect position) + { + Rect rect = GUIClip.Unclip(position); + Rect result = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + return result; + } + public static Vector2 GetMainGameViewSize() + { + return GameView.GetSizeOfMainGameView(); + } + public static void ClearCamera(Rect position, Camera camera) + { + Event current = Event.current; + if (camera.targetTexture == null) + { + Rect rect = GUIClip.Unclip(position); + Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + camera.pixelRect = pixelRect; + } + else + { + camera.rect = new Rect(0f, 0f, 1f, 1f); + } + if (current.type == EventType.Repaint) + { + Handles.Internal_ClearCamera(camera); + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } + } + internal static void DrawCameraImpl(Rect position, Camera camera, DrawCameraMode drawMode, bool drawGrid, DrawGridParameters gridParam, bool finish) + { + Event current = Event.current; + if (current.type == EventType.Repaint) + { + if (camera.targetTexture == null) + { + Rect rect = GUIClip.Unclip(position); + camera.pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + } + else + { + camera.rect = new Rect(0f, 0f, 1f, 1f); + } + if (drawMode == DrawCameraMode.Normal) + { + RenderTexture targetTexture = camera.targetTexture; + camera.targetTexture = RenderTexture.active; + camera.Render(); + camera.targetTexture = targetTexture; + } + else + { + if (drawGrid) + { + Handles.Internal_DrawCameraWithGrid(camera, (int)drawMode, ref gridParam); + } + else + { + Handles.Internal_DrawCamera(camera, (int)drawMode); + } + if (finish) + { + Handles.Internal_FinishDrawingCamera(camera); + } + } + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } + } + internal static void DrawCamera(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) + { + Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, true); + } + internal static void DrawCameraStep1(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) + { + Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, false); + } + internal static void DrawCameraStep2(Camera camera, DrawCameraMode drawMode) + { + if (Event.current.type == EventType.Repaint && drawMode != DrawCameraMode.Normal) + { + Handles.Internal_FinishDrawingCamera(camera); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EmitGUIGeometryForCamera(Camera source, Camera dest); + [ExcludeFromDocs] + public static void DrawCamera(Rect position, Camera camera) + { + DrawCameraMode drawMode = DrawCameraMode.Normal; + Handles.DrawCamera(position, camera, drawMode); + } + public static void DrawCamera(Rect position, Camera camera, [DefaultValue("DrawCameraMode.Normal")] DrawCameraMode drawMode) + { + Handles.DrawCameraImpl(position, camera, drawMode, false, default(DrawGridParameters), true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetCameraFilterMode(Camera camera, Handles.FilterMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Handles.FilterMode GetCameraFilterMode(Camera camera); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DrawCameraFade(Camera camera, float fade); + public static void SetCamera(Camera camera) + { + if (Event.current.type == EventType.Repaint) + { + Handles.Internal_SetupCamera(camera); + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } + } + public static void SetCamera(Rect position, Camera camera) + { + Rect rect = GUIClip.Unclip(position); + Event current = Event.current; + Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + camera.pixelRect = pixelRect; + if (current.type == EventType.Repaint) + { + Handles.Internal_SetupCamera(camera); + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } + } + public static void BeginGUI() + { + if (Camera.current && Event.current.type == EventType.Repaint) + { + GUIClip.Reapply(); + } + } + [Obsolete("Please use BeginGUI() with GUILayout.BeginArea(position) / GUILayout.EndArea()")] + public static void BeginGUI(Rect position) + { + GUILayout.BeginArea(position); + } + public static void EndGUI() + { + Camera current = Camera.current; + if (current && Event.current.type == EventType.Repaint) + { + Handles.Internal_SetupCamera(current); + } + } + internal static void ShowStaticLabelIfNeeded(Vector3 pos) + { + if (!Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects)) + { + Handles.color = Color.white; + GUIStyle gUIStyle = "SC ViewAxisLabel"; + gUIStyle.alignment = TextAnchor.MiddleLeft; + gUIStyle.fixedWidth = 0f; + Handles.BeginGUI(); + Rect position = HandleUtility.WorldPointToSizedRect(pos, EditorGUIUtility.TempContent("Static"), gUIStyle); + position.x += 10f; + position.y += 10f; + GUI.Label(position, EditorGUIUtility.TempContent("Static"), gUIStyle); + Handles.EndGUI(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/HeaderDrawer.cs b/UnityEditor/UnityEditor/HeaderDrawer.cs new file mode 100644 index 00000000..3d84ed24 --- /dev/null +++ b/UnityEditor/UnityEditor/HeaderDrawer.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomPropertyDrawer(typeof(HeaderAttribute))] + internal sealed class HeaderDrawer : DecoratorDrawer + { + public override void OnGUI(Rect position) + { + position.y += 8f; + position = EditorGUI.IndentedRect(position); + GUI.Label(position, (base.attribute as HeaderAttribute).header, EditorStyles.boldLabel); + } + public override float GetHeight() + { + return 24f; + } + } +} diff --git a/UnityEditor/UnityEditor/HeapshotReader.cs b/UnityEditor/UnityEditor/HeapshotReader.cs new file mode 100644 index 00000000..fac013ff --- /dev/null +++ b/UnityEditor/UnityEditor/HeapshotReader.cs @@ -0,0 +1,343 @@ +using System; +using System.Collections.Generic; +using System.IO; +namespace UnityEditor +{ + internal class HeapshotReader + { + public enum Tag + { + Type = 1, + Object, + UnityObjects, + EndOfFile = 255 + } + public enum ObjectType + { + None, + Root, + Managed, + UnityRoot + } + public class FieldInfo + { + public string name = string.Empty; + public FieldInfo() + { + } + public FieldInfo(string name) + { + this.name = name; + } + } + public class TypeInfo + { + public string name = string.Empty; + public Dictionary fields = new Dictionary(); + public TypeInfo() + { + } + public TypeInfo(string name) + { + this.name = name; + } + } + public class ReferenceInfo + { + public uint code; + public HeapshotReader.ObjectInfo referencedObject; + public HeapshotReader.FieldInfo fieldInfo; + public ReferenceInfo() + { + } + public ReferenceInfo(HeapshotReader.ObjectInfo refObj, HeapshotReader.FieldInfo field) + { + this.referencedObject = refObj; + this.fieldInfo = field; + } + } + public class BackReferenceInfo + { + public HeapshotReader.ObjectInfo parentObject; + public HeapshotReader.FieldInfo fieldInfo; + } + public class ObjectInfo + { + public uint code; + public HeapshotReader.TypeInfo typeInfo; + public uint size; + public List references = new List(); + public List inverseReferences = new List(); + public HeapshotReader.ObjectType type; + public ObjectInfo() + { + } + public ObjectInfo(HeapshotReader.TypeInfo typeInfo, uint size) + { + this.typeInfo = typeInfo; + this.size = size; + } + public ObjectInfo(HeapshotReader.TypeInfo typeInfo, uint size, HeapshotReader.ObjectType type) + { + this.typeInfo = typeInfo; + this.size = size; + this.type = type; + } + } + private const uint kMagicNumber = 1319894481u; + private const int kLogVersion = 6; + private const string kLogFileLabel = "heap-shot logfile"; + private Dictionary types = new Dictionary(); + private Dictionary objects = new Dictionary(); + private List roots = new List(); + private List allObjects = new List(); + private List allTypes = new List(); + private HeapshotReader.ObjectInfo kUnmanagedObject = new HeapshotReader.ObjectInfo(new HeapshotReader.TypeInfo("Unmanaged"), 0u); + private HeapshotReader.ObjectInfo kUnity = new HeapshotReader.ObjectInfo(new HeapshotReader.TypeInfo(""), 0u, HeapshotReader.ObjectType.UnityRoot); + public List Roots + { + get + { + return this.roots; + } + } + public List Objects + { + get + { + return this.allObjects; + } + } + public List Types + { + get + { + return this.allTypes; + } + } + public List GetObjectsOfType(string name) + { + List list = new List(); + foreach (HeapshotReader.ObjectInfo current in this.allObjects) + { + if (current.typeInfo.name == name) + { + list.Add(current); + } + } + return list; + } + public bool Open(string fileName) + { + this.types.Clear(); + this.objects.Clear(); + this.roots.Clear(); + this.allObjects.Clear(); + this.allTypes.Clear(); + Stream stream; + try + { + stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + bool result = false; + return result; + } + BinaryReader binaryReader; + try + { + binaryReader = new BinaryReader(stream); + } + catch (Exception ex2) + { + Console.WriteLine(ex2.Message); + stream.Close(); + bool result = false; + return result; + } + this.ReadHeader(binaryReader); + while (this.ReadData(binaryReader)) + { + } + this.ResolveReferences(); + this.ResolveInverseReferences(); + this.ResolveRoots(); + binaryReader.Close(); + stream.Close(); + return true; + } + private void ReadHeader(BinaryReader reader) + { + uint num = reader.ReadUInt32(); + if (num != 1319894481u) + { + throw new Exception(string.Format("Bad magic number: expected {0}, found {1}", 1319894481u, num)); + } + int num2 = reader.ReadInt32(); + string text = reader.ReadString(); + if (!(text == "heap-shot logfile")) + { + throw new Exception("Unknown file label in heap-shot outfile"); + } + int num3 = 6; + if (num2 != num3) + { + throw new Exception(string.Format("Version error in {0}: expected {1}, found {2}", text, num3, num2)); + } + reader.ReadUInt32(); + reader.ReadUInt32(); + reader.ReadUInt32(); + reader.ReadUInt32(); + } + private bool ReadData(BinaryReader reader) + { + HeapshotReader.Tag tag = (HeapshotReader.Tag)reader.ReadByte(); + HeapshotReader.Tag tag2 = tag; + switch (tag2) + { + case HeapshotReader.Tag.Type: + this.ReadType(reader); + break; + case HeapshotReader.Tag.Object: + this.ReadObject(reader); + break; + case HeapshotReader.Tag.UnityObjects: + this.ReadUnityObjects(reader); + break; + default: + if (tag2 != HeapshotReader.Tag.EndOfFile) + { + throw new Exception("Unknown tag! " + tag); + } + return false; + } + return true; + } + private void ReadType(BinaryReader reader) + { + uint num = reader.ReadUInt32(); + HeapshotReader.TypeInfo typeInfo = new HeapshotReader.TypeInfo(); + typeInfo.name = reader.ReadString(); + uint key; + while ((key = reader.ReadUInt32()) != 0u) + { + HeapshotReader.FieldInfo fieldInfo = new HeapshotReader.FieldInfo(); + fieldInfo.name = reader.ReadString(); + typeInfo.fields[key] = fieldInfo; + } + if (this.types.ContainsKey(num)) + { + throw new Exception(string.Format("Type info for object {0} was already loaded!!!", num)); + } + this.types[num] = typeInfo; + this.allTypes.Add(typeInfo); + } + private void ReadObject(BinaryReader reader) + { + uint num = reader.ReadUInt32(); + uint num2 = reader.ReadUInt32(); + HeapshotReader.ObjectInfo objectInfo = new HeapshotReader.ObjectInfo(); + objectInfo.code = num; + objectInfo.size = reader.ReadUInt32(); + if (!this.types.ContainsKey(num2)) + { + throw new Exception(string.Format("Failed to find type info {0} for object {1}!!!", num2, num)); + } + objectInfo.typeInfo = this.types[num2]; + uint code; + while ((code = reader.ReadUInt32()) != 0u) + { + HeapshotReader.ReferenceInfo referenceInfo = new HeapshotReader.ReferenceInfo(); + referenceInfo.code = code; + uint num3 = reader.ReadUInt32(); + if (num3 == 0u) + { + referenceInfo.fieldInfo = null; + } + else + { + if (objectInfo.typeInfo.fields.ContainsKey(num3)) + { + referenceInfo.fieldInfo = objectInfo.typeInfo.fields[num3]; + } + else + { + referenceInfo.fieldInfo = null; + } + } + objectInfo.references.Add(referenceInfo); + } + if (this.objects.ContainsKey(num)) + { + throw new Exception(string.Format("Object {0} was already loaded?!", num)); + } + objectInfo.type = ((num != num2) ? HeapshotReader.ObjectType.Managed : HeapshotReader.ObjectType.Root); + this.objects[num] = objectInfo; + this.allObjects.Add(objectInfo); + } + private void ReadUnityObjects(BinaryReader reader) + { + uint key; + while ((key = reader.ReadUInt32()) != 0u) + { + if (this.objects.ContainsKey(key)) + { + HeapshotReader.BackReferenceInfo backReferenceInfo = new HeapshotReader.BackReferenceInfo(); + backReferenceInfo.parentObject = this.kUnity; + backReferenceInfo.fieldInfo = new HeapshotReader.FieldInfo(this.objects[key].typeInfo.name); + this.objects[key].inverseReferences.Add(backReferenceInfo); + } + } + } + private void ResolveReferences() + { + foreach (KeyValuePair current in this.objects) + { + foreach (HeapshotReader.ReferenceInfo current2 in current.Value.references) + { + if (!this.objects.ContainsKey(current2.code)) + { + current2.referencedObject = this.kUnmanagedObject; + } + else + { + current2.referencedObject = this.objects[current2.code]; + if (current2.fieldInfo == null) + { + current2.fieldInfo = new HeapshotReader.FieldInfo(); + current2.fieldInfo.name = current2.referencedObject.typeInfo.name; + } + } + } + } + } + private void ResolveInverseReferences() + { + foreach (KeyValuePair current in this.objects) + { + foreach (HeapshotReader.ReferenceInfo current2 in current.Value.references) + { + HeapshotReader.BackReferenceInfo backReferenceInfo = new HeapshotReader.BackReferenceInfo(); + backReferenceInfo.parentObject = current.Value; + backReferenceInfo.fieldInfo = current2.fieldInfo; + current2.referencedObject.inverseReferences.Add(backReferenceInfo); + } + } + } + private void ResolveRoots() + { + foreach (KeyValuePair current in this.objects) + { + if (current.Value.type == HeapshotReader.ObjectType.Root) + { + foreach (HeapshotReader.ReferenceInfo current2 in current.Value.references) + { + this.roots.Add(current2); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/HeapshotWindow.cs b/UnityEditor/UnityEditor/HeapshotWindow.cs new file mode 100644 index 00000000..edd62542 --- /dev/null +++ b/UnityEditor/UnityEditor/HeapshotWindow.cs @@ -0,0 +1,544 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class HeapshotWindow : EditorWindow + { + public class HeapshotUIObject + { + private string name; + private HeapshotReader.ObjectInfo obj; + private List children = new List(); + private bool inverseReference; + private bool isDummyObject; + public bool HasChildren + { + get + { + return (!this.inverseReference) ? (this.obj.references.Count > 0) : (this.obj.inverseReferences.Count > 0); + } + } + public bool IsExpanded + { + get + { + return this.HasChildren && this.children.Count > 0; + } + } + public string Name + { + get + { + return this.name; + } + } + public uint Code + { + get + { + return this.obj.code; + } + } + public uint Size + { + get + { + return this.obj.size; + } + } + public int ReferenceCount + { + get + { + return (!this.inverseReference) ? this.obj.references.Count : this.obj.inverseReferences.Count; + } + } + public int InverseReferenceCount + { + get + { + return (!this.inverseReference) ? this.obj.inverseReferences.Count : this.obj.references.Count; + } + } + public bool IsDummyObject + { + get + { + return this.isDummyObject; + } + set + { + this.isDummyObject = value; + } + } + public string TypeName + { + get + { + return this.obj.typeInfo.name; + } + } + public HeapshotReader.ObjectInfo ObjectInfo + { + get + { + return this.obj; + } + } + public List Children + { + get + { + if (this.HasChildren && this.IsExpanded) + { + return this.children; + } + return null; + } + } + public HeapshotUIObject(string name, HeapshotReader.ObjectInfo refObject, bool inverseReference) + { + this.name = name; + this.obj = refObject; + this.inverseReference = inverseReference; + } + public void Expand() + { + if (this.IsExpanded) + { + return; + } + if (this.HasChildren) + { + if (this.inverseReference) + { + foreach (HeapshotReader.BackReferenceInfo current in this.obj.inverseReferences) + { + this.children.Add(new HeapshotWindow.HeapshotUIObject(current.fieldInfo.name, current.parentObject, true)); + } + } + else + { + foreach (HeapshotReader.ReferenceInfo current2 in this.obj.references) + { + this.children.Add(new HeapshotWindow.HeapshotUIObject(current2.fieldInfo.name, current2.referencedObject, false)); + } + } + } + } + public void Collapse() + { + if (!this.IsExpanded) + { + return; + } + this.children.Clear(); + } + } + internal class UIStyles + { + public GUIStyle background = "OL Box"; + public GUIStyle header = "OL title"; + public GUIStyle rightHeader = "OL title TextRight"; + public GUIStyle entryEven = "OL EntryBackEven"; + public GUIStyle entryOdd = "OL EntryBackOdd"; + public GUIStyle numberLabel = "OL Label"; + public GUIStyle foldout = "IN foldout"; + } + internal class UIOptions + { + public const float height = 16f; + public const float foldoutWidth = 14f; + public const float tabWidth = 50f; + } + private delegate void OnSelect(HeapshotWindow.HeapshotUIObject o); + private delegate void DelegateReceivedHeapshot(string fileName); + private const string heapshotExtension = ".heapshot"; + private HeapshotReader heapshotReader; + private List heapshotFiles = new List(); + private int itemIndex = -1; + private Rect guiRect; + private int selectedItem = -1; + private int currentTab; + private string lastOpenedHeapshotFile = string.Empty; + private string lastOpenedProfiler = string.Empty; + private static HeapshotWindow.DelegateReceivedHeapshot onReceivedHeapshot; + private List hsRoots = new List(); + private List hsAllObjects = new List(); + private List hsBackTraceObjects = new List(); + private Vector2 leftViewScrollPosition = Vector2.zero; + private Vector2 rightViewScrollPosition = Vector2.zero; + private static HeapshotWindow.UIStyles ms_Styles; + private SplitterState viewSplit = new SplitterState(new float[] + { + 50f, + 50f + }, null, null); + private string[] titleNames = new string[] + { + "Field Name", + "Type", + "Pointer", + "Size", + "References/Referenced" + }; + private SplitterState titleSplit1 = new SplitterState(new float[] + { + 30f, + 25f, + 15f, + 15f, + 15f + }, new int[] + { + 200, + 200, + 50, + 50, + 50 + }, null); + private SplitterState titleSplit2 = new SplitterState(new float[] + { + 30f, + 25f, + 15f, + 15f, + 15f + }, new int[] + { + 200, + 200, + 50, + 50, + 50 + }, null); + private int selectedHeapshot = -1; + private int[] connectionGuids; + private string HeapshotPath + { + get + { + return Application.dataPath + "/../Heapshots"; + } + } + private static HeapshotWindow.UIStyles Styles + { + get + { + HeapshotWindow.UIStyles arg_17_0; + if ((arg_17_0 = HeapshotWindow.ms_Styles) == null) + { + arg_17_0 = (HeapshotWindow.ms_Styles = new HeapshotWindow.UIStyles()); + } + return arg_17_0; + } + } + private static void Init() + { + EditorWindow window = EditorWindow.GetWindow(typeof(HeapshotWindow)); + window.title = "Mono heapshot"; + } + private static void EventHeapShotReceived(string name) + { + Debug.Log("Received " + name); + if (HeapshotWindow.onReceivedHeapshot != null) + { + HeapshotWindow.onReceivedHeapshot(name); + } + } + private void OnReceivedHeapshot(string name) + { + this.SearchForHeapShots(); + this.OpenHeapshot(name); + } + private void SearchForHeapShots() + { + this.heapshotFiles.Clear(); + if (!Directory.Exists(this.HeapshotPath)) + { + return; + } + string[] files = Directory.GetFiles(this.HeapshotPath, "*.heapshot"); + this.selectedHeapshot = -1; + string[] array = files; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + string text2 = text.Substring(text.LastIndexOf("\\") + 1); + text2 = text2.Substring(0, text2.IndexOf(".heapshot")); + this.heapshotFiles.Add(text2); + } + if (this.heapshotFiles.Count > 0) + { + this.selectedHeapshot = this.heapshotFiles.Count - 1; + } + } + private void OnEnable() + { + HeapshotWindow.onReceivedHeapshot = new HeapshotWindow.DelegateReceivedHeapshot(this.OnReceivedHeapshot); + } + private void OnDisable() + { + HeapshotWindow.onReceivedHeapshot = null; + } + private void OnFocus() + { + this.SearchForHeapShots(); + } + private void RefreshHeapshotUIObjects() + { + this.hsRoots.Clear(); + this.hsAllObjects.Clear(); + foreach (HeapshotReader.ReferenceInfo current in this.heapshotReader.Roots) + { + string name = current.fieldInfo.name; + this.hsRoots.Add(new HeapshotWindow.HeapshotUIObject(name, current.referencedObject, false)); + } + SortedDictionary> sortedDictionary = new SortedDictionary>(); + foreach (HeapshotReader.ObjectInfo current2 in this.heapshotReader.Objects) + { + if (current2.type == HeapshotReader.ObjectType.Managed) + { + string name2 = current2.typeInfo.name; + if (!sortedDictionary.ContainsKey(name2)) + { + sortedDictionary.Add(name2, new List()); + } + sortedDictionary[name2].Add(current2); + } + } + foreach (KeyValuePair> current3 in sortedDictionary) + { + HeapshotReader.ObjectInfo objectInfo = new HeapshotReader.ObjectInfo(); + HeapshotReader.FieldInfo field = new HeapshotReader.FieldInfo("(Unknown)"); + foreach (HeapshotReader.ObjectInfo current4 in current3.Value) + { + objectInfo.references.Add(new HeapshotReader.ReferenceInfo(current4, field)); + } + HeapshotWindow.HeapshotUIObject heapshotUIObject = new HeapshotWindow.HeapshotUIObject(current3.Key + " x " + current3.Value.Count, objectInfo, false); + heapshotUIObject.IsDummyObject = true; + this.hsAllObjects.Add(heapshotUIObject); + } + } + private int GetItemCount(List objects) + { + int num = 0; + foreach (HeapshotWindow.HeapshotUIObject current in objects) + { + num++; + if (current.IsExpanded) + { + num += this.GetItemCount(current.Children); + } + } + return num; + } + private void OpenHeapshot(string fileName) + { + this.heapshotReader = new HeapshotReader(); + string text = this.HeapshotPath + "/" + fileName; + if (this.heapshotReader.Open(text)) + { + this.lastOpenedHeapshotFile = fileName; + this.RefreshHeapshotUIObjects(); + } + else + { + Debug.LogError("Failed to read " + text); + } + } + private void OnGUI() + { + GUI.Label(new Rect(0f, 0f, base.position.width, 20f), "Heapshots are located here: " + Path.Combine(Application.dataPath, "Heapshots")); + GUI.Label(new Rect(0f, 20f, base.position.width, 20f), "Currently opened: " + this.lastOpenedHeapshotFile); + GUI.Label(new Rect(100f, 40f, base.position.width, 20f), "Profiling: " + this.lastOpenedProfiler); + this.DoActiveProfilerButton(new Rect(0f, 40f, 100f, 30f)); + if (GUI.Button(new Rect(0f, 70f, 200f, 20f), "CaptureHeapShot", EditorStyles.toolbarDropDown)) + { + ProfilerDriver.CaptureHeapshot(); + } + GUI.changed = false; + this.selectedHeapshot = EditorGUI.Popup(new Rect(250f, 70f, 500f, 30f), "Click to open -->", this.selectedHeapshot, this.heapshotFiles.ToArray()); + if (GUI.changed && this.heapshotFiles[this.selectedHeapshot].Length > 0) + { + this.OpenHeapshot(this.heapshotFiles[this.selectedHeapshot] + ".heapshot"); + } + GUILayout.BeginArea(new Rect(0f, 90f, base.position.width, 60f)); + SplitterGUILayout.BeginHorizontalSplit(this.viewSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + string[] array = new string[] + { + "Roots", + "All Objects" + }; + for (int i = 0; i < array.Length; i++) + { + bool flag = GUILayout.Toggle(this.currentTab == i, array[i], EditorStyles.toolbarButton, new GUILayoutOption[] + { + GUILayout.MaxHeight(16f) + }); + if (flag) + { + this.currentTab = i; + } + } + GUILayout.EndHorizontal(); + this.DoTitles(this.titleSplit1); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Back trace references", EditorStyles.toolbarButton, new GUILayoutOption[] + { + GUILayout.MaxHeight(16f) + }); + this.DoTitles(this.titleSplit2); + GUILayout.EndVertical(); + SplitterGUILayout.EndHorizontalSplit(); + GUILayout.EndArea(); + this.guiRect = new Rect(0f, 130f, (float)this.viewSplit.realSizes[0], 16f); + float height = (float)this.GetItemCount(this.hsAllObjects) * 16f; + Rect position = new Rect(this.guiRect.x, this.guiRect.y, this.guiRect.width, base.position.height - this.guiRect.y); + this.leftViewScrollPosition = GUI.BeginScrollView(position, this.leftViewScrollPosition, new Rect(0f, 0f, position.width - 20f, height)); + this.itemIndex = 0; + this.guiRect.y = 0f; + int num = this.currentTab; + if (num != 0) + { + if (num == 1) + { + this.DoHeapshotObjects(this.hsAllObjects, this.titleSplit1, 0, new HeapshotWindow.OnSelect(this.OnSelectObject)); + } + } + else + { + this.DoHeapshotObjects(this.hsRoots, this.titleSplit1, 0, new HeapshotWindow.OnSelect(this.OnSelectObject)); + } + GUI.EndScrollView(); + this.guiRect = new Rect((float)this.viewSplit.realSizes[0], 130f, (float)this.viewSplit.realSizes[1], 16f); + float height2 = (float)this.GetItemCount(this.hsBackTraceObjects) * 16f; + position = new Rect(this.guiRect.x, this.guiRect.y, this.guiRect.width, base.position.height - this.guiRect.y); + this.rightViewScrollPosition = GUI.BeginScrollView(position, this.rightViewScrollPosition, new Rect(0f, 0f, position.width - 20f, height2)); + if (this.hsBackTraceObjects.Count > 0) + { + this.guiRect.y = 0f; + this.itemIndex = 0; + this.DoHeapshotObjects(this.hsBackTraceObjects, this.titleSplit2, 0, null); + } + GUI.EndScrollView(); + } + private void OnSelectObject(HeapshotWindow.HeapshotUIObject o) + { + this.hsBackTraceObjects.Clear(); + this.hsBackTraceObjects.Add(new HeapshotWindow.HeapshotUIObject(o.Name, o.ObjectInfo, true)); + } + private void DoActiveProfilerButton(Rect position) + { + if (EditorGUI.ButtonMouseDown(position, new GUIContent("Active Profler"), FocusType.Native, EditorStyles.toolbarDropDown)) + { + int connectedProfiler = ProfilerDriver.connectedProfiler; + this.connectionGuids = ProfilerDriver.GetAvailableProfilers(); + int num = this.connectionGuids.Length; + int[] array = new int[1]; + bool[] array2 = new bool[num]; + string[] array3 = new string[num]; + for (int i = 0; i < num; i++) + { + int num2 = this.connectionGuids[i]; + bool flag = ProfilerDriver.IsIdentifierConnectable(num2); + array2[i] = flag; + string text = ProfilerDriver.GetConnectionIdentifier(num2); + if (!flag) + { + text += " (Version mismatch)"; + } + array3[i] = text; + if (num2 == connectedProfiler) + { + array[0] = i; + } + } + EditorUtility.DisplayCustomMenu(position, array3, array2, array, new EditorUtility.SelectMenuItemFunction(this.SelectProfilerClick), null); + } + } + private void SelectProfilerClick(object userData, string[] options, int selected) + { + int num = this.connectionGuids[selected]; + this.lastOpenedProfiler = ProfilerDriver.GetConnectionIdentifier(num); + ProfilerDriver.connectedProfiler = num; + } + private void DoTitles(SplitterState splitter) + { + SplitterGUILayout.BeginHorizontalSplit(splitter, new GUILayoutOption[0]); + for (int i = 0; i < this.titleNames.Length; i++) + { + GUILayout.Toggle(false, this.titleNames[i], EditorStyles.toolbarButton, new GUILayoutOption[] + { + GUILayout.MaxHeight(16f) + }); + } + SplitterGUILayout.EndHorizontalSplit(); + } + private void DoHeapshotObjects(List objects, SplitterState splitter, int indent, HeapshotWindow.OnSelect onSelect) + { + if (objects == null) + { + return; + } + Event current = Event.current; + foreach (HeapshotWindow.HeapshotUIObject current2 in objects) + { + Rect position = new Rect(14f * (float)indent, this.guiRect.y, 14f, this.guiRect.height); + Rect[] array = new Rect[this.titleNames.Length]; + float num = 14f * (float)(indent + 1); + for (int i = 0; i < array.Length; i++) + { + float num2 = (i != 0) ? ((float)splitter.realSizes[i]) : ((float)splitter.realSizes[i] - num); + array[i] = new Rect(num, this.guiRect.y, num2, this.guiRect.height); + num += num2; + } + if (current.type == EventType.Repaint) + { + Rect position2 = new Rect(0f, 16f * (float)this.itemIndex, base.position.width, 16f); + GUIStyle gUIStyle = ((this.itemIndex & 1) != 0) ? HeapshotWindow.Styles.entryOdd : HeapshotWindow.Styles.entryEven; + gUIStyle.Draw(position2, GUIContent.none, false, false, this.itemIndex == this.selectedItem, false); + } + if (current2.HasChildren) + { + GUI.changed = false; + bool flag = GUI.Toggle(position, current2.IsExpanded, GUIContent.none, HeapshotWindow.Styles.foldout); + if (GUI.changed) + { + if (flag) + { + current2.Expand(); + } + else + { + current2.Collapse(); + } + } + } + GUI.changed = false; + bool flag2 = GUI.Toggle(array[0], this.itemIndex == this.selectedItem, current2.Name, HeapshotWindow.Styles.numberLabel); + if (!current2.IsDummyObject) + { + GUI.Toggle(array[1], this.itemIndex == this.selectedItem, current2.TypeName, HeapshotWindow.Styles.numberLabel); + GUI.Toggle(array[2], this.itemIndex == this.selectedItem, "0x" + current2.Code.ToString("X"), HeapshotWindow.Styles.numberLabel); + GUI.Toggle(array[3], this.itemIndex == this.selectedItem, current2.Size.ToString(), HeapshotWindow.Styles.numberLabel); + GUI.Toggle(array[4], this.itemIndex == this.selectedItem, string.Format("{0} / {1}", current2.ReferenceCount, current2.InverseReferenceCount), HeapshotWindow.Styles.numberLabel); + if (GUI.changed && flag2 && onSelect != null) + { + this.selectedItem = this.itemIndex; + onSelect(current2); + } + } + this.itemIndex++; + this.guiRect.y = this.guiRect.y + 16f; + this.DoHeapshotObjects(current2.Children, splitter, indent + 1, onSelect); + } + } + } +} diff --git a/UnityEditor/UnityEditor/HeightmapFilters.cs b/UnityEditor/UnityEditor/HeightmapFilters.cs new file mode 100644 index 00000000..397de41e --- /dev/null +++ b/UnityEditor/UnityEditor/HeightmapFilters.cs @@ -0,0 +1,70 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class HeightmapFilters + { + private static void WobbleStuff(float[,] heights, TerrainData terrain) + { + for (int i = 0; i < heights.GetLength(0); i++) + { + for (int j = 0; j < heights.GetLength(1); j++) + { + heights[i, j] = (heights[i, j] + 1f) / 2f; + } + } + } + private static void Noise(float[,] heights, TerrainData terrain) + { + for (int i = 0; i < heights.GetLength(0); i++) + { + for (int j = 0; j < heights.GetLength(1); j++) + { + heights[i, j] += UnityEngine.Random.value * 0.01f; + } + } + } + public static void Smooth(float[,] heights, TerrainData terrain) + { + float[,] array = heights.Clone() as float[,]; + int length = heights.GetLength(1); + int length2 = heights.GetLength(0); + for (int i = 1; i < length2 - 1; i++) + { + for (int j = 1; j < length - 1; j++) + { + float num = 0f; + num += array[i, j]; + num += array[i, j - 1]; + num += array[i, j + 1]; + num += array[i - 1, j]; + num += array[i + 1, j]; + num /= 5f; + heights[i, j] = num; + } + } + } + public static void Smooth(TerrainData terrain) + { + int heightmapWidth = terrain.heightmapWidth; + int heightmapHeight = terrain.heightmapHeight; + float[,] heights = terrain.GetHeights(0, 0, heightmapWidth, heightmapHeight); + HeightmapFilters.Smooth(heights, terrain); + terrain.SetHeights(0, 0, heights); + } + public static void Flatten(TerrainData terrain, float height) + { + int heightmapWidth = terrain.heightmapWidth; + int heightmapHeight = terrain.heightmapHeight; + float[,] array = new float[heightmapHeight, heightmapWidth]; + for (int i = 0; i < array.GetLength(0); i++) + { + for (int j = 0; j < array.GetLength(1); j++) + { + array[i, j] = height; + } + } + terrain.SetHeights(0, 0, array); + } + } +} diff --git a/UnityEditor/UnityEditor/HeightmapPainter.cs b/UnityEditor/UnityEditor/HeightmapPainter.cs new file mode 100644 index 00000000..291e44a5 --- /dev/null +++ b/UnityEditor/UnityEditor/HeightmapPainter.cs @@ -0,0 +1,93 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class HeightmapPainter + { + public int size; + public float strength; + public float targetHeight; + public TerrainTool tool; + public Brush brush; + public TerrainData terrainData; + private float Smooth(int x, int y) + { + float num = 0f; + float num2 = 1f / this.terrainData.size.y; + num += this.terrainData.GetHeight(x, y) * num2; + num += this.terrainData.GetHeight(x + 1, y) * num2; + num += this.terrainData.GetHeight(x - 1, y) * num2; + num += this.terrainData.GetHeight(x + 1, y + 1) * num2 * 0.75f; + num += this.terrainData.GetHeight(x - 1, y + 1) * num2 * 0.75f; + num += this.terrainData.GetHeight(x + 1, y - 1) * num2 * 0.75f; + num += this.terrainData.GetHeight(x - 1, y - 1) * num2 * 0.75f; + num += this.terrainData.GetHeight(x, y + 1) * num2; + num += this.terrainData.GetHeight(x, y - 1) * num2; + return num / 8f; + } + private float ApplyBrush(float height, float brushStrength, int x, int y) + { + if (this.tool == TerrainTool.PaintHeight) + { + return height + brushStrength; + } + if (this.tool == TerrainTool.SetHeight) + { + if (this.targetHeight > height) + { + height += brushStrength; + height = Mathf.Min(height, this.targetHeight); + return height; + } + height -= brushStrength; + height = Mathf.Max(height, this.targetHeight); + return height; + } + else + { + if (this.tool == TerrainTool.SmoothHeight) + { + return Mathf.Lerp(height, this.Smooth(x, y), brushStrength); + } + return height; + } + } + public void PaintHeight(float xCenterNormalized, float yCenterNormalized) + { + int num; + int num2; + if (this.size % 2 == 0) + { + num = Mathf.CeilToInt(xCenterNormalized * (float)(this.terrainData.heightmapWidth - 1)); + num2 = Mathf.CeilToInt(yCenterNormalized * (float)(this.terrainData.heightmapHeight - 1)); + } + else + { + num = Mathf.RoundToInt(xCenterNormalized * (float)(this.terrainData.heightmapWidth - 1)); + num2 = Mathf.RoundToInt(yCenterNormalized * (float)(this.terrainData.heightmapHeight - 1)); + } + int num3 = this.size / 2; + int num4 = this.size % 2; + int num5 = Mathf.Clamp(num - num3, 0, this.terrainData.heightmapWidth - 1); + int num6 = Mathf.Clamp(num2 - num3, 0, this.terrainData.heightmapHeight - 1); + int num7 = Mathf.Clamp(num + num3 + num4, 0, this.terrainData.heightmapWidth); + int num8 = Mathf.Clamp(num2 + num3 + num4, 0, this.terrainData.heightmapHeight); + int num9 = num7 - num5; + int num10 = num8 - num6; + float[,] heights = this.terrainData.GetHeights(num5, num6, num9, num10); + for (int i = 0; i < num10; i++) + { + for (int j = 0; j < num9; j++) + { + int ix = num5 + j - (num - num3); + int iy = num6 + i - (num2 - num3); + float strengthInt = this.brush.GetStrengthInt(ix, iy); + float num11 = heights[i, j]; + num11 = this.ApplyBrush(num11, strengthInt * this.strength, j + num5, i + num6); + heights[i, j] = num11; + } + } + this.terrainData.SetHeightsDelayLOD(num5, num6, heights); + } + } +} diff --git a/UnityEditor/UnityEditor/Help.cs b/UnityEditor/UnityEditor/Help.cs new file mode 100644 index 00000000..300d36bc --- /dev/null +++ b/UnityEditor/UnityEditor/Help.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Help + { + public static bool HasHelpForObject(UnityEngine.Object obj) + { + return Help.HasHelpForObject(obj, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasHelpForObject(UnityEngine.Object obj, bool defaultToMonoBehaviour); + internal static string GetNiceHelpNameForObject(UnityEngine.Object obj) + { + return Help.GetNiceHelpNameForObject(obj, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetNiceHelpNameForObject(UnityEngine.Object obj, bool defaultToMonoBehaviour); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ShowHelpForObject(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ShowHelpPage(string page); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BrowseURL(string url); + } +} diff --git a/UnityEditor/UnityEditor/HierarchyProperty.cs b/UnityEditor/UnityEditor/HierarchyProperty.cs new file mode 100644 index 00000000..9cf3c70f --- /dev/null +++ b/UnityEditor/UnityEditor/HierarchyProperty.cs @@ -0,0 +1,155 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class HierarchyProperty : IHierarchyProperty + { + private IntPtr m_Property; + public extern int instanceID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern UnityEngine.Object pptrValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasChildren + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int[] ancestors + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int row + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int colorCode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string guid + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isValid + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isMainRepresentation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasFullPreviewImage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern IconDrawStyle iconDrawStyle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isFolder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Texture2D icon + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern HierarchyProperty(HierarchyType hierarchytType); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Reset(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Dispose(); + ~HierarchyProperty() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsExpanded(int[] expanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Next(int[] expanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool NextWithDepthCheck(int[] expanded, int minDepth); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Previous(int[] expanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Parent(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Find(int instanceID, int[] expanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Skip(int count, int[] expanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int CountRemaining(int[] expanded); + public void SetSearchFilter(string searchString, int mode) + { + SearchFilter searchFilter = SearchableEditorWindow.CreateFilter(searchString, (SearchableEditorWindow.SearchMode)mode); + this.SetSearchFilter(searchFilter); + } + internal void SetSearchFilter(SearchFilter filter) + { + this.SetSearchFilterINTERNAL(filter.SplitNameFilter(), filter.classNames, filter.assetLabels, filter.referencingInstanceIDs, filter.showAllHits); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetSearchFilterINTERNAL(string[] nameFilters, string[] classNames, string[] assetLabels, int[] referencingInstanceIDs, bool showAllHits); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[] FindAllAncestors(int[] instanceIDs); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FilterSingleSceneObject(int instanceID, bool otherVisibilityState); + } +} diff --git a/UnityEditor/UnityEditor/HierarchyType.cs b/UnityEditor/UnityEditor/HierarchyType.cs new file mode 100644 index 00000000..34e1ef3a --- /dev/null +++ b/UnityEditor/UnityEditor/HierarchyType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum HierarchyType + { + Assets = 1, + GameObjects + } +} diff --git a/UnityEditor/UnityEditor/HierarchyWindow.cs b/UnityEditor/UnityEditor/HierarchyWindow.cs new file mode 100644 index 00000000..497a9726 --- /dev/null +++ b/UnityEditor/UnityEditor/HierarchyWindow.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal class HierarchyWindow : BaseProjectWindow + { + public HierarchyWindow() + { + this.m_HierarchyType = HierarchyType.GameObjects; + } + } +} diff --git a/UnityEditor/UnityEditor/HighLevelEvent.cs b/UnityEditor/UnityEditor/HighLevelEvent.cs new file mode 100644 index 00000000..b14d4f58 --- /dev/null +++ b/UnityEditor/UnityEditor/HighLevelEvent.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditor +{ + internal enum HighLevelEvent + { + None, + Click, + DoubleClick, + ContextClick, + BeginDrag, + Drag, + EndDrag, + Delete, + SelectionChanged + } +} diff --git a/UnityEditor/UnityEditor/HighlightSearchMode.cs b/UnityEditor/UnityEditor/HighlightSearchMode.cs new file mode 100644 index 00000000..a82e7751 --- /dev/null +++ b/UnityEditor/UnityEditor/HighlightSearchMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum HighlightSearchMode + { + None, + Auto, + Identifier, + PrefixLabel, + Content + } +} diff --git a/UnityEditor/UnityEditor/Highlighter.cs b/UnityEditor/UnityEditor/Highlighter.cs new file mode 100644 index 00000000..02d1e1ed --- /dev/null +++ b/UnityEditor/UnityEditor/Highlighter.cs @@ -0,0 +1,286 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Highlighter + { + private const float kPulseSpeed = 0.45f; + private const float kPopupDuration = 0.33f; + private const int kExpansionMovementSize = 5; + private static GUIView s_View; + private static HighlightSearchMode s_SearchMode; + private static float s_HighlightElapsedTime; + private static float s_LastTime; + private static Rect s_RepaintRegion; + private static GUIStyle s_HighlightStyle; + private static GUIStyle highlightStyle + { + get + { + if (Highlighter.s_HighlightStyle == null) + { + Highlighter.s_HighlightStyle = new GUIStyle("ControlHighlight"); + } + return Highlighter.s_HighlightStyle; + } + } + public static bool active + { + get; + private set; + } + public static bool activeVisible + { + get + { + return Highlighter.internal_get_activeVisible(); + } + private set + { + Highlighter.internal_set_activeVisible(value); + } + } + public static string activeText + { + get + { + return Highlighter.internal_get_activeText(); + } + private set + { + Highlighter.internal_set_activeText(value); + } + } + public static Rect activeRect + { + get + { + return Highlighter.internal_get_activeRect(); + } + private set + { + Highlighter.internal_set_activeRect(value); + } + } + internal static extern HighlightSearchMode searchMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool searching + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static void Stop() + { + Highlighter.active = false; + Highlighter.activeVisible = false; + Highlighter.activeText = string.Empty; + Highlighter.activeRect = default(Rect); + Highlighter.s_LastTime = 0f; + Highlighter.s_HighlightElapsedTime = 0f; + } + public static bool Highlight(string windowTitle, string text) + { + return Highlighter.Highlight(windowTitle, text, HighlightSearchMode.Auto); + } + public static bool Highlight(string windowTitle, string text, HighlightSearchMode mode) + { + Highlighter.Stop(); + Highlighter.active = true; + if (!Highlighter.SetWindow(windowTitle)) + { + Debug.LogWarning("Window " + windowTitle + " not found."); + return false; + } + Highlighter.activeText = text; + Highlighter.s_SearchMode = mode; + Highlighter.s_LastTime = Time.realtimeSinceStartup; + bool flag = Highlighter.Search(); + if (flag) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(Highlighter.Update)); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(Highlighter.Update)); + } + else + { + Debug.LogWarning(string.Concat(new string[] + { + "Item ", + text, + " not found in window ", + windowTitle, + "." + })); + Highlighter.Stop(); + } + InternalEditorUtility.RepaintAllViews(); + return flag; + } + public static void HighlightIdentifier(Rect position, string identifier) + { + if (Highlighter.searchMode == HighlightSearchMode.Identifier || Highlighter.searchMode == HighlightSearchMode.Auto) + { + Highlighter.Handle(position, identifier); + } + } + private static void Update() + { + Rect activeRect = Highlighter.activeRect; + if (Highlighter.activeRect.width == 0f || Highlighter.s_View == null) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(Highlighter.Update)); + Highlighter.Stop(); + InternalEditorUtility.RepaintAllViews(); + } + else + { + Highlighter.Search(); + } + if (Highlighter.activeVisible) + { + Highlighter.s_HighlightElapsedTime += Time.realtimeSinceStartup - Highlighter.s_LastTime; + } + Highlighter.s_LastTime = Time.realtimeSinceStartup; + Rect rect = Highlighter.activeRect; + if (activeRect.width > 0f) + { + rect.xMin = Mathf.Min(rect.xMin, activeRect.xMin); + rect.xMax = Mathf.Max(rect.xMax, activeRect.xMax); + rect.yMin = Mathf.Min(rect.yMin, activeRect.yMin); + rect.yMax = Mathf.Max(rect.yMax, activeRect.yMax); + } + rect = Highlighter.highlightStyle.padding.Add(rect); + rect = Highlighter.highlightStyle.overflow.Add(rect); + rect = new RectOffset(7, 7, 7, 7).Add(rect); + if (Highlighter.s_HighlightElapsedTime < 0.43f) + { + rect = new RectOffset((int)rect.width / 2, (int)rect.width / 2, (int)rect.height / 2, (int)rect.height / 2).Add(rect); + } + Highlighter.s_RepaintRegion = rect; + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(GUIView)); + for (int i = 0; i < array.Length; i++) + { + GUIView gUIView = (GUIView)array[i]; + if (gUIView.window == Highlighter.s_View.window) + { + gUIView.SendEvent(EditorGUIUtility.CommandEvent("HandleControlHighlight")); + } + } + } + private static bool SetWindow(string windowTitle) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(GUIView)); + GUIView x = null; + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + GUIView gUIView = (GUIView)array2[i]; + if (gUIView is HostView) + { + if (EditorGUIUtility.TextContent((gUIView as HostView).actualView.title).text == windowTitle) + { + x = gUIView; + break; + } + } + else + { + if (gUIView.window && gUIView.GetType().Name == windowTitle) + { + x = gUIView; + break; + } + } + } + Highlighter.s_View = x; + return x != null; + } + private static bool Search() + { + Highlighter.searchMode = Highlighter.s_SearchMode; + Highlighter.s_View.RepaintImmediately(); + if (Highlighter.searchMode == HighlightSearchMode.None) + { + return true; + } + Highlighter.searchMode = HighlightSearchMode.None; + Highlighter.Stop(); + return false; + } + internal static void ControlHighlightGUI(GUIView self) + { + if (Highlighter.s_View == null || self.window != Highlighter.s_View.window) + { + return; + } + if (!Highlighter.activeVisible || Highlighter.searching) + { + return; + } + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "HandleControlHighlight") + { + if (self.screenPosition.Overlaps(Highlighter.s_RepaintRegion)) + { + self.Repaint(); + } + return; + } + if (Event.current.type != EventType.Repaint) + { + return; + } + Rect rect = GUIUtility.ScreenToGUIRect(Highlighter.activeRect); + rect = Highlighter.highlightStyle.padding.Add(rect); + float num = (Mathf.Cos(Highlighter.s_HighlightElapsedTime * 3.14159274f * 2f * 0.45f) + 1f) * 0.5f; + float num2 = Mathf.Min(1f, 0.01f + Highlighter.s_HighlightElapsedTime / 0.33f); + num2 += Mathf.Sin(num2 * 3.14159274f) * 0.5f; + Vector2 b = new Vector2((rect.width + 5f) / rect.width - 1f, (rect.height + 5f) / rect.height - 1f) * num; + Vector2 scale = (Vector2.one + b) * num2; + Matrix4x4 matrix = GUI.matrix; + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, 0.8f - 0.3f * num); + GUIUtility.ScaleAroundPivot(scale, rect.center); + Highlighter.highlightStyle.Draw(rect, false, false, false, false); + GUI.color = color; + GUI.matrix = matrix; + } + internal static void Handle(Rect position, string text) + { + Highlighter.INTERNAL_CALL_Handle(ref position, text); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Handle(ref Rect position, string text); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string internal_get_activeText(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void internal_set_activeText(string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect internal_get_activeRect(); + internal static void internal_set_activeRect(Rect value) + { + Highlighter.INTERNAL_CALL_internal_set_activeRect(ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_internal_set_activeRect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool internal_get_activeVisible(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void internal_set_activeVisible(bool value); + } +} diff --git a/UnityEditor/UnityEditor/HingeJoint2DEditor.cs b/UnityEditor/UnityEditor/HingeJoint2DEditor.cs new file mode 100644 index 00000000..e9ee93e5 --- /dev/null +++ b/UnityEditor/UnityEditor/HingeJoint2DEditor.cs @@ -0,0 +1,52 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(HingeJoint2D))] + internal class HingeJoint2DEditor : AnchoredJoint2DEditor + { + public new void OnSceneGUI() + { + HingeJoint2D hingeJoint2D = (HingeJoint2D)this.target; + if (!hingeJoint2D.enabled) + { + return; + } + if (hingeJoint2D.useLimits) + { + Vector3 vector = Joint2DEditorBase.TransformPoint(hingeJoint2D.transform, hingeJoint2D.anchor); + float num = Mathf.Min(hingeJoint2D.limits.min, hingeJoint2D.limits.max); + float num2 = Mathf.Max(hingeJoint2D.limits.min, hingeJoint2D.limits.max); + float angle = num2 - num; + float num3 = HandleUtility.GetHandleSize(vector) * 0.8f; + float rotation = hingeJoint2D.GetComponent().rotation; + Vector3 vector2 = Joint2DEditorBase.RotateVector2(Vector3.right, -num2 - rotation); + Vector3 end = vector + Joint2DEditorBase.RotateVector2(Vector3.right, -hingeJoint2D.jointAngle - rotation) * num3; + Handles.color = new Color(0f, 1f, 0f, 0.7f); + Joint2DEditorBase.DrawAALine(vector, end); + Handles.color = new Color(0f, 1f, 0f, 0.03f); + Handles.DrawSolidArc(vector, Vector3.back, vector2, angle, num3); + Handles.color = new Color(0f, 1f, 0f, 0.7f); + Handles.DrawWireArc(vector, Vector3.back, vector2, angle, num3); + this.DrawTick(vector, num3, 0f, vector2, 1f); + this.DrawTick(vector, num3, angle, vector2, 1f); + } + base.OnSceneGUI(); + } + private void DrawTick(Vector3 center, float radius, float angle, Vector3 up, float length) + { + Vector3 a = Joint2DEditorBase.RotateVector2(up, angle).normalized; + Vector3 vector = center + a * radius; + Vector3 vector2 = vector + (center - vector).normalized * radius * length; + Handles.DrawAAPolyLine(new Color[] + { + new Color(0f, 1f, 0f, 0.7f), + new Color(0f, 1f, 0f, 0f) + }, new Vector3[] + { + vector, + vector2 + }); + } + } +} diff --git a/UnityEditor/UnityEditor/HorizontalLayout.cs b/UnityEditor/UnityEditor/HorizontalLayout.cs new file mode 100644 index 00000000..c82d91dc --- /dev/null +++ b/UnityEditor/UnityEditor/HorizontalLayout.cs @@ -0,0 +1,21 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class HorizontalLayout : IDisposable + { + private static readonly HorizontalLayout instance = new HorizontalLayout(); + private HorizontalLayout() + { + } + void IDisposable.Dispose() + { + GUILayout.EndHorizontal(); + } + public static IDisposable DoLayout() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + return HorizontalLayout.instance; + } + } +} diff --git a/UnityEditor/UnityEditor/HostView.cs b/UnityEditor/UnityEditor/HostView.cs new file mode 100644 index 00000000..13048119 --- /dev/null +++ b/UnityEditor/UnityEditor/HostView.cs @@ -0,0 +1,280 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class HostView : GUIView + { + internal static Color kViewColor = new Color(0.76f, 0.76f, 0.76f, 1f); + internal static PrefColor kPlayModeDarken = new PrefColor("Playmode tint", 0.8f, 0.8f, 0.8f, 1f); + internal GUIStyle background; + [SerializeField] + protected EditorWindow m_ActualView; + [NonSerialized] + private Rect m_BackgroundClearRect = new Rect(0f, 0f, 0f, 0f); + internal EditorWindow actualView + { + get + { + return this.m_ActualView; + } + set + { + if (this.m_ActualView == value) + { + return; + } + this.DeregisterSelectedPane(true); + this.m_ActualView = value; + this.RegisterSelectedPane(); + } + } + internal RectOffset borderSize + { + get + { + return this.GetBorderSize(); + } + } + protected override void SetPosition(Rect newPos) + { + base.SetPosition(newPos); + if (this.m_ActualView != null) + { + this.m_ActualView.m_Pos = newPos; + this.m_ActualView.OnResized(); + } + } + public void OnEnable() + { + this.background = null; + this.RegisterSelectedPane(); + } + private void OnDisable() + { + this.DeregisterSelectedPane(false); + } + private void OnGUI() + { + EditorGUIUtility.ResetGUIState(); + base.DoWindowDecorationStart(); + if (this.background == null) + { + this.background = "hostview"; + this.background.padding.top = 0; + } + GUILayout.BeginVertical(this.background, new GUILayoutOption[0]); + if (this.actualView) + { + this.actualView.m_Pos = base.screenPosition; + } + this.Invoke("OnGUI"); + EditorGUIUtility.ResetGUIState(); + if (this.m_ActualView.m_FadeoutTime != 0f && Event.current.type == EventType.Repaint) + { + this.m_ActualView.DrawNotification(); + } + GUILayout.EndVertical(); + base.DoWindowDecorationEnd(); + EditorGUI.ShowRepaints(); + } + protected override bool OnFocus() + { + this.Invoke("OnFocus"); + if (this == null) + { + return false; + } + base.Repaint(); + return true; + } + private void OnLostFocus() + { + this.Invoke("OnLostFocus"); + base.Repaint(); + } + public new void OnDestroy() + { + if (this.m_ActualView) + { + UnityEngine.Object.DestroyImmediate(this.m_ActualView, true); + } + base.OnDestroy(); + } + protected Type[] GetPaneTypes() + { + return new Type[] + { + typeof(SceneView), + typeof(GameView), + typeof(InspectorWindow), + typeof(SceneHierarchyWindow), + typeof(ProjectBrowser), + typeof(ProfilerWindow), + typeof(AnimationWindow) + }; + } + internal void OnProjectChange() + { + this.Invoke("OnProjectChange"); + } + internal void OnSelectionChange() + { + this.Invoke("OnSelectionChange"); + } + internal void OnDidOpenScene() + { + this.Invoke("OnDidOpenScene"); + } + internal void OnInspectorUpdate() + { + this.Invoke("OnInspectorUpdate"); + } + internal void OnHierarchyChange() + { + this.Invoke("OnHierarchyChange"); + } + private MethodInfo GetPaneMethod(string methodName) + { + return this.GetPaneMethod(methodName, this.m_ActualView); + } + private MethodInfo GetPaneMethod(string methodName, object obj) + { + if (obj == null) + { + return null; + } + for (Type type = obj.GetType(); type != null; type = type.BaseType) + { + MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + return method; + } + } + return null; + } + protected void Invoke(string methodName) + { + this.Invoke(methodName, this.m_ActualView); + } + protected void Invoke(string methodName, object obj) + { + MethodInfo paneMethod = this.GetPaneMethod(methodName, obj); + if (paneMethod != null) + { + paneMethod.Invoke(obj, null); + } + } + protected void RegisterSelectedPane() + { + if (!this.m_ActualView) + { + return; + } + this.m_ActualView.m_Parent = this; + if (this.GetPaneMethod("Update") != null) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.SendUpdate)); + } + if (this.GetPaneMethod("ModifierKeysChanged") != null) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendModKeysChanged)); + } + this.m_ActualView.MakeParentsSettingsMatchMe(); + if (this.m_ActualView.m_FadeoutTime != 0f) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.m_ActualView.CheckForWindowRepaint)); + } + this.Invoke("OnBecameVisible"); + this.Invoke("OnFocus"); + } + protected void DeregisterSelectedPane(bool clearActualView) + { + if (!this.m_ActualView) + { + return; + } + if (this.GetPaneMethod("Update") != null) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.SendUpdate)); + } + if (this.GetPaneMethod("ModifierKeysChanged") != null) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendModKeysChanged)); + } + if (this.m_ActualView.m_FadeoutTime != 0f) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.m_ActualView.CheckForWindowRepaint)); + } + if (clearActualView) + { + EditorWindow actualView = this.m_ActualView; + this.m_ActualView = null; + this.Invoke("OnLostFocus", actualView); + this.Invoke("OnBecameInvisible", actualView); + } + } + private void SendUpdate() + { + this.Invoke("Update"); + } + private void SendModKeysChanged() + { + this.Invoke("ModifierKeysChanged"); + } + protected virtual RectOffset GetBorderSize() + { + return new RectOffset(); + } + protected void ShowGenericMenu() + { + GUIStyle gUIStyle = "PaneOptions"; + Rect rect = new Rect(base.position.width - gUIStyle.fixedWidth - 4f, Mathf.Floor((float)(this.background.margin.top + 20) - gUIStyle.fixedHeight), gUIStyle.fixedWidth, gUIStyle.fixedHeight); + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, "PaneOptions")) + { + this.PopupGenericMenu(this.m_ActualView, rect); + } + MethodInfo paneMethod = this.GetPaneMethod("ShowButton", this.m_ActualView); + if (paneMethod != null) + { + object[] parameters = new object[] + { + new Rect(base.position.width - gUIStyle.fixedWidth - 20f, Mathf.Floor((float)(this.background.margin.top + 4)), 16f, 16f) + }; + paneMethod.Invoke(this.m_ActualView, parameters); + } + } + public void PopupGenericMenu(EditorWindow view, Rect pos) + { + GenericMenu genericMenu = new GenericMenu(); + IHasCustomMenu hasCustomMenu = view as IHasCustomMenu; + if (hasCustomMenu != null) + { + hasCustomMenu.AddItemsToMenu(genericMenu); + } + this.AddDefaultItemsToMenu(genericMenu, view); + genericMenu.DropDown(pos); + Event.current.Use(); + } + protected virtual void AddDefaultItemsToMenu(GenericMenu menu, EditorWindow view) + { + } + protected void ClearBackground() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + EditorWindow actualView = this.actualView; + if (actualView != null && actualView.dontClearBackground && base.backgroundValid && base.position == this.m_BackgroundClearRect) + { + return; + } + Color color = (!EditorGUIUtility.isProSkin) ? HostView.kViewColor : EditorGUIUtility.kDarkViewBackground; + GL.Clear(true, true, (!EditorApplication.isPlayingOrWillChangePlaymode) ? color : (color * HostView.kPlayModeDarken)); + base.backgroundValid = true; + this.m_BackgroundClearRect = base.position; + } + } +} diff --git a/UnityEditor/UnityEditor/HumanTemplate.cs b/UnityEditor/UnityEditor/HumanTemplate.cs new file mode 100644 index 00000000..aa1daaf2 --- /dev/null +++ b/UnityEditor/UnityEditor/HumanTemplate.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class HumanTemplate : UnityEngine.Object + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern HumanTemplate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Insert(string name, string templateName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string Find(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearTemplate(); + } +} diff --git a/UnityEditor/UnityEditor/ICleanuppable.cs b/UnityEditor/UnityEditor/ICleanuppable.cs new file mode 100644 index 00000000..427440d9 --- /dev/null +++ b/UnityEditor/UnityEditor/ICleanuppable.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + internal interface ICleanuppable + { + void Cleanup(); + } +} diff --git a/UnityEditor/UnityEditor/IDropArea.cs b/UnityEditor/UnityEditor/IDropArea.cs new file mode 100644 index 00000000..9d29dfdb --- /dev/null +++ b/UnityEditor/UnityEditor/IDropArea.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal interface IDropArea + { + DropInfo DragOver(EditorWindow w, Vector2 screenPos); + bool PerformDrop(EditorWindow w, DropInfo dropInfo, Vector2 screenPos); + } +} diff --git a/UnityEditor/UnityEditor/IEditablePoint.cs b/UnityEditor/UnityEditor/IEditablePoint.cs new file mode 100644 index 00000000..04b1e7a5 --- /dev/null +++ b/UnityEditor/UnityEditor/IEditablePoint.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal interface IEditablePoint + { + int Count + { + get; + } + Vector3 GetPosition(int idx); + void SetPosition(int idx, Vector3 position); + Color GetDefaultColor(); + Color GetSelectedColor(); + float GetPointScale(); + IEnumerable GetPositions(); + Vector3[] GetUnselectedPositions(); + Vector3[] GetSelectedPositions(); + } +} diff --git a/UnityEditor/UnityEditor/IFlexibleMenuItemProvider.cs b/UnityEditor/UnityEditor/IFlexibleMenuItemProvider.cs new file mode 100644 index 00000000..e2bdeb8e --- /dev/null +++ b/UnityEditor/UnityEditor/IFlexibleMenuItemProvider.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEditor +{ + internal interface IFlexibleMenuItemProvider + { + int Count(); + object GetItem(int index); + int Add(object obj); + void Replace(int index, object newPresetObject); + void Remove(int index); + object Create(); + void Move(int index, int destIndex, bool insertAfterDestIndex); + string GetName(int index); + bool IsModificationAllowed(int index); + int[] GetSeperatorIndices(); + } +} diff --git a/UnityEditor/UnityEditor/IHasCustomMenu.cs b/UnityEditor/UnityEditor/IHasCustomMenu.cs new file mode 100644 index 00000000..129a7b9c --- /dev/null +++ b/UnityEditor/UnityEditor/IHasCustomMenu.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + public interface IHasCustomMenu + { + void AddItemsToMenu(GenericMenu menu); + } +} diff --git a/UnityEditor/UnityEditor/IHierarchyProperty.cs b/UnityEditor/UnityEditor/IHierarchyProperty.cs new file mode 100644 index 00000000..7266c7b0 --- /dev/null +++ b/UnityEditor/UnityEditor/IHierarchyProperty.cs @@ -0,0 +1,78 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal interface IHierarchyProperty + { + int instanceID + { + get; + } + UnityEngine.Object pptrValue + { + get; + } + string name + { + get; + } + bool hasChildren + { + get; + } + int depth + { + get; + } + int row + { + get; + } + int colorCode + { + get; + } + string guid + { + get; + } + Texture2D icon + { + get; + } + bool isValid + { + get; + } + bool isMainRepresentation + { + get; + } + bool hasFullPreviewImage + { + get; + } + IconDrawStyle iconDrawStyle + { + get; + } + bool isFolder + { + get; + } + int[] ancestors + { + get; + } + void Reset(); + bool IsExpanded(int[] expanded); + bool Next(int[] expanded); + bool NextWithDepthCheck(int[] expanded, int minDepth); + bool Previous(int[] expanded); + bool Parent(); + bool Find(int instanceID, int[] expanded); + int[] FindAllAncestors(int[] instanceIDs); + bool Skip(int count, int[] expanded); + int CountRemaining(int[] expanded); + } +} diff --git a/UnityEditor/UnityEditor/IPrefType.cs b/UnityEditor/UnityEditor/IPrefType.cs new file mode 100644 index 00000000..4c3c0df8 --- /dev/null +++ b/UnityEditor/UnityEditor/IPrefType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal interface IPrefType + { + string ToUniqueString(); + void FromUniqueString(string sstr); + } +} diff --git a/UnityEditor/UnityEditor/IPreviewable.cs b/UnityEditor/UnityEditor/IPreviewable.cs new file mode 100644 index 00000000..6af3faff --- /dev/null +++ b/UnityEditor/UnityEditor/IPreviewable.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal interface IPreviewable + { + UnityEngine.Object target + { + get; + } + void Initialize(UnityEngine.Object[] targets); + bool MoveNextTarget(); + void ResetTarget(); + bool HasPreviewGUI(); + GUIContent GetPreviewTitle(); + void DrawPreview(Rect previewArea); + void OnPreviewGUI(Rect r, GUIStyle background); + void OnInteractivePreviewGUI(Rect r, GUIStyle background); + void OnPreviewSettings(); + string GetInfoString(); + } +} diff --git a/UnityEditor/UnityEditor/ITreeViewDataSource.cs b/UnityEditor/UnityEditor/ITreeViewDataSource.cs new file mode 100644 index 00000000..56d4c272 --- /dev/null +++ b/UnityEditor/UnityEditor/ITreeViewDataSource.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal interface ITreeViewDataSource + { + TreeViewItem root + { + get; + } + void ReloadData(); + TreeViewItem FindItem(int id); + List GetVisibleRows(); + void SetExpandedWithChildren(TreeViewItem item, bool expand); + void SetExpanded(TreeViewItem item, bool expand); + bool IsExpanded(TreeViewItem item); + bool IsExpandable(TreeViewItem item); + int[] GetExpandedIDs(); + void SetExpandedIDs(int[] ids); + bool CanBeMultiSelected(TreeViewItem item); + bool CanBeParent(TreeViewItem item); + bool IsRenamingItemAllowed(TreeViewItem item); + void InsertFakeItem(int id, int parentID, string name, Texture2D icon); + void RemoveFakeItem(); + bool HasFakeItem(); + } +} diff --git a/UnityEditor/UnityEditor/ITreeViewDragging.cs b/UnityEditor/UnityEditor/ITreeViewDragging.cs new file mode 100644 index 00000000..a9ae23a6 --- /dev/null +++ b/UnityEditor/UnityEditor/ITreeViewDragging.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal interface ITreeViewDragging + { + bool drawRowMarkerAbove + { + get; + set; + } + void StartDrag(TreeViewItem draggedItem, List draggedItemIDs); + bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bool firstItem); + void DragCleanup(bool revertExpanded); + int GetDropTargetControlID(); + int GetRowMarkerControlID(); + } +} diff --git a/UnityEditor/UnityEditor/ITreeViewGUI.cs b/UnityEditor/UnityEditor/ITreeViewGUI.cs new file mode 100644 index 00000000..36c135b0 --- /dev/null +++ b/UnityEditor/UnityEditor/ITreeViewGUI.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal interface ITreeViewGUI + { + float halfDropBetweenHeight + { + get; + } + Vector2 GetTotalSize(List rows); + void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible); + float GetTopPixelOfRow(int row, List rows); + float GetHeightOfLastRow(); + int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView); + Rect OnRowGUI(TreeViewItem item, int row, float rowWidth, bool selected, bool focused); + void BeginRowGUI(); + void EndRowGUI(); + void BeginPingNode(TreeViewItem item, float topPixelOfRow, float availableWidth); + void EndPingNode(); + bool BeginRename(TreeViewItem item, float delay); + void EndRename(); + float GetContentIndent(TreeViewItem item); + } +} diff --git a/UnityEditor/UnityEditor/IconDrawStyle.cs b/UnityEditor/UnityEditor/IconDrawStyle.cs new file mode 100644 index 00000000..ed782fdc --- /dev/null +++ b/UnityEditor/UnityEditor/IconDrawStyle.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum IconDrawStyle + { + NonTexture, + Texture + } +} diff --git a/UnityEditor/UnityEditor/IconSelector.cs b/UnityEditor/UnityEditor/IconSelector.cs new file mode 100644 index 00000000..05ab33e8 --- /dev/null +++ b/UnityEditor/UnityEditor/IconSelector.cs @@ -0,0 +1,321 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class IconSelector : EditorWindow + { + private class Styles + { + public GUIStyle background = "sv_iconselector_back"; + public GUIStyle seperator = "sv_iconselector_sep"; + public GUIStyle selection = "sv_iconselector_selection"; + public GUIStyle selectionLabel = "sv_iconselector_labelselection"; + public GUIStyle noneButton = "sv_iconselector_button"; + } + public delegate void MonoScriptIconChangedCallback(MonoScript monoScript); + private static IconSelector s_IconSelector = null; + private static long s_LastClosedTime = 0L; + private static int s_LastInstanceID = -1; + private static int s_HashIconSelector = "IconSelector".GetHashCode(); + private static IconSelector.Styles m_Styles; + private UnityEngine.Object m_TargetObject; + private Texture2D m_StartIcon; + private bool m_ShowLabelIcons; + private GUIContent[] m_LabelLargeIcons; + private GUIContent[] m_LabelIcons; + private GUIContent[] m_LargeIcons; + private GUIContent[] m_SmallIcons; + private GUIContent m_NoneButtonContent; + private IconSelector.MonoScriptIconChangedCallback m_MonoScriptIconChangedCallback; + private IconSelector() + { + base.hideFlags = HideFlags.DontSave; + } + private GUIContent[] GetTextures(string baseName, string postFix, int startIndex, int count) + { + GUIContent[] array = new GUIContent[count]; + for (int i = 0; i < count; i++) + { + array[i] = EditorGUIUtility.IconContent(baseName + (startIndex + i) + postFix); + } + return array; + } + private void OnEnable() + { + } + private void OnDisable() + { + this.SaveIconChanges(); + IconSelector.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + IconSelector.s_IconSelector = null; + } + private void SaveIconChanges() + { + Texture2D iconForObject = EditorGUIUtility.GetIconForObject(this.m_TargetObject); + if (iconForObject != this.m_StartIcon) + { + MonoScript monoScript = this.m_TargetObject as MonoScript; + if (monoScript != null) + { + if (this.m_MonoScriptIconChangedCallback != null) + { + this.m_MonoScriptIconChangedCallback(monoScript); + } + else + { + MonoImporter.CopyMonoScriptIconToImporters(monoScript); + } + } + } + } + internal static bool ShowAtPosition(UnityEngine.Object targetObj, Rect activatorRect, bool showLabelIcons) + { + int instanceID = targetObj.GetInstanceID(); + long num = DateTime.Now.Ticks / 10000L; + bool flag = num < IconSelector.s_LastClosedTime + 50L; + if (instanceID != IconSelector.s_LastInstanceID || !flag) + { + Event.current.Use(); + IconSelector.s_LastInstanceID = instanceID; + if (IconSelector.s_IconSelector == null) + { + IconSelector.s_IconSelector = ScriptableObject.CreateInstance(); + } + IconSelector.s_IconSelector.Init(targetObj, activatorRect, showLabelIcons); + return true; + } + return false; + } + internal static void SetMonoScriptIconChangedCallback(IconSelector.MonoScriptIconChangedCallback callback) + { + if (IconSelector.s_IconSelector != null) + { + IconSelector.s_IconSelector.m_MonoScriptIconChangedCallback = callback; + } + else + { + Debug.Log("ERROR: setting callback on hidden IconSelector"); + } + } + private void Init(UnityEngine.Object targetObj, Rect activatorRect, bool showLabelIcons) + { + this.m_TargetObject = targetObj; + this.m_StartIcon = EditorGUIUtility.GetIconForObject(this.m_TargetObject); + this.m_ShowLabelIcons = showLabelIcons; + Rect buttonRect = GUIUtility.GUIToScreenRect(activatorRect); + GUIUtility.keyboardControl = 0; + this.m_LabelLargeIcons = this.GetTextures("sv_label_", string.Empty, 0, 8); + this.m_LabelIcons = this.GetTextures("sv_icon_name", string.Empty, 0, 8); + this.m_SmallIcons = this.GetTextures("sv_icon_dot", "_sml", 0, 16); + this.m_LargeIcons = this.GetTextures("sv_icon_dot", "_pix16_gizmo", 0, 16); + this.m_NoneButtonContent = EditorGUIUtility.IconContent("sv_icon_none"); + this.m_NoneButtonContent.text = "None"; + float x = 140f; + float y = 86f; + if (this.m_ShowLabelIcons) + { + y = 126f; + } + base.ShowAsDropDown(buttonRect, new Vector2(x, y)); + } + private Texture2D ConvertLargeIconToSmallIcon(Texture2D largeIcon, ref bool isLabelIcon) + { + if (largeIcon == null) + { + return null; + } + isLabelIcon = true; + for (int i = 0; i < this.m_LabelLargeIcons.Length; i++) + { + if (this.m_LabelLargeIcons[i].image == largeIcon) + { + return (Texture2D)this.m_LabelIcons[i].image; + } + } + isLabelIcon = false; + for (int j = 0; j < this.m_LargeIcons.Length; j++) + { + if (this.m_LargeIcons[j].image == largeIcon) + { + return (Texture2D)this.m_SmallIcons[j].image; + } + } + return largeIcon; + } + private Texture2D ConvertSmallIconToLargeIcon(Texture2D smallIcon, bool labelIcon) + { + if (labelIcon) + { + for (int i = 0; i < this.m_LabelIcons.Length; i++) + { + if (this.m_LabelIcons[i].image == smallIcon) + { + return (Texture2D)this.m_LabelLargeIcons[i].image; + } + } + } + else + { + for (int j = 0; j < this.m_SmallIcons.Length; j++) + { + if (this.m_SmallIcons[j].image == smallIcon) + { + return (Texture2D)this.m_LargeIcons[j].image; + } + } + } + return smallIcon; + } + private void DoButton(GUIContent content, Texture2D selectedIcon, bool labelIcon) + { + int controlID = GUIUtility.GetControlID(IconSelector.s_HashIconSelector, FocusType.Keyboard); + if (content.image == selectedIcon) + { + Rect position = GUILayoutUtility.topLevel.PeekNext(); + float num = 2f; + position.x -= num; + position.y -= num; + position.width = (float)selectedIcon.width + 2f * num; + position.height = (float)selectedIcon.height + 2f * num; + GUI.Label(position, GUIContent.none, (!labelIcon) ? IconSelector.m_Styles.selection : IconSelector.m_Styles.selectionLabel); + } + if (EditorGUILayout.IconButton(controlID, content, GUIStyle.none, new GUILayoutOption[0])) + { + Texture2D icon = this.ConvertSmallIconToLargeIcon((Texture2D)content.image, labelIcon); + EditorGUIUtility.SetIconForObject(this.m_TargetObject, icon); + EditorUtility.ForceReloadInspectors(); + AnnotationWindow.IconChanged(); + if (Event.current.clickCount == 2) + { + this.CloseWindow(); + } + } + } + private void DoTopSection(bool anySelected) + { + Rect position = new Rect(6f, 4f, 110f, 20f); + GUI.Label(position, "Select Icon"); + if (anySelected) + { + Rect position2 = new Rect(93f, 6f, 43f, 12f); + if (GUI.Button(position2, this.m_NoneButtonContent, IconSelector.m_Styles.noneButton)) + { + EditorGUIUtility.SetIconForObject(this.m_TargetObject, null); + EditorUtility.ForceReloadInspectors(); + AnnotationWindow.IconChanged(); + } + } + } + private void CloseWindow() + { + base.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + } + internal void OnGUI() + { + if (IconSelector.m_Styles == null) + { + IconSelector.m_Styles = new IconSelector.Styles(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.CloseWindow(); + } + Texture2D texture2D = EditorGUIUtility.GetIconForObject(this.m_TargetObject); + bool flag = false; + if (Event.current.type == EventType.Repaint) + { + texture2D = this.ConvertLargeIconToSmallIcon(texture2D, ref flag); + } + Event current = Event.current; + EventType type = current.type; + GUI.BeginGroup(new Rect(0f, 0f, base.position.width, base.position.height), IconSelector.m_Styles.background); + this.DoTopSection(texture2D != null); + GUILayout.Space(22f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(1f); + GUI.enabled = false; + GUILayout.Label(string.Empty, IconSelector.m_Styles.seperator, new GUILayoutOption[0]); + GUI.enabled = true; + GUILayout.Space(1f); + GUILayout.EndHorizontal(); + GUILayout.Space(3f); + if (this.m_ShowLabelIcons) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(6f); + for (int i = 0; i < this.m_LabelIcons.Length / 2; i++) + { + this.DoButton(this.m_LabelIcons[i], texture2D, true); + } + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(6f); + for (int j = this.m_LabelIcons.Length / 2; j < this.m_LabelIcons.Length; j++) + { + this.DoButton(this.m_LabelIcons[j], texture2D, true); + } + GUILayout.EndHorizontal(); + GUILayout.Space(3f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(1f); + GUI.enabled = false; + GUILayout.Label(string.Empty, IconSelector.m_Styles.seperator, new GUILayoutOption[0]); + GUI.enabled = true; + GUILayout.Space(1f); + GUILayout.EndHorizontal(); + GUILayout.Space(3f); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(9f); + for (int k = 0; k < this.m_SmallIcons.Length / 2; k++) + { + this.DoButton(this.m_SmallIcons[k], texture2D, false); + } + GUILayout.Space(3f); + GUILayout.EndHorizontal(); + GUILayout.Space(6f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(9f); + for (int l = this.m_SmallIcons.Length / 2; l < this.m_SmallIcons.Length; l++) + { + this.DoButton(this.m_SmallIcons[l], texture2D, false); + } + GUILayout.Space(3f); + GUILayout.EndHorizontal(); + GUILayout.Space(6f); + GUI.backgroundColor = new Color(1f, 1f, 1f, 0.7f); + bool flag2 = false; + int controlID = GUIUtility.GetControlID(IconSelector.s_HashIconSelector, FocusType.Keyboard); + if (GUILayout.Button(EditorGUIUtility.TempContent("Other..."), new GUILayoutOption[0])) + { + GUIUtility.keyboardControl = controlID; + flag2 = true; + } + GUI.backgroundColor = new Color(1f, 1f, 1f, 1f); + GUI.EndGroup(); + if (flag2) + { + ObjectSelector.get.Show(this.m_TargetObject, typeof(Texture2D), null, false); + ObjectSelector.get.objectSelectorID = controlID; + GUI.backgroundColor = new Color(1f, 1f, 1f, 0.7f); + current.Use(); + GUIUtility.ExitGUI(); + } + EventType eventType = type; + if (eventType == EventType.ExecuteCommand) + { + string commandName = current.commandName; + if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == controlID && GUIUtility.keyboardControl == controlID) + { + Texture2D icon = ObjectSelector.GetCurrentObject() as Texture2D; + EditorGUIUtility.SetIconForObject(this.m_TargetObject, icon); + GUI.changed = true; + current.Use(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ImportAssetOptions.cs b/UnityEditor/UnityEditor/ImportAssetOptions.cs new file mode 100644 index 00000000..ca305758 --- /dev/null +++ b/UnityEditor/UnityEditor/ImportAssetOptions.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum ImportAssetOptions + { + Default = 0, + ForceUpdate = 1, + ForceSynchronousImport = 8, + ImportRecursive = 256, + DontDownloadFromCacheServer = 8192, + ForceUncompressedImport = 16384 + } +} diff --git a/UnityEditor/UnityEditor/ImportRawHeightmap.cs b/UnityEditor/UnityEditor/ImportRawHeightmap.cs new file mode 100644 index 00000000..7a2827cc --- /dev/null +++ b/UnityEditor/UnityEditor/ImportRawHeightmap.cs @@ -0,0 +1,148 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class ImportRawHeightmap : TerrainWizard + { + internal enum Depth + { + Bit8 = 1, + Bit16 + } + internal enum ByteOrder + { + Mac = 1, + Windows + } + public ImportRawHeightmap.Depth m_Depth = ImportRawHeightmap.Depth.Bit16; + public int m_Width = 1; + public int m_Height = 1; + public ImportRawHeightmap.ByteOrder m_ByteOrder = ImportRawHeightmap.ByteOrder.Mac; + public Vector3 m_TerrainSize = new Vector3(2000f, 600f, 2000f); + private string m_Path; + private void PickRawDefaults(string path) + { + FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read); + int num = (int)fileStream.Length; + fileStream.Close(); + this.m_TerrainSize = base.terrainData.size; + if (base.terrainData.heightmapWidth * base.terrainData.heightmapHeight == num) + { + this.m_Width = base.terrainData.heightmapWidth; + this.m_Height = base.terrainData.heightmapHeight; + this.m_Depth = ImportRawHeightmap.Depth.Bit8; + } + else + { + if (base.terrainData.heightmapWidth * base.terrainData.heightmapHeight * 2 == num) + { + this.m_Width = base.terrainData.heightmapWidth; + this.m_Height = base.terrainData.heightmapHeight; + this.m_Depth = ImportRawHeightmap.Depth.Bit16; + } + else + { + this.m_Depth = ImportRawHeightmap.Depth.Bit16; + int num2 = num / (int)this.m_Depth; + int num3 = Mathf.RoundToInt(Mathf.Sqrt((float)num2)); + int num4 = Mathf.RoundToInt(Mathf.Sqrt((float)num2)); + if (num3 * num4 * (int)this.m_Depth == num) + { + this.m_Width = num3; + this.m_Height = num4; + return; + } + this.m_Depth = ImportRawHeightmap.Depth.Bit8; + num2 = num / (int)this.m_Depth; + num3 = Mathf.RoundToInt(Mathf.Sqrt((float)num2)); + num4 = Mathf.RoundToInt(Mathf.Sqrt((float)num2)); + if (num3 * num4 * (int)this.m_Depth == num) + { + this.m_Width = num3; + this.m_Height = num4; + return; + } + this.m_Depth = ImportRawHeightmap.Depth.Bit16; + } + } + } + internal void OnWizardCreate() + { + if (this.m_Terrain == null) + { + base.isValid = false; + base.errorString = "Terrain does not exist"; + } + if (this.m_Width >= 4097 || this.m_Height >= 4097) + { + base.isValid = false; + base.errorString = "Heightmaps above 4096x4096 in resolution are not supported"; + Debug.LogError("Heightmaps above 4096x4096 in resolution are not supported"); + } + if (File.Exists(this.m_Path) && base.isValid) + { + Undo.RegisterCompleteObjectUndo(base.terrainData, "Import Raw heightmap"); + base.terrainData.heightmapResolution = Mathf.Max(this.m_Width, this.m_Height); + base.terrainData.size = this.m_TerrainSize; + this.ReadRaw(this.m_Path); + base.FlushHeightmapModification(); + } + } + private void ReadRaw(string path) + { + byte[] array; + using (BinaryReader binaryReader = new BinaryReader(File.Open(path, FileMode.Open, FileAccess.Read))) + { + array = binaryReader.ReadBytes(this.m_Width * this.m_Height * (int)this.m_Depth); + binaryReader.Close(); + } + int heightmapWidth = base.terrainData.heightmapWidth; + int heightmapHeight = base.terrainData.heightmapHeight; + float[,] array2 = new float[heightmapHeight, heightmapWidth]; + if (this.m_Depth == ImportRawHeightmap.Depth.Bit16) + { + float num = 1.52587891E-05f; + for (int i = 0; i < heightmapHeight; i++) + { + for (int j = 0; j < heightmapWidth; j++) + { + int num2 = Mathf.Clamp(j, 0, this.m_Width - 1) + Mathf.Clamp(i, 0, this.m_Height - 1) * this.m_Width; + if (this.m_ByteOrder == ImportRawHeightmap.ByteOrder.Mac == BitConverter.IsLittleEndian) + { + byte b = array[num2 * 2]; + array[num2 * 2] = array[num2 * 2 + 1]; + array[num2 * 2 + 1] = b; + } + ushort num3 = BitConverter.ToUInt16(array, num2 * 2); + float num4 = (float)num3 * num; + array2[i, j] = num4; + } + } + } + else + { + float num5 = 0.00390625f; + for (int k = 0; k < heightmapHeight; k++) + { + for (int l = 0; l < heightmapWidth; l++) + { + int num6 = Mathf.Clamp(l, 0, this.m_Width - 1) + Mathf.Clamp(k, 0, this.m_Height - 1) * this.m_Width; + byte b2 = array[num6]; + float num7 = (float)b2 * num5; + array2[k, l] = num7; + } + } + } + base.terrainData.SetHeights(0, 0, array2); + } + internal void InitializeImportRaw(Terrain terrain, string path) + { + this.m_Terrain = terrain; + this.m_Path = path; + this.PickRawDefaults(this.m_Path); + base.helpString = "Raw files must use a single channel and be either 8 or 16 bit."; + this.OnWizardUpdate(); + } + } +} diff --git a/UnityEditor/UnityEditor/InitialModuleUI.cs b/UnityEditor/UnityEditor/InitialModuleUI.cs new file mode 100644 index 00000000..559144af --- /dev/null +++ b/UnityEditor/UnityEditor/InitialModuleUI.cs @@ -0,0 +1,127 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class InitialModuleUI : ModuleUI + { + private class Texts + { + public GUIContent duration = new GUIContent("Duration", "The length of time the Particle System is emitting partcles, if the system is looping, this indicates the length of one cycle."); + public GUIContent looping = new GUIContent("Looping", "If true, the emission cycle will repeat after the duration."); + public GUIContent prewarm = new GUIContent("Prewarm", "When played a prewarmed system will be in a state as if it had emitted one loop cycle. Can only be used if the system is looping."); + public GUIContent startDelay = new GUIContent("Start Delay", "Delay in seconds that this Particle System will wait before emitting particles. Cannot be used together with a prewarmed looping system."); + public GUIContent maxParticles = new GUIContent("Max Particles", "The number of particles in the system will be limited by this number. Emission will be temporarily halted if this is reached."); + public GUIContent lifetime = new GUIContent("Start Lifetime", "Start lifetime in seconds, particle will die when its lifetime reaches 0."); + public GUIContent speed = new GUIContent("Start Speed", "The start speed of particles, applied in the starting direction."); + public GUIContent color = new GUIContent("Start Color", "The start color of particles."); + public GUIContent size = new GUIContent("Start Size", "The start size of particles."); + public GUIContent rotation = new GUIContent("Start Rotation", "The start rotation of particles in degrees."); + public GUIContent autoplay = new GUIContent("Play On Awake", "If enabled, the system will start playing automatically."); + public GUIContent gravity = new GUIContent("Gravity Multiplier", "Scales the gravity defined in Physics Manager"); + public GUIContent inheritvelocity = new GUIContent("Inherit Velocity", "Applies the current directional velocity of the Transform to newly emitted particles."); + public GUIContent simulationSpace = new GUIContent("Simulation Space", "Makes particle positions simulate in worldspace or local space. In local space they stay relative to the Transform."); + public string[] simulationSpaces = new string[] + { + "World", + "Local" + }; + } + public SerializedProperty m_LengthInSec; + public SerializedProperty m_Looping; + public SerializedProperty m_Prewarm; + public SerializedProperty m_StartDelay; + public SerializedProperty m_PlayOnAwake; + public SerializedProperty m_SimulationSpace; + public SerializedMinMaxCurve m_LifeTime; + public SerializedMinMaxCurve m_Speed; + public SerializedMinMaxGradient m_Color; + public SerializedMinMaxCurve m_Size; + public SerializedMinMaxCurve m_Rotation; + public SerializedProperty m_GravityModifier; + public SerializedProperty m_InheritVelocity; + public SerializedProperty m_MaxNumParticles; + private static InitialModuleUI.Texts s_Texts; + public InitialModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "InitialModule", displayName, ModuleUI.VisibilityState.VisibleAndFoldedOut) + { + this.Init(); + } + public override float GetXAxisScalar() + { + return this.m_ParticleSystemUI.GetEmitterDuration(); + } + protected override void Init() + { + if (InitialModuleUI.s_Texts == null) + { + InitialModuleUI.s_Texts = new InitialModuleUI.Texts(); + } + if (this.m_LengthInSec != null) + { + return; + } + this.m_LengthInSec = base.GetProperty0("lengthInSec"); + this.m_Looping = base.GetProperty0("looping"); + this.m_Prewarm = base.GetProperty0("prewarm"); + this.m_StartDelay = base.GetProperty0("startDelay"); + this.m_PlayOnAwake = base.GetProperty0("playOnAwake"); + this.m_SimulationSpace = base.GetProperty0("moveWithTransform"); + this.m_LifeTime = new SerializedMinMaxCurve(this, InitialModuleUI.s_Texts.lifetime, "startLifetime"); + this.m_Speed = new SerializedMinMaxCurve(this, InitialModuleUI.s_Texts.speed, "startSpeed", ModuleUI.kUseSignedRange); + this.m_Color = new SerializedMinMaxGradient(this, "startColor"); + this.m_Size = new SerializedMinMaxCurve(this, InitialModuleUI.s_Texts.size, "startSize"); + this.m_Rotation = new SerializedMinMaxCurve(this, InitialModuleUI.s_Texts.rotation, "startRotation", ModuleUI.kUseSignedRange); + this.m_Rotation.m_RemapValue = 57.29578f; + this.m_Rotation.m_DefaultCurveScalar = 3.14159274f; + this.m_GravityModifier = base.GetProperty("gravityModifier"); + this.m_InheritVelocity = base.GetProperty("inheritVelocity"); + this.m_MaxNumParticles = base.GetProperty("maxNumParticles"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (InitialModuleUI.s_Texts == null) + { + InitialModuleUI.s_Texts = new InitialModuleUI.Texts(); + } + ModuleUI.GUIFloat(InitialModuleUI.s_Texts.duration, this.m_LengthInSec, "f2"); + this.m_LengthInSec.floatValue = Mathf.Min(100000f, Mathf.Max(0f, this.m_LengthInSec.floatValue)); + bool boolValue = this.m_Looping.boolValue; + ModuleUI.GUIToggle(InitialModuleUI.s_Texts.looping, this.m_Looping); + if (this.m_Looping.boolValue && !boolValue && s.time >= this.m_LengthInSec.floatValue) + { + s.time = 0f; + } + EditorGUI.BeginDisabledGroup(!this.m_Looping.boolValue); + ModuleUI.GUIToggle(InitialModuleUI.s_Texts.prewarm, this.m_Prewarm); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.m_Prewarm.boolValue && this.m_Looping.boolValue); + ModuleUI.GUIFloat(InitialModuleUI.s_Texts.startDelay, this.m_StartDelay); + EditorGUI.EndDisabledGroup(); + ModuleUI.GUIMinMaxCurve(InitialModuleUI.s_Texts.lifetime, this.m_LifeTime); + ModuleUI.GUIMinMaxCurve(InitialModuleUI.s_Texts.speed, this.m_Speed); + ModuleUI.GUIMinMaxCurve(InitialModuleUI.s_Texts.size, this.m_Size); + ModuleUI.GUIMinMaxCurve(InitialModuleUI.s_Texts.rotation, this.m_Rotation); + base.GUIMinMaxGradient(InitialModuleUI.s_Texts.color, this.m_Color); + ModuleUI.GUIFloat(InitialModuleUI.s_Texts.gravity, this.m_GravityModifier); + ModuleUI.GUIFloat(InitialModuleUI.s_Texts.inheritvelocity, this.m_InheritVelocity); + ModuleUI.GUIBoolAsPopup(InitialModuleUI.s_Texts.simulationSpace, this.m_SimulationSpace, InitialModuleUI.s_Texts.simulationSpaces); + bool boolValue2 = this.m_PlayOnAwake.boolValue; + bool flag = ModuleUI.GUIToggle(InitialModuleUI.s_Texts.autoplay, this.m_PlayOnAwake); + if (boolValue2 != flag) + { + this.m_ParticleSystemUI.m_ParticleEffectUI.PlayOnAwakeChanged(flag); + } + ModuleUI.GUIInt(InitialModuleUI.s_Texts.maxParticles, this.m_MaxNumParticles); + } + public override void UpdateCullingSupportedString(ref string text) + { + if (!this.m_SimulationSpace.boolValue) + { + text += "\n\tWorld space simulation is used."; + } + if (this.m_LifeTime.state == MinMaxCurveState.k_TwoCurves || this.m_LifeTime.state == MinMaxCurveState.k_TwoScalars) + { + text += "\n\tStart lifetime is random."; + } + } + } +} diff --git a/UnityEditor/UnityEditor/InitializeOnLoadAttribute.cs b/UnityEditor/UnityEditor/InitializeOnLoadAttribute.cs new file mode 100644 index 00000000..9ddda8d5 --- /dev/null +++ b/UnityEditor/UnityEditor/InitializeOnLoadAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Class)] + public class InitializeOnLoadAttribute : Attribute + { + } +} diff --git a/UnityEditor/UnityEditor/InspectorMode.cs b/UnityEditor/UnityEditor/InspectorMode.cs new file mode 100644 index 00000000..ecfaa2b8 --- /dev/null +++ b/UnityEditor/UnityEditor/InspectorMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum InspectorMode + { + Normal, + Debug, + DebugInternal + } +} diff --git a/UnityEditor/UnityEditor/InspectorState.cs b/UnityEditor/UnityEditor/InspectorState.cs new file mode 100644 index 00000000..9ac57aa2 --- /dev/null +++ b/UnityEditor/UnityEditor/InspectorState.cs @@ -0,0 +1,62 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class InspectorState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetBool(string key, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetBool(string key, bool defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseBool(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetFloat(string key, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float GetFloat(string key, float defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseFloat(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetInt(string key, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetInt(string key, int defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseInt(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetString(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetString(string key, string defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseString(string key); + internal static void SetVector3(string key, Vector3 value) + { + InspectorState.INTERNAL_CALL_SetVector3(key, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetVector3(string key, ref Vector3 value); + internal static Vector3 GetVector3(string key, Vector3 defaultValue) + { + return InspectorState.INTERNAL_CALL_GetVector3(key, ref defaultValue); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_GetVector3(string key, ref Vector3 defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseVector3(string key); + } +} diff --git a/UnityEditor/UnityEditor/InspectorWindow.cs b/UnityEditor/UnityEditor/InspectorWindow.cs new file mode 100644 index 00000000..8972400c --- /dev/null +++ b/UnityEditor/UnityEditor/InspectorWindow.cs @@ -0,0 +1,1139 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class InspectorWindow : EditorWindow, IHasCustomMenu + { + internal class Styles + { + public readonly GUIStyle preToolbar = "preToolbar"; + public readonly GUIStyle preToolbar2 = "preToolbar2"; + public readonly GUIStyle preDropDown = "preDropDown"; + public readonly GUIStyle dragHandle = "RL DragHandle"; + public readonly GUIStyle lockButton = "IN LockButton"; + public readonly GUIContent preTitle = EditorGUIUtility.TextContent("InspectorPreviewTitle"); + public readonly GUIContent labelTitle = EditorGUIUtility.TextContent("InspectorLabelTitle"); + public readonly GUIContent addComponentLabel = new GUIContent("Add Component"); + public GUIStyle preBackground = "preBackground"; + public GUIStyle addComponentArea = EditorStyles.inspectorTitlebar; + public GUIStyle addComponentButtonStyle = "LargeButton"; + public GUIStyle previewMiniLabel = new GUIStyle(EditorStyles.whiteMiniLabel); + public GUIStyle typeSelection = new GUIStyle("PR Label"); + public GUIStyle lockedHeaderButton = "preButton"; + public GUIStyle stickyNote = new GUIStyle("VCS_StickyNote"); + public GUIStyle stickyNoteArrow = new GUIStyle("VCS_StickyNoteArrow"); + public GUIStyle stickyNotePerforce = new GUIStyle("VCS_StickyNoteP4"); + public GUIStyle stickyNoteLabel = new GUIStyle("VCS_StickyNoteLabel"); + public Styles() + { + this.typeSelection.padding.left = 12; + } + } + private const float kBottomToolbarHeight = 17f; + internal const int kInspectorPaddingLeft = 14; + internal const int kInspectorPaddingRight = 4; + public Vector2 m_ScrollPosition; + public InspectorMode m_InspectorMode; + private static readonly List m_AllInspectors = new List(); + private bool m_ResetKeyboardControl; + protected ActiveEditorTracker m_Tracker; + private Editor m_LastInteractedEditor; + private bool m_IsOpenForEdit; + private static InspectorWindow.Styles s_Styles; + [SerializeField] + private PreviewResizer m_PreviewResizer = new PreviewResizer(); + [SerializeField] + private PreviewWindow m_PreviewWindow; + private LabelGUI m_LabelGUI = new LabelGUI(); + private TypeSelectionList m_TypeSelectionList; + private double m_lastRenderedTime; + private List m_Previews; + private IPreviewable m_SelectedPreview; + public static InspectorWindow s_CurrentInspectorWindow; + internal static InspectorWindow.Styles styles + { + get + { + InspectorWindow.Styles arg_17_0; + if ((arg_17_0 = InspectorWindow.s_Styles) == null) + { + arg_17_0 = (InspectorWindow.s_Styles = new InspectorWindow.Styles()); + } + return arg_17_0; + } + } + public bool isLocked + { + get + { + this.CreateTracker(); + return this.m_Tracker.isLocked; + } + set + { + this.CreateTracker(); + this.m_Tracker.isLocked = value; + } + } + private void Awake() + { + if (!InspectorWindow.m_AllInspectors.Contains(this)) + { + InspectorWindow.m_AllInspectors.Add(this); + } + } + private void OnDestroy() + { + if (this.m_PreviewWindow != null) + { + this.m_PreviewWindow.Close(); + } + if (this.m_Tracker != null && !this.m_Tracker.Equals(ActiveEditorTracker.sharedTracker)) + { + this.m_Tracker.Destroy(); + } + } + protected virtual void OnEnable() + { + base.title = ((this.m_InspectorMode != InspectorMode.Normal) ? "UnityEditor.DebugInspectorWindow" : "UnityEditor.InspectorWindow"); + base.minSize = new Vector2(275f, 50f); + if (!InspectorWindow.m_AllInspectors.Contains(this)) + { + InspectorWindow.m_AllInspectors.Add(this); + } + this.m_PreviewResizer.Init("InspectorPreview"); + this.m_LabelGUI.OnEnable(); + } + protected virtual void OnDisable() + { + InspectorWindow.m_AllInspectors.Remove(this); + this.m_LabelGUI.OnDisable(); + } + private void OnLostFocus() + { + EditorGUI.EndEditingActiveTextField(); + this.m_LabelGUI.OnLostFocus(); + } + internal static void RepaintAllInspectors() + { + foreach (InspectorWindow current in InspectorWindow.m_AllInspectors) + { + current.Repaint(); + } + } + internal static List GetInspectors() + { + return InspectorWindow.m_AllInspectors; + } + private void OnSelectionChange() + { + this.m_Previews = null; + this.m_SelectedPreview = null; + this.m_TypeSelectionList = null; + this.m_Parent.ClearKeyboardControl(); + ScriptAttributeUtility.ClearGlobalCache(); + base.Repaint(); + } + public static InspectorWindow[] GetAllInspectorWindows() + { + return InspectorWindow.m_AllInspectors.ToArray(); + } + private void OnInspectorUpdate() + { + if (this.m_Tracker != null) + { + this.m_Tracker.VerifyModifiedMonoBehaviours(); + if (!this.m_Tracker.isDirty) + { + return; + } + } + base.Repaint(); + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Normal"), this.m_InspectorMode == InspectorMode.Normal, new GenericMenu.MenuFunction(this.SetNormal)); + menu.AddItem(new GUIContent("Debug"), this.m_InspectorMode == InspectorMode.Debug, new GenericMenu.MenuFunction(this.SetDebug)); + if (Unsupported.IsDeveloperBuild()) + { + menu.AddItem(new GUIContent("Debug-Internal"), this.m_InspectorMode == InspectorMode.DebugInternal, new GenericMenu.MenuFunction(this.SetDebugInternal)); + } + menu.AddSeparator(string.Empty); + menu.AddItem(new GUIContent("Lock"), this.m_Tracker != null && this.isLocked, new GenericMenu.MenuFunction(this.FlipLocked)); + } + private void SetMode(InspectorMode mode) + { + if (mode == InspectorMode.Normal) + { + base.title = "UnityEditor.InspectorWindow"; + } + else + { + base.title = "UnityEditor.DebugInspectorWindow"; + } + this.m_InspectorMode = mode; + this.CreateTracker(); + this.m_Tracker.inspectorMode = mode; + this.m_ResetKeyboardControl = true; + } + private void SetDebug() + { + this.SetMode(InspectorMode.Debug); + } + private void SetNormal() + { + this.SetMode(InspectorMode.Normal); + } + private void SetDebugInternal() + { + this.SetMode(InspectorMode.DebugInternal); + } + private void FlipLocked() + { + this.isLocked = !this.isLocked; + } + private static void DoInspectorDragAndDrop(Rect rect, UnityEngine.Object[] targets) + { + if (!InspectorWindow.Dragging(rect)) + { + return; + } + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targets, Event.current.type == EventType.DragPerform); + if (Event.current.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + } + } + private static bool Dragging(Rect rect) + { + return (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) && rect.Contains(Event.current.mousePosition); + } + public ActiveEditorTracker GetTracker() + { + this.CreateTracker(); + return this.m_Tracker; + } + protected virtual void CreateTracker() + { + if (this.m_Tracker != null) + { + return; + } + ActiveEditorTracker sharedTracker = ActiveEditorTracker.sharedTracker; + bool flag = InspectorWindow.m_AllInspectors.Any((InspectorWindow i) => i.m_Tracker != null && i.m_Tracker.Equals(sharedTracker)); + this.m_Tracker = ((!flag) ? ActiveEditorTracker.sharedTracker : new ActiveEditorTracker()); + this.m_Tracker.inspectorMode = this.m_InspectorMode; + this.m_Tracker.RebuildIfNecessary(); + } + protected virtual void CreatePreviewables() + { + if (this.m_Previews != null) + { + return; + } + this.m_Previews = new List(); + if (this.m_Tracker.activeEditors.Length == 0) + { + return; + } + Editor[] activeEditors = this.m_Tracker.activeEditors; + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor = activeEditors[i]; + IEnumerable previewsForType = this.GetPreviewsForType(editor); + foreach (IPreviewable current in previewsForType) + { + this.m_Previews.Add(current); + } + } + } + private IEnumerable GetPreviewsForType(Editor editor) + { + List list = new List(); + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = 0; i < loadedAssemblies.Length; i++) + { + Assembly assembly = loadedAssemblies[i]; + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int j = 0; j < array.Length; j++) + { + Type type = array[j]; + if (typeof(IPreviewable).IsAssignableFrom(type)) + { + if (!typeof(Editor).IsAssignableFrom(type)) + { + object[] customAttributes = type.GetCustomAttributes(typeof(CustomPreviewAttribute), false); + object[] array2 = customAttributes; + for (int k = 0; k < array2.Length; k++) + { + CustomPreviewAttribute customPreviewAttribute = (CustomPreviewAttribute)array2[k]; + if (customPreviewAttribute.m_Type == editor.target.GetType()) + { + IPreviewable previewable = Activator.CreateInstance(type) as IPreviewable; + previewable.Initialize(editor.targets); + list.Add(previewable); + } + } + } + } + } + } + return list; + } + protected virtual void ShowButton(Rect r) + { + bool flag = GUI.Toggle(r, this.isLocked, GUIContent.none, InspectorWindow.styles.lockButton); + if (flag != this.isLocked) + { + this.isLocked = flag; + this.m_Tracker.RebuildIfNecessary(); + } + } + protected virtual void OnGUI() + { + Profiler.BeginSample("InspectorWindow.OnGUI"); + this.CreateTracker(); + this.CreatePreviewables(); + this.ResetKeyboardControl(); + this.m_ScrollPosition = EditorGUILayout.BeginVerticalScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); + if (Event.current.type == EventType.Repaint) + { + this.m_Tracker.ClearDirty(); + } + InspectorWindow.s_CurrentInspectorWindow = this; + Editor[] activeEditors = this.m_Tracker.activeEditors; + Profiler.BeginSample("InspectorWindow.DrawEditors()"); + this.DrawEditors(activeEditors); + Profiler.EndSample(); + if (this.m_Tracker.hasComponentsWhichCannotBeMultiEdited) + { + if (activeEditors.Length == 0 && !this.m_Tracker.isLocked && Selection.objects.Length > 0) + { + this.DrawSelectionPickerList(); + } + else + { + Rect rect = GUILayoutUtility.GetRect(10f, 4f, EditorStyles.inspectorTitlebar); + if (Event.current.type == EventType.Repaint) + { + this.DrawSplitLine(rect.y); + } + GUILayout.Label("Components that are only on some of the selected objects cannot be multi-edited.", EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Space(4f); + } + } + InspectorWindow.s_CurrentInspectorWindow = null; + EditorGUI.indentLevel = 0; + this.AddComponentButton(this.m_Tracker.activeEditors); + GUI.enabled = true; + this.CheckDragAndDrop(this.m_Tracker.activeEditors); + this.MoveFocusOnKeyPress(); + GUILayout.EndScrollView(); + Profiler.BeginSample("InspectorWindow.DrawPreviewAndLabels"); + this.DrawPreviewAndLabels(); + Profiler.EndSample(); + if (this.m_Tracker.activeEditors.Length > 0) + { + this.DrawVCSShortInfo(); + } + Profiler.EndSample(); + } + public virtual Editor GetLastInteractedEditor() + { + return this.m_LastInteractedEditor; + } + public IPreviewable GetEditorThatControlsPreview(IPreviewable[] editors) + { + if (editors.Length == 0) + { + return null; + } + if (this.m_SelectedPreview != null) + { + return this.m_SelectedPreview; + } + IPreviewable lastInteractedEditor = this.GetLastInteractedEditor(); + Type type = (lastInteractedEditor == null) ? null : lastInteractedEditor.GetType(); + IPreviewable previewable = null; + IPreviewable previewable2 = null; + for (int i = 0; i < editors.Length; i++) + { + IPreviewable previewable3 = editors[i]; + if (previewable3 != null && !(previewable3.target == null)) + { + if (!EditorUtility.IsPersistent(previewable3.target) || !(AssetDatabase.GetAssetPath(previewable3.target) != AssetDatabase.GetAssetPath(editors[0].target))) + { + if (previewable3.HasPreviewGUI()) + { + if (previewable3 == lastInteractedEditor) + { + return previewable3; + } + if (previewable2 == null && previewable3.GetType() == type) + { + previewable2 = previewable3; + } + if (previewable == null) + { + previewable = previewable3; + } + } + } + } + } + if (previewable2 != null) + { + return previewable2; + } + if (previewable != null) + { + return previewable; + } + return null; + } + public IPreviewable[] GetEditorsWithPreviews(Editor[] editors) + { + IList list = new List(); + int num = -1; + for (int i = 0; i < editors.Length; i++) + { + Editor editor = editors[i]; + num++; + if (!(editor.target == null)) + { + if (!EditorUtility.IsPersistent(editor.target) || !(AssetDatabase.GetAssetPath(editor.target) != AssetDatabase.GetAssetPath(editors[0].target))) + { + if (EditorUtility.IsPersistent(editors[0].target) || !EditorUtility.IsPersistent(editor.target)) + { + if (!this.ShouldCullEditor(editors, num)) + { + if (editor.HasPreviewGUI()) + { + list.Add(editor); + } + } + } + } + } + } + foreach (IPreviewable current in this.m_Previews) + { + if (current.HasPreviewGUI()) + { + list.Add(current); + } + } + return list.ToArray(); + } + public UnityEngine.Object GetInspectedObject() + { + if (this.m_Tracker == null) + { + return null; + } + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(this.m_Tracker.activeEditors); + if (firstNonImportInspectorEditor == null) + { + return null; + } + return firstNonImportInspectorEditor.target; + } + private Editor GetFirstNonImportInspectorEditor(Editor[] editors) + { + for (int i = 0; i < editors.Length; i++) + { + Editor editor = editors[i]; + if (!(editor.target is AssetImporter)) + { + return editor; + } + } + return null; + } + private void MoveFocusOnKeyPress() + { + KeyCode keyCode = Event.current.keyCode; + if (Event.current.type != EventType.KeyDown || (keyCode != KeyCode.DownArrow && keyCode != KeyCode.UpArrow && keyCode != KeyCode.Tab)) + { + return; + } + if (keyCode != KeyCode.Tab) + { + EditorGUIUtility.MoveFocusAndScroll(keyCode == KeyCode.DownArrow); + } + else + { + EditorGUIUtility.ScrollForTabbing(!Event.current.shift); + } + Event.current.Use(); + } + private void ResetKeyboardControl() + { + if (this.m_ResetKeyboardControl) + { + GUIUtility.keyboardControl = 0; + this.m_ResetKeyboardControl = false; + } + } + private void CheckDragAndDrop(Editor[] editors) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + if (rect.Contains(Event.current.mousePosition)) + { + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(editors); + if (firstNonImportInspectorEditor != null) + { + InspectorWindow.DoInspectorDragAndDrop(rect, firstNonImportInspectorEditor.targets); + } + if (Event.current.type == EventType.MouseDown) + { + GUIUtility.keyboardControl = 0; + Event.current.Use(); + } + } + } + private UnityEngine.Object[] GetInspectedAssets() + { + if (this.m_Tracker != null) + { + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(this.m_Tracker.activeEditors); + if (firstNonImportInspectorEditor != null && firstNonImportInspectorEditor != null && firstNonImportInspectorEditor.targets.Length == 1) + { + string assetPath = AssetDatabase.GetAssetPath(firstNonImportInspectorEditor.target); + bool flag = assetPath.ToLower().StartsWith("assets") && !Directory.Exists(assetPath); + if (flag) + { + return firstNonImportInspectorEditor.targets; + } + } + } + return Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + } + private void DrawPreviewAndLabels() + { + if (this.m_PreviewWindow && Event.current.type == EventType.Repaint) + { + this.m_PreviewWindow.Repaint(); + } + IPreviewable[] editorsWithPreviews = this.GetEditorsWithPreviews(this.m_Tracker.activeEditors); + IPreviewable editorThatControlsPreview = this.GetEditorThatControlsPreview(editorsWithPreviews); + bool flag = editorThatControlsPreview != null && editorThatControlsPreview.HasPreviewGUI() && this.m_PreviewWindow == null; + UnityEngine.Object[] inspectedAssets = this.GetInspectedAssets(); + bool flag2 = inspectedAssets.Length > 0; + if (!flag && !flag2) + { + return; + } + Event current = Event.current; + Rect position = EditorGUILayout.BeginHorizontal(GUIContent.none, InspectorWindow.styles.preToolbar, new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + Rect position2 = default(Rect); + GUILayout.FlexibleSpace(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + GUIContent content; + if (flag) + { + GUIContent previewTitle = editorThatControlsPreview.GetPreviewTitle(); + content = (previewTitle ?? InspectorWindow.styles.preTitle); + } + else + { + content = InspectorWindow.styles.labelTitle; + } + position2.x = lastRect.x + 3f; + position2.y = lastRect.y + (17f - InspectorWindow.s_Styles.dragHandle.fixedHeight) / 2f + 1f; + position2.width = lastRect.width - 6f; + position2.height = InspectorWindow.s_Styles.dragHandle.fixedHeight; + if (editorsWithPreviews.Length > 1) + { + Vector2 vector = InspectorWindow.styles.preDropDown.CalcSize(content); + Rect position3 = new Rect(lastRect.x, lastRect.y, vector.x, vector.y); + lastRect.xMin += vector.x; + position2.xMin += vector.x; + GUIContent[] array = new GUIContent[editorsWithPreviews.Length]; + int selected = -1; + for (int i = 0; i < editorsWithPreviews.Length; i++) + { + IPreviewable previewable = editorsWithPreviews[i]; + GUIContent gUIContent = previewable.GetPreviewTitle() ?? InspectorWindow.styles.preTitle; + string text; + if (gUIContent == InspectorWindow.styles.preTitle) + { + string str = ObjectNames.GetTypeName(previewable.target); + if (previewable.target is MonoBehaviour) + { + str = MonoScript.FromMonoBehaviour(previewable.target as MonoBehaviour).GetClass().Name; + } + text = gUIContent.text + " - " + str; + } + else + { + text = gUIContent.text; + } + array[i] = new GUIContent(text); + if (editorsWithPreviews[i] == editorThatControlsPreview) + { + selected = i; + } + } + if (GUI.Button(position3, content, InspectorWindow.styles.preDropDown)) + { + EditorUtility.DisplayCustomMenu(position3, array, selected, new EditorUtility.SelectMenuItemFunction(this.OnPreviewSelected), editorsWithPreviews); + } + } + else + { + position2.xMin = position2.x + InspectorWindow.styles.preToolbar2.CalcSize(content).x + 3f; + GUI.Label(lastRect, content, InspectorWindow.styles.preToolbar2); + } + if (flag && Event.current.type == EventType.Repaint) + { + InspectorWindow.s_Styles.dragHandle.Draw(position2, GUIContent.none, false, false, false, false); + } + if (flag && this.m_PreviewResizer.GetExpandedBeforeDragging()) + { + editorThatControlsPreview.OnPreviewSettings(); + } + EditorGUILayout.EndHorizontal(); + if (current.type == EventType.MouseUp && current.button == 1 && position.Contains(current.mousePosition) && this.m_PreviewWindow == null) + { + this.DetachPreview(); + } + float height; + if (flag) + { + Rect position4 = base.position; + if (EditorSettings.externalVersionControl != ExternalVersionControl.Disabled && EditorSettings.externalVersionControl != ExternalVersionControl.AutoDetect && EditorSettings.externalVersionControl != ExternalVersionControl.Generic) + { + position4.height -= 17f; + } + height = this.m_PreviewResizer.ResizeHandle(position4, 100f, 100f, 17f, lastRect); + } + else + { + if (GUI.Button(position, GUIContent.none, GUIStyle.none)) + { + this.m_PreviewResizer.ToggleExpanded(); + } + height = 0f; + } + if (!this.m_PreviewResizer.GetExpanded()) + { + return; + } + GUILayout.BeginVertical(InspectorWindow.styles.preBackground, new GUILayoutOption[] + { + GUILayout.Height(height) + }); + if (flag) + { + editorThatControlsPreview.DrawPreview(GUILayoutUtility.GetRect(0f, 10240f, 64f, 10240f)); + } + if (flag2) + { + EditorGUI.BeginDisabledGroup(inspectedAssets.Any((UnityEngine.Object a) => EditorUtility.IsPersistent(a) && !AssetDatabase.IsOpenForEdit(a))); + this.m_LabelGUI.OnLabelGUI(inspectedAssets); + EditorGUI.EndDisabledGroup(); + } + GUILayout.EndVertical(); + } + protected UnityEngine.Object[] GetTargetsForPreview(IPreviewable previewEditor) + { + Editor editor = null; + Editor[] activeEditors = this.m_Tracker.activeEditors; + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor2 = activeEditors[i]; + if (editor2.target.GetType() == previewEditor.target.GetType()) + { + editor = editor2; + break; + } + } + return editor.targets; + } + private void OnPreviewSelected(object userData, string[] options, int selected) + { + IPreviewable[] array = userData as IPreviewable[]; + this.m_SelectedPreview = array[selected]; + } + private void DetachPreview() + { + Event.current.Use(); + this.m_PreviewWindow = (ScriptableObject.CreateInstance(typeof(PreviewWindow)) as PreviewWindow); + this.m_PreviewWindow.SetParentInspector(this); + this.m_PreviewWindow.Show(); + base.Repaint(); + GUIUtility.ExitGUI(); + } + protected virtual void DrawVCSSticky(float offset) + { + string empty = string.Empty; + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(this.m_Tracker.activeEditors); + if (!EditorPrefs.GetBool("vcssticky") && !AssetDatabase.IsOpenForEdit(firstNonImportInspectorEditor.target, out empty)) + { + Rect position = new Rect(10f, base.position.height - 94f, base.position.width - 20f, 80f); + position.y -= offset; + if (Event.current.type == EventType.Repaint) + { + InspectorWindow.styles.stickyNote.Draw(position, false, false, false, false); + Rect position2 = new Rect(position.x, position.y + position.height / 2f - 32f, 64f, 64f); + if (EditorSettings.externalVersionControl == "Perforce") + { + InspectorWindow.styles.stickyNotePerforce.Draw(position2, false, false, false, false); + } + Rect position3 = new Rect(position.x + position2.width, position.y, position.width - position2.width, position.height); + GUI.Label(position3, new GUIContent("Under Version Control\nCheck out this asset in order to make changes."), InspectorWindow.styles.stickyNoteLabel); + Rect position4 = new Rect(position.x + position.width / 2f, position.y + 80f, 19f, 14f); + InspectorWindow.styles.stickyNoteArrow.Draw(position4, false, false, false, false); + } + } + } + private void DrawVCSShortInfo() + { + if (EditorSettings.externalVersionControl == ExternalVersionControl.AssetServer) + { + EditorGUILayout.BeginHorizontal(GUIContent.none, InspectorWindow.styles.preToolbar, new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + UnityEngine.Object target = this.GetFirstNonImportInspectorEditor(this.m_Tracker.activeEditors).target; + int controlID = GUIUtility.GetControlID(FocusType.Passive); + GUILayout.FlexibleSpace(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + EditorGUILayout.EndHorizontal(); + AssetInspector.Get().OnAssetStatusGUI(lastRect, controlID, target, InspectorWindow.styles.preToolbar2); + } + if (Provider.isActive && EditorSettings.externalVersionControl != ExternalVersionControl.Disabled && EditorSettings.externalVersionControl != ExternalVersionControl.AutoDetect && EditorSettings.externalVersionControl != ExternalVersionControl.Generic) + { + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(this.m_Tracker.activeEditors); + string assetPath = AssetDatabase.GetAssetPath(firstNonImportInspectorEditor.target); + Asset assetByPath = Provider.GetAssetByPath(assetPath); + if (assetByPath == null || (!assetByPath.path.StartsWith("Assets") && !assetByPath.path.StartsWith("ProjectSettings"))) + { + return; + } + GUILayout.Label(GUIContent.none, InspectorWindow.styles.preToolbar, new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + Rect lastRect2 = GUILayoutUtility.GetLastRect(); + string text = assetByPath.StateToString(); + if (text != string.Empty && (Event.current.type == EventType.Layout || Event.current.type == EventType.Repaint)) + { + Texture2D texture2D = AssetDatabase.GetCachedIcon(assetPath) as Texture2D; + Rect rect = new Rect(lastRect2.x, lastRect2.y, 28f, 16f); + Rect position = rect; + position.x += 6f; + position.width = 16f; + if (texture2D != null) + { + GUI.DrawTexture(position, texture2D); + } + Overlay.DrawOverlay(assetByPath, rect); + Rect position2 = new Rect(lastRect2.x + 26f, lastRect2.y, lastRect2.width - 31f, lastRect2.height); + GUIContent label = GUIContent.Temp(text); + EditorGUI.LabelField(position2, label, InspectorWindow.styles.preToolbar2); + } + string empty = string.Empty; + if (!AssetDatabase.IsOpenForEdit(firstNonImportInspectorEditor.target, out empty)) + { + float num = 66f; + Rect position3 = new Rect(lastRect2.x + lastRect2.width - num, lastRect2.y, num, lastRect2.height); + if (GUI.Button(position3, "Checkout", InspectorWindow.styles.lockedHeaderButton)) + { + EditorPrefs.SetBool("vcssticky", true); + Task task = Provider.Checkout(firstNonImportInspectorEditor.targets, CheckoutMode.Both); + task.SetCompletionAction(CompletionAction.UpdatePendingWindow); + task.Wait(); + base.Repaint(); + } + this.DrawVCSSticky(lastRect2.height / 2f); + } + } + } + private void DrawEditors(Editor[] editors) + { + if (editors.Length == 0) + { + return; + } + UnityEngine.Object inspectedObject = this.GetInspectedObject(); + string empty = string.Empty; + bool forceDirty = false; + if (Event.current.type == EventType.Repaint && inspectedObject != null && this.m_IsOpenForEdit != AssetDatabase.IsOpenForEdit(inspectedObject, out empty)) + { + this.m_IsOpenForEdit = !this.m_IsOpenForEdit; + forceDirty = true; + } + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea != null) + { + dockArea.tabStyle = "dragtabbright"; + } + GUILayout.Space(0f); + if (editors.Length > 1 && editors[0] is AssetImporterInspector) + { + (editors[0] as AssetImporterInspector).m_AssetEditor = editors[1]; + } + bool eyeDropperDirty = Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "EyeDropperUpdate"; + Editor.m_AllowMultiObjectAccess = true; + bool flag = false; + Rect position = default(Rect); + for (int i = 0; i < editors.Length; i++) + { + if (this.ShouldCullEditor(editors, i)) + { + if (Event.current.type == EventType.Repaint) + { + editors[i].isInspectorDirty = false; + } + } + else + { + this.DrawEditor(editors[i], i, forceDirty, ref flag, ref position, eyeDropperDirty); + } + } + EditorGUIUtility.ResetGUIState(); + if (position.height > 0f) + { + GUI.BeginGroup(position); + GUI.Label(new Rect(0f, 0f, position.width, position.height), "Imported Object", "OL Title"); + GUI.EndGroup(); + } + } + private void DrawEditor(Editor editor, int editorIndex, bool forceDirty, ref bool showImportedObjectBarNext, ref Rect importedObjectBarRect, bool eyeDropperDirty) + { + if (editor == null) + { + return; + } + UnityEngine.Object target = editor.target; + GUIUtility.GetControlID(target.GetInstanceID(), FocusType.Passive); + EditorGUIUtility.ResetGUIState(); + GUILayoutGroup topLevel = GUILayoutUtility.current.topLevel; + int visible = this.m_Tracker.GetVisible(editorIndex); + bool flag; + if (visible == -1) + { + flag = InternalEditorUtility.GetIsInspectorExpanded(target); + this.m_Tracker.SetVisible(editorIndex, (!flag) ? 0 : 1); + } + else + { + flag = (visible == 1); + } + bool flag2 = forceDirty || editor.isInspectorDirty || eyeDropperDirty; + if (Event.current.type == EventType.Repaint) + { + editor.isInspectorDirty = false; + } + ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; + bool flag3 = AssetDatabase.IsMainAsset(target) || AssetDatabase.IsSubAsset(target) || editorIndex == 0 || target is Material; + if (flag3) + { + string empty = string.Empty; + bool flag4 = editor.IsOpenForEdit(out empty); + if (showImportedObjectBarNext) + { + showImportedObjectBarNext = false; + GUILayout.Space(15f); + importedObjectBarRect = GUILayoutUtility.GetRect(16f, 16f); + importedObjectBarRect.height = 17f; + } + flag = true; + EditorGUI.BeginDisabledGroup(!flag4); + editor.DrawHeader(); + EditorGUI.EndDisabledGroup(); + } + if (editor.target is AssetImporter) + { + showImportedObjectBarNext = true; + } + bool flag5 = false; + if (editor is GenericInspector && CustomEditorAttributes.FindCustomEditorType(target, false) != null) + { + if (this.m_InspectorMode != InspectorMode.DebugInternal) + { + if (this.m_InspectorMode == InspectorMode.Normal) + { + flag5 = true; + } + else + { + if (target is AssetImporter) + { + flag5 = true; + } + } + } + } + if (!flag3) + { + EditorGUI.BeginDisabledGroup(!editor.IsEnabled()); + bool flag6 = EditorGUILayout.InspectorTitlebar(flag, editor.targets); + if (flag != flag6) + { + this.m_Tracker.SetVisible(editorIndex, (!flag6) ? 0 : 1); + InternalEditorUtility.SetIsInspectorExpanded(target, flag6); + if (flag6) + { + this.m_LastInteractedEditor = editor; + } + else + { + if (this.m_LastInteractedEditor == editor) + { + this.m_LastInteractedEditor = null; + } + } + } + EditorGUI.EndDisabledGroup(); + } + if (flag5 && flag) + { + GUILayout.Label("Multi-object editing not supported.", EditorStyles.helpBox, new GUILayoutOption[0]); + return; + } + EditorGUIUtility.ResetGUIState(); + EditorGUI.BeginDisabledGroup(!editor.IsEnabled()); + GenericInspector genericInspector = editor as GenericInspector; + if (genericInspector) + { + genericInspector.m_InspectorMode = this.m_InspectorMode; + } + EditorGUIUtility.hierarchyMode = true; + EditorGUIUtility.wideMode = (base.position.width > 330f); + ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; + Rect rect = default(Rect); + OptimizedGUIBlock optimizedGUIBlock; + float num; + if (editor.GetOptimizedGUIBlock(flag2, flag, out optimizedGUIBlock, out num)) + { + rect = GUILayoutUtility.GetRect(0f, (!flag) ? 0f : num); + this.HandleLastInteractedEditor(rect, editor); + if (Event.current.type == EventType.Layout) + { + return; + } + if (optimizedGUIBlock.Begin(flag2, rect) && flag) + { + GUI.changed = false; + editor.OnOptimizedInspectorGUI(rect); + } + optimizedGUIBlock.End(); + } + else + { + if (flag) + { + GUIStyle style = (!editor.UseDefaultMargins()) ? GUIStyle.none : EditorStyles.inspectorDefaultMargins; + rect = EditorGUILayout.BeginVertical(style, new GUILayoutOption[0]); + this.HandleLastInteractedEditor(rect, editor); + GUI.changed = false; + try + { + editor.OnInspectorGUI(); + } + catch (Exception ex) + { + if (ex is ExitGUIException) + { + throw; + } + Debug.LogException(ex); + } + EditorGUILayout.EndVertical(); + } + if (Event.current.type == EventType.Used) + { + return; + } + } + EditorGUI.EndDisabledGroup(); + if (GUILayoutUtility.current.topLevel != topLevel) + { + if (!GUILayoutUtility.current.layoutGroups.Contains(topLevel)) + { + Debug.LogError("Expected top level layout group missing! Too many GUILayout.EndScrollView/EndVertical/EndHorizontal?"); + GUIUtility.ExitGUI(); + } + else + { + Debug.LogWarning("Unexpected top level layout group! Missing GUILayout.EndScrollView/EndVertical/EndHorizontal?"); + while (GUILayoutUtility.current.topLevel != topLevel) + { + GUILayoutUtility.EndLayoutGroup(); + } + } + } + this.HandleComponentScreenshot(rect, editor); + } + private void HandleComponentScreenshot(Rect contentRect, Editor editor) + { + if (ScreenShots.s_TakeComponentScreenshot) + { + contentRect.yMin -= 16f; + if (contentRect.Contains(Event.current.mousePosition)) + { + Rect contentRect2 = GUIClip.Unclip(contentRect); + contentRect2.position += this.m_Parent.screenPosition.position; + ScreenShots.ScreenShotComponent(contentRect2, editor.target); + } + } + } + private bool ShouldCullEditor(Editor[] editors, int editorIndex) + { + if (editors[editorIndex].hideInspector) + { + return true; + } + UnityEngine.Object target = editors[editorIndex].target; + if (target is SubstanceImporter || target is ParticleSystemRenderer) + { + return true; + } + if (target.GetType() == typeof(AssetImporter)) + { + return true; + } + if (this.m_InspectorMode == InspectorMode.Normal && editorIndex != 0) + { + AssetImporterInspector assetImporterInspector = editors[0] as AssetImporterInspector; + if (assetImporterInspector != null && !assetImporterInspector.showImportedObject) + { + return true; + } + } + return false; + } + private void DrawSelectionPickerList() + { + if (this.m_TypeSelectionList == null) + { + this.m_TypeSelectionList = new TypeSelectionList(Selection.objects); + } + DockArea dockArea = this.m_Parent as DockArea; + if (dockArea != null) + { + dockArea.tabStyle = "dragtabbright"; + } + GUILayout.Space(0f); + Editor.DrawHeaderGUI(null, Selection.objects.Length + " Objects"); + GUILayout.Label("Narrow the Selection:", EditorStyles.label, new GUILayoutOption[0]); + GUILayout.Space(4f); + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + foreach (TypeSelection current in this.m_TypeSelectionList.typeSelections) + { + Rect rect = GUILayoutUtility.GetRect(16f, 16f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (GUI.Button(rect, current.label, InspectorWindow.styles.typeSelection)) + { + Selection.objects = current.objects; + Event.current.Use(); + } + if (GUIUtility.hotControl == 0) + { + EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link); + } + GUILayout.Space(4f); + } + EditorGUIUtility.SetIconSize(iconSize); + } + private void HandleLastInteractedEditor(Rect componentRect, Editor editor) + { + if (editor != this.m_LastInteractedEditor && Event.current.type == EventType.MouseDown && componentRect.Contains(Event.current.mousePosition)) + { + this.m_LastInteractedEditor = editor; + base.Repaint(); + } + } + private void AddComponentButton(Editor[] editors) + { + Editor firstNonImportInspectorEditor = this.GetFirstNonImportInspectorEditor(editors); + if (firstNonImportInspectorEditor != null && firstNonImportInspectorEditor.target != null && firstNonImportInspectorEditor.target is GameObject && firstNonImportInspectorEditor.IsEnabled()) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent addComponentLabel = InspectorWindow.s_Styles.addComponentLabel; + Rect rect = GUILayoutUtility.GetRect(addComponentLabel, InspectorWindow.styles.addComponentButtonStyle, null); + rect.y += 10f; + rect.x += (rect.width - 230f) / 2f; + rect.width = 230f; + if (Event.current.type == EventType.Repaint) + { + this.DrawSplitLine(rect.y - 11f); + } + Event current = Event.current; + bool flag = false; + EventType type = current.type; + if (type == EventType.ExecuteCommand) + { + string commandName = current.commandName; + if (commandName == "OpenAddComponentDropdown") + { + flag = true; + current.Use(); + } + } + if (EditorGUI.ButtonMouseDown(rect, addComponentLabel, FocusType.Passive, InspectorWindow.styles.addComponentButtonStyle) || flag) + { + if (AddComponentWindow.Show(rect, ( + from o in firstNonImportInspectorEditor.targets + select (GameObject)o).ToArray())) + { + GUIUtility.ExitGUI(); + } + } + EditorGUILayout.EndHorizontal(); + } + } + private void DrawSplitLine(float y) + { + Rect position = new Rect(0f, y, this.m_Pos.width + 1f, 1f); + Rect texCoords = new Rect(0f, 1f, 1f, 1f - 1f / (float)EditorStyles.inspectorTitlebar.normal.background.height); + GUI.DrawTextureWithTexCoords(position, EditorStyles.inspectorTitlebar.normal.background, texCoords); + } + internal static void ShowWindow() + { + EditorWindow.GetWindow(typeof(InspectorWindow)); + } + private void Update() + { + if (this.m_Tracker == null || this.m_Tracker.activeEditors == null) + { + return; + } + bool flag = false; + Editor[] activeEditors = this.m_Tracker.activeEditors; + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor = activeEditors[i]; + if (editor.RequiresConstantRepaint() && !editor.hideInspector) + { + flag = true; + } + } + if (flag && this.m_lastRenderedTime + 0.032999999821186066 < EditorApplication.timeSinceStartup) + { + this.m_lastRenderedTime = EditorApplication.timeSinceStartup; + base.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/InternalMeshUtil.cs b/UnityEditor/UnityEditor/InternalMeshUtil.cs new file mode 100644 index 00000000..cf8be579 --- /dev/null +++ b/UnityEditor/UnityEditor/InternalMeshUtil.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class InternalMeshUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPrimitiveCount(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CalcTriangleCount(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasNormals(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetVertexFormat(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetCachedMeshSurfaceArea(MeshRenderer meshRenderer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetCachedSkinnedMeshSurfaceArea(SkinnedMeshRenderer skinnedMeshRenderer); + } +} diff --git a/UnityEditor/UnityEditor/Joint2DEditorBase.cs b/UnityEditor/UnityEditor/Joint2DEditorBase.cs new file mode 100644 index 00000000..ff067df1 --- /dev/null +++ b/UnityEditor/UnityEditor/Joint2DEditorBase.cs @@ -0,0 +1,142 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class Joint2DEditorBase : Editor + { + public class Styles + { + public readonly GUIStyle anchor = "U2D.pivotDot"; + public readonly GUIStyle anchorActive = "U2D.pivotDotActive"; + public readonly GUIStyle connectedAnchor = "U2D.dragDot"; + public readonly GUIStyle connectedAnchorActive = "U2D.dragDotActive"; + } + protected static Joint2DEditorBase.Styles s_Styles; + protected bool HandleAnchor(ref Vector3 position, bool isConnectedAnchor) + { + if (Joint2DEditorBase.s_Styles == null) + { + Joint2DEditorBase.s_Styles = new Joint2DEditorBase.Styles(); + } + Handles.DrawCapFunction drawFunc = (!isConnectedAnchor) ? new Handles.DrawCapFunction(Joint2DEditorBase.AnchorCap) : new Handles.DrawCapFunction(Joint2DEditorBase.ConnectedAnchorCap); + int id = this.target.GetInstanceID() + ((!isConnectedAnchor) ? 0 : 1); + EditorGUI.BeginChangeCheck(); + position = Handles.Slider2D(id, position, Vector3.back, Vector3.right, Vector3.up, 0f, drawFunc, Vector2.zero); + return EditorGUI.EndChangeCheck(); + } + public static void AnchorCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (controlID == GUIUtility.keyboardControl) + { + Joint2DEditorBase.DrawCap(controlID, position, Joint2DEditorBase.s_Styles.anchorActive); + } + else + { + Joint2DEditorBase.DrawCap(controlID, position, Joint2DEditorBase.s_Styles.anchor); + } + } + public static void ConnectedAnchorCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (controlID == GUIUtility.keyboardControl) + { + Joint2DEditorBase.DrawCap(controlID, position, Joint2DEditorBase.s_Styles.connectedAnchorActive); + } + else + { + Joint2DEditorBase.DrawCap(controlID, position, Joint2DEditorBase.s_Styles.connectedAnchor); + } + } + private static void DrawCap(int controlID, Vector3 position, GUIStyle guiStyle) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Handles.BeginGUI(); + position = HandleUtility.WorldToGUIPoint(position); + float fixedWidth = guiStyle.fixedWidth; + float fixedHeight = guiStyle.fixedHeight; + Rect position2 = new Rect(position.x - fixedWidth / 2f, position.y - fixedHeight / 2f, fixedWidth, fixedHeight); + guiStyle.Draw(position2, GUIContent.none, controlID); + Handles.EndGUI(); + } + public static void DrawAALine(Vector3 start, Vector3 end) + { + Handles.DrawAAPolyLine(new Vector3[] + { + start, + end + }); + } + public static void DrawDistanceGizmo(Vector3 anchor, Vector3 connectedAnchor, float distance) + { + Vector3 normalized = (anchor - connectedAnchor).normalized; + Vector3 vector = connectedAnchor + normalized * distance; + Vector3 vector2 = Vector3.Cross(normalized, Vector3.forward); + vector2 *= HandleUtility.GetHandleSize(connectedAnchor) * 0.16f; + Handles.color = Color.green; + Joint2DEditorBase.DrawAALine(anchor, vector); + Joint2DEditorBase.DrawAALine(connectedAnchor + vector2, connectedAnchor - vector2); + Joint2DEditorBase.DrawAALine(vector + vector2, vector - vector2); + } + private static Matrix4x4 GetAnchorSpaceMatrix(Transform transform) + { + return Matrix4x4.TRS(transform.position, Quaternion.Euler(0f, 0f, transform.rotation.eulerAngles.z), transform.lossyScale); + } + protected static Vector3 TransformPoint(Transform transform, Vector3 position) + { + return Joint2DEditorBase.GetAnchorSpaceMatrix(transform).MultiplyPoint(position); + } + protected static Vector3 InverseTransformPoint(Transform transform, Vector3 position) + { + return Joint2DEditorBase.GetAnchorSpaceMatrix(transform).inverse.MultiplyPoint(position); + } + protected static Vector3 SnapToSprite(SpriteRenderer spriteRenderer, Vector3 position, float snapDistance) + { + if (spriteRenderer == null) + { + return position; + } + snapDistance = HandleUtility.GetHandleSize(position) * snapDistance; + float num = spriteRenderer.sprite.bounds.size.x / 2f; + float num2 = spriteRenderer.sprite.bounds.size.y / 2f; + Vector2[] array = new Vector2[] + { + new Vector2(-num, -num2), + new Vector2(0f, -num2), + new Vector2(num, -num2), + new Vector2(-num, 0f), + new Vector2(0f, 0f), + new Vector2(num, 0f), + new Vector2(-num, num2), + new Vector2(0f, num2), + new Vector2(num, num2) + }; + Vector2[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Vector2 v = array2[i]; + Vector3 vector = spriteRenderer.transform.TransformPoint(v); + if (Vector2.Distance(position, vector) <= snapDistance) + { + return vector; + } + } + return position; + } + protected static Vector3 SnapToPoint(Vector3 position, Vector3 snapPosition, float snapDistance) + { + snapDistance = HandleUtility.GetHandleSize(position) * snapDistance; + return (Vector3.Distance(position, snapPosition) > snapDistance) ? position : snapPosition; + } + protected static Vector2 RotateVector2(Vector2 direction, float angle) + { + float f = 0.0174532924f * -angle; + float num = Mathf.Cos(f); + float num2 = Mathf.Sin(f); + float x = direction.x * num - direction.y * num2; + float y = direction.x * num2 + direction.y * num; + return new Vector2(x, y); + } + } +} diff --git a/UnityEditor/UnityEditor/KeyIdentifier.cs b/UnityEditor/UnityEditor/KeyIdentifier.cs new file mode 100644 index 00000000..b52981a4 --- /dev/null +++ b/UnityEditor/UnityEditor/KeyIdentifier.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class KeyIdentifier + { + public CurveRenderer renderer; + public int curveId; + public int key; + public AnimationCurve curve + { + get + { + return this.renderer.GetCurve(); + } + } + public Keyframe keyframe + { + get + { + return this.curve[this.key]; + } + } + public KeyIdentifier(CurveRenderer _renderer, int _curveId, int _keyIndex) + { + this.renderer = _renderer; + this.curveId = _curveId; + this.key = _keyIndex; + } + } +} diff --git a/UnityEditor/UnityEditor/LODGroupEditor.cs b/UnityEditor/UnityEditor/LODGroupEditor.cs new file mode 100644 index 00000000..3b4c9bc8 --- /dev/null +++ b/UnityEditor/UnityEditor/LODGroupEditor.cs @@ -0,0 +1,1226 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(LODGroup))] + internal class LODGroupEditor : Editor + { + private class Styles + { + public const int kSceneLabelHalfWidth = 100; + public const int kSceneLabelHeight = 45; + public const int kSceneHeaderOffset = 40; + public const int kSliderBarHeight = 30; + public const int kRenderersButtonHeight = 60; + public const int kButtonPadding = 2; + public const int kDeleteButtonSize = 20; + public const int kSelectedLODRangePadding = 3; + public const int kRenderAreaForegroundPadding = 3; + public readonly GUIStyle m_LODSliderBG = "LODSliderBG"; + public readonly GUIStyle m_LODSliderRange = "LODSliderRange"; + public readonly GUIStyle m_LODSliderRangeSelected = "LODSliderRangeSelected"; + public readonly GUIStyle m_LODSliderText = "LODSliderText"; + public readonly GUIStyle m_LODSliderTextSelected = "LODSliderTextSelected"; + public readonly GUIStyle m_LODStandardButton = "Button"; + public readonly GUIStyle m_LODRendererButton = "LODRendererButton"; + public readonly GUIStyle m_LODRendererAddButton = "LODRendererAddButton"; + public readonly GUIStyle m_LODRendererRemove = "LODRendererRemove"; + public readonly GUIStyle m_LODBlackBox = "LODBlackBox"; + public readonly GUIStyle m_LODCameraLine = "LODCameraLine"; + public readonly GUIStyle m_LODSceneText = "LODSceneText"; + public readonly GUIStyle m_LODRenderersText = "LODRenderersText"; + public readonly GUIStyle m_LODLevelNotifyText = "LODLevelNotifyText"; + public readonly GUIContent m_IconRendererPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add New Renderers"); + public readonly GUIContent m_IconRendererMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove Renderer"); + public readonly GUIContent m_CameraIcon = EditorGUIUtility.IconContent("Camera Icon"); + public readonly GUIContent m_UploadToImporter = new GUIContent("Upload to Importer", "Upload the modified screen percentages to the model importer."); + public readonly GUIContent m_UploadToImporterDisabled = new GUIContent("Upload to Importer", "Number of LOD's in the scene instance differ from the number of LOD's in the imported model."); + public readonly GUIContent m_RecalculateBounds = new GUIContent("Bounds", "Recalculate bounds for the current LOD group."); + public readonly GUIContent m_LightmapScale = new GUIContent("Lightmap Scale", "Set the lightmap scale to match the LOD percentages"); + public readonly GUIContent m_RendersTitle = new GUIContent("Renderers:"); + } + private class LODInfo + { + private float m_ScreenPercentage; + public readonly int m_LODLevel; + public Rect m_ButtonPosition; + public Rect m_RangePosition; + public float ScreenPercent + { + get + { + return LODGroupEditor.DelinearizeScreenPercentage(this.m_ScreenPercentage); + } + set + { + this.m_ScreenPercentage = LODGroupEditor.LinearizeScreenPercentage(value); + } + } + public float RawScreenPercent + { + get + { + return this.m_ScreenPercentage; + } + } + public LODInfo(int lodLevel, float screenPercentage) + { + this.m_LODLevel = lodLevel; + this.m_ScreenPercentage = screenPercentage; + } + } + private class LODAction + { + public delegate void Callback(); + private readonly float m_Percentage; + private readonly List m_LODs; + private readonly Vector2 m_ClickedPosition; + private readonly SerializedObject m_ObjectRef; + private readonly LODGroupEditor.LODAction.Callback m_Callback; + public LODAction(List loDs, float percentage, Vector2 clickedPosition, SerializedObject objectRef, LODGroupEditor.LODAction.Callback callback) + { + this.m_LODs = loDs; + this.m_Percentage = percentage; + this.m_ClickedPosition = clickedPosition; + this.m_ObjectRef = objectRef; + this.m_Callback = callback; + } + public void InsertLOD() + { + SerializedProperty serializedProperty = this.m_ObjectRef.FindProperty("m_LODs"); + if (!serializedProperty.isArray) + { + return; + } + int num = -1; + foreach (LODGroupEditor.LODInfo current in this.m_LODs) + { + if (this.m_Percentage > current.RawScreenPercent) + { + num = current.m_LODLevel; + break; + } + } + if (num < 0) + { + serializedProperty.InsertArrayElementAtIndex(this.m_LODs.Count); + num = this.m_LODs.Count; + } + else + { + serializedProperty.InsertArrayElementAtIndex(num); + } + SerializedProperty serializedProperty2 = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", num)); + serializedProperty2.arraySize = 0; + SerializedProperty arrayElementAtIndex = serializedProperty.GetArrayElementAtIndex(num); + arrayElementAtIndex.FindPropertyRelative("screenRelativeHeight").floatValue = this.m_Percentage; + if (this.m_Callback != null) + { + this.m_Callback(); + } + this.m_ObjectRef.ApplyModifiedProperties(); + } + public void DeleteLOD() + { + if (this.m_LODs.Count <= 0) + { + return; + } + foreach (LODGroupEditor.LODInfo current in this.m_LODs) + { + int arraySize = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", current.m_LODLevel)).arraySize; + if (current.m_RangePosition.Contains(this.m_ClickedPosition) && (arraySize == 0 || EditorUtility.DisplayDialog("Delete LOD", "Are you sure you wish to delete this LOD?", "Yes", "No"))) + { + SerializedProperty serializedProperty = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}]", current.m_LODLevel)); + serializedProperty.DeleteCommand(); + this.m_ObjectRef.ApplyModifiedProperties(); + if (this.m_Callback != null) + { + this.m_Callback(); + } + break; + } + } + } + } + private class LODLightmapScale + { + public readonly float m_Scale; + public readonly List m_Renderers; + public LODLightmapScale(float scale, List renderers) + { + this.m_Scale = scale; + this.m_Renderers = renderers; + } + } + private const string kLODRootPath = "m_LODs"; + private const string kLODDataPath = "m_LODs.Array.data[{0}]"; + private const string kPixelHeightDataPath = "m_LODs.Array.data[{0}].screenRelativeHeight"; + private const string kRenderRootPath = "m_LODs.Array.data[{0}].renderers"; + private static readonly Color[] kLODColors = new Color[] + { + new Color(0.4831376f, 0.6211768f, 0.0219608f, 1f), + new Color(0.279216f, 0.4078432f, 0.5835296f, 1f), + new Color(0.2070592f, 0.5333336f, 0.6556864f, 1f), + new Color(0.5333336f, 0.16f, 0.0282352f, 1f), + new Color(0.3827448f, 0.2886272f, 0.5239216f, 1f), + new Color(0.8f, 0.4423528f, 0f, 1f), + new Color(0.4486272f, 0.4078432f, 0.050196f, 1f), + new Color(0.7749016f, 0.6368624f, 0.0250984f, 1f) + }; + private static readonly Color kCulledLODColor = new Color(0.4f, 0f, 0f, 1f); + private static LODGroupEditor.Styles s_Styles; + private SerializedObject m_Object; + private int m_SelectedLODSlider = -1; + private int m_SelectedLOD = -1; + private int m_NumberOfLODs; + private bool m_IsPrefab; + private Vector3 m_LastCameraPos = Vector3.zero; + private readonly int m_LODSliderId = "LODSliderIDHash".GetHashCode(); + private readonly int m_CameraSliderId = "LODCameraIDHash".GetHashCode(); + private PreviewRenderUtility m_PreviewUtility; + private static readonly GUIContent[] kSLightIcons = new GUIContent[2]; + private Vector2 m_PreviewDir = new Vector2(0f, -20f); + private int activeLOD + { + get + { + return this.m_SelectedLOD; + } + } + private void OnEnable() + { + this.m_Object = new SerializedObject(this.target); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + PrefabType prefabType = PrefabUtility.GetPrefabType(((LODGroup)this.target).gameObject); + if (prefabType == PrefabType.Prefab || prefabType == PrefabType.ModelPrefab) + { + this.m_IsPrefab = true; + } + else + { + this.m_IsPrefab = false; + } + base.Repaint(); + } + private void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + private static Rect CalculateScreenRect(IEnumerable points) + { + List list = ( + from p in points + select HandleUtility.WorldToGUIPoint(p)).ToList(); + Vector2 vector = new Vector2(3.40282347E+38f, 3.40282347E+38f); + Vector2 vector2 = new Vector2(-3.40282347E+38f, -3.40282347E+38f); + foreach (Vector2 current in list) + { + vector.x = ((current.x >= vector.x) ? vector.x : current.x); + vector2.x = ((current.x <= vector2.x) ? vector2.x : current.x); + vector.y = ((current.y >= vector.y) ? vector.y : current.y); + vector2.y = ((current.y <= vector2.y) ? vector2.y : current.y); + } + return new Rect(vector.x, vector.y, vector2.x - vector.x, vector2.y - vector.y); + } + public void OnSceneGUI() + { + if (!Application.HasAdvancedLicense() || Event.current.type != EventType.Repaint || Camera.current == null || SceneView.lastActiveSceneView != SceneView.currentDrawingSceneView || Vector3.Dot(Camera.current.transform.forward, (Camera.current.transform.position - ((LODGroup)this.target).transform.position).normalized) > 0f) + { + return; + } + if (LODGroupEditor.s_Styles == null) + { + LODGroupEditor.s_Styles = new LODGroupEditor.Styles(); + } + Camera camera = SceneView.lastActiveSceneView.camera; + LODGroup lODGroup = this.target as LODGroup; + Vector3 vector = lODGroup.transform.TransformPoint(lODGroup.localReferencePoint); + LODVisualizationInformation lODVisualizationInformation = LODUtility.CalculateVisualizationData(camera, lODGroup, -1); + float worldSpaceSize = lODVisualizationInformation.worldSpaceSize; + Handles.color = ((lODVisualizationInformation.activeLODLevel == -1) ? LODGroupEditor.kCulledLODColor : LODGroupEditor.kLODColors[lODVisualizationInformation.activeLODLevel]); + Handles.SelectionFrame(0, vector, camera.transform.rotation, worldSpaceSize / 2f); + Vector3 b = camera.transform.right * worldSpaceSize / 2f; + Vector3 b2 = camera.transform.up * worldSpaceSize / 2f; + Rect position = LODGroupEditor.CalculateScreenRect(new Vector3[] + { + vector - b + b2, + vector - b - b2, + vector + b + b2, + vector + b - b2 + }); + float num = position.x + position.width / 2f; + position = new Rect(num - 100f, position.yMax, 200f, 45f); + if (position.yMax > (float)(Screen.height - 45)) + { + position.y = (float)(Screen.height - 45 - 40); + } + Handles.BeginGUI(); + GUI.Label(position, GUIContent.none, EditorStyles.notificationBackground); + EditorGUI.DoDropShadowLabel(position, GUIContent.Temp((lODVisualizationInformation.activeLODLevel < 0) ? "Culled" : ("LOD " + lODVisualizationInformation.activeLODLevel)), LODGroupEditor.s_Styles.m_LODLevelNotifyText, 0.3f); + Handles.EndGUI(); + } + public void Update() + { + if (SceneView.lastActiveSceneView == null || SceneView.lastActiveSceneView.camera == null) + { + return; + } + if (!Mathf.Approximately(0f, Vector3.Distance(SceneView.lastActiveSceneView.camera.transform.position, this.m_LastCameraPos))) + { + this.m_LastCameraPos = SceneView.lastActiveSceneView.camera.transform.position; + base.Repaint(); + } + } + private static float DelinearizeScreenPercentage(float percentage) + { + if (Mathf.Approximately(0f, percentage)) + { + return 0f; + } + return Mathf.Sqrt(percentage); + } + private static float LinearizeScreenPercentage(float percentage) + { + return percentage * percentage; + } + private ModelImporter GetImporter() + { + return AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(this.target))) as ModelImporter; + } + public override void OnInspectorGUI() + { + bool enabled = GUI.enabled; + if (!Application.HasAdvancedLicense()) + { + EditorGUILayout.HelpBox("LOD only available in Unity Pro", MessageType.Warning); + GUI.enabled = false; + } + if (LODGroupEditor.s_Styles == null) + { + LODGroupEditor.s_Styles = new LODGroupEditor.Styles(); + } + this.m_Object.Update(); + this.m_NumberOfLODs = this.m_Object.FindProperty("m_LODs").arraySize; + if (this.m_NumberOfLODs > 0 && this.activeLOD >= 0) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + for (int i = serializedProperty.arraySize - 1; i >= 0; i--) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("renderer"); + Renderer x = serializedProperty2.objectReferenceValue as Renderer; + if (x == null) + { + serializedProperty.DeleteArrayElementAtIndex(i); + } + } + } + GUILayout.Space(17f); + Rect rect = GUILayoutUtility.GetRect(0f, 30f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + List list = new List(); + float num = -1f; + for (int j = 0; j < this.m_NumberOfLODs; j++) + { + SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", j)); + LODGroupEditor.LODInfo lODInfo = new LODGroupEditor.LODInfo(j, serializedProperty3.floatValue); + lODInfo.m_ButtonPosition = LODGroupEditor.CalcLODButton(rect, lODInfo.ScreenPercent); + float startPercent = (j - 1 >= 0) ? num : 1f; + lODInfo.m_RangePosition = LODGroupEditor.CalcLODRange(rect, startPercent, lODInfo.ScreenPercent); + num = lODInfo.ScreenPercent; + list.Add(lODInfo); + } + GUILayout.Space(8f); + this.DrawLODLevelSlider(rect, list); + GUILayout.Space(8f); + GUILayout.Label(string.Format("LODBias of {0:0.00} active", QualitySettings.lodBias), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (this.m_NumberOfLODs > 0 && this.activeLOD >= 0 && this.activeLOD < this.m_NumberOfLODs) + { + this.DrawRenderersInfo(Screen.width / 60); + } + GUILayout.Space(8f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Recalculate:", EditorStyles.boldLabel, new GUILayoutOption[0]); + if (GUILayout.Button(LODGroupEditor.s_Styles.m_RecalculateBounds, new GUILayoutOption[0])) + { + LODUtility.CalculateLODGroupBoundingBox(this.target as LODGroup); + } + if (GUILayout.Button(LODGroupEditor.s_Styles.m_LightmapScale, new GUILayoutOption[0])) + { + this.SendPercentagesToLightmapScale(); + } + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + bool flag = PrefabUtility.GetPrefabType(this.target) == PrefabType.ModelPrefabInstance; + if (flag) + { + ModelImporter importer = this.GetImporter(); + SerializedObject serializedObject = new SerializedObject(importer); + SerializedProperty serializedProperty4 = serializedObject.FindProperty("m_LODScreenPercentages"); + bool flag2 = serializedProperty4.isArray && serializedProperty4.arraySize == list.Count; + bool enabled2 = GUI.enabled; + if (!flag2) + { + GUI.enabled = false; + } + if (importer != null && GUILayout.Button((!flag2) ? LODGroupEditor.s_Styles.m_UploadToImporterDisabled : LODGroupEditor.s_Styles.m_UploadToImporter, new GUILayoutOption[0])) + { + for (int k = 0; k < serializedProperty4.arraySize; k++) + { + serializedProperty4.GetArrayElementAtIndex(k).floatValue = list[k].RawScreenPercent; + } + serializedObject.ApplyModifiedProperties(); + AssetDatabase.ImportAsset(importer.assetPath); + } + GUI.enabled = enabled2; + } + this.m_Object.ApplyModifiedProperties(); + GUI.enabled = enabled; + } + private void DrawRenderersInfo(int horizontalNumber) + { + Rect rect = GUILayoutUtility.GetRect(LODGroupEditor.s_Styles.m_RendersTitle, LODGroupEditor.s_Styles.m_LODSliderTextSelected); + if (Event.current.type == EventType.Repaint) + { + EditorStyles.label.Draw(rect, LODGroupEditor.s_Styles.m_RendersTitle, false, false, false, false); + } + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + int num = serializedProperty.arraySize + 1; + int num2 = Mathf.CeilToInt((float)num / (float)horizontalNumber); + Rect rect2 = GUILayoutUtility.GetRect(0f, (float)(num2 * 60), new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + Rect rect3 = rect2; + GUI.Box(rect2, GUIContent.none); + rect3.width -= 6f; + rect3.x += 3f; + float num3 = rect3.width / (float)horizontalNumber; + List list = new List(); + for (int i = 0; i < num2; i++) + { + int num4 = 0; + while (num4 < horizontalNumber && i * horizontalNumber + num4 < serializedProperty.arraySize) + { + Rect rect4 = new Rect(2f + rect3.x + (float)num4 * num3, 2f + rect3.y + (float)(i * 60), num3 - 4f, 56f); + list.Add(rect4); + this.DrawRendererButton(rect4, i * horizontalNumber + num4); + num4++; + } + } + if (this.m_IsPrefab) + { + return; + } + int num5 = (num - 1) % horizontalNumber; + int num6 = num2 - 1; + this.HandleAddRenderer(new Rect(2f + rect3.x + (float)num5 * num3, 2f + rect3.y + (float)(num6 * 60), num3 - 4f, 56f), list, rect2); + } + private void HandleAddRenderer(Rect position, IEnumerable alreadyDrawn, Rect drawArea) + { + Event evt = Event.current; + EventType type = evt.type; + switch (type) + { + case EventType.Repaint: + LODGroupEditor.s_Styles.m_LODStandardButton.Draw(position, GUIContent.none, false, false, false, false); + LODGroupEditor.s_Styles.m_LODRendererAddButton.Draw(new Rect(position.x - 2f, position.y, position.width, position.height), "Add", false, false, false, false); + return; + case EventType.Layout: + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + IL_4A: + if (type != EventType.MouseDown) + { + return; + } + if (position.Contains(evt.mousePosition)) + { + evt.Use(); + int hashCode = "LODGroupSelector".GetHashCode(); + ObjectSelector.get.Show(null, typeof(Renderer), null, true); + ObjectSelector.get.objectSelectorID = hashCode; + GUIUtility.ExitGUI(); + } + return; + case EventType.DragUpdated: + case EventType.DragPerform: + { + bool flag = false; + if (drawArea.Contains(evt.mousePosition) && alreadyDrawn.All((Rect x) => !x.Contains(evt.mousePosition))) + { + flag = true; + } + if (!flag) + { + return; + } + if (DragAndDrop.objectReferences.Count() > 0) + { + DragAndDrop.visualMode = ((!this.m_IsPrefab) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None); + if (evt.type == EventType.DragPerform) + { + IEnumerable selectedGameObjects = + from go in DragAndDrop.objectReferences + where go as GameObject != null + select go as GameObject; + IEnumerable renderers = this.GetRenderers(selectedGameObjects, true); + this.AddGameObjectRenderers(renderers, true); + DragAndDrop.AcceptDrag(); + evt.Use(); + return; + } + } + evt.Use(); + return; + } + case EventType.ExecuteCommand: + { + string commandName = evt.commandName; + if (commandName == "ObjectSelectorClosed" && ObjectSelector.get.objectSelectorID == "LODGroupSelector".GetHashCode()) + { + this.AddGameObjectRenderers(this.GetRenderers(new List + { + ObjectSelector.GetCurrentObject() as GameObject + }, true), true); + evt.Use(); + GUIUtility.ExitGUI(); + } + return; + } + } + goto IL_4A; + } + private void DrawRendererButton(Rect position, int rendererIndex) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(rendererIndex).FindPropertyRelative("renderer"); + Renderer renderer = serializedProperty2.objectReferenceValue as Renderer; + Rect position2 = new Rect(position.xMax - 20f, position.yMax - 20f, 20f, 20f); + Event current = Event.current; + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + if (renderer != null) + { + MeshFilter component = renderer.GetComponent(); + GUIContent content; + if (component != null && component.sharedMesh != null) + { + content = new GUIContent(AssetPreview.GetAssetPreview(component.sharedMesh), renderer.gameObject.name); + } + else + { + if (renderer is SkinnedMeshRenderer) + { + content = new GUIContent(AssetPreview.GetAssetPreview((renderer as SkinnedMeshRenderer).sharedMesh), renderer.gameObject.name); + } + else + { + content = new GUIContent(ObjectNames.NicifyVariableName(renderer.GetType().Name), renderer.gameObject.name); + } + } + LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); + GUIStyle gUIStyle = "LODRendererButton"; + gUIStyle.Draw(new Rect(position.x + 2f, position.y + 2f, position.width - 4f, position.height - 4f), content, false, false, false, false); + } + else + { + LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); + LODGroupEditor.s_Styles.m_LODRendererButton.Draw(position, "", false, false, false, false); + } + if (!this.m_IsPrefab) + { + LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position2, GUIContent.none, false, false, false, false); + LODGroupEditor.s_Styles.m_LODRendererRemove.Draw(position2, LODGroupEditor.s_Styles.m_IconRendererMinus, false, false, false, false); + } + } + } + else + { + if (!this.m_IsPrefab && position2.Contains(current.mousePosition)) + { + serializedProperty.DeleteArrayElementAtIndex(rendererIndex); + current.Use(); + this.m_Object.ApplyModifiedProperties(); + LODUtility.CalculateLODGroupBoundingBox(this.target as LODGroup); + } + else + { + if (position.Contains(current.mousePosition)) + { + EditorGUIUtility.PingObject(renderer); + current.Use(); + } + } + } + } + private IEnumerable GetRenderers(IEnumerable selectedGameObjects, bool searchChildren) + { + LODGroup lodGroup = this.target as LODGroup; + if (lodGroup == null || EditorUtility.IsPersistent(lodGroup)) + { + return new List(); + } + IEnumerable enumerable = + from go in selectedGameObjects + where go.transform.IsChildOf(lodGroup.transform) + select go; + IEnumerable enumerable2 = + from go in selectedGameObjects + where !go.transform.IsChildOf(lodGroup.transform) + select go; + List list = new List(); + if (enumerable2.Count() > 0 && EditorUtility.DisplayDialog("Reparent GameObjects", "Some objects are not children of the LODGroup GameObject. Do you want to reparent them and add them to the LODGroup?", "Yes, Reparent", "No, Use Only Existing Children")) + { + foreach (GameObject current in enumerable2) + { + if (EditorUtility.IsPersistent(current)) + { + GameObject gameObject = UnityEngine.Object.Instantiate(current) as GameObject; + if (gameObject != null) + { + gameObject.transform.parent = lodGroup.transform; + gameObject.transform.localPosition = Vector3.zero; + gameObject.transform.localRotation = Quaternion.identity; + list.Add(gameObject); + } + } + else + { + current.transform.parent = lodGroup.transform; + list.Add(current); + } + } + enumerable = enumerable.Union(list); + } + List list2 = new List(); + foreach (GameObject current2 in enumerable) + { + if (searchChildren) + { + list2.AddRange(current2.GetComponentsInChildren()); + } + else + { + list2.Add(current2.GetComponent()); + } + } + IEnumerable collection = + from go in DragAndDrop.objectReferences + where go as Renderer != null + select go as Renderer; + list2.AddRange(collection); + return list2; + } + private void AddGameObjectRenderers(IEnumerable toAdd, bool add) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + if (!add) + { + serializedProperty.ClearArray(); + } + List list = new List(); + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("renderer"); + Renderer renderer = serializedProperty2.objectReferenceValue as Renderer; + if (!(renderer == null)) + { + list.Add(renderer); + } + } + foreach (Renderer current in toAdd) + { + if (!list.Contains(current)) + { + serializedProperty.arraySize++; + serializedProperty.GetArrayElementAtIndex(serializedProperty.arraySize - 1).FindPropertyRelative("renderer").objectReferenceValue = current; + list.Add(current); + } + } + this.m_Object.ApplyModifiedProperties(); + LODUtility.CalculateLODGroupBoundingBox(this.target as LODGroup); + } + private void DeletedLOD() + { + this.m_SelectedLOD--; + } + private static void UpdateCamera(float desiredPercentage, LODGroup group) + { + Vector3 position = group.transform.TransformPoint(group.localReferencePoint); + float num = LODUtility.CalculateDistance(SceneView.lastActiveSceneView.camera, (desiredPercentage > 0f) ? desiredPercentage : 1E-06f, group); + if (SceneView.lastActiveSceneView.camera.orthographic) + { + num = Mathf.Sqrt(num * num * (1f + SceneView.lastActiveSceneView.camera.aspect)); + } + SceneView.lastActiveSceneView.LookAtDirect(position, SceneView.lastActiveSceneView.camera.transform.rotation, num); + } + private void UpdateSelectedLODFromCamera(IEnumerable lods, float cameraPercent) + { + foreach (LODGroupEditor.LODInfo current in lods) + { + if (cameraPercent > current.RawScreenPercent) + { + this.m_SelectedLOD = current.m_LODLevel; + break; + } + } + } + private static float GetCameraPercentForCurrentQualityLevel(float clickPosition, float sliderStart, float sliderWidth) + { + float percentage = Mathf.Clamp(1f - (clickPosition - sliderStart) / sliderWidth, 0.01f, 1f); + return LODGroupEditor.LinearizeScreenPercentage(percentage); + } + private void DrawLODLevelSlider(Rect sliderPosition, List lods) + { + int controlID = GUIUtility.GetControlID(this.m_LODSliderId, FocusType.Passive); + int controlID2 = GUIUtility.GetControlID(this.m_CameraSliderId, FocusType.Passive); + Event current = Event.current; + LODGroup lODGroup = this.target as LODGroup; + if (lODGroup == null) + { + return; + } + EventType typeForControl = current.GetTypeForControl(controlID); + switch (typeForControl) + { + case EventType.MouseDown: + { + if (current.button == 1 && sliderPosition.Contains(current.mousePosition)) + { + float num = LODGroupEditor.CalculatePercentageFromBar(sliderPosition, current.mousePosition); + GenericMenu genericMenu = new GenericMenu(); + if (lods.Count >= 8) + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("Insert Before")); + } + else + { + genericMenu.AddItem(EditorGUIUtility.TextContent("Insert Before"), false, new GenericMenu.MenuFunction(new LODGroupEditor.LODAction(lods, LODGroupEditor.LinearizeScreenPercentage(num), current.mousePosition, this.m_Object, null).InsertLOD)); + } + bool flag = true; + if (lods.Count > 0 && lods[lods.Count - 1].ScreenPercent < num) + { + flag = false; + } + if (flag) + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("Delete")); + } + else + { + genericMenu.AddItem(EditorGUIUtility.TextContent("Delete"), false, new GenericMenu.MenuFunction(new LODGroupEditor.LODAction(lods, LODGroupEditor.LinearizeScreenPercentage(num), current.mousePosition, this.m_Object, new LODGroupEditor.LODAction.Callback(this, ldftn(DeletedLOD))).DeleteLOD)); + } + genericMenu.ShowAsContext(); + bool flag2 = false; + foreach (LODGroupEditor.LODInfo current2 in lods) + { + if (current2.m_RangePosition.Contains(current.mousePosition)) + { + this.m_SelectedLOD = current2.m_LODLevel; + flag2 = true; + break; + } + } + if (!flag2) + { + this.m_SelectedLOD = -1; + } + current.Use(); + goto IL_851; + } + Rect rect = sliderPosition; + rect.x -= 5f; + rect.width += 10f; + if (rect.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + bool flag3 = false; + IOrderedEnumerable collection = + from lod in lods + where lod.ScreenPercent > 0.5f + select lod into x + orderby x.m_LODLevel descending + select x; + IOrderedEnumerable collection2 = + from lod in lods + where lod.ScreenPercent <= 0.5f + select lod into x + orderby x.m_LODLevel + select x; + List list = new List(); + list.AddRange(collection); + list.AddRange(collection2); + foreach (LODGroupEditor.LODInfo current3 in list) + { + if (current3.m_ButtonPosition.Contains(current.mousePosition)) + { + this.m_SelectedLODSlider = current3.m_LODLevel; + flag3 = true; + if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) + { + LODGroupEditor.UpdateCamera(current3.RawScreenPercent + 0.001f, lODGroup); + SceneView.lastActiveSceneView.ClearSearchFilter(); + SceneView.lastActiveSceneView.SetSceneViewFiltering(true); + HierarchyProperty.FilterSingleSceneObject(lODGroup.gameObject.GetInstanceID(), false); + SceneView.RepaintAll(); + } + break; + } + } + if (!flag3) + { + foreach (LODGroupEditor.LODInfo current4 in lods) + { + if (current4.m_RangePosition.Contains(current.mousePosition)) + { + this.m_SelectedLOD = current4.m_LODLevel; + break; + } + } + } + } + goto IL_851; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + this.m_SelectedLODSlider = -1; + if (SceneView.lastActiveSceneView != null) + { + SceneView.lastActiveSceneView.SetSceneViewFiltering(false); + SceneView.lastActiveSceneView.ClearSearchFilter(); + } + current.Use(); + } + goto IL_851; + case EventType.MouseMove: + case EventType.KeyDown: + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Layout: + IL_75: + if (typeForControl != EventType.DragExited) + { + goto IL_851; + } + current.Use(); + goto IL_851; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && this.m_SelectedLODSlider >= 0 && lods[this.m_SelectedLODSlider] != null) + { + current.Use(); + float num2 = Mathf.Clamp01(1f - (current.mousePosition.x - sliderPosition.x) / sliderPosition.width); + this.SetSelectedLODLevelPercentage(num2 - 0.001f, lods); + if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) + { + LODGroupEditor.UpdateCamera(LODGroupEditor.LinearizeScreenPercentage(num2), lODGroup); + SceneView.RepaintAll(); + } + } + goto IL_851; + case EventType.Repaint: + { + Rect rect2 = sliderPosition; + rect2.width += 2f; + rect2.height += 2f; + rect2.center -= new Vector2(1f, 1f); + LODGroupEditor.s_Styles.m_LODSliderBG.Draw(sliderPosition, GUIContent.none, false, false, false, false); + for (int i = 0; i < lods.Count; i++) + { + LODGroupEditor.LODInfo currentLOD = lods[i]; + this.DrawLODRange(currentLOD, (i != 0) ? lods[i - 1].RawScreenPercent : 1f); + LODGroupEditor.DrawLODButton(currentLOD); + } + LODGroupEditor.DrawCulledRange(sliderPosition, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].RawScreenPercent); + goto IL_851; + } + case EventType.DragUpdated: + case EventType.DragPerform: + { + int num3 = -2; + foreach (LODGroupEditor.LODInfo current5 in lods) + { + if (current5.m_RangePosition.Contains(current.mousePosition)) + { + num3 = current5.m_LODLevel; + break; + } + } + if (num3 == -2 && LODGroupEditor.GetCulledBox(sliderPosition, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].ScreenPercent).Contains(current.mousePosition)) + { + num3 = -1; + } + if (num3 >= -1) + { + this.m_SelectedLOD = num3; + if (DragAndDrop.objectReferences.Count() > 0) + { + DragAndDrop.visualMode = ((!this.m_IsPrefab) ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.None); + if (current.type == EventType.DragPerform) + { + IEnumerable selectedGameObjects = + from go in DragAndDrop.objectReferences + where go as GameObject != null + select go as GameObject; + IEnumerable renderers = this.GetRenderers(selectedGameObjects, true); + if (num3 == -1) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty("m_LODs"); + serializedProperty.arraySize++; + SerializedProperty serializedProperty2 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count)); + if (lods.Count == 0) + { + serializedProperty2.floatValue = 0.5f; + } + else + { + SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count - 1)); + serializedProperty2.floatValue = serializedProperty3.floatValue / 2f; + } + this.m_SelectedLOD = lods.Count; + this.AddGameObjectRenderers(renderers, false); + } + else + { + this.AddGameObjectRenderers(renderers, true); + } + DragAndDrop.AcceptDrag(); + } + } + current.Use(); + goto IL_851; + } + goto IL_851; + } + } + goto IL_75; + IL_851: + if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) + { + Camera camera = SceneView.lastActiveSceneView.camera; + float num4 = LODUtility.CalculateVisualizationData(camera, lODGroup, -1).activeRelativeScreenSize / QualitySettings.lodBias; + float value = LODGroupEditor.DelinearizeScreenPercentage(num4); + Vector3 normalized = (SceneView.lastActiveSceneView.camera.transform.position - ((LODGroup)this.target).transform.position).normalized; + if (Vector3.Dot(camera.transform.forward, normalized) > 0f) + { + value = 1f; + } + Rect rect3 = LODGroupEditor.CalcLODButton(sliderPosition, Mathf.Clamp01(value)); + Rect position = new Rect(rect3.center.x - 15f, rect3.y - 25f, 32f, 32f); + Rect position2 = new Rect(rect3.center.x - 1f, rect3.y, 2f, rect3.height); + Rect position3 = new Rect(position.center.x - 5f, position2.yMax, 35f, 20f); + switch (current.GetTypeForControl(controlID2)) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + current.Use(); + float cameraPercentForCurrentQualityLevel = LODGroupEditor.GetCameraPercentForCurrentQualityLevel(current.mousePosition.x, sliderPosition.x, sliderPosition.width); + LODGroupEditor.UpdateCamera(cameraPercentForCurrentQualityLevel, lODGroup); + this.UpdateSelectedLODFromCamera(lods, cameraPercentForCurrentQualityLevel); + GUIUtility.hotControl = controlID2; + SceneView.lastActiveSceneView.ClearSearchFilter(); + SceneView.lastActiveSceneView.SetSceneViewFiltering(true); + HierarchyProperty.FilterSingleSceneObject(lODGroup.gameObject.GetInstanceID(), false); + SceneView.RepaintAll(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID2) + { + SceneView.lastActiveSceneView.SetSceneViewFiltering(false); + SceneView.lastActiveSceneView.ClearSearchFilter(); + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID2) + { + current.Use(); + float cameraPercentForCurrentQualityLevel2 = LODGroupEditor.GetCameraPercentForCurrentQualityLevel(current.mousePosition.x, sliderPosition.x, sliderPosition.width); + this.UpdateSelectedLODFromCamera(lods, cameraPercentForCurrentQualityLevel2); + LODGroupEditor.UpdateCamera(cameraPercentForCurrentQualityLevel2, lODGroup); + SceneView.RepaintAll(); + } + break; + case EventType.Repaint: + { + Color backgroundColor = GUI.backgroundColor; + GUI.backgroundColor = new Color(backgroundColor.r, backgroundColor.g, backgroundColor.b, 0.8f); + LODGroupEditor.s_Styles.m_LODCameraLine.Draw(position2, false, false, false, false); + GUI.backgroundColor = backgroundColor; + GUI.Label(position, LODGroupEditor.s_Styles.m_CameraIcon, GUIStyle.none); + LODGroupEditor.s_Styles.m_LODSliderText.Draw(position3, string.Format("{0:0}%", Mathf.Clamp01(num4) * 100f), false, false, false, false); + break; + } + } + } + } + private void SetSelectedLODLevelPercentage(float newScreenPercentage, List lods) + { + IEnumerable source = + from lod in lods + where lod.m_LODLevel == lods[this.m_SelectedLODSlider].m_LODLevel + 1 + select lod; + float num = 0f; + if (source.FirstOrDefault() != null) + { + num = source.FirstOrDefault().ScreenPercent; + } + IEnumerable source2 = + from lod in lods + where lod.m_LODLevel == lods[this.m_SelectedLODSlider].m_LODLevel - 1 + select lod; + float num2 = 1f; + if (source2.FirstOrDefault() != null) + { + num2 = source2.FirstOrDefault().ScreenPercent; + } + num2 = Mathf.Clamp01(num2); + num = Mathf.Clamp01(num); + lods[this.m_SelectedLODSlider].ScreenPercent = Mathf.Clamp(newScreenPercentage, num, num2); + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods[this.m_SelectedLODSlider].m_LODLevel)); + serializedProperty.floatValue = lods[this.m_SelectedLODSlider].RawScreenPercent; + } + private static void DrawLODButton(LODGroupEditor.LODInfo currentLOD) + { + EditorGUIUtility.AddCursorRect(currentLOD.m_ButtonPosition, MouseCursor.ResizeHorizontal); + } + private void DrawLODRange(LODGroupEditor.LODInfo currentLOD, float previousLODPercentage) + { + Color backgroundColor = GUI.backgroundColor; + string text = string.Format("LOD: {0}\n{1:0}%", currentLOD.m_LODLevel, previousLODPercentage * 100f); + if (currentLOD.m_LODLevel == this.activeLOD) + { + Rect rangePosition = currentLOD.m_RangePosition; + rangePosition.width -= 6f; + rangePosition.height -= 6f; + rangePosition.center += new Vector2(3f, 3f); + LODGroupEditor.s_Styles.m_LODSliderRangeSelected.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); + GUI.backgroundColor = LODGroupEditor.kLODColors[currentLOD.m_LODLevel]; + if (rangePosition.width > 0f) + { + LODGroupEditor.s_Styles.m_LODSliderRange.Draw(rangePosition, GUIContent.none, false, false, false, false); + } + LODGroupEditor.s_Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); + } + else + { + GUI.backgroundColor = LODGroupEditor.kLODColors[currentLOD.m_LODLevel]; + GUI.backgroundColor *= 0.6f; + LODGroupEditor.s_Styles.m_LODSliderRange.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); + LODGroupEditor.s_Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); + } + GUI.backgroundColor = backgroundColor; + } + private static Rect GetCulledBox(Rect totalRect, float previousLODPercentage) + { + Rect result = LODGroupEditor.CalcLODRange(totalRect, previousLODPercentage, 0f); + result.height -= 2f; + result.width -= 1f; + result.center += new Vector2(0f, 1f); + return result; + } + private static void DrawCulledRange(Rect totalRect, float previousLODPercentage) + { + if (Mathf.Approximately(previousLODPercentage, 0f)) + { + return; + } + Rect culledBox = LODGroupEditor.GetCulledBox(totalRect, LODGroupEditor.DelinearizeScreenPercentage(previousLODPercentage)); + Color color = GUI.color; + GUI.color = LODGroupEditor.kCulledLODColor; + LODGroupEditor.s_Styles.m_LODSliderRange.Draw(culledBox, GUIContent.none, false, false, false, false); + GUI.color = color; + string text = string.Format("Culled\n{0:0}%", previousLODPercentage * 100f); + LODGroupEditor.s_Styles.m_LODSliderText.Draw(culledBox, text, false, false, false, false); + } + private static float CalculatePercentageFromBar(Rect totalRect, Vector2 clickPosition) + { + clickPosition.x -= totalRect.x; + totalRect.x = 0f; + return (totalRect.width <= 0f) ? 0f : (1f - clickPosition.x / totalRect.width); + } + private static Rect CalcLODButton(Rect totalRect, float percentage) + { + return new Rect(totalRect.x + Mathf.Round(totalRect.width * (1f - percentage)) - 5f, totalRect.y, 10f, totalRect.height); + } + private static Rect CalcLODRange(Rect totalRect, float startPercent, float endPercent) + { + float num = Mathf.Round(totalRect.width * (1f - startPercent)); + float num2 = Mathf.Round(totalRect.width * (1f - endPercent)); + return new Rect(totalRect.x + num, totalRect.y, num2 - num, totalRect.height); + } + private void SendPercentagesToLightmapScale() + { + List list = new List(); + for (int i = 0; i < this.m_NumberOfLODs; i++) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", i)); + List list2 = new List(); + for (int j = 0; j < serializedProperty.arraySize; j++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(j).FindPropertyRelative("renderer"); + if (serializedProperty2 != null) + { + list2.Add(serializedProperty2); + } + } + float scale = (i != 0) ? this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", i - 1)).floatValue : 1f; + list.Add(new LODGroupEditor.LODLightmapScale(scale, list2)); + } + for (int k = 0; k < this.m_NumberOfLODs; k++) + { + LODGroupEditor.SetLODLightmapScale(list[k]); + } + } + private static void SetLODLightmapScale(LODGroupEditor.LODLightmapScale lodRenderer) + { + foreach (SerializedProperty current in lodRenderer.m_Renderers) + { + SerializedObject serializedObject = new SerializedObject(current.objectReferenceValue); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_ScaleInLightmap"); + serializedProperty.floatValue = Mathf.Max(0f, lodRenderer.m_Scale * (1f / LightmapVisualization.GetLightmapLODLevelScale((Renderer)current.objectReferenceValue))); + serializedObject.ApplyModifiedProperties(); + } + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "LOD preview \nnot available"); + } + return; + } + this.InitPreview(); + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); + this.m_PreviewDir.y = Mathf.Clamp(this.m_PreviewDir.y, -89f, 89f); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + this.DoRenderPreview(); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + } + if (LODGroupEditor.kSLightIcons[0] == null) + { + LODGroupEditor.kSLightIcons[0] = EditorGUIUtility.IconContent("PreMatLight0"); + LODGroupEditor.kSLightIcons[1] = EditorGUIUtility.IconContent("PreMatLight1"); + } + } + protected void DoRenderPreview() + { + if (this.m_PreviewUtility.m_RenderTexture.width <= 0 || this.m_PreviewUtility.m_RenderTexture.height <= 0 || this.m_NumberOfLODs <= 0 || this.activeLOD < 0) + { + return; + } + Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); + bool flag = false; + List list = new List(); + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("renderer"); + Renderer renderer = serializedProperty2.objectReferenceValue as Renderer; + if (!(renderer == null)) + { + MeshFilter component = renderer.GetComponent(); + if (component != null && component.sharedMesh != null && component.sharedMesh.subMeshCount > 0) + { + list.Add(component); + } + if (!flag) + { + bounds = renderer.bounds; + flag = true; + } + else + { + bounds.Encapsulate(renderer.bounds); + } + } + } + if (!flag) + { + return; + } + float magnitude = bounds.extents.magnitude; + float d = magnitude * 10f; + Vector2 vector = -(this.m_PreviewDir / 100f); + this.m_PreviewUtility.m_Camera.transform.position = bounds.center + new Vector3(Mathf.Sin(vector.x) * Mathf.Cos(vector.y), Mathf.Sin(vector.y), Mathf.Cos(vector.x) * Mathf.Cos(vector.y)) * d; + this.m_PreviewUtility.m_Camera.transform.LookAt(bounds.center); + this.m_PreviewUtility.m_Camera.nearClipPlane = 0.05f; + this.m_PreviewUtility.m_Camera.farClipPlane = 1000f; + this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + Color ambient = new Color(0.2f, 0.2f, 0.2f, 0f); + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + foreach (MeshFilter current in list) + { + for (int j = 0; j < current.sharedMesh.subMeshCount; j++) + { + if (j < current.renderer.sharedMaterials.Length) + { + Matrix4x4 matrix = Matrix4x4.TRS(current.transform.position, current.transform.rotation, current.transform.localScale); + this.m_PreviewUtility.DrawMesh(current.sharedMesh, matrix, current.renderer.sharedMaterials[j], j); + } + } + } + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + InternalEditorUtility.RemoveCustomLighting(); + } + public override string GetInfoString() + { + if (SceneView.lastActiveSceneView == null || SceneView.lastActiveSceneView.camera == null || this.m_NumberOfLODs <= 0 || this.activeLOD < 0) + { + return string.Empty; + } + List list = new List(); + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("renderer"); + Renderer renderer = serializedProperty2.objectReferenceValue as Renderer; + if (renderer != null) + { + list.AddRange(renderer.sharedMaterials); + } + } + Camera camera = SceneView.lastActiveSceneView.camera; + LODGroup group = this.target as LODGroup; + LODVisualizationInformation lODVisualizationInformation = LODUtility.CalculateVisualizationData(camera, group, this.activeLOD); + return (this.activeLOD == -1) ? "LOD: culled" : string.Format("{0} Renderer(s)\n{1} Triangle(s)\n{2} Material(s)", serializedProperty.arraySize, lODVisualizationInformation.triangleCount, list.Distinct().Count()); + } + } +} diff --git a/UnityEditor/UnityEditor/LODUtility.cs b/UnityEditor/UnityEditor/LODUtility.cs new file mode 100644 index 00000000..d589cc10 --- /dev/null +++ b/UnityEditor/UnityEditor/LODUtility.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class LODUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern LODVisualizationInformation CalculateVisualizationData(Camera camera, LODGroup group, int lodLevel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float CalculateDistance(Camera camera, float relativeScreenHeight, LODGroup group); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CalculateLODGroupBoundingBox(LODGroup group); + } +} diff --git a/UnityEditor/UnityEditor/LODVisualizationInformation.cs b/UnityEditor/UnityEditor/LODVisualizationInformation.cs new file mode 100644 index 00000000..667fb67e --- /dev/null +++ b/UnityEditor/UnityEditor/LODVisualizationInformation.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEditor +{ + internal struct LODVisualizationInformation + { + public int triangleCount; + public int vertexCount; + public int rendererCount; + public int submeshCount; + public int activeLODLevel; + public float activeLODFade; + public float activeDistance; + public float activeRelativeScreenSize; + public float activePixelSize; + public float worldSpaceSize; + } +} diff --git a/UnityEditor/UnityEditor/LabelGUI.cs b/UnityEditor/UnityEditor/LabelGUI.cs new file mode 100644 index 00000000..ca0e20a1 --- /dev/null +++ b/UnityEditor/UnityEditor/LabelGUI.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class LabelGUI + { + private HashSet m_CurrentAssetsSet; + private PopupList.InputData m_AssetLabels; + private string m_ChangedLabel; + private bool m_CurrentChanged; + private bool m_ChangeWasAdd; + private bool m_IgnoreNextAssetLabelsChangedCall; + private static Action s_AssetLabelsForObjectChangedDelegates; + private static int s_MaxShownLabels = 10; + public void OnEnable() + { + LabelGUI.s_AssetLabelsForObjectChangedDelegates = (Action)Delegate.Combine(LabelGUI.s_AssetLabelsForObjectChangedDelegates, new Action(this.AssetLabelsChangedForObject)); + } + public void OnDisable() + { + LabelGUI.s_AssetLabelsForObjectChangedDelegates = (Action)Delegate.Remove(LabelGUI.s_AssetLabelsForObjectChangedDelegates, new Action(this.AssetLabelsChangedForObject)); + this.SaveLabels(); + } + public void OnLostFocus() + { + this.SaveLabels(); + } + public void AssetLabelsChangedForObject(UnityEngine.Object asset) + { + if (!this.m_IgnoreNextAssetLabelsChangedCall && this.m_CurrentAssetsSet != null && this.m_CurrentAssetsSet.Contains(asset)) + { + this.m_AssetLabels = null; + } + this.m_IgnoreNextAssetLabelsChangedCall = false; + } + public void SaveLabels() + { + if (this.m_CurrentChanged && this.m_AssetLabels != null && this.m_CurrentAssetsSet != null) + { + bool flag = false; + foreach (UnityEngine.Object current in this.m_CurrentAssetsSet) + { + bool flag2 = false; + string[] labels = AssetDatabase.GetLabels(current); + List list = labels.ToList(); + if (this.m_ChangeWasAdd) + { + if (!list.Contains(this.m_ChangedLabel)) + { + list.Add(this.m_ChangedLabel); + flag2 = true; + } + } + else + { + if (list.Contains(this.m_ChangedLabel)) + { + list.Remove(this.m_ChangedLabel); + flag2 = true; + } + } + if (flag2) + { + AssetDatabase.SetLabels(current, list.ToArray()); + if (LabelGUI.s_AssetLabelsForObjectChangedDelegates != null) + { + this.m_IgnoreNextAssetLabelsChangedCall = true; + LabelGUI.s_AssetLabelsForObjectChangedDelegates(current); + } + flag = true; + } + } + if (flag) + { + EditorApplication.Internal_CallAssetLabelsHaveChanged(); + } + this.m_CurrentChanged = false; + } + } + public void AssetLabelListCallback(PopupList.ListElement element) + { + this.m_ChangedLabel = element.text; + element.selected = !element.selected; + this.m_ChangeWasAdd = element.selected; + element.partiallySelected = false; + this.m_CurrentChanged = true; + this.SaveLabels(); + InspectorWindow.RepaintAllInspectors(); + } + public void InitLabelCache(UnityEngine.Object[] assets) + { + HashSet hashSet = new HashSet(assets); + if (this.m_CurrentAssetsSet == null || !this.m_CurrentAssetsSet.SetEquals(hashSet)) + { + List source; + List source2; + this.GetLabelsForAssets(assets, out source, out source2); + this.m_AssetLabels = new PopupList.InputData + { + m_AllowCustom = true, + m_OnSelectCallback = new PopupList.OnSelectCallback(this.AssetLabelListCallback), + m_MaxCount = 15, + m_SortAlphabetically = true + }; + Dictionary allLabels = AssetDatabase.GetAllLabels(); + foreach (KeyValuePair pair in allLabels) + { + PopupList.ListElement listElement = this.m_AssetLabels.NewOrMatchingElement(pair.Key); + if (listElement.filterScore < pair.Value) + { + listElement.filterScore = pair.Value; + } + listElement.selected = source.Any((string label) => string.Equals(label, pair.Key, StringComparison.OrdinalIgnoreCase)); + listElement.partiallySelected = source2.Any((string label) => string.Equals(label, pair.Key, StringComparison.OrdinalIgnoreCase)); + } + } + this.m_CurrentAssetsSet = hashSet; + this.m_CurrentChanged = false; + } + public void OnLabelGUI(UnityEngine.Object[] assets) + { + this.InitLabelCache(assets); + float num = 1f; + float num2 = 2f; + float pixels = 3f; + float num3 = 5f; + GUIStyle assetLabelIcon = EditorStyles.assetLabelIcon; + float num4 = (float)assetLabelIcon.margin.left + assetLabelIcon.fixedWidth + num2; + GUILayout.Space(pixels); + Rect rect = GUILayoutUtility.GetRect(0f, 10240f, 0f, 0f); + rect.width -= num4; + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayoutUtility.GetRect(num, num, 0f, 0f); + this.DrawLabelList(false, rect.xMax); + this.DrawLabelList(true, rect.xMax); + GUILayout.FlexibleSpace(); + Rect rect2 = GUILayoutUtility.GetRect(assetLabelIcon.fixedWidth, assetLabelIcon.fixedWidth, assetLabelIcon.fixedHeight + num3, assetLabelIcon.fixedHeight + num3); + rect2.x = rect.xMax + (float)assetLabelIcon.margin.left; + if (EditorGUI.ButtonMouseDown(rect2, GUIContent.none, FocusType.Passive, assetLabelIcon)) + { + PopupWindow.Show(rect2, new PopupList(this.m_AssetLabels)); + } + EditorGUILayout.EndHorizontal(); + } + private void DrawLabelList(bool partiallySelected, float xMax) + { + GUIStyle style = (!partiallySelected) ? EditorStyles.assetLabel : EditorStyles.assetLabelPartial; + Event current = Event.current; + foreach (GUIContent current2 in ( + from i in this.m_AssetLabels.m_ListElements + where (!partiallySelected) ? i.selected : i.partiallySelected + orderby i.text.ToLower() + select i.m_Content).Take(LabelGUI.s_MaxShownLabels)) + { + Rect rect = GUILayoutUtility.GetRect(current2, style); + if (Event.current.type == EventType.Repaint && rect.xMax >= xMax) + { + break; + } + GUI.Label(rect, current2, style); + if (rect.xMax <= xMax && current.type == EventType.MouseDown && rect.Contains(current.mousePosition) && current.button == 0 && GUI.enabled) + { + current.Use(); + rect.x = xMax; + PopupWindow.Show(rect, new PopupList(this.m_AssetLabels, current2.text)); + } + } + } + private void GetLabelsForAssets(UnityEngine.Object[] assets, out List all, out List partial) + { + all = new List(); + partial = new List(); + Dictionary dictionary = new Dictionary(); + for (int i = 0; i < assets.Length; i++) + { + UnityEngine.Object obj = assets[i]; + string[] labels = AssetDatabase.GetLabels(obj); + string[] array = labels; + for (int j = 0; j < array.Length; j++) + { + string key = array[j]; + dictionary[key] = ((!dictionary.ContainsKey(key)) ? 1 : (dictionary[key] + 1)); + } + } + foreach (KeyValuePair current in dictionary) + { + List list = (current.Value != assets.Length) ? partial : all; + list.Add(current.Key); + } + } + } +} diff --git a/UnityEditor/UnityEditor/LayerMatrixGUI.cs b/UnityEditor/UnityEditor/LayerMatrixGUI.cs new file mode 100644 index 00000000..bb7e189c --- /dev/null +++ b/UnityEditor/UnityEditor/LayerMatrixGUI.cs @@ -0,0 +1,86 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class LayerMatrixGUI + { + public delegate bool GetValueFunc(int layerA, int layerB); + public delegate void SetValueFunc(int layerA, int layerB, bool val); + public static void DoGUI(string title, ref bool show, ref Vector2 scrollPos, LayerMatrixGUI.GetValueFunc getValue, LayerMatrixGUI.SetValueFunc setValue) + { + int num = 0; + for (int i = 0; i < 32; i++) + { + if (LayerMask.LayerToName(i) != string.Empty) + { + num++; + } + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(0f); + show = EditorGUILayout.Foldout(show, title); + GUILayout.EndHorizontal(); + if (show) + { + scrollPos = GUILayout.BeginScrollView(scrollPos, new GUILayoutOption[] + { + GUILayout.MinHeight(120f), + GUILayout.MaxHeight((float)(100 + (num + 1) * 15)) + }); + Rect rect = GUILayoutUtility.GetRect((float)(15 * num + 100), 100f); + Rect topmostRect = GUIClip.topmostRect; + Vector2 vector = GUIClip.Unclip(new Vector2(rect.x, rect.y)); + int num2 = 0; + for (int j = 0; j < 32; j++) + { + if (LayerMask.LayerToName(j) != string.Empty) + { + float num3 = (float)(130 + (num - num2) * 15) - (topmostRect.width + scrollPos.x); + if (num3 < 0f) + { + num3 = 0f; + } + Vector3 pos = new Vector3((float)(130 + 15 * (num - num2)) + vector.y + vector.x + scrollPos.y - num3, vector.y + scrollPos.y, 0f); + GUI.matrix = Matrix4x4.TRS(pos, Quaternion.identity, Vector3.one) * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, 90f), Vector3.one); + if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9.0")) + { + GUI.matrix *= Matrix4x4.TRS(new Vector3(-0.5f, -0.5f, 0f), Quaternion.identity, Vector3.one); + } + GUI.Label(new Rect(2f - vector.x - scrollPos.y, scrollPos.y - num3, 100f, 15f), LayerMask.LayerToName(j), "RightLabel"); + num2++; + } + } + GUI.matrix = Matrix4x4.identity; + num2 = 0; + for (int k = 0; k < 32; k++) + { + if (LayerMask.LayerToName(k) != string.Empty) + { + int num4 = 0; + Rect rect2 = GUILayoutUtility.GetRect((float)(30 + 15 * num + 100), 15f); + GUI.Label(new Rect(rect2.x + 30f, rect2.y, 100f, 15f), LayerMask.LayerToName(k), "RightLabel"); + for (int l = 31; l >= 0; l--) + { + if (LayerMask.LayerToName(l) != string.Empty) + { + if (num4 < num - num2) + { + GUIContent content = new GUIContent(string.Empty, LayerMask.LayerToName(k) + "/" + LayerMask.LayerToName(l)); + bool flag = getValue(k, l); + bool flag2 = GUI.Toggle(new Rect(130f + rect2.x + (float)(num4 * 15), rect2.y, 15f, 15f), flag, content); + if (flag2 != flag) + { + setValue(k, l, flag2); + } + } + num4++; + } + } + num2++; + } + } + GUILayout.EndScrollView(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/LayerVisibilityWindow.cs b/UnityEditor/UnityEditor/LayerVisibilityWindow.cs new file mode 100644 index 00000000..016e815e --- /dev/null +++ b/UnityEditor/UnityEditor/LayerVisibilityWindow.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class LayerVisibilityWindow : EditorWindow + { + private class Styles + { + public readonly GUIStyle background = "grey_border"; + public readonly GUIStyle menuItem = "MenuItem"; + public readonly GUIStyle listEvenBg = "ObjectPickerResultsOdd"; + public readonly GUIStyle listOddBg = "ObjectPickerResultsEven"; + public readonly GUIStyle separator = "sv_iconselector_sep"; + public readonly GUIStyle lockButton = "IN LockButton"; + public readonly GUIStyle listTextStyle; + public readonly GUIStyle listHeaderStyle; + public readonly Texture2D visibleOn = EditorGUIUtility.LoadIcon("animationvisibilitytoggleon"); + public readonly Texture2D visibleOff = EditorGUIUtility.LoadIcon("animationvisibilitytoggleoff"); + public Styles() + { + this.listTextStyle = new GUIStyle(EditorStyles.label); + this.listTextStyle.alignment = TextAnchor.MiddleLeft; + this.listTextStyle.padding.left = 10; + this.listHeaderStyle = new GUIStyle(EditorStyles.boldLabel); + this.listHeaderStyle.padding.left = 5; + } + } + private const float kScrollBarWidth = 14f; + private const float kFrameWidth = 1f; + private const float kToggleSize = 17f; + private const float kSeparatorHeight = 6f; + private const string kLayerVisible = "Show/Hide Layer"; + private const string kLayerLocked = "Lock Layer for Picking"; + private static LayerVisibilityWindow s_LayerVisibilityWindow; + private static long s_LastClosedTime; + private static LayerVisibilityWindow.Styles s_Styles; + private List s_LayerNames; + private List s_LayerMasks; + private int m_AllLayersMask; + private float m_ContentHeight; + private Vector2 m_ScrollPosition; + private LayerVisibilityWindow() + { + base.hideFlags = HideFlags.DontSave; + base.wantsMouseMove = true; + } + private void CalcValidLayers() + { + this.s_LayerNames = new List(); + this.s_LayerMasks = new List(); + this.m_AllLayersMask = 0; + for (int i = 0; i < 32; i++) + { + string layerName = InternalEditorUtility.GetLayerName(i); + if (!(layerName == string.Empty)) + { + this.s_LayerNames.Add(layerName); + this.s_LayerMasks.Add(i); + this.m_AllLayersMask |= 1 << i; + } + } + } + internal void OnDisable() + { + LayerVisibilityWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + LayerVisibilityWindow.s_LayerVisibilityWindow = null; + } + internal static bool ShowAtPosition(Rect buttonRect) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= LayerVisibilityWindow.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (LayerVisibilityWindow.s_LayerVisibilityWindow == null) + { + LayerVisibilityWindow.s_LayerVisibilityWindow = ScriptableObject.CreateInstance(); + } + LayerVisibilityWindow.s_LayerVisibilityWindow.Init(buttonRect); + return true; + } + return false; + } + private void Init(Rect buttonRect) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + this.CalcValidLayers(); + int num = this.s_LayerNames.Count + 2 + 1 + 1; + float num2 = (float)num * 16f + 6f; + int sortingLayerCount = InternalEditorUtility.GetSortingLayerCount(); + if (sortingLayerCount > 1) + { + num2 += 22f; + num2 += (float)sortingLayerCount * 16f; + } + this.m_ContentHeight = num2; + num2 += 2f; + num2 = Mathf.Min(num2, 600f); + Vector2 windowSize = new Vector2(180f, num2); + base.ShowAsDropDown(buttonRect, windowSize); + } + internal void OnGUI() + { + if (Event.current.type == EventType.Layout) + { + return; + } + if (LayerVisibilityWindow.s_Styles == null) + { + LayerVisibilityWindow.s_Styles = new LayerVisibilityWindow.Styles(); + } + Rect position = new Rect(1f, 1f, base.position.width - 2f, base.position.height - 2f); + Rect viewRect = new Rect(0f, 0f, 1f, this.m_ContentHeight); + bool flag = this.m_ContentHeight > position.height; + float num = position.width; + if (flag) + { + num -= 14f; + } + this.m_ScrollPosition = GUI.BeginScrollView(position, this.m_ScrollPosition, viewRect); + this.Draw(num); + GUI.EndScrollView(); + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, LayerVisibilityWindow.s_Styles.background); + if (Event.current.type == EventType.MouseMove) + { + Event.current.Use(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + base.Close(); + GUIUtility.ExitGUI(); + } + } + private void DrawListBackground(Rect rect, bool even) + { + GUIStyle style = (!even) ? LayerVisibilityWindow.s_Styles.listOddBg : LayerVisibilityWindow.s_Styles.listEvenBg; + GUI.Label(rect, GUIContent.none, style); + } + private void DrawHeader(ref Rect rect, string text, ref bool even) + { + this.DrawListBackground(rect, even); + GUI.Label(rect, GUIContent.Temp(text), LayerVisibilityWindow.s_Styles.listHeaderStyle); + rect.y += 16f; + even = !even; + } + private void DrawSeparator(ref Rect rect, bool even) + { + this.DrawListBackground(new Rect(rect.x + 1f, rect.y, rect.width - 2f, 6f), even); + GUI.Label(new Rect(rect.x + 5f, rect.y + 3f, rect.width - 10f, 3f), GUIContent.none, LayerVisibilityWindow.s_Styles.separator); + rect.y += 6f; + } + private void Draw(float listElementWidth) + { + Rect rect = new Rect(0f, 0f, listElementWidth, 16f); + bool even = false; + this.DrawHeader(ref rect, "Layers", ref even); + this.DoSpecialLayer(rect, true, ref even); + rect.y += 16f; + this.DoSpecialLayer(rect, false, ref even); + rect.y += 16f; + for (int i = 0; i < this.s_LayerNames.Count; i++) + { + this.DoOneLayer(rect, i, ref even); + rect.y += 16f; + } + int sortingLayerCount = InternalEditorUtility.GetSortingLayerCount(); + if (sortingLayerCount > 1) + { + this.DrawSeparator(ref rect, even); + this.DrawHeader(ref rect, "Sorting Layers", ref even); + for (int j = 0; j < sortingLayerCount; j++) + { + this.DoOneSortingLayer(rect, j, ref even); + rect.y += 16f; + } + } + this.DrawSeparator(ref rect, even); + this.DrawListBackground(rect, even); + if (GUI.Button(rect, EditorGUIUtility.TempContent("Edit Layers..."), LayerVisibilityWindow.s_Styles.menuItem)) + { + base.Close(); + Selection.activeObject = EditorApplication.tagManager; + GUIUtility.ExitGUI(); + } + } + private void DoSpecialLayer(Rect rect, bool all, ref bool even) + { + int visibleLayers = Tools.visibleLayers; + int num = (!all) ? 0 : this.m_AllLayersMask; + bool visible = (visibleLayers & this.m_AllLayersMask) == num; + bool flag; + bool flag2; + this.DoLayerEntry(rect, (!all) ? "Nothing" : "Everything", even, true, false, visible, false, out flag, out flag2); + if (flag) + { + Tools.visibleLayers = ((!all) ? 0 : -1); + LayerVisibilityWindow.RepaintAllSceneViews(); + } + even = !even; + } + private void DoOneLayer(Rect rect, int index, ref bool even) + { + int visibleLayers = Tools.visibleLayers; + int lockedLayers = Tools.lockedLayers; + int num = 1 << this.s_LayerMasks[index]; + bool visible = (visibleLayers & num) != 0; + bool locked = (lockedLayers & num) != 0; + bool flag; + bool flag2; + this.DoLayerEntry(rect, this.s_LayerNames[index], even, true, true, visible, locked, out flag, out flag2); + if (flag) + { + Tools.visibleLayers ^= num; + LayerVisibilityWindow.RepaintAllSceneViews(); + } + if (flag2) + { + Tools.lockedLayers ^= num; + } + even = !even; + } + private void DoOneSortingLayer(Rect rect, int index, ref bool even) + { + bool sortingLayerLocked = InternalEditorUtility.GetSortingLayerLocked(index); + bool flag; + bool flag2; + this.DoLayerEntry(rect, InternalEditorUtility.GetSortingLayerName(index), even, false, true, true, sortingLayerLocked, out flag, out flag2); + if (flag2) + { + InternalEditorUtility.SetSortingLayerLocked(index, !sortingLayerLocked); + } + even = !even; + } + private void DoLayerEntry(Rect rect, string layerName, bool even, bool showVisible, bool showLock, bool visible, bool locked, out bool visibleChanged, out bool lockedChanged) + { + this.DrawListBackground(rect, even); + EditorGUI.BeginChangeCheck(); + Rect position = rect; + position.width -= 34f; + visible = GUI.Toggle(position, visible, EditorGUIUtility.TempContent(layerName), LayerVisibilityWindow.s_Styles.listTextStyle); + Rect rect2 = new Rect(rect.width - 34f, rect.y + (rect.height - 17f) * 0.5f, 17f, 17f); + visibleChanged = false; + if (showVisible) + { + Color color = GUI.color; + Color color2 = color; + color2.a = ((!visible) ? 0.4f : 0.6f); + GUI.color = color2; + Rect position2 = rect2; + position2.y += 3f; + GUIContent content = new GUIContent(string.Empty, (!visible) ? LayerVisibilityWindow.s_Styles.visibleOff : LayerVisibilityWindow.s_Styles.visibleOn, "Show/Hide Layer"); + GUI.Toggle(position2, visible, content, GUIStyle.none); + GUI.color = color; + visibleChanged = EditorGUI.EndChangeCheck(); + } + lockedChanged = false; + if (showLock) + { + rect2.x += 17f; + EditorGUI.BeginChangeCheck(); + Color backgroundColor = GUI.backgroundColor; + Color backgroundColor2 = backgroundColor; + if (!locked) + { + backgroundColor2.a *= 0.4f; + } + GUI.backgroundColor = backgroundColor2; + GUI.Toggle(rect2, locked, new GUIContent(string.Empty, "Lock Layer for Picking"), LayerVisibilityWindow.s_Styles.lockButton); + GUI.backgroundColor = backgroundColor; + lockedChanged = EditorGUI.EndChangeCheck(); + } + } + private static void RepaintAllSceneViews() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneView)); + for (int i = 0; i < array.Length; i++) + { + SceneView sceneView = (SceneView)array[i]; + sceneView.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/LayoutDropdownWindow.cs b/UnityEditor/UnityEditor/LayoutDropdownWindow.cs new file mode 100644 index 00000000..944b4863 --- /dev/null +++ b/UnityEditor/UnityEditor/LayoutDropdownWindow.cs @@ -0,0 +1,565 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class LayoutDropdownWindow : PopupWindowContent + { + private class Styles + { + public Color tableHeaderColor; + public Color tableLineColor; + public Color parentColor; + public Color selfColor; + public Color simpleAnchorColor; + public Color stretchAnchorColor; + public Color anchorCornerColor; + public Color pivotColor; + public GUIStyle frame; + public GUIStyle label = new GUIStyle(EditorStyles.miniLabel); + public Styles() + { + this.frame = new GUIStyle(); + Texture2D texture2D = new Texture2D(4, 4); + texture2D.SetPixels(new Color[] + { + Color.white, + Color.white, + Color.white, + Color.white, + Color.white, + Color.clear, + Color.clear, + Color.white, + Color.white, + Color.clear, + Color.clear, + Color.white, + Color.white, + Color.white, + Color.white, + Color.white + }); + texture2D.filterMode = FilterMode.Point; + texture2D.Apply(); + texture2D.hideFlags = HideFlags.HideAndDontSave; + this.frame.normal.background = texture2D; + this.frame.border = new RectOffset(2, 2, 2, 2); + this.label.alignment = TextAnchor.LowerCenter; + if (EditorGUIUtility.isProSkin) + { + this.tableHeaderColor = new Color(0.18f, 0.18f, 0.18f, 1f); + this.tableLineColor = new Color(1f, 1f, 1f, 0.3f); + this.parentColor = new Color(0.4f, 0.4f, 0.4f, 1f); + this.selfColor = new Color(0.6f, 0.6f, 0.6f, 1f); + this.simpleAnchorColor = new Color(0.7f, 0.3f, 0.3f, 1f); + this.stretchAnchorColor = new Color(0f, 0.6f, 0.8f, 1f); + this.anchorCornerColor = new Color(0.8f, 0.6f, 0f, 1f); + this.pivotColor = new Color(0f, 0.6f, 0.8f, 1f); + } + else + { + this.tableHeaderColor = new Color(0.8f, 0.8f, 0.8f, 1f); + this.tableLineColor = new Color(0f, 0f, 0f, 0.5f); + this.parentColor = new Color(0.55f, 0.55f, 0.55f, 1f); + this.selfColor = new Color(0.2f, 0.2f, 0.2f, 1f); + this.simpleAnchorColor = new Color(0.8f, 0.3f, 0.3f, 1f); + this.stretchAnchorColor = new Color(0.2f, 0.5f, 0.9f, 1f); + this.anchorCornerColor = new Color(0.6f, 0.4f, 0f, 1f); + this.pivotColor = new Color(0.2f, 0.5f, 0.9f, 1f); + } + } + } + public enum LayoutMode + { + Undefined = -1, + Min, + Middle, + Max, + Stretch + } + private const int kTopPartHeight = 38; + private static LayoutDropdownWindow.Styles s_Styles; + private SerializedProperty m_AnchorMin; + private SerializedProperty m_AnchorMax; + private SerializedProperty m_Position; + private SerializedProperty m_SizeDelta; + private SerializedProperty m_Pivot; + private Vector2[,] m_InitValues; + private static float[] kPivotsForModes = new float[] + { + 0f, + 0.5f, + 1f, + 0.5f, + 0.5f + }; + private static string[] kHLabels = new string[] + { + "custom", + "left", + "center", + "right", + "stretch", + "%" + }; + private static string[] kVLabels = new string[] + { + "custom", + "top", + "middle", + "bottom", + "stretch", + "%" + }; + public LayoutDropdownWindow(SerializedObject so) + { + this.m_AnchorMin = so.FindProperty("m_AnchorMin"); + this.m_AnchorMax = so.FindProperty("m_AnchorMax"); + this.m_Position = so.FindProperty("m_Position"); + this.m_SizeDelta = so.FindProperty("m_SizeDelta"); + this.m_Pivot = so.FindProperty("m_Pivot"); + this.m_InitValues = new Vector2[so.targetObjects.Length, 4]; + for (int i = 0; i < so.targetObjects.Length; i++) + { + RectTransform rectTransform = so.targetObjects[i] as RectTransform; + this.m_InitValues[i, 0] = rectTransform.anchorMin; + this.m_InitValues[i, 1] = rectTransform.anchorMax; + this.m_InitValues[i, 2] = rectTransform.anchoredPosition; + this.m_InitValues[i, 3] = rectTransform.sizeDelta; + } + } + public override void OnOpen() + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(base.editorWindow.Repaint)); + } + public override void OnClose() + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(base.editorWindow.Repaint)); + } + public override Vector2 GetWindowSize() + { + return new Vector2(262f, 300f); + } + public override void OnGUI(Rect rect) + { + if (LayoutDropdownWindow.s_Styles == null) + { + LayoutDropdownWindow.s_Styles = new LayoutDropdownWindow.Styles(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) + { + base.editorWindow.Close(); + } + GUI.Label(new Rect(rect.x + 5f, rect.y + 3f, rect.width - 10f, 16f), new GUIContent("Anchor Presets"), EditorStyles.boldLabel); + GUI.Label(new Rect(rect.x + 5f, rect.y + 3f + 16f, rect.width - 10f, 16f), new GUIContent("Shift: Also set pivot Alt: Also set position"), EditorStyles.label); + Color color = GUI.color; + GUI.color = LayoutDropdownWindow.s_Styles.tableLineColor * color; + GUI.DrawTexture(new Rect(0f, 37f, 400f, 1f), EditorGUIUtility.whiteTexture); + GUI.color = color; + GUI.BeginGroup(new Rect(rect.x, rect.y + 38f, rect.width, rect.height - 38f)); + this.TableGUI(rect); + GUI.EndGroup(); + } + private static LayoutDropdownWindow.LayoutMode SwappedVMode(LayoutDropdownWindow.LayoutMode vMode) + { + if (vMode == LayoutDropdownWindow.LayoutMode.Min) + { + return LayoutDropdownWindow.LayoutMode.Max; + } + if (vMode == LayoutDropdownWindow.LayoutMode.Max) + { + return LayoutDropdownWindow.LayoutMode.Min; + } + return vMode; + } + internal static void DrawLayoutModeHeadersOutsideRect(Rect rect, SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta) + { + LayoutDropdownWindow.LayoutMode layoutModeForAxis = LayoutDropdownWindow.GetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, 0); + LayoutDropdownWindow.LayoutMode layoutMode = LayoutDropdownWindow.GetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, 1); + layoutMode = LayoutDropdownWindow.SwappedVMode(layoutMode); + LayoutDropdownWindow.DrawLayoutModeHeaderOutsideRect(rect, 0, layoutModeForAxis); + LayoutDropdownWindow.DrawLayoutModeHeaderOutsideRect(rect, 1, layoutMode); + } + internal static void DrawLayoutModeHeaderOutsideRect(Rect position, int axis, LayoutDropdownWindow.LayoutMode mode) + { + Rect position2 = new Rect(position.x, position.y - 16f, position.width, 16f); + Matrix4x4 matrix = GUI.matrix; + if (axis == 1) + { + GUIUtility.RotateAroundPivot(-90f, position.center); + } + int num = (int)(mode + 1); + GUI.Label(position2, (axis != 0) ? LayoutDropdownWindow.kVLabels[num] : LayoutDropdownWindow.kHLabels[num], LayoutDropdownWindow.s_Styles.label); + GUI.matrix = matrix; + } + private void TableGUI(Rect rect) + { + int num = 6; + int num2 = 31 + num * 2; + int num3 = 0; + int[] array = new int[] + { + 15, + 30, + 30, + 30, + 45, + 45 + }; + Color color = GUI.color; + int num4 = 62; + GUI.color = LayoutDropdownWindow.s_Styles.tableHeaderColor * color; + GUI.DrawTexture(new Rect(0f, 0f, 400f, (float)num4), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(0f, 0f, (float)num4, 400f), EditorGUIUtility.whiteTexture); + GUI.color = LayoutDropdownWindow.s_Styles.tableLineColor * color; + GUI.DrawTexture(new Rect(0f, (float)num4, 400f, 1f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect((float)num4, 0f, 1f, 400f), EditorGUIUtility.whiteTexture); + GUI.color = color; + LayoutDropdownWindow.LayoutMode layoutModeForAxis = LayoutDropdownWindow.GetLayoutModeForAxis(this.m_AnchorMin, this.m_AnchorMax, this.m_Position, this.m_SizeDelta, 0); + LayoutDropdownWindow.LayoutMode layoutMode = LayoutDropdownWindow.GetLayoutModeForAxis(this.m_AnchorMin, this.m_AnchorMax, this.m_Position, this.m_SizeDelta, 1); + layoutMode = LayoutDropdownWindow.SwappedVMode(layoutMode); + bool shift = Event.current.shift; + bool alt = Event.current.alt; + int num5 = 5; + for (int i = 0; i < num5; i++) + { + LayoutDropdownWindow.LayoutMode layoutMode2 = (LayoutDropdownWindow.LayoutMode)(i - 1); + for (int j = 0; j < num5; j++) + { + LayoutDropdownWindow.LayoutMode layoutMode3 = (LayoutDropdownWindow.LayoutMode)(j - 1); + if (i != 0 || j != 0 || layoutMode < LayoutDropdownWindow.LayoutMode.Min || layoutModeForAxis < LayoutDropdownWindow.LayoutMode.Min) + { + Rect position = new Rect((float)(i * (num2 + num3) + array[i]), (float)(j * (num2 + num3) + array[j]), (float)num2, (float)num2); + if (j == 0 && (i != 0 || layoutModeForAxis == LayoutDropdownWindow.LayoutMode.Undefined)) + { + LayoutDropdownWindow.DrawLayoutModeHeaderOutsideRect(position, 0, layoutMode2); + } + if (i == 0 && (j != 0 || layoutMode == LayoutDropdownWindow.LayoutMode.Undefined)) + { + LayoutDropdownWindow.DrawLayoutModeHeaderOutsideRect(position, 1, layoutMode3); + } + bool flag = layoutMode2 == layoutModeForAxis && layoutMode3 == layoutMode; + bool flag2 = false; + if (i == 0 && layoutMode3 == layoutMode) + { + flag2 = true; + } + if (j == 0 && layoutMode2 == layoutModeForAxis) + { + flag2 = true; + } + if (Event.current.type == EventType.Repaint) + { + if (flag) + { + GUI.color = Color.white * color; + LayoutDropdownWindow.s_Styles.frame.Draw(position, false, false, false, false); + } + else + { + if (flag2) + { + GUI.color = new Color(1f, 1f, 1f, 0.7f) * color; + LayoutDropdownWindow.s_Styles.frame.Draw(position, false, false, false, false); + } + } + } + LayoutDropdownWindow.DrawLayoutMode(new Rect(position.x + (float)num, position.y + (float)num, position.width - (float)(num * 2), position.height - (float)(num * 2)), layoutMode2, layoutMode3, shift, alt); + int clickCount = Event.current.clickCount; + if (GUI.Button(position, GUIContent.none, GUIStyle.none)) + { + LayoutDropdownWindow.SetLayoutModeForAxis(this.m_AnchorMin, this.m_AnchorMax, this.m_Position, this.m_SizeDelta, this.m_Pivot, 0, layoutMode2, shift, alt, this.m_InitValues); + LayoutDropdownWindow.SetLayoutModeForAxis(this.m_AnchorMin, this.m_AnchorMax, this.m_Position, this.m_SizeDelta, this.m_Pivot, 1, LayoutDropdownWindow.SwappedVMode(layoutMode3), shift, alt, this.m_InitValues); + if (clickCount == 2) + { + base.editorWindow.Close(); + } + else + { + base.editorWindow.Repaint(); + } + } + } + } + } + GUI.color = color; + } + private static LayoutDropdownWindow.LayoutMode GetLayoutModeForAxis(SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta, int axis) + { + if (anchorMin.vector2Value[axis] == 0f && anchorMax.vector2Value[axis] == 0f) + { + return LayoutDropdownWindow.LayoutMode.Min; + } + if (anchorMin.vector2Value[axis] == 0.5f && anchorMax.vector2Value[axis] == 0.5f) + { + return LayoutDropdownWindow.LayoutMode.Middle; + } + if (anchorMin.vector2Value[axis] == 1f && anchorMax.vector2Value[axis] == 1f) + { + return LayoutDropdownWindow.LayoutMode.Max; + } + if (anchorMin.vector2Value[axis] == 0f && anchorMax.vector2Value[axis] == 1f) + { + return LayoutDropdownWindow.LayoutMode.Stretch; + } + return LayoutDropdownWindow.LayoutMode.Undefined; + } + private static void SetLayoutModeForAxis(SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta, SerializedProperty pivot, int axis, LayoutDropdownWindow.LayoutMode layoutMode) + { + LayoutDropdownWindow.SetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, pivot, axis, layoutMode, false, false, null); + } + private static void SetLayoutModeForAxis(SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta, SerializedProperty pivot, int axis, LayoutDropdownWindow.LayoutMode layoutMode, bool doPivot) + { + LayoutDropdownWindow.SetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, pivot, axis, layoutMode, doPivot, false, null); + } + private static void SetLayoutModeForAxis(SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta, SerializedProperty pivot, int axis, LayoutDropdownWindow.LayoutMode layoutMode, bool doPivot, bool doPosition) + { + LayoutDropdownWindow.SetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, pivot, axis, layoutMode, doPivot, doPosition, null); + } + private static void SetLayoutModeForAxis(SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta, SerializedProperty pivot, int axis, LayoutDropdownWindow.LayoutMode layoutMode, bool doPivot, bool doPosition, Vector2[,] defaultValues) + { + anchorMin.serializedObject.ApplyModifiedProperties(); + for (int i = 0; i < anchorMin.serializedObject.targetObjects.Length; i++) + { + RectTransform rectTransform = anchorMin.serializedObject.targetObjects[i] as RectTransform; + Undo.RecordObject(rectTransform, "Change Rectangle Anchors"); + if (doPosition && defaultValues != null && defaultValues.Length > i) + { + Vector2 vector = rectTransform.anchorMin; + vector[axis] = defaultValues[i, 0][axis]; + rectTransform.anchorMin = vector; + vector = rectTransform.anchorMax; + vector[axis] = defaultValues[i, 1][axis]; + rectTransform.anchorMax = vector; + vector = rectTransform.anchoredPosition; + vector[axis] = defaultValues[i, 2][axis]; + rectTransform.anchoredPosition = vector; + vector = rectTransform.sizeDelta; + vector[axis] = defaultValues[i, 3][axis]; + rectTransform.sizeDelta = vector; + } + if (doPivot && layoutMode != LayoutDropdownWindow.LayoutMode.Undefined) + { + RectTransformEditor.SetPivotSmart(rectTransform, LayoutDropdownWindow.kPivotsForModes[(int)layoutMode], axis, true, true); + } + Vector2 vector2 = Vector2.zero; + switch (layoutMode) + { + case LayoutDropdownWindow.LayoutMode.Min: + RectTransformEditor.SetAnchorSmart(rectTransform, 0f, axis, false, true, true); + RectTransformEditor.SetAnchorSmart(rectTransform, 0f, axis, true, true, true); + vector2 = rectTransform.offsetMin; + EditorUtility.SetDirty(rectTransform); + break; + case LayoutDropdownWindow.LayoutMode.Middle: + RectTransformEditor.SetAnchorSmart(rectTransform, 0.5f, axis, false, true, true); + RectTransformEditor.SetAnchorSmart(rectTransform, 0.5f, axis, true, true, true); + vector2 = (rectTransform.offsetMin + rectTransform.offsetMax) * 0.5f; + EditorUtility.SetDirty(rectTransform); + break; + case LayoutDropdownWindow.LayoutMode.Max: + RectTransformEditor.SetAnchorSmart(rectTransform, 1f, axis, false, true, true); + RectTransformEditor.SetAnchorSmart(rectTransform, 1f, axis, true, true, true); + vector2 = rectTransform.offsetMax; + EditorUtility.SetDirty(rectTransform); + break; + case LayoutDropdownWindow.LayoutMode.Stretch: + RectTransformEditor.SetAnchorSmart(rectTransform, 0f, axis, false, true, true); + RectTransformEditor.SetAnchorSmart(rectTransform, 1f, axis, true, true, true); + vector2 = (rectTransform.offsetMin + rectTransform.offsetMax) * 0.5f; + EditorUtility.SetDirty(rectTransform); + break; + } + if (doPosition) + { + Vector2 anchoredPosition = rectTransform.anchoredPosition; + float num = anchoredPosition[axis]; + anchoredPosition[axis] = num - vector2[axis]; + rectTransform.anchoredPosition = anchoredPosition; + if (layoutMode == LayoutDropdownWindow.LayoutMode.Stretch) + { + Vector2 sizeDelta2 = rectTransform.sizeDelta; + sizeDelta2[axis] = 0f; + rectTransform.sizeDelta = sizeDelta2; + } + } + } + anchorMin.serializedObject.Update(); + } + internal static void DrawLayoutMode(Rect rect, SerializedProperty anchorMin, SerializedProperty anchorMax, SerializedProperty position, SerializedProperty sizeDelta) + { + LayoutDropdownWindow.LayoutMode layoutModeForAxis = LayoutDropdownWindow.GetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, 0); + LayoutDropdownWindow.LayoutMode vMode = LayoutDropdownWindow.GetLayoutModeForAxis(anchorMin, anchorMax, position, sizeDelta, 1); + vMode = LayoutDropdownWindow.SwappedVMode(vMode); + LayoutDropdownWindow.DrawLayoutMode(rect, layoutModeForAxis, vMode); + } + internal static void DrawLayoutMode(Rect position, LayoutDropdownWindow.LayoutMode hMode, LayoutDropdownWindow.LayoutMode vMode) + { + LayoutDropdownWindow.DrawLayoutMode(position, hMode, vMode, false, false); + } + internal static void DrawLayoutMode(Rect position, LayoutDropdownWindow.LayoutMode hMode, LayoutDropdownWindow.LayoutMode vMode, bool doPivot) + { + LayoutDropdownWindow.DrawLayoutMode(position, hMode, vMode, doPivot, false); + } + internal static void DrawLayoutMode(Rect position, LayoutDropdownWindow.LayoutMode hMode, LayoutDropdownWindow.LayoutMode vMode, bool doPivot, bool doPosition) + { + if (LayoutDropdownWindow.s_Styles == null) + { + LayoutDropdownWindow.s_Styles = new LayoutDropdownWindow.Styles(); + } + Color color = GUI.color; + int num = (int)Mathf.Min(position.width, position.height); + if (num % 2 == 0) + { + num--; + } + int num2 = num / 2; + if (num2 % 2 == 0) + { + num2++; + } + Vector2 b = (float)num * Vector2.one; + Vector2 b2 = (float)num2 * Vector2.one; + Vector2 vector = (position.size - b) / 2f; + vector.x = Mathf.Floor(vector.x); + vector.y = Mathf.Floor(vector.y); + Vector2 vector2 = (position.size - b2) / 2f; + vector2.x = Mathf.Floor(vector2.x); + vector2.y = Mathf.Floor(vector2.y); + Rect position2 = new Rect(position.x + vector.x, position.y + vector.y, b.x, b.y); + Rect position3 = new Rect(position.x + vector2.x, position.y + vector2.y, b2.x, b2.y); + if (doPosition) + { + for (int i = 0; i < 2; i++) + { + LayoutDropdownWindow.LayoutMode layoutMode = (i != 0) ? vMode : hMode; + if (layoutMode == LayoutDropdownWindow.LayoutMode.Min) + { + Vector2 center = position3.center; + int index; + int expr_181 = index = i; + float num3 = center[index]; + center[expr_181] = num3 + (position2.min[i] - position3.min[i]); + position3.center = center; + } + if (layoutMode == LayoutDropdownWindow.LayoutMode.Middle) + { + } + if (layoutMode == LayoutDropdownWindow.LayoutMode.Max) + { + Vector2 center2 = position3.center; + int index; + int expr_1E5 = index = i; + float num3 = center2[index]; + center2[expr_1E5] = num3 + (position2.max[i] - position3.max[i]); + position3.center = center2; + } + if (layoutMode == LayoutDropdownWindow.LayoutMode.Stretch) + { + Vector2 min = position3.min; + Vector2 max = position3.max; + min[i] = position2.min[i]; + max[i] = position2.max[i]; + position3.min = min; + position3.max = max; + } + } + } + Rect rect = default(Rect); + Vector2 zero = Vector2.zero; + Vector2 zero2 = Vector2.zero; + for (int j = 0; j < 2; j++) + { + LayoutDropdownWindow.LayoutMode layoutMode2 = (j != 0) ? vMode : hMode; + if (layoutMode2 == LayoutDropdownWindow.LayoutMode.Min) + { + zero[j] = position2.min[j] + 0.5f; + zero2[j] = position2.min[j] + 0.5f; + } + if (layoutMode2 == LayoutDropdownWindow.LayoutMode.Middle) + { + zero[j] = position2.center[j]; + zero2[j] = position2.center[j]; + } + if (layoutMode2 == LayoutDropdownWindow.LayoutMode.Max) + { + zero[j] = position2.max[j] - 0.5f; + zero2[j] = position2.max[j] - 0.5f; + } + if (layoutMode2 == LayoutDropdownWindow.LayoutMode.Stretch) + { + zero[j] = position2.min[j] + 0.5f; + zero2[j] = position2.max[j] - 0.5f; + } + } + rect.min = zero; + rect.max = zero2; + if (Event.current.type == EventType.Repaint) + { + GUI.color = LayoutDropdownWindow.s_Styles.parentColor * color; + LayoutDropdownWindow.s_Styles.frame.Draw(position2, false, false, false, false); + } + if (hMode != LayoutDropdownWindow.LayoutMode.Undefined && hMode != LayoutDropdownWindow.LayoutMode.Stretch) + { + GUI.color = LayoutDropdownWindow.s_Styles.simpleAnchorColor * color; + GUI.DrawTexture(new Rect(rect.xMin - 0.5f, position2.y + 1f, 1f, position2.height - 2f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(rect.xMax - 0.5f, position2.y + 1f, 1f, position2.height - 2f), EditorGUIUtility.whiteTexture); + } + if (vMode != LayoutDropdownWindow.LayoutMode.Undefined && vMode != LayoutDropdownWindow.LayoutMode.Stretch) + { + GUI.color = LayoutDropdownWindow.s_Styles.simpleAnchorColor * color; + GUI.DrawTexture(new Rect(position2.x + 1f, rect.yMin - 0.5f, position2.width - 2f, 1f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(position2.x + 1f, rect.yMax - 0.5f, position2.width - 2f, 1f), EditorGUIUtility.whiteTexture); + } + if (hMode == LayoutDropdownWindow.LayoutMode.Stretch) + { + GUI.color = LayoutDropdownWindow.s_Styles.stretchAnchorColor * color; + LayoutDropdownWindow.DrawArrow(new Rect(position3.x + 1f, position3.center.y - 0.5f, position3.width - 2f, 1f)); + } + if (vMode == LayoutDropdownWindow.LayoutMode.Stretch) + { + GUI.color = LayoutDropdownWindow.s_Styles.stretchAnchorColor * color; + LayoutDropdownWindow.DrawArrow(new Rect(position3.center.x - 0.5f, position3.y + 1f, 1f, position3.height - 2f)); + } + if (Event.current.type == EventType.Repaint) + { + GUI.color = LayoutDropdownWindow.s_Styles.selfColor * color; + LayoutDropdownWindow.s_Styles.frame.Draw(position3, false, false, false, false); + } + if (doPivot && hMode != LayoutDropdownWindow.LayoutMode.Undefined && vMode != LayoutDropdownWindow.LayoutMode.Undefined) + { + Vector2 vector3 = new Vector2(Mathf.Lerp(position3.xMin + 0.5f, position3.xMax - 0.5f, LayoutDropdownWindow.kPivotsForModes[(int)hMode]), Mathf.Lerp(position3.yMin + 0.5f, position3.yMax - 0.5f, LayoutDropdownWindow.kPivotsForModes[(int)vMode])); + GUI.color = LayoutDropdownWindow.s_Styles.pivotColor * color; + GUI.DrawTexture(new Rect(vector3.x - 2.5f, vector3.y - 1.5f, 5f, 3f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(vector3.x - 1.5f, vector3.y - 2.5f, 3f, 5f), EditorGUIUtility.whiteTexture); + } + if (hMode != LayoutDropdownWindow.LayoutMode.Undefined && vMode != LayoutDropdownWindow.LayoutMode.Undefined) + { + GUI.color = LayoutDropdownWindow.s_Styles.anchorCornerColor * color; + GUI.DrawTexture(new Rect(rect.xMin - 1.5f, rect.yMin - 1.5f, 2f, 2f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(rect.xMax - 0.5f, rect.yMin - 1.5f, 2f, 2f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(rect.xMin - 1.5f, rect.yMax - 0.5f, 2f, 2f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(rect.xMax - 0.5f, rect.yMax - 0.5f, 2f, 2f), EditorGUIUtility.whiteTexture); + } + GUI.color = color; + } + private static void DrawArrow(Rect lineRect) + { + GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture); + if (lineRect.width == 1f) + { + GUI.DrawTexture(new Rect(lineRect.x - 1f, lineRect.y + 1f, 3f, 1f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.x - 2f, lineRect.y + 2f, 5f, 1f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.x - 1f, lineRect.yMax - 2f, 3f, 1f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.x - 2f, lineRect.yMax - 3f, 5f, 1f), EditorGUIUtility.whiteTexture); + } + else + { + GUI.DrawTexture(new Rect(lineRect.x + 1f, lineRect.y - 1f, 1f, 3f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.x + 2f, lineRect.y - 2f, 1f, 5f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.xMax - 2f, lineRect.y - 1f, 1f, 3f), EditorGUIUtility.whiteTexture); + GUI.DrawTexture(new Rect(lineRect.xMax - 3f, lineRect.y - 2f, 1f, 5f), EditorGUIUtility.whiteTexture); + } + } + } +} diff --git a/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs b/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs new file mode 100644 index 00000000..ec0fdf66 --- /dev/null +++ b/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +namespace UnityEditor +{ + internal abstract class LazyTreeViewDataSource : TreeViewDataSource + { + public LazyTreeViewDataSource(TreeView treeView) : base(treeView) + { + } + protected abstract HashSet GetParentsAbove(int id); + protected abstract HashSet GetParentsBelow(int id); + public override TreeViewItem FindItem(int id) + { + HashSet hashSet = new HashSet(base.expandedIDs); + int count = hashSet.Count; + HashSet parentsAbove = this.GetParentsAbove(id); + hashSet.UnionWith(parentsAbove); + if (count != hashSet.Count) + { + this.SetExpandedIDs(hashSet.ToArray()); + if (this.m_NeedRefreshVisibleFolders) + { + this.FetchData(); + } + } + return base.FindItem(id); + } + public override void SetExpandedWithChildren(TreeViewItem item, bool expand) + { + HashSet hashSet = new HashSet(base.expandedIDs); + HashSet parentsBelow = this.GetParentsBelow(item.id); + if (expand) + { + hashSet.UnionWith(parentsBelow); + } + else + { + hashSet.ExceptWith(parentsBelow); + } + this.SetExpandedIDs(hashSet.ToArray()); + } + public override bool SetExpanded(int id, bool expand) + { + if (base.SetExpanded(id, expand)) + { + InternalEditorUtility.expandedProjectWindowItems = base.expandedIDs.ToArray(); + return true; + } + return false; + } + public override List GetVisibleRows() + { + if (this.m_VisibleRows == null || this.m_NeedRefreshVisibleFolders) + { + this.FetchData(); + this.m_NeedRefreshVisibleFolders = false; + this.m_TreeView.Repaint(); + } + return this.m_VisibleRows; + } + } +} diff --git a/UnityEditor/UnityEditor/LicenseManagementWindow.cs b/UnityEditor/UnityEditor/LicenseManagementWindow.cs new file mode 100644 index 00000000..28ca1d3f --- /dev/null +++ b/UnityEditor/UnityEditor/LicenseManagementWindow.cs @@ -0,0 +1,120 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class LicenseManagementWindow : EditorWindow + { + private static int width = 600; + private static int height = 350; + private static int left = 0; + private static int top = 0; + private static int offsetX = 50; + private static int offsetY = 25; + private static int buttonWidth = 140; + private static Rect windowArea; + private static Rect rectArea = new Rect((float)LicenseManagementWindow.offsetX, (float)LicenseManagementWindow.offsetY, (float)(LicenseManagementWindow.width - LicenseManagementWindow.offsetX * 2), (float)(LicenseManagementWindow.height - LicenseManagementWindow.offsetY * 2)); + private static LicenseManagementWindow win = null; + private static LicenseManagementWindow Window + { + get + { + if (LicenseManagementWindow.win == null) + { + LicenseManagementWindow.win = EditorWindow.GetWindowWithRect(LicenseManagementWindow.windowArea, true, "License Management"); + } + return LicenseManagementWindow.win; + } + } + private static void ShowWindow() + { + Resolution currentResolution = Screen.currentResolution; + LicenseManagementWindow.left = (currentResolution.width - LicenseManagementWindow.width) / 2; + LicenseManagementWindow.top = (currentResolution.height - LicenseManagementWindow.height) / 2; + LicenseManagementWindow.windowArea = new Rect((float)LicenseManagementWindow.left, (float)LicenseManagementWindow.top, (float)LicenseManagementWindow.width, (float)LicenseManagementWindow.height); + LicenseManagementWindow.win = LicenseManagementWindow.Window; + LicenseManagementWindow.win.position = LicenseManagementWindow.windowArea; + LicenseManagementWindow.win.Show(); + } + private void OnGUI() + { + GUILayout.BeginArea(LicenseManagementWindow.rectArea); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Check for updates", new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.Width((float)LicenseManagementWindow.buttonWidth) + })) + { + LicenseManagementWindow.CheckForUpdates(); + } + GUI.skin.label.wordWrap = true; + GUILayout.Label("Checks for updates to the currently installed license. If you have purchased addons you can install them by pressing this button (Internet access required)", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(15f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Activate new license", new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.Width((float)LicenseManagementWindow.buttonWidth) + })) + { + LicenseManagementWindow.ActivateNewLicense(); + LicenseManagementWindow.Window.Close(); + } + GUILayout.Label("Activate Unity with a different serial number, switch to a free serial or start a trial period if you are eligible for it (Internet access required).", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(15f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Return license", new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.Width((float)LicenseManagementWindow.buttonWidth) + })) + { + LicenseManagementWindow.ReturnLicense(); + } + GUILayout.Label("Return this license and free an activation for the serial it is using. You can then reuse the activation on another machine (Internet access required).", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(15f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Manual activation", new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.Width((float)LicenseManagementWindow.buttonWidth) + })) + { + LicenseManagementWindow.ManualActivation(); + } + GUILayout.Label("Start the manual activation process, you can save this machines license activation request file or deploy a license file you have already activated manually.", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Space(15f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Unity FAQ", new GUILayoutOption[] + { + GUILayout.ExpandHeight(true), + GUILayout.Width((float)LicenseManagementWindow.buttonWidth) + })) + { + Application.OpenURL("http://unity3d.com/unity/faq"); + } + GUILayout.Label("Open the Unity FAQ web page, where you can find information about Unity's license system.", new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUILayout.EndArea(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CheckForUpdates(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ActivateNewLicense(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ManualActivation(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ReturnLicense(); + } +} diff --git a/UnityEditor/UnityEditor/LightEditor.cs b/UnityEditor/UnityEditor/LightEditor.cs new file mode 100644 index 00000000..3899d833 --- /dev/null +++ b/UnityEditor/UnityEditor/LightEditor.cs @@ -0,0 +1,322 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Light))] + internal class LightEditor : Editor + { + private SerializedProperty m_Type; + private SerializedProperty m_Range; + private SerializedProperty m_SpotAngle; + private SerializedProperty m_CookieSize; + private SerializedProperty m_Color; + private SerializedProperty m_Intensity; + private SerializedProperty m_Cookie; + private SerializedProperty m_ShadowsType; + private SerializedProperty m_ShadowsStrength; + private SerializedProperty m_ShadowsResolution; + private SerializedProperty m_ShadowsBias; + private SerializedProperty m_ShadowsSoftness; + private SerializedProperty m_ShadowsSoftnessFade; + private SerializedProperty m_Halo; + private SerializedProperty m_Flare; + private SerializedProperty m_RenderMode; + private SerializedProperty m_CullingMask; + private SerializedProperty m_Lightmapping; + private SerializedProperty m_AreaSizeX; + private SerializedProperty m_AreaSizeY; + private AnimBool m_ShowSpotOptions = new AnimBool(); + private AnimBool m_ShowPointOptions = new AnimBool(); + private AnimBool m_ShowSoftOptions = new AnimBool(); + private AnimBool m_ShowDirOptions = new AnimBool(); + private AnimBool m_ShowAreaOptions = new AnimBool(); + private AnimBool m_ShowShadowOptions = new AnimBool(); + private AnimBool m_ShowShadowWarning = new AnimBool(); + private AnimBool m_ShowForwardShadowsWarning = new AnimBool(); + private AnimBool m_ShowAreaWarning = new AnimBool(); + private bool m_UsingDeferred; + internal static Color kGizmoLight = new Color(0.996078432f, 0.992156863f, 0.533333361f, 0.5019608f); + internal static Color kGizmoDisabledLight = new Color(0.5294118f, 0.454901963f, 0.196078435f, 0.5019608f); + private bool typeIsSame + { + get + { + return !this.m_Type.hasMultipleDifferentValues; + } + } + private bool shadowTypeIsSame + { + get + { + return !this.m_ShadowsType.hasMultipleDifferentValues; + } + } + private Light light + { + get + { + return this.target as Light; + } + } + private bool spotOptionsValue + { + get + { + return this.typeIsSame && this.light.type == LightType.Spot; + } + } + private bool pointOptionsValue + { + get + { + return this.typeIsSame && this.light.type == LightType.Point; + } + } + private bool softOptionsValue + { + get + { + return this.shadowTypeIsSame && this.typeIsSame && this.light.shadows == LightShadows.Soft && this.light.type == LightType.Directional; + } + } + private bool dirOptionsValue + { + get + { + return this.typeIsSame && this.light.type == LightType.Directional; + } + } + private bool areaOptionsValue + { + get + { + return this.typeIsSame && this.light.type == LightType.Area; + } + } + private bool shadowOptionsValue + { + get + { + return this.shadowTypeIsSame && this.light.shadows != LightShadows.None; + } + } + private bool shadowWarningValue + { + get + { + return this.typeIsSame && !InternalEditorUtility.HasPro() && this.light.type != LightType.Directional; + } + } + private bool forwardWarningValue + { + get + { + return this.typeIsSame && !this.m_UsingDeferred && this.light.type != LightType.Directional; + } + } + private bool areaWarningValue + { + get + { + return this.typeIsSame && !InternalEditorUtility.HasPro() && this.light.type == LightType.Area; + } + } + private void InitShowOptions() + { + this.m_ShowSpotOptions.value = this.spotOptionsValue; + this.m_ShowPointOptions.value = this.pointOptionsValue; + this.m_ShowSoftOptions.value = this.softOptionsValue; + this.m_ShowDirOptions.value = this.dirOptionsValue; + this.m_ShowAreaOptions.value = this.areaOptionsValue; + this.m_ShowShadowOptions.value = this.shadowOptionsValue; + this.m_ShowShadowWarning.value = this.shadowWarningValue; + this.m_ShowForwardShadowsWarning.value = this.forwardWarningValue; + this.m_ShowAreaWarning.value = this.areaWarningValue; + this.m_ShowSpotOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowPointOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowDirOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowAreaOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowShadowOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowShadowWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowForwardShadowsWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowSoftOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowAreaWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + private void UpdateShowOptions() + { + this.m_ShowSpotOptions.target = this.spotOptionsValue; + this.m_ShowPointOptions.target = this.pointOptionsValue; + this.m_ShowSoftOptions.target = this.softOptionsValue; + this.m_ShowDirOptions.target = this.dirOptionsValue; + this.m_ShowAreaOptions.target = this.areaOptionsValue; + this.m_ShowShadowOptions.target = this.shadowOptionsValue; + this.m_ShowShadowWarning.target = this.shadowWarningValue; + this.m_ShowForwardShadowsWarning.target = this.forwardWarningValue; + this.m_ShowAreaWarning.target = this.areaWarningValue; + } + private void OnEnable() + { + this.m_Type = base.serializedObject.FindProperty("m_Type"); + this.m_Range = base.serializedObject.FindProperty("m_Range"); + this.m_SpotAngle = base.serializedObject.FindProperty("m_SpotAngle"); + this.m_CookieSize = base.serializedObject.FindProperty("m_CookieSize"); + this.m_Color = base.serializedObject.FindProperty("m_Color"); + this.m_Intensity = base.serializedObject.FindProperty("m_Intensity"); + this.m_Cookie = base.serializedObject.FindProperty("m_Cookie"); + this.m_ShadowsType = base.serializedObject.FindProperty("m_Shadows.m_Type"); + this.m_ShadowsStrength = base.serializedObject.FindProperty("m_Shadows.m_Strength"); + this.m_ShadowsResolution = base.serializedObject.FindProperty("m_Shadows.m_Resolution"); + this.m_ShadowsBias = base.serializedObject.FindProperty("m_Shadows.m_Bias"); + this.m_ShadowsSoftness = base.serializedObject.FindProperty("m_Shadows.m_Softness"); + this.m_ShadowsSoftnessFade = base.serializedObject.FindProperty("m_Shadows.m_SoftnessFade"); + this.m_Halo = base.serializedObject.FindProperty("m_DrawHalo"); + this.m_Flare = base.serializedObject.FindProperty("m_Flare"); + this.m_RenderMode = base.serializedObject.FindProperty("m_RenderMode"); + this.m_CullingMask = base.serializedObject.FindProperty("m_CullingMask"); + this.m_Lightmapping = base.serializedObject.FindProperty("m_Lightmapping"); + this.m_AreaSizeX = base.serializedObject.FindProperty("m_AreaSize.x"); + this.m_AreaSizeY = base.serializedObject.FindProperty("m_AreaSize.y"); + this.InitShowOptions(); + this.m_UsingDeferred = CameraUtility.DoesAnyCameraUseDeferred(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + this.UpdateShowOptions(); + EditorGUILayout.PropertyField(this.m_Type, new GUILayoutOption[0]); + bool flag = this.m_ShowDirOptions.isAnimating && this.m_ShowAreaOptions.isAnimating && (this.m_ShowDirOptions.target || this.m_ShowAreaOptions.target); + float value = (!flag) ? (1f - Mathf.Max(this.m_ShowDirOptions.faded, this.m_ShowAreaOptions.faded)) : 0f; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowAreaWarning.faded)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("LightEditor.AreaLightsProOnly"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(value)) + { + EditorGUILayout.PropertyField(this.m_Range, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowSpotOptions.faded)) + { + EditorGUILayout.Slider(this.m_SpotAngle, 1f, 179f, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_Color, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Intensity, 0f, 8f, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowAreaOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_Cookie, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowDirOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_CookieSize, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_ShadowsType, new GUIContent("Shadow Type", "Shadow cast options"), new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowOptions.faded)) + { + EditorGUI.indentLevel++; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowForwardShadowsWarning.faded)) + { + GUIContent gUIContent2 = EditorGUIUtility.TextContent("LightEditor.ForwardRenderingShadowsWarning"); + EditorGUILayout.HelpBox(gUIContent2.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowWarning.faded)) + { + GUIContent gUIContent3 = EditorGUIUtility.TextContent("LightEditor.NoShadowsWarning"); + EditorGUILayout.HelpBox(gUIContent3.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowShadowWarning.faded)) + { + EditorGUILayout.Slider(this.m_ShadowsStrength, 0f, 1f, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ShadowsResolution, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ShadowsBias, 0f, 2f, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowSoftOptions.faded)) + { + EditorGUILayout.Slider(this.m_ShadowsSoftness, 1f, 8f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ShadowsSoftnessFade, 0.1f, 5f, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_Halo, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Flare, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_RenderMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Lightmapping, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowAreaOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_AreaSizeX, new GUIContent("Width"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AreaSizeY, new GUIContent("Height"), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Space(); + base.serializedObject.ApplyModifiedProperties(); + } + private void OnSceneGUI() + { + Light light = (Light)this.target; + Color color = Handles.color; + if (light.enabled) + { + Handles.color = LightEditor.kGizmoLight; + } + else + { + Handles.color = LightEditor.kGizmoDisabledLight; + } + float num = light.range; + switch (light.type) + { + case LightType.Spot: + { + Color color2 = Handles.color; + color2.a = Mathf.Clamp01(color.a * 2f); + Handles.color = color2; + Vector2 angleAndRange = new Vector2(light.spotAngle, light.range); + angleAndRange = Handles.ConeHandle(light.transform.rotation, light.transform.position, angleAndRange, 1f, 1f, true); + if (GUI.changed) + { + Undo.RecordObject(light, "Adjust Spot Light"); + light.spotAngle = angleAndRange.x; + light.range = Mathf.Max(angleAndRange.y, 0.01f); + } + break; + } + case LightType.Point: + num = Handles.RadiusHandle(Quaternion.identity, light.transform.position, num, true); + if (GUI.changed) + { + Undo.RecordObject(light, "Adjust Point Light"); + light.range = num; + } + break; + case LightType.Area: + { + EditorGUI.BeginChangeCheck(); + Vector2 areaSize = Handles.DoRectHandles(light.transform.rotation, light.transform.position, light.areaSize); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObject(light, "Adjust Area Light"); + light.areaSize = areaSize; + } + break; + } + } + Handles.color = color; + } + } +} diff --git a/UnityEditor/UnityEditor/LightProbeGUI.cs b/UnityEditor/UnityEditor/LightProbeGUI.cs new file mode 100644 index 00000000..758ec566 --- /dev/null +++ b/UnityEditor/UnityEditor/LightProbeGUI.cs @@ -0,0 +1,15 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class LightProbeGUI + { + private const int kLightProbeCoefficientCount = 27; + private const float kDuplicateEpsilonSq = 0.1f; + public void DisplayControls(SceneView sceneView) + { + LightmapVisualization.showLightProbeLocations = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.ShowProbes"), LightmapVisualization.showLightProbeLocations, new GUILayoutOption[0]); + LightmapVisualization.showLightProbeCells = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.ShowCells"), LightmapVisualization.showLightProbeCells, new GUILayoutOption[0]); + } + } +} diff --git a/UnityEditor/UnityEditor/LightProbeGroupEditor.cs b/UnityEditor/UnityEditor/LightProbeGroupEditor.cs new file mode 100644 index 00000000..a6e5d8de --- /dev/null +++ b/UnityEditor/UnityEditor/LightProbeGroupEditor.cs @@ -0,0 +1,485 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Serialization; +using UnityEngine; +namespace UnityEditor +{ + internal class LightProbeGroupEditor : IEditablePoint + { + private const int kLightProbeCoefficientCount = 27; + private const float kDuplicateEpsilonSq = 0.1f; + private bool m_Editing; + private List m_SourcePositions; + private List m_Selection = new List(); + private readonly LightProbeGroupSelection m_SerializedSelectedProbes; + private readonly LightProbeGroup m_Group; + private bool m_ShouldRecalculateTetrahedra; + private Vector3 m_LastPosition = Vector3.zero; + private Quaternion m_LastRotation = Quaternion.identity; + private Vector3 m_LastScale = Vector3.one; + private static readonly Color kCloudColor = new Color(0.784313738f, 0.784313738f, 0.0784313753f, 0.85f); + private static readonly Color kSelectedCloudColor = new Color(0.3f, 0.6f, 1f, 1f); + public Bounds selectedProbeBounds + { + get + { + if (this.m_Selection.Count == 0) + { + return default(Bounds); + } + if (this.m_Selection.Count == 1) + { + return new Bounds(this.GetWorldPosition(this.m_Selection[0]), new Vector3(1f, 1f, 1f)); + } + Vector3 min = new Vector3(3.40282347E+38f, 3.40282347E+38f, 3.40282347E+38f); + Vector3 max = new Vector3(-3.40282347E+38f, -3.40282347E+38f, -3.40282347E+38f); + foreach (int current in this.m_Selection) + { + Vector3 worldPosition = this.GetWorldPosition(current); + if (worldPosition.x < min.x) + { + min.x = worldPosition.x; + } + if (worldPosition.y < min.y) + { + min.y = worldPosition.y; + } + if (worldPosition.z < min.z) + { + min.z = worldPosition.z; + } + if (worldPosition.x > max.x) + { + max.x = worldPosition.x; + } + if (worldPosition.y > max.y) + { + max.y = worldPosition.y; + } + if (worldPosition.z > max.z) + { + max.z = worldPosition.z; + } + } + Bounds result = default(Bounds); + result.SetMinMax(min, max); + return result; + } + } + public int Count + { + get + { + return this.m_SourcePositions.Count; + } + } + public int SelectedCount + { + get + { + return this.m_Selection.Count; + } + } + public LightProbeGroupEditor(LightProbeGroup group) + { + this.m_Group = group; + this.MarkTetrahedraDirty(); + this.m_SerializedSelectedProbes = ScriptableObject.CreateInstance(); + this.m_SerializedSelectedProbes.hideFlags = HideFlags.HideAndDontSave; + } + public void SetEditing(bool editing) + { + this.m_Editing = editing; + } + public void AddProbe(Vector3 position) + { + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Add Probe"); + this.m_SourcePositions.Add(position); + this.SelectProbe(this.m_SourcePositions.Count - 1); + this.MarkTetrahedraDirty(); + } + private void SelectProbe(int i) + { + if (!this.m_Selection.Contains(i)) + { + this.m_Selection.Add(i); + } + } + public void SelectAllProbes() + { + this.DeselectProbes(); + for (int i = 0; i < this.m_SourcePositions.Count; i++) + { + this.SelectProbe(i); + } + } + public void DeselectProbes() + { + this.m_Selection.Clear(); + } + private IEnumerable SelectedProbePositions() + { + return ( + from t in this.m_Selection + select this.m_SourcePositions[t]).ToList(); + } + public void DuplicateSelectedProbes() + { + if (this.m_Selection.Count == 0) + { + return; + } + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Duplicate Probes"); + foreach (Vector3 current in this.SelectedProbePositions()) + { + this.m_SourcePositions.Add(current); + } + this.MarkTetrahedraDirty(); + } + private void CopySelectedProbes() + { + IEnumerable source = this.SelectedProbePositions(); + XmlSerializer xmlSerializer = new XmlSerializer(typeof(Vector3[])); + StringWriter stringWriter = new StringWriter(); + xmlSerializer.Serialize(stringWriter, ( + from pos in source + select this.m_Group.transform.TransformPoint(pos)).ToArray()); + stringWriter.Close(); + GUIUtility.systemCopyBuffer = stringWriter.ToString(); + } + private static bool CanPasteProbes() + { + bool result; + try + { + XmlSerializer xmlSerializer = new XmlSerializer(typeof(Vector3[])); + StringReader stringReader = new StringReader(GUIUtility.systemCopyBuffer); + xmlSerializer.Deserialize(stringReader); + stringReader.Close(); + result = true; + } + catch + { + result = false; + } + return result; + } + private bool PasteProbes() + { + bool result; + try + { + XmlSerializer xmlSerializer = new XmlSerializer(typeof(Vector3[])); + StringReader stringReader = new StringReader(GUIUtility.systemCopyBuffer); + Vector3[] array = (Vector3[])xmlSerializer.Deserialize(stringReader); + stringReader.Close(); + if (array.Length == 0) + { + result = false; + } + else + { + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Paste Probes"); + int count = this.m_SourcePositions.Count; + Vector3[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Vector3 position = array2[i]; + this.m_SourcePositions.Add(this.m_Group.transform.InverseTransformPoint(position)); + } + this.DeselectProbes(); + for (int j = count; j < count + array.Length; j++) + { + this.SelectProbe(j); + } + this.MarkTetrahedraDirty(); + result = true; + } + } + catch + { + result = false; + } + return result; + } + public void RemoveSelectedProbes() + { + if (this.m_Selection.Count == 0) + { + return; + } + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Delete Probes"); + IOrderedEnumerable orderedEnumerable = + from x in this.m_Selection + orderby x descending + select x; + foreach (int current in orderedEnumerable) + { + this.m_SourcePositions.RemoveAt(current); + } + this.DeselectProbes(); + this.MarkTetrahedraDirty(); + } + public void PullProbePositions() + { + this.m_SourcePositions = new List(this.m_Group.probePositions); + this.m_Selection = new List(this.m_SerializedSelectedProbes.m_Selection); + } + public void PushProbePositions() + { + bool flag = false; + if (this.m_Group.probePositions.Length != this.m_SourcePositions.Count || this.m_SerializedSelectedProbes.m_Selection.Count != this.m_Selection.Count) + { + flag = true; + } + if (!flag) + { + if (this.m_Group.probePositions.Where((Vector3 t, int i) => t != this.m_SourcePositions[i]).Any()) + { + flag = true; + } + for (int j = 0; j < this.m_SerializedSelectedProbes.m_Selection.Count; j++) + { + if (this.m_SerializedSelectedProbes.m_Selection[j] != this.m_Selection[j]) + { + flag = true; + } + } + } + if (flag) + { + this.m_Group.probePositions = this.m_SourcePositions.ToArray(); + this.m_SerializedSelectedProbes.m_Selection = this.m_Selection; + LightmappingWindow.ProbePositionsChanged(); + } + } + private void DrawTetrahedra() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (SceneView.lastActiveSceneView) + { + LightmapVisualization.DrawTetrahedra(this.m_ShouldRecalculateTetrahedra, SceneView.lastActiveSceneView.camera.transform.position); + this.m_ShouldRecalculateTetrahedra = false; + } + } + public static void TetrahedralizeSceneProbes(out Vector3[] positions, out int[] indices) + { + LightProbeGroup[] array = UnityEngine.Object.FindObjectsOfType(typeof(LightProbeGroup)) as LightProbeGroup[]; + if (array == null) + { + positions = new Vector3[0]; + indices = new int[0]; + return; + } + List list = new List(); + LightProbeGroup[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + LightProbeGroup lightProbeGroup = array2[i]; + Vector3[] probePositions = lightProbeGroup.probePositions; + Vector3[] array3 = probePositions; + for (int j = 0; j < array3.Length; j++) + { + Vector3 position = array3[j]; + Vector3 item = lightProbeGroup.transform.TransformPoint(position); + list.Add(item); + } + } + if (list.Count == 0) + { + positions = new Vector3[0]; + indices = new int[0]; + return; + } + Lightmapping.Tetrahedralize(list.ToArray(), out indices, out positions); + } + public bool OnSceneGUI(Transform transform) + { + if (Event.current.type == EventType.Layout) + { + if (this.m_LastPosition != this.m_Group.transform.position || this.m_LastRotation != this.m_Group.transform.rotation || this.m_LastScale != this.m_Group.transform.localScale) + { + this.MarkTetrahedraDirty(); + } + this.m_LastPosition = this.m_Group.transform.position; + this.m_LastRotation = this.m_Group.transform.rotation; + this.m_LastScale = this.m_Group.transform.localScale; + } + bool firstSelect = false; + if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && this.SelectedCount == 0) + { + int num = PointEditor.FindNearest(Event.current.mousePosition, transform, this); + bool flag = num != -1; + if (flag && !this.m_Editing) + { + this.m_Editing = true; + firstSelect = true; + } + } + bool flag2 = Event.current.type == EventType.MouseUp; + if (this.m_Editing && PointEditor.SelectPoints(this, transform, ref this.m_Selection, firstSelect)) + { + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Select Probes"); + } + if (this.m_Editing && flag2 && this.SelectedCount == 0) + { + this.m_Editing = false; + this.MarkTetrahedraDirty(); + } + if ((Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand) && Event.current.commandName == "Paste") + { + if (Event.current.type == EventType.ValidateCommand && LightProbeGroupEditor.CanPasteProbes()) + { + Event.current.Use(); + } + if (Event.current.type == EventType.ExecuteCommand && this.PasteProbes()) + { + Event.current.Use(); + this.m_Editing = true; + } + } + this.DrawTetrahedra(); + PointEditor.Draw(this, transform, this.m_Selection, true); + if (!this.m_Editing) + { + return this.m_Editing; + } + if (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand) + { + bool flag3 = Event.current.type == EventType.ExecuteCommand; + string commandName = Event.current.commandName; + switch (commandName) + { + case "SoftDelete": + case "Delete": + if (flag3) + { + this.RemoveSelectedProbes(); + } + Event.current.Use(); + break; + case "Duplicate": + if (flag3) + { + this.DuplicateSelectedProbes(); + } + Event.current.Use(); + break; + case "SelectAll": + if (flag3) + { + this.SelectAllProbes(); + } + Event.current.Use(); + break; + case "Cut": + if (flag3) + { + this.CopySelectedProbes(); + this.RemoveSelectedProbes(); + } + Event.current.Use(); + break; + case "Copy": + if (flag3) + { + this.CopySelectedProbes(); + } + Event.current.Use(); + break; + } + } + if (this.m_Editing && PointEditor.MovePoints(this, transform, this.m_Selection)) + { + Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] + { + this.m_Group, + this.m_SerializedSelectedProbes + }, "Move Probes"); + if (LightmapVisualization.dynamicUpdateLightProbes) + { + this.MarkTetrahedraDirty(); + } + } + if (this.m_Editing && flag2 && !LightmapVisualization.dynamicUpdateLightProbes) + { + this.MarkTetrahedraDirty(); + } + return this.m_Editing; + } + public void MarkTetrahedraDirty() + { + this.m_ShouldRecalculateTetrahedra = true; + } + public Vector3 GetPosition(int idx) + { + return this.m_SourcePositions[idx]; + } + public Vector3 GetWorldPosition(int idx) + { + return this.m_Group.transform.TransformPoint(this.m_SourcePositions[idx]); + } + public void SetPosition(int idx, Vector3 position) + { + if (this.m_SourcePositions[idx] == position) + { + return; + } + this.m_SourcePositions[idx] = position; + } + public Color GetDefaultColor() + { + return LightProbeGroupEditor.kCloudColor; + } + public Color GetSelectedColor() + { + return LightProbeGroupEditor.kSelectedCloudColor; + } + public float GetPointScale() + { + return 10f * AnnotationUtility.iconSize; + } + public Vector3[] GetSelectedPositions() + { + Vector3[] array = new Vector3[this.SelectedCount]; + for (int i = 0; i < this.SelectedCount; i++) + { + array[i] = this.m_SourcePositions[this.m_Selection[i]]; + } + return array; + } + public IEnumerable GetPositions() + { + return this.m_SourcePositions; + } + public Vector3[] GetUnselectedPositions() + { + return this.m_SourcePositions.Where((Vector3 t, int i) => !this.m_Selection.Contains(i)).ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/LightProbeGroupInspector.cs b/UnityEditor/UnityEditor/LightProbeGroupInspector.cs new file mode 100644 index 00000000..f95fd165 --- /dev/null +++ b/UnityEditor/UnityEditor/LightProbeGroupInspector.cs @@ -0,0 +1,154 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(LightProbeGroup))] + internal class LightProbeGroupInspector : Editor + { + private LightProbeGroupEditor m_Editor; + private bool m_EditingProbes; + private bool m_ShouldFocus; + public void OnEnable() + { + this.m_Editor = new LightProbeGroupEditor(this.target as LightProbeGroup); + this.m_Editor.PullProbePositions(); + this.m_Editor.DeselectProbes(); + this.m_Editor.PushProbePositions(); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneGUIDelegate)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + private void StartEditProbes() + { + if (this.m_EditingProbes) + { + return; + } + this.m_EditingProbes = true; + this.m_Editor.SetEditing(true); + Tools.s_Hidden = true; + SceneView.RepaintAll(); + } + private void EndEditProbes() + { + if (!this.m_EditingProbes) + { + return; + } + this.m_Editor.DeselectProbes(); + this.m_EditingProbes = false; + Tools.s_Hidden = false; + } + public void OnDisable() + { + this.EndEditProbes(); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneGUIDelegate)); + if (this.target != null) + { + this.m_Editor.PushProbePositions(); + } + } + private void UndoRedoPerformed() + { + this.m_Editor.MarkTetrahedraDirty(); + } + public override void OnInspectorGUI() + { + bool flag = Application.HasAdvancedLicense(); + EditorGUI.BeginDisabledGroup(!flag); + this.m_Editor.PullProbePositions(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (GUILayout.Button("Add Probe", new GUILayoutOption[0])) + { + Vector3 position = Vector3.zero; + if (SceneView.lastActiveSceneView) + { + position = SceneView.lastActiveSceneView.pivot; + LightProbeGroup lightProbeGroup = this.target as LightProbeGroup; + if (lightProbeGroup) + { + position = lightProbeGroup.transform.InverseTransformPoint(position); + } + } + this.StartEditProbes(); + this.m_Editor.DeselectProbes(); + this.m_Editor.AddProbe(position); + } + if (GUILayout.Button("Delete Selected", new GUILayoutOption[0])) + { + this.StartEditProbes(); + this.m_Editor.RemoveSelectedProbes(); + } + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (GUILayout.Button("Select All", new GUILayoutOption[0])) + { + this.StartEditProbes(); + this.m_Editor.SelectAllProbes(); + } + if (GUILayout.Button("Duplicate Selected", new GUILayoutOption[0])) + { + this.StartEditProbes(); + this.m_Editor.DuplicateSelectedProbes(); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + this.m_Editor.PushProbePositions(); + EditorGUI.EndDisabledGroup(); + if (!flag) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("LightProbeGroup.ProOnly"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, true); + } + } + private void InternalOnSceneView() + { + if (SceneView.lastActiveSceneView != null && this.m_ShouldFocus) + { + this.m_ShouldFocus = false; + SceneView.lastActiveSceneView.FrameSelected(); + } + this.m_Editor.PullProbePositions(); + LightProbeGroup lightProbeGroup = this.target as LightProbeGroup; + if (lightProbeGroup != null) + { + if (this.m_Editor.OnSceneGUI(lightProbeGroup.transform)) + { + this.StartEditProbes(); + } + else + { + this.EndEditProbes(); + } + } + this.m_Editor.PushProbePositions(); + } + public void OnSceneGUI() + { + if (!Application.HasAdvancedLicense()) + { + return; + } + if (Event.current.type != EventType.Repaint) + { + this.InternalOnSceneView(); + } + } + public void OnSceneGUIDelegate(SceneView sceneView) + { + if (Event.current.type == EventType.Repaint) + { + this.InternalOnSceneView(); + } + } + public bool HasFrameBounds() + { + return this.m_Editor.SelectedCount > 0; + } + public Bounds OnGetFrameBounds() + { + return this.m_Editor.selectedProbeBounds; + } + } +} diff --git a/UnityEditor/UnityEditor/LightProbeGroupSelection.cs b/UnityEditor/UnityEditor/LightProbeGroupSelection.cs new file mode 100644 index 00000000..b62e24ee --- /dev/null +++ b/UnityEditor/UnityEditor/LightProbeGroupSelection.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class LightProbeGroupSelection : ScriptableObject + { + public List m_Selection = new List(); + } +} diff --git a/UnityEditor/UnityEditor/LightProbesInspector.cs b/UnityEditor/UnityEditor/LightProbesInspector.cs new file mode 100644 index 00000000..f3b23edb --- /dev/null +++ b/UnityEditor/UnityEditor/LightProbesInspector.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(LightProbes))] + internal class LightProbesInspector : Editor + { + public override void OnInspectorGUI() + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + LightProbes lightProbes = this.target as LightProbes; + GUIStyle wordWrappedMiniLabel = EditorStyles.wordWrappedMiniLabel; + GUILayout.Label("Light probe count: " + lightProbes.count, wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.Label("Cell count: " + lightProbes.cellCount, wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + } +} diff --git a/UnityEditor/UnityEditor/LightmapBakeQuality.cs b/UnityEditor/UnityEditor/LightmapBakeQuality.cs new file mode 100644 index 00000000..bd1d0d9a --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapBakeQuality.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum LightmapBakeQuality + { + High, + Low + } +} diff --git a/UnityEditor/UnityEditor/LightmapEditorSettings.cs b/UnityEditor/UnityEditor/LightmapEditorSettings.cs new file mode 100644 index 00000000..c1e037a1 --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapEditorSettings.cs @@ -0,0 +1,202 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class LightmapEditorSettings + { + public static extern float bounceBoost + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float bounceIntensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int maxAtlasWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int maxAtlasHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float resolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float lastUsedResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color skyLightColor + { + get + { + Color result; + LightmapEditorSettings.INTERNAL_get_skyLightColor(out result); + return result; + } + set + { + LightmapEditorSettings.INTERNAL_set_skyLightColor(ref value); + } + } + public static extern float skyLightIntensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern LightmapBakeQuality quality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool textureCompression + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int bounces + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int finalGatherRays + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float finalGatherContrastThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float finalGatherGradientThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int finalGatherInterpolationPoints + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float aoAmount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float aoMaxDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float aoContrast + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool lockAtlas + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int padding + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_skyLightColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_skyLightColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern UnityEngine.Object GetLightmapSettings(); + } +} diff --git a/UnityEditor/UnityEditor/LightmapVisualization.cs b/UnityEditor/UnityEditor/LightmapVisualization.cs new file mode 100644 index 00000000..bb2419a9 --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapVisualization.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class LightmapVisualization + { + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float shadowDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useLightmaps + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showLightProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showLightProbeLocations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showLightProbeCells + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool dynamicUpdateLightProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float GetLightmapLODLevelScale(Renderer renderer); + internal static void DrawPointCloud(Vector3[] unselectedPositions, Vector3[] selectedPositions, Color baseColor, Color selectedColor, float scale, Transform cloudTransform) + { + LightmapVisualization.INTERNAL_CALL_DrawPointCloud(unselectedPositions, selectedPositions, ref baseColor, ref selectedColor, scale, cloudTransform); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawPointCloud(Vector3[] unselectedPositions, Vector3[] selectedPositions, ref Color baseColor, ref Color selectedColor, float scale, Transform cloudTransform); + internal static void DrawTetrahedra(bool shouldRecalculateTetrahedra, Vector3 cameraPosition) + { + LightmapVisualization.INTERNAL_CALL_DrawTetrahedra(shouldRecalculateTetrahedra, ref cameraPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawTetrahedra(bool shouldRecalculateTetrahedra, ref Vector3 cameraPosition); + } +} diff --git a/UnityEditor/UnityEditor/Lightmapping.cs b/UnityEditor/UnityEditor/Lightmapping.cs new file mode 100644 index 00000000..9e4d45c1 --- /dev/null +++ b/UnityEditor/UnityEditor/Lightmapping.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Lightmapping + { + public static extern bool isRunning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeAsync(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Bake(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeSelectedAsync(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeSelected(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeLightProbesOnlyAsync(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeLightProbesOnly(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Cancel(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Tetrahedralize(Vector3[] positions, out int[] outIndices, out Vector3[] outPositions); + } +} diff --git a/UnityEditor/UnityEditor/LightmappingWindow.cs b/UnityEditor/UnityEditor/LightmappingWindow.cs new file mode 100644 index 00000000..02099832 --- /dev/null +++ b/UnityEditor/UnityEditor/LightmappingWindow.cs @@ -0,0 +1,1212 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + internal class LightmappingWindow : EditorWindow, IHasCustomMenu + { + private enum Mode + { + ObjectSettings, + BakeSettings, + Maps + } + private enum BakeMode + { + BakeScene, + BakeSelected, + BakeProbes + } + private class Styles + { + public GUIContent[] ModeToggles = new GUIContent[] + { + EditorGUIUtility.TextContent("LightmapEditor.ObjectSettings"), + EditorGUIUtility.TextContent("LightmapEditor.BakeSettings"), + EditorGUIUtility.TextContent("LightmapEditor.Maps") + }; + public GUIContent UseDualInForward = EditorGUIUtility.TextContent("LightmapEditor.UseDualInForward"); + public GUIContent SkyLightColor = EditorGUIUtility.TextContent("LightmapEditor.SkyLightColor"); + public GUIContent LODSurfaceDistance = EditorGUIUtility.TextContent("LightmapEditor.LODSurfaceDistance"); + public GUIContent SkyLightIntensity = EditorGUIUtility.TextContent("LightmapEditor.SkyLightIntensity"); + public GUIContent Bounces = EditorGUIUtility.TextContent("LightmapEditor.Bounces"); + public GUIContent BounceBoost = EditorGUIUtility.TextContent("LightmapEditor.BounceBoost"); + public GUIContent BounceIntensity = EditorGUIUtility.TextContent("LightmapEditor.BounceIntensity"); + public GUIContent Quality = EditorGUIUtility.TextContent("LightmapEditor.Quality"); + public GUIContent FinalGatherRays = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.Rays"); + public GUIContent FinalGatherContrastThreshold = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.ContrastThreshold"); + public GUIContent FinalGatherGradientThreshold = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.GradientThreshold"); + public GUIContent FinalGatherInterpolationPoints = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.InterpolationPoints"); + public GUIContent Resolution = EditorGUIUtility.TextContent("LightmapEditor.Resolution"); + public GUIContent EmptySelection = EditorGUIUtility.TextContent("LightmapEditor.EmptySelection"); + public GUIContent ScaleInLightmap = EditorGUIUtility.TextContent("LightmapEditor.ScaleInLightmap"); + public GUIContent Static = EditorGUIUtility.TextContent("LightmapEditor.Static"); + public GUIContent LightShadows = EditorGUIUtility.TextContent("LightmapEditor.Light.Shadows"); + public GUIContent LightIndirectIntensity = EditorGUIUtility.TextContent("LightmapEditor.Light.IndirectIntensity"); + public GUIContent LightShadowSamples = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowSamples"); + public GUIContent LightShadowRadius = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowRadius"); + public GUIContent LightShadowAngle = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowAngle"); + public GUIContent TerrainLightmapSize = EditorGUIUtility.TextContent("LightmapEditor.Terrain.LightmapSize"); + public GUIContent AO = EditorGUIUtility.TextContent("LightmapEditor.AO"); + public GUIContent AOMaxDistance = EditorGUIUtility.TextContent("LightmapEditor.AOMaxDistance"); + public GUIContent AOContrast = EditorGUIUtility.TextContent("LightmapEditor.AOContrast"); + public GUIContent MapsArraySize = EditorGUIUtility.TextContent("LightmapEditor.MapsArraySize"); + public GUIContent Mode = EditorGUIUtility.TextContent("LightmapEditor.Mode"); + public GUIContent LockAtlas = EditorGUIUtility.TextContent("LightmapEditor.LockAtlas"); + public GUIContent Atlas = EditorGUIUtility.TextContent("LightmapEditor.Atlas"); + public GUIContent AtlasIndex = EditorGUIUtility.TextContent("LightmapEditor.AtlasIndex"); + public GUIContent AtlasTilingX = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingX"); + public GUIContent AtlasTilingY = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingY"); + public GUIContent AtlasOffsetX = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetX"); + public GUIContent AtlasOffsetY = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetY"); + public GUIContent TextureCompression = EditorGUIUtility.TextContent("LightmapEditor.TextureCompression"); + public GUIContent ClampedSize = EditorGUIUtility.TextContent("LightmapEditor.ClampedSize"); + public GUIContent NoNormalsNoLightmapping = EditorGUIUtility.TextContent("LightmapEditor.NoNormalsNoLightmapping"); + public GUIContent DirectionalLightmapsProOnly = EditorGUIUtility.TextContent("LightmapEditor.DirectionalLightmapsProOnly"); + public GUIContent IncorrectLightProbePositions = EditorGUIUtility.TextContent("LightmapEditor.IncorrectLightProbePositions"); + public GUIContent Padding = EditorGUIUtility.TextContent("LightmapEditor.Padding"); + public GUIContent LightProbes = EditorGUIUtility.TextContent("LightmapEditor.LightProbes"); + public GUIStyle selectedLightmapHighlight = "LightmapEditorSelectedHighlight"; + public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; + public GUIStyle dropDownButton = "DropDownButton"; + } + private const string kBakeModeKey = "LightmapEditor.BakeMode"; + private const string kBeastSettingsFileName = "BeastSettings.xml"; + private int[] kModeValues = new int[] + { + 0, + 1, + 2 + }; + private GUIContent[] kModeStrings = new GUIContent[] + { + new GUIContent("Single Lightmaps"), + new GUIContent("Dual Lightmaps"), + new GUIContent("Directional Lightmaps") + }; + private GUIContent[] kBouncesStrings = new GUIContent[] + { + new GUIContent("0"), + new GUIContent("1"), + new GUIContent("2"), + new GUIContent("3"), + new GUIContent("4") + }; + private int[] kBouncesValues = new int[] + { + 0, + 1, + 2, + 3, + 4 + }; + private GUIContent[] kQualityStrings = new GUIContent[] + { + new GUIContent("High"), + new GUIContent("Low") + }; + private int[] kQualityValues = new int[] + { + 0, + 1 + }; + private GUIContent[] kShadowTypeStrings = new GUIContent[] + { + new GUIContent("Off"), + new GUIContent("On (Realtime: Hard Shadows)"), + new GUIContent("On (Realtime: Soft Shadows)") + }; + private int[] kShadowTypeValues = new int[] + { + 0, + 1, + 2 + }; + private GUIContent[] kTerrainLightmapSizeStrings = new GUIContent[] + { + new GUIContent("0"), + new GUIContent("32"), + new GUIContent("64"), + new GUIContent("128"), + new GUIContent("256"), + new GUIContent("512"), + new GUIContent("1024"), + new GUIContent("2048"), + new GUIContent("4096") + }; + private int[] kTerrainLightmapSizeValues = new int[] + { + 0, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096 + }; + private static LightmappingWindow s_LightmappingWindow; + private readonly LightProbeGUI m_LightProbeEditor = new LightProbeGUI(); + private Vector2 m_ScrollPosition = Vector2.zero; + private Vector2 m_ScrollPositionLightmaps = Vector2.zero; + private Vector2 m_ScrollPositionMaps = Vector2.zero; + private float m_OldResolution = -1f; + private LightmappingWindow.Mode m_Mode; + private int m_SelectedLightmap = -1; + private float m_BakeStartTime = -1f; + private string m_LastBakeTimeString = string.Empty; + private AnimBool m_ShowDualOptions = new AnimBool(); + private AnimBool m_ShowFinalGather = new AnimBool(); + private AnimBool m_ShowShadowOptions = new AnimBool(); + private AnimBool m_ShowShadowAngleOrSize = new AnimBool(); + private AnimBool m_ShowAO = new AnimBool(); + private AnimBool m_ShowClampedSize = new AnimBool(); + private AnimBool m_ShowColorSpaceWarning = new AnimBool(); + private AnimBool m_ShowAreaLight = new AnimBool(); + private bool m_ShowAtlas; + private int m_LastAmountOfLights; + private PreviewResizer m_PreviewResizer = new PreviewResizer(); + private bool m_ProbePositionsChanged = true; + private bool m_IncorrectProbePositions; + private static LightmappingWindow.Styles s_Styles; + private float m_OldQualitySettingsShadowDistance = -1f; + private float m_ShadowDistance = -1f; + private static bool s_IsVisible; + private LightmappingWindow.BakeMode bakeMode + { + get + { + return (LightmappingWindow.BakeMode)EditorPrefs.GetInt("LightmapEditor.BakeMode", 0); + } + set + { + EditorPrefs.SetInt("LightmapEditor.BakeMode", (int)value); + } + } + private static bool colorSpaceWarningValue + { + get + { + return LightmapSettings.bakedColorSpace != QualitySettings.desiredColorSpace && LightmapSettings.lightmaps.Length > 0; + } + } + public static void ProbePositionsChanged() + { + if (LightmappingWindow.s_LightmappingWindow) + { + LightmappingWindow.s_LightmappingWindow.m_ProbePositionsChanged = true; + } + } + private void OnEnable() + { + LightmappingWindow.s_LightmappingWindow = this; + this.m_ShowDualOptions.value = (LightmapSettings.lightmapsMode == LightmapsMode.Dual); + this.m_ShowFinalGather.value = (LightmapEditorSettings.bounces > 0 && InternalEditorUtility.HasPro()); + this.m_ShowShadowOptions.value = true; + this.m_ShowShadowAngleOrSize.value = true; + this.m_ShowAO.value = (LightmapEditorSettings.aoAmount > 0f); + this.m_ShowClampedSize.value = false; + this.m_ShowColorSpaceWarning.value = LightmappingWindow.colorSpaceWarningValue; + this.m_ShowAreaLight.value = false; + this.m_ShowDualOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowFinalGather.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowShadowOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowShadowAngleOrSize.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowAO.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowClampedSize.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowColorSpaceWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowAreaLight.valueChanged.AddListener(new UnityAction(base.Repaint)); + base.autoRepaintOnSceneChange = true; + this.m_PreviewResizer.Init("LightmappingPreview"); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + base.Repaint(); + } + private void OnDisable() + { + LightmappingWindow.s_LightmappingWindow = null; + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + } + private void OnBecameVisible() + { + if (LightmappingWindow.s_IsVisible) + { + return; + } + LightmappingWindow.s_IsVisible = true; + LightmapVisualization.enabled = true; + LightmapVisualization.showLightProbes = true; + if (this.m_OldQualitySettingsShadowDistance != QualitySettings.shadowDistance) + { + this.m_ShadowDistance = QualitySettings.shadowDistance; + this.m_OldQualitySettingsShadowDistance = this.m_ShadowDistance; + } + LightmapVisualization.shadowDistance = this.m_ShadowDistance; + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + LightmappingWindow.RepaintSceneAndGameViews(); + } + private void OnBecameInvisible() + { + LightmappingWindow.s_IsVisible = false; + LightmapVisualization.enabled = false; + LightmapVisualization.showLightProbes = false; + this.m_OldQualitySettingsShadowDistance = QualitySettings.shadowDistance; + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + LightmappingWindow.RepaintSceneAndGameViews(); + } + private void OnSelectionChange() + { + this.UpdateLightmapSelection(); + if (this.m_Mode == LightmappingWindow.Mode.ObjectSettings || this.m_Mode == LightmappingWindow.Mode.Maps) + { + base.Repaint(); + } + } + private static void LightmappingDone() + { + if (LightmappingWindow.s_LightmappingWindow) + { + LightmappingWindow.s_LightmappingWindow.MarkEndTime(); + LightmappingWindow.s_LightmappingWindow.Repaint(); + } + Analytics.Track("/LightMapper/Created"); + } + private static void RepaintSceneAndGameViews() + { + SceneView.RepaintAll(); + GameView.RepaintAll(); + } + private void OnGUI() + { + if (LightmappingWindow.s_Styles == null) + { + LightmappingWindow.s_Styles = new LightmappingWindow.Styles(); + } + EditorGUIUtility.labelWidth = 130f; + EditorGUILayout.Space(); + this.ModeToggle(); + EditorGUILayout.Space(); + this.m_ShowColorSpaceWarning.target = LightmappingWindow.colorSpaceWarningValue; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowColorSpaceWarning.faded)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("LightEditor.WrongColorSpaceWarning"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning); + } + EditorGUILayout.EndFadeGroup(); + this.m_ScrollPosition = EditorGUILayout.BeginScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); + switch (this.m_Mode) + { + case LightmappingWindow.Mode.ObjectSettings: + this.ObjectSettings(); + break; + case LightmappingWindow.Mode.BakeSettings: + this.BakeSettings(); + break; + case LightmappingWindow.Mode.Maps: + this.Maps(); + break; + } + EditorGUILayout.EndScrollView(); + EditorGUILayout.Space(); + if (this.m_ProbePositionsChanged && Event.current.type == EventType.Layout) + { + Vector3[] array; + int[] array2; + LightProbeGroupEditor.TetrahedralizeSceneProbes(out array, out array2); + this.m_IncorrectProbePositions = (array.Length > 0 && array2.Length == 0); + this.m_ProbePositionsChanged = false; + } + if (this.m_IncorrectProbePositions) + { + EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.IncorrectLightProbePositions.text, MessageType.Warning); + } + GUI.enabled = !EditorApplication.isPlayingOrWillChangePlaymode; + this.Buttons(); + GUI.enabled = true; + EditorGUILayout.Space(); + this.Summary(); + EditorGUILayout.BeginHorizontal(GUIContent.none, "preToolbar", new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + GUILayout.FlexibleSpace(); + GUI.Label(GUILayoutUtility.GetLastRect(), "Preview", "preToolbar2"); + EditorGUILayout.EndHorizontal(); + float num = this.m_PreviewResizer.ResizeHandle(base.position, 100f, 250f, 17f); + if (num > 0f) + { + this.Lightmaps(new Rect(0f, base.position.height - num, base.position.width, num)); + } + } + private void ModeToggle() + { + this.m_Mode = (LightmappingWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, LightmappingWindow.s_Styles.ModeToggles, "LargeButton", new GUILayoutOption[0]); + } + public void OnSceneViewGUI(SceneView sceneView) + { + if (!LightmappingWindow.s_IsVisible) + { + return; + } + SceneViewOverlay.Window(new GUIContent("Lightmap Display"), new SceneViewOverlay.WindowFunction(this.DisplayControls), 200, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + } + private void OnDidOpenScene() + { + } + private void DisplayControls(UnityEngine.Object target, SceneView sceneView) + { + EditorGUIUtility.labelWidth = 110f; + bool useLightmaps = LightmapVisualization.useLightmaps; + if (useLightmaps != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.UseLightmaps"), useLightmaps, new GUILayoutOption[0])) + { + LightmapVisualization.useLightmaps = !useLightmaps; + LightmappingWindow.RepaintSceneAndGameViews(); + } + float num = Mathf.Max(EditorGUILayout.FloatField(EditorGUIUtility.TextContent("LightmapEditor.ShadowDistance"), this.m_ShadowDistance, new GUILayoutOption[0]), 0f); + if (num != this.m_ShadowDistance) + { + this.m_ShadowDistance = num; + LightmapVisualization.shadowDistance = this.m_ShadowDistance; + LightmappingWindow.RepaintSceneAndGameViews(); + } + if (sceneView) + { + DrawCameraMode renderMode = sceneView.renderMode; + bool flag = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.VisualiseResolution"), renderMode == DrawCameraMode.LightmapResolution, new GUILayoutOption[0]); + if (flag && renderMode != DrawCameraMode.LightmapResolution) + { + sceneView.renderMode = DrawCameraMode.LightmapResolution; + sceneView.Repaint(); + } + else + { + if (!flag && renderMode == DrawCameraMode.LightmapResolution) + { + sceneView.renderMode = DrawCameraMode.Textured; + sceneView.Repaint(); + } + } + this.m_LightProbeEditor.DisplayControls(sceneView); + } + else + { + bool enabled = GUI.enabled; + GUI.enabled = false; + EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.VisualiseResolution"), false, new GUILayoutOption[0]); + GUI.enabled = enabled; + } + } + private float LightmapScaleGUI(SerializedObject so, Renderer[] renderers) + { + float num = LightmapVisualization.GetLightmapLODLevelScale(renderers[0]); + for (int i = 1; i < renderers.Length; i++) + { + if (!Mathf.Approximately(num, LightmapVisualization.GetLightmapLODLevelScale(renderers[i]))) + { + num = 1f; + } + } + SerializedProperty serializedProperty = so.FindProperty("m_ScaleInLightmap"); + float num2 = num * serializedProperty.floatValue; + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + EditorGUI.BeginProperty(controlRect, null, serializedProperty); + EditorGUI.BeginChangeCheck(); + num2 = EditorGUI.FloatField(controlRect, LightmappingWindow.s_Styles.ScaleInLightmap, num2); + if (EditorGUI.EndChangeCheck()) + { + serializedProperty.floatValue = Mathf.Max(num2 / num, 0f); + } + EditorGUI.EndProperty(); + return LightmapVisualization.GetLightmapLODLevelScale(renderers[0]) * num2; + } + private bool HasNormals(Renderer renderer) + { + Mesh mesh = null; + if (renderer is MeshRenderer) + { + MeshFilter component = renderer.GetComponent(); + if (component != null) + { + mesh = component.sharedMesh; + } + } + else + { + if (renderer is SkinnedMeshRenderer) + { + mesh = (renderer as SkinnedMeshRenderer).sharedMesh; + } + } + return InternalMeshUtil.HasNormals(mesh); + } + private void ObjectSettings() + { + bool flag = true; + SceneModeUtility.SearchBar(new Type[] + { + typeof(Light), + typeof(Renderer), + typeof(Terrain) + }); + EditorGUILayout.Space(); + GameObject[] array; + Renderer[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[] + { + typeof(MeshRenderer), + typeof(SkinnedMeshRenderer) + }); + if (array.Length > 0) + { + flag = false; + EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType); + SerializedObject serializedObject = new SerializedObject(array); + EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject.FindProperty("m_StaticEditorFlags"), 1)); + SerializedObject serializedObject2 = new SerializedObject(selectedObjectsOfType); + float num = this.LightmapScaleGUI(serializedObject2, selectedObjectsOfType); + float f = (!(selectedObjectsOfType[0] is MeshRenderer)) ? InternalMeshUtil.GetCachedSkinnedMeshSurfaceArea(selectedObjectsOfType[0] as SkinnedMeshRenderer) : InternalMeshUtil.GetCachedMeshSurfaceArea(selectedObjectsOfType[0] as MeshRenderer); + float num2 = Mathf.Sqrt(f) * LightmapEditorSettings.resolution * num; + float num3 = (float)Math.Min(LightmapEditorSettings.maxAtlasWidth, LightmapEditorSettings.maxAtlasHeight); + this.m_ShowClampedSize.target = (num2 > num3); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowClampedSize.faded)) + { + GUILayout.Label(LightmappingWindow.s_Styles.ClampedSize, EditorStyles.helpBox, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + this.m_ShowAtlas = EditorGUILayout.Foldout(this.m_ShowAtlas, LightmappingWindow.s_Styles.Atlas); + if (this.m_ShowAtlas) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapIndex"), LightmappingWindow.s_Styles.AtlasIndex, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.x"), LightmappingWindow.s_Styles.AtlasTilingX, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.y"), LightmappingWindow.s_Styles.AtlasTilingY, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.z"), LightmappingWindow.s_Styles.AtlasOffsetX, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.w"), LightmappingWindow.s_Styles.AtlasOffsetY, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + if (!this.HasNormals(selectedObjectsOfType[0])) + { + EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.NoNormalsNoLightmapping.text, MessageType.Warning); + } + serializedObject.ApplyModifiedProperties(); + serializedObject2.ApplyModifiedProperties(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + } + Light[] selectedObjectsOfType2 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length > 0) + { + flag = false; + EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType2.ToArray()); + SerializedObject serializedObject3 = new SerializedObject(selectedObjectsOfType2.ToArray()); + SerializedProperty serializedProperty = serializedObject3.FindProperty("m_Type"); + bool flag2 = !serializedProperty.hasMultipleDifferentValues && selectedObjectsOfType2[0].type == LightType.Area; + if (this.m_LastAmountOfLights > 0) + { + this.m_ShowAreaLight.target = flag2; + } + else + { + this.m_ShowAreaLight.value = flag2; + } + SerializedProperty serializedProperty2 = serializedObject3.FindProperty("m_Lightmapping"); + if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowAreaLight.faded)) + { + EditorGUILayout.PropertyField(serializedProperty2, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.BeginDisabledGroup(serializedProperty2.intValue == 0); + EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_Color"), new GUILayoutOption[0]); + EditorGUILayout.Slider(serializedObject3.FindProperty("m_Intensity"), 0f, 8f, new GUILayoutOption[0]); + if (InternalEditorUtility.HasPro()) + { + EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_IndirectIntensity"), LightmappingWindow.s_Styles.LightIndirectIntensity, new GUILayoutOption[0]); + } + EditorGUILayout.IntPopup(serializedObject3.FindProperty("m_Shadows.m_Type"), this.kShadowTypeStrings, this.kShadowTypeValues, LightmappingWindow.s_Styles.LightShadows, new GUILayoutOption[0]); + this.m_ShowShadowOptions.target = (selectedObjectsOfType2[0].shadows != LightShadows.None); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowOptions.faded)) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_ShadowSamples"), LightmappingWindow.s_Styles.LightShadowSamples, new GUILayoutOption[0]); + this.m_ShowShadowAngleOrSize.target = (selectedObjectsOfType2[0].type != LightType.Area); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowAngleOrSize.faded)) + { + if (selectedObjectsOfType2[0].type == LightType.Directional) + { + EditorGUILayout.Slider(serializedObject3.FindProperty("m_ShadowAngle"), 0f, 90f, LightmappingWindow.s_Styles.LightShadowAngle, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.Slider(serializedObject3.FindProperty("m_ShadowRadius"), 0f, 2f, LightmappingWindow.s_Styles.LightShadowRadius, new GUILayoutOption[0]); + } + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); + serializedObject3.ApplyModifiedProperties(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + } + this.m_LastAmountOfLights = selectedObjectsOfType2.Length; + Terrain[] selectedObjectsOfType3 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length > 0) + { + flag = false; + EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType3); + SerializedObject serializedObject4 = new SerializedObject(array); + EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject4.FindProperty("m_StaticEditorFlags"), 1)); + SerializedObject serializedObject5 = new SerializedObject(selectedObjectsOfType3.ToArray()); + SerializedProperty serializedProperty3 = serializedObject5.FindProperty("m_LightmapSize"); + bool flag3 = false; + int intValue = serializedProperty3.intValue; + EditorGUILayout.IntPopup(serializedProperty3, this.kTerrainLightmapSizeStrings, this.kTerrainLightmapSizeValues, LightmappingWindow.s_Styles.TerrainLightmapSize, new GUILayoutOption[0]); + flag3 |= (intValue != serializedProperty3.intValue); + this.m_ShowAtlas = EditorGUILayout.Foldout(this.m_ShowAtlas, LightmappingWindow.s_Styles.Atlas); + if (this.m_ShowAtlas) + { + EditorGUI.indentLevel++; + SerializedProperty serializedProperty4 = serializedObject5.FindProperty("m_LightmapIndex"); + int intValue2 = serializedProperty4.intValue; + EditorGUILayout.PropertyField(serializedProperty4, LightmappingWindow.s_Styles.AtlasIndex, new GUILayoutOption[0]); + flag3 |= (intValue2 != serializedProperty4.intValue); + EditorGUI.indentLevel--; + } + serializedObject4.ApplyModifiedProperties(); + serializedObject5.ApplyModifiedProperties(); + if (flag3) + { + Terrain[] array2 = selectedObjectsOfType3; + for (int i = 0; i < array2.Length; i++) + { + Terrain terrain = array2[i]; + if (terrain != null) + { + terrain.Flush(); + } + } + } + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + } + if (flag) + { + GUILayout.Label(LightmappingWindow.s_Styles.EmptySelection, EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private void BakeSettings() + { + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + SerializedProperty property = serializedObject.FindProperty("m_LightmapsMode"); + SerializedProperty property2 = serializedObject.FindProperty("m_UseDualLightmapsInForward"); + SerializedProperty property3 = serializedObject.FindProperty("m_LightmapEditorSettings.m_SkyLightColor"); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_LightmapEditorSettings.m_SkyLightIntensity"); + SerializedProperty serializedProperty2 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Bounces"); + SerializedProperty property4 = serializedObject.FindProperty("m_LightmapEditorSettings.m_BounceBoost"); + SerializedProperty property5 = serializedObject.FindProperty("m_LightmapEditorSettings.m_BounceIntensity"); + SerializedProperty serializedProperty3 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Quality"); + SerializedProperty serializedProperty4 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherRays"); + SerializedProperty serializedProperty5 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherContrastThreshold"); + SerializedProperty property6 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherGradientThreshold"); + SerializedProperty property7 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherInterpolationPoints"); + SerializedProperty serializedProperty6 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOAmount"); + SerializedProperty serializedProperty7 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOMaxDistance"); + SerializedProperty property8 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOContrast"); + SerializedProperty serializedProperty8 = serializedObject.FindProperty("m_LightmapEditorSettings.m_LockAtlas"); + SerializedProperty serializedProperty9 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Resolution"); + SerializedProperty property9 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Padding"); + SerializedProperty property10 = serializedObject.FindProperty("m_LightmapEditorSettings.m_LODSurfaceMappingDistance"); + bool flag = this.BeastSettingsFileOverride(); + EditorGUILayout.IntPopup(property, this.kModeStrings, this.kModeValues, LightmappingWindow.s_Styles.Mode, new GUILayoutOption[0]); + this.m_ShowDualOptions.target = (LightmapSettings.lightmapsMode == LightmapsMode.Dual); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowDualOptions.faded)) + { + EditorGUILayout.PropertyField(property2, LightmappingWindow.s_Styles.UseDualInForward, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + GUILayout.Space(5f); + GUI.enabled = !flag; + int intValue = serializedProperty3.intValue; + EditorGUILayout.IntPopup(serializedProperty3, this.kQualityStrings, this.kQualityValues, LightmappingWindow.s_Styles.Quality, new GUILayoutOption[0]); + if (serializedProperty3.intValue != intValue) + { + if (serializedProperty3.intValue == 0) + { + serializedProperty4.intValue = 1000; + serializedProperty5.floatValue = 0.05f; + } + else + { + serializedProperty4.intValue = 200; + serializedProperty5.floatValue = 0.1f; + } + } + GUILayout.Space(5f); + if (InternalEditorUtility.HasPro()) + { + EditorGUILayout.IntPopup(serializedProperty2, this.kBouncesStrings, this.kBouncesValues, LightmappingWindow.s_Styles.Bounces, new GUILayoutOption[0]); + } + else + { + bool enabled = GUI.enabled; + GUI.enabled = false; + string[] displayedOptions = new string[] + { + "0" + }; + EditorGUILayout.IntPopup(LightmappingWindow.s_Styles.Bounces.text, 0, displayedOptions, this.kBouncesValues, new GUILayoutOption[0]); + GUI.enabled = enabled; + } + this.m_ShowFinalGather.target = (serializedProperty2.intValue > 0 && InternalEditorUtility.HasPro()); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowFinalGather.faded)) + { + EditorGUILayout.PropertyField(property3, LightmappingWindow.s_Styles.SkyLightColor, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedProperty, LightmappingWindow.s_Styles.SkyLightIntensity, new GUILayoutOption[0]); + if (serializedProperty.floatValue < 0f) + { + serializedProperty.floatValue = 0f; + } + EditorGUILayout.Slider(property4, 0f, 4f, LightmappingWindow.s_Styles.BounceBoost, new GUILayoutOption[0]); + EditorGUILayout.Slider(property5, 0f, 5f, LightmappingWindow.s_Styles.BounceIntensity, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedProperty4, LightmappingWindow.s_Styles.FinalGatherRays, new GUILayoutOption[0]); + if (serializedProperty4.intValue < 1) + { + serializedProperty4.intValue = 1; + } + EditorGUILayout.Slider(serializedProperty5, 0f, 0.5f, LightmappingWindow.s_Styles.FinalGatherContrastThreshold, new GUILayoutOption[0]); + EditorGUILayout.Slider(property6, 0f, 1f, LightmappingWindow.s_Styles.FinalGatherGradientThreshold, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(property7, 15, 30, LightmappingWindow.s_Styles.FinalGatherInterpolationPoints, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + GUI.enabled = true; + GUILayout.Space(5f); + EditorGUILayout.Slider(serializedProperty6, 0f, 1f, LightmappingWindow.s_Styles.AO, new GUILayoutOption[0]); + this.m_ShowAO.target = (serializedProperty6.floatValue > 0f); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowAO.faded)) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(serializedProperty7, LightmappingWindow.s_Styles.AOMaxDistance, new GUILayoutOption[0]); + if (serializedProperty7.floatValue < 0f) + { + serializedProperty7.floatValue = 0f; + } + EditorGUILayout.Slider(property8, 0f, 2f, LightmappingWindow.s_Styles.AOContrast, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); + GUILayout.Space(5f); + EditorGUILayout.PropertyField(property10, LightmappingWindow.s_Styles.LODSurfaceDistance, new GUILayoutOption[0]); + GUILayout.Space(20f); + EditorGUILayout.PropertyField(serializedProperty8, LightmappingWindow.s_Styles.LockAtlas, new GUILayoutOption[0]); + GUI.enabled = !serializedProperty8.boolValue; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedProperty9, LightmappingWindow.s_Styles.Resolution, new GUILayoutOption[0]); + if (serializedProperty9.floatValue != this.m_OldResolution) + { + serializedProperty9.floatValue = ((serializedProperty9.floatValue <= 0f) ? 0f : serializedProperty9.floatValue); + SceneView.RepaintAll(); + this.m_OldResolution = serializedProperty9.floatValue; + } + GUILayout.Label(" texels per world unit", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property9, LightmappingWindow.s_Styles.Padding, new GUILayoutOption[0]); + GUILayout.Label(" texels", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUI.enabled = true; + serializedObject.ApplyModifiedProperties(); + } + private void UpdateLightmapSelection() + { + Terrain terrain = null; + MeshRenderer component; + if (Selection.activeGameObject == null || ((component = Selection.activeGameObject.GetComponent()) == null && (terrain = Selection.activeGameObject.GetComponent()) == null)) + { + this.m_SelectedLightmap = -1; + return; + } + this.m_SelectedLightmap = ((!(component != null)) ? terrain.lightmapIndex : component.lightmapIndex); + } + private Texture2D LightmapField(Texture2D lightmap, int index) + { + Rect rect = GUILayoutUtility.GetRect(100f, 100f, EditorStyles.objectField); + this.MenuSelectLightmapUsers(rect, index); + Texture2D result = EditorGUI.ObjectField(rect, lightmap, typeof(Texture2D), false) as Texture2D; + if (index == this.m_SelectedLightmap && Event.current.type == EventType.Repaint) + { + LightmappingWindow.s_Styles.selectedLightmapHighlight.Draw(rect, false, false, false, false); + } + return result; + } + private void Maps() + { + GUI.changed = false; + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + SerializedProperty property = serializedObject.FindProperty("m_LightProbes"); + EditorGUILayout.PropertyField(property, LightmappingWindow.s_Styles.LightProbes, new GUILayoutOption[0]); + serializedObject.ApplyModifiedProperties(); + GUILayout.Space(10f); + LightmapData[] lightmaps = LightmapSettings.lightmaps; + Rect rect = GUILayoutUtility.GetRect(100f, 100f, 16f, 16f, EditorStyles.numberField); + int num = Mathf.Clamp(EditorGUI.ArraySizeField(rect, LightmappingWindow.s_Styles.MapsArraySize, LightmapSettings.lightmaps.Length, EditorStyles.numberField), 0, 254); + this.Compress(); + this.m_ScrollPositionMaps = GUILayout.BeginScrollView(this.m_ScrollPositionMaps, new GUILayoutOption[0]); + for (int i = 0; i < lightmaps.Length; i++) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(i.ToString(), new GUILayoutOption[0]); + GUILayout.Space(5f); + lightmaps[i].lightmapFar = this.LightmapField(lightmaps[i].lightmapFar, i); + GUILayout.Space(10f); + lightmaps[i].lightmapNear = this.LightmapField(lightmaps[i].lightmapNear, i); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + GUILayout.EndScrollView(); + if (GUI.changed) + { + if (num != lightmaps.Length) + { + LightmapData[] array = Array.CreateInstance(typeof(LightmapData), num) as LightmapData[]; + Array.Copy(lightmaps, array, Mathf.Min(lightmaps.Length, num)); + for (int j = lightmaps.Length; j < num; j++) + { + array[j] = new LightmapData(); + } + LightmapSettings.lightmaps = array; + } + else + { + LightmapSettings.lightmaps = lightmaps; + } + LightmappingWindow.RepaintSceneAndGameViews(); + } + } + private void Compress() + { + bool flag = true; + LightmapData[] lightmaps = LightmapSettings.lightmaps; + Texture2D texture2D = null; + LightmapData[] array = lightmaps; + for (int i = 0; i < array.Length; i++) + { + LightmapData lightmapData = array[i]; + if (lightmapData.lightmapFar != null) + { + texture2D = lightmapData.lightmapFar; + break; + } + if (lightmapData.lightmapNear != null) + { + texture2D = lightmapData.lightmapNear; + break; + } + } + if (texture2D != null) + { + string assetPath = AssetDatabase.GetAssetPath(texture2D); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + if (textureImporter != null) + { + flag = (textureImporter.textureFormat == TextureImporterFormat.AutomaticCompressed); + } + } + bool flag2 = EditorGUILayout.Toggle(LightmappingWindow.s_Styles.TextureCompression, flag, new GUILayoutOption[0]); + if (flag2 != flag) + { + UnityEngine.Object[] objects = new UnityEngine.Object[0]; + Selection.objects = objects; + LightmapData[] array2 = lightmaps; + for (int j = 0; j < array2.Length; j++) + { + LightmapData lightmapData2 = array2[j]; + string assetPath2 = AssetDatabase.GetAssetPath(lightmapData2.lightmapFar); + TextureImporter textureImporter2 = AssetImporter.GetAtPath(assetPath2) as TextureImporter; + if (textureImporter2 != null) + { + textureImporter2.textureFormat = ((!flag2) ? TextureImporterFormat.AutomaticTruecolor : TextureImporterFormat.AutomaticCompressed); + AssetDatabase.ImportAsset(assetPath2); + } + string assetPath3 = AssetDatabase.GetAssetPath(lightmapData2.lightmapNear); + TextureImporter textureImporter3 = AssetImporter.GetAtPath(assetPath3) as TextureImporter; + if (textureImporter3 != null) + { + textureImporter3.textureFormat = ((!flag2) ? TextureImporterFormat.AutomaticTruecolor : TextureImporterFormat.AutomaticCompressed); + AssetDatabase.ImportAsset(assetPath3); + } + } + } + } + private void MarkStartTime() + { + this.m_BakeStartTime = Time.realtimeSinceStartup; + } + private void MarkEndTime() + { + if (this.m_BakeStartTime < 0f || Time.realtimeSinceStartup - this.m_BakeStartTime < 0f) + { + this.m_LastBakeTimeString = string.Empty; + return; + } + try + { + TimeSpan timeSpan = TimeSpan.FromSeconds((double)(Time.realtimeSinceStartup - this.m_BakeStartTime)); + this.m_LastBakeTimeString = string.Concat(new string[] + { + "Last bake took ", + (timeSpan.Days <= 0) ? string.Empty : (timeSpan.Days + "."), + (timeSpan.Hours <= 0 && timeSpan.Days <= 0) ? string.Empty : (timeSpan.Hours.ToString("00") + ":"), + timeSpan.Minutes.ToString("00"), + ":", + timeSpan.Seconds.ToString("00") + }); + } + catch (Exception) + { + this.m_LastBakeTimeString = string.Empty; + } + } + private void Buttons() + { + float width = 120f; + bool flag = LightmapSettings.lightmapsMode == LightmapsMode.Directional && !InternalEditorUtility.HasPro(); + if (flag) + { + EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.DirectionalLightmapsProOnly.text, MessageType.Warning); + } + EditorGUI.BeginDisabledGroup(flag); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Clear", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + Lightmapping.Clear(); + Analytics.Track("/LightMapper/Clear"); + } + if (!Lightmapping.isRunning) + { + if (this.BakeButton(new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + this.DoBake(); + GUIUtility.ExitGUI(); + } + } + else + { + if (GUILayout.Button("Cancel", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + Lightmapping.Cancel(); + this.m_BakeStartTime = -1f; + Analytics.Track("/LightMapper/Cancel"); + } + } + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + } + private void DoBake() + { + LightmapsMode lightmapsMode = LightmapSettings.lightmapsMode; + Analytics.Track("/LightMapper/Start"); + Analytics.Event("LightMapper", "Mode", lightmapsMode.ToString(), 1); + this.MarkStartTime(); + switch (this.bakeMode) + { + case LightmappingWindow.BakeMode.BakeScene: + Analytics.Event("LightMapper", "Button", "BakeScene", 1); + Lightmapping.BakeAsync(); + break; + case LightmappingWindow.BakeMode.BakeSelected: + Analytics.Event("LightMapper", "Button", "BakeSelected", 1); + Lightmapping.BakeSelectedAsync(); + break; + case LightmappingWindow.BakeMode.BakeProbes: + Analytics.Event("LightMapper", "Button", "BakeProbes", 1); + Lightmapping.BakeLightProbesOnlyAsync(); + break; + } + } + private bool BakeButton(params GUILayoutOption[] options) + { + GUIContent content = EditorGUIUtility.TempContent(ObjectNames.NicifyVariableName(this.bakeMode.ToString())); + Rect rect = GUILayoutUtility.GetRect(content, LightmappingWindow.s_Styles.dropDownButton, options); + Rect rect2 = rect; + rect2.xMin = rect2.xMax - 20f; + if (Event.current.type == EventType.MouseDown && rect2.Contains(Event.current.mousePosition)) + { + GenericMenu genericMenu = new GenericMenu(); + string[] names = Enum.GetNames(typeof(LightmappingWindow.BakeMode)); + int num = Array.IndexOf(names, Enum.GetName(typeof(LightmappingWindow.BakeMode), this.bakeMode)); + int num2 = 0; + foreach (string current in + from x in names + select ObjectNames.NicifyVariableName(x)) + { + genericMenu.AddItem(new GUIContent(current), num2 == num, new GenericMenu.MenuFunction2(this.BakeDropDownCallback), num2++); + } + genericMenu.DropDown(rect); + Event.current.Use(); + return false; + } + return GUI.Button(rect, content, LightmappingWindow.s_Styles.dropDownButton); + } + private void BakeDropDownCallback(object data) + { + this.bakeMode = (LightmappingWindow.BakeMode)((int)data); + this.DoBake(); + } + private void Summary() + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + if (this.m_LastBakeTimeString != string.Empty) + { + GUILayout.Label(this.m_LastBakeTimeString, LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + } + int num = 0; + int num2 = 0; + Dictionary dictionary = new Dictionary(); + bool flag = false; + LightmapData[] lightmaps = LightmapSettings.lightmaps; + for (int i = 0; i < lightmaps.Length; i++) + { + LightmapData lightmapData = lightmaps[i]; + if (!(lightmapData.lightmapFar == null)) + { + num2++; + Vector2 vector = new Vector2((float)lightmapData.lightmapFar.width, (float)lightmapData.lightmapFar.height); + if (dictionary.ContainsKey(vector)) + { + Dictionary dictionary2; + Dictionary expr_AC = dictionary2 = dictionary; + Vector2 key; + Vector2 expr_B1 = key = vector; + int num3 = dictionary2[key]; + expr_AC[expr_B1] = num3 + 1; + } + else + { + dictionary.Add(vector, 1); + } + num += TextureUtil.GetRuntimeMemorySize(lightmapData.lightmapFar); + if (lightmapData.lightmapNear) + { + num += TextureUtil.GetRuntimeMemorySize(lightmapData.lightmapNear); + flag = true; + } + } + } + string text = string.Concat(new object[] + { + num2, + (!flag) ? " single" : " dual", + " lightmap", + (num2 != 1) ? "s" : string.Empty + }); + bool flag2 = true; + foreach (KeyValuePair current in dictionary) + { + text += ((!flag2) ? ", " : ": "); + flag2 = false; + if (current.Value > 1) + { + text = text + current.Value + "x"; + } + string text2 = text; + text = string.Concat(new object[] + { + text2, + current.Key.x, + "x", + current.Key.y, + "px" + }); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(text + " ", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.Label("Color space ", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(EditorUtility.FormatBytes(num), LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.Label((num2 != 0) ? (string.Empty + LightmapSettings.bakedColorSpace) : "No Lightmaps", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + private static void Header(ref Rect rect, float headerHeight, float headerLeftMargin, float maxLightmaps, LightmapsMode lightmapsMode) + { + Rect rect2 = GUILayoutUtility.GetRect(rect.width, headerHeight); + rect2.width = rect.width / maxLightmaps; + rect2.y -= rect.height; + rect.y += headerHeight; + rect2.x += headerLeftMargin; + if (lightmapsMode == LightmapsMode.Directional) + { + EditorGUI.DropShadowLabel(rect2, "color"); + rect2.x += rect2.width; + EditorGUI.DropShadowLabel(rect2, "scale"); + } + else + { + EditorGUI.DropShadowLabel(rect2, "far"); + rect2.x += rect2.width; + EditorGUI.DropShadowLabel(rect2, "near"); + } + } + private void Lightmaps(Rect r) + { + bool flag = true; + GUI.Box(r, string.Empty, "PreBackground"); + this.m_ScrollPositionLightmaps = EditorGUILayout.BeginScrollView(this.m_ScrollPositionLightmaps, new GUILayoutOption[] + { + GUILayout.Height(r.height) + }); + int num = 0; + LightmapsMode lightmapsMode = LightmapSettings.lightmapsMode; + float num2 = 2f; + LightmapData[] lightmaps = LightmapSettings.lightmaps; + for (int i = 0; i < lightmaps.Length; i++) + { + LightmapData lightmapData = lightmaps[i]; + if (lightmapData.lightmapFar == null) + { + num++; + } + else + { + GUILayoutOption[] options = new GUILayoutOption[] + { + GUILayout.MaxWidth((float)lightmapData.lightmapFar.width * num2), + GUILayout.MaxHeight((float)lightmapData.lightmapFar.height) + }; + Rect aspectRect = GUILayoutUtility.GetAspectRect((float)lightmapData.lightmapFar.width * num2 / (float)lightmapData.lightmapFar.height, options); + if (flag) + { + LightmappingWindow.Header(ref aspectRect, 20f, 6f, num2, lightmapsMode); + flag = false; + } + aspectRect.width /= num2; + EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapFar); + this.MenuSelectLightmapUsers(aspectRect, num); + if (lightmapData.lightmapNear) + { + aspectRect.x += aspectRect.width; + EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapNear); + this.MenuSelectLightmapUsers(aspectRect, num); + } + num++; + } + } + EditorGUILayout.EndScrollView(); + } + private void MenuSelectLightmapUsers(Rect rect, int lightmapIndex) + { + if (Event.current.type == EventType.ContextClick && rect.Contains(Event.current.mousePosition)) + { + string[] texts = new string[] + { + "Select Lightmap Users" + }; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(texts), -1, new EditorUtility.SelectMenuItemFunction(this.SelectLightmapUsers), lightmapIndex); + Event.current.Use(); + } + } + private void SelectLightmapUsers(object userData, string[] options, int selected) + { + int num = (int)userData; + ArrayList arrayList = new ArrayList(); + MeshRenderer[] array = UnityEngine.Object.FindObjectsOfType(typeof(MeshRenderer)) as MeshRenderer[]; + MeshRenderer[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + MeshRenderer meshRenderer = array2[i]; + if (meshRenderer != null && meshRenderer.lightmapIndex == num) + { + arrayList.Add(meshRenderer.gameObject); + } + } + Terrain[] array3 = UnityEngine.Object.FindObjectsOfType(typeof(Terrain)) as Terrain[]; + Terrain[] array4 = array3; + for (int j = 0; j < array4.Length; j++) + { + Terrain terrain = array4[j]; + if (terrain != null && terrain.lightmapIndex == num) + { + arrayList.Add(terrain.gameObject); + } + } + Selection.objects = (arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Generate Beast settings file"), false, new GenericMenu.MenuFunction(this.GenerateBeastSettingsFile)); + } + private void GenerateBeastSettingsFile() + { + string lightmapAssetsPath = this.GetLightmapAssetsPath(); + string text = lightmapAssetsPath + "/BeastSettings.xml"; + if (lightmapAssetsPath.Length == 0) + { + Debug.LogWarning("Scene hasn't been saved yet, can't generate settings file."); + return; + } + if (File.Exists(text)) + { + Debug.LogWarning("Beast settings file already exists for this scene."); + return; + } + Directory.CreateDirectory(lightmapAssetsPath); + AssetDatabase.ImportAsset(lightmapAssetsPath); + FileUtil.CopyFileOrDirectory(EditorApplication.applicationContentsPath + "/Resources/BeastSettings.xml", text); + AssetDatabase.ImportAsset(text); + } + private string GetLightmapAssetsPath() + { + string currentScene = EditorApplication.currentScene; + return currentScene.Substring(0, Mathf.Max(0, currentScene.Length - 6)); + } + private bool BeastSettingsFileOverride() + { + string text = this.GetLightmapAssetsPath() + "/BeastSettings.xml"; + if (!File.Exists(text)) + { + return false; + } + GUILayout.Space(5f); + GUILayout.BeginVertical(GUI.skin.box, new GUILayoutOption[0]); + GUILayout.Label("Bake settings will be overridden by BeastSettings.xml", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + if (GUILayout.Button("Open", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath(text)); + } + GUILayout.EndVertical(); + GUILayout.Space(5f); + return true; + } + [MenuItem("Window/Lightmapping", false, 2098)] + private static void CreateLightmapEditor() + { + LightmappingWindow window = EditorWindow.GetWindow(); + window.title = EditorGUIUtility.TextContent("LightmapEditor.WindowTitle").text; + window.minSize = new Vector2(300f, 360f); + window.Show(); + } + } +} diff --git a/UnityEditor/UnityEditor/ListViewElement.cs b/UnityEditor/UnityEditor/ListViewElement.cs new file mode 100644 index 00000000..4aa9a8d3 --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewElement.cs @@ -0,0 +1,11 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct ListViewElement + { + public int row; + public int column; + public Rect position; + } +} diff --git a/UnityEditor/UnityEditor/ListViewGUI.cs b/UnityEditor/UnityEditor/ListViewGUI.cs new file mode 100644 index 00000000..8f8e3383 --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewGUI.cs @@ -0,0 +1,117 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ListViewGUI + { + private static int[] dummyWidths = new int[1]; + internal static ListViewShared.InternalListViewState ilvState = new ListViewShared.InternalListViewState(); + private static int listViewHash = "ListView".GetHashCode(); + public static ListViewShared.ListViewElementsEnumerator ListView(Rect pos, ListViewState state) + { + return ListViewGUI.DoListView(pos, state, null, string.Empty); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUI.ListView(state, (ListViewOptions)0, null, string.Empty, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, int[] colWidths, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUI.ListView(state, (ListViewOptions)0, colWidths, string.Empty, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUI.ListView(state, lvOptions, null, string.Empty, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, string dragTitle, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUI.ListView(state, lvOptions, null, dragTitle, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, int[] colWidths, string dragTitle, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(style, new GUILayoutOption[0]); + state.scrollPos = EditorGUILayout.BeginScrollView(state.scrollPos, options); + ListViewGUI.ilvState.beganHorizontal = true; + state.draggedFrom = -1; + state.draggedTo = -1; + state.fileNames = null; + if ((lvOptions & ListViewOptions.wantsReordering) != (ListViewOptions)0) + { + ListViewGUI.ilvState.wantsReordering = true; + } + if ((lvOptions & ListViewOptions.wantsExternalFiles) != (ListViewOptions)0) + { + ListViewGUI.ilvState.wantsExternalFiles = true; + } + if ((lvOptions & ListViewOptions.wantsToStartCustomDrag) != (ListViewOptions)0) + { + ListViewGUI.ilvState.wantsToStartCustomDrag = true; + } + if ((lvOptions & ListViewOptions.wantsToAcceptCustomDrag) != (ListViewOptions)0) + { + ListViewGUI.ilvState.wantsToAcceptCustomDrag = true; + } + return ListViewGUI.DoListView(GUILayoutUtility.GetRect(1f, (float)(state.totalRows * state.rowHeight + 3)), state, colWidths, string.Empty); + } + public static ListViewShared.ListViewElementsEnumerator DoListView(Rect pos, ListViewState state, int[] colWidths, string dragTitle) + { + int controlID = GUIUtility.GetControlID(ListViewGUI.listViewHash, FocusType.Native); + state.ID = controlID; + state.selectionChanged = false; + Rect rect; + if (GUIClip.visibleRect.x < 0f || GUIClip.visibleRect.y < 0f) + { + rect = pos; + } + else + { + rect = ((pos.y >= 0f) ? new Rect(0f, state.scrollPos.y, GUIClip.visibleRect.width, GUIClip.visibleRect.height) : new Rect(0f, 0f, GUIClip.visibleRect.width, GUIClip.visibleRect.height)); + } + if (rect.width <= 0f) + { + rect.width = 1f; + } + if (rect.height <= 0f) + { + rect.height = 1f; + } + ListViewGUI.ilvState.rect = rect; + int num = (int)((-pos.y + rect.yMin) / (float)state.rowHeight); + int num2 = num + (int)Math.Ceiling((double)(((rect.yMin - pos.y) % (float)state.rowHeight + rect.height) / (float)state.rowHeight)) - 1; + if (colWidths == null) + { + ListViewGUI.dummyWidths[0] = (int)rect.width; + colWidths = ListViewGUI.dummyWidths; + } + ListViewGUI.ilvState.invisibleRows = num; + ListViewGUI.ilvState.endRow = num2; + ListViewGUI.ilvState.rectHeight = (int)rect.height; + ListViewGUI.ilvState.state = state; + if (num < 0) + { + num = 0; + } + if (num2 >= state.totalRows) + { + num2 = state.totalRows - 1; + } + return new ListViewShared.ListViewElementsEnumerator(ListViewGUI.ilvState, colWidths, num, num2, dragTitle, new Rect(0f, (float)(num * state.rowHeight), pos.width, (float)state.rowHeight)); + } + public static bool MultiSelection(int prevSelected, int currSelected, ref int initialSelected, ref bool[] selectedItems) + { + return ListViewShared.MultiSelection(ListViewGUI.ilvState, prevSelected, currSelected, ref initialSelected, ref selectedItems); + } + public static bool HasMouseUp(Rect r) + { + return ListViewShared.HasMouseUp(ListViewGUI.ilvState, r, 0); + } + public static bool HasMouseDown(Rect r) + { + return ListViewShared.HasMouseDown(ListViewGUI.ilvState, r, 0); + } + public static bool HasMouseDown(Rect r, int button) + { + return ListViewShared.HasMouseDown(ListViewGUI.ilvState, r, button); + } + } +} diff --git a/UnityEditor/UnityEditor/ListViewGUILayout.cs b/UnityEditor/UnityEditor/ListViewGUILayout.cs new file mode 100644 index 00000000..62af6f6a --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewGUILayout.cs @@ -0,0 +1,182 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ListViewGUILayout + { + internal class GUILayoutedListViewGroup : GUILayoutGroup + { + internal ListViewState state; + public override void CalcWidth() + { + base.CalcWidth(); + this.minWidth = 0f; + this.maxWidth = 0f; + this.stretchWidth = 10000; + } + public override void CalcHeight() + { + this.minHeight = 0f; + this.maxHeight = 0f; + base.CalcHeight(); + this.margin.top = 0; + this.margin.bottom = 0; + if (this.minHeight == 0f) + { + this.minHeight = 1f; + this.maxHeight = 1f; + this.state.rowHeight = 1; + } + else + { + this.state.rowHeight = (int)this.minHeight; + this.minHeight *= (float)this.state.totalRows; + this.maxHeight *= (float)this.state.totalRows; + } + } + private void AddYRecursive(GUILayoutEntry e, float y) + { + e.rect.y = e.rect.y + y; + GUILayoutGroup gUILayoutGroup = e as GUILayoutGroup; + if (gUILayoutGroup != null) + { + for (int i = 0; i < gUILayoutGroup.entries.Count; i++) + { + this.AddYRecursive(gUILayoutGroup.entries[i], y); + } + } + } + public void AddY() + { + if (this.entries.Count > 0) + { + this.AddYRecursive(this.entries[0], this.entries[0].minHeight); + } + } + public void AddY(float val) + { + if (this.entries.Count > 0) + { + this.AddYRecursive(this.entries[0], val); + } + } + } + private static int layoutedListViewHash = "layoutedListView".GetHashCode(); + private static ListViewState lvState = null; + private static int listViewHash = "ListView".GetHashCode(); + private static int[] dummyWidths = new int[1]; + private static Rect dummyRect = new Rect(0f, 0f, 1f, 1f); + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUILayout.ListView(state, (ListViewOptions)0, string.Empty, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, string dragTitle, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUILayout.ListView(state, (ListViewOptions)0, dragTitle, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, GUIStyle style, params GUILayoutOption[] options) + { + return ListViewGUILayout.ListView(state, lvOptions, string.Empty, style, options); + } + public static ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, string dragTitle, GUIStyle style, params GUILayoutOption[] options) + { + ListViewGUILayout.lvState = state; + GUILayout.BeginHorizontal(style, options); + state.scrollPos = EditorGUILayout.BeginScrollView(state.scrollPos, options); + ListViewGUILayout.BeginLayoutedListview(state, GUIStyle.none, new GUILayoutOption[0]); + state.draggedFrom = -1; + state.draggedTo = -1; + state.fileNames = null; + if ((lvOptions & ListViewOptions.wantsReordering) != (ListViewOptions)0) + { + state.ilvState.wantsReordering = true; + } + if ((lvOptions & ListViewOptions.wantsExternalFiles) != (ListViewOptions)0) + { + state.ilvState.wantsExternalFiles = true; + } + if ((lvOptions & ListViewOptions.wantsToStartCustomDrag) != (ListViewOptions)0) + { + state.ilvState.wantsToStartCustomDrag = true; + } + if ((lvOptions & ListViewOptions.wantsToAcceptCustomDrag) != (ListViewOptions)0) + { + state.ilvState.wantsToAcceptCustomDrag = true; + } + return ListViewGUILayout.DoListView(state, null, dragTitle); + } + private static ListViewShared.ListViewElementsEnumerator DoListView(ListViewState state, int[] colWidths, string dragTitle) + { + Rect rect = ListViewGUILayout.dummyRect; + int num = 0; + int num2 = 0; + ListViewShared.InternalLayoutedListViewState ilvState = state.ilvState; + int controlID = GUIUtility.GetControlID(ListViewGUILayout.listViewHash, FocusType.Native); + state.ID = controlID; + state.selectionChanged = false; + ilvState.state = state; + if (Event.current.type != EventType.Layout) + { + rect = new Rect(0f, state.scrollPos.y, GUIClip.visibleRect.width, GUIClip.visibleRect.height); + if (rect.width <= 0f) + { + rect.width = 1f; + } + if (rect.height <= 0f) + { + rect.height = 1f; + } + state.ilvState.rect = rect; + num = (int)rect.yMin / state.rowHeight; + num2 = num + (int)Math.Ceiling((double)((rect.yMin % (float)state.rowHeight + rect.height) / (float)state.rowHeight)) - 1; + ilvState.invisibleRows = num; + ilvState.endRow = num2; + ilvState.rectHeight = (int)rect.height; + if (num < 0) + { + num = 0; + } + if (num2 >= state.totalRows) + { + num2 = state.totalRows - 1; + } + } + if (colWidths == null) + { + ListViewGUILayout.dummyWidths[0] = (int)rect.width; + colWidths = ListViewGUILayout.dummyWidths; + } + return new ListViewShared.ListViewElementsEnumerator(ilvState, colWidths, num, num2, dragTitle, new Rect(0f, (float)(num * state.rowHeight), rect.width, (float)state.rowHeight)); + } + private static void BeginLayoutedListview(ListViewState state, GUIStyle style, params GUILayoutOption[] options) + { + ListViewGUILayout.GUILayoutedListViewGroup gUILayoutedListViewGroup = (ListViewGUILayout.GUILayoutedListViewGroup)GUILayoutUtility.BeginLayoutGroup(style, null, typeof(ListViewGUILayout.GUILayoutedListViewGroup)); + gUILayoutedListViewGroup.state = state; + state.ilvState.group = gUILayoutedListViewGroup; + GUIUtility.GetControlID(ListViewGUILayout.layoutedListViewHash, FocusType.Native); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUILayoutedListViewGroup.resetCoords = false; + gUILayoutedListViewGroup.isVertical = true; + gUILayoutedListViewGroup.ApplyOptions(options); + } + } + public static bool MultiSelection(int prevSelected, int currSelected, ref int initialSelected, ref bool[] selectedItems) + { + return ListViewShared.MultiSelection(ListViewGUILayout.lvState.ilvState, prevSelected, currSelected, ref initialSelected, ref selectedItems); + } + public static bool HasMouseUp(Rect r) + { + return ListViewShared.HasMouseUp(ListViewGUILayout.lvState.ilvState, r, 0); + } + public static bool HasMouseDown(Rect r) + { + return ListViewShared.HasMouseDown(ListViewGUILayout.lvState.ilvState, r, 0); + } + public static bool HasMouseDown(Rect r, int button) + { + return ListViewShared.HasMouseDown(ListViewGUILayout.lvState.ilvState, r, button); + } + } +} diff --git a/UnityEditor/UnityEditor/ListViewOptions.cs b/UnityEditor/UnityEditor/ListViewOptions.cs new file mode 100644 index 00000000..1fee8e89 --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewOptions.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal enum ListViewOptions + { + wantsReordering = 1, + wantsExternalFiles, + wantsToStartCustomDrag = 4, + wantsToAcceptCustomDrag = 8 + } +} diff --git a/UnityEditor/UnityEditor/ListViewShared.cs b/UnityEditor/UnityEditor/ListViewShared.cs new file mode 100644 index 00000000..09a13ec8 --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewShared.cs @@ -0,0 +1,622 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ListViewShared + { + internal class InternalListViewState + { + public int id = -1; + public int invisibleRows; + public int endRow; + public int rectHeight; + public ListViewState state; + public bool beganHorizontal; + public Rect rect; + public bool wantsReordering; + public bool wantsExternalFiles; + public bool wantsToStartCustomDrag; + public bool wantsToAcceptCustomDrag; + public int dragItem; + } + internal class InternalLayoutedListViewState : ListViewShared.InternalListViewState + { + public ListViewGUILayout.GUILayoutedListViewGroup group; + } + internal class Constants + { + public static string insertion = "PR Insertion"; + } + internal class ListViewElementsEnumerator : IDisposable, IEnumerator, IEnumerator + { + private int[] colWidths; + private int xTo; + private int yFrom; + private int yTo; + private Rect firstRect; + private Rect rect; + private int xPos = -1; + private int yPos = -1; + private ListViewElement element; + private ListViewShared.InternalListViewState ilvState; + private ListViewShared.InternalLayoutedListViewState ilvStateL; + private bool quiting; + private bool isLayouted; + private string dragTitle; + ListViewElement IEnumerator.Current + { + get + { + return this.element; + } + } + object IEnumerator.Current + { + get + { + return this.element; + } + } + internal ListViewElementsEnumerator(ListViewShared.InternalListViewState ilvState, int[] colWidths, int yFrom, int yTo, string dragTitle, Rect firstRect) + { + this.colWidths = colWidths; + this.xTo = colWidths.Length - 1; + this.yFrom = yFrom; + this.yTo = yTo; + this.firstRect = firstRect; + this.rect = firstRect; + this.quiting = (ilvState.state.totalRows == 0); + this.ilvState = ilvState; + this.ilvStateL = (ilvState as ListViewShared.InternalLayoutedListViewState); + this.isLayouted = (this.ilvStateL != null); + this.dragTitle = dragTitle; + ilvState.state.customDraggedFromID = 0; + this.Reset(); + } + public bool MoveNext() + { + if (this.xPos > -1) + { + if (ListViewShared.HasMouseDown(this.ilvState, this.rect)) + { + this.ilvState.state.selectionChanged = true; + this.ilvState.state.row = this.yPos; + this.ilvState.state.column = this.xPos; + this.ilvState.state.scrollPos = ListViewShared.ListViewScrollToRow(this.ilvState, this.yPos); + if ((this.ilvState.wantsReordering || this.ilvState.wantsToStartCustomDrag) && GUIUtility.hotControl == this.ilvState.state.ID) + { + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), this.ilvState.state.ID); + dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; + this.ilvState.dragItem = this.yPos; + ListViewShared.dragControlID = this.ilvState.state.ID; + } + } + if ((this.ilvState.wantsReordering || this.ilvState.wantsToStartCustomDrag) && GUIUtility.hotControl == this.ilvState.state.ID && Event.current.type == EventType.MouseDrag && GUIClip.visibleRect.Contains(Event.current.mousePosition)) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), this.ilvState.state.ID); + if (dragAndDropDelay2.CanStartDrag()) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + DragAndDrop.paths = null; + if (this.ilvState.wantsReordering) + { + this.ilvState.state.dropHereRect = new Rect(this.ilvState.rect.x, 0f, this.ilvState.rect.width, (float)(this.ilvState.state.rowHeight * 2)); + DragAndDrop.StartDrag(this.dragTitle); + } + else + { + if (this.ilvState.wantsToStartCustomDrag) + { + DragAndDrop.SetGenericData("CustomDragID", this.ilvState.state.ID); + DragAndDrop.StartDrag(this.dragTitle); + } + } + } + Event.current.Use(); + } + } + this.xPos++; + if (this.xPos > this.xTo) + { + this.xPos = 0; + this.yPos++; + this.rect.x = this.firstRect.x; + this.rect.width = (float)this.colWidths[0]; + if (this.yPos > this.yTo) + { + this.quiting = true; + } + else + { + this.rect.y = this.rect.y + this.rect.height; + } + } + else + { + if (this.xPos >= 1) + { + this.rect.x = this.rect.x + (float)this.colWidths[this.xPos - 1]; + } + this.rect.width = (float)this.colWidths[this.xPos]; + } + this.element.row = this.yPos; + this.element.column = this.xPos; + this.element.position = this.rect; + if (this.element.row >= this.ilvState.state.totalRows) + { + this.quiting = true; + } + if (this.isLayouted && Event.current.type == EventType.Layout && this.yFrom + 1 == this.yPos) + { + this.quiting = true; + } + if (this.isLayouted && this.yPos != this.yFrom) + { + GUILayout.EndHorizontal(); + } + if (this.quiting) + { + if (this.ilvState.state.drawDropHere && Event.current.GetTypeForControl(this.ilvState.state.ID) == EventType.Repaint) + { + GUIStyle gUIStyle = ListViewShared.Constants.insertion; + gUIStyle.Draw(gUIStyle.margin.Remove(this.ilvState.state.dropHereRect), false, false, false, false); + } + if (ListViewShared.ListViewKeyboard(this.ilvState, this.colWidths.Length)) + { + this.ilvState.state.selectionChanged = true; + } + if (Event.current.GetTypeForControl(this.ilvState.state.ID) == EventType.MouseUp) + { + GUIUtility.hotControl = 0; + } + if (this.ilvState.wantsReordering && GUIUtility.hotControl == this.ilvState.state.ID) + { + ListViewState state = this.ilvState.state; + EventType type = Event.current.type; + if (type != EventType.DragUpdated) + { + if (type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + this.ilvState.wantsReordering = false; + this.ilvState.state.drawDropHere = false; + GUIUtility.hotControl = 0; + } + } + else + { + if (GUIClip.visibleRect.Contains(Event.current.mousePosition)) + { + this.ilvState.state.draggedFrom = this.ilvState.dragItem; + this.ilvState.state.draggedTo = Mathf.RoundToInt(Event.current.mousePosition.y / (float)state.rowHeight); + if (this.ilvState.state.draggedTo > this.ilvState.state.totalRows) + { + this.ilvState.state.draggedTo = this.ilvState.state.totalRows; + } + if (this.ilvState.state.draggedTo > this.ilvState.state.draggedFrom) + { + this.ilvState.state.row = this.ilvState.state.draggedTo - 1; + } + else + { + this.ilvState.state.row = this.ilvState.state.draggedTo; + } + this.ilvState.state.selectionChanged = true; + DragAndDrop.AcceptDrag(); + Event.current.Use(); + this.ilvState.wantsReordering = false; + this.ilvState.state.drawDropHere = false; + } + GUIUtility.hotControl = 0; + } + } + else + { + DragAndDrop.visualMode = ((!this.ilvState.rect.Contains(Event.current.mousePosition)) ? DragAndDropVisualMode.None : DragAndDropVisualMode.Move); + Event.current.Use(); + if (DragAndDrop.visualMode != DragAndDropVisualMode.None) + { + state.dropHereRect.y = (float)((Mathf.RoundToInt(Event.current.mousePosition.y / (float)state.rowHeight) - 1) * state.rowHeight); + if (state.dropHereRect.y >= (float)(state.rowHeight * state.totalRows)) + { + state.dropHereRect.y = (float)(state.rowHeight * (state.totalRows - 1)); + } + state.drawDropHere = true; + } + } + } + else + { + if (this.ilvState.wantsExternalFiles) + { + EventType type = Event.current.type; + if (type != EventType.DragUpdated) + { + if (type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + this.ilvState.wantsExternalFiles = false; + this.ilvState.state.drawDropHere = false; + GUIUtility.hotControl = 0; + } + } + else + { + if (GUIClip.visibleRect.Contains(Event.current.mousePosition)) + { + this.ilvState.state.fileNames = DragAndDrop.paths; + DragAndDrop.AcceptDrag(); + Event.current.Use(); + this.ilvState.wantsExternalFiles = false; + this.ilvState.state.drawDropHere = false; + this.ilvState.state.draggedTo = Mathf.RoundToInt(Event.current.mousePosition.y / (float)this.ilvState.state.rowHeight); + if (this.ilvState.state.draggedTo > this.ilvState.state.totalRows) + { + this.ilvState.state.draggedTo = this.ilvState.state.totalRows; + } + this.ilvState.state.row = this.ilvState.state.draggedTo; + } + GUIUtility.hotControl = 0; + } + } + else + { + if (GUIClip.visibleRect.Contains(Event.current.mousePosition) && DragAndDrop.paths != null && DragAndDrop.paths.Length != 0) + { + DragAndDrop.visualMode = ((!this.ilvState.rect.Contains(Event.current.mousePosition)) ? DragAndDropVisualMode.None : DragAndDropVisualMode.Copy); + Event.current.Use(); + if (DragAndDrop.visualMode != DragAndDropVisualMode.None) + { + this.ilvState.state.dropHereRect = new Rect(this.ilvState.rect.x, (float)((Mathf.RoundToInt(Event.current.mousePosition.y / (float)this.ilvState.state.rowHeight) - 1) * this.ilvState.state.rowHeight), this.ilvState.rect.width, (float)this.ilvState.state.rowHeight); + if (this.ilvState.state.dropHereRect.y >= (float)(this.ilvState.state.rowHeight * this.ilvState.state.totalRows)) + { + this.ilvState.state.dropHereRect.y = (float)(this.ilvState.state.rowHeight * (this.ilvState.state.totalRows - 1)); + } + this.ilvState.state.drawDropHere = true; + } + } + } + } + else + { + if (this.ilvState.wantsToAcceptCustomDrag && ListViewShared.dragControlID != this.ilvState.state.ID) + { + EventType type = Event.current.type; + if (type != EventType.DragUpdated) + { + if (type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + GUIUtility.hotControl = 0; + } + } + else + { + object genericData = DragAndDrop.GetGenericData("CustomDragID"); + if (GUIClip.visibleRect.Contains(Event.current.mousePosition) && genericData != null) + { + this.ilvState.state.customDraggedFromID = (int)genericData; + DragAndDrop.AcceptDrag(); + Event.current.Use(); + } + GUIUtility.hotControl = 0; + } + } + else + { + object genericData2 = DragAndDrop.GetGenericData("CustomDragID"); + if (GUIClip.visibleRect.Contains(Event.current.mousePosition) && genericData2 != null) + { + DragAndDrop.visualMode = ((!this.ilvState.rect.Contains(Event.current.mousePosition)) ? DragAndDropVisualMode.None : DragAndDropVisualMode.Move); + Event.current.Use(); + } + } + } + } + } + if (this.ilvState.beganHorizontal) + { + EditorGUILayout.EndScrollView(); + GUILayout.EndHorizontal(); + this.ilvState.beganHorizontal = false; + } + if (this.isLayouted) + { + GUILayoutUtility.EndLayoutGroup(); + EditorGUILayout.EndScrollView(); + } + this.ilvState.wantsReordering = false; + this.ilvState.wantsExternalFiles = false; + } + else + { + if (this.isLayouted) + { + if (this.yPos != this.yFrom) + { + this.ilvStateL.group.ResetCursor(); + this.ilvStateL.group.AddY(); + } + else + { + this.ilvStateL.group.AddY((float)(this.ilvState.invisibleRows * this.ilvState.state.rowHeight)); + } + } + } + if (this.isLayouted) + { + if (!this.quiting) + { + GUILayout.BeginHorizontal(GUIStyle.none, new GUILayoutOption[0]); + } + else + { + GUILayout.EndHorizontal(); + } + } + return !this.quiting; + } + public void Reset() + { + this.xPos = -1; + this.yPos = this.yFrom; + } + public IEnumerator GetEnumerator() + { + return this; + } + public void Dispose() + { + } + } + public static bool OSX = Application.platform == RuntimePlatform.OSXEditor; + internal static int dragControlID = -1; + private static bool DoLVPageUpDown(ListViewShared.InternalListViewState ilvState, ref int selectedRow, ref Vector2 scrollPos, bool up) + { + int num = ilvState.endRow - ilvState.invisibleRows; + if (up) + { + if (!ListViewShared.OSX) + { + selectedRow -= num; + if (selectedRow < 0) + { + selectedRow = 0; + } + return true; + } + scrollPos.y -= (float)(ilvState.state.rowHeight * num); + if (scrollPos.y < 0f) + { + scrollPos.y = 0f; + } + } + else + { + if (!ListViewShared.OSX) + { + selectedRow += num; + if (selectedRow >= ilvState.state.totalRows) + { + selectedRow = ilvState.state.totalRows - 1; + } + return true; + } + scrollPos.y += (float)(ilvState.state.rowHeight * num); + } + return false; + } + internal static bool ListViewKeyboard(ListViewShared.InternalListViewState ilvState, int totalCols) + { + int totalRows = ilvState.state.totalRows; + return Event.current.type == EventType.KeyDown && totalRows != 0 && GUIUtility.keyboardControl == ilvState.state.ID && Event.current.GetTypeForControl(ilvState.state.ID) == EventType.KeyDown && ListViewShared.SendKey(ilvState, Event.current.keyCode, totalCols); + } + internal static void SendKey(ListViewState state, KeyCode keyCode) + { + ListViewShared.SendKey(state.ilvState, keyCode, 1); + } + internal static bool SendKey(ListViewShared.InternalListViewState ilvState, KeyCode keyCode, int totalCols) + { + ListViewState state = ilvState.state; + switch (keyCode) + { + case KeyCode.UpArrow: + if (state.row > 0) + { + state.row--; + } + goto IL_136; + case KeyCode.DownArrow: + if (state.row < state.totalRows - 1) + { + state.row++; + } + goto IL_136; + case KeyCode.RightArrow: + if (state.column < totalCols - 1) + { + state.column++; + } + goto IL_136; + case KeyCode.LeftArrow: + if (state.column > 0) + { + state.column--; + } + goto IL_136; + case KeyCode.Home: + state.row = 0; + goto IL_136; + case KeyCode.End: + state.row = state.totalRows - 1; + goto IL_136; + case KeyCode.PageUp: + if (!ListViewShared.DoLVPageUpDown(ilvState, ref state.row, ref state.scrollPos, true)) + { + Event.current.Use(); + return false; + } + goto IL_136; + case KeyCode.PageDown: + if (!ListViewShared.DoLVPageUpDown(ilvState, ref state.row, ref state.scrollPos, false)) + { + Event.current.Use(); + return false; + } + goto IL_136; + } + return false; + IL_136: + state.scrollPos = ListViewShared.ListViewScrollToRow(ilvState, state.scrollPos, state.row); + Event.current.Use(); + return true; + } + internal static bool HasMouseDown(ListViewShared.InternalListViewState ilvState, Rect r) + { + return ListViewShared.HasMouseDown(ilvState, r, 0); + } + internal static bool HasMouseDown(ListViewShared.InternalListViewState ilvState, Rect r, int button) + { + if (Event.current.type == EventType.MouseDown && Event.current.button == button && r.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = ilvState.state.ID; + GUIUtility.keyboardControl = ilvState.state.ID; + Event.current.Use(); + return true; + } + return false; + } + internal static bool HasMouseUp(ListViewShared.InternalListViewState ilvState, Rect r) + { + return ListViewShared.HasMouseUp(ilvState, r, 0); + } + internal static bool HasMouseUp(ListViewShared.InternalListViewState ilvState, Rect r, int button) + { + if (Event.current.type == EventType.MouseUp && Event.current.button == button && r.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + return true; + } + return false; + } + internal static bool MultiSelection(ListViewShared.InternalListViewState ilvState, int prevSelected, int currSelected, ref int initialSelected, ref bool[] selectedItems) + { + bool shift = Event.current.shift; + bool actionKey = EditorGUI.actionKey; + bool result = false; + if ((shift || actionKey) && initialSelected == -1) + { + initialSelected = prevSelected; + } + if (shift) + { + int num = Math.Min(initialSelected, currSelected); + int num2 = Math.Max(initialSelected, currSelected); + if (!actionKey) + { + for (int i = 0; i < num; i++) + { + if (selectedItems[i]) + { + result = true; + } + selectedItems[i] = false; + } + for (int j = num2 + 1; j < selectedItems.Length; j++) + { + if (selectedItems[j]) + { + result = true; + } + selectedItems[j] = false; + } + } + if (num < 0) + { + num = num2; + } + for (int k = num; k <= num2; k++) + { + if (!selectedItems[k]) + { + result = true; + } + selectedItems[k] = true; + } + } + else + { + if (actionKey) + { + selectedItems[currSelected] = !selectedItems[currSelected]; + initialSelected = currSelected; + result = true; + } + else + { + if (!selectedItems[currSelected]) + { + result = true; + } + for (int l = 0; l < selectedItems.Length; l++) + { + if (selectedItems[l] && currSelected != l) + { + result = true; + } + selectedItems[l] = false; + } + initialSelected = -1; + selectedItems[currSelected] = true; + } + } + if (ilvState != null) + { + ilvState.state.scrollPos = ListViewShared.ListViewScrollToRow(ilvState, currSelected); + } + return result; + } + internal static Vector2 ListViewScrollToRow(ListViewShared.InternalListViewState ilvState, int row) + { + return ListViewShared.ListViewScrollToRow(ilvState, ilvState.state.scrollPos, row); + } + internal static int ListViewScrollToRow(ListViewShared.InternalListViewState ilvState, int currPosY, int row) + { + return (int)ListViewShared.ListViewScrollToRow(ilvState, new Vector2(0f, (float)currPosY), row).y; + } + internal static Vector2 ListViewScrollToRow(ListViewShared.InternalListViewState ilvState, Vector2 currPos, int row) + { + if (ilvState.invisibleRows < row && ilvState.endRow > row) + { + return currPos; + } + if (row <= ilvState.invisibleRows) + { + currPos.y = (float)(ilvState.state.rowHeight * row); + } + else + { + currPos.y = (float)(ilvState.state.rowHeight * (row + 1) - ilvState.rectHeight); + } + if (currPos.y < 0f) + { + currPos.y = 0f; + } + else + { + if (currPos.y > (float)(ilvState.state.totalRows * ilvState.state.rowHeight - ilvState.rectHeight)) + { + currPos.y = (float)(ilvState.state.totalRows * ilvState.state.rowHeight - ilvState.rectHeight); + } + } + return currPos; + } + } +} diff --git a/UnityEditor/UnityEditor/ListViewState.cs b/UnityEditor/UnityEditor/ListViewState.cs new file mode 100644 index 00000000..eed307c7 --- /dev/null +++ b/UnityEditor/UnityEditor/ListViewState.cs @@ -0,0 +1,45 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ListViewState + { + private const int c_rowHeight = 16; + public int row; + public int column; + public Vector2 scrollPos; + public int totalRows; + public int rowHeight; + public int ID; + public bool selectionChanged; + public int draggedFrom; + public int draggedTo; + public bool drawDropHere; + public Rect dropHereRect = new Rect(0f, 0f, 0f, 0f); + public string[] fileNames; + public int customDraggedFromID; + internal ListViewShared.InternalLayoutedListViewState ilvState = new ListViewShared.InternalLayoutedListViewState(); + public ListViewState() + { + this.Init(0, 16); + } + public ListViewState(int totalRows) + { + this.Init(totalRows, 16); + } + public ListViewState(int totalRows, int rowHeight) + { + this.Init(totalRows, rowHeight); + } + private void Init(int totalRows, int rowHeight) + { + this.row = -1; + this.column = 0; + this.scrollPos = Vector2.zero; + this.totalRows = totalRows; + this.rowHeight = rowHeight; + this.selectionChanged = false; + } + } +} diff --git a/UnityEditor/UnityEditor/MacFullscreenMode.cs b/UnityEditor/UnityEditor/MacFullscreenMode.cs new file mode 100644 index 00000000..8b950f7b --- /dev/null +++ b/UnityEditor/UnityEditor/MacFullscreenMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum MacFullscreenMode + { + CaptureDisplay, + FullscreenWindow, + FullscreenWindowWithDockAndMenuBar + } +} diff --git a/UnityEditor/UnityEditor/MainWindow.cs b/UnityEditor/UnityEditor/MainWindow.cs new file mode 100644 index 00000000..61433e01 --- /dev/null +++ b/UnityEditor/UnityEditor/MainWindow.cs @@ -0,0 +1,57 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class MainWindow : View, ICleanuppable + { + private const float kStatusbarHeight = 20f; + private const float kMinWidth = 711f; + protected override void SetPosition(Rect newPos) + { + base.SetPosition(newPos); + if (base.children.Length == 0) + { + return; + } + Toolbar toolbar = (Toolbar)base.children[0]; + base.children[0].position = new Rect(0f, 0f, newPos.width, toolbar.CalcHeight()); + if (base.children.Length > 2) + { + base.children[1].position = new Rect(0f, toolbar.CalcHeight(), newPos.width, newPos.height - toolbar.CalcHeight() - base.children[2].position.height); + base.children[2].position = new Rect(0f, newPos.height - base.children[2].position.height, newPos.width, base.children[2].position.height); + } + } + protected override void ChildrenMinMaxChanged() + { + if (base.children.Length == 3) + { + Toolbar toolbar = (Toolbar)base.children[0]; + base.SetMinMaxSizes(new Vector2(711f, toolbar.CalcHeight() + 20f + base.children[1].minSize.y), new Vector2(10000f, 10000f)); + } + base.ChildrenMinMaxChanged(); + } + public static void MakeMain() + { + ContainerWindow containerWindow = ScriptableObject.CreateInstance(); + MainWindow mainWindow = ScriptableObject.CreateInstance(); + mainWindow.SetMinMaxSizes(new Vector2(711f, 300f), new Vector2(10000f, 10000f)); + containerWindow.mainView = mainWindow; + Resolution desktopResolution = InternalEditorUtility.GetDesktopResolution(); + int num = Mathf.Clamp(desktopResolution.width * 3 / 4, 800, 1400); + int num2 = Mathf.Clamp(desktopResolution.height * 3 / 4, 600, 950); + containerWindow.position = new Rect(60f, 20f, (float)num, (float)num2); + containerWindow.Show(ShowMode.MainWindow, true, true); + containerWindow.DisplayAllViews(); + } + public void Cleanup() + { + if (base.children[1].children.Length == 0) + { + Rect position = base.window.position; + Toolbar toolbar = (Toolbar)base.children[0]; + position.height = toolbar.CalcHeight() + 20f; + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaintDatabaseRecord.cs b/UnityEditor/UnityEditor/MaintDatabaseRecord.cs new file mode 100644 index 00000000..3afb6b2b --- /dev/null +++ b/UnityEditor/UnityEditor/MaintDatabaseRecord.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + internal sealed class MaintDatabaseRecord + { + public string name; + public string dbName; + } +} diff --git a/UnityEditor/UnityEditor/MaintUserRecord.cs b/UnityEditor/UnityEditor/MaintUserRecord.cs new file mode 100644 index 00000000..d21fa1c6 --- /dev/null +++ b/UnityEditor/UnityEditor/MaintUserRecord.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + internal sealed class MaintUserRecord + { + public int enabled; + public string userName; + public string fullName; + public string email; + } +} diff --git a/UnityEditor/UnityEditor/ManagedEditorCodeRebuilder.cs b/UnityEditor/UnityEditor/ManagedEditorCodeRebuilder.cs new file mode 100644 index 00000000..d0b92331 --- /dev/null +++ b/UnityEditor/UnityEditor/ManagedEditorCodeRebuilder.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor.Modules; +using UnityEditor.Scripting.Compilers; +namespace UnityEditor +{ + internal class ManagedEditorCodeRebuilder + { + private static readonly char[] kNewlineChars = new char[] + { + '\r', + '\n' + }; + private static bool Run(out CompilerMessage[] messages, bool includeModules) + { + int num; + messages = ManagedEditorCodeRebuilder.ParseResults(ManagedEditorCodeRebuilder.GetOutputStream(ManagedEditorCodeRebuilder.GetJamStartInfo(includeModules), out num)); + return num == 0; + } + private static ProcessStartInfo GetJamStartInfo(bool includeModules) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("jam.pl LiveReloadableEditorAssemblies"); + if (includeModules) + { + foreach (string current in ModuleManager.GetJamTargets()) + { + stringBuilder.Append(" ").Append(current); + } + } + return new ProcessStartInfo + { + WorkingDirectory = Unsupported.GetBaseUnityDeveloperFolder(), + RedirectStandardOutput = true, + RedirectStandardError = false, + Arguments = stringBuilder.ToString(), + FileName = "perl" + }; + } + private static CompilerMessage[] ParseResults(string text) + { + Console.Write(text); + string[] errorOutput = text.Split(ManagedEditorCodeRebuilder.kNewlineChars, StringSplitOptions.RemoveEmptyEntries); + string baseUnityDeveloperFolder = Unsupported.GetBaseUnityDeveloperFolder(); + List list = new MonoCSharpCompilerOutputParser().Parse(errorOutput, false).ToList(); + for (int i = 0; i < list.Count; i++) + { + CompilerMessage value = list[i]; + value.file = Path.Combine(baseUnityDeveloperFolder, value.file); + list[i] = value; + } + return list.ToArray(); + } + private static string GetOutputStream(ProcessStartInfo startInfo, out int exitCode) + { + startInfo.UseShellExecute = false; + startInfo.CreateNoWindow = true; + Process process = new Process + { + StartInfo = startInfo + }; + StringBuilder sbStandardOut = new StringBuilder(); + StringBuilder sbStandardError = new StringBuilder(); + process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs data) + { + sbStandardOut.AppendLine(data.Data); + }; + process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs data) + { + sbStandardError.AppendLine(data.Data); + }; + process.Start(); + if (startInfo.RedirectStandardError) + { + process.BeginErrorReadLine(); + } + else + { + process.BeginOutputReadLine(); + } + process.WaitForExit(); + string result = (!startInfo.RedirectStandardError) ? sbStandardOut.ToString() : sbStandardError.ToString(); + exitCode = process.ExitCode; + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/ManipulationTool.cs b/UnityEditor/UnityEditor/ManipulationTool.cs new file mode 100644 index 00000000..fcbee50d --- /dev/null +++ b/UnityEditor/UnityEditor/ManipulationTool.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class ManipulationTool + { + protected virtual void OnToolGUI(SceneView view) + { + if (!Selection.activeTransform || Tools.s_Hidden) + { + return; + } + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + EditorGUI.BeginDisabledGroup(flag); + Vector3 handlePosition = Tools.handlePosition; + this.ToolGUI(view, handlePosition, flag); + Handles.ShowStaticLabelIfNeeded(handlePosition); + EditorGUI.EndDisabledGroup(); + } + public abstract void ToolGUI(SceneView view, Vector3 handlePosition, bool isStatic); + } +} diff --git a/UnityEditor/UnityEditor/ManipulationToolUtility.cs b/UnityEditor/UnityEditor/ManipulationToolUtility.cs new file mode 100644 index 00000000..d8d94101 --- /dev/null +++ b/UnityEditor/UnityEditor/ManipulationToolUtility.cs @@ -0,0 +1,67 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ManipulationToolUtility + { + public delegate void HandleDragChange(string handleName, bool dragging); + public static ManipulationToolUtility.HandleDragChange handleDragChange; + public static Vector3 minDragDifference + { + get; + set; + } + public static void SetMinDragDifferenceForPos(Vector3 position) + { + ManipulationToolUtility.minDragDifference = Vector3.one * (HandleUtility.GetHandleSize(position) / 80f); + } + public static void DisableMinDragDifference() + { + ManipulationToolUtility.minDragDifference = Vector3.zero; + } + public static void DisableMinDragDifferenceForAxis(int axis) + { + Vector2 v = ManipulationToolUtility.minDragDifference; + v[axis] = 0f; + ManipulationToolUtility.minDragDifference = v; + } + public static void DisableMinDragDifferenceBasedOnSnapping(Vector3 positionBeforeSnapping, Vector3 positionAfterSnapping) + { + for (int i = 0; i < 3; i++) + { + if (positionBeforeSnapping[i] != positionAfterSnapping[i]) + { + ManipulationToolUtility.DisableMinDragDifferenceForAxis(i); + } + } + } + public static void BeginDragging(string handleName) + { + if (ManipulationToolUtility.handleDragChange != null) + { + ManipulationToolUtility.handleDragChange(handleName, true); + } + } + public static void EndDragging(string handleName) + { + if (ManipulationToolUtility.handleDragChange != null) + { + ManipulationToolUtility.handleDragChange(handleName, false); + } + } + public static void DetectDraggingBasedOnMouseDownUp(string handleName, EventType typeBefore) + { + if (typeBefore == EventType.MouseDrag && Event.current.type != EventType.MouseDrag) + { + ManipulationToolUtility.BeginDragging(handleName); + } + else + { + if (typeBefore == EventType.MouseUp && Event.current.type != EventType.MouseUp) + { + ManipulationToolUtility.EndDragging(handleName); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaskFieldGUI.cs b/UnityEditor/UnityEditor/MaskFieldGUI.cs new file mode 100644 index 00000000..55dd0d7d --- /dev/null +++ b/UnityEditor/UnityEditor/MaskFieldGUI.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal static class MaskFieldGUI + { + private class MaskCallbackInfo + { + private const string kMaskMenuChangedMessage = "MaskMenuChanged"; + public static MaskFieldGUI.MaskCallbackInfo m_Instance; + private readonly int m_ControlID; + private int m_Mask; + private bool m_SetAll; + private bool m_ClearAll; + private bool m_DoNothing; + private readonly GUIView m_SourceView; + public MaskCallbackInfo(int controlID) + { + this.m_ControlID = controlID; + this.m_SourceView = GUIView.current; + } + public static int GetSelectedValueForControl(int controlID, int mask, out int changedFlags, out bool changedToValue) + { + Event current = Event.current; + changedFlags = 0; + changedToValue = false; + if (current.type == EventType.ExecuteCommand && current.commandName == "MaskMenuChanged") + { + if (MaskFieldGUI.MaskCallbackInfo.m_Instance == null) + { + Debug.LogError("Mask menu has no instance"); + return mask; + } + if (MaskFieldGUI.MaskCallbackInfo.m_Instance.m_ControlID == controlID) + { + if (!MaskFieldGUI.MaskCallbackInfo.m_Instance.m_DoNothing) + { + if (MaskFieldGUI.MaskCallbackInfo.m_Instance.m_ClearAll) + { + mask = 0; + changedFlags = -1; + changedToValue = false; + } + else + { + if (MaskFieldGUI.MaskCallbackInfo.m_Instance.m_SetAll) + { + mask = -1; + changedFlags = -1; + changedToValue = true; + } + else + { + mask ^= MaskFieldGUI.MaskCallbackInfo.m_Instance.m_Mask; + changedFlags = MaskFieldGUI.MaskCallbackInfo.m_Instance.m_Mask; + changedToValue = ((mask & MaskFieldGUI.MaskCallbackInfo.m_Instance.m_Mask) > 0); + } + } + GUI.changed = true; + } + MaskFieldGUI.MaskCallbackInfo.m_Instance.m_DoNothing = false; + MaskFieldGUI.MaskCallbackInfo.m_Instance.m_ClearAll = false; + MaskFieldGUI.MaskCallbackInfo.m_Instance.m_SetAll = false; + MaskFieldGUI.MaskCallbackInfo.m_Instance = null; + current.Use(); + } + } + return mask; + } + internal void SetMaskValueDelegate(object userData, string[] options, int selected) + { + if (selected != 0) + { + if (selected != 1) + { + this.m_Mask = 1 << selected - 2; + } + else + { + this.m_SetAll = true; + } + } + else + { + this.m_ClearAll = true; + } + if (this.m_SourceView) + { + this.m_SourceView.SendEvent(EditorGUIUtility.CommandEvent("MaskMenuChanged")); + } + } + } + internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, GUIStyle style) + { + int num; + bool flag; + return MaskFieldGUI.DoMaskField(position, controlID, mask, flagNames, style, out num, out flag); + } + internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, GUIStyle style, out int changedFlags, out bool changedToValue) + { + mask = MaskFieldGUI.MaskCallbackInfo.GetSelectedValueForControl(controlID, mask, out changedFlags, out changedToValue); + List list = new List(); + List list2 = new List + { + "Nothing", + "Everything" + }; + for (int i = 0; i < flagNames.Length; i++) + { + if ((mask & 1 << i) > 0) + { + list.Add(i + 2); + } + } + list2.AddRange(flagNames); + GUIContent content = EditorGUI.mixedValueContent; + if (!EditorGUI.showMixedValue) + { + int count = list.Count; + if (count != 0) + { + if (count != 1) + { + if (list.Count >= flagNames.Length) + { + content = EditorGUIUtility.TempContent("Everything"); + list.Add(1); + mask = -1; + } + else + { + content = EditorGUIUtility.TempContent("Mixed ..."); + } + } + else + { + content = new GUIContent(list2[list[0]]); + } + } + else + { + content = EditorGUIUtility.TempContent("Nothing"); + list.Add(0); + } + } + Event current = Event.current; + if (current.type == EventType.Repaint) + { + style.Draw(position, content, controlID, false); + } + else + { + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + MaskFieldGUI.MaskCallbackInfo.m_Instance = new MaskFieldGUI.MaskCallbackInfo(controlID); + current.Use(); + EditorUtility.DisplayCustomMenu(position, list2.ToArray(), (!EditorGUI.showMixedValue) ? list.ToArray() : new int[0], new EditorUtility.SelectMenuItemFunction(MaskFieldGUI.MaskCallbackInfo.m_Instance.SetMaskValueDelegate), null); + } + } + return mask; + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialEditor.cs b/UnityEditor/UnityEditor/MaterialEditor.cs new file mode 100644 index 00000000..36d886a6 --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialEditor.cs @@ -0,0 +1,1070 @@ +using System; +using UnityEditor.Utils; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Material))] + public class MaterialEditor : Editor + { + private enum PreviewType + { + Mesh, + Plane + } + private class ForwardApplyMaterialModification + { + private Renderer renderer; + public ForwardApplyMaterialModification(Renderer r) + { + this.renderer = r; + } + public bool DidModifyAnimationModeMaterialProperty(MaterialProperty property, int changedMask, object previousValue) + { + return MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(property, changedMask, this.renderer, previousValue); + } + } + private const int kSpacingUnderTexture = 6; + private bool m_IsVisible; + private SerializedProperty m_Shader; + private string m_InfoMessage; + private Vector2 m_PreviewDir = new Vector2(0f, -20f); + private int m_SelectedMesh; + private int m_TimeUpdate; + private int m_LightMode = 1; + private MaterialProperty.TexDim m_DesiredTexdim; + private PreviewRenderUtility m_PreviewUtility; + private static Mesh[] s_Meshes = new Mesh[4]; + private static Mesh s_PlaneMesh = null; + private static GUIContent[] s_MeshIcons = new GUIContent[4]; + private static GUIContent[] s_LightIcons = new GUIContent[2]; + private static GUIContent[] s_TimeIcons = new GUIContent[2]; + public bool isVisible + { + get + { + return this.m_IsVisible; + } + } + private MaterialEditor.PreviewType GetPreviewType(Material mat) + { + if (mat == null) + { + return MaterialEditor.PreviewType.Mesh; + } + string a = mat.GetTag("PreviewType", false, string.Empty).ToLower(); + if (a == "plane") + { + return MaterialEditor.PreviewType.Plane; + } + return MaterialEditor.PreviewType.Mesh; + } + private bool DoesPreviewAllowRotation(MaterialEditor.PreviewType type) + { + return type != MaterialEditor.PreviewType.Plane; + } + public void SetShader(Shader shader) + { + this.SetShader(shader, true); + } + public void SetShader(Shader shader, bool registerUndo) + { + bool flag = false; + Shader shader2 = this.m_Shader.objectReferenceValue as Shader; + if (shader2 != null && shader2.customEditor != shader.customEditor) + { + flag = true; + } + this.m_Shader.objectReferenceValue = shader; + base.serializedObject.ApplyModifiedProperties(); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + if (material.shader.customEditor != shader.customEditor) + { + flag = true; + } + Undo.RecordObject(material, "Assign shader"); + material.shader = shader; + EditorMaterialUtility.ResetDefaultTextures(material, false); + MaterialEditor.ApplyMaterialPropertyDrawers(material); + } + if (flag && ActiveEditorTracker.sharedTracker != null) + { + ActiveEditorTracker.sharedTracker.ForceRebuild(); + } + } + private void OnSelectedShaderPopup(string command, Shader shader) + { + base.serializedObject.Update(); + if (shader != null) + { + this.SetShader(shader); + } + this.PropertiesChanged(); + } + private void ShaderPopup(GUIStyle style) + { + bool enabled = GUI.enabled; + Shader shader = this.m_Shader.objectReferenceValue as Shader; + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, 47385, EditorGUIUtility.TempContent("Shader")); + EditorGUI.showMixedValue = this.m_Shader.hasMultipleDifferentValues; + GUIContent content = EditorGUIUtility.TempContent((!(shader != null)) ? "No Shader Selected" : shader.name); + if (EditorGUI.ButtonMouseDown(rect, content, EditorGUIUtility.native, style)) + { + EditorGUI.showMixedValue = false; + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(rect.x, rect.y)); + InternalEditorUtility.SetupShaderMenu(this.target as Material); + EditorUtility.Internal_DisplayPopupMenu(new Rect(vector.x, vector.y, rect.width, rect.height), "CONTEXT/ShaderPopup", this, 0); + Event.current.Use(); + } + EditorGUI.showMixedValue = false; + GUI.enabled = enabled; + } + public virtual void Awake() + { + this.m_IsVisible = InternalEditorUtility.GetIsInspectorExpanded(this.target); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + if (this.m_IsVisible && !this.m_Shader.hasMultipleDifferentValues && this.m_Shader.objectReferenceValue != null && this.PropertiesGUI()) + { + this.PropertiesChanged(); + } + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + public void PropertiesChanged() + { + this.m_InfoMessage = null; + if (base.targets.Length == 1) + { + this.m_InfoMessage = PerformanceChecks.CheckMaterial(this.target as Material, EditorUserBuildSettings.activeBuildTarget); + } + } + protected override void OnHeaderGUI() + { + Rect position = Editor.DrawHeaderGUI(this, this.targetTitle); + int controlID = GUIUtility.GetControlID(45678, FocusType.Passive); + bool flag = EditorGUI.DoObjectFoldout(controlID, position, base.targets, this.m_IsVisible); + if (flag != this.m_IsVisible) + { + this.m_IsVisible = flag; + InternalEditorUtility.SetIsInspectorExpanded(this.target, flag); + } + } + internal override void OnHeaderControlsGUI() + { + base.serializedObject.Update(); + EditorGUI.BeginDisabledGroup(!this.IsEnabled()); + EditorGUIUtility.labelWidth = 50f; + this.ShaderPopup("MiniPulldown"); + if (!this.m_Shader.hasMultipleDifferentValues && this.m_Shader.objectReferenceValue != null && (this.m_Shader.objectReferenceValue.hideFlags & HideFlags.DontSave) == HideFlags.None && GUILayout.Button("Edit...", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + AssetDatabase.OpenAsset(this.m_Shader.objectReferenceValue); + } + EditorGUI.EndDisabledGroup(); + } + [Obsolete("Use GetMaterialProperty instead.")] + public float GetFloat(string propertyName, out bool hasMixedValue) + { + hasMixedValue = false; + float @float = (base.targets[0] as Material).GetFloat(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + if ((base.targets[i] as Material).GetFloat(propertyName) != @float) + { + hasMixedValue = true; + break; + } + } + return @float; + } + [Obsolete("Use MaterialProperty instead.")] + public void SetFloat(string propertyName, float value) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + material.SetFloat(propertyName, value); + } + } + [Obsolete("Use GetMaterialProperty instead.")] + public Color GetColor(string propertyName, out bool hasMixedValue) + { + hasMixedValue = false; + Color color = (base.targets[0] as Material).GetColor(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + if ((base.targets[i] as Material).GetColor(propertyName) != color) + { + hasMixedValue = true; + break; + } + } + return color; + } + [Obsolete("Use MaterialProperty instead.")] + public void SetColor(string propertyName, Color value) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + material.SetColor(propertyName, value); + } + } + [Obsolete("Use GetMaterialProperty instead.")] + public Vector4 GetVector(string propertyName, out bool hasMixedValue) + { + hasMixedValue = false; + Vector4 vector = (base.targets[0] as Material).GetVector(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + if ((base.targets[i] as Material).GetVector(propertyName) != vector) + { + hasMixedValue = true; + break; + } + } + return vector; + } + [Obsolete("Use MaterialProperty instead.")] + public void SetVector(string propertyName, Vector4 value) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + material.SetVector(propertyName, value); + } + } + [Obsolete("Use GetMaterialProperty instead.")] + public Texture GetTexture(string propertyName, out bool hasMixedValue) + { + hasMixedValue = false; + Texture texture = (base.targets[0] as Material).GetTexture(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + if ((base.targets[i] as Material).GetTexture(propertyName) != texture) + { + hasMixedValue = true; + break; + } + } + return texture; + } + [Obsolete("Use MaterialProperty instead.")] + public void SetTexture(string propertyName, Texture value) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + material.SetTexture(propertyName, value); + } + } + [Obsolete("Use MaterialProperty instead.")] + public Vector2 GetTextureScale(string propertyName, out bool hasMixedValueX, out bool hasMixedValueY) + { + hasMixedValueX = false; + hasMixedValueY = false; + Vector2 textureScale = (base.targets[0] as Material).GetTextureScale(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + Vector2 textureScale2 = (base.targets[i] as Material).GetTextureScale(propertyName); + if (textureScale2.x != textureScale.x) + { + hasMixedValueX = true; + } + if (textureScale2.y != textureScale.y) + { + hasMixedValueY = true; + } + if (hasMixedValueX && hasMixedValueY) + { + break; + } + } + return textureScale; + } + [Obsolete("Use MaterialProperty instead.")] + public Vector2 GetTextureOffset(string propertyName, out bool hasMixedValueX, out bool hasMixedValueY) + { + hasMixedValueX = false; + hasMixedValueY = false; + Vector2 textureOffset = (base.targets[0] as Material).GetTextureOffset(propertyName); + for (int i = 1; i < base.targets.Length; i++) + { + Vector2 textureOffset2 = (base.targets[i] as Material).GetTextureOffset(propertyName); + if (textureOffset2.x != textureOffset.x) + { + hasMixedValueX = true; + } + if (textureOffset2.y != textureOffset.y) + { + hasMixedValueY = true; + } + if (hasMixedValueX && hasMixedValueY) + { + break; + } + } + return textureOffset; + } + [Obsolete("Use MaterialProperty instead.")] + public void SetTextureScale(string propertyName, Vector2 value, int coord) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + Vector2 textureScale = material.GetTextureScale(propertyName); + textureScale[coord] = value[coord]; + material.SetTextureScale(propertyName, textureScale); + } + } + [Obsolete("Use MaterialProperty instead.")] + public void SetTextureOffset(string propertyName, Vector2 value, int coord) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + Vector2 textureOffset = material.GetTextureOffset(propertyName); + textureOffset[coord] = value[coord]; + material.SetTextureOffset(propertyName, textureOffset); + } + } + public float RangeProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + return this.RangeProperty(propertyRect, prop, label); + } + public float RangeProperty(Rect position, MaterialProperty prop, string label) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + float power = (!(prop.name == "_Shininess")) ? 1f : 5f; + float floatValue = EditorGUI.PowerSlider(position, label, prop.floatValue, prop.rangeLimits.x, prop.rangeLimits.y, power); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = floatValue; + } + return prop.floatValue; + } + public float FloatProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + return this.FloatProperty(propertyRect, prop, label); + } + public float FloatProperty(Rect position, MaterialProperty prop, string label) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + float floatValue = EditorGUI.FloatField(position, label, prop.floatValue); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = floatValue; + } + return prop.floatValue; + } + public Color ColorProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + return this.ColorProperty(propertyRect, prop, label); + } + public Color ColorProperty(Rect position, MaterialProperty prop, string label) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + Color colorValue = EditorGUI.ColorField(position, label, prop.colorValue); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.colorValue = colorValue; + } + return prop.colorValue; + } + public Vector4 VectorProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + return this.VectorProperty(propertyRect, prop, label); + } + public Vector4 VectorProperty(Rect position, MaterialProperty prop, string label) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + Vector4 vectorValue = EditorGUI.Vector4Field(position, label, prop.vectorValue); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.vectorValue = vectorValue; + } + return prop.vectorValue; + } + internal static void TextureScaleOffsetProperty(Rect position, MaterialProperty property) + { + EditorGUI.BeginChangeCheck(); + int mixedValueMask = property.mixedValueMask >> 1; + Vector4 textureScaleAndOffset = MaterialEditor.TextureScaleOffsetProperty(position, property.textureScaleAndOffset, mixedValueMask); + if (EditorGUI.EndChangeCheck()) + { + property.textureScaleAndOffset = textureScaleAndOffset; + } + } + private Texture TexturePropertyBody(Rect position, MaterialProperty prop, string label) + { + position.xMin = position.xMax - 64f; + this.m_DesiredTexdim = prop.textureDimension; + Type objType; + switch (this.m_DesiredTexdim) + { + case MaterialProperty.TexDim.Tex2D: + objType = typeof(Texture); + goto IL_8F; + case MaterialProperty.TexDim.Tex3D: + objType = typeof(Texture3D); + goto IL_8F; + case MaterialProperty.TexDim.Cube: + objType = typeof(Cubemap); + goto IL_8F; + case MaterialProperty.TexDim.Any: + objType = typeof(Texture); + goto IL_8F; + } + objType = null; + IL_8F: + bool enabled = GUI.enabled; + EditorGUI.BeginChangeCheck(); + if ((prop.flags & MaterialProperty.PropFlags.PerRendererData) != MaterialProperty.PropFlags.None) + { + GUI.enabled = false; + } + EditorGUI.showMixedValue = prop.hasMixedValue; + Texture textureValue = EditorGUI.DoObjectField(position, position, GUIUtility.GetControlID(12354, EditorGUIUtility.native, position), prop.textureValue, objType, null, new EditorGUI.ObjectFieldValidator(this.TextureValidator), false) as Texture; + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.textureValue = textureValue; + } + GUI.enabled = enabled; + return prop.textureValue; + } + public Texture TextureProperty(MaterialProperty prop, string label) + { + return this.TextureProperty(prop, label, true); + } + public Texture TextureProperty(MaterialProperty prop, string label, bool scaleOffset) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + return this.TextureProperty(propertyRect, prop, label, scaleOffset); + } + private static bool DoesNeedNormalMapFix(MaterialProperty prop) + { + if (prop.name != "_BumpMap") + { + return false; + } + UnityEngine.Object[] targets = prop.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + if (InternalEditorUtility.BumpMapTextureNeedsFixing(material)) + { + return true; + } + } + return false; + } + public Texture TextureProperty(Rect position, MaterialProperty prop, string label, bool scaleOffset) + { + if (this.target is ProceduralMaterial) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + if (SubstanceImporter.IsProceduralTextureSlot(material, material.GetTexture(prop.name), prop.name)) + { + break; + } + } + } + EditorGUI.PrefixLabel(position, EditorGUIUtility.TempContent(label)); + float height = position.height - 64f - 6f; + position.height = 64f; + Rect position2 = position; + position2.xMin = position2.xMax - EditorGUIUtility.fieldWidth; + Texture result = this.TexturePropertyBody(position2, prop, label); + if (scaleOffset) + { + EditorGUI.indentLevel++; + Rect rect = position; + rect.yMin += 16f; + rect.xMax -= EditorGUIUtility.fieldWidth + 2f; + rect = EditorGUI.IndentedRect(rect); + EditorGUI.indentLevel--; + MaterialEditor.TextureScaleOffsetProperty(rect, prop); + } + if (MaterialEditor.DoesNeedNormalMapFix(prop)) + { + Rect rect2 = position; + rect2.y += rect2.height; + rect2.height = height; + rect2.yMin += 4f; + EditorGUI.indentLevel++; + rect2 = EditorGUI.IndentedRect(rect2); + EditorGUI.indentLevel--; + GUI.Box(rect2, GUIContent.none, EditorStyles.helpBox); + rect2 = EditorStyles.helpBox.padding.Remove(rect2); + Rect position3 = rect2; + position3.width -= 60f; + GUI.Label(position3, EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingWarning"), EditorStyles.wordWrappedMiniLabel); + position3 = rect2; + position3.xMin += position3.width - 60f; + position3.y += 2f; + position3.height -= 4f; + if (GUI.Button(position3, EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingButton"))) + { + UnityEngine.Object[] targets2 = base.targets; + for (int j = 0; j < targets2.Length; j++) + { + Material material2 = (Material)targets2[j]; + if (InternalEditorUtility.BumpMapTextureNeedsFixing(material2)) + { + InternalEditorUtility.FixNormalmapTexture(material2); + } + } + } + } + return result; + } + internal static Vector4 TextureScaleOffsetProperty(Rect position, Vector4 scaleOffset, int mixedValueMask) + { + Rect rect = default(Rect); + Rect rect6; + Rect rect5; + Rect rect4; + Rect rect3; + Rect rect2 = rect3 = (rect4 = (rect5 = (rect6 = rect))); + position.y = position.yMax - 48f + 3f; + rect5.x = position.x; + rect5.width = 10f; + rect6.x = rect5.xMax + 2f; + rect6.width = (position.xMax - rect6.x - 2f) / 2f; + rect.x = rect6.xMax + 2f; + rect.xMax = position.xMax; + rect3.y = position.y; + rect3.height = 16f; + rect2 = rect3; + rect2.y += 16f; + rect4 = rect2; + rect4.y += 16f; + GUI.Label(new Rect(rect5.x, rect2.y, rect5.width, rect2.height), "x", EditorStyles.miniLabel); + GUI.Label(new Rect(rect5.x, rect4.y, rect5.width, rect4.height), "y", EditorStyles.miniLabel); + GUI.Label(new Rect(rect6.x, rect3.y, rect6.width, rect3.height), "Tiling", EditorStyles.miniLabel); + GUI.Label(new Rect(rect.x, rect3.y, rect.width, rect3.height), "Offset", EditorStyles.miniLabel); + for (int i = 0; i < 2; i++) + { + int num = i; + EditorGUI.showMixedValue = ((mixedValueMask & 1 << num) != 0); + Rect rect7 = (i != 0) ? rect4 : rect2; + scaleOffset[num] = EditorGUI.FloatField(new Rect(rect6.x, rect7.y, rect6.width, rect7.height), scaleOffset[num], EditorStyles.miniTextField); + } + for (int j = 0; j < 2; j++) + { + int num2 = j + 2; + EditorGUI.showMixedValue = ((mixedValueMask & 1 << num2) != 0); + Rect rect8 = (j != 0) ? rect4 : rect2; + scaleOffset[num2] = EditorGUI.FloatField(new Rect(rect.x, rect8.y, rect.width, rect8.height), scaleOffset[num2], EditorStyles.miniTextField); + } + return scaleOffset; + } + public float GetPropertyHeight(MaterialProperty prop) + { + return this.GetPropertyHeight(prop, prop.displayName); + } + public float GetPropertyHeight(MaterialProperty prop, string label) + { + MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); + if (drawer != null) + { + return drawer.GetPropertyHeight(prop, label ?? prop.displayName, this); + } + return MaterialEditor.GetDefaultPropertyHeight(prop); + } + public static float GetDefaultPropertyHeight(MaterialProperty prop) + { + if (prop.type == MaterialProperty.PropType.Vector) + { + return 32f; + } + if (prop.type == MaterialProperty.PropType.Texture) + { + float num = 70f; + if (MaterialEditor.DoesNeedNormalMapFix(prop)) + { + num += 36f; + } + return num; + } + return 16f; + } + private Rect GetPropertyRect(MaterialProperty prop, string label, bool ignoreDrawer) + { + if (!ignoreDrawer) + { + MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); + if (drawer != null) + { + return EditorGUILayout.GetControlRect(true, drawer.GetPropertyHeight(prop, label ?? prop.displayName, this), EditorStyles.layerMaskField, new GUILayoutOption[0]); + } + } + return EditorGUILayout.GetControlRect(true, MaterialEditor.GetDefaultPropertyHeight(prop), EditorStyles.layerMaskField, new GUILayoutOption[0]); + } + public void ShaderProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, false); + this.ShaderProperty(propertyRect, prop, label); + } + public void ShaderProperty(Rect position, MaterialProperty prop, string label) + { + MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); + if (drawer != null) + { + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + drawer.OnGUI(position, prop, label ?? prop.displayName, this); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + return; + } + this.DefaultShaderProperty(position, prop, label); + } + public void DefaultShaderProperty(MaterialProperty prop, string label) + { + Rect propertyRect = this.GetPropertyRect(prop, label, true); + this.DefaultShaderProperty(propertyRect, prop, label); + } + public void DefaultShaderProperty(Rect position, MaterialProperty prop, string label) + { + switch (prop.type) + { + case MaterialProperty.PropType.Color: + this.ColorProperty(position, prop, label); + break; + case MaterialProperty.PropType.Vector: + this.VectorProperty(position, prop, label); + break; + case MaterialProperty.PropType.Float: + this.FloatProperty(position, prop, label); + break; + case MaterialProperty.PropType.Range: + this.RangeProperty(position, prop, label); + break; + case MaterialProperty.PropType.Texture: + this.TextureProperty(position, prop, label, true); + break; + default: + GUI.Label(position, string.Concat(new object[] + { + "Unknown property type: ", + prop.name, + ": ", + (int)prop.type + })); + break; + } + } + [Obsolete("Use RangeProperty with MaterialProperty instead.")] + public float RangeProperty(string propertyName, string label, float v2, float v3) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.RangeProperty(materialProperty, label); + } + [Obsolete("Use FloatProperty with MaterialProperty instead.")] + public float FloatProperty(string propertyName, string label) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.FloatProperty(materialProperty, label); + } + [Obsolete("Use ColorProperty with MaterialProperty instead.")] + public Color ColorProperty(string propertyName, string label) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.ColorProperty(materialProperty, label); + } + [Obsolete("Use VectorProperty with MaterialProperty instead.")] + public Vector4 VectorProperty(string propertyName, string label) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.VectorProperty(materialProperty, label); + } + [Obsolete("Use TextureProperty with MaterialProperty instead.")] + public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.TextureProperty(materialProperty, label, true); + } + [Obsolete("Use TextureProperty with MaterialProperty instead.")] + public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim, bool scaleOffset) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); + return this.TextureProperty(materialProperty, label, scaleOffset); + } + [Obsolete("Use ShaderProperty that takes MaterialProperty parameter instead.")] + public void ShaderProperty(Shader shader, int propertyIndex) + { + MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyIndex); + this.ShaderProperty(materialProperty, materialProperty.displayName); + } + public static MaterialProperty[] GetMaterialProperties(UnityEngine.Object[] mats) + { + return ShaderUtil.GetMaterialProperties(mats); + } + public static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, string name) + { + return ShaderUtil.GetMaterialProperty(mats, name); + } + public static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, int propertyIndex) + { + return ShaderUtil.GetMaterialProperty_Index(mats, propertyIndex); + } + private static Renderer GetAssociatedRenderFromInspector() + { + if (InspectorWindow.s_CurrentInspectorWindow) + { + Editor[] activeEditors = InspectorWindow.s_CurrentInspectorWindow.GetTracker().activeEditors; + Editor[] array = activeEditors; + for (int i = 0; i < array.Length; i++) + { + Editor editor = array[i]; + Renderer renderer = editor.target as Renderer; + if (renderer) + { + return renderer; + } + } + } + return null; + } + private Renderer PrepareMaterialPropertiesForAnimationMode(MaterialProperty[] properties) + { + if (!AnimationMode.InAnimationMode()) + { + return null; + } + Renderer associatedRenderFromInspector = MaterialEditor.GetAssociatedRenderFromInspector(); + if (associatedRenderFromInspector != null) + { + MaterialEditor.ForwardApplyMaterialModification @object = new MaterialEditor.ForwardApplyMaterialModification(associatedRenderFromInspector); + MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock(); + associatedRenderFromInspector.GetPropertyBlock(materialPropertyBlock); + for (int i = 0; i < properties.Length; i++) + { + MaterialProperty materialProperty = properties[i]; + materialProperty.ReadFromMaterialPropertyBlock(materialPropertyBlock); + materialProperty.applyPropertyCallback = new MaterialProperty.ApplyPropertyCallback(@object.DidModifyAnimationModeMaterialProperty); + } + } + return associatedRenderFromInspector; + } + public bool PropertiesGUI() + { + EditorGUIUtility.fieldWidth = 64f; + EditorGUIUtility.labelWidth = GUIClip.visibleRect.width - EditorGUIUtility.fieldWidth - 17f; + EditorGUI.BeginChangeCheck(); + if (this.m_InfoMessage != null) + { + EditorGUILayout.HelpBox(this.m_InfoMessage, MessageType.Info); + } + MaterialProperty[] materialProperties = MaterialEditor.GetMaterialProperties(base.targets); + Renderer renderer = this.PrepareMaterialPropertiesForAnimationMode(materialProperties); + float num = 0f; + for (int i = 0; i < materialProperties.Length; i++) + { + if ((materialProperties[i].flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) + { + num += this.GetPropertyHeight(materialProperties[i], materialProperties[i].displayName) + 2f; + } + } + Rect controlRect = EditorGUILayout.GetControlRect(true, num, EditorStyles.layerMaskField, new GUILayoutOption[0]); + for (int j = 0; j < materialProperties.Length; j++) + { + if ((materialProperties[j].flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) + { + float propertyHeight = this.GetPropertyHeight(materialProperties[j], materialProperties[j].displayName); + controlRect.height = propertyHeight; + Color color = GUI.color; + if (renderer != null && MaterialAnimationUtility.IsAnimated(materialProperties[j], renderer)) + { + GUI.color = AnimationMode.animatedPropertyColor; + } + this.ShaderProperty(controlRect, materialProperties[j], materialProperties[j].displayName); + GUI.color = color; + controlRect.y += propertyHeight + 2f; + } + } + return EditorGUI.EndChangeCheck(); + } + public static void ApplyMaterialPropertyDrawers(Material material) + { + UnityEngine.Object[] targets = new UnityEngine.Object[] + { + material + }; + MaterialEditor.ApplyMaterialPropertyDrawers(targets); + } + public static void ApplyMaterialPropertyDrawers(UnityEngine.Object[] targets) + { + if (targets == null || targets.Length == 0) + { + return; + } + Material material = targets[0] as Material; + if (material == null) + { + return; + } + Shader shader = material.shader; + MaterialProperty[] materialProperties = MaterialEditor.GetMaterialProperties(targets); + for (int i = 0; i < materialProperties.Length; i++) + { + MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer(shader, materialProperties[i].name); + if (drawer != null) + { + drawer.Apply(materialProperties[i]); + } + } + } + public void RegisterPropertyChangeUndo(string label) + { + Undo.RecordObjects(base.targets, "Modify " + label + " of " + this.targetTitle); + } + private UnityEngine.Object TextureValidator(UnityEngine.Object[] references, Type objType, SerializedProperty property) + { + for (int i = 0; i < references.Length; i++) + { + UnityEngine.Object @object = references[i]; + Texture texture = @object as Texture; + if (texture && (ShaderUtil.GetTextureDimension(texture) == (int)this.m_DesiredTexdim || this.m_DesiredTexdim == MaterialProperty.TexDim.Any)) + { + return texture; + } + } + return null; + } + private void Init() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + EditorUtility.SetCameraAnimateMaterials(this.m_PreviewUtility.m_Camera, true); + } + if (MaterialEditor.s_Meshes[0] == null) + { + GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + string name = transform.name; + switch (name) + { + case "sphere": + MaterialEditor.s_Meshes[0] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "cube": + MaterialEditor.s_Meshes[1] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "cylinder": + MaterialEditor.s_Meshes[2] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "torus": + MaterialEditor.s_Meshes[3] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + } + Debug.Log("Something is wrong, weird object found: " + transform.name); + } + MaterialEditor.s_MeshIcons[0] = EditorGUIUtility.IconContent("PreMatSphere"); + MaterialEditor.s_MeshIcons[1] = EditorGUIUtility.IconContent("PreMatCube"); + MaterialEditor.s_MeshIcons[2] = EditorGUIUtility.IconContent("PreMatCylinder"); + MaterialEditor.s_MeshIcons[3] = EditorGUIUtility.IconContent("PreMatTorus"); + MaterialEditor.s_LightIcons[0] = EditorGUIUtility.IconContent("PreMatLight0"); + MaterialEditor.s_LightIcons[1] = EditorGUIUtility.IconContent("PreMatLight1"); + MaterialEditor.s_TimeIcons[0] = EditorGUIUtility.IconContent("PlayButton"); + MaterialEditor.s_TimeIcons[1] = EditorGUIUtility.IconContent("PauseButton"); + MaterialEditor.s_PlaneMesh = (Resources.GetBuiltinResource(typeof(Mesh), "Quad.fbx") as Mesh); + } + } + public sealed override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + this.Init(); + Material mat = this.target as Material; + MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); + if (base.targets.Length > 1 || previewType == MaterialEditor.PreviewType.Mesh) + { + this.m_TimeUpdate = PreviewGUI.CycleButton(this.m_TimeUpdate, MaterialEditor.s_TimeIcons); + this.m_SelectedMesh = PreviewGUI.CycleButton(this.m_SelectedMesh, MaterialEditor.s_MeshIcons); + this.m_LightMode = PreviewGUI.CycleButton(this.m_LightMode, MaterialEditor.s_LightIcons); + } + } + public sealed override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + this.Init(); + this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float)width, (float)height)); + this.DoRenderPreview(); + return this.m_PreviewUtility.EndStaticPreview(); + } + private void DoRenderPreview() + { + if (this.m_PreviewUtility.m_RenderTexture.width <= 0 || this.m_PreviewUtility.m_RenderTexture.height <= 0) + { + return; + } + Material mat = this.target as Material; + MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 5f; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + Color ambient; + if (this.m_LightMode == 0) + { + this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0f; + ambient = new Color(0.2f, 0.2f, 0.2f, 0f); + } + else + { + this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + ambient = new Color(0.2f, 0.2f, 0.2f, 0f); + } + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + Quaternion rot = Quaternion.identity; + if (this.DoesPreviewAllowRotation(previewType)) + { + rot = Quaternion.Euler(this.m_PreviewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.m_PreviewDir.x, 0f); + } + Mesh mesh = MaterialEditor.s_Meshes[this.m_SelectedMesh]; + if (previewType == MaterialEditor.PreviewType.Plane) + { + mesh = MaterialEditor.s_PlaneMesh; + } + this.m_PreviewUtility.DrawMesh(mesh, Vector3.zero, rot, mat, 0); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + InternalEditorUtility.RemoveCustomLighting(); + } + public sealed override bool HasPreviewGUI() + { + return true; + } + public override bool RequiresConstantRepaint() + { + return this.m_TimeUpdate == 1; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Material preview \nnot available"); + } + return; + } + this.Init(); + Material mat = this.target as Material; + MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); + if (this.DoesPreviewAllowRotation(previewType)) + { + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); + } + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + this.DoRenderPreview(); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + public virtual void OnEnable() + { + this.m_Shader = base.serializedObject.FindProperty("m_Shader"); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.PropertiesChanged(); + } + public virtual void UndoRedoPerformed() + { + if (ActiveEditorTracker.sharedTracker != null) + { + ActiveEditorTracker.sharedTracker.ForceRebuild(); + } + this.PropertiesChanged(); + } + public virtual void OnDisable() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + internal void OnSceneDrag(SceneView sceneView) + { + Event current = Event.current; + if (current.type == EventType.Repaint) + { + return; + } + GameObject gameObject = HandleUtility.PickGameObject(current.mousePosition, false); + if (!gameObject || !gameObject.renderer) + { + return; + } + EventType type = current.type; + if (type != EventType.DragUpdated) + { + if (type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + Undo.RecordObject(gameObject.renderer, "Set Material"); + gameObject.renderer.sharedMaterial = (this.target as Material); + current.Use(); + } + } + else + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + Undo.RecordObject(gameObject.renderer, "Set Material"); + gameObject.renderer.sharedMaterial = (this.target as Material); + current.Use(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialEnumDrawer.cs b/UnityEditor/UnityEditor/MaterialEnumDrawer.cs new file mode 100644 index 00000000..8f360c98 --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialEnumDrawer.cs @@ -0,0 +1,172 @@ +using System; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialEnumDrawer : MaterialPropertyDrawer + { + public readonly string[] names; + public readonly int[] values; + public MaterialEnumDrawer(string enumName) + { + Type[] source = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => AssemblyHelper.GetTypesFromAssembly(x)).ToArray(); + try + { + Type enumType = source.FirstOrDefault((Type x) => x.IsSubclassOf(typeof(Enum)) && (x.Name == enumName || x.FullName == enumName)); + this.names = Enum.GetNames(enumType); + Array array = Enum.GetValues(enumType); + this.values = new int[array.Length]; + for (int i = 0; i < array.Length; i++) + { + this.values[i] = (int)array.GetValue(i); + } + } + catch (Exception) + { + Debug.LogWarning(string.Format("Failed to create MaterialEnum, enum {0} not found", enumName)); + throw; + } + } + public MaterialEnumDrawer(string n1, float v1) : this(new string[] + { + n1 + }, new float[] + { + v1 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2) : this(new string[] + { + n1, + n2 + }, new float[] + { + v1, + v2 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3) : this(new string[] + { + n1, + n2, + n3 + }, new float[] + { + v1, + v2, + v3 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4) : this(new string[] + { + n1, + n2, + n3, + n4 + }, new float[] + { + v1, + v2, + v3, + v4 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5) : this(new string[] + { + n1, + n2, + n3, + n4, + n5 + }, new float[] + { + v1, + v2, + v3, + v4, + v5 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5, string n6, float v6) : this(new string[] + { + n1, + n2, + n3, + n4, + n5, + n6 + }, new float[] + { + v1, + v2, + v3, + v4, + v5, + v6 + }) + { + } + public MaterialEnumDrawer(string n1, float v1, string n2, float v2, string n3, float v3, string n4, float v4, string n5, float v5, string n6, float v6, string n7, float v7) : this(new string[] + { + n1, + n2, + n3, + n4, + n5, + n6, + n7 + }, new float[] + { + v1, + v2, + v3, + v4, + v5, + v6, + v7 + }) + { + } + public MaterialEnumDrawer(string[] names, float[] vals) + { + this.names = names; + this.values = new int[vals.Length]; + for (int i = 0; i < vals.Length; i++) + { + this.values[i] = (int)vals[i]; + } + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + if (prop.type != MaterialProperty.PropType.Float && prop.type != MaterialProperty.PropType.Range) + { + return 40f; + } + return base.GetPropertyHeight(prop, label, editor); + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + if (prop.type != MaterialProperty.PropType.Float && prop.type != MaterialProperty.PropType.Range) + { + GUIContent label2 = EditorGUIUtility.TempContent("Enum used on a non-float property: " + prop.name, EditorGUIUtility.GetHelpIcon(MessageType.Warning)); + EditorGUI.LabelField(position, label2, EditorStyles.helpBox); + return; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + int num = (int)prop.floatValue; + num = EditorGUI.IntPopup(position, label, num, this.names, this.values); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = (float)num; + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs b/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs new file mode 100644 index 00000000..384828ae --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs @@ -0,0 +1,172 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialKeywordEnumDrawer : MaterialPropertyDrawer + { + public readonly string[] keywords; + public MaterialKeywordEnumDrawer(string kw1) : this(new string[] + { + kw1 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2) : this(new string[] + { + kw1, + kw2 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3) : this(new string[] + { + kw1, + kw2, + kw3 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4) : this(new string[] + { + kw1, + kw2, + kw3, + kw4 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5) : this(new string[] + { + kw1, + kw2, + kw3, + kw4, + kw5 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6) : this(new string[] + { + kw1, + kw2, + kw3, + kw4, + kw5, + kw6 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7) : this(new string[] + { + kw1, + kw2, + kw3, + kw4, + kw5, + kw6, + kw7 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7, string kw8) : this(new string[] + { + kw1, + kw2, + kw3, + kw4, + kw5, + kw6, + kw7, + kw8 + }) + { + } + public MaterialKeywordEnumDrawer(string kw1, string kw2, string kw3, string kw4, string kw5, string kw6, string kw7, string kw8, string kw9) : this(new string[] + { + kw1, + kw2, + kw3, + kw4, + kw5, + kw6, + kw7, + kw8, + kw9 + }) + { + } + public MaterialKeywordEnumDrawer(params string[] keywords) + { + this.keywords = keywords; + } + private static bool IsPropertyTypeSuitable(MaterialProperty prop) + { + return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range; + } + private void SetKeyword(MaterialProperty prop, int index) + { + for (int i = 0; i < this.keywords.Length; i++) + { + string keywordName = MaterialKeywordEnumDrawer.GetKeywordName(prop.name, this.keywords[i]); + UnityEngine.Object[] targets = prop.targets; + for (int j = 0; j < targets.Length; j++) + { + Material material = (Material)targets[j]; + if (index == i) + { + material.EnableKeyword(keywordName); + } + else + { + material.DisableKeyword(keywordName); + } + } + } + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + if (!MaterialKeywordEnumDrawer.IsPropertyTypeSuitable(prop)) + { + return 40f; + } + return base.GetPropertyHeight(prop, label, editor); + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + if (!MaterialKeywordEnumDrawer.IsPropertyTypeSuitable(prop)) + { + GUIContent label2 = EditorGUIUtility.TempContent("KeywordEnum used on a non-float property: " + prop.name, EditorGUIUtility.GetHelpIcon(MessageType.Warning)); + EditorGUI.LabelField(position, label2, EditorStyles.helpBox); + return; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + int num = (int)prop.floatValue; + num = EditorGUI.Popup(position, label, num, this.keywords); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = (float)num; + this.SetKeyword(prop, num); + } + } + public override void Apply(MaterialProperty prop) + { + base.Apply(prop); + if (!MaterialKeywordEnumDrawer.IsPropertyTypeSuitable(prop)) + { + return; + } + if (prop.hasMixedValue) + { + return; + } + this.SetKeyword(prop, (int)prop.floatValue); + } + private static string GetKeywordName(string propName, string name) + { + string text = propName + "_" + name; + return text.Replace(' ', '_').ToUpperInvariant(); + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs b/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs new file mode 100644 index 00000000..c31382da --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialPowerSliderDrawer : MaterialPropertyDrawer + { + public readonly float power; + public MaterialPowerSliderDrawer(float power) + { + this.power = power; + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + if (prop.type != MaterialProperty.PropType.Range) + { + return 40f; + } + return base.GetPropertyHeight(prop, label, editor); + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + if (prop.type != MaterialProperty.PropType.Range) + { + GUIContent label2 = EditorGUIUtility.TempContent("PowerSlider used on a non-range property: " + prop.name, EditorGUIUtility.GetHelpIcon(MessageType.Warning)); + EditorGUI.LabelField(position, label2, EditorStyles.helpBox); + return; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = prop.hasMixedValue; + float floatValue = EditorGUI.PowerSlider(position, label, prop.floatValue, prop.rangeLimits.x, prop.rangeLimits.y, this.power); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = floatValue; + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialProperty.cs b/UnityEditor/UnityEditor/MaterialProperty.cs new file mode 100644 index 00000000..b1c0113a --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialProperty.cs @@ -0,0 +1,298 @@ +using System; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class MaterialProperty + { + public enum PropType + { + Color, + Vector, + Float, + Range, + Texture + } + public enum TexDim + { + Unknown = -1, + None, + Tex2D = 2, + Tex3D, + Cube, + Any = 6 + } + [Flags] + public enum PropFlags + { + None = 0, + HideInInspector = 1, + PerRendererData = 2 + } + public delegate bool ApplyPropertyCallback(MaterialProperty prop, int changeMask, object previousValue); + private UnityEngine.Object[] m_Targets; + private MaterialProperty.ApplyPropertyCallback m_ApplyPropertyCallback; + private string m_Name; + private string m_DisplayName; + private object m_Value; + private Vector4 m_TextureScaleAndOffset; + private Vector2 m_RangeLimits; + private MaterialProperty.PropType m_Type; + private MaterialProperty.PropFlags m_Flags; + private MaterialProperty.TexDim m_TextureDimension; + private int m_MixedValueMask; + public UnityEngine.Object[] targets + { + get + { + return this.m_Targets; + } + } + public MaterialProperty.PropType type + { + get + { + return this.m_Type; + } + } + public string name + { + get + { + return this.m_Name; + } + } + public string displayName + { + get + { + return this.m_DisplayName; + } + } + public MaterialProperty.PropFlags flags + { + get + { + return this.m_Flags; + } + } + public MaterialProperty.TexDim textureDimension + { + get + { + return this.m_TextureDimension; + } + } + public Vector2 rangeLimits + { + get + { + return this.m_RangeLimits; + } + } + public bool hasMixedValue + { + get + { + return (this.m_MixedValueMask & 1) != 0; + } + } + public MaterialProperty.ApplyPropertyCallback applyPropertyCallback + { + get + { + return this.m_ApplyPropertyCallback; + } + set + { + this.m_ApplyPropertyCallback = value; + } + } + internal int mixedValueMask + { + get + { + return this.m_MixedValueMask; + } + } + public Color colorValue + { + get + { + if (this.m_Type == MaterialProperty.PropType.Color) + { + return (Color)this.m_Value; + } + return Color.black; + } + set + { + if (this.m_Type != MaterialProperty.PropType.Color) + { + return; + } + if (!this.hasMixedValue && value == (Color)this.m_Value) + { + return; + } + this.ApplyProperty(value); + } + } + public Vector4 vectorValue + { + get + { + if (this.m_Type == MaterialProperty.PropType.Vector) + { + return (Vector4)this.m_Value; + } + return Vector4.zero; + } + set + { + if (this.m_Type != MaterialProperty.PropType.Vector) + { + return; + } + if (!this.hasMixedValue && value == (Vector4)this.m_Value) + { + return; + } + this.ApplyProperty(value); + } + } + public float floatValue + { + get + { + if (this.m_Type == MaterialProperty.PropType.Float || this.m_Type == MaterialProperty.PropType.Range) + { + return (float)this.m_Value; + } + return 0f; + } + set + { + if (this.m_Type != MaterialProperty.PropType.Float && this.m_Type != MaterialProperty.PropType.Range) + { + return; + } + if (!this.hasMixedValue && value == (float)this.m_Value) + { + return; + } + this.ApplyProperty(value); + } + } + public Texture textureValue + { + get + { + if (this.m_Type == MaterialProperty.PropType.Texture) + { + return (Texture)this.m_Value; + } + return null; + } + set + { + if (this.m_Type != MaterialProperty.PropType.Texture) + { + return; + } + if (!this.hasMixedValue && value == (Texture)this.m_Value) + { + return; + } + this.m_MixedValueMask &= -2; + object value2 = this.m_Value; + this.m_Value = value; + this.ApplyProperty(value2, 1); + } + } + public Vector4 textureScaleAndOffset + { + get + { + if (this.m_Type == MaterialProperty.PropType.Texture) + { + return this.m_TextureScaleAndOffset; + } + return Vector4.zero; + } + set + { + if (this.m_Type != MaterialProperty.PropType.Texture) + { + return; + } + if (!this.hasMixedValue && value == this.m_TextureScaleAndOffset) + { + return; + } + this.m_MixedValueMask &= 1; + int num = 0; + for (int i = 1; i < 5; i++) + { + num |= 1 << i; + } + object previousValue = this.m_TextureScaleAndOffset; + this.m_TextureScaleAndOffset = value; + this.ApplyProperty(previousValue, num); + } + } + public void ReadFromMaterialPropertyBlock(MaterialPropertyBlock block) + { + ShaderUtil.ApplyMaterialPropertyBlockToMaterialProperty(block, this); + } + public void WriteToMaterialPropertyBlock(MaterialPropertyBlock materialblock, int changedPropertyMask) + { + ShaderUtil.ApplyMaterialPropertyToMaterialPropertyBlock(this, changedPropertyMask, materialblock); + } + internal static bool IsTextureOffsetAndScaleChangedMask(int changedMask) + { + changedMask >>= 1; + return changedMask != 0; + } + private void ApplyProperty(object newValue) + { + this.m_MixedValueMask = 0; + object value = this.m_Value; + this.m_Value = newValue; + this.ApplyProperty(value, 1); + } + private void ApplyProperty(object previousValue, int changedPropertyMask) + { + if (this.targets == null || this.targets.Length == 0) + { + throw new ArgumentException("No material targets provided"); + } + UnityEngine.Object[] targets = this.targets; + string str; + if (targets.Length == 1) + { + str = targets[0].name; + } + else + { + str = string.Concat(new object[] + { + targets.Length, + " ", + ObjectNames.NicifyVariableName(ObjectNames.GetClassName(targets[0])), + "s" + }); + } + bool flag = false; + if (this.m_ApplyPropertyCallback != null) + { + flag = this.m_ApplyPropertyCallback(this, changedPropertyMask, previousValue); + } + if (!flag) + { + ShaderUtil.ApplyProperty(this, changedPropertyMask, "Modify " + this.displayName + " of " + str); + } + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs b/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs new file mode 100644 index 00000000..2641f854 --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + public abstract class MaterialPropertyDrawer + { + internal static Dictionary s_PropertyDrawers = new Dictionary(); + public virtual void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent("No GUI Implemented")); + } + public virtual float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + return 16f; + } + public virtual void Apply(MaterialProperty prop) + { + } + private static string GetPropertyString(Shader shader, string name) + { + if (shader == null) + { + return string.Empty; + } + return shader.GetInstanceID() + "_" + name; + } + internal static void InvalidatePropertyCache(Shader shader) + { + if (shader == null) + { + return; + } + string value = shader.GetInstanceID() + "_"; + List list = new List(); + foreach (string current in MaterialPropertyDrawer.s_PropertyDrawers.Keys) + { + if (current.StartsWith(value)) + { + list.Add(current); + } + } + foreach (string current2 in list) + { + MaterialPropertyDrawer.s_PropertyDrawers.Remove(current2); + } + } + private static MaterialPropertyDrawer CreatePropertyDrawer(Type klass, string argsText) + { + if (string.IsNullOrEmpty(argsText)) + { + return Activator.CreateInstance(klass) as MaterialPropertyDrawer; + } + string[] array = argsText.Split(new char[] + { + ',' + }); + object[] array2 = new object[array.Length]; + for (int i = 0; i < array.Length; i++) + { + string text = array[i].Trim(); + float num; + if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num)) + { + array2[i] = num; + } + else + { + array2[i] = text; + } + } + return Activator.CreateInstance(klass, array2) as MaterialPropertyDrawer; + } + private static MaterialPropertyDrawer GetShaderPropertyDrawer(Shader shader, string name) + { + string shaderPropertyAttribute = ShaderUtil.GetShaderPropertyAttribute(shader, name); + if (string.IsNullOrEmpty(shaderPropertyAttribute)) + { + return null; + } + string text = shaderPropertyAttribute; + string text2 = string.Empty; + Match match = Regex.Match(shaderPropertyAttribute, "(\\w+)\\s*\\((.*)\\)"); + if (match.Success) + { + text = match.Groups[1].Value; + text2 = match.Groups[2].Value.Trim(); + } + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(MaterialPropertyDrawer))) + { + if (!(current.Name == text) && !(current.Name == text + "Drawer")) + { + if (!(current.Name == "Material" + text + "Drawer")) + { + continue; + } + } + try + { + MaterialPropertyDrawer result = MaterialPropertyDrawer.CreatePropertyDrawer(current, text2); + return result; + } + catch (Exception) + { + Debug.LogWarning(string.Format("Failed to create material drawer {0} with arguments '{1}'", text, text2)); + MaterialPropertyDrawer result = null; + return result; + } + } + return null; + } + internal static MaterialPropertyDrawer GetDrawer(Shader shader, string name) + { + if (shader == null) + { + return null; + } + string propertyString = MaterialPropertyDrawer.GetPropertyString(shader, name); + MaterialPropertyDrawer shaderPropertyDrawer; + if (MaterialPropertyDrawer.s_PropertyDrawers.TryGetValue(propertyString, out shaderPropertyDrawer)) + { + return shaderPropertyDrawer; + } + shaderPropertyDrawer = MaterialPropertyDrawer.GetShaderPropertyDrawer(shader, name); + MaterialPropertyDrawer.s_PropertyDrawers[propertyString] = shaderPropertyDrawer; + return shaderPropertyDrawer; + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialToggleDrawer.cs b/UnityEditor/UnityEditor/MaterialToggleDrawer.cs new file mode 100644 index 00000000..d00bf80b --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialToggleDrawer.cs @@ -0,0 +1,77 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialToggleDrawer : MaterialPropertyDrawer + { + public readonly string keyword; + public MaterialToggleDrawer() + { + } + public MaterialToggleDrawer(string keyword) + { + this.keyword = keyword; + } + private static bool IsPropertyTypeSuitable(MaterialProperty prop) + { + return prop.type == MaterialProperty.PropType.Float || prop.type == MaterialProperty.PropType.Range; + } + private void SetKeyword(MaterialProperty prop, bool on) + { + string text = (!string.IsNullOrEmpty(this.keyword)) ? this.keyword : (prop.name.ToUpperInvariant() + "_ON"); + UnityEngine.Object[] targets = prop.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + if (on) + { + material.EnableKeyword(text); + } + else + { + material.DisableKeyword(text); + } + } + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + if (!MaterialToggleDrawer.IsPropertyTypeSuitable(prop)) + { + return 40f; + } + return base.GetPropertyHeight(prop, label, editor); + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + if (!MaterialToggleDrawer.IsPropertyTypeSuitable(prop)) + { + GUIContent label2 = EditorGUIUtility.TempContent("Toggle used on a non-float property: " + prop.name, EditorGUIUtility.GetHelpIcon(MessageType.Warning)); + EditorGUI.LabelField(position, label2, EditorStyles.helpBox); + return; + } + EditorGUI.BeginChangeCheck(); + bool flag = Math.Abs(prop.floatValue) > 0.001f; + EditorGUI.showMixedValue = prop.hasMixedValue; + flag = EditorGUI.Toggle(position, label, flag); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + prop.floatValue = ((!flag) ? 0f : 1f); + this.SetKeyword(prop, flag); + } + } + public override void Apply(MaterialProperty prop) + { + base.Apply(prop); + if (!MaterialToggleDrawer.IsPropertyTypeSuitable(prop)) + { + return; + } + if (prop.hasMixedValue) + { + return; + } + this.SetKeyword(prop, Math.Abs(prop.floatValue) > 0.001f); + } + } +} diff --git a/UnityEditor/UnityEditor/MathUtils.cs b/UnityEditor/UnityEditor/MathUtils.cs new file mode 100644 index 00000000..bc5a6f6a --- /dev/null +++ b/UnityEditor/UnityEditor/MathUtils.cs @@ -0,0 +1,347 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class MathUtils + { + private const int kMaxDecimals = 15; + internal static float RoundToMultipleOf(float value, float roundingValue) + { + if (roundingValue == 0f) + { + return value; + } + return Mathf.Round(value / roundingValue) * roundingValue; + } + internal static float GetClosestPowerOfTen(float positiveNumber) + { + if (positiveNumber <= 0f) + { + return 1f; + } + return Mathf.Pow(10f, (float)Mathf.RoundToInt(Mathf.Log10(positiveNumber))); + } + internal static int GetNumberOfDecimalsForMinimumDifference(float minDifference) + { + return Mathf.Clamp(-Mathf.FloorToInt(Mathf.Log10(minDifference)), 0, 15); + } + internal static float RoundBasedOnMinimumDifference(float valueToRound, float minDifference) + { + if (minDifference == 0f) + { + return MathUtils.DiscardLeastSignificantDecimal(valueToRound); + } + return (float)Math.Round((double)valueToRound, MathUtils.GetNumberOfDecimalsForMinimumDifference(minDifference), MidpointRounding.AwayFromZero); + } + internal static float DiscardLeastSignificantDecimal(float v) + { + int digits = Mathf.Clamp((int)(5f - Mathf.Log10(Mathf.Abs(v))), 0, 15); + return (float)Math.Round((double)v, digits, MidpointRounding.AwayFromZero); + } + public static float GetQuatLength(Quaternion q) + { + return Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); + } + public static Quaternion GetQuatConjugate(Quaternion q) + { + return new Quaternion(-q.x, -q.y, -q.z, q.w); + } + public static Matrix4x4 OrthogonalizeMatrix(Matrix4x4 m) + { + Matrix4x4 identity = Matrix4x4.identity; + Vector3 vector = m.GetColumn(0); + Vector3 vector2 = m.GetColumn(1); + Vector3 normalized = m.GetColumn(2).normalized; + vector = Vector3.Cross(vector2, normalized).normalized; + vector2 = Vector3.Cross(normalized, vector).normalized; + identity.SetColumn(0, vector); + identity.SetColumn(1, vector2); + identity.SetColumn(2, normalized); + return identity; + } + public static void QuaternionNormalize(ref Quaternion q) + { + float num = 1f / Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); + q.x *= num; + q.y *= num; + q.z *= num; + q.w *= num; + } + public static Quaternion QuaternionFromMatrix(Matrix4x4 m) + { + Quaternion result = default(Quaternion); + result.w = Mathf.Sqrt(Mathf.Max(0f, 1f + m[0, 0] + m[1, 1] + m[2, 2])) / 2f; + result.x = Mathf.Sqrt(Mathf.Max(0f, 1f + m[0, 0] - m[1, 1] - m[2, 2])) / 2f; + result.y = Mathf.Sqrt(Mathf.Max(0f, 1f - m[0, 0] + m[1, 1] - m[2, 2])) / 2f; + result.z = Mathf.Sqrt(Mathf.Max(0f, 1f - m[0, 0] - m[1, 1] + m[2, 2])) / 2f; + result.x *= Mathf.Sign(result.x * (m[2, 1] - m[1, 2])); + result.y *= Mathf.Sign(result.y * (m[0, 2] - m[2, 0])); + result.z *= Mathf.Sign(result.z * (m[1, 0] - m[0, 1])); + MathUtils.QuaternionNormalize(ref result); + return result; + } + public static Quaternion GetQuatLog(Quaternion q) + { + Quaternion result = q; + result.w = 0f; + if (Mathf.Abs(q.w) < 1f) + { + float num = Mathf.Acos(q.w); + float num2 = Mathf.Sin(num); + if ((double)Mathf.Abs(num2) > 0.0001) + { + float num3 = num / num2; + result.x = q.x * num3; + result.y = q.y * num3; + result.z = q.z * num3; + } + } + return result; + } + public static Quaternion GetQuatExp(Quaternion q) + { + Quaternion result = q; + float num = Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z); + float num2 = Mathf.Sin(num); + result.w = Mathf.Cos(num); + if ((double)Mathf.Abs(num2) > 0.0001) + { + float num3 = num2 / num; + result.x = num3 * q.x; + result.y = num3 * q.y; + result.z = num3 * q.z; + } + return result; + } + public static Quaternion GetQuatSquad(float t, Quaternion q0, Quaternion q1, Quaternion a0, Quaternion a1) + { + float t2 = 2f * t * (1f - t); + Quaternion p = MathUtils.Slerp(q0, q1, t); + Quaternion q2 = MathUtils.Slerp(a0, a1, t); + Quaternion result = MathUtils.Slerp(p, q2, t2); + float num = Mathf.Sqrt(result.x * result.x + result.y * result.y + result.z * result.z + result.w * result.w); + result.x /= num; + result.y /= num; + result.z /= num; + result.w /= num; + return result; + } + public static Quaternion GetSquadIntermediate(Quaternion q0, Quaternion q1, Quaternion q2) + { + Quaternion quatConjugate = MathUtils.GetQuatConjugate(q1); + Quaternion quatLog = MathUtils.GetQuatLog(quatConjugate * q0); + Quaternion quatLog2 = MathUtils.GetQuatLog(quatConjugate * q2); + Quaternion q3 = new Quaternion(-0.25f * (quatLog.x + quatLog2.x), -0.25f * (quatLog.y + quatLog2.y), -0.25f * (quatLog.z + quatLog2.z), -0.25f * (quatLog.w + quatLog2.w)); + return q1 * MathUtils.GetQuatExp(q3); + } + public static float Ease(float t, float k1, float k2) + { + float num = k1 * 2f / 3.14159274f + k2 - k1 + (1f - k2) * 2f / 3.14159274f; + float num2; + if (t < k1) + { + num2 = k1 * 0.636619747f * (Mathf.Sin(t / k1 * 3.14159274f / 2f - 1.57079637f) + 1f); + } + else + { + if (t < k2) + { + num2 = 2f * k1 / 3.14159274f + t - k1; + } + else + { + num2 = 2f * k1 / 3.14159274f + k2 - k1 + (1f - k2) * 0.636619747f * Mathf.Sin((t - k2) / (1f - k2) * 3.14159274f / 2f); + } + } + return num2 / num; + } + public static Quaternion Slerp(Quaternion p, Quaternion q, float t) + { + float num = Quaternion.Dot(p, q); + Quaternion result; + if ((double)(1f + num) > 1E-05) + { + float num4; + float num5; + if ((double)(1f - num) > 1E-05) + { + float num2 = Mathf.Acos(num); + float num3 = 1f / Mathf.Sin(num2); + num4 = Mathf.Sin((1f - t) * num2) * num3; + num5 = Mathf.Sin(t * num2) * num3; + } + else + { + num4 = 1f - t; + num5 = t; + } + result.x = num4 * p.x + num5 * q.x; + result.y = num4 * p.y + num5 * q.y; + result.z = num4 * p.z + num5 * q.z; + result.w = num4 * p.w + num5 * q.w; + } + else + { + float num6 = Mathf.Sin((1f - t) * 3.14159274f * 0.5f); + float num7 = Mathf.Sin(t * 3.14159274f * 0.5f); + result.x = num6 * p.x - num7 * p.y; + result.y = num6 * p.y + num7 * p.x; + result.z = num6 * p.z - num7 * p.w; + result.w = p.z; + } + return result; + } + public static object IntersectRayTriangle(Ray ray, Vector3 v0, Vector3 v1, Vector3 v2, bool bidirectional) + { + Vector3 lhs = v1 - v0; + Vector3 vector = v2 - v0; + Vector3 vector2 = Vector3.Cross(lhs, vector); + float num = Vector3.Dot(-ray.direction, vector2); + if (num <= 0f) + { + return null; + } + Vector3 vector3 = ray.origin - v0; + float num2 = Vector3.Dot(vector3, vector2); + if (num2 < 0f && !bidirectional) + { + return null; + } + Vector3 rhs = Vector3.Cross(-ray.direction, vector3); + float num3 = Vector3.Dot(vector, rhs); + if (num3 < 0f || num3 > num) + { + return null; + } + float num4 = -Vector3.Dot(lhs, rhs); + if (num4 < 0f || num3 + num4 > num) + { + return null; + } + float num5 = 1f / num; + num2 *= num5; + num3 *= num5; + num4 *= num5; + float x = 1f - num3 - num4; + return new RaycastHit + { + point = ray.origin + num2 * ray.direction, + distance = num2, + barycentricCoordinate = new Vector3(x, num3, num4), + normal = Vector3.Normalize(vector2) + }; + } + public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out float squaredDist, out float s, out Vector3 closestRay) + { + Vector3 origin = ray.origin; + Vector3 point = ray.GetPoint(10000f); + Vector3 vector = q1 - p1; + Vector3 vector2 = point - origin; + Vector3 rhs = p1 - origin; + float num = Vector3.Dot(vector, vector); + float num2 = Vector3.Dot(vector2, vector2); + float num3 = Vector3.Dot(vector2, rhs); + if (num <= 1.401298E-45f && num2 <= 1.401298E-45f) + { + squaredDist = Vector3.Dot(p1 - origin, p1 - origin); + s = 0f; + closestRay = origin; + return p1; + } + float num4; + if (num <= 1.401298E-45f) + { + s = 0f; + num4 = num3 / num2; + num4 = Mathf.Clamp(num4, 0f, 1f); + } + else + { + float num5 = Vector3.Dot(vector, rhs); + if (num2 <= 1.401298E-45f) + { + num4 = 0f; + s = Mathf.Clamp(-num5 / num, 0f, 1f); + } + else + { + float num6 = Vector3.Dot(vector, vector2); + float num7 = num * num2 - num6 * num6; + if (num7 != 0f) + { + s = Mathf.Clamp((num6 * num3 - num5 * num2) / num7, 0f, 1f); + } + else + { + s = 0f; + } + num4 = (num6 * s + num3) / num2; + if (num4 < 0f) + { + num4 = 0f; + s = Mathf.Clamp(-num5 / num, 0f, 1f); + } + else + { + if (num4 > 1f) + { + num4 = 1f; + s = Mathf.Clamp((num6 - num5) / num, 0f, 1f); + } + } + } + } + Vector3 vector3 = p1 + vector * s; + Vector3 vector4 = origin + vector2 * num4; + squaredDist = Vector3.Dot(vector3 - vector4, vector3 - vector4); + closestRay = vector4; + return vector3; + } + public static bool IntersectRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) + { + Vector3 vector = ray.origin - sphereOrigin; + float num = Vector3.Dot(vector, ray.direction); + float num2 = Vector3.Dot(vector, vector) - sphereRadius * sphereRadius; + if (num2 > 0f && num > 0f) + { + return false; + } + float num3 = num * num - num2; + if (num3 < 0f) + { + return false; + } + t = -num - Mathf.Sqrt(num3); + if (t < 0f) + { + t = 0f; + } + q = ray.origin + t * ray.direction; + return true; + } + public static bool ClosestPtRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) + { + Vector3 vector = ray.origin - sphereOrigin; + float num = Vector3.Dot(vector, ray.direction); + float num2 = Vector3.Dot(vector, vector) - sphereRadius * sphereRadius; + if (num2 > 0f && num > 0f) + { + t = 0f; + q = ray.origin; + return true; + } + float num3 = num * num - num2; + if (num3 < 0f) + { + num3 = 0f; + } + t = -num - Mathf.Sqrt(num3); + if (t < 0f) + { + t = 0f; + } + q = ray.origin + t * ray.direction; + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/MaximizedHostView.cs b/UnityEditor/UnityEditor/MaximizedHostView.cs new file mode 100644 index 00000000..f9fbb688 --- /dev/null +++ b/UnityEditor/UnityEditor/MaximizedHostView.cs @@ -0,0 +1,88 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class MaximizedHostView : HostView + { + public void OnGUI() + { + base.ClearBackground(); + EditorGUIUtility.ResetGUIState(); + Rect rect = new Rect(-2f, 0f, base.position.width + 4f, base.position.height); + this.background = "dockarea"; + GUIStyle style = "dockareaoverlay"; + rect = this.background.margin.Remove(rect); + base.DoWindowDecorationStart(); + Rect position = new Rect(rect.x + 1f, rect.y, rect.width - 2f, 17f); + if (Event.current.type == EventType.Repaint) + { + this.background.Draw(rect, GUIContent.none, false, false, false, false); + GUIStyle gUIStyle = "dragTab"; + gUIStyle.Draw(position, base.actualView.cachedTitleContent, false, false, true, base.hasFocus); + } + if (Event.current.type == EventType.ContextClick && position.Contains(Event.current.mousePosition)) + { + base.PopupGenericMenu(base.actualView, new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 0f, 0f)); + } + base.ShowGenericMenu(); + if (base.actualView) + { + base.actualView.m_Pos = base.borderSize.Remove(base.screenPosition); + if (base.actualView is GameView) + { + GUI.Box(rect, GUIContent.none, style); + } + } + DockArea.BeginOffsetArea(new Rect(rect.x + 2f, rect.y + 17f, rect.width - 4f, rect.height - 17f - 2f), GUIContent.none, "TabWindowBackground"); + try + { + base.Invoke("OnGUI"); + } + catch (TargetInvocationException ex) + { + throw ex.InnerException; + } + EditorGUIUtility.ResetGUIState(); + DockArea.EndOffsetArea(); + base.DoWindowDecorationEnd(); + GUI.Box(rect, GUIContent.none, style); + } + protected override RectOffset GetBorderSize() + { + return new RectOffset + { + top = 17, + bottom = 4 + }; + } + private void Unmaximize(object userData) + { + EditorWindow win = (EditorWindow)userData; + WindowLayout.Unmaximize(win); + } + protected override void AddDefaultItemsToMenu(GenericMenu menu, EditorWindow view) + { + if (menu.GetItemCount() != 0) + { + menu.AddSeparator(string.Empty); + } + menu.AddItem(EditorGUIUtility.TextContent("DockAreaMaximize"), !(base.parent is SplitView), new GenericMenu.MenuFunction2(this.Unmaximize), view); + menu.AddDisabledItem(EditorGUIUtility.TextContent("DockAreaCloseTab")); + menu.AddSeparator(string.Empty); + Type[] paneTypes = base.GetPaneTypes(); + GUIContent gUIContent = EditorGUIUtility.TextContent("DockAreaAddTab"); + Type[] array = paneTypes; + for (int i = 0; i < array.Length; i++) + { + Type type = array[i]; + if (type != null) + { + GUIContent gUIContent2 = new GUIContent(EditorGUIUtility.TextContent(type.ToString())); + gUIContent2.text = gUIContent.text + "/" + gUIContent2.text; + menu.AddDisabledItem(gUIContent2); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MecanimUtilities.cs b/UnityEditor/UnityEditor/MecanimUtilities.cs new file mode 100644 index 00000000..6a1b0942 --- /dev/null +++ b/UnityEditor/UnityEditor/MecanimUtilities.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class MecanimUtilities + { + public static bool HasChildMotion(Motion parent, Motion motion) + { + if (parent == motion) + { + return true; + } + if (parent is BlendTree) + { + BlendTree blendTree = parent as BlendTree; + int childCount = blendTree.childCount; + for (int i = 0; i < childCount; i++) + { + if (MecanimUtilities.HasChildMotion(blendTree.GetMotion(i), motion)) + { + return true; + } + } + } + return false; + } + public static bool StateMachineRelativePath(StateMachine parent, StateMachine toFind, ref List hierarchy) + { + hierarchy.Add(parent); + if (parent == toFind) + { + return true; + } + for (int i = 0; i < parent.stateMachineCount; i++) + { + if (MecanimUtilities.StateMachineRelativePath(parent.GetStateMachine(i), toFind, ref hierarchy)) + { + return true; + } + } + hierarchy.Remove(parent); + return false; + } + internal static bool AreSameAsset(UnityEngine.Object obj1, UnityEngine.Object obj2) + { + return AssetDatabase.GetAssetPath(obj1) == AssetDatabase.GetAssetPath(obj2); + } + internal static void DestroyStateMachineRecursive(StateMachine stateMachine) + { + for (int i = 0; i < stateMachine.stateMachineCount; i++) + { + StateMachine stateMachine2 = stateMachine.GetStateMachine(i); + if (MecanimUtilities.AreSameAsset(stateMachine, stateMachine2)) + { + MecanimUtilities.DestroyStateMachineRecursive(stateMachine2); + } + } + for (int j = 0; j < stateMachine.stateCount; j++) + { + for (int k = 0; k < stateMachine.motionSetCount; k++) + { + BlendTree blendTree = stateMachine.GetState(j).GetMotionInternal(k) as BlendTree; + if (blendTree != null && MecanimUtilities.AreSameAsset(stateMachine, blendTree)) + { + MecanimUtilities.DestroyBlendTreeRecursive(blendTree); + } + } + } + Undo.DestroyObjectImmediate(stateMachine); + } + internal static void DestroyBlendTreeRecursive(BlendTree blendTree) + { + for (int i = 0; i < blendTree.childCount; i++) + { + BlendTree blendTree2 = blendTree.GetMotion(i) as BlendTree; + if (blendTree2 != null && MecanimUtilities.AreSameAsset(blendTree, blendTree2)) + { + MecanimUtilities.DestroyBlendTreeRecursive(blendTree2); + } + } + Undo.DestroyObjectImmediate(blendTree); + } + } +} diff --git a/UnityEditor/UnityEditor/MemoryElement.cs b/UnityEditor/UnityEditor/MemoryElement.cs new file mode 100644 index 00000000..1c275371 --- /dev/null +++ b/UnityEditor/UnityEditor/MemoryElement.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + [Serializable] + internal class MemoryElement + { + public List children; + public MemoryElement parent; + public ObjectInfo memoryInfo; + public int totalMemory; + public int totalChildCount; + public string name; + public bool expanded; + public string description; + public MemoryElement() + { + this.children = new List(); + } + public MemoryElement(string n) + { + this.expanded = false; + this.name = n; + this.children = new List(); + this.description = string.Empty; + } + public MemoryElement(ObjectInfo memInfo, bool finalize) + { + this.expanded = false; + this.memoryInfo = memInfo; + this.name = this.memoryInfo.name; + this.totalMemory = ((memInfo == null) ? 0 : memInfo.memorySize); + this.totalChildCount = 1; + if (finalize) + { + this.children = new List(); + } + } + public MemoryElement(string n, List groups) + { + this.name = n; + this.expanded = false; + this.description = string.Empty; + this.totalMemory = 0; + this.totalChildCount = 0; + this.children = new List(); + foreach (MemoryElement current in groups) + { + this.AddChild(current); + } + } + public void ExpandChildren() + { + if (this.children != null) + { + return; + } + this.children = new List(); + for (int i = 0; i < this.ReferenceCount(); i++) + { + this.AddChild(new MemoryElement(this.memoryInfo.referencedBy[i], false)); + } + } + public int AccumulatedChildCount() + { + return this.totalChildCount; + } + public int ChildCount() + { + if (this.children != null) + { + return this.children.Count; + } + return this.ReferenceCount(); + } + public int ReferenceCount() + { + return (this.memoryInfo == null || this.memoryInfo.referencedBy == null) ? 0 : this.memoryInfo.referencedBy.Count; + } + public void AddChild(MemoryElement node) + { + if (node == this) + { + throw new Exception("Should not AddChild to itself"); + } + this.children.Add(node); + node.parent = this; + this.totalMemory += node.totalMemory; + this.totalChildCount += node.totalChildCount; + } + public int GetChildIndexInList() + { + for (int i = 0; i < this.parent.children.Count; i++) + { + if (this.parent.children[i] == this) + { + return i; + } + } + return this.parent.children.Count; + } + public MemoryElement GetPrevNode() + { + int num = this.GetChildIndexInList() - 1; + if (num >= 0) + { + MemoryElement memoryElement = this.parent.children[num]; + while (memoryElement.expanded) + { + memoryElement = memoryElement.children[memoryElement.children.Count - 1]; + } + return memoryElement; + } + return this.parent; + } + public MemoryElement GetNextNode() + { + if (this.expanded && this.children.Count > 0) + { + return this.children[0]; + } + int num = this.GetChildIndexInList() + 1; + if (num < this.parent.children.Count) + { + return this.parent.children[num]; + } + MemoryElement memoryElement = this.parent; + while (memoryElement.parent != null) + { + int num2 = memoryElement.GetChildIndexInList() + 1; + if (num2 < memoryElement.parent.children.Count) + { + return memoryElement.parent.children[num2]; + } + memoryElement = memoryElement.parent; + } + return null; + } + public MemoryElement GetRoot() + { + if (this.parent != null) + { + return this.parent.GetRoot(); + } + return this; + } + public MemoryElement FirstChild() + { + return this.children[0]; + } + public MemoryElement LastChild() + { + if (!this.expanded) + { + return this; + } + return this.children[this.children.Count - 1].LastChild(); + } + } +} diff --git a/UnityEditor/UnityEditor/MemoryElementDataManager.cs b/UnityEditor/UnityEditor/MemoryElementDataManager.cs new file mode 100644 index 00000000..ca4d2fb4 --- /dev/null +++ b/UnityEditor/UnityEditor/MemoryElementDataManager.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class MemoryElementDataManager + { + private enum ObjectTypeFilter + { + Scene, + Asset, + BuiltinResource, + DontSave, + Other + } + private static int SortByMemoryClassName(ObjectInfo x, ObjectInfo y) + { + return y.className.CompareTo(x.className); + } + private static int SortByMemorySize(MemoryElement x, MemoryElement y) + { + return y.totalMemory.CompareTo(x.totalMemory); + } + private static MemoryElementDataManager.ObjectTypeFilter GetObjectTypeFilter(ObjectInfo info) + { + switch (info.reason) + { + case 1: + return MemoryElementDataManager.ObjectTypeFilter.BuiltinResource; + case 2: + return MemoryElementDataManager.ObjectTypeFilter.DontSave; + case 3: + case 8: + case 9: + return MemoryElementDataManager.ObjectTypeFilter.Asset; + case 10: + return MemoryElementDataManager.ObjectTypeFilter.Other; + } + return MemoryElementDataManager.ObjectTypeFilter.Scene; + } + private static bool HasValidNames(List memory) + { + for (int i = 0; i < memory.Count; i++) + { + if (!string.IsNullOrEmpty(memory[i].name)) + { + return true; + } + } + return false; + } + private static List GenerateObjectTypeGroups(ObjectInfo[] memory, MemoryElementDataManager.ObjectTypeFilter filter) + { + List list = new List(); + MemoryElement memoryElement = null; + for (int i = 0; i < memory.Length; i++) + { + ObjectInfo objectInfo = memory[i]; + if (MemoryElementDataManager.GetObjectTypeFilter(objectInfo) == filter) + { + if (memoryElement == null || objectInfo.className != memoryElement.name) + { + memoryElement = new MemoryElement(objectInfo.className); + list.Add(memoryElement); + } + memoryElement.AddChild(new MemoryElement(objectInfo, true)); + } + } + list.Sort(new Comparison(MemoryElementDataManager.SortByMemorySize)); + foreach (MemoryElement current in list) + { + current.children.Sort(new Comparison(MemoryElementDataManager.SortByMemorySize)); + if (filter == MemoryElementDataManager.ObjectTypeFilter.Other && !MemoryElementDataManager.HasValidNames(current.children)) + { + current.children.Clear(); + } + } + return list; + } + public static MemoryElement GetTreeRoot(ObjectMemoryInfo[] memoryObjectList, int[] referencesIndices) + { + ObjectInfo[] array = new ObjectInfo[memoryObjectList.Length]; + for (int i = 0; i < memoryObjectList.Length; i++) + { + array[i] = new ObjectInfo + { + instanceId = memoryObjectList[i].instanceId, + memorySize = memoryObjectList[i].memorySize, + reason = memoryObjectList[i].reason, + name = memoryObjectList[i].name, + className = memoryObjectList[i].className + }; + } + int num = 0; + for (int j = 0; j < memoryObjectList.Length; j++) + { + for (int k = 0; k < memoryObjectList[j].count; k++) + { + int num2 = referencesIndices[k + num]; + if (array[num2].referencedBy == null) + { + array[num2].referencedBy = new List(); + } + array[num2].referencedBy.Add(array[j]); + } + num += memoryObjectList[j].count; + } + MemoryElement memoryElement = new MemoryElement(); + Array.Sort(array, new Comparison(MemoryElementDataManager.SortByMemoryClassName)); + memoryElement.AddChild(new MemoryElement("Scene Memory", MemoryElementDataManager.GenerateObjectTypeGroups(array, MemoryElementDataManager.ObjectTypeFilter.Scene))); + memoryElement.AddChild(new MemoryElement("Assets", MemoryElementDataManager.GenerateObjectTypeGroups(array, MemoryElementDataManager.ObjectTypeFilter.Asset))); + memoryElement.AddChild(new MemoryElement("Builtin Resources", MemoryElementDataManager.GenerateObjectTypeGroups(array, MemoryElementDataManager.ObjectTypeFilter.BuiltinResource))); + memoryElement.AddChild(new MemoryElement("Not Saved", MemoryElementDataManager.GenerateObjectTypeGroups(array, MemoryElementDataManager.ObjectTypeFilter.DontSave))); + memoryElement.AddChild(new MemoryElement("Other", MemoryElementDataManager.GenerateObjectTypeGroups(array, MemoryElementDataManager.ObjectTypeFilter.Other))); + memoryElement.children.Sort(new Comparison(MemoryElementDataManager.SortByMemorySize)); + return memoryElement; + } + } +} diff --git a/UnityEditor/UnityEditor/MemoryElementSelection.cs b/UnityEditor/UnityEditor/MemoryElementSelection.cs new file mode 100644 index 00000000..62f4df60 --- /dev/null +++ b/UnityEditor/UnityEditor/MemoryElementSelection.cs @@ -0,0 +1,108 @@ +using System; +namespace UnityEditor +{ + [Serializable] + internal class MemoryElementSelection + { + private MemoryElement m_Selected; + public MemoryElement Selected + { + get + { + return this.m_Selected; + } + } + public void SetSelection(MemoryElement node) + { + this.m_Selected = node; + for (MemoryElement parent = node.parent; parent != null; parent = parent.parent) + { + parent.expanded = true; + } + } + public void ClearSelection() + { + this.m_Selected = null; + } + public bool isSelected(MemoryElement node) + { + return this.m_Selected == node; + } + public void MoveUp() + { + if (this.m_Selected == null) + { + return; + } + if (this.m_Selected.parent == null) + { + return; + } + MemoryElement prevNode = this.m_Selected.GetPrevNode(); + if (prevNode.parent != null) + { + this.SetSelection(prevNode); + } + else + { + this.SetSelection(prevNode.FirstChild()); + } + } + public void MoveDown() + { + if (this.m_Selected == null) + { + return; + } + if (this.m_Selected.parent == null) + { + return; + } + MemoryElement nextNode = this.m_Selected.GetNextNode(); + if (nextNode != null) + { + this.SetSelection(nextNode); + } + } + public void MoveFirst() + { + if (this.m_Selected == null) + { + return; + } + if (this.m_Selected.parent == null) + { + return; + } + this.SetSelection(this.m_Selected.GetRoot().FirstChild()); + } + public void MoveLast() + { + if (this.m_Selected == null) + { + return; + } + if (this.m_Selected.parent == null) + { + return; + } + this.SetSelection(this.m_Selected.GetRoot().LastChild()); + } + public void MoveParent() + { + if (this.m_Selected == null) + { + return; + } + if (this.m_Selected.parent == null) + { + return; + } + if (this.m_Selected.parent.parent == null) + { + return; + } + this.SetSelection(this.m_Selected.parent); + } + } +} diff --git a/UnityEditor/UnityEditor/MemoryTreeList.cs b/UnityEditor/UnityEditor/MemoryTreeList.cs new file mode 100644 index 00000000..31aae9f6 --- /dev/null +++ b/UnityEditor/UnityEditor/MemoryTreeList.cs @@ -0,0 +1,301 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MemoryTreeList + { + internal class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle header = "OL title"; + public GUIStyle entryEven = "OL EntryBackEven"; + public GUIStyle entryOdd = "OL EntryBackOdd"; + public GUIStyle numberLabel = "OL Label"; + public GUIStyle foldout = "IN foldout"; + } + private const float kIndentPx = 16f; + private const float kBaseIndent = 4f; + protected const float kSmallMargin = 4f; + protected const float kRowHeight = 16f; + protected const float kNameColumnSize = 300f; + protected const float kColumnSize = 70f; + protected const float kFoldoutSize = 14f; + private static MemoryTreeList.Styles m_Styles; + public MemoryElementSelection m_MemorySelection; + protected MemoryElement m_Root; + protected EditorWindow m_EditorWindow; + protected SplitterState m_Splitter; + protected MemoryTreeList m_DetailView; + protected int m_ControlID; + protected Vector2 m_ScrollPosition; + protected float m_SelectionOffset; + protected float m_VisibleHeight; + protected static MemoryTreeList.Styles styles + { + get + { + MemoryTreeList.Styles arg_17_0; + if ((arg_17_0 = MemoryTreeList.m_Styles) == null) + { + arg_17_0 = (MemoryTreeList.m_Styles = new MemoryTreeList.Styles()); + } + return arg_17_0; + } + } + public MemoryTreeList(EditorWindow editorWindow, MemoryTreeList detailview) + { + this.m_MemorySelection = new MemoryElementSelection(); + this.m_EditorWindow = editorWindow; + this.m_DetailView = detailview; + this.m_ControlID = GUIUtility.GetPermanentControlID(); + this.SetupSplitter(); + } + protected virtual void SetupSplitter() + { + float[] array = new float[1]; + int[] array2 = new int[1]; + array[0] = 300f; + array2[0] = 100; + this.m_Splitter = new SplitterState(array, array2, null); + } + public void OnGUI() + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + SplitterGUILayout.BeginHorizontalSplit(this.m_Splitter, EditorStyles.toolbar, new GUILayoutOption[0]); + this.DrawHeader(); + SplitterGUILayout.EndHorizontalSplit(); + if (this.m_Root == null) + { + GUILayout.EndVertical(); + return; + } + this.HandleKeyboard(); + this.m_ScrollPosition = GUILayout.BeginScrollView(this.m_ScrollPosition, MemoryTreeList.styles.background); + int num = 0; + foreach (MemoryElement current in this.m_Root.children) + { + this.DrawItem(current, ref num, 1); + num++; + } + GUILayoutUtility.GetRect(0f, (float)num * 16f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (Event.current.type == EventType.Repaint) + { + this.m_VisibleHeight = GUIClip.visibleRect.height; + } + GUILayout.EndScrollView(); + GUILayout.EndVertical(); + } + private static float Clamp(float value, float min, float max) + { + return (value >= min) ? ((value <= max) ? value : max) : min; + } + public void SetRoot(MemoryElement root) + { + this.m_Root = root; + if (this.m_Root != null) + { + this.m_Root.ExpandChildren(); + } + if (this.m_DetailView != null) + { + this.m_DetailView.SetRoot(null); + } + } + public MemoryElement GetRoot() + { + return this.m_Root; + } + protected static void DrawBackground(int row, bool selected) + { + Rect position = MemoryTreeList.GenerateRect(row); + GUIStyle gUIStyle = (row % 2 != 0) ? MemoryTreeList.styles.entryOdd : MemoryTreeList.styles.entryEven; + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(position, GUIContent.none, false, false, selected, false); + } + } + protected virtual void DrawHeader() + { + GUILayout.Label("Referenced By:", MemoryTreeList.styles.header, new GUILayoutOption[0]); + } + protected static Rect GenerateRect(int row) + { + Rect result = new Rect(1f, 16f * (float)row, GUIClip.visibleRect.width, 16f); + return result; + } + protected virtual void DrawData(Rect rect, MemoryElement memoryElement, int indent, int row, bool selected) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + string text = memoryElement.name + "(" + memoryElement.memoryInfo.className + ")"; + MemoryTreeList.styles.numberLabel.Draw(rect, text, false, false, false, selected); + } + protected void DrawRecursiveData(MemoryElement element, ref int row, int indent) + { + if (element.ChildCount() == 0) + { + return; + } + element.ExpandChildren(); + foreach (MemoryElement current in element.children) + { + row++; + this.DrawItem(current, ref row, indent); + } + } + protected virtual void DrawItem(MemoryElement memoryElement, ref int row, int indent) + { + bool flag = this.m_MemorySelection.isSelected(memoryElement); + MemoryTreeList.DrawBackground(row, flag); + Rect rect = MemoryTreeList.GenerateRect(row); + rect.x = 4f + (float)indent * 16f - 14f; + Rect position = rect; + position.width = 14f; + if (memoryElement.ChildCount() > 0) + { + memoryElement.expanded = GUI.Toggle(position, memoryElement.expanded, GUIContent.none, MemoryTreeList.styles.foldout); + } + rect.x += 14f; + if (flag) + { + this.m_SelectionOffset = (float)row * 16f; + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + this.RowClicked(Event.current, memoryElement); + } + this.DrawData(rect, memoryElement, indent, row, flag); + if (memoryElement.expanded) + { + this.DrawRecursiveData(memoryElement, ref row, indent + 1); + } + } + protected void RowClicked(Event evt, MemoryElement memoryElement) + { + this.m_MemorySelection.SetSelection(memoryElement); + GUIUtility.keyboardControl = this.m_ControlID; + if (evt.clickCount == 2 && memoryElement.memoryInfo != null && memoryElement.memoryInfo.instanceId != 0) + { + Selection.instanceIDs = new int[0]; + Selection.activeInstanceID = memoryElement.memoryInfo.instanceId; + } + evt.Use(); + if (memoryElement.memoryInfo != null) + { + EditorGUIUtility.PingObject(memoryElement.memoryInfo.instanceId); + } + if (this.m_DetailView != null) + { + this.m_DetailView.SetRoot((memoryElement.memoryInfo != null) ? new MemoryElement(memoryElement.memoryInfo, false) : null); + } + this.m_EditorWindow.Repaint(); + } + protected void HandleKeyboard() + { + Event current = Event.current; + if (current.GetTypeForControl(this.m_ControlID) != EventType.KeyDown || this.m_ControlID != GUIUtility.keyboardControl) + { + return; + } + if (this.m_MemorySelection.Selected == null) + { + return; + } + KeyCode keyCode = current.keyCode; + switch (keyCode) + { + case KeyCode.UpArrow: + this.m_MemorySelection.MoveUp(); + goto IL_1D0; + case KeyCode.DownArrow: + this.m_MemorySelection.MoveDown(); + goto IL_1D0; + case KeyCode.RightArrow: + if (this.m_MemorySelection.Selected.ChildCount() > 0) + { + this.m_MemorySelection.Selected.expanded = true; + } + goto IL_1D0; + case KeyCode.LeftArrow: + if (this.m_MemorySelection.Selected.expanded) + { + this.m_MemorySelection.Selected.expanded = false; + } + else + { + this.m_MemorySelection.MoveParent(); + } + goto IL_1D0; + case KeyCode.Insert: + IL_73: + if (keyCode != KeyCode.Return) + { + return; + } + if (this.m_MemorySelection.Selected.memoryInfo != null) + { + Selection.instanceIDs = new int[0]; + Selection.activeInstanceID = this.m_MemorySelection.Selected.memoryInfo.instanceId; + } + goto IL_1D0; + case KeyCode.Home: + this.m_MemorySelection.MoveFirst(); + goto IL_1D0; + case KeyCode.End: + this.m_MemorySelection.MoveLast(); + goto IL_1D0; + case KeyCode.PageUp: + { + int num = Mathf.RoundToInt(this.m_VisibleHeight / 16f); + for (int i = 0; i < num; i++) + { + this.m_MemorySelection.MoveUp(); + } + goto IL_1D0; + } + case KeyCode.PageDown: + { + int num = Mathf.RoundToInt(this.m_VisibleHeight / 16f); + for (int j = 0; j < num; j++) + { + this.m_MemorySelection.MoveDown(); + } + goto IL_1D0; + } + } + goto IL_73; + IL_1D0: + this.RowClicked(current, this.m_MemorySelection.Selected); + this.EnsureVisible(); + this.m_EditorWindow.Repaint(); + } + private void RecursiveFindSelected(MemoryElement element, ref int row) + { + if (this.m_MemorySelection.isSelected(element)) + { + this.m_SelectionOffset = (float)row * 16f; + } + row++; + if (!element.expanded || element.ChildCount() == 0) + { + return; + } + element.ExpandChildren(); + foreach (MemoryElement current in element.children) + { + this.RecursiveFindSelected(current, ref row); + } + } + protected void EnsureVisible() + { + int num = 0; + this.RecursiveFindSelected(this.m_Root, ref num); + this.m_ScrollPosition.y = MemoryTreeList.Clamp(this.m_ScrollPosition.y, this.m_SelectionOffset - this.m_VisibleHeight, this.m_SelectionOffset - 16f); + } + } +} diff --git a/UnityEditor/UnityEditor/MemoryTreeListClickable.cs b/UnityEditor/UnityEditor/MemoryTreeListClickable.cs new file mode 100644 index 00000000..367bea64 --- /dev/null +++ b/UnityEditor/UnityEditor/MemoryTreeListClickable.cs @@ -0,0 +1,60 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MemoryTreeListClickable : MemoryTreeList + { + public MemoryTreeListClickable(EditorWindow editorWindow, MemoryTreeList detailview) : base(editorWindow, detailview) + { + } + protected override void SetupSplitter() + { + float[] array = new float[3]; + int[] array2 = new int[3]; + array[0] = 300f; + array2[0] = 100; + array[1] = 70f; + array2[1] = 50; + array[2] = 70f; + array2[2] = 50; + this.m_Splitter = new SplitterState(array, array2, null); + } + protected override void DrawHeader() + { + GUILayout.Label("Name", MemoryTreeList.styles.header, new GUILayoutOption[0]); + GUILayout.Label("Memory", MemoryTreeList.styles.header, new GUILayoutOption[0]); + GUILayout.Label("Ref count", MemoryTreeList.styles.header, new GUILayoutOption[0]); + } + protected override void DrawData(Rect rect, MemoryElement memoryElement, int indent, int row, bool selected) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + string text = memoryElement.name; + if (memoryElement.ChildCount() > 0 && indent < 3) + { + text = text + " (" + memoryElement.AccumulatedChildCount().ToString() + ")"; + } + int num = 0; + rect.xMax = (float)this.m_Splitter.realSizes[num]; + MemoryTreeList.styles.numberLabel.Draw(rect, text, false, false, false, selected); + rect.x = rect.xMax; + rect.width = (float)this.m_Splitter.realSizes[++num] - 4f; + MemoryTreeList.styles.numberLabel.Draw(rect, EditorUtility.FormatBytes(memoryElement.totalMemory), false, false, false, selected); + rect.x += (float)this.m_Splitter.realSizes[num++]; + rect.width = (float)this.m_Splitter.realSizes[num] - 4f; + if (memoryElement.ReferenceCount() > 0) + { + MemoryTreeList.styles.numberLabel.Draw(rect, memoryElement.ReferenceCount().ToString(), false, false, false, selected); + } + else + { + if (selected) + { + MemoryTreeList.styles.numberLabel.Draw(rect, string.Empty, false, false, false, selected); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MenuCommand.cs b/UnityEditor/UnityEditor/MenuCommand.cs new file mode 100644 index 00000000..fd0750ad --- /dev/null +++ b/UnityEditor/UnityEditor/MenuCommand.cs @@ -0,0 +1,22 @@ +using System; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class MenuCommand + { + public UnityEngine.Object context; + public int userData; + public MenuCommand(UnityEngine.Object inContext, int inUserData) + { + this.context = inContext; + this.userData = inUserData; + } + public MenuCommand(UnityEngine.Object inContext) + { + this.context = inContext; + this.userData = 0; + } + } +} diff --git a/UnityEditor/UnityEditor/MenuItem.cs b/UnityEditor/UnityEditor/MenuItem.cs new file mode 100644 index 00000000..de116bcb --- /dev/null +++ b/UnityEditor/UnityEditor/MenuItem.cs @@ -0,0 +1,33 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + public sealed class MenuItem : Attribute + { + public string menuItem; + public bool validate; + public int priority; + public MenuItem(string itemName) : this(itemName, false) + { + } + public MenuItem(string itemName, bool isValidateFunction) : this(itemName, isValidateFunction, (!itemName.StartsWith("GameObject/Create Other")) ? 1000 : 10) + { + } + public MenuItem(string itemName, bool isValidateFunction, int priority) : this(itemName, isValidateFunction, priority, false) + { + } + internal MenuItem(string itemName, bool isValidateFunction, int priority, bool internalMenu) + { + if (internalMenu) + { + this.menuItem = "internal:" + itemName; + } + else + { + this.menuItem = itemName; + } + this.validate = isValidateFunction; + this.priority = priority; + } + } +} diff --git a/UnityEditor/UnityEditor/MenuUtils.cs b/UnityEditor/UnityEditor/MenuUtils.cs new file mode 100644 index 00000000..cd3ee3a4 --- /dev/null +++ b/UnityEditor/UnityEditor/MenuUtils.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class MenuUtils + { + private class MenuCallbackObject + { + public string menuItemPath; + public UnityEngine.Object[] temporaryContext; + } + public static void MenuCallback(object callbackObject) + { + MenuUtils.MenuCallbackObject menuCallbackObject = callbackObject as MenuUtils.MenuCallbackObject; + if (menuCallbackObject.temporaryContext != null) + { + EditorApplication.ExecuteMenuItemWithTemporaryContext(menuCallbackObject.menuItemPath, menuCallbackObject.temporaryContext); + } + else + { + EditorApplication.ExecuteMenuItem(menuCallbackObject.menuItemPath); + } + } + public static void ExtractSubMenuWithPath(string path, GenericMenu menu, string replacementPath, UnityEngine.Object[] temporaryContext) + { + HashSet hashSet = new HashSet(Unsupported.GetSubmenus(path)); + string[] submenusIncludingSeparators = Unsupported.GetSubmenusIncludingSeparators(path); + for (int i = 0; i < submenusIncludingSeparators.Length; i++) + { + string text = submenusIncludingSeparators[i]; + string replacementMenuString = replacementPath + text.Substring(path.Length); + if (hashSet.Contains(text)) + { + MenuUtils.ExtractMenuItemWithPath(text, menu, replacementMenuString, temporaryContext); + } + } + } + public static void ExtractMenuItemWithPath(string menuString, GenericMenu menu, string replacementMenuString, UnityEngine.Object[] temporaryContext) + { + MenuUtils.MenuCallbackObject menuCallbackObject = new MenuUtils.MenuCallbackObject(); + menuCallbackObject.menuItemPath = menuString; + menuCallbackObject.temporaryContext = temporaryContext; + menu.AddItem(new GUIContent(replacementMenuString), false, new GenericMenu.MenuFunction2(MenuUtils.MenuCallback), menuCallbackObject); + } + } +} diff --git a/UnityEditor/UnityEditor/MeshColliderEditor.cs b/UnityEditor/UnityEditor/MeshColliderEditor.cs new file mode 100644 index 00000000..9e8f23d0 --- /dev/null +++ b/UnityEditor/UnityEditor/MeshColliderEditor.cs @@ -0,0 +1,29 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(MeshCollider))] + internal class MeshColliderEditor : Collider3DEditorBase + { + private SerializedProperty m_Mesh; + private SerializedProperty m_Convex; + private SerializedProperty m_SmoothSphereCollisions; + public override void OnEnable() + { + base.OnEnable(); + this.m_Mesh = base.serializedObject.FindProperty("m_Mesh"); + this.m_Convex = base.serializedObject.FindProperty("m_Convex"); + this.m_SmoothSphereCollisions = base.serializedObject.FindProperty("m_SmoothSphereCollisions"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Convex, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SmoothSphereCollisions, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Mesh, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/MeshRendererEditor.cs b/UnityEditor/UnityEditor/MeshRendererEditor.cs new file mode 100644 index 00000000..1a47608a --- /dev/null +++ b/UnityEditor/UnityEditor/MeshRendererEditor.cs @@ -0,0 +1,33 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(MeshRenderer))] + internal class MeshRendererEditor : Editor + { + private SerializedProperty m_UseLightProbes; + private SerializedProperty m_LightProbeAnchor; + public void OnEnable() + { + this.m_UseLightProbes = base.serializedObject.FindProperty("m_UseLightProbes"); + this.m_LightProbeAnchor = base.serializedObject.FindProperty("m_LightProbeAnchor"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Editor.DrawPropertiesExcluding(base.serializedObject, new string[] + { + "m_UseLightProbes", + "m_LightProbeAnchor" + }); + EditorGUILayout.PropertyField(this.m_UseLightProbes, new GUILayoutOption[0]); + if (this.m_UseLightProbes.boolValue) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_LightProbeAnchor, new GUIContent("Anchor Override", this.m_LightProbeAnchor.tooltip), new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/MeshUtility.cs b/UnityEditor/UnityEditor/MeshUtility.cs new file mode 100644 index 00000000..ba60ff41 --- /dev/null +++ b/UnityEditor/UnityEditor/MeshUtility.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class MeshUtility + { + public static void SetPerTriangleUV2(Mesh src, Vector2[] triUV) + { + int num = InternalMeshUtil.CalcTriangleCount(src); + int num2 = triUV.Length; + if (num2 != 3 * num) + { + Debug.LogError(string.Concat(new object[] + { + "mesh contains ", + num, + " triangles but ", + num2, + " uvs are provided" + })); + return; + } + MeshUtility.SetPerTriangleUV2NoCheck(src, triUV); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPerTriangleUV2NoCheck(Mesh src, Vector2[] triUV); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Vector2[] ComputeTextureBoundingHull(Texture texture, int vertexCount); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetMeshCompression(Mesh mesh, ModelImporterMeshCompression compression); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ModelImporterMeshCompression GetMeshCompression(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Optimize(Mesh mesh); + } +} diff --git a/UnityEditor/UnityEditor/MessageType.cs b/UnityEditor/UnityEditor/MessageType.cs new file mode 100644 index 00000000..1aab5a02 --- /dev/null +++ b/UnityEditor/UnityEditor/MessageType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum MessageType + { + None, + Info, + Warning, + Error + } +} diff --git a/UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs b/UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs new file mode 100644 index 00000000..f1efbea4 --- /dev/null +++ b/UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum MetroBuildAndRunDeployTarget + { + LocalMachine, + WindowsPhone, + LocalMachineAndWindowsPhone + } +} diff --git a/UnityEditor/UnityEditor/MetroBuildType.cs b/UnityEditor/UnityEditor/MetroBuildType.cs new file mode 100644 index 00000000..3e23634c --- /dev/null +++ b/UnityEditor/UnityEditor/MetroBuildType.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum MetroBuildType + { + AppX, + VisualStudioCpp, + VisualStudioCSharp, + VisualStudioCppDX, + VisualStudioCSharpDX + } +} diff --git a/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs b/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs new file mode 100644 index 00000000..eb0a5c20 --- /dev/null +++ b/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs @@ -0,0 +1,111 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MetroCertificatePasswordWindow : EditorWindow + { + private const float kSpace = 5f; + private const char kPasswordChar = '●'; + private const string kPasswordId = "password"; + private static readonly GUILayoutOption kLabelWidth = GUILayout.Width(110f); + private static readonly GUILayoutOption kButtonWidth = GUILayout.Width(110f); + private string path; + private string password; + private GUIContent message; + private GUIStyle messageStyle; + private string focus; + public static void Show(string path) + { + MetroCertificatePasswordWindow[] array = (MetroCertificatePasswordWindow[])Resources.FindObjectsOfTypeAll(typeof(MetroCertificatePasswordWindow)); + MetroCertificatePasswordWindow metroCertificatePasswordWindow = (array.Length <= 0) ? ScriptableObject.CreateInstance() : array[0]; + metroCertificatePasswordWindow.path = path; + metroCertificatePasswordWindow.password = string.Empty; + metroCertificatePasswordWindow.message = GUIContent.none; + metroCertificatePasswordWindow.messageStyle = new GUIStyle(GUI.skin.label); + metroCertificatePasswordWindow.messageStyle.fontStyle = FontStyle.Italic; + metroCertificatePasswordWindow.focus = "password"; + if (array.Length > 0) + { + metroCertificatePasswordWindow.Focus(); + } + else + { + metroCertificatePasswordWindow.title = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePasswordTitle").text; + metroCertificatePasswordWindow.position = new Rect(100f, 100f, 350f, 90f); + metroCertificatePasswordWindow.minSize = new Vector2(metroCertificatePasswordWindow.position.width, metroCertificatePasswordWindow.position.height); + metroCertificatePasswordWindow.maxSize = metroCertificatePasswordWindow.minSize; + metroCertificatePasswordWindow.ShowUtility(); + } + } + public void OnGUI() + { + Event current = Event.current; + bool flag = false; + bool flag2 = false; + if (current.type == EventType.KeyDown) + { + flag = (current.keyCode == KeyCode.Escape); + flag2 = (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter); + } + using (HorizontalLayout.DoLayout()) + { + GUILayout.Space(10f); + using (VerticalLayout.DoLayout()) + { + GUILayout.FlexibleSpace(); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePasswordPassword"), new GUILayoutOption[] + { + MetroCertificatePasswordWindow.kLabelWidth + }); + GUI.SetNextControlName("password"); + this.password = GUILayout.PasswordField(this.password, '●', new GUILayoutOption[0]); + } + GUILayout.Space(10f); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(this.message, this.messageStyle, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePasswordButton"), new GUILayoutOption[] + { + MetroCertificatePasswordWindow.kButtonWidth + }) || flag2) + { + this.message = GUIContent.none; + try + { + if (PlayerSettings.Metro.SetCertificate(this.path, this.password)) + { + flag = true; + } + else + { + this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePasswordPasswordInvalid"); + } + } + catch (UnityException ex) + { + Debug.LogError(ex.Message); + } + } + } + GUILayout.FlexibleSpace(); + } + GUILayout.Space(10f); + } + if (flag) + { + base.Close(); + } + else + { + if (this.focus != null) + { + EditorGUI.FocusTextInControl(this.focus); + this.focus = null; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs b/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs new file mode 100644 index 00000000..d9bae8db --- /dev/null +++ b/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs @@ -0,0 +1,163 @@ +using System; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class MetroCreateTestCertificateWindow : EditorWindow + { + private const float kSpace = 5f; + private const char kPasswordChar = '●'; + private const string kPublisherId = "publisher"; + private const string kPasswordId = "password"; + private const string kConfirmId = "confirm"; + private static readonly GUILayoutOption kLabelWidth = GUILayout.Width(110f); + private static readonly GUILayoutOption kButtonWidth = GUILayout.Width(110f); + private string path; + private string publisher; + private string password; + private string confirm; + private GUIContent message; + private GUIStyle messageStyle; + private string focus; + public static void Show(string publisher) + { + MetroCreateTestCertificateWindow[] array = (MetroCreateTestCertificateWindow[])Resources.FindObjectsOfTypeAll(typeof(MetroCreateTestCertificateWindow)); + MetroCreateTestCertificateWindow metroCreateTestCertificateWindow = (array.Length <= 0) ? ScriptableObject.CreateInstance() : array[0]; + metroCreateTestCertificateWindow.path = Path.Combine(Application.dataPath, "MetroTestCertificate.pfx").Replace('\\', '/'); + metroCreateTestCertificateWindow.publisher = publisher; + metroCreateTestCertificateWindow.password = string.Empty; + metroCreateTestCertificateWindow.confirm = metroCreateTestCertificateWindow.password; + metroCreateTestCertificateWindow.message = ((!File.Exists(metroCreateTestCertificateWindow.path)) ? GUIContent.none : EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreateOverwrite")); + metroCreateTestCertificateWindow.messageStyle = new GUIStyle(GUI.skin.label); + metroCreateTestCertificateWindow.messageStyle.fontStyle = FontStyle.Italic; + metroCreateTestCertificateWindow.focus = "publisher"; + if (array.Length > 0) + { + metroCreateTestCertificateWindow.Focus(); + } + else + { + metroCreateTestCertificateWindow.title = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreateTitle").text; + metroCreateTestCertificateWindow.position = new Rect(100f, 100f, 350f, 140f); + metroCreateTestCertificateWindow.minSize = new Vector2(metroCreateTestCertificateWindow.position.width, metroCreateTestCertificateWindow.position.height); + metroCreateTestCertificateWindow.maxSize = metroCreateTestCertificateWindow.minSize; + metroCreateTestCertificateWindow.ShowUtility(); + } + } + public void OnGUI() + { + Event current = Event.current; + bool flag = false; + bool flag2 = false; + if (current.type == EventType.KeyDown) + { + flag = (current.keyCode == KeyCode.Escape); + flag2 = (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter); + } + using (HorizontalLayout.DoLayout()) + { + GUILayout.Space(10f); + using (VerticalLayout.DoLayout()) + { + GUILayout.FlexibleSpace(); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePublisher"), new GUILayoutOption[] + { + MetroCreateTestCertificateWindow.kLabelWidth + }); + GUI.SetNextControlName("publisher"); + this.publisher = GUILayout.TextField(this.publisher, new GUILayoutOption[0]); + } + GUILayout.Space(5f); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePassword"), new GUILayoutOption[] + { + MetroCreateTestCertificateWindow.kLabelWidth + }); + GUI.SetNextControlName("password"); + this.password = GUILayout.PasswordField(this.password, '●', new GUILayoutOption[0]); + } + GUILayout.Space(5f); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreateConfirmPassword"), new GUILayoutOption[] + { + MetroCreateTestCertificateWindow.kLabelWidth + }); + GUI.SetNextControlName("confirm"); + this.confirm = GUILayout.PasswordField(this.confirm, '●', new GUILayoutOption[0]); + } + GUILayout.Space(10f); + using (HorizontalLayout.DoLayout()) + { + GUILayout.Label(this.message, this.messageStyle, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreateButton"), new GUILayoutOption[] + { + MetroCreateTestCertificateWindow.kButtonWidth + }) || flag2) + { + this.message = GUIContent.none; + if (string.IsNullOrEmpty(this.publisher)) + { + this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePublisherMissing"); + this.focus = "publisher"; + } + else + { + if (this.password != this.confirm) + { + if (string.IsNullOrEmpty(this.confirm)) + { + this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreateConfirmPasswordConfirm"); + this.focus = "confirm"; + } + else + { + this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePasswordMismatch"); + this.password = string.Empty; + this.confirm = this.password; + this.focus = "password"; + } + } + else + { + try + { + EditorUtility.MetroCreateTestCertificate(this.path, this.publisher, this.password, true); + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + if (!PlayerSettings.Metro.SetCertificate(FileUtil.GetProjectRelativePath(this.path), this.password)) + { + this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePasswordInvalid"); + } + flag = true; + } + catch (UnityException ex) + { + Debug.LogError(ex.Message); + } + } + } + } + } + GUILayout.FlexibleSpace(); + } + GUILayout.Space(10f); + } + if (flag) + { + base.Close(); + } + else + { + if (this.focus != null) + { + EditorGUI.FocusTextInControl(this.focus); + this.focus = null; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MetroSDK.cs b/UnityEditor/UnityEditor/MetroSDK.cs new file mode 100644 index 00000000..b3d89a46 --- /dev/null +++ b/UnityEditor/UnityEditor/MetroSDK.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum MetroSDK + { + SDK80, + SDK81, + PhoneSDK81, + UniversalSDK81 + } +} diff --git a/UnityEditor/UnityEditor/MinMaxCurveState.cs b/UnityEditor/UnityEditor/MinMaxCurveState.cs new file mode 100644 index 00000000..b7222923 --- /dev/null +++ b/UnityEditor/UnityEditor/MinMaxCurveState.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal enum MinMaxCurveState + { + k_Scalar, + k_Curve, + k_TwoCurves, + k_TwoScalars + } +} diff --git a/UnityEditor/UnityEditor/MinMaxGradientState.cs b/UnityEditor/UnityEditor/MinMaxGradientState.cs new file mode 100644 index 00000000..c9396d38 --- /dev/null +++ b/UnityEditor/UnityEditor/MinMaxGradientState.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal enum MinMaxGradientState + { + k_Color, + k_Gradient, + k_RandomBetweenTwoColors, + k_RandomBetweenTwoGradients + } +} diff --git a/UnityEditor/UnityEditor/ModelImporter.cs b/UnityEditor/UnityEditor/ModelImporter.cs new file mode 100644 index 00000000..e251f168 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporter.cs @@ -0,0 +1,384 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public sealed class ModelImporter : AssetImporter + { + [Obsolete("Use importMaterials, materialName and materialSearch instead")] + public extern ModelImporterGenerateMaterials generateMaterials + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool importMaterials + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterMaterialName materialName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterMaterialSearch materialSearch + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float globalScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isUseFileUnitsSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool useFileUnits + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool importBlendShapes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool addCollider + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float normalSmoothingAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool splitTangentsAcrossSeams + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool swapUVChannels + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool generateSecondaryUV + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float secondaryUVAngleDistortion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float secondaryUVAreaDistortion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float secondaryUVHardAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float secondaryUVPackMargin + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterGenerateAnimations generateAnimations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern TakeInfo[] importedTakeInfos + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string[] transformPaths + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string[] referencedClips + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isReadable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool optimizeMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterTangentSpaceMode normalImportMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterTangentSpaceMode tangentImportMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bakeIK + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isBakeIKSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isTangentImportSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Use animationCompression instead", true)] + private bool reduceKeyframes + { + get + { + return false; + } + set + { + } + } + public extern ModelImporterMeshCompression meshCompression + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool importAnimation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool optimizeGameObjects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string[] extraExposedTransformPaths + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterAnimationCompression animationCompression + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float animationRotationError + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float animationPositionError + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float animationScaleError + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern WrapMode animationWrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ModelImporterAnimationType animationType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("splitAnimations has been deprecated please use clipAnimations instead.", true)] + public bool splitAnimations + { + get + { + return this.clipAnimations.Length != 0; + } + set + { + } + } + public extern ModelImporterClipAnimation[] clipAnimations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool isAssetOlderOr42 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateSkeletonPose(SkeletonBone[] skeletonBones, SerializedProperty serializedProperty); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateTransformMask(AvatarMask mask, SerializedProperty serializedProperty); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimationClip GetPreviewAnimationClipForTake(string takeName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string CalculateBestFittingPreviewGameObject(); + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterAnimationCompression.cs b/UnityEditor/UnityEditor/ModelImporterAnimationCompression.cs new file mode 100644 index 00000000..0594ae63 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterAnimationCompression.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterAnimationCompression + { + Off, + KeyframeReduction, + KeyframeReductionAndCompression, + Optimal + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterAnimationType.cs b/UnityEditor/UnityEditor/ModelImporterAnimationType.cs new file mode 100644 index 00000000..b7a248a8 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterAnimationType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterAnimationType + { + None, + Legacy, + Generic, + Human + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs b/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs new file mode 100644 index 00000000..21a85516 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs @@ -0,0 +1,273 @@ +using System; +using System.Runtime.InteropServices; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class ModelImporterClipAnimation + { + private string m_TakeName; + private string m_Name; + private float m_FirstFrame; + private float m_LastFrame; + private int m_WrapMode; + private int m_Loop; + private float m_OrientationOffsetY; + private float m_Level; + private float m_CycleOffset; + private int m_LoopTime; + private int m_LoopBlend; + private int m_LoopBlendOrientation; + private int m_LoopBlendPositionY; + private int m_LoopBlendPositionXZ; + private int m_KeepOriginalOrientation; + private int m_KeepOriginalPositionY; + private int m_KeepOriginalPositionXZ; + private int m_HeightFromFeet; + private int m_Mirror; + private int m_MaskType; + private AvatarMask m_MaskSource; + public string takeName + { + get + { + return this.m_TakeName; + } + set + { + this.m_TakeName = value; + } + } + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public float firstFrame + { + get + { + return this.m_FirstFrame; + } + set + { + this.m_FirstFrame = value; + } + } + public float lastFrame + { + get + { + return this.m_LastFrame; + } + set + { + this.m_LastFrame = value; + } + } + public WrapMode wrapMode + { + get + { + return (WrapMode)this.m_WrapMode; + } + set + { + this.m_WrapMode = (int)value; + } + } + public bool loop + { + get + { + return this.m_Loop != 0; + } + set + { + this.m_Loop = ((!value) ? 0 : 1); + } + } + public float rotationOffset + { + get + { + return this.m_OrientationOffsetY; + } + set + { + this.m_OrientationOffsetY = value; + } + } + public float heightOffset + { + get + { + return this.m_Level; + } + set + { + this.m_Level = value; + } + } + public float cycleOffset + { + get + { + return this.m_CycleOffset; + } + set + { + this.m_CycleOffset = value; + } + } + public bool loopTime + { + get + { + return this.m_LoopTime != 0; + } + set + { + this.m_LoopTime = ((!value) ? 0 : 1); + } + } + public bool loopPose + { + get + { + return this.m_LoopBlend != 0; + } + set + { + this.m_LoopBlend = ((!value) ? 0 : 1); + } + } + public bool lockRootRotation + { + get + { + return this.m_LoopBlendOrientation != 0; + } + set + { + this.m_LoopBlendOrientation = ((!value) ? 0 : 1); + } + } + public bool lockRootHeightY + { + get + { + return this.m_LoopBlendPositionY != 0; + } + set + { + this.m_LoopBlendPositionY = ((!value) ? 0 : 1); + } + } + public bool lockRootPositionXZ + { + get + { + return this.m_LoopBlendPositionXZ != 0; + } + set + { + this.m_LoopBlendPositionXZ = ((!value) ? 0 : 1); + } + } + public bool keepOriginalOrientation + { + get + { + return this.m_KeepOriginalOrientation != 0; + } + set + { + this.m_KeepOriginalOrientation = ((!value) ? 0 : 1); + } + } + public bool keepOriginalPositionY + { + get + { + return this.m_KeepOriginalPositionY != 0; + } + set + { + this.m_KeepOriginalPositionY = ((!value) ? 0 : 1); + } + } + public bool keepOriginalPositionXZ + { + get + { + return this.m_KeepOriginalPositionXZ != 0; + } + set + { + this.m_KeepOriginalPositionXZ = ((!value) ? 0 : 1); + } + } + public bool heightFromFeet + { + get + { + return this.m_HeightFromFeet != 0; + } + set + { + this.m_HeightFromFeet = ((!value) ? 0 : 1); + } + } + public bool mirror + { + get + { + return this.m_Mirror != 0; + } + set + { + this.m_Mirror = ((!value) ? 0 : 1); + } + } + public ClipAnimationMaskType maskType + { + get + { + return (ClipAnimationMaskType)this.m_MaskType; + } + set + { + this.m_MaskType = (int)value; + } + } + public AvatarMask maskSource + { + get + { + return this.m_MaskSource; + } + set + { + this.m_MaskSource = value; + } + } + public override bool Equals(object o) + { + ModelImporterClipAnimation modelImporterClipAnimation = o as ModelImporterClipAnimation; + return modelImporterClipAnimation != null && this.takeName == modelImporterClipAnimation.takeName && this.name == modelImporterClipAnimation.name && this.firstFrame == modelImporterClipAnimation.firstFrame && this.lastFrame == modelImporterClipAnimation.lastFrame && this.m_WrapMode == modelImporterClipAnimation.m_WrapMode && this.m_Loop == modelImporterClipAnimation.m_Loop && this.loopPose == modelImporterClipAnimation.loopPose && this.lockRootRotation == modelImporterClipAnimation.lockRootRotation && this.lockRootHeightY == modelImporterClipAnimation.lockRootHeightY && this.lockRootPositionXZ == modelImporterClipAnimation.lockRootPositionXZ && this.mirror == modelImporterClipAnimation.mirror && this.maskType == modelImporterClipAnimation.maskType && this.maskSource == modelImporterClipAnimation.maskSource; + } + public override int GetHashCode() + { + return this.name.GetHashCode(); + } + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterClipEditor.cs b/UnityEditor/UnityEditor/ModelImporterClipEditor.cs new file mode 100644 index 00000000..8de6c85d --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterClipEditor.cs @@ -0,0 +1,628 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ModelImporterClipEditor : AssetImporterInspector + { + private class Styles + { + public GUIContent ImportAnimations = EditorGUIUtility.TextContent("ModelImporterImportAnimations"); + public GUIStyle numberStyle = new GUIStyle(EditorStyles.label); + public GUIContent AnimWrapModeLabel = EditorGUIUtility.TextContent("ModelImporterAnimWrapMode"); + public GUIContent[] AnimWrapModeOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterAnimWrapModeDefault"), + EditorGUIUtility.TextContent("ModelImporterAnimWrapModeOnce"), + EditorGUIUtility.TextContent("ModelImporterAnimWrapModeLoop"), + EditorGUIUtility.TextContent("ModelImporterAnimWrapModePingPong"), + EditorGUIUtility.TextContent("ModelImporterAnimWrapModeClampForever") + }; + public GUIContent BakeIK = EditorGUIUtility.TextContent("ModelImporterAnimBakeIK"); + public GUIContent AnimCompressionLabel = EditorGUIUtility.TextContent("ModelImporterAnimComprSetting"); + public GUIContent[] AnimCompressionOptLegacy = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingOff"), + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingReduction"), + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingReductionAndCompression") + }; + public GUIContent[] AnimCompressionOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingOff"), + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingReduction"), + EditorGUIUtility.TextContent("ModelImporterAnimComprSettingOptimal") + }; + public GUIContent AnimRotationErrorLabel = EditorGUIUtility.TextContent("ModelImporterAnimComprRotationError"); + public GUIContent AnimPositionErrorLabel = EditorGUIUtility.TextContent("ModelImporterAnimComprPositionError"); + public GUIContent AnimScaleErrorLabel = EditorGUIUtility.TextContent("ModelImporterAnimComprScaleError"); + public GUIContent AnimationCompressionHelp = EditorGUIUtility.TextContent("ModelImporterAnimComprHelp"); + public GUIContent clipMultiEditInfo = new GUIContent("Multi-object editing of clips not supported."); + public GUIContent updateMuscleDefinitionFromSource = EditorGUIUtility.TextContent("ModelImporterRigUpdateMuscleDefinitionFromSource"); + public GUIContent MotionSetting = EditorGUIUtility.TextContent("ModelImporterMotionSetting"); + public GUIContent MotionNode = EditorGUIUtility.TextContent("ModelImporterMotionNode"); + public Styles() + { + this.numberStyle.alignment = TextAnchor.UpperRight; + } + } + private const int kFrameColumnWidth = 45; + private AnimationClipEditor m_AnimationClipEditor; + public int m_SelectedClipIndexDoNotUseDirectly = -1; + private SerializedObject m_DefaultClipsSerializedObject; + private SerializedProperty m_AnimationType; + private SerializedProperty m_ImportAnimation; + private SerializedProperty m_ClipAnimations; + private SerializedProperty m_BakeSimulation; + private SerializedProperty m_AnimationCompression; + private SerializedProperty m_AnimationRotationError; + private SerializedProperty m_AnimationPositionError; + private SerializedProperty m_AnimationScaleError; + private SerializedProperty m_AnimationWrapMode; + private SerializedProperty m_LegacyGenerateAnimations; + private SerializedProperty m_MotionNodeName; + private GUIContent[] m_MotionNodeList; + private bool motionNodeFoldout; + private ReorderableList m_ClipList; + private static ModelImporterClipEditor.Styles styles; + private ModelImporter singleImporter + { + get + { + return base.targets[0] as ModelImporter; + } + } + public int selectedClipIndex + { + get + { + return this.m_SelectedClipIndexDoNotUseDirectly; + } + set + { + this.m_SelectedClipIndexDoNotUseDirectly = value; + if (this.m_ClipList != null) + { + this.m_ClipList.index = value; + } + } + } + public int motionNodeIndex + { + get; + set; + } + private ModelImporterAnimationType animationType + { + get + { + return (ModelImporterAnimationType)this.m_AnimationType.intValue; + } + set + { + this.m_AnimationType.intValue = (int)value; + } + } + private ModelImporterGenerateAnimations legacyGenerateAnimations + { + get + { + return (ModelImporterGenerateAnimations)this.m_LegacyGenerateAnimations.intValue; + } + set + { + this.m_LegacyGenerateAnimations.intValue = (int)value; + } + } + public void OnEnable() + { + this.m_ClipAnimations = base.serializedObject.FindProperty("m_ClipAnimations"); + this.m_AnimationType = base.serializedObject.FindProperty("m_AnimationType"); + this.m_LegacyGenerateAnimations = base.serializedObject.FindProperty("m_LegacyGenerateAnimations"); + this.m_ImportAnimation = base.serializedObject.FindProperty("m_ImportAnimation"); + this.m_BakeSimulation = base.serializedObject.FindProperty("m_BakeSimulation"); + this.m_AnimationCompression = base.serializedObject.FindProperty("m_AnimationCompression"); + this.m_AnimationRotationError = base.serializedObject.FindProperty("m_AnimationRotationError"); + this.m_AnimationPositionError = base.serializedObject.FindProperty("m_AnimationPositionError"); + this.m_AnimationScaleError = base.serializedObject.FindProperty("m_AnimationScaleError"); + this.m_AnimationWrapMode = base.serializedObject.FindProperty("m_AnimationWrapMode"); + if (this.m_ClipAnimations.arraySize == 0) + { + this.SetupDefaultClips(); + } + this.ValidateClipSelectionIndex(); + if (this.m_AnimationClipEditor != null && this.selectedClipIndex >= 0) + { + this.SyncClipEditor(); + } + if (this.selectedClipIndex == -1 && this.m_ClipAnimations.arraySize != 0) + { + this.SelectClip(0); + } + this.m_MotionNodeName = base.serializedObject.FindProperty("m_MotionNodeName"); + string[] transformPaths = this.singleImporter.transformPaths; + this.m_MotionNodeList = new GUIContent[transformPaths.Length]; + for (int i = 0; i < transformPaths.Length; i++) + { + this.m_MotionNodeList[i] = new GUIContent(transformPaths[i]); + } + if (this.m_MotionNodeList.Length > 0) + { + this.m_MotionNodeList[0] = new GUIContent("None"); + } + this.motionNodeIndex = ArrayUtility.FindIndex(this.m_MotionNodeList, (GUIContent content) => content.text == this.m_MotionNodeName.stringValue); + this.motionNodeIndex = ((this.motionNodeIndex >= 1) ? this.motionNodeIndex : 0); + } + private void SyncClipEditor() + { + if (this.m_AnimationClipEditor == null) + { + return; + } + this.m_AnimationClipEditor.ShowRange(this.GetAnimationClipInfoAtIndex(this.selectedClipIndex)); + this.m_AnimationClipEditor.referenceTransformPaths = this.singleImporter.transformPaths; + } + private void SetupDefaultClips() + { + this.m_DefaultClipsSerializedObject = new SerializedObject(this.target); + this.m_ClipAnimations = this.m_DefaultClipsSerializedObject.FindProperty("m_ClipAnimations"); + this.m_AnimationType = this.m_DefaultClipsSerializedObject.FindProperty("m_AnimationType"); + this.m_ClipAnimations.arraySize = 0; + TakeInfo[] importedTakeInfos = this.singleImporter.importedTakeInfos; + for (int i = 0; i < importedTakeInfos.Length; i++) + { + TakeInfo takeInfo = importedTakeInfos[i]; + this.AddClip(takeInfo); + } + } + private void PatchDefaultClipTakeNamesToSplitClipNames() + { + TakeInfo[] importedTakeInfos = this.singleImporter.importedTakeInfos; + for (int i = 0; i < importedTakeInfos.Length; i++) + { + TakeInfo takeInfo = importedTakeInfos[i]; + PatchImportSettingRecycleID.Patch(base.serializedObject, 74, takeInfo.name, takeInfo.defaultClipName); + } + } + private void TransferDefaultClipsToCustomClips() + { + if (this.m_DefaultClipsSerializedObject == null) + { + return; + } + if (base.serializedObject.FindProperty("m_ClipAnimations").arraySize != 0) + { + Debug.LogError("Transferring default clips failed, target already has clips"); + } + base.serializedObject.CopyFromSerializedProperty(this.m_ClipAnimations); + this.m_ClipAnimations = base.serializedObject.FindProperty("m_ClipAnimations"); + this.m_DefaultClipsSerializedObject = null; + this.PatchDefaultClipTakeNamesToSplitClipNames(); + this.SyncClipEditor(); + } + private void ValidateClipSelectionIndex() + { + if (this.selectedClipIndex > this.m_ClipAnimations.arraySize - 1) + { + this.selectedClipIndex = -1; + } + } + public void OnDestroy() + { + UnityEngine.Object.DestroyImmediate(this.m_AnimationClipEditor); + } + internal override void ResetValues() + { + base.ResetValues(); + this.m_ClipAnimations = base.serializedObject.FindProperty("m_ClipAnimations"); + this.m_AnimationType = base.serializedObject.FindProperty("m_AnimationType"); + this.m_DefaultClipsSerializedObject = null; + if (this.m_ClipAnimations.arraySize == 0) + { + this.SetupDefaultClips(); + } + this.ValidateClipSelectionIndex(); + this.UpdateList(); + this.SelectClip(this.selectedClipIndex); + } + private void AnimationClipGUI() + { + this.AnimationSettings(); + Profiler.BeginSample("Clip inspector"); + EditorGUILayout.Space(); + if (base.targets.Length == 1) + { + this.AnimationSplitTable(); + } + else + { + GUILayout.Label(ModelImporterClipEditor.styles.clipMultiEditInfo, EditorStyles.helpBox, new GUILayoutOption[0]); + } + Profiler.EndSample(); + if (InternalEditorUtility.HasPro()) + { + this.RootMotionNodeSettings(); + } + } + public override void OnInspectorGUI() + { + if (ModelImporterClipEditor.styles == null) + { + ModelImporterClipEditor.styles = new ModelImporterClipEditor.Styles(); + } + EditorGUI.BeginDisabledGroup(this.singleImporter.animationType == ModelImporterAnimationType.None); + EditorGUILayout.PropertyField(this.m_ImportAnimation, ModelImporterClipEditor.styles.ImportAnimations, new GUILayoutOption[0]); + if (this.m_ImportAnimation.boolValue && !this.m_ImportAnimation.hasMultipleDifferentValues) + { + bool flag = base.targets.Length == 1 && this.singleImporter.importedTakeInfos.Length == 0; + if (this.IsDeprecatedMultiAnimationRootImport()) + { + EditorGUILayout.HelpBox("Animation data was imported using a deprecated Generation option in the Rig tab. Please switch to a non-deprecated import mode in the Rig tab to be able to edit the animation import settings.", MessageType.Info); + } + else + { + if (flag) + { + if (base.serializedObject.hasModifiedProperties) + { + EditorGUILayout.HelpBox("The animations settings can be edited after clicking Apply.", MessageType.Info); + } + else + { + EditorGUILayout.HelpBox("No animation data available in this model.", MessageType.Info); + } + } + else + { + if (this.m_AnimationType.hasMultipleDifferentValues) + { + EditorGUILayout.HelpBox("The rigs of the selected models have different animation types.", MessageType.Info); + } + else + { + if (this.animationType == ModelImporterAnimationType.None) + { + EditorGUILayout.HelpBox("The rigs is not setup to handle animation. Edit the settings in the Rig tab.", MessageType.Info); + } + else + { + if (this.m_ImportAnimation.boolValue && !this.m_ImportAnimation.hasMultipleDifferentValues) + { + this.AnimationClipGUI(); + } + } + } + } + } + } + EditorGUI.EndDisabledGroup(); + base.ApplyRevertGUI(); + } + private void AnimationSettings() + { + EditorGUILayout.Space(); + bool flag = true; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ModelImporter modelImporter = (ModelImporter)targets[i]; + if (!modelImporter.isBakeIKSupported) + { + flag = false; + } + } + EditorGUI.BeginDisabledGroup(!flag); + EditorGUILayout.PropertyField(this.m_BakeSimulation, ModelImporterClipEditor.styles.BakeIK, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (this.animationType == ModelImporterAnimationType.Legacy) + { + EditorGUI.showMixedValue = this.m_AnimationWrapMode.hasMultipleDifferentValues; + EditorGUILayout.Popup(this.m_AnimationWrapMode, ModelImporterClipEditor.styles.AnimWrapModeOpt, ModelImporterClipEditor.styles.AnimWrapModeLabel, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + int[] optionValues = new int[] + { + 0, + 1, + 2 + }; + EditorGUILayout.IntPopup(this.m_AnimationCompression, ModelImporterClipEditor.styles.AnimCompressionOptLegacy, optionValues, ModelImporterClipEditor.styles.AnimCompressionLabel, new GUILayoutOption[0]); + } + else + { + int[] optionValues2 = new int[] + { + 0, + 1, + 3 + }; + EditorGUILayout.IntPopup(this.m_AnimationCompression, ModelImporterClipEditor.styles.AnimCompressionOpt, optionValues2, ModelImporterClipEditor.styles.AnimCompressionLabel, new GUILayoutOption[0]); + } + if (this.m_AnimationCompression.intValue > 0) + { + EditorGUILayout.PropertyField(this.m_AnimationRotationError, ModelImporterClipEditor.styles.AnimRotationErrorLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AnimationPositionError, ModelImporterClipEditor.styles.AnimPositionErrorLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AnimationScaleError, ModelImporterClipEditor.styles.AnimScaleErrorLabel, new GUILayoutOption[0]); + GUILayout.Label(ModelImporterClipEditor.styles.AnimationCompressionHelp, EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private void RootMotionNodeSettings() + { + if (this.animationType == ModelImporterAnimationType.Human) + { + this.motionNodeFoldout = EditorGUILayout.Foldout(this.motionNodeFoldout, ModelImporterClipEditor.styles.MotionSetting); + if (this.motionNodeFoldout) + { + EditorGUI.BeginChangeCheck(); + this.motionNodeIndex = EditorGUILayout.Popup(ModelImporterClipEditor.styles.MotionNode, this.motionNodeIndex, this.m_MotionNodeList, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (this.motionNodeIndex > 0 && this.motionNodeIndex < this.m_MotionNodeList.Length) + { + this.m_MotionNodeName.stringValue = this.m_MotionNodeList[this.motionNodeIndex].text; + } + else + { + this.m_MotionNodeName.stringValue = string.Empty; + } + } + } + } + } + private void SelectClip(int selected) + { + if (EditorGUI.s_DelayedTextEditor != null && Event.current != null) + { + EditorGUI.s_DelayedTextEditor.EndGUI(Event.current.type); + } + UnityEngine.Object.DestroyImmediate(this.m_AnimationClipEditor); + this.m_AnimationClipEditor = null; + this.selectedClipIndex = selected; + if (this.selectedClipIndex < 0 || this.selectedClipIndex >= this.m_ClipAnimations.arraySize) + { + this.selectedClipIndex = -1; + return; + } + AnimationClipInfoProperties animationClipInfoAtIndex = this.GetAnimationClipInfoAtIndex(selected); + AnimationClip previewAnimationClipForTake = this.singleImporter.GetPreviewAnimationClipForTake(animationClipInfoAtIndex.takeName); + if (previewAnimationClipForTake != null) + { + this.m_AnimationClipEditor = (AnimationClipEditor)Editor.CreateEditor(previewAnimationClipForTake); + this.SyncClipEditor(); + } + } + private void UpdateList() + { + if (this.m_ClipList == null) + { + return; + } + List list = new List(); + for (int i = 0; i < this.m_ClipAnimations.arraySize; i++) + { + list.Add(this.GetAnimationClipInfoAtIndex(i)); + } + this.m_ClipList.list = list; + } + private void AddClipInList(ReorderableList list) + { + if (this.m_DefaultClipsSerializedObject != null) + { + this.TransferDefaultClipsToCustomClips(); + } + this.AddClip(this.singleImporter.importedTakeInfos[0]); + this.UpdateList(); + this.SelectClip(list.list.Count - 1); + } + private void RemoveClipInList(ReorderableList list) + { + this.TransferDefaultClipsToCustomClips(); + this.RemoveClip(list.index); + this.UpdateList(); + this.SelectClip(Mathf.Min(list.index, list.count - 1)); + } + private void SelectClipInList(ReorderableList list) + { + this.SelectClip(list.index); + } + private void DrawClipElement(Rect rect, int index, bool selected, bool focused) + { + AnimationClipInfoProperties animationClipInfoAtIndex = this.GetAnimationClipInfoAtIndex(index); + rect.xMax -= 90f; + GUI.Label(rect, animationClipInfoAtIndex.name, EditorStyles.label); + rect.x = rect.xMax; + rect.width = 45f; + GUI.Label(rect, animationClipInfoAtIndex.firstFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); + rect.x = rect.xMax; + GUI.Label(rect, animationClipInfoAtIndex.lastFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); + } + private void DrawClipHeader(Rect rect) + { + rect.xMax -= 90f; + GUI.Label(rect, "Clips", EditorStyles.label); + rect.x = rect.xMax; + rect.width = 45f; + GUI.Label(rect, "Start", ModelImporterClipEditor.styles.numberStyle); + rect.x = rect.xMax; + GUI.Label(rect, "End", ModelImporterClipEditor.styles.numberStyle); + } + private void AnimationSplitTable() + { + if (this.m_ClipList == null) + { + this.m_ClipList = new ReorderableList(new List(), typeof(string), false, true, true, true); + this.m_ClipList.onAddCallback = new ReorderableList.AddCallbackDelegate(this.AddClipInList); + this.m_ClipList.onSelectCallback = new ReorderableList.SelectCallbackDelegate(this.SelectClipInList); + this.m_ClipList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveClipInList); + this.m_ClipList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawClipElement); + this.m_ClipList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawClipHeader); + this.m_ClipList.elementHeight = 16f; + this.UpdateList(); + this.m_ClipList.index = this.selectedClipIndex; + } + this.m_ClipList.DoLayoutList(); + EditorGUI.BeginChangeCheck(); + AnimationClipInfoProperties selectedClipInfo = this.GetSelectedClipInfo(); + if (selectedClipInfo == null) + { + return; + } + if (this.m_AnimationClipEditor != null && this.selectedClipIndex != -1) + { + GUILayout.Space(5f); + AnimationClip animationClip = this.m_AnimationClipEditor.target as AnimationClip; + if (animationClip.isAnimatorMotion) + { + this.GetSelectedClipInfo().AssignToPreviewClip(animationClip); + } + TakeInfo[] importedTakeInfos = this.singleImporter.importedTakeInfos; + string[] array = new string[importedTakeInfos.Length]; + for (int i = 0; i < importedTakeInfos.Length; i++) + { + array[i] = importedTakeInfos[i].name; + } + EditorGUI.BeginChangeCheck(); + string name = selectedClipInfo.name; + int num = ArrayUtility.IndexOf(array, selectedClipInfo.takeName); + this.m_AnimationClipEditor.takeNames = array; + this.m_AnimationClipEditor.takeIndex = ArrayUtility.IndexOf(array, selectedClipInfo.takeName); + this.m_AnimationClipEditor.DrawHeader(); + if (EditorGUI.EndChangeCheck()) + { + if (selectedClipInfo.name != name) + { + this.TransferDefaultClipsToCustomClips(); + PatchImportSettingRecycleID.Patch(base.serializedObject, 74, name, selectedClipInfo.name); + } + int takeIndex = this.m_AnimationClipEditor.takeIndex; + if (takeIndex != -1 && takeIndex != num) + { + selectedClipInfo.name = this.MakeUniqueClipName(array[takeIndex], -1); + this.SetupTakeNameAndFrames(selectedClipInfo, importedTakeInfos[takeIndex]); + GUIUtility.keyboardControl = 0; + this.SelectClip(this.selectedClipIndex); + animationClip = (this.m_AnimationClipEditor.target as AnimationClip); + } + } + this.m_AnimationClipEditor.OnInspectorGUI(); + if (animationClip.isAnimatorMotion) + { + this.GetSelectedClipInfo().ExtractFromPreviewClip(animationClip); + } + } + if (EditorGUI.EndChangeCheck()) + { + this.TransferDefaultClipsToCustomClips(); + } + } + public override bool HasPreviewGUI() + { + return this.m_AnimationClipEditor != null && this.m_AnimationClipEditor.HasPreviewGUI(); + } + public override void OnPreviewSettings() + { + if (this.m_AnimationClipEditor != null) + { + this.m_AnimationClipEditor.OnPreviewSettings(); + } + } + private bool IsDeprecatedMultiAnimationRootImport() + { + return this.animationType == ModelImporterAnimationType.Legacy && (this.legacyGenerateAnimations == ModelImporterGenerateAnimations.InOriginalRoots || this.legacyGenerateAnimations == ModelImporterGenerateAnimations.InNodes); + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + if (this.m_AnimationClipEditor) + { + this.m_AnimationClipEditor.OnInteractivePreviewGUI(r, background); + } + } + private AnimationClipInfoProperties GetAnimationClipInfoAtIndex(int index) + { + return new AnimationClipInfoProperties(this.m_ClipAnimations.GetArrayElementAtIndex(index)); + } + private AnimationClipInfoProperties GetSelectedClipInfo() + { + if (this.selectedClipIndex >= 0 && this.selectedClipIndex < this.m_ClipAnimations.arraySize) + { + return this.GetAnimationClipInfoAtIndex(this.selectedClipIndex); + } + return null; + } + private string MakeUniqueClipName(string name, int row) + { + string text = name; + int num = 0; + int i; + do + { + for (i = 0; i < this.m_ClipAnimations.arraySize; i++) + { + AnimationClipInfoProperties animationClipInfoAtIndex = this.GetAnimationClipInfoAtIndex(i); + if (text == animationClipInfoAtIndex.name && row != i) + { + text = name + num.ToString(); + num++; + break; + } + } + } + while (i != this.m_ClipAnimations.arraySize); + return text; + } + private void RemoveClip(int index) + { + this.m_ClipAnimations.DeleteArrayElementAtIndex(index); + if (this.m_ClipAnimations.arraySize == 0) + { + this.SetupDefaultClips(); + this.m_ImportAnimation.boolValue = false; + } + } + private void SetupTakeNameAndFrames(AnimationClipInfoProperties info, TakeInfo takeInfo) + { + info.takeName = takeInfo.name; + info.firstFrame = (float)((int)Mathf.Round(takeInfo.bakeStartTime * takeInfo.sampleRate)); + info.lastFrame = (float)((int)Mathf.Round(takeInfo.bakeStopTime * takeInfo.sampleRate)); + } + private void AddClip(TakeInfo takeInfo) + { + this.m_ClipAnimations.InsertArrayElementAtIndex(this.m_ClipAnimations.arraySize); + AnimationClipInfoProperties animationClipInfoAtIndex = this.GetAnimationClipInfoAtIndex(this.m_ClipAnimations.arraySize - 1); + animationClipInfoAtIndex.name = this.MakeUniqueClipName(takeInfo.defaultClipName, -1); + this.SetupTakeNameAndFrames(animationClipInfoAtIndex, takeInfo); + animationClipInfoAtIndex.wrapMode = 0; + animationClipInfoAtIndex.loop = false; + animationClipInfoAtIndex.orientationOffsetY = 0f; + animationClipInfoAtIndex.level = 0f; + animationClipInfoAtIndex.cycleOffset = 0f; + animationClipInfoAtIndex.loopTime = false; + animationClipInfoAtIndex.loopBlend = false; + animationClipInfoAtIndex.loopBlendOrientation = false; + animationClipInfoAtIndex.loopBlendPositionY = false; + animationClipInfoAtIndex.loopBlendPositionXZ = false; + animationClipInfoAtIndex.keepOriginalOrientation = false; + animationClipInfoAtIndex.keepOriginalPositionY = true; + animationClipInfoAtIndex.keepOriginalPositionXZ = false; + animationClipInfoAtIndex.heightFromFeet = false; + animationClipInfoAtIndex.mirror = false; + animationClipInfoAtIndex.maskType = ClipAnimationMaskType.CreateFromThisModel; + AvatarMask avatarMask = new AvatarMask(); + string[] array = null; + SerializedObject serializedObject = animationClipInfoAtIndex.maskTypeProperty.serializedObject; + ModelImporter modelImporter = serializedObject.targetObject as ModelImporter; + if (this.animationType == ModelImporterAnimationType.Human && !modelImporter.isAssetOlderOr42) + { + array = AvatarMaskUtility.GetAvatarHumanTransform(serializedObject, modelImporter.transformPaths); + if (array == null) + { + return; + } + } + AvatarMaskUtility.UpdateTransformMask(avatarMask, modelImporter.transformPaths, array); + animationClipInfoAtIndex.MaskToClip(avatarMask); + animationClipInfoAtIndex.ClearEvents(); + animationClipInfoAtIndex.ClearCurves(); + UnityEngine.Object.DestroyImmediate(avatarMask); + } + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterEditor.cs b/UnityEditor/UnityEditor/ModelImporterEditor.cs new file mode 100644 index 00000000..6adcf9ee --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterEditor.cs @@ -0,0 +1,41 @@ +using System; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(ModelImporter))] + internal class ModelImporterEditor : AssetImporterTabbedEditor + { + internal override bool showImportedObject + { + get + { + return base.activeEditor is ModelImporterModelEditor; + } + } + protected override bool useAssetDrawPreview + { + get + { + return false; + } + } + internal override void OnEnable() + { + if (this.m_SubEditorTypes == null) + { + this.m_SubEditorTypes = new Type[] + { + typeof(ModelImporterModelEditor), + typeof(ModelImporterRigEditor), + typeof(ModelImporterClipEditor) + }; + this.m_SubEditorNames = new string[] + { + "Model", + "Rig", + "Animations" + }; + } + base.OnEnable(); + } + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterGenerateAnimations.cs b/UnityEditor/UnityEditor/ModelImporterGenerateAnimations.cs new file mode 100644 index 00000000..1e594be8 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterGenerateAnimations.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterGenerateAnimations + { + None, + GenerateAnimations = 4, + InRoot = 3, + InOriginalRoots = 1, + InNodes + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterGenerateMaterials.cs b/UnityEditor/UnityEditor/ModelImporterGenerateMaterials.cs new file mode 100644 index 00000000..95eb5a7b --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterGenerateMaterials.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [Obsolete("Use ModelImporterMaterialName, ModelImporter.materialName and ModelImporter.importMaterials instead")] + public enum ModelImporterGenerateMaterials + { + None, + PerTexture, + PerSourceMaterial + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterMaterialName.cs b/UnityEditor/UnityEditor/ModelImporterMaterialName.cs new file mode 100644 index 00000000..f6b86302 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterMaterialName.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterMaterialName + { + BasedOnTextureName, + BasedOnMaterialName, + BasedOnModelNameAndMaterialName, + BasedOnTextureName_Or_ModelNameAndMaterialName + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterMaterialSearch.cs b/UnityEditor/UnityEditor/ModelImporterMaterialSearch.cs new file mode 100644 index 00000000..27c4f1a6 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterMaterialSearch.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterMaterialSearch + { + Local, + RecursiveUp, + Everywhere + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterMeshCompression.cs b/UnityEditor/UnityEditor/ModelImporterMeshCompression.cs new file mode 100644 index 00000000..162e6ca4 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterMeshCompression.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterMeshCompression + { + Off, + Low, + Medium, + High + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterModelEditor.cs b/UnityEditor/UnityEditor/ModelImporterModelEditor.cs new file mode 100644 index 00000000..1d3b6926 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterModelEditor.cs @@ -0,0 +1,334 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ModelImporterModelEditor : AssetImporterInspector + { + private class Styles + { + public GUIContent Meshes = EditorGUIUtility.TextContent("ModelImporter.Meshes"); + public GUIContent ScaleFactor = EditorGUIUtility.TextContent("ModelImporter.ScaleFactor"); + public GUIContent UseFileUnits = EditorGUIUtility.TextContent("ModelImporter.UseFileUnits"); + public GUIContent ImportBlendShapes = EditorGUIUtility.TextContent("ModelImporter.ImportBlendShapes"); + public GUIContent GenerateColliders = EditorGUIUtility.TextContent("ModelImporter.GenerateColliders"); + public GUIContent SwapUVChannels = EditorGUIUtility.TextContent("ModelImporter.SwapUVChannels"); + public GUIContent GenerateSecondaryUV = EditorGUIUtility.TextContent("ModelImporterGenerateSecondaryUV"); + public GUIContent GenerateSecondaryUVAdvanced = EditorGUIUtility.TextContent("ModelImporterGenerateSecondaryUVAdvanced"); + public GUIContent secondaryUVAngleDistortion = EditorGUIUtility.TextContent("ModelImporterSecondaryUVAngleDistortion"); + public GUIContent secondaryUVAreaDistortion = EditorGUIUtility.TextContent("ModelImporterSecondaryUVAreaDistortion"); + public GUIContent secondaryUVHardAngle = EditorGUIUtility.TextContent("ModelImporterSecondaryUVHardAngle"); + public GUIContent secondaryUVPackMargin = EditorGUIUtility.TextContent("ModelImporterSecondaryUVPackMargin"); + public GUIContent secondaryUVDefaults = EditorGUIUtility.TextContent("ModelImporterSecondaryUVDefaults"); + public GUIContent TangentSpace = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Title"); + public GUIContent TangentSpaceNormalLabel = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Normals"); + public GUIContent TangentSpaceTangentLabel = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Tangents"); + public GUIContent TangentSpaceOptionImport = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Options.Import"); + public GUIContent TangentSpaceOptionCalculate = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Options.Calculate"); + public GUIContent TangentSpaceOptionNone = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.Options.None"); + public GUIContent[] TangentSpaceModeOptLabelsAll; + public GUIContent[] TangentSpaceModeOptLabelsCalculate; + public GUIContent[] TangentSpaceModeOptLabelsNone; + public ModelImporterTangentSpaceMode[] TangentSpaceModeOptEnumsAll; + public ModelImporterTangentSpaceMode[] TangentSpaceModeOptEnumsCalculate; + public ModelImporterTangentSpaceMode[] TangentSpaceModeOptEnumsNone; + public GUIContent SmoothingAngle = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.NormalSmoothingAngle"); + public GUIContent SplitTangents = EditorGUIUtility.TextContent("ModelImporter.TangentSpace.SplitTangents"); + public GUIContent MeshCompressionLabel = new GUIContent("Mesh Compression"); + public GUIContent[] MeshCompressionOpt = new GUIContent[] + { + new GUIContent("Off"), + new GUIContent("Low"), + new GUIContent("Medium"), + new GUIContent("High") + }; + public GUIContent OptimizeMeshForGPU = EditorGUIUtility.TextContent("ModelImporterOptimizeMesh"); + public GUIContent IsReadable = EditorGUIUtility.TextContent("ModelImporterIsReadable"); + public GUIContent Materials = EditorGUIUtility.TextContent("ModelImporterMaterials"); + public GUIContent ImportMaterials = EditorGUIUtility.TextContent("ModelImporterMatImportMaterials"); + public GUIContent MaterialName = EditorGUIUtility.TextContent("ModelImporterMatMaterialName"); + public GUIContent MaterialNameTex = EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTex"); + public GUIContent MaterialNameMat = EditorGUIUtility.TextContent("ModelImporterMatMaterialNameMat"); + public GUIContent[] MaterialNameOptMain = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTex"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameMat"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameModelMat") + }; + public GUIContent[] MaterialNameOptAll = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTex"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameMat"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameModelMat"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTex_ModelMat") + }; + public GUIContent MaterialSearch = EditorGUIUtility.TextContent("ModelImporterMatMaterialSearch"); + public GUIContent[] MaterialSearchOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchLocal"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchRecursiveUp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchEverywhere") + }; + public GUIContent MaterialHelpStart = EditorGUIUtility.TextContent("ModelImporterMatHelpStart"); + public GUIContent MaterialHelpEnd = EditorGUIUtility.TextContent("ModelImporterMatHelpEnd"); + public GUIContent MaterialHelpDefault = EditorGUIUtility.TextContent("ModelImporterMatDefaultHelp"); + public GUIContent[] MaterialNameHelp = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTexHelp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameMatHelp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameModelMatHelp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialNameTex_ModelMatHelp") + }; + public GUIContent[] MaterialSearchHelp = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchLocalHelp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchRecursiveUpHelp"), + EditorGUIUtility.TextContent("ModelImporterMatMaterialSearchEverywhereHelp") + }; + public Styles() + { + this.TangentSpaceModeOptLabelsAll = new GUIContent[] + { + this.TangentSpaceOptionImport, + this.TangentSpaceOptionCalculate, + this.TangentSpaceOptionNone + }; + this.TangentSpaceModeOptLabelsCalculate = new GUIContent[] + { + this.TangentSpaceOptionCalculate, + this.TangentSpaceOptionNone + }; + this.TangentSpaceModeOptLabelsNone = new GUIContent[] + { + this.TangentSpaceOptionNone + }; + this.TangentSpaceModeOptEnumsAll = new ModelImporterTangentSpaceMode[] + { + ModelImporterTangentSpaceMode.Import, + ModelImporterTangentSpaceMode.Calculate, + ModelImporterTangentSpaceMode.None + }; + this.TangentSpaceModeOptEnumsCalculate = new ModelImporterTangentSpaceMode[] + { + ModelImporterTangentSpaceMode.Calculate, + ModelImporterTangentSpaceMode.None + }; + this.TangentSpaceModeOptEnumsNone = new ModelImporterTangentSpaceMode[] + { + ModelImporterTangentSpaceMode.None + }; + } + } + private bool m_SecondaryUVAdvancedOptions; + private bool m_ShowAllMaterialNameOptions = true; + private SerializedProperty m_ImportMaterials; + private SerializedProperty m_MaterialName; + private SerializedProperty m_MaterialSearch; + private SerializedProperty m_GlobalScale; + private SerializedProperty m_MeshCompression; + private SerializedProperty m_ImportBlendShapes; + private SerializedProperty m_AddColliders; + private SerializedProperty m_SwapUVChannels; + private SerializedProperty m_GenerateSecondaryUV; + private SerializedProperty m_UseFileUnits; + private SerializedProperty m_SecondaryUVAngleDistortion; + private SerializedProperty m_SecondaryUVAreaDistortion; + private SerializedProperty m_SecondaryUVHardAngle; + private SerializedProperty m_SecondaryUVPackMargin; + private SerializedProperty m_NormalSmoothAngle; + private SerializedProperty m_SplitTangentsAcrossSeams; + private SerializedProperty m_NormalImportMode; + private SerializedProperty m_TangentImportMode; + private SerializedProperty m_OptimizeMeshForGPU; + private SerializedProperty m_IsReadable; + private static ModelImporterModelEditor.Styles styles; + private void UpdateShowAllMaterialNameOptions() + { + this.m_MaterialName = base.serializedObject.FindProperty("m_MaterialName"); + this.m_ShowAllMaterialNameOptions = (this.m_MaterialName.intValue == 3); + } + private void OnEnable() + { + this.m_ImportMaterials = base.serializedObject.FindProperty("m_ImportMaterials"); + this.m_MaterialName = base.serializedObject.FindProperty("m_MaterialName"); + this.m_MaterialSearch = base.serializedObject.FindProperty("m_MaterialSearch"); + this.m_GlobalScale = base.serializedObject.FindProperty("m_GlobalScale"); + this.m_MeshCompression = base.serializedObject.FindProperty("m_MeshCompression"); + this.m_ImportBlendShapes = base.serializedObject.FindProperty("m_ImportBlendShapes"); + this.m_AddColliders = base.serializedObject.FindProperty("m_AddColliders"); + this.m_SwapUVChannels = base.serializedObject.FindProperty("swapUVChannels"); + this.m_GenerateSecondaryUV = base.serializedObject.FindProperty("generateSecondaryUV"); + this.m_UseFileUnits = base.serializedObject.FindProperty("m_UseFileUnits"); + this.m_SecondaryUVAngleDistortion = base.serializedObject.FindProperty("secondaryUVAngleDistortion"); + this.m_SecondaryUVAreaDistortion = base.serializedObject.FindProperty("secondaryUVAreaDistortion"); + this.m_SecondaryUVHardAngle = base.serializedObject.FindProperty("secondaryUVHardAngle"); + this.m_SecondaryUVPackMargin = base.serializedObject.FindProperty("secondaryUVPackMargin"); + this.m_NormalSmoothAngle = base.serializedObject.FindProperty("normalSmoothAngle"); + this.m_SplitTangentsAcrossSeams = base.serializedObject.FindProperty("splitTangentsAcrossUV"); + this.m_NormalImportMode = base.serializedObject.FindProperty("normalImportMode"); + this.m_TangentImportMode = base.serializedObject.FindProperty("tangentImportMode"); + this.m_OptimizeMeshForGPU = base.serializedObject.FindProperty("optimizeMeshForGPU"); + this.m_IsReadable = base.serializedObject.FindProperty("m_IsReadable"); + this.UpdateShowAllMaterialNameOptions(); + } + internal override void ResetValues() + { + base.ResetValues(); + this.UpdateShowAllMaterialNameOptions(); + } + internal override void Apply() + { + this.ScaleAvatar(); + base.Apply(); + this.UpdateShowAllMaterialNameOptions(); + } + public override void OnInspectorGUI() + { + if (ModelImporterModelEditor.styles == null) + { + ModelImporterModelEditor.styles = new ModelImporterModelEditor.Styles(); + } + GUILayout.Label(ModelImporterModelEditor.styles.Meshes, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_GlobalScale, ModelImporterModelEditor.styles.ScaleFactor, new GUILayoutOption[0]); + bool flag = true; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ModelImporter modelImporter = (ModelImporter)targets[i]; + if (!modelImporter.isUseFileUnitsSupported) + { + flag = false; + } + } + if (flag) + { + EditorGUILayout.PropertyField(this.m_UseFileUnits, ModelImporterModelEditor.styles.UseFileUnits, new GUILayoutOption[0]); + } + EditorGUILayout.Popup(this.m_MeshCompression, ModelImporterModelEditor.styles.MeshCompressionOpt, ModelImporterModelEditor.styles.MeshCompressionLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IsReadable, ModelImporterModelEditor.styles.IsReadable, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_OptimizeMeshForGPU, ModelImporterModelEditor.styles.OptimizeMeshForGPU, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ImportBlendShapes, ModelImporterModelEditor.styles.ImportBlendShapes, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AddColliders, ModelImporterModelEditor.styles.GenerateColliders, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SwapUVChannels, ModelImporterModelEditor.styles.SwapUVChannels, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_GenerateSecondaryUV, ModelImporterModelEditor.styles.GenerateSecondaryUV, new GUILayoutOption[0]); + if (this.m_GenerateSecondaryUV.boolValue) + { + EditorGUI.indentLevel++; + this.m_SecondaryUVAdvancedOptions = EditorGUILayout.Foldout(this.m_SecondaryUVAdvancedOptions, ModelImporterModelEditor.styles.GenerateSecondaryUVAdvanced, EditorStyles.foldout); + if (this.m_SecondaryUVAdvancedOptions) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.Slider(this.m_SecondaryUVHardAngle, 0f, 180f, ModelImporterModelEditor.styles.secondaryUVHardAngle, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_SecondaryUVPackMargin, 1f, 64f, ModelImporterModelEditor.styles.secondaryUVPackMargin, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_SecondaryUVAngleDistortion, 1f, 75f, ModelImporterModelEditor.styles.secondaryUVAngleDistortion, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_SecondaryUVAreaDistortion, 1f, 75f, ModelImporterModelEditor.styles.secondaryUVAreaDistortion, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_SecondaryUVHardAngle.floatValue = Mathf.Round(this.m_SecondaryUVHardAngle.floatValue); + this.m_SecondaryUVPackMargin.floatValue = Mathf.Round(this.m_SecondaryUVPackMargin.floatValue); + this.m_SecondaryUVAngleDistortion.floatValue = Mathf.Round(this.m_SecondaryUVAngleDistortion.floatValue); + this.m_SecondaryUVAreaDistortion.floatValue = Mathf.Round(this.m_SecondaryUVAreaDistortion.floatValue); + } + } + EditorGUI.indentLevel--; + } + GUILayout.Label(ModelImporterModelEditor.styles.TangentSpace, EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag2 = true; + UnityEngine.Object[] targets2 = base.targets; + for (int j = 0; j < targets2.Length; j++) + { + ModelImporter modelImporter2 = (ModelImporter)targets2[j]; + if (!modelImporter2.isTangentImportSupported) + { + flag2 = false; + } + } + EditorGUI.BeginChangeCheck(); + EditorGUILayout.Popup(this.m_NormalImportMode, ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsAll, ModelImporterModelEditor.styles.TangentSpaceNormalLabel, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_TangentImportMode.intValue = this.m_NormalImportMode.intValue; + if (!flag2 && this.m_TangentImportMode.intValue == 0) + { + this.m_TangentImportMode.intValue = 1; + } + } + GUIContent[] displayedOptions = ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsAll; + ModelImporterTangentSpaceMode[] array = ModelImporterModelEditor.styles.TangentSpaceModeOptEnumsAll; + if (this.m_NormalImportMode.intValue == 1 || !flag2) + { + displayedOptions = ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsCalculate; + array = ModelImporterModelEditor.styles.TangentSpaceModeOptEnumsCalculate; + } + else + { + if (this.m_NormalImportMode.intValue == 2) + { + displayedOptions = ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsNone; + array = ModelImporterModelEditor.styles.TangentSpaceModeOptEnumsNone; + } + } + EditorGUI.BeginDisabledGroup(this.m_NormalImportMode.intValue == 2); + int num = Array.IndexOf(array, (ModelImporterTangentSpaceMode)this.m_TangentImportMode.intValue); + EditorGUI.BeginChangeCheck(); + num = EditorGUILayout.Popup(ModelImporterModelEditor.styles.TangentSpaceTangentLabel, num, displayedOptions, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_TangentImportMode.intValue = (int)array[num]; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.m_NormalImportMode.intValue != 1); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.Slider(this.m_NormalSmoothAngle, 0f, 180f, ModelImporterModelEditor.styles.SmoothingAngle, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_NormalSmoothAngle.floatValue = Mathf.Round(this.m_NormalSmoothAngle.floatValue); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.m_TangentImportMode.intValue != 1); + EditorGUILayout.PropertyField(this.m_SplitTangentsAcrossSeams, ModelImporterModelEditor.styles.SplitTangents, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + GUILayout.Label(ModelImporterModelEditor.styles.Materials, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ImportMaterials, ModelImporterModelEditor.styles.ImportMaterials, new GUILayoutOption[0]); + string text; + if (this.m_ImportMaterials.boolValue) + { + EditorGUILayout.Popup(this.m_MaterialName, (!this.m_ShowAllMaterialNameOptions) ? ModelImporterModelEditor.styles.MaterialNameOptMain : ModelImporterModelEditor.styles.MaterialNameOptAll, ModelImporterModelEditor.styles.MaterialName, new GUILayoutOption[0]); + EditorGUILayout.Popup(this.m_MaterialSearch, ModelImporterModelEditor.styles.MaterialSearchOpt, ModelImporterModelEditor.styles.MaterialSearch, new GUILayoutOption[0]); + text = string.Concat(new string[] + { + ModelImporterModelEditor.styles.MaterialHelpStart.text.Replace("%MAT%", ModelImporterModelEditor.styles.MaterialNameHelp[this.m_MaterialName.intValue].text), + "\n", + ModelImporterModelEditor.styles.MaterialSearchHelp[this.m_MaterialSearch.intValue].text, + "\n", + ModelImporterModelEditor.styles.MaterialHelpEnd.text + }); + } + else + { + text = ModelImporterModelEditor.styles.MaterialHelpDefault.text; + } + GUILayout.Label(new GUIContent(text), EditorStyles.helpBox, new GUILayoutOption[0]); + base.ApplyRevertGUI(); + } + private void ScaleAvatar() + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + object obj = targets[i]; + float globalScale = (obj as ModelImporter).globalScale; + float floatValue = this.m_GlobalScale.floatValue; + if (globalScale != floatValue && floatValue != 0f && globalScale != 0f) + { + float d = floatValue / globalScale; + SerializedProperty serializedProperty = base.serializedObject.FindProperty(AvatarSetupTool.sSkeleton); + for (int j = 0; j < serializedProperty.arraySize; j++) + { + SerializedProperty arrayElementAtIndex = serializedProperty.GetArrayElementAtIndex(j); + arrayElementAtIndex.FindPropertyRelative(AvatarSetupTool.sPosition).vector3Value = arrayElementAtIndex.FindPropertyRelative(AvatarSetupTool.sPosition).vector3Value * d; + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterRigEditor.cs b/UnityEditor/UnityEditor/ModelImporterRigEditor.cs new file mode 100644 index 00000000..9eb7f245 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterRigEditor.cs @@ -0,0 +1,574 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ModelImporterRigEditor : AssetImporterInspector + { + private class Styles + { + public GUIContent AnimationType = EditorGUIUtility.TextContent("ModelImporterAnimationType"); + public GUIContent[] AnimationTypeOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterAnimationTypeNone"), + EditorGUIUtility.TextContent("ModelImporterAnimationTypeLegacy"), + EditorGUIUtility.TextContent("ModelImporterAnimationTypeGeneric"), + EditorGUIUtility.TextContent("ModelImporterAnimationTypeHumanoid") + }; + public GUIContent AnimLabel = EditorGUIUtility.TextContent("ModelImporterAnimLabel"); + public GUIContent[] AnimationsOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterAnimNone"), + EditorGUIUtility.TextContent("ModelImporterAnimOrigRoot"), + EditorGUIUtility.TextContent("ModelImporterAnimNode"), + EditorGUIUtility.TextContent("ModelImporterAnimRoot"), + EditorGUIUtility.TextContent("ModelImporterAnimRootNew") + }; + public GUIStyle helpText = new GUIStyle(EditorStyles.helpBox); + public GUIContent avatar = new GUIContent("Animator"); + public GUIContent configureAvatar = EditorGUIUtility.TextContent("Configure..."); + public GUIContent avatarValid = EditorGUIUtility.TextContent("✓"); + public GUIContent avatarInvalid = EditorGUIUtility.TextContent("✕"); + public GUIContent avatarPending = EditorGUIUtility.TextContent("..."); + public GUIContent UpdateMuscleDefinitionFromSource = EditorGUIUtility.TextContent("ModelImporterRigUpdateMuscleDefinitionFromSource"); + public GUIContent RootNode = EditorGUIUtility.TextContent("ModelImporterRigRootNode"); + public GUIContent AvatarDefinition = EditorGUIUtility.TextContent("ModelImporterRigAvatarDefinition"); + public GUIContent[] AvatarDefinitionOpt = new GUIContent[] + { + EditorGUIUtility.TextContent("ModelImporterRigCreateFromThisModel"), + EditorGUIUtility.TextContent("ModelImporterRigCopyFromOtherAvatar") + }; + public GUIContent UpdateReferenceClips = EditorGUIUtility.TextContent("ModelImporterRigUpdateReferenceClips"); + public Styles() + { + this.helpText.normal.background = null; + this.helpText.alignment = TextAnchor.MiddleLeft; + this.helpText.padding = new RectOffset(0, 0, 0, 0); + } + } + private struct MappingRelevantSettings + { + public bool humanoid; + public bool copyAvatar; + public bool hasNoAnimation; + public bool usesOwnAvatar + { + get + { + return this.humanoid && !this.copyAvatar; + } + } + } + private const float kDeleteWidth = 17f; + public int m_SelectedClipIndex = -1; + private Avatar m_Avatar; + private SerializedProperty m_OptimizeGameObjects; + private SerializedProperty m_AnimationType; + private SerializedProperty m_AvatarSource; + private SerializedProperty m_CopyAvatar; + private SerializedProperty m_LegacyGenerateAnimations; + private SerializedProperty m_AnimationCompression; + private SerializedProperty m_RootMotionBoneName; + private GUIContent[] m_RootMotionBoneList; + private ExposeTransformEditor m_ExposeTransformEditor; + private bool m_AvatarCopyIsUpToDate; + private bool m_CanMultiEditTransformList; + private static ModelImporterRigEditor.Styles styles; + private ModelImporter singleImporter + { + get + { + return base.targets[0] as ModelImporter; + } + } + private ModelImporterAnimationType animationType + { + get + { + return (ModelImporterAnimationType)this.m_AnimationType.intValue; + } + set + { + this.m_AnimationType.intValue = (int)value; + } + } + public int rootIndex + { + get; + set; + } + public bool isLocked + { + get + { + InspectorWindow[] allInspectorWindows = InspectorWindow.GetAllInspectorWindows(); + for (int i = 0; i < allInspectorWindows.Length; i++) + { + InspectorWindow inspectorWindow = allInspectorWindows[i]; + ActiveEditorTracker tracker = inspectorWindow.GetTracker(); + Editor[] activeEditors = tracker.activeEditors; + for (int j = 0; j < activeEditors.Length; j++) + { + Editor x = activeEditors[j]; + if (x == this) + { + return inspectorWindow.isLocked; + } + } + } + return false; + } + } + public void OnEnable() + { + this.m_AnimationType = base.serializedObject.FindProperty("m_AnimationType"); + this.m_AvatarSource = base.serializedObject.FindProperty("m_LastHumanDescriptionAvatarSource"); + this.m_OptimizeGameObjects = base.serializedObject.FindProperty("m_OptimizeGameObjects"); + this.m_RootMotionBoneName = base.serializedObject.FindProperty("m_HumanDescription.m_RootMotionBoneName"); + this.m_ExposeTransformEditor = new ExposeTransformEditor(); + string[] transformPaths = this.singleImporter.transformPaths; + this.m_RootMotionBoneList = new GUIContent[transformPaths.Length]; + for (int i = 0; i < transformPaths.Length; i++) + { + this.m_RootMotionBoneList[i] = new GUIContent(transformPaths[i]); + } + if (this.m_RootMotionBoneList.Length > 0) + { + this.m_RootMotionBoneList[0] = new GUIContent("None"); + } + this.rootIndex = ArrayUtility.FindIndex(this.m_RootMotionBoneList, (GUIContent content) => FileUtil.GetLastPathNameComponent(content.text) == this.m_RootMotionBoneName.stringValue); + this.rootIndex = ((this.rootIndex >= 1) ? this.rootIndex : 0); + this.m_CopyAvatar = base.serializedObject.FindProperty("m_CopyAvatar"); + this.m_LegacyGenerateAnimations = base.serializedObject.FindProperty("m_LegacyGenerateAnimations"); + this.m_AnimationCompression = base.serializedObject.FindProperty("m_AnimationCompression"); + this.m_ExposeTransformEditor.OnEnable(this.singleImporter.transformPaths, base.serializedObject); + this.m_CanMultiEditTransformList = this.CanMultiEditTransformList(); + this.CheckIfAvatarCopyIsUpToDate(); + } + private bool CanMultiEditTransformList() + { + string[] transformPaths = this.singleImporter.transformPaths; + for (int i = 1; i < base.targets.Length; i++) + { + ModelImporter modelImporter = base.targets[i] as ModelImporter; + if (!ArrayUtility.ArrayEquals(transformPaths, modelImporter.transformPaths)) + { + return false; + } + } + return true; + } + private void CheckIfAvatarCopyIsUpToDate() + { + if ((this.animationType != ModelImporterAnimationType.Human && this.animationType != ModelImporterAnimationType.Generic) || this.m_AvatarSource.objectReferenceValue == null) + { + this.m_AvatarCopyIsUpToDate = true; + return; + } + string assetPath = AssetDatabase.GetAssetPath(this.m_AvatarSource.objectReferenceValue); + ModelImporter otherImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter; + this.m_AvatarCopyIsUpToDate = ModelImporterRigEditor.DoesHumanDescriptionMatch(this.singleImporter, otherImporter); + } + internal override void ResetValues() + { + base.ResetValues(); + this.m_Avatar = (AssetDatabase.LoadAssetAtPath((this.target as ModelImporter).assetPath, typeof(Avatar)) as Avatar); + } + private void LegacyGUI() + { + EditorGUILayout.Popup(this.m_LegacyGenerateAnimations, ModelImporterRigEditor.styles.AnimationsOpt, ModelImporterRigEditor.styles.AnimLabel, new GUILayoutOption[0]); + if (this.m_LegacyGenerateAnimations.intValue == 1 || this.m_LegacyGenerateAnimations.intValue == 2 || this.m_LegacyGenerateAnimations.intValue == 3) + { + EditorGUILayout.HelpBox("The animation import setting \"" + ModelImporterRigEditor.styles.AnimationsOpt[this.m_LegacyGenerateAnimations.intValue].text + "\" is deprecated.", MessageType.Warning); + } + } + private void AvatarSourceGUI() + { + EditorGUI.BeginChangeCheck(); + int num = (!this.m_CopyAvatar.boolValue) ? 0 : 1; + EditorGUI.showMixedValue = this.m_CopyAvatar.hasMultipleDifferentValues; + num = EditorGUILayout.Popup(ModelImporterRigEditor.styles.AvatarDefinition, num, ModelImporterRigEditor.styles.AvatarDefinitionOpt, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_CopyAvatar.boolValue = (num == 1); + } + } + private void GenericGUI() + { + this.AvatarSourceGUI(); + if (!this.m_CopyAvatar.hasMultipleDifferentValues) + { + if (!this.m_CopyAvatar.boolValue) + { + EditorGUI.BeginDisabledGroup(!this.m_CanMultiEditTransformList); + EditorGUI.BeginChangeCheck(); + this.rootIndex = EditorGUILayout.Popup(ModelImporterRigEditor.styles.RootNode, this.rootIndex, this.m_RootMotionBoneList, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + if (this.rootIndex > 0 && this.rootIndex < this.m_RootMotionBoneList.Length) + { + this.m_RootMotionBoneName.stringValue = FileUtil.GetLastPathNameComponent(this.m_RootMotionBoneList[this.rootIndex].text); + } + else + { + this.m_RootMotionBoneName.stringValue = string.Empty; + } + } + } + else + { + this.CopyAvatarGUI(); + } + } + } + private void HumanoidGUI() + { + this.AvatarSourceGUI(); + if (!this.m_CopyAvatar.hasMultipleDifferentValues) + { + if (!this.m_CopyAvatar.boolValue) + { + this.ConfigureAvatarGUI(); + } + else + { + this.CopyAvatarGUI(); + } + } + EditorGUILayout.Space(); + } + private void ConfigureAvatarGUI() + { + if (base.targets.Length > 1) + { + GUILayout.Label("Can't configure avatar in multi-editing mode", EditorStyles.helpBox, new GUILayoutOption[0]); + return; + } + if (this.singleImporter.transformPaths.Length <= HumanTrait.RequiredBoneCount) + { + GUILayout.Label("Not enough bones to create human avatar (requires " + HumanTrait.RequiredBoneCount + ")", EditorStyles.helpBox, new GUILayoutOption[0]); + return; + } + GUIContent content; + if (this.m_Avatar && !this.HasModified()) + { + if (this.m_Avatar.isHuman) + { + content = ModelImporterRigEditor.styles.avatarValid; + } + else + { + content = ModelImporterRigEditor.styles.avatarInvalid; + } + } + else + { + content = ModelImporterRigEditor.styles.avatarPending; + GUILayout.Label("The avatar can be configured after settings have been applied.", EditorStyles.helpBox, new GUILayoutOption[0]); + } + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + GUI.Label(new Rect(controlRect.xMax - 75f - 18f, controlRect.y, 18f, controlRect.height), content, EditorStyles.label); + EditorGUI.BeginDisabledGroup(this.m_Avatar == null); + if (GUI.Button(new Rect(controlRect.xMax - 75f, controlRect.y + 1f, 75f, controlRect.height - 1f), ModelImporterRigEditor.styles.configureAvatar, EditorStyles.miniButton)) + { + if (!this.isLocked) + { + if (EditorApplication.SaveCurrentSceneIfUserWantsTo()) + { + Selection.activeObject = this.m_Avatar; + AvatarEditor.s_EditImmediatelyOnNextOpen = true; + } + } + else + { + Debug.Log("Cannot configure avatar, inspector is locked"); + } + } + EditorGUI.EndDisabledGroup(); + } + private void CheckAvatar(Avatar sourceAvatar) + { + if (sourceAvatar != null) + { + if (sourceAvatar.isHuman && this.animationType != ModelImporterAnimationType.Human) + { + if (EditorUtility.DisplayDialog("Asigning an Humanoid Avatar on a Generic Rig", "Do you want to change Animation Type to Humanoid ?", "Yes", "No")) + { + this.animationType = ModelImporterAnimationType.Human; + } + else + { + this.m_AvatarSource.objectReferenceValue = null; + } + } + else + { + if (!sourceAvatar.isHuman && this.animationType != ModelImporterAnimationType.Generic) + { + if (EditorUtility.DisplayDialog("Asigning an Generic Avatar on a Humanoid Rig", "Do you want to change Animation Type to Generic ?", "Yes", "No")) + { + this.animationType = ModelImporterAnimationType.Generic; + } + else + { + this.m_AvatarSource.objectReferenceValue = null; + } + } + } + } + } + private void CopyAvatarGUI() + { + GUILayout.Label("If you have already created an Avatar for another model with a rig identical to this one, you can copy its Avatar definition.\nWith this option, this model will not create any avatar but only import animations.", EditorStyles.helpBox, new GUILayoutOption[0]); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_AvatarSource, GUIContent.Temp("Source"), new GUILayoutOption[0]); + Avatar avatar = this.m_AvatarSource.objectReferenceValue as Avatar; + if (EditorGUI.EndChangeCheck()) + { + this.CheckAvatar(avatar); + AvatarSetupTool.ClearAll(base.serializedObject); + if (avatar != null) + { + this.CopyHumanDescriptionFromOtherModel(avatar); + } + this.m_AvatarCopyIsUpToDate = true; + } + if (avatar != null && !this.m_AvatarSource.hasMultipleDifferentValues && !this.m_AvatarCopyIsUpToDate && GUILayout.Button(ModelImporterRigEditor.styles.UpdateMuscleDefinitionFromSource, EditorStyles.miniButton, new GUILayoutOption[0])) + { + AvatarSetupTool.ClearAll(base.serializedObject); + this.CopyHumanDescriptionFromOtherModel(avatar); + this.m_AvatarCopyIsUpToDate = true; + } + EditorGUILayout.EndHorizontal(); + } + private void ShowUpdateReferenceClip() + { + if (base.targets.Length > 1 || this.animationType != ModelImporterAnimationType.Human || this.m_CopyAvatar.boolValue) + { + return; + } + string[] array = new string[0]; + ModelImporter modelImporter = this.target as ModelImporter; + if (modelImporter.referencedClips.Length > 0) + { + string[] referencedClips = modelImporter.referencedClips; + for (int i = 0; i < referencedClips.Length; i++) + { + string guid = referencedClips[i]; + ArrayUtility.Add(ref array, AssetDatabase.GUIDToAssetPath(guid)); + } + } + if (array.Length > 0 && GUILayout.Button(ModelImporterRigEditor.styles.UpdateReferenceClips, new GUILayoutOption[] + { + GUILayout.Width(150f) + })) + { + string[] array2 = array; + for (int j = 0; j < array2.Length; j++) + { + string otherModelImporterPath = array2[j]; + this.SetupReferencedClip(otherModelImporterPath); + } + try + { + AssetDatabase.StartAssetEditing(); + string[] array3 = array; + for (int k = 0; k < array3.Length; k++) + { + string path = array3[k]; + AssetDatabase.ImportAsset(path); + } + } + finally + { + AssetDatabase.StopAssetEditing(); + } + } + } + public override void OnInspectorGUI() + { + if (ModelImporterRigEditor.styles == null) + { + ModelImporterRigEditor.styles = new ModelImporterRigEditor.Styles(); + } + EditorGUI.BeginChangeCheck(); + EditorGUILayout.Popup(this.m_AnimationType, ModelImporterRigEditor.styles.AnimationTypeOpt, ModelImporterRigEditor.styles.AnimationType, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_AvatarSource.objectReferenceValue = null; + if (this.animationType == ModelImporterAnimationType.Legacy) + { + this.m_AnimationCompression.intValue = 1; + } + else + { + if (this.animationType == ModelImporterAnimationType.Generic || this.animationType == ModelImporterAnimationType.Human) + { + this.m_AnimationCompression.intValue = 3; + } + } + } + EditorGUILayout.Space(); + if (!this.m_AnimationType.hasMultipleDifferentValues) + { + if (this.animationType == ModelImporterAnimationType.Human) + { + this.HumanoidGUI(); + } + else + { + if (this.animationType == ModelImporterAnimationType.Generic) + { + this.GenericGUI(); + } + else + { + if (this.animationType == ModelImporterAnimationType.Legacy) + { + this.LegacyGUI(); + } + } + } + } + if (this.m_Avatar && this.m_Avatar.isValid && this.m_Avatar.isHuman) + { + this.ShowUpdateReferenceClip(); + } + bool flag = true; + if (this.animationType != ModelImporterAnimationType.Human && this.animationType != ModelImporterAnimationType.Generic) + { + flag = false; + } + if (this.m_CopyAvatar.boolValue) + { + flag = false; + } + if (flag) + { + EditorGUILayout.PropertyField(this.m_OptimizeGameObjects, new GUILayoutOption[0]); + if (this.m_OptimizeGameObjects.boolValue && base.serializedObject.targetObjects.Length == 1) + { + EditorGUILayout.Space(); + EditorGUI.BeginDisabledGroup(!this.m_CanMultiEditTransformList); + this.m_ExposeTransformEditor.OnGUI(); + EditorGUI.EndDisabledGroup(); + } + } + base.ApplyRevertGUI(); + } + private static SerializedObject GetModelImporterSerializedObject(string assetPath) + { + ModelImporter modelImporter = AssetImporter.GetAtPath(assetPath) as ModelImporter; + if (modelImporter == null) + { + return null; + } + return new SerializedObject(modelImporter); + } + private static bool DoesHumanDescriptionMatch(ModelImporter importer, ModelImporter otherImporter) + { + SerializedObject serializedObject = new SerializedObject(new UnityEngine.Object[] + { + importer, + otherImporter + }); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_HumanDescription"); + bool result = !serializedProperty.hasMultipleDifferentValues; + serializedObject.Dispose(); + return result; + } + private static void CopyHumanDescriptionToDestination(SerializedObject sourceObject, SerializedObject targetObject) + { + targetObject.CopyFromSerializedProperty(sourceObject.FindProperty("m_HumanDescription")); + } + private void CopyHumanDescriptionFromOtherModel(Avatar sourceAvatar) + { + string assetPath = AssetDatabase.GetAssetPath(sourceAvatar); + SerializedObject modelImporterSerializedObject = ModelImporterRigEditor.GetModelImporterSerializedObject(assetPath); + ModelImporterRigEditor.CopyHumanDescriptionToDestination(modelImporterSerializedObject, base.serializedObject); + modelImporterSerializedObject.Dispose(); + } + private void SetupReferencedClip(string otherModelImporterPath) + { + SerializedObject modelImporterSerializedObject = ModelImporterRigEditor.GetModelImporterSerializedObject(otherModelImporterPath); + if (modelImporterSerializedObject != null) + { + modelImporterSerializedObject.CopyFromSerializedProperty(base.serializedObject.FindProperty("m_AnimationType")); + SerializedProperty serializedProperty = modelImporterSerializedObject.FindProperty("m_CopyAvatar"); + if (serializedProperty != null) + { + serializedProperty.boolValue = true; + } + SerializedProperty serializedProperty2 = modelImporterSerializedObject.FindProperty("m_LastHumanDescriptionAvatarSource"); + if (serializedProperty2 != null) + { + serializedProperty2.objectReferenceValue = this.m_Avatar; + } + ModelImporterRigEditor.CopyHumanDescriptionToDestination(base.serializedObject, modelImporterSerializedObject); + modelImporterSerializedObject.ApplyModifiedProperties(); + modelImporterSerializedObject.Dispose(); + } + } + internal override void Apply() + { + ModelImporterRigEditor.MappingRelevantSettings[] array = new ModelImporterRigEditor.MappingRelevantSettings[base.targets.Length]; + for (int i = 0; i < base.targets.Length; i++) + { + SerializedObject serializedObject = new SerializedObject(base.targets[i]); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_AnimationType"); + SerializedProperty serializedProperty2 = serializedObject.FindProperty("m_CopyAvatar"); + array[i].humanoid = (serializedProperty.intValue == 3); + array[i].hasNoAnimation = (serializedProperty.intValue == 0); + array[i].copyAvatar = serializedProperty2.boolValue; + } + ModelImporterRigEditor.MappingRelevantSettings[] array2 = new ModelImporterRigEditor.MappingRelevantSettings[base.targets.Length]; + Array.Copy(array, array2, base.targets.Length); + for (int j = 0; j < base.targets.Length; j++) + { + if (!this.m_AnimationType.hasMultipleDifferentValues) + { + array2[j].humanoid = (this.m_AnimationType.intValue == 3); + } + if (!this.m_CopyAvatar.hasMultipleDifferentValues) + { + array2[j].copyAvatar = this.m_CopyAvatar.boolValue; + } + } + base.serializedObject.ApplyModifiedProperties(); + for (int k = 0; k < base.targets.Length; k++) + { + if (array[k].usesOwnAvatar && !array2[k].usesOwnAvatar) + { + SerializedObject serializedObject2 = new SerializedObject(base.targets[k]); + AvatarSetupTool.ClearAll(serializedObject2); + serializedObject2.ApplyModifiedProperties(); + } + if (!array[k].usesOwnAvatar && array2[k].usesOwnAvatar) + { + ModelImporter modelImporter = base.targets[k] as ModelImporter; + if (array[k].hasNoAnimation) + { + AssetDatabase.ImportAsset(modelImporter.assetPath); + } + SerializedObject serializedObject3 = new SerializedObject(base.targets[k]); + GameObject gameObject = AssetDatabase.LoadMainAssetAtPath(modelImporter.assetPath) as GameObject; + Animator component = gameObject.GetComponent(); + bool flag = component && !component.hasTransformHierarchy; + if (flag) + { + gameObject = (UnityEngine.Object.Instantiate(gameObject) as GameObject); + AnimatorUtility.DeoptimizeTransformHierarchy(gameObject); + } + AvatarSetupTool.AutoSetupOnInstance(gameObject, serializedObject3); + if (flag) + { + UnityEngine.Object.DestroyImmediate(gameObject); + } + serializedObject3.ApplyModifiedProperties(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ModelImporterTangentSpaceMode.cs b/UnityEditor/UnityEditor/ModelImporterTangentSpaceMode.cs new file mode 100644 index 00000000..c54af054 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelImporterTangentSpaceMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum ModelImporterTangentSpaceMode + { + Import, + Calculate, + None + } +} diff --git a/UnityEditor/UnityEditor/ModelInspector.cs b/UnityEditor/UnityEditor/ModelInspector.cs new file mode 100644 index 00000000..2b9e0327 --- /dev/null +++ b/UnityEditor/UnityEditor/ModelInspector.cs @@ -0,0 +1,161 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Mesh))] + internal class ModelInspector : Editor + { + private PreviewRenderUtility m_PreviewUtility; + private Material m_Material; + private Material m_WireMaterial; + public Vector2 previewDir = new Vector2(120f, -20f); + private void Init() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Diffuse.mat") as Material); + this.m_WireMaterial = new Material("Shader \"Hidden/ModelInspectorWireframe\" {\nSubShader {\n\tTags { \"ForceSupported\" = \"True\" } \n\tColor (0,0,0,0.3) Blend SrcAlpha OneMinusSrcAlpha\n\tZTest LEqual ZWrite Off\n\tOffset -1, -1\n\tPass { Cull Off }\n}}"); + this.m_WireMaterial.hideFlags = HideFlags.HideAndDontSave; + this.m_WireMaterial.shader.hideFlags = HideFlags.HideAndDontSave; + } + } + public override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + GUI.enabled = true; + this.Init(); + } + private void DoRenderPreview() + { + Mesh mesh = this.target as Mesh; + Bounds bounds = mesh.bounds; + float magnitude = bounds.extents.magnitude; + float num = magnitude * 4f; + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * num; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + this.m_PreviewUtility.m_Camera.nearClipPlane = num - magnitude * 1.1f; + this.m_PreviewUtility.m_Camera.farClipPlane = num + magnitude * 1.1f; + this.m_PreviewUtility.m_Light[0].intensity = 0.7f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.7f; + Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + Quaternion quaternion = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); + Vector3 pos = quaternion * -bounds.center; + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + int subMeshCount = mesh.subMeshCount; + this.m_PreviewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; + for (int i = 0; i < subMeshCount; i++) + { + this.m_PreviewUtility.DrawMesh(mesh, pos, quaternion, this.m_Material, i); + } + this.m_PreviewUtility.m_Camera.Render(); + this.m_PreviewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; + ShaderUtil.wireframeMode = true; + for (int j = 0; j < subMeshCount; j++) + { + this.m_PreviewUtility.DrawMesh(mesh, pos, quaternion, this.m_WireMaterial, j); + } + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + ShaderUtil.wireframeMode = false; + InternalEditorUtility.RemoveCustomLighting(); + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + this.Init(); + this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float)width, (float)height)); + this.DoRenderPreview(); + return this.m_PreviewUtility.EndStaticPreview(); + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Mesh preview requires\nrender texture support"); + } + return; + } + this.Init(); + this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + this.DoRenderPreview(); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + public void OnDestroy() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + if (this.m_WireMaterial) + { + UnityEngine.Object.DestroyImmediate(this.m_WireMaterial.shader, true); + UnityEngine.Object.DestroyImmediate(this.m_WireMaterial, true); + } + } + public override string GetInfoString() + { + Mesh mesh = this.target as Mesh; + string text = string.Concat(new object[] + { + mesh.vertexCount, + " verts, ", + InternalMeshUtil.GetPrimitiveCount(mesh), + " tris" + }); + int subMeshCount = mesh.subMeshCount; + if (subMeshCount > 1) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + ", ", + subMeshCount, + " submeshes" + }); + } + int blendShapeCount = mesh.blendShapeCount; + if (blendShapeCount > 1) + { + string text2 = text; + text = string.Concat(new object[] + { + text2, + ", ", + blendShapeCount, + " blendShapes" + }); + } + return text + "\n" + InternalMeshUtil.GetVertexFormat(mesh); + } + } +} diff --git a/UnityEditor/UnityEditor/ModuleUI.cs b/UnityEditor/UnityEditor/ModuleUI.cs new file mode 100644 index 00000000..0e86ddea --- /dev/null +++ b/UnityEditor/UnityEditor/ModuleUI.cs @@ -0,0 +1,952 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class ModuleUI : SerializedModule + { + public enum VisibilityState + { + NotVisible, + VisibleAndFolded, + VisibleAndFoldedOut + } + private class CurveStateCallbackData + { + public SerializedMinMaxCurve[] minMaxCurves; + public MinMaxCurveState selectedState; + public CurveStateCallbackData(MinMaxCurveState state, SerializedMinMaxCurve[] curves) + { + this.minMaxCurves = curves; + this.selectedState = state; + } + } + private class GradientCallbackData + { + public SerializedMinMaxGradient gradientProp; + public MinMaxGradientState selectedState; + public GradientCallbackData(MinMaxGradientState state, SerializedMinMaxGradient p) + { + this.gradientProp = p; + this.selectedState = state; + } + } + private class ColorCallbackData + { + public SerializedProperty boolProp; + public bool selectedState; + public ColorCallbackData(bool state, SerializedProperty bp) + { + this.boolProp = bp; + this.selectedState = state; + } + } + public delegate bool CurveFieldMouseDownCallback(int button, Rect drawRect, Rect curveRanges); + protected const int kSingleLineHeight = 13; + protected const float k_minMaxToggleWidth = 13f; + protected const float k_toggleWidth = 9f; + protected const float kDragSpace = 20f; + protected const int kPlusAddRemoveButtonWidth = 12; + protected const int kPlusAddRemoveButtonSpacing = 5; + protected const int kSpacingSubLabel = 4; + protected const int kSubLabelWidth = 10; + public ParticleSystemUI m_ParticleSystemUI; + private string m_DisplayName; + protected string m_ToolTip = string.Empty; + private SerializedProperty m_Enabled; + private ModuleUI.VisibilityState m_VisibilityState; + public List m_ModuleCurves = new List(); + private List m_CurvesRemovedWhenFolded = new List(); + protected static readonly bool kUseSignedRange = true; + protected static readonly Rect kUnsignedRange = new Rect(0f, 0f, 1f, 1f); + protected static readonly Rect kSignedRange = new Rect(0f, -1f, 1f, 2f); + public static float k_CompactFixedModuleWidth = 195f; + public static float k_SpaceBetweenModules = 5f; + public bool visibleUI + { + get + { + return this.m_VisibilityState != ModuleUI.VisibilityState.NotVisible; + } + set + { + this.SetVisibilityState((!value) ? ModuleUI.VisibilityState.NotVisible : ModuleUI.VisibilityState.VisibleAndFolded); + } + } + public bool foldout + { + get + { + return this.m_VisibilityState == ModuleUI.VisibilityState.VisibleAndFoldedOut; + } + set + { + this.SetVisibilityState((!value) ? ModuleUI.VisibilityState.VisibleAndFolded : ModuleUI.VisibilityState.VisibleAndFoldedOut); + } + } + public bool enabled + { + get + { + return this.m_Enabled.boolValue; + } + set + { + if (this.m_Enabled.boolValue != value) + { + this.m_Enabled.boolValue = value; + if (value) + { + this.OnModuleEnable(); + } + else + { + this.OnModuleDisable(); + } + } + } + } + public string displayName + { + get + { + return this.m_DisplayName; + } + } + public string toolTip + { + get + { + return this.m_ToolTip; + } + } + public ModuleUI(ParticleSystemUI owner, SerializedObject o, string name, string displayName) : base(o, name) + { + this.Setup(owner, o, name, displayName, ModuleUI.VisibilityState.NotVisible); + } + public ModuleUI(ParticleSystemUI owner, SerializedObject o, string name, string displayName, ModuleUI.VisibilityState initialVisibilityState) : base(o, name) + { + this.Setup(owner, o, name, displayName, initialVisibilityState); + } + private void Setup(ParticleSystemUI owner, SerializedObject o, string name, string displayName, ModuleUI.VisibilityState defaultVisibilityState) + { + this.m_ParticleSystemUI = owner; + this.m_DisplayName = displayName; + if (this is RendererModuleUI) + { + this.m_Enabled = base.GetProperty0("m_Enabled"); + } + else + { + this.m_Enabled = base.GetProperty("enabled"); + } + this.m_VisibilityState = (ModuleUI.VisibilityState)InspectorState.GetInt(base.GetUniqueModuleName(), (int)defaultVisibilityState); + this.CheckVisibilityState(); + if (this.foldout) + { + this.Init(); + } + } + protected abstract void Init(); + public virtual void Validate() + { + } + public virtual float GetXAxisScalar() + { + return 1f; + } + public abstract void OnInspectorGUI(ParticleSystem s); + public virtual void OnSceneGUI(ParticleSystem s, InitialModuleUI initial) + { + } + public virtual void UpdateCullingSupportedString(ref string text) + { + } + protected virtual void OnModuleEnable() + { + this.Init(); + } + protected virtual void OnModuleDisable() + { + ParticleSystemCurveEditor particleSystemCurveEditor = this.m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); + foreach (SerializedProperty current in this.m_ModuleCurves) + { + if (particleSystemCurveEditor.IsAdded(current)) + { + particleSystemCurveEditor.RemoveCurve(current); + } + } + } + internal void CheckVisibilityState() + { + if (!(this is RendererModuleUI) && !this.m_Enabled.boolValue && !ParticleEffectUI.GetAllModulesVisible()) + { + this.SetVisibilityState(ModuleUI.VisibilityState.NotVisible); + } + if (this.m_Enabled.boolValue && !this.visibleUI) + { + this.SetVisibilityState(ModuleUI.VisibilityState.VisibleAndFolded); + } + } + protected virtual void SetVisibilityState(ModuleUI.VisibilityState newState) + { + if (newState != this.m_VisibilityState) + { + if (newState == ModuleUI.VisibilityState.VisibleAndFolded) + { + ParticleSystemCurveEditor particleSystemCurveEditor = this.m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); + foreach (SerializedProperty current in this.m_ModuleCurves) + { + if (particleSystemCurveEditor.IsAdded(current)) + { + this.m_CurvesRemovedWhenFolded.Add(current); + particleSystemCurveEditor.SetVisible(current, false); + } + } + particleSystemCurveEditor.Refresh(); + } + else + { + if (newState == ModuleUI.VisibilityState.VisibleAndFoldedOut) + { + ParticleSystemCurveEditor particleSystemCurveEditor2 = this.m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); + foreach (SerializedProperty current2 in this.m_CurvesRemovedWhenFolded) + { + particleSystemCurveEditor2.SetVisible(current2, true); + } + this.m_CurvesRemovedWhenFolded.Clear(); + particleSystemCurveEditor2.Refresh(); + } + } + this.m_VisibilityState = newState; + InspectorState.SetInt(base.GetUniqueModuleName(), (int)this.m_VisibilityState); + if (newState == ModuleUI.VisibilityState.VisibleAndFoldedOut) + { + this.Init(); + } + } + } + protected ParticleSystem GetParticleSystem() + { + return this.m_Enabled.serializedObject.targetObject as ParticleSystem; + } + public ParticleSystemCurveEditor GetParticleSystemCurveEditor() + { + return this.m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor(); + } + public void AddToModuleCurves(SerializedProperty curveProp) + { + this.m_ModuleCurves.Add(curveProp); + if (!this.foldout) + { + this.m_CurvesRemovedWhenFolded.Add(curveProp); + } + } + private static void Label(Rect rect, GUIContent guiContent) + { + GUI.Label(rect, guiContent, ParticleSystemStyles.Get().label); + } + protected static Rect GetControlRect(int height) + { + GUIStyle gUIStyle = new GUIStyle(); + gUIStyle.margin = new RectOffset(0, 0, 2, 2); + return GUILayoutUtility.GetRect(0f, (float)height, gUIStyle); + } + private static Rect PrefixLabel(Rect totalPosition, GUIContent label) + { + Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 13f); + Rect result = new Rect(totalPosition.x + EditorGUIUtility.labelWidth, totalPosition.y, totalPosition.width - EditorGUIUtility.labelWidth, totalPosition.height); + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, 0, ParticleSystemStyles.Get().label); + return result; + } + private static Rect SubtractPopupWidth(Rect position) + { + position.width -= 14f; + return position; + } + private static Rect GetPopupRect(Rect position) + { + position.xMin = position.xMax - 13f; + return position; + } + protected static bool PlusButton(Rect position) + { + return GUI.Button(new Rect(position.x - 2f, position.y - 2f, 12f, 13f), GUIContent.none, "OL Plus"); + } + protected static bool MinusButton(Rect position) + { + return GUI.Button(new Rect(position.x - 2f, position.y - 2f, 12f, 13f), GUIContent.none, "OL Minus"); + } + private static float FloatDraggable(Rect rect, SerializedProperty floatProp, float remap, float dragWidth) + { + return ModuleUI.FloatDraggable(rect, floatProp, remap, dragWidth, "g7"); + } + public static float FloatDraggable(Rect rect, float floatValue, float remap, float dragWidth, string formatString) + { + int controlID = GUIUtility.GetControlID(1658656233, FocusType.Keyboard, rect); + Rect dragHotZone = rect; + dragHotZone.width = dragWidth; + Rect position = rect; + position.xMin += dragWidth; + return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, dragHotZone, controlID, floatValue * remap, formatString, ParticleSystemStyles.Get().numberField, true) / remap; + } + public static float FloatDraggable(Rect rect, SerializedProperty floatProp, float remap, float dragWidth, string formatString) + { + float floatValue = floatProp.floatValue; + float num = ModuleUI.FloatDraggable(rect, floatValue, remap, dragWidth, formatString); + if (num != floatValue) + { + floatProp.floatValue = num; + } + return num; + } + public static float GUIFloat(string label, SerializedProperty floatProp) + { + return ModuleUI.GUIFloat(GUIContent.Temp(label), floatProp); + } + public static float GUIFloat(GUIContent guiContent, SerializedProperty floatProp) + { + return ModuleUI.GUIFloat(guiContent, floatProp, "g7"); + } + public static float GUIFloat(GUIContent guiContent, SerializedProperty floatProp, string formatString) + { + Rect controlRect = ModuleUI.GetControlRect(13); + ModuleUI.PrefixLabel(controlRect, guiContent); + return ModuleUI.FloatDraggable(controlRect, floatProp, 1f, EditorGUIUtility.labelWidth, formatString); + } + public static float GUIFloat(GUIContent guiContent, float floatValue, string formatString) + { + Rect controlRect = ModuleUI.GetControlRect(13); + ModuleUI.PrefixLabel(controlRect, guiContent); + return ModuleUI.FloatDraggable(controlRect, floatValue, 1f, EditorGUIUtility.labelWidth, formatString); + } + private static bool Toggle(Rect rect, SerializedProperty boolProp) + { + bool boolValue = boolProp.boolValue; + bool flag = EditorGUI.Toggle(rect, boolValue, ParticleSystemStyles.Get().toggle); + if (boolValue != flag) + { + boolProp.boolValue = flag; + } + return flag; + } + public static bool GUIToggle(string label, SerializedProperty boolProp) + { + return ModuleUI.GUIToggle(GUIContent.Temp(label), boolProp); + } + public static bool GUIToggle(GUIContent guiContent, SerializedProperty boolProp) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, guiContent); + return ModuleUI.Toggle(rect, boolProp); + } + public static void GUILayerMask(GUIContent guiContent, SerializedProperty boolProp) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, guiContent); + EditorGUI.LayerMaskField(rect, boolProp, GUIContent.none, ParticleSystemStyles.Get().popup); + } + public static bool GUIToggle(GUIContent guiContent, bool boolValue) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, guiContent); + boolValue = EditorGUI.Toggle(rect, boolValue, ParticleSystemStyles.Get().toggle); + return boolValue; + } + public static void GUIToggleWithFloatField(string name, SerializedProperty boolProp, SerializedProperty floatProp) + { + ModuleUI.GUIToggleWithFloatField(EditorGUIUtility.TempContent(name), boolProp, floatProp); + } + public static void GUIToggleWithFloatField(GUIContent guiContent, SerializedProperty boolProp, SerializedProperty floatProp) + { + Rect rect = GUILayoutUtility.GetRect(0f, 13f); + rect = ModuleUI.PrefixLabel(rect, guiContent); + bool flag = ModuleUI.Toggle(rect, boolProp); + if (flag) + { + float dragWidth = 25f; + Rect rect2 = new Rect(rect.x + EditorGUIUtility.labelWidth + 9f, rect.y, rect.width - 9f, rect.height); + ModuleUI.FloatDraggable(rect2, floatProp, 1f, dragWidth); + } + } + public static void GUIToogleWithIntField(string name, SerializedProperty boolProp, SerializedProperty floatProp, bool invertToggle) + { + ModuleUI.GUIToogleWithIntField(EditorGUIUtility.TempContent(name), boolProp, floatProp, invertToggle); + } + public static void GUIToogleWithIntField(GUIContent guiContent, SerializedProperty boolProp, SerializedProperty intProp, bool invertToggle) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, guiContent); + bool flag = ModuleUI.Toggle(rect, boolProp); + flag = ((!invertToggle) ? flag : (!flag)); + if (flag) + { + float dragWidth = 25f; + Rect rect2 = new Rect(rect.x + EditorGUIUtility.labelWidth + 9f, rect.y, rect.width - 9f, rect.height); + intProp.intValue = ModuleUI.IntDraggable(rect2, null, intProp.intValue, dragWidth); + } + } + public static void GUIObject(GUIContent label, SerializedProperty objectProp) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, label); + EditorGUI.ObjectField(rect, objectProp, null, GUIContent.none, ParticleSystemStyles.Get().objectField); + } + public static void GUIObjectFieldAndToggle(GUIContent label, SerializedProperty objectProp, SerializedProperty boolProp) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, label); + rect.xMax -= 19f; + EditorGUI.ObjectField(rect, objectProp, GUIContent.none); + if (boolProp != null) + { + rect.x += rect.width + 10f; + rect.width = 9f; + ModuleUI.Toggle(rect, boolProp); + } + } + internal UnityEngine.Object ParticleSystemValidator(UnityEngine.Object[] references, Type objType, SerializedProperty property) + { + for (int i = 0; i < references.Length; i++) + { + UnityEngine.Object @object = references[i]; + if (@object != null) + { + GameObject gameObject = @object as GameObject; + if (gameObject != null) + { + ParticleSystem component = gameObject.GetComponent(); + if (component) + { + return component; + } + } + } + } + return null; + } + public int GUIListOfFloatObjectToggleFields(GUIContent label, SerializedProperty[] objectProps, EditorGUI.ObjectFieldValidator validator, GUIContent buttonTooltip, bool allowCreation) + { + int result = -1; + int num = objectProps.Length; + Rect rect = GUILayoutUtility.GetRect(0f, (float)(15 * num)); + rect.height = 13f; + float num2 = 10f; + float num3 = 35f; + float num4 = 10f; + float width = rect.width - num2 - num3 - num4 * 2f - 9f; + ModuleUI.PrefixLabel(rect, label); + for (int i = 0; i < num; i++) + { + SerializedProperty serializedProperty = objectProps[i]; + Rect rect2 = new Rect(rect.x + num2 + num3 + num4, rect.y, width, rect.height); + int controlID = GUIUtility.GetControlID(1235498, EditorGUIUtility.native, rect2); + EditorGUI.DoObjectField(rect2, rect2, controlID, null, null, serializedProperty, validator, true, ParticleSystemStyles.Get().objectField); + if (serializedProperty.objectReferenceValue == null) + { + rect2 = new Rect(rect.xMax - 9f, rect.y + 3f, 9f, 9f); + if (!allowCreation || GUI.Button(rect2, buttonTooltip ?? GUIContent.none, ParticleSystemStyles.Get().plus)) + { + result = i; + } + } + rect.y += 15f; + } + return result; + } + public static int GUIIntDraggable(GUIContent label, SerializedProperty intProp) + { + return ModuleUI.GUIIntDraggable(label, intProp.intValue); + } + public static int GUIIntDraggable(GUIContent label, int intValue) + { + Rect rect = GUILayoutUtility.GetRect(0f, 13f); + return ModuleUI.IntDraggable(rect, label, intValue, EditorGUIUtility.labelWidth); + } + public static void GUIIntDraggableX2(GUIContent mainLabel, GUIContent label1, SerializedProperty intProp1, GUIContent label2, SerializedProperty intProp2) + { + Rect totalPosition = ModuleUI.GetControlRect(13); + totalPosition = ModuleUI.PrefixLabel(totalPosition, mainLabel); + float num = (totalPosition.width - 4f) * 0.5f; + Rect rect = new Rect(totalPosition.x, totalPosition.y, num, totalPosition.height); + ModuleUI.IntDraggable(rect, label1, intProp1, 10f); + rect.x += num + 4f; + ModuleUI.IntDraggable(rect, label2, intProp2, 10f); + } + public static int IntDraggable(Rect rect, GUIContent label, SerializedProperty intProp, float dragWidth) + { + intProp.intValue = ModuleUI.IntDraggable(rect, label, intProp.intValue, dragWidth); + return intProp.intValue; + } + public static int GUIInt(GUIContent guiContent, int intValue) + { + Rect rect = GUILayoutUtility.GetRect(0f, 13f); + ModuleUI.PrefixLabel(rect, guiContent); + return ModuleUI.IntDraggable(rect, null, intValue, EditorGUIUtility.labelWidth); + } + public static void GUIInt(GUIContent guiContent, SerializedProperty intProp) + { + intProp.intValue = ModuleUI.GUIInt(guiContent, intProp.intValue); + } + public static int IntDraggable(Rect rect, GUIContent label, int value, float dragWidth) + { + float width = rect.width; + Rect rect2 = rect; + rect2.width = width; + int controlID = GUIUtility.GetControlID(16586232, FocusType.Keyboard, rect2); + Rect rect3 = rect2; + rect3.width = dragWidth; + if (label != null && !string.IsNullOrEmpty(label.text)) + { + ModuleUI.Label(rect3, label); + } + Rect position = rect2; + position.x += dragWidth; + position.width = width - dragWidth; + float dragSensitivity = Mathf.Max(1f, Mathf.Pow(Mathf.Abs((float)value), 0.5f) * 0.03f); + return (int)EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, rect3, controlID, (float)value, EditorGUI.kIntFieldFormatString, ParticleSystemStyles.Get().numberField, true, dragSensitivity); + } + public static void GUIMinMaxRange(GUIContent label, SerializedProperty vec2Prop) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.SubtractPopupWidth(rect); + rect = ModuleUI.PrefixLabel(rect, label); + float num = (rect.width - 20f) * 0.5f; + Vector2 vector2Value = vec2Prop.vector2Value; + rect.width = num; + rect.xMin -= 20f; + vector2Value.x = ModuleUI.FloatDraggable(rect, vector2Value.x, 1f, 20f, "g7"); + vector2Value.x = Mathf.Clamp(vector2Value.x, 0f, vector2Value.y - 0.01f); + rect.x += num + 20f; + vector2Value.y = ModuleUI.FloatDraggable(rect, vector2Value.y, 1f, 20f, "g7"); + vector2Value.y = Mathf.Max(vector2Value.x + 0.01f, vector2Value.y); + vec2Prop.vector2Value = vector2Value; + } + public static void GUISlider(SerializedProperty floatProp, float a, float b, float remap) + { + ModuleUI.GUISlider(string.Empty, floatProp, a, b, remap); + } + public static void GUISlider(string name, SerializedProperty floatProp, float a, float b, float remap) + { + floatProp.floatValue = EditorGUILayout.Slider(name, floatProp.floatValue * remap, a, b, new GUILayoutOption[] + { + GUILayout.MinWidth(300f) + }) / remap; + } + public static void GUIMinMaxSlider(GUIContent label, SerializedProperty vec2Prop, float a, float b) + { + Rect controlRect = ModuleUI.GetControlRect(26); + Rect rect = controlRect; + rect.height = 13f; + rect.y += 3f; + ModuleUI.PrefixLabel(rect, label); + Vector2 vector2Value = vec2Prop.vector2Value; + rect.y += 13f; + EditorGUI.MinMaxSlider(rect, ref vector2Value.x, ref vector2Value.y, a, b); + vec2Prop.vector2Value = vector2Value; + } + public static bool GUIBoolAsPopup(GUIContent label, SerializedProperty boolProp, string[] options) + { + Assert.That(options.Length == 2); + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, label); + int num = (!boolProp.boolValue) ? 0 : 1; + int num2 = EditorGUI.Popup(rect, num, options, ParticleSystemStyles.Get().popup); + if (num2 != num) + { + boolProp.boolValue = (num2 > 0); + } + return num2 > 0; + } + public static int GUIPopup(string name, SerializedProperty intProp, string[] options) + { + return ModuleUI.GUIPopup(GUIContent.Temp(name), intProp, options); + } + public static int GUIPopup(GUIContent label, SerializedProperty intProp, string[] options) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, label); + intProp.intValue = EditorGUI.Popup(rect, intProp.intValue, options, ParticleSystemStyles.Get().popup); + return intProp.intValue; + } + public static int GUIPopup(GUIContent label, int intValue, string[] options) + { + Rect rect = ModuleUI.GetControlRect(13); + rect = ModuleUI.PrefixLabel(rect, label); + return EditorGUI.Popup(rect, intValue, options, ParticleSystemStyles.Get().popup); + } + private static Color GetColor(SerializedMinMaxCurve mmCurve) + { + return mmCurve.m_Module.m_ParticleSystemUI.m_ParticleEffectUI.GetParticleSystemCurveEditor().GetCurveColor(mmCurve.maxCurve); + } + private static void GUICurveField(Rect position, SerializedProperty maxCurve, SerializedProperty minCurve, Color color, Rect ranges, ModuleUI.CurveFieldMouseDownCallback mouseDownCallback) + { + int controlID = GUIUtility.GetControlID(1321321231, EditorGUIUtility.native, position); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl != EventType.MouseDown) + { + if (typeForControl == EventType.Repaint) + { + Rect position2 = position; + if (minCurve == null) + { + EditorGUIUtility.DrawCurveSwatch(position2, null, maxCurve, color, EditorGUI.kCurveBGColor, ranges); + } + else + { + EditorGUIUtility.DrawRegionSwatch(position2, maxCurve, minCurve, color, EditorGUI.kCurveBGColor, ranges); + } + EditorStyles.colorPickerBox.Draw(position2, GUIContent.none, controlID, false); + } + } + else + { + if (position.Contains(current.mousePosition) && mouseDownCallback != null && mouseDownCallback(current.button, position, ranges)) + { + current.Use(); + } + } + } + public static void GUIMinMaxCurve(string label, SerializedMinMaxCurve mmCurve) + { + ModuleUI.GUIMinMaxCurve(GUIContent.Temp(label), mmCurve); + } + public static void GUIMinMaxCurve(GUIContent label, SerializedMinMaxCurve mmCurve) + { + Rect rect = ModuleUI.GetControlRect(13); + Rect popupRect = ModuleUI.GetPopupRect(rect); + rect = ModuleUI.SubtractPopupWidth(rect); + Rect rect2 = ModuleUI.PrefixLabel(rect, label); + MinMaxCurveState state = mmCurve.state; + if (state == MinMaxCurveState.k_Scalar) + { + float a = ModuleUI.FloatDraggable(rect, mmCurve.scalar, mmCurve.m_RemapValue, EditorGUIUtility.labelWidth); + if (!mmCurve.signedRange) + { + mmCurve.scalar.floatValue = Mathf.Max(a, 0f); + } + } + else + { + if (state == MinMaxCurveState.k_TwoScalars) + { + Rect rect3 = rect2; + rect3.width = (rect2.width - 20f) * 0.5f; + float num = mmCurve.minConstant; + float num2 = mmCurve.maxConstant; + Rect rect4 = rect3; + rect4.xMin -= 20f; + EditorGUI.BeginChangeCheck(); + num = ModuleUI.FloatDraggable(rect4, num, mmCurve.m_RemapValue, 20f, "g5"); + if (EditorGUI.EndChangeCheck()) + { + mmCurve.minConstant = num; + } + rect4.x += rect3.width + 20f; + EditorGUI.BeginChangeCheck(); + num2 = ModuleUI.FloatDraggable(rect4, num2, mmCurve.m_RemapValue, 20f, "g5"); + if (EditorGUI.EndChangeCheck()) + { + mmCurve.maxConstant = num2; + } + } + else + { + Rect ranges = (!mmCurve.signedRange) ? ModuleUI.kUnsignedRange : ModuleUI.kSignedRange; + SerializedProperty minCurve = (state != MinMaxCurveState.k_TwoCurves) ? null : mmCurve.minCurve; + ModuleUI.GUICurveField(rect2, mmCurve.maxCurve, minCurve, ModuleUI.GetColor(mmCurve), ranges, new ModuleUI.CurveFieldMouseDownCallback(mmCurve.OnCurveAreaMouseDown)); + } + } + ModuleUI.GUIMMCurveStateList(popupRect, mmCurve); + } + public void GUIMinMaxGradient(GUIContent label, SerializedMinMaxGradient minMaxGradient) + { + MinMaxGradientState state = minMaxGradient.state; + bool flag = state >= MinMaxGradientState.k_RandomBetweenTwoColors; + Rect rect = GUILayoutUtility.GetRect(0f, (float)((!flag) ? 13 : 26)); + Rect popupRect = ModuleUI.GetPopupRect(rect); + rect = ModuleUI.SubtractPopupWidth(rect); + Rect rect2 = ModuleUI.PrefixLabel(rect, label); + rect2.height = 13f; + switch (state) + { + case MinMaxGradientState.k_Color: + ModuleUI.GUIColor(rect2, minMaxGradient.m_MaxColor); + break; + case MinMaxGradientState.k_Gradient: + EditorGUI.GradientField(rect2, minMaxGradient.m_MaxGradient); + break; + case MinMaxGradientState.k_RandomBetweenTwoColors: + ModuleUI.GUIColor(rect2, minMaxGradient.m_MaxColor); + rect2.y += rect2.height; + ModuleUI.GUIColor(rect2, minMaxGradient.m_MinColor); + break; + case MinMaxGradientState.k_RandomBetweenTwoGradients: + EditorGUI.GradientField(rect2, minMaxGradient.m_MaxGradient); + rect2.y += rect2.height; + EditorGUI.GradientField(rect2, minMaxGradient.m_MinGradient); + break; + } + ModuleUI.GUIMMGradientPopUp(popupRect, minMaxGradient); + } + private static void GUIGradientAsColor(Rect rect, SerializedProperty gradientProp) + { + bool changed = GUI.changed; + GUI.changed = false; + Color color = SerializedMinMaxGradient.GetGradientAsColor(gradientProp); + color = EditorGUI.ColorField(rect, color, false, true); + if (GUI.changed) + { + SerializedMinMaxGradient.SetGradientAsColor(gradientProp, color); + } + GUI.changed |= changed; + } + private static void GUIColor(Rect rect, SerializedProperty colorProp) + { + colorProp.colorValue = EditorGUI.ColorField(rect, colorProp.colorValue, false, true); + } + public void GUIMinMaxColor(GUIContent label, SerializedMinMaxColor minMaxColor) + { + Rect totalPosition = ModuleUI.GetControlRect(13); + totalPosition = ModuleUI.PrefixLabel(totalPosition, label); + float num = totalPosition.width - 13f - 5f; + if (!minMaxColor.minMax.boolValue) + { + Rect rect = new Rect(totalPosition.x, totalPosition.y, num, totalPosition.height); + ModuleUI.GUIColor(rect, minMaxColor.maxColor); + } + else + { + Rect rect2 = new Rect(totalPosition.x, totalPosition.y, num * 0.5f - 2f, totalPosition.height); + ModuleUI.GUIColor(rect2, minMaxColor.minColor); + rect2.x += rect2.width + 4f; + ModuleUI.GUIColor(rect2, minMaxColor.maxColor); + } + Rect rect3 = new Rect(totalPosition.xMax - 13f, totalPosition.y, 13f, 13f); + ModuleUI.GUIMMColorPopUp(rect3, minMaxColor.minMax); + } + public void GUITripleMinMaxCurve(GUIContent label, GUIContent x, SerializedMinMaxCurve xCurve, GUIContent y, SerializedMinMaxCurve yCurve, GUIContent z, SerializedMinMaxCurve zCurve, SerializedProperty randomizePerFrame) + { + MinMaxCurveState state = xCurve.state; + bool flag = label != GUIContent.none; + int num = (!flag) ? 1 : 2; + if (state == MinMaxCurveState.k_TwoScalars) + { + num++; + } + Rect rect = ModuleUI.GetControlRect(13 * num); + Rect popupRect = ModuleUI.GetPopupRect(rect); + rect = ModuleUI.SubtractPopupWidth(rect); + Rect rect2 = rect; + float num2 = (rect.width - 8f) / 3f; + if (num > 1) + { + rect2.height = 13f; + } + if (flag) + { + ModuleUI.PrefixLabel(rect, label); + rect2.y += rect2.height; + } + rect2.width = num2; + GUIContent[] array = new GUIContent[] + { + x, + y, + z + }; + SerializedMinMaxCurve[] array2 = new SerializedMinMaxCurve[] + { + xCurve, + yCurve, + zCurve + }; + if (state == MinMaxCurveState.k_Scalar) + { + for (int i = 0; i < array2.Length; i++) + { + ModuleUI.Label(rect2, array[i]); + float a = ModuleUI.FloatDraggable(rect2, array2[i].scalar, array2[i].m_RemapValue, 10f); + if (!array2[i].signedRange) + { + array2[i].scalar.floatValue = Mathf.Max(a, 0f); + } + rect2.x += num2 + 4f; + } + } + else + { + if (state == MinMaxCurveState.k_TwoScalars) + { + for (int j = 0; j < array2.Length; j++) + { + ModuleUI.Label(rect2, array[j]); + float num3 = array2[j].minConstant; + float num4 = array2[j].maxConstant; + EditorGUI.BeginChangeCheck(); + num4 = ModuleUI.FloatDraggable(rect2, num4, array2[j].m_RemapValue, 10f, "g5"); + if (EditorGUI.EndChangeCheck()) + { + array2[j].maxConstant = num4; + } + rect2.y += 13f; + EditorGUI.BeginChangeCheck(); + num3 = ModuleUI.FloatDraggable(rect2, num3, array2[j].m_RemapValue, 10f, "g5"); + if (EditorGUI.EndChangeCheck()) + { + array2[j].minConstant = num3; + } + rect2.x += num2 + 4f; + rect2.y -= 13f; + } + } + else + { + rect2.width = num2; + Rect ranges = (!xCurve.signedRange) ? ModuleUI.kUnsignedRange : ModuleUI.kSignedRange; + for (int k = 0; k < array2.Length; k++) + { + ModuleUI.Label(rect2, array[k]); + Rect position = rect2; + position.xMin += 10f; + SerializedProperty minCurve = (state != MinMaxCurveState.k_TwoCurves) ? null : array2[k].minCurve; + ModuleUI.GUICurveField(position, array2[k].maxCurve, minCurve, ModuleUI.GetColor(array2[k]), ranges, new ModuleUI.CurveFieldMouseDownCallback(array2[k].OnCurveAreaMouseDown)); + rect2.x += num2 + 4f; + } + } + } + ModuleUI.GUIMMCurveStateList(popupRect, array2); + } + private static void SelectMinMaxCurveStateCallback(object obj) + { + ModuleUI.CurveStateCallbackData curveStateCallbackData = (ModuleUI.CurveStateCallbackData)obj; + SerializedMinMaxCurve[] minMaxCurves = curveStateCallbackData.minMaxCurves; + for (int i = 0; i < minMaxCurves.Length; i++) + { + SerializedMinMaxCurve serializedMinMaxCurve = minMaxCurves[i]; + serializedMinMaxCurve.state = curveStateCallbackData.selectedState; + } + } + public static void GUIMMCurveStateList(Rect rect, SerializedMinMaxCurve minMaxCurves) + { + SerializedMinMaxCurve[] minMaxCurves2 = new SerializedMinMaxCurve[] + { + minMaxCurves + }; + ModuleUI.GUIMMCurveStateList(rect, minMaxCurves2); + } + public static void GUIMMCurveStateList(Rect rect, SerializedMinMaxCurve[] minMaxCurves) + { + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, ParticleSystemStyles.Get().minMaxCurveStateDropDown)) + { + if (minMaxCurves.Length == 0) + { + return; + } + GUIContent[] array = new GUIContent[] + { + new GUIContent("Constant"), + new GUIContent("Curve"), + new GUIContent("Random Between Two Constants"), + new GUIContent("Random Between Two Curves") + }; + MinMaxCurveState[] array2 = new MinMaxCurveState[] + { + MinMaxCurveState.k_Scalar, + MinMaxCurveState.k_Curve, + MinMaxCurveState.k_TwoScalars, + MinMaxCurveState.k_TwoCurves + }; + bool[] array3 = new bool[] + { + minMaxCurves[0].m_AllowConstant, + true, + minMaxCurves[0].m_AllowRandom, + minMaxCurves[0].m_AllowRandom + }; + GenericMenu genericMenu = new GenericMenu(); + for (int i = 0; i < array.Length; i++) + { + if (array3[i]) + { + genericMenu.AddItem(array[i], minMaxCurves[0].state == array2[i], new GenericMenu.MenuFunction2(ModuleUI.SelectMinMaxCurveStateCallback), new ModuleUI.CurveStateCallbackData(array2[i], minMaxCurves)); + } + } + genericMenu.DropDown(rect); + Event.current.Use(); + } + } + private static void SelectMinMaxGradientStateCallback(object obj) + { + ModuleUI.GradientCallbackData gradientCallbackData = (ModuleUI.GradientCallbackData)obj; + gradientCallbackData.gradientProp.state = gradientCallbackData.selectedState; + } + public static void GUIMMGradientPopUp(Rect rect, SerializedMinMaxGradient gradientProp) + { + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, ParticleSystemStyles.Get().minMaxCurveStateDropDown)) + { + GUIContent[] array = new GUIContent[] + { + new GUIContent("Color"), + new GUIContent("Gradient"), + new GUIContent("Random Between Two Colors"), + new GUIContent("Random Between Two Gradients") + }; + MinMaxGradientState[] array2 = new MinMaxGradientState[] + { + MinMaxGradientState.k_Color, + MinMaxGradientState.k_Gradient, + MinMaxGradientState.k_RandomBetweenTwoColors, + MinMaxGradientState.k_RandomBetweenTwoGradients + }; + bool[] array3 = new bool[] + { + gradientProp.m_AllowColor, + gradientProp.m_AllowGradient, + gradientProp.m_AllowRandomBetweenTwoColors, + gradientProp.m_AllowRandomBetweenTwoGradients + }; + GenericMenu genericMenu = new GenericMenu(); + for (int i = 0; i < array.Length; i++) + { + if (array3[i]) + { + genericMenu.AddItem(array[i], gradientProp.state == array2[i], new GenericMenu.MenuFunction2(ModuleUI.SelectMinMaxGradientStateCallback), new ModuleUI.GradientCallbackData(array2[i], gradientProp)); + } + } + genericMenu.ShowAsContext(); + Event.current.Use(); + } + } + private static void SelectMinMaxColorStateCallback(object obj) + { + ModuleUI.ColorCallbackData colorCallbackData = (ModuleUI.ColorCallbackData)obj; + colorCallbackData.boolProp.boolValue = colorCallbackData.selectedState; + } + public static void GUIMMColorPopUp(Rect rect, SerializedProperty boolProp) + { + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, ParticleSystemStyles.Get().minMaxCurveStateDropDown)) + { + GenericMenu genericMenu = new GenericMenu(); + GUIContent[] array = new GUIContent[] + { + new GUIContent("Constant Color"), + new GUIContent("Random Between Two Colors") + }; + bool[] array2 = new bool[] + { + default(bool), + true + }; + for (int i = 0; i < array.Length; i++) + { + genericMenu.AddItem(array[i], boolProp.boolValue == array2[i], new GenericMenu.MenuFunction2(ModuleUI.SelectMinMaxColorStateCallback), new ModuleUI.ColorCallbackData(array2[i], boolProp)); + } + genericMenu.ShowAsContext(); + Event.current.Use(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/MonoAOTRegistration.cs b/UnityEditor/UnityEditor/MonoAOTRegistration.cs new file mode 100644 index 00000000..ecb4ab80 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoAOTRegistration.cs @@ -0,0 +1,246 @@ +using Mono.Cecil; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class MonoAOTRegistration + { + private static void ExtractNativeMethodsFromTypes(ICollection types, ArrayList res) + { + foreach (TypeDefinition current in types) + { + foreach (MethodDefinition current2 in current.Methods) + { + if (current2.IsStatic && current2.IsPInvokeImpl && current2.PInvokeInfo.Module.Name.Equals("__Internal")) + { + if (res.Contains(current2.Name)) + { + throw new SystemException("Duplicate native method found : " + current2.Name + ". Please check your source carefully."); + } + res.Add(current2.Name); + } + } + if (current.HasNestedTypes) + { + MonoAOTRegistration.ExtractNativeMethodsFromTypes(current.NestedTypes, res); + } + } + } + private static ArrayList BuildNativeMethodList(AssemblyDefinition[] assemblies) + { + ArrayList arrayList = new ArrayList(); + for (int i = 0; i < assemblies.Length; i++) + { + AssemblyDefinition assemblyDefinition = assemblies[i]; + if (!"System".Equals(assemblyDefinition.Name.Name)) + { + MonoAOTRegistration.ExtractNativeMethodsFromTypes(assemblyDefinition.MainModule.Types, arrayList); + } + } + return arrayList; + } + public static HashSet BuildReferencedTypeList(AssemblyDefinition[] assemblies) + { + HashSet hashSet = new HashSet(); + for (int i = 0; i < assemblies.Length; i++) + { + AssemblyDefinition assemblyDefinition = assemblies[i]; + if (!assemblyDefinition.Name.Name.StartsWith("System") && !assemblyDefinition.Name.Name.Equals("UnityEngine")) + { + foreach (TypeReference current in assemblyDefinition.MainModule.GetTypeReferences()) + { + hashSet.Add(current.FullName); + } + } + } + return hashSet; + } + public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string librariesFolder, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker) + { + using (TextWriter textWriter = new StreamWriter(Path.Combine(librariesFolder, "RegisterMonoModules.cpp"))) + { + string[] assemblyFileNames = checker.GetAssemblyFileNames(); + AssemblyDefinition[] assemblyDefinitions = checker.GetAssemblyDefinitions(); + bool flag = (crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic; + ArrayList arrayList = MonoAOTRegistration.BuildNativeMethodList(assemblyDefinitions); + if (buildTarget == BuildTarget.iPhone) + { + textWriter.WriteLine("#include \"RegisterMonoModules.h\""); + } + textWriter.WriteLine(string.Empty); + textWriter.WriteLine("extern \"C\"\n{"); + textWriter.WriteLine("\ttypedef void* gpointer;"); + textWriter.WriteLine("\ttypedef int gboolean;"); + textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)"); + if (buildTarget == BuildTarget.iPhone) + { + textWriter.WriteLine("\tconst char*\t\t\tUnityIPhoneRuntimeVersion = \"{0}\";", Application.unityVersion); + textWriter.WriteLine("\tvoid\t\t\t\tmono_dl_register_symbol (const char* name, void *addr);"); + textWriter.WriteLine("\textern int \t\t\tmono_ficall_flag;"); + } + textWriter.WriteLine("\tvoid\t\t\t\tmono_aot_register_module(gpointer *aot_info);"); + textWriter.WriteLine("\textern gboolean\t\tmono_aot_only;"); + for (int i = 0; i < assemblyFileNames.Length; i++) + { + string arg = assemblyFileNames[i]; + string text = assemblyDefinitions[i].Name.Name; + text = text.Replace(".", "_"); + text = text.Replace("-", "_"); + text = text.Replace(" ", "_"); + textWriter.WriteLine("\textern gpointer*\tmono_aot_module_{0}_info; // {1}", text, arg); + } + textWriter.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)"); + foreach (string arg2 in arrayList) + { + textWriter.WriteLine("\tvoid\t{0}();", arg2); + } + textWriter.WriteLine("}"); + textWriter.WriteLine("void RegisterMonoModules()"); + textWriter.WriteLine("{"); + textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)"); + textWriter.WriteLine("\tmono_aot_only = true;"); + if (buildTarget == BuildTarget.iPhone) + { + textWriter.WriteLine("\tmono_ficall_flag = {0};", (!flag) ? "false" : "true"); + } + AssemblyDefinition[] array = assemblyDefinitions; + for (int j = 0; j < array.Length; j++) + { + AssemblyDefinition assemblyDefinition = array[j]; + string text2 = assemblyDefinition.Name.Name; + text2 = text2.Replace(".", "_"); + text2 = text2.Replace("-", "_"); + text2 = text2.Replace(" ", "_"); + textWriter.WriteLine("\tmono_aot_register_module(mono_aot_module_{0}_info);", text2); + } + textWriter.WriteLine(string.Empty); + if (buildTarget == BuildTarget.iPhone) + { + foreach (string arg3 in arrayList) + { + textWriter.WriteLine("\tmono_dl_register_symbol(\"{0}\", (void*)&{0});", arg3); + } + } + textWriter.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)"); + textWriter.WriteLine("}"); + textWriter.WriteLine(string.Empty); + AssemblyDefinition assemblyDefinition2 = null; + for (int k = 0; k < assemblyFileNames.Length; k++) + { + if (assemblyFileNames[k] == "UnityEngine.dll") + { + assemblyDefinition2 = assemblyDefinitions[k]; + } + } + if (buildTarget == BuildTarget.iPhone) + { + AssemblyDefinition[] assemblies = new AssemblyDefinition[] + { + assemblyDefinition2 + }; + MonoAOTRegistration.GenerateRegisterInternalCalls(assemblies, textWriter); + MonoAOTRegistration.ResolveDefinedNativeClassesFromMono(assemblies, usedClassRegistry); + MonoAOTRegistration.ResolveReferencedUnityEngineClassesFromMono(assemblyDefinitions, assemblyDefinition2, usedClassRegistry); + if (stripping && usedClassRegistry != null) + { + MonoAOTRegistration.GenerateRegisterClassesForStripping(usedClassRegistry, textWriter); + } + else + { + MonoAOTRegistration.GenerateRegisterClasses(usedClassRegistry, textWriter); + } + } + textWriter.Close(); + } + } + public static void ResolveReferencedUnityEngineClassesFromMono(AssemblyDefinition[] assemblies, AssemblyDefinition unityEngine, RuntimeClassRegistry res) + { + if (res == null) + { + return; + } + for (int i = 0; i < assemblies.Length; i++) + { + AssemblyDefinition assemblyDefinition = assemblies[i]; + if (assemblyDefinition != unityEngine) + { + foreach (TypeReference current in assemblyDefinition.MainModule.GetTypeReferences()) + { + if (current.Namespace.StartsWith("UnityEngine")) + { + string name = current.Name; + res.AddMonoClass(name); + } + } + } + } + } + public static void ResolveDefinedNativeClassesFromMono(AssemblyDefinition[] assemblies, RuntimeClassRegistry res) + { + if (res == null) + { + return; + } + for (int i = 0; i < assemblies.Length; i++) + { + AssemblyDefinition assemblyDefinition = assemblies[i]; + foreach (TypeDefinition current in assemblyDefinition.MainModule.Types) + { + if (current.Fields.Count > 0 || current.Methods.Count > 0 || current.Properties.Count > 0) + { + string name = current.Name; + res.AddMonoClass(name); + } + } + } + } + public static void GenerateRegisterClassesForStripping(RuntimeClassRegistry allClasses, TextWriter output) + { + output.Write("void RegisterAllClasses() \n{\n"); + allClasses.SynchronizeClasses(); + foreach (string current in allClasses.GetAllNativeClassesAsString()) + { + output.WriteLine(string.Format("extern int RegisterClass_{0}();\nRegisterClass_{0}();", current)); + } + output.Write("\n}\n"); + } + public static void GenerateRegisterClasses(RuntimeClassRegistry allClasses, TextWriter output) + { + output.Write("void RegisterAllClasses() \n{\n"); + output.Write("void RegisterAllClassesIPhone();\nRegisterAllClassesIPhone();\n"); + output.Write("\n}\n"); + } + public static void GenerateRegisterInternalCalls(AssemblyDefinition[] assemblies, TextWriter output) + { + output.Write("void RegisterAllStrippedInternalCalls ()\n{\n"); + for (int i = 0; i < assemblies.Length; i++) + { + AssemblyDefinition assemblyDefinition = assemblies[i]; + foreach (TypeDefinition current in assemblyDefinition.MainModule.Types) + { + foreach (MethodDefinition current2 in current.Methods) + { + MonoAOTRegistration.GenerateInternalCallMethod(current, current2, output); + } + } + } + output.Write("\n}\n"); + } + private static void GenerateInternalCallMethod(TypeDefinition typeDefinition, MethodDefinition method, TextWriter output) + { + if (!method.IsInternalCall) + { + return; + } + string text = string.Format("\tvoid Register_{0}_{1}_{2} ();", typeDefinition.Namespace, typeDefinition.Name, method.Name); + string text2 = string.Format("\tRegister_{0}_{1}_{2} ();", typeDefinition.Namespace, typeDefinition.Name, method.Name); + text2 = text2.Replace('.', '_'); + text = text.Replace('.', '_'); + output.WriteLine(text); + output.WriteLine(text2); + } + } +} diff --git a/UnityEditor/UnityEditor/MonoAssemblyStripping.cs b/UnityEditor/UnityEditor/MonoAssemblyStripping.cs new file mode 100644 index 00000000..1816e3cf --- /dev/null +++ b/UnityEditor/UnityEditor/MonoAssemblyStripping.cs @@ -0,0 +1,217 @@ +using Mono.Cecil; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditor +{ + internal class MonoAssemblyStripping + { + private static void ReplaceFile(string src, string dst) + { + if (File.Exists(dst)) + { + FileUtil.DeleteFileOrDirectory(dst); + } + FileUtil.CopyFileOrDirectory(src, dst); + } + public static void MonoCilStrip(BuildTarget buildTarget, string managedLibrariesDirectory, string[] fileNames) + { + string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(buildTarget); + string str = Path.Combine(buildToolsDirectory, "mono-cil-strip.exe"); + for (int i = 0; i < fileNames.Length; i++) + { + string text = fileNames[i]; + Process process = MonoProcessUtility.PrepareMonoProcess(buildTarget, managedLibrariesDirectory); + string text2 = text + ".out"; + process.StartInfo.Arguments = "\"" + str + "\""; + ProcessStartInfo expr_5B = process.StartInfo; + string arguments = expr_5B.Arguments; + expr_5B.Arguments = string.Concat(new string[] + { + arguments, + " \"", + text, + "\" \"", + text, + ".out\"" + }); + MonoProcessUtility.RunMonoProcess(process, "byte code stripper", Path.Combine(managedLibrariesDirectory, text2)); + MonoAssemblyStripping.ReplaceFile(managedLibrariesDirectory + "/" + text2, managedLibrariesDirectory + "/" + text); + File.Delete(managedLibrariesDirectory + "/" + text2); + } + } + public static string GenerateBlackList(string librariesFolder, RuntimeClassRegistry usedClasses, string[] allAssemblies) + { + string text = "tmplink.xml"; + usedClasses.SynchronizeClasses(); + using (TextWriter textWriter = new StreamWriter(Path.Combine(librariesFolder, text))) + { + textWriter.WriteLine(""); + textWriter.WriteLine(""); + foreach (string current in usedClasses.GetAllManagedClassesAsString()) + { + textWriter.WriteLine(string.Format("", current, usedClasses.GetRetentionLevel(current))); + } + textWriter.WriteLine(""); + DefaultAssemblyResolver defaultAssemblyResolver = new DefaultAssemblyResolver(); + defaultAssemblyResolver.AddSearchDirectory(librariesFolder); + for (int i = 0; i < allAssemblies.Length; i++) + { + string path = allAssemblies[i]; + AssemblyDefinition assemblyDefinition = defaultAssemblyResolver.Resolve(Path.GetFileNameWithoutExtension(path), new ReaderParameters + { + AssemblyResolver = defaultAssemblyResolver + }); + textWriter.WriteLine("", assemblyDefinition.Name.Name); + MonoAssemblyStripping.GenerateBlackListTypeXML(textWriter, assemblyDefinition.MainModule.Types, usedClasses.GetAllManagedBaseClassesAsString()); + textWriter.WriteLine(""); + } + textWriter.WriteLine(""); + } + return text; + } + private static void GenerateBlackListTypeXML(TextWriter w, IList types, List baseTypes) + { + if (types == null) + { + return; + } + foreach (TypeDefinition current in types) + { + if (current != null) + { + foreach (string current2 in baseTypes) + { + if (MonoAssemblyStripping.DoesTypeEnheritFrom(current, current2)) + { + w.WriteLine("", current.FullName); + break; + } + } + MonoAssemblyStripping.GenerateBlackListTypeXML(w, current.NestedTypes, baseTypes); + } + } + } + private static bool DoesTypeEnheritFrom(TypeReference type, string typeName) + { + while (type != null) + { + if (type.FullName == typeName) + { + return true; + } + type = type.Resolve().BaseType; + } + return false; + } + private static string StripperExe() + { + RuntimePlatform platform = Application.platform; + if (platform != RuntimePlatform.WindowsEditor) + { + return "Tools/UnusedByteCodeStripper/UnusedBytecodeStripper.exe"; + } + return "Tools/UnusedBytecodeStripper.exe"; + } + public static void MonoLink(BuildTarget buildTarget, string managedLibrariesDirectory, string[] input, string[] allAssemblies, RuntimeClassRegistry usedClasses) + { + Process process = MonoProcessUtility.PrepareMonoProcess(buildTarget, managedLibrariesDirectory); + string buildToolsDirectory = BuildPipeline.GetBuildToolsDirectory(buildTarget); + string text = null; + string frameWorksFolder = MonoInstallationFinder.GetFrameWorksFolder(); + string text2 = Path.Combine(frameWorksFolder, MonoAssemblyStripping.StripperExe()); + string text3 = Path.Combine(Path.GetDirectoryName(text2), "link.xml"); + string text4 = Path.Combine(managedLibrariesDirectory, "output"); + Directory.CreateDirectory(text4); + process.StartInfo.Arguments = "\"" + text2 + "\" -l none -c link"; + for (int i = 0; i < input.Length; i++) + { + string str = input[i]; + ProcessStartInfo expr_80 = process.StartInfo; + expr_80.Arguments = expr_80.Arguments + " -a \"" + str + "\""; + } + ProcessStartInfo expr_B3 = process.StartInfo; + string arguments = expr_B3.Arguments; + expr_B3.Arguments = string.Concat(new string[] + { + arguments, + " -out output -x \"", + text3, + "\" -d \"", + managedLibrariesDirectory, + "\"" + }); + string text5 = Path.Combine(buildToolsDirectory, "link.xml"); + if (File.Exists(text5)) + { + ProcessStartInfo expr_110 = process.StartInfo; + expr_110.Arguments = expr_110.Arguments + " -x \"" + text5 + "\""; + } + string[] files = Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "link.xml", SearchOption.AllDirectories); + string[] array = files; + for (int j = 0; j < array.Length; j++) + { + string str2 = array[j]; + ProcessStartInfo expr_161 = process.StartInfo; + expr_161.Arguments = expr_161.Arguments + " -x \"" + str2 + "\""; + } + if (usedClasses != null) + { + text = MonoAssemblyStripping.GenerateBlackList(managedLibrariesDirectory, usedClasses, allAssemblies); + ProcessStartInfo expr_1A5 = process.StartInfo; + expr_1A5.Arguments = expr_1A5.Arguments + " -x \"" + text + "\""; + } + MonoProcessUtility.RunMonoProcess(process, "assemblies stripper", Path.Combine(text4, "mscorlib.dll")); + if (buildTarget == BuildTarget.FlashPlayer) + { + IEnumerable files2 = + from _ in input + select Path.GetFileName(_); + MonoAssemblyStripping.CopyFiles(files2, text4, managedLibrariesDirectory); + } + else + { + MonoAssemblyStripping.DeleteAllDllsFrom(managedLibrariesDirectory); + MonoAssemblyStripping.CopyAllDlls(managedLibrariesDirectory, text4); + } + if (text != null) + { + FileUtil.DeleteFileOrDirectory(Path.Combine(managedLibrariesDirectory, text)); + } + FileUtil.DeleteFileOrDirectory(text4); + } + private static void CopyFiles(IEnumerable files, string fromDir, string toDir) + { + foreach (string current in files) + { + FileUtil.ReplaceFile(Path.Combine(fromDir, current), Path.Combine(toDir, current)); + } + } + private static void CopyAllDlls(string fromDir, string toDir) + { + DirectoryInfo directoryInfo = new DirectoryInfo(toDir); + FileInfo[] files = directoryInfo.GetFiles("*.dll"); + FileInfo[] array = files; + for (int i = 0; i < array.Length; i++) + { + FileInfo fileInfo = array[i]; + FileUtil.ReplaceFile(Path.Combine(toDir, fileInfo.Name), Path.Combine(fromDir, fileInfo.Name)); + } + } + private static void DeleteAllDllsFrom(string managedLibrariesDirectory) + { + DirectoryInfo directoryInfo = new DirectoryInfo(managedLibrariesDirectory); + FileInfo[] files = directoryInfo.GetFiles("*.dll"); + FileInfo[] array = files; + for (int i = 0; i < array.Length; i++) + { + FileInfo fileInfo = array[i]; + FileUtil.DeleteFileOrDirectory(fileInfo.FullName); + } + } + } +} diff --git a/UnityEditor/UnityEditor/MonoCrossCompile.cs b/UnityEditor/UnityEditor/MonoCrossCompile.cs new file mode 100644 index 00000000..5a1212aa --- /dev/null +++ b/UnityEditor/UnityEditor/MonoCrossCompile.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using UnityEngine; +namespace UnityEditor +{ + internal class MonoCrossCompile + { + private class JobCompileAOT + { + private BuildTarget m_target; + private string m_crossCompilerAbsolutePath; + private string m_assembliesAbsoluteDirectory; + private CrossCompileOptions m_crossCompileOptions; + public string m_input; + public string m_output; + public string m_additionalOptions; + public ManualResetEvent m_doneEvent = new ManualResetEvent(false); + public Exception m_Exception; + public JobCompileAOT(BuildTarget target, string crossCompilerAbsolutePath, string assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, string input, string output, string additionalOptions) + { + this.m_target = target; + this.m_crossCompilerAbsolutePath = crossCompilerAbsolutePath; + this.m_assembliesAbsoluteDirectory = assembliesAbsoluteDirectory; + this.m_crossCompileOptions = crossCompileOptions; + this.m_input = input; + this.m_output = output; + this.m_additionalOptions = additionalOptions; + } + public void ThreadPoolCallback(object threadContext) + { + try + { + MonoCrossCompile.CrossCompileAOT(this.m_target, this.m_crossCompilerAbsolutePath, this.m_assembliesAbsoluteDirectory, this.m_crossCompileOptions, this.m_input, this.m_output, this.m_additionalOptions); + } + catch (Exception exception) + { + this.m_Exception = exception; + } + this.m_doneEvent.Set(); + } + } + public static string ArtifactsPath; + public static void CrossCompileAOTDirectory(BuildTarget buildTarget, CrossCompileOptions crossCompileOptions, string sourceAssembliesFolder, string targetCrossCompiledASMFolder, string additionalOptions) + { + MonoCrossCompile.CrossCompileAOTDirectory(buildTarget, crossCompileOptions, sourceAssembliesFolder, targetCrossCompiledASMFolder, string.Empty, additionalOptions); + } + public static void CrossCompileAOTDirectory(BuildTarget buildTarget, CrossCompileOptions crossCompileOptions, string sourceAssembliesFolder, string targetCrossCompiledASMFolder, string pathExtension, string additionalOptions) + { + string text = BuildPipeline.GetBuildToolsDirectory(buildTarget); + if (Application.platform == RuntimePlatform.OSXEditor) + { + text = Path.Combine(Path.Combine(text, pathExtension), "mono-xcompiler"); + } + else + { + text = Path.Combine(Path.Combine(text, pathExtension), "mono-xcompiler.exe"); + } + sourceAssembliesFolder = Path.Combine(Directory.GetCurrentDirectory(), sourceAssembliesFolder); + targetCrossCompiledASMFolder = Path.Combine(Directory.GetCurrentDirectory(), targetCrossCompiledASMFolder); + string[] files = Directory.GetFiles(sourceAssembliesFolder); + for (int i = 0; i < files.Length; i++) + { + string path = files[i]; + if (!(Path.GetExtension(path) != ".dll")) + { + string fileName = Path.GetFileName(path); + string output = Path.Combine(targetCrossCompiledASMFolder, fileName + ".s"); + if (EditorUtility.DisplayCancelableProgressBar("Building Player", "AOT cross compile " + fileName, 0.95f)) + { + return; + } + MonoCrossCompile.CrossCompileAOT(buildTarget, text, sourceAssembliesFolder, crossCompileOptions, fileName, output, additionalOptions); + } + } + } + public static bool CrossCompileAOTDirectoryParallel(BuildTarget buildTarget, CrossCompileOptions crossCompileOptions, string sourceAssembliesFolder, string targetCrossCompiledASMFolder, string additionalOptions) + { + return MonoCrossCompile.CrossCompileAOTDirectoryParallel(buildTarget, crossCompileOptions, sourceAssembliesFolder, targetCrossCompiledASMFolder, string.Empty, additionalOptions); + } + public static bool CrossCompileAOTDirectoryParallel(BuildTarget buildTarget, CrossCompileOptions crossCompileOptions, string sourceAssembliesFolder, string targetCrossCompiledASMFolder, string pathExtension, string additionalOptions) + { + string text = BuildPipeline.GetBuildToolsDirectory(buildTarget); + if (Application.platform == RuntimePlatform.OSXEditor) + { + text = Path.Combine(Path.Combine(text, pathExtension), "mono-xcompiler"); + } + else + { + text = Path.Combine(Path.Combine(text, pathExtension), "mono-xcompiler.exe"); + } + return MonoCrossCompile.CrossCompileAOTDirectoryParallel(text, buildTarget, crossCompileOptions, sourceAssembliesFolder, targetCrossCompiledASMFolder, additionalOptions); + } + private static bool WaitForBuildOfFile(List events, ref long timeout) + { + long num = DateTime.Now.Ticks / 10000L; + int num2 = WaitHandle.WaitAny(events.ToArray(), (int)timeout); + long num3 = DateTime.Now.Ticks / 10000L; + if (num2 == 258) + { + return false; + } + events.RemoveAt(num2); + timeout -= num3 - num; + if (timeout < 0L) + { + timeout = 0L; + } + return true; + } + public static void DisplayAOTProgressBar(int totalFiles, int filesFinished) + { + string info = string.Format("AOT cross compile ({0}/{1})", (filesFinished + 1).ToString(), totalFiles.ToString()); + EditorUtility.DisplayProgressBar("Building Player", info, 0.95f); + } + public static bool CrossCompileAOTDirectoryParallel(string crossCompilerPath, BuildTarget buildTarget, CrossCompileOptions crossCompileOptions, string sourceAssembliesFolder, string targetCrossCompiledASMFolder, string additionalOptions) + { + sourceAssembliesFolder = Path.Combine(Directory.GetCurrentDirectory(), sourceAssembliesFolder); + targetCrossCompiledASMFolder = Path.Combine(Directory.GetCurrentDirectory(), targetCrossCompiledASMFolder); + int num = 1; + int num2 = 1; + ThreadPool.GetMaxThreads(out num, out num2); + List list = new List(); + List list2 = new List(); + bool flag = true; + List list3 = new List( + from path in Directory.GetFiles(sourceAssembliesFolder) + where Path.GetExtension(path) == ".dll" + select path); + int count = list3.Count; + int num3 = 0; + MonoCrossCompile.DisplayAOTProgressBar(count, num3); + long num4 = (long)Math.Min(1800000, (count + 3) * 1000 * 30); + foreach (string current in list3) + { + if (!(Path.GetExtension(current) != ".dll")) + { + string fileName = Path.GetFileName(current); + string output = Path.Combine(targetCrossCompiledASMFolder, fileName + ".s"); + MonoCrossCompile.JobCompileAOT jobCompileAOT = new MonoCrossCompile.JobCompileAOT(buildTarget, crossCompilerPath, sourceAssembliesFolder, crossCompileOptions, fileName, output, additionalOptions); + list.Add(jobCompileAOT); + list2.Add(jobCompileAOT.m_doneEvent); + ThreadPool.QueueUserWorkItem(new WaitCallback(jobCompileAOT.ThreadPoolCallback)); + if (list2.Count >= Environment.ProcessorCount) + { + flag = MonoCrossCompile.WaitForBuildOfFile(list2, ref num4); + MonoCrossCompile.DisplayAOTProgressBar(count, num3); + num3++; + if (!flag) + { + break; + } + } + } + } + while (list2.Count > 0) + { + flag = MonoCrossCompile.WaitForBuildOfFile(list2, ref num4); + MonoCrossCompile.DisplayAOTProgressBar(count, num3); + num3++; + if (!flag) + { + break; + } + } + foreach (MonoCrossCompile.JobCompileAOT current2 in list) + { + if (current2.m_Exception != null) + { + UnityEngine.Debug.LogError(string.Format("Cross compilation job {0} failed.\n{1}", current2.m_input, current2.m_Exception.ToString())); + flag = false; + } + } + return flag; + } + private static bool IsDebugableAssembly(string fname) + { + fname = Path.GetFileName(fname); + return fname.StartsWith("Assembly", StringComparison.OrdinalIgnoreCase); + } + private static void CrossCompileAOT(BuildTarget target, string crossCompilerAbsolutePath, string assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, string input, string output, string additionalOptions) + { + string text = string.Empty; + if (!MonoCrossCompile.IsDebugableAssembly(input)) + { + crossCompileOptions &= ~CrossCompileOptions.Debugging; + crossCompileOptions &= ~CrossCompileOptions.LoadSymbols; + } + bool flag = (crossCompileOptions & CrossCompileOptions.Debugging) != CrossCompileOptions.Dynamic; + bool flag2 = (crossCompileOptions & CrossCompileOptions.LoadSymbols) != CrossCompileOptions.Dynamic; + bool flag3 = flag || flag2; + if (flag3) + { + text += "--debug "; + } + if (flag) + { + text += "--optimize=-linears "; + } + text += "--aot=full,asmonly,"; + if (flag3) + { + text += "write-symbols,"; + } + if ((crossCompileOptions & CrossCompileOptions.Debugging) != CrossCompileOptions.Dynamic) + { + text += "soft-debug,"; + } + else + { + if (!flag3) + { + text += "nodebug,"; + } + } + if (target != BuildTarget.iPhone) + { + text += "print-skipped,"; + } + if (additionalOptions != null & additionalOptions.Trim().Length > 0) + { + text = text + additionalOptions.Trim() + ","; + } + string fileName = Path.GetFileName(output); + string text2 = Path.Combine(assembliesAbsoluteDirectory, fileName); + if ((crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic) + { + text += "ficall,"; + } + if ((crossCompileOptions & CrossCompileOptions.Static) != CrossCompileOptions.Dynamic) + { + text += "static,"; + } + string text3 = text; + text = string.Concat(new string[] + { + text3, + "outfile=\"", + fileName, + "\" \"", + input, + "\" " + }); + Process process = new Process(); + process.StartInfo.FileName = crossCompilerAbsolutePath; + process.StartInfo.Arguments = text; + process.StartInfo.EnvironmentVariables["MONO_PATH"] = assembliesAbsoluteDirectory; + process.StartInfo.EnvironmentVariables["GAC_PATH"] = assembliesAbsoluteDirectory; + process.StartInfo.EnvironmentVariables["GC_DONT_GC"] = "yes please"; + if ((crossCompileOptions & CrossCompileOptions.ExplicitNullChecks) != CrossCompileOptions.Dynamic) + { + process.StartInfo.EnvironmentVariables["MONO_DEBUG"] = "explicit-null-checks"; + } + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.RedirectStandardOutput = true; + if (MonoCrossCompile.ArtifactsPath != null) + { + if (!Directory.Exists(MonoCrossCompile.ArtifactsPath)) + { + Directory.CreateDirectory(MonoCrossCompile.ArtifactsPath); + } + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "output.txt", process.StartInfo.FileName + "\n"); + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "output.txt", process.StartInfo.Arguments + "\n"); + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "output.txt", assembliesAbsoluteDirectory + "\n"); + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "output.txt", text2 + "\n"); + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "output.txt", input + "\n"); + File.AppendAllText(MonoCrossCompile.ArtifactsPath + "houtput.txt", fileName + "\n\n"); + File.Copy(assembliesAbsoluteDirectory + "\\" + input, MonoCrossCompile.ArtifactsPath + "\\" + input, true); + } + process.StartInfo.WorkingDirectory = assembliesAbsoluteDirectory; + MonoProcessUtility.RunMonoProcess(process, "AOT cross compiler", text2); + File.Move(text2, output); + if ((crossCompileOptions & CrossCompileOptions.Static) == CrossCompileOptions.Dynamic) + { + string text4 = Path.Combine(assembliesAbsoluteDirectory, fileName + ".def"); + if (File.Exists(text4)) + { + File.Move(text4, output + ".def"); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/MonoImporter.cs b/UnityEditor/UnityEditor/MonoImporter.cs new file mode 100644 index 00000000..fa7ddee7 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoImporter.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class MonoImporter : AssetImporter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetDefaultReferences(string[] name, UnityEngine.Object[] target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MonoScript[] GetAllRuntimeMonoScripts(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetExecutionOrder(MonoScript script, int order); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void CopyMonoScriptIconToImporters(MonoScript script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetExecutionOrder(MonoScript script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern MonoScript GetScript(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UnityEngine.Object GetDefaultReference(string name); + } +} diff --git a/UnityEditor/UnityEditor/MonoManager.cs b/UnityEditor/UnityEditor/MonoManager.cs new file mode 100644 index 00000000..cd8bfe6e --- /dev/null +++ b/UnityEditor/UnityEditor/MonoManager.cs @@ -0,0 +1,8 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class MonoManager : UnityEngine.Object + { + } +} diff --git a/UnityEditor/UnityEditor/MonoProcessUtility.cs b/UnityEditor/UnityEditor/MonoProcessUtility.cs new file mode 100644 index 00000000..3c5cafd6 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoProcessUtility.cs @@ -0,0 +1,109 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using UnityEngine; +namespace UnityEditor +{ + internal class MonoProcessUtility + { + public static string ProcessToString(Process process) + { + string text = string.Empty; + foreach (string text2 in process.StartInfo.EnvironmentVariables.Keys) + { + text += string.Format("{0} = '{1}'\n", text2, process.StartInfo.EnvironmentVariables[text2]); + } + return string.Concat(new string[] + { + process.StartInfo.FileName, + " ", + process.StartInfo.Arguments, + " current dir : ", + process.StartInfo.WorkingDirectory, + "\n Env: ", + text + }); + } + public static void RunMonoProcess(Process process, string name, string resultingFile) + { + StringBuilder output = new StringBuilder(string.Empty); + StringBuilder error = new StringBuilder(string.Empty); + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs dataLine) + { + if (!string.IsNullOrEmpty(dataLine.Data)) + { + output.Append(dataLine.Data); + } + }; + process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs dataLine) + { + if (!string.IsNullOrEmpty(dataLine.Data)) + { + error.Append(dataLine.Data); + } + }; + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + bool flag = process.WaitForExit(300000); + if (process.ExitCode != 0 || !File.Exists(resultingFile)) + { + process.CancelOutputRead(); + process.CancelErrorRead(); + string text = string.Concat(new object[] + { + "Failed ", + name, + ": ", + MonoProcessUtility.ProcessToString(process), + " result file exists: ", + File.Exists(resultingFile), + ". Timed out: ", + !flag + }); + text += "\n\n"; + string text2 = text; + text = string.Concat(new object[] + { + text2, + "stdout:\n", + output, + "\n\n" + }); + text = text + "stderr:\n" + error; + Console.WriteLine(text); + throw new UnityException(text); + } + } + public static string GetMonoExec(BuildTarget buildTarget) + { + string monoBinDirectory = BuildPipeline.GetMonoBinDirectory(buildTarget); + if (Application.platform == RuntimePlatform.OSXEditor) + { + return Path.Combine(monoBinDirectory, "mono"); + } + return Path.Combine(monoBinDirectory, "mono.exe"); + } + public static string GetMonoPath(BuildTarget buildTarget) + { + string monoLibDirectory = BuildPipeline.GetMonoLibDirectory(buildTarget); + return monoLibDirectory + Path.PathSeparator + "."; + } + public static Process PrepareMonoProcess(BuildTarget target, string workDir) + { + Process process = new Process(); + process.StartInfo.FileName = MonoProcessUtility.GetMonoExec(target); + process.StartInfo.EnvironmentVariables["_WAPI_PROCESS_HANDLE_OFFSET"] = "5"; + process.StartInfo.EnvironmentVariables["MONO_PATH"] = MonoProcessUtility.GetMonoPath(target); + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.CreateNoWindow = true; + process.StartInfo.WorkingDirectory = workDir; + return process; + } + } +} diff --git a/UnityEditor/UnityEditor/MonoReloadableIntPtr.cs b/UnityEditor/UnityEditor/MonoReloadableIntPtr.cs new file mode 100644 index 00000000..1dcbd470 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoReloadableIntPtr.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + internal struct MonoReloadableIntPtr + { + internal IntPtr m_IntPtr; + } +} diff --git a/UnityEditor/UnityEditor/MonoReloadableIntPtrClear.cs b/UnityEditor/UnityEditor/MonoReloadableIntPtrClear.cs new file mode 100644 index 00000000..a60a7fbb --- /dev/null +++ b/UnityEditor/UnityEditor/MonoReloadableIntPtrClear.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + internal struct MonoReloadableIntPtrClear + { + internal IntPtr m_IntPtr; + } +} diff --git a/UnityEditor/UnityEditor/MonoScript.cs b/UnityEditor/UnityEditor/MonoScript.cs new file mode 100644 index 00000000..d28ae044 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoScript.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class MonoScript : TextAsset + { + internal extern ScriptableObject editorGraphData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern MonoScript(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Type GetClass(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MonoScript FromMonoBehaviour(MonoBehaviour behaviour); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MonoScript FromScriptableObject(ScriptableObject scriptableObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool GetScriptTypeWasJustCreatedFromComponentMenu(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetScriptTypeWasJustCreatedFromComponentMenu(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Init(string scriptContents, string className, string nameSpace, string assemblyName, bool isEditorScript); + } +} diff --git a/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs b/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs new file mode 100644 index 00000000..83dea313 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(MonoImporter))] + internal class MonoScriptImporterInspector : AssetImporterInspector + { + private const int m_RowHeight = 16; + private static GUIContent s_HelpIcon; + private static GUIContent s_TitleSettingsIcon; + private SerializedObject m_TargetObject; + private SerializedProperty m_Icon; + internal override void OnHeaderControlsGUI() + { + TextAsset textAsset = base.assetEditor.target as TextAsset; + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Open...", EditorStyles.miniButton, new GUILayoutOption[0])) + { + AssetDatabase.OpenAsset(textAsset); + GUIUtility.ExitGUI(); + } + if (textAsset as MonoScript && GUILayout.Button("Execution Order...", EditorStyles.miniButton, new GUILayoutOption[0])) + { + EditorApplication.ExecuteMenuItem("Edit/Project Settings/Script Execution Order"); + GUIUtility.ExitGUI(); + } + } + internal override void OnHeaderIconGUI(Rect iconRect) + { + if (this.m_Icon == null) + { + this.m_TargetObject = new SerializedObject(base.assetEditor.targets); + this.m_Icon = this.m_TargetObject.FindProperty("m_Icon"); + } + EditorGUI.ObjectIconDropDown(iconRect, base.assetEditor.targets, true, null, this.m_Icon); + } + [MenuItem("CONTEXT/MonoImporter/Reset")] + private static void ResetDefaultReferences(MenuCommand command) + { + MonoImporter monoImporter = command.context as MonoImporter; + monoImporter.SetDefaultReferences(new string[0], new UnityEngine.Object[0]); + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter)); + } + private void ShowFieldInfo(Type type, MonoImporter importer, List names, List objects, ref bool didModify) + { + if (type == null || !type.IsSubclassOf(typeof(MonoBehaviour))) + { + return; + } + this.ShowFieldInfo(type.BaseType, importer, names, objects, ref didModify); + FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + FieldInfo[] array = fields; + int i = 0; + while (i < array.Length) + { + FieldInfo fieldInfo = array[i]; + if (fieldInfo.IsPublic) + { + goto IL_77; + } + object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(SerializeField), true); + if (customAttributes != null && customAttributes.Length != 0) + { + goto IL_77; + } + IL_FC: + i++; + continue; + IL_77: + if (!fieldInfo.FieldType.IsSubclassOf(typeof(UnityEngine.Object)) && fieldInfo.FieldType != typeof(UnityEngine.Object)) + { + goto IL_FC; + } + UnityEngine.Object defaultReference = importer.GetDefaultReference(fieldInfo.Name); + UnityEngine.Object @object = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(fieldInfo.Name), defaultReference, fieldInfo.FieldType, false, new GUILayoutOption[0]); + names.Add(fieldInfo.Name); + objects.Add(@object); + if (defaultReference != @object) + { + didModify = true; + goto IL_FC; + } + goto IL_FC; + } + } + public override void OnInspectorGUI() + { + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + MonoImporter monoImporter = this.target as MonoImporter; + MonoScript script = monoImporter.GetScript(); + if (script) + { + List list = new List(); + List list2 = new List(); + bool flag = false; + Type @class = script.GetClass(); + this.ShowFieldInfo(@class, monoImporter, list, list2, ref flag); + if (flag) + { + monoImporter.SetDefaultReferences(list.ToArray(), list2.ToArray()); + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter)); + } + } + EditorGUIUtility.SetIconSize(iconSize); + } + } +} diff --git a/UnityEditor/UnityEditor/MonoScriptInspector.cs b/UnityEditor/UnityEditor/MonoScriptInspector.cs new file mode 100644 index 00000000..5c2f9896 --- /dev/null +++ b/UnityEditor/UnityEditor/MonoScriptInspector.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(MonoScript))] + internal class MonoScriptInspector : TextAssetInspector + { + protected override void OnHeaderGUI() + { + } + } +} diff --git a/UnityEditor/UnityEditor/MouseCursor.cs b/UnityEditor/UnityEditor/MouseCursor.cs new file mode 100644 index 00000000..67c9c75f --- /dev/null +++ b/UnityEditor/UnityEditor/MouseCursor.cs @@ -0,0 +1,27 @@ +using System; +namespace UnityEditor +{ + public enum MouseCursor + { + Arrow, + Text, + ResizeVertical, + ResizeHorizontal, + Link, + SlideArrow, + ResizeUpRight, + ResizeUpLeft, + MoveArrow, + RotateArrow, + ScaleArrow, + ArrowPlus, + ArrowMinus, + Pan, + Orbit, + Zoom, + FPS, + CustomCursor, + SplitResizeUpDown, + SplitResizeLeftRight + } +} diff --git a/UnityEditor/UnityEditor/MoveTool.cs b/UnityEditor/UnityEditor/MoveTool.cs new file mode 100644 index 00000000..52414cc4 --- /dev/null +++ b/UnityEditor/UnityEditor/MoveTool.cs @@ -0,0 +1,30 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MoveTool : ManipulationTool + { + private static MoveTool s_Instance; + public static void OnGUI(SceneView view) + { + if (MoveTool.s_Instance == null) + { + MoveTool.s_Instance = new MoveTool(); + } + MoveTool.s_Instance.OnToolGUI(view); + } + public override void ToolGUI(SceneView view, Vector3 handlePosition, bool isStatic) + { + TransformManipulator.BeginManipulationHandling(false); + EditorGUI.BeginChangeCheck(); + Vector3 a = Handles.PositionHandle(handlePosition, Tools.handleRotation); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + Vector3 positionDelta = a - TransformManipulator.mouseDownHandlePosition; + ManipulationToolUtility.SetMinDragDifferenceForPos(handlePosition); + TransformManipulator.SetPositionDelta(positionDelta); + } + TransformManipulator.EndManipulationHandling(); + } + } +} diff --git a/UnityEditor/UnityEditor/MovieImporter.cs b/UnityEditor/UnityEditor/MovieImporter.cs new file mode 100644 index 00000000..7107086f --- /dev/null +++ b/UnityEditor/UnityEditor/MovieImporter.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class MovieImporter : AssetImporter + { + public extern float quality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool linearTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float duration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + } +} diff --git a/UnityEditor/UnityEditor/MovieImporterInspector.cs b/UnityEditor/UnityEditor/MovieImporterInspector.cs new file mode 100644 index 00000000..a79d6c1d --- /dev/null +++ b/UnityEditor/UnityEditor/MovieImporterInspector.cs @@ -0,0 +1,77 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(MovieImporter))] + internal class MovieImporterInspector : AssetImporterInspector + { + private float m_quality; + private float m_duration; + private bool m_linearTexture; + private static GUIContent linearTextureContent = EditorGUIUtility.TextContent("TextureImporter.LinearTexture"); + internal override bool showImportedObject + { + get + { + return false; + } + } + internal override bool HasModified() + { + MovieImporter movieImporter = this.target as MovieImporter; + return movieImporter.quality != this.m_quality || movieImporter.linearTexture != this.m_linearTexture; + } + internal override void ResetValues() + { + MovieImporter movieImporter = this.target as MovieImporter; + this.m_quality = movieImporter.quality; + this.m_linearTexture = movieImporter.linearTexture; + this.m_duration = movieImporter.duration; + } + internal override void Apply() + { + MovieImporter movieImporter = this.target as MovieImporter; + movieImporter.quality = this.m_quality; + movieImporter.linearTexture = this.m_linearTexture; + } + public override void OnInspectorGUI() + { + MovieImporter x = this.target as MovieImporter; + if (x != null) + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + this.m_linearTexture = EditorGUILayout.Toggle(MovieImporterInspector.linearTextureContent, this.m_linearTexture, new GUILayoutOption[0]); + int num = (int)(this.GetVideoBitrateForQuality((double)this.m_quality) + this.GetAudioBitrateForQuality((double)this.m_quality)); + float num2 = (float)(num / 8) * this.m_duration; + float num3 = 1048576f; + this.m_quality = EditorGUILayout.Slider("Quality", this.m_quality, 0f, 1f, new GUILayoutOption[0]); + GUILayout.Label(string.Format("Approx. {0:0.00} " + ((num2 >= num3) ? "MB" : "kB") + ", {1} kbps", num2 / ((num2 >= num3) ? num3 : 1024f), num / 1000), EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + base.ApplyRevertGUI(); + MovieTexture movieTexture = base.assetEditor.target as MovieTexture; + if (movieTexture && movieTexture.loop) + { + EditorGUILayout.Space(); + movieTexture.loop = EditorGUILayout.Toggle("Loop", movieTexture.loop, new GUILayoutOption[0]); + GUILayout.Label("The Loop setting in the Inspector is obsolete. Use the Scripting API to control looping instead.\n\nThe loop setting will be disabled on next re-import or by disabling it above.", EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private double GetAudioBitrateForQuality(double f) + { + return 56000.0 + 200000.0 * f; + } + private double GetVideoBitrateForQuality(double f) + { + return 100000.0 + 8000000.0 * f; + } + private double GetAudioQualityForBitrate(double f) + { + return (f - 56000.0) / 200000.0; + } + private double GetVideoQualityForBitrate(double f) + { + return (f - 100000.0) / 8000000.0; + } + } +} diff --git a/UnityEditor/UnityEditor/MovieTextureInspector.cs b/UnityEditor/UnityEditor/MovieTextureInspector.cs new file mode 100644 index 00000000..564214a7 --- /dev/null +++ b/UnityEditor/UnityEditor/MovieTextureInspector.cs @@ -0,0 +1,101 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(MovieTexture))] + internal class MovieTextureInspector : TextureInspector + { + private static GUIContent[] s_PlayIcons = new GUIContent[2]; + private static void Init() + { + MovieTextureInspector.s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff"); + MovieTextureInspector.s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn"); + } + protected override void OnEnable() + { + } + public override void OnInspectorGUI() + { + } + public override void OnPreviewSettings() + { + MovieTextureInspector.Init(); + EditorGUI.BeginDisabledGroup(Application.isPlaying || base.targets.Length > 1); + MovieTexture movieTexture = this.target as MovieTexture; + AudioClip audioClip = movieTexture.audioClip; + bool flag = PreviewGUI.CycleButton((!movieTexture.isPlaying) ? 0 : 1, MovieTextureInspector.s_PlayIcons) != 0; + if (flag != movieTexture.isPlaying) + { + if (flag) + { + movieTexture.Stop(); + movieTexture.Play(); + if (audioClip != null) + { + AudioUtil.PlayClip(audioClip); + } + } + else + { + movieTexture.Pause(); + if (audioClip != null) + { + AudioUtil.PauseClip(audioClip); + } + } + } + EditorGUI.EndDisabledGroup(); + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type == EventType.Repaint) + { + background.Draw(r, false, false, false, false); + } + MovieTexture movieTexture = this.target as MovieTexture; + float num = Mathf.Min(Mathf.Min(r.width / (float)movieTexture.width, r.height / (float)movieTexture.height), 1f); + Rect rect = new Rect(r.x, r.y, (float)movieTexture.width * num, (float)movieTexture.height * num); + PreviewGUI.BeginScrollView(r, this.m_Pos, rect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); + EditorGUI.DrawPreviewTexture(rect, movieTexture, null, ScaleMode.StretchToFill); + this.m_Pos = PreviewGUI.EndScrollView(); + if (movieTexture.isPlaying) + { + GUIView.current.Repaint(); + } + if (Application.isPlaying) + { + if (movieTexture.isPlaying) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10f, r.width, 20f), "Can't pause preview when in play mode"); + } + else + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10f, r.width, 20f), "Can't start preview when in play mode"); + } + } + } + public void OnDisable() + { + MovieTexture movieTexture = this.target as MovieTexture; + if (!Application.isPlaying && movieTexture != null) + { + AudioClip audioClip = movieTexture.audioClip; + movieTexture.Stop(); + if (audioClip != null) + { + AudioUtil.StopClip(audioClip); + } + } + } + public override string GetInfoString() + { + string text = base.GetInfoString(); + MovieTexture movieTexture = this.target as MovieTexture; + if (!movieTexture.isReadyToPlay) + { + text += "/nNot ready to play yet."; + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditor/MultilineDrawer.cs b/UnityEditor/UnityEditor/MultilineDrawer.cs new file mode 100644 index 00000000..988b2032 --- /dev/null +++ b/UnityEditor/UnityEditor/MultilineDrawer.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomPropertyDrawer(typeof(MultilineAttribute))] + internal sealed class MultilineDrawer : PropertyDrawer + { + private const int kLineHeight = 13; + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + if (property.propertyType == SerializedPropertyType.String) + { + label = EditorGUI.BeginProperty(position, label, property); + position = EditorGUI.MultiFieldPrefixLabel(position, 0, label, 1); + EditorGUI.BeginChangeCheck(); + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + string stringValue = EditorGUI.TextArea(position, property.stringValue); + EditorGUI.indentLevel = indentLevel; + if (EditorGUI.EndChangeCheck()) + { + property.stringValue = stringValue; + } + EditorGUI.EndProperty(); + } + else + { + EditorGUI.LabelField(position, label.text, "Use Multiline with string."); + } + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f + (float)((((MultilineAttribute)base.attribute).lines - 1) * 13); + } + } +} diff --git a/UnityEditor/UnityEditor/MuscleClipEditorUtilities.cs b/UnityEditor/UnityEditor/MuscleClipEditorUtilities.cs new file mode 100644 index 00000000..b0909cf8 --- /dev/null +++ b/UnityEditor/UnityEditor/MuscleClipEditorUtilities.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class MuscleClipEditorUtilities + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MuscleClipQualityInfo GetMuscleClipQualityInfo(AnimationClip clip, float startTime, float stopTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CalculateQualityCurves(AnimationClip clip, QualityCurvesTime time, Vector2[] poseCurve, Vector2[] rotationCurve, Vector2[] heightCurve, Vector2[] positionCurve); + } +} diff --git a/UnityEditor/UnityEditor/MuscleClipQualityInfo.cs b/UnityEditor/UnityEditor/MuscleClipQualityInfo.cs new file mode 100644 index 00000000..7761068a --- /dev/null +++ b/UnityEditor/UnityEditor/MuscleClipQualityInfo.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal sealed class MuscleClipQualityInfo + { + public float loop; + public float loopOrientation; + public float loopPositionY; + public float loopPositionXZ; + } +} diff --git a/UnityEditor/UnityEditor/NETVersion.cs b/UnityEditor/UnityEditor/NETVersion.cs new file mode 100644 index 00000000..7c719d3d --- /dev/null +++ b/UnityEditor/UnityEditor/NETVersion.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum NETVersion + { + NET_1_1, + NET_2_1 + } +} diff --git a/UnityEditor/UnityEditor/NameConflictResolution.cs b/UnityEditor/UnityEditor/NameConflictResolution.cs new file mode 100644 index 00000000..c9d92e04 --- /dev/null +++ b/UnityEditor/UnityEditor/NameConflictResolution.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + internal enum NameConflictResolution + { + Unresolved, + RenameLocal, + RenameRemote + } +} diff --git a/UnityEditor/UnityEditor/NavMeshAgentInspector.cs b/UnityEditor/UnityEditor/NavMeshAgentInspector.cs new file mode 100644 index 00000000..12d76e33 --- /dev/null +++ b/UnityEditor/UnityEditor/NavMeshAgentInspector.cs @@ -0,0 +1,90 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(NavMeshAgent))] + internal class NavMeshAgentInspector : Editor + { + private SerializedProperty m_WalkableMask; + private SerializedProperty m_Radius; + private SerializedProperty m_Speed; + private SerializedProperty m_Acceleration; + private SerializedProperty m_AngularSpeed; + private SerializedProperty m_StoppingDistance; + private SerializedProperty m_AutoTraverseOffMeshLink; + private SerializedProperty m_AutoBraking; + private SerializedProperty m_AutoRepath; + private SerializedProperty m_Height; + private SerializedProperty m_BaseOffset; + private SerializedProperty m_ObstacleAvoidanceType; + private SerializedProperty m_AvoidancePriority; + private void OnEnable() + { + this.m_WalkableMask = base.serializedObject.FindProperty("m_WalkableMask"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_Speed = base.serializedObject.FindProperty("m_Speed"); + this.m_Acceleration = base.serializedObject.FindProperty("m_Acceleration"); + this.m_AngularSpeed = base.serializedObject.FindProperty("m_AngularSpeed"); + this.m_StoppingDistance = base.serializedObject.FindProperty("m_StoppingDistance"); + this.m_AutoTraverseOffMeshLink = base.serializedObject.FindProperty("m_AutoTraverseOffMeshLink"); + this.m_AutoBraking = base.serializedObject.FindProperty("m_AutoBraking"); + this.m_AutoRepath = base.serializedObject.FindProperty("m_AutoRepath"); + this.m_Height = base.serializedObject.FindProperty("m_Height"); + this.m_BaseOffset = base.serializedObject.FindProperty("m_BaseOffset"); + this.m_ObstacleAvoidanceType = base.serializedObject.FindProperty("m_ObstacleAvoidanceType"); + this.m_AvoidancePriority = base.serializedObject.FindProperty("avoidancePriority"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Speed, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Acceleration, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AngularSpeed, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_StoppingDistance, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AutoTraverseOffMeshLink, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AutoBraking, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AutoRepath, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BaseOffset, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ObstacleAvoidanceType, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AvoidancePriority, new GUILayoutOption[0]); + string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); + int intValue = this.m_WalkableMask.intValue; + int num = 0; + for (int i = 0; i < navMeshLayerNames.Length; i++) + { + int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]); + if ((1 << navMeshLayerFromName & intValue) > 0) + { + num |= 1 << i; + } + } + Rect rect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.layerMaskField); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_WalkableMask.hasMultipleDifferentValues; + int num2 = EditorGUI.MaskField(rect, "NavMesh Walkable", num, navMeshLayerNames, EditorStyles.layerMaskField); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + if (num2 == -1) + { + this.m_WalkableMask.intValue = -1; + } + else + { + int num3 = 0; + for (int j = 0; j < navMeshLayerNames.Length; j++) + { + if ((num2 >> j & 1) > 0) + { + num3 |= 1 << GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[j]); + } + } + this.m_WalkableMask.intValue = num3; + } + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/NavMeshBuilder.cs b/UnityEditor/UnityEditor/NavMeshBuilder.cs new file mode 100644 index 00000000..aa16b7e7 --- /dev/null +++ b/UnityEditor/UnityEditor/NavMeshBuilder.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class NavMeshBuilder + { + public static extern UnityEngine.Object navMeshSettingsObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isRunning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BuildNavMesh(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BuildNavMeshAsync(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearAllNavMeshes(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Cancel(); + } +} diff --git a/UnityEditor/UnityEditor/NavMeshEditorWindow.cs b/UnityEditor/UnityEditor/NavMeshEditorWindow.cs new file mode 100644 index 00000000..4e30df3b --- /dev/null +++ b/UnityEditor/UnityEditor/NavMeshEditorWindow.cs @@ -0,0 +1,477 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class NavMeshEditorWindow : EditorWindow, IHasCustomMenu + { + private enum Mode + { + ObjectSettings, + BakeSettings, + LayerSettings + } + private class Styles + { + public readonly GUIContent m_AgentRadiusContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.Radius"); + public readonly GUIContent m_AgentHeightContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.Height"); + public readonly GUIContent m_AgentSlopeContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.MaxSlope"); + public readonly GUIContent m_AgentDropContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.DropHeight"); + public readonly GUIContent m_AgentClimbContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.StepHeight"); + public readonly GUIContent m_AgentJumpContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.JumpDistance"); + public readonly GUIContent m_AgentPlacementContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.HeightMesh"); + public readonly GUIContent m_MinRegionAreaContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.MinRegionArea"); + public readonly GUIContent m_WidthInaccuracyContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.WidthInaccuracy"); + public readonly GUIContent m_HeightInaccuracyContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.HeightInaccuracy"); + public readonly GUIContent m_GeneralHeader = new GUIContent("General"); + public readonly GUIContent m_OffmeshHeader = new GUIContent("Generated Off Mesh Links"); + public readonly GUIContent m_AdvancedHeader = new GUIContent("Advanced"); + public readonly GUIContent[] m_ModeToggles = new GUIContent[] + { + EditorGUIUtility.TextContent("NavmeshEditor.ObjectSettings"), + EditorGUIUtility.TextContent("NavmeshEditor.BakeSettings"), + EditorGUIUtility.TextContent("NavmeshEditor.LayerSettings") + }; + } + private const string kRootPath = "m_BuildSettings."; + private static NavMeshEditorWindow s_MsNavMeshEditorWindow; + private SerializedObject m_Object; + private SerializedProperty m_AgentRadius; + private SerializedProperty m_AgentHeight; + private SerializedProperty m_AgentSlope; + private SerializedProperty m_AgentClimb; + private SerializedProperty m_LedgeDropHeight; + private SerializedProperty m_MaxJumpAcrossDistance; + private SerializedProperty m_AccuratePlacement; + private SerializedProperty m_MinRegionArea; + private SerializedProperty m_WidthInaccuracy; + private SerializedProperty m_HeightInaccuracy; + private static NavMeshEditorWindow.Styles s_Styles; + private Vector2 m_ScrollPos = Vector2.zero; + private bool m_HasSelectedNavMeshAgents; + private NavMeshEditorWindow.Mode m_Mode; + private bool m_Advanced; + [MenuItem("Window/Navigation", false, 2100)] + public static void SetupWindow() + { + NavMeshEditorWindow window = EditorWindow.GetWindow(new Type[] + { + typeof(InspectorWindow) + }); + window.title = EditorGUIUtility.TextContent("NavmeshEditor.WindowTitle").text; + window.minSize = new Vector2(300f, 360f); + } + public void OnEnable() + { + NavMeshEditorWindow.s_MsNavMeshEditorWindow = this; + NavMeshEditorWindow.s_Styles = new NavMeshEditorWindow.Styles(); + this.Init(); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + base.Repaint(); + } + private void Init() + { + this.m_Object = new SerializedObject(NavMeshBuilder.navMeshSettingsObject); + this.m_AgentRadius = this.m_Object.FindProperty("m_BuildSettings.agentRadius"); + this.m_AgentHeight = this.m_Object.FindProperty("m_BuildSettings.agentHeight"); + this.m_AgentSlope = this.m_Object.FindProperty("m_BuildSettings.agentSlope"); + this.m_LedgeDropHeight = this.m_Object.FindProperty("m_BuildSettings.ledgeDropHeight"); + this.m_AgentClimb = this.m_Object.FindProperty("m_BuildSettings.agentClimb"); + this.m_MaxJumpAcrossDistance = this.m_Object.FindProperty("m_BuildSettings.maxJumpAcrossDistance"); + this.m_AccuratePlacement = this.m_Object.FindProperty("m_BuildSettings.accuratePlacement"); + this.m_MinRegionArea = this.m_Object.FindProperty("m_BuildSettings.minRegionArea"); + this.m_WidthInaccuracy = this.m_Object.FindProperty("m_BuildSettings.widthInaccuracy"); + this.m_HeightInaccuracy = this.m_Object.FindProperty("m_BuildSettings.heightInaccuracy"); + } + public void OnDisable() + { + NavMeshEditorWindow.s_MsNavMeshEditorWindow = null; + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + } + private void OnSelectionChange() + { + this.m_HasSelectedNavMeshAgents = false; + Transform[] transforms = Selection.GetTransforms((SelectionMode)12); + Transform[] array = transforms; + for (int i = 0; i < array.Length; i++) + { + Transform transform = array[i]; + if (transform.gameObject.GetComponent() != null) + { + this.m_HasSelectedNavMeshAgents = true; + break; + } + } + this.m_ScrollPos = Vector2.zero; + if (this.m_Mode == NavMeshEditorWindow.Mode.ObjectSettings) + { + base.Repaint(); + } + } + private void ModeToggle() + { + this.m_Mode = (NavMeshEditorWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, NavMeshEditorWindow.s_Styles.m_ModeToggles, "LargeButton", new GUILayoutOption[0]); + } + public void OnGUI() + { + if (this.m_Object.targetObject == null) + { + this.Init(); + } + this.m_Object.Update(); + EditorGUIUtility.labelWidth = 130f; + EditorGUILayout.Space(); + this.ModeToggle(); + EditorGUILayout.Space(); + this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, new GUILayoutOption[0]); + switch (this.m_Mode) + { + case NavMeshEditorWindow.Mode.ObjectSettings: + NavMeshEditorWindow.ObjectSettings(); + break; + case NavMeshEditorWindow.Mode.BakeSettings: + this.BakeSettings(); + break; + case NavMeshEditorWindow.Mode.LayerSettings: + this.LayerSettings(); + break; + } + EditorGUILayout.EndScrollView(); + NavMeshEditorWindow.BakeButtons(); + this.m_Object.ApplyModifiedProperties(); + } + public void OnBecameVisible() + { + if (NavMeshVisualizationSettings.showNavigation) + { + return; + } + NavMeshVisualizationSettings.showNavigation = true; + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + public void OnBecameInvisible() + { + NavMeshVisualizationSettings.showNavigation = false; + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + private static void RepaintSceneAndGameViews() + { + SceneView.RepaintAll(); + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(GameView)); + for (int i = 0; i < array.Length; i++) + { + GameView gameView = (GameView)array[i]; + gameView.Repaint(); + } + } + public void OnSceneViewGUI(SceneView sceneView) + { + if (!NavMeshVisualizationSettings.showNavigation) + { + return; + } + SceneViewOverlay.Window(new GUIContent("Navmesh Display"), new SceneViewOverlay.WindowFunction(NavMeshEditorWindow.DisplayControls), 300, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + if (this.m_HasSelectedNavMeshAgents) + { + SceneViewOverlay.Window(new GUIContent("Agent Display"), new SceneViewOverlay.WindowFunction(NavMeshEditorWindow.DisplayAgentControls), 300, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + } + } + private static void DisplayControls(UnityEngine.Object target, SceneView sceneView) + { + EditorGUIUtility.labelWidth = 150f; + bool flag = false; + bool showNavMesh = NavMeshVisualizationSettings.showNavMesh; + if (showNavMesh != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowNavMesh"), showNavMesh, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showNavMesh = !showNavMesh; + flag = true; + } + EditorGUI.BeginDisabledGroup(!NavMeshVisualizationSettings.hasHeightMesh); + bool showHeightMesh = NavMeshVisualizationSettings.showHeightMesh; + if (showHeightMesh != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowHeightMesh"), showHeightMesh, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showHeightMesh = !showHeightMesh; + flag = true; + } + EditorGUI.EndDisabledGroup(); + if (flag) + { + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + } + private static void DisplayAgentControls(UnityEngine.Object target, SceneView sceneView) + { + EditorGUIUtility.labelWidth = 150f; + bool flag = false; + bool showAgentPath = NavMeshVisualizationSettings.showAgentPath; + if (showAgentPath != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentPath"), showAgentPath, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showAgentPath = !showAgentPath; + flag = true; + } + bool showAgentPathInfo = NavMeshVisualizationSettings.showAgentPathInfo; + if (showAgentPathInfo != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentPathInfo"), showAgentPathInfo, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showAgentPathInfo = !showAgentPathInfo; + flag = true; + } + bool showAgentNeighbours = NavMeshVisualizationSettings.showAgentNeighbours; + if (showAgentNeighbours != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentNeighbours"), showAgentNeighbours, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showAgentNeighbours = !showAgentNeighbours; + flag = true; + } + bool showAgentWalls = NavMeshVisualizationSettings.showAgentWalls; + if (showAgentWalls != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentWalls"), showAgentWalls, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showAgentWalls = !showAgentWalls; + flag = true; + } + if (flag) + { + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Reset Bake Settings"), false, new GenericMenu.MenuFunction(this.ResetBakeSettings)); + } + private void ResetBakeSettings() + { + Unsupported.SmartReset(NavMeshBuilder.navMeshSettingsObject); + } + public static void BackgroundTaskStatusChanged() + { + if (NavMeshEditorWindow.s_MsNavMeshEditorWindow != null) + { + NavMeshEditorWindow.s_MsNavMeshEditorWindow.Repaint(); + } + } + private static IEnumerable GetObjectsRecurse(GameObject root) + { + List list = new List + { + root + }; + foreach (Transform transform in root.transform) + { + list.AddRange(NavMeshEditorWindow.GetObjectsRecurse(transform.gameObject)); + } + return list; + } + private static List GetObjects(bool includeChildren) + { + if (includeChildren) + { + List list = new List(); + GameObject[] gameObjects = Selection.gameObjects; + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject root = gameObjects[i]; + list.AddRange(NavMeshEditorWindow.GetObjectsRecurse(root)); + } + return list; + } + return new List(Selection.gameObjects); + } + private static bool SelectionHasChildren() + { + return Selection.gameObjects.Any((GameObject obj) => obj.transform.childCount > 0); + } + private static void SetNavMeshLayer(int layer, bool includeChildren) + { + List objects = NavMeshEditorWindow.GetObjects(includeChildren); + if (objects.Count <= 0) + { + return; + } + Undo.RecordObjects(objects.ToArray(), "Change NavMesh layer"); + foreach (GameObject current in objects) + { + GameObjectUtility.SetNavMeshLayer(current, layer); + } + } + private static void ObjectSettings() + { + bool flag = true; + SceneModeUtility.SearchBar(new Type[] + { + typeof(MeshRenderer), + typeof(Terrain) + }); + EditorGUILayout.Space(); + GameObject[] array; + MeshRenderer[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length > 0) + { + flag = false; + NavMeshEditorWindow.ObjectSettings(selectedObjectsOfType, array); + } + Terrain[] selectedObjectsOfType2 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length > 0) + { + flag = false; + NavMeshEditorWindow.ObjectSettings(selectedObjectsOfType2, array); + } + if (flag) + { + GUILayout.Label("Select a MeshRenderer or a Terrain from the scene.", EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private static void ObjectSettings(UnityEngine.Object[] components, GameObject[] gos) + { + EditorGUILayout.MultiSelectionObjectTitleBar(components); + SerializedObject serializedObject = new SerializedObject(gos); + EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Navigation Static", serializedObject.FindProperty("m_StaticEditorFlags"), 8)); + SceneModeUtility.StaticFlagField("OffMeshLink Generation", serializedObject.FindProperty("m_StaticEditorFlags"), 32); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_NavMeshLayer"); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = serializedProperty.hasMultipleDifferentValues; + string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); + int navMeshLayer = GameObjectUtility.GetNavMeshLayer(gos[0]); + int selectedIndex = -1; + for (int i = 0; i < navMeshLayerNames.Length; i++) + { + if (GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]) == navMeshLayer) + { + selectedIndex = i; + break; + } + } + int num = EditorGUILayout.Popup("Navigation Layer", selectedIndex, navMeshLayerNames, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[num]); + GameObjectUtility.ShouldIncludeChildren shouldIncludeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(Selection.gameObjects, "Change Navigation Layer", "Do you want change the navigation layer to " + navMeshLayerNames[num] + " for all the child objects as well?"); + if (shouldIncludeChildren != GameObjectUtility.ShouldIncludeChildren.Cancel) + { + serializedProperty.intValue = navMeshLayerFromName; + NavMeshEditorWindow.SetNavMeshLayer(navMeshLayerFromName, shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); + } + } + EditorGUI.EndDisabledGroup(); + serializedObject.ApplyModifiedProperties(); + } + private void BakeSettings() + { + EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_GeneralHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + float num = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentRadiusContent, this.m_AgentRadius.floatValue, new GUILayoutOption[0]); + if (num >= 0.001f && !Mathf.Approximately(num - this.m_AgentRadius.floatValue, 0f)) + { + this.m_AgentRadius.floatValue = num; + } + float num2 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentHeightContent, this.m_AgentHeight.floatValue, new GUILayoutOption[0]); + if (num2 >= 0.001f && !Mathf.Approximately(num2 - this.m_AgentHeight.floatValue, 0f)) + { + this.m_AgentHeight.floatValue = num2; + } + EditorGUILayout.Slider(this.m_AgentSlope, 0f, 90f, NavMeshEditorWindow.s_Styles.m_AgentSlopeContent, new GUILayoutOption[0]); + float num3 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentClimbContent, this.m_AgentClimb.floatValue, new GUILayoutOption[0]); + if (num3 >= 0f && !Mathf.Approximately(this.m_AgentClimb.floatValue - num3, 0f)) + { + this.m_AgentClimb.floatValue = num3; + } + if (this.m_AgentClimb.floatValue >= this.m_AgentHeight.floatValue) + { + EditorGUILayout.HelpBox("Step height should be less than agent height.\nClamping step height to " + this.m_AgentHeight.floatValue + ".", MessageType.Warning); + } + EditorGUILayout.Space(); + EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_OffmeshHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag = !Application.HasProLicense(); + if (flag) + { + EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); + if (this.m_LedgeDropHeight.floatValue != 0f) + { + this.m_LedgeDropHeight.floatValue = 0f; + } + if (this.m_MaxJumpAcrossDistance.floatValue != 0f) + { + this.m_MaxJumpAcrossDistance.floatValue = 0f; + } + GUI.enabled = false; + } + float num4 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentDropContent, this.m_LedgeDropHeight.floatValue, new GUILayoutOption[0]); + if (num4 >= 0f && !Mathf.Approximately(num4 - this.m_LedgeDropHeight.floatValue, 0f)) + { + this.m_LedgeDropHeight.floatValue = num4; + } + float num5 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentJumpContent, this.m_MaxJumpAcrossDistance.floatValue, new GUILayoutOption[0]); + if (num5 >= 0f && !Mathf.Approximately(num5 - this.m_MaxJumpAcrossDistance.floatValue, 0f)) + { + this.m_MaxJumpAcrossDistance.floatValue = num5; + } + if (flag) + { + GUI.enabled = true; + } + EditorGUILayout.Space(); + this.m_Advanced = GUILayout.Toggle(this.m_Advanced, NavMeshEditorWindow.s_Styles.m_AdvancedHeader, EditorStyles.foldout, new GUILayoutOption[0]); + if (this.m_Advanced) + { + float num6 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_MinRegionAreaContent, this.m_MinRegionArea.floatValue, new GUILayoutOption[0]); + if (num6 >= 0f && num6 != this.m_MinRegionArea.floatValue) + { + this.m_MinRegionArea.floatValue = num6; + } + EditorGUILayout.Slider(this.m_WidthInaccuracy, 1f, 100f, NavMeshEditorWindow.s_Styles.m_WidthInaccuracyContent, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_HeightInaccuracy, 1f, 100f, NavMeshEditorWindow.s_Styles.m_HeightInaccuracyContent, new GUILayoutOption[0]); + bool flag2 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_AgentPlacementContent, this.m_AccuratePlacement.boolValue, new GUILayoutOption[0]); + if (flag2 != this.m_AccuratePlacement.boolValue) + { + this.m_AccuratePlacement.boolValue = flag2; + } + } + } + private void LayerSettings() + { + UnityEngine.Object serializedAssetInterfaceSingleton = Unsupported.GetSerializedAssetInterfaceSingleton("NavMeshLayers"); + SerializedObject obj = new SerializedObject(serializedAssetInterfaceSingleton); + Editor.DoDrawDefaultInspector(obj); + } + private static void BakeButtons() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + bool enabled = GUI.enabled; + GUI.enabled &= !Application.isPlaying; + if (GUILayout.Button("Clear", new GUILayoutOption[] + { + GUILayout.Width(95f) + })) + { + NavMeshBuilder.ClearAllNavMeshes(); + } + GUI.enabled = enabled; + if (NavMeshBuilder.isRunning) + { + if (GUILayout.Button("Cancel", new GUILayoutOption[] + { + GUILayout.Width(95f) + })) + { + NavMeshBuilder.Cancel(); + } + } + else + { + enabled = GUI.enabled; + GUI.enabled &= !Application.isPlaying; + if (GUILayout.Button("Bake", new GUILayoutOption[] + { + GUILayout.Width(95f) + })) + { + NavMeshBuilder.BuildNavMeshAsync(); + } + GUI.enabled = enabled; + } + GUILayout.EndHorizontal(); + EditorGUILayout.Space(); + } + } +} diff --git a/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs b/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs new file mode 100644 index 00000000..a0a0cddf --- /dev/null +++ b/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs @@ -0,0 +1,34 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(NavMeshObstacle))] + internal class NavMeshObstacleInspector : Editor + { + private SerializedProperty m_Radius; + private SerializedProperty m_Height; + private SerializedProperty m_MoveThreshold; + private SerializedProperty m_Carve; + private void OnEnable() + { + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_Height = base.serializedObject.FindProperty("m_Height"); + this.m_MoveThreshold = base.serializedObject.FindProperty("m_MoveThreshold"); + this.m_Carve = base.serializedObject.FindProperty("m_Carve"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); + if (!Application.HasProLicense()) + { + EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); + GUI.enabled = false; + } + EditorGUILayout.PropertyField(this.m_MoveThreshold, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Carve, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs b/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs new file mode 100644 index 00000000..071626b7 --- /dev/null +++ b/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class NavMeshVisualizationSettings + { + public static extern bool showNavigation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showNavMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showHeightMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool hasHeightMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool showAgentPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showAgentPathInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showAgentNeighbours + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showAgentWalls + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEditor/UnityEditor/NormalCurveRenderer.cs b/UnityEditor/UnityEditor/NormalCurveRenderer.cs new file mode 100644 index 00000000..49fd60d6 --- /dev/null +++ b/UnityEditor/UnityEditor/NormalCurveRenderer.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class NormalCurveRenderer : CurveRenderer + { + private const float kSegmentWindowResolution = 1000f; + private const int kMaximumSampleCount = 50; + private AnimationCurve m_Curve; + private float m_CustomRangeStart; + private float m_CustomRangeEnd; + private WrapMode preWrapMode = WrapMode.Once; + private WrapMode postWrapMode = WrapMode.Once; + private float rangeStart + { + get + { + return (this.m_CustomRangeStart != 0f || this.m_CustomRangeEnd != 0f || this.m_Curve.length <= 0) ? this.m_CustomRangeStart : this.m_Curve.keys[0].time; + } + } + private float rangeEnd + { + get + { + return (this.m_CustomRangeStart != 0f || this.m_CustomRangeEnd != 0f || this.m_Curve.length <= 0) ? this.m_CustomRangeEnd : this.m_Curve.keys[this.m_Curve.length - 1].time; + } + } + public NormalCurveRenderer(AnimationCurve curve) + { + this.m_Curve = curve; + if (this.m_Curve == null) + { + this.m_Curve = new AnimationCurve(); + } + } + public AnimationCurve GetCurve() + { + return this.m_Curve; + } + public float RangeStart() + { + return this.rangeStart; + } + public float RangeEnd() + { + return this.rangeEnd; + } + public void SetWrap(WrapMode wrap) + { + this.preWrapMode = wrap; + this.postWrapMode = wrap; + } + public void SetWrap(WrapMode preWrap, WrapMode postWrap) + { + this.preWrapMode = preWrap; + this.postWrapMode = postWrap; + } + public void SetCustomRange(float start, float end) + { + this.m_CustomRangeStart = start; + this.m_CustomRangeEnd = end; + } + public float EvaluateCurveSlow(float time) + { + return this.m_Curve.Evaluate(time); + } + public float EvaluateCurveDeltaSlow(float time) + { + float num = 0.0001f; + return (this.m_Curve.Evaluate(time + num) - this.m_Curve.Evaluate(time - num)) / (num * 2f); + } + private Vector3[] GetPoints(float minTime, float maxTime) + { + List list = new List(); + if (this.m_Curve.length == 0) + { + return list.ToArray(); + } + list.Capacity = 1000 + this.m_Curve.length; + float[,] array = NormalCurveRenderer.CalculateRanges(minTime, maxTime, this.rangeStart, this.rangeEnd, this.preWrapMode, this.postWrapMode); + for (int i = 0; i < array.GetLength(0); i++) + { + this.AddPoints(ref list, array[i, 0], array[i, 1], minTime, maxTime); + } + if (list.Count > 0) + { + for (int j = 1; j < list.Count; j++) + { + if (list[j].x < list[j - 1].x) + { + list.RemoveAt(j); + j--; + } + } + } + return list.ToArray(); + } + public static float[,] CalculateRanges(float minTime, float maxTime, float rangeStart, float rangeEnd, WrapMode preWrapMode, WrapMode postWrapMode) + { + if (postWrapMode != preWrapMode) + { + float[,] expr_12 = new float[1, 2]; + expr_12[0, 0] = rangeStart; + expr_12[0, 1] = rangeEnd; + return expr_12; + } + if (preWrapMode == WrapMode.Loop) + { + if (maxTime - minTime > rangeEnd - rangeStart) + { + float[,] expr_3E = new float[1, 2]; + expr_3E[0, 0] = rangeStart; + expr_3E[0, 1] = rangeEnd; + return expr_3E; + } + minTime = Mathf.Repeat(minTime - rangeStart, rangeEnd - rangeStart) + rangeStart; + maxTime = Mathf.Repeat(maxTime - rangeStart, rangeEnd - rangeStart) + rangeStart; + if (minTime < maxTime) + { + float[,] expr_7D = new float[1, 2]; + expr_7D[0, 0] = minTime; + expr_7D[0, 1] = maxTime; + return expr_7D; + } + float[,] expr_97 = new float[2, 2]; + expr_97[0, 0] = rangeStart; + expr_97[0, 1] = maxTime; + expr_97[1, 0] = minTime; + expr_97[1, 1] = rangeEnd; + return expr_97; + } + else + { + if (preWrapMode == WrapMode.PingPong) + { + float[,] expr_CA = new float[1, 2]; + expr_CA[0, 0] = rangeStart; + expr_CA[0, 1] = rangeEnd; + return expr_CA; + } + float[,] expr_E4 = new float[1, 2]; + expr_E4[0, 0] = minTime; + expr_E4[0, 1] = maxTime; + return expr_E4; + } + } + private static int GetSegmentResolution(float minTime, float maxTime, float keyTime, float nextKeyTime) + { + float num = maxTime - minTime; + float num2 = nextKeyTime - keyTime; + int value = Mathf.RoundToInt(1000f * (num2 / num)); + return Mathf.Clamp(value, 1, 50); + } + private void AddPoints(ref List points, float minTime, float maxTime, float visibleMinTime, float visibleMaxTime) + { + if (this.m_Curve[0].time >= minTime) + { + points.Add(new Vector3(this.rangeStart, this.m_Curve[0].value)); + points.Add(new Vector3(this.m_Curve[0].time, this.m_Curve[0].value)); + } + for (int i = 0; i < this.m_Curve.length - 1; i++) + { + Keyframe keyframe = this.m_Curve[i]; + Keyframe keyframe2 = this.m_Curve[i + 1]; + if (keyframe2.time >= minTime && keyframe.time <= maxTime) + { + points.Add(new Vector3(keyframe.time, keyframe.value)); + int segmentResolution = NormalCurveRenderer.GetSegmentResolution(visibleMinTime, visibleMaxTime, keyframe.time, keyframe2.time); + float num = Mathf.Lerp(keyframe.time, keyframe2.time, 0.001f / (float)segmentResolution); + points.Add(new Vector3(num, this.m_Curve.Evaluate(num))); + for (float num2 = 1f; num2 < (float)segmentResolution; num2 += 1f) + { + num = Mathf.Lerp(keyframe.time, keyframe2.time, num2 / (float)segmentResolution); + points.Add(new Vector3(num, this.m_Curve.Evaluate(num))); + } + num = Mathf.Lerp(keyframe.time, keyframe2.time, 1f - 0.001f / (float)segmentResolution); + points.Add(new Vector3(num, this.m_Curve.Evaluate(num))); + num = keyframe2.time; + points.Add(new Vector3(num, keyframe2.value)); + } + } + if (this.m_Curve[this.m_Curve.length - 1].time <= maxTime) + { + points.Add(new Vector3(this.m_Curve[this.m_Curve.length - 1].time, this.m_Curve[this.m_Curve.length - 1].value)); + points.Add(new Vector3(this.rangeEnd, this.m_Curve[this.m_Curve.length - 1].value)); + } + } + public void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, Color wrapColor) + { + Vector3[] points = this.GetPoints(minTime, maxTime); + NormalCurveRenderer.DrawCurveWrapped(minTime, maxTime, this.rangeStart, this.rangeEnd, this.preWrapMode, this.postWrapMode, color, transform, points, wrapColor); + } + public static void DrawPolyLine(Matrix4x4 transform, float minDistance, params Vector3[] points) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color c = Handles.color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + Vector3 vector = transform.MultiplyPoint(points[0]); + for (int i = 1; i < points.Length; i++) + { + Vector3 vector2 = transform.MultiplyPoint(points[i]); + if ((vector - vector2).magnitude > minDistance) + { + GL.Vertex(vector); + GL.Vertex(vector2); + vector = vector2; + } + } + GL.End(); + GL.PopMatrix(); + } + public static void DrawCurveWrapped(float minTime, float maxTime, float rangeStart, float rangeEnd, WrapMode preWrap, WrapMode postWrap, Color color, Matrix4x4 transform, Vector3[] points, Color wrapColor) + { + if (points.Length == 0) + { + return; + } + int num; + int num2; + if (rangeEnd - rangeStart != 0f) + { + num = Mathf.FloorToInt((minTime - rangeStart) / (rangeEnd - rangeStart)); + num2 = Mathf.CeilToInt((maxTime - rangeEnd) / (rangeEnd - rangeStart)); + } + else + { + preWrap = WrapMode.Once; + postWrap = WrapMode.Once; + num = ((minTime >= rangeStart) ? 0 : -1); + num2 = ((maxTime <= rangeEnd) ? 0 : 1); + } + int num3 = points.Length - 1; + Handles.color = color; + List list = new List(); + if (num <= 0 && num2 >= 0) + { + NormalCurveRenderer.DrawPolyLine(transform, 2f, points); + } + else + { + Handles.DrawPolyLine(points); + } + Handles.color = new Color(wrapColor.r, wrapColor.g, wrapColor.b, wrapColor.a * color.a); + if (preWrap == WrapMode.Loop) + { + list = new List(); + for (int i = num; i < 0; i++) + { + for (int j = 0; j < points.Length; j++) + { + Vector3 vector = points[j]; + vector.x += (float)i * (rangeEnd - rangeStart); + vector = transform.MultiplyPoint(vector); + list.Add(vector); + } + } + list.Add(transform.MultiplyPoint(points[0])); + Handles.DrawPolyLine(list.ToArray()); + } + else + { + if (preWrap == WrapMode.PingPong) + { + list = new List(); + for (int k = num; k < 0; k++) + { + for (int l = 0; l < points.Length; l++) + { + if ((float)(k / 2) == (float)k / 2f) + { + Vector3 vector2 = points[l]; + vector2.x += (float)k * (rangeEnd - rangeStart); + vector2 = transform.MultiplyPoint(vector2); + list.Add(vector2); + } + else + { + Vector3 vector3 = points[num3 - l]; + vector3.x = -vector3.x + (float)(k + 1) * (rangeEnd - rangeStart) + rangeStart * 2f; + vector3 = transform.MultiplyPoint(vector3); + list.Add(vector3); + } + } + } + Handles.DrawPolyLine(list.ToArray()); + } + else + { + if (num < 0) + { + Handles.DrawPolyLine(new Vector3[] + { + transform.MultiplyPoint(new Vector3(minTime, points[0].y, 0f)), + transform.MultiplyPoint(new Vector3(Mathf.Min(maxTime, points[0].x), points[0].y, 0f)) + }); + } + } + } + if (postWrap == WrapMode.Loop) + { + list = new List(); + list.Add(transform.MultiplyPoint(points[num3])); + for (int m = 1; m <= num2; m++) + { + for (int n = 0; n < points.Length; n++) + { + Vector3 vector4 = points[n]; + vector4.x += (float)m * (rangeEnd - rangeStart); + vector4 = transform.MultiplyPoint(vector4); + list.Add(vector4); + } + } + Handles.DrawPolyLine(list.ToArray()); + } + else + { + if (postWrap == WrapMode.PingPong) + { + list = new List(); + for (int num4 = 1; num4 <= num2; num4++) + { + for (int num5 = 0; num5 < points.Length; num5++) + { + if ((float)(num4 / 2) == (float)num4 / 2f) + { + Vector3 vector5 = points[num5]; + vector5.x += (float)num4 * (rangeEnd - rangeStart); + vector5 = transform.MultiplyPoint(vector5); + list.Add(vector5); + } + else + { + Vector3 vector6 = points[num3 - num5]; + vector6.x = -vector6.x + (float)(num4 + 1) * (rangeEnd - rangeStart) + rangeStart * 2f; + vector6 = transform.MultiplyPoint(vector6); + list.Add(vector6); + } + } + } + Handles.DrawPolyLine(list.ToArray()); + } + else + { + if (num2 > 0) + { + Handles.DrawPolyLine(new Vector3[] + { + transform.MultiplyPoint(new Vector3(Mathf.Max(minTime, points[num3].x), points[num3].y, 0f)), + transform.MultiplyPoint(new Vector3(maxTime, points[num3].y, 0f)) + }); + } + } + } + } + public Bounds GetBounds() + { + return this.GetBounds(this.rangeStart, this.rangeEnd); + } + public Bounds GetBounds(float minTime, float maxTime) + { + Vector3[] points = this.GetPoints(minTime, maxTime); + float num = float.PositiveInfinity; + float num2 = float.NegativeInfinity; + Vector3[] array = points; + for (int i = 0; i < array.Length; i++) + { + Vector3 vector = array[i]; + if (vector.y > num2) + { + num2 = vector.y; + } + if (vector.y < num) + { + num = vector.y; + } + } + if (num == float.PositiveInfinity) + { + num = 0f; + num2 = 0f; + } + return new Bounds(new Vector3((maxTime + minTime) * 0.5f, (num2 + num) * 0.5f, 0f), new Vector3(maxTime - minTime, num2 - num, 0f)); + } + } +} diff --git a/UnityEditor/UnityEditor/OSColorPicker.cs b/UnityEditor/UnityEditor/OSColorPicker.cs new file mode 100644 index 00000000..c108bfae --- /dev/null +++ b/UnityEditor/UnityEditor/OSColorPicker.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class OSColorPicker + { + public static extern bool visible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Color color + { + get + { + Color result; + OSColorPicker.INTERNAL_get_color(out result); + return result; + } + set + { + OSColorPicker.INTERNAL_set_color(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Show(bool showAlpha); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Close(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_color(ref Color value); + } +} diff --git a/UnityEditor/UnityEditor/OSUtil.cs b/UnityEditor/UnityEditor/OSUtil.cs new file mode 100644 index 00000000..a03ae9bc --- /dev/null +++ b/UnityEditor/UnityEditor/OSUtil.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class OSUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetDefaultApps(string fileType); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAppFriendlyName(string app); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetDefaultAppPath(string fileType); + } +} diff --git a/UnityEditor/UnityEditor/ObjectCopier.cs b/UnityEditor/UnityEditor/ObjectCopier.cs new file mode 100644 index 00000000..eb9e2bc1 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectCopier.cs @@ -0,0 +1,31 @@ +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters.Binary; +namespace UnityEditor +{ + internal static class ObjectCopier + { + public static T DeepClone(T source) + { + if (!typeof(T).IsSerializable) + { + throw new ArgumentException("The type must be serializable.", "source"); + } + if (object.ReferenceEquals(source, null)) + { + return default(T); + } + IFormatter formatter = new BinaryFormatter(); + Stream stream = new MemoryStream(); + T result; + using (stream) + { + formatter.Serialize(stream, source); + stream.Seek(0L, SeekOrigin.Begin); + result = (T)((object)formatter.Deserialize(stream)); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectInfo.cs b/UnityEditor/UnityEditor/ObjectInfo.cs new file mode 100644 index 00000000..d2cdf072 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectInfo.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + internal class ObjectInfo + { + public int instanceId; + public int memorySize; + public int reason; + public List referencedBy; + public string name; + public string className; + } +} diff --git a/UnityEditor/UnityEditor/ObjectListArea.cs b/UnityEditor/UnityEditor/ObjectListArea.cs new file mode 100644 index 00000000..6009ffc9 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectListArea.cs @@ -0,0 +1,3415 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEditorInternal.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + internal class ObjectListArea + { + private class Styles + { + public GUIStyle resultsLabel = new GUIStyle("PR Label"); + public GUIStyle resultsGridLabel = ObjectListArea.Styles.GetStyle("ProjectBrowserGridLabel"); + public GUIStyle resultsGrid = "ObjectPickerResultsGrid"; + public GUIStyle background = "ObjectPickerBackground"; + public GUIStyle previewTextureBackground = "ObjectPickerPreviewBackground"; + public GUIStyle groupHeaderMiddle = ObjectListArea.Styles.GetStyle("ProjectBrowserHeaderBgMiddle"); + public GUIStyle groupHeaderTop = ObjectListArea.Styles.GetStyle("ProjectBrowserHeaderBgTop"); + public GUIStyle groupHeaderLabel = "Label"; + public GUIStyle groupHeaderLabelCount = "MiniLabel"; + public GUIStyle groupFoldout = "Foldout"; + public GUIStyle toolbarBack = "ObjectPickerToolbar"; + public GUIStyle resultsFocusMarker; + public GUIStyle miniRenameField = new GUIStyle("PR TextField"); + public GUIStyle ping = new GUIStyle("PR Ping"); + public GUIStyle miniPing = new GUIStyle("PR Ping"); + public GUIStyle iconDropShadow = ObjectListArea.Styles.GetStyle("ProjectBrowserIconDropShadow"); + public GUIStyle textureIconDropShadow = ObjectListArea.Styles.GetStyle("ProjectBrowserTextureIconDropShadow"); + public GUIStyle iconAreaBg = ObjectListArea.Styles.GetStyle("ProjectBrowserIconAreaBg"); + public GUIStyle previewBg = ObjectListArea.Styles.GetStyle("ProjectBrowserPreviewBg"); + public GUIStyle subAssetBg = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetBg"); + public GUIStyle subAssetBgOpenEnded = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetBgOpenEnded"); + public GUIStyle subAssetBgCloseEnded = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetBgCloseEnded"); + public GUIStyle subAssetBgMiddle = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetBgMiddle"); + public GUIStyle subAssetBgDivider = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetBgDivider"); + public GUIStyle subAssetExpandButton = ObjectListArea.Styles.GetStyle("ProjectBrowserSubAssetExpandBtn"); + public GUIContent m_AssetStoreNotAvailableText = new GUIContent("The Asset Store is not available"); + public Styles() + { + this.resultsFocusMarker = new GUIStyle(this.resultsGridLabel); + GUIStyle arg_1D4_0 = this.resultsFocusMarker; + float num = 0f; + this.resultsFocusMarker.fixedWidth = num; + arg_1D4_0.fixedHeight = num; + this.miniRenameField.font = EditorStyles.miniLabel.font; + this.miniRenameField.alignment = TextAnchor.LowerCenter; + this.ping.fixedHeight = 16f; + this.ping.padding.right = 10; + this.miniPing.font = EditorStyles.miniLabel.font; + this.miniPing.alignment = TextAnchor.MiddleCenter; + this.resultsLabel.alignment = TextAnchor.MiddleLeft; + } + private static GUIStyle GetStyle(string styleName) + { + return styleName; + } + } + private class AssetStoreGroup : ObjectListArea.Group + { + public const int kDefaultRowsShown = 3; + public const int kDefaultRowsShownListMode = 10; + private const int kMoreButtonOffset = 3; + private const int kMoreRowsAdded = 10; + private const int kMoreRowsAddedListMode = 75; + private const int kMaxQueryItems = 1000; + private GUIContent m_Content = new GUIContent(); + private List m_Assets; + private string m_Name; + private bool m_ListMode; + private Vector3 m_ShowMoreDims; + public string Name + { + get + { + return this.m_Name; + } + } + public List Assets + { + get + { + return this.m_Assets; + } + set + { + this.m_Assets = value; + } + } + public override int ItemCount + { + get + { + return Math.Min(this.m_Assets.Count, this.ItemsWantedShown); + } + } + public override bool ListMode + { + get + { + return this.m_ListMode; + } + set + { + this.m_ListMode = value; + } + } + public bool NeedItems + { + get + { + int num = Math.Min(1000, this.ItemsWantedShown); + int count = this.Assets.Count; + return (this.ItemsAvailable >= num && count < num) || (this.ItemsAvailable < num && count < this.ItemsAvailable); + } + } + public override bool NeedsRepaint + { + get; + protected set; + } + public AssetStoreGroup(ObjectListArea owner, string groupTitle, string groupName) : base(owner, groupTitle) + { + this.m_Assets = new List(); + this.m_Name = groupName; + this.m_ListMode = false; + this.m_ShowMoreDims = EditorStyles.miniButton.CalcSize(new GUIContent("Show more")); + this.m_Owner.UpdateGroupSizes(this); + this.ItemsWantedShown = 3 * this.m_Grid.columns; + } + public override void UpdateAssets() + { + } + protected override void DrawInternal(int itemIdx, int endItem, float yOffset) + { + int count = this.m_Assets.Count; + int num = itemIdx; + yOffset += this.kGroupSeparatorHeight; + bool flag = Event.current.type == EventType.Repaint; + Rect position; + if (this.ListMode) + { + while (itemIdx < endItem && itemIdx < count) + { + position = this.m_Grid.CalcRect(itemIdx, yOffset); + int num2 = this.HandleMouse(position); + if (num2 != 0) + { + this.m_Owner.SetSelection(this.m_Assets[itemIdx], num2 == 2); + } + if (flag) + { + bool selected = !AssetStoreAssetSelection.Empty && AssetStoreAssetSelection.ContainsAsset(this.m_Assets[itemIdx].id); + this.DrawLabel(position, this.m_Assets[itemIdx], selected); + } + itemIdx++; + } + } + else + { + while (itemIdx < endItem && itemIdx < count) + { + position = this.m_Grid.CalcRect(itemIdx, yOffset); + int num3 = this.HandleMouse(position); + if (num3 != 0) + { + this.m_Owner.SetSelection(this.m_Assets[itemIdx], num3 == 2); + } + if (flag) + { + Rect position2 = new Rect(position.x, position.y, position.width, position.height - ObjectListArea.s_Styles.resultsGridLabel.fixedHeight); + this.DrawIcon(position2, this.m_Assets[itemIdx]); + } + itemIdx++; + } + itemIdx = num; + if (flag) + { + while (itemIdx < endItem && itemIdx < count) + { + position = this.m_Grid.CalcRect(itemIdx, yOffset); + bool selected2 = !AssetStoreAssetSelection.Empty && AssetStoreAssetSelection.ContainsAsset(this.m_Assets[itemIdx].id); + this.DrawLabel(position, this.m_Assets[itemIdx], selected2); + itemIdx++; + } + } + } + if (this.ItemsAvailable <= this.m_Grid.rows * this.m_Grid.columns) + { + return; + } + position = new Rect(this.m_Owner.GetVisibleWidth() - this.m_ShowMoreDims.x - 6f, yOffset + this.m_Grid.height + 3f, this.m_ShowMoreDims.x, this.m_ShowMoreDims.y); + if (this.ItemsAvailable > this.m_Grid.rows * this.m_Grid.columns && this.ItemsAvailable >= this.Assets.Count && this.Assets.Count < 1000) + { + Event current = Event.current; + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + EditorStyles.miniButton.Draw(position, "More", false, false, false, false); + } + } + else + { + if (current.button == 0 && position.Contains(current.mousePosition)) + { + if (this.ListMode) + { + this.ItemsWantedShown += 75; + } + else + { + int num4 = this.m_Grid.columns - this.ItemCount % this.m_Grid.columns; + num4 %= this.m_Grid.columns; + this.ItemsWantedShown += 10 * this.m_Grid.columns + num4; + } + if (this.NeedItems) + { + this.m_Owner.QueryAssetStore(); + } + current.Use(); + } + } + } + } + private AssetStorePreviewManager.CachedAssetStoreImage GetIconForAssetStoreAsset(AssetStoreAsset assetStoreResource) + { + if (!string.IsNullOrEmpty(assetStoreResource.staticPreviewURL)) + { + this.m_Owner.LastScrollTime += 1.0; + return AssetStorePreviewManager.TextureFromUrl(assetStoreResource.staticPreviewURL, assetStoreResource.name, this.m_Owner.gridSize, ObjectListArea.s_Styles.resultsGridLabel, ObjectListArea.s_Styles.previewBg, false); + } + return null; + } + private void DrawIcon(Rect position, AssetStoreAsset assetStoreResource) + { + bool flag = false; + this.m_Content.text = null; + AssetStorePreviewManager.CachedAssetStoreImage iconForAssetStoreAsset = this.GetIconForAssetStoreAsset(assetStoreResource); + if (iconForAssetStoreAsset == null) + { + Texture2D iconForFile = InternalEditorUtility.GetIconForFile(assetStoreResource.name); + ObjectListArea.s_Styles.resultsGrid.Draw(position, iconForFile, false, false, flag, flag); + } + else + { + this.m_Content.image = iconForAssetStoreAsset.image; + Color color = iconForAssetStoreAsset.color; + Color color2 = GUI.color; + if (color.a != 1f) + { + GUI.color = color; + } + ObjectListArea.s_Styles.resultsGrid.Draw(position, this.m_Content, false, false, flag, flag); + if (color.a != 1f) + { + GUI.color = color2; + this.NeedsRepaint = true; + } + base.DrawDropShadowOverlay(position, flag, false, false); + } + } + private void DrawLabel(Rect position, AssetStoreAsset assetStoreResource, bool selected) + { + if (this.ListMode) + { + position.width = Mathf.Max(position.width, 500f); + this.m_Content.text = assetStoreResource.displayName; + this.m_Content.image = InternalEditorUtility.GetIconForFile(assetStoreResource.name); + ObjectListArea.s_Styles.resultsLabel.Draw(position, this.m_Content, false, false, selected, selected); + } + else + { + int instanceID = assetStoreResource.id + 10000000; + string croppedLabelText = this.m_Owner.GetCroppedLabelText(instanceID, assetStoreResource.displayName, position.width); + position.height -= ObjectListArea.s_Styles.resultsGridLabel.fixedHeight; + ObjectListArea.s_Styles.resultsGridLabel.Draw(new Rect(position.x, position.yMax + 1f, position.width - 1f, ObjectListArea.s_Styles.resultsGridLabel.fixedHeight), croppedLabelText, false, false, selected, this.m_Owner.HasFocus()); + } + } + public override void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool showFoldersFirst) + { + this.ItemsWantedShown = ((!this.ListMode) ? (3 * this.m_Grid.columns) : 10); + this.Assets.Clear(); + } + public override void UpdateHeight() + { + this.m_Height = (float)((int)this.kGroupSeparatorHeight); + if (!this.Visible) + { + return; + } + this.m_Height += this.m_Grid.height; + if (this.ItemsAvailable <= this.m_Grid.rows * this.m_Grid.columns) + { + return; + } + this.m_Height += (float)(6 + (int)this.m_ShowMoreDims.y); + } + public int IndexOf(int assetID) + { + int num = 0; + foreach (AssetStoreAsset current in this.m_Assets) + { + if (current.id == assetID) + { + return num; + } + num++; + } + return -1; + } + public AssetStoreAsset AssetAtIndex(int selectedIdx) + { + if (selectedIdx >= this.m_Grid.rows * this.m_Grid.columns) + { + return null; + } + if (selectedIdx < this.m_Grid.rows * this.m_Grid.columns && selectedIdx > this.ItemCount) + { + return this.m_Assets.Last(); + } + int num = 0; + foreach (AssetStoreAsset current in this.m_Assets) + { + if (selectedIdx == num) + { + return current; + } + num++; + } + return null; + } + protected int HandleMouse(Rect position) + { + Event current = Event.current; + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.ContextClick) + { + if (position.Contains(current.mousePosition)) + { + return 1; + } + } + } + else + { + if (current.button == 0 && position.Contains(current.mousePosition)) + { + this.m_Owner.Repaint(); + if (current.clickCount == 2) + { + current.Use(); + return 2; + } + this.m_Owner.ScrollToPosition(ObjectListArea.AdjustRectForFraming(position)); + current.Use(); + return 1; + } + } + return 0; + } + } + private abstract class Group + { + protected readonly float kGroupSeparatorHeight = EditorStyles.toolbar.fixedHeight; + protected string m_GroupSeparatorTitle; + protected static int[] s_Empty; + public ObjectListArea m_Owner; + public VerticalGrid m_Grid = new VerticalGrid(); + public float m_Height; + public bool Visible = true; + public int ItemsAvailable; + public int ItemsWantedShown; + protected bool m_Collapsable = true; + public double m_LastClickedDrawTime; + public float Height + { + get + { + return this.m_Height; + } + } + public abstract int ItemCount + { + get; + } + public abstract bool ListMode + { + get; + set; + } + public abstract bool NeedsRepaint + { + get; + protected set; + } + public bool visiblePreference + { + get + { + return string.IsNullOrEmpty(this.m_GroupSeparatorTitle) || EditorPrefs.GetBool(this.m_GroupSeparatorTitle, true); + } + set + { + if (string.IsNullOrEmpty(this.m_GroupSeparatorTitle)) + { + return; + } + EditorPrefs.SetBool(this.m_GroupSeparatorTitle, value); + } + } + public Group(ObjectListArea owner, string groupTitle) + { + this.m_GroupSeparatorTitle = groupTitle; + if (ObjectListArea.Group.s_Empty == null) + { + ObjectListArea.Group.s_Empty = new int[0]; + } + this.m_Owner = owner; + this.Visible = this.visiblePreference; + } + public abstract void UpdateAssets(); + public abstract void UpdateHeight(); + protected abstract void DrawInternal(int itemIdx, int endItem, float yOffset); + public abstract void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool showFoldersFirst); + protected virtual float GetHeaderHeight() + { + return this.kGroupSeparatorHeight; + } + protected virtual void HandleUnusedDragEvents(float yOffset) + { + } + private int FirstVisibleRow(float yOffset, Vector2 scrollPos) + { + if (!this.Visible) + { + return -1; + } + float num = scrollPos.y - (yOffset + this.GetHeaderHeight()); + int result = 0; + if (num > 0f) + { + float num2 = this.m_Grid.itemSize.y + this.m_Grid.verticalSpacing; + result = (int)Mathf.Max(0f, Mathf.Floor(num / num2)); + } + return result; + } + private bool IsInView(float yOffset, Vector2 scrollPos, float scrollViewHeight) + { + return scrollPos.y + scrollViewHeight >= yOffset && yOffset + this.Height >= scrollPos.y; + } + public void Draw(float yOffset, Vector2 scrollPos) + { + this.NeedsRepaint = false; + bool flag = Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout; + if (!flag) + { + this.DrawHeader(yOffset, this.m_Collapsable); + } + if (!this.IsInView(yOffset, scrollPos, this.m_Owner.m_VisibleRect.height)) + { + return; + } + int num = this.FirstVisibleRow(yOffset, scrollPos); + int num2 = num * this.m_Grid.columns; + int itemCount = this.ItemCount; + if (num2 >= 0 && num2 < itemCount) + { + int num3 = num2; + int num4 = Math.Min(itemCount, this.m_Grid.rows * this.m_Grid.columns); + float num5 = this.m_Grid.itemSize.y + this.m_Grid.verticalSpacing; + int num6 = (int)Math.Ceiling((double)(this.m_Owner.m_VisibleRect.height / num5)); + num4 = Math.Min(num4, num3 + num6 * this.m_Grid.columns + this.m_Grid.columns); + this.DrawInternal(num3, num4, yOffset); + } + if (flag) + { + this.DrawHeader(yOffset, this.m_Collapsable); + } + this.HandleUnusedDragEvents(yOffset); + } + protected void DrawObjectIcon(Rect position, Texture icon) + { + if (icon == null) + { + return; + } + int width = icon.width; + FilterMode filterMode = icon.filterMode; + icon.filterMode = FilterMode.Point; + GUI.DrawTexture(new Rect(position.x + (float)(((int)position.width - width) / 2), position.y + (float)(((int)position.height - width) / 2), (float)width, (float)width), icon, ScaleMode.ScaleToFit); + icon.filterMode = filterMode; + } + protected void DrawDropShadowOverlay(Rect position, bool selected, bool isDropTarget, bool isRenaming) + { + float num = position.width / 128f; + Rect position2 = new Rect(position.x - 4f * num, position.y - 2f * num, position.width + 8f * num, position.height + 12f * num - 0.5f); + ObjectListArea.s_Styles.iconDropShadow.Draw(position2, GUIContent.none, false, false, selected || isDropTarget, this.m_Owner.HasFocus() || isRenaming || isDropTarget); + } + protected void DrawHeaderBackground(Rect rect, bool firstHeader) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + GUI.Label(rect, GUIContent.none, (!firstHeader) ? ObjectListArea.s_Styles.groupHeaderMiddle : ObjectListArea.s_Styles.groupHeaderTop); + } + protected float GetHeaderYPosInScrollArea(float yOffset) + { + float result = yOffset; + float y = this.m_Owner.m_State.m_ScrollPosition.y; + if (y > yOffset) + { + result = Mathf.Min(y, yOffset + this.Height - this.kGroupSeparatorHeight); + } + return result; + } + protected virtual void DrawHeader(float yOffset, bool collapsable) + { + Rect rect = new Rect(0f, this.GetHeaderYPosInScrollArea(yOffset), this.m_Owner.GetVisibleWidth(), this.kGroupSeparatorHeight - 1f); + this.DrawHeaderBackground(rect, yOffset == 0f); + rect.x += 7f; + if (collapsable) + { + bool visible = this.Visible; + this.Visible = GUI.Toggle(rect, this.Visible, GUIContent.none, ObjectListArea.s_Styles.groupFoldout); + if (visible ^ this.Visible) + { + this.visiblePreference = this.Visible; + } + } + GUIStyle groupHeaderLabel = ObjectListArea.s_Styles.groupHeaderLabel; + if (collapsable) + { + rect.x += 14f; + } + rect.y += 1f; + if (!string.IsNullOrEmpty(this.m_GroupSeparatorTitle)) + { + GUI.Label(rect, this.m_GroupSeparatorTitle, groupHeaderLabel); + } + if (ObjectListArea.s_Debug) + { + Rect position = rect; + position.x += 120f; + GUI.Label(position, AssetStorePreviewManager.StatsString()); + } + rect.y -= 1f; + if (this.m_Owner.GetVisibleWidth() > 150f) + { + this.DrawItemCount(rect); + } + } + protected void DrawItemCount(Rect rect) + { + string text = this.ItemsAvailable.ToString() + " Total"; + Vector2 vector = ObjectListArea.s_Styles.groupHeaderLabelCount.CalcSize(new GUIContent(text)); + if (vector.x < rect.width) + { + rect.x = this.m_Owner.GetVisibleWidth() - vector.x - 4f; + } + rect.width = vector.x; + rect.y += 2f; + GUI.Label(rect, text, ObjectListArea.s_Styles.groupHeaderLabelCount); + } + private UnityEngine.Object[] GetSelectedReferences() + { + return Selection.objects; + } + private static string[] GetMainSelectedPaths() + { + List list = new List(); + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + if (AssetDatabase.IsMainAsset(instanceID)) + { + string assetPath = AssetDatabase.GetAssetPath(instanceID); + list.Add(assetPath); + } + } + return list.ToArray(); + } + } + private class LocalGroup : ObjectListArea.Group + { + private class ItemFader + { + private double m_FadeDuration = 0.3; + private double m_FirstToLastDuration = 0.3; + private double m_FadeStartTime; + private double m_TimeBetweenEachItem; + private List m_InstanceIDs; + public void Start(List instanceIDs) + { + this.m_InstanceIDs = instanceIDs; + this.m_FadeStartTime = EditorApplication.timeSinceStartup; + this.m_FirstToLastDuration = Math.Min(0.5, (double)instanceIDs.Count * 0.03); + this.m_TimeBetweenEachItem = 0.0; + if (this.m_InstanceIDs.Count > 1) + { + this.m_TimeBetweenEachItem = this.m_FirstToLastDuration / (double)(this.m_InstanceIDs.Count - 1); + } + } + public float GetAlpha(int instanceID) + { + if (this.m_InstanceIDs == null) + { + return 1f; + } + if (EditorApplication.timeSinceStartup > this.m_FadeStartTime + this.m_FadeDuration + this.m_FirstToLastDuration) + { + this.m_InstanceIDs = null; + return 1f; + } + int num = this.m_InstanceIDs.IndexOf(instanceID); + if (num >= 0) + { + double num2 = EditorApplication.timeSinceStartup - this.m_FadeStartTime; + double num3 = this.m_TimeBetweenEachItem * (double)num; + float result = 0f; + if (num3 < num2) + { + result = Mathf.Clamp((float)((num2 - num3) / this.m_FadeDuration), 0f, 1f); + } + return result; + } + return 1f; + } + } + public const int k_ListModeLeftPadding = 16; + public const int k_ListModeLeftPaddingForSubAssets = 28; + public const int k_ListModeVersionControlOverlayPadding = 14; + private BuiltinResource[] m_NoneList; + private GUIContent m_Content = new GUIContent(); + private List m_DragSelection = new List(); + private int m_DropTargetControlID; + private Dictionary m_BuiltinResourceMap; + private BuiltinResource[] m_CurrentBuiltinResources; + private bool m_ShowNoneItem; + private List m_LastRenderedAssetInstanceIDs = new List(); + private List m_LastRenderedAssetDirtyIDs = new List(); + public bool m_ListMode; + private FilteredHierarchy m_FilteredHierarchy; + private BuiltinResource[] m_ActiveBuiltinList; + private ObjectListArea.LocalGroup.ItemFader m_ItemFader = new ObjectListArea.LocalGroup.ItemFader(); + public bool ShowNone + { + get + { + return this.m_ShowNoneItem; + } + } + public override bool NeedsRepaint + { + get + { + return false; + } + protected set + { + } + } + public SearchFilter searchFilter + { + get + { + return this.m_FilteredHierarchy.searchFilter; + } + } + public override bool ListMode + { + get + { + return this.m_ListMode; + } + set + { + this.m_ListMode = value; + } + } + public bool HasBuiltinResources + { + get + { + return this.m_CurrentBuiltinResources.Length > 0; + } + } + public override int ItemCount + { + get + { + int num = this.m_FilteredHierarchy.results.Length; + int num2 = num + this.m_ActiveBuiltinList.Length; + int num3 = (!this.m_ShowNoneItem) ? 0 : 1; + int num4 = (this.m_Owner.m_State.m_NewAssetIndexInList == -1) ? 0 : 1; + return num2 + num3 + num4; + } + } + public LocalGroup(ObjectListArea owner, string groupTitle, bool showNone) : base(owner, groupTitle) + { + this.m_ShowNoneItem = showNone; + this.m_ListMode = false; + this.InitBuiltinResources(); + this.ItemsWantedShown = 2147483647; + this.m_Collapsable = false; + } + public override void UpdateAssets() + { + if (this.m_FilteredHierarchy.hierarchyType == HierarchyType.Assets) + { + this.m_ActiveBuiltinList = this.m_CurrentBuiltinResources; + } + else + { + this.m_ActiveBuiltinList = new BuiltinResource[0]; + } + this.ItemsAvailable = this.m_FilteredHierarchy.results.Length + this.m_ActiveBuiltinList.Length; + } + protected override float GetHeaderHeight() + { + return 0f; + } + protected override void DrawHeader(float yOffset, bool collapsable) + { + if (this.GetHeaderHeight() > 0f) + { + Rect rect = new Rect(0f, base.GetHeaderYPosInScrollArea(yOffset), this.m_Owner.GetVisibleWidth(), this.kGroupSeparatorHeight); + base.DrawHeaderBackground(rect, true); + if (collapsable) + { + rect.x += 7f; + bool visible = this.Visible; + this.Visible = GUI.Toggle(new Rect(rect.x, rect.y, 14f, rect.height), this.Visible, GUIContent.none, ObjectListArea.s_Styles.groupFoldout); + if (visible ^ this.Visible) + { + EditorPrefs.SetBool(this.m_GroupSeparatorTitle, this.Visible); + } + rect.x += 7f; + } + float num = 0f; + if (this.m_Owner.drawLocalAssetHeader != null) + { + num = this.m_Owner.drawLocalAssetHeader(rect) + 10f; + } + rect.x += num; + rect.width -= num; + if (rect.width > 0f) + { + base.DrawItemCount(rect); + } + } + } + public override void UpdateHeight() + { + this.m_Height = this.GetHeaderHeight(); + if (!this.Visible) + { + return; + } + this.m_Height += this.m_Grid.height; + } + private bool IsCreatingAtThisIndex(int itemIdx) + { + return this.m_Owner.m_State.m_NewAssetIndexInList == itemIdx; + } + protected override void DrawInternal(int beginIndex, int endIndex, float yOffset) + { + int num = beginIndex; + int num2 = 0; + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + bool flag = this.m_FilteredHierarchy.searchFilter.GetState() == SearchFilter.State.FolderBrowsing; + yOffset += this.GetHeaderHeight(); + if (this.m_NoneList.Length > 0) + { + if (beginIndex < 1) + { + Rect position = this.m_Grid.CalcRect(num, yOffset); + this.DrawItem(position, null, this.m_NoneList[0], flag); + num++; + } + num2++; + } + if (!this.ListMode && flag) + { + this.DrawSubAssetBackground(beginIndex, endIndex, yOffset); + } + if (Event.current.type == EventType.Repaint) + { + this.ClearDirtyStateTracking(); + } + int num3 = num - num2; + while (true) + { + if (this.IsCreatingAtThisIndex(num)) + { + BuiltinResource builtinResource = new BuiltinResource(); + builtinResource.m_Name = this.m_Owner.GetCreateAssetUtility().originalName; + builtinResource.m_InstanceID = this.m_Owner.GetCreateAssetUtility().instanceID; + this.DrawItem(this.m_Grid.CalcRect(num, yOffset), null, builtinResource, flag); + num++; + num2++; + } + if (num > endIndex) + { + break; + } + if (num3 >= results.Length) + { + break; + } + FilteredHierarchy.FilterResult filterItem = results[num3]; + Rect position = this.m_Grid.CalcRect(num, yOffset); + this.DrawItem(position, filterItem, null, flag); + num++; + num3++; + } + num2 += results.Length; + if (this.m_ActiveBuiltinList.Length > 0) + { + int num4 = beginIndex - num2; + num4 = Math.Max(num4, 0); + int num5 = num4; + while (num5 < this.m_ActiveBuiltinList.Length && num <= endIndex) + { + this.DrawItem(this.m_Grid.CalcRect(num, yOffset), null, this.m_ActiveBuiltinList[num5], flag); + num++; + num5++; + } + } + if (!this.ListMode && AssetPreview.IsLoadingAssetPreviews(this.m_Owner.GetAssetPreviewManagerID())) + { + this.m_Owner.Repaint(); + } + } + private void ClearDirtyStateTracking() + { + this.m_LastRenderedAssetInstanceIDs.Clear(); + this.m_LastRenderedAssetDirtyIDs.Clear(); + } + private void AddDirtyStateFor(int instanceID) + { + this.m_LastRenderedAssetInstanceIDs.Add(instanceID); + this.m_LastRenderedAssetDirtyIDs.Add(EditorUtility.GetDirtyIndex(instanceID)); + } + public bool IsAnyLastRenderedAssetsDirty() + { + for (int i = 0; i < this.m_LastRenderedAssetInstanceIDs.Count; i++) + { + int dirtyIndex = EditorUtility.GetDirtyIndex(this.m_LastRenderedAssetInstanceIDs[i]); + if (dirtyIndex != this.m_LastRenderedAssetDirtyIDs[i]) + { + this.m_LastRenderedAssetDirtyIDs[i] = dirtyIndex; + return true; + } + } + return false; + } + protected override void HandleUnusedDragEvents(float yOffset) + { + if (!this.m_Owner.allowDragging) + { + return; + } + Event current = Event.current; + EventType type = current.type; + if (type == EventType.DragUpdated || type == EventType.DragPerform) + { + Rect rect = new Rect(0f, yOffset, this.m_Owner.m_TotalRect.width, (this.m_Owner.m_TotalRect.height <= base.Height) ? base.Height : this.m_Owner.m_TotalRect.height); + if (rect.Contains(current.mousePosition)) + { + bool flag = this.m_FilteredHierarchy.searchFilter.GetState() == SearchFilter.State.FolderBrowsing; + DragAndDropVisualMode dragAndDropVisualMode; + if (flag && this.m_FilteredHierarchy.searchFilter.folders.Length == 1) + { + string assetPath = this.m_FilteredHierarchy.searchFilter.folders[0]; + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(assetPath); + bool flag2 = current.type == EventType.DragPerform; + dragAndDropVisualMode = this.DoDrag(mainAssetInstanceID, flag2); + if (flag2 && dragAndDropVisualMode != DragAndDropVisualMode.None) + { + DragAndDrop.AcceptDrag(); + } + } + else + { + dragAndDropVisualMode = DragAndDropVisualMode.None; + } + DragAndDrop.visualMode = dragAndDropVisualMode; + current.Use(); + } + } + } + private void HandleMouseWithDragging(int instanceID, int controlID, Rect rect) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + switch (typeForControl) + { + case EventType.DragUpdated: + case EventType.DragPerform: + { + bool flag = current.type == EventType.DragPerform; + if (rect.Contains(current.mousePosition)) + { + DragAndDropVisualMode dragAndDropVisualMode = this.DoDrag(instanceID, flag); + if (dragAndDropVisualMode != DragAndDropVisualMode.None) + { + if (flag) + { + DragAndDrop.AcceptDrag(); + } + this.m_DropTargetControlID = controlID; + DragAndDrop.visualMode = dragAndDropVisualMode; + current.Use(); + } + if (flag) + { + this.m_DropTargetControlID = 0; + } + } + if (flag) + { + this.m_DragSelection.Clear(); + } + return; + } + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + IL_39: + switch (typeForControl) + { + case EventType.MouseDown: + if (Event.current.button == 0 && rect.Contains(Event.current.mousePosition)) + { + if (current.clickCount == 2) + { + this.m_Owner.SetSelection(new int[] + { + instanceID + }, true); + this.m_DragSelection.Clear(); + } + else + { + this.m_DragSelection = this.GetNewSelection(instanceID, true, false); + GUIUtility.hotControl = controlID; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), controlID); + dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; + this.m_Owner.ScrollToPosition(ObjectListArea.AdjustRectForFraming(rect)); + } + current.Use(); + } + else + { + if (Event.current.button == 1 && rect.Contains(Event.current.mousePosition)) + { + this.m_Owner.SetSelection(this.GetNewSelection(instanceID, true, false).ToArray(), false); + } + } + return; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + if (rect.Contains(current.mousePosition)) + { + bool flag2; + if (this.ListMode) + { + rect.x += 28f; + rect.width += 28f; + flag2 = rect.Contains(current.mousePosition); + } + else + { + rect.y = rect.y + rect.height - ObjectListArea.s_Styles.resultsGridLabel.fixedHeight; + rect.height = ObjectListArea.s_Styles.resultsGridLabel.fixedHeight; + flag2 = rect.Contains(current.mousePosition); + } + List selectedInstanceIDs = this.m_Owner.m_State.m_SelectedInstanceIDs; + if (flag2 && this.m_Owner.allowRenaming && this.m_Owner.m_AllowRenameOnMouseUp && selectedInstanceIDs.Count == 1 && selectedInstanceIDs[0] == instanceID && !EditorGUIUtility.HasHolddownKeyModifiers(current)) + { + this.m_Owner.BeginRename(0.5f); + } + else + { + List newSelection = this.GetNewSelection(instanceID, false, false); + this.m_Owner.SetSelection(newSelection.ToArray(), false); + } + GUIUtility.hotControl = 0; + current.Use(); + } + this.m_DragSelection.Clear(); + } + return; + case EventType.MouseMove: + return; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), controlID); + if (dragAndDropDelay2.CanStartDrag()) + { + this.StartDrag(instanceID, this.m_DragSelection); + GUIUtility.hotControl = 0; + } + current.Use(); + } + return; + default: + return; + } + break; + case EventType.DragExited: + this.m_DragSelection.Clear(); + return; + case EventType.ContextClick: + { + Rect drawRect = rect; + drawRect.x += 2f; + drawRect = ProjectHooks.GetOverlayRect(drawRect); + if (drawRect.width != rect.width && Provider.isActive && drawRect.Contains(current.mousePosition)) + { + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/Version Control", new MenuCommand(null, 0)); + current.Use(); + } + return; + } + } + goto IL_39; + } + private void HandleMouseWithoutDragging(int instanceID, int controlID, Rect position) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl != EventType.MouseDown) + { + if (typeForControl == EventType.ContextClick) + { + if (position.Contains(current.mousePosition)) + { + this.m_Owner.SetSelection(new int[] + { + instanceID + }, false); + Rect drawRect = position; + drawRect.x += 2f; + drawRect = ProjectHooks.GetOverlayRect(drawRect); + if (drawRect.width != position.width && Provider.isActive && drawRect.Contains(current.mousePosition)) + { + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/Version Control", new MenuCommand(null, 0)); + current.Use(); + } + } + } + } + else + { + if (current.button == 0 && position.Contains(current.mousePosition)) + { + this.m_Owner.Repaint(); + if (current.clickCount == 1) + { + this.m_Owner.ScrollToPosition(ObjectListArea.AdjustRectForFraming(position)); + } + current.Use(); + List newSelection = this.GetNewSelection(instanceID, false, false); + this.m_Owner.SetSelection(newSelection.ToArray(), current.clickCount == 2); + } + } + } + public void ChangeExpandedState(int instanceID, bool expanded) + { + this.m_Owner.m_State.m_ExpandedInstanceIDs.Remove(instanceID); + if (expanded) + { + this.m_Owner.m_State.m_ExpandedInstanceIDs.Add(instanceID); + } + this.m_FilteredHierarchy.RefreshVisibleItems(this.m_Owner.m_State.m_ExpandedInstanceIDs); + } + private bool IsExpanded(int instanceID) + { + return this.m_Owner.m_State.m_ExpandedInstanceIDs.IndexOf(instanceID) >= 0; + } + private void SelectAndFrameParentOf(int instanceID) + { + int num = 0; + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + if (results[i].instanceID == instanceID) + { + if (results[i].isMainRepresentation) + { + num = 0; + } + break; + } + if (results[i].isMainRepresentation) + { + num = results[i].instanceID; + } + } + if (num != 0) + { + this.m_Owner.SetSelection(new int[] + { + num + }, false); + this.m_Owner.Frame(num, true, false); + } + } + private bool IsRenaming(int instanceID) + { + RenameOverlay renameOverlay = this.m_Owner.GetRenameOverlay(); + return renameOverlay.IsRenaming() && renameOverlay.userData == instanceID && !renameOverlay.isWaitingForDelay; + } + protected void DrawSubAssetRowBg(int startSubAssetIndex, int endSubAssetIndex, bool continued, float yOffset) + { + Rect rect = this.m_Grid.CalcRect(startSubAssetIndex, yOffset); + Rect rect2 = this.m_Grid.CalcRect(endSubAssetIndex, yOffset); + float num = 30f; + float num2 = 128f; + float num3 = rect.width / num2; + float num4 = 9f * num3; + float num5 = 4f; + bool flag = startSubAssetIndex % this.m_Grid.columns == 0; + float num6 = (!flag) ? (this.m_Grid.horizontalSpacing + num3 * 10f) : (18f * num3); + Rect position = new Rect(rect.x - num6, rect.y + num5, num * num3, rect.width - num5 * 2f + num4 - 1f); + position.y = Mathf.Round(position.y); + position.height = Mathf.Ceil(position.height); + ObjectListArea.s_Styles.subAssetBg.Draw(position, GUIContent.none, false, false, false, false); + float num7 = num * num3; + bool flag2 = endSubAssetIndex % this.m_Grid.columns == this.m_Grid.columns - 1; + float num8 = (!continued && !flag2) ? (8f * num3) : (16f * num3); + Rect position2 = new Rect(rect2.xMax - num7 + num8, rect2.y + num5, num7, position.height); + position2.y = Mathf.Round(position2.y); + position2.height = Mathf.Ceil(position2.height); + GUIStyle gUIStyle = (!continued) ? ObjectListArea.s_Styles.subAssetBgCloseEnded : ObjectListArea.s_Styles.subAssetBgOpenEnded; + gUIStyle.Draw(position2, GUIContent.none, false, false, false, false); + position = new Rect(position.xMax, position.y, position2.xMin - position.xMax, position.height); + position.y = Mathf.Round(position.y); + position.height = Mathf.Ceil(position.height); + ObjectListArea.s_Styles.subAssetBgMiddle.Draw(position, GUIContent.none, false, false, false, false); + } + private void DrawSubAssetBackground(int beginIndex, int endIndex, float yOffset) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + int columns = this.m_Grid.columns; + int num = (endIndex - beginIndex) / columns + 1; + for (int i = 0; i < num; i++) + { + int num2 = -1; + int endSubAssetIndex = -1; + for (int j = 0; j < columns; j++) + { + int num3 = beginIndex + (j + i * columns); + if (num3 >= results.Length) + { + break; + } + FilteredHierarchy.FilterResult filterResult = results[num3]; + if (!filterResult.isMainRepresentation) + { + if (num2 == -1) + { + num2 = num3; + } + endSubAssetIndex = num3; + } + else + { + if (num2 != -1) + { + this.DrawSubAssetRowBg(num2, endSubAssetIndex, false, yOffset); + num2 = -1; + endSubAssetIndex = -1; + } + } + } + if (num2 != -1) + { + bool continued = false; + if (i < num - 1) + { + int num4 = beginIndex + (i + 1) * columns; + if (num4 < results.Length) + { + continued = !results[num4].isMainRepresentation; + } + } + this.DrawSubAssetRowBg(num2, endSubAssetIndex, continued, yOffset); + } + } + } + private void DrawItem(Rect position, FilteredHierarchy.FilterResult filterItem, BuiltinResource builtinResource, bool isFolderBrowsing) + { + Assert.IsTrue((filterItem != null && builtinResource == null) || (builtinResource != null && filterItem == null)); + Event current = Event.current; + Rect selectionRect = position; + int num = 0; + bool flag = false; + if (filterItem != null) + { + num = filterItem.instanceID; + flag = (filterItem.hasChildren && !filterItem.isFolder && isFolderBrowsing); + } + else + { + if (builtinResource != null) + { + num = builtinResource.m_InstanceID; + } + } + int controlIDFromInstanceID = ObjectListArea.LocalGroup.GetControlIDFromInstanceID(num); + bool flag2; + if (this.m_Owner.allowDragging) + { + flag2 = ((this.m_DragSelection.Count <= 0) ? this.m_Owner.IsSelected(num) : this.m_DragSelection.Contains(num)); + } + else + { + flag2 = this.m_Owner.IsSelected(num); + } + if (flag2 && num == this.m_Owner.m_State.m_LastClickedInstanceID) + { + this.m_LastClickedDrawTime = EditorApplication.timeSinceStartup; + } + Rect position2 = new Rect(position.x + 2f, position.y, 16f, 16f); + if (flag && !this.ListMode) + { + float num2 = position.height / 128f; + float num3 = 28f * num2; + float height = 32f * num2; + position2 = new Rect(position.xMax - num3 * 0.5f, position.y + (position.height - ObjectListArea.s_Styles.resultsGridLabel.fixedHeight) * 0.5f - num3 * 0.5f, num3, height); + } + bool flag3 = false; + if (flag2 && current.type == EventType.KeyDown && this.m_Owner.HasFocus()) + { + KeyCode keyCode = current.keyCode; + if (keyCode != KeyCode.RightArrow) + { + if (keyCode == KeyCode.LeftArrow) + { + if (this.ListMode || this.m_Owner.IsPreviewIconExpansionModifierPressed()) + { + if (this.IsExpanded(num)) + { + flag3 = true; + } + else + { + this.SelectAndFrameParentOf(num); + } + current.Use(); + } + } + } + else + { + if (this.ListMode || this.m_Owner.IsPreviewIconExpansionModifierPressed()) + { + if (!this.IsExpanded(num)) + { + flag3 = true; + } + current.Use(); + } + } + } + if (flag && current.type == EventType.MouseDown && current.button == 0 && position2.Contains(current.mousePosition)) + { + flag3 = true; + } + if (flag3) + { + bool flag4 = !this.IsExpanded(num); + if (flag4) + { + this.m_ItemFader.Start(this.m_FilteredHierarchy.GetSubAssetInstanceIDs(num)); + } + this.ChangeExpandedState(num, flag4); + current.Use(); + GUIUtility.ExitGUI(); + } + bool flag5 = this.IsRenaming(num); + Rect rect = position; + if (!this.ListMode) + { + rect = new Rect(position.x, position.yMax + 1f - ObjectListArea.s_Styles.resultsGridLabel.fixedHeight, position.width - 1f, ObjectListArea.s_Styles.resultsGridLabel.fixedHeight); + } + int num4 = (!Provider.isActive || !this.ListMode) ? 0 : 14; + float num5 = 16f; + if (this.ListMode) + { + selectionRect.x = 16f; + if (filterItem != null && !filterItem.isMainRepresentation && isFolderBrowsing) + { + num5 = 28f; + selectionRect.x = 28f + (float)num4 * 0.5f; + } + selectionRect.width -= selectionRect.x; + } + if (Event.current.type == EventType.Repaint) + { + if (this.m_DropTargetControlID == controlIDFromInstanceID && !position.Contains(current.mousePosition)) + { + this.m_DropTargetControlID = 0; + } + bool flag6 = controlIDFromInstanceID == this.m_DropTargetControlID; + string text = (filterItem == null) ? builtinResource.m_Name : filterItem.name; + if (this.ListMode) + { + if (flag5) + { + flag2 = false; + text = string.Empty; + } + position.width = Mathf.Max(position.width, 500f); + this.m_Content.text = text; + this.m_Content.image = null; + Texture2D texture2D = (filterItem == null) ? AssetPreview.GetAssetPreview(num, this.m_Owner.GetAssetPreviewManagerID()) : filterItem.icon; + if (texture2D == null && this.m_Owner.GetCreateAssetUtility().icon != null) + { + texture2D = this.m_Owner.GetCreateAssetUtility().icon; + } + if (flag2) + { + ObjectListArea.s_Styles.resultsLabel.Draw(position, GUIContent.none, false, false, flag2, this.m_Owner.HasFocus()); + } + if (flag6) + { + ObjectListArea.s_Styles.resultsLabel.Draw(position, GUIContent.none, true, true, false, false); + } + ObjectListArea.LocalGroup.DrawIconAndLabel(new Rect(num5, position.y, position.width - num5, position.height), filterItem, text, texture2D, flag2, this.m_Owner.HasFocus()); + if (flag) + { + ObjectListArea.s_Styles.groupFoldout.Draw(position2, !this.ListMode, !this.ListMode, this.IsExpanded(num), false); + } + } + else + { + bool flag7 = false; + if (this.m_Owner.GetCreateAssetUtility().instanceID == num && this.m_Owner.GetCreateAssetUtility().icon != null) + { + this.m_Content.image = this.m_Owner.GetCreateAssetUtility().icon; + } + else + { + this.m_Content.image = AssetPreview.GetAssetPreview(num, this.m_Owner.GetAssetPreviewManagerID()); + if (this.m_Content.image != null) + { + flag7 = true; + } + if (filterItem != null) + { + if (this.m_Content.image == null) + { + this.m_Content.image = filterItem.icon; + } + if (isFolderBrowsing && !filterItem.isMainRepresentation) + { + flag7 = false; + } + } + } + float num6 = (!flag7) ? 0f : 2f; + position.height -= ObjectListArea.s_Styles.resultsGridLabel.fixedHeight + 2f * num6; + position.y += num6; + Rect rect2 = (!(this.m_Content.image == null)) ? ObjectListArea.LocalGroup.ActualImageDrawPosition(position, (float)this.m_Content.image.width, (float)this.m_Content.image.height) : default(Rect); + this.m_Content.text = null; + float num7 = 1f; + if (filterItem != null) + { + this.AddDirtyStateFor(filterItem.instanceID); + if (!filterItem.isMainRepresentation && isFolderBrowsing) + { + position.x += 4f; + position.y += 4f; + position.width -= 8f; + position.height -= 8f; + rect2 = ((!(this.m_Content.image == null)) ? ObjectListArea.LocalGroup.ActualImageDrawPosition(position, (float)this.m_Content.image.width, (float)this.m_Content.image.height) : default(Rect)); + num7 = this.m_ItemFader.GetAlpha(filterItem.instanceID); + if (num7 < 1f) + { + this.m_Owner.Repaint(); + } + } + if (flag7 && filterItem.iconDrawStyle == IconDrawStyle.NonTexture) + { + ObjectListArea.s_Styles.previewBg.Draw(rect2, GUIContent.none, false, false, false, false); + } + } + Color color = GUI.color; + if (flag2) + { + GUI.color *= new Color(0.85f, 0.9f, 1f); + } + if (this.m_Content.image != null) + { + Color color2 = GUI.color; + if (num7 < 1f) + { + GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, num7); + } + ObjectListArea.s_Styles.resultsGrid.Draw(rect2, this.m_Content, false, false, flag2, this.m_Owner.HasFocus()); + if (num7 < 1f) + { + GUI.color = color2; + } + } + if (flag2) + { + GUI.color = color; + } + if (flag7) + { + Rect position3 = new RectOffset(1, 1, 1, 1).Remove(ObjectListArea.s_Styles.textureIconDropShadow.border.Add(rect2)); + ObjectListArea.s_Styles.textureIconDropShadow.Draw(position3, GUIContent.none, false, false, flag2 || flag6, this.m_Owner.HasFocus() || flag5 || flag6); + } + if (!flag5) + { + text = this.m_Owner.GetCroppedLabelText(num, text, position.width); + ObjectListArea.s_Styles.resultsGridLabel.Draw(rect, text, false, false, flag2, this.m_Owner.HasFocus()); + } + if (flag) + { + ObjectListArea.s_Styles.subAssetExpandButton.Draw(position2, !this.ListMode, !this.ListMode, this.IsExpanded(num), false); + } + if (filterItem != null && filterItem.isMainRepresentation) + { + ProjectHooks.OnProjectWindowItem(filterItem.guid, position); + } + } + } + if (flag5) + { + if (this.ListMode) + { + float num8 = (float)(num4 + 16); + rect.x = selectionRect.x + num8; + rect.width -= rect.x; + } + else + { + rect.x -= 4f; + rect.width += 8f; + } + this.m_Owner.GetRenameOverlay().editFieldRect = rect; + this.m_Owner.HandleRenameOverlay(); + } + if (EditorApplication.projectWindowItemOnGUI != null && filterItem != null && this.m_Owner.allowUserRenderingHook) + { + EditorApplication.projectWindowItemOnGUI(filterItem.guid, selectionRect); + } + if (this.m_Owner.allowDragging) + { + this.HandleMouseWithDragging(num, controlIDFromInstanceID, position); + } + else + { + this.HandleMouseWithoutDragging(num, controlIDFromInstanceID, position); + } + } + private static Rect ActualImageDrawPosition(Rect position, float imageWidth, float imageHeight) + { + if (imageWidth > position.width || imageHeight > position.height) + { + Rect result = default(Rect); + Rect rect = default(Rect); + float imageAspect = imageWidth / imageHeight; + GUI.CalculateScaledTextureRects(position, ScaleMode.ScaleToFit, imageAspect, ref result, ref rect); + return result; + } + float left = position.x + Mathf.Round((position.width - imageWidth) / 2f); + float top = position.y + Mathf.Round((position.height - imageHeight) / 2f); + return new Rect(left, top, imageWidth, imageHeight); + } + public List> GetVisibleNameAndInstanceIDs() + { + List> list = new List>(); + if (this.m_NoneList.Length > 0) + { + list.Add(new KeyValuePair(this.m_NoneList[0].m_Name, this.m_NoneList[0].m_InstanceID)); + } + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + FilteredHierarchy.FilterResult filterResult = results[i]; + list.Add(new KeyValuePair(filterResult.name, filterResult.instanceID)); + } + for (int j = 0; j < this.m_ActiveBuiltinList.Length; j++) + { + list.Add(new KeyValuePair(this.m_ActiveBuiltinList[j].m_Name, this.m_ActiveBuiltinList[j].m_InstanceID)); + } + return list; + } + private void BeginPing(int instanceID) + { + } + public List GetInstanceIDs() + { + List list = new List(); + if (this.m_NoneList.Length > 0) + { + list.Add(this.m_NoneList[0].m_InstanceID); + } + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + FilteredHierarchy.FilterResult filterResult = results[i]; + list.Add(filterResult.instanceID); + } + if (this.m_Owner.m_State.m_NewAssetIndexInList >= 0) + { + list.Add(this.m_Owner.GetCreateAssetUtility().instanceID); + } + for (int j = 0; j < this.m_ActiveBuiltinList.Length; j++) + { + list.Add(this.m_ActiveBuiltinList[j].m_InstanceID); + } + return list; + } + public List GetNewSelection(int clickedInstanceID, bool beginOfDrag, bool useShiftAsActionKey) + { + List instanceIDs = this.GetInstanceIDs(); + List selectedInstanceIDs = this.m_Owner.m_State.m_SelectedInstanceIDs; + int lastClickedInstanceID = this.m_Owner.m_State.m_LastClickedInstanceID; + bool allowMultiSelect = this.m_Owner.allowMultiSelect; + return InternalEditorUtility.GetNewSelection(clickedInstanceID, instanceIDs, selectedInstanceIDs, lastClickedInstanceID, beginOfDrag, useShiftAsActionKey, allowMultiSelect); + } + public override void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool foldersFirst) + { + this.RefreshHierarchy(hierarchyType, searchFilter, foldersFirst); + this.RefreshBuiltinResourceList(searchFilter); + } + private void RefreshHierarchy(HierarchyType hierarchyType, SearchFilter searchFilter, bool foldersFirst) + { + this.m_FilteredHierarchy = new FilteredHierarchy(hierarchyType); + this.m_FilteredHierarchy.foldersFirst = foldersFirst; + this.m_FilteredHierarchy.searchFilter = searchFilter; + this.m_FilteredHierarchy.RefreshVisibleItems(this.m_Owner.m_State.m_ExpandedInstanceIDs); + } + private void RefreshBuiltinResourceList(SearchFilter searchFilter) + { + if (!this.m_Owner.allowBuiltinResources || searchFilter.GetState() == SearchFilter.State.FolderBrowsing || searchFilter.GetState() == SearchFilter.State.EmptySearchFilter) + { + this.m_CurrentBuiltinResources = new BuiltinResource[0]; + return; + } + List list = new List(); + if (searchFilter.assetLabels != null && searchFilter.assetLabels.Length > 0) + { + this.m_CurrentBuiltinResources = list.ToArray(); + return; + } + List list2 = new List(); + string[] classNames = searchFilter.classNames; + for (int i = 0; i < classNames.Length; i++) + { + string classString = classNames[i]; + int num = BaseObjectTools.StringToClassIDCaseInsensitive(classString); + if (num >= 0) + { + list2.Add(num); + } + } + if (list2.Count > 0) + { + foreach (KeyValuePair current in this.m_BuiltinResourceMap) + { + int classID = BaseObjectTools.StringToClassID(current.Key); + foreach (int current2 in list2) + { + if (BaseObjectTools.IsDerivedFromClassID(classID, current2)) + { + list.AddRange(current.Value); + } + } + } + } + BuiltinResource[] array = list.ToArray(); + if (array.Length > 0 && !string.IsNullOrEmpty(searchFilter.nameFilter)) + { + List list3 = new List(); + string value = searchFilter.nameFilter.ToLower(); + BuiltinResource[] array2 = array; + for (int j = 0; j < array2.Length; j++) + { + BuiltinResource builtinResource = array2[j]; + if (builtinResource.m_Name.ToLower().Contains(value)) + { + list3.Add(builtinResource); + } + } + array = list3.ToArray(); + } + this.m_CurrentBuiltinResources = array; + } + public bool IsBuiltinAsset(int instanceID) + { + foreach (KeyValuePair current in this.m_BuiltinResourceMap) + { + BuiltinResource[] value = current.Value; + for (int i = 0; i < value.Length; i++) + { + if (value[i].m_InstanceID == instanceID) + { + return true; + } + } + } + return false; + } + private void InitBuiltinAssetType(Type type) + { + if (type == null) + { + Debug.LogWarning("ObjectSelector::InitBuiltinAssetType: type is null!"); + return; + } + string text = type.ToString().Substring(type.Namespace.ToString().Length + 1); + int num = BaseObjectTools.StringToClassID(text); + if (num < 0) + { + Debug.LogWarning("ObjectSelector::InitBuiltinAssetType: class '" + text + "' not found"); + return; + } + BuiltinResource[] builtinResourceList = EditorGUIUtility.GetBuiltinResourceList(num); + if (builtinResourceList != null) + { + this.m_BuiltinResourceMap.Add(text, builtinResourceList); + } + } + public void InitBuiltinResources() + { + if (this.m_BuiltinResourceMap != null) + { + return; + } + this.m_BuiltinResourceMap = new Dictionary(); + if (this.m_ShowNoneItem) + { + this.m_NoneList = new BuiltinResource[1]; + this.m_NoneList[0] = new BuiltinResource(); + this.m_NoneList[0].m_InstanceID = 0; + this.m_NoneList[0].m_Name = "None"; + } + else + { + this.m_NoneList = new BuiltinResource[0]; + } + this.InitBuiltinAssetType(typeof(Mesh)); + this.InitBuiltinAssetType(typeof(Material)); + this.InitBuiltinAssetType(typeof(Texture2D)); + this.InitBuiltinAssetType(typeof(Font)); + this.InitBuiltinAssetType(typeof(Shader)); + this.InitBuiltinAssetType(typeof(Sprite)); + } + public void PrintBuiltinResourcesAvailable() + { + string text = string.Empty; + text += "ObjectSelector -Builtin Assets Available:\n"; + foreach (KeyValuePair current in this.m_BuiltinResourceMap) + { + BuiltinResource[] value = current.Value; + text = text + " " + current.Key + ": "; + for (int i = 0; i < value.Length; i++) + { + if (i != 0) + { + text += ", "; + } + text += value[i].m_Name; + } + text += "\n"; + } + Debug.Log(text); + } + public int IndexOfNewText(string newText, bool isCreatingNewFolder, bool foldersFirst) + { + int i = 0; + if (this.m_ShowNoneItem) + { + i++; + } + while (i < this.m_FilteredHierarchy.results.Length) + { + FilteredHierarchy.FilterResult filterResult = this.m_FilteredHierarchy.results[i]; + if (!foldersFirst || !filterResult.isFolder || isCreatingNewFolder) + { + if (foldersFirst && !filterResult.isFolder && isCreatingNewFolder) + { + break; + } + string assetPath = AssetDatabase.GetAssetPath(filterResult.instanceID); + if (EditorUtility.NaturalCompare(Path.GetFileNameWithoutExtension(assetPath), newText) > 0) + { + return i; + } + } + i++; + } + return i; + } + public int IndexOf(int instanceID) + { + if (instanceID == 0) + { + return -1; + } + int num = 0; + if (this.m_ShowNoneItem) + { + if (instanceID == 0) + { + return 0; + } + num++; + } + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + FilteredHierarchy.FilterResult filterResult = results[i]; + if (this.m_Owner.m_State.m_NewAssetIndexInList == num) + { + num++; + } + if (filterResult.instanceID == instanceID) + { + return num; + } + num++; + } + BuiltinResource[] activeBuiltinList = this.m_ActiveBuiltinList; + for (int j = 0; j < activeBuiltinList.Length; j++) + { + BuiltinResource builtinResource = activeBuiltinList[j]; + if (instanceID == builtinResource.m_InstanceID) + { + return num; + } + num++; + } + return -1; + } + public FilteredHierarchy.FilterResult LookupByInstanceID(int instanceID) + { + if (instanceID == 0) + { + return null; + } + int num = 0; + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + FilteredHierarchy.FilterResult filterResult = results[i]; + if (this.m_Owner.m_State.m_NewAssetIndexInList == num) + { + num++; + } + if (filterResult.instanceID == instanceID) + { + return filterResult; + } + num++; + } + return null; + } + public bool InstanceIdAtIndex(int index, out int instanceID) + { + instanceID = 0; + if (index >= this.m_Grid.rows * this.m_Grid.columns) + { + return false; + } + int num = 0; + if (this.m_ShowNoneItem) + { + if (index == 0) + { + return true; + } + num++; + } + FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; + for (int i = 0; i < results.Length; i++) + { + FilteredHierarchy.FilterResult filterResult = results[i]; + instanceID = filterResult.instanceID; + if (num == index) + { + return true; + } + num++; + } + BuiltinResource[] activeBuiltinList = this.m_ActiveBuiltinList; + for (int j = 0; j < activeBuiltinList.Length; j++) + { + BuiltinResource builtinResource = activeBuiltinList[j]; + instanceID = builtinResource.m_InstanceID; + if (num == index) + { + return true; + } + num++; + } + return index < this.m_Grid.rows * this.m_Grid.columns; + } + public virtual void StartDrag(int draggedInstanceID, List selectedInstanceIDs) + { + ProjectWindowUtil.StartDrag(draggedInstanceID, selectedInstanceIDs); + } + public DragAndDropVisualMode DoDrag(int dragToInstanceID, bool perform) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (!hierarchyProperty.Find(dragToInstanceID, null)) + { + hierarchyProperty = null; + } + return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + } + internal static int GetControlIDFromInstanceID(int instanceID) + { + return instanceID + 100000000; + } + public bool DoCharacterOffsetSelection() + { + if (Event.current.type == EventType.KeyDown && Event.current.shift) + { + StringComparison comparisonType = StringComparison.CurrentCultureIgnoreCase; + string text = string.Empty; + if (Selection.activeObject != null) + { + text = Selection.activeObject.name; + } + string value = new string(new char[] + { + Event.current.character + }); + List> visibleNameAndInstanceIDs = this.GetVisibleNameAndInstanceIDs(); + if (visibleNameAndInstanceIDs.Count == 0) + { + return false; + } + int num = 0; + if (text.StartsWith(value, comparisonType)) + { + for (int i = 0; i < visibleNameAndInstanceIDs.Count; i++) + { + if (visibleNameAndInstanceIDs[i].Key == text) + { + num = i + 1; + } + } + } + for (int j = 0; j < visibleNameAndInstanceIDs.Count; j++) + { + int index = (j + num) % visibleNameAndInstanceIDs.Count; + if (visibleNameAndInstanceIDs[index].Key.StartsWith(value, comparisonType)) + { + Selection.activeInstanceID = visibleNameAndInstanceIDs[index].Value; + this.m_Owner.Repaint(); + return true; + } + } + } + return false; + } + public void ShowObjectsInList(int[] instanceIDs) + { + this.m_FilteredHierarchy = new FilteredHierarchy(HierarchyType.Assets); + this.m_FilteredHierarchy.SetResults(instanceIDs); + } + public static void DrawIconAndLabel(Rect rect, FilteredHierarchy.FilterResult filterItem, string label, Texture2D icon, bool selected, bool focus) + { + float num = (!ObjectListArea.s_VCEnabled) ? 0f : 14f; + ObjectListArea.s_Styles.resultsLabel.padding.left = (int)(num + 16f + 2f); + ObjectListArea.s_Styles.resultsLabel.Draw(rect, label, false, false, selected, focus); + Rect position = rect; + position.width = 16f; + position.x += num * 0.5f; + if (icon != null) + { + GUI.DrawTexture(position, icon); + } + if (filterItem != null && filterItem.isMainRepresentation) + { + Rect drawRect = rect; + drawRect.width = num + 16f; + ProjectHooks.OnProjectWindowItem(filterItem.guid, drawRect); + } + } + } + private const int kHome = -2147483648; + private const int kEnd = 2147483647; + private const int kPageDown = 2147483646; + private const int kPageUp = -2147483647; + private const float k_ListModeVersionControlOverlayPadding = 14f; + private const double kDelayQueryAfterScroll = 0.0; + private const int kListLineHeight = 16; + private const int kSpaceForScrollBar = 16; + private const double kQueryDelay = 0.2; + private static ObjectListArea.Styles s_Styles; + private ObjectListAreaState m_State; + private int m_SelectionOffset; + private static bool s_VCEnabled; + private PingData m_Ping = new PingData(); + private EditorWindow m_Owner; + private int m_KeyboardControlID; + private Dictionary m_InstanceIDToCroppedNameMap = new Dictionary(); + private int m_WidthUsedForCroppingName; + private bool m_AllowRenameOnMouseUp = true; + private Vector2 m_LastScrollPosition = new Vector2(0f, 0f); + private double LastScrollTime; + public bool selectedAssetStoreAsset; + internal Texture m_SelectedObjectIcon; + private ObjectListArea.LocalGroup m_LocalAssets; + private List m_StoreAssets; + private string m_AssetStoreError = string.Empty; + private List m_Groups; + private Rect m_TotalRect; + private Rect m_VisibleRect; + private int m_pingIndex; + private int m_MinIconSize = 32; + private int m_MinGridSize = 16; + private int m_MaxGridSize = 96; + private bool m_AllowThumbnails = true; + private int m_LeftPaddingForPinging; + private bool m_FrameLastClickedItem; + private bool m_ShowLocalAssetsOnly = true; + public bool m_RequeryAssetStore; + private bool m_QueryInProgress; + private int m_ResizePreviewCacheTo; + private string m_LastAssetStoreQuerySearchFilter = string.Empty; + private string[] m_LastAssetStoreQueryClassName = new string[0]; + private string[] m_LastAssetStoreQueryLabels = new string[0]; + private double m_LastAssetStoreQueryChangeTime; + private double m_NextDirtyCheck; + private Action m_RepaintWantedCallback; + private Action m_ItemSelectedCallback; + private Action m_KeyboardInputCallback; + private Action m_GotKeyboardFocus; + private Func m_DrawLocalAssetHeader; + private Action m_AssetStoreSearchEnded; + internal static bool s_Debug; + public float m_SpaceBetween = 6f; + public float m_TopMargin = 10f; + public float m_BottomMargin = 10f; + public float m_RightMargin = 10f; + public float m_LeftMargin = 10f; + public bool allowDragging + { + get; + set; + } + public bool allowRenaming + { + get; + set; + } + public bool allowMultiSelect + { + get; + set; + } + public bool allowDeselection + { + get; + set; + } + public bool allowFocusRendering + { + get; + set; + } + public bool allowBuiltinResources + { + get; + set; + } + public bool allowUserRenderingHook + { + get; + set; + } + public bool allowFindNextShortcut + { + get; + set; + } + public bool foldersFirst + { + get; + set; + } + public Action repaintCallback + { + get + { + return this.m_RepaintWantedCallback; + } + set + { + this.m_RepaintWantedCallback = value; + } + } + public Action itemSelectedCallback + { + get + { + return this.m_ItemSelectedCallback; + } + set + { + this.m_ItemSelectedCallback = value; + } + } + public Action keyboardCallback + { + get + { + return this.m_KeyboardInputCallback; + } + set + { + this.m_KeyboardInputCallback = value; + } + } + public Action gotKeyboardFocus + { + get + { + return this.m_GotKeyboardFocus; + } + set + { + this.m_GotKeyboardFocus = value; + } + } + public Action assetStoreSearchEnded + { + get + { + return this.m_AssetStoreSearchEnded; + } + set + { + this.m_AssetStoreSearchEnded = value; + } + } + public Func drawLocalAssetHeader + { + get + { + return this.m_DrawLocalAssetHeader; + } + set + { + this.m_DrawLocalAssetHeader = value; + } + } + public int gridSize + { + get + { + return this.m_State.m_GridSize; + } + set + { + if (this.m_State.m_GridSize != value) + { + this.m_State.m_GridSize = value; + this.m_FrameLastClickedItem = true; + } + } + } + public int minGridSize + { + get + { + return this.m_MinGridSize; + } + } + public int maxGridSize + { + get + { + return this.m_MaxGridSize; + } + } + public int numItemsDisplayed + { + get + { + return this.m_LocalAssets.ItemCount; + } + } + public ObjectListArea(ObjectListAreaState state, EditorWindow owner, bool showNoneItem) + { + this.m_State = state; + this.m_Owner = owner; + AssetStorePreviewManager.MaxCachedImages = 72; + this.m_StoreAssets = new List(); + this.m_RequeryAssetStore = false; + this.m_LocalAssets = new ObjectListArea.LocalGroup(this, string.Empty, showNoneItem); + this.m_Groups = new List(); + this.m_Groups.Add(this.m_LocalAssets); + } + public void ShowObjectsInList(int[] instanceIDs) + { + this.Init(this.m_TotalRect, HierarchyType.Assets, new SearchFilter(), false); + this.m_LocalAssets.ShowObjectsInList(instanceIDs); + } + public void Init(Rect rect, HierarchyType hierarchyType, SearchFilter searchFilter, bool checkThumbnails) + { + this.m_VisibleRect = rect; + this.m_TotalRect = rect; + this.m_LocalAssets.UpdateFilter(hierarchyType, searchFilter, this.foldersFirst); + foreach (ObjectListArea.AssetStoreGroup current in this.m_StoreAssets) + { + current.UpdateFilter(hierarchyType, searchFilter, this.foldersFirst); + } + bool flag = searchFilter.GetState() == SearchFilter.State.FolderBrowsing; + if (flag) + { + this.m_LastAssetStoreQuerySearchFilter = string.Empty; + this.m_LastAssetStoreQueryClassName = new string[0]; + this.m_LastAssetStoreQueryLabels = new string[0]; + } + else + { + this.m_LastAssetStoreQuerySearchFilter = ((searchFilter.nameFilter != null) ? searchFilter.nameFilter : string.Empty); + bool flag2 = searchFilter.classNames == null || Array.IndexOf(searchFilter.classNames, "Object") >= 0; + this.m_LastAssetStoreQueryClassName = ((!flag2) ? searchFilter.classNames : new string[0]); + this.m_LastAssetStoreQueryLabels = ((searchFilter.assetLabels != null) ? searchFilter.assetLabels : new string[0]); + } + this.m_LastAssetStoreQueryChangeTime = EditorApplication.timeSinceStartup; + this.m_RequeryAssetStore = true; + this.m_ShowLocalAssetsOnly = (flag || searchFilter.GetState() != SearchFilter.State.SearchingInAssetStore); + this.m_AssetStoreError = string.Empty; + if (checkThumbnails) + { + this.m_AllowThumbnails = this.ObjectsHaveThumbnails(hierarchyType, searchFilter); + } + else + { + this.m_AllowThumbnails = true; + } + this.Repaint(); + this.ClearCroppedLabelCache(); + this.SetupData(true); + } + private bool HasFocus() + { + return !this.allowFocusRendering || (this.m_KeyboardControlID == GUIUtility.keyboardControl && this.m_Owner.m_Parent.hasFocus); + } + private void QueryAssetStore() + { + bool requeryAssetStore = this.m_RequeryAssetStore; + this.m_RequeryAssetStore = false; + if (this.m_ShowLocalAssetsOnly && !this.ShowAssetStoreHitsWhileSearchingLocalAssets()) + { + return; + } + bool flag = this.m_LastAssetStoreQuerySearchFilter != string.Empty || this.m_LastAssetStoreQueryClassName.Length != 0 || this.m_LastAssetStoreQueryLabels.Length != 0; + if (this.m_QueryInProgress) + { + return; + } + if (!flag) + { + this.ClearAssetStoreGroups(); + return; + } + if (this.m_LastAssetStoreQueryChangeTime + 0.2 > EditorApplication.timeSinceStartup) + { + this.m_RequeryAssetStore = true; + this.Repaint(); + return; + } + this.m_QueryInProgress = true; + string queryFilter = this.m_LastAssetStoreQuerySearchFilter + this.m_LastAssetStoreQueryClassName + this.m_LastAssetStoreQueryLabels; + AssetStoreResultBase.Callback callback = delegate(AssetStoreSearchResults results) + { + this.m_QueryInProgress = false; + if (queryFilter != this.m_LastAssetStoreQuerySearchFilter + this.m_LastAssetStoreQueryClassName + this.m_LastAssetStoreQueryLabels) + { + this.m_RequeryAssetStore = true; + } + if (results.error != null && results.error != string.Empty) + { + if (ObjectListArea.s_Debug) + { + Debug.LogError("Error performing Asset Store search: " + results.error); + } + else + { + Console.Write("Error performing Asset Store search: " + results.error); + } + this.m_AssetStoreError = results.error; + this.m_Groups.Clear(); + this.m_Groups.Add(this.m_LocalAssets); + this.Repaint(); + if (this.assetStoreSearchEnded != null) + { + this.assetStoreSearchEnded(); + } + return; + } + this.m_AssetStoreError = string.Empty; + List list2 = new List(); + foreach (ObjectListArea.AssetStoreGroup current2 in this.m_StoreAssets) + { + list2.Add(current2.Name); + } + this.m_Groups.Clear(); + this.m_Groups.Add(this.m_LocalAssets); + foreach (AssetStoreSearchResults.Group inGroup in results.groups) + { + list2.Remove(inGroup.name); + ObjectListArea.AssetStoreGroup assetStoreGroup = this.m_StoreAssets.Find((ObjectListArea.AssetStoreGroup g) => g.Name == inGroup.name); + if (assetStoreGroup == null) + { + assetStoreGroup = new ObjectListArea.AssetStoreGroup(this, inGroup.label, inGroup.name); + this.m_StoreAssets.Add(assetStoreGroup); + } + this.m_Groups.Add(assetStoreGroup); + if (inGroup.limit != 0) + { + assetStoreGroup.ItemsAvailable = inGroup.totalFound; + } + if (inGroup.offset == 0 && inGroup.limit != 0) + { + assetStoreGroup.Assets = inGroup.assets; + } + else + { + assetStoreGroup.Assets.AddRange(inGroup.assets); + } + } + foreach (string k in list2) + { + this.m_StoreAssets.RemoveAll((ObjectListArea.AssetStoreGroup g) => g.Name == k); + } + this.EnsureAssetStoreGroupsAreOpenIfAllClosed(); + this.Repaint(); + if (this.assetStoreSearchEnded != null) + { + this.assetStoreSearchEnded(); + } + }; + List list = new List(); + if (!requeryAssetStore) + { + foreach (ObjectListArea.AssetStoreGroup current in this.m_StoreAssets) + { + AssetStoreClient.SearchCount item = default(AssetStoreClient.SearchCount); + if (current.Visible && current.NeedItems) + { + item.offset = current.Assets.Count; + item.limit = current.ItemsWantedShown - item.offset; + } + item.name = current.Name; + list.Add(item); + } + } + AssetStoreClient.SearchAssets(this.m_LastAssetStoreQuerySearchFilter, this.m_LastAssetStoreQueryClassName, this.m_LastAssetStoreQueryLabels, list, callback); + } + private void EnsureAssetStoreGroupsAreOpenIfAllClosed() + { + if (this.m_StoreAssets.Count > 0) + { + int num = 0; + foreach (ObjectListArea.AssetStoreGroup current in this.m_StoreAssets) + { + if (current.Visible) + { + num++; + } + } + if (num == 0) + { + foreach (ObjectListArea.AssetStoreGroup current2 in this.m_StoreAssets) + { + ObjectListArea.Group arg_86_0 = current2; + bool flag = true; + current2.visiblePreference = flag; + arg_86_0.Visible = flag; + } + } + } + } + private void RequeryAssetStore() + { + this.m_RequeryAssetStore = true; + } + private void ClearAssetStoreGroups() + { + this.m_Groups.Clear(); + this.m_Groups.Add(this.m_LocalAssets); + this.m_StoreAssets.Clear(); + this.Repaint(); + } + public string GetAssetStoreButtonText() + { + string text = "Asset Store"; + if (this.ShowAssetStoreHitsWhileSearchingLocalAssets()) + { + for (int i = 0; i < this.m_StoreAssets.Count; i++) + { + if (i == 0) + { + text += ": "; + } + else + { + text += " ∕ "; + } + ObjectListArea.AssetStoreGroup assetStoreGroup = this.m_StoreAssets[i]; + text += ((assetStoreGroup.ItemsAvailable <= 999) ? assetStoreGroup.ItemsAvailable.ToString() : "999+"); + } + } + return text; + } + private bool ShowAssetStoreHitsWhileSearchingLocalAssets() + { + return EditorPrefs.GetBool("ShowAssetStoreSearchHits", true); + } + public void ShowAssetStoreHitCountWhileSearchingLocalAssetsChanged() + { + if (this.ShowAssetStoreHitsWhileSearchingLocalAssets()) + { + this.RequeryAssetStore(); + } + else + { + if (this.m_ShowLocalAssetsOnly) + { + this.ClearAssetStoreGroups(); + } + } + this.Repaint(); + } + internal float GetVisibleWidth() + { + return this.m_VisibleRect.width; + } + public void OnGUI(Rect position, int keyboardControlID) + { + if (ObjectListArea.s_Styles == null) + { + ObjectListArea.s_Styles = new ObjectListArea.Styles(); + } + ObjectListArea.s_VCEnabled = Provider.isActive; + Event current = Event.current; + this.m_TotalRect = position; + this.FrameLastClickedItemIfWanted(); + GUI.Label(this.m_TotalRect, GUIContent.none, ObjectListArea.s_Styles.iconAreaBg); + this.m_KeyboardControlID = keyboardControlID; + if (current.type == EventType.MouseDown && position.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = this.m_KeyboardControlID; + this.m_AllowRenameOnMouseUp = true; + this.Repaint(); + } + bool flag = this.m_KeyboardControlID == GUIUtility.keyboardControl; + if (flag != this.m_State.m_HadKeyboardFocusLastEvent) + { + this.m_State.m_HadKeyboardFocusLastEvent = flag; + if (flag) + { + if (current.type == EventType.MouseDown) + { + this.m_AllowRenameOnMouseUp = false; + } + if (this.m_GotKeyboardFocus != null) + { + this.m_GotKeyboardFocus(); + } + } + } + int activeInstanceID; + if (current.keyCode == KeyCode.Tab && current.type == EventType.KeyDown && !flag && !this.IsShowingAny(this.GetSelection()) && this.m_LocalAssets.InstanceIdAtIndex(0, out activeInstanceID)) + { + Selection.activeInstanceID = activeInstanceID; + } + this.HandleKeyboard(true); + this.HandleZoomScrolling(); + this.HandleListArea(); + this.DoOffsetSelection(); + this.HandleUnusedEvents(); + } + private void FrameLastClickedItemIfWanted() + { + if (this.m_FrameLastClickedItem && Event.current.type == EventType.Repaint) + { + this.m_FrameLastClickedItem = false; + double num = EditorApplication.timeSinceStartup - this.m_LocalAssets.m_LastClickedDrawTime; + if (this.m_State.m_SelectedInstanceIDs.Count > 0 && num < 0.2) + { + this.Frame(this.m_State.m_LastClickedInstanceID, true, false); + } + } + } + private void HandleUnusedEvents() + { + if (this.allowDeselection && Event.current.type == EventType.MouseDown && Event.current.button == 0 && this.m_TotalRect.Contains(Event.current.mousePosition)) + { + this.SetSelection(new int[0], false); + } + } + public bool CanShowThumbnails() + { + return this.m_AllowThumbnails; + } + private static string CreateFilterString(string searchString, string requiredClassName) + { + string text = searchString; + if (!string.IsNullOrEmpty(requiredClassName)) + { + text = text + " t:" + requiredClassName; + } + return text; + } + private bool ObjectsHaveThumbnails(HierarchyType type, SearchFilter searchFilter) + { + if (this.m_LocalAssets.HasBuiltinResources) + { + return true; + } + IHierarchyProperty hierarchyProperty = FilteredHierarchyProperty.CreateHierarchyPropertyForFilter(new FilteredHierarchy(type) + { + searchFilter = searchFilter + }); + int[] expanded = new int[0]; + if (hierarchyProperty.CountRemaining(expanded) == 0) + { + return true; + } + hierarchyProperty.Reset(); + while (hierarchyProperty.Next(expanded)) + { + if (hierarchyProperty.hasFullPreviewImage) + { + return true; + } + } + return false; + } + internal void OnDestroy() + { + AssetPreview.DeletePreviewTextureManagerByID(this.GetAssetPreviewManagerID()); + } + private void Repaint() + { + if (this.m_RepaintWantedCallback != null) + { + this.m_RepaintWantedCallback(); + } + } + public void OnEvent() + { + this.GetRenameOverlay().OnEvent(); + } + private CreateAssetUtility GetCreateAssetUtility() + { + return this.m_State.m_CreateAssetUtility; + } + private RenameOverlay GetRenameOverlay() + { + return this.m_State.m_RenameOverlay; + } + internal void BeginNamingNewAsset(string newAssetName, int instanceID, bool isCreatingNewFolder) + { + this.m_State.m_NewAssetIndexInList = this.m_LocalAssets.IndexOfNewText(newAssetName, isCreatingNewFolder, this.foldersFirst); + if (this.m_State.m_NewAssetIndexInList != -1) + { + this.Frame(instanceID, true, false); + this.GetRenameOverlay().BeginRename(newAssetName, instanceID, 0f); + } + else + { + Debug.LogError("Failed to insert new asset into list"); + } + this.Repaint(); + } + public bool BeginRename(float delay) + { + if (!this.allowRenaming) + { + return false; + } + if (this.m_State.m_SelectedInstanceIDs.Count != 1) + { + return false; + } + int num = this.m_State.m_SelectedInstanceIDs[0]; + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + return (!hierarchyProperty.Find(num, null) || hierarchyProperty.isMainRepresentation) && !this.m_LocalAssets.IsBuiltinAsset(num) && hierarchyProperty.isValid && this.GetRenameOverlay().BeginRename(hierarchyProperty.name, num, delay); + } + public void EndRename(bool acceptChanges) + { + if (this.GetRenameOverlay().IsRenaming()) + { + this.GetRenameOverlay().EndRename(acceptChanges); + this.RenameEnded(); + } + } + private void RenameEnded() + { + string name = (!string.IsNullOrEmpty(this.GetRenameOverlay().name)) ? this.GetRenameOverlay().name : this.GetRenameOverlay().originalName; + int userData = this.GetRenameOverlay().userData; + if (this.GetCreateAssetUtility().IsCreatingNewAsset()) + { + if (this.GetRenameOverlay().userAcceptedRename) + { + this.GetCreateAssetUtility().EndNewAssetCreation(name); + } + } + else + { + if (this.GetRenameOverlay().userAcceptedRename) + { + ObjectNames.SetNameSmartWithInstanceID(userData, name); + } + } + if (this.GetRenameOverlay().HasKeyboardFocus()) + { + GUIUtility.keyboardControl = this.m_KeyboardControlID; + } + if (this.GetRenameOverlay().userAcceptedRename) + { + this.Frame(userData, true, false); + } + this.ClearRenameState(); + } + private void ClearRenameState() + { + this.GetRenameOverlay().Clear(); + this.GetCreateAssetUtility().Clear(); + this.m_State.m_NewAssetIndexInList = -1; + } + internal void HandleRenameOverlay() + { + if (this.GetRenameOverlay().IsRenaming()) + { + GUIStyle textFieldStyle = (!this.IsListMode()) ? ObjectListArea.s_Styles.miniRenameField : null; + if (!this.GetRenameOverlay().OnGUI(textFieldStyle)) + { + this.RenameEnded(); + GUIUtility.ExitGUI(); + } + } + } + public bool IsSelected(int instanceID) + { + return this.m_State.m_SelectedInstanceIDs.Contains(instanceID); + } + public int[] GetSelection() + { + return this.m_State.m_SelectedInstanceIDs.ToArray(); + } + public bool IsLastClickedItemVisible() + { + return this.GetSelectedAssetIdx() >= 0; + } + public void SelectAll() + { + List instanceIDs = this.m_LocalAssets.GetInstanceIDs(); + this.SetSelection(instanceIDs.ToArray(), false); + } + private void SetSelection(int[] selectedInstanceIDs, bool doubleClicked) + { + this.InitSelection(selectedInstanceIDs); + if (this.m_ItemSelectedCallback != null) + { + this.Repaint(); + this.m_ItemSelectedCallback(doubleClicked); + } + } + public void InitSelection(int[] selectedInstanceIDs) + { + this.m_State.m_SelectedInstanceIDs = new List(selectedInstanceIDs); + if (this.m_State.m_SelectedInstanceIDs.Count > 0) + { + if (!this.m_State.m_SelectedInstanceIDs.Contains(this.m_State.m_LastClickedInstanceID)) + { + this.m_State.m_LastClickedInstanceID = this.m_State.m_SelectedInstanceIDs[this.m_State.m_SelectedInstanceIDs.Count - 1]; + } + } + else + { + this.m_State.m_LastClickedInstanceID = 0; + } + if (Selection.activeObject == null || Selection.activeObject.GetType() != typeof(AssetStoreAssetInspector)) + { + this.selectedAssetStoreAsset = false; + AssetStoreAssetSelection.Clear(); + } + } + private void SetSelection(AssetStoreAsset assetStoreResult, bool doubleClicked) + { + this.m_State.m_SelectedInstanceIDs.Clear(); + this.selectedAssetStoreAsset = true; + AssetStoreAssetSelection.Clear(); + AssetStorePreviewManager.CachedAssetStoreImage cachedAssetStoreImage = AssetStorePreviewManager.TextureFromUrl(assetStoreResult.staticPreviewURL, assetStoreResult.name, this.gridSize, ObjectListArea.s_Styles.resultsGridLabel, ObjectListArea.s_Styles.resultsGrid, true); + Texture2D image = cachedAssetStoreImage.image; + AssetStoreAssetSelection.AddAsset(assetStoreResult, image); + if (this.m_ItemSelectedCallback != null) + { + this.Repaint(); + this.m_ItemSelectedCallback(doubleClicked); + } + } + private void HandleZoomScrolling() + { + if (EditorGUI.actionKey && Event.current.type == EventType.ScrollWheel && this.m_TotalRect.Contains(Event.current.mousePosition)) + { + int num = (Event.current.delta.y <= 0f) ? 1 : -1; + this.gridSize = Mathf.Clamp(this.gridSize + num * 7, this.minGridSize, this.maxGridSize); + if (num < 0 && this.gridSize < this.m_MinIconSize) + { + this.gridSize = this.m_MinGridSize; + } + if (num > 0 && this.gridSize < this.m_MinIconSize) + { + this.gridSize = this.m_MinIconSize; + } + Event.current.Use(); + GUI.changed = true; + } + } + private bool IsPreviewIconExpansionModifierPressed() + { + return Event.current.alt; + } + public void HandleKeyboard(bool checkKeyboardControl) + { + if ((checkKeyboardControl && GUIUtility.keyboardControl != this.m_KeyboardControlID) || !GUI.enabled) + { + return; + } + if (this.m_KeyboardInputCallback != null) + { + this.m_KeyboardInputCallback(); + } + if (Event.current.type == EventType.KeyDown) + { + int num = 0; + if (this.IsLastClickedItemVisible()) + { + switch (Event.current.keyCode) + { + case KeyCode.UpArrow: + num = -this.m_LocalAssets.m_Grid.columns; + break; + case KeyCode.DownArrow: + num = this.m_LocalAssets.m_Grid.columns; + break; + case KeyCode.RightArrow: + if (!this.m_LocalAssets.ListMode && !this.IsPreviewIconExpansionModifierPressed()) + { + num = 1; + } + break; + case KeyCode.LeftArrow: + if (!this.m_LocalAssets.ListMode && !this.IsPreviewIconExpansionModifierPressed()) + { + num = -1; + } + break; + case KeyCode.Home: + num = -2147483648; + break; + case KeyCode.End: + num = 2147483647; + break; + case KeyCode.PageUp: + num = -2147483647; + break; + case KeyCode.PageDown: + num = 2147483646; + break; + } + } + else + { + switch (Event.current.keyCode) + { + case KeyCode.UpArrow: + case KeyCode.DownArrow: + case KeyCode.RightArrow: + case KeyCode.LeftArrow: + case KeyCode.Home: + case KeyCode.End: + case KeyCode.PageUp: + case KeyCode.PageDown: + this.SelectFirst(); + Event.current.Use(); + break; + } + } + if (num != 0) + { + if (this.GetSelectedAssetIdx() < 0 && !this.m_LocalAssets.ShowNone) + { + this.SetSelectedAssetByIdx(0); + } + else + { + this.m_SelectionOffset = num; + } + Event.current.Use(); + GUI.changed = true; + } + else + { + if (this.allowFindNextShortcut && this.m_LocalAssets.DoCharacterOffsetSelection()) + { + Event.current.Use(); + } + } + } + } + private void DoOffsetSelectionSpecialKeys(int idx, int maxIndex) + { + float num = this.m_LocalAssets.m_Grid.itemSize.y + this.m_LocalAssets.m_Grid.verticalSpacing; + int columns = this.m_LocalAssets.m_Grid.columns; + int selectionOffset = this.m_SelectionOffset; + if (selectionOffset != 2147483646) + { + if (selectionOffset != 2147483647) + { + if (selectionOffset == -2147483648) + { + this.m_SelectionOffset = 0; + this.SetSelectedAssetByIdx(0); + return; + } + if (selectionOffset == -2147483647) + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + ObjectListAreaState expr_8D_cp_0 = this.m_State; + expr_8D_cp_0.m_ScrollPosition.y = expr_8D_cp_0.m_ScrollPosition.y - this.m_TotalRect.height; + this.m_SelectionOffset = 0; + return; + } + this.m_SelectionOffset = -Mathf.RoundToInt(this.m_TotalRect.height / num) * columns; + this.m_SelectionOffset = Mathf.Max(-Mathf.FloorToInt((float)idx / (float)columns) * columns, this.m_SelectionOffset); + } + } + else + { + this.m_SelectionOffset = maxIndex - 1 - idx; + } + } + else + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + ObjectListAreaState expr_FF_cp_0 = this.m_State; + expr_FF_cp_0.m_ScrollPosition.y = expr_FF_cp_0.m_ScrollPosition.y + this.m_TotalRect.height; + this.m_SelectionOffset = 0; + return; + } + this.m_SelectionOffset = Mathf.RoundToInt(this.m_TotalRect.height / num) * columns; + int num2 = maxIndex - idx - 1; + this.m_SelectionOffset = Mathf.Min(Mathf.FloorToInt((float)num2 / (float)columns) * columns, this.m_SelectionOffset); + } + } + private void DoOffsetSelection() + { + if (this.m_SelectionOffset == 0) + { + return; + } + int maxIdx = this.GetMaxIdx(); + if (this.maxGridSize == -1) + { + return; + } + int num = this.GetSelectedAssetIdx(); + num = ((num >= 0) ? num : 0); + this.DoOffsetSelectionSpecialKeys(num, maxIdx); + if (this.m_SelectionOffset == 0) + { + return; + } + int num2 = num + this.m_SelectionOffset; + this.m_SelectionOffset = 0; + if (num2 < 0) + { + num2 = num; + } + else + { + num2 = Mathf.Min(num2, maxIdx); + } + int selectedAssetByIdx = num2; + this.SetSelectedAssetByIdx(selectedAssetByIdx); + } + public void OffsetSelection(int selectionOffset) + { + this.m_SelectionOffset = selectionOffset; + } + public void SelectFirst() + { + int selectedAssetByIdx = 0; + if (this.m_ShowLocalAssetsOnly && this.m_LocalAssets.ShowNone) + { + selectedAssetByIdx = 1; + } + this.SetSelectedAssetByIdx(selectedAssetByIdx); + } + public int GetInstanceIDByIndex(int index) + { + int result; + if (this.m_LocalAssets.InstanceIdAtIndex(index, out result)) + { + return result; + } + return 0; + } + private void SetSelectedAssetByIdx(int selectedIdx) + { + int num; + if (this.m_LocalAssets.InstanceIdAtIndex(selectedIdx, out num)) + { + Rect r = this.m_LocalAssets.m_Grid.CalcRect(selectedIdx, 0f); + this.ScrollToPosition(ObjectListArea.AdjustRectForFraming(r)); + this.Repaint(); + int[] selectedInstanceIDs; + if (this.IsLocalAssetsCurrentlySelected()) + { + selectedInstanceIDs = this.m_LocalAssets.GetNewSelection(num, false, true).ToArray(); + } + else + { + selectedInstanceIDs = new int[] + { + num + }; + } + this.SetSelection(selectedInstanceIDs, false); + this.m_State.m_LastClickedInstanceID = num; + return; + } + selectedIdx -= this.m_LocalAssets.m_Grid.rows * this.m_LocalAssets.m_Grid.columns; + float num2 = this.m_LocalAssets.Height; + foreach (ObjectListArea.AssetStoreGroup current in this.m_StoreAssets) + { + if (!current.Visible) + { + num2 += current.Height; + } + else + { + AssetStoreAsset assetStoreAsset = current.AssetAtIndex(selectedIdx); + if (assetStoreAsset != null) + { + Rect r2 = current.m_Grid.CalcRect(selectedIdx, num2); + this.ScrollToPosition(ObjectListArea.AdjustRectForFraming(r2)); + this.Repaint(); + this.SetSelection(assetStoreAsset, false); + break; + } + selectedIdx -= current.m_Grid.rows * current.m_Grid.columns; + num2 += current.Height; + } + } + } + private void Reveal(int instanceID) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, null) && hierarchyProperty.Parent() && !hierarchyProperty.isFolder) + { + int instanceID2 = hierarchyProperty.instanceID; + this.m_LocalAssets.ChangeExpandedState(instanceID2, true); + } + } + public bool Frame(int instanceID, bool frame, bool ping) + { + if (ObjectListArea.s_Styles == null) + { + ObjectListArea.s_Styles = new ObjectListArea.Styles(); + } + int num = -1; + if (this.GetCreateAssetUtility().IsCreatingNewAsset() && this.m_State.m_NewAssetIndexInList != -1 && this.GetCreateAssetUtility().instanceID == instanceID) + { + num = this.m_State.m_NewAssetIndexInList; + } + if (frame) + { + this.Reveal(instanceID); + } + if (num == -1) + { + num = this.m_LocalAssets.IndexOf(instanceID); + } + if (num != -1) + { + if (frame) + { + float yOffset = 0f; + Rect r = this.m_LocalAssets.m_Grid.CalcRect(num, yOffset); + this.CenterRect(ObjectListArea.AdjustRectForFraming(r)); + this.Repaint(); + } + if (ping) + { + this.BeginPing(instanceID); + } + return true; + } + return false; + } + private int GetSelectedAssetIdx() + { + int num = this.m_LocalAssets.IndexOf(this.m_State.m_LastClickedInstanceID); + if (num != -1) + { + return num; + } + num = this.m_LocalAssets.m_Grid.rows * this.m_LocalAssets.m_Grid.columns; + if (AssetStoreAssetSelection.Count == 0) + { + return -1; + } + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset == null) + { + return -1; + } + int id = firstAsset.id; + foreach (ObjectListArea.AssetStoreGroup current in this.m_StoreAssets) + { + if (current.Visible) + { + int num2 = current.IndexOf(id); + if (num2 != -1) + { + return num + num2; + } + num += current.m_Grid.rows * current.m_Grid.columns; + } + } + return -1; + } + private int GetMaxIdx() + { + int num = 0; + int num2 = 0; + int num3 = 0; + foreach (ObjectListArea.Group current in this.m_Groups) + { + if (this.m_ShowLocalAssetsOnly) + { + if (current is ObjectListArea.AssetStoreGroup) + { + continue; + } + } + else + { + if (current is ObjectListArea.LocalGroup) + { + continue; + } + } + if (current.Visible) + { + num2 += num3; + num3 = current.m_Grid.rows * current.m_Grid.columns; + num = current.ItemCount - 1; + } + } + int num4 = num2 + num; + return (num3 + num4 != 0) ? num4 : -1; + } + private bool IsLocalAssetsCurrentlySelected() + { + int num = this.m_State.m_SelectedInstanceIDs.FirstOrDefault(); + if (num != 0) + { + int num2 = this.m_LocalAssets.IndexOf(num); + return num2 != -1; + } + return false; + } + private void SetupData(bool forceReflow) + { + foreach (ObjectListArea.Group current in this.m_Groups) + { + current.UpdateAssets(); + } + if (forceReflow || Event.current.type == EventType.Layout) + { + this.Reflow(); + } + } + private bool IsObjectSelector() + { + return this.m_LocalAssets.ShowNone; + } + private void HandleListArea() + { + this.SetupData(false); + if (!this.IsObjectSelector() && !this.m_QueryInProgress) + { + if (this.m_StoreAssets.Exists((ObjectListArea.AssetStoreGroup g) => g.NeedItems) || this.m_RequeryAssetStore) + { + this.QueryAssetStore(); + } + } + float num = 0f; + foreach (ObjectListArea.Group current in this.m_Groups) + { + if (this.m_ShowLocalAssetsOnly) + { + if (current is ObjectListArea.AssetStoreGroup) + { + continue; + } + } + else + { + if (current is ObjectListArea.LocalGroup) + { + continue; + } + } + num += current.Height; + if (this.m_LocalAssets.ShowNone) + { + break; + } + } + Rect totalRect = this.m_TotalRect; + Rect viewRect = new Rect(0f, 0f, 1f, num); + bool flag = num > this.m_TotalRect.height; + this.m_VisibleRect = this.m_TotalRect; + if (flag) + { + this.m_VisibleRect.width = this.m_VisibleRect.width - 16f; + } + double timeSinceStartup = EditorApplication.timeSinceStartup; + this.m_LastScrollPosition = this.m_State.m_ScrollPosition; + bool flag2 = false; + this.m_State.m_ScrollPosition = GUI.BeginScrollView(totalRect, this.m_State.m_ScrollPosition, viewRect); + Vector2 scrollPosition = this.m_State.m_ScrollPosition; + if (this.m_LastScrollPosition != this.m_State.m_ScrollPosition) + { + this.LastScrollTime = timeSinceStartup; + } + float num2 = 0f; + foreach (ObjectListArea.Group current2 in this.m_Groups) + { + if (this.m_ShowLocalAssetsOnly) + { + if (current2 is ObjectListArea.AssetStoreGroup) + { + continue; + } + } + else + { + if (current2 is ObjectListArea.LocalGroup) + { + continue; + } + } + current2.Draw(num2, scrollPosition); + flag2 = (flag2 || current2.NeedsRepaint); + num2 += current2.Height; + if (this.m_LocalAssets.ShowNone) + { + break; + } + } + this.HandlePing(); + if (flag2) + { + this.Repaint(); + } + GUI.EndScrollView(); + if (this.m_ResizePreviewCacheTo > 0 && AssetStorePreviewManager.MaxCachedImages != this.m_ResizePreviewCacheTo) + { + AssetStorePreviewManager.MaxCachedImages = this.m_ResizePreviewCacheTo; + } + if (Event.current.type == EventType.Repaint) + { + AssetStorePreviewManager.AbortOlderThan(timeSinceStartup); + } + if (!this.m_ShowLocalAssetsOnly && !string.IsNullOrEmpty(this.m_AssetStoreError)) + { + Vector2 vector = EditorStyles.label.CalcSize(ObjectListArea.s_Styles.m_AssetStoreNotAvailableText); + Rect position = new Rect(this.m_TotalRect.x + 2f + Mathf.Max(0f, (this.m_TotalRect.width - vector.x) * 0.5f), this.m_TotalRect.y + 10f, vector.x, 20f); + EditorGUI.BeginDisabledGroup(true); + GUI.Label(position, ObjectListArea.s_Styles.m_AssetStoreNotAvailableText, EditorStyles.label); + EditorGUI.EndDisabledGroup(); + } + } + private bool IsListMode() + { + if (this.allowMultiSelect) + { + return this.gridSize == 16; + } + return this.gridSize == 16 || !this.CanShowThumbnails(); + } + private void Reflow() + { + if (this.gridSize < 20) + { + this.gridSize = this.m_MinGridSize; + } + else + { + if (this.gridSize < this.m_MinIconSize) + { + this.gridSize = this.m_MinIconSize; + } + } + if (this.IsListMode()) + { + foreach (ObjectListArea.Group current in this.m_Groups) + { + current.ListMode = true; + this.UpdateGroupSizes(current); + if (this.m_LocalAssets.ShowNone) + { + break; + } + } + this.m_ResizePreviewCacheTo = Mathf.CeilToInt(this.m_TotalRect.height / 16f) + 10; + } + else + { + float num = 0f; + foreach (ObjectListArea.Group current2 in this.m_Groups) + { + current2.ListMode = false; + this.UpdateGroupSizes(current2); + num += current2.Height; + if (this.m_LocalAssets.ShowNone) + { + break; + } + } + bool flag = this.m_TotalRect.height < num; + if (flag) + { + foreach (ObjectListArea.Group current3 in this.m_Groups) + { + current3.m_Grid.fixedWidth = this.m_TotalRect.width - 16f; + current3.m_Grid.InitNumRowsAndColumns(current3.ItemCount, current3.m_Grid.CalcRows(current3.ItemsWantedShown)); + current3.UpdateHeight(); + if (this.m_LocalAssets.ShowNone) + { + break; + } + } + } + int maxNumVisibleItems = this.GetMaxNumVisibleItems(); + this.m_ResizePreviewCacheTo = maxNumVisibleItems * 2; + AssetPreview.SetPreviewTextureCacheSize(maxNumVisibleItems * 2 + 30, this.GetAssetPreviewManagerID()); + } + } + private void UpdateGroupSizes(ObjectListArea.Group g) + { + if (g.ListMode) + { + g.m_Grid.fixedWidth = this.m_VisibleRect.width; + g.m_Grid.itemSize = new Vector2(this.m_VisibleRect.width, 16f); + g.m_Grid.topMargin = 0f; + g.m_Grid.bottomMargin = 0f; + g.m_Grid.leftMargin = 0f; + g.m_Grid.rightMargin = 0f; + g.m_Grid.verticalSpacing = 0f; + g.m_Grid.minHorizontalSpacing = 0f; + g.m_Grid.InitNumRowsAndColumns(g.ItemCount, g.ItemsWantedShown); + g.UpdateHeight(); + } + else + { + g.m_Grid.fixedWidth = this.m_TotalRect.width; + g.m_Grid.itemSize = new Vector2((float)this.gridSize, (float)(this.gridSize + 14)); + g.m_Grid.topMargin = 10f; + g.m_Grid.bottomMargin = 10f; + g.m_Grid.leftMargin = 10f; + g.m_Grid.rightMargin = 10f; + g.m_Grid.verticalSpacing = 15f; + g.m_Grid.minHorizontalSpacing = 12f; + g.m_Grid.InitNumRowsAndColumns(g.ItemCount, g.m_Grid.CalcRows(g.ItemsWantedShown)); + g.UpdateHeight(); + } + } + private int GetMaxNumVisibleItems() + { + return this.m_LocalAssets.m_Grid.GetMaxVisibleItems(this.m_TotalRect.height); + } + private static Rect AdjustRectForFraming(Rect r) + { + r.height += ObjectListArea.s_Styles.resultsGridLabel.fixedHeight * 2f; + r.y -= ObjectListArea.s_Styles.resultsGridLabel.fixedHeight; + return r; + } + private void CenterRect(Rect r) + { + float num = (r.yMax + r.yMin) / 2f; + float num2 = this.m_TotalRect.height / 2f; + this.m_State.m_ScrollPosition.y = num - num2; + this.ScrollToPosition(r); + } + private void ScrollToPosition(Rect r) + { + float y = r.y; + float yMax = r.yMax; + float height = this.m_TotalRect.height; + if (yMax > height + this.m_State.m_ScrollPosition.y) + { + this.m_State.m_ScrollPosition.y = yMax - height; + } + if (y < this.m_State.m_ScrollPosition.y) + { + this.m_State.m_ScrollPosition.y = y; + } + this.m_State.m_ScrollPosition.y = Mathf.Max(this.m_State.m_ScrollPosition.y, 0f); + } + public void OnInspectorUpdate() + { + if (EditorApplication.timeSinceStartup > this.m_NextDirtyCheck && this.m_LocalAssets.IsAnyLastRenderedAssetsDirty()) + { + AssetPreview.ClearTemporaryAssetPreviews(); + this.Repaint(); + this.m_NextDirtyCheck = EditorApplication.timeSinceStartup + 0.77; + } + if (AssetStorePreviewManager.CheckRepaint()) + { + this.Repaint(); + } + } + private void ClearCroppedLabelCache() + { + this.m_InstanceIDToCroppedNameMap.Clear(); + } + protected string GetCroppedLabelText(int instanceID, string fullText, float cropWidth) + { + if (this.m_WidthUsedForCroppingName != (int)cropWidth) + { + this.ClearCroppedLabelCache(); + } + string text; + if (!this.m_InstanceIDToCroppedNameMap.TryGetValue(instanceID, out text)) + { + if (this.m_InstanceIDToCroppedNameMap.Count > this.GetMaxNumVisibleItems() * 2 + 30) + { + this.ClearCroppedLabelCache(); + } + int numCharactersThatFitWithinWidth = ObjectListArea.s_Styles.resultsGridLabel.GetNumCharactersThatFitWithinWidth(fullText, cropWidth); + if (numCharactersThatFitWithinWidth == -1) + { + this.Repaint(); + return fullText; + } + if (numCharactersThatFitWithinWidth > 1 && numCharactersThatFitWithinWidth != fullText.Length) + { + text = fullText.Substring(0, numCharactersThatFitWithinWidth - 1) + "…"; + } + else + { + text = fullText; + } + this.m_InstanceIDToCroppedNameMap[instanceID] = text; + this.m_WidthUsedForCroppingName = (int)cropWidth; + } + return text; + } + public bool IsShowing(int instanceID) + { + return this.m_LocalAssets.IndexOf(instanceID) >= 0; + } + public bool IsShowingAny(int[] instanceIDs) + { + if (instanceIDs.Length == 0) + { + return false; + } + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + if (this.IsShowing(instanceID)) + { + return true; + } + } + return false; + } + protected Texture GetIconByInstanceID(int instanceID) + { + Texture result = null; + if (instanceID != 0) + { + string assetPath = AssetDatabase.GetAssetPath(instanceID); + result = AssetDatabase.GetCachedIcon(assetPath); + } + return result; + } + internal int GetAssetPreviewManagerID() + { + return this.m_Owner.GetInstanceID(); + } + public void BeginPing(int instanceID) + { + if (ObjectListArea.s_Styles == null) + { + ObjectListArea.s_Styles = new ObjectListArea.Styles(); + } + int num = this.m_LocalAssets.IndexOf(instanceID); + if (num != -1) + { + string text = null; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, null)) + { + text = hierarchyProperty.name; + } + if (text == null) + { + return; + } + this.m_Ping.m_TimeStart = Time.realtimeSinceStartup; + this.m_Ping.m_AvailableWidth = this.m_VisibleRect.width; + this.m_pingIndex = num; + float num2 = (!ObjectListArea.s_VCEnabled) ? 0f : 14f; + GUIContent gUIContent = new GUIContent((!this.m_LocalAssets.ListMode) ? this.GetCroppedLabelText(instanceID, text, (float)this.m_WidthUsedForCroppingName) : text); + string label = gUIContent.text; + if (this.m_LocalAssets.ListMode) + { + this.m_Ping.m_PingStyle = ObjectListArea.s_Styles.ping; + Vector2 vector = this.m_Ping.m_PingStyle.CalcSize(gUIContent); + this.m_Ping.m_ContentRect.width = vector.x + num2 + 16f; + this.m_Ping.m_ContentRect.height = vector.y; + this.m_LeftPaddingForPinging = ((!hierarchyProperty.isMainRepresentation) ? 28 : 16); + FilteredHierarchy.FilterResult res = this.m_LocalAssets.LookupByInstanceID(instanceID); + this.m_Ping.m_ContentDraw = delegate(Rect r) + { + ObjectListArea.LocalGroup.DrawIconAndLabel(r, res, label, hierarchyProperty.icon, false, false); + }; + } + else + { + this.m_Ping.m_PingStyle = ObjectListArea.s_Styles.miniPing; + Vector2 vector2 = this.m_Ping.m_PingStyle.CalcSize(gUIContent); + this.m_Ping.m_ContentRect.width = vector2.x; + this.m_Ping.m_ContentRect.height = vector2.y; + this.m_Ping.m_ContentDraw = delegate(Rect r) + { + TextAnchor alignment = ObjectListArea.s_Styles.resultsGridLabel.alignment; + ObjectListArea.s_Styles.resultsGridLabel.alignment = TextAnchor.UpperLeft; + ObjectListArea.s_Styles.resultsGridLabel.Draw(r, label, false, false, false, false); + ObjectListArea.s_Styles.resultsGridLabel.alignment = alignment; + }; + } + Vector2 vector3 = this.CalculatePingPosition(); + this.m_Ping.m_ContentRect.x = vector3.x; + this.m_Ping.m_ContentRect.y = vector3.y; + this.Repaint(); + } + } + public void EndPing() + { + this.m_Ping.m_TimeStart = -1f; + } + private void HandlePing() + { + if (this.m_Ping.isPinging && !this.m_LocalAssets.ListMode) + { + Vector2 vector = this.CalculatePingPosition(); + this.m_Ping.m_ContentRect.x = vector.x; + this.m_Ping.m_ContentRect.y = vector.y; + } + this.m_Ping.HandlePing(); + if (this.m_Ping.isPinging) + { + this.Repaint(); + } + } + private Vector2 CalculatePingPosition() + { + Rect rect = this.m_LocalAssets.m_Grid.CalcRect(this.m_pingIndex, 0f); + if (this.m_LocalAssets.ListMode) + { + return new Vector2((float)this.m_LeftPaddingForPinging, rect.y); + } + float width = this.m_Ping.m_ContentRect.width; + return new Vector2(rect.center.x - width / 2f + (float)this.m_Ping.m_PingStyle.padding.left, rect.yMax - ObjectListArea.s_Styles.resultsGridLabel.fixedHeight + 3f); + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectListAreaState.cs b/UnityEditor/UnityEditor/ObjectListAreaState.cs new file mode 100644 index 00000000..04fb7b4f --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectListAreaState.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ObjectListAreaState + { + public List m_SelectedInstanceIDs = new List(); + public int m_LastClickedInstanceID; + public bool m_HadKeyboardFocusLastEvent; + public List m_ExpandedInstanceIDs = new List(); + public RenameOverlay m_RenameOverlay = new RenameOverlay(); + public CreateAssetUtility m_CreateAssetUtility = new CreateAssetUtility(); + public int m_NewAssetIndexInList = -1; + public Vector2 m_ScrollPosition; + public int m_GridSize = 64; + public void OnAwake() + { + this.m_NewAssetIndexInList = -1; + this.m_RenameOverlay.Clear(); + this.m_CreateAssetUtility = new CreateAssetUtility(); + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectNames.cs b/UnityEditor/UnityEditor/ObjectNames.cs new file mode 100644 index 00000000..45edac2b --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectNames.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class ObjectNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string NicifyVariableName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetInspectorTitle(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetClassName(UnityEngine.Object obj); + internal static string GetTypeName(UnityEngine.Object obj) + { + string text = AssetDatabase.GetAssetPath(obj).ToLower(); + if (text.EndsWith(".unity")) + { + return "Scene"; + } + if (text.EndsWith(".guiskin")) + { + return "GUI Skin"; + } + if (Directory.Exists(AssetDatabase.GetAssetPath(obj))) + { + return "Folder"; + } + if (obj.GetType() == typeof(UnityEngine.Object)) + { + return Path.GetExtension(text) + " File"; + } + return ObjectNames.GetClassName(obj); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetDragAndDropTitle(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNameSmart(UnityEngine.Object obj, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetNameSmartWithInstanceID(int instanceID, string name); + [Obsolete("Please use NicifyVariableName instead")] + public static string MangleVariableName(string name) + { + return ObjectNames.NicifyVariableName(name); + } + [Obsolete("Please use GetInspectorTitle instead")] + public static string GetPropertyEditorTitle(UnityEngine.Object obj) + { + return ObjectNames.GetInspectorTitle(obj); + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectPreview.cs b/UnityEditor/UnityEditor/ObjectPreview.cs new file mode 100644 index 00000000..8d284945 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectPreview.cs @@ -0,0 +1,220 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class ObjectPreview : IPreviewable + { + private class Styles + { + public GUIStyle preBackground = "preBackground"; + public GUIStyle preBackgroundSolid = new GUIStyle("preBackground"); + public GUIStyle previewMiniLabel = new GUIStyle(EditorStyles.whiteMiniLabel); + public GUIStyle dropShadowLabelStyle = new GUIStyle("PreOverlayLabel"); + public Styles() + { + this.preBackgroundSolid.overflow = this.preBackgroundSolid.border; + this.previewMiniLabel.alignment = TextAnchor.UpperCenter; + } + } + private const int kPreviewLabelHeight = 12; + private const int kPreviewMinSize = 55; + private const int kGridTargetCount = 25; + private const int kGridSpacing = 10; + private const int kPreviewLabelPadding = 5; + private static ObjectPreview.Styles s_Styles; + protected UnityEngine.Object[] m_Targets; + protected int m_ReferenceTargetIndex; + public virtual UnityEngine.Object target + { + get + { + return this.m_Targets[this.m_ReferenceTargetIndex]; + } + } + public virtual void Initialize(UnityEngine.Object[] targets) + { + this.m_ReferenceTargetIndex = 0; + this.m_Targets = targets; + } + public virtual bool MoveNextTarget() + { + this.m_ReferenceTargetIndex++; + return this.m_ReferenceTargetIndex < this.m_Targets.Length - 1; + } + public virtual void ResetTarget() + { + this.m_ReferenceTargetIndex = 0; + } + public virtual bool HasPreviewGUI() + { + return false; + } + public virtual GUIContent GetPreviewTitle() + { + GUIContent gUIContent = new GUIContent(); + if (this.m_Targets.Length == 1) + { + gUIContent.text = this.target.name; + } + else + { + gUIContent.text = this.m_Targets.Length + " "; + if (this.target is MonoBehaviour) + { + GUIContent expr_58 = gUIContent; + expr_58.text += MonoScript.FromMonoBehaviour(this.target as MonoBehaviour).GetClass().Name; + } + else + { + GUIContent expr_88 = gUIContent; + expr_88.text += ObjectNames.NicifyVariableName(ObjectNames.GetClassName(this.target)); + } + GUIContent expr_A9 = gUIContent; + expr_A9.text += "s"; + } + return gUIContent; + } + public virtual void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type == EventType.Repaint) + { + background.Draw(r, false, false, false, false); + } + } + public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.OnPreviewGUI(r, background); + } + public virtual void OnPreviewSettings() + { + } + public virtual string GetInfoString() + { + return string.Empty; + } + public void DrawPreview(Rect previewArea) + { + ObjectPreview.DrawPreview(this, previewArea, this.m_Targets); + } + internal static void DrawPreview(IPreviewable defaultPreview, Rect previewArea, UnityEngine.Object[] targets) + { + if (ObjectPreview.s_Styles == null) + { + ObjectPreview.s_Styles = new ObjectPreview.Styles(); + } + string text = string.Empty; + Event current = Event.current; + if (targets.Length > 1) + { + Rect rect = new RectOffset(16, 16, 20, 25).Remove(previewArea); + int num = Mathf.Max(1, Mathf.FloorToInt((rect.height + 10f) / 77f)); + int num2 = Mathf.Max(1, Mathf.FloorToInt((rect.width + 10f) / 65f)); + int num3 = num * num2; + int num4 = Mathf.Min(targets.Length, 25); + bool flag = true; + int[] array = new int[] + { + num2, + num + }; + if (num4 < num3) + { + array = ObjectPreview.GetGridDivision(rect, num4, 12); + flag = false; + } + int num5 = Mathf.Min(array[0] * array[1], targets.Length); + rect.width += 10f; + rect.height += 10f; + Vector2 vector = new Vector2((float)Mathf.FloorToInt(rect.width / (float)array[0] - 10f), (float)Mathf.FloorToInt(rect.height / (float)array[1] - 10f)); + float num6 = Mathf.Min(vector.x, vector.y - 12f); + if (flag) + { + num6 = Mathf.Min(num6, 55f); + } + bool flag2 = current.type == EventType.MouseDown && current.button == 0 && current.clickCount == 2 && previewArea.Contains(current.mousePosition); + defaultPreview.ResetTarget(); + for (int i = 0; i < num5; i++) + { + Rect position = new Rect(rect.x + (float)(i % array[0]) * rect.width / (float)array[0], rect.y + (float)(i / array[0]) * rect.height / (float)array[1], vector.x, vector.y); + if (flag2 && position.Contains(Event.current.mousePosition)) + { + Selection.objects = new UnityEngine.Object[] + { + defaultPreview.target + }; + } + position.height -= 12f; + Rect position2 = new Rect(position.x + (position.width - num6) * 0.5f, position.y + (position.height - num6) * 0.5f, num6, num6); + GUI.BeginGroup(position2); + Editor.m_AllowMultiObjectAccess = false; + defaultPreview.OnInteractivePreviewGUI(new Rect(0f, 0f, num6, num6), ObjectPreview.s_Styles.preBackgroundSolid); + Editor.m_AllowMultiObjectAccess = true; + GUI.EndGroup(); + position.y = position2.yMax; + position.height = 16f; + GUI.Label(position, targets[i].name, ObjectPreview.s_Styles.previewMiniLabel); + defaultPreview.MoveNextTarget(); + } + defaultPreview.ResetTarget(); + if (Event.current.type == EventType.Repaint) + { + text = string.Format("Previewing {0} of {1} Objects", num5, targets.Length); + } + } + else + { + defaultPreview.OnInteractivePreviewGUI(previewArea, ObjectPreview.s_Styles.preBackground); + if (Event.current.type == EventType.Repaint) + { + text = defaultPreview.GetInfoString(); + if (text != string.Empty) + { + text = text.Replace("\n", " "); + text = string.Format("{0}\n{1}", defaultPreview.target.name, text); + } + } + } + if (Event.current.type == EventType.Repaint && text != string.Empty) + { + float num7 = ObjectPreview.s_Styles.dropShadowLabelStyle.CalcHeight(GUIContent.Temp(text), previewArea.width); + EditorGUI.DropShadowLabel(new Rect(previewArea.x, previewArea.yMax - num7 - 5f, previewArea.width, num7), text); + } + } + private static int[] GetGridDivision(Rect rect, int minimumNr, int labelHeight) + { + float num = Mathf.Sqrt(rect.width * rect.height / (float)minimumNr); + int num2 = Mathf.FloorToInt(rect.width / num); + int num3 = Mathf.FloorToInt(rect.height / (num + (float)labelHeight)); + while (num2 * num3 < minimumNr) + { + float num4 = ObjectPreview.AbsRatioDiff((float)(num2 + 1) / rect.width, (float)num3 / (rect.height - (float)(num3 * labelHeight))); + float num5 = ObjectPreview.AbsRatioDiff((float)num2 / rect.width, (float)(num3 + 1) / (rect.height - (float)((num3 + 1) * labelHeight))); + if (num4 < num5) + { + num2++; + if (num2 * num3 > minimumNr) + { + num3 = Mathf.CeilToInt((float)minimumNr / (float)num2); + } + } + else + { + num3++; + if (num2 * num3 > minimumNr) + { + num2 = Mathf.CeilToInt((float)minimumNr / (float)num3); + } + } + } + return new int[] + { + num2, + num3 + }; + } + private static float AbsRatioDiff(float x, float y) + { + return Mathf.Max(x / y, y / x); + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectReferenceKeyframe.cs b/UnityEditor/UnityEditor/ObjectReferenceKeyframe.cs new file mode 100644 index 00000000..8ff78378 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectReferenceKeyframe.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public struct ObjectReferenceKeyframe + { + public float time; + public UnityEngine.Object value; + } +} diff --git a/UnityEditor/UnityEditor/ObjectSelector.cs b/UnityEditor/UnityEditor/ObjectSelector.cs new file mode 100644 index 00000000..988817f6 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectSelector.cs @@ -0,0 +1,661 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + internal class ObjectSelector : EditorWindow + { + private class Styles + { + public GUIStyle smallStatus = "ObjectPickerSmallStatus"; + public GUIStyle largeStatus = "ObjectPickerLargeStatus"; + public GUIStyle toolbarBack = "ObjectPickerToolbar"; + public GUIStyle tab = "ObjectPickerTab"; + public GUIStyle bottomResize = "WindowBottomResize"; + public GUIStyle background = "ObjectPickerBackground"; + public GUIStyle previewBackground = "PopupCurveSwatchBackground"; + public GUIStyle previewTextureBackground = "ObjectPickerPreviewBackground"; + } + private const float kMinTopSize = 250f; + private const float kMinWidth = 200f; + private const float kPreviewMargin = 5f; + private const float kPreviewExpandedAreaHeight = 75f; + private ObjectSelector.Styles m_Styles; + private string m_RequiredType; + private string m_SearchFilter; + private bool m_FocusSearchFilter; + private bool m_AllowSceneObjects; + private bool m_IsShowingAssets; + private SavedInt m_StartGridSize = new SavedInt("ObjectSelector.GridSize", 64); + internal int objectSelectorID; + private int m_ModalUndoGroup = -1; + private UnityEngine.Object m_OriginalSelection; + private EditorCache m_EditorCache; + private GUIView m_DelegateView; + private PreviewResizer m_PreviewResizer = new PreviewResizer(); + private ObjectListAreaState m_ListAreaState; + private ObjectListArea m_ListArea; + private float m_ToolbarHeight = 44f; + private float m_PreviewSize; + private float m_TopSize; + private AnimBool m_ShowWidePreview = new AnimBool(); + private AnimBool m_ShowOverlapPreview = new AnimBool(); + private static ObjectSelector s_SharedObjectSelector; + private Rect listPosition + { + get + { + return new Rect(0f, this.m_ToolbarHeight, base.position.width, Mathf.Max(0f, this.m_TopSize - this.m_ToolbarHeight)); + } + } + public static ObjectSelector get + { + get + { + if (ObjectSelector.s_SharedObjectSelector == null) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(ObjectSelector)); + if (array != null && array.Length > 0) + { + ObjectSelector.s_SharedObjectSelector = (ObjectSelector)array[0]; + } + if (ObjectSelector.s_SharedObjectSelector == null) + { + ObjectSelector.s_SharedObjectSelector = ScriptableObject.CreateInstance(); + } + } + return ObjectSelector.s_SharedObjectSelector; + } + } + public static bool isVisible + { + get + { + return ObjectSelector.s_SharedObjectSelector != null; + } + } + internal string searchFilter + { + get + { + return this.m_SearchFilter; + } + set + { + this.m_SearchFilter = value; + this.FilterSettingsChanged(); + } + } + private ObjectSelector() + { + base.hideFlags = HideFlags.DontSave; + } + private int GetSelectedInstanceID() + { + int[] selection = this.m_ListArea.GetSelection(); + if (selection.Length >= 1) + { + return selection[0]; + } + return 0; + } + private void OnEnable() + { + this.m_ShowOverlapPreview.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowOverlapPreview.speed = 1.5f; + this.m_ShowWidePreview.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowWidePreview.speed = 1.5f; + this.m_PreviewResizer.Init("ObjectPickerPreview"); + this.m_PreviewSize = this.m_PreviewResizer.GetPreviewSize(); + AssetPreview.ClearTemporaryAssetPreviews(); + this.SetupPreview(); + } + private void OnDisable() + { + this.SendEvent("ObjectSelectorClosed", false); + if (this.m_ListArea != null) + { + this.m_StartGridSize.value = this.m_ListArea.gridSize; + } + Undo.CollapseUndoOperations(this.m_ModalUndoGroup); + if (ObjectSelector.s_SharedObjectSelector == this) + { + ObjectSelector.s_SharedObjectSelector = null; + } + if (this.m_EditorCache != null) + { + this.m_EditorCache.Dispose(); + } + AssetPreview.ClearTemporaryAssetPreviews(); + } + public void SetupPreview() + { + bool flag = this.PreviewIsOpen(); + bool flag2 = this.PreviewIsWide(); + BaseAnimValue arg_2F_0 = this.m_ShowOverlapPreview; + bool flag3 = flag && !flag2; + this.m_ShowOverlapPreview.value = flag3; + arg_2F_0.target = flag3; + BaseAnimValue arg_52_0 = this.m_ShowWidePreview; + flag3 = (flag && flag2); + this.m_ShowWidePreview.value = flag3; + arg_52_0.target = flag3; + } + private void ItemSelectedCallback(bool doubleClicked) + { + if (doubleClicked) + { + base.Close(); + GUIUtility.ExitGUI(); + } + else + { + this.m_FocusSearchFilter = false; + this.SendEvent("ObjectSelectorUpdated", true); + } + } + private static bool GuessIfUserIsLookingForAnAsset(string requiredClassName, bool checkGameObject) + { + string[] array = new string[] + { + "AnimationClip", + "AnimatorController", + "AnimatorOverrideController", + "AudioClip", + "Avatar", + "Flare", + "Font", + "Material", + "ProceduralMaterial", + "Mesh", + "PhysicMaterial", + "PhysicsMaterial2D", + "GUISkin", + "Shader", + "TerrainData", + "Texture", + "Cubemap", + "MovieTexture", + "RenderTexture", + "Texture2D", + "ProceduralTexture", + "Sprite" + }; + if (checkGameObject && requiredClassName == "GameObject") + { + return true; + } + for (int i = 0; i < array.Length; i++) + { + if (array[i] == requiredClassName) + { + return true; + } + } + return false; + } + private void FilterSettingsChanged() + { + SearchFilter searchFilter = new SearchFilter(); + searchFilter.SearchFieldStringToFilter(this.m_SearchFilter); + if (!string.IsNullOrEmpty(this.m_RequiredType)) + { + searchFilter.classNames = new string[] + { + this.m_RequiredType + }; + } + this.m_ListArea.Init(this.listPosition, (!this.m_IsShowingAssets) ? HierarchyType.GameObjects : HierarchyType.Assets, searchFilter, true); + } + public void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects) + { + this.m_AllowSceneObjects = allowSceneObjects; + this.m_IsShowingAssets = true; + string text = string.Empty; + if (property != null) + { + text = property.objectReferenceTypeString; + obj = property.objectReferenceValue; + UnityEngine.Object targetObject = property.serializedObject.targetObject; + if (targetObject != null && EditorUtility.IsPersistent(targetObject)) + { + this.m_AllowSceneObjects = false; + } + } + else + { + if (requiredType != null) + { + text = requiredType.Name; + } + } + if (this.m_AllowSceneObjects) + { + if (obj != null) + { + if (typeof(Component).IsAssignableFrom(obj.GetType())) + { + obj = ((Component)obj).gameObject; + } + this.m_IsShowingAssets = (EditorUtility.IsPersistent(obj) || ObjectSelector.GuessIfUserIsLookingForAnAsset(text, false)); + } + else + { + this.m_IsShowingAssets = ObjectSelector.GuessIfUserIsLookingForAnAsset(text, true); + } + } + else + { + this.m_IsShowingAssets = true; + } + this.m_DelegateView = GUIView.current; + this.m_RequiredType = text; + this.m_SearchFilter = string.Empty; + this.m_OriginalSelection = obj; + this.m_ModalUndoGroup = Undo.GetCurrentGroup(); + ContainerWindow.SetFreezeDisplay(true); + base.ShowWithMode(ShowMode.AuxWindow); + base.title = "Select " + text; + Rect position = this.m_Parent.window.position; + position.width = EditorPrefs.GetFloat("ObjectSelectorWidth", 200f); + position.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390f); + base.position = position; + base.minSize = new Vector2(200f, 335f); + base.maxSize = new Vector2(10000f, 10000f); + this.SetupPreview(); + base.Focus(); + ContainerWindow.SetFreezeDisplay(false); + this.m_FocusSearchFilter = true; + this.m_Parent.AddToAuxWindowList(); + this.InitIfNeeded(); + if (property != null && property.hasMultipleDifferentValues) + { + this.m_ListArea.InitSelection(new int[0]); + } + else + { + int num = (!(obj != null)) ? 0 : obj.GetInstanceID(); + this.m_ListArea.InitSelection(new int[] + { + num + }); + this.m_ListArea.Frame(num, true, false); + } + } + private void InitIfNeeded() + { + if (this.m_ListAreaState == null) + { + this.m_ListAreaState = new ObjectListAreaState(); + } + if (this.m_ListArea == null) + { + this.m_ListArea = new ObjectListArea(this.m_ListAreaState, this, true); + this.m_ListArea.allowDeselection = false; + this.m_ListArea.allowDragging = false; + this.m_ListArea.allowFocusRendering = false; + this.m_ListArea.allowMultiSelect = false; + this.m_ListArea.allowRenaming = false; + this.m_ListArea.allowBuiltinResources = true; + ObjectListArea expr_82 = this.m_ListArea; + expr_82.repaintCallback = (Action)Delegate.Combine(expr_82.repaintCallback, new Action(base.Repaint)); + ObjectListArea expr_A9 = this.m_ListArea; + expr_A9.itemSelectedCallback = (Action)Delegate.Combine(expr_A9.itemSelectedCallback, new Action(this.ItemSelectedCallback)); + this.m_ListArea.gridSize = this.m_StartGridSize.value; + SearchFilter searchFilter = new SearchFilter(); + searchFilter.nameFilter = this.m_SearchFilter; + if (!string.IsNullOrEmpty(this.m_RequiredType)) + { + searchFilter.classNames = new string[] + { + this.m_RequiredType + }; + } + this.m_ListArea.Init(this.listPosition, (!this.m_IsShowingAssets) ? HierarchyType.GameObjects : HierarchyType.Assets, searchFilter, true); + } + } + public static UnityEngine.Object GetCurrentObject() + { + return EditorUtility.InstanceIDToObject(ObjectSelector.get.GetSelectedInstanceID()); + } + public static UnityEngine.Object GetInitialObject() + { + return ObjectSelector.get.m_OriginalSelection; + } + private void SearchArea() + { + GUI.Label(new Rect(0f, 0f, base.position.width, this.m_ToolbarHeight), GUIContent.none, this.m_Styles.toolbarBack); + bool flag = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; + GUI.SetNextControlName("SearchFilter"); + string text = EditorGUI.SearchField(new Rect(5f, 5f, base.position.width - 10f, 15f), this.m_SearchFilter); + if (flag && Event.current.type == EventType.Used) + { + if (this.m_SearchFilter == string.Empty) + { + this.Cancel(); + } + this.m_FocusSearchFilter = true; + } + if (text != this.m_SearchFilter || this.m_FocusSearchFilter) + { + this.m_SearchFilter = text; + this.FilterSettingsChanged(); + base.Repaint(); + } + if (this.m_FocusSearchFilter) + { + EditorGUI.FocusTextInControl("SearchFilter"); + this.m_FocusSearchFilter = false; + } + GUI.changed = false; + GUILayout.BeginArea(new Rect(0f, 26f, base.position.width, this.m_ToolbarHeight - 26f)); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + bool flag2 = GUILayout.Toggle(this.m_IsShowingAssets, "Assets", this.m_Styles.tab, new GUILayoutOption[0]); + if (!this.m_IsShowingAssets && flag2) + { + this.m_IsShowingAssets = true; + } + if (!this.m_AllowSceneObjects) + { + GUI.enabled = false; + GUI.color = new Color(1f, 1f, 1f, 0f); + } + bool flag3 = !this.m_IsShowingAssets; + flag3 = GUILayout.Toggle(flag3, "Scene", this.m_Styles.tab, new GUILayoutOption[0]); + if (this.m_IsShowingAssets && flag3) + { + this.m_IsShowingAssets = false; + } + if (!this.m_AllowSceneObjects) + { + GUI.color = new Color(1f, 1f, 1f, 1f); + GUI.enabled = true; + } + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + if (GUI.changed) + { + this.FilterSettingsChanged(); + } + if (this.m_ListArea.CanShowThumbnails()) + { + this.m_ListArea.gridSize = (int)GUI.HorizontalSlider(new Rect(base.position.width - 60f, 26f, 55f, this.m_ToolbarHeight - 28f), (float)this.m_ListArea.gridSize, (float)this.m_ListArea.minGridSize, (float)this.m_ListArea.maxGridSize); + } + } + private void OnInspectorUpdate() + { + if (this.m_ListArea != null && AssetPreview.HasAnyNewPreviewTexturesAvailable(this.m_ListArea.GetAssetPreviewManagerID())) + { + base.Repaint(); + } + } + private void PreviewArea() + { + GUI.Box(new Rect(0f, this.m_TopSize, base.position.width, this.m_PreviewSize), string.Empty, this.m_Styles.previewBackground); + if (this.m_ListArea.GetSelection().Length == 0) + { + return; + } + EditorWrapper editorWrapper = null; + UnityEngine.Object currentObject = ObjectSelector.GetCurrentObject(); + if (this.m_PreviewSize < 75f) + { + string text; + if (currentObject != null) + { + editorWrapper = this.m_EditorCache[currentObject]; + string str = ObjectNames.NicifyVariableName(currentObject.GetType().Name); + if (editorWrapper != null) + { + text = editorWrapper.name + " (" + str + ")"; + } + else + { + text = currentObject.name + " (" + str + ")"; + } + text = text + " " + AssetDatabase.GetAssetPath(currentObject); + } + else + { + text = "None"; + } + this.LinePreview(text, currentObject, editorWrapper); + } + else + { + if (this.m_EditorCache == null) + { + this.m_EditorCache = new EditorCache(EditorFeatures.PreviewGUI); + } + string text3; + if (currentObject != null) + { + editorWrapper = this.m_EditorCache[currentObject]; + string text2 = ObjectNames.NicifyVariableName(currentObject.GetType().Name); + if (editorWrapper != null) + { + text3 = editorWrapper.GetInfoString(); + if (text3 != string.Empty) + { + text3 = string.Concat(new string[] + { + editorWrapper.name, + "\n", + text2, + "\n", + text3 + }); + } + else + { + text3 = editorWrapper.name + "\n" + text2; + } + } + else + { + text3 = currentObject.name + "\n" + text2; + } + text3 = text3 + "\n" + AssetDatabase.GetAssetPath(currentObject); + } + else + { + text3 = "None"; + } + if (this.m_ShowWidePreview.faded != 0f) + { + GUI.color = new Color(1f, 1f, 1f, this.m_ShowWidePreview.faded); + this.WidePreview(this.m_PreviewSize, text3, currentObject, editorWrapper); + } + if (this.m_ShowOverlapPreview.faded != 0f) + { + GUI.color = new Color(1f, 1f, 1f, this.m_ShowOverlapPreview.faded); + this.OverlapPreview(this.m_PreviewSize, text3, currentObject, editorWrapper); + } + GUI.color = Color.white; + this.m_EditorCache.CleanupUntouchedEditors(); + } + } + private void WidePreview(float actualSize, string s, UnityEngine.Object o, EditorWrapper p) + { + float num = 5f; + Rect position = new Rect(num, this.m_TopSize + num, actualSize - num * 2f, actualSize - num * 2f); + Rect position2 = new Rect(this.m_PreviewSize + 3f, this.m_TopSize + (this.m_PreviewSize - 75f) * 0.5f, this.m_Parent.window.position.width - this.m_PreviewSize - 3f - num, 75f); + if (p != null && p.HasPreviewGUI()) + { + p.OnPreviewGUI(position, this.m_Styles.previewTextureBackground); + } + else + { + if (o != null) + { + this.DrawObjectIcon(position, this.m_ListArea.m_SelectedObjectIcon); + } + } + if (EditorGUIUtility.isProSkin) + { + EditorGUI.DropShadowLabel(position2, s, this.m_Styles.smallStatus); + } + else + { + GUI.Label(position2, s, this.m_Styles.smallStatus); + } + } + private void OverlapPreview(float actualSize, string s, UnityEngine.Object o, EditorWrapper p) + { + float num = 5f; + Rect position = new Rect(num, this.m_TopSize + num, base.position.width - num * 2f, actualSize - num * 2f); + if (p != null && p.HasPreviewGUI()) + { + p.OnPreviewGUI(position, this.m_Styles.previewTextureBackground); + } + else + { + if (o != null) + { + this.DrawObjectIcon(position, this.m_ListArea.m_SelectedObjectIcon); + } + } + if (EditorGUIUtility.isProSkin) + { + EditorGUI.DropShadowLabel(position, s, this.m_Styles.largeStatus); + } + else + { + EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(s), this.m_Styles.largeStatus, 0.3f); + } + } + private void LinePreview(string s, UnityEngine.Object o, EditorWrapper p) + { + if (this.m_ListArea.m_SelectedObjectIcon != null) + { + GUI.DrawTexture(new Rect(2f, (float)((int)(this.m_TopSize + 2f)), 16f, 16f), this.m_ListArea.m_SelectedObjectIcon, ScaleMode.StretchToFill); + } + Rect position = new Rect(20f, this.m_TopSize + 1f, base.position.width - 22f, 18f); + if (EditorGUIUtility.isProSkin) + { + EditorGUI.DropShadowLabel(position, s, this.m_Styles.smallStatus); + } + else + { + GUI.Label(position, s, this.m_Styles.smallStatus); + } + } + private void DrawObjectIcon(Rect position, Texture icon) + { + if (icon == null) + { + return; + } + int num = Mathf.Min((int)position.width, (int)position.height); + if (num >= icon.width * 2) + { + num = icon.width * 2; + } + FilterMode filterMode = icon.filterMode; + icon.filterMode = FilterMode.Point; + GUI.DrawTexture(new Rect(position.x + (float)(((int)position.width - num) / 2), position.y + (float)(((int)position.height - num) / 2), (float)num, (float)num), icon, ScaleMode.ScaleToFit); + icon.filterMode = filterMode; + } + private void ResizeBottomPartOfWindow() + { + GUI.changed = false; + this.m_PreviewSize = this.m_PreviewResizer.ResizeHandle(base.position, 65f, 270f, 20f) + 20f; + this.m_TopSize = base.position.height - this.m_PreviewSize; + bool flag = this.PreviewIsOpen(); + bool flag2 = this.PreviewIsWide(); + this.m_ShowOverlapPreview.target = (flag && !flag2); + this.m_ShowWidePreview.target = (flag && flag2); + } + private bool PreviewIsOpen() + { + return this.m_PreviewSize >= 37f; + } + private bool PreviewIsWide() + { + return base.position.width - this.m_PreviewSize - 5f > Mathf.Min(this.m_PreviewSize * 2f - 20f, 256f); + } + private void SendEvent(string eventName, bool exitGUI) + { + if (this.m_DelegateView) + { + Event e = EditorGUIUtility.CommandEvent(eventName); + try + { + this.m_DelegateView.SendEvent(e); + } + finally + { + } + if (exitGUI) + { + GUIUtility.ExitGUI(); + } + } + } + private void HandleKeyboard() + { + if (Event.current.type != EventType.KeyDown) + { + return; + } + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.Return && keyCode != KeyCode.KeypadEnter) + { + return; + } + base.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + Event.current.Use(); + GUI.changed = true; + } + private void Cancel() + { + Undo.RevertAllDownToGroup(this.m_ModalUndoGroup); + base.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + } + private void OnDestroy() + { + if (this.m_ListArea != null) + { + this.m_ListArea.OnDestroy(); + } + } + private void OnGUI() + { + this.InitIfNeeded(); + if (this.m_Styles == null) + { + this.m_Styles = new ObjectSelector.Styles(); + } + if (this.m_EditorCache == null) + { + this.m_EditorCache = new EditorCache(EditorFeatures.PreviewGUI); + } + this.ResizeBottomPartOfWindow(); + Rect position = base.position; + EditorPrefs.SetFloat("ObjectSelectorWidth", position.width); + EditorPrefs.SetFloat("ObjectSelectorHeight", position.height); + GUI.BeginGroup(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none); + this.HandleKeyboard(); + this.m_ListArea.HandleKeyboard(false); + this.SearchArea(); + this.GridListArea(); + this.PreviewArea(); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.Cancel(); + } + GUI.EndGroup(); + GUI.Label(new Rect(base.position.width * 0.5f - 16f, base.position.height - this.m_PreviewSize + 2f, 32f, this.m_Styles.bottomResize.fixedHeight), GUIContent.none, this.m_Styles.bottomResize); + } + private void GridListArea() + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.m_ListArea.OnGUI(this.listPosition, controlID); + } + } +} diff --git a/UnityEditor/UnityEditor/OcclusionAreaEditor.cs b/UnityEditor/UnityEditor/OcclusionAreaEditor.cs new file mode 100644 index 00000000..946b296a --- /dev/null +++ b/UnityEditor/UnityEditor/OcclusionAreaEditor.cs @@ -0,0 +1,74 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(OcclusionArea))] + internal class OcclusionAreaEditor : Editor + { + private SerializedObject m_Object; + private SerializedProperty m_Size; + private SerializedProperty m_Center; + private void OnEnable() + { + this.m_Object = new SerializedObject(this.target); + this.m_Size = base.serializedObject.FindProperty("m_Size"); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + } + private void OnDisable() + { + this.m_Object.Dispose(); + this.m_Object = null; + } + private void OnSceneGUI() + { + this.m_Object.Update(); + OcclusionArea occlusionArea = (OcclusionArea)this.target; + Color color = Handles.color; + Handles.color = new Color(145f, 244f, 139f, 255f) / 255f; + Vector3 p = occlusionArea.transform.TransformPoint(this.m_Center.vector3Value); + Vector3 vector = this.m_Size.vector3Value * 0.5f; + Vector3 a = this.m_Size.vector3Value * 0.5f; + Vector3 lossyScale = occlusionArea.transform.lossyScale; + Vector3 b = new Vector3(1f / lossyScale.x, 1f / lossyScale.y, 1f / lossyScale.z); + vector = Vector3.Scale(vector, lossyScale); + a = Vector3.Scale(a, lossyScale); + bool changed = GUI.changed; + vector.x = this.SizeSlider(p, -Vector3.right, vector.x); + vector.y = this.SizeSlider(p, -Vector3.up, vector.y); + vector.z = this.SizeSlider(p, -Vector3.forward, vector.z); + a.x = this.SizeSlider(p, Vector3.right, a.x); + a.y = this.SizeSlider(p, Vector3.up, a.y); + a.z = this.SizeSlider(p, Vector3.forward, a.z); + if (GUI.changed) + { + this.m_Center.vector3Value = this.m_Center.vector3Value + Vector3.Scale(Quaternion.Inverse(occlusionArea.transform.rotation) * (a - vector) * 0.5f, b); + vector = Vector3.Scale(vector, b); + a = Vector3.Scale(a, b); + this.m_Size.vector3Value = a + vector; + base.serializedObject.ApplyModifiedProperties(); + } + GUI.changed |= changed; + Handles.color = color; + } + private float SizeSlider(Vector3 p, Vector3 d, float r) + { + Vector3 vector = p + d * r; + Color color = Handles.color; + if (Vector3.Dot(vector - Camera.current.transform.position, d) >= 0f) + { + Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier); + } + float handleSize = HandleUtility.GetHandleSize(vector); + bool changed = GUI.changed; + GUI.changed = false; + vector = Handles.Slider(vector, d, handleSize * 0.1f, new Handles.DrawCapFunction(Handles.CylinderCap), 0f); + if (GUI.changed) + { + r = Vector3.Dot(vector - p, d); + } + GUI.changed |= changed; + Handles.color = color; + return r; + } + } +} diff --git a/UnityEditor/UnityEditor/OcclusionCullingWindow.cs b/UnityEditor/UnityEditor/OcclusionCullingWindow.cs new file mode 100644 index 00000000..94246e7c --- /dev/null +++ b/UnityEditor/UnityEditor/OcclusionCullingWindow.cs @@ -0,0 +1,516 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class OcclusionCullingWindow : EditorWindow + { + private class Styles + { + public GUIContent[] ModeToggles = new GUIContent[] + { + new GUIContent("Object"), + new GUIContent("Bake"), + new GUIContent("Visualization") + }; + public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; + public GUIContent emptyAreaSelection = new GUIContent("Select a Mesh Renderer or an Occlusion Area from the scene."); + public GUIContent emptyCameraSelection = new GUIContent("Select a Camera from the scene."); + public GUIContent visualizationNote = new GUIContent("The visualization may not correspond to current bake settings and Occlusion Area placements if they have been changed since last bake."); + public GUIContent seeVisualizationInScene = new GUIContent("See the occlusion culling visualization in the Scene View based on the selected Camera."); + public GUIContent noOcclusionData = new GUIContent("No occlusion data has been baked."); + public GUIContent smallestHole = EditorGUIUtility.TextContent("OcclusionCullingWindow.SmallestHole"); + public GUIContent backfaceThreshold = EditorGUIUtility.TextContent("OcclusionCullingWindow.BackfaceThreshold"); + public GUIContent farClipPlane = EditorGUIUtility.TextContent("OcclusionCullingWindow.FarClipPlane"); + public GUIContent smallestOccluder = EditorGUIUtility.TextContent("OcclusionCullingWindow.SmallestOccluder"); + public GUIContent defaultParameterText = EditorGUIUtility.TextContent("OcclusionCullingWindow.DefaultParameters"); + } + private enum Mode + { + AreaSettings, + BakeSettings, + Visualization + } + private static bool s_IsVisible; + private bool m_PreVis; + private string m_Warning; + private static OcclusionCullingWindow ms_OcclusionCullingWindow; + private UnityEngine.Object[] m_Objects; + private Vector2 m_ScrollPosition = Vector2.zero; + private OcclusionCullingWindow.Mode m_Mode; + private static OcclusionCullingWindow.Styles s_Styles; + private void OnBecameVisible() + { + if (OcclusionCullingWindow.s_IsVisible) + { + return; + } + OcclusionCullingWindow.s_IsVisible = true; + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + StaticOcclusionCullingVisualization.showOcclusionCulling = true; + SceneView.RepaintAll(); + } + private void OnBecameInvisible() + { + OcclusionCullingWindow.s_IsVisible = false; + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + StaticOcclusionCullingVisualization.showOcclusionCulling = false; + SceneView.RepaintAll(); + } + private void OnSelectionChange() + { + if (this.m_Mode == OcclusionCullingWindow.Mode.AreaSettings || this.m_Mode == OcclusionCullingWindow.Mode.Visualization) + { + base.Repaint(); + } + } + private void Awake() + { + this.SetDefaultComputationParameters(); + } + private void OnEnable() + { + OcclusionCullingWindow.ms_OcclusionCullingWindow = this; + base.autoRepaintOnSceneChange = true; + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + base.Repaint(); + } + private void OnDisable() + { + OcclusionCullingWindow.ms_OcclusionCullingWindow = null; + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + } + private static void BackgroundTaskStatusChanged() + { + if (OcclusionCullingWindow.ms_OcclusionCullingWindow) + { + OcclusionCullingWindow.ms_OcclusionCullingWindow.Repaint(); + } + } + [MenuItem("Window/Occlusion Culling", false, 2099)] + private static void GenerateWindow() + { + if (Application.HasAdvancedLicense()) + { + OcclusionCullingWindow window = EditorWindow.GetWindow(new Type[] + { + typeof(InspectorWindow) + }); + window.title = "Occlusion"; + window.minSize = new Vector2(300f, 250f); + } + else + { + Debug.LogError("Occlusion Culling is only supported in Unity Pro."); + } + } + [MenuItem("Window/Occlusion Culling", true, 2099)] + public static bool SetupWindowValidate() + { + return InternalEditorUtility.HasPro(); + } + private void SummaryGUI() + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + if (StaticOcclusionCulling.umbraDataSize == 0) + { + GUILayout.Label(OcclusionCullingWindow.s_Styles.noOcclusionData, OcclusionCullingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + } + else + { + GUILayout.Label("Last bake:", OcclusionCullingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Occlusion data size ", OcclusionCullingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(EditorUtility.FormatBytes(StaticOcclusionCulling.umbraDataSize), OcclusionCullingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + GUILayout.EndVertical(); + } + private OcclusionArea CreateNewArea() + { + GameObject gameObject = new GameObject("Occlusion Area"); + OcclusionArea result = gameObject.AddComponent(); + Selection.activeGameObject = gameObject; + return result; + } + private void AreaSelectionGUI() + { + bool flag = true; + Type type = SceneModeUtility.SearchBar(new Type[] + { + typeof(Renderer), + typeof(OcclusionArea) + }); + EditorGUILayout.Space(); + GameObject[] array; + OcclusionArea[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length > 0) + { + flag = false; + EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType); + SerializedObject serializedObject = new SerializedObject(selectedObjectsOfType); + EditorGUILayout.PropertyField(serializedObject.FindProperty("m_IsViewVolume"), new GUILayoutOption[0]); + serializedObject.ApplyModifiedProperties(); + } + Renderer[] selectedObjectsOfType2 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[] + { + typeof(MeshRenderer), + typeof(SkinnedMeshRenderer) + }); + if (array.Length > 0) + { + flag = false; + EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType2); + SerializedObject serializedObject2 = new SerializedObject(array); + SceneModeUtility.StaticFlagField("Occluder Static", serializedObject2.FindProperty("m_StaticEditorFlags"), 2); + SceneModeUtility.StaticFlagField("Occludee Static", serializedObject2.FindProperty("m_StaticEditorFlags"), 16); + serializedObject2.ApplyModifiedProperties(); + } + if (flag) + { + GUILayout.Label(OcclusionCullingWindow.s_Styles.emptyAreaSelection, EditorStyles.helpBox, new GUILayoutOption[0]); + if (type == typeof(OcclusionArea)) + { + EditorGUIUtility.labelWidth = 80f; + EditorGUILayout.Space(); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Create New"); + if (GUILayout.Button("Occlusion Area", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + this.CreateNewArea(); + } + EditorGUILayout.EndHorizontal(); + } + } + } + private void CameraSelectionGUI() + { + SceneModeUtility.SearchBar(new Type[] + { + typeof(Camera) + }); + EditorGUILayout.Space(); + Camera camera = null; + if (Selection.activeGameObject) + { + camera = Selection.activeGameObject.GetComponent(); + } + if (camera) + { + Camera[] objects = new Camera[] + { + camera + }; + EditorGUILayout.MultiSelectionObjectTitleBar(objects); + EditorGUILayout.HelpBox(OcclusionCullingWindow.s_Styles.seeVisualizationInScene.text, MessageType.Info); + } + else + { + GUILayout.Label(OcclusionCullingWindow.s_Styles.emptyCameraSelection, EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private void SetDefaultComputationParameters() + { + GUIUtility.keyboardControl = 0; + StaticOcclusionCulling.SetDefaultOcclusionBakeSettings(); + } + private void BakeSettings() + { + float width = 150f; + if (GUILayout.Button("Set default parameters", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + this.SetDefaultComputationParameters(); + } + GUILayout.Label(OcclusionCullingWindow.s_Styles.defaultParameterText.tooltip, EditorStyles.helpBox, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + float smallestOccluder = EditorGUILayout.FloatField(OcclusionCullingWindow.s_Styles.smallestOccluder, StaticOcclusionCulling.smallestOccluder, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + StaticOcclusionCulling.smallestOccluder = smallestOccluder; + } + EditorGUI.BeginChangeCheck(); + float smallestHole = EditorGUILayout.FloatField(OcclusionCullingWindow.s_Styles.smallestHole, StaticOcclusionCulling.smallestHole, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + StaticOcclusionCulling.smallestHole = smallestHole; + } + EditorGUI.BeginChangeCheck(); + float backfaceThreshold = EditorGUILayout.Slider(OcclusionCullingWindow.s_Styles.backfaceThreshold, StaticOcclusionCulling.backfaceThreshold, 5f, 100f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + StaticOcclusionCulling.backfaceThreshold = backfaceThreshold; + } + } + private void BakeButtons() + { + float width = 95f; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + bool flag = !EditorApplication.isPlayingOrWillChangePlaymode; + GUI.enabled = (StaticOcclusionCulling.umbraDataSize != 0 && flag); + if (GUILayout.Button("Clear", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + StaticOcclusionCulling.Clear(); + } + GUI.enabled = flag; + if (StaticOcclusionCulling.isRunning) + { + if (GUILayout.Button("Cancel", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + StaticOcclusionCulling.Cancel(); + } + } + else + { + if (GUILayout.Button("Bake", new GUILayoutOption[] + { + GUILayout.Width(width) + })) + { + StaticOcclusionCulling.GenerateInBackground(); + } + } + GUILayout.EndHorizontal(); + GUI.enabled = true; + } + private void ModeToggle() + { + this.m_Mode = (OcclusionCullingWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, OcclusionCullingWindow.s_Styles.ModeToggles, "LargeButton", new GUILayoutOption[0]); + if (GUI.changed) + { + if (this.m_Mode == OcclusionCullingWindow.Mode.Visualization && StaticOcclusionCulling.umbraDataSize > 0) + { + StaticOcclusionCullingVisualization.showPreVisualization = false; + } + else + { + StaticOcclusionCullingVisualization.showPreVisualization = true; + } + SceneView.RepaintAll(); + } + } + private void OnGUI() + { + if (!Application.HasAdvancedLicense()) + { + EditorGUILayout.HelpBox(BuildPipeline.GetBuildTargetAdvancedLicenseName(EditorUserBuildSettings.activeBuildTarget) + " is required for Occlusion Culling on " + BuildPipeline.GetBuildTargetGroupName(EditorUserBuildSettings.activeBuildTarget), MessageType.Warning); + return; + } + if (OcclusionCullingWindow.s_Styles == null) + { + OcclusionCullingWindow.s_Styles = new OcclusionCullingWindow.Styles(); + } + if (this.m_Mode != OcclusionCullingWindow.Mode.Visualization && !StaticOcclusionCullingVisualization.showPreVisualization) + { + this.m_Mode = OcclusionCullingWindow.Mode.Visualization; + } + EditorGUILayout.Space(); + this.ModeToggle(); + EditorGUILayout.Space(); + this.m_ScrollPosition = EditorGUILayout.BeginScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); + switch (this.m_Mode) + { + case OcclusionCullingWindow.Mode.AreaSettings: + this.AreaSelectionGUI(); + break; + case OcclusionCullingWindow.Mode.BakeSettings: + this.BakeSettings(); + break; + case OcclusionCullingWindow.Mode.Visualization: + if (StaticOcclusionCulling.umbraDataSize > 0) + { + this.CameraSelectionGUI(); + GUILayout.FlexibleSpace(); + GUILayout.Label(OcclusionCullingWindow.s_Styles.visualizationNote, EditorStyles.helpBox, new GUILayoutOption[0]); + } + else + { + GUILayout.Label(OcclusionCullingWindow.s_Styles.noOcclusionData, EditorStyles.helpBox, new GUILayoutOption[0]); + } + break; + } + EditorGUILayout.EndScrollView(); + EditorGUILayout.Space(); + this.BakeButtons(); + EditorGUILayout.Space(); + this.SummaryGUI(); + } + public void OnSceneViewGUI(SceneView sceneView) + { + if (!OcclusionCullingWindow.s_IsVisible) + { + return; + } + SceneViewOverlay.Window(new GUIContent("Occlusion Culling"), new SceneViewOverlay.WindowFunction(this.DisplayControls), 100, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + } + private void OnDidOpenScene() + { + base.Repaint(); + } + private void SetShowVolumePreVis() + { + StaticOcclusionCullingVisualization.showPreVisualization = true; + if (this.m_Mode == OcclusionCullingWindow.Mode.Visualization) + { + this.m_Mode = OcclusionCullingWindow.Mode.AreaSettings; + } + if (OcclusionCullingWindow.ms_OcclusionCullingWindow) + { + OcclusionCullingWindow.ms_OcclusionCullingWindow.Repaint(); + } + SceneView.RepaintAll(); + } + private void SetShowVolumeCulling() + { + StaticOcclusionCullingVisualization.showPreVisualization = false; + this.m_Mode = OcclusionCullingWindow.Mode.Visualization; + if (OcclusionCullingWindow.ms_OcclusionCullingWindow) + { + OcclusionCullingWindow.ms_OcclusionCullingWindow.Repaint(); + } + SceneView.RepaintAll(); + } + private bool ShowModePopup(Rect popupRect) + { + int umbraDataSize = StaticOcclusionCulling.umbraDataSize; + if (this.m_PreVis != StaticOcclusionCullingVisualization.showPreVisualization) + { + SceneView.RepaintAll(); + } + if (Event.current.type == EventType.Layout) + { + this.m_PreVis = StaticOcclusionCullingVisualization.showPreVisualization; + } + string[] array = new string[] + { + "Edit", + "Visualize" + }; + int num = (!this.m_PreVis) ? 1 : 0; + if (EditorGUI.ButtonMouseDown(popupRect, new GUIContent(array[num]), FocusType.Passive, EditorStyles.popup)) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent(array[0]), num == 0, new GenericMenu.MenuFunction(this.SetShowVolumePreVis)); + if (umbraDataSize > 0) + { + genericMenu.AddItem(new GUIContent(array[1]), num == 1, new GenericMenu.MenuFunction(this.SetShowVolumeCulling)); + } + else + { + genericMenu.AddDisabledItem(new GUIContent(array[1])); + } + genericMenu.Popup(popupRect, num); + } + return this.m_PreVis; + } + private void DisplayControls(UnityEngine.Object target, SceneView sceneView) + { + if (!sceneView) + { + return; + } + if (!OcclusionCullingWindow.s_IsVisible) + { + return; + } + bool flag = this.ShowModePopup(GUILayoutUtility.GetRect(170f, EditorGUIUtility.singleLineHeight)); + if (Event.current.type == EventType.Layout) + { + this.m_Warning = string.Empty; + if (!flag) + { + if (StaticOcclusionCullingVisualization.previewOcclucionCamera == null) + { + this.m_Warning = "No camera selected for occlusion preview."; + } + else + { + if (!StaticOcclusionCullingVisualization.isPreviewOcclusionCullingCameraInPVS) + { + this.m_Warning = "Camera is not inside an Occlusion View Area."; + } + } + } + } + int num = 12; + if (!string.IsNullOrEmpty(this.m_Warning)) + { + Rect rect = GUILayoutUtility.GetRect(100f, (float)(num + 19)); + rect.x += EditorGUI.indent; + rect.width -= EditorGUI.indent; + GUI.Label(rect, this.m_Warning, EditorStyles.helpBox); + } + else + { + Rect rect2 = GUILayoutUtility.GetRect(200f, (float)num); + rect2.x += EditorGUI.indent; + rect2.width -= EditorGUI.indent; + Rect position = new Rect(rect2.x, rect2.y, rect2.width, rect2.height); + if (flag) + { + EditorGUI.DrawLegend(position, Color.white, "View Volumes", StaticOcclusionCullingVisualization.showViewVolumes); + } + else + { + EditorGUI.DrawLegend(position, Color.white, "Camera Volumes", StaticOcclusionCullingVisualization.showViewVolumes); + } + bool flag2 = GUI.Toggle(position, StaticOcclusionCullingVisualization.showViewVolumes, string.Empty, GUIStyle.none); + if (flag2 != StaticOcclusionCullingVisualization.showViewVolumes) + { + StaticOcclusionCullingVisualization.showViewVolumes = flag2; + SceneView.RepaintAll(); + } + if (!flag) + { + rect2 = GUILayoutUtility.GetRect(100f, (float)num); + rect2.x += EditorGUI.indent; + rect2.width -= EditorGUI.indent; + position = new Rect(rect2.x, rect2.y, rect2.width, rect2.height); + EditorGUI.DrawLegend(position, Color.green, "Visibility Lines", StaticOcclusionCullingVisualization.showVisibilityLines); + flag2 = GUI.Toggle(position, StaticOcclusionCullingVisualization.showVisibilityLines, string.Empty, GUIStyle.none); + if (flag2 != StaticOcclusionCullingVisualization.showVisibilityLines) + { + StaticOcclusionCullingVisualization.showVisibilityLines = flag2; + SceneView.RepaintAll(); + } + rect2 = GUILayoutUtility.GetRect(100f, (float)num); + rect2.x += EditorGUI.indent; + rect2.width -= EditorGUI.indent; + position = new Rect(rect2.x, rect2.y, rect2.width, rect2.height); + EditorGUI.DrawLegend(position, Color.grey, "Portals", StaticOcclusionCullingVisualization.showPortals); + flag2 = GUI.Toggle(position, StaticOcclusionCullingVisualization.showPortals, string.Empty, GUIStyle.none); + if (flag2 != StaticOcclusionCullingVisualization.showPortals) + { + StaticOcclusionCullingVisualization.showPortals = flag2; + SceneView.RepaintAll(); + } + } + if (!flag) + { + flag2 = GUILayout.Toggle(StaticOcclusionCullingVisualization.showGeometryCulling, "Occlusion culling", new GUILayoutOption[0]); + if (flag2 != StaticOcclusionCullingVisualization.showGeometryCulling) + { + StaticOcclusionCullingVisualization.showGeometryCulling = flag2; + SceneView.RepaintAll(); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/OcclusionPortalInspector.cs b/UnityEditor/UnityEditor/OcclusionPortalInspector.cs new file mode 100644 index 00000000..7624e8f0 --- /dev/null +++ b/UnityEditor/UnityEditor/OcclusionPortalInspector.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(OcclusionPortal))] + internal class OcclusionPortalInspector : Editor + { + private static readonly int s_BoxHash = "BoxColliderEditor".GetHashCode(); + private readonly BoxEditor m_BoxEditor = new BoxEditor(true, OcclusionPortalInspector.s_BoxHash); + private SerializedProperty m_Center; + private SerializedProperty m_Size; + private SerializedObject m_Object; + public void OnEnable() + { + this.m_Object = new SerializedObject(base.targets); + this.m_Center = this.m_Object.FindProperty("m_Center"); + this.m_Size = this.m_Object.FindProperty("m_Size"); + this.m_BoxEditor.OnEnable(); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + } + private void OnSceneGUI() + { + OcclusionPortal occlusionPortal = this.target as OcclusionPortal; + Vector3 vector3Value = this.m_Center.vector3Value; + Vector3 vector3Value2 = this.m_Size.vector3Value; + Color s_ColliderHandleColor = Handles.s_ColliderHandleColor; + if (this.m_BoxEditor.OnSceneGUI(occlusionPortal.transform, s_ColliderHandleColor, ref vector3Value, ref vector3Value2)) + { + this.m_Center.vector3Value = vector3Value; + this.m_Size.vector3Value = vector3Value2; + this.m_Object.ApplyModifiedProperties(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/OffMeshLinkInspector.cs b/UnityEditor/UnityEditor/OffMeshLinkInspector.cs new file mode 100644 index 00000000..73724f3d --- /dev/null +++ b/UnityEditor/UnityEditor/OffMeshLinkInspector.cs @@ -0,0 +1,66 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(OffMeshLink))] + internal class OffMeshLinkInspector : Editor + { + private SerializedProperty m_NavMeshLayer; + private SerializedProperty m_Start; + private SerializedProperty m_End; + private SerializedProperty m_CostOverride; + private SerializedProperty m_BiDirectional; + private SerializedProperty m_Activated; + private SerializedProperty m_AutoUpdatePositions; + private void OnEnable() + { + this.m_NavMeshLayer = base.serializedObject.FindProperty("m_NavMeshLayer"); + this.m_Start = base.serializedObject.FindProperty("m_Start"); + this.m_End = base.serializedObject.FindProperty("m_End"); + this.m_CostOverride = base.serializedObject.FindProperty("m_CostOverride"); + this.m_BiDirectional = base.serializedObject.FindProperty("m_BiDirectional"); + this.m_Activated = base.serializedObject.FindProperty("m_Activated"); + this.m_AutoUpdatePositions = base.serializedObject.FindProperty("m_AutoUpdatePositions"); + } + public override void OnInspectorGUI() + { + if (!Application.HasProLicense()) + { + EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); + GUI.enabled = false; + } + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Start, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_End, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CostOverride, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BiDirectional, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Activated, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AutoUpdatePositions, new GUILayoutOption[0]); + this.SelectNavMeshLayer(); + base.serializedObject.ApplyModifiedProperties(); + } + private void SelectNavMeshLayer() + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_NavMeshLayer.hasMultipleDifferentValues; + string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); + int intValue = this.m_NavMeshLayer.intValue; + int selectedIndex = -1; + for (int i = 0; i < navMeshLayerNames.Length; i++) + { + if (GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]) == intValue) + { + selectedIndex = i; + break; + } + } + int num = EditorGUILayout.Popup("Navigation Layer", selectedIndex, navMeshLayerNames, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[num]); + this.m_NavMeshLayer.intValue = navMeshLayerFromName; + } + } + } +} diff --git a/UnityEditor/UnityEditor/OptimizedGUIBlock.cs b/UnityEditor/UnityEditor/OptimizedGUIBlock.cs new file mode 100644 index 00000000..ebd6020a --- /dev/null +++ b/UnityEditor/UnityEditor/OptimizedGUIBlock.cs @@ -0,0 +1,127 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class OptimizedGUIBlock + { + [NonSerialized] + private IntPtr m_Ptr; + private bool m_Valid; + private bool m_Recording; + private bool m_WatchForUsed; + private int m_KeyboardControl; + private int m_LastSearchIndex; + private int m_ActiveDragControl; + private Color m_GUIColor; + private Rect m_Rect; + public OptimizedGUIBlock() + { + this.Init(); + } + ~OptimizedGUIBlock() + { + if (this.m_Ptr != IntPtr.Zero) + { + Debug.Log("Failed cleaning up Optimized GUI Block"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + public bool Begin(bool hasChanged, Rect position) + { + if (hasChanged) + { + this.m_Valid = false; + } + if (Event.current.type == EventType.Repaint) + { + if (GUIUtility.keyboardControl != this.m_KeyboardControl) + { + this.m_Valid = false; + this.m_KeyboardControl = GUIUtility.keyboardControl; + } + if (DragAndDrop.activeControlID != this.m_ActiveDragControl) + { + this.m_Valid = false; + this.m_ActiveDragControl = DragAndDrop.activeControlID; + } + if (GUI.color != this.m_GUIColor) + { + this.m_Valid = false; + this.m_GUIColor = GUI.color; + } + position = GUIClip.Unclip(position); + if (this.m_Valid && position != this.m_Rect) + { + this.m_Rect = position; + this.m_Valid = false; + } + if (EditorGUI.isCollectingTooltips) + { + return true; + } + if (this.m_Valid) + { + return false; + } + this.m_Recording = true; + this.BeginRecording(); + return true; + } + else + { + if (Event.current.type == EventType.Used) + { + return false; + } + if (Event.current.type != EventType.Used) + { + this.m_WatchForUsed = true; + } + return true; + } + } + public void End() + { + bool recording = this.m_Recording; + if (this.m_Recording) + { + this.EndRecording(); + this.m_Recording = false; + this.m_Valid = true; + this.m_LastSearchIndex = EditorGUIUtility.GetSearchIndexOfControlIDList(); + } + if (Event.current == null) + { + Debug.LogError("Event.current is null"); + } + if (Event.current.type == EventType.Repaint && !EditorGUI.isCollectingTooltips) + { + this.Execute(); + if (!recording) + { + EditorGUIUtility.SetSearchIndexOfControlIDList(this.m_LastSearchIndex); + } + } + if (this.m_WatchForUsed && Event.current.type == EventType.Used) + { + this.m_Valid = false; + } + this.m_WatchForUsed = false; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void BeginRecording(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void EndRecording(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Execute(); + } +} diff --git a/UnityEditor/UnityEditor/OverwriteHandling.cs b/UnityEditor/UnityEditor/OverwriteHandling.cs new file mode 100644 index 00000000..ec5327b0 --- /dev/null +++ b/UnityEditor/UnityEditor/OverwriteHandling.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal enum OverwriteHandling + { + Prompt, + Overwrite, + Version, + Cancel + } +} diff --git a/UnityEditor/UnityEditor/PListConfig.cs b/UnityEditor/UnityEditor/PListConfig.cs new file mode 100644 index 00000000..893c2c2e --- /dev/null +++ b/UnityEditor/UnityEditor/PListConfig.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using System.Text.RegularExpressions; +namespace UnityEditor +{ + internal class PListConfig + { + private string fileName; + private string xml; + public string this[string paramName] + { + get + { + Match match = PListConfig.GetRegex(paramName).Match(this.xml); + return (!match.Success) ? string.Empty : match.Groups["Value"].Value; + } + set + { + Match match = PListConfig.GetRegex(paramName).Match(this.xml); + if (match.Success) + { + this.xml = PListConfig.GetRegex(paramName).Replace(this.xml, "${Part1}" + value + ""); + } + else + { + this.WriteNewValue(paramName, value); + } + } + } + public PListConfig(string fileName) + { + if (File.Exists(fileName)) + { + StreamReader streamReader = new StreamReader(fileName); + this.xml = streamReader.ReadToEnd(); + streamReader.Close(); + } + else + { + this.Clear(); + } + this.fileName = fileName; + } + private static Regex GetRegex(string paramName) + { + return new Regex("(?" + paramName + "\\s*)(?.*)"); + } + public void Save() + { + StreamWriter streamWriter = new StreamWriter(this.fileName); + streamWriter.Write(this.xml); + streamWriter.Close(); + } + private void WriteNewValue(string key, string val) + { + Regex regex = new Regex(""); + this.xml = regex.Replace(this.xml, string.Concat(new string[] + { + "\t", + key, + "\n\t", + val, + "\n" + })); + } + public void Clear() + { + this.xml = "\n\n\n\n\n\n"; + } + } +} diff --git a/UnityEditor/UnityEditor/PSP2BuildSubtarget.cs b/UnityEditor/UnityEditor/PSP2BuildSubtarget.cs new file mode 100644 index 00000000..4599ea95 --- /dev/null +++ b/UnityEditor/UnityEditor/PSP2BuildSubtarget.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum PSP2BuildSubtarget + { + PCHosted, + Package + } +} diff --git a/UnityEditor/UnityEditor/PackageExport.cs b/UnityEditor/UnityEditor/PackageExport.cs new file mode 100644 index 00000000..a2f9b70c --- /dev/null +++ b/UnityEditor/UnityEditor/PackageExport.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PackageExport : EditorWindow + { + internal class Constants + { + public GUIStyle ConsoleEntryBackEven = "CN EntryBackEven"; + public GUIStyle ConsoleEntryBackOdd = "CN EntryBackOdd"; + public GUIStyle title = "OL Title"; + public Color lineColor; + public Constants() + { + this.lineColor = ((!EditorGUIUtility.isProSkin) ? new Color(0.4f, 0.4f, 0.4f) : new Color(0.1f, 0.1f, 0.1f)); + } + } + [SerializeField] + private AssetsItem[] m_assets; + [SerializeField] + private bool m_bIncludeDependencies = true; + [SerializeField] + private int m_LeastIndent = 999999; + [SerializeField] + private ListViewState m_ListView; + private static PackageExport.Constants ms_Constants; + public PackageExport() + { + this.m_ListView = new ListViewState(0, 18); + base.position = new Rect(100f, 100f, 400f, 300f); + base.minSize = new Vector2(400f, 200f); + } + public void OnGUI() + { + if (PackageExport.ms_Constants == null) + { + PackageExport.ms_Constants = new PackageExport.Constants(); + } + if (this.m_assets == null) + { + return; + } + if (this.m_LeastIndent == 999999) + { + int num = this.m_LeastIndent; + for (int i = 0; i < this.m_assets.Length; i++) + { + int num2 = PackageExport.CountOccurencesOfChar(this.m_assets[i].pathName, '/'); + if (num > num2) + { + num = num2; + } + } + this.m_LeastIndent = num - 1; + } + if (this.m_assets != null) + { + this.SetupListView(); + bool flag = Event.current.type == EventType.Repaint; + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Items to Export", PackageExport.ms_Constants.title, new GUILayoutOption[0]); + GUILayout.Space(1f); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + foreach (ListViewElement listViewElement in ListViewGUI.ListView(this.m_ListView, GUIStyle.none, new GUILayoutOption[0])) + { + AssetsItem assetsItem = this.m_assets[listViewElement.row]; + Rect position = listViewElement.position; + position = new Rect(position.x + 1f, position.y, position.width - 2f, position.height); + int num3 = PackageExport.CountOccurencesOfChar(assetsItem.pathName, '/') - this.m_LeastIndent; + if (flag && this.m_ListView.row == listViewElement.row) + { + PackageExport.ms_Constants.ConsoleEntryBackEven.Draw(position, false, false, true, false); + } + float y = listViewElement.position.y; + position.x += 3f; + int enabled = assetsItem.enabled; + assetsItem.enabled = ((!GUI.Toggle(new Rect(position.x, position.y, 16f, 16f), assetsItem.enabled != 0, string.Empty)) ? 0 : 1); + if (enabled != assetsItem.enabled) + { + this.m_ListView.row = listViewElement.row; + GUIUtility.keyboardControl = this.m_ListView.ID; + this.CheckChildren(assetsItem); + } + if (flag) + { + Rect position2 = new Rect(position.x + (float)(15 * num3), y + 1f, 16f, 16f); + Texture cachedIcon = AssetDatabase.GetCachedIcon(assetsItem.pathName); + if (cachedIcon != null) + { + GUI.DrawTexture(position2, cachedIcon); + } + } + position = new Rect(position.x + 20f + (float)(15 * num3), listViewElement.position.y, position.width - (float)(20 + 15 * num3), position.height); + GUI.Label(position, assetsItem.pathName); + } + this.FrameLastGUIRect(); + GUILayout.EndVertical(); + if (this.m_ListView.row != -1 && GUIUtility.keyboardControl == this.m_ListView.ID && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Space) + { + this.m_assets[this.m_ListView.row].enabled = ((this.m_assets[this.m_ListView.row].enabled != 0) ? 0 : 1); + this.CheckChildren(this.m_assets[this.m_ListView.row]); + Event.current.Use(); + } + EditorGUIUtility.SetIconSize(Vector2.zero); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + if (GUILayout.Button(EditorGUIUtility.TextContent("All"), new GUILayoutOption[] + { + GUILayout.Width(50f) + })) + { + for (int j = 0; j < this.m_assets.Length; j++) + { + this.m_assets[j].enabled = 1; + } + } + if (GUILayout.Button(EditorGUIUtility.TextContent("None"), new GUILayoutOption[] + { + GUILayout.Width(50f) + })) + { + for (int k = 0; k < this.m_assets.Length; k++) + { + this.m_assets[k].enabled = 0; + } + } + GUILayout.Space(10f); + bool flag2 = GUILayout.Toggle(this.m_bIncludeDependencies, "Include dependencies", new GUILayoutOption[0]); + if (flag2 != this.m_bIncludeDependencies) + { + this.m_bIncludeDependencies = flag2; + this.BuildAssetList(); + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button(EditorGUIUtility.TextContent("Export..."), new GUILayoutOption[0])) + { + this.Export(); + GUIUtility.ExitGUI(); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + } + } + private void BuildAssetList() + { + this.m_assets = PackageExport.GetAssetItemsForExport(Selection.assetGUIDsDeepSelection, this.m_bIncludeDependencies).ToArray(); + } + private void SetupListView() + { + if (this.m_assets != null) + { + this.m_ListView.totalRows = this.m_assets.Length; + } + } + private void Export() + { + string text = EditorUtility.SaveFilePanel("Export package ...", string.Empty, string.Empty, "unitypackage"); + if (text != string.Empty) + { + List list = new List(); + AssetsItem[] assets = this.m_assets; + for (int i = 0; i < assets.Length; i++) + { + AssetsItem assetsItem = assets[i]; + if (assetsItem.enabled != 0) + { + list.Add(assetsItem.guid); + } + } + AssetServer.ExportPackage(list.ToArray(), text); + base.Close(); + GUIUtility.ExitGUI(); + } + } + private static void ShowExportPackage() + { + PackageExport window = EditorWindow.GetWindow(true, "Exporting package"); + window.BuildAssetList(); + window.Repaint(); + } + private void CheckChildren(AssetsItem parentAI) + { + AssetsItem[] assets = this.m_assets; + for (int i = 0; i < assets.Length; i++) + { + AssetsItem assetsItem = assets[i]; + if (assetsItem.parentGuid == parentAI.guid) + { + assetsItem.enabled = parentAI.enabled; + this.CheckChildren(assetsItem); + } + } + } + private void FrameLastGUIRect() + { + Rect lastRect = GUILayoutUtility.GetLastRect(); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + GL.Color(PackageExport.ms_Constants.lineColor); + GL.Vertex3(lastRect.xMax + 1f, lastRect.y, 0f); + GL.Vertex3(lastRect.xMax + 1f, lastRect.yMax, 0f); + GL.Vertex3(lastRect.xMax + 1f, lastRect.yMax, 0f); + GL.Vertex3(lastRect.x + 1f, lastRect.yMax, 0f); + GL.Vertex3(lastRect.x + 1f, lastRect.yMax, 0f); + GL.Vertex3(lastRect.x + 1f, lastRect.y, 0f); + GL.End(); + } + private static int CountOccurencesOfChar(string instance, char c) + { + int num = 0; + for (int i = 0; i < instance.Length; i++) + { + char c2 = instance[i]; + if (c == c2) + { + num++; + } + } + return num; + } + internal static IEnumerable GetAssetItemsForExport(ICollection guids, bool includeDependencies) + { + if (guids.Count == 0) + { + string[] collection = new string[0]; + guids = new HashSet(AssetServer.CollectAllChildren(AssetServer.GetRootGUID(), collection)); + } + AssetsItem[] array = AssetServer.BuildExportPackageAssetListAssetsItems(guids.ToArray(), includeDependencies); + if (includeDependencies) + { + if (array.Any((AssetsItem asset) => InternalEditorUtility.IsScriptOrAssembly(asset.pathName))) + { + array = AssetServer.BuildExportPackageAssetListAssetsItems(guids.Union(InternalEditorUtility.GetAllScriptGUIDs()).ToArray(), includeDependencies); + } + } + return array; + } + } +} diff --git a/UnityEditor/UnityEditor/PackageImport.cs b/UnityEditor/UnityEditor/PackageImport.cs new file mode 100644 index 00000000..8c445552 --- /dev/null +++ b/UnityEditor/UnityEditor/PackageImport.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + internal class PackageImport : EditorWindow, ISerializationCallbackReceiver + { + internal class Constants + { + public GUIStyle ConsoleEntryBackEven = "CN EntryBackEven"; + public GUIStyle ConsoleEntryBackOdd = "CN EntryBackOdd"; + public GUIStyle title = new GUIStyle(EditorStyles.largeLabel); + public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; + public GUIStyle topBarBg = new GUIStyle("ProjectBrowserHeaderBgTop"); + public GUIStyle textureIconDropShadow = "ProjectBrowserTextureIconDropShadow"; + public Color lineColor; + public Constants() + { + this.lineColor = ((!EditorGUIUtility.isProSkin) ? new Color(0.4f, 0.4f, 0.4f) : new Color(0.1f, 0.1f, 0.1f)); + this.topBarBg.fixedHeight = 0f; + RectOffset arg_D7_0 = this.topBarBg.border; + int num = 2; + this.topBarBg.border.bottom = num; + arg_D7_0.top = num; + this.title.fontStyle = FontStyle.Bold; + this.title.alignment = TextAnchor.MiddleLeft; + } + } + [SerializeField] + private AssetsItem[] m_Assets; + [SerializeField] + private List m_EnabledFolders; + [SerializeField] + private string m_PackageName; + [SerializeField] + private string m_PackageIconPath; + [SerializeField] + private TreeViewState m_TreeViewState; + [NonSerialized] + private PackageImportTreeView m_Tree; + private static Texture2D s_PackageIcon; + private static Texture2D s_Preview; + private static string s_LastPreviewPath; + private static PackageImport.Constants ms_Constants; + public PackageImport() + { + base.minSize = new Vector2(350f, 350f); + } + public static void ShowImportPackage(string packagePath, AssetsItem[] items, string packageIconPath) + { + PackageImport window = EditorWindow.GetWindow(true, "Importing package"); + window.Init(packagePath, items, packageIconPath); + } + public void OnBeforeSerialize() + { + if (this.m_Tree != null) + { + if (this.m_EnabledFolders == null) + { + this.m_EnabledFolders = new List(); + } + this.m_EnabledFolders.Clear(); + this.m_Tree.GetEnabledFolders(this.m_EnabledFolders); + } + } + public void OnAfterDeserialize() + { + } + private void OnDisable() + { + this.DestroyCreatedIcons(); + } + private void DestroyCreatedIcons() + { + if (PackageImport.s_Preview != null) + { + UnityEngine.Object.DestroyImmediate(PackageImport.s_Preview); + PackageImport.s_Preview = null; + PackageImport.s_LastPreviewPath = null; + } + if (PackageImport.s_PackageIcon != null) + { + UnityEngine.Object.DestroyImmediate(PackageImport.s_PackageIcon); + PackageImport.s_PackageIcon = null; + } + } + private void Init(string packagePath, AssetsItem[] items, string packageIconPath) + { + this.DestroyCreatedIcons(); + this.m_TreeViewState = null; + this.m_Tree = null; + this.m_EnabledFolders = null; + this.m_Assets = items; + this.m_PackageName = Path.GetFileNameWithoutExtension(packagePath); + this.m_PackageIconPath = packageIconPath; + base.Repaint(); + } + public void OnGUI() + { + if (PackageImport.ms_Constants == null) + { + PackageImport.ms_Constants = new PackageImport.Constants(); + } + if (this.m_Assets == null) + { + return; + } + if (this.m_TreeViewState == null) + { + this.m_TreeViewState = new TreeViewState(); + } + if (this.m_Tree == null) + { + this.m_Tree = new PackageImportTreeView(this.m_Assets, this.m_EnabledFolders, this.m_TreeViewState, this, default(Rect)); + } + if (this.m_Assets.Length > 0) + { + this.TopArea(); + this.m_Tree.OnGUI(GUILayoutUtility.GetRect(1f, 9999f, 1f, 99999f)); + this.BottomArea(); + } + else + { + GUILayout.Label("Nothing to import!", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label("All assets from this package are already in your project.", "WordWrappedLabel", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("OK", new GUILayoutOption[0])) + { + base.Close(); + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + } + } + private void TopArea() + { + if (PackageImport.s_PackageIcon == null && !string.IsNullOrEmpty(this.m_PackageIconPath)) + { + PackageImport.LoadTexture(this.m_PackageIconPath, ref PackageImport.s_PackageIcon); + } + bool flag = PackageImport.s_PackageIcon != null; + float height = (!flag) ? 52f : 84f; + Rect rect = GUILayoutUtility.GetRect(base.position.width, height); + GUI.Label(rect, GUIContent.none, PackageImport.ms_Constants.topBarBg); + Rect position; + if (flag) + { + Rect r = new Rect(rect.x + 10f, rect.y + 10f, 64f, 64f); + PackageImport.DrawTexture(r, PackageImport.s_PackageIcon, true); + position = new Rect(r.xMax + 10f, r.yMin, rect.width, r.height); + } + else + { + position = new Rect(rect.x + 5f, rect.yMin, rect.width, rect.height); + } + GUI.Label(position, this.m_PackageName, PackageImport.ms_Constants.title); + } + private void BottomArea() + { + GUILayout.BeginVertical(PackageImport.ms_Constants.bottomBarBg, new GUILayoutOption[0]); + GUILayout.Space(8f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + if (GUILayout.Button(EditorGUIUtility.TextContent("All"), new GUILayoutOption[] + { + GUILayout.Width(50f) + })) + { + this.m_Tree.SetAllEnabled(1); + } + if (GUILayout.Button(EditorGUIUtility.TextContent("None"), new GUILayoutOption[] + { + GUILayout.Width(50f) + })) + { + this.m_Tree.SetAllEnabled(0); + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button(EditorGUIUtility.TextContent("Cancel"), new GUILayoutOption[0])) + { + base.Close(); + GUIUtility.ExitGUI(); + } + if (GUILayout.Button(EditorGUIUtility.TextContent("Import"), new GUILayoutOption[0])) + { + if (this.m_Assets != null) + { + AssetServer.ImportPackageStep2(this.m_Assets); + } + base.Close(); + GUIUtility.ExitGUI(); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + GUILayout.EndVertical(); + } + private static void LoadTexture(string filepath, ref Texture2D texture) + { + if (!texture) + { + texture = new Texture2D(128, 128); + } + byte[] array = null; + try + { + array = File.ReadAllBytes(filepath); + } + catch + { + } + if (filepath == string.Empty || array == null || !texture.LoadImage(array)) + { + Color[] pixels = texture.GetPixels(); + for (int i = 0; i < pixels.Length; i++) + { + pixels[i] = new Color(0.5f, 0.5f, 0.5f, 0f); + } + texture.SetPixels(pixels); + texture.Apply(); + } + } + public static void DrawTexture(Rect r, Texture2D tex, bool useDropshadow) + { + if (tex == null) + { + return; + } + float num = (float)tex.width; + float num2 = (float)tex.height; + if (num >= num2 && num > r.width) + { + num2 = num2 * r.width / num; + num = r.width; + } + else + { + if (num2 > num && num2 > r.height) + { + num = num * r.height / num2; + num2 = r.height; + } + } + float left = r.x + Mathf.Round((r.width - num) / 2f); + float top = r.y + Mathf.Round((r.height - num2) / 2f); + r = new Rect(left, top, num, num2); + if (useDropshadow && Event.current.type == EventType.Repaint) + { + Rect position = new RectOffset(1, 1, 1, 1).Remove(PackageImport.ms_Constants.textureIconDropShadow.border.Add(r)); + PackageImport.ms_Constants.textureIconDropShadow.Draw(position, GUIContent.none, false, false, false, false); + } + GUI.DrawTexture(r, tex, ScaleMode.ScaleToFit, true); + } + public static Texture2D GetPreview(string previewPath) + { + if (previewPath != PackageImport.s_LastPreviewPath) + { + PackageImport.s_LastPreviewPath = previewPath; + PackageImport.LoadTexture(previewPath, ref PackageImport.s_Preview); + } + return PackageImport.s_Preview; + } + } +} diff --git a/UnityEditor/UnityEditor/PackageImportTreeView.cs b/UnityEditor/UnityEditor/PackageImportTreeView.cs new file mode 100644 index 00000000..b48ccf12 --- /dev/null +++ b/UnityEditor/UnityEditor/PackageImportTreeView.cs @@ -0,0 +1,464 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PackageImportTreeView + { + public enum Amount + { + NotSet = -1, + None, + All, + Mixed + } + private class PackageImportTreeViewItem : TreeViewItem + { + public AssetsItem item + { + get; + set; + } + public bool isFolder + { + get; + set; + } + public PackageImportTreeViewItem(int id, int depth, TreeViewItem parent, string displayName) : base(id, depth, parent, displayName) + { + this.item = this.item; + } + } + private class PackageImportTreeViewGUI : TreeViewGUI + { + private static Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + public Action itemWasToggled; + public int showPreviewForID + { + get; + set; + } + public PackageImportTreeViewGUI(TreeView treeView) : base(treeView) + { + this.k_BaseIndent = 4f; + if (!PackageImportTreeView.s_UseFoldouts) + { + this.k_FoldoutWidth = 0f; + } + } + public override Rect OnRowGUI(TreeViewItem node, int row, float rowWidth, bool selected, bool focused) + { + Rect rect = new Rect(0f, (float)row * this.k_LineHeight, rowWidth, this.k_LineHeight); + this.DoNodeGUI(rect, node, selected, focused, false); + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = node as PackageImportTreeView.PackageImportTreeViewItem; + if (packageImportTreeViewItem != null) + { + Rect toggleRect = new Rect(2f, rect.y, rect.height, rect.height); + EditorGUI.BeginChangeCheck(); + PackageImportTreeView.PackageImportTreeViewGUI.Toggle(packageImportTreeViewItem, toggleRect); + if (EditorGUI.EndChangeCheck()) + { + if (this.m_TreeView.GetSelection().Length <= 1 || !this.m_TreeView.GetSelection().Contains(packageImportTreeViewItem.id)) + { + this.m_TreeView.SetSelection(new int[] + { + packageImportTreeViewItem.id + }, false); + this.m_TreeView.NotifyListenersThatSelectionChanged(); + } + if (this.itemWasToggled != null) + { + this.itemWasToggled(packageImportTreeViewItem); + } + Event.current.Use(); + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition) && !PopupWindowWithoutFocus.IsVisible()) + { + this.showPreviewForID = packageImportTreeViewItem.id; + } + if (packageImportTreeViewItem.id == this.showPreviewForID && Event.current.type != EventType.Layout) + { + this.showPreviewForID = 0; + if (!string.IsNullOrEmpty(packageImportTreeViewItem.item.previewPath)) + { + Texture2D preview = PackageImport.GetPreview(packageImportTreeViewItem.item.previewPath); + Rect rect2 = rect; + rect2.width = EditorGUIUtility.currentViewWidth; + Rect arg_190_0 = rect2; + PopupWindowContent arg_190_1 = new PackageImportTreeView.PreviewPopup(preview); + PopupLocationHelper.PopupLocation[] expr_188 = new PopupLocationHelper.PopupLocation[3]; + expr_188[0] = PopupLocationHelper.PopupLocation.Right; + expr_188[1] = PopupLocationHelper.PopupLocation.Left; + PopupWindowWithoutFocus.Show(arg_190_0, arg_190_1, expr_188); + } + } + if (packageImportTreeViewItem.item.exists == 0) + { + Texture image = ASMainWindow.badgeNew.image; + GUI.DrawTexture(new Rect(rect.xMax - (float)image.width - 6f, rect.y + (rect.height - (float)image.height) / 2f, (float)image.width, (float)image.height), image); + } + } + return rect; + } + private static void Toggle(PackageImportTreeView.PackageImportTreeViewItem pitem, Rect toggleRect) + { + bool flag = pitem.item.enabled > 0; + GUIStyle style = EditorStyles.toggle; + bool flag2 = pitem.isFolder && pitem.item.enabled == 2; + if (flag2) + { + style = EditorStyles.toggleMixed; + } + bool flag3 = GUI.Toggle(toggleRect, flag, GUIContent.none, style); + if (flag3 != flag) + { + pitem.item.enabled = ((!flag3) ? 0 : 1); + } + } + protected override Texture GetIconForNode(TreeViewItem item) + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = item as PackageImportTreeView.PackageImportTreeViewItem; + if (packageImportTreeViewItem.isFolder) + { + return PackageImportTreeView.PackageImportTreeViewGUI.folderIcon; + } + return InternalEditorUtility.GetIconForFile(packageImportTreeViewItem.item.pathName); + } + protected override void RenameEnded() + { + } + } + private class PackageImportTreeViewDataSource : TreeViewDataSource + { + public AssetsItem[] m_AssetItems; + public List m_EnabledFolders; + public PackageImportTreeViewDataSource(TreeView treeView, AssetsItem[] assetItems, List enabledFolders) : base(treeView) + { + this.m_AssetItems = assetItems; + this.m_EnabledFolders = enabledFolders; + base.rootIsCollapsable = false; + base.showRootNode = false; + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return false; + } + public override bool IsExpandable(TreeViewItem item) + { + return PackageImportTreeView.s_UseFoldouts && base.IsExpandable(item); + } + public override void FetchData() + { + this.m_RootItem = new PackageImportTreeView.PackageImportTreeViewItem("Assets".GetHashCode(), 0, null, "InvisibleAssetsFolder"); + ((PackageImportTreeView.PackageImportTreeViewItem)this.m_RootItem).isFolder = true; + bool flag = this.m_TreeView.state.expandedIDs.Count == 0; + if (flag) + { + this.m_TreeView.state.expandedIDs.Add(this.m_RootItem.id); + } + Dictionary dictionary = new Dictionary(); + AssetsItem[] assetItems = this.m_AssetItems; + for (int i = 0; i < assetItems.Length; i++) + { + AssetsItem assetsItem = assetItems[i]; + if (assetsItem.assetIsDir == 1) + { + dictionary[assetsItem.pathName] = assetsItem; + } + } + Dictionary treeViewFolders = new Dictionary(); + AssetsItem[] assetItems2 = this.m_AssetItems; + for (int j = 0; j < assetItems2.Length; j++) + { + AssetsItem assetsItem2 = assetItems2[j]; + if (assetsItem2.assetIsDir != 1) + { + string fileName = Path.GetFileName(assetsItem2.pathName); + string directoryName = Path.GetDirectoryName(assetsItem2.pathName); + TreeViewItem treeViewItem = this.EnsureFolderPath(directoryName, dictionary, treeViewFolders, flag); + if (treeViewItem != null) + { + int hashCode = assetsItem2.pathName.GetHashCode(); + treeViewItem.AddChild(new PackageImportTreeView.PackageImportTreeViewItem(hashCode, treeViewItem.depth + 1, treeViewItem, fileName) + { + item = assetsItem2 + }); + } + } + } + if (flag) + { + this.m_TreeView.state.expandedIDs.Sort(); + } + } + private TreeViewItem EnsureFolderPath(string folderPath, Dictionary packageFolders, Dictionary treeViewFolders, bool initExpandedState) + { + int hashCode = folderPath.GetHashCode(); + TreeViewItem treeViewItem = TreeViewUtility.FindItem(hashCode, this.m_RootItem); + if (treeViewItem != null) + { + return treeViewItem; + } + string[] array = folderPath.Split(new char[] + { + '/' + }); + string text = string.Empty; + TreeViewItem treeViewItem2 = this.m_RootItem; + for (int i = 0; i < array.Length; i++) + { + string text2 = array[i]; + if (text != string.Empty) + { + text += '/'; + } + text += text2; + if (!(text == "Assets")) + { + hashCode = text.GetHashCode(); + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem; + if (treeViewFolders.TryGetValue(text, out packageImportTreeViewItem)) + { + treeViewItem2 = packageImportTreeViewItem; + } + else + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem2 = new PackageImportTreeView.PackageImportTreeViewItem(hashCode, i, treeViewItem2, text2); + packageImportTreeViewItem2.isFolder = true; + AssetsItem item; + if (packageFolders.TryGetValue(text, out item)) + { + packageImportTreeViewItem2.item = item; + } + if (packageImportTreeViewItem2.item == null) + { + packageImportTreeViewItem2.item = new AssetsItem + { + assetIsDir = 1, + pathName = text, + exportedAssetPath = text, + enabled = (this.m_EnabledFolders != null) ? ((!this.m_EnabledFolders.Contains(text)) ? 0 : 1) : 1, + guid = AssetDatabase.AssetPathToGUID(text), + previewPath = string.Empty + }; + packageImportTreeViewItem2.item.exists = ((!string.IsNullOrEmpty(packageImportTreeViewItem2.item.guid)) ? 1 : 0); + } + treeViewItem2.AddChild(packageImportTreeViewItem2); + treeViewItem2 = packageImportTreeViewItem2; + if (initExpandedState) + { + this.m_TreeView.state.expandedIDs.Add(hashCode); + } + treeViewFolders[text] = packageImportTreeViewItem2; + } + } + } + return treeViewItem2; + } + } + private class PreviewPopup : PopupWindowContent + { + private readonly Texture2D m_Preview; + private readonly Vector2 kPreviewSize = new Vector2(128f, 128f); + public PreviewPopup(Texture2D preview) + { + this.m_Preview = preview; + } + public override void OnGUI(Rect rect) + { + PackageImport.DrawTexture(rect, this.m_Preview, false); + } + public override Vector2 GetWindowSize() + { + return this.kPreviewSize; + } + } + private TreeView m_TreeView; + private List m_Selection = new List(); + private static readonly bool s_UseFoldouts = true; + public PackageImportTreeView(AssetsItem[] items, List enabledFolders, TreeViewState treeViewState, PackageImport packageImportWindow, Rect startRect) + { + this.m_TreeView = new TreeView(packageImportWindow, treeViewState); + PackageImportTreeView.PackageImportTreeViewDataSource data = new PackageImportTreeView.PackageImportTreeViewDataSource(this.m_TreeView, items, enabledFolders); + PackageImportTreeView.PackageImportTreeViewGUI packageImportTreeViewGUI = new PackageImportTreeView.PackageImportTreeViewGUI(this.m_TreeView); + this.m_TreeView.Init(startRect, data, packageImportTreeViewGUI, null); + this.m_TreeView.ReloadData(); + TreeView expr_5A = this.m_TreeView; + expr_5A.selectionChangedCallback = (Action)Delegate.Combine(expr_5A.selectionChangedCallback, new Action(this.SelectionChanged)); + PackageImportTreeView.PackageImportTreeViewGUI expr_7C = packageImportTreeViewGUI; + expr_7C.itemWasToggled = (Action)Delegate.Combine(expr_7C.itemWasToggled, new Action(this.ItemWasToggled)); + this.ComputeEnabledStateForFolders(); + } + private void ComputeEnabledStateForFolders() + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = this.m_TreeView.data.root as PackageImportTreeView.PackageImportTreeViewItem; + this.RecursiveComputeEnabledStateForFolders(packageImportTreeViewItem, new HashSet + { + packageImportTreeViewItem + }); + } + private void RecursiveComputeEnabledStateForFolders(PackageImportTreeView.PackageImportTreeViewItem pitem, HashSet done) + { + if (!pitem.isFolder) + { + return; + } + if (pitem.hasChildren) + { + foreach (TreeViewItem current in pitem.children) + { + this.RecursiveComputeEnabledStateForFolders(current as PackageImportTreeView.PackageImportTreeViewItem, done); + } + } + if (!done.Contains(pitem)) + { + PackageImportTreeView.Amount folderChildrenEnabledState = this.GetFolderChildrenEnabledState(pitem); + pitem.item.enabled = (int)folderChildrenEnabledState; + if (folderChildrenEnabledState == PackageImportTreeView.Amount.Mixed) + { + done.Add(pitem); + for (PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = pitem.parent as PackageImportTreeView.PackageImportTreeViewItem; packageImportTreeViewItem != null; packageImportTreeViewItem = (packageImportTreeViewItem.parent as PackageImportTreeView.PackageImportTreeViewItem)) + { + if (!done.Contains(packageImportTreeViewItem)) + { + packageImportTreeViewItem.item.enabled = 2; + done.Add(packageImportTreeViewItem); + } + } + } + } + } + private PackageImportTreeView.Amount GetFolderChildrenEnabledState(PackageImportTreeView.PackageImportTreeViewItem folder) + { + if (!folder.isFolder) + { + Debug.LogError("Should be a folder item!"); + } + if (!folder.hasChildren) + { + return PackageImportTreeView.Amount.None; + } + PackageImportTreeView.Amount amount = PackageImportTreeView.Amount.NotSet; + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = folder.children[0] as PackageImportTreeView.PackageImportTreeViewItem; + int enabled = packageImportTreeViewItem.item.enabled; + for (int i = 1; i < folder.children.Count; i++) + { + if (enabled != (folder.children[i] as PackageImportTreeView.PackageImportTreeViewItem).item.enabled) + { + amount = PackageImportTreeView.Amount.Mixed; + break; + } + } + if (amount == PackageImportTreeView.Amount.NotSet) + { + amount = ((enabled != 1) ? PackageImportTreeView.Amount.None : PackageImportTreeView.Amount.All); + } + return amount; + } + private void SelectionChanged(int[] selectedIDs) + { + this.m_Selection = new List(); + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + foreach (TreeViewItem current in visibleRows) + { + if (selectedIDs.Contains(current.id)) + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = current as PackageImportTreeView.PackageImportTreeViewItem; + if (packageImportTreeViewItem != null) + { + this.m_Selection.Add(packageImportTreeViewItem); + } + } + } + if (this.m_Selection.Count == 1 && !string.IsNullOrEmpty(this.m_Selection[0].item.previewPath)) + { + PackageImportTreeView.PackageImportTreeViewGUI packageImportTreeViewGUI = this.m_TreeView.gui as PackageImportTreeView.PackageImportTreeViewGUI; + packageImportTreeViewGUI.showPreviewForID = this.m_Selection[0].id; + } + else + { + PopupWindowWithoutFocus.Hide(); + } + } + public AssetsItem GetSingleSelection() + { + if (this.m_Selection != null && this.m_Selection.Count == 1) + { + return this.m_Selection[0].item; + } + return null; + } + public void GetEnabledFolders(List folderPaths) + { + this.GetEnabledFoldersRecursive(this.m_TreeView.data.root, folderPaths); + } + private void GetEnabledFoldersRecursive(TreeViewItem parentItem, List folderPaths) + { + if (!parentItem.hasChildren) + { + return; + } + foreach (TreeViewItem current in parentItem.children) + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = current as PackageImportTreeView.PackageImportTreeViewItem; + if (packageImportTreeViewItem.isFolder && packageImportTreeViewItem.item.enabled > 0) + { + folderPaths.Add(packageImportTreeViewItem.item.pathName); + } + this.GetEnabledFoldersRecursive(packageImportTreeViewItem, folderPaths); + } + } + public void OnGUI(Rect rect) + { + if (Event.current.type == EventType.ScrollWheel) + { + PopupWindowWithoutFocus.Hide(); + } + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.m_TreeView.OnGUI(rect, controlID); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Space && this.m_Selection != null && this.m_Selection.Count > 0 && GUIUtility.keyboardControl == controlID) + { + int enabled = (this.m_Selection[0].item.enabled != 0) ? 0 : 1; + this.m_Selection[0].item.enabled = enabled; + this.ItemWasToggled(this.m_Selection[0]); + Event.current.Use(); + } + } + public void SetAllEnabled(int enabled) + { + this.EnableChildrenRecursive(this.m_TreeView.data.root, enabled); + this.ComputeEnabledStateForFolders(); + } + private void ItemWasToggled(PackageImportTreeView.PackageImportTreeViewItem pitem) + { + if (this.m_Selection.Count <= 1) + { + this.EnableChildrenRecursive(pitem, pitem.item.enabled); + } + else + { + foreach (PackageImportTreeView.PackageImportTreeViewItem current in this.m_Selection) + { + current.item.enabled = pitem.item.enabled; + } + } + this.ComputeEnabledStateForFolders(); + } + private void EnableChildrenRecursive(TreeViewItem parentItem, int enabled) + { + if (!parentItem.hasChildren) + { + return; + } + foreach (TreeViewItem current in parentItem.children) + { + PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = current as PackageImportTreeView.PackageImportTreeViewItem; + packageImportTreeViewItem.item.enabled = enabled; + this.EnableChildrenRecursive(packageImportTreeViewItem, enabled); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PackageInfo.cs b/UnityEditor/UnityEditor/PackageInfo.cs new file mode 100644 index 00000000..6aa6ef86 --- /dev/null +++ b/UnityEditor/UnityEditor/PackageInfo.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public struct PackageInfo + { + public string packagePath; + public string jsonInfo; + public string iconURL; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern PackageInfo[] GetPackageList(); + } +} diff --git a/UnityEditor/UnityEditor/PaneDragTab.cs b/UnityEditor/UnityEditor/PaneDragTab.cs new file mode 100644 index 00000000..b2c58c0b --- /dev/null +++ b/UnityEditor/UnityEditor/PaneDragTab.cs @@ -0,0 +1,209 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + internal class PaneDragTab : GUIView + { + private const float kTopThumbnailOffset = 10f; + [SerializeField] + private bool m_Shadow; + private static PaneDragTab s_Get; + [SerializeField] + private Vector2 m_ThumbnailSize = new Vector2(80f, 60f); + private Rect m_StartRect; + [SerializeField] + private Rect m_TargetRect; + [SerializeField] + private static GUIStyle s_PaneStyle; + [SerializeField] + private static GUIStyle s_TabStyle; + private AnimBool m_PaneVisible = new AnimBool(); + private AnimBool m_TabVisible = new AnimBool(); + private float m_StartAlpha = 1f; + private float m_TargetAlpha = 1f; + private bool m_DidResizeOnLastLayout; + private DropInfo.Type m_Type = (DropInfo.Type)(-1); + private float m_StartTime; + public GUIContent content; + private Texture2D m_Thumbnail; + [SerializeField] + internal ContainerWindow m_Window; + [SerializeField] + private ContainerWindow m_InFrontOfWindow; + public static PaneDragTab get + { + get + { + if (!PaneDragTab.s_Get) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(PaneDragTab)); + if (array.Length != 0) + { + PaneDragTab.s_Get = (PaneDragTab)array[0]; + } + if (PaneDragTab.s_Get) + { + return PaneDragTab.s_Get; + } + PaneDragTab.s_Get = ScriptableObject.CreateInstance(); + } + return PaneDragTab.s_Get; + } + } + public void OnEnable() + { + this.m_PaneVisible.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_TabVisible.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + public void OnDisable() + { + this.m_PaneVisible.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_TabVisible.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + } + public void GrabThumbnail() + { + if (this.m_Thumbnail != null) + { + UnityEngine.Object.DestroyImmediate(this.m_Thumbnail); + } + this.m_Thumbnail = new Texture2D(Screen.width, Screen.height); + this.m_Thumbnail.ReadPixels(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), 0, 0); + this.m_Thumbnail.Apply(); + float num = (float)(this.m_Thumbnail.width * this.m_Thumbnail.height); + this.m_ThumbnailSize = new Vector2((float)this.m_Thumbnail.width, (float)this.m_Thumbnail.height) * Mathf.Sqrt(Mathf.Clamp01(50000f / num)); + } + public void SetDropInfo(DropInfo di, Vector2 mouseScreenPos, ContainerWindow inFrontOf) + { + if (this.m_Type != di.type || (di.type == DropInfo.Type.Pane && di.rect != this.m_TargetRect)) + { + this.m_Type = di.type; + this.m_StartRect = this.GetInterpolatedRect(this.CalcFade()); + this.m_StartTime = Time.realtimeSinceStartup; + switch (di.type) + { + case DropInfo.Type.Tab: + case DropInfo.Type.Pane: + this.m_TargetAlpha = 1f; + break; + case DropInfo.Type.Window: + this.m_TargetAlpha = 0.6f; + break; + } + } + switch (di.type) + { + case DropInfo.Type.Tab: + case DropInfo.Type.Pane: + this.m_TargetRect = di.rect; + break; + case DropInfo.Type.Window: + this.m_TargetRect = new Rect(mouseScreenPos.x - this.m_ThumbnailSize.x / 2f, mouseScreenPos.y - this.m_ThumbnailSize.y / 2f, this.m_ThumbnailSize.x, this.m_ThumbnailSize.y); + break; + } + this.m_PaneVisible.target = (di.type == DropInfo.Type.Pane); + this.m_TabVisible.target = (di.type == DropInfo.Type.Tab); + this.m_TargetRect.x = Mathf.Round(this.m_TargetRect.x); + this.m_TargetRect.y = Mathf.Round(this.m_TargetRect.y); + this.m_TargetRect.width = Mathf.Round(this.m_TargetRect.width); + this.m_TargetRect.height = Mathf.Round(this.m_TargetRect.height); + this.m_InFrontOfWindow = inFrontOf; + this.m_Window.MoveInFrontOf(this.m_InFrontOfWindow); + this.SetWindowPos(this.GetInterpolatedRect(this.CalcFade())); + base.Repaint(); + } + public void Close() + { + if (this.m_Thumbnail != null) + { + UnityEngine.Object.DestroyImmediate(this.m_Thumbnail); + } + if (this.m_Window) + { + this.m_Window.Close(); + } + UnityEngine.Object.DestroyImmediate(this, true); + PaneDragTab.s_Get = null; + } + public void Show(Rect pixelPos, Vector2 mouseScreenPosition) + { + if (!this.m_Window) + { + this.m_Window = ScriptableObject.CreateInstance(); + this.m_Window.m_DontSaveToLayout = true; + base.SetMinMaxSizes(Vector2.zero, new Vector2(10000f, 10000f)); + this.SetWindowPos(pixelPos); + this.m_Window.mainView = this; + } + else + { + this.SetWindowPos(pixelPos); + } + this.m_Window.Show(ShowMode.NoShadow, true, false); + this.m_TargetRect = pixelPos; + } + private void SetWindowPos(Rect screenPosition) + { + this.m_Window.position = screenPosition; + } + private float CalcFade() + { + if (Application.platform == RuntimePlatform.WindowsEditor) + { + return 1f; + } + return Mathf.SmoothStep(0f, 1f, Mathf.Clamp01(5f * (Time.realtimeSinceStartup - this.m_StartTime))); + } + private Rect GetInterpolatedRect(float fade) + { + return new Rect(Mathf.Lerp(this.m_StartRect.x, this.m_TargetRect.x, fade), Mathf.Lerp(this.m_StartRect.y, this.m_TargetRect.y, fade), Mathf.Lerp(this.m_StartRect.width, this.m_TargetRect.width, fade), Mathf.Lerp(this.m_StartRect.height, this.m_TargetRect.height, fade)); + } + private void OnGUI() + { + float num = this.CalcFade(); + if (PaneDragTab.s_PaneStyle == null) + { + PaneDragTab.s_PaneStyle = "dragtabdropwindow"; + PaneDragTab.s_TabStyle = "dragtab"; + } + if (Event.current.type == EventType.Layout) + { + this.m_DidResizeOnLastLayout = !this.m_DidResizeOnLastLayout; + if (!this.m_DidResizeOnLastLayout) + { + this.SetWindowPos(this.GetInterpolatedRect(num)); + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_Window.SetAlpha(Mathf.Lerp(this.m_StartAlpha, this.m_TargetAlpha, num)); + } + return; + } + } + if (Event.current.type == EventType.Repaint) + { + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, 1f); + if (this.m_Thumbnail != null) + { + GUI.DrawTexture(new Rect(0f, 0f, base.position.width, base.position.height), this.m_Thumbnail, ScaleMode.StretchToFill, false); + } + if (this.m_TabVisible.faded != 0f) + { + GUI.color = new Color(1f, 1f, 1f, this.m_TabVisible.faded); + PaneDragTab.s_TabStyle.Draw(new Rect(0f, 0f, base.position.width, base.position.height), this.content, false, false, true, true); + } + if (this.m_PaneVisible.faded != 0f) + { + GUI.color = new Color(1f, 1f, 1f, this.m_PaneVisible.faded); + PaneDragTab.s_PaneStyle.Draw(new Rect(0f, 0f, base.position.width, base.position.height), this.content, false, false, true, true); + } + GUI.color = color; + } + if (Application.platform != RuntimePlatform.WindowsEditor) + { + base.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ParentViewFile.cs b/UnityEditor/UnityEditor/ParentViewFile.cs new file mode 100644 index 00000000..d7cfda5d --- /dev/null +++ b/UnityEditor/UnityEditor/ParentViewFile.cs @@ -0,0 +1,23 @@ +using System; +namespace UnityEditor +{ + [Serializable] + internal class ParentViewFile + { + public string guid; + public string name; + public ChangeFlags changeFlags; + public ParentViewFile(string name, string guid) + { + this.guid = guid; + this.name = name; + this.changeFlags = ChangeFlags.None; + } + public ParentViewFile(string name, string guid, ChangeFlags flags) + { + this.guid = guid; + this.name = name; + this.changeFlags = flags; + } + } +} diff --git a/UnityEditor/UnityEditor/ParentViewFolder.cs b/UnityEditor/UnityEditor/ParentViewFolder.cs new file mode 100644 index 00000000..35a2960b --- /dev/null +++ b/UnityEditor/UnityEditor/ParentViewFolder.cs @@ -0,0 +1,53 @@ +using System; +namespace UnityEditor +{ + [Serializable] + internal class ParentViewFolder + { + private const string rootDirText = "/"; + private const string assetsFolder = "Assets"; + private const string libraryFolder = "Library"; + public string guid; + public string name; + public ChangeFlags changeFlags; + public ParentViewFile[] files; + public ParentViewFolder(string name, string guid) + { + this.guid = guid; + this.name = name; + this.changeFlags = ChangeFlags.None; + this.files = new ParentViewFile[0]; + } + public ParentViewFolder(string name, string guid, ChangeFlags flags) + { + this.guid = guid; + this.name = name; + this.changeFlags = flags; + this.files = new ParentViewFile[0]; + } + public static string MakeNiceName(string name) + { + if (name.StartsWith("Assets")) + { + if (name != "Assets") + { + name = name.Substring("Assets".Length + 1); + return (!(name == string.Empty)) ? name : "/"; + } + return "/"; + } + else + { + if (name.StartsWith("Library")) + { + return "../" + name; + } + return (!(name == string.Empty)) ? name : "/"; + } + } + public ParentViewFolder CloneWithoutFiles() + { + return new ParentViewFolder(this.name, this.guid, this.changeFlags); + } + } +} diff --git a/UnityEditor/UnityEditor/ParentViewState.cs b/UnityEditor/UnityEditor/ParentViewState.cs new file mode 100644 index 00000000..6344a5b3 --- /dev/null +++ b/UnityEditor/UnityEditor/ParentViewState.cs @@ -0,0 +1,211 @@ +using System; +namespace UnityEditor +{ + [Serializable] + internal class ParentViewState + { + public ListViewState lv; + public int selectedFolder = -1; + public int selectedFile = -1; + public int initialSelectedItem = -1; + public ParentViewFolder[] folders = new ParentViewFolder[0]; + public bool[] selectedItems; + public int GetLineCount() + { + int num = 0; + for (int i = 0; i < this.folders.Length; i++) + { + num += this.folders[i].files.Length + 1; + } + return num; + } + public bool HasTrue() + { + for (int i = 0; i < this.selectedItems.Length; i++) + { + if (this.selectedItems[i]) + { + return true; + } + } + return false; + } + public void SetLineCount() + { + this.lv.totalRows = this.GetLineCount(); + } + public int GetFoldersCount() + { + return this.folders.Length; + } + public void ClearSelection() + { + for (int i = 0; i < this.selectedItems.Length; i++) + { + this.selectedItems[i] = false; + } + this.initialSelectedItem = -1; + } + internal static int IndexOf(ParentViewFolder[] foldersFrom, string lfname) + { + for (int i = 0; i < foldersFrom.Length; i++) + { + if (string.Compare(foldersFrom[i].name, lfname, true) == 0) + { + return i; + } + } + return -1; + } + internal static int IndexOf(ParentViewFile[] filesFrom, string lfname) + { + for (int i = 0; i < filesFrom.Length; i++) + { + if (string.Compare(filesFrom[i].name, lfname, true) == 0) + { + return i; + } + } + return -1; + } + internal static int CompareViewFolder(ParentViewFolder p1, ParentViewFolder p2) + { + return string.Compare(p1.name, p2.name, true); + } + internal static int CompareViewFile(ParentViewFile p1, ParentViewFile p2) + { + return string.Compare(p1.name, p2.name, true); + } + private void AddAssetItem(string guid, string pathName, bool isDir, ChangeFlags changeFlags, int changeset) + { + if (pathName == string.Empty) + { + return; + } + if (isDir) + { + string text = ParentViewFolder.MakeNiceName(pathName); + int num = ParentViewState.IndexOf(this.folders, text); + if (num == -1) + { + ParentViewFolder item = new ParentViewFolder(text, guid, changeFlags); + ArrayUtility.Add(ref this.folders, item); + } + else + { + this.folders[num].changeFlags = changeFlags; + this.folders[num].guid = guid; + } + } + else + { + string text2 = ParentViewFolder.MakeNiceName(FileUtil.DeleteLastPathNameComponent(pathName)); + string text3 = pathName.Substring(pathName.LastIndexOf("/") + 1); + int num2 = ParentViewState.IndexOf(this.folders, text2); + ParentViewFolder parentViewFolder; + if (num2 == -1) + { + parentViewFolder = new ParentViewFolder(text2, AssetServer.GetParentGUID(guid, changeset)); + ArrayUtility.Add(ref this.folders, parentViewFolder); + } + else + { + parentViewFolder = this.folders[num2]; + } + num2 = ParentViewState.IndexOf(parentViewFolder.files, text3); + if (num2 != -1) + { + if ((parentViewFolder.files[num2].changeFlags & ChangeFlags.Deleted) == ChangeFlags.None) + { + parentViewFolder.files[num2].guid = guid; + parentViewFolder.files[num2].changeFlags = changeFlags; + } + return; + } + ArrayUtility.Add(ref parentViewFolder.files, new ParentViewFile(text3, guid, changeFlags)); + } + } + public void AddAssetItems(AssetsItem[] assets) + { + for (int i = 0; i < assets.Length; i++) + { + AssetsItem assetsItem = assets[i]; + this.AddAssetItem(assetsItem.guid, assetsItem.pathName, assetsItem.assetIsDir != 0, (ChangeFlags)assetsItem.changeFlags, -1); + } + Array.Sort(this.folders, new Comparison(ParentViewState.CompareViewFolder)); + for (int j = 0; j < this.folders.Length; j++) + { + Array.Sort(this.folders[j].files, new Comparison(ParentViewState.CompareViewFile)); + } + } + public void AddAssetItems(Changeset assets) + { + ChangesetItem[] items = assets.items; + for (int i = 0; i < items.Length; i++) + { + ChangesetItem changesetItem = items[i]; + this.AddAssetItem(changesetItem.guid, changesetItem.fullPath, changesetItem.assetIsDir != 0, changesetItem.changeFlags, assets.changeset); + } + Array.Sort(this.folders, new Comparison(ParentViewState.CompareViewFolder)); + for (int j = 0; j < this.folders.Length; j++) + { + Array.Sort(this.folders[j].files, new Comparison(ParentViewState.CompareViewFile)); + } + } + public void AddAssetItems(DeletedAsset[] assets) + { + for (int i = 0; i < assets.Length; i++) + { + DeletedAsset deletedAsset = assets[i]; + this.AddAssetItem(deletedAsset.guid, deletedAsset.fullPath, deletedAsset.assetIsDir != 0, ChangeFlags.None, -1); + } + Array.Sort(this.folders, new Comparison(ParentViewState.CompareViewFolder)); + for (int j = 0; j < this.folders.Length; j++) + { + Array.Sort(this.folders[j].files, new Comparison(ParentViewState.CompareViewFile)); + } + } + public void Clear() + { + this.folders = new ParentViewFolder[0]; + this.selectedFolder = -1; + this.selectedFile = -1; + this.initialSelectedItem = -1; + } + public bool NextFileFolder(ref int folder, ref int file) + { + if (folder >= this.folders.Length) + { + return false; + } + ParentViewFolder parentViewFolder = this.folders[folder]; + if (file >= parentViewFolder.files.Length - 1) + { + folder++; + file = -1; + if (folder >= this.folders.Length) + { + return false; + } + } + else + { + file++; + } + return true; + } + public bool IndexToFolderAndFile(int index, ref int folder, ref int file) + { + folder = 0; + file = -1; + for (int i = 0; i < index; i++) + { + if (!this.NextFileFolder(ref folder, ref file)) + { + return false; + } + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleEffectUI.cs b/UnityEditor/UnityEditor/ParticleEffectUI.cs new file mode 100644 index 00000000..2eb5884b --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleEffectUI.cs @@ -0,0 +1,927 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleEffectUI + { + private enum PlayState + { + Stopped, + Playing, + Paused + } + private enum OwnerType + { + Inspector, + ParticleSystemWindow + } + internal class Texts + { + public GUIContent previewSpeed = new GUIContent("Playback Speed"); + public GUIContent previewTime = new GUIContent("Playback Time"); + public GUIContent play = new GUIContent("Simulate"); + public GUIContent stop = new GUIContent("Stop"); + public GUIContent pause = new GUIContent("Pause"); + public GUIContent addParticleSystem = new GUIContent(string.Empty, "Create Particle System"); + public GUIContent wireframe = new GUIContent("Wireframe", "Show particles with wireframe and particle system bounds"); + public GUIContent resimulation = new GUIContent("Resimulate", "If resimulate is enabled the particle system will show changes made to the system immediately (including changes made to the particle system transform)"); + public string secondsFloatFieldFormatString = "f2"; + } + private const string k_SimulationStateId = "SimulationState"; + private const string k_ShowSelectedId = "ShowSelected"; + public ParticleEffectUIOwner m_Owner; + public ParticleSystemUI[] m_Emitters; + private ParticleSystemCurveEditor m_ParticleSystemCurveEditor; + private ParticleSystem m_SelectedParticleSystem; + private bool m_ShowOnlySelectedMode; + private TimeHelper m_TimeHelper = default(TimeHelper); + public static bool m_ShowWireframe = false; + public static bool m_VerticalLayout; + private static readonly Vector2 k_MinEmitterAreaSize = new Vector2(125f, 100f); + private static readonly Vector2 k_MinCurveAreaSize = new Vector2(100f, 100f); + private float m_EmitterAreaWidth = 230f; + private float m_CurveEditorAreaHeight = 330f; + private Vector2 m_EmitterAreaScrollPos = Vector2.zero; + private static readonly Color k_DarkSkinDisabledColor = new Color(0.66f, 0.66f, 0.66f, 0.95f); + private static readonly Color k_LightSkinDisabledColor = new Color(0.84f, 0.84f, 0.84f, 0.95f); + private static ParticleEffectUI.Texts s_Texts; + private static PrefKey kPlay = new PrefKey("ParticleSystem/Play", ","); + private static PrefKey kStop = new PrefKey("ParticleSystem/Stop", "."); + private static PrefKey kForward = new PrefKey("ParticleSystem/Forward", "m"); + private static PrefKey kReverse = new PrefKey("ParticleSystem/Reverse", "n"); + private int m_IsDraggingTimeHotControlID = -1; + internal static ParticleEffectUI.Texts texts + { + get + { + if (ParticleEffectUI.s_Texts == null) + { + ParticleEffectUI.s_Texts = new ParticleEffectUI.Texts(); + } + return ParticleEffectUI.s_Texts; + } + } + public ParticleEffectUI(ParticleEffectUIOwner owner) + { + this.m_Owner = owner; + Assert.That(this.m_Owner is ParticleSystemInspector || this.m_Owner is ParticleSystemWindow); + } + private bool ShouldManagePlaybackState(ParticleSystem root) + { + bool flag = false; + if (root != null) + { + flag = root.gameObject.activeInHierarchy; + } + return !EditorApplication.isPlaying && !ParticleSystemEditorUtils.editorUpdateAll && flag; + } + private static Color GetDisabledColor() + { + return EditorGUIUtility.isProSkin ? ParticleEffectUI.k_DarkSkinDisabledColor : ParticleEffectUI.k_LightSkinDisabledColor; + } + public bool InitializeIfNeeded(ParticleSystem shuriken) + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(shuriken); + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(root); + if (particleSystems == null || particleSystems.Length == 0) + { + return false; + } + if (root == this.GetRoot() && this.m_ParticleSystemCurveEditor != null && this.m_Emitters != null && particleSystems.Length == this.m_Emitters.Length) + { + this.m_SelectedParticleSystem = shuriken; + if (this.IsShowOnlySelectedMode()) + { + this.RefreshShowOnlySelected(); + } + return false; + } + if (this.m_ParticleSystemCurveEditor != null) + { + this.Clear(); + } + this.m_SelectedParticleSystem = shuriken; + ParticleSystemEditorUtils.PerformCompleteResimulation(); + this.m_ParticleSystemCurveEditor = new ParticleSystemCurveEditor(); + this.m_ParticleSystemCurveEditor.Init(); + this.m_EmitterAreaWidth = EditorPrefs.GetFloat("ParticleSystemEmitterAreaWidth", ParticleEffectUI.k_MinEmitterAreaSize.x); + this.m_CurveEditorAreaHeight = EditorPrefs.GetFloat("ParticleSystemCurveEditorAreaHeight", ParticleEffectUI.k_MinCurveAreaSize.y); + this.InitAllEmitters(particleSystems); + this.m_ShowOnlySelectedMode = (this.m_Owner is ParticleSystemWindow && InspectorState.GetBool("ShowSelected" + root.GetInstanceID(), false)); + if (this.IsShowOnlySelectedMode()) + { + this.RefreshShowOnlySelected(); + } + this.m_EmitterAreaScrollPos.x = InspectorState.GetFloat("CurrentEmitterAreaScroll", 0f); + if (this.ShouldManagePlaybackState(root)) + { + Vector3 vector = InspectorState.GetVector3("SimulationState" + root.GetInstanceID(), Vector3.zero); + if (root.GetInstanceID() == (int)vector.x) + { + float z = vector.z; + if (z > 0f) + { + ParticleSystemEditorUtils.editorPlaybackTime = z; + } + } + this.Play(); + } + return true; + } + internal void UndoRedoPerformed() + { + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + ModuleUI[] modules = particleSystemUI.m_Modules; + for (int j = 0; j < modules.Length; j++) + { + ModuleUI moduleUI = modules[j]; + if (moduleUI != null) + { + moduleUI.CheckVisibilityState(); + } + } + } + this.m_Owner.Repaint(); + } + public void Clear() + { + ParticleSystem root = this.GetRoot(); + if (this.ShouldManagePlaybackState(root) && root != null) + { + ParticleEffectUI.PlayState playState; + if (this.IsPlaying()) + { + playState = ParticleEffectUI.PlayState.Playing; + } + else + { + if (this.IsPaused()) + { + playState = ParticleEffectUI.PlayState.Paused; + } + else + { + playState = ParticleEffectUI.PlayState.Stopped; + } + } + int instanceID = root.GetInstanceID(); + InspectorState.SetVector3("SimulationState" + instanceID, new Vector3((float)instanceID, (float)playState, ParticleSystemEditorUtils.editorPlaybackTime)); + } + this.m_ParticleSystemCurveEditor.OnDisable(); + ParticleEffectUtils.ClearPlanes(); + Tools.s_Hidden = false; + if (root != null) + { + InspectorState.SetBool("ShowSelected" + root.GetInstanceID(), this.m_ShowOnlySelectedMode); + } + this.SetShowOnlySelectedMode(false); + GameView.RepaintAll(); + SceneView.RepaintAll(); + } + public static Vector2 GetMinSize() + { + return ParticleEffectUI.k_MinEmitterAreaSize + ParticleEffectUI.k_MinCurveAreaSize; + } + public void Refresh() + { + this.UpdateProperties(); + this.m_ParticleSystemCurveEditor.Refresh(); + } + public string GetNextParticleSystemName() + { + string text = string.Empty; + for (int i = 2; i < 50; i++) + { + text = "Particle System " + i; + bool flag = false; + ParticleSystemUI[] emitters = this.m_Emitters; + for (int j = 0; j < emitters.Length; j++) + { + ParticleSystemUI particleSystemUI = emitters[j]; + if (particleSystemUI.m_ParticleSystem.name == text) + { + flag = true; + break; + } + } + if (!flag) + { + return text; + } + } + return "Particle System"; + } + public bool IsParticleSystemUIVisible(ParticleSystemUI psUI) + { + ParticleEffectUI.OwnerType ownerType = (!(this.m_Owner is ParticleSystemInspector)) ? ParticleEffectUI.OwnerType.ParticleSystemWindow : ParticleEffectUI.OwnerType.Inspector; + return ownerType == ParticleEffectUI.OwnerType.ParticleSystemWindow || (ownerType == ParticleEffectUI.OwnerType.Inspector && psUI.m_ParticleSystem == this.m_SelectedParticleSystem); + } + private void InitAllEmitters(ParticleSystem[] shurikens) + { + int num = shurikens.Length; + if (num == 0) + { + return; + } + this.m_Emitters = new ParticleSystemUI[num]; + for (int i = 0; i < num; i++) + { + this.m_Emitters[i] = new ParticleSystemUI(); + this.m_Emitters[i].Init(this, shurikens[i]); + } + ParticleSystemUI[] emitters = this.m_Emitters; + for (int j = 0; j < emitters.Length; j++) + { + ParticleSystemUI particleSystemUI = emitters[j]; + ModuleUI[] modules = particleSystemUI.m_Modules; + for (int k = 0; k < modules.Length; k++) + { + ModuleUI moduleUI = modules[k]; + if (moduleUI != null) + { + moduleUI.Validate(); + } + } + } + if (ParticleEffectUI.GetAllModulesVisible()) + { + this.SetAllModulesVisible(true); + } + } + public ParticleSystemUI GetParticleSystemUIForParticleSystem(ParticleSystem shuriken) + { + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + if (particleSystemUI.m_ParticleSystem == shuriken) + { + return particleSystemUI; + } + } + return null; + } + public void PlayOnAwakeChanged(bool newPlayOnAwake) + { + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + InitialModuleUI initialModuleUI = particleSystemUI.m_Modules[0] as InitialModuleUI; + Assert.That(initialModuleUI != null); + initialModuleUI.m_PlayOnAwake.boolValue = newPlayOnAwake; + particleSystemUI.ApplyProperties(); + } + } + public bool ValidateParticleSystemProperty(SerializedProperty shurikenProperty) + { + if (shurikenProperty != null) + { + ParticleSystem particleSystem = shurikenProperty.objectReferenceValue as ParticleSystem; + if (particleSystem != null && this.GetParticleSystemUIForParticleSystem(particleSystem) == null) + { + EditorUtility.DisplayDialog("ParticleSystem Warning", string.Concat(new string[] + { + "The SubEmitter module cannot reference a ParticleSystem that is not a child of the root ParticleSystem.\n\nThe ParticleSystem '", + particleSystem.name, + "' must be a child of the ParticleSystem '", + ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem).name, + "'." + }), "Ok"); + shurikenProperty.objectReferenceValue = null; + return false; + } + } + return true; + } + public GameObject CreateParticleSystem(ParticleSystem parentOfNewParticleSystem, SubModuleUI.SubEmitterType defaultType) + { + string nextParticleSystemName = this.GetNextParticleSystemName(); + GameObject gameObject = new GameObject(nextParticleSystemName, new Type[] + { + typeof(ParticleSystem) + }); + if (gameObject) + { + if (parentOfNewParticleSystem) + { + gameObject.transform.parent = parentOfNewParticleSystem.transform; + } + gameObject.transform.localPosition = Vector3.zero; + gameObject.transform.localRotation = Quaternion.identity; + ParticleSystem component = gameObject.GetComponent(); + if (defaultType != SubModuleUI.SubEmitterType.None) + { + component.SetupDefaultType((int)defaultType); + } + InspectorState.SetFloat("CurrentEmitterAreaScroll", this.m_EmitterAreaScrollPos.x); + return gameObject; + } + return null; + } + public List GetParticleSystemUIList(List shurikens) + { + List list = new List(); + foreach (ParticleSystem current in shurikens) + { + ParticleSystemUI particleSystemUIForParticleSystem = this.GetParticleSystemUIForParticleSystem(current); + if (particleSystemUIForParticleSystem != null) + { + list.Add(particleSystemUIForParticleSystem); + } + } + return list; + } + public ParticleSystemCurveEditor GetParticleSystemCurveEditor() + { + return this.m_ParticleSystemCurveEditor; + } + private void DisplayInfo(ParticleSystem s) + { + GUILayout.Label(string.Concat(new object[] + { + "Time: ", + Mathf.Floor(s.time), + ".", + Mathf.Floor(Mathf.Repeat(s.time, 1f) * 10f) + }), new GUILayoutOption[0]); + GUILayout.Label("Particles: " + s.particleCount, new GUILayoutOption[0]); + } + private void SceneViewGUICallback(UnityEngine.Object target, SceneView sceneView) + { + this.PlayStopGUI(); + } + public void OnSceneViewGUI() + { + ParticleSystem root = this.GetRoot(); + if (root && root.gameObject.activeInHierarchy) + { + SceneViewOverlay.Window(ParticleSystemInspector.playBackTitle, new SceneViewOverlay.WindowFunction(this.SceneViewGUICallback), 400, SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle); + } + } + public void OnSceneGUI() + { + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + particleSystemUI.OnSceneGUI(); + } + } + internal void PlayBackTimeGUI(ParticleSystem root) + { + if (root == null) + { + root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + } + EventType type = Event.current.type; + int hotControl = GUIUtility.hotControl; + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + EditorGUI.BeginChangeCheck(); + EditorGUI.kFloatFieldFormatString = ParticleEffectUI.s_Texts.secondsFloatFieldFormatString; + float num = EditorGUILayout.FloatField(ParticleEffectUI.s_Texts.previewTime, ParticleSystemEditorUtils.editorPlaybackTime, new GUILayoutOption[0]); + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + if (EditorGUI.EndChangeCheck()) + { + if (type == EventType.MouseDrag) + { + ParticleSystemEditorUtils.editorIsScrubbing = true; + float editorSimulationSpeed = ParticleSystemEditorUtils.editorSimulationSpeed; + float editorPlaybackTime = ParticleSystemEditorUtils.editorPlaybackTime; + float num2 = num - editorPlaybackTime; + num = editorPlaybackTime + num2 * (0.05f * editorSimulationSpeed); + } + num = Mathf.Max(num, 0f); + ParticleSystemEditorUtils.editorPlaybackTime = num; + if (root.isStopped) + { + root.Play(); + root.Pause(); + } + ParticleSystemEditorUtils.PerformCompleteResimulation(); + } + if (type == EventType.MouseDown && GUIUtility.hotControl != hotControl) + { + this.m_IsDraggingTimeHotControlID = GUIUtility.hotControl; + ParticleSystemEditorUtils.editorIsScrubbing = true; + } + if (this.m_IsDraggingTimeHotControlID != -1 && GUIUtility.hotControl != this.m_IsDraggingTimeHotControlID) + { + this.m_IsDraggingTimeHotControlID = -1; + ParticleSystemEditorUtils.editorIsScrubbing = false; + } + } + private void HandleKeyboardShortcuts(ParticleSystem root) + { + Event current = Event.current; + if (current.type == EventType.KeyDown) + { + int num = 0; + if (current.keyCode == ParticleEffectUI.kPlay.keyCode) + { + if (EditorApplication.isPlaying) + { + this.Stop(); + this.Play(); + } + else + { + if (!ParticleSystemEditorUtils.editorIsPlaying) + { + this.Play(); + } + else + { + this.Pause(); + } + } + current.Use(); + } + else + { + if (current.keyCode == ParticleEffectUI.kStop.keyCode) + { + this.Stop(); + current.Use(); + } + else + { + if (current.keyCode == ParticleEffectUI.kReverse.keyCode) + { + num = -1; + } + else + { + if (current.keyCode == ParticleEffectUI.kForward.keyCode) + { + num = 1; + } + } + } + } + if (num != 0) + { + ParticleSystemEditorUtils.editorIsScrubbing = true; + float editorSimulationSpeed = ParticleSystemEditorUtils.editorSimulationSpeed; + float num2 = ((!current.shift) ? 1f : 3f) * this.m_TimeHelper.deltaTime * ((num <= 0) ? -3f : 3f); + ParticleSystemEditorUtils.editorPlaybackTime = Mathf.Max(0f, ParticleSystemEditorUtils.editorPlaybackTime + num2 * editorSimulationSpeed); + if (root.isStopped) + { + root.Play(); + root.Pause(); + } + ParticleSystemEditorUtils.PerformCompleteResimulation(); + current.Use(); + } + } + if (current.type == EventType.KeyUp && (current.keyCode == ParticleEffectUI.kReverse.keyCode || current.keyCode == ParticleEffectUI.kForward.keyCode)) + { + ParticleSystemEditorUtils.editorIsScrubbing = false; + } + } + internal ParticleSystem GetRoot() + { + return ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + } + internal static bool IsStopped(ParticleSystem root) + { + return !ParticleSystemEditorUtils.editorIsPlaying && !ParticleSystemEditorUtils.editorIsPaused && !ParticleSystemEditorUtils.editorIsScrubbing; + } + internal bool IsPaused() + { + return !this.IsPlaying() && !ParticleEffectUI.IsStopped(this.GetRoot()); + } + internal bool IsPlaying() + { + return ParticleSystemEditorUtils.editorIsPlaying; + } + internal void Play() + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + if (root) + { + root.Play(); + ParticleSystemEditorUtils.editorIsScrubbing = false; + this.m_Owner.Repaint(); + } + } + internal void Pause() + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + if (root) + { + root.Pause(); + ParticleSystemEditorUtils.editorIsScrubbing = true; + this.m_Owner.Repaint(); + } + } + internal void Stop() + { + ParticleSystemEditorUtils.editorIsScrubbing = false; + ParticleSystemEditorUtils.editorPlaybackTime = 0f; + ParticleSystemEditorUtils.StopEffect(); + this.m_Owner.Repaint(); + } + internal void PlayStopGUI() + { + if (ParticleEffectUI.s_Texts == null) + { + ParticleEffectUI.s_Texts = new ParticleEffectUI.Texts(); + } + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + Event current = Event.current; + if (current.type == EventType.Layout) + { + this.m_TimeHelper.Update(); + } + if (!EditorApplication.isPlaying) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + bool flag = ParticleSystemEditorUtils.editorIsPlaying && !ParticleSystemEditorUtils.editorIsPaused; + if (GUILayout.Button((!flag) ? ParticleEffectUI.s_Texts.play : ParticleEffectUI.s_Texts.pause, "ButtonLeft", new GUILayoutOption[0])) + { + if (flag) + { + this.Pause(); + } + else + { + this.Play(); + } + } + if (GUILayout.Button(ParticleEffectUI.s_Texts.stop, "ButtonRight", new GUILayoutOption[0])) + { + this.Stop(); + } + GUILayout.EndHorizontal(); + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + EditorGUI.kFloatFieldFormatString = ParticleEffectUI.s_Texts.secondsFloatFieldFormatString; + ParticleSystemEditorUtils.editorSimulationSpeed = Mathf.Clamp(EditorGUILayout.FloatField(ParticleEffectUI.s_Texts.previewSpeed, ParticleSystemEditorUtils.editorSimulationSpeed, new GUILayoutOption[0]), 0f, 10f); + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + this.PlayBackTimeGUI(root); + } + else + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(ParticleEffectUI.s_Texts.play, new GUILayoutOption[0])) + { + this.Stop(); + this.Play(); + } + if (GUILayout.Button(ParticleEffectUI.s_Texts.stop, new GUILayoutOption[0])) + { + this.Stop(); + } + GUILayout.EndHorizontal(); + } + this.HandleKeyboardShortcuts(root); + } + private void SingleParticleSystemGUI() + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + GUILayout.BeginVertical(ParticleSystemStyles.Get().effectBgStyle, new GUILayoutOption[0]); + ParticleSystemUI particleSystemUIForParticleSystem = this.GetParticleSystemUIForParticleSystem(this.m_SelectedParticleSystem); + if (particleSystemUIForParticleSystem != null) + { + float width = GUIClip.visibleRect.width - 18f; + particleSystemUIForParticleSystem.OnGUI(root, width, false); + } + GUILayout.EndVertical(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + ParticleSystemEditorUtils.editorResimulation = GUILayout.Toggle(ParticleSystemEditorUtils.editorResimulation, ParticleEffectUI.s_Texts.resimulation, EditorStyles.toggle, new GUILayoutOption[0]); + ParticleEffectUI.m_ShowWireframe = GUILayout.Toggle(ParticleEffectUI.m_ShowWireframe, "Wireframe", EditorStyles.toggle, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + this.HandleKeyboardShortcuts(root); + } + private void DrawSelectionMarker(Rect rect) + { + rect.x += 1f; + rect.y += 1f; + rect.width -= 2f; + rect.height -= 2f; + ParticleSystemStyles.Get().selectionMarker.Draw(rect, GUIContent.none, false, true, true, false); + } + private List GetSelectedParticleSystemUIs() + { + List list = new List(); + int[] instanceIDs = Selection.instanceIDs; + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + if (instanceIDs.Contains(particleSystemUI.m_ParticleSystem.gameObject.GetInstanceID())) + { + list.Add(particleSystemUI); + } + } + return list; + } + private void MultiParticleSystemGUI(bool verticalLayout) + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_SelectedParticleSystem); + GUILayout.BeginVertical(ParticleSystemStyles.Get().effectBgStyle, new GUILayoutOption[0]); + this.m_EmitterAreaScrollPos = EditorGUILayout.BeginScrollView(this.m_EmitterAreaScrollPos, new GUILayoutOption[0]); + Rect position = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + this.m_EmitterAreaScrollPos -= EditorGUI.MouseDeltaReader(position, Event.current.alt); + GUILayout.Space(3f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(3f); + Color color = GUI.color; + bool flag = Event.current.type == EventType.Repaint; + bool flag2 = this.IsShowOnlySelectedMode(); + List selectedParticleSystemUIs = this.GetSelectedParticleSystemUIs(); + for (int i = 0; i < this.m_Emitters.Length; i++) + { + if (i != 0) + { + GUILayout.Space(ModuleUI.k_SpaceBetweenModules); + } + bool flag3 = selectedParticleSystemUIs.Contains(this.m_Emitters[i]); + ModuleUI particleSystemRendererModuleUI = this.m_Emitters[i].GetParticleSystemRendererModuleUI(); + if (flag && particleSystemRendererModuleUI != null && !particleSystemRendererModuleUI.enabled) + { + GUI.color = ParticleEffectUI.GetDisabledColor(); + } + if (flag && flag2 && !flag3) + { + GUI.color = ParticleEffectUI.GetDisabledColor(); + } + Rect rect = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + if (flag && flag3 && this.m_Emitters.Length > 1) + { + this.DrawSelectionMarker(rect); + } + this.m_Emitters[i].OnGUI(root, ModuleUI.k_CompactFixedModuleWidth, true); + EditorGUILayout.EndVertical(); + GUI.color = color; + } + GUILayout.Space(5f); + if (GUILayout.Button(ParticleEffectUI.s_Texts.addParticleSystem, "OL Plus", new GUILayoutOption[] + { + GUILayout.Width(20f) + })) + { + this.CreateParticleSystem(root, SubModuleUI.SubEmitterType.None); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.Space(4f); + this.m_EmitterAreaScrollPos -= EditorGUI.MouseDeltaReader(position, true); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndVertical(); + EditorGUILayout.EndScrollView(); + GUILayout.EndVertical(); + this.HandleKeyboardShortcuts(root); + } + private void WindowCurveEditorGUI(bool verticalLayout) + { + Rect rect; + if (verticalLayout) + { + rect = GUILayoutUtility.GetRect(13f, this.m_CurveEditorAreaHeight, new GUILayoutOption[] + { + GUILayout.MinHeight(this.m_CurveEditorAreaHeight) + }); + } + else + { + EditorWindow editorWindow = (EditorWindow)this.m_Owner; + Assert.That(editorWindow != null); + rect = GUILayoutUtility.GetRect(editorWindow.position.width - this.m_EmitterAreaWidth, editorWindow.position.height - 17f); + } + this.ResizeHandling(verticalLayout); + this.m_ParticleSystemCurveEditor.OnGUI(rect); + } + private Rect ResizeHandling(bool verticalLayout) + { + Rect lastRect; + if (verticalLayout) + { + lastRect = GUILayoutUtility.GetLastRect(); + lastRect.y += -5f; + lastRect.height = 5f; + float y = EditorGUI.MouseDeltaReader(lastRect, true).y; + if (y != 0f) + { + this.m_CurveEditorAreaHeight -= y; + this.ClampWindowContentSizes(); + EditorPrefs.SetFloat("ParticleSystemCurveEditorAreaHeight", this.m_CurveEditorAreaHeight); + } + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.SplitResizeUpDown); + } + } + else + { + lastRect = new Rect(this.m_EmitterAreaWidth - 5f, 0f, 5f, GUIClip.visibleRect.height); + float x = EditorGUI.MouseDeltaReader(lastRect, true).x; + if (x != 0f) + { + this.m_EmitterAreaWidth += x; + this.ClampWindowContentSizes(); + EditorPrefs.SetFloat("ParticleSystemEmitterAreaWidth", this.m_EmitterAreaWidth); + } + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.SplitResizeLeftRight); + } + } + return lastRect; + } + private void ClampWindowContentSizes() + { + EventType type = Event.current.type; + if (type != EventType.Layout) + { + float width = GUIClip.visibleRect.width; + float height = GUIClip.visibleRect.height; + bool verticalLayout = ParticleEffectUI.m_VerticalLayout; + if (verticalLayout) + { + this.m_CurveEditorAreaHeight = Mathf.Clamp(this.m_CurveEditorAreaHeight, ParticleEffectUI.k_MinCurveAreaSize.y, height - ParticleEffectUI.k_MinEmitterAreaSize.y); + } + else + { + this.m_EmitterAreaWidth = Mathf.Clamp(this.m_EmitterAreaWidth, ParticleEffectUI.k_MinEmitterAreaSize.x, width - ParticleEffectUI.k_MinCurveAreaSize.x); + } + } + } + public void OnGUI() + { + if (ParticleEffectUI.s_Texts == null) + { + ParticleEffectUI.s_Texts = new ParticleEffectUI.Texts(); + } + if (this.m_Emitters == null) + { + return; + } + this.UpdateProperties(); + ParticleEffectUI.OwnerType ownerType = (!(this.m_Owner is ParticleSystemInspector)) ? ParticleEffectUI.OwnerType.ParticleSystemWindow : ParticleEffectUI.OwnerType.Inspector; + ParticleEffectUI.OwnerType ownerType2 = ownerType; + if (ownerType2 != ParticleEffectUI.OwnerType.Inspector) + { + if (ownerType2 != ParticleEffectUI.OwnerType.ParticleSystemWindow) + { + Debug.LogError("Unhandled enum"); + } + else + { + this.ClampWindowContentSizes(); + bool verticalLayout = ParticleEffectUI.m_VerticalLayout; + if (verticalLayout) + { + this.MultiParticleSystemGUI(verticalLayout); + this.WindowCurveEditorGUI(verticalLayout); + } + else + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.MultiParticleSystemGUI(verticalLayout); + this.WindowCurveEditorGUI(verticalLayout); + GUILayout.EndHorizontal(); + } + } + } + else + { + this.SingleParticleSystemGUI(); + } + this.ApplyModifiedProperties(); + } + private void ApplyModifiedProperties() + { + for (int i = 0; i < this.m_Emitters.Length; i++) + { + this.m_Emitters[i].ApplyProperties(); + } + } + internal void UpdateProperties() + { + for (int i = 0; i < this.m_Emitters.Length; i++) + { + this.m_Emitters[i].UpdateProperties(); + } + } + internal bool IsPlayOnAwake() + { + if (this.m_Emitters.Length > 0) + { + InitialModuleUI initialModuleUI = this.m_Emitters[0].m_Modules[0] as InitialModuleUI; + return initialModuleUI.m_PlayOnAwake.boolValue; + } + return false; + } + internal GameObject[] GetParticleSystemGameObjects() + { + List list = new List(); + for (int i = 0; i < this.m_Emitters.Length; i++) + { + list.Add(this.m_Emitters[i].m_ParticleSystem.gameObject); + } + return list.ToArray(); + } + internal static bool GetAllModulesVisible() + { + return EditorPrefs.GetBool("ParticleSystemShowAllModules", true); + } + internal void SetAllModulesVisible(bool showAll) + { + EditorPrefs.SetBool("ParticleSystemShowAllModules", showAll); + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + for (int j = 0; j < particleSystemUI.m_Modules.Length; j++) + { + ModuleUI moduleUI = particleSystemUI.m_Modules[j]; + if (moduleUI != null) + { + if (showAll) + { + if (!moduleUI.visibleUI) + { + moduleUI.visibleUI = true; + } + } + else + { + bool flag = true; + if (moduleUI is RendererModuleUI && particleSystemUI.GetParticleSystemRenderer() != null) + { + flag = false; + } + if (flag && !moduleUI.enabled) + { + moduleUI.visibleUI = false; + } + } + } + } + } + } + internal int GetNumEnabledRenderers() + { + int num = 0; + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + ModuleUI particleSystemRendererModuleUI = particleSystemUI.GetParticleSystemRendererModuleUI(); + if (particleSystemRendererModuleUI != null && particleSystemRendererModuleUI.enabled) + { + num++; + } + } + return num; + } + internal bool IsShowOnlySelectedMode() + { + return this.m_ShowOnlySelectedMode; + } + internal void SetShowOnlySelectedMode(bool enable) + { + this.m_ShowOnlySelectedMode = enable; + this.RefreshShowOnlySelected(); + } + internal void RefreshShowOnlySelected() + { + if (this.IsShowOnlySelectedMode()) + { + int[] instanceIDs = Selection.instanceIDs; + ParticleSystemUI[] emitters = this.m_Emitters; + for (int i = 0; i < emitters.Length; i++) + { + ParticleSystemUI particleSystemUI = emitters[i]; + ParticleSystemRenderer particleSystemRenderer = particleSystemUI.GetParticleSystemRenderer(); + if (particleSystemRenderer != null) + { + particleSystemRenderer.editorEnabled = instanceIDs.Contains(particleSystemUI.m_ParticleSystem.gameObject.GetInstanceID()); + } + } + } + else + { + ParticleSystemUI[] emitters2 = this.m_Emitters; + for (int j = 0; j < emitters2.Length; j++) + { + ParticleSystemUI particleSystemUI2 = emitters2[j]; + ParticleSystemRenderer particleSystemRenderer2 = particleSystemUI2.GetParticleSystemRenderer(); + if (particleSystemRenderer2 != null) + { + particleSystemRenderer2.editorEnabled = true; + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleEffectUIOwner.cs b/UnityEditor/UnityEditor/ParticleEffectUIOwner.cs new file mode 100644 index 00000000..c7436af4 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleEffectUIOwner.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + internal interface ParticleEffectUIOwner + { + void Repaint(); + } +} diff --git a/UnityEditor/UnityEditor/ParticleEffectUtils.cs b/UnityEditor/UnityEditor/ParticleEffectUtils.cs new file mode 100644 index 00000000..a930b26b --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleEffectUtils.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleEffectUtils + { + private static List s_Planes = new List(); + public static GameObject GetPlane(int index) + { + while (ParticleEffectUtils.s_Planes.Count <= index) + { + GameObject gameObject = GameObject.CreatePrimitive(PrimitiveType.Plane); + gameObject.hideFlags = HideFlags.HideAndDontSave; + ParticleEffectUtils.s_Planes.Add(gameObject); + } + return ParticleEffectUtils.s_Planes[index]; + } + public static void ClearPlanes() + { + if (ParticleEffectUtils.s_Planes.Count > 0) + { + foreach (GameObject current in ParticleEffectUtils.s_Planes) + { + UnityEngine.Object.DestroyImmediate(current); + } + ParticleEffectUtils.s_Planes.Clear(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemClipboard.cs b/UnityEditor/UnityEditor/ParticleSystemClipboard.cs new file mode 100644 index 00000000..795a5b05 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemClipboard.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleSystemClipboard + { + private static AnimationCurve m_AnimationCurve1; + private static AnimationCurve m_AnimationCurve2; + private static float m_AnimationCurveScalar; + private static Gradient m_Gradient1; + private static Gradient m_Gradient2; + public static bool HasSingleGradient() + { + return ParticleSystemClipboard.m_Gradient1 != null && ParticleSystemClipboard.m_Gradient2 == null; + } + public static bool HasDoubleGradient() + { + return ParticleSystemClipboard.m_Gradient1 != null && ParticleSystemClipboard.m_Gradient2 != null; + } + public static void CopyGradient(Gradient gradient1, Gradient gradient2) + { + ParticleSystemClipboard.m_Gradient1 = gradient1; + ParticleSystemClipboard.m_Gradient2 = gradient2; + } + public static void PasteGradient(SerializedProperty gradientProperty, SerializedProperty gradientProperty2) + { + if (gradientProperty != null && ParticleSystemClipboard.m_Gradient1 != null) + { + gradientProperty.gradientValue = ParticleSystemClipboard.m_Gradient1; + } + if (gradientProperty2 != null && ParticleSystemClipboard.m_Gradient2 != null) + { + gradientProperty2.gradientValue = ParticleSystemClipboard.m_Gradient2; + } + } + public static bool HasSingleAnimationCurve() + { + return ParticleSystemClipboard.m_AnimationCurve1 != null && ParticleSystemClipboard.m_AnimationCurve2 == null; + } + public static bool HasDoubleAnimationCurve() + { + return ParticleSystemClipboard.m_AnimationCurve1 != null && ParticleSystemClipboard.m_AnimationCurve2 != null; + } + public static void CopyAnimationCurves(AnimationCurve animCurve, AnimationCurve animCurve2, float scalar) + { + ParticleSystemClipboard.m_AnimationCurve1 = animCurve; + ParticleSystemClipboard.m_AnimationCurve2 = animCurve2; + ParticleSystemClipboard.m_AnimationCurveScalar = scalar; + } + private static void ClampCurve(SerializedProperty animCurveProperty, Rect curveRanges) + { + AnimationCurve animationCurveValue = animCurveProperty.animationCurveValue; + Keyframe[] keys = animationCurveValue.keys; + for (int i = 0; i < keys.Length; i++) + { + keys[i].time = Mathf.Clamp(keys[i].time, curveRanges.xMin, curveRanges.xMax); + keys[i].value = Mathf.Clamp(keys[i].value, curveRanges.yMin, curveRanges.yMax); + } + animationCurveValue.keys = keys; + animCurveProperty.animationCurveValue = animationCurveValue; + } + public static void PasteAnimationCurves(SerializedProperty animCurveProperty, SerializedProperty animCurveProperty2, SerializedProperty scalarProperty, Rect curveRanges, ParticleSystemCurveEditor particleSystemCurveEditor) + { + if (animCurveProperty != null && ParticleSystemClipboard.m_AnimationCurve1 != null) + { + animCurveProperty.animationCurveValue = ParticleSystemClipboard.m_AnimationCurve1; + ParticleSystemClipboard.ClampCurve(animCurveProperty, curveRanges); + } + if (animCurveProperty2 != null && ParticleSystemClipboard.m_AnimationCurve2 != null) + { + animCurveProperty2.animationCurveValue = ParticleSystemClipboard.m_AnimationCurve2; + ParticleSystemClipboard.ClampCurve(animCurveProperty2, curveRanges); + } + if (scalarProperty != null) + { + scalarProperty.floatValue = ParticleSystemClipboard.m_AnimationCurveScalar; + } + if (particleSystemCurveEditor != null) + { + particleSystemCurveEditor.Refresh(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemEditorUtils.cs b/UnityEditor/UnityEditor/ParticleSystemEditorUtils.cs new file mode 100644 index 00000000..aad9a06b --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemEditorUtils.cs @@ -0,0 +1,117 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + internal sealed class ParticleSystemEditorUtils + { + internal static extern float editorSimulationSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern float editorPlaybackTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool editorIsScrubbing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool editorIsPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool editorIsPaused + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool editorResimulation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool editorUpdateAll + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern ParticleSystem lockedParticleSystem + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string CheckCircularReferences(ParticleSystem subEmitter, ParticleSystem subEmitterParent, ParticleSystem root); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void PerformCompleteResimulation(); + public static ParticleSystem GetRoot(ParticleSystem ps) + { + if (ps == null) + { + return null; + } + Transform transform = ps.transform; + while (transform.parent && transform.parent.gameObject.GetComponent() != null) + { + transform = transform.parent; + } + return transform.gameObject.GetComponent(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void StopEffect([DefaultValue("true")] bool stop, [DefaultValue("true")] bool clear); + [ExcludeFromDocs] + internal static void StopEffect(bool stop) + { + bool clear = true; + ParticleSystemEditorUtils.StopEffect(stop, clear); + } + [ExcludeFromDocs] + internal static void StopEffect() + { + bool clear = true; + bool stop = true; + ParticleSystemEditorUtils.StopEffect(stop, clear); + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemInspector.cs b/UnityEditor/UnityEditor/ParticleSystemInspector.cs new file mode 100644 index 00000000..79cf67c1 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemInspector.cs @@ -0,0 +1,206 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(ParticleSystem))] + internal class ParticleSystemInspector : Editor, ParticleEffectUIOwner + { + private ParticleEffectUI m_ParticleEffectUI; + private GUIContent m_PreviewTitle = new GUIContent("Particle System Curves"); + private GUIContent showWindowText = new GUIContent("Open Editor..."); + private GUIContent closeWindowText = new GUIContent("Close Editor"); + private GUIContent hideWindowText = new GUIContent("Hide Editor"); + private static GUIContent m_PlayBackTitle; + public static GUIContent playBackTitle + { + get + { + if (ParticleSystemInspector.m_PlayBackTitle == null) + { + ParticleSystemInspector.m_PlayBackTitle = new GUIContent("Particle Effect"); + } + return ParticleSystemInspector.m_PlayBackTitle; + } + } + public void OnEnable() + { + EditorApplication.hierarchyWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.hierarchyWindowChanged, new EditorApplication.CallbackFunction(this.HierarchyOrProjectWindowWasChanged)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.HierarchyOrProjectWindowWasChanged)); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public void OnDisable() + { + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.HierarchyOrProjectWindowWasChanged)); + EditorApplication.hierarchyWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.hierarchyWindowChanged, new EditorApplication.CallbackFunction(this.HierarchyOrProjectWindowWasChanged)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Clear(); + } + } + private void HierarchyOrProjectWindowWasChanged() + { + if (this.ShouldShowInspector()) + { + this.Init(true); + } + } + private void UndoRedoPerformed() + { + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.UndoRedoPerformed(); + } + } + private void Init(bool forceInit) + { + ParticleSystem particleSystem = this.target as ParticleSystem; + if (particleSystem == null) + { + return; + } + if (this.m_ParticleEffectUI == null) + { + this.m_ParticleEffectUI = new ParticleEffectUI(this); + this.m_ParticleEffectUI.InitializeIfNeeded(particleSystem); + } + else + { + if (forceInit) + { + this.m_ParticleEffectUI.InitializeIfNeeded(particleSystem); + } + } + } + private void ShowEdiorButtonGUI() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + ParticleSystemWindow instance = ParticleSystemWindow.GetInstance(); + GUIContent content; + if (instance && instance.IsVisible()) + { + if (instance.GetNumTabs() > 1) + { + content = this.hideWindowText; + } + else + { + content = this.closeWindowText; + } + } + else + { + content = this.showWindowText; + } + if (GUILayout.Button(content, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.Width(110f) + })) + { + if (instance) + { + if (instance.IsVisible()) + { + if (!instance.ShowNextTabIfPossible()) + { + instance.Close(); + } + } + else + { + instance.Focus(); + } + } + else + { + this.Clear(); + ParticleSystemWindow.CreateWindow(); + GUIUtility.ExitGUI(); + } + } + GUILayout.EndHorizontal(); + } + public override bool UseDefaultMargins() + { + return false; + } + public override void OnInspectorGUI() + { + EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + this.ShowEdiorButtonGUI(); + if (this.ShouldShowInspector()) + { + if (this.m_ParticleEffectUI == null) + { + this.Init(true); + } + EditorGUILayout.EndVertical(); + EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins, new GUILayoutOption[0]); + this.m_ParticleEffectUI.OnGUI(); + EditorGUILayout.EndVertical(); + EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + } + else + { + this.Clear(); + } + EditorGUILayout.EndVertical(); + } + private void Clear() + { + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Clear(); + } + this.m_ParticleEffectUI = null; + } + private bool ShouldShowInspector() + { + ParticleSystemWindow instance = ParticleSystemWindow.GetInstance(); + return !instance || !instance.IsVisible(); + } + public void OnSceneGUI() + { + if (this.ShouldShowInspector() && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.OnSceneGUI(); + } + } + public void OnSceneViewGUI(SceneView sceneView) + { + if (this.ShouldShowInspector()) + { + this.Init(false); + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.OnSceneViewGUI(); + } + } + } + public override bool HasPreviewGUI() + { + return this.ShouldShowInspector() && Selection.objects.Length == 1; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.GetParticleSystemCurveEditor().OnGUI(r); + } + } + public override GUIContent GetPreviewTitle() + { + return this.m_PreviewTitle; + } + public override void OnPreviewSettings() + { + } + virtual void Repaint() + { + base.Repaint(); + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemStyles.cs b/UnityEditor/UnityEditor/ParticleSystemStyles.cs new file mode 100644 index 00000000..e23db9a6 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemStyles.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleSystemStyles + { + private static ParticleSystemStyles s_ParticleSystemStyles; + public GUIStyle label = ParticleSystemStyles.FindStyle("ShurikenLabel"); + public GUIStyle numberField = ParticleSystemStyles.FindStyle("ShurikenValue"); + public GUIStyle objectField = ParticleSystemStyles.FindStyle("ShurikenObjectField"); + public GUIStyle effectBgStyle = ParticleSystemStyles.FindStyle("ShurikenEffectBg"); + public GUIStyle emitterHeaderStyle = ParticleSystemStyles.FindStyle("ShurikenEmitterTitle"); + public GUIStyle moduleHeaderStyle = ParticleSystemStyles.FindStyle("ShurikenModuleTitle"); + public GUIStyle moduleBgStyle = ParticleSystemStyles.FindStyle("ShurikenModuleBg"); + public GUIStyle plus = ParticleSystemStyles.FindStyle("ShurikenPlus"); + public GUIStyle minus = ParticleSystemStyles.FindStyle("ShurikenMinus"); + public GUIStyle line = ParticleSystemStyles.FindStyle("ShurikenLine"); + public GUIStyle checkmark = ParticleSystemStyles.FindStyle("ShurikenCheckMark"); + public GUIStyle minMaxCurveStateDropDown = ParticleSystemStyles.FindStyle("ShurikenDropdown"); + public GUIStyle toggle = ParticleSystemStyles.FindStyle("ShurikenToggle"); + public GUIStyle popup = ParticleSystemStyles.FindStyle("ShurikenPopUp"); + public GUIStyle selectionMarker = ParticleSystemStyles.FindStyle("IN ThumbnailShadow"); + public GUIStyle toolbarButtonLeftAlignText = new GUIStyle(ParticleSystemStyles.FindStyle("ToolbarButton")); + public GUIStyle modulePadding = new GUIStyle(); + public Texture2D warningIcon; + private ParticleSystemStyles() + { + this.emitterHeaderStyle.clipping = TextClipping.Clip; + this.emitterHeaderStyle.padding.right = 45; + this.warningIcon = EditorGUIUtility.LoadIcon("console.infoicon.sml"); + this.toolbarButtonLeftAlignText.alignment = TextAnchor.MiddleLeft; + this.modulePadding.padding = new RectOffset(3, 3, 4, 2); + } + public static ParticleSystemStyles Get() + { + if (ParticleSystemStyles.s_ParticleSystemStyles == null) + { + ParticleSystemStyles.s_ParticleSystemStyles = new ParticleSystemStyles(); + } + return ParticleSystemStyles.s_ParticleSystemStyles; + } + private static GUIStyle FindStyle(string styleName) + { + return styleName; + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemUI.cs b/UnityEditor/UnityEditor/ParticleSystemUI.cs new file mode 100644 index 00000000..f1dd93ac --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemUI.cs @@ -0,0 +1,599 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleSystemUI + { + public enum DefaultTypes + { + Root, + SubBirth, + SubCollision, + SubDeath + } + protected class Texts + { + public GUIContent addModules = new GUIContent(string.Empty, "Show/Hide Modules"); + public GUIContent supportsCullingText = new GUIContent(string.Empty, ParticleSystemStyles.Get().warningIcon); + } + public ParticleEffectUI m_ParticleEffectUI; + public ModuleUI[] m_Modules; + public ParticleSystem m_ParticleSystem; + public SerializedObject m_ParticleSystemSerializedObject; + public SerializedObject m_RendererSerializedObject; + private static string[] s_ModuleNames; + private static string m_SupportsCullingText; + private static ParticleSystemUI.Texts s_Texts; + public void Init(ParticleEffectUI owner, ParticleSystem ps) + { + if (ParticleSystemUI.s_ModuleNames == null) + { + ParticleSystemUI.s_ModuleNames = ParticleSystemUI.GetUIModuleNames(); + } + this.m_ParticleEffectUI = owner; + this.m_ParticleSystem = ps; + this.m_ParticleSystemSerializedObject = new SerializedObject(this.m_ParticleSystem); + this.m_RendererSerializedObject = null; + ParticleSystemUI.m_SupportsCullingText = null; + this.m_Modules = ParticleSystemUI.CreateUIModules(this, this.m_ParticleSystemSerializedObject); + ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); + if (particleSystemRenderer != null) + { + this.InitRendererUI(); + } + this.UpdateParticleSystemInfoString(); + } + internal ParticleSystemRenderer GetParticleSystemRenderer() + { + if (this.m_ParticleSystem != null) + { + return this.m_ParticleSystem.GetComponent(); + } + return null; + } + internal ModuleUI GetParticleSystemRendererModuleUI() + { + return this.m_Modules[this.m_Modules.Length - 1]; + } + private void InitRendererUI() + { + ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); + if (particleSystemRenderer == null) + { + this.m_ParticleSystem.gameObject.AddComponent("ParticleSystemRenderer"); + } + particleSystemRenderer = this.GetParticleSystemRenderer(); + if (particleSystemRenderer != null) + { + Assert.That(this.m_Modules[this.m_Modules.Length - 1] == null); + this.m_RendererSerializedObject = new SerializedObject(particleSystemRenderer); + this.m_Modules[this.m_Modules.Length - 1] = new RendererModuleUI(this, this.m_RendererSerializedObject, ParticleSystemUI.s_ModuleNames[ParticleSystemUI.s_ModuleNames.Length - 1]); + EditorUtility.SetSelectedWireframeHidden(particleSystemRenderer, !ParticleEffectUI.m_ShowWireframe); + } + } + private void ClearRenderer() + { + this.m_RendererSerializedObject = null; + ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); + if (particleSystemRenderer != null) + { + Undo.DestroyObjectImmediate(particleSystemRenderer); + } + this.m_Modules[this.m_Modules.Length - 1] = null; + } + public string GetName() + { + return this.m_ParticleSystem.gameObject.name; + } + public float GetEmitterDuration() + { + InitialModuleUI initialModuleUI = this.m_Modules[0] as InitialModuleUI; + if (initialModuleUI != null) + { + return initialModuleUI.m_LengthInSec.floatValue; + } + return -1f; + } + private ParticleSystem GetSelectedParticleSystem() + { + return Selection.activeGameObject.GetComponent(); + } + public void OnGUI(ParticleSystem root, float width, bool fixedWidth) + { + if (ParticleSystemUI.s_Texts == null) + { + ParticleSystemUI.s_Texts = new ParticleSystemUI.Texts(); + } + bool flag = Event.current.type == EventType.Repaint; + string text = (!this.m_ParticleSystem) ? null : this.m_ParticleSystem.gameObject.name; + if (fixedWidth) + { + EditorGUIUtility.labelWidth = width * 0.55f; + EditorGUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(width) + }); + } + else + { + EditorGUIUtility.labelWidth = 0f; + EditorGUIUtility.labelWidth -= 4f; + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + } + for (int i = 0; i < this.m_Modules.Length; i++) + { + ModuleUI moduleUI = this.m_Modules[i]; + if (moduleUI != null) + { + bool flag2 = moduleUI == this.m_Modules[0]; + if (moduleUI.visibleUI || flag2) + { + GUIContent gUIContent = new GUIContent(); + Rect rect; + GUIStyle style; + if (flag2) + { + rect = GUILayoutUtility.GetRect(width, 25f); + style = ParticleSystemStyles.Get().emitterHeaderStyle; + } + else + { + rect = GUILayoutUtility.GetRect(width, 15f); + style = ParticleSystemStyles.Get().moduleHeaderStyle; + } + if (moduleUI.foldout) + { + EditorGUI.BeginDisabledGroup(!moduleUI.enabled); + Rect position = EditorGUILayout.BeginVertical(ParticleSystemStyles.Get().modulePadding, new GUILayoutOption[0]); + position.y -= 4f; + position.height += 4f; + GUI.Label(position, GUIContent.none, ParticleSystemStyles.Get().moduleBgStyle); + moduleUI.OnInspectorGUI(this.m_ParticleSystem); + EditorGUILayout.EndVertical(); + EditorGUI.EndDisabledGroup(); + } + if (flag2) + { + ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); + float num = 21f; + Rect position2 = new Rect(rect.x + 4f, rect.y + 2f, num, num); + if (flag && particleSystemRenderer != null) + { + bool flag3 = false; + int num2 = 0; + RendererModuleUI rendererModuleUI = this.m_Modules[this.m_Modules.Length - 1] as RendererModuleUI; + if (rendererModuleUI != null) + { + if (rendererModuleUI.IsMeshEmitter()) + { + if (particleSystemRenderer.mesh != null) + { + num2 = particleSystemRenderer.mesh.GetInstanceID(); + } + } + else + { + if (particleSystemRenderer.sharedMaterial != null) + { + num2 = particleSystemRenderer.sharedMaterial.GetInstanceID(); + } + } + if (EditorUtility.IsDirty(num2)) + { + AssetPreview.ClearTemporaryAssetPreviews(); + } + } + if (num2 != 0) + { + Texture2D assetPreview = AssetPreview.GetAssetPreview(num2); + if (assetPreview != null) + { + GUI.DrawTexture(position2, assetPreview, ScaleMode.StretchToFill, true); + flag3 = true; + } + } + if (!flag3) + { + GUI.Label(position2, GUIContent.none, ParticleSystemStyles.Get().moduleBgStyle); + } + } + if (EditorGUI.ButtonMouseDown(position2, GUIContent.none, FocusType.Passive, GUIStyle.none)) + { + if (EditorGUI.actionKey) + { + List list = new List(); + int instanceID = this.m_ParticleSystem.gameObject.GetInstanceID(); + list.AddRange(Selection.instanceIDs); + if (!list.Contains(instanceID) || list.Count != 1) + { + if (list.Contains(instanceID)) + { + list.Remove(instanceID); + } + else + { + list.Add(instanceID); + } + } + Selection.instanceIDs = list.ToArray(); + } + else + { + Selection.instanceIDs = new int[0]; + Selection.activeInstanceID = this.m_ParticleSystem.gameObject.GetInstanceID(); + } + } + } + Rect position3 = new Rect(rect.x + 2f, rect.y + 1f, 13f, 13f); + if (!flag2 && GUI.Button(position3, GUIContent.none, GUIStyle.none)) + { + moduleUI.enabled = !moduleUI.enabled; + } + Rect position4 = new Rect(rect.x + rect.width - 10f, rect.y + rect.height - 10f, 10f, 10f); + Rect position5 = new Rect(position4.x - 4f, position4.y - 4f, position4.width + 4f, position4.height + 4f); + Rect position6 = new Rect(position4.x - 23f, position4.y - 3f, 16f, 16f); + if (flag2 && EditorGUI.ButtonMouseDown(position5, ParticleSystemUI.s_Texts.addModules, FocusType.Passive, GUIStyle.none)) + { + this.ShowAddModuleMenu(); + } + if (!string.IsNullOrEmpty(text)) + { + gUIContent.text = ((!flag2) ? moduleUI.displayName : text); + } + else + { + gUIContent.text = moduleUI.displayName; + } + gUIContent.tooltip = moduleUI.toolTip; + bool flag4 = GUI.Toggle(rect, moduleUI.foldout, gUIContent, style); + if (flag4 != moduleUI.foldout) + { + int button = Event.current.button; + if (button != 0) + { + if (button == 1) + { + if (flag2) + { + this.ShowEmitterMenu(); + } + else + { + this.ShowModuleMenu(i); + } + } + } + else + { + bool foldout = !moduleUI.foldout; + if (Event.current.control) + { + ModuleUI[] modules = this.m_Modules; + for (int j = 0; j < modules.Length; j++) + { + ModuleUI moduleUI2 = modules[j]; + if (moduleUI2 != null && moduleUI2.visibleUI) + { + moduleUI2.foldout = foldout; + } + } + } + else + { + moduleUI.foldout = foldout; + } + } + } + if (!flag2) + { + GUI.Toggle(position3, moduleUI.enabled, GUIContent.none, ParticleSystemStyles.Get().checkmark); + } + if (flag && flag2) + { + GUI.Label(position4, GUIContent.none, ParticleSystemStyles.Get().plus); + } + ParticleSystemUI.s_Texts.supportsCullingText.tooltip = ParticleSystemUI.m_SupportsCullingText; + if (flag2 && ParticleSystemUI.s_Texts.supportsCullingText.tooltip != null) + { + GUI.Label(position6, ParticleSystemUI.s_Texts.supportsCullingText); + } + GUILayout.Space(1f); + } + } + } + GUILayout.Space(-1f); + EditorGUILayout.EndVertical(); + this.ApplyProperties(); + } + public void OnSceneGUI() + { + if (this.m_Modules == null || this.m_ParticleSystem == null) + { + return; + } + if (this.m_ParticleSystem.particleCount > 0) + { + ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); + EditorUtility.SetSelectedWireframeHidden(particleSystemRenderer, !ParticleEffectUI.m_ShowWireframe); + if (ParticleEffectUI.m_ShowWireframe) + { + ModuleUI particleSystemRendererModuleUI = this.GetParticleSystemRendererModuleUI(); + ParticleSystemRenderer particleSystemRenderer2 = this.GetParticleSystemRenderer(); + if (particleSystemRendererModuleUI != null && particleSystemRendererModuleUI.enabled && particleSystemRenderer2.editorEnabled) + { + Vector3 extents = particleSystemRenderer.bounds.extents; + Transform transform = Camera.current.transform; + Vector2 size = new Vector2(0f, 0f); + Vector3[] array = new Vector3[] + { + new Vector3(-1f, -1f, -1f), + new Vector3(-1f, -1f, 1f), + new Vector3(-1f, 1f, -1f), + new Vector3(-1f, 1f, 1f), + new Vector3(1f, -1f, -1f), + new Vector3(1f, -1f, 1f), + new Vector3(1f, 1f, -1f), + new Vector3(1f, 1f, 1f) + }; + for (int i = 0; i < 8; i++) + { + size.x = Mathf.Max(size.x, Vector3.Dot(Vector3.Scale(array[i], extents), transform.right)); + size.y = Mathf.Max(size.y, Vector3.Dot(Vector3.Scale(array[i], extents), transform.up)); + } + Handles.RectangleCap(0, particleSystemRenderer.bounds.center, Camera.current.transform.rotation, size); + } + } + } + this.UpdateProperties(); + InitialModuleUI initial = (InitialModuleUI)this.m_Modules[0]; + ModuleUI[] modules = this.m_Modules; + for (int j = 0; j < modules.Length; j++) + { + ModuleUI moduleUI = modules[j]; + if (moduleUI != null && moduleUI.visibleUI && moduleUI.enabled) + { + if (moduleUI.foldout) + { + moduleUI.OnSceneGUI(this.m_ParticleSystem, initial); + } + } + } + this.ApplyProperties(); + } + public void ApplyProperties() + { + bool hasModifiedProperties = this.m_ParticleSystemSerializedObject.hasModifiedProperties; + this.m_ParticleSystemSerializedObject.ApplyModifiedProperties(); + if (hasModifiedProperties) + { + ParticleSystem root = ParticleSystemEditorUtils.GetRoot(this.m_ParticleSystem); + if (!ParticleEffectUI.IsStopped(root) && ParticleSystemEditorUtils.editorResimulation) + { + ParticleSystemEditorUtils.PerformCompleteResimulation(); + } + this.UpdateParticleSystemInfoString(); + } + if (this.m_RendererSerializedObject != null) + { + this.m_RendererSerializedObject.ApplyModifiedProperties(); + } + } + private void UpdateParticleSystemInfoString() + { + string empty = string.Empty; + ModuleUI[] modules = this.m_Modules; + for (int i = 0; i < modules.Length; i++) + { + ModuleUI moduleUI = modules[i]; + if (moduleUI != null && moduleUI.visibleUI && moduleUI.enabled) + { + moduleUI.UpdateCullingSupportedString(ref empty); + } + } + if (empty != string.Empty) + { + ParticleSystemUI.m_SupportsCullingText = "Automatic culling is disabled because: " + empty; + } + else + { + ParticleSystemUI.m_SupportsCullingText = null; + } + } + public void UpdateProperties() + { + this.m_ParticleSystemSerializedObject.UpdateIfDirtyOrScript(); + if (this.m_RendererSerializedObject != null) + { + this.m_RendererSerializedObject.UpdateIfDirtyOrScript(); + } + } + private void ResetModules() + { + ModuleUI[] modules = this.m_Modules; + for (int i = 0; i < modules.Length; i++) + { + ModuleUI moduleUI = modules[i]; + if (moduleUI != null) + { + moduleUI.enabled = false; + if (!ParticleEffectUI.GetAllModulesVisible()) + { + moduleUI.visibleUI = false; + } + } + } + if (this.m_Modules[this.m_Modules.Length - 1] == null) + { + this.InitRendererUI(); + } + int[] array = new int[] + { + 1, + 2, + this.m_Modules.Length - 1 + }; + for (int j = 0; j < array.Length; j++) + { + int num = array[j]; + if (this.m_Modules[num] != null) + { + this.m_Modules[num].enabled = true; + this.m_Modules[num].visibleUI = true; + } + } + } + private void ShowAddModuleMenu() + { + GenericMenu genericMenu = new GenericMenu(); + for (int i = 0; i < ParticleSystemUI.s_ModuleNames.Length; i++) + { + if (this.m_Modules[i] == null || !this.m_Modules[i].visibleUI) + { + genericMenu.AddItem(new GUIContent(ParticleSystemUI.s_ModuleNames[i]), false, new GenericMenu.MenuFunction2(this.AddModuleCallback), i); + } + else + { + genericMenu.AddDisabledItem(new GUIContent(ParticleSystemUI.s_ModuleNames[i])); + } + } + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Show All Modules"), ParticleEffectUI.GetAllModulesVisible(), new GenericMenu.MenuFunction2(this.AddModuleCallback), 10000); + genericMenu.ShowAsContext(); + Event.current.Use(); + } + private void AddModuleCallback(object obj) + { + int num = (int)obj; + if (num >= 0 && num < this.m_Modules.Length) + { + if (num == this.m_Modules.Length - 1) + { + this.InitRendererUI(); + } + else + { + this.m_Modules[num].enabled = true; + this.m_Modules[num].foldout = true; + } + } + else + { + this.m_ParticleEffectUI.SetAllModulesVisible(!ParticleEffectUI.GetAllModulesVisible()); + } + this.ApplyProperties(); + } + private void ModuleMenuCallback(object obj) + { + int num = (int)obj; + bool flag = num == this.m_Modules.Length - 1; + if (flag) + { + this.ClearRenderer(); + } + else + { + if (!ParticleEffectUI.GetAllModulesVisible()) + { + this.m_Modules[num].visibleUI = false; + } + this.m_Modules[num].enabled = false; + } + } + private void ShowModuleMenu(int moduleIndex) + { + GenericMenu genericMenu = new GenericMenu(); + if (!ParticleEffectUI.GetAllModulesVisible()) + { + genericMenu.AddItem(new GUIContent("Remove"), false, new GenericMenu.MenuFunction2(this.ModuleMenuCallback), moduleIndex); + } + else + { + genericMenu.AddDisabledItem(new GUIContent("Remove")); + } + genericMenu.ShowAsContext(); + Event.current.Use(); + } + private void EmitterMenuCallback(object obj) + { + switch ((int)obj) + { + case 0: + this.m_ParticleEffectUI.CreateParticleSystem(this.m_ParticleSystem, SubModuleUI.SubEmitterType.None); + break; + case 1: + this.ResetModules(); + break; + case 2: + EditorGUIUtility.PingObject(this.m_ParticleSystem); + break; + default: + Assert.That("Enum not handled!".Length == 0); + break; + } + } + private void ShowEmitterMenu() + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Show Location"), false, new GenericMenu.MenuFunction2(this.EmitterMenuCallback), 2); + genericMenu.AddSeparator(string.Empty); + if (this.m_ParticleSystem.gameObject.activeInHierarchy) + { + genericMenu.AddItem(new GUIContent("Create Particle System"), false, new GenericMenu.MenuFunction2(this.EmitterMenuCallback), 0); + } + else + { + genericMenu.AddDisabledItem(new GUIContent("Create new Particle System")); + } + genericMenu.AddItem(new GUIContent("Reset"), false, new GenericMenu.MenuFunction2(this.EmitterMenuCallback), 1); + genericMenu.ShowAsContext(); + Event.current.Use(); + } + private static ModuleUI[] CreateUIModules(ParticleSystemUI e, SerializedObject so) + { + int num = 0; + ModuleUI[] expr_09 = new ModuleUI[17]; + expr_09[0] = new InitialModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[1] = new EmissionModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[2] = new ShapeModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[3] = new VelocityModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[4] = new ClampVelocityModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[5] = new ForceModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[6] = new ColorModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[7] = new ColorByVelocityModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[8] = new SizeModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[9] = new SizeByVelocityModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[10] = new RotationModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[11] = new RotationByVelocityModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[12] = new ExternalForcesModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[13] = new CollisionModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[14] = new SubModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + expr_09[15] = new UVModuleUI(e, so, ParticleSystemUI.s_ModuleNames[num++]); + return expr_09; + } + public static string[] GetUIModuleNames() + { + return new string[] + { + string.Empty, + "Emission", + "Shape", + "Velocity over Lifetime", + "Limit Velocity over Lifetime", + "Force over Lifetime", + "Color over Lifetime", + "Color by Speed", + "Size over Lifetime", + "Size by Speed", + "Rotation over Lifetime", + "Rotation by Speed", + "External Forces", + "Collision", + "Sub Emitters", + "Texture Sheet Animation", + "Renderer" + }; + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemWindow.cs b/UnityEditor/UnityEditor/ParticleSystemWindow.cs new file mode 100644 index 00000000..1cee9c29 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleSystemWindow.cs @@ -0,0 +1,279 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ParticleSystemWindow : EditorWindow, ParticleEffectUIOwner + { + private class Texts + { + public GUIContent lockParticleSystem = new GUIContent(string.Empty, "Lock the current selected Particle System"); + public GUIContent previewAll = new GUIContent("Simulate All", "Simulate all particle systems that have Play On Awake set"); + } + private static ParticleSystemWindow s_Instance; + private ParticleSystem m_Target; + private ParticleEffectUI m_ParticleEffectUI; + private bool m_IsVisible; + private static GUIContent[] s_Icons = new GUIContent[] + { + EditorGUIUtility.IconContent("HorizontalSplit"), + EditorGUIUtility.IconContent("VerticalSplit") + }; + private static ParticleSystemWindow.Texts s_Texts; + private ParticleSystemWindow() + { + } + public static void CreateWindow() + { + ParticleSystemWindow.s_Instance = EditorWindow.GetWindow(); + ParticleSystemWindow.s_Instance.title = "Particle Effect"; + ParticleSystemWindow.s_Instance.minSize = ParticleEffectUI.GetMinSize(); + } + internal static ParticleSystemWindow GetInstance() + { + return ParticleSystemWindow.s_Instance; + } + internal bool IsVisible() + { + return this.m_IsVisible; + } + private void OnEnable() + { + ParticleSystemWindow.s_Instance = this; + this.m_Target = null; + ParticleEffectUI.m_VerticalLayout = EditorPrefs.GetBool("ShurikenVerticalLayout", false); + EditorApplication.hierarchyWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.hierarchyWindowChanged, new EditorApplication.CallbackFunction(this.OnHierarchyOrProjectWindowWasChanged)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnHierarchyOrProjectWindowWasChanged)); + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + base.autoRepaintOnSceneChange = false; + } + private void OnDisable() + { + ParticleSystemEditorUtils.editorUpdateAll = false; + SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnHierarchyOrProjectWindowWasChanged)); + EditorApplication.hierarchyWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.hierarchyWindowChanged, new EditorApplication.CallbackFunction(this.OnHierarchyOrProjectWindowWasChanged)); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.Clear(); + if (ParticleSystemWindow.s_Instance == this) + { + ParticleSystemWindow.s_Instance = null; + } + } + private void Clear() + { + this.m_Target = null; + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Clear(); + this.m_ParticleEffectUI = null; + } + } + private void OnPlayModeStateChanged() + { + base.Repaint(); + } + private void UndoRedoPerformed() + { + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.UndoRedoPerformed(); + } + base.Repaint(); + } + private void OnHierarchyOrProjectWindowWasChanged() + { + this.InitEffectUI(); + } + private void OnBecameVisible() + { + if (this.m_IsVisible) + { + return; + } + this.m_IsVisible = true; + this.InitEffectUI(); + SceneView.RepaintAll(); + InspectorWindow.RepaintAllInspectors(); + } + private void OnBecameInvisible() + { + this.m_IsVisible = false; + ParticleSystemEditorUtils.editorUpdateAll = false; + this.Clear(); + SceneView.RepaintAll(); + InspectorWindow.RepaintAllInspectors(); + } + private void OnSelectionChange() + { + this.InitEffectUI(); + base.Repaint(); + } + private void InitEffectUI() + { + if (!this.m_IsVisible) + { + return; + } + ParticleSystem particleSystem = ParticleSystemEditorUtils.lockedParticleSystem; + if (particleSystem == null && Selection.activeGameObject != null) + { + particleSystem = Selection.activeGameObject.GetComponent(); + } + this.m_Target = particleSystem; + if (this.m_Target != null) + { + if (this.m_ParticleEffectUI == null) + { + this.m_ParticleEffectUI = new ParticleEffectUI(this); + } + if (this.m_ParticleEffectUI.InitializeIfNeeded(this.m_Target)) + { + base.Repaint(); + } + } + if (this.m_Target == null && this.m_ParticleEffectUI != null) + { + this.Clear(); + base.Repaint(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + } + } + private void Awake() + { + } + private void DoToolbarGUI() + { + GUILayout.BeginHorizontal("Toolbar", new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(this.m_ParticleEffectUI == null); + EditorGUI.BeginDisabledGroup(ParticleSystemEditorUtils.editorUpdateAll); + if (!EditorApplication.isPlaying) + { + bool flag = false; + if (this.m_ParticleEffectUI != null) + { + flag = this.m_ParticleEffectUI.IsPlaying(); + } + if (GUILayout.Button((!flag) ? ParticleEffectUI.texts.play : ParticleEffectUI.texts.pause, "ToolbarButton", new GUILayoutOption[] + { + GUILayout.Width(65f) + })) + { + if (this.m_ParticleEffectUI != null) + { + if (flag) + { + this.m_ParticleEffectUI.Pause(); + } + else + { + this.m_ParticleEffectUI.Play(); + } + } + base.Repaint(); + } + if (GUILayout.Button(ParticleEffectUI.texts.stop, "ToolbarButton", new GUILayoutOption[0]) && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Stop(); + } + } + else + { + if (GUILayout.Button(ParticleEffectUI.texts.play, "ToolbarButton", new GUILayoutOption[] + { + GUILayout.Width(65f) + }) && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Stop(); + this.m_ParticleEffectUI.Play(); + } + if (GUILayout.Button(ParticleEffectUI.texts.stop, "ToolbarButton", new GUILayoutOption[0]) && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.Stop(); + } + } + GUILayout.FlexibleSpace(); + bool flag2 = this.m_ParticleEffectUI != null && this.m_ParticleEffectUI.IsShowOnlySelectedMode(); + bool flag3 = GUILayout.Toggle(flag2, (!flag2) ? "Show: All" : "Show: Selected", ParticleSystemStyles.Get().toolbarButtonLeftAlignText, new GUILayoutOption[] + { + GUILayout.Width(100f) + }); + if (flag3 != flag2 && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.SetShowOnlySelectedMode(flag3); + } + ParticleSystemEditorUtils.editorResimulation = GUILayout.Toggle(ParticleSystemEditorUtils.editorResimulation, ParticleEffectUI.texts.resimulation, "ToolbarButton", new GUILayoutOption[0]); + ParticleEffectUI.m_ShowWireframe = GUILayout.Toggle(ParticleEffectUI.m_ShowWireframe, ParticleEffectUI.texts.wireframe, "ToolbarButton", new GUILayoutOption[0]); + if (GUILayout.Button((!ParticleEffectUI.m_VerticalLayout) ? ParticleSystemWindow.s_Icons[1] : ParticleSystemWindow.s_Icons[0], "ToolbarButton", new GUILayoutOption[0])) + { + ParticleEffectUI.m_VerticalLayout = !ParticleEffectUI.m_VerticalLayout; + EditorPrefs.SetBool("ShurikenVerticalLayout", ParticleEffectUI.m_VerticalLayout); + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(3f); + ParticleSystem lockedParticleSystem = ParticleSystemEditorUtils.lockedParticleSystem; + bool flag4 = lockedParticleSystem != null; + bool flag5 = GUILayout.Toggle(flag4, ParticleSystemWindow.s_Texts.lockParticleSystem, "IN LockButton", new GUILayoutOption[0]); + if (flag4 != flag5 && this.m_ParticleEffectUI != null && this.m_Target != null) + { + if (flag5) + { + ParticleSystemEditorUtils.lockedParticleSystem = this.m_Target; + } + else + { + ParticleSystemEditorUtils.lockedParticleSystem = null; + } + } + GUILayout.EndVertical(); + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + } + private void OnGUI() + { + if (ParticleSystemWindow.s_Texts == null) + { + ParticleSystemWindow.s_Texts = new ParticleSystemWindow.Texts(); + } + if (this.m_Target == null && (Selection.activeGameObject != null || ParticleSystemEditorUtils.lockedParticleSystem != null)) + { + this.InitEffectUI(); + } + this.DoToolbarGUI(); + EditorGUI.BeginDisabledGroup(ParticleSystemEditorUtils.editorUpdateAll); + if (this.m_Target != null && this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.OnGUI(); + } + EditorGUI.EndDisabledGroup(); + } + public void OnSceneViewGUI(SceneView sceneView) + { + if (!this.m_IsVisible) + { + return; + } + if (ParticleSystemEditorUtils.editorUpdateAll) + { + return; + } + if (this.m_ParticleEffectUI != null) + { + this.m_ParticleEffectUI.OnSceneGUI(); + this.m_ParticleEffectUI.OnSceneViewGUI(); + } + } + private void OnDidOpenScene() + { + base.Repaint(); + } + virtual void Repaint() + { + base.Repaint(); + } + } +} diff --git a/UnityEditor/UnityEditor/Physics2DSettings.cs b/UnityEditor/UnityEditor/Physics2DSettings.cs new file mode 100644 index 00000000..5838fb46 --- /dev/null +++ b/UnityEditor/UnityEditor/Physics2DSettings.cs @@ -0,0 +1,8 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class Physics2DSettings : UnityEngine.Object + { + } +} diff --git a/UnityEditor/UnityEditor/Physics2DSettingsInspector.cs b/UnityEditor/UnityEditor/Physics2DSettingsInspector.cs new file mode 100644 index 00000000..d4e37742 --- /dev/null +++ b/UnityEditor/UnityEditor/Physics2DSettingsInspector.cs @@ -0,0 +1,24 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Physics2DSettings))] + internal class Physics2DSettingsInspector : Editor + { + private Vector2 scrollPos; + private bool show = true; + private bool GetValue(int layerA, int layerB) + { + return !Physics2D.GetIgnoreLayerCollision(layerA, layerB); + } + private void SetValue(int layerA, int layerB, bool val) + { + Physics2D.IgnoreLayerCollision(layerA, layerB, !val); + } + public override void OnInspectorGUI() + { + base.DrawDefaultInspector(); + LayerMatrixGUI.DoGUI("Layer Collision Matrix", ref this.show, ref this.scrollPos, new LayerMatrixGUI.GetValueFunc(this.GetValue), new LayerMatrixGUI.SetValueFunc(this.SetValue)); + } + } +} diff --git a/UnityEditor/UnityEditor/PhysicsManager.cs b/UnityEditor/UnityEditor/PhysicsManager.cs new file mode 100644 index 00000000..9eae9067 --- /dev/null +++ b/UnityEditor/UnityEditor/PhysicsManager.cs @@ -0,0 +1,8 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class PhysicsManager : UnityEngine.Object + { + } +} diff --git a/UnityEditor/UnityEditor/PhysicsManagerInspector.cs b/UnityEditor/UnityEditor/PhysicsManagerInspector.cs new file mode 100644 index 00000000..db94fd2b --- /dev/null +++ b/UnityEditor/UnityEditor/PhysicsManagerInspector.cs @@ -0,0 +1,24 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(PhysicsManager))] + internal class PhysicsManagerInspector : Editor + { + private Vector2 scrollPos; + private bool show = true; + private bool GetValue(int layerA, int layerB) + { + return !Physics.GetIgnoreLayerCollision(layerA, layerB); + } + private void SetValue(int layerA, int layerB, bool val) + { + Physics.IgnoreLayerCollision(layerA, layerB, !val); + } + public override void OnInspectorGUI() + { + base.DrawDefaultInspector(); + LayerMatrixGUI.DoGUI("Layer Collision Matrix", ref this.show, ref this.scrollPos, new LayerMatrixGUI.GetValueFunc(this.GetValue), new LayerMatrixGUI.SetValueFunc(this.SetValue)); + } + } +} diff --git a/UnityEditor/UnityEditor/PingData.cs b/UnityEditor/UnityEditor/PingData.cs new file mode 100644 index 00000000..6bdd3ce8 --- /dev/null +++ b/UnityEditor/UnityEditor/PingData.cs @@ -0,0 +1,69 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PingData + { + public float m_TimeStart = -1f; + public float m_ZoomTime = 0.2f; + public float m_WaitTime = 2.5f; + public float m_FadeOutTime = 1.5f; + public float m_PeakScale = 1.75f; + public Action m_ContentDraw; + public Rect m_ContentRect; + public float m_AvailableWidth = 100f; + public GUIStyle m_PingStyle; + public bool isPinging + { + get + { + return this.m_TimeStart > -1f; + } + } + public void HandlePing() + { + if (this.isPinging) + { + float num = this.m_ZoomTime + this.m_WaitTime + this.m_FadeOutTime; + float num2 = Time.realtimeSinceStartup - this.m_TimeStart; + if (num2 > 0f && num2 < num) + { + Color color = GUI.color; + Matrix4x4 matrix = GUI.matrix; + if (num2 < this.m_ZoomTime) + { + float num3 = this.m_ZoomTime / 2f; + float num4 = (this.m_PeakScale - 1f) * ((this.m_ZoomTime - Mathf.Abs(num3 - num2)) / num3 - 1f) + 1f; + Matrix4x4 matrix2 = GUI.matrix; + Vector2 pos = (this.m_ContentRect.xMax >= this.m_AvailableWidth) ? new Vector2(this.m_AvailableWidth, this.m_ContentRect.center.y) : this.m_ContentRect.center; + Vector2 vector = GUIClip.Unclip(pos); + Matrix4x4 lhs = Matrix4x4.TRS(vector, Quaternion.identity, new Vector3(num4, num4, 1f)) * Matrix4x4.TRS(-vector, Quaternion.identity, Vector3.one); + GUI.matrix = lhs * matrix2; + } + else + { + if (num2 > this.m_ZoomTime + this.m_WaitTime) + { + float num5 = (num - num2) / this.m_FadeOutTime; + GUI.color = new Color(color.r, color.g, color.b, color.a * num5); + } + } + if (this.m_ContentDraw != null && Event.current.type == EventType.Repaint) + { + Rect contentRect = this.m_ContentRect; + contentRect.x -= (float)this.m_PingStyle.padding.left; + contentRect.y -= (float)this.m_PingStyle.padding.top; + this.m_PingStyle.Draw(contentRect, GUIContent.none, false, false, false, false); + this.m_ContentDraw(this.m_ContentRect); + } + GUI.matrix = matrix; + GUI.color = color; + } + else + { + this.m_TimeStart = -1f; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/PivotMode.cs b/UnityEditor/UnityEditor/PivotMode.cs new file mode 100644 index 00000000..834f8393 --- /dev/null +++ b/UnityEditor/UnityEditor/PivotMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum PivotMode + { + Center, + Pivot + } +} diff --git a/UnityEditor/UnityEditor/PivotRotation.cs b/UnityEditor/UnityEditor/PivotRotation.cs new file mode 100644 index 00000000..640d2efe --- /dev/null +++ b/UnityEditor/UnityEditor/PivotRotation.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum PivotRotation + { + Local, + Global + } +} diff --git a/UnityEditor/UnityEditor/PlaceTreeWizard.cs b/UnityEditor/UnityEditor/PlaceTreeWizard.cs new file mode 100644 index 00000000..93f13962 --- /dev/null +++ b/UnityEditor/UnityEditor/PlaceTreeWizard.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PlaceTreeWizard : TerrainWizard + { + public int numberOfTrees = 10000; + public void OnEnable() + { + base.minSize = new Vector2(250f, 150f); + } + private void OnWizardCreate() + { + TreePlacementUtility.PlaceRandomTrees(this.m_Terrain.terrainData, this.numberOfTrees); + this.m_Terrain.Flush(); + } + } +} diff --git a/UnityEditor/UnityEditor/PlayerSettings.cs b/UnityEditor/UnityEditor/PlayerSettings.cs new file mode 100644 index 00000000..372586df --- /dev/null +++ b/UnityEditor/UnityEditor/PlayerSettings.cs @@ -0,0 +1,2124 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class PlayerSettings : UnityEngine.Object + { + public sealed class Android + { + public static extern bool use24BitDepthBuffer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int bundleVersionCode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidSdkVersions minSdkVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidPreferredInstallLocation preferredInstallLocation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool forceInternetPermission + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool forceSDCardPermission + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool createWallpaper + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidTargetDevice targetDevice + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidSplashScreenScale splashScreenScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keystoreName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keystorePass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keyaliasName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keyaliasPass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool licenseVerification + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool useAPKExpansionFiles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AndroidShowActivityIndicatorOnLoading showActivityIndicatorOnLoading + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public sealed class iOS + { + public static extern string applicationDisplayName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ScriptCallOptimizationLevel scriptCallOptimization + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSSdkVersion sdkVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSTargetOSVersion targetOSVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSTargetDevice targetDevice + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSTargetResolution targetResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool prerenderedIcon + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool requiresPersistentWiFi + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSStatusBarStyle statusBarStyle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool exitOnSuspend + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern iOSShowActivityIndicatorOnLoading showActivityIndicatorOnLoading + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public enum MetroApplicationShowName + { + NotSet, + AllLogos, + NoLogos, + StandardLogoOnly, + WideLogoOnly + } + public enum MetroDefaultTileSize + { + NotSet, + Medium, + Wide + } + public enum MetroApplicationForegroundText + { + Light = 1, + Dark + } + public enum MetroCompilationOverrides + { + None, + UseNetCore, + UseNetCorePartially + } + public enum MetroCapability + { + EnterpriseAuthentication, + InternetClient, + InternetClientServer, + MusicLibrary, + PicturesLibrary, + PrivateNetworkClientServer, + RemovableStorage, + SharedUserCertificates, + VideosLibrary, + WebCam, + Proximity, + Microphone, + Location + } + public sealed class Metro + { + public static extern string packageName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string packageLogo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string packageLogo140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string packageLogo180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string packageLogo240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Version packageVersion + { + get + { + Version result; + try + { + result = new Version(PlayerSettingsEditor.ValidateMetroPackageVersion(PlayerSettings.Metro.packageVersionRaw)); + } + catch (Exception ex) + { + throw new Exception(string.Format("{0}, the raw string was {1}", ex.Message, PlayerSettings.Metro.packageVersionRaw)); + } + return result; + } + set + { + PlayerSettings.Metro.packageVersionRaw = value.ToString(); + } + } + private static extern string packageVersionRaw + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string commandLineArgsFile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string certificatePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern string certificatePassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string certificateSubject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string certificateIssuer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static DateTime? certificateNotAfter + { + get + { + long certificateNotAfterRaw = PlayerSettings.Metro.certificateNotAfterRaw; + if (certificateNotAfterRaw != 0L) + { + return new DateTime?(DateTime.FromFileTime(certificateNotAfterRaw)); + } + return null; + } + } + private static extern long certificateNotAfterRaw + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string applicationDescription + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileLogo80 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileLogo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileLogo140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileLogo180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileWideLogo80 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileWideLogo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileWideLogo140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileWideLogo180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileSmallLogo80 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileSmallLogo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileSmallLogo140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeTileSmallLogo180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSmallTile80 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSmallTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSmallTile140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSmallTile180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeLargeTile80 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeLargeTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeLargeTile140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeLargeTile180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSplashScreenImage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSplashScreenImageScale140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string storeSplashScreenImageScale180 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneAppIcon + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneAppIcon140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneAppIcon240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSmallTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSmallTile140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSmallTile240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneMediumTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneMediumTile140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneMediumTile240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneWideTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneWideTile140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneWideTile240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSplashScreenImage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSplashScreenImageScale140 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string phoneSplashScreenImageScale240 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string tileShortName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.MetroApplicationShowName tileShowName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool mediumTileShowName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool largeTileShowName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool wideTileShowName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.MetroDefaultTileSize defaultTileSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.MetroCompilationOverrides compilationOverrides + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.MetroApplicationForegroundText tileForegroundText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string[] unprocessedPlugins + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color tileBackgroundColor + { + get + { + Color result; + PlayerSettings.Metro.INTERNAL_get_tileBackgroundColor(out result); + return result; + } + set + { + PlayerSettings.Metro.INTERNAL_set_tileBackgroundColor(ref value); + } + } + public static extern bool enableIndependentInputSource + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enableLowLatencyPresentationAPI + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color? splashScreenBackgroundColor + { + get + { + if (PlayerSettings.Metro.splashScreenUseBackgroundColor) + { + return new Color?(PlayerSettings.Metro.splashScreenBackgroundColorRaw); + } + return null; + } + set + { + PlayerSettings.Metro.splashScreenUseBackgroundColor = value.HasValue; + if (value.HasValue) + { + PlayerSettings.Metro.splashScreenBackgroundColorRaw = value.Value; + } + } + } + private static extern bool splashScreenUseBackgroundColor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + private static Color splashScreenBackgroundColorRaw + { + get + { + Color result; + PlayerSettings.Metro.INTERNAL_get_splashScreenBackgroundColorRaw(out result); + return result; + } + set + { + PlayerSettings.Metro.INTERNAL_set_splashScreenBackgroundColorRaw(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SetCertificate(string path, string password); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_tileBackgroundColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_tileBackgroundColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_splashScreenBackgroundColorRaw(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_splashScreenBackgroundColorRaw(ref Color value); + public static void SetCapability(PlayerSettings.MetroCapability capability, bool enabled) + { + PlayerSettings.Metro.InternalSetCapability(capability.ToString(), enabled); + } + public static bool GetCapability(PlayerSettings.MetroCapability capability) + { + return PlayerSettings.Metro.InternalGetCapability(capability.ToString()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void InternalSetCapability(string name, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool InternalGetCapability(string name); + } + public sealed class WP8 + { + public static extern string[] unprocessedPlugins + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public sealed class BlackBerry + { + public static extern string deviceAddress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string devicePassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string tokenPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string tokenExpires + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string tokenAuthor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string tokenAuthorId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string authorId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string cskPassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string saveLogPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAuthorIDOverride(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsAuthorIDOverride(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasSharedPermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSharedPermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasCameraPermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetCameraPermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasGPSPermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGPSPermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasIdentificationPermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetIdentificationPermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasMicrophonePermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetMicrophonePermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasGamepadSupport(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGamepadSupport(bool enable); + } + public sealed class Tizen + { + public static extern string productDescription + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string productURL + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string certificatePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string certificatePassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasGPSPermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGPSPermissions(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasMicrophonePermissions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetMicrophonePermissions(bool enable); + } + public sealed class PS3 + { + public static extern int videoMemoryForVertexBuffers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public sealed class SamsungTV + { + public static extern string deviceAddress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + private static SerializedObject _serializedObject; + internal static readonly char[] defineSplits = new char[] + { + ';', + ',', + ' ' + }; + public static extern string companyName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string productName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Guid productGUID + { + get + { + return new Guid(PlayerSettings.productGUIDRaw); + } + } + private static extern byte[] productGUIDRaw + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ColorSpace colorSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int defaultScreenWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int defaultScreenHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int defaultWebScreenWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int defaultWebScreenHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ResolutionDialogSetting displayResolutionDialog + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool defaultIsFullScreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool defaultIsNativeResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool runInBackground + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool captureSingleScreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool usePlayerLog + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool resizableWindow + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool stripPhysics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useMacAppStoreValidation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern MacFullscreenMode macFullscreenMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern D3D9FullscreenMode d3d9FullscreenMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool d3d11ForceExclusiveMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool visibleInBackground + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool forceSingleInstance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("The option alwaysDisplayWatermark is deprecated and is always false.")] + public static bool alwaysDisplayWatermark + { + get + { + return false; + } + set + { + } + } + public static extern int firstStreamedLevelWithResources + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Texture2D resolutionDialogBanner + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string locationUsageDescription + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string iPhoneBundleIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern string webPlayerTemplate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern string[] templateCustomKeys + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern string spritePackerPolicy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keystorePass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keyaliasPass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string xboxTitleId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string xboxImageXexFilePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string xboxSpaFilePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxGenerateSpa + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxEnableGuest + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxDeployKinectResources + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxDeployKinectHeadOrientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool xboxDeployKinectHeadPosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Texture2D xboxSplashScreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int xboxAdditionalTitleMemorySize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool xboxEnableKinect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxEnableKinectAutoTracking + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxEnableSpeech + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern uint xboxSpeechDB + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool gpuSkinning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxPIXTextureCapture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool xboxEnableAvatar + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3TitleConfigPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3DLCConfigPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3ThumbnailPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3BackgroundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3SoundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3TrophyCommId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3NpCommunicationPassphrase + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3TrophyCommSig + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string ps3TrophyPackagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int ps3BootCheckMaxSaveGameSizeKB + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool ps3TrialMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int ps3SaveGameSlots + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2NPTrophyPackPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2NPCommsID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2NPCommsPassphrase + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2NPCommsSig + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2ParamSfxPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2PackagePassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2DLCConfigPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2ThumbnailPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2BackgroundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2SoundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2TrophyCommId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string psp2TrophyPackagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string bundleIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string bundleVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string shortBundleVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool statusBarHidden + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern StrippingLevel strippingLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern UIOrientation defaultInterfaceOrientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool allowedAutorotateToPortrait + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool allowedAutorotateToPortraitUpsideDown + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool allowedAutorotateToLandscapeRight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool allowedAutorotateToLandscapeLeft + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useAnimatedAutorotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool use32BitDisplayBuffer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern TargetGlesGraphics targetGlesGraphics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern TargetIOSGraphics targetIOSGraphics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ApiCompatibilityLevel apiCompatibilityLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool stripUnusedMeshComponents + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool advancedLicense + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string aotOptions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int accelerometerFrequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool MTRendering + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool mobileMTRendering + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern RenderingPath renderingPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern RenderingPath mobileRenderingPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useDirect3D11 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool stereoscopic3D + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern UnityEngine.Object InternalGetPlayerSettingsObject(); + internal static SerializedObject GetSerializedObject() + { + if (PlayerSettings._serializedObject == null) + { + PlayerSettings._serializedObject = new SerializedObject(PlayerSettings.InternalGetPlayerSettingsObject()); + } + return PlayerSettings._serializedObject; + } + internal static SerializedProperty FindProperty(string name) + { + SerializedProperty serializedProperty = PlayerSettings.GetSerializedObject().FindProperty(name); + if (serializedProperty == null) + { + Debug.LogError("Failed to find:" + name); + } + return serializedProperty; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetPropertyOptionalInt(string name, ref int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target); + [ExcludeFromDocs] + public static bool GetPropertyOptionalInt(string name, ref int value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyOptionalInt(name, ref value, target); + } + [ExcludeFromDocs] + public static int GetPropertyInt(string name) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyInt(name, target); + } + public static int GetPropertyInt(string name, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + return PlayerSettings.GetPropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetPropertyIntInternal(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPropertyIntInternal(string name, int value); + public static void SetPropertyInt(string name, int value, BuildTarget target) + { + PlayerSettings.SetPropertyInt(name, value, BuildPipeline.GetBuildTargetGroup(target)); + } + [ExcludeFromDocs] + public static void SetPropertyInt(string name, int value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.SetPropertyInt(name, value, target); + } + public static void SetPropertyInt(string name, int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.SetPropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InitializePropertyIntInternal(string name, int value); + [ExcludeFromDocs] + internal static void InitializePropertyInt(string name, int value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.InitializePropertyInt(name, value, target); + } + internal static void InitializePropertyInt(string name, int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.InitializePropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + [ExcludeFromDocs] + public static bool GetPropertyOptionalString(string name, ref string value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyOptionalString(name, ref value, target); + } + public static bool GetPropertyOptionalString(string name, ref string value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + string propertyOptionalStringInternal = PlayerSettings.GetPropertyOptionalStringInternal(name, target); + if (propertyOptionalStringInternal == null) + { + return false; + } + value = propertyOptionalStringInternal; + return true; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string GetPropertyOptionalStringInternal(string name, BuildTargetGroup target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPropertyNameForBuildTargetGroupInternal(BuildTargetGroup target, string name); + internal static string GetPropertyNameForBuildTarget(BuildTargetGroup target, string name) + { + string propertyNameForBuildTargetGroupInternal = PlayerSettings.GetPropertyNameForBuildTargetGroupInternal(target, name); + if (propertyNameForBuildTargetGroupInternal != string.Empty) + { + return propertyNameForBuildTargetGroupInternal; + } + throw new ArgumentException("Failed to get property name for the given target."); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasAspectRatio(AspectRatio aspectRatio); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAspectRatio(AspectRatio aspectRatio, bool enable); + public static Texture2D[] GetIconsForTargetGroup(BuildTargetGroup platform) + { + Texture2D[] iconsForPlatform = PlayerSettings.GetIconsForPlatform(PlayerSettings.GetPlatformName(platform)); + if (iconsForPlatform.Length == 0) + { + return new Texture2D[PlayerSettings.GetIconSizesForTargetGroup(platform).Length]; + } + return iconsForPlatform; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D[] GetIconsForPlatform(string platform); + public static void SetIconsForTargetGroup(BuildTargetGroup platform, Texture2D[] icons) + { + PlayerSettings.SetIconsForPlatform(PlayerSettings.GetPlatformName(platform), icons); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetIconsForPlatform(string platform, Texture2D[] icons); + public static int[] GetIconSizesForTargetGroup(BuildTargetGroup platform) + { + return PlayerSettings.GetIconSizesForPlatform(PlayerSettings.GetPlatformName(platform)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int[] GetIconSizesForPlatform(string platform); + internal static string GetPlatformName(BuildTargetGroup targetGroup) + { + BuildPlayerWindow.BuildPlatform buildPlatform = BuildPlayerWindow.GetValidPlatforms().Find((BuildPlayerWindow.BuildPlatform p) => p.targetGroup == targetGroup); + return (buildPlatform != null) ? buildPlatform.name : string.Empty; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D GetIconForPlatformAtSize(string platform, int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void GetBatchingForPlatform(BuildTarget platform, out int staticBatching, out int dynamicBatching); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetBatchingForPlatform(BuildTarget platform, int staticBatching, int dynamicBatching); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetTemplateCustomValue(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetTemplateCustomValue(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup); + public static void SetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup, string defines) + { + if (!string.IsNullOrEmpty(defines)) + { + defines = string.Join(";", defines.Split(PlayerSettings.defineSplits, StringSplitOptions.RemoveEmptyEntries)); + } + PlayerSettings.SetScriptingDefineSymbolsForGroupInternal(targetGroup, defines); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetScriptingDefineSymbolsForGroupInternal(BuildTargetGroup targetGroup, string defines); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetApiCompatibilityInternal(int value); + } +} diff --git a/UnityEditor/UnityEditor/PlayerSettingsEditor.cs b/UnityEditor/UnityEditor/PlayerSettingsEditor.cs new file mode 100644 index 00000000..1b2acdc9 --- /dev/null +++ b/UnityEditor/UnityEditor/PlayerSettingsEditor.cs @@ -0,0 +1,2310 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor.AnimatedValues; +using UnityEditor.Modules; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CustomEditor(typeof(PlayerSettings))] + internal class PlayerSettingsEditor : Editor + { + private class Styles + { + public GUIStyle thumbnail = "IN ThumbnailShadow"; + public GUIStyle thumbnailLabel = "IN ThumbnailSelection"; + public GUIStyle categoryBox = new GUIStyle(EditorStyles.helpBox); + public GUIContent colorSpaceWarning = EditorGUIUtility.TextContent("PlayerSettings.ActiveColorSpaceWarning"); + public GUIContent cursorHotspot = EditorGUIUtility.TextContent("PlayerSettings.CursorHotspot"); + public GUIContent defaultCursor = EditorGUIUtility.TextContent("PlayerSettings.DefaultCursor"); + public GUIContent defaultIcon = EditorGUIUtility.TextContent("PlayerSettings.DefaultIcon"); + public Styles() + { + this.categoryBox.padding.left = 14; + } + } + private enum FakeEnum + { + WebplayerSubset, + FlashPlayerSubset + } + internal class WebPlayerTemplate + { + private static PlayerSettingsEditor.WebPlayerTemplate[] s_Templates; + private static GUIContent[] s_TemplateGUIThumbnails; + private string m_Path; + private string m_Name; + private Texture2D m_Thumbnail; + private string[] m_CustomKeys; + public string[] CustomKeys + { + get + { + return this.m_CustomKeys; + } + } + public static PlayerSettingsEditor.WebPlayerTemplate[] Templates + { + get + { + if (PlayerSettingsEditor.WebPlayerTemplate.s_Templates == null || PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails == null) + { + PlayerSettingsEditor.WebPlayerTemplate.BuildTemplateList(); + } + return PlayerSettingsEditor.WebPlayerTemplate.s_Templates; + } + } + public static GUIContent[] TemplateGUIThumbnails + { + get + { + if (PlayerSettingsEditor.WebPlayerTemplate.s_Templates == null || PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails == null) + { + PlayerSettingsEditor.WebPlayerTemplate.BuildTemplateList(); + } + return PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails; + } + } + public static int GetTemplateIndex(string path) + { + for (int i = 0; i < PlayerSettingsEditor.WebPlayerTemplate.Templates.Length; i++) + { + if (path.Equals(PlayerSettingsEditor.WebPlayerTemplate.Templates[i].ToString())) + { + return i; + } + } + return 0; + } + public static void ClearTemplates() + { + PlayerSettingsEditor.WebPlayerTemplate.s_Templates = null; + PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails = null; + } + private static void BuildTemplateList() + { + List list = new List(); + string path = Path.Combine(Application.dataPath.Replace('/', Path.DirectorySeparatorChar), "WebPlayerTemplates"); + if (Directory.Exists(path)) + { + list.AddRange(PlayerSettingsEditor.WebPlayerTemplate.ListTemplates(path)); + } + string path2 = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath.Replace('/', Path.DirectorySeparatorChar), "Resources"), "WebPlayerTemplates"); + if (Directory.Exists(path2)) + { + list.AddRange(PlayerSettingsEditor.WebPlayerTemplate.ListTemplates(path2)); + } + else + { + Debug.LogError("Did not find built-in templates."); + } + PlayerSettingsEditor.WebPlayerTemplate.s_Templates = list.ToArray(); + PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails = new GUIContent[PlayerSettingsEditor.WebPlayerTemplate.s_Templates.Length]; + for (int i = 0; i < PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails.Length; i++) + { + PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails[i] = PlayerSettingsEditor.WebPlayerTemplate.s_Templates[i].ToGUIContent(); + } + } + private static PlayerSettingsEditor.WebPlayerTemplate Load(string path) + { + if (!Directory.Exists(path) || Directory.GetFiles(path, "index.*").Length < 1) + { + return null; + } + string[] array = path.Split(new char[] + { + Path.DirectorySeparatorChar + }); + PlayerSettingsEditor.WebPlayerTemplate webPlayerTemplate = new PlayerSettingsEditor.WebPlayerTemplate(); + webPlayerTemplate.m_Name = array[array.Length - 1]; + if (array.Length > 3 && array[array.Length - 3].Equals("Assets")) + { + webPlayerTemplate.m_Path = "PROJECT:" + webPlayerTemplate.m_Name; + } + else + { + webPlayerTemplate.m_Path = "APPLICATION:" + webPlayerTemplate.m_Name; + } + string[] files = Directory.GetFiles(path, "thumbnail.*"); + if (files.Length > 0) + { + webPlayerTemplate.m_Thumbnail = new Texture2D(2, 2); + webPlayerTemplate.m_Thumbnail.LoadImage(File.ReadAllBytes(files[0])); + } + List list = new List(); + Regex regex = new Regex("\\%UNITY_CUSTOM_([A-Z_]+)\\%"); + MatchCollection matchCollection = regex.Matches(File.ReadAllText(Directory.GetFiles(path, "index.*")[0])); + foreach (Match match in matchCollection) + { + string text = match.Value.Substring("%UNITY_CUSTOM_".Length); + text = text.Substring(0, text.Length - 1); + if (!list.Contains(text)) + { + list.Add(text); + } + } + webPlayerTemplate.m_CustomKeys = list.ToArray(); + return webPlayerTemplate; + } + private static List ListTemplates(string path) + { + List list = new List(); + string[] directories = Directory.GetDirectories(path); + string[] array = directories; + for (int i = 0; i < array.Length; i++) + { + string path2 = array[i]; + PlayerSettingsEditor.WebPlayerTemplate webPlayerTemplate = PlayerSettingsEditor.WebPlayerTemplate.Load(path2); + if (webPlayerTemplate != null) + { + list.Add(webPlayerTemplate); + } + } + return list; + } + public override bool Equals(object other) + { + return other is PlayerSettingsEditor.WebPlayerTemplate && other.ToString().Equals(this.ToString()); + } + public override int GetHashCode() + { + return base.GetHashCode() ^ this.m_Path.GetHashCode(); + } + public override string ToString() + { + return this.m_Path; + } + public GUIContent ToGUIContent() + { + return new GUIContent(this.m_Name, (!(this.m_Thumbnail == null)) ? this.m_Thumbnail : ((Texture2D)EditorGUIUtility.IconContent("BuildSettings.Web.Small").image)); + } + } + private const int kSlotSize = 64; + private const int kMaxPreviewSize = 96; + private const int kIconSpacing = 6; + private const string kWebPlayerTemplateDefaultIconResource = "BuildSettings.Web.Small"; + private const float kWebPlayerTemplateGridPadding = 15f; + private const float kThumbnailSize = 80f; + private const float kThumbnailLabelHeight = 20f; + private const float kThumbnailPadding = 5f; + private static PlayerSettingsEditor.Styles s_Styles; + private SavedInt m_SelectedSection = new SavedInt("PlayerSettings.ShownSection", -1); + private BuildPlayerWindow.BuildPlatform[] validPlatforms; + private SerializedProperty m_IPhoneBundleIdentifier; + private SerializedProperty m_IPhoneBundleVersion; + private SerializedProperty m_IPhoneShortBundleVersion; + private SerializedProperty m_IPhoneApplicationDisplayName; + private SerializedProperty m_LocationUsageDescription; + private SerializedProperty m_ApiCompatibilityLevel; + private SerializedProperty m_IPhoneStrippingLevel; + private SerializedProperty m_IPhoneScriptCallOptimization; + private SerializedProperty m_AotOptions; + private SerializedProperty m_DefaultScreenOrientation; + private SerializedProperty m_AllowedAutoRotateToPortrait; + private SerializedProperty m_AllowedAutoRotateToPortraitUpsideDown; + private SerializedProperty m_AllowedAutoRotateToLandscapeRight; + private SerializedProperty m_AllowedAutoRotateToLandscapeLeft; + private SerializedProperty m_UseOSAutoRotation; + private SerializedProperty m_Use32BitDisplayBuffer; + private SerializedProperty m_Use24BitDepthBuffer; + private SerializedProperty m_iosShowActivityIndicatorOnLoading; + private SerializedProperty m_androidShowActivityIndicatorOnLoading; + private SerializedProperty m_IPhoneSdkVersion; + private SerializedProperty m_IPhoneTargetOSVersion; + private SerializedProperty m_AndroidProfiler; + private SerializedProperty m_UIPrerenderedIcon; + private SerializedProperty m_UIRequiresPersistentWiFi; + private SerializedProperty m_UIStatusBarHidden; + private SerializedProperty m_UIStatusBarStyle; + private SerializedProperty m_UIExitOnSuspend; + private SerializedProperty m_EnableHWStatistics; + private SerializedProperty m_TargetDevice; + private SerializedProperty m_TargetGlesGraphics; + private SerializedProperty m_TargetIOSGraphics; + private SerializedProperty m_TargetResolution; + private SerializedProperty m_AccelerometerFrequency; + private SerializedProperty m_OverrideIPodMusic; + private SerializedProperty m_PrepareIOSForRecording; + private SerializedProperty m_XboxTitleId; + private SerializedProperty m_XboxImageXexPath; + private SerializedProperty m_XboxSpaPath; + private SerializedProperty m_XboxGenerateSpa; + private SerializedProperty m_XboxDeployKinectResources; + private SerializedProperty m_XboxPIXTextureCapture; + private SerializedProperty m_XboxEnableAvatar; + private SerializedProperty m_XboxEnableKinect; + private SerializedProperty m_XboxEnableKinectAutoTracking; + private SerializedProperty m_XboxEnableHeadOrientation; + private SerializedProperty m_XboxDeployHeadOrientation; + private SerializedProperty m_XboxDeployKinectHeadPosition; + private SerializedProperty m_XboxSplashScreen; + private SerializedProperty m_XboxEnableSpeech; + private SerializedProperty m_XboxSpeechDB; + private SerializedProperty m_XboxEnableFitness; + private SerializedProperty m_XboxAdditionalTitleMemorySize; + private SerializedProperty m_XboxEnableGuest; + private SerializedProperty m_PS3TitleConfigPath; + private SerializedProperty m_PS3DLCConfigPath; + private SerializedProperty m_PS3ThumbnailPath; + private SerializedProperty m_PS3BackgroundPath; + private SerializedProperty m_PS3SoundPath; + private SerializedProperty m_PS3TrophyCommId; + private SerializedProperty m_PS3NpCommunicationPassphrase; + private SerializedProperty m_PS3TrophyPackagePath; + private SerializedProperty m_PS3BootCheckMaxSaveGameSizeKB; + private SerializedProperty m_PS3TrophyCommSig; + private SerializedProperty m_PS3TrialMode; + private SerializedProperty m_PS3SaveGameSlots; + private SerializedProperty m_PSP2SplashScreen; + private SerializedProperty m_PSP2LiveAreaGate; + private SerializedProperty m_PSP2LiveAreaBackground; + private SerializedProperty m_PSP2NPCommsID; + private SerializedProperty m_PSP2NPCommsPassphrase; + private SerializedProperty m_PSP2NPCommsSig; + private SerializedProperty m_PSP2TrophyPackPath; + private SerializedProperty m_PSP2ParamSfxPath; + private SerializedProperty m_PSP2PackagePassword; + private SerializedProperty m_FlashStrippingLevel; + private SerializedProperty m_VideoMemoryForVertexBuffers; + private SerializedProperty m_MetroPackageName; + private SerializedProperty m_MetroPackageLogo; + private SerializedProperty m_MetroPackageLogo140; + private SerializedProperty m_MetroPackageLogo180; + private SerializedProperty m_MetroPackageLogo240; + private SerializedProperty m_MetroPackageVersion; + private SerializedProperty m_MetroApplicationDescription; + private SerializedProperty m_MetroTileShortName; + private SerializedProperty m_MetroTileBackgroundColor; + private SerializedProperty m_MetroStoreTileLogo80; + private SerializedProperty m_MetroStoreTileLogo; + private SerializedProperty m_MetroStoreTileLogo140; + private SerializedProperty m_MetroStoreTileLogo180; + private SerializedProperty m_MetroStoreTileWideLogo80; + private SerializedProperty m_MetroStoreTileWideLogo; + private SerializedProperty m_MetroStoreTileWideLogo140; + private SerializedProperty m_MetroStoreTileWideLogo180; + private SerializedProperty m_MetroStoreTileSmallLogo80; + private SerializedProperty m_MetroStoreTileSmallLogo; + private SerializedProperty m_MetroStoreTileSmallLogo140; + private SerializedProperty m_MetroStoreTileSmallLogo180; + private SerializedProperty m_MetroStoreSmallTile80; + private SerializedProperty m_MetroStoreSmallTile; + private SerializedProperty m_MetroStoreSmallTile140; + private SerializedProperty m_MetroStoreSmallTile180; + private SerializedProperty m_MetroStoreLargeTile80; + private SerializedProperty m_MetroStoreLargeTile; + private SerializedProperty m_MetroStoreLargeTile140; + private SerializedProperty m_MetroStoreLargeTile180; + private SerializedProperty m_MetroStoreSplashScreenImage; + private SerializedProperty m_MetroStoreSplashScreenImage140; + private SerializedProperty m_MetroStoreSplashScreenImage180; + private SerializedProperty m_MetroPhoneAppIcon; + private SerializedProperty m_MetroPhoneAppIcon140; + private SerializedProperty m_MetroPhoneAppIcon240; + private SerializedProperty m_MetroPhoneSmallTile; + private SerializedProperty m_MetroPhoneSmallTile140; + private SerializedProperty m_MetroPhoneSmallTile240; + private SerializedProperty m_MetroPhoneMediumTile; + private SerializedProperty m_MetroPhoneMediumTile140; + private SerializedProperty m_MetroPhoneMediumTile240; + private SerializedProperty m_MetroPhoneWideTile; + private SerializedProperty m_MetroPhoneWideTile140; + private SerializedProperty m_MetroPhoneWideTile240; + private SerializedProperty m_MetroPhoneSplashScreenImage; + private SerializedProperty m_MetroPhoneSplashScreenImage140; + private SerializedProperty m_MetroPhoneSplashScreenImage240; + private SerializedProperty m_MetroUnprocessedPlugins; + private SerializedProperty m_MetroEnableIndependentInputSource; + private SerializedProperty m_MetroEnableLowLatencyPresentationAPI; + private SerializedProperty m_WP8UnprocessedPlugins; + private SerializedProperty m_CompanyName; + private SerializedProperty m_ProductName; + private SerializedProperty m_DefaultCursor; + private SerializedProperty m_CursorHotspot; + private SerializedProperty m_DefaultScreenWidth; + private SerializedProperty m_DefaultScreenHeight; + private SerializedProperty m_DefaultScreenWidthWeb; + private SerializedProperty m_DefaultScreenHeightWeb; + private SerializedProperty m_RenderingPath; + private SerializedProperty m_MobileRenderingPath; + private SerializedProperty m_ActiveColorSpace; + private SerializedProperty m_MTRendering; + private SerializedProperty m_MobileMTRendering; + private SerializedProperty m_StripUnusedMeshComponents; + private SerializedProperty m_DisplayResolutionDialog; + private SerializedProperty m_DefaultIsFullScreen; + private SerializedProperty m_DefaultIsNativeResolution; + private SerializedProperty m_UsePlayerLog; + private SerializedProperty m_ResizableWindow; + private SerializedProperty m_StripPhysics; + private SerializedProperty m_UseMacAppStoreValidation; + private SerializedProperty m_MacFullscreenMode; + private SerializedProperty m_D3D9FullscreenMode; + private SerializedProperty m_D3D11ForceExclusiveMode; + private SerializedProperty m_VisibleInBackground; + private SerializedProperty m_ForceSingleInstance; + private SerializedProperty m_RunInBackground; + private SerializedProperty m_CaptureSingleScreen; + private SerializedProperty m_ResolutionDialogBanner; + private SerializedProperty m_SupportedAspectRatios; + private SerializedProperty m_SkinOnGPU; + private SerializedProperty m_FirstStreamedLevelWithResources; + private SerializedProperty m_WebPlayerTemplate; + private int selectedPlatform; + private int scriptingDefinesControlID; + private AnimBool[] m_SectionAnimators = new AnimBool[5]; + private readonly AnimBool m_ShowDeferredWarning = new AnimBool(); + private readonly AnimBool m_ShowDefaultIsNativeResolution = new AnimBool(); + private readonly AnimBool m_ShowResolution = new AnimBool(); + private static Texture2D s_WarningIcon; + private Vector2 capScrollViewPosition = Vector2.zero; + private static readonly Regex metroPackageNameRegex = new Regex("^[A-Za-z0-9\\.\\-]{2,49}[A-Za-z0-9\\-]$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private static readonly Regex metroPackageVersionRegex = new Regex("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + private bool IsMobileTarget(BuildTargetGroup targetGroup) + { + return targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.Tizen; + } + public SerializedProperty FindPropertyAssert(string name) + { + SerializedProperty serializedProperty = base.serializedObject.FindProperty(name); + if (serializedProperty == null) + { + Debug.LogError("Failed to find:" + name); + } + return serializedProperty; + } + private void OnEnable() + { + this.validPlatforms = BuildPlayerWindow.GetValidPlatforms().ToArray(); + this.m_PS3TitleConfigPath = this.FindPropertyAssert("ps3TitleConfigPath"); + this.m_PS3DLCConfigPath = this.FindPropertyAssert("ps3DLCConfigPath"); + this.m_PS3ThumbnailPath = this.FindPropertyAssert("ps3ThumbnailPath"); + this.m_PS3BackgroundPath = this.FindPropertyAssert("ps3BackgroundPath"); + this.m_PS3SoundPath = this.FindPropertyAssert("ps3SoundPath"); + this.m_PS3TrophyCommId = this.FindPropertyAssert("ps3TrophyCommId"); + this.m_PS3NpCommunicationPassphrase = this.FindPropertyAssert("ps3NpCommunicationPassphrase"); + this.m_PS3TrophyPackagePath = this.FindPropertyAssert("ps3TrophyPackagePath"); + this.m_PS3BootCheckMaxSaveGameSizeKB = this.FindPropertyAssert("ps3BootCheckMaxSaveGameSizeKB"); + this.m_PS3TrophyCommSig = this.FindPropertyAssert("ps3TrophyCommSig"); + this.m_PS3TrialMode = this.FindPropertyAssert("ps3TrialMode"); + this.m_PS3SaveGameSlots = this.FindPropertyAssert("ps3SaveGameSlots"); + this.m_IPhoneSdkVersion = this.FindPropertyAssert("iPhoneSdkVersion"); + this.m_IPhoneTargetOSVersion = this.FindPropertyAssert("iPhoneTargetOSVersion"); + this.m_IPhoneStrippingLevel = this.FindPropertyAssert("iPhoneStrippingLevel"); + this.m_IPhoneScriptCallOptimization = this.FindPropertyAssert("iPhoneScriptCallOptimization"); + this.m_AndroidProfiler = this.FindPropertyAssert("AndroidProfiler"); + this.m_CompanyName = this.FindPropertyAssert("companyName"); + this.m_ProductName = this.FindPropertyAssert("productName"); + this.m_DefaultCursor = this.FindPropertyAssert("defaultCursor"); + this.m_CursorHotspot = this.FindPropertyAssert("cursorHotspot"); + this.m_UIPrerenderedIcon = this.FindPropertyAssert("uIPrerenderedIcon"); + this.m_ResolutionDialogBanner = this.FindPropertyAssert("resolutionDialogBanner"); + this.m_UIStatusBarHidden = this.FindPropertyAssert("uIStatusBarHidden"); + this.m_UIStatusBarStyle = this.FindPropertyAssert("uIStatusBarStyle"); + this.m_RenderingPath = this.FindPropertyAssert("m_RenderingPath"); + this.m_MobileRenderingPath = this.FindPropertyAssert("m_MobileRenderingPath"); + this.m_ActiveColorSpace = this.FindPropertyAssert("m_ActiveColorSpace"); + this.m_MTRendering = this.FindPropertyAssert("m_MTRendering"); + this.m_MobileMTRendering = this.FindPropertyAssert("m_MobileMTRendering"); + this.m_StripUnusedMeshComponents = this.FindPropertyAssert("StripUnusedMeshComponents"); + this.m_FirstStreamedLevelWithResources = this.FindPropertyAssert("firstStreamedLevelWithResources"); + this.m_IPhoneBundleIdentifier = this.FindPropertyAssert("iPhoneBundleIdentifier"); + this.m_IPhoneBundleVersion = this.FindPropertyAssert("iPhoneBundleVersion"); + this.m_IPhoneShortBundleVersion = this.FindPropertyAssert("iPhoneShortBundleVersion"); + this.m_TargetResolution = this.FindPropertyAssert("targetResolution"); + this.m_AccelerometerFrequency = this.FindPropertyAssert("accelerometerFrequency"); + this.m_OverrideIPodMusic = this.FindPropertyAssert("Override IPod Music"); + this.m_PrepareIOSForRecording = this.FindPropertyAssert("Prepare IOS For Recording"); + this.m_UIRequiresPersistentWiFi = this.FindPropertyAssert("uIRequiresPersistentWiFi"); + this.m_UIExitOnSuspend = this.FindPropertyAssert("uIExitOnSuspend"); + this.m_EnableHWStatistics = this.FindPropertyAssert("enableHWStatistics"); + this.m_ApiCompatibilityLevel = this.FindPropertyAssert("apiCompatibilityLevel"); + this.m_AotOptions = this.FindPropertyAssert("aotOptions"); + this.m_LocationUsageDescription = this.FindPropertyAssert("locationUsageDescription"); + this.m_DefaultScreenWidth = this.FindPropertyAssert("defaultScreenWidth"); + this.m_DefaultScreenHeight = this.FindPropertyAssert("defaultScreenHeight"); + this.m_DefaultScreenWidthWeb = this.FindPropertyAssert("defaultScreenWidthWeb"); + this.m_DefaultScreenHeightWeb = this.FindPropertyAssert("defaultScreenHeightWeb"); + this.m_RunInBackground = this.FindPropertyAssert("runInBackground"); + this.m_DefaultScreenOrientation = this.FindPropertyAssert("defaultScreenOrientation"); + this.m_AllowedAutoRotateToPortrait = this.FindPropertyAssert("allowedAutorotateToPortrait"); + this.m_AllowedAutoRotateToPortraitUpsideDown = this.FindPropertyAssert("allowedAutorotateToPortraitUpsideDown"); + this.m_AllowedAutoRotateToLandscapeRight = this.FindPropertyAssert("allowedAutorotateToLandscapeRight"); + this.m_AllowedAutoRotateToLandscapeLeft = this.FindPropertyAssert("allowedAutorotateToLandscapeLeft"); + this.m_UseOSAutoRotation = this.FindPropertyAssert("useOSAutorotation"); + this.m_Use32BitDisplayBuffer = this.FindPropertyAssert("use32BitDisplayBuffer"); + this.m_Use24BitDepthBuffer = this.FindPropertyAssert("use24BitDepthBuffer"); + this.m_iosShowActivityIndicatorOnLoading = this.FindPropertyAssert("iosShowActivityIndicatorOnLoading"); + this.m_androidShowActivityIndicatorOnLoading = this.FindPropertyAssert("androidShowActivityIndicatorOnLoading"); + this.m_DefaultIsFullScreen = this.FindPropertyAssert("defaultIsFullScreen"); + this.m_DefaultIsNativeResolution = this.FindPropertyAssert("defaultIsNativeResolution"); + this.m_CaptureSingleScreen = this.FindPropertyAssert("captureSingleScreen"); + this.m_DisplayResolutionDialog = this.FindPropertyAssert("displayResolutionDialog"); + this.m_SupportedAspectRatios = this.FindPropertyAssert("m_SupportedAspectRatios"); + this.m_WebPlayerTemplate = this.FindPropertyAssert("webPlayerTemplate"); + this.m_TargetGlesGraphics = this.FindPropertyAssert("targetGlesGraphics"); + this.m_TargetIOSGraphics = this.FindPropertyAssert("targetIOSGraphics"); + this.m_TargetDevice = this.FindPropertyAssert("targetDevice"); + this.m_UsePlayerLog = this.FindPropertyAssert("usePlayerLog"); + this.m_ResizableWindow = this.FindPropertyAssert("resizableWindow"); + this.m_StripPhysics = this.FindPropertyAssert("stripPhysics"); + this.m_UseMacAppStoreValidation = this.FindPropertyAssert("useMacAppStoreValidation"); + this.m_D3D9FullscreenMode = this.FindPropertyAssert("d3d9FullscreenMode"); + this.m_D3D11ForceExclusiveMode = this.FindPropertyAssert("d3d11ForceExclusiveMode"); + this.m_VisibleInBackground = this.FindPropertyAssert("visibleInBackground"); + this.m_MacFullscreenMode = this.FindPropertyAssert("macFullscreenMode"); + this.m_SkinOnGPU = this.FindPropertyAssert("gpuSkinning"); + this.m_ForceSingleInstance = this.FindPropertyAssert("forceSingleInstance"); + this.m_XboxTitleId = this.FindPropertyAssert("XboxTitleId"); + this.m_XboxImageXexPath = this.FindPropertyAssert("XboxImageXexPath"); + this.m_XboxSpaPath = this.FindPropertyAssert("XboxSpaPath"); + this.m_XboxGenerateSpa = this.FindPropertyAssert("XboxGenerateSpa"); + this.m_XboxDeployKinectResources = this.FindPropertyAssert("XboxDeployKinectResources"); + this.m_XboxPIXTextureCapture = this.FindPropertyAssert("xboxPIXTextureCapture"); + this.m_XboxEnableAvatar = this.FindPropertyAssert("xboxEnableAvatar"); + this.m_XboxEnableKinect = this.FindPropertyAssert("xboxEnableKinect"); + this.m_XboxEnableKinectAutoTracking = this.FindPropertyAssert("xboxEnableKinectAutoTracking"); + this.m_XboxSplashScreen = this.FindPropertyAssert("XboxSplashScreen"); + this.m_XboxEnableSpeech = this.FindPropertyAssert("xboxEnableSpeech"); + this.m_XboxSpeechDB = this.FindPropertyAssert("xboxSpeechDB"); + this.m_XboxEnableFitness = this.FindPropertyAssert("xboxEnableFitness"); + this.m_XboxAdditionalTitleMemorySize = this.FindPropertyAssert("xboxAdditionalTitleMemorySize"); + this.m_XboxEnableHeadOrientation = this.FindPropertyAssert("xboxEnableHeadOrientation"); + this.m_XboxDeployHeadOrientation = this.FindPropertyAssert("xboxDeployKinectHeadOrientation"); + this.m_XboxDeployKinectHeadPosition = this.FindPropertyAssert("xboxDeployKinectHeadPosition"); + this.m_XboxEnableGuest = this.FindPropertyAssert("xboxEnableGuest"); + this.m_FlashStrippingLevel = this.FindPropertyAssert("flashStrippingLevel"); + this.m_PSP2SplashScreen = this.FindPropertyAssert("psp2Splashimage"); + this.m_PSP2LiveAreaGate = this.FindPropertyAssert("psp2LiveAreaGate"); + this.m_PSP2LiveAreaBackground = this.FindPropertyAssert("psp2LiveAreaBackround"); + this.m_PSP2NPCommsID = this.FindPropertyAssert("psp2NPCommsID"); + this.m_PSP2NPCommsPassphrase = this.FindPropertyAssert("psp2NPCommsPassphrase"); + this.m_PSP2NPCommsSig = this.FindPropertyAssert("psp2NPCommsSig"); + this.m_PSP2TrophyPackPath = this.FindPropertyAssert("psp2NPTrophyPackPath"); + this.m_PSP2ParamSfxPath = this.FindPropertyAssert("psp2ParamSfxPath"); + this.m_PSP2PackagePassword = this.FindPropertyAssert("psp2PackagePassword"); + this.m_VideoMemoryForVertexBuffers = this.FindPropertyAssert("videoMemoryForVertexBuffers"); + this.m_MetroPackageName = this.FindPropertyAssert("metroPackageName"); + this.m_MetroPackageName.stringValue = this.ValidateMetroPackageName(this.m_MetroPackageName.stringValue); + this.m_MetroPackageLogo = this.FindPropertyAssert("metroPackageLogo"); + this.m_MetroPackageLogo140 = this.FindPropertyAssert("metroPackageLogo140"); + this.m_MetroPackageLogo180 = this.FindPropertyAssert("metroPackageLogo180"); + this.m_MetroPackageLogo240 = this.FindPropertyAssert("metroPackageLogo240"); + this.m_MetroPackageVersion = this.FindPropertyAssert("metroPackageVersion"); + this.m_MetroPackageVersion.stringValue = PlayerSettingsEditor.ValidateMetroPackageVersion(this.m_MetroPackageVersion.stringValue); + this.m_MetroApplicationDescription = this.FindPropertyAssert("metroApplicationDescription"); + this.m_MetroApplicationDescription.stringValue = this.ValidateMetroApplicationDescription(this.m_MetroApplicationDescription.stringValue); + this.m_MetroStoreTileLogo80 = this.FindPropertyAssert("metroStoreTileLogo80"); + this.m_MetroStoreTileLogo = this.FindPropertyAssert("metroStoreTileLogo"); + this.m_MetroStoreTileLogo140 = this.FindPropertyAssert("metroStoreTileLogo140"); + this.m_MetroStoreTileLogo180 = this.FindPropertyAssert("metroStoreTileLogo180"); + this.m_MetroStoreTileWideLogo80 = this.FindPropertyAssert("metroStoreTileWideLogo80"); + this.m_MetroStoreTileWideLogo = this.FindPropertyAssert("metroStoreTileWideLogo"); + this.m_MetroStoreTileWideLogo140 = this.FindPropertyAssert("metroStoreTileWideLogo140"); + this.m_MetroStoreTileWideLogo180 = this.FindPropertyAssert("metroStoreTileWideLogo180"); + this.m_MetroStoreTileSmallLogo80 = this.FindPropertyAssert("metroStoreTileSmallLogo80"); + this.m_MetroStoreTileSmallLogo = this.FindPropertyAssert("metroStoreTileSmallLogo"); + this.m_MetroStoreTileSmallLogo140 = this.FindPropertyAssert("metroStoreTileSmallLogo140"); + this.m_MetroStoreTileSmallLogo180 = this.FindPropertyAssert("metroStoreTileSmallLogo180"); + this.m_MetroStoreSmallTile80 = this.FindPropertyAssert("metroStoreSmallTile80"); + this.m_MetroStoreSmallTile = this.FindPropertyAssert("metroStoreSmallTile"); + this.m_MetroStoreSmallTile140 = this.FindPropertyAssert("metroStoreSmallTile140"); + this.m_MetroStoreSmallTile180 = this.FindPropertyAssert("metroStoreSmallTile180"); + this.m_MetroStoreLargeTile80 = this.FindPropertyAssert("metroStoreLargeTile80"); + this.m_MetroStoreLargeTile = this.FindPropertyAssert("metroStoreLargeTile"); + this.m_MetroStoreLargeTile140 = this.FindPropertyAssert("metroStoreLargeTile140"); + this.m_MetroStoreLargeTile180 = this.FindPropertyAssert("metroStoreLargeTile180"); + this.m_MetroStoreSplashScreenImage = this.FindPropertyAssert("metroStoreSplashScreenImage"); + this.m_MetroStoreSplashScreenImage140 = this.FindPropertyAssert("metroStoreSplashScreenImage140"); + this.m_MetroStoreSplashScreenImage180 = this.FindPropertyAssert("metroStoreSplashScreenImage180"); + this.m_MetroPhoneAppIcon = this.FindPropertyAssert("metroPhoneAppIcon"); + this.m_MetroPhoneAppIcon140 = this.FindPropertyAssert("metroPhoneAppIcon140"); + this.m_MetroPhoneAppIcon240 = this.FindPropertyAssert("metroPhoneAppIcon240"); + this.m_MetroPhoneSmallTile = this.FindPropertyAssert("metroPhoneSmallTile"); + this.m_MetroPhoneSmallTile140 = this.FindPropertyAssert("metroPhoneSmallTile140"); + this.m_MetroPhoneSmallTile240 = this.FindPropertyAssert("metroPhoneSmallTile240"); + this.m_MetroPhoneMediumTile = this.FindPropertyAssert("metroPhoneMediumTile"); + this.m_MetroPhoneMediumTile140 = this.FindPropertyAssert("metroPhoneMediumTile140"); + this.m_MetroPhoneMediumTile240 = this.FindPropertyAssert("metroPhoneMediumTile240"); + this.m_MetroPhoneWideTile = this.FindPropertyAssert("metroPhoneWideTile"); + this.m_MetroPhoneWideTile140 = this.FindPropertyAssert("metroPhoneWideTile140"); + this.m_MetroPhoneWideTile240 = this.FindPropertyAssert("metroPhoneWideTile240"); + this.m_MetroPhoneSplashScreenImage = this.FindPropertyAssert("metroPhoneSplashScreenImage"); + this.m_MetroPhoneSplashScreenImage140 = this.FindPropertyAssert("metroPhoneSplashScreenImage140"); + this.m_MetroPhoneSplashScreenImage240 = this.FindPropertyAssert("metroPhoneSplashScreenImage240"); + this.m_MetroTileShortName = this.FindPropertyAssert("metroTileShortName"); + this.m_MetroTileShortName.stringValue = this.ValidateMetroTileShortName(this.m_MetroTileShortName.stringValue); + this.m_MetroTileBackgroundColor = this.FindPropertyAssert("metroTileBackgroundColor"); + this.m_MetroUnprocessedPlugins = this.FindPropertyAssert("metroUnprocessedPlugins"); + this.m_MetroEnableIndependentInputSource = this.FindPropertyAssert("metroEnableIndependentInputSource"); + this.m_MetroEnableLowLatencyPresentationAPI = this.FindPropertyAssert("metroEnableLowLatencyPresentationAPI"); + this.m_WP8UnprocessedPlugins = this.FindPropertyAssert("wp8UnprocessedPlugins"); + BuildPlayerWindow.BuildPlatform[] array = this.validPlatforms; + for (int i = 0; i < array.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array[i]; + string targetStringFromBuildTargetGroup = ModuleManager.GetTargetStringFromBuildTargetGroup(buildPlatform.targetGroup); + ISettingEditorExtension editorSettingsExtension = ModuleManager.GetEditorSettingsExtension(targetStringFromBuildTargetGroup); + if (editorSettingsExtension != null) + { + editorSettingsExtension.OnEnable(this); + } + } + for (int j = 0; j < this.m_SectionAnimators.Length; j++) + { + this.m_SectionAnimators[j] = new AnimBool(this.m_SelectedSection.value == j, new UnityAction(base.Repaint)); + } + this.m_ShowDeferredWarning.value = (!InternalEditorUtility.HasPro() && PlayerSettings.renderingPath == RenderingPath.DeferredLighting); + this.m_ShowDefaultIsNativeResolution.value = this.m_DefaultIsFullScreen.boolValue; + this.m_ShowResolution.value = (!this.m_DefaultIsFullScreen.boolValue || !this.m_DefaultIsNativeResolution.boolValue); + this.m_ShowDeferredWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowDefaultIsNativeResolution.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowResolution.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + private void OnDisable() + { + PlayerSettingsEditor.WebPlayerTemplate.ClearTemplates(); + } + public override bool UseDefaultMargins() + { + return false; + } + public override void OnInspectorGUI() + { + if (PlayerSettingsEditor.s_Styles == null) + { + PlayerSettingsEditor.s_Styles = new PlayerSettingsEditor.Styles(); + } + base.serializedObject.Update(); + this.m_ShowDeferredWarning.target = (!InternalEditorUtility.HasPro() && PlayerSettings.renderingPath == RenderingPath.DeferredLighting); + EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + this.CommonSettings(); + EditorGUILayout.EndVertical(); + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + int num = this.selectedPlatform; + this.selectedPlatform = EditorGUILayout.BeginPlatformGrouping(this.validPlatforms, null); + if (EditorGUI.EndChangeCheck()) + { + if (EditorGUI.s_DelayedTextEditor.IsEditingControl(this.scriptingDefinesControlID)) + { + EditorGUI.EndEditingActiveTextField(); + GUIUtility.keyboardControl = 0; + PlayerSettings.SetScriptingDefineSymbolsForGroup(this.validPlatforms[num].targetGroup, EditorGUI.s_DelayedTextEditor.content.text); + } + GUI.FocusControl(string.Empty); + } + GUILayout.Label("Settings for " + this.validPlatforms[this.selectedPlatform].title.text, new GUILayoutOption[0]); + EditorGUIUtility.labelWidth = Mathf.Max(150f, EditorGUIUtility.labelWidth - 8f); + BuildPlayerWindow.BuildPlatform buildPlatform = this.validPlatforms[this.selectedPlatform]; + BuildTargetGroup targetGroup = buildPlatform.targetGroup; + string targetStringFromBuildTargetGroup = ModuleManager.GetTargetStringFromBuildTargetGroup(targetGroup); + ISettingEditorExtension editorSettingsExtension = ModuleManager.GetEditorSettingsExtension(targetStringFromBuildTargetGroup); + this.ResolutionSectionGUI(targetGroup, editorSettingsExtension); + this.IconSectionGUI(targetGroup); + this.SplashSectionGUI(buildPlatform, targetGroup, editorSettingsExtension); + this.OtherSectionGUI(buildPlatform, targetGroup, editorSettingsExtension); + this.PublishSectionGUI(targetGroup, editorSettingsExtension); + EditorGUILayout.EndPlatformGrouping(); + base.serializedObject.ApplyModifiedProperties(); + } + private void CommonSettings() + { + EditorGUILayout.PropertyField(this.m_CompanyName, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ProductName, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUI.changed = false; + string empty = string.Empty; + Texture2D[] array = PlayerSettings.GetIconsForPlatform(empty); + int[] iconSizesForPlatform = PlayerSettings.GetIconSizesForPlatform(empty); + if (array.Length != iconSizesForPlatform.Length) + { + array = new Texture2D[iconSizesForPlatform.Length]; + PlayerSettings.SetIconsForPlatform(empty, array); + } + array[0] = (Texture2D)EditorGUILayout.ObjectField(PlayerSettingsEditor.s_Styles.defaultIcon, array[0], typeof(Texture2D), false, new GUILayoutOption[0]); + if (GUI.changed) + { + PlayerSettings.SetIconsForPlatform(empty, array); + } + GUILayout.Space(3f); + this.m_DefaultCursor.objectReferenceValue = EditorGUILayout.ObjectField(PlayerSettingsEditor.s_Styles.defaultCursor, this.m_DefaultCursor.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, 0, PlayerSettingsEditor.s_Styles.cursorHotspot); + EditorGUI.PropertyField(rect, this.m_CursorHotspot, GUIContent.none); + } + private bool BeginSettingsBox(int nr, GUIContent header) + { + bool enabled = GUI.enabled; + GUI.enabled = true; + EditorGUILayout.BeginVertical(PlayerSettingsEditor.s_Styles.categoryBox, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(20f, 18f); + rect.x += 3f; + rect.width += 6f; + bool flag = GUI.Toggle(rect, this.m_SelectedSection.value == nr, header, EditorStyles.inspectorTitlebarText); + if (GUI.changed) + { + this.m_SelectedSection.value = ((!flag) ? -1 : nr); + } + this.m_SectionAnimators[nr].target = flag; + GUI.enabled = enabled; + return EditorGUILayout.BeginFadeGroup(this.m_SectionAnimators[nr].faded); + } + private void EndSettingsBox() + { + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.EndVertical(); + } + private void ShowNoSettings() + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.NotApplicableForPlatform"), EditorStyles.miniLabel, new GUILayoutOption[0]); + } + private void ShowSharedNote() + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.SharedSettingsFootnote"), EditorStyles.miniLabel, new GUILayoutOption[0]); + } + private void IconSectionGUI(BuildTargetGroup targetGroup) + { + GUI.changed = false; + if (this.BeginSettingsBox(1, EditorGUIUtility.TextContent("PlayerSettings.IconHeader"))) + { + bool flag = this.selectedPlatform < 0; + BuildPlayerWindow.BuildPlatform buildPlatform = null; + targetGroup = BuildTargetGroup.Standalone; + string platform = string.Empty; + if (!flag) + { + buildPlatform = this.validPlatforms[this.selectedPlatform]; + targetGroup = buildPlatform.targetGroup; + platform = buildPlatform.name; + } + bool enabled = GUI.enabled; + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.WP8) + { + this.ShowNoSettings(); + EditorGUILayout.Space(); + } + else + { + if (targetGroup == BuildTargetGroup.Metro) + { + float num = 16f; + float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; + this.MetroLogoSection(num2, num2, num, num); + } + else + { + Texture2D[] array = PlayerSettings.GetIconsForPlatform(platform); + int[] iconSizesForPlatform = PlayerSettings.GetIconSizesForPlatform(platform); + bool flag2 = true; + if (flag) + { + if (array.Length != iconSizesForPlatform.Length) + { + array = new Texture2D[iconSizesForPlatform.Length]; + PlayerSettings.SetIconsForPlatform(platform, array); + } + } + else + { + GUI.changed = false; + flag2 = (array.Length == iconSizesForPlatform.Length); + flag2 = GUILayout.Toggle(flag2, "Override for " + buildPlatform.name, new GUILayoutOption[0]); + GUI.enabled = (enabled && flag2); + if (GUI.changed || (!flag2 && array.Length > 0)) + { + if (flag2) + { + array = new Texture2D[iconSizesForPlatform.Length]; + } + else + { + array = new Texture2D[0]; + } + PlayerSettings.SetIconsForPlatform(platform, array); + } + } + GUI.changed = false; + for (int i = 0; i < iconSizesForPlatform.Length; i++) + { + int num3 = Mathf.Min(96, iconSizesForPlatform[i]); + Rect rect = GUILayoutUtility.GetRect(64f, (float)(Mathf.Max(64, num3) + 6)); + float num4 = Mathf.Min(rect.width, EditorGUIUtility.labelWidth + 4f + 64f + 6f + 96f); + string text = iconSizesForPlatform[i] + "x" + iconSizesForPlatform[i]; + GUI.Label(new Rect(rect.x, rect.y, num4 - 96f - 64f - 12f, 20f), text); + if (flag2) + { + array[i] = (Texture2D)EditorGUI.ObjectField(new Rect(rect.x + num4 - 96f - 64f - 6f, rect.y, 64f, 64f), array[i], typeof(Texture2D), false); + } + Rect position = new Rect(rect.x + num4 - 96f, rect.y, (float)num3, (float)num3); + Texture2D iconForPlatformAtSize = PlayerSettings.GetIconForPlatformAtSize(platform, iconSizesForPlatform[i]); + if (iconForPlatformAtSize != null) + { + GUI.DrawTexture(position, iconForPlatformAtSize); + } + else + { + GUI.Box(position, string.Empty); + } + } + if (GUI.changed) + { + PlayerSettings.SetIconsForPlatform(platform, array); + } + GUI.enabled = enabled; + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_UIPrerenderedIcon, EditorGUIUtility.TextContent("PlayerSettings.UIPrerenderedIcon"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + } + } + } + this.EndSettingsBox(); + } + private void SplashSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) + { + GUI.changed = false; + if (this.BeginSettingsBox(2, EditorGUIUtility.TextContent("PlayerSettings.SplashHeader"))) + { + if (targetGroup == BuildTargetGroup.Standalone) + { + this.m_ResolutionDialogBanner.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.ResolutionDialogBanner"), (Texture2D)this.m_ResolutionDialogBanner.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.NaCl || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.WP8) + { + this.ShowNoSettings(); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.XBOX360) + { + this.m_XboxSplashScreen.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.XboxSplashScreen"), (Texture2D)this.m_XboxSplashScreen.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM) + { + this.m_PSP2SplashScreen.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2SplashScreen"), (Texture2D)this.m_PSP2SplashScreen.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget)); + if (targetGroup == BuildTargetGroup.Metro) + { + float num = 16f; + float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; + this.MetroSplashScreenSection(num2, num2, num, num); + } + if (settingsExtension != null) + { + settingsExtension.SplashSectionGUI(); + } + EditorGUI.EndDisabledGroup(); + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + { + this.ShowSharedNote(); + } + } + this.EndSettingsBox(); + } + public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) + { + GUI.changed = false; + if (this.BeginSettingsBox(0, EditorGUIUtility.TextContent("PlayerSettings.ResolutionHeader"))) + { + if (targetGroup == BuildTargetGroup.Standalone) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ResolutionSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DefaultIsFullScreen, new GUILayoutOption[0]); + this.m_ShowDefaultIsNativeResolution.target = this.m_DefaultIsFullScreen.boolValue; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowDefaultIsNativeResolution.faded)) + { + EditorGUILayout.PropertyField(this.m_DefaultIsNativeResolution, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + this.m_ShowResolution.target = (!this.m_DefaultIsFullScreen.boolValue || !this.m_DefaultIsNativeResolution.boolValue); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowResolution.faded)) + { + EditorGUILayout.PropertyField(this.m_DefaultScreenWidth, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenWidth"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DefaultScreenHeight, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenHeight"), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + } + if (targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.NaCl) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ResolutionSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DefaultScreenWidthWeb, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenWidthWeb"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DefaultScreenHeightWeb, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenHeightWeb"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.XBOX360) + { + this.ShowNoSettings(); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.Metro) + { + this.ShowNoSettings(); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.BB10) + { + EditorGUILayout.PropertyField(this.m_RunInBackground, EditorGUIUtility.TextContent("PlayerSettings.RunInBackground"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone || (settingsExtension != null && settingsExtension.SupportsOrientation()) || targetGroup == BuildTargetGroup.WP8) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ScreenOrientationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DefaultScreenOrientation, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenOrientation"), new GUILayoutOption[0]); + if (this.m_DefaultScreenOrientation.enumValueIndex == 4) + { + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_UseOSAutoRotation, EditorGUIUtility.TextContent("PlayerSettings.UseOSAutorotation"), new GUILayoutOption[0]); + } + EditorGUI.indentLevel++; + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.AutoRotationAllowedOrientation"), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (!this.m_AllowedAutoRotateToPortrait.boolValue && !this.m_AllowedAutoRotateToPortraitUpsideDown.boolValue && !this.m_AllowedAutoRotateToLandscapeRight.boolValue && !this.m_AllowedAutoRotateToLandscapeLeft.boolValue) + { + this.m_AllowedAutoRotateToPortrait.boolValue = true; + Debug.LogError("All orientations are disabled. Allowing portrait"); + } + EditorGUILayout.PropertyField(this.m_AllowedAutoRotateToPortrait, EditorGUIUtility.TextContent("PlayerSettings.PortraitOrientation"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AllowedAutoRotateToPortraitUpsideDown, EditorGUIUtility.TextContent("PlayerSettings.PortraitUpsideDownOrientation"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AllowedAutoRotateToLandscapeRight, EditorGUIUtility.TextContent("PlayerSettings.LandscapeRightOrientation"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AllowedAutoRotateToLandscapeLeft, EditorGUIUtility.TextContent("PlayerSettings.LandscapeLeftOrientation"), new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + { + if (targetGroup != BuildTargetGroup.WP8) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.StatusBarSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UIStatusBarHidden, EditorGUIUtility.TextContent("PlayerSettings.UIStatusBarHidden"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_UIStatusBarStyle, EditorGUIUtility.TextContent("PlayerSettings.UIStatusBarStyle"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + } + EditorGUILayout.Space(); + if (targetGroup == BuildTargetGroup.Standalone) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.StandalonePlayerSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CaptureSingleScreen, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DisplayResolutionDialog, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UsePlayerLog, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ResizableWindow, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UseMacAppStoreValidation, EditorGUIUtility.TempContent("Mac App Store Validation"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MacFullscreenMode, new GUILayoutOption[0]); + bool useDirect3D = PlayerSettings.useDirect3D11; + bool flag = this.m_D3D9FullscreenMode.intValue == 0; + if (useDirect3D) + { + this.m_D3D9FullscreenMode.intValue = 1; + } + EditorGUI.BeginDisabledGroup(useDirect3D); + EditorGUILayout.PropertyField(this.m_D3D9FullscreenMode, EditorGUIUtility.TempContent("D3D9 Fullscreen Mode"), new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!useDirect3D); + EditorGUILayout.PropertyField(this.m_D3D11ForceExclusiveMode, new GUIContent("D3D11 Force Exclusive Mode", "Only recommended to fix Oculus vsync. There are known issues with alt-tab."), new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (!useDirect3D && flag) + { + this.m_VisibleInBackground.boolValue = false; + } + EditorGUI.BeginDisabledGroup(!useDirect3D && flag); + EditorGUILayout.PropertyField(this.m_VisibleInBackground, EditorGUIUtility.TempContent("Visible In Background"), new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.PropertyField(this.m_ForceSingleInstance, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SupportedAspectRatios, true, new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.WebPlayer) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WebPlayerTemplateSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length < 1) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.NoTemplatesFound"), new GUILayoutOption[0]); + } + else + { + int num = Mathf.Min((int)Mathf.Max(((float)Screen.width - 30f) / 80f, 1f), PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length); + int num2 = Mathf.Max((int)Mathf.Ceil((float)PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length / (float)num), 1); + bool changed = GUI.changed; + this.m_WebPlayerTemplate.stringValue = PlayerSettingsEditor.WebPlayerTemplate.Templates[PlayerSettingsEditor.ThumbnailList(GUILayoutUtility.GetRect((float)num * 80f, (float)num2 * 100f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }), PlayerSettingsEditor.WebPlayerTemplate.GetTemplateIndex(this.m_WebPlayerTemplate.stringValue), PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails, num)].ToString(); + bool flag2 = !changed && GUI.changed; + bool changed2 = GUI.changed; + GUI.changed = false; + string[] templateCustomKeys = PlayerSettings.templateCustomKeys; + for (int i = 0; i < templateCustomKeys.Length; i++) + { + string text = templateCustomKeys[i]; + string text2 = PlayerSettings.GetTemplateCustomValue(text); + text2 = EditorGUILayout.TextField(PlayerSettingsEditor.PrettyTemplateKeyName(text), text2, new GUILayoutOption[0]); + PlayerSettings.SetTemplateCustomValue(text, text2); + } + if (GUI.changed) + { + base.serializedObject.Update(); + } + GUI.changed |= changed2; + if (flag2) + { + GUIUtility.hotControl = 0; + GUIUtility.keyboardControl = 0; + base.serializedObject.ApplyModifiedProperties(); + PlayerSettings.templateCustomKeys = PlayerSettingsEditor.WebPlayerTemplate.Templates[PlayerSettingsEditor.WebPlayerTemplate.GetTemplateIndex(this.m_WebPlayerTemplate.stringValue)].CustomKeys; + base.serializedObject.Update(); + } + } + EditorGUILayout.Space(); + } + if (this.IsMobileTarget(targetGroup)) + { + if (targetGroup != BuildTargetGroup.Tizen) + { + EditorGUILayout.PropertyField(this.m_Use32BitDisplayBuffer, EditorGUIUtility.TextContent("PlayerSettings.Use32BitDisplayBuffer"), new GUILayoutOption[0]); + } + EditorGUILayout.PropertyField(this.m_Use24BitDepthBuffer, EditorGUIUtility.TextContent("PlayerSettings.Use24BitDepthBuffer"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_iosShowActivityIndicatorOnLoading, EditorGUIUtility.TextContent("PlayerSettings.iosShowActivityIndicatorOnLoading"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Android) + { + EditorGUILayout.PropertyField(this.m_androidShowActivityIndicatorOnLoading, EditorGUIUtility.TextContent("PlayerSettings.androidShowActivityIndicatorOnLoading"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + { + EditorGUILayout.Space(); + } + this.ShowSharedNote(); + } + this.EndSettingsBox(); + } + private void ShowDisabledFakeEnumPopup(PlayerSettingsEditor.FakeEnum enumValue) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(this.m_ApiCompatibilityLevel.displayName); + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.EnumPopup(enumValue, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + } + private void ShowAdvancedOptionWarning(string option, BuildTarget target) + { + if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(target)) + { + GUIContent gUIContent = new GUIContent(option + " requires " + BuildPipeline.GetBuildTargetAdvancedLicenseName(target)); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning); + } + } + private void DX11SettingGUI(BuildTargetGroup targetGroup) + { + if (targetGroup != BuildTargetGroup.Standalone && targetGroup != BuildTargetGroup.WebPlayer) + { + return; + } + bool flag = Application.platform == RuntimePlatform.WindowsEditor; + bool useDirect3D = PlayerSettings.useDirect3D11; + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + bool flag2 = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.UseDX11"), useDirect3D, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (flag2 != useDirect3D) + { + if (flag) + { + if (EditorUtility.DisplayDialog("Changing graphics device", "Changing DX11 option requires reloading all graphics objects, it might take a while", "Apply", "Cancel") && EditorApplication.SaveCurrentSceneIfUserWantsTo()) + { + PlayerSettings.useDirect3D11 = flag2; + ShaderUtil.RecreateGfxDevice(); + GUIUtility.ExitGUI(); + } + } + else + { + PlayerSettings.useDirect3D11 = flag2; + } + } + if (flag2) + { + if (!flag) + { + EditorGUILayout.HelpBox(EditorGUIUtility.TextContent("PlayerSettings.DX11Warning").text, MessageType.Warning); + } + else + { + if (!SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 11")) + { + EditorGUILayout.HelpBox(EditorGUIUtility.TextContent("PlayerSettings.DX11NotSupported").text, MessageType.Warning); + } + } + } + } + public static void BuildDisabledEnumPopup(GUIContent selected, string uiString) + { + EditorGUI.BeginDisabledGroup(true); + EditorGUI.Popup(EditorGUILayout.GetControlRect(true, new GUILayoutOption[0]), EditorGUIUtility.TextContent(uiString), 0, new GUIContent[] + { + selected + }); + EditorGUI.EndDisabledGroup(); + } + public static int BuildEnumPopup(int value, string uiString, string textPrefixOptional, T[] options) + { + T t = (T)((object)value); + int selectedIndex = 0; + for (int i = 1; i < options.Length; i++) + { + if (t.Equals(options[i])) + { + selectedIndex = i; + break; + } + } + GUIContent[] array = new GUIContent[options.Length]; + for (int j = 0; j < options.Length; j++) + { + array[j] = ((textPrefixOptional != null) ? EditorGUIUtility.TextContent(string.Format("{0}.{1}", textPrefixOptional, (int)((object)options[j]))) : new GUIContent(options[j].ToString())); + } + int num = EditorGUILayout.Popup(EditorGUIUtility.TextContent(uiString), selectedIndex, array, new GUILayoutOption[0]); + return (int)((object)options[num]); + } + public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) + { + GUI.changed = false; + if (this.BeginSettingsBox(3, EditorGUIUtility.TextContent("PlayerSettings.OtherHeader"))) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.RenderingSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || this.IsMobileTarget(targetGroup)) + { + bool flag = this.IsMobileTarget(targetGroup); + EditorGUILayout.PropertyField((!flag) ? this.m_RenderingPath : this.m_MobileRenderingPath, EditorGUIUtility.TextContent("PlayerSettings.RenderingPath"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer) + { + if (EditorGUILayout.BeginFadeGroup(this.m_ShowDeferredWarning.faded)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("CameraEditor.DeferredProOnly"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + } + if ((targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.XBOX360) && InternalEditorUtility.HasPro()) + { + EditorGUILayout.PropertyField(this.m_ActiveColorSpace, EditorGUIUtility.TextContent("PlayerSettings.ActiveColorSpace"), new GUILayoutOption[0]); + if (QualitySettings.activeColorSpace != QualitySettings.desiredColorSpace) + { + EditorGUILayout.HelpBox(PlayerSettingsEditor.s_Styles.colorSpaceWarning.text, MessageType.Warning); + } + } + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.Android) + { + if (this.IsMobileTarget(targetGroup)) + { + this.m_MobileMTRendering.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.MultithreadedRendering"), this.m_MobileMTRendering.boolValue, new GUILayoutOption[0]); + } + else + { + this.m_MTRendering.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.MultithreadedRendering"), this.m_MTRendering.boolValue, new GUILayoutOption[0]); + } + } + this.DX11SettingGUI(targetGroup); + bool flag2 = targetGroup != BuildTargetGroup.PS3; + bool flag3 = targetGroup != BuildTargetGroup.PS3 && targetGroup != BuildTargetGroup.XBOX360; + int num; + int num2; + PlayerSettings.GetBatchingForPlatform(platform.DefaultTarget, out num, out num2); + bool flag4 = false; + if (!flag2 && num == 1) + { + num = 0; + flag4 = true; + } + if (!flag3 && num2 == 1) + { + num2 = 0; + flag4 = true; + } + if (flag4) + { + PlayerSettings.SetBatchingForPlatform(platform.DefaultTarget, num, num2); + } + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget) || !flag2); + if (GUI.enabled) + { + num = ((!EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.StaticBatching"), num != 0, new GUILayoutOption[0])) ? 0 : 1); + } + else + { + EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.StaticBatching"), false, new GUILayoutOption[0]); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!flag3); + num2 = ((!EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.DynamicBatching"), num2 != 0, new GUILayoutOption[0])) ? 0 : 1); + EditorGUI.EndDisabledGroup(); + this.ShowAdvancedOptionWarning("Static Batching", platform.DefaultTarget); + if (GUI.changed) + { + Undo.RecordObject(this.target, "Changed Batching Settings"); + PlayerSettings.SetBatchingForPlatform(platform.DefaultTarget, num, num2); + } + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Metro) + { + bool flag5 = InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget); + EditorGUI.BeginDisabledGroup(!flag5); + if (GUI.enabled) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_SkinOnGPU, EditorGUIUtility.TextContent("PlayerSettings.GPUSkinning"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + ShaderUtil.RecreateSkinnedMeshResources(); + } + } + else + { + EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.GPUSkinning"), false, new GUILayoutOption[0]); + } + EditorGUI.EndDisabledGroup(); + if (!flag5) + { + this.ShowAdvancedOptionWarning("GPU skinning", platform.DefaultTarget); + } + } + if (targetGroup == BuildTargetGroup.XBOX360) + { + this.m_XboxPIXTextureCapture.boolValue = EditorGUILayout.Toggle("Enable PIX texture capture", this.m_XboxPIXTextureCapture.boolValue, new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.Metro) + { + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget)); + if (GUI.enabled) + { + PlayerSettings.stereoscopic3D = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.Stereo3D"), PlayerSettings.stereoscopic3D, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.Stereo3D"), false, new GUILayoutOption[0]); + } + EditorGUI.EndDisabledGroup(); + } + EditorGUILayout.Space(); + if (targetGroup == BuildTargetGroup.WebPlayer) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.StreamingSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_FirstStreamedLevelWithResources, EditorGUIUtility.TextContent("PlayerSettings.FirstStreamedLevelWithResources"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + if (targetGroup == BuildTargetGroup.iPhone || (settingsExtension != null && settingsExtension.HasIdentificationGUI())) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.IdentificationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IPhoneBundleIdentifier, EditorGUIUtility.TextContent("PlayerSettings.IPhoneBundleIdentifier"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IPhoneBundleVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneBundleVersion"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IPhoneShortBundleVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneShortBundleVersion"), new GUILayoutOption[0]); + if (settingsExtension != null) + { + settingsExtension.IdentificationSectionGUI(); + } + EditorGUILayout.Space(); + } + if (targetGroup != BuildTargetGroup.FlashPlayer) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ConfigurationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (targetGroup == BuildTargetGroup.iPhone) + { + ScriptingImplementation[] options = new ScriptingImplementation[] + { + ScriptingImplementation.Mono2x, + ScriptingImplementation.IL2CPP + }; + iPhoneArchitecture[] options2 = new iPhoneArchitecture[] + { + iPhoneArchitecture.ARMv7, + iPhoneArchitecture.ARM64, + iPhoneArchitecture.Universal + }; + int num3 = 0; + PlayerSettings.GetPropertyOptionalInt("ScriptingBackend", ref num3, targetGroup); + int num4 = PlayerSettingsEditor.BuildEnumPopup(num3, "PlayerSettings.ScriptingBackend", "PlayerSettings.ScriptingBackend", options); + if (num4 != num3) + { + PlayerSettings.SetPropertyInt("ScriptingBackend", num4, targetGroup); + } + int propertyInt = PlayerSettings.GetPropertyInt("Architecture", targetGroup); + int num5; + if (num3 == 1) + { + num5 = PlayerSettingsEditor.BuildEnumPopup(propertyInt, "PlayerSettings.iOS.Architecture", null, options2); + } + else + { + num5 = 0; + PlayerSettingsEditor.BuildDisabledEnumPopup(new GUIContent("ARMv7"), "PlayerSettings.iOS.Architecture"); + } + if (num5 != propertyInt) + { + PlayerSettings.SetPropertyInt("Architecture", num5, targetGroup); + } + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.WP8) + { + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_TargetDevice, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_TargetResolution, EditorGUIUtility.TextContent("PlayerSettings.TargetResolution"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10) + { + EditorGUILayout.PropertyField(this.m_TargetGlesGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetGlesGraphics"), new GUILayoutOption[0]); + } + else + { + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_TargetIOSGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetIOSGraphics"), new GUILayoutOption[0]); + } + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.WP8) + { + EditorGUILayout.PropertyField(this.m_AccelerometerFrequency, EditorGUIUtility.TextContent("PlayerSettings.AccelerometerFrequency"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_LocationUsageDescription, EditorGUIUtility.TextContent("PlayerSettings.IOSLocationUsageDescription"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_OverrideIPodMusic, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PrepareIOSForRecording, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UIRequiresPersistentWiFi, EditorGUIUtility.TextContent("PlayerSettings.UIRequiresPersistentWiFi"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UIExitOnSuspend, EditorGUIUtility.TextContent("PlayerSettings.UIExitOnSuspend"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_EnableHWStatistics, EditorGUIUtility.TextContent("PlayerSettings.enableHWStatistics"), new GUILayoutOption[0]); + } + } + if (settingsExtension != null) + { + settingsExtension.ConfigurationSectionGUI(); + } + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.scriptingDefineSymbols"), new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + string defines = EditorGUILayout.DelayedTextField(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup), null, EditorStyles.textField, new GUILayoutOption[0]); + this.scriptingDefinesControlID = EditorGUIUtility.s_LastControlID; + if (EditorGUI.EndChangeCheck()) + { + PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines); + } + EditorGUILayout.Space(); + } + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.OptimizationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (targetGroup == BuildTargetGroup.WebPlayer) + { + this.ShowDisabledFakeEnumPopup(PlayerSettingsEditor.FakeEnum.WebplayerSubset); + } + else + { + if (targetGroup == BuildTargetGroup.FlashPlayer) + { + this.ShowDisabledFakeEnumPopup(PlayerSettingsEditor.FakeEnum.FlashPlayerSubset); + EditorGUILayout.PropertyField(this.m_FlashStrippingLevel, EditorGUIUtility.TextContent("PlayerSettings.flashStrippingLevel"), new GUILayoutOption[0]); + } + else + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_ApiCompatibilityLevel, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + PlayerSettings.SetApiCompatibilityInternal(this.m_ApiCompatibilityLevel.intValue); + } + } + } + if (targetGroup == BuildTargetGroup.NaCl || targetGroup == BuildTargetGroup.FlashPlayer) + { + EditorGUILayout.PropertyField(this.m_StripPhysics, EditorGUIUtility.TextContent("PlayerSettings.StripPhysics"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2) + { + EditorGUILayout.PropertyField(this.m_AotOptions, EditorGUIUtility.TextContent("PlayerSettings.aotOptions"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.Tizen || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne) + { + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_IPhoneSdkVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneSdkVersion"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IPhoneTargetOSVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneTargetOSVersion"), new GUILayoutOption[0]); + } + if (InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget)) + { + EditorGUILayout.PropertyField(this.m_IPhoneStrippingLevel, EditorGUIUtility.TextContent("PlayerSettings.IPhoneStrippingLevel"), new GUILayoutOption[0]); + } + else + { + EditorGUI.BeginDisabledGroup(true); + int[] optionValues = new int[1]; + GUIContent[] displayedOptions = new GUIContent[] + { + new GUIContent("Disabled") + }; + EditorGUILayout.IntPopup(EditorGUIUtility.TextContent("PlayerSettings.IPhoneStrippingLevel"), 0, displayedOptions, optionValues, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + } + if (targetGroup == BuildTargetGroup.iPhone) + { + EditorGUILayout.PropertyField(this.m_IPhoneScriptCallOptimization, EditorGUIUtility.TextContent("PlayerSettings.IPhoneScriptCallOptimization"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Android) + { + EditorGUILayout.PropertyField(this.m_AndroidProfiler, EditorGUIUtility.TextContent("PlayerSettings.AndroidProfiler"), new GUILayoutOption[0]); + } + EditorGUILayout.Space(); + } + EditorGUILayout.PropertyField(this.m_StripUnusedMeshComponents, EditorGUIUtility.TextContent("PlayerSettings.StripUnusedMeshComponents"), new GUILayoutOption[0]); + if (targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM) + { + EditorGUILayout.PropertyField(this.m_VideoMemoryForVertexBuffers, EditorGUIUtility.TextContent("PlayerSettings.VideoMemoryForVertexBuffers"), new GUILayoutOption[0]); + } + EditorGUILayout.Space(); + this.ShowSharedNote(); + } + this.EndSettingsBox(); + } + private void AutoAssignProperty(SerializedProperty property, string packageDir, string fileName) + { + if (property.stringValue.Length == 0 || !File.Exists(Path.Combine(packageDir, property.stringValue))) + { + string path = Path.Combine(packageDir, fileName); + if (File.Exists(path)) + { + property.stringValue = fileName; + } + } + } + private void ShowBrowseableProperty(SerializedProperty property, string textContent, string extension, string dir, float kLabelFloatMinW, float kLabelFloatMaxW, float h) + { + bool flag = textContent.Length != 0; + if (flag) + { + GUILayout.Label(EditorGUIUtility.TextContent(textContent), EditorStyles.boldLabel, new GUILayoutOption[0]); + } + Rect rect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, h, h, EditorStyles.layerMaskField, null); + float labelWidth = EditorGUIUtility.labelWidth; + Rect position = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth - EditorGUI.indent, rect.height); + Rect position2 = new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, rect.height); + string text = (property.stringValue.Length != 0) ? property.stringValue : "Not selected."; + EditorGUI.TextArea(position2, text, EditorStyles.label); + if (GUI.Button(position, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) + { + property.stringValue = FileUtil.GetLastPathNameComponent(EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, dir, extension)); + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + EditorGUILayout.Space(); + } + internal static void BuildFileBoxButton(SerializedProperty prop, string uiString, string directory, string ext) + { + PlayerSettingsEditor.BuildFileBoxButton(prop, uiString, directory, ext, null); + } + internal static void BuildFileBoxButton(SerializedProperty prop, string uiString, string directory, string ext, Action onSelect) + { + float num = 16f; + float minWidth = 80f + EditorGUIUtility.fieldWidth + 5f; + float maxWidth = 80f + EditorGUIUtility.fieldWidth + 5f; + Rect rect = GUILayoutUtility.GetRect(minWidth, maxWidth, num, num, EditorStyles.layerMaskField, null); + float labelWidth = EditorGUIUtility.labelWidth; + Rect position = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth - EditorGUI.indent, rect.height); + Rect position2 = new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, rect.height); + string text = (prop.stringValue.Length != 0) ? prop.stringValue : "Not selected."; + EditorGUI.TextArea(position2, text, EditorStyles.label); + if (GUI.Button(position, EditorGUIUtility.TextContent(uiString))) + { + string text2 = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent(uiString).text, directory, ext); + string projectRelativePath = FileUtil.GetProjectRelativePath(text2); + prop.stringValue = ((!(projectRelativePath != string.Empty)) ? text2 : projectRelativePath); + if (onSelect != null) + { + onSelect(); + } + prop.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + } + public void PublishSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) + { + if (targetGroup != BuildTargetGroup.Metro && targetGroup != BuildTargetGroup.WP8 && targetGroup != BuildTargetGroup.XBOX360 && targetGroup != BuildTargetGroup.PS3 && targetGroup != BuildTargetGroup.PSP2 && targetGroup != BuildTargetGroup.PSM && (settingsExtension == null || !settingsExtension.HasPublishSection())) + { + return; + } + GUI.changed = false; + if (this.BeginSettingsBox(4, EditorGUIUtility.TextContent("PlayerSettings.PublishingHeader"))) + { + string text = "Assets"; + string directory = FileUtil.DeleteLastPathNameComponent(Application.dataPath); + float num = 16f; + float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; + float num3 = 80f + EditorGUIUtility.fieldWidth + 5f; + if (settingsExtension != null) + { + settingsExtension.PublishSectionGUI(num, num2, num3); + } + if (targetGroup == BuildTargetGroup.Metro) + { + this.PublishSectionGUIMetro(num2, num3, num, num); + } + if (targetGroup == BuildTargetGroup.WP8) + { + this.PublishSectionGUIWP8(num2, num3, num, num); + } + if (targetGroup == BuildTargetGroup.PS3) + { + string text2 = Path.Combine(Application.dataPath, "PS3 Submission Package"); + if (Directory.Exists(text2)) + { + this.AutoAssignProperty(this.m_PS3TitleConfigPath, text2, "TITLECONFIG.XML"); + this.AutoAssignProperty(this.m_PS3DLCConfigPath, text2, "DLCconfig.txt"); + this.AutoAssignProperty(this.m_PS3ThumbnailPath, text2, "ICON0.PNG"); + this.AutoAssignProperty(this.m_PS3BackgroundPath, text2, "BACKGROUND0.PNG"); + this.AutoAssignProperty(this.m_PS3TrophyPackagePath, text2, "TROPHY.TRP"); + this.AutoAssignProperty(this.m_PS3SoundPath, text2, "SDN0.AT3"); + } + else + { + text2 = text; + } + this.ShowBrowseableProperty(this.m_PS3TitleConfigPath, "PlayerSettings.ps3TitleConfigPath", "xml", text2, num2, num3, num); + this.ShowBrowseableProperty(this.m_PS3DLCConfigPath, "PlayerSettings.ps3DLCConfigPath", "txt", text2, num2, num3, num); + this.ShowBrowseableProperty(this.m_PS3ThumbnailPath, "PlayerSettings.ps3ThumbnailPath", "png", text2, num2, num3, num); + this.ShowBrowseableProperty(this.m_PS3BackgroundPath, "PlayerSettings.ps3BackgroundPath", "png", text2, num2, num3, num); + this.ShowBrowseableProperty(this.m_PS3SoundPath, "PlayerSettings.ps3SoundPath", "at3", text2, num2, num3, num); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyPackagePath"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.ShowBrowseableProperty(this.m_PS3TrophyPackagePath, string.Empty, "trp", text2, num2, num3, num); + EditorGUILayout.PropertyField(this.m_PS3TrophyCommId, EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyCommId"), new GUILayoutOption[0]); + this.m_PS3NpCommunicationPassphrase.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.ps3NpCommunicationPassphrase"), this.m_PS3NpCommunicationPassphrase.stringValue, new GUILayoutOption[] + { + GUILayout.Height(280f) + }); + this.m_PS3TrophyCommSig.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyCommSig"), this.m_PS3TrophyCommSig.stringValue, new GUILayoutOption[] + { + GUILayout.Height(280f) + }); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ps3TitleSettings"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PS3TrialMode, EditorGUIUtility.TextContent("PlayerSettings.ps3TrialMode"), new GUILayoutOption[0]); + this.m_PS3BootCheckMaxSaveGameSizeKB.intValue = EditorGUILayout.IntField(EditorGUIUtility.TextContent("PlayerSettings.ps3BootCheckMaxSaveGameSizeKB"), this.m_PS3BootCheckMaxSaveGameSizeKB.intValue, new GUILayoutOption[0]); + this.m_PS3SaveGameSlots.intValue = EditorGUILayout.IntField(EditorGUIUtility.TextContent("PlayerSettings.ps3SaveGameSlots"), this.m_PS3SaveGameSlots.intValue, new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.PSP2) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveArea"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_PSP2LiveAreaBackground.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveAreaBackround"), (Texture2D)this.m_PSP2LiveAreaBackground.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + this.m_PSP2LiveAreaGate.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveAreaGate"), (Texture2D)this.m_PSP2LiveAreaGate.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2NP"), EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2NPTrophyPath"), new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); + GUIContent gUIContent; + if (this.m_PSP2TrophyPackPath.stringValue.Length == 0) + { + gUIContent = EditorGUIUtility.TextContent("Not selected."); + EditorGUI.BeginDisabledGroup(true); + } + else + { + gUIContent = EditorGUIUtility.TempContent(this.m_PSP2TrophyPackPath.stringValue); + EditorGUI.BeginDisabledGroup(false); + } + float labelWidth = EditorGUIUtility.labelWidth; + Rect position = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth - EditorGUI.indent, rect.height); + Rect position2 = new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, rect.height); + EditorGUI.TextArea(position2, gUIContent.text, EditorStyles.label); + EditorGUI.EndDisabledGroup(); + if (GUI.Button(position, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) + { + string text3 = Directory.GetCurrentDirectory().Replace('\\', '/'); + this.m_PSP2TrophyPackPath.stringValue = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, text3, "trp"); + text3 += "/"; + if (this.m_PSP2TrophyPackPath.stringValue.StartsWith(text3)) + { + this.m_PSP2TrophyPackPath.stringValue = this.m_PSP2TrophyPackPath.stringValue.Substring(text3.Length); + } + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + EditorGUILayout.PropertyField(this.m_PSP2NPCommsID, EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsID"), new GUILayoutOption[0]); + this.m_PSP2NPCommsPassphrase.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsPassphrase"), this.m_PSP2NPCommsPassphrase.stringValue, new GUILayoutOption[] + { + GUILayout.Height(280f) + }); + this.m_PSP2NPCommsSig.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsSig"), this.m_PSP2NPCommsSig.stringValue, new GUILayoutOption[] + { + GUILayout.Height(280f) + }); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2PackageParams"), EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2ParamSfxPath"), new GUILayoutOption[0]); + rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); + GUIContent gUIContent2; + if (this.m_PSP2ParamSfxPath.stringValue.Length == 0) + { + gUIContent2 = EditorGUIUtility.TextContent("Not selected."); + EditorGUI.BeginDisabledGroup(true); + } + else + { + gUIContent2 = EditorGUIUtility.TempContent(this.m_PSP2ParamSfxPath.stringValue); + EditorGUI.BeginDisabledGroup(false); + } + float labelWidth2 = EditorGUIUtility.labelWidth; + Rect position3 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth2 - EditorGUI.indent, rect.height); + Rect position4 = new Rect(rect.x + labelWidth2, rect.y, rect.width - labelWidth2, rect.height); + EditorGUI.TextArea(position4, gUIContent2.text, EditorStyles.label); + EditorGUI.EndDisabledGroup(); + if (GUI.Button(position3, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) + { + string text4 = Directory.GetCurrentDirectory().Replace('\\', '/'); + this.m_PSP2ParamSfxPath.stringValue = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, text4, "sfx"); + text4 += "/"; + if (this.m_PSP2ParamSfxPath.stringValue.StartsWith(text4)) + { + this.m_PSP2ParamSfxPath.stringValue = this.m_PSP2ParamSfxPath.stringValue.Substring(text4.Length); + } + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + EditorGUILayout.PropertyField(this.m_PSP2PackagePassword, EditorGUIUtility.TextContent("PlayerSettings.psp2PackagePassword"), new GUILayoutOption[0]); + if (this.m_PSP2PackagePassword.stringValue.Length == 0) + { + System.Random random = new System.Random(); + StringBuilder stringBuilder = new StringBuilder(); + string text5 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + for (int i = 0; i < 32; i++) + { + int index = random.Next(text5.Length); + stringBuilder.Append(text5[index]); + } + this.m_PSP2PackagePassword.stringValue = stringBuilder.ToString(); + base.serializedObject.ApplyModifiedProperties(); + } + else + { + if (this.m_PSP2PackagePassword.stringValue.Length != 32) + { + GUIContent content = EditorGUIUtility.TextContent("PlayerSettings.psp2PasswordBadLength"); + GUILayout.Label(content, EditorStyles.miniLabel, new GUILayoutOption[0]); + } + } + } + if (targetGroup == BuildTargetGroup.PSM) + { + } + if (targetGroup == BuildTargetGroup.XBOX360) + { + this.m_XboxAdditionalTitleMemorySize = base.serializedObject.FindProperty("xboxAdditionalTitleMemorySize"); + this.m_XboxAdditionalTitleMemorySize.intValue = (int)EditorGUILayout.Slider(EditorGUIUtility.TextContent("PlayerSettings.XboxAdditionalTitleMemorySize"), (float)this.m_XboxAdditionalTitleMemorySize.intValue, 0f, 416f, new GUILayoutOption[0]); + if (this.m_XboxAdditionalTitleMemorySize.intValue > 0) + { + PlayerSettingsEditor.ShowWarning(EditorGUIUtility.TextContent("PlayerSettings.XboxAdditionalTitleMemoryWarning")); + } + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.SubmissionSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_XboxTitleId, EditorGUIUtility.TextContent("PlayerSettings.XboxTitleId"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxImageConversion"), EditorStyles.boldLabel, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); + float labelWidth3 = EditorGUIUtility.labelWidth; + Rect position5 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth3 - EditorGUI.indent, rect.height); + Rect position6 = new Rect(rect.x + labelWidth3, rect.y, rect.width - labelWidth3, rect.height); + string text6 = (this.m_XboxImageXexPath.stringValue.Length != 0) ? this.m_XboxImageXexPath.stringValue : "Not selected."; + EditorGUI.TextArea(position6, text6, EditorStyles.label); + if (GUI.Button(position5, EditorGUIUtility.TextContent("PlayerSettings.XboxImageXEXFile"))) + { + string text7 = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.XboxImageXEXFile").text, directory, "cfg"); + this.m_XboxImageXexPath.stringValue = text7; + text7 = FileUtil.GetProjectRelativePath(text7); + if (text7 != string.Empty) + { + this.m_XboxImageXexPath.stringValue = text7; + } + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxLive"), EditorStyles.boldLabel, new GUILayoutOption[0]); + rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); + float labelWidth4 = EditorGUIUtility.labelWidth; + Rect position7 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth4 - EditorGUI.indent, rect.height); + Rect position8 = new Rect(rect.x + labelWidth4, rect.y, rect.width - labelWidth4, rect.height); + string text8 = (this.m_XboxSpaPath.stringValue.Length != 0) ? this.m_XboxSpaPath.stringValue : "Not selected."; + EditorGUI.TextArea(position8, text8, EditorStyles.label); + if (GUI.Button(position7, EditorGUIUtility.TextContent("PlayerSettings.XboxSpaFile"))) + { + string text9 = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.XboxSpaFile").text, directory, "spa"); + this.m_XboxSpaPath.stringValue = text9; + text9 = FileUtil.GetProjectRelativePath(text9); + if (text9 != string.Empty) + { + this.m_XboxSpaPath.stringValue = text9; + } + if (this.m_XboxTitleId.stringValue.Length == 0) + { + Debug.LogWarning("Title id must be present when using a SPA file."); + } + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } + if (this.m_XboxSpaPath.stringValue.Length > 0) + { + bool boolValue = this.m_XboxGenerateSpa.boolValue; + this.m_XboxGenerateSpa.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.XboxGenerateSPAConfig"), boolValue, new GUILayoutOption[0]); + if (!boolValue && this.m_XboxGenerateSpa.boolValue) + { + InternalEditorUtility.Xbox360GenerateSPAConfig(this.m_XboxSpaPath.stringValue); + } + } + this.m_XboxEnableGuest.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.XboxEnableGuest"), this.m_XboxEnableGuest.boolValue, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxServices"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_XboxEnableAvatar.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.XboxAvatarEnable"), this.m_XboxEnableAvatar.boolValue, new GUILayoutOption[0]); + this.KinectGUI(); + } + } + this.EndSettingsBox(); + } + private void KinectGUI() + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxKinect"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_XboxEnableKinect.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.XboxEnableKinect"), this.m_XboxEnableKinect.boolValue, new GUILayoutOption[0]); + if (this.m_XboxEnableKinect.boolValue) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.m_XboxEnableHeadOrientation.boolValue = GUILayout.Toggle(this.m_XboxEnableHeadOrientation.boolValue, new GUIContent("Head Orientation", "Head orientation support"), new GUILayoutOption[0]); + this.m_XboxEnableKinectAutoTracking.boolValue = GUILayout.Toggle(this.m_XboxEnableKinectAutoTracking.boolValue, new GUIContent("Auto Tracking", "Automatic player tracking"), new GUILayoutOption[0]); + this.m_XboxEnableFitness.boolValue = GUILayout.Toggle(this.m_XboxEnableFitness.boolValue, new GUIContent("Fitness", "Fitness support"), new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.m_XboxEnableSpeech.boolValue = GUILayout.Toggle(this.m_XboxEnableSpeech.boolValue, new GUIContent("Speech", "Speech Recognition Support"), new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + this.m_XboxDeployKinectResources.boolValue = true; + if (this.m_XboxEnableHeadOrientation.boolValue) + { + this.m_XboxDeployHeadOrientation.boolValue = true; + } + } + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxKinectDeployResources"), EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + GUI.enabled = !this.m_XboxEnableKinect.boolValue; + this.m_XboxDeployKinectResources.boolValue = GUILayout.Toggle(this.m_XboxDeployKinectResources.boolValue, new GUIContent("Base", "Identity and Skeleton Database files"), new GUILayoutOption[0]); + GUI.enabled = (!this.m_XboxEnableHeadOrientation.boolValue || !this.m_XboxEnableKinect.boolValue); + this.m_XboxDeployHeadOrientation.boolValue = GUILayout.Toggle(this.m_XboxDeployHeadOrientation.boolValue, new GUIContent("Head Orientation", "Head orientation database"), new GUILayoutOption[0]); + GUI.enabled = true; + this.m_XboxDeployKinectHeadPosition.boolValue = GUILayout.Toggle(this.m_XboxDeployKinectHeadPosition.boolValue, new GUIContent("Head Position", "Head position database"), new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxKinectSpeech"), new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 1) != 0, new GUIContent("en-US", "Speech database: English - US, Canada"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 1) != 0)) ? 0 : 1); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 2) != 0, new GUIContent("fr-CA", "Speech database: French - Canada"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 2) != 0)) ? 0 : 2); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 4) != 0, new GUIContent("en-GB", "Speech database: English - United Kingdom, Ireland"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 4) != 0)) ? 0 : 4); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 8) != 0, new GUIContent("es-MX", "Speech database: Spanish - Mexico"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 8) != 0)) ? 0 : 8); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 16) != 0, new GUIContent("ja-JP", "Speech database: Japanese - Japan"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 16) != 0)) ? 0 : 16); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 32) != 0, new GUIContent("fr-FR", "Speech database: French - France, Switzerland"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 32) != 0)) ? 0 : 32); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 64) != 0, new GUIContent("es-ES", "Speech database: Spanish - Spain"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 64) != 0)) ? 0 : 64); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 128) != 0, new GUIContent("de-DE", "Speech database: German - Germany, Austria, Switzerland"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 128) != 0)) ? 0 : 128); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 256) != 0, new GUIContent("it-IT", "Speech database: Italian - Italy"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 256) != 0)) ? 0 : 256); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 512) != 0, new GUIContent("en-AU", "Speech database: English - Australia, New Zealand"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 512) != 0)) ? 0 : 512); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.m_XboxSpeechDB.intValue ^= ((GUILayout.Toggle((this.m_XboxSpeechDB.intValue & 1024) != 0, new GUIContent("pt-BR", "Speech database: Portuguese - Brazil"), new GUILayoutOption[0]) == ((this.m_XboxSpeechDB.intValue & 1024) != 0)) ? 0 : 1024); + GUILayout.EndHorizontal(); + } + private static void ShowWarning(GUIContent warningMessage) + { + if (PlayerSettingsEditor.s_WarningIcon == null) + { + PlayerSettingsEditor.s_WarningIcon = EditorGUIUtility.LoadIcon("console.warnicon"); + } + warningMessage.image = PlayerSettingsEditor.s_WarningIcon; + GUILayout.Space(5f); + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label(warningMessage, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + public void PublishSectionGUIMetro(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroPackaging"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroPackageName, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageName"), new GUILayoutOption[0]); + this.m_MetroPackageName.stringValue = this.ValidateMetroPackageName(this.m_MetroPackageName.stringValue); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroPackageDisplayName"), new GUIContent(this.m_ProductName.stringValue), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroPackageVersion, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageVersion"), new GUILayoutOption[0]); + this.m_MetroPackageVersion.stringValue = PlayerSettingsEditor.ValidateMetroPackageVersion(this.m_MetroPackageVersion.stringValue); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroPackagePublisherDisplayName"), new GUIContent(this.m_CompanyName.stringValue), new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificate"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePublisher"), new GUIContent(PlayerSettings.Metro.certificateSubject), new GUILayoutOption[0]); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateIssuer"), new GUIContent(PlayerSettings.Metro.certificateIssuer), new GUILayoutOption[0]); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateNotAfter"), new GUIContent((!PlayerSettings.Metro.certificateNotAfter.HasValue) ? null : PlayerSettings.Metro.certificateNotAfter.Value.ToShortDateString()), new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); + Rect position = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); + string text = PlayerSettings.Metro.certificatePath; + GUIContent content; + if (string.IsNullOrEmpty(text)) + { + content = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateSelect"); + } + else + { + content = new GUIContent(FileUtil.GetLastPathNameComponent(text), text); + } + if (GUI.Button(position, content)) + { + text = EditorUtility.OpenFilePanel(null, Application.dataPath, "pfx").Replace('\\', '/'); + string projectRelativePath = FileUtil.GetProjectRelativePath(text); + if (string.IsNullOrEmpty(projectRelativePath) && !string.IsNullOrEmpty(text)) + { + Debug.LogError("Certificate path '" + Path.GetFullPath(text) + "' has to be relative to " + Path.GetFullPath(Application.dataPath + "\\..")); + } + else + { + try + { + if (!PlayerSettings.Metro.SetCertificate(text, null)) + { + MetroCertificatePasswordWindow.Show(text); + } + } + catch (UnityException ex) + { + Debug.LogError(ex.Message); + } + } + } + Rect rect2 = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); + Rect position2 = new Rect(rect2.x + EditorGUIUtility.labelWidth, rect2.y, rect2.width - EditorGUIUtility.labelWidth, rect2.height); + if (GUI.Button(position2, EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreate"))) + { + MetroCreateTestCertificateWindow.Show(this.m_CompanyName.stringValue); + } + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroApplication"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroApplicationDisplayName"), new GUIContent(this.m_ProductName.stringValue), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroApplicationDescription, EditorGUIUtility.TextContent("PlayerSettings.MetroApplicationDescription"), new GUILayoutOption[0]); + this.m_MetroApplicationDescription.stringValue = this.ValidateMetroApplicationDescription(this.m_MetroApplicationDescription.stringValue); + EditorGUILayout.Space(); + GUILayout.Label("Compilation", EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettings.Metro.compilationOverrides = (PlayerSettings.MetroCompilationOverrides)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroCompilationOverrides"), PlayerSettings.Metro.compilationOverrides, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label("Misc", EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroUnprocessedPlugins, EditorGUIUtility.TextContent("PlayerSettings.MetroUnprocessedPlugins"), true, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_MetroEnableIndependentInputSource, EditorGUIUtility.TextContent("PlayerSettings.MetroEnableIndependentInputSource"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroEnableLowLatencyPresentationAPI, EditorGUIUtility.TextContent("PlayerSettings.MetroEnableLowLatencyPresentationAPI"), new GUILayoutOption[0]); + GUILayout.Label("Capabilities", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.capScrollViewPosition = GUILayout.BeginScrollView(this.capScrollViewPosition, EditorStyles.helpBox, new GUILayoutOption[] + { + GUILayout.MinHeight(200f) + }); + IEnumerator enumerator = Enum.GetValues(typeof(PlayerSettings.MetroCapability)).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + PlayerSettings.MetroCapability metroCapability = (PlayerSettings.MetroCapability)((int)enumerator.Current); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + bool enabled = GUILayout.Toggle(PlayerSettings.Metro.GetCapability(metroCapability), metroCapability.ToString(), new GUILayoutOption[] + { + GUILayout.MinWidth(150f) + }); + PlayerSettings.Metro.SetCapability(metroCapability, enabled); + GUILayout.EndHorizontal(); + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + GUILayout.EndScrollView(); + } + private static void ImageField(SerializedProperty property, GUIContent label, float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight, int imageWidth, int imageHeight) + { + Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); + Rect position = new Rect(rect.x - EditorGUI.indent, rect.y, EditorGUIUtility.labelWidth - EditorGUI.indent, rect.height); + Rect position2 = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); + EditorGUI.LabelField(position, label); + GUIContent content; + if (string.IsNullOrEmpty(property.stringValue)) + { + content = EditorGUIUtility.TextContent("PlayerSettings.MetroImageSelect"); + } + else + { + content = new GUIContent(FileUtil.GetLastPathNameComponent(property.stringValue), property.stringValue); + } + if (GUI.Button(position2, content)) + { + string text = EditorUtility.OpenFilePanel(null, Application.dataPath, "png").Replace('\\', '/'); + if (string.IsNullOrEmpty(text)) + { + property.stringValue = text; + } + else + { + if (!PlayerSettingsEditor.ValidateImage(text, imageWidth, imageHeight)) + { + property.stringValue = string.Empty; + return; + } + property.stringValue = text; + } + text = FileUtil.GetProjectRelativePath(text); + if (!string.IsNullOrEmpty(text)) + { + property.stringValue = text; + } + } + } + private static bool ValidateImage(string imageFile, int width, int height) + { + Texture2D texture2D = new Texture2D(1, 1); + texture2D.LoadImage(File.ReadAllBytes(imageFile)); + int width2 = texture2D.width; + int height2 = texture2D.height; + UnityEngine.Object.DestroyImmediate(texture2D); + if (width2 != width || height2 != height) + { + Debug.LogError(string.Format("Invalid image size ({0}x{1}), should be {2}x{3}", new object[] + { + width2, + height2, + width, + height + })); + return false; + } + return true; + } + private string ValidateMetroPackageName(string value) + { + if (PlayerSettingsEditor.IsValidMetroPackageName(value)) + { + return value; + } + return this.GetDefaultMetroPackageName(); + } + private static bool IsValidMetroPackageName(string value) + { + if (!PlayerSettingsEditor.metroPackageNameRegex.IsMatch(value)) + { + return false; + } + string text = value.ToUpper(); + if (text != null) + { + if (PlayerSettingsEditor.<>f__switch$map15 == null) + { + PlayerSettingsEditor.<>f__switch$map15 = new Dictionary(22) + { + + { + "CON", + 0 + }, + + { + "PRN", + 0 + }, + + { + "AUX", + 0 + }, + + { + "NUL", + 0 + }, + + { + "COM1", + 0 + }, + + { + "COM2", + 0 + }, + + { + "COM3", + 0 + }, + + { + "COM4", + 0 + }, + + { + "COM5", + 0 + }, + + { + "COM6", + 0 + }, + + { + "COM7", + 0 + }, + + { + "COM8", + 0 + }, + + { + "COM9", + 0 + }, + + { + "LPT1", + 0 + }, + + { + "LPT2", + 0 + }, + + { + "LPT3", + 0 + }, + + { + "LPT4", + 0 + }, + + { + "LPT5", + 0 + }, + + { + "LPT6", + 0 + }, + + { + "LPT7", + 0 + }, + + { + "LPT8", + 0 + }, + + { + "LPT9", + 0 + } + }; + } + int num; + if (PlayerSettingsEditor.<>f__switch$map15.TryGetValue(text, out num)) + { + if (num == 0) + { + return false; + } + } + } + return true; + } + private string GetDefaultMetroPackageName() + { + string text = this.m_ProductName.stringValue; + if (text != null) + { + StringBuilder stringBuilder = new StringBuilder(text.Length); + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (char.IsLetterOrDigit(c) || c == '-') + { + stringBuilder.Append(c); + } + else + { + if (c == '.' && i != text.Length - 1) + { + stringBuilder.Append(c); + } + } + } + text = stringBuilder.ToString(); + } + if (!PlayerSettingsEditor.IsValidMetroPackageName(text)) + { + text = "DefaultPackageName"; + } + return text; + } + internal static string ValidateMetroPackageVersion(string value) + { + if (PlayerSettingsEditor.metroPackageVersionRegex.IsMatch(value)) + { + return value; + } + return "1.0.0.0"; + } + private string ValidateMetroApplicationDescription(string value) + { + if (string.IsNullOrEmpty(value)) + { + return this.m_ProductName.stringValue; + } + return value; + } + private string ValidateMetroTileShortName(string value) + { + if (string.IsNullOrEmpty(value)) + { + value = this.m_ProductName.stringValue; + } + if (value != null && value.Length > 13) + { + return value.Substring(0, 13).TrimEnd(new char[] + { + ' ' + }); + } + return value; + } + private void MetroLogoSection(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogo"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 50, 50); + PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 70, 70); + PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 90, 90); + PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo240, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 120, 120); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroTileShortName, EditorGUIUtility.TextContent("PlayerSettings.MetroTileShortName"), new GUILayoutOption[0]); + this.m_MetroTileShortName.stringValue = this.ValidateMetroTileShortName(this.m_MetroTileShortName.stringValue); + PlayerSettings.MetroApplicationShowName tileShowName = PlayerSettings.Metro.tileShowName; + if (tileShowName != PlayerSettings.MetroApplicationShowName.NotSet) + { + switch (tileShowName) + { + case PlayerSettings.MetroApplicationShowName.AllLogos: + PlayerSettings.Metro.mediumTileShowName = true; + PlayerSettings.Metro.largeTileShowName = true; + PlayerSettings.Metro.wideTileShowName = true; + break; + case PlayerSettings.MetroApplicationShowName.StandardLogoOnly: + PlayerSettings.Metro.mediumTileShowName = true; + PlayerSettings.Metro.largeTileShowName = true; + break; + case PlayerSettings.MetroApplicationShowName.WideLogoOnly: + PlayerSettings.Metro.wideTileShowName = true; + break; + } + PlayerSettings.Metro.tileShowName = PlayerSettings.MetroApplicationShowName.NotSet; + } + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroTileShowName"), new GUILayoutOption[0]); + PlayerSettings.Metro.mediumTileShowName = GUILayout.Toggle(PlayerSettings.Metro.mediumTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), new GUILayoutOption[0]); + PlayerSettings.Metro.largeTileShowName = GUILayout.Toggle(PlayerSettings.Metro.largeTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroLargeTile"), new GUILayoutOption[0]); + PlayerSettings.Metro.wideTileShowName = GUILayout.Toggle(PlayerSettings.Metro.wideTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), new GUILayoutOption[0]); + PlayerSettings.Metro.tileForegroundText = (PlayerSettings.MetroApplicationForegroundText)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroTileForegroundText"), PlayerSettings.Metro.tileForegroundText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MetroTileBackgroundColor, EditorGUIUtility.TextContent("PlayerSettings.MetroTileBackgroundColor"), new GUILayoutOption[0]); + PlayerSettings.Metro.defaultTileSize = (PlayerSettings.MetroDefaultTileSize)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroDefaultTileSize"), PlayerSettings.Metro.defaultTileSize, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WindowsTiles"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallLogo"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 24, 24); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 30, 30); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 42, 42); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 54, 54); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 120, 120); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 150, 150); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 210, 210); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 270, 270); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 248, 120); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 150); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 210); + PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 558, 270); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 56, 56); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 70, 70); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 98, 98); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 126, 126); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroLargeTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 248, 248); + PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 310); + PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 434); + PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 558, 558); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WindowsPhoneTiles"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroAppIcon"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 44, 44); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 62, 62); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 106, 106); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 71, 71); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 99, 99); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 170, 170); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 150, 150); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 210, 210); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 360, 360); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 150); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 210); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 744, 360); + EditorGUILayout.Space(); + } + private void MetroSplashScreenSection(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) + { + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWindows"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 620, 300); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 868, 420); + PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 1116, 540); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWindowsPhone"), EditorStyles.boldLabel, new GUILayoutOption[0]); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 480, 800); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 672, 1120); + PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 1152, 1920); + EditorGUILayout.Space(); + bool hasValue = PlayerSettings.Metro.splashScreenBackgroundColor.HasValue; + bool flag = EditorGUILayout.BeginToggleGroup(EditorGUIUtility.TextContent("PlayerSettings.MetroSplashScreenOverwriteBackgroundColor"), hasValue); + Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); + Rect position = new Rect(rect.x - EditorGUI.indent, rect.y, EditorGUIUtility.labelWidth - EditorGUI.indent, rect.height); + Rect position2 = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); + EditorGUI.LabelField(position, EditorGUIUtility.TextContent("PlayerSettings.MetroSplashScreenBackgroundColor")); + if (flag != hasValue) + { + if (flag) + { + PlayerSettings.Metro.splashScreenBackgroundColor = new Color?(PlayerSettings.Metro.tileBackgroundColor); + } + else + { + PlayerSettings.Metro.splashScreenBackgroundColor = null; + } + } + if (flag) + { + PlayerSettings.Metro.splashScreenBackgroundColor = new Color?(EditorGUI.ColorField(position2, PlayerSettings.Metro.splashScreenBackgroundColor.Value)); + } + else + { + EditorGUI.ColorField(position2, PlayerSettings.Metro.tileBackgroundColor); + } + EditorGUILayout.EndToggleGroup(); + } + public void PublishSectionGUIWP8(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) + { + EditorGUILayout.PropertyField(this.m_WP8UnprocessedPlugins, EditorGUIUtility.TextContent("PlayerSettings.WP8UnprocessedPlugins"), true, new GUILayoutOption[0]); + } + private static string PrettyTemplateKeyName(string name) + { + string[] array = name.Split(new char[] + { + '_' + }); + array[0] = PlayerSettingsEditor.UppercaseFirst(array[0].ToLower()); + for (int i = 1; i < array.Length; i++) + { + array[i] = array[i].ToLower(); + } + return string.Join(" ", array); + } + private static string UppercaseFirst(string target) + { + if (string.IsNullOrEmpty(target)) + { + return string.Empty; + } + return char.ToUpper(target[0]) + target.Substring(1); + } + private static int ThumbnailList(Rect rect, int selection, GUIContent[] thumbnails, int maxRowItems) + { + int num = 0; + int i = 0; + while (i < thumbnails.Length) + { + int num2 = 0; + while (num2 < maxRowItems && i < thumbnails.Length) + { + if (PlayerSettingsEditor.ThumbnailListItem(new Rect(rect.x + (float)num2 * 80f, rect.y + (float)num * 100f, 80f, 100f), i == selection, thumbnails[i])) + { + selection = i; + } + num2++; + i++; + } + num++; + } + return selection; + } + private static bool ThumbnailListItem(Rect rect, bool selected, GUIContent content) + { + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + Rect position = new Rect(rect.x + 5f, rect.y + 5f, rect.width - 10f, rect.height - 20f - 10f); + PlayerSettingsEditor.s_Styles.thumbnail.Draw(position, content.image, false, false, selected, selected); + PlayerSettingsEditor.s_Styles.thumbnailLabel.Draw(new Rect(rect.x, rect.y + rect.height - 20f, rect.width, 20f), content.text, false, false, selected, selected); + } + } + else + { + if (rect.Contains(Event.current.mousePosition)) + { + if (!selected) + { + GUI.changed = true; + } + selected = true; + Event.current.Use(); + } + } + return selected; + } + } +} diff --git a/UnityEditor/UnityEditor/PointEditor.cs b/UnityEditor/UnityEditor/PointEditor.cs new file mode 100644 index 00000000..0ca20580 --- /dev/null +++ b/UnityEditor/UnityEditor/PointEditor.cs @@ -0,0 +1,239 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class PointEditor + { + private static Vector2 s_StartMouseDragPosition; + private static List s_StartDragSelection; + private static bool s_DidDrag; + private static Mesh s_Mesh; + private static Vector3 s_EditingScale = Vector3.one; + private static Quaternion s_EditingRotation = Quaternion.identity; + private static Mesh GetMesh() + { + PointEditor.s_Mesh = (PointEditor.s_Mesh ?? (Resources.GetBuiltinResource(typeof(Mesh), "New-Sphere.fbx") as Mesh)); + return PointEditor.s_Mesh; + } + public static bool MovePoints(IEditablePoint points, Transform cloudTransform, List selection) + { + if (selection.Count == 0) + { + return false; + } + if (Event.current.type == EventType.MouseUp) + { + PointEditor.s_EditingScale = Vector3.one; + PointEditor.s_EditingRotation = Quaternion.identity; + } + if (Camera.current) + { + Vector3 vector = Vector3.zero; + vector = ((Tools.pivotMode != PivotMode.Pivot) ? (selection.Aggregate(vector, (Vector3 current, int index) => current + points.GetPosition(index)) / (float)selection.Count) : points.GetPosition(selection[0])); + vector = cloudTransform.TransformPoint(vector); + switch (Tools.current) + { + case Tool.Move: + { + Vector3 position = Handles.PositionHandle(vector, (Tools.pivotRotation != PivotRotation.Local) ? Quaternion.identity : cloudTransform.rotation); + if (GUI.changed) + { + Vector3 b = cloudTransform.InverseTransformPoint(position) - cloudTransform.InverseTransformPoint(vector); + foreach (int current4 in selection) + { + points.SetPosition(current4, points.GetPosition(current4) + b); + } + return true; + } + break; + } + case Tool.Rotate: + { + Quaternion rotation = Handles.RotationHandle(PointEditor.s_EditingRotation, vector); + if (GUI.changed) + { + Vector3 b2 = cloudTransform.InverseTransformPoint(vector); + foreach (int current2 in selection) + { + Vector3 vector2 = points.GetPosition(current2) - b2; + vector2 = Quaternion.Inverse(PointEditor.s_EditingRotation) * vector2; + vector2 = rotation * vector2; + vector2 += b2; + points.SetPosition(current2, vector2); + } + PointEditor.s_EditingRotation = rotation; + return true; + } + break; + } + case Tool.Scale: + { + Vector3 vector3 = Handles.ScaleHandle(PointEditor.s_EditingScale, vector, Quaternion.identity, HandleUtility.GetHandleSize(vector)); + if (GUI.changed) + { + Vector3 b3 = cloudTransform.InverseTransformPoint(vector); + foreach (int current3 in selection) + { + Vector3 vector4 = points.GetPosition(current3) - b3; + vector4.x /= PointEditor.s_EditingScale.x; + vector4.y /= PointEditor.s_EditingScale.y; + vector4.z /= PointEditor.s_EditingScale.z; + vector4.x *= vector3.x; + vector4.y *= vector3.y; + vector4.z *= vector3.z; + vector4 += b3; + points.SetPosition(current3, vector4); + } + PointEditor.s_EditingScale = vector3; + return true; + } + break; + } + } + } + return false; + } + public static int FindNearest(Vector2 point, Transform cloudTransform, IEditablePoint points) + { + Ray ray = HandleUtility.GUIPointToWorldRay(point); + Dictionary dictionary = new Dictionary(); + for (int i = 0; i < points.Count; i++) + { + float num = 0f; + Vector3 zero = Vector3.zero; + if (MathUtils.IntersectRaySphere(ray, cloudTransform.TransformPoint(points.GetPosition(i)), points.GetPointScale() * 0.5f, ref num, ref zero) && num > 0f) + { + dictionary.Add(i, num); + } + } + if (dictionary.Count <= 0) + { + return -1; + } + IOrderedEnumerable> source = + from x in dictionary + orderby x.Value + select x; + return source.First>().Key; + } + public static bool SelectPoints(IEditablePoint points, Transform cloudTransform, ref List selection, bool firstSelect) + { + int controlID = GUIUtility.GetControlID(FocusType.Passive); + if (Event.current.alt && Event.current.type != EventType.Repaint) + { + return false; + } + bool result = false; + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == controlID || firstSelect) && current.button == 0) + { + if (!current.shift && !EditorGUI.actionKey) + { + selection.Clear(); + result = true; + } + GUIUtility.hotControl = controlID; + PointEditor.s_StartMouseDragPosition = current.mousePosition; + PointEditor.s_StartDragSelection = new List(selection); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + if (!PointEditor.s_DidDrag) + { + int num = PointEditor.FindNearest(PointEditor.s_StartMouseDragPosition, cloudTransform, points); + if (num != -1) + { + if (!current.shift && !EditorGUI.actionKey) + { + selection.Add(num); + } + else + { + int num2 = selection.IndexOf(num); + if (num2 != -1) + { + selection.RemoveAt(num2); + } + else + { + selection.Add(num); + } + } + } + GUI.changed = true; + result = true; + } + PointEditor.s_StartDragSelection = null; + PointEditor.s_StartMouseDragPosition = Vector2.zero; + PointEditor.s_DidDrag = false; + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + PointEditor.s_DidDrag = true; + selection.Clear(); + selection.AddRange(PointEditor.s_StartDragSelection); + Rect rect = PointEditor.FromToRect(PointEditor.s_StartMouseDragPosition, current.mousePosition); + Matrix4x4 matrix = Handles.matrix; + Handles.matrix = cloudTransform.localToWorldMatrix; + for (int i = 0; i < points.Count; i++) + { + Vector2 point = HandleUtility.WorldToGUIPoint(points.GetPosition(i)); + if (rect.Contains(point)) + { + selection.Add(i); + } + } + Handles.matrix = matrix; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == controlID && current.mousePosition != PointEditor.s_StartMouseDragPosition) + { + GUIStyle gUIStyle = "SelectionRect"; + Handles.BeginGUI(); + gUIStyle.Draw(PointEditor.FromToRect(PointEditor.s_StartMouseDragPosition, current.mousePosition), false, false, false, false); + Handles.EndGUI(); + } + break; + case EventType.Layout: + HandleUtility.AddDefaultControl(controlID); + break; + } + selection = selection.Distinct().ToList(); + return result; + } + public static void Draw(IEditablePoint points, Transform cloudTransform, List selection, bool twoPassDrawing) + { + LightmapVisualization.DrawPointCloud(points.GetUnselectedPositions(), points.GetSelectedPositions(), points.GetDefaultColor(), points.GetSelectedColor(), points.GetPointScale(), cloudTransform); + } + private static Rect FromToRect(Vector2 from, Vector2 to) + { + Rect result = new Rect(from.x, from.y, to.x - from.x, to.y - from.y); + if (result.width < 0f) + { + result.x += result.width; + result.width = -result.width; + } + if (result.height < 0f) + { + result.y += result.height; + result.height = -result.height; + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/PolygonColliderEditor.cs b/UnityEditor/UnityEditor/PolygonColliderEditor.cs new file mode 100644 index 00000000..a6a97311 --- /dev/null +++ b/UnityEditor/UnityEditor/PolygonColliderEditor.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Sprites; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(PolygonCollider2D))] + internal class PolygonColliderEditor : Collider2DEditorBase + { + private PolygonEditorUtility m_PolyUtility = new PolygonEditorUtility(); + private bool m_ShowColliderInfo; + public override void OnEnable() + { + base.OnEnable(); + } + public override void OnInspectorGUI() + { + this.HandleDragAndDrop(); + base.BeginColliderInspector(); + this.ColliderInfoGUI(); + base.EndColliderInspector(); + base.CheckColliderErrorState(); + } + private void HandleDragAndDrop() + { + if (Event.current.type != EventType.DragPerform && Event.current.type != EventType.DragUpdated) + { + return; + } + using (IEnumerator enumerator = ( + from obj in DragAndDrop.objectReferences + where obj is Sprite || obj is Texture2D + select obj).GetEnumerator()) + { + if (enumerator.MoveNext()) + { + UnityEngine.Object current = enumerator.Current; + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (Event.current.type == EventType.DragPerform) + { + Sprite sprite = (!(current is Sprite)) ? SpriteUtility.TextureToSprite(current as Texture2D) : (current as Sprite); + foreach (PolygonCollider2D current2 in + from target in base.targets + select target as PolygonCollider2D) + { + Vector2[][] array; + DataUtility.GenerateOutlineFromSprite(sprite, 0.25f, 200, true, out array); + current2.pathCount = array.Length; + for (int i = 0; i < array.Length; i++) + { + current2.SetPath(i, array[i]); + } + this.m_PolyUtility.StopEditing(); + DragAndDrop.AcceptDrag(); + } + } + return; + } + } + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + } + private void ColliderInfoGUI() + { + EditorGUI.BeginDisabledGroup(base.targets.Length != 1); + this.m_ShowColliderInfo = EditorGUILayout.Foldout(this.m_ShowColliderInfo, "Collider Info"); + if (this.m_ShowColliderInfo) + { + PolygonCollider2D polygonCollider2D = base.targets[0] as PolygonCollider2D; + if (polygonCollider2D) + { + int totalPointCount = polygonCollider2D.GetTotalPointCount(); + string label = (!GUI.enabled) ? "---" : (string.Empty + totalPointCount); + EditorGUI.indentLevel++; + EditorGUILayout.LabelField("Vertices", label, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + } + EditorGUI.EndDisabledGroup(); + } + protected override void OnEditStart() + { + if (this.target == null) + { + return; + } + this.m_PolyUtility.StartEditing(this.target as Collider2D); + } + protected override void OnEditEnd() + { + this.m_PolyUtility.StopEditing(); + } + public void OnSceneGUI() + { + if (!base.editingCollider) + { + return; + } + this.m_PolyUtility.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/PolygonEditor.cs b/UnityEditor/UnityEditor/PolygonEditor.cs new file mode 100644 index 00000000..6786ebc9 --- /dev/null +++ b/UnityEditor/UnityEditor/PolygonEditor.cs @@ -0,0 +1,65 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class PolygonEditor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StartEditing(Collider2D collider); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ApplyEditing(Collider2D collider); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopEditing(); + public static bool GetNearestPoint(Vector2 point, out int pathIndex, out int pointIndex, out float distance) + { + return PolygonEditor.INTERNAL_CALL_GetNearestPoint(ref point, out pathIndex, out pointIndex, out distance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_GetNearestPoint(ref Vector2 point, out int pathIndex, out int pointIndex, out float distance); + public static bool GetNearestEdge(Vector2 point, out int pathIndex, out int pointIndex0, out int pointIndex1, out float distance, bool loop) + { + return PolygonEditor.INTERNAL_CALL_GetNearestEdge(ref point, out pathIndex, out pointIndex0, out pointIndex1, out distance, loop); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_GetNearestEdge(ref Vector2 point, out int pathIndex, out int pointIndex0, out int pointIndex1, out float distance, bool loop); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPathCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPointCount(int pathIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetPoint(int pathIndex, int pointIndex, out Vector2 point); + public static void SetPoint(int pathIndex, int pointIndex, Vector2 value) + { + PolygonEditor.INTERNAL_CALL_SetPoint(pathIndex, pointIndex, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetPoint(int pathIndex, int pointIndex, ref Vector2 value); + public static void InsertPoint(int pathIndex, int pointIndex, Vector2 value) + { + PolygonEditor.INTERNAL_CALL_InsertPoint(pathIndex, pointIndex, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_InsertPoint(int pathIndex, int pointIndex, ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemovePoint(int pathIndex, int pointIndex); + public static void TestPointMove(int pathIndex, int pointIndex, Vector2 movePosition, out bool leftIntersect, out bool rightIntersect, bool loop) + { + PolygonEditor.INTERNAL_CALL_TestPointMove(pathIndex, pointIndex, ref movePosition, out leftIntersect, out rightIntersect, loop); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_TestPointMove(int pathIndex, int pointIndex, ref Vector2 movePosition, out bool leftIntersect, out bool rightIntersect, bool loop); + } +} diff --git a/UnityEditor/UnityEditor/PolygonEditorUtility.cs b/UnityEditor/UnityEditor/PolygonEditorUtility.cs new file mode 100644 index 00000000..95b402fa --- /dev/null +++ b/UnityEditor/UnityEditor/PolygonEditorUtility.cs @@ -0,0 +1,321 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PolygonEditorUtility + { + private const float k_HandlePointSnap = 0.2f; + private const float k_HandlePickDistance = 50f; + private Collider2D m_ActiveCollider; + private bool m_LoopingCollider; + private int m_MinPathPoints = 3; + private int m_SelectedPath = -1; + private int m_SelectedVertex = -1; + private float m_SelectedDistance; + private int m_SelectedEdgePath = -1; + private int m_SelectedEdgeVertex0 = -1; + private int m_SelectedEdgeVertex1 = -1; + private float m_SelectedEdgeDistance; + private bool m_LeftIntersect; + private bool m_RightIntersect; + private bool m_DeleteMode; + private bool m_FirstOnSceneGUIAfterReset; + public void Reset() + { + this.m_SelectedPath = -1; + this.m_SelectedVertex = -1; + this.m_SelectedEdgePath = -1; + this.m_SelectedEdgeVertex0 = -1; + this.m_SelectedEdgeVertex1 = -1; + this.m_LeftIntersect = false; + this.m_RightIntersect = false; + this.m_FirstOnSceneGUIAfterReset = true; + } + private void UndoRedoPerformed() + { + if (this.m_ActiveCollider != null) + { + Collider2D activeCollider = this.m_ActiveCollider; + this.StopEditing(); + this.StartEditing(activeCollider); + } + } + public void StartEditing(Collider2D collider) + { + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.Reset(); + PolygonCollider2D polygonCollider2D = collider as PolygonCollider2D; + if (polygonCollider2D) + { + this.m_ActiveCollider = collider; + this.m_LoopingCollider = true; + this.m_MinPathPoints = 3; + PolygonEditor.StartEditing(polygonCollider2D); + return; + } + EdgeCollider2D edgeCollider2D = collider as EdgeCollider2D; + if (edgeCollider2D) + { + this.m_ActiveCollider = collider; + this.m_LoopingCollider = false; + this.m_MinPathPoints = 2; + PolygonEditor.StartEditing(edgeCollider2D); + return; + } + throw new NotImplementedException(string.Format("PolygonEditorUtility does not support {0}", collider)); + } + public void StopEditing() + { + PolygonEditor.StopEditing(); + this.m_ActiveCollider = null; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + private void ApplyEditing(Collider2D collider) + { + PolygonCollider2D polygonCollider2D = collider as PolygonCollider2D; + if (polygonCollider2D) + { + PolygonEditor.ApplyEditing(polygonCollider2D); + return; + } + EdgeCollider2D edgeCollider2D = collider as EdgeCollider2D; + if (edgeCollider2D) + { + PolygonEditor.ApplyEditing(edgeCollider2D); + return; + } + throw new NotImplementedException(string.Format("PolygonEditorUtility does not support {0}", collider)); + } + public void OnSceneGUI() + { + if (this.m_ActiveCollider == null) + { + return; + } + Event current = Event.current; + this.m_DeleteMode = (current.command || current.control); + Transform transform = this.m_ActiveCollider.transform; + GUIUtility.keyboardControl = 0; + HandleUtility.s_CustomPickDistance = 50f; + Plane plane = new Plane(-transform.forward, Vector3.zero); + Ray ray = HandleUtility.GUIPointToWorldRay(current.mousePosition); + float distance; + plane.Raycast(ray, out distance); + Vector3 point = ray.GetPoint(distance); + Vector2 vector = transform.InverseTransformPoint(point); + if (current.type == EventType.MouseMove || this.m_FirstOnSceneGUIAfterReset) + { + int num; + int num2; + float num3; + if (PolygonEditor.GetNearestPoint(vector, out num, out num2, out num3)) + { + this.m_SelectedPath = num; + this.m_SelectedVertex = num2; + this.m_SelectedDistance = num3; + } + else + { + this.m_SelectedPath = -1; + } + int selectedEdgeVertex; + if (PolygonEditor.GetNearestEdge(vector, out num, out num2, out selectedEdgeVertex, out num3, this.m_LoopingCollider)) + { + this.m_SelectedEdgePath = num; + this.m_SelectedEdgeVertex0 = num2; + this.m_SelectedEdgeVertex1 = selectedEdgeVertex; + this.m_SelectedEdgeDistance = num3; + } + else + { + this.m_SelectedEdgePath = -1; + } + current.Use(); + } + else + { + if (current.type == EventType.MouseUp) + { + this.m_LeftIntersect = false; + this.m_RightIntersect = false; + } + } + bool flag = false; + bool flag2 = false; + if (this.m_SelectedPath != -1 && this.m_SelectedEdgePath != -1) + { + Vector2 v; + PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out v); + Vector3 position = transform.TransformPoint(v); + float num4 = HandleUtility.GetHandleSize(position) * 0.2f; + flag2 = (this.m_SelectedEdgeDistance < this.m_SelectedDistance - num4); + flag = !flag2; + } + else + { + if (this.m_SelectedPath != -1) + { + flag = true; + } + else + { + if (this.m_SelectedEdgePath != -1) + { + flag2 = true; + } + } + } + if (this.m_DeleteMode && flag2) + { + flag2 = false; + flag = true; + } + bool flag3 = false; + if (flag2 && !this.m_DeleteMode) + { + Vector2 vector2; + PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex0, out vector2); + Vector2 vector3; + PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, out vector3); + Vector3 vector4 = transform.TransformPoint(vector2); + Vector3 vector5 = transform.TransformPoint(vector3); + vector4.z = (vector5.z = 0f); + Handles.color = Color.green; + Handles.DrawAAPolyLine(4f, new Vector3[] + { + vector4, + vector5 + }); + Handles.color = Color.white; + Vector2 v2 = this.GetNearestPointOnEdge(transform.TransformPoint(vector), vector4, vector5); + EditorGUI.BeginChangeCheck(); + float handleSize = HandleUtility.GetHandleSize(v2) * 0.04f; + Handles.color = Color.green; + v2 = Handles.Slider2D(v2, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); + Handles.color = Color.white; + if (EditorGUI.EndChangeCheck()) + { + PolygonEditor.InsertPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, (vector2 + vector3) / 2f); + this.m_SelectedPath = this.m_SelectedEdgePath; + this.m_SelectedVertex = this.m_SelectedEdgeVertex1; + this.m_SelectedDistance = 0f; + flag = true; + flag3 = true; + } + } + if (flag) + { + Vector2 vector6; + PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out vector6); + Vector3 vector7 = transform.TransformPoint(vector6); + vector7.z = 0f; + Vector2 a = HandleUtility.WorldToGUIPoint(vector7); + float handleSize2 = HandleUtility.GetHandleSize(vector7) * 0.04f; + if ((this.m_DeleteMode && current.type == EventType.MouseDown && Vector2.Distance(a, Event.current.mousePosition) < 50f) || this.DeleteCommandEvent(current)) + { + if (current.type != EventType.ValidateCommand) + { + int pointCount = PolygonEditor.GetPointCount(this.m_SelectedPath); + if (pointCount > this.m_MinPathPoints) + { + PolygonEditor.RemovePoint(this.m_SelectedPath, this.m_SelectedVertex); + this.Reset(); + flag3 = true; + } + } + current.Use(); + } + EditorGUI.BeginChangeCheck(); + Handles.color = ((!this.m_DeleteMode) ? Color.green : Color.red); + Vector3 vector8 = Handles.Slider2D(vector7, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize2, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); + Handles.color = Color.white; + if (EditorGUI.EndChangeCheck() && !this.m_DeleteMode) + { + vector6 = transform.InverseTransformPoint(vector8); + PolygonEditor.TestPointMove(this.m_SelectedPath, this.m_SelectedVertex, vector6, out this.m_LeftIntersect, out this.m_RightIntersect, this.m_LoopingCollider); + PolygonEditor.SetPoint(this.m_SelectedPath, this.m_SelectedVertex, vector6); + flag3 = true; + } + if (!flag3) + { + this.DrawEdgesForSelectedPoint(vector8, transform, this.m_LeftIntersect, this.m_RightIntersect, this.m_LoopingCollider); + } + } + if (flag3) + { + Undo.RecordObject(this.m_ActiveCollider, "Edit Collider"); + PolygonEditor.ApplyEditing(this.m_ActiveCollider); + } + if (this.DeleteCommandEvent(current)) + { + Event.current.Use(); + } + this.m_FirstOnSceneGUIAfterReset = false; + } + private bool DeleteCommandEvent(Event evt) + { + return (evt.type == EventType.ExecuteCommand || evt.type == EventType.ValidateCommand) && (evt.commandName == "Delete" || evt.commandName == "SoftDelete"); + } + private void DrawEdgesForSelectedPoint(Vector3 worldPos, Transform transform, bool leftIntersect, bool rightIntersect, bool loop) + { + bool flag = true; + bool flag2 = true; + int pointCount = PolygonEditor.GetPointCount(this.m_SelectedPath); + int num = this.m_SelectedVertex - 1; + if (num == -1) + { + num = pointCount - 1; + flag = loop; + } + int num2 = this.m_SelectedVertex + 1; + if (num2 == pointCount) + { + num2 = 0; + flag2 = loop; + } + Vector2 v; + PolygonEditor.GetPoint(this.m_SelectedPath, num, out v); + Vector2 v2; + PolygonEditor.GetPoint(this.m_SelectedPath, num2, out v2); + Vector3 vector = transform.TransformPoint(v); + Vector3 vector2 = transform.TransformPoint(v2); + vector.z = (vector2.z = worldPos.z); + float width = 4f; + if (flag) + { + Handles.color = ((!leftIntersect && !this.m_DeleteMode) ? Color.green : Color.red); + Handles.DrawAAPolyLine(width, new Vector3[] + { + worldPos, + vector + }); + } + if (flag2) + { + Handles.color = ((!rightIntersect && !this.m_DeleteMode) ? Color.green : Color.red); + Handles.DrawAAPolyLine(width, new Vector3[] + { + worldPos, + vector2 + }); + } + Handles.color = Color.white; + } + private Vector2 GetNearestPointOnEdge(Vector2 point, Vector2 start, Vector2 end) + { + Vector2 rhs = point - start; + Vector2 normalized = (end - start).normalized; + float num = Vector2.Dot(normalized, rhs); + if (num <= 0f) + { + return start; + } + if (num >= Vector2.Distance(start, end)) + { + return end; + } + Vector2 b = normalized * num; + return start + b; + } + } +} diff --git a/UnityEditor/UnityEditor/PopupList.cs b/UnityEditor/UnityEditor/PopupList.cs new file mode 100644 index 00000000..5d95b9be --- /dev/null +++ b/UnityEditor/UnityEditor/PopupList.cs @@ -0,0 +1,526 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class PopupList : PopupWindowContent + { + public enum Gravity + { + Top, + Bottom + } + public class ListElement + { + public GUIContent m_Content; + private float m_FilterScore; + private bool m_Selected; + private bool m_WasSelected; + private bool m_PartiallySelected; + public float filterScore + { + get + { + return (!this.m_WasSelected) ? this.m_FilterScore : 3.40282347E+38f; + } + set + { + this.m_FilterScore = value; + this.ResetScore(); + } + } + public bool selected + { + get + { + return this.m_Selected; + } + set + { + this.m_Selected = value; + if (this.m_Selected) + { + this.m_WasSelected = true; + } + } + } + public bool partiallySelected + { + get + { + return this.m_PartiallySelected; + } + set + { + this.m_PartiallySelected = value; + if (this.m_PartiallySelected) + { + this.m_WasSelected = true; + } + } + } + public string text + { + get + { + return this.m_Content.text; + } + set + { + this.m_Content.text = value; + } + } + public ListElement(string text, bool selected, float score) + { + this.m_Content = new GUIContent(text); + if (!string.IsNullOrEmpty(this.m_Content.text)) + { + char[] array = this.m_Content.text.ToCharArray(); + array[0] = char.ToUpper(array[0]); + this.m_Content.text = new string(array); + } + this.m_Selected = selected; + this.filterScore = score; + this.m_PartiallySelected = false; + } + public ListElement(string text, bool selected) + { + this.m_Content = new GUIContent(text); + this.m_Selected = selected; + this.filterScore = 0f; + this.m_PartiallySelected = false; + } + public ListElement(string text) : this(text, false) + { + } + public void ResetScore() + { + this.m_WasSelected = (this.m_Selected || this.m_PartiallySelected); + } + } + public class InputData + { + public List m_ListElements; + public bool m_CloseOnSelection; + public bool m_AllowCustom; + public bool m_SortAlphabetically; + public PopupList.OnSelectCallback m_OnSelectCallback; + public int m_MaxCount; + public InputData() + { + this.m_ListElements = new List(); + } + public void DeselectAll() + { + foreach (PopupList.ListElement current in this.m_ListElements) + { + current.selected = false; + current.partiallySelected = false; + } + } + public void ResetScores() + { + foreach (PopupList.ListElement current in this.m_ListElements) + { + current.ResetScore(); + } + } + private IEnumerable BuildQuery(string prefix) + { + if (prefix == string.Empty) + { + return this.m_ListElements; + } + return + from element in this.m_ListElements + where element.m_Content.text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + select element; + } + public IEnumerable GetFilteredList(string prefix) + { + IEnumerable enumerable = this.BuildQuery(prefix); + if (this.m_MaxCount > 0) + { + enumerable = ( + from element in enumerable + orderby element.filterScore descending + select element).Take(this.m_MaxCount); + } + if (this.m_SortAlphabetically) + { + return + from element in enumerable + orderby element.text.ToLower() + select element; + } + return enumerable; + } + public int GetFilteredCount(string prefix) + { + IEnumerable source = this.BuildQuery(prefix); + if (this.m_MaxCount > 0) + { + source = source.Take(this.m_MaxCount); + } + return source.Count(); + } + public PopupList.ListElement NewOrMatchingElement(string label) + { + PopupList.ListElement listElement = ( + from element in this.m_ListElements + where element.text.Equals(label, StringComparison.OrdinalIgnoreCase) + select element).DefaultIfEmpty(null).FirstOrDefault(); + if (listElement == null) + { + listElement = new PopupList.ListElement(label, false, -1f); + this.m_ListElements.Add(listElement); + } + return listElement; + } + } + private class Styles + { + public GUIStyle menuItem = "MenuItem"; + public GUIStyle menuItemMixed = "MenuItemMixed"; + public GUIStyle label = "PR Label"; + public GUIStyle background = "grey_border"; + public GUIStyle customTextField; + public GUIStyle customTextFieldCancelButton; + public GUIStyle customTextFieldCancelButtonEmpty; + public Styles() + { + this.customTextField = new GUIStyle(EditorStyles.toolbarSearchField); + this.customTextFieldCancelButton = new GUIStyle(EditorStyles.toolbarSearchFieldCancelButton); + this.customTextFieldCancelButtonEmpty = new GUIStyle(EditorStyles.toolbarSearchFieldCancelButtonEmpty); + } + } + public delegate void OnSelectCallback(PopupList.ListElement element); + private const float scrollBarWidth = 14f; + private const float listElementHeight = 18f; + private const float gizmoRightAlign = 23f; + private const float iconRightAlign = 64f; + private const float frameWidth = 1f; + private const float k_LineHeight = 16f; + private const float k_TextFieldHeight = 16f; + private const float k_Margin = 10f; + private static EditorGUI.RecycledTextEditor s_RecycledEditor = new EditorGUI.RecycledTextEditor(); + private static string s_TextFieldName = "ProjectBrowserPopupsTextField"; + private static int s_TextFieldHash = PopupList.s_TextFieldName.GetHashCode(); + private static PopupList.Styles s_Styles; + private PopupList.InputData m_Data; + private Vector2 m_ScrollPosition; + private Vector2 m_ScreenPos; + private PopupList.Gravity m_Gravity; + private string m_EnteredTextCompletion = string.Empty; + private string m_EnteredText = string.Empty; + private int m_SelectedCompletionIndex; + public PopupList(PopupList.InputData inputData) : this(inputData, null) + { + } + public PopupList(PopupList.InputData inputData, string initialSelectionLabel) + { + this.m_Data = inputData; + this.m_Data.ResetScores(); + this.SelectNoCompletion(); + this.m_Gravity = PopupList.Gravity.Top; + if (initialSelectionLabel != null) + { + this.m_EnteredTextCompletion = initialSelectionLabel; + this.UpdateCompletion(); + } + } + public override void OnClose() + { + if (this.m_Data != null) + { + this.m_Data.ResetScores(); + } + } + private float GetWindowHeight() + { + int num = (this.m_Data.m_MaxCount != 0) ? this.m_Data.m_MaxCount : this.m_Data.GetFilteredCount(this.m_EnteredText); + return (float)num * 16f + 20f + ((!this.m_Data.m_AllowCustom) ? 0f : 16f); + } + private float GetWindowWidth() + { + return 150f; + } + public override Vector2 GetWindowSize() + { + return new Vector2(this.GetWindowWidth(), this.GetWindowHeight()); + } + public override void OnGUI(Rect windowRect) + { + Event current = Event.current; + if (current.type == EventType.Layout) + { + return; + } + if (PopupList.s_Styles == null) + { + PopupList.s_Styles = new PopupList.Styles(); + } + if (current.type == EventType.KeyDown && current.keyCode == KeyCode.Escape) + { + base.editorWindow.Close(); + GUIUtility.ExitGUI(); + } + if (this.m_Gravity == PopupList.Gravity.Bottom) + { + this.DrawList(base.editorWindow, windowRect); + this.DrawCustomTextField(base.editorWindow, windowRect); + } + else + { + this.DrawCustomTextField(base.editorWindow, windowRect); + this.DrawList(base.editorWindow, windowRect); + } + if (current.type == EventType.Repaint) + { + PopupList.s_Styles.background.Draw(new Rect(0f, 0f, windowRect.width, windowRect.height), false, false, false, false); + } + } + private void DrawCustomTextField(EditorWindow editorWindow, Rect windowRect) + { + if (!this.m_Data.m_AllowCustom) + { + return; + } + Event current = Event.current; + bool flag = true; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + string text = this.CurrentDisplayedText(); + if (current.type == EventType.KeyDown) + { + KeyCode keyCode = current.keyCode; + switch (keyCode) + { + case KeyCode.Backspace: + goto IL_12C; + case KeyCode.Tab: + goto IL_AB; + case (KeyCode)10: + case (KeyCode)11: + case KeyCode.Clear: + IL_5D: + if (keyCode == KeyCode.UpArrow) + { + this.ChangeSelectedCompletion(-1); + flag3 = true; + goto IL_170; + } + if (keyCode == KeyCode.DownArrow) + { + this.ChangeSelectedCompletion(1); + flag3 = true; + goto IL_170; + } + if (keyCode == KeyCode.None) + { + if (current.character == ' ' || current.character == ',') + { + flag3 = true; + } + goto IL_170; + } + if (keyCode == KeyCode.Space) + { + goto IL_AB; + } + if (keyCode == KeyCode.Comma) + { + goto IL_AB; + } + if (keyCode != KeyCode.Delete) + { + goto IL_170; + } + goto IL_12C; + case KeyCode.Return: + goto IL_AB; + } + goto IL_5D; + IL_AB: + if (text != string.Empty) + { + if (this.m_Data.m_OnSelectCallback != null) + { + this.m_Data.m_OnSelectCallback(this.m_Data.NewOrMatchingElement(text)); + } + if (current.keyCode == KeyCode.Tab || current.keyCode == KeyCode.Comma) + { + flag4 = true; + } + if (this.m_Data.m_CloseOnSelection || current.keyCode == KeyCode.Return) + { + flag2 = true; + } + } + flag3 = true; + goto IL_170; + IL_12C: + flag = false; + } + IL_170: + bool flag5 = false; + Rect rect = new Rect(5f, (this.m_Gravity != PopupList.Gravity.Top) ? (windowRect.height - 16f - 5f) : 5f, windowRect.width - 10f - 14f, 16f); + GUI.SetNextControlName(PopupList.s_TextFieldName); + EditorGUI.FocusTextInControl(PopupList.s_TextFieldName); + int controlID = GUIUtility.GetControlID(PopupList.s_TextFieldHash, FocusType.Keyboard, rect); + if (flag3) + { + current.Use(); + } + if (GUIUtility.keyboardControl == 0) + { + GUIUtility.keyboardControl = controlID; + } + string text2 = EditorGUI.DoTextField(PopupList.s_RecycledEditor, controlID, rect, text, PopupList.s_Styles.customTextField, null, out flag5, false, false, false); + Rect position = rect; + position.x += rect.width; + position.width = 14f; + if ((GUI.Button(position, GUIContent.none, (!(text2 != string.Empty)) ? PopupList.s_Styles.customTextFieldCancelButtonEmpty : PopupList.s_Styles.customTextFieldCancelButton) && text2 != string.Empty) || flag4) + { + string empty = string.Empty; + PopupList.s_RecycledEditor.content.text = empty; + text2 = (EditorGUI.s_OriginalText = empty); + PopupList.s_RecycledEditor.pos = 0; + PopupList.s_RecycledEditor.selectPos = 0; + flag = false; + } + if (text != text2) + { + this.m_EnteredText = ((0 > PopupList.s_RecycledEditor.pos || PopupList.s_RecycledEditor.pos >= text2.Length) ? text2 : text2.Substring(0, PopupList.s_RecycledEditor.pos)); + if (flag) + { + this.UpdateCompletion(); + } + else + { + this.SelectNoCompletion(); + } + } + if (flag2) + { + editorWindow.Close(); + } + } + private string CurrentDisplayedText() + { + return (!(this.m_EnteredTextCompletion != string.Empty)) ? this.m_EnteredText : this.m_EnteredTextCompletion; + } + private void UpdateCompletion() + { + IEnumerable source = + from element in this.m_Data.GetFilteredList(this.m_EnteredText) + select element.text; + if (this.m_EnteredTextCompletion != string.Empty && this.m_EnteredTextCompletion.StartsWith(this.m_EnteredText, StringComparison.OrdinalIgnoreCase)) + { + this.m_SelectedCompletionIndex = source.TakeWhile((string element) => element != this.m_EnteredTextCompletion).Count(); + } + else + { + if (this.m_SelectedCompletionIndex < 0) + { + this.m_SelectedCompletionIndex = 0; + } + else + { + if (this.m_SelectedCompletionIndex >= source.Count()) + { + this.m_SelectedCompletionIndex = source.Count() - 1; + } + } + this.m_EnteredTextCompletion = source.Skip(this.m_SelectedCompletionIndex).DefaultIfEmpty(string.Empty).FirstOrDefault(); + } + this.AdjustRecycledEditorSelectionToCompletion(); + } + private void ChangeSelectedCompletion(int change) + { + int filteredCount = this.m_Data.GetFilteredCount(this.m_EnteredText); + if (this.m_SelectedCompletionIndex == -1 && change < 0) + { + this.m_SelectedCompletionIndex = filteredCount; + } + int index = (filteredCount <= 0) ? 0 : ((this.m_SelectedCompletionIndex + change + filteredCount) % filteredCount); + this.SelectCompletionWithIndex(index); + } + private void SelectCompletionWithIndex(int index) + { + this.m_SelectedCompletionIndex = index; + this.m_EnteredTextCompletion = string.Empty; + this.UpdateCompletion(); + } + private void SelectNoCompletion() + { + this.m_SelectedCompletionIndex = -1; + this.m_EnteredTextCompletion = string.Empty; + this.AdjustRecycledEditorSelectionToCompletion(); + } + private void AdjustRecycledEditorSelectionToCompletion() + { + if (this.m_EnteredTextCompletion != string.Empty) + { + PopupList.s_RecycledEditor.content.text = this.m_EnteredTextCompletion; + EditorGUI.s_OriginalText = this.m_EnteredTextCompletion; + PopupList.s_RecycledEditor.pos = this.m_EnteredText.Length; + PopupList.s_RecycledEditor.selectPos = this.m_EnteredTextCompletion.Length; + } + } + private void DrawList(EditorWindow editorWindow, Rect windowRect) + { + Event current = Event.current; + int num = -1; + foreach (PopupList.ListElement current2 in this.m_Data.GetFilteredList(this.m_EnteredText)) + { + num++; + Rect position = new Rect(0f, 10f + (float)num * 16f + ((this.m_Gravity != PopupList.Gravity.Top || !this.m_Data.m_AllowCustom) ? 0f : 16f), windowRect.width, 16f); + EventType type = current.type; + switch (type) + { + case EventType.MouseDown: + if (Event.current.button == 0 && position.Contains(Event.current.mousePosition)) + { + if (this.m_Data.m_OnSelectCallback != null) + { + this.m_Data.m_OnSelectCallback(current2); + } + current.Use(); + if (this.m_Data.m_CloseOnSelection) + { + editorWindow.Close(); + } + } + continue; + case EventType.MouseUp: + { + IL_9B: + if (type != EventType.Repaint) + { + continue; + } + GUIStyle gUIStyle = (!current2.partiallySelected) ? PopupList.s_Styles.menuItem : PopupList.s_Styles.menuItemMixed; + bool flag = current2.selected || current2.partiallySelected; + bool hasKeyboardFocus = false; + bool isHover = num == this.m_SelectedCompletionIndex; + bool isActive = flag; + GUIContent content = current2.m_Content; + gUIStyle.Draw(position, content, isHover, isActive, flag, hasKeyboardFocus); + continue; + } + case EventType.MouseMove: + if (position.Contains(Event.current.mousePosition)) + { + this.SelectCompletionWithIndex(num); + current.Use(); + } + continue; + } + goto IL_9B; + } + } + } +} diff --git a/UnityEditor/UnityEditor/PopupLocationHelper.cs b/UnityEditor/UnityEditor/PopupLocationHelper.cs new file mode 100644 index 00000000..9f56158f --- /dev/null +++ b/UnityEditor/UnityEditor/PopupLocationHelper.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal static class PopupLocationHelper + { + public enum PopupLocation + { + Below, + Above, + Left, + Right + } + private static float k_SpaceFromBottom + { + get + { + if (Application.platform == RuntimePlatform.OSXEditor) + { + return 10f; + } + return 0f; + } + } + public static Rect GetDropDownRect(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow) + { + return PopupLocationHelper.GetDropDownRect(buttonRect, minSize, maxSize, popupContainerWindow, null); + } + public static Rect GetDropDownRect(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + if (locationPriorityOrder == null) + { + locationPriorityOrder = new PopupLocationHelper.PopupLocation[] + { + PopupLocationHelper.PopupLocation.Below, + PopupLocationHelper.PopupLocation.Above + }; + } + List list = new List(); + PopupLocationHelper.PopupLocation[] array = locationPriorityOrder; + for (int i = 0; i < array.Length; i++) + { + switch (array[i]) + { + case PopupLocationHelper.PopupLocation.Below: + { + Rect rect; + if (PopupLocationHelper.PopupBelow(buttonRect, minSize, maxSize, popupContainerWindow, out rect)) + { + return rect; + } + list.Add(rect); + break; + } + case PopupLocationHelper.PopupLocation.Above: + { + Rect rect; + if (PopupLocationHelper.PopupAbove(buttonRect, minSize, maxSize, popupContainerWindow, out rect)) + { + return rect; + } + list.Add(rect); + break; + } + case PopupLocationHelper.PopupLocation.Left: + { + Rect rect; + if (PopupLocationHelper.PopupLeft(buttonRect, minSize, maxSize, popupContainerWindow, out rect)) + { + return rect; + } + list.Add(rect); + break; + } + case PopupLocationHelper.PopupLocation.Right: + { + Rect rect; + if (PopupLocationHelper.PopupRight(buttonRect, minSize, maxSize, popupContainerWindow, out rect)) + { + return rect; + } + list.Add(rect); + break; + } + } + } + return PopupLocationHelper.GetLargestRect(list); + } + private static Rect FitRect(Rect rect, ContainerWindow popupContainerWindow) + { + if (popupContainerWindow) + { + return popupContainerWindow.FitWindowRectToScreen(rect, true, true); + } + return ContainerWindow.FitRectToScreen(rect, true, true); + } + private static bool PopupRight(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow, out Rect resultRect) + { + Rect rect = new Rect(buttonRect.xMax, buttonRect.y, maxSize.x, maxSize.y); + float num = 0f; + rect.xMax += num; + rect.height += PopupLocationHelper.k_SpaceFromBottom; + rect = PopupLocationHelper.FitRect(rect, popupContainerWindow); + float num2 = Mathf.Max(rect.xMax - buttonRect.xMax - num, 0f); + float width = Mathf.Min(num2, maxSize.x); + resultRect = new Rect(rect.x, rect.y, width, rect.height - PopupLocationHelper.k_SpaceFromBottom); + return num2 >= minSize.x; + } + private static bool PopupLeft(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow, out Rect resultRect) + { + Rect rect = new Rect(buttonRect.x - maxSize.x, buttonRect.y, maxSize.x, maxSize.y); + float num = 0f; + rect.xMin -= num; + rect.height += PopupLocationHelper.k_SpaceFromBottom; + rect = PopupLocationHelper.FitRect(rect, popupContainerWindow); + float num2 = Mathf.Max(buttonRect.x - rect.x - num, 0f); + float width = Mathf.Min(num2, maxSize.x); + resultRect = new Rect(rect.x, rect.y, width, rect.height - PopupLocationHelper.k_SpaceFromBottom); + return num2 >= minSize.x; + } + private static bool PopupAbove(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow, out Rect resultRect) + { + Rect rect = new Rect(buttonRect.x, buttonRect.y - maxSize.y, maxSize.x, maxSize.y); + float num = 0f; + rect.yMin -= num; + rect = PopupLocationHelper.FitRect(rect, popupContainerWindow); + float num2 = Mathf.Max(buttonRect.y - rect.y - num, 0f); + if (num2 >= minSize.y) + { + float num3 = Mathf.Min(num2, maxSize.y); + resultRect = new Rect(rect.x, buttonRect.y - num3, rect.width, num3); + return true; + } + resultRect = new Rect(rect.x, buttonRect.y - num2, rect.width, num2); + return false; + } + private static bool PopupBelow(Rect buttonRect, Vector2 minSize, Vector2 maxSize, ContainerWindow popupContainerWindow, out Rect resultRect) + { + Rect rect = new Rect(buttonRect.x, buttonRect.yMax, maxSize.x, maxSize.y); + rect.height += PopupLocationHelper.k_SpaceFromBottom; + rect = PopupLocationHelper.FitRect(rect, popupContainerWindow); + float num = Mathf.Max(rect.yMax - buttonRect.yMax - PopupLocationHelper.k_SpaceFromBottom, 0f); + if (num >= minSize.y) + { + float height = Mathf.Min(num, maxSize.y); + resultRect = new Rect(rect.x, buttonRect.yMax, rect.width, height); + return true; + } + resultRect = new Rect(rect.x, buttonRect.yMax, rect.width, num); + return false; + } + private static Rect GetLargestRect(List rects) + { + Rect result = default(Rect); + foreach (Rect current in rects) + { + if (current.height * current.width > result.height * result.width) + { + result = current; + } + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/PopupWindow.cs b/UnityEditor/UnityEditor/PopupWindow.cs new file mode 100644 index 00000000..d4628e4c --- /dev/null +++ b/UnityEditor/UnityEditor/PopupWindow.cs @@ -0,0 +1,80 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class PopupWindow : EditorWindow + { + private PopupWindowContent m_WindowContent; + private Vector2 m_LastWantedSize = Vector2.zero; + private Rect m_ActivatorRect; + private static double s_LastClosedTime; + private static Rect s_LastActivatorRect; + internal PopupWindow() + { + base.hideFlags = HideFlags.DontSave; + base.wantsMouseMove = true; + } + public static void Show(Rect activatorRect, PopupWindowContent windowContent) + { + PopupWindow.Show(activatorRect, windowContent, null); + } + internal static void Show(Rect activatorRect, PopupWindowContent windowContent, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + if (PopupWindow.ShouldShowWindow(activatorRect)) + { + PopupWindow popupWindow = ScriptableObject.CreateInstance(); + if (popupWindow != null) + { + popupWindow.Init(activatorRect, windowContent, locationPriorityOrder); + } + GUIUtility.ExitGUI(); + } + } + private static bool ShouldShowWindow(Rect activatorRect) + { + bool flag = EditorApplication.timeSinceStartup - PopupWindow.s_LastClosedTime < 0.2; + if (!flag || activatorRect != PopupWindow.s_LastActivatorRect) + { + PopupWindow.s_LastActivatorRect = activatorRect; + return true; + } + return false; + } + private void Init(Rect activatorRect, PopupWindowContent windowContent, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + this.m_WindowContent = windowContent; + this.m_WindowContent.editorWindow = this; + this.m_WindowContent.OnOpen(); + this.m_ActivatorRect = GUIUtility.GUIToScreenRect(activatorRect); + base.ShowAsDropDown(this.m_ActivatorRect, this.m_WindowContent.GetWindowSize(), locationPriorityOrder); + } + internal void OnGUI() + { + this.FitWindowToContent(); + Rect rect = new Rect(0f, 0f, base.position.width, base.position.height); + this.m_WindowContent.OnGUI(rect); + GUI.Label(rect, GUIContent.none, "grey_border"); + } + private void FitWindowToContent() + { + Vector2 windowSize = this.m_WindowContent.GetWindowSize(); + if (this.m_LastWantedSize != windowSize) + { + this.m_LastWantedSize = windowSize; + Rect dropDownRect = this.m_Parent.window.GetDropDownRect(this.m_ActivatorRect, windowSize, windowSize); + this.m_Pos = dropDownRect; + Vector2 vector = new Vector2(dropDownRect.width, dropDownRect.height); + base.maxSize = vector; + base.minSize = vector; + } + } + private void OnDisable() + { + PopupWindow.s_LastClosedTime = EditorApplication.timeSinceStartup; + if (this.m_WindowContent != null) + { + this.m_WindowContent.OnClose(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PopupWindowContent.cs b/UnityEditor/UnityEditor/PopupWindowContent.cs new file mode 100644 index 00000000..fa124da4 --- /dev/null +++ b/UnityEditor/UnityEditor/PopupWindowContent.cs @@ -0,0 +1,24 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public abstract class PopupWindowContent + { + public EditorWindow editorWindow + { + get; + internal set; + } + public abstract void OnGUI(Rect rect); + public virtual Vector2 GetWindowSize() + { + return new Vector2(200f, 200f); + } + public virtual void OnOpen() + { + } + public virtual void OnClose() + { + } + } +} diff --git a/UnityEditor/UnityEditor/PopupWindowContentForNewLibrary.cs b/UnityEditor/UnityEditor/PopupWindowContentForNewLibrary.cs new file mode 100644 index 00000000..d68e7751 --- /dev/null +++ b/UnityEditor/UnityEditor/PopupWindowContentForNewLibrary.cs @@ -0,0 +1,124 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PopupWindowContentForNewLibrary : PopupWindowContent + { + private class Texts + { + public GUIContent header = new GUIContent("Create New Library"); + public GUIContent name = new GUIContent("Name"); + public GUIContent location = new GUIContent("Location"); + public GUIContent[] fileLocations = new GUIContent[] + { + new GUIContent("Preferences Folder"), + new GUIContent("Project Folder") + }; + public PresetFileLocation[] fileLocationOrder = new PresetFileLocation[] + { + PresetFileLocation.PreferencesFolder, + PresetFileLocation.ProjectFolder + }; + } + private string m_NewLibraryName = string.Empty; + private int m_SelectedIndexInPopup; + private string m_ErrorString; + private Rect m_WantedSize; + private Func m_CreateLibraryCallback; + private static PopupWindowContentForNewLibrary.Texts s_Texts; + public PopupWindowContentForNewLibrary(Func createLibraryCallback) + { + this.m_CreateLibraryCallback = createLibraryCallback; + } + public override void OnGUI(Rect rect) + { + if (PopupWindowContentForNewLibrary.s_Texts == null) + { + PopupWindowContentForNewLibrary.s_Texts = new PopupWindowContentForNewLibrary.Texts(); + } + this.KeyboardHandling(base.editorWindow); + float width = 80f; + Rect wantedSize = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + if (Event.current.type != EventType.Layout) + { + this.m_WantedSize = wantedSize; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(PopupWindowContentForNewLibrary.s_Texts.header, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + EditorGUI.BeginChangeCheck(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(PopupWindowContentForNewLibrary.s_Texts.name, new GUILayoutOption[] + { + GUILayout.Width(width) + }); + EditorGUI.FocusTextInControl("NewLibraryName"); + GUI.SetNextControlName("NewLibraryName"); + this.m_NewLibraryName = GUILayout.TextField(this.m_NewLibraryName, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(PopupWindowContentForNewLibrary.s_Texts.location, new GUILayoutOption[] + { + GUILayout.Width(width) + }); + this.m_SelectedIndexInPopup = EditorGUILayout.Popup(this.m_SelectedIndexInPopup, PopupWindowContentForNewLibrary.s_Texts.fileLocations, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + if (EditorGUI.EndChangeCheck()) + { + this.m_ErrorString = null; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (!string.IsNullOrEmpty(this.m_ErrorString)) + { + Color color = GUI.color; + GUI.color = new Color(1f, 0.8f, 0.8f); + GUILayout.Label(GUIContent.Temp(this.m_ErrorString), EditorStyles.helpBox, new GUILayoutOption[0]); + GUI.color = color; + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button(GUIContent.Temp("Create"), new GUILayoutOption[0])) + { + this.CreateLibraryAndCloseWindow(base.editorWindow); + } + GUILayout.EndHorizontal(); + GUILayout.Space(15f); + EditorGUILayout.EndVertical(); + } + public override Vector2 GetWindowSize() + { + return new Vector2(350f, (this.m_WantedSize.height <= 0f) ? 90f : this.m_WantedSize.height); + } + private void KeyboardHandling(EditorWindow editorWindow) + { + Event current = Event.current; + EventType type = current.type; + if (type == EventType.KeyDown) + { + KeyCode keyCode = current.keyCode; + if (keyCode != KeyCode.Return) + { + if (keyCode == KeyCode.Escape) + { + editorWindow.Close(); + goto IL_57; + } + if (keyCode != KeyCode.KeypadEnter) + { + goto IL_57; + } + } + this.CreateLibraryAndCloseWindow(editorWindow); + IL_57:; + } + } + private void CreateLibraryAndCloseWindow(EditorWindow editorWindow) + { + PresetFileLocation arg = PopupWindowContentForNewLibrary.s_Texts.fileLocationOrder[this.m_SelectedIndexInPopup]; + this.m_ErrorString = this.m_CreateLibraryCallback(this.m_NewLibraryName, arg); + if (string.IsNullOrEmpty(this.m_ErrorString)) + { + editorWindow.Close(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs b/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs new file mode 100644 index 00000000..dac71521 --- /dev/null +++ b/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs @@ -0,0 +1,119 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PopupWindowWithoutFocus : EditorWindow + { + private static PopupWindowWithoutFocus s_PopupWindowWithoutFocus; + private static double s_LastClosedTime; + private static Rect s_LastActivatorRect; + private PopupWindowContent m_WindowContent; + private PopupLocationHelper.PopupLocation[] m_LocationPriorityOrder; + private Vector2 m_LastWantedSize = Vector2.zero; + private Rect m_ActivatorRect; + private float m_BorderWidth = 1f; + private PopupWindowWithoutFocus() + { + base.hideFlags = HideFlags.DontSave; + } + public static void Show(Rect activatorRect, PopupWindowContent windowContent) + { + PopupWindowWithoutFocus.Show(activatorRect, windowContent, null); + } + public static bool IsVisible() + { + return PopupWindowWithoutFocus.s_PopupWindowWithoutFocus != null; + } + internal static void Show(Rect activatorRect, PopupWindowContent windowContent, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + if (PopupWindowWithoutFocus.ShouldShowWindow(activatorRect)) + { + if (PopupWindowWithoutFocus.s_PopupWindowWithoutFocus == null) + { + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus = ScriptableObject.CreateInstance(); + } + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus.Init(activatorRect, windowContent, locationPriorityOrder); + } + } + public static void Hide() + { + if (PopupWindowWithoutFocus.s_PopupWindowWithoutFocus != null) + { + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus.Close(); + } + } + private void Init(Rect activatorRect, PopupWindowContent windowContent, PopupLocationHelper.PopupLocation[] locationPriorityOrder) + { + this.m_WindowContent = windowContent; + this.m_ActivatorRect = GUIUtility.GUIToScreenRect(activatorRect); + this.m_LastWantedSize = windowContent.GetWindowSize(); + this.m_LocationPriorityOrder = locationPriorityOrder; + Vector2 vector = windowContent.GetWindowSize() + new Vector2(this.m_BorderWidth * 2f, this.m_BorderWidth * 2f); + base.position = PopupLocationHelper.GetDropDownRect(this.m_ActivatorRect, vector, vector, null, this.m_LocationPriorityOrder); + base.ShowPopup(); + base.Repaint(); + } + private void OnEnable() + { + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus = this; + } + private void OnDisable() + { + PopupWindowWithoutFocus.s_LastClosedTime = EditorApplication.timeSinceStartup; + if (this.m_WindowContent != null) + { + this.m_WindowContent.OnClose(); + } + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus = null; + } + private static bool OnGlobalMouseOrKeyEvent(EventType type, KeyCode keyCode, Vector2 mousePosition) + { + if (PopupWindowWithoutFocus.s_PopupWindowWithoutFocus == null) + { + return false; + } + if (type == EventType.KeyDown && keyCode == KeyCode.Escape) + { + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus.Close(); + return true; + } + if (type == EventType.MouseDown && !PopupWindowWithoutFocus.s_PopupWindowWithoutFocus.position.Contains(mousePosition)) + { + PopupWindowWithoutFocus.s_PopupWindowWithoutFocus.Close(); + return true; + } + return false; + } + private static bool ShouldShowWindow(Rect activatorRect) + { + bool flag = EditorApplication.timeSinceStartup - PopupWindowWithoutFocus.s_LastClosedTime < 0.2; + if (!flag || activatorRect != PopupWindowWithoutFocus.s_LastActivatorRect) + { + PopupWindowWithoutFocus.s_LastActivatorRect = activatorRect; + return true; + } + return false; + } + internal void OnGUI() + { + this.FitWindowToContent(); + Rect rect = new Rect(this.m_BorderWidth, this.m_BorderWidth, base.position.width - 2f * this.m_BorderWidth, base.position.height - 2f * this.m_BorderWidth); + this.m_WindowContent.OnGUI(rect); + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, "grey_border"); + } + private void FitWindowToContent() + { + Vector2 windowSize = this.m_WindowContent.GetWindowSize(); + if (this.m_LastWantedSize != windowSize) + { + this.m_LastWantedSize = windowSize; + Vector2 vector = windowSize + new Vector2(2f * this.m_BorderWidth, 2f * this.m_BorderWidth); + Rect dropDownRect = PopupLocationHelper.GetDropDownRect(this.m_ActivatorRect, vector, vector, null, this.m_LocationPriorityOrder); + this.m_Pos = dropDownRect; + Vector2 vector2 = new Vector2(dropDownRect.width, dropDownRect.height); + base.maxSize = vector2; + base.minSize = vector2; + } + } + } +} diff --git a/UnityEditor/UnityEditor/PostProcessAttribute.cs b/UnityEditor/UnityEditor/PostProcessAttribute.cs new file mode 100644 index 00000000..717e74bb --- /dev/null +++ b/UnityEditor/UnityEditor/PostProcessAttribute.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditor +{ + [Obsolete("PostProcessAttribute has been renamed to CallbackOrderAttribute.")] + public abstract class PostProcessAttribute : CallbackOrderAttribute + { + [Obsolete("PostProcessAttribute has been renamed. Use m_CallbackOrder of CallbackOrderAttribute.")] + protected int m_PostprocessOrder; + [Obsolete("PostProcessAttribute has been renamed. Use callbackOrder of CallbackOrderAttribute.")] + internal int GetPostprocessOrder + { + get + { + return this.m_PostprocessOrder; + } + } + } +} diff --git a/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs b/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs new file mode 100644 index 00000000..6f14635f --- /dev/null +++ b/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs @@ -0,0 +1,466 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using UnityEditor.Modules; +using UnityEditor.Utils; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PostprocessBuildPlayer + { + internal const string StreamingAssets = "Assets/StreamingAssets"; + public static string subDir32Bit + { + get + { + return "x86"; + } + } + public static string subDir64Bit + { + get + { + return "x86_64"; + } + } + internal static string GenerateBundleIdentifier(string companyName, string productName) + { + return "unity." + companyName + "." + productName; + } + internal static void InstallPlugins(string destPluginFolder, BuildTarget target) + { + string text = "Assets/Plugins"; + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor != null) + { + bool flag; + string[] array = buildPostProcessor.FindPluginFilesToCopy(text, out flag); + if (array != null) + { + if (array.Length > 0 && !Directory.Exists(destPluginFolder)) + { + Directory.CreateDirectory(destPluginFolder); + } + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text2 = array2[i]; + if (Directory.Exists(text2)) + { + string target2 = Path.Combine(destPluginFolder, text2); + FileUtil.CopyDirectoryRecursive(text2, target2); + } + else + { + string fileName = Path.GetFileName(text2); + if (flag) + { + string directoryName = Path.GetDirectoryName(text2.Substring(text.Length + 1)); + string text3 = Path.Combine(destPluginFolder, directoryName); + string to = Path.Combine(text3, fileName); + if (!Directory.Exists(text3)) + { + Directory.CreateDirectory(text3); + } + FileUtil.UnityFileCopy(text2, to); + } + else + { + string to2 = Path.Combine(destPluginFolder, fileName); + FileUtil.UnityFileCopy(text2, to2); + } + } + } + return; + } + } + bool flag2 = false; + List list = new List(); + bool flag3 = target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal; + bool copyDirectories = flag3; + string extension = string.Empty; + string debugExtension = string.Empty; + if (flag3) + { + extension = ".bundle"; + list.Add(string.Empty); + } + else + { + if (target == BuildTarget.StandaloneWindows) + { + extension = ".dll"; + debugExtension = ".pdb"; + PostprocessBuildPlayer.AddPluginSubdirIfExists(list, text, PostprocessBuildPlayer.subDir32Bit); + } + else + { + if (target == BuildTarget.StandaloneWindows64) + { + extension = ".dll"; + debugExtension = ".pdb"; + PostprocessBuildPlayer.AddPluginSubdirIfExists(list, text, PostprocessBuildPlayer.subDir64Bit); + } + else + { + if (target == BuildTarget.StandaloneGLESEmu) + { + extension = ".dll"; + debugExtension = ".pdb"; + list.Add(string.Empty); + } + else + { + if (target == BuildTarget.StandaloneLinux) + { + extension = ".so"; + PostprocessBuildPlayer.AddPluginSubdirIfExists(list, text, PostprocessBuildPlayer.subDir32Bit); + } + else + { + if (target == BuildTarget.StandaloneLinux64) + { + extension = ".so"; + PostprocessBuildPlayer.AddPluginSubdirIfExists(list, text, PostprocessBuildPlayer.subDir64Bit); + } + else + { + if (target == BuildTarget.StandaloneLinuxUniversal) + { + extension = ".so"; + list.Add(PostprocessBuildPlayer.subDir32Bit); + list.Add(PostprocessBuildPlayer.subDir64Bit); + flag2 = true; + } + else + { + if (target == BuildTarget.PS3) + { + extension = ".sprx"; + list.Add(string.Empty); + } + else + { + if (target == BuildTarget.Android) + { + extension = ".so"; + list.Add("Android"); + } + else + { + if (target == BuildTarget.BB10) + { + extension = ".so"; + list.Add("BlackBerry"); + } + } + } + } + } + } + } + } + } + } + foreach (string current in list) + { + if (flag2) + { + PostprocessBuildPlayer.InstallPluginsByExtension(Path.Combine(text, current), extension, debugExtension, Path.Combine(destPluginFolder, current), copyDirectories); + } + else + { + PostprocessBuildPlayer.InstallPluginsByExtension(Path.Combine(text, current), extension, debugExtension, destPluginFolder, copyDirectories); + } + } + } + private static void AddPluginSubdirIfExists(List subdirs, string basedir, string subdir) + { + if (Directory.Exists(Path.Combine(basedir, subdir))) + { + subdirs.Add(subdir); + } + else + { + subdirs.Add(string.Empty); + } + } + internal static bool IsPlugin(string path, string targetExtension) + { + return string.Compare(Path.GetExtension(path), targetExtension, true) == 0 || string.Compare(Path.GetFileName(path), targetExtension, true) == 0; + } + internal static bool InstallPluginsByExtension(string pluginSourceFolder, string extension, string debugExtension, string destPluginFolder, bool copyDirectories) + { + bool result = false; + if (!Directory.Exists(pluginSourceFolder)) + { + return result; + } + string[] fileSystemEntries = Directory.GetFileSystemEntries(pluginSourceFolder); + string[] array = fileSystemEntries; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + string fileName = Path.GetFileName(text); + string extension2 = Path.GetExtension(text); + bool flag = extension2.Equals(extension, StringComparison.OrdinalIgnoreCase) || fileName.Equals(extension, StringComparison.OrdinalIgnoreCase); + bool flag2 = debugExtension != null && debugExtension.Length != 0 && (extension2.Equals(debugExtension, StringComparison.OrdinalIgnoreCase) || fileName.Equals(debugExtension, StringComparison.OrdinalIgnoreCase)); + if (flag || flag2) + { + if (!Directory.Exists(destPluginFolder)) + { + Directory.CreateDirectory(destPluginFolder); + } + string text2 = Path.Combine(destPluginFolder, fileName); + if (copyDirectories) + { + FileUtil.CopyDirectoryRecursive(text, text2); + } + else + { + if (!Directory.Exists(text)) + { + FileUtil.UnityFileCopy(text, text2); + } + } + result = true; + } + } + return result; + } + internal static void InstallStreamingAssets(string stagingAreaDataPath) + { + if (Directory.Exists("Assets/StreamingAssets")) + { + FileUtil.CopyDirectoryRecursiveForPostprocess("Assets/StreamingAssets", Path.Combine(stagingAreaDataPath, "StreamingAssets"), true); + } + } + public static string GetExtensionForBuildTarget(BuildTarget target) + { + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor != null) + { + return buildPostProcessor.GetExtension(); + } + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + case BuildTarget.StandaloneOSXIntel64: + return "app"; + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneGLESEmu: + case BuildTarget.StandaloneWindows64: + return "exe"; + case BuildTarget.WebPlayer: + case BuildTarget.WebPlayerStreamed: + return string.Empty; + case BuildTarget.StandaloneLinux: + case BuildTarget.StandaloneLinux64: + case BuildTarget.StandaloneLinuxUniversal: + return PostprocessBuildPlayer.GetArchitectureForTarget(target); + case BuildTarget.FlashPlayer: + return "swf"; + case BuildTarget.MetroPlayer: + return (EditorUserBuildSettings.metroBuildType != MetroBuildType.AppX) ? string.Empty : "appx"; + } + return string.Empty; + } + public static bool SupportsInstallInBuildFolder(BuildTarget target) + { + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor != null) + { + return buildPostProcessor.SupportsInstallInBuildFolder(); + } + switch (target) + { + case BuildTarget.WP8Player: + case BuildTarget.StandaloneOSXIntel64: + case BuildTarget.PSP2: + case BuildTarget.PSM: + return true; + case BuildTarget.BB10: + case BuildTarget.Tizen: + case BuildTarget.PS4: + IL_3B: + switch (target) + { + case BuildTarget.PS3: + case BuildTarget.Android: + case BuildTarget.StandaloneGLESEmu: + return true; + case BuildTarget.XBOX360: + case (BuildTarget)12: + IL_58: + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + case BuildTarget.StandaloneWindows: + return true; + case (BuildTarget)3: + IL_70: + switch (target) + { + case BuildTarget.StandaloneWindows64: + case BuildTarget.MetroPlayer: + return true; + } + return false; + } + goto IL_70; + } + goto IL_58; + } + goto IL_3B; + } + public static void Launch(BuildTarget target, string path, string productName, BuildOptions options) + { + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor != null) + { + BuildLaunchPlayerArgs args; + args.target = target; + args.playerPackage = BuildPipeline.GetPlaybackEngineDirectory(target, options); + args.installPath = path; + args.productName = productName; + args.options = options; + buildPostProcessor.LaunchPlayer(args); + } + else + { + if (target != BuildTarget.NaCl) + { + throw new UnityException(string.Format("Launching {0} build target via mono is not supported", target)); + } + PostProcessNaclPlayer.Launch(target, path); + } + } + public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry) + { + string stagingArea = "Temp/StagingArea"; + string stagingAreaData = "Temp/StagingArea/Data"; + string stagingAreaDataManaged = "Temp/StagingArea/Data/Managed"; + string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(target, options); + bool flag = (options & BuildOptions.InstallInBuildFolder) != BuildOptions.None && PostprocessBuildPlayer.SupportsInstallInBuildFolder(target); + if (installPath == string.Empty && !flag) + { + throw new Exception(installPath + " must not be an empty string"); + } + BuildPostProcessArgs buildPostProcessArgs = new BuildPostProcessArgs + { + target = target, + stagingAreaData = stagingAreaData, + stagingArea = stagingArea, + stagingAreaDataManaged = stagingAreaDataManaged, + playerPackage = playbackEngineDirectory, + installPath = installPath, + companyName = companyName, + productName = productName, + productGUID = PlayerSettings.productGUID, + options = options, + usedClassRegistry = usedClassRegistry + }; + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor != null) + { + buildPostProcessor.PostProcess(buildPostProcessArgs); + return; + } + switch (target) + { + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + case BuildTarget.StandaloneOSXIntel64: + new OSXDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); + return; + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneGLESEmu: + case BuildTarget.StandaloneWindows64: + new WindowsDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); + return; + case BuildTarget.WebPlayer: + case BuildTarget.WebPlayerStreamed: + PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); + return; + case BuildTarget.NaCl: + PostProcessNaclPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); + return; + case BuildTarget.StandaloneLinux: + case BuildTarget.StandaloneLinux64: + case BuildTarget.StandaloneLinuxUniversal: + new LinuxDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); + return; + case BuildTarget.FlashPlayer: + PostProcessFlashPlayer.PostProcess(new PostProcessFlashPlayerOptions + { + Target = target, + StagingAreaData = stagingAreaData, + StagingArea = stagingArea, + StagingAreaDataManaged = stagingAreaDataManaged, + PlayerPackage = playbackEngineDirectory, + InstallPath = installPath, + CompanyName = companyName, + ProductName = productName, + Options = options, + UsedClassRegistry = usedClassRegistry, + Width = width, + Height = height + }); + return; + } + throw new UnityException(string.Format("Build target '{0}' not supported", target)); + } + internal static string ExecuteSystemProcess(string command, string args, string workingdir) + { + ProcessStartInfo si = new ProcessStartInfo + { + FileName = command, + Arguments = args, + WorkingDirectory = workingdir, + CreateNoWindow = true + }; + Program program = new Program(si); + program.Start(); + while (!program.WaitForExit(100)) + { + } + string standardOutputAsString = program.GetStandardOutputAsString(); + program.Dispose(); + return standardOutputAsString; + } + internal static string GetArchitectureForTarget(BuildTarget target) + { + switch (target) + { + case BuildTarget.StandaloneLinux: + goto IL_40; + case BuildTarget.FlashPlayer: + IL_17: + if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneWindows) + { + goto IL_40; + } + if (target == BuildTarget.StandaloneLinux64) + { + goto IL_3A; + } + if (target != BuildTarget.StandaloneLinuxUniversal) + { + return string.Empty; + } + goto IL_40; + case BuildTarget.StandaloneWindows64: + goto IL_3A; + } + goto IL_17; + IL_3A: + return "x86_64"; + IL_40: + return "x86"; + } + } +} diff --git a/UnityEditor/UnityEditor/PostprocessScene.cs b/UnityEditor/UnityEditor/PostprocessScene.cs new file mode 100644 index 00000000..9f16af80 --- /dev/null +++ b/UnityEditor/UnityEditor/PostprocessScene.cs @@ -0,0 +1,23 @@ +using System; +using UnityEditor.Callbacks; +using UnityEngine; +namespace UnityEditor +{ + internal class PostprocessScene + { + internal class UnityBuildPostprocessor + { + [PostProcessScene(0)] + public static void OnPostprocessScene() + { + int num; + int num2; + PlayerSettings.GetBatchingForPlatform(EditorUserBuildSettings.activeBuildTarget, out num, out num2); + if (num != 0 && PlayerSettings.advancedLicense) + { + InternalStaticBatchingUtility.Combine(null, true); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/PragmaFixingWindow.cs b/UnityEditor/UnityEditor/PragmaFixingWindow.cs new file mode 100644 index 00000000..81b0732e --- /dev/null +++ b/UnityEditor/UnityEditor/PragmaFixingWindow.cs @@ -0,0 +1,79 @@ +using System; +using UnityEditor.Scripting; +using UnityEngine; +namespace UnityEditor +{ + internal class PragmaFixingWindow : EditorWindow + { + private class Styles + { + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle box = "OL Box"; + public GUIStyle button = "LargeButton"; + } + private static PragmaFixingWindow.Styles s_Styles; + private ListViewState m_LV = new ListViewState(); + private string[] m_Paths; + public PragmaFixingWindow() + { + base.title = "Unity - #pragma fixing"; + } + public static void ShowWindow(string[] paths) + { + PragmaFixingWindow window = EditorWindow.GetWindow(true); + window.SetPaths(paths); + window.ShowModal(); + } + public void SetPaths(string[] paths) + { + this.m_Paths = paths; + this.m_LV.totalRows = paths.Length; + } + private void OnGUI() + { + if (PragmaFixingWindow.s_Styles == null) + { + PragmaFixingWindow.s_Styles = new PragmaFixingWindow.Styles(); + base.minSize = new Vector2(450f, 300f); + base.position = new Rect(base.position.x, base.position.y, base.minSize.x, base.minSize.y); + } + GUILayout.Space(10f); + GUILayout.Label("#pragma implicit and #pragma downcast need to be added to following files\nfor backwards compatibility", new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + foreach (ListViewElement listViewElement in ListViewGUILayout.ListView(this.m_LV, PragmaFixingWindow.s_Styles.box, new GUILayoutOption[0])) + { + if (listViewElement.row == this.m_LV.row && Event.current.type == EventType.Repaint) + { + PragmaFixingWindow.s_Styles.selected.Draw(listViewElement.position, false, false, false, false); + } + GUILayout.Label(this.m_Paths[listViewElement.row], new GUILayoutOption[0]); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Fix now", PragmaFixingWindow.s_Styles.button, new GUILayoutOption[0])) + { + base.Close(); + PragmaFixing30.FixFiles(this.m_Paths); + GUIUtility.ExitGUI(); + } + if (GUILayout.Button("Ignore", PragmaFixingWindow.s_Styles.button, new GUILayoutOption[0])) + { + base.Close(); + GUIUtility.ExitGUI(); + } + if (GUILayout.Button("Quit", PragmaFixingWindow.s_Styles.button, new GUILayoutOption[0])) + { + EditorApplication.Exit(0); + GUIUtility.ExitGUI(); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + } + } +} diff --git a/UnityEditor/UnityEditor/PrefColor.cs b/UnityEditor/UnityEditor/PrefColor.cs new file mode 100644 index 00000000..8caa5356 --- /dev/null +++ b/UnityEditor/UnityEditor/PrefColor.cs @@ -0,0 +1,93 @@ +using System; +using System.Globalization; +using UnityEngine; +namespace UnityEditor +{ + internal class PrefColor : IPrefType + { + private string m_name; + private Color m_color; + private Color m_DefaultColor; + public Color Color + { + get + { + return this.m_color; + } + set + { + this.m_color = value; + } + } + public string Name + { + get + { + return this.m_name; + } + } + public PrefColor() + { + } + public PrefColor(string name, float defaultRed, float defaultGreen, float defaultBlue, float defaultAlpha) + { + this.m_name = name; + this.m_color = (this.m_DefaultColor = new Color(defaultRed, defaultGreen, defaultBlue, defaultAlpha)); + PrefColor prefColor = Settings.Get(name, this); + this.m_name = prefColor.Name; + this.m_color = prefColor.Color; + } + public string ToUniqueString() + { + return string.Format(CultureInfo.InvariantCulture, "{0};{1};{2};{3};{4}", new object[] + { + this.m_name, + this.Color.r, + this.Color.g, + this.Color.b, + this.Color.a + }); + } + public void FromUniqueString(string s) + { + string[] array = s.Split(new char[] + { + ';' + }); + if (array.Length != 5) + { + Debug.LogError("Parsing PrefColor failed"); + return; + } + this.m_name = array[0]; + array[1] = array[1].Replace(',', '.'); + array[2] = array[2].Replace(',', '.'); + array[3] = array[3].Replace(',', '.'); + array[4] = array[4].Replace(',', '.'); + float r; + bool flag = float.TryParse(array[1], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out r); + float g; + flag &= float.TryParse(array[2], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out g); + float b; + flag &= float.TryParse(array[3], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out b); + float a; + flag &= float.TryParse(array[4], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out a); + if (flag) + { + this.m_color = new Color(r, g, b, a); + } + else + { + Debug.LogError("Parsing PrefColor failed"); + } + } + internal void ResetToDefault() + { + this.m_color = this.m_DefaultColor; + } + public static implicit operator Color(PrefColor pcolor) + { + return pcolor.Color; + } + } +} diff --git a/UnityEditor/UnityEditor/PrefKey.cs b/UnityEditor/UnityEditor/PrefKey.cs new file mode 100644 index 00000000..23819a85 --- /dev/null +++ b/UnityEditor/UnityEditor/PrefKey.cs @@ -0,0 +1,80 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PrefKey : IPrefType + { + private string m_name; + private Event m_event; + private string m_DefaultShortcut; + public string Name + { + get + { + return this.m_name; + } + } + public Event KeyboardEvent + { + get + { + return this.m_event; + } + set + { + this.m_event = value; + } + } + public bool activated + { + get + { + return Event.current.Equals(this); + } + } + public PrefKey() + { + } + public PrefKey(string name, string shortcut) + { + this.m_name = name; + this.m_event = Event.KeyboardEvent(shortcut); + this.m_DefaultShortcut = shortcut; + PrefKey prefKey = Settings.Get(name, this); + this.m_name = prefKey.Name; + this.m_event = prefKey.KeyboardEvent; + } + public string ToUniqueString() + { + return string.Concat(new object[] + { + this.m_name, + ";", + (!this.m_event.alt) ? string.Empty : "&", + (!this.m_event.command) ? string.Empty : "%", + (!this.m_event.shift) ? string.Empty : "#", + (!this.m_event.control) ? string.Empty : "^", + this.m_event.keyCode + }); + } + public void FromUniqueString(string s) + { + int num = s.IndexOf(";"); + if (num < 0) + { + Debug.LogError("Malformed string in Keyboard preferences"); + return; + } + this.m_name = s.Substring(0, num); + this.m_event = Event.KeyboardEvent(s.Substring(num + 1)); + } + internal void ResetToDefault() + { + this.m_event = Event.KeyboardEvent(this.m_DefaultShortcut); + } + public static implicit operator Event(PrefKey pkey) + { + return pkey.m_event; + } + } +} diff --git a/UnityEditor/UnityEditor/PrefabInspector.cs b/UnityEditor/UnityEditor/PrefabInspector.cs new file mode 100644 index 00000000..8a77f5f1 --- /dev/null +++ b/UnityEditor/UnityEditor/PrefabInspector.cs @@ -0,0 +1,51 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PrefabInspector + { + public static void OnOverridenPrefabsInspector(GameObject gameObject) + { + GUI.enabled = true; + UnityEngine.Object prefabObject = PrefabUtility.GetPrefabObject(gameObject); + if (prefabObject == null) + { + return; + } + EditorGUIUtility.labelWidth = 200f; + if (PrefabUtility.GetPrefabType(gameObject) == PrefabType.PrefabInstance) + { + PropertyModification[] propertyModifications = PrefabUtility.GetPropertyModifications(gameObject); + if (propertyModifications != null && propertyModifications.Length != 0) + { + GUI.changed = false; + for (int i = 0; i < propertyModifications.Length; i++) + { + propertyModifications[i].value = EditorGUILayout.TextField(propertyModifications[i].propertyPath, propertyModifications[i].value, new GUILayoutOption[0]); + } + if (GUI.changed) + { + PrefabUtility.SetPropertyModifications(gameObject, propertyModifications); + } + } + } + PrefabInspector.AddComponentGUI(prefabObject); + } + private static void AddComponentGUI(UnityEngine.Object prefab) + { + SerializedObject serializedObject = new SerializedObject(prefab); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_Modification"); + SerializedProperty endProperty = serializedProperty.GetEndProperty(); + do + { + bool enterChildren = EditorGUILayout.PropertyField(serializedProperty, new GUILayoutOption[0]); + if (!serializedProperty.NextVisible(enterChildren)) + { + break; + } + } + while (!SerializedProperty.EqualContents(serializedProperty, endProperty)); + serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/PrefabType.cs b/UnityEditor/UnityEditor/PrefabType.cs new file mode 100644 index 00000000..53db99d8 --- /dev/null +++ b/UnityEditor/UnityEditor/PrefabType.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor +{ + public enum PrefabType + { + None, + Prefab, + ModelPrefab, + PrefabInstance, + ModelPrefabInstance, + MissingPrefabInstance, + DisconnectedPrefabInstance, + DisconnectedModelPrefabInstance + } +} diff --git a/UnityEditor/UnityEditor/PrefabUtility.cs b/UnityEditor/UnityEditor/PrefabUtility.cs new file mode 100644 index 00000000..71fdcc96 --- /dev/null +++ b/UnityEditor/UnityEditor/PrefabUtility.cs @@ -0,0 +1,97 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public sealed class PrefabUtility + { + public delegate void PrefabInstanceUpdated(GameObject instance); + public static PrefabUtility.PrefabInstanceUpdated prefabInstanceUpdated; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetPrefabParent(UnityEngine.Object source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetPrefabObject(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern PropertyModification[] GetPropertyModifications(UnityEngine.Object targetPrefab); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetPropertyModifications(UnityEngine.Object targetPrefab, PropertyModification[] modifications); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object InstantiateAttachedAsset(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RecordPrefabInstancePropertyModifications(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MergeAllPrefabInstances(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool IsPrefabExploded(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetIsPrefabExploded(UnityEngine.Object targetObject, bool exploded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DisconnectPrefabInstance(UnityEngine.Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object InstantiatePrefab(UnityEngine.Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object CreateEmptyPrefab(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject CreatePrefab(string path, GameObject go, [DefaultValue("ReplacePrefabOptions.Default")] ReplacePrefabOptions options); + [ExcludeFromDocs] + public static GameObject CreatePrefab(string path, GameObject go) + { + ReplacePrefabOptions options = ReplacePrefabOptions.Default; + return PrefabUtility.CreatePrefab(path, go, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject ReplacePrefab(GameObject go, UnityEngine.Object targetPrefab, [DefaultValue("ReplacePrefabOptions.Default")] ReplacePrefabOptions options); + [ExcludeFromDocs] + public static GameObject ReplacePrefab(GameObject go, UnityEngine.Object targetPrefab) + { + ReplacePrefabOptions options = ReplacePrefabOptions.Default; + return PrefabUtility.ReplacePrefab(go, targetPrefab, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject FindRootGameObjectWithSameParentPrefab(GameObject target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject FindValidUploadPrefabInstanceRoot(GameObject target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ReconnectToLastPrefab(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ResetToPrefabState(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsComponentAddedToPrefabInstance(UnityEngine.Object source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool RevertPrefabInstance(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern PrefabType GetPrefabType(UnityEngine.Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject FindPrefabRoot(GameObject source); + private static void Internal_CallPrefabInstanceUpdated(GameObject instance) + { + if (PrefabUtility.prefabInstanceUpdated != null) + { + PrefabUtility.prefabInstanceUpdated(instance); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PreferenceItem.cs b/UnityEditor/UnityEditor/PreferenceItem.cs new file mode 100644 index 00000000..5a2f2e7f --- /dev/null +++ b/UnityEditor/UnityEditor/PreferenceItem.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Method)] + public sealed class PreferenceItem : Attribute + { + public string name; + public PreferenceItem(string name) + { + this.name = name; + } + } +} diff --git a/UnityEditor/UnityEditor/PreferencesWindow.cs b/UnityEditor/UnityEditor/PreferencesWindow.cs new file mode 100644 index 00000000..a899cf5c --- /dev/null +++ b/UnityEditor/UnityEditor/PreferencesWindow.cs @@ -0,0 +1,838 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using UnityEditor.Modules; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PreferencesWindow : EditorWindow + { + internal class Constants + { + public GUIStyle sectionScrollView = "PreferencesSectionBox"; + public GUIStyle settingsBoxTitle = "OL Title"; + public GUIStyle settingsBox = "OL Box"; + public GUIStyle errorLabel = "WordWrappedLabel"; + public GUIStyle sectionElement = "PreferencesSection"; + public GUIStyle evenRow = "CN EntryBackEven"; + public GUIStyle oddRow = "CN EntryBackOdd"; + public GUIStyle selected = "ServerUpdateChangesetOn"; + public GUIStyle keysElement = "PreferencesKeysElement"; + public GUIStyle sectionHeader = new GUIStyle(EditorStyles.largeLabel); + public Constants() + { + this.sectionScrollView = new GUIStyle(this.sectionScrollView); + this.sectionScrollView.overflow.bottom++; + this.sectionHeader.fontStyle = FontStyle.Bold; + this.sectionHeader.fontSize = 18; + this.sectionHeader.margin.top = 10; + this.sectionHeader.margin.left++; + if (!EditorGUIUtility.isProSkin) + { + this.sectionHeader.normal.textColor = new Color(0.4f, 0.4f, 0.4f, 1f); + } + else + { + this.sectionHeader.normal.textColor = new Color(0.7f, 0.7f, 0.7f, 1f); + } + } + } + private class Section + { + public GUIContent content; + public PreferencesWindow.OnGUIDelegate guiFunc; + public Section(string name, PreferencesWindow.OnGUIDelegate guiFunc) + { + this.content = new GUIContent(name); + this.guiFunc = guiFunc; + } + public Section(string name, Texture2D icon, PreferencesWindow.OnGUIDelegate guiFunc) + { + this.content = new GUIContent(name, icon); + this.guiFunc = guiFunc; + } + public Section(GUIContent content, PreferencesWindow.OnGUIDelegate guiFunc) + { + this.content = content; + this.guiFunc = guiFunc; + } + } + private class RefString + { + public string str; + public RefString(string s) + { + this.str = s; + } + public override string ToString() + { + return this.str; + } + public static implicit operator string(PreferencesWindow.RefString s) + { + return s.str; + } + } + private class AppsListUserData + { + public string[] paths; + public PreferencesWindow.RefString str; + public Action onChanged; + public AppsListUserData(string[] paths, PreferencesWindow.RefString str, Action onChanged) + { + this.paths = paths; + this.str = str; + this.onChanged = onChanged; + } + } + private delegate void OnGUIDelegate(); + private const string kRecentScriptAppsKey = "RecentlyUsedScriptApp"; + private const string kRecentImageAppsKey = "RecentlyUsedImageApp"; + private const string m_ExpressNotSupportedMessage = "Unfortunately Visual Studio Express does not allow itself to be controlled by external applications. You can still use it by manually opening the Visual Studio project file, but Unity cannot automatically open files for you when you doubleclick them. \n(This does work with Visual Studio Pro)"; + private const int kRecentAppsCount = 10; + private List m_Sections; + private int m_SelectedSectionIndex; + private static PreferencesWindow.Constants constants = null; + private List prefWinExtensions; + private bool m_AutoRefresh; + private bool m_AlwaysShowProjectWizard; + private bool m_CompressAssetsOnImport; + private bool m_UseOSColorPicker; + private bool m_EnableEditorAnalytics; + private bool m_ShowAssetStoreSearchHits; + private bool m_VerifySavingAssets; + private bool m_AllowAttachedDebuggingOfEditor; + private bool m_AllowAttachedDebuggingOfEditorStateChangedThisSession; + private PreferencesWindow.RefString m_ScriptEditorPath = new PreferencesWindow.RefString(string.Empty); + private string m_ScriptEditorArgs = string.Empty; + private PreferencesWindow.RefString m_ImageAppPath = new PreferencesWindow.RefString(string.Empty); + private int m_DiffToolIndex; + private bool m_AllowAlphaNumericHierarchy; + private string m_AndroidSdkPath = string.Empty; + private string[] m_ScriptApps; + private string[] m_ImageApps; + private string[] m_DiffTools; + private string m_noDiffToolsMessage = string.Empty; + private bool m_RefreshCustomPreferences; + private string[] m_ScriptAppDisplayNames; + private string[] m_ImageAppDisplayNames; + private Vector2 m_KeyScrollPos; + private Vector2 m_SectionScrollPos; + private PrefKey m_SelectedKey; + private SortedDictionary>> s_CachedColors; + private static Vector2 s_ColorScrollPos = Vector2.zero; + private int currentPage; + private static int s_KeysControlHash = "KeysControlHash".GetHashCode(); + private int selectedSectionIndex + { + get + { + return this.m_SelectedSectionIndex; + } + set + { + this.m_SelectedSectionIndex = value; + if (this.m_SelectedSectionIndex >= this.m_Sections.Count) + { + this.m_SelectedSectionIndex = 0; + } + else + { + if (this.m_SelectedSectionIndex < 0) + { + this.m_SelectedSectionIndex = this.m_Sections.Count - 1; + } + } + } + } + private PreferencesWindow.Section selectedSection + { + get + { + return this.m_Sections[this.m_SelectedSectionIndex]; + } + } + private static void ShowPreferencesWindow() + { + EditorWindow windowWithRect = EditorWindow.GetWindowWithRect(new Rect(100f, 100f, 500f, 400f), true, "Unity Preferences"); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + } + private void OnEnable() + { + this.prefWinExtensions = ModuleManager.GetPreferenceWindowExtensions(); + this.ReadPreferences(); + this.m_Sections = new List(); + this.m_Sections.Add(new PreferencesWindow.Section("General", new PreferencesWindow.OnGUIDelegate(this.ShowGeneral))); + this.m_Sections.Add(new PreferencesWindow.Section("External Tools", new PreferencesWindow.OnGUIDelegate(this.ShowExternalApplications))); + this.m_Sections.Add(new PreferencesWindow.Section("Colors", new PreferencesWindow.OnGUIDelegate(this.ShowColors))); + this.m_Sections.Add(new PreferencesWindow.Section("Keys", new PreferencesWindow.OnGUIDelegate(this.ShowKeys))); + this.m_RefreshCustomPreferences = true; + } + private void AddCustomSections() + { + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = 0; i < loadedAssemblies.Length; i++) + { + Assembly assembly = loadedAssemblies[i]; + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int j = 0; j < array.Length; j++) + { + Type type = array[j]; + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + for (int k = 0; k < methods.Length; k++) + { + MethodInfo methodInfo = methods[k]; + PreferenceItem preferenceItem = Attribute.GetCustomAttribute(methodInfo, typeof(PreferenceItem)) as PreferenceItem; + if (preferenceItem != null) + { + PreferencesWindow.OnGUIDelegate onGUIDelegate = Delegate.CreateDelegate(typeof(PreferencesWindow.OnGUIDelegate), methodInfo) as PreferencesWindow.OnGUIDelegate; + if (onGUIDelegate != null) + { + this.m_Sections.Add(new PreferencesWindow.Section(preferenceItem.name, onGUIDelegate)); + } + } + } + } + } + } + private void OnGUI() + { + if (this.m_RefreshCustomPreferences) + { + this.AddCustomSections(); + this.m_RefreshCustomPreferences = false; + } + EditorGUIUtility.labelWidth = 180f; + if (PreferencesWindow.constants == null) + { + PreferencesWindow.constants = new PreferencesWindow.Constants(); + } + this.HandleKeys(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_SectionScrollPos = GUILayout.BeginScrollView(this.m_SectionScrollPos, PreferencesWindow.constants.sectionScrollView, new GUILayoutOption[] + { + GUILayout.Width(120f) + }); + GUILayout.Space(40f); + for (int i = 0; i < this.m_Sections.Count; i++) + { + PreferencesWindow.Section section = this.m_Sections[i]; + Rect rect = GUILayoutUtility.GetRect(section.content, PreferencesWindow.constants.sectionElement, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (section == this.selectedSection && Event.current.type == EventType.Repaint) + { + PreferencesWindow.constants.selected.Draw(rect, false, false, false, false); + } + EditorGUI.BeginChangeCheck(); + if (GUI.Toggle(rect, this.m_SelectedSectionIndex == i, section.content, PreferencesWindow.constants.sectionElement)) + { + this.m_SelectedSectionIndex = i; + } + if (EditorGUI.EndChangeCheck()) + { + GUIUtility.keyboardControl = 0; + } + } + GUILayout.EndScrollView(); + GUILayout.Space(10f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(this.selectedSection.content, PreferencesWindow.constants.sectionHeader, new GUILayoutOption[0]); + this.selectedSection.guiFunc(); + GUILayout.Space(5f); + GUILayout.EndVertical(); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + } + private void HandleKeys() + { + if (Event.current.type != EventType.KeyDown || GUIUtility.keyboardControl != 0) + { + return; + } + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.UpArrow) + { + if (keyCode == KeyCode.DownArrow) + { + this.selectedSectionIndex++; + Event.current.Use(); + } + } + else + { + this.selectedSectionIndex--; + Event.current.Use(); + } + } + private void ShowExternalApplications() + { + GUILayout.Space(10f); + this.FilePopup("External Script Editor", this.m_ScriptEditorPath, ref this.m_ScriptAppDisplayNames, ref this.m_ScriptApps, this.m_ScriptEditorPath, new Action(this.OnScriptEditorChanged)); + if (!this.IsSelectedScriptEditorSpecial() && Application.platform != RuntimePlatform.OSXEditor) + { + string scriptEditorArgs = this.m_ScriptEditorArgs; + this.m_ScriptEditorArgs = EditorGUILayout.TextField("External Script Editor Args", this.m_ScriptEditorArgs, new GUILayoutOption[0]); + if (scriptEditorArgs != this.m_ScriptEditorArgs) + { + this.OnScriptEditorArgsChanged(); + } + } + bool allowAttachedDebuggingOfEditor = this.m_AllowAttachedDebuggingOfEditor; + this.m_AllowAttachedDebuggingOfEditor = EditorGUILayout.Toggle("Editor Attaching", this.m_AllowAttachedDebuggingOfEditor, new GUILayoutOption[0]); + if (allowAttachedDebuggingOfEditor != this.m_AllowAttachedDebuggingOfEditor) + { + this.m_AllowAttachedDebuggingOfEditorStateChangedThisSession = true; + } + if (this.m_AllowAttachedDebuggingOfEditorStateChangedThisSession) + { + GUILayout.Label("Changing this setting requires a restart to take effect.", EditorStyles.helpBox, new GUILayoutOption[0]); + } + if (this.m_ScriptEditorPath.str.Contains("VCSExpress")) + { + GUILayout.BeginHorizontal(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label(string.Empty, "CN EntryWarn", new GUILayoutOption[0]); + GUILayout.Label("Unfortunately Visual Studio Express does not allow itself to be controlled by external applications. You can still use it by manually opening the Visual Studio project file, but Unity cannot automatically open files for you when you doubleclick them. \n(This does work with Visual Studio Pro)", PreferencesWindow.constants.errorLabel, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + GUILayout.Space(10f); + this.FilePopup("Image application", this.m_ImageAppPath, ref this.m_ImageAppDisplayNames, ref this.m_ImageApps, this.m_ImageAppPath, null); + GUILayout.Space(10f); + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasMaint()); + this.m_DiffToolIndex = EditorGUILayout.Popup("Revision Control Diff/Merge", this.m_DiffToolIndex, this.m_DiffTools, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (this.m_noDiffToolsMessage != string.Empty) + { + GUILayout.BeginHorizontal(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label(string.Empty, "CN EntryWarn", new GUILayoutOption[0]); + GUILayout.Label(this.m_noDiffToolsMessage, PreferencesWindow.constants.errorLabel, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + GUILayout.Space(10f); + this.AndroidSdkLocation(); + foreach (IPreferenceWindowExtension current in this.prefWinExtensions) + { + if (current.HasExternalApplications()) + { + GUILayout.Space(10f); + current.ShowExternalApplications(); + } + } + this.ApplyChangesToPrefs(); + } + private bool IsSelectedScriptEditorSpecial() + { + string text = this.m_ScriptEditorPath.str.ToLower(); + return text == string.Empty || text.EndsWith("monodevelop.exe") || text.EndsWith("devenv.exe") || text.EndsWith("vcsexpress.exe"); + } + private void OnScriptEditorChanged() + { + if (this.IsSelectedScriptEditorSpecial()) + { + this.m_ScriptEditorArgs = string.Empty; + } + else + { + this.m_ScriptEditorArgs = EditorPrefs.GetString("kScriptEditorArgs" + this.m_ScriptEditorPath.str, "\"$(File)\""); + } + EditorPrefs.SetString("kScriptEditorArgs", this.m_ScriptEditorArgs); + } + private void OnScriptEditorArgsChanged() + { + EditorPrefs.SetString("kScriptEditorArgs" + this.m_ScriptEditorPath.str, this.m_ScriptEditorArgs); + EditorPrefs.SetString("kScriptEditorArgs", this.m_ScriptEditorArgs); + } + private void ShowGeneral() + { + GUILayout.Space(10f); + this.m_AutoRefresh = EditorGUILayout.Toggle("Auto Refresh", this.m_AutoRefresh, new GUILayoutOption[0]); + this.m_AlwaysShowProjectWizard = EditorGUILayout.Toggle("Always Show Project Wizard", this.m_AlwaysShowProjectWizard, new GUILayoutOption[0]); + bool compressAssetsOnImport = this.m_CompressAssetsOnImport; + this.m_CompressAssetsOnImport = EditorGUILayout.Toggle("Compress Assets on Import", compressAssetsOnImport, new GUILayoutOption[0]); + if (GUI.changed && this.m_CompressAssetsOnImport != compressAssetsOnImport) + { + Unsupported.SetApplicationSettingCompressAssetsOnImport(this.m_CompressAssetsOnImport); + } + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_UseOSColorPicker = EditorGUILayout.Toggle("OS X Color Picker", this.m_UseOSColorPicker, new GUILayoutOption[0]); + } + this.m_EnableEditorAnalytics = EditorGUILayout.Toggle("Editor Analytics", this.m_EnableEditorAnalytics, new GUILayoutOption[0]); + bool flag = false; + EditorGUI.BeginChangeCheck(); + this.m_ShowAssetStoreSearchHits = EditorGUILayout.Toggle("Show Asset Store search hits", this.m_ShowAssetStoreSearchHits, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + flag = true; + } + this.m_VerifySavingAssets = EditorGUILayout.Toggle("Verify Saving Assets", this.m_VerifySavingAssets, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasPro()); + int num = EditorGUILayout.Popup("Skin (Pro Only)", EditorGUIUtility.isProSkin ? 1 : 0, new string[] + { + "Light", + "Dark" + }, new GUILayoutOption[0]); + if ((EditorGUIUtility.isProSkin ? 1 : 0) != num) + { + InternalEditorUtility.SwitchSkinAndRepaintAllViews(); + } + EditorGUI.EndDisabledGroup(); + bool allowAlphaNumericHierarchy = this.m_AllowAlphaNumericHierarchy; + this.m_AllowAlphaNumericHierarchy = EditorGUILayout.Toggle("Enable Alpha Numeric Sorting", this.m_AllowAlphaNumericHierarchy, new GUILayoutOption[0]); + this.ApplyChangesToPrefs(); + if (allowAlphaNumericHierarchy != this.m_AllowAlphaNumericHierarchy) + { + EditorApplication.DirtyHierarchyWindowSorting(); + } + if (flag) + { + ProjectBrowser.ShowAssetStoreHitsWhileSearchingLocalAssetsChanged(); + } + } + private void ApplyChangesToPrefs() + { + if (GUI.changed) + { + this.WritePreferences(); + this.ReadPreferences(); + base.Repaint(); + } + } + private void RevertKeys() + { + foreach (KeyValuePair current in Settings.Prefs()) + { + current.Value.ResetToDefault(); + EditorPrefs.SetString(current.Value.Name, current.Value.ToUniqueString()); + } + } + private SortedDictionary>> OrderPrefs(IEnumerable> input) where T : IPrefType + { + SortedDictionary>> sortedDictionary = new SortedDictionary>>(); + foreach (KeyValuePair current in input) + { + int num = current.Key.IndexOf('/'); + string key; + string key2; + if (num == -1) + { + key = "General"; + key2 = current.Key; + } + else + { + key = current.Key.Substring(0, num); + key2 = current.Key.Substring(num + 1); + } + if (!sortedDictionary.ContainsKey(key)) + { + sortedDictionary.Add(key, new List>(new List> + { + new KeyValuePair(key2, current.Value) + })); + } + else + { + sortedDictionary[key].Add(new KeyValuePair(key2, current.Value)); + } + } + return sortedDictionary; + } + private void ShowKeys() + { + int controlID = GUIUtility.GetControlID(PreferencesWindow.s_KeysControlHash, FocusType.Keyboard); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(185f) + }); + GUILayout.Label("Actions", PreferencesWindow.constants.settingsBoxTitle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + this.m_KeyScrollPos = GUILayout.BeginScrollView(this.m_KeyScrollPos, PreferencesWindow.constants.settingsBox); + PrefKey prefKey = null; + PrefKey prefKey2 = null; + bool flag = false; + foreach (KeyValuePair current in Settings.Prefs()) + { + if (!flag) + { + if (current.Value == this.m_SelectedKey) + { + flag = true; + } + else + { + prefKey = current.Value; + } + } + else + { + if (prefKey2 == null) + { + prefKey2 = current.Value; + } + } + EditorGUI.BeginChangeCheck(); + if (GUILayout.Toggle(current.Value == this.m_SelectedKey, current.Key, PreferencesWindow.constants.keysElement, new GUILayoutOption[0])) + { + this.m_SelectedKey = current.Value; + } + if (EditorGUI.EndChangeCheck()) + { + GUIUtility.keyboardControl = controlID; + } + } + GUILayout.EndScrollView(); + GUILayout.EndVertical(); + GUILayout.Space(10f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (this.m_SelectedKey != null) + { + Event @event = this.m_SelectedKey.KeyboardEvent; + GUI.changed = false; + string[] array = this.m_SelectedKey.Name.Split(new char[] + { + '/' + }); + Assert.AreEqual(array.Length, 2, "Unexpected Split: " + this.m_SelectedKey.Name); + GUILayout.Label(array[0], "boldLabel", new GUILayoutOption[0]); + GUILayout.Label(array[1], "boldLabel", new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Key:", new GUILayoutOption[0]); + @event = EditorGUILayout.KeyEventField(@event, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Modifiers:", new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (Application.platform == RuntimePlatform.OSXEditor) + { + @event.command = GUILayout.Toggle(@event.command, "Command", new GUILayoutOption[0]); + } + @event.control = GUILayout.Toggle(@event.control, "Control", new GUILayoutOption[0]); + @event.shift = GUILayout.Toggle(@event.shift, "Shift", new GUILayoutOption[0]); + @event.alt = GUILayout.Toggle(@event.alt, "Alt", new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + if (GUI.changed) + { + this.m_SelectedKey.KeyboardEvent = @event; + Settings.Set(this.m_SelectedKey.Name, this.m_SelectedKey); + } + else + { + if (GUIUtility.keyboardControl == controlID && Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.UpArrow) + { + if (keyCode == KeyCode.DownArrow) + { + if (prefKey2 != null) + { + this.m_SelectedKey = prefKey2; + } + Event.current.Use(); + } + } + else + { + if (prefKey != null) + { + this.m_SelectedKey = prefKey; + } + Event.current.Use(); + } + } + } + } + GUILayout.EndVertical(); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.Space(5f); + if (GUILayout.Button("Use Defaults", new GUILayoutOption[] + { + GUILayout.Width(120f) + })) + { + this.RevertKeys(); + } + } + private void RevertColors() + { + foreach (KeyValuePair current in Settings.Prefs()) + { + current.Value.ResetToDefault(); + EditorPrefs.SetString(current.Value.Name, current.Value.ToUniqueString()); + } + } + private void ShowColors() + { + if (this.s_CachedColors == null) + { + this.s_CachedColors = this.OrderPrefs(Settings.Prefs()); + } + bool flag = false; + PreferencesWindow.s_ColorScrollPos = EditorGUILayout.BeginScrollView(PreferencesWindow.s_ColorScrollPos, new GUILayoutOption[0]); + GUILayout.Space(10f); + PrefColor prefColor = null; + foreach (KeyValuePair>> current in this.s_CachedColors) + { + GUILayout.Label(current.Key, EditorStyles.boldLabel, new GUILayoutOption[0]); + foreach (KeyValuePair current2 in current.Value) + { + EditorGUI.BeginChangeCheck(); + Color color = EditorGUILayout.ColorField(current2.Key, current2.Value.Color, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + prefColor = current2.Value; + prefColor.Color = color; + flag = true; + } + } + if (prefColor != null) + { + Settings.Set(prefColor.Name, prefColor); + } + } + GUILayout.EndScrollView(); + GUILayout.Space(5f); + if (GUILayout.Button("Use Defaults", new GUILayoutOption[] + { + GUILayout.Width(120f) + })) + { + this.RevertColors(); + flag = true; + } + if (flag) + { + EditorApplication.RequestRepaintAllViews(); + } + } + private void WriteRecentAppsList(string[] paths, string path, string prefsKey) + { + int num = 0; + if (path.Length != 0) + { + EditorPrefs.SetString(prefsKey + num, path); + num++; + } + for (int i = 0; i < paths.Length; i++) + { + if (num >= 10) + { + break; + } + if (paths[i].Length != 0) + { + if (!(paths[i] == path)) + { + EditorPrefs.SetString(prefsKey + num, paths[i]); + num++; + } + } + } + } + private void WritePreferences() + { + EditorPrefs.SetString("kScriptsDefaultApp", this.m_ScriptEditorPath); + EditorPrefs.SetString("kScriptEditorArgs", this.m_ScriptEditorArgs); + EditorPrefs.SetString("kImagesDefaultApp", this.m_ImageAppPath); + EditorPrefs.SetString("kDiffsDefaultApp", (this.m_DiffTools.Length != 0) ? this.m_DiffTools[this.m_DiffToolIndex] : string.Empty); + EditorPrefs.SetString("AndroidSdkRoot", this.m_AndroidSdkPath); + this.WriteRecentAppsList(this.m_ScriptApps, this.m_ScriptEditorPath, "RecentlyUsedScriptApp"); + this.WriteRecentAppsList(this.m_ImageApps, this.m_ImageAppPath, "RecentlyUsedImageApp"); + EditorPrefs.SetBool("kAutoRefresh", this.m_AutoRefresh); + EditorPrefs.SetBool("AlwaysShowProjectWizard", this.m_AlwaysShowProjectWizard); + EditorPrefs.SetBool("UseOSColorPicker", this.m_UseOSColorPicker); + EditorPrefs.SetBool("EnableEditorAnalytics", this.m_EnableEditorAnalytics); + EditorPrefs.SetBool("ShowAssetStoreSearchHits", this.m_ShowAssetStoreSearchHits); + EditorPrefs.SetBool("VerifySavingAssets", this.m_VerifySavingAssets); + EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", this.m_AllowAttachedDebuggingOfEditor); + EditorPrefs.SetBool("AllowAlphaNumericHierarchy", this.m_AllowAlphaNumericHierarchy); + foreach (IPreferenceWindowExtension current in this.prefWinExtensions) + { + current.WritePreferences(); + } + } + private static void SetupDefaultPreferences() + { + } + private static string GetProgramFilesFolder() + { + string environmentVariable = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); + if (environmentVariable != null) + { + return environmentVariable; + } + return Environment.GetEnvironmentVariable("ProgramFiles"); + } + private void ReadPreferences() + { + this.m_ScriptEditorPath.str = EditorPrefs.GetString("kScriptsDefaultApp"); + this.m_ScriptEditorArgs = EditorPrefs.GetString("kScriptEditorArgs", "\"$(File)\""); + this.m_ImageAppPath.str = EditorPrefs.GetString("kImagesDefaultApp"); + this.m_AndroidSdkPath = EditorPrefs.GetString("AndroidSdkRoot"); + this.m_ScriptApps = this.BuildAppPathList(this.m_ScriptEditorPath, "RecentlyUsedScriptApp"); + if (Application.platform == RuntimePlatform.WindowsEditor) + { + foreach (string current in SyncVS.InstalledVisualStudios.Values) + { + if (Array.IndexOf(this.m_ScriptApps, current) == -1) + { + if (this.m_ScriptApps.Length < 10) + { + ArrayUtility.Add(ref this.m_ScriptApps, current); + } + else + { + this.m_ScriptApps[1] = current; + } + } + } + } + this.m_ImageApps = this.BuildAppPathList(this.m_ImageAppPath, "RecentlyUsedImageApp"); + this.m_ScriptAppDisplayNames = this.BuildFriendlyAppNameList(this.m_ScriptApps, "MonoDevelop (built-in)"); + this.m_ImageAppDisplayNames = this.BuildFriendlyAppNameList(this.m_ImageApps, "Open by file extension"); + this.m_DiffTools = InternalEditorUtility.GetAvailableDiffTools(); + if ((this.m_DiffTools == null || this.m_DiffTools.Length == 0) && InternalEditorUtility.HasMaint()) + { + this.m_noDiffToolsMessage = InternalEditorUtility.GetNoDiffToolsDetectedMessage(); + } + string @string = EditorPrefs.GetString("kDiffsDefaultApp"); + this.m_DiffToolIndex = ArrayUtility.IndexOf(this.m_DiffTools, @string); + if (this.m_DiffToolIndex == -1) + { + this.m_DiffToolIndex = 0; + } + this.m_AutoRefresh = EditorPrefs.GetBool("kAutoRefresh"); + this.m_AlwaysShowProjectWizard = EditorPrefs.GetBool("AlwaysShowProjectWizard"); + this.m_UseOSColorPicker = EditorPrefs.GetBool("UseOSColorPicker"); + this.m_EnableEditorAnalytics = EditorPrefs.GetBool("EnableEditorAnalytics", true); + this.m_ShowAssetStoreSearchHits = EditorPrefs.GetBool("ShowAssetStoreSearchHits", true); + this.m_VerifySavingAssets = EditorPrefs.GetBool("VerifySavingAssets", false); + this.m_AllowAttachedDebuggingOfEditor = EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true); + this.m_AllowAlphaNumericHierarchy = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); + this.m_CompressAssetsOnImport = Unsupported.GetApplicationSettingCompressAssetsOnImport(); + foreach (IPreferenceWindowExtension current2 in this.prefWinExtensions) + { + current2.ReadPreferences(); + } + } + private void AppsListClick(object userData, string[] options, int selected) + { + PreferencesWindow.AppsListUserData appsListUserData = (PreferencesWindow.AppsListUserData)userData; + if (options[selected] == "Browse...") + { + string text = EditorUtility.OpenFilePanel("Browse for application", string.Empty, (Application.platform != RuntimePlatform.OSXEditor) ? "exe" : "app"); + if (text.Length != 0) + { + appsListUserData.str.str = text; + if (appsListUserData.onChanged != null) + { + appsListUserData.onChanged(); + } + } + } + else + { + appsListUserData.str.str = appsListUserData.paths[selected]; + if (appsListUserData.onChanged != null) + { + appsListUserData.onChanged(); + } + } + this.WritePreferences(); + this.ReadPreferences(); + } + private void FilePopup(string label, string selectedString, ref string[] names, ref string[] paths, PreferencesWindow.RefString outString, Action onChanged) + { + GUIStyle gUIStyle = "MiniPopup"; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(label, gUIStyle); + int[] array = new int[] + { + Array.IndexOf(paths, selectedString) + }; + GUIContent content = new GUIContent(names[array[0]]); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, gUIStyle); + PreferencesWindow.AppsListUserData userData = new PreferencesWindow.AppsListUserData(paths, outString, onChanged); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, gUIStyle)) + { + ArrayUtility.Add(ref names, "Browse..."); + EditorUtility.DisplayCustomMenu(rect, names, array, new EditorUtility.SelectMenuItemFunction(this.AppsListClick), userData); + } + GUILayout.EndHorizontal(); + } + private void AndroidSdkLocation() + { + GUIStyle gUIStyle = "MiniPopup"; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Android SDK Location", gUIStyle); + string text = (!string.IsNullOrEmpty(this.m_AndroidSdkPath)) ? this.m_AndroidSdkPath : "Browse..."; + GUIContent content = new GUIContent(text); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, gUIStyle); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, gUIStyle)) + { + string text2 = AndroidSdkRoot.Browse(this.m_AndroidSdkPath); + if (!string.IsNullOrEmpty(text2)) + { + this.m_AndroidSdkPath = text2; + this.WritePreferences(); + this.ReadPreferences(); + } + } + GUILayout.EndHorizontal(); + } + private string[] BuildAppPathList(string userAppPath, string recentAppsKey) + { + string[] array = new string[] + { + string.Empty + }; + if (userAppPath != null && userAppPath.Length != 0 && Array.IndexOf(array, userAppPath) == -1) + { + ArrayUtility.Add(ref array, userAppPath); + } + for (int i = 0; i < 10; i++) + { + string text = EditorPrefs.GetString(recentAppsKey + i); + if (!File.Exists(text)) + { + text = string.Empty; + EditorPrefs.SetString(recentAppsKey + i, text); + } + if (text.Length != 0 && Array.IndexOf(array, text) == -1) + { + ArrayUtility.Add(ref array, text); + } + } + return array; + } + private string[] BuildFriendlyAppNameList(string[] appPathList, string defaultBuiltIn) + { + List list = new List(); + for (int i = 0; i < appPathList.Length; i++) + { + string text = appPathList[i]; + if (text == string.Empty) + { + list.Add(defaultBuiltIn); + } + else + { + list.Add(OSUtil.GetAppFriendlyName(text)); + } + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/PresetFileLocation.cs b/UnityEditor/UnityEditor/PresetFileLocation.cs new file mode 100644 index 00000000..1db18d9a --- /dev/null +++ b/UnityEditor/UnityEditor/PresetFileLocation.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum PresetFileLocation + { + PreferencesFolder, + ProjectFolder + } +} diff --git a/UnityEditor/UnityEditor/PresetLibrary.cs b/UnityEditor/UnityEditor/PresetLibrary.cs new file mode 100644 index 00000000..bcd6998d --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibrary.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class PresetLibrary : ScriptableObject + { + public abstract int Count(); + public abstract object GetPreset(int index); + public abstract void Add(object presetObject, string presetName); + public abstract void Replace(int index, object newPresetObject); + public abstract void Remove(int index); + public abstract void Move(int index, int destIndex, bool insertAfterDestIndex); + public abstract void Draw(Rect rect, int index); + public abstract void Draw(Rect rect, object presetObject); + public abstract string GetName(int index); + public abstract void SetName(int index, string name); + } +} diff --git a/UnityEditor/UnityEditor/PresetLibraryEditor.cs b/UnityEditor/UnityEditor/PresetLibraryEditor.cs new file mode 100644 index 00000000..51feb64c --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibraryEditor.cs @@ -0,0 +1,1062 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PresetLibraryEditor where T : PresetLibrary + { + private class Styles + { + public GUIStyle innerShadowBg = PresetLibraryEditor.Styles.GetStyle("InnerShadowBg"); + public GUIStyle optionsButton = PresetLibraryEditor.Styles.GetStyle("PaneOptions"); + public GUIStyle newPresetStyle = new GUIStyle(EditorStyles.boldLabel); + public GUIContent plusButtonText = new GUIContent(string.Empty, "Add new preset"); + public GUIContent plusButtonTextNotCheckedOut = new GUIContent(string.Empty, "To add presets you need to press the 'Checkout' button below"); + public GUIContent header = new GUIContent("Presets"); + public GUIContent newPreset = new GUIContent("New"); + public Styles() + { + this.newPresetStyle.alignment = TextAnchor.MiddleCenter; + this.newPresetStyle.normal.textColor = Color.white; + } + private static GUIStyle GetStyle(string styleName) + { + return styleName; + } + } + private class DragState + { + public int dragUponIndex + { + get; + set; + } + public int draggingIndex + { + get; + set; + } + public bool insertAfterIndex + { + get; + set; + } + public Rect dragUponRect + { + get; + set; + } + public DragState() + { + this.dragUponIndex = -1; + this.draggingIndex = -1; + } + public bool IsDragging() + { + return this.draggingIndex != -1; + } + } + internal class PresetContextMenu + { + private static PresetLibraryEditor s_Caller; + private static int s_PresetIndex; + internal static void Show(bool isOpenForEdit, int presetIndex, object newPresetObject, PresetLibraryEditor caller) + { + PresetLibraryEditor.PresetContextMenu.s_Caller = caller; + PresetLibraryEditor.PresetContextMenu.s_PresetIndex = presetIndex; + GUIContent content = new GUIContent("Replace"); + GUIContent content2 = new GUIContent("Delete"); + GUIContent content3 = new GUIContent("Rename"); + GUIContent content4 = new GUIContent("Move To First"); + GenericMenu genericMenu = new GenericMenu(); + if (isOpenForEdit) + { + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction2(new PresetLibraryEditor.PresetContextMenu().Replace), newPresetObject); + genericMenu.AddItem(content2, false, new GenericMenu.MenuFunction2(new PresetLibraryEditor.PresetContextMenu().Delete), 0); + if (caller.drawLabels) + { + genericMenu.AddItem(content3, false, new GenericMenu.MenuFunction2(new PresetLibraryEditor.PresetContextMenu().Rename), 0); + } + genericMenu.AddItem(content4, false, new GenericMenu.MenuFunction2(new PresetLibraryEditor.PresetContextMenu().MoveToTop), 0); + } + else + { + genericMenu.AddDisabledItem(content); + genericMenu.AddDisabledItem(content2); + if (caller.drawLabels) + { + genericMenu.AddDisabledItem(content3); + } + genericMenu.AddDisabledItem(content4); + } + genericMenu.ShowAsContext(); + } + private void Delete(object userData) + { + PresetLibraryEditor.PresetContextMenu.s_Caller.DeletePreset(PresetLibraryEditor.PresetContextMenu.s_PresetIndex); + } + private void Replace(object userData) + { + PresetLibraryEditor.PresetContextMenu.s_Caller.ReplacePreset(PresetLibraryEditor.PresetContextMenu.s_PresetIndex, userData); + } + private void Rename(object userData) + { + T currentLib = PresetLibraryEditor.PresetContextMenu.s_Caller.GetCurrentLib(); + string name = currentLib.GetName(PresetLibraryEditor.PresetContextMenu.s_PresetIndex); + PresetLibraryEditor.PresetContextMenu.s_Caller.BeginRenaming(name, PresetLibraryEditor.PresetContextMenu.s_PresetIndex, 0f); + } + private void MoveToTop(object userData) + { + PresetLibraryEditor.PresetContextMenu.s_Caller.MovePreset(PresetLibraryEditor.PresetContextMenu.s_PresetIndex, 0, false); + } + } + private class SettingsMenu + { + private class ViewModeData + { + public GUIContent text; + public int itemHeight; + public PresetLibraryEditorState.ItemViewMode viewmode; + } + private static PresetLibraryEditor s_Owner; + public static void Show(Rect activatorRect, PresetLibraryEditor owner) + { + PresetLibraryEditor.SettingsMenu.s_Owner = owner; + GenericMenu genericMenu = new GenericMenu(); + int num = (int)PresetLibraryEditor.SettingsMenu.s_Owner.minMaxPreviewHeight.x; + int num2 = (int)PresetLibraryEditor.SettingsMenu.s_Owner.minMaxPreviewHeight.y; + List.SettingsMenu.ViewModeData> list; + if (num == num2) + { + list = new List.SettingsMenu.ViewModeData> + { + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("Grid"), + itemHeight = num + }, + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("List"), + itemHeight = num, + viewmode = PresetLibraryEditorState.ItemViewMode.List + } + }; + } + else + { + list = new List.SettingsMenu.ViewModeData> + { + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("Small Grid"), + itemHeight = num + }, + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("Large Grid"), + itemHeight = num2 + }, + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("Small List"), + itemHeight = num, + viewmode = PresetLibraryEditorState.ItemViewMode.List + }, + new PresetLibraryEditor.SettingsMenu.ViewModeData + { + text = new GUIContent("Large List"), + itemHeight = num2, + viewmode = PresetLibraryEditorState.ItemViewMode.List + } + }; + } + for (int i = 0; i < list.Count; i++) + { + bool on = PresetLibraryEditor.SettingsMenu.s_Owner.itemViewMode == list[i].viewmode && (int)PresetLibraryEditor.SettingsMenu.s_Owner.previewHeight == list[i].itemHeight; + genericMenu.AddItem(list[i].text, on, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.ViewModeChange), list[i]); + } + genericMenu.AddSeparator(string.Empty); + List list2; + List list3; + ScriptableSingleton.instance.GetAvailableLibraries(PresetLibraryEditor.SettingsMenu.s_Owner.m_SaveLoadHelper, out list2, out list3); + list2.Sort(); + list3.Sort(); + string a = PresetLibraryEditor.SettingsMenu.s_Owner.currentLibraryWithoutExtension + "." + PresetLibraryEditor.SettingsMenu.s_Owner.m_SaveLoadHelper.fileExtensionWithoutDot; + string str = " (Project)"; + foreach (string current in list2) + { + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(current); + genericMenu.AddItem(new GUIContent(fileNameWithoutExtension), a == current, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.LibraryModeChange), current); + } + foreach (string current2 in list3) + { + string fileNameWithoutExtension2 = Path.GetFileNameWithoutExtension(current2); + genericMenu.AddItem(new GUIContent(fileNameWithoutExtension2 + str), a == current2, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.LibraryModeChange), current2); + } + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Create New Library..."), false, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.CreateLibrary), 0); + if (PresetLibraryEditor.SettingsMenu.HasDefaultPresets()) + { + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Add Factory Presets To Current Library"), false, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.AddDefaultPresetsToCurrentLibrary), 0); + } + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Reveal Current Library Location"), false, new GenericMenu.MenuFunction2(PresetLibraryEditor.SettingsMenu.RevealCurrentLibrary), 0); + genericMenu.DropDown(activatorRect); + } + private static void ViewModeChange(object userData) + { + PresetLibraryEditor.SettingsMenu.ViewModeData viewModeData = (PresetLibraryEditor.SettingsMenu.ViewModeData)userData; + PresetLibraryEditor.SettingsMenu.s_Owner.itemViewMode = viewModeData.viewmode; + PresetLibraryEditor.SettingsMenu.s_Owner.previewHeight = (float)viewModeData.itemHeight; + } + private static void LibraryModeChange(object userData) + { + string currentLibraryWithoutExtension = (string)userData; + PresetLibraryEditor.SettingsMenu.s_Owner.currentLibraryWithoutExtension = currentLibraryWithoutExtension; + } + private static void CreateLibrary(object userData) + { + PresetLibraryEditor.SettingsMenu.s_Owner.wantsToCreateLibrary = true; + } + private static void RevealCurrentLibrary(object userData) + { + PresetLibraryEditor.SettingsMenu.s_Owner.RevealCurrentLibrary(); + } + private static bool HasDefaultPresets() + { + return PresetLibraryEditor.SettingsMenu.s_Owner.addDefaultPresets != null; + } + private static void AddDefaultPresetsToCurrentLibrary(object userData) + { + if (PresetLibraryEditor.SettingsMenu.s_Owner.addDefaultPresets != null) + { + PresetLibraryEditor.SettingsMenu.s_Owner.addDefaultPresets(PresetLibraryEditor.SettingsMenu.s_Owner.GetCurrentLib()); + } + PresetLibraryEditor.SettingsMenu.s_Owner.SaveCurrentLib(); + } + } + private const float kGridLabelHeight = 16f; + private const float kCheckoutButtonMaxWidth = 100f; + private const float kCheckoutButtonMargin = 2f; + private static PresetLibraryEditor.Styles s_Styles; + private PresetLibraryEditor.DragState m_DragState = new PresetLibraryEditor.DragState(); + private readonly VerticalGrid m_Grid = new VerticalGrid(); + private readonly PresetLibraryEditorState m_State; + private readonly ScriptableObjectSaveLoadHelper m_SaveLoadHelper; + private readonly Action m_ItemClickedCallback; + public Action addDefaultPresets; + public Action presetsWasReordered; + private Vector2 m_MinMaxPreviewHeight = new Vector2(14f, 64f); + private float m_PreviewAspect = 8f; + private bool m_ShowAddNewPresetItem = true; + private bool m_ShowedScrollBarLastFrame; + private bool m_IsOpenForEdit = true; + private PresetFileLocation m_PresetLibraryFileLocation; + public float contentHeight + { + get; + private set; + } + private float topAreaHeight + { + get + { + return 20f; + } + } + private float versionControlAreaHeight + { + get + { + return 20f; + } + } + private float gridWidth + { + get; + set; + } + public bool wantsToCreateLibrary + { + get; + set; + } + public bool showHeader + { + get; + set; + } + public float settingsMenuRightMargin + { + get; + set; + } + public bool alwaysShowScrollAreaHorizontalLines + { + get; + set; + } + public bool useOnePixelOverlappedGrid + { + get; + set; + } + public RectOffset marginsForList + { + get; + set; + } + public RectOffset marginsForGrid + { + get; + set; + } + public string currentLibraryWithoutExtension + { + get + { + return this.m_State.m_CurrrentLibrary; + } + set + { + this.m_State.m_CurrrentLibrary = Path.ChangeExtension(value, null); + this.m_PresetLibraryFileLocation = PresetLibraryLocations.GetFileLocationFromPath(this.m_State.m_CurrrentLibrary); + this.OnLayoutChanged(); + this.Repaint(); + } + } + public float previewAspect + { + get + { + return this.m_PreviewAspect; + } + set + { + this.m_PreviewAspect = value; + } + } + public Vector2 minMaxPreviewHeight + { + get + { + return this.m_MinMaxPreviewHeight; + } + set + { + this.m_MinMaxPreviewHeight = value; + this.previewHeight = this.previewHeight; + } + } + public float previewHeight + { + get + { + return this.m_State.m_PreviewHeight; + } + set + { + this.m_State.m_PreviewHeight = Mathf.Clamp(value, this.minMaxPreviewHeight.x, this.minMaxPreviewHeight.y); + this.Repaint(); + } + } + public PresetLibraryEditorState.ItemViewMode itemViewMode + { + get + { + return this.m_State.itemViewMode; + } + set + { + this.m_State.itemViewMode = value; + this.OnLayoutChanged(); + this.Repaint(); + } + } + private bool drawLabels + { + get + { + return this.m_State.itemViewMode == PresetLibraryEditorState.ItemViewMode.List; + } + } + private string pathWithExtension + { + get + { + return this.currentLibraryWithoutExtension + "." + this.m_SaveLoadHelper.fileExtensionWithoutDot; + } + } + public PresetLibraryEditor(ScriptableObjectSaveLoadHelper helper, PresetLibraryEditorState state, Action itemClickedCallback) + { + this.m_SaveLoadHelper = helper; + this.m_State = state; + this.m_ItemClickedCallback = itemClickedCallback; + this.settingsMenuRightMargin = 10f; + this.useOnePixelOverlappedGrid = false; + this.alwaysShowScrollAreaHorizontalLines = true; + this.marginsForList = new RectOffset(10, 10, 5, 5); + this.marginsForGrid = new RectOffset(5, 5, 5, 5); + this.m_PresetLibraryFileLocation = PresetLibraryLocations.GetFileLocationFromPath(this.currentLibraryWithoutExtension); + } + private void Repaint() + { + HandleUtility.Repaint(); + } + private void InitIfNeeded() + { + } + private void ValidateNoExtension(string value) + { + if (Path.HasExtension(value)) + { + Debug.LogError("currentLibraryWithoutExtension should not have an extension: " + value); + } + } + private string CreateNewLibraryCallback(string libraryName, PresetFileLocation fileLocation) + { + string defaultFilePathForFileLocation = PresetLibraryLocations.GetDefaultFilePathForFileLocation(fileLocation); + string text = Path.Combine(defaultFilePathForFileLocation, libraryName); + if (this.CreateNewLibrary(text) != null) + { + this.currentLibraryWithoutExtension = text; + } + return ScriptableSingleton.instance.GetLastError(); + } + private static bool IsItemVisible(float scrollHeight, float itemYMin, float itemYMax, float scrollPos) + { + float num = itemYMin - scrollPos; + float num2 = itemYMax - scrollPos; + return num2 >= 0f && num <= scrollHeight; + } + private void OnLayoutChanged() + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null || this.gridWidth <= 0f) + { + return; + } + this.SetupGrid(this.gridWidth, currentLib.Count()); + } + private void SetupGrid(float width, int itemCount) + { + if (width < 1f) + { + Debug.LogError(string.Concat(new object[] + { + "Invalid width ", + width, + ", ", + Event.current.type + })); + return; + } + if (this.m_ShowAddNewPresetItem) + { + itemCount++; + } + this.m_Grid.useFixedHorizontalSpacing = this.useOnePixelOverlappedGrid; + this.m_Grid.fixedHorizontalSpacing = (float)((!this.useOnePixelOverlappedGrid) ? 0 : -1); + PresetLibraryEditorState.ItemViewMode itemViewMode = this.m_State.itemViewMode; + if (itemViewMode != PresetLibraryEditorState.ItemViewMode.Grid) + { + if (itemViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + this.m_Grid.fixedWidth = width; + this.m_Grid.topMargin = (float)this.marginsForList.top; + this.m_Grid.bottomMargin = (float)this.marginsForList.bottom; + this.m_Grid.leftMargin = (float)this.marginsForList.left; + this.m_Grid.rightMargin = (float)this.marginsForList.right; + this.m_Grid.verticalSpacing = 2f; + this.m_Grid.minHorizontalSpacing = 0f; + this.m_Grid.itemSize = new Vector2(width - this.m_Grid.leftMargin, this.m_State.m_PreviewHeight); + this.m_Grid.InitNumRowsAndColumns(itemCount, 2147483647); + } + } + else + { + this.m_Grid.fixedWidth = width; + this.m_Grid.topMargin = (float)this.marginsForGrid.top; + this.m_Grid.bottomMargin = (float)this.marginsForGrid.bottom; + this.m_Grid.leftMargin = (float)this.marginsForGrid.left; + this.m_Grid.rightMargin = (float)this.marginsForGrid.right; + this.m_Grid.verticalSpacing = (float)((!this.useOnePixelOverlappedGrid) ? 2 : -1); + this.m_Grid.minHorizontalSpacing = 1f; + this.m_Grid.itemSize = new Vector2(this.m_State.m_PreviewHeight * this.m_PreviewAspect, this.m_State.m_PreviewHeight); + this.m_Grid.InitNumRowsAndColumns(itemCount, 2147483647); + } + float num = this.m_Grid.CalcRect(itemCount - 1, 0f).yMax + this.m_Grid.bottomMargin; + this.contentHeight = this.topAreaHeight + num + ((!this.m_IsOpenForEdit) ? this.versionControlAreaHeight : 0f); + } + public void OnGUI(Rect rect, object presetObject) + { + if (rect.width < 2f) + { + return; + } + this.m_State.m_RenameOverlay.OnEvent(); + T currentLib = this.GetCurrentLib(); + if (PresetLibraryEditor.s_Styles == null) + { + PresetLibraryEditor.s_Styles = new PresetLibraryEditor.Styles(); + } + this.InitIfNeeded(); + Rect rect2 = new Rect(rect.x, rect.y, rect.width, this.topAreaHeight); + Rect rect3 = new Rect(rect.x, rect2.yMax, rect.width, rect.height - this.topAreaHeight); + this.TopArea(rect2); + this.ListArea(rect3, currentLib, presetObject); + } + private void TopArea(Rect rect) + { + GUI.BeginGroup(rect); + if (this.showHeader) + { + GUI.Label(new Rect(10f, 2f, rect.width - 20f, rect.height), PresetLibraryEditor.s_Styles.header); + } + Rect rect2 = new Rect(rect.width - 16f - this.settingsMenuRightMargin, (rect.height - 6f) * 0.5f, 16f, rect.height); + if (Event.current.type == EventType.Repaint) + { + PresetLibraryEditor.s_Styles.optionsButton.Draw(rect2, false, false, false, false); + } + rect2.y = 0f; + rect2.height = rect.height; + rect2.width = 24f; + if (GUI.Button(rect2, GUIContent.none, GUIStyle.none)) + { + PresetLibraryEditor.SettingsMenu.Show(rect2, this); + } + if (this.wantsToCreateLibrary) + { + this.wantsToCreateLibrary = false; + PopupWindow.Show(rect2, new PopupWindowContentForNewLibrary(new Func(this.CreateNewLibraryCallback))); + GUIUtility.ExitGUI(); + } + GUI.EndGroup(); + } + private Rect GetDragRect(Rect itemRect) + { + int num = Mathf.FloorToInt(this.m_Grid.horizontalSpacing * 0.5f + 0.5f); + int num2 = Mathf.FloorToInt(this.m_Grid.verticalSpacing * 0.5f + 0.5f); + return new RectOffset(num, num, num2, num2).Add(itemRect); + } + private void ClearDragState() + { + this.m_DragState.dragUponIndex = -1; + this.m_DragState.draggingIndex = -1; + } + private void DrawHoverEffect(Rect itemRect, bool drawAsSelection) + { + Color color = GUI.color; + GUI.color = new Color(0f, 0f, 0.4f, (!drawAsSelection) ? 0.3f : 0.8f); + Rect position = new RectOffset(3, 3, 3, 3).Add(itemRect); + GUI.Label(position, GUIContent.none, EditorStyles.helpBox); + GUI.color = color; + } + private void VersionControlArea(Rect rect) + { + if (rect.width > 100f) + { + rect = new Rect(rect.xMax - 100f - 2f, rect.y + 2f, 100f, rect.height - 4f); + } + if (GUI.Button(rect, "Checkout", EditorStyles.miniButton)) + { + Provider.Checkout(new string[] + { + this.pathWithExtension + }, CheckoutMode.Both).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + } + private void ListArea(Rect rect, PresetLibrary lib, object newPresetObject) + { + if (lib == null) + { + return; + } + Event current = Event.current; + if (this.m_PresetLibraryFileLocation == PresetFileLocation.ProjectFolder && current.type == EventType.Repaint) + { + this.m_IsOpenForEdit = AssetDatabase.IsOpenForEdit(this.pathWithExtension); + } + else + { + if (this.m_PresetLibraryFileLocation == PresetFileLocation.PreferencesFolder) + { + this.m_IsOpenForEdit = true; + } + } + if (!this.m_IsOpenForEdit) + { + Rect rect2 = new Rect(rect.x, rect.yMax - this.versionControlAreaHeight, rect.width, this.versionControlAreaHeight); + this.VersionControlArea(rect2); + rect.height -= this.versionControlAreaHeight; + } + for (int i = 0; i < 2; i++) + { + this.gridWidth = ((!this.m_ShowedScrollBarLastFrame) ? rect.width : (rect.width - 17f)); + this.SetupGrid(this.gridWidth, lib.Count()); + bool flag = this.m_Grid.height > rect.height; + if (flag == this.m_ShowedScrollBarLastFrame) + { + break; + } + this.m_ShowedScrollBarLastFrame = flag; + } + if ((this.m_ShowedScrollBarLastFrame || this.alwaysShowScrollAreaHorizontalLines) && Event.current.type == EventType.Repaint) + { + Rect rect3 = new RectOffset(1, 1, 1, 1).Add(rect); + rect3.height = 1f; + EditorGUI.DrawRect(rect3, new Color(0f, 0f, 0f, 0.3f)); + rect3.y += rect.height + 1f; + EditorGUI.DrawRect(rect3, new Color(0f, 0f, 0f, 0.3f)); + } + Rect viewRect = new Rect(0f, 0f, 1f, this.m_Grid.height); + this.m_State.m_ScrollPosition = GUI.BeginScrollView(rect, this.m_State.m_ScrollPosition, viewRect); + float num = 0f; + int maxIndex = (!this.m_ShowAddNewPresetItem) ? (lib.Count() - 1) : lib.Count(); + int num2; + int num3; + bool flag2 = this.m_Grid.IsVisibleInScrollView(rect.height, this.m_State.m_ScrollPosition.y, num, maxIndex, out num2, out num3); + bool flag3 = false; + if (flag2) + { + if (this.GetRenameOverlay().IsRenaming() && !this.GetRenameOverlay().isWaitingForDelay) + { + if (!this.m_State.m_RenameOverlay.OnGUI()) + { + this.EndRename(); + current.Use(); + } + this.Repaint(); + } + for (int j = num2; j <= num3; j++) + { + int num4 = j + 1000000; + Rect rect4 = this.m_Grid.CalcRect(j, num); + Rect rect5 = rect4; + Rect rect6 = rect4; + PresetLibraryEditorState.ItemViewMode itemViewMode = this.m_State.itemViewMode; + if (itemViewMode != PresetLibraryEditorState.ItemViewMode.Grid) + { + if (itemViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + rect5.width = this.m_State.m_PreviewHeight * this.m_PreviewAspect; + rect6.x += rect5.width + 8f; + rect6.width -= rect5.width + 10f; + rect6.height = 16f; + rect6.y = rect4.yMin + (rect4.height - 16f) * 0.5f; + } + } + if (this.m_ShowAddNewPresetItem && j == lib.Count()) + { + this.CreateNewPresetButton(rect5, newPresetObject, lib, this.m_IsOpenForEdit); + } + else + { + bool flag4 = this.IsRenaming(j); + if (flag4) + { + Rect editFieldRect = rect6; + editFieldRect.y -= 1f; + editFieldRect.x -= 1f; + this.m_State.m_RenameOverlay.editFieldRect = editFieldRect; + } + switch (current.type) + { + case EventType.MouseDown: + if (current.button == 0 && rect4.Contains(current.mousePosition)) + { + GUIUtility.hotControl = num4; + if (current.clickCount == 1) + { + this.m_ItemClickedCallback(current.clickCount, lib.GetPreset(j)); + current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == num4) + { + GUIUtility.hotControl = 0; + if (current.button == 0 && rect4.Contains(current.mousePosition) && Event.current.alt && this.m_IsOpenForEdit) + { + this.DeletePreset(j); + current.Use(); + } + } + break; + case EventType.MouseMove: + if (rect4.Contains(current.mousePosition)) + { + if (this.m_State.m_HoverIndex != j) + { + this.m_State.m_HoverIndex = j; + this.Repaint(); + } + } + else + { + if (this.m_State.m_HoverIndex == j) + { + this.m_State.m_HoverIndex = -1; + this.Repaint(); + } + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == num4 && this.m_IsOpenForEdit) + { + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), num4); + if (dragAndDropDelay.CanStartDrag()) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.SetGenericData("DraggingPreset", j); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + DragAndDrop.StartDrag(string.Empty); + this.m_DragState.draggingIndex = j; + this.m_DragState.dragUponIndex = j; + GUIUtility.hotControl = 0; + } + current.Use(); + } + break; + case EventType.Repaint: + if (this.m_State.m_HoverIndex == j) + { + if (!rect4.Contains(current.mousePosition)) + { + this.m_State.m_HoverIndex = -1; + } + } + if (this.m_DragState.draggingIndex == j || GUIUtility.hotControl == num4) + { + this.DrawHoverEffect(rect4, false); + } + lib.Draw(rect5, j); + if (!flag4 && this.drawLabels) + { + GUI.Label(rect6, GUIContent.Temp(lib.GetName(j))); + } + if (this.m_DragState.dragUponIndex == j && this.m_DragState.draggingIndex != this.m_DragState.dragUponIndex) + { + flag3 = true; + } + if (GUIUtility.hotControl == 0 && Event.current.alt && this.m_IsOpenForEdit) + { + EditorGUIUtility.AddCursorRect(rect4, MouseCursor.ArrowMinus); + } + break; + case EventType.DragUpdated: + case EventType.DragPerform: + { + Rect dragRect = this.GetDragRect(rect4); + if (dragRect.Contains(current.mousePosition)) + { + this.m_DragState.dragUponIndex = j; + this.m_DragState.dragUponRect = rect4; + if (this.m_State.itemViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + this.m_DragState.insertAfterIndex = ((current.mousePosition.y - dragRect.y) / dragRect.height > 0.5f); + } + else + { + this.m_DragState.insertAfterIndex = ((current.mousePosition.x - dragRect.x) / dragRect.width > 0.5f); + } + bool flag5 = current.type == EventType.DragPerform; + if (flag5) + { + if (this.m_DragState.draggingIndex >= 0) + { + this.MovePreset(this.m_DragState.draggingIndex, this.m_DragState.dragUponIndex, this.m_DragState.insertAfterIndex); + DragAndDrop.AcceptDrag(); + } + this.ClearDragState(); + } + DragAndDrop.visualMode = DragAndDropVisualMode.Move; + current.Use(); + } + break; + } + case EventType.DragExited: + if (this.m_DragState.IsDragging()) + { + this.ClearDragState(); + current.Use(); + } + break; + case EventType.ContextClick: + if (rect4.Contains(current.mousePosition)) + { + PresetLibraryEditor.PresetContextMenu.Show(this.m_IsOpenForEdit, j, newPresetObject, this); + current.Use(); + } + break; + } + } + } + if (flag3) + { + this.DrawDragInsertionMarker(); + } + } + GUI.EndScrollView(); + } + private void DrawDragInsertionMarker() + { + if (!this.m_DragState.IsDragging()) + { + return; + } + Rect dragRect = this.GetDragRect(this.m_DragState.dragUponRect); + Rect rect; + if (this.m_State.itemViewMode == PresetLibraryEditorState.ItemViewMode.List) + { + if (this.m_DragState.insertAfterIndex) + { + rect = new Rect(dragRect.xMin, dragRect.yMax - 1f, dragRect.width, 2f); + } + else + { + rect = new Rect(dragRect.xMin, dragRect.yMin - 1f, dragRect.width, 2f); + } + } + else + { + if (this.m_DragState.insertAfterIndex) + { + rect = new Rect(dragRect.xMax - 1f, dragRect.yMin, 2f, dragRect.height); + } + else + { + rect = new Rect(dragRect.xMin - 1f, dragRect.yMin, 2f, dragRect.height); + } + } + EditorGUI.DrawRect(rect, new Color(0.3f, 0.3f, 1f)); + } + private void CreateNewPresetButton(Rect buttonRect, object newPresetObject, PresetLibrary lib, bool isOpenForEdit) + { + EditorGUI.BeginDisabledGroup(!isOpenForEdit); + if (GUI.Button(buttonRect, (!isOpenForEdit) ? PresetLibraryEditor.s_Styles.plusButtonTextNotCheckedOut : PresetLibraryEditor.s_Styles.plusButtonText)) + { + int itemIndex = this.CreateNewPreset(newPresetObject, string.Empty); + if (this.drawLabels) + { + this.BeginRenaming(string.Empty, itemIndex, 0f); + } + InspectorWindow.RepaintAllInspectors(); + } + if (Event.current.type == EventType.Repaint) + { + Rect rect = new RectOffset(-3, -3, -3, -3).Add(buttonRect); + lib.Draw(rect, newPresetObject); + if (buttonRect.width > 30f) + { + PresetLibraryEditor.LabelWithOutline(buttonRect, PresetLibraryEditor.s_Styles.newPreset, new Color(0.1f, 0.1f, 0.1f), PresetLibraryEditor.s_Styles.newPresetStyle); + } + else + { + if (lib.Count() == 0 && isOpenForEdit) + { + buttonRect.x = buttonRect.xMax + 5f; + buttonRect.width = 200f; + buttonRect.height = 16f; + EditorGUI.BeginDisabledGroup(true); + GUI.Label(buttonRect, "Click to add new preset"); + EditorGUI.EndDisabledGroup(); + } + } + } + EditorGUI.EndDisabledGroup(); + } + private static void LabelWithOutline(Rect rect, GUIContent content, Color outlineColor, GUIStyle style) + { + Color color = GUI.color; + GUI.color = outlineColor; + for (int i = -1; i <= 1; i++) + { + for (int j = -1; j <= 1; j++) + { + if (i != 0 || j != 0) + { + Rect position = rect; + position.x += (float)j; + position.y += (float)i; + GUI.Label(position, content, style); + } + } + } + GUI.color = color; + GUI.Label(rect, content, style); + } + private bool IsRenaming(int itemID) + { + return this.GetRenameOverlay().IsRenaming() && this.GetRenameOverlay().userData == itemID && !this.GetRenameOverlay().isWaitingForDelay; + } + private RenameOverlay GetRenameOverlay() + { + return this.m_State.m_RenameOverlay; + } + private void BeginRenaming(string name, int itemIndex, float delay) + { + this.GetRenameOverlay().BeginRename(name, itemIndex, delay); + } + private void EndRename() + { + if (!this.GetRenameOverlay().userAcceptedRename) + { + return; + } + string name = (!string.IsNullOrEmpty(this.GetRenameOverlay().name)) ? this.GetRenameOverlay().name : this.GetRenameOverlay().originalName; + int userData = this.GetRenameOverlay().userData; + T currentLib = this.GetCurrentLib(); + if (userData >= 0 && userData < currentLib.Count()) + { + currentLib.SetName(userData, name); + this.SaveCurrentLib(); + } + this.GetRenameOverlay().EndRename(true); + } + public T GetCurrentLib() + { + T t = ScriptableSingleton.instance.GetLibrary(this.m_SaveLoadHelper, this.currentLibraryWithoutExtension); + if (t == null) + { + t = ScriptableSingleton.instance.GetLibrary(this.m_SaveLoadHelper, PresetLibraryLocations.defaultPresetLibraryPath); + if (t == null) + { + t = this.CreateNewLibrary(PresetLibraryLocations.defaultPresetLibraryPath); + if (t != null) + { + if (this.addDefaultPresets != null) + { + this.addDefaultPresets(t); + ScriptableSingleton.instance.SaveLibrary(this.m_SaveLoadHelper, t, PresetLibraryLocations.defaultPresetLibraryPath); + } + } + else + { + Debug.LogError("Could not create Default preset library " + ScriptableSingleton.instance.GetLastError()); + } + } + this.currentLibraryWithoutExtension = PresetLibraryLocations.defaultPresetLibraryPath; + } + return t; + } + public void UnloadUsedLibraries() + { + ScriptableSingleton.instance.UnloadAllLibrariesFor(this.m_SaveLoadHelper); + } + public void DeletePreset(int presetIndex) + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null) + { + return; + } + if (presetIndex < 0 || presetIndex >= currentLib.Count()) + { + Debug.LogError("DeletePreset: Invalid index: out of bounds"); + return; + } + currentLib.Remove(presetIndex); + this.SaveCurrentLib(); + if (this.presetsWasReordered != null) + { + this.presetsWasReordered(); + } + this.OnLayoutChanged(); + } + public void ReplacePreset(int presetIndex, object presetObject) + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null) + { + return; + } + if (presetIndex < 0 || presetIndex >= currentLib.Count()) + { + Debug.LogError("ReplacePreset: Invalid index: out of bounds"); + return; + } + currentLib.Replace(presetIndex, presetObject); + this.SaveCurrentLib(); + if (this.presetsWasReordered != null) + { + this.presetsWasReordered(); + } + } + public void MovePreset(int presetIndex, int destPresetIndex, bool insertAfterDestIndex) + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null) + { + return; + } + if (presetIndex < 0 || presetIndex >= currentLib.Count()) + { + Debug.LogError("ReplacePreset: Invalid index: out of bounds"); + return; + } + currentLib.Move(presetIndex, destPresetIndex, insertAfterDestIndex); + this.SaveCurrentLib(); + if (this.presetsWasReordered != null) + { + this.presetsWasReordered(); + } + } + public int CreateNewPreset(object presetObject, string presetName) + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null) + { + Debug.Log("No current library selected!"); + return -1; + } + currentLib.Add(presetObject, presetName); + this.SaveCurrentLib(); + if (this.presetsWasReordered != null) + { + this.presetsWasReordered(); + } + this.Repaint(); + this.OnLayoutChanged(); + return currentLib.Count() - 1; + } + public void SaveCurrentLib() + { + T currentLib = this.GetCurrentLib(); + if (currentLib == null) + { + Debug.Log("No current library selected!"); + return; + } + ScriptableSingleton.instance.SaveLibrary(this.m_SaveLoadHelper, currentLib, this.currentLibraryWithoutExtension); + InternalEditorUtility.RepaintAllViews(); + } + public T CreateNewLibrary(string presetLibraryPathWithoutExtension) + { + T t = ScriptableSingleton.instance.CreateLibrary(this.m_SaveLoadHelper, presetLibraryPathWithoutExtension); + if (t != null) + { + ScriptableSingleton.instance.SaveLibrary(this.m_SaveLoadHelper, t, presetLibraryPathWithoutExtension); + InternalEditorUtility.RepaintAllViews(); + } + return t; + } + public void RevealCurrentLibrary() + { + if (this.m_PresetLibraryFileLocation == PresetFileLocation.PreferencesFolder) + { + EditorUtility.RevealInFinder(Path.GetFullPath(this.pathWithExtension)); + } + else + { + EditorGUIUtility.PingObject(AssetDatabase.GetMainAssetInstanceID(this.pathWithExtension)); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PresetLibraryEditorState.cs b/UnityEditor/UnityEditor/PresetLibraryEditorState.cs new file mode 100644 index 00000000..a6f53527 --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibraryEditorState.cs @@ -0,0 +1,63 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class PresetLibraryEditorState + { + public enum ItemViewMode + { + Grid, + List + } + [SerializeField] + private PresetLibraryEditorState.ItemViewMode m_ItemViewMode; + public float m_PreviewHeight = 32f; + public Vector2 m_ScrollPosition; + public string m_CurrrentLibrary = PresetLibraryLocations.defaultPresetLibraryPath; + public int m_HoverIndex = -1; + public RenameOverlay m_RenameOverlay = new RenameOverlay(); + public string m_Prefix; + public PresetLibraryEditorState.ItemViewMode itemViewMode + { + get + { + return this.m_ItemViewMode; + } + set + { + if (this.m_ItemViewMode != value) + { + this.m_ItemViewMode = value; + InspectorWindow.RepaintAllInspectors(); + EditorPrefs.SetInt(this.m_Prefix + "ViewMode", (int)this.m_ItemViewMode); + } + } + } + public PresetLibraryEditorState(string prefix) + { + this.m_Prefix = prefix; + } + public static PresetLibraryEditorState.ItemViewMode GetItemViewMode(string prefix) + { + return (PresetLibraryEditorState.ItemViewMode)EditorPrefs.GetInt(prefix + "ViewMode", 0); + } + public void TransferEditorPrefsState(bool load) + { + if (load) + { + this.m_ItemViewMode = (PresetLibraryEditorState.ItemViewMode)EditorPrefs.GetInt(this.m_Prefix + "ViewMode", (int)this.m_ItemViewMode); + this.m_PreviewHeight = EditorPrefs.GetFloat(this.m_Prefix + "ItemHeight", this.m_PreviewHeight); + this.m_ScrollPosition.y = EditorPrefs.GetFloat(this.m_Prefix + "Scroll", this.m_ScrollPosition.y); + this.m_CurrrentLibrary = EditorPrefs.GetString(this.m_Prefix + "CurrentLib", this.m_CurrrentLibrary); + } + else + { + EditorPrefs.SetInt(this.m_Prefix + "ViewMode", (int)this.m_ItemViewMode); + EditorPrefs.SetFloat(this.m_Prefix + "ItemHeight", this.m_PreviewHeight); + EditorPrefs.SetFloat(this.m_Prefix + "Scroll", this.m_ScrollPosition.y); + EditorPrefs.SetString(this.m_Prefix + "CurrentLib", this.m_CurrrentLibrary); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PresetLibraryHelpers.cs b/UnityEditor/UnityEditor/PresetLibraryHelpers.cs new file mode 100644 index 00000000..b1878f5f --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibraryHelpers.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal static class PresetLibraryHelpers + { + public static void MoveListItem(List list, int index, int destIndex, bool insertAfterDestIndex) + { + if (index < 0 || destIndex < 0) + { + Debug.LogError("Invalid preset move"); + return; + } + if (index == destIndex) + { + return; + } + if (destIndex > index) + { + destIndex--; + } + if (insertAfterDestIndex && destIndex < list.Count - 1) + { + destIndex++; + } + T item = list[index]; + list.RemoveAt(index); + list.Insert(destIndex, item); + } + } +} diff --git a/UnityEditor/UnityEditor/PresetLibraryLocations.cs b/UnityEditor/UnityEditor/PresetLibraryLocations.cs new file mode 100644 index 00000000..0cb6b487 --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibraryLocations.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal static class PresetLibraryLocations + { + public static string defaultLibraryLocation + { + get + { + return PresetLibraryLocations.GetDefaultFilePathForFileLocation(PresetFileLocation.PreferencesFolder); + } + } + public static string defaultPresetLibraryPath + { + get + { + return Path.Combine(PresetLibraryLocations.defaultLibraryLocation, PresetLibraryLocations.defaultLibraryName); + } + } + public static string defaultLibraryName + { + get + { + return "Default"; + } + } + public static List GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation fileLocation, string fileExtensionWithoutDot) + { + List directoryPaths = PresetLibraryLocations.GetDirectoryPaths(fileLocation); + List filesWithExentionFromFolders = PresetLibraryLocations.GetFilesWithExentionFromFolders(directoryPaths, fileExtensionWithoutDot); + for (int i = 0; i < filesWithExentionFromFolders.Count; i++) + { + filesWithExentionFromFolders[i] = PresetLibraryLocations.ConvertToUnitySeperators(filesWithExentionFromFolders[i]); + } + return filesWithExentionFromFolders; + } + public static string GetDefaultFilePathForFileLocation(PresetFileLocation fileLocation) + { + if (fileLocation == PresetFileLocation.PreferencesFolder) + { + return InternalEditorUtility.unityPreferencesFolder + "/Presets/"; + } + if (fileLocation != PresetFileLocation.ProjectFolder) + { + Debug.LogError("Enum not handled!"); + return string.Empty; + } + return "Assets/Editor/"; + } + private static List GetDirectoryPaths(PresetFileLocation fileLocation) + { + List list = new List(); + if (fileLocation != PresetFileLocation.PreferencesFolder) + { + if (fileLocation != PresetFileLocation.ProjectFolder) + { + Debug.LogError("Enum not handled!"); + } + else + { + string[] directories = Directory.GetDirectories("Assets/", "Editor", SearchOption.AllDirectories); + list.AddRange(directories); + } + } + else + { + list.Add(PresetLibraryLocations.GetDefaultFilePathForFileLocation(PresetFileLocation.PreferencesFolder)); + } + return list; + } + private static List GetFilesWithExentionFromFolders(List folderPaths, string fileExtensionWithoutDot) + { + List list = new List(); + foreach (string current in folderPaths) + { + string[] files = Directory.GetFiles(current, "*." + fileExtensionWithoutDot); + list.AddRange(files); + } + return list; + } + public static PresetFileLocation GetFileLocationFromPath(string path) + { + if (path.Contains(InternalEditorUtility.unityPreferencesFolder)) + { + return PresetFileLocation.PreferencesFolder; + } + if (path.Contains("Assets/")) + { + return PresetFileLocation.ProjectFolder; + } + Debug.LogError("Could not determine preset file location type " + path); + return PresetFileLocation.ProjectFolder; + } + private static string ConvertToUnitySeperators(string path) + { + return path.Replace('\\', '/'); + } + public static string GetParticleCurveLibraryExtension(bool singleCurve, bool signedRange) + { + string text = "particle"; + if (singleCurve) + { + text += "Curves"; + } + else + { + text += "DoubleCurves"; + } + if (signedRange) + { + text += "Signed"; + } + else + { + text += string.Empty; + } + return text; + } + public static string GetCurveLibraryExtension(bool normalized) + { + if (normalized) + { + return "curvesNormalized"; + } + return "curves"; + } + } +} diff --git a/UnityEditor/UnityEditor/PresetLibraryManager.cs b/UnityEditor/UnityEditor/PresetLibraryManager.cs new file mode 100644 index 00000000..cbbde80a --- /dev/null +++ b/UnityEditor/UnityEditor/PresetLibraryManager.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PresetLibraryManager : ScriptableSingleton + { + private class LibraryCache + { + private string m_Identifier; + private List m_LoadedLibraries = new List(); + private List m_LoadedLibraryIDs = new List(); + public string identifier + { + get + { + return this.m_Identifier; + } + } + public List loadedLibraries + { + get + { + return this.m_LoadedLibraries; + } + } + public List loadedLibraryIDs + { + get + { + return this.m_LoadedLibraryIDs; + } + } + public LibraryCache(string identifier) + { + this.m_Identifier = identifier; + } + public void UnloadScriptableObjects() + { + foreach (ScriptableObject current in this.m_LoadedLibraries) + { + UnityEngine.Object.DestroyImmediate(current); + } + this.m_LoadedLibraries.Clear(); + this.m_LoadedLibraryIDs.Clear(); + } + } + private static string s_LastError; + private List m_LibraryCaches = new List(); + private HideFlags libraryHideFlag + { + get + { + return HideFlags.DontSave; + } + } + public void GetAvailableLibraries(ScriptableObjectSaveLoadHelper helper, out List preferencesLibs, out List projectLibs) where T : ScriptableObject + { + preferencesLibs = PresetLibraryLocations.GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation.PreferencesFolder, helper.fileExtensionWithoutDot); + projectLibs = PresetLibraryLocations.GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation.ProjectFolder, helper.fileExtensionWithoutDot); + } + private string GetLibaryNameFromPath(string filePath) + { + return Path.GetFileNameWithoutExtension(filePath); + } + public T CreateLibrary(ScriptableObjectSaveLoadHelper helper, string presetLibraryPathWithoutExtension) where T : ScriptableObject + { + string libaryNameFromPath = this.GetLibaryNameFromPath(presetLibraryPathWithoutExtension); + if (!InternalEditorUtility.IsValidFileName(libaryNameFromPath)) + { + string displayStringOfInvalidCharsOfFileName = InternalEditorUtility.GetDisplayStringOfInvalidCharsOfFileName(libaryNameFromPath); + if (displayStringOfInvalidCharsOfFileName.Length > 0) + { + PresetLibraryManager.s_LastError = string.Format("A library filename cannot contain the following character{0}: {1}", (displayStringOfInvalidCharsOfFileName.Length <= 1) ? string.Empty : "s", displayStringOfInvalidCharsOfFileName); + } + else + { + PresetLibraryManager.s_LastError = "Invalid filename"; + } + return (T)((object)null); + } + if (this.GetLibrary(helper, presetLibraryPathWithoutExtension) != null) + { + PresetLibraryManager.s_LastError = "Library '" + libaryNameFromPath + "' already exists! Ensure a unique name."; + return (T)((object)null); + } + T t = helper.Create(); + t.hideFlags = this.libraryHideFlag; + PresetLibraryManager.LibraryCache presetLibraryCache = this.GetPresetLibraryCache(helper.fileExtensionWithoutDot); + presetLibraryCache.loadedLibraries.Add(t); + presetLibraryCache.loadedLibraryIDs.Add(presetLibraryPathWithoutExtension); + PresetLibraryManager.s_LastError = null; + return t; + } + public T GetLibrary(ScriptableObjectSaveLoadHelper helper, string presetLibraryPathWithoutExtension) where T : ScriptableObject + { + PresetLibraryManager.LibraryCache presetLibraryCache = this.GetPresetLibraryCache(helper.fileExtensionWithoutDot); + int i = 0; + while (i < presetLibraryCache.loadedLibraryIDs.Count) + { + if (presetLibraryCache.loadedLibraryIDs[i] == presetLibraryPathWithoutExtension) + { + if (presetLibraryCache.loadedLibraries[i] != null) + { + return presetLibraryCache.loadedLibraries[i] as T; + } + presetLibraryCache.loadedLibraries.RemoveAt(i); + presetLibraryCache.loadedLibraryIDs.RemoveAt(i); + Debug.LogError("Invalid library detected: Reload " + presetLibraryCache.loadedLibraryIDs[i] + " from HDD"); + break; + } + else + { + i++; + } + } + T t = helper.Load(presetLibraryPathWithoutExtension); + if (t != null) + { + t.hideFlags = this.libraryHideFlag; + presetLibraryCache.loadedLibraries.Add(t); + presetLibraryCache.loadedLibraryIDs.Add(presetLibraryPathWithoutExtension); + return t; + } + return (T)((object)null); + } + public void UnloadAllLibrariesFor(ScriptableObjectSaveLoadHelper helper) where T : ScriptableObject + { + for (int i = 0; i < this.m_LibraryCaches.Count; i++) + { + if (this.m_LibraryCaches[i].identifier == helper.fileExtensionWithoutDot) + { + this.m_LibraryCaches[i].UnloadScriptableObjects(); + this.m_LibraryCaches.RemoveAt(i); + break; + } + } + } + public void SaveLibrary(ScriptableObjectSaveLoadHelper helper, T library, string presetLibraryPathWithoutExtension) where T : ScriptableObject + { + bool flag = File.Exists(presetLibraryPathWithoutExtension + "." + helper.fileExtensionWithoutDot); + helper.Save(library, presetLibraryPathWithoutExtension); + if (!flag) + { + AssetDatabase.Refresh(); + } + } + public string GetLastError() + { + string result = PresetLibraryManager.s_LastError; + PresetLibraryManager.s_LastError = null; + return result; + } + private PresetLibraryManager.LibraryCache GetPresetLibraryCache(string identifier) + { + foreach (PresetLibraryManager.LibraryCache current in this.m_LibraryCaches) + { + if (current.identifier == identifier) + { + return current; + } + } + PresetLibraryManager.LibraryCache libraryCache = new PresetLibraryManager.LibraryCache(identifier); + this.m_LibraryCaches.Add(libraryCache); + return libraryCache; + } + } +} diff --git a/UnityEditor/UnityEditor/PreviewBlendTree.cs b/UnityEditor/UnityEditor/PreviewBlendTree.cs new file mode 100644 index 00000000..31c95cfa --- /dev/null +++ b/UnityEditor/UnityEditor/PreviewBlendTree.cs @@ -0,0 +1,199 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class PreviewBlendTree + { + private AnimatorController m_Controller; + private AvatarPreview m_AvatarPreview; + private StateMachine m_StateMachine; + private State m_State; + private BlendTree m_BlendTree; + private bool m_ControllerIsDirty; + private bool m_PrevIKOnFeet; + public Animator PreviewAnimator + { + get + { + return this.m_AvatarPreview.Animator; + } + } + protected virtual void ControllerDirty() + { + this.m_ControllerIsDirty = true; + } + public void Init(BlendTree blendTree, Animator animator) + { + this.m_BlendTree = blendTree; + if (this.m_AvatarPreview == null) + { + this.m_AvatarPreview = new AvatarPreview(animator, this.m_BlendTree); + this.m_AvatarPreview.OnAvatarChangeFunc = new AvatarPreview.OnAvatarChange(this.OnPreviewAvatarChanged); + this.m_PrevIKOnFeet = this.m_AvatarPreview.IKOnFeet; + } + this.CreateStateMachine(); + } + public void CreateParameters() + { + int parameterCount = this.m_Controller.parameterCount; + for (int i = 0; i < parameterCount; i++) + { + this.m_Controller.RemoveParameter(0); + } + for (int j = 0; j < this.m_BlendTree.recursiveBlendParameterCount; j++) + { + this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(j), AnimatorControllerParameterType.Float); + } + } + private void CreateStateMachine() + { + if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) + { + if (this.m_Controller == null) + { + this.m_Controller = new AnimatorController(); + this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.AddLayer("preview"); + this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + this.CreateParameters(); + this.m_State = this.m_StateMachine.AddState("preview"); + this.m_State.SetMotionInternal(this.m_BlendTree); + this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; + this.m_State.hideFlags = HideFlags.DontSave; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + AnimatorController expr_D7 = this.m_Controller; + expr_D7.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_D7.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + this.m_ControllerIsDirty = false; + } + if (AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) + { + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + } + } + } + private void ClearStateMachine() + { + if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) + { + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); + } + if (this.m_Controller != null) + { + AnimatorController expr_49 = this.m_Controller; + expr_49.OnAnimatorControllerDirty = (Action)Delegate.Remove(expr_49.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + } + UnityEngine.Object.DestroyImmediate(this.m_Controller); + UnityEngine.Object.DestroyImmediate(this.m_State); + this.m_StateMachine = null; + this.m_Controller = null; + this.m_State = null; + } + private void OnPreviewAvatarChanged() + { + this.ResetStateMachine(); + } + public void ResetStateMachine() + { + this.ClearStateMachine(); + this.CreateStateMachine(); + } + public void OnDisable() + { + this.ClearStateMachine(); + this.m_AvatarPreview.OnDestroy(); + } + public void OnDestroy() + { + this.ClearStateMachine(); + if (this.m_AvatarPreview != null) + { + this.m_AvatarPreview.OnDestroy(); + this.m_AvatarPreview = null; + } + } + private void UpdateAvatarState() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Animator animator = this.m_AvatarPreview.Animator; + if (animator) + { + if (this.m_ControllerIsDirty) + { + this.ResetStateMachine(); + } + if (this.m_PrevIKOnFeet != this.m_AvatarPreview.IKOnFeet) + { + this.m_PrevIKOnFeet = this.m_AvatarPreview.IKOnFeet; + Vector3 rootPosition = this.m_AvatarPreview.Animator.rootPosition; + Quaternion rootRotation = this.m_AvatarPreview.Animator.rootRotation; + this.ResetStateMachine(); + this.m_AvatarPreview.Animator.Update(this.m_AvatarPreview.timeControl.currentTime); + this.m_AvatarPreview.Animator.Update(0f); + this.m_AvatarPreview.Animator.rootPosition = rootPosition; + this.m_AvatarPreview.Animator.rootRotation = rootRotation; + } + if (animator) + { + for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) + { + string recursiveBlendParameter = this.m_BlendTree.GetRecursiveBlendParameter(i); + float inputBlendValue = this.m_BlendTree.GetInputBlendValue(recursiveBlendParameter); + animator.SetFloat(recursiveBlendParameter, inputBlendValue); + } + } + this.m_AvatarPreview.timeControl.loop = true; + float num = 1f; + float num2 = 0f; + if (animator.layerCount > 0) + { + AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); + num = currentAnimatorStateInfo.length; + num2 = currentAnimatorStateInfo.normalizedTime; + } + this.m_AvatarPreview.timeControl.startTime = 0f; + this.m_AvatarPreview.timeControl.stopTime = num; + this.m_AvatarPreview.timeControl.Update(); + float num3 = this.m_AvatarPreview.timeControl.deltaTime; + if (!this.m_BlendTree.isLooping) + { + if (num2 >= 1f) + { + num3 -= num; + } + else + { + if (num2 < 0f) + { + num3 += num; + } + } + } + animator.Update(num3); + } + } + public void TestForReset() + { + if (this.m_State != null && this.m_AvatarPreview != null && this.m_State.iKOnFeet != this.m_AvatarPreview.IKOnFeet) + { + this.ResetStateMachine(); + } + } + public bool HasPreviewGUI() + { + return true; + } + public void OnPreviewSettings() + { + this.m_AvatarPreview.DoPreviewSettings(); + } + public void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.UpdateAvatarState(); + this.m_AvatarPreview.DoAvatarPreview(r, background); + } + } +} diff --git a/UnityEditor/UnityEditor/PreviewHelpers.cs b/UnityEditor/UnityEditor/PreviewHelpers.cs new file mode 100644 index 00000000..f243d479 --- /dev/null +++ b/UnityEditor/UnityEditor/PreviewHelpers.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PreviewHelpers + { + internal static void AdjustWidthAndHeightForStaticPreview(int textureWidth, int textureHeight, ref int width, ref int height) + { + int max = width; + int max2 = height; + if (textureWidth <= width && textureHeight <= height) + { + width = textureWidth; + height = textureHeight; + } + else + { + float b = (float)height / (float)textureWidth; + float a = (float)width / (float)textureHeight; + float num = Mathf.Min(a, b); + width = Mathf.RoundToInt((float)textureWidth * num); + height = Mathf.RoundToInt((float)textureHeight * num); + } + width = Mathf.Clamp(width, 2, max); + height = Mathf.Clamp(height, 2, max2); + } + } +} diff --git a/UnityEditor/UnityEditor/PreviewRenderUtility.cs b/UnityEditor/UnityEditor/PreviewRenderUtility.cs new file mode 100644 index 00000000..fbf77577 --- /dev/null +++ b/UnityEditor/UnityEditor/PreviewRenderUtility.cs @@ -0,0 +1,185 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class PreviewRenderUtility + { + public Camera m_Camera; + public float m_CameraFieldOfView = 15f; + public Light[] m_Light = new Light[2]; + internal RenderTexture m_RenderTexture; + internal RenderTexture m_RenderTextureGammaCorrect; + private Rect m_TargetRect; + private SavedRenderTargetState m_SavedState; + public PreviewRenderUtility() : this(false) + { + } + public PreviewRenderUtility(bool renderFullScene) + { + GameObject gameObject = EditorUtility.CreateGameObjectWithHideFlags("PreRenderCamera", HideFlags.HideAndDontSave, new Type[] + { + typeof(Camera) + }); + this.m_Camera = gameObject.camera; + this.m_Camera.fieldOfView = this.m_CameraFieldOfView; + this.m_Camera.enabled = false; + this.m_Camera.clearFlags = CameraClearFlags.Depth; + this.m_Camera.farClipPlane = 10f; + this.m_Camera.nearClipPlane = 2f; + this.m_Camera.backgroundColor = new Color(0.192156866f, 0.192156866f, 0.192156866f, 1f); + this.m_Camera.renderingPath = RenderingPath.Forward; + this.m_Camera.useOcclusionCulling = false; + if (!renderFullScene) + { + Handles.SetCameraOnlyDrawMesh(this.m_Camera); + } + for (int i = 0; i < 2; i++) + { + GameObject gameObject2 = EditorUtility.CreateGameObjectWithHideFlags("PreRenderLight", HideFlags.HideAndDontSave, new Type[] + { + typeof(Light) + }); + this.m_Light[i] = gameObject2.light; + this.m_Light[i].type = LightType.Directional; + this.m_Light[i].intensity = 0.5f; + this.m_Light[i].enabled = false; + } + this.m_Light[0].color = SceneView.kSceneViewFrontLight; + this.m_Light[1].transform.rotation = Quaternion.Euler(340f, 218f, 177f); + this.m_Light[1].color = new Color(0.4f, 0.4f, 0.45f, 0f) * 0.7f; + } + public void Cleanup() + { + if (this.m_Camera) + { + UnityEngine.Object.DestroyImmediate(this.m_Camera.gameObject, true); + } + if (this.m_RenderTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_RenderTexture); + this.m_RenderTexture = null; + } + if (this.m_RenderTextureGammaCorrect) + { + UnityEngine.Object.DestroyImmediate(this.m_RenderTextureGammaCorrect); + this.m_RenderTextureGammaCorrect = null; + } + Light[] light = this.m_Light; + for (int i = 0; i < light.Length; i++) + { + Light light2 = light[i]; + if (light2) + { + UnityEngine.Object.DestroyImmediate(light2.gameObject, true); + } + } + } + private void InitPreview(Rect r) + { + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + this.m_TargetRect = r; + int num = (int)r.width; + int num2 = (int)r.height; + if (!this.m_RenderTexture || this.m_RenderTexture.width != num || this.m_RenderTexture.height != num2 || !this.m_RenderTextureGammaCorrect || this.m_RenderTextureGammaCorrect.width != num || this.m_RenderTextureGammaCorrect.height != num2) + { + if (this.m_RenderTexture) + { + UnityEngine.Object.DestroyImmediate(this.m_RenderTexture); + this.m_RenderTexture = null; + } + if (this.m_RenderTextureGammaCorrect) + { + UnityEngine.Object.DestroyImmediate(this.m_RenderTextureGammaCorrect); + this.m_RenderTextureGammaCorrect = null; + } + float a = (float)(Mathf.Max(Mathf.Min(num * 2, 1024), num) / num); + float b = (float)(Mathf.Max(Mathf.Min(num2 * 2, 1024), num2) / num2); + float num3 = Mathf.Min(a, b); + bool flag = QualitySettings.activeColorSpace == ColorSpace.Linear; + this.m_RenderTexture = new RenderTexture((int)((float)num * num3), (int)((float)num2 * num3), 16, RenderTextureFormat.ARGB32, (!flag) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB); + this.m_RenderTexture.hideFlags = HideFlags.HideAndDontSave; + this.m_RenderTextureGammaCorrect = new RenderTexture((int)((float)num * num3), (int)((float)num2 * num3), 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + this.m_RenderTextureGammaCorrect.hideFlags = HideFlags.HideAndDontSave; + this.m_Camera.targetTexture = this.m_RenderTexture; + } + float num4 = (this.m_RenderTexture.width > 0) ? Mathf.Max(1f, (float)this.m_RenderTexture.height / (float)this.m_RenderTexture.width) : 1f; + this.m_Camera.fieldOfView = Mathf.Atan(num4 * Mathf.Tan(this.m_CameraFieldOfView * 0.5f * 0.0174532924f)) * 57.29578f * 2f; + this.m_SavedState = new SavedRenderTargetState(); + EditorGUIUtility.SetRenderTextureNoViewport(this.m_RenderTexture); + GL.LoadOrtho(); + GL.LoadPixelMatrix(0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height, 0f); + ShaderUtil.rawViewportRect = new Rect(0f, 0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height); + ShaderUtil.rawScissorRect = new Rect(0f, 0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height); + GL.Clear(true, true, new Color(0f, 0f, 0f, 0f)); + } + public void BeginStaticPreview(Rect r) + { + this.InitPreview(r); + Color color = new Color(0.321568638f, 0.321568638f, 0.321568638f, 1f); + Texture2D texture2D = new Texture2D(1, 1, TextureFormat.ARGB32, true, true); + texture2D.SetPixel(0, 0, color); + texture2D.Apply(); + Graphics.DrawTexture(new Rect(0f, 0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height), texture2D); + UnityEngine.Object.DestroyImmediate(texture2D); + } + public void BeginPreview(Rect r, GUIStyle previewBackground) + { + this.InitPreview(r); + if (previewBackground == null || previewBackground == GUIStyle.none) + { + return; + } + Graphics.DrawTexture(previewBackground.overflow.Add(new Rect(0f, 0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height)), previewBackground.normal.background, new Rect(0f, 0f, 1f, 1f), previewBackground.border.left, previewBackground.border.right, previewBackground.border.top, previewBackground.border.bottom, new Color(0.5f, 0.5f, 0.5f, 1f), null); + } + private void GammaBlit() + { + if (QualitySettings.activeColorSpace == ColorSpace.Linear) + { + Material material = EditorGUI.gammaCorrectMaterialNoClip; + if (Unsupported.IsDeveloperBuild()) + { + material = new Material(material); + } + Graphics.Blit(this.m_RenderTexture, this.m_RenderTextureGammaCorrect, material); + if (material != null && Unsupported.IsDeveloperBuild()) + { + UnityEngine.Object.DestroyImmediate(material); + } + } + } + public Texture EndPreview() + { + this.GammaBlit(); + this.m_SavedState.Restore(); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + return (QualitySettings.activeColorSpace != ColorSpace.Linear) ? this.m_RenderTexture : this.m_RenderTextureGammaCorrect; + } + public Texture2D EndStaticPreview() + { + this.GammaBlit(); + RenderTexture source = (QualitySettings.activeColorSpace != ColorSpace.Linear) ? this.m_RenderTexture : this.m_RenderTextureGammaCorrect; + RenderTexture temporary = RenderTexture.GetTemporary((int)this.m_TargetRect.width, (int)this.m_TargetRect.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + Graphics.Blit(source, temporary); + RenderTexture.active = temporary; + Texture2D texture2D = new Texture2D((int)this.m_TargetRect.width, (int)this.m_TargetRect.height, TextureFormat.RGB24, false, true); + texture2D.ReadPixels(new Rect(0f, 0f, this.m_TargetRect.width, this.m_TargetRect.height), 0, 0); + texture2D.Apply(); + RenderTexture.ReleaseTemporary(temporary); + this.m_SavedState.Restore(); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + return texture2D; + } + public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex) + { + Graphics.DrawMesh(mesh, pos, rot, mat, 1, this.m_Camera, subMeshIndex); + } + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material mat, int subMeshIndex) + { + Graphics.DrawMesh(mesh, matrix, mat, 1, this.m_Camera, subMeshIndex); + } + public void DrawSprite(Sprite frame, Matrix4x4 matrix, Material mat, Color color) + { + Graphics.DrawSprite(frame, matrix, mat, 1, this.m_Camera, color, null); + } + } +} diff --git a/UnityEditor/UnityEditor/PreviewResizer.cs b/UnityEditor/UnityEditor/PreviewResizer.cs new file mode 100644 index 00000000..5e891848 --- /dev/null +++ b/UnityEditor/UnityEditor/PreviewResizer.cs @@ -0,0 +1,174 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class PreviewResizer + { + private static float s_DraggedPreviewSize; + private static float s_CachedPreviewSizeWhileDragging; + private static float s_MouseDownLocation; + private static float s_MouseDownValue; + private static bool s_MouseDragged; + [SerializeField] + private float m_CachedPref; + [SerializeField] + private int m_ControlHash; + [SerializeField] + private string m_PrefName; + private int m_Id; + private int id + { + get + { + if (this.m_Id == 0) + { + this.m_Id = GUIUtility.GetControlID(this.m_ControlHash, FocusType.Passive, default(Rect)); + } + return this.m_Id; + } + } + public void Init(string prefName) + { + if (this.m_ControlHash != 0 && !string.IsNullOrEmpty(this.m_PrefName)) + { + return; + } + this.m_ControlHash = prefName.GetHashCode(); + this.m_PrefName = "Preview_" + prefName; + this.m_CachedPref = EditorPrefs.GetFloat(this.m_PrefName, 1f); + } + public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight) + { + return this.ResizeHandle(windowPosition, minSize, minRemainingSize, resizerHeight, default(Rect)); + } + public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight, Rect dragRect) + { + if (Mathf.Abs(this.m_CachedPref) < minSize) + { + this.m_CachedPref = minSize * Mathf.Sign(this.m_CachedPref); + } + float num = windowPosition.height - minRemainingSize; + bool flag = GUIUtility.hotControl == this.id; + float num2 = (!flag) ? Mathf.Max(0f, this.m_CachedPref) : PreviewResizer.s_DraggedPreviewSize; + bool flag2 = this.m_CachedPref > 0f; + float num3 = Mathf.Abs(this.m_CachedPref); + Rect position = new Rect(0f, windowPosition.height - num2 - resizerHeight, windowPosition.width, resizerHeight); + if (dragRect.width != 0f) + { + position.x = dragRect.x; + position.width = dragRect.width; + } + bool flag3 = flag2; + num2 = -PreviewResizer.PixelPreciseCollapsibleSlider(this.id, position, -num2, -num, 0f, ref flag2); + num2 = Mathf.Min(num2, num); + flag = (GUIUtility.hotControl == this.id); + if (flag) + { + PreviewResizer.s_DraggedPreviewSize = num2; + } + if (num2 < minSize) + { + num2 = ((num2 >= minSize * 0.5f) ? minSize : 0f); + } + if (flag2 != flag3) + { + num2 = ((!flag2) ? 0f : num3); + } + flag2 = (num2 >= minSize / 2f); + if (GUIUtility.hotControl == 0) + { + if (num2 > 0f) + { + num3 = num2; + } + float num4 = num3 * (float)((!flag2) ? -1 : 1); + if (num4 != this.m_CachedPref) + { + this.m_CachedPref = num4; + EditorPrefs.SetFloat(this.m_PrefName, this.m_CachedPref); + } + } + PreviewResizer.s_CachedPreviewSizeWhileDragging = num2; + return num2; + } + public bool GetExpanded() + { + if (GUIUtility.hotControl == this.id) + { + return PreviewResizer.s_CachedPreviewSizeWhileDragging > 0f; + } + return this.m_CachedPref > 0f; + } + public float GetPreviewSize() + { + if (GUIUtility.hotControl == this.id) + { + return Mathf.Max(0f, PreviewResizer.s_CachedPreviewSizeWhileDragging); + } + return Mathf.Max(0f, this.m_CachedPref); + } + public bool GetExpandedBeforeDragging() + { + return this.m_CachedPref > 0f; + } + public void SetExpanded(bool expanded) + { + this.m_CachedPref = Mathf.Abs(this.m_CachedPref) * (float)((!expanded) ? -1 : 1); + EditorPrefs.SetFloat(this.m_PrefName, this.m_CachedPref); + } + public void ToggleExpanded() + { + this.m_CachedPref = -this.m_CachedPref; + EditorPrefs.SetFloat(this.m_PrefName, this.m_CachedPref); + } + public static float PixelPreciseCollapsibleSlider(int id, Rect position, float value, float min, float max, ref bool expanded) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (GUIUtility.hotControl == 0 && current.button == 0 && position.Contains(current.mousePosition)) + { + GUIUtility.hotControl = id; + PreviewResizer.s_MouseDownLocation = current.mousePosition.y; + PreviewResizer.s_MouseDownValue = value; + PreviewResizer.s_MouseDragged = false; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + GUIUtility.hotControl = 0; + if (!PreviewResizer.s_MouseDragged) + { + expanded = !expanded; + } + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + value = Mathf.Clamp(current.mousePosition.y - PreviewResizer.s_MouseDownLocation + PreviewResizer.s_MouseDownValue, min, max - 1f); + GUI.changed = true; + PreviewResizer.s_MouseDragged = true; + current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == 0) + { + EditorGUIUtility.AddCursorRect(position, MouseCursor.SplitResizeUpDown); + } + if (GUIUtility.hotControl == id) + { + EditorGUIUtility.AddCursorRect(new Rect(position.x, position.y - 100f, position.width, position.height + 200f), MouseCursor.SplitResizeUpDown); + } + break; + } + return value; + } + } +} diff --git a/UnityEditor/UnityEditor/PreviewWindow.cs b/UnityEditor/UnityEditor/PreviewWindow.cs new file mode 100644 index 00000000..9db57ba3 --- /dev/null +++ b/UnityEditor/UnityEditor/PreviewWindow.cs @@ -0,0 +1,86 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PreviewWindow : InspectorWindow + { + [SerializeField] + private InspectorWindow m_ParentInspectorWindow; + public void SetParentInspector(InspectorWindow inspector) + { + this.m_ParentInspectorWindow = inspector; + } + protected override void OnEnable() + { + base.OnEnable(); + base.title = "Preview"; + base.minSize = new Vector2(260f, 220f); + } + protected override void OnDisable() + { + base.OnDisable(); + this.m_ParentInspectorWindow.Repaint(); + } + protected override void CreateTracker() + { + this.m_Tracker = this.m_ParentInspectorWindow.GetTracker(); + } + public override Editor GetLastInteractedEditor() + { + return this.m_ParentInspectorWindow.GetLastInteractedEditor(); + } + protected override void OnGUI() + { + if (!this.m_ParentInspectorWindow) + { + base.Close(); + GUIUtility.ExitGUI(); + } + Editor.m_AllowMultiObjectAccess = true; + this.CreateTracker(); + this.CreatePreviewables(); + IPreviewable[] editorsWithPreviews = base.GetEditorsWithPreviews(this.m_Tracker.activeEditors); + IPreviewable editorThatControlsPreview = base.GetEditorThatControlsPreview(editorsWithPreviews); + bool flag = editorThatControlsPreview != null && editorThatControlsPreview.HasPreviewGUI(); + Rect rect = EditorGUILayout.BeginHorizontal(GUIContent.none, InspectorWindow.styles.preToolbar, new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + GUILayout.FlexibleSpace(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + string text = string.Empty; + if (editorThatControlsPreview != null) + { + text = editorThatControlsPreview.GetPreviewTitle().text; + } + GUI.Label(lastRect, text, InspectorWindow.styles.preToolbar2); + if (flag) + { + editorThatControlsPreview.OnPreviewSettings(); + } + EditorGUILayout.EndHorizontal(); + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && rect.Contains(current.mousePosition)) + { + base.Close(); + current.Use(); + return; + } + Rect rect2 = GUILayoutUtility.GetRect(0f, 10240f, 64f, 10240f); + if (Event.current.type == EventType.Repaint) + { + InspectorWindow.styles.preBackground.Draw(rect2, false, false, false, false); + } + if (editorThatControlsPreview != null && editorThatControlsPreview.HasPreviewGUI()) + { + editorThatControlsPreview.DrawPreview(rect2); + } + } + public override void AddItemsToMenu(GenericMenu menu) + { + } + protected override void ShowButton(Rect r) + { + } + } +} diff --git a/UnityEditor/UnityEditor/ProceduralMaterialInformation.cs b/UnityEditor/UnityEditor/ProceduralMaterialInformation.cs new file mode 100644 index 00000000..b3754920 --- /dev/null +++ b/UnityEditor/UnityEditor/ProceduralMaterialInformation.cs @@ -0,0 +1,68 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct ProceduralMaterialInformation + { + private Vector2 m_TextureOffsets; + private Vector2 m_TextureScales; + private int m_GenerateAllOutputs; + private int m_AnimationUpdateRate; + private bool m_GenerateMipMaps; + public Vector2 offset + { + get + { + return this.m_TextureOffsets; + } + set + { + this.m_TextureOffsets = value; + } + } + public Vector2 scale + { + get + { + return this.m_TextureScales; + } + set + { + this.m_TextureScales = value; + } + } + public bool generateAllOutputs + { + get + { + return this.m_GenerateAllOutputs != 0; + } + set + { + this.m_GenerateAllOutputs = ((!value) ? 0 : 1); + } + } + public int animationUpdateRate + { + get + { + return this.m_AnimationUpdateRate; + } + set + { + this.m_AnimationUpdateRate = value; + } + } + public bool generateMipMaps + { + get + { + return this.m_GenerateMipMaps; + } + set + { + this.m_GenerateMipMaps = value; + } + } + } +} diff --git a/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs b/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs new file mode 100644 index 00000000..fefc996e --- /dev/null +++ b/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs @@ -0,0 +1,1262 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(ProceduralMaterial))] + internal class ProceduralMaterialInspector : MaterialEditor + { + private class Styles + { + public GUIContent hslContent = new GUIContent("HSL Adjustment", "Hue_Shift, Saturation, Luminosity"); + public GUIContent randomSeedContent = new GUIContent("Random Seed", "$randomseed : the overall random aspect of the texture."); + public GUIContent randomizeButtonContent = new GUIContent("Randomize"); + public GUIContent generateAllOutputsContent = new GUIContent("Generate all outputs", "Force the generation of all Substance outputs."); + public GUIContent animatedContent = new GUIContent("Animation update rate", "Set the animation update rate in millisecond"); + public GUIContent defaultPlatform = EditorGUIUtility.TextContent("TextureImporter.Platforms.Default"); + public GUIContent targetWidth = new GUIContent("Target Width"); + public GUIContent targetHeight = new GUIContent("Target Height"); + public GUIContent textureFormat = EditorGUIUtility.TextContent("TextureImporter.TextureFormat"); + public GUIContent loadBehavior = new GUIContent("Load Behavior"); + public GUIContent mipmapContent = new GUIContent("Generate Mip Maps"); + } + [Serializable] + protected class ProceduralPlatformSetting + { + private UnityEngine.Object[] targets; + public string name; + public bool m_Overridden; + public int maxTextureWidth; + public int maxTextureHeight; + public int m_TextureFormat; + public int m_LoadBehavior; + public BuildTarget target; + public Texture2D icon; + public bool isDefault + { + get + { + return this.name == string.Empty; + } + } + public int textureFormat + { + get + { + return this.m_TextureFormat; + } + set + { + this.m_TextureFormat = value; + } + } + public bool overridden + { + get + { + return this.m_Overridden; + } + } + public ProceduralPlatformSetting(UnityEngine.Object[] objects, string _name, BuildTarget _target, Texture2D _icon) + { + this.targets = objects; + this.m_Overridden = false; + this.target = _target; + this.name = _name; + this.icon = _icon; + this.m_Overridden = false; + if (this.name != string.Empty) + { + UnityEngine.Object[] array = this.targets; + for (int i = 0; i < array.Length; i++) + { + ProceduralMaterial proceduralMaterial = (ProceduralMaterial)array[i]; + string assetPath = AssetDatabase.GetAssetPath(proceduralMaterial); + SubstanceImporter substanceImporter = AssetImporter.GetAtPath(assetPath) as SubstanceImporter; + if (substanceImporter != null && substanceImporter.GetPlatformTextureSettings(proceduralMaterial.name, this.name, out this.maxTextureWidth, out this.maxTextureHeight, out this.m_TextureFormat, out this.m_LoadBehavior)) + { + this.m_Overridden = true; + break; + } + } + } + if (!this.m_Overridden && this.targets.Length > 0) + { + string assetPath2 = AssetDatabase.GetAssetPath(this.targets[0]); + SubstanceImporter substanceImporter2 = AssetImporter.GetAtPath(assetPath2) as SubstanceImporter; + if (substanceImporter2 != null) + { + substanceImporter2.GetPlatformTextureSettings((this.targets[0] as ProceduralMaterial).name, string.Empty, out this.maxTextureWidth, out this.maxTextureHeight, out this.m_TextureFormat, out this.m_LoadBehavior); + } + } + } + public void SetOverride(ProceduralMaterialInspector.ProceduralPlatformSetting master) + { + this.m_Overridden = true; + } + public void ClearOverride(ProceduralMaterialInspector.ProceduralPlatformSetting master) + { + this.m_TextureFormat = master.textureFormat; + this.maxTextureWidth = master.maxTextureWidth; + this.maxTextureHeight = master.maxTextureHeight; + this.m_LoadBehavior = master.m_LoadBehavior; + this.m_Overridden = false; + } + public bool HasChanged() + { + ProceduralMaterialInspector.ProceduralPlatformSetting proceduralPlatformSetting = new ProceduralMaterialInspector.ProceduralPlatformSetting(this.targets, this.name, this.target, null); + return proceduralPlatformSetting.m_Overridden != this.m_Overridden || proceduralPlatformSetting.maxTextureWidth != this.maxTextureWidth || proceduralPlatformSetting.maxTextureHeight != this.maxTextureHeight || proceduralPlatformSetting.textureFormat != this.textureFormat || proceduralPlatformSetting.m_LoadBehavior != this.m_LoadBehavior; + } + public void Apply() + { + UnityEngine.Object[] array = this.targets; + for (int i = 0; i < array.Length; i++) + { + ProceduralMaterial proceduralMaterial = (ProceduralMaterial)array[i]; + string assetPath = AssetDatabase.GetAssetPath(proceduralMaterial); + SubstanceImporter substanceImporter = AssetImporter.GetAtPath(assetPath) as SubstanceImporter; + if (this.name != string.Empty) + { + if (this.m_Overridden) + { + substanceImporter.SetPlatformTextureSettings(proceduralMaterial.name, this.name, this.maxTextureWidth, this.maxTextureHeight, this.m_TextureFormat, this.m_LoadBehavior); + } + else + { + substanceImporter.ClearPlatformTextureSettings(proceduralMaterial.name, this.name); + } + } + else + { + substanceImporter.SetPlatformTextureSettings(proceduralMaterial.name, this.name, this.maxTextureWidth, this.maxTextureHeight, this.m_TextureFormat, this.m_LoadBehavior); + } + } + } + } + private static ProceduralMaterial m_Material = null; + private static Shader m_ShaderPMaterial = null; + private static SubstanceImporter m_Importer = null; + private static string[] kMaxTextureSizeStrings = new string[] + { + "32", + "64", + "128", + "256", + "512", + "1024", + "2048" + }; + private static int[] kMaxTextureSizeValues = new int[] + { + 32, + 64, + 128, + 256, + 512, + 1024, + 2048 + }; + private bool m_ShowTexturesSection; + private bool m_ShowHSLInputs = true; + private string m_LastGroup; + private ProceduralMaterialInspector.Styles m_Styles; + private static string[] kMaxLoadBehaviorStrings = new string[] + { + "Do nothing", + "Do nothing and cache", + "Build on level load", + "Build on level load and cache", + "Bake and keep Substance", + "Bake and discard Substance" + }; + private static int[] kMaxLoadBehaviorValues = new int[] + { + 0, + 5, + 1, + 4, + 2, + 3 + }; + private static string[] kTextureFormatStrings = new string[] + { + "Compressed", + "Compressed - No Alpha", + "RAW", + "RAW - No Alpha" + }; + private static int[] kTextureFormatValues = new int[] + { + 0, + 2, + 1, + 3 + }; + private bool m_MightHaveModified; + private static bool m_UndoWasPerformed = false; + private static Dictionary m_GeneratingSince = new Dictionary(); + private bool m_ReimportOnDisable = true; + private Vector2 m_ScrollPos = default(Vector2); + protected List m_PlatformSettings; + public void DisableReimportOnDisable() + { + this.m_ReimportOnDisable = false; + } + public void ReimportSubstances() + { + string[] array = new string[base.targets.GetLength(0)]; + int num = 0; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ProceduralMaterial assetObject = (ProceduralMaterial)targets[i]; + array[num++] = AssetDatabase.GetAssetPath(assetObject); + } + for (int j = 0; j < num; j++) + { + SubstanceImporter substanceImporter = AssetImporter.GetAtPath(array[j]) as SubstanceImporter; + if (substanceImporter && EditorUtility.IsDirty(substanceImporter.GetInstanceID())) + { + AssetDatabase.ImportAsset(array[j], ImportAssetOptions.ForceUncompressedImport); + } + } + } + public override void Awake() + { + base.Awake(); + this.m_ShowTexturesSection = EditorPrefs.GetBool("ProceduralShowTextures", false); + this.m_ReimportOnDisable = true; + ProceduralMaterialInspector.m_UndoWasPerformed = false; + } + public override void OnEnable() + { + base.OnEnable(); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public void ReimportSubstancesIfNeeded() + { + if (this.m_MightHaveModified && !ProceduralMaterialInspector.m_UndoWasPerformed && !EditorApplication.isPlaying && !InternalEditorUtility.ignoreInspectorChanges) + { + this.ReimportSubstances(); + } + } + public override void OnDisable() + { + if (this.m_ReimportOnDisable) + { + this.ReimportSubstancesIfNeeded(); + } + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + base.OnDisable(); + } + public override void UndoRedoPerformed() + { + ProceduralMaterialInspector.m_UndoWasPerformed = true; + base.UndoRedoPerformed(); + if (ProceduralMaterialInspector.m_Material != null) + { + ProceduralMaterialInspector.m_Material.RebuildTextures(); + } + base.Repaint(); + } + internal void DisplayRestrictedInspector() + { + this.m_MightHaveModified = false; + if (this.m_Styles == null) + { + this.m_Styles = new ProceduralMaterialInspector.Styles(); + } + ProceduralMaterial proceduralMaterial = this.target as ProceduralMaterial; + if (ProceduralMaterialInspector.m_Material != proceduralMaterial) + { + ProceduralMaterialInspector.m_Material = proceduralMaterial; + ProceduralMaterialInspector.m_ShaderPMaterial = proceduralMaterial.shader; + } + this.ProceduralProperties(); + GUILayout.Space(15f); + this.GeneratedTextures(); + } + internal override void OnAssetStoreInspectorGUI() + { + this.DisplayRestrictedInspector(); + } + internal override bool IsEnabled() + { + return base.IsOpenForEdit(); + } + internal override void OnHeaderTitleGUI(Rect titleRect, string header) + { + ProceduralMaterial proceduralMaterial = this.target as ProceduralMaterial; + string assetPath = AssetDatabase.GetAssetPath(this.target); + ProceduralMaterialInspector.m_Importer = (AssetImporter.GetAtPath(assetPath) as SubstanceImporter); + if (ProceduralMaterialInspector.m_Importer == null) + { + return; + } + string text = proceduralMaterial.name; + text = EditorGUI.DelayedTextField(titleRect, text, null, EditorStyles.textField); + if (text != proceduralMaterial.name) + { + if (ProceduralMaterialInspector.m_Importer.RenameMaterial(proceduralMaterial, text)) + { + AssetDatabase.ImportAsset(ProceduralMaterialInspector.m_Importer.assetPath, ImportAssetOptions.ForceUncompressedImport); + GUIUtility.ExitGUI(); + } + else + { + text = proceduralMaterial.name; + } + } + } + public override void OnInspectorGUI() + { + EditorGUI.BeginDisabledGroup(AnimationMode.InAnimationMode()); + this.m_MightHaveModified = true; + if (this.m_Styles == null) + { + this.m_Styles = new ProceduralMaterialInspector.Styles(); + } + ProceduralMaterial proceduralMaterial = this.target as ProceduralMaterial; + string assetPath = AssetDatabase.GetAssetPath(this.target); + ProceduralMaterialInspector.m_Importer = (AssetImporter.GetAtPath(assetPath) as SubstanceImporter); + if (ProceduralMaterialInspector.m_Importer == null) + { + this.DisplayRestrictedInspector(); + return; + } + if (ProceduralMaterialInspector.m_Material != proceduralMaterial) + { + ProceduralMaterialInspector.m_Material = proceduralMaterial; + ProceduralMaterialInspector.m_ShaderPMaterial = proceduralMaterial.shader; + } + if (!base.isVisible || proceduralMaterial.shader == null) + { + return; + } + if (ProceduralMaterialInspector.m_ShaderPMaterial != proceduralMaterial.shader) + { + ProceduralMaterialInspector.m_ShaderPMaterial = proceduralMaterial.shader; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ProceduralMaterial proceduralMaterial2 = (ProceduralMaterial)targets[i]; + string assetPath2 = AssetDatabase.GetAssetPath(proceduralMaterial2); + SubstanceImporter substanceImporter = AssetImporter.GetAtPath(assetPath2) as SubstanceImporter; + substanceImporter.OnShaderModified(proceduralMaterial2); + } + } + if (base.PropertiesGUI()) + { + ProceduralMaterialInspector.m_ShaderPMaterial = proceduralMaterial.shader; + UnityEngine.Object[] targets2 = base.targets; + for (int j = 0; j < targets2.Length; j++) + { + ProceduralMaterial proceduralMaterial3 = (ProceduralMaterial)targets2[j]; + string assetPath3 = AssetDatabase.GetAssetPath(proceduralMaterial3); + SubstanceImporter substanceImporter2 = AssetImporter.GetAtPath(assetPath3) as SubstanceImporter; + substanceImporter2.OnShaderModified(proceduralMaterial3); + } + base.PropertiesChanged(); + } + GUILayout.Space(5f); + this.ProceduralProperties(); + GUILayout.Space(15f); + this.GeneratedTextures(); + EditorGUI.EndDisabledGroup(); + } + private void ProceduralProperties() + { + GUILayout.Label("Procedural Properties", EditorStyles.boldLabel, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ProceduralMaterial proceduralMaterial = (ProceduralMaterial)targets[i]; + if (proceduralMaterial.isProcessing) + { + base.Repaint(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + break; + } + } + if (base.targets.Length > 1) + { + GUILayout.Label("Procedural properties do not support multi-editing.", EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + return; + } + EditorGUIUtility.labelWidth = 0f; + EditorGUIUtility.fieldWidth = 0f; + if (ProceduralMaterialInspector.m_Importer != null) + { + if (!ProceduralMaterial.isSupported) + { + GUILayout.Label("Procedural Materials are not supported on " + EditorUserBuildSettings.activeBuildTarget + ". Textures will be baked.", EditorStyles.helpBox, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + } + bool changed = GUI.changed; + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + EditorGUI.BeginChangeCheck(); + bool generated = EditorGUILayout.Toggle(this.m_Styles.generateAllOutputsContent, ProceduralMaterialInspector.m_Importer.GetGenerateAllOutputs(ProceduralMaterialInspector.m_Material), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + ProceduralMaterialInspector.m_Importer.SetGenerateAllOutputs(ProceduralMaterialInspector.m_Material, generated); + } + EditorGUI.BeginChangeCheck(); + bool mode = EditorGUILayout.Toggle(this.m_Styles.mipmapContent, ProceduralMaterialInspector.m_Importer.GetGenerateMipMaps(ProceduralMaterialInspector.m_Material), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + ProceduralMaterialInspector.m_Importer.SetGenerateMipMaps(ProceduralMaterialInspector.m_Material, mode); + } + EditorGUI.EndDisabledGroup(); + if (ProceduralMaterialInspector.m_Material.HasProceduralProperty("$time")) + { + EditorGUI.BeginChangeCheck(); + int animation_update_rate = EditorGUILayout.IntField(this.m_Styles.animatedContent, ProceduralMaterialInspector.m_Importer.GetAnimationUpdateRate(ProceduralMaterialInspector.m_Material), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + ProceduralMaterialInspector.m_Importer.SetAnimationUpdateRate(ProceduralMaterialInspector.m_Material, animation_update_rate); + } + } + GUI.changed = changed; + } + this.InputOptions(ProceduralMaterialInspector.m_Material); + } + private void GeneratedTextures() + { + if (base.targets.Length > 1) + { + return; + } + string text = "Generated Textures"; + if (ProceduralMaterialInspector.ShowIsGenerating(this.target as ProceduralMaterial)) + { + text += " (Generating...)"; + } + EditorGUI.BeginChangeCheck(); + this.m_ShowTexturesSection = EditorGUILayout.Foldout(this.m_ShowTexturesSection, text); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("ProceduralShowTextures", this.m_ShowTexturesSection); + } + if (this.m_ShowTexturesSection) + { + this.ShowProceduralTexturesGUI(ProceduralMaterialInspector.m_Material); + this.ShowGeneratedTexturesGUI(ProceduralMaterialInspector.m_Material); + if (ProceduralMaterialInspector.m_Importer != null) + { + if (this.HasProceduralTextureProperties(ProceduralMaterialInspector.m_Material)) + { + this.OffsetScaleGUI(ProceduralMaterialInspector.m_Material); + } + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + this.ShowTextureSizeGUI(); + EditorGUI.EndDisabledGroup(); + } + } + } + public static bool ShowIsGenerating(ProceduralMaterial mat) + { + if (!ProceduralMaterialInspector.m_GeneratingSince.ContainsKey(mat)) + { + ProceduralMaterialInspector.m_GeneratingSince[mat] = 0f; + } + if (mat.isProcessing) + { + return Time.realtimeSinceStartup > ProceduralMaterialInspector.m_GeneratingSince[mat] + 0.4f; + } + ProceduralMaterialInspector.m_GeneratingSince[mat] = Time.realtimeSinceStartup; + return false; + } + public override string GetInfoString() + { + ProceduralMaterial proceduralMaterial = this.target as ProceduralMaterial; + if (proceduralMaterial.mainTexture == null) + { + return string.Empty; + } + return proceduralMaterial.mainTexture.width + "x" + proceduralMaterial.mainTexture.height; + } + public bool HasProceduralTextureProperties(Material material) + { + Shader shader = material.shader; + int propertyCount = ShaderUtil.GetPropertyCount(shader); + for (int i = 0; i < propertyCount; i++) + { + if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) + { + string propertyName = ShaderUtil.GetPropertyName(shader, i); + Texture texture = material.GetTexture(propertyName); + if (SubstanceImporter.IsProceduralTextureSlot(material, texture, propertyName)) + { + return true; + } + } + } + return false; + } + protected void RecordForUndo(ProceduralMaterial material, SubstanceImporter importer, string message) + { + if (importer) + { + Undo.RecordObjects(new UnityEngine.Object[] + { + material, + importer + }, message); + } + else + { + Undo.RecordObject(material, message); + } + } + protected void OffsetScaleGUI(ProceduralMaterial material) + { + if (ProceduralMaterialInspector.m_Importer == null || base.targets.Length > 1) + { + return; + } + GUILayoutOption gUILayoutOption = GUILayout.Width(10f); + GUILayoutOption gUILayoutOption2 = GUILayout.MinWidth(32f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + Vector2 materialScale = ProceduralMaterialInspector.m_Importer.GetMaterialScale(material); + Vector2 lhs = materialScale; + Vector2 materialOffset = ProceduralMaterialInspector.m_Importer.GetMaterialOffset(material); + Vector2 lhs2 = materialOffset; + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + GUILayout.Space(8f); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(string.Empty, EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.Label("x", EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.Label("y", EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Tiling", EditorStyles.miniLabel, new GUILayoutOption[0]); + materialScale.x = EditorGUILayout.FloatField(materialScale.x, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + materialScale.y = EditorGUILayout.FloatField(materialScale.y, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Offset", EditorStyles.miniLabel, new GUILayoutOption[0]); + materialOffset.x = EditorGUILayout.FloatField(materialOffset.x, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + materialOffset.y = EditorGUILayout.FloatField(materialOffset.y, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + if (lhs != materialScale || lhs2 != materialOffset) + { + this.RecordForUndo(material, ProceduralMaterialInspector.m_Importer, "Modify " + material.name + "'s Tiling/Offset"); + ProceduralMaterialInspector.m_Importer.SetMaterialOffset(material, materialOffset); + ProceduralMaterialInspector.m_Importer.SetMaterialScale(material, materialScale); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + protected void InputOptions(ProceduralMaterial material) + { + EditorGUI.BeginChangeCheck(); + this.InputsGUI(); + if (EditorGUI.EndChangeCheck()) + { + material.RebuildTextures(); + } + } + [MenuItem("CONTEXT/ProceduralMaterial/Reset", false, -100)] + public static void ResetSubstance(MenuCommand command) + { + string assetPath = AssetDatabase.GetAssetPath(command.context); + ProceduralMaterialInspector.m_Importer = (AssetImporter.GetAtPath(assetPath) as SubstanceImporter); + ProceduralMaterialInspector.m_Importer.ResetMaterial(command.context as ProceduralMaterial); + } + [MenuItem("CONTEXT/ProceduralMaterial/Export Bitmaps", false)] + public static void ExportBitmaps(MenuCommand command) + { + string assetPath = AssetDatabase.GetAssetPath(command.context); + ProceduralMaterialInspector.m_Importer = (AssetImporter.GetAtPath(assetPath) as SubstanceImporter); + ProceduralMaterialInspector.m_Importer.ExportBitmaps(command.context as ProceduralMaterial); + } + protected void ShowProceduralTexturesGUI(ProceduralMaterial material) + { + if (base.targets.Length > 1) + { + return; + } + EditorGUILayout.Space(); + Shader shader = material.shader; + if (shader == null) + { + return; + } + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(4f); + GUILayout.FlexibleSpace(); + float pixels = 10f; + bool flag = true; + for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++) + { + if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) + { + string propertyName = ShaderUtil.GetPropertyName(shader, i); + Texture texture = material.GetTexture(propertyName); + if (SubstanceImporter.IsProceduralTextureSlot(material, texture, propertyName)) + { + string propertyDescription = ShaderUtil.GetPropertyDescription(shader, i); + Type objType; + switch (ShaderUtil.GetTexDim(shader, i)) + { + case ShaderUtil.ShaderPropertyTexDim.TexDim2D: + objType = typeof(Texture); + break; + case ShaderUtil.ShaderPropertyTexDim.TexDim3D: + objType = typeof(Texture3D); + break; + case ShaderUtil.ShaderPropertyTexDim.TexDimCUBE: + objType = typeof(Cubemap); + break; + case ShaderUtil.ShaderPropertyTexDim.TexDimAny: + objType = typeof(Texture); + break; + default: + objType = null; + break; + } + GUIStyle gUIStyle = "ObjectPickerResultsGridLabel"; + if (flag) + { + flag = false; + } + else + { + GUILayout.Space(pixels); + } + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Height(72f + gUIStyle.fixedHeight + gUIStyle.fixedHeight + 8f) + }); + Rect rect = GUILayoutUtility.GetRect(72f, 72f); + ProceduralMaterialInspector.DoObjectPingField(rect, rect, GUIUtility.GetControlID(12354, EditorGUIUtility.native, rect), texture, objType); + this.ShowAlphaSourceGUI(material, texture as ProceduralTexture, ref rect); + rect.height = gUIStyle.fixedHeight; + GUI.Label(rect, propertyDescription, gUIStyle); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + } + } + } + GUILayout.Space(4f); + EditorGUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + } + protected void ShowGeneratedTexturesGUI(ProceduralMaterial material) + { + if (base.targets.Length > 1) + { + return; + } + if (ProceduralMaterialInspector.m_Importer != null && !ProceduralMaterialInspector.m_Importer.GetGenerateAllOutputs(ProceduralMaterialInspector.m_Material)) + { + return; + } + GUIStyle gUIStyle = "ObjectPickerResultsGridLabel"; + EditorGUILayout.Space(); + GUILayout.FlexibleSpace(); + this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, new GUILayoutOption[] + { + GUILayout.Height(64f + gUIStyle.fixedHeight + gUIStyle.fixedHeight + 16f) + }); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + float pixels = 10f; + Texture[] generatedTextures = material.GetGeneratedTextures(); + for (int i = 0; i < generatedTextures.Length; i++) + { + ProceduralTexture proceduralTexture = generatedTextures[i] as ProceduralTexture; + if (proceduralTexture != null) + { + GUILayout.Space(pixels); + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Height(64f + gUIStyle.fixedHeight + 8f) + }); + Rect rect = GUILayoutUtility.GetRect(64f, 64f); + ProceduralMaterialInspector.DoObjectPingField(rect, rect, GUIUtility.GetControlID(12354, EditorGUIUtility.native, rect), proceduralTexture, typeof(Texture)); + this.ShowAlphaSourceGUI(material, proceduralTexture, ref rect); + GUILayout.EndVertical(); + GUILayout.Space(pixels); + GUILayout.FlexibleSpace(); + } + } + EditorGUILayout.EndHorizontal(); + EditorGUILayout.EndScrollView(); + } + private void ShowAlphaSourceGUI(ProceduralMaterial material, ProceduralTexture tex, ref Rect rect) + { + GUIStyle gUIStyle = "ObjectPickerResultsGridLabel"; + float num = 10f; + rect.y = rect.yMax + 2f; + if (ProceduralMaterialInspector.m_Importer != null) + { + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + if (tex.GetProceduralOutputType() != ProceduralOutputType.Normal && tex.hasAlpha) + { + rect.height = gUIStyle.fixedHeight; + string[] displayedOptions = new string[] + { + "Source (A)", + "Diffuse (A)", + "Normal (A)", + "Height (A)", + "Emissive (A)", + "Specular (A)", + "Opacity (A)" + }; + EditorGUILayout.Space(); + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + int alphaSource = EditorGUI.Popup(rect, (int)ProceduralMaterialInspector.m_Importer.GetTextureAlphaSource(material, tex.name), displayedOptions); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(material, ProceduralMaterialInspector.m_Importer, "Modify " + material.name + "'s Alpha Modifier"); + ProceduralMaterialInspector.m_Importer.SetTextureAlphaSource(material, tex.name, (ProceduralOutputType)alphaSource); + } + rect.y = rect.yMax + 2f; + } + EditorGUI.EndDisabledGroup(); + } + rect.width += num; + } + private UnityEngine.Object TextureValidator(UnityEngine.Object[] references, Type objType, SerializedProperty property) + { + for (int i = 0; i < references.Length; i++) + { + UnityEngine.Object @object = references[i]; + Texture texture = @object as Texture; + if (texture) + { + return texture; + } + } + return null; + } + internal static void DoObjectPingField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType) + { + Event current = Event.current; + EventType eventType = current.type; + if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + { + eventType = Event.current.rawType; + } + bool flag = EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f; + EventType eventType2 = eventType; + if (eventType2 != EventType.MouseDown) + { + if (eventType2 == EventType.Repaint) + { + GUIContent gUIContent = EditorGUIUtility.ObjectContent(obj, objType); + if (flag) + { + GUIStyle objectFieldThumb = EditorStyles.objectFieldThumb; + objectFieldThumb.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); + if (obj != null) + { + EditorGUI.DrawPreviewTexture(objectFieldThumb.padding.Remove(position), gUIContent.image); + } + else + { + GUIStyle gUIStyle = objectFieldThumb.name + "Overlay"; + gUIStyle.Draw(position, gUIContent, id); + } + } + else + { + GUIStyle objectField = EditorStyles.objectField; + objectField.Draw(position, gUIContent, id, DragAndDrop.activeControlID == id); + } + } + } + else + { + if (Event.current.button == 0) + { + if (position.Contains(Event.current.mousePosition)) + { + UnityEngine.Object @object = obj; + Component component = @object as Component; + if (component) + { + @object = component.gameObject; + } + if (Event.current.clickCount == 1) + { + GUIUtility.keyboardControl = id; + if (@object) + { + EditorGUIUtility.PingObject(@object); + } + current.Use(); + } + else + { + if (Event.current.clickCount == 2) + { + if (@object) + { + AssetDatabase.OpenAsset(@object); + GUIUtility.ExitGUI(); + } + current.Use(); + } + } + } + } + } + } + internal void ResetValues() + { + this.BuildTargetList(); + if (this.HasModified()) + { + Debug.LogError("Impossible"); + } + } + internal void Apply() + { + foreach (ProceduralMaterialInspector.ProceduralPlatformSetting current in this.m_PlatformSettings) + { + current.Apply(); + } + } + internal bool HasModified() + { + foreach (ProceduralMaterialInspector.ProceduralPlatformSetting current in this.m_PlatformSettings) + { + if (current.HasChanged()) + { + return true; + } + } + return false; + } + public void BuildTargetList() + { + List validPlatforms = BuildPlayerWindow.GetValidPlatforms(); + this.m_PlatformSettings = new List(); + this.m_PlatformSettings.Add(new ProceduralMaterialInspector.ProceduralPlatformSetting(base.targets, string.Empty, BuildTarget.StandaloneWindows, null)); + foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) + { + this.m_PlatformSettings.Add(new ProceduralMaterialInspector.ProceduralPlatformSetting(base.targets, current.name, current.DefaultTarget, current.smallIcon)); + } + } + public void ShowTextureSizeGUI() + { + if (this.m_PlatformSettings == null) + { + this.BuildTargetList(); + } + this.TextureSizeGUI(); + } + protected void TextureSizeGUI() + { + BuildPlayerWindow.BuildPlatform[] platforms = BuildPlayerWindow.GetValidPlatforms().ToArray(); + int num = EditorGUILayout.BeginPlatformGrouping(platforms, this.m_Styles.defaultPlatform); + ProceduralMaterialInspector.ProceduralPlatformSetting proceduralPlatformSetting = this.m_PlatformSettings[num + 1]; + ProceduralMaterialInspector.ProceduralPlatformSetting proceduralPlatformSetting2 = proceduralPlatformSetting; + bool flag = true; + if (proceduralPlatformSetting.name != string.Empty) + { + EditorGUI.BeginChangeCheck(); + flag = GUILayout.Toggle(proceduralPlatformSetting.overridden, "Override for " + proceduralPlatformSetting.name, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (flag) + { + proceduralPlatformSetting.SetOverride(this.m_PlatformSettings[0]); + } + else + { + proceduralPlatformSetting.ClearOverride(this.m_PlatformSettings[0]); + } + } + } + EditorGUI.BeginDisabledGroup(!flag); + EditorGUI.BeginChangeCheck(); + proceduralPlatformSetting2.maxTextureWidth = EditorGUILayout.IntPopup(this.m_Styles.targetWidth.text, proceduralPlatformSetting2.maxTextureWidth, ProceduralMaterialInspector.kMaxTextureSizeStrings, ProceduralMaterialInspector.kMaxTextureSizeValues, new GUILayoutOption[0]); + proceduralPlatformSetting2.maxTextureHeight = EditorGUILayout.IntPopup(this.m_Styles.targetHeight.text, proceduralPlatformSetting2.maxTextureHeight, ProceduralMaterialInspector.kMaxTextureSizeStrings, ProceduralMaterialInspector.kMaxTextureSizeValues, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && proceduralPlatformSetting2.isDefault) + { + foreach (ProceduralMaterialInspector.ProceduralPlatformSetting current in this.m_PlatformSettings) + { + if (!current.isDefault && !current.overridden) + { + current.maxTextureWidth = proceduralPlatformSetting2.maxTextureWidth; + current.maxTextureHeight = proceduralPlatformSetting2.maxTextureHeight; + } + } + } + EditorGUI.BeginChangeCheck(); + int num2 = proceduralPlatformSetting2.textureFormat; + if (num2 < 0 || num2 >= ProceduralMaterialInspector.kTextureFormatStrings.Length) + { + Debug.LogError("Invalid TextureFormat"); + } + num2 = EditorGUILayout.IntPopup(this.m_Styles.textureFormat.text, num2, ProceduralMaterialInspector.kTextureFormatStrings, ProceduralMaterialInspector.kTextureFormatValues, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + proceduralPlatformSetting2.textureFormat = num2; + if (proceduralPlatformSetting2.isDefault) + { + foreach (ProceduralMaterialInspector.ProceduralPlatformSetting current2 in this.m_PlatformSettings) + { + if (!current2.isDefault && !current2.overridden) + { + current2.textureFormat = proceduralPlatformSetting2.textureFormat; + } + } + } + } + EditorGUI.BeginChangeCheck(); + proceduralPlatformSetting2.m_LoadBehavior = EditorGUILayout.IntPopup(this.m_Styles.loadBehavior.text, proceduralPlatformSetting2.m_LoadBehavior, ProceduralMaterialInspector.kMaxLoadBehaviorStrings, ProceduralMaterialInspector.kMaxLoadBehaviorValues, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && proceduralPlatformSetting2.isDefault) + { + foreach (ProceduralMaterialInspector.ProceduralPlatformSetting current3 in this.m_PlatformSettings) + { + if (!current3.isDefault && !current3.overridden) + { + current3.m_LoadBehavior = proceduralPlatformSetting2.m_LoadBehavior; + } + } + } + GUILayout.Space(5f); + EditorGUI.BeginDisabledGroup(!this.HasModified()); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Revert", new GUILayoutOption[0])) + { + this.ResetValues(); + } + if (GUILayout.Button("Apply", new GUILayoutOption[0])) + { + this.Apply(); + this.ReimportSubstances(); + this.ResetValues(); + } + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(5f); + EditorGUILayout.EndPlatformGrouping(); + EditorGUI.EndDisabledGroup(); + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + base.OnPreviewGUI(r, background); + if (ProceduralMaterialInspector.ShowIsGenerating(this.target as ProceduralMaterial) && r.width > 50f) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Generating..."); + } + } + public void InputsGUI() + { + ProceduralPropertyDescription[] proceduralPropertyDescriptions = ProceduralMaterialInspector.m_Material.GetProceduralPropertyDescriptions(); + ProceduralPropertyDescription proceduralPropertyDescription = null; + ProceduralPropertyDescription proceduralPropertyDescription2 = null; + ProceduralPropertyDescription proceduralPropertyDescription3 = null; + this.m_LastGroup = string.Empty; + for (int i = 0; i < proceduralPropertyDescriptions.Length; i++) + { + ProceduralPropertyDescription proceduralPropertyDescription4 = proceduralPropertyDescriptions[i]; + if (!(proceduralPropertyDescription4.name == "$outputsize")) + { + if (proceduralPropertyDescription4.name == "$randomseed") + { + this.InputSeedGUI(proceduralPropertyDescription4); + } + else + { + if (proceduralPropertyDescription4.name == "Hue_Shift" && proceduralPropertyDescription4.group == string.Empty) + { + proceduralPropertyDescription = proceduralPropertyDescription4; + } + else + { + if (proceduralPropertyDescription4.name == "Saturation" && proceduralPropertyDescription4.group == string.Empty) + { + proceduralPropertyDescription2 = proceduralPropertyDescription4; + } + else + { + if (proceduralPropertyDescription4.name == "Luminosity" && proceduralPropertyDescription4.group == string.Empty) + { + proceduralPropertyDescription3 = proceduralPropertyDescription4; + } + else + { + if (proceduralPropertyDescription4.name.Length <= 0 || proceduralPropertyDescription4.name[0] != '$') + { + this.InputGUI(proceduralPropertyDescription4); + } + } + } + } + } + } + } + if (proceduralPropertyDescription != null && proceduralPropertyDescription2 != null && proceduralPropertyDescription3 != null && proceduralPropertyDescription.type == ProceduralPropertyType.Float && proceduralPropertyDescription2.type == ProceduralPropertyType.Float && proceduralPropertyDescription3.type == ProceduralPropertyType.Float) + { + this.InputHSLGUI(proceduralPropertyDescription, proceduralPropertyDescription2, proceduralPropertyDescription3); + } + else + { + if (proceduralPropertyDescription != null) + { + this.InputGUI(proceduralPropertyDescription); + } + if (proceduralPropertyDescription2 != null) + { + this.InputGUI(proceduralPropertyDescription2); + } + if (proceduralPropertyDescription3 != null) + { + this.InputGUI(proceduralPropertyDescription3); + } + } + } + private void InputGUI(ProceduralPropertyDescription input) + { + bool flag = true; + ProceduralMaterial proceduralMaterial = this.target as ProceduralMaterial; + string name = proceduralMaterial.name; + string key = name + input.group; + if (input.group != this.m_LastGroup) + { + GUILayout.Space(5f); + if (input.group != string.Empty) + { + this.m_LastGroup = input.group; + flag = EditorPrefs.GetBool(key, true); + EditorGUI.BeginChangeCheck(); + flag = EditorGUILayout.Foldout(flag, input.group); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool(key, flag); + } + } + } + else + { + flag = EditorPrefs.GetBool(key, true); + } + if (flag || input.group == string.Empty) + { + int indentLevel = EditorGUI.indentLevel; + if (input.group != string.Empty) + { + EditorGUI.indentLevel++; + } + ProceduralPropertyType type = input.type; + GUIContent gUIContent = new GUIContent(input.label, input.name); + switch (type) + { + case ProceduralPropertyType.Boolean: + { + EditorGUI.BeginChangeCheck(); + bool value = EditorGUILayout.Toggle(gUIContent, ProceduralMaterialInspector.m_Material.GetProceduralBoolean(input.name), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralBoolean(input.name, value); + } + break; + } + case ProceduralPropertyType.Float: + { + EditorGUI.BeginChangeCheck(); + float value2; + if (input.hasRange) + { + float minimum = input.minimum; + float maximum = input.maximum; + value2 = EditorGUILayout.Slider(gUIContent, ProceduralMaterialInspector.m_Material.GetProceduralFloat(input.name), minimum, maximum, new GUILayoutOption[0]); + } + else + { + value2 = EditorGUILayout.FloatField(gUIContent, ProceduralMaterialInspector.m_Material.GetProceduralFloat(input.name), new GUILayoutOption[0]); + } + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralFloat(input.name, value2); + } + break; + } + case ProceduralPropertyType.Vector2: + case ProceduralPropertyType.Vector3: + case ProceduralPropertyType.Vector4: + { + int num = (type != ProceduralPropertyType.Vector2) ? ((type != ProceduralPropertyType.Vector3) ? 4 : 3) : 2; + Vector4 vector = ProceduralMaterialInspector.m_Material.GetProceduralVector(input.name); + EditorGUI.BeginChangeCheck(); + if (input.hasRange) + { + float minimum2 = input.minimum; + float maximum2 = input.maximum; + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(gUIContent, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + for (int i = 0; i < num; i++) + { + vector[i] = EditorGUILayout.Slider(new GUIContent(input.componentLabels[i]), vector[i], minimum2, maximum2, new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + EditorGUILayout.EndVertical(); + } + else + { + switch (num) + { + case 2: + vector = EditorGUILayout.Vector2Field(input.name, vector, new GUILayoutOption[0]); + break; + case 3: + vector = EditorGUILayout.Vector3Field(input.name, vector, new GUILayoutOption[0]); + break; + case 4: + vector = EditorGUILayout.Vector4Field(input.name, vector, new GUILayoutOption[0]); + break; + } + } + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralVector(input.name, vector); + } + break; + } + case ProceduralPropertyType.Color3: + case ProceduralPropertyType.Color4: + { + EditorGUI.BeginChangeCheck(); + Color value3 = EditorGUILayout.ColorField(gUIContent, ProceduralMaterialInspector.m_Material.GetProceduralColor(input.name), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralColor(input.name, value3); + } + break; + } + case ProceduralPropertyType.Enum: + { + GUIContent[] array = new GUIContent[input.enumOptions.Length]; + for (int j = 0; j < array.Length; j++) + { + array[j] = new GUIContent(input.enumOptions[j]); + } + EditorGUI.BeginChangeCheck(); + int value4 = EditorGUILayout.Popup(gUIContent, ProceduralMaterialInspector.m_Material.GetProceduralEnum(input.name), array, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralEnum(input.name, value4); + } + break; + } + case ProceduralPropertyType.Texture: + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(gUIContent, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect rect = GUILayoutUtility.GetRect(64f, 64f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + EditorGUI.BeginChangeCheck(); + Texture2D value5 = EditorGUI.DoObjectField(rect, rect, GUIUtility.GetControlID(12354, EditorGUIUtility.native, rect), ProceduralMaterialInspector.m_Material.GetProceduralTexture(input.name), typeof(Texture2D), null, null, false) as Texture2D; + EditorGUILayout.EndHorizontal(); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified property " + input.name + " for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralTexture(input.name, value5); + } + break; + } + } + EditorGUI.indentLevel = indentLevel; + } + } + private void InputHSLGUI(ProceduralPropertyDescription hInput, ProceduralPropertyDescription sInput, ProceduralPropertyDescription lInput) + { + GUILayout.Space(5f); + this.m_ShowHSLInputs = EditorPrefs.GetBool("ProceduralShowHSL", true); + EditorGUI.BeginChangeCheck(); + this.m_ShowHSLInputs = EditorGUILayout.Foldout(this.m_ShowHSLInputs, this.m_Styles.hslContent); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("ProceduralShowHSL", this.m_ShowHSLInputs); + } + if (this.m_ShowHSLInputs) + { + EditorGUI.indentLevel++; + this.InputGUI(hInput); + this.InputGUI(sInput); + this.InputGUI(lInput); + EditorGUI.indentLevel--; + } + } + private void InputSeedGUI(ProceduralPropertyDescription input) + { + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + float value = (float)this.RandomIntField(controlRect, this.m_Styles.randomSeedContent, (int)ProceduralMaterialInspector.m_Material.GetProceduralFloat(input.name), 0, 9999); + if (EditorGUI.EndChangeCheck()) + { + this.RecordForUndo(ProceduralMaterialInspector.m_Material, ProceduralMaterialInspector.m_Importer, "Modified random seed for material " + ProceduralMaterialInspector.m_Material.name); + ProceduralMaterialInspector.m_Material.SetProceduralFloat(input.name, value); + } + } + internal int RandomIntField(Rect position, GUIContent label, int val, int min, int max) + { + position = EditorGUI.PrefixLabel(position, 0, label); + return this.RandomIntField(position, val, min, max); + } + internal int RandomIntField(Rect position, int val, int min, int max) + { + position.width = position.width - EditorGUIUtility.fieldWidth - 5f; + if (GUI.Button(position, this.m_Styles.randomizeButtonContent, EditorStyles.miniButton)) + { + val = UnityEngine.Random.Range(min, max + 1); + } + position.x += position.width + 5f; + position.width = EditorGUIUtility.fieldWidth; + val = Mathf.Clamp(EditorGUI.IntField(position, val), min, max); + return val; + } + } +} diff --git a/UnityEditor/UnityEditor/ProceduralTextureInspector.cs b/UnityEditor/UnityEditor/ProceduralTextureInspector.cs new file mode 100644 index 00000000..85c825aa --- /dev/null +++ b/UnityEditor/UnityEditor/ProceduralTextureInspector.cs @@ -0,0 +1,89 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(ProceduralTexture))] + internal class ProceduralTextureInspector : TextureInspector + { + private bool m_MightHaveModified; + public void OnDisable() + { + if (!EditorApplication.isPlaying && !InternalEditorUtility.ignoreInspectorChanges && this.m_MightHaveModified) + { + this.m_MightHaveModified = false; + string[] array = new string[base.targets.GetLength(0)]; + int num = 0; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ProceduralTexture proceduralTexture = (ProceduralTexture)targets[i]; + string assetPath = AssetDatabase.GetAssetPath(proceduralTexture); + SubstanceImporter substanceImporter = AssetImporter.GetAtPath(assetPath) as SubstanceImporter; + if (substanceImporter) + { + substanceImporter.OnTextureInformationsChanged(proceduralTexture); + } + assetPath = AssetDatabase.GetAssetPath(proceduralTexture.GetProceduralMaterial()); + bool flag = false; + for (int j = 0; j < num; j++) + { + if (array[j] == assetPath) + { + flag = true; + break; + } + } + if (!flag) + { + array[num++] = assetPath; + } + } + for (int k = 0; k < num; k++) + { + SubstanceImporter substanceImporter2 = AssetImporter.GetAtPath(array[k]) as SubstanceImporter; + if (substanceImporter2 && EditorUtility.IsDirty(substanceImporter2.GetInstanceID())) + { + AssetDatabase.ImportAsset(array[k], ImportAssetOptions.ForceUncompressedImport); + } + } + } + } + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + if (GUI.changed) + { + this.m_MightHaveModified = true; + } + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + ProceduralTexture proceduralTexture = (ProceduralTexture)targets[i]; + if (proceduralTexture) + { + ProceduralMaterial proceduralMaterial = proceduralTexture.GetProceduralMaterial(); + if (proceduralMaterial && proceduralMaterial.isProcessing) + { + base.Repaint(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + break; + } + } + } + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + base.OnPreviewGUI(r, background); + if (this.target) + { + ProceduralMaterial proceduralMaterial = (this.target as ProceduralTexture).GetProceduralMaterial(); + if (proceduralMaterial && ProceduralMaterialInspector.ShowIsGenerating(proceduralMaterial) && r.width > 50f) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Generating..."); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ProfilerIPWindow.cs b/UnityEditor/UnityEditor/ProfilerIPWindow.cs new file mode 100644 index 00000000..af954c1c --- /dev/null +++ b/UnityEditor/UnityEditor/ProfilerIPWindow.cs @@ -0,0 +1,46 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ProfilerIPWindow : EditorWindow + { + private const string kTextFieldId = "IPWindow"; + private const string kLastIP = "ProfilerLastIP"; + internal string m_IPString = ProfilerIPWindow.GetLastIPString(); + internal bool didFocus; + public static void Show(Rect buttonScreenRect) + { + Rect rect = new Rect(buttonScreenRect.x, buttonScreenRect.yMax, 300f, 50f); + ProfilerIPWindow windowWithRect = EditorWindow.GetWindowWithRect(rect, true, "Enter Player IP"); + windowWithRect.position = rect; + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + } + public static string GetLastIPString() + { + return EditorPrefs.GetString("ProfilerLastIP", string.Empty); + } + private void OnGUI() + { + Event current = Event.current; + bool flag = current.type == EventType.KeyDown && (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter); + GUI.SetNextControlName("IPWindow"); + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(5f); + this.m_IPString = EditorGUILayout.TextField(this.m_IPString, new GUILayoutOption[0]); + if (!this.didFocus) + { + this.didFocus = true; + EditorGUI.FocusTextInControl("IPWindow"); + } + GUI.enabled = (this.m_IPString.Length != 0); + if (GUILayout.Button("Connect", new GUILayoutOption[0]) || flag) + { + base.Close(); + EditorPrefs.SetString("ProfilerLastIP", this.m_IPString); + AttachProfilerUI.DirectIPConnect(this.m_IPString); + GUIUtility.ExitGUI(); + } + EditorGUILayout.EndVertical(); + } + } +} diff --git a/UnityEditor/UnityEditor/ProfilerWindow.cs b/UnityEditor/UnityEditor/ProfilerWindow.cs new file mode 100644 index 00000000..97504606 --- /dev/null +++ b/UnityEditor/UnityEditor/ProfilerWindow.cs @@ -0,0 +1,889 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ProfilerWindow : EditorWindow, IProfilerWindowController + { + internal class Styles + { + public GUIContent addArea = EditorGUIUtility.TextContent("Profiler.AddArea"); + public GUIContent deepProfile = EditorGUIUtility.TextContent("Profiler.DeepProfile"); + public GUIContent profileEditor = EditorGUIUtility.TextContent("Profiler.ProfileEditor"); + public GUIContent noData = EditorGUIUtility.TextContent("Profiler.NoFrameDataAvailable"); + public GUIContent noLicense = EditorGUIUtility.TextContent("Profiler.NoLicense"); + public GUIContent profilerRecord = EditorGUIUtility.TextContent("Profiler.Record"); + public GUIContent prevFrame = EditorGUIUtility.IconContent("Profiler.PrevFrame"); + public GUIContent nextFrame = EditorGUIUtility.IconContent("Profiler.NextFrame"); + public GUIContent currentFrame = EditorGUIUtility.TextContent("Profiler.CurrentFrame"); + public GUIContent frame = EditorGUIUtility.TextContent("Frame: "); + public GUIContent clearData = EditorGUIUtility.TextContent("Clear"); + public GUIContent[] reasons = EditorGUIUtility.GetTextContentsForEnum(typeof(MemoryInfoGCReason)); + public GUIStyle background = "OL Box"; + public GUIStyle header = "OL title"; + public GUIStyle label = "OL label"; + public GUIStyle entryEven = "OL EntryBackEven"; + public GUIStyle entryOdd = "OL EntryBackOdd"; + public GUIStyle foldout = "IN foldout"; + public GUIStyle profilerGraphBackground = "ProfilerScrollviewBackground"; + public Styles() + { + this.profilerGraphBackground.overflow.left = -170; + } + } + private const float kRowHeight = 16f; + private const float kIndentPx = 16f; + private const float kBaseIndent = 8f; + private const float kSmallMargin = 4f; + private const float kNameColumnSize = 350f; + private const float kColumnSize = 80f; + private const float kFoldoutSize = 14f; + private const int kFirst = -999999; + private const int kLast = 999999; + private const string kProfilerColumnSettings = "VisibleProfilerColumnsV2"; + private const string kProfilerDetailColumnSettings = "VisibleProfilerDetailColumns"; + private const string kProfilerGPUColumnSettings = "VisibleProfilerGPUColumns"; + private const string kProfilerGPUDetailColumnSettings = "VisibleProfilerGPUDetailColumns"; + private const string kProfilerVisibleGraphsSettings = "VisibleProfilerGraphs"; + internal const string kPrefCharts = "ProfilerChart"; + private static ProfilerWindow.Styles ms_Styles; + private bool m_HasProfilerLicense; + private SplitterState m_VertSplit = new SplitterState(new float[] + { + 50f, + 50f + }, new int[] + { + 50, + 50 + }, null); + private SplitterState m_ViewSplit = new SplitterState(new float[] + { + 70f, + 30f + }, new int[] + { + 450, + 50 + }, null); + [SerializeField] + private bool m_Recording = true; + private AttachProfilerUI m_AttachProfilerUI = default(AttachProfilerUI); + private Vector2 m_GraphPos = Vector2.zero; + private Vector2[] m_PaneScroll = new Vector2[7]; + private static List m_ProfilerWindows = new List(); + private ProfilerViewType m_ViewType; + private ProfilerArea m_CurrentArea; + private ProfilerMemoryView m_ShowDetailedMemoryPane; + private int m_CurrentFrame = -1; + private int m_LastFrameFromTick = -1; + private int m_PrevLastFrame = -1; + private ProfilerChart[] m_Charts; + private float[] m_ChartOldMax = new float[] + { + -1f, + -1f + }; + private float m_ChartMaxClamp = 70000f; + private ProfilerHierarchyGUI m_CPUHierarchyGUI; + private ProfilerHierarchyGUI m_GPUHierarchyGUI; + private ProfilerHierarchyGUI m_CPUDetailHierarchyGUI; + private ProfilerHierarchyGUI m_GPUDetailHierarchyGUI; + private ProfilerTimelineGUI m_CPUTimelineGUI; + private MemoryTreeList m_ReferenceListView; + private MemoryTreeListClickable m_MemoryListView; + private bool wantsMemoryRefresh + { + get + { + return this.m_MemoryListView.GetRoot() == null; + } + } + private void BuildColumns() + { + ProfilerColumn[] array = new ProfilerColumn[] + { + ProfilerColumn.FunctionName, + ProfilerColumn.TotalPercent, + ProfilerColumn.SelfPercent, + ProfilerColumn.Calls, + ProfilerColumn.GCMemory, + ProfilerColumn.TotalTime, + ProfilerColumn.SelfTime, + ProfilerColumn.WarningCount + }; + ProfilerColumn[] array2 = new ProfilerColumn[] + { + ProfilerColumn.ObjectName, + ProfilerColumn.TotalPercent, + ProfilerColumn.SelfPercent, + ProfilerColumn.Calls, + ProfilerColumn.GCMemory, + ProfilerColumn.TotalTime, + ProfilerColumn.SelfTime + }; + this.m_CPUHierarchyGUI = new ProfilerHierarchyGUI(this, "VisibleProfilerColumnsV2", array, ProfilerWindow.ProfilerColumnNames(array), false, ProfilerColumn.TotalTime); + this.m_CPUTimelineGUI = new ProfilerTimelineGUI(this); + string text = EditorGUIUtility.TextContent("ProfilerColumn.DetailViewObject").text; + string[] array3 = ProfilerWindow.ProfilerColumnNames(array2); + array3[0] = text; + this.m_CPUDetailHierarchyGUI = new ProfilerHierarchyGUI(this, "VisibleProfilerDetailColumns", array2, array3, true, ProfilerColumn.TotalTime); + ProfilerColumn[] array4 = new ProfilerColumn[] + { + ProfilerColumn.FunctionName, + ProfilerColumn.TotalGPUPercent, + ProfilerColumn.DrawCalls, + ProfilerColumn.TotalGPUTime + }; + ProfilerColumn[] array5 = new ProfilerColumn[] + { + ProfilerColumn.ObjectName, + ProfilerColumn.TotalGPUPercent, + ProfilerColumn.DrawCalls, + ProfilerColumn.TotalGPUTime + }; + this.m_GPUHierarchyGUI = new ProfilerHierarchyGUI(this, "VisibleProfilerGPUColumns", array4, ProfilerWindow.ProfilerColumnNames(array4), false, ProfilerColumn.TotalGPUTime); + array3 = ProfilerWindow.ProfilerColumnNames(array5); + array3[0] = text; + this.m_GPUDetailHierarchyGUI = new ProfilerHierarchyGUI(this, "VisibleProfilerGPUDetailColumns", array5, array3, true, ProfilerColumn.TotalGPUTime); + } + private static string[] ProfilerColumnNames(ProfilerColumn[] columns) + { + string[] names = Enum.GetNames(typeof(ProfilerColumn)); + string[] array = new string[columns.Length]; + for (int i = 0; i < columns.Length; i++) + { + array[i] = "ProfilerColumn." + names[(int)columns[i]]; + } + return array; + } + public void SetSelectedPropertyPath(string path) + { + if (ProfilerDriver.selectedPropertyPath != path) + { + ProfilerDriver.selectedPropertyPath = path; + this.UpdateCharts(); + } + } + public void ClearSelectedPropertyPath() + { + if (ProfilerDriver.selectedPropertyPath != string.Empty) + { + this.m_CPUHierarchyGUI.selectedIndex = -1; + ProfilerDriver.selectedPropertyPath = string.Empty; + this.UpdateCharts(); + } + } + public ProfilerProperty CreateProperty(bool details) + { + ProfilerProperty profilerProperty = new ProfilerProperty(); + ProfilerColumn profilerSortColumn = (this.m_CurrentArea != ProfilerArea.CPU) ? ((!details) ? this.m_GPUHierarchyGUI.sortType : this.m_GPUDetailHierarchyGUI.sortType) : ((!details) ? this.m_CPUHierarchyGUI.sortType : this.m_CPUDetailHierarchyGUI.sortType); + profilerProperty.SetRoot(this.GetActiveVisibleFrameIndex(), profilerSortColumn, this.m_ViewType); + profilerProperty.onlyShowGPUSamples = (this.m_CurrentArea == ProfilerArea.GPU); + return profilerProperty; + } + private void OnEnable() + { + ProfilerWindow.m_ProfilerWindows.Add(this); + this.m_HasProfilerLicense = InternalEditorUtility.HasPro(); + int len = ProfilerDriver.maxHistoryLength - 1; + this.m_Charts = new ProfilerChart[7]; + Color[] colors = ProfilerColors.colors; + for (ProfilerArea profilerArea = ProfilerArea.CPU; profilerArea < ProfilerArea.AreaCount; profilerArea++) + { + float dataScale = 1f; + Chart.ChartType type = Chart.ChartType.Line; + string[] graphStatisticsPropertiesForArea = ProfilerDriver.GetGraphStatisticsPropertiesForArea(profilerArea); + int num = graphStatisticsPropertiesForArea.Length; + if (profilerArea == ProfilerArea.GPU || profilerArea == ProfilerArea.CPU) + { + type = Chart.ChartType.StackedFill; + dataScale = 0.001f; + } + ProfilerChart profilerChart = new ProfilerChart(profilerArea, type, dataScale, num); + for (int i = 0; i < num; i++) + { + profilerChart.m_Series[i] = new ChartSeries(graphStatisticsPropertiesForArea[i], len, colors[i]); + } + this.m_Charts[(int)profilerArea] = profilerChart; + } + if (this.m_ReferenceListView == null) + { + this.m_ReferenceListView = new MemoryTreeList(this, null); + } + if (this.m_MemoryListView == null) + { + this.m_MemoryListView = new MemoryTreeListClickable(this, this.m_ReferenceListView); + } + this.UpdateCharts(); + this.BuildColumns(); + ProfilerChart[] charts = this.m_Charts; + for (int j = 0; j < charts.Length; j++) + { + ProfilerChart profilerChart2 = charts[j]; + profilerChart2.LoadAndBindSettings(); + } + } + private void OnDisable() + { + ProfilerWindow.m_ProfilerWindows.Remove(this); + } + private void Awake() + { + if (!Profiler.supported) + { + return; + } + Profiler.enabled = this.m_Recording; + } + private void OnDestroy() + { + if (Profiler.supported) + { + Profiler.enabled = false; + } + } + private void OnFocus() + { + if (Profiler.supported) + { + Profiler.enabled = this.m_Recording; + } + } + private void OnLostFocus() + { + } + private static void ShowProfilerWindow() + { + EditorWindow.GetWindow(false); + } + private static void RepaintAllProfilerWindows() + { + foreach (ProfilerWindow current in ProfilerWindow.m_ProfilerWindows) + { + if (ProfilerDriver.lastFrameIndex != current.m_LastFrameFromTick) + { + current.m_LastFrameFromTick = ProfilerDriver.lastFrameIndex; + current.RepaintImmediately(); + } + } + } + private static void SetMemoryProfilerInfo(ObjectMemoryInfo[] memoryInfo, int[] referencedIndices) + { + foreach (ProfilerWindow current in ProfilerWindow.m_ProfilerWindows) + { + if (current.wantsMemoryRefresh) + { + current.m_MemoryListView.SetRoot(MemoryElementDataManager.GetTreeRoot(memoryInfo, referencedIndices)); + } + } + } + private static void SetProfileDeepScripts(bool deep) + { + bool deepProfiling = ProfilerDriver.deepProfiling; + if (deepProfiling == deep) + { + return; + } + bool flag = true; + if (EditorApplication.isPlaying) + { + if (deep) + { + flag = EditorUtility.DisplayDialog("Enable deep script profiling", "Enabling deep profiling requires reloading scripts.", "Reload", "Cancel"); + } + else + { + flag = EditorUtility.DisplayDialog("Disable deep script profiling", "Disabling deep profiling requires reloading all scripts", "Reload", "Cancel"); + } + } + if (flag) + { + ProfilerDriver.deepProfiling = deep; + InternalEditorUtility.RequestScriptReload(); + } + } + private string PickFrameLabel() + { + if (this.m_CurrentFrame == -1) + { + return "Current"; + } + return this.m_CurrentFrame + 1 + " / " + (ProfilerDriver.lastFrameIndex + 1); + } + private void PrevFrame() + { + int previousFrameIndex = ProfilerDriver.GetPreviousFrameIndex(this.m_CurrentFrame); + if (previousFrameIndex != -1) + { + this.SetCurrentFrame(previousFrameIndex); + } + } + private void NextFrame() + { + int nextFrameIndex = ProfilerDriver.GetNextFrameIndex(this.m_CurrentFrame); + if (nextFrameIndex != -1) + { + this.SetCurrentFrame(nextFrameIndex); + } + } + private static void DrawEmptyCPUOrRenderingDetailPane() + { + GUILayout.Box(string.Empty, ProfilerWindow.ms_Styles.header, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label("Select Line for per-object breakdown", EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + private void DrawCPUOrRenderingToolbar(ProfilerProperty property) + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + string[] displayedOptions; + int[] optionValues; + if (!Unsupported.IsDeveloperBuild()) + { + displayedOptions = new string[] + { + "Hierarchy", + "Raw Hierarchy" + }; + optionValues = new int[] + { + 0, + 2 + }; + } + else + { + displayedOptions = new string[] + { + "Hierarchy", + "Timeline", + "Raw Hierarchy" + }; + optionValues = new int[] + { + 0, + 1, + 2 + }; + } + this.m_ViewType = (ProfilerViewType)EditorGUILayout.IntPopup((int)this.m_ViewType, displayedOptions, optionValues, EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(100f) + }); + GUILayout.FlexibleSpace(); + GUILayout.Label(string.Format("CPU:{0}ms GPU:{1}ms", property.frameTime, property.frameGpuTime), EditorStyles.miniLabel, new GUILayoutOption[0]); + EditorGUILayout.EndHorizontal(); + } + private static bool CheckFrameData(ProfilerProperty property) + { + if (!property.frameDataReady) + { + GUILayout.Label(ProfilerWindow.ms_Styles.noData, ProfilerWindow.ms_Styles.background, new GUILayoutOption[0]); + return false; + } + return true; + } + private void DrawCPUOrRenderingPane(ProfilerHierarchyGUI mainPane, ProfilerHierarchyGUI detailPane, ProfilerTimelineGUI timelinePane) + { + ProfilerProperty profilerProperty = this.CreateProperty(false); + this.DrawCPUOrRenderingToolbar(profilerProperty); + if (!ProfilerWindow.CheckFrameData(profilerProperty)) + { + profilerProperty.Cleanup(); + return; + } + if (timelinePane != null && this.m_ViewType == ProfilerViewType.Timeline) + { + float num = (float)this.m_VertSplit.realSizes[1]; + num -= EditorStyles.toolbar.CalcHeight(GUIContent.none, 10f) + 2f; + timelinePane.DoGUI(this.GetActiveVisibleFrameIndex(), base.position.width, base.position.height - num, num); + profilerProperty.Cleanup(); + } + else + { + SplitterGUILayout.BeginHorizontalSplit(this.m_ViewSplit, new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + bool expandAll = false; + mainPane.DoGUI(profilerProperty, expandAll); + profilerProperty.Cleanup(); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + ProfilerProperty profilerProperty2 = this.CreateProperty(true); + ProfilerProperty detailedProperty = mainPane.GetDetailedProperty(profilerProperty2); + profilerProperty2.Cleanup(); + if (detailedProperty != null) + { + detailPane.DoGUI(detailedProperty, expandAll); + detailedProperty.Cleanup(); + } + else + { + ProfilerWindow.DrawEmptyCPUOrRenderingDetailPane(); + } + GUILayout.EndVertical(); + SplitterGUILayout.EndHorizontalSplit(); + } + } + private void DrawMemoryPane(SplitterState splitter) + { + this.DrawMemoryToolbar(); + if (this.m_ShowDetailedMemoryPane == ProfilerMemoryView.Simple) + { + this.DrawOverviewText(ProfilerArea.Memory); + } + else + { + this.DrawDetailedMemoryPane(splitter); + } + } + private void DrawDetailedMemoryPane(SplitterState splitter) + { + SplitterGUILayout.BeginHorizontalSplit(splitter, new GUILayoutOption[0]); + this.m_MemoryListView.OnGUI(); + this.m_ReferenceListView.OnGUI(); + SplitterGUILayout.EndHorizontalSplit(); + } + private static Rect GenerateRect(ref int row, int indent) + { + Rect result = new Rect((float)indent * 16f + 8f, (float)row * 16f, 0f, 16f); + result.xMax = 350f; + row++; + return result; + } + private static void DrawBackground(int row, bool selected) + { + Rect position = new Rect(1f, 16f * (float)row, GUIClip.visibleRect.width, 16f); + GUIStyle gUIStyle = (row % 2 != 0) ? ProfilerWindow.ms_Styles.entryOdd : ProfilerWindow.ms_Styles.entryEven; + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(position, GUIContent.none, false, false, selected, false); + } + } + private void DrawMemoryToolbar() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + this.m_ShowDetailedMemoryPane = (ProfilerMemoryView)EditorGUILayout.EnumPopup(this.m_ShowDetailedMemoryPane, EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(70f) + }); + GUILayout.Space(5f); + if (this.m_ShowDetailedMemoryPane == ProfilerMemoryView.Detailed) + { + if (GUILayout.Button("Take Sample: " + this.m_AttachProfilerUI.GetConnectedProfiler(), EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.RefreshMemoryData(); + } + if (this.m_AttachProfilerUI.IsEditor()) + { + GUILayout.Label("Memory usage in editor is not as it would be in a player", EditorStyles.toolbarButton, new GUILayoutOption[0]); + } + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + } + private void RefreshMemoryData() + { + this.m_MemoryListView.SetRoot(null); + ProfilerDriver.RequestObjectMemoryInfo(); + } + private static void UpdateChartGrid(float timeMax, ChartData data) + { + if (timeMax < 1500f) + { + data.SetGrid(new float[] + { + 1000f, + 250f, + 100f + }, new string[] + { + "1ms (1000FPS)", + "0.25ms (4000FPS)", + "0.1ms (10000FPS)" + }); + } + else + { + if (timeMax < 10000f) + { + data.SetGrid(new float[] + { + 8333f, + 4000f, + 1000f + }, new string[] + { + "8ms (120FPS)", + "4ms (250FPS)", + "1ms (1000FPS)" + }); + } + else + { + if (timeMax < 30000f) + { + data.SetGrid(new float[] + { + 16667f, + 10000f, + 5000f + }, new string[] + { + "16ms (60FPS)", + "10ms (100FPS)", + "5ms (200FPS)" + }); + } + else + { + if (timeMax < 100000f) + { + data.SetGrid(new float[] + { + 66667f, + 33333f, + 16667f + }, new string[] + { + "66ms (15FPS)", + "33ms (30FPS)", + "16ms (60FPS)" + }); + } + else + { + data.SetGrid(new float[] + { + 500000f, + 200000f, + 66667f + }, new string[] + { + "500ms (2FPS)", + "200ms (5FPS)", + "66ms (15FPS)" + }); + } + } + } + } + } + private void UpdateCharts() + { + int num = ProfilerDriver.maxHistoryLength - 1; + int num2 = ProfilerDriver.lastFrameIndex - num; + int num3 = Mathf.Max(ProfilerDriver.firstFrameIndex, num2); + ProfilerChart[] charts = this.m_Charts; + for (int i = 0; i < charts.Length; i++) + { + ProfilerChart profilerChart = charts[i]; + float[] array = new float[profilerChart.m_Series.Length]; + for (int j = 0; j < profilerChart.m_Series.Length; j++) + { + int statisticsIdentifier = ProfilerDriver.GetStatisticsIdentifier(profilerChart.m_Series[j].identifierName); + float num4; + ProfilerDriver.GetStatisticsValues(statisticsIdentifier, num2, profilerChart.m_DataScale, profilerChart.m_Series[j].data, out num4); + float num5; + if (profilerChart.m_Type == Chart.ChartType.Line) + { + num5 = 1f / (num4 * (1.05f + (float)j * 0.05f)); + } + else + { + num5 = 1f / num4; + } + array[j] = num5; + } + if (profilerChart.m_Type == Chart.ChartType.Line) + { + profilerChart.m_Data.AssignScale(array); + } + profilerChart.m_Data.Assign(profilerChart.m_Series, num2, num3); + } + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + bool flag = selectedPropertyPath != string.Empty && this.m_CurrentArea == ProfilerArea.CPU; + ProfilerChart profilerChart2 = this.m_Charts[0]; + if (flag) + { + profilerChart2.m_Data.hasOverlay = true; + ChartSeries[] series = profilerChart2.m_Series; + for (int k = 0; k < series.Length; k++) + { + ChartSeries chartSeries = series[k]; + int statisticsIdentifier2 = ProfilerDriver.GetStatisticsIdentifier("Selected" + chartSeries.identifierName); + chartSeries.CreateOverlayData(); + float num6; + ProfilerDriver.GetStatisticsValues(statisticsIdentifier2, num2, profilerChart2.m_DataScale, chartSeries.overlayData, out num6); + } + } + else + { + profilerChart2.m_Data.hasOverlay = false; + } + for (ProfilerArea profilerArea = ProfilerArea.CPU; profilerArea <= ProfilerArea.GPU; profilerArea++) + { + ProfilerChart profilerChart3 = this.m_Charts[(int)profilerArea]; + float num7 = 0f; + float num8 = 0f; + for (int l = 0; l < num; l++) + { + float num9 = 0f; + for (int m = 0; m < profilerChart3.m_Series.Length; m++) + { + if (profilerChart3.m_Series[m].enabled) + { + num9 += profilerChart3.m_Series[m].data[l]; + } + } + if (num9 > num7) + { + num7 = num9; + } + if (num9 > num8 && l + num2 >= num3 + 1) + { + num8 = num9; + } + } + if (num8 != 0f) + { + num7 = num8; + } + num7 = Math.Min(num7, this.m_ChartMaxClamp); + if (this.m_ChartOldMax[(int)profilerArea] > 0f) + { + num7 = Mathf.Lerp(this.m_ChartOldMax[(int)profilerArea], num7, 0.4f); + } + this.m_ChartOldMax[(int)profilerArea] = num7; + profilerChart3.m_Data.AssignScale(new float[] + { + 1f / num7 + }); + ProfilerWindow.UpdateChartGrid(num7, profilerChart3.m_Data); + } + string notSupportedWarning = null; + if (ProfilerDriver.isGPUProfilerBuggyOnDriver) + { + notSupportedWarning = "Graphics card driver returned invalid timing information. Please update to a newer version if available."; + } + else + { + if (!ProfilerDriver.isGPUProfilerSupported) + { + notSupportedWarning = "GPU profiling is not supported by the graphics card driver. Please update to a newer version if available."; + if (Application.platform == RuntimePlatform.OSXEditor) + { + if (!ProfilerDriver.isGPUProfilerSupportedByOS) + { + notSupportedWarning = "GPU profiling requires Mac OS X 10.7 (Lion) and a capable video card. GPU profiling is currently not supported on mobile."; + } + else + { + notSupportedWarning = "GPU profiling is not supported by the graphics card driver (or it was disabled because of driver bugs)."; + } + } + } + } + this.m_Charts[1].m_Chart.m_NotSupportedWarning = notSupportedWarning; + } + private void AddAreaClick(object userData, string[] options, int selected) + { + this.m_Charts[selected].m_Active = true; + EditorPrefs.SetBool("ProfilerChart" + (ProfilerArea)selected, true); + } + private void DrawMainToolbar() + { + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(ProfilerWindow.ms_Styles.addArea, EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(120f) + }); + if (EditorGUI.ButtonMouseDown(rect, ProfilerWindow.ms_Styles.addArea, FocusType.Native, EditorStyles.toolbarDropDown)) + { + int num = this.m_Charts.Length; + string[] array = new string[num]; + bool[] array2 = new bool[num]; + for (int i = 0; i < num; i++) + { + array[i] = ((ProfilerArea)i).ToString(); + array2[i] = !this.m_Charts[i].m_Active; + } + EditorUtility.DisplayCustomMenu(rect, array, array2, null, new EditorUtility.SelectMenuItemFunction(this.AddAreaClick), null); + } + GUILayout.FlexibleSpace(); + this.m_Recording = GUILayout.Toggle(this.m_Recording, ProfilerWindow.ms_Styles.profilerRecord, EditorStyles.toolbarButton, new GUILayoutOption[0]); + Profiler.enabled = this.m_Recording; + ProfilerWindow.SetProfileDeepScripts(GUILayout.Toggle(ProfilerDriver.deepProfiling, ProfilerWindow.ms_Styles.deepProfile, EditorStyles.toolbarButton, new GUILayoutOption[0])); + ProfilerDriver.profileEditor = GUILayout.Toggle(ProfilerDriver.profileEditor, ProfilerWindow.ms_Styles.profileEditor, EditorStyles.toolbarButton, new GUILayoutOption[0]); + this.m_AttachProfilerUI.OnGUILayout(this); + if (GUILayout.Button(ProfilerWindow.ms_Styles.clearData, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + ProfilerDriver.ClearAllFrames(); + } + GUILayout.Space(5f); + GUILayout.FlexibleSpace(); + this.FrameNavigationControls(); + GUILayout.EndHorizontal(); + } + private void FrameNavigationControls() + { + if (this.m_CurrentFrame > ProfilerDriver.lastFrameIndex) + { + this.SetCurrentFrameDontPause(ProfilerDriver.lastFrameIndex); + } + GUILayout.Label(ProfilerWindow.ms_Styles.frame, EditorStyles.miniLabel, new GUILayoutOption[0]); + GUILayout.Label(" " + this.PickFrameLabel(), EditorStyles.miniLabel, new GUILayoutOption[] + { + GUILayout.Width(100f) + }); + GUI.enabled = (ProfilerDriver.GetPreviousFrameIndex(this.m_CurrentFrame) != -1); + if (GUILayout.Button(ProfilerWindow.ms_Styles.prevFrame, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.PrevFrame(); + } + GUI.enabled = (ProfilerDriver.GetNextFrameIndex(this.m_CurrentFrame) != -1); + if (GUILayout.Button(ProfilerWindow.ms_Styles.nextFrame, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.NextFrame(); + } + GUI.enabled = true; + GUILayout.Space(10f); + if (GUILayout.Button(ProfilerWindow.ms_Styles.currentFrame, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.SetCurrentFrame(-1); + this.m_LastFrameFromTick = ProfilerDriver.lastFrameIndex; + } + } + private int GetActiveVisibleFrameIndex() + { + return (this.m_CurrentFrame != -1) ? this.m_CurrentFrame : this.m_LastFrameFromTick; + } + private static void DrawOtherToolbar() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + } + private void DrawOverviewText(ProfilerArea area) + { + this.m_PaneScroll[(int)area] = GUILayout.BeginScrollView(this.m_PaneScroll[(int)area], ProfilerWindow.ms_Styles.background); + GUILayout.Label(ProfilerDriver.GetOverviewText(area, this.GetActiveVisibleFrameIndex()), EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + GUILayout.EndScrollView(); + } + private void DrawPane(ProfilerArea area) + { + ProfilerWindow.DrawOtherToolbar(); + this.DrawOverviewText(area); + } + private void SetCurrentFrameDontPause(int frame) + { + this.m_CurrentFrame = frame; + } + private void SetCurrentFrame(int frame) + { + if (frame != -1 && Profiler.enabled && !ProfilerDriver.profileEditor && this.m_CurrentFrame != frame && EditorApplication.isPlayingOrWillChangePlaymode) + { + EditorApplication.isPaused = true; + } + this.SetCurrentFrameDontPause(frame); + } + private void OnGUI() + { + if (ProfilerWindow.ms_Styles == null) + { + ProfilerWindow.ms_Styles = new ProfilerWindow.Styles(); + } + if (!this.m_HasProfilerLicense) + { + GUILayout.Label(ProfilerWindow.ms_Styles.noLicense, EditorStyles.largeLabel, new GUILayoutOption[0]); + return; + } + this.DrawMainToolbar(); + SplitterGUILayout.BeginVerticalSplit(this.m_VertSplit, new GUILayoutOption[0]); + this.m_GraphPos = EditorGUILayout.BeginScrollView(this.m_GraphPos, ProfilerWindow.ms_Styles.profilerGraphBackground, new GUILayoutOption[0]); + if (this.m_PrevLastFrame != ProfilerDriver.lastFrameIndex) + { + this.UpdateCharts(); + this.m_PrevLastFrame = ProfilerDriver.lastFrameIndex; + } + int num = this.m_CurrentFrame; + Chart.ChartAction[] array = new Chart.ChartAction[this.m_Charts.Length]; + for (int i = 0; i < this.m_Charts.Length; i++) + { + ProfilerChart profilerChart = this.m_Charts[i]; + if (profilerChart.m_Active) + { + num = profilerChart.DoChartGUI(num, this.m_CurrentArea, out array[i]); + } + } + bool flag = false; + if (num != this.m_CurrentFrame) + { + this.SetCurrentFrame(num); + flag = true; + } + for (int j = 0; j < this.m_Charts.Length; j++) + { + ProfilerChart profilerChart2 = this.m_Charts[j]; + if (profilerChart2.m_Active) + { + if (array[j] == Chart.ChartAction.Closed) + { + if (this.m_CurrentArea == (ProfilerArea)j) + { + this.m_CurrentArea = ProfilerArea.CPU; + } + profilerChart2.m_Active = false; + EditorPrefs.SetBool("ProfilerChart" + (ProfilerArea)j, false); + } + else + { + if (array[j] == Chart.ChartAction.Activated) + { + this.m_CurrentArea = (ProfilerArea)j; + if (this.m_CurrentArea != ProfilerArea.CPU && this.m_CPUHierarchyGUI.selectedIndex != -1) + { + this.ClearSelectedPropertyPath(); + } + flag = true; + } + } + } + } + if (flag) + { + base.Repaint(); + GUIUtility.ExitGUI(); + } + GUILayout.EndScrollView(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + switch (this.m_CurrentArea) + { + case ProfilerArea.CPU: + this.DrawCPUOrRenderingPane(this.m_CPUHierarchyGUI, this.m_CPUDetailHierarchyGUI, this.m_CPUTimelineGUI); + goto IL_257; + case ProfilerArea.GPU: + this.DrawCPUOrRenderingPane(this.m_GPUHierarchyGUI, this.m_GPUDetailHierarchyGUI, null); + goto IL_257; + case ProfilerArea.Memory: + this.DrawMemoryPane(this.m_ViewSplit); + goto IL_257; + } + this.DrawPane(this.m_CurrentArea); + IL_257: + GUILayout.EndVertical(); + SplitterGUILayout.EndVerticalSplit(); + } + virtual void Repaint() + { + base.Repaint(); + } + } +} diff --git a/UnityEditor/UnityEditor/ProjectBrowser.cs b/UnityEditor/UnityEditor/ProjectBrowser.cs new file mode 100644 index 00000000..66d8d230 --- /dev/null +++ b/UnityEditor/UnityEditor/ProjectBrowser.cs @@ -0,0 +1,2542 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.ProjectWindowCallback; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ProjectBrowser : EditorWindow, IHasCustomMenu + { + internal enum ItemType + { + Asset, + SavedFilter + } + private enum ViewMode + { + OneColumn, + TwoColumns + } + public enum SearchViewState + { + NotSearching, + AllAssets, + SubFolders, + AssetStore + } + private class Styles + { + public GUIStyle smallStatus = "ObjectPickerSmallStatus"; + public GUIStyle largeStatus = "ObjectPickerLargeStatus"; + public GUIStyle toolbarBack = "ObjectPickerToolbar"; + public GUIStyle tab = "ObjectPickerTab"; + public GUIStyle bottomResize = "WindowBottomResize"; + public GUIStyle background = "ObjectPickerBackground"; + public GUIStyle previewBackground = "PopupCurveSwatchBackground"; + public GUIStyle previewTextureBackground = "ObjectPickerPreviewBackground"; + public GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg"; + public GUIStyle topBarBg = "ProjectBrowserTopBarBg"; + public GUIStyle selectedPathLabel = "Label"; + public GUIStyle exposablePopup = ProjectBrowser.Styles.GetStyle("ExposablePopupMenu"); + public GUIStyle lockButton = "IN LockButton"; + public GUIStyle foldout = "AC RightArrow"; + public GUIStyle exposablePopupItem = ProjectBrowser.Styles.GetStyle("ExposablePopupItem"); + public GUIContent m_FilterByLabel = new GUIContent(EditorGUIUtility.FindTexture("FilterByLabel"), "Search by Label"); + public GUIContent m_FilterByType = new GUIContent(EditorGUIUtility.FindTexture("FilterByType"), "Search by Type"); + public GUIContent m_ShowChildAssetsContent = new GUIContent(string.Empty, EditorGUIUtility.FindTexture("UnityEditor.HierarchyWindow"), "Toggle visibility of child assets in folders"); + public GUIContent m_CreateDropdownContent = new GUIContent("Create"); + public GUIContent m_SaveFilterContent = new GUIContent(EditorGUIUtility.FindTexture("Favorite"), "Save search"); + public GUIContent m_EmptyFolderText = new GUIContent("This folder is empty"); + public GUIContent m_SearchIn = new GUIContent("Search:"); + private static GUIStyle GetStyle(string styleName) + { + return styleName; + } + } + internal class SavedFiltersContextMenu + { + private int m_SavedFilterInstanceID; + private SavedFiltersContextMenu(int savedFilterInstanceID) + { + this.m_SavedFilterInstanceID = savedFilterInstanceID; + } + internal static void Show(int savedFilterInstanceID) + { + GUIContent content = new GUIContent("Delete"); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction(new ProjectBrowser.SavedFiltersContextMenu(savedFilterInstanceID).Delete)); + genericMenu.ShowAsContext(); + } + private void Delete() + { + ProjectBrowser.DeleteFilter(this.m_SavedFilterInstanceID); + } + } + internal class BreadCrumbListMenu + { + private static ProjectBrowser m_Caller; + private string m_SubFolder; + private BreadCrumbListMenu(string subFolder) + { + this.m_SubFolder = subFolder; + } + public static List GetSubFolders(string folder) + { + if (Directory.Exists(folder)) + { + return new List(Directory.GetDirectories(folder)); + } + return new List(); + } + internal static void Show(string folder, string currentSubFolder, Rect activatorRect, ProjectBrowser caller) + { + ProjectBrowser.BreadCrumbListMenu.m_Caller = caller; + List subFolders = ProjectBrowser.BreadCrumbListMenu.GetSubFolders(folder); + GenericMenu genericMenu = new GenericMenu(); + if (subFolders.Count >= 0) + { + currentSubFolder = Path.GetFileName(currentSubFolder); + foreach (string current in subFolders) + { + string fileName = Path.GetFileName(current); + genericMenu.AddItem(new GUIContent(fileName), fileName == currentSubFolder, new GenericMenu.MenuFunction(new ProjectBrowser.BreadCrumbListMenu(current).SelectSubFolder)); + genericMenu.ShowAsContext(); + } + } + else + { + genericMenu.AddDisabledItem(new GUIContent("No sub folders...")); + } + genericMenu.DropDown(activatorRect); + } + private void SelectSubFolder() + { + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(this.m_SubFolder); + if (mainAssetInstanceID != 0) + { + ProjectBrowser.BreadCrumbListMenu.m_Caller.ShowFolderContents(mainAssetInstanceID, false); + } + } + } + internal class AssetStoreItemContextMenu + { + private AssetStoreItemContextMenu() + { + } + internal static void Show() + { + GenericMenu genericMenu = new GenericMenu(); + GUIContent content = new GUIContent("Show in Asset Store window"); + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset != null && firstAsset.id != 0) + { + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction(new ProjectBrowser.AssetStoreItemContextMenu().OpenAssetStoreWindow)); + } + else + { + genericMenu.AddDisabledItem(content); + } + genericMenu.ShowAsContext(); + } + private void OpenAssetStoreWindow() + { + AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset(); + if (firstAsset != null) + { + AssetStoreAssetInspector.OpenItemInAssetStore(firstAsset); + } + } + } + private const float k_MinHeight = 250f; + private const float k_MinWidthOneColumn = 230f; + private const float k_MinWidthTwoColumns = 230f; + private const float k_BottomBarHeight = 17f; + private const float k_ResizerWidth = 5f; + private const float k_SliderWidth = 55f; + private static List s_ProjectBrowsers = new List(); + public static ProjectBrowser s_LastInteractedProjectBrowser; + private static ProjectBrowser.Styles s_Styles; + private static int s_HashForSearchField = "ProjectBrowserSearchField".GetHashCode(); + [SerializeField] + private SearchFilter m_SearchFilter; + [NonSerialized] + private string m_SearchFieldText = string.Empty; + [SerializeField] + private ProjectBrowser.ViewMode m_ViewMode = ProjectBrowser.ViewMode.TwoColumns; + [SerializeField] + private int m_StartGridSize = 64; + [SerializeField] + private string[] m_LastFolders = new string[0]; + [SerializeField] + private float m_LastFoldersGridSize = -1f; + [SerializeField] + private string m_LastProjectPath; + [SerializeField] + private bool m_IsLocked; + private bool m_EnableOldAssetTree = true; + private bool m_FocusSearchField; + private string m_SelectedPath; + private List m_SelectedPathSplitted = new List(); + private float m_LastListWidth; + private int m_CurrentNumItems; + private bool m_DidSelectSearchResult; + private bool m_ItemSelectedByRightClickThisEvent; + private bool m_InternalSelectionChange; + private SearchFilter.SearchArea m_LastLocalAssetsSearchArea; + private PopupList.InputData m_AssetLabels; + private PopupList.InputData m_ObjectTypes; + private bool m_UseTreeViewSelectionInsteadOfMainSelection; + [SerializeField] + private TreeViewState m_FolderTreeState; + private TreeView m_FolderTree; + private int m_TreeViewKeyboardControlID; + [SerializeField] + private TreeViewState m_AssetTreeState; + private TreeView m_AssetTree; + [SerializeField] + private ObjectListAreaState m_ListAreaState; + private ObjectListArea m_ListArea; + private int m_ListKeyboardControlID; + private bool m_GrabKeyboardFocusForListArea; + private List> m_BreadCrumbs = new List>(); + private bool m_BreadCrumbLastFolderHasSubFolders; + private ExposablePopupMenu m_SearchAreaMenu; + private float m_ToolbarHeight; + private float k_MinDirectoriesAreaWidth = 110f; + [SerializeField] + private float m_DirectoriesAreaWidth = 115f; + [NonSerialized] + private float m_SearchAreaMenuOffset = -1f; + [NonSerialized] + private Rect m_ListAreaRect; + [NonSerialized] + private Rect m_TreeViewRect; + [NonSerialized] + private Rect m_BottomBarRect; + [NonSerialized] + private Rect m_ListHeaderRect; + [NonSerialized] + private int m_LastFramedID = -1; + [NonSerialized] + public GUIContent m_SearchAllAssets = new GUIContent("Assets"); + [NonSerialized] + public GUIContent m_SearchInFolders = new GUIContent(string.Empty); + [NonSerialized] + public GUIContent m_SearchAssetStore = new GUIContent("Asset Store"); + private bool useTreeViewSelectionInsteadOfMainSelection + { + get + { + return this.m_UseTreeViewSelectionInsteadOfMainSelection; + } + set + { + this.m_UseTreeViewSelectionInsteadOfMainSelection = value; + } + } + public float listAreaGridSize + { + get + { + return (float)this.m_ListArea.gridSize; + } + } + private ProjectBrowser() + { + } + public static List GetAllProjectBrowsers() + { + return ProjectBrowser.s_ProjectBrowsers; + } + private void OnEnable() + { + base.title = "Project"; + ProjectBrowser.s_ProjectBrowsers.Add(this); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnProjectChanged)); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + EditorApplication.assetLabelsChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.assetLabelsChanged, new EditorApplication.CallbackFunction(this.OnAssetLabelsChanged)); + ProjectBrowser.s_LastInteractedProjectBrowser = this; + } + private void OnDisable() + { + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnProjectChanged)); + EditorApplication.assetLabelsChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.assetLabelsChanged, new EditorApplication.CallbackFunction(this.OnAssetLabelsChanged)); + ProjectBrowser.s_ProjectBrowsers.Remove(this); + } + private void OnPlayModeStateChanged() + { + this.EndRenaming(); + } + private void OnAssetLabelsChanged() + { + if (this.Initialized()) + { + this.SetupAssetLabelList(); + } + } + private void Awake() + { + base.title = "Project"; + if (this.m_ListAreaState != null) + { + this.m_ListAreaState.OnAwake(); + } + if (this.m_FolderTreeState != null) + { + this.m_FolderTreeState.OnAwake(); + this.m_FolderTreeState.expandedIDs = new List(InternalEditorUtility.expandedProjectWindowItems); + } + if (this.m_AssetTreeState != null) + { + this.m_AssetTreeState.OnAwake(); + this.m_AssetTreeState.expandedIDs = new List(InternalEditorUtility.expandedProjectWindowItems); + } + Analytics.Event("ProjectBrowser", "StartLayout", this.m_ViewMode.ToString(), 1); + } + private string GetAnalyticsSizeLabel(float size) + { + if (size > 600f) + { + return "Larger than 600 pix"; + } + if (size < 240f) + { + return "Less than 240 pix"; + } + return "240 - 600 pix"; + } + internal static ProjectBrowser.ItemType GetItemType(int instanceID) + { + if (SavedSearchFilters.IsSavedFilter(instanceID)) + { + return ProjectBrowser.ItemType.SavedFilter; + } + return ProjectBrowser.ItemType.Asset; + } + internal string GetActiveFolderPath() + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && this.m_SearchFilter.folders.Length > 0) + { + return this.m_SearchFilter.folders[0]; + } + return "Assets"; + } + private void EnsureValidFolders() + { + HashSet hashSet = new HashSet(); + string[] folders = this.m_SearchFilter.folders; + for (int i = 0; i < folders.Length; i++) + { + string text = folders[i]; + if (Directory.Exists(text)) + { + hashSet.Add(text); + } + else + { + if (!string.IsNullOrEmpty(text)) + { + string text2 = text; + for (int j = 0; j < 30; j++) + { + text2 = Path.GetDirectoryName(text2); + if (!string.IsNullOrEmpty(text2) && Directory.Exists(text2)) + { + hashSet.Add(text2); + break; + } + } + } + } + } + this.m_SearchFilter.folders = hashSet.ToArray(); + } + private void OnProjectChanged() + { + if (this.m_AssetTree != null) + { + this.m_AssetTree.ReloadData(); + this.SetSearchFoldersFromCurrentSelection(); + } + if (this.m_FolderTree != null) + { + this.m_FolderTree.ReloadData(); + this.SetSearchFolderFromFolderTreeSelection(); + } + this.EnsureValidFolders(); + if (this.m_ListArea != null) + { + this.InitListArea(); + } + this.RefreshSelectedPath(); + this.m_BreadCrumbs.Clear(); + } + public bool Initialized() + { + return this.m_ListArea != null; + } + public void Init() + { + if (this.Initialized()) + { + return; + } + this.m_FocusSearchField = false; + bool flag = this.m_SearchFilter == null; + if (flag) + { + this.m_DirectoriesAreaWidth = Mathf.Min(base.position.width / 2f, 200f); + } + if (this.m_SearchFilter == null) + { + this.m_SearchFilter = new SearchFilter(); + } + this.m_SearchFieldText = this.m_SearchFilter.FilterToSearchFieldString(); + this.CalculateRects(); + this.RefreshSelectedPath(); + this.SetupDroplists(); + if (this.m_ListAreaState == null) + { + this.m_ListAreaState = new ObjectListAreaState(); + } + this.m_ListAreaState.m_RenameOverlay.isRenamingFilename = true; + this.m_ListArea = new ObjectListArea(this.m_ListAreaState, this, false); + this.m_ListArea.allowDeselection = true; + this.m_ListArea.allowDragging = true; + this.m_ListArea.allowFocusRendering = true; + this.m_ListArea.allowMultiSelect = true; + this.m_ListArea.allowRenaming = true; + this.m_ListArea.allowBuiltinResources = false; + this.m_ListArea.allowUserRenderingHook = true; + this.m_ListArea.allowFindNextShortcut = true; + this.m_ListArea.foldersFirst = this.GetShouldShowFoldersFirst(); + ObjectListArea expr_131 = this.m_ListArea; + expr_131.repaintCallback = (Action)Delegate.Combine(expr_131.repaintCallback, new Action(base.Repaint)); + ObjectListArea expr_158 = this.m_ListArea; + expr_158.itemSelectedCallback = (Action)Delegate.Combine(expr_158.itemSelectedCallback, new Action(this.ListAreaItemSelectedCallback)); + ObjectListArea expr_17F = this.m_ListArea; + expr_17F.keyboardCallback = (Action)Delegate.Combine(expr_17F.keyboardCallback, new Action(this.ListAreaKeyboardCallback)); + ObjectListArea expr_1A6 = this.m_ListArea; + expr_1A6.gotKeyboardFocus = (Action)Delegate.Combine(expr_1A6.gotKeyboardFocus, new Action(this.ListGotKeyboardFocus)); + ObjectListArea expr_1CD = this.m_ListArea; + expr_1CD.drawLocalAssetHeader = (Func)Delegate.Combine(expr_1CD.drawLocalAssetHeader, new Func(this.DrawLocalAssetHeader)); + ObjectListArea expr_1F4 = this.m_ListArea; + expr_1F4.assetStoreSearchEnded = (Action)Delegate.Combine(expr_1F4.assetStoreSearchEnded, new Action(this.AssetStoreSearchEndedCallback)); + this.m_ListArea.gridSize = this.m_StartGridSize; + this.m_StartGridSize = Mathf.Clamp(this.m_StartGridSize, this.m_ListArea.minGridSize, this.m_ListArea.maxGridSize); + this.m_LastFoldersGridSize = Mathf.Min(this.m_LastFoldersGridSize, (float)this.m_ListArea.maxGridSize); + this.InitListArea(); + this.SyncFilterGUI(); + if (this.m_FolderTreeState == null) + { + this.m_FolderTreeState = new TreeViewState(); + } + this.m_FolderTreeState.renameOverlay.isRenamingFilename = true; + if (this.m_AssetTreeState == null) + { + this.m_AssetTreeState = new TreeViewState(); + } + this.m_AssetTreeState.renameOverlay.isRenamingFilename = true; + this.InitViewMode(this.m_ViewMode); + this.m_SearchAreaMenu = new ExposablePopupMenu(); + this.RefreshSearchText(); + this.DefaultSetup(); + } + private void SetSearchViewState(ProjectBrowser.SearchViewState state) + { + switch (state) + { + case ProjectBrowser.SearchViewState.NotSearching: + Debug.LogError("Invalid search mode as setter"); + break; + case ProjectBrowser.SearchViewState.AllAssets: + this.m_SearchFilter.searchArea = SearchFilter.SearchArea.AllAssets; + break; + case ProjectBrowser.SearchViewState.SubFolders: + this.m_SearchFilter.searchArea = SearchFilter.SearchArea.SelectedFolders; + break; + case ProjectBrowser.SearchViewState.AssetStore: + this.m_SearchFilter.searchArea = SearchFilter.SearchArea.AssetStore; + break; + } + this.InitSearchMenu(); + this.InitListArea(); + } + private ProjectBrowser.SearchViewState GetSearchViewState() + { + switch (this.m_SearchFilter.GetState()) + { + case SearchFilter.State.SearchingInAllAssets: + return ProjectBrowser.SearchViewState.AllAssets; + case SearchFilter.State.SearchingInFolders: + return ProjectBrowser.SearchViewState.SubFolders; + case SearchFilter.State.SearchingInAssetStore: + return ProjectBrowser.SearchViewState.AssetStore; + default: + return ProjectBrowser.SearchViewState.NotSearching; + } + } + private void SearchButtonClickedCallback(ExposablePopupMenu.ItemData itemClicked) + { + if (!itemClicked.m_On) + { + this.SetSearchViewState((ProjectBrowser.SearchViewState)((int)itemClicked.m_UserData)); + if (this.m_SearchFilter.searchArea == SearchFilter.SearchArea.AllAssets || this.m_SearchFilter.searchArea == SearchFilter.SearchArea.SelectedFolders) + { + this.m_LastLocalAssetsSearchArea = this.m_SearchFilter.searchArea; + } + Analytics.Event("ProjectBrowser", "UserChangedSearchArea", this.m_SearchFilter.searchArea.ToString(), 1); + } + } + private void InitSearchMenu() + { + ProjectBrowser.SearchViewState searchViewState = this.GetSearchViewState(); + if (searchViewState == ProjectBrowser.SearchViewState.NotSearching) + { + return; + } + List list = new List(); + GUIStyle gUIStyle = "ExposablePopupItem"; + GUIStyle gUIStyle2 = "ExposablePopupItem"; + bool enabled = this.m_SearchFilter.folders.Length > 0; + this.m_SearchAssetStore.text = this.m_ListArea.GetAssetStoreButtonText(); + bool flag = searchViewState == ProjectBrowser.SearchViewState.AllAssets; + list.Add(new ExposablePopupMenu.ItemData(this.m_SearchAllAssets, (!flag) ? gUIStyle2 : gUIStyle, flag, true, 1)); + flag = (searchViewState == ProjectBrowser.SearchViewState.SubFolders); + list.Add(new ExposablePopupMenu.ItemData(this.m_SearchInFolders, (!flag) ? gUIStyle2 : gUIStyle, flag, enabled, 2)); + flag = (searchViewState == ProjectBrowser.SearchViewState.AssetStore); + list.Add(new ExposablePopupMenu.ItemData(this.m_SearchAssetStore, (!flag) ? gUIStyle2 : gUIStyle, flag, true, 3)); + GUIContent content = this.m_SearchAllAssets; + switch (searchViewState) + { + case ProjectBrowser.SearchViewState.NotSearching: + content = this.m_SearchAssetStore; + break; + case ProjectBrowser.SearchViewState.AllAssets: + content = this.m_SearchAllAssets; + break; + case ProjectBrowser.SearchViewState.SubFolders: + content = this.m_SearchInFolders; + break; + case ProjectBrowser.SearchViewState.AssetStore: + content = this.m_SearchAssetStore; + break; + default: + Debug.LogError("Unhandled enum"); + break; + } + ExposablePopupMenu.PopupButtonData popupButtonData = new ExposablePopupMenu.PopupButtonData(content, ProjectBrowser.s_Styles.exposablePopup); + this.m_SearchAreaMenu.Init(list, 10f, 450f, popupButtonData, new Action(this.SearchButtonClickedCallback)); + } + private void AssetStoreSearchEndedCallback() + { + this.InitSearchMenu(); + } + public static void ShowAssetStoreHitsWhileSearchingLocalAssetsChanged() + { + foreach (ProjectBrowser current in ProjectBrowser.s_ProjectBrowsers) + { + current.m_ListArea.ShowAssetStoreHitCountWhileSearchingLocalAssetsChanged(); + current.InitSearchMenu(); + } + } + private void RefreshSearchText() + { + if (this.m_SearchFilter.folders.Length > 0) + { + string[] baseFolders = ProjectWindowUtil.GetBaseFolders(this.m_SearchFilter.folders); + string text = string.Empty; + string tooltip = string.Empty; + int num = 3; + int num2 = 0; + while (num2 < baseFolders.Length && num2 < num) + { + if (num2 > 0) + { + text += ", "; + } + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(baseFolders[num2]); + text = text + "'" + fileNameWithoutExtension + "'"; + if (num2 == 0 && fileNameWithoutExtension != "Assets") + { + tooltip = baseFolders[num2]; + } + num2++; + } + if (baseFolders.Length > num) + { + text += " +"; + } + this.m_SearchInFolders.text = text; + this.m_SearchInFolders.tooltip = tooltip; + } + else + { + this.m_SearchInFolders.text = "Selected folder"; + this.m_SearchInFolders.tooltip = string.Empty; + } + this.m_BreadCrumbs.Clear(); + this.InitSearchMenu(); + } + private void DefaultSetup() + { + if (this.m_LastProjectPath != Directory.GetCurrentDirectory()) + { + this.m_SearchFilter = new SearchFilter(); + this.m_LastFolders = new string[0]; + this.SyncFilterGUI(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.SelectAssetsFolder(); + } + } + this.m_LastProjectPath = Directory.GetCurrentDirectory(); + } + private void OnGUIAssetCallback(int instanceID, Rect rect) + { + if (EditorApplication.projectWindowItemOnGUI != null) + { + string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(instanceID)); + EditorApplication.projectWindowItemOnGUI(guid, rect); + } + } + private void InitViewMode(ProjectBrowser.ViewMode viewMode) + { + this.m_ViewMode = viewMode; + this.m_FolderTree = null; + this.m_AssetTree = null; + this.useTreeViewSelectionInsteadOfMainSelection = false; + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + this.m_AssetTree = new TreeView(this, this.m_AssetTreeState); + this.m_AssetTree.deselectOnUnhandledMouseDown = true; + TreeView expr_4B = this.m_AssetTree; + expr_4B.selectionChangedCallback = (Action)Delegate.Combine(expr_4B.selectionChangedCallback, new Action(this.AssetTreeSelectionCallback)); + TreeView expr_72 = this.m_AssetTree; + expr_72.keyboardInputCallback = (Action)Delegate.Combine(expr_72.keyboardInputCallback, new Action(this.AssetTreeKeyboardInputCallback)); + TreeView expr_99 = this.m_AssetTree; + expr_99.contextClickCallback = (Action)Delegate.Combine(expr_99.contextClickCallback, new Action(this.AssetTreeViewContextClick)); + TreeView expr_C0 = this.m_AssetTree; + expr_C0.itemDoubleClickedCallback = (Action)Delegate.Combine(expr_C0.itemDoubleClickedCallback, new Action(this.AssetTreeItemDoubleClickedCallback)); + TreeView expr_E7 = this.m_AssetTree; + expr_E7.onGUIRowCallback = (Action)Delegate.Combine(expr_E7.onGUIRowCallback, new Action(this.OnGUIAssetCallback)); + TreeView expr_10E = this.m_AssetTree; + expr_10E.dragEndedCallback = (Action)Delegate.Combine(expr_10E.dragEndedCallback, new Action(this.AssetTreeDragEnded)); + string guid = AssetDatabase.AssetPathToGUID("Assets"); + AssetsTreeViewDataSource assetsTreeViewDataSource = new AssetsTreeViewDataSource(this.m_AssetTree, AssetDatabase.GetInstanceIDFromGUID(guid), false, false); + assetsTreeViewDataSource.foldersFirst = this.GetShouldShowFoldersFirst(); + this.m_AssetTree.Init(this.m_TreeViewRect, assetsTreeViewDataSource, new AssetsTreeViewGUI(this.m_AssetTree), new AssetOrGameObjectTreeViewDragging(this.m_AssetTree, HierarchyType.Assets)); + this.m_AssetTree.ReloadData(); + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.m_FolderTree = new TreeView(this, this.m_FolderTreeState); + this.m_FolderTree.deselectOnUnhandledMouseDown = false; + TreeView expr_1C3 = this.m_FolderTree; + expr_1C3.selectionChangedCallback = (Action)Delegate.Combine(expr_1C3.selectionChangedCallback, new Action(this.FolderTreeSelectionCallback)); + TreeView expr_1EA = this.m_FolderTree; + expr_1EA.contextClickCallback = (Action)Delegate.Combine(expr_1EA.contextClickCallback, new Action(this.FolderTreeViewContextClick)); + TreeView expr_211 = this.m_FolderTree; + expr_211.onGUIRowCallback = (Action)Delegate.Combine(expr_211.onGUIRowCallback, new Action(this.OnGUIAssetCallback)); + TreeView expr_238 = this.m_FolderTree; + expr_238.dragEndedCallback = (Action)Delegate.Combine(expr_238.dragEndedCallback, new Action(this.FolderTreeDragEnded)); + this.m_FolderTree.Init(this.m_TreeViewRect, new ProjectBrowserColumnOneTreeViewDataSource(this.m_FolderTree), new ProjectBrowserColumnOneTreeViewGUI(this.m_FolderTree), new ProjectBrowserColumnOneTreeViewDragging(this.m_FolderTree)); + this.m_FolderTree.ReloadData(); + } + } + float x = (this.m_ViewMode != ProjectBrowser.ViewMode.OneColumn) ? 230f : 230f; + base.minSize = new Vector2(x, 250f); + base.maxSize = new Vector2(10000f, 10000f); + } + private bool GetShouldShowFoldersFirst() + { + return Application.platform != RuntimePlatform.OSXEditor; + } + private void SetViewMode(ProjectBrowser.ViewMode newViewMode) + { + if (this.m_ViewMode == newViewMode) + { + return; + } + this.EndRenaming(); + this.InitViewMode((this.m_ViewMode != ProjectBrowser.ViewMode.OneColumn) ? ProjectBrowser.ViewMode.OneColumn : ProjectBrowser.ViewMode.TwoColumns); + if (Selection.activeInstanceID != 0) + { + this.FrameObjectPrivate(Selection.activeInstanceID, !this.m_IsLocked, false); + } + base.RepaintImmediately(); + } + private void EndRenaming() + { + if (this.m_AssetTree != null) + { + this.m_AssetTree.EndNameEditing(true); + } + if (this.m_FolderTree != null) + { + this.m_FolderTree.EndNameEditing(true); + } + if (this.m_ListArea != null) + { + this.m_ListArea.EndRename(true); + } + } + private string[] GetTypesDisplayNames() + { + return new string[] + { + "AnimationClip", + "AudioClip", + "Font", + "GUISkin", + "Material", + "Mesh", + "Model", + "PhysicMaterial", + "Prefab", + "Scene", + "Script", + "Shader", + "Sprite", + "Texture" + }; + } + public void TypeListCallback(PopupList.ListElement element) + { + if (!Event.current.control) + { + foreach (PopupList.ListElement current in this.m_ObjectTypes.m_ListElements) + { + if (current != element) + { + current.selected = false; + } + } + } + element.selected = !element.selected; + string[] array = ( + from item in this.m_ObjectTypes.m_ListElements + where item.selected + select item.text).ToArray(); + for (int i = 0; i < array.Length; i++) + { + array[i] = array[i]; + } + this.m_SearchFilter.classNames = array; + this.m_SearchFieldText = this.m_SearchFilter.FilterToSearchFieldString(); + this.TopBarSearchSettingsChanged(); + base.Repaint(); + } + public void AssetLabelListCallback(PopupList.ListElement element) + { + if (!Event.current.control) + { + foreach (PopupList.ListElement current in this.m_AssetLabels.m_ListElements) + { + if (current != element) + { + current.selected = false; + } + } + } + element.selected = !element.selected; + this.m_SearchFilter.assetLabels = ( + from item in this.m_AssetLabels.m_ListElements + where item.selected + select item.text).ToArray(); + this.m_SearchFieldText = this.m_SearchFilter.FilterToSearchFieldString(); + this.TopBarSearchSettingsChanged(); + base.Repaint(); + } + private void SetupDroplists() + { + this.SetupAssetLabelList(); + this.m_ObjectTypes = new PopupList.InputData(); + this.m_ObjectTypes.m_CloseOnSelection = false; + this.m_ObjectTypes.m_AllowCustom = false; + this.m_ObjectTypes.m_OnSelectCallback = new PopupList.OnSelectCallback(this.TypeListCallback); + this.m_ObjectTypes.m_SortAlphabetically = false; + this.m_ObjectTypes.m_MaxCount = 0; + string[] typesDisplayNames = this.GetTypesDisplayNames(); + for (int i = 0; i < typesDisplayNames.Length; i++) + { + PopupList.ListElement listElement = this.m_ObjectTypes.NewOrMatchingElement(typesDisplayNames[i]); + if (i == 0) + { + listElement.selected = true; + } + } + } + private void SetupAssetLabelList() + { + Dictionary allLabels = AssetDatabase.GetAllLabels(); + this.m_AssetLabels = new PopupList.InputData(); + this.m_AssetLabels.m_CloseOnSelection = false; + this.m_AssetLabels.m_AllowCustom = true; + this.m_AssetLabels.m_OnSelectCallback = new PopupList.OnSelectCallback(this.AssetLabelListCallback); + this.m_AssetLabels.m_MaxCount = 15; + this.m_AssetLabels.m_SortAlphabetically = true; + foreach (KeyValuePair current in allLabels) + { + PopupList.ListElement listElement = this.m_AssetLabels.NewOrMatchingElement(current.Key); + if (listElement.filterScore < current.Value) + { + listElement.filterScore = current.Value; + } + } + } + private void SyncFilterGUI() + { + List list = new List(this.m_SearchFilter.assetLabels); + foreach (PopupList.ListElement current in this.m_AssetLabels.m_ListElements) + { + current.selected = list.Contains(current.text); + } + List list2 = new List(this.m_SearchFilter.classNames); + foreach (PopupList.ListElement current2 in this.m_ObjectTypes.m_ListElements) + { + current2.selected = list2.Contains(current2.text); + } + this.m_SearchFieldText = this.m_SearchFilter.FilterToSearchFieldString(); + } + private static int GetParentInstanceID(int objectInstanceID) + { + string assetPath = AssetDatabase.GetAssetPath(objectInstanceID); + int num = assetPath.LastIndexOf("/"); + if (num >= 0) + { + string assetPath2 = assetPath.Substring(0, num); + UnityEngine.Object @object = AssetDatabase.LoadAssetAtPath(assetPath2, typeof(UnityEngine.Object)); + if (@object != null) + { + return @object.GetInstanceID(); + } + } + else + { + Debug.LogError("Invalid path: " + assetPath); + } + return -1; + } + public static bool IsFolder(int instanceID) + { + if (instanceID == 0) + { + return false; + } + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + return hierarchyProperty.Find(instanceID, null) && hierarchyProperty.isFolder; + } + private bool IsShowingFolder(int folderInstanceID) + { + string assetPath = AssetDatabase.GetAssetPath(folderInstanceID); + return new List(this.m_SearchFilter.folders).Contains(assetPath); + } + private void ShowFolderContents(int folderInstanceID, bool revealAndFrameInFolderTree) + { + if (this.m_ViewMode != ProjectBrowser.ViewMode.TwoColumns) + { + Debug.LogError("ShowFolderContents should only be called in two column mode"); + } + if (folderInstanceID == 0) + { + return; + } + string assetPath = AssetDatabase.GetAssetPath(folderInstanceID); + this.m_SearchFilter.ClearSearch(); + this.m_SearchFilter.folders = new string[] + { + assetPath + }; + this.m_FolderTree.SetSelection(new int[] + { + folderInstanceID + }, revealAndFrameInFolderTree); + this.FolderTreeSelectionChanged(true); + } + private bool IsShowingFolderContents() + { + return this.m_SearchFilter.folders.Length > 0; + } + private void ListGotKeyboardFocus() + { + } + private void ListAreaKeyboardCallback() + { + if (Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_56; + case KeyCode.KeypadEquals: + IL_37: + if (keyCode == KeyCode.Backspace) + { + if (Application.platform == RuntimePlatform.WindowsEditor && this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.ShowParentFolderOfCurrentlySelected(); + Event.current.Use(); + } + return; + } + if (keyCode == KeyCode.Return) + { + goto IL_56; + } + if (keyCode != KeyCode.F2) + { + return; + } + if (Application.platform == RuntimePlatform.WindowsEditor && this.m_ListArea.BeginRename(0f)) + { + Event.current.Use(); + } + return; + case KeyCode.UpArrow: + if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command && this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.ShowParentFolderOfCurrentlySelected(); + Event.current.Use(); + } + return; + case KeyCode.DownArrow: + if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) + { + Event.current.Use(); + this.OpenListAreaSelection(); + } + return; + } + goto IL_37; + IL_56: + if (Application.platform == RuntimePlatform.OSXEditor) + { + if (this.m_ListArea.BeginRename(0f)) + { + Event.current.Use(); + } + } + else + { + Event.current.Use(); + this.OpenListAreaSelection(); + } + } + } + private void ShowParentFolderOfCurrentlySelected() + { + if (this.IsShowingFolderContents()) + { + int[] selection = this.m_FolderTree.GetSelection(); + if (selection.Length == 1) + { + TreeViewItem treeViewItem = this.m_FolderTree.FindNode(selection[0]); + if (treeViewItem != null && treeViewItem.parent != null && treeViewItem.id != ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID()) + { + this.SetFolderSelection(new int[] + { + treeViewItem.parent.id + }, true); + this.m_ListArea.Frame(treeViewItem.id, true, false); + Selection.activeInstanceID = treeViewItem.id; + } + } + } + } + private void OpenListAreaSelection() + { + int[] selection = this.m_ListArea.GetSelection(); + int num = selection.Length; + if (num > 0) + { + int num2 = 0; + int[] array = selection; + for (int i = 0; i < array.Length; i++) + { + int instanceID = array[i]; + if (ProjectBrowser.IsFolder(instanceID)) + { + num2++; + } + } + bool flag = num2 == num; + if (flag) + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.SetFolderSelection(selection, false); + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + this.ClearSearch(); + this.m_AssetTree.Frame(selection[0], true, false); + } + } + base.Repaint(); + GUIUtility.ExitGUI(); + } + else + { + ProjectBrowser.OpenAssetSelection(selection); + base.Repaint(); + GUIUtility.ExitGUI(); + } + } + } + private static void OpenAssetSelection(int[] selectedInstanceIDs) + { + for (int i = 0; i < selectedInstanceIDs.Length; i++) + { + int instanceID = selectedInstanceIDs[i]; + if (AssetDatabase.Contains(instanceID)) + { + AssetDatabase.OpenAsset(instanceID); + } + } + GUIUtility.ExitGUI(); + } + private void SetAsLastInteractedProjectBrowser() + { + ProjectBrowser.s_LastInteractedProjectBrowser = this; + } + private void RefreshSelectedPath() + { + if (Selection.activeObject != null) + { + this.m_SelectedPath = AssetDatabase.GetAssetPath(Selection.activeObject); + } + else + { + this.m_SelectedPath = string.Empty; + } + this.m_SelectedPathSplitted.Clear(); + } + private void ListAreaItemSelectedCallback(bool doubleClicked) + { + this.SetAsLastInteractedProjectBrowser(); + Selection.activeObject = null; + int[] selection = this.m_ListArea.GetSelection(); + if (selection.Length > 0) + { + Selection.instanceIDs = selection; + this.m_SearchFilter.searchArea = this.m_LastLocalAssetsSearchArea; + this.m_InternalSelectionChange = true; + } + else + { + if (AssetStoreAssetSelection.Count > 0) + { + Selection.activeObject = AssetStoreAssetInspector.Instance; + } + } + this.m_FocusSearchField = false; + if (Event.current.button == 1 && Event.current.type == EventType.MouseDown) + { + this.m_ItemSelectedByRightClickThisEvent = true; + } + this.RefreshSelectedPath(); + this.m_DidSelectSearchResult = this.m_SearchFilter.IsSearching(); + if (doubleClicked) + { + this.OpenListAreaSelection(); + } + } + private int GetParentFolderInstanceID(int instanceID) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, null)) + { + while (hierarchyProperty.Parent()) + { + if (hierarchyProperty.isFolder) + { + return hierarchyProperty.instanceID; + } + } + } + return ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); + } + private void OnGotFocus() + { + } + private void OnLostFocus() + { + this.EndRenaming(); + EditorGUI.EndEditingActiveTextField(); + } + private void OnSelectionChange() + { + if (this.m_ListArea == null) + { + return; + } + this.m_ListArea.InitSelection(Selection.instanceIDs); + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + bool revealSelectionAndFrameLastSelected = !this.m_IsLocked; + this.m_AssetTree.SetSelection(Selection.instanceIDs, revealSelectionAndFrameLastSelected); + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && !this.m_InternalSelectionChange) + { + bool flag = !this.m_IsLocked && Selection.instanceIDs.Length > 0; + if (flag) + { + int instanceID = Selection.instanceIDs[Selection.instanceIDs.Length - 1]; + if (this.m_SearchFilter.IsSearching()) + { + this.m_ListArea.Frame(instanceID, true, false); + } + else + { + if (flag) + { + this.FrameObjectPrivate(instanceID, true, false); + } + } + } + } + } + this.m_InternalSelectionChange = false; + if (Selection.activeObject != null && Selection.activeObject.GetType() != typeof(AssetStoreAssetInspector)) + { + this.m_ListArea.selectedAssetStoreAsset = false; + AssetStoreAssetSelection.Clear(); + } + this.RefreshSelectedPath(); + base.Repaint(); + } + private void SetFoldersInSearchFilter(int[] selectedInstanceIDs) + { + this.m_SearchFilter.folders = ProjectBrowser.GetFolderPathsFromInstanceIDs(selectedInstanceIDs); + this.EnsureValidFolders(); + if (selectedInstanceIDs.Length > 0 && this.m_LastFoldersGridSize > 0f) + { + this.m_ListArea.gridSize = (int)this.m_LastFoldersGridSize; + } + } + private void SetFolderSelection(int[] selectedInstanceIDs, bool revealSelectionAndFrameLastSelected) + { + this.m_FolderTree.SetSelection(selectedInstanceIDs, revealSelectionAndFrameLastSelected); + this.SetFoldersInSearchFilter(selectedInstanceIDs); + this.FolderTreeSelectionChanged(true); + } + private void AssetTreeItemDoubleClickedCallback(int instanceID) + { + ProjectBrowser.OpenAssetSelection(Selection.instanceIDs); + } + private void AssetTreeKeyboardInputCallback() + { + if (Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_44; + case KeyCode.KeypadEquals: + case KeyCode.UpArrow: + IL_37: + if (keyCode != KeyCode.Return) + { + return; + } + goto IL_44; + case KeyCode.DownArrow: + if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) + { + Event.current.Use(); + ProjectBrowser.OpenAssetSelection(Selection.instanceIDs); + } + return; + } + goto IL_37; + IL_44: + if (Application.platform == RuntimePlatform.WindowsEditor) + { + Event.current.Use(); + ProjectBrowser.OpenAssetSelection(Selection.instanceIDs); + } + } + } + private void AssetTreeSelectionCallback(int[] selectedTreeViewInstanceIDs) + { + this.SetAsLastInteractedProjectBrowser(); + Selection.activeObject = null; + if (selectedTreeViewInstanceIDs.Length > 0) + { + Selection.instanceIDs = selectedTreeViewInstanceIDs; + } + this.RefreshSelectedPath(); + this.SetSearchFoldersFromCurrentSelection(); + this.RefreshSearchText(); + } + private void SetSearchFoldersFromCurrentSelection() + { + HashSet hashSet = new HashSet(); + int[] instanceIDs = Selection.instanceIDs; + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, null)) + { + int num = 0; + while (hierarchyProperty.isValid && !hierarchyProperty.isFolder && num++ < 3) + { + hierarchyProperty.Parent(); + } + if (hierarchyProperty.isValid && hierarchyProperty.isFolder) + { + hashSet.Add(AssetDatabase.GetAssetPath(hierarchyProperty.instanceID)); + } + } + } + this.m_SearchFilter.folders = ProjectWindowUtil.GetBaseFolders(hashSet.ToArray()); + } + private void SetSearchFolderFromFolderTreeSelection() + { + if (this.m_FolderTree != null) + { + this.m_SearchFilter.folders = ProjectBrowser.GetFolderPathsFromInstanceIDs(this.m_FolderTree.GetSelection()); + } + } + private void FolderTreeSelectionCallback(int[] selectedTreeViewInstanceIDs) + { + this.SetAsLastInteractedProjectBrowser(); + int num = 0; + if (selectedTreeViewInstanceIDs.Length > 0) + { + num = selectedTreeViewInstanceIDs[0]; + } + bool folderWasSelected = false; + if (num != 0) + { + ProjectBrowser.ItemType itemType = ProjectBrowser.GetItemType(num); + if (itemType == ProjectBrowser.ItemType.Asset) + { + this.SetFoldersInSearchFilter(selectedTreeViewInstanceIDs); + folderWasSelected = true; + } + if (itemType == ProjectBrowser.ItemType.SavedFilter) + { + SearchFilter filter = SavedSearchFilters.GetFilter(num); + if (this.ValidateFilter(num, filter)) + { + this.m_SearchFilter = filter; + this.EnsureValidFolders(); + float previewSize = SavedSearchFilters.GetPreviewSize(num); + if (previewSize > 0f) + { + this.m_ListArea.gridSize = Mathf.Clamp((int)previewSize, this.m_ListArea.minGridSize, this.m_ListArea.maxGridSize); + } + this.SyncFilterGUI(); + } + } + } + this.FolderTreeSelectionChanged(folderWasSelected); + } + private bool ValidateFilter(int savedFilterID, SearchFilter filter) + { + if (filter == null) + { + return false; + } + SearchFilter.State state = filter.GetState(); + if (state == SearchFilter.State.FolderBrowsing || state == SearchFilter.State.SearchingInFolders) + { + string[] folders = filter.folders; + for (int i = 0; i < folders.Length; i++) + { + string text = folders[i]; + if (AssetDatabase.GetMainAssetInstanceID(text) == 0) + { + if (EditorUtility.DisplayDialog("Folder not found", "The folder '" + text + "' might have been deleted or belong to another project. Do you want to delete the favorite?", "Delete", "Cancel")) + { + SavedSearchFilters.RemoveSavedFilter(savedFilterID); + } + return false; + } + } + } + return true; + } + private void ShowAndHideFolderTreeSelectionAsNeeded() + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && this.m_FolderTree != null) + { + bool flag = false; + int[] selection = this.m_FolderTree.GetSelection(); + if (selection.Length > 0) + { + flag = (ProjectBrowser.GetItemType(selection[0]) == ProjectBrowser.ItemType.SavedFilter); + } + switch (this.GetSearchViewState()) + { + case ProjectBrowser.SearchViewState.NotSearching: + case ProjectBrowser.SearchViewState.SubFolders: + if (!flag) + { + this.m_FolderTree.SetSelection(ProjectBrowser.GetFolderInstanceIDs(this.m_SearchFilter.folders), true); + } + break; + case ProjectBrowser.SearchViewState.AllAssets: + case ProjectBrowser.SearchViewState.AssetStore: + if (!flag) + { + this.m_FolderTree.SetSelection(new int[0], false); + } + break; + } + } + } + private void InitListArea() + { + this.ShowAndHideFolderTreeSelectionAsNeeded(); + this.m_ListArea.Init(this.m_ListAreaRect, HierarchyType.Assets, this.m_SearchFilter, false); + this.m_ListArea.InitSelection(Selection.instanceIDs); + } + private void OnInspectorUpdate() + { + if (this.m_ListArea != null) + { + this.m_ListArea.OnInspectorUpdate(); + } + } + private void OnDestroy() + { + if (this.m_ListArea != null) + { + this.m_ListArea.OnDestroy(); + } + if (this == ProjectBrowser.s_LastInteractedProjectBrowser) + { + ProjectBrowser.s_LastInteractedProjectBrowser = null; + } + } + private static List GetMainPaths(List instanceIDs) + { + List list = new List(); + foreach (int current in instanceIDs) + { + if (AssetDatabase.IsMainAsset(current)) + { + string assetPath = AssetDatabase.GetAssetPath(current); + list.Add(assetPath); + } + } + return list; + } + internal static int[] DuplicateFolders(int[] instanceIDs) + { + AssetDatabase.Refresh(); + List list = new List(); + bool flag = false; + int assetsFolderInstanceID = ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); + for (int i = 0; i < instanceIDs.Length; i++) + { + int num = instanceIDs[i]; + if (num != assetsFolderInstanceID) + { + string assetPath = AssetDatabase.GetAssetPath(InternalEditorUtility.GetObjectFromInstanceID(num)); + string text = AssetDatabase.GenerateUniqueAssetPath(assetPath); + if (text.Length != 0) + { + flag |= !AssetDatabase.CopyAsset(assetPath, text); + } + else + { + flag |= true; + } + if (!flag) + { + list.Add(text); + } + } + } + AssetDatabase.Refresh(); + int[] array = new int[list.Count]; + for (int j = 0; j < list.Count; j++) + { + array[j] = AssetDatabase.LoadMainAssetAtPath(list[j]).GetInstanceID(); + } + return array; + } + private static void DeleteFilter(int filterInstanceID) + { + if (SavedSearchFilters.GetRootInstanceID() == filterInstanceID) + { + string title = "Cannot Delete"; + EditorUtility.DisplayDialog(title, "Deleting the 'Filters' root is not allowed", "Ok"); + } + else + { + string title2 = "Delete selected favorite?"; + if (EditorUtility.DisplayDialog(title2, "You cannot undo this action.", "Delete", "Cancel")) + { + SavedSearchFilters.RemoveSavedFilter(filterInstanceID); + } + } + } + private bool HandleCommandEventsForTreeView() + { + EventType type = Event.current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + int[] selection = this.m_FolderTree.GetSelection(); + if (selection.Length == 0) + { + return false; + } + ProjectBrowser.ItemType itemType = ProjectBrowser.GetItemType(selection[0]); + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + Event.current.Use(); + if (flag) + { + if (itemType == ProjectBrowser.ItemType.SavedFilter) + { + Assert.That(selection.Length == 1); + ProjectBrowser.DeleteFilter(selection[0]); + } + else + { + if (itemType == ProjectBrowser.ItemType.Asset) + { + bool flag2 = Event.current.commandName == "SoftDelete"; + ProjectBrowser.DeleteSelectedAssets(flag2); + if (flag2) + { + base.Focus(); + } + } + } + } + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Duplicate") + { + if (flag) + { + if (itemType != ProjectBrowser.ItemType.SavedFilter) + { + if (itemType == ProjectBrowser.ItemType.Asset) + { + Event.current.Use(); + int[] selectedIDs = ProjectBrowser.DuplicateFolders(selection); + this.m_FolderTree.SetSelection(selectedIDs, true); + GUIUtility.ExitGUI(); + } + } + } + else + { + Event.current.Use(); + } + } + } + } + return false; + } + private bool HandleCommandEvents() + { + EventType type = Event.current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + Event.current.Use(); + if (flag) + { + bool flag2 = Event.current.commandName == "SoftDelete"; + ProjectBrowser.DeleteSelectedAssets(flag2); + if (flag2) + { + base.Focus(); + } + } + GUIUtility.ExitGUI(); + } + else + { + if (Event.current.commandName == "Duplicate") + { + if (flag) + { + Event.current.Use(); + BaseProjectWindow.DuplicateSelectedAssets(); + GUIUtility.ExitGUI(); + } + else + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + if (filtered.Length != 0) + { + Event.current.Use(); + } + } + } + else + { + if (Event.current.commandName == "FocusProjectWindow") + { + if (flag) + { + this.FrameObjectPrivate(Selection.activeInstanceID, true, false); + Event.current.Use(); + base.Focus(); + GUIUtility.ExitGUI(); + } + else + { + Event.current.Use(); + } + } + else + { + if (Event.current.commandName == "SelectAll") + { + if (flag) + { + this.SelectAll(); + } + Event.current.Use(); + } + else + { + if (Event.current.commandName == "FrameSelected") + { + if (flag) + { + this.FrameObjectPrivate(Selection.activeInstanceID, true, false); + Event.current.Use(); + GUIUtility.ExitGUI(); + } + Event.current.Use(); + } + else + { + if (Event.current.commandName == "Find") + { + if (flag) + { + this.m_FocusSearchField = true; + } + Event.current.Use(); + } + } + } + } + } + } + } + return false; + } + private void SelectAll() + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + if (this.m_SearchFilter.IsSearching()) + { + this.m_ListArea.SelectAll(); + } + else + { + int[] visibleRowIDs = this.m_AssetTree.GetVisibleRowIDs(); + this.m_AssetTree.SetSelection(visibleRowIDs, false); + this.AssetTreeSelectionCallback(visibleRowIDs); + } + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.m_ListArea.SelectAll(); + } + else + { + Debug.LogError("Missing implementation for ViewMode " + this.m_ViewMode); + } + } + } + private void RefreshSplittedSelectedPath() + { + if (ProjectBrowser.s_Styles == null) + { + ProjectBrowser.s_Styles = new ProjectBrowser.Styles(); + } + this.m_SelectedPathSplitted.Clear(); + if (string.IsNullOrEmpty(this.m_SelectedPath)) + { + this.m_SelectedPathSplitted.Add(new GUIContent()); + } + else + { + string text = this.m_SelectedPath; + if (this.m_SelectedPath.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) + { + text = this.m_SelectedPath.Substring("assets/".Length); + } + if (this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing) + { + this.m_SelectedPathSplitted.Add(new GUIContent(Path.GetFileName(this.m_SelectedPath), AssetDatabase.GetCachedIcon(this.m_SelectedPath))); + } + else + { + float num = base.position.width - this.m_DirectoriesAreaWidth - 55f - 16f; + if (ProjectBrowser.s_Styles.selectedPathLabel.CalcSize(GUIContent.Temp(text)).x + 25f > num) + { + string[] array = text.Split(new char[] + { + '/' + }); + string text2 = "Assets/"; + for (int i = 0; i < array.Length; i++) + { + text2 += array[i]; + Texture cachedIcon = AssetDatabase.GetCachedIcon(text2); + this.m_SelectedPathSplitted.Add(new GUIContent(array[i], cachedIcon)); + text2 += "/"; + } + } + else + { + this.m_SelectedPathSplitted.Add(new GUIContent(text, AssetDatabase.GetCachedIcon(this.m_SelectedPath))); + } + } + } + } + private float GetBottomBarHeight() + { + if (this.m_SelectedPathSplitted.Count == 0) + { + this.RefreshSplittedSelectedPath(); + } + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn && !this.m_SearchFilter.IsSearching()) + { + return 0f; + } + return 17f * (float)this.m_SelectedPathSplitted.Count; + } + private float GetListHeaderHeight() + { + return (this.m_SearchFilter.GetState() != SearchFilter.State.EmptySearchFilter) ? 18f : 0f; + } + private void CalculateRects() + { + float bottomBarHeight = this.GetBottomBarHeight(); + float listHeaderHeight = this.GetListHeaderHeight(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + this.m_ListAreaRect = new Rect(0f, this.m_ToolbarHeight + listHeaderHeight, base.position.width, base.position.height - this.m_ToolbarHeight - listHeaderHeight - bottomBarHeight); + this.m_TreeViewRect = new Rect(0f, this.m_ToolbarHeight, base.position.width, base.position.height - this.m_ToolbarHeight - bottomBarHeight); + this.m_BottomBarRect = new Rect(0f, base.position.height - bottomBarHeight, base.position.width, bottomBarHeight); + this.m_ListHeaderRect = new Rect(0f, this.m_ToolbarHeight, base.position.width, listHeaderHeight); + } + else + { + float width = base.position.width - this.m_DirectoriesAreaWidth; + this.m_ListAreaRect = new Rect(this.m_DirectoriesAreaWidth, this.m_ToolbarHeight + listHeaderHeight, width, base.position.height - this.m_ToolbarHeight - listHeaderHeight - bottomBarHeight); + this.m_TreeViewRect = new Rect(0f, this.m_ToolbarHeight, this.m_DirectoriesAreaWidth, base.position.height - this.m_ToolbarHeight); + this.m_BottomBarRect = new Rect(this.m_DirectoriesAreaWidth, base.position.height - bottomBarHeight, width, bottomBarHeight); + this.m_ListHeaderRect = new Rect(this.m_ListAreaRect.x, this.m_ToolbarHeight, this.m_ListAreaRect.width, listHeaderHeight); + } + } + private void EndPing() + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + this.m_AssetTree.EndPing(); + } + else + { + this.m_FolderTree.EndPing(); + this.m_ListArea.EndPing(); + } + } + private void OnEvent() + { + if (this.m_AssetTree != null) + { + this.m_AssetTree.OnEvent(); + } + if (this.m_FolderTree != null) + { + this.m_FolderTree.OnEvent(); + } + if (this.m_ListArea != null) + { + this.m_ListArea.OnEvent(); + } + } + private void OnGUI() + { + if (ProjectBrowser.s_Styles == null) + { + ProjectBrowser.s_Styles = new ProjectBrowser.Styles(); + } + if (!this.Initialized()) + { + this.Init(); + } + this.m_ListKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.m_TreeViewKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.OnEvent(); + this.m_ToolbarHeight = EditorStyles.toolbar.fixedHeight; + this.m_ItemSelectedByRightClickThisEvent = false; + this.ResizeHandling(base.position.width, base.position.height - this.m_ToolbarHeight); + this.CalculateRects(); + Event current = Event.current; + Rect position = new Rect(0f, 0f, base.position.width, base.position.height); + if (current.type == EventType.MouseDown && position.Contains(current.mousePosition)) + { + this.EndPing(); + this.SetAsLastInteractedProjectBrowser(); + } + if (this.m_GrabKeyboardFocusForListArea) + { + this.m_GrabKeyboardFocusForListArea = false; + GUIUtility.keyboardControl = this.m_ListKeyboardControlID; + } + GUI.BeginGroup(position, GUIContent.none); + this.TopToolbar(); + this.BottomBar(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + if (this.m_SearchFilter.IsSearching()) + { + this.SearchAreaBar(); + if (GUIUtility.keyboardControl == this.m_TreeViewKeyboardControlID) + { + GUIUtility.keyboardControl = this.m_ListKeyboardControlID; + } + this.m_ListArea.OnGUI(this.m_ListAreaRect, this.m_ListKeyboardControlID); + } + else + { + if (GUIUtility.keyboardControl == this.m_ListKeyboardControlID) + { + GUIUtility.keyboardControl = this.m_TreeViewKeyboardControlID; + } + this.m_AssetTree.OnGUI(this.m_TreeViewRect, this.m_TreeViewKeyboardControlID); + ProjectBrowser.HandleUnusedAssetDragEvents(this.m_TreeViewRect); + } + } + else + { + if (this.m_SearchFilter.IsSearching()) + { + this.SearchAreaBar(); + } + else + { + this.BreadCrumbBar(); + } + this.m_FolderTree.OnGUI(this.m_TreeViewRect, this.m_TreeViewKeyboardControlID); + if (current.type == EventType.Repaint) + { + Color color = GUI.color; + GUI.color *= ((!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.12f, 0.12f, 0.12f, 1.333f)); + Rect position2 = new Rect(this.m_ListAreaRect.x - 1f, this.m_ToolbarHeight, 1f, this.m_TreeViewRect.height); + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture); + GUI.color = color; + } + this.m_ListArea.OnGUI(this.m_ListAreaRect, this.m_ListKeyboardControlID); + if (this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && this.m_ListArea.numItemsDisplayed == 0) + { + Vector2 vector = EditorStyles.label.CalcSize(ProjectBrowser.s_Styles.m_EmptyFolderText); + Rect position3 = new Rect(this.m_ListAreaRect.x + 2f + Mathf.Max(0f, (this.m_ListAreaRect.width - vector.x) * 0.5f), this.m_ListAreaRect.y + 10f, vector.x, 20f); + EditorGUI.BeginDisabledGroup(true); + GUI.Label(position3, ProjectBrowser.s_Styles.m_EmptyFolderText, EditorStyles.label); + EditorGUI.EndDisabledGroup(); + } + } + this.HandleContextClickInListArea(this.m_ListAreaRect); + if (this.m_ListArea.gridSize != this.m_StartGridSize) + { + this.m_StartGridSize = this.m_ListArea.gridSize; + if (this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing) + { + this.m_LastFoldersGridSize = (float)this.m_ListArea.gridSize; + } + } + GUI.EndGroup(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.useTreeViewSelectionInsteadOfMainSelection = (GUIUtility.keyboardControl == this.m_TreeViewKeyboardControlID); + } + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && GUIUtility.keyboardControl == this.m_TreeViewKeyboardControlID) + { + this.HandleCommandEventsForTreeView(); + } + this.HandleCommandEvents(); + } + private void HandleContextClickInListArea(Rect listRect) + { + Event current = Event.current; + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.ContextClick) + { + if (listRect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = 0; + if (AssetStoreAssetSelection.GetFirstAsset() != null) + { + ProjectBrowser.AssetStoreItemContextMenu.Show(); + } + else + { + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/", null); + } + current.Use(); + } + } + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && current.button == 1 && !this.m_ItemSelectedByRightClickThisEvent && this.m_SearchFilter.folders.Length > 0 && listRect.Contains(current.mousePosition)) + { + this.m_InternalSelectionChange = true; + Selection.instanceIDs = ProjectBrowser.GetFolderInstanceIDs(this.m_SearchFilter.folders); + } + } + } + private static void HandleUnusedAssetDragEvents(Rect rect) + { + Event current = Event.current; + EventType type = current.type; + if (type == EventType.DragUpdated || type == EventType.DragPerform) + { + if (rect.Contains(current.mousePosition)) + { + int assetsFolderInstanceID = ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (!hierarchyProperty.Find(assetsFolderInstanceID, null)) + { + hierarchyProperty = null; + } + bool perform = current.type == EventType.DragPerform; + DragAndDrop.visualMode = InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + current.Use(); + } + } + } + private void AssetTreeViewContextClick(int clickedNodeInstanceID) + { + Event current = Event.current; + Assert.That(current.type == EventType.ContextClick); + if (clickedNodeInstanceID == 0 && this.m_AssetTree.GetSelection().Length > 0) + { + int[] array = new int[0]; + this.m_AssetTree.SetSelection(array, false); + this.AssetTreeSelectionCallback(array); + } + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/", null); + current.Use(); + } + private void FolderTreeViewContextClick(int clickedNodeInstanceID) + { + Event current = Event.current; + Assert.That(current.type == EventType.ContextClick); + if (SavedSearchFilters.IsSavedFilter(clickedNodeInstanceID)) + { + if (clickedNodeInstanceID != SavedSearchFilters.GetRootInstanceID()) + { + ProjectBrowser.SavedFiltersContextMenu.Show(clickedNodeInstanceID); + } + } + else + { + if (clickedNodeInstanceID != 0) + { + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/", null); + } + } + current.Use(); + } + private void AssetTreeDragEnded(int[] draggedInstanceIds, bool draggedItemsFromOwnTreeView) + { + if (draggedInstanceIds != null && draggedItemsFromOwnTreeView) + { + this.m_AssetTree.SetSelection(draggedInstanceIds, true); + this.m_AssetTree.NotifyListenersThatSelectionChanged(); + base.Repaint(); + GUIUtility.ExitGUI(); + } + } + private void FolderTreeDragEnded(int[] draggedInstanceIds, bool draggedItemsFromOwnTreeView) + { + } + private void TopToolbar() + { + GUILayout.BeginArea(new Rect(0f, 0f, base.position.width, this.m_ToolbarHeight)); + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + float num = base.position.width - this.m_DirectoriesAreaWidth; + float num2 = 4f; + if (num >= 500f) + { + num2 = 10f; + } + this.CreateDropdown(); + GUILayout.FlexibleSpace(); + GUILayout.Space(num2 * 2f); + this.SearchField(); + GUILayout.Space(num2); + this.TypeDropDown(); + this.AssetLabelsDropDown(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.ButtonSaveFilter(); + } + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } + private void SetOneColumn() + { + this.SetViewMode(ProjectBrowser.ViewMode.OneColumn); + } + private void SetTwoColumns() + { + this.SetViewMode(ProjectBrowser.ViewMode.TwoColumns); + } + private void OpenTreeViewTestWindow() + { + EditorWindow.GetWindow(); + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + if (this.m_EnableOldAssetTree) + { + GUIContent content = new GUIContent("One Column Layout"); + GUIContent content2 = new GUIContent("Two Columns Layout"); + menu.AddItem(content, this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn, new GenericMenu.MenuFunction(this.SetOneColumn)); + if (base.position.width >= 230f) + { + menu.AddItem(content2, this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns, new GenericMenu.MenuFunction(this.SetTwoColumns)); + } + else + { + menu.AddDisabledItem(content2); + } + if (Unsupported.IsDeveloperBuild()) + { + menu.AddItem(new GUIContent("Debug TreeView"), false, new GenericMenu.MenuFunction(this.OpenTreeViewTestWindow)); + } + } + } + private float DrawLocalAssetHeader(Rect r) + { + return 0f; + } + private void ResizeHandling(float width, float height) + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + return; + } + Rect position = new Rect(this.m_DirectoriesAreaWidth, this.m_ToolbarHeight, 5f, height); + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(position, MouseCursor.SplitResizeLeftRight); + } + float num = 0f; + float x = EditorGUI.MouseDeltaReader(position, true).x; + if (x != 0f) + { + this.m_DirectoriesAreaWidth += x; + float max = width - this.k_MinDirectoriesAreaWidth; + num = Mathf.Clamp(this.m_DirectoriesAreaWidth, this.k_MinDirectoriesAreaWidth, max); + } + float num2 = 230f - this.k_MinDirectoriesAreaWidth; + if (width - this.m_DirectoriesAreaWidth < num2) + { + num = width - num2; + } + if (num > 0f) + { + this.m_DirectoriesAreaWidth = num; + } + float num3 = base.position.width - this.m_DirectoriesAreaWidth; + if (num3 != this.m_LastListWidth) + { + this.RefreshSplittedSelectedPath(); + } + this.m_LastListWidth = num3; + } + private void ButtonSaveFilter() + { + EditorGUI.BeginDisabledGroup(!this.m_SearchFilter.IsSearching()); + if (GUILayout.Button(ProjectBrowser.s_Styles.m_SaveFilterContent, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + ProjectBrowserColumnOneTreeViewGUI projectBrowserColumnOneTreeViewGUI = this.m_FolderTree.gui as ProjectBrowserColumnOneTreeViewGUI; + if (projectBrowserColumnOneTreeViewGUI != null) + { + bool flag = true; + int[] selection = this.m_FolderTree.GetSelection(); + if (selection.Length == 1) + { + int num = selection[0]; + bool flag2 = SavedSearchFilters.GetRootInstanceID() == num; + if (SavedSearchFilters.IsSavedFilter(num) && !flag2) + { + flag = false; + string title = "Overwrite Filter?"; + string message = "Do you want to overwrite '" + SavedSearchFilters.GetName(num) + "' or create a new filter?"; + int num2 = EditorUtility.DisplayDialogComplex(title, message, "Overwrite", "Create", "Cancel"); + if (num2 == 0) + { + SavedSearchFilters.UpdateExistingSavedFilter(num, this.m_SearchFilter, this.listAreaGridSize); + } + else + { + if (num2 == 1) + { + flag = true; + } + } + } + } + if (flag) + { + base.Focus(); + projectBrowserColumnOneTreeViewGUI.BeginCreateSavedFilter(this.m_SearchFilter); + } + } + } + EditorGUI.EndDisabledGroup(); + } + private void CreateDropdown() + { + Rect rect = GUILayoutUtility.GetRect(ProjectBrowser.s_Styles.m_CreateDropdownContent, EditorStyles.toolbarDropDown); + if (EditorGUI.ButtonMouseDown(rect, ProjectBrowser.s_Styles.m_CreateDropdownContent, FocusType.Passive, EditorStyles.toolbarDropDown)) + { + GUIUtility.hotControl = 0; + EditorUtility.DisplayPopupMenu(rect, "Assets/Create", null); + } + } + private void AssetLabelsDropDown() + { + Rect rect = GUILayoutUtility.GetRect(ProjectBrowser.s_Styles.m_FilterByLabel, EditorStyles.toolbarButton); + if (EditorGUI.ButtonMouseDown(rect, ProjectBrowser.s_Styles.m_FilterByLabel, FocusType.Passive, EditorStyles.toolbarButton)) + { + PopupWindow.Show(rect, new PopupList(this.m_AssetLabels)); + } + } + private void TypeDropDown() + { + Rect rect = GUILayoutUtility.GetRect(ProjectBrowser.s_Styles.m_FilterByType, EditorStyles.toolbarButton); + if (EditorGUI.ButtonMouseDown(rect, ProjectBrowser.s_Styles.m_FilterByType, FocusType.Passive, EditorStyles.toolbarButton)) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + PopupWindow.Show(last, new PopupList(this.m_ObjectTypes)); + } + } + private void SearchField() + { + Rect rect = GUILayoutUtility.GetRect(0f, EditorGUILayout.kLabelFloatMaxW * 1.5f, 16f, 16f, EditorStyles.toolbarSearchField, new GUILayoutOption[] + { + GUILayout.MinWidth(65f), + GUILayout.MaxWidth(300f) + }); + int controlID = GUIUtility.GetControlID(ProjectBrowser.s_HashForSearchField, FocusType.Passive, rect); + if (this.m_FocusSearchField) + { + GUIUtility.keyboardControl = controlID; + EditorGUIUtility.editingTextField = true; + if (Event.current.type == EventType.Repaint) + { + this.m_FocusSearchField = false; + } + } + Event current = Event.current; + if (current.type == EventType.KeyDown && (current.keyCode == KeyCode.DownArrow || current.keyCode == KeyCode.UpArrow) && GUIUtility.keyboardControl == controlID) + { + if (!this.m_ListArea.IsLastClickedItemVisible()) + { + this.m_ListArea.SelectFirst(); + } + GUIUtility.keyboardControl = this.m_ListKeyboardControlID; + current.Use(); + } + string text = EditorGUI.ToolbarSearchField(controlID, rect, this.m_SearchFieldText, false); + if (text != this.m_SearchFieldText || this.m_FocusSearchField) + { + this.m_SearchFieldText = text; + this.m_SearchFilter.SearchFieldStringToFilter(this.m_SearchFieldText); + this.SyncFilterGUI(); + this.TopBarSearchSettingsChanged(); + base.Repaint(); + } + } + private void TopBarSearchSettingsChanged() + { + if (!this.m_SearchFilter.IsSearching()) + { + if (this.m_DidSelectSearchResult) + { + this.m_DidSelectSearchResult = false; + this.FrameObjectPrivate(Selection.activeInstanceID, true, false); + if (GUIUtility.keyboardControl == 0) + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + GUIUtility.keyboardControl = this.m_TreeViewKeyboardControlID; + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + GUIUtility.keyboardControl = this.m_ListKeyboardControlID; + } + } + } + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && GUIUtility.keyboardControl == 0 && this.m_LastFolders != null && this.m_LastFolders.Length > 0) + { + this.m_SearchFilter.folders = this.m_LastFolders; + this.SetFolderSelection(ProjectBrowser.GetFolderInstanceIDs(this.m_LastFolders), true); + } + } + } + else + { + this.InitSearchMenu(); + } + this.InitListArea(); + } + private static int[] GetFolderInstanceIDs(string[] folders) + { + int[] array = new int[folders.Length]; + for (int i = 0; i < folders.Length; i++) + { + array[i] = AssetDatabase.GetMainAssetInstanceID(folders[i]); + } + return array; + } + private static string[] GetFolderPathsFromInstanceIDs(int[] instanceIDs) + { + List list = new List(); + for (int i = 0; i < instanceIDs.Length; i++) + { + int instanceID = instanceIDs[i]; + string assetPath = AssetDatabase.GetAssetPath(instanceID); + if (!string.IsNullOrEmpty(assetPath)) + { + list.Add(assetPath); + } + } + return list.ToArray(); + } + private void ClearSearch() + { + this.m_SearchFilter.ClearSearch(); + this.m_SearchFieldText = string.Empty; + this.m_AssetLabels.DeselectAll(); + this.m_ObjectTypes.DeselectAll(); + this.m_DidSelectSearchResult = false; + } + private void FolderTreeSelectionChanged(bool folderWasSelected) + { + if (folderWasSelected) + { + ProjectBrowser.SearchViewState searchViewState = this.GetSearchViewState(); + if (searchViewState == ProjectBrowser.SearchViewState.AllAssets || searchViewState == ProjectBrowser.SearchViewState.AssetStore) + { + string[] folders = this.m_SearchFilter.folders; + this.ClearSearch(); + this.m_SearchFilter.folders = folders; + this.m_SearchFilter.searchArea = this.m_LastLocalAssetsSearchArea; + } + this.m_LastFolders = this.m_SearchFilter.folders; + } + this.RefreshSearchText(); + this.InitListArea(); + } + private void IconSizeSlider(Rect r) + { + EditorGUI.BeginChangeCheck(); + int gridSize = (int)GUI.HorizontalSlider(r, (float)this.m_ListArea.gridSize, (float)this.m_ListArea.minGridSize, (float)this.m_ListArea.maxGridSize); + if (EditorGUI.EndChangeCheck()) + { + AssetStorePreviewManager.AbortSize(this.m_ListArea.gridSize); + this.m_ListArea.gridSize = gridSize; + } + } + private void SearchAreaBar() + { + GUI.Label(this.m_ListHeaderRect, GUIContent.none, ProjectBrowser.s_Styles.topBarBg); + Rect listHeaderRect = this.m_ListHeaderRect; + listHeaderRect.x += 5f; + listHeaderRect.width -= 10f; + listHeaderRect.y += 1f; + GUIStyle boldLabel = EditorStyles.boldLabel; + GUI.Label(listHeaderRect, ProjectBrowser.s_Styles.m_SearchIn, boldLabel); + if (this.m_SearchAreaMenuOffset < 0f) + { + this.m_SearchAreaMenuOffset = boldLabel.CalcSize(ProjectBrowser.s_Styles.m_SearchIn).x; + } + listHeaderRect.x += this.m_SearchAreaMenuOffset + 7f; + listHeaderRect.width -= this.m_SearchAreaMenuOffset + 7f; + listHeaderRect.width = this.m_SearchAreaMenu.OnGUI(listHeaderRect); + } + private void BreadCrumbBar() + { + if (this.m_ListHeaderRect.height <= 0f) + { + return; + } + if (this.m_SearchFilter.folders.Length == 0) + { + return; + } + Event current = Event.current; + if (current.type == EventType.MouseDown && this.m_ListHeaderRect.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = this.m_ListKeyboardControlID; + base.Repaint(); + } + if (this.m_BreadCrumbs.Count == 0) + { + string text = this.m_SearchFilter.folders[0]; + string[] array = text.Split(new char[] + { + '/' + }); + string text2 = string.Empty; + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text3 = array2[i]; + if (!string.IsNullOrEmpty(text2)) + { + text2 += "/"; + } + text2 += text3; + this.m_BreadCrumbs.Add(new KeyValuePair(new GUIContent(text3), text2)); + } + this.m_BreadCrumbLastFolderHasSubFolders = (ProjectBrowser.BreadCrumbListMenu.GetSubFolders(text).Count > 0); + } + GUI.Label(this.m_ListHeaderRect, GUIContent.none, ProjectBrowser.s_Styles.topBarBg); + Rect listHeaderRect = this.m_ListHeaderRect; + listHeaderRect.y += 1f; + listHeaderRect.x += 4f; + if (this.m_SearchFilter.folders.Length == 1) + { + for (int j = 0; j < this.m_BreadCrumbs.Count; j++) + { + bool flag = j == this.m_BreadCrumbs.Count - 1; + GUIStyle gUIStyle = (!flag) ? EditorStyles.label : EditorStyles.boldLabel; + GUIContent key = this.m_BreadCrumbs[j].Key; + string value = this.m_BreadCrumbs[j].Value; + Vector2 vector = gUIStyle.CalcSize(key); + listHeaderRect.width = vector.x; + if (GUI.Button(listHeaderRect, key, gUIStyle)) + { + this.ShowFolderContents(AssetDatabase.GetMainAssetInstanceID(value), false); + } + listHeaderRect.x += vector.x + 3f; + if (!flag || this.m_BreadCrumbLastFolderHasSubFolders) + { + Rect rect = new Rect(listHeaderRect.x, listHeaderRect.y + 2f, 13f, 13f); + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, ProjectBrowser.s_Styles.foldout)) + { + string currentSubFolder = string.Empty; + if (!flag) + { + currentSubFolder = this.m_BreadCrumbs[j + 1].Value; + } + ProjectBrowser.BreadCrumbListMenu.Show(value, currentSubFolder, rect, this); + } + } + listHeaderRect.x += 11f; + } + } + else + { + if (this.m_SearchFilter.folders.Length > 1) + { + GUI.Label(listHeaderRect, GUIContent.Temp("Showing multiple folders..."), EditorStyles.miniLabel); + } + } + } + private void BottomBar() + { + if (this.m_BottomBarRect.height == 0f) + { + return; + } + Rect bottomBarRect = this.m_BottomBarRect; + GUI.Label(bottomBarRect, GUIContent.none, ProjectBrowser.s_Styles.bottomBarBg); + Rect r = new Rect(bottomBarRect.x + bottomBarRect.width - 55f - 16f, bottomBarRect.y + bottomBarRect.height - 17f, 55f, 17f); + this.IconSizeSlider(r); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + bottomBarRect.width -= 4f; + bottomBarRect.x += 2f; + bottomBarRect.height = 17f; + for (int i = this.m_SelectedPathSplitted.Count - 1; i >= 0; i--) + { + if (i == 0) + { + bottomBarRect.width = bottomBarRect.width - 55f - 14f; + } + GUI.Label(bottomBarRect, this.m_SelectedPathSplitted[i], ProjectBrowser.s_Styles.selectedPathLabel); + bottomBarRect.y += 17f; + } + EditorGUIUtility.SetIconSize(new Vector2(0f, 0f)); + } + private void SelectAssetsFolder() + { + this.ShowFolderContents(ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(), true); + } + private string ValidateCreateNewAssetPath(string pathName) + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns && this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && this.m_SearchFilter.folders.Length > 0 && !pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase) && Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets).Length == 0) + { + pathName = Path.Combine(this.m_SearchFilter.folders[0], pathName); + pathName = pathName.Replace("\\", "/"); + } + return pathName; + } + internal void BeginPreimportedNameEditing(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile) + { + if (!this.Initialized()) + { + this.Init(); + } + this.EndRenaming(); + bool isCreatingNewFolder = endAction is DoCreateFolder; + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + if (this.m_SearchFilter.GetState() != SearchFilter.State.FolderBrowsing) + { + this.SelectAssetsFolder(); + } + pathName = this.ValidateCreateNewAssetPath(pathName); + this.m_ListAreaState.m_CreateAssetUtility.BeginNewAssetCreation(instanceID, endAction, pathName, icon, resourceFile); + this.ShowFolderContents(AssetDatabase.GetMainAssetInstanceID(this.m_ListAreaState.m_CreateAssetUtility.folder), true); + this.m_ListArea.BeginNamingNewAsset(this.m_ListAreaState.m_CreateAssetUtility.originalName, instanceID, isCreatingNewFolder); + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + if (this.m_SearchFilter.IsSearching()) + { + this.ClearSearch(); + } + AssetsTreeViewGUI assetsTreeViewGUI = this.m_AssetTree.gui as AssetsTreeViewGUI; + if (assetsTreeViewGUI != null) + { + assetsTreeViewGUI.BeginCreateNewAsset(instanceID, endAction, pathName, icon, resourceFile); + } + else + { + Debug.LogError("Not valid defaultTreeViewGUI!"); + } + } + } + } + public void FrameObject(int instanceID, bool ping) + { + this.FrameObjectPrivate(instanceID, !this.m_IsLocked, ping); + if (ProjectBrowser.s_LastInteractedProjectBrowser == this) + { + this.m_GrabKeyboardFocusForListArea = true; + } + } + private void FrameObjectPrivate(int instanceID, bool frame, bool ping) + { + if (instanceID == 0 || this.m_ListArea == null) + { + return; + } + if (this.m_LastFramedID != instanceID) + { + this.EndPing(); + } + this.m_LastFramedID = instanceID; + this.ClearSearch(); + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + int num = 0; + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(instanceID, null)) + { + while (hierarchyProperty.Parent()) + { + if (hierarchyProperty.isFolder) + { + num = hierarchyProperty.instanceID; + break; + } + } + if (num == 0) + { + num = ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); + } + } + if (num != 0) + { + this.m_FolderTree.Frame(num, frame, ping); + if (frame) + { + this.ShowFolderContents(num, true); + } + this.m_ListArea.Frame(instanceID, frame, ping); + } + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + this.m_AssetTree.Frame(instanceID, frame, ping); + } + } + } + private static int[] GetTreeViewFolderSelection() + { + ProjectBrowser projectBrowser = ProjectBrowser.s_LastInteractedProjectBrowser; + if (projectBrowser != null && projectBrowser.useTreeViewSelectionInsteadOfMainSelection && projectBrowser.m_FolderTree != null) + { + return ProjectBrowser.s_LastInteractedProjectBrowser.m_FolderTree.GetSelection(); + } + return new int[0]; + } + private int GetProjectBrowserDebugID() + { + for (int i = 0; i < ProjectBrowser.s_ProjectBrowsers.Count; i++) + { + if (ProjectBrowser.s_ProjectBrowsers[i] == this) + { + return i; + } + } + return -1; + } + internal static void DeleteSelectedAssets(bool askIfSure) + { + int[] treeViewFolderSelection = ProjectBrowser.GetTreeViewFolderSelection(); + List list; + if (treeViewFolderSelection.Length > 0) + { + list = new List(treeViewFolderSelection); + } + else + { + list = new List(Selection.instanceIDs); + } + if (list.Count == 0) + { + return; + } + bool flag = list.IndexOf(ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID()) >= 0; + if (flag) + { + string title = "Cannot Delete"; + EditorUtility.DisplayDialog(title, "Deleting the 'Assets' folder is not allowed", "Ok"); + } + else + { + List mainPaths = ProjectBrowser.GetMainPaths(list); + if (mainPaths.Count == 0) + { + return; + } + if (askIfSure) + { + string text = "Delete selected asset"; + if (mainPaths.Count > 1) + { + text += "s"; + } + text += "?"; + int num = 3; + string text2 = string.Empty; + int num2 = 0; + while (num2 < mainPaths.Count && num2 < num) + { + text2 = text2 + " " + mainPaths[num2] + "\n"; + num2++; + } + if (mainPaths.Count > num) + { + text2 += " ...\n"; + } + text2 += "\nYou cannot undo this action."; + if (!EditorUtility.DisplayDialog(text, text2, "Delete", "Cancel")) + { + return; + } + } + AssetDatabase.StartAssetEditing(); + foreach (string current in mainPaths) + { + AssetDatabase.MoveAssetToTrash(current); + } + AssetDatabase.StopAssetEditing(); + } + } + internal IHierarchyProperty GetHierarchyPropertyUsingFilter(string textFilter) + { + return FilteredHierarchyProperty.CreateHierarchyPropertyForFilter(new FilteredHierarchy(HierarchyType.Assets) + { + searchFilter = SearchFilter.CreateSearchFilterFromString(textFilter) + }); + } + internal void ShowObjectsInList(int[] instanceIDs) + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.TwoColumns) + { + this.m_ListArea.ShowObjectsInList(instanceIDs); + this.m_FolderTree.SetSelection(new int[0], false); + } + else + { + if (this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn) + { + int[] instanceIDs2 = Selection.instanceIDs; + for (int i = 0; i < instanceIDs2.Length; i++) + { + int id = instanceIDs2[i]; + this.m_AssetTree.Frame(id, true, false); + } + } + } + } + private static void ShowSelectedObjectsInLastInteractedProjectBrowser() + { + if (ProjectBrowser.s_LastInteractedProjectBrowser != null) + { + int[] instanceIDs = Selection.instanceIDs; + ProjectBrowser.s_LastInteractedProjectBrowser.ShowObjectsInList(instanceIDs); + } + } + protected virtual void ShowButton(Rect r) + { + if (ProjectBrowser.s_Styles == null) + { + ProjectBrowser.s_Styles = new ProjectBrowser.Styles(); + } + this.m_IsLocked = GUI.Toggle(r, this.m_IsLocked, GUIContent.none, ProjectBrowser.s_Styles.lockButton); + } + } +} diff --git a/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDataSource.cs b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDataSource.cs new file mode 100644 index 00000000..094d1e0d --- /dev/null +++ b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDataSource.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ProjectBrowserColumnOneTreeViewDataSource : TreeViewDataSource + { + private static string kProjectBrowserString = "ProjectBrowser"; + public ProjectBrowserColumnOneTreeViewDataSource(TreeView treeView) : base(treeView) + { + base.showRootNode = false; + base.rootIsCollapsable = false; + SavedSearchFilters.AddChangeListener(new Action(this.ReloadData)); + } + public override bool SetExpanded(int id, bool expand) + { + if (base.SetExpanded(id, expand)) + { + InternalEditorUtility.expandedProjectWindowItems = base.expandedIDs.ToArray(); + if (this.m_RootItem.hasChildren) + { + foreach (TreeViewItem current in this.m_RootItem.children) + { + if (current.id == id) + { + EditorPrefs.SetBool(ProjectBrowserColumnOneTreeViewDataSource.kProjectBrowserString + current.displayName, expand); + } + } + } + return true; + } + return false; + } + public override bool IsExpandable(TreeViewItem item) + { + return item.hasChildren && (item != this.m_RootItem || base.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) + { + return item.parent != null && item.parent.parent == null; + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return !this.IsVisibleRootNode(item) && base.IsRenamingItemAllowed(item); + } + public static int GetAssetsFolderInstanceID() + { + string path = "Assets"; + string guid = AssetDatabase.AssetPathToGUID(path); + return AssetDatabase.GetInstanceIDFromGUID(guid); + } + public override void FetchData() + { + this.m_RootItem = new TreeViewItem(2147483647, 0, null, "Invisible Root Item"); + this.SetExpanded(this.m_RootItem, true); + List list = new List(); + int assetsFolderInstanceID = ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); + int num = 0; + string displayName = "Assets"; + TreeViewItem treeViewItem = new TreeViewItem(assetsFolderInstanceID, num, this.m_RootItem, displayName); + this.ReadAssetDatabase(treeViewItem, num + 1); + TreeViewItem treeViewItem2 = SavedSearchFilters.ConvertToTreeView(); + treeViewItem2.parent = this.m_RootItem; + list.Add(treeViewItem2); + list.Add(treeViewItem); + this.m_RootItem.children = list; + foreach (TreeViewItem current in this.m_RootItem.children) + { + bool @bool = EditorPrefs.GetBool(ProjectBrowserColumnOneTreeViewDataSource.kProjectBrowserString + current.displayName, true); + this.SetExpanded(current, @bool); + } + this.m_NeedRefreshVisibleFolders = true; + } + private void ReadAssetDatabase(TreeViewItem parent, int baseDepth) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.Reset(); + Texture2D texture2D = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + Texture2D texture2D2 = EditorGUIUtility.FindTexture(EditorResourcesUtility.emptyFolderIconName); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + if (hierarchyProperty.isFolder) + { + list.Add(new TreeViewItem(hierarchyProperty.instanceID, baseDepth + hierarchyProperty.depth, null, hierarchyProperty.name) + { + icon = (!hierarchyProperty.hasChildren) ? texture2D2 : texture2D + }); + } + } + TreeViewUtility.SetChildParentReferences(list, parent); + } + } +} diff --git a/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs new file mode 100644 index 00000000..ecb46ca8 --- /dev/null +++ b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ProjectBrowserColumnOneTreeViewDragging : AssetOrGameObjectTreeViewDragging + { + public ProjectBrowserColumnOneTreeViewDragging(TreeView treeView) : base(treeView, HierarchyType.Assets) + { + } + public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) + { + if (SavedSearchFilters.IsSavedFilter(draggedItem.id) && draggedItem.id == SavedSearchFilters.GetRootInstanceID()) + { + return; + } + ProjectWindowUtil.StartDrag(draggedItem.id, draggedItemIDs); + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos) + { + if (targetItem == null) + { + return DragAndDropVisualMode.None; + } + object genericData = DragAndDrop.GetGenericData(ProjectWindowUtil.k_DraggingFavoriteGenericData); + if (genericData != null) + { + int instanceID = (int)genericData; + if (targetItem is SearchFilterTreeItem && parentItem is SearchFilterTreeItem) + { + bool flag = SavedSearchFilters.CanMoveSavedFilter(instanceID, parentItem.id, targetItem.id, true); + if (flag && perform) + { + SavedSearchFilters.MoveSavedFilter(instanceID, parentItem.id, targetItem.id, true); + } + return (!flag) ? DragAndDropVisualMode.None : DragAndDropVisualMode.Copy; + } + return DragAndDropVisualMode.None; + } + else + { + if (!(targetItem is SearchFilterTreeItem) || !(parentItem is SearchFilterTreeItem)) + { + return base.DoDrag(parentItem, targetItem, perform, dropPos); + } + string a = DragAndDrop.GetGenericData(ProjectWindowUtil.k_IsFolderGenericData) as string; + if (a == "isFolder") + { + if (perform) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + if (objectReferences.Length > 0) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(objectReferences[0].GetInstanceID(), null)) + { + SearchFilter searchFilter = new SearchFilter(); + string assetPath = AssetDatabase.GetAssetPath(hierarchyProperty.instanceID); + if (!string.IsNullOrEmpty(assetPath)) + { + searchFilter.folders = new string[] + { + assetPath + }; + bool addAsChild = targetItem == parentItem; + float listAreaGridSize = ProjectBrowserColumnOneTreeViewGUI.GetListAreaGridSize(); + int activeInstanceID = SavedSearchFilters.AddSavedFilterAfterInstanceID(hierarchyProperty.name, searchFilter, listAreaGridSize, targetItem.id, addAsChild); + Selection.activeInstanceID = activeInstanceID; + } + else + { + Debug.Log("Could not get asset path from id " + hierarchyProperty.name); + } + } + } + } + return DragAndDropVisualMode.Copy; + } + return DragAndDropVisualMode.None; + } + } + } +} diff --git a/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewGUI.cs b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewGUI.cs new file mode 100644 index 00000000..ad72182a --- /dev/null +++ b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewGUI.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ProjectBrowserColumnOneTreeViewGUI : AssetsTreeViewGUI + { + private const float k_DistBetweenRootTypes = 15f; + private Texture2D k_FavoritesIcon = EditorGUIUtility.FindTexture("Favorite Icon"); + private Texture2D k_FavoriteFolderIcon = EditorGUIUtility.FindTexture("FolderFavorite Icon"); + private Texture2D k_FavoriteFilterIcon = EditorGUIUtility.FindTexture("Search Icon"); + private bool m_IsCreatingSavedFilter; + public ProjectBrowserColumnOneTreeViewGUI(TreeView treeView) : base(treeView) + { + } + public override Vector2 GetTotalSize(List rows) + { + Vector2 totalSize = base.GetTotalSize(rows); + totalSize.y += 15f; + return totalSize; + } + public override float GetTopPixelOfRow(int row, List rows) + { + float num = (float)row * this.k_LineHeight; + TreeViewItem treeViewItem = rows[row]; + if (ProjectBrowser.GetItemType(treeViewItem.id) == ProjectBrowser.ItemType.Asset) + { + num += 15f; + } + return num; + } + public override float GetHeightOfLastRow() + { + return this.k_LineHeight; + } + public override int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) + { + return (int)Mathf.Floor(heightOfTreeView / this.k_LineHeight) - 1; + } + public override void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) + { + firstRowVisible = (int)Mathf.Floor(topPixel / this.k_LineHeight); + lastRowVisible = firstRowVisible + (int)Mathf.Ceil(heightInPixels / this.k_LineHeight); + float num = 15f / this.k_LineHeight; + firstRowVisible -= (int)Mathf.Ceil(2f * num); + lastRowVisible += (int)Mathf.Ceil(2f * num); + firstRowVisible = Mathf.Max(firstRowVisible, 0); + lastRowVisible = Mathf.Min(lastRowVisible, rows.Count - 1); + } + public override Rect OnRowGUI(TreeViewItem item, int row, float rowWidth, bool selected, bool focused) + { + float num = (float)row * this.k_LineHeight; + if (ProjectBrowser.GetItemType(item.id) == ProjectBrowser.ItemType.Asset) + { + num += 15f; + } + Rect rect = new Rect(0f, num, rowWidth, this.k_LineHeight); + bool useBoldFont = this.IsVisibleRootNode(item); + this.DoNodeGUI(rect, item, selected, focused, useBoldFont); + return rect; + } + private bool IsVisibleRootNode(TreeViewItem item) + { + return (this.m_TreeView.data as ProjectBrowserColumnOneTreeViewDataSource).IsVisibleRootNode(item); + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item != null && item.icon != null) + { + return item.icon; + } + SearchFilterTreeItem searchFilterTreeItem = item as SearchFilterTreeItem; + if (searchFilterTreeItem == null) + { + return base.GetIconForNode(item); + } + if (this.IsVisibleRootNode(item)) + { + return this.k_FavoritesIcon; + } + if (searchFilterTreeItem.isFolder) + { + return this.k_FavoriteFolderIcon; + } + return this.k_FavoriteFilterIcon; + } + public static float GetListAreaGridSize() + { + float result = -1f; + if (ProjectBrowser.s_LastInteractedProjectBrowser != null) + { + result = ProjectBrowser.s_LastInteractedProjectBrowser.listAreaGridSize; + } + return result; + } + internal virtual void BeginCreateSavedFilter(SearchFilter filter) + { + string text = "New Saved Search"; + this.m_IsCreatingSavedFilter = true; + int num = SavedSearchFilters.AddSavedFilter(text, filter, ProjectBrowserColumnOneTreeViewGUI.GetListAreaGridSize()); + this.m_TreeView.Frame(num, true, false); + this.m_TreeView.state.renameOverlay.BeginRename(text, num, 0f); + } + protected override void RenameEnded() + { + int userData = base.GetRenameOverlay().userData; + ProjectBrowser.ItemType itemType = ProjectBrowser.GetItemType(userData); + if (this.m_IsCreatingSavedFilter) + { + this.m_IsCreatingSavedFilter = false; + if (base.GetRenameOverlay().userAcceptedRename) + { + SavedSearchFilters.SetName(userData, base.GetRenameOverlay().name); + this.m_TreeView.SetSelection(new int[] + { + userData + }, true); + } + else + { + SavedSearchFilters.RemoveSavedFilter(userData); + } + } + else + { + if (itemType == ProjectBrowser.ItemType.SavedFilter) + { + if (base.GetRenameOverlay().userAcceptedRename) + { + SavedSearchFilters.SetName(userData, base.GetRenameOverlay().name); + } + } + else + { + base.RenameEnded(); + if (base.GetRenameOverlay().userAcceptedRename) + { + this.m_TreeView.NotifyListenersThatSelectionChanged(); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/ProjectWindowUtil.cs b/UnityEditor/UnityEditor/ProjectWindowUtil.cs new file mode 100644 index 00000000..a51c1fe4 --- /dev/null +++ b/UnityEditor/UnityEditor/ProjectWindowUtil.cs @@ -0,0 +1,260 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor.ProjectWindowCallback; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public class ProjectWindowUtil + { + internal static int k_FavoritesStartInstanceID = 1000000000; + internal static string k_DraggingFavoriteGenericData = "DraggingFavorite"; + internal static string k_IsFolderGenericData = "IsFolder"; + [MenuItem("Assets/Create/GUI Skin", false, 601)] + public static void CreateNewGUISkin() + { + GUISkin gUISkin = ScriptableObject.CreateInstance(); + GUISkin gUISkin2 = Resources.GetBuiltinResource(typeof(GUISkin), "GameSkin/GameSkin.guiskin") as GUISkin; + if (gUISkin2) + { + EditorUtility.CopySerialized(gUISkin2, gUISkin); + } + else + { + Debug.LogError("Internal error: unable to load builtin GUIskin"); + } + ProjectWindowUtil.CreateAsset(gUISkin, "New GUISkin.guiskin"); + } + internal static string GetActiveFolderPath() + { + ProjectBrowser projectBrowserIfExists = ProjectWindowUtil.GetProjectBrowserIfExists(); + if (projectBrowserIfExists == null) + { + return "Assets"; + } + return projectBrowserIfExists.GetActiveFolderPath(); + } + internal static void EndNameEditAction(EndNameEditAction action, int instanceId, string pathName, string resourceFile) + { + pathName = AssetDatabase.GenerateUniqueAssetPath(pathName); + if (action != null) + { + action.Action(instanceId, pathName, resourceFile); + action.CleanUp(); + } + } + public static void CreateAsset(UnityEngine.Object asset, string pathName) + { + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(asset.GetInstanceID(), ScriptableObject.CreateInstance(), pathName, AssetPreview.GetMiniThumbnail(asset), null); + } + public static void CreateFolder() + { + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Folder", EditorGUIUtility.IconContent(EditorResourcesUtility.emptyFolderIconName).image as Texture2D, null); + } + public static void CreatePrefab() + { + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Prefab.prefab", EditorGUIUtility.IconContent("Prefab Icon").image as Texture2D, null); + } + private static void CreateScriptAsset(string templatePath, string destName) + { + string extension = Path.GetExtension(destName); + Texture2D icon; + switch (extension) + { + case ".js": + icon = (EditorGUIUtility.IconContent("js Script Icon").image as Texture2D); + goto IL_105; + case ".cs": + icon = (EditorGUIUtility.IconContent("cs Script Icon").image as Texture2D); + goto IL_105; + case ".boo": + icon = (EditorGUIUtility.IconContent("boo Script Icon").image as Texture2D); + goto IL_105; + case ".shader": + icon = (EditorGUIUtility.IconContent("Shader Icon").image as Texture2D); + goto IL_105; + } + icon = (EditorGUIUtility.IconContent("TextAsset Icon").image as Texture2D); + IL_105: + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), destName, icon, templatePath); + } + public static void ShowCreatedAsset(UnityEngine.Object o) + { + Selection.activeObject = o; + if (o) + { + ProjectWindowUtil.FrameObjectInProjectWindow(o.GetInstanceID()); + } + } + private static void CreateAnimatorController() + { + Texture2D icon = EditorGUIUtility.IconContent("AnimatorController Icon").image as Texture2D; + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Animator Controller.controller", icon, null); + } + internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile) + { + string fullPath = Path.GetFullPath(pathName); + StreamReader streamReader = new StreamReader(resourceFile); + string text = streamReader.ReadToEnd(); + streamReader.Close(); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName); + text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension); + string text2 = Regex.Replace(fileNameWithoutExtension, " ", string.Empty); + text = Regex.Replace(text, "#SCRIPTNAME#", text2); + if (char.IsUpper(text2, 0)) + { + text2 = char.ToLower(text2[0]) + text2.Substring(1); + text = Regex.Replace(text, "#SCRIPTNAME_LOWER#", text2); + } + else + { + text2 = "my" + char.ToUpper(text2[0]) + text2.Substring(1); + text = Regex.Replace(text, "#SCRIPTNAME_LOWER#", text2); + } + bool encoderShouldEmitUTF8Identifier = true; + bool throwOnInvalidBytes = false; + UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes); + bool append = false; + StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding); + streamWriter.Write(text); + streamWriter.Close(); + AssetDatabase.ImportAsset(pathName); + return AssetDatabase.LoadAssetAtPath(pathName, typeof(UnityEngine.Object)); + } + public static void StartNameEditingIfProjectWindowExists(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile) + { + ProjectBrowser projectBrowserIfExists = ProjectWindowUtil.GetProjectBrowserIfExists(); + if (projectBrowserIfExists) + { + projectBrowserIfExists.Focus(); + projectBrowserIfExists.BeginPreimportedNameEditing(instanceID, endAction, pathName, icon, resourceFile); + projectBrowserIfExists.Repaint(); + } + else + { + if (!pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) + { + pathName = "Assets/" + pathName; + } + ProjectWindowUtil.EndNameEditAction(endAction, instanceID, pathName, resourceFile); + Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); + } + } + private static ProjectBrowser GetProjectBrowserIfExists() + { + return ProjectBrowser.s_LastInteractedProjectBrowser; + } + internal static void FrameObjectInProjectWindow(int instanceID) + { + ProjectBrowser projectBrowserIfExists = ProjectWindowUtil.GetProjectBrowserIfExists(); + if (projectBrowserIfExists) + { + projectBrowserIfExists.FrameObject(instanceID, false); + } + } + internal static bool IsFavoritesItem(int instanceID) + { + return instanceID >= ProjectWindowUtil.k_FavoritesStartInstanceID; + } + internal static void StartDrag(int draggedInstanceID, List selectedInstanceIDs) + { + DragAndDrop.PrepareStartDrag(); + string title = string.Empty; + if (ProjectWindowUtil.IsFavoritesItem(draggedInstanceID)) + { + DragAndDrop.SetGenericData(ProjectWindowUtil.k_DraggingFavoriteGenericData, draggedInstanceID); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + } + else + { + bool flag = false; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (hierarchyProperty.Find(draggedInstanceID, null)) + { + flag = hierarchyProperty.isFolder; + } + DragAndDrop.objectReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedInstanceID, selectedInstanceIDs); + DragAndDrop.SetGenericData(ProjectWindowUtil.k_IsFolderGenericData, (!flag) ? string.Empty : "isFolder"); + string[] dragAndDropPaths = ProjectWindowUtil.GetDragAndDropPaths(draggedInstanceID, selectedInstanceIDs); + if (dragAndDropPaths.Length > 0) + { + DragAndDrop.paths = dragAndDropPaths; + } + if (DragAndDrop.objectReferences.Length > 1) + { + title = ""; + } + else + { + title = ObjectNames.GetDragAndDropTitle(InternalEditorUtility.GetObjectFromInstanceID(draggedInstanceID)); + } + } + DragAndDrop.StartDrag(title); + } + internal static UnityEngine.Object[] GetDragAndDropObjects(int draggedInstanceID, List selectedInstanceIDs) + { + if (selectedInstanceIDs.Contains(draggedInstanceID)) + { + UnityEngine.Object[] array = new UnityEngine.Object[selectedInstanceIDs.Count]; + for (int i = 0; i < selectedInstanceIDs.Count; i++) + { + array[i] = InternalEditorUtility.GetObjectFromInstanceID(selectedInstanceIDs[i]); + } + return array; + } + return new UnityEngine.Object[] + { + InternalEditorUtility.GetObjectFromInstanceID(draggedInstanceID) + }; + } + internal static string[] GetDragAndDropPaths(int draggedInstanceID, List selectedInstanceIDs) + { + List list = new List(); + foreach (int current in selectedInstanceIDs) + { + if (AssetDatabase.IsMainAsset(current)) + { + string assetPath = AssetDatabase.GetAssetPath(current); + list.Add(assetPath); + } + } + string assetPath2 = AssetDatabase.GetAssetPath(draggedInstanceID); + if (string.IsNullOrEmpty(assetPath2)) + { + return new string[0]; + } + if (list.Contains(assetPath2)) + { + return list.ToArray(); + } + return new string[] + { + assetPath2 + }; + } + public static string[] GetBaseFolders(string[] folders) + { + if (folders.Length < 2) + { + return folders; + } + List list = new List(); + List list2 = new List(folders); + list2.Sort(); + string text = list2[0]; + list.Add(text); + for (int i = 1; i < list2.Count; i++) + { + if (list2[i].IndexOf(text) < 0) + { + list.Add(list2[i]); + text = list2[i]; + } + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyAndTargetHandler.cs b/UnityEditor/UnityEditor/PropertyAndTargetHandler.cs new file mode 100644 index 00000000..082b3e69 --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyAndTargetHandler.cs @@ -0,0 +1,17 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class PropertyAndTargetHandler + { + public SerializedProperty property; + public UnityEngine.Object target; + public TargetChoiceHandler.TargetChoiceMenuFunction function; + public PropertyAndTargetHandler(SerializedProperty property, UnityEngine.Object target, TargetChoiceHandler.TargetChoiceMenuFunction function) + { + this.property = property; + this.target = target; + this.function = function; + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyDrawer.cs b/UnityEditor/UnityEditor/PropertyDrawer.cs new file mode 100644 index 00000000..c123e489 --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyDrawer.cs @@ -0,0 +1,47 @@ +using System; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + public abstract class PropertyDrawer : GUIDrawer + { + internal PropertyAttribute m_Attribute; + internal FieldInfo m_FieldInfo; + public PropertyAttribute attribute + { + get + { + return this.m_Attribute; + } + } + public FieldInfo fieldInfo + { + get + { + return this.m_FieldInfo; + } + } + internal void OnGUISafe(Rect position, SerializedProperty property, GUIContent label) + { + ScriptAttributeUtility.s_DrawerStack.Push(this); + this.OnGUI(position, property, label); + ScriptAttributeUtility.s_DrawerStack.Pop(); + } + public virtual void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.DefaultPropertyField(position, property, label); + EditorGUI.LabelField(position, label, EditorGUIUtility.TempContent("No GUI Implemented")); + } + internal float GetPropertyHeightSafe(SerializedProperty property, GUIContent label) + { + ScriptAttributeUtility.s_DrawerStack.Push(this); + float propertyHeight = this.GetPropertyHeight(property, label); + ScriptAttributeUtility.s_DrawerStack.Pop(); + return propertyHeight; + } + public virtual float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return 16f; + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyGUIData.cs b/UnityEditor/UnityEditor/PropertyGUIData.cs new file mode 100644 index 00000000..4bdce73b --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyGUIData.cs @@ -0,0 +1,21 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct PropertyGUIData + { + public SerializedProperty property; + public Rect totalPosition; + public bool wasBoldDefaultFont; + public bool wasEnabled; + public Color color; + public PropertyGUIData(SerializedProperty property, Rect totalPosition, bool wasBoldDefaultFont, bool wasEnabled, Color color) + { + this.property = property; + this.totalPosition = totalPosition; + this.wasBoldDefaultFont = wasBoldDefaultFont; + this.wasEnabled = wasEnabled; + this.color = color; + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyHandler.cs b/UnityEditor/UnityEditor/PropertyHandler.cs new file mode 100644 index 00000000..0a12174d --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyHandler.cs @@ -0,0 +1,232 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class PropertyHandler + { + private PropertyDrawer m_PropertyDrawer; + private List m_DecoratorDrawers; + public string tooltip; + public List contextMenuItems; + public bool hasPropertyDrawer + { + get + { + return this.propertyDrawer != null; + } + } + private PropertyDrawer propertyDrawer + { + get + { + if (this.m_PropertyDrawer != null && ScriptAttributeUtility.s_DrawerStack.Any() && this.m_PropertyDrawer == ScriptAttributeUtility.s_DrawerStack.Peek()) + { + return null; + } + return this.m_PropertyDrawer; + } + } + public bool empty + { + get + { + return this.m_DecoratorDrawers == null && this.tooltip == null && this.propertyDrawer == null && this.contextMenuItems == null; + } + } + public void HandleAttribute(PropertyAttribute attribute, FieldInfo field, Type propertyType) + { + if (attribute is TooltipAttribute) + { + this.tooltip = (attribute as TooltipAttribute).tooltip; + return; + } + if (!(attribute is ContextMenuItemAttribute)) + { + this.HandleDrawnType(attribute.GetType(), propertyType, field, attribute); + return; + } + if (propertyType.IsArrayOrList()) + { + return; + } + if (this.contextMenuItems == null) + { + this.contextMenuItems = new List(); + } + this.contextMenuItems.Add(attribute as ContextMenuItemAttribute); + } + public void HandleDrawnType(Type drawnType, Type propertyType, FieldInfo field, PropertyAttribute attribute) + { + Type drawerTypeForType = ScriptAttributeUtility.GetDrawerTypeForType(drawnType); + if (drawerTypeForType != null) + { + if (typeof(PropertyDrawer).IsAssignableFrom(drawerTypeForType)) + { + if (propertyType != null && propertyType.IsArrayOrList()) + { + return; + } + this.m_PropertyDrawer = (PropertyDrawer)Activator.CreateInstance(drawerTypeForType); + this.m_PropertyDrawer.m_FieldInfo = field; + this.m_PropertyDrawer.m_Attribute = attribute; + } + else + { + if (typeof(DecoratorDrawer).IsAssignableFrom(drawerTypeForType)) + { + if (field != null && field.FieldType.IsArrayOrList() && !propertyType.IsArrayOrList()) + { + return; + } + DecoratorDrawer decoratorDrawer = (DecoratorDrawer)Activator.CreateInstance(drawerTypeForType); + decoratorDrawer.m_Attribute = attribute; + if (this.m_DecoratorDrawers == null) + { + this.m_DecoratorDrawers = new List(); + } + this.m_DecoratorDrawers.Add(decoratorDrawer); + } + } + } + } + public bool OnGUI(Rect position, SerializedProperty property, GUIContent label, bool includeChildren) + { + float num = position.height; + position.height = 0f; + if (this.m_DecoratorDrawers != null) + { + foreach (DecoratorDrawer current in this.m_DecoratorDrawers) + { + position.height = current.GetHeight(); + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + current.OnGUI(position); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + position.y += position.height; + num -= position.height; + } + } + position.height = num; + if (this.propertyDrawer != null) + { + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + this.propertyDrawer.OnGUISafe(position, property.Copy(), label ?? EditorGUIUtility.TempContent(property.displayName)); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + return false; + } + if (!includeChildren) + { + return EditorGUI.DefaultPropertyField(position, property, label); + } + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + bool enabled = GUI.enabled; + int indentLevel = EditorGUI.indentLevel; + int num2 = indentLevel - property.depth; + SerializedProperty serializedProperty = property.Copy(); + SerializedProperty endProperty = serializedProperty.GetEndProperty(); + position.height = EditorGUI.GetSinglePropertyHeight(serializedProperty, label); + EditorGUI.indentLevel = serializedProperty.depth + num2; + bool enterChildren = EditorGUI.DefaultPropertyField(position, serializedProperty, label) && EditorGUI.HasVisibleChildFields(serializedProperty); + position.y += position.height + 2f; + while (serializedProperty.NextVisible(enterChildren) && !SerializedProperty.EqualContents(serializedProperty, endProperty)) + { + EditorGUI.indentLevel = serializedProperty.depth + num2; + position.height = EditorGUI.GetPropertyHeight(serializedProperty, null, false); + EditorGUI.BeginChangeCheck(); + enterChildren = (ScriptAttributeUtility.GetHandler(serializedProperty).OnGUI(position, serializedProperty, null, false) && EditorGUI.HasVisibleChildFields(serializedProperty)); + if (EditorGUI.EndChangeCheck()) + { + break; + } + position.y += position.height + 2f; + } + GUI.enabled = enabled; + EditorGUIUtility.SetIconSize(iconSize); + EditorGUI.indentLevel = indentLevel; + return false; + } + public bool OnGUILayout(SerializedProperty property, GUIContent label, bool includeChildren, params GUILayoutOption[] options) + { + Rect rect; + if (property.propertyType == SerializedPropertyType.Boolean && this.propertyDrawer == null && (this.m_DecoratorDrawers == null || this.m_DecoratorDrawers.Count == 0)) + { + rect = EditorGUILayout.GetToggleRect(true, options); + } + else + { + rect = EditorGUILayout.GetControlRect(EditorGUI.LabelHasContent(label), this.GetHeight(property, label, includeChildren), options); + } + EditorGUILayout.s_LastRect = rect; + return this.OnGUI(rect, property, label, includeChildren); + } + public float GetHeight(SerializedProperty property, GUIContent label, bool includeChildren) + { + float num = 0f; + if (this.m_DecoratorDrawers != null) + { + foreach (DecoratorDrawer current in this.m_DecoratorDrawers) + { + num += current.GetHeight(); + } + } + if (this.propertyDrawer != null) + { + num += this.propertyDrawer.GetPropertyHeightSafe(property.Copy(), label ?? EditorGUIUtility.TempContent(property.displayName)); + } + else + { + if (!includeChildren) + { + num += EditorGUI.GetSinglePropertyHeight(property, label); + } + else + { + property = property.Copy(); + SerializedProperty endProperty = property.GetEndProperty(); + num += EditorGUI.GetSinglePropertyHeight(property, label); + bool enterChildren = property.isExpanded && EditorGUI.HasVisibleChildFields(property); + while (property.NextVisible(enterChildren) && !SerializedProperty.EqualContents(property, endProperty)) + { + num += ScriptAttributeUtility.GetHandler(property).GetHeight(property, EditorGUIUtility.TempContent(property.displayName), true); + enterChildren = false; + num += 2f; + } + } + } + return num; + } + public void AddMenuItems(SerializedProperty property, GenericMenu menu) + { + if (this.contextMenuItems == null) + { + return; + } + Type type = property.serializedObject.targetObject.GetType(); + foreach (ContextMenuItemAttribute current in this.contextMenuItems) + { + MethodInfo method = type.GetMethod(current.function, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + menu.AddItem(new GUIContent(current.name), false, delegate + { + this.CallMenuCallback(property.serializedObject.targetObjects, method); + }); + } + } + } + public void CallMenuCallback(object[] targets, MethodInfo method) + { + for (int i = 0; i < targets.Length; i++) + { + object obj = targets[i]; + method.Invoke(obj, new object[0]); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyHandlerCache.cs b/UnityEditor/UnityEditor/PropertyHandlerCache.cs new file mode 100644 index 00000000..058acdab --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyHandlerCache.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + internal class PropertyHandlerCache + { + protected Dictionary m_PropertyHandlers = new Dictionary(); + internal PropertyHandler GetHandler(SerializedProperty property) + { + int propertyHash = PropertyHandlerCache.GetPropertyHash(property); + PropertyHandler result; + if (this.m_PropertyHandlers.TryGetValue(propertyHash, out result)) + { + return result; + } + return null; + } + internal void SetHandler(SerializedProperty property, PropertyHandler handler) + { + int propertyHash = PropertyHandlerCache.GetPropertyHash(property); + this.m_PropertyHandlers[propertyHash] = handler; + } + private static int GetPropertyHash(SerializedProperty property) + { + if (property.serializedObject.targetObject == null) + { + return 0; + } + int num = property.serializedObject.targetObject.GetInstanceID() ^ property.arrayIndexLessPropertyPath.GetHashCode(); + if (property.propertyType == SerializedPropertyType.ObjectReference) + { + num ^= property.objectReferenceInstanceIDValue; + } + return num; + } + public void Clear() + { + this.m_PropertyHandlers.Clear(); + } + } +} diff --git a/UnityEditor/UnityEditor/PropertyModification.cs b/UnityEditor/UnityEditor/PropertyModification.cs new file mode 100644 index 00000000..be10262e --- /dev/null +++ b/UnityEditor/UnityEditor/PropertyModification.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class PropertyModification + { + public UnityEngine.Object target; + public string propertyPath; + public string value; + public UnityEngine.Object objectReference; + } +} diff --git a/UnityEditor/UnityEditor/PurchaseResult.cs b/UnityEditor/UnityEditor/PurchaseResult.cs new file mode 100644 index 00000000..bcee0885 --- /dev/null +++ b/UnityEditor/UnityEditor/PurchaseResult.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class PurchaseResult : AssetStoreResultBase + { + public enum Status + { + BasketNotEmpty, + ServiceDisabled, + AnonymousUser, + PasswordMissing, + PasswordWrong, + PurchaseDeclined, + Ok + } + public PurchaseResult.Status status; + public int packageID; + public string message; + public PurchaseResult(AssetStoreResultBase.Callback c) : base(c) + { + } + protected override void Parse(Dictionary dict) + { + this.packageID = int.Parse(dict["package_id"].AsString()); + this.message = ((!dict.ContainsKey("message")) ? null : dict["message"].AsString(true)); + string a = dict["status"].AsString(true); + if (a == "basket-not-empty") + { + this.status = PurchaseResult.Status.BasketNotEmpty; + } + else + { + if (a == "service-disabled") + { + this.status = PurchaseResult.Status.ServiceDisabled; + } + else + { + if (a == "user-anonymous") + { + this.status = PurchaseResult.Status.AnonymousUser; + } + else + { + if (a == "password-missing") + { + this.status = PurchaseResult.Status.PasswordMissing; + } + else + { + if (a == "password-wrong") + { + this.status = PurchaseResult.Status.PasswordWrong; + } + else + { + if (a == "purchase-declined") + { + this.status = PurchaseResult.Status.PurchaseDeclined; + } + else + { + if (a == "ok") + { + this.status = PurchaseResult.Status.Ok; + } + } + } + } + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/QualityCurvesTime.cs b/UnityEditor/UnityEditor/QualityCurvesTime.cs new file mode 100644 index 00000000..74ff6f9a --- /dev/null +++ b/UnityEditor/UnityEditor/QualityCurvesTime.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal struct QualityCurvesTime + { + public float fixedTime; + public float variableEndStart; + public float variableEndEnd; + public int q; + } +} diff --git a/UnityEditor/UnityEditor/QualitySettingsEditor.cs b/UnityEditor/UnityEditor/QualitySettingsEditor.cs new file mode 100644 index 00000000..08a15319 --- /dev/null +++ b/UnityEditor/UnityEditor/QualitySettingsEditor.cs @@ -0,0 +1,467 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(QualitySettings))] + internal class QualitySettingsEditor : Editor + { + private static class Styles + { + public const int kMinToggleWidth = 15; + public const int kMaxToggleWidth = 20; + public const int kHeaderRowHeight = 20; + public const int kLabelWidth = 80; + public static readonly GUIStyle kToggle = "OL Toggle"; + public static readonly GUIStyle kDefaultToggle = "OL ToggleWhite"; + public static readonly GUIStyle kButton = "Button"; + public static readonly GUIStyle kSelected = "PR Label"; + public static readonly GUIContent kPlatformTooltip = new GUIContent(string.Empty, "Allow quality setting on platform"); + public static readonly GUIContent kIconTrash = EditorGUIUtility.IconContent("TreeEditor.Trash", "Delete Level"); + public static readonly GUIContent kSoftParticlesHint = EditorGUIUtility.TextContent("QualitySettings.SoftParticlesHint"); + public static readonly GUIStyle kListEvenBg = "ObjectPickerResultsOdd"; + public static readonly GUIStyle kListOddBg = "ObjectPickerResultsEven"; + public static readonly GUIStyle kDefaultDropdown = "QualitySettingsDefault"; + } + private struct QualitySetting + { + public string m_Name; + public string m_PropertyPath; + public List m_ExcludedPlatforms; + } + private class Dragging + { + public int m_StartPosition; + public int m_Position; + } + private SerializedObject m_QualitySettings; + private SerializedProperty m_QualitySettingsProperty; + private SerializedProperty m_PerPlatformDefaultQualityProperty; + private List m_ValidPlatforms; + private readonly int m_QualityElementHash = "QualityElementHash".GetHashCode(); + private QualitySettingsEditor.Dragging m_Dragging; + private bool m_ShouldAddNewLevel; + private int m_DeleteLevel = -1; + public void OnEnable() + { + this.m_QualitySettings = new SerializedObject(this.target); + this.m_QualitySettingsProperty = this.m_QualitySettings.FindProperty("m_QualitySettings"); + this.m_PerPlatformDefaultQualityProperty = this.m_QualitySettings.FindProperty("m_PerPlatformDefaultQuality"); + this.m_ValidPlatforms = BuildPlayerWindow.GetValidPlatforms(); + } + private int DoQualityLevelSelection(int currentQualitylevel, IList qualitySettings, Dictionary platformDefaultQualitySettings) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + int num = currentQualitylevel; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false), + GUILayout.Width(80f), + GUILayout.Height(20f) + }); + rect.x += EditorGUI.indent; + rect.width -= EditorGUI.indent; + GUI.Label(rect, "Levels", EditorStyles.boldLabel); + foreach (BuildPlayerWindow.BuildPlatform current in this.m_ValidPlatforms) + { + Rect rect2 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f), + GUILayout.Height(20f) + }); + GUIContent gUIContent = EditorGUIUtility.TempContent(current.smallIcon); + gUIContent.tooltip = current.name; + GUI.Label(rect2, gUIContent); + gUIContent.tooltip = string.Empty; + } + GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f), + GUILayout.Height(20f) + }); + GUILayout.EndHorizontal(); + Event current2 = Event.current; + for (int i = 0; i < qualitySettings.Count; i++) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIStyle gUIStyle = (i % 2 != 0) ? QualitySettingsEditor.Styles.kListOddBg : QualitySettingsEditor.Styles.kListEvenBg; + bool on = num == i; + Rect rect3 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false), + GUILayout.Width(80f) + }); + switch (current2.type) + { + case EventType.MouseDown: + if (rect3.Contains(current2.mousePosition)) + { + num = i; + GUIUtility.keyboardControl = 0; + GUIUtility.hotControl = this.m_QualityElementHash; + this.m_Dragging = new QualitySettingsEditor.Dragging + { + m_StartPosition = i, + m_Position = i + }; + current2.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == this.m_QualityElementHash) + { + GUIUtility.hotControl = 0; + current2.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == this.m_QualityElementHash && rect3.Contains(current2.mousePosition)) + { + this.m_Dragging.m_Position = i; + current2.Use(); + } + break; + case EventType.KeyDown: + if (current2.keyCode == KeyCode.UpArrow || current2.keyCode == KeyCode.DownArrow) + { + num += ((current2.keyCode != KeyCode.UpArrow) ? 1 : -1); + num = Mathf.Clamp(num, 0, qualitySettings.Count - 1); + GUIUtility.keyboardControl = 0; + current2.Use(); + } + break; + case EventType.Repaint: + gUIStyle.Draw(rect3, GUIContent.none, false, false, on, false); + GUI.Label(rect3, EditorGUIUtility.TempContent(qualitySettings[i].m_Name)); + break; + } + foreach (BuildPlayerWindow.BuildPlatform current3 in this.m_ValidPlatforms) + { + bool flag = false; + if (platformDefaultQualitySettings.ContainsKey(current3.name) && platformDefaultQualitySettings[current3.name] == i) + { + flag = true; + } + Rect rect4 = GUILayoutUtility.GetRect(QualitySettingsEditor.Styles.kPlatformTooltip, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f) + }); + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(rect4, GUIContent.none, false, false, on, false); + } + Color backgroundColor = GUI.backgroundColor; + if (flag && !EditorApplication.isPlayingOrWillChangePlaymode) + { + GUI.backgroundColor = Color.green; + } + bool flag2 = !qualitySettings[i].m_ExcludedPlatforms.Contains(current3.name); + bool flag3 = GUI.Toggle(rect4, flag2, QualitySettingsEditor.Styles.kPlatformTooltip, (!flag) ? QualitySettingsEditor.Styles.kToggle : QualitySettingsEditor.Styles.kDefaultToggle); + if (flag2 != flag3) + { + if (flag3) + { + qualitySettings[i].m_ExcludedPlatforms.Remove(current3.name); + } + else + { + qualitySettings[i].m_ExcludedPlatforms.Add(current3.name); + } + } + GUI.backgroundColor = backgroundColor; + } + Rect rect5 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f) + }); + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(rect5, GUIContent.none, false, false, on, false); + } + if (GUI.Button(rect5, QualitySettingsEditor.Styles.kIconTrash, GUIStyle.none)) + { + this.m_DeleteLevel = i; + } + GUILayout.EndHorizontal(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f), + GUILayout.Height(1f) + }); + QualitySettingsEditor.DrawHorizontalDivider(); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect rect6 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false), + GUILayout.Width(80f), + GUILayout.Height(20f) + }); + rect6.x += EditorGUI.indent; + rect6.width -= EditorGUI.indent; + GUI.Label(rect6, "Default", EditorStyles.boldLabel); + foreach (BuildPlayerWindow.BuildPlatform current4 in this.m_ValidPlatforms) + { + Rect rect7 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f), + GUILayout.Height(20f) + }); + int num2; + if (!platformDefaultQualitySettings.TryGetValue(current4.name, out num2)) + { + platformDefaultQualitySettings.Add(current4.name, 0); + } + num2 = EditorGUI.Popup(rect7, num2, ( + from x in qualitySettings + select x.m_Name).ToArray(), QualitySettingsEditor.Styles.kDefaultDropdown); + platformDefaultQualitySettings[current4.name] = num2; + } + GUILayout.EndHorizontal(); + GUILayout.Space(10f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.MinWidth(15f), + GUILayout.MaxWidth(20f), + GUILayout.Height(20f) + }); + Rect rect8 = GUILayoutUtility.GetRect(GUIContent.none, QualitySettingsEditor.Styles.kToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (GUI.Button(rect8, EditorGUIUtility.TempContent("Add Quality Level"))) + { + this.m_ShouldAddNewLevel = true; + } + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + return num; + } + private List GetQualitySettings() + { + List list = new List(); + foreach (SerializedProperty serializedProperty in this.m_QualitySettingsProperty) + { + QualitySettingsEditor.QualitySetting qualitySetting = default(QualitySettingsEditor.QualitySetting); + QualitySettingsEditor.QualitySetting qualitySetting2 = qualitySetting; + qualitySetting2.m_Name = serializedProperty.FindPropertyRelative("name").stringValue; + qualitySetting2.m_PropertyPath = serializedProperty.propertyPath; + qualitySetting = qualitySetting2; + qualitySetting.m_PropertyPath = serializedProperty.propertyPath; + List list2 = new List(); + SerializedProperty serializedProperty2 = serializedProperty.FindPropertyRelative("excludedTargetPlatforms"); + foreach (SerializedProperty serializedProperty3 in serializedProperty2) + { + list2.Add(serializedProperty3.stringValue); + } + qualitySetting.m_ExcludedPlatforms = list2; + list.Add(qualitySetting); + } + return list; + } + private void SetQualitySettings(IEnumerable settings) + { + foreach (QualitySettingsEditor.QualitySetting current in settings) + { + SerializedProperty serializedProperty = this.m_QualitySettings.FindProperty(current.m_PropertyPath); + if (serializedProperty != null) + { + SerializedProperty serializedProperty2 = serializedProperty.FindPropertyRelative("excludedTargetPlatforms"); + if (serializedProperty2.arraySize != current.m_ExcludedPlatforms.Count) + { + serializedProperty2.arraySize = current.m_ExcludedPlatforms.Count; + } + int num = 0; + foreach (SerializedProperty serializedProperty3 in serializedProperty2) + { + if (serializedProperty3.stringValue != current.m_ExcludedPlatforms[num]) + { + serializedProperty3.stringValue = current.m_ExcludedPlatforms[num]; + } + num++; + } + } + } + } + private void HandleAddRemoveQualitySetting(ref int selectedLevel) + { + if (this.m_DeleteLevel >= 0) + { + if (this.m_DeleteLevel < selectedLevel || this.m_DeleteLevel == this.m_QualitySettingsProperty.arraySize - 1) + { + selectedLevel--; + } + if (this.m_QualitySettingsProperty.arraySize > 1 && this.m_DeleteLevel >= 0 && this.m_DeleteLevel < this.m_QualitySettingsProperty.arraySize) + { + this.m_QualitySettingsProperty.DeleteArrayElementAtIndex(this.m_DeleteLevel); + } + this.m_DeleteLevel = -1; + } + if (this.m_ShouldAddNewLevel) + { + this.m_QualitySettingsProperty.arraySize++; + SerializedProperty arrayElementAtIndex = this.m_QualitySettingsProperty.GetArrayElementAtIndex(this.m_QualitySettingsProperty.arraySize - 1); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("name"); + serializedProperty.stringValue = "Level " + (this.m_QualitySettingsProperty.arraySize - 1); + this.m_ShouldAddNewLevel = false; + } + } + private Dictionary GetDefaultQualityForPlatforms() + { + Dictionary dictionary = new Dictionary(); + foreach (SerializedProperty serializedProperty in this.m_PerPlatformDefaultQualityProperty) + { + dictionary.Add(serializedProperty.FindPropertyRelative("first").stringValue, serializedProperty.FindPropertyRelative("second").intValue); + } + return dictionary; + } + private void SetDefaultQualityForPlatforms(Dictionary platformDefaults) + { + if (this.m_PerPlatformDefaultQualityProperty.arraySize != platformDefaults.Count) + { + this.m_PerPlatformDefaultQualityProperty.arraySize = platformDefaults.Count; + } + int num = 0; + foreach (KeyValuePair current in platformDefaults) + { + SerializedProperty arrayElementAtIndex = this.m_PerPlatformDefaultQualityProperty.GetArrayElementAtIndex(num); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("first"); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("second"); + if (serializedProperty.stringValue != current.Key || serializedProperty2.intValue != current.Value) + { + serializedProperty.stringValue = current.Key; + serializedProperty2.intValue = current.Value; + } + num++; + } + } + private static void DrawHorizontalDivider() + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.Height(1f) + }); + Color backgroundColor = GUI.backgroundColor; + if (EditorGUIUtility.isProSkin) + { + GUI.backgroundColor = backgroundColor * 0.7058f; + } + else + { + GUI.backgroundColor = Color.black; + } + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.whiteTextureStyle.Draw(rect, GUIContent.none, false, false, false, false); + } + GUI.backgroundColor = backgroundColor; + } + private void SoftParticlesHintGUI() + { + Camera main = Camera.main; + if (main == null) + { + return; + } + RenderingPath actualRenderingPath = main.actualRenderingPath; + if (actualRenderingPath == RenderingPath.DeferredLighting) + { + return; + } + if ((main.depthTextureMode & DepthTextureMode.Depth) != DepthTextureMode.None) + { + return; + } + EditorGUILayout.HelpBox(QualitySettingsEditor.Styles.kSoftParticlesHint.text, MessageType.Warning, false); + } + public override void OnInspectorGUI() + { + if (EditorApplication.isPlayingOrWillChangePlaymode) + { + EditorGUILayout.HelpBox("Changes made in play mode will not be saved.", MessageType.Warning, true); + } + this.m_QualitySettings.Update(); + List qualitySettings = this.GetQualitySettings(); + Dictionary defaultQualityForPlatforms = this.GetDefaultQualityForPlatforms(); + int num = QualitySettings.GetQualityLevel(); + num = this.DoQualityLevelSelection(num, qualitySettings, defaultQualityForPlatforms); + this.SetQualitySettings(qualitySettings); + this.HandleAddRemoveQualitySetting(ref num); + this.SetDefaultQualityForPlatforms(defaultQualityForPlatforms); + GUILayout.Space(10f); + QualitySettingsEditor.DrawHorizontalDivider(); + GUILayout.Space(10f); + SerializedProperty arrayElementAtIndex = this.m_QualitySettingsProperty.GetArrayElementAtIndex(num); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("name"); + SerializedProperty property = arrayElementAtIndex.FindPropertyRelative("pixelLightCount"); + SerializedProperty property2 = arrayElementAtIndex.FindPropertyRelative("shadows"); + SerializedProperty property3 = arrayElementAtIndex.FindPropertyRelative("shadowResolution"); + SerializedProperty property4 = arrayElementAtIndex.FindPropertyRelative("shadowProjection"); + SerializedProperty property5 = arrayElementAtIndex.FindPropertyRelative("shadowCascades"); + SerializedProperty property6 = arrayElementAtIndex.FindPropertyRelative("shadowDistance"); + SerializedProperty property7 = arrayElementAtIndex.FindPropertyRelative("blendWeights"); + SerializedProperty property8 = arrayElementAtIndex.FindPropertyRelative("textureQuality"); + SerializedProperty property9 = arrayElementAtIndex.FindPropertyRelative("anisotropicTextures"); + SerializedProperty property10 = arrayElementAtIndex.FindPropertyRelative("antiAliasing"); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("softParticles"); + SerializedProperty property11 = arrayElementAtIndex.FindPropertyRelative("vSyncCount"); + SerializedProperty property12 = arrayElementAtIndex.FindPropertyRelative("lodBias"); + SerializedProperty property13 = arrayElementAtIndex.FindPropertyRelative("maximumLODLevel"); + SerializedProperty property14 = arrayElementAtIndex.FindPropertyRelative("particleRaycastBudget"); + if (string.IsNullOrEmpty(serializedProperty.stringValue)) + { + serializedProperty.stringValue = "Level " + num; + } + EditorGUILayout.PropertyField(serializedProperty, new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.Label(EditorGUIUtility.TempContent("Rendering"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property8, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property9, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property10, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedProperty2, new GUILayoutOption[0]); + if (serializedProperty2.boolValue) + { + this.SoftParticlesHintGUI(); + } + GUILayout.Space(10f); + GUILayout.Label(EditorGUIUtility.TempContent("Shadows"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property2, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property3, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property4, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property5, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property6, new GUILayoutOption[0]); + GUILayout.Space(10f); + GUILayout.Label(EditorGUIUtility.TempContent("Other"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property7, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property11, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property12, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property13, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property14, new GUILayoutOption[0]); + if (this.m_Dragging != null && this.m_Dragging.m_Position != this.m_Dragging.m_StartPosition) + { + this.m_QualitySettingsProperty.MoveArrayElement(this.m_Dragging.m_StartPosition, this.m_Dragging.m_Position); + this.m_Dragging.m_StartPosition = this.m_Dragging.m_Position; + num = this.m_Dragging.m_Position; + } + this.m_QualitySettings.ApplyModifiedProperties(); + QualitySettings.SetQualityLevel(Mathf.Clamp(num, 0, this.m_QualitySettingsProperty.arraySize - 1)); + } + } +} diff --git a/UnityEditor/UnityEditor/QuaternionCurveTangentCalculation.cs b/UnityEditor/UnityEditor/QuaternionCurveTangentCalculation.cs new file mode 100644 index 00000000..1bc6bcce --- /dev/null +++ b/UnityEditor/UnityEditor/QuaternionCurveTangentCalculation.cs @@ -0,0 +1,240 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct QuaternionCurveTangentCalculation + { + private AnimationCurve eulerX; + private AnimationCurve eulerY; + private AnimationCurve eulerZ; + public AnimationCurve GetCurve(int index) + { + if (index == 0) + { + return this.eulerX; + } + if (index == 1) + { + return this.eulerY; + } + return this.eulerZ; + } + public void SetCurve(int index, AnimationCurve curve) + { + if (index == 0) + { + this.eulerX = curve; + } + else + { + if (index == 1) + { + this.eulerY = curve; + } + else + { + this.eulerZ = curve; + } + } + } + private Vector3 EvaluateEulerCurvesDirectly(float time) + { + return new Vector3(this.eulerX.Evaluate(time), this.eulerY.Evaluate(time), this.eulerZ.Evaluate(time)); + } + public float CalculateLinearTangent(int fromIndex, int toIndex, int componentIndex) + { + AnimationCurve curve = this.GetCurve(componentIndex); + return this.CalculateLinearTangent(curve[fromIndex], curve[toIndex], componentIndex); + } + public float CalculateLinearTangent(Keyframe from, Keyframe to, int component) + { + float num = 0.01f; + Vector3 vector = this.EvaluateEulerCurvesDirectly(to.time); + Vector3 euler = this.EvaluateEulerCurvesDirectly(from.time); + Quaternion from2 = Quaternion.Euler(vector); + Quaternion to2 = Quaternion.Euler(euler); + Quaternion q = Quaternion.Slerp(from2, to2, num); + Vector3 eulerFromQuaternion = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(q, vector); + switch (component) + { + case 0: + return (eulerFromQuaternion.x - vector.x) / num / -(to.time - from.time); + case 1: + return (eulerFromQuaternion.y - vector.y) / num / -(to.time - from.time); + case 2: + return (eulerFromQuaternion.z - vector.z) / num / -(to.time - from.time); + default: + return 0f; + } + } + public float CalculateSmoothTangent(int index, int component) + { + AnimationCurve curve = this.GetCurve(component); + if (curve.length < 2) + { + return 0f; + } + if (index <= 0) + { + return this.CalculateLinearTangent(curve[0], curve[1], component); + } + if (index >= curve.length - 1) + { + return this.CalculateLinearTangent(curve[curve.length - 1], curve[curve.length - 2], component); + } + float time = curve[index - 1].time; + float time2 = curve[index].time; + float time3 = curve[index + 1].time; + Vector3 euler = this.EvaluateEulerCurvesDirectly(time); + Vector3 vector = this.EvaluateEulerCurvesDirectly(time2); + Vector3 euler2 = this.EvaluateEulerCurvesDirectly(time3); + Quaternion quaternion = Quaternion.Euler(euler); + Quaternion quaternion2 = Quaternion.Euler(vector); + Quaternion quaternion3 = Quaternion.Euler(euler2); + if (quaternion.x * quaternion2.x + quaternion.y * quaternion2.y + quaternion.z * quaternion2.z + quaternion.w * quaternion2.w < 0f) + { + quaternion = new Quaternion(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w); + } + if (quaternion3.x * quaternion2.x + quaternion3.y * quaternion2.y + quaternion3.z * quaternion2.z + quaternion3.w * quaternion2.w < 0f) + { + quaternion3 = new Quaternion(-quaternion3.x, -quaternion3.y, -quaternion3.z, -quaternion3.w); + } + Quaternion quaternion4 = default(Quaternion); + float dx = time2 - time; + float dx2 = time3 - time2; + for (int i = 0; i < 4; i++) + { + float dy = quaternion2[i] - quaternion[i]; + float dy2 = quaternion3[i] - quaternion2[i]; + float num = QuaternionCurveTangentCalculation.SafeDeltaDivide(dy, dx); + float num2 = QuaternionCurveTangentCalculation.SafeDeltaDivide(dy2, dx2); + quaternion4[i] = 0.5f * num + 0.5f * num2; + } + float num3 = Mathf.Abs(time3 - time) * 0.01f; + Quaternion q = new Quaternion(quaternion2.x - quaternion4.x * num3, quaternion2.y - quaternion4.y * num3, quaternion2.z - quaternion4.z * num3, quaternion2.w - quaternion4.w * num3); + Quaternion q2 = new Quaternion(quaternion2.x + quaternion4.x * num3, quaternion2.y + quaternion4.y * num3, quaternion2.z + quaternion4.z * num3, quaternion2.w + quaternion4.w * num3); + Vector3 eulerFromQuaternion = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(q, vector); + Vector3 eulerFromQuaternion2 = QuaternionCurveTangentCalculation.GetEulerFromQuaternion(q2, vector); + return ((eulerFromQuaternion2 - eulerFromQuaternion) / (num3 * 2f))[component]; + } + public static Vector3[] GetEquivalentEulerAngles(Quaternion quat) + { + Vector3 eulerAngles = quat.eulerAngles; + return new Vector3[] + { + eulerAngles, + new Vector3(180f - eulerAngles.x, eulerAngles.y + 180f, eulerAngles.z + 180f) + }; + } + public static Vector3 GetEulerFromQuaternion(Quaternion q, Vector3 refEuler) + { + Vector3[] equivalentEulerAngles = QuaternionCurveTangentCalculation.GetEquivalentEulerAngles(q); + for (int i = 0; i < equivalentEulerAngles.Length; i++) + { + equivalentEulerAngles[i] = new Vector3(Mathf.Repeat(equivalentEulerAngles[i].x - refEuler.x + 180f, 360f) + refEuler.x - 180f, Mathf.Repeat(equivalentEulerAngles[i].y - refEuler.y + 180f, 360f) + refEuler.y - 180f, Mathf.Repeat(equivalentEulerAngles[i].z - refEuler.z + 180f, 360f) + refEuler.z - 180f); + float num = Mathf.Repeat(equivalentEulerAngles[i].x, 360f); + if (Mathf.Abs(num - 90f) < 1f) + { + float num2 = equivalentEulerAngles[i].z - equivalentEulerAngles[i].y; + float num3 = refEuler.z - refEuler.y; + float num4 = num2 - num3; + equivalentEulerAngles[i].z = refEuler.z + num4 * 0.5f; + equivalentEulerAngles[i].y = refEuler.y - num4 * 0.5f; + } + if (Mathf.Abs(num - 270f) < 1f) + { + float num5 = equivalentEulerAngles[i].z + equivalentEulerAngles[i].y; + float num6 = refEuler.z + refEuler.y; + float num7 = num5 - num6; + equivalentEulerAngles[i].z = refEuler.z + num7 * 0.5f; + equivalentEulerAngles[i].y = refEuler.y + num7 * 0.5f; + } + } + Vector3 result = equivalentEulerAngles[0]; + float num8 = (equivalentEulerAngles[0] - refEuler).sqrMagnitude; + for (int j = 1; j < equivalentEulerAngles.Length; j++) + { + float sqrMagnitude = (equivalentEulerAngles[j] - refEuler).sqrMagnitude; + if (sqrMagnitude < num8) + { + num8 = sqrMagnitude; + result = equivalentEulerAngles[j]; + } + } + return result; + } + public static float SafeDeltaDivide(float dy, float dx) + { + if (dx == 0f) + { + return 0f; + } + return dy / dx; + } + public void UpdateTangentsFromMode(int componentIndex) + { + AnimationCurve curve = this.GetCurve(componentIndex); + for (int i = 0; i < curve.length; i++) + { + this.UpdateTangentsFromMode(i, componentIndex); + } + } + public void UpdateTangentsFromMode(int index, int componentIndex) + { + AnimationCurve curve = this.GetCurve(componentIndex); + if (index < 0 || index >= curve.length) + { + return; + } + Keyframe key = curve[index]; + if (CurveUtility.GetKeyTangentMode(key, 0) == TangentMode.Linear && index >= 1) + { + key.inTangent = this.CalculateLinearTangent(index, index - 1, componentIndex); + curve.MoveKey(index, key); + } + if (CurveUtility.GetKeyTangentMode(key, 1) == TangentMode.Linear && index + 1 < curve.length) + { + key.outTangent = this.CalculateLinearTangent(index, index + 1, componentIndex); + curve.MoveKey(index, key); + } + if (CurveUtility.GetKeyTangentMode(key, 0) == TangentMode.Smooth || CurveUtility.GetKeyTangentMode(key, 1) == TangentMode.Smooth) + { + float num = this.CalculateSmoothTangent(index, componentIndex); + key.outTangent = num; + key.inTangent = num; + curve.MoveKey(index, key); + } + } + public static void UpdateTangentsFromMode(AnimationCurve curve, AnimationClip clip, EditorCurveBinding curveBinding) + { + if (RotationCurveInterpolation.GetModeFromCurveData(curveBinding) == RotationCurveInterpolation.Mode.NonBaked) + { + QuaternionCurveTangentCalculation quaternionCurveTangentCalculation = default(QuaternionCurveTangentCalculation); + int curveIndexFromName = RotationCurveInterpolation.GetCurveIndexFromName(curveBinding.propertyName); + for (int i = 0; i < 3; i++) + { + if (i == curveIndexFromName) + { + quaternionCurveTangentCalculation.SetCurve(i, curve); + } + else + { + EditorCurveBinding binding = curveBinding; + binding.propertyName = "localEulerAngles." + RotationCurveInterpolation.kPostFix[i]; + AnimationCurve editorCurve = AnimationUtility.GetEditorCurve(clip, binding); + if (editorCurve == null) + { + return; + } + quaternionCurveTangentCalculation.SetCurve(i, editorCurve); + } + } + quaternionCurveTangentCalculation.UpdateTangentsFromMode(curveIndexFromName); + } + else + { + CurveUtility.UpdateTangentsFromMode(curve); + } + } + } +} diff --git a/UnityEditor/UnityEditor/RagdollBuilder.cs b/UnityEditor/UnityEditor/RagdollBuilder.cs new file mode 100644 index 00000000..3f6044eb --- /dev/null +++ b/UnityEditor/UnityEditor/RagdollBuilder.cs @@ -0,0 +1,518 @@ +using System; +using System.Collections; +using UnityEngine; +namespace UnityEditor +{ + internal class RagdollBuilder : ScriptableWizard + { + private class BoneInfo + { + public string name; + public Transform anchor; + public CharacterJoint joint; + public RagdollBuilder.BoneInfo parent; + public float minLimit; + public float maxLimit; + public float swingLimit; + public Vector3 axis; + public Vector3 normalAxis; + public float radiusScale; + public Type colliderType; + public ArrayList children = new ArrayList(); + public float density; + public float summedMass; + } + public Transform root; + public Transform leftHips; + public Transform leftKnee; + public Transform leftFoot; + public Transform rightHips; + public Transform rightKnee; + public Transform rightFoot; + public Transform leftArm; + public Transform leftElbow; + public Transform rightArm; + public Transform rightElbow; + public Transform middleSpine; + public Transform head; + public float totalMass = 20f; + public float strength; + private Vector3 right = Vector3.right; + private Vector3 up = Vector3.up; + private Vector3 forward = Vector3.forward; + private Vector3 worldRight = Vector3.right; + private Vector3 worldUp = Vector3.up; + private Vector3 worldForward = Vector3.forward; + public bool flipForward; + private ArrayList bones; + private RagdollBuilder.BoneInfo rootBone; + private string CheckConsistency() + { + this.PrepareBones(); + Hashtable hashtable = new Hashtable(); + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.anchor) + { + if (hashtable[boneInfo.anchor] != null) + { + RagdollBuilder.BoneInfo boneInfo2 = (RagdollBuilder.BoneInfo)hashtable[boneInfo.anchor]; + string result = string.Format("{0} and {1} may not be assigned to the same bone.", boneInfo.name, boneInfo2.name); + return result; + } + hashtable[boneInfo.anchor] = boneInfo; + } + } + foreach (RagdollBuilder.BoneInfo boneInfo3 in this.bones) + { + if (boneInfo3.anchor == null) + { + string result = string.Format("{0} has not been assigned yet.\n", boneInfo3.name); + return result; + } + } + return string.Empty; + } + private void OnDrawGizmos() + { + if (this.root) + { + Gizmos.color = Color.red; + Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.right)); + Gizmos.color = Color.green; + Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.up)); + Gizmos.color = Color.blue; + Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.forward)); + } + } + [MenuItem("GameObject/3D Object/Ragdoll...", false, 2000)] + private static void CreateWizard() + { + ScriptableWizard.DisplayWizard("Create Ragdoll"); + } + private void DecomposeVector(out Vector3 normalCompo, out Vector3 tangentCompo, Vector3 outwardDir, Vector3 outwardNormal) + { + outwardNormal = outwardNormal.normalized; + normalCompo = outwardNormal * Vector3.Dot(outwardDir, outwardNormal); + tangentCompo = outwardDir - normalCompo; + } + private void CalculateAxes() + { + if (this.head != null && this.root != null) + { + this.up = RagdollBuilder.CalculateDirectionAxis(this.root.InverseTransformPoint(this.head.position)); + } + if (this.rightElbow != null && this.root != null) + { + Vector3 vector; + Vector3 point; + this.DecomposeVector(out vector, out point, this.root.InverseTransformPoint(this.rightElbow.position), this.up); + this.right = RagdollBuilder.CalculateDirectionAxis(point); + } + this.forward = Vector3.Cross(this.right, this.up); + if (this.flipForward) + { + this.forward = -this.forward; + } + } + private void OnWizardUpdate() + { + base.errorString = this.CheckConsistency(); + this.CalculateAxes(); + if (base.errorString.Length != 0) + { + base.helpString = "Drag all bones from the hierarchy into their slots.\nMake sure your character is in T-Stand.\n"; + } + else + { + base.helpString = "Make sure your character is in T-Stand.\nMake sure the blue axis faces in the same direction the chracter is looking.\nUse flipForward to flip the direction"; + } + base.isValid = (base.errorString.Length == 0); + } + private void PrepareBones() + { + if (this.root) + { + this.worldRight = this.root.TransformDirection(this.right); + this.worldUp = this.root.TransformDirection(this.up); + this.worldForward = this.root.TransformDirection(this.forward); + } + this.bones = new ArrayList(); + this.rootBone = new RagdollBuilder.BoneInfo(); + this.rootBone.name = "Root"; + this.rootBone.anchor = this.root; + this.rootBone.parent = null; + this.rootBone.density = 2.5f; + this.bones.Add(this.rootBone); + this.AddMirroredJoint("Hips", this.leftHips, this.rightHips, "Root", this.worldRight, this.worldForward, -20f, 70f, 30f, typeof(CapsuleCollider), 0.3f, 1.5f); + this.AddMirroredJoint("Knee", this.leftKnee, this.rightKnee, "Hips", this.worldRight, this.worldForward, -80f, 0f, 0f, typeof(CapsuleCollider), 0.25f, 1.5f); + this.AddJoint("Middle Spine", this.middleSpine, "Root", this.worldRight, this.worldForward, -20f, 20f, 10f, null, 1f, 2.5f); + this.AddMirroredJoint("Arm", this.leftArm, this.rightArm, "Middle Spine", this.worldUp, this.worldForward, -70f, 10f, 50f, typeof(CapsuleCollider), 0.25f, 1f); + this.AddMirroredJoint("Elbow", this.leftElbow, this.rightElbow, "Arm", this.worldForward, this.worldUp, -90f, 0f, 0f, typeof(CapsuleCollider), 0.2f, 1f); + this.AddJoint("Head", this.head, "Middle Spine", this.worldRight, this.worldForward, -40f, 25f, 25f, null, 1f, 1f); + } + private void OnWizardCreate() + { + this.Cleanup(); + this.BuildCapsules(); + this.AddBreastColliders(); + this.AddHeadCollider(); + this.BuildBodies(); + this.BuildJoints(); + this.CalculateMass(); + this.CalculateSpringDampers(); + } + private RagdollBuilder.BoneInfo FindBone(string name) + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.name == name) + { + return boneInfo; + } + } + return null; + } + private void AddMirroredJoint(string name, Transform leftAnchor, Transform rightAnchor, string parent, Vector3 worldTwistAxis, Vector3 worldSwingAxis, float minLimit, float maxLimit, float swingLimit, Type colliderType, float radiusScale, float density) + { + this.AddJoint("Left " + name, leftAnchor, parent, worldTwistAxis, worldSwingAxis, minLimit, maxLimit, swingLimit, colliderType, radiusScale, density); + this.AddJoint("Right " + name, rightAnchor, parent, worldTwistAxis, worldSwingAxis, minLimit, maxLimit, swingLimit, colliderType, radiusScale, density); + } + private void AddJoint(string name, Transform anchor, string parent, Vector3 worldTwistAxis, Vector3 worldSwingAxis, float minLimit, float maxLimit, float swingLimit, Type colliderType, float radiusScale, float density) + { + RagdollBuilder.BoneInfo boneInfo = new RagdollBuilder.BoneInfo(); + boneInfo.name = name; + boneInfo.anchor = anchor; + boneInfo.axis = worldTwistAxis; + boneInfo.normalAxis = worldSwingAxis; + boneInfo.minLimit = minLimit; + boneInfo.maxLimit = maxLimit; + boneInfo.swingLimit = swingLimit; + boneInfo.density = density; + boneInfo.colliderType = colliderType; + boneInfo.radiusScale = radiusScale; + if (this.FindBone(parent) != null) + { + boneInfo.parent = this.FindBone(parent); + } + else + { + if (name.StartsWith("Left")) + { + boneInfo.parent = this.FindBone("Left " + parent); + } + else + { + if (name.StartsWith("Right")) + { + boneInfo.parent = this.FindBone("Right " + parent); + } + } + } + boneInfo.parent.children.Add(boneInfo); + this.bones.Add(boneInfo); + } + private void BuildCapsules() + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.colliderType == typeof(CapsuleCollider)) + { + int num; + float num2; + if (boneInfo.children.Count == 1) + { + RagdollBuilder.BoneInfo boneInfo2 = (RagdollBuilder.BoneInfo)boneInfo.children[0]; + Vector3 position = boneInfo2.anchor.position; + RagdollBuilder.CalculateDirection(boneInfo.anchor.InverseTransformPoint(position), out num, out num2); + } + else + { + Vector3 position2 = boneInfo.anchor.position - boneInfo.parent.anchor.position + boneInfo.anchor.position; + RagdollBuilder.CalculateDirection(boneInfo.anchor.InverseTransformPoint(position2), out num, out num2); + if (boneInfo.anchor.GetComponentsInChildren(typeof(Transform)).Length > 1) + { + Bounds bounds = default(Bounds); + Component[] componentsInChildren = boneInfo.anchor.GetComponentsInChildren(typeof(Transform)); + for (int i = 0; i < componentsInChildren.Length; i++) + { + Transform transform = (Transform)componentsInChildren[i]; + bounds.Encapsulate(boneInfo.anchor.InverseTransformPoint(transform.position)); + } + if (num2 > 0f) + { + num2 = bounds.max[num]; + } + else + { + num2 = bounds.min[num]; + } + } + } + CapsuleCollider capsuleCollider = (CapsuleCollider)boneInfo.anchor.gameObject.AddComponent("CapsuleCollider"); + capsuleCollider.direction = num; + Vector3 zero = Vector3.zero; + zero[num] = num2 * 0.5f; + capsuleCollider.center = zero; + capsuleCollider.height = Mathf.Abs(num2); + capsuleCollider.radius = Mathf.Abs(num2 * boneInfo.radiusScale); + } + } + } + private void Cleanup() + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.anchor) + { + Component[] componentsInChildren = boneInfo.anchor.GetComponentsInChildren(typeof(Joint)); + Component[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + Joint obj = (Joint)array[i]; + UnityEngine.Object.DestroyImmediate(obj); + } + Component[] componentsInChildren2 = boneInfo.anchor.GetComponentsInChildren(typeof(Rigidbody)); + Component[] array2 = componentsInChildren2; + for (int j = 0; j < array2.Length; j++) + { + Rigidbody obj2 = (Rigidbody)array2[j]; + UnityEngine.Object.DestroyImmediate(obj2); + } + Component[] componentsInChildren3 = boneInfo.anchor.GetComponentsInChildren(typeof(Collider)); + Component[] array3 = componentsInChildren3; + for (int k = 0; k < array3.Length; k++) + { + Collider obj3 = (Collider)array3[k]; + UnityEngine.Object.DestroyImmediate(obj3); + } + } + } + } + private void BuildBodies() + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + boneInfo.anchor.gameObject.AddComponent("Rigidbody"); + boneInfo.anchor.rigidbody.mass = boneInfo.density; + } + } + private void BuildJoints() + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.parent != null) + { + CharacterJoint characterJoint = (CharacterJoint)boneInfo.anchor.gameObject.AddComponent("CharacterJoint"); + boneInfo.joint = characterJoint; + characterJoint.axis = RagdollBuilder.CalculateDirectionAxis(boneInfo.anchor.InverseTransformDirection(boneInfo.axis)); + characterJoint.swingAxis = RagdollBuilder.CalculateDirectionAxis(boneInfo.anchor.InverseTransformDirection(boneInfo.normalAxis)); + characterJoint.anchor = Vector3.zero; + characterJoint.connectedBody = boneInfo.parent.anchor.rigidbody; + SoftJointLimit softJointLimit = default(SoftJointLimit); + softJointLimit.limit = boneInfo.minLimit; + characterJoint.lowTwistLimit = softJointLimit; + softJointLimit.limit = boneInfo.maxLimit; + characterJoint.highTwistLimit = softJointLimit; + softJointLimit.limit = boneInfo.swingLimit; + characterJoint.swing1Limit = softJointLimit; + softJointLimit.limit = 0f; + characterJoint.swing2Limit = softJointLimit; + } + } + } + private void CalculateMassRecurse(RagdollBuilder.BoneInfo bone) + { + float num = bone.anchor.rigidbody.mass; + foreach (RagdollBuilder.BoneInfo boneInfo in bone.children) + { + this.CalculateMassRecurse(boneInfo); + num += boneInfo.summedMass; + } + bone.summedMass = num; + } + private void CalculateMass() + { + this.CalculateMassRecurse(this.rootBone); + float num = this.totalMass / this.rootBone.summedMass; + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + boneInfo.anchor.rigidbody.mass *= num; + } + this.CalculateMassRecurse(this.rootBone); + } + private JointDrive CalculateSpringDamper(float frequency, float damping, float mass) + { + return new JointDrive + { + positionSpring = 9f * frequency * frequency * mass, + positionDamper = 4.5f * frequency * damping * mass + }; + } + private void CalculateSpringDampers() + { + foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) + { + if (boneInfo.joint) + { + boneInfo.joint.rotationDrive = this.CalculateSpringDamper(this.strength / 100f, 1f, boneInfo.summedMass); + } + } + } + private static void CalculateDirection(Vector3 point, out int direction, out float distance) + { + direction = 0; + if (Mathf.Abs(point[1]) > Mathf.Abs(point[0])) + { + direction = 1; + } + if (Mathf.Abs(point[2]) > Mathf.Abs(point[direction])) + { + direction = 2; + } + distance = point[direction]; + } + private static Vector3 CalculateDirectionAxis(Vector3 point) + { + int index = 0; + float num; + RagdollBuilder.CalculateDirection(point, out index, out num); + Vector3 zero = Vector3.zero; + if (num > 0f) + { + zero[index] = 1f; + } + else + { + zero[index] = -1f; + } + return zero; + } + private static int SmallestComponent(Vector3 point) + { + int num = 0; + if (Mathf.Abs(point[1]) < Mathf.Abs(point[0])) + { + num = 1; + } + if (Mathf.Abs(point[2]) < Mathf.Abs(point[num])) + { + num = 2; + } + return num; + } + private static int LargestComponent(Vector3 point) + { + int num = 0; + if (Mathf.Abs(point[1]) > Mathf.Abs(point[0])) + { + num = 1; + } + if (Mathf.Abs(point[2]) > Mathf.Abs(point[num])) + { + num = 2; + } + return num; + } + private static int SecondLargestComponent(Vector3 point) + { + int num = RagdollBuilder.SmallestComponent(point); + int num2 = RagdollBuilder.LargestComponent(point); + if (num < num2) + { + int num3 = num2; + num2 = num; + num = num3; + } + if (num == 0 && num2 == 1) + { + return 2; + } + if (num == 0 && num2 == 2) + { + return 1; + } + return 0; + } + private Bounds Clip(Bounds bounds, Transform relativeTo, Transform clipTransform, bool below) + { + int index = RagdollBuilder.LargestComponent(bounds.size); + if (Vector3.Dot(this.worldUp, relativeTo.TransformPoint(bounds.max)) > Vector3.Dot(this.worldUp, relativeTo.TransformPoint(bounds.min)) == below) + { + Vector3 min = bounds.min; + min[index] = relativeTo.InverseTransformPoint(clipTransform.position)[index]; + bounds.min = min; + } + else + { + Vector3 max = bounds.max; + max[index] = relativeTo.InverseTransformPoint(clipTransform.position)[index]; + bounds.max = max; + } + return bounds; + } + private Bounds GetBreastBounds(Transform relativeTo) + { + Bounds result = default(Bounds); + result.Encapsulate(relativeTo.InverseTransformPoint(this.leftHips.position)); + result.Encapsulate(relativeTo.InverseTransformPoint(this.rightHips.position)); + result.Encapsulate(relativeTo.InverseTransformPoint(this.leftArm.position)); + result.Encapsulate(relativeTo.InverseTransformPoint(this.rightArm.position)); + Vector3 size = result.size; + size[RagdollBuilder.SmallestComponent(result.size)] = size[RagdollBuilder.LargestComponent(result.size)] / 2f; + result.size = size; + return result; + } + private void AddBreastColliders() + { + if (this.middleSpine != null && this.root != null) + { + Bounds bounds = this.Clip(this.GetBreastBounds(this.root), this.root, this.middleSpine, false); + BoxCollider boxCollider = (BoxCollider)this.root.gameObject.AddComponent("BoxCollider"); + boxCollider.center = bounds.center; + boxCollider.size = bounds.size; + bounds = this.Clip(this.GetBreastBounds(this.middleSpine), this.middleSpine, this.middleSpine, true); + boxCollider = (BoxCollider)this.middleSpine.gameObject.AddComponent("BoxCollider"); + boxCollider.center = bounds.center; + boxCollider.size = bounds.size; + } + else + { + Bounds bounds2 = default(Bounds); + bounds2.Encapsulate(this.root.InverseTransformPoint(this.leftHips.position)); + bounds2.Encapsulate(this.root.InverseTransformPoint(this.rightHips.position)); + bounds2.Encapsulate(this.root.InverseTransformPoint(this.leftArm.position)); + bounds2.Encapsulate(this.root.InverseTransformPoint(this.rightArm.position)); + Vector3 size = bounds2.size; + size[RagdollBuilder.SmallestComponent(bounds2.size)] = size[RagdollBuilder.LargestComponent(bounds2.size)] / 2f; + BoxCollider boxCollider2 = (BoxCollider)this.root.gameObject.AddComponent("BoxCollider"); + boxCollider2.center = bounds2.center; + boxCollider2.size = size; + } + } + private void AddHeadCollider() + { + if (this.head.collider) + { + UnityEngine.Object.Destroy(this.head.collider); + } + float num = Vector3.Distance(this.leftArm.transform.position, this.rightArm.transform.position); + num /= 4f; + SphereCollider sphereCollider = (SphereCollider)this.head.gameObject.AddComponent("SphereCollider"); + sphereCollider.radius = num; + Vector3 zero = Vector3.zero; + int index; + float num2; + RagdollBuilder.CalculateDirection(this.head.InverseTransformPoint(this.root.position), out index, out num2); + if (num2 > 0f) + { + zero[index] = -num; + } + else + { + zero[index] = num; + } + sphereCollider.center = zero; + } + } +} diff --git a/UnityEditor/UnityEditor/RangeDrawer.cs b/UnityEditor/UnityEditor/RangeDrawer.cs new file mode 100644 index 00000000..fdc84d8f --- /dev/null +++ b/UnityEditor/UnityEditor/RangeDrawer.cs @@ -0,0 +1,28 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomPropertyDrawer(typeof(RangeAttribute))] + internal sealed class RangeDrawer : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + RangeAttribute rangeAttribute = (RangeAttribute)base.attribute; + if (property.propertyType == SerializedPropertyType.Float) + { + EditorGUI.Slider(position, property, rangeAttribute.min, rangeAttribute.max, label); + } + else + { + if (property.propertyType == SerializedPropertyType.Integer) + { + EditorGUI.IntSlider(position, property, (int)rangeAttribute.min, (int)rangeAttribute.max, label); + } + else + { + EditorGUI.LabelField(position, label.text, "Use Range with float or int."); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/RectHandles.cs b/UnityEditor/UnityEditor/RectHandles.cs new file mode 100644 index 00000000..7d22eb11 --- /dev/null +++ b/UnityEditor/UnityEditor/RectHandles.cs @@ -0,0 +1,278 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class RectHandles + { + private class Styles + { + public readonly GUIStyle dragdot = "U2D.dragDot"; + public readonly GUIStyle pivotdot = "U2D.pivotDot"; + public readonly GUIStyle dragdotactive = "U2D.dragDotActive"; + public readonly GUIStyle pivotdotactive = "U2D.pivotDotActive"; + } + private static RectHandles.Styles s_Styles; + private static Vector2 s_StartMousePosition; + private static Vector2 s_CurrentMousePosition; + private static Vector3 s_StartPosition; + private static float s_StartRotation; + private static float s_RotationDist; + private static int s_LastCursorId = 0; + private static Vector3[] s_TempVectors = new Vector3[0]; + internal static bool RaycastGUIPointToWorldHit(Vector2 guiPoint, Plane plane, out Vector3 hit) + { + Ray ray = HandleUtility.GUIPointToWorldRay(guiPoint); + float distance = 0f; + bool flag = plane.Raycast(ray, out distance); + hit = ((!flag) ? Vector3.zero : ray.GetPoint(distance)); + return flag; + } + internal static void DetectCursorChange(int id) + { + if (HandleUtility.nearestControl == id) + { + RectHandles.s_LastCursorId = id; + Event.current.Use(); + } + else + { + if (RectHandles.s_LastCursorId == id) + { + RectHandles.s_LastCursorId = 0; + Event.current.Use(); + } + } + } + internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) + { + return RectHandles.SideSlider(id, position, sideVector, direction, size, drawFunc, snap, 0f); + } + internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap, float bias) + { + Event current = Event.current; + Vector3 normalized = Vector3.Cross(sideVector, direction).normalized; + Vector3 vector = Handles.Slider2D(id, position, normalized, direction, sideVector, 0f, drawFunc, Vector2.one * snap); + vector = position + Vector3.Project(vector - position, direction); + EventType type = current.type; + if (type != EventType.Repaint) + { + if (type != EventType.Layout) + { + if (type == EventType.MouseMove) + { + RectHandles.DetectCursorChange(id); + } + } + else + { + Vector3 normalized2 = sideVector.normalized; + HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position + sideVector * 0.5f - normalized2 * size * 2f, position - sideVector * 0.5f + normalized2 * size * 2f) - bias); + } + } + else + { + if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) + { + RectHandles.HandleDirectionalCursor(position, normalized, direction); + } + } + return vector; + } + internal static Vector3 CornerSlider(int id, Vector3 cornerPos, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + Event current = Event.current; + Vector3 result = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, snap); + EventType type = current.type; + if (type != EventType.MouseMove) + { + if (type == EventType.Repaint) + { + if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) + { + RectHandles.HandleDirectionalCursor(cornerPos, handleDir, outwardsDir1 + outwardsDir2); + } + } + } + else + { + RectHandles.DetectCursorChange(id); + } + return result; + } + private static void HandleDirectionalCursor(Vector3 handlePosition, Vector3 handlePlaneNormal, Vector3 direction) + { + Vector2 mousePosition = Event.current.mousePosition; + Plane plane = new Plane(handlePlaneNormal, handlePosition); + Vector3 worldPos; + if (RectHandles.RaycastGUIPointToWorldHit(mousePosition, plane, out worldPos)) + { + Vector2 direction2 = RectHandles.WorldToScreenSpaceDir(worldPos, direction); + Rect position = new Rect(mousePosition.x - 100f, mousePosition.y - 100f, 200f, 200f); + EditorGUIUtility.AddCursorRect(position, RectHandles.GetScaleCursor(direction2)); + } + } + public static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis) + { + dirA = Vector3.ProjectOnPlane(dirA, axis); + dirB = Vector3.ProjectOnPlane(dirB, axis); + float num = Vector3.Angle(dirA, dirB); + return num * (float)((Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) >= 0f) ? 1 : -1); + } + public static float RotationSlider(int id, Vector3 cornerPos, float rotation, Vector3 pivot, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + Vector3 b = outwardsDir1 + outwardsDir2; + Vector2 vector = HandleUtility.WorldToGUIPoint(cornerPos); + Vector2 b2 = (HandleUtility.WorldToGUIPoint(cornerPos + b) - vector).normalized * 15f; + RectHandles.RaycastGUIPointToWorldHit(vector + b2, new Plane(handleDir, cornerPos), out cornerPos); + Event current = Event.current; + Vector3 a = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, Vector2.zero); + if (current.type == EventType.MouseMove) + { + RectHandles.DetectCursorChange(id); + } + if (current.type == EventType.Repaint && ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id)) + { + Rect position = new Rect(current.mousePosition.x - 100f, current.mousePosition.y - 100f, 200f, 200f); + EditorGUIUtility.AddCursorRect(position, MouseCursor.RotateArrow); + } + return rotation - RectHandles.AngleAroundAxis(a - pivot, cornerPos - pivot, handleDir); + } + private static Vector2 WorldToScreenSpaceDir(Vector3 worldPos, Vector3 worldDir) + { + Vector3 b = HandleUtility.WorldToGUIPoint(worldPos); + Vector3 a = HandleUtility.WorldToGUIPoint(worldPos + worldDir); + Vector2 result = a - b; + result.y *= -1f; + return result; + } + private static MouseCursor GetScaleCursor(Vector2 direction) + { + float num = Mathf.Atan2(direction.x, direction.y) * 57.29578f; + if (num < 0f) + { + num = 360f + num; + } + if (num < 27.5f) + { + return MouseCursor.ResizeVertical; + } + if (num < 72.5f) + { + return MouseCursor.ResizeUpRight; + } + if (num < 117.5f) + { + return MouseCursor.ResizeHorizontal; + } + if (num < 162.5f) + { + return MouseCursor.ResizeUpLeft; + } + if (num < 207.5f) + { + return MouseCursor.ResizeVertical; + } + if (num < 252.5f) + { + return MouseCursor.ResizeUpRight; + } + if (num < 297.5f) + { + return MouseCursor.ResizeHorizontal; + } + if (num < 342.5f) + { + return MouseCursor.ResizeUpLeft; + } + return MouseCursor.ResizeVertical; + } + public static void RectScalingCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (RectHandles.s_Styles == null) + { + RectHandles.s_Styles = new RectHandles.Styles(); + } + RectHandles.DrawImageBasedCap(controlID, position, rotation, size, RectHandles.s_Styles.dragdot, RectHandles.s_Styles.dragdotactive); + } + public static void PivotCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (RectHandles.s_Styles == null) + { + RectHandles.s_Styles = new RectHandles.Styles(); + } + RectHandles.DrawImageBasedCap(controlID, position, rotation, size, RectHandles.s_Styles.pivotdot, RectHandles.s_Styles.pivotdotactive); + } + private static void DrawImageBasedCap(int controlID, Vector3 position, Quaternion rotation, float size, GUIStyle normal, GUIStyle active) + { + if (Camera.current && Vector3.Dot(position - Camera.current.transform.position, Camera.current.transform.forward) < 0f) + { + return; + } + Vector3 vector = HandleUtility.WorldToGUIPoint(position); + Handles.BeginGUI(); + float fixedWidth = normal.fixedWidth; + float fixedHeight = normal.fixedHeight; + Rect position2 = new Rect(vector.x - fixedWidth / 2f, vector.y - fixedHeight / 2f, fixedWidth, fixedHeight); + if (GUIUtility.hotControl == controlID) + { + active.Draw(position2, GUIContent.none, controlID); + } + else + { + normal.Draw(position2, GUIContent.none, controlID); + } + Handles.EndGUI(); + } + public static void RenderRectWithShadow(bool active, params Vector3[] corners) + { + Vector3[] points = new Vector3[] + { + corners[0], + corners[1], + corners[2], + corners[3], + corners[0] + }; + Color color = Handles.color; + Handles.color = new Color(1f, 1f, 1f, (!active) ? 0.5f : 1f); + RectHandles.DrawPolyLineWithShadow(new Color(0f, 0f, 0f, (!active) ? 0.5f : 1f), new Vector2(1f, -1f), points); + Handles.color = color; + } + public static void DrawPolyLineWithShadow(Color shadowColor, Vector2 screenOffset, params Vector3[] points) + { + Camera current = Camera.current; + if (!current || Event.current.type != EventType.Repaint) + { + return; + } + if (RectHandles.s_TempVectors.Length != points.Length) + { + RectHandles.s_TempVectors = new Vector3[points.Length]; + } + for (int i = 0; i < points.Length; i++) + { + RectHandles.s_TempVectors[i] = current.ScreenToWorldPoint(current.WorldToScreenPoint(points[i]) + screenOffset); + } + Color color = Handles.color; + shadowColor.a *= color.a; + Handles.color = shadowColor; + Handles.DrawPolyLine(RectHandles.s_TempVectors); + Handles.color = color; + Handles.DrawPolyLine(points); + } + public static void DrawDottedLineWithShadow(Color shadowColor, Vector2 screenOffset, Vector3 p1, Vector3 p2, float screenSpaceSize) + { + Camera current = Camera.current; + if (!current || Event.current.type != EventType.Repaint) + { + return; + } + Color color = Handles.color; + shadowColor.a *= color.a; + Handles.color = shadowColor; + Handles.DrawDottedLine(current.ScreenToWorldPoint(current.WorldToScreenPoint(p1) + screenOffset), current.ScreenToWorldPoint(current.WorldToScreenPoint(p2) + screenOffset), screenSpaceSize); + Handles.color = color; + Handles.DrawDottedLine(p1, p2, screenSpaceSize); + } + } +} diff --git a/UnityEditor/UnityEditor/RectSelection.cs b/UnityEditor/UnityEditor/RectSelection.cs new file mode 100644 index 00000000..69a9d3ce --- /dev/null +++ b/UnityEditor/UnityEditor/RectSelection.cs @@ -0,0 +1,315 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class RectSelection + { + private enum SelectionType + { + Normal, + Additive, + Subtractive + } + private Vector2 m_SelectStartPoint; + private Vector2 m_SelectMousePoint; + private UnityEngine.Object[] m_SelectionStart; + private bool m_RectSelecting; + private Dictionary m_LastSelection; + private UnityEngine.Object[] m_CurrentSelection; + private EditorWindow m_Window; + private static int s_RectSelectionID = GUIUtility.GetPermanentControlID(); + public RectSelection(EditorWindow window) + { + this.m_Window = window; + } + public void OnGUI() + { + Event current = Event.current; + Handles.BeginGUI(); + Vector2 mousePosition = current.mousePosition; + int num = RectSelection.s_RectSelectionID; + EventType typeForControl = current.GetTypeForControl(num); + switch (typeForControl) + { + case EventType.MouseDown: + if (HandleUtility.nearestControl == num && current.button == 0) + { + if (SceneView.lastActiveSceneView.m_OneClickDragObject == null && !current.shift && !EditorGUI.actionKey) + { + this.TryOneClickDrag(); + } + GUIUtility.hotControl = num; + this.m_SelectStartPoint = mousePosition; + this.m_SelectionStart = Selection.objects; + this.m_RectSelecting = false; + } + goto IL_518; + case EventType.MouseUp: + if (GUIUtility.hotControl == num && current.button == 0) + { + GUIUtility.hotControl = 0; + if (this.m_RectSelecting) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendCommandsOnModifierKeys)); + this.m_RectSelecting = false; + this.m_SelectionStart = new UnityEngine.Object[0]; + current.Use(); + } + else + { + UnityEngine.Object @object = HandleUtility.PickGameObject(Event.current.mousePosition, true); + if (current.shift) + { + if (Selection.activeGameObject == @object) + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Subtractive, this.m_RectSelecting); + } + else + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Additive, this.m_RectSelecting); + } + } + else + { + if (EditorGUI.actionKey && @object != null) + { + if (Selection.Contains(@object)) + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Subtractive, this.m_RectSelecting); + } + else + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Additive, this.m_RectSelecting); + } + } + else + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Normal, this.m_RectSelecting); + } + } + current.Use(); + } + } + goto IL_518; + case EventType.MouseMove: + case EventType.KeyDown: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_4C: + if (typeForControl != EventType.ExecuteCommand) + { + goto IL_518; + } + if (num == GUIUtility.hotControl && current.commandName == "ModifierKeysChanged") + { + if (current.shift) + { + RectSelection.UpdateSelection(this.m_SelectionStart, this.m_CurrentSelection, RectSelection.SelectionType.Additive, this.m_RectSelecting); + } + else + { + if (EditorGUI.actionKey) + { + RectSelection.UpdateSelection(this.m_SelectionStart, this.m_CurrentSelection, RectSelection.SelectionType.Subtractive, this.m_RectSelecting); + } + else + { + RectSelection.UpdateSelection(this.m_SelectionStart, this.m_CurrentSelection, RectSelection.SelectionType.Normal, this.m_RectSelecting); + } + } + current.Use(); + } + goto IL_518; + case EventType.MouseDrag: + if (GUIUtility.hotControl == num) + { + if (!this.m_RectSelecting && (mousePosition - this.m_SelectStartPoint).magnitude > 6f) + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendCommandsOnModifierKeys)); + this.m_RectSelecting = true; + this.m_LastSelection = null; + this.m_CurrentSelection = null; + } + if (this.m_RectSelecting) + { + this.m_SelectMousePoint = new Vector2(Mathf.Max(mousePosition.x, 0f), Mathf.Max(mousePosition.y, 0f)); + GameObject[] array = HandleUtility.PickRectObjects(EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint)); + this.m_CurrentSelection = array; + bool flag = false; + if (this.m_LastSelection == null) + { + this.m_LastSelection = new Dictionary(); + flag = true; + } + flag |= (this.m_LastSelection.Count != array.Length); + if (!flag) + { + Dictionary dictionary = new Dictionary(array.Length); + GameObject[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + GameObject key = array2[i]; + dictionary.Add(key, false); + } + foreach (GameObject current2 in this.m_LastSelection.Keys) + { + if (!dictionary.ContainsKey(current2)) + { + flag = true; + break; + } + } + } + if (flag) + { + this.m_LastSelection = new Dictionary(array.Length); + GameObject[] array3 = array; + for (int j = 0; j < array3.Length; j++) + { + GameObject key2 = array3[j]; + this.m_LastSelection.Add(key2, false); + } + if (array != null) + { + if (current.shift) + { + RectSelection.UpdateSelection(this.m_SelectionStart, array, RectSelection.SelectionType.Additive, this.m_RectSelecting); + } + else + { + if (EditorGUI.actionKey) + { + RectSelection.UpdateSelection(this.m_SelectionStart, array, RectSelection.SelectionType.Subtractive, this.m_RectSelecting); + } + else + { + RectSelection.UpdateSelection(this.m_SelectionStart, array, RectSelection.SelectionType.Normal, this.m_RectSelecting); + } + } + } + } + } + current.Use(); + } + goto IL_518; + case EventType.Repaint: + if (GUIUtility.hotControl == num && this.m_RectSelecting) + { + EditorStyles.selectionRect.Draw(EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint), GUIContent.none, false, false, false, false); + } + goto IL_518; + case EventType.Layout: + if (!Tools.viewToolActive) + { + HandleUtility.AddDefaultControl(num); + } + goto IL_518; + } + goto IL_4C; + IL_518: + Handles.EndGUI(); + } + private static void UpdateSelection(UnityEngine.Object[] existingSelection, UnityEngine.Object newObject, RectSelection.SelectionType type, bool isRectSelection) + { + UnityEngine.Object[] newObjects; + if (newObject == null) + { + newObjects = new UnityEngine.Object[0]; + } + else + { + newObjects = new UnityEngine.Object[] + { + newObject + }; + } + RectSelection.UpdateSelection(existingSelection, newObjects, type, isRectSelection); + } + private static void UpdateSelection(UnityEngine.Object[] existingSelection, UnityEngine.Object[] newObjects, RectSelection.SelectionType type, bool isRectSelection) + { + switch (type) + { + case RectSelection.SelectionType.Additive: + if (newObjects.Length > 0) + { + UnityEngine.Object[] array = new UnityEngine.Object[existingSelection.Length + newObjects.Length]; + Array.Copy(existingSelection, array, existingSelection.Length); + for (int i = 0; i < newObjects.Length; i++) + { + array[existingSelection.Length + i] = newObjects[i]; + } + if (!isRectSelection) + { + Selection.activeObject = newObjects[0]; + } + else + { + Selection.activeObject = array[0]; + } + Selection.objects = array; + } + else + { + Selection.objects = existingSelection; + } + return; + case RectSelection.SelectionType.Subtractive: + { + Dictionary dictionary = new Dictionary(existingSelection.Length); + for (int j = 0; j < existingSelection.Length; j++) + { + GameObject key = (GameObject)existingSelection[j]; + dictionary.Add(key, false); + } + for (int k = 0; k < newObjects.Length; k++) + { + GameObject key2 = (GameObject)newObjects[k]; + if (dictionary.ContainsKey(key2)) + { + dictionary.Remove(key2); + } + } + UnityEngine.Object[] array = new UnityEngine.Object[dictionary.Keys.Count]; + dictionary.Keys.CopyTo(array, 0); + Selection.objects = array; + return; + } + } + Selection.objects = newObjects; + } + private void TryOneClickDrag() + { + EventType type = Event.current.type; + if (type == EventType.MouseDown) + { + UnityEngine.Object @object = HandleUtility.PickGameObject(Event.current.mousePosition, true); + if (@object) + { + GameObject gameObject = @object as GameObject; + bool flag = false; + GameObject[] gameObjects = Selection.gameObjects; + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject y = gameObjects[i]; + if (gameObject == y) + { + flag = true; + break; + } + } + if (!flag && gameObject.GetComponent() != null) + { + RectSelection.UpdateSelection(this.m_SelectionStart, @object, RectSelection.SelectionType.Normal, this.m_RectSelecting); + SceneView.lastActiveSceneView.m_OneClickDragObject = @object; + Event.current.Use(); + } + } + } + } + internal void SendCommandsOnModifierKeys() + { + this.m_Window.SendEvent(EditorGUIUtility.CommandEvent("ModifierKeysChanged")); + } + } +} diff --git a/UnityEditor/UnityEditor/RectTool.cs b/UnityEditor/UnityEditor/RectTool.cs new file mode 100644 index 00000000..2a80d13b --- /dev/null +++ b/UnityEditor/UnityEditor/RectTool.cs @@ -0,0 +1,617 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class RectTool : ManipulationTool + { + internal const string kChangingLeft = "ChangingLeft"; + internal const string kChangingRight = "ChangingRight"; + internal const string kChangingTop = "ChangingTop"; + internal const string kChangingBottom = "ChangingBottom"; + internal const string kChangingPosX = "ChangingPosX"; + internal const string kChangingPosY = "ChangingPosY"; + internal const string kChangingWidth = "ChangingWidth"; + internal const string kChangingHeight = "ChangingHeight"; + internal const string kChangingPivot = "ChangingPivot"; + private const float kMinVisibleSize = 0.2f; + private static RectTool s_Instance; + private static int s_ResizeHandlesHash = "ResizeHandles".GetHashCode(); + private static int s_RotationHandlesHash = "RotationHandles".GetHashCode(); + private static int s_MoveHandleHash = "MoveHandle".GetHashCode(); + private static int s_PivotHandleHash = "PivotHandle".GetHashCode(); + private static Rect s_StartRect = default(Rect); + private static Vector3 s_StartMouseWorldPos; + private static Vector3 s_StartPosition; + private static Vector2 s_StartMousePos; + private static Vector3 s_StartRectPosition; + private static Vector2 s_CurrentMousePos; + private static bool s_Moving = false; + private static int s_LockAxis = -1; + public static void OnGUI(SceneView view) + { + if (RectTool.s_Instance == null) + { + RectTool.s_Instance = new RectTool(); + } + RectTool.s_Instance.OnToolGUI(view); + } + public static Vector2 GetLocalRectPoint(Rect rect, int index) + { + switch (index) + { + case 0: + return new Vector2(rect.xMin, rect.yMax); + case 1: + return new Vector2(rect.xMax, rect.yMax); + case 2: + return new Vector2(rect.xMax, rect.yMin); + case 3: + return new Vector2(rect.xMin, rect.yMin); + default: + return Vector3.zero; + } + } + public override void ToolGUI(SceneView view, Vector3 handlePosition, bool isStatic) + { + Rect handleRect = Tools.handleRect; + Quaternion handleRectRotation = Tools.handleRectRotation; + Vector3[] array = new Vector3[4]; + for (int i = 0; i < 4; i++) + { + Vector3 point = RectTool.GetLocalRectPoint(handleRect, i); + array[i] = handleRectRotation * point + handlePosition; + } + RectHandles.RenderRectWithShadow(false, array); + Color color = GUI.color; + if (Camera.current) + { + Vector3 planeNormal = (!Camera.current.orthographic) ? (handlePosition + handleRectRotation * handleRect.center - Camera.current.transform.position) : Camera.current.transform.forward; + Vector3 vector = handleRectRotation * Vector3.right * handleRect.width; + Vector3 vector2 = handleRectRotation * Vector3.up * handleRect.height; + float num = Mathf.Sqrt(Vector3.Cross(Vector3.ProjectOnPlane(vector, planeNormal), Vector3.ProjectOnPlane(vector2, planeNormal)).magnitude); + num /= HandleUtility.GetHandleSize(handlePosition); + float num2 = Mathf.Clamp01((num - 0.2f) / 0.2f * 2f); + Color color2 = color; + color2.a *= num2; + GUI.color = color2; + } + Vector3 handlePosition2 = Tools.GetHandlePosition(); + if (!Tools.vertexDragging) + { + RectTransform component = Selection.activeTransform.GetComponent(); + bool flag = Selection.transforms.Length > 1; + bool flag2 = !flag && Tools.pivotMode == PivotMode.Pivot && component != null; + EditorGUI.BeginDisabledGroup(!flag && !flag2); + EditorGUI.BeginChangeCheck(); + Vector3 a = RectTool.PivotHandleGUI(handleRect, handlePosition2, handleRectRotation); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + if (flag) + { + Tools.localHandleOffset += Quaternion.Inverse(Tools.handleRotation) * (a - handlePosition2); + } + else + { + if (flag2) + { + Transform activeTransform = Selection.activeTransform; + Undo.RecordObject(component, "Move Rectangle Pivot"); + Transform transform = (!Tools.rectBlueprintMode || !InternalEditorUtility.SupportsRectLayout(activeTransform)) ? activeTransform : activeTransform.parent; + Vector2 b = transform.InverseTransformVector(a - handlePosition2); + b.x /= component.rect.width; + b.y /= component.rect.height; + Vector2 vector3 = component.pivot + b; + RectTransformEditor.SetPivotSmart(component, vector3.x, 0, true, transform != component.transform); + RectTransformEditor.SetPivotSmart(component, vector3.y, 1, true, transform != component.transform); + } + } + } + EditorGUI.EndDisabledGroup(); + } + TransformManipulator.BeginManipulationHandling(true); + if (!Tools.vertexDragging) + { + EditorGUI.BeginChangeCheck(); + Vector3 pivotPosition = handlePosition; + Vector3 scaleDelta = RectTool.ResizeHandlesGUI(handleRect, handlePosition, handleRectRotation, out pivotPosition); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + TransformManipulator.SetResizeDelta(scaleDelta, pivotPosition, handleRectRotation); + } + bool flag3 = true; + if (Tools.rectBlueprintMode) + { + Transform[] transforms = Selection.transforms; + for (int j = 0; j < transforms.Length; j++) + { + Transform transform2 = transforms[j]; + if (transform2.GetComponent() != null) + { + flag3 = false; + } + } + } + if (flag3) + { + EditorGUI.BeginChangeCheck(); + Quaternion rhs = RectTool.RotationHandlesGUI(handleRect, handlePosition, handleRectRotation); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + float angle; + Vector3 vector4; + (Quaternion.Inverse(handleRectRotation) * rhs).ToAngleAxis(out angle, out vector4); + vector4 = handleRectRotation * vector4; + Undo.RecordObjects(Selection.transforms, "Rotate"); + Transform[] transforms2 = Selection.transforms; + for (int k = 0; k < transforms2.Length; k++) + { + Transform transform3 = transforms2[k]; + transform3.RotateAround(handlePosition, vector4, angle); + if (transform3.parent != null) + { + transform3.SendTransformChangedScale(); + } + } + Tools.handleRotation = Quaternion.AngleAxis(angle, vector4) * Tools.handleRotation; + } + } + } + TransformManipulator.EndManipulationHandling(); + TransformManipulator.BeginManipulationHandling(false); + EditorGUI.BeginChangeCheck(); + Vector3 a2 = RectTool.MoveHandlesGUI(handleRect, handlePosition, handleRectRotation); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + Vector3 positionDelta = a2 - TransformManipulator.mouseDownHandlePosition; + TransformManipulator.SetPositionDelta(positionDelta); + } + TransformManipulator.EndManipulationHandling(); + GUI.color = color; + } + private static Vector3 GetRectPointInWorld(Rect rect, Vector3 pivot, Quaternion rotation, int xHandle, int yHandle) + { + Vector3 point = new Vector2(point.x = Mathf.Lerp(rect.xMin, rect.xMax, (float)xHandle * 0.5f), point.y = Mathf.Lerp(rect.yMin, rect.yMax, (float)yHandle * 0.5f)); + return rotation * point + pivot; + } + private static Vector3 ResizeHandlesGUI(Rect rect, Vector3 pivot, Quaternion rotation, out Vector3 scalePivot) + { + if (Event.current.type == EventType.MouseDown) + { + RectTool.s_StartRect = rect; + } + scalePivot = pivot; + Vector3 result = Vector3.one; + Quaternion rotation2 = Quaternion.Inverse(rotation); + for (int i = 0; i <= 2; i++) + { + for (int j = 0; j <= 2; j++) + { + if (i != 1 || j != 1) + { + Vector3 rectPointInWorld = RectTool.GetRectPointInWorld(RectTool.s_StartRect, pivot, rotation, i, j); + Vector3 rectPointInWorld2 = RectTool.GetRectPointInWorld(rect, pivot, rotation, i, j); + float num = 0.05f * HandleUtility.GetHandleSize(rectPointInWorld2); + int controlID = GUIUtility.GetControlID(RectTool.s_ResizeHandlesHash, FocusType.Passive); + if (GUI.color.a > 0f || GUIUtility.hotControl == controlID) + { + EditorGUI.BeginChangeCheck(); + EventType type = Event.current.type; + Vector3 vector; + if (i == 1 || j == 1) + { + Vector3 sideVector = (i != 1) ? (rotation * Vector3.up * rect.height) : (rotation * Vector3.right * rect.width); + Vector3 direction = (i != 1) ? (rotation * Vector3.right) : (rotation * Vector3.up); + vector = RectHandles.SideSlider(controlID, rectPointInWorld2, sideVector, direction, num, null, 0f); + } + else + { + Vector3 outwardsDir = rotation * Vector3.right * (float)(i - 1); + Vector3 outwardsDir2 = rotation * Vector3.up * (float)(j - 1); + vector = RectHandles.CornerSlider(controlID, rectPointInWorld2, rotation * Vector3.forward, outwardsDir, outwardsDir2, num, new Handles.DrawCapFunction(RectHandles.RectScalingCap), Vector2.zero); + } + bool flag = Selection.transforms.Length == 1 && InternalEditorUtility.SupportsRectLayout(Selection.activeTransform) && Selection.activeTransform.parent.rotation == rotation; + if (flag) + { + Transform activeTransform = Selection.activeTransform; + RectTransform component = activeTransform.GetComponent(); + Transform parent = activeTransform.parent; + RectTransform component2 = parent.GetComponent(); + if (type == EventType.MouseDown && Event.current.type != EventType.MouseDown) + { + RectTransformSnapping.CalculateOffsetSnapValues(parent, activeTransform, component2, component, i, j); + } + } + if (EditorGUI.EndChangeCheck()) + { + ManipulationToolUtility.SetMinDragDifferenceForPos(rectPointInWorld2); + if (flag) + { + Transform parent2 = Selection.activeTransform.parent; + RectTransform component3 = parent2.GetComponent(); + Vector2 snapDistance = Vector2.one * HandleUtility.GetHandleSize(vector) * 0.05f; + snapDistance.x /= (rotation2 * parent2.TransformVector(Vector3.right)).x; + snapDistance.y /= (rotation2 * parent2.TransformVector(Vector3.up)).y; + Vector3 vector2 = parent2.InverseTransformPoint(vector) - component3.rect.min; + Vector3 vector3 = RectTransformSnapping.SnapToGuides(vector2, snapDistance) + Vector3.forward * vector2.z; + ManipulationToolUtility.DisableMinDragDifferenceBasedOnSnapping(vector2, vector3); + vector = parent2.TransformPoint(vector3 + component3.rect.min); + } + bool alt = Event.current.alt; + bool actionKey = EditorGUI.actionKey; + bool flag2 = Event.current.shift && !actionKey; + if (!alt) + { + scalePivot = RectTool.GetRectPointInWorld(RectTool.s_StartRect, pivot, rotation, 2 - i, 2 - j); + } + if (flag2) + { + vector = Vector3.Project(vector - scalePivot, rectPointInWorld - scalePivot) + scalePivot; + } + Vector3 vector4 = rotation2 * (rectPointInWorld - scalePivot); + Vector3 vector5 = rotation2 * (vector - scalePivot); + if (i != 1) + { + result.x = vector5.x / vector4.x; + } + if (j != 1) + { + result.y = vector5.y / vector4.y; + } + if (flag2) + { + float d = (i != 1) ? result.x : result.y; + result = Vector3.one * d; + } + if (actionKey && i == 1) + { + if (Event.current.shift) + { + result.x = (result.z = 1f / Mathf.Sqrt(Mathf.Max(result.y, 0.0001f))); + } + else + { + result.x = 1f / Mathf.Max(result.y, 0.0001f); + } + } + if (flag2) + { + float d2 = (i != 1) ? result.x : result.y; + result = Vector3.one * d2; + } + if (actionKey && i == 1) + { + if (Event.current.shift) + { + result.x = (result.z = 1f / Mathf.Sqrt(Mathf.Max(result.y, 0.0001f))); + } + else + { + result.x = 1f / Mathf.Max(result.y, 0.0001f); + } + } + if (actionKey && j == 1) + { + if (Event.current.shift) + { + result.y = (result.z = 1f / Mathf.Sqrt(Mathf.Max(result.x, 0.0001f))); + } + else + { + result.y = 1f / Mathf.Max(result.x, 0.0001f); + } + } + } + if (i == 0) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingLeft", type); + } + if (i == 2) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingRight", type); + } + if (i != 1) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingWidth", type); + } + if (j == 0) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingBottom", type); + } + if (j == 2) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingTop", type); + } + if (j != 1) + { + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingHeight", type); + } + } + } + } + } + return result; + } + private static Vector3 MoveHandlesGUI(Rect rect, Vector3 pivot, Quaternion rotation) + { + int controlID = GUIUtility.GetControlID(RectTool.s_MoveHandleHash, FocusType.Passive); + Vector3 vector = pivot; + float num = HandleUtility.GetHandleSize(pivot) * 0.2f; + float num2 = 1f - GUI.color.a; + Vector3[] array = new Vector3[] + { + rotation * new Vector2(rect.x, rect.y) + pivot, + rotation * new Vector2(rect.xMax, rect.y) + pivot, + rotation * new Vector2(rect.xMax, rect.yMax) + pivot, + rotation * new Vector2(rect.x, rect.yMax) + pivot + }; + VertexSnapping.HandleKeyAndMouseMove(controlID); + bool flag = Selection.transforms.Length == 1 && InternalEditorUtility.SupportsRectLayout(Selection.activeTransform) && Selection.activeTransform.parent.rotation == rotation; + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + Plane plane = new Plane(array[0], array[1], array[2]); + switch (typeForControl) + { + case EventType.MouseDown: + { + bool flag2 = Tools.vertexDragging || (current.button == 0 && current.modifiers == EventModifiers.None && RectHandles.RaycastGUIPointToWorldHit(current.mousePosition, plane, out RectTool.s_StartMouseWorldPos) && (RectTool.SceneViewDistanceToRectangle(array, current.mousePosition) == 0f || (num2 > 0f && RectTool.SceneViewDistanceToDisc(pivot, rotation * Vector3.forward, num, current.mousePosition) == 0f))); + if (flag2) + { + RectTool.s_StartPosition = pivot; + RectTool.s_StartMousePos = (RectTool.s_CurrentMousePos = current.mousePosition); + RectTool.s_Moving = false; + RectTool.s_LockAxis = -1; + int num3 = controlID; + GUIUtility.keyboardControl = num3; + GUIUtility.hotControl = num3; + EditorGUIUtility.SetWantsMouseJumping(1); + HandleUtility.ignoreRaySnapObjects = null; + current.Use(); + if (flag) + { + Transform activeTransform = Selection.activeTransform; + RectTransform component = activeTransform.GetComponent(); + Transform parent = activeTransform.parent; + RectTransform component2 = parent.GetComponent(); + RectTool.s_StartRectPosition = component.anchoredPosition; + RectTransformSnapping.CalculatePositionSnapValues(parent, activeTransform, component2, component); + } + } + break; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + if (!RectTool.s_Moving) + { + Selection.activeGameObject = HandleUtility.PickGameObject(current.mousePosition, true); + } + GUIUtility.hotControl = 0; + EditorGUIUtility.SetWantsMouseJumping(0); + HandleUtility.ignoreRaySnapObjects = null; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + RectTool.s_CurrentMousePos += current.delta; + if (!RectTool.s_Moving && (RectTool.s_CurrentMousePos - RectTool.s_StartMousePos).magnitude > 3f) + { + RectTool.s_Moving = true; + RectHandles.RaycastGUIPointToWorldHit(RectTool.s_CurrentMousePos, plane, out RectTool.s_StartMouseWorldPos); + } + if (RectTool.s_Moving) + { + if (Tools.vertexDragging) + { + if (HandleUtility.ignoreRaySnapObjects == null) + { + Handles.SetupIgnoreRaySnapObjects(); + } + Vector3 vector2; + if (HandleUtility.FindNearestVertex(RectTool.s_CurrentMousePos, null, out vector2)) + { + vector = vector2; + GUI.changed = true; + } + ManipulationToolUtility.minDragDifference = Vector2.zero; + } + else + { + ManipulationToolUtility.SetMinDragDifferenceForPos(pivot); + Vector3 a; + if (RectHandles.RaycastGUIPointToWorldHit(RectTool.s_CurrentMousePos, plane, out a)) + { + Vector3 vector3 = a - RectTool.s_StartMouseWorldPos; + if (current.shift) + { + vector3 = Quaternion.Inverse(rotation) * vector3; + if (RectTool.s_LockAxis == -1) + { + RectTool.s_LockAxis = ((Mathf.Abs(vector3.x) <= Mathf.Abs(vector3.y)) ? 1 : 0); + } + vector3[1 - RectTool.s_LockAxis] = 0f; + vector3 = rotation * vector3; + } + else + { + RectTool.s_LockAxis = -1; + } + if (flag) + { + Transform parent2 = Selection.activeTransform.parent; + Vector3 vector4 = RectTool.s_StartRectPosition + parent2.InverseTransformVector(vector3); + vector4.z = 0f; + Quaternion rotation2 = Quaternion.Inverse(rotation); + Vector2 snapDistance = Vector2.one * HandleUtility.GetHandleSize(vector) * 0.05f; + snapDistance.x /= (rotation2 * parent2.TransformVector(Vector3.right)).x; + snapDistance.y /= (rotation2 * parent2.TransformVector(Vector3.up)).y; + Vector3 vector5 = RectTransformSnapping.SnapToGuides(vector4, snapDistance); + ManipulationToolUtility.DisableMinDragDifferenceBasedOnSnapping(vector4, vector5); + vector3 = parent2.TransformVector(vector5 - RectTool.s_StartRectPosition); + } + vector = RectTool.s_StartPosition + vector3; + GUI.changed = true; + } + } + } + current.Use(); + } + break; + case EventType.Repaint: + if (Tools.vertexDragging) + { + RectHandles.RectScalingCap(controlID, pivot, rotation, 1f); + } + else + { + Handles.color = Handles.secondaryColor * new Color(1f, 1f, 1f, 1.5f * num2); + Handles.CircleCap(controlID, pivot, rotation, num); + Handles.color = Handles.secondaryColor * new Color(1f, 1f, 1f, 0.3f * num2); + Handles.DrawSolidDisc(pivot, rotation * Vector3.forward, num); + } + break; + } + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingPosX", typeForControl); + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingLeft", typeForControl); + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingRight", typeForControl); + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingPosY", typeForControl); + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingTop", typeForControl); + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingBottom", typeForControl); + return vector; + } + private static float SceneViewDistanceToDisc(Vector3 center, Vector3 normal, float radius, Vector2 mousePos) + { + Plane plane = new Plane(normal, center); + Ray ray = HandleUtility.GUIPointToWorldRay(mousePos); + float distance; + if (plane.Raycast(ray, out distance)) + { + Vector3 point = ray.GetPoint(distance); + return Mathf.Max(0f, (point - center).magnitude - radius); + } + return float.PositiveInfinity; + } + private static float SceneViewDistanceToRectangle(Vector3[] worldPoints, Vector2 mousePos) + { + Vector2[] array = new Vector2[4]; + for (int i = 0; i < 4; i++) + { + array[i] = HandleUtility.WorldToGUIPoint(worldPoints[i]); + } + return RectTool.DistanceToRectangle(array, mousePos); + } + private static float DistancePointToLineSegment(Vector2 point, Vector2 a, Vector2 b) + { + float sqrMagnitude = (b - a).sqrMagnitude; + if (sqrMagnitude == 0f) + { + return (point - a).magnitude; + } + float num = Vector2.Dot(point - a, b - a) / sqrMagnitude; + if (num < 0f) + { + return (point - a).magnitude; + } + if (num > 1f) + { + return (point - b).magnitude; + } + Vector2 b2 = a + num * (b - a); + return (point - b2).magnitude; + } + private static float DistanceToRectangle(Vector2[] screenPoints, Vector2 mousePos) + { + bool flag = false; + int num = 4; + for (int i = 0; i < 5; i++) + { + Vector3 vector = screenPoints[i % 4]; + Vector3 vector2 = screenPoints[num % 4]; + if (vector.y > mousePos.y != vector2.y > mousePos.y && mousePos.x < (vector2.x - vector.x) * (mousePos.y - vector.y) / (vector2.y - vector.y) + vector.x) + { + flag = !flag; + } + num = i; + } + if (!flag) + { + float num2 = -1f; + for (int j = 0; j < 4; j++) + { + Vector3 v = screenPoints[j]; + Vector3 v2 = screenPoints[(j + 1) % 4]; + float num3 = RectTool.DistancePointToLineSegment(mousePos, v, v2); + if (num3 < num2 || num2 < 0f) + { + num2 = num3; + } + } + return num2; + } + return 0f; + } + private static Quaternion RotationHandlesGUI(Rect rect, Vector3 pivot, Quaternion rotation) + { + Vector3 eulerAngles = rotation.eulerAngles; + for (int i = 0; i <= 2; i += 2) + { + for (int j = 0; j <= 2; j += 2) + { + Vector3 rectPointInWorld = RectTool.GetRectPointInWorld(rect, pivot, rotation, i, j); + float handleSize = 0.05f * HandleUtility.GetHandleSize(rectPointInWorld); + int controlID = GUIUtility.GetControlID(RectTool.s_RotationHandlesHash, FocusType.Passive); + if (GUI.color.a > 0f || GUIUtility.hotControl == controlID) + { + EditorGUI.BeginChangeCheck(); + Vector3 outwardsDir = rotation * Vector3.right * (float)(i - 1); + Vector3 outwardsDir2 = rotation * Vector3.up * (float)(j - 1); + float num = RectHandles.RotationSlider(controlID, rectPointInWorld, eulerAngles.z, pivot, rotation * Vector3.forward, outwardsDir, outwardsDir2, handleSize, null, Vector2.zero); + if (EditorGUI.EndChangeCheck()) + { + if (Event.current.shift) + { + num = Mathf.Round((num - eulerAngles.z) / 15f) * 15f + eulerAngles.z; + } + eulerAngles.z = num; + rotation = Quaternion.Euler(eulerAngles); + } + } + } + } + return rotation; + } + private static Vector3 PivotHandleGUI(Rect rect, Vector3 pivot, Quaternion rotation) + { + int controlID = GUIUtility.GetControlID(RectTool.s_PivotHandleHash, FocusType.Passive); + EventType typeForControl = Event.current.GetTypeForControl(controlID); + if (GUI.color.a > 0f || GUIUtility.hotControl == controlID) + { + EventType eventType = typeForControl; + EditorGUI.BeginChangeCheck(); + Vector3 a = Handles.Slider2D(controlID, pivot, rotation * Vector3.forward, rotation * Vector3.right, rotation * Vector3.up, HandleUtility.GetHandleSize(pivot) * 0.1f, new Handles.DrawCapFunction(RectHandles.PivotCap), Vector2.zero); + if (eventType == EventType.MouseDown && GUIUtility.hotControl == controlID) + { + RectTransformSnapping.CalculatePivotSnapValues(rect, pivot, rotation); + } + if (EditorGUI.EndChangeCheck()) + { + Vector2 vector = Quaternion.Inverse(rotation) * (a - pivot); + vector.x /= rect.width; + vector.y /= rect.height; + Vector2 vector2 = new Vector2(-rect.x / rect.width, -rect.y / rect.height); + Vector2 vector3 = vector2 + vector; + Vector2 snapDistance = HandleUtility.GetHandleSize(pivot) * 0.05f * new Vector2(1f / rect.width, 1f / rect.height); + vector3 = RectTransformSnapping.SnapToGuides(vector3, snapDistance); + vector = vector3 - vector2; + vector.x *= rect.width; + vector.y *= rect.height; + pivot += rotation * vector; + } + } + ManipulationToolUtility.DetectDraggingBasedOnMouseDownUp("ChangingPivot", typeForControl); + return pivot; + } + } +} diff --git a/UnityEditor/UnityEditor/RectTransformEditor.cs b/UnityEditor/UnityEditor/RectTransformEditor.cs new file mode 100644 index 00000000..4ada847b --- /dev/null +++ b/UnityEditor/UnityEditor/RectTransformEditor.cs @@ -0,0 +1,1316 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(RectTransform))] + internal class RectTransformEditor : Editor + { + private class Styles + { + public GUIStyle lockStyle = EditorStyles.miniButton; + public GUIStyle measuringLabelStyle = new GUIStyle("PreOverlayLabel"); + public GUIContent anchorsContent = new GUIContent("Anchors"); + public GUIContent anchorMinContent = new GUIContent("Min", "The normalized position in the parent rectangle that the lower left corner is anchored to."); + public GUIContent anchorMaxContent = new GUIContent("Max", "The normalized position in the parent rectangle that the upper right corner is anchored to."); + public GUIContent positionContent = new GUIContent("Position", "The local position of the rectangle. The position specifies this rectangle's pivot relative to the anchor reference point."); + public GUIContent sizeContent = new GUIContent("Size", "The size of the rectangle."); + public GUIContent pivotContent = new GUIContent("Pivot", "The pivot point specified in normalized values between 0 and 1. The pivot point is the origin of this rectangle. Rotation and scaling is around this point."); + public GUIContent transformScaleContent = new GUIContent("Scale", "The local scaling of this Game Object relative to the parent. This scales everything including image borders and text."); + public GUIContent transformPositionZContent = new GUIContent("Pos Z", "Distance to offset the rectangle along the Z axis of the parent. The effect is visible if the Canvas uses a perspective camera, or if a parent RectTransform is rotated along the X or Y axis."); + public GUIContent rawEditContent; + public GUIContent blueprintContent; + public Styles() + { + this.rawEditContent = EditorGUIUtility.IconContent("RectTransformRaw", "Raw edit mode. When enabled, editing pivot and anchor values will not counter-adjust the position and size of the rectangle in order to make it stay in place."); + this.blueprintContent = EditorGUIUtility.IconContent("RectTransformBlueprint", "Blueprint mode. Edit RectTransforms as if they were not rotated and scaled. This enables snapping too."); + } + } + private enum AnchorFusedState + { + None, + All, + Horizontal, + Vertical + } + private delegate float FloatGetter(RectTransform rect); + private delegate void FloatSetter(RectTransform rect, float f); + private const string kShowAnchorPropsPrefName = "RectTransformEditor.showAnchorProperties"; + private const string kLockRectPrefName = "RectTransformEditor.lockRect"; + private const float kDottedLineSize = 5f; + private static Vector2 kShadowOffset = new Vector2(1f, -1f); + private static Color kShadowColor = new Color(0f, 0f, 0f, 0.5f); + private static float kDropdownSize = 49f; + private static Color kRectInParentSpaceColor = new Color(1f, 1f, 1f, 0.4f); + private static Color kParentColor = new Color(1f, 1f, 1f, 0.6f); + private static Color kSiblingColor = new Color(1f, 1f, 1f, 0.2f); + private static Color kAnchorColor = new Color(1f, 1f, 1f, 1f); + private static Color kAnchorLineColor = new Color(1f, 1f, 1f, 0.6f); + private static Vector3[] s_Corners = new Vector3[4]; + private static RectTransformEditor.Styles s_Styles; + private static int s_FoldoutHash = "Foldout".GetHashCode(); + private static int s_FloatFieldHash = "EditorTextField".GetHashCode(); + private static int s_ParentRectPreviewHandlesHash = "ParentRectPreviewDragHandles".GetHashCode(); + private static GUIContent[] s_XYLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y") + }; + private static GUIContent[] s_XYZLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y"), + new GUIContent("Z") + }; + private static bool[] s_ScaleDisabledMask = new bool[3]; + private static Vector3 s_StartMouseWorldPos; + private static Vector3 s_StartPosition; + private static Vector2 s_StartMousePos; + private static bool s_DragAnchorsTogether; + private static Vector2 s_StartDragAnchorMin; + private static Vector2 s_StartDragAnchorMax; + private static RectTransformEditor.AnchorFusedState s_AnchorFusedState = RectTransformEditor.AnchorFusedState.None; + private SerializedProperty m_AnchorMin; + private SerializedProperty m_AnchorMax; + private SerializedProperty m_AnchoredPosition; + private SerializedProperty m_SizeDelta; + private SerializedProperty m_Pivot; + private SerializedProperty m_LocalPositionZ; + private SerializedProperty m_LocalScale; + private TransformRotationGUI m_RotationGUI; + private bool m_ShowLayoutOptions; + private bool m_RawEditMode; + private int m_TargetCount; + private Dictionary m_KeyboardControlIDs = new Dictionary(); + private AnimBool m_ChangingAnchors = new AnimBool(); + private AnimBool m_ChangingPivot = new AnimBool(); + private AnimBool m_ChangingWidth = new AnimBool(); + private AnimBool m_ChangingHeight = new AnimBool(); + private AnimBool m_ChangingPosX = new AnimBool(); + private AnimBool m_ChangingPosY = new AnimBool(); + private AnimBool m_ChangingLeft = new AnimBool(); + private AnimBool m_ChangingRight = new AnimBool(); + private AnimBool m_ChangingTop = new AnimBool(); + private AnimBool m_ChangingBottom = new AnimBool(); + private static float s_ParentDragTime = 0f; + private static float s_ParentDragId = 0f; + private static Rect s_ParentDragOrigRect = default(Rect); + private static Rect s_ParentDragPreviewRect = default(Rect); + private static RectTransform s_ParentDragRectTransform = null; + private static RectTransformEditor.Styles styles + { + get + { + if (RectTransformEditor.s_Styles == null) + { + RectTransformEditor.s_Styles = new RectTransformEditor.Styles(); + } + return RectTransformEditor.s_Styles; + } + } + private void OnEnable() + { + this.m_AnchorMin = base.serializedObject.FindProperty("m_AnchorMin"); + this.m_AnchorMax = base.serializedObject.FindProperty("m_AnchorMax"); + this.m_AnchoredPosition = base.serializedObject.FindProperty("m_AnchoredPosition"); + this.m_SizeDelta = base.serializedObject.FindProperty("m_SizeDelta"); + this.m_Pivot = base.serializedObject.FindProperty("m_Pivot"); + this.m_TargetCount = base.targets.Length; + this.m_LocalPositionZ = base.serializedObject.FindProperty("m_LocalPosition.z"); + this.m_LocalScale = base.serializedObject.FindProperty("m_LocalScale"); + if (this.m_RotationGUI == null) + { + this.m_RotationGUI = new TransformRotationGUI(); + } + this.m_RotationGUI.OnEnable(base.serializedObject.FindProperty("m_LocalRotation"), new GUIContent("Rotation")); + this.m_ShowLayoutOptions = EditorPrefs.GetBool("RectTransformEditor.showAnchorProperties", false); + this.m_RawEditMode = EditorPrefs.GetBool("RectTransformEditor.lockRect", false); + this.m_ChangingAnchors.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPivot.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingWidth.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingHeight.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPosX.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPosY.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingLeft.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingRight.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingTop.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + this.m_ChangingBottom.valueChanged.AddListener(new UnityAction(this.RepaintScene)); + ManipulationToolUtility.handleDragChange = (ManipulationToolUtility.HandleDragChange)Delegate.Combine(ManipulationToolUtility.handleDragChange, new ManipulationToolUtility.HandleDragChange(this.HandleDragChange)); + } + private void OnDisable() + { + this.m_ChangingAnchors.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPivot.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingWidth.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingHeight.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPosX.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingPosY.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingLeft.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingRight.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingTop.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + this.m_ChangingBottom.valueChanged.RemoveListener(new UnityAction(this.RepaintScene)); + ManipulationToolUtility.handleDragChange = (ManipulationToolUtility.HandleDragChange)Delegate.Remove(ManipulationToolUtility.handleDragChange, new ManipulationToolUtility.HandleDragChange(this.HandleDragChange)); + } + private void HandleDragChange(string handleName, bool dragging) + { + AnimBool animBool; + switch (handleName) + { + case "ChangingLeft": + animBool = this.m_ChangingLeft; + goto IL_140; + case "ChangingRight": + animBool = this.m_ChangingRight; + goto IL_140; + case "ChangingPosY": + animBool = this.m_ChangingPosY; + goto IL_140; + case "ChangingWidth": + animBool = this.m_ChangingWidth; + goto IL_140; + case "ChangingBottom": + animBool = this.m_ChangingBottom; + goto IL_140; + case "ChangingTop": + animBool = this.m_ChangingTop; + goto IL_140; + case "ChangingPosX": + animBool = this.m_ChangingPosX; + goto IL_140; + case "ChangingHeight": + animBool = this.m_ChangingHeight; + goto IL_140; + case "ChangingPivot": + animBool = this.m_ChangingPivot; + goto IL_140; + } + animBool = null; + IL_140: + if (animBool != null) + { + animBool.target = dragging; + } + } + private void SetFadingBasedOnMouseDownUp(ref AnimBool animBool, Event eventBefore) + { + if (eventBefore.type == EventType.MouseDrag && Event.current.type != EventType.MouseDrag) + { + animBool.value = true; + } + else + { + if (eventBefore.type == EventType.MouseUp && Event.current.type != EventType.MouseUp) + { + animBool.target = false; + } + } + } + private void SetFadingBasedOnControlID(ref AnimBool animBool, int id) + { + GUIView y = (!(EditorWindow.focusedWindow == null)) ? EditorWindow.focusedWindow.m_Parent : null; + if (GUIUtility.keyboardControl == id && GUIView.current == y) + { + animBool.value = true; + this.m_KeyboardControlIDs[id] = animBool; + } + else + { + if ((GUIUtility.keyboardControl != id || GUIView.current != y) && this.m_KeyboardControlIDs.ContainsKey(id)) + { + this.m_KeyboardControlIDs.Remove(id); + if (!this.m_KeyboardControlIDs.ContainsValue(animBool)) + { + animBool.target = false; + } + } + } + } + private void RepaintScene() + { + SceneView.RepaintAll(); + } + private static bool ShouldDoIntSnapping(RectTransform rect) + { + Canvas componentInParent = rect.gameObject.GetComponentInParent(); + return componentInParent != null && componentInParent.renderMode != RenderMode.WorldSpace; + } + public override void OnInspectorGUI() + { + if (!EditorGUIUtility.wideMode) + { + EditorGUIUtility.wideMode = true; + EditorGUIUtility.labelWidth = EditorGUIUtility.currentViewWidth - 212f; + } + bool flag = false; + bool anyDrivenX = false; + bool anyDrivenY = false; + bool anyWithoutParent = false; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + RectTransform rectTransform = (RectTransform)targets[i]; + if (rectTransform.drivenByObject != null) + { + flag = true; + if ((rectTransform.drivenProperties & (DrivenTransformProperties.AnchoredPositionX | DrivenTransformProperties.SizeDeltaX)) != DrivenTransformProperties.None) + { + anyDrivenX = true; + } + if ((rectTransform.drivenProperties & (DrivenTransformProperties.AnchoredPositionY | DrivenTransformProperties.SizeDeltaY)) != DrivenTransformProperties.None) + { + anyDrivenY = true; + } + } + PrefabType prefabType = PrefabUtility.GetPrefabType(rectTransform.gameObject); + if ((rectTransform.transform.parent == null || rectTransform.transform.parent.GetComponent() == null) && prefabType != PrefabType.Prefab && prefabType != PrefabType.ModelPrefab) + { + anyWithoutParent = true; + } + } + if (flag) + { + if (base.targets.Length == 1) + { + EditorGUILayout.HelpBox("Some values driven by " + (this.target as RectTransform).drivenByObject.GetType().Name + ".", MessageType.None); + } + else + { + EditorGUILayout.HelpBox("Some values in some or all objects are driven.", MessageType.None); + } + } + base.serializedObject.Update(); + this.LayoutDropdownButton(anyWithoutParent); + this.SmartPositionAndSizeFields(anyWithoutParent, anyDrivenX, anyDrivenY); + this.SmartAnchorFields(); + this.SmartPivotField(); + EditorGUILayout.Space(); + this.m_RotationGUI.RotationField(base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & DrivenTransformProperties.Rotation) != DrivenTransformProperties.None)); + RectTransformEditor.s_ScaleDisabledMask[0] = base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & DrivenTransformProperties.ScaleX) != DrivenTransformProperties.None); + RectTransformEditor.s_ScaleDisabledMask[1] = base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & DrivenTransformProperties.ScaleY) != DrivenTransformProperties.None); + RectTransformEditor.s_ScaleDisabledMask[2] = base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & DrivenTransformProperties.ScaleZ) != DrivenTransformProperties.None); + RectTransformEditor.Vector3FieldWithDisabledMash(EditorGUILayout.GetControlRect(new GUILayoutOption[0]), this.m_LocalScale, RectTransformEditor.styles.transformScaleContent, RectTransformEditor.s_ScaleDisabledMask); + base.serializedObject.ApplyModifiedProperties(); + } + private static void Vector3FieldWithDisabledMash(Rect position, SerializedProperty property, GUIContent label, bool[] disabledMask) + { + int controlID = GUIUtility.GetControlID(RectTransformEditor.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + position.height = EditorGUIUtility.singleLineHeight; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, RectTransformEditor.s_XYZLabels, serializedProperty, 13f, disabledMask); + } + private void LayoutDropdownButton(bool anyWithoutParent) + { + Rect rect = GUILayoutUtility.GetRect(0f, 0f); + rect.x += 2f; + rect.y += 17f; + rect.height = RectTransformEditor.kDropdownSize; + rect.width = RectTransformEditor.kDropdownSize; + EditorGUI.BeginDisabledGroup(anyWithoutParent); + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, 0.6f) * color; + if (EditorGUI.ButtonMouseDown(rect, GUIContent.none, FocusType.Passive, "box")) + { + GUIUtility.keyboardControl = 0; + PopupWindow.Show(rect, new LayoutDropdownWindow(base.serializedObject)); + } + GUI.color = color; + EditorGUI.EndDisabledGroup(); + if (!anyWithoutParent) + { + LayoutDropdownWindow.DrawLayoutMode(new RectOffset(7, 7, 7, 7).Remove(rect), this.m_AnchorMin, this.m_AnchorMax, this.m_AnchoredPosition, this.m_SizeDelta); + LayoutDropdownWindow.DrawLayoutModeHeadersOutsideRect(rect, this.m_AnchorMin, this.m_AnchorMax, this.m_AnchoredPosition, this.m_SizeDelta); + } + } + private void SmartPositionAndSizeFields(bool anyWithoutParent, bool anyDrivenX, bool anyDrivenY) + { + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 4f, new GUILayoutOption[0]); + controlRect.height = EditorGUIUtility.singleLineHeight * 2f; + bool flag = base.targets.Any((UnityEngine.Object x) => (x as RectTransform).anchorMin.x != (x as RectTransform).anchorMax.x); + bool flag2 = base.targets.Any((UnityEngine.Object x) => (x as RectTransform).anchorMin.y != (x as RectTransform).anchorMax.y); + bool flag3 = base.targets.Any((UnityEngine.Object x) => (x as RectTransform).anchorMin.x == (x as RectTransform).anchorMax.x); + bool flag4 = base.targets.Any((UnityEngine.Object x) => (x as RectTransform).anchorMin.y == (x as RectTransform).anchorMax.y); + Rect rect = this.GetColumnRect(controlRect, 0); + if (flag3 || anyWithoutParent || anyDrivenX) + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("x")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.anchoredPosition.x, delegate(RectTransform rectTransform, float val) + { + rectTransform.anchoredPosition = new Vector2(val, rectTransform.anchoredPosition.y); + }, DrivenTransformProperties.AnchoredPositionX, new GUIContent("Pos X")); + this.SetFadingBasedOnControlID(ref this.m_ChangingPosX, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + } + else + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("x")); + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("x")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.offsetMin.x, delegate(RectTransform rectTransform, float val) + { + rectTransform.offsetMin = new Vector2(val, rectTransform.offsetMin.y); + }, DrivenTransformProperties.None, new GUIContent("Left")); + this.SetFadingBasedOnControlID(ref this.m_ChangingLeft, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + EditorGUI.EndProperty(); + } + rect = this.GetColumnRect(controlRect, 1); + if (flag4 || anyWithoutParent || anyDrivenY) + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("y")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.anchoredPosition.y, delegate(RectTransform rectTransform, float val) + { + rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, val); + }, DrivenTransformProperties.AnchoredPositionY, new GUIContent("Pos Y")); + this.SetFadingBasedOnControlID(ref this.m_ChangingPosY, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + } + else + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("y")); + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("y")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => -rectTransform.offsetMax.y, delegate(RectTransform rectTransform, float val) + { + rectTransform.offsetMax = new Vector2(rectTransform.offsetMax.x, -val); + }, DrivenTransformProperties.None, new GUIContent("Top")); + this.SetFadingBasedOnControlID(ref this.m_ChangingTop, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + EditorGUI.EndProperty(); + } + rect = this.GetColumnRect(controlRect, 2); + EditorGUI.BeginProperty(rect, null, this.m_LocalPositionZ); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.transform.localPosition.z, delegate(RectTransform rectTransform, float val) + { + rectTransform.transform.localPosition = new Vector3(rectTransform.transform.localPosition.x, rectTransform.transform.localPosition.y, val); + }, DrivenTransformProperties.AnchoredPositionZ, new GUIContent("Pos Z")); + EditorGUI.EndProperty(); + controlRect.y += EditorGUIUtility.singleLineHeight * 2f; + rect = this.GetColumnRect(controlRect, 0); + if (flag3 || anyWithoutParent || anyDrivenX) + { + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("x")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.sizeDelta.x, delegate(RectTransform rectTransform, float val) + { + rectTransform.sizeDelta = new Vector2(val, rectTransform.sizeDelta.y); + }, DrivenTransformProperties.SizeDeltaX, (!flag) ? new GUIContent("Width") : new GUIContent("W Delta")); + this.SetFadingBasedOnControlID(ref this.m_ChangingWidth, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + } + else + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("x")); + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("x")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => -rectTransform.offsetMax.x, delegate(RectTransform rectTransform, float val) + { + rectTransform.offsetMax = new Vector2(-val, rectTransform.offsetMax.y); + }, DrivenTransformProperties.None, new GUIContent("Right")); + this.SetFadingBasedOnControlID(ref this.m_ChangingRight, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + EditorGUI.EndProperty(); + } + rect = this.GetColumnRect(controlRect, 1); + if (flag4 || anyWithoutParent || anyDrivenY) + { + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("y")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.sizeDelta.y, delegate(RectTransform rectTransform, float val) + { + rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, val); + }, DrivenTransformProperties.SizeDeltaY, (!flag2) ? new GUIContent("Height") : new GUIContent("H Delta")); + this.SetFadingBasedOnControlID(ref this.m_ChangingHeight, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + } + else + { + EditorGUI.BeginProperty(rect, null, this.m_AnchoredPosition.FindPropertyRelative("y")); + EditorGUI.BeginProperty(rect, null, this.m_SizeDelta.FindPropertyRelative("y")); + this.FloatFieldLabelAbove(rect, (RectTransform rectTransform) => rectTransform.offsetMin.y, delegate(RectTransform rectTransform, float val) + { + rectTransform.offsetMin = new Vector2(rectTransform.offsetMin.x, val); + }, DrivenTransformProperties.None, new GUIContent("Bottom")); + this.SetFadingBasedOnControlID(ref this.m_ChangingBottom, EditorGUIUtility.s_LastControlID); + EditorGUI.EndProperty(); + EditorGUI.EndProperty(); + } + rect = controlRect; + rect.height = EditorGUIUtility.singleLineHeight; + rect.y += EditorGUIUtility.singleLineHeight; + rect.yMin -= 2f; + rect.xMin = rect.xMax - 26f; + rect.x -= rect.width; + this.BlueprintButton(rect); + rect.x += rect.width; + this.RawButton(rect); + } + private void SmartAnchorFields() + { + Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (float)((!this.m_ShowLayoutOptions) ? 1 : 3), new GUILayoutOption[0]); + controlRect.height = EditorGUIUtility.singleLineHeight; + EditorGUI.BeginChangeCheck(); + this.m_ShowLayoutOptions = EditorGUI.Foldout(controlRect, this.m_ShowLayoutOptions, RectTransformEditor.styles.anchorsContent); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("RectTransformEditor.showAnchorProperties", this.m_ShowLayoutOptions); + } + if (!this.m_ShowLayoutOptions) + { + return; + } + EditorGUI.indentLevel++; + controlRect.y += EditorGUIUtility.singleLineHeight; + this.Vector2Field(controlRect, (RectTransform rectTransform) => rectTransform.anchorMin.x, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetAnchorSmart(rectTransform, val, 0, false, !this.m_RawEditMode, true); + }, (RectTransform rectTransform) => rectTransform.anchorMin.y, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetAnchorSmart(rectTransform, val, 1, false, !this.m_RawEditMode, true); + }, DrivenTransformProperties.AnchorMinX, DrivenTransformProperties.AnchorMinY, this.m_AnchorMin.FindPropertyRelative("x"), this.m_AnchorMin.FindPropertyRelative("y"), RectTransformEditor.styles.anchorMinContent); + controlRect.y += EditorGUIUtility.singleLineHeight; + this.Vector2Field(controlRect, (RectTransform rectTransform) => rectTransform.anchorMax.x, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetAnchorSmart(rectTransform, val, 0, true, !this.m_RawEditMode, true); + }, (RectTransform rectTransform) => rectTransform.anchorMax.y, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetAnchorSmart(rectTransform, val, 1, true, !this.m_RawEditMode, true); + }, DrivenTransformProperties.AnchorMaxX, DrivenTransformProperties.AnchorMaxY, this.m_AnchorMax.FindPropertyRelative("x"), this.m_AnchorMax.FindPropertyRelative("y"), RectTransformEditor.styles.anchorMaxContent); + EditorGUI.indentLevel--; + } + private void SmartPivotField() + { + this.Vector2Field(EditorGUILayout.GetControlRect(new GUILayoutOption[0]), (RectTransform rectTransform) => rectTransform.pivot.x, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetPivotSmart(rectTransform, val, 0, !this.m_RawEditMode, false); + }, (RectTransform rectTransform) => rectTransform.pivot.y, delegate(RectTransform rectTransform, float val) + { + RectTransformEditor.SetPivotSmart(rectTransform, val, 1, !this.m_RawEditMode, false); + }, DrivenTransformProperties.PivotX, DrivenTransformProperties.PivotY, this.m_Pivot.FindPropertyRelative("x"), this.m_Pivot.FindPropertyRelative("y"), RectTransformEditor.styles.pivotContent); + } + private void RawButton(Rect position) + { + EditorGUI.BeginChangeCheck(); + this.m_RawEditMode = GUI.Toggle(position, this.m_RawEditMode, RectTransformEditor.styles.rawEditContent, "ButtonRight"); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetBool("RectTransformEditor.lockRect", this.m_RawEditMode); + } + } + private void BlueprintButton(Rect position) + { + EditorGUI.BeginChangeCheck(); + bool rectBlueprintMode = GUI.Toggle(position, Tools.rectBlueprintMode, RectTransformEditor.styles.blueprintContent, "ButtonLeft"); + if (EditorGUI.EndChangeCheck()) + { + Tools.rectBlueprintMode = rectBlueprintMode; + Tools.RepaintAllToolViews(); + } + } + private void FloatFieldLabelAbove(Rect position, RectTransformEditor.FloatGetter getter, RectTransformEditor.FloatSetter setter, DrivenTransformProperties driven, GUIContent label) + { + EditorGUI.BeginDisabledGroup(base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & driven) != DrivenTransformProperties.None)); + float value = getter(this.target as RectTransform); + EditorGUI.showMixedValue = (( + from x in base.targets + select getter(x as RectTransform)).Distinct().Count() >= 2); + EditorGUI.BeginChangeCheck(); + int controlID = GUIUtility.GetControlID(RectTransformEditor.s_FloatFieldHash, FocusType.Keyboard, position); + Rect rect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight); + Rect position2 = new Rect(position.x, position.y + EditorGUIUtility.singleLineHeight, position.width, EditorGUIUtility.singleLineHeight); + EditorGUI.HandlePrefixLabel(position, rect, label, controlID); + float f = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position2, rect, controlID, value, EditorGUI.kFloatFieldFormatString, EditorStyles.textField, true); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(base.targets, "Inspector"); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + RectTransform rect2 = (RectTransform)targets[i]; + setter(rect2, f); + } + } + EditorGUI.EndDisabledGroup(); + } + private void Vector2Field(Rect position, RectTransformEditor.FloatGetter xGetter, RectTransformEditor.FloatSetter xSetter, RectTransformEditor.FloatGetter yGetter, RectTransformEditor.FloatSetter ySetter, DrivenTransformProperties xDriven, DrivenTransformProperties yDriven, SerializedProperty xProperty, SerializedProperty yProperty, GUIContent label) + { + EditorGUI.PrefixLabel(position, -1, label); + float labelWidth = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + Rect columnRect = this.GetColumnRect(position, 0); + Rect columnRect2 = this.GetColumnRect(position, 1); + EditorGUIUtility.labelWidth = 13f; + EditorGUI.indentLevel = 0; + EditorGUI.BeginProperty(columnRect, RectTransformEditor.s_XYLabels[0], xProperty); + this.FloatField(columnRect, xGetter, xSetter, xDriven, RectTransformEditor.s_XYLabels[0]); + EditorGUI.EndProperty(); + EditorGUI.BeginProperty(columnRect, RectTransformEditor.s_XYLabels[1], yProperty); + this.FloatField(columnRect2, yGetter, ySetter, yDriven, RectTransformEditor.s_XYLabels[1]); + EditorGUI.EndProperty(); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = indentLevel; + } + private void FloatField(Rect position, RectTransformEditor.FloatGetter getter, RectTransformEditor.FloatSetter setter, DrivenTransformProperties driven, GUIContent label) + { + EditorGUI.BeginDisabledGroup(base.targets.Any((UnityEngine.Object x) => ((x as RectTransform).drivenProperties & driven) != DrivenTransformProperties.None)); + float value = getter(this.target as RectTransform); + EditorGUI.showMixedValue = (( + from x in base.targets + select getter(x as RectTransform)).Distinct().Count() >= 2); + EditorGUI.BeginChangeCheck(); + float f = EditorGUI.FloatField(position, label, value); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(base.targets, "Inspector"); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + RectTransform rect = (RectTransform)targets[i]; + setter(rect, f); + } + } + EditorGUI.EndDisabledGroup(); + } + private Rect GetColumnRect(Rect totalRect, int column) + { + totalRect.xMin += EditorGUIUtility.labelWidth - 1f; + Rect result = totalRect; + result.xMin += (totalRect.width - 4f) * ((float)column / 3f) + (float)(column * 2); + result.width = (totalRect.width - 4f) / 3f; + return result; + } + private int AnchorPopup(Rect position, string label, int selected, string[] displayedOptions) + { + EditorGUIUtility.labelWidth = 12f; + int result = EditorGUI.Popup(position, label, selected, displayedOptions); + EditorGUIUtility.labelWidth = 0f; + return result; + } + private void DrawRect(Rect rect, Transform space, bool dotted) + { + Vector3 vector = space.TransformPoint(new Vector2(rect.x, rect.y)); + Vector3 vector2 = space.TransformPoint(new Vector2(rect.x, rect.yMax)); + Vector3 vector3 = space.TransformPoint(new Vector2(rect.xMax, rect.yMax)); + Vector3 vector4 = space.TransformPoint(new Vector2(rect.xMax, rect.y)); + if (!dotted) + { + Handles.DrawLine(vector, vector2); + Handles.DrawLine(vector2, vector3); + Handles.DrawLine(vector3, vector4); + Handles.DrawLine(vector4, vector); + } + else + { + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, vector, vector2, 5f); + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, vector2, vector3, 5f); + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, vector3, vector4, 5f); + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, vector4, vector, 5f); + } + } + private void OnSceneGUI() + { + RectTransform rectTransform = this.target as RectTransform; + Rect rect = rectTransform.rect; + Rect rectInUserSpace = rect; + Rect rect2 = rect; + Transform transform = rectTransform.transform; + Transform userSpace = transform; + Transform transform2 = transform; + RectTransform rectTransform2 = null; + if (transform.parent != null) + { + transform2 = transform.parent; + rect2.x += transform.localPosition.x; + rect2.y += transform.localPosition.y; + rectTransform2 = transform2.GetComponent(); + } + if (Tools.rectBlueprintMode) + { + userSpace = transform2; + rectInUserSpace = rect2; + } + float num = Mathf.Max(this.m_ChangingAnchors.faded, this.m_ChangingPivot.faded); + if (rectTransform.anchorMin != rectTransform.anchorMax) + { + num = Mathf.Max(new float[] + { + num, + this.m_ChangingPosX.faded, + this.m_ChangingPosY.faded, + this.m_ChangingLeft.faded, + this.m_ChangingRight.faded, + this.m_ChangingTop.faded, + this.m_ChangingBottom.faded + }); + } + Color color = RectTransformEditor.kRectInParentSpaceColor; + color.a *= num; + Handles.color = color; + this.DrawRect(rect2, transform2, true); + if (this.m_TargetCount == 1) + { + RectTransformSnapping.OnGUI(); + if (rectTransform2 != null) + { + this.AllAnchorsSceneGUI(rectTransform, rectTransform2, transform2, transform); + } + this.DrawSizes(rectInUserSpace, userSpace, rect2, transform2, rectTransform, rectTransform2); + RectTransformSnapping.DrawGuides(); + if (Tools.current == Tool.Rect) + { + this.ParentRectPreviewDragHandles(rectTransform2, transform2); + } + } + } + private void ParentRectPreviewDragHandles(RectTransform gui, Transform space) + { + if (gui == null) + { + return; + } + float size = 0.05f * HandleUtility.GetHandleSize(space.position); + Rect rect = gui.rect; + for (int i = 0; i <= 2; i++) + { + for (int j = 0; j <= 2; j++) + { + if (i == 1 != (j == 1)) + { + Vector3 position = Vector2.zero; + for (int k = 0; k < 2; k++) + { + position[k] = Mathf.Lerp(rect.min[k], rect.max[k], (float)((k != 0) ? j : i) * 0.5f); + } + position = space.TransformPoint(position); + int controlID = GUIUtility.GetControlID(RectTransformEditor.s_ParentRectPreviewHandlesHash, FocusType.Native); + Vector3 sideVector = (i != 1) ? (space.up * rect.height) : (space.right * rect.width); + Vector3 direction = (i != 1) ? space.right : space.up; + EditorGUI.BeginChangeCheck(); + Vector3 position2 = RectHandles.SideSlider(controlID, position, sideVector, direction, size, null, 0f, -3f); + if (EditorGUI.EndChangeCheck()) + { + Vector2 b = space.InverseTransformPoint(position); + Vector2 a = space.InverseTransformPoint(position2); + Rect rect2 = rect; + Vector2 vector = a - b; + if (i == 0) + { + rect2.min = new Vector2(rect2.min.x + vector.x, rect2.min.y); + } + if (i == 2) + { + rect2.max = new Vector2(rect2.max.x + vector.x, rect2.max.y); + } + if (j == 0) + { + rect2.min = new Vector2(rect2.min.x, rect2.min.y + vector.y); + } + if (j == 2) + { + rect2.max = new Vector2(rect2.max.x, rect2.max.y + vector.y); + } + this.SetTemporaryRect(gui, rect2, controlID); + } + if (GUIUtility.hotControl == controlID) + { + Handles.BeginGUI(); + EditorGUI.DropShadowLabel(new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 60f, 16f), "Preview"); + Handles.EndGUI(); + } + } + } + } + } + private void SetTemporaryRect(RectTransform gui, Rect rect, int id) + { + if (RectTransformEditor.s_ParentDragRectTransform == null) + { + RectTransformEditor.s_ParentDragRectTransform = gui; + RectTransformEditor.s_ParentDragOrigRect = gui.rect; + RectTransformEditor.s_ParentDragId = (float)id; + } + else + { + if (RectTransformEditor.s_ParentDragRectTransform != gui) + { + return; + } + } + RectTransformEditor.s_ParentDragPreviewRect = rect; + RectTransformEditor.s_ParentDragTime = Time.realtimeSinceStartup; + InternalEditorUtility.SetRectTransformTemporaryRect(gui, rect); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.UpdateTemporaryRect)); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.UpdateTemporaryRect)); + } + private void UpdateTemporaryRect() + { + if (RectTransformEditor.s_ParentDragRectTransform == null) + { + return; + } + if ((float)GUIUtility.hotControl == RectTransformEditor.s_ParentDragId) + { + RectTransformEditor.s_ParentDragTime = Time.realtimeSinceStartup; + Canvas.ForceUpdateCanvases(); + GameView.RepaintAll(); + return; + } + float num = Time.realtimeSinceStartup - RectTransformEditor.s_ParentDragTime; + float num2 = Mathf.Clamp01(1f - num * 8f); + if (num2 > 0f) + { + Rect rect = default(Rect); + rect.position = Vector2.Lerp(RectTransformEditor.s_ParentDragOrigRect.position, RectTransformEditor.s_ParentDragPreviewRect.position, num2); + rect.size = Vector2.Lerp(RectTransformEditor.s_ParentDragOrigRect.size, RectTransformEditor.s_ParentDragPreviewRect.size, num2); + InternalEditorUtility.SetRectTransformTemporaryRect(RectTransformEditor.s_ParentDragRectTransform, rect); + } + else + { + InternalEditorUtility.SetRectTransformTemporaryRect(RectTransformEditor.s_ParentDragRectTransform, default(Rect)); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.UpdateTemporaryRect)); + RectTransformEditor.s_ParentDragRectTransform = null; + } + Canvas.ForceUpdateCanvases(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + } + private void AllAnchorsSceneGUI(RectTransform gui, RectTransform guiParent, Transform parentSpace, Transform transform) + { + Handles.color = RectTransformEditor.kParentColor; + this.DrawRect(guiParent.rect, parentSpace, false); + Handles.color = RectTransformEditor.kSiblingColor; + foreach (Transform transform2 in parentSpace) + { + if (transform2.gameObject.activeInHierarchy) + { + RectTransform component = transform2.GetComponent(); + if (component) + { + Rect rect = component.rect; + rect.x += component.transform.localPosition.x; + rect.y += component.transform.localPosition.y; + this.DrawRect(component.rect, component, false); + if (component != transform) + { + this.AnchorsSceneGUI(component, guiParent, parentSpace, false); + } + } + } + } + Handles.color = RectTransformEditor.kAnchorColor; + this.AnchorsSceneGUI(gui, guiParent, parentSpace, true); + } + private Vector3 GetAnchorLocal(RectTransform guiParent, Vector2 anchor) + { + return Rect.NormalizedToPoint(guiParent.rect, anchor); + } + private void AnchorsSceneGUI(RectTransform gui, RectTransform guiParent, Transform parentSpace, bool interactive) + { + if (Event.current.type == EventType.MouseDown) + { + RectTransformEditor.s_AnchorFusedState = RectTransformEditor.AnchorFusedState.None; + if (gui.anchorMin == gui.anchorMax) + { + RectTransformEditor.s_AnchorFusedState = RectTransformEditor.AnchorFusedState.All; + } + else + { + if (gui.anchorMin.x == gui.anchorMax.x) + { + RectTransformEditor.s_AnchorFusedState = RectTransformEditor.AnchorFusedState.Horizontal; + } + else + { + if (gui.anchorMin.y == gui.anchorMax.y) + { + RectTransformEditor.s_AnchorFusedState = RectTransformEditor.AnchorFusedState.Vertical; + } + } + } + } + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 0, 0, GUIUtility.GetControlID(FocusType.Passive)); + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 0, 1, GUIUtility.GetControlID(FocusType.Passive)); + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 1, 0, GUIUtility.GetControlID(FocusType.Passive)); + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 1, 1, GUIUtility.GetControlID(FocusType.Passive)); + if (!interactive) + { + return; + } + int controlID = GUIUtility.GetControlID(FocusType.Passive); + int controlID2 = GUIUtility.GetControlID(FocusType.Passive); + int controlID3 = GUIUtility.GetControlID(FocusType.Passive); + int controlID4 = GUIUtility.GetControlID(FocusType.Passive); + int controlID5 = GUIUtility.GetControlID(FocusType.Passive); + if (RectTransformEditor.s_AnchorFusedState == RectTransformEditor.AnchorFusedState.All) + { + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 2, 2, controlID); + } + if (RectTransformEditor.s_AnchorFusedState == RectTransformEditor.AnchorFusedState.Horizontal) + { + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 2, 0, controlID2); + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 2, 1, controlID3); + } + if (RectTransformEditor.s_AnchorFusedState == RectTransformEditor.AnchorFusedState.Vertical) + { + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 0, 2, controlID4); + this.AnchorSceneGUI(gui, guiParent, parentSpace, interactive, 1, 2, controlID5); + } + } + private void AnchorSceneGUI(RectTransform gui, RectTransform guiParent, Transform parentSpace, bool interactive, int minmaxX, int minmaxY, int id) + { + Vector3 vector = default(Vector2); + vector.x = ((minmaxX != 0) ? gui.anchorMax.x : gui.anchorMin.x); + vector.y = ((minmaxY != 0) ? gui.anchorMax.y : gui.anchorMin.y); + vector = this.GetAnchorLocal(guiParent, vector); + vector = parentSpace.TransformPoint(vector); + float num = 0.05f * HandleUtility.GetHandleSize(vector); + if (minmaxX < 2) + { + vector += parentSpace.right * num * (float)(minmaxX * 2 - 1); + } + if (minmaxY < 2) + { + vector += parentSpace.up * num * (float)(minmaxY * 2 - 1); + } + if (minmaxX < 2 && minmaxY < 2) + { + this.DrawAnchor(vector, parentSpace.right * num * 2f * (float)(minmaxX * 2 - 1), parentSpace.up * num * 2f * (float)(minmaxY * 2 - 1)); + } + if (!interactive) + { + return; + } + Event @event = new Event(Event.current); + EditorGUI.BeginChangeCheck(); + Vector3 vector2 = Handles.Slider2D(id, vector, parentSpace.forward, parentSpace.right, parentSpace.up, num, null, Vector2.zero); + if (@event.type == EventType.MouseDown && GUIUtility.hotControl == id) + { + RectTransformEditor.s_DragAnchorsTogether = EditorGUI.actionKey; + RectTransformEditor.s_StartDragAnchorMin = gui.anchorMin; + RectTransformEditor.s_StartDragAnchorMax = gui.anchorMax; + RectTransformSnapping.CalculateAnchorSnapValues(parentSpace, gui.transform, gui, minmaxX, minmaxY); + } + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObject(gui, "Move Rectangle Anchors"); + Vector2 vector3 = parentSpace.InverseTransformVector(vector2 - vector); + for (int i = 0; i <= 1; i++) + { + int index; + int expr_1F8 = index = i; + float num2 = vector3[index]; + vector3[expr_1F8] = num2 / guiParent.rect.size[i]; + int num3 = (i != 0) ? minmaxY : minmaxX; + bool flag = num3 == 1; + float num4 = (!flag) ? gui.anchorMin[i] : gui.anchorMax[i]; + float num5 = num4 + vector3[i]; + float num6 = Mathf.Clamp01(num5); + if (num3 == 0) + { + num6 = Mathf.Min(num6, gui.anchorMax[i]); + } + if (num3 == 1) + { + num6 = Mathf.Max(num6, gui.anchorMin[i]); + } + float num7 = HandleUtility.GetHandleSize(vector2) * 0.05f / guiParent.rect.size[i]; + num7 *= parentSpace.InverseTransformVector((i != 0) ? Vector3.up : Vector3.right)[i]; + num6 = RectTransformSnapping.SnapToGuides(num6, num7, i); + bool enforceExactValue = num6 != num5; + num5 = num6; + if (num3 == 2) + { + RectTransformEditor.SetAnchorSmart(gui, num5, i, false, !@event.shift, enforceExactValue, false, RectTransformEditor.s_DragAnchorsTogether); + RectTransformEditor.SetAnchorSmart(gui, num5, i, true, !@event.shift, enforceExactValue, false, RectTransformEditor.s_DragAnchorsTogether); + } + else + { + RectTransformEditor.SetAnchorSmart(gui, num5, i, flag, !@event.shift, enforceExactValue, true, RectTransformEditor.s_DragAnchorsTogether); + } + EditorUtility.SetDirty(gui); + if (gui.drivenByObject != null) + { + RectTransform.SendReapplyDrivenProperties(gui); + } + } + } + this.SetFadingBasedOnMouseDownUp(ref this.m_ChangingAnchors, @event); + } + private static float Round(float value) + { + return Mathf.Floor(0.5f + value); + } + private static int RoundToInt(float value) + { + return Mathf.FloorToInt(0.5f + value); + } + private void DrawSizes(Rect rectInUserSpace, Transform userSpace, Rect rectInParentSpace, Transform parentSpace, RectTransform gui, RectTransform guiParent) + { + float size = 0.05f * HandleUtility.GetHandleSize(parentSpace.position); + bool flag = gui.anchorMin.x != gui.anchorMax.x; + bool flag2 = gui.anchorMin.y != gui.anchorMax.y; + float alpha = Mathf.Max(new float[] + { + this.m_ChangingPosX.faded, + this.m_ChangingLeft.faded, + this.m_ChangingRight.faded, + this.m_ChangingAnchors.faded + }); + this.DrawAnchorRect(parentSpace, gui, guiParent, 0, alpha); + alpha = Mathf.Max(new float[] + { + this.m_ChangingPosY.faded, + this.m_ChangingTop.faded, + this.m_ChangingBottom.faded, + this.m_ChangingAnchors.faded + }); + this.DrawAnchorRect(parentSpace, gui, guiParent, 1, alpha); + this.DrawAnchorDistances(parentSpace, gui, guiParent, size, this.m_ChangingAnchors.faded); + if (flag) + { + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 0, 1, this.m_ChangingLeft.faded); + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 0, 2, this.m_ChangingRight.faded); + } + else + { + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 0, 0, this.m_ChangingPosX.faded); + this.DrawSizeDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 0, this.m_ChangingWidth.faded); + } + if (flag2) + { + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 1, 1, this.m_ChangingBottom.faded); + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 1, 2, this.m_ChangingTop.faded); + } + else + { + this.DrawPositionDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 1, 0, this.m_ChangingPosY.faded); + this.DrawSizeDistances(userSpace, rectInParentSpace, parentSpace, gui, guiParent, size, 1, this.m_ChangingHeight.faded); + } + } + private void DrawSizeDistances(Transform userSpace, Rect rectInParentSpace, Transform parentSpace, RectTransform gui, RectTransform guiParent, float size, int axis, float alpha) + { + if (alpha <= 0f) + { + return; + } + Color color = RectTransformEditor.kAnchorColor; + color.a *= alpha; + GUI.color = color; + if (userSpace == gui.transform) + { + gui.GetWorldCorners(RectTransformEditor.s_Corners); + } + else + { + gui.GetLocalCorners(RectTransformEditor.s_Corners); + for (int i = 0; i < 4; i++) + { + RectTransformEditor.s_Corners[i] += gui.transform.localPosition; + RectTransformEditor.s_Corners[i] = userSpace.TransformPoint(RectTransformEditor.s_Corners[i]); + } + } + string text = gui.sizeDelta[axis].ToString(); + GUIContent label = new GUIContent(text); + Vector3 b = ((axis != 0) ? userSpace.right : userSpace.up) * size * 2f; + this.DrawLabelBetweenPoints(RectTransformEditor.s_Corners[0] + b, RectTransformEditor.s_Corners[(axis != 0) ? 1 : 3] + b, label); + } + private void DrawPositionDistances(Transform userSpace, Rect rectInParentSpace, Transform parentSpace, RectTransform gui, RectTransform guiParent, float size, int axis, int side, float alpha) + { + if (guiParent == null || alpha <= 0f) + { + return; + } + Color color = RectTransformEditor.kAnchorLineColor; + color.a *= alpha; + Handles.color = color; + color = RectTransformEditor.kAnchorColor; + color.a *= alpha; + GUI.color = color; + Vector3 vector; + Vector3 vector2; + float num; + if (side == 0) + { + Vector2 v = Rect.NormalizedToPoint(rectInParentSpace, gui.pivot); + vector = v; + vector2 = v; + vector[axis] = Mathf.Lerp(guiParent.rect.min[axis], guiParent.rect.max[axis], gui.anchorMin[axis]); + num = gui.anchoredPosition[axis]; + } + else + { + Vector2 center = rectInParentSpace.center; + vector = center; + vector2 = center; + if (side == 1) + { + vector[axis] = Mathf.Lerp(guiParent.rect.min[axis], guiParent.rect.max[axis], gui.anchorMin[axis]); + vector2[axis] = rectInParentSpace.min[axis]; + num = gui.offsetMin[axis]; + } + else + { + vector[axis] = Mathf.Lerp(guiParent.rect.min[axis], guiParent.rect.max[axis], gui.anchorMax[axis]); + vector2[axis] = rectInParentSpace.max[axis]; + num = -gui.offsetMax[axis]; + } + } + vector = parentSpace.TransformPoint(vector); + vector2 = parentSpace.TransformPoint(vector2); + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, vector, vector2, 5f); + GUIContent label = new GUIContent(num.ToString()); + this.DrawLabelBetweenPoints(vector, vector2, label); + } + private void DrawAnchorDistances(Transform parentSpace, RectTransform gui, RectTransform guiParent, float size, float alpha) + { + if (guiParent == null || alpha <= 0f) + { + return; + } + Color color = RectTransformEditor.kAnchorColor; + color.a *= alpha; + GUI.color = color; + Vector3[,] array = new Vector3[2, 4]; + for (int i = 0; i < 2; i++) + { + for (int j = 0; j < 4; j++) + { + Vector3 vector = Vector3.zero; + switch (j) + { + case 0: + vector = Vector3.zero; + break; + case 1: + vector = gui.anchorMin; + break; + case 2: + vector = gui.anchorMax; + break; + case 3: + vector = Vector3.one; + break; + } + vector[i] = gui.anchorMin[i]; + vector = parentSpace.TransformPoint(this.GetAnchorLocal(guiParent, vector)); + array[i, j] = vector; + } + } + for (int k = 0; k < 2; k++) + { + Vector3 b = ((k != 0) ? parentSpace.up : parentSpace.right) * size * 2f; + int num = RectTransformEditor.RoundToInt(gui.anchorMin[1 - k] * 100f); + int num2 = RectTransformEditor.RoundToInt((gui.anchorMax[1 - k] - gui.anchorMin[1 - k]) * 100f); + int num3 = RectTransformEditor.RoundToInt((1f - gui.anchorMax[1 - k]) * 100f); + this.DrawLabelBetweenPoints(array[k, 0] - b, array[k, 1] - b, GUIContent.Temp(num.ToString() + "%")); + this.DrawLabelBetweenPoints(array[k, 1] - b, array[k, 2] - b, GUIContent.Temp(num2.ToString() + "%")); + this.DrawLabelBetweenPoints(array[k, 2] - b, array[k, 3] - b, GUIContent.Temp(num3.ToString() + "%")); + } + } + private void DrawAnchorRect(Transform parentSpace, RectTransform gui, RectTransform guiParent, int axis, float alpha) + { + if (guiParent == null || alpha <= 0f) + { + return; + } + Color color = RectTransformEditor.kAnchorLineColor; + color.a *= alpha; + Handles.color = color; + Vector3[,] array = new Vector3[2, 2]; + for (int i = 0; i < 2; i++) + { + if (i != 1 || gui.anchorMin[axis] != gui.anchorMax[axis]) + { + for (int j = 0; j < 2; j++) + { + array[i, j][1 - axis] = (float)j; + array[i, j][axis] = ((i != 0) ? gui.anchorMax[axis] : gui.anchorMin[axis]); + array[i, j] = parentSpace.TransformPoint(this.GetAnchorLocal(guiParent, array[i, j])); + } + RectHandles.DrawDottedLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, array[i, 0], array[i, 1], 5f); + } + } + } + private void DrawLabelBetweenPoints(Vector3 pA, Vector3 pB, GUIContent label) + { + if (pA == pB) + { + return; + } + Vector2 a = HandleUtility.WorldToGUIPoint(pA); + Vector2 b = HandleUtility.WorldToGUIPoint(pB); + Vector2 pivotPoint = (a + b) * 0.5f; + pivotPoint.x = RectTransformEditor.Round(pivotPoint.x); + pivotPoint.y = RectTransformEditor.Round(pivotPoint.y); + float num = Mathf.Atan2(b.y - a.y, b.x - a.x) * 57.29578f; + num = Mathf.Repeat(num + 89f, 180f) - 89f; + Handles.BeginGUI(); + Matrix4x4 matrix = GUI.matrix; + GUIStyle measuringLabelStyle = RectTransformEditor.styles.measuringLabelStyle; + measuringLabelStyle.alignment = TextAnchor.MiddleCenter; + GUIUtility.RotateAroundPivot(num, pivotPoint); + EditorGUI.DropShadowLabel(new Rect(pivotPoint.x - 50f, pivotPoint.y - 9f, 100f, 16f), label, measuringLabelStyle); + GUI.matrix = matrix; + Handles.EndGUI(); + } + private static Vector3 GetRectReferenceCorner(RectTransform gui, bool worldSpace) + { + if (!worldSpace) + { + return gui.rect.min + gui.transform.localPosition; + } + Transform transform = gui.transform; + gui.GetWorldCorners(RectTransformEditor.s_Corners); + if (transform.parent) + { + return transform.parent.InverseTransformPoint(RectTransformEditor.s_Corners[0]); + } + return RectTransformEditor.s_Corners[0]; + } + private void DrawAnchor(Vector3 pos, Vector3 right, Vector3 up) + { + pos -= up * 0.5f; + pos -= right * 0.5f; + up *= 1.4f; + right *= 1.4f; + RectHandles.DrawPolyLineWithShadow(RectTransformEditor.kShadowColor, RectTransformEditor.kShadowOffset, new Vector3[] + { + pos, + pos + up + right * 0.5f, + pos + right + up * 0.5f, + pos + }); + } + public static void SetPivotSmart(RectTransform rect, float value, int axis, bool smart, bool parentSpace) + { + Vector3 rectReferenceCorner = RectTransformEditor.GetRectReferenceCorner(rect, !parentSpace); + Vector2 pivot = rect.pivot; + pivot[axis] = value; + rect.pivot = pivot; + if (smart) + { + Vector3 rectReferenceCorner2 = RectTransformEditor.GetRectReferenceCorner(rect, !parentSpace); + Vector3 v = rectReferenceCorner2 - rectReferenceCorner; + rect.anchoredPosition -= v; + Vector3 position = rect.transform.position; + position.z -= v.z; + rect.transform.position = position; + } + } + public static void SetAnchorSmart(RectTransform rect, float value, int axis, bool isMax, bool smart) + { + RectTransformEditor.SetAnchorSmart(rect, value, axis, isMax, smart, false, false, false); + } + public static void SetAnchorSmart(RectTransform rect, float value, int axis, bool isMax, bool smart, bool enforceExactValue) + { + RectTransformEditor.SetAnchorSmart(rect, value, axis, isMax, smart, enforceExactValue, false, false); + } + public static void SetAnchorSmart(RectTransform rect, float value, int axis, bool isMax, bool smart, bool enforceExactValue, bool enforceMinNoLargerThanMax, bool moveTogether) + { + RectTransform rectTransform = null; + if (rect.transform.parent == null) + { + smart = false; + } + else + { + rectTransform = rect.transform.parent.GetComponent(); + if (rectTransform == null) + { + smart = false; + } + } + value = Mathf.Clamp01(value); + if (enforceMinNoLargerThanMax) + { + if (isMax) + { + value = Mathf.Max(value, rect.anchorMin[axis]); + } + else + { + value = Mathf.Min(value, rect.anchorMax[axis]); + } + } + float num = 0f; + float num2 = 0f; + if (smart) + { + float num3 = (!isMax) ? rect.anchorMin[axis] : rect.anchorMax[axis]; + num = (value - num3) * rectTransform.rect.size[axis]; + float num4 = 0f; + if (RectTransformEditor.ShouldDoIntSnapping(rect)) + { + num4 = Mathf.Round(num) - num; + } + num += num4; + if (!enforceExactValue) + { + value += num4 / rectTransform.rect.size[axis]; + if (Mathf.Abs(RectTransformEditor.Round(value * 1000f) - value * 1000f) < 0.1f) + { + value = RectTransformEditor.Round(value * 1000f) * 0.001f; + } + value = Mathf.Clamp01(value); + if (enforceMinNoLargerThanMax) + { + if (isMax) + { + value = Mathf.Max(value, rect.anchorMin[axis]); + } + else + { + value = Mathf.Min(value, rect.anchorMax[axis]); + } + } + } + if (moveTogether) + { + num2 = num; + } + else + { + num2 = ((!isMax) ? (num * (1f - rect.pivot[axis])) : (num * rect.pivot[axis])); + } + } + if (isMax) + { + Vector2 anchorMax = rect.anchorMax; + anchorMax[axis] = value; + rect.anchorMax = anchorMax; + Vector2 anchorMin = rect.anchorMin; + if (moveTogether) + { + anchorMin[axis] = RectTransformEditor.s_StartDragAnchorMin[axis] + anchorMax[axis] - RectTransformEditor.s_StartDragAnchorMax[axis]; + } + rect.anchorMin = anchorMin; + } + else + { + Vector2 anchorMin2 = rect.anchorMin; + anchorMin2[axis] = value; + rect.anchorMin = anchorMin2; + Vector2 anchorMax2 = rect.anchorMax; + if (moveTogether) + { + anchorMax2[axis] = RectTransformEditor.s_StartDragAnchorMax[axis] + anchorMin2[axis] - RectTransformEditor.s_StartDragAnchorMin[axis]; + } + rect.anchorMax = anchorMax2; + } + if (smart) + { + Vector2 anchoredPosition = rect.anchoredPosition; + float num5 = anchoredPosition[axis]; + anchoredPosition[axis] = num5 - num2; + rect.anchoredPosition = anchoredPosition; + if (!moveTogether) + { + Vector2 sizeDelta = rect.sizeDelta; + num5 = sizeDelta[axis]; + sizeDelta[axis] = num5 + num * (float)((!isMax) ? 1 : -1); + rect.sizeDelta = sizeDelta; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/RectTransformSnapping.cs b/UnityEditor/UnityEditor/RectTransformSnapping.cs new file mode 100644 index 00000000..ccd1e212 --- /dev/null +++ b/UnityEditor/UnityEditor/RectTransformSnapping.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class RectTransformSnapping + { + internal const float kSnapThreshold = 0.05f; + private static SnapGuideCollection[] s_SnapGuides = new SnapGuideCollection[] + { + new SnapGuideCollection(), + new SnapGuideCollection() + }; + private static float[] kSidesAndMiddle = new float[] + { + 0f, + 0.5f, + 1f + }; + private static Vector3[] s_Corners = new Vector3[4]; + internal static void OnGUI() + { + RectTransformSnapping.s_SnapGuides[0].OnGUI(); + RectTransformSnapping.s_SnapGuides[1].OnGUI(); + } + internal static void DrawGuides() + { + if (EditorGUI.actionKey) + { + return; + } + RectTransformSnapping.s_SnapGuides[0].DrawGuides(); + RectTransformSnapping.s_SnapGuides[1].DrawGuides(); + } + private static Vector3 GetInterpolatedCorner(Vector3[] corners, int mainAxis, float alongMainAxis, float alongOtherAxis) + { + if (mainAxis != 0) + { + float num = alongMainAxis; + alongMainAxis = alongOtherAxis; + alongOtherAxis = num; + } + return corners[0] * (1f - alongMainAxis) * (1f - alongOtherAxis) + corners[1] * (1f - alongMainAxis) * alongOtherAxis + corners[3] * alongMainAxis * (1f - alongOtherAxis) + corners[2] * alongMainAxis * alongOtherAxis; + } + internal static void CalculatePivotSnapValues(Rect rect, Vector3 pivot, Quaternion rotation) + { + for (int i = 0; i < 2; i++) + { + RectTransformSnapping.s_SnapGuides[i].Clear(); + for (int j = 0; j < RectTransformSnapping.kSidesAndMiddle.Length; j++) + { + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(RectTransformSnapping.kSidesAndMiddle[j], RectTransformSnapping.GetGuideLineForRect(rect, pivot, rotation, i, RectTransformSnapping.kSidesAndMiddle[j]))); + } + } + } + internal static void CalculateAnchorSnapValues(Transform parentSpace, Transform self, RectTransform gui, int minmaxX, int minmaxY) + { + for (int i = 0; i < 2; i++) + { + RectTransformSnapping.s_SnapGuides[i].Clear(); + RectTransform component = parentSpace.GetComponent(); + component.GetWorldCorners(RectTransformSnapping.s_Corners); + for (int j = 0; j < RectTransformSnapping.kSidesAndMiddle.Length; j++) + { + float num = RectTransformSnapping.kSidesAndMiddle[j]; + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(num, new Vector3[] + { + RectTransformSnapping.GetInterpolatedCorner(RectTransformSnapping.s_Corners, i, num, 0f), + RectTransformSnapping.GetInterpolatedCorner(RectTransformSnapping.s_Corners, i, num, 1f) + })); + } + foreach (Transform transform in parentSpace) + { + if (!(transform == self)) + { + RectTransform component2 = transform.GetComponent(); + if (component2) + { + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(component2.anchorMin[i], new Vector3[0])); + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(component2.anchorMax[i], new Vector3[0])); + } + } + } + int num2 = (i != 0) ? minmaxY : minmaxX; + if (num2 == 0) + { + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(gui.anchorMax[i], new Vector3[0])); + } + if (num2 == 1) + { + RectTransformSnapping.s_SnapGuides[i].AddGuide(new SnapGuide(gui.anchorMin[i], new Vector3[0])); + } + } + } + internal static void CalculateOffsetSnapValues(Transform parentSpace, Transform self, RectTransform parentRect, RectTransform rect, int xHandle, int yHandle) + { + for (int i = 0; i < 2; i++) + { + RectTransformSnapping.s_SnapGuides[i].Clear(); + } + if (parentSpace == null) + { + return; + } + for (int j = 0; j < 2; j++) + { + int num = (j != 0) ? yHandle : xHandle; + if (num != 1) + { + List snapGuides = RectTransformSnapping.GetSnapGuides(parentSpace, self, parentRect, rect, j, num); + foreach (SnapGuide current in snapGuides) + { + RectTransformSnapping.s_SnapGuides[j].AddGuide(current); + } + } + } + } + internal static void CalculatePositionSnapValues(Transform parentSpace, Transform self, RectTransform parentRect, RectTransform rect) + { + for (int i = 0; i < 2; i++) + { + RectTransformSnapping.s_SnapGuides[i].Clear(); + } + if (parentSpace == null) + { + return; + } + for (int j = 0; j < 2; j++) + { + for (int k = 0; k < RectTransformSnapping.kSidesAndMiddle.Length; k++) + { + List snapGuides = RectTransformSnapping.GetSnapGuides(parentSpace, self, parentRect, rect, j, k); + foreach (SnapGuide current in snapGuides) + { + current.value = RectTransformSnapping.GetGuideValueForRect(rect, current.value, j, RectTransformSnapping.kSidesAndMiddle[k]); + RectTransformSnapping.s_SnapGuides[j].AddGuide(current); + } + } + } + } + private static List GetSnapGuides(Transform parentSpace, Transform self, RectTransform parentRect, RectTransform rect, int axis, int side) + { + List list = new List(); + if (parentRect != null) + { + float num = RectTransformSnapping.kSidesAndMiddle[side]; + float num2 = Mathf.Lerp(rect.anchorMin[axis], rect.anchorMax[axis], num); + list.Add(new SnapGuide(num2 * parentRect.rect.size[axis], RectTransformSnapping.GetGuideLineForRect(parentRect, axis, num2))); + float num3 = Mathf.Lerp(rect.anchorMin[axis], rect.anchorMax[axis], num); + if (num != num3) + { + list.Add(new SnapGuide(num * parentRect.rect.size[axis], false, RectTransformSnapping.GetGuideLineForRect(parentRect, axis, num))); + } + } + foreach (Transform transform in parentSpace) + { + if (!(transform == self)) + { + RectTransform component = transform.GetComponent(); + if (component) + { + if (side == 0) + { + bool safe = component.anchorMin[axis] == rect.anchorMin[axis]; + list.Add(new SnapGuide(component.GetRectInParentSpace().min[axis], safe, RectTransformSnapping.GetGuideLineForRect(component, axis, 0f))); + safe = (component.anchorMax[axis] == rect.anchorMin[axis]); + list.Add(new SnapGuide(component.GetRectInParentSpace().max[axis], safe, RectTransformSnapping.GetGuideLineForRect(component, axis, 1f))); + } + if (side == 2) + { + bool safe = component.anchorMax[axis] == rect.anchorMax[axis]; + list.Add(new SnapGuide(component.GetRectInParentSpace().max[axis], safe, RectTransformSnapping.GetGuideLineForRect(component, axis, 1f))); + safe = (component.anchorMin[axis] == rect.anchorMax[axis]); + list.Add(new SnapGuide(component.GetRectInParentSpace().min[axis], safe, RectTransformSnapping.GetGuideLineForRect(component, axis, 0f))); + } + if (side == 1) + { + bool safe = component.anchorMin[axis] - rect.anchorMin[axis] == -(component.anchorMax[axis] - rect.anchorMax[axis]); + list.Add(new SnapGuide(component.GetRectInParentSpace().center[axis], safe, RectTransformSnapping.GetGuideLineForRect(component, axis, 0.5f))); + } + } + } + } + return list; + } + private static Vector3[] GetGuideLineForRect(RectTransform rect, int axis, float side) + { + Vector3[] array = new Vector3[2]; + array[0][1 - axis] = rect.rect.min[1 - axis]; + array[1][1 - axis] = rect.rect.max[1 - axis]; + array[0][axis] = Mathf.Lerp(rect.rect.min[axis], rect.rect.max[axis], side); + array[1][axis] = array[0][axis]; + array[0] = rect.transform.TransformPoint(array[0]); + array[1] = rect.transform.TransformPoint(array[1]); + return array; + } + private static Vector3[] GetGuideLineForRect(Rect rect, Vector3 pivot, Quaternion rotation, int axis, float side) + { + Vector3[] array = new Vector3[2]; + array[0][1 - axis] = rect.min[1 - axis]; + array[1][1 - axis] = rect.max[1 - axis]; + array[0][axis] = Mathf.Lerp(rect.min[axis], rect.max[axis], side); + array[1][axis] = array[0][axis]; + array[0] = rotation * array[0] + pivot; + array[1] = rotation * array[1] + pivot; + return array; + } + private static float GetGuideValueForRect(RectTransform rect, float value, int axis, float side) + { + RectTransform component = rect.transform.parent.GetComponent(); + float num = (!component) ? 0f : component.rect.size[axis]; + float num2 = Mathf.Lerp(rect.anchorMin[axis], rect.anchorMax[axis], rect.pivot[axis]) * num; + float num3 = rect.rect.size[axis] * (rect.pivot[axis] - side); + return value - num2 + num3; + } + internal static Vector2 SnapToGuides(Vector2 value, Vector2 snapDistance) + { + return new Vector2(RectTransformSnapping.SnapToGuides(value.x, snapDistance.x, 0), RectTransformSnapping.SnapToGuides(value.y, snapDistance.y, 1)); + } + internal static float SnapToGuides(float value, float snapDistance, int axis) + { + if (EditorGUI.actionKey) + { + return value; + } + SnapGuideCollection snapGuideCollection = (axis != 0) ? RectTransformSnapping.s_SnapGuides[1] : RectTransformSnapping.s_SnapGuides[0]; + return snapGuideCollection.SnapToGuides(value, snapDistance); + } + } +} diff --git a/UnityEditor/UnityEditor/RemoveAssetOptions.cs b/UnityEditor/UnityEditor/RemoveAssetOptions.cs new file mode 100644 index 00000000..8f0d2196 --- /dev/null +++ b/UnityEditor/UnityEditor/RemoveAssetOptions.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum RemoveAssetOptions + { + MoveAssetToTrash, + DeleteAssets = 2 + } +} diff --git a/UnityEditor/UnityEditor/RenameOverlay.cs b/UnityEditor/UnityEditor/RenameOverlay.cs new file mode 100644 index 00000000..77a16d30 --- /dev/null +++ b/UnityEditor/UnityEditor/RenameOverlay.cs @@ -0,0 +1,311 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class RenameOverlay + { + [SerializeField] + private bool m_UserAcceptedRename; + [SerializeField] + private string m_Name; + [SerializeField] + private string m_OriginalName; + [SerializeField] + private Rect m_EditFieldRect; + [SerializeField] + private int m_UserData; + [SerializeField] + private bool m_IsWaitingForDelay; + [SerializeField] + private bool m_IsRenaming; + [SerializeField] + private EventType m_OriginalEventType = EventType.Ignore; + [SerializeField] + private bool m_IsRenamingFilename; + [SerializeField] + private GUIView m_ClientGUIView; + [NonSerialized] + private Rect m_LastScreenPosition; + private string k_RenameOverlayFocusName = "RenameOverlayField"; + private double s_RenameEndedTime; + private static GUIStyle s_DefaultTextFieldStyle = null; + private static int s_TextFieldHash = "RenameFieldTextField".GetHashCode(); + private int m_TextFieldControlID; + public string name + { + get + { + return this.m_Name; + } + } + public string originalName + { + get + { + return this.m_OriginalName; + } + } + public bool userAcceptedRename + { + get + { + return this.m_UserAcceptedRename; + } + } + public int userData + { + get + { + return this.m_UserData; + } + } + public bool isWaitingForDelay + { + get + { + return this.m_IsWaitingForDelay; + } + } + public Rect editFieldRect + { + get + { + return this.m_EditFieldRect; + } + set + { + this.m_EditFieldRect = value; + } + } + public bool isRenamingFilename + { + get + { + return this.m_IsRenamingFilename; + } + set + { + this.m_IsRenamingFilename = value; + } + } + public bool BeginRename(string name, int userData, float delay) + { + if (EditorApplication.timeSinceStartup - this.s_RenameEndedTime < 0.2) + { + return false; + } + if (this.m_IsRenaming) + { + Debug.Log("BeginRename fail: already renaming"); + return false; + } + this.m_Name = name; + this.m_OriginalName = name; + this.m_UserData = userData; + this.m_UserAcceptedRename = false; + this.m_IsWaitingForDelay = (delay > 0f); + this.m_IsRenaming = true; + this.m_EditFieldRect = new Rect(0f, 0f, 0f, 0f); + this.m_ClientGUIView = GUIView.current; + if (delay > 0f) + { + EditorApplication.CallDelayed(new EditorApplication.CallbackFunction(this.BeginRenameInternalCallback), delay); + } + else + { + this.BeginRenameInternalCallback(); + } + return true; + } + private void BeginRenameInternalCallback() + { + if (this.m_IsRenaming) + { + EditorGUI.s_RecycledEditor.content.text = this.m_Name; + EditorGUI.s_RecycledEditor.SelectAll(); + this.RepaintClientView(); + } + this.m_IsWaitingForDelay = false; + } + public void EndRename(bool acceptChanges) + { + if (!this.m_IsRenaming) + { + return; + } + this.RemoveMessage(); + if (this.isRenamingFilename) + { + this.m_Name = InternalEditorUtility.RemoveInvalidCharsFromFileName(this.m_Name, true); + } + this.m_IsRenaming = false; + this.m_UserAcceptedRename = acceptChanges; + this.RepaintClientView(); + this.s_RenameEndedTime = EditorApplication.timeSinceStartup; + } + private void RepaintClientView() + { + if (this.m_ClientGUIView != null) + { + this.m_ClientGUIView.Repaint(); + } + } + public void Clear() + { + this.m_IsRenaming = false; + this.m_UserAcceptedRename = false; + this.m_Name = string.Empty; + this.m_OriginalName = string.Empty; + this.m_EditFieldRect = default(Rect); + this.m_UserData = 0; + this.m_IsWaitingForDelay = false; + this.m_OriginalEventType = EventType.Ignore; + } + public bool HasKeyboardFocus() + { + return GUI.GetNameOfFocusedControl() == this.k_RenameOverlayFocusName; + } + public bool IsRenaming() + { + return this.m_IsRenaming; + } + public bool OnEvent() + { + if (!this.m_IsRenaming) + { + return true; + } + if (!this.m_IsWaitingForDelay) + { + GUIUtility.GetControlID(84895748, FocusType.Passive); + GUI.SetNextControlName(this.k_RenameOverlayFocusName); + EditorGUI.FocusTextInControl(this.k_RenameOverlayFocusName); + this.m_TextFieldControlID = GUIUtility.GetControlID(RenameOverlay.s_TextFieldHash, FocusType.Keyboard, this.m_EditFieldRect); + } + this.m_OriginalEventType = Event.current.type; + if (this.m_IsWaitingForDelay && (this.m_OriginalEventType == EventType.MouseDown || this.m_OriginalEventType == EventType.KeyDown)) + { + this.EndRename(false); + return false; + } + return true; + } + public bool OnGUI() + { + return this.OnGUI(null); + } + public bool OnGUI(GUIStyle textFieldStyle) + { + if (this.m_IsWaitingForDelay) + { + return true; + } + if (!this.m_IsRenaming) + { + return false; + } + if (this.m_EditFieldRect.width <= 0f || this.m_EditFieldRect.height <= 0f || this.m_TextFieldControlID == 0) + { + HandleUtility.Repaint(); + return true; + } + Event current = Event.current; + if (current.type == EventType.KeyDown) + { + if (current.keyCode == KeyCode.Escape) + { + current.Use(); + this.EndRename(false); + return false; + } + if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) + { + current.Use(); + this.EndRename(true); + return false; + } + } + if (this.m_OriginalEventType == EventType.MouseDown && !this.m_EditFieldRect.Contains(Event.current.mousePosition)) + { + this.EndRename(true); + return false; + } + this.m_Name = this.DoTextField(this.m_Name, textFieldStyle); + if (current.type == EventType.ScrollWheel) + { + current.Use(); + } + return true; + } + private string DoTextField(string text, GUIStyle textFieldStyle) + { + if (this.m_TextFieldControlID == 0) + { + Debug.LogError("RenameOverlay: Ensure to call OnEvent() as early as possible in the OnGUI of the current EditorWindow!"); + } + if (RenameOverlay.s_DefaultTextFieldStyle == null) + { + RenameOverlay.s_DefaultTextFieldStyle = "PR TextField"; + } + if (this.isRenamingFilename) + { + this.EatInvalidChars(); + } + GUI.changed = false; + if (GUIUtility.keyboardControl != this.m_TextFieldControlID) + { + GUIUtility.keyboardControl = this.m_TextFieldControlID; + } + bool flag; + return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, this.m_TextFieldControlID, EditorGUI.IndentedRect(this.m_EditFieldRect), text, textFieldStyle ?? RenameOverlay.s_DefaultTextFieldStyle, null, out flag, false, false, false); + } + private void EatInvalidChars() + { + if (this.isRenamingFilename) + { + Event current = Event.current; + if (GUIUtility.keyboardControl == this.m_TextFieldControlID && current.GetTypeForControl(this.m_TextFieldControlID) == EventType.KeyDown) + { + string text = string.Empty; + string invalidFilenameChars = EditorUtility.GetInvalidFilenameChars(); + if (invalidFilenameChars.IndexOf(current.character) > -1) + { + text = "A file name can't contain any of the following characters:\t" + invalidFilenameChars; + } + if (text != string.Empty) + { + current.Use(); + this.ShowMessage(text); + } + else + { + this.RemoveMessage(); + } + } + if (current.type == EventType.Repaint) + { + Rect screenRect = this.GetScreenRect(); + if (!Mathf.Approximately(this.m_LastScreenPosition.x, screenRect.x) || !Mathf.Approximately(this.m_LastScreenPosition.y, screenRect.y)) + { + this.RemoveMessage(); + } + this.m_LastScreenPosition = screenRect; + } + } + } + private Rect GetScreenRect() + { + return GUIUtility.GUIToScreenRect(this.m_EditFieldRect); + } + private void ShowMessage(string msg) + { + TooltipView.Show(msg, this.GetScreenRect()); + } + private void RemoveMessage() + { + TooltipView.Close(); + } + } +} diff --git a/UnityEditor/UnityEditor/RenderTextureInspector.cs b/UnityEditor/UnityEditor/RenderTextureInspector.cs new file mode 100644 index 00000000..36346249 --- /dev/null +++ b/UnityEditor/UnityEditor/RenderTextureInspector.cs @@ -0,0 +1,107 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(RenderTexture))] + internal class RenderTextureInspector : TextureInspector + { + private static GUIContent[] kRenderTextureAntiAliasing = new GUIContent[] + { + new GUIContent("None"), + new GUIContent("2 samples"), + new GUIContent("4 samples"), + new GUIContent("8 samples") + }; + private static int[] kRenderTextureAntiAliasingValues = new int[] + { + 1, + 2, + 4, + 8 + }; + private static GUIContent[] kRenderTextureDepths = new GUIContent[] + { + new GUIContent("None"), + new GUIContent("16 bit"), + new GUIContent("24 bit") + }; + private static int[] kRenderTextureDepthsValues = new int[] + { + 0, + 1, + 2 + }; + private SerializedProperty m_Width; + private SerializedProperty m_Height; + private SerializedProperty m_DepthFormat; + private SerializedProperty m_AntiAliasing; + private static string[] kTextureFormatsStrings = new string[] + { + "RGBA 32bit", + "Depth", + "RGBA 64bit FP", + "Shadowmap", + "RGB 16bit", + "RGBA 16bit", + "RGBA 16bit (5-1)", + string.Empty, + "RGBA 32bit (10-2)", + string.Empty, + "RGBA 64bit", + "RGBA 128bit FP", + "RG 64bit FP", + "RG 32bit FP", + "R 32bit FP", + "R 16bit FP", + "R 8bit" + }; + protected override void OnEnable() + { + base.OnEnable(); + this.m_Width = base.serializedObject.FindProperty("m_Width"); + this.m_Height = base.serializedObject.FindProperty("m_Height"); + this.m_AntiAliasing = base.serializedObject.FindProperty("m_AntiAliasing"); + this.m_DepthFormat = base.serializedObject.FindProperty("m_DepthFormat"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + RenderTexture renderTexture = this.target as RenderTexture; + GUI.changed = false; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Size", "MiniPopup"); + EditorGUILayout.PropertyField(this.m_Width, GUIContent.none, new GUILayoutOption[] + { + GUILayout.MinWidth(40f) + }); + GUILayout.Label("x", new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, GUIContent.none, new GUILayoutOption[] + { + GUILayout.MinWidth(40f) + }); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + EditorGUILayout.IntPopup(this.m_AntiAliasing, RenderTextureInspector.kRenderTextureAntiAliasing, RenderTextureInspector.kRenderTextureAntiAliasingValues, EditorGUIUtility.TempContent("Anti-Aliasing"), new GUILayoutOption[0]); + EditorGUILayout.IntPopup(this.m_DepthFormat, RenderTextureInspector.kRenderTextureDepths, RenderTextureInspector.kRenderTextureDepthsValues, EditorGUIUtility.TempContent("Depth Buffer"), new GUILayoutOption[0]); + if (GUI.changed) + { + renderTexture.Release(); + } + base.isInspectorDirty = true; + base.serializedObject.ApplyModifiedProperties(); + EditorGUILayout.Space(); + base.OnInspectorGUI(); + } + public override string GetInfoString() + { + RenderTexture renderTexture = this.target as RenderTexture; + string str = renderTexture.width.ToString() + "x" + renderTexture.height.ToString(); + if (!renderTexture.isPowerOfTwo) + { + str += "(NPOT)"; + } + str = str + " " + RenderTextureInspector.kTextureFormatsStrings[(int)renderTexture.format]; + return str + " " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySize(renderTexture)); + } + } +} diff --git a/UnityEditor/UnityEditor/RenderThumbnailUtility.cs b/UnityEditor/UnityEditor/RenderThumbnailUtility.cs new file mode 100644 index 00000000..685b218c --- /dev/null +++ b/UnityEditor/UnityEditor/RenderThumbnailUtility.cs @@ -0,0 +1,93 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class RenderThumbnailUtility + { + public static Bounds CalculateVisibleBounds(GameObject prefab) + { + return prefab.renderer.bounds; + } + public static Texture2D Render(GameObject prefab) + { + if (prefab == null) + { + return null; + } + if (prefab.renderer == null) + { + return null; + } + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + Texture2D texture2D = new Texture2D(64, 64); + texture2D.hideFlags = HideFlags.HideAndDontSave; + texture2D.name = "Preview Texture"; + RenderTexture temporary = RenderTexture.GetTemporary(texture2D.width, texture2D.height); + GameObject gameObject = new GameObject("Preview"); + gameObject.hideFlags = HideFlags.HideAndDontSave; + Camera camera = gameObject.AddComponent(typeof(Camera)) as Camera; + camera.clearFlags = CameraClearFlags.Color; + camera.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0f); + camera.cullingMask = 0; + camera.enabled = false; + camera.targetTexture = temporary; + Light light = gameObject.AddComponent(typeof(Light)) as Light; + light.type = LightType.Directional; + Bounds bounds = RenderThumbnailUtility.CalculateVisibleBounds(prefab); + Vector3 vector = new Vector3(0.7f, 0.3f, 0.7f); + float num = bounds.extents.magnitude * 1.6f; + gameObject.transform.position = bounds.center + vector.normalized * num; + gameObject.transform.LookAt(bounds.center); + camera.nearClipPlane = num * 0.1f; + camera.farClipPlane = num * 2.2f; + Camera current = Camera.current; + camera.RenderDontRestore(); + Light[] lights = new Light[] + { + light + }; + Graphics.SetupVertexLights(lights); + Component[] componentsInChildren = prefab.GetComponentsInChildren(typeof(Renderer)); + Component[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + Renderer renderer = (Renderer)array[i]; + if (renderer.enabled) + { + Material[] sharedMaterials = renderer.sharedMaterials; + for (int j = 0; j < sharedMaterials.Length; j++) + { + if (!(sharedMaterials[j] == null)) + { + Material material = sharedMaterials[j]; + string dependency = ShaderUtil.GetDependency(material.shader, "BillboardShader"); + if (dependency != null && dependency != string.Empty) + { + material = (UnityEngine.Object.Instantiate(material) as Material); + material.shader = Shader.Find(dependency); + material.hideFlags = HideFlags.HideAndDontSave; + } + for (int k = 0; k < material.passCount; k++) + { + if (material.SetPass(k)) + { + renderer.Render(j); + } + } + if (material != sharedMaterials[j]) + { + UnityEngine.Object.DestroyImmediate(material); + } + } + } + } + } + texture2D.ReadPixels(new Rect(0f, 0f, (float)texture2D.width, (float)texture2D.height), 0, 0); + RenderTexture.ReleaseTemporary(temporary); + UnityEngine.Object.DestroyImmediate(gameObject); + Camera.SetupCurrent(current); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + return texture2D; + } + } +} diff --git a/UnityEditor/UnityEditor/RendererModuleUI.cs b/UnityEditor/UnityEditor/RendererModuleUI.cs new file mode 100644 index 00000000..b0de871b --- /dev/null +++ b/UnityEditor/UnityEditor/RendererModuleUI.cs @@ -0,0 +1,169 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class RendererModuleUI : ModuleUI + { + private enum RenderMode + { + Billboard, + Stretch3D, + BillboardFixedHorizontal, + BillboardFixedVertical, + Mesh + } + private class Texts + { + public GUIContent renderMode = new GUIContent("Render Mode", "Defines the render mode of the particle renderer."); + public GUIContent material = new GUIContent("Material", "Defines the material used to render particles."); + public GUIContent mesh = new GUIContent("Mesh", "Defines the mesh that will be rendered as particle."); + public GUIContent maxParticleSize = new GUIContent("Max Particle Size", "How large is a particle allowed to be on screen at most? 1 is entire viewport. 0.5 is half viewport."); + public GUIContent cameraSpeedScale = new GUIContent("Camera Scale", "How much the camera speed is factored in when determining particle stretching."); + public GUIContent speedScale = new GUIContent("Speed Scale", "Defines the length of the particle compared to its speed."); + public GUIContent lengthScale = new GUIContent("Length Scale", "Defines the length of the particle compared to its width."); + public GUIContent sortingFudge = new GUIContent("Sorting Fudge", "Lower the number and most likely these particles will appear in front of other transparent objects, including other particles."); + public GUIContent sortMode = new GUIContent("Sort Mode", "The draw order of particles can be sorted by distance, youngest first, or oldest first."); + public GUIContent rotation = new GUIContent("Rotation", "Set whether the rotation of the particles is defined in Screen or World space."); + public GUIContent castShadows = new GUIContent("Cast Shadows", "Only opaque materials cast shadows"); + public GUIContent receiveShadows = new GUIContent("Receive Shadows", "Only opaque materials receive shadows"); + public GUIContent normalDirection = new GUIContent("Normal Direction", "Value between 0.0 and 1.0. If 1.0 is used, normals will point towards camera. If 0.0 is used, normals will point out in the corner direction of the particle."); + public string[] particleTypes = new string[] + { + "Billboard", + "Stretched Billboard", + "Horizontal Billboard", + "Vertical Billboard", + "Mesh" + }; + public string[] sortTypes = new string[] + { + "None", + "By Distance", + "Youngest First", + "Oldest First" + }; + } + private const int k_MaxNumMeshes = 4; + private SerializedProperty m_CastShadows; + private SerializedProperty m_ReceiveShadows; + private SerializedProperty m_Material; + private SerializedProperty m_RenderMode; + private SerializedProperty[] m_Meshes = new SerializedProperty[4]; + private SerializedProperty[] m_ShownMeshes; + private SerializedProperty m_MaxParticleSize; + private SerializedProperty m_CameraVelocityScale; + private SerializedProperty m_VelocityScale; + private SerializedProperty m_LengthScale; + private SerializedProperty m_SortMode; + private SerializedProperty m_SortingFudge; + private SerializedProperty m_NormalDirection; + private static RendererModuleUI.Texts s_Texts; + public RendererModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ParticleSystemRenderer", displayName, ModuleUI.VisibilityState.VisibleAndFolded) + { + this.m_ToolTip = "Specifies how the particles are rendered."; + } + protected override void Init() + { + if (this.m_CastShadows != null) + { + return; + } + this.m_CastShadows = base.GetProperty0("m_CastShadows"); + this.m_ReceiveShadows = base.GetProperty0("m_ReceiveShadows"); + this.m_Material = base.GetProperty0("m_Materials.Array.data[0]"); + this.m_RenderMode = base.GetProperty0("m_RenderMode"); + this.m_MaxParticleSize = base.GetProperty0("m_MaxParticleSize"); + this.m_CameraVelocityScale = base.GetProperty0("m_CameraVelocityScale"); + this.m_VelocityScale = base.GetProperty0("m_VelocityScale"); + this.m_LengthScale = base.GetProperty0("m_LengthScale"); + this.m_SortingFudge = base.GetProperty0("m_SortingFudge"); + this.m_SortMode = base.GetProperty0("m_SortMode"); + this.m_NormalDirection = base.GetProperty0("m_NormalDirection"); + this.m_Meshes[0] = base.GetProperty0("m_Mesh"); + this.m_Meshes[1] = base.GetProperty0("m_Mesh1"); + this.m_Meshes[2] = base.GetProperty0("m_Mesh2"); + this.m_Meshes[3] = base.GetProperty0("m_Mesh3"); + List list = new List(); + for (int i = 0; i < this.m_Meshes.Length; i++) + { + if (i == 0 || this.m_Meshes[i].objectReferenceValue != null) + { + list.Add(this.m_Meshes[i]); + } + } + this.m_ShownMeshes = list.ToArray(); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (RendererModuleUI.s_Texts == null) + { + RendererModuleUI.s_Texts = new RendererModuleUI.Texts(); + } + RendererModuleUI.RenderMode intValue = (RendererModuleUI.RenderMode)this.m_RenderMode.intValue; + RendererModuleUI.RenderMode renderMode = (RendererModuleUI.RenderMode)ModuleUI.GUIPopup(RendererModuleUI.s_Texts.renderMode, this.m_RenderMode, RendererModuleUI.s_Texts.particleTypes); + if (renderMode == RendererModuleUI.RenderMode.Mesh) + { + EditorGUI.indentLevel++; + this.DoListOfMeshesGUI(); + EditorGUI.indentLevel--; + if (intValue != RendererModuleUI.RenderMode.Mesh && this.m_Meshes[0].objectReferenceInstanceIDValue == 0) + { + this.m_Meshes[0].objectReferenceValue = Resources.GetBuiltinResource(typeof(Mesh), "Cube.fbx"); + } + } + else + { + if (renderMode == RendererModuleUI.RenderMode.Stretch3D) + { + EditorGUI.indentLevel++; + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.cameraSpeedScale, this.m_CameraVelocityScale); + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.speedScale, this.m_VelocityScale); + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.lengthScale, this.m_LengthScale); + EditorGUI.indentLevel--; + } + } + if (renderMode != RendererModuleUI.RenderMode.Mesh) + { + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.normalDirection, this.m_NormalDirection); + } + if (this.m_Material != null) + { + ModuleUI.GUIObject(RendererModuleUI.s_Texts.material, this.m_Material); + } + ModuleUI.GUIPopup(RendererModuleUI.s_Texts.sortMode, this.m_SortMode, RendererModuleUI.s_Texts.sortTypes); + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.sortingFudge, this.m_SortingFudge); + ModuleUI.GUIToggle(RendererModuleUI.s_Texts.castShadows, this.m_CastShadows); + ModuleUI.GUIToggle(RendererModuleUI.s_Texts.receiveShadows, this.m_ReceiveShadows); + ModuleUI.GUIFloat(RendererModuleUI.s_Texts.maxParticleSize, this.m_MaxParticleSize); + } + private void DoListOfMeshesGUI() + { + base.GUIListOfFloatObjectToggleFields(RendererModuleUI.s_Texts.mesh, this.m_ShownMeshes, null, null, false); + Rect rect = GUILayoutUtility.GetRect(0f, 13f); + rect.x = rect.xMax - 24f - 5f; + rect.width = 12f; + if (this.m_ShownMeshes.Length > 1 && ModuleUI.MinusButton(rect)) + { + this.m_ShownMeshes[this.m_ShownMeshes.Length - 1].objectReferenceValue = null; + List list = new List(this.m_ShownMeshes); + list.RemoveAt(list.Count - 1); + this.m_ShownMeshes = list.ToArray(); + } + if (this.m_ShownMeshes.Length < 4) + { + rect.x += 17f; + if (ModuleUI.PlusButton(rect)) + { + List list2 = new List(this.m_ShownMeshes); + list2.Add(this.m_Meshes[list2.Count]); + this.m_ShownMeshes = list2.ToArray(); + } + } + } + public bool IsMeshEmitter() + { + return this.m_RenderMode != null && this.m_RenderMode.intValue == 4; + } + } +} diff --git a/UnityEditor/UnityEditor/ReplacePrefabOptions.cs b/UnityEditor/UnityEditor/ReplacePrefabOptions.cs new file mode 100644 index 00000000..489d90a3 --- /dev/null +++ b/UnityEditor/UnityEditor/ReplacePrefabOptions.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum ReplacePrefabOptions + { + Default, + ConnectToPrefab, + ReplaceNameBased + } +} diff --git a/UnityEditor/UnityEditor/ResolutionDialogSetting.cs b/UnityEditor/UnityEditor/ResolutionDialogSetting.cs new file mode 100644 index 00000000..871bd773 --- /dev/null +++ b/UnityEditor/UnityEditor/ResolutionDialogSetting.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum ResolutionDialogSetting + { + Disabled, + Enabled, + HiddenByDefault + } +} diff --git a/UnityEditor/UnityEditor/RigidbodyEditor.cs b/UnityEditor/UnityEditor/RigidbodyEditor.cs new file mode 100644 index 00000000..bd5bb2b6 --- /dev/null +++ b/UnityEditor/UnityEditor/RigidbodyEditor.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Rigidbody))] + internal class RigidbodyEditor : Editor + { + private SerializedProperty m_Constraints; + private static GUIContent m_FreezePositionLabel = new GUIContent("Freeze Position"); + private static GUIContent m_FreezeRotationLabel = new GUIContent("Freeze Rotation"); + public void OnEnable() + { + this.m_Constraints = base.serializedObject.FindProperty("m_Constraints"); + } + private void ConstraintToggle(Rect r, string label, RigidbodyConstraints value, int bit) + { + bool value2 = (value & (RigidbodyConstraints)(1 << bit)) != RigidbodyConstraints.None; + EditorGUI.showMixedValue = ((this.m_Constraints.hasMultipleDifferentValuesBitwise & 1 << bit) != 0); + EditorGUI.BeginChangeCheck(); + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + value2 = EditorGUI.ToggleLeft(r, label, value2); + EditorGUI.indentLevel = indentLevel; + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(base.targets, "Edit Constraints"); + this.m_Constraints.SetBitAtIndexForAllTargetsImmediate(bit, value2); + } + EditorGUI.showMixedValue = false; + } + private void ToggleBlock(RigidbodyConstraints constraints, GUIContent label, int x, int y, int z) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.numberField); + int controlID = GUIUtility.GetControlID(7231, FocusType.Keyboard, rect); + rect = EditorGUI.PrefixLabel(rect, controlID, label); + rect.width = 30f; + this.ConstraintToggle(rect, "X", constraints, x); + rect.x += 30f; + this.ConstraintToggle(rect, "Y", constraints, y); + rect.x += 30f; + this.ConstraintToggle(rect, "Z", constraints, z); + GUILayout.EndHorizontal(); + } + public override void OnInspectorGUI() + { + base.DrawDefaultInspector(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_Constraints.isExpanded = EditorGUILayout.Foldout(this.m_Constraints.isExpanded, "Constraints"); + GUILayout.EndHorizontal(); + base.serializedObject.Update(); + RigidbodyConstraints intValue = (RigidbodyConstraints)this.m_Constraints.intValue; + if (this.m_Constraints.isExpanded) + { + EditorGUI.indentLevel++; + this.ToggleBlock(intValue, RigidbodyEditor.m_FreezePositionLabel, 1, 2, 3); + this.ToggleBlock(intValue, RigidbodyEditor.m_FreezeRotationLabel, 4, 5, 6); + EditorGUI.indentLevel--; + } + } + } +} diff --git a/UnityEditor/UnityEditor/RotateTool.cs b/UnityEditor/UnityEditor/RotateTool.cs new file mode 100644 index 00000000..224fce1a --- /dev/null +++ b/UnityEditor/UnityEditor/RotateTool.cs @@ -0,0 +1,58 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class RotateTool : ManipulationTool + { + private static RotateTool s_Instance; + public static void OnGUI(SceneView view) + { + if (RotateTool.s_Instance == null) + { + RotateTool.s_Instance = new RotateTool(); + } + RotateTool.s_Instance.OnToolGUI(view); + } + public override void ToolGUI(SceneView view, Vector3 handlePosition, bool isStatic) + { + Quaternion handleRotation = Tools.handleRotation; + EditorGUI.BeginChangeCheck(); + Quaternion quaternion = Handles.RotationHandle(handleRotation, handlePosition); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + float angle; + Vector3 vector; + (Quaternion.Inverse(handleRotation) * quaternion).ToAngleAxis(out angle, out vector); + vector = handleRotation * vector; + if (TransformManipulator.individualSpace) + { + vector = Quaternion.Inverse(Tools.handleRotation) * vector; + } + Undo.RecordObjects(Selection.transforms, "Rotate"); + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + Vector3 axis = vector; + if (TransformManipulator.individualSpace) + { + axis = transform.rotation * vector; + } + if (Tools.pivotMode == PivotMode.Center) + { + transform.RotateAround(handlePosition, axis, angle); + } + else + { + transform.RotateAround(transform.position, axis, angle); + } + if (transform.parent != null) + { + transform.SendTransformChangedScale(); + } + } + Tools.handleRotation = quaternion; + } + } + } +} diff --git a/UnityEditor/UnityEditor/RotationByVelocityModuleUI.cs b/UnityEditor/UnityEditor/RotationByVelocityModuleUI.cs new file mode 100644 index 00000000..c5aa39bf --- /dev/null +++ b/UnityEditor/UnityEditor/RotationByVelocityModuleUI.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class RotationByVelocityModuleUI : ModuleUI + { + private class Texts + { + public GUIContent velocityRange = new GUIContent("Speed Range", "Remaps speed in the defined range to an angular velocity."); + public GUIContent rotation = new GUIContent("Angular Velocity", "Controls the angular velocity of each particle based on its speed."); + } + private static RotationByVelocityModuleUI.Texts s_Texts; + private SerializedMinMaxCurve m_Curve; + private SerializedProperty m_Range; + public RotationByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "RotationBySpeedModule", displayName) + { + this.m_ToolTip = "Controls the angular velocity of each particle based on its speed."; + } + protected override void Init() + { + if (this.m_Curve != null) + { + return; + } + if (RotationByVelocityModuleUI.s_Texts == null) + { + RotationByVelocityModuleUI.s_Texts = new RotationByVelocityModuleUI.Texts(); + } + this.m_Curve = new SerializedMinMaxCurve(this, RotationByVelocityModuleUI.s_Texts.rotation, ModuleUI.kUseSignedRange); + this.m_Curve.m_RemapValue = 57.29578f; + this.m_Range = base.GetProperty("range"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (RotationByVelocityModuleUI.s_Texts == null) + { + RotationByVelocityModuleUI.s_Texts = new RotationByVelocityModuleUI.Texts(); + } + ModuleUI.GUIMinMaxCurve(RotationByVelocityModuleUI.s_Texts.rotation, this.m_Curve); + ModuleUI.GUIMinMaxRange(RotationByVelocityModuleUI.s_Texts.velocityRange, this.m_Range); + } + public override void UpdateCullingSupportedString(ref string text) + { + text += "\n\tRotation by Speed is enabled."; + } + } +} diff --git a/UnityEditor/UnityEditor/RotationCurveInterpolation.cs b/UnityEditor/UnityEditor/RotationCurveInterpolation.cs new file mode 100644 index 00000000..66cdf3c7 --- /dev/null +++ b/UnityEditor/UnityEditor/RotationCurveInterpolation.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class RotationCurveInterpolation + { + public struct State + { + public bool allAreNonBaked; + public bool allAreBaked; + public bool allAreRotations; + } + public enum Mode + { + Baked, + NonBaked, + RawQuaternions, + Undefined + } + public static char[] kPostFix = new char[] + { + 'x', + 'y', + 'z', + 'w' + }; + public static RotationCurveInterpolation.Mode GetModeFromCurveData(EditorCurveBinding data) + { + if (AnimationWindowUtility.IsTransformType(data.type) && data.propertyName.StartsWith("localEulerAngles")) + { + if (data.propertyName.StartsWith("localEulerAnglesBaked")) + { + return RotationCurveInterpolation.Mode.Baked; + } + return RotationCurveInterpolation.Mode.NonBaked; + } + else + { + if (AnimationWindowUtility.IsTransformType(data.type) && data.propertyName.StartsWith("m_LocalRotation")) + { + return RotationCurveInterpolation.Mode.RawQuaternions; + } + return RotationCurveInterpolation.Mode.Undefined; + } + } + public static RotationCurveInterpolation.State GetCurveState(AnimationClip clip, EditorCurveBinding[] selection) + { + RotationCurveInterpolation.State result; + result.allAreNonBaked = true; + result.allAreBaked = false; + result.allAreRotations = false; + for (int i = 0; i < selection.Length; i++) + { + EditorCurveBinding data = selection[i]; + RotationCurveInterpolation.Mode modeFromCurveData = RotationCurveInterpolation.GetModeFromCurveData(data); + if (modeFromCurveData == RotationCurveInterpolation.Mode.NonBaked) + { + result.allAreNonBaked = false; + } + else + { + if (modeFromCurveData == RotationCurveInterpolation.Mode.Baked) + { + result.allAreBaked = false; + } + else + { + result.allAreRotations = false; + } + } + } + return result; + } + public static int GetCurveIndexFromName(string name) + { + return (int)(RotationCurveInterpolation.ExtractComponentCharacter(name) - 'x'); + } + public static char ExtractComponentCharacter(string name) + { + return name[name.Length - 1]; + } + public static string GetPrefixForInterpolation(RotationCurveInterpolation.Mode newInterpolationMode) + { + if (newInterpolationMode == RotationCurveInterpolation.Mode.Baked) + { + return "localEulerAnglesBaked"; + } + if (newInterpolationMode == RotationCurveInterpolation.Mode.NonBaked) + { + return "localEulerAngles"; + } + if (newInterpolationMode == RotationCurveInterpolation.Mode.RawQuaternions) + { + return "m_LocalRotation"; + } + return null; + } + internal static EditorCurveBinding[] ConvertRotationPropertiesToDefaultInterpolation(AnimationClip clip, EditorCurveBinding[] selection) + { + return RotationCurveInterpolation.ConvertRotationPropertiesToInterpolationType(selection, RotationCurveInterpolation.Mode.Baked); + } + internal static EditorCurveBinding[] ConvertRotationPropertiesToInterpolationType(EditorCurveBinding[] selection, RotationCurveInterpolation.Mode newInterpolationMode) + { + if (selection.Length != 4) + { + return selection; + } + if (RotationCurveInterpolation.GetModeFromCurveData(selection[0]) == RotationCurveInterpolation.Mode.RawQuaternions) + { + EditorCurveBinding[] array = new EditorCurveBinding[] + { + selection[0], + selection[1], + selection[2] + }; + string prefixForInterpolation = RotationCurveInterpolation.GetPrefixForInterpolation(newInterpolationMode); + array[0].propertyName = prefixForInterpolation + ".x"; + array[1].propertyName = prefixForInterpolation + ".y"; + array[2].propertyName = prefixForInterpolation + ".z"; + return array; + } + return selection; + } + private static EditorCurveBinding[] GenerateTransformCurveBindingArray(string path, string property, Type type, int count) + { + EditorCurveBinding[] array = new EditorCurveBinding[count]; + for (int i = 0; i < count; i++) + { + array[i] = EditorCurveBinding.FloatCurve(path, type, property + RotationCurveInterpolation.kPostFix[i]); + } + return array; + } + public static EditorCurveBinding[] RemapAnimationBindingForAddKey(EditorCurveBinding binding, AnimationClip clip) + { + if (!AnimationWindowUtility.IsTransformType(binding.type)) + { + return null; + } + if (binding.propertyName.StartsWith("m_LocalPosition.")) + { + if (binding.type == typeof(Transform)) + { + return RotationCurveInterpolation.GenerateTransformCurveBindingArray(binding.path, "m_LocalPosition.", binding.type, 3); + } + return null; + } + else + { + if (binding.propertyName.StartsWith("m_LocalScale.")) + { + return RotationCurveInterpolation.GenerateTransformCurveBindingArray(binding.path, "m_LocalScale.", binding.type, 3); + } + if (!binding.propertyName.StartsWith("m_LocalRotation")) + { + return null; + } + EditorCurveBinding binding2 = binding; + binding2.propertyName = "localEulerAngles.x"; + if (AnimationUtility.GetEditorCurve(clip, binding2) != null) + { + return RotationCurveInterpolation.GenerateTransformCurveBindingArray(binding.path, "localEulerAngles.", binding.type, 3); + } + return RotationCurveInterpolation.GenerateTransformCurveBindingArray(binding.path, "localEulerAnglesBaked.", binding.type, 3); + } + } + public static EditorCurveBinding RemapAnimationBindingForRotationCurves(EditorCurveBinding curveBinding, AnimationClip clip) + { + if (!AnimationWindowUtility.IsTransformType(curveBinding.type)) + { + return curveBinding; + } + if (!curveBinding.propertyName.StartsWith("m_LocalRotation")) + { + return curveBinding; + } + string str = curveBinding.propertyName.Split(new char[] + { + '.' + })[1]; + EditorCurveBinding editorCurveBinding = curveBinding; + editorCurveBinding.propertyName = "localEulerAngles." + str; + AnimationCurve editorCurve = AnimationUtility.GetEditorCurve(clip, editorCurveBinding); + if (editorCurve != null) + { + return editorCurveBinding; + } + editorCurveBinding.propertyName = "localEulerAnglesBaked." + str; + editorCurve = AnimationUtility.GetEditorCurve(clip, editorCurveBinding); + if (editorCurve != null) + { + return editorCurveBinding; + } + return curveBinding; + } + internal static void SetInterpolation(AnimationClip clip, EditorCurveBinding[] curveBindings, RotationCurveInterpolation.Mode newInterpolationMode) + { + Undo.RegisterCompleteObjectUndo(clip, "Rotation Interpolation"); + List list = new List(); + List list2 = new List(); + List list3 = new List(); + for (int i = 0; i < curveBindings.Length; i++) + { + EditorCurveBinding editorCurveBinding = curveBindings[i]; + RotationCurveInterpolation.Mode modeFromCurveData = RotationCurveInterpolation.GetModeFromCurveData(editorCurveBinding); + if (modeFromCurveData != RotationCurveInterpolation.Mode.Undefined) + { + if (modeFromCurveData == RotationCurveInterpolation.Mode.RawQuaternions) + { + Debug.LogWarning("Can't convert quaternion curve: " + editorCurveBinding.propertyName); + } + else + { + AnimationCurve editorCurve = AnimationUtility.GetEditorCurve(clip, editorCurveBinding); + if (editorCurve != null) + { + string propertyName = RotationCurveInterpolation.GetPrefixForInterpolation(newInterpolationMode) + '.' + RotationCurveInterpolation.ExtractComponentCharacter(editorCurveBinding.propertyName); + list.Add(new EditorCurveBinding + { + propertyName = propertyName, + type = editorCurveBinding.type, + path = editorCurveBinding.path + }); + list2.Add(editorCurve); + list3.Add(new EditorCurveBinding + { + propertyName = editorCurveBinding.propertyName, + type = editorCurveBinding.type, + path = editorCurveBinding.path + }); + } + } + } + } + Undo.RegisterCompleteObjectUndo(clip, "Rotation Interpolation"); + foreach (EditorCurveBinding current in list3) + { + AnimationUtility.SetEditorCurve(clip, current, null); + } + foreach (EditorCurveBinding current2 in list) + { + AnimationUtility.SetEditorCurve(clip, current2, list2[list.IndexOf(current2)]); + } + } + } +} diff --git a/UnityEditor/UnityEditor/RotationModuleUI.cs b/UnityEditor/UnityEditor/RotationModuleUI.cs new file mode 100644 index 00000000..78b42a5d --- /dev/null +++ b/UnityEditor/UnityEditor/RotationModuleUI.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class RotationModuleUI : ModuleUI + { + private class Texts + { + public GUIContent rotation = new GUIContent("Angular Velocity", "Controls the angular velocity of each particle during its lifetime."); + } + private SerializedMinMaxCurve m_Curve; + private static RotationModuleUI.Texts s_Texts; + public RotationModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "RotationModule", displayName) + { + this.m_ToolTip = "Controls the angular velocity of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_Curve != null) + { + return; + } + if (RotationModuleUI.s_Texts == null) + { + RotationModuleUI.s_Texts = new RotationModuleUI.Texts(); + } + this.m_Curve = new SerializedMinMaxCurve(this, RotationModuleUI.s_Texts.rotation, ModuleUI.kUseSignedRange); + this.m_Curve.m_RemapValue = 57.29578f; + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (RotationModuleUI.s_Texts == null) + { + RotationModuleUI.s_Texts = new RotationModuleUI.Texts(); + } + ModuleUI.GUIMinMaxCurve(RotationModuleUI.s_Texts.rotation, this.m_Curve); + } + public override void UpdateCullingSupportedString(ref string text) + { + this.Init(); + if (!this.m_Curve.SupportsProcedural()) + { + text += "\n\tLifetime rotation curve uses too many keys."; + } + } + } +} diff --git a/UnityEditor/UnityEditor/RuntimeClassRegistry.cs b/UnityEditor/UnityEditor/RuntimeClassRegistry.cs new file mode 100644 index 00000000..669bff56 --- /dev/null +++ b/UnityEditor/UnityEditor/RuntimeClassRegistry.cs @@ -0,0 +1,393 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class RuntimeClassRegistry + { + internal class MethodDescription + { + public string assembly; + public string fullTypeName; + public string methodName; + } + protected BuildTarget buildTarget; + protected Dictionary nativeClasses = new Dictionary(); + protected HashSet monoClasses = new HashSet(); + protected HashSet monoBaseClasses = new HashSet(); + protected Dictionary m_UsedTypesPerUserAssembly = new Dictionary(); + protected Dictionary allNativeClasses = new Dictionary(); + protected Dictionary retentionLevel = new Dictionary(); + protected Dictionary functionalityGroups = new Dictionary(); + protected Dictionary> groupNativeDependencies = new Dictionary>(); + protected Dictionary> groupManagedDependencies = new Dictionary>(); + internal List m_MethodsToPreserve = new List(); + internal List m_UserAssemblies = new List(); + public Dictionary UsedTypePerUserAssembly + { + get + { + return this.m_UsedTypesPerUserAssembly; + } + } + public void AddNativeClassID(int ID) + { + string text = BaseObjectTools.ClassIDToString(ID); + if (text.Length > 0) + { + this.allNativeClasses[ID] = text; + if (!this.functionalityGroups.ContainsValue(text)) + { + this.nativeClasses[ID] = text; + } + } + } + public void SetUsedTypesInUserAssembly(string[] typeNames, string assemblyName) + { + this.m_UsedTypesPerUserAssembly[assemblyName] = typeNames; + } + public bool IsUGUIUsed() + { + return this.m_UsedTypesPerUserAssembly.ContainsKey("UnityEngine.UI.dll"); + } + public void AddMonoClass(string className) + { + this.monoClasses.Add(className); + } + public void AddMonoClasses(List classes) + { + foreach (string current in classes) + { + this.AddMonoClass(current); + } + } + protected void AddManagedBaseClass(string className) + { + this.monoBaseClasses.Add(className); + } + protected void AddNativeClassFromName(string className) + { + int num = BaseObjectTools.StringToClassID(className); + if (num != -1 && !BaseObjectTools.IsBaseObject(num)) + { + this.nativeClasses[num] = className; + } + } + protected void SynchronizeMonoToNativeClasses() + { + foreach (string current in this.monoClasses) + { + this.AddNativeClassFromName(current); + } + } + protected void SynchronizeNativeToMonoClasses() + { + foreach (string current in this.nativeClasses.Values) + { + this.AddMonoClass(current); + } + } + public void SynchronizeClasses() + { + this.SynchronizeMonoToNativeClasses(); + this.SynchronizeNativeToMonoClasses(); + this.InjectFunctionalityGroupDependencies(); + this.SynchronizeMonoToNativeClasses(); + } + protected void InjectFunctionalityGroupDependencies() + { + HashSet hashSet = new HashSet(); + foreach (string current in this.functionalityGroups.Keys) + { + foreach (string current2 in this.monoClasses) + { + if (this.groupManagedDependencies[current].Contains(current2) || this.groupNativeDependencies[current].Contains(current2)) + { + hashSet.Add(current); + } + } + } + foreach (string current3 in hashSet) + { + foreach (string current4 in this.groupManagedDependencies[current3]) + { + this.AddMonoClass(current4); + } + foreach (string current5 in this.groupNativeDependencies[current3]) + { + this.AddNativeClassFromName(current5); + } + } + } + public List GetAllNativeClassesAsString() + { + return new List(this.nativeClasses.Values); + } + public List GetAllNativeClassesIncludingManagersAsString() + { + return new List(this.allNativeClasses.Values); + } + public List GetAllManagedClassesAsString() + { + return new List(this.monoClasses); + } + public List GetAllManagedBaseClassesAsString() + { + return new List(this.monoBaseClasses); + } + public static RuntimeClassRegistry Create() + { + return new RuntimeClassRegistry(); + } + public void Initialize(int[] nativeClassIDs, BuildTarget buildTarget) + { + this.buildTarget = buildTarget; + this.InitRuntimeClassRegistry(); + for (int i = 0; i < nativeClassIDs.Length; i++) + { + int iD = nativeClassIDs[i]; + this.AddNativeClassID(iD); + } + } + protected void AddFunctionalityGroup(string groupName, string managerClassName) + { + this.functionalityGroups.Add(groupName, managerClassName); + this.groupManagedDependencies[groupName] = new HashSet(); + this.groupNativeDependencies[groupName] = new HashSet(); + } + protected void AddNativeDependenciesForFunctionalityGroup(string groupName, string depClassName) + { + this.groupNativeDependencies[groupName].Add(depClassName); + } + protected void AddManagedDependenciesForFunctionalityGroup(string groupName, Type depClass) + { + this.AddManagedDependenciesForFunctionalityGroup(groupName, this.ResolveTypeName(depClass)); + } + protected void AddManagedDependenciesForFunctionalityGroup(string groupName, string depClassName) + { + this.AddManagedDependenciesForFunctionalityGroup(groupName, depClassName, null); + } + protected string ResolveTypeName(Type type) + { + string fullName = type.FullName; + return fullName.Substring(fullName.LastIndexOf(".") + 1).Replace("+", "/"); + } + protected void AddManagedDependenciesForFunctionalityGroup(string groupName, Type depClass, string retain) + { + this.AddManagedDependenciesForFunctionalityGroup(groupName, this.ResolveTypeName(depClass), retain); + } + protected void AddManagedDependenciesForFunctionalityGroup(string groupName, string depClassName, string retain) + { + this.groupManagedDependencies[groupName].Add(depClassName); + if (retain != null) + { + this.SetRetentionLevel(depClassName, retain); + } + } + protected void SetRetentionLevel(string className, string level) + { + this.retentionLevel[className] = level; + } + public string GetRetentionLevel(string className) + { + if (this.retentionLevel.ContainsKey(className)) + { + return this.retentionLevel[className]; + } + return "fields"; + } + protected void InitRuntimeClassRegistry() + { + BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(this.buildTarget); + this.AddFunctionalityGroup("Runtime", "[no manager]"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "GameObject"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "Material"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "PreloadData"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "PlayerSettings"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "InputManager"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "BuildSettings"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "GraphicsSettings"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "QualitySettings"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "MonoManager"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "AudioManager"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "ScriptMapper"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "DelayedCallManager"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "TimeManager"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "Cubemap"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "Texture3D"); + this.AddNativeDependenciesForFunctionalityGroup("Runtime", "LODGroup"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GameObject), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Transform), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Mesh), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SkinnedMeshRenderer), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(MeshRenderer), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UnityException), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Resolution)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(LayerMask)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SerializeField)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(WaitForSeconds)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(WaitForFixedUpdate)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(WaitForEndOfFrame)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AssetBundleRequest)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Event), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(HideInInspector)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SerializePrivateVariables)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SerializeField)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Font), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUIStyle)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUISkin), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUI), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(TextGenerator), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SendMouseEvents), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SetupCoroutine), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Coroutine)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AttributeHelperEngine), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(StackTraceUtility), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUIUtility), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUI), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Application), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Animation), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimationClip), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimationEvent)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AsyncOperation)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(CacheIndex)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Keyframe)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(RenderTexture)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimationCurve), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(BoneWeight)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Particle)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SliderState), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUI.ScrollViewState), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GUIScrollGroup), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(TextEditor), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(ClassLibraryInitializer), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AssetBundleCreateRequest), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "ImageEffectTransformsToLDR"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "ImageEffectOpaque"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Gradient), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GradientColorKey)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(GradientAlphaKey)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Canvas), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(RectTransform), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AssemblyIsEditorAssembly), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimatorStateInfo), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimatorTransitionInfo), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SkeletonBone), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(HumanBone), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UIVertex), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UICharInfo), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UILineInfo), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AudioClip), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "iPhone", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNI", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNIHelper", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "_AndroidJNIHelper", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaObject", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaClass", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaRunnableProxy", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SamsungTV", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(ISerializationCallbackReceiver), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "UnhandledExceptionHandler", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "Display", "all"); + if (buildTargetGroup == BuildTargetGroup.Android) + { + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNI", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNIHelper", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "_AndroidJNIHelper", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaObject", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaClass", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJavaRunnableProxy", "all"); + } + if (buildTargetGroup == BuildTargetGroup.SamsungTV) + { + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SamsungTV", "all"); + } + if (buildTargetGroup == BuildTargetGroup.iPhone) + { + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "iPhoneKeyboard"); + } + if (buildTargetGroup == BuildTargetGroup.iPhone || (buildTargetGroup == BuildTargetGroup.Standalone && (this.buildTarget == BuildTarget.StandaloneOSXIntel || this.buildTarget == BuildTarget.StandaloneOSXIntel64 || this.buildTarget == BuildTarget.StandaloneOSXUniversal))) + { + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SocialPlatforms.GameCenter.GameCenterPlatform", "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SocialPlatforms.GameCenter.GcLeaderboard", "all"); + } + if (buildTargetGroup == BuildTargetGroup.iPhone || buildTargetGroup == BuildTargetGroup.Android || buildTargetGroup == BuildTargetGroup.BB10 || buildTargetGroup == BuildTargetGroup.WP8 || buildTargetGroup == BuildTargetGroup.Tizen) + { + this.AddManagedDependenciesForFunctionalityGroup("Runtime", "TouchScreenKeyboard"); + } + this.AddFunctionalityGroup("Networking", "NetworkManager"); + this.AddNativeDependenciesForFunctionalityGroup("Networking", "NetworkManager"); + this.AddNativeDependenciesForFunctionalityGroup("Networking", "NetworkView"); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(Network)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(NetworkMessageInfo)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(RPC)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(HostData)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(BitStream)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(NetworkPlayer)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(NetworkViewID)); + this.AddManagedDependenciesForFunctionalityGroup("Networking", typeof(Ping), "all"); + this.AddFunctionalityGroup("Physics", "PhysicsManager"); + this.AddNativeDependenciesForFunctionalityGroup("Physics", "PhysicsManager"); + this.AddNativeDependenciesForFunctionalityGroup("Physics", "Rigidbody"); + this.AddNativeDependenciesForFunctionalityGroup("Physics", "Collider"); + this.AddManagedDependenciesForFunctionalityGroup("Physics", typeof(ControllerColliderHit)); + this.AddManagedDependenciesForFunctionalityGroup("Physics", typeof(RaycastHit)); + this.AddManagedDependenciesForFunctionalityGroup("Physics", typeof(Collision)); + this.AddManagedDependenciesForFunctionalityGroup("Physics", typeof(MeshCollider)); + this.AddFunctionalityGroup("Physics2D", "Physics2DSettings"); + this.AddNativeDependenciesForFunctionalityGroup("Physics2D", "Physics2DSettings"); + this.AddNativeDependenciesForFunctionalityGroup("Physics2D", "Rigidbody2D"); + this.AddNativeDependenciesForFunctionalityGroup("Physics2D", "Collider2D"); + this.AddNativeDependenciesForFunctionalityGroup("Physics2D", "Joint2D"); + this.AddNativeDependenciesForFunctionalityGroup("Physics2D", "PhysicsMaterial2D"); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(RaycastHit2D)); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(Collision2D)); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(JointMotor2D)); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(JointAngleLimits2D)); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(JointTranslationLimits2D)); + this.AddManagedDependenciesForFunctionalityGroup("Physics2D", typeof(JointSuspension2D)); + this.AddFunctionalityGroup("Terrain", "Terrain"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(Terrain), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(TerrainData), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(TerrainCollider), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(DetailPrototype), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(TreePrototype), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(TreeInstance), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Terrain", typeof(SplatPrototype), "all"); + this.AddFunctionalityGroup("Shuriken", "ParticleSystem"); + this.AddManagedDependenciesForFunctionalityGroup("Shuriken", typeof(ParticleSystem)); + this.AddManagedDependenciesForFunctionalityGroup("Shuriken", typeof(ParticleSystemRenderer)); + this.AddManagedBaseClass("UnityEngine.MonoBehaviour"); + this.AddManagedBaseClass("UnityEngine.ScriptableObject"); + if (buildTargetGroup == BuildTargetGroup.Android) + { + this.AddManagedBaseClass("UnityEngine.AndroidJavaProxy"); + } + } + internal void AddMethodToPreserve(string assembly, string @namespace, string klassName, string methodName) + { + this.m_MethodsToPreserve.Add(new RuntimeClassRegistry.MethodDescription + { + assembly = assembly, + fullTypeName = @namespace + ((@namespace.Length <= 0) ? string.Empty : ".") + klassName, + methodName = methodName + }); + } + internal List GetMethodsToPreserve() + { + return this.m_MethodsToPreserve; + } + internal void AddUserAssembly(string assembly) + { + if (!this.m_UserAssemblies.Contains(assembly)) + { + this.m_UserAssemblies.Add(assembly); + } + } + internal string[] GetUserAssemblies() + { + return this.m_UserAssemblies.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/SCEBuildSubtarget.cs b/UnityEditor/UnityEditor/SCEBuildSubtarget.cs new file mode 100644 index 00000000..7019034a --- /dev/null +++ b/UnityEditor/UnityEditor/SCEBuildSubtarget.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum SCEBuildSubtarget + { + PCHosted, + HddTitle, + BluRayTitle + } +} diff --git a/UnityEditor/UnityEditor/SaveAssetsProcessor.cs b/UnityEditor/UnityEditor/SaveAssetsProcessor.cs new file mode 100644 index 00000000..af4bc79d --- /dev/null +++ b/UnityEditor/UnityEditor/SaveAssetsProcessor.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + [Obsolete("Use UnityEditor.AssetModificationProcessor")] + public class SaveAssetsProcessor : AssetModificationProcessor + { + } +} diff --git a/UnityEditor/UnityEditor/SaveType.cs b/UnityEditor/UnityEditor/SaveType.cs new file mode 100644 index 00000000..8e2230b1 --- /dev/null +++ b/UnityEditor/UnityEditor/SaveType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum SaveType + { + Binary, + Text + } +} diff --git a/UnityEditor/UnityEditor/SaveWindowLayout.cs b/UnityEditor/UnityEditor/SaveWindowLayout.cs new file mode 100644 index 00000000..93d2eaef --- /dev/null +++ b/UnityEditor/UnityEditor/SaveWindowLayout.cs @@ -0,0 +1,35 @@ +using System; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SaveWindowLayout : EditorWindow + { + internal string m_LayoutName = Toolbar.lastLoadedLayoutName; + internal bool didFocus; + private void OnGUI() + { + GUILayout.Space(5f); + Event current = Event.current; + bool flag = current.type == EventType.KeyDown && (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter); + GUI.SetNextControlName("m_PreferencesName"); + this.m_LayoutName = EditorGUILayout.TextField(this.m_LayoutName, new GUILayoutOption[0]); + if (!this.didFocus) + { + this.didFocus = true; + EditorGUI.FocusTextInControl("m_PreferencesName"); + } + GUI.enabled = (this.m_LayoutName.Length != 0); + if (GUILayout.Button("Save", new GUILayoutOption[0]) || flag) + { + base.Close(); + string path = Path.Combine(WindowLayout.layoutsPreferencesPath, this.m_LayoutName + ".wlt"); + Toolbar.lastLoadedLayoutName = this.m_LayoutName; + WindowLayout.SaveWindowLayout(path); + InternalEditorUtility.ReloadWindowLayoutMenu(); + GUIUtility.ExitGUI(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SavedBool.cs b/UnityEditor/UnityEditor/SavedBool.cs new file mode 100644 index 00000000..8a09be11 --- /dev/null +++ b/UnityEditor/UnityEditor/SavedBool.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEditor +{ + internal class SavedBool + { + private bool m_Value; + private string m_Name; + public bool value + { + get + { + return this.m_Value; + } + set + { + if (this.m_Value == value) + { + return; + } + this.m_Value = value; + EditorPrefs.SetBool(this.m_Name, value); + } + } + public SavedBool(string name, bool value) + { + this.m_Name = name; + this.m_Value = EditorPrefs.GetBool(name, value); + } + public static implicit operator bool(SavedBool s) + { + return s.value; + } + } +} diff --git a/UnityEditor/UnityEditor/SavedFilter.cs b/UnityEditor/UnityEditor/SavedFilter.cs new file mode 100644 index 00000000..9ca33bbf --- /dev/null +++ b/UnityEditor/UnityEditor/SavedFilter.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEditor +{ + [Serializable] + internal class SavedFilter + { + public string m_Name; + public int m_Depth; + public float m_PreviewSize = -1f; + public int m_ID; + public SearchFilter m_Filter; + public SavedFilter(string name, SearchFilter filter, int depth, float previewSize) + { + this.m_Name = name; + this.m_Depth = depth; + this.m_Filter = filter; + this.m_PreviewSize = previewSize; + } + } +} diff --git a/UnityEditor/UnityEditor/SavedFloat.cs b/UnityEditor/UnityEditor/SavedFloat.cs new file mode 100644 index 00000000..81d66a07 --- /dev/null +++ b/UnityEditor/UnityEditor/SavedFloat.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEditor +{ + internal class SavedFloat + { + private float m_Value; + private string m_Name; + public float value + { + get + { + return this.m_Value; + } + set + { + if (this.m_Value == value) + { + return; + } + this.m_Value = value; + EditorPrefs.SetFloat(this.m_Name, value); + } + } + public SavedFloat(string name, float value) + { + this.m_Name = name; + this.m_Value = EditorPrefs.GetFloat(name, value); + } + public static implicit operator float(SavedFloat s) + { + return s.value; + } + } +} diff --git a/UnityEditor/UnityEditor/SavedGUIState.cs b/UnityEditor/UnityEditor/SavedGUIState.cs new file mode 100644 index 00000000..fa20763d --- /dev/null +++ b/UnityEditor/UnityEditor/SavedGUIState.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal struct SavedGUIState + { + internal GUILayoutUtility.LayoutCache layoutCache; + internal IntPtr guiState; + internal Vector2 screenManagerSize; + internal Rect renderManagerRect; + internal GUISkin skin; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetupSavedGUIState(out IntPtr state, out Vector2 screenManagerSize, out Rect renderManagerRect); + private static void Internal_ApplySavedGUIState(IntPtr state, Vector2 screenManagerSize, Rect renderManagerRect) + { + SavedGUIState.INTERNAL_CALL_Internal_ApplySavedGUIState(state, ref screenManagerSize, ref renderManagerRect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_ApplySavedGUIState(IntPtr state, ref Vector2 screenManagerSize, ref Rect renderManagerRect); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int Internal_GetGUIDepth(); + internal static SavedGUIState Create() + { + SavedGUIState result = default(SavedGUIState); + if (SavedGUIState.Internal_GetGUIDepth() > 0) + { + result.skin = GUI.skin; + result.layoutCache = new GUILayoutUtility.LayoutCache(GUILayoutUtility.current); + SavedGUIState.Internal_SetupSavedGUIState(out result.guiState, out result.screenManagerSize, out result.renderManagerRect); + } + return result; + } + internal void ApplyAndForget() + { + if (this.layoutCache != null) + { + GUILayoutUtility.current = this.layoutCache; + GUI.skin = this.skin; + SavedGUIState.Internal_ApplySavedGUIState(this.guiState, this.screenManagerSize, this.renderManagerRect); + GUIClip.Reapply(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SavedInt.cs b/UnityEditor/UnityEditor/SavedInt.cs new file mode 100644 index 00000000..60caacc9 --- /dev/null +++ b/UnityEditor/UnityEditor/SavedInt.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEditor +{ + internal class SavedInt + { + private int m_Value; + private string m_Name; + public int value + { + get + { + return this.m_Value; + } + set + { + if (this.m_Value == value) + { + return; + } + this.m_Value = value; + EditorPrefs.SetInt(this.m_Name, value); + } + } + public SavedInt(string name, int value) + { + this.m_Name = name; + this.m_Value = EditorPrefs.GetInt(name, value); + } + public static implicit operator int(SavedInt s) + { + return s.value; + } + } +} diff --git a/UnityEditor/UnityEditor/SavedRenderTargetState.cs b/UnityEditor/UnityEditor/SavedRenderTargetState.cs new file mode 100644 index 00000000..944cfc36 --- /dev/null +++ b/UnityEditor/UnityEditor/SavedRenderTargetState.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SavedRenderTargetState + { + private RenderTexture renderTexture; + private Rect viewport; + private Rect scissor; + internal SavedRenderTargetState() + { + GL.PushMatrix(); + if (ShaderUtil.hardwareSupportsRectRenderTexture) + { + this.renderTexture = RenderTexture.active; + } + this.viewport = ShaderUtil.rawViewportRect; + this.scissor = ShaderUtil.rawScissorRect; + } + internal void Restore() + { + if (ShaderUtil.hardwareSupportsRectRenderTexture) + { + EditorGUIUtility.SetRenderTextureNoViewport(this.renderTexture); + } + ShaderUtil.rawViewportRect = this.viewport; + ShaderUtil.rawScissorRect = this.scissor; + GL.PopMatrix(); + } + } +} diff --git a/UnityEditor/UnityEditor/SavedSearchFilters.cs b/UnityEditor/UnityEditor/SavedSearchFilters.cs new file mode 100644 index 00000000..7954b545 --- /dev/null +++ b/UnityEditor/UnityEditor/SavedSearchFilters.cs @@ -0,0 +1,408 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [FilePath("SearchFilters", FilePathAttribute.Location.PreferencesFolder)] + internal class SavedSearchFilters : ScriptableSingleton + { + [SerializeField] + private List m_SavedFilters; + private Action m_SavedFiltersChanged; + private bool m_AllowHierarchy; + public static int AddSavedFilter(string displayName, SearchFilter filter, float previewSize) + { + return ScriptableSingleton.instance.Add(displayName, filter, previewSize, SavedSearchFilters.GetRootInstanceID(), true); + } + public static int AddSavedFilterAfterInstanceID(string displayName, SearchFilter filter, float previewSize, int insertAfterID, bool addAsChild) + { + return ScriptableSingleton.instance.Add(displayName, filter, previewSize, insertAfterID, addAsChild); + } + public static void RemoveSavedFilter(int instanceID) + { + ScriptableSingleton.instance.Remove(instanceID); + } + public static bool IsSavedFilter(int instanceID) + { + return ScriptableSingleton.instance.IndexOf(instanceID) >= 0; + } + public static int GetRootInstanceID() + { + return ScriptableSingleton.instance.GetRoot(); + } + public static SearchFilter GetFilter(int instanceID) + { + SavedFilter savedFilter = ScriptableSingleton.instance.Find(instanceID); + if (savedFilter != null && savedFilter.m_Filter != null) + { + return ObjectCopier.DeepClone(savedFilter.m_Filter); + } + return null; + } + public static float GetPreviewSize(int instanceID) + { + SavedFilter savedFilter = ScriptableSingleton.instance.Find(instanceID); + if (savedFilter != null) + { + return savedFilter.m_PreviewSize; + } + return -1f; + } + public static string GetName(int instanceID) + { + SavedFilter savedFilter = ScriptableSingleton.instance.Find(instanceID); + if (savedFilter != null) + { + return savedFilter.m_Name; + } + Debug.LogError(string.Concat(new object[] + { + "Could not find saved filter ", + instanceID, + " ", + ScriptableSingleton.instance.ToString() + })); + return string.Empty; + } + public static void SetName(int instanceID, string name) + { + SavedFilter savedFilter = ScriptableSingleton.instance.Find(instanceID); + if (savedFilter != null) + { + savedFilter.m_Name = name; + ScriptableSingleton.instance.Changed(); + } + else + { + Debug.LogError(string.Concat(new object[] + { + "Could not set name of saved filter ", + instanceID, + " ", + ScriptableSingleton.instance.ToString() + })); + } + } + public static void UpdateExistingSavedFilter(int instanceID, SearchFilter filter, float previewSize) + { + ScriptableSingleton.instance.UpdateFilter(instanceID, filter, previewSize); + } + public static TreeViewItem ConvertToTreeView() + { + return ScriptableSingleton.instance.BuildTreeView(); + } + public static void AddChangeListener(Action callback) + { + SavedSearchFilters expr_05 = ScriptableSingleton.instance; + expr_05.m_SavedFiltersChanged = (Action)Delegate.Remove(expr_05.m_SavedFiltersChanged, callback); + SavedSearchFilters expr_20 = ScriptableSingleton.instance; + expr_20.m_SavedFiltersChanged = (Action)Delegate.Combine(expr_20.m_SavedFiltersChanged, callback); + } + public static void MoveSavedFilter(int instanceID, int parentInstanceID, int targetInstanceID, bool after) + { + ScriptableSingleton.instance.Move(instanceID, parentInstanceID, targetInstanceID, after); + } + public static bool CanMoveSavedFilter(int instanceID, int parentInstanceID, int targetInstanceID, bool after) + { + return ScriptableSingleton.instance.IsValidMove(instanceID, parentInstanceID, targetInstanceID, after); + } + public static bool AllowsHierarchy() + { + return ScriptableSingleton.instance.m_AllowHierarchy; + } + private bool IsValidMove(int instanceID, int parentInstanceID, int targetInstanceID, bool after) + { + int num = this.IndexOf(instanceID); + int num2 = this.IndexOf(parentInstanceID); + int num3 = this.IndexOf(targetInstanceID); + if (num < 0 || num2 < 0 || num3 < 0) + { + Debug.LogError(string.Concat(new object[] + { + "Move of a SavedFilter has invalid input: ", + num, + " ", + num2, + " ", + num3 + })); + return false; + } + if (instanceID == targetInstanceID) + { + return false; + } + for (int i = num + 1; i < this.m_SavedFilters.Count; i++) + { + if (this.m_SavedFilters[i].m_Depth <= this.m_SavedFilters[num].m_Depth) + { + break; + } + if (i == num3 || i == num2) + { + return false; + } + } + return true; + } + private void Move(int instanceID, int parentInstanceID, int targetInstanceID, bool after) + { + if (!this.IsValidMove(instanceID, parentInstanceID, targetInstanceID, after)) + { + return; + } + int index = this.IndexOf(instanceID); + int index2 = this.IndexOf(parentInstanceID); + int num = this.IndexOf(targetInstanceID); + SavedFilter savedFilter = this.m_SavedFilters[index]; + SavedFilter savedFilter2 = this.m_SavedFilters[index2]; + int num2 = 0; + if (this.m_AllowHierarchy) + { + num2 = savedFilter2.m_Depth + 1 - savedFilter.m_Depth; + } + List savedFilterAndChildren = this.GetSavedFilterAndChildren(instanceID); + this.m_SavedFilters.RemoveRange(index, savedFilterAndChildren.Count); + foreach (SavedFilter current in savedFilterAndChildren) + { + current.m_Depth += num2; + } + num = this.IndexOf(targetInstanceID); + if (num != -1) + { + this.m_SavedFilters.InsertRange(num + 1, savedFilterAndChildren); + } + this.Changed(); + } + private void UpdateFilter(int instanceID, SearchFilter filter, float previewSize) + { + SavedFilter savedFilter = this.Find(instanceID); + if (savedFilter != null) + { + if (filter != null) + { + SearchFilter filter2 = ObjectCopier.DeepClone(filter); + savedFilter.m_Filter = filter2; + } + savedFilter.m_PreviewSize = previewSize; + this.Changed(); + } + else + { + Debug.LogError(string.Concat(new object[] + { + "Could not find saved filter ", + instanceID, + " ", + ScriptableSingleton.instance.ToString() + })); + } + } + private int GetNextAvailableID() + { + List list = new List(); + foreach (SavedFilter current in this.m_SavedFilters) + { + if (current.m_ID >= ProjectWindowUtil.k_FavoritesStartInstanceID) + { + list.Add(current.m_ID); + } + } + list.Sort(); + int num = ProjectWindowUtil.k_FavoritesStartInstanceID; + for (int i = 0; i < 1000; i++) + { + if (list.BinarySearch(num) < 0) + { + return num; + } + num++; + } + Debug.LogError(string.Concat(new object[] + { + "Could not assign valid ID to saved filter ", + DebugUtils.ListToString(list), + " ", + num + })); + return ProjectWindowUtil.k_FavoritesStartInstanceID + 1000; + } + private int Add(string displayName, SearchFilter filter, float previewSize, int insertAfterInstanceID, bool addAsChild) + { + SearchFilter searchFilter = null; + if (filter != null) + { + searchFilter = ObjectCopier.DeepClone(filter); + } + if (searchFilter.GetState() == SearchFilter.State.SearchingInAllAssets || searchFilter.GetState() == SearchFilter.State.SearchingInAssetStore) + { + searchFilter.folders = new string[0]; + } + int num = 0; + if (insertAfterInstanceID != 0) + { + num = this.IndexOf(insertAfterInstanceID); + if (num == -1) + { + Debug.LogError("Invalid insert position"); + return 0; + } + } + int depth = this.m_SavedFilters[num].m_Depth + ((!addAsChild) ? 0 : 1); + SavedFilter savedFilter = new SavedFilter(displayName, searchFilter, depth, previewSize); + savedFilter.m_ID = this.GetNextAvailableID(); + if (this.m_SavedFilters.Count == 0) + { + this.m_SavedFilters.Add(savedFilter); + } + else + { + this.m_SavedFilters.Insert(num + 1, savedFilter); + } + this.Changed(); + return savedFilter.m_ID; + } + private List GetSavedFilterAndChildren(int instanceID) + { + List list = new List(); + int num = this.IndexOf(instanceID); + if (num >= 0) + { + list.Add(this.m_SavedFilters[num]); + for (int i = num + 1; i < this.m_SavedFilters.Count; i++) + { + if (this.m_SavedFilters[i].m_Depth <= this.m_SavedFilters[num].m_Depth) + { + break; + } + list.Add(this.m_SavedFilters[i]); + } + } + return list; + } + private void Remove(int instanceID) + { + int num = this.IndexOf(instanceID); + if (num >= 1) + { + List savedFilterAndChildren = this.GetSavedFilterAndChildren(instanceID); + if (savedFilterAndChildren.Count > 0) + { + this.m_SavedFilters.RemoveRange(num, savedFilterAndChildren.Count); + this.Changed(); + } + } + } + private int IndexOf(int instanceID) + { + for (int i = 0; i < this.m_SavedFilters.Count; i++) + { + if (this.m_SavedFilters[i].m_ID == instanceID) + { + return i; + } + } + return -1; + } + private SavedFilter Find(int instanceID) + { + int num = this.IndexOf(instanceID); + if (num >= 0) + { + return this.m_SavedFilters[num]; + } + return null; + } + private void Init() + { + if (this.m_SavedFilters == null || this.m_SavedFilters.Count == 0) + { + this.m_SavedFilters = new List(); + this.m_SavedFilters.Add(new SavedFilter("Favorites", null, 0, -1f)); + } + SearchFilter searchFilter = new SearchFilter(); + searchFilter.classNames = new string[0]; + this.m_SavedFilters[0].m_Name = "Favorites"; + this.m_SavedFilters[0].m_Filter = searchFilter; + this.m_SavedFilters[0].m_Depth = 0; + this.m_SavedFilters[0].m_ID = ProjectWindowUtil.k_FavoritesStartInstanceID; + for (int i = 0; i < this.m_SavedFilters.Count; i++) + { + if (this.m_SavedFilters[i].m_ID < ProjectWindowUtil.k_FavoritesStartInstanceID) + { + this.m_SavedFilters[i].m_ID = this.GetNextAvailableID(); + } + } + if (!this.m_AllowHierarchy) + { + for (int j = 1; j < this.m_SavedFilters.Count; j++) + { + this.m_SavedFilters[j].m_Depth = 1; + } + } + } + private int GetRoot() + { + if (this.m_SavedFilters != null && this.m_SavedFilters.Count > 0) + { + return this.m_SavedFilters[0].m_ID; + } + return 0; + } + private TreeViewItem BuildTreeView() + { + this.Init(); + if (this.m_SavedFilters.Count == 0) + { + Debug.LogError("BuildTreeView: No saved filters! We should at least have a root"); + return null; + } + TreeViewItem treeViewItem = null; + List list = new List(); + for (int i = 0; i < this.m_SavedFilters.Count; i++) + { + SavedFilter savedFilter = this.m_SavedFilters[i]; + int iD = savedFilter.m_ID; + int depth = savedFilter.m_Depth; + bool isFolder = savedFilter.m_Filter.GetState() == SearchFilter.State.FolderBrowsing; + TreeViewItem treeViewItem2 = new SearchFilterTreeItem(iD, depth, null, savedFilter.m_Name, isFolder); + if (i == 0) + { + treeViewItem = treeViewItem2; + } + else + { + list.Add(treeViewItem2); + } + } + TreeViewUtility.SetChildParentReferences(list, treeViewItem); + return treeViewItem; + } + private void Changed() + { + bool saveAsText = true; + this.Save(saveAsText); + if (this.m_SavedFiltersChanged != null) + { + this.m_SavedFiltersChanged(); + } + } + public override string ToString() + { + string text = "Saved Filters "; + for (int i = 0; i < this.m_SavedFilters.Count; i++) + { + int iD = this.m_SavedFilters[i].m_ID; + SavedFilter savedFilter = this.m_SavedFilters[i]; + text += string.Format(": {0} ({1})({2})({3}) ", new object[] + { + savedFilter.m_Name, + iD, + savedFilter.m_Depth, + savedFilter.m_PreviewSize + }); + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditor/ScaleTool.cs b/UnityEditor/UnityEditor/ScaleTool.cs new file mode 100644 index 00000000..9177fad1 --- /dev/null +++ b/UnityEditor/UnityEditor/ScaleTool.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ScaleTool : ManipulationTool + { + private static ScaleTool s_Instance; + private static Vector3 s_CurrentScale = Vector3.one; + public static void OnGUI(SceneView view) + { + if (ScaleTool.s_Instance == null) + { + ScaleTool.s_Instance = new ScaleTool(); + } + ScaleTool.s_Instance.OnToolGUI(view); + } + public override void ToolGUI(SceneView view, Vector3 handlePosition, bool isStatic) + { + Quaternion quaternion = (Selection.transforms.Length <= 1) ? Tools.handleLocalRotation : Tools.handleRotation; + TransformManipulator.DebugAlignment(quaternion); + if (Event.current.type == EventType.MouseDown) + { + ScaleTool.s_CurrentScale = Vector3.one; + } + EditorGUI.BeginChangeCheck(); + TransformManipulator.BeginManipulationHandling(true); + ScaleTool.s_CurrentScale = Handles.ScaleHandle(ScaleTool.s_CurrentScale, handlePosition, quaternion, HandleUtility.GetHandleSize(handlePosition)); + TransformManipulator.EndManipulationHandling(); + if (EditorGUI.EndChangeCheck() && !isStatic) + { + TransformManipulator.SetScaleDelta(ScaleTool.s_CurrentScale, quaternion); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SceneFXWindow.cs b/UnityEditor/UnityEditor/SceneFXWindow.cs new file mode 100644 index 00000000..cbe66032 --- /dev/null +++ b/UnityEditor/UnityEditor/SceneFXWindow.cs @@ -0,0 +1,112 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneFXWindow : EditorWindow + { + private class Styles + { + public GUIStyle background = "grey_border"; + public GUIStyle menuItem = "MenuItem"; + } + private const float kFrameWidth = 1f; + private static SceneFXWindow s_SceneFXWindow; + private static long s_LastClosedTime; + private static SceneFXWindow.Styles s_Styles; + private SceneView m_SceneView; + private SceneFXWindow() + { + base.hideFlags = HideFlags.DontSave; + base.wantsMouseMove = true; + } + private float GetHeight() + { + return 64f; + } + private void OnDisable() + { + SceneFXWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + SceneFXWindow.s_SceneFXWindow = null; + } + internal static bool ShowAtPosition(Rect buttonRect, SceneView view) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= SceneFXWindow.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (SceneFXWindow.s_SceneFXWindow == null) + { + SceneFXWindow.s_SceneFXWindow = ScriptableObject.CreateInstance(); + } + SceneFXWindow.s_SceneFXWindow.Init(buttonRect, view); + return true; + } + return false; + } + private void Init(Rect buttonRect, SceneView view) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + this.m_SceneView = view; + float num = 2f + this.GetHeight(); + num = Mathf.Min(num, 900f); + Vector2 windowSize = new Vector2(150f, num); + base.ShowAsDropDown(buttonRect, windowSize); + } + internal void OnGUI() + { + if (Event.current.type == EventType.Layout) + { + return; + } + if (Event.current.type == EventType.MouseMove) + { + Event.current.Use(); + } + if (SceneFXWindow.s_Styles == null) + { + SceneFXWindow.s_Styles = new SceneFXWindow.Styles(); + } + this.Draw(this.GetHeight()); + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, SceneFXWindow.s_Styles.background); + } + private void Draw(float height) + { + if (this.m_SceneView == null || this.m_SceneView.m_SceneViewState == null) + { + return; + } + Rect rect = new Rect(1f, 1f, base.position.width - 2f, 16f); + SceneView.SceneViewState state = this.m_SceneView.m_SceneViewState; + this.DrawListElement(rect, "Skybox", state.showSkybox, delegate(bool value) + { + state.showSkybox = value; + }); + rect.y += 16f; + this.DrawListElement(rect, "Fog", state.showFog, delegate(bool value) + { + state.showFog = value; + }); + rect.y += 16f; + this.DrawListElement(rect, "Flares", state.showFlares, delegate(bool value) + { + state.showFlares = value; + }); + rect.y += 16f; + this.DrawListElement(rect, "Animated Materials", state.showMaterialUpdate, delegate(bool value) + { + state.showMaterialUpdate = value; + }); + rect.y += 16f; + } + private void DrawListElement(Rect rect, string toggleName, bool value, Action setValue) + { + EditorGUI.BeginChangeCheck(); + bool obj = GUI.Toggle(rect, value, EditorGUIUtility.TempContent(toggleName), SceneFXWindow.s_Styles.menuItem); + if (EditorGUI.EndChangeCheck()) + { + setValue(obj); + this.m_SceneView.Repaint(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs b/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs new file mode 100644 index 00000000..1d43936c --- /dev/null +++ b/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneHierarchySortingWindow : EditorWindow + { + private class Styles + { + public GUIStyle background = "grey_border"; + public GUIStyle menuItem = "MenuItem"; + } + public class InputData + { + public string m_Name; + public bool m_Selected; + } + public delegate void OnSelectCallback(SceneHierarchySortingWindow.InputData element); + private const float kFrameWidth = 1f; + private static SceneHierarchySortingWindow s_SceneHierarchySortingWindow; + private static long s_LastClosedTime; + private static SceneHierarchySortingWindow.Styles s_Styles; + private List m_Data; + private SceneHierarchySortingWindow.OnSelectCallback m_Callback; + private SceneHierarchySortingWindow() + { + base.hideFlags = HideFlags.DontSave; + base.wantsMouseMove = true; + } + private float GetHeight() + { + return 16f * (float)this.m_Data.Count; + } + private float GetWidth() + { + float num = 0f; + foreach (SceneHierarchySortingWindow.InputData current in this.m_Data) + { + float x = SceneHierarchySortingWindow.s_Styles.menuItem.CalcSize(GUIContent.Temp(current.m_Name)).x; + if (x > num) + { + num = x; + } + } + return num; + } + private void OnDisable() + { + SceneHierarchySortingWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + } + internal static bool ShowAtPosition(Vector2 pos, List data, SceneHierarchySortingWindow.OnSelectCallback callback) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= SceneHierarchySortingWindow.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (SceneHierarchySortingWindow.s_SceneHierarchySortingWindow == null) + { + SceneHierarchySortingWindow.s_SceneHierarchySortingWindow = ScriptableObject.CreateInstance(); + } + SceneHierarchySortingWindow.s_SceneHierarchySortingWindow.Init(pos, data, callback); + return true; + } + return false; + } + private void Init(Vector2 pos, List data, SceneHierarchySortingWindow.OnSelectCallback callback) + { + Rect rect = new Rect(pos.x, pos.y - 16f, 16f, 16f); + rect = GUIUtility.GUIToScreenRect(rect); + data.Sort((SceneHierarchySortingWindow.InputData lhs, SceneHierarchySortingWindow.InputData rhs) => lhs.m_Name.CompareTo(rhs.m_Name)); + this.m_Data = data; + this.m_Callback = callback; + if (SceneHierarchySortingWindow.s_Styles == null) + { + SceneHierarchySortingWindow.s_Styles = new SceneHierarchySortingWindow.Styles(); + } + float y = 2f + this.GetHeight(); + float x = 2f + this.GetWidth(); + Vector2 windowSize = new Vector2(x, y); + base.ShowAsDropDown(rect, windowSize); + } + internal void OnGUI() + { + if (Event.current.type == EventType.Layout) + { + return; + } + if (Event.current.type == EventType.MouseMove) + { + Event.current.Use(); + } + this.Draw(); + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, SceneHierarchySortingWindow.s_Styles.background); + } + private void Draw() + { + Rect rect = new Rect(1f, 1f, base.position.width - 2f, 16f); + foreach (SceneHierarchySortingWindow.InputData current in this.m_Data) + { + this.DrawListElement(rect, current); + rect.y += 16f; + } + } + private void DrawListElement(Rect rect, SceneHierarchySortingWindow.InputData data) + { + EditorGUI.BeginChangeCheck(); + GUI.Toggle(rect, data.m_Selected, EditorGUIUtility.TempContent(data.m_Name), SceneHierarchySortingWindow.s_Styles.menuItem); + if (EditorGUI.EndChangeCheck()) + { + this.m_Callback(data); + base.Close(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SceneHierarchyWindow.cs b/UnityEditor/UnityEditor/SceneHierarchyWindow.cs new file mode 100644 index 00000000..a6cdd01f --- /dev/null +++ b/UnityEditor/UnityEditor/SceneHierarchyWindow.cs @@ -0,0 +1,658 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneHierarchyWindow : SearchableEditorWindow + { + private class Styles + { + private const string kCustomSorting = "CustomSorting"; + private const string kWarningSymbol = "console.warnicon.sml"; + private const string kWarningMessage = "Custom fetch is taking a lot of time. Could effect editor frame rate."; + public GUIContent defaultSortingContent = new GUIContent(EditorGUIUtility.FindTexture("CustomSorting")); + public GUIContent createContent = new GUIContent("Create"); + public GUIContent fetchWarning = new GUIContent(string.Empty, EditorGUIUtility.FindTexture("console.warnicon.sml"), "Custom fetch is taking a lot of time. Could effect editor frame rate."); + public GUIStyle MiniButton; + public Styles() + { + this.MiniButton = "ToolbarButton"; + } + } + private const float toolbarHeight = 17f; + private static SceneHierarchyWindow.Styles s_Styles; + private static List s_SceneHierarchyWindow = new List(); + private TreeView m_TreeView; + [SerializeField] + private TreeViewState m_TreeViewState; + private int m_TreeViewKeyboardControlID; + [SerializeField] + private string m_CurrentSortMethod = string.Empty; + [NonSerialized] + private int m_LastFramedID = -1; + private List m_SortFunctionNames; + private Dictionary m_SortFunctions; + private bool m_AllowAlphaNumericalSort; + private bool m_AllowManualSort; + [NonSerialized] + private bool m_DidSelectSearchResult; + private string currentSortMethod + { + get + { + return this.m_CurrentSortMethod; + } + set + { + this.m_CurrentSortMethod = value; + if (!this.m_SortFunctions.ContainsKey(this.m_CurrentSortMethod)) + { + if (this.m_AllowManualSort) + { + this.m_CurrentSortMethod = "TransformSort"; + } + else + { + this.m_CurrentSortMethod = "AlphabeticalSort"; + } + } + GameObjectTreeViewDataSource gameObjectTreeViewDataSource = this.treeView.data as GameObjectTreeViewDataSource; + gameObjectTreeViewDataSource.compareData.comparerImpl = this.m_SortFunctions[this.m_CurrentSortMethod]; + gameObjectTreeViewDataSource.compareData.comparerImplementsCompare = (gameObjectTreeViewDataSource.compareData.comparerImpl.GetType().GetMethod("Compare").DeclaringType != typeof(BaseHierarchySort)); + AssetOrGameObjectTreeViewDragging assetOrGameObjectTreeViewDragging = this.treeView.dragging as AssetOrGameObjectTreeViewDragging; + assetOrGameObjectTreeViewDragging.allowDragBetween = !gameObjectTreeViewDataSource.compareData.comparerImplementsCompare; + } + } + private bool hasSortMethods + { + get + { + return this.m_SortFunctions.Count > 1; + } + } + private Rect treeViewRect + { + get + { + return new Rect(0f, 17f, base.position.width, base.position.height - 17f); + } + } + private TreeView treeView + { + get + { + if (this.m_TreeView == null) + { + this.Init(); + } + return this.m_TreeView; + } + } + public static List GetAllSceneHierarchyWindows() + { + return SceneHierarchyWindow.s_SceneHierarchyWindow; + } + private void Init() + { + if (this.m_TreeView != null) + { + return; + } + if (this.m_TreeViewState == null) + { + this.m_TreeViewState = new TreeViewState(); + } + this.m_TreeView = new TreeView(this, this.m_TreeViewState); + TreeView expr_3A = this.m_TreeView; + expr_3A.itemDoubleClickedCallback = (Action)Delegate.Combine(expr_3A.itemDoubleClickedCallback, new Action(this.TreeViewItemDoubleClicked)); + TreeView expr_61 = this.m_TreeView; + expr_61.selectionChangedCallback = (Action)Delegate.Combine(expr_61.selectionChangedCallback, new Action(this.TreeViewSelectionChanged)); + TreeView expr_88 = this.m_TreeView; + expr_88.onGUIRowCallback = (Action)Delegate.Combine(expr_88.onGUIRowCallback, new Action(this.OnGUIAssetCallback)); + TreeView expr_AF = this.m_TreeView; + expr_AF.dragEndedCallback = (Action)Delegate.Combine(expr_AF.dragEndedCallback, new Action(this.OnDragEndedCallback)); + this.m_TreeView.deselectOnUnhandledMouseDown = true; + GameObjectTreeViewDataSource data = new GameObjectTreeViewDataSource(this.m_TreeView, 0, false, false); + ITreeViewDragging dragging = new AssetOrGameObjectTreeViewDragging(this.m_TreeView, HierarchyType.GameObjects); + ITreeViewGUI gui = new GameObjectTreeViewGUI(this.m_TreeView, false); + this.m_TreeView.Init(this.treeViewRect, data, gui, dragging); + this.m_AllowAlphaNumericalSort = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); + this.m_AllowManualSort = EditorPrefs.GetBool("AllowManualHierarchy", true); + this.SetUpSortMethodLists(); + this.m_TreeView.ReloadData(); + } + private void Awake() + { + this.m_HierarchyType = HierarchyType.GameObjects; + } + private void OnBecameVisible() + { + this.ReloadData(); + } + public override void OnEnable() + { + base.OnEnable(); + SceneHierarchyWindow.s_SceneHierarchyWindow.Add(this); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.ReloadData)); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(this.SearchChanged)); + } + public override void OnDisable() + { + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.ReloadData)); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(this.SearchChanged)); + SceneHierarchyWindow.s_SceneHierarchyWindow.Remove(this); + } + private void OnGUI() + { + if (SceneHierarchyWindow.s_Styles == null) + { + SceneHierarchyWindow.s_Styles = new SceneHierarchyWindow.Styles(); + } + this.m_TreeViewKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.OnEvent(); + Rect rect = new Rect(0f, 0f, base.position.width, base.position.height); + Event current = Event.current; + if (current.type == EventType.MouseDown && rect.Contains(current.mousePosition)) + { + this.treeView.EndPing(); + } + this.DoToolbar(); + float searchPathHeight = this.DoSearchResultPathGUI(); + this.DoTreeView(searchPathHeight); + this.ExecuteCommands(); + this.HandleContextClick(); + } + private void OnLostFocus() + { + this.treeView.EndNameEditing(true); + EditorGUI.EndEditingActiveTextField(); + } + private void TreeViewItemDoubleClicked(int instanceID) + { + SceneView.FrameLastActiveSceneView(); + } + private void TreeViewSelectionChanged(int[] ids) + { + Selection.instanceIDs = ids; + this.m_DidSelectSearchResult = !string.IsNullOrEmpty(this.m_SearchFilter); + } + public void SetExpandedRecursive(int id, bool expand) + { + TreeViewItem treeViewItem = this.treeView.data.FindItem(id); + if (treeViewItem == null) + { + this.ReloadData(); + treeViewItem = this.treeView.data.FindItem(id); + } + if (treeViewItem != null) + { + this.treeView.data.SetExpandedWithChildren(treeViewItem, expand); + } + } + private void OnGUIAssetCallback(int instanceID, Rect rect) + { + if (EditorApplication.hierarchyWindowItemOnGUI != null) + { + EditorApplication.hierarchyWindowItemOnGUI(instanceID, rect); + } + } + private void OnDragEndedCallback(int[] draggedInstanceIds, bool draggedItemsFromOwnTreeView) + { + if (draggedInstanceIds != null && draggedItemsFromOwnTreeView) + { + this.ReloadData(); + this.treeView.SetSelection(draggedInstanceIds, true); + this.treeView.NotifyListenersThatSelectionChanged(); + base.Repaint(); + GUIUtility.ExitGUI(); + } + } + public void ReloadData() + { + this.treeView.ReloadData(); + } + public void SearchChanged() + { + GameObjectTreeViewDataSource gameObjectTreeViewDataSource = this.treeView.data as GameObjectTreeViewDataSource; + if (gameObjectTreeViewDataSource.searchMode == (int)base.searchMode && gameObjectTreeViewDataSource.searchString == this.m_SearchFilter) + { + return; + } + gameObjectTreeViewDataSource.searchMode = (int)base.searchMode; + gameObjectTreeViewDataSource.searchString = this.m_SearchFilter; + if (this.m_SearchFilter == string.Empty) + { + this.treeView.Frame(Selection.activeInstanceID, true, false); + } + this.ReloadData(); + } + private void OnSelectionChange() + { + if (!this.treeView.IsVisible(Selection.activeInstanceID) && !string.IsNullOrEmpty(this.m_SearchFilter)) + { + base.ClearSearchFilter(); + } + this.treeView.SetSelection(Selection.instanceIDs, true); + base.Repaint(); + } + private void OnHierarchyChange() + { + this.treeView.EndNameEditing(false); + this.ReloadData(); + } + private float DoSearchResultPathGUI() + { + if (!base.hasSearchFilter) + { + return 0f; + } + GUILayout.FlexibleSpace(); + Rect rect = EditorGUILayout.BeginVertical(EditorStyles.inspectorBig, new GUILayoutOption[0]); + GUILayout.Label("Path:", new GUILayoutOption[0]); + int num = 1; + if (this.m_TreeView.HasSelection()) + { + TreeViewItem treeViewItem = this.m_TreeView.FindNode(this.m_TreeView.GetSelection()[0]); + if (treeViewItem != null) + { + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + hierarchyProperty.Find(treeViewItem.id, null); + do + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(hierarchyProperty.icon, new GUILayoutOption[0]); + GUILayout.Label(hierarchyProperty.name, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + num++; + } + while (hierarchyProperty.Parent()); + } + } + EditorGUILayout.EndVertical(); + GUILayout.Space(0f); + return rect.height; + } + private void OnEvent() + { + this.treeView.OnEvent(); + } + private void DoTreeView(float searchPathHeight) + { + Rect treeViewRect = this.treeViewRect; + treeViewRect.height -= searchPathHeight; + this.treeView.OnGUI(treeViewRect, this.m_TreeViewKeyboardControlID); + this.HandleUnusedDragEvents(this.treeViewRect); + } + private void HandleUnusedDragEvents(Rect rect) + { + Event current = Event.current; + EventType type = current.type; + if (type == EventType.DragUpdated || type == EventType.DragPerform) + { + if (rect.Contains(current.mousePosition)) + { + bool flag = current.type == EventType.DragPerform; + DragAndDrop.visualMode = InternalEditorUtility.HierarchyWindowDrag(null, flag, InternalEditorUtility.HierarchyDropMode.kHierarchyDropUpon); + if (flag && DragAndDrop.visualMode != DragAndDropVisualMode.None) + { + DragAndDrop.AcceptDrag(); + List list = new List(DragAndDrop.objectReferences); + int[] array = new int[list.Count]; + for (int i = 0; i < list.Count; i++) + { + if (!(list[i] == null)) + { + array[i] = list[i].GetInstanceID(); + } + } + this.OnDragEndedCallback(array, false); + } + current.Use(); + } + } + } + private void DoToolbar() + { + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + this.CreateGameObjectPopup(); + GUILayout.Space(6f); + GUILayout.FlexibleSpace(); + Event current = Event.current; + if (base.hasSearchFilterFocus && current.type == EventType.KeyDown && (current.keyCode == KeyCode.DownArrow || current.keyCode == KeyCode.UpArrow)) + { + GUIUtility.keyboardControl = this.m_TreeViewKeyboardControlID; + if (this.treeView.IsLastClickedPartOfVisibleRows()) + { + this.treeView.Frame(this.treeView.state.lastClickedID, true, false); + this.m_DidSelectSearchResult = !string.IsNullOrEmpty(this.m_SearchFilter); + } + else + { + this.treeView.OffsetSelection(1); + } + current.Use(); + } + base.SearchFieldGUI(); + GUILayout.Space(6f); + if (this.hasSortMethods) + { + if (Application.isPlaying && (this.treeView.data as GameObjectTreeViewDataSource).isFetchAIssue) + { + GUILayout.Toggle(false, SceneHierarchyWindow.s_Styles.fetchWarning, SceneHierarchyWindow.s_Styles.MiniButton, new GUILayoutOption[0]); + } + this.SortMethodsDropDown(); + } + GUILayout.EndHorizontal(); + } + internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + { + base.SetSearchFilter(searchFilter, searchMode, setAll); + if (this.m_DidSelectSearchResult && string.IsNullOrEmpty(searchFilter)) + { + this.m_DidSelectSearchResult = false; + this.FrameObjectPrivate(Selection.activeInstanceID, true, false); + if (GUIUtility.keyboardControl == 0) + { + GUIUtility.keyboardControl = this.m_TreeViewKeyboardControlID; + } + } + } + private void AddCreateGameObjectItemsToMenu(GenericMenu menu, UnityEngine.Object[] context, bool includeCreateEmptyChild) + { + string[] submenus = Unsupported.GetSubmenus("GameObject"); + string[] array = submenus; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + UnityEngine.Object[] temporaryContext = context; + if (includeCreateEmptyChild || !(text.ToLower() == "GameObject/Create Empty Child".ToLower())) + { + if (text.EndsWith("...")) + { + temporaryContext = null; + } + if (text.ToLower() == "GameObject/Center On Children".ToLower()) + { + return; + } + MenuUtils.ExtractMenuItemWithPath(text, menu, text.Substring(11), temporaryContext); + } + } + } + private void CreateGameObjectPopup() + { + Rect rect = GUILayoutUtility.GetRect(SceneHierarchyWindow.s_Styles.createContent, EditorStyles.toolbarDropDown, null); + if (Event.current.type == EventType.Repaint) + { + EditorStyles.toolbarDropDown.Draw(rect, SceneHierarchyWindow.s_Styles.createContent, false, false, false, false); + } + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = 0; + GenericMenu genericMenu = new GenericMenu(); + this.AddCreateGameObjectItemsToMenu(genericMenu, null, true); + genericMenu.DropDown(rect); + Event.current.Use(); + } + } + private void SortMethodsDropDown() + { + if (this.hasSortMethods) + { + GUIContent gUIContent = this.m_SortFunctions[this.currentSortMethod].content; + if (gUIContent == null) + { + gUIContent = SceneHierarchyWindow.s_Styles.defaultSortingContent; + gUIContent.tooltip = this.currentSortMethod; + } + Rect rect = GUILayoutUtility.GetRect(gUIContent, EditorStyles.toolbarButton); + if (EditorGUI.ButtonMouseDown(rect, gUIContent, FocusType.Passive, EditorStyles.toolbarButton) && SceneHierarchySortingWindow.ShowAtPosition(new Vector2(rect.x, rect.y + rect.height), this.m_SortFunctionNames, new SceneHierarchySortingWindow.OnSelectCallback(this.SortFunctionCallback))) + { + GUIUtility.ExitGUI(); + } + } + } + private void SetUpSortMethodLists() + { + this.m_SortFunctionNames = new List(); + this.m_SortFunctions = new Dictionary(); + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = 0; i < loadedAssemblies.Length; i++) + { + Assembly assembly = loadedAssemblies[i]; + foreach (BaseHierarchySort current in AssemblyHelper.FindImplementors(assembly)) + { + string text = current.ToString(); + int num = text.LastIndexOf('.'); + if (num > -1) + { + text = text.Substring(num + 1); + } + if (!(text == "TransformSort") || this.m_AllowManualSort) + { + if (!(text == "AlphabeticalSort") || this.m_AllowAlphaNumericalSort) + { + this.m_SortFunctions.Add(text, current); + SceneHierarchySortingWindow.InputData inputData = new SceneHierarchySortingWindow.InputData(); + inputData.m_Name = text; + this.m_SortFunctionNames.Add(inputData); + } + } + } + } + this.currentSortMethod = this.m_CurrentSortMethod; + foreach (SceneHierarchySortingWindow.InputData current2 in this.m_SortFunctionNames) + { + if (current2.m_Name == this.m_CurrentSortMethod) + { + current2.m_Selected = true; + break; + } + } + } + private void SortFunctionCallback(SceneHierarchySortingWindow.InputData data) + { + foreach (SceneHierarchySortingWindow.InputData current in this.m_SortFunctionNames) + { + current.m_Selected = (current == data); + } + this.currentSortMethod = data.m_Name; + this.treeView.SetSelection(this.treeView.GetSelection(), true); + this.treeView.ReloadData(); + } + public void DirtySortingMethods() + { + this.m_AllowAlphaNumericalSort = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); + this.m_AllowManualSort = EditorPrefs.GetBool("AllowManualHierarchy", true); + this.SetUpSortMethodLists(); + this.treeView.SetSelection(this.treeView.GetSelection(), true); + this.treeView.ReloadData(); + } + private void ExecuteCommands() + { + Event current = Event.current; + if (current.type != EventType.ExecuteCommand && current.type != EventType.ValidateCommand) + { + return; + } + bool flag = current.type == EventType.ExecuteCommand; + if (current.commandName == "Delete" || current.commandName == "SoftDelete") + { + if (flag) + { + this.DeleteGO(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "Duplicate") + { + if (flag) + { + this.DuplicateGO(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "Copy") + { + if (flag) + { + this.CopyGO(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "Paste") + { + if (flag) + { + this.PasteGO(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "SelectAll") + { + if (flag) + { + this.SelectAll(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "FrameSelected") + { + if (current.type == EventType.ExecuteCommand) + { + this.FrameObjectPrivate(Selection.activeInstanceID, true, true); + } + current.Use(); + GUIUtility.ExitGUI(); + } + else + { + if (current.commandName == "Find") + { + if (current.type == EventType.ExecuteCommand) + { + base.FocusSearchField(); + } + current.Use(); + } + } + } + } + } + } + } + } + private void HandleContextClick() + { + Event current = Event.current; + if (current.type != EventType.ContextClick) + { + return; + } + current.Use(); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupCopy"), false, new GenericMenu.MenuFunction(this.CopyGO)); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupPaste"), false, new GenericMenu.MenuFunction(this.PasteGO)); + genericMenu.AddSeparator(string.Empty); + if (!base.hasSearchFilter && this.m_TreeViewState.selectedIDs.Count == 1) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupRename"), false, new GenericMenu.MenuFunction(this.RenameGO)); + } + else + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupRename")); + } + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDuplicate"), false, new GenericMenu.MenuFunction(this.DuplicateGO)); + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDelete"), false, new GenericMenu.MenuFunction(this.DeleteGO)); + genericMenu.AddSeparator(string.Empty); + bool flag = false; + if (this.m_TreeViewState.selectedIDs.Count == 1) + { + GameObjectTreeViewItem gameObjectTreeViewItem = this.treeView.FindNode(this.m_TreeViewState.selectedIDs[0]) as GameObjectTreeViewItem; + if (gameObjectTreeViewItem != null) + { + UnityEngine.Object prefab = PrefabUtility.GetPrefabParent(gameObjectTreeViewItem.objectPPTR); + if (prefab != null) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab"), false, delegate + { + Selection.activeObject = prefab; + EditorGUIUtility.PingObject(prefab.GetInstanceID()); + }); + flag = true; + } + } + } + if (!flag) + { + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab")); + } + genericMenu.AddSeparator(string.Empty); + this.AddCreateGameObjectItemsToMenu(genericMenu, Selection.objects, false); + genericMenu.ShowAsContext(); + } + private void CopyGO() + { + Unsupported.CopyGameObjectsToPasteboard(); + } + private void PasteGO() + { + Unsupported.PasteGameObjectsFromPasteboard(); + } + private void DuplicateGO() + { + Unsupported.DuplicateGameObjectsUsingPasteboard(); + } + private void RenameGO() + { + this.treeView.BeginNameEditing(0f); + } + private void DeleteGO() + { + Unsupported.DeleteGameObjectSelection(); + } + private void SelectAll() + { + int[] visibleRowIDs = this.treeView.GetVisibleRowIDs(); + this.treeView.SetSelection(visibleRowIDs, false); + this.TreeViewSelectionChanged(visibleRowIDs); + } + public void FrameObject(int instanceID, bool ping) + { + this.FrameObjectPrivate(instanceID, true, ping); + } + private void FrameObjectPrivate(int instanceID, bool frame, bool ping) + { + if (instanceID == 0) + { + return; + } + if (this.m_LastFramedID != instanceID) + { + this.treeView.EndPing(); + } + this.SetSearchFilter(string.Empty, SearchableEditorWindow.SearchMode.All, true); + this.m_LastFramedID = instanceID; + this.treeView.Frame(instanceID, frame, ping); + this.FrameObjectPrivate(InternalEditorUtility.GetGameObjectInstanceIDFromComponent(instanceID), frame, ping); + } + } +} diff --git a/UnityEditor/UnityEditor/SceneModeUtility.cs b/UnityEditor/UnityEditor/SceneModeUtility.cs new file mode 100644 index 00000000..bd8ed65a --- /dev/null +++ b/UnityEditor/UnityEditor/SceneModeUtility.cs @@ -0,0 +1,220 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + public static class SceneModeUtility + { + private class Styles + { + public GUIStyle typeButton = "SearchModeFilter"; + } + private static Type s_FocusType; + private static SceneHierarchyWindow s_HierarchyWindow; + private static GUIContent s_NoneButtonContent; + private static SceneModeUtility.Styles s_Styles; + private static SceneModeUtility.Styles styles + { + get + { + if (SceneModeUtility.s_Styles == null) + { + SceneModeUtility.s_Styles = new SceneModeUtility.Styles(); + } + return SceneModeUtility.s_Styles; + } + } + public static T[] GetSelectedObjectsOfType(out GameObject[] gameObjects, params Type[] types) where T : UnityEngine.Object + { + if (types.Length == 0) + { + types = new Type[] + { + typeof(T) + }; + } + List list = new List(); + List list2 = new List(); + Transform[] transforms = Selection.GetTransforms((SelectionMode)12); + Transform[] array = transforms; + for (int i = 0; i < array.Length; i++) + { + Transform transform = array[i]; + Type[] array2 = types; + for (int j = 0; j < array2.Length; j++) + { + Type type = array2[j]; + UnityEngine.Object component = transform.gameObject.GetComponent(type); + if (component != null) + { + list.Add(transform.gameObject); + list2.Add((T)((object)component)); + break; + } + } + } + gameObjects = list.ToArray(); + return list2.ToArray(); + } + public static void SearchForType(Type type) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow)); + SceneHierarchyWindow sceneHierarchyWindow = (array.Length <= 0) ? null : (array[0] as SceneHierarchyWindow); + if (sceneHierarchyWindow) + { + SceneModeUtility.s_HierarchyWindow = sceneHierarchyWindow; + if (type == null || type == typeof(GameObject)) + { + SceneModeUtility.s_FocusType = null; + sceneHierarchyWindow.ClearSearchFilter(); + } + else + { + SceneModeUtility.s_FocusType = type; + if (sceneHierarchyWindow.searchMode == SearchableEditorWindow.SearchMode.Name) + { + sceneHierarchyWindow.searchMode = SearchableEditorWindow.SearchMode.All; + } + sceneHierarchyWindow.SetSearchFilter("t:" + type.Name, sceneHierarchyWindow.searchMode, false); + sceneHierarchyWindow.hasSearchFilterFocus = true; + } + } + else + { + SceneModeUtility.s_FocusType = null; + } + } + public static Type SearchBar(params Type[] types) + { + if (SceneModeUtility.s_NoneButtonContent == null) + { + SceneModeUtility.s_NoneButtonContent = EditorGUIUtility.IconContent("sv_icon_none"); + SceneModeUtility.s_NoneButtonContent.text = "None"; + } + if (SceneModeUtility.s_FocusType != null && (SceneModeUtility.s_HierarchyWindow == null || SceneModeUtility.s_HierarchyWindow.m_SearchFilter != "t:" + SceneModeUtility.s_FocusType.Name)) + { + SceneModeUtility.s_FocusType = null; + } + GUILayout.Label("Scene Filter:", new GUILayoutOption[0]); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUIContent label = EditorGUIUtility.TempContent("All", AssetPreview.GetMiniTypeThumbnail(typeof(GameObject))); + if (SceneModeUtility.TypeButton(label, SceneModeUtility.s_FocusType == null, SceneModeUtility.styles.typeButton)) + { + SceneModeUtility.SearchForType(null); + } + for (int i = 0; i < types.Length; i++) + { + Type type = types[i]; + Texture2D i2; + if (type == typeof(Terrain)) + { + i2 = (EditorGUIUtility.IconContent("Terrain Icon").image as Texture2D); + } + else + { + if (type == typeof(Renderer)) + { + i2 = (EditorGUIUtility.IconContent("MeshRenderer Icon").image as Texture2D); + } + else + { + i2 = AssetPreview.GetMiniTypeThumbnail(type); + } + } + string t = ObjectNames.NicifyVariableName(type.Name) + "s"; + GUIContent label2 = EditorGUIUtility.TempContent(t, i2); + if (SceneModeUtility.TypeButton(label2, type == SceneModeUtility.s_FocusType, SceneModeUtility.styles.typeButton)) + { + SceneModeUtility.SearchForType(type); + } + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + return SceneModeUtility.s_FocusType; + } + private static bool TypeButton(GUIContent label, bool selected, GUIStyle style) + { + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + bool flag = GUILayout.Toggle(selected, label, style, new GUILayoutOption[0]); + EditorGUIUtility.SetIconSize(Vector2.zero); + return flag && flag != selected; + } + public static bool StaticFlagField(string label, SerializedProperty property, int flag) + { + bool flag2 = (property.intValue & flag) != 0; + bool flag3 = (property.hasMultipleDifferentValuesBitwise & flag) != 0; + EditorGUI.showMixedValue = flag3; + EditorGUI.BeginChangeCheck(); + bool flag4 = EditorGUILayout.Toggle(label, flag2, new GUILayoutOption[0]); + if (!EditorGUI.EndChangeCheck()) + { + EditorGUI.showMixedValue = false; + return flag4 && !flag3; + } + if (!SceneModeUtility.SetStaticFlags(property.serializedObject.targetObjects, flag, flag4)) + { + return flag2 && !flag3; + } + return flag4; + } + public static bool SetStaticFlags(UnityEngine.Object[] targetObjects, int changedFlags, bool flagValue) + { + bool flag = changedFlags == -1; + StaticEditorFlags staticEditorFlags = (StaticEditorFlags)((!flag) ? ((int)Enum.Parse(typeof(StaticEditorFlags), changedFlags.ToString())) : 0); + GameObjectUtility.ShouldIncludeChildren shouldIncludeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(targetObjects.OfType(), "Change Static Flags", (!flag) ? string.Concat(new string[] + { + "Do you want to ", + (!flagValue) ? "disable" : "enable", + " the ", + ObjectNames.NicifyVariableName(staticEditorFlags.ToString()), + " flag for all the child objects as well?" + }) : ("Do you want to " + ((!flagValue) ? "disable" : "enable") + " the static flags for all the child objects as well?")); + if (shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.Cancel) + { + GUIUtility.ExitGUI(); + return false; + } + GameObject[] objects = SceneModeUtility.GetObjects(targetObjects, shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); + Undo.RecordObjects(objects, "Change Static Flags"); + GameObject[] array = objects; + for (int i = 0; i < array.Length; i++) + { + GameObject go = array[i]; + int num = (int)GameObjectUtility.GetStaticEditorFlags(go); + num = ((!flagValue) ? (num & ~changedFlags) : (num | changedFlags)); + GameObjectUtility.SetStaticEditorFlags(go, (StaticEditorFlags)num); + } + return true; + } + private static void GetObjectsRecurse(Transform root, List arr) + { + arr.Add(root.gameObject); + foreach (Transform root2 in root) + { + SceneModeUtility.GetObjectsRecurse(root2, arr); + } + } + public static GameObject[] GetObjects(UnityEngine.Object[] gameObjects, bool includeChildren) + { + List list = new List(); + if (!includeChildren) + { + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject item = (GameObject)gameObjects[i]; + list.Add(item); + } + } + else + { + for (int j = 0; j < gameObjects.Length; j++) + { + GameObject gameObject = (GameObject)gameObjects[j]; + SceneModeUtility.GetObjectsRecurse(gameObject.transform, list); + } + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/SceneView.cs b/UnityEditor/UnityEditor/SceneView.cs new file mode 100644 index 00000000..68b19493 --- /dev/null +++ b/UnityEditor/UnityEditor/SceneView.cs @@ -0,0 +1,1819 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + public class SceneView : SearchableEditorWindow + { + [Serializable] + public class SceneViewState + { + public bool showFog = true; + public bool showMaterialUpdate; + public bool showSkybox = true; + public bool showFlares = true; + public SceneViewState() + { + } + public SceneViewState(SceneView.SceneViewState other) + { + this.showFog = other.showFog; + this.showMaterialUpdate = other.showMaterialUpdate; + this.showSkybox = other.showSkybox; + this.showFlares = other.showFlares; + } + public bool IsAllOn() + { + return this.showFog && this.showMaterialUpdate && this.showSkybox && this.showFlares; + } + public void Toggle(bool value) + { + this.showFog = value; + this.showMaterialUpdate = value; + this.showSkybox = value; + this.showFlares = value; + } + } + private struct CursorRect + { + public Rect rect; + public MouseCursor cursor; + public CursorRect(Rect rect, MouseCursor cursor) + { + this.rect = rect; + this.cursor = cursor; + } + } + internal enum DraggingLockedState + { + NotDragging, + Dragging, + LookAt + } + public delegate void OnSceneFunc(SceneView sceneView); + private const float kOrthoThresholdAngle = 3f; + private const float kOneOverSqrt2 = 0.707106769f; + private const double k_MaxDoubleKeypressTime = 0.5; + private const float kPerspectiveFov = 90f; + public const float kToolbarHeight = 17f; + private static SceneView s_LastActiveSceneView; + private static SceneView s_CurrentDrawingSceneView; + private static PrefColor kSceneViewBackground = new PrefColor("Scene/Background", 0.278431f, 0.278431f, 0.278431f, 0f); + private static PrefColor kSceneViewWire = new PrefColor("Scene/Wireframe", 0f, 0f, 0f, 0.5f); + private static PrefColor kSceneViewWireOverlay = new PrefColor("Scene/Wireframe Overlay", 0f, 0f, 0f, 0.25f); + private static PrefColor kSceneViewWireActive = new PrefColor("Scene/Wireframe Active", 0.490196079f, 0.6901961f, 0.980392158f, 0.372549027f); + private static PrefColor kSceneViewWireSelected = new PrefColor("Scene/Wireframe Selected", 0.368627459f, 0.466666669f, 0.607843161f, 0.25f); + internal static Color kSceneViewFrontLight = new Color(0.769f, 0.769f, 0.769f, 1f); + internal static Color kSceneViewUpLight = new Color(0.212f, 0.227f, 0.259f, 1f); + internal static Color kSceneViewMidLight = new Color(0.114f, 0.125f, 0.133f, 1f); + internal static Color kSceneViewDownLight = new Color(0.047f, 0.043f, 0.035f, 1f); + [NonSerialized] + private static readonly Quaternion kDefaultRotation = Quaternion.LookRotation(new Vector3(-1f, -0.7f, -1f)); + [NonSerialized] + private static readonly float kDefaultViewSize = 10f; + [NonSerialized] + private static readonly Vector3 kDefaultPivot = Vector3.zero; + [NonSerialized] + private ActiveEditorTracker m_Tracker; + public bool m_SceneLighting; + public double lastFramingTime; + private static PrefKey k2DMode = new PrefKey("Tools/2D Mode", "2"); + private static bool waitingFor2DModeKeyUp; + [SerializeField] + private bool m_2DMode; + internal UnityEngine.Object m_OneClickDragObject; + [NonSerialized] + public bool m_AudioPlay; + private static SceneView s_AudioSceneView = null; + [SerializeField] + private AnimVector3 m_Position = new AnimVector3(SceneView.kDefaultPivot); + private static string[] s_RenderModes = new string[] + { + "Textured", + "Wireframe", + "Textured Wire", + "Render Paths", + "Lightmap Resolution" + }; + private static string[] s_OverlayModes = new string[] + { + "RGB", + "Alpha", + "Overdraw", + "Mipmaps" + }; + public static SceneView.OnSceneFunc onSceneGUIDelegate; + public DrawCameraMode m_RenderMode; + public int m_OverlayMode; + [SerializeField] + internal SceneView.SceneViewState m_SceneViewState; + [SerializeField] + private SceneViewGrid grid; + [SerializeField] + internal SceneViewRotation svRot; + [SerializeField] + internal AnimQuaternion m_Rotation = new AnimQuaternion(SceneView.kDefaultRotation); + [SerializeField] + private AnimFloat m_Size = new AnimFloat(SceneView.kDefaultViewSize); + [SerializeField] + internal AnimBool m_Ortho = new AnimBool(); + [NonSerialized] + private Camera m_Camera; + [SerializeField] + private Quaternion m_LastSceneViewRotation; + [SerializeField] + private bool m_LastSceneViewOrtho; + private static MouseCursor s_LastCursor = MouseCursor.Arrow; + private static List s_MouseRects = new List(); + private bool s_DraggingCursorIsCashed; + [NonSerialized] + private Light[] m_Light = new Light[3]; + private RectSelection m_RectSelection; + private static ArrayList s_SceneViews = new ArrayList(); + private static Material s_AlphaOverlayMaterial; + private static Shader s_ShowOverdrawShader; + private static Shader s_ShowMipsShader; + private static Shader s_ShowLightmapsShader; + private static Shader s_AuraShader; + private static Shader s_GrayScaleShader; + private static Texture2D s_MipColorsTexture; + private static GUIContent s_Fx = new GUIContent("Effects"); + private static GUIContent s_Lighting = EditorGUIUtility.IconContent("SceneviewLighting"); + private static GUIContent s_AudioPlay = EditorGUIUtility.IconContent("SceneviewAudio"); + private static GUIContent s_GizmosContent = new GUIContent("Gizmos"); + private static GUIContent s_2DMode = new GUIContent("2D"); + private static Tool s_CurrentTool; + private double m_StartSearchFilterTime = -1.0; + private RenderTexture m_SearchFilterTexture; + private int m_MainViewControlID; + [SerializeField] + private Shader m_ReplacementShader; + [SerializeField] + private string m_ReplacementString; + internal bool m_ShowSceneViewWindows; + private SceneViewOverlay m_SceneViewOverlay; + private EditorCache m_DragEditorCache; + private SceneView.DraggingLockedState m_DraggingLockedState; + [SerializeField] + private UnityEngine.Object m_LastLockedObject; + [SerializeField] + private bool m_ViewIsLockedToObject; + private static GUIStyle s_DropDownStyle; + private bool m_RequestedSceneViewFiltering; + private double m_lastRenderedTime; + public static SceneView lastActiveSceneView + { + get + { + return SceneView.s_LastActiveSceneView; + } + } + public static SceneView currentDrawingSceneView + { + get + { + return SceneView.s_CurrentDrawingSceneView; + } + } + public bool in2DMode + { + get + { + return this.m_2DMode; + } + set + { + if (this.m_2DMode != value && Tools.viewTool != ViewTool.FPS && Tools.viewTool != ViewTool.Orbit) + { + this.m_2DMode = value; + this.On2DModeChange(); + } + } + } + public DrawCameraMode renderMode + { + get + { + return this.m_RenderMode; + } + set + { + this.m_RenderMode = value; + } + } + public Quaternion lastSceneViewRotation + { + get + { + if (this.m_LastSceneViewRotation == new Quaternion(0f, 0f, 0f, 0f)) + { + this.m_LastSceneViewRotation = Quaternion.identity; + } + return this.m_LastSceneViewRotation; + } + set + { + this.m_LastSceneViewRotation = value; + } + } + internal float cameraDistance + { + get + { + float num = this.m_Ortho.Fade(90f, 0f); + if (!this.camera.orthographic) + { + return this.size / Mathf.Tan(num * 0.5f * 0.0174532924f); + } + return this.size * 2f; + } + } + public static ArrayList sceneViews + { + get + { + return SceneView.s_SceneViews; + } + } + public Camera camera + { + get + { + return this.m_Camera; + } + } + internal SceneView.DraggingLockedState draggingLocked + { + set + { + this.m_DraggingLockedState = value; + } + } + internal bool viewIsLockedToObject + { + get + { + return this.m_ViewIsLockedToObject; + } + set + { + if (value) + { + this.m_LastLockedObject = Selection.activeObject; + } + else + { + this.m_LastLockedObject = null; + } + this.m_ViewIsLockedToObject = value; + this.draggingLocked = SceneView.DraggingLockedState.LookAt; + } + } + private GUIStyle effectsDropDownStyle + { + get + { + if (SceneView.s_DropDownStyle == null) + { + SceneView.s_DropDownStyle = "GV Gizmo DropDown"; + } + return SceneView.s_DropDownStyle; + } + } + public Vector3 pivot + { + get + { + return this.m_Position.value; + } + set + { + this.m_Position.value = value; + } + } + public Quaternion rotation + { + get + { + return this.m_Rotation.value; + } + set + { + this.m_Rotation.value = value; + } + } + public float size + { + get + { + return this.m_Size.value; + } + set + { + if (value > 40000f) + { + value = 40000f; + } + this.m_Size.value = value; + } + } + public bool orthographic + { + get + { + return this.m_Ortho.value; + } + set + { + this.m_Ortho.value = value; + } + } + internal Quaternion cameraTargetRotation + { + get + { + return this.m_Rotation.target; + } + } + internal Vector3 cameraTargetPosition + { + get + { + return this.m_Position.target + this.m_Rotation.target * new Vector3(0f, 0f, this.cameraDistance); + } + } + public SceneView() + { + this.m_HierarchyType = HierarchyType.GameObjects; + base.depthBufferBits = 32; + base.antiAlias = -1; + } + internal static void AddCursorRect(Rect rect, MouseCursor cursor) + { + if (Event.current.type == EventType.Repaint) + { + SceneView.s_MouseRects.Add(new SceneView.CursorRect(rect, cursor)); + } + } + public void SetSceneViewShaderReplace(Shader shader, string replaceString) + { + this.m_ReplacementShader = shader; + this.m_ReplacementString = replaceString; + } + public static bool FrameLastActiveSceneView() + { + return !(SceneView.lastActiveSceneView == null) && SceneView.lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent("FrameSelected")); + } + public static bool FrameLastActiveSceneViewWithLock() + { + return !(SceneView.lastActiveSceneView == null) && SceneView.lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent("FrameSelectedWithLock")); + } + private Editor[] GetActiveEditors() + { + if (this.m_Tracker == null) + { + this.m_Tracker = ActiveEditorTracker.sharedTracker; + } + return this.m_Tracker.activeEditors; + } + public static Camera[] GetAllSceneCameras() + { + ArrayList arrayList = new ArrayList(); + for (int i = 0; i < SceneView.s_SceneViews.Count; i++) + { + Camera camera = ((SceneView)SceneView.s_SceneViews[i]).m_Camera; + if (camera != null) + { + arrayList.Add(camera); + } + } + return (Camera[])arrayList.ToArray(typeof(Camera)); + } + public static void RepaintAll() + { + foreach (SceneView sceneView in SceneView.s_SceneViews) + { + sceneView.Repaint(); + } + } + internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + { + if (this.m_SearchFilter == string.Empty || searchFilter == string.Empty) + { + this.m_StartSearchFilterTime = EditorApplication.timeSinceStartup; + } + base.SetSearchFilter(searchFilter, searchMode, setAll); + } + private void OnFocus() + { + if (!Application.isPlaying && this.m_AudioPlay) + { + this.ToggleAudio(); + } + } + private void OnLostFocus() + { + GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); + if (gameView && gameView.m_Parent != null && this.m_Parent != null && gameView.m_Parent == this.m_Parent) + { + gameView.m_Parent.backgroundValid = false; + } + } + public override void OnEnable() + { + this.m_RectSelection = new RectSelection(this); + if (this.grid == null) + { + this.grid = new SceneViewGrid(); + } + this.grid.Register(this); + if (this.svRot == null) + { + this.svRot = new SceneViewRotation(); + } + this.svRot.Register(this); + base.autoRepaintOnSceneChange = true; + this.m_Rotation.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_Position.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_Size.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_Ortho.valueChanged.AddListener(new UnityAction(base.Repaint)); + base.wantsMouseMove = true; + base.dontClearBackground = true; + SceneView.s_SceneViews.Add(this); + this.m_SceneViewOverlay = new SceneViewOverlay(this); + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(SceneView.RepaintAll)); + this.m_DraggingLockedState = SceneView.DraggingLockedState.NotDragging; + base.OnEnable(); + } + private void Awake() + { + if (this.m_SceneViewState == null) + { + this.m_SceneViewState = new SceneView.SceneViewState(); + } + if (!BuildPipeline.isBuildingPlayer) + { + this.m_SceneLighting = InternalEditorUtility.CalculateShouldEnableLights(); + } + if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) + { + this.m_2DMode = true; + this.m_LastSceneViewRotation = Quaternion.LookRotation(new Vector3(-1f, -0.7f, -1f)); + this.m_LastSceneViewOrtho = false; + this.m_Rotation.value = Quaternion.identity; + this.m_Ortho.value = true; + } + } + private static void OnForceEnableLights() + { + foreach (SceneView sceneView in SceneView.s_SceneViews) + { + sceneView.m_SceneLighting = true; + } + } + private void OnDidOpenScene() + { + if (BuildPipeline.isBuildingPlayer) + { + return; + } + foreach (SceneView sceneView in SceneView.s_SceneViews) + { + sceneView.m_SceneLighting = InternalEditorUtility.CalculateShouldEnableLights(); + } + } + internal static void PlaceGameObjectInFrontOfSceneView(GameObject go) + { + if (SceneView.s_SceneViews.Count >= 1) + { + SceneView sceneView = SceneView.s_LastActiveSceneView; + if (!sceneView) + { + sceneView = (SceneView.s_SceneViews[0] as SceneView); + } + if (sceneView) + { + sceneView.MoveToView(go.transform); + } + } + } + public override void OnDisable() + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(SceneView.RepaintAll)); + if (this.m_Camera) + { + UnityEngine.Object.DestroyImmediate(this.m_Camera.gameObject, true); + } + if (this.m_Light[0]) + { + UnityEngine.Object.DestroyImmediate(this.m_Light[0].gameObject, true); + } + if (this.m_Light[1]) + { + UnityEngine.Object.DestroyImmediate(this.m_Light[1].gameObject, true); + } + if (this.m_Light[2]) + { + UnityEngine.Object.DestroyImmediate(this.m_Light[2].gameObject, true); + } + if (SceneView.s_MipColorsTexture) + { + UnityEngine.Object.DestroyImmediate(SceneView.s_MipColorsTexture, true); + } + SceneView.s_SceneViews.Remove(this); + if (SceneView.s_LastActiveSceneView == this) + { + if (SceneView.s_SceneViews.Count > 0) + { + SceneView.s_LastActiveSceneView = (SceneView.s_SceneViews[0] as SceneView); + } + else + { + SceneView.s_LastActiveSceneView = null; + } + } + this.CleanupEditorDragFunctions(); + base.OnDisable(); + } + public void OnDestroy() + { + if (this.m_AudioPlay) + { + this.m_AudioPlay = false; + this.ToggleAudio(); + } + } + private void DoStatusBarGUI() + { + GUILayout.BeginHorizontal("toolbar", new GUILayoutOption[0]); + this.m_RenderMode = (DrawCameraMode)EditorGUILayout.Popup((int)this.m_RenderMode, SceneView.s_RenderModes, "ToolbarPopup", new GUILayoutOption[] + { + GUILayout.Width(120f) + }); + EditorGUILayout.Space(); + bool enabled = GUI.enabled; + GUI.enabled = string.IsNullOrEmpty(this.m_SearchFilter); + this.m_OverlayMode = EditorGUILayout.Popup(this.m_OverlayMode, SceneView.s_OverlayModes, "ToolbarPopup", new GUILayoutOption[] + { + GUILayout.Width(70f) + }); + GUI.enabled = enabled; + EditorGUILayout.Space(); + this.in2DMode = GUILayout.Toggle(this.in2DMode, SceneView.s_2DMode, "toolbarbutton", new GUILayoutOption[0]); + this.m_SceneLighting = GUILayout.Toggle(this.m_SceneLighting, SceneView.s_Lighting, "toolbarbutton", new GUILayoutOption[0]); + GUI.enabled = !Application.isPlaying; + GUI.changed = false; + this.m_AudioPlay = GUILayout.Toggle(this.m_AudioPlay, SceneView.s_AudioPlay, EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (GUI.changed) + { + this.ToggleAudio(); + } + GUI.enabled = true; + Rect rect = GUILayoutUtility.GetRect(SceneView.s_Fx, this.effectsDropDownStyle); + Rect position = new Rect(rect.xMax - (float)this.effectsDropDownStyle.border.right, rect.y, (float)this.effectsDropDownStyle.border.right, rect.height); + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none)) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + if (SceneFXWindow.ShowAtPosition(last, this)) + { + GUIUtility.ExitGUI(); + } + } + bool flag = GUI.Toggle(rect, this.m_SceneViewState.IsAllOn(), SceneView.s_Fx, this.effectsDropDownStyle); + if (flag != this.m_SceneViewState.IsAllOn()) + { + this.m_SceneViewState.Toggle(flag); + } + GUILayout.Space(6f); + GUILayout.FlexibleSpace(); + if (this.m_MainViewControlID != GUIUtility.keyboardControl && Event.current.type == EventType.KeyDown && !string.IsNullOrEmpty(this.m_SearchFilter)) + { + KeyCode keyCode = Event.current.keyCode; + if (keyCode == KeyCode.UpArrow || keyCode == KeyCode.DownArrow) + { + if (Event.current.keyCode == KeyCode.UpArrow) + { + base.SelectPreviousSearchResult(); + } + else + { + base.SelectNextSearchResult(); + } + this.FrameSelected(false); + Event.current.Use(); + GUIUtility.ExitGUI(); + return; + } + } + Rect rect2 = GUILayoutUtility.GetRect(SceneView.s_GizmosContent, EditorStyles.toolbarDropDown); + if (EditorGUI.ButtonMouseDown(rect2, SceneView.s_GizmosContent, FocusType.Passive, EditorStyles.toolbarDropDown)) + { + Rect last2 = GUILayoutUtility.topLevel.GetLast(); + if (AnnotationWindow.ShowAtPosition(last2, false)) + { + GUIUtility.ExitGUI(); + } + } + GUILayout.Space(6f); + base.SearchFieldGUI(); + GUILayout.EndHorizontal(); + } + private void ToggleAudio() + { + if (SceneView.s_AudioSceneView != null && SceneView.s_AudioSceneView != this && SceneView.s_AudioSceneView.m_AudioPlay) + { + SceneView.s_AudioSceneView.m_AudioPlay = false; + SceneView.s_AudioSceneView.Repaint(); + } + AudioSource[] array = (AudioSource[])UnityEngine.Object.FindObjectsOfType(typeof(AudioSource)); + AudioSource[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + AudioSource audioSource = array2[i]; + if (audioSource.playOnAwake) + { + if (!this.m_AudioPlay) + { + audioSource.Stop(); + } + else + { + if (!audioSource.isPlaying) + { + audioSource.Play(); + } + } + } + } + AudioUtil.SetListenerTransform((!this.m_AudioPlay) ? null : this.m_Camera.transform); + SceneView.s_AudioSceneView = this; + } + public void OnSelectionChange() + { + if (Selection.activeObject != null && this.m_LastLockedObject != Selection.activeObject) + { + this.viewIsLockedToObject = false; + } + base.Repaint(); + } + [MenuItem("GameObject/Set as first sibling %=")] + private static void MenuMoveToFront() + { + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + Undo.SetTransformParent(transform, transform.parent, "Set as first sibling"); + transform.SetAsFirstSibling(); + } + } + [MenuItem("GameObject/Set as first sibling %=", true)] + private static bool ValidateMenuMoveToFront() + { + if (Selection.activeTransform != null) + { + Transform parent = Selection.activeTransform.parent; + return parent != null && parent.GetChild(0) != Selection.activeTransform; + } + return false; + } + [MenuItem("GameObject/Set as last sibling %-")] + private static void MenuMoveToBack() + { + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + Undo.SetTransformParent(transform, transform.parent, "Set as last sibling"); + transform.SetAsLastSibling(); + } + } + [MenuItem("GameObject/Set as last sibling %-", true)] + private static bool ValidateMenuMoveToBack() + { + if (Selection.activeTransform != null) + { + Transform parent = Selection.activeTransform.parent; + return parent != null && parent.GetChild(parent.childCount - 1) != Selection.activeTransform; + } + return false; + } + [MenuItem("GameObject/Move To View %&f")] + private static void MenuMoveToView() + { + if (SceneView.ValidateMoveToView()) + { + SceneView.s_LastActiveSceneView.MoveToView(); + } + } + [MenuItem("GameObject/Move To View %&f", true)] + private static bool ValidateMoveToView() + { + return SceneView.s_LastActiveSceneView != null && Selection.transforms.Length != 0; + } + [MenuItem("GameObject/Align With View %#f")] + private static void MenuAlignWithView() + { + if (SceneView.ValidateAlignWithView()) + { + SceneView.s_LastActiveSceneView.AlignWithView(); + } + } + [MenuItem("GameObject/Align With View %#f", true)] + private static bool ValidateAlignWithView() + { + return SceneView.s_LastActiveSceneView != null && Selection.activeTransform != null; + } + [MenuItem("GameObject/Align View to Selected")] + private static void MenuAlignViewToSelected() + { + if (SceneView.ValidateAlignViewToSelected()) + { + SceneView.s_LastActiveSceneView.AlignViewToObject(Selection.activeTransform); + } + } + [MenuItem("GameObject/Align View to Selected", true)] + private static bool ValidateAlignViewToSelected() + { + return SceneView.s_LastActiveSceneView != null && Selection.activeTransform != null; + } + [MenuItem("GameObject/Toggle Active State &#a")] + private static void ActivateSelection() + { + if (Selection.activeTransform != null) + { + GameObject[] gameObjects = Selection.gameObjects; + bool active = !Selection.activeGameObject.activeSelf; + GameObject[] array = gameObjects; + for (int i = 0; i < array.Length; i++) + { + GameObject gameObject = array[i]; + gameObject.SetActive(active); + } + } + } + [MenuItem("GameObject/Toggle Active State &#a", true)] + private static bool ValidateActivateSelection() + { + return Selection.activeTransform != null; + } + private static void CreateMipColorsTexture() + { + if (SceneView.s_MipColorsTexture) + { + return; + } + SceneView.s_MipColorsTexture = new Texture2D(32, 32, TextureFormat.ARGB32, true); + SceneView.s_MipColorsTexture.hideFlags = HideFlags.HideAndDontSave; + Color[] array = new Color[] + { + new Color(0f, 0f, 1f, 0.8f), + new Color(0f, 0.5f, 1f, 0.4f), + new Color(1f, 1f, 1f, 0f), + new Color(1f, 0.7f, 0f, 0.2f), + new Color(1f, 0.3f, 0f, 0.6f), + new Color(1f, 0f, 0f, 0.8f) + }; + int num = Mathf.Min(6, SceneView.s_MipColorsTexture.mipmapCount); + for (int i = 0; i < num; i++) + { + int num2 = Mathf.Max(SceneView.s_MipColorsTexture.width >> i, 1); + int num3 = Mathf.Max(SceneView.s_MipColorsTexture.height >> i, 1); + Color[] array2 = new Color[num2 * num3]; + for (int j = 0; j < array2.Length; j++) + { + array2[j] = array[i]; + } + SceneView.s_MipColorsTexture.SetPixels(array2, i); + } + SceneView.s_MipColorsTexture.filterMode = FilterMode.Trilinear; + SceneView.s_MipColorsTexture.Apply(false); + Shader.SetGlobalTexture("__SceneViewMipcolorsTexture", SceneView.s_MipColorsTexture); + } + public void SetSceneViewFiltering(bool enable) + { + this.m_RequestedSceneViewFiltering = enable; + } + private bool UseSceneFiltering() + { + return !string.IsNullOrEmpty(this.m_SearchFilter) || this.m_RequestedSceneViewFiltering; + } + private void OnGUI() + { + SceneView.s_CurrentDrawingSceneView = this; + if (Event.current.type == EventType.Repaint) + { + SceneView.s_MouseRects.Clear(); + } + Color color = GUI.color; + if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag) + { + SceneView.s_LastActiveSceneView = this; + } + else + { + if (SceneView.s_LastActiveSceneView == null) + { + SceneView.s_LastActiveSceneView = this; + } + } + if (Event.current.type == EventType.MouseDrag) + { + this.draggingLocked = SceneView.DraggingLockedState.Dragging; + } + else + { + if (Event.current.type == EventType.MouseUp) + { + this.draggingLocked = SceneView.DraggingLockedState.LookAt; + } + } + if (Event.current.type == EventType.MouseDown) + { + Tools.s_ButtonDown = Event.current.button; + if (Event.current.button == 1 && Application.platform == RuntimePlatform.OSXEditor) + { + base.Focus(); + } + } + if (Event.current.type == EventType.Layout) + { + this.m_ShowSceneViewWindows = (SceneView.lastActiveSceneView == this); + } + this.m_SceneViewOverlay.Begin(); + bool fog = RenderSettings.fog; + float shadowDistance = QualitySettings.shadowDistance; + if (Event.current.type == EventType.Repaint) + { + if (!this.m_SceneViewState.showFog) + { + Unsupported.SetRenderSettingsUseFogNoDirty(false); + } + if (this.m_Camera.isOrthoGraphic) + { + Unsupported.SetQualitySettingsShadowDistanceTemporarily(QualitySettings.shadowDistance + 0.5f * this.cameraDistance); + } + } + this.DoStatusBarGUI(); + GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); + EditorGUIUtility.labelWidth = 100f; + this.SetupCamera(); + RenderingPath renderingPath = this.m_Camera.renderingPath; + if (!this.m_SceneLighting) + { + this.m_Light[0].transform.rotation = this.m_Camera.transform.rotation; + if (Event.current.type == EventType.Repaint) + { + InternalEditorUtility.SetCustomLighting(this.m_Light, SceneView.kSceneViewMidLight); + } + } + GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); + Rect rect = new Rect(0f, 0f, base.position.width, base.position.height - 17f); + if (Tools.viewToolActive && Event.current.type == EventType.Repaint) + { + MouseCursor mouseCursor = MouseCursor.Arrow; + switch (Tools.viewTool) + { + case ViewTool.Orbit: + mouseCursor = MouseCursor.Orbit; + break; + case ViewTool.Pan: + mouseCursor = MouseCursor.Pan; + break; + case ViewTool.Zoom: + mouseCursor = MouseCursor.Zoom; + break; + case ViewTool.FPS: + mouseCursor = MouseCursor.FPS; + break; + } + if (mouseCursor != MouseCursor.Arrow) + { + SceneView.AddCursorRect(new Rect(0f, 17f, base.position.width, base.position.height - 17f), mouseCursor); + } + } + if (this.UseSceneFiltering()) + { + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + if (this.m_SearchFilterTexture == null) + { + this.m_SearchFilterTexture = new RenderTexture(0, 0, 24); + this.m_SearchFilterTexture.hideFlags = HideFlags.HideAndDontSave; + } + Rect cameraRect = Handles.GetCameraRect(rect); + if (this.m_SearchFilterTexture.width != (int)cameraRect.width || this.m_SearchFilterTexture.height != (int)cameraRect.height) + { + this.m_SearchFilterTexture.Release(); + this.m_SearchFilterTexture.width = (int)cameraRect.width; + this.m_SearchFilterTexture.height = (int)cameraRect.height; + } + this.m_Camera.targetTexture = this.m_SearchFilterTexture; + if (this.m_Camera.actualRenderingPath == RenderingPath.DeferredLighting) + { + this.m_Camera.renderingPath = RenderingPath.Forward; + } + } + else + { + this.m_Camera.targetTexture = null; + } + float verticalFOV = this.GetVerticalFOV(90f); + float fieldOfView = this.m_Camera.fieldOfView; + this.m_Camera.fieldOfView = verticalFOV; + Handles.ClearCamera(rect, this.m_Camera); + this.m_Camera.fieldOfView = fieldOfView; + this.m_Camera.cullingMask = Tools.visibleLayers; + if (!this.UseSceneFiltering()) + { + Handles.SetCamera(rect, this.m_Camera); + this.CallOnPreSceneGUI(); + } + if (Event.current.type == EventType.Repaint) + { + Handles.SetSceneViewColors(SceneView.kSceneViewWire, SceneView.kSceneViewWireOverlay, SceneView.kSceneViewWireActive, SceneView.kSceneViewWireSelected); + if (this.m_OverlayMode == 2) + { + if (!SceneView.s_ShowOverdrawShader) + { + SceneView.s_ShowOverdrawShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowOverdraw.shader") as Shader); + } + this.m_Camera.SetReplacementShader(SceneView.s_ShowOverdrawShader, "RenderType"); + } + else + { + if (this.m_OverlayMode == 3) + { + if (!SceneView.s_ShowMipsShader) + { + SceneView.s_ShowMipsShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowMips.shader") as Shader); + } + if (SceneView.s_ShowMipsShader.isSupported) + { + SceneView.CreateMipColorsTexture(); + this.m_Camera.SetReplacementShader(SceneView.s_ShowMipsShader, "RenderType"); + } + else + { + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + } + } + else + { + if (this.m_OverlayMode == 4) + { + if (!SceneView.s_ShowLightmapsShader) + { + SceneView.s_ShowLightmapsShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowLightmap.shader") as Shader); + } + if (SceneView.s_ShowLightmapsShader.isSupported) + { + this.m_Camera.SetReplacementShader(SceneView.s_ShowLightmapsShader, "RenderType"); + } + else + { + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + } + } + else + { + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + } + } + } + } + this.m_MainViewControlID = GUIUtility.GetControlID(FocusType.Keyboard); + if (Event.current.GetTypeForControl(this.m_MainViewControlID) == EventType.MouseDown) + { + GUIUtility.keyboardControl = this.m_MainViewControlID; + } + if (this.m_Camera.gameObject.activeInHierarchy) + { + DrawGridParameters gridParam = this.grid.PrepareGridRender(this.camera, this.pivot, this.m_Rotation.target, this.m_Size.value, this.m_Ortho.target, AnnotationUtility.showGrid); + if (this.UseSceneFiltering()) + { + if (Event.current.type == EventType.Repaint) + { + Handles.EnableCameraFx(this.m_Camera, true); + Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowRest); + float num = Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - this.m_StartSearchFilterTime)); + Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode); + Handles.DrawCameraFade(this.m_Camera, num); + RenderTexture.active = null; + Handles.EnableCameraFx(this.m_Camera, false); + Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowFiltered); + if (!SceneView.s_AuraShader) + { + SceneView.s_AuraShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader); + } + this.m_Camera.SetReplacementShader(SceneView.s_AuraShader, string.Empty); + Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode); + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode, gridParam); + if (num < 1f) + { + base.Repaint(); + } + } + Rect position = rect; + GUI.EndGroup(); + GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); + GUI.DrawTexture(position, this.m_SearchFilterTexture, ScaleMode.StretchToFill, false, 0f); + Handles.SetCamera(rect, this.m_Camera); + this.HandleSelectionAndOnSceneGUI(); + } + else + { + Handles.DrawCameraStep1(rect, this.m_Camera, this.m_RenderMode, gridParam); + this.DrawAlphaOverlay(); + } + } + if (!this.m_SceneLighting && Event.current.type == EventType.Repaint) + { + InternalEditorUtility.RemoveCustomLighting(); + } + if (this.UseSceneFiltering()) + { + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + } + if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) + { + this.CommandsGUI(); + } + if (Event.current.type == EventType.Repaint) + { + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + Unsupported.SetQualitySettingsShadowDistanceTemporarily(shadowDistance); + } + this.m_Camera.renderingPath = renderingPath; + if (!this.UseSceneFiltering()) + { + Handles.DrawCameraStep2(this.m_Camera, this.m_RenderMode); + } + if (this.UseSceneFiltering()) + { + Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.ShowFiltered); + } + else + { + Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.Off); + } + if (!this.UseSceneFiltering()) + { + this.HandleSelectionAndOnSceneGUI(); + } + this.DefaultHandles(); + Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.Off); + Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.Off); + this.HandleDragging(); + this.svRot.HandleContextClick(this); + this.svRot.OnGUI(this); + SceneViewMotion.ArrowKeys(this); + SceneViewMotion.DoViewTool(this.camera.transform, this); + if (SceneView.k2DMode.activated && !SceneView.waitingFor2DModeKeyUp) + { + SceneView.waitingFor2DModeKeyUp = true; + this.in2DMode = !this.in2DMode; + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.KeyUp && Event.current.keyCode == SceneView.k2DMode.KeyboardEvent.keyCode) + { + SceneView.waitingFor2DModeKeyUp = false; + } + } + GUI.EndGroup(); + GUI.color = color; + this.m_SceneViewOverlay.End(); + if (GUIUtility.hotControl == 0) + { + this.s_DraggingCursorIsCashed = false; + } + Rect rect2 = new Rect(0f, 0f, base.position.width, base.position.height); + if (!this.s_DraggingCursorIsCashed) + { + MouseCursor mouseCursor2 = MouseCursor.Arrow; + if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.Repaint) + { + foreach (SceneView.CursorRect current in SceneView.s_MouseRects) + { + if (current.rect.Contains(Event.current.mousePosition)) + { + mouseCursor2 = current.cursor; + rect2 = current.rect; + } + } + if (GUIUtility.hotControl != 0) + { + this.s_DraggingCursorIsCashed = true; + } + if (mouseCursor2 != SceneView.s_LastCursor) + { + SceneView.s_LastCursor = mouseCursor2; + InternalEditorUtility.ResetCursor(); + base.Repaint(); + } + } + } + if (Event.current.type == EventType.Repaint && SceneView.s_LastCursor != MouseCursor.Arrow) + { + EditorGUIUtility.AddCursorRect(rect2, SceneView.s_LastCursor); + } + } + private void DrawAlphaOverlay() + { + if (this.m_OverlayMode != 1) + { + return; + } + if (!SceneView.s_AlphaOverlayMaterial) + { + SceneView.s_AlphaOverlayMaterial = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAlphaMaterial.mat") as Material); + } + Handles.BeginGUI(); + if (Event.current.type == EventType.Repaint) + { + Graphics.DrawTexture(new Rect(0f, 0f, base.position.width, base.position.height), EditorGUIUtility.whiteTexture, SceneView.s_AlphaOverlayMaterial); + } + Handles.EndGUI(); + } + private void HandleSelectionAndOnSceneGUI() + { + this.m_RectSelection.OnGUI(); + this.CallOnSceneGUI(); + } + public void FixNegativeSize() + { + float num = 90f; + if (this.size < 0f) + { + float num2 = this.size / Mathf.Tan(num * 0.5f * 0.0174532924f); + Vector3 a = this.m_Position.value + this.rotation * new Vector3(0f, 0f, -num2); + this.size = -this.size; + num2 = this.size / Mathf.Tan(num * 0.5f * 0.0174532924f); + this.m_Position.value = a + this.rotation * new Vector3(0f, 0f, num2); + } + } + private float CalcCameraDist() + { + float num = this.m_Ortho.Fade(90f, 0f); + if (num > 3f) + { + this.m_Camera.orthographic = false; + return this.size / Mathf.Tan(num * 0.5f * 0.0174532924f); + } + return 0f; + } + private void ResetIfNaN() + { + if (float.IsInfinity(this.m_Position.value.x) || float.IsNaN(this.m_Position.value.x)) + { + this.m_Position.value = Vector3.zero; + } + if (float.IsInfinity(this.m_Rotation.value.x) || float.IsNaN(this.m_Rotation.value.x)) + { + this.m_Rotation.value = Quaternion.identity; + } + } + internal static RenderingPath GetSceneViewRenderingPath() + { + Camera main = Camera.main; + if (main != null) + { + return main.renderingPath; + } + Camera[] allCameras = Camera.allCameras; + if (allCameras != null && allCameras.Length == 1) + { + return allCameras[0].renderingPath; + } + return RenderingPath.UsePlayerSettings; + } + private void SetupCamera() + { + if (!this.m_Camera) + { + this.Setup(); + } + if (this.m_OverlayMode == 2) + { + this.m_Camera.backgroundColor = Color.black; + } + else + { + this.m_Camera.backgroundColor = SceneView.kSceneViewBackground; + } + EditorUtility.SetCameraAnimateMaterials(this.m_Camera, this.m_SceneViewState.showMaterialUpdate); + this.ResetIfNaN(); + this.m_Camera.transform.rotation = this.m_Rotation.value; + float num = this.m_Ortho.Fade(90f, 0f); + if (num > 3f) + { + this.m_Camera.orthographic = false; + this.m_Camera.fieldOfView = this.GetVerticalFOV(num); + } + else + { + this.m_Camera.orthographic = true; + this.m_Camera.orthographicSize = this.GetVerticalOrthoSize(); + } + this.m_Camera.transform.position = this.m_Position.value + this.m_Camera.transform.rotation * new Vector3(0f, 0f, -this.cameraDistance); + float num2 = Mathf.Max(1000f, 2000f * this.size); + this.m_Camera.nearClipPlane = num2 * 5E-06f; + this.m_Camera.farClipPlane = num2; + this.m_Camera.renderingPath = SceneView.GetSceneViewRenderingPath(); + Handles.EnableCameraFlares(this.m_Camera, this.m_SceneViewState.showFlares); + Handles.EnableCameraSkybox(this.m_Camera, this.m_SceneViewState.showSkybox); + this.m_Light[0].transform.position = this.m_Camera.transform.position; + this.m_Light[0].transform.rotation = this.m_Camera.transform.rotation; + if (this.m_AudioPlay) + { + AudioUtil.SetListenerTransform(this.m_Camera.transform); + AudioUtil.UpdateAudio(); + } + if (this.m_ViewIsLockedToObject && Selection.gameObjects.Length > 0) + { + switch (this.m_DraggingLockedState) + { + case SceneView.DraggingLockedState.NotDragging: + this.m_Position.value = Selection.activeGameObject.transform.position; + break; + case SceneView.DraggingLockedState.LookAt: + if (!this.m_Position.value.Equals(Selection.activeGameObject.transform.position)) + { + if (!EditorApplication.isPlaying) + { + this.m_Position.target = Selection.activeGameObject.transform.position; + } + else + { + this.m_Position.value = Selection.activeGameObject.transform.position; + } + } + else + { + this.m_DraggingLockedState = SceneView.DraggingLockedState.NotDragging; + } + break; + } + } + } + public void Update() + { + if (this.m_SceneViewState.showMaterialUpdate && this.m_lastRenderedTime + 0.032999999821186066 < EditorApplication.timeSinceStartup) + { + this.m_lastRenderedTime = EditorApplication.timeSinceStartup; + base.Repaint(); + } + } + internal float GetVerticalFOV(float aspectNeutralFOV) + { + float f = Mathf.Tan(aspectNeutralFOV * 0.5f * 0.0174532924f) * 0.707106769f / Mathf.Sqrt(this.m_Camera.aspect); + return Mathf.Atan(f) * 2f * 57.29578f; + } + internal float GetVerticalOrthoSize() + { + return this.size * 0.707106769f / Mathf.Sqrt(this.m_Camera.aspect); + } + public void LookAt(Vector3 position) + { + this.FixNegativeSize(); + this.m_Position.target = position; + } + public void LookAt(Vector3 position, Quaternion rotation) + { + this.FixNegativeSize(); + this.m_Position.target = position; + this.m_Rotation.target = rotation; + this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + } + public void LookAtDirect(Vector3 position, Quaternion rotation) + { + this.FixNegativeSize(); + this.m_Position.value = position; + this.m_Rotation.value = rotation; + this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + } + public void LookAt(Vector3 position, Quaternion rotation, float size) + { + this.FixNegativeSize(); + this.m_Position.target = position; + this.m_Rotation.target = rotation; + this.m_Size.target = Mathf.Abs(size); + this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + } + public void LookAtDirect(Vector3 position, Quaternion rotation, float size) + { + this.FixNegativeSize(); + this.m_Position.value = position; + this.m_Rotation.value = rotation; + this.m_Size.value = Mathf.Abs(size); + this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + } + public void LookAt(Vector3 position, Quaternion rotation, float size, bool orthographic) + { + this.LookAt(position, rotation, size, orthographic, false); + } + public void LookAt(Vector3 position, Quaternion rotation, float size, bool orthographic, bool instant) + { + this.FixNegativeSize(); + if (instant) + { + this.m_Position.value = position; + this.m_Rotation.value = rotation; + this.m_Size.value = Mathf.Abs(size); + this.m_Ortho.value = orthographic; + } + else + { + this.m_Position.target = position; + this.m_Rotation.target = rotation; + this.m_Size.target = Mathf.Abs(size); + this.m_Ortho.target = orthographic; + } + this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + } + private void DefaultHandles() + { + EditorGUI.BeginChangeCheck(); + bool flag = Event.current.GetTypeForControl(GUIUtility.hotControl) == EventType.MouseDrag; + bool flag2 = Event.current.GetTypeForControl(GUIUtility.hotControl) == EventType.MouseUp; + if (GUIUtility.hotControl == 0) + { + SceneView.s_CurrentTool = ((!Tools.viewToolActive) ? Tools.current : Tool.View); + } + Tool tool = (Event.current.type != EventType.Repaint) ? SceneView.s_CurrentTool : Tools.current; + Tool tool2 = tool; + switch (tool2 + 1) + { + case Tool.Rotate: + MoveTool.OnGUI(this); + break; + case Tool.Scale: + RotateTool.OnGUI(this); + break; + case Tool.Rect: + ScaleTool.OnGUI(this); + break; + case (Tool)5: + RectTool.OnGUI(this); + break; + } + if (EditorGUI.EndChangeCheck() && EditorApplication.isPlaying && flag) + { + Physics2D.SetEditorDragMovement(true, Selection.gameObjects); + } + if (EditorApplication.isPlaying && flag2) + { + Physics2D.SetEditorDragMovement(false, Selection.gameObjects); + } + } + private void CleanupEditorDragFunctions() + { + if (this.m_DragEditorCache != null) + { + this.m_DragEditorCache.Dispose(); + } + this.m_DragEditorCache = null; + } + private void CallEditorDragFunctions() + { + if (DragAndDrop.objectReferences.Length == 0) + { + return; + } + if (this.m_DragEditorCache == null) + { + this.m_DragEditorCache = new EditorCache(EditorFeatures.OnSceneDrag); + } + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + for (int i = 0; i < objectReferences.Length; i++) + { + UnityEngine.Object @object = objectReferences[i]; + if (!(@object == null)) + { + EditorWrapper editorWrapper = this.m_DragEditorCache[@object]; + if (editorWrapper != null) + { + editorWrapper.OnSceneDrag(this); + } + if (Event.current.type == EventType.Used) + { + return; + } + } + } + } + private void HandleDragging() + { + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.Repaint: + this.CallEditorDragFunctions(); + return; + case EventType.Layout: + IL_25: + if (type != EventType.DragExited) + { + return; + } + this.CallEditorDragFunctions(); + this.CleanupEditorDragFunctions(); + return; + case EventType.DragUpdated: + case EventType.DragPerform: + { + this.CallEditorDragFunctions(); + bool flag = current.type == EventType.DragPerform; + if (this.m_2DMode) + { + SpriteUtility.OnSceneDrag(this); + } + if (current.type == EventType.Used) + { + return; + } + if (DragAndDrop.visualMode != DragAndDropVisualMode.Copy) + { + GameObject dropUpon = HandleUtility.PickGameObject(Event.current.mousePosition, true); + DragAndDrop.visualMode = InternalEditorUtility.SceneViewDrag(dropUpon, this.pivot, Event.current.mousePosition, flag); + } + if (flag && DragAndDrop.visualMode != DragAndDropVisualMode.None) + { + DragAndDrop.AcceptDrag(); + current.Use(); + GUIUtility.ExitGUI(); + } + current.Use(); + return; + } + } + goto IL_25; + } + private void CommandsGUI() + { + bool flag = Event.current.type == EventType.ExecuteCommand; + string commandName = Event.current.commandName; + switch (commandName) + { + case "Find": + if (flag) + { + base.FocusSearchField(); + } + Event.current.Use(); + break; + case "FrameSelected": + if (flag) + { + bool lockView = EditorApplication.timeSinceStartup - this.lastFramingTime < 0.5; + this.FrameSelected(lockView); + this.lastFramingTime = EditorApplication.timeSinceStartup; + } + Event.current.Use(); + break; + case "FrameSelectedWithLock": + if (flag) + { + this.FrameSelected(true); + } + Event.current.Use(); + break; + case "SoftDelete": + case "Delete": + if (flag) + { + Unsupported.DeleteGameObjectSelection(); + } + Event.current.Use(); + break; + case "Duplicate": + if (flag) + { + Unsupported.DuplicateGameObjectsUsingPasteboard(); + } + Event.current.Use(); + break; + case "Copy": + if (flag) + { + Unsupported.CopyGameObjectsToPasteboard(); + } + Event.current.Use(); + break; + case "Paste": + if (flag) + { + Unsupported.PasteGameObjectsFromPasteboard(); + } + Event.current.Use(); + break; + case "SelectAll": + if (flag) + { + Selection.objects = UnityEngine.Object.FindObjectsOfType(typeof(GameObject)); + } + Event.current.Use(); + break; + } + } + public void AlignViewToObject(Transform t) + { + this.FixNegativeSize(); + this.size = 10f; + this.LookAt(t.position + t.forward * this.CalcCameraDist(), t.rotation); + } + public void AlignWithView() + { + this.FixNegativeSize(); + Vector3 position = this.camera.transform.position; + Vector3 b = position - Tools.handlePosition; + float angle; + Vector3 vector; + (Quaternion.Inverse(Selection.activeTransform.rotation) * this.camera.transform.rotation).ToAngleAxis(out angle, out vector); + vector = Selection.activeTransform.TransformDirection(vector); + Undo.RecordObjects(Selection.transforms, "Align with view"); + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + transform.position += b; + transform.RotateAround(position, vector, angle); + } + } + public void MoveToView() + { + this.FixNegativeSize(); + Vector3 b = this.pivot - Tools.handlePosition; + Undo.RecordObjects(Selection.transforms, "Move to view"); + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + transform.position += b; + } + } + public void MoveToView(Transform target) + { + target.position = this.pivot; + } + public bool FrameSelected() + { + return this.FrameSelected(false); + } + public bool FrameSelected(bool lockView) + { + this.viewIsLockedToObject = lockView; + this.FixNegativeSize(); + Bounds bounds = InternalEditorUtility.CalculateSelectionBounds(false); + Editor[] activeEditors = this.GetActiveEditors(); + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor = activeEditors[i]; + MethodInfo method = editor.GetType().GetMethod("HasFrameBounds", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method != null) + { + object obj = method.Invoke(editor, null); + if (obj != null && obj is bool && (bool)obj) + { + MethodInfo method2 = editor.GetType().GetMethod("OnGetFrameBounds", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method2 != null) + { + object obj2 = method2.Invoke(editor, null); + if (obj2 != null && obj2 is Bounds) + { + bounds = (Bounds)obj2; + } + } + } + } + } + return this.Frame(bounds); + } + internal bool Frame(Bounds bounds) + { + float num = bounds.extents.magnitude * 1.5f; + if (num == float.PositiveInfinity) + { + return false; + } + if (num == 0f) + { + num = 10f; + } + this.LookAt(bounds.center, this.m_Rotation.target, num * 2.2f, this.m_Ortho.value, EditorApplication.isPlaying); + return true; + } + private void Setup() + { + GameObject gameObject = EditorUtility.CreateGameObjectWithHideFlags("SceneCamera", HideFlags.HideAndDontSave, new Type[] + { + typeof(Camera) + }); + gameObject.AddComponent("FlareLayer"); + gameObject.AddComponent("HaloLayer"); + this.m_Camera = gameObject.camera; + this.m_Camera.enabled = false; + for (int i = 0; i < 3; i++) + { + GameObject gameObject2 = EditorUtility.CreateGameObjectWithHideFlags("SceneLight", HideFlags.HideAndDontSave, new Type[] + { + typeof(Light) + }); + this.m_Light[i] = gameObject2.light; + this.m_Light[i].type = LightType.Directional; + this.m_Light[i].intensity = 0.5f; + this.m_Light[i].enabled = false; + } + this.m_Light[0].color = SceneView.kSceneViewFrontLight; + this.m_Light[1].color = SceneView.kSceneViewUpLight - SceneView.kSceneViewMidLight; + this.m_Light[1].transform.LookAt(Vector3.down); + this.m_Light[1].renderMode = LightRenderMode.ForceVertex; + this.m_Light[2].color = SceneView.kSceneViewDownLight - SceneView.kSceneViewMidLight; + this.m_Light[2].transform.LookAt(Vector3.up); + this.m_Light[2].renderMode = LightRenderMode.ForceVertex; + HandleUtility.handleMaterial.SetColor("_SkyColor", SceneView.kSceneViewUpLight * 1.5f); + HandleUtility.handleMaterial.SetColor("_GroundColor", SceneView.kSceneViewDownLight * 1.5f); + HandleUtility.handleMaterial.SetColor("_Color", SceneView.kSceneViewFrontLight * 1.5f); + } + private void CallOnSceneGUI() + { + Editor[] activeEditors = this.GetActiveEditors(); + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor = activeEditors[i]; + if (EditorGUIUtility.IsGizmosAllowedForObject(editor.target)) + { + MethodInfo method = editor.GetType().GetMethod("OnSceneGUI", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method != null) + { + for (int j = 0; j < editor.targets.Length; j++) + { + this.ResetOnSceneGUIState(); + editor.referenceTargetIndex = j; + EditorGUI.BeginChangeCheck(); + Editor.m_AllowMultiObjectAccess = !editor.canEditMultipleObjects; + method.Invoke(editor, null); + Editor.m_AllowMultiObjectAccess = true; + if (EditorGUI.EndChangeCheck()) + { + editor.serializedObject.SetIsDifferentCacheDirty(); + } + } + this.ResetOnSceneGUIState(); + } + } + } + if (SceneView.onSceneGUIDelegate != null) + { + SceneView.onSceneGUIDelegate(this); + this.ResetOnSceneGUIState(); + } + } + private void ResetOnSceneGUIState() + { + Handles.matrix = Matrix4x4.identity; + HandleUtility.s_CustomPickDistance = 5f; + EditorGUIUtility.ResetGUIState(); + } + private void CallOnPreSceneGUI() + { + Editor[] activeEditors = this.GetActiveEditors(); + for (int i = 0; i < activeEditors.Length; i++) + { + Editor editor = activeEditors[i]; + Handles.matrix = Matrix4x4.identity; + Component component = editor.target as Component; + if (!component || component.gameObject.activeInHierarchy) + { + MethodInfo method = editor.GetType().GetMethod("OnPreSceneGUI", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method != null) + { + for (int j = 0; j < editor.targets.Length; j++) + { + editor.referenceTargetIndex = j; + Editor.m_AllowMultiObjectAccess = !editor.canEditMultipleObjects; + method.Invoke(editor, null); + Editor.m_AllowMultiObjectAccess = true; + } + } + } + } + Handles.matrix = Matrix4x4.identity; + } + internal static void ShowNotification(string notificationText) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneView)); + List list = new List(); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + SceneView sceneView = (SceneView)array2[i]; + if (sceneView.m_Parent is DockArea) + { + DockArea dockArea = (DockArea)sceneView.m_Parent; + if (dockArea && dockArea.actualView == sceneView) + { + list.Add(sceneView); + } + } + } + if (list.Count > 0) + { + foreach (EditorWindow current in list) + { + current.ShowNotification(GUIContent.Temp(notificationText)); + } + } + else + { + Debug.LogError(notificationText); + } + } + public static void ShowCompileErrorNotification() + { + SceneView.ShowNotification("All compiler errors have to be fixed before you can enter playmode!"); + } + internal static void ShowSceneViewPlayModeSaveWarning() + { + GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); + if (gameView != null) + { + gameView.ShowNotification(new GUIContent("You must exit play mode to save the scene!")); + } + else + { + SceneView.ShowNotification("You must exit play mode to save the scene!"); + } + } + private void ResetToDefaults(EditorBehaviorMode behaviorMode) + { + if (behaviorMode != EditorBehaviorMode.Mode3D) + { + if (behaviorMode == EditorBehaviorMode.Mode2D) + { + this.m_2DMode = true; + this.m_Rotation.value = Quaternion.identity; + this.m_Position.value = SceneView.kDefaultPivot; + this.m_Size.value = SceneView.kDefaultViewSize; + this.m_Ortho.value = true; + this.m_LastSceneViewRotation = SceneView.kDefaultRotation; + this.m_LastSceneViewOrtho = false; + return; + } + } + this.m_2DMode = false; + this.m_Rotation.value = SceneView.kDefaultRotation; + this.m_Position.value = SceneView.kDefaultPivot; + this.m_Size.value = SceneView.kDefaultViewSize; + this.m_Ortho.value = false; + } + internal void OnNewProjectLayoutWasCreated() + { + this.ResetToDefaults(EditorSettings.defaultBehaviorMode); + } + private void On2DModeChange() + { + if (this.m_2DMode) + { + this.lastSceneViewRotation = this.rotation; + this.m_LastSceneViewOrtho = this.orthographic; + this.LookAt(this.pivot, Quaternion.identity, this.size, true); + if (Tools.current == Tool.Move) + { + Tools.current = Tool.Rect; + } + } + else + { + this.LookAt(this.pivot, this.lastSceneViewRotation, this.size, this.m_LastSceneViewOrtho); + if (Tools.current == Tool.Rect) + { + Tools.current = Tool.Move; + } + } + HandleUtility.ignoreRaySnapObjects = null; + Tools.vertexDragging = false; + Tools.handleOffset = Vector3.zero; + } + internal static void Report2DAnalytics() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneView)); + if (array.Length == 1) + { + SceneView sceneView = array[0] as SceneView; + if (sceneView.in2DMode) + { + Analytics.Event("2D", "SceneView", "Single 2D", 1); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SceneViewGrid.cs b/UnityEditor/UnityEditor/SceneViewGrid.cs new file mode 100644 index 00000000..7bb4835e --- /dev/null +++ b/UnityEditor/UnityEditor/SceneViewGrid.cs @@ -0,0 +1,70 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [Serializable] + internal class SceneViewGrid + { + private static PrefColor kViewGridColor = new PrefColor("Scene/Grid", 0.5f, 0.5f, 0.5f, 0.4f); + [SerializeField] + private AnimBool xGrid = new AnimBool(); + [SerializeField] + private AnimBool yGrid = new AnimBool(); + [SerializeField] + private AnimBool zGrid = new AnimBool(); + public void Register(SceneView source) + { + this.xGrid.valueChanged.AddListener(new UnityAction(source.Repaint)); + this.yGrid.valueChanged.AddListener(new UnityAction(source.Repaint)); + this.zGrid.valueChanged.AddListener(new UnityAction(source.Repaint)); + } + public DrawGridParameters PrepareGridRender(Camera camera, Vector3 pivot, Quaternion rotation, float size, bool orthoMode, bool gridVisible) + { + bool target = false; + bool target2 = false; + bool target3 = false; + if (gridVisible) + { + if (orthoMode) + { + Vector3 lhs = rotation * Vector3.forward; + if (Mathf.Abs(lhs.y) > 0.2f) + { + target2 = true; + } + else + { + if (lhs == Vector3.left || lhs == Vector3.right) + { + target = true; + } + else + { + if (lhs == Vector3.forward || lhs == Vector3.back) + { + target3 = true; + } + } + } + } + else + { + target2 = true; + } + } + this.xGrid.target = target; + this.yGrid.target = target2; + this.zGrid.target = target3; + DrawGridParameters result; + result.pivot = pivot; + result.color = SceneViewGrid.kViewGridColor; + result.size = size; + result.alphaX = this.xGrid.faded; + result.alphaY = this.yGrid.faded; + result.alphaZ = this.zGrid.faded; + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/SceneViewMotion.cs b/UnityEditor/UnityEditor/SceneViewMotion.cs new file mode 100644 index 00000000..42c8055c --- /dev/null +++ b/UnityEditor/UnityEditor/SceneViewMotion.cs @@ -0,0 +1,532 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneViewMotion + { + private const float kFlyAcceleration = 1.8f; + private static Vector3 s_Motion; + private static float s_FlySpeed = 0f; + private static float s_StartZoom = 0f; + private static float s_ZoomSpeed = 0f; + private static float s_TotalMotion = 0f; + private static bool s_Dragged = false; + private static int s_ViewToolID = GUIUtility.GetPermanentControlID(); + private static PrefKey kFPSForward = new PrefKey("View/FPS Forward", "w"); + private static PrefKey kFPSBack = new PrefKey("View/FPS Back", "s"); + private static PrefKey kFPSLeft = new PrefKey("View/FPS Strafe Left", "a"); + private static PrefKey kFPSRight = new PrefKey("View/FPS Strafe Right", "d"); + private static PrefKey kFPSUp = new PrefKey("View/FPS Strafe Up", "e"); + private static PrefKey kFPSDown = new PrefKey("View/FPS Strafe Down", "q"); + private static TimeHelper s_FPSTiming = default(TimeHelper); + public static void ArrowKeys(SceneView sv) + { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(FocusType.Passive); + if (GUIUtility.hotControl == 0 || GUIUtility.hotControl == controlID) + { + if (EditorGUI.actionKey) + { + return; + } + switch (current.GetTypeForControl(controlID)) + { + case EventType.KeyDown: + switch (current.keyCode) + { + case KeyCode.UpArrow: + sv.viewIsLockedToObject = false; + if (sv.m_Ortho.value) + { + SceneViewMotion.s_Motion.y = 1f; + } + else + { + SceneViewMotion.s_Motion.z = 1f; + } + GUIUtility.hotControl = controlID; + current.Use(); + break; + case KeyCode.DownArrow: + sv.viewIsLockedToObject = false; + if (sv.m_Ortho.value) + { + SceneViewMotion.s_Motion.y = -1f; + } + else + { + SceneViewMotion.s_Motion.z = -1f; + } + GUIUtility.hotControl = controlID; + current.Use(); + break; + case KeyCode.RightArrow: + sv.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.x = 1f; + GUIUtility.hotControl = controlID; + current.Use(); + break; + case KeyCode.LeftArrow: + sv.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.x = -1f; + GUIUtility.hotControl = controlID; + current.Use(); + break; + } + break; + case EventType.KeyUp: + if (GUIUtility.hotControl == controlID) + { + switch (current.keyCode) + { + case KeyCode.UpArrow: + case KeyCode.DownArrow: + SceneViewMotion.s_Motion.z = 0f; + SceneViewMotion.s_Motion.y = 0f; + current.Use(); + break; + case KeyCode.RightArrow: + case KeyCode.LeftArrow: + SceneViewMotion.s_Motion.x = 0f; + current.Use(); + break; + } + } + break; + case EventType.Layout: + if (GUIUtility.hotControl == controlID) + { + Vector3 forward; + if (!sv.m_Ortho.value) + { + forward = Camera.current.transform.forward + Camera.current.transform.up * 0.3f; + forward.y = 0f; + forward.Normalize(); + } + else + { + forward = Camera.current.transform.forward; + } + Vector3 movementDirection = SceneViewMotion.GetMovementDirection(); + sv.LookAtDirect(sv.pivot + Quaternion.LookRotation(forward) * movementDirection, sv.rotation); + if (SceneViewMotion.s_Motion.sqrMagnitude == 0f) + { + sv.pivot = sv.pivot; + SceneViewMotion.s_FlySpeed = 0f; + GUIUtility.hotControl = 0; + } + else + { + sv.Repaint(); + } + } + break; + } + } + } + public static void DoViewTool(Transform cameraTransform, SceneView view) + { + Event current = Event.current; + int num = SceneViewMotion.s_ViewToolID; + EventType typeForControl = current.GetTypeForControl(num); + float d = 0f; + if (view && Tools.s_LockedViewTool == ViewTool.FPS) + { + view.FixNegativeSize(); + d = (view.pivot - cameraTransform.position).magnitude; + } + switch (typeForControl) + { + case EventType.MouseDown: + SceneViewMotion.HandleMouseDown(view, num, current.button); + break; + case EventType.MouseUp: + SceneViewMotion.HandleMouseUp(view, num, current.button, current.clickCount); + break; + case EventType.MouseDrag: + SceneViewMotion.HandleMouseDrag(cameraTransform, view, num); + break; + case EventType.KeyDown: + SceneViewMotion.HandleKeyDown(view); + break; + case EventType.KeyUp: + SceneViewMotion.HandleKeyUp(); + break; + case EventType.ScrollWheel: + SceneViewMotion.HandleScrollWheel(view, !current.alt); + break; + case EventType.Layout: + { + Vector3 movementDirection = SceneViewMotion.GetMovementDirection(); + if (GUIUtility.hotControl == num && movementDirection.sqrMagnitude != 0f) + { + cameraTransform.position += cameraTransform.rotation * movementDirection; + } + break; + } + } + if (view && Tools.s_LockedViewTool == ViewTool.FPS) + { + if (!view.orthographic) + { + view.rotation = cameraTransform.rotation; + } + view.pivot = cameraTransform.position + cameraTransform.forward * d; + view.Repaint(); + } + } + private static Vector3 GetMovementDirection() + { + float num = SceneViewMotion.s_FPSTiming.Update(); + if (SceneViewMotion.s_Motion.sqrMagnitude == 0f) + { + SceneViewMotion.s_FlySpeed = 0f; + return Vector3.zero; + } + float d = (float)((!Event.current.shift) ? 1 : 5); + if (SceneViewMotion.s_FlySpeed == 0f) + { + SceneViewMotion.s_FlySpeed = 9f; + } + else + { + SceneViewMotion.s_FlySpeed *= Mathf.Pow(1.8f, num); + } + return SceneViewMotion.s_Motion.normalized * SceneViewMotion.s_FlySpeed * d * num; + } + private static void HandleMouseDown(SceneView view, int id, int button) + { + SceneViewMotion.s_Dragged = false; + if (Tools.viewToolActive) + { + ViewTool viewTool = Tools.viewTool; + if (Tools.s_LockedViewTool != viewTool) + { + Event current = Event.current; + GUIUtility.hotControl = id; + Tools.s_LockedViewTool = viewTool; + SceneViewMotion.s_StartZoom = view.size; + SceneViewMotion.s_ZoomSpeed = Mathf.Max(Mathf.Abs(SceneViewMotion.s_StartZoom), 0.3f); + SceneViewMotion.s_TotalMotion = 0f; + if (view) + { + view.Focus(); + } + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + EditorGUIUtility.SetWantsMouseJumping(1); + current.Use(); + GUIUtility.ExitGUI(); + } + } + } + private static void ResetDragState() + { + GUIUtility.hotControl = 0; + Tools.s_LockedViewTool = ViewTool.None; + Tools.s_ButtonDown = -1; + SceneViewMotion.s_Motion = Vector3.zero; + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + EditorGUIUtility.SetWantsMouseJumping(0); + } + private static void HandleMouseUp(SceneView view, int id, int button, int clickCount) + { + if (GUIUtility.hotControl == id) + { + SceneViewMotion.ResetDragState(); + RaycastHit raycastHit; + if (button == 2 && !SceneViewMotion.s_Dragged && SceneViewMotion.RaycastWorld(Event.current.mousePosition, out raycastHit)) + { + Vector3 b = view.pivot - view.rotation * Vector3.forward * view.cameraDistance; + float size = view.size; + if (!view.orthographic) + { + size = view.size * Vector3.Dot(raycastHit.point - b, view.rotation * Vector3.forward) / view.cameraDistance; + } + view.LookAt(raycastHit.point, view.rotation, size); + } + Event.current.Use(); + } + } + private static bool RaycastWorld(Vector2 position, out RaycastHit hit) + { + hit = default(RaycastHit); + GameObject gameObject = HandleUtility.PickGameObject(position, false); + if (!gameObject) + { + return false; + } + Ray ray = HandleUtility.GUIPointToWorldRay(position); + MeshFilter[] componentsInChildren = gameObject.GetComponentsInChildren(); + float num = float.PositiveInfinity; + MeshFilter[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + MeshFilter meshFilter = array[i]; + Mesh sharedMesh = meshFilter.sharedMesh; + if (sharedMesh) + { + RaycastHit raycastHit; + if (HandleUtility.IntersectRayMesh(ray, sharedMesh, meshFilter.transform.localToWorldMatrix, out raycastHit) && raycastHit.distance < num) + { + hit = raycastHit; + num = hit.distance; + } + } + } + if (num == float.PositiveInfinity) + { + hit.point = Vector3.Project(gameObject.transform.position - ray.origin, ray.direction) + ray.origin; + } + return true; + } + private static void OrbitCameraBehavior(SceneView view) + { + Event current = Event.current; + view.FixNegativeSize(); + Quaternion quaternion = view.m_Rotation.target; + quaternion = Quaternion.AngleAxis(current.delta.y * 0.003f * 57.29578f, quaternion * Vector3.right) * quaternion; + quaternion = Quaternion.AngleAxis(current.delta.x * 0.003f * 57.29578f, Vector3.up) * quaternion; + if (view.size < 0f) + { + view.pivot = view.camera.transform.position; + view.size = 0f; + } + view.rotation = quaternion; + } + private static void HandleMouseDrag(Transform cameraTransform, SceneView view, int id) + { + SceneViewMotion.s_Dragged = true; + if (GUIUtility.hotControl == id) + { + Event current = Event.current; + switch (Tools.s_LockedViewTool) + { + case ViewTool.Orbit: + if (!view.in2DMode) + { + SceneViewMotion.OrbitCameraBehavior(view); + view.svRot.UpdateGizmoLabel(view, view.rotation * Vector3.forward, view.m_Ortho.target); + } + break; + case ViewTool.Pan: + { + view.viewIsLockedToObject = false; + view.FixNegativeSize(); + Camera camera = view.camera; + Vector3 vector = camera.WorldToScreenPoint(view.pivot); + vector += new Vector3(-Event.current.delta.x, Event.current.delta.y, 0f); + Vector3 vector2 = Camera.current.ScreenToWorldPoint(vector) - view.pivot; + if (current.shift) + { + vector2 *= 4f; + } + view.pivot += vector2; + break; + } + case ViewTool.Zoom: + { + float num = HandleUtility.niceMouseDeltaZoom * (float)((!current.shift) ? 3 : 9); + if (view.orthographic) + { + view.size = Mathf.Max(0.0001f, view.size * (1f + num * 0.001f)); + } + else + { + SceneViewMotion.s_TotalMotion += num; + if (SceneViewMotion.s_TotalMotion < 0f) + { + view.size = SceneViewMotion.s_StartZoom * (1f + SceneViewMotion.s_TotalMotion * 0.001f); + } + else + { + view.size += num * SceneViewMotion.s_ZoomSpeed * 0.003f; + } + } + break; + } + case ViewTool.FPS: + if (!view.in2DMode) + { + if (!view.orthographic) + { + view.viewIsLockedToObject = false; + Quaternion quaternion = cameraTransform.rotation; + quaternion = Quaternion.AngleAxis(current.delta.y * 0.003f * 57.29578f, quaternion * Vector3.right) * quaternion; + quaternion = Quaternion.AngleAxis(current.delta.x * 0.003f * 57.29578f, Vector3.up) * quaternion; + cameraTransform.rotation = quaternion; + } + else + { + SceneViewMotion.OrbitCameraBehavior(view); + } + view.svRot.UpdateGizmoLabel(view, view.rotation * Vector3.forward, view.m_Ortho.target); + } + break; + default: + Debug.Log("Enum value Tools.s_LockViewTool not handled"); + break; + } + current.Use(); + } + } + private static void HandleKeyDown(SceneView sceneView) + { + if (Event.current.keyCode == KeyCode.Escape && GUIUtility.hotControl == SceneViewMotion.s_ViewToolID) + { + SceneViewMotion.ResetDragState(); + } + if (Tools.s_LockedViewTool == ViewTool.FPS) + { + Event current = Event.current; + Vector3 vector = SceneViewMotion.s_Motion; + if (current.keyCode == SceneViewMotion.kFPSForward.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.z = 1f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSBack.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.z = -1f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSLeft.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.x = -1f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSRight.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.x = 1f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSUp.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.y = 1f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSDown.keyCode) + { + sceneView.viewIsLockedToObject = false; + SceneViewMotion.s_Motion.y = -1f; + current.Use(); + } + } + } + } + } + } + if (current.type != EventType.KeyDown && vector.sqrMagnitude == 0f) + { + SceneViewMotion.s_FPSTiming.Begin(); + } + } + } + private static void HandleKeyUp() + { + if (Tools.s_LockedViewTool == ViewTool.FPS) + { + Event current = Event.current; + if (current.keyCode == SceneViewMotion.kFPSForward.keyCode) + { + SceneViewMotion.s_Motion.z = 0f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSBack.keyCode) + { + SceneViewMotion.s_Motion.z = 0f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSLeft.keyCode) + { + SceneViewMotion.s_Motion.x = 0f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSRight.keyCode) + { + SceneViewMotion.s_Motion.x = 0f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSUp.keyCode) + { + SceneViewMotion.s_Motion.y = 0f; + current.Use(); + } + else + { + if (current.keyCode == SceneViewMotion.kFPSDown.keyCode) + { + SceneViewMotion.s_Motion.y = 0f; + current.Use(); + } + } + } + } + } + } + } + } + private static void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) + { + float cameraDistance = view.cameraDistance; + Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); + Vector3 a = ray.origin + ray.direction * view.cameraDistance; + Vector3 a2 = a - view.pivot; + float y = Event.current.delta.y; + if (!view.orthographic) + { + float num = Mathf.Abs(view.size) * y * 0.015f; + if (num > 0f && num < 0.3f) + { + num = 0.3f; + } + else + { + if (num < 0f && num > -0.3f) + { + num = -0.3f; + } + } + view.size += num; + } + else + { + view.size = Mathf.Abs(view.size) * (y * 0.015f + 1f); + } + float d = 1f - view.cameraDistance / cameraDistance; + if (!zoomTowardsCenter) + { + view.pivot += a2 * d; + } + Event.current.Use(); + } + } +} diff --git a/UnityEditor/UnityEditor/SceneViewOverlay.cs b/UnityEditor/UnityEditor/SceneViewOverlay.cs new file mode 100644 index 00000000..35af7ff8 --- /dev/null +++ b/UnityEditor/UnityEditor/SceneViewOverlay.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneViewOverlay + { + public enum Ordering + { + Camera = -100, + OcclusionCulling = 100, + Lightmapping = 200, + NavMesh = 300, + ParticleEffect = 400 + } + public enum WindowDisplayOption + { + MultipleWindowsPerTarget, + OneWindowPerTarget, + OneWindowPerTitle + } + private class OverlayWindow : IComparable + { + public GUIContent m_Title; + public SceneViewOverlay.WindowFunction m_SceneViewFunc; + public int m_PrimaryOrder; + public int m_SecondaryOrder; + public UnityEngine.Object m_Target; + public int CompareTo(SceneViewOverlay.OverlayWindow other) + { + int num = other.m_PrimaryOrder.CompareTo(this.m_PrimaryOrder); + if (num == 0) + { + num = other.m_SecondaryOrder.CompareTo(this.m_SecondaryOrder); + } + return num; + } + } + public delegate void WindowFunction(UnityEngine.Object target, SceneView sceneView); + private static List m_Windows; + private Rect m_WindowRect = new Rect(0f, 0f, 0f, 0f); + private SceneView m_SceneView; + private float k_WindowPadding = 9f; + public SceneViewOverlay(SceneView sceneView) + { + this.m_SceneView = sceneView; + SceneViewOverlay.m_Windows = new List(); + } + public void Begin() + { + if (!this.m_SceneView.m_ShowSceneViewWindows) + { + return; + } + if (Event.current.type == EventType.Layout) + { + SceneViewOverlay.m_Windows.Clear(); + } + this.m_SceneView.BeginWindows(); + } + public void End() + { + if (!this.m_SceneView.m_ShowSceneViewWindows) + { + return; + } + SceneViewOverlay.m_Windows.Sort(); + if (SceneViewOverlay.m_Windows.Count > 0) + { + this.m_WindowRect.x = 0f; + this.m_WindowRect.y = 0f; + this.m_WindowRect.width = this.m_SceneView.position.width; + this.m_WindowRect.height = this.m_SceneView.position.height; + this.m_WindowRect = GUILayout.Window("SceneViewOverlay".GetHashCode(), this.m_WindowRect, new GUI.WindowFunction(this.WindowTrampoline), string.Empty, "SceneViewOverlayTransparentBackground", new GUILayoutOption[0]); + } + this.m_SceneView.EndWindows(); + } + private void WindowTrampoline(int id) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + float num = -this.k_WindowPadding; + foreach (SceneViewOverlay.OverlayWindow current in SceneViewOverlay.m_Windows) + { + GUILayout.Space(this.k_WindowPadding + num); + num = 0f; + EditorGUIUtility.ResetGUIState(); + GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); + EditorStyles.UpdateSkinCache(1); + GUILayout.BeginVertical(current.m_Title, GUI.skin.window, new GUILayoutOption[0]); + current.m_SceneViewFunc(current.m_Target, this.m_SceneView); + GUILayout.EndVertical(); + } + EditorStyles.UpdateSkinCache(); + GUILayout.EndVertical(); + Rect lastRect = GUILayoutUtility.GetLastRect(); + this.EatMouseInput(lastRect); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + private void EatMouseInput(Rect position) + { + SceneView.AddCursorRect(position, MouseCursor.Arrow); + int controlID = GUIUtility.GetControlID("SceneViewOverlay".GetHashCode(), FocusType.Native, position); + switch (Event.current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = controlID; + Event.current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Event.current.Use(); + } + break; + case EventType.ScrollWheel: + if (position.Contains(Event.current.mousePosition)) + { + Event.current.Use(); + } + break; + } + } + public static void Window(GUIContent title, SceneViewOverlay.WindowFunction sceneViewFunc, int order, SceneViewOverlay.WindowDisplayOption option) + { + SceneViewOverlay.Window(title, sceneViewFunc, order, null, option); + } + public static void Window(GUIContent title, SceneViewOverlay.WindowFunction sceneViewFunc, int order, UnityEngine.Object target, SceneViewOverlay.WindowDisplayOption option) + { + if (Event.current.type != EventType.Layout) + { + return; + } + foreach (SceneViewOverlay.OverlayWindow current in SceneViewOverlay.m_Windows) + { + if (option == SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget && current.m_Target == target && target != null) + { + return; + } + if (option == SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle && (current.m_Title == title || current.m_Title.text == title.text)) + { + return; + } + } + SceneViewOverlay.OverlayWindow overlayWindow = new SceneViewOverlay.OverlayWindow(); + overlayWindow.m_Title = title; + overlayWindow.m_SceneViewFunc = sceneViewFunc; + overlayWindow.m_PrimaryOrder = order; + overlayWindow.m_SecondaryOrder = SceneViewOverlay.m_Windows.Count; + overlayWindow.m_Target = target; + SceneViewOverlay.m_Windows.Add(overlayWindow); + } + } +} diff --git a/UnityEditor/UnityEditor/SceneViewRotation.cs b/UnityEditor/UnityEditor/SceneViewRotation.cs new file mode 100644 index 00000000..b2a960ef --- /dev/null +++ b/UnityEditor/UnityEditor/SceneViewRotation.cs @@ -0,0 +1,500 @@ +using System; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [Serializable] + internal class SceneViewRotation + { + private class Styles + { + public GUIStyle viewLabelStyleLeftAligned; + public GUIStyle viewLabelStyleCentered; + public GUIStyle viewAxisLabelStyle; + public Styles() + { + this.viewLabelStyleLeftAligned = new GUIStyle("SC ViewLabel"); + this.viewLabelStyleCentered = new GUIStyle("SC ViewLabel"); + this.viewLabelStyleLeftAligned.alignment = TextAnchor.MiddleLeft; + this.viewLabelStyleCentered.alignment = TextAnchor.MiddleCenter; + this.viewAxisLabelStyle = "SC ViewAxisLabel"; + } + } + private const int kRotationSize = 100; + private const int kRotationTop = 14; + private const int kRotationMenuInset = 22; + private static Quaternion[] kDirectionRotations = new Quaternion[] + { + Quaternion.LookRotation(new Vector3(-1f, 0f, 0f)), + Quaternion.LookRotation(new Vector3(0f, -1f, 0f)), + Quaternion.LookRotation(new Vector3(0f, 0f, -1f)), + Quaternion.LookRotation(new Vector3(1f, 0f, 0f)), + Quaternion.LookRotation(new Vector3(0f, 1f, 0f)), + Quaternion.LookRotation(new Vector3(0f, 0f, 1f)) + }; + private static string[] kDirNames = new string[] + { + "Right", + "Top", + "Front", + "Left", + "Bottom", + "Back", + "Iso", + "Persp", + "2D" + }; + private static string[] kMenuDirNames = new string[] + { + "Free", + "Right", + "Top", + "Front", + "Left", + "Bottom", + "Back", + string.Empty, + "Perspective" + }; + private int currentDir = 7; + private AnimBool[] dirVisible = new AnimBool[] + { + new AnimBool(), + new AnimBool(), + new AnimBool() + }; + private AnimBool[] dirNameVisible = new AnimBool[] + { + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool(), + new AnimBool() + }; + private AnimBool m_Visible = new AnimBool(); + private static SceneViewRotation.Styles s_Styles; + private float faded2Dgray + { + get + { + return this.dirNameVisible[8].faded; + } + } + private static SceneViewRotation.Styles styles + { + get + { + if (SceneViewRotation.s_Styles == null) + { + SceneViewRotation.s_Styles = new SceneViewRotation.Styles(); + } + return SceneViewRotation.s_Styles; + } + } + public void Register(SceneView view) + { + for (int i = 0; i < this.dirVisible.Length; i++) + { + this.dirVisible[i].valueChanged.AddListener(new UnityAction(view.Repaint)); + } + for (int j = 0; j < this.dirNameVisible.Length; j++) + { + this.dirNameVisible[j].valueChanged.AddListener(new UnityAction(view.Repaint)); + } + this.m_Visible.valueChanged.AddListener(new UnityAction(view.Repaint)); + int labelIndexForView = this.GetLabelIndexForView(view, view.rotation * Vector3.forward, view.orthographic); + for (int k = 0; k < this.dirNameVisible.Length; k++) + { + this.dirNameVisible[k].value = (k == labelIndexForView); + } + this.m_Visible.value = (labelIndexForView != 8); + this.SwitchDirNameVisible(labelIndexForView); + } + private void AxisSelectors(SceneView view, Camera cam, float size, float sgn, GUIStyle viewAxisLabelStyle) + { + for (int i = SceneViewRotation.kDirectionRotations.Length - 1; i >= 0; i--) + { + Quaternion quaternion = SceneViewRotation.kDirectionRotations[i]; + string[] array = new string[] + { + "x", + "y", + "z" + }; + float faded = this.dirVisible[i % 3].faded; + Vector3 vector = SceneViewRotation.kDirectionRotations[i] * Vector3.forward; + float num = Vector3.Dot(view.camera.transform.forward, vector); + if ((double)num > 0.0 || sgn <= 0f) + { + if ((double)num <= 0.0 || sgn >= 0f) + { + Color color; + switch (i) + { + case 0: + color = Handles.xAxisColor; + break; + case 1: + color = Handles.yAxisColor; + break; + case 2: + color = Handles.zAxisColor; + break; + default: + color = Handles.centerColor; + break; + } + if (view.in2DMode) + { + color = Color.Lerp(color, Color.gray, this.faded2Dgray); + } + color.a *= faded * this.m_Visible.faded; + Handles.color = color; + if (color.a <= 0.1f) + { + GUI.enabled = false; + } + if (sgn > 0f && Handles.Button(quaternion * Vector3.forward * size * -1.2f, quaternion, size, size * 0.7f, new Handles.DrawCapFunction(Handles.ConeCap)) && !view.in2DMode) + { + this.ViewAxisDirection(view, i); + } + if (i < 3) + { + GUI.color = new Color(1f, 1f, 1f, this.dirVisible[i].faded * this.m_Visible.faded); + Vector3 a = vector; + a += num * view.camera.transform.forward * -0.5f; + a = (a * 0.7f + a.normalized * 1.5f) * size; + Handles.Label(-a, new GUIContent(array[i]), SceneViewRotation.styles.viewAxisLabelStyle); + } + if (sgn < 0f && Handles.Button(quaternion * Vector3.forward * size * -1.2f, quaternion, size, size * 0.7f, new Handles.DrawCapFunction(Handles.ConeCap)) && !view.in2DMode) + { + this.ViewAxisDirection(view, i); + } + Handles.color = Color.white; + GUI.color = Color.white; + GUI.enabled = true; + } + } + } + } + internal void HandleContextClick(SceneView view) + { + if (!view.in2DMode) + { + Event current = Event.current; + if (current.type == EventType.MouseDown && current.button == 1) + { + int num = Mathf.Min(Screen.width, Screen.height - 14); + if (num < 100) + { + return; + } + Rect rect = new Rect((float)(Screen.width - 100 + 22), 20f, 56f, 56f); + if (rect.Contains(current.mousePosition)) + { + this.DisplayContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), view); + current.Use(); + } + } + } + } + private void DisplayContextMenu(Rect buttonOrCursorRect, SceneView view) + { + int[] array = new int[(!view.orthographic) ? 2 : 1]; + array[0] = ((this.currentDir < 6) ? (this.currentDir + 1) : 0); + if (!view.orthographic) + { + array[1] = 8; + } + EditorUtility.DisplayCustomMenu(buttonOrCursorRect, SceneViewRotation.kMenuDirNames, array, new EditorUtility.SelectMenuItemFunction(this.ContextMenuDelegate), view); + GUIUtility.ExitGUI(); + } + private void ContextMenuDelegate(object userData, string[] options, int selected) + { + SceneView sceneView = userData as SceneView; + if (sceneView == null) + { + return; + } + if (selected == 0) + { + this.ViewFromNiceAngle(sceneView, false); + } + else + { + if (selected >= 1 && selected <= 6) + { + int dir = selected - 1; + this.ViewAxisDirection(sceneView, dir); + } + else + { + if (selected == 8) + { + this.ViewSetOrtho(sceneView, !sceneView.orthographic); + } + } + } + } + private void DrawIsoStatusSymbol(Vector3 center, SceneView view, float alpha) + { + float num = 1f - Mathf.Clamp01(view.m_Ortho.faded * 1.2f - 0.1f); + Vector3 a = Vector3.up * 3f; + Vector3 vector = Vector3.right * 10f; + Vector3 vector2 = center - vector * 0.5f; + Handles.color = new Color(1f, 1f, 1f, 0.6f * alpha); + Handles.DrawAAPolyLine(new Vector3[] + { + vector2 + a * (1f - num), + vector2 + vector + a * (1f + num * 0.5f) + }); + Handles.DrawAAPolyLine(new Vector3[] + { + vector2, + vector2 + vector + }); + Handles.DrawAAPolyLine(new Vector3[] + { + vector2 - a * (1f - num), + vector2 + vector - a * (1f + num * 0.5f) + }); + } + internal void OnGUI(SceneView view) + { + int num = Mathf.Min(Screen.width, Screen.height - 14); + if (num < 100) + { + return; + } + Camera camera = view.camera; + HandleUtility.PushCamera(camera); + if (camera.orthographic) + { + camera.orthographicSize = 0.5f; + } + camera.cullingMask = 0; + camera.transform.position = camera.transform.rotation * new Vector3(0f, 0f, -5f); + camera.clearFlags = CameraClearFlags.Nothing; + camera.nearClipPlane = 0.1f; + camera.farClipPlane = 10f; + camera.fieldOfView = view.m_Ortho.Fade(70f, 0f); + SceneView.AddCursorRect(new Rect((float)(Screen.width - 100), -14f, 100f, 148f), MouseCursor.Arrow); + Handles.SetCamera(new Rect((float)(Screen.width - 100), -14f, 100f, 128f), camera); + Handles.BeginGUI(); + Rect rect = new Rect((float)(Screen.width - 100 + 17), 88f, 66f, 16f); + if (!view.in2DMode && GUI.Button(rect, string.Empty, SceneViewRotation.styles.viewLabelStyleLeftAligned)) + { + if (Event.current.button == 1) + { + this.DisplayContextMenu(rect, view); + } + else + { + this.ViewSetOrtho(view, !view.orthographic); + } + } + int num2 = 8; + Rect position = rect; + float num3 = 0f; + float num4 = 0f; + for (int i = 0; i < SceneViewRotation.kDirNames.Length; i++) + { + if (i != num2) + { + num4 += this.dirNameVisible[i].faded; + if (this.dirNameVisible[i].faded > 0f) + { + num3 += SceneViewRotation.styles.viewLabelStyleLeftAligned.CalcSize(EditorGUIUtility.TempContent(SceneViewRotation.kDirNames[i])).x * this.dirNameVisible[i].faded; + } + } + } + if (num4 > 0f) + { + num3 /= num4; + } + position.x += 37f - num3 * 0.5f; + position.x = (float)Mathf.RoundToInt(position.x); + int num5 = 0; + while (num5 < this.dirNameVisible.Length && num5 < SceneViewRotation.kDirNames.Length) + { + if (num5 != num2) + { + Color centerColor = Handles.centerColor; + centerColor.a *= this.dirNameVisible[num5].faded; + GUI.color = centerColor; + GUI.Label(position, SceneViewRotation.kDirNames[num5], SceneViewRotation.styles.viewLabelStyleLeftAligned); + } + num5++; + } + Color centerColor2 = Handles.centerColor; + centerColor2.a *= this.faded2Dgray * this.m_Visible.faded; + GUI.color = centerColor2; + GUI.Label(rect, SceneViewRotation.kDirNames[num2], SceneViewRotation.styles.viewLabelStyleCentered); + if (this.faded2Dgray < 1f) + { + this.DrawIsoStatusSymbol(new Vector3(position.x - 8f, position.y + 8.5f, 0f), view, 1f - this.faded2Dgray); + } + Handles.EndGUI(); + for (int j = 0; j < 3; j++) + { + Vector3 rhs = SceneViewRotation.kDirectionRotations[j] * Vector3.forward; + this.dirVisible[j].target = (Mathf.Abs(Vector3.Dot(camera.transform.forward, rhs)) < 0.9f); + } + float num6 = HandleUtility.GetHandleSize(Vector3.zero) * 0.2f; + this.AxisSelectors(view, camera, num6, -1f, SceneViewRotation.styles.viewAxisLabelStyle); + Color color = Handles.centerColor; + color = Color.Lerp(color, Color.gray, this.faded2Dgray); + color.a *= this.m_Visible.faded; + if (color.a <= 0.1f) + { + GUI.enabled = false; + } + Handles.color = color; + if (Handles.Button(Vector3.zero, Quaternion.identity, num6 * 0.8f, num6, new Handles.DrawCapFunction(Handles.CubeCap)) && !view.in2DMode) + { + if (Event.current.clickCount == 2) + { + view.FrameSelected(); + } + else + { + if (Event.current.shift || Event.current.button == 2) + { + this.ViewFromNiceAngle(view, true); + } + else + { + this.ViewSetOrtho(view, !view.orthographic); + } + } + } + this.AxisSelectors(view, camera, num6, 1f, SceneViewRotation.styles.viewAxisLabelStyle); + GUI.enabled = true; + if (!view.in2DMode && Event.current.type == EditorGUIUtility.swipeGestureEventType) + { + Event current = Event.current; + Vector3 a; + if (current.delta.y > 0f) + { + a = Vector3.up; + } + else + { + if (current.delta.y < 0f) + { + a = -Vector3.up; + } + else + { + if (current.delta.x < 0f) + { + a = Vector3.right; + } + else + { + a = -Vector3.right; + } + } + } + Vector3 vector = -a - Vector3.forward * 0.9f; + vector = view.camera.transform.TransformDirection(vector); + float num7 = 0f; + int dir = 0; + for (int k = 0; k < 6; k++) + { + float num8 = Vector3.Dot(SceneViewRotation.kDirectionRotations[k] * -Vector3.forward, vector); + if (num8 > num7) + { + num7 = num8; + dir = k; + } + } + this.ViewAxisDirection(view, dir); + Event.current.Use(); + } + HandleUtility.PopCamera(camera); + Handles.SetCamera(camera); + } + private void ViewAxisDirection(SceneView view, int dir) + { + bool orthographic = view.orthographic; + if (Event.current != null && (Event.current.shift || Event.current.button == 2)) + { + orthographic = true; + } + view.LookAt(view.pivot, SceneViewRotation.kDirectionRotations[dir], view.size, orthographic); + this.SwitchDirNameVisible(dir); + } + private void ViewSetOrtho(SceneView view, bool ortho) + { + view.LookAt(view.pivot, view.rotation, view.size, ortho); + } + internal void UpdateGizmoLabel(SceneView view, Vector3 direction, bool ortho) + { + this.SwitchDirNameVisible(this.GetLabelIndexForView(view, direction, ortho)); + } + internal int GetLabelIndexForView(SceneView view, Vector3 direction, bool ortho) + { + if (!view.in2DMode) + { + if (this.IsAxisAligned(direction)) + { + for (int i = 0; i < 6; i++) + { + if (Vector3.Dot(SceneViewRotation.kDirectionRotations[i] * Vector3.forward, direction) > 0.9f) + { + return i; + } + } + } + return (!ortho) ? 7 : 6; + } + return 8; + } + private void ViewFromNiceAngle(SceneView view, bool forcePerspective) + { + Vector3 vector = view.rotation * Vector3.forward; + vector.y = 0f; + if (vector == Vector3.zero) + { + vector = Vector3.forward; + } + else + { + vector = vector.normalized; + } + vector.y = -0.5f; + bool flag = !forcePerspective && view.orthographic; + view.LookAt(view.pivot, Quaternion.LookRotation(vector), view.size, flag); + this.SwitchDirNameVisible((!flag) ? 7 : 6); + } + private bool IsAxisAligned(Vector3 v) + { + return Mathf.Abs(v.x * v.y) < 0.0001f && Mathf.Abs(v.y * v.z) < 0.0001f && Mathf.Abs(v.z * v.x) < 0.0001f; + } + private void SwitchDirNameVisible(int newVisible) + { + if (newVisible == this.currentDir) + { + return; + } + this.dirNameVisible[this.currentDir].target = false; + this.currentDir = newVisible; + this.dirNameVisible[this.currentDir].target = true; + if (newVisible == 8) + { + this.m_Visible.speed = 0.3f; + } + else + { + this.m_Visible.speed = 2f; + } + this.m_Visible.target = (newVisible != 8); + } + } +} diff --git a/UnityEditor/UnityEditor/ScreenShots.cs b/UnityEditor/UnityEditor/ScreenShots.cs new file mode 100644 index 00000000..4f30eb7f --- /dev/null +++ b/UnityEditor/UnityEditor/ScreenShots.cs @@ -0,0 +1,164 @@ +using System; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ScreenShots + { + public static Color kToolbarBorderColor = new Color(0.54f, 0.54f, 0.54f, 1f); + public static Color kWindowBorderColor = new Color(0.51f, 0.51f, 0.51f, 1f); + public static bool s_TakeComponentScreenshot = false; + [MenuItem("Window/Screenshot/Set Window Size %&l", false, 1000, true)] + public static void SetMainWindowSize() + { + MainWindow mainWindow = Resources.FindObjectsOfTypeAll(typeof(MainWindow))[0] as MainWindow; + mainWindow.window.position = new Rect(0f, 0f, 1024f, 768f); + } + [MenuItem("Window/Screenshot/Set Window Size Small", false, 1000, true)] + public static void SetMainWindowSizeSmall() + { + MainWindow mainWindow = Resources.FindObjectsOfTypeAll(typeof(MainWindow))[0] as MainWindow; + mainWindow.window.position = new Rect(0f, 0f, 762f, 600f); + } + [MenuItem("Window/Screenshot/Snap View %&j", false, 1000, true)] + public static void Screenshot() + { + GUIView mouseOverView = ScreenShots.GetMouseOverView(); + if (mouseOverView != null) + { + string gUIViewName = ScreenShots.GetGUIViewName(mouseOverView); + Rect screenPosition = mouseOverView.screenPosition; + screenPosition.y -= 1f; + screenPosition.height += 2f; + ScreenShots.SaveScreenShot(screenPosition, gUIViewName); + } + } + [MenuItem("Window/Screenshot/Snap View Toolbar", false, 1000, true)] + public static void ScreenshotToolbar() + { + GUIView mouseOverView = ScreenShots.GetMouseOverView(); + if (mouseOverView != null) + { + string name = ScreenShots.GetGUIViewName(mouseOverView) + "Toolbar"; + Rect screenPosition = mouseOverView.screenPosition; + screenPosition.y += 19f; + screenPosition.height = 16f; + screenPosition.width -= 2f; + ScreenShots.SaveScreenShotWithBorder(screenPosition, ScreenShots.kToolbarBorderColor, name); + } + } + [MenuItem("Window/Screenshot/Snap View Extended Right %&k", false, 1000, true)] + public static void ScreenshotExtendedRight() + { + GUIView mouseOverView = ScreenShots.GetMouseOverView(); + if (mouseOverView != null) + { + string name = ScreenShots.GetGUIViewName(mouseOverView) + "Extended"; + MainWindow mainWindow = Resources.FindObjectsOfTypeAll(typeof(MainWindow))[0] as MainWindow; + Rect screenPosition = mouseOverView.screenPosition; + screenPosition.xMax = mainWindow.window.position.xMax; + screenPosition.y -= 1f; + screenPosition.height += 2f; + ScreenShots.SaveScreenShot(screenPosition, name); + } + } + [MenuItem("Window/Screenshot/Snap Component", false, 1000, true)] + public static void ScreenShotComponent() + { + ScreenShots.s_TakeComponentScreenshot = true; + } + public static void ScreenShotComponent(Rect contentRect, UnityEngine.Object target) + { + ScreenShots.s_TakeComponentScreenshot = false; + contentRect.yMax += 2f; + contentRect.xMin += 1f; + ScreenShots.SaveScreenShotWithBorder(contentRect, ScreenShots.kWindowBorderColor, target.GetType().Name + "Inspector"); + } + [MenuItem("Window/Screenshot/Snap Game View Content", false, 1000, true)] + public static void ScreenGameViewContent() + { + string uniquePathForName = ScreenShots.GetUniquePathForName("ContentExample"); + Application.CaptureScreenshot(uniquePathForName); + Debug.Log(string.Format("Saved screenshot at {0}", uniquePathForName)); + } + [MenuItem("Window/Screenshot/Toggle DeveloperBuild", false, 1000, true)] + public static void ToggleFakeNonDeveloperBuild() + { + Unsupported.fakeNonDeveloperBuild = !Unsupported.fakeNonDeveloperBuild; + InternalEditorUtility.RequestScriptReload(); + InternalEditorUtility.RepaintAllViews(); + } + private static GUIView GetMouseOverView() + { + GUIView mouseOverView = GUIView.mouseOverView; + if (mouseOverView == null) + { + EditorApplication.Beep(); + Debug.LogWarning("Could not take screenshot."); + } + return mouseOverView; + } + private static string GetGUIViewName(GUIView view) + { + HostView hostView = view as HostView; + if (hostView != null) + { + return hostView.actualView.GetType().Name; + } + return "Window"; + } + public static void SaveScreenShot(Rect r, string name) + { + ScreenShots.SaveScreenShot((int)r.width, (int)r.height, InternalEditorUtility.ReadScreenPixel(new Vector2(r.x, r.y), (int)r.width, (int)r.height), name); + } + public static string SaveScreenShotWithBorder(Rect r, Color borderColor, string name) + { + int num = (int)r.width; + int num2 = (int)r.height; + Color[] array = InternalEditorUtility.ReadScreenPixel(new Vector2(r.x, r.y), num, num2); + Color[] array2 = new Color[(num + 2) * (num2 + 2)]; + for (int i = 0; i < num; i++) + { + for (int j = 0; j < num2; j++) + { + array2[i + 1 + (num + 2) * (j + 1)] = array[i + num * j]; + } + } + for (int k = 0; k < num + 2; k++) + { + array2[k] = borderColor; + array2[k + (num + 2) * (num2 + 1)] = borderColor; + } + for (int l = 0; l < num2 + 2; l++) + { + array2[l * (num + 2)] = borderColor; + array2[l * (num + 2) + (num + 1)] = borderColor; + } + return ScreenShots.SaveScreenShot((int)(r.width + 2f), (int)(r.height + 2f), array2, name); + } + private static string SaveScreenShot(int width, int height, Color[] pixels, string name) + { + Texture2D texture2D = new Texture2D(width, height); + texture2D.SetPixels(pixels, 0); + texture2D.Apply(true); + byte[] bytes = texture2D.EncodeToPNG(); + UnityEngine.Object.DestroyImmediate(texture2D, true); + string uniquePathForName = ScreenShots.GetUniquePathForName(name); + File.WriteAllBytes(uniquePathForName, bytes); + Debug.Log(string.Format("Saved screenshot at {0}", uniquePathForName)); + return uniquePathForName; + } + private static string GetUniquePathForName(string name) + { + string text = string.Format("{0}/../../{1}.png", Application.dataPath, name); + int num = 0; + while (File.Exists(text)) + { + text = string.Format("{0}/../../{1}{2:000}.png", Application.dataPath, name, num); + num++; + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptAttributeUtility.cs b/UnityEditor/UnityEditor/ScriptAttributeUtility.cs new file mode 100644 index 00000000..0559e573 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptAttributeUtility.cs @@ -0,0 +1,263 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEditor +{ + internal class ScriptAttributeUtility + { + private struct DrawerKeySet + { + public Type drawer; + public Type type; + } + internal static Stack s_DrawerStack = new Stack(); + private static Dictionary s_DrawerTypeForType = null; + private static Dictionary> s_BuiltinAttributes = null; + private static PropertyHandler s_SharedNullHandler = new PropertyHandler(); + private static PropertyHandler s_NextHandler = new PropertyHandler(); + private static PropertyHandlerCache s_GlobalCache = new PropertyHandlerCache(); + private static PropertyHandlerCache s_CurrentCache = null; + internal static PropertyHandlerCache propertyHandlerCache + { + get + { + return ScriptAttributeUtility.s_CurrentCache ?? ScriptAttributeUtility.s_GlobalCache; + } + set + { + ScriptAttributeUtility.s_CurrentCache = value; + } + } + internal static void ClearGlobalCache() + { + ScriptAttributeUtility.s_GlobalCache.Clear(); + } + private static void PopulateBuiltinAttributes() + { + ScriptAttributeUtility.s_BuiltinAttributes = new Dictionary>(); + ScriptAttributeUtility.AddBuiltinAttribute("GUIText", "m_Text", new MultilineAttribute()); + } + private static void AddBuiltinAttribute(string componentTypeName, string propertyPath, PropertyAttribute attr) + { + string key = componentTypeName + "_" + propertyPath; + if (!ScriptAttributeUtility.s_BuiltinAttributes.ContainsKey(key)) + { + ScriptAttributeUtility.s_BuiltinAttributes.Add(key, new List()); + } + ScriptAttributeUtility.s_BuiltinAttributes[key].Add(attr); + } + private static List GetBuiltinAttributes(SerializedProperty property) + { + if (property.serializedObject.targetObject == null) + { + return null; + } + Type type = property.serializedObject.targetObject.GetType(); + if (type == null) + { + return null; + } + string key = type.Name + "_" + property.propertyPath; + List result = null; + ScriptAttributeUtility.s_BuiltinAttributes.TryGetValue(key, out result); + return result; + } + private static void BuildDrawerTypeForTypeDictionary() + { + ScriptAttributeUtility.s_DrawerTypeForType = new Dictionary(); + Type[] source = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => AssemblyHelper.GetTypesFromAssembly(x)).ToArray(); + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(GUIDrawer))) + { + object[] customAttributes = current.GetCustomAttributes(typeof(CustomPropertyDrawer), true); + object[] array = customAttributes; + CustomPropertyDrawer editor; + for (int i = 0; i < array.Length; i++) + { + editor = (CustomPropertyDrawer)array[i]; + ScriptAttributeUtility.s_DrawerTypeForType[editor.m_Type] = new ScriptAttributeUtility.DrawerKeySet + { + drawer = current, + type = editor.m_Type + }; + if (editor.m_UseForChildren) + { + IEnumerable enumerable = + from x in source + where x.IsSubclassOf(editor.m_Type) + select x; + foreach (Type current2 in enumerable) + { + if (!ScriptAttributeUtility.s_DrawerTypeForType.ContainsKey(current2) || !editor.m_Type.IsAssignableFrom(ScriptAttributeUtility.s_DrawerTypeForType[current2].type)) + { + ScriptAttributeUtility.s_DrawerTypeForType[current2] = new ScriptAttributeUtility.DrawerKeySet + { + drawer = current, + type = editor.m_Type + }; + } + } + } + } + } + } + internal static Type GetDrawerTypeForType(Type type) + { + if (ScriptAttributeUtility.s_DrawerTypeForType == null) + { + ScriptAttributeUtility.BuildDrawerTypeForTypeDictionary(); + } + ScriptAttributeUtility.DrawerKeySet drawerKeySet; + ScriptAttributeUtility.s_DrawerTypeForType.TryGetValue(type, out drawerKeySet); + if (drawerKeySet.drawer != null) + { + return drawerKeySet.drawer; + } + if (type.IsGenericType) + { + ScriptAttributeUtility.s_DrawerTypeForType.TryGetValue(type.GetGenericTypeDefinition(), out drawerKeySet); + } + return drawerKeySet.drawer; + } + private static List GetFieldAttributes(FieldInfo field) + { + if (field == null) + { + return null; + } + object[] customAttributes = field.GetCustomAttributes(typeof(PropertyAttribute), true); + if (customAttributes != null && customAttributes.Length > 0) + { + return new List( + from e in customAttributes + select e as PropertyAttribute into e + orderby -e.order + select e); + } + return null; + } + private static FieldInfo GetFieldInfoFromProperty(SerializedProperty property, out Type type) + { + Type scriptTypeFromProperty = ScriptAttributeUtility.GetScriptTypeFromProperty(property); + if (scriptTypeFromProperty == null) + { + type = null; + return null; + } + return ScriptAttributeUtility.GetFieldInfoFromPropertyPath(scriptTypeFromProperty, property.propertyPath, out type); + } + private static Type GetScriptTypeFromProperty(SerializedProperty property) + { + SerializedProperty serializedProperty = property.serializedObject.FindProperty("m_Script"); + if (serializedProperty == null) + { + return null; + } + MonoScript monoScript = serializedProperty.objectReferenceValue as MonoScript; + if (monoScript == null) + { + return null; + } + return monoScript.GetClass(); + } + private static FieldInfo GetFieldInfoFromPropertyPath(Type host, string path, out Type type) + { + FieldInfo fieldInfo = null; + type = host; + string[] array = path.Split(new char[] + { + '.' + }); + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + if (i < array.Length - 1 && text == "Array" && array[i + 1].StartsWith("data[")) + { + if (type.IsArrayOrList()) + { + type = type.GetArrayOrListElementType(); + } + i++; + } + else + { + FieldInfo fieldInfo2 = null; + Type type2 = type; + while (fieldInfo2 == null && type2 != null) + { + fieldInfo2 = type2.GetField(text, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + type2 = type2.BaseType; + } + if (fieldInfo2 == null) + { + type = null; + return null; + } + fieldInfo = fieldInfo2; + type = fieldInfo.FieldType; + } + } + return fieldInfo; + } + internal static PropertyHandler GetHandler(SerializedProperty property) + { + if (property == null) + { + return ScriptAttributeUtility.s_SharedNullHandler; + } + if (property.serializedObject.inspectorMode != InspectorMode.Normal) + { + return ScriptAttributeUtility.s_SharedNullHandler; + } + PropertyHandler handler = ScriptAttributeUtility.propertyHandlerCache.GetHandler(property); + if (handler != null) + { + return handler; + } + Type type = null; + List list = null; + FieldInfo field = null; + UnityEngine.Object targetObject = property.serializedObject.targetObject; + if (targetObject is MonoBehaviour || targetObject is ScriptableObject) + { + field = ScriptAttributeUtility.GetFieldInfoFromProperty(property, out type); + list = ScriptAttributeUtility.GetFieldAttributes(field); + } + else + { + if (ScriptAttributeUtility.s_BuiltinAttributes == null) + { + ScriptAttributeUtility.PopulateBuiltinAttributes(); + } + if (list == null) + { + list = ScriptAttributeUtility.GetBuiltinAttributes(property); + } + } + handler = ScriptAttributeUtility.s_NextHandler; + if (list != null) + { + for (int i = list.Count - 1; i >= 0; i--) + { + handler.HandleAttribute(list[i], field, type); + } + } + if (!handler.hasPropertyDrawer && type != null) + { + handler.HandleDrawnType(type, type, field, null); + } + if (handler.empty) + { + ScriptAttributeUtility.propertyHandlerCache.SetHandler(property, ScriptAttributeUtility.s_SharedNullHandler); + handler = ScriptAttributeUtility.s_SharedNullHandler; + } + else + { + ScriptAttributeUtility.propertyHandlerCache.SetHandler(property, handler); + ScriptAttributeUtility.s_NextHandler = new PropertyHandler(); + } + return handler; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptCallOptimizationLevel.cs b/UnityEditor/UnityEditor/ScriptCallOptimizationLevel.cs new file mode 100644 index 00000000..d32f2cbe --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptCallOptimizationLevel.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum ScriptCallOptimizationLevel + { + SlowAndSafe, + FastButNoExceptions + } +} diff --git a/UnityEditor/UnityEditor/ScriptExecutionOrderInspector.cs b/UnityEditor/UnityEditor/ScriptExecutionOrderInspector.cs new file mode 100644 index 00000000..1c08fa27 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptExecutionOrderInspector.cs @@ -0,0 +1,652 @@ +using System; +using System.Collections.Generic; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(MonoManager))] + internal class ScriptExecutionOrderInspector : Editor + { + public class SortMonoScriptExecutionOrder : IComparer + { + private ScriptExecutionOrderInspector inspector; + public SortMonoScriptExecutionOrder(ScriptExecutionOrderInspector inspector) + { + this.inspector = inspector; + } + public int Compare(MonoScript x, MonoScript y) + { + if (!(x != null) || !(y != null)) + { + return -1; + } + int executionOrder = this.inspector.GetExecutionOrder(x); + int executionOrder2 = this.inspector.GetExecutionOrder(y); + if (executionOrder == executionOrder2) + { + return x.name.CompareTo(y.name); + } + return executionOrder.CompareTo(executionOrder2); + } + } + public class SortMonoScriptNameOrder : IComparer + { + public int Compare(MonoScript x, MonoScript y) + { + if (x != null && y != null) + { + return x.name.CompareTo(y.name); + } + return -1; + } + } + public class Styles + { + public GUIContent helpText = EditorGUIUtility.TextContent("ScriptExecutionOrderInspector.HelpText"); + public GUIContent iconToolbarPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add script to custom order"); + public GUIContent iconToolbarMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove script from custom order"); + public GUIContent defaultTimeContent = EditorGUIUtility.TextContent("ScriptExecutionOrderInspector.DefaultTime"); + public GUIStyle toolbar = "TE Toolbar"; + public GUIStyle toolbarDropDown = "TE ToolbarDropDown"; + public GUIStyle boxBackground = "TE NodeBackground"; + public GUIStyle removeButton = "InvisibleButton"; + public GUIStyle elementBackground = new GUIStyle("OL Box"); + public GUIStyle defaultTime = new GUIStyle(EditorStyles.inspectorBig); + public GUIStyle draggingHandle = "WindowBottomResize"; + public GUIStyle dropField = new GUIStyle(EditorStyles.objectFieldThumb); + public Styles() + { + this.boxBackground.margin = new RectOffset(); + this.boxBackground.padding = new RectOffset(1, 1, 1, 0); + this.elementBackground.overflow = new RectOffset(1, 1, 1, 0); + this.defaultTime.alignment = TextAnchor.MiddleCenter; + this.defaultTime.overflow = new RectOffset(0, 0, 1, 0); + this.dropField.overflow = new RectOffset(2, 2, 2, 2); + this.dropField.normal.background = null; + this.dropField.hover.background = null; + this.dropField.active.background = null; + this.dropField.focused.background = null; + } + } + private class DragReorderGUI + { + public delegate void DrawElementDelegate(Rect r, object obj, bool dragging); + private static int s_ReorderingDraggedElement; + private static float[] s_ReorderingPositions; + private static int[] s_ReorderingGoals; + private static int s_DragReorderGUIHash = "DragReorderGUI".GetHashCode(); + private static bool IsDefaultTimeElement(MonoScript element) + { + return element.name == string.Empty; + } + public static int DragReorder(Rect position, int elementHeight, List elements, ScriptExecutionOrderInspector.DragReorderGUI.DrawElementDelegate drawElementDelegate) + { + int controlID = GUIUtility.GetControlID(ScriptExecutionOrderInspector.DragReorderGUI.s_DragReorderGUIHash, FocusType.Passive); + Rect r = position; + r.height = (float)elementHeight; + int num = 0; + Rect position2; + if (GUIUtility.hotControl == controlID && Event.current.type == EventType.Repaint) + { + for (int i = 0; i < elements.Count; i++) + { + if (i != ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement) + { + if (ScriptExecutionOrderInspector.DragReorderGUI.IsDefaultTimeElement(elements[i])) + { + num = i; + i++; + } + else + { + r.y = position.y + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[i] * (float)elementHeight; + drawElementDelegate(r, elements[i], false); + } + } + } + position2 = new Rect(r.x, position.y + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[num] * (float)elementHeight, r.width, (ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[num + 1] - ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[num] + 1f) * (float)elementHeight); + } + else + { + for (int j = 0; j < elements.Count; j++) + { + r.y = position.y + (float)(j * elementHeight); + if (ScriptExecutionOrderInspector.DragReorderGUI.IsDefaultTimeElement(elements[j])) + { + num = j; + j++; + } + else + { + drawElementDelegate(r, elements[j], false); + } + } + position2 = new Rect(r.x, position.y + (float)(num * elementHeight), r.width, (float)(elementHeight * 2)); + } + GUI.Label(position2, ScriptExecutionOrderInspector.m_Styles.defaultTimeContent, ScriptExecutionOrderInspector.m_Styles.defaultTime); + bool flag = position2.height > (float)elementHeight * 2.5f; + if (GUIUtility.hotControl == controlID) + { + if (flag) + { + GUI.color = new Color(1f, 1f, 1f, 0.5f); + } + r.y = position.y + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement] * (float)elementHeight; + drawElementDelegate(r, elements[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement], true); + GUI.color = Color.white; + } + int result = -1; + switch (Event.current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = 0; + EditorGUI.EndEditingActiveTextField(); + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement = Mathf.FloorToInt((Event.current.mousePosition.y - position.y) / (float)elementHeight); + if (!ScriptExecutionOrderInspector.DragReorderGUI.IsDefaultTimeElement(elements[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement])) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions = new float[elements.Count]; + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals = new int[elements.Count]; + for (int k = 0; k < elements.Count; k++) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[k] = k; + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[k] = (float)k; + } + GUIUtility.hotControl = controlID; + Event.current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + if (ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement] != ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement) + { + List list = new List(elements); + for (int l = 0; l < elements.Count; l++) + { + elements[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[l]] = list[l]; + } + result = ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement]; + } + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals = null; + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions = null; + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement = -1; + GUIUtility.hotControl = 0; + Event.current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement] = (Event.current.mousePosition.y - position.y) / (float)elementHeight - 0.5f; + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement] = Mathf.Clamp(ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement], 0f, (float)(elements.Count - 1)); + int num2 = Mathf.RoundToInt(ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement]); + if (num2 != ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement]) + { + for (int m = 0; m < elements.Count; m++) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[m] = m; + } + int num3 = (num2 <= ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement) ? 1 : -1; + for (int num4 = ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement; num4 != num2; num4 -= num3) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[num4 - num3] = num4; + } + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement] = num2; + } + Event.current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == controlID) + { + for (int n = 0; n < elements.Count; n++) + { + if (n != ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingDraggedElement) + { + ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[n] = Mathf.MoveTowards(ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingPositions[n], (float)ScriptExecutionOrderInspector.DragReorderGUI.s_ReorderingGoals[n], 0.075f); + } + } + GUIView.current.Repaint(); + } + break; + } + return result; + } + } + private const int kOrderRangeMin = -32000; + private const int kOrderRangeMax = 32000; + private const int kListElementHeight = 21; + private const int kIntFieldWidth = 50; + private const int kPreferredSpacing = 100; + private const string kOrderValuesEditorPrefString = "ScriptExecutionOrderShowOrderValues"; + private int[] kRoundingAmounts = new int[] + { + 1000, + 500, + 100, + 50, + 10, + 5, + 1 + }; + private MonoScript m_Edited; + private List m_CustomTimeScripts; + private List m_DefaultTimeScripts; + private static MonoScript sDummyScript; + private Vector2 m_Scroll = Vector2.zero; + private MonoScript[] m_AllScripts; + private int[] m_AllOrders; + private bool m_DirtyOrders; + private static int s_DropFieldHash = "DropField".GetHashCode(); + public static ScriptExecutionOrderInspector.Styles m_Styles; + public void OnEnable() + { + if (ScriptExecutionOrderInspector.sDummyScript == null) + { + ScriptExecutionOrderInspector.sDummyScript = new MonoScript(); + } + if (this.m_AllScripts == null || !this.m_DirtyOrders) + { + this.PopulateScriptArray(); + } + } + private static UnityEngine.Object MonoScriptValidatorCallback(UnityEngine.Object[] references, Type objType, SerializedProperty property) + { + for (int i = 0; i < references.Length; i++) + { + UnityEngine.Object @object = references[i]; + MonoScript monoScript = @object as MonoScript; + if (monoScript != null && ScriptExecutionOrderInspector.IsValidScript(monoScript)) + { + return monoScript; + } + } + return null; + } + private static bool IsValidScript(MonoScript script) + { + if (script == null) + { + return false; + } + if (script.GetClass() == null) + { + return false; + } + bool flag = typeof(MonoBehaviour).IsAssignableFrom(script.GetClass()); + bool flag2 = typeof(ScriptableObject).IsAssignableFrom(script.GetClass()); + return (flag || flag2) && AssetDatabase.GetAssetPath(script).IndexOf("Assets/") == 0; + } + private void PopulateScriptArray() + { + this.m_AllScripts = MonoImporter.GetAllRuntimeMonoScripts(); + this.m_AllOrders = new int[this.m_AllScripts.Length]; + this.m_CustomTimeScripts = new List(); + this.m_DefaultTimeScripts = new List(); + for (int i = 0; i < this.m_AllScripts.Length; i++) + { + MonoScript monoScript = this.m_AllScripts[i]; + this.m_AllOrders[i] = MonoImporter.GetExecutionOrder(monoScript); + if (ScriptExecutionOrderInspector.IsValidScript(monoScript)) + { + if (this.GetExecutionOrder(monoScript) == 0) + { + this.m_DefaultTimeScripts.Add(monoScript); + } + else + { + this.m_CustomTimeScripts.Add(monoScript); + } + } + } + this.m_CustomTimeScripts.Add(ScriptExecutionOrderInspector.sDummyScript); + this.m_CustomTimeScripts.Add(ScriptExecutionOrderInspector.sDummyScript); + this.m_CustomTimeScripts.Sort(new ScriptExecutionOrderInspector.SortMonoScriptExecutionOrder(this)); + this.m_DefaultTimeScripts.Sort(new ScriptExecutionOrderInspector.SortMonoScriptNameOrder()); + this.m_Edited = null; + this.m_DirtyOrders = false; + } + private int GetExecutionOrder(MonoScript script) + { + int num = Array.IndexOf(this.m_AllScripts, script); + if (num >= 0) + { + return this.m_AllOrders[num]; + } + return 0; + } + private void SetExecutionOrder(MonoScript script, int order) + { + int num = Array.IndexOf(this.m_AllScripts, script); + if (num >= 0) + { + this.m_AllOrders[num] = Mathf.Clamp(order, -32000, 32000); + this.m_DirtyOrders = true; + } + } + private void Apply() + { + List list = new List(); + List list2 = new List(); + for (int i = 0; i < this.m_AllScripts.Length; i++) + { + if (MonoImporter.GetExecutionOrder(this.m_AllScripts[i]) != this.m_AllOrders[i]) + { + list.Add(i); + list2.Add(this.m_AllScripts[i]); + } + } + bool flag = true; + if (Provider.enabled) + { + Task task = Provider.Checkout(list2.ToArray(), CheckoutMode.Both); + task.SetCompletionAction(CompletionAction.UpdatePendingWindow); + task.Wait(); + flag = task.success; + } + if (flag) + { + foreach (int current in list) + { + MonoImporter.SetExecutionOrder(this.m_AllScripts[current], this.m_AllOrders[current]); + } + this.PopulateScriptArray(); + } + else + { + Debug.LogError("Could not checkout scrips in version control for changing script execution order"); + } + } + private void Revert() + { + this.PopulateScriptArray(); + } + private void OnDestroy() + { + if (this.m_DirtyOrders && EditorUtility.DisplayDialog("Unapplied execution order", "Unapplied script execution order", "Apply", "Revert")) + { + this.Apply(); + } + } + private void ApplyRevertGUI() + { + EditorGUILayout.Space(); + bool enabled = GUI.enabled; + GUI.enabled = this.m_DirtyOrders; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Revert", new GUILayoutOption[0])) + { + this.Revert(); + } + if (GUILayout.Button("Apply", new GUILayoutOption[0])) + { + this.Apply(); + } + GUILayout.EndHorizontal(); + GUI.enabled = enabled; + } + private void MenuSelection(object userData, string[] options, int selected) + { + this.AddScriptToCustomOrder(this.m_DefaultTimeScripts[selected]); + } + private void AddScriptToCustomOrder(MonoScript script) + { + if (!ScriptExecutionOrderInspector.IsValidScript(script)) + { + return; + } + if (this.m_CustomTimeScripts.Contains(script)) + { + return; + } + int order = this.RoundByAmount(this.GetExecutionOrderAtIndex(this.m_CustomTimeScripts.Count - 1) + 100, 100); + this.SetExecutionOrder(script, order); + this.m_CustomTimeScripts.Add(script); + this.m_DefaultTimeScripts.Remove(script); + } + private void ShowScriptPopup(Rect r) + { + int count = this.m_DefaultTimeScripts.Count; + string[] array = new string[count]; + bool[] array2 = new bool[count]; + for (int i = 0; i < count; i++) + { + array[i] = this.m_DefaultTimeScripts[i].GetClass().FullName; + array2[i] = true; + } + EditorUtility.DisplayCustomMenu(r, array, array2, null, new EditorUtility.SelectMenuItemFunction(this.MenuSelection), null); + } + private int RoundBasedOnContext(int val, int lowerBound, int upperBound) + { + int num = Mathf.Max(0, (upperBound - lowerBound) / 6); + lowerBound += num; + upperBound -= num; + for (int i = 0; i < this.kRoundingAmounts.Length; i++) + { + int num2 = this.RoundByAmount(val, this.kRoundingAmounts[i]); + if (num2 > lowerBound && num2 < upperBound) + { + return num2; + } + } + return val; + } + private int RoundByAmount(int val, int rounding) + { + return Mathf.RoundToInt((float)val / (float)rounding) * rounding; + } + private int GetAverageRoundedAwayFromZero(int a, int b) + { + if ((a + b) % 2 == 0) + { + return (a + b) / 2; + } + return (a + b + Math.Sign(a + b)) / 2; + } + private void SetExecutionOrderAtIndexAccordingToNeighbors(int indexOfChangedItem, int pushDirection) + { + if (indexOfChangedItem < 0 || indexOfChangedItem >= this.m_CustomTimeScripts.Count) + { + return; + } + if (indexOfChangedItem == 0) + { + this.SetExecutionOrderAtIndex(indexOfChangedItem, this.RoundByAmount(this.GetExecutionOrderAtIndex(indexOfChangedItem + 1) - 100, 100)); + return; + } + if (indexOfChangedItem == this.m_CustomTimeScripts.Count - 1) + { + this.SetExecutionOrderAtIndex(indexOfChangedItem, this.RoundByAmount(this.GetExecutionOrderAtIndex(indexOfChangedItem - 1) + 100, 100)); + return; + } + int executionOrderAtIndex = this.GetExecutionOrderAtIndex(indexOfChangedItem - 1); + int executionOrderAtIndex2 = this.GetExecutionOrderAtIndex(indexOfChangedItem + 1); + int num = this.RoundBasedOnContext(this.GetAverageRoundedAwayFromZero(executionOrderAtIndex, executionOrderAtIndex2), executionOrderAtIndex, executionOrderAtIndex2); + if (num != 0) + { + if (pushDirection == 0) + { + pushDirection = this.GetBestPushDirectionForOrderValue(num); + } + if (pushDirection > 0) + { + num = Mathf.Max(num, executionOrderAtIndex + 1); + } + else + { + num = Mathf.Min(num, executionOrderAtIndex2 - 1); + } + } + this.SetExecutionOrderAtIndex(indexOfChangedItem, num); + } + private void UpdateOrder(MonoScript changedScript) + { + this.m_CustomTimeScripts.Remove(changedScript); + int executionOrder = this.GetExecutionOrder(changedScript); + if (executionOrder == 0) + { + this.m_DefaultTimeScripts.Add(changedScript); + this.m_DefaultTimeScripts.Sort(new ScriptExecutionOrderInspector.SortMonoScriptNameOrder()); + return; + } + int num = -1; + for (int i = 0; i < this.m_CustomTimeScripts.Count; i++) + { + if (this.GetExecutionOrderAtIndex(i) == executionOrder) + { + num = i; + break; + } + } + if (num == -1) + { + this.m_CustomTimeScripts.Add(changedScript); + this.m_CustomTimeScripts.Sort(new ScriptExecutionOrderInspector.SortMonoScriptExecutionOrder(this)); + return; + } + int bestPushDirectionForOrderValue = this.GetBestPushDirectionForOrderValue(executionOrder); + if (bestPushDirectionForOrderValue == 1) + { + this.m_CustomTimeScripts.Insert(num, changedScript); + num++; + } + else + { + this.m_CustomTimeScripts.Insert(num + 1, changedScript); + } + this.PushAwayToAvoidConflicts(num, bestPushDirectionForOrderValue); + } + private void PushAwayToAvoidConflicts(int startIndex, int pushDirection) + { + int num = startIndex; + while (num >= 0 && num < this.m_CustomTimeScripts.Count) + { + if ((this.GetExecutionOrderAtIndex(num) - this.GetExecutionOrderAtIndex(num - pushDirection)) * pushDirection >= 1) + { + break; + } + this.SetExecutionOrderAtIndexAccordingToNeighbors(num, pushDirection); + num += pushDirection; + } + } + private int GetBestPushDirectionForOrderValue(int order) + { + int num = (int)Mathf.Sign((float)order); + if (order < -16000 || order > 16000) + { + num = -num; + } + return num; + } + public override bool UseDefaultMargins() + { + return false; + } + public override void OnInspectorGUI() + { + if (ScriptExecutionOrderInspector.m_Styles == null) + { + ScriptExecutionOrderInspector.m_Styles = new ScriptExecutionOrderInspector.Styles(); + } + if (this.m_Edited) + { + this.UpdateOrder(this.m_Edited); + this.m_Edited = null; + } + EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins, new GUILayoutOption[0]); + GUILayout.Label(ScriptExecutionOrderInspector.m_Styles.helpText, EditorStyles.helpBox, new GUILayoutOption[0]); + EditorGUILayout.Space(); + Rect position = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + int controlID = GUIUtility.GetControlID(ScriptExecutionOrderInspector.s_DropFieldHash, FocusType.Passive, position); + MonoScript monoScript = EditorGUI.DoDropField(position, controlID, typeof(MonoScript), new EditorGUI.ObjectFieldValidator(ScriptExecutionOrderInspector.MonoScriptValidatorCallback), false, ScriptExecutionOrderInspector.m_Styles.dropField) as MonoScript; + if (monoScript) + { + this.AddScriptToCustomOrder(monoScript); + } + EditorGUILayout.BeginVertical(ScriptExecutionOrderInspector.m_Styles.boxBackground, new GUILayoutOption[0]); + this.m_Scroll = EditorGUILayout.BeginVerticalScrollView(this.m_Scroll, new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(10f, (float)(21 * this.m_CustomTimeScripts.Count), new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + int num = ScriptExecutionOrderInspector.DragReorderGUI.DragReorder(rect, 21, this.m_CustomTimeScripts, new ScriptExecutionOrderInspector.DragReorderGUI.DrawElementDelegate(this.DrawElement)); + if (num >= 0) + { + this.SetExecutionOrderAtIndexAccordingToNeighbors(num, 0); + this.UpdateOrder(this.m_CustomTimeScripts[num]); + this.SetExecutionOrderAtIndexAccordingToNeighbors(num, 0); + } + EditorGUILayout.EndScrollView(); + EditorGUILayout.EndVertical(); + GUILayout.BeginHorizontal(ScriptExecutionOrderInspector.m_Styles.toolbar, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUIContent iconToolbarPlus = ScriptExecutionOrderInspector.m_Styles.iconToolbarPlus; + Rect rect2 = GUILayoutUtility.GetRect(iconToolbarPlus, ScriptExecutionOrderInspector.m_Styles.toolbarDropDown); + if (EditorGUI.ButtonMouseDown(rect2, iconToolbarPlus, FocusType.Native, ScriptExecutionOrderInspector.m_Styles.toolbarDropDown)) + { + this.ShowScriptPopup(rect2); + } + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + this.ApplyRevertGUI(); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + } + private int GetExecutionOrderAtIndex(int idx) + { + return this.GetExecutionOrder(this.m_CustomTimeScripts[idx]); + } + private void SetExecutionOrderAtIndex(int idx, int order) + { + this.SetExecutionOrder(this.m_CustomTimeScripts[idx], order); + } + private Rect GetButtonLabelRect(Rect r) + { + return new Rect(r.x + 20f, r.y + 1f, r.width - this.GetMinusButtonSize().x - 10f - 20f - 55f, r.height); + } + private Rect GetAddRemoveButtonRect(Rect r) + { + Vector2 minusButtonSize = this.GetMinusButtonSize(); + return new Rect(r.xMax - minusButtonSize.x - 5f, r.y + 1f, minusButtonSize.x, minusButtonSize.y); + } + private Rect GetFieldRect(Rect r) + { + return new Rect(r.xMax - 50f - this.GetMinusButtonSize().x - 10f, r.y + 2f, 50f, r.height - 5f); + } + private Vector2 GetMinusButtonSize() + { + return ScriptExecutionOrderInspector.m_Styles.removeButton.CalcSize(ScriptExecutionOrderInspector.m_Styles.iconToolbarMinus); + } + private Rect GetDraggingHandleRect(Rect r) + { + return new Rect(r.x + 5f, r.y + 7f, 10f, r.height - 14f); + } + public void DrawElement(Rect r, object obj, bool dragging) + { + MonoScript monoScript = obj as MonoScript; + if (Event.current.type == EventType.Repaint) + { + ScriptExecutionOrderInspector.m_Styles.elementBackground.Draw(r, false, false, false, false); + ScriptExecutionOrderInspector.m_Styles.draggingHandle.Draw(this.GetDraggingHandleRect(r), false, false, false, false); + } + GUI.Label(this.GetButtonLabelRect(r), monoScript.GetClass().FullName); + int executionOrder = this.GetExecutionOrder(monoScript); + string s = EditorGUI.DelayedTextField(this.GetFieldRect(r), executionOrder.ToString(), "0123456789-", EditorStyles.textField); + int num = executionOrder; + if (int.TryParse(s, out num) && num != executionOrder) + { + this.SetExecutionOrder(monoScript, num); + this.m_Edited = monoScript; + } + if (GUI.Button(this.GetAddRemoveButtonRect(r), ScriptExecutionOrderInspector.m_Styles.iconToolbarMinus, ScriptExecutionOrderInspector.m_Styles.removeButton)) + { + this.SetExecutionOrder(monoScript, 0); + this.m_Edited = monoScript; + } + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptReloadProperties.cs b/UnityEditor/UnityEditor/ScriptReloadProperties.cs new file mode 100644 index 00000000..9b0099a2 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptReloadProperties.cs @@ -0,0 +1,82 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class ScriptReloadProperties : ScriptableObject + { + public bool EditorGUI_IsActuallEditing; + public int EditorGUI_TextEditor_pos; + public int EditorGUI_TextEditor_selectPos; + public int EditorGUI_TextEditor_controlID; + public bool EditorGUI_TextEditor_hasHorizontalCursorPos; + public Vector2 EditorGUI_TextEditor_scrollOffset; + public bool EditorGUI_TextEditor_hasFocus; + public Vector2 EditorGUI_TextEditor_graphicalCursorPos; + public string EditorGUI_TextEditor_content; + public string EditorGUI_Current_Editing_String; + public int EditorGUI_DelayedTextEditor_pos; + public int EditorGUI_DelayedTextEditor_selectPos; + public int EditorGUI_DelayedTextEditor_controlID; + public bool EditorGUI_DelayedTextEditor_hasHorizontalCursorPos; + public Vector2 EditorGUI_DelayedTextEditor_scrollOffset; + public bool EditorGUI_DelayedTextEditor_hasFocus; + public Vector2 EditorGUI_DelayedTextEditor_graphicalCursorPos; + public string EditorGUI_DelayedTextEditor_content; + public string EditorGUI_DelayedControlThatHadFocusValue; + private static ScriptReloadProperties Store() + { + ScriptReloadProperties scriptReloadProperties = ScriptableObject.CreateInstance(); + scriptReloadProperties.hideFlags = HideFlags.HideAndDontSave; + scriptReloadProperties.ManagedStore(); + return scriptReloadProperties; + } + private static void Load(ScriptReloadProperties properties) + { + properties.ManagedLoad(); + } + private void ManagedStore() + { + this.EditorGUI_IsActuallEditing = EditorGUI.RecycledTextEditor.s_ActuallyEditing; + this.EditorGUI_TextEditor_pos = EditorGUI.s_RecycledEditor.pos; + this.EditorGUI_TextEditor_selectPos = EditorGUI.s_RecycledEditor.selectPos; + this.EditorGUI_TextEditor_controlID = EditorGUI.s_RecycledEditor.controlID; + this.EditorGUI_TextEditor_hasHorizontalCursorPos = EditorGUI.s_RecycledEditor.hasHorizontalCursorPos; + this.EditorGUI_TextEditor_scrollOffset = EditorGUI.s_RecycledEditor.scrollOffset; + this.EditorGUI_TextEditor_hasFocus = EditorGUI.s_RecycledEditor.m_HasFocus; + this.EditorGUI_TextEditor_graphicalCursorPos = EditorGUI.s_RecycledEditor.graphicalCursorPos; + this.EditorGUI_TextEditor_content = EditorGUI.s_RecycledEditor.content.text; + this.EditorGUI_Current_Editing_String = EditorGUI.s_RecycledCurrentEditingString; + this.EditorGUI_DelayedTextEditor_pos = EditorGUI.s_DelayedTextEditor.pos; + this.EditorGUI_DelayedTextEditor_selectPos = EditorGUI.s_DelayedTextEditor.selectPos; + this.EditorGUI_DelayedTextEditor_controlID = EditorGUI.s_DelayedTextEditor.controlID; + this.EditorGUI_DelayedTextEditor_hasHorizontalCursorPos = EditorGUI.s_DelayedTextEditor.hasHorizontalCursorPos; + this.EditorGUI_DelayedTextEditor_scrollOffset = EditorGUI.s_DelayedTextEditor.scrollOffset; + this.EditorGUI_DelayedTextEditor_hasFocus = EditorGUI.s_DelayedTextEditor.m_HasFocus; + this.EditorGUI_DelayedTextEditor_graphicalCursorPos = EditorGUI.s_DelayedTextEditor.graphicalCursorPos; + this.EditorGUI_DelayedTextEditor_content = EditorGUI.s_DelayedTextEditor.content.text; + this.EditorGUI_DelayedControlThatHadFocusValue = EditorGUI.s_DelayedTextEditor.controlThatHadFocusValue; + } + private void ManagedLoad() + { + EditorGUI.RecycledTextEditor.s_ActuallyEditing = this.EditorGUI_IsActuallEditing; + EditorGUI.s_RecycledEditor.pos = this.EditorGUI_TextEditor_pos; + EditorGUI.s_RecycledEditor.selectPos = this.EditorGUI_TextEditor_selectPos; + EditorGUI.s_RecycledEditor.controlID = this.EditorGUI_TextEditor_controlID; + EditorGUI.s_RecycledEditor.hasHorizontalCursorPos = this.EditorGUI_TextEditor_hasHorizontalCursorPos; + EditorGUI.s_RecycledEditor.scrollOffset = this.EditorGUI_TextEditor_scrollOffset; + EditorGUI.s_RecycledEditor.m_HasFocus = this.EditorGUI_TextEditor_hasFocus; + EditorGUI.s_RecycledEditor.graphicalCursorPos = this.EditorGUI_TextEditor_graphicalCursorPos; + EditorGUI.s_RecycledEditor.content.text = this.EditorGUI_TextEditor_content; + EditorGUI.s_RecycledCurrentEditingString = this.EditorGUI_Current_Editing_String; + EditorGUI.s_DelayedTextEditor.pos = this.EditorGUI_DelayedTextEditor_pos; + EditorGUI.s_DelayedTextEditor.selectPos = this.EditorGUI_DelayedTextEditor_selectPos; + EditorGUI.s_DelayedTextEditor.controlID = this.EditorGUI_DelayedTextEditor_controlID; + EditorGUI.s_DelayedTextEditor.hasHorizontalCursorPos = this.EditorGUI_DelayedTextEditor_hasHorizontalCursorPos; + EditorGUI.s_DelayedTextEditor.scrollOffset = this.EditorGUI_DelayedTextEditor_scrollOffset; + EditorGUI.s_DelayedTextEditor.m_HasFocus = this.EditorGUI_DelayedTextEditor_hasFocus; + EditorGUI.s_DelayedTextEditor.graphicalCursorPos = this.EditorGUI_DelayedTextEditor_graphicalCursorPos; + EditorGUI.s_DelayedTextEditor.content.text = this.EditorGUI_DelayedTextEditor_content; + EditorGUI.s_DelayedTextEditor.controlThatHadFocusValue = this.EditorGUI_DelayedControlThatHadFocusValue; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptableObjectSaveLoadHelper.cs b/UnityEditor/UnityEditor/ScriptableObjectSaveLoadHelper.cs new file mode 100644 index 00000000..fc5e1ef9 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptableObjectSaveLoadHelper.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class ScriptableObjectSaveLoadHelper where T : ScriptableObject + { + public string fileExtensionWithoutDot + { + get; + private set; + } + private SaveType saveType + { + get; + set; + } + public ScriptableObjectSaveLoadHelper(string fileExtensionWithoutDot, SaveType saveType) + { + this.saveType = saveType; + this.fileExtensionWithoutDot = fileExtensionWithoutDot.TrimStart(new char[] + { + '.' + }); + } + public T Load(string filePath) + { + filePath = this.AppendFileExtensionIfNeeded(filePath); + if (!string.IsNullOrEmpty(filePath)) + { + UnityEngine.Object[] array = InternalEditorUtility.LoadSerializedFileAndForget(filePath); + if (array != null && array.Length > 0) + { + return array[0] as T; + } + } + return (T)((object)null); + } + public T Create() + { + return ScriptableObject.CreateInstance(); + } + public void Save(T t, string filePath) + { + if (t == null) + { + Debug.LogError("Cannot save scriptableObject: its null!"); + return; + } + if (string.IsNullOrEmpty(filePath)) + { + Debug.LogError("Invalid path: '" + filePath + "'"); + return; + } + string directoryName = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + filePath = this.AppendFileExtensionIfNeeded(filePath); + InternalEditorUtility.SaveToSerializedFileAndForget(new T[] + { + t + }, filePath, this.saveType == SaveType.Text); + } + public override string ToString() + { + return string.Format("{0}, {1}, {2}", this.fileExtensionWithoutDot, this.saveType); + } + private string AppendFileExtensionIfNeeded(string path) + { + if (!Path.HasExtension(path) && !string.IsNullOrEmpty(this.fileExtensionWithoutDot)) + { + return path + "." + this.fileExtensionWithoutDot; + } + return path; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptableSingleton.cs b/UnityEditor/UnityEditor/ScriptableSingleton.cs new file mode 100644 index 00000000..a8fb7072 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptableSingleton.cs @@ -0,0 +1,87 @@ +using NUnit.Framework; +using System; +using System.IO; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public class ScriptableSingleton : ScriptableObject where T : ScriptableObject + { + private static T s_Instance; + public static T instance + { + get + { + if (ScriptableSingleton.s_Instance == null) + { + ScriptableSingleton.CreateAndLoad(); + } + return ScriptableSingleton.s_Instance; + } + } + protected ScriptableSingleton() + { + if (ScriptableSingleton.s_Instance != null) + { + Debug.LogError("ScriptableSingleton already exists. Did you query the singleton in a constructor?"); + } + else + { + ScriptableSingleton.s_Instance = (this as T); + Assert.That(ScriptableSingleton.s_Instance != null); + } + } + private static void CreateAndLoad() + { + Assert.That(ScriptableSingleton.s_Instance == null); + string filePath = ScriptableSingleton.GetFilePath(); + if (!string.IsNullOrEmpty(filePath)) + { + InternalEditorUtility.LoadSerializedFileAndForget(filePath); + } + if (ScriptableSingleton.s_Instance == null) + { + T t = ScriptableObject.CreateInstance(); + t.hideFlags = HideFlags.HideAndDontSave; + } + Assert.That(ScriptableSingleton.s_Instance != null); + } + protected virtual void Save(bool saveAsText) + { + if (ScriptableSingleton.s_Instance == null) + { + Debug.Log("Cannot save ScriptableSingleton: no instance!"); + return; + } + string filePath = ScriptableSingleton.GetFilePath(); + if (!string.IsNullOrEmpty(filePath)) + { + string directoryName = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directoryName)) + { + Directory.CreateDirectory(directoryName); + } + InternalEditorUtility.SaveToSerializedFileAndForget(new T[] + { + ScriptableSingleton.s_Instance + }, filePath, saveAsText); + } + } + private static string GetFilePath() + { + Type typeFromHandle = typeof(T); + object[] customAttributes = typeFromHandle.GetCustomAttributes(true); + object[] array = customAttributes; + for (int i = 0; i < array.Length; i++) + { + object obj = array[i]; + if (obj is FilePathAttribute) + { + FilePathAttribute filePathAttribute = obj as FilePathAttribute; + return filePathAttribute.filepath; + } + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptableWizard.cs b/UnityEditor/UnityEditor/ScriptableWizard.cs new file mode 100644 index 00000000..35c44536 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptableWizard.cs @@ -0,0 +1,207 @@ +using System; +using System.Reflection; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + public class ScriptableWizard : EditorWindow + { + private sealed class Styles + { + public static string errorText = "Wizard Error"; + public static string box = "Wizard Box"; + } + private GenericInspector m_Inspector; + private string m_HelpString = string.Empty; + private string m_ErrorString = string.Empty; + private bool m_IsValid = true; + private Vector2 m_ScrollPosition; + private string m_CreateButton = "Create"; + private string m_OtherButton = string.Empty; + public string helpString + { + get + { + return this.m_HelpString; + } + set + { + if (this.m_HelpString != value) + { + base.Repaint(); + } + if (this.m_HelpString != null) + { + this.m_HelpString = value; + } + else + { + this.m_HelpString = string.Empty; + } + } + } + public string errorString + { + get + { + return this.m_ErrorString; + } + set + { + if (this.m_ErrorString != value) + { + base.Repaint(); + } + if (this.m_ErrorString != null) + { + this.m_ErrorString = value; + } + else + { + this.m_ErrorString = string.Empty; + } + } + } + public bool isValid + { + get + { + return this.m_IsValid; + } + set + { + this.m_IsValid = value; + } + } + private void OnDestroy() + { + UnityEngine.Object.DestroyImmediate(this.m_Inspector); + } + private void InvokeWizardUpdate() + { + MethodInfo method = base.GetType().GetMethod("OnWizardUpdate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method != null) + { + method.Invoke(this, null); + } + } + private void OnGUI() + { + EditorGUIUtility.labelWidth = 150f; + GUILayout.Label(this.m_HelpString, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + if (this.m_Inspector == null) + { + this.m_Inspector = ScriptableObject.CreateInstance(); + this.m_Inspector.hideFlags = HideFlags.HideAndDontSave; + this.m_Inspector.InternalSetTargets(new UnityEngine.Object[] + { + this + }); + } + this.m_ScrollPosition = EditorGUILayout.BeginVerticalScrollView(this.m_ScrollPosition, false, GUI.skin.verticalScrollbar, "OL Box", new GUILayoutOption[0]); + GUIUtility.GetControlID(645789, FocusType.Passive); + bool flag = this.m_Inspector.DrawDefaultInspector(); + EditorGUILayout.EndScrollView(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (this.m_ErrorString != string.Empty) + { + GUILayout.Label(this.m_ErrorString, ScriptableWizard.Styles.errorText, new GUILayoutOption[] + { + GUILayout.MinHeight(32f) + }); + } + else + { + GUILayout.Label(string.Empty, new GUILayoutOption[] + { + GUILayout.MinHeight(32f) + }); + } + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = this.m_IsValid; + if (this.m_OtherButton != string.Empty && GUILayout.Button(this.m_OtherButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + MethodInfo method = base.GetType().GetMethod("OnWizardOtherButton", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method != null) + { + method.Invoke(this, null); + GUIUtility.ExitGUI(); + } + else + { + Debug.LogError("OnWizardOtherButton has not been implemented in script"); + } + } + if (this.m_CreateButton != string.Empty && GUILayout.Button(this.m_CreateButton, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + MethodInfo method2 = base.GetType().GetMethod("OnWizardCreate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); + if (method2 != null) + { + method2.Invoke(this, null); + } + else + { + Debug.LogError("OnWizardCreate has not been implemented in script"); + } + base.Close(); + GUIUtility.ExitGUI(); + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + if (flag) + { + this.InvokeWizardUpdate(); + } + } + public static T DisplayWizard(string title) where T : ScriptableWizard + { + return ScriptableWizard.DisplayWizard(title, "Create", string.Empty); + } + public static T DisplayWizard(string title, string createButtonName) where T : ScriptableWizard + { + return ScriptableWizard.DisplayWizard(title, createButtonName, string.Empty); + } + public static T DisplayWizard(string title, string createButtonName, string otherButtonName) where T : ScriptableWizard + { + return (T)((object)ScriptableWizard.DisplayWizard(title, typeof(T), createButtonName, otherButtonName)); + } + [ExcludeFromDocs] + public static ScriptableWizard DisplayWizard(string title, Type klass, string createButtonName) + { + string empty = string.Empty; + return ScriptableWizard.DisplayWizard(title, klass, createButtonName, empty); + } + [ExcludeFromDocs] + public static ScriptableWizard DisplayWizard(string title, Type klass) + { + string empty = string.Empty; + string createButtonName = "Create"; + return ScriptableWizard.DisplayWizard(title, klass, createButtonName, empty); + } + public static ScriptableWizard DisplayWizard(string title, Type klass, [DefaultValue("\"Create\"")] string createButtonName, [DefaultValue("\"\"")] string otherButtonName) + { + ScriptableWizard scriptableWizard = ScriptableObject.CreateInstance(klass) as ScriptableWizard; + scriptableWizard.m_CreateButton = createButtonName; + scriptableWizard.m_OtherButton = otherButtonName; + scriptableWizard.title = title; + if (scriptableWizard != null) + { + scriptableWizard.InvokeWizardUpdate(); + scriptableWizard.ShowUtility(); + } + return scriptableWizard; + } + } +} diff --git a/UnityEditor/UnityEditor/ScriptingImplementation.cs b/UnityEditor/UnityEditor/ScriptingImplementation.cs new file mode 100644 index 00000000..2d06a899 --- /dev/null +++ b/UnityEditor/UnityEditor/ScriptingImplementation.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum ScriptingImplementation + { + Mono2x, + IL2CPP, + WinRTDotNET + } +} diff --git a/UnityEditor/UnityEditor/SearchFilter.cs b/UnityEditor/UnityEditor/SearchFilter.cs new file mode 100644 index 00000000..6c0cf615 --- /dev/null +++ b/UnityEditor/UnityEditor/SearchFilter.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class SearchFilter + { + public enum SearchArea + { + AllAssets, + SelectedFolders, + AssetStore + } + public enum State + { + EmptySearchFilter, + FolderBrowsing, + SearchingInAllAssets, + SearchingInFolders, + SearchingInAssetStore + } + [SerializeField] + private string m_NameFilter = string.Empty; + [SerializeField] + private string[] m_ClassNames = new string[0]; + [SerializeField] + private string[] m_AssetLabels = new string[0]; + [SerializeField] + private int[] m_ReferencingInstanceIDs = new int[0]; + [SerializeField] + private bool m_ShowAllHits; + [SerializeField] + private SearchFilter.SearchArea m_SearchArea; + [SerializeField] + private string[] m_Folders = new string[0]; + public string nameFilter + { + get + { + return this.m_NameFilter; + } + set + { + this.m_NameFilter = value; + } + } + public string[] classNames + { + get + { + return this.m_ClassNames; + } + set + { + this.m_ClassNames = value; + } + } + public string[] assetLabels + { + get + { + return this.m_AssetLabels; + } + set + { + this.m_AssetLabels = value; + } + } + public int[] referencingInstanceIDs + { + get + { + return this.m_ReferencingInstanceIDs; + } + set + { + this.m_ReferencingInstanceIDs = value; + } + } + public bool showAllHits + { + get + { + return this.m_ShowAllHits; + } + set + { + this.m_ShowAllHits = value; + } + } + public string[] folders + { + get + { + return this.m_Folders; + } + set + { + this.m_Folders = value; + } + } + public SearchFilter.SearchArea searchArea + { + get + { + return this.m_SearchArea; + } + set + { + this.m_SearchArea = value; + } + } + public void ClearSearch() + { + this.m_NameFilter = string.Empty; + this.m_ClassNames = new string[0]; + this.m_AssetLabels = new string[0]; + this.m_ReferencingInstanceIDs = new int[0]; + this.m_ShowAllHits = false; + } + private bool IsNullOrEmtpy(T[] list) + { + return list == null || list.Length == 0; + } + public SearchFilter.State GetState() + { + bool flag = !string.IsNullOrEmpty(this.m_NameFilter) || !this.IsNullOrEmtpy(this.m_AssetLabels) || !this.IsNullOrEmtpy(this.m_ClassNames) || !this.IsNullOrEmtpy(this.m_ReferencingInstanceIDs); + bool flag2 = !this.IsNullOrEmtpy(this.m_Folders); + if (flag) + { + if (this.m_SearchArea == SearchFilter.SearchArea.AssetStore) + { + return SearchFilter.State.SearchingInAssetStore; + } + if (flag2 && this.m_SearchArea == SearchFilter.SearchArea.SelectedFolders) + { + return SearchFilter.State.SearchingInFolders; + } + return SearchFilter.State.SearchingInAllAssets; + } + else + { + if (flag2) + { + return SearchFilter.State.FolderBrowsing; + } + return SearchFilter.State.EmptySearchFilter; + } + } + public bool IsSearching() + { + SearchFilter.State state = this.GetState(); + return state == SearchFilter.State.SearchingInAllAssets || state == SearchFilter.State.SearchingInFolders || state == SearchFilter.State.SearchingInAssetStore; + } + public bool SetNewFilter(SearchFilter newFilter) + { + bool result = false; + if (newFilter.m_NameFilter != this.m_NameFilter) + { + this.m_NameFilter = newFilter.m_NameFilter; + result = true; + } + if (newFilter.m_ClassNames != this.m_ClassNames) + { + this.m_ClassNames = newFilter.m_ClassNames; + result = true; + } + if (newFilter.m_Folders != this.m_Folders) + { + this.m_Folders = newFilter.m_Folders; + result = true; + } + if (newFilter.m_AssetLabels != this.m_AssetLabels) + { + this.m_AssetLabels = newFilter.m_AssetLabels; + result = true; + } + if (newFilter.m_ReferencingInstanceIDs != this.m_ReferencingInstanceIDs) + { + this.m_ReferencingInstanceIDs = newFilter.m_ReferencingInstanceIDs; + result = true; + } + if (newFilter.m_SearchArea != this.m_SearchArea) + { + this.m_SearchArea = newFilter.m_SearchArea; + result = true; + } + this.m_ShowAllHits = newFilter.m_ShowAllHits; + return result; + } + public override string ToString() + { + string text = "SearchFilter: "; + text += string.Format("[Area: {0}, State: {1}]", this.m_SearchArea, this.GetState()); + if (!string.IsNullOrEmpty(this.m_NameFilter)) + { + text = text + "[Name: " + this.m_NameFilter + "]"; + } + if (this.m_AssetLabels != null && this.m_AssetLabels.Length > 0) + { + text = text + "[Labels: " + this.m_AssetLabels[0] + "]"; + } + string text2; + if (this.m_ClassNames != null && this.m_ClassNames.Length > 0) + { + text2 = text; + text = string.Concat(new object[] + { + text2, + "[Types: ", + this.m_ClassNames[0], + " (", + this.m_ClassNames.Length, + ")]" + }); + } + if (this.m_ReferencingInstanceIDs != null && this.m_ReferencingInstanceIDs.Length > 0) + { + text2 = text; + text = string.Concat(new object[] + { + text2, + "[RefIDs: ", + this.m_ReferencingInstanceIDs[0], + "]" + }); + } + if (this.m_Folders != null && this.m_Folders.Length > 0) + { + text = text + "[Folders: " + this.m_Folders[0] + "]"; + } + text2 = text; + return string.Concat(new object[] + { + text2, + "[ShowAllHits: ", + this.showAllHits, + "]" + }); + } + internal string FilterToSearchFieldString() + { + string text = string.Empty; + if (!string.IsNullOrEmpty(this.m_NameFilter)) + { + text += this.m_NameFilter; + } + this.AddToString("t:", this.m_ClassNames, ref text); + this.AddToString("l:", this.m_AssetLabels, ref text); + return text; + } + private void AddToString(string prefix, T[] list, ref string result) + { + if (list == null) + { + return; + } + if (result == null) + { + result = string.Empty; + } + for (int i = 0; i < list.Length; i++) + { + T t = list[i]; + if (!string.IsNullOrEmpty(result)) + { + result += " "; + } + result = result + prefix + t; + } + } + internal void SearchFieldStringToFilter(string searchString) + { + this.ClearSearch(); + if (string.IsNullOrEmpty(searchString)) + { + return; + } + SearchUtility.ParseSearchString(searchString, this); + } + internal static SearchFilter CreateSearchFilterFromString(string searchText) + { + SearchFilter searchFilter = new SearchFilter(); + SearchUtility.ParseSearchString(searchText, searchFilter); + return searchFilter; + } + public string[] SplitNameFilter() + { + List list = new List(); + foreach (Match match in Regex.Matches(this.m_NameFilter, "(?\\w+)|\\\"(?[\\w\\s]*)\"")) + { + list.Add(match.Value.Replace("\"", string.Empty)); + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor/SearchFilterTreeItem.cs b/UnityEditor/UnityEditor/SearchFilterTreeItem.cs new file mode 100644 index 00000000..5246dae2 --- /dev/null +++ b/UnityEditor/UnityEditor/SearchFilterTreeItem.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor +{ + internal class SearchFilterTreeItem : TreeViewItem + { + private bool m_IsFolder; + public bool isFolder + { + get + { + return this.m_IsFolder; + } + } + public SearchFilterTreeItem(int id, int depth, TreeViewItem parent, string displayName, bool isFolder) : base(id, depth, parent, displayName) + { + this.m_IsFolder = isFolder; + } + } +} diff --git a/UnityEditor/UnityEditor/SearchUtility.cs b/UnityEditor/UnityEditor/SearchUtility.cs new file mode 100644 index 00000000..71984792 --- /dev/null +++ b/UnityEditor/UnityEditor/SearchUtility.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SearchUtility + { + private static void RemoveUnwantedWhitespaces(ref string searchString) + { + searchString = searchString.Replace(": ", ":"); + } + internal static bool ParseSearchString(string searchText, SearchFilter filter) + { + if (string.IsNullOrEmpty(searchText)) + { + return false; + } + filter.ClearSearch(); + string text = string.Copy(searchText); + SearchUtility.RemoveUnwantedWhitespaces(ref text); + bool result = false; + int i = SearchUtility.FindFirstPositionNotOf(text, " \t,"); + if (i == -1) + { + i = 0; + } + while (i < text.Length) + { + int num = text.IndexOfAny(" \t,".ToCharArray(), i); + int num2 = text.IndexOf('"', i); + int num3 = -1; + if (num2 != -1) + { + num3 = text.IndexOf('"', num2 + 1); + if (num3 != -1) + { + num = text.IndexOfAny(" \t,".ToCharArray(), num3); + } + else + { + num = -1; + } + } + if (num == -1) + { + num = text.Length; + } + if (num > i) + { + string text2 = text.Substring(i, num - i); + if (SearchUtility.ParseSingleWord(text2, filter, num2, num3)) + { + result = true; + } + else + { + filter.nameFilter = filter.nameFilter + ((!string.IsNullOrEmpty(filter.nameFilter)) ? " " : string.Empty) + text2; + } + } + i = num + 1; + } + return result; + } + internal static bool ParseSingleWord(string searchString, SearchFilter filter, int quote1, int quote2) + { + bool result = false; + int num = searchString.IndexOf("t:"); + if (num >= 0) + { + string item = searchString.Substring(num + 2); + filter.classNames = new List(filter.classNames) + { + item + }.ToArray(); + result = true; + } + num = searchString.IndexOf("l:"); + if (num >= 0) + { + string item2 = searchString.Substring(num + 2); + filter.assetLabels = new List(filter.assetLabels) + { + item2 + }.ToArray(); + result = true; + } + num = searchString.IndexOf("ref:"); + if (num >= 0) + { + int num2 = 0; + int num3 = num + 3; + int num4 = searchString.IndexOf(':', num3 + 1); + if (num4 >= 0) + { + string s = searchString.Substring(num3 + 1, num4 - num3 - 1); + int num5; + if (int.TryParse(s, out num5)) + { + num2 = num5; + } + } + else + { + string assetPath; + if (quote1 != -1 && quote2 != -1) + { + int num6 = quote1 + 1; + int num7 = quote2 - quote1 - 1; + if (num7 < 0 || quote2 == -1) + { + num7 = searchString.Length - num6; + } + assetPath = "Assets/" + searchString.Substring(num6, num7); + } + else + { + assetPath = "Assets/" + searchString.Substring(num3 + 1); + } + UnityEngine.Object @object = AssetDatabase.LoadMainAssetAtPath(assetPath); + if (@object != null) + { + num2 = @object.GetInstanceID(); + } + } + filter.referencingInstanceIDs = new int[] + { + num2 + }; + result = true; + } + return result; + } + private static int FindFirstPositionNotOf(string source, string chars) + { + if (source == null) + { + return -1; + } + if (chars == null) + { + return 0; + } + if (source.Length == 0) + { + return -1; + } + if (chars.Length == 0) + { + return 0; + } + for (int i = 0; i < source.Length; i++) + { + if (chars.IndexOf(source[i]) == -1) + { + return i; + } + } + return -1; + } + } +} diff --git a/UnityEditor/UnityEditor/SearchableEditorWindow.cs b/UnityEditor/UnityEditor/SearchableEditorWindow.cs new file mode 100644 index 00000000..bec984ce --- /dev/null +++ b/UnityEditor/UnityEditor/SearchableEditorWindow.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +namespace UnityEditor +{ + public class SearchableEditorWindow : EditorWindow + { + public enum SearchMode + { + All, + Name, + Type, + Label + } + public enum SearchModeHierarchyWindow + { + All, + Name, + Type + } + private static List searchableWindows = new List(); + private static int s_SearchableEditorWindowSearchField = "SearchableEditorWindowSearchField".GetHashCode(); + internal HierarchyType m_HierarchyType = HierarchyType.Assets; + internal string m_SearchFilter = string.Empty; + internal SearchableEditorWindow.SearchMode m_SearchMode; + private bool m_FocusSearchField; + private bool m_HasSearchFilterFocus; + private int m_SearchFieldControlId; + internal bool hasSearchFilter + { + get + { + return this.m_SearchFilter != string.Empty; + } + } + internal bool hasSearchFilterFocus + { + get + { + return this.m_HasSearchFilterFocus; + } + set + { + this.m_HasSearchFilterFocus = value; + } + } + internal SearchableEditorWindow.SearchMode searchMode + { + get + { + return this.m_SearchMode; + } + set + { + this.m_SearchMode = value; + } + } + internal static SearchFilter CreateFilter(string searchString, SearchableEditorWindow.SearchMode searchMode) + { + SearchFilter searchFilter = new SearchFilter(); + if (string.IsNullOrEmpty(searchString)) + { + return searchFilter; + } + switch (searchMode) + { + case SearchableEditorWindow.SearchMode.All: + if (!SearchUtility.ParseSearchString(searchString, searchFilter)) + { + searchFilter.nameFilter = searchString; + searchFilter.classNames = new string[] + { + searchString + }; + searchFilter.assetLabels = new string[] + { + searchString + }; + searchFilter.showAllHits = true; + } + break; + case SearchableEditorWindow.SearchMode.Name: + searchFilter.nameFilter = searchString; + break; + case SearchableEditorWindow.SearchMode.Type: + searchFilter.classNames = new string[] + { + searchString + }; + break; + case SearchableEditorWindow.SearchMode.Label: + searchFilter.assetLabels = new string[] + { + searchString + }; + break; + } + return searchFilter; + } + [MenuItem("Assets/Find References In Scene", false, 25)] + private static void OnSearchForReferences() + { + int activeInstanceID = Selection.activeInstanceID; + string text = AssetDatabase.GetAssetPath(activeInstanceID).Substring(7); + if (text.IndexOf(' ') != -1) + { + text = '"' + text + '"'; + } + string searchFilter; + if (AssetDatabase.IsMainAsset(activeInstanceID)) + { + searchFilter = "ref:" + text; + } + else + { + searchFilter = string.Concat(new object[] + { + "ref:", + activeInstanceID, + ":", + text + }); + } + foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) + { + if (current.m_HierarchyType == HierarchyType.GameObjects) + { + current.SetSearchFilter(searchFilter, SearchableEditorWindow.SearchMode.All, false); + current.m_HasSearchFilterFocus = true; + current.Repaint(); + } + } + } + [MenuItem("Assets/Find References In Scene", true)] + private static bool OnSearchForReferencesValidate() + { + UnityEngine.Object activeObject = Selection.activeObject; + if (activeObject != null && AssetDatabase.Contains(activeObject)) + { + string assetPath = AssetDatabase.GetAssetPath(activeObject); + return !Directory.Exists(assetPath); + } + return false; + } + public virtual void OnEnable() + { + SearchableEditorWindow.searchableWindows.Add(this); + } + public virtual void OnDisable() + { + SearchableEditorWindow.searchableWindows.Remove(this); + } + internal void FocusSearchField() + { + this.m_FocusSearchField = true; + } + internal void ClearSearchFilter() + { + this.SetSearchFilter(string.Empty, this.m_SearchMode, true); + if (EditorGUI.s_RecycledEditor != null) + { + EditorGUI.s_RecycledEditor.controlID = 0; + } + } + internal void SelectPreviousSearchResult() + { + foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) + { + if (current is BaseProjectWindow && current.m_HierarchyType == this.m_HierarchyType) + { + ((BaseProjectWindow)current).SelectPrevious(); + break; + } + } + } + internal void SelectNextSearchResult() + { + foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) + { + if (current is BaseProjectWindow && current.m_HierarchyType == this.m_HierarchyType) + { + ((BaseProjectWindow)current).SelectNext(); + break; + } + } + } + internal virtual void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + { + this.m_SearchMode = searchMode; + this.m_SearchFilter = searchFilter; + if (setAll) + { + foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) + { + if (current != this && current.m_HierarchyType == this.m_HierarchyType && current.m_HierarchyType != HierarchyType.Assets) + { + current.SetSearchFilter(this.m_SearchFilter, this.m_SearchMode, false); + } + } + } + base.Repaint(); + EditorApplication.Internal_CallSearchHasChanged(); + } + internal virtual void ClickedSearchField() + { + } + internal void SearchFieldGUI() + { + Rect rect = GUILayoutUtility.GetRect(0f, EditorGUILayout.kLabelFloatMaxW * 1.5f, 16f, 16f, EditorStyles.toolbarSearchField); + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + this.ClickedSearchField(); + } + GUI.SetNextControlName("SearchFilter"); + if (this.m_FocusSearchField) + { + EditorGUI.FocusTextInControl("SearchFilter"); + if (Event.current.type == EventType.Repaint) + { + this.m_FocusSearchField = false; + } + } + int searchMode = (int)this.m_SearchMode; + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape && GUI.GetNameOfFocusedControl() == "SearchFilter") + { + this.SetSearchFilter(string.Empty, (SearchableEditorWindow.SearchMode)searchMode, true); + } + string[] names = Enum.GetNames((this.m_HierarchyType != HierarchyType.GameObjects) ? typeof(SearchableEditorWindow.SearchMode) : typeof(SearchableEditorWindow.SearchModeHierarchyWindow)); + this.m_SearchFieldControlId = GUIUtility.GetControlID(SearchableEditorWindow.s_SearchableEditorWindowSearchField, FocusType.Keyboard, rect); + EditorGUI.BeginChangeCheck(); + string searchFilter = EditorGUI.ToolbarSearchField(this.m_SearchFieldControlId, rect, names, ref searchMode, this.m_SearchFilter); + if (EditorGUI.EndChangeCheck()) + { + this.SetSearchFilter(searchFilter, (SearchableEditorWindow.SearchMode)searchMode, true); + } + this.m_HasSearchFilterFocus = (GUIUtility.keyboardControl == this.m_SearchFieldControlId); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape && this.m_SearchFilter != string.Empty && GUIUtility.hotControl == 0) + { + this.m_SearchFilter = string.Empty; + this.SetSearchFilter(searchFilter, (SearchableEditorWindow.SearchMode)searchMode, true); + Event.current.Use(); + this.m_HasSearchFilterFocus = false; + } + } + } +} diff --git a/UnityEditor/UnityEditor/Selection.cs b/UnityEditor/UnityEditor/Selection.cs new file mode 100644 index 00000000..7f29f118 --- /dev/null +++ b/UnityEditor/UnityEditor/Selection.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Selection + { + public static extern Transform[] transforms + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Transform activeTransform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern GameObject[] gameObjects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern GameObject activeGameObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern UnityEngine.Object activeObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int activeInstanceID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern UnityEngine.Object[] objects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int[] instanceIDs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern string[] assetGUIDsDeepSelection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] assetGUIDs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static bool Contains(int instanceID) + { + return Array.IndexOf(Selection.instanceIDs, instanceID) != -1; + } + public static bool Contains(UnityEngine.Object obj) + { + return Selection.Contains(obj.GetInstanceID()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Transform[] GetTransforms(SelectionMode mode); + public static UnityEngine.Object[] GetFiltered(Type type, SelectionMode mode) + { + ArrayList arrayList = new ArrayList(); + if (type == typeof(Component) || type.IsSubclassOf(typeof(Component))) + { + Transform[] transforms = Selection.GetTransforms(mode); + Transform[] array = transforms; + for (int i = 0; i < array.Length; i++) + { + Transform transform = array[i]; + Component component = transform.GetComponent(type); + if (component) + { + arrayList.Add(component); + } + } + } + else + { + if (type == typeof(GameObject) || type.IsSubclassOf(typeof(GameObject))) + { + Transform[] transforms2 = Selection.GetTransforms(mode); + Transform[] array2 = transforms2; + for (int j = 0; j < array2.Length; j++) + { + Transform transform2 = array2[j]; + arrayList.Add(transform2.gameObject); + } + } + else + { + UnityEngine.Object[] objectsMode = Selection.GetObjectsMode(mode); + UnityEngine.Object[] array3 = objectsMode; + for (int k = 0; k < array3.Length; k++) + { + UnityEngine.Object @object = array3[k]; + if (@object != null && (@object.GetType() == type || @object.GetType().IsSubclassOf(type))) + { + arrayList.Add(@object); + } + } + } + } + return (UnityEngine.Object[])arrayList.ToArray(typeof(UnityEngine.Object)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern UnityEngine.Object[] GetObjectsMode(SelectionMode mode); + } +} diff --git a/UnityEditor/UnityEditor/SelectionMode.cs b/UnityEditor/UnityEditor/SelectionMode.cs new file mode 100644 index 00000000..90232913 --- /dev/null +++ b/UnityEditor/UnityEditor/SelectionMode.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor +{ + public enum SelectionMode + { + Unfiltered, + TopLevel, + Deep, + ExcludePrefab = 4, + Editable = 8, + Assets = 16, + DeepAssets = 32, + OnlyUserModifiable = 8 + } +} diff --git a/UnityEditor/UnityEditor/SerializationMode.cs b/UnityEditor/UnityEditor/SerializationMode.cs new file mode 100644 index 00000000..94c33eb7 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializationMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum SerializationMode + { + Mixed, + ForceBinary, + ForceText + } +} diff --git a/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs b/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs new file mode 100644 index 00000000..4bafc867 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +namespace UnityEditor +{ + internal static class SerializedFileContainerWriter + { + internal class SerializedFile + { + public string Name; + public string FileName; + public long FileSize; + } + public static void Write(string filepath, IEnumerable files, string outputdir) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(SerializedFileContainerWriter.GetHead()); + filepath = Environment.CurrentDirectory + "/" + filepath; + filepath = filepath.Replace("\\", "/"); + foreach (SerializedFileContainerWriter.SerializedFile current in files) + { + stringBuilder.Append(SerializedFileContainerWriter.GetFieldDeclarationForFile(filepath, current.FileName)); + } + stringBuilder.Append(SerializedFileContainerWriter.GetConstructor(files)); + stringBuilder.Append(SerializedFileContainerWriter.GetTail()); + File.WriteAllText(Path.Combine(outputdir, "ProjectSerializedFileContainer.as"), stringBuilder.ToString()); + } + private static string GetHead() + { + return "\npackage\n{\n import flash.utils.ByteArray;\n import flash.utils.Dictionary;\n import flash.utils.Endian;\n import UnityEngine.*;\n\t\timport com.unity.SerializedFileContainer;\n\n public class ProjectSerializedFileContainer extends SerializedFileContainer\n {\n \n"; + } + private static string GetFieldDeclarationForFile(string filepath, string file) + { + return string.Concat(new string[] + { + " [Embed(\"", + filepath, + "/", + file, + "_txt\", mimeType=\"application/octet-stream\")]\n private var ", + SerializedFileContainerWriter.GetTypeNameForFile(file), + ":Class;\n\n" + }); + } + private static string GetConstructor(IEnumerable files) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(" \n public function ProjectSerializedFileContainer()\n {\n files = new Dictionary();\n"); + foreach (SerializedFileContainerWriter.SerializedFile current in files) + { + stringBuilder.AppendLine(string.Concat(new object[] + { + "files[\"", + current.Name, + "\"] = ", + SerializedFileContainerWriter.GetArrayOfByteArrays(current) + })); + stringBuilder.AppendLine(string.Concat(new object[] + { + "fileSizes[\"", + current.Name, + "\"] = ", + current.FileSize + })); + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + private static StringBuilder GetArrayOfByteArrays(SerializedFileContainerWriter.SerializedFile file) + { + StringBuilder stringBuilder = new StringBuilder(string.Empty); + stringBuilder.Append("new " + SerializedFileContainerWriter.GetTypeNameForFile(file.Name) + "() as ByteArray"); + return stringBuilder; + } + private static string GetTypeNameForFile(string file) + { + file = file.Replace("/", "_"); + file = file.Replace(" ", "_"); + return file.Replace(".", "_"); + } + private static string GetTail() + { + return "\t}\n}\n"; + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedMinMaxColor.cs b/UnityEditor/UnityEditor/SerializedMinMaxColor.cs new file mode 100644 index 00000000..92c59827 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedMinMaxColor.cs @@ -0,0 +1,24 @@ +using System; +namespace UnityEditor +{ + internal class SerializedMinMaxColor + { + public SerializedProperty maxColor; + public SerializedProperty minColor; + public SerializedProperty minMax; + public SerializedMinMaxColor(SerializedModule m) + { + this.Init(m, "curve"); + } + public SerializedMinMaxColor(SerializedModule m, string name) + { + this.Init(m, name); + } + private void Init(SerializedModule m, string name) + { + this.maxColor = m.GetProperty(name, "maxColor"); + this.minColor = m.GetProperty(name, "minColor"); + this.minMax = m.GetProperty(name, "minMax"); + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs b/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs new file mode 100644 index 00000000..dc92bc1c --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs @@ -0,0 +1,393 @@ +using NUnit.Framework; +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SerializedMinMaxCurve + { + public SerializedProperty scalar; + public SerializedProperty maxCurve; + public SerializedProperty minCurve; + public SerializedProperty minCurveFirstKeyValue; + public SerializedProperty maxCurveFirstKeyValue; + private SerializedProperty minMaxState; + public ModuleUI m_Module; + private string m_Name; + public GUIContent m_DisplayName; + private bool m_SignedRange; + public float m_DefaultCurveScalar; + public float m_RemapValue; + public bool m_AllowConstant; + public bool m_AllowRandom; + public float m_MaxAllowedScalar = float.PositiveInfinity; + public MinMaxCurveState state + { + get + { + return (MinMaxCurveState)this.minMaxState.intValue; + } + set + { + this.SetMinMaxState(value); + } + } + public bool signedRange + { + get + { + return this.m_SignedRange; + } + } + public float maxConstant + { + get + { + return this.maxCurveFirstKeyValue.floatValue * this.scalar.floatValue; + } + set + { + value = this.ClampValueToMaxAllowed(value); + if (!this.signedRange) + { + value = Mathf.Max(value, 0f); + } + float minConstant = this.minConstant; + float num = Mathf.Abs(minConstant); + float num2 = Mathf.Abs(value); + float num3 = (num2 <= num) ? num : num2; + if (num3 != this.scalar.floatValue) + { + this.SetScalarAndNormalizedConstants(num3, minConstant, value); + } + else + { + this.SetNormalizedConstant(this.maxCurve, value); + } + } + } + public float minConstant + { + get + { + return this.minCurveFirstKeyValue.floatValue * this.scalar.floatValue; + } + set + { + value = this.ClampValueToMaxAllowed(value); + if (!this.signedRange) + { + value = Mathf.Max(value, 0f); + } + float maxConstant = this.maxConstant; + float num = Mathf.Abs(value); + float num2 = Mathf.Abs(maxConstant); + float num3 = (num2 <= num) ? num : num2; + if (num3 != this.scalar.floatValue) + { + this.SetScalarAndNormalizedConstants(num3, value, maxConstant); + } + else + { + this.SetNormalizedConstant(this.minCurve, value); + } + } + } + public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName) + { + this.Init(m, displayName, "curve", false); + } + public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name) + { + this.Init(m, displayName, name, false); + } + public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, bool signedRange) + { + this.Init(m, displayName, "curve", signedRange); + } + public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name, bool signedRange) + { + this.Init(m, displayName, name, signedRange); + } + private void Init(ModuleUI m, GUIContent displayName, string uniqueName, bool signedRange) + { + this.m_Module = m; + this.m_DisplayName = displayName; + this.m_Name = uniqueName; + this.m_SignedRange = signedRange; + this.m_RemapValue = 1f; + this.m_DefaultCurveScalar = 1f; + this.m_AllowConstant = true; + this.m_AllowRandom = true; + this.scalar = m.GetProperty(this.m_Name, "scalar"); + this.maxCurve = m.GetProperty(this.m_Name, "maxCurve"); + this.maxCurveFirstKeyValue = this.maxCurve.FindPropertyRelative("m_Curve.Array.data[0].value"); + this.minCurve = m.GetProperty(this.m_Name, "minCurve"); + this.minCurveFirstKeyValue = this.minCurve.FindPropertyRelative("m_Curve.Array.data[0].value"); + this.minMaxState = m.GetProperty(this.m_Name, "minMaxState"); + if ((this.state == MinMaxCurveState.k_Curve || this.state == MinMaxCurveState.k_TwoCurves) && this.m_Module.m_ParticleSystemUI.m_ParticleEffectUI.IsParticleSystemUIVisible(this.m_Module.m_ParticleSystemUI)) + { + m.GetParticleSystemCurveEditor().AddCurveDataIfNeeded(this.GetUniqueCurveName(), this.CreateCurveData(Color.black)); + } + m.AddToModuleCurves(this.maxCurve); + } + private float ClampValueToMaxAllowed(float val) + { + if (Mathf.Abs(val) > this.m_MaxAllowedScalar) + { + return this.m_MaxAllowedScalar * Mathf.Sign(val); + } + return val; + } + public void SetScalarAndNormalizedConstants(float newScalar, float totalMin, float totalMax) + { + this.scalar.floatValue = newScalar; + this.SetNormalizedConstant(this.minCurve, totalMin); + this.SetNormalizedConstant(this.maxCurve, totalMax); + } + private void SetNormalizedConstant(SerializedProperty curve, float totalValue) + { + float num = this.scalar.floatValue; + num = Mathf.Max(num, 0.0001f); + float value = totalValue / num; + this.SetCurveConstant(curve, value); + } + public Vector2 GetAxisScalars() + { + return new Vector2(this.m_Module.GetXAxisScalar(), this.scalar.floatValue * this.m_RemapValue); + } + public void SetAxisScalars(Vector2 axisScalars) + { + float num = (this.m_RemapValue != 0f) ? this.m_RemapValue : 1f; + this.scalar.floatValue = axisScalars.y / num; + } + public void RemoveCurveFromEditor() + { + ParticleSystemCurveEditor particleSystemCurveEditor = this.m_Module.GetParticleSystemCurveEditor(); + if (particleSystemCurveEditor.IsAdded(this.GetMinCurve(), this.maxCurve)) + { + particleSystemCurveEditor.RemoveCurve(this.GetMinCurve(), this.maxCurve); + } + } + public bool OnCurveAreaMouseDown(int button, Rect drawRect, Rect curveRanges) + { + if (button == 0) + { + this.ToggleCurveInEditor(); + return true; + } + if (button == 1) + { + AnimationCurveContextMenu.Show(drawRect, this.maxCurve, this.GetMinCurve(), this.scalar, curveRanges, this.m_Module.GetParticleSystemCurveEditor()); + return true; + } + return false; + } + public ParticleSystemCurveEditor.CurveData CreateCurveData(Color color) + { + Assert.That(this.state != MinMaxCurveState.k_Scalar); + return new ParticleSystemCurveEditor.CurveData(this.GetUniqueCurveName(), this.m_DisplayName, this.GetMinCurve(), this.maxCurve, color, this.m_SignedRange, new CurveWrapper.GetAxisScalarsCallback(this.GetAxisScalars), new CurveWrapper.SetAxisScalarsCallback(this.SetAxisScalars), this.m_Module.foldout); + } + private SerializedProperty GetMinCurve() + { + return (this.state != MinMaxCurveState.k_TwoCurves) ? null : this.minCurve; + } + public void ToggleCurveInEditor() + { + ParticleSystemCurveEditor particleSystemCurveEditor = this.m_Module.GetParticleSystemCurveEditor(); + if (particleSystemCurveEditor.IsAdded(this.GetMinCurve(), this.maxCurve)) + { + particleSystemCurveEditor.RemoveCurve(this.GetMinCurve(), this.maxCurve); + } + else + { + particleSystemCurveEditor.AddCurve(this.CreateCurveData(particleSystemCurveEditor.GetAvailableColor())); + } + } + private void SetMinMaxState(MinMaxCurveState newState) + { + if (newState == this.state) + { + return; + } + MinMaxCurveState state = this.state; + ParticleSystemCurveEditor particleSystemCurveEditor = this.m_Module.GetParticleSystemCurveEditor(); + if (particleSystemCurveEditor.IsAdded(this.GetMinCurve(), this.maxCurve)) + { + particleSystemCurveEditor.RemoveCurve(this.GetMinCurve(), this.maxCurve); + } + switch (newState) + { + case MinMaxCurveState.k_Scalar: + this.InitSingleScalar(state); + break; + case MinMaxCurveState.k_Curve: + this.InitSingleCurve(state); + break; + case MinMaxCurveState.k_TwoCurves: + this.InitDoubleCurves(state); + break; + case MinMaxCurveState.k_TwoScalars: + this.InitDoubleScalars(state); + break; + } + this.minMaxState.intValue = (int)newState; + switch (newState) + { + case MinMaxCurveState.k_Scalar: + case MinMaxCurveState.k_TwoScalars: + break; + case MinMaxCurveState.k_Curve: + case MinMaxCurveState.k_TwoCurves: + particleSystemCurveEditor.AddCurve(this.CreateCurveData(particleSystemCurveEditor.GetAvailableColor())); + break; + default: + Debug.LogError("Unhandled enum value"); + break; + } + AnimationCurvePreviewCache.ClearCache(); + } + private void InitSingleScalar(MinMaxCurveState oldState) + { + switch (oldState) + { + case MinMaxCurveState.k_Curve: + case MinMaxCurveState.k_TwoCurves: + case MinMaxCurveState.k_TwoScalars: + { + float maxKeyValue = this.GetMaxKeyValue(this.maxCurve.animationCurveValue.keys); + this.scalar.floatValue *= maxKeyValue; + break; + } + } + this.SetCurveConstant(this.maxCurve, 1f); + } + private void InitDoubleScalars(MinMaxCurveState oldState) + { + this.minConstant = this.GetAverageKeyValue(this.minCurve.animationCurveValue.keys) * this.scalar.floatValue; + switch (oldState) + { + case MinMaxCurveState.k_Scalar: + this.maxConstant = this.scalar.floatValue; + break; + case MinMaxCurveState.k_Curve: + case MinMaxCurveState.k_TwoCurves: + this.maxConstant = this.GetAverageKeyValue(this.maxCurve.animationCurveValue.keys) * this.scalar.floatValue; + break; + default: + Debug.LogError("Enum not handled!"); + break; + } + this.SetCurveRequirements(); + } + private void InitSingleCurve(MinMaxCurveState oldState) + { + switch (oldState) + { + case MinMaxCurveState.k_Scalar: + this.SetCurveConstant(this.maxCurve, this.GetNormalizedValueFromScalar()); + break; + } + this.SetCurveRequirements(); + } + private void InitDoubleCurves(MinMaxCurveState oldState) + { + switch (oldState) + { + case MinMaxCurveState.k_Scalar: + this.SetCurveConstant(this.maxCurve, this.GetNormalizedValueFromScalar()); + break; + } + this.SetCurveRequirements(); + } + private float GetNormalizedValueFromScalar() + { + if (this.scalar.floatValue < 0f) + { + return -1f; + } + if (this.scalar.floatValue > 0f) + { + return 1f; + } + return 0f; + } + private void SetCurveRequirements() + { + this.scalar.floatValue = Mathf.Abs(this.scalar.floatValue); + if (this.scalar.floatValue == 0f) + { + this.scalar.floatValue = this.m_DefaultCurveScalar; + } + } + private void SetCurveConstant(SerializedProperty curve, float value) + { + curve.animationCurveValue = new AnimationCurve(new Keyframe[] + { + new Keyframe(0f, value) + }); + } + private float GetAverageKeyValue(Keyframe[] keyFrames) + { + float num = 0f; + for (int i = 0; i < keyFrames.Length; i++) + { + Keyframe keyframe = keyFrames[i]; + num += keyframe.value; + } + return num / (float)keyFrames.Length; + } + private float GetMaxKeyValue(Keyframe[] keyFrames) + { + float num = float.NegativeInfinity; + float num2 = float.PositiveInfinity; + for (int i = 0; i < keyFrames.Length; i++) + { + Keyframe keyframe = keyFrames[i]; + if (keyframe.value > num) + { + num = keyframe.value; + } + if (keyframe.value < num2) + { + num2 = keyframe.value; + } + } + if (Mathf.Abs(num2) > num) + { + return num2; + } + return num; + } + private bool IsCurveConstant(Keyframe[] keyFrames, out float constantValue) + { + if (keyFrames.Length == 0) + { + constantValue = 0f; + return false; + } + constantValue = keyFrames[0].value; + for (int i = 1; i < keyFrames.Length; i++) + { + if (Mathf.Abs(constantValue - keyFrames[i].value) > 1E-05f) + { + return false; + } + } + return true; + } + public string GetUniqueCurveName() + { + return SerializedModule.Concat(this.m_Module.GetUniqueModuleName(), this.m_Name); + } + public bool SupportsProcedural() + { + bool flag = AnimationUtility.CurveSupportsProcedural(this.maxCurve.animationCurveValue); + if (this.state != MinMaxCurveState.k_TwoCurves && this.state != MinMaxCurveState.k_TwoScalars) + { + return flag; + } + return flag && AnimationUtility.CurveSupportsProcedural(this.minCurve.animationCurveValue); + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedMinMaxGradient.cs b/UnityEditor/UnityEditor/SerializedMinMaxGradient.cs new file mode 100644 index 00000000..741532a1 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedMinMaxGradient.cs @@ -0,0 +1,68 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SerializedMinMaxGradient + { + public SerializedProperty m_MaxGradient; + public SerializedProperty m_MinGradient; + public SerializedProperty m_MaxColor; + public SerializedProperty m_MinColor; + private SerializedProperty m_MinMaxState; + public bool m_AllowColor; + public bool m_AllowGradient; + public bool m_AllowRandomBetweenTwoColors; + public bool m_AllowRandomBetweenTwoGradients; + public MinMaxGradientState state + { + get + { + return (MinMaxGradientState)this.m_MinMaxState.intValue; + } + set + { + this.SetMinMaxState(value); + } + } + public SerializedMinMaxGradient(SerializedModule m) + { + this.Init(m, "gradient"); + } + public SerializedMinMaxGradient(SerializedModule m, string name) + { + this.Init(m, name); + } + private void Init(SerializedModule m, string name) + { + this.m_MaxGradient = m.GetProperty(name, "maxGradient"); + this.m_MinGradient = m.GetProperty(name, "minGradient"); + this.m_MaxColor = m.GetProperty(name, "maxColor"); + this.m_MinColor = m.GetProperty(name, "minColor"); + this.m_MinMaxState = m.GetProperty(name, "minMaxState"); + this.m_AllowColor = true; + this.m_AllowGradient = true; + this.m_AllowRandomBetweenTwoColors = true; + this.m_AllowRandomBetweenTwoGradients = true; + } + private void SetMinMaxState(MinMaxGradientState newState) + { + if (newState == this.state) + { + return; + } + this.m_MinMaxState.intValue = (int)newState; + } + public static Color GetGradientAsColor(SerializedProperty gradientProp) + { + Gradient gradientValue = gradientProp.gradientValue; + return gradientValue.constantColor; + } + public static void SetGradientAsColor(SerializedProperty gradientProp, Color color) + { + Gradient gradientValue = gradientProp.gradientValue; + gradientValue.constantColor = color; + GradientPreviewCache.ClearCache(); + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedModule.cs b/UnityEditor/UnityEditor/SerializedModule.cs new file mode 100644 index 00000000..ceb111d1 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedModule.cs @@ -0,0 +1,50 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SerializedModule + { + protected string m_ModuleName; + private SerializedObject m_Object; + public SerializedModule(SerializedObject o, string name) + { + this.m_Object = o; + this.m_ModuleName = name; + } + public SerializedProperty GetProperty0(string name) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(name); + if (serializedProperty == null) + { + Debug.LogError("GetProperty0: not found: " + name); + } + return serializedProperty; + } + public SerializedProperty GetProperty(string name) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(SerializedModule.Concat(this.m_ModuleName, name)); + if (serializedProperty == null) + { + Debug.LogError("GetProperty: not found: " + SerializedModule.Concat(this.m_ModuleName, name)); + } + return serializedProperty; + } + public SerializedProperty GetProperty(string structName, string propName) + { + SerializedProperty serializedProperty = this.m_Object.FindProperty(SerializedModule.Concat(SerializedModule.Concat(this.m_ModuleName, structName), propName)); + if (serializedProperty == null) + { + Debug.LogError("GetProperty: not found: " + SerializedModule.Concat(SerializedModule.Concat(this.m_ModuleName, structName), propName)); + } + return serializedProperty; + } + public static string Concat(string a, string b) + { + return a + "." + b; + } + public string GetUniqueModuleName() + { + return SerializedModule.Concat(string.Empty + this.m_Object.targetObject.GetInstanceID(), this.m_ModuleName); + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedObject.cs b/UnityEditor/UnityEditor/SerializedObject.cs new file mode 100644 index 00000000..391396c6 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedObject.cs @@ -0,0 +1,110 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class SerializedObject + { + private IntPtr m_Property; + public extern UnityEngine.Object targetObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern UnityEngine.Object[] targetObjects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool hasModifiedProperties + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern InspectorMode inspectorMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isEditingMultipleObjects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public SerializedObject(UnityEngine.Object obj) + { + this.InternalCreate(new UnityEngine.Object[] + { + obj + }); + } + public SerializedObject(UnityEngine.Object[] objs) + { + this.InternalCreate(objs); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreate(UnityEngine.Object[] monoObjs); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Update(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetIsDifferentCacheDirty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateIfDirtyOrScript(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~SerializedObject() + { + this.Dispose(); + } + public SerializedProperty GetIterator() + { + SerializedProperty iterator_Internal = this.GetIterator_Internal(); + iterator_Internal.m_SerializedObject = this; + return iterator_Internal; + } + public SerializedProperty FindProperty(string propertyPath) + { + SerializedProperty iterator_Internal = this.GetIterator_Internal(); + iterator_Internal.m_SerializedObject = this; + if (iterator_Internal.FindPropertyInternal(propertyPath)) + { + return iterator_Internal; + } + return null; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern SerializedProperty GetIterator_Internal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Cache(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern SerializedObject LoadFromCache(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern PropertyModification ExtractPropertyModification(string propertyPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool ApplyModifiedProperties(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool ApplyModifiedPropertiesWithoutUndo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CopyFromSerializedProperty(SerializedProperty prop); + } +} diff --git a/UnityEditor/UnityEditor/SerializedProperty.cs b/UnityEditor/UnityEditor/SerializedProperty.cs new file mode 100644 index 00000000..43eff151 --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedProperty.cs @@ -0,0 +1,579 @@ +using System; +using System.Collections; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class SerializedProperty + { + private IntPtr m_Property; + internal SerializedObject m_SerializedObject; + public SerializedObject serializedObject + { + get + { + return this.m_SerializedObject; + } + } + public extern bool hasMultipleDifferentValues + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int hasMultipleDifferentValuesBitwise + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string displayName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string type + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string tooltip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string propertyPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern string arrayIndexLessPropertyPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool editable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isAnimated + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isExpanded + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasChildren + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasVisibleChildren + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isInstantiatedPrefab + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool prefabOverride + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern SerializedPropertyType propertyType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int intValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool boolValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float floatValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string stringValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color colorValue + { + get + { + Color result; + this.INTERNAL_get_colorValue(out result); + return result; + } + set + { + this.INTERNAL_set_colorValue(ref value); + } + } + public extern AnimationCurve animationCurveValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern Gradient gradientValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern UnityEngine.Object objectReferenceValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int objectReferenceInstanceIDValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern string objectReferenceStringValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern string objectReferenceTypeString + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern string layerMaskStringValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int enumValueIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string[] enumNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string[] enumDisplayNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector2 vector2Value + { + get + { + Vector2 result; + this.INTERNAL_get_vector2Value(out result); + return result; + } + set + { + this.INTERNAL_set_vector2Value(ref value); + } + } + public Vector3 vector3Value + { + get + { + Vector3 result; + this.INTERNAL_get_vector3Value(out result); + return result; + } + set + { + this.INTERNAL_set_vector3Value(ref value); + } + } + public Vector4 vector4Value + { + get + { + Vector4 result; + this.INTERNAL_get_vector4Value(out result); + return result; + } + set + { + this.INTERNAL_set_vector4Value(ref value); + } + } + public Quaternion quaternionValue + { + get + { + Quaternion result; + this.INTERNAL_get_quaternionValue(out result); + return result; + } + set + { + this.INTERNAL_set_quaternionValue(ref value); + } + } + public Rect rectValue + { + get + { + Rect result; + this.INTERNAL_get_rectValue(out result); + return result; + } + set + { + this.INTERNAL_set_rectValue(ref value); + } + } + public Bounds boundsValue + { + get + { + Bounds result; + this.INTERNAL_get_boundsValue(out result); + return result; + } + set + { + this.INTERNAL_set_boundsValue(ref value); + } + } + public extern bool isArray + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int arraySize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal SerializedProperty() + { + } + ~SerializedProperty() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool EqualContents(SerializedProperty x, SerializedProperty y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetBitAtIndexForAllTargetsImmediate(int index, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_colorValue(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_colorValue(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool ValidateObjectReferenceValue(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AppendFoldoutPPtrValue(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_vector2Value(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_vector2Value(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_vector3Value(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_vector3Value(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_vector4Value(out Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_vector4Value(ref Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_quaternionValue(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_quaternionValue(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rectValue(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rectValue(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_boundsValue(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_boundsValue(ref Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Next(bool enterChildren); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool NextVisible(bool enterChildren); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Reset(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int CountRemaining(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int CountInProperty(); + public SerializedProperty Copy() + { + SerializedProperty serializedProperty = this.CopyInternal(); + serializedProperty.m_SerializedObject = this.m_SerializedObject; + return serializedProperty; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern SerializedProperty CopyInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool DuplicateCommand(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool DeleteCommand(); + public SerializedProperty FindPropertyRelative(string relativePropertyPath) + { + SerializedProperty serializedProperty = this.Copy(); + if (serializedProperty.FindPropertyRelativeInternal(relativePropertyPath)) + { + return serializedProperty; + } + return null; + } + [ExcludeFromDocs] + public SerializedProperty GetEndProperty() + { + bool includeInvisible = false; + return this.GetEndProperty(includeInvisible); + } + public SerializedProperty GetEndProperty([DefaultValue("false")] bool includeInvisible) + { + SerializedProperty serializedProperty = this.Copy(); + if (includeInvisible) + { + serializedProperty.Next(false); + } + else + { + serializedProperty.NextVisible(false); + } + return serializedProperty; + } + [DebuggerHidden] + public IEnumerator GetEnumerator() + { + SerializedProperty.c__Iterator7 c__Iterator = new SerializedProperty.c__Iterator7(); + c__Iterator.<>f__this = this; + return c__Iterator; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool FindPropertyInternal(string propertyPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool FindPropertyRelativeInternal(string propertyPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int[] GetLayerMaskSelectedIndex(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string[] GetLayerMaskNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void ToggleLayerMaskAtIndex(int index); + public SerializedProperty GetArrayElementAtIndex(int index) + { + SerializedProperty serializedProperty = this.Copy(); + if (serializedProperty.GetArrayElementAtIndexInternal(index)) + { + return serializedProperty; + } + return null; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool GetArrayElementAtIndexInternal(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InsertArrayElementAtIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DeleteArrayElementAtIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearArray(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool MoveArrayElement(int srcIndex, int dstIndex); + internal void SetToValueOfTarget(UnityEngine.Object target) + { + SerializedProperty serializedProperty = new SerializedObject(target).FindProperty(this.propertyPath); + if (serializedProperty == null) + { + UnityEngine.Debug.LogError(target.name + " does not have the property " + this.propertyPath); + return; + } + switch (this.propertyType) + { + case SerializedPropertyType.Integer: + this.intValue = serializedProperty.intValue; + break; + case SerializedPropertyType.Boolean: + this.boolValue = serializedProperty.boolValue; + break; + case SerializedPropertyType.Float: + this.floatValue = serializedProperty.floatValue; + break; + case SerializedPropertyType.String: + this.stringValue = serializedProperty.stringValue; + break; + case SerializedPropertyType.Color: + this.colorValue = serializedProperty.colorValue; + break; + case SerializedPropertyType.ObjectReference: + this.objectReferenceValue = serializedProperty.objectReferenceValue; + break; + case SerializedPropertyType.LayerMask: + this.intValue = serializedProperty.intValue; + break; + case SerializedPropertyType.Enum: + this.enumValueIndex = serializedProperty.enumValueIndex; + break; + case SerializedPropertyType.Vector2: + this.vector2Value = serializedProperty.vector2Value; + break; + case SerializedPropertyType.Vector3: + this.vector3Value = serializedProperty.vector3Value; + break; + case SerializedPropertyType.Vector4: + this.vector4Value = serializedProperty.vector4Value; + break; + case SerializedPropertyType.Rect: + this.rectValue = serializedProperty.rectValue; + break; + case SerializedPropertyType.ArraySize: + this.intValue = serializedProperty.intValue; + break; + case SerializedPropertyType.Character: + this.intValue = serializedProperty.intValue; + break; + case SerializedPropertyType.AnimationCurve: + this.animationCurveValue = serializedProperty.animationCurveValue; + break; + case SerializedPropertyType.Bounds: + this.boundsValue = serializedProperty.boundsValue; + break; + case SerializedPropertyType.Gradient: + this.gradientValue = serializedProperty.gradientValue; + break; + } + } + } +} diff --git a/UnityEditor/UnityEditor/SerializedPropertyType.cs b/UnityEditor/UnityEditor/SerializedPropertyType.cs new file mode 100644 index 00000000..1c1f887e --- /dev/null +++ b/UnityEditor/UnityEditor/SerializedPropertyType.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEditor +{ + public enum SerializedPropertyType + { + Generic = -1, + Integer, + Boolean, + Float, + String, + Color, + ObjectReference, + LayerMask, + Enum, + Vector2, + Vector3, + Vector4, + Rect, + ArraySize, + Character, + AnimationCurve, + Bounds, + Gradient, + Quaternion + } +} diff --git a/UnityEditor/UnityEditor/SetResolutionWizard.cs b/UnityEditor/UnityEditor/SetResolutionWizard.cs new file mode 100644 index 00000000..c295e334 --- /dev/null +++ b/UnityEditor/UnityEditor/SetResolutionWizard.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SetResolutionWizard : TerrainWizard + { + public float m_TerrainWidth = 2000f; + public float m_TerrainHeight = 600f; + public float m_TerrainLength = 2000f; + public int m_HeightmapResolution = 1024; + public int m_DetailResolution = 1024; + public int m_DetailResolutionPerPatch = 16; + public int m_ControlTextureResolution = 1024; + public int m_BaseTextureResolution = 1024; + internal new void InitializeDefaults(Terrain terrain) + { + this.m_Terrain = terrain; + this.m_TerrainWidth = base.terrainData.size.x; + this.m_TerrainHeight = base.terrainData.size.y; + this.m_TerrainLength = base.terrainData.size.z; + this.m_HeightmapResolution = base.terrainData.heightmapResolution; + this.m_DetailResolution = base.terrainData.detailResolution; + this.m_DetailResolutionPerPatch = base.terrainData.detailResolutionPerPatch; + this.m_ControlTextureResolution = base.terrainData.alphamapResolution; + this.m_BaseTextureResolution = base.terrainData.baseMapResolution; + this.OnWizardUpdate(); + } + private void OnWizardCreate() + { + if (this.m_HeightmapResolution >= 4097) + { + base.isValid = false; + base.errorString = "Heightmaps above 4096x4096 in resolution are not supported"; + Debug.LogError("Heightmaps above 4096x4096 in resolution are not supported"); + return; + } + List list = new List(); + list.Add(base.terrainData); + list.AddRange(base.terrainData.alphamapTextures); + Undo.RegisterCompleteObjectUndo(list.ToArray(), "Set Resolution"); + if (base.terrainData.heightmapResolution != this.m_HeightmapResolution) + { + base.terrainData.heightmapResolution = this.m_HeightmapResolution; + } + base.terrainData.size = new Vector3(this.m_TerrainWidth, this.m_TerrainHeight, this.m_TerrainLength); + if (base.terrainData.detailResolution != this.m_DetailResolution || this.m_DetailResolutionPerPatch != base.terrainData.detailResolutionPerPatch) + { + SetResolutionWizard.ResizeDetailResolution(base.terrainData, this.m_DetailResolution, this.m_DetailResolutionPerPatch); + } + if (base.terrainData.alphamapResolution != this.m_ControlTextureResolution) + { + base.terrainData.alphamapResolution = this.m_ControlTextureResolution; + } + if (base.terrainData.baseMapResolution != this.m_BaseTextureResolution) + { + base.terrainData.baseMapResolution = this.m_BaseTextureResolution; + } + base.FlushHeightmapModification(); + } + private static void ResizeDetailResolution(TerrainData terrainData, int resolution, int resolutionPerPatch) + { + if (resolution == terrainData.detailResolution) + { + List list = new List(); + for (int i = 0; i < terrainData.detailPrototypes.Length; i++) + { + list.Add(terrainData.GetDetailLayer(0, 0, terrainData.detailWidth, terrainData.detailHeight, i)); + } + terrainData.SetDetailResolution(resolution, resolutionPerPatch); + for (int j = 0; j < list.Count; j++) + { + terrainData.SetDetailLayer(0, 0, j, list[j]); + } + } + else + { + terrainData.SetDetailResolution(resolution, resolutionPerPatch); + } + } + internal override void OnWizardUpdate() + { + base.helpString = "Please note that modifying the resolution will clear the heightmap, detail map or splatmap."; + base.OnWizardUpdate(); + if (base.terrainData != null) + { + this.m_HeightmapResolution = base.terrainData.GetAdjustedSize(this.m_HeightmapResolution); + } + if (this.m_TerrainWidth <= 0f) + { + this.m_TerrainWidth = 1f; + } + if (this.m_TerrainHeight <= 0f) + { + this.m_TerrainHeight = 1f; + } + if (this.m_TerrainLength <= 0f) + { + this.m_TerrainLength = 1f; + } + this.m_ControlTextureResolution = Mathf.Clamp(Mathf.ClosestPowerOfTwo(this.m_ControlTextureResolution), 16, 2048); + this.m_BaseTextureResolution = Mathf.Clamp(Mathf.ClosestPowerOfTwo(this.m_BaseTextureResolution), 16, 2048); + this.m_DetailResolution = Mathf.Clamp(this.m_DetailResolution, 0, 4048); + this.m_DetailResolutionPerPatch = Mathf.Clamp(this.m_DetailResolutionPerPatch, 8, 128); + } + } +} diff --git a/UnityEditor/UnityEditor/Settings.cs b/UnityEditor/UnityEditor/Settings.cs new file mode 100644 index 00000000..f28f9531 --- /dev/null +++ b/UnityEditor/UnityEditor/Settings.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +namespace UnityEditor +{ + internal class Settings + { + private static SortedList m_Prefs = new SortedList(); + internal static T Get(string name, T defaultValue) where T : IPrefType, new() + { + if (defaultValue == null) + { + throw new ArgumentException("default can not be null", "defaultValue"); + } + if (Settings.m_Prefs.ContainsKey(name)) + { + return (T)((object)Settings.m_Prefs[name]); + } + string @string = EditorPrefs.GetString(name, string.Empty); + if (@string == string.Empty) + { + Settings.Set(name, defaultValue); + return defaultValue; + } + defaultValue.FromUniqueString(@string); + Settings.Set(name, defaultValue); + return defaultValue; + } + internal static void Set(string name, T value) where T : IPrefType + { + EditorPrefs.SetString(name, value.ToUniqueString()); + Settings.m_Prefs[name] = value; + } + [DebuggerHidden] + internal static IEnumerable> Prefs() where T : IPrefType + { + Settings.c__Iterator1 c__Iterator = new Settings.c__Iterator1(); + Settings.c__Iterator1 expr_07 = c__Iterator; + expr_07.$PC = -2; + return expr_07; + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderImporter.cs b/UnityEditor/UnityEditor/ShaderImporter.cs new file mode 100644 index 00000000..cc99ecf3 --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderImporter.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class ShaderImporter : AssetImporter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Shader GetShader(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetDefaultTextures(string[] name, Texture[] textures); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture GetDefaultTexture(string name); + } +} diff --git a/UnityEditor/UnityEditor/ShaderImporterInspector.cs b/UnityEditor/UnityEditor/ShaderImporterInspector.cs new file mode 100644 index 00000000..57d2945d --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderImporterInspector.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(ShaderImporter))] + internal class ShaderImporterInspector : AssetImporterInspector + { + private List names = new List(); + private List textures = new List(); + private List dimensions = new List(); + internal override void OnHeaderControlsGUI() + { + Shader target = base.assetEditor.target as Shader; + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Open...", EditorStyles.miniButton, new GUILayoutOption[0])) + { + AssetDatabase.OpenAsset(target); + GUIUtility.ExitGUI(); + } + } + public void OnEnable() + { + this.ResetValues(); + } + private void ShowDefaultTextures(Shader shader, ShaderImporter importer) + { + for (int i = 0; i < this.names.Count; i++) + { + string name = this.names[i]; + string label = ObjectNames.NicifyVariableName(name); + Texture obj = this.textures[i]; + Texture value = null; + EditorGUI.BeginChangeCheck(); + switch (this.dimensions[i]) + { + case ShaderUtil.ShaderPropertyTexDim.TexDim2D: + value = (EditorGUILayout.ObjectField(label, obj, typeof(Texture2D), false, new GUILayoutOption[0]) as Texture2D); + break; + case ShaderUtil.ShaderPropertyTexDim.TexDimCUBE: + value = (EditorGUILayout.ObjectField(label, obj, typeof(Cubemap), false, new GUILayoutOption[0]) as Cubemap); + break; + } + if (EditorGUI.EndChangeCheck()) + { + this.textures[i] = value; + } + } + } + internal override bool HasModified() + { + if (base.HasModified()) + { + return true; + } + ShaderImporter shaderImporter = this.target as ShaderImporter; + if (shaderImporter == null) + { + return false; + } + Shader shader = shaderImporter.GetShader(); + if (shader == null) + { + return false; + } + int propertyCount = ShaderUtil.GetPropertyCount(shader); + for (int i = 0; i < propertyCount; i++) + { + string propertyName = ShaderUtil.GetPropertyName(shader, i); + for (int j = 0; j < this.names.Count; j++) + { + if (this.names[j] == propertyName && this.textures[j] != shaderImporter.GetDefaultTexture(propertyName)) + { + return true; + } + } + } + return false; + } + internal override void ResetValues() + { + base.ResetValues(); + this.names = new List(); + this.textures = new List(); + this.dimensions = new List(); + ShaderImporter shaderImporter = this.target as ShaderImporter; + if (shaderImporter == null) + { + return; + } + Shader shader = shaderImporter.GetShader(); + if (shader == null) + { + return; + } + int propertyCount = ShaderUtil.GetPropertyCount(shader); + for (int i = 0; i < propertyCount; i++) + { + if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) + { + string propertyName = ShaderUtil.GetPropertyName(shader, i); + Texture defaultTexture = shaderImporter.GetDefaultTexture(propertyName); + this.names.Add(propertyName); + this.textures.Add(defaultTexture); + this.dimensions.Add(ShaderUtil.GetTexDim(shader, i)); + } + } + } + internal override void Apply() + { + base.Apply(); + ShaderImporter shaderImporter = this.target as ShaderImporter; + if (shaderImporter == null) + { + return; + } + shaderImporter.SetDefaultTextures(this.names.ToArray(), this.textures.ToArray()); + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(shaderImporter)); + } + private static int GetNumberOfTextures(Shader shader) + { + int num = 0; + int propertyCount = ShaderUtil.GetPropertyCount(shader); + for (int i = 0; i < propertyCount; i++) + { + if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) + { + num++; + } + } + return num; + } + public override void OnInspectorGUI() + { + ShaderImporter shaderImporter = this.target as ShaderImporter; + if (shaderImporter == null) + { + return; + } + Shader shader = shaderImporter.GetShader(); + if (shader == null) + { + return; + } + if (ShaderImporterInspector.GetNumberOfTextures(shader) != this.names.Count) + { + this.ResetValues(); + } + this.ShowDefaultTextures(shader, shaderImporter); + base.ApplyRevertGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderInspector.cs b/UnityEditor/UnityEditor/ShaderInspector.cs new file mode 100644 index 00000000..2e38276f --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderInspector.cs @@ -0,0 +1,296 @@ +using System; +using System.Globalization; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Shader))] + internal class ShaderInspector : Editor + { + internal class Styles + { + public Texture2D errorIcon = EditorGUIUtility.LoadIcon("console.erroricon.sml"); + public Texture2D warningIcon = EditorGUIUtility.LoadIcon("console.warnicon.sml"); + public GUIContent showSurface = EditorGUIUtility.TextContent("ShaderInspector.ShowSurface"); + public GUIContent showCurrent = EditorGUIUtility.TextContent("ShaderInspector.ShowCurrent"); + public GUIContent showAll = EditorGUIUtility.TextContent("ShaderInspector.ShowAll"); + public GUIStyle messageStyle = "CN StatusInfo"; + public GUIStyle evenBackground = "CN EntryBackEven"; + } + internal class ShaderContextData + { + internal Shader shader; + internal int index; + internal ShaderContextData(Shader s, int i) + { + this.shader = s; + this.index = i; + } + } + private const float kSpace = 5f; + private static readonly string[] kPropertyTypes = new string[] + { + "Color: ", + "Vector: ", + "Float: ", + "Range: ", + "Texture: " + }; + private static readonly string[] kTextureTypes = new string[] + { + "No Texture?: ", + "1D texture: ", + "Texture: ", + "Volume: ", + "Cubemap: ", + "Any texture: " + }; + private static readonly string[] kShaderLevels = new string[] + { + "Fixed function", + "SM1.x", + "SM2.0", + "SM3.0", + "SM4.0", + "SM5.0" + }; + internal static ShaderInspector.Styles ms_Styles; + private static readonly int kErrorViewHash = "ShaderErrorView".GetHashCode(); + private Vector2 m_ScrollPosition = Vector2.zero; + public virtual void OnEnable() + { + Shader s = this.target as Shader; + ShaderUtil.FetchCachedErrors(s); + } + private static string GetPropertyType(Shader s, int index) + { + ShaderUtil.ShaderPropertyType propertyType = ShaderUtil.GetPropertyType(s, index); + if (propertyType == ShaderUtil.ShaderPropertyType.TexEnv) + { + return ShaderInspector.kTextureTypes[(int)ShaderUtil.GetTexDim(s, index)]; + } + return ShaderInspector.kPropertyTypes[(int)propertyType]; + } + public override void OnInspectorGUI() + { + if (ShaderInspector.ms_Styles == null) + { + ShaderInspector.ms_Styles = new ShaderInspector.Styles(); + } + Shader shader = this.target as Shader; + if (shader == null) + { + return; + } + GUI.enabled = true; + EditorGUI.indentLevel = 0; + if (!shader.isSupported) + { + GUILayout.Label("Shader has errors or is not supported by your graphics card", EditorStyles.helpBox, new GUILayoutOption[0]); + } + ShaderInspector.ShowSurfaceShaderButton(shader); + if (shader.isSupported) + { + EditorGUILayout.LabelField("Cast shadows", (!ShaderUtil.HasShadowCasterPass(shader) || !ShaderUtil.HasShadowCollectorPass(shader)) ? "no" : "yes", new GUILayoutOption[0]); + EditorGUILayout.LabelField("Render queue", ShaderUtil.GetRenderQueue(shader).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[0]); + EditorGUILayout.LabelField("LOD", ShaderUtil.GetLOD(shader).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[0]); + EditorGUILayout.LabelField("Geometry", ShaderUtil.GetSourceChannels(shader), new GUILayoutOption[0]); + EditorGUILayout.LabelField("Vertex shader", ShaderInspector.kShaderLevels[(int)ShaderUtil.GetVertexModel(shader)], new GUILayoutOption[0]); + EditorGUILayout.LabelField("Fragment shader", ShaderInspector.kShaderLevels[(int)ShaderUtil.GetFragmentModel(shader)], new GUILayoutOption[0]); + EditorGUILayout.LabelField("Ignore projector", (!ShaderUtil.DoesIgnoreProjector(shader)) ? "no" : "yes", new GUILayoutOption[0]); + ShaderInspector.ShowShaderProperties(shader); + } + this.ShowShaderErrors(shader); + ShaderInspector.ShowDebuggingData(shader); + } + private static void ShowShaderProperties(Shader s) + { + GUILayout.Space(5f); + GUILayout.Label("Properties:", EditorStyles.boldLabel, new GUILayoutOption[0]); + int propertyCount = ShaderUtil.GetPropertyCount(s); + for (int i = 0; i < propertyCount; i++) + { + string propertyName = ShaderUtil.GetPropertyName(s, i); + string label = ShaderInspector.GetPropertyType(s, i) + ShaderUtil.GetPropertyDescription(s, i); + EditorGUILayout.LabelField(propertyName, label, new GUILayoutOption[0]); + } + } + private static void ShowShaderVariantsUI(Shader s) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Variants", EditorStyles.miniButton); + GUILayout.Label(ShaderUtil.GetComboCount(s).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + if (GUILayout.Button("Show", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + ShaderUtil.OpenShaderCombinations(s); + GUIUtility.ExitGUI(); + } + EditorGUILayout.EndHorizontal(); + } + private static void ShowCompiledShaderButtons(Shader s) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Compiled code", EditorStyles.miniButton); + if (GUILayout.Button(ShaderInspector.ms_Styles.showCurrent, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + ShaderUtil.OpenCompiledShader(s, false); + GUIUtility.ExitGUI(); + } + if (GUILayout.Button(ShaderInspector.ms_Styles.showAll, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + ShaderUtil.OpenCompiledShader(s, true); + GUIUtility.ExitGUI(); + } + EditorGUILayout.EndHorizontal(); + } + private void CopyShaderError(object o) + { + ShaderInspector.ShaderContextData shaderContextData = o as ShaderInspector.ShaderContextData; + if (shaderContextData == null) + { + return; + } + string shaderErrorMessage = ShaderUtil.GetShaderErrorMessage(shaderContextData.shader, shaderContextData.index); + EditorGUIUtility.systemCopyBuffer = shaderErrorMessage; + } + private void ShowShaderErrors(Shader s) + { + int errorCount = ShaderUtil.GetErrorCount(s); + if (errorCount < 1) + { + return; + } + GUILayout.Space(5f); + GUILayout.Label("Errors:", EditorStyles.boldLabel, new GUILayoutOption[0]); + int controlID = GUIUtility.GetControlID(ShaderInspector.kErrorViewHash, FocusType.Native); + float minHeight = Mathf.Min((float)errorCount * 20f + 40f, 150f); + this.m_ScrollPosition = GUILayout.BeginScrollView(this.m_ScrollPosition, GUISkin.current.box, new GUILayoutOption[] + { + GUILayout.MinHeight(minHeight) + }); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + float height = ShaderInspector.ms_Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(ShaderInspector.ms_Styles.errorIcon), 100f); + Event current = Event.current; + for (int i = 0; i < errorCount; i++) + { + Rect controlRect = EditorGUILayout.GetControlRect(false, height, new GUILayoutOption[0]); + string shaderErrorMessage = ShaderUtil.GetShaderErrorMessage(s, i); + string shaderErrorPlatform = ShaderUtil.GetShaderErrorPlatform(s, i); + bool shaderErrorWarning = ShaderUtil.GetShaderErrorWarning(s, i); + string shaderErrorFile = ShaderUtil.GetShaderErrorFile(s, i, true); + int shaderErrorLine = ShaderUtil.GetShaderErrorLine(s, i); + if (current.type == EventType.MouseDown && current.button == 0 && controlRect.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = controlID; + if (current.clickCount == 2) + { + string shaderErrorFile2 = ShaderUtil.GetShaderErrorFile(s, i, false); + UnityEngine.Object @object = (!string.IsNullOrEmpty(shaderErrorFile2)) ? AssetDatabase.LoadMainAssetAtPath(shaderErrorFile2) : null; + if (@object != null) + { + AssetDatabase.OpenAsset(@object, shaderErrorLine); + } + else + { + AssetDatabase.OpenAsset(s, shaderErrorLine); + } + GUIUtility.ExitGUI(); + } + current.Use(); + } + if (current.type == EventType.ContextClick && controlRect.Contains(current.mousePosition)) + { + current.Use(); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Copy error text"), false, new GenericMenu.MenuFunction2(this.CopyShaderError), new ShaderInspector.ShaderContextData(s, i)); + genericMenu.ShowAsContext(); + } + if (current.type == EventType.Repaint && (i & 1) == 0) + { + GUIStyle evenBackground = ShaderInspector.ms_Styles.evenBackground; + evenBackground.Draw(controlRect, false, false, false, false); + } + Rect rect = controlRect; + rect.xMin = rect.xMax; + if (shaderErrorLine > 0) + { + GUIContent content; + if (string.IsNullOrEmpty(shaderErrorFile)) + { + content = EditorGUIUtility.TempContent(shaderErrorLine.ToString(CultureInfo.InvariantCulture)); + } + else + { + content = EditorGUIUtility.TempContent(shaderErrorFile + ":" + shaderErrorLine.ToString(CultureInfo.InvariantCulture)); + } + Vector2 vector = EditorStyles.miniLabel.CalcSize(content); + rect.xMin -= vector.x; + GUI.Label(rect, content, EditorStyles.miniLabel); + rect.xMin -= 2f; + if (rect.width < 30f) + { + rect.xMin = rect.xMax - 30f; + } + } + Rect position = rect; + position.width = 0f; + if (shaderErrorPlatform.Length > 0) + { + GUIContent content2 = EditorGUIUtility.TempContent(shaderErrorPlatform); + Vector2 vector2 = EditorStyles.miniLabel.CalcSize(content2); + position.xMin -= vector2.x; + Color contentColor = GUI.contentColor; + GUI.contentColor = new Color(1f, 1f, 1f, 0.5f); + GUI.Label(position, content2, EditorStyles.miniLabel); + GUI.contentColor = contentColor; + position.xMin -= 2f; + } + Rect position2 = controlRect; + position2.xMax = position.xMin; + GUI.Label(position2, EditorGUIUtility.TempContent(shaderErrorMessage, (!shaderErrorWarning) ? ShaderInspector.ms_Styles.errorIcon : ShaderInspector.ms_Styles.warningIcon), ShaderInspector.ms_Styles.messageStyle); + } + EditorGUIUtility.SetIconSize(Vector2.zero); + GUILayout.EndScrollView(); + } + private static void ShowDebuggingData(Shader s) + { + GUILayout.Space(5f); + GUILayout.Label("Debugging:", EditorStyles.boldLabel, new GUILayoutOption[0]); + ShaderInspector.ShowCompiledShaderButtons(s); + ShaderInspector.ShowShaderVariantsUI(s); + } + private static void ShowSurfaceShaderButton(Shader s) + { + bool flag = ShaderUtil.HasSurfaceShaders(s); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Surface shader", EditorStyles.miniButton); + if (flag) + { + if (GUILayout.Button(ShaderInspector.ms_Styles.showSurface, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + ShaderUtil.OpenParsedSurfaceShader(s); + GUIUtility.ExitGUI(); + } + } + else + { + GUILayout.Label("no", new GUILayoutOption[0]); + } + EditorGUILayout.EndHorizontal(); + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderUtil.cs b/UnityEditor/UnityEditor/ShaderUtil.cs new file mode 100644 index 00000000..c3302049 --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderUtil.cs @@ -0,0 +1,244 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class ShaderUtil + { + public enum ShaderPropertyType + { + Color, + Vector, + Float, + Range, + TexEnv + } + public enum ShaderPropertyTexDim + { + TexDimUnknown = -1, + TexDimNone, + TexDimDeprecated1D, + TexDim2D, + TexDim3D, + TexDimCUBE, + TexDimAny, + TexDimRECT = 5 + } + internal enum ShaderModel + { + None, + SM1, + SM2, + SM3, + SM4, + SM5 + } + internal static Rect rawViewportRect + { + get + { + Rect result; + ShaderUtil.INTERNAL_get_rawViewportRect(out result); + return result; + } + set + { + ShaderUtil.INTERNAL_set_rawViewportRect(ref value); + } + } + internal static Rect rawScissorRect + { + get + { + Rect result; + ShaderUtil.INTERNAL_get_rawScissorRect(out result); + return result; + } + set + { + ShaderUtil.INTERNAL_set_rawScissorRect(ref value); + } + } + public static extern bool hardwareSupportsRectRenderTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern bool hardwareSupportsFullNPOT + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern bool wireframeMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void FetchCachedErrors(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetErrorCount(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetShaderErrorMessage(Shader s, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetShaderErrorPlatform(Shader s, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetShaderErrorWarning(Shader s, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetShaderErrorFile(Shader s, int index, bool fileNameOnly); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetShaderErrorLine(Shader s, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSnippetCount(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSnippetSize(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetComboCount(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasSurfaceShaders(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPropertyCount(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetPropertyDescription(Shader s, int propertyIdx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetPropertyName(Shader s, int propertyIdx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ShaderUtil.ShaderPropertyType GetPropertyType(Shader s, int propertyIdx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetRangeLimits(Shader s, int propertyIdx, int defminmax); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ShaderUtil.ShaderPropertyTexDim GetTexDim(Shader s, int propertyIdx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetTextureDimension(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsShaderPropertyHidden(Shader s, int propertyIdx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetShaderPropertyAttribute(Shader s, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasShadowCasterPass(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasShadowCollectorPass(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasTangentChannel(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetSourceChannels(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool DoesIgnoreProjector(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetRenderQueue(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetLOD(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetFallback(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSubShaderCount(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetDependency(Shader s, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern ShaderUtil.ShaderModel GetVertexModel(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern ShaderUtil.ShaderModel GetFragmentModel(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool DoesShaderContainFixedFunctionPasses(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void OpenCompiledShader(Shader shader, bool allPlatforms); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void OpenParsedSurfaceShader(Shader shader); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void OpenShaderSnippets(Shader shader); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void OpenShaderCombinations(Shader shader); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_rawViewportRect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_rawViewportRect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_rawScissorRect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_rawScissorRect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasClip(Shader s); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void RecreateGfxDevice(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void RecreateSkinnedMeshResources(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Shader CreateShaderAsset(string source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UpdateShaderAsset(Shader shader, string source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern MaterialProperty[] GetMaterialProperties(UnityEngine.Object[] mats); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, string name); + internal static MaterialProperty GetMaterialProperty(UnityEngine.Object[] mats, int propertyIndex) + { + return ShaderUtil.GetMaterialProperty_Index(mats, propertyIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern MaterialProperty GetMaterialProperty_Index(UnityEngine.Object[] mats, int propertyIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ApplyProperty(MaterialProperty prop, int propertyMask, string undoName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ApplyMaterialPropertyBlockToMaterialProperty(MaterialPropertyBlock propertyBlock, MaterialProperty materialProperty); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ApplyMaterialPropertyToMaterialPropertyBlock(MaterialProperty materialProperty, int propertyMask, MaterialPropertyBlock propertyBlock); + } +} diff --git a/UnityEditor/UnityEditor/ShapeModuleUI.cs b/UnityEditor/UnityEditor/ShapeModuleUI.cs new file mode 100644 index 00000000..4986d5bd --- /dev/null +++ b/UnityEditor/UnityEditor/ShapeModuleUI.cs @@ -0,0 +1,301 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ShapeModuleUI : ModuleUI + { + private enum ShapeTypes + { + Sphere, + SphereShell, + HemiSphere, + HemiSphereShell, + Cone, + Box, + Mesh, + ConeShell, + ConeVolume, + ConeVolumeShell + } + private class Texts + { + public GUIContent shape = new GUIContent("Shape", "Defines the shape of the volume from which particles can be emitted, and the direction of the start velocity."); + public GUIContent radius = new GUIContent("Radius", "Radius of the shape."); + public GUIContent coneAngle = new GUIContent("Angle", "Angle of the cone."); + public GUIContent coneLength = new GUIContent("Length", "Length of the cone."); + public GUIContent boxX = new GUIContent("Box X", "Scale of the box in X Axis."); + public GUIContent boxY = new GUIContent("Box Y", "Scale of the box in Y Axis."); + public GUIContent boxZ = new GUIContent("Box Z", "Scale of the box in Z Axis."); + public GUIContent mesh = new GUIContent("Mesh", "Mesh that the particle system will emit from."); + public GUIContent randomDirection = new GUIContent("Random Direction", "Randomizes the starting direction of particles."); + public GUIContent emitFromShell = new GUIContent("Emit from Shell", "Emit from shell of the sphere. If disabled particles will be emitted from the volume of the shape."); + public GUIContent emitFrom = new GUIContent("Emit from:", "Specifies from where particles are emitted."); + } + private SerializedProperty m_Type; + private SerializedProperty m_RandomDirection; + private SerializedProperty m_Radius; + private SerializedProperty m_Angle; + private SerializedProperty m_Length; + private SerializedProperty m_BoxX; + private SerializedProperty m_BoxY; + private SerializedProperty m_BoxZ; + private SerializedProperty m_PlacementMode; + private SerializedProperty m_Mesh; + private Material m_Material; + private static int s_BoxHash = "BoxColliderEditor".GetHashCode(); + private BoxEditor m_BoxEditor = new BoxEditor(true, ShapeModuleUI.s_BoxHash); + private static Color s_ShapeGizmoColor = new Color(0.5803922f, 0.8980392f, 1f, 0.9f); + private string[] m_GuiNames = new string[] + { + "Sphere", + "HemiSphere", + "Cone", + "Box", + "Mesh" + }; + private ShapeModuleUI.ShapeTypes[] m_GuiTypes = new ShapeModuleUI.ShapeTypes[] + { + ShapeModuleUI.ShapeTypes.Sphere, + ShapeModuleUI.ShapeTypes.HemiSphere, + ShapeModuleUI.ShapeTypes.Cone, + ShapeModuleUI.ShapeTypes.Box, + ShapeModuleUI.ShapeTypes.Mesh + }; + private int[] m_TypeToGuiTypeIndex = new int[] + { + 0, + 0, + 1, + 1, + 2, + 3, + 4, + 2, + 2, + 2 + }; + private static ShapeModuleUI.Texts s_Texts = new ShapeModuleUI.Texts(); + public ShapeModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ShapeModule", displayName, ModuleUI.VisibilityState.VisibleAndFolded) + { + this.m_ToolTip = "Shape of the emitter volume, which controls where particles are emitted and their initial direction."; + } + protected override void Init() + { + if (this.m_Type != null) + { + return; + } + if (ShapeModuleUI.s_Texts == null) + { + ShapeModuleUI.s_Texts = new ShapeModuleUI.Texts(); + } + this.m_Type = base.GetProperty("type"); + this.m_Radius = base.GetProperty("radius"); + this.m_Angle = base.GetProperty("angle"); + this.m_Length = base.GetProperty("length"); + this.m_BoxX = base.GetProperty("boxX"); + this.m_BoxY = base.GetProperty("boxY"); + this.m_BoxZ = base.GetProperty("boxZ"); + this.m_PlacementMode = base.GetProperty("placementMode"); + this.m_Mesh = base.GetProperty("m_Mesh"); + this.m_RandomDirection = base.GetProperty("randomDirection"); + this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Diffuse.mat") as Material); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + } + public override float GetXAxisScalar() + { + return this.m_ParticleSystemUI.GetEmitterDuration(); + } + private ShapeModuleUI.ShapeTypes ConvertConeEmitFromToConeType(int emitFrom) + { + if (emitFrom == 0) + { + return ShapeModuleUI.ShapeTypes.Cone; + } + if (emitFrom == 1) + { + return ShapeModuleUI.ShapeTypes.ConeShell; + } + if (emitFrom == 2) + { + return ShapeModuleUI.ShapeTypes.ConeVolume; + } + return ShapeModuleUI.ShapeTypes.ConeVolumeShell; + } + private int ConvertConeTypeToConeEmitFrom(ShapeModuleUI.ShapeTypes shapeType) + { + if (shapeType == ShapeModuleUI.ShapeTypes.Cone) + { + return 0; + } + if (shapeType == ShapeModuleUI.ShapeTypes.ConeShell) + { + return 1; + } + if (shapeType == ShapeModuleUI.ShapeTypes.ConeVolume) + { + return 2; + } + if (shapeType == ShapeModuleUI.ShapeTypes.ConeVolumeShell) + { + return 3; + } + return 0; + } + private bool GetUsesShell(ShapeModuleUI.ShapeTypes shapeType) + { + return shapeType == ShapeModuleUI.ShapeTypes.HemiSphereShell || shapeType == ShapeModuleUI.ShapeTypes.SphereShell || shapeType == ShapeModuleUI.ShapeTypes.ConeShell || shapeType == ShapeModuleUI.ShapeTypes.ConeVolumeShell; + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (ShapeModuleUI.s_Texts == null) + { + ShapeModuleUI.s_Texts = new ShapeModuleUI.Texts(); + } + int num = this.m_Type.intValue; + int num2 = this.m_TypeToGuiTypeIndex[num]; + bool usesShell = this.GetUsesShell((ShapeModuleUI.ShapeTypes)num); + int num3 = ModuleUI.GUIPopup(ShapeModuleUI.s_Texts.shape, num2, this.m_GuiNames); + ShapeModuleUI.ShapeTypes shapeTypes = this.m_GuiTypes[num3]; + if (num3 != num2) + { + num = (int)shapeTypes; + } + switch (shapeTypes) + { + case ShapeModuleUI.ShapeTypes.Sphere: + { + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.radius, this.m_Radius); + bool flag = ModuleUI.GUIToggle(ShapeModuleUI.s_Texts.emitFromShell, usesShell); + num = ((!flag) ? 0 : 1); + break; + } + case ShapeModuleUI.ShapeTypes.HemiSphere: + { + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.radius, this.m_Radius); + bool flag2 = ModuleUI.GUIToggle(ShapeModuleUI.s_Texts.emitFromShell, usesShell); + num = ((!flag2) ? 2 : 3); + break; + } + case ShapeModuleUI.ShapeTypes.Cone: + { + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.coneAngle, this.m_Angle); + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.radius, this.m_Radius); + bool disabled = num != 8 && num != 9; + EditorGUI.BeginDisabledGroup(disabled); + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.coneLength, this.m_Length); + EditorGUI.EndDisabledGroup(); + string[] options = new string[] + { + "Base", + "Base Shell", + "Volume", + "Volume Shell" + }; + int num4 = this.ConvertConeTypeToConeEmitFrom((ShapeModuleUI.ShapeTypes)num); + num4 = ModuleUI.GUIPopup(ShapeModuleUI.s_Texts.emitFrom, num4, options); + num = (int)this.ConvertConeEmitFromToConeType(num4); + break; + } + case ShapeModuleUI.ShapeTypes.Box: + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.boxX, this.m_BoxX); + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.boxY, this.m_BoxY); + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.boxZ, this.m_BoxZ); + break; + case ShapeModuleUI.ShapeTypes.Mesh: + { + string[] options2 = new string[] + { + "Vertex", + "Edge", + "Triangle" + }; + ModuleUI.GUIPopup(string.Empty, this.m_PlacementMode, options2); + ModuleUI.GUIObject(ShapeModuleUI.s_Texts.mesh, this.m_Mesh); + break; + } + } + this.m_Type.intValue = num; + ModuleUI.GUIToggle(ShapeModuleUI.s_Texts.randomDirection, this.m_RandomDirection); + } + public override void OnSceneGUI(ParticleSystem s, InitialModuleUI initial) + { + Color color = Handles.color; + Handles.color = ShapeModuleUI.s_ShapeGizmoColor; + Matrix4x4 matrix = Handles.matrix; + Matrix4x4 matrix4x = default(Matrix4x4); + matrix4x.SetTRS(s.transform.position, s.transform.rotation, s.transform.lossyScale); + Handles.matrix = matrix4x; + EditorGUI.BeginChangeCheck(); + int intValue = this.m_Type.intValue; + if (intValue == 0 || intValue == 1) + { + this.m_Radius.floatValue = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, this.m_Radius.floatValue, false); + } + else + { + if (intValue == 2 || intValue == 3) + { + this.m_Radius.floatValue = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, this.m_Radius.floatValue, true); + } + else + { + if (intValue == 4 || intValue == 7) + { + Vector3 radiusAngleRange = new Vector3(this.m_Radius.floatValue, this.m_Angle.floatValue, initial.m_Speed.scalar.floatValue); + radiusAngleRange = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusAngleRange); + this.m_Radius.floatValue = radiusAngleRange.x; + this.m_Angle.floatValue = radiusAngleRange.y; + initial.m_Speed.scalar.floatValue = radiusAngleRange.z; + } + else + { + if (intValue == 8 || intValue == 9) + { + Vector3 radiusAngleRange2 = new Vector3(this.m_Radius.floatValue, this.m_Angle.floatValue, this.m_Length.floatValue); + radiusAngleRange2 = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusAngleRange2); + this.m_Radius.floatValue = radiusAngleRange2.x; + this.m_Angle.floatValue = radiusAngleRange2.y; + this.m_Length.floatValue = radiusAngleRange2.z; + } + else + { + if (intValue == 5) + { + Vector3 zero = Vector3.zero; + Vector3 vector = new Vector3(this.m_BoxX.floatValue, this.m_BoxY.floatValue, this.m_BoxZ.floatValue); + if (this.m_BoxEditor.OnSceneGUI(matrix4x, ShapeModuleUI.s_ShapeGizmoColor, false, ref zero, ref vector)) + { + this.m_BoxX.floatValue = vector.x; + this.m_BoxY.floatValue = vector.y; + this.m_BoxZ.floatValue = vector.z; + } + } + else + { + if (intValue == 6) + { + Mesh mesh = (Mesh)this.m_Mesh.objectReferenceValue; + if (mesh) + { + bool wireframeMode = ShaderUtil.wireframeMode; + ShaderUtil.wireframeMode = true; + this.m_Material.SetPass(0); + Graphics.DrawMeshNow(mesh, s.transform.localToWorldMatrix); + ShaderUtil.wireframeMode = wireframeMode; + } + } + } + } + } + } + } + if (EditorGUI.EndChangeCheck()) + { + this.m_ParticleSystemUI.m_ParticleEffectUI.m_Owner.Repaint(); + } + Handles.color = color; + Handles.matrix = matrix; + } + } +} diff --git a/UnityEditor/UnityEditor/ShowMode.cs b/UnityEditor/UnityEditor/ShowMode.cs new file mode 100644 index 00000000..44606a8c --- /dev/null +++ b/UnityEditor/UnityEditor/ShowMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + internal enum ShowMode + { + NormalWindow, + PopupMenu, + Utility, + NoShadow, + MainWindow, + AuxWindow + } +} diff --git a/UnityEditor/UnityEditor/SimpleProfiler.cs b/UnityEditor/UnityEditor/SimpleProfiler.cs new file mode 100644 index 00000000..865e12a8 --- /dev/null +++ b/UnityEditor/UnityEditor/SimpleProfiler.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using UnityEngine; +namespace UnityEditor +{ + internal class SimpleProfiler + { + private static Stack m_Names = new Stack(); + private static Stack m_StartTime = new Stack(); + private static Dictionary m_Timers = new Dictionary(); + [Conditional("SIMPLE_PROFILER")] + public static void Begin(string label) + { + SimpleProfiler.m_Names.Push(label); + SimpleProfiler.m_StartTime.Push(Time.realtimeSinceStartup); + } + [Conditional("SIMPLE_PROFILER")] + public static void End() + { + string text = SimpleProfiler.m_Names.Pop(); + float num = Time.realtimeSinceStartup - SimpleProfiler.m_StartTime.Pop(); + if (SimpleProfiler.m_Timers.ContainsKey(text)) + { + Dictionary timers; + Dictionary expr_31 = timers = SimpleProfiler.m_Timers; + string key; + string expr_34 = key = text; + float num2 = timers[key]; + expr_31[expr_34] = num2 + num; + } + else + { + SimpleProfiler.m_Timers[text] = num; + } + } + [Conditional("SIMPLE_PROFILER")] + public static void PrintTimes() + { + string text = "Measured execution times:\n----------------------------\n"; + foreach (KeyValuePair current in SimpleProfiler.m_Timers) + { + text += string.Format("{0,6:0.0} ms: {1}\n", current.Value * 1000f, current.Key); + } + UnityEngine.Debug.Log(text); + SimpleProfiler.m_Names.Clear(); + SimpleProfiler.m_StartTime.Clear(); + SimpleProfiler.m_Timers.Clear(); + } + } +} diff --git a/UnityEditor/UnityEditor/SizeByVelocityModuleUI.cs b/UnityEditor/UnityEditor/SizeByVelocityModuleUI.cs new file mode 100644 index 00000000..e2692bc2 --- /dev/null +++ b/UnityEditor/UnityEditor/SizeByVelocityModuleUI.cs @@ -0,0 +1,43 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SizeByVelocityModuleUI : ModuleUI + { + private class Texts + { + public GUIContent velocityRange = new GUIContent("Speed Range", "Remaps speed in the defined range to a size."); + public GUIContent size = new GUIContent("Size", "Controls the size of each particle based on its speed."); + } + private static SizeByVelocityModuleUI.Texts s_Texts; + private SerializedMinMaxCurve m_Curve; + private SerializedProperty m_Range; + public SizeByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "SizeBySpeedModule", displayName) + { + this.m_ToolTip = "Controls the size of each particle based on its speed."; + } + protected override void Init() + { + if (this.m_Curve != null) + { + return; + } + if (SizeByVelocityModuleUI.s_Texts == null) + { + SizeByVelocityModuleUI.s_Texts = new SizeByVelocityModuleUI.Texts(); + } + this.m_Curve = new SerializedMinMaxCurve(this, SizeByVelocityModuleUI.s_Texts.size); + this.m_Curve.m_AllowConstant = false; + this.m_Range = base.GetProperty("range"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (SizeByVelocityModuleUI.s_Texts == null) + { + SizeByVelocityModuleUI.s_Texts = new SizeByVelocityModuleUI.Texts(); + } + ModuleUI.GUIMinMaxCurve(SizeByVelocityModuleUI.s_Texts.size, this.m_Curve); + ModuleUI.GUIMinMaxRange(SizeByVelocityModuleUI.s_Texts.velocityRange, this.m_Range); + } + } +} diff --git a/UnityEditor/UnityEditor/SizeModuleUI.cs b/UnityEditor/UnityEditor/SizeModuleUI.cs new file mode 100644 index 00000000..3cc42fb0 --- /dev/null +++ b/UnityEditor/UnityEditor/SizeModuleUI.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SizeModuleUI : ModuleUI + { + private SerializedMinMaxCurve m_Curve; + private GUIContent m_SizeText = new GUIContent("Size", "Controls the size of each particle during its lifetime."); + public SizeModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "SizeModule", displayName) + { + this.m_ToolTip = "Controls the size of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_Curve != null) + { + return; + } + this.m_Curve = new SerializedMinMaxCurve(this, this.m_SizeText); + this.m_Curve.m_AllowConstant = false; + } + public override void OnInspectorGUI(ParticleSystem s) + { + ModuleUI.GUIMinMaxCurve(this.m_SizeText, this.m_Curve); + } + } +} diff --git a/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs b/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs new file mode 100644 index 00000000..ac2934bc --- /dev/null +++ b/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SkinnedMeshRenderer))] + internal class SkinnedMeshRendererEditor : Editor + { + private static int s_BoxHash = "SkinnedMeshRendererEditor".GetHashCode(); + private SerializedProperty m_CastShadows; + private SerializedProperty m_ReceiveShadows; + private SerializedProperty m_Materials; + private SerializedProperty m_UseLightProbes; + private SerializedProperty m_LightProbeAnchor; + private SerializedProperty m_AABB; + private SerializedProperty m_DirtyAABB; + private SerializedProperty m_BlendShapeWeights; + private BoxEditor m_BoxEditor = new BoxEditor(false, SkinnedMeshRendererEditor.s_BoxHash); + public void OnEnable() + { + this.m_CastShadows = base.serializedObject.FindProperty("m_CastShadows"); + this.m_ReceiveShadows = base.serializedObject.FindProperty("m_ReceiveShadows"); + this.m_Materials = base.serializedObject.FindProperty("m_Materials"); + this.m_UseLightProbes = base.serializedObject.FindProperty("m_UseLightProbes"); + this.m_LightProbeAnchor = base.serializedObject.FindProperty("m_LightProbeAnchor"); + this.m_BlendShapeWeights = base.serializedObject.FindProperty("m_BlendShapeWeights"); + this.m_AABB = base.serializedObject.FindProperty("m_AABB"); + this.m_DirtyAABB = base.serializedObject.FindProperty("m_DirtyAABB"); + this.m_BoxEditor.OnEnable(); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + } + public void OnDisable() + { + this.m_BoxEditor.OnDisable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + this.OnBlendShapeUI(); + EditorGUILayout.PropertyField(this.m_CastShadows, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ReceiveShadows, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Materials, true, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UseLightProbes, new GUILayoutOption[0]); + if (this.m_UseLightProbes.boolValue) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_LightProbeAnchor, new GUIContent("Anchor Override", this.m_LightProbeAnchor.tooltip), new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + Editor.DrawPropertiesExcluding(base.serializedObject, new string[] + { + "m_CastShadows", + "m_ReceiveShadows", + "m_Materials", + "m_UseLightProbes", + "m_LightProbeAnchor", + "m_BlendShapeWeights", + "m_AABB" + }); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_AABB, new GUIContent("Bounds"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_DirtyAABB.boolValue = false; + } + base.serializedObject.ApplyModifiedProperties(); + } + public void OnBlendShapeUI() + { + SkinnedMeshRenderer skinnedMeshRenderer = (SkinnedMeshRenderer)this.target; + int num = (!(skinnedMeshRenderer.sharedMesh == null)) ? skinnedMeshRenderer.sharedMesh.blendShapeCount : 0; + if (num == 0) + { + return; + } + GUIContent gUIContent = new GUIContent(); + gUIContent.text = "BlendShapes"; + EditorGUILayout.PropertyField(this.m_BlendShapeWeights, gUIContent, false, new GUILayoutOption[0]); + if (!this.m_BlendShapeWeights.isExpanded) + { + return; + } + EditorGUI.indentLevel++; + Mesh sharedMesh = skinnedMeshRenderer.sharedMesh; + int num2 = this.m_BlendShapeWeights.arraySize; + for (int i = 0; i < num; i++) + { + gUIContent.text = sharedMesh.GetBlendShapeName(i); + if (i < num2) + { + EditorGUILayout.PropertyField(this.m_BlendShapeWeights.GetArrayElementAtIndex(i), gUIContent, new GUILayoutOption[0]); + } + else + { + EditorGUI.BeginChangeCheck(); + float floatValue = EditorGUILayout.FloatField(gUIContent, 0f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_BlendShapeWeights.arraySize = num; + num2 = num; + this.m_BlendShapeWeights.GetArrayElementAtIndex(i).floatValue = floatValue; + } + } + } + EditorGUI.indentLevel--; + } + public void OnSceneGUI() + { + SkinnedMeshRenderer skinnedMeshRenderer = (SkinnedMeshRenderer)this.target; + if (skinnedMeshRenderer.updateWhenOffscreen) + { + Bounds bounds = skinnedMeshRenderer.bounds; + Vector3 center = bounds.center; + Vector3 size = bounds.size; + this.m_BoxEditor.DrawWireframeBox(center, size); + } + else + { + Bounds localBounds = skinnedMeshRenderer.localBounds; + Vector3 center2 = localBounds.center; + Vector3 size2 = localBounds.size; + if (this.m_BoxEditor.OnSceneGUI(skinnedMeshRenderer.actualRootBone, Handles.s_BoundingBoxHandleColor, false, ref center2, ref size2)) + { + Undo.RecordObject(skinnedMeshRenderer, "Resize Bounds"); + skinnedMeshRenderer.localBounds = new Bounds(center2, size2); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SliderJoint2DEditor.cs b/UnityEditor/UnityEditor/SliderJoint2DEditor.cs new file mode 100644 index 00000000..4474425a --- /dev/null +++ b/UnityEditor/UnityEditor/SliderJoint2DEditor.cs @@ -0,0 +1,40 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SliderJoint2D))] + internal class SliderJoint2DEditor : AnchoredJoint2DEditor + { + public new void OnSceneGUI() + { + SliderJoint2D sliderJoint2D = (SliderJoint2D)this.target; + if (!sliderJoint2D.enabled) + { + return; + } + Vector3 vector = Joint2DEditorBase.TransformPoint(sliderJoint2D.transform, sliderJoint2D.anchor); + Vector3 vector2 = vector; + Vector3 vector3 = vector; + Vector3 vector4 = Joint2DEditorBase.RotateVector2(Vector3.right, -sliderJoint2D.angle - sliderJoint2D.transform.eulerAngles.z); + Handles.color = Color.green; + if (sliderJoint2D.useLimits) + { + vector2 = vector + vector4 * sliderJoint2D.limits.max; + vector3 = vector + vector4 * sliderJoint2D.limits.min; + Vector3 a = Vector3.Cross(vector4, Vector3.forward); + float d = HandleUtility.GetHandleSize(vector2) * 0.16f; + float d2 = HandleUtility.GetHandleSize(vector3) * 0.16f; + Joint2DEditorBase.DrawAALine(vector2 + a * d, vector2 - a * d); + Joint2DEditorBase.DrawAALine(vector3 + a * d2, vector3 - a * d2); + } + else + { + vector4 *= HandleUtility.GetHandleSize(vector) * 0.3f; + vector2 += vector4; + vector3 -= vector4; + } + Joint2DEditorBase.DrawAALine(vector2, vector3); + base.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/SnapEdge.cs b/UnityEditor/UnityEditor/SnapEdge.cs new file mode 100644 index 00000000..d991a91f --- /dev/null +++ b/UnityEditor/UnityEditor/SnapEdge.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SnapEdge + { + public enum EdgeDir + { + Left, + Right, + CenterX, + Up, + Down, + CenterY, + None + } + private const float kSnapDist = 0f; + public UnityEngine.Object m_Object; + public float pos; + public float start; + public float end; + public float startDragPos; + public float startDragStart; + public SnapEdge.EdgeDir dir; + internal SnapEdge(UnityEngine.Object win, SnapEdge.EdgeDir _d, float _p, float _s, float _e) + { + this.dir = _d; + this.m_Object = win; + this.pos = _p; + this.start = _s; + this.end = _e; + } + public override string ToString() + { + if (this.m_Object != null) + { + return string.Concat(new object[] + { + "Edge: ", + this.dir, + " of ", + this.m_Object.name, + " pos: ", + this.pos, + " (", + this.start, + " - ", + this.end, + ")" + }); + } + return "Edge: " + this.dir + " of NULL - something is wrong!"; + } + internal static SnapEdge.EdgeDir OppositeEdge(SnapEdge.EdgeDir dir) + { + switch (dir) + { + case SnapEdge.EdgeDir.Left: + return SnapEdge.EdgeDir.Right; + case SnapEdge.EdgeDir.Right: + return SnapEdge.EdgeDir.Left; + case SnapEdge.EdgeDir.CenterX: + return SnapEdge.EdgeDir.CenterX; + case SnapEdge.EdgeDir.Up: + return SnapEdge.EdgeDir.Down; + case SnapEdge.EdgeDir.Down: + return SnapEdge.EdgeDir.Up; + } + return SnapEdge.EdgeDir.CenterY; + } + private int EdgeCoordinateIndex() + { + if (this.dir == SnapEdge.EdgeDir.Left || this.dir == SnapEdge.EdgeDir.Right || this.dir == SnapEdge.EdgeDir.CenterX) + { + return 0; + } + return 1; + } + internal static Vector2 Snap(List sourceEdges, List edgesToSnapAgainst, List>[] activeEdges) + { + Vector2 zero = Vector2.zero; + float num = 10f; + activeEdges[0].Clear(); + activeEdges[1].Clear(); + float[] array = new float[] + { + num, + num + }; + float[] array2 = new float[2]; + foreach (SnapEdge current in sourceEdges) + { + int num2 = current.EdgeCoordinateIndex(); + SnapEdge.Snap(current, edgesToSnapAgainst, ref array[num2], ref array2[num2], activeEdges[num2]); + } + zero.x = array2[0]; + zero.y = array2[1]; + return zero; + } + private static bool EdgeInside(SnapEdge edge, List frustum) + { + foreach (SnapEdge current in frustum) + { + if (!SnapEdge.ShouldEdgesSnap(edge, current)) + { + return false; + } + } + return true; + } + private static bool ShouldEdgesSnap(SnapEdge a, SnapEdge b) + { + return ((a.dir == SnapEdge.EdgeDir.CenterX || a.dir == SnapEdge.EdgeDir.CenterY) && a.dir == b.dir) || (a.dir == SnapEdge.OppositeEdge(b.dir) && (a.start <= b.end && a.end >= b.start)); + } + internal static void Snap(SnapEdge edge, List otherEdges, ref float maxDist, ref float snapVal, List> activeEdges) + { + foreach (SnapEdge current in otherEdges) + { + if (SnapEdge.ShouldEdgesSnap(edge, current)) + { + float num = Mathf.Abs(current.pos - edge.pos); + if (num < maxDist) + { + maxDist = num; + snapVal = current.pos - edge.pos; + activeEdges.Clear(); + activeEdges.Add(new KeyValuePair(edge, current)); + } + else + { + if (num == maxDist) + { + activeEdges.Add(new KeyValuePair(edge, current)); + } + } + } + } + } + internal void ApplyOffset(Vector2 offset, ref int changedEdges, bool windowMove) + { + offset = ((this.dir != SnapEdge.EdgeDir.Left && this.dir != SnapEdge.EdgeDir.Right) ? new Vector2(offset.y, offset.x) : offset); + if (windowMove) + { + this.pos += offset.x; + if (offset.x != 0f) + { + changedEdges |= 1 << (int)this.dir; + } + } + else + { + float num = this.pos; + this.pos = offset.x + this.startDragPos; + if (this.pos != num) + { + changedEdges |= 1 << (int)this.dir; + } + } + this.start += offset.y; + this.end += offset.y; + } + } +} diff --git a/UnityEditor/UnityEditor/SnapGuide.cs b/UnityEditor/UnityEditor/SnapGuide.cs new file mode 100644 index 00000000..0413efb7 --- /dev/null +++ b/UnityEditor/UnityEditor/SnapGuide.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SnapGuide + { + public float value; + public List lineVertices = new List(); + public bool safe = true; + public SnapGuide(float value, params Vector3[] vertices) : this(value, true, vertices) + { + } + public SnapGuide(float value, bool safe, params Vector3[] vertices) + { + this.value = value; + this.lineVertices.AddRange(vertices); + this.safe = safe; + } + public void Draw() + { + Handles.color = ((!this.safe) ? new Color(1f, 0.5f, 0f, 1f) : new Color(0f, 0.5f, 1f, 1f)); + for (int i = 0; i < this.lineVertices.Count; i += 2) + { + Vector3 vector = this.lineVertices[i]; + Vector3 vector2 = this.lineVertices[i + 1]; + if (!(vector == vector2)) + { + Vector3 a = (vector2 - vector).normalized * 0.05f; + vector -= a * HandleUtility.GetHandleSize(vector); + vector2 += a * HandleUtility.GetHandleSize(vector2); + Handles.DrawLine(vector, vector2); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SnapGuideCollection.cs b/UnityEditor/UnityEditor/SnapGuideCollection.cs new file mode 100644 index 00000000..d9331c6e --- /dev/null +++ b/UnityEditor/UnityEditor/SnapGuideCollection.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SnapGuideCollection + { + private List currentGuides; + private Dictionary> guides = new Dictionary>(); + public void Clear() + { + this.guides.Clear(); + } + public void AddGuide(SnapGuide guide) + { + List list; + if (!this.guides.TryGetValue(guide.value, out list)) + { + list = new List(); + this.guides.Add(guide.value, list); + } + list.Add(guide); + } + public float SnapToGuides(float value, float snapDistance) + { + if (this.guides.Count == 0) + { + return value; + } + KeyValuePair> keyValuePair = default(KeyValuePair>); + float num = float.PositiveInfinity; + foreach (KeyValuePair> current in this.guides) + { + float num2 = Mathf.Abs(value - current.Key); + if (num2 < num) + { + keyValuePair = current; + num = num2; + } + } + if (num <= snapDistance) + { + value = keyValuePair.Key; + this.currentGuides = keyValuePair.Value; + } + else + { + this.currentGuides = null; + } + return value; + } + public void OnGUI() + { + if (Event.current.type == EventType.MouseUp) + { + this.currentGuides = null; + } + } + public void DrawGuides() + { + if (this.currentGuides != null) + { + foreach (SnapGuide current in this.currentGuides) + { + current.Draw(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SnapSettings.cs b/UnityEditor/UnityEditor/SnapSettings.cs new file mode 100644 index 00000000..8a52597c --- /dev/null +++ b/UnityEditor/UnityEditor/SnapSettings.cs @@ -0,0 +1,169 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SnapSettings : EditorWindow + { + private class Styles + { + public GUIStyle buttonLeft = "ButtonLeft"; + public GUIStyle buttonMid = "ButtonMid"; + public GUIStyle buttonRight = "ButtonRight"; + public GUIContent snapAllAxes = EditorGUIUtility.TextContent("Snap.SnapAllAxes"); + public GUIContent snapX = EditorGUIUtility.TextContent("Snap.SnapX"); + public GUIContent snapY = EditorGUIUtility.TextContent("Snap.SnapY"); + public GUIContent snapZ = EditorGUIUtility.TextContent("Snap.SnapZ"); + public GUIContent moveX = EditorGUIUtility.TextContent("Snap.MoveX"); + public GUIContent moveY = EditorGUIUtility.TextContent("Snap.MoveY"); + public GUIContent moveZ = EditorGUIUtility.TextContent("Snap.MoveZ"); + public GUIContent scale = EditorGUIUtility.TextContent("Snap.Scale"); + public GUIContent rotation = EditorGUIUtility.TextContent("Snap.Rotation"); + } + private static float s_MoveSnapX; + private static float s_MoveSnapY; + private static float s_MoveSnapZ; + private static float s_ScaleSnap; + private static float s_RotationSnap; + private static bool s_Initialized; + private static SnapSettings.Styles ms_Styles; + public static Vector3 move + { + get + { + SnapSettings.Initialize(); + return new Vector3(SnapSettings.s_MoveSnapX, SnapSettings.s_MoveSnapY, SnapSettings.s_MoveSnapZ); + } + set + { + EditorPrefs.SetFloat("MoveSnapX", value.x); + SnapSettings.s_MoveSnapX = value.x; + EditorPrefs.SetFloat("MoveSnapY", value.y); + SnapSettings.s_MoveSnapY = value.y; + EditorPrefs.SetFloat("MoveSnapZ", value.z); + SnapSettings.s_MoveSnapZ = value.z; + } + } + public static float scale + { + get + { + SnapSettings.Initialize(); + return SnapSettings.s_ScaleSnap; + } + set + { + EditorPrefs.SetFloat("ScaleSnap", value); + SnapSettings.s_ScaleSnap = value; + } + } + public static float rotation + { + get + { + SnapSettings.Initialize(); + return SnapSettings.s_RotationSnap; + } + set + { + EditorPrefs.SetFloat("RotationSnap", value); + SnapSettings.s_RotationSnap = value; + } + } + private static void Initialize() + { + if (!SnapSettings.s_Initialized) + { + SnapSettings.s_MoveSnapX = EditorPrefs.GetFloat("MoveSnapX", 1f); + SnapSettings.s_MoveSnapY = EditorPrefs.GetFloat("MoveSnapY", 1f); + SnapSettings.s_MoveSnapZ = EditorPrefs.GetFloat("MoveSnapZ", 1f); + SnapSettings.s_ScaleSnap = EditorPrefs.GetFloat("ScaleSnap", 0.1f); + SnapSettings.s_RotationSnap = EditorPrefs.GetFloat("RotationSnap", 15f); + SnapSettings.s_Initialized = true; + } + } + [MenuItem("Edit/Snap Settings...")] + private static void ShowSnapSettings() + { + EditorWindow.GetWindowWithRect(new Rect(100f, 100f, 230f, 130f), true, "Snap settings"); + } + private void OnGUI() + { + if (SnapSettings.ms_Styles == null) + { + SnapSettings.ms_Styles = new SnapSettings.Styles(); + } + GUILayout.Space(5f); + EditorGUI.BeginChangeCheck(); + Vector3 move = SnapSettings.move; + move.x = EditorGUILayout.FloatField(SnapSettings.ms_Styles.moveX, move.x, new GUILayoutOption[0]); + move.y = EditorGUILayout.FloatField(SnapSettings.ms_Styles.moveY, move.y, new GUILayoutOption[0]); + move.z = EditorGUILayout.FloatField(SnapSettings.ms_Styles.moveZ, move.z, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (move.x <= 0f) + { + move.x = SnapSettings.move.x; + } + if (move.y <= 0f) + { + move.y = SnapSettings.move.y; + } + if (move.z <= 0f) + { + move.z = SnapSettings.move.z; + } + SnapSettings.move = move; + } + SnapSettings.scale = EditorGUILayout.FloatField(SnapSettings.ms_Styles.scale, SnapSettings.scale, new GUILayoutOption[0]); + SnapSettings.rotation = EditorGUILayout.FloatField(SnapSettings.ms_Styles.rotation, SnapSettings.rotation, new GUILayoutOption[0]); + GUILayout.Space(5f); + bool flag = false; + bool flag2 = false; + bool flag3 = false; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(SnapSettings.ms_Styles.snapAllAxes, SnapSettings.ms_Styles.buttonLeft, new GUILayoutOption[0])) + { + flag = true; + flag2 = true; + flag3 = true; + } + if (GUILayout.Button(SnapSettings.ms_Styles.snapX, SnapSettings.ms_Styles.buttonMid, new GUILayoutOption[0])) + { + flag = true; + } + if (GUILayout.Button(SnapSettings.ms_Styles.snapY, SnapSettings.ms_Styles.buttonMid, new GUILayoutOption[0])) + { + flag2 = true; + } + if (GUILayout.Button(SnapSettings.ms_Styles.snapZ, SnapSettings.ms_Styles.buttonRight, new GUILayoutOption[0])) + { + flag3 = true; + } + GUILayout.EndHorizontal(); + if (flag | flag2 | flag3) + { + Vector3 vector = new Vector3(1f / SnapSettings.move.x, 1f / SnapSettings.move.y, 1f / SnapSettings.move.z); + Undo.RecordObjects(Selection.transforms, "Snap " + ((Selection.transforms.Length != 1) ? " selection" : Selection.activeGameObject.name) + " to grid"); + Transform[] transforms = Selection.transforms; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + Vector3 position = transform.position; + if (flag) + { + position.x = Mathf.Round(position.x * vector.x) / vector.x; + } + if (flag2) + { + position.y = Mathf.Round(position.y * vector.y) / vector.y; + } + if (flag3) + { + position.z = Mathf.Round(position.z * vector.z) / vector.z; + } + transform.position = position; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SpaceDrawer.cs b/UnityEditor/UnityEditor/SpaceDrawer.cs new file mode 100644 index 00000000..e4b9b6b9 --- /dev/null +++ b/UnityEditor/UnityEditor/SpaceDrawer.cs @@ -0,0 +1,13 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomPropertyDrawer(typeof(SpaceAttribute))] + internal sealed class SpaceDrawer : DecoratorDrawer + { + public override float GetHeight() + { + return (base.attribute as SpaceAttribute).height; + } + } +} diff --git a/UnityEditor/UnityEditor/SphereColliderEditor.cs b/UnityEditor/UnityEditor/SphereColliderEditor.cs new file mode 100644 index 00000000..64351231 --- /dev/null +++ b/UnityEditor/UnityEditor/SphereColliderEditor.cs @@ -0,0 +1,69 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SphereCollider))] + internal class SphereColliderEditor : Collider3DEditorBase + { + private SerializedProperty m_Center; + private SerializedProperty m_Radius; + private int m_HandleControlID; + public override void OnEnable() + { + base.OnEnable(); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_HandleControlID = -1; + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + base.InspectorEditButtonGUI(); + EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public void OnSceneGUI() + { + bool flag = GUIUtility.hotControl == this.m_HandleControlID; + SphereCollider sphereCollider = (SphereCollider)this.target; + Color color = Handles.color; + if (sphereCollider.enabled) + { + Handles.color = Handles.s_ColliderHandleColor; + } + else + { + Handles.color = Handles.s_ColliderHandleColorDisabled; + } + bool enabled = GUI.enabled; + if (!base.editingCollider && !flag) + { + GUI.enabled = false; + Handles.color = new Color(0f, 0f, 0f, 0.001f); + } + Vector3 lossyScale = sphereCollider.transform.lossyScale; + float num = Mathf.Max(Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.y)), Mathf.Abs(lossyScale.z)); + float num2 = num * sphereCollider.radius; + num2 = Mathf.Abs(num2); + num2 = Mathf.Max(num2, 1E-05f); + Vector3 position = sphereCollider.transform.TransformPoint(sphereCollider.center); + Quaternion rotation = sphereCollider.transform.rotation; + int hotControl = GUIUtility.hotControl; + float num3 = Handles.RadiusHandle(rotation, position, num2, true); + if (GUI.changed) + { + Undo.RecordObject(sphereCollider, "Adjust Radius"); + sphereCollider.radius = num3 * 1f / num; + } + if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) + { + this.m_HandleControlID = GUIUtility.hotControl; + } + Handles.color = color; + GUI.enabled = enabled; + } + } +} diff --git a/UnityEditor/UnityEditor/SplatPainter.cs b/UnityEditor/UnityEditor/SplatPainter.cs new file mode 100644 index 00000000..2e591c2a --- /dev/null +++ b/UnityEditor/UnityEditor/SplatPainter.cs @@ -0,0 +1,88 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SplatPainter + { + public int size; + public float strength; + public Brush brush; + public float target; + public TerrainData terrainData; + public TerrainTool tool; + private float ApplyBrush(float height, float brushStrength) + { + if (this.target > height) + { + height += brushStrength; + height = Mathf.Min(height, this.target); + return height; + } + height -= brushStrength; + height = Mathf.Max(height, this.target); + return height; + } + private void Normalize(int x, int y, int splatIndex, float[,,] alphamap) + { + float num = alphamap[y, x, splatIndex]; + float num2 = 0f; + int length = alphamap.GetLength(2); + for (int i = 0; i < length; i++) + { + if (i != splatIndex) + { + num2 += alphamap[y, x, i]; + } + } + if ((double)num2 > 0.01) + { + float num3 = (1f - num) / num2; + for (int j = 0; j < length; j++) + { + if (j != splatIndex) + { + alphamap[y, x, j] *= num3; + } + } + } + else + { + for (int k = 0; k < length; k++) + { + alphamap[y, x, k] = ((k != splatIndex) ? 0f : 1f); + } + } + } + public void Paint(float xCenterNormalized, float yCenterNormalized, int splatIndex) + { + if (splatIndex >= this.terrainData.alphamapLayers) + { + return; + } + int num = Mathf.FloorToInt(xCenterNormalized * (float)this.terrainData.alphamapWidth); + int num2 = Mathf.FloorToInt(yCenterNormalized * (float)this.terrainData.alphamapHeight); + int num3 = Mathf.RoundToInt((float)this.size) / 2; + int num4 = Mathf.RoundToInt((float)this.size) % 2; + int num5 = Mathf.Clamp(num - num3, 0, this.terrainData.alphamapWidth - 1); + int num6 = Mathf.Clamp(num2 - num3, 0, this.terrainData.alphamapHeight - 1); + int num7 = Mathf.Clamp(num + num3 + num4, 0, this.terrainData.alphamapWidth); + int num8 = Mathf.Clamp(num2 + num3 + num4, 0, this.terrainData.alphamapHeight); + int num9 = num7 - num5; + int num10 = num8 - num6; + float[,,] alphamaps = this.terrainData.GetAlphamaps(num5, num6, num9, num10); + for (int i = 0; i < num10; i++) + { + for (int j = 0; j < num9; j++) + { + int ix = num5 + j - (num - num3 + num4); + int iy = num6 + i - (num2 - num3 + num4); + float strengthInt = this.brush.GetStrengthInt(ix, iy); + float num11 = this.ApplyBrush(alphamaps[i, j, splatIndex], strengthInt * this.strength); + alphamaps[i, j, splatIndex] = num11; + this.Normalize(j, i, splatIndex, alphamaps); + } + } + this.terrainData.SetAlphamaps(num5, num6, alphamaps); + } + } +} diff --git a/UnityEditor/UnityEditor/SplitView.cs b/UnityEditor/UnityEditor/SplitView.cs new file mode 100644 index 00000000..5a203611 --- /dev/null +++ b/UnityEditor/UnityEditor/SplitView.cs @@ -0,0 +1,804 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class SplitView : View, ICleanuppable, IDropArea + { + private class ExtraDropInfo + { + public Rect dropRect; + public int idx; + public ExtraDropInfo(Rect _dropRect, int _idx) + { + this.dropRect = _dropRect; + this.idx = _idx; + } + } + internal const float kGrabDist = 5f; + public bool vertical; + public int controlID; + private SplitterState splitState; + private static float[] s_StartDragPos; + private static float[] s_DragPos; + private void SetupSplitter() + { + int[] array = new int[base.children.Length]; + int[] array2 = new int[base.children.Length]; + for (int i = 0; i < base.children.Length; i++) + { + View view = base.children[i]; + array[i] = ((!this.vertical) ? ((int)view.position.width) : ((int)view.position.height)); + array2[i] = (int)((!this.vertical) ? view.minSize.x : view.minSize.y); + } + this.splitState = new SplitterState(array, array2, null); + this.splitState.splitSize = 10; + } + private void SetupRectsFromSplitter() + { + if (base.children.Length == 0) + { + return; + } + int num = 0; + int num2 = 0; + int[] realSizes = this.splitState.realSizes; + for (int i = 0; i < realSizes.Length; i++) + { + int num3 = realSizes[i]; + num2 += num3; + } + float num4 = 1f; + if ((float)num2 > ((!this.vertical) ? base.position.width : base.position.height)) + { + num4 = ((!this.vertical) ? base.position.width : base.position.height) / (float)num2; + } + for (int j = 0; j < base.children.Length; j++) + { + int num5 = (int)Mathf.Round((float)this.splitState.realSizes[j] * num4); + if (this.vertical) + { + base.children[j].position = new Rect(0f, (float)num, base.position.width, (float)num5); + } + else + { + base.children[j].position = new Rect((float)num, 0f, (float)num5, base.position.height); + } + num += num5; + } + } + private static void RecalcMinMaxAndReflowAll(SplitView start) + { + SplitView splitView = start; + SplitView splitView2; + do + { + splitView2 = splitView; + splitView = (splitView2.parent as SplitView); + } + while (splitView); + SplitView.RecalcMinMaxRecurse(splitView2); + SplitView.ReflowRecurse(splitView2); + } + private static void RecalcMinMaxRecurse(SplitView node) + { + View[] children = node.children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + SplitView splitView = view as SplitView; + if (splitView) + { + SplitView.RecalcMinMaxRecurse(splitView); + } + } + node.ChildrenMinMaxChanged(); + } + private static void ReflowRecurse(SplitView node) + { + node.Reflow(); + View[] children = node.children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + SplitView splitView = view as SplitView; + if (splitView) + { + SplitView.RecalcMinMaxRecurse(splitView); + } + } + } + internal override void Reflow() + { + this.SetupSplitter(); + for (int i = 0; i < base.children.Length - 1; i++) + { + this.splitState.DoSplitter(i, i + 1, 0); + } + this.splitState.RelativeToRealSizes((!this.vertical) ? ((int)base.position.width) : ((int)base.position.height)); + this.SetupRectsFromSplitter(); + } + private void PlaceView(int i, float pos, float size) + { + float num = Mathf.Round(pos); + if (this.vertical) + { + base.children[i].position = new Rect(0f, num, base.position.width, Mathf.Round(pos + size) - num); + } + else + { + base.children[i].position = new Rect(num, 0f, Mathf.Round(pos + size) - num, base.position.height); + } + } + public override void AddChild(View child, int idx) + { + base.AddChild(child, idx); + this.ChildrenMinMaxChanged(); + this.splitState = null; + } + public void RemoveChildNice(View child) + { + if (base.children.Length != 1) + { + int num = base.IndexOfChild(child); + float num2; + if (num == 0) + { + num2 = 0f; + } + else + { + if (num == base.children.Length - 1) + { + num2 = 1f; + } + else + { + num2 = 0.5f; + } + } + num2 = ((!this.vertical) ? Mathf.Lerp(child.position.xMin, child.position.xMax, num2) : Mathf.Lerp(child.position.yMin, child.position.yMax, num2)); + if (num > 0) + { + View view = base.children[num - 1]; + Rect position = view.position; + if (this.vertical) + { + position.yMax = num2; + } + else + { + position.xMax = num2; + } + view.position = position; + if (view is SplitView) + { + ((SplitView)view).Reflow(); + } + } + if (num < base.children.Length - 1) + { + View view2 = base.children[num + 1]; + Rect position2 = view2.position; + if (this.vertical) + { + view2.position = new Rect(position2.x, num2, position2.width, position2.yMax - num2); + } + else + { + view2.position = new Rect(num2, position2.y, position2.xMax - num2, position2.height); + } + if (view2 is SplitView) + { + ((SplitView)view2).Reflow(); + } + } + } + this.RemoveChild(child); + } + public override void RemoveChild(View child) + { + this.splitState = null; + base.RemoveChild(child); + } + private DropInfo DoDropZone(int idx, Vector2 mousePos, Rect sourceRect, Rect previewRect) + { + if (!sourceRect.Contains(mousePos)) + { + return null; + } + return new DropInfo(this) + { + type = DropInfo.Type.Pane, + userData = idx, + rect = previewRect + }; + } + private DropInfo CheckRootWindowDropZones(Vector2 mouseScreenPosition) + { + DropInfo dropInfo = null; + if (!(base.parent is SplitView) && (base.children.Length != 1 || !(DockArea.s_IgnoreDockingForView == base.children[0]))) + { + Rect screenPosition = base.screenPosition; + if (base.parent is MainWindow) + { + dropInfo = this.DoDropZone(-1, mouseScreenPosition, new Rect(screenPosition.x, screenPosition.yMax, screenPosition.width, 100f), new Rect(screenPosition.x, screenPosition.yMax - 200f, screenPosition.width, 200f)); + } + else + { + dropInfo = this.DoDropZone(-1, mouseScreenPosition, new Rect(screenPosition.x, screenPosition.yMax - 20f, screenPosition.width, 100f), new Rect(screenPosition.x, screenPosition.yMax - 50f, screenPosition.width, 200f)); + } + if (dropInfo != null) + { + return dropInfo; + } + dropInfo = this.DoDropZone(-2, mouseScreenPosition, new Rect(screenPosition.x - 30f, screenPosition.y, 50f, screenPosition.height), new Rect(screenPosition.x - 50f, screenPosition.y, 100f, screenPosition.height)); + if (dropInfo != null) + { + return dropInfo; + } + dropInfo = this.DoDropZone(-3, mouseScreenPosition, new Rect(screenPosition.xMax - 20f, screenPosition.y, 50f, screenPosition.height), new Rect(screenPosition.xMax - 50f, screenPosition.y, 100f, screenPosition.height)); + } + return dropInfo; + } + public DropInfo DragOver(EditorWindow w, Vector2 mouseScreenPosition) + { + DropInfo dropInfo = this.CheckRootWindowDropZones(mouseScreenPosition); + if (dropInfo != null) + { + return dropInfo; + } + for (int i = 0; i < base.children.Length; i++) + { + View view = base.children[i]; + if (!(view == DockArea.s_IgnoreDockingForView)) + { + if (!(view is SplitView)) + { + Rect screenPosition = view.screenPosition; + int num = 0; + float num2 = Mathf.Round(Mathf.Min(screenPosition.width / 3f, 300f)); + float num3 = Mathf.Round(Mathf.Min(screenPosition.height / 3f, 300f)); + Rect rect = new Rect(screenPosition.x, screenPosition.y + 39f, num2, screenPosition.height - 39f); + if (rect.Contains(mouseScreenPosition)) + { + num |= 1; + } + Rect rect2 = new Rect(screenPosition.x, screenPosition.yMax - num3, screenPosition.width, num3); + if (rect2.Contains(mouseScreenPosition)) + { + num |= 2; + } + Rect rect3 = new Rect(screenPosition.xMax - num2, screenPosition.y + 39f, num2, screenPosition.height - 39f); + if (rect3.Contains(mouseScreenPosition)) + { + num |= 4; + } + if (num == 3) + { + Vector2 vector = new Vector2(screenPosition.x, screenPosition.yMax) - mouseScreenPosition; + Vector2 vector2 = new Vector2(num2, -num3); + if (vector.x * vector2.y - vector.y * vector2.x < 0f) + { + num = 1; + } + else + { + num = 2; + } + } + else + { + if (num == 6) + { + Vector2 vector3 = new Vector2(screenPosition.xMax, screenPosition.yMax) - mouseScreenPosition; + Vector2 vector4 = new Vector2(-num2, -num3); + if (vector3.x * vector4.y - vector3.y * vector4.x < 0f) + { + num = 2; + } + else + { + num = 4; + } + } + } + float num4 = Mathf.Round(Mathf.Max(screenPosition.width / 3f, 100f)); + float num5 = Mathf.Round(Mathf.Max(screenPosition.height / 3f, 100f)); + if (this.vertical) + { + switch (num) + { + case 1: + return new DropInfo(this) + { + userData = i + 1000, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.x, screenPosition.y, num4, screenPosition.height) + }; + case 2: + return new DropInfo(this) + { + userData = i + 1, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.x, screenPosition.yMax - num5, screenPosition.width, num5) + }; + case 4: + return new DropInfo(this) + { + userData = i + 2000, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.xMax - num4, screenPosition.y, num4, screenPosition.height) + }; + } + } + else + { + switch (num) + { + case 1: + return new DropInfo(this) + { + userData = i, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.x, screenPosition.y, num4, screenPosition.height) + }; + case 2: + return new DropInfo(this) + { + userData = i + 2000, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.x, screenPosition.yMax - num5, screenPosition.width, num5) + }; + case 4: + return new DropInfo(this) + { + userData = i + 1, + type = DropInfo.Type.Pane, + rect = new Rect(screenPosition.xMax - num4, screenPosition.y, num4, screenPosition.height) + }; + } + } + } + } + } + if (base.screenPosition.Contains(mouseScreenPosition) && !(base.parent is SplitView)) + { + return new DropInfo(null); + } + return null; + } + protected override void ChildrenMinMaxChanged() + { + Vector2 zero = Vector2.zero; + Vector2 zero2 = Vector2.zero; + if (this.vertical) + { + View[] children = base.children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + zero.x = Mathf.Max(view.minSize.x, zero.x); + zero2.x = Mathf.Max(view.maxSize.x, zero2.x); + zero.y += view.minSize.y; + zero2.y += view.maxSize.y; + } + } + else + { + View[] children2 = base.children; + for (int j = 0; j < children2.Length; j++) + { + View view2 = children2[j]; + zero.x += view2.minSize.x; + zero2.x += view2.maxSize.x; + zero.y = Mathf.Max(view2.minSize.y, zero.y); + zero2.y = Mathf.Max(view2.maxSize.y, zero2.y); + } + } + this.splitState = null; + base.SetMinMaxSizes(zero, zero2); + } + public override string ToString() + { + return (!this.vertical) ? "SplitView (horiz)" : "SplitView (vert)"; + } + public bool PerformDrop(EditorWindow w, DropInfo di, Vector2 screenPos) + { + int num = (int)di.userData; + DockArea dockArea = ScriptableObject.CreateInstance(); + Rect rect = di.rect; + if (num == -1 || num == -2 || num == -3) + { + bool flag = num == -2; + bool flag2 = num == -1; + this.splitState = null; + if (this.vertical == flag2 || base.children.Length < 2) + { + this.vertical = flag2; + rect.x -= base.screenPosition.x; + rect.y -= base.screenPosition.y; + this.MakeRoomForRect(rect); + this.AddChild(dockArea, (!flag) ? base.children.Length : 0); + dockArea.position = rect; + } + else + { + SplitView splitView = ScriptableObject.CreateInstance(); + Rect position = base.position; + splitView.vertical = flag2; + splitView.position = new Rect(position.x, position.y, position.width, position.height); + if (base.window.mainView == this) + { + base.window.mainView = splitView; + } + else + { + base.parent.AddChild(splitView, base.parent.IndexOfChild(this)); + } + splitView.AddChild(this); + base.position = new Rect(0f, 0f, position.width, position.height); + Rect rect2 = rect; + rect2.x -= base.screenPosition.x; + rect2.y -= base.screenPosition.y; + splitView.MakeRoomForRect(rect2); + dockArea.position = rect2; + splitView.AddChild(dockArea, (!flag) ? 1 : 0); + } + } + else + { + if (num < 1000) + { + Rect rect3 = rect; + rect3.x -= base.screenPosition.x; + rect3.y -= base.screenPosition.y; + this.MakeRoomForRect(rect3); + this.AddChild(dockArea, num); + dockArea.position = rect3; + } + else + { + int num2 = num % 1000; + if (base.children.Length != 1) + { + SplitView splitView2 = ScriptableObject.CreateInstance(); + splitView2.vertical = !this.vertical; + Rect position2 = base.children[num2].position; + splitView2.AddChild(base.children[num2]); + this.AddChild(splitView2, num2); + splitView2.position = position2; + float num3 = 0f; + position2.y = num3; + position2.x = num3; + splitView2.children[0].position = position2; + Rect rect4 = rect; + rect4.x -= splitView2.screenPosition.x; + rect4.y -= splitView2.screenPosition.y; + splitView2.MakeRoomForRect(rect4); + splitView2.AddChild(dockArea, (num >= 2000) ? 1 : 0); + dockArea.position = rect4; + } + else + { + this.vertical = !this.vertical; + Rect rect5 = rect; + rect5.x -= base.screenPosition.x; + rect5.y -= base.screenPosition.y; + this.MakeRoomForRect(rect5); + this.AddChild(dockArea, (num != 1000) ? 1 : 0); + dockArea.position = rect5; + } + } + } + DockArea.s_OriginalDragSource.RemoveTab(w); + w.m_Parent = dockArea; + dockArea.AddTab(w); + this.Reflow(); + SplitView.RecalcMinMaxAndReflowAll(this); + dockArea.MakeVistaDWMHappyDance(); + return true; + } + private static string PosVals(float[] posVals) + { + string text = "["; + for (int i = 0; i < posVals.Length; i++) + { + float num = posVals[i]; + string text2 = text; + text = string.Concat(new object[] + { + text2, + string.Empty, + num, + ", " + }); + } + return text + "]"; + } + private void MakeRoomForRect(Rect r) + { + Rect[] array = new Rect[base.children.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = base.children[i].position; + } + this.CalcRoomForRect(array, r); + for (int j = 0; j < array.Length; j++) + { + base.children[j].position = array[j]; + } + } + private void CalcRoomForRect(Rect[] sources, Rect r) + { + float num = (!this.vertical) ? r.x : r.y; + float num2 = num + ((!this.vertical) ? r.width : r.height); + float num3 = (num + num2) * 0.5f; + int i; + for (i = 0; i < sources.Length; i++) + { + float num4 = (!this.vertical) ? (sources[i].x + sources[i].width * 0.5f) : (sources[i].y + sources[i].height * 0.5f); + if (num4 > num3) + { + break; + } + } + float num5 = num; + for (int j = i - 1; j >= 0; j--) + { + if (this.vertical) + { + sources[j].yMax = num5; + if (sources[j].height >= base.children[j].minSize.y) + { + break; + } + float num6 = sources[j].yMax - base.children[j].minSize.y; + sources[j].yMin = num6; + num5 = num6; + } + else + { + sources[j].xMax = num5; + if (sources[j].width >= base.children[j].minSize.x) + { + break; + } + float num6 = sources[j].xMax - base.children[j].minSize.x; + sources[j].xMin = num6; + num5 = num6; + } + } + if (num5 < 0f) + { + float num7 = -num5; + for (int k = 0; k < i - 1; k++) + { + if (this.vertical) + { + int expr_20A_cp_1 = k; + sources[expr_20A_cp_1].y = sources[expr_20A_cp_1].y + num7; + } + else + { + int expr_225_cp_1 = k; + sources[expr_225_cp_1].x = sources[expr_225_cp_1].x + num7; + } + } + num2 += num7; + } + num5 = num2; + for (int l = i; l < sources.Length; l++) + { + if (this.vertical) + { + float yMax = sources[l].yMax; + sources[l].yMin = num5; + sources[l].yMax = yMax; + if (sources[l].height >= base.children[l].minSize.y) + { + break; + } + float num6 = sources[l].yMin + base.children[l].minSize.y; + sources[l].yMax = num6; + num5 = num6; + } + else + { + float xMax = sources[l].xMax; + sources[l].xMin = num5; + sources[l].xMax = xMax; + if (sources[l].width >= base.children[l].minSize.x) + { + break; + } + float num6 = sources[l].xMin + base.children[l].minSize.x; + sources[l].xMax = num6; + num5 = num6; + } + } + float num8 = (!this.vertical) ? base.position.width : base.position.height; + if (num5 > num8) + { + float num9 = num8 - num5; + for (int m = 0; m < i - 1; m++) + { + if (this.vertical) + { + int expr_402_cp_1 = m; + sources[expr_402_cp_1].y = sources[expr_402_cp_1].y + num9; + } + else + { + int expr_41D_cp_1 = m; + sources[expr_41D_cp_1].x = sources[expr_41D_cp_1].x + num9; + } + } + num2 += num9; + } + } + public void Cleanup() + { + SplitView splitView = base.parent as SplitView; + if (base.children.Length == 1 && splitView != null) + { + View view = base.children[0]; + view.position = base.position; + if (base.parent != null) + { + base.parent.AddChild(view, base.parent.IndexOfChild(this)); + base.parent.RemoveChild(this); + if (splitView) + { + splitView.Cleanup(); + } + view.position = base.position; + if (!Unsupported.IsDestroyScriptableObject(this)) + { + UnityEngine.Object.DestroyImmediate(this); + } + return; + } + if (view is SplitView) + { + this.RemoveChild(view); + base.window.mainView = view; + view.position = new Rect(0f, 0f, view.window.position.width, base.window.position.height); + view.Reflow(); + if (!Unsupported.IsDestroyScriptableObject(this)) + { + UnityEngine.Object.DestroyImmediate(this); + } + return; + } + } + if (splitView) + { + splitView.Cleanup(); + splitView = (base.parent as SplitView); + if (splitView && splitView.vertical == this.vertical) + { + int num = new List(base.parent.children).IndexOf(this); + View[] children = base.children; + for (int i = 0; i < children.Length; i++) + { + View view2 = children[i]; + splitView.AddChild(view2, num++); + view2.position = new Rect(base.position.x + view2.position.x, base.position.y + view2.position.y, view2.position.width, view2.position.height); + } + } + } + if (base.children.Length == 0) + { + if (base.parent == null && base.window != null) + { + base.window.Close(); + } + else + { + ICleanuppable cleanuppable = base.parent as ICleanuppable; + if (base.parent is SplitView) + { + ((SplitView)base.parent).RemoveChildNice(this); + if (!Unsupported.IsDestroyScriptableObject(this)) + { + UnityEngine.Object.DestroyImmediate(this, true); + } + } + cleanuppable.Cleanup(); + } + return; + } + this.splitState = null; + this.Reflow(); + } + public void SplitGUI(Event evt) + { + if (this.splitState == null) + { + this.SetupSplitter(); + } + SplitView splitView = base.parent as SplitView; + if (splitView) + { + Event @event = new Event(evt); + @event.mousePosition += new Vector2(base.position.x, base.position.y); + splitView.SplitGUI(@event); + if (@event.type == EventType.Used) + { + evt.Use(); + } + } + float num = (!this.vertical) ? evt.mousePosition.x : evt.mousePosition.y; + int num2 = GUIUtility.GetControlID(546739, FocusType.Passive); + this.controlID = num2; + switch (evt.GetTypeForControl(num2)) + { + case EventType.MouseDown: + if (base.children.Length != 1) + { + int num3 = (!this.vertical) ? ((int)base.children[0].position.x) : ((int)base.children[0].position.y); + for (int i = 0; i < base.children.Length - 1; i++) + { + if (i >= this.splitState.realSizes.Length) + { + DockArea dockArea = GUIView.current as DockArea; + string text = "Non-dock area " + GUIView.current.GetType(); + if (dockArea && dockArea.m_Selected < dockArea.m_Panes.Count && dockArea.m_Panes[dockArea.m_Selected]) + { + text = dockArea.m_Panes[dockArea.m_Selected].GetType().ToString(); + } + if (Unsupported.IsDeveloperBuild()) + { + Debug.LogError(string.Concat(new object[] + { + "Real sizes out of bounds for: ", + text, + " index: ", + i, + " RealSizes: ", + this.splitState.realSizes.Length + })); + } + this.SetupSplitter(); + } + if (((!this.vertical) ? new Rect((float)(num3 + this.splitState.realSizes[i] - this.splitState.splitSize / 2), base.children[0].position.y, (float)this.splitState.splitSize, base.children[0].position.height) : new Rect(base.children[0].position.x, (float)(num3 + this.splitState.realSizes[i] - this.splitState.splitSize / 2), base.children[0].position.width, (float)this.splitState.splitSize)).Contains(evt.mousePosition)) + { + this.splitState.splitterInitialOffset = (int)num; + this.splitState.currentActiveSplitter = i; + GUIUtility.hotControl = num2; + evt.Use(); + break; + } + num3 += this.splitState.realSizes[i]; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == num2) + { + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + if (base.children.Length > 1 && GUIUtility.hotControl == num2 && this.splitState.currentActiveSplitter >= 0) + { + int num4 = (int)num - this.splitState.splitterInitialOffset; + if (num4 != 0) + { + this.splitState.splitterInitialOffset = (int)num; + this.splitState.DoSplitter(this.splitState.currentActiveSplitter, this.splitState.currentActiveSplitter + 1, num4); + } + this.SetupRectsFromSplitter(); + evt.Use(); + } + break; + } + } + protected override void SetPosition(Rect newPos) + { + base.SetPosition(newPos); + this.Reflow(); + } + } +} diff --git a/UnityEditor/UnityEditor/SplitterGUILayout.cs b/UnityEditor/UnityEditor/SplitterGUILayout.cs new file mode 100644 index 00000000..ba4d7c04 --- /dev/null +++ b/UnityEditor/UnityEditor/SplitterGUILayout.cs @@ -0,0 +1,207 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SplitterGUILayout + { + internal class GUISplitterGroup : GUILayoutGroup + { + public SplitterState state; + public override void SetHorizontal(float x, float width) + { + if (!this.isVertical) + { + this.state.xOffset = x; + int i; + if (width != (float)this.state.lastTotalSize) + { + this.state.RelativeToRealSizes((int)width); + this.state.lastTotalSize = (int)width; + for (i = 0; i < this.state.realSizes.Length - 1; i++) + { + this.state.DoSplitter(i, i + 1, 0); + } + } + i = 0; + foreach (GUILayoutEntry current in this.entries) + { + float num = (float)this.state.realSizes[i]; + current.SetHorizontal(Mathf.Round(x), Mathf.Round(num)); + x += num + this.spacing; + i++; + } + } + else + { + base.SetHorizontal(x, width); + } + } + public override void SetVertical(float y, float height) + { + this.rect.y = y; + this.rect.height = height; + RectOffset padding = base.style.padding; + if (this.isVertical) + { + if (base.style != GUIStyle.none) + { + float num = (float)padding.top; + float num2 = (float)padding.bottom; + if (this.entries.Count != 0) + { + num = Mathf.Max(num, (float)this.entries[0].margin.top); + num2 = Mathf.Max(num2, (float)this.entries[this.entries.Count - 1].margin.bottom); + } + y += num; + height -= num2 + num; + } + int i; + if (height != (float)this.state.lastTotalSize) + { + this.state.RelativeToRealSizes((int)height); + this.state.lastTotalSize = (int)height; + for (i = 0; i < this.state.realSizes.Length - 1; i++) + { + this.state.DoSplitter(i, i + 1, 0); + } + } + i = 0; + foreach (GUILayoutEntry current in this.entries) + { + float num3 = (float)this.state.realSizes[i]; + current.SetVertical(Mathf.Round(y), Mathf.Round(num3)); + y += num3 + this.spacing; + i++; + } + } + else + { + if (base.style != GUIStyle.none) + { + foreach (GUILayoutEntry current2 in this.entries) + { + float num4 = (float)Mathf.Max(current2.margin.top, padding.top); + float y2 = y + num4; + float num5 = height - (float)Mathf.Max(current2.margin.bottom, padding.bottom) - num4; + if (current2.stretchHeight != 0) + { + current2.SetVertical(y2, num5); + } + else + { + current2.SetVertical(y2, Mathf.Clamp(num5, current2.minHeight, current2.maxHeight)); + } + } + } + else + { + float num6 = y - (float)this.margin.top; + float num7 = height + (float)this.margin.vertical; + foreach (GUILayoutEntry current3 in this.entries) + { + if (current3.stretchHeight != 0) + { + current3.SetVertical(num6 + (float)current3.margin.top, num7 - (float)current3.margin.vertical); + } + else + { + current3.SetVertical(num6 + (float)current3.margin.top, Mathf.Clamp(num7 - (float)current3.margin.vertical, current3.minHeight, current3.maxHeight)); + } + } + } + } + } + } + private static int splitterHash = "Splitter".GetHashCode(); + public static void BeginSplit(SplitterState state, GUIStyle style, bool vertical, params GUILayoutOption[] options) + { + SplitterGUILayout.GUISplitterGroup gUISplitterGroup = (SplitterGUILayout.GUISplitterGroup)GUILayoutUtility.BeginLayoutGroup(style, null, typeof(SplitterGUILayout.GUISplitterGroup)); + state.ID = GUIUtility.GetControlID(SplitterGUILayout.splitterHash, FocusType.Native); + switch (Event.current.type) + { + case EventType.MouseDown: + if (Event.current.button == 0 && Event.current.clickCount == 1) + { + int num = (!gUISplitterGroup.isVertical) ? ((int)gUISplitterGroup.rect.x) : ((int)gUISplitterGroup.rect.y); + int num2 = (!gUISplitterGroup.isVertical) ? ((int)Event.current.mousePosition.x) : ((int)Event.current.mousePosition.y); + for (int i = 0; i < state.relativeSizes.Length - 1; i++) + { + if (((!gUISplitterGroup.isVertical) ? new Rect(state.xOffset + (float)num + (float)state.realSizes[i] - (float)(state.splitSize / 2), gUISplitterGroup.rect.y, (float)state.splitSize, gUISplitterGroup.rect.height) : new Rect(state.xOffset + gUISplitterGroup.rect.x, (float)(num + state.realSizes[i] - state.splitSize / 2), gUISplitterGroup.rect.width, (float)state.splitSize)).Contains(Event.current.mousePosition)) + { + state.splitterInitialOffset = num2; + state.currentActiveSplitter = i; + GUIUtility.hotControl = state.ID; + Event.current.Use(); + break; + } + num += state.realSizes[i]; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == state.ID) + { + GUIUtility.hotControl = 0; + state.currentActiveSplitter = -1; + state.RealToRelativeSizes(); + Event.current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == state.ID && state.currentActiveSplitter >= 0) + { + int num2 = (!gUISplitterGroup.isVertical) ? ((int)Event.current.mousePosition.x) : ((int)Event.current.mousePosition.y); + int num3 = num2 - state.splitterInitialOffset; + if (num3 != 0) + { + state.splitterInitialOffset = num2; + state.DoSplitter(state.currentActiveSplitter, state.currentActiveSplitter + 1, num3); + } + Event.current.Use(); + } + break; + case EventType.Repaint: + { + int num4 = (!gUISplitterGroup.isVertical) ? ((int)gUISplitterGroup.rect.x) : ((int)gUISplitterGroup.rect.y); + for (int j = 0; j < state.relativeSizes.Length - 1; j++) + { + Rect position = (!gUISplitterGroup.isVertical) ? new Rect(state.xOffset + (float)num4 + (float)state.realSizes[j] - (float)(state.splitSize / 2), gUISplitterGroup.rect.y, (float)state.splitSize, gUISplitterGroup.rect.height) : new Rect(state.xOffset + gUISplitterGroup.rect.x, (float)(num4 + state.realSizes[j] - state.splitSize / 2), gUISplitterGroup.rect.width, (float)state.splitSize); + EditorGUIUtility.AddCursorRect(position, (!gUISplitterGroup.isVertical) ? MouseCursor.SplitResizeLeftRight : MouseCursor.ResizeVertical); + num4 += state.realSizes[j]; + } + break; + } + case EventType.Layout: + gUISplitterGroup.state = state; + gUISplitterGroup.resetCoords = false; + gUISplitterGroup.isVertical = vertical; + gUISplitterGroup.ApplyOptions(options); + break; + } + } + public static void BeginHorizontalSplit(SplitterState state, params GUILayoutOption[] options) + { + SplitterGUILayout.BeginSplit(state, GUIStyle.none, false, options); + } + public static void BeginVerticalSplit(SplitterState state, params GUILayoutOption[] options) + { + SplitterGUILayout.BeginSplit(state, GUIStyle.none, true, options); + } + public static void BeginHorizontalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) + { + SplitterGUILayout.BeginSplit(state, style, false, options); + } + public static void BeginVerticalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) + { + SplitterGUILayout.BeginSplit(state, style, true, options); + } + public static void EndVerticalSplit() + { + GUILayoutUtility.EndLayoutGroup(); + } + public static void EndHorizontalSplit() + { + GUILayoutUtility.EndLayoutGroup(); + } + } +} diff --git a/UnityEditor/UnityEditor/SplitterState.cs b/UnityEditor/UnityEditor/SplitterState.cs new file mode 100644 index 00000000..05197df0 --- /dev/null +++ b/UnityEditor/UnityEditor/SplitterState.cs @@ -0,0 +1,214 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class SplitterState + { + private const int defaultSplitSize = 6; + public int ID; + public int splitterInitialOffset; + public int currentActiveSplitter = -1; + public int[] realSizes; + public float[] relativeSizes; + public int[] minSizes; + public int[] maxSizes; + public int lastTotalSize; + public int splitSize; + public float xOffset; + public SplitterState(params float[] relativeSizes) + { + this.Init(relativeSizes, null, null, 0); + } + public SplitterState(int[] realSizes, int[] minSizes, int[] maxSizes) + { + this.realSizes = realSizes; + this.minSizes = ((minSizes != null) ? minSizes : new int[realSizes.Length]); + this.maxSizes = ((maxSizes != null) ? maxSizes : new int[realSizes.Length]); + this.relativeSizes = new float[realSizes.Length]; + this.splitSize = ((this.splitSize != 0) ? this.splitSize : 6); + this.RealToRelativeSizes(); + } + public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes) + { + this.Init(relativeSizes, minSizes, maxSizes, 0); + } + public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes, int splitSize) + { + this.Init(relativeSizes, minSizes, maxSizes, splitSize); + } + private void Init(float[] relativeSizes, int[] minSizes, int[] maxSizes, int splitSize) + { + this.relativeSizes = relativeSizes; + this.minSizes = ((minSizes != null) ? minSizes : new int[relativeSizes.Length]); + this.maxSizes = ((maxSizes != null) ? maxSizes : new int[relativeSizes.Length]); + this.realSizes = new int[relativeSizes.Length]; + this.splitSize = ((splitSize != 0) ? splitSize : 6); + this.NormalizeRelativeSizes(); + } + public void NormalizeRelativeSizes() + { + float num = 1f; + float num2 = 0f; + for (int i = 0; i < this.relativeSizes.Length; i++) + { + num2 += this.relativeSizes[i]; + } + for (int i = 0; i < this.relativeSizes.Length; i++) + { + this.relativeSizes[i] = this.relativeSizes[i] / num2; + num -= this.relativeSizes[i]; + } + this.relativeSizes[this.relativeSizes.Length - 1] += num; + } + public void RealToRelativeSizes() + { + float num = 1f; + float num2 = 0f; + for (int i = 0; i < this.realSizes.Length; i++) + { + num2 += (float)this.realSizes[i]; + } + for (int i = 0; i < this.realSizes.Length; i++) + { + this.relativeSizes[i] = (float)this.realSizes[i] / num2; + num -= this.relativeSizes[i]; + } + if (this.relativeSizes.Length > 0) + { + this.relativeSizes[this.relativeSizes.Length - 1] += num; + } + } + public void RelativeToRealSizes(int totalSpace) + { + int num = totalSpace; + for (int i = 0; i < this.relativeSizes.Length; i++) + { + this.realSizes[i] = (int)Mathf.Round(this.relativeSizes[i] * (float)totalSpace); + if (this.realSizes[i] < this.minSizes[i]) + { + this.realSizes[i] = this.minSizes[i]; + } + num -= this.realSizes[i]; + } + if (num < 0) + { + for (int i = 0; i < this.relativeSizes.Length; i++) + { + if (this.realSizes[i] > this.minSizes[i]) + { + int num2 = this.realSizes[i] - this.minSizes[i]; + int num3 = (-num >= num2) ? num2 : (-num); + num += num3; + this.realSizes[i] -= num3; + if (num >= 0) + { + break; + } + } + } + } + int num4 = this.realSizes.Length - 1; + if (num4 >= 0) + { + this.realSizes[num4] += num; + if (this.realSizes[num4] < this.minSizes[num4]) + { + this.realSizes[num4] = this.minSizes[num4]; + } + } + } + public void DoSplitter(int i1, int i2, int diff) + { + int num = this.realSizes[i1]; + int num2 = this.realSizes[i2]; + int num3 = this.minSizes[i1]; + int num4 = this.minSizes[i2]; + int num5 = this.maxSizes[i1]; + int num6 = this.maxSizes[i2]; + bool flag = false; + if (num3 == 0) + { + num3 = 16; + } + if (num4 == 0) + { + num4 = 16; + } + if (num + diff < num3) + { + diff -= num3 - num; + this.realSizes[i2] += this.realSizes[i1] - num3; + this.realSizes[i1] = num3; + if (i1 != 0) + { + this.DoSplitter(i1 - 1, i2, diff); + } + else + { + this.splitterInitialOffset -= diff; + } + flag = true; + } + else + { + if (num2 - diff < num4) + { + diff -= num2 - num4; + this.realSizes[i1] += this.realSizes[i2] - num4; + this.realSizes[i2] = num4; + if (i2 != this.realSizes.Length - 1) + { + this.DoSplitter(i1, i2 + 1, diff); + } + else + { + this.splitterInitialOffset -= diff; + } + flag = true; + } + } + if (!flag) + { + if (num5 != 0 && num + diff > num5) + { + diff -= this.realSizes[i1] - num5; + this.realSizes[i2] += this.realSizes[i1] - num5; + this.realSizes[i1] = num5; + if (i1 != 0) + { + this.DoSplitter(i1 - 1, i2, diff); + } + else + { + this.splitterInitialOffset -= diff; + } + flag = true; + } + else + { + if (num6 != 0 && num2 - diff > num6) + { + diff -= num2 - num6; + this.realSizes[i1] += this.realSizes[i2] - num6; + this.realSizes[i2] = num6; + if (i2 != this.realSizes.Length - 1) + { + this.DoSplitter(i1, i2 + 1, diff); + } + else + { + this.splitterInitialOffset -= diff; + } + flag = true; + } + } + } + if (!flag) + { + this.realSizes[i1] += diff; + this.realSizes[i2] -= diff; + } + } + } +} diff --git a/UnityEditor/UnityEditor/SpringJoint2DEditor.cs b/UnityEditor/UnityEditor/SpringJoint2DEditor.cs new file mode 100644 index 00000000..b7731b0f --- /dev/null +++ b/UnityEditor/UnityEditor/SpringJoint2DEditor.cs @@ -0,0 +1,25 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SpringJoint2D))] + internal class SpringJoint2DEditor : AnchoredJoint2DEditor + { + public new void OnSceneGUI() + { + SpringJoint2D springJoint2D = (SpringJoint2D)this.target; + if (!springJoint2D.enabled) + { + return; + } + Vector3 anchor = Joint2DEditorBase.TransformPoint(springJoint2D.transform, springJoint2D.anchor); + Vector3 vector = springJoint2D.connectedAnchor; + if (springJoint2D.connectedBody) + { + vector = Joint2DEditorBase.TransformPoint(springJoint2D.connectedBody.transform, vector); + } + Joint2DEditorBase.DrawDistanceGizmo(anchor, vector, springJoint2D.distance); + base.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteEditorTexturePostprocessor.cs b/UnityEditor/UnityEditor/SpriteEditorTexturePostprocessor.cs new file mode 100644 index 00000000..2a91391b --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteEditorTexturePostprocessor.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SpriteEditorTexturePostprocessor : AssetPostprocessor + { + public override int GetPostprocessOrder() + { + return 1; + } + public void OnPostprocessTexture(Texture2D tex) + { + if (SpriteEditorWindow.s_Instance != null && base.assetPath.Equals(SpriteEditorWindow.s_Instance.m_SelectedAssetPath)) + { + if (!SpriteEditorWindow.s_Instance.m_IgnoreNextPostprocessEvent) + { + SpriteEditorWindow.s_Instance.m_ResetOnNextRepaint = true; + SpriteEditorWindow.s_Instance.Repaint(); + } + else + { + SpriteEditorWindow.s_Instance.m_IgnoreNextPostprocessEvent = false; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteEditorWindow.cs b/UnityEditor/UnityEditor/SpriteEditorWindow.cs new file mode 100644 index 00000000..43753ce1 --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteEditorWindow.cs @@ -0,0 +1,1298 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.Sprites; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SpriteEditorWindow : SpriteUtilityWindow + { + private enum GizmoMode + { + BorderEditing, + RectEditing + } + public enum AutoSlicingMethod + { + DeleteAll, + Smart, + Safe + } + private const float maxSnapDistance = 14f; + internal static PrefKey k_SpriteEditorTrim = new PrefKey("Sprite Editor/Trim", "#t"); + public static SpriteEditorWindow s_Instance; + public bool m_ResetOnNextRepaint; + public bool m_IgnoreNextPostprocessEvent; + public Texture2D m_OriginalTexture; + private SpriteRectCache m_RectsCache; + private SerializedObject m_TextureImporterSO; + private TextureImporter m_TextureImporter; + private SerializedProperty m_TextureImporterSprites; + public static bool s_OneClickDragStarted = false; + private bool m_TextureIsDirty; + private static bool[] s_AlphaPixelCache; + public string m_SelectedAssetPath; + private SpriteEditorWindow.GizmoMode m_GizmoMode; + [SerializeField] + private SpriteRect m_Selected; + public readonly GUIContent[] spriteAlignmentOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Custom") + }; + public static GUIContent s_PivotLabel = EditorGUIUtility.TextContent("Pivot"); + public static GUIContent s_NoSelectionWarning = EditorGUIUtility.TextContent("SpriteEditor.NoTextureOrSpriteSelected"); + public Texture2D originalTexture + { + get + { + return this.m_OriginalTexture; + } + } + private SpriteRect selected + { + get + { + return this.m_Selected; + } + set + { + if (value != this.m_Selected) + { + this.m_Selected = value; + } + } + } + private int defaultColliderAlphaCutoff + { + get + { + return 254; + } + } + private float defaultColliderDetail + { + get + { + return 0.25f; + } + } + private Rect inspectorRect + { + get + { + return new Rect(base.position.width - 330f - 8f - 16f, base.position.height - 148f - 8f - 16f, 330f, 148f); + } + } + private bool multipleSprites + { + get + { + return this.m_TextureImporter != null && this.m_TextureImporter.spriteImportMode == SpriteImportMode.Multiple; + } + } + private bool activeTextureSelected + { + get + { + return this.m_TextureImporter != null && this.m_Texture != null && this.m_OriginalTexture != null; + } + } + public bool textureIsDirty + { + get + { + return this.m_TextureIsDirty; + } + set + { + this.m_TextureIsDirty = value; + } + } + public bool selectedTextureChanged + { + get + { + Texture2D selectedTexture2D = this.GetSelectedTexture2D(); + return selectedTexture2D != null && this.m_OriginalTexture != selectedTexture2D; + } + } + public static void GetWindow() + { + EditorWindow.GetWindow(); + } + public void RefreshPropertiesCache() + { + this.m_OriginalTexture = this.GetSelectedTexture2D(); + if (this.m_OriginalTexture == null) + { + return; + } + this.m_TextureImporter = (AssetImporter.GetAtPath(this.m_SelectedAssetPath) as TextureImporter); + if (this.m_TextureImporter == null) + { + return; + } + this.m_TextureImporterSO = new SerializedObject(this.m_TextureImporter); + this.m_TextureImporterSprites = this.m_TextureImporterSO.FindProperty("m_SpriteSheet.m_Sprites"); + if (this.m_RectsCache != null) + { + this.selected = ((this.m_TextureImporterSprites.arraySize <= 0) ? null : this.m_RectsCache.RectAt(0)); + } + int width = 0; + int height = 0; + this.m_TextureImporter.GetWidthAndHeight(ref width, ref height); + this.m_Texture = this.CreateTemporaryDuplicate(AssetDatabase.LoadMainAssetAtPath(this.m_TextureImporter.assetPath) as Texture2D, width, height); + if (this.m_Texture == null) + { + return; + } + this.m_Texture.filterMode = FilterMode.Point; + } + public void InvalidatePropertiesCache() + { + if (this.m_RectsCache) + { + this.m_RectsCache.ClearAll(); + UnityEngine.Object.DestroyImmediate(this.m_RectsCache); + } + if (this.m_Texture) + { + UnityEngine.Object.DestroyImmediate(this.m_Texture); + } + this.m_OriginalTexture = null; + this.m_TextureImporter = null; + this.m_TextureImporterSO = null; + this.m_TextureImporterSprites = null; + SpriteEditorWindow.s_AlphaPixelCache = null; + } + private void InitializeAnimVariables() + { + } + private void OnSelectionChange() + { + if (this.selectedTextureChanged) + { + this.HandleApplyRevertDialog(); + } + this.InvalidatePropertiesCache(); + this.Reset(); + this.UpdateSelectedSprite(); + base.Repaint(); + } + public void Reset() + { + this.InvalidatePropertiesCache(); + this.selected = null; + this.m_Zoom = -1f; + this.RefreshPropertiesCache(); + this.RefreshRects(); + base.Repaint(); + } + private void OnEnable() + { + base.minSize = new Vector2(360f, 200f); + base.title = EditorGUIUtility.TextContent("SpriteEditorWindow.WindowTitle").text; + SpriteEditorWindow.s_Instance = this; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.Reset(); + } + private void UndoRedoPerformed() + { + Texture2D selectedTexture2D = this.GetSelectedTexture2D(); + if (selectedTexture2D != null && this.m_OriginalTexture != selectedTexture2D) + { + this.OnSelectionChange(); + } + if (this.m_RectsCache != null && !this.m_RectsCache.Contains(this.selected)) + { + this.selected = null; + } + base.Repaint(); + } + private void OnDisable() + { + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + this.HandleApplyRevertDialog(); + this.InvalidatePropertiesCache(); + SpriteEditorWindow.s_Instance = null; + } + private void HandleApplyRevertDialog() + { + if (this.textureIsDirty && this.m_TextureImporter != null) + { + if (EditorUtility.DisplayDialog("Unapplied import settings", "Unapplied import settings for '" + this.m_TextureImporter.assetPath + "'", "Apply", "Revert")) + { + this.DoApply(); + } + else + { + this.DoRevert(); + } + } + } + private void RefreshRects() + { + if (this.m_TextureImporterSprites == null) + { + return; + } + if (this.m_RectsCache) + { + this.m_RectsCache.ClearAll(); + UnityEngine.Object.DestroyImmediate(this.m_RectsCache); + } + this.m_RectsCache = ScriptableObject.CreateInstance(); + if (this.m_TextureImporter.spriteImportMode == SpriteImportMode.None) + { + return; + } + if (this.multipleSprites) + { + for (int i = 0; i < this.m_TextureImporterSprites.arraySize; i++) + { + SpriteRect spriteRect = new SpriteRect(); + spriteRect.m_Rect = this.m_TextureImporterSprites.GetArrayElementAtIndex(i).FindPropertyRelative("m_Rect").rectValue; + spriteRect.m_Name = this.m_TextureImporterSprites.GetArrayElementAtIndex(i).FindPropertyRelative("m_Name").stringValue; + spriteRect.m_Alignment = (SpriteAlignment)this.m_TextureImporterSprites.GetArrayElementAtIndex(i).FindPropertyRelative("m_Alignment").intValue; + spriteRect.m_Border = this.m_TextureImporterSprites.GetArrayElementAtIndex(i).FindPropertyRelative("m_Border").vector4Value; + spriteRect.m_Pivot = SpriteEditorUtility.GetPivotValue(spriteRect.m_Alignment, this.m_TextureImporterSprites.GetArrayElementAtIndex(i).FindPropertyRelative("m_Pivot").vector2Value); + this.m_RectsCache.AddRect(spriteRect); + } + } + else + { + SpriteRect spriteRect2 = new SpriteRect(); + spriteRect2.m_Rect = new Rect(0f, 0f, (float)this.m_Texture.width, (float)this.m_Texture.height); + spriteRect2.m_Name = this.m_OriginalTexture.name; + spriteRect2.m_Alignment = (SpriteAlignment)this.m_TextureImporterSO.FindProperty("m_Alignment").intValue; + spriteRect2.m_Border = this.m_TextureImporter.spriteBorder; + spriteRect2.m_Pivot = SpriteEditorUtility.GetPivotValue(spriteRect2.m_Alignment, this.m_TextureImporter.spritePivot); + this.m_RectsCache.AddRect(spriteRect2); + } + if (this.m_RectsCache.Count > 0) + { + this.selected = this.m_RectsCache.RectAt(0); + } + } + private void OnGUI() + { + if (this.m_ResetOnNextRepaint || this.selectedTextureChanged) + { + this.Reset(); + this.m_ResetOnNextRepaint = false; + } + Matrix4x4 matrix = Handles.matrix; + if (!this.activeTextureSelected) + { + EditorGUI.BeginDisabledGroup(true); + GUILayout.Label(SpriteEditorWindow.s_NoSelectionWarning, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + return; + } + base.InitStyles(); + Rect rect = EditorGUILayout.BeginHorizontal(GUIContent.none, "Toolbar", new GUILayoutOption[0]); + this.DoToolbarGUI(); + GUILayout.FlexibleSpace(); + this.DoApplyRevertGUI(); + base.DoAlphaZoomToolbarGUI(); + EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.m_TextureViewRect = new Rect(0f, rect.yMax, base.position.width - 16f, base.position.height - 16f - rect.height); + GUILayout.FlexibleSpace(); + base.DoTextureGUI(); + EditorGUILayout.EndHorizontal(); + this.DoSelectedFrameInspector(); + this.DoHotkeys(); + Handles.matrix = matrix; + } + protected override void DoTextureGUIExtras() + { + this.HandleGizmoMode(); + if (this.multipleSprites) + { + this.HandleRectCornerScalingHandles(); + } + this.HandleBorderCornerScalingHandles(); + this.HandleBorderSidePointScalingSliders(); + if (this.multipleSprites) + { + this.HandleRectSideScalingHandles(); + } + this.HandleBorderSideScalingHandles(); + this.HandlePivotHandle(); + if (this.multipleSprites) + { + this.HandleDragging(); + } + this.HandleSelection(); + if (this.multipleSprites) + { + this.HandleCreate(); + this.HandleDelete(); + this.HandleDuplicate(); + } + } + private void HandleGizmoMode() + { + if (Event.current.control) + { + this.m_GizmoMode = SpriteEditorWindow.GizmoMode.BorderEditing; + } + else + { + this.m_GizmoMode = SpriteEditorWindow.GizmoMode.RectEditing; + } + Event current = Event.current; + if ((current.type == EventType.KeyDown || current.type == EventType.KeyUp) && (current.keyCode == KeyCode.LeftControl || current.keyCode == KeyCode.RightControl || current.keyCode == KeyCode.LeftAlt || current.keyCode == KeyCode.RightAlt)) + { + base.Repaint(); + } + } + private void DoToolbarGUI() + { + EditorGUI.BeginDisabledGroup(!this.multipleSprites); + Rect buttonRect = EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Slice", "toolbarPopup", new GUILayoutOption[0])) + { + SpriteEditorMenu.s_SpriteEditor = this; + if (SpriteEditorMenu.ShowAtPosition(buttonRect)) + { + GUIUtility.ExitGUI(); + } + } + EditorGUI.BeginDisabledGroup(this.selected == null); + if (GUILayout.Button(new GUIContent("Trim", "Trims selected rectangle (T)"), EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.TrimSelectedSprite(); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + } + private void DoSelectedFrameInspector() + { + if (this.selected != null) + { + EditorGUIUtility.wideMode = true; + float labelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 135f; + GUILayout.BeginArea(this.inspectorRect); + GUILayout.BeginVertical(new GUIContent("Sprite"), GUI.skin.window, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!this.multipleSprites); + EditorGUI.BeginChangeCheck(); + string name = this.selected.m_Name; + string text = EditorGUILayout.TextField("Name", name, new GUILayoutOption[0]); + Rect rect = this.selected.m_Rect; + Rect rect2 = EditorGUILayout.RectField("Position", this.FlipNegativeRect(rect), new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + Rect rect3 = GUILayoutUtility.GetRect(322f, 322f, 32f, 32f); + Vector4 vector = this.ClampSpriteBorder(this.selected.m_Border); + Vector4 border = vector; + Rect position = rect3; + position.width = EditorGUIUtility.labelWidth; + position.height = 16f; + GUI.Label(position, "Border"); + Rect position2 = rect3; + position2.width -= EditorGUIUtility.labelWidth; + position2.height = 16f; + position2.x += EditorGUIUtility.labelWidth; + position2.width /= 2f; + position2.width -= 2f; + EditorGUIUtility.labelWidth = 12f; + border.x = (float)EditorGUI.IntField(position2, "L", Mathf.RoundToInt(border.x)); + position2.x += position2.width + 3f; + border.y = (float)EditorGUI.IntField(position2, "B", Mathf.RoundToInt(border.y)); + position2.y += 16f; + position2.x -= position2.width + 3f; + border.z = (float)EditorGUI.IntField(position2, "R", Mathf.RoundToInt(border.z)); + position2.x += position2.width + 3f; + border.w = (float)EditorGUI.IntField(position2, "T", Mathf.RoundToInt(border.w)); + EditorGUIUtility.labelWidth = 135f; + this.selected.m_Alignment = (SpriteAlignment)EditorGUILayout.Popup(SpriteEditorWindow.s_PivotLabel, (int)this.selected.m_Alignment, this.spriteAlignmentOptions, new GUILayoutOption[0]); + Vector2 pivot = this.selected.m_Pivot; + Vector2 customOffset = pivot; + EditorGUI.BeginDisabledGroup(this.selected.m_Alignment != SpriteAlignment.Custom); + position2.x = 5f; + position2.y += 36f; + position2.width = 414f; + customOffset = EditorGUI.Vector2Field(position2, "Custom Pivot", pivot); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Modify sprite"); + if (this.multipleSprites) + { + text = InternalEditorUtility.RemoveInvalidCharsFromFileName(text, true); + if (string.IsNullOrEmpty(this.selected.m_OriginalName) && text != name) + { + this.selected.m_OriginalName = name; + } + if (string.IsNullOrEmpty(text)) + { + text = name; + } + foreach (SpriteRect current in this.m_RectsCache.m_Rects) + { + if (current.m_Name == text) + { + text = this.selected.m_OriginalName; + break; + } + } + this.selected.m_Name = text; + this.selected.m_Rect = this.ClampSpriteRect(rect2); + this.selected.m_Border = this.ClampSpriteBorder(border); + } + this.selected.m_Border = this.ClampSpriteBorder(border); + this.selected.m_Pivot = SpriteEditorUtility.GetPivotValue(this.selected.m_Alignment, customOffset); + this.textureIsDirty = true; + } + GUILayout.EndVertical(); + GUILayout.EndArea(); + EditorGUIUtility.labelWidth = labelWidth; + } + } + private void DoHotkeys() + { + Event current = Event.current; + if (SpriteEditorWindow.k_SpriteEditorTrim.activated && current.type == EventType.KeyDown) + { + this.TrimSelectedSprite(); + current.Use(); + } + } + private void DoApplyRevertGUI() + { + EditorGUI.BeginDisabledGroup(!this.textureIsDirty); + if (GUILayout.Button("Revert", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.DoRevert(); + } + if (GUILayout.Button("Apply", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.DoApply(); + } + EditorGUI.EndDisabledGroup(); + } + private void DoApply() + { + if (this.multipleSprites) + { + List list = new List(); + List list2 = new List(); + this.m_TextureImporterSprites.ClearArray(); + for (int i = 0; i < this.m_RectsCache.Count; i++) + { + SpriteRect spriteRect = this.m_RectsCache.RectAt(i); + if (!string.IsNullOrEmpty(spriteRect.m_OriginalName)) + { + list.Add(spriteRect.m_OriginalName); + list2.Add(spriteRect.m_Name); + } + this.m_TextureImporterSprites.InsertArrayElementAtIndex(i); + SerializedProperty arrayElementAtIndex = this.m_TextureImporterSprites.GetArrayElementAtIndex(i); + arrayElementAtIndex.FindPropertyRelative("m_Rect").rectValue = spriteRect.m_Rect; + arrayElementAtIndex.FindPropertyRelative("m_Border").vector4Value = spriteRect.m_Border; + arrayElementAtIndex.FindPropertyRelative("m_Name").stringValue = spriteRect.m_Name; + arrayElementAtIndex.FindPropertyRelative("m_Alignment").intValue = (int)spriteRect.m_Alignment; + arrayElementAtIndex.FindPropertyRelative("m_Pivot").vector2Value = spriteRect.m_Pivot; + } + if (list.Count > 0) + { + PatchImportSettingRecycleID.PatchMultiple(this.m_TextureImporterSO, 213, list.ToArray(), list2.ToArray()); + } + this.m_TextureImporterSO.ApplyModifiedProperties(); + } + else + { + if (this.m_RectsCache.Count > 0) + { + SpriteRect spriteRect2 = this.m_RectsCache.RectAt(0); + this.m_TextureImporterSO.FindProperty("m_Alignment").intValue = (int)spriteRect2.m_Alignment; + this.m_TextureImporterSO.ApplyModifiedProperties(); + this.m_TextureImporter.spriteBorder = spriteRect2.m_Border; + this.m_TextureImporter.spritePivot = spriteRect2.m_Pivot; + } + } + this.m_IgnoreNextPostprocessEvent = true; + this.DoTextureReimport(this.m_TextureImporter.assetPath); + this.textureIsDirty = false; + } + private void DoRevert() + { + this.m_TextureIsDirty = false; + this.selected = null; + this.RefreshRects(); + } + private void HandleDuplicate() + { + if (Event.current.commandName == "Duplicate" && (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand)) + { + if (Event.current.type == EventType.ExecuteCommand) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Duplicate sprite"); + this.selected = this.AddSprite(this.selected.m_Rect, (int)this.selected.m_Alignment, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + } + Event.current.Use(); + } + } + private void HandleCreate() + { + if (!this.MouseOnTopOfInspector() && !Event.current.alt) + { + EditorGUI.BeginChangeCheck(); + Rect rect = SpriteEditorHandles.RectCreator((float)this.m_Texture.width, (float)this.m_Texture.height, SpriteUtilityWindow.s_Styles.createRect); + if (EditorGUI.EndChangeCheck() && rect.width > 0f && rect.height > 0f) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Create sprite"); + this.selected = this.AddSprite(rect, 0, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + } + } + } + private void HandleDelete() + { + if ((Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") && (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand)) + { + if (Event.current.type == EventType.ExecuteCommand) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Delete sprite"); + this.m_RectsCache.RemoveRect(this.selected); + this.selected = null; + this.textureIsDirty = true; + } + Event.current.Use(); + } + } + private void HandleDragging() + { + if (this.selected != null && !this.MouseOnTopOfInspector()) + { + Rect clamp = new Rect(0f, 0f, (float)this.m_Texture.width, (float)this.m_Texture.height); + EditorGUI.BeginChangeCheck(); + SpriteRect selected = this.selected; + Rect rect = this.selected.m_Rect; + Rect rect2 = SpriteEditorUtility.ClampedRect(SpriteEditorUtility.RoundedRect(SpriteEditorHandles.SliderRect(rect)), clamp, true); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Move sprite"); + selected.m_Rect = rect2; + this.textureIsDirty = true; + } + } + } + private void HandleSelection() + { + if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && GUIUtility.hotControl == 0 && !Event.current.alt && !this.MouseOnTopOfInspector()) + { + SpriteRect selected = this.selected; + this.selected = this.TrySelect(Event.current.mousePosition); + if (this.selected != null) + { + SpriteEditorWindow.s_OneClickDragStarted = true; + } + else + { + base.Repaint(); + } + if (selected != this.selected && this.selected != null) + { + Event.current.Use(); + } + } + } + private bool ShouldShowRectScaling() + { + return this.selected != null && this.m_GizmoMode == SpriteEditorWindow.GizmoMode.RectEditing; + } + private void HandlePivotHandle() + { + if (this.selected != null) + { + EditorGUI.BeginChangeCheck(); + SpriteRect selected = this.selected; + selected.m_Pivot = this.ApplySpriteAlignmentToPivot(selected.m_Pivot, selected.m_Rect, selected.m_Alignment); + Vector2 pivot = SpriteEditorHandles.PivotSlider(selected.m_Rect, selected.m_Pivot, SpriteUtilityWindow.s_Styles.pivotdot, SpriteUtilityWindow.s_Styles.pivotdotactive); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Move sprite pivot"); + this.selected.m_Pivot = this.SnapPivot(pivot); + this.textureIsDirty = true; + } + } + } + private void TrimSelectedSprite() + { + Rect rect = this.TrimAlpha(this.selected.m_Rect); + rect = this.ClampSpriteRect(rect); + this.selected.m_Rect = rect; + base.Repaint(); + } + private Rect ClampSpriteRect(Rect rect) + { + return SpriteEditorUtility.RoundedRect(new Rect + { + xMin = Mathf.Clamp(rect.xMin, 0f, (float)(this.m_Texture.width - 1)), + yMin = Mathf.Clamp(rect.yMin, 0f, (float)(this.m_Texture.height - 1)), + xMax = Mathf.Clamp(rect.xMax, 1f, (float)this.m_Texture.width), + yMax = Mathf.Clamp(rect.yMax, 1f, (float)this.m_Texture.height) + }); + } + private Rect FlipNegativeRect(Rect rect) + { + return new Rect + { + xMin = Mathf.Min(rect.xMin, rect.xMax), + yMin = Mathf.Min(rect.yMin, rect.yMax), + xMax = Mathf.Max(rect.xMin, rect.xMax), + yMax = Mathf.Max(rect.yMin, rect.yMax) + }; + } + private Vector4 ClampSpriteBorder(Vector4 border) + { + Rect rect = this.FlipNegativeRect(this.selected.m_Rect); + float width = rect.width; + float height = rect.height; + return new Vector4 + { + x = (float)Mathf.RoundToInt(Mathf.Clamp(border.x, 0f, Mathf.Min(width - border.z, width))), + z = (float)Mathf.RoundToInt(Mathf.Clamp(border.z, 0f, Mathf.Min(width - border.x, width))), + y = (float)Mathf.RoundToInt(Mathf.Clamp(border.y, 0f, Mathf.Min(height - border.w, height))), + w = (float)Mathf.RoundToInt(Mathf.Clamp(border.w, 0f, Mathf.Min(height - border.y, height))) + }; + } + private Vector2 SnapPivot(Vector2 pivot) + { + SpriteRect selected = this.selected; + Rect rect = selected.m_Rect; + Vector2 vector = new Vector2(rect.xMin + rect.width * pivot.x, rect.yMin + rect.height * pivot.y); + Vector2[] snapPointsArray = this.GetSnapPointsArray(rect); + bool flag = false; + for (int i = 0; i < snapPointsArray.Length; i++) + { + if ((vector - snapPointsArray[i]).magnitude * this.m_Zoom < 14f) + { + vector = snapPointsArray[i]; + this.selected.m_Alignment = (SpriteAlignment)i; + flag = true; + break; + } + } + if (!flag) + { + this.selected.m_Alignment = SpriteAlignment.Custom; + } + return this.ConvertFromTextureToNormalizedSpace(vector, rect); + } + public Vector2 ApplySpriteAlignmentToPivot(Vector2 pivot, Rect rect, SpriteAlignment alignment) + { + Vector2[] snapPointsArray = this.GetSnapPointsArray(rect); + if (alignment != SpriteAlignment.Custom) + { + Vector2 texturePos = snapPointsArray[(int)alignment]; + return this.ConvertFromTextureToNormalizedSpace(texturePos, rect); + } + return pivot; + } + private Vector2 ConvertFromTextureToNormalizedSpace(Vector2 texturePos, Rect rect) + { + return new Vector2((texturePos.x - rect.xMin) / rect.width, (texturePos.y - rect.yMin) / rect.height); + } + private Vector2[] GetSnapPointsArray(Rect rect) + { + Vector2[] array = new Vector2[9]; + array[1] = new Vector2(rect.xMin, rect.yMax); + array[2] = new Vector2(rect.center.x, rect.yMax); + array[3] = new Vector2(rect.xMax, rect.yMax); + array[4] = new Vector2(rect.xMin, rect.center.y); + array[0] = new Vector2(rect.center.x, rect.center.y); + array[5] = new Vector2(rect.xMax, rect.center.y); + array[6] = new Vector2(rect.xMin, rect.yMin); + array[7] = new Vector2(rect.center.x, rect.yMin); + array[8] = new Vector2(rect.xMax, rect.yMin); + return array; + } + private void UpdateSelectedSprite() + { + if (Selection.activeObject is Sprite) + { + this.SelectSpriteIndex(Selection.activeObject as Sprite); + } + else + { + if (Selection.activeGameObject != null && Selection.activeGameObject.GetComponent()) + { + Sprite sprite = Selection.activeGameObject.GetComponent().sprite; + this.SelectSpriteIndex(sprite); + } + } + } + private void SelectSpriteIndex(Sprite sprite) + { + if (sprite == null) + { + return; + } + this.selected = null; + for (int i = 0; i < this.m_RectsCache.Count; i++) + { + if (sprite.rect == this.m_RectsCache.RectAt(i).m_Rect) + { + this.selected = this.m_RectsCache.RectAt(i); + return; + } + } + } + private Texture2D GetSelectedTexture2D() + { + Texture2D texture2D = null; + if (Selection.activeObject is Texture2D) + { + texture2D = (Selection.activeObject as Texture2D); + } + else + { + if (Selection.activeObject is Sprite) + { + texture2D = DataUtility.GetSpriteTexture(Selection.activeObject as Sprite, false); + } + else + { + if (Selection.activeGameObject && Selection.activeGameObject.GetComponent() && Selection.activeGameObject.GetComponent().sprite) + { + texture2D = DataUtility.GetSpriteTexture(Selection.activeGameObject.GetComponent().sprite, false); + } + } + } + if (texture2D != null) + { + this.m_SelectedAssetPath = AssetDatabase.GetAssetPath(texture2D); + } + return texture2D; + } + protected override void DrawGizmos() + { + SpriteEditorUtility.BeginLines(new Color(0f, 0f, 0f, 0.25f)); + for (int i = 0; i < this.m_RectsCache.Count; i++) + { + Rect rect = this.m_RectsCache.RectAt(i).m_Rect; + if (this.m_RectsCache.RectAt(i) != this.selected) + { + SpriteEditorUtility.DrawBox(new Rect(rect.xMin + 1f / this.m_Zoom, rect.yMin + 1f / this.m_Zoom, rect.width, rect.height)); + } + } + SpriteEditorUtility.EndLines(); + SpriteEditorUtility.BeginLines(new Color(1f, 1f, 1f, 0.5f)); + for (int j = 0; j < this.m_RectsCache.Count; j++) + { + if (this.m_RectsCache.RectAt(j) != this.selected) + { + SpriteEditorUtility.DrawBox(this.m_RectsCache.RectAt(j).m_Rect); + } + } + SpriteEditorUtility.EndLines(); + SpriteEditorUtility.BeginLines(new Color(0f, 1f, 0f, 0.7f)); + for (int k = 0; k < this.m_RectsCache.Count; k++) + { + SpriteRect spriteRect = this.m_RectsCache.RectAt(k); + if (this.ShouldDrawBorders(spriteRect)) + { + Vector4 border = spriteRect.m_Border; + Rect rect2 = spriteRect.m_Rect; + SpriteEditorUtility.DrawLine(new Vector3(rect2.xMin + border.x, rect2.yMin), new Vector3(rect2.xMin + border.x, rect2.yMax)); + SpriteEditorUtility.DrawLine(new Vector3(rect2.xMax - border.z, rect2.yMin), new Vector3(rect2.xMax - border.z, rect2.yMax)); + SpriteEditorUtility.DrawLine(new Vector3(rect2.xMin, rect2.yMin + border.y), new Vector3(rect2.xMax, rect2.yMin + border.y)); + SpriteEditorUtility.DrawLine(new Vector3(rect2.xMin, rect2.yMax - border.w), new Vector3(rect2.xMax, rect2.yMax - border.w)); + } + } + SpriteEditorUtility.EndLines(); + if (this.ShouldShowRectScaling()) + { + Rect rect3 = this.selected.m_Rect; + SpriteEditorUtility.BeginLines(new Color(0f, 0.1f, 0.3f, 0.25f)); + SpriteEditorUtility.DrawBox(new Rect(rect3.xMin + 1f / this.m_Zoom, rect3.yMin + 1f / this.m_Zoom, rect3.width, rect3.height)); + SpriteEditorUtility.EndLines(); + SpriteEditorUtility.BeginLines(new Color(0.25f, 0.5f, 1f, 0.75f)); + SpriteEditorUtility.DrawBox(rect3); + SpriteEditorUtility.EndLines(); + } + } + private bool ShouldDrawBorders(SpriteRect currentRect) + { + Vector4 border = currentRect.m_Border; + return !Mathf.Approximately(border.sqrMagnitude, 0f) || (currentRect == this.selected && this.m_GizmoMode == SpriteEditorWindow.GizmoMode.BorderEditing); + } + private SpriteRect TrySelect(Vector2 mousePosition) + { + float num = 1E+07f; + SpriteRect result = null; + for (int i = 0; i < this.m_RectsCache.Count; i++) + { + if (this.m_RectsCache.RectAt(i).m_Rect.Contains(Handles.s_InverseMatrix.MultiplyPoint(mousePosition))) + { + if (this.m_RectsCache.RectAt(i) == this.selected) + { + return this.m_RectsCache.RectAt(i); + } + float width = this.m_RectsCache.RectAt(i).m_Rect.width; + float height = this.m_RectsCache.RectAt(i).m_Rect.height; + float num2 = width * height; + if (width > 0f && height > 0f && num2 < num) + { + result = this.m_RectsCache.RectAt(i); + num = num2; + } + } + } + return result; + } + public SpriteRect AddSprite(Rect rect, int alignment, int colliderAlphaCutoff, float colliderDetail) + { + SpriteRect spriteRect = new SpriteRect(); + spriteRect.m_Rect = rect; + spriteRect.m_Alignment = (SpriteAlignment)alignment; + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.m_TextureImporter.assetPath); + spriteRect.m_Name = this.GetUniqueName(fileNameWithoutExtension); + this.textureIsDirty = true; + this.m_RectsCache.AddRect(spriteRect); + return spriteRect; + } + private string GetUniqueName(string prefix) + { + int num = 0; + string text; + bool flag; + do + { + text = prefix + "_" + num++; + flag = false; + foreach (SpriteRect current in this.m_RectsCache.m_Rects) + { + if (current.m_Name == text) + { + flag = true; + } + } + } + while (flag); + return text; + } + private Rect TrimAlpha(Rect rect) + { + int num = (int)rect.xMax; + int num2 = (int)rect.xMin; + int num3 = (int)rect.yMax; + int num4 = (int)rect.yMin; + for (int i = (int)rect.yMin; i < (int)rect.yMax; i++) + { + for (int j = (int)rect.xMin; j < (int)rect.xMax; j++) + { + if (this.PixelHasAlpha(j, i)) + { + num = Mathf.Min(num, j); + num2 = Mathf.Max(num2, j); + num3 = Mathf.Min(num3, i); + num4 = Mathf.Max(num4, i); + } + } + } + return new Rect((float)num, (float)num3, (float)(num2 - num + 1), (float)(num4 - num3 + 1)); + } + public void DoTextureReimport(string path) + { + if (this.m_TextureImporterSO != null) + { + try + { + AssetDatabase.StartAssetEditing(); + AssetDatabase.ImportAsset(path); + } + finally + { + AssetDatabase.StopAssetEditing(); + } + this.textureIsDirty = false; + } + } + private void HandleRectCornerScalingHandles() + { + if (this.selected == null) + { + return; + } + GUIStyle dragdot = SpriteUtilityWindow.s_Styles.dragdot; + GUIStyle dragdotactive = SpriteUtilityWindow.s_Styles.dragdotactive; + Color white = Color.white; + Rect rect = new Rect(this.selected.m_Rect); + float xMin = rect.xMin; + float xMax = rect.xMax; + float yMax = rect.yMax; + float yMin = rect.yMin; + EditorGUI.BeginChangeCheck(); + this.HandleBorderPointSlider(ref xMin, ref yMax, MouseCursor.ResizeUpLeft, false, dragdot, dragdotactive, white); + this.HandleBorderPointSlider(ref xMax, ref yMax, MouseCursor.ResizeUpRight, false, dragdot, dragdotactive, white); + this.HandleBorderPointSlider(ref xMin, ref yMin, MouseCursor.ResizeUpRight, false, dragdot, dragdotactive, white); + this.HandleBorderPointSlider(ref xMax, ref yMin, MouseCursor.ResizeUpLeft, false, dragdot, dragdotactive, white); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Scale sprite"); + rect.xMin = xMin; + rect.xMax = xMax; + rect.yMax = yMax; + rect.yMin = yMin; + this.selected.m_Rect = this.ClampSpriteRect(rect); + this.selected.m_Border = this.ClampSpriteBorder(this.selected.m_Border); + this.textureIsDirty = true; + } + if (GUIUtility.hotControl == 0) + { + this.selected.m_Rect = this.FlipNegativeRect(this.selected.m_Rect); + this.selected.m_Border = this.ClampSpriteBorder(this.selected.m_Border); + } + } + private void HandleRectSideScalingHandles() + { + if (this.selected == null) + { + return; + } + Rect rect = new Rect(this.selected.m_Rect); + float num = rect.xMin; + float num2 = rect.xMax; + float num3 = rect.yMax; + float num4 = rect.yMin; + Vector2 vector = Handles.matrix.MultiplyPoint(new Vector3(rect.xMin, rect.yMin)); + Vector2 vector2 = Handles.matrix.MultiplyPoint(new Vector3(rect.xMax, rect.yMax)); + float width = Mathf.Abs(vector2.x - vector.x); + float height = Mathf.Abs(vector2.y - vector.y); + EditorGUI.BeginChangeCheck(); + num = this.HandleBorderScaleSlider(num, rect.yMax, width, height, true); + num2 = this.HandleBorderScaleSlider(num2, rect.yMax, width, height, true); + num3 = this.HandleBorderScaleSlider(rect.xMin, num3, width, height, false); + num4 = this.HandleBorderScaleSlider(rect.xMin, num4, width, height, false); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Scale sprite"); + rect.xMin = num; + rect.xMax = num2; + rect.yMax = num3; + rect.yMin = num4; + this.selected.m_Rect = this.ClampSpriteRect(rect); + this.selected.m_Border = this.ClampSpriteBorder(this.selected.m_Border); + this.textureIsDirty = true; + } + } + private void HandleBorderSidePointScalingSliders() + { + if (this.selected == null) + { + return; + } + GUIStyle dragBorderdot = SpriteUtilityWindow.s_Styles.dragBorderdot; + GUIStyle dragBorderDotActive = SpriteUtilityWindow.s_Styles.dragBorderDotActive; + Color color = new Color(0f, 1f, 0f); + Rect rect = this.selected.m_Rect; + Vector4 border = this.selected.m_Border; + float num = rect.xMin + border.x; + float num2 = rect.xMax - border.z; + float num3 = rect.yMax - border.w; + float num4 = rect.yMin + border.y; + EditorGUI.BeginChangeCheck(); + float num5 = num4 - (num4 - num3) / 2f; + float num6 = num - (num - num2) / 2f; + float num7 = num5; + this.HandleBorderPointSlider(ref num, ref num7, MouseCursor.ResizeHorizontal, false, dragBorderdot, dragBorderDotActive, color); + num7 = num5; + this.HandleBorderPointSlider(ref num2, ref num7, MouseCursor.ResizeHorizontal, false, dragBorderdot, dragBorderDotActive, color); + num7 = num6; + this.HandleBorderPointSlider(ref num7, ref num3, MouseCursor.ResizeVertical, false, dragBorderdot, dragBorderDotActive, color); + num7 = num6; + this.HandleBorderPointSlider(ref num7, ref num4, MouseCursor.ResizeVertical, false, dragBorderdot, dragBorderDotActive, color); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Scale sprite border"); + border.x = num - rect.xMin; + border.z = rect.xMax - num2; + border.w = rect.yMax - num3; + border.y = num4 - rect.yMin; + this.textureIsDirty = true; + } + this.selected.m_Border = this.ClampSpriteBorder(border); + } + private void HandleBorderCornerScalingHandles() + { + if (this.selected == null) + { + return; + } + GUIStyle dragBorderdot = SpriteUtilityWindow.s_Styles.dragBorderdot; + GUIStyle dragBorderDotActive = SpriteUtilityWindow.s_Styles.dragBorderDotActive; + Color color = new Color(0f, 1f, 0f); + Rect rect = new Rect(this.selected.m_Rect); + Vector4 border = this.selected.m_Border; + float num = rect.xMin + border.x; + float num2 = rect.xMax - border.z; + float num3 = rect.yMax - border.w; + float num4 = rect.yMin + border.y; + EditorGUI.BeginChangeCheck(); + this.HandleBorderPointSlider(ref num, ref num3, MouseCursor.ResizeUpLeft, border.x < 1f && border.w < 1f, dragBorderdot, dragBorderDotActive, color); + this.HandleBorderPointSlider(ref num2, ref num3, MouseCursor.ResizeUpRight, border.z < 1f && border.w < 1f, dragBorderdot, dragBorderDotActive, color); + this.HandleBorderPointSlider(ref num, ref num4, MouseCursor.ResizeUpRight, border.x < 1f && border.y < 1f, dragBorderdot, dragBorderDotActive, color); + this.HandleBorderPointSlider(ref num2, ref num4, MouseCursor.ResizeUpLeft, border.z < 1f && border.y < 1f, dragBorderdot, dragBorderDotActive, color); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Scale sprite border"); + border.x = num - rect.xMin; + border.z = rect.xMax - num2; + border.w = rect.yMax - num3; + border.y = num4 - rect.yMin; + this.textureIsDirty = true; + } + this.selected.m_Border = this.ClampSpriteBorder(border); + } + private void HandleBorderSideScalingHandles() + { + if (this.selected == null) + { + return; + } + Rect rect = new Rect(this.selected.m_Rect); + Vector4 border = this.selected.m_Border; + float num = rect.xMin + border.x; + float num2 = rect.xMax - border.z; + float num3 = rect.yMax - border.w; + float num4 = rect.yMin + border.y; + Vector2 vector = Handles.matrix.MultiplyPoint(new Vector3(rect.xMin, rect.yMin)); + Vector2 vector2 = Handles.matrix.MultiplyPoint(new Vector3(rect.xMax, rect.yMax)); + float width = Mathf.Abs(vector2.x - vector.x); + float height = Mathf.Abs(vector2.y - vector.y); + EditorGUI.BeginChangeCheck(); + num = this.HandleBorderScaleSlider(num, rect.yMax, width, height, true); + num2 = this.HandleBorderScaleSlider(num2, rect.yMax, width, height, true); + num3 = this.HandleBorderScaleSlider(rect.xMin, num3, width, height, false); + num4 = this.HandleBorderScaleSlider(rect.xMin, num4, width, height, false); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Scale sprite border"); + border.x = num - rect.xMin; + border.z = rect.xMax - num2; + border.w = rect.yMax - num3; + border.y = num4 - rect.yMin; + this.selected.m_Border = this.ClampSpriteBorder(border); + this.textureIsDirty = true; + } + } + private void HandleBorderPointSlider(ref float x, ref float y, MouseCursor mouseCursor, bool isHidden, GUIStyle dragDot, GUIStyle dragDotActive, Color color) + { + Color color2 = GUI.color; + if (isHidden) + { + GUI.color = new Color(0f, 0f, 0f, 0f); + } + else + { + GUI.color = color; + } + Vector2 vector = SpriteEditorHandles.PointSlider(new Vector2(x, y), mouseCursor, dragDot, dragDotActive); + x = vector.x; + y = vector.y; + GUI.color = color2; + } + private float HandleBorderScaleSlider(float x, float y, float width, float height, bool isHorizontal) + { + float fixedWidth = SpriteUtilityWindow.s_Styles.dragBorderdot.fixedWidth; + Vector2 pos = Handles.matrix.MultiplyPoint(new Vector2(x, y)); + EditorGUI.BeginChangeCheck(); + float result; + if (isHorizontal) + { + Rect cursorRect = new Rect(pos.x - fixedWidth * 0.5f, pos.y, fixedWidth, height); + result = SpriteEditorHandles.ScaleSlider(pos, MouseCursor.ResizeHorizontal, cursorRect).x; + } + else + { + Rect cursorRect2 = new Rect(pos.x, pos.y - fixedWidth * 0.5f, width, fixedWidth); + result = SpriteEditorHandles.ScaleSlider(pos, MouseCursor.ResizeVertical, cursorRect2).y; + } + if (EditorGUI.EndChangeCheck()) + { + return result; + } + return (!isHorizontal) ? y : x; + } + public void DoAutomaticSlicing(int minimumSpriteSize, int alignment, SpriteEditorWindow.AutoSlicingMethod slicingMethod) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Automatic Slicing"); + if (slicingMethod == SpriteEditorWindow.AutoSlicingMethod.DeleteAll) + { + this.m_RectsCache.ClearAll(); + } + List list = new List(InternalSpriteUtility.GenerateAutomaticSpriteRectangles(this.m_Texture, minimumSpriteSize, 0)); + list = this.SortRects(list); + foreach (Rect current in list) + { + this.AddSprite(current, alignment, slicingMethod); + } + this.selected = null; + this.textureIsDirty = true; + base.Repaint(); + } + public void DoGridSlicing(Vector2 size, Vector2 offset, Vector2 padding, int alignment) + { + Rect[] array = InternalSpriteUtility.GenerateGridSpriteRectangles(this.m_Texture, offset, size, padding); + bool flag = true; + if (array.Length > 1000 && !EditorUtility.DisplayDialog("Creating multiple sprites", "Creating " + array.Length + " sprites. \nThis can take up to several minutes.", "Ok", "Cancel")) + { + flag = false; + } + if (flag) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Grid Slicing"); + this.m_RectsCache.ClearAll(); + Rect[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Rect rect = array2[i]; + this.AddSprite(rect, alignment, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + } + this.selected = null; + this.textureIsDirty = true; + } + base.Repaint(); + } + private List SortRects(List rects) + { + List list = new List(); + while (rects.Count > 0) + { + Rect rect = rects[rects.Count - 1]; + Rect sweepRect = new Rect(0f, rect.yMin, (float)this.m_Texture.width, rect.height); + List list2 = this.RectSweep(rects, sweepRect); + if (list2.Count <= 0) + { + list.AddRange(rects); + break; + } + list.AddRange(list2); + } + return list; + } + private List RectSweep(List rects, Rect sweepRect) + { + if (rects == null || rects.Count == 0) + { + return new List(); + } + List list = new List(); + foreach (Rect current in rects) + { + if (this.Overlap(current, sweepRect)) + { + list.Add(current); + } + } + foreach (Rect current2 in list) + { + rects.Remove(current2); + } + list.Sort((Rect a, Rect b) => a.x.CompareTo(b.x)); + return list; + } + private void AddSprite(Rect frame, int alignment, SpriteEditorWindow.AutoSlicingMethod slicingMethod) + { + if (slicingMethod != SpriteEditorWindow.AutoSlicingMethod.DeleteAll) + { + SpriteRect existingOverlappingSprite = this.GetExistingOverlappingSprite(frame); + if (existingOverlappingSprite != null) + { + if (slicingMethod == SpriteEditorWindow.AutoSlicingMethod.Smart) + { + existingOverlappingSprite.m_Rect = frame; + existingOverlappingSprite.m_Alignment = (SpriteAlignment)alignment; + } + } + else + { + this.AddSprite(frame, alignment, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + } + } + else + { + this.AddSprite(frame, alignment, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + } + } + private SpriteRect GetExistingOverlappingSprite(Rect rect) + { + for (int i = 0; i < this.m_RectsCache.Count; i++) + { + Rect rect2 = this.m_RectsCache.RectAt(i).m_Rect; + if (this.Overlap(rect2, rect)) + { + return this.m_RectsCache.RectAt(i); + } + } + return null; + } + private bool Overlap(Rect a, Rect b) + { + return a.xMin < b.xMax && a.xMax > b.xMin && a.yMin < b.yMax && a.yMax > b.yMin; + } + private bool MouseOnTopOfInspector() + { + if (this.selected == null) + { + return false; + } + Vector2 vector = GUIClip.Unclip(Event.current.mousePosition); + vector += new Vector2(0f, -22f); + return this.inspectorRect.Contains(vector); + } + private bool PixelHasAlpha(int x, int y) + { + if (this.m_Texture == null) + { + return false; + } + if (SpriteEditorWindow.s_AlphaPixelCache == null) + { + SpriteEditorWindow.s_AlphaPixelCache = new bool[this.m_Texture.width * this.m_Texture.height]; + Color32[] pixels = this.m_Texture.GetPixels32(); + for (int i = 0; i < pixels.Length; i++) + { + SpriteEditorWindow.s_AlphaPixelCache[i] = (pixels[i].a != 0); + } + } + int num = y * this.m_Texture.width + x; + return SpriteEditorWindow.s_AlphaPixelCache[num]; + } + private Texture2D CreateTemporaryDuplicate(Texture2D original, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original) + { + return null; + } + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + RenderTexture active = RenderTexture.active; + RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); + Graphics.Blit(original, temporary); + RenderTexture.active = temporary; + Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, original.mipmapCount > 1); + texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); + texture2D.Apply(); + RenderTexture.ReleaseTemporary(temporary); + EditorGUIUtility.SetRenderTextureNoViewport(active); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + texture2D.alphaIsTransparency = original.alphaIsTransparency; + return texture2D; + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteImportMode.cs b/UnityEditor/UnityEditor/SpriteImportMode.cs new file mode 100644 index 00000000..e6d80340 --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteImportMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum SpriteImportMode + { + None, + Single, + Multiple + } +} diff --git a/UnityEditor/UnityEditor/SpriteInspector.cs b/UnityEditor/UnityEditor/SpriteInspector.cs new file mode 100644 index 00000000..e4d9fffa --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteInspector.cs @@ -0,0 +1,298 @@ +using System; +using UnityEditor.Sprites; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Sprites; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Sprite))] + internal class SpriteInspector : Editor + { + public readonly GUIContent[] spriteAlignmentOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Custom") + }; + public readonly GUIContent spriteAlignment = EditorGUIUtility.TextContent("SpriteInspector.Pivot"); + private Sprite sprite + { + get + { + return this.target as Sprite; + } + } + private SpriteMetaData GetMetaData(string name) + { + string assetPath = AssetDatabase.GetAssetPath(this.sprite); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + if (!(textureImporter != null)) + { + return default(SpriteMetaData); + } + if (textureImporter.spriteImportMode == SpriteImportMode.Single) + { + return SpriteInspector.GetMetaDataInSingleMode(name, textureImporter); + } + return SpriteInspector.GetMetaDataInMultipleMode(name, textureImporter); + } + private static SpriteMetaData GetMetaDataInMultipleMode(string name, TextureImporter textureImporter) + { + SpriteMetaData[] spritesheet = textureImporter.spritesheet; + for (int i = 0; i < spritesheet.Length; i++) + { + if (spritesheet[i].name.Equals(name)) + { + return spritesheet[i]; + } + } + return default(SpriteMetaData); + } + private static SpriteMetaData GetMetaDataInSingleMode(string name, TextureImporter textureImporter) + { + SpriteMetaData result = default(SpriteMetaData); + result.border = textureImporter.spriteBorder; + result.name = name; + result.pivot = textureImporter.spritePivot; + result.rect = new Rect(0f, 0f, 1f, 1f); + TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); + textureImporter.ReadTextureSettings(textureImporterSettings); + result.alignment = textureImporterSettings.spriteAlignment; + return result; + } + public override void OnInspectorGUI() + { + bool flag; + bool flag2; + bool flag3; + this.UnifiedValues(out flag, out flag2, out flag3); + if (flag) + { + EditorGUILayout.LabelField("Name", this.sprite.name, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.LabelField("Name", "-", new GUILayoutOption[0]); + } + if (flag2) + { + int alignment = this.GetMetaData(this.sprite.name).alignment; + EditorGUILayout.LabelField(this.spriteAlignment, this.spriteAlignmentOptions[alignment], new GUILayoutOption[0]); + } + else + { + EditorGUILayout.LabelField(this.spriteAlignment.text, "-", new GUILayoutOption[0]); + } + if (flag3) + { + Vector4 border = this.GetMetaData(this.sprite.name).border; + EditorGUILayout.LabelField("Border", string.Format("L:{0} B:{1} R:{2} T:{3}", new object[] + { + border.x, + border.y, + border.z, + border.w + }), new GUILayoutOption[0]); + } + else + { + EditorGUILayout.LabelField("Border", "-", new GUILayoutOption[0]); + } + } + private void UnifiedValues(out bool name, out bool alignment, out bool border) + { + name = true; + alignment = true; + border = true; + if (base.targets.Length < 2) + { + return; + } + string assetPath = AssetDatabase.GetAssetPath(this.sprite); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + SpriteMetaData[] spritesheet = textureImporter.spritesheet; + string text = null; + int num = -1; + Vector4? vector = null; + for (int i = 0; i < base.targets.Length; i++) + { + Sprite sprite = base.targets[i] as Sprite; + for (int j = 0; j < spritesheet.Length; j++) + { + if (spritesheet[j].name.Equals(sprite.name)) + { + if (spritesheet[j].alignment != num && num > 0) + { + alignment = false; + } + else + { + num = spritesheet[j].alignment; + } + if (spritesheet[j].name != text && text != null) + { + name = false; + } + else + { + text = spritesheet[j].name; + } + if (spritesheet[j].border != vector && vector.HasValue) + { + border = false; + } + else + { + vector = new Vector4?(spritesheet[j].border); + } + } + } + } + } + private static Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + float width2 = sprite.rect.width; + float height2 = sprite.rect.height; + Texture2D spriteTexture = UnityEditor.Sprites.DataUtility.GetSpriteTexture(sprite, false); + PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)width2, (int)height2, ref width, ref height); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState(); + RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Default); + RenderTexture.active = temporary; + GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear); + GL.Clear(true, true, new Color(0f, 0f, 0f, 0f)); + Texture texture = null; + Vector4 vector = new Vector4(0f, 0f, 0f, 0f); + bool flag = false; + bool flag2 = false; + if (spriteRendererMaterial != null) + { + flag = spriteRendererMaterial.HasProperty("_MainTex"); + flag2 = spriteRendererMaterial.HasProperty("_MainTex_TexelSize"); + } + Material material = null; + if (spriteRendererMaterial != null) + { + if (flag) + { + texture = spriteRendererMaterial.GetTexture("_MainTex"); + spriteRendererMaterial.SetTexture("_MainTex", spriteTexture); + } + if (flag2) + { + vector = spriteRendererMaterial.GetVector("_MainTex_TexelSize"); + spriteRendererMaterial.SetVector("_MainTex_TexelSize", TextureUtil.GetTexelSizeVector(spriteTexture)); + } + spriteRendererMaterial.SetPass(0); + } + else + { + material = new Material(Shader.Find("Hidden/BlitCopy")); + material.mainTexture = spriteTexture; + material.SetPass(0); + } + Vector4 spriteOuterUV = InternalEditorUtility.GetSpriteOuterUV(sprite, false); + Vector4 padding = UnityEngine.Sprites.DataUtility.GetPadding(sprite); + Rect textureRect = sprite.textureRect; + float width3 = textureRect.width; + float height3 = textureRect.height; + GL.PushMatrix(); + GL.LoadOrtho(); + GL.Begin(7); + GL.Color(new Color(1f, 1f, 1f, 1f)); + GL.TexCoord(new Vector3(spriteOuterUV.x, spriteOuterUV.w, 0f)); + GL.Vertex3(padding.x / width2, (padding.y + height3) / height2, 0f); + GL.TexCoord(new Vector3(spriteOuterUV.z, spriteOuterUV.w, 0f)); + GL.Vertex3((padding.x + width3) / width2, (padding.y + height3) / height2, 0f); + GL.TexCoord(new Vector3(spriteOuterUV.z, spriteOuterUV.y, 0f)); + GL.Vertex3((padding.x + width3) / width2, padding.y / height2, 0f); + GL.TexCoord(new Vector3(spriteOuterUV.x, spriteOuterUV.y, 0f)); + GL.Vertex3(padding.x / width2, padding.y / height2, 0f); + GL.End(); + GL.PopMatrix(); + GL.sRGBWrite = false; + if (spriteRendererMaterial != null) + { + if (flag) + { + spriteRendererMaterial.SetTexture("_MainTex", texture); + } + if (flag2) + { + spriteRendererMaterial.SetVector("_MainTex_TexelSize", vector); + } + } + Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false); + texture2D.hideFlags = HideFlags.HideAndDontSave; + texture2D.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); + texture2D.Apply(); + RenderTexture.ReleaseTemporary(temporary); + savedRenderTargetState.Restore(); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + if (material != null) + { + UnityEngine.Object.DestroyImmediate(material); + } + return texture2D; + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + return SpriteInspector.BuildPreviewTexture(width, height, this.sprite, null); + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (this.target == null) + { + return; + } + if (Event.current.type != EventType.Repaint) + { + return; + } + SpriteInspector.DrawPreview(r, this.sprite, null); + } + public static void DrawPreview(Rect r, Sprite frame, Material spriteRendererMaterial) + { + if (frame == null) + { + return; + } + float num = Mathf.Min(r.width / frame.rect.width, r.height / frame.rect.height); + Rect position = new Rect(r.x, r.y, frame.rect.width * num, frame.rect.height * num); + position.center = r.center; + Texture2D texture2D = SpriteInspector.BuildPreviewTexture((int)position.width, (int)position.height, frame, spriteRendererMaterial); + EditorGUI.DrawTextureTransparent(position, texture2D, ScaleMode.ScaleToFit); + Vector4 border = frame.border; + if (!Mathf.Approximately((border * num).sqrMagnitude, 0f)) + { + SpriteEditorUtility.BeginLines(new Color(0f, 1f, 0f, 0.7f)); + SpriteEditorUtility.EndLines(); + } + UnityEngine.Object.DestroyImmediate(texture2D); + } + public override string GetInfoString() + { + if (this.target == null) + { + return string.Empty; + } + Sprite sprite = this.target as Sprite; + return string.Format("({0}x{1})", (int)sprite.rect.width, (int)sprite.rect.height); + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteMetaData.cs b/UnityEditor/UnityEditor/SpriteMetaData.cs new file mode 100644 index 00000000..156c7642 --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteMetaData.cs @@ -0,0 +1,13 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public struct SpriteMetaData + { + public string name; + public Rect rect; + public int alignment; + public Vector2 pivot; + public Vector4 border; + } +} diff --git a/UnityEditor/UnityEditor/SpritePackerMode.cs b/UnityEditor/UnityEditor/SpritePackerMode.cs new file mode 100644 index 00000000..80fce42c --- /dev/null +++ b/UnityEditor/UnityEditor/SpritePackerMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum SpritePackerMode + { + Disabled, + BuildTimeOnly, + AlwaysOn + } +} diff --git a/UnityEditor/UnityEditor/SpriteRect.cs b/UnityEditor/UnityEditor/SpriteRect.cs new file mode 100644 index 00000000..ef8b8d69 --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteRect.cs @@ -0,0 +1,21 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class SpriteRect + { + [SerializeField] + public string m_Name = string.Empty; + [SerializeField] + public string m_OriginalName = string.Empty; + [SerializeField] + public Vector2 m_Pivot = Vector2.zero; + [SerializeField] + public SpriteAlignment m_Alignment; + [SerializeField] + public Vector4 m_Border; + [SerializeField] + public Rect m_Rect; + } +} diff --git a/UnityEditor/UnityEditor/SpriteRectCache.cs b/UnityEditor/UnityEditor/SpriteRectCache.cs new file mode 100644 index 00000000..1b3d9ba8 --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteRectCache.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class SpriteRectCache : ScriptableObject + { + [SerializeField] + public List m_Rects; + public int Count + { + get + { + if (this.m_Rects != null) + { + return this.m_Rects.Count; + } + return 0; + } + } + public SpriteRect RectAt(int i) + { + if (i >= this.Count) + { + return null; + } + return this.m_Rects[i]; + } + public void AddRect(SpriteRect r) + { + if (this.m_Rects != null) + { + this.m_Rects.Add(r); + } + } + public void RemoveRect(SpriteRect r) + { + if (this.m_Rects != null) + { + this.m_Rects.Remove(r); + } + } + public void ClearAll() + { + if (this.m_Rects != null) + { + this.m_Rects.Clear(); + } + } + public int GetIndex(SpriteRect spriteRect) + { + if (this.m_Rects != null) + { + return this.m_Rects.FindIndex((SpriteRect p) => p.Equals(spriteRect)); + } + return 0; + } + public bool Contains(SpriteRect spriteRect) + { + return this.m_Rects != null && this.m_Rects.Contains(spriteRect); + } + private void OnEnable() + { + if (this.m_Rects == null) + { + this.m_Rects = new List(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteRendererInspector.cs b/UnityEditor/UnityEditor/SpriteRendererInspector.cs new file mode 100644 index 00000000..1ee74bbe --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteRendererInspector.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SpriteRenderer))] + internal class SpriteRendererInspector : Editor + { + private SerializedProperty m_Sprite; + private SerializedProperty m_Color; + private SerializedProperty m_Material; + private SerializedProperty m_SortingOrder; + private SerializedProperty m_SortingLayerID; + private static Texture2D s_WarningIcon; + private GUIContent m_MaterialStyle = EditorGUIUtility.TextContent("SpriteRenderer.Material"); + private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingLayer"); + private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingOrder"); + public void OnEnable() + { + this.m_Sprite = base.serializedObject.FindProperty("m_Sprite"); + this.m_Color = base.serializedObject.FindProperty("m_Color"); + this.m_Material = base.serializedObject.FindProperty("m_Materials.Array"); + this.m_SortingOrder = base.serializedObject.FindProperty("m_SortingOrder"); + this.m_SortingLayerID = base.serializedObject.FindProperty("m_SortingLayerID"); + EditorUtility.SetSelectedWireframeHidden(this.target as SpriteRenderer, true); + } + public void OnDisable() + { + EditorUtility.SetSelectedWireframeHidden(this.target as SpriteRenderer, false); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Sprite, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Color, true, new GUILayoutOption[0]); + if (this.m_Material.arraySize == 0) + { + this.m_Material.InsertArrayElementAtIndex(0); + } + EditorGUILayout.PropertyField(this.m_Material.GetArrayElementAtIndex(0), this.m_MaterialStyle, true, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + this.CheckForErrors(); + base.serializedObject.ApplyModifiedProperties(); + } + private void CheckForErrors() + { + if (this.IsMaterialUsingFixedFunction()) + { + SpriteRendererInspector.ShowError("Material uses fixed function shader. It is not compatible with SpriteRenderer."); + } + if (this.IsMaterialTextureAtlasConflict()) + { + SpriteRendererInspector.ShowError("Material has CanUseSpriteAtlas=False tag. Sprite texture has atlasHint set. Rendering artifacts possible."); + } + bool flag; + if (!this.DoesMaterialHaveSpriteTexture(out flag)) + { + SpriteRendererInspector.ShowError("Material does not have a _MainTex texture property. It is required for SpriteRenderer."); + } + else + { + if (flag) + { + SpriteRendererInspector.ShowError("Material texture property _MainTex has offset/scale set. It is incompatible with SpriteRenderer."); + } + } + } + private bool IsMaterialUsingFixedFunction() + { + Material sharedMaterial = (this.target as SpriteRenderer).sharedMaterial; + return !(sharedMaterial == null) && ShaderUtil.DoesShaderContainFixedFunctionPasses(sharedMaterial.shader); + } + private bool IsMaterialTextureAtlasConflict() + { + Material sharedMaterial = (this.target as SpriteRenderer).sharedMaterial; + if (sharedMaterial == null) + { + return false; + } + string tag = sharedMaterial.GetTag("CanUseSpriteAtlas", false); + if (tag.ToLower() == "false") + { + Sprite assetObject = this.m_Sprite.objectReferenceValue as Sprite; + TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(assetObject)) as TextureImporter; + if (textureImporter.spritePackingTag != null && textureImporter.spritePackingTag.Length > 0) + { + return true; + } + } + return false; + } + private bool DoesMaterialHaveSpriteTexture(out bool tiled) + { + tiled = false; + Material sharedMaterial = (this.target as SpriteRenderer).sharedMaterial; + if (sharedMaterial == null) + { + return true; + } + bool flag = sharedMaterial.HasProperty("_MainTex"); + if (flag) + { + Vector2 textureOffset = sharedMaterial.GetTextureOffset("_MainTex"); + Vector2 textureScale = sharedMaterial.GetTextureScale("_MainTex"); + if (textureOffset.x != 0f || textureOffset.y != 0f || textureScale.x != 1f || textureScale.y != 1f) + { + tiled = true; + } + } + return sharedMaterial.HasProperty("_MainTex"); + } + private static void ShowError(string error) + { + if (SpriteRendererInspector.s_WarningIcon == null) + { + SpriteRendererInspector.s_WarningIcon = EditorGUIUtility.LoadIcon("console.warnicon"); + } + GUIContent content = new GUIContent(error) + { + image = SpriteRendererInspector.s_WarningIcon + }; + GUILayout.Space(5f); + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label(content, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteUtility.cs b/UnityEditor/UnityEditor/SpriteUtility.cs new file mode 100644 index 00000000..7a03bead --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteUtility.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal static class SpriteUtility + { + public static void OnSceneDrag(SceneView sceneView) + { + Event current = Event.current; + if (current.type != EventType.DragUpdated && current.type != EventType.DragPerform && current.type != EventType.DragExited) + { + return; + } + Sprite[] spriteFromDraggedPathsOrObjects = SpriteUtility.GetSpriteFromDraggedPathsOrObjects(); + if (spriteFromDraggedPathsOrObjects.Length == 0) + { + return; + } + Sprite sprite = spriteFromDraggedPathsOrObjects[0]; + if (sprite == null) + { + return; + } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + EventType type = current.type; + if (type == EventType.DragPerform) + { + Vector3 point = HandleUtility.GUIPointToWorldRay(current.mousePosition).GetPoint(10f); + point.z = 0f; + GameObject objectToUndo = SpriteUtility.DropFramesToSceneToCreateGO(sprite.name, spriteFromDraggedPathsOrObjects, point); + Undo.RegisterCreatedObjectUndo(objectToUndo, "Create Sprite"); + current.Use(); + } + } + private static bool CreateAnimation(GameObject gameObject, UnityEngine.Object[] frames) + { + Array.Sort(frames, (UnityEngine.Object a, UnityEngine.Object b) => EditorUtility.NaturalCompare(a.name, b.name)); + string message = string.Format("Create a new animation for the game object '{0}':", gameObject.name); + string directoryName = Path.GetDirectoryName(AssetDatabase.GetAssetPath(frames[0])); + string text = EditorUtility.SaveFilePanelInProject("Create New Animation", "New Animation", "anim", message, directoryName); + if (string.IsNullOrEmpty(text)) + { + return false; + } + AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true); + AssetDatabase.CreateAsset(animationClip, text); + AnimationSelection.AddClipToAnimatorComponent(gameObject, animationClip); + animationClip.frameRate = 12f; + ObjectReferenceKeyframe[] array = new ObjectReferenceKeyframe[frames.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = default(ObjectReferenceKeyframe); + array[i].value = SpriteUtility.RemapObjectToSprite(frames[i]); + array[i].time = (float)i / animationClip.frameRate; + } + EditorCurveBinding binding = EditorCurveBinding.PPtrCurve(string.Empty, typeof(SpriteRenderer), "m_Sprite"); + AnimationUtility.SetObjectReferenceCurve(animationClip, binding, array); + return true; + } + public static Sprite[] GetSpriteFromDraggedPathsOrObjects() + { + List list = new List(); + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + for (int i = 0; i < objectReferences.Length; i++) + { + UnityEngine.Object @object = objectReferences[i]; + if (AssetDatabase.Contains(@object)) + { + if (@object is Sprite) + { + list.Add(@object as Sprite); + } + else + { + if (@object is Texture2D) + { + list.Add(SpriteUtility.TextureToSprite(@object as Texture2D)); + } + } + } + } + if (list.Count > 0) + { + return list.ToArray(); + } + return new Sprite[] + { + SpriteUtility.HandleExternalDrag(Event.current.type == EventType.DragPerform) + }; + } + public static Sprite[] GetSpritesFromDraggedObjects() + { + List list = new List(); + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + for (int i = 0; i < objectReferences.Length; i++) + { + UnityEngine.Object @object = objectReferences[i]; + if (@object.GetType() == typeof(Sprite)) + { + list.Add(@object as Sprite); + } + else + { + if (@object.GetType() == typeof(Texture2D)) + { + Sprite sprite = SpriteUtility.TextureToSprite(@object as Texture2D); + if (sprite != null) + { + list.Add(sprite); + } + } + } + } + return list.ToArray(); + } + private static Sprite HandleExternalDrag(bool perform) + { + if (DragAndDrop.paths.Length == 0) + { + return null; + } + string text = DragAndDrop.paths[0]; + if (!SpriteUtility.ValidPathForTextureAsset(text)) + { + return null; + } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (!perform) + { + return null; + } + string text2 = AssetDatabase.GenerateUniqueAssetPath(Path.Combine("Assets", FileUtil.GetLastPathNameComponent(text))); + if (text2.Length <= 0) + { + return null; + } + FileUtil.CopyFileOrDirectory(text, text2); + SpriteUtility.ForcedImportFor(text2); + return SpriteUtility.GenerateDefaultSprite(AssetDatabase.LoadMainAssetAtPath(text2) as Texture2D); + } + public static bool HandleMultipleSpritesDragIntoHierarchy(IHierarchyProperty property, Sprite[] sprites, bool perform) + { + GameObject gameObject = null; + if (property == null || property.pptrValue == null) + { + if (perform) + { + Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites to empty hierarchy", "null", 1); + gameObject = new GameObject(); + gameObject.name = sprites[0].name; + gameObject.transform.position = SpriteUtility.GetDefaultInstantiatePosition(); + } + } + else + { + UnityEngine.Object pptrValue = property.pptrValue; + gameObject = (pptrValue as GameObject); + if (perform) + { + Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites to gameobject", "null", 1); + } + } + if (perform) + { + SpriteRenderer spriteRenderer = gameObject.GetComponent(); + if (spriteRenderer == null) + { + spriteRenderer = gameObject.AddComponent(); + } + if (spriteRenderer == null) + { + return true; + } + if (spriteRenderer.sprite == null) + { + spriteRenderer.sprite = sprites[0]; + } + SpriteUtility.CreateAnimation(gameObject, sprites); + Selection.activeGameObject = gameObject; + } + return true; + } + public static bool HandleSingleSpriteDragIntoHierarchy(IHierarchyProperty property, Sprite sprite, bool perform) + { + GameObject gameObject = null; + if (property != null && property.pptrValue != null) + { + UnityEngine.Object pptrValue = property.pptrValue; + gameObject = (pptrValue as GameObject); + } + if (perform) + { + Vector3 defaultInstantiatePosition = SpriteUtility.GetDefaultInstantiatePosition(); + GameObject gameObject2 = SpriteUtility.DropSpriteToSceneToCreateGO(sprite.name, sprite, defaultInstantiatePosition); + if (gameObject != null) + { + Analytics.Event("Sprite Drag and Drop", "Drop single sprite to existing gameobject", "null", 1); + gameObject2.transform.parent = gameObject.transform; + gameObject2.transform.localPosition = Vector3.zero; + } + else + { + Analytics.Event("Sprite Drag and Drop", "Drop single sprite to empty hierarchy", "null", 1); + } + Selection.activeGameObject = gameObject2; + } + return true; + } + private static Vector3 GetDefaultInstantiatePosition() + { + Vector3 result = Vector3.zero; + if (SceneView.lastActiveSceneView) + { + if (SceneView.lastActiveSceneView.in2DMode) + { + result = SceneView.lastActiveSceneView.camera.transform.position; + result.z = 0f; + } + else + { + result = SceneView.lastActiveSceneView.cameraTargetPosition; + } + } + return result; + } + private static void ForcedImportFor(string newPath) + { + try + { + AssetDatabase.StartAssetEditing(); + AssetDatabase.ImportAsset(newPath); + } + finally + { + AssetDatabase.StopAssetEditing(); + } + } + private static Sprite GenerateDefaultSprite(Texture2D texture) + { + string assetPath = AssetDatabase.GetAssetPath(texture); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + if (textureImporter.textureType != TextureImporterType.Sprite && textureImporter.textureType != TextureImporterType.Advanced) + { + return null; + } + if (textureImporter.spriteImportMode == SpriteImportMode.None) + { + if (textureImporter.textureType == TextureImporterType.Advanced) + { + return null; + } + textureImporter.spriteImportMode = SpriteImportMode.Single; + AssetDatabase.WriteImportSettingsIfDirty(assetPath); + SpriteUtility.ForcedImportFor(assetPath); + } + UnityEngine.Object @object = null; + try + { + @object = AssetDatabase.LoadAllAssetsAtPath(assetPath).First((UnityEngine.Object t) => t is Sprite); + } + catch (Exception) + { + Debug.LogWarning("Texture being dragged has no Sprites."); + } + return @object as Sprite; + } + public static GameObject DropFramesToSceneToCreateGO(string name, Sprite[] frames, Vector3 position) + { + if (frames.Length > 0) + { + Sprite sprite = frames[0]; + GameObject gameObject = new GameObject(name); + SpriteRenderer spriteRenderer = gameObject.AddComponent(); + spriteRenderer.sprite = sprite; + gameObject.transform.position = position; + Selection.activeObject = gameObject; + if (frames.Length > 1) + { + Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites to scene", "null", 1); + if (!SpriteUtility.CreateAnimation(gameObject, frames)) + { + UnityEngine.Object.DestroyImmediate(gameObject); + return null; + } + } + else + { + Analytics.Event("Sprite Drag and Drop", "Drop single sprite to scene", "null", 1); + } + return gameObject; + } + return null; + } + public static GameObject DropSpriteToSceneToCreateGO(string name, Sprite sprite, Vector3 position) + { + GameObject gameObject = new GameObject(name); + gameObject.name = sprite.name; + SpriteRenderer spriteRenderer = gameObject.AddComponent(); + spriteRenderer.sprite = sprite; + gameObject.transform.position = position; + Selection.activeObject = gameObject; + return gameObject; + } + public static Sprite RemapObjectToSprite(UnityEngine.Object obj) + { + if (obj is Sprite) + { + return (Sprite)obj; + } + if (obj is Texture2D) + { + UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(obj)); + for (int i = 0; i < array.Length; i++) + { + if (array[i].GetType() == typeof(Sprite)) + { + return array[i] as Sprite; + } + } + } + return null; + } + public static Sprite TextureToSprite(Texture2D tex) + { + UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); + for (int i = 0; i < array.Length; i++) + { + if (array[i].GetType() == typeof(Sprite)) + { + return array[i] as Sprite; + } + } + return SpriteUtility.GenerateDefaultSprite(tex); + } + private static bool ValidPathForTextureAsset(string path) + { + string a = FileUtil.GetPathExtension(path).ToLower(); + return a == "jpg" || a == "jpeg" || a == "tif" || a == "tiff" || a == "tga" || a == "gif" || a == "png" || a == "psd" || a == "bmp" || a == "iff" || a == "pict" || a == "pic" || a == "pct" || a == "exr"; + } + } +} diff --git a/UnityEditor/UnityEditor/SpriteUtilityWindow.cs b/UnityEditor/UnityEditor/SpriteUtilityWindow.cs new file mode 100644 index 00000000..d375b6cb --- /dev/null +++ b/UnityEditor/UnityEditor/SpriteUtilityWindow.cs @@ -0,0 +1,277 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class SpriteUtilityWindow : EditorWindow + { + protected class Styles + { + public readonly GUIStyle dragdot = "U2D.dragDot"; + public readonly GUIStyle dragdotDimmed = "U2D.dragDotDimmed"; + public readonly GUIStyle dragdotactive = "U2D.dragDotActive"; + public readonly GUIStyle createRect = "U2D.createRect"; + public readonly GUIStyle preToolbar = "preToolbar"; + public readonly GUIStyle preButton = "preButton"; + public readonly GUIStyle preLabel = "preLabel"; + public readonly GUIStyle preSlider = "preSlider"; + public readonly GUIStyle preSliderThumb = "preSliderThumb"; + public readonly GUIStyle preBackground = "preBackground"; + public readonly GUIStyle pivotdotactive = "U2D.pivotDotActive"; + public readonly GUIStyle pivotdot = "U2D.pivotDot"; + public readonly GUIStyle dragBorderdot = new GUIStyle(); + public readonly GUIStyle dragBorderDotActive = new GUIStyle(); + public readonly GUIStyle toolbar; + public readonly GUIContent alphaIcon; + public readonly GUIContent RGBIcon; + public readonly GUIStyle notice; + public readonly GUIContent smallMip; + public readonly GUIContent largeMip; + public Styles() + { + this.toolbar = new GUIStyle(EditorStyles.inspectorBig); + this.toolbar.margin.top = 0; + this.toolbar.margin.bottom = 0; + this.alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); + this.RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); + this.preToolbar.border.top = 0; + this.createRect.border = new RectOffset(3, 3, 3, 3); + this.notice = new GUIStyle(GUI.skin.label); + this.notice.alignment = TextAnchor.MiddleCenter; + this.notice.normal.textColor = Color.yellow; + this.dragBorderdot.fixedHeight = 5f; + this.dragBorderdot.fixedWidth = 5f; + this.dragBorderdot.normal.background = EditorGUIUtility.whiteTexture; + this.dragBorderDotActive.fixedHeight = this.dragBorderdot.fixedHeight; + this.dragBorderDotActive.fixedWidth = this.dragBorderdot.fixedWidth; + this.dragBorderDotActive.normal.background = EditorGUIUtility.whiteTexture; + this.smallMip = EditorGUIUtility.IconContent("PreTextureMipMapLow"); + this.largeMip = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); + } + } + protected const float k_BorderMargin = 10f; + protected const float k_ScrollbarMargin = 16f; + protected const float k_InspectorWindowMargin = 8f; + protected const float k_InspectorWidth = 330f; + protected const float k_InspectorHeight = 148f; + protected const float k_MinZoomPercentage = 0.9f; + protected const float k_MaxZoom = 10f; + protected const float k_WheelZoomSpeed = 0.03f; + protected const float k_MouseZoomSpeed = 0.005f; + protected static SpriteUtilityWindow.Styles s_Styles; + protected Texture2D m_Texture; + protected Rect m_TextureViewRect; + protected Rect m_TextureRect; + protected bool m_ShowAlpha; + protected float m_Zoom = -1f; + protected float m_MipLevel; + protected Vector2 m_ScrollPosition = default(Vector2); + protected Rect maxScrollRect + { + get + { + float num = (float)this.m_Texture.width * 0.5f * this.m_Zoom; + float num2 = (float)this.m_Texture.height * 0.5f * this.m_Zoom; + return new Rect(-num, -num2, this.m_TextureViewRect.width + num * 2f, this.m_TextureViewRect.height + num2 * 2f); + } + } + protected Rect maxRect + { + get + { + float num = this.m_TextureViewRect.width * 0.5f / this.GetMinZoom(); + float num2 = this.m_TextureViewRect.height * 0.5f / this.GetMinZoom(); + float left = -num; + float top = -num2; + float width = (float)this.m_Texture.width + num * 2f; + float height = (float)this.m_Texture.height + num2 * 2f; + return new Rect(left, top, width, height); + } + } + protected void InitStyles() + { + if (SpriteUtilityWindow.s_Styles == null) + { + SpriteUtilityWindow.s_Styles = new SpriteUtilityWindow.Styles(); + } + } + protected float GetMinZoom() + { + if (this.m_Texture == null) + { + return 1f; + } + return Mathf.Min(this.m_TextureViewRect.width / (float)this.m_Texture.width, this.m_TextureViewRect.height / (float)this.m_Texture.height) * 0.9f; + } + protected void HandleZoom() + { + bool flag = Event.current.alt && Event.current.button == 1; + if (flag) + { + EditorGUIUtility.AddCursorRect(this.m_TextureViewRect, MouseCursor.Zoom); + } + if (((Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown) && flag) || ((Event.current.type == EventType.KeyUp || Event.current.type == EventType.KeyDown) && Event.current.keyCode == KeyCode.LeftAlt)) + { + base.Repaint(); + } + if (Event.current.type == EventType.ScrollWheel || (Event.current.type == EventType.MouseDrag && Event.current.alt && Event.current.button == 1)) + { + float num = 1f - Event.current.delta.y * ((Event.current.type != EventType.ScrollWheel) ? -0.005f : 0.03f); + float num2 = this.m_Zoom * num; + float num3 = Mathf.Clamp(num2, this.GetMinZoom(), 10f); + if (num3 != this.m_Zoom) + { + this.m_Zoom = num3; + if (num2 != num3) + { + num /= num2 / num3; + } + this.m_ScrollPosition *= num; + Event.current.Use(); + } + } + } + protected void HandlePanning() + { + bool flag = (!Event.current.alt && Event.current.button > 0) || (Event.current.alt && Event.current.button <= 0); + if (flag && GUIUtility.hotControl == 0) + { + EditorGUIUtility.AddCursorRect(this.m_TextureViewRect, MouseCursor.Pan); + if (Event.current.type == EventType.MouseDrag) + { + this.m_ScrollPosition -= Event.current.delta; + Event.current.Use(); + } + } + if (((Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown) && flag) || ((Event.current.type == EventType.KeyUp || Event.current.type == EventType.KeyDown) && Event.current.keyCode == KeyCode.LeftAlt)) + { + base.Repaint(); + } + } + protected void DrawTexturespaceBackground() + { + float num = Mathf.Max(this.maxRect.width, this.maxRect.height); + Vector2 b = new Vector2(this.maxRect.xMin, this.maxRect.yMin); + float num2 = num * 0.5f; + float a = (!EditorGUIUtility.isProSkin) ? 0.08f : 0.15f; + float num3 = 8f; + SpriteEditorUtility.BeginLines(new Color(0f, 0f, 0f, a)); + for (float num4 = 0f; num4 <= num; num4 += num3) + { + SpriteEditorUtility.DrawLine(new Vector2(-num2 + num4, num2 + num4) + b, new Vector2(num2 + num4, -num2 + num4) + b); + } + SpriteEditorUtility.EndLines(); + } + private float Log2(float x) + { + return (float)(Math.Log((double)x) / Math.Log(2.0)); + } + protected void DrawTexture() + { + int num = Mathf.Max(this.m_Texture.width, 1); + float num2 = Mathf.Min(this.m_MipLevel, (float)(TextureUtil.CountMipmaps(this.m_Texture) - 1)); + float mipMapBias = this.m_Texture.mipMapBias; + TextureUtil.SetMipMapBiasNoDirty(this.m_Texture, num2 - this.Log2((float)num / this.m_TextureRect.width)); + FilterMode filterMode = this.m_Texture.filterMode; + TextureUtil.SetFilterModeNoDirty(this.m_Texture, FilterMode.Point); + if (this.m_ShowAlpha) + { + EditorGUI.DrawTextureAlpha(this.m_TextureRect, this.m_Texture); + } + else + { + EditorGUI.DrawTextureTransparent(this.m_TextureRect, this.m_Texture); + } + TextureUtil.SetMipMapBiasNoDirty(this.m_Texture, mipMapBias); + TextureUtil.SetFilterModeNoDirty(this.m_Texture, filterMode); + } + protected void DrawScreenspaceBackground() + { + if (Event.current.type == EventType.Repaint) + { + SpriteUtilityWindow.s_Styles.preBackground.Draw(this.m_TextureViewRect, false, false, false, false); + } + } + protected void HandleScrollbars() + { + Rect position = new Rect(this.m_TextureViewRect.xMin, this.m_TextureViewRect.yMax, this.m_TextureViewRect.width, 16f); + this.m_ScrollPosition.x = GUI.HorizontalScrollbar(position, this.m_ScrollPosition.x, this.m_TextureViewRect.width, this.maxScrollRect.xMin, this.maxScrollRect.xMax); + Rect position2 = new Rect(this.m_TextureViewRect.xMax, this.m_TextureViewRect.yMin, 16f, this.m_TextureViewRect.height); + this.m_ScrollPosition.y = GUI.VerticalScrollbar(position2, this.m_ScrollPosition.y, this.m_TextureViewRect.height, this.maxScrollRect.yMin, this.maxScrollRect.yMax); + } + protected void SetupHandlesMatrix() + { + Vector3 pos = new Vector3(this.m_TextureRect.x, this.m_TextureRect.yMax, 0f); + Vector3 s = new Vector3(this.m_Zoom, -this.m_Zoom, 1f); + Handles.matrix = Matrix4x4.TRS(pos, Quaternion.identity, s); + } + protected void DoAlphaZoomToolbarGUI() + { + this.m_ShowAlpha = GUILayout.Toggle(this.m_ShowAlpha, (!this.m_ShowAlpha) ? SpriteUtilityWindow.s_Styles.RGBIcon : SpriteUtilityWindow.s_Styles.alphaIcon, "toolbarButton", new GUILayoutOption[0]); + this.m_Zoom = GUILayout.HorizontalSlider(this.m_Zoom, this.GetMinZoom(), 10f, SpriteUtilityWindow.s_Styles.preSlider, SpriteUtilityWindow.s_Styles.preSliderThumb, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + }); + int num = 1; + if (this.m_Texture != null) + { + num = Mathf.Max(num, TextureUtil.CountMipmaps(this.m_Texture)); + } + EditorGUI.BeginDisabledGroup(num == 1); + GUILayout.Box(SpriteUtilityWindow.s_Styles.smallMip, SpriteUtilityWindow.s_Styles.preLabel, new GUILayoutOption[0]); + this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, SpriteUtilityWindow.s_Styles.preSlider, SpriteUtilityWindow.s_Styles.preSliderThumb, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + })); + GUILayout.Box(SpriteUtilityWindow.s_Styles.largeMip, SpriteUtilityWindow.s_Styles.preLabel, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + } + protected void DoTextureGUI() + { + if (this.m_Texture == null) + { + return; + } + if (this.m_Zoom < 0f) + { + this.m_Zoom = this.GetMinZoom(); + } + this.m_TextureRect = new Rect(this.m_TextureViewRect.width / 2f - (float)this.m_Texture.width * this.m_Zoom / 2f, this.m_TextureViewRect.height / 2f - (float)this.m_Texture.height * this.m_Zoom / 2f, (float)this.m_Texture.width * this.m_Zoom, (float)this.m_Texture.height * this.m_Zoom); + this.HandleScrollbars(); + this.SetupHandlesMatrix(); + this.HandleZoom(); + this.HandlePanning(); + this.DrawScreenspaceBackground(); + GUIClip.Push(this.m_TextureViewRect, -this.m_ScrollPosition, Vector2.zero, false); + if (Event.current.type == EventType.Repaint) + { + this.DrawTexturespaceBackground(); + this.DrawTexture(); + this.DrawGizmos(); + } + this.DoTextureGUIExtras(); + GUIClip.Pop(); + } + protected virtual void DoTextureGUIExtras() + { + } + protected virtual void DrawGizmos() + { + } + protected void SetNewTexture(Texture2D texture) + { + if (texture != this.m_Texture) + { + this.m_Texture = texture; + this.m_Zoom = -1f; + } + } + internal override void OnResized() + { + if (this.m_Texture != null && Event.current != null) + { + this.HandleZoom(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/StaticEditorFlags.cs b/UnityEditor/UnityEditor/StaticEditorFlags.cs new file mode 100644 index 00000000..458d5988 --- /dev/null +++ b/UnityEditor/UnityEditor/StaticEditorFlags.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + [Flags] + public enum StaticEditorFlags + { + LightmapStatic = 1, + OccluderStatic = 2, + OccludeeStatic = 16, + BatchingStatic = 4, + NavigationStatic = 8, + OffMeshLinkGeneration = 32 + } +} diff --git a/UnityEditor/UnityEditor/StaticOcclusionCulling.cs b/UnityEditor/UnityEditor/StaticOcclusionCulling.cs new file mode 100644 index 00000000..2caaa773 --- /dev/null +++ b/UnityEditor/UnityEditor/StaticOcclusionCulling.cs @@ -0,0 +1,69 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class StaticOcclusionCulling + { + public static extern bool isRunning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float smallestOccluder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float smallestHole + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float backfaceThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool doesSceneHaveManualPortals + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int umbraDataSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Compute(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GenerateInBackground(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Cancel(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDefaultOcclusionBakeSettings(); + } +} diff --git a/UnityEditor/UnityEditor/StaticOcclusionCullingVisualization.cs b/UnityEditor/UnityEditor/StaticOcclusionCullingVisualization.cs new file mode 100644 index 00000000..5889c486 --- /dev/null +++ b/UnityEditor/UnityEditor/StaticOcclusionCullingVisualization.cs @@ -0,0 +1,90 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class StaticOcclusionCullingVisualization + { + public static extern bool showOcclusionCulling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showPreVisualization + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showViewVolumes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showDynamicObjectBounds + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showPortals + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showVisibilityLines + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showGeometryCulling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool isPreviewOcclusionCullingCameraInPVS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Camera previewOcclusionCamera + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Camera previewOcclucionCamera + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + } +} diff --git a/UnityEditor/UnityEditor/StrippingLevel.cs b/UnityEditor/UnityEditor/StrippingLevel.cs new file mode 100644 index 00000000..10e5019b --- /dev/null +++ b/UnityEditor/UnityEditor/StrippingLevel.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum StrippingLevel + { + Disabled, + StripAssemblies, + StripByteCode, + UseMicroMSCorlib + } +} diff --git a/UnityEditor/UnityEditor/StructPropertyGUI.cs b/UnityEditor/UnityEditor/StructPropertyGUI.cs new file mode 100644 index 00000000..507c02bc --- /dev/null +++ b/UnityEditor/UnityEditor/StructPropertyGUI.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class StructPropertyGUI + { + internal static void JointSpring(Rect position, SerializedProperty property) + { + StructPropertyGUI.GenericStruct(position, property); + } + internal static void WheelFrictionCurve(Rect position, SerializedProperty property) + { + StructPropertyGUI.GenericStruct(position, property); + } + internal static void GenericStruct(Rect position, SerializedProperty property) + { + GUI.Label(EditorGUI.IndentedRect(position), property.displayName, EditorStyles.label); + position.y += 16f; + StructPropertyGUI.DoChildren(position, property); + } + private static void DoChildren(Rect position, SerializedProperty property) + { + float num = (float)property.depth; + position.height = 16f; + EditorGUI.indentLevel++; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + while ((float)serializedProperty.depth == num + 1f) + { + EditorGUI.PropertyField(position, serializedProperty); + position.y += 16f; + serializedProperty.NextVisible(false); + } + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + } + } +} diff --git a/UnityEditor/UnityEditor/StructPropertyGUILayout.cs b/UnityEditor/UnityEditor/StructPropertyGUILayout.cs new file mode 100644 index 00000000..a14e7bc0 --- /dev/null +++ b/UnityEditor/UnityEditor/StructPropertyGUILayout.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class StructPropertyGUILayout + { + internal static void JointSpring(SerializedProperty property, params GUILayoutOption[] options) + { + StructPropertyGUILayout.GenericStruct(property, options); + } + internal static void WheelFrictionCurve(SerializedProperty property, params GUILayoutOption[] options) + { + StructPropertyGUILayout.GenericStruct(property, options); + } + internal static void GenericStruct(SerializedProperty property, params GUILayoutOption[] options) + { + float num = 16f + 16f * (float)StructPropertyGUILayout.GetChildrenCount(property); + Rect rect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, num, num, EditorStyles.layerMaskField, options); + StructPropertyGUI.GenericStruct(rect, property); + } + internal static int GetChildrenCount(SerializedProperty property) + { + int depth = property.depth; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + int num = 0; + while (serializedProperty.depth == depth + 1) + { + num++; + serializedProperty.NextVisible(false); + } + return num; + } + } +} diff --git a/UnityEditor/UnityEditor/SubModuleUI.cs b/UnityEditor/UnityEditor/SubModuleUI.cs new file mode 100644 index 00000000..11c510c8 --- /dev/null +++ b/UnityEditor/UnityEditor/SubModuleUI.cs @@ -0,0 +1,217 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SubModuleUI : ModuleUI + { + public enum SubEmitterType + { + None = -1, + Birth, + Collision, + Death, + TypesMax + } + private class Texts + { + public GUIContent[] subEmitterTypeTexts; + public GUIContent create = new GUIContent(string.Empty, "Create and assign a Particle System as sub emitter"); + public Texts() + { + this.subEmitterTypeTexts = new GUIContent[3]; + this.subEmitterTypeTexts[0] = new GUIContent("Birth", "Start spawning on birth of particle."); + this.subEmitterTypeTexts[1] = new GUIContent("Collision", "Spawn on collision of particle. Sub emitter can only emit as burst."); + this.subEmitterTypeTexts[2] = new GUIContent("Death", "Spawn on death of particle. Sub emitter can only emit as burst."); + } + } + private const int k_MaxSubPerType = 2; + private SerializedProperty[,] m_SubEmitters; + private int m_CheckObjectTypeIndex = -1; + private int m_CheckObjectIndex = -1; + private static SubModuleUI.Texts s_Texts; + public SubModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "SubModule", displayName) + { + this.m_ToolTip = "Sub emission of particles. This allows each particle to emit particles in another system."; + this.Init(); + } + protected override void Init() + { + if (this.m_SubEmitters != null) + { + return; + } + this.m_SubEmitters = new SerializedProperty[3, 2]; + this.m_SubEmitters[0, 0] = base.GetProperty("subEmitterBirth"); + this.m_SubEmitters[0, 1] = base.GetProperty("subEmitterBirth1"); + this.m_SubEmitters[1, 0] = base.GetProperty("subEmitterCollision"); + this.m_SubEmitters[1, 1] = base.GetProperty("subEmitterCollision1"); + this.m_SubEmitters[2, 0] = base.GetProperty("subEmitterDeath"); + this.m_SubEmitters[2, 1] = base.GetProperty("subEmitterDeath1"); + } + public override void Validate() + { + } + private void CreateAndAssignSubEmitter(SerializedProperty objectRefProp, SubModuleUI.SubEmitterType type) + { + GameObject gameObject = this.m_ParticleSystemUI.m_ParticleEffectUI.CreateParticleSystem(this.m_ParticleSystemUI.m_ParticleSystem, type); + gameObject.name = "SubEmitter"; + objectRefProp.objectReferenceValue = gameObject.GetComponent(); + } + private void Update() + { + if (this.m_CheckObjectIndex >= 0 && this.m_CheckObjectTypeIndex >= 0 && !ObjectSelector.isVisible) + { + UnityEngine.Object objectReferenceValue = this.m_SubEmitters[this.m_CheckObjectTypeIndex, this.m_CheckObjectIndex].objectReferenceValue; + ParticleSystem particleSystem = objectReferenceValue as ParticleSystem; + if (particleSystem != null) + { + bool flag = true; + if (this.ValidateSubemitter(particleSystem)) + { + string text = ParticleSystemEditorUtils.CheckCircularReferences(particleSystem, this.m_ParticleSystemUI.m_ParticleSystem, this.m_ParticleSystemUI.m_ParticleEffectUI.GetRoot()); + if (text.Length == 0) + { + this.CheckIfChild(objectReferenceValue); + } + else + { + string message = string.Format("'{0}' could not be assigned as subemitter on '{1}' due to circular referencing!\nBacktrace: {2} \n\nReference will be removed.", particleSystem.gameObject.name, this.m_ParticleSystemUI.m_ParticleSystem.gameObject.name, text); + EditorUtility.DisplayDialog("Circular References Detected", message, "Ok"); + flag = false; + } + } + else + { + flag = false; + } + if (!flag) + { + this.m_SubEmitters[this.m_CheckObjectTypeIndex, this.m_CheckObjectIndex].objectReferenceValue = null; + this.m_ParticleSystemUI.ApplyProperties(); + this.m_ParticleSystemUI.m_ParticleEffectUI.m_Owner.Repaint(); + } + } + this.m_CheckObjectIndex = -1; + this.m_CheckObjectTypeIndex = -1; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + } + internal static bool IsChild(ParticleSystem subEmitter, ParticleSystem root) + { + if (subEmitter == null || root == null) + { + return false; + } + ParticleSystem root2 = ParticleSystemEditorUtils.GetRoot(subEmitter); + return root2 == root; + } + private bool ValidateSubemitter(ParticleSystem subEmitter) + { + if (subEmitter == null) + { + return false; + } + ParticleSystem root = this.m_ParticleSystemUI.m_ParticleEffectUI.GetRoot(); + if (root.gameObject.activeInHierarchy && !subEmitter.gameObject.activeInHierarchy) + { + string message = string.Format("The assigned sub emitter is part of a prefab and can therefore not be assigned.", new object[0]); + EditorUtility.DisplayDialog("Invalid Sub Emitter", message, "Ok"); + return false; + } + if (!root.gameObject.activeInHierarchy && subEmitter.gameObject.activeInHierarchy) + { + string message2 = string.Format("The assigned sub emitter is part of a scene object and can therefore not be assigned to a prefab.", new object[0]); + EditorUtility.DisplayDialog("Invalid Sub Emitter", message2, "Ok"); + return false; + } + return true; + } + private void CheckIfChild(UnityEngine.Object subEmitter) + { + if (subEmitter != null) + { + ParticleSystem root = this.m_ParticleSystemUI.m_ParticleEffectUI.GetRoot(); + if (SubModuleUI.IsChild(subEmitter as ParticleSystem, root)) + { + return; + } + string message = string.Format("The assigned sub emitter is not a child of the current root particle system GameObject: '{0}' and is therefore NOT considered a part of the current effect. Do you want to reparent it?", root.gameObject.name); + if (EditorUtility.DisplayDialog("Reparent GameObjects", message, "Yes, Reparent", "No")) + { + if (EditorUtility.IsPersistent(subEmitter)) + { + GameObject gameObject = UnityEngine.Object.Instantiate(subEmitter) as GameObject; + if (gameObject != null) + { + gameObject.transform.parent = this.m_ParticleSystemUI.m_ParticleSystem.transform; + gameObject.transform.localPosition = Vector3.zero; + gameObject.transform.localRotation = Quaternion.identity; + } + } + else + { + ParticleSystem particleSystem = subEmitter as ParticleSystem; + if (particleSystem) + { + particleSystem.gameObject.transform.parent = this.m_ParticleSystemUI.m_ParticleSystem.transform; + } + } + } + } + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (SubModuleUI.s_Texts == null) + { + SubModuleUI.s_Texts = new SubModuleUI.Texts(); + } + UnityEngine.Object[,] expr_1B = new UnityEngine.Object[3, 2]; + expr_1B[0, 0] = this.m_SubEmitters[0, 0].objectReferenceValue; + expr_1B[0, 1] = this.m_SubEmitters[0, 1].objectReferenceValue; + expr_1B[1, 0] = this.m_SubEmitters[1, 0].objectReferenceValue; + expr_1B[1, 1] = this.m_SubEmitters[1, 1].objectReferenceValue; + expr_1B[2, 0] = this.m_SubEmitters[2, 0].objectReferenceValue; + expr_1B[2, 1] = this.m_SubEmitters[2, 1].objectReferenceValue; + UnityEngine.Object[,] array = expr_1B; + for (int i = 0; i < 3; i++) + { + int num = base.GUIListOfFloatObjectToggleFields(SubModuleUI.s_Texts.subEmitterTypeTexts[i], new SerializedProperty[] + { + this.m_SubEmitters[i, 0], + this.m_SubEmitters[i, 1] + }, null, SubModuleUI.s_Texts.create, true); + if (num != -1) + { + this.CreateAndAssignSubEmitter(this.m_SubEmitters[i, num], (SubModuleUI.SubEmitterType)i); + } + } + UnityEngine.Object[,] expr_131 = new UnityEngine.Object[3, 2]; + expr_131[0, 0] = this.m_SubEmitters[0, 0].objectReferenceValue; + expr_131[0, 1] = this.m_SubEmitters[0, 1].objectReferenceValue; + expr_131[1, 0] = this.m_SubEmitters[1, 0].objectReferenceValue; + expr_131[1, 1] = this.m_SubEmitters[1, 1].objectReferenceValue; + expr_131[2, 0] = this.m_SubEmitters[2, 0].objectReferenceValue; + expr_131[2, 1] = this.m_SubEmitters[2, 1].objectReferenceValue; + UnityEngine.Object[,] array2 = expr_131; + for (int j = 0; j < 3; j++) + { + for (int k = 0; k < 2; k++) + { + if (array[j, k] != array2[j, k]) + { + if (this.m_CheckObjectIndex == -1 && this.m_CheckObjectTypeIndex == -1) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + this.m_CheckObjectTypeIndex = j; + this.m_CheckObjectIndex = k; + } + } + } + } + public override void UpdateCullingSupportedString(ref string text) + { + text += "\n\tSub Emitters are enabled."; + } + } +} diff --git a/UnityEditor/UnityEditor/SubstanceArchive.cs b/UnityEditor/UnityEditor/SubstanceArchive.cs new file mode 100644 index 00000000..115d76ba --- /dev/null +++ b/UnityEditor/UnityEditor/SubstanceArchive.cs @@ -0,0 +1,8 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public sealed class SubstanceArchive : UnityEngine.Object + { + } +} diff --git a/UnityEditor/UnityEditor/SubstanceImporter.cs b/UnityEditor/UnityEditor/SubstanceImporter.cs new file mode 100644 index 00000000..6c37862c --- /dev/null +++ b/UnityEditor/UnityEditor/SubstanceImporter.cs @@ -0,0 +1,123 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class SubstanceImporter : AssetImporter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetPrototypeNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetMaterialCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProceduralMaterial[] GetMaterials(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string CloneMaterial(ProceduralMaterial material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string InstantiateMaterial(string prototypeName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DestroyMaterial(ProceduralMaterial material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ResetMaterial(ProceduralMaterial material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool RenameMaterial(ProceduralMaterial material, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void OnShaderModified(ProceduralMaterial material); + public Vector2 GetMaterialOffset(ProceduralMaterial material) + { + return this.GetMaterialInformation(material).offset; + } + public void SetMaterialOffset(ProceduralMaterial material, Vector2 offset) + { + ProceduralMaterialInformation materialInformation = this.GetMaterialInformation(material); + materialInformation.offset = offset; + this.SetMaterialInformation(material, materialInformation); + } + public Vector2 GetMaterialScale(ProceduralMaterial material) + { + return this.GetMaterialInformation(material).scale; + } + public void SetMaterialScale(ProceduralMaterial material, Vector2 scale) + { + ProceduralMaterialInformation materialInformation = this.GetMaterialInformation(material); + materialInformation.scale = scale; + this.SetMaterialInformation(material, materialInformation); + } + public bool GetGenerateAllOutputs(ProceduralMaterial material) + { + return this.GetMaterialInformation(material).generateAllOutputs; + } + public void SetGenerateAllOutputs(ProceduralMaterial material, bool generated) + { + ProceduralMaterialInformation materialInformation = this.GetMaterialInformation(material); + materialInformation.generateAllOutputs = generated; + this.SetMaterialInformation(material, materialInformation); + } + public int GetAnimationUpdateRate(ProceduralMaterial material) + { + return this.GetMaterialInformation(material).animationUpdateRate; + } + public void SetAnimationUpdateRate(ProceduralMaterial material, int animation_update_rate) + { + ProceduralMaterialInformation materialInformation = this.GetMaterialInformation(material); + materialInformation.animationUpdateRate = animation_update_rate; + this.SetMaterialInformation(material, materialInformation); + } + public bool GetGenerateMipMaps(ProceduralMaterial material) + { + return this.GetMaterialInformation(material).generateMipMaps; + } + public void SetGenerateMipMaps(ProceduralMaterial material, bool mode) + { + ProceduralMaterialInformation materialInformation = this.GetMaterialInformation(material); + materialInformation.generateMipMaps = mode; + this.SetMaterialInformation(material, materialInformation); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProceduralOutputType GetTextureAlphaSource(ProceduralMaterial material, string textureName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTextureAlphaSource(ProceduralMaterial material, string textureName, ProceduralOutputType alphaSource); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetPlatformTextureSettings(string materialName, string platform, out int maxTextureWidth, out int maxTextureHeight, out int textureFormat, out int loadBehavior); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPlatformTextureSettings(string materialName, string platform, int maxTextureWidth, int maxTextureHeight, int textureFormat, int loadBehavior); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern ProceduralMaterialInformation GetMaterialInformation(ProceduralMaterial material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetMaterialInformation(ProceduralMaterial material, ProceduralMaterialInformation information); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string ProceduralOutputTypeToUnityShaderPropertyName(ProceduralOutputType substanceType); + internal static bool IsProceduralTextureSlot(Material material, Texture tex, string name) + { + return material is ProceduralMaterial && tex is ProceduralTexture && SubstanceImporter.ProceduralOutputTypeToUnityShaderPropertyName((tex as ProceduralTexture).GetProceduralOutputType()) == name && SubstanceImporter.IsSubstanceParented(tex as ProceduralTexture, material as ProceduralMaterial); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void ClearPlatformTextureSettings(string materialName, string platform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void OnTextureInformationsChanged(ProceduralTexture texture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void ExportBitmaps(ProceduralMaterial material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsSubstanceParented(ProceduralTexture texture, ProceduralMaterial material); + } +} diff --git a/UnityEditor/UnityEditor/SubstanceImporterInspector.cs b/UnityEditor/UnityEditor/SubstanceImporterInspector.cs new file mode 100644 index 00000000..6e46daad --- /dev/null +++ b/UnityEditor/UnityEditor/SubstanceImporterInspector.cs @@ -0,0 +1,462 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(SubstanceArchive))] + internal class SubstanceImporterInspector : Editor + { + private class SubstanceStyles + { + public GUIContent iconToolbarPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add substance from prototype."); + public GUIContent iconToolbarMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove selected substance."); + public GUIContent iconDuplicate = EditorGUIUtility.IconContent("TreeEditor.Duplicate", "Duplicate selected substance."); + public GUIStyle resultsGridLabel = "ObjectPickerResultsGridLabel"; + public GUIStyle resultsGrid = "ObjectPickerResultsGrid"; + public GUIStyle gridBackground = "TE NodeBackground"; + public GUIStyle background = "ObjectPickerBackground"; + public GUIStyle toolbar = "TE Toolbar"; + public GUIStyle toolbarButton = "TE toolbarbutton"; + public GUIStyle toolbarDropDown = "TE toolbarDropDown"; + } + public class SubstanceNameComparer : IComparer + { + public int Compare(object o1, object o2) + { + UnityEngine.Object @object = o1 as UnityEngine.Object; + UnityEngine.Object object2 = o2 as UnityEngine.Object; + return EditorUtility.NaturalCompare(@object.name, object2.name); + } + } + private const float kPreviewWidth = 60f; + private const float kPreviewHeight = 76f; + private const int kMaxRows = 2; + private static SubstanceArchive s_LastSelectedPackage = null; + private static string s_CachedSelectedMaterialInstanceName = null; + private string m_SelectedMaterialInstanceName; + private Vector2 m_ListScroll = Vector2.zero; + private EditorCache m_EditorCache; + [NonSerialized] + private string[] m_PrototypeNames; + private Editor m_MaterialInspector; + protected bool m_IsVisible; + public Vector2 previewDir = new Vector2(0f, -20f); + public int selectedMesh; + public int lightMode = 1; + private PreviewRenderUtility m_PreviewUtility; + private static Mesh[] s_Meshes = new Mesh[4]; + private static GUIContent[] s_MeshIcons = new GUIContent[4]; + private static GUIContent[] s_LightIcons = new GUIContent[2]; + private SubstanceImporterInspector.SubstanceStyles m_SubstanceStyles; + private static int previewNoDragDropHash = "PreviewWithoutDragAndDrop".GetHashCode(); + public void OnEnable() + { + if (this.target == SubstanceImporterInspector.s_LastSelectedPackage) + { + this.m_SelectedMaterialInstanceName = SubstanceImporterInspector.s_CachedSelectedMaterialInstanceName; + } + else + { + SubstanceImporterInspector.s_LastSelectedPackage = (this.target as SubstanceArchive); + } + } + public void OnDisable() + { + if (this.m_EditorCache != null) + { + this.m_EditorCache.Dispose(); + } + if (this.m_MaterialInspector != null) + { + ProceduralMaterialInspector proceduralMaterialInspector = (ProceduralMaterialInspector)this.m_MaterialInspector; + proceduralMaterialInspector.ReimportSubstancesIfNeeded(); + UnityEngine.Object.DestroyImmediate(this.m_MaterialInspector); + } + SubstanceImporterInspector.s_CachedSelectedMaterialInstanceName = this.m_SelectedMaterialInstanceName; + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + } + private ProceduralMaterial GetSelectedMaterial() + { + SubstanceImporter importer = this.GetImporter(); + if (importer == null) + { + return null; + } + ProceduralMaterial[] sortedMaterials = this.GetSortedMaterials(); + if (this.m_SelectedMaterialInstanceName != null) + { + return Array.Find(sortedMaterials, (ProceduralMaterial element) => element.name == this.m_SelectedMaterialInstanceName); + } + if (sortedMaterials.Length > 0) + { + this.m_SelectedMaterialInstanceName = sortedMaterials[0].name; + return sortedMaterials[0]; + } + return null; + } + private void SelectNextMaterial() + { + SubstanceImporter importer = this.GetImporter(); + if (importer == null) + { + return; + } + string selectedMaterialInstanceName = null; + ProceduralMaterial[] sortedMaterials = this.GetSortedMaterials(); + for (int i = 0; i < sortedMaterials.Length; i++) + { + if (sortedMaterials[i].name == this.m_SelectedMaterialInstanceName) + { + int num = Math.Min(i + 1, sortedMaterials.Length - 1); + if (num == i) + { + num--; + } + if (num >= 0) + { + selectedMaterialInstanceName = sortedMaterials[num].name; + } + break; + } + } + this.m_SelectedMaterialInstanceName = selectedMaterialInstanceName; + } + private Editor GetSelectedMaterialInspector() + { + ProceduralMaterial selectedMaterial = this.GetSelectedMaterial(); + if (selectedMaterial && this.m_MaterialInspector != null && this.m_MaterialInspector.target == selectedMaterial) + { + return this.m_MaterialInspector; + } + EditorGUI.EndEditingActiveTextField(); + UnityEngine.Object.DestroyImmediate(this.m_MaterialInspector); + this.m_MaterialInspector = null; + if (selectedMaterial) + { + this.m_MaterialInspector = Editor.CreateEditor(selectedMaterial); + ProceduralMaterialInspector proceduralMaterialInspector = (ProceduralMaterialInspector)this.m_MaterialInspector; + proceduralMaterialInspector.DisableReimportOnDisable(); + } + return this.m_MaterialInspector; + } + public override void OnInspectorGUI() + { + if (this.m_SubstanceStyles == null) + { + this.m_SubstanceStyles = new SubstanceImporterInspector.SubstanceStyles(); + } + EditorGUILayout.Space(); + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + this.MaterialListing(); + this.MaterialManagement(); + EditorGUILayout.EndVertical(); + Editor selectedMaterialInspector = this.GetSelectedMaterialInspector(); + if (selectedMaterialInspector) + { + selectedMaterialInspector.DrawHeader(); + selectedMaterialInspector.OnInspectorGUI(); + } + } + private SubstanceImporter GetImporter() + { + return AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.target)) as SubstanceImporter; + } + private void MaterialListing() + { + ProceduralMaterial[] sortedMaterials = this.GetSortedMaterials(); + ProceduralMaterial[] array = sortedMaterials; + for (int i = 0; i < array.Length; i++) + { + ProceduralMaterial proceduralMaterial = array[i]; + if (proceduralMaterial.isProcessing) + { + base.Repaint(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + break; + } + } + int num = sortedMaterials.Length; + float num2 = GUIView.current.position.width - 16f - 18f - 2f; + if (num2 * 2f < (float)num * 60f) + { + num2 -= 16f; + } + int num3 = Mathf.Max(1, Mathf.FloorToInt(num2 / 60f)); + int num4 = Mathf.CeilToInt((float)num / (float)num3); + Rect viewRect = new Rect(0f, 0f, (float)num3 * 60f, (float)num4 * 76f); + Rect rect = GUILayoutUtility.GetRect(viewRect.width, Mathf.Clamp(viewRect.height, 76f, 152f) + 1f); + Rect position = new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 1f); + GUI.Box(rect, GUIContent.none, this.m_SubstanceStyles.gridBackground); + GUI.Box(position, GUIContent.none, this.m_SubstanceStyles.background); + this.m_ListScroll = GUI.BeginScrollView(position, this.m_ListScroll, viewRect, false, false); + if (this.m_EditorCache == null) + { + this.m_EditorCache = new EditorCache(EditorFeatures.PreviewGUI); + } + for (int j = 0; j < sortedMaterials.Length; j++) + { + ProceduralMaterial proceduralMaterial2 = sortedMaterials[j]; + if (!(proceduralMaterial2 == null)) + { + float left = (float)(j % num3) * 60f; + float top = (float)(j / num3) * 76f; + Rect rect2 = new Rect(left, top, 60f, 76f); + bool flag = proceduralMaterial2.name == this.m_SelectedMaterialInstanceName; + Event current = Event.current; + int controlID = GUIUtility.GetControlID(SubstanceImporterInspector.previewNoDragDropHash, FocusType.Native, rect2); + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl != EventType.MouseDown) + { + if (typeForControl == EventType.Repaint) + { + Rect position2 = rect2; + position2.y = rect2.yMax - 16f; + position2.height = 16f; + this.m_SubstanceStyles.resultsGridLabel.Draw(position2, EditorGUIUtility.TempContent(proceduralMaterial2.name), false, false, flag, flag); + } + } + else + { + if (current.button == 0) + { + if (rect2.Contains(current.mousePosition)) + { + if (current.clickCount == 1) + { + this.m_SelectedMaterialInstanceName = proceduralMaterial2.name; + current.Use(); + } + else + { + if (current.clickCount == 2) + { + AssetDatabase.OpenAsset(proceduralMaterial2); + GUIUtility.ExitGUI(); + current.Use(); + } + } + } + } + } + rect2.height -= 16f; + EditorWrapper editorWrapper = this.m_EditorCache[proceduralMaterial2]; + editorWrapper.OnPreviewGUI(rect2, this.m_SubstanceStyles.background); + } + } + GUI.EndScrollView(); + } + public override bool HasPreviewGUI() + { + return this.GetSelectedMaterialInspector() != null; + } + public override void OnPreviewGUI(Rect position, GUIStyle style) + { + Editor selectedMaterialInspector = this.GetSelectedMaterialInspector(); + if (selectedMaterialInspector) + { + selectedMaterialInspector.OnPreviewGUI(position, style); + } + } + public override string GetInfoString() + { + Editor selectedMaterialInspector = this.GetSelectedMaterialInspector(); + if (selectedMaterialInspector) + { + return selectedMaterialInspector.targetTitle + "\n" + selectedMaterialInspector.GetInfoString(); + } + return string.Empty; + } + public override void OnPreviewSettings() + { + Editor selectedMaterialInspector = this.GetSelectedMaterialInspector(); + if (selectedMaterialInspector) + { + selectedMaterialInspector.OnPreviewSettings(); + } + } + public void InstanciatePrototype(object prototypeName) + { + this.m_SelectedMaterialInstanceName = this.GetImporter().InstantiateMaterial(prototypeName as string); + this.ApplyAndRefresh(false); + } + private ProceduralMaterial[] GetSortedMaterials() + { + SubstanceImporter importer = this.GetImporter(); + ProceduralMaterial[] materials = importer.GetMaterials(); + Array.Sort(materials, new SubstanceImporterInspector.SubstanceNameComparer()); + return materials; + } + private void MaterialManagement() + { + SubstanceImporter importer = this.GetImporter(); + if (this.m_PrototypeNames == null) + { + this.m_PrototypeNames = importer.GetPrototypeNames(); + } + ProceduralMaterial selectedMaterial = this.GetSelectedMaterial(); + GUILayout.BeginHorizontal(this.m_SubstanceStyles.toolbar, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + if (this.m_PrototypeNames.Length > 1) + { + Rect rect = GUILayoutUtility.GetRect(this.m_SubstanceStyles.iconToolbarPlus, this.m_SubstanceStyles.toolbarDropDown); + if (EditorGUI.ButtonMouseDown(rect, this.m_SubstanceStyles.iconToolbarPlus, FocusType.Passive, this.m_SubstanceStyles.toolbarDropDown)) + { + GenericMenu genericMenu = new GenericMenu(); + for (int i = 0; i < this.m_PrototypeNames.Length; i++) + { + genericMenu.AddItem(new GUIContent(this.m_PrototypeNames[i]), false, new GenericMenu.MenuFunction2(this.InstanciatePrototype), this.m_PrototypeNames[i]); + } + genericMenu.DropDown(rect); + } + } + else + { + if (this.m_PrototypeNames.Length == 1 && GUILayout.Button(this.m_SubstanceStyles.iconToolbarPlus, this.m_SubstanceStyles.toolbarButton, new GUILayoutOption[0])) + { + this.m_SelectedMaterialInstanceName = this.GetImporter().InstantiateMaterial(this.m_PrototypeNames[0]); + this.ApplyAndRefresh(true); + } + } + EditorGUI.BeginDisabledGroup(selectedMaterial == null); + if (GUILayout.Button(this.m_SubstanceStyles.iconToolbarMinus, this.m_SubstanceStyles.toolbarButton, new GUILayoutOption[0]) && this.GetSortedMaterials().Length > 1) + { + this.SelectNextMaterial(); + importer.DestroyMaterial(selectedMaterial); + this.ApplyAndRefresh(true); + } + if (GUILayout.Button(this.m_SubstanceStyles.iconDuplicate, this.m_SubstanceStyles.toolbarButton, new GUILayoutOption[0])) + { + string text = importer.CloneMaterial(selectedMaterial); + if (text != string.Empty) + { + this.m_SelectedMaterialInstanceName = text; + this.ApplyAndRefresh(true); + } + } + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + } + private void ApplyAndRefresh(bool exitGUI) + { + string assetPath = AssetDatabase.GetAssetPath(this.target); + AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUncompressedImport); + if (exitGUI) + { + GUIUtility.ExitGUI(); + } + base.Repaint(); + } + private void Init() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + } + if (SubstanceImporterInspector.s_Meshes[0] == null) + { + GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + string name = transform.name; + switch (name) + { + case "sphere": + SubstanceImporterInspector.s_Meshes[0] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "cube": + SubstanceImporterInspector.s_Meshes[1] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "cylinder": + SubstanceImporterInspector.s_Meshes[2] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + case "torus": + SubstanceImporterInspector.s_Meshes[3] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + continue; + } + Debug.Log("Something is wrong, weird object found: " + transform.name); + } + SubstanceImporterInspector.s_MeshIcons[0] = EditorGUIUtility.IconContent("PreMatSphere"); + SubstanceImporterInspector.s_MeshIcons[1] = EditorGUIUtility.IconContent("PreMatCube"); + SubstanceImporterInspector.s_MeshIcons[2] = EditorGUIUtility.IconContent("PreMatCylinder"); + SubstanceImporterInspector.s_MeshIcons[3] = EditorGUIUtility.IconContent("PreMatTorus"); + SubstanceImporterInspector.s_LightIcons[0] = EditorGUIUtility.IconContent("PreMatLight0"); + SubstanceImporterInspector.s_LightIcons[1] = EditorGUIUtility.IconContent("PreMatLight1"); + } + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + this.Init(); + this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float)width, (float)height)); + this.DoRenderPreview(subAssets); + return this.m_PreviewUtility.EndStaticPreview(); + } + protected void DoRenderPreview(UnityEngine.Object[] subAssets) + { + if (this.m_PreviewUtility.m_RenderTexture.width <= 0 || this.m_PreviewUtility.m_RenderTexture.height <= 0) + { + return; + } + List list = new List(); + for (int i = 0; i < subAssets.Length; i++) + { + UnityEngine.Object @object = subAssets[i]; + if (@object is ProceduralMaterial) + { + list.Add(@object as ProceduralMaterial); + } + } + int num = 1; + while (num * num < list.Count) + { + num++; + } + int num2 = Mathf.CeilToInt((float)list.Count / (float)num); + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 5f * (float)num; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + this.m_PreviewUtility.m_Camera.farClipPlane = (float)(5 * num) + 5f; + this.m_PreviewUtility.m_Camera.nearClipPlane = (float)(5 * num) - 3f; + Color ambient; + if (this.lightMode == 0) + { + this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0f; + ambient = new Color(0.2f, 0.2f, 0.2f, 0f); + } + else + { + this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + ambient = new Color(0.2f, 0.2f, 0.2f, 0f); + } + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + for (int j = 0; j < list.Count; j++) + { + ProceduralMaterial mat = list[j]; + Vector3 vector = new Vector3((float)(j % num) - (float)(num - 1) * 0.5f, (float)(-(float)j / num) + (float)(num2 - 1) * 0.5f, 0f); + vector *= Mathf.Tan(this.m_PreviewUtility.m_Camera.fieldOfView * 0.5f * 0.0174532924f) * 5f * 2f; + this.m_PreviewUtility.DrawMesh(SubstanceImporterInspector.s_Meshes[this.selectedMesh], vector, Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f), mat, 0); + } + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + InternalEditorUtility.RemoveCustomLighting(); + } + } +} diff --git a/UnityEditor/UnityEditor/SyncVS.cs b/UnityEditor/UnityEditor/SyncVS.cs new file mode 100644 index 00000000..f840b87f --- /dev/null +++ b/UnityEditor/UnityEditor/SyncVS.cs @@ -0,0 +1,353 @@ +using Microsoft.Win32; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Utils; +using UnityEditor.VisualStudioIntegration; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [InitializeOnLoad] + internal class SyncVS : AssetPostprocessor + { + private class SolutionSynchronizationSettings : DefaultSolutionSynchronizationSettings + { + public override int VisualStudioVersion + { + get + { + string externalScriptEditor = InternalEditorUtility.GetExternalScriptEditor(); + if (SyncVS.InstalledVisualStudios.ContainsKey(UnityEditor.VisualStudioVersion.VisualStudio2008) && SyncVS.PathsAreEquivalent(SyncVS.InstalledVisualStudios[UnityEditor.VisualStudioVersion.VisualStudio2008], externalScriptEditor)) + { + return 9; + } + return 10; + } + } + public override string SolutionTemplate + { + get + { + return EditorPrefs.GetString("VSSolutionText", base.SolutionTemplate); + } + } + public override string EditorAssemblyPath + { + get + { + return InternalEditorUtility.GetEditorAssemblyPath(); + } + } + public override string EngineAssemblyPath + { + get + { + return InternalEditorUtility.GetEngineAssemblyPath(); + } + } + public override string[] Defines + { + get + { + return EditorUserBuildSettings.activeScriptCompilationDefines; + } + } + internal static bool IsOSX + { + get + { + return Environment.OSVersion.Platform == PlatformID.Unix; + } + } + internal static bool IsWindows + { + get + { + return !SyncVS.SolutionSynchronizationSettings.IsOSX && Path.DirectorySeparatorChar == '\\' && Environment.NewLine == "\r\n"; + } + } + public override string GetProjectHeaderTemplate(ScriptingLanguage language) + { + return EditorPrefs.GetString("VSProjectHeader", base.GetProjectHeaderTemplate(language)); + } + public override string GetProjectFooterTemplate(ScriptingLanguage language) + { + return EditorPrefs.GetString("VSProjectFooter", base.GetProjectFooterTemplate(language)); + } + protected override string FrameworksPath() + { + string applicationContentsPath = EditorApplication.applicationContentsPath; + return (!SyncVS.SolutionSynchronizationSettings.IsOSX) ? applicationContentsPath : (applicationContentsPath + "/Frameworks"); + } + } + private static readonly SolutionSynchronizer Synchronizer; + internal static Dictionary InstalledVisualStudios + { + get; + private set; + } + static SyncVS() + { + SyncVS.Synchronizer = new SolutionSynchronizer(Directory.GetParent(Application.dataPath).FullName, new SyncVS.SolutionSynchronizationSettings()); + EditorUserBuildSettings.activeBuildTargetChanged = (Action)Delegate.Combine(EditorUserBuildSettings.activeBuildTargetChanged, new Action(SyncVS.SyncVisualStudioProjectIfItAlreadyExists)); + try + { + SyncVS.InstalledVisualStudios = (SyncVS.GetInstalledVisualStudios() as Dictionary); + } + catch (Exception ex) + { + Console.WriteLine("Error detecting Visual Studio installations: {0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace); + SyncVS.InstalledVisualStudios = new Dictionary(); + } + } + public static bool ProjectExists() + { + return SyncVS.Synchronizer.SolutionExists(); + } + public static void CreateIfDoesntExist() + { + if (!SyncVS.Synchronizer.SolutionExists()) + { + SyncVS.Synchronizer.Sync(); + AssetPostprocessingInternal.CallOnGeneratedCSProjectFiles(); + } + } + public static void SyncVisualStudioProjectIfItAlreadyExists() + { + if (SyncVS.Synchronizer.SolutionExists()) + { + SyncVS.Synchronizer.Sync(); + AssetPostprocessingInternal.CallOnGeneratedCSProjectFiles(); + } + } + public static void PostprocessSyncProject(string[] importedAssets, string[] addedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) + { + if (SyncVS.Synchronizer.SyncIfNeeded(addedAssets.Union(deletedAssets.Union(movedAssets.Union(movedFromAssetPaths))))) + { + AssetPostprocessingInternal.CallOnGeneratedCSProjectFiles(); + } + } + [MenuItem("Assets/Sync MonoDevelop Project")] + public static void SyncSolution() + { + AssetDatabase.Refresh(); + SyncVS.Synchronizer.Sync(); + AssetPostprocessingInternal.CallOnGeneratedCSProjectFiles(); + SyncVS.OpenProjectFileUnlessInBatchMode(); + } + private static void OpenProjectFileUnlessInBatchMode() + { + if (InternalEditorUtility.inBatchMode) + { + return; + } + bool onlyCSharp = InternalEditorUtility.GetExternalScriptEditor().EndsWith("devenv.exe", StringComparison.OrdinalIgnoreCase); + InternalEditorUtility.OpenFileAtLineExternal(SyncVS.Synchronizer.SolutionFile(onlyCSharp), -1); + } + private static IDictionary GetInstalledVisualStudios() + { + Dictionary dictionary = new Dictionary(); + if (SyncVS.SolutionSynchronizationSettings.IsWindows) + { + IEnumerator enumerator = Enum.GetValues(typeof(VisualStudioVersion)).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + VisualStudioVersion visualStudioVersion = (VisualStudioVersion)((int)enumerator.Current); + try + { + string text = Environment.GetEnvironmentVariable(string.Format("VS{0}0COMNTOOLS", (int)visualStudioVersion)); + if (!string.IsNullOrEmpty(text)) + { + string text2 = Paths.Combine(new string[] + { + text, + "..", + "IDE", + "devenv.exe" + }); + if (File.Exists(text2)) + { + dictionary[visualStudioVersion] = text2; + continue; + } + } + text = (Registry.GetValue(string.Format("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\{0}.0\\Debugger", (int)visualStudioVersion), "FEQARuntimeImplDll", null) as string); + if (!string.IsNullOrEmpty(text)) + { + string text3 = SyncVS.DeriveVisualStudioPath(text); + if (!string.IsNullOrEmpty(text3) && File.Exists(text3)) + { + dictionary[visualStudioVersion] = SyncVS.DeriveVisualStudioPath(text); + } + } + } + catch + { + } + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + } + return dictionary; + } + private static string DeriveVisualStudioPath(string debuggerPath) + { + string a = SyncVS.DeriveProgramFilesSentinel(); + string a2 = "Common7"; + bool flag = false; + string[] array = debuggerPath.Split(new char[] + { + Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar + }, StringSplitOptions.RemoveEmptyEntries); + string text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text2 = array2[i]; + if (!flag && string.Equals(a, text2, StringComparison.OrdinalIgnoreCase)) + { + flag = true; + } + else + { + if (flag) + { + text = Path.Combine(text, text2); + if (string.Equals(a2, text2, StringComparison.OrdinalIgnoreCase)) + { + break; + } + } + } + } + return Paths.Combine(new string[] + { + text, + "IDE", + "devenv.exe" + }); + } + private static string DeriveProgramFilesSentinel() + { + string text = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).Split(new char[] + { + Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar + }).LastOrDefault(); + if (!string.IsNullOrEmpty(text)) + { + int num = text.LastIndexOf("(x86)"); + if (0 <= num) + { + text = text.Remove(num); + } + return text.TrimEnd(new char[0]); + } + return "Program Files"; + } + private static bool PathsAreEquivalent(string aPath, string zPath) + { + if (aPath == null && zPath == null) + { + return true; + } + if (string.IsNullOrEmpty(aPath) || string.IsNullOrEmpty(zPath)) + { + return false; + } + if (aPath.Length > 0) + { + aPath = Path.GetFullPath(aPath); + } + if (zPath.Length > 0) + { + zPath = Path.GetFullPath(zPath); + } + StringComparison comparisonType = StringComparison.OrdinalIgnoreCase; + if (!SyncVS.SolutionSynchronizationSettings.IsOSX && !SyncVS.SolutionSynchronizationSettings.IsWindows) + { + comparisonType = StringComparison.Ordinal; + } + aPath = aPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + zPath = zPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); + return string.Equals(aPath, zPath, comparisonType); + } + internal static bool CheckVisualStudioVersion(int major, int minor, int build) + { + int num = -1; + int num2 = -1; + if (major != 11) + { + return false; + } + RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Microsoft\\DevDiv\\vc\\Servicing"); + if (registryKey == null) + { + return false; + } + string[] subKeyNames = registryKey.GetSubKeyNames(); + for (int i = 0; i < subKeyNames.Length; i++) + { + string text = subKeyNames[i]; + if (text.StartsWith("11.") && text.Length > 3) + { + try + { + int num3 = Convert.ToInt32(text.Substring(3)); + if (num3 > num) + { + num = num3; + } + } + catch (Exception) + { + } + } + } + if (num < 0) + { + return false; + } + RegistryKey registryKey2 = registryKey.OpenSubKey(string.Format("11.{0}\\RuntimeDebug", num)); + if (registryKey2 == null) + { + return false; + } + string text2 = registryKey2.GetValue("Version", null) as string; + if (text2 == null) + { + return false; + } + string[] array = text2.Split(new char[] + { + '.' + }); + if (array == null || array.Length < 3) + { + return false; + } + try + { + num2 = Convert.ToInt32(array[2]); + } + catch (Exception) + { + return false; + } + return num > minor || (num == minor && num2 >= build); + } + } +} diff --git a/UnityEditor/UnityEditor/TabbedEditor.cs b/UnityEditor/UnityEditor/TabbedEditor.cs new file mode 100644 index 00000000..3e0a73f6 --- /dev/null +++ b/UnityEditor/UnityEditor/TabbedEditor.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class TabbedEditor : Editor + { + protected Type[] m_SubEditorTypes; + protected string[] m_SubEditorNames; + private int m_ActiveEditorIndex; + private Editor m_ActiveEditor; + public Editor activeEditor + { + get + { + return this.m_ActiveEditor; + } + } + internal virtual void OnEnable() + { + this.m_ActiveEditorIndex = EditorPrefs.GetInt(base.GetType().Name + "ActiveEditorIndex", 0); + if (this.m_ActiveEditor == null) + { + this.m_ActiveEditor = Editor.CreateEditor(base.targets, this.m_SubEditorTypes[this.m_ActiveEditorIndex]); + } + } + private void OnDestroy() + { + UnityEngine.Object.DestroyImmediate(this.activeEditor); + } + public override void OnInspectorGUI() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginChangeCheck(); + this.m_ActiveEditorIndex = GUILayout.Toolbar(this.m_ActiveEditorIndex, this.m_SubEditorNames, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorPrefs.SetInt(base.GetType().Name + "ActiveEditorIndex", this.m_ActiveEditorIndex); + Editor activeEditor = this.activeEditor; + this.m_ActiveEditor = null; + UnityEngine.Object.DestroyImmediate(activeEditor); + this.m_ActiveEditor = Editor.CreateEditor(base.targets, this.m_SubEditorTypes[this.m_ActiveEditorIndex]); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + this.activeEditor.OnInspectorGUI(); + } + public override void OnPreviewSettings() + { + this.activeEditor.OnPreviewSettings(); + } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.activeEditor.OnInteractivePreviewGUI(r, background); + } + public override bool HasPreviewGUI() + { + return this.activeEditor.HasPreviewGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/TagManager.cs b/UnityEditor/UnityEditor/TagManager.cs new file mode 100644 index 00000000..de6ae039 --- /dev/null +++ b/UnityEditor/UnityEditor/TagManager.cs @@ -0,0 +1,9 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class TagManager : UnityEngine.Object + { + public string m_DefaultExpandedFoldout; + } +} diff --git a/UnityEditor/UnityEditor/TagManagerInspector.cs b/UnityEditor/UnityEditor/TagManagerInspector.cs new file mode 100644 index 00000000..bd171e25 --- /dev/null +++ b/UnityEditor/UnityEditor/TagManagerInspector.cs @@ -0,0 +1,134 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(TagManager))] + internal class TagManagerInspector : Editor + { + protected SerializedProperty m_Tags; + protected SerializedProperty m_SortingLayers; + protected SerializedProperty[] m_Layers; + protected bool m_LayersExpanded = true; + private ReorderableList m_SortLayersList; + public TagManager tagManager + { + get + { + return this.target as TagManager; + } + } + internal override string targetTitle + { + get + { + return "Tags & Layers"; + } + } + public virtual void OnEnable() + { + this.m_Tags = base.serializedObject.FindProperty("tags"); + this.m_SortingLayers = base.serializedObject.FindProperty("m_SortingLayers"); + this.m_Layers = new SerializedProperty[32]; + for (int i = 0; i < 32; i++) + { + string propertyPath = ((i < 8) ? "Builtin Layer " : "User Layer ") + i; + this.m_Layers[i] = base.serializedObject.FindProperty(propertyPath); + } + if (this.m_SortLayersList == null) + { + this.m_SortLayersList = new ReorderableList(base.serializedObject, this.m_SortingLayers, true, false, true, true); + this.m_SortLayersList.onReorderCallback = new ReorderableList.ReorderCallbackDelegate(this.ReorderSortLayerList); + this.m_SortLayersList.onAddCallback = new ReorderableList.AddCallbackDelegate(this.AddToSortLayerList); + this.m_SortLayersList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveFromSortLayerList); + this.m_SortLayersList.onCanRemoveCallback = new ReorderableList.CanRemoveCallbackDelegate(this.CanRemoveSortLayerEntry); + this.m_SortLayersList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawSortLayerListElement); + this.m_SortLayersList.elementHeight = EditorGUIUtility.singleLineHeight + 2f; + this.m_SortLayersList.headerHeight = 3f; + } + this.m_LayersExpanded = false; + this.m_SortingLayers.isExpanded = false; + this.m_Tags.isExpanded = false; + string defaultExpandedFoldout = this.tagManager.m_DefaultExpandedFoldout; + switch (defaultExpandedFoldout) + { + case "Tags": + this.m_Tags.isExpanded = true; + return; + case "SortingLayers": + this.m_SortingLayers.isExpanded = true; + return; + case "Layers": + this.m_LayersExpanded = true; + return; + } + this.m_LayersExpanded = true; + } + private void AddToSortLayerList(ReorderableList list) + { + base.serializedObject.ApplyModifiedProperties(); + InternalEditorUtility.AddSortingLayer(); + base.serializedObject.Update(); + list.index = list.serializedProperty.arraySize - 1; + } + public void ReorderSortLayerList(ReorderableList list) + { + InternalEditorUtility.UpdateSortingLayersOrder(); + } + private void RemoveFromSortLayerList(ReorderableList list) + { + ReorderableList.defaultBehaviours.DoRemoveButton(list); + base.serializedObject.ApplyModifiedProperties(); + base.serializedObject.Update(); + InternalEditorUtility.UpdateSortingLayersOrder(); + } + private bool CanEditSortLayerEntry(int index) + { + return index >= 0 && index < InternalEditorUtility.GetSortingLayerCount() && !InternalEditorUtility.IsSortingLayerDefault(index); + } + private bool CanRemoveSortLayerEntry(ReorderableList list) + { + return this.CanEditSortLayerEntry(list.index); + } + private void DrawSortLayerListElement(Rect rect, int index, bool selected, bool focused) + { + rect.height -= 2f; + rect.xMin -= 20f; + bool enabled = GUI.enabled; + GUI.enabled = this.CanEditSortLayerEntry(index); + string sortingLayerName = InternalEditorUtility.GetSortingLayerName(index); + int sortingLayerUserID = InternalEditorUtility.GetSortingLayerUserID(index); + string text = EditorGUI.TextField(rect, " Layer " + sortingLayerUserID, sortingLayerName); + if (text != sortingLayerName) + { + base.serializedObject.ApplyModifiedProperties(); + InternalEditorUtility.SetSortingLayerName(index, text); + base.serializedObject.Update(); + } + GUI.enabled = enabled; + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Tags, true, new GUILayoutOption[0]); + this.m_SortingLayers.isExpanded = EditorGUILayout.Foldout(this.m_SortingLayers.isExpanded, "Sorting Layers"); + if (this.m_SortingLayers.isExpanded) + { + EditorGUI.indentLevel++; + this.m_SortLayersList.DoLayoutList(); + EditorGUI.indentLevel--; + } + this.m_LayersExpanded = EditorGUILayout.Foldout(this.m_LayersExpanded, "Layers", EditorStyles.foldout); + if (this.m_LayersExpanded) + { + EditorGUI.indentLevel++; + for (int i = 0; i < this.m_Layers.Length; i++) + { + EditorGUILayout.PropertyField(this.m_Layers[i], new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/TakeInfo.cs b/UnityEditor/UnityEditor/TakeInfo.cs new file mode 100644 index 00000000..f09f709e --- /dev/null +++ b/UnityEditor/UnityEditor/TakeInfo.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor +{ + public struct TakeInfo + { + public string name; + public string defaultClipName; + public float startTime; + public float stopTime; + public float bakeStartTime; + public float bakeStopTime; + public float sampleRate; + } +} diff --git a/UnityEditor/UnityEditor/TangentMode.cs b/UnityEditor/UnityEditor/TangentMode.cs new file mode 100644 index 00000000..074c4e27 --- /dev/null +++ b/UnityEditor/UnityEditor/TangentMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + [Flags] + internal enum TangentMode + { + Editable = 0, + Smooth = 1, + Linear = 2, + Stepped = 3 + } +} diff --git a/UnityEditor/UnityEditor/TargetChoiceHandler.cs b/UnityEditor/UnityEditor/TargetChoiceHandler.cs new file mode 100644 index 00000000..32a6d799 --- /dev/null +++ b/UnityEditor/UnityEditor/TargetChoiceHandler.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class TargetChoiceHandler + { + internal delegate void TargetChoiceMenuFunction(SerializedProperty property, UnityEngine.Object target); + internal static void DuplicateArrayElement(object userData) + { + SerializedProperty serializedProperty = (SerializedProperty)userData; + serializedProperty.DuplicateCommand(); + serializedProperty.serializedObject.ApplyModifiedProperties(); + EditorUtility.ForceReloadInspectors(); + } + internal static void DeleteArrayElement(object userData) + { + SerializedProperty serializedProperty = (SerializedProperty)userData; + serializedProperty.DeleteCommand(); + serializedProperty.serializedObject.ApplyModifiedProperties(); + EditorUtility.ForceReloadInspectors(); + } + internal static void SetPrefabOverride(object userData) + { + SerializedProperty serializedProperty = (SerializedProperty)userData; + serializedProperty.prefabOverride = false; + serializedProperty.serializedObject.ApplyModifiedProperties(); + EditorUtility.ForceReloadInspectors(); + } + internal static void SetToValueOfTarget(SerializedProperty property, UnityEngine.Object target) + { + property.SetToValueOfTarget(target); + property.serializedObject.ApplyModifiedProperties(); + EditorUtility.ForceReloadInspectors(); + } + private static void TargetChoiceForwardFunction(object userData) + { + PropertyAndTargetHandler propertyAndTargetHandler = (PropertyAndTargetHandler)userData; + propertyAndTargetHandler.function(propertyAndTargetHandler.property, propertyAndTargetHandler.target); + } + internal static void AddSetToValueOfTargetMenuItems(GenericMenu menu, SerializedProperty property, TargetChoiceHandler.TargetChoiceMenuFunction func) + { + SerializedProperty property2 = property.serializedObject.FindProperty(property.propertyPath); + UnityEngine.Object[] targetObjects = property.serializedObject.targetObjects; + List list = new List(); + UnityEngine.Object[] array = targetObjects; + for (int i = 0; i < array.Length; i++) + { + UnityEngine.Object @object = array[i]; + string text = "Set to Value of " + @object.name; + if (list.Contains(text)) + { + int num = 1; + while (true) + { + text = string.Concat(new object[] + { + "Set to Value of ", + @object.name, + " (", + num, + ")" + }); + if (!list.Contains(text)) + { + break; + } + num++; + } + } + list.Add(text); + menu.AddItem(EditorGUIUtility.TextContent(text), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.TargetChoiceForwardFunction), new PropertyAndTargetHandler(property2, @object, func)); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TargetGlesGraphics.cs b/UnityEditor/UnityEditor/TargetGlesGraphics.cs new file mode 100644 index 00000000..4110144d --- /dev/null +++ b/UnityEditor/UnityEditor/TargetGlesGraphics.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum TargetGlesGraphics + { + OpenGLES_1_x, + OpenGLES_2_0, + OpenGLES_3_0, + Automatic = -1 + } +} diff --git a/UnityEditor/UnityEditor/TargetIOSGraphics.cs b/UnityEditor/UnityEditor/TargetIOSGraphics.cs new file mode 100644 index 00000000..340a24f4 --- /dev/null +++ b/UnityEditor/UnityEditor/TargetIOSGraphics.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum TargetIOSGraphics + { + OpenGLES_2_0 = 2, + OpenGLES_3_0, + Metal, + Automatic = -1 + } +} diff --git a/UnityEditor/UnityEditor/TerrainDetailContextMenus.cs b/UnityEditor/UnityEditor/TerrainDetailContextMenus.cs new file mode 100644 index 00000000..55bb6058 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainDetailContextMenus.cs @@ -0,0 +1,56 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainDetailContextMenus + { + [MenuItem("CONTEXT/TerrainEngineDetails/Add Grass Texture")] + internal static void AddDetailTexture(MenuCommand item) + { + DetailTextureWizard detailTextureWizard = ScriptableWizard.DisplayWizard("Add Grass Texture", "Add"); + detailTextureWizard.m_DetailTexture = null; + detailTextureWizard.InitializeDefaults((Terrain)item.context, -1); + } + [MenuItem("CONTEXT/TerrainEngineDetails/Add Detail Mesh")] + internal static void AddDetailMesh(MenuCommand item) + { + DetailMeshWizard detailMeshWizard = ScriptableWizard.DisplayWizard("Add Detail Mesh", "Add"); + detailMeshWizard.m_Detail = null; + detailMeshWizard.InitializeDefaults((Terrain)item.context, -1); + } + [MenuItem("CONTEXT/TerrainEngineDetails/Edit")] + internal static void EditDetail(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + DetailPrototype detailPrototype = terrain.terrainData.detailPrototypes[item.userData]; + if (detailPrototype.usePrototypeMesh) + { + DetailMeshWizard detailMeshWizard = ScriptableWizard.DisplayWizard("Edit Detail Mesh", "Apply"); + detailMeshWizard.InitializeDefaults((Terrain)item.context, item.userData); + } + else + { + DetailTextureWizard detailTextureWizard = ScriptableWizard.DisplayWizard("Edit Grass Texture", "Apply"); + detailTextureWizard.InitializeDefaults((Terrain)item.context, item.userData); + } + } + [MenuItem("CONTEXT/TerrainEngineDetails/Edit", true)] + internal static bool EditDetailCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.detailPrototypes.Length; + } + [MenuItem("CONTEXT/TerrainEngineDetails/Remove")] + internal static void RemoveDetail(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + TerrainEditorUtility.RemoveDetail(terrain, item.userData); + } + [MenuItem("CONTEXT/TerrainEngineDetails/Remove", true)] + internal static bool RemoveDetailCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.detailPrototypes.Length; + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainEditorUtility.cs b/UnityEditor/UnityEditor/TerrainEditorUtility.cs new file mode 100644 index 00000000..dbf70f53 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainEditorUtility.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainEditorUtility + { + private static void Extract(uint staticFlag, ref TerrainData[] datas, ref Vector3[] positions, ref int[] castShadows, ref Material[] materials, ref int[] lightmapSizes, ref int[] lightmapIndices, ref bool[] selection) + { + List list = new List(); + List list2 = new List(); + List list3 = new List(); + List list4 = new List(); + List list5 = new List(); + List list6 = new List(); + List list7 = new List(); + int num = Terrain.activeTerrains.Length; + for (int i = 0; i < num; i++) + { + Terrain terrain = Terrain.activeTerrains[i]; + if (GameObjectUtility.AreStaticEditorFlagsSet(terrain.gameObject, (StaticEditorFlags)staticFlag) && terrain.terrainData) + { + list.Add(terrain.terrainData); + list2.Add(terrain.GetPosition()); + list3.Add((!terrain.castShadows) ? 0 : 1); + list4.Add(terrain.materialTemplate); + list5.Add(terrain.lightmapSize); + list6.Add(terrain.lightmapIndex); + list7.Add(Selection.Contains(terrain.gameObject)); + } + } + datas = list.ToArray(); + positions = list2.ToArray(); + castShadows = list3.ToArray(); + materials = list4.ToArray(); + lightmapSizes = list5.ToArray(); + lightmapIndices = list6.ToArray(); + selection = list7.ToArray(); + } + internal static void RemoveSplatTexture(TerrainData terrainData, int index) + { + Undo.RegisterCompleteObjectUndo(terrainData, "Remove texture"); + int alphamapWidth = terrainData.alphamapWidth; + int alphamapHeight = terrainData.alphamapHeight; + float[,,] alphamaps = terrainData.GetAlphamaps(0, 0, alphamapWidth, alphamapHeight); + int length = alphamaps.GetLength(2); + int num = length - 1; + float[,,] array = new float[alphamapHeight, alphamapWidth, num]; + for (int i = 0; i < alphamapHeight; i++) + { + for (int j = 0; j < alphamapWidth; j++) + { + for (int k = 0; k < index; k++) + { + array[i, j, k] = alphamaps[i, j, k]; + } + for (int l = index + 1; l < length; l++) + { + array[i, j, l - 1] = alphamaps[i, j, l]; + } + } + } + for (int m = 0; m < alphamapHeight; m++) + { + for (int n = 0; n < alphamapWidth; n++) + { + float num2 = 0f; + for (int num3 = 0; num3 < num; num3++) + { + num2 += array[m, n, num3]; + } + if ((double)num2 >= 0.01) + { + float num4 = 1f / num2; + for (int num5 = 0; num5 < num; num5++) + { + array[m, n, num5] *= num4; + } + } + else + { + for (int num6 = 0; num6 < num; num6++) + { + array[m, n, num6] = ((num6 != 0) ? 0f : 1f); + } + } + } + } + SplatPrototype[] splatPrototypes = terrainData.splatPrototypes; + SplatPrototype[] array2 = new SplatPrototype[splatPrototypes.Length - 1]; + for (int num7 = 0; num7 < index; num7++) + { + array2[num7] = splatPrototypes[num7]; + } + for (int num8 = index + 1; num8 < length; num8++) + { + array2[num8 - 1] = splatPrototypes[num8]; + } + terrainData.splatPrototypes = array2; + terrainData.SetAlphamaps(0, 0, array); + } + internal static void RemoveTree(Terrain terrain, int index) + { + TerrainData terrainData = terrain.terrainData; + if (terrainData == null) + { + return; + } + Undo.RegisterCompleteObjectUndo(terrainData, "Remove tree"); + terrainData.RemoveTreePrototype(index); + } + internal static void RemoveDetail(Terrain terrain, int index) + { + TerrainData terrainData = terrain.terrainData; + if (terrainData == null) + { + return; + } + Undo.RegisterCompleteObjectUndo(terrainData, "Remove detail object"); + terrainData.RemoveDetailPrototype(index); + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainInspector.cs b/UnityEditor/UnityEditor/TerrainInspector.cs new file mode 100644 index 00000000..ec8c9404 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainInspector.cs @@ -0,0 +1,1163 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Terrain))] + internal class TerrainInspector : Editor + { + private class Styles + { + public GUIStyle gridList = "GridList"; + public GUIStyle gridListText = "GridListText"; + public GUIStyle label = "RightLabel"; + public GUIStyle largeSquare = "Button"; + public GUIStyle command = "Command"; + public Texture settingsIcon = EditorGUIUtility.IconContent("SettingsIcon").image; + public GUIContent[] toolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolRaise"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolSetHeight"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolSmoothHeight"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolSplat"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolTrees"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolPlants"), + EditorGUIUtility.IconContent("TerrainInspector.TerrainToolSettings") + }; + public GUIContent[] toolNames = new GUIContent[] + { + EditorGUIUtility.TextContent("TerrainInspector.RaiseHeightTip"), + EditorGUIUtility.TextContent("TerrainInspector.PaintHeightTip"), + EditorGUIUtility.TextContent("TerrainInspector.SmoothHeightTip"), + EditorGUIUtility.TextContent("TerrainInspector.PaintTextureTip"), + EditorGUIUtility.TextContent("TerrainInspector.PlaceTreesTip"), + EditorGUIUtility.TextContent("TerrainInspector.PaintDetailsTip"), + EditorGUIUtility.TextContent("TerrainInspector.TerrainSettingsTip") + }; + public GUIContent brushSize = EditorGUIUtility.TextContent("TerrainInspector.BrushSize"); + public GUIContent opacity = EditorGUIUtility.TextContent("TerrainInspector.BrushOpacity"); + public GUIContent settings = EditorGUIUtility.TextContent("TerrainInspector.Settings"); + public GUIContent brushes = EditorGUIUtility.TextContent("TerrainInspector.Brushes"); + public GUIContent textures = EditorGUIUtility.TextContent("TerrainInspector.Textures.Textures"); + public GUIContent editTextures = EditorGUIUtility.TextContent("TerrainInspector.Textures.Edit"); + public GUIContent trees = EditorGUIUtility.TextContent("TerrainInspector.Trees.Trees"); + public GUIContent noTrees = EditorGUIUtility.TextContent("TerrainInspector.Trees.NoTrees"); + public GUIContent editTrees = EditorGUIUtility.TextContent("TerrainInspector.Trees.EditTrees"); + public GUIContent treeDensity = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeDensity"); + public GUIContent treeColorVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.ColorVar"); + public GUIContent treeHeight = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeight"); + public GUIContent treeHeightVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeightVar"); + public GUIContent treeWidth = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidth"); + public GUIContent treeWidthVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidthVar"); + public GUIContent details = EditorGUIUtility.TextContent("TerrainInspector.Details.Details"); + public GUIContent editDetails = EditorGUIUtility.TextContent("TerrainInspector.Details.Edit"); + public GUIContent detailTargetStrength = EditorGUIUtility.TextContent("TerrainInspector.Details.TargetStrength"); + public GUIContent heightmap = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.Heightmap"); + public GUIContent importRaw = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.ImportRaw"); + public GUIContent exportRaw = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.ExportRaw"); + public GUIContent flatten = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.Flatten"); + public GUIContent resolution = EditorGUIUtility.TextContent("TerrainInspector.Resolution"); + public GUIContent refresh = EditorGUIUtility.TextContent("TerrainInspector.Refresh"); + public GUIContent massPlaceTrees = EditorGUIUtility.TextContent("TerrainInspector.MassPlaceTrees"); + } + private const float kHeightmapBrushScale = 0.01f; + private const float kMinBrushStrength = 0.00167849252f; + private static TerrainInspector.Styles styles; + internal static PrefKey[] s_ToolKeys = new PrefKey[] + { + new PrefKey("Terrain/Raise Height", "#q"), + new PrefKey("Terrain/Set Height", "#w"), + new PrefKey("Terrain/Smooth Height", "#e"), + new PrefKey("Terrain/Texture Paint", "#r"), + new PrefKey("Terrain/Tree Brush", "#t"), + new PrefKey("Terrain/Detail Brush", "#y") + }; + internal static PrefKey s_PrevBrush = new PrefKey("Terrain/Previous Brush", ","); + internal static PrefKey s_NextBrush = new PrefKey("Terrain/Next Brush", "."); + internal static PrefKey s_PrevTexture = new PrefKey("Terrain/Previous Detail", "#,"); + internal static PrefKey s_NextTexture = new PrefKey("Terrain/Next Detail", "#."); + private Terrain m_Terrain; + private GUIContent[] m_TreeContents; + private GUIContent[] m_DetailContents; + private SavedFloat m_TargetHeight = new SavedFloat("TerrainBrushTargetHeight", 0.2f); + private SavedFloat m_Strength = new SavedFloat("TerrainBrushStrength", 0.5f); + private SavedInt m_Size = new SavedInt("TerrainBrushSize", 25); + private SavedFloat m_SplatAlpha = new SavedFloat("TerrainBrushSplatAlpha", 1f); + private SavedFloat m_DetailOpacity = new SavedFloat("TerrainDetailOpacity", 1f); + private SavedFloat m_DetailStrength = new SavedFloat("TerrainDetailStrength", 0.8f); + private Brush m_CachedBrush; + private static Texture2D[] s_BrushTextures = null; + private int m_SelectedBrush; + private int m_SelectedSplat; + private int m_SelectedDetail; + private static int s_TerrainEditorHash = "TerrainEditor".GetHashCode(); + private SavedInt m_SelectedTool = new SavedInt("TerrainSelectedTool", 0); + private TerrainTool selectedTool + { + get + { + if (Tools.current == Tool.None) + { + return (TerrainTool)this.m_SelectedTool.value; + } + return TerrainTool.None; + } + set + { + if (value != TerrainTool.None) + { + Tools.current = Tool.None; + } + this.m_SelectedTool.value = (int)value; + } + } + private static float PercentSlider(GUIContent content, float valueInPercent, float minVal, float maxVal) + { + bool changed = GUI.changed; + GUI.changed = false; + float num = EditorGUILayout.Slider(content, Mathf.Round(valueInPercent * 100f), minVal * 100f, maxVal * 100f, new GUILayoutOption[0]); + if (GUI.changed) + { + return num / 100f; + } + GUI.changed = changed; + return valueInPercent; + } + private void CheckKeys() + { + if (GUIUtility.textFieldInput) + { + return; + } + for (int i = 0; i < TerrainInspector.s_ToolKeys.Length; i++) + { + if (TerrainInspector.s_ToolKeys[i].activated) + { + this.selectedTool = (TerrainTool)i; + base.Repaint(); + Event.current.Use(); + } + } + if (TerrainInspector.s_PrevBrush.activated) + { + this.m_SelectedBrush--; + if (this.m_SelectedBrush < 0) + { + this.m_SelectedBrush = TerrainInspector.s_BrushTextures.Length - 1; + } + base.Repaint(); + Event.current.Use(); + } + if (TerrainInspector.s_NextBrush.activated) + { + this.m_SelectedBrush++; + if (this.m_SelectedBrush >= TerrainInspector.s_BrushTextures.Length) + { + this.m_SelectedBrush = 0; + } + base.Repaint(); + Event.current.Use(); + } + int num = 0; + if (TerrainInspector.s_NextTexture.activated) + { + num = 1; + } + if (TerrainInspector.s_PrevTexture.activated) + { + num = -1; + } + if (num != 0) + { + switch (this.selectedTool) + { + case TerrainTool.PaintTexture: + this.m_SelectedSplat = (int)Mathf.Repeat((float)(this.m_SelectedSplat + num), (float)this.m_Terrain.terrainData.splatPrototypes.Length); + Event.current.Use(); + base.Repaint(); + break; + case TerrainTool.PlaceTree: + TreePainter.selectedTree = (int)Mathf.Repeat((float)(TreePainter.selectedTree + num), (float)this.m_TreeContents.Length); + Event.current.Use(); + base.Repaint(); + break; + case TerrainTool.PaintDetail: + this.m_SelectedDetail = (int)Mathf.Repeat((float)(this.m_SelectedDetail + num), (float)this.m_Terrain.terrainData.detailPrototypes.Length); + Event.current.Use(); + base.Repaint(); + break; + } + } + } + private void LoadBrushIcons() + { + ArrayList arrayList = new ArrayList(); + int num = 1; + Texture texture; + do + { + texture = (Texture2D)EditorGUIUtility.Load(string.Concat(new object[] + { + EditorResourcesUtility.brushesPath, + "builtin_brush_", + num, + ".png" + })); + if (texture) + { + arrayList.Add(texture); + } + num++; + } + while (texture); + num = 0; + do + { + texture = EditorGUIUtility.FindTexture("brush_" + num + ".png"); + if (texture) + { + arrayList.Add(texture); + } + num++; + } + while (texture); + TerrainInspector.s_BrushTextures = (arrayList.ToArray(typeof(Texture2D)) as Texture2D[]); + } + private void Initialize() + { + this.m_Terrain = (this.target as Terrain); + if (TerrainInspector.s_BrushTextures == null) + { + this.LoadBrushIcons(); + } + } + public void OnDisable() + { + if (this.m_CachedBrush != null) + { + this.m_CachedBrush.Dispose(); + } + } + private static string IntString(float p) + { + return ((int)p).ToString(); + } + public void MenuButton(GUIContent title, string menuName, int userData) + { + GUIContent content = new GUIContent(title.text, TerrainInspector.styles.settingsIcon, title.tooltip); + Rect rect = GUILayoutUtility.GetRect(content, TerrainInspector.styles.largeSquare); + if (GUI.Button(rect, content, TerrainInspector.styles.largeSquare)) + { + MenuCommand command = new MenuCommand(this.m_Terrain, userData); + EditorUtility.DisplayPopupMenu(new Rect(rect.x, rect.y, 0f, 0f), menuName, command); + } + } + public static int AspectSelectionGrid(int selected, Texture[] textures, int approxSize, GUIStyle style, string emptyString, out bool doubleClick) + { + GUILayout.BeginVertical("box", new GUILayoutOption[] + { + GUILayout.MinHeight(10f) + }); + int result = 0; + doubleClick = false; + if (textures.Length != 0) + { + float num = (float)((Screen.width - 20) / approxSize); + int num2 = (int)Mathf.Ceil((float)textures.Length / num); + Rect aspectRect = GUILayoutUtility.GetAspectRect(num / (float)num2); + Event current = Event.current; + if (current.type == EventType.MouseDown && current.clickCount == 2 && aspectRect.Contains(current.mousePosition)) + { + doubleClick = true; + current.Use(); + } + result = GUI.SelectionGrid(aspectRect, selected, textures, (Screen.width - 20) / approxSize, style); + } + else + { + GUILayout.Label(emptyString, new GUILayoutOption[0]); + } + GUILayout.EndVertical(); + return result; + } + private static Rect GetBrushAspectRect(int elementCount, int approxSize, int extraLineHeight) + { + int num = (int)Mathf.Ceil((float)((Screen.width - 20) / approxSize)); + int num2 = elementCount / num; + if (elementCount % num != 0) + { + num2++; + } + Rect aspectRect = GUILayoutUtility.GetAspectRect((float)num / (float)num2); + Rect rect = GUILayoutUtility.GetRect(10f, (float)(extraLineHeight * num2)); + aspectRect.height += rect.height; + return aspectRect; + } + public static int AspectSelectionGridImageAndText(int selected, GUIContent[] textures, int approxSize, GUIStyle style, string emptyString, out bool doubleClick) + { + EditorGUILayout.BeginVertical(GUIContent.none, EditorStyles.helpBox, new GUILayoutOption[] + { + GUILayout.MinHeight(10f) + }); + int result = 0; + doubleClick = false; + if (textures.Length != 0) + { + Rect brushAspectRect = TerrainInspector.GetBrushAspectRect(textures.Length, approxSize, 12); + Event current = Event.current; + if (current.type == EventType.MouseDown && current.clickCount == 2 && brushAspectRect.Contains(current.mousePosition)) + { + doubleClick = true; + current.Use(); + } + result = GUI.SelectionGrid(brushAspectRect, selected, textures, (int)Mathf.Ceil((float)((Screen.width - 20) / approxSize)), style); + } + else + { + GUILayout.Label(emptyString, new GUILayoutOption[0]); + } + GUILayout.EndVertical(); + return result; + } + private void LoadTreeIcons() + { + TreePrototype[] treePrototypes = this.m_Terrain.terrainData.treePrototypes; + this.m_TreeContents = new GUIContent[treePrototypes.Length]; + for (int i = 0; i < this.m_TreeContents.Length; i++) + { + this.m_TreeContents[i] = new GUIContent(); + Texture assetPreview = AssetPreview.GetAssetPreview(treePrototypes[i].prefab); + if (assetPreview != null) + { + this.m_TreeContents[i].image = assetPreview; + } + if (treePrototypes[i].prefab != null) + { + this.m_TreeContents[i].text = treePrototypes[i].prefab.name; + } + else + { + this.m_TreeContents[i].text = "Missing"; + } + } + } + private void LoadDetailIcons() + { + DetailPrototype[] detailPrototypes = this.m_Terrain.terrainData.detailPrototypes; + this.m_DetailContents = new GUIContent[detailPrototypes.Length]; + for (int i = 0; i < this.m_DetailContents.Length; i++) + { + this.m_DetailContents[i] = new GUIContent(); + if (detailPrototypes[i].usePrototypeMesh) + { + Texture assetPreview = AssetPreview.GetAssetPreview(detailPrototypes[i].prototype); + if (assetPreview != null) + { + this.m_DetailContents[i].image = assetPreview; + } + if (detailPrototypes[i].prototype != null) + { + this.m_DetailContents[i].text = detailPrototypes[i].prototype.name; + } + else + { + this.m_DetailContents[i].text = "Missing"; + } + } + else + { + Texture prototypeTexture = detailPrototypes[i].prototypeTexture; + if (prototypeTexture != null) + { + this.m_DetailContents[i].image = prototypeTexture; + } + if (prototypeTexture != null) + { + this.m_DetailContents[i].text = prototypeTexture.name; + } + else + { + this.m_DetailContents[i].text = "Missing"; + } + } + } + } + public void ShowTrees() + { + this.LoadTreeIcons(); + GUI.changed = false; + GUILayout.Label(TerrainInspector.styles.trees, EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag; + TreePainter.selectedTree = TerrainInspector.AspectSelectionGridImageAndText(TreePainter.selectedTree, this.m_TreeContents, 64, TerrainInspector.styles.gridListText, "No trees defined", out flag); + if (flag) + { + TerrainTreeContextMenus.EditTree(new MenuCommand(this.m_Terrain, TreePainter.selectedTree)); + GUIUtility.ExitGUI(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowMassPlaceTrees(); + GUILayout.FlexibleSpace(); + this.MenuButton(TerrainInspector.styles.editTrees, "CONTEXT/TerrainEngineTrees", TreePainter.selectedTree); + this.ShowRefreshPrototypes(); + GUILayout.EndHorizontal(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + TreePainter.brushSize = EditorGUILayout.Slider(TerrainInspector.styles.brushSize, TreePainter.brushSize, 1f, 100f, new GUILayoutOption[0]); + float num = (3.3f - TreePainter.spacing) / 3f; + float num2 = TerrainInspector.PercentSlider(TerrainInspector.styles.treeDensity, num, 0.1f, 1f); + if (num2 != num) + { + TreePainter.spacing = (1.1f - num2) * 3f; + } + GUILayout.Space(5f); + TreePainter.treeColorAdjustment = EditorGUILayout.Slider(TerrainInspector.styles.treeColorVar, TreePainter.treeColorAdjustment, 0f, 1f, new GUILayoutOption[0]); + GUILayout.Space(5f); + TreePainter.treeHeight = TerrainInspector.PercentSlider(TerrainInspector.styles.treeHeight, TreePainter.treeHeight, 0.5f, 2f); + TreePainter.treeHeightVariation = TerrainInspector.PercentSlider(TerrainInspector.styles.treeHeightVar, TreePainter.treeHeightVariation, 0f, 0.3f); + GUILayout.Space(5f); + TreePainter.treeWidth = TerrainInspector.PercentSlider(TerrainInspector.styles.treeWidth, TreePainter.treeWidth, 0.5f, 2f); + TreePainter.treeWidthVariation = TerrainInspector.PercentSlider(TerrainInspector.styles.treeWidthVar, TreePainter.treeWidthVariation, 0f, 0.3f); + GUILayout.Space(5f); + } + public void ShowDetails() + { + this.LoadDetailIcons(); + this.ShowBrushes(); + GUI.changed = false; + GUILayout.Label(TerrainInspector.styles.details, EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag; + this.m_SelectedDetail = TerrainInspector.AspectSelectionGridImageAndText(this.m_SelectedDetail, this.m_DetailContents, 64, TerrainInspector.styles.gridListText, "No Detail Objects defined", out flag); + if (flag) + { + TerrainDetailContextMenus.EditDetail(new MenuCommand(this.m_Terrain, this.m_SelectedDetail)); + GUIUtility.ExitGUI(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + this.MenuButton(TerrainInspector.styles.editDetails, "CONTEXT/TerrainEngineDetails", this.m_SelectedDetail); + this.ShowRefreshPrototypes(); + GUILayout.EndHorizontal(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_Size.value = Mathf.RoundToInt(EditorGUILayout.Slider(TerrainInspector.styles.brushSize, (float)this.m_Size, 1f, 100f, new GUILayoutOption[0])); + this.m_DetailOpacity.value = EditorGUILayout.Slider(TerrainInspector.styles.opacity, this.m_DetailOpacity, 0f, 1f, new GUILayoutOption[0]); + this.m_DetailStrength.value = EditorGUILayout.Slider(TerrainInspector.styles.detailTargetStrength, this.m_DetailStrength, 0f, 1f, new GUILayoutOption[0]); + this.m_DetailStrength.value = Mathf.Round(this.m_DetailStrength * 16f) / 16f; + } + public void ShowSettings() + { + TerrainData terrainData = this.m_Terrain.terrainData; + EditorGUI.BeginChangeCheck(); + GUILayout.Label("Base Terrain", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_Terrain.heightmapPixelError = EditorGUILayout.Slider("Pixel Error", this.m_Terrain.heightmapPixelError, 1f, 200f, new GUILayoutOption[0]); + this.m_Terrain.basemapDistance = EditorGUILayout.Slider("Base Map Dist.", this.m_Terrain.basemapDistance, 0f, 2000f, new GUILayoutOption[0]); + this.m_Terrain.castShadows = EditorGUILayout.Toggle("Cast shadows", this.m_Terrain.castShadows, new GUILayoutOption[0]); + this.m_Terrain.materialTemplate = (EditorGUILayout.ObjectField("Material", this.m_Terrain.materialTemplate, typeof(Material), false, new GUILayoutOption[0]) as Material); + if (this.m_Terrain.materialTemplate != null) + { + Shader shader = this.m_Terrain.materialTemplate.shader; + if (ShaderUtil.HasTangentChannel(shader)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("TerrainInspector.ShaderWarning"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } + } + EditorGUI.BeginChangeCheck(); + PhysicMaterial physicMaterial = EditorGUILayout.ObjectField("Physics Material", terrainData.physicMaterial, typeof(PhysicMaterial), false, new GUILayoutOption[0]) as PhysicMaterial; + if (EditorGUI.EndChangeCheck()) + { + terrainData.physicMaterial = physicMaterial; + } + GUILayout.Label("Tree & Detail Objects", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_Terrain.drawTreesAndFoliage = EditorGUILayout.Toggle("Draw", this.m_Terrain.drawTreesAndFoliage, new GUILayoutOption[0]); + this.m_Terrain.collectDetailPatches = EditorGUILayout.Toggle("Collect Detail Patches", this.m_Terrain.collectDetailPatches, new GUILayoutOption[0]); + this.m_Terrain.detailObjectDistance = EditorGUILayout.Slider("Detail Distance", this.m_Terrain.detailObjectDistance, 0f, 250f, new GUILayoutOption[0]); + this.m_Terrain.detailObjectDensity = EditorGUILayout.Slider("Detail Density", this.m_Terrain.detailObjectDensity, 0f, 1f, new GUILayoutOption[0]); + this.m_Terrain.treeDistance = EditorGUILayout.Slider("Tree Distance", this.m_Terrain.treeDistance, 0f, 2000f, new GUILayoutOption[0]); + this.m_Terrain.treeBillboardDistance = EditorGUILayout.Slider("Billboard Start", this.m_Terrain.treeBillboardDistance, 5f, 2000f, new GUILayoutOption[0]); + this.m_Terrain.treeCrossFadeLength = EditorGUILayout.Slider("Fade Length", this.m_Terrain.treeCrossFadeLength, 0f, 200f, new GUILayoutOption[0]); + this.m_Terrain.treeMaximumFullLODCount = EditorGUILayout.IntSlider("Max Mesh Trees", this.m_Terrain.treeMaximumFullLODCount, 0, 10000, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditorApplication.SetSceneRepaintDirty(); + EditorUtility.SetDirty(this.m_Terrain); + } + EditorGUI.BeginChangeCheck(); + GUILayout.Label("Wind Settings", EditorStyles.boldLabel, new GUILayoutOption[0]); + float wavingGrassStrength = EditorGUILayout.Slider("Speed", terrainData.wavingGrassStrength, 0f, 1f, new GUILayoutOption[0]); + float wavingGrassSpeed = EditorGUILayout.Slider("Size", terrainData.wavingGrassSpeed, 0f, 1f, new GUILayoutOption[0]); + float wavingGrassAmount = EditorGUILayout.Slider("Bending", terrainData.wavingGrassAmount, 0f, 1f, new GUILayoutOption[0]); + Color wavingGrassTint = EditorGUILayout.ColorField("Grass Tint", terrainData.wavingGrassTint, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + terrainData.wavingGrassStrength = wavingGrassStrength; + terrainData.wavingGrassSpeed = wavingGrassSpeed; + terrainData.wavingGrassAmount = wavingGrassAmount; + terrainData.wavingGrassTint = wavingGrassTint; + } + this.ShowResolution(); + this.ShowHeightmaps(); + } + public void ShowRaiseHeight() + { + this.ShowBrushes(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.ShowBrushSettings(); + } + public void ShowSmoothHeight() + { + this.ShowBrushes(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.ShowBrushSettings(); + } + public void ShowTextures() + { + this.ShowBrushes(); + GUILayout.Label(TerrainInspector.styles.textures, EditorStyles.boldLabel, new GUILayoutOption[0]); + SplatPrototype[] splatPrototypes = this.m_Terrain.terrainData.splatPrototypes; + Texture2D[] array = new Texture2D[splatPrototypes.Length]; + for (int i = 0; i < splatPrototypes.Length; i++) + { + array[i] = splatPrototypes[i].texture; + } + GUI.changed = false; + bool flag; + this.m_SelectedSplat = TerrainInspector.AspectSelectionGrid(this.m_SelectedSplat, array, 64, TerrainInspector.styles.gridList, "No terrain textures defined.", out flag); + if (flag) + { + TerrainSplatContextMenus.EditSplat(new MenuCommand(this.m_Terrain, this.m_SelectedSplat)); + GUIUtility.ExitGUI(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + this.MenuButton(TerrainInspector.styles.editTextures, "CONTEXT/TerrainEngineSplats", this.m_SelectedSplat); + GUILayout.EndHorizontal(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.ShowBrushSettings(); + this.m_SplatAlpha.value = EditorGUILayout.Slider("Target Strength", this.m_SplatAlpha, 0f, 1f, new GUILayoutOption[0]); + } + public void ShowBrushes() + { + GUILayout.Label(TerrainInspector.styles.brushes, EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag; + this.m_SelectedBrush = TerrainInspector.AspectSelectionGrid(this.m_SelectedBrush, TerrainInspector.s_BrushTextures, 32, TerrainInspector.styles.gridList, "No brushes defined.", out flag); + } + public void ShowHeightmaps() + { + GUILayout.Label(TerrainInspector.styles.heightmap, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(TerrainInspector.styles.importRaw, new GUILayoutOption[0])) + { + TerrainMenus.ImportRaw(); + } + if (GUILayout.Button(TerrainInspector.styles.exportRaw, new GUILayoutOption[0])) + { + TerrainMenus.ExportHeightmapRaw(); + } + GUILayout.EndHorizontal(); + } + public void ShowResolution() + { + GUILayout.Label("Resolution", EditorStyles.boldLabel, new GUILayoutOption[0]); + float num = this.m_Terrain.terrainData.size.x; + float num2 = this.m_Terrain.terrainData.size.y; + float num3 = this.m_Terrain.terrainData.size.z; + int num4 = this.m_Terrain.terrainData.heightmapResolution; + int num5 = this.m_Terrain.terrainData.detailResolution; + int num6 = this.m_Terrain.terrainData.detailResolutionPerPatch; + int num7 = this.m_Terrain.terrainData.alphamapResolution; + int num8 = this.m_Terrain.terrainData.baseMapResolution; + EditorGUI.BeginChangeCheck(); + num = this.DelayedFloatField("Terrain Width", num); + if (num <= 0f) + { + num = 1f; + } + num3 = this.DelayedFloatField("Terrain Length", num3); + if (num3 <= 0f) + { + num3 = 1f; + } + num2 = this.DelayedFloatField("Terrain Height", num2); + if (num2 <= 0f) + { + num2 = 1f; + } + num4 = this.DelayedIntField("Heightmap Resolution", num4); + num4 = Mathf.Clamp(num4, 33, 4097); + num4 = this.m_Terrain.terrainData.GetAdjustedSize(num4); + num5 = this.DelayedIntField("Detail Resolution", num5); + num5 = Mathf.Clamp(num5, 0, 4048); + num6 = this.DelayedIntField("Detail Resolution Per Patch", num6); + num6 = Mathf.Clamp(num6, 8, 128); + num7 = this.DelayedIntField("Control Texture Resolution", num7); + num7 = Mathf.Clamp(Mathf.ClosestPowerOfTwo(num7), 16, 2048); + num8 = this.DelayedIntField("Base Texture Resolution", num8); + num8 = Mathf.Clamp(Mathf.ClosestPowerOfTwo(num8), 16, 2048); + if (EditorGUI.EndChangeCheck()) + { + ArrayList arrayList = new ArrayList(); + arrayList.Add(this.m_Terrain.terrainData); + arrayList.AddRange(this.m_Terrain.terrainData.alphamapTextures); + Undo.RegisterCompleteObjectUndo(arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[], "Set Resolution"); + if (this.m_Terrain.terrainData.heightmapResolution != num4) + { + this.m_Terrain.terrainData.heightmapResolution = num4; + } + this.m_Terrain.terrainData.size = new Vector3(num, num2, num3); + if (this.m_Terrain.terrainData.detailResolution != num5 || num6 != this.m_Terrain.terrainData.detailResolutionPerPatch) + { + this.ResizeDetailResolution(this.m_Terrain.terrainData, num5, num6); + } + if (this.m_Terrain.terrainData.alphamapResolution != num7) + { + this.m_Terrain.terrainData.alphamapResolution = num7; + } + if (this.m_Terrain.terrainData.baseMapResolution != num8) + { + this.m_Terrain.terrainData.baseMapResolution = num8; + } + this.m_Terrain.Flush(); + } + GUILayout.Label("* Please note that modifying the resolution will clear the heightmap, detail map or splatmap.", EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); + } + private void ResizeDetailResolution(TerrainData terrainData, int resolution, int resolutionPerPatch) + { + if (resolution == terrainData.detailResolution) + { + List list = new List(); + for (int i = 0; i < terrainData.detailPrototypes.Length; i++) + { + list.Add(terrainData.GetDetailLayer(0, 0, terrainData.detailWidth, terrainData.detailHeight, i)); + } + terrainData.SetDetailResolution(resolution, resolutionPerPatch); + for (int j = 0; j < list.Count; j++) + { + terrainData.SetDetailLayer(0, 0, j, list[j]); + } + } + else + { + terrainData.SetDetailResolution(resolution, resolutionPerPatch); + } + } + internal float DelayedFloatField(string label, float value) + { + float num = value; + float num2 = num; + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TempContent(label)); + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(rect, num.ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.numberField); + if (EditorGUI.EndChangeCheck() && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num2) && num2 != num) + { + value = num2; + GUI.changed = true; + } + return num2; + } + internal int DelayedIntField(string label, int value) + { + int num = value; + int num2 = num; + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TempContent(label)); + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(rect, num.ToString(), "0123456789-", EditorStyles.numberField); + if (EditorGUI.EndChangeCheck() && int.TryParse(s, out num2) && num2 != num) + { + value = num2; + GUI.changed = true; + } + return num2; + } + public void ShowRefreshPrototypes() + { + if (GUILayout.Button(TerrainInspector.styles.refresh, new GUILayoutOption[0])) + { + TerrainMenus.RefreshPrototypes(); + } + } + public void ShowMassPlaceTrees() + { + EditorGUI.BeginDisabledGroup(this.m_Terrain.terrainData.treePrototypes == null || this.m_Terrain.terrainData.treePrototypes.Length <= 0); + if (GUILayout.Button(TerrainInspector.styles.massPlaceTrees, new GUILayoutOption[0])) + { + TerrainMenus.MassPlaceTrees(); + } + EditorGUI.EndDisabledGroup(); + } + public void ShowBrushSettings() + { + this.m_Size.value = Mathf.RoundToInt(EditorGUILayout.Slider(TerrainInspector.styles.brushSize, (float)this.m_Size, 1f, 100f, new GUILayoutOption[0])); + this.m_Strength.value = TerrainInspector.PercentSlider(TerrainInspector.styles.opacity, this.m_Strength, 0.00167849252f, 1f); + } + public void ShowSetHeight() + { + this.ShowBrushes(); + GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.ShowBrushSettings(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUI.changed = false; + float num = this.m_TargetHeight * this.m_Terrain.terrainData.size.y; + num = EditorGUILayout.Slider("Height", num, 0f, this.m_Terrain.terrainData.size.y, new GUILayoutOption[0]); + if (GUI.changed) + { + this.m_TargetHeight.value = num / this.m_Terrain.terrainData.size.y; + } + if (GUILayout.Button(TerrainInspector.styles.flatten, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + Undo.RegisterCompleteObjectUndo(this.m_Terrain.terrainData, "Flatten Heightmap"); + HeightmapFilters.Flatten(this.m_Terrain.terrainData, this.m_TargetHeight.value); + } + GUILayout.EndHorizontal(); + } + private void OnInspectorUpdate() + { + if (AssetPreview.HasAnyNewPreviewTexturesAvailable()) + { + base.Repaint(); + } + } + public override void OnInspectorGUI() + { + this.Initialize(); + if (TerrainInspector.styles == null) + { + TerrainInspector.styles = new TerrainInspector.Styles(); + } + if (!this.m_Terrain.terrainData) + { + GUI.enabled = false; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Toolbar(-1, TerrainInspector.styles.toolIcons, TerrainInspector.styles.command, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUI.enabled = true; + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label("Terrain Asset Missing", new GUILayoutOption[0]); + this.m_Terrain.terrainData = (EditorGUILayout.ObjectField("Assign:", this.m_Terrain.terrainData, typeof(TerrainData), false, new GUILayoutOption[0]) as TerrainData); + GUILayout.EndVertical(); + return; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.changed = false; + int selectedTool = (int)this.selectedTool; + this.selectedTool = (TerrainTool)GUILayout.Toolbar(selectedTool, TerrainInspector.styles.toolIcons, TerrainInspector.styles.command, new GUILayoutOption[0]); + if (this.selectedTool != (TerrainTool)selectedTool && Toolbar.get != null) + { + Toolbar.get.Repaint(); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + this.CheckKeys(); + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + if (selectedTool >= 0 && selectedTool < TerrainInspector.styles.toolIcons.Length) + { + GUILayout.Label(TerrainInspector.styles.toolNames[selectedTool].text, new GUILayoutOption[0]); + GUILayout.Label(TerrainInspector.styles.toolNames[selectedTool].tooltip, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + } + else + { + GUILayout.Label("No tool selected", new GUILayoutOption[0]); + GUILayout.Label("Please select a tool", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + } + GUILayout.EndVertical(); + switch (selectedTool) + { + case 0: + this.ShowRaiseHeight(); + break; + case 1: + this.ShowSetHeight(); + break; + case 2: + this.ShowSmoothHeight(); + break; + case 3: + this.ShowTextures(); + break; + case 4: + this.ShowTrees(); + break; + case 5: + this.ShowDetails(); + break; + case 6: + this.ShowSettings(); + break; + } + GUI.changed = false; + if (GUI.changed) + { + EditorUtility.SetDirty(this); + } + GUILayout.Space(5f); + } + private Brush GetActiveBrush(int size) + { + if (this.m_CachedBrush == null) + { + this.m_CachedBrush = new Brush(); + } + this.m_CachedBrush.Load(TerrainInspector.s_BrushTextures[this.m_SelectedBrush], size); + return this.m_CachedBrush; + } + public bool Raycast(out Vector2 uv, out Vector3 pos) + { + Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); + RaycastHit raycastHit; + if (this.m_Terrain.collider.Raycast(ray, out raycastHit, float.PositiveInfinity)) + { + uv = raycastHit.textureCoord; + pos = raycastHit.point; + return true; + } + uv = Vector2.zero; + pos = Vector3.zero; + return false; + } + public bool HasFrameBounds() + { + return this.m_Terrain != null; + } + public Bounds OnGetFrameBounds() + { + Vector2 vector; + Vector3 center; + if (Camera.current && this.Raycast(out vector, out center)) + { + Bounds result = default(Bounds); + float num = (this.selectedTool != TerrainTool.PlaceTree) ? ((float)this.m_Size) : TreePainter.brushSize; + Vector3 size; + size.x = num / (float)this.m_Terrain.terrainData.heightmapWidth * this.m_Terrain.terrainData.size.x; + size.z = num / (float)this.m_Terrain.terrainData.heightmapHeight * this.m_Terrain.terrainData.size.z; + size.y = (size.x + size.z) * 0.5f; + result.center = center; + result.size = size; + if (this.selectedTool == TerrainTool.PaintDetail && this.m_Terrain.terrainData.detailWidth != 0) + { + size.x = num / (float)this.m_Terrain.terrainData.detailWidth * this.m_Terrain.terrainData.size.x * 0.7f; + size.z = num / (float)this.m_Terrain.terrainData.detailHeight * this.m_Terrain.terrainData.size.z * 0.7f; + size.y = 0f; + result.size = size; + } + return result; + } + Vector3 position = this.m_Terrain.transform.position; + Vector3 size2 = this.m_Terrain.terrainData.size; + float[,] heights = this.m_Terrain.terrainData.GetHeights(0, 0, this.m_Terrain.terrainData.heightmapWidth, this.m_Terrain.terrainData.heightmapHeight); + float num2 = -3.40282347E+38f; + for (int i = 0; i < this.m_Terrain.terrainData.heightmapHeight; i++) + { + for (int j = 0; j < this.m_Terrain.terrainData.heightmapWidth; j++) + { + num2 = Mathf.Max(num2, heights[j, i]); + } + } + size2.y = num2 * size2.y; + return new Bounds(position + size2 * 0.5f, size2); + } + private bool IsModificationToolActive() + { + if (!this.m_Terrain) + { + return false; + } + TerrainTool selectedTool = this.selectedTool; + return selectedTool != TerrainTool.TerrainSettings && selectedTool >= TerrainTool.PaintHeight && selectedTool < TerrainTool.TerrainToolCount; + } + private bool IsBrushPreviewVisible() + { + Vector2 vector; + Vector3 vector2; + return this.IsModificationToolActive() && this.Raycast(out vector, out vector2); + } + private void DisableProjector() + { + if (this.m_CachedBrush != null) + { + this.m_CachedBrush.GetPreviewProjector().enabled = false; + } + } + private void UpdatePreviewBrush() + { + if (!this.IsModificationToolActive() || this.m_Terrain.terrainData == null) + { + this.DisableProjector(); + return; + } + Projector previewProjector = this.GetActiveBrush(this.m_Size).GetPreviewProjector(); + float num = 1f; + float num2 = this.m_Terrain.terrainData.size.x / this.m_Terrain.terrainData.size.z; + Transform transform = previewProjector.transform; + bool flag = true; + Vector2 vector; + Vector3 vector2; + if (this.Raycast(out vector, out vector2)) + { + if (this.selectedTool == TerrainTool.PlaceTree) + { + previewProjector.material.mainTexture = (Texture2D)EditorGUIUtility.Load(EditorResourcesUtility.brushesPath + "builtin_brush_4.png"); + num = TreePainter.brushSize / 0.8f; + num2 = 1f; + } + else + { + if (this.selectedTool == TerrainTool.PaintHeight || this.selectedTool == TerrainTool.SetHeight || this.selectedTool == TerrainTool.SmoothHeight) + { + if (this.m_Size % 2 == 0) + { + float num3 = 0.5f; + vector.x = (Mathf.Floor(vector.x * (float)(this.m_Terrain.terrainData.heightmapWidth - 1)) + num3) / (float)(this.m_Terrain.terrainData.heightmapWidth - 1); + vector.y = (Mathf.Floor(vector.y * (float)(this.m_Terrain.terrainData.heightmapHeight - 1)) + num3) / (float)(this.m_Terrain.terrainData.heightmapHeight - 1); + } + else + { + vector.x = Mathf.Round(vector.x * (float)(this.m_Terrain.terrainData.heightmapWidth - 1)) / (float)(this.m_Terrain.terrainData.heightmapWidth - 1); + vector.y = Mathf.Round(vector.y * (float)(this.m_Terrain.terrainData.heightmapHeight - 1)) / (float)(this.m_Terrain.terrainData.heightmapHeight - 1); + } + vector2.x = vector.x * this.m_Terrain.terrainData.size.x; + vector2.z = vector.y * this.m_Terrain.terrainData.size.z; + vector2 += this.m_Terrain.transform.position; + num = (float)this.m_Size * 0.5f / (float)this.m_Terrain.terrainData.heightmapWidth * this.m_Terrain.terrainData.size.x; + } + else + { + if (this.selectedTool == TerrainTool.PaintTexture || this.selectedTool == TerrainTool.PaintDetail) + { + float num4 = (this.m_Size % 2 != 0) ? 0.5f : 0f; + int num5; + int num6; + if (this.selectedTool == TerrainTool.PaintTexture) + { + num5 = this.m_Terrain.terrainData.alphamapWidth; + num6 = this.m_Terrain.terrainData.alphamapHeight; + } + else + { + num5 = this.m_Terrain.terrainData.detailWidth; + num6 = this.m_Terrain.terrainData.detailHeight; + } + if (num5 == 0 || num6 == 0) + { + flag = false; + } + vector.x = (Mathf.Floor(vector.x * (float)num5) + num4) / (float)num5; + vector.y = (Mathf.Floor(vector.y * (float)num6) + num4) / (float)num6; + vector2.x = vector.x * this.m_Terrain.terrainData.size.x; + vector2.z = vector.y * this.m_Terrain.terrainData.size.z; + vector2 += this.m_Terrain.transform.position; + num = (float)this.m_Size * 0.5f / (float)num5 * this.m_Terrain.terrainData.size.x; + num2 = (float)num5 / (float)num6; + } + } + } + } + else + { + flag = false; + } + previewProjector.enabled = flag; + if (flag) + { + vector2.y = this.m_Terrain.SampleHeight(vector2); + transform.position = vector2 + new Vector3(0f, 50f, 0f); + } + previewProjector.orthographicSize = num / num2; + previewProjector.aspectRatio = num2; + } + public void OnSceneGUI() + { + this.Initialize(); + if (!this.m_Terrain.terrainData) + { + return; + } + Event current = Event.current; + this.CheckKeys(); + int controlID = GUIUtility.GetControlID(TerrainInspector.s_TerrainEditorHash, FocusType.Passive); + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + case EventType.MouseDrag: + { + if (current.GetTypeForControl(controlID) == EventType.MouseDrag && GUIUtility.hotControl != controlID) + { + return; + } + if (Event.current.alt) + { + return; + } + if (current.button != 0) + { + return; + } + if (!this.IsModificationToolActive()) + { + return; + } + if (HandleUtility.nearestControl != controlID) + { + return; + } + if (current.type == EventType.MouseDown) + { + GUIUtility.hotControl = controlID; + } + Vector2 vector; + Vector3 vector2; + if (this.Raycast(out vector, out vector2)) + { + if (this.selectedTool == TerrainTool.SetHeight && Event.current.shift) + { + this.m_TargetHeight.value = this.m_Terrain.terrainData.GetInterpolatedHeight(vector.x, vector.y) / this.m_Terrain.terrainData.size.y; + InspectorWindow.RepaintAllInspectors(); + } + else + { + if (this.selectedTool == TerrainTool.PlaceTree) + { + if (current.type == EventType.MouseDown) + { + Undo.RegisterCompleteObjectUndo(this.m_Terrain.terrainData, "Place Tree"); + } + TreePainter.terrain = this.m_Terrain; + if (!Event.current.shift && !Event.current.control) + { + TreePainter.PlaceTrees(vector.x, vector.y); + } + else + { + TreePainter.RemoveTrees(vector.x, vector.y, Event.current.control); + } + } + else + { + if (this.selectedTool == TerrainTool.PaintTexture) + { + if (current.type == EventType.MouseDown) + { + List list = new List(); + list.Add(this.m_Terrain.terrainData); + list.AddRange(this.m_Terrain.terrainData.alphamapTextures); + Undo.RegisterCompleteObjectUndo(list.ToArray(), "Detail Edit"); + } + SplatPainter splatPainter = new SplatPainter(); + splatPainter.size = this.m_Size; + splatPainter.strength = this.m_Strength; + splatPainter.terrainData = this.m_Terrain.terrainData; + splatPainter.brush = this.GetActiveBrush(splatPainter.size); + splatPainter.target = this.m_SplatAlpha; + splatPainter.tool = this.selectedTool; + this.m_Terrain.editorRenderFlags = TerrainRenderFlags.heightmap; + splatPainter.Paint(vector.x, vector.y, this.m_SelectedSplat); + this.m_Terrain.terrainData.SetBasemapDirty(false); + } + else + { + if (this.selectedTool == TerrainTool.PaintDetail) + { + if (current.type == EventType.MouseDown) + { + Undo.RegisterCompleteObjectUndo(this.m_Terrain.terrainData, "Detail Edit"); + } + DetailPainter detailPainter = new DetailPainter(); + detailPainter.size = this.m_Size; + detailPainter.targetStrength = this.m_DetailStrength * 16f; + detailPainter.opacity = this.m_DetailOpacity; + if (Event.current.shift || Event.current.control) + { + detailPainter.targetStrength *= -1f; + } + detailPainter.clearSelectedOnly = Event.current.control; + detailPainter.terrainData = this.m_Terrain.terrainData; + detailPainter.brush = this.GetActiveBrush(detailPainter.size); + detailPainter.tool = this.selectedTool; + detailPainter.randomizeDetails = true; + detailPainter.Paint(vector.x, vector.y, this.m_SelectedDetail); + } + else + { + if (current.type == EventType.MouseDown) + { + Undo.RegisterCompleteObjectUndo(this.m_Terrain.terrainData, "Heightmap Edit"); + } + HeightmapPainter heightmapPainter = new HeightmapPainter(); + heightmapPainter.size = this.m_Size; + heightmapPainter.strength = this.m_Strength * 0.01f; + if (this.selectedTool == TerrainTool.SmoothHeight) + { + heightmapPainter.strength = this.m_Strength; + } + heightmapPainter.terrainData = this.m_Terrain.terrainData; + heightmapPainter.brush = this.GetActiveBrush(this.m_Size); + heightmapPainter.targetHeight = this.m_TargetHeight; + heightmapPainter.tool = this.selectedTool; + this.m_Terrain.editorRenderFlags = TerrainRenderFlags.heightmap; + if (this.selectedTool == TerrainTool.PaintHeight && Event.current.shift) + { + heightmapPainter.strength = -heightmapPainter.strength; + } + heightmapPainter.PaintHeight(vector.x, vector.y); + } + } + } + } + } + current.Use(); + break; + } + case EventType.MouseUp: + if (GUIUtility.hotControl != controlID) + { + return; + } + GUIUtility.hotControl = 0; + if (!this.IsModificationToolActive()) + { + return; + } + if (this.selectedTool == TerrainTool.PaintTexture) + { + this.m_Terrain.terrainData.SetBasemapDirty(true); + } + this.m_Terrain.editorRenderFlags = TerrainRenderFlags.all; + this.m_Terrain.ApplyDelayedHeightmapModification(); + current.Use(); + break; + case EventType.MouseMove: + if (this.IsBrushPreviewVisible()) + { + HandleUtility.Repaint(); + } + break; + case EventType.Repaint: + this.DisableProjector(); + break; + case EventType.Layout: + if (!this.IsModificationToolActive()) + { + return; + } + HandleUtility.AddDefaultControl(controlID); + break; + } + } + public void OnPreSceneGUI() + { + if (Event.current.type == EventType.Repaint) + { + this.UpdatePreviewBrush(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainInspectorUtil.cs b/UnityEditor/UnityEditor/TerrainInspectorUtil.cs new file mode 100644 index 00000000..7568249f --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainInspectorUtil.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class TerrainInspectorUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetTreePlacementSize(TerrainData terrainData, int prototypeIndex, float spacing, float treeCount); + public static bool CheckTreeDistance(TerrainData terrainData, Vector3 position, int treeIndex, float distanceBias) + { + return TerrainInspectorUtil.INTERNAL_CALL_CheckTreeDistance(terrainData, ref position, treeIndex, distanceBias); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_CheckTreeDistance(TerrainData terrainData, ref Vector3 position, int treeIndex, float distanceBias); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector3 GetPrototypeExtent(TerrainData terrainData, int prototypeIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPrototypeCount(TerrainData terrainData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PrototypeHasMaterials(TerrainData terrainData, int prototypeIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RefreshPhysicsInEditMode(); + } +} diff --git a/UnityEditor/UnityEditor/TerrainMenus.cs b/UnityEditor/UnityEditor/TerrainMenus.cs new file mode 100644 index 00000000..47f12889 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainMenus.cs @@ -0,0 +1,78 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainMenus + { + [MenuItem("GameObject/3D Object/Terrain", false, 3000)] + private static void CreateTerrain(MenuCommand menuCommand) + { + TerrainData terrainData = new TerrainData(); + terrainData.heightmapResolution = 513; + terrainData.size = new Vector3(2000f, 600f, 2000f); + terrainData.heightmapResolution = 512; + terrainData.baseMapResolution = 1024; + terrainData.SetDetailResolution(1024, terrainData.detailResolutionPerPatch); + AssetDatabase.CreateAsset(terrainData, AssetDatabase.GenerateUniqueAssetPath("Assets/New Terrain.asset")); + GameObject gameObject = Terrain.CreateTerrainGameObject(terrainData); + GameObjectUtility.SetParentAndAlign(gameObject, menuCommand.context as GameObject); + Selection.activeObject = gameObject; + Undo.RegisterCreatedObjectUndo(gameObject, "Create terrain"); + } + internal static void ImportRaw() + { + string text = EditorUtility.OpenFilePanel("Import Raw Heightmap", string.Empty, "raw"); + if (text != string.Empty) + { + ImportRawHeightmap importRawHeightmap = ScriptableWizard.DisplayWizard("Import Heightmap", "Import"); + importRawHeightmap.InitializeImportRaw(TerrainMenus.GetActiveTerrain(), text); + } + } + internal static void ExportHeightmapRaw() + { + ExportRawHeightmap exportRawHeightmap = ScriptableWizard.DisplayWizard("Export Heightmap", "Export"); + exportRawHeightmap.InitializeDefaults(TerrainMenus.GetActiveTerrain()); + } + internal static void SetHeightmapResolution() + { + SetResolutionWizard setResolutionWizard = ScriptableWizard.DisplayWizard("Set Heightmap resolution", "Set Resolution"); + setResolutionWizard.InitializeDefaults(TerrainMenus.GetActiveTerrain()); + } + internal static void MassPlaceTrees() + { + PlaceTreeWizard placeTreeWizard = ScriptableWizard.DisplayWizard("Place Trees", "Place"); + placeTreeWizard.InitializeDefaults(TerrainMenus.GetActiveTerrain()); + } + internal static void Flatten() + { + FlattenHeightmap flattenHeightmap = ScriptableWizard.DisplayWizard("Flatten Heightmap", "Flatten"); + flattenHeightmap.InitializeDefaults(TerrainMenus.GetActiveTerrain()); + } + internal static void RefreshPrototypes() + { + TerrainMenus.GetActiveTerrainData().RefreshPrototypes(); + TerrainMenus.GetActiveTerrain().Flush(); + } + private static void FlushHeightmapModification() + { + TerrainMenus.GetActiveTerrain().Flush(); + } + private static Terrain GetActiveTerrain() + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(Terrain), SelectionMode.Editable); + if (filtered.Length != 0) + { + return filtered[0] as Terrain; + } + return Terrain.activeTerrain; + } + private static TerrainData GetActiveTerrainData() + { + if (TerrainMenus.GetActiveTerrain()) + { + return TerrainMenus.GetActiveTerrain().terrainData; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs b/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs new file mode 100644 index 00000000..5d031bde --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainSplatContextMenus + { + [MenuItem("CONTEXT/TerrainEngineSplats/Add Texture...")] + internal static void AddSplat(MenuCommand item) + { + TerrainSplatEditor.ShowTerrainSplatEditor("Add Terrain Texture", "Add", (Terrain)item.context, -1); + } + [MenuItem("CONTEXT/TerrainEngineSplats/Edit Texture...")] + internal static void EditSplat(MenuCommand item) + { + TerrainSplatEditor.ShowTerrainSplatEditor("Edit Terrain Texture", "Apply", (Terrain)item.context, item.userData); + } + [MenuItem("CONTEXT/TerrainEngineSplats/Edit Texture...", true)] + internal static bool EditSplatCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.splatPrototypes.Length; + } + [MenuItem("CONTEXT/TerrainEngineSplats/Remove Texture")] + internal static void RemoveSplat(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + TerrainEditorUtility.RemoveSplatTexture(terrain.terrainData, item.userData); + } + [MenuItem("CONTEXT/TerrainEngineSplats/Remove Texture", true)] + internal static bool RemoveSplatCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.splatPrototypes.Length; + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainSplatEditor.cs b/UnityEditor/UnityEditor/TerrainSplatEditor.cs new file mode 100644 index 00000000..ee7bf1c8 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainSplatEditor.cs @@ -0,0 +1,199 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainSplatEditor : EditorWindow + { + private string m_ButtonTitle = string.Empty; + private Vector2 m_ScrollPosition; + private Terrain m_Terrain; + private int m_Index = -1; + public Texture2D m_Texture; + public Texture2D m_NormalMap; + private Vector2 m_TileSize; + private Vector2 m_TileOffset; + public TerrainSplatEditor() + { + base.position = new Rect(50f, 50f, 200f, 300f); + base.minSize = new Vector2(200f, 300f); + } + internal static void ShowTerrainSplatEditor(string title, string button, Terrain terrain, int index) + { + TerrainSplatEditor window = EditorWindow.GetWindow(true, title); + window.m_ButtonTitle = button; + window.InitializeData(terrain, index); + } + private void InitializeData(Terrain terrain, int index) + { + this.m_Terrain = terrain; + this.m_Index = index; + SplatPrototype splatPrototype; + if (index == -1) + { + splatPrototype = new SplatPrototype(); + } + else + { + splatPrototype = this.m_Terrain.terrainData.splatPrototypes[index]; + } + this.m_Texture = splatPrototype.texture; + this.m_NormalMap = splatPrototype.normalMap; + this.m_TileSize = splatPrototype.tileSize; + this.m_TileOffset = splatPrototype.tileOffset; + } + private void ApplyTerrainSplat() + { + if (this.m_Terrain == null || this.m_Terrain.terrainData == null) + { + return; + } + SplatPrototype[] array = this.m_Terrain.terrainData.splatPrototypes; + if (this.m_Index == -1) + { + SplatPrototype[] array2 = new SplatPrototype[array.Length + 1]; + Array.Copy(array, 0, array2, 0, array.Length); + this.m_Index = array.Length; + array = array2; + array[this.m_Index] = new SplatPrototype(); + } + array[this.m_Index].texture = this.m_Texture; + array[this.m_Index].normalMap = this.m_NormalMap; + array[this.m_Index].tileSize = this.m_TileSize; + array[this.m_Index].tileOffset = this.m_TileOffset; + this.m_Terrain.terrainData.splatPrototypes = array; + EditorUtility.SetDirty(this.m_Terrain); + } + private bool ValidateTerrain() + { + if (this.m_Terrain == null || this.m_Terrain.terrainData == null) + { + EditorGUILayout.HelpBox("Terrain does not exist", MessageType.Error); + return false; + } + return true; + } + private bool ValidateMainTexture(Texture2D tex) + { + if (tex == null) + { + EditorGUILayout.HelpBox("Assign a tiling texture", MessageType.Warning); + return false; + } + if (tex.width != Mathf.ClosestPowerOfTwo(tex.width) || tex.height != Mathf.ClosestPowerOfTwo(tex.height)) + { + EditorGUILayout.HelpBox("Texture size must be power of two", MessageType.Warning); + return false; + } + if (tex.mipmapCount <= 1) + { + EditorGUILayout.HelpBox("Texture must have mip maps", MessageType.Warning); + return false; + } + return true; + } + private void ShowNormalMapShaderWarning() + { + if (this.m_NormalMap != null && this.m_Terrain != null && (this.m_Terrain.materialTemplate == null || !this.m_Terrain.materialTemplate.HasProperty("_Normal0"))) + { + EditorGUILayout.HelpBox("Note: in order for normal map to have effect, a custom material with normal mapped terrain shader needs to be used.", MessageType.Info); + } + } + private static void TextureFieldGUI(string label, ref Texture2D texture) + { + GUILayout.Space(6f); + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(80f) + }); + GUILayout.Label(label, new GUILayoutOption[0]); + Type typeFromHandle = typeof(Texture2D); + Rect rect = GUILayoutUtility.GetRect(64f, 64f, 64f, 64f, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + }); + texture = (EditorGUI.DoObjectField(rect, rect, GUIUtility.GetControlID(12354, EditorGUIUtility.native, rect), texture, typeFromHandle, null, null, false) as Texture2D); + GUILayout.EndVertical(); + } + private static void SplatSizeGUI(ref Vector2 scale, ref Vector2 offset) + { + GUILayoutOption gUILayoutOption = GUILayout.Width(10f); + GUILayoutOption gUILayoutOption2 = GUILayout.MinWidth(32f); + GUILayout.Space(6f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(string.Empty, EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.Label("x", EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.Label("y", EditorStyles.miniLabel, new GUILayoutOption[] + { + gUILayoutOption + }); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Size", EditorStyles.miniLabel, new GUILayoutOption[0]); + scale.x = EditorGUILayout.FloatField(scale.x, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + scale.y = EditorGUILayout.FloatField(scale.y, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Offset", EditorStyles.miniLabel, new GUILayoutOption[0]); + offset.x = EditorGUILayout.FloatField(offset.x, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + offset.y = EditorGUILayout.FloatField(offset.y, EditorStyles.miniTextField, new GUILayoutOption[] + { + gUILayoutOption2 + }); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + private void OnGUI() + { + EditorGUIUtility.labelWidth = (float)Screen.width - 64f - 20f; + bool flag = true; + this.m_ScrollPosition = EditorGUILayout.BeginVerticalScrollView(this.m_ScrollPosition, false, GUI.skin.verticalScrollbar, GUI.skin.scrollView, new GUILayoutOption[0]); + flag &= this.ValidateTerrain(); + EditorGUI.BeginChangeCheck(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + TerrainSplatEditor.TextureFieldGUI("Texture", ref this.m_Texture); + TerrainSplatEditor.TextureFieldGUI("Normal Map", ref this.m_NormalMap); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + flag &= this.ValidateMainTexture(this.m_Texture); + this.ShowNormalMapShaderWarning(); + TerrainSplatEditor.SplatSizeGUI(ref this.m_TileSize, ref this.m_TileOffset); + bool flag2 = EditorGUI.EndChangeCheck(); + EditorGUILayout.EndScrollView(); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.enabled = flag; + if (GUILayout.Button(this.m_ButtonTitle, new GUILayoutOption[] + { + GUILayout.MinWidth(100f) + })) + { + this.ApplyTerrainSplat(); + base.Close(); + GUIUtility.ExitGUI(); + } + GUI.enabled = true; + GUILayout.EndHorizontal(); + if (flag2 && flag && this.m_Index != -1) + { + this.ApplyTerrainSplat(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainTool.cs b/UnityEditor/UnityEditor/TerrainTool.cs new file mode 100644 index 00000000..4db7d823 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainTool.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditor +{ + internal enum TerrainTool + { + None = -1, + PaintHeight, + SetHeight, + SmoothHeight, + PaintTexture, + PlaceTree, + PaintDetail, + TerrainSettings, + TerrainToolCount + } +} diff --git a/UnityEditor/UnityEditor/TerrainTreeContextMenus.cs b/UnityEditor/UnityEditor/TerrainTreeContextMenus.cs new file mode 100644 index 00000000..39458165 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainTreeContextMenus.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainTreeContextMenus + { + [MenuItem("CONTEXT/TerrainEngineTrees/Add Tree")] + internal static void AddTree(MenuCommand item) + { + TreeWizard treeWizard = ScriptableWizard.DisplayWizard("Add Tree", "Add"); + treeWizard.InitializeDefaults((Terrain)item.context, -1); + } + [MenuItem("CONTEXT/TerrainEngineTrees/Edit Tree")] + internal static void EditTree(MenuCommand item) + { + TreeWizard treeWizard = ScriptableWizard.DisplayWizard("Edit Tree", "Apply"); + treeWizard.InitializeDefaults((Terrain)item.context, item.userData); + } + [MenuItem("CONTEXT/TerrainEngineTrees/Edit Tree", true)] + internal static bool EditTreeCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.treePrototypes.Length; + } + [MenuItem("CONTEXT/TerrainEngineTrees/Remove Tree")] + internal static void RemoveTree(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + TerrainEditorUtility.RemoveTree(terrain, item.userData); + } + [MenuItem("CONTEXT/TerrainEngineTrees/Remove Tree", true)] + internal static bool RemoveTreeCheck(MenuCommand item) + { + Terrain terrain = (Terrain)item.context; + return item.userData >= 0 && item.userData < terrain.terrainData.treePrototypes.Length; + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainWizard.cs b/UnityEditor/UnityEditor/TerrainWizard.cs new file mode 100644 index 00000000..aeb874fd --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainWizard.cs @@ -0,0 +1,40 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TerrainWizard : ScriptableWizard + { + internal const int kMaxResolution = 4097; + protected Terrain m_Terrain; + protected TerrainData terrainData + { + get + { + if (this.m_Terrain != null) + { + return this.m_Terrain.terrainData; + } + return null; + } + } + internal virtual void OnWizardUpdate() + { + base.isValid = true; + base.errorString = string.Empty; + if (this.m_Terrain == null || this.m_Terrain.terrainData == null) + { + base.isValid = false; + base.errorString = "Terrain does not exist"; + } + } + internal void InitializeDefaults(Terrain terrain) + { + this.m_Terrain = terrain; + this.OnWizardUpdate(); + } + internal void FlushHeightmapModification() + { + this.m_Terrain.Flush(); + } + } +} diff --git a/UnityEditor/UnityEditor/TerrainWizards.cs b/UnityEditor/UnityEditor/TerrainWizards.cs new file mode 100644 index 00000000..21872713 --- /dev/null +++ b/UnityEditor/UnityEditor/TerrainWizards.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEditor +{ + internal class TerrainWizards + { + } +} diff --git a/UnityEditor/UnityEditor/TextAreaDrawer.cs b/UnityEditor/UnityEditor/TextAreaDrawer.cs new file mode 100644 index 00000000..a1ad84da --- /dev/null +++ b/UnityEditor/UnityEditor/TextAreaDrawer.cs @@ -0,0 +1,42 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomPropertyDrawer(typeof(TextAreaAttribute))] + internal sealed class TextAreaDrawer : PropertyDrawer + { + private const int kLineHeight = 13; + private Vector2 m_ScrollPosition = default(Vector2); + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + if (property.propertyType == SerializedPropertyType.String) + { + label = EditorGUI.BeginProperty(position, label, property); + Rect labelPosition = position; + labelPosition.height = 16f; + position.yMin += labelPosition.height; + EditorGUI.HandlePrefixLabel(position, labelPosition, label); + EditorGUI.BeginChangeCheck(); + string stringValue = EditorGUI.ScrollableTextAreaInternal(position, property.stringValue, ref this.m_ScrollPosition, EditorStyles.textArea); + if (EditorGUI.EndChangeCheck()) + { + property.stringValue = stringValue; + } + EditorGUI.EndProperty(); + } + else + { + EditorGUI.LabelField(position, label.text, "Use TextAreaDrawer with string."); + } + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + TextAreaAttribute textAreaAttribute = base.attribute as TextAreaAttribute; + string stringValue = property.stringValue; + float num = EditorStyles.textArea.CalcHeight(GUIContent.Temp(stringValue), EditorGUIUtility.contextWidth); + int num2 = Mathf.CeilToInt(num / 13f); + num2 = Mathf.Clamp(num2, textAreaAttribute.minLines, textAreaAttribute.maxLines); + return 32f + (float)((num2 - 1) * 13); + } + } +} diff --git a/UnityEditor/UnityEditor/TextAssetInspector.cs b/UnityEditor/UnityEditor/TextAssetInspector.cs new file mode 100644 index 00000000..437dd6bf --- /dev/null +++ b/UnityEditor/UnityEditor/TextAssetInspector.cs @@ -0,0 +1,43 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(TextAsset))] + internal class TextAssetInspector : Editor + { + private const int kMaxChars = 7000; + private GUIStyle m_TextStyle; + public override void OnInspectorGUI() + { + if (this.m_TextStyle == null) + { + this.m_TextStyle = "ScriptText"; + } + bool enabled = GUI.enabled; + GUI.enabled = true; + TextAsset textAsset = this.target as TextAsset; + if (textAsset != null) + { + string text; + if (base.targets.Length > 1) + { + text = this.targetTitle; + } + else + { + text = textAsset.ToString(); + if (text.Length > 7000) + { + text = text.Substring(0, 7000) + "...\n\n<...etc...>"; + } + } + Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(text), this.m_TextStyle); + rect.x = 0f; + rect.y -= 3f; + rect.width = GUIClip.visibleRect.width + 1f; + GUI.Box(rect, text, this.m_TextStyle); + } + GUI.enabled = enabled; + } + } +} diff --git a/UnityEditor/UnityEditor/TextMeshInspector.cs b/UnityEditor/UnityEditor/TextMeshInspector.cs new file mode 100644 index 00000000..3c7aa8bf --- /dev/null +++ b/UnityEditor/UnityEditor/TextMeshInspector.cs @@ -0,0 +1,33 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(TextMesh))] + internal class TextMeshInspector : Editor + { + private SerializedProperty m_Font; + private void OnEnable() + { + this.m_Font = base.serializedObject.FindProperty("m_Font"); + } + public override void OnInspectorGUI() + { + Font y = (!this.m_Font.hasMultipleDifferentValues) ? (this.m_Font.objectReferenceValue as Font) : null; + base.DrawDefaultInspector(); + Font font = (!this.m_Font.hasMultipleDifferentValues) ? (this.m_Font.objectReferenceValue as Font) : null; + if (font != null && font != y) + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + TextMesh textMesh = (TextMesh)targets[i]; + MeshRenderer component = textMesh.GetComponent(); + if (component) + { + component.sharedMaterial = font.material; + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/Texture3DInspector.cs b/UnityEditor/UnityEditor/Texture3DInspector.cs new file mode 100644 index 00000000..8498ea9b --- /dev/null +++ b/UnityEditor/UnityEditor/Texture3DInspector.cs @@ -0,0 +1,104 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Texture3D))] + internal class Texture3DInspector : TextureInspector + { + private PreviewRenderUtility m_PreviewUtility; + private Material m_Material; + private Mesh m_Mesh; + public Vector2 previewDir = new Vector2(0f, 0f); + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + } + public override string GetInfoString() + { + Texture3D texture3D = this.target as Texture3D; + return string.Format("{0}x{1}x{2} {3} {4}", new object[] + { + texture3D.width, + texture3D.height, + texture3D.depth, + TextureUtil.GetTextureFormatString(texture3D.format), + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySize(texture3D)) + }); + } + public void OnDisable() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + if (this.m_Material) + { + UnityEngine.Object.DestroyImmediate(this.m_Material.shader, true); + UnityEngine.Object.DestroyImmediate(this.m_Material, true); + this.m_Material = null; + } + } + public override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture || !SystemInfo.supports3DTextures) + { + return; + } + GUI.enabled = true; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture || !SystemInfo.supports3DTextures) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "3D texture preview not supported"); + } + return; + } + this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.InitPreview(); + this.m_Material.mainTexture = (this.target as Texture); + this.m_PreviewUtility.BeginPreview(r, background); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 3f; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + Quaternion rot = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); + this.m_PreviewUtility.DrawMesh(this.m_Mesh, Vector3.zero, rot, this.m_Material, 0); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + this.m_Material = new Material("Shader \"Hidden/3DTextureInspector\" {\n Properties {\n\t _MainTex (\"\", 3D) = \"\" { TexGen ObjectLinear }\n }\n SubShader {\n Tags { \"ForceSupported\" = \"True\" } \n\t Pass { SetTexture[_MainTex] { combine texture } }\n }\n Fallback Off\n }"); + this.m_Material.hideFlags = HideFlags.HideAndDontSave; + this.m_Material.shader.hideFlags = HideFlags.HideAndDontSave; + this.m_Material.mainTexture = (this.target as Texture); + } + if (this.m_Mesh == null) + { + GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + if (transform.name == "sphere") + { + this.m_Mesh = transform.GetComponent().sharedMesh; + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/TextureImportInstructions.cs b/UnityEditor/UnityEditor/TextureImportInstructions.cs new file mode 100644 index 00000000..73b9d453 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImportInstructions.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + public sealed class TextureImportInstructions + { + [SerializeField] + public TextureFormat compressedFormat; + [SerializeField] + public TextureFormat uncompressedFormat; + [SerializeField] + public TextureFormat recommendedFormat; + [SerializeField] + public TextureFormat desiredFormat; + [SerializeField] + public TextureUsageMode usageMode; + [SerializeField] + public ColorSpace colorSpace; + [SerializeField] + public int width; + [SerializeField] + public int height; + [SerializeField] + public int compressionQuality; + } +} diff --git a/UnityEditor/UnityEditor/TextureImporter.cs b/UnityEditor/UnityEditor/TextureImporter.cs new file mode 100644 index 00000000..da3ffed4 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporter.cs @@ -0,0 +1,388 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class TextureImporter : AssetImporter + { + public extern TextureImporterFormat textureFormat + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int maxTextureSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int compressionQuality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool grayscaleToAlpha + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureImporterGenerateCubemap generateCubemap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureImporterNPOTScale npotScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isReadable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mipmapEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool borderMipmap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool linearTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureImporterMipFilter mipmapFilter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool fadeout + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int mipmapFadeDistanceStart + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int mipmapFadeDistanceEnd + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool generateMipsInLinearSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("correctGamma Property deprecated. Use generateMipsInLinearSpace instead.")] + public extern bool correctGamma + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool convertToNormalmap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool normalmap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureImporterNormalFilter normalmapFilter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float heightmapScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool lightmap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int anisoLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FilterMode filterMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureWrapMode wrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float mipMapBias + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool alphaIsTransparency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool qualifiesForSpritePacking + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern SpriteImportMode spriteImportMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern SpriteMetaData[] spritesheet + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string spritePackingTag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float spritePixelsPerUnit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use spritePixelsPerUnit property instead.")] + public extern float spritePixelsToUnits + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 spritePivot + { + get + { + Vector2 result; + this.INTERNAL_get_spritePivot(out result); + return result; + } + set + { + this.INTERNAL_set_spritePivot(ref value); + } + } + public Vector4 spriteBorder + { + get + { + Vector4 result; + this.INTERNAL_get_spriteBorder(out result); + return result; + } + set + { + this.INTERNAL_set_spriteBorder(ref value); + } + } + public extern TextureImporterType textureType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetPlatformTextureSettings(string platform, out int maxTextureSize, out TextureImporterFormat textureFormat, out int compressionQuality); + public bool GetPlatformTextureSettings(string platform, out int maxTextureSize, out TextureImporterFormat textureFormat) + { + int num = 0; + return this.GetPlatformTextureSettings(platform, out maxTextureSize, out textureFormat, out num); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPlatformTextureSettings(string platform, int maxTextureSize, TextureImporterFormat textureFormat, int compressionQuality); + public void SetPlatformTextureSettings(string platform, int maxTextureSize, TextureImporterFormat textureFormat) + { + this.SetPlatformTextureSettings(platform, maxTextureSize, textureFormat, 50); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearPlatformTextureSettings(string platform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern TextureImporterFormat FullToSimpleTextureFormat(TextureImporterFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern TextureImporterFormat SimpleToFullTextureFormat2(TextureImporterFormat simpleFormat, TextureImporterType tType, TextureImporterSettings settings, bool doesTextureContainAlpha, bool doesTextureContainColor, BuildTarget destinationPlatform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_spritePivot(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_spritePivot(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_spriteBorder(out Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_spriteBorder(ref Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void GetWidthAndHeight(ref int width, ref int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool DoesSourceTextureHaveAlpha(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool DoesSourceTextureHaveColor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ReadTextureSettings(TextureImporterSettings dest); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTextureSettings(TextureImporterSettings src); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetImportWarnings(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ReadTextureImportInstructions(TextureImportInstructions dest, BuildTarget target); + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterFormat.cs b/UnityEditor/UnityEditor/TextureImporterFormat.cs new file mode 100644 index 00000000..08c2d6b9 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterFormat.cs @@ -0,0 +1,48 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterFormat + { + AutomaticCompressed = -1, + Automatic16bit = -2, + AutomaticTruecolor = -3, + DXT1 = 10, + DXT5 = 12, + RGB16 = 7, + RGB24 = 3, + Alpha8 = 1, + ARGB16, + RGBA32 = 4, + ARGB32, + RGBA16 = 13, + PVRTC_RGB2 = 30, + PVRTC_RGBA2, + PVRTC_RGB4, + PVRTC_RGBA4, + ETC_RGB4, + ATC_RGB4, + ATC_RGBA8, + ATF_RGB_DXT1 = 38, + ATF_RGBA_JPG, + ATF_RGB_JPG, + EAC_R, + EAC_R_SIGNED, + EAC_RG, + EAC_RG_SIGNED, + ETC2_RGB4, + ETC2_RGB4_PUNCHTHROUGH_ALPHA, + ETC2_RGBA8, + ASTC_RGB_4x4, + ASTC_RGB_5x5, + ASTC_RGB_6x6, + ASTC_RGB_8x8, + ASTC_RGB_10x10, + ASTC_RGB_12x12, + ASTC_RGBA_4x4, + ASTC_RGBA_5x5, + ASTC_RGBA_6x6, + ASTC_RGBA_8x8, + ASTC_RGBA_10x10, + ASTC_RGBA_12x12 + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs b/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs new file mode 100644 index 00000000..23ee97a6 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterGenerateCubemap + { + None, + Spheremap, + Cylindrical, + SimpleSpheremap, + NiceSpheremap, + FullCubemap + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterInspector.cs b/UnityEditor/UnityEditor/TextureImporterInspector.cs new file mode 100644 index 00000000..d426715f --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterInspector.cs @@ -0,0 +1,2150 @@ +using NUnit.Framework; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(TextureImporter))] + internal class TextureImporterInspector : AssetImporterInspector + { + private enum AdvancedTextureType + { + Default, + NormalMap, + LightMap + } + [Serializable] + protected class PlatformSetting + { + [SerializeField] + public string name; + [SerializeField] + private bool m_Overridden; + [SerializeField] + private bool m_OverriddenIsDifferent; + [SerializeField] + private int m_MaxTextureSize; + [SerializeField] + private bool m_MaxTextureSizeIsDifferent; + [SerializeField] + private int m_CompressionQuality; + [SerializeField] + private bool m_CompressionQualityIsDifferent; + [SerializeField] + private TextureImporterFormat[] m_TextureFormatArray; + [SerializeField] + private bool m_TextureFormatIsDifferent; + [SerializeField] + public BuildTarget m_Target; + [SerializeField] + private TextureImporter[] m_Importers; + [SerializeField] + private bool m_HasChanged; + [SerializeField] + private TextureImporterInspector m_Inspector; + public bool overridden + { + get + { + return this.m_Overridden; + } + } + public bool overriddenIsDifferent + { + get + { + return this.m_OverriddenIsDifferent; + } + } + public bool allAreOverridden + { + get + { + return this.isDefault || (this.m_Overridden && !this.m_OverriddenIsDifferent); + } + } + public int maxTextureSize + { + get + { + return this.m_MaxTextureSize; + } + } + public bool maxTextureSizeIsDifferent + { + get + { + return this.m_MaxTextureSizeIsDifferent; + } + } + public int compressionQuality + { + get + { + return this.m_CompressionQuality; + } + } + public bool compressionQualityIsDifferent + { + get + { + return this.m_CompressionQualityIsDifferent; + } + } + public TextureImporterFormat[] textureFormats + { + get + { + return this.m_TextureFormatArray; + } + } + public bool textureFormatIsDifferent + { + get + { + return this.m_TextureFormatIsDifferent; + } + } + public TextureImporter[] importers + { + get + { + return this.m_Importers; + } + } + public bool isDefault + { + get + { + return this.name == string.Empty; + } + } + public PlatformSetting(string name, BuildTarget target, TextureImporterInspector inspector) + { + this.name = name; + this.m_Target = target; + this.m_Inspector = inspector; + this.m_Overridden = false; + this.m_Importers = ( + from x in inspector.targets + select x as TextureImporter).ToArray(); + this.m_TextureFormatArray = new TextureImporterFormat[this.importers.Length]; + for (int i = 0; i < this.importers.Length; i++) + { + TextureImporter textureImporter = this.importers[i]; + int maxTextureSize; + TextureImporterFormat textureFormat; + int compressionQuality; + bool flag; + if (!this.isDefault) + { + flag = textureImporter.GetPlatformTextureSettings(name, out maxTextureSize, out textureFormat, out compressionQuality); + } + else + { + flag = true; + maxTextureSize = textureImporter.maxTextureSize; + textureFormat = textureImporter.textureFormat; + compressionQuality = textureImporter.compressionQuality; + } + this.m_TextureFormatArray[i] = textureFormat; + if (i == 0) + { + this.m_Overridden = flag; + this.m_MaxTextureSize = maxTextureSize; + this.m_CompressionQuality = compressionQuality; + } + else + { + if (flag != this.m_Overridden) + { + this.m_OverriddenIsDifferent = true; + } + if (maxTextureSize != this.m_MaxTextureSize) + { + this.m_MaxTextureSizeIsDifferent = true; + } + if (compressionQuality != this.m_CompressionQuality) + { + this.m_CompressionQualityIsDifferent = true; + } + if (textureFormat != this.m_TextureFormatArray[0]) + { + this.m_TextureFormatIsDifferent = true; + } + } + } + this.Sync(); + } + public void SetOverriddenForAll(bool overridden) + { + this.m_Overridden = overridden; + this.m_OverriddenIsDifferent = false; + this.m_HasChanged = true; + } + public void SetMaxTextureSizeForAll(int maxTextureSize) + { + Assert.IsTrue(this.allAreOverridden, "Attempting to set max texture size for all platforms even though settings are not overwritten for all platforms."); + this.m_MaxTextureSize = maxTextureSize; + this.m_MaxTextureSizeIsDifferent = false; + this.m_HasChanged = true; + } + public void SetCompressionQualityForAll(int quality) + { + Assert.IsTrue(this.allAreOverridden, "Attempting to set texture compression quality for all platforms even though settings are not overwritten for all platforms."); + this.m_CompressionQuality = quality; + this.m_CompressionQualityIsDifferent = false; + this.m_HasChanged = true; + } + public void SetTextureFormatForAll(TextureImporterFormat format) + { + Assert.IsTrue(this.allAreOverridden, "Attempting to set texture format for all platforms even though settings are not overwritten for all platforms."); + for (int i = 0; i < this.m_TextureFormatArray.Length; i++) + { + this.m_TextureFormatArray[i] = format; + } + this.m_TextureFormatIsDifferent = false; + this.m_HasChanged = true; + } + public bool SupportsFormat(TextureImporterFormat format, TextureImporter importer) + { + TextureImporterSettings settings = this.GetSettings(importer); + BuildTarget target = this.m_Target; + int[] array; + switch (target) + { + case BuildTarget.Android: + array = TextureImporterInspector.kTextureFormatsValueAndroid; + goto IL_D9; + case BuildTarget.StandaloneGLESEmu: + array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueGLESEmu : TextureImporterInspector.kNormalFormatsValueWeb); + goto IL_D9; + case (BuildTarget)15: + case BuildTarget.NaCl: + case BuildTarget.StandaloneLinux: + IL_30: + if (target == BuildTarget.BB10) + { + array = TextureImporterInspector.kTextureFormatsValueBB10; + goto IL_D9; + } + if (target == BuildTarget.Tizen) + { + array = TextureImporterInspector.kTextureFormatsValueTizen; + goto IL_D9; + } + if (target != BuildTarget.iPhone) + { + array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueWeb : TextureImporterInspector.kNormalFormatsValueWeb); + goto IL_D9; + } + array = TextureImporterInspector.kTextureFormatsValueiPhone; + goto IL_D9; + case BuildTarget.FlashPlayer: + array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueFlash : TextureImporterInspector.kNormalFormatsValueFlash); + goto IL_D9; + } + goto IL_30; + IL_D9: + return ((IList)array).Contains((int)format); + } + public TextureImporterSettings GetSettings(TextureImporter importer) + { + TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); + importer.ReadTextureSettings(textureImporterSettings); + this.m_Inspector.GetSerializedPropertySettings(textureImporterSettings); + return textureImporterSettings; + } + public virtual bool HasChanged() + { + return this.m_HasChanged; + } + public void Sync() + { + if (!this.isDefault && (!this.m_Overridden || this.m_OverriddenIsDifferent)) + { + TextureImporterInspector.PlatformSetting platformSetting = this.m_Inspector.m_PlatformSettings[0]; + this.m_MaxTextureSize = platformSetting.m_MaxTextureSize; + this.m_MaxTextureSizeIsDifferent = platformSetting.m_MaxTextureSizeIsDifferent; + this.m_TextureFormatArray = (TextureImporterFormat[])platformSetting.m_TextureFormatArray.Clone(); + this.m_TextureFormatIsDifferent = platformSetting.m_TextureFormatIsDifferent; + this.m_CompressionQuality = platformSetting.m_CompressionQuality; + this.m_CompressionQualityIsDifferent = platformSetting.m_CompressionQualityIsDifferent; + } + TextureImporterType textureType = this.m_Inspector.textureType; + int i = 0; + while (i < this.importers.Length) + { + TextureImporter textureImporter = this.importers[i]; + TextureImporterSettings settings = this.GetSettings(textureImporter); + if (textureType == TextureImporterType.Advanced) + { + if (!this.isDefault) + { + if (!this.SupportsFormat(this.m_TextureFormatArray[i], textureImporter)) + { + this.m_TextureFormatArray[i] = TextureImporter.FullToSimpleTextureFormat(this.m_TextureFormatArray[i]); + } + if (this.m_TextureFormatArray[i] < (TextureImporterFormat)0) + { + this.m_TextureFormatArray[i] = TextureImporter.SimpleToFullTextureFormat2(this.m_TextureFormatArray[i], textureType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.DoesSourceTextureHaveColor(), this.m_Target); + } + goto IL_14A; + } + } + else + { + if (this.m_TextureFormatArray[i] >= (TextureImporterFormat)0) + { + this.m_TextureFormatArray[i] = TextureImporter.FullToSimpleTextureFormat(this.m_TextureFormatArray[i]); + goto IL_14A; + } + goto IL_14A; + } + IL_17B: + i++; + continue; + IL_14A: + if (settings.normalMap && !TextureImporterInspector.IsGLESMobileTargetPlatform(this.m_Target)) + { + this.m_TextureFormatArray[i] = TextureImporterInspector.MakeTextureFormatHaveAlpha(this.m_TextureFormatArray[i]); + goto IL_17B; + } + goto IL_17B; + } + this.m_TextureFormatIsDifferent = false; + TextureImporterFormat[] textureFormatArray = this.m_TextureFormatArray; + for (int j = 0; j < textureFormatArray.Length; j++) + { + TextureImporterFormat textureImporterFormat = textureFormatArray[j]; + if (textureImporterFormat != this.m_TextureFormatArray[0]) + { + this.m_TextureFormatIsDifferent = true; + } + } + } + private bool GetOverridden(TextureImporter importer) + { + if (!this.m_OverriddenIsDifferent) + { + return this.m_Overridden; + } + int num; + TextureImporterFormat textureImporterFormat; + return importer.GetPlatformTextureSettings(this.name, out num, out textureImporterFormat); + } + public void Apply() + { + for (int i = 0; i < this.importers.Length; i++) + { + TextureImporter textureImporter = this.importers[i]; + int compressionQuality = -1; + bool flag = false; + int maxTextureSize; + if (this.isDefault) + { + maxTextureSize = textureImporter.maxTextureSize; + } + else + { + TextureImporterFormat textureImporterFormat; + flag = textureImporter.GetPlatformTextureSettings(this.name, out maxTextureSize, out textureImporterFormat, out compressionQuality); + } + if (!flag) + { + maxTextureSize = textureImporter.maxTextureSize; + } + if (!this.m_MaxTextureSizeIsDifferent) + { + maxTextureSize = this.m_MaxTextureSize; + } + if (!this.m_CompressionQualityIsDifferent) + { + compressionQuality = this.m_CompressionQuality; + } + if (!this.isDefault) + { + if (!this.m_OverriddenIsDifferent) + { + flag = this.m_Overridden; + } + if (flag) + { + textureImporter.SetPlatformTextureSettings(this.name, maxTextureSize, this.m_TextureFormatArray[i], compressionQuality); + } + else + { + textureImporter.ClearPlatformTextureSettings(this.name); + } + } + else + { + textureImporter.maxTextureSize = maxTextureSize; + textureImporter.textureFormat = this.m_TextureFormatArray[i]; + } + } + } + } + private enum CookieMode + { + Spot, + Directional, + Point + } + private class Styles + { + public readonly GUIContent textureType = EditorGUIUtility.TextContent("TextureImporter.TextureType"); + public readonly GUIContent[] textureTypeOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.TextureType.Image"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Normalmap"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.GUI"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Sprite"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Cursor"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Reflection"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Cookie"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Lightmap"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Advanced") + }; + public readonly GUIContent generateAlphaFromGrayscale = EditorGUIUtility.TextContent("TextureImporter.GenerateAlphaFromGrayscale"); + public readonly GUIContent cookieType = EditorGUIUtility.TextContent("TextureImporter.Cookie"); + public readonly GUIContent[] cookieOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.Cookie.Spot"), + EditorGUIUtility.TextContent("TextureImporter.Cookie.Directional"), + EditorGUIUtility.TextContent("TextureImporter.Cookie.Point") + }; + public readonly GUIContent generateFromBump = EditorGUIUtility.TextContent("TextureImporter.GenerateFromBump"); + public readonly GUIContent generateBumpmap = EditorGUIUtility.TextContent("TextureImporter.GenerateBumpmap"); + public readonly GUIContent bumpiness = EditorGUIUtility.TextContent("TextureImporter.Bumpiness"); + public readonly GUIContent bumpFiltering = EditorGUIUtility.TextContent("TextureImporter.BumpFiltering"); + public readonly GUIContent[] bumpFilteringOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.BumpFiltering.Sharp"), + EditorGUIUtility.TextContent("TextureImporter.BumpFiltering.Smooth") + }; + public readonly GUIContent refMap = EditorGUIUtility.TextContent("TextureImporter.RefMap"); + public readonly GUIContent[] refMapOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.RefMap.Sphere"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.Cylindrical"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.SimpleSphere"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.NiceSphere"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.FullCubemap") + }; + public readonly GUIContent seamlessCubemap = EditorGUIUtility.TextContent("TextureImporter.SeamlessCubemap"); + public readonly GUIContent maxSize = EditorGUIUtility.TextContent("TextureImporter.MaxSize"); + public readonly GUIContent textureFormat = EditorGUIUtility.TextContent("TextureImporter.TextureFormat"); + public readonly string[] textureFormatOptions = new string[] + { + EditorGUIUtility.TextContent("TextureImporter.TextureFormat.Compressed").text, + EditorGUIUtility.TextContent("TextureImporter.TextureFormat.16 bit").text, + EditorGUIUtility.TextContent("TextureImporter.TextureFormat.Truecolor").text + }; + public readonly GUIContent defaultPlatform = EditorGUIUtility.TextContent("TextureImporter.Platforms.Default"); + public readonly GUIContent mipmapFadeOutToggle = EditorGUIUtility.TextContent("TextureImporter.MipmapFadeToggle"); + public readonly GUIContent mipmapFadeOut = EditorGUIUtility.TextContent("TextureImporter.MipmapFade"); + public readonly GUIContent readWrite = EditorGUIUtility.TextContent("TextureImporter.ReadWrite"); + public readonly GUIContent generateMipMaps = EditorGUIUtility.TextContent("TextureImporter.GenerateMipMaps"); + public readonly GUIContent mipMapsInLinearSpace = EditorGUIUtility.TextContent("TextureImporter.MipMapsInLinearSpace"); + public readonly GUIContent linearTexture = EditorGUIUtility.TextContent("TextureImporter.LinearTexture"); + public readonly GUIContent borderMipMaps = EditorGUIUtility.TextContent("TextureImporter.BorderMipMaps"); + public readonly GUIContent mipMapFilter = EditorGUIUtility.TextContent("TextureImporter.MipMapFilter"); + public readonly GUIContent[] mipMapFilterOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.MipMapFilterOptions.Box"), + EditorGUIUtility.TextContent("TextureImporter.MipMapFilterOptions.Kaiser") + }; + public readonly GUIContent normalmap = EditorGUIUtility.TextContent("TextureImporter.NormalMap"); + public readonly GUIContent npot = EditorGUIUtility.TextContent("TextureImporter.Npot"); + public readonly GUIContent generateCubemap = EditorGUIUtility.TextContent("TextureImporter.GenerateCubemap"); + public readonly GUIContent lightmap = EditorGUIUtility.TextContent("TextureImporter.Lightmap"); + public readonly GUIContent compressionQuality = EditorGUIUtility.TextContent("TextureImporter.CompressionQuality"); + public readonly GUIContent[] mobileCompressionQualityOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.CompressionQualityOptions.Fast"), + EditorGUIUtility.TextContent("TextureImporter.CompressionQualityOptions.Normal"), + EditorGUIUtility.TextContent("TextureImporter.CompressionQualityOptions.Best") + }; + public readonly GUIContent spriteMode = EditorGUIUtility.TextContent("TextureImporter.SpriteMode"); + public readonly GUIContent[] spriteModeOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.SpriteModeOptions.SingleSprite"), + EditorGUIUtility.TextContent("TextureImporter.SpriteModeOptions.Multiple") + }; + public readonly GUIContent[] spriteModeOptionsAdvanced = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.SpriteModeOptions.None"), + EditorGUIUtility.TextContent("TextureImporter.SpriteModeOptions.SingleSprite"), + EditorGUIUtility.TextContent("TextureImporter.SpriteModeOptions.Multiple") + }; + public readonly GUIContent[] spriteMeshTypeOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.SpriteMeshTypeOptions.FullRect"), + EditorGUIUtility.TextContent("TextureImporter.SpriteMeshTypeOptions.Tight") + }; + public readonly GUIContent spritePackingTag = EditorGUIUtility.TextContent("TextureImporter.SpritePackingTag"); + public readonly GUIContent spritePixelsPerUnit = EditorGUIUtility.TextContent("TextureImporter.SpritePixelsPerUnit"); + public readonly GUIContent spriteExtrude = EditorGUIUtility.TextContent("TextureImporter.SpriteExtrude"); + public readonly GUIContent spriteMeshType = EditorGUIUtility.TextContent("TextureImporter.SpriteMeshType"); + public readonly GUIContent spriteAlignment = EditorGUIUtility.TextContent("SpriteInspector.Pivot"); + public readonly GUIContent[] spriteAlignmentOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Custom") + }; + public readonly GUIContent alphaIsTransparency = EditorGUIUtility.TextContent("TextureImporter.AlphaIsTransparency"); + } + private SerializedProperty m_TextureType; + [SerializeField] + protected List m_PlatformSettings; + private static int[] s_TextureFormatsValueAll; + private static readonly int[] kTextureFormatsValueWeb = new int[] + { + 10, + 12, + 7, + 3, + 1, + 2, + 5 + }; + private static readonly int[] kTextureFormatsValueiPhone = new int[] + { + 30, + 31, + 32, + 33, + 7, + 3, + 1, + 13, + 4 + }; + private static readonly int[] kTextureFormatsValueAndroid = new int[] + { + 10, + 12, + 34, + 45, + 46, + 47, + 30, + 31, + 32, + 33, + 35, + 36, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 7, + 3, + 1, + 13, + 4 + }; + private static readonly int[] kTextureFormatsValueBB10 = new int[] + { + 34, + 30, + 31, + 32, + 33, + 7, + 3, + 1, + 13, + 4 + }; + private static readonly int[] kTextureFormatsValueTizen = new int[] + { + 34, + 7, + 3, + 1, + 13, + 4 + }; + private static readonly int[] kTextureFormatsValueFlash = new int[] + { + 40, + 39, + 3, + 4 + }; + private static readonly int[] kTextureFormatsValueGLESEmu = new int[] + { + 34, + 30, + 31, + 32, + 33, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59, + 7, + 3, + 1, + 13, + 5 + }; + private static int[] s_NormalFormatsValueAll; + private static readonly int[] kNormalFormatsValueWeb = new int[] + { + 12, + 2, + 5 + }; + private static readonly int[] kNormalFormatsValueFlash = new int[] + { + 39, + 4 + }; + private static readonly TextureImporterFormat[] kFormatsWithCompressionSettings = new TextureImporterFormat[] + { + TextureImporterFormat.PVRTC_RGB2, + TextureImporterFormat.PVRTC_RGB4, + TextureImporterFormat.PVRTC_RGBA2, + TextureImporterFormat.PVRTC_RGBA4, + TextureImporterFormat.ATC_RGB4, + TextureImporterFormat.ATC_RGBA8, + TextureImporterFormat.ETC_RGB4, + TextureImporterFormat.ATF_RGB_JPG, + TextureImporterFormat.ATF_RGBA_JPG, + TextureImporterFormat.ETC2_RGB4, + TextureImporterFormat.ETC2_RGB4_PUNCHTHROUGH_ALPHA, + TextureImporterFormat.ETC2_RGBA8, + TextureImporterFormat.ASTC_RGB_4x4, + TextureImporterFormat.ASTC_RGB_5x5, + TextureImporterFormat.ASTC_RGB_6x6, + TextureImporterFormat.ASTC_RGB_8x8, + TextureImporterFormat.ASTC_RGB_10x10, + TextureImporterFormat.ASTC_RGB_12x12, + TextureImporterFormat.ASTC_RGBA_4x4, + TextureImporterFormat.ASTC_RGBA_5x5, + TextureImporterFormat.ASTC_RGBA_6x6, + TextureImporterFormat.ASTC_RGBA_8x8, + TextureImporterFormat.ASTC_RGBA_10x10, + TextureImporterFormat.ASTC_RGBA_12x12 + }; + private static string[] s_TextureFormatStringsAll; + private static string[] s_TextureFormatStringsGLESEmu; + private static string[] s_TextureFormatStringsiPhone; + private static string[] s_TextureFormatStringsAndroid; + private static string[] s_TextureFormatStringsBB10; + private static string[] s_TextureFormatStringsTizen; + private static string[] s_TextureFormatStringsFlash; + private static string[] s_TextureFormatStringsWeb; + private static string[] s_NormalFormatStringsAll; + private static string[] s_NormalFormatStringsFlash; + private static string[] s_NormalFormatStringsWeb; + private readonly AnimBool m_ShowBumpGenerationSettings = new AnimBool(); + private readonly AnimBool m_ShowCookieCubeMapSettings = new AnimBool(); + private readonly AnimBool m_ShowGenericSpriteSettings = new AnimBool(); + private readonly AnimBool m_ShowManualAtlasGenerationSettings = new AnimBool(); + private readonly GUIContent m_EmptyContent = new GUIContent(" "); + private readonly int[] m_TextureTypeValues = new int[] + { + 0, + 1, + 2, + 8, + 7, + 3, + 4, + 6, + 5 + }; + private readonly int[] m_TextureFormatValues = new int[] + { + 0, + 1, + 2 + }; + private string m_ImportWarning; + private static TextureImporterInspector.Styles s_Styles; + private SerializedProperty m_GrayscaleToAlpha; + private SerializedProperty m_ConvertToNormalMap; + private SerializedProperty m_NormalMap; + private SerializedProperty m_HeightScale; + private SerializedProperty m_NormalMapFilter; + private SerializedProperty m_GenerateCubemap; + private SerializedProperty m_SeamlessCubemap; + private SerializedProperty m_BorderMipMap; + private SerializedProperty m_NPOTScale; + private SerializedProperty m_IsReadable; + private SerializedProperty m_LinearTexture; + private SerializedProperty m_EnableMipMap; + private SerializedProperty m_GenerateMipsInLinearSpace; + private SerializedProperty m_MipMapMode; + private SerializedProperty m_FadeOut; + private SerializedProperty m_MipMapFadeDistanceStart; + private SerializedProperty m_MipMapFadeDistanceEnd; + private SerializedProperty m_Lightmap; + private SerializedProperty m_Aniso; + private SerializedProperty m_FilterMode; + private SerializedProperty m_WrapMode; + private SerializedProperty m_SpriteMode; + private SerializedProperty m_SpritePackingTag; + private SerializedProperty m_SpritePixelsToUnits; + private SerializedProperty m_SpriteExtrude; + private SerializedProperty m_SpriteMeshType; + private SerializedProperty m_Alignment; + private SerializedProperty m_SpritePivot; + private SerializedProperty m_AlphaIsTransparency; + private static readonly string[] kMaxTextureSizeStrings = new string[] + { + "32", + "64", + "128", + "256", + "512", + "1024", + "2048", + "4096" + }; + private static readonly int[] kMaxTextureSizeValues = new int[] + { + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096 + }; + private TextureImporterType textureType + { + get + { + if (this.textureTypeHasMultipleDifferentValues) + { + return (TextureImporterType)(-1); + } + if (this.m_TextureType.intValue < 0) + { + return (this.target as TextureImporter).textureType; + } + return (TextureImporterType)this.m_TextureType.intValue; + } + } + private bool textureTypeHasMultipleDifferentValues + { + get + { + if (this.m_TextureType.hasMultipleDifferentValues) + { + return true; + } + if (this.m_TextureType.intValue >= 0) + { + return false; + } + TextureImporterType textureType = (this.target as TextureImporter).textureType; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + if ((@object as TextureImporter).textureType != textureType) + { + return true; + } + } + return false; + } + } + internal override bool showImportedObject + { + get + { + return false; + } + } + private static int[] TextureFormatsValueAll + { + get + { + if (TextureImporterInspector.s_TextureFormatsValueAll != null) + { + return TextureImporterInspector.s_TextureFormatsValueAll; + } + bool flag = false; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + bool flag5 = false; + BuildPlayerWindow.BuildPlatform[] buildPlayerValidPlatforms = TextureImporterInspector.GetBuildPlayerValidPlatforms(); + BuildPlayerWindow.BuildPlatform[] array = buildPlayerValidPlatforms; + for (int i = 0; i < array.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array[i]; + BuildTarget defaultTarget = buildPlatform.DefaultTarget; + switch (defaultTarget) + { + case BuildTarget.iPhone: + flag2 = true; + goto IL_B1; + case BuildTarget.PS3: + case BuildTarget.XBOX360: + case (BuildTarget)12: + IL_60: + if (defaultTarget == BuildTarget.BB10) + { + flag2 = true; + flag = true; + goto IL_B1; + } + if (defaultTarget != BuildTarget.Tizen) + { + goto IL_B1; + } + flag = true; + goto IL_B1; + case BuildTarget.Android: + flag2 = true; + flag = true; + flag3 = true; + flag4 = true; + flag5 = true; + goto IL_B1; + case BuildTarget.StandaloneGLESEmu: + flag2 = true; + flag = true; + flag4 = true; + flag5 = true; + goto IL_B1; + } + goto IL_60; + IL_B1:; + } + List list = new List(); + list.AddRange(new int[] + { + -1, + 10, + 12 + }); + if (flag) + { + list.Add(34); + } + if (flag2) + { + list.AddRange(new int[] + { + 30, + 31, + 32, + 33 + }); + } + if (flag3) + { + list.AddRange(new int[] + { + 35, + 36 + }); + } + if (flag4) + { + list.AddRange(new int[] + { + 45, + 46, + 47 + }); + } + if (flag5) + { + list.AddRange(new int[] + { + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59 + }); + } + list.AddRange(new int[] + { + -2, + 7, + 2, + 13, + -3, + 3, + 1, + 5, + 4 + }); + TextureImporterInspector.s_TextureFormatsValueAll = list.ToArray(); + return TextureImporterInspector.s_TextureFormatsValueAll; + } + } + private static int[] NormalFormatsValueAll + { + get + { + bool flag = false; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + bool flag5 = false; + BuildPlayerWindow.BuildPlatform[] buildPlayerValidPlatforms = TextureImporterInspector.GetBuildPlayerValidPlatforms(); + BuildPlayerWindow.BuildPlatform[] array = buildPlayerValidPlatforms; + for (int i = 0; i < array.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array[i]; + BuildTarget defaultTarget = buildPlatform.DefaultTarget; + switch (defaultTarget) + { + case BuildTarget.iPhone: + flag2 = true; + flag = true; + goto IL_A3; + case BuildTarget.PS3: + case BuildTarget.XBOX360: + case (BuildTarget)12: + IL_50: + if (defaultTarget == BuildTarget.BB10) + { + flag2 = true; + flag = true; + goto IL_A3; + } + if (defaultTarget != BuildTarget.Tizen) + { + goto IL_A3; + } + flag = true; + goto IL_A3; + case BuildTarget.Android: + flag2 = true; + flag3 = true; + flag = true; + flag4 = true; + flag5 = true; + goto IL_A3; + case BuildTarget.StandaloneGLESEmu: + flag2 = true; + flag = true; + flag4 = true; + flag5 = true; + goto IL_A3; + } + goto IL_50; + IL_A3:; + } + List list = new List(); + list.AddRange(new int[] + { + -1, + 12 + }); + if (flag2) + { + list.AddRange(new int[] + { + 30, + 31, + 32, + 33 + }); + } + if (flag3) + { + list.AddRange(new int[] + { + 35, + 36 + }); + } + if (flag) + { + list.AddRange(new int[] + { + 34 + }); + } + if (flag4) + { + list.AddRange(new int[] + { + 45, + 46, + 47 + }); + } + if (flag5) + { + list.AddRange(new int[] + { + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 58, + 59 + }); + } + list.AddRange(new int[] + { + -2, + 2, + 13, + -3, + 4 + }); + TextureImporterInspector.s_NormalFormatsValueAll = list.ToArray(); + return TextureImporterInspector.s_NormalFormatsValueAll; + } + } + public new void OnDisable() + { + base.OnDisable(); + } + internal static bool IsGLESMobileTargetPlatform(BuildTarget target) + { + return target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.BB10 || target == BuildTarget.Tizen; + } + private void UpdateImportWarning() + { + TextureImporter textureImporter = this.target as TextureImporter; + this.m_ImportWarning = ((!textureImporter) ? null : textureImporter.GetImportWarnings()); + } + private void ToggleFromInt(SerializedProperty property, GUIContent label) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = property.hasMultipleDifferentValues; + int intValue = (!EditorGUILayout.Toggle(label, property.intValue > 0, new GUILayoutOption[0])) ? 0 : 1; + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + } + private void EnumPopup(SerializedProperty property, Type type, GUIContent label) + { + EditorGUILayout.IntPopup(property, EditorGUIUtility.TempContent(Enum.GetNames(type)), Enum.GetValues(type) as int[], label, new GUILayoutOption[0]); + } + private void CacheSerializedProperties() + { + this.m_TextureType = base.serializedObject.FindProperty("m_TextureType"); + this.m_GrayscaleToAlpha = base.serializedObject.FindProperty("m_GrayScaleToAlpha"); + this.m_ConvertToNormalMap = base.serializedObject.FindProperty("m_ConvertToNormalMap"); + this.m_NormalMap = base.serializedObject.FindProperty("m_ExternalNormalMap"); + this.m_HeightScale = base.serializedObject.FindProperty("m_HeightScale"); + this.m_NormalMapFilter = base.serializedObject.FindProperty("m_NormalMapFilter"); + this.m_GenerateCubemap = base.serializedObject.FindProperty("m_GenerateCubemap"); + this.m_SeamlessCubemap = base.serializedObject.FindProperty("m_SeamlessCubemap"); + this.m_BorderMipMap = base.serializedObject.FindProperty("m_BorderMipMap"); + this.m_NPOTScale = base.serializedObject.FindProperty("m_NPOTScale"); + this.m_IsReadable = base.serializedObject.FindProperty("m_IsReadable"); + this.m_LinearTexture = base.serializedObject.FindProperty("m_LinearTexture"); + this.m_EnableMipMap = base.serializedObject.FindProperty("m_EnableMipMap"); + this.m_MipMapMode = base.serializedObject.FindProperty("m_MipMapMode"); + this.m_GenerateMipsInLinearSpace = base.serializedObject.FindProperty("correctGamma"); + this.m_FadeOut = base.serializedObject.FindProperty("m_FadeOut"); + this.m_MipMapFadeDistanceStart = base.serializedObject.FindProperty("m_MipMapFadeDistanceStart"); + this.m_MipMapFadeDistanceEnd = base.serializedObject.FindProperty("m_MipMapFadeDistanceEnd"); + this.m_Lightmap = base.serializedObject.FindProperty("m_Lightmap"); + this.m_Aniso = base.serializedObject.FindProperty("m_TextureSettings.m_Aniso"); + this.m_FilterMode = base.serializedObject.FindProperty("m_TextureSettings.m_FilterMode"); + this.m_WrapMode = base.serializedObject.FindProperty("m_TextureSettings.m_WrapMode"); + this.m_SpriteMode = base.serializedObject.FindProperty("m_SpriteMode"); + this.m_SpritePackingTag = base.serializedObject.FindProperty("m_SpritePackingTag"); + this.m_SpritePixelsToUnits = base.serializedObject.FindProperty("m_SpritePixelsToUnits"); + this.m_SpriteExtrude = base.serializedObject.FindProperty("m_SpriteExtrude"); + this.m_SpriteMeshType = base.serializedObject.FindProperty("m_SpriteMeshType"); + this.m_Alignment = base.serializedObject.FindProperty("m_Alignment"); + this.m_SpritePivot = base.serializedObject.FindProperty("m_SpritePivot"); + this.m_AlphaIsTransparency = base.serializedObject.FindProperty("m_AlphaIsTransparency"); + } + public virtual void OnEnable() + { + this.CacheSerializedProperties(); + this.m_ShowBumpGenerationSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowCookieCubeMapSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowCookieCubeMapSettings.value = (this.textureType == TextureImporterType.Cookie && this.m_GenerateCubemap.intValue != 0); + this.m_ShowBumpGenerationSettings.value = (this.m_ConvertToNormalMap.intValue > 0); + this.m_ShowGenericSpriteSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowManualAtlasGenerationSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowGenericSpriteSettings.value = (this.m_SpriteMode.intValue != 0); + this.m_ShowManualAtlasGenerationSettings.value = (this.m_SpriteMode.intValue == 2); + } + private void SetSerializedPropertySettings(TextureImporterSettings settings) + { + this.m_GrayscaleToAlpha.intValue = ((!settings.grayscaleToAlpha) ? 0 : 1); + this.m_ConvertToNormalMap.intValue = ((!settings.convertToNormalMap) ? 0 : 1); + this.m_NormalMap.intValue = ((!settings.normalMap) ? 0 : 1); + this.m_HeightScale.floatValue = settings.heightmapScale; + this.m_NormalMapFilter.intValue = (int)settings.normalMapFilter; + this.m_GenerateCubemap.intValue = (int)settings.generateCubemap; + this.m_SeamlessCubemap.intValue = ((!settings.seamlessCubemap) ? 0 : 1); + this.m_BorderMipMap.intValue = ((!settings.borderMipmap) ? 0 : 1); + this.m_NPOTScale.intValue = (int)settings.npotScale; + this.m_IsReadable.intValue = ((!settings.readable) ? 0 : 1); + this.m_EnableMipMap.intValue = ((!settings.mipmapEnabled) ? 0 : 1); + this.m_LinearTexture.intValue = ((!settings.linearTexture) ? 0 : 1); + this.m_MipMapMode.intValue = (int)settings.mipmapFilter; + this.m_GenerateMipsInLinearSpace.intValue = ((!settings.generateMipsInLinearSpace) ? 0 : 1); + this.m_FadeOut.intValue = ((!settings.fadeOut) ? 0 : 1); + this.m_MipMapFadeDistanceStart.intValue = settings.mipmapFadeDistanceStart; + this.m_MipMapFadeDistanceEnd.intValue = settings.mipmapFadeDistanceEnd; + this.m_Lightmap.intValue = ((!settings.lightmap) ? 0 : 1); + this.m_SpriteMode.intValue = settings.spriteMode; + this.m_SpritePixelsToUnits.floatValue = settings.spritePixelsPerUnit; + this.m_SpriteExtrude.intValue = (int)settings.spriteExtrude; + this.m_SpriteMeshType.intValue = (int)settings.spriteMeshType; + this.m_Alignment.intValue = settings.spriteAlignment; + this.m_WrapMode.intValue = (int)settings.wrapMode; + this.m_FilterMode.intValue = (int)settings.filterMode; + this.m_Aniso.intValue = settings.aniso; + this.m_AlphaIsTransparency.intValue = ((!settings.alphaIsTransparency) ? 0 : 1); + } + private TextureImporterSettings GetSerializedPropertySettings() + { + return this.GetSerializedPropertySettings(new TextureImporterSettings()); + } + private TextureImporterSettings GetSerializedPropertySettings(TextureImporterSettings settings) + { + if (!this.m_GrayscaleToAlpha.hasMultipleDifferentValues) + { + settings.grayscaleToAlpha = (this.m_GrayscaleToAlpha.intValue > 0); + } + if (!this.m_ConvertToNormalMap.hasMultipleDifferentValues) + { + settings.convertToNormalMap = (this.m_ConvertToNormalMap.intValue > 0); + } + if (!this.m_NormalMap.hasMultipleDifferentValues) + { + settings.normalMap = (this.m_NormalMap.intValue > 0); + } + if (!this.m_HeightScale.hasMultipleDifferentValues) + { + settings.heightmapScale = this.m_HeightScale.floatValue; + } + if (!this.m_NormalMapFilter.hasMultipleDifferentValues) + { + settings.normalMapFilter = (TextureImporterNormalFilter)this.m_NormalMapFilter.intValue; + } + if (!this.m_GenerateCubemap.hasMultipleDifferentValues) + { + settings.generateCubemap = (TextureImporterGenerateCubemap)this.m_GenerateCubemap.intValue; + } + if (!this.m_SeamlessCubemap.hasMultipleDifferentValues) + { + settings.seamlessCubemap = (this.m_SeamlessCubemap.intValue > 0); + } + if (!this.m_BorderMipMap.hasMultipleDifferentValues) + { + settings.borderMipmap = (this.m_BorderMipMap.intValue > 0); + } + if (!this.m_NPOTScale.hasMultipleDifferentValues) + { + settings.npotScale = (TextureImporterNPOTScale)this.m_NPOTScale.intValue; + } + if (!this.m_IsReadable.hasMultipleDifferentValues) + { + settings.readable = (this.m_IsReadable.intValue > 0); + } + if (!this.m_LinearTexture.hasMultipleDifferentValues) + { + settings.linearTexture = (this.m_LinearTexture.intValue > 0); + } + if (!this.m_EnableMipMap.hasMultipleDifferentValues) + { + settings.mipmapEnabled = (this.m_EnableMipMap.intValue > 0); + } + if (!this.m_GenerateMipsInLinearSpace.hasMultipleDifferentValues) + { + settings.generateMipsInLinearSpace = (this.m_GenerateMipsInLinearSpace.intValue > 0); + } + if (!this.m_MipMapMode.hasMultipleDifferentValues) + { + settings.mipmapFilter = (TextureImporterMipFilter)this.m_MipMapMode.intValue; + } + if (!this.m_FadeOut.hasMultipleDifferentValues) + { + settings.fadeOut = (this.m_FadeOut.intValue > 0); + } + if (!this.m_MipMapFadeDistanceStart.hasMultipleDifferentValues) + { + settings.mipmapFadeDistanceStart = this.m_MipMapFadeDistanceStart.intValue; + } + if (!this.m_MipMapFadeDistanceEnd.hasMultipleDifferentValues) + { + settings.mipmapFadeDistanceEnd = this.m_MipMapFadeDistanceEnd.intValue; + } + if (!this.m_Lightmap.hasMultipleDifferentValues) + { + settings.lightmap = (this.m_Lightmap.intValue > 0); + } + if (!this.m_SpriteMode.hasMultipleDifferentValues) + { + settings.spriteMode = this.m_SpriteMode.intValue; + } + if (!this.m_SpritePixelsToUnits.hasMultipleDifferentValues) + { + settings.spritePixelsPerUnit = this.m_SpritePixelsToUnits.floatValue; + } + if (!this.m_SpriteExtrude.hasMultipleDifferentValues) + { + settings.spriteExtrude = (uint)this.m_SpriteExtrude.intValue; + } + if (!this.m_SpriteMeshType.hasMultipleDifferentValues) + { + settings.spriteMeshType = (SpriteMeshType)this.m_SpriteMeshType.intValue; + } + if (!this.m_Alignment.hasMultipleDifferentValues) + { + settings.spriteAlignment = this.m_Alignment.intValue; + } + if (!this.m_SpritePivot.hasMultipleDifferentValues) + { + settings.spritePivot = this.m_SpritePivot.vector2Value; + } + if (!this.m_WrapMode.hasMultipleDifferentValues) + { + settings.wrapMode = (TextureWrapMode)this.m_WrapMode.intValue; + } + if (!this.m_FilterMode.hasMultipleDifferentValues) + { + settings.filterMode = (FilterMode)this.m_FilterMode.intValue; + } + if (!this.m_Aniso.hasMultipleDifferentValues) + { + settings.aniso = this.m_Aniso.intValue; + } + if (!this.m_AlphaIsTransparency.hasMultipleDifferentValues) + { + settings.alphaIsTransparency = (this.m_AlphaIsTransparency.intValue > 0); + } + return settings; + } + public override void OnInspectorGUI() + { + if (TextureImporterInspector.s_Styles == null) + { + TextureImporterInspector.s_Styles = new TextureImporterInspector.Styles(); + } + bool enabled = GUI.enabled; + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.textureTypeHasMultipleDifferentValues; + int intValue = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.textureType, (int)this.textureType, TextureImporterInspector.s_Styles.textureTypeOptions, this.m_TextureTypeValues, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_TextureType.intValue = intValue; + TextureImporterSettings serializedPropertySettings = this.GetSerializedPropertySettings(); + serializedPropertySettings.ApplyTextureType(this.textureType, true); + this.SetSerializedPropertySettings(serializedPropertySettings); + this.SyncPlatformSettings(); + this.ApplySettingsToTexture(); + } + if (!this.textureTypeHasMultipleDifferentValues) + { + switch (this.textureType) + { + case TextureImporterType.Image: + this.ImageGUI(); + break; + case TextureImporterType.Bump: + this.BumpGUI(); + break; + case TextureImporterType.Reflection: + this.ReflectionGUI(); + break; + case TextureImporterType.Cookie: + this.CookieGUI(); + break; + case TextureImporterType.Advanced: + this.AdvancedGUI(); + break; + case TextureImporterType.Sprite: + this.SpriteGUI(); + break; + } + } + EditorGUILayout.Space(); + this.PreviewableGUI(); + this.SizeAndFormatGUI(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + base.ApplyRevertGUI(); + GUILayout.EndHorizontal(); + this.UpdateImportWarning(); + if (this.m_ImportWarning != null) + { + EditorGUILayout.HelpBox(this.m_ImportWarning, MessageType.Warning); + } + GUI.enabled = enabled; + } + private void PreviewableGUI() + { + EditorGUI.BeginChangeCheck(); + if (this.textureType != TextureImporterType.GUI && this.textureType != TextureImporterType.Sprite && this.textureType != TextureImporterType.Reflection && this.textureType != TextureImporterType.Cookie && this.textureType != TextureImporterType.Lightmap) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_WrapMode.hasMultipleDifferentValues; + TextureWrapMode textureWrapMode = (TextureWrapMode)this.m_WrapMode.intValue; + if (textureWrapMode == (TextureWrapMode)(-1)) + { + textureWrapMode = TextureWrapMode.Repeat; + } + textureWrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Wrap Mode"), textureWrapMode, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_WrapMode.intValue = (int)textureWrapMode; + } + if (textureWrapMode == TextureWrapMode.Repeat && !ShaderUtil.hardwareSupportsFullNPOT) + { + bool flag = false; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + int value = -1; + int value2 = -1; + TextureImporter textureImporter = (TextureImporter)@object; + textureImporter.GetWidthAndHeight(ref value, ref value2); + if (!Mathf.IsPowerOfTwo(value) || !Mathf.IsPowerOfTwo(value2)) + { + flag = true; + break; + } + } + if (flag) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("TextureImporter.WrapWarning"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, true); + } + } + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_FilterMode.hasMultipleDifferentValues; + FilterMode filterMode = (FilterMode)this.m_FilterMode.intValue; + if (filterMode == (FilterMode)(-1)) + { + if (this.m_FadeOut.intValue > 0 || this.m_ConvertToNormalMap.intValue > 0 || this.m_NormalMap.intValue > 0) + { + filterMode = FilterMode.Trilinear; + } + else + { + filterMode = FilterMode.Bilinear; + } + } + filterMode = (FilterMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Filter Mode"), filterMode, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_FilterMode.intValue = (int)filterMode; + } + if (filterMode != FilterMode.Point && (this.m_EnableMipMap.intValue > 0 || this.textureType == TextureImporterType.Advanced) && this.textureType != TextureImporterType.Sprite) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_Aniso.hasMultipleDifferentValues; + int num = this.m_Aniso.intValue; + if (num == -1) + { + num = 1; + } + num = EditorGUILayout.IntSlider("Aniso Level", num, 0, 16, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_Aniso.intValue = num; + } + } + if (EditorGUI.EndChangeCheck()) + { + this.ApplySettingsToTexture(); + } + } + private void ApplySettingsToTexture() + { + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + AssetImporter assetImporter = (AssetImporter)targets[i]; + Texture tex = AssetDatabase.LoadMainAssetAtPath(assetImporter.assetPath) as Texture; + if (this.m_Aniso.intValue != -1) + { + TextureUtil.SetAnisoLevelNoDirty(tex, this.m_Aniso.intValue); + } + if (this.m_FilterMode.intValue != -1) + { + TextureUtil.SetFilterModeNoDirty(tex, (FilterMode)this.m_FilterMode.intValue); + } + if (this.m_WrapMode.intValue != -1) + { + TextureUtil.SetWrapModeNoDirty(tex, (TextureWrapMode)this.m_WrapMode.intValue); + } + } + SceneView.RepaintAll(); + } + private static bool CountImportersWithAlpha(UnityEngine.Object[] importers, out int count) + { + bool result; + try + { + count = 0; + for (int i = 0; i < importers.Length; i++) + { + UnityEngine.Object @object = importers[i]; + if ((@object as TextureImporter).DoesSourceTextureHaveAlpha()) + { + count++; + } + } + result = true; + } + catch + { + count = importers.Length; + result = false; + } + return result; + } + private void DoAlphaIsTransparencyGUI() + { + int num; + bool flag = TextureImporterInspector.CountImportersWithAlpha(base.targets, out num); + bool flag2 = this.m_GrayscaleToAlpha.boolValue || num == base.targets.Length; + if (flag2) + { + EditorGUI.BeginDisabledGroup(!flag); + this.ToggleFromInt(this.m_AlphaIsTransparency, TextureImporterInspector.s_Styles.alphaIsTransparency); + EditorGUI.EndDisabledGroup(); + } + } + private void ImageGUI() + { + TextureImporter x = this.target as TextureImporter; + if (x == null) + { + return; + } + this.ToggleFromInt(this.m_GrayscaleToAlpha, TextureImporterInspector.s_Styles.generateAlphaFromGrayscale); + this.DoAlphaIsTransparencyGUI(); + } + private void BumpGUI() + { + this.ToggleFromInt(this.m_ConvertToNormalMap, TextureImporterInspector.s_Styles.generateFromBump); + this.m_ShowBumpGenerationSettings.target = (this.m_ConvertToNormalMap.intValue > 0); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBumpGenerationSettings.faded)) + { + EditorGUILayout.Slider(this.m_HeightScale, 0f, 0.3f, TextureImporterInspector.s_Styles.bumpiness, new GUILayoutOption[0]); + EditorGUILayout.Popup(this.m_NormalMapFilter, TextureImporterInspector.s_Styles.bumpFilteringOptions, TextureImporterInspector.s_Styles.bumpFiltering, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + } + private void SpriteGUI() + { + this.SpriteGUI(true); + } + private void SpriteGUI(bool showMipMapControls) + { + EditorGUI.BeginChangeCheck(); + if (this.textureType == TextureImporterType.Advanced) + { + EditorGUILayout.IntPopup(this.m_SpriteMode, TextureImporterInspector.s_Styles.spriteModeOptionsAdvanced, new int[] + { + 0, + 1, + 2 + }, TextureImporterInspector.s_Styles.spriteMode, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.IntPopup(this.m_SpriteMode, TextureImporterInspector.s_Styles.spriteModeOptions, new int[] + { + 1, + 2 + }, TextureImporterInspector.s_Styles.spriteMode, new GUILayoutOption[0]); + } + if (EditorGUI.EndChangeCheck()) + { + GUIUtility.keyboardControl = 0; + } + EditorGUI.indentLevel++; + this.m_ShowGenericSpriteSettings.target = (this.m_SpriteMode.intValue != 0); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowGenericSpriteSettings.faded)) + { + EditorGUILayout.PropertyField(this.m_SpritePackingTag, TextureImporterInspector.s_Styles.spritePackingTag, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SpritePixelsToUnits, TextureImporterInspector.s_Styles.spritePixelsPerUnit, new GUILayoutOption[0]); + if (this.textureType == TextureImporterType.Advanced && Application.HasAdvancedLicense()) + { + EditorGUILayout.IntPopup(this.m_SpriteMeshType, TextureImporterInspector.s_Styles.spriteMeshTypeOptions, new int[] + { + 0, + 1 + }, TextureImporterInspector.s_Styles.spriteMeshType, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_SpriteExtrude, 0, 32, TextureImporterInspector.s_Styles.spriteExtrude, new GUILayoutOption[0]); + } + if (this.m_SpriteMode.intValue == 1) + { + EditorGUILayout.Popup(this.m_Alignment, TextureImporterInspector.s_Styles.spriteAlignmentOptions, TextureImporterInspector.s_Styles.spriteAlignment, new GUILayoutOption[0]); + if (this.m_Alignment.intValue == 9) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SpritePivot, this.m_EmptyContent, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + } + EditorGUI.BeginDisabledGroup(base.targets.Length != 1); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Sprite Editor", new GUILayoutOption[0])) + { + bool flag = (this.target as TextureImporter).spriteImportMode != (SpriteImportMode)this.m_SpriteMode.intValue; + if (flag) + { + base.ApplyAndImport(); + } + SpriteEditorWindow.GetWindow(); + GUIUtility.ExitGUI(); + } + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + if (showMipMapControls) + { + this.ToggleFromInt(this.m_EnableMipMap, TextureImporterInspector.s_Styles.generateMipMaps); + } + } + private void ReflectionGUI() + { + this.ReflectionMappingGUI(); + } + private void ReflectionMappingGUI() + { + EditorGUI.showMixedValue = (this.m_GenerateCubemap.hasMultipleDifferentValues || this.m_SeamlessCubemap.hasMultipleDifferentValues); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUILayout.Popup(TextureImporterInspector.s_Styles.refMap, this.m_GenerateCubemap.intValue - 1, TextureImporterInspector.s_Styles.refMapOptions, new GUILayoutOption[0]) + 1; + if (EditorGUI.EndChangeCheck()) + { + this.m_GenerateCubemap.intValue = intValue; + } + this.ToggleFromInt(this.m_SeamlessCubemap, TextureImporterInspector.s_Styles.seamlessCubemap); + EditorGUI.showMixedValue = false; + } + private void CookieGUI() + { + EditorGUI.BeginChangeCheck(); + TextureImporterInspector.CookieMode cookieMode; + if (this.m_BorderMipMap.intValue > 0) + { + cookieMode = TextureImporterInspector.CookieMode.Spot; + } + else + { + if (this.m_GenerateCubemap.intValue != 0) + { + cookieMode = TextureImporterInspector.CookieMode.Point; + } + else + { + cookieMode = TextureImporterInspector.CookieMode.Directional; + } + } + cookieMode = (TextureImporterInspector.CookieMode)EditorGUILayout.Popup(TextureImporterInspector.s_Styles.cookieType, (int)cookieMode, TextureImporterInspector.s_Styles.cookieOptions, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.SetCookieMode(cookieMode); + } + this.m_ShowCookieCubeMapSettings.target = (cookieMode == TextureImporterInspector.CookieMode.Point); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowCookieCubeMapSettings.faded)) + { + this.ReflectionMappingGUI(); + } + EditorGUILayout.EndFadeGroup(); + this.ToggleFromInt(this.m_GrayscaleToAlpha, TextureImporterInspector.s_Styles.generateAlphaFromGrayscale); + } + private void SetCookieMode(TextureImporterInspector.CookieMode cm) + { + switch (cm) + { + case TextureImporterInspector.CookieMode.Spot: + this.m_BorderMipMap.intValue = 1; + this.m_WrapMode.intValue = 1; + this.m_GenerateCubemap.intValue = 0; + break; + case TextureImporterInspector.CookieMode.Directional: + this.m_BorderMipMap.intValue = 0; + this.m_WrapMode.intValue = 0; + this.m_GenerateCubemap.intValue = 0; + break; + case TextureImporterInspector.CookieMode.Point: + this.m_BorderMipMap.intValue = 0; + this.m_WrapMode.intValue = 1; + this.m_GenerateCubemap.intValue = 3; + break; + } + } + private void BeginToggleGroup(SerializedProperty property, GUIContent label) + { + EditorGUI.showMixedValue = property.hasMultipleDifferentValues; + EditorGUI.BeginChangeCheck(); + int intValue = (!EditorGUILayout.BeginToggleGroup(label, property.intValue > 0)) ? 0 : 1; + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + EditorGUI.showMixedValue = false; + } + private void AdvancedGUI() + { + TextureImporter textureImporter = this.target as TextureImporter; + if (textureImporter == null) + { + return; + } + int f = 0; + int f2 = 0; + textureImporter.GetWidthAndHeight(ref f2, ref f); + bool flag = TextureImporterInspector.IsPowerOfTwo(f) && TextureImporterInspector.IsPowerOfTwo(f2); + EditorGUI.BeginDisabledGroup(flag); + this.EnumPopup(this.m_NPOTScale, typeof(TextureImporterNPOTScale), TextureImporterInspector.s_Styles.npot); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(!flag && this.m_NPOTScale.intValue == 0); + this.EnumPopup(this.m_GenerateCubemap, typeof(TextureImporterGenerateCubemap), TextureImporterInspector.s_Styles.generateCubemap); + EditorGUI.EndDisabledGroup(); + this.ToggleFromInt(this.m_IsReadable, TextureImporterInspector.s_Styles.readWrite); + TextureImporterInspector.AdvancedTextureType advancedTextureType = TextureImporterInspector.AdvancedTextureType.Default; + if (this.m_NormalMap.intValue > 0) + { + advancedTextureType = TextureImporterInspector.AdvancedTextureType.NormalMap; + } + else + { + if (this.m_Lightmap.intValue > 0) + { + advancedTextureType = TextureImporterInspector.AdvancedTextureType.LightMap; + } + } + EditorGUI.BeginChangeCheck(); + advancedTextureType = (TextureImporterInspector.AdvancedTextureType)EditorGUILayout.Popup("Import Type", (int)advancedTextureType, new string[] + { + "Default", + "Normal Map", + "Lightmap" + }, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + switch (advancedTextureType) + { + case TextureImporterInspector.AdvancedTextureType.Default: + this.m_NormalMap.intValue = 0; + this.m_Lightmap.intValue = 0; + this.m_ConvertToNormalMap.intValue = 0; + break; + case TextureImporterInspector.AdvancedTextureType.NormalMap: + this.m_NormalMap.intValue = 1; + this.m_Lightmap.intValue = 0; + this.m_LinearTexture.intValue = 1; + break; + case TextureImporterInspector.AdvancedTextureType.LightMap: + this.m_NormalMap.intValue = 0; + this.m_Lightmap.intValue = 1; + this.m_ConvertToNormalMap.intValue = 0; + this.m_LinearTexture.intValue = 1; + break; + } + } + EditorGUI.indentLevel++; + if (advancedTextureType == TextureImporterInspector.AdvancedTextureType.NormalMap) + { + EditorGUI.BeginChangeCheck(); + this.BumpGUI(); + if (EditorGUI.EndChangeCheck()) + { + this.SyncPlatformSettings(); + } + } + else + { + if (advancedTextureType == TextureImporterInspector.AdvancedTextureType.Default) + { + this.ToggleFromInt(this.m_GrayscaleToAlpha, TextureImporterInspector.s_Styles.generateAlphaFromGrayscale); + this.DoAlphaIsTransparencyGUI(); + this.ToggleFromInt(this.m_LinearTexture, TextureImporterInspector.s_Styles.linearTexture); + this.SpriteGUI(false); + } + } + EditorGUI.indentLevel--; + this.ToggleFromInt(this.m_EnableMipMap, TextureImporterInspector.s_Styles.generateMipMaps); + if (this.m_EnableMipMap.boolValue && !this.m_EnableMipMap.hasMultipleDifferentValues) + { + EditorGUI.indentLevel++; + this.ToggleFromInt(this.m_GenerateMipsInLinearSpace, TextureImporterInspector.s_Styles.mipMapsInLinearSpace); + this.ToggleFromInt(this.m_BorderMipMap, TextureImporterInspector.s_Styles.borderMipMaps); + EditorGUILayout.Popup(this.m_MipMapMode, TextureImporterInspector.s_Styles.mipMapFilterOptions, TextureImporterInspector.s_Styles.mipMapFilter, new GUILayoutOption[0]); + this.ToggleFromInt(this.m_FadeOut, TextureImporterInspector.s_Styles.mipmapFadeOutToggle); + if (this.m_FadeOut.intValue > 0) + { + EditorGUI.indentLevel++; + EditorGUI.BeginChangeCheck(); + float f3 = (float)this.m_MipMapFadeDistanceStart.intValue; + float f4 = (float)this.m_MipMapFadeDistanceEnd.intValue; + EditorGUILayout.MinMaxSlider(TextureImporterInspector.s_Styles.mipmapFadeOut, ref f3, ref f4, 0f, 10f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_MipMapFadeDistanceStart.intValue = Mathf.RoundToInt(f3); + this.m_MipMapFadeDistanceEnd.intValue = Mathf.RoundToInt(f4); + } + EditorGUI.indentLevel--; + } + EditorGUI.indentLevel--; + } + } + private void SyncPlatformSettings() + { + foreach (TextureImporterInspector.PlatformSetting current in this.m_PlatformSettings) + { + current.Sync(); + } + } + private static string[] BuildTextureStrings(int[] texFormatValues) + { + string[] array = new string[texFormatValues.Length]; + for (int i = 0; i < texFormatValues.Length; i++) + { + int num = texFormatValues[i]; + int num2 = num; + switch (num2 + 3) + { + case 0: + array[i] = "Automatic Truecolor"; + break; + case 1: + array[i] = "Automatic 16 bits"; + break; + case 2: + array[i] = "Automatic Compressed"; + break; + default: + array[i] = " " + TextureUtil.GetTextureFormatString((TextureFormat)num); + break; + } + } + return array; + } + private static TextureImporterFormat MakeTextureFormatHaveAlpha(TextureImporterFormat format) + { + switch (format) + { + case TextureImporterFormat.RGB16: + return TextureImporterFormat.ARGB16; + case (TextureImporterFormat)8: + case (TextureImporterFormat)9: + IL_1A: + switch (format) + { + case TextureImporterFormat.PVRTC_RGB2: + return TextureImporterFormat.PVRTC_RGBA2; + case TextureImporterFormat.PVRTC_RGBA2: + IL_2F: + if (format != TextureImporterFormat.RGB24) + { + return format; + } + return TextureImporterFormat.ARGB32; + case TextureImporterFormat.PVRTC_RGB4: + return TextureImporterFormat.PVRTC_RGBA4; + } + goto IL_2F; + case TextureImporterFormat.DXT1: + return TextureImporterFormat.DXT5; + } + goto IL_1A; + } + protected void SizeAndFormatGUI() + { + BuildPlayerWindow.BuildPlatform[] platforms = TextureImporterInspector.GetBuildPlayerValidPlatforms().ToArray(); + GUILayout.Space(10f); + int num = EditorGUILayout.BeginPlatformGrouping(platforms, TextureImporterInspector.s_Styles.defaultPlatform); + TextureImporterInspector.PlatformSetting platformSetting = this.m_PlatformSettings[num + 1]; + if (!platformSetting.isDefault) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = platformSetting.overriddenIsDifferent; + bool overriddenForAll = GUILayout.Toggle(platformSetting.overridden, "Override for " + platformSetting.name, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + platformSetting.SetOverriddenForAll(overriddenForAll); + this.SyncPlatformSettings(); + } + } + bool disabled = !platformSetting.isDefault && !platformSetting.allAreOverridden; + EditorGUI.BeginDisabledGroup(disabled); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = (platformSetting.overriddenIsDifferent || platformSetting.maxTextureSizeIsDifferent); + int maxTextureSizeForAll = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.maxSize.text, platformSetting.maxTextureSize, TextureImporterInspector.kMaxTextureSizeStrings, TextureImporterInspector.kMaxTextureSizeValues, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + platformSetting.SetMaxTextureSizeForAll(maxTextureSizeForAll); + this.SyncPlatformSettings(); + } + int[] array = null; + string[] array2 = null; + bool flag = false; + int num2 = 0; + bool flag2 = false; + int num3 = 0; + bool flag3 = false; + for (int i = 0; i < base.targets.Length; i++) + { + TextureImporter textureImporter = base.targets[i] as TextureImporter; + TextureImporterType textureImporterType = (!this.textureTypeHasMultipleDifferentValues) ? this.textureType : textureImporter.textureType; + TextureImporterSettings settings = platformSetting.GetSettings(textureImporter); + int num4 = (int)platformSetting.textureFormats[i]; + int num5 = num4; + if (!platformSetting.isDefault && num4 < 0) + { + num5 = (int)TextureImporter.SimpleToFullTextureFormat2((TextureImporterFormat)num5, textureImporterType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.DoesSourceTextureHaveColor(), platformSetting.m_Target); + } + if (settings.normalMap && !TextureImporterInspector.IsGLESMobileTargetPlatform(platformSetting.m_Target)) + { + num5 = (int)TextureImporterInspector.MakeTextureFormatHaveAlpha((TextureImporterFormat)num5); + } + TextureImporterType textureImporterType2 = textureImporterType; + int[] array3; + string[] array4; + if (textureImporterType2 != TextureImporterType.Cookie) + { + if (textureImporterType2 != TextureImporterType.Advanced) + { + array3 = this.m_TextureFormatValues; + array4 = TextureImporterInspector.s_Styles.textureFormatOptions; + if (num4 >= 0) + { + num4 = (int)TextureImporter.FullToSimpleTextureFormat((TextureImporterFormat)num4); + } + num4 = -1 - num4; + } + else + { + num4 = num5; + if (TextureImporterInspector.IsGLESMobileTargetPlatform(platformSetting.m_Target)) + { + if (TextureImporterInspector.s_TextureFormatStringsiPhone == null) + { + TextureImporterInspector.s_TextureFormatStringsiPhone = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueiPhone); + } + if (TextureImporterInspector.s_TextureFormatStringsAndroid == null) + { + TextureImporterInspector.s_TextureFormatStringsAndroid = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueAndroid); + } + if (platformSetting.m_Target == BuildTarget.iPhone) + { + array3 = TextureImporterInspector.kTextureFormatsValueiPhone; + array4 = TextureImporterInspector.s_TextureFormatStringsiPhone; + } + else + { + array3 = TextureImporterInspector.kTextureFormatsValueAndroid; + array4 = TextureImporterInspector.s_TextureFormatStringsAndroid; + } + } + else + { + if (!settings.normalMap) + { + if (TextureImporterInspector.s_TextureFormatStringsAll == null) + { + TextureImporterInspector.s_TextureFormatStringsAll = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.TextureFormatsValueAll); + } + if (TextureImporterInspector.s_TextureFormatStringsFlash == null) + { + TextureImporterInspector.s_TextureFormatStringsFlash = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueFlash); + } + if (TextureImporterInspector.s_TextureFormatStringsGLESEmu == null) + { + TextureImporterInspector.s_TextureFormatStringsGLESEmu = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueGLESEmu); + } + if (TextureImporterInspector.s_TextureFormatStringsWeb == null) + { + TextureImporterInspector.s_TextureFormatStringsWeb = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueWeb); + } + if (platformSetting.isDefault) + { + array3 = TextureImporterInspector.TextureFormatsValueAll; + array4 = TextureImporterInspector.s_TextureFormatStringsAll; + } + else + { + if (platformSetting.m_Target == BuildTarget.StandaloneGLESEmu) + { + array3 = TextureImporterInspector.kTextureFormatsValueGLESEmu; + array4 = TextureImporterInspector.s_TextureFormatStringsGLESEmu; + } + else + { + if (platformSetting.m_Target == BuildTarget.FlashPlayer) + { + array3 = TextureImporterInspector.kTextureFormatsValueFlash; + array4 = TextureImporterInspector.s_TextureFormatStringsFlash; + } + else + { + array3 = TextureImporterInspector.kTextureFormatsValueWeb; + array4 = TextureImporterInspector.s_TextureFormatStringsWeb; + } + } + } + } + else + { + if (TextureImporterInspector.s_NormalFormatStringsAll == null) + { + TextureImporterInspector.s_NormalFormatStringsAll = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.NormalFormatsValueAll); + } + if (TextureImporterInspector.s_NormalFormatStringsFlash == null) + { + TextureImporterInspector.s_NormalFormatStringsFlash = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kNormalFormatsValueFlash); + } + if (TextureImporterInspector.s_NormalFormatStringsWeb == null) + { + TextureImporterInspector.s_NormalFormatStringsWeb = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kNormalFormatsValueWeb); + } + if (platformSetting.isDefault) + { + array3 = TextureImporterInspector.NormalFormatsValueAll; + array4 = TextureImporterInspector.s_NormalFormatStringsAll; + } + else + { + if (platformSetting.m_Target == BuildTarget.FlashPlayer) + { + array3 = TextureImporterInspector.kNormalFormatsValueFlash; + array4 = TextureImporterInspector.s_NormalFormatStringsFlash; + } + else + { + array3 = TextureImporterInspector.kNormalFormatsValueWeb; + array4 = TextureImporterInspector.s_NormalFormatStringsWeb; + } + } + } + } + } + } + else + { + array3 = new int[1]; + array4 = new string[] + { + "8 Bit Alpha" + }; + num4 = 0; + } + if (i == 0) + { + array = array3; + array2 = array4; + num2 = num4; + num3 = num5; + } + else + { + if (num4 != num2) + { + flag2 = true; + } + if (num5 != num3) + { + flag3 = true; + } + if (!array3.SequenceEqual(array) || !array4.SequenceEqual(array2)) + { + flag = true; + break; + } + } + } + EditorGUI.BeginDisabledGroup(flag || array2.Length == 1); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = (flag || flag2); + num2 = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.textureFormat, num2, EditorGUIUtility.TempContent(array2), array, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + if (this.textureType != TextureImporterType.Advanced) + { + num2 = -1 - num2; + } + platformSetting.SetTextureFormatForAll((TextureImporterFormat)num2); + this.SyncPlatformSettings(); + } + EditorGUI.EndDisabledGroup(); + if (!flag3 && ArrayUtility.Contains(TextureImporterInspector.kFormatsWithCompressionSettings, (TextureImporterFormat)num3)) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = (platformSetting.overriddenIsDifferent || platformSetting.compressionQualityIsDifferent); + int compressionQualityForAll = this.EditCompressionQuality(platformSetting.m_Target, platformSetting.compressionQuality); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + platformSetting.SetCompressionQualityForAll(compressionQualityForAll); + this.SyncPlatformSettings(); + } + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndPlatformGrouping(); + } + private int EditCompressionQuality(BuildTarget target, int compression) + { + if (target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.BB10 || target == BuildTarget.Tizen) + { + int selectedIndex = 1; + if (compression == 0) + { + selectedIndex = 0; + } + else + { + if (compression == 100) + { + selectedIndex = 2; + } + } + switch (EditorGUILayout.Popup(TextureImporterInspector.s_Styles.compressionQuality, selectedIndex, TextureImporterInspector.s_Styles.mobileCompressionQualityOptions, new GUILayoutOption[0])) + { + case 0: + return 0; + case 1: + return 50; + case 2: + return 100; + default: + return 50; + } + } + else + { + if (target == BuildTarget.FlashPlayer) + { + return EditorGUILayout.IntSlider(TextureImporterInspector.s_Styles.compressionQuality, compression, 0, 100, new GUILayoutOption[0]); + } + return compression; + } + } + private static bool IsPowerOfTwo(int f) + { + return (f & f - 1) == 0; + } + public static BuildPlayerWindow.BuildPlatform[] GetBuildPlayerValidPlatforms() + { + List validPlatforms = BuildPlayerWindow.GetValidPlatforms(); + List list = new List(); + foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) + { + if (current.targetGroup != BuildTargetGroup.NaCl) + { + list.Add(current); + } + } + return list.ToArray(); + } + public virtual void BuildTargetList() + { + BuildPlayerWindow.BuildPlatform[] buildPlayerValidPlatforms = TextureImporterInspector.GetBuildPlayerValidPlatforms(); + this.m_PlatformSettings = new List(); + this.m_PlatformSettings.Add(new TextureImporterInspector.PlatformSetting(string.Empty, BuildTarget.StandaloneWindows, this)); + BuildPlayerWindow.BuildPlatform[] array = buildPlayerValidPlatforms; + for (int i = 0; i < array.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array[i]; + this.m_PlatformSettings.Add(new TextureImporterInspector.PlatformSetting(buildPlatform.name, buildPlatform.DefaultTarget, this)); + } + } + internal override bool HasModified() + { + if (base.HasModified()) + { + return true; + } + foreach (TextureImporterInspector.PlatformSetting current in this.m_PlatformSettings) + { + if (current.HasChanged()) + { + return true; + } + } + return false; + } + internal override void ResetValues() + { + base.ResetValues(); + this.CacheSerializedProperties(); + this.BuildTargetList(); + Assert.IsFalse(this.HasModified(), "TextureImporter settings are marked as modified after calling Reset."); + this.ApplySettingsToTexture(); + } + internal override void Apply() + { + base.Apply(); + this.SyncPlatformSettings(); + foreach (TextureImporterInspector.PlatformSetting current in this.m_PlatformSettings) + { + current.Apply(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterMipFilter.cs b/UnityEditor/UnityEditor/TextureImporterMipFilter.cs new file mode 100644 index 00000000..0694f5b4 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterMipFilter.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterMipFilter + { + BoxFilter, + KaiserFilter + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterNPOTScale.cs b/UnityEditor/UnityEditor/TextureImporterNPOTScale.cs new file mode 100644 index 00000000..0e82afa3 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterNPOTScale.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterNPOTScale + { + None, + ToNearest, + ToLarger, + ToSmaller + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterNormalFilter.cs b/UnityEditor/UnityEditor/TextureImporterNormalFilter.cs new file mode 100644 index 00000000..2a42ed9c --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterNormalFilter.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterNormalFilter + { + Standard, + Sobel + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterSettings.cs b/UnityEditor/UnityEditor/TextureImporterSettings.cs new file mode 100644 index 00000000..fdf635a3 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterSettings.cs @@ -0,0 +1,466 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + public sealed class TextureImporterSettings + { + [SerializeField] + private int m_MipMapMode; + [SerializeField] + private int m_EnableMipMap; + [SerializeField] + private int m_GenerateMipsInLinearSpace; + [SerializeField] + private int m_FadeOut; + [SerializeField] + private int m_BorderMipMap; + [SerializeField] + private int m_MipMapFadeDistanceStart; + [SerializeField] + private int m_MipMapFadeDistanceEnd; + [SerializeField] + private int m_ConvertToNormalMap; + [SerializeField] + private int m_NormalMap; + [SerializeField] + private float m_HeightScale; + [SerializeField] + private int m_NormalMapFilter; + [SerializeField] + private int m_GrayScaleToAlpha; + [SerializeField] + private int m_IsReadable; + [SerializeField] + private int m_TextureFormat; + [SerializeField] + private int m_RecommendedTextureFormat; + [SerializeField] + private int m_MaxTextureSize; + [SerializeField] + private int m_NPOTScale; + [SerializeField] + private int m_Lightmap; + [SerializeField] + private int m_LinearTexture; + [SerializeField] + private int m_CompressionQuality; + [SerializeField] + private int m_SpriteMode; + [SerializeField] + private uint m_SpriteExtrude; + [SerializeField] + private int m_SpriteMeshType; + [SerializeField] + private int m_Alignment; + [SerializeField] + private Vector2 m_SpritePivot; + [SerializeField] + private float m_SpritePixelsToUnits; + [SerializeField] + private Vector4 m_SpriteBorder; + [SerializeField] + private int m_GenerateCubemap; + [SerializeField] + private int m_SeamlessCubemap; + [SerializeField] + private int m_AlphaIsTransparency; + [SerializeField] + private int m_FilterMode; + [SerializeField] + private int m_Aniso; + [SerializeField] + private float m_MipBias; + [SerializeField] + private int m_WrapMode; + public TextureImporterMipFilter mipmapFilter + { + get + { + return (TextureImporterMipFilter)this.m_MipMapMode; + } + set + { + this.m_MipMapMode = (int)value; + } + } + public bool mipmapEnabled + { + get + { + return this.m_EnableMipMap != 0; + } + set + { + this.m_EnableMipMap = ((!value) ? 0 : 1); + } + } + public bool generateMipsInLinearSpace + { + get + { + return this.m_GenerateMipsInLinearSpace != 0; + } + set + { + this.m_GenerateMipsInLinearSpace = ((!value) ? 0 : 1); + } + } + public bool linearTexture + { + get + { + return this.m_LinearTexture != 0; + } + set + { + this.m_LinearTexture = ((!value) ? 0 : 1); + } + } + public bool fadeOut + { + get + { + return this.m_FadeOut != 0; + } + set + { + this.m_FadeOut = ((!value) ? 0 : 1); + } + } + public bool borderMipmap + { + get + { + return this.m_BorderMipMap != 0; + } + set + { + this.m_BorderMipMap = ((!value) ? 0 : 1); + } + } + public int mipmapFadeDistanceStart + { + get + { + return this.m_MipMapFadeDistanceStart; + } + set + { + this.m_MipMapFadeDistanceStart = value; + } + } + public int mipmapFadeDistanceEnd + { + get + { + return this.m_MipMapFadeDistanceEnd; + } + set + { + this.m_MipMapFadeDistanceEnd = value; + } + } + public bool convertToNormalMap + { + get + { + return this.m_ConvertToNormalMap != 0; + } + set + { + this.m_ConvertToNormalMap = ((!value) ? 0 : 1); + } + } + public bool normalMap + { + get + { + return this.m_NormalMap != 0; + } + set + { + this.m_NormalMap = ((!value) ? 0 : 1); + } + } + public float heightmapScale + { + get + { + return this.m_HeightScale; + } + set + { + this.m_HeightScale = value; + } + } + public TextureImporterNormalFilter normalMapFilter + { + get + { + return (TextureImporterNormalFilter)this.m_NormalMapFilter; + } + set + { + this.m_NormalMapFilter = (int)value; + } + } + public bool grayscaleToAlpha + { + get + { + return this.m_GrayScaleToAlpha != 0; + } + set + { + this.m_GrayScaleToAlpha = ((!value) ? 0 : 1); + } + } + public bool readable + { + get + { + return this.m_IsReadable != 0; + } + set + { + this.m_IsReadable = ((!value) ? 0 : 1); + } + } + public TextureImporterFormat textureFormat + { + get + { + return (TextureImporterFormat)this.m_TextureFormat; + } + set + { + this.m_TextureFormat = (int)value; + } + } + public int maxTextureSize + { + get + { + return this.m_MaxTextureSize; + } + set + { + this.m_MaxTextureSize = value; + } + } + public TextureImporterNPOTScale npotScale + { + get + { + return (TextureImporterNPOTScale)this.m_NPOTScale; + } + set + { + this.m_NPOTScale = (int)value; + } + } + public bool lightmap + { + get + { + return this.m_Lightmap != 0; + } + set + { + this.m_Lightmap = ((!value) ? 0 : 1); + } + } + public TextureImporterGenerateCubemap generateCubemap + { + get + { + return (TextureImporterGenerateCubemap)this.m_GenerateCubemap; + } + set + { + this.m_GenerateCubemap = (int)value; + } + } + public bool seamlessCubemap + { + get + { + return this.m_SeamlessCubemap != 0; + } + set + { + this.m_SeamlessCubemap = ((!value) ? 0 : 1); + } + } + public FilterMode filterMode + { + get + { + return (FilterMode)this.m_FilterMode; + } + set + { + this.m_FilterMode = (int)value; + } + } + public int aniso + { + get + { + return this.m_Aniso; + } + set + { + this.m_Aniso = value; + } + } + public float mipmapBias + { + get + { + return this.m_MipBias; + } + set + { + this.m_MipBias = value; + } + } + public TextureWrapMode wrapMode + { + get + { + return (TextureWrapMode)this.m_WrapMode; + } + set + { + this.m_WrapMode = (int)value; + } + } + public int compressionQuality + { + get + { + return this.m_CompressionQuality; + } + set + { + this.m_CompressionQuality = value; + } + } + public bool alphaIsTransparency + { + get + { + return this.m_AlphaIsTransparency != 0; + } + set + { + this.m_AlphaIsTransparency = ((!value) ? 0 : 1); + } + } + public int spriteMode + { + get + { + return this.m_SpriteMode; + } + set + { + this.m_SpriteMode = value; + } + } + public float spritePixelsPerUnit + { + get + { + return this.m_SpritePixelsToUnits; + } + set + { + this.m_SpritePixelsToUnits = value; + } + } + [Obsolete("Use spritePixelsPerUnit property instead.")] + public float spritePixelsToUnits + { + get + { + return this.m_SpritePixelsToUnits; + } + set + { + this.m_SpritePixelsToUnits = value; + } + } + public uint spriteExtrude + { + get + { + return this.m_SpriteExtrude; + } + set + { + this.m_SpriteExtrude = value; + } + } + public SpriteMeshType spriteMeshType + { + get + { + return (SpriteMeshType)this.m_SpriteMeshType; + } + set + { + this.m_SpriteMeshType = (int)value; + } + } + public int spriteAlignment + { + get + { + return this.m_Alignment; + } + set + { + this.m_Alignment = value; + } + } + public Vector2 spritePivot + { + get + { + return this.m_SpritePivot; + } + set + { + this.m_SpritePivot = value; + } + } + public Vector4 spriteBorder + { + get + { + return this.m_SpriteBorder; + } + set + { + this.m_SpriteBorder = value; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Equal(TextureImporterSettings a, TextureImporterSettings b); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CopyTo(TextureImporterSettings target); + public void ApplyTextureType(TextureImporterType type, bool applyAll) + { + TextureImporterSettings.Internal_ApplyTextureType(this, type, applyAll); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_ApplyTextureType(TextureImporterSettings s, TextureImporterType type, bool applyAll); + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterType.cs b/UnityEditor/UnityEditor/TextureImporterType.cs new file mode 100644 index 00000000..234f1f8c --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterType.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterType + { + Image, + Bump, + GUI, + Sprite = 8, + Cursor = 7, + Reflection = 3, + Cookie, + Lightmap = 6, + Advanced = 5 + } +} diff --git a/UnityEditor/UnityEditor/TextureInspector.cs b/UnityEditor/UnityEditor/TextureInspector.cs new file mode 100644 index 00000000..3ed0b031 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureInspector.cs @@ -0,0 +1,374 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Texture2D))] + internal class TextureInspector : Editor + { + private static GUIContent s_SmallZoom; + private static GUIContent s_LargeZoom; + private static GUIContent s_AlphaIcon; + private static GUIContent s_RGBIcon; + private static GUIStyle s_PreButton; + private static GUIStyle s_PreSlider; + private static GUIStyle s_PreSliderThumb; + private static GUIStyle s_PreLabel; + private bool m_bShowAlpha; + private SerializedProperty m_WrapMode; + private SerializedProperty m_FilterMode; + private SerializedProperty m_Aniso; + [SerializeField] + protected Vector2 m_Pos; + [SerializeField] + private float m_MipLevel; + public static bool IsNormalMap(Texture t) + { + TextureUsageMode usageMode = TextureUtil.GetUsageMode(t); + return usageMode == TextureUsageMode.NormalmapPlain || usageMode == TextureUsageMode.NormalmapDXT5nm; + } + protected virtual void OnEnable() + { + float realtimeSinceStartup = Time.realtimeSinceStartup; + if (Time.realtimeSinceStartup - realtimeSinceStartup > 1f) + { + Debug.LogWarning("Took " + (Time.realtimeSinceStartup - realtimeSinceStartup) + " seconds to create SerializedObject!"); + } + this.m_WrapMode = base.serializedObject.FindProperty("m_TextureSettings.m_WrapMode"); + this.m_FilterMode = base.serializedObject.FindProperty("m_TextureSettings.m_FilterMode"); + this.m_Aniso = base.serializedObject.FindProperty("m_TextureSettings.m_Aniso"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_WrapMode.hasMultipleDifferentValues; + TextureWrapMode textureWrapMode = (TextureWrapMode)this.m_WrapMode.intValue; + textureWrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Wrap Mode"), textureWrapMode, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_WrapMode.intValue = (int)textureWrapMode; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_FilterMode.hasMultipleDifferentValues; + FilterMode filterMode = (FilterMode)this.m_FilterMode.intValue; + filterMode = (FilterMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Filter Mode"), filterMode, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_FilterMode.intValue = (int)filterMode; + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = this.m_Aniso.hasMultipleDifferentValues; + int num = this.m_Aniso.intValue; + num = EditorGUILayout.IntSlider("Aniso Level", num, 0, 16, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + this.m_Aniso.intValue = num; + } + base.serializedObject.ApplyModifiedProperties(); + } + private static void Init() + { + TextureInspector.s_SmallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); + TextureInspector.s_LargeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); + TextureInspector.s_AlphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); + TextureInspector.s_RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); + TextureInspector.s_PreButton = "preButton"; + TextureInspector.s_PreSlider = "preSlider"; + TextureInspector.s_PreSliderThumb = "preSliderThumb"; + TextureInspector.s_PreLabel = "preLabel"; + } + public override void OnPreviewSettings() + { + TextureInspector.Init(); + Texture t = this.target as Texture; + bool flag = true; + bool flag2 = false; + bool flag3 = true; + int num = 1; + if (this.target is Texture2D || this.target is ProceduralTexture) + { + flag2 = true; + flag3 = false; + } + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + Texture texture = (Texture)targets[i]; + TextureFormat format = (TextureFormat)0; + bool flag4 = false; + if (texture is Texture2D) + { + format = (texture as Texture2D).format; + flag4 = true; + } + else + { + if (texture is ProceduralTexture) + { + format = (texture as ProceduralTexture).format; + flag4 = true; + } + } + if (flag4) + { + num = Mathf.Max(num, TextureUtil.CountMipmaps(texture)); + if (!TextureUtil.IsAlphaOnlyTextureFormat(format)) + { + flag2 = false; + } + if (TextureUtil.HasAlphaTextureFormat(format)) + { + flag3 = true; + } + } + } + if (flag2) + { + this.m_bShowAlpha = true; + flag = false; + } + else + { + if (!flag3) + { + this.m_bShowAlpha = false; + flag = false; + } + } + if (flag && !TextureInspector.IsNormalMap(t)) + { + this.m_bShowAlpha = GUILayout.Toggle(this.m_bShowAlpha, (!this.m_bShowAlpha) ? TextureInspector.s_RGBIcon : TextureInspector.s_AlphaIcon, TextureInspector.s_PreButton, new GUILayoutOption[0]); + } + GUI.enabled = (num != 1); + GUILayout.Box(TextureInspector.s_SmallZoom, TextureInspector.s_PreLabel, new GUILayoutOption[0]); + GUI.changed = false; + this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, TextureInspector.s_PreSlider, TextureInspector.s_PreSliderThumb, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + })); + GUILayout.Box(TextureInspector.s_LargeZoom, TextureInspector.s_PreLabel, new GUILayoutOption[0]); + GUI.enabled = true; + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type == EventType.Repaint) + { + background.Draw(r, false, false, false, false); + } + Texture texture = this.target as Texture; + RenderTexture renderTexture = texture as RenderTexture; + if (renderTexture != null && !renderTexture.IsCreated()) + { + renderTexture.Create(); + } + int num = Mathf.Max(texture.width, 1); + int num2 = Mathf.Max(texture.height, 1); + float num3 = (!(texture is Texture2D) && !(texture is ProceduralTexture)) ? 0f : Mathf.Min(this.m_MipLevel, (float)(TextureUtil.CountMipmaps(texture) - 1)); + float num4 = Mathf.Min(Mathf.Min(r.width / (float)num, r.height / (float)num2), 1f); + Rect rect = new Rect(r.x, r.y, (float)num * num4, (float)num2 * num4); + PreviewGUI.BeginScrollView(r, this.m_Pos, rect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); + float mipMapBias = texture.mipMapBias; + TextureUtil.SetMipMapBiasNoDirty(texture, num3 - this.Log2((float)num / rect.width)); + FilterMode filterMode = texture.filterMode; + TextureUtil.SetFilterModeNoDirty(texture, FilterMode.Point); + if (this.m_bShowAlpha) + { + EditorGUI.DrawTextureAlpha(rect, texture); + } + else + { + Texture2D texture2D = texture as Texture2D; + if (texture2D != null && texture2D.alphaIsTransparency) + { + EditorGUI.DrawTextureTransparent(rect, texture); + } + else + { + EditorGUI.DrawPreviewTexture(rect, texture); + } + } + if (rect.width > 32f && rect.height > 32f) + { + string assetPath = AssetDatabase.GetAssetPath(texture); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + SpriteMetaData[] array = (!(textureImporter != null)) ? null : textureImporter.spritesheet; + if (array != null && textureImporter.spriteImportMode == SpriteImportMode.Multiple) + { + Rect rect2 = default(Rect); + Rect rect3 = default(Rect); + GUI.CalculateScaledTextureRects(rect, ScaleMode.StretchToFill, (float)texture.width / (float)texture.height, ref rect2, ref rect3); + int width = texture.width; + int height = texture.height; + textureImporter.GetWidthAndHeight(ref width, ref height); + float num5 = (float)texture.width / (float)width; + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(new Color(1f, 1f, 1f, 0.5f)); + SpriteMetaData[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + SpriteMetaData spriteMetaData = array2[i]; + Rect rect4 = spriteMetaData.rect; + this.DrawRect(new Rect + { + xMin = rect2.xMin + rect2.width * (rect4.xMin / (float)texture.width * num5), + xMax = rect2.xMin + rect2.width * (rect4.xMax / (float)texture.width * num5), + yMin = rect2.yMin + rect2.height * (1f - rect4.yMin / (float)texture.height * num5), + yMax = rect2.yMin + rect2.height * (1f - rect4.yMax / (float)texture.height * num5) + }); + } + GL.End(); + GL.PopMatrix(); + } + } + TextureUtil.SetMipMapBiasNoDirty(texture, mipMapBias); + TextureUtil.SetFilterModeNoDirty(texture, filterMode); + this.m_Pos = PreviewGUI.EndScrollView(); + if (num3 != 0f) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Mip " + num3); + } + } + private void DrawRect(Rect rect) + { + GL.Vertex(new Vector3(rect.xMin, rect.yMin, 0f)); + GL.Vertex(new Vector3(rect.xMax, rect.yMin, 0f)); + GL.Vertex(new Vector3(rect.xMax, rect.yMin, 0f)); + GL.Vertex(new Vector3(rect.xMax, rect.yMax, 0f)); + GL.Vertex(new Vector3(rect.xMax, rect.yMax, 0f)); + GL.Vertex(new Vector3(rect.xMin, rect.yMax, 0f)); + GL.Vertex(new Vector3(rect.xMin, rect.yMax, 0f)); + GL.Vertex(new Vector3(rect.xMin, rect.yMin, 0f)); + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + Texture texture = this.target as Texture; + PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texture.width, texture.height, ref width, ref height); + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + RenderTexture active = RenderTexture.active; + Rect rawViewportRect = ShaderUtil.rawViewportRect; + RenderTexture temporary = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); + Material material = EditorGUI.GetMaterialForSpecialTexture(texture); + if (material) + { + if (Unsupported.IsDeveloperBuild()) + { + material = new Material(material); + } + Graphics.Blit(texture, temporary, material); + } + else + { + Graphics.Blit(texture, temporary); + } + RenderTexture.active = temporary; + Texture2D texture2D = this.target as Texture2D; + Texture2D texture2D2; + if (texture2D != null && texture2D.alphaIsTransparency) + { + texture2D2 = new Texture2D(width, height, TextureFormat.ARGB32, false); + } + else + { + texture2D2 = new Texture2D(width, height, TextureFormat.RGB24, false); + } + texture2D2.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0); + texture2D2.Apply(); + RenderTexture.ReleaseTemporary(temporary); + EditorGUIUtility.SetRenderTextureNoViewport(active); + ShaderUtil.rawViewportRect = rawViewportRect; + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + if (material && Unsupported.IsDeveloperBuild()) + { + UnityEngine.Object.DestroyImmediate(material); + } + return texture2D2; + } + private float Log2(float x) + { + return (float)(Math.Log((double)x) / Math.Log(2.0)); + } + public override string GetInfoString() + { + Texture texture = this.target as Texture; + Texture2D texture2D = this.target as Texture2D; + string text = texture.width.ToString() + "x" + texture.height.ToString(); + if (QualitySettings.desiredColorSpace == ColorSpace.Linear) + { + text = text + " " + TextureUtil.GetTextureColorSpaceString(texture); + } + bool flag = TextureInspector.IsNormalMap(texture); + bool flag2 = TextureUtil.DoesTextureStillNeedToBeCompressed(AssetDatabase.GetAssetPath(texture)); + bool flag3 = texture2D != null && TextureUtil.IsNonPowerOfTwo(texture2D); + TextureFormat textureFormat = TextureUtil.GetTextureFormat(texture); + bool flag4 = !flag2; + if (flag3) + { + text += " (NPOT)"; + } + if (flag2) + { + text += " (Not yet compressed)"; + } + else + { + if (flag) + { + TextureFormat textureFormat2 = textureFormat; + switch (textureFormat2) + { + case TextureFormat.ARGB4444: + text += " Nm 16 bit"; + goto IL_142; + case TextureFormat.RGB24: + case TextureFormat.RGBA32: + IL_E9: + if (textureFormat2 != TextureFormat.DXT5) + { + text = text + " " + TextureUtil.GetTextureFormatString(textureFormat); + goto IL_142; + } + text += " DXTnm"; + goto IL_142; + case TextureFormat.ARGB32: + text += " Nm 32 bit"; + goto IL_142; + } + goto IL_E9; + IL_142:; + } + else + { + text = text + " " + TextureUtil.GetTextureFormatString(textureFormat); + } + } + if (flag4) + { + text = text + "\n" + EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySize(texture)); + } + if (TextureUtil.GetUsageMode(texture) == TextureUsageMode.AlwaysPadded) + { + int gLWidth = TextureUtil.GetGLWidth(texture); + int gLHeight = TextureUtil.GetGLHeight(texture); + if (texture.width != gLWidth || texture.height != gLHeight) + { + text += string.Format("\nPadded to {0}x{1}", gLWidth, gLHeight); + } + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditor/TextureUsageMode.cs b/UnityEditor/UnityEditor/TextureUsageMode.cs new file mode 100644 index 00000000..28d10aa0 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureUsageMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum TextureUsageMode + { + Default, + LightmapDoubleLDR, + LightmapRGBM, + NormalmapDXT5nm, + NormalmapPlain, + AlwaysPadded = 6 + } +} diff --git a/UnityEditor/UnityEditor/TextureUtil.cs b/UnityEditor/UnityEditor/TextureUtil.cs new file mode 100644 index 00000000..7d1f27e8 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureUtil.cs @@ -0,0 +1,114 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class TextureUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStorageMemorySize(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetRuntimeMemorySize(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsNonPowerOfTwo(Texture2D t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern TextureUsageMode GetUsageMode(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetBytesFromTextureFormat(TextureFormat inFormat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetRowBytesFromWidthAndFormat(int width, TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsValidTextureFormat(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsCompressedTextureFormat(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern TextureFormat GetTextureFormat(Texture texture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsAlphaOnlyTextureFormat(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasAlphaTextureFormat(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetTextureFormatString(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetTextureColorSpaceString(Texture texture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern TextureFormat ConvertToAlphaTextureFormat(TextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsDepthRTFormat(RenderTextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasMipMap(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetGLWidth(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetGLHeight(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CountMipmaps(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetLinearSampled(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetDefaultCompressionQuality(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetTexelSizeVector(Texture t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetSourceTexture(Cubemap cubemapRef, CubemapFace face); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSourceTexture(Cubemap cubemapRef, CubemapFace face, Texture2D tex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyTextureIntoCubemapFace(Texture2D textureRef, Cubemap cubemapRef, CubemapFace face); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyCubemapFaceIntoTexture(Cubemap cubemapRef, CubemapFace face, Texture2D textureRef); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ReformatCubemap(ref Cubemap cubemap, int width, int height, TextureFormat textureFormat, bool useMipmap, bool linear); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool ReformatTexture(ref Texture2D texture, int width, int height, TextureFormat textureFormat, bool useMipmap, bool linear); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnisoLevelNoDirty(Texture tex, int level); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetWrapModeNoDirty(Texture tex, TextureWrapMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetMipMapBiasNoDirty(Texture tex, float bias); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetFilterModeNoDirty(Texture tex, FilterMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DoesTextureStillNeedToBeCompressed(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsCubemapReadable(Cubemap cubemapRef); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MarkCubemapReadable(Cubemap cubemapRef, bool readable); + } +} diff --git a/UnityEditor/UnityEditor/TickHandler.cs b/UnityEditor/UnityEditor/TickHandler.cs new file mode 100644 index 00000000..2d2d169b --- /dev/null +++ b/UnityEditor/UnityEditor/TickHandler.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class TickHandler + { + private float[] m_TickModulos = new float[0]; + private float[] m_TickStrengths = new float[0]; + private int m_SmallestTick; + private int m_BiggestTick = -1; + private float m_MinValue; + private float m_MaxValue = 1f; + private float m_PixelRange = 1f; + public int tickLevels + { + get + { + return this.m_BiggestTick - this.m_SmallestTick + 1; + } + } + public void SetTickModulos(float[] tickModulos) + { + this.m_TickModulos = tickModulos; + } + public void SetTickModulosForFrameRate(float frameRate) + { + if (frameRate != Mathf.Round(frameRate)) + { + this.SetTickModulos(new float[] + { + 1f / frameRate, + 5f / frameRate, + 10f / frameRate, + 50f / frameRate, + 100f / frameRate, + 500f / frameRate, + 1000f / frameRate, + 5000f / frameRate, + 10000f / frameRate, + 50000f / frameRate, + 100000f / frameRate, + 500000f / frameRate + }); + } + else + { + List list = new List(); + int num = 1; + while ((float)num < frameRate) + { + if ((float)num == frameRate) + { + break; + } + int num2 = Mathf.RoundToInt(frameRate / (float)num); + if (num2 % 60 == 0) + { + num *= 2; + list.Add(num); + } + else + { + if (num2 % 30 == 0) + { + num *= 3; + list.Add(num); + } + else + { + if (num2 % 20 == 0) + { + num *= 2; + list.Add(num); + } + else + { + if (num2 % 10 == 0) + { + num *= 2; + list.Add(num); + } + else + { + if (num2 % 5 == 0) + { + num *= 5; + list.Add(num); + } + else + { + if (num2 % 2 == 0) + { + num *= 2; + list.Add(num); + } + else + { + if (num2 % 3 == 0) + { + num *= 3; + list.Add(num); + } + else + { + num = Mathf.RoundToInt(frameRate); + } + } + } + } + } + } + } + } + float[] array = new float[9 + list.Count]; + for (int i = 0; i < list.Count; i++) + { + array[i] = 1f / (float)list[list.Count - i - 1]; + } + array[array.Length - 1] = 3600f; + array[array.Length - 2] = 1800f; + array[array.Length - 3] = 600f; + array[array.Length - 4] = 300f; + array[array.Length - 5] = 60f; + array[array.Length - 6] = 30f; + array[array.Length - 7] = 10f; + array[array.Length - 8] = 5f; + array[array.Length - 9] = 1f; + this.SetTickModulos(array); + } + } + public void SetRanges(float minValue, float maxValue, float minPixel, float maxPixel) + { + this.m_MinValue = minValue; + this.m_MaxValue = maxValue; + this.m_PixelRange = maxPixel - minPixel; + } + public float[] GetTicksAtLevel(int level, bool excludeTicksFromHigherlevels) + { + int num = Mathf.Clamp(this.m_SmallestTick + level, 0, this.m_TickModulos.Length - 1); + List list = new List(); + int num2 = Mathf.FloorToInt(this.m_MinValue / this.m_TickModulos[num]); + int num3 = Mathf.CeilToInt(this.m_MaxValue / this.m_TickModulos[num]); + for (int i = num2; i <= num3; i++) + { + if (!excludeTicksFromHigherlevels || num >= this.m_BiggestTick || i % Mathf.RoundToInt(this.m_TickModulos[num + 1] / this.m_TickModulos[num]) != 0) + { + list.Add((float)i * this.m_TickModulos[num]); + } + } + return list.ToArray(); + } + public float GetStrengthOfLevel(int level) + { + return this.m_TickStrengths[this.m_SmallestTick + level]; + } + public float GetPeriodOfLevel(int level) + { + return this.m_TickModulos[Mathf.Clamp(this.m_SmallestTick + level, 0, this.m_TickModulos.Length - 1)]; + } + public int GetLevelWithMinSeparation(float pixelSeparation) + { + for (int i = 0; i < this.m_TickModulos.Length; i++) + { + float num = this.m_TickModulos[i] * this.m_PixelRange / (this.m_MaxValue - this.m_MinValue); + if (num >= pixelSeparation) + { + return i - this.m_SmallestTick; + } + } + return -1; + } + public void SetTickStrengths(float tickMinSpacing, float tickMaxSpacing, bool sqrt) + { + this.m_TickStrengths = new float[this.m_TickModulos.Length]; + this.m_SmallestTick = 0; + this.m_BiggestTick = this.m_TickModulos.Length - 1; + for (int i = this.m_TickModulos.Length - 1; i >= 0; i--) + { + float num = this.m_TickModulos[i] * this.m_PixelRange / (this.m_MaxValue - this.m_MinValue); + this.m_TickStrengths[i] = (num - tickMinSpacing) / (tickMaxSpacing - tickMinSpacing); + if (this.m_TickStrengths[i] >= 1f) + { + this.m_BiggestTick = i; + } + if (num <= tickMinSpacing) + { + this.m_SmallestTick = i; + break; + } + } + for (int j = this.m_SmallestTick; j <= this.m_BiggestTick; j++) + { + this.m_TickStrengths[j] = Mathf.Clamp01(this.m_TickStrengths[j]); + if (sqrt) + { + this.m_TickStrengths[j] = Mathf.Sqrt(this.m_TickStrengths[j]); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/TickStyle.cs b/UnityEditor/UnityEditor/TickStyle.cs new file mode 100644 index 00000000..1e1511d4 --- /dev/null +++ b/UnityEditor/UnityEditor/TickStyle.cs @@ -0,0 +1,30 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class TickStyle + { + public Color color = new Color(0f, 0f, 0f, 0.2f); + public Color labelColor = new Color(0f, 0f, 0f, 1f); + public int distMin = 10; + public int distFull = 80; + public int distLabel = 50; + public bool stubs; + public bool centerLabel; + public string unit = string.Empty; + public TickStyle() + { + if (EditorGUIUtility.isProSkin) + { + this.color = new Color(0.45f, 0.45f, 0.45f, 0.2f); + this.labelColor = new Color(0.8f, 0.8f, 0.8f, 0.32f); + } + else + { + this.color = new Color(0f, 0f, 0f, 0.2f); + this.labelColor = new Color(0f, 0f, 0f, 0.32f); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TimeArea.cs b/UnityEditor/UnityEditor/TimeArea.cs new file mode 100644 index 00000000..71917202 --- /dev/null +++ b/UnityEditor/UnityEditor/TimeArea.cs @@ -0,0 +1,337 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class TimeArea : ZoomableArea + { + private class Styles2 + { + public GUIStyle TimelineTick = "AnimationTimelineTick"; + public GUIStyle labelTickMarks = "CurveEditorLabelTickMarks"; + } + public enum TimeRulerDragMode + { + None, + Start, + End, + Dragging, + Cancel + } + internal const int kTickRulerDistMin = 3; + internal const int kTickRulerDistFull = 80; + internal const int kTickRulerDistLabel = 40; + internal const float kTickRulerHeightMax = 0.7f; + internal const float kTickRulerFatThreshold = 0.5f; + private TickHandler m_HTicks; + private TickHandler m_VTicks; + private static TimeArea.Styles2 styles; + private CurveEditorSettings m_Settings = new CurveEditorSettings(); + private static float s_OriginalTime; + private static float s_PickOffset; + public TickHandler hTicks + { + get + { + return this.m_HTicks; + } + set + { + this.m_HTicks = value; + } + } + public TickHandler vTicks + { + get + { + return this.m_VTicks; + } + set + { + this.m_VTicks = value; + } + } + public CurveEditorSettings settings + { + get + { + return this.m_Settings; + } + set + { + if (value != null) + { + this.m_Settings = value; + this.ApplySettings(); + } + } + } + public TimeArea(bool minimalGUI) : base(minimalGUI) + { + float[] tickModulos = new float[] + { + 1E-07f, + 5E-07f, + 1E-06f, + 5E-06f, + 1E-05f, + 5E-05f, + 0.0001f, + 0.0005f, + 0.001f, + 0.005f, + 0.01f, + 0.05f, + 0.1f, + 0.5f, + 1f, + 5f, + 10f, + 50f, + 100f, + 500f, + 1000f, + 5000f, + 10000f, + 50000f, + 100000f, + 500000f, + 1000000f, + 5000000f, + 1E+07f + }; + this.hTicks = new TickHandler(); + this.hTicks.SetTickModulos(tickModulos); + this.vTicks = new TickHandler(); + this.vTicks.SetTickModulos(tickModulos); + } + private static void InitStyles() + { + if (TimeArea.styles == null) + { + TimeArea.styles = new TimeArea.Styles2(); + } + } + private void ApplySettings() + { + base.hRangeLocked = this.settings.hRangeLocked; + base.vRangeLocked = this.settings.vRangeLocked; + base.hRangeMin = this.settings.hRangeMin; + base.hRangeMax = this.settings.hRangeMax; + base.vRangeMin = this.settings.vRangeMin; + base.vRangeMax = this.settings.vRangeMax; + base.scaleWithWindow = this.settings.scaleWithWindow; + base.hSlider = this.settings.hSlider; + base.vSlider = this.settings.vSlider; + } + private void SetTickMarkerRanges() + { + this.hTicks.SetRanges(base.shownArea.xMin, base.shownArea.xMax, base.drawRect.xMin, base.drawRect.xMax); + this.vTicks.SetRanges(base.shownArea.yMin, base.shownArea.yMax, base.drawRect.yMin, base.drawRect.yMax); + } + public void DrawMajorTicks(Rect position, float frameRate) + { + Color color = Handles.color; + GUI.BeginGroup(position); + if (Event.current.type != EventType.Repaint) + { + GUI.EndGroup(); + return; + } + TimeArea.InitStyles(); + this.SetTickMarkerRanges(); + this.hTicks.SetTickStrengths(3f, 80f, true); + Color textColor = TimeArea.styles.TimelineTick.normal.textColor; + textColor.a = 0.1f; + Handles.color = textColor; + for (int i = 0; i < this.hTicks.tickLevels; i++) + { + float num = this.hTicks.GetStrengthOfLevel(i) * 0.9f; + if (num > 0.5f) + { + float[] ticksAtLevel = this.hTicks.GetTicksAtLevel(i, true); + for (int j = 0; j < ticksAtLevel.Length; j++) + { + if (ticksAtLevel[j] >= 0f) + { + int num2 = Mathf.RoundToInt(ticksAtLevel[j] * frameRate); + float x = this.FrameToPixel((float)num2, frameRate, position); + Handles.DrawLine(new Vector3(x, 0f, 0f), new Vector3(x, position.height, 0f)); + } + } + } + } + GUI.EndGroup(); + Handles.color = color; + } + public void TimeRuler(Rect position, float frameRate) + { + Color color = GUI.color; + GUI.BeginGroup(position); + if (Event.current.type != EventType.Repaint) + { + GUI.EndGroup(); + return; + } + TimeArea.InitStyles(); + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + Color backgroundColor = GUI.backgroundColor; + this.SetTickMarkerRanges(); + this.hTicks.SetTickStrengths(3f, 80f, true); + Color textColor = TimeArea.styles.TimelineTick.normal.textColor; + textColor.a = 0.75f; + for (int i = 0; i < this.hTicks.tickLevels; i++) + { + float num = this.hTicks.GetStrengthOfLevel(i) * 0.9f; + float[] ticksAtLevel = this.hTicks.GetTicksAtLevel(i, true); + for (int j = 0; j < ticksAtLevel.Length; j++) + { + if (ticksAtLevel[j] >= base.hRangeMin && ticksAtLevel[j] <= base.hRangeMax) + { + int num2 = Mathf.RoundToInt(ticksAtLevel[j] * frameRate); + float num3 = position.height * Mathf.Min(1f, num) * 0.7f; + float num4 = this.FrameToPixel((float)num2, frameRate, position); + GL.Color(new Color(1f, 1f, 1f, num / 0.5f) * textColor); + GL.Vertex(new Vector3(num4, position.height - num3 + 0.5f, 0f)); + GL.Vertex(new Vector3(num4, position.height - 0.5f, 0f)); + if (num > 0.5f) + { + GL.Color(new Color(1f, 1f, 1f, num / 0.5f - 1f) * textColor); + GL.Vertex(new Vector3(num4 + 1f, position.height - num3 + 0.5f, 0f)); + GL.Vertex(new Vector3(num4 + 1f, position.height - 0.5f, 0f)); + } + } + } + } + GL.End(); + int levelWithMinSeparation = this.hTicks.GetLevelWithMinSeparation(40f); + float[] ticksAtLevel2 = this.hTicks.GetTicksAtLevel(levelWithMinSeparation, false); + for (int k = 0; k < ticksAtLevel2.Length; k++) + { + if (ticksAtLevel2[k] >= base.hRangeMin && ticksAtLevel2[k] <= base.hRangeMax) + { + int num5 = Mathf.RoundToInt(ticksAtLevel2[k] * frameRate); + float num6 = Mathf.Floor(this.FrameToPixel((float)num5, frameRate, base.rect)); + string text = this.FormatFrame(num5, frameRate); + GUI.Label(new Rect(num6 + 3f, -3f, 40f, 20f), text, TimeArea.styles.TimelineTick); + } + } + GUI.EndGroup(); + GUI.backgroundColor = backgroundColor; + GUI.color = color; + } + public TimeArea.TimeRulerDragMode BrowseRuler(Rect position, ref float time, float frameRate, bool pickAnywhere, GUIStyle thumbStyle) + { + int controlID = GUIUtility.GetControlID(3126789, FocusType.Passive); + return this.BrowseRuler(position, controlID, ref time, frameRate, pickAnywhere, thumbStyle); + } + public TimeArea.TimeRulerDragMode BrowseRuler(Rect position, int id, ref float time, float frameRate, bool pickAnywhere, GUIStyle thumbStyle) + { + Event current = Event.current; + Rect position2 = position; + if (time != -1f) + { + position2.x = Mathf.Round(base.TimeToPixel(time, position)) - (float)thumbStyle.overflow.left; + position2.width = thumbStyle.fixedWidth + (float)thumbStyle.overflow.horizontal; + } + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (position2.Contains(current.mousePosition)) + { + GUIUtility.hotControl = id; + TimeArea.s_PickOffset = current.mousePosition.x - base.TimeToPixel(time, position); + current.Use(); + return TimeArea.TimeRulerDragMode.Start; + } + if (pickAnywhere && position.Contains(current.mousePosition)) + { + GUIUtility.hotControl = id; + float num = TimeArea.SnapTimeToWholeFPS(base.PixelToTime(current.mousePosition.x, position), frameRate); + TimeArea.s_OriginalTime = time; + if (num != time) + { + GUI.changed = true; + } + time = num; + TimeArea.s_PickOffset = 0f; + current.Use(); + return TimeArea.TimeRulerDragMode.Start; + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + GUIUtility.hotControl = 0; + current.Use(); + return TimeArea.TimeRulerDragMode.End; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + float num2 = TimeArea.SnapTimeToWholeFPS(base.PixelToTime(current.mousePosition.x - TimeArea.s_PickOffset, position), frameRate); + if (num2 != time) + { + GUI.changed = true; + } + time = num2; + current.Use(); + return TimeArea.TimeRulerDragMode.Dragging; + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape) + { + if (time != TimeArea.s_OriginalTime) + { + GUI.changed = true; + } + time = TimeArea.s_OriginalTime; + GUIUtility.hotControl = 0; + current.Use(); + return TimeArea.TimeRulerDragMode.Cancel; + } + break; + case EventType.Repaint: + if (time != -1f) + { + bool flag = position.Contains(current.mousePosition); + position2.x += (float)thumbStyle.overflow.left; + thumbStyle.Draw(position2, id == GUIUtility.hotControl, flag || id == GUIUtility.hotControl, false, false); + } + break; + } + return TimeArea.TimeRulerDragMode.None; + } + private void DrawLine(Vector2 lhs, Vector2 rhs) + { + GL.Vertex(base.DrawingToViewTransformPoint(new Vector3(lhs.x, lhs.y, 0f))); + GL.Vertex(base.DrawingToViewTransformPoint(new Vector3(rhs.x, rhs.y, 0f))); + } + public float FrameToPixel(float i, float frameRate, Rect rect) + { + return (i - base.shownArea.xMin * frameRate) * rect.width / (base.shownArea.width * frameRate); + } + public string FormatFrame(int frame, float frameRate) + { + int length = ((int)frameRate).ToString().Length; + string str = string.Empty; + if (frame < 0) + { + str = "-"; + frame = -frame; + } + return str + (frame / (int)frameRate).ToString() + ":" + ((float)frame % frameRate).ToString().PadLeft(length, '0'); + } + public static float SnapTimeToWholeFPS(float time, float frameRate) + { + if (frameRate == 0f) + { + return time; + } + return Mathf.Round(time * frameRate) / frameRate; + } + } +} diff --git a/UnityEditor/UnityEditor/TimeControl.cs b/UnityEditor/UnityEditor/TimeControl.cs new file mode 100644 index 00000000..39481f9c --- /dev/null +++ b/UnityEditor/UnityEditor/TimeControl.cs @@ -0,0 +1,216 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TimeControl + { + private class Styles + { + public GUIContent playIcon = EditorGUIUtility.IconContent("PlayButton"); + public GUIContent pauseIcon = EditorGUIUtility.IconContent("PauseButton"); + public GUIStyle playButton = "TimeScrubberButton"; + public GUIStyle timeScrubber = "TimeScrubber"; + } + private const float kStepTime = 0.01f; + private const float kScrubberHeight = 21f; + private const float kPlayButtonWidth = 33f; + public float currentTime = float.NegativeInfinity; + private bool m_NextCurrentTimeSet; + public float startTime; + public float stopTime = 1f; + public bool playSelection; + public bool loop = true; + public float playbackSpeed = 1f; + private float m_DeltaTime; + private bool m_DeltaTimeSet; + private double m_LastFrameEditorTime; + private bool m_Playing; + private bool m_ResetOnPlay; + private float m_MouseDrag; + private bool m_WrapForwardDrag; + private static TimeControl.Styles s_Styles; + private static readonly int kScrubberIDHash = "ScrubberIDHash".GetHashCode(); + public float nextCurrentTime + { + set + { + this.deltaTime = value - this.currentTime; + this.m_NextCurrentTimeSet = true; + } + } + public float deltaTime + { + get + { + return this.m_DeltaTime; + } + set + { + this.m_DeltaTime = value; + this.m_DeltaTimeSet = true; + } + } + public float normalizedTime + { + get + { + return (this.stopTime != this.startTime) ? ((this.currentTime - this.startTime) / (this.stopTime - this.startTime)) : 0f; + } + set + { + this.currentTime = this.startTime * (1f - value) + this.stopTime * value; + } + } + public bool playing + { + get + { + return this.m_Playing; + } + set + { + if (this.m_Playing != value) + { + if (value) + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(InspectorWindow.RepaintAllInspectors)); + this.m_LastFrameEditorTime = EditorApplication.timeSinceStartup; + if (this.m_ResetOnPlay) + { + this.nextCurrentTime = this.startTime; + this.m_ResetOnPlay = false; + } + } + else + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(InspectorWindow.RepaintAllInspectors)); + } + } + this.m_Playing = value; + } + } + public void DoTimeControl(Rect rect) + { + if (TimeControl.s_Styles == null) + { + TimeControl.s_Styles = new TimeControl.Styles(); + } + Event current = Event.current; + int controlID = GUIUtility.GetControlID(TimeControl.kScrubberIDHash, FocusType.Keyboard); + Rect rect2 = rect; + rect2.height = 21f; + Rect rect3 = rect2; + rect3.xMin += 33f; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (rect.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = controlID; + } + if (rect3.Contains(current.mousePosition)) + { + EditorGUIUtility.SetWantsMouseJumping(1); + GUIUtility.hotControl = controlID; + this.m_MouseDrag = current.mousePosition.x - rect3.xMin; + this.nextCurrentTime = this.m_MouseDrag * (this.stopTime - this.startTime) / rect3.width + this.startTime; + this.m_WrapForwardDrag = false; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + EditorGUIUtility.SetWantsMouseJumping(0); + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + this.m_MouseDrag += current.delta.x * this.playbackSpeed; + if (this.loop && ((this.m_MouseDrag < 0f && this.m_WrapForwardDrag) || this.m_MouseDrag > rect3.width)) + { + this.m_WrapForwardDrag = true; + this.m_MouseDrag = Mathf.Repeat(this.m_MouseDrag, rect3.width); + } + this.nextCurrentTime = Mathf.Clamp(this.m_MouseDrag, 0f, rect3.width) * (this.stopTime - this.startTime) / rect3.width + this.startTime; + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == controlID) + { + if (current.keyCode == KeyCode.LeftArrow) + { + if (this.currentTime - this.startTime > 0.01f) + { + this.deltaTime = -0.01f; + } + current.Use(); + } + if (current.keyCode == KeyCode.RightArrow) + { + if (this.stopTime - this.currentTime > 0.01f) + { + this.deltaTime = 0.01f; + } + current.Use(); + } + } + break; + } + GUI.Box(rect2, GUIContent.none, TimeControl.s_Styles.timeScrubber); + this.playing = GUI.Toggle(rect2, this.playing, (!this.playing) ? TimeControl.s_Styles.playIcon : TimeControl.s_Styles.pauseIcon, TimeControl.s_Styles.playButton); + float num = Mathf.Lerp(rect3.x, rect3.xMax, this.normalizedTime); + if (GUIUtility.keyboardControl == controlID) + { + Handles.color = new Color(1f, 0f, 0f, 1f); + } + else + { + Handles.color = new Color(1f, 0f, 0f, 0.5f); + } + Handles.DrawLine(new Vector2(num, rect3.yMin), new Vector2(num, rect3.yMax)); + Handles.DrawLine(new Vector2(num + 1f, rect3.yMin), new Vector2(num + 1f, rect3.yMax)); + } + public void OnDisable() + { + this.playing = false; + } + public void Update() + { + if (!this.m_DeltaTimeSet) + { + if (this.playing) + { + double timeSinceStartup = EditorApplication.timeSinceStartup; + this.deltaTime = (float)(timeSinceStartup - this.m_LastFrameEditorTime) * this.playbackSpeed; + this.m_LastFrameEditorTime = timeSinceStartup; + } + else + { + this.deltaTime = 0f; + } + } + this.currentTime += this.deltaTime; + bool flag = this.loop && this.playing && !this.m_NextCurrentTimeSet; + if (flag) + { + this.normalizedTime = Mathf.Repeat(this.normalizedTime, 1f); + } + else + { + if (this.normalizedTime > 1f) + { + this.playing = false; + this.m_ResetOnPlay = true; + } + this.normalizedTime = Mathf.Clamp01(this.normalizedTime); + } + this.m_DeltaTimeSet = false; + this.m_NextCurrentTimeSet = false; + } + } +} diff --git a/UnityEditor/UnityEditor/TimeHelper.cs b/UnityEditor/UnityEditor/TimeHelper.cs new file mode 100644 index 00000000..66756df2 --- /dev/null +++ b/UnityEditor/UnityEditor/TimeHelper.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor +{ + internal struct TimeHelper + { + public float deltaTime; + private long lastTime; + public void Begin() + { + this.lastTime = DateTime.Now.Ticks; + } + public float Update() + { + this.deltaTime = (float)(DateTime.Now.Ticks - this.lastTime) / 1E+07f; + this.lastTime = DateTime.Now.Ticks; + return this.deltaTime; + } + } +} diff --git a/UnityEditor/UnityEditor/TimeUpdater.cs b/UnityEditor/UnityEditor/TimeUpdater.cs new file mode 100644 index 00000000..4480ec8a --- /dev/null +++ b/UnityEditor/UnityEditor/TimeUpdater.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + internal interface TimeUpdater + { + void UpdateTime(float time); + } +} diff --git a/UnityEditor/UnityEditor/Timeline.cs b/UnityEditor/UnityEditor/Timeline.cs new file mode 100644 index 00000000..91401939 --- /dev/null +++ b/UnityEditor/UnityEditor/Timeline.cs @@ -0,0 +1,811 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class Timeline + { + private enum DragStates + { + None, + LeftSelection, + RightSelection, + FullSelection, + Destination, + Source, + Playhead + } + private class Styles + { + public readonly GUIStyle block = new GUIStyle("MeTransitionBlock"); + public GUIStyle leftBlock = new GUIStyle("MeTransitionBlock"); + public GUIStyle rightBlock = new GUIStyle("MeTransitionBlock"); + public GUIStyle timeBlockRight = new GUIStyle("MeTimeLabel"); + public GUIStyle timeBlockLeft = new GUIStyle("MeTimeLabel"); + public readonly GUIStyle offLeft = new GUIStyle("MeTransOffLeft"); + public readonly GUIStyle offRight = new GUIStyle("MeTransOffRight"); + public readonly GUIStyle onLeft = new GUIStyle("MeTransOnLeft"); + public readonly GUIStyle onRight = new GUIStyle("MeTransOnRight"); + public readonly GUIStyle offOn = new GUIStyle("MeTransOff2On"); + public readonly GUIStyle onOff = new GUIStyle("MeTransOn2Off"); + public readonly GUIStyle background = new GUIStyle("MeTransitionBack"); + public readonly GUIStyle header = new GUIStyle("MeTransitionHead"); + public readonly GUIStyle handLeft = new GUIStyle("MeTransitionHandleLeft"); + public readonly GUIStyle handRight = new GUIStyle("MeTransitionHandleRight"); + public readonly GUIStyle handLeftPrev = new GUIStyle("MeTransitionHandleLeftPrev"); + public readonly GUIStyle playhead = new GUIStyle("MeTransPlayhead"); + public readonly GUIStyle selectHead = new GUIStyle("MeTransitionSelectHead"); + public readonly GUIStyle select = new GUIStyle("MeTransitionSelect"); + public readonly GUIStyle overlay = new GUIStyle("MeTransBGOver"); + public Styles() + { + this.timeBlockRight.alignment = TextAnchor.MiddleRight; + this.timeBlockRight.normal.background = null; + this.timeBlockLeft.normal.background = null; + } + } + internal class PivotSample + { + public float m_Time; + public float m_Weight; + } + private TimeArea m_TimeArea; + private float m_Time = float.PositiveInfinity; + private float m_StartTime; + private float m_StopTime = 1f; + private string m_SrcName = "Left"; + private string m_DstName = "Right"; + private bool m_SrcLoop; + private bool m_DstLoop; + private float m_SrcStartTime; + private float m_SrcStopTime = 0.75f; + private float m_DstStartTime = 0.25f; + private float m_DstStopTime = 1f; + private bool m_HasExitTime; + private float m_TransitionStartTime = float.PositiveInfinity; + private float m_TransitionStopTime = float.PositiveInfinity; + private float m_DstDragOffset; + private float m_LeftThumbOffset; + private float m_RightThumbOffset; + private Timeline.DragStates m_DragState; + private int id = -1; + private Rect m_Rect = new Rect(0f, 0f, 0f, 0f); + private Vector3[] m_SrcPivotVectors; + private Vector3[] m_DstPivotVectors; + private List m_SrcPivotList = new List(); + private List m_DstPivotList = new List(); + private Timeline.Styles styles; + public List SrcPivotList + { + get + { + return this.m_SrcPivotList; + } + set + { + this.m_SrcPivotList = value; + this.m_SrcPivotVectors = null; + } + } + public List DstPivotList + { + get + { + return this.m_DstPivotList; + } + set + { + this.m_DstPivotList = value; + this.m_DstPivotVectors = null; + } + } + public bool srcLoop + { + get + { + return this.m_SrcLoop; + } + set + { + this.m_SrcLoop = value; + } + } + public bool dstLoop + { + get + { + return this.m_DstLoop; + } + set + { + this.m_DstLoop = value; + } + } + public float Time + { + get + { + return this.m_Time; + } + set + { + this.m_Time = value; + } + } + public float StartTime + { + get + { + return this.m_StartTime; + } + set + { + this.m_StartTime = value; + } + } + public float StopTime + { + get + { + return this.m_StopTime; + } + set + { + this.m_StopTime = value; + } + } + public string SrcName + { + get + { + return this.m_SrcName; + } + set + { + this.m_SrcName = value; + } + } + public string DstName + { + get + { + return this.m_DstName; + } + set + { + this.m_DstName = value; + } + } + public float SrcStartTime + { + get + { + return this.m_SrcStartTime; + } + set + { + this.m_SrcStartTime = value; + } + } + public float SrcStopTime + { + get + { + return this.m_SrcStopTime; + } + set + { + this.m_SrcStopTime = value; + } + } + public float SrcDuration + { + get + { + return this.SrcStopTime - this.SrcStartTime; + } + } + public float DstStartTime + { + get + { + return this.m_DstStartTime; + } + set + { + this.m_DstStartTime = value; + } + } + public float DstStopTime + { + get + { + return this.m_DstStopTime; + } + set + { + this.m_DstStopTime = value; + } + } + public float DstDuration + { + get + { + return this.DstStopTime - this.DstStartTime; + } + } + public float TransitionStartTime + { + get + { + return this.m_TransitionStartTime; + } + set + { + this.m_TransitionStartTime = value; + } + } + public float TransitionStopTime + { + get + { + return this.m_TransitionStopTime; + } + set + { + this.m_TransitionStopTime = value; + } + } + public bool HasExitTime + { + get + { + return this.m_HasExitTime; + } + set + { + this.m_HasExitTime = value; + } + } + public float TransitionDuration + { + get + { + return this.TransitionStopTime - this.TransitionStartTime; + } + } + public Timeline() + { + this.Init(); + } + public void ResetRange() + { + this.m_TimeArea.SetShownHRangeInsideMargins(0f, this.StopTime); + } + private void Init() + { + if (this.id == -1) + { + this.id = GUIUtility.GetPermanentControlID(); + } + if (this.m_TimeArea == null) + { + this.m_TimeArea = new TimeArea(false); + this.m_TimeArea.hRangeLocked = false; + this.m_TimeArea.vRangeLocked = true; + this.m_TimeArea.hSlider = false; + this.m_TimeArea.vSlider = false; + this.m_TimeArea.margin = 10f; + this.m_TimeArea.scaleWithWindow = true; + this.m_TimeArea.hTicks.SetTickModulosForFrameRate(30f); + this.m_TimeArea.OnEnable(); + } + if (this.styles == null) + { + this.styles = new Timeline.Styles(); + } + } + private List GetControls(List segmentPoints, float scale) + { + List list = new List(); + if (segmentPoints.Count < 2) + { + return list; + } + for (int i = 0; i < segmentPoints.Count; i++) + { + if (i == 0) + { + Vector3 vector = segmentPoints[i]; + Vector3 a = segmentPoints[i + 1]; + Vector3 a2 = a - vector; + Vector3 item = vector + scale * a2; + list.Add(vector); + list.Add(item); + } + else + { + if (i == segmentPoints.Count - 1) + { + Vector3 b = segmentPoints[i - 1]; + Vector3 vector2 = segmentPoints[i]; + Vector3 a3 = vector2 - b; + Vector3 item2 = vector2 - scale * a3; + list.Add(item2); + list.Add(vector2); + } + else + { + Vector3 b2 = segmentPoints[i - 1]; + Vector3 vector3 = segmentPoints[i]; + Vector3 a4 = segmentPoints[i + 1]; + Vector3 normalized = (a4 - b2).normalized; + Vector3 item3 = vector3 - scale * normalized * (vector3 - b2).magnitude; + Vector3 item4 = vector3 + scale * normalized * (a4 - vector3).magnitude; + list.Add(item3); + list.Add(vector3); + list.Add(item4); + } + } + } + return list; + } + private Vector3 CalculatePoint(float t, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3) + { + float num = 1f - t; + float num2 = t * t; + float num3 = num * num; + float d = num3 * num; + float d2 = num2 * t; + Vector3 a = d * p0; + a += 3f * num3 * t * p1; + a += 3f * num * num2 * p2; + return a + d2 * p3; + } + private Color[] GetPivotColors(Vector3[] vectors, float motionStart, float motionStop, Color fromColor, Color toColor, Color loopColor, float offset) + { + Color[] array = new Color[vectors.Length]; + float num = this.m_TimeArea.TimeToPixel(this.m_TransitionStartTime, this.m_Rect) + this.m_LeftThumbOffset; + float num2 = this.m_TimeArea.TimeToPixel(this.m_TransitionStopTime, this.m_Rect) + this.m_RightThumbOffset; + float num3 = num2 - num; + for (int i = 0; i < array.Length; i++) + { + if (vectors[i].x >= num && vectors[i].x <= num2) + { + array[i] = Color.Lerp(fromColor, toColor, (vectors[i].x - num) / num3); + } + else + { + if (vectors[i].x < num && vectors[i].x >= motionStart + offset) + { + array[i] = fromColor; + } + else + { + if (vectors[i].x > num2 && vectors[i].x <= motionStop + offset) + { + array[i] = toColor; + } + else + { + array[i] = loopColor; + } + } + } + } + return array; + } + private Vector3[] GetPivotVectors(Timeline.PivotSample[] samples, float motionStart, float motionStop, Rect rect, bool loop) + { + if (samples.Length == 0 || motionStop - motionStart < 0.33f) + { + return new Vector3[0]; + } + float num = motionStop - motionStart; + List list = new List(); + for (int i = 0; i < samples.Length; i++) + { + Timeline.PivotSample pivotSample = samples[i]; + Vector3 zero = Vector3.zero; + zero.x = this.m_TimeArea.TimeToPixel(pivotSample.m_Time, rect); + zero.y = rect.height / 16f + pivotSample.m_Weight * 12f * rect.height / 16f; + list.Add(zero); + } + if (loop && list[list.Count - 1].x <= rect.width) + { + float x = list[list.Count - 1].x; + int num2 = 0; + int num3 = 1; + List list2 = new List(); + list2.Add(list[list.Count - 1]); + while (x < rect.width) + { + if (num2 > list.Count - 1) + { + num2 = 0; + num3++; + } + Vector3 item = list[num2]; + item.x += (float)num3 * num; + x = item.x; + list2.Add(item); + num2++; + } + list.AddRange(list2); + } + List controls = this.GetControls(list, 0.5f); + list.Clear(); + for (int j = 0; j < controls.Count - 3; j += 3) + { + Vector3 p = controls[j]; + Vector3 p2 = controls[j + 1]; + Vector3 p3 = controls[j + 2]; + Vector3 p4 = controls[j + 3]; + if (j == 0) + { + list.Add(this.CalculatePoint(0f, p, p2, p3, p4)); + } + for (int k = 1; k <= 10; k++) + { + list.Add(this.CalculatePoint((float)k / 10f, p, p2, p3, p4)); + } + } + return list.ToArray(); + } + private Vector3[] OffsetPivotVectors(Vector3[] vectors, float offset) + { + for (int i = 0; i < vectors.Length; i++) + { + int expr_0E_cp_1 = i; + vectors[expr_0E_cp_1].x = vectors[expr_0E_cp_1].x + offset; + } + return vectors; + } + private void DoPivotCurves() + { + Color white = Color.white; + Color white2 = Color.white; + Color toColor = new Color(1f, 1f, 1f, 0.1f); + Color fromColor = new Color(1f, 1f, 1f, 0.1f); + Color loopColor = new Color(0.75f, 0.75f, 0.75f, 0.2f); + Color loopColor2 = new Color(0.75f, 0.75f, 0.75f, 0.2f); + Rect rect = new Rect(0f, 18f, this.m_Rect.width, 66f); + GUI.BeginGroup(rect); + float num = this.m_TimeArea.TimeToPixel(this.SrcStartTime, rect); + float motionStop = this.m_TimeArea.TimeToPixel(this.SrcStopTime, rect); + float num2 = this.m_TimeArea.TimeToPixel(this.DstStartTime, rect); + float motionStop2 = this.m_TimeArea.TimeToPixel(this.DstStopTime, rect); + if (this.m_SrcPivotVectors == null) + { + this.m_SrcPivotVectors = this.GetPivotVectors(this.m_SrcPivotList.ToArray(), num, motionStop, rect, this.srcLoop); + } + if (this.m_DstPivotVectors == null) + { + this.m_DstPivotVectors = this.GetPivotVectors(this.m_DstPivotList.ToArray(), num2, motionStop2, rect, this.dstLoop); + } + this.m_DstPivotVectors = this.OffsetPivotVectors(this.m_DstPivotVectors, this.m_DstDragOffset + num2 - num); + Color[] pivotColors = this.GetPivotColors(this.m_SrcPivotVectors, num, motionStop, white, toColor, loopColor, 0f); + Color[] pivotColors2 = this.GetPivotColors(this.m_DstPivotVectors, num2, motionStop2, fromColor, white2, loopColor2, this.m_DstDragOffset); + Handles.DrawAAPolyLine(pivotColors, this.m_SrcPivotVectors); + Handles.DrawAAPolyLine(pivotColors2, this.m_DstPivotVectors); + GUI.EndGroup(); + } + private void EnforceConstraints() + { + } + private bool WasDraggingData() + { + return this.m_DstDragOffset != 0f || this.m_LeftThumbOffset != 0f || this.m_RightThumbOffset != 0f; + } + public bool DoTimeline(Rect timeRect) + { + bool result = false; + this.Init(); + this.m_Rect = timeRect; + float num = this.m_TimeArea.PixelToTime(timeRect.xMin, timeRect); + float num2 = this.m_TimeArea.PixelToTime(timeRect.xMax, timeRect); + if (num != this.StartTime) + { + this.StartTime = num; + GUI.changed = true; + } + if (num2 != this.StopTime) + { + this.StopTime = num2; + GUI.changed = true; + } + this.Time = ((this.Time >= this.StartTime) ? this.Time : this.StartTime); + this.Time = ((this.Time <= this.StopTime) ? this.Time : this.StartTime); + this.Time = Mathf.Max(this.Time, 0f); + if (Event.current.type == EventType.Repaint) + { + this.m_TimeArea.rect = timeRect; + } + this.m_TimeArea.BeginViewGUI(); + this.m_TimeArea.EndViewGUI(); + GUI.BeginGroup(timeRect); + Event current = Event.current; + Rect rect = new Rect(0f, 0f, timeRect.width, timeRect.height); + Rect position = new Rect(0f, 0f, timeRect.width, 18f); + Rect position2 = new Rect(0f, 18f, timeRect.width, 132f); + float num3 = this.m_TimeArea.TimeToPixel(this.SrcStartTime, timeRect); + float num4 = this.m_TimeArea.TimeToPixel(this.SrcStopTime, timeRect); + float num5 = this.m_TimeArea.TimeToPixel(this.DstStartTime, timeRect) + this.m_DstDragOffset; + float num6 = this.m_TimeArea.TimeToPixel(this.DstStopTime, timeRect) + this.m_DstDragOffset; + float num7 = this.m_TimeArea.TimeToPixel(this.TransitionStartTime, timeRect) + this.m_LeftThumbOffset; + float num8 = this.m_TimeArea.TimeToPixel(this.TransitionStopTime, timeRect) + this.m_RightThumbOffset; + float num9 = this.m_TimeArea.TimeToPixel(this.Time, timeRect); + Rect rect2 = new Rect(num3, 85f, num4 - num3, 32f); + Rect rect3 = new Rect(num5, 117f, num6 - num5, 32f); + Rect position3 = new Rect(num7, 0f, num8 - num7, 18f); + Rect position4 = new Rect(num7, 18f, num8 - num7, timeRect.height - 18f); + Rect position5 = new Rect(num7 - 9f, 5f, 9f, 15f); + Rect position6 = new Rect(num8, 5f, 9f, 15f); + Rect position7 = new Rect(num9 - 7f, 4f, 15f, 15f); + if (current.type == EventType.KeyDown) + { + if (GUIUtility.keyboardControl == this.id && this.m_DragState == Timeline.DragStates.Destination) + { + this.m_DstDragOffset = 0f; + } + if (this.m_DragState == Timeline.DragStates.LeftSelection) + { + this.m_LeftThumbOffset = 0f; + } + if (this.m_DragState == Timeline.DragStates.RightSelection) + { + this.m_RightThumbOffset = 0f; + } + if (this.m_DragState == Timeline.DragStates.FullSelection) + { + this.m_LeftThumbOffset = 0f; + this.m_RightThumbOffset = 0f; + } + } + if (current.type == EventType.MouseDown && rect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = this.id; + GUIUtility.keyboardControl = this.id; + if (position7.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.Playhead; + } + else + { + if (rect2.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.Source; + } + else + { + if (rect3.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.Destination; + } + else + { + if (position5.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.LeftSelection; + } + else + { + if (position6.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.RightSelection; + } + else + { + if (position3.Contains(current.mousePosition)) + { + this.m_DragState = Timeline.DragStates.FullSelection; + } + else + { + this.m_DragState = Timeline.DragStates.None; + } + } + } + } + } + } + current.Use(); + } + if (current.type == EventType.MouseDrag && GUIUtility.hotControl == this.id) + { + switch (this.m_DragState) + { + case Timeline.DragStates.LeftSelection: + this.m_LeftThumbOffset += current.delta.x; + this.EnforceConstraints(); + break; + case Timeline.DragStates.RightSelection: + this.m_RightThumbOffset += current.delta.x; + this.EnforceConstraints(); + break; + case Timeline.DragStates.FullSelection: + this.m_RightThumbOffset += current.delta.x; + this.m_LeftThumbOffset += current.delta.x; + this.EnforceConstraints(); + break; + case Timeline.DragStates.Destination: + this.m_DstDragOffset += current.delta.x; + this.EnforceConstraints(); + break; + case Timeline.DragStates.Source: + { + TimeArea expr_498_cp_0 = this.m_TimeArea; + expr_498_cp_0.m_Translation.x = expr_498_cp_0.m_Translation.x + current.delta.x; + break; + } + case Timeline.DragStates.Playhead: + this.Time = this.m_TimeArea.PixelToTime(num9 + current.delta.x, timeRect); + break; + } + current.Use(); + GUI.changed = true; + } + if (current.type == EventType.MouseUp && GUIUtility.hotControl == this.id) + { + this.SrcStartTime = this.m_TimeArea.PixelToTime(num3, timeRect); + this.SrcStopTime = this.m_TimeArea.PixelToTime(num4, timeRect); + this.DstStartTime = this.m_TimeArea.PixelToTime(num5, timeRect); + this.DstStopTime = this.m_TimeArea.PixelToTime(num6, timeRect); + this.TransitionStartTime = this.m_TimeArea.PixelToTime(num7, timeRect); + this.TransitionStopTime = this.m_TimeArea.PixelToTime(num8, timeRect); + GUI.changed = true; + this.m_DragState = Timeline.DragStates.None; + result = this.WasDraggingData(); + this.m_LeftThumbOffset = 0f; + this.m_RightThumbOffset = 0f; + this.m_DstDragOffset = 0f; + GUIUtility.hotControl = 0; + current.Use(); + } + GUI.Box(position, GUIContent.none, this.styles.header); + GUI.Box(position2, GUIContent.none, this.styles.background); + this.m_TimeArea.DrawMajorTicks(position2, 30f); + GUIContent content = EditorGUIUtility.TempContent(this.SrcName); + int num10 = (!this.srcLoop) ? 1 : (1 + (int)((num8 - rect2.xMin) / (rect2.xMax - rect2.xMin))); + Rect position8 = rect2; + if (rect2.width < 10f) + { + position8 = new Rect(rect2.x, rect2.y, (rect2.xMax - rect2.xMin) * (float)num10, rect2.height); + num10 = 1; + } + for (int i = 0; i < num10; i++) + { + GUI.BeginGroup(position8, GUIContent.none, this.styles.leftBlock); + float num11 = num7 - position8.xMin; + float num12 = num8 - num7; + float num13 = position8.xMax - position8.xMin - (num11 + num12); + if (num11 > 0f) + { + GUI.Box(new Rect(0f, 0f, num11, rect2.height), GUIContent.none, this.styles.onLeft); + } + if (num12 > 0f) + { + GUI.Box(new Rect(num11, 0f, num12, rect2.height), GUIContent.none, this.styles.onOff); + } + if (num13 > 0f) + { + GUI.Box(new Rect(num11 + num12, 0f, num13, rect2.height), GUIContent.none, this.styles.offRight); + } + float num14 = 1f; + float x = this.styles.block.CalcSize(content).x; + float num15 = Mathf.Max(0f, num11) - 20f; + float num16 = num15 + 15f; + if (num15 < x && num16 > 0f && this.m_DragState == Timeline.DragStates.LeftSelection) + { + num14 = 0f; + } + GUI.EndGroup(); + float num17 = this.styles.leftBlock.normal.textColor.a; + if (!Mathf.Approximately(num17, num14) && Event.current.type == EventType.Repaint) + { + num17 = Mathf.Lerp(num17, num14, 0.1f); + this.styles.leftBlock.normal.textColor = new Color(this.styles.leftBlock.normal.textColor.r, this.styles.leftBlock.normal.textColor.g, this.styles.leftBlock.normal.textColor.b, num17); + HandleUtility.Repaint(); + } + GUI.Box(position8, content, this.styles.leftBlock); + position8 = new Rect(position8.xMax, 85f, position8.xMax - position8.xMin, 32f); + } + GUIContent content2 = EditorGUIUtility.TempContent(this.DstName); + int num18 = (!this.dstLoop) ? 1 : (1 + (int)((num8 - rect3.xMin) / (rect3.xMax - rect3.xMin))); + position8 = rect3; + if (rect3.width < 10f) + { + position8 = new Rect(rect3.x, rect3.y, (rect3.xMax - rect3.xMin) * (float)num18, rect3.height); + num18 = 1; + } + for (int j = 0; j < num18; j++) + { + GUI.BeginGroup(position8, GUIContent.none, this.styles.rightBlock); + float num19 = num7 - position8.xMin; + float num20 = num8 - num7; + float num21 = position8.xMax - position8.xMin - (num19 + num20); + if (num19 > 0f) + { + GUI.Box(new Rect(0f, 0f, num19, rect3.height), GUIContent.none, this.styles.offLeft); + } + if (num20 > 0f) + { + GUI.Box(new Rect(num19, 0f, num20, rect3.height), GUIContent.none, this.styles.offOn); + } + if (num21 > 0f) + { + GUI.Box(new Rect(num19 + num20, 0f, num21, rect3.height), GUIContent.none, this.styles.onRight); + } + float num22 = 1f; + float x2 = this.styles.block.CalcSize(content2).x; + float num23 = Mathf.Max(0f, num19) - 20f; + float num24 = num23 + 15f; + if (num23 < x2 && num24 > 0f && (this.m_DragState == Timeline.DragStates.LeftSelection || this.m_DragState == Timeline.DragStates.Destination)) + { + num22 = 0f; + } + GUI.EndGroup(); + float num25 = this.styles.rightBlock.normal.textColor.a; + if (!Mathf.Approximately(num25, num22) && Event.current.type == EventType.Repaint) + { + num25 = Mathf.Lerp(num25, num22, 0.1f); + this.styles.rightBlock.normal.textColor = new Color(this.styles.rightBlock.normal.textColor.r, this.styles.rightBlock.normal.textColor.g, this.styles.rightBlock.normal.textColor.b, num25); + HandleUtility.Repaint(); + } + GUI.Box(position8, content2, this.styles.rightBlock); + position8 = new Rect(position8.xMax, position8.yMin, position8.xMax - position8.xMin, 32f); + } + GUI.Box(position4, GUIContent.none, this.styles.select); + GUI.Box(position3, GUIContent.none, this.styles.selectHead); + this.m_TimeArea.TimeRuler(position, 30f); + GUI.Box(position5, GUIContent.none, (!this.m_HasExitTime) ? this.styles.handLeftPrev : this.styles.handLeft); + GUI.Box(position6, GUIContent.none, this.styles.handRight); + GUI.Box(position7, GUIContent.none, this.styles.playhead); + Color color = Handles.color; + Handles.color = Color.white; + Handles.DrawLine(new Vector3(num9, 19f, 0f), new Vector3(num9, timeRect.height, 0f)); + Handles.color = color; + bool flag = this.SrcStopTime - this.SrcStartTime < 0.0333333351f; + bool flag2 = this.DstStopTime - this.DstStartTime < 0.0333333351f; + if (this.m_DragState == Timeline.DragStates.Destination && !flag2) + { + Rect position9 = new Rect(num7 - 50f, rect3.y, 45f, rect3.height); + string t = string.Format("{0:0%}", (num7 - num5) / (num6 - num5)); + GUI.Box(position9, EditorGUIUtility.TempContent(t), this.styles.timeBlockRight); + } + if (this.m_DragState == Timeline.DragStates.LeftSelection) + { + if (!flag) + { + Rect position10 = new Rect(num7 - 50f, rect2.y, 45f, rect2.height); + string t2 = string.Format("{0:0%}", (num7 - num3) / (num4 - num3)); + GUI.Box(position10, EditorGUIUtility.TempContent(t2), this.styles.timeBlockRight); + } + if (!flag2) + { + Rect position11 = new Rect(num7 - 50f, rect3.y, 45f, rect3.height); + string t3 = string.Format("{0:0%}", (num7 - num5) / (num6 - num5)); + GUI.Box(position11, EditorGUIUtility.TempContent(t3), this.styles.timeBlockRight); + } + } + if (this.m_DragState == Timeline.DragStates.RightSelection) + { + if (!flag) + { + Rect position12 = new Rect(num8 + 5f, rect2.y, 45f, rect2.height); + string t4 = string.Format("{0:0%}", (num8 - num3) / (num4 - num3)); + GUI.Box(position12, EditorGUIUtility.TempContent(t4), this.styles.timeBlockLeft); + } + if (!flag2) + { + Rect position13 = new Rect(num8 + 5f, rect3.y, 45f, rect3.height); + string t5 = string.Format("{0:0%}", (num8 - num5) / (num6 - num5)); + GUI.Box(position13, EditorGUIUtility.TempContent(t5), this.styles.timeBlockLeft); + } + } + this.DoPivotCurves(); + GUI.EndGroup(); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/TizenBuildSubtarget.cs b/UnityEditor/UnityEditor/TizenBuildSubtarget.cs new file mode 100644 index 00000000..72cb6f40 --- /dev/null +++ b/UnityEditor/UnityEditor/TizenBuildSubtarget.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum TizenBuildSubtarget + { + Generic, + ATC, + ETC + } +} diff --git a/UnityEditor/UnityEditor/Tool.cs b/UnityEditor/UnityEditor/Tool.cs new file mode 100644 index 00000000..56ace814 --- /dev/null +++ b/UnityEditor/UnityEditor/Tool.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum Tool + { + View, + Move, + Rotate, + Scale, + Rect, + None = -1 + } +} diff --git a/UnityEditor/UnityEditor/Toolbar.cs b/UnityEditor/UnityEditor/Toolbar.cs new file mode 100644 index 00000000..7e2110b5 --- /dev/null +++ b/UnityEditor/UnityEditor/Toolbar.cs @@ -0,0 +1,244 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class Toolbar : GUIView + { + private static GUIContent[] s_ToolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("MoveTool"), + EditorGUIUtility.IconContent("RotateTool"), + EditorGUIUtility.IconContent("ScaleTool"), + EditorGUIUtility.IconContent("RectTool"), + EditorGUIUtility.IconContent("MoveTool On"), + EditorGUIUtility.IconContent("RotateTool On"), + EditorGUIUtility.IconContent("ScaleTool On"), + EditorGUIUtility.IconContent("RectTool On") + }; + private static GUIContent[] s_ViewToolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("ViewToolOrbit"), + EditorGUIUtility.IconContent("ViewToolMove"), + EditorGUIUtility.IconContent("ViewToolZoom"), + EditorGUIUtility.IconContent("ViewToolOrbit"), + EditorGUIUtility.IconContent("ViewToolOrbit On"), + EditorGUIUtility.IconContent("ViewToolMove On"), + EditorGUIUtility.IconContent("ViewToolZoom On"), + EditorGUIUtility.IconContent("ViewToolOrbit On") + }; + private static GUIContent[] s_PivotIcons = new GUIContent[] + { + EditorGUIUtility.TextContent("ToolHandleCenter"), + EditorGUIUtility.TextContent("ToolHandlePivot") + }; + private static GUIContent[] s_PivotRotation = new GUIContent[] + { + EditorGUIUtility.TextContent("ToolHandleLocal"), + EditorGUIUtility.TextContent("ToolHandleGlobal") + }; + private static GUIContent s_LayerContent = EditorGUIUtility.TextContent("ToolbarLayers"); + private static GUIContent[] s_PlayIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("PlayButton"), + EditorGUIUtility.IconContent("PauseButton"), + EditorGUIUtility.IconContent("StepButton"), + EditorGUIUtility.IconContent("PlayButtonProfile"), + EditorGUIUtility.IconContent("PlayButton On"), + EditorGUIUtility.IconContent("PauseButton On"), + EditorGUIUtility.IconContent("StepButton On"), + EditorGUIUtility.IconContent("PlayButtonProfile On"), + EditorGUIUtility.IconContent("PlayButton Anim"), + EditorGUIUtility.IconContent("PauseButton Anim"), + EditorGUIUtility.IconContent("StepButton Anim"), + EditorGUIUtility.IconContent("PlayButtonProfile Anim") + }; + private bool t1; + private bool t2; + private bool t3; + private static GUIContent[] s_ShownToolIcons = new GUIContent[5]; + public static Toolbar get = null; + [SerializeField] + private string m_LastLoadedLayoutName; + internal static string lastLoadedLayoutName + { + get + { + return (!string.IsNullOrEmpty(Toolbar.get.m_LastLoadedLayoutName)) ? Toolbar.get.m_LastLoadedLayoutName : "Layout"; + } + set + { + Toolbar.get.m_LastLoadedLayoutName = value; + Toolbar.get.Repaint(); + } + } + public void OnEnable() + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(base.Repaint)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.OnSelectionChange)); + Toolbar.get = this; + } + public void OnDisable() + { + EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(base.Repaint)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.OnSelectionChange)); + } + protected override bool OnFocus() + { + return false; + } + private void OnSelectionChange() + { + Tools.OnSelectionChange(); + base.Repaint(); + } + private void OnGUI() + { + bool isPlayingOrWillChangePlaymode = EditorApplication.isPlayingOrWillChangePlaymode; + if (isPlayingOrWillChangePlaymode) + { + GUI.color = HostView.kPlayModeDarken; + } + GUIStyle gUIStyle = "AppToolbar"; + if (Event.current.type == EventType.Repaint) + { + gUIStyle.Draw(new Rect(0f, 0f, base.position.width, base.position.height), false, false, false, false); + } + this.DoToolButtons(); + float num = 100f; + float num2 = (base.position.width - num) / 2f; + num2 = Mathf.Max(num2, 373f); + GUILayout.BeginArea(new Rect(num2, 5f, 120f, 24f)); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.DoPlayButtons(isPlayingOrWillChangePlaymode); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + float num3 = 220f; + num2 = base.position.width - num3; + num2 = Mathf.Max(num2, 440f); + GUILayout.BeginArea(new Rect(num2, 7f, base.position.width - num2 - 10f, 24f)); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.DoLayersDropDown(); + GUILayout.Space(6f); + this.DoLayoutDropDown(); + GUILayout.EndArea(); + EditorGUI.ShowRepaints(); + Highlighter.ControlHighlightGUI(this); + } + private void DoToolButtons() + { + GUI.changed = false; + int num = (int)((!Tools.viewToolActive) ? Tools.current : Tool.View); + for (int i = 1; i < 5; i++) + { + Toolbar.s_ShownToolIcons[i] = Toolbar.s_ToolIcons[i - 1 + ((i != num) ? 0 : 4)]; + Toolbar.s_ShownToolIcons[i].tooltip = Toolbar.s_ToolIcons[i - 1].tooltip; + } + Toolbar.s_ShownToolIcons[0] = Toolbar.s_ViewToolIcons[(int)(Tools.viewTool + ((num != 0) ? 0 : 4))]; + num = GUI.Toolbar(new Rect(10f, 5f, 160f, 24f), num, Toolbar.s_ShownToolIcons, "Command"); + if (GUI.changed) + { + Tools.current = (Tool)num; + } + Tools.pivotMode = (PivotMode)EditorGUI.CycleButton(new Rect(190f, 8f, 64f, 18f), (int)Tools.pivotMode, Toolbar.s_PivotIcons, "ButtonLeft"); + if (Tools.current == Tool.Scale && Selection.transforms.Length < 2) + { + GUI.enabled = false; + } + PivotRotation pivotRotation = (PivotRotation)EditorGUI.CycleButton(new Rect(254f, 8f, 64f, 18f), (int)Tools.pivotRotation, Toolbar.s_PivotRotation, "ButtonRight"); + if (Tools.pivotRotation != pivotRotation) + { + Tools.pivotRotation = pivotRotation; + if (pivotRotation == PivotRotation.Global) + { + Tools.ResetGlobalHandleRotation(); + } + } + if (Tools.current == Tool.Scale) + { + GUI.enabled = true; + } + if (GUI.changed) + { + Tools.RepaintAllToolViews(); + } + } + private void DoPlayButtons(bool isOrWillEnterPlaymode) + { + bool isPlaying = EditorApplication.isPlaying; + GUI.changed = false; + int num = (!isPlaying) ? 0 : 4; + if (AnimationMode.InAnimationMode()) + { + num = 8; + } + Color color = GUI.color + new Color(0.01f, 0.01f, 0.01f, 0.01f); + GUI.contentColor = new Color(1f / color.r, 1f / color.g, 1f / color.g, 1f / color.a); + GUILayout.Toggle(isOrWillEnterPlaymode, Toolbar.s_PlayIcons[num], "CommandLeft", new GUILayoutOption[0]); + GUI.backgroundColor = Color.white; + if (GUI.changed) + { + Toolbar.TogglePlaying(); + GUIUtility.ExitGUI(); + } + GUI.changed = false; + bool isPaused = GUILayout.Toggle(EditorApplication.isPaused, Toolbar.s_PlayIcons[num + 1], "CommandMid", new GUILayoutOption[0]); + if (GUI.changed) + { + EditorApplication.isPaused = isPaused; + GUIUtility.ExitGUI(); + } + if (GUILayout.Button(Toolbar.s_PlayIcons[num + 2], "CommandRight", new GUILayoutOption[0])) + { + EditorApplication.Step(); + GUIUtility.ExitGUI(); + } + } + private void DoLayersDropDown() + { + GUIStyle style = "DropDown"; + Rect rect = GUILayoutUtility.GetRect(Toolbar.s_LayerContent, style); + if (EditorGUI.ButtonMouseDown(rect, Toolbar.s_LayerContent, FocusType.Passive, style)) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + if (LayerVisibilityWindow.ShowAtPosition(last)) + { + GUIUtility.ExitGUI(); + } + } + } + private void DoLayoutDropDown() + { + Rect rect = GUILayoutUtility.GetRect(Toolbar.s_LayerContent, "DropDown"); + if (EditorGUI.ButtonMouseDown(rect, GUIContent.Temp(Toolbar.lastLoadedLayoutName), FocusType.Passive, "DropDown")) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(rect.x, rect.y)); + rect.x = vector.x; + rect.y = vector.y; + EditorUtility.Internal_DisplayPopupMenu(rect, "Window/Layouts", this, 0); + } + GUILayout.EndHorizontal(); + } + private static void InternalWillTogglePlaymode() + { + InternalEditorUtility.RepaintAllViews(); + } + private static void TogglePlaying() + { + bool isPlaying = !EditorApplication.isPlaying; + EditorApplication.isPlaying = isPlaying; + Toolbar.InternalWillTogglePlaymode(); + } + internal static void RepaintToolbar() + { + if (Toolbar.get != null) + { + Toolbar.get.Repaint(); + } + } + public float CalcHeight() + { + return 30f; + } + } +} diff --git a/UnityEditor/UnityEditor/Tools.cs b/UnityEditor/UnityEditor/Tools.cs new file mode 100644 index 00000000..34df6a87 --- /dev/null +++ b/UnityEditor/UnityEditor/Tools.cs @@ -0,0 +1,518 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Tools : ScriptableObject + { + private static Tools s_Get; + internal static Tool s_LockedTool = Tool.None; + internal static ViewTool s_LockedViewTool = ViewTool.None; + internal static int s_ButtonDown = -1; + private PivotMode m_PivotMode; + private bool m_RectBlueprintMode; + private PivotRotation m_PivotRotation; + internal static bool s_Hidden = false; + internal static bool vertexDragging; + private static Vector3 s_LockHandlePosition; + private static bool s_LockHandlePositionActive = false; + private static int s_LockHandleRectAxis; + private static bool s_LockHandleRectAxisActive = false; + private int m_VisibleLayers = -1; + private int m_LockedLayers = -1; + internal Quaternion m_GlobalHandleRotation = Quaternion.identity; + private Tool currentTool = Tool.Move; + private ViewTool m_ViewTool = ViewTool.Pan; + private static int originalTool; + private static PrefKey kViewKey = new PrefKey("Tools/View", "q"); + private static PrefKey kMoveKey = new PrefKey("Tools/Move", "w"); + private static PrefKey kRotateKey = new PrefKey("Tools/Rotate", "e"); + private static PrefKey kScaleKey = new PrefKey("Tools/Scale", "r"); + private static PrefKey kRectKey = new PrefKey("Tools/Rect Handles", "t"); + private static PrefKey kPivotMode = new PrefKey("Tools/Pivot Mode", "z"); + private static PrefKey kPivotRotation = new PrefKey("Tools/Pivot Rotation", "x"); + internal static Vector3 handleOffset; + internal static Vector3 localHandleOffset; + private static Tools get + { + get + { + if (!Tools.s_Get) + { + Tools.s_Get = ScriptableObject.CreateInstance(); + Tools.s_Get.hideFlags = HideFlags.HideAndDontSave; + } + return Tools.s_Get; + } + } + public static Tool current + { + get + { + return (Tools.s_LockedTool != Tool.None) ? Tools.s_LockedTool : Tools.get.currentTool; + } + set + { + if (Tools.get.currentTool != value) + { + Tools.get.currentTool = value; + Tools.RepaintAllToolViews(); + } + } + } + public static ViewTool viewTool + { + get + { + Event current = Event.current; + if (Tools.viewToolActive) + { + if (Tools.s_LockedViewTool == ViewTool.None) + { + bool flag = current.control && Application.platform == RuntimePlatform.OSXEditor; + bool actionKey = EditorGUI.actionKey; + bool flag2 = !actionKey && !flag && !current.alt; + if ((Tools.s_ButtonDown <= 0 && flag2) || (Tools.s_ButtonDown <= 0 && actionKey) || Tools.s_ButtonDown == 2 || (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.in2DMode && (Tools.s_ButtonDown != 1 || !current.alt) && (Tools.s_ButtonDown > 0 || !flag))) + { + Tools.get.m_ViewTool = ViewTool.Pan; + } + else + { + if ((Tools.s_ButtonDown <= 0 && flag) || (Tools.s_ButtonDown == 1 && current.alt)) + { + Tools.get.m_ViewTool = ViewTool.Zoom; + } + else + { + if (Tools.s_ButtonDown <= 0 && current.alt) + { + Tools.get.m_ViewTool = ViewTool.Orbit; + } + else + { + if (Tools.s_ButtonDown == 1 && !current.alt) + { + Tools.get.m_ViewTool = ViewTool.FPS; + } + } + } + } + } + } + else + { + Tools.get.m_ViewTool = ViewTool.Pan; + } + return Tools.get.m_ViewTool; + } + set + { + Tools.get.m_ViewTool = value; + } + } + internal static bool viewToolActive + { + get + { + return (GUIUtility.hotControl == 0 || Tools.s_LockedViewTool != ViewTool.None) && (Tools.s_LockedViewTool != ViewTool.None || Tools.current == Tool.View || Event.current.alt || Tools.s_ButtonDown == 1 || Tools.s_ButtonDown == 2); + } + } + public static Vector3 handlePosition + { + get + { + Transform activeTransform = Selection.activeTransform; + if (!activeTransform) + { + return new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + if (Tools.s_LockHandlePositionActive) + { + return Tools.s_LockHandlePosition; + } + return Tools.GetHandlePosition(); + } + } + public static Rect handleRect + { + get + { + Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(Tools.handlePosition, Tools.handleRotation, Tools.rectBlueprintMode); + int rectAxisForViewDir = Tools.GetRectAxisForViewDir(bounds, Tools.handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); + return Tools.GetRectFromBoundsForAxis(bounds, rectAxisForViewDir); + } + } + public static Quaternion handleRectRotation + { + get + { + Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(Tools.handlePosition, Tools.handleRotation, Tools.rectBlueprintMode); + int rectAxisForViewDir = Tools.GetRectAxisForViewDir(bounds, Tools.handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); + return Tools.GetRectRotationForAxis(Tools.handleRotation, rectAxisForViewDir); + } + } + public static PivotMode pivotMode + { + get + { + return Tools.get.m_PivotMode; + } + set + { + if (Tools.get.m_PivotMode != value) + { + Tools.get.m_PivotMode = value; + EditorPrefs.SetInt("PivotMode", (int)Tools.pivotMode); + } + } + } + public static bool rectBlueprintMode + { + get + { + return Tools.get.m_RectBlueprintMode; + } + set + { + if (Tools.get.m_RectBlueprintMode != value) + { + Tools.get.m_RectBlueprintMode = value; + EditorPrefs.SetBool("RectBlueprintMode", Tools.rectBlueprintMode); + } + } + } + public static Quaternion handleRotation + { + get + { + PivotRotation pivotRotation = Tools.get.m_PivotRotation; + if (pivotRotation == PivotRotation.Local) + { + return Tools.handleLocalRotation; + } + if (pivotRotation != PivotRotation.Global) + { + return Quaternion.identity; + } + return Tools.get.m_GlobalHandleRotation; + } + set + { + if (Tools.get.m_PivotRotation == PivotRotation.Global) + { + Tools.get.m_GlobalHandleRotation = value; + } + } + } + public static PivotRotation pivotRotation + { + get + { + return Tools.get.m_PivotRotation; + } + set + { + if (Tools.get.m_PivotRotation != value) + { + Tools.get.m_PivotRotation = value; + EditorPrefs.SetInt("PivotRotation", (int)Tools.pivotRotation); + } + } + } + public static bool hidden + { + get + { + return Tools.s_Hidden; + } + set + { + Tools.s_Hidden = value; + } + } + public static int visibleLayers + { + get + { + return Tools.get.m_VisibleLayers; + } + set + { + if (Tools.get.m_VisibleLayers != value) + { + Tools.get.m_VisibleLayers = value; + EditorGUIUtility.SetVisibleLayers(value); + EditorPrefs.SetInt("VisibleLayers", Tools.visibleLayers); + } + } + } + public static int lockedLayers + { + get + { + return Tools.get.m_LockedLayers; + } + set + { + if (Tools.get.m_LockedLayers != value) + { + Tools.get.m_LockedLayers = value; + EditorGUIUtility.SetLockedLayers(value); + EditorPrefs.SetInt("LockedLayers", Tools.lockedLayers); + } + } + } + internal static Quaternion handleLocalRotation + { + get + { + Transform activeTransform = Selection.activeTransform; + if (!activeTransform) + { + return Quaternion.identity; + } + if (Tools.rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(activeTransform)) + { + return activeTransform.parent.rotation; + } + return activeTransform.rotation; + } + } + internal static Vector3 GetHandlePosition() + { + Transform activeTransform = Selection.activeTransform; + if (!activeTransform) + { + return new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + Vector3 b = Tools.handleOffset + Tools.handleRotation * Tools.localHandleOffset; + PivotMode pivotMode = Tools.get.m_PivotMode; + if (pivotMode != PivotMode.Center) + { + if (pivotMode != PivotMode.Pivot) + { + return new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + } + if (Tools.current == Tool.Rect && Tools.rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(activeTransform)) + { + return activeTransform.parent.TransformPoint(new Vector3(activeTransform.localPosition.x, activeTransform.localPosition.y, 0f)) + b; + } + return activeTransform.position + b; + } + else + { + if (Tools.current == Tool.Rect) + { + return Tools.handleRotation * InternalEditorUtility.CalculateSelectionBoundsInSpace(Vector3.zero, Tools.handleRotation, Tools.rectBlueprintMode).center + b; + } + return InternalEditorUtility.CalculateSelectionBounds(true).center + b; + } + } + private static int GetRectAxisForViewDir(Bounds bounds, Quaternion rotation, Vector3 viewDir) + { + if (Tools.s_LockHandleRectAxisActive) + { + return Tools.s_LockHandleRectAxis; + } + if (viewDir == Vector3.zero) + { + return 2; + } + if (bounds.size == Vector3.zero) + { + bounds.size = Vector3.one; + } + int result = -1; + float num = -1f; + for (int i = 0; i < 3; i++) + { + Vector3 zero = Vector3.zero; + Vector3 zero2 = Vector3.zero; + int index = (i + 1) % 3; + int index2 = (i + 2) % 3; + zero[index] = bounds.size[index]; + zero2[index2] = bounds.size[index2]; + float magnitude = Vector3.Cross(Vector3.ProjectOnPlane(rotation * zero, viewDir), Vector3.ProjectOnPlane(rotation * zero2, viewDir)).magnitude; + if (magnitude > num) + { + num = magnitude; + result = i; + } + } + return result; + } + private static Rect GetRectFromBoundsForAxis(Bounds bounds, int axis) + { + switch (axis) + { + case 0: + return new Rect(-bounds.max.z, bounds.min.y, bounds.size.z, bounds.size.y); + case 1: + return new Rect(bounds.min.x, -bounds.max.z, bounds.size.x, bounds.size.z); + } + return new Rect(bounds.min.x, bounds.min.y, bounds.size.x, bounds.size.y); + } + private static Quaternion GetRectRotationForAxis(Quaternion rotation, int axis) + { + switch (axis) + { + case 0: + return rotation * Quaternion.Euler(0f, 90f, 0f); + case 1: + return rotation * Quaternion.Euler(-90f, 0f, 0f); + } + return rotation; + } + internal static void LockHandleRectRotation() + { + Bounds bounds = InternalEditorUtility.CalculateSelectionBoundsInSpace(Tools.handlePosition, Tools.handleRotation, Tools.rectBlueprintMode); + Tools.s_LockHandleRectAxis = Tools.GetRectAxisForViewDir(bounds, Tools.handleRotation, SceneView.currentDrawingSceneView.camera.transform.forward); + Tools.s_LockHandleRectAxisActive = true; + } + internal static void UnlockHandleRectRotation() + { + Tools.s_LockHandleRectAxisActive = false; + } + internal static int GetPivotMode() + { + return (int)Tools.pivotMode; + } + private void OnEnable() + { + Tools.s_Get = this; + EditorApplication.globalEventHandler = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.globalEventHandler, new EditorApplication.CallbackFunction(Tools.ControlsHack)); + Tools.pivotMode = (PivotMode)EditorPrefs.GetInt("PivotMode", 0); + Tools.rectBlueprintMode = EditorPrefs.GetBool("RectBlueprintMode", false); + Tools.pivotRotation = (PivotRotation)EditorPrefs.GetInt("PivotRotation", 0); + Tools.visibleLayers = EditorPrefs.GetInt("VisibleLayers", -1); + Tools.lockedLayers = EditorPrefs.GetInt("LockedLayers", 0); + } + private void OnDisable() + { + EditorApplication.globalEventHandler = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.globalEventHandler, new EditorApplication.CallbackFunction(Tools.ControlsHack)); + } + internal static void OnSelectionChange() + { + Tools.ResetGlobalHandleRotation(); + Tools.localHandleOffset = Vector3.zero; + } + internal static void ResetGlobalHandleRotation() + { + Tools.get.m_GlobalHandleRotation = Quaternion.identity; + } + internal static void ControlsHack() + { + Event current = Event.current; + if (Tools.kViewKey.activated) + { + Tools.current = Tool.View; + Tools.ResetGlobalHandleRotation(); + current.Use(); + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + else + { + Debug.LogError("Press Play twice for sceneview keyboard shortcuts to work"); + } + } + if (Tools.kMoveKey.activated) + { + Tools.current = Tool.Move; + Tools.ResetGlobalHandleRotation(); + current.Use(); + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + else + { + Debug.LogError("Press Play twice for sceneview keyboard shortcuts to work"); + } + } + if (Tools.kRotateKey.activated) + { + Tools.current = Tool.Rotate; + Tools.ResetGlobalHandleRotation(); + current.Use(); + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + else + { + Debug.LogError("Press Play twice for sceneview keyboard shortcuts to work"); + } + } + if (Tools.kScaleKey.activated) + { + Tools.current = Tool.Scale; + Tools.ResetGlobalHandleRotation(); + current.Use(); + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + else + { + Debug.LogError("Press Play twice for sceneview keyboard shortcuts to work"); + } + } + if (Tools.kRectKey.activated) + { + Tools.current = Tool.Rect; + Tools.ResetGlobalHandleRotation(); + current.Use(); + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + else + { + Debug.LogError("Press Play twice for sceneview keyboard shortcuts to work"); + } + } + if (Tools.kPivotMode.activated) + { + Tools.pivotMode = PivotMode.Pivot - (int)Tools.pivotMode; + Tools.ResetGlobalHandleRotation(); + current.Use(); + Tools.RepaintAllToolViews(); + } + if (Tools.kPivotRotation.activated) + { + Tools.pivotRotation = PivotRotation.Global - (int)Tools.pivotRotation; + Tools.ResetGlobalHandleRotation(); + current.Use(); + Tools.RepaintAllToolViews(); + } + } + internal static void RepaintAllToolViews() + { + if (Toolbar.get) + { + Toolbar.get.Repaint(); + } + SceneView.RepaintAll(); + InspectorWindow.RepaintAllInspectors(); + } + internal static void HandleKeys() + { + Tools.ControlsHack(); + } + internal static void LockHandlePosition(Vector3 pos) + { + Tools.s_LockHandlePosition = pos; + Tools.s_LockHandlePositionActive = true; + } + internal static void LockHandlePosition() + { + Tools.LockHandlePosition(Tools.handlePosition); + } + internal static void UnlockHandlePosition() + { + Tools.s_LockHandlePositionActive = false; + } + } +} diff --git a/UnityEditor/UnityEditor/TooltipView.cs b/UnityEditor/UnityEditor/TooltipView.cs new file mode 100644 index 00000000..173d8c4b --- /dev/null +++ b/UnityEditor/UnityEditor/TooltipView.cs @@ -0,0 +1,82 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TooltipView : GUIView + { + private const float MAX_WIDTH = 300f; + private GUIContent m_tooltip = new GUIContent(); + private Vector2 m_optimalSize; + private GUIStyle m_Style; + private Rect m_hoverRect; + private ContainerWindow m_tooltipContainer; + private static TooltipView s_guiView; + private void OnEnable() + { + TooltipView.s_guiView = this; + } + private void OnDisable() + { + TooltipView.s_guiView = null; + } + private void OnGUI() + { + if (this.m_tooltipContainer != null) + { + GUI.Box(new Rect(0f, 0f, this.m_optimalSize.x, this.m_optimalSize.y), this.m_tooltip, this.m_Style); + } + } + private void Setup(string tooltip, Rect rect) + { + this.m_hoverRect = rect; + this.m_tooltip.text = tooltip; + if (this.m_Style == null) + { + this.m_Style = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle("Tooltip"); + } + this.m_Style.wordWrap = false; + this.m_optimalSize = this.m_Style.CalcSize(this.m_tooltip); + if (this.m_optimalSize.x > 300f) + { + this.m_Style.wordWrap = true; + this.m_optimalSize.x = 300f; + this.m_optimalSize.y = this.m_Style.CalcHeight(this.m_tooltip, 300f); + } + this.m_tooltipContainer.position = new Rect(Mathf.Floor(this.m_hoverRect.x + this.m_hoverRect.width / 2f - this.m_optimalSize.x / 2f), Mathf.Floor(this.m_hoverRect.y + this.m_hoverRect.height + 10f), this.m_optimalSize.x, this.m_optimalSize.y); + base.position = new Rect(0f, 0f, this.m_optimalSize.x, this.m_optimalSize.y); + this.m_tooltipContainer.ShowPopup(); + this.m_tooltipContainer.SetAlpha(1f); + TooltipView.s_guiView.mouseRayInvisible = true; + } + public static void Show(string tooltip, Rect rect) + { + if (TooltipView.s_guiView == null) + { + TooltipView.s_guiView = ScriptableObject.CreateInstance(); + TooltipView.s_guiView.m_tooltipContainer = ScriptableObject.CreateInstance(); + TooltipView.s_guiView.m_tooltipContainer.m_DontSaveToLayout = true; + TooltipView.s_guiView.m_tooltipContainer.mainView = TooltipView.s_guiView; + TooltipView.s_guiView.m_tooltipContainer.SetMinMaxSizes(new Vector2(10f, 10f), new Vector2(2000f, 2000f)); + } + if (TooltipView.s_guiView.m_tooltip.text == tooltip && rect == TooltipView.s_guiView.m_hoverRect) + { + return; + } + TooltipView.s_guiView.Setup(tooltip, rect); + } + public static void Close() + { + if (TooltipView.s_guiView != null) + { + TooltipView.s_guiView.m_tooltipContainer.Close(); + } + } + public static void SetAlpha(float percent) + { + if (TooltipView.s_guiView != null) + { + TooltipView.s_guiView.m_tooltipContainer.SetAlpha(percent); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TransformInspector.cs b/UnityEditor/UnityEditor/TransformInspector.cs new file mode 100644 index 00000000..44435bbc --- /dev/null +++ b/UnityEditor/UnityEditor/TransformInspector.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Transform))] + internal class TransformInspector : Editor + { + private class Contents + { + public GUIContent positionContent = new GUIContent("Position", "The local position of this Game Object relative to the parent."); + public GUIContent scaleContent = new GUIContent("Scale", "The local scaling of this Game Object relative to the parent."); + public GUIContent[] subLabels = new GUIContent[] + { + new GUIContent("X"), + new GUIContent("Y") + }; + public string floatingPointWarning = "Due to floating-point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range."; + } + private SerializedProperty m_Position; + private SerializedProperty m_Scale; + private TransformRotationGUI m_RotationGUI; + private static TransformInspector.Contents s_Contents; + public void OnEnable() + { + this.m_Position = base.serializedObject.FindProperty("m_LocalPosition"); + this.m_Scale = base.serializedObject.FindProperty("m_LocalScale"); + if (this.m_RotationGUI == null) + { + this.m_RotationGUI = new TransformRotationGUI(); + } + this.m_RotationGUI.OnEnable(base.serializedObject.FindProperty("m_LocalRotation"), new GUIContent("Rotation")); + } + public override void OnInspectorGUI() + { + if (TransformInspector.s_Contents == null) + { + TransformInspector.s_Contents = new TransformInspector.Contents(); + } + if (!EditorGUIUtility.wideMode) + { + EditorGUIUtility.wideMode = true; + EditorGUIUtility.labelWidth = EditorGUIUtility.currentViewWidth - 212f; + } + base.serializedObject.Update(); + this.Inspector3D(); + Transform transform = this.target as Transform; + Vector3 position = transform.position; + if (Mathf.Abs(position.x) > 100000f || Mathf.Abs(position.y) > 100000f || Mathf.Abs(position.z) > 100000f) + { + EditorGUILayout.HelpBox(TransformInspector.s_Contents.floatingPointWarning, MessageType.Warning); + } + base.serializedObject.ApplyModifiedProperties(); + } + private void Inspector3D() + { + EditorGUILayout.PropertyField(this.m_Position, TransformInspector.s_Contents.positionContent, new GUILayoutOption[0]); + this.m_RotationGUI.RotationField(); + EditorGUILayout.PropertyField(this.m_Scale, TransformInspector.s_Contents.scaleContent, new GUILayoutOption[0]); + } + } +} diff --git a/UnityEditor/UnityEditor/TransformManipulator.cs b/UnityEditor/UnityEditor/TransformManipulator.cs new file mode 100644 index 00000000..5c039cdd --- /dev/null +++ b/UnityEditor/UnityEditor/TransformManipulator.cs @@ -0,0 +1,321 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class TransformManipulator + { + private struct TransformData + { + public static Quaternion[] s_Alignments = new Quaternion[] + { + Quaternion.LookRotation(Vector3.right, Vector3.up), + Quaternion.LookRotation(Vector3.right, Vector3.forward), + Quaternion.LookRotation(Vector3.up, Vector3.forward), + Quaternion.LookRotation(Vector3.up, Vector3.right), + Quaternion.LookRotation(Vector3.forward, Vector3.right), + Quaternion.LookRotation(Vector3.forward, Vector3.up) + }; + public Transform transform; + public Vector3 position; + public Vector3 localPosition; + public Quaternion rotation; + public Vector3 scale; + public RectTransform rectTransform; + public Rect rect; + public Vector2 anchoredPosition; + public Vector2 sizeDelta; + public static TransformManipulator.TransformData GetData(Transform t) + { + TransformManipulator.TransformData result = default(TransformManipulator.TransformData); + result.transform = t; + result.position = t.position; + result.localPosition = t.localPosition; + result.rotation = t.rotation; + result.scale = t.localScale; + result.rectTransform = t.GetComponent(); + if (result.rectTransform != null) + { + result.sizeDelta = result.rectTransform.sizeDelta; + result.rect = result.rectTransform.rect; + result.anchoredPosition = result.rectTransform.anchoredPosition; + } + return result; + } + private Quaternion GetRefAlignment(Quaternion targetRotation, Quaternion ownRotation) + { + float num = float.NegativeInfinity; + Quaternion result = Quaternion.identity; + for (int i = 0; i < TransformManipulator.TransformData.s_Alignments.Length; i++) + { + float num2 = Mathf.Min(new float[] + { + Mathf.Abs(Vector3.Dot(targetRotation * Vector3.right, ownRotation * TransformManipulator.TransformData.s_Alignments[i] * Vector3.right)), + Mathf.Abs(Vector3.Dot(targetRotation * Vector3.up, ownRotation * TransformManipulator.TransformData.s_Alignments[i] * Vector3.up)), + Mathf.Abs(Vector3.Dot(targetRotation * Vector3.forward, ownRotation * TransformManipulator.TransformData.s_Alignments[i] * Vector3.forward)) + }); + if (num2 > num) + { + num = num2; + result = TransformManipulator.TransformData.s_Alignments[i]; + } + } + return result; + } + public void SetScaleDelta(Vector3 scaleDelta, Vector3 scalePivot, Quaternion scaleRotation, bool preferRectResize) + { + this.SetPosition(scaleRotation * Vector3.Scale(Quaternion.Inverse(scaleRotation) * (this.position - scalePivot), scaleDelta) + scalePivot); + Vector3 minDragDifference = ManipulationToolUtility.minDragDifference; + if (this.transform.parent != null) + { + minDragDifference.x /= this.transform.parent.lossyScale.x; + minDragDifference.y /= this.transform.parent.lossyScale.y; + minDragDifference.z /= this.transform.parent.lossyScale.z; + } + Quaternion ownRotation = (!Tools.rectBlueprintMode || !InternalEditorUtility.SupportsRectLayout(this.transform)) ? this.rotation : this.transform.parent.rotation; + Quaternion refAlignment = this.GetRefAlignment(scaleRotation, ownRotation); + scaleDelta = refAlignment * scaleDelta; + scaleDelta = Vector3.Scale(scaleDelta, refAlignment * Vector3.one); + if (preferRectResize && this.rectTransform != null) + { + Vector2 vector = this.sizeDelta + Vector2.Scale(this.rect.size, scaleDelta) - this.rect.size; + vector.x = MathUtils.RoundBasedOnMinimumDifference(vector.x, minDragDifference.x); + vector.y = MathUtils.RoundBasedOnMinimumDifference(vector.y, minDragDifference.y); + this.rectTransform.sizeDelta = vector; + if (this.rectTransform.drivenByObject != null) + { + RectTransform.SendReapplyDrivenProperties(this.rectTransform); + } + } + else + { + this.transform.localScale = Vector3.Scale(this.scale, scaleDelta); + } + } + private void SetPosition(Vector3 newPosition) + { + this.SetPositionDelta(newPosition - this.position); + } + public void SetPositionDelta(Vector3 positionDelta) + { + Vector3 vector = positionDelta; + Vector3 minDragDifference = ManipulationToolUtility.minDragDifference; + if (this.transform.parent != null) + { + vector = this.transform.parent.InverseTransformVector(vector); + minDragDifference.x /= this.transform.parent.lossyScale.x; + minDragDifference.y /= this.transform.parent.lossyScale.y; + minDragDifference.z /= this.transform.parent.lossyScale.z; + } + if (this.rectTransform == null) + { + Vector3 vector2 = this.localPosition + vector; + vector2.x = MathUtils.RoundBasedOnMinimumDifference(vector2.x, minDragDifference.x); + vector2.y = MathUtils.RoundBasedOnMinimumDifference(vector2.y, minDragDifference.y); + vector2.z = MathUtils.RoundBasedOnMinimumDifference(vector2.z, minDragDifference.z); + this.transform.localPosition = vector2; + } + else + { + Vector3 vector3 = this.localPosition + vector; + vector3.z = MathUtils.RoundBasedOnMinimumDifference(vector3.z, minDragDifference.z); + this.transform.localPosition = vector3; + Vector2 vector4 = this.anchoredPosition + vector; + vector4.x = MathUtils.RoundBasedOnMinimumDifference(vector4.x, minDragDifference.x); + vector4.y = MathUtils.RoundBasedOnMinimumDifference(vector4.y, minDragDifference.y); + this.rectTransform.anchoredPosition = vector4; + if (this.rectTransform.drivenByObject != null) + { + RectTransform.SendReapplyDrivenProperties(this.rectTransform); + } + } + } + public void DebugAlignment(Quaternion targetRotation) + { + Quaternion rhs = Quaternion.identity; + if (!TransformManipulator.individualSpace) + { + rhs = this.GetRefAlignment(targetRotation, this.rotation); + } + Vector3 a = this.transform.position; + float d = HandleUtility.GetHandleSize(a) * 0.25f; + Color color = Handles.color; + Handles.color = Color.red; + Vector3 b = this.rotation * rhs * Vector3.right * d; + Handles.DrawLine(a - b, a + b); + Handles.color = Color.green; + b = this.rotation * rhs * Vector3.up * d; + Handles.DrawLine(a - b, a + b); + Handles.color = Color.blue; + b = this.rotation * rhs * Vector3.forward * d; + Handles.DrawLine(a - b, a + b); + Handles.color = color; + } + } + private static EventType s_EventTypeBefore = EventType.Ignore; + private static TransformManipulator.TransformData[] s_MouseDownState = null; + private static Vector3 s_StartHandlePosition = Vector3.zero; + private static Vector3 s_StartLocalHandleOffset = Vector3.zero; + private static int s_HotControl = 0; + private static bool s_LockHandle = false; + public static Vector3 mouseDownHandlePosition + { + get + { + return TransformManipulator.s_StartHandlePosition; + } + } + public static bool active + { + get + { + return TransformManipulator.s_MouseDownState != null; + } + } + public static bool individualSpace + { + get + { + return Tools.pivotRotation == PivotRotation.Local && Tools.pivotMode == PivotMode.Pivot; + } + } + private static void BeginEventCheck() + { + TransformManipulator.s_EventTypeBefore = Event.current.GetTypeForControl(TransformManipulator.s_HotControl); + } + private static EventType EndEventCheck() + { + EventType eventType = (TransformManipulator.s_EventTypeBefore == Event.current.GetTypeForControl(TransformManipulator.s_HotControl)) ? EventType.Ignore : TransformManipulator.s_EventTypeBefore; + TransformManipulator.s_EventTypeBefore = EventType.Ignore; + if (eventType == EventType.MouseDown) + { + TransformManipulator.s_HotControl = GUIUtility.hotControl; + } + else + { + if (eventType == EventType.MouseUp) + { + TransformManipulator.s_HotControl = 0; + } + } + return eventType; + } + public static void BeginManipulationHandling(bool lockHandleWhileDragging) + { + TransformManipulator.BeginEventCheck(); + TransformManipulator.s_LockHandle = lockHandleWhileDragging; + } + public static EventType EndManipulationHandling() + { + EventType eventType = TransformManipulator.EndEventCheck(); + if (eventType == EventType.MouseDown) + { + TransformManipulator.RecordMouseDownState(Selection.transforms); + TransformManipulator.s_StartHandlePosition = Tools.handlePosition; + TransformManipulator.s_StartLocalHandleOffset = Tools.localHandleOffset; + if (TransformManipulator.s_LockHandle) + { + Tools.LockHandlePosition(); + } + Tools.LockHandleRectRotation(); + } + else + { + if (TransformManipulator.s_MouseDownState != null && (eventType == EventType.MouseUp || GUIUtility.hotControl != TransformManipulator.s_HotControl)) + { + TransformManipulator.s_MouseDownState = null; + if (TransformManipulator.s_LockHandle) + { + Tools.UnlockHandlePosition(); + } + Tools.UnlockHandleRectRotation(); + ManipulationToolUtility.DisableMinDragDifference(); + } + } + return eventType; + } + private static void RecordMouseDownState(Transform[] transforms) + { + TransformManipulator.s_MouseDownState = new TransformManipulator.TransformData[transforms.Length]; + for (int i = 0; i < transforms.Length; i++) + { + TransformManipulator.s_MouseDownState[i] = TransformManipulator.TransformData.GetData(transforms[i]); + } + } + private static void SetLocalHandleOffsetScaleDelta(Vector3 scaleDelta, Quaternion pivotRotation) + { + Quaternion rotation = Quaternion.Inverse(Tools.handleRotation) * pivotRotation; + Tools.localHandleOffset = Vector3.Scale(Vector3.Scale(TransformManipulator.s_StartLocalHandleOffset, rotation * scaleDelta), rotation * Vector3.one); + } + public static void SetScaleDelta(Vector3 scaleDelta, Quaternion pivotRotation) + { + if (TransformManipulator.s_MouseDownState == null) + { + return; + } + TransformManipulator.SetLocalHandleOffsetScaleDelta(scaleDelta, pivotRotation); + for (int i = 0; i < TransformManipulator.s_MouseDownState.Length; i++) + { + TransformManipulator.TransformData transformData = TransformManipulator.s_MouseDownState[i]; + Undo.RecordObject(transformData.transform, "Scale"); + } + Vector3 scalePivot = Tools.handlePosition; + for (int j = 0; j < TransformManipulator.s_MouseDownState.Length; j++) + { + if (Tools.pivotMode == PivotMode.Pivot) + { + scalePivot = TransformManipulator.s_MouseDownState[j].position; + } + if (TransformManipulator.individualSpace) + { + pivotRotation = TransformManipulator.s_MouseDownState[j].rotation; + } + TransformManipulator.s_MouseDownState[j].SetScaleDelta(scaleDelta, scalePivot, pivotRotation, false); + } + } + public static void SetResizeDelta(Vector3 scaleDelta, Vector3 pivotPosition, Quaternion pivotRotation) + { + if (TransformManipulator.s_MouseDownState == null) + { + return; + } + TransformManipulator.SetLocalHandleOffsetScaleDelta(scaleDelta, pivotRotation); + for (int i = 0; i < TransformManipulator.s_MouseDownState.Length; i++) + { + TransformManipulator.TransformData transformData = TransformManipulator.s_MouseDownState[i]; + Undo.RecordObject((!(transformData.rectTransform != null)) ? transformData.transform : transformData.rectTransform, "Resize"); + } + for (int j = 0; j < TransformManipulator.s_MouseDownState.Length; j++) + { + TransformManipulator.s_MouseDownState[j].SetScaleDelta(scaleDelta, pivotPosition, pivotRotation, true); + } + } + public static void SetPositionDelta(Vector3 positionDelta) + { + if (TransformManipulator.s_MouseDownState == null) + { + return; + } + for (int i = 0; i < TransformManipulator.s_MouseDownState.Length; i++) + { + TransformManipulator.TransformData transformData = TransformManipulator.s_MouseDownState[i]; + Undo.RecordObject((!(transformData.rectTransform != null)) ? transformData.transform : transformData.rectTransform, "Move"); + } + for (int j = 0; j < TransformManipulator.s_MouseDownState.Length; j++) + { + TransformManipulator.s_MouseDownState[j].SetPositionDelta(positionDelta); + } + } + public static void DebugAlignment(Quaternion targetRotation) + { + if (TransformManipulator.s_MouseDownState == null) + { + return; + } + for (int i = 0; i < TransformManipulator.s_MouseDownState.Length; i++) + { + TransformManipulator.s_MouseDownState[i].DebugAlignment(targetRotation); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TransformRotationGUI.cs b/UnityEditor/UnityEditor/TransformRotationGUI.cs new file mode 100644 index 00000000..0d47f1c1 --- /dev/null +++ b/UnityEditor/UnityEditor/TransformRotationGUI.cs @@ -0,0 +1,70 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class TransformRotationGUI + { + private GUIContent rotationContent = new GUIContent("Rotation", "The local rotation of this Game Object relative to the parent."); + private Vector3 m_EulerAngles; + private Quaternion m_OldQuaternion = new Quaternion(1234f, 1000f, 4321f, -1000f); + private SerializedProperty m_Rotation; + private UnityEngine.Object[] targets; + private static int s_FoldoutHash = "Foldout".GetHashCode(); + public void OnEnable(SerializedProperty m_Rotation, GUIContent label) + { + this.m_Rotation = m_Rotation; + this.targets = m_Rotation.serializedObject.targetObjects; + this.rotationContent = label; + } + public void RotationField() + { + this.RotationField(false); + } + public void RotationField(bool disabled) + { + Transform transform = this.targets[0] as Transform; + Quaternion localRotation = transform.localRotation; + if (this.m_OldQuaternion.x != localRotation.x || this.m_OldQuaternion.y != localRotation.y || this.m_OldQuaternion.z != localRotation.z || this.m_OldQuaternion.w != localRotation.w) + { + this.m_EulerAngles = transform.localEulerAngles; + this.m_OldQuaternion = localRotation; + } + bool flag = false; + UnityEngine.Object[] array = this.targets; + for (int i = 0; i < array.Length; i++) + { + Transform transform2 = (Transform)array[i]; + flag |= (transform2.localEulerAngles != this.m_EulerAngles); + } + Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (float)((!EditorGUIUtility.wideMode) ? 2 : 1), new GUILayoutOption[0]); + GUIContent label = EditorGUI.BeginProperty(rect, this.rotationContent, this.m_Rotation); + EditorGUI.showMixedValue = flag; + EditorGUI.BeginChangeCheck(); + int controlID = GUIUtility.GetControlID(TransformRotationGUI.s_FoldoutHash, EditorGUIUtility.native, rect); + rect = EditorGUI.MultiFieldPrefixLabel(rect, controlID, label, 3); + rect.height = EditorGUIUtility.singleLineHeight; + EditorGUI.BeginDisabledGroup(disabled); + this.m_EulerAngles = EditorGUI.Vector3Field(rect, GUIContent.none, this.m_EulerAngles); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(this.targets, "Inspector"); + UnityEngine.Object[] array2 = this.targets; + for (int j = 0; j < array2.Length; j++) + { + Transform transform3 = (Transform)array2[j]; + transform3.localEulerAngles = this.m_EulerAngles; + if (transform3.parent != null) + { + transform3.SendTransformChangedScale(); + } + } + this.m_Rotation.serializedObject.SetIsDifferentCacheDirty(); + this.m_OldQuaternion = localRotation; + } + EditorGUI.showMixedValue = false; + EditorGUI.EndProperty(); + } + } +} diff --git a/UnityEditor/UnityEditor/TransformSort.cs b/UnityEditor/UnityEditor/TransformSort.cs new file mode 100644 index 00000000..b53d287e --- /dev/null +++ b/UnityEditor/UnityEditor/TransformSort.cs @@ -0,0 +1,17 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class TransformSort : BaseHierarchySort + { + private const string kDefaultSorting = "DefaultSorting"; + private GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("DefaultSorting"), "Transform child order"); + public override GUIContent content + { + get + { + return this.m_Content; + } + } + } +} diff --git a/UnityEditor/UnityEditor/TransformX.cs b/UnityEditor/UnityEditor/TransformX.cs new file mode 100644 index 00000000..612053d9 --- /dev/null +++ b/UnityEditor/UnityEditor/TransformX.cs @@ -0,0 +1,11 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct TransformX + { + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + } +} diff --git a/UnityEditor/UnityEditor/TransitionPreview.cs b/UnityEditor/UnityEditor/TransitionPreview.cs new file mode 100644 index 00000000..ea5062d7 --- /dev/null +++ b/UnityEditor/UnityEditor/TransitionPreview.cs @@ -0,0 +1,630 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class TransitionPreview + { + private class ParameterInfo + { + public string m_Name; + public float m_Value; + } + private class TransitionInfo + { + private State m_SrcState; + private State m_DstState; + private float m_TransitionDuration; + private float m_TransitionOffset; + private float m_ExitTime; + public TransitionInfo() + { + this.Init(); + } + public bool IsEqual(TransitionPreview.TransitionInfo info) + { + return this.m_SrcState == info.m_SrcState && this.m_DstState == info.m_DstState && Mathf.Approximately(this.m_TransitionDuration, info.m_TransitionDuration) && Mathf.Approximately(this.m_TransitionOffset, info.m_TransitionOffset) && Mathf.Approximately(this.m_ExitTime, info.m_ExitTime); + } + private void Init() + { + this.m_SrcState = null; + this.m_DstState = null; + this.m_TransitionDuration = 0f; + this.m_TransitionOffset = 0f; + this.m_ExitTime = 0.5f; + } + public void Set(Transition transition, State srcState) + { + if (transition != null) + { + if (srcState != null) + { + this.m_SrcState = srcState; + } + else + { + this.m_SrcState = transition.srcState; + } + this.m_DstState = transition.dstState; + this.m_TransitionDuration = transition.duration; + this.m_TransitionOffset = transition.offset; + this.m_ExitTime = 0.5f; + for (int i = 0; i < transition.conditionCount; i++) + { + AnimatorCondition condition = transition.GetCondition(i); + if (condition.mode == TransitionConditionMode.ExitTime) + { + this.m_ExitTime = condition.exitTime; + break; + } + } + } + else + { + this.Init(); + } + } + } + private AvatarPreview m_AvatarPreview; + private Timeline m_Timeline; + private AnimatorController m_Controller; + private StateMachine m_StateMachine; + private List m_ParameterMinMax = new List(); + private List m_ParameterInfoList; + private Transition m_RefTransition; + private TransitionPreview.TransitionInfo m_RefTransitionInfo = new TransitionPreview.TransitionInfo(); + private Transition m_Transition; + private State m_SrcState; + private State m_DstState; + private State m_RefSrcState; + private bool m_ShowBlendValue; + private bool m_MustResample = true; + private bool m_MustSampleMotions; + private float m_LastEvalTime = -1f; + private AvatarMask m_LayerMask; + private int m_LayerIndex; + private int m_MotionSetIndex; + private float m_ExitTime = 0.5f; + private float m_LeftStateWeightA; + private float m_LeftStateWeightB = 1f; + private float m_LeftStateTimeA; + private float m_LeftStateTimeB = 1f; + private float m_RightStateWeightA; + private float m_RightStateWeightB = 1f; + private float m_RightStateTimeA; + private float m_RightStateTimeB = 1f; + private List m_SrcPivotList = new List(); + private List m_DstPivotList = new List(); + public bool mustResample + { + get + { + return this.m_MustResample; + } + set + { + this.m_MustResample = value; + } + } + private int FindParameterInfo(List parameterInfoList, string name) + { + int num = -1; + int num2 = 0; + while (num2 < parameterInfoList.Count && num == -1) + { + if (parameterInfoList[num2].m_Name == name) + { + num = num2; + } + num2++; + } + return num; + } + private bool HasExitTime(Transition t) + { + for (int i = 0; i < t.conditionCount; i++) + { + if (t.GetCondition(i).mode == TransitionConditionMode.ExitTime) + { + return true; + } + } + return false; + } + private void SetExitTime(Transition t, float time) + { + for (int i = 0; i < t.conditionCount; i++) + { + AnimatorCondition condition = t.GetCondition(i); + if (condition.mode == TransitionConditionMode.ExitTime) + { + condition.exitTime = time; + break; + } + } + this.m_ExitTime = time; + } + private float GetExitTime(Transition t) + { + for (int i = 0; i < t.conditionCount; i++) + { + AnimatorCondition condition = t.GetCondition(i); + if (condition.mode == TransitionConditionMode.ExitTime) + { + return condition.exitTime; + } + } + return this.m_ExitTime; + } + private void CopyStateForPreview(State src, ref State dst) + { + dst.name = src.name; + dst.iKOnFeet = src.iKOnFeet; + dst.speed = src.speed; + dst.mirror = src.mirror; + dst.SetMotionInternal(src.GetMotionInternal(this.m_MotionSetIndex)); + } + private void CopyTransitionForPreview(Transition src, ref Transition dst) + { + if (src != null) + { + dst.duration = src.duration; + dst.offset = src.offset; + this.SetExitTime(dst, this.GetExitTime(src)); + } + } + private bool MustResample(TransitionPreview.TransitionInfo info) + { + return this.mustResample || !info.IsEqual(this.m_RefTransitionInfo); + } + private void WriteParametersInController() + { + if (this.m_Controller) + { + int parameterCount = this.m_Controller.parameterCount; + for (int i = 0; i < parameterCount; i++) + { + string parameterName = this.m_Controller.GetParameterName(i); + int num = this.FindParameterInfo(this.m_ParameterInfoList, parameterName); + if (num != -1) + { + this.m_AvatarPreview.Animator.SetFloat(parameterName, this.m_ParameterInfoList[num].m_Value); + } + } + } + } + private void ResampleTransition(Transition transition, AvatarMask layerMask, TransitionPreview.TransitionInfo info, Animator previewObject) + { + this.m_MustResample = false; + bool flag = this.m_RefTransition != transition; + this.m_RefTransition = transition; + this.m_RefTransitionInfo = info; + this.m_LayerMask = layerMask; + if (this.m_AvatarPreview != null) + { + this.m_AvatarPreview.OnDestroy(); + this.m_AvatarPreview = null; + } + this.ClearController(); + Motion motion = (!transition.srcState) ? this.m_RefSrcState.GetMotionInternal(this.m_MotionSetIndex) : transition.srcState.GetMotionInternal(this.m_MotionSetIndex); + this.Init(previewObject, (!(motion != null)) ? transition.dstState.GetMotionInternal(this.m_MotionSetIndex) : motion); + if (this.m_Controller == null) + { + return; + } + this.m_AvatarPreview.Animator.allowConstantClipSamplingOptimization = false; + this.m_StateMachine.defaultState = this.m_DstState; + this.m_Transition.mute = true; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + this.m_AvatarPreview.Animator.Update(1E-05f); + this.WriteParametersInController(); + this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); + float length = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; + this.m_StateMachine.defaultState = this.m_SrcState; + this.m_Transition.mute = false; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + this.m_AvatarPreview.Animator.Update(1E-05f); + this.WriteParametersInController(); + this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); + float length2 = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex).length; + if (this.m_LayerIndex > 0) + { + this.m_AvatarPreview.Animator.stabilizeFeet = false; + } + float num = length2 * this.GetExitTime(this.m_RefTransition) + length2 * this.m_Transition.duration + length; + if (num > 2000f) + { + Debug.LogWarning("Transition duration is longer than 2000 second, Disabling previewer."); + return; + } + float num2 = (length2 <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length2 / 300f, 0.0333333351f), length2 / 5f); + float num3 = (length <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length / 300f, 0.0333333351f), length / 5f); + float num4 = num2; + float num5 = 0f; + bool flag2 = false; + bool flag3 = false; + bool flag4 = false; + this.m_AvatarPreview.Animator.StartRecording(-1); + this.m_LeftStateWeightA = 0f; + this.m_LeftStateTimeA = 0f; + this.m_AvatarPreview.Animator.Update(0f); + while (!flag4) + { + this.m_AvatarPreview.Animator.Update(num4); + AnimatorStateInfo currentAnimatorStateInfo = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex); + num5 += num4; + if (!flag2) + { + this.m_LeftStateWeightA = currentAnimatorStateInfo.normalizedTime; + this.m_LeftStateTimeA = num5; + flag2 = true; + } + if (flag3 && num5 >= num) + { + flag4 = true; + } + if (!flag3 && currentAnimatorStateInfo.IsName(this.m_DstState.uniqueName)) + { + this.m_RightStateWeightA = currentAnimatorStateInfo.normalizedTime; + this.m_RightStateTimeA = num5; + flag3 = true; + } + if (!flag3) + { + this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime; + this.m_LeftStateTimeB = num5; + } + if (flag3) + { + this.m_RightStateWeightB = currentAnimatorStateInfo.normalizedTime; + this.m_RightStateTimeB = num5; + } + if (this.m_AvatarPreview.Animator.IsInTransition(this.m_LayerIndex)) + { + num4 = num3; + } + } + float stopTime = num5; + this.m_AvatarPreview.Animator.StopRecording(); + float num6 = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); + float num7 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); + if (this.m_MustSampleMotions) + { + this.m_MustSampleMotions = false; + this.m_SrcPivotList.Clear(); + this.m_DstPivotList.Clear(); + num4 = num3; + this.m_StateMachine.defaultState = this.m_DstState; + this.m_Transition.mute = true; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); + this.m_AvatarPreview.Animator.Update(1E-07f); + this.WriteParametersInController(); + num5 = 0f; + while (num5 <= num7) + { + this.m_AvatarPreview.Animator.Update(num4 * 2f); + num5 += num4 * 2f; + Timeline.PivotSample pivotSample = new Timeline.PivotSample(); + pivotSample.m_Time = num5; + pivotSample.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; + this.m_DstPivotList.Add(pivotSample); + } + num4 = num2; + this.m_StateMachine.defaultState = this.m_SrcState; + this.m_Transition.mute = true; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + this.m_AvatarPreview.Animator.Update(1E-07f); + this.WriteParametersInController(); + this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); + num5 = 0f; + while (num5 <= num6) + { + this.m_AvatarPreview.Animator.Update(num4 * 2f); + num5 += num4 * 2f; + Timeline.PivotSample pivotSample2 = new Timeline.PivotSample(); + pivotSample2.m_Time = num5; + pivotSample2.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; + this.m_SrcPivotList.Add(pivotSample2); + } + this.m_Transition.mute = false; + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + this.m_AvatarPreview.Animator.Update(1E-07f); + this.WriteParametersInController(); + } + this.m_Timeline.StopTime = (this.m_AvatarPreview.timeControl.stopTime = stopTime); + this.m_AvatarPreview.timeControl.currentTime = this.m_Timeline.Time; + if (flag) + { + Timeline arg_6DE_0 = this.m_Timeline; + float num8 = this.m_AvatarPreview.timeControl.currentTime = (this.m_AvatarPreview.timeControl.startTime = 0f); + this.m_Timeline.StartTime = num8; + arg_6DE_0.Time = num8; + this.m_Timeline.ResetRange(); + } + this.m_AvatarPreview.Animator.StartPlayback(); + } + public void SetAnyStateTransition(Transition transition, State sourceState, AvatarMask layerMask, int motionSetIndex, Animator previewObject) + { + TransitionPreview.TransitionInfo transitionInfo = new TransitionPreview.TransitionInfo(); + transitionInfo.Set(transition, sourceState); + this.m_MotionSetIndex = motionSetIndex; + if (this.MustResample(transitionInfo)) + { + this.m_RefSrcState = sourceState; + this.ResampleTransition(transition, layerMask, transitionInfo, previewObject); + } + } + public void SetTransition(Transition transition, AvatarMask layerMask, int motionSetIndex, Animator previewObject) + { + TransitionPreview.TransitionInfo transitionInfo = new TransitionPreview.TransitionInfo(); + transitionInfo.Set(transition, null); + this.m_MotionSetIndex = motionSetIndex; + if (this.MustResample(transitionInfo)) + { + this.ResampleTransition(transition, layerMask, transitionInfo, previewObject); + } + } + private void OnPreviewAvatarChanged() + { + this.m_RefTransitionInfo = new TransitionPreview.TransitionInfo(); + this.ClearController(); + this.CreateController(); + this.CreateParameterInfoList(); + } + private void ClearController() + { + if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) + { + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); + } + UnityEngine.Object.DestroyImmediate(this.m_Controller); + UnityEngine.Object.DestroyImmediate(this.m_SrcState); + UnityEngine.Object.DestroyImmediate(this.m_DstState); + UnityEngine.Object.DestroyImmediate(this.m_Transition); + this.m_StateMachine = null; + this.m_Controller = null; + this.m_SrcState = null; + this.m_DstState = null; + this.m_Transition = null; + } + private void CreateParameterInfoList() + { + this.m_ParameterInfoList = new List(); + if (this.m_Controller) + { + int parameterCount = this.m_Controller.parameterCount; + for (int i = 0; i < parameterCount; i++) + { + TransitionPreview.ParameterInfo parameterInfo = new TransitionPreview.ParameterInfo(); + parameterInfo.m_Name = this.m_Controller.GetParameterName(i); + this.m_ParameterInfoList.Add(parameterInfo); + } + } + } + private void CreateController() + { + if (this.m_Controller == null && this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null && this.m_RefTransition != null) + { + this.m_LayerIndex = 0; + this.m_Controller = new AnimatorController(); + this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.AddLayer("preview"); + bool flag = true; + if (this.m_LayerMask != null) + { + int humanoidBodyPartCount = this.m_LayerMask.humanoidBodyPartCount; + int num = 0; + while (num < humanoidBodyPartCount && flag) + { + if (!this.m_LayerMask.GetHumanoidBodyPartActive(num)) + { + flag = false; + } + num++; + } + if (!flag) + { + this.m_Controller.AddLayer("Additionnal"); + this.m_LayerIndex++; + this.m_Controller.SetLayerMask(this.m_LayerIndex, this.m_LayerMask); + } + } + this.m_StateMachine = this.m_Controller.GetLayerStateMachine(this.m_LayerIndex); + State state = (!this.m_RefTransition.srcState) ? this.m_RefSrcState : this.m_RefTransition.srcState; + this.m_ParameterMinMax.Clear(); + Motion motionInternal = state.GetMotionInternal(this.m_MotionSetIndex); + if (motionInternal && motionInternal is BlendTree) + { + BlendTree blendTree = motionInternal as BlendTree; + for (int i = 0; i < blendTree.recursiveBlendParameterCount; i++) + { + string recursiveBlendParameter = blendTree.GetRecursiveBlendParameter(i); + if (this.m_Controller.FindParameter(recursiveBlendParameter) == -1) + { + this.m_Controller.AddParameter(recursiveBlendParameter, AnimatorControllerParameterType.Float); + this.m_ParameterMinMax.Add(new Vector2(blendTree.GetRecursiveBlendParameterMin(i), blendTree.GetRecursiveBlendParameterMax(i))); + } + } + } + Motion motionInternal2 = this.m_RefTransition.dstState.GetMotionInternal(this.m_MotionSetIndex); + if (motionInternal2 && motionInternal2 is BlendTree) + { + BlendTree blendTree2 = motionInternal2 as BlendTree; + for (int j = 0; j < blendTree2.recursiveBlendParameterCount; j++) + { + string recursiveBlendParameter2 = blendTree2.GetRecursiveBlendParameter(j); + int num2 = this.m_Controller.FindParameter(recursiveBlendParameter2); + if (num2 == -1) + { + this.m_Controller.AddParameter(recursiveBlendParameter2, AnimatorControllerParameterType.Float); + this.m_ParameterMinMax.Add(new Vector2(blendTree2.GetRecursiveBlendParameterMin(j), blendTree2.GetRecursiveBlendParameterMax(j))); + } + else + { + this.m_ParameterMinMax[num2] = new Vector2(Mathf.Min(blendTree2.GetRecursiveBlendParameterMin(j), this.m_ParameterMinMax[num2][0]), Mathf.Max(blendTree2.GetRecursiveBlendParameterMax(j), this.m_ParameterMinMax[num2][1])); + } + } + } + this.m_SrcState = this.m_StateMachine.AddState(state.name); + this.m_SrcState.hideFlags = HideFlags.DontSave; + this.m_DstState = this.m_StateMachine.AddState(this.m_RefTransition.dstState.name); + this.m_DstState.hideFlags = HideFlags.DontSave; + this.CopyStateForPreview(state, ref this.m_SrcState); + this.CopyStateForPreview(this.m_RefTransition.dstState, ref this.m_DstState); + this.m_Transition = this.m_StateMachine.AddTransition(this.m_SrcState, this.m_DstState); + this.m_Transition.hideFlags = HideFlags.DontSave; + this.CopyTransitionForPreview(this.m_RefTransition, ref this.m_Transition); + this.DisableIKOnFeetIfNeeded(); + AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + } + } + private void DisableIKOnFeetIfNeeded() + { + bool flag = false; + if (this.m_SrcState.GetMotion() == null || this.m_DstState.GetMotion() == null) + { + flag = true; + } + if (this.m_LayerIndex > 0) + { + flag = !this.m_LayerMask.hasFeetIK; + } + if (flag) + { + this.m_SrcState.iKOnFeet = false; + this.m_DstState.iKOnFeet = false; + } + } + private void Init(Animator scenePreviewObject, Motion motion) + { + if (this.m_AvatarPreview == null) + { + this.m_AvatarPreview = new AvatarPreview(scenePreviewObject, motion); + this.m_AvatarPreview.OnAvatarChangeFunc = new AvatarPreview.OnAvatarChange(this.OnPreviewAvatarChanged); + this.m_AvatarPreview.ShowIKOnFeetButton = false; + } + if (this.m_Timeline == null) + { + this.m_Timeline = new Timeline(); + this.m_MustSampleMotions = true; + } + this.CreateController(); + if (this.m_ParameterInfoList == null) + { + this.CreateParameterInfoList(); + } + } + public void DoTransitionPreview() + { + if (this.m_Controller == null) + { + return; + } + if (Event.current.type == EventType.Repaint) + { + this.m_AvatarPreview.timeControl.Update(); + } + this.DoTimeline(); + if (this.m_Controller.parameterCount > 0) + { + this.m_ShowBlendValue = EditorGUILayout.Foldout(this.m_ShowBlendValue, "BlendTree Parameters"); + if (this.m_ShowBlendValue) + { + for (int i = 0; i < this.m_Controller.parameterCount; i++) + { + string parameterName = this.m_Controller.GetParameterName(i); + float value = this.m_ParameterInfoList[i].m_Value; + float num = EditorGUILayout.Slider(parameterName, value, this.m_ParameterMinMax[i][0], this.m_ParameterMinMax[i][1], new GUILayoutOption[0]); + if (num != value) + { + this.m_ParameterInfoList[i].m_Value = num; + this.mustResample = true; + this.m_MustSampleMotions = true; + } + } + } + } + } + private void DoTimeline() + { + float num = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); + float num2 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); + float num3 = this.m_Transition.duration * num; + this.m_Timeline.SrcStartTime = 0f; + this.m_Timeline.SrcStopTime = num; + this.m_Timeline.SrcName = this.m_SrcState.name; + this.m_Timeline.HasExitTime = this.HasExitTime(this.m_RefTransition); + this.m_Timeline.srcLoop = (this.m_SrcState.GetMotion() && this.m_SrcState.GetMotion().isLooping); + this.m_Timeline.dstLoop = (this.m_DstState.GetMotion() && this.m_DstState.GetMotion().isLooping); + this.m_Timeline.TransitionStartTime = this.GetExitTime(this.m_RefTransition) * num; + this.m_Timeline.TransitionStopTime = this.m_Timeline.TransitionStartTime + num3; + this.m_Timeline.Time = this.m_AvatarPreview.timeControl.currentTime; + this.m_Timeline.DstStartTime = this.m_Timeline.TransitionStartTime - this.m_RefTransition.offset * num2; + this.m_Timeline.DstStopTime = this.m_Timeline.DstStartTime + num2; + if (this.m_Timeline.TransitionStopTime == float.PositiveInfinity) + { + this.m_Timeline.TransitionStopTime = Mathf.Min(this.m_Timeline.DstStopTime, this.m_Timeline.SrcStopTime); + } + this.m_Timeline.DstName = this.m_DstState.name; + this.m_Timeline.SrcPivotList = this.m_SrcPivotList; + this.m_Timeline.DstPivotList = this.m_DstPivotList; + Rect controlRect = EditorGUILayout.GetControlRect(false, 150f, EditorStyles.label, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + bool flag = this.m_Timeline.DoTimeline(controlRect); + if (EditorGUI.EndChangeCheck()) + { + if (flag) + { + Undo.RegisterCompleteObjectUndo(this.m_RefTransition, "Edit Transition"); + this.SetExitTime(this.m_RefTransition, this.m_Timeline.TransitionStartTime / this.m_Timeline.SrcDuration); + this.m_RefTransition.duration = this.m_Timeline.TransitionDuration / this.m_Timeline.SrcDuration; + this.m_RefTransition.offset = (this.m_Timeline.TransitionStartTime - this.m_Timeline.DstStartTime) / this.m_Timeline.DstDuration; + } + this.m_AvatarPreview.timeControl.nextCurrentTime = Mathf.Clamp(this.m_Timeline.Time, 0f, this.m_AvatarPreview.timeControl.stopTime); + } + } + public void OnDisable() + { + this.ClearController(); + } + public void OnDestroy() + { + this.ClearController(); + if (this.m_Timeline != null) + { + this.m_Timeline = null; + } + if (this.m_AvatarPreview != null) + { + this.m_AvatarPreview.OnDestroy(); + this.m_AvatarPreview = null; + } + } + public bool HasPreviewGUI() + { + return true; + } + public void OnPreviewSettings() + { + if (this.m_AvatarPreview != null) + { + this.m_AvatarPreview.DoPreviewSettings(); + } + } + public void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + if (this.m_AvatarPreview != null && this.m_Controller != null) + { + if (this.m_LastEvalTime != this.m_AvatarPreview.timeControl.currentTime && Event.current.type == EventType.Repaint) + { + this.m_AvatarPreview.Animator.playbackTime = this.m_AvatarPreview.timeControl.currentTime; + this.m_AvatarPreview.Animator.Update(0f); + this.m_LastEvalTime = this.m_AvatarPreview.timeControl.currentTime; + } + this.m_AvatarPreview.DoAvatarPreview(r, background); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TreeAO.cs b/UnityEditor/UnityEditor/TreeAO.cs new file mode 100644 index 00000000..5dd44ae4 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeAO.cs @@ -0,0 +1,136 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeAO + { + private const int kWorkLayer = 29; + private const float occlusion = 0.5f; + private static bool kDebug; + private static Vector3[] directions; + private static int PermuteCuboid(Vector3[] dirs, int offset, float x, float y, float z) + { + dirs[offset] = new Vector3(x, y, z); + dirs[offset + 1] = new Vector3(x, y, -z); + dirs[offset + 2] = new Vector3(x, -y, z); + dirs[offset + 3] = new Vector3(x, -y, -z); + dirs[offset + 4] = new Vector3(-x, y, z); + dirs[offset + 5] = new Vector3(-x, y, -z); + dirs[offset + 6] = new Vector3(-x, -y, z); + dirs[offset + 7] = new Vector3(-x, -y, -z); + return offset + 8; + } + public static void InitializeDirections() + { + float num = (1f + Mathf.Sqrt(5f)) / 2f; + TreeAO.directions = new Vector3[60]; + TreeAO.directions[0] = new Vector3(0f, 1f, 3f * num); + TreeAO.directions[1] = new Vector3(0f, 1f, -3f * num); + TreeAO.directions[2] = new Vector3(0f, -1f, 3f * num); + TreeAO.directions[3] = new Vector3(0f, -1f, -3f * num); + TreeAO.directions[4] = new Vector3(1f, 3f * num, 0f); + TreeAO.directions[5] = new Vector3(1f, -3f * num, 0f); + TreeAO.directions[6] = new Vector3(-1f, 3f * num, 0f); + TreeAO.directions[7] = new Vector3(-1f, -3f * num, 0f); + TreeAO.directions[8] = new Vector3(3f * num, 0f, 1f); + TreeAO.directions[9] = new Vector3(3f * num, 0f, -1f); + TreeAO.directions[10] = new Vector3(-3f * num, 0f, 1f); + TreeAO.directions[11] = new Vector3(-3f * num, 0f, -1f); + int offset = 12; + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, 2f, 1f + 2f * num, num); + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, 1f + 2f * num, num, 2f); + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, num, 2f, 1f + 2f * num); + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, 1f, 2f + num, 2f * num); + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, 2f + num, 2f * num, 1f); + offset = TreeAO.PermuteCuboid(TreeAO.directions, offset, 2f * num, 1f, 2f + num); + for (int i = 0; i < TreeAO.directions.Length; i++) + { + TreeAO.directions[i] = TreeAO.directions[i].normalized; + } + } + public static void CalcSoftOcclusion(Mesh mesh) + { + GameObject gameObject = new GameObject("Test"); + gameObject.layer = 29; + MeshFilter meshFilter = (MeshFilter)gameObject.AddComponent("MeshFilter"); + meshFilter.mesh = mesh; + gameObject.AddComponent("MeshCollider"); + if (TreeAO.directions == null) + { + TreeAO.InitializeDirections(); + } + Vector4[] array = new Vector4[TreeAO.directions.Length]; + for (int i = 0; i < TreeAO.directions.Length; i++) + { + array[i] = new Vector4(TreeAO.GetWeight(1, TreeAO.directions[i]), TreeAO.GetWeight(2, TreeAO.directions[i]), TreeAO.GetWeight(3, TreeAO.directions[i]), TreeAO.GetWeight(0, TreeAO.directions[i])); + } + Vector3[] vertices = mesh.vertices; + Vector4[] array2 = new Vector4[vertices.Length]; + float num = 0f; + for (int j = 0; j < vertices.Length; j++) + { + Vector4 vector = Vector4.zero; + Vector3 v = gameObject.transform.TransformPoint(vertices[j]); + for (int k = 0; k < TreeAO.directions.Length; k++) + { + float num2 = (float)TreeAO.CountIntersections(v, gameObject.transform.TransformDirection(TreeAO.directions[k]), 3f); + num2 = Mathf.Pow(0.5f, num2); + vector += array[k] * num2; + } + vector /= (float)TreeAO.directions.Length; + num += vector.w; + array2[j] = vector; + } + num /= (float)vertices.Length; + for (int l = 0; l < vertices.Length; l++) + { + Vector4[] expr_1E3_cp_0 = array2; + int expr_1E3_cp_1 = l; + expr_1E3_cp_0[expr_1E3_cp_1].w = expr_1E3_cp_0[expr_1E3_cp_1].w - num; + } + mesh.tangents = array2; + UnityEngine.Object.DestroyImmediate(gameObject); + } + private static int CountIntersections(Vector3 v, Vector3 dist, float length) + { + v += dist * 0.01f; + if (!TreeAO.kDebug) + { + return Physics.RaycastAll(v, dist, length, 536870912).Length + Physics.RaycastAll(v + dist * length, -dist, length, 536870912).Length; + } + RaycastHit[] array = Physics.RaycastAll(v, dist, length, 536870912); + int num = array.Length; + float num2 = 0f; + if (num > 0) + { + num2 = array[array.Length - 1].distance; + } + array = Physics.RaycastAll(v + dist * length, -dist, length, 536870912); + if (array.Length > 0) + { + float num3 = length - array[0].distance; + if (num3 > num2) + { + } + } + return num + array.Length; + } + private static float GetWeight(int coeff, Vector3 dir) + { + switch (coeff) + { + case 0: + return 0.5f; + case 1: + return 0.5f * dir.x; + case 2: + return 0.5f * dir.y; + case 3: + return 0.5f * dir.z; + default: + Debug.Log("Only defined up to 3"); + return 0f; + } + } + } +} diff --git a/UnityEditor/UnityEditor/TreeAOImporter.cs b/UnityEditor/UnityEditor/TreeAOImporter.cs new file mode 100644 index 00000000..5b290278 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeAOImporter.cs @@ -0,0 +1,58 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeAOImporter : AssetPostprocessor + { + private void OnPostprocessModel(GameObject root) + { + string text = base.assetPath.ToLower(); + if (text.IndexOf("ambient-occlusion") != -1) + { + Component[] componentsInChildren = root.GetComponentsInChildren(typeof(MeshFilter)); + Component[] array = componentsInChildren; + for (int i = 0; i < array.Length; i++) + { + MeshFilter meshFilter = (MeshFilter)array[i]; + if (meshFilter.sharedMesh != null) + { + Mesh sharedMesh = meshFilter.sharedMesh; + TreeAO.CalcSoftOcclusion(sharedMesh); + Bounds bounds = sharedMesh.bounds; + Color[] array2 = sharedMesh.colors; + Vector3[] vertices = sharedMesh.vertices; + Vector4[] tangents = sharedMesh.tangents; + if (array2.Length == 0) + { + array2 = new Color[sharedMesh.vertexCount]; + for (int j = 0; j < array2.Length; j++) + { + array2[j] = Color.white; + } + } + float b = 0f; + for (int k = 0; k < tangents.Length; k++) + { + b = Mathf.Max(tangents[k].w, b); + } + float num = 0f; + for (int l = 0; l < array2.Length; l++) + { + Vector2 vector = new Vector2(vertices[l].x, vertices[l].z); + float magnitude = vector.magnitude; + num = Mathf.Max(magnitude, num); + } + for (int m = 0; m < array2.Length; m++) + { + Vector2 vector2 = new Vector2(vertices[m].x, vertices[m].z); + float num2 = vector2.magnitude / num; + float num3 = (vertices[m].y - bounds.min.y) / bounds.size.y; + array2[m].a = num3 * num2 * 0.6f + num3 * 0.5f; + } + sharedMesh.colors = array2; + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/TreePainter.cs b/UnityEditor/UnityEditor/TreePainter.cs new file mode 100644 index 00000000..5d9f6ae1 --- /dev/null +++ b/UnityEditor/UnityEditor/TreePainter.cs @@ -0,0 +1,92 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreePainter + { + public static float brushSize = 40f; + public static float spacing = 0.8f; + public static float treeColorAdjustment = 0.4f; + public static float treeWidth = 1f; + public static float treeHeight = 1f; + public static float treeWidthVariation = 0.1f; + public static float treeHeightVariation = 0.1f; + public static int selectedTree; + public static Terrain terrain; + private static Color GetTreeColor() + { + Color result = Color.white * UnityEngine.Random.Range(1f, 1f - TreePainter.treeColorAdjustment); + result.a = 1f; + return result; + } + private static float GetTreeWidth() + { + return TreePainter.treeWidth * UnityEngine.Random.Range(1f - TreePainter.treeWidthVariation, 1f + TreePainter.treeWidthVariation); + } + private static float GetTreeHeight() + { + return TreePainter.treeHeight * UnityEngine.Random.Range(1f - TreePainter.treeHeightVariation, 1f + TreePainter.treeHeightVariation); + } + public static void PlaceTrees(float xBase, float yBase) + { + if (TreePainter.terrain.terrainData.treePrototypes.Length == 0) + { + return; + } + TreePainter.selectedTree = Mathf.Min(TerrainInspectorUtil.GetPrototypeCount(TreePainter.terrain.terrainData) - 1, TreePainter.selectedTree); + if (!TerrainInspectorUtil.PrototypeHasMaterials(TreePainter.terrain.terrainData, TreePainter.selectedTree)) + { + return; + } + int num = 0; + TreeInstance instance = default(TreeInstance); + instance.position = new Vector3(xBase, 0f, yBase); + instance.color = TreePainter.GetTreeColor(); + instance.lightmapColor = Color.white; + instance.prototypeIndex = TreePainter.selectedTree; + instance.widthScale = TreePainter.GetTreeWidth(); + instance.heightScale = TreePainter.GetTreeHeight(); + bool flag = Event.current.type == EventType.MouseDrag || TreePainter.brushSize > 1f; + if (!flag || TerrainInspectorUtil.CheckTreeDistance(TreePainter.terrain.terrainData, instance.position, instance.prototypeIndex, TreePainter.spacing)) + { + TreePainter.terrain.AddTreeInstance(instance); + num++; + } + Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(TreePainter.terrain.terrainData, TreePainter.selectedTree); + prototypeExtent.y = 0f; + float num2 = TreePainter.brushSize / (prototypeExtent.magnitude * TreePainter.spacing * 0.5f); + int num3 = (int)(num2 * num2 * 0.5f); + num3 = Mathf.Clamp(num3, 0, 100); + int num4 = 1; + while (num4 < num3 && num < num3) + { + Vector2 insideUnitCircle = UnityEngine.Random.insideUnitCircle; + insideUnitCircle.x *= TreePainter.brushSize / TreePainter.terrain.terrainData.size.x; + insideUnitCircle.y *= TreePainter.brushSize / TreePainter.terrain.terrainData.size.z; + Vector3 position = new Vector3(xBase + insideUnitCircle.x, 0f, yBase + insideUnitCircle.y); + if (position.x >= 0f && position.x <= 1f && position.z >= 0f && position.z <= 1f && TerrainInspectorUtil.CheckTreeDistance(TreePainter.terrain.terrainData, position, TreePainter.selectedTree, TreePainter.spacing * 0.5f)) + { + instance = default(TreeInstance); + instance.position = position; + instance.color = TreePainter.GetTreeColor(); + instance.lightmapColor = Color.white; + instance.prototypeIndex = TreePainter.selectedTree; + instance.widthScale = TreePainter.GetTreeWidth(); + instance.heightScale = TreePainter.GetTreeHeight(); + TreePainter.terrain.AddTreeInstance(instance); + num++; + } + num4++; + } + } + private float GetTreePlacementSize(float treeCount) + { + return TerrainInspectorUtil.GetTreePlacementSize(TreePainter.terrain.terrainData, TreePainter.selectedTree, TreePainter.spacing, treeCount); + } + public static void RemoveTrees(float xBase, float yBase, bool clearSelectedOnly) + { + float radius = TreePainter.brushSize / TreePainter.terrain.terrainData.size.x; + TreePainter.terrain.RemoveTrees(new Vector2(xBase, yBase), radius, (!clearSelectedOnly) ? -1 : TreePainter.selectedTree); + } + } +} diff --git a/UnityEditor/UnityEditor/TreePlacementUtility.cs b/UnityEditor/UnityEditor/TreePlacementUtility.cs new file mode 100644 index 00000000..0511beb5 --- /dev/null +++ b/UnityEditor/UnityEditor/TreePlacementUtility.cs @@ -0,0 +1,39 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreePlacementUtility + { + public static void PlaceRandomTrees(TerrainData terrainData, int treeCount) + { + int num = terrainData.treePrototypes.Length; + if (num == 0) + { + Debug.Log("Can't place trees because no prototypes are defined"); + return; + } + Undo.RegisterCompleteObjectUndo(terrainData, "Mass Place Trees"); + TreeInstance[] array = new TreeInstance[treeCount]; + int i = 0; + while (i < array.Length) + { + TreeInstance treeInstance = default(TreeInstance); + treeInstance.position = new Vector3(UnityEngine.Random.value, 0f, UnityEngine.Random.value); + if (terrainData.GetSteepness(treeInstance.position.x, treeInstance.position.z) < 30f) + { + Color color = Color.Lerp(Color.white, Color.gray * 0.7f, UnityEngine.Random.value); + color.a = 1f; + treeInstance.color = color; + treeInstance.lightmapColor = Color.white; + treeInstance.prototypeIndex = UnityEngine.Random.Range(0, num); + treeInstance.widthScale = 1f; + treeInstance.heightScale = 1f; + array[i] = treeInstance; + i++; + } + } + terrainData.treeInstances = array; + terrainData.RecalculateTreePositions(); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeView.cs b/UnityEditor/UnityEditor/TreeView.cs new file mode 100644 index 00000000..e838c595 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeView.cs @@ -0,0 +1,776 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeView + { + private const float kSpaceForScrollBar = 16f; + private EditorWindow m_EditorWindow; + private List m_DragSelection = new List(); + private bool m_UseScrollView = true; + private bool m_AllowRenameOnMouseUp = true; + private bool m_GrabKeyboardFocus; + private Rect m_TotalRect; + private bool m_HadFocusLastEvent; + private int m_KeyboardControlID; + public Action selectionChangedCallback + { + get; + set; + } + public Action itemDoubleClickedCallback + { + get; + set; + } + public Action dragEndedCallback + { + get; + set; + } + public Action contextClickCallback + { + get; + set; + } + public Action keyboardInputCallback + { + get; + set; + } + public Action onGUIRowCallback + { + get; + set; + } + public ITreeViewDataSource data + { + get; + set; + } + public ITreeViewDragging dragging + { + get; + set; + } + public ITreeViewGUI gui + { + get; + set; + } + public TreeViewState state + { + get; + set; + } + public bool deselectOnUnhandledMouseDown + { + get; + set; + } + public TreeView(EditorWindow editorWindow, TreeViewState treeViewState) + { + this.m_EditorWindow = editorWindow; + this.state = treeViewState; + } + public void Init(Rect rect, ITreeViewDataSource data, ITreeViewGUI gui, ITreeViewDragging dragging) + { + this.data = data; + this.gui = gui; + this.dragging = dragging; + this.m_TotalRect = rect; + } + public bool IsSelected(int id) + { + return this.state.selectedIDs.Contains(id); + } + public bool HasSelection() + { + return this.state.selectedIDs.Count() > 0; + } + public int[] GetSelection() + { + return this.state.selectedIDs.ToArray(); + } + private bool IsSameAsCurrentSelection(int[] selectedIDs) + { + if (selectedIDs.Length != this.state.selectedIDs.Count) + { + return false; + } + for (int i = 0; i < selectedIDs.Length; i++) + { + if (selectedIDs[i] != this.state.selectedIDs[i]) + { + return false; + } + } + return true; + } + public int[] GetVisibleRowIDs() + { + return ( + from item in this.data.GetVisibleRows() + select item.id).ToArray(); + } + public void SetSelection(int[] selectedIDs, bool revealSelectionAndFrameLastSelected) + { + if (selectedIDs.Length > 0) + { + if (revealSelectionAndFrameLastSelected) + { + int[] selectedIDs2 = selectedIDs; + for (int i = 0; i < selectedIDs2.Length; i++) + { + int id = selectedIDs2[i]; + this.RevealNode(id); + } + } + this.state.selectedIDs = new List(selectedIDs); + if (this.state.selectedIDs.IndexOf(this.state.lastClickedID) < 0) + { + List visibleRows = this.data.GetVisibleRows(); + List list = ( + from item in visibleRows + where selectedIDs.Contains(item.id) + select item.id).ToList(); + if (list.Count > 0) + { + this.state.lastClickedID = list[list.Count - 1]; + } + else + { + this.state.lastClickedID = 0; + } + } + if (revealSelectionAndFrameLastSelected) + { + this.Frame(this.state.lastClickedID, true, false); + } + } + else + { + this.state.selectedIDs.Clear(); + this.state.lastClickedID = 0; + } + } + public TreeViewItem FindNode(int id) + { + return this.data.FindItem(id); + } + public void SetUseScrollView(bool useScrollView) + { + this.m_UseScrollView = useScrollView; + } + public void Repaint() + { + if (this.m_EditorWindow != null) + { + this.m_EditorWindow.Repaint(); + } + } + public void ReloadData() + { + this.data.ReloadData(); + this.Repaint(); + } + public bool HasFocus() + { + return this.m_EditorWindow != null && this.m_EditorWindow.m_Parent.hasFocus && GUIUtility.keyboardControl == this.m_KeyboardControlID; + } + internal static int GetItemControlID(TreeViewItem item) + { + return ((item == null) ? 0 : item.id) + 10000000; + } + private void HandleUnusedMouseEventsForNode(Rect rect, TreeViewItem item, bool firstItem) + { + int itemControlID = TreeView.GetItemControlID(item); + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.MouseDown: + if (rect.Contains(Event.current.mousePosition)) + { + if (Event.current.button == 0) + { + GUIUtility.keyboardControl = this.m_KeyboardControlID; + this.Repaint(); + if (Event.current.clickCount == 2) + { + if (this.itemDoubleClickedCallback != null) + { + this.itemDoubleClickedCallback(item.id); + } + } + else + { + this.m_DragSelection = this.GetNewSelection(item, true, false); + GUIUtility.hotControl = itemControlID; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), itemControlID); + dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; + } + current.Use(); + } + else + { + if (Event.current.button == 1) + { + bool keepMultiSelection = true; + this.SelectionClick(item, keepMultiSelection); + } + } + } + return; + case EventType.MouseUp: + if (GUIUtility.hotControl == itemControlID) + { + if (rect.Contains(current.mousePosition)) + { + float contentIndent = this.gui.GetContentIndent(item); + Rect rect2 = new Rect(rect.x + contentIndent, rect.y, rect.width - contentIndent, rect.height); + List selectedIDs = this.state.selectedIDs; + if (this.m_AllowRenameOnMouseUp && selectedIDs != null && selectedIDs.Count == 1 && selectedIDs[0] == item.id && rect2.Contains(current.mousePosition) && !EditorGUIUtility.HasHolddownKeyModifiers(current)) + { + this.BeginNameEditing(0.5f); + } + else + { + this.SelectionClick(item, false); + } + GUIUtility.hotControl = 0; + } + this.m_DragSelection.Clear(); + current.Use(); + } + return; + case EventType.MouseMove: + IL_2C: + if (type == EventType.DragUpdated || type == EventType.DragPerform) + { + if (this.dragging != null && this.dragging.DragElement(item, rect, firstItem)) + { + GUIUtility.hotControl = 0; + } + return; + } + if (type != EventType.ContextClick) + { + return; + } + if (rect.Contains(current.mousePosition) && this.contextClickCallback != null) + { + this.contextClickCallback(item.id); + } + return; + case EventType.MouseDrag: + if (GUIUtility.hotControl == itemControlID && this.dragging != null) + { + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), itemControlID); + if (dragAndDropDelay2.CanStartDrag()) + { + this.dragging.StartDrag(item, this.m_DragSelection); + GUIUtility.hotControl = 0; + } + current.Use(); + } + return; + } + goto IL_2C; + } + public void GrabKeyboardFocus() + { + this.m_GrabKeyboardFocus = true; + } + public void NotifyListenersThatSelectionChanged() + { + if (this.selectionChangedCallback != null) + { + this.selectionChangedCallback(this.state.selectedIDs.ToArray()); + } + } + public void NotifyListenersThatDragEnded(int[] draggedIDs, bool draggedItemsFromOwnTreeView) + { + if (this.dragEndedCallback != null) + { + this.dragEndedCallback(draggedIDs, draggedItemsFromOwnTreeView); + } + } + public Vector2 GetContentSize() + { + return this.gui.GetTotalSize(this.data.GetVisibleRows()); + } + public Rect GetTotalRect() + { + return this.m_TotalRect; + } + public void OnGUI(Rect rect, int keyboardControlID) + { + this.m_TotalRect = rect; + this.m_KeyboardControlID = keyboardControlID; + Event current = Event.current; + if (this.m_GrabKeyboardFocus || (current.type == EventType.MouseDown && this.m_TotalRect.Contains(current.mousePosition))) + { + this.m_GrabKeyboardFocus = false; + GUIUtility.keyboardControl = this.m_KeyboardControlID; + this.m_AllowRenameOnMouseUp = true; + this.Repaint(); + } + bool flag = this.HasFocus(); + if (flag != this.m_HadFocusLastEvent && current.type != EventType.Layout) + { + this.m_HadFocusLastEvent = flag; + if (flag && current.type == EventType.MouseDown) + { + this.m_AllowRenameOnMouseUp = false; + } + } + List visibleRows = this.data.GetVisibleRows(); + Vector2 totalSize = this.gui.GetTotalSize(visibleRows); + Rect viewRect = new Rect(0f, 0f, totalSize.x, totalSize.y + this.gui.halfDropBetweenHeight * 2f); + if (this.m_UseScrollView) + { + this.state.scrollPos = GUI.BeginScrollView(this.m_TotalRect, this.state.scrollPos, viewRect); + } + this.gui.BeginRowGUI(); + float topPixel = (!this.m_UseScrollView) ? 0f : this.state.scrollPos.y; + int num; + int num2; + this.gui.GetFirstAndLastRowVisible(visibleRows, topPixel, this.m_TotalRect.height, out num, out num2); + for (int i = num; i <= num2; i++) + { + TreeViewItem treeViewItem = visibleRows[i]; + bool selected = (this.m_DragSelection.Count <= 0) ? this.state.selectedIDs.Contains(treeViewItem.id) : this.m_DragSelection.Contains(treeViewItem.id); + Rect rect2 = this.gui.OnRowGUI(treeViewItem, i, Mathf.Max(GUIClip.visibleRect.width, viewRect.width), selected, flag); + if (this.onGUIRowCallback != null) + { + float contentIndent = this.gui.GetContentIndent(treeViewItem); + Rect arg = new Rect(rect2.x + contentIndent, rect2.y, rect2.width - contentIndent, rect2.height); + this.onGUIRowCallback(treeViewItem.id, arg); + } + this.HandleUnusedMouseEventsForNode(rect2, visibleRows[i], i == 0); + } + this.gui.EndRowGUI(); + if (this.m_UseScrollView) + { + GUI.EndScrollView(); + } + this.HandleUnusedEvents(); + this.KeyboardGUI(); + } + private void HandleUnusedEvents() + { + EventType type = Event.current.type; + switch (type) + { + case EventType.DragUpdated: + if (this.dragging != null) + { + this.dragging.DragElement(null, default(Rect), false); + this.Repaint(); + } + return; + case EventType.DragPerform: + if (this.dragging != null) + { + this.m_DragSelection.Clear(); + this.dragging.DragElement(null, default(Rect), false); + this.Repaint(); + } + return; + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + case EventType.ExecuteCommand: + IL_34: + if (type != EventType.MouseDown) + { + return; + } + if (this.deselectOnUnhandledMouseDown && Event.current.button == 0 && this.m_TotalRect.Contains(Event.current.mousePosition) && this.state.selectedIDs.Count > 0) + { + this.SetSelection(new int[0], false); + this.NotifyListenersThatSelectionChanged(); + } + return; + case EventType.DragExited: + if (this.dragging != null) + { + this.m_DragSelection.Clear(); + this.dragging.DragCleanup(true); + this.Repaint(); + } + return; + case EventType.ContextClick: + if (this.m_TotalRect.Contains(Event.current.mousePosition) && this.contextClickCallback != null) + { + this.contextClickCallback(0); + } + return; + } + goto IL_34; + } + public void OnEvent() + { + this.state.renameOverlay.OnEvent(); + } + public bool BeginNameEditing(float delay) + { + if (this.state.selectedIDs.Count == 1) + { + TreeViewItem treeViewItem = this.data.FindItem(this.state.selectedIDs[0]); + if (treeViewItem != null) + { + if (this.data.IsRenamingItemAllowed(treeViewItem)) + { + return this.gui.BeginRename(treeViewItem, delay); + } + } + else + { + Debug.LogError("Item not found for renaming with id = " + this.state.selectedIDs[0]); + } + } + return false; + } + public void EndNameEditing(bool acceptChanges) + { + if (this.state.renameOverlay.IsRenaming()) + { + this.state.renameOverlay.EndRename(acceptChanges); + this.gui.EndRename(); + } + } + private void KeyboardGUI() + { + if (this.m_KeyboardControlID != GUIUtility.keyboardControl || !GUI.enabled) + { + return; + } + if (this.keyboardInputCallback != null) + { + this.keyboardInputCallback(); + } + if (Event.current.type == EventType.KeyDown) + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.KeypadEnter: + goto IL_392; + case KeyCode.KeypadEquals: + case KeyCode.Insert: + case KeyCode.F1: + IL_8E: + if (keyCode != KeyCode.Return) + { + if (Event.current.keyCode <= KeyCode.A || Event.current.keyCode < KeyCode.Z) + { + } + return; + } + goto IL_392; + case KeyCode.UpArrow: + Event.current.Use(); + this.OffsetSelection(-1); + return; + case KeyCode.DownArrow: + Event.current.Use(); + this.OffsetSelection(1); + return; + case KeyCode.RightArrow: + foreach (int current in this.state.selectedIDs) + { + TreeViewItem treeViewItem = this.data.FindItem(current); + if (treeViewItem != null) + { + if (this.data.IsExpandable(treeViewItem) && !this.data.IsExpanded(treeViewItem)) + { + if (Event.current.alt) + { + this.data.SetExpandedWithChildren(treeViewItem, true); + } + else + { + this.data.SetExpanded(treeViewItem, true); + } + this.UserExpandedNode(treeViewItem); + } + else + { + if (treeViewItem.hasChildren && this.state.selectedIDs.Count == 1) + { + this.SelectionClick(treeViewItem.children[0], false); + } + } + } + } + Event.current.Use(); + return; + case KeyCode.LeftArrow: + foreach (int current2 in this.state.selectedIDs) + { + TreeViewItem treeViewItem2 = this.data.FindItem(current2); + if (treeViewItem2 != null) + { + if (this.data.IsExpandable(treeViewItem2) && this.data.IsExpanded(treeViewItem2)) + { + if (Event.current.alt) + { + this.data.SetExpandedWithChildren(treeViewItem2, false); + } + else + { + this.data.SetExpanded(treeViewItem2, false); + } + } + else + { + if (treeViewItem2.parent != null && this.state.selectedIDs.Count == 1 && this.data.GetVisibleRows().Contains(treeViewItem2.parent)) + { + this.SelectionClick(treeViewItem2.parent, false); + } + } + } + } + Event.current.Use(); + return; + case KeyCode.Home: + Event.current.Use(); + this.OffsetSelection(-1000000); + return; + case KeyCode.End: + Event.current.Use(); + this.OffsetSelection(1000000); + return; + case KeyCode.PageUp: + { + Event.current.Use(); + TreeViewItem treeViewItem3 = this.data.FindItem(this.state.lastClickedID); + if (treeViewItem3 != null) + { + int numRowsOnPageUpDown = this.gui.GetNumRowsOnPageUpDown(treeViewItem3, true, this.m_TotalRect.height); + this.OffsetSelection(-numRowsOnPageUpDown); + } + return; + } + case KeyCode.PageDown: + { + Event.current.Use(); + TreeViewItem treeViewItem4 = this.data.FindItem(this.state.lastClickedID); + if (treeViewItem4 != null) + { + int numRowsOnPageUpDown2 = this.gui.GetNumRowsOnPageUpDown(treeViewItem4, true, this.m_TotalRect.height); + this.OffsetSelection(numRowsOnPageUpDown2); + } + return; + } + case KeyCode.F2: + if (Application.platform == RuntimePlatform.WindowsEditor && this.BeginNameEditing(0f)) + { + Event.current.Use(); + } + return; + } + goto IL_8E; + IL_392: + if (Application.platform == RuntimePlatform.OSXEditor && this.BeginNameEditing(0f)) + { + Event.current.Use(); + } + } + } + internal static int GetIndexOfID(List items, int id) + { + for (int i = 0; i < items.Count; i++) + { + if (items[i].id == id) + { + return i; + } + } + return -1; + } + public bool IsLastClickedPartOfVisibleRows() + { + List visibleRows = this.data.GetVisibleRows(); + return visibleRows.Count != 0 && TreeView.GetIndexOfID(visibleRows, this.state.lastClickedID) >= 0; + } + public void OffsetSelection(int offset) + { + List visibleRows = this.data.GetVisibleRows(); + if (visibleRows.Count == 0) + { + return; + } + int indexOfID = TreeView.GetIndexOfID(visibleRows, this.state.lastClickedID); + int num = Mathf.Clamp(indexOfID + offset, 0, visibleRows.Count - 1); + this.SelectionByKey(visibleRows[num]); + this.EnsureRowIsVisible(num, visibleRows); + Event.current.Use(); + } + private bool GetFirstAndLastSelected(List items, out int firstIndex, out int lastIndex) + { + firstIndex = -1; + lastIndex = -1; + for (int i = 0; i < items.Count; i++) + { + if (this.state.selectedIDs.Contains(items[i].id)) + { + if (firstIndex == -1) + { + firstIndex = i; + } + lastIndex = i; + } + } + return firstIndex != -1 && lastIndex != -1; + } + private List GetNewSelection(TreeViewItem clickedItem, bool keepMultiSelection, bool useShiftAsActionKey) + { + List visibleRows = this.data.GetVisibleRows(); + List list = new List(visibleRows.Count); + for (int i = 0; i < visibleRows.Count; i++) + { + list.Add(visibleRows[i].id); + } + List selectedIDs = this.state.selectedIDs; + int lastClickedID = this.state.lastClickedID; + bool allowMultiSelection = this.data.CanBeMultiSelected(clickedItem); + return InternalEditorUtility.GetNewSelection(clickedItem.id, list, selectedIDs, lastClickedID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection); + } + private void SelectionByKey(TreeViewItem itemSelected) + { + this.state.selectedIDs = this.GetNewSelection(itemSelected, false, true); + this.state.lastClickedID = itemSelected.id; + this.NotifyListenersThatSelectionChanged(); + } + public void RemoveSelection() + { + if (this.state.selectedIDs.Count > 0) + { + this.state.selectedIDs.Clear(); + this.NotifyListenersThatSelectionChanged(); + } + } + private void SelectionClick(TreeViewItem itemClicked, bool keepMultiSelection) + { + this.state.selectedIDs = this.GetNewSelection(itemClicked, keepMultiSelection, false); + this.state.lastClickedID = ((itemClicked == null) ? 0 : itemClicked.id); + this.NotifyListenersThatSelectionChanged(); + } + private float EnsureRowIsVisible(int row, List rows) + { + float num = -1f; + if (row >= 0) + { + num = this.gui.GetTopPixelOfRow(row, rows); + float min = num - this.m_TotalRect.height + this.gui.GetHeightOfLastRow(); + this.state.scrollPos.y = Mathf.Clamp(this.state.scrollPos.y, min, num); + return num; + } + return num; + } + public void Frame(int id, bool frame, bool ping) + { + float num = -1f; + TreeViewItem treeViewItem = null; + if (frame) + { + this.RevealNode(id); + List visibleRows = this.data.GetVisibleRows(); + int indexOfID = TreeView.GetIndexOfID(visibleRows, id); + if (indexOfID >= 0) + { + treeViewItem = visibleRows[indexOfID]; + num = this.gui.GetTopPixelOfRow(indexOfID, visibleRows); + this.EnsureRowIsVisible(indexOfID, visibleRows); + } + } + if (ping) + { + if (num == -1f) + { + List visibleRows2 = this.data.GetVisibleRows(); + int indexOfID2 = TreeView.GetIndexOfID(visibleRows2, id); + if (indexOfID2 >= 0) + { + treeViewItem = visibleRows2[indexOfID2]; + num = this.gui.GetTopPixelOfRow(indexOfID2, visibleRows2); + } + } + if (num >= 0f && treeViewItem != null) + { + float num2 = (this.GetContentSize().y <= this.m_TotalRect.height) ? 0f : -16f; + this.gui.BeginPingNode(treeViewItem, num, this.m_TotalRect.width + num2); + } + } + } + public void EndPing() + { + this.gui.EndPingNode(); + } + public bool IsVisible(int id) + { + List visibleRows = this.data.GetVisibleRows(); + return TreeView.GetIndexOfID(visibleRows, id) >= 0; + } + private void RevealNode(int id) + { + if (this.IsVisible(id)) + { + return; + } + TreeViewItem treeViewItem = this.FindNode(id); + if (treeViewItem != null) + { + for (TreeViewItem parent = treeViewItem.parent; parent != null; parent = parent.parent) + { + this.data.SetExpanded(parent, true); + } + } + } + public void UserExpandedNode(TreeViewItem item) + { + } + public List SortIDsInVisiblityOrder(List ids) + { + if (ids.Count <= 1) + { + return ids; + } + List visibleRows = this.data.GetVisibleRows(); + List list = new List(); + for (int i = 0; i < visibleRows.Count; i++) + { + int id = visibleRows[i].id; + for (int j = 0; j < ids.Count; j++) + { + if (ids[j] == id) + { + list.Add(id); + break; + } + } + } + if (ids.Count != list.Count) + { + list.AddRange(ids.Except(list)); + if (ids.Count != list.Count) + { + Debug.LogError(string.Concat(new object[] + { + "SortIDsInVisiblityOrder failed: ", + ids.Count, + " != ", + list.Count + })); + } + } + return list; + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewDataSource.cs b/UnityEditor/UnityEditor/TreeViewDataSource.cs new file mode 100644 index 00000000..7dea1e6d --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewDataSource.cs @@ -0,0 +1,198 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class TreeViewDataSource : ITreeViewDataSource + { + protected readonly TreeView m_TreeView; + protected TreeViewItem m_RootItem; + protected List m_VisibleRows; + protected bool m_NeedRefreshVisibleFolders = true; + protected TreeViewItem m_FakeItem; + public bool showRootNode + { + get; + set; + } + public bool rootIsCollapsable + { + get; + set; + } + public TreeViewItem root + { + get + { + return this.m_RootItem; + } + } + protected List expandedIDs + { + get + { + return this.m_TreeView.state.expandedIDs; + } + set + { + this.m_TreeView.state.expandedIDs = value; + } + } + public TreeViewDataSource(TreeView treeView) + { + this.m_TreeView = treeView; + this.showRootNode = true; + this.rootIsCollapsable = false; + } + public abstract void FetchData(); + public void ReloadData() + { + this.m_FakeItem = null; + this.FetchData(); + } + public virtual TreeViewItem FindItem(int id) + { + return TreeViewUtility.FindItem(id, this.m_RootItem); + } + protected void GetVisibleItemsRecursive(TreeViewItem item, List items) + { + if (item != this.m_RootItem || this.showRootNode) + { + items.Add(item); + } + if (item.hasChildren && this.IsExpanded(item)) + { + foreach (TreeViewItem current in item.children) + { + this.GetVisibleItemsRecursive(current, items); + } + } + } + public virtual List GetVisibleRows() + { + if (this.m_VisibleRows == null || this.m_NeedRefreshVisibleFolders) + { + this.m_VisibleRows = new List(); + this.GetVisibleItemsRecursive(this.m_RootItem, this.m_VisibleRows); + this.m_NeedRefreshVisibleFolders = false; + this.m_TreeView.Repaint(); + } + return this.m_VisibleRows; + } + public virtual int[] GetExpandedIDs() + { + return this.expandedIDs.ToArray(); + } + public virtual void SetExpandedIDs(int[] ids) + { + this.expandedIDs = new List(ids); + this.expandedIDs.Sort(); + this.m_NeedRefreshVisibleFolders = true; + this.OnExpandedStateChanged(); + } + public virtual bool IsExpanded(int id) + { + return this.expandedIDs.BinarySearch(id) >= 0; + } + public virtual bool SetExpanded(int id, bool expand) + { + bool flag = this.IsExpanded(id); + if (expand != flag) + { + if (expand) + { + Assert.That(!this.expandedIDs.Contains(id)); + this.expandedIDs.Add(id); + this.expandedIDs.Sort(); + } + else + { + this.expandedIDs.Remove(id); + } + this.m_NeedRefreshVisibleFolders = true; + this.OnExpandedStateChanged(); + return true; + } + return false; + } + public virtual void SetExpandedWithChildren(TreeViewItem fromItem, bool expand) + { + Stack stack = new Stack(); + stack.Push(fromItem); + HashSet hashSet = new HashSet(); + while (stack.Count > 0) + { + TreeViewItem treeViewItem = stack.Pop(); + if (treeViewItem.hasChildren) + { + hashSet.Add(treeViewItem.id); + foreach (TreeViewItem current in treeViewItem.children) + { + stack.Push(current); + } + } + } + HashSet hashSet2 = new HashSet(this.expandedIDs); + if (expand) + { + hashSet2.UnionWith(hashSet); + } + else + { + hashSet2.ExceptWith(hashSet); + } + this.SetExpandedIDs(hashSet2.ToArray()); + } + public virtual void SetExpanded(TreeViewItem item, bool expand) + { + this.SetExpanded(item.id, expand); + } + public virtual bool IsExpanded(TreeViewItem item) + { + return this.IsExpanded(item.id); + } + public virtual bool IsExpandable(TreeViewItem item) + { + return item.hasChildren; + } + public virtual bool CanBeMultiSelected(TreeViewItem item) + { + return true; + } + public virtual bool CanBeParent(TreeViewItem item) + { + return true; + } + public virtual void OnExpandedStateChanged() + { + } + public virtual bool IsRenamingItemAllowed(TreeViewItem item) + { + return true; + } + public virtual void InsertFakeItem(int id, int parentID, string name, Texture2D icon) + { + Debug.LogError("InsertFakeItem missing implementation"); + } + public virtual bool HasFakeItem() + { + return this.m_FakeItem != null; + } + public virtual void RemoveFakeItem() + { + if (!this.HasFakeItem()) + { + return; + } + List visibleRows = this.GetVisibleRows(); + int indexOfID = TreeView.GetIndexOfID(visibleRows, this.m_FakeItem.id); + if (indexOfID != -1) + { + visibleRows.RemoveAt(indexOfID); + } + this.m_FakeItem = null; + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewDragging.cs b/UnityEditor/UnityEditor/TreeViewDragging.cs new file mode 100644 index 00000000..66e3f6b2 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewDragging.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class TreeViewDragging : ITreeViewDragging + { + private class DropData + { + public int[] expandedArrayBeforeDrag; + public int lastControlID; + public int dropTargetControlID; + public int rowMarkerControlID; + public double expandItemBeginTimer; + public Vector2 expandItemBeginPosition; + } + public enum DropPosition + { + Upon, + Below, + Above + } + private const double k_DropExpandTimeout = 0.7; + protected TreeView m_TreeView; + private TreeViewDragging.DropData m_DropData = new TreeViewDragging.DropData(); + public bool drawRowMarkerAbove + { + get; + set; + } + public TreeViewDragging(TreeView treeView) + { + this.m_TreeView = treeView; + } + public int GetDropTargetControlID() + { + return this.m_DropData.dropTargetControlID; + } + public int GetRowMarkerControlID() + { + return this.m_DropData.rowMarkerControlID; + } + public abstract void StartDrag(TreeViewItem draggedItem, List draggedItemIDs); + public abstract DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dragPos); + public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bool firstItem) + { + if (targetItem == null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.None; + if (this.m_DropData != null) + { + this.m_DropData.dropTargetControlID = 0; + this.m_DropData.rowMarkerControlID = 0; + } + return false; + } + Vector2 mousePosition = Event.current.mousePosition; + bool flag = this.m_TreeView.data.CanBeParent(targetItem); + Rect rect = targetItemRect; + float num = (!flag) ? (targetItemRect.height * 0.5f) : this.m_TreeView.gui.halfDropBetweenHeight; + if (firstItem) + { + rect.yMin -= num; + } + rect.yMax += num; + if (!rect.Contains(mousePosition)) + { + return false; + } + TreeViewDragging.DropPosition dropPosition; + if (!flag || mousePosition.y >= targetItemRect.yMax - num) + { + dropPosition = TreeViewDragging.DropPosition.Below; + } + else + { + if (!flag || (firstItem && mousePosition.y <= targetItemRect.yMin + num)) + { + dropPosition = TreeViewDragging.DropPosition.Above; + } + else + { + dropPosition = TreeViewDragging.DropPosition.Upon; + } + } + TreeViewItem treeViewItem; + if (this.m_TreeView.data.IsExpanded(targetItem) && targetItem.hasChildren) + { + treeViewItem = targetItem; + } + else + { + treeViewItem = targetItem.parent; + } + DragAndDropVisualMode dragAndDropVisualMode = DragAndDropVisualMode.None; + if (Event.current.type == EventType.DragPerform) + { + if (dropPosition == TreeViewDragging.DropPosition.Upon) + { + dragAndDropVisualMode = this.DoDrag(targetItem, targetItem, true, dropPosition); + } + if (dragAndDropVisualMode == DragAndDropVisualMode.None && treeViewItem != null) + { + dragAndDropVisualMode = this.DoDrag(treeViewItem, targetItem, true, dropPosition); + } + if (dragAndDropVisualMode != DragAndDropVisualMode.None) + { + DragAndDrop.AcceptDrag(); + this.DragCleanup(false); + List list = new List(DragAndDrop.objectReferences); + bool draggedItemsFromOwnTreeView = true; + if (list.Count > 0 && TreeViewUtility.FindItemInList(list[0].GetInstanceID(), this.m_TreeView.data.GetVisibleRows()) == null) + { + draggedItemsFromOwnTreeView = false; + } + int[] array = new int[list.Count]; + for (int i = 0; i < list.Count; i++) + { + if (!(list[i] == null)) + { + array[i] = list[i].GetInstanceID(); + } + } + this.m_TreeView.NotifyListenersThatDragEnded(array, draggedItemsFromOwnTreeView); + } + else + { + this.DragCleanup(true); + this.m_TreeView.NotifyListenersThatDragEnded(null, false); + } + } + else + { + if (this.m_DropData == null) + { + this.m_DropData = new TreeViewDragging.DropData(); + } + this.m_DropData.dropTargetControlID = 0; + this.m_DropData.rowMarkerControlID = 0; + int itemControlID = TreeView.GetItemControlID(targetItem); + this.HandleAutoExpansion(itemControlID, targetItem, targetItemRect, num, mousePosition); + if (dropPosition == TreeViewDragging.DropPosition.Upon) + { + dragAndDropVisualMode = this.DoDrag(targetItem, targetItem, false, dropPosition); + } + if (dragAndDropVisualMode != DragAndDropVisualMode.None) + { + this.m_DropData.dropTargetControlID = itemControlID; + DragAndDrop.visualMode = dragAndDropVisualMode; + } + else + { + if (targetItem != null && treeViewItem != null) + { + dragAndDropVisualMode = this.DoDrag(treeViewItem, targetItem, false, dropPosition); + if (dragAndDropVisualMode != DragAndDropVisualMode.None) + { + this.drawRowMarkerAbove = (dropPosition == TreeViewDragging.DropPosition.Above); + this.m_DropData.rowMarkerControlID = itemControlID; + this.m_DropData.dropTargetControlID = ((!this.drawRowMarkerAbove) ? TreeView.GetItemControlID(treeViewItem) : 0); + DragAndDrop.visualMode = dragAndDropVisualMode; + } + } + } + } + Event.current.Use(); + return true; + } + protected virtual void HandleAutoExpansion(int itemControlID, TreeViewItem targetItem, Rect targetItemRect, float betweenHalfHeight, Vector2 currentMousePos) + { + float contentIndent = this.m_TreeView.gui.GetContentIndent(targetItem); + Rect rect = new Rect(targetItemRect.x + contentIndent, targetItemRect.y + betweenHalfHeight, targetItemRect.width - contentIndent, targetItemRect.height - betweenHalfHeight * 2f); + bool flag = rect.Contains(currentMousePos); + if (itemControlID != this.m_DropData.lastControlID || !flag || this.m_DropData.expandItemBeginPosition != currentMousePos) + { + this.m_DropData.lastControlID = itemControlID; + this.m_DropData.expandItemBeginTimer = (double)Time.realtimeSinceStartup; + this.m_DropData.expandItemBeginPosition = currentMousePos; + } + bool flag2 = (double)Time.realtimeSinceStartup - this.m_DropData.expandItemBeginTimer > 0.7; + bool flag3 = flag && flag2; + if (targetItem != null && flag3 && targetItem.hasChildren && !this.m_TreeView.data.IsExpanded(targetItem)) + { + if (this.m_DropData.expandedArrayBeforeDrag == null) + { + List currentExpanded = this.GetCurrentExpanded(); + this.m_DropData.expandedArrayBeforeDrag = currentExpanded.ToArray(); + } + this.m_TreeView.data.SetExpanded(targetItem, true); + this.m_DropData.expandItemBeginTimer = (double)Time.realtimeSinceStartup; + this.m_DropData.lastControlID = 0; + } + } + public virtual void DragCleanup(bool revertExpanded) + { + if (this.m_DropData != null) + { + if (this.m_DropData.expandedArrayBeforeDrag != null && revertExpanded) + { + this.RestoreExpanded(new List(this.m_DropData.expandedArrayBeforeDrag)); + } + this.m_DropData = new TreeViewDragging.DropData(); + } + } + public List GetCurrentExpanded() + { + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + return ( + from item in visibleRows + where this.m_TreeView.data.IsExpanded(item) + select item.id).ToList(); + } + public void RestoreExpanded(List ids) + { + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + foreach (TreeViewItem current in visibleRows) + { + this.m_TreeView.data.SetExpanded(current, ids.Contains(current.id)); + } + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewGUI.cs b/UnityEditor/UnityEditor/TreeViewGUI.cs new file mode 100644 index 00000000..63212a97 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewGUI.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class TreeViewGUI : ITreeViewGUI + { + internal class Styles + { + public GUIStyle foldout = "IN Foldout"; + public GUIStyle insertion = "PR Insertion"; + public GUIStyle insertionAbove = "PR Insertion Above"; + public GUIStyle ping = new GUIStyle("PR Ping"); + public GUIStyle toolbarButton = "ToolbarButton"; + public GUIStyle lineStyle = new GUIStyle("PR Label"); + public GUIStyle lineBoldStyle = new GUIStyle("PR Label"); + public GUIContent content = new GUIContent(EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName)); + public Styles() + { + this.lineStyle.alignment = TextAnchor.MiddleLeft; + this.lineBoldStyle.alignment = TextAnchor.MiddleLeft; + this.lineBoldStyle.font = EditorStyles.boldLabel.font; + this.lineBoldStyle.fontStyle = EditorStyles.boldLabel.fontStyle; + this.ping.padding.left = 16; + this.ping.padding.right = 16; + this.ping.fixedHeight = 16f; + } + } + protected TreeView m_TreeView; + protected PingData m_Ping = new PingData(); + protected Rect m_DraggingInsertionMarkerRect; + protected bool m_UseHorizontalScroll; + protected float k_LineHeight = 16f; + protected float k_BaseIndent = 2f; + protected float k_IndentWidth = 14f; + protected float k_FoldoutWidth = 12f; + protected float k_IconWidth = 16f; + protected float k_SpaceBetweenIconAndText = 2f; + protected float k_TopRowMargin; + protected float k_HalfDropBetweenHeight = 4f; + protected static TreeViewGUI.Styles s_Styles; + public float iconLeftPadding + { + get; + set; + } + public float iconRightPadding + { + get; + set; + } + public float iconTotalPadding + { + get + { + return this.iconLeftPadding + this.iconRightPadding; + } + } + public Action iconOverlayGUI + { + get; + set; + } + protected float indentWidth + { + get + { + return this.k_IndentWidth + this.iconTotalPadding; + } + } + public float halfDropBetweenHeight + { + get + { + return this.k_HalfDropBetweenHeight; + } + } + public virtual float topRowMargin + { + get + { + return this.k_TopRowMargin; + } + } + public TreeViewGUI(TreeView treeView) + { + this.m_TreeView = treeView; + } + public TreeViewGUI(TreeView treeView, bool useHorizontalScroll) + { + this.m_TreeView = treeView; + this.m_UseHorizontalScroll = useHorizontalScroll; + } + protected virtual void InitStyles() + { + if (TreeViewGUI.s_Styles == null) + { + TreeViewGUI.s_Styles = new TreeViewGUI.Styles(); + } + } + protected abstract Texture GetIconForNode(TreeViewItem item); + public virtual Vector2 GetTotalSize(List rows) + { + this.InitStyles(); + float x = 1f; + if (this.m_UseHorizontalScroll) + { + x = this.GetMaxWidth(rows); + } + return new Vector2(x, (float)rows.Count * this.k_LineHeight); + } + protected float GetMaxWidth(List rows) + { + float num = 1f; + foreach (TreeViewItem current in rows) + { + float num2 = 0f; + num2 += this.GetContentIndent(current); + if (current.icon != null) + { + num2 += this.k_IconWidth; + } + float num3; + float num4; + TreeViewGUI.s_Styles.lineStyle.CalcMinMaxWidth(GUIContent.Temp(current.displayName), out num3, out num4); + num2 += num4; + num2 += this.k_BaseIndent; + if (num2 > num) + { + num = num2; + } + } + return num; + } + public virtual float GetTopPixelOfRow(int row, List rows) + { + return (float)row * this.k_LineHeight + this.topRowMargin; + } + public virtual float GetHeightOfLastRow() + { + return this.k_LineHeight; + } + public virtual int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) + { + return (int)Mathf.Floor(heightOfTreeView / this.k_LineHeight); + } + public virtual void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) + { + firstRowVisible = (int)Mathf.Floor(topPixel / this.k_LineHeight); + lastRowVisible = firstRowVisible + (int)Mathf.Ceil(heightInPixels / this.k_LineHeight); + firstRowVisible = Mathf.Max(firstRowVisible, 0); + lastRowVisible = Mathf.Min(lastRowVisible, rows.Count - 1); + } + public virtual void BeginRowGUI() + { + this.InitStyles(); + this.m_DraggingInsertionMarkerRect.x = -1f; + this.SyncFakeItem(); + if (Event.current.type != EventType.Repaint) + { + this.DoRenameOverlay(); + } + } + public virtual void EndRowGUI() + { + if (this.m_DraggingInsertionMarkerRect.x >= 0f && Event.current.type == EventType.Repaint) + { + if (this.m_TreeView.dragging.drawRowMarkerAbove) + { + TreeViewGUI.s_Styles.insertionAbove.Draw(this.m_DraggingInsertionMarkerRect, false, false, false, false); + } + else + { + TreeViewGUI.s_Styles.insertion.Draw(this.m_DraggingInsertionMarkerRect, false, false, false, false); + } + } + if (Event.current.type == EventType.Repaint) + { + this.DoRenameOverlay(); + } + this.HandlePing(); + } + public virtual Rect OnRowGUI(TreeViewItem item, int row, float rowWidth, bool selected, bool focused) + { + Rect rect = new Rect(0f, this.GetTopPixelOfRow(row, this.m_TreeView.data.GetVisibleRows()), rowWidth, this.k_LineHeight); + this.DoNodeGUI(rect, item, selected, focused, false); + return rect; + } + protected virtual void DoNodeGUI(Rect rect, TreeViewItem item, bool selected, bool focused, bool useBoldFont) + { + EditorGUIUtility.SetIconSize(new Vector2(this.k_IconWidth, this.k_IconWidth)); + float foldoutIndent = this.GetFoldoutIndent(item); + Rect position = rect; + int itemControlID = TreeView.GetItemControlID(item); + bool flag = false; + if (this.m_TreeView.dragging != null) + { + flag = (this.m_TreeView.dragging.GetDropTargetControlID() == itemControlID && this.m_TreeView.data.CanBeParent(item)); + } + bool flag2 = this.IsRenaming(item.id); + bool flag3 = this.m_TreeView.data.IsExpandable(item); + if (flag2 && rect.width > 1f) + { + float num = foldoutIndent + this.k_FoldoutWidth + this.k_IconWidth + this.iconTotalPadding - 1f; + this.GetRenameOverlay().editFieldRect = new Rect(rect.x + num, rect.y, rect.width - num, rect.height); + } + if (Event.current.type == EventType.Repaint) + { + string label = item.displayName; + if (flag2) + { + selected = false; + label = string.Empty; + } + if (selected) + { + TreeViewGUI.s_Styles.lineStyle.Draw(rect, false, false, true, focused); + } + if (flag) + { + TreeViewGUI.s_Styles.lineStyle.Draw(rect, GUIContent.none, true, true, false, false); + } + this.DrawIconAndLabel(rect, item, label, selected, focused, useBoldFont, false); + if (this.m_TreeView.dragging != null && this.m_TreeView.dragging.GetRowMarkerControlID() == itemControlID) + { + this.m_DraggingInsertionMarkerRect = new Rect(rect.x + foldoutIndent + this.k_FoldoutWidth, rect.y, rect.width - foldoutIndent, rect.height); + } + } + if (flag3) + { + position.x = foldoutIndent; + position.width = this.k_FoldoutWidth; + EditorGUI.BeginChangeCheck(); + bool flag4 = GUI.Toggle(position, this.m_TreeView.data.IsExpanded(item), GUIContent.none, TreeViewGUI.s_Styles.foldout); + if (EditorGUI.EndChangeCheck()) + { + if (Event.current.alt) + { + this.m_TreeView.data.SetExpandedWithChildren(item, flag4); + } + else + { + this.m_TreeView.data.SetExpanded(item, flag4); + } + if (flag4) + { + this.m_TreeView.UserExpandedNode(item); + } + } + } + EditorGUIUtility.SetIconSize(Vector2.zero); + } + protected virtual void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + if (!isPinging) + { + float contentIndent = this.GetContentIndent(item); + rect.x += contentIndent; + rect.width -= contentIndent; + } + GUIStyle gUIStyle = (!useBoldFont) ? TreeViewGUI.s_Styles.lineStyle : TreeViewGUI.s_Styles.lineBoldStyle; + gUIStyle.padding.left = (int)(this.k_IconWidth + this.iconTotalPadding + this.k_SpaceBetweenIconAndText); + gUIStyle.Draw(rect, label, false, false, selected, focused); + Rect position = rect; + position.width = this.k_IconWidth; + position.height = this.k_IconWidth; + position.x += this.iconLeftPadding; + Texture iconForNode = this.GetIconForNode(item); + if (iconForNode != null) + { + GUI.DrawTexture(position, iconForNode); + } + if (this.iconOverlayGUI != null) + { + Rect arg = rect; + arg.width = this.k_IconWidth + this.iconTotalPadding; + this.iconOverlayGUI(item, arg); + } + } + public virtual void BeginPingNode(TreeViewItem item, float topPixelOfRow, float availableWidth) + { + if (item == null) + { + return; + } + if (topPixelOfRow >= 0f) + { + this.m_Ping.m_TimeStart = Time.realtimeSinceStartup; + this.m_Ping.m_PingStyle = TreeViewGUI.s_Styles.ping; + GUIContent content = GUIContent.Temp(item.displayName); + Vector2 vector = this.m_Ping.m_PingStyle.CalcSize(content); + this.m_Ping.m_ContentRect = new Rect(this.GetContentIndent(item), topPixelOfRow, this.k_IconWidth + this.k_SpaceBetweenIconAndText + vector.x + this.iconTotalPadding, vector.y); + this.m_Ping.m_AvailableWidth = availableWidth; + bool useBoldFont = item.displayName.Equals("Assets"); + this.m_Ping.m_ContentDraw = delegate(Rect r) + { + this.DrawIconAndLabel(r, item, item.displayName, false, false, useBoldFont, true); + }; + this.m_TreeView.Repaint(); + } + } + public virtual void EndPingNode() + { + this.m_Ping.m_TimeStart = -1f; + } + private void HandlePing() + { + this.m_Ping.HandlePing(); + if (this.m_Ping.isPinging) + { + this.m_TreeView.Repaint(); + } + } + protected RenameOverlay GetRenameOverlay() + { + return this.m_TreeView.state.renameOverlay; + } + protected virtual bool IsRenaming(int id) + { + return this.GetRenameOverlay().IsRenaming() && this.GetRenameOverlay().userData == id && !this.GetRenameOverlay().isWaitingForDelay; + } + public virtual bool BeginRename(TreeViewItem item, float delay) + { + return this.GetRenameOverlay().BeginRename(item.displayName, item.id, delay); + } + public virtual void EndRename() + { + if (this.GetRenameOverlay().HasKeyboardFocus()) + { + this.m_TreeView.GrabKeyboardFocus(); + } + this.RenameEnded(); + this.ClearRenameAndNewNodeState(); + } + protected abstract void RenameEnded(); + public virtual void DoRenameOverlay() + { + if (this.GetRenameOverlay().IsRenaming() && !this.GetRenameOverlay().OnGUI()) + { + this.EndRename(); + } + } + protected virtual void SyncFakeItem() + { + } + protected virtual void ClearRenameAndNewNodeState() + { + this.m_TreeView.data.RemoveFakeItem(); + this.GetRenameOverlay().Clear(); + } + public virtual float GetFoldoutIndent(TreeViewItem item) + { + return this.k_BaseIndent + (float)item.depth * this.indentWidth; + } + public virtual float GetContentIndent(TreeViewItem item) + { + return this.k_BaseIndent + (float)item.depth * this.indentWidth + this.k_FoldoutWidth; + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewItem.cs b/UnityEditor/UnityEditor/TreeViewItem.cs new file mode 100644 index 00000000..b00fe13c --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewItem.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeViewItem : IComparable + { + private int m_ID; + private TreeViewItem m_Parent; + private List m_Children; + private int m_Depth; + private string m_DisplayName; + private Texture2D m_Icon; + public virtual int id + { + get + { + return this.m_ID; + } + } + public virtual string displayName + { + get + { + return this.m_DisplayName; + } + set + { + this.m_DisplayName = value; + } + } + public virtual int depth + { + get + { + return this.m_Depth; + } + } + public virtual bool hasChildren + { + get + { + return this.m_Children != null && this.m_Children.Count > 0; + } + } + public virtual List children + { + get + { + return this.m_Children; + } + set + { + this.m_Children = value; + } + } + public virtual TreeViewItem parent + { + get + { + return this.m_Parent; + } + set + { + this.m_Parent = value; + } + } + public virtual Texture2D icon + { + get + { + return this.m_Icon; + } + set + { + this.m_Icon = value; + } + } + public TreeViewItem(int id, int depth, TreeViewItem parent, string displayName) + { + this.m_Depth = depth; + this.m_Parent = parent; + this.m_ID = id; + this.m_DisplayName = displayName; + } + public void AddChild(TreeViewItem child) + { + if (this.m_Children == null) + { + this.m_Children = new List(); + } + this.m_Children.Add(child); + if (child != null) + { + child.parent = this; + } + } + public virtual int CompareTo(TreeViewItem other) + { + return this.displayName.CompareTo(other.displayName); + } + public override string ToString() + { + return string.Format("Item: '{0}' ({1}), has {2} children, depth {3}, parent id {4}", new object[] + { + this.displayName, + this.id, + (!this.hasChildren) ? 0 : this.children.Count, + this.depth, + (this.parent == null) ? -1 : this.parent.id + }); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewState.cs b/UnityEditor/UnityEditor/TreeViewState.cs new file mode 100644 index 00000000..d7ab2cf0 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewState.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class TreeViewState + { + public Vector2 scrollPos; + [SerializeField] + private List m_SelectedIDs = new List(); + [SerializeField] + private int m_LastClickedID; + [SerializeField] + private List m_ExpandedIDs = new List(); + [SerializeField] + private RenameOverlay m_RenameOverlay = new RenameOverlay(); + [SerializeField] + private CreateAssetUtility m_CreateAssetUtility = new CreateAssetUtility(); + [SerializeField] + private float[] m_ColumnWidths; + public List selectedIDs + { + get + { + return this.m_SelectedIDs; + } + set + { + this.m_SelectedIDs = value; + } + } + public int lastClickedID + { + get + { + return this.m_LastClickedID; + } + set + { + this.m_LastClickedID = value; + } + } + public List expandedIDs + { + get + { + return this.m_ExpandedIDs; + } + set + { + this.m_ExpandedIDs = value; + } + } + public RenameOverlay renameOverlay + { + get + { + return this.m_RenameOverlay; + } + set + { + this.m_RenameOverlay = value; + } + } + public CreateAssetUtility createAssetUtility + { + get + { + return this.m_CreateAssetUtility; + } + set + { + this.m_CreateAssetUtility = value; + } + } + public float[] columnWidths + { + get + { + return this.m_ColumnWidths; + } + set + { + this.m_ColumnWidths = value; + } + } + public void OnAwake() + { + this.m_RenameOverlay.Clear(); + this.m_CreateAssetUtility = new CreateAssetUtility(); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewTest.cs b/UnityEditor/UnityEditor/TreeViewTest.cs new file mode 100644 index 00000000..cfbbc3d0 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewTest.cs @@ -0,0 +1,664 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeViewTest + { + public class FooTreeViewItem : TreeViewItem + { + public TreeViewTest.BackendData.Foo foo + { + get; + private set; + } + public FooTreeViewItem(int id, int depth, TreeViewItem parent, string displayName, TreeViewTest.BackendData.Foo foo) : base(id, depth, parent, displayName) + { + this.foo = foo; + } + } + private class TestDataSource : TreeViewDataSource + { + private TreeViewTest.BackendData m_Backend; + public int itemCounter + { + get; + private set; + } + public TestDataSource(TreeView treeView, TreeViewTest.BackendData data) : base(treeView) + { + this.m_Backend = data; + this.FetchData(); + } + public override void FetchData() + { + this.itemCounter = 1; + this.m_RootItem = new TreeViewTest.FooTreeViewItem(this.m_Backend.root.id, 0, null, this.m_Backend.root.name, this.m_Backend.root); + this.AddChildrenRecursive(this.m_Backend.root, this.m_RootItem); + this.m_NeedRefreshVisibleFolders = true; + } + private void AddChildrenRecursive(TreeViewTest.BackendData.Foo source, TreeViewItem dest) + { + if (source.hasChildren) + { + dest.children = new List(source.children.Count); + for (int i = 0; i < source.children.Count; i++) + { + TreeViewTest.BackendData.Foo foo = source.children[i]; + dest.children[i] = new TreeViewTest.FooTreeViewItem(foo.id, dest.depth + 1, dest, foo.name, foo); + this.itemCounter++; + this.AddChildrenRecursive(foo, dest.children[i]); + } + } + } + public override bool CanBeParent(TreeViewItem item) + { + return item.hasChildren; + } + } + private class LazyTestDataSource : LazyTreeViewDataSource + { + private TreeViewTest.BackendData m_Backend; + public int itemCounter + { + get; + private set; + } + public LazyTestDataSource(TreeView treeView, TreeViewTest.BackendData data) : base(treeView) + { + this.m_Backend = data; + this.FetchData(); + } + public override void FetchData() + { + this.itemCounter = 1; + this.m_RootItem = new TreeViewTest.FooTreeViewItem(this.m_Backend.root.id, 0, null, this.m_Backend.root.name, this.m_Backend.root); + this.AddVisibleChildrenRecursive(this.m_Backend.root, this.m_RootItem); + this.m_VisibleRows = new List(); + base.GetVisibleItemsRecursive(this.m_RootItem, this.m_VisibleRows); + this.m_NeedRefreshVisibleFolders = false; + } + private void AddVisibleChildrenRecursive(TreeViewTest.BackendData.Foo source, TreeViewItem dest) + { + if (this.IsExpanded(source.id)) + { + if (source.children != null && source.children.Count > 0) + { + dest.children = new List(source.children.Count); + for (int i = 0; i < source.children.Count; i++) + { + TreeViewTest.BackendData.Foo foo = source.children[i]; + dest.children[i] = new TreeViewTest.FooTreeViewItem(foo.id, dest.depth + 1, dest, foo.name, foo); + this.itemCounter++; + this.AddVisibleChildrenRecursive(foo, dest.children[i]); + } + } + } + else + { + if (source.hasChildren) + { + dest.children = new List + { + new TreeViewItem(-1, -1, null, string.Empty) + }; + } + } + } + public override bool CanBeParent(TreeViewItem item) + { + return item.hasChildren; + } + protected override HashSet GetParentsAbove(int id) + { + HashSet hashSet = new HashSet(); + for (TreeViewTest.BackendData.Foo foo = TreeViewTest.BackendData.FindNodeRecursive(this.m_Backend.root, id); foo != null; foo = foo.parent) + { + if (foo.parent != null) + { + hashSet.Add(foo.parent.id); + } + } + return hashSet; + } + protected override HashSet GetParentsBelow(int id) + { + return this.m_Backend.GetParentsBelow(id); + } + } + private class TestGUI : TreeViewGUI + { + private Texture2D m_FolderIcon = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + private Texture2D m_Icon = EditorGUIUtility.FindTexture("boo Script Icon"); + private GUIStyle m_LabelStyle; + private GUIStyle m_LabelStyleRightAlign; + private float[] columnWidths + { + get + { + return this.m_TreeView.state.columnWidths; + } + } + public TestGUI(TreeView treeView) : base(treeView) + { + } + protected override Texture GetIconForNode(TreeViewItem item) + { + return (!item.hasChildren) ? this.m_Icon : this.m_FolderIcon; + } + protected override void RenameEnded() + { + } + protected override void SyncFakeItem() + { + } + protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + if (this.m_LabelStyle == null) + { + this.m_LabelStyle = new GUIStyle(TreeViewGUI.s_Styles.lineStyle); + RectOffset arg_3F_0 = this.m_LabelStyle.padding; + int num = 6; + this.m_LabelStyle.padding.right = num; + arg_3F_0.left = num; + this.m_LabelStyleRightAlign = new GUIStyle(TreeViewGUI.s_Styles.lineStyle); + RectOffset arg_78_0 = this.m_LabelStyleRightAlign.padding; + num = 6; + this.m_LabelStyleRightAlign.padding.left = num; + arg_78_0.right = num; + this.m_LabelStyleRightAlign.alignment = TextAnchor.MiddleRight; + } + if (isPinging || this.columnWidths == null || this.columnWidths.Length == 0) + { + base.DrawIconAndLabel(rect, item, label, selected, focused, useBoldFont, isPinging); + return; + } + Rect rect2 = rect; + for (int i = 0; i < this.columnWidths.Length; i++) + { + rect2.width = this.columnWidths[i]; + if (i == 0) + { + base.DrawIconAndLabel(rect2, item, label, selected, focused, useBoldFont, isPinging); + } + else + { + GUI.Label(rect2, "Zksdf SDFS DFASDF ", (i % 2 != 0) ? this.m_LabelStyleRightAlign : this.m_LabelStyle); + } + rect2.x += rect2.width; + } + } + } + public class TestDragging : TreeViewDragging + { + private class FooDragData + { + public List m_DraggedItems; + public FooDragData(List draggedItems) + { + this.m_DraggedItems = draggedItems; + } + } + private const string k_GenericDragID = "FooDragging"; + private TreeViewTest.BackendData m_BackendData; + public TestDragging(TreeView treeView, TreeViewTest.BackendData data) : base(treeView) + { + this.m_BackendData = data; + } + public override void StartDrag(TreeViewItem draggedNode, List draggedItemIDs) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.SetGenericData("FooDragging", new TreeViewTest.TestDragging.FooDragData(this.GetItemsFromIDs(draggedItemIDs))); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + string title = draggedItemIDs.Count + " Foo" + ((draggedItemIDs.Count <= 1) ? string.Empty : "s"); + DragAndDrop.StartDrag(title); + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos) + { + TreeViewTest.TestDragging.FooDragData fooDragData = DragAndDrop.GetGenericData("FooDragging") as TreeViewTest.TestDragging.FooDragData; + TreeViewTest.FooTreeViewItem fooTreeViewItem = targetItem as TreeViewTest.FooTreeViewItem; + TreeViewTest.FooTreeViewItem fooTreeViewItem2 = parentItem as TreeViewTest.FooTreeViewItem; + if (fooTreeViewItem2 != null && fooDragData != null) + { + bool flag = this.ValidDrag(parentItem, fooDragData.m_DraggedItems); + if (perform && flag) + { + List draggedItems = ( + from x in fooDragData.m_DraggedItems + where x is TreeViewTest.FooTreeViewItem + select ((TreeViewTest.FooTreeViewItem)x).foo).ToList(); + this.m_BackendData.ReparentSelection(fooTreeViewItem2.foo, fooTreeViewItem.foo, draggedItems); + this.m_TreeView.ReloadData(); + } + return (!flag) ? DragAndDropVisualMode.None : DragAndDropVisualMode.Move; + } + return DragAndDropVisualMode.None; + } + private bool ValidDrag(TreeViewItem parent, List draggedItems) + { + if (!parent.hasChildren) + { + return false; + } + for (TreeViewItem treeViewItem = parent; treeViewItem != null; treeViewItem = treeViewItem.parent) + { + if (draggedItems.Contains(treeViewItem)) + { + return false; + } + } + return true; + } + private List GetItemsFromIDs(IEnumerable draggedItemIDs) + { + return TreeViewUtility.FindItemsInList(draggedItemIDs, this.m_TreeView.data.GetVisibleRows()); + } + } + public class BackendData + { + public class Foo + { + public string name + { + get; + set; + } + public int id + { + get; + set; + } + public int depth + { + get; + set; + } + public TreeViewTest.BackendData.Foo parent + { + get; + set; + } + public List children + { + get; + set; + } + public bool hasChildren + { + get + { + return this.children != null && this.children.Count > 0; + } + } + public Foo(string name, int depth, int id) + { + this.name = name; + this.depth = depth; + this.id = id; + } + } + private const int k_MinChildren = 3; + private const int k_MaxChildren = 15; + private const float k_ProbOfLastDescendent = 0.5f; + private const int k_MaxDepth = 12; + private TreeViewTest.BackendData.Foo m_Root; + public bool m_RecursiveFindParentsBelow = true; + private int m_MaxItems = 10000; + public TreeViewTest.BackendData.Foo root + { + get + { + return this.m_Root; + } + } + public int IDCounter + { + get; + private set; + } + public void GenerateData(int maxNumItems) + { + this.m_MaxItems = maxNumItems; + this.IDCounter = 1; + this.m_Root = new TreeViewTest.BackendData.Foo("Root", 0, 0); + while (this.IDCounter < this.m_MaxItems) + { + this.AddChildrenRecursive(this.m_Root, UnityEngine.Random.Range(3, 15), true); + } + } + public HashSet GetParentsBelow(int id) + { + TreeViewTest.BackendData.Foo foo = TreeViewTest.BackendData.FindNodeRecursive(this.root, id); + if (foo == null) + { + return new HashSet(); + } + if (this.m_RecursiveFindParentsBelow) + { + return this.GetParentsBelowRecursive(foo); + } + return this.GetParentsBelowStackBased(foo); + } + private HashSet GetParentsBelowStackBased(TreeViewTest.BackendData.Foo searchFromThis) + { + Stack stack = new Stack(); + stack.Push(searchFromThis); + HashSet hashSet = new HashSet(); + while (stack.Count > 0) + { + TreeViewTest.BackendData.Foo foo = stack.Pop(); + if (foo.hasChildren) + { + hashSet.Add(foo.id); + foreach (TreeViewTest.BackendData.Foo current in foo.children) + { + stack.Push(current); + } + } + } + return hashSet; + } + private HashSet GetParentsBelowRecursive(TreeViewTest.BackendData.Foo searchFromThis) + { + HashSet hashSet = new HashSet(); + TreeViewTest.BackendData.GetParentsBelowRecursive(searchFromThis, hashSet); + return hashSet; + } + private static void GetParentsBelowRecursive(TreeViewTest.BackendData.Foo item, HashSet parentIDs) + { + if (!item.hasChildren) + { + return; + } + parentIDs.Add(item.id); + foreach (TreeViewTest.BackendData.Foo current in item.children) + { + TreeViewTest.BackendData.GetParentsBelowRecursive(current, parentIDs); + } + } + public void ReparentSelection(TreeViewTest.BackendData.Foo parentItem, TreeViewTest.BackendData.Foo insertAfterItem, List draggedItems) + { + foreach (TreeViewTest.BackendData.Foo current in draggedItems) + { + current.parent.children.Remove(current); + current.parent = parentItem; + } + if (!parentItem.hasChildren) + { + parentItem.children = new List(); + } + List list = new List(parentItem.children); + int index = 0; + if (parentItem == insertAfterItem) + { + index = 0; + } + else + { + int num = parentItem.children.IndexOf(insertAfterItem); + if (num >= 0) + { + index = num + 1; + } + else + { + Debug.LogError("Did not find insertAfterItem, should be a child of parentItem!!"); + } + } + list.InsertRange(index, draggedItems); + parentItem.children = list; + } + private void AddChildrenRecursive(TreeViewTest.BackendData.Foo foo, int numChildren, bool force) + { + if (this.IDCounter > this.m_MaxItems) + { + return; + } + if (foo.depth >= 12) + { + return; + } + if (!force && UnityEngine.Random.value < 0.5f) + { + return; + } + if (foo.children == null) + { + foo.children = new List(numChildren); + } + for (int i = 0; i < numChildren; i++) + { + TreeViewTest.BackendData.Foo foo2 = new TreeViewTest.BackendData.Foo("Tud" + this.IDCounter, foo.depth + 1, ++this.IDCounter); + foo2.parent = foo; + foo.children.Add(foo2); + } + if (this.IDCounter > this.m_MaxItems) + { + return; + } + foreach (TreeViewTest.BackendData.Foo current in foo.children) + { + this.AddChildrenRecursive(current, UnityEngine.Random.Range(3, 15), false); + } + } + public static TreeViewTest.BackendData.Foo FindNodeRecursive(TreeViewTest.BackendData.Foo item, int id) + { + if (item == null) + { + return null; + } + if (item.id == id) + { + return item; + } + if (item.children == null) + { + return null; + } + foreach (TreeViewTest.BackendData.Foo current in item.children) + { + TreeViewTest.BackendData.Foo foo = TreeViewTest.BackendData.FindNodeRecursive(current, id); + if (foo != null) + { + return foo; + } + } + return null; + } + } + internal class TreeViewColumnHeader + { + public float[] columnWidths + { + get; + set; + } + public float minColumnWidth + { + get; + set; + } + public float dragWidth + { + get; + set; + } + public Action columnRenderer + { + get; + set; + } + public TreeViewColumnHeader() + { + this.minColumnWidth = 10f; + this.dragWidth = 6f; + } + public void OnGUI(Rect rect) + { + float num = rect.x; + for (int i = 0; i < this.columnWidths.Length; i++) + { + Rect arg = new Rect(num, rect.y, this.columnWidths[i], rect.height); + num += this.columnWidths[i]; + Rect position = new Rect(num - this.dragWidth / 2f, rect.y, 3f, rect.height); + float x = EditorGUI.MouseDeltaReader(position, true).x; + if (x != 0f) + { + this.columnWidths[i] += x; + this.columnWidths[i] = Mathf.Max(this.columnWidths[i], this.minColumnWidth); + } + if (this.columnRenderer != null) + { + this.columnRenderer(i, arg); + } + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(position, MouseCursor.SplitResizeLeftRight); + } + } + } + } + private TreeViewTest.BackendData m_BackendData; + private TreeView m_TreeView; + private EditorWindow m_EditorWindow; + private bool m_Lazy; + private TreeViewTest.TreeViewColumnHeader m_ColumnHeader; + private GUIStyle m_HeaderStyle; + private GUIStyle m_HeaderStyleRightAligned; + public TreeViewTest(EditorWindow editorWindow, bool lazy) + { + this.m_EditorWindow = editorWindow; + this.m_Lazy = lazy; + } + public int GetNumItemsInData() + { + return this.m_BackendData.IDCounter; + } + public int GetNumItemsInTree() + { + TreeViewTest.LazyTestDataSource lazyTestDataSource = this.m_TreeView.data as TreeViewTest.LazyTestDataSource; + if (lazyTestDataSource != null) + { + return lazyTestDataSource.itemCounter; + } + TreeViewTest.TestDataSource testDataSource = this.m_TreeView.data as TreeViewTest.TestDataSource; + if (testDataSource != null) + { + return testDataSource.itemCounter; + } + return -1; + } + public void Init(Rect rect, TreeViewTest.BackendData backendData) + { + if (this.m_TreeView != null) + { + return; + } + this.m_BackendData = backendData; + TreeViewState treeViewState = new TreeViewState(); + treeViewState.columnWidths = new float[] + { + 250f, + 90f, + 93f, + 98f, + 74f, + 78f + }; + this.m_TreeView = new TreeView(this.m_EditorWindow, treeViewState); + ITreeViewGUI gui = new TreeViewTest.TestGUI(this.m_TreeView); + ITreeViewDragging dragging = new TreeViewTest.TestDragging(this.m_TreeView, this.m_BackendData); + ITreeViewDataSource data; + if (this.m_Lazy) + { + data = new TreeViewTest.LazyTestDataSource(this.m_TreeView, this.m_BackendData); + } + else + { + data = new TreeViewTest.TestDataSource(this.m_TreeView, this.m_BackendData); + } + this.m_TreeView.Init(rect, data, gui, dragging); + this.m_ColumnHeader = new TreeViewTest.TreeViewColumnHeader(); + this.m_ColumnHeader.columnWidths = treeViewState.columnWidths; + this.m_ColumnHeader.minColumnWidth = 30f; + TreeViewTest.TreeViewColumnHeader expr_D5 = this.m_ColumnHeader; + expr_D5.columnRenderer = (Action)Delegate.Combine(expr_D5.columnRenderer, new Action(this.OnColumnRenderer)); + } + private void OnColumnRenderer(int column, Rect rect) + { + if (this.m_HeaderStyle == null) + { + this.m_HeaderStyle = new GUIStyle(EditorStyles.toolbarButton); + this.m_HeaderStyle.padding.left = 4; + this.m_HeaderStyle.alignment = TextAnchor.MiddleLeft; + this.m_HeaderStyleRightAligned = new GUIStyle(EditorStyles.toolbarButton); + this.m_HeaderStyleRightAligned.padding.right = 4; + this.m_HeaderStyleRightAligned.alignment = TextAnchor.MiddleRight; + } + string[] array = new string[] + { + "Name", + "Date Modified", + "Size", + "Kind", + "Author", + "Platform", + "Faster", + "Slower" + }; + GUI.Label(rect, array[column], (column % 2 != 0) ? this.m_HeaderStyleRightAligned : this.m_HeaderStyle); + } + public void OnGUI(Rect rect) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard, rect); + Rect rect2 = new Rect(rect.x, rect.y, rect.width, 17f); + Rect screenRect = new Rect(rect.x, rect.yMax - 20f, rect.width, 20f); + GUI.Label(rect2, string.Empty, EditorStyles.toolbar); + this.m_ColumnHeader.OnGUI(rect2); + Profiler.BeginSample("TREEVIEW"); + rect.y += rect2.height; + rect.height -= rect2.height + screenRect.height; + this.m_TreeView.OnEvent(); + this.m_TreeView.OnGUI(rect, controlID); + Profiler.EndSample(); + GUILayout.BeginArea(screenRect, this.GetHeader(), EditorStyles.helpBox); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + this.m_BackendData.m_RecursiveFindParentsBelow = GUILayout.Toggle(this.m_BackendData.m_RecursiveFindParentsBelow, GUIContent.Temp("Recursive"), new GUILayoutOption[0]); + if (GUILayout.Button("Ping", EditorStyles.miniButton, new GUILayoutOption[0])) + { + int num = this.GetNumItemsInData() / 2; + this.m_TreeView.Frame(num, true, true); + this.m_TreeView.SetSelection(new int[] + { + num + }, false); + } + if (GUILayout.Button("Frame", EditorStyles.miniButton, new GUILayoutOption[0])) + { + int num2 = this.GetNumItemsInData() / 10; + this.m_TreeView.Frame(num2, true, false); + this.m_TreeView.SetSelection(new int[] + { + num2 + }, false); + } + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } + private string GetHeader() + { + return string.Concat(new object[] + { + (!this.m_Lazy) ? "FULL: " : "LAZY: ", + "GUI items: ", + this.GetNumItemsInTree(), + " (data items: ", + this.GetNumItemsInData(), + ")" + }); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewTestWindow.cs b/UnityEditor/UnityEditor/TreeViewTestWindow.cs new file mode 100644 index 00000000..30cda5a8 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewTestWindow.cs @@ -0,0 +1,34 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeViewTestWindow : EditorWindow + { + private TreeViewTest.BackendData m_BackendData; + private TreeViewTest m_TreeViewTest; + private TreeViewTest m_TreeViewTest2; + public TreeViewTestWindow() + { + base.title = "TreeView Test"; + } + private void OnGUI() + { + Rect rect = new Rect(0f, 0f, base.position.width / 2f, base.position.height); + Rect rect2 = new Rect(base.position.width / 2f, 0f, base.position.width / 2f, base.position.height); + if (this.m_TreeViewTest == null) + { + this.m_BackendData = new TreeViewTest.BackendData(); + this.m_BackendData.GenerateData(1000000); + bool lazy = false; + this.m_TreeViewTest = new TreeViewTest(this, lazy); + this.m_TreeViewTest.Init(rect, this.m_BackendData); + lazy = true; + this.m_TreeViewTest2 = new TreeViewTest(this, lazy); + this.m_TreeViewTest2.Init(rect2, this.m_BackendData); + } + this.m_TreeViewTest.OnGUI(rect); + this.m_TreeViewTest2.OnGUI(rect2); + EditorGUI.DrawRect(new Rect(rect.xMax - 1f, 0f, 2f, base.position.height), new Color(0.4f, 0.4f, 0.4f, 0.8f)); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewUtility.cs b/UnityEditor/UnityEditor/TreeViewUtility.cs new file mode 100644 index 00000000..858d2329 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewUtility.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.Linq; +namespace UnityEditor +{ + internal static class TreeViewUtility + { + public static List FindItemsInList(IEnumerable itemIDs, List treeViewItems) + { + return ( + from x in treeViewItems + where itemIDs.Contains(x.id) + select x).ToList(); + } + public static TreeViewItem FindItemInList(int id, List treeViewItems) + { + return treeViewItems.FirstOrDefault((TreeViewItem t) => t.id == id); + } + public static TreeViewItem FindItem(int id, TreeViewItem searchFromThisItem) + { + return TreeViewUtility.FindItemRecursive(id, searchFromThisItem); + } + private static TreeViewItem FindItemRecursive(int id, TreeViewItem item) + { + if (item == null) + { + return null; + } + if (item.id == id) + { + return item; + } + if (!item.hasChildren) + { + return null; + } + foreach (TreeViewItem current in item.children) + { + TreeViewItem treeViewItem = TreeViewUtility.FindItemRecursive(id, current); + if (treeViewItem != null) + { + return treeViewItem; + } + } + return null; + } + public static void DebugPrintToEditorLogRecursive(TreeViewItem item) + { + if (item == null) + { + return; + } + Console.WriteLine(new string(' ', item.depth * 3) + item.displayName); + if (!item.hasChildren) + { + return; + } + foreach (TreeViewItem current in item.children) + { + TreeViewUtility.DebugPrintToEditorLogRecursive(current); + } + } + public static void SetChildParentReferences(List visibleItems, TreeViewItem root) + { + Dictionary> dictionary = new Dictionary>(); + for (int i = 0; i < visibleItems.Count; i++) + { + TreeViewItem treeViewItem = visibleItems[i]; + TreeViewItem treeViewItem2 = TreeViewUtility.FindParent(visibleItems, treeViewItem.depth, i); + if (treeViewItem2 == null) + { + treeViewItem2 = root; + } + if (!dictionary.ContainsKey(treeViewItem2)) + { + dictionary.Add(treeViewItem2, new List(4)); + } + dictionary[treeViewItem2].Add(treeViewItem); + treeViewItem.parent = treeViewItem2; + } + foreach (KeyValuePair> current in dictionary) + { + TreeViewUtility.SetParent(current.Value, current.Key); + } + } + private static void SetParent(List children, TreeViewItem parent) + { + if (parent.hasChildren && parent.children[0] == null) + { + parent.children.RemoveAt(0); + } + if (parent.children == null) + { + parent.children = new List(children.Count); + } + parent.children.AddRange(children); + } + private static void SetParent(TreeViewItem child, TreeViewItem parent) + { + child.parent = parent; + if (parent.hasChildren && parent.children[0] == null) + { + parent.children.RemoveAt(0); + } + parent.AddChild(child); + } + private static TreeViewItem FindParent(List visibleItems, int childDepth, int childIndex) + { + if (childDepth == 0) + { + return null; + } + while (childIndex >= 0) + { + TreeViewItem treeViewItem = visibleItems[childIndex]; + if (treeViewItem.depth == childDepth - 1) + { + return treeViewItem; + } + childIndex--; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/TreeWizard.cs b/UnityEditor/UnityEditor/TreeWizard.cs new file mode 100644 index 00000000..18843a39 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeWizard.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TreeWizard : TerrainWizard + { + public GameObject m_Tree; + public float m_BendFactor; + private int m_PrototypeIndex = -1; + public void OnEnable() + { + base.minSize = new Vector2(400f, 150f); + } + internal void InitializeDefaults(Terrain terrain, int index) + { + this.m_Terrain = terrain; + this.m_PrototypeIndex = index; + if (this.m_PrototypeIndex == -1) + { + this.m_Tree = null; + this.m_BendFactor = 0f; + } + else + { + this.m_Tree = this.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].prefab; + this.m_BendFactor = this.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].bendFactor; + } + this.OnWizardUpdate(); + } + private void DoApply() + { + if (base.terrainData == null) + { + return; + } + TreePrototype[] treePrototypes = this.m_Terrain.terrainData.treePrototypes; + if (this.m_PrototypeIndex == -1) + { + TreePrototype[] array = new TreePrototype[treePrototypes.Length + 1]; + for (int i = 0; i < treePrototypes.Length; i++) + { + array[i] = treePrototypes[i]; + } + array[treePrototypes.Length] = new TreePrototype(); + array[treePrototypes.Length].prefab = this.m_Tree; + array[treePrototypes.Length].bendFactor = this.m_BendFactor; + this.m_PrototypeIndex = treePrototypes.Length; + this.m_Terrain.terrainData.treePrototypes = array; + } + else + { + treePrototypes[this.m_PrototypeIndex].prefab = this.m_Tree; + treePrototypes[this.m_PrototypeIndex].bendFactor = this.m_BendFactor; + this.m_Terrain.terrainData.treePrototypes = treePrototypes; + } + this.m_Terrain.Flush(); + EditorUtility.SetDirty(this.m_Terrain); + } + private void OnWizardCreate() + { + this.DoApply(); + } + private void OnWizardOtherButton() + { + this.DoApply(); + } + internal override void OnWizardUpdate() + { + base.OnWizardUpdate(); + if (this.m_Tree == null) + { + base.errorString = "Please assign a tree"; + base.isValid = false; + } + else + { + if (this.m_PrototypeIndex != -1) + { + this.DoApply(); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/TrueTypeFontImporter.cs b/UnityEditor/UnityEditor/TrueTypeFontImporter.cs new file mode 100644 index 00000000..5d8f6eef --- /dev/null +++ b/UnityEditor/UnityEditor/TrueTypeFontImporter.cs @@ -0,0 +1,125 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class TrueTypeFontImporter : AssetImporter + { + public extern int fontSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FontTextureCase fontTextureCase + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("FontRenderModes are no longer supported.", true)] + private int fontRenderMode + { + get + { + return 0; + } + set + { + } + } + public extern bool includeFontData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("use2xBehaviour is deprecated and will be removed in a future release.")] + public extern bool use2xBehaviour + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string[] fontNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string customCharacters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string fontTTFName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Per-Font styles are no longer supported. Set the style in the rendering component, or import a styled version of the font.", true)] + private FontStyle style + { + get + { + return FontStyle.Normal; + } + set + { + } + } + public extern int characterSpacing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int characterPadding + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FontRenderingMode fontRenderingMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool IsFormatSupported(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Font GenerateEditableFont(string path); + } +} diff --git a/UnityEditor/UnityEditor/TrueTypeFontImporterInspector.cs b/UnityEditor/UnityEditor/TrueTypeFontImporterInspector.cs new file mode 100644 index 00000000..2ea2c5f1 --- /dev/null +++ b/UnityEditor/UnityEditor/TrueTypeFontImporterInspector.cs @@ -0,0 +1,242 @@ +using System; +using System.IO; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(TrueTypeFontImporter))] + internal class TrueTypeFontImporterInspector : AssetImporterInspector + { + private SerializedProperty m_FontSize; + private SerializedProperty m_TextureCase; + private SerializedProperty m_IncludeFontData; + private SerializedProperty m_FontNamesArraySize; + private SerializedProperty m_CustomCharacters; + private SerializedProperty m_FontRenderingMode; + private string m_FontNamesString = string.Empty; + private string m_DefaultFontNamesString = string.Empty; + private bool? m_FormatSupported; + private static GUIContent[] kCharacterStrings = new GUIContent[] + { + new GUIContent("Dynamic"), + new GUIContent("Unicode"), + new GUIContent("ASCII default set"), + new GUIContent("ASCII upper case"), + new GUIContent("ASCII lower case"), + new GUIContent("Custom set") + }; + private static int[] kCharacterValues = new int[] + { + -2, + -1, + 0, + 1, + 2, + 3 + }; + private static GUIContent[] kRenderingModeStrings = new GUIContent[] + { + new GUIContent("Smooth"), + new GUIContent("Hinted Smooth"), + new GUIContent("Hinted Raster"), + new GUIContent("OS Default") + }; + private static int[] kRenderingModeValues = new int[] + { + 0, + 1, + 2, + 3 + }; + private void OnEnable() + { + this.m_FontSize = base.serializedObject.FindProperty("m_FontSize"); + this.m_TextureCase = base.serializedObject.FindProperty("m_ForceTextureCase"); + this.m_IncludeFontData = base.serializedObject.FindProperty("m_IncludeFontData"); + this.m_FontNamesArraySize = base.serializedObject.FindProperty("m_FontNames.Array.size"); + this.m_CustomCharacters = base.serializedObject.FindProperty("m_CustomCharacters"); + this.m_FontRenderingMode = base.serializedObject.FindProperty("m_FontRenderingMode"); + if (base.targets.Length == 1) + { + this.m_DefaultFontNamesString = this.GetDefaultFontNames(); + this.m_FontNamesString = this.GetFontNames(); + } + } + private string GetDefaultFontNames() + { + TrueTypeFontImporter trueTypeFontImporter = this.target as TrueTypeFontImporter; + return trueTypeFontImporter.fontTTFName; + } + private string GetFontNames() + { + TrueTypeFontImporter trueTypeFontImporter = this.target as TrueTypeFontImporter; + string text = string.Empty; + string[] fontNames = trueTypeFontImporter.fontNames; + for (int i = 0; i < fontNames.Length; i++) + { + text += fontNames[i]; + if (i < fontNames.Length - 1) + { + text += ", "; + } + } + if (text == string.Empty) + { + text = this.m_DefaultFontNamesString; + } + return text; + } + private void SetFontNames(string fontNames) + { + string[] array; + if (fontNames == this.m_DefaultFontNamesString) + { + array = new string[] + { + string.Empty + }; + } + else + { + array = fontNames.Split(new char[] + { + ',' + }); + for (int i = 0; i < array.Length; i++) + { + array[i] = array[i].Trim(); + } + } + this.m_FontNamesArraySize.intValue = array.Length; + SerializedProperty serializedProperty = this.m_FontNamesArraySize.Copy(); + for (int j = 0; j < array.Length; j++) + { + serializedProperty.Next(false); + serializedProperty.stringValue = array[j]; + } + } + private void ShowFormatUnsupportedGUI() + { + GUILayout.Space(5f); + EditorGUILayout.HelpBox("Format of selected font is not supported by Unity.", MessageType.Warning); + } + private static string GetUniquePath(string basePath, string extension) + { + for (int i = 0; i < 10000; i++) + { + string text = basePath + ((i != 0) ? (string.Empty + i) : string.Empty) + "." + extension; + if (!File.Exists(text)) + { + return text; + } + } + return string.Empty; + } + [MenuItem("CONTEXT/TrueTypeFontImporter/Create Editable Copy")] + private static void CreateEditableCopy(MenuCommand command) + { + TrueTypeFontImporter trueTypeFontImporter = command.context as TrueTypeFontImporter; + if (trueTypeFontImporter.fontTextureCase == FontTextureCase.Dynamic) + { + EditorUtility.DisplayDialog("Cannot generate editabled font asset for dynamic fonts", "Please reimport the font in a different mode.", "Ok"); + return; + } + string str = Path.GetDirectoryName(trueTypeFontImporter.assetPath) + "/" + Path.GetFileNameWithoutExtension(trueTypeFontImporter.assetPath); + EditorGUIUtility.PingObject(trueTypeFontImporter.GenerateEditableFont(TrueTypeFontImporterInspector.GetUniquePath(str + "_copy", "fontsettings"))); + } + public override void OnInspectorGUI() + { + if (!this.m_FormatSupported.HasValue) + { + this.m_FormatSupported = new bool?(true); + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + TrueTypeFontImporter trueTypeFontImporter = @object as TrueTypeFontImporter; + if (trueTypeFontImporter == null || !trueTypeFontImporter.IsFormatSupported()) + { + this.m_FormatSupported = new bool?(false); + } + } + } + if (this.m_FormatSupported == false) + { + this.ShowFormatUnsupportedGUI(); + return; + } + EditorGUILayout.PropertyField(this.m_FontSize, new GUILayoutOption[0]); + if (this.m_FontSize.intValue < 1) + { + this.m_FontSize.intValue = 1; + } + if (this.m_FontSize.intValue > 500) + { + this.m_FontSize.intValue = 500; + } + EditorGUILayout.IntPopup(this.m_FontRenderingMode, TrueTypeFontImporterInspector.kRenderingModeStrings, TrueTypeFontImporterInspector.kRenderingModeValues, new GUIContent("Rendering Mode"), new GUILayoutOption[0]); + EditorGUILayout.IntPopup(this.m_TextureCase, TrueTypeFontImporterInspector.kCharacterStrings, TrueTypeFontImporterInspector.kCharacterValues, new GUIContent("Character"), new GUILayoutOption[0]); + if (!this.m_TextureCase.hasMultipleDifferentValues) + { + if (this.m_TextureCase.intValue != -2) + { + if (this.m_TextureCase.intValue == 3) + { + EditorGUI.BeginChangeCheck(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Custom Chars"); + EditorGUI.showMixedValue = this.m_CustomCharacters.hasMultipleDifferentValues; + string text = EditorGUILayout.TextArea(this.m_CustomCharacters.stringValue, GUI.skin.textArea, new GUILayoutOption[] + { + GUILayout.MinHeight(32f) + }); + EditorGUI.showMixedValue = false; + GUILayout.EndHorizontal(); + if (EditorGUI.EndChangeCheck()) + { + text = new string(text.Distinct().ToArray()); + text = text.Replace("\n", string.Empty); + text = text.Replace("\r", string.Empty); + this.m_CustomCharacters.stringValue = text; + } + } + } + else + { + EditorGUILayout.PropertyField(this.m_IncludeFontData, new GUIContent("Incl. Font Data"), new GUILayoutOption[0]); + if (base.targets.Length == 1) + { + EditorGUI.BeginChangeCheck(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Font Names"); + GUI.SetNextControlName("fontnames"); + this.m_FontNamesString = EditorGUILayout.TextArea(this.m_FontNamesString, "TextArea", new GUILayoutOption[] + { + GUILayout.MinHeight(32f) + }); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginDisabledGroup(this.m_FontNamesString == this.m_DefaultFontNamesString); + if (GUILayout.Button("Reset", "MiniButton", new GUILayoutOption[0])) + { + GUI.changed = true; + if (GUI.GetNameOfFocusedControl() == "fontnames") + { + GUIUtility.keyboardControl = 0; + } + this.m_FontNamesString = this.m_DefaultFontNamesString; + } + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + if (EditorGUI.EndChangeCheck()) + { + this.SetFontNames(this.m_FontNamesString); + } + } + } + } + base.ApplyRevertGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/TypeSelection.cs b/UnityEditor/UnityEditor/TypeSelection.cs new file mode 100644 index 00000000..a4505fcb --- /dev/null +++ b/UnityEditor/UnityEditor/TypeSelection.cs @@ -0,0 +1,33 @@ +using NUnit.Framework; +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class TypeSelection : IComparable + { + public GUIContent label; + public UnityEngine.Object[] objects; + public TypeSelection(string typeName, UnityEngine.Object[] objects) + { + Assert.That(objects != null || objects.Length >= 1); + this.objects = objects; + this.label = new GUIContent(string.Concat(new object[] + { + objects.Length, + " ", + ObjectNames.NicifyVariableName(typeName), + (objects.Length <= 1) ? string.Empty : "s" + })); + this.label.image = AssetPreview.GetMiniTypeThumbnail(objects[0]); + } + public int CompareTo(object o) + { + TypeSelection typeSelection = (TypeSelection)o; + if (typeSelection.objects.Length != this.objects.Length) + { + return typeSelection.objects.Length.CompareTo(this.objects.Length); + } + return this.label.text.CompareTo(typeSelection.label.text); + } + } +} diff --git a/UnityEditor/UnityEditor/TypeSelectionList.cs b/UnityEditor/UnityEditor/TypeSelectionList.cs new file mode 100644 index 00000000..960f6e1f --- /dev/null +++ b/UnityEditor/UnityEditor/TypeSelectionList.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class TypeSelectionList + { + private List m_TypeSelections; + public List typeSelections + { + get + { + return this.m_TypeSelections; + } + } + public TypeSelectionList(UnityEngine.Object[] objects) + { + Dictionary> dictionary = new Dictionary>(); + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + string typeName = ObjectNames.GetTypeName(@object); + if (!dictionary.ContainsKey(typeName)) + { + dictionary[typeName] = new List(); + } + dictionary[typeName].Add(@object); + } + this.m_TypeSelections = new List(); + foreach (KeyValuePair> current in dictionary) + { + this.m_TypeSelections.Add(new TypeSelection(current.Key, current.Value.ToArray())); + } + this.m_TypeSelections.Sort(); + } + } +} diff --git a/UnityEditor/UnityEditor/UIOrientation.cs b/UnityEditor/UnityEditor/UIOrientation.cs new file mode 100644 index 00000000..c3be295f --- /dev/null +++ b/UnityEditor/UnityEditor/UIOrientation.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum UIOrientation + { + Portrait, + PortraitUpsideDown, + LandscapeRight, + LandscapeLeft, + AutoRotation + } +} diff --git a/UnityEditor/UnityEditor/UVModuleUI.cs b/UnityEditor/UnityEditor/UVModuleUI.cs new file mode 100644 index 00000000..6ef6e816 --- /dev/null +++ b/UnityEditor/UnityEditor/UVModuleUI.cs @@ -0,0 +1,87 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class UVModuleUI : ModuleUI + { + private enum AnimationType + { + WholeSheet, + SingleRow + } + private class Texts + { + public GUIContent frameOverTime = new GUIContent("Frame over Time", "Controls the uv animation frame of each particle over its lifetime. On the horisontal axis you will find the lifetime. On the vertical axis you will find the sheet index."); + public GUIContent animation = new GUIContent("Animation", "Specifies the animation type: Whole Sheet or Single Row. Whole Sheet will animate over the whole texture sheet from left to right, top to bottom. Single Row will animate a single row in the sheet from left to right."); + public GUIContent tiles = new GUIContent("Tiles", "Defines the tiling of the texture."); + public GUIContent tilesX = new GUIContent("X"); + public GUIContent tilesY = new GUIContent("Y"); + public GUIContent row = new GUIContent("Row", "The row in the sheet which will be played."); + public GUIContent frame = new GUIContent("Frame", "The frame in the sheet which will be used."); + public GUIContent cycles = new GUIContent("Cycles", "Specifies how many times the animation will loop during the lifetime of the particle."); + public GUIContent randomRow = new GUIContent("Random Row", "If enabled, the animated row will be chosen randomly."); + public string[] types = new string[] + { + "Whole Sheet", + "Single Row" + }; + } + private SerializedMinMaxCurve m_FrameOverTime; + private SerializedProperty m_TilesX; + private SerializedProperty m_TilesY; + private SerializedProperty m_AnimationType; + private SerializedProperty m_Cycles; + private SerializedProperty m_RandomRow; + private SerializedProperty m_RowIndex; + private static UVModuleUI.Texts s_Texts; + public UVModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "UVModule", displayName) + { + this.m_ToolTip = "Particle UV animation. This allows you to specify a texture sheet (a texture with multiple tiles/sub frames) and animate or randomize over it per particle."; + } + protected override void Init() + { + if (this.m_TilesX != null) + { + return; + } + if (UVModuleUI.s_Texts == null) + { + UVModuleUI.s_Texts = new UVModuleUI.Texts(); + } + this.m_FrameOverTime = new SerializedMinMaxCurve(this, UVModuleUI.s_Texts.frameOverTime, "frameOverTime"); + this.m_TilesX = base.GetProperty("tilesX"); + this.m_TilesY = base.GetProperty("tilesY"); + this.m_AnimationType = base.GetProperty("animationType"); + this.m_Cycles = base.GetProperty("cycles"); + this.m_RandomRow = base.GetProperty("randomRow"); + this.m_RowIndex = base.GetProperty("rowIndex"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (UVModuleUI.s_Texts == null) + { + UVModuleUI.s_Texts = new UVModuleUI.Texts(); + } + ModuleUI.GUIIntDraggableX2(UVModuleUI.s_Texts.tiles, UVModuleUI.s_Texts.tilesX, this.m_TilesX, UVModuleUI.s_Texts.tilesY, this.m_TilesY); + int num = ModuleUI.GUIPopup(UVModuleUI.s_Texts.animation, this.m_AnimationType, UVModuleUI.s_Texts.types); + if (num == 1) + { + ModuleUI.GUIToggle(UVModuleUI.s_Texts.randomRow, this.m_RandomRow); + if (!this.m_RandomRow.boolValue) + { + ModuleUI.GUIInt(UVModuleUI.s_Texts.row, this.m_RowIndex); + } + } + if (num == 1) + { + this.m_FrameOverTime.m_RemapValue = (float)this.m_TilesX.intValue; + } + if (num == 0) + { + this.m_FrameOverTime.m_RemapValue = (float)(this.m_TilesX.intValue * this.m_TilesY.intValue); + } + ModuleUI.GUIMinMaxCurve(UVModuleUI.s_Texts.frameOverTime, this.m_FrameOverTime); + ModuleUI.GUIFloat(UVModuleUI.s_Texts.cycles, this.m_Cycles); + } + } +} diff --git a/UnityEditor/UnityEditor/Undo.cs b/UnityEditor/UnityEditor/Undo.cs new file mode 100644 index 00000000..44a5f5f2 --- /dev/null +++ b/UnityEditor/UnityEditor/Undo.cs @@ -0,0 +1,150 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Undo + { + public delegate void UndoRedoCallback(); + public delegate void WillFlushUndoRecord(); + public delegate UndoPropertyModification[] PostprocessModifications(UndoPropertyModification[] modifications); + public static Undo.UndoRedoCallback undoRedoPerformed; + public static Undo.WillFlushUndoRecord willFlushUndoRecord; + public static Undo.PostprocessModifications postprocessModifications; + public static void RegisterCompleteObjectUndo(UnityEngine.Object objectToUndo, string name) + { + UnityEngine.Object[] objectsToUndo = new UnityEngine.Object[] + { + objectToUndo + }; + Undo.RegisterCompleteObjectUndoMultiple(objectToUndo, objectsToUndo, name, 0); + } + public static void RegisterCompleteObjectUndo(UnityEngine.Object[] objectsToUndo, string name) + { + if (objectsToUndo.Length > 0) + { + Undo.RegisterCompleteObjectUndoMultiple(objectsToUndo[0], objectsToUndo, name, 0); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void RegisterCompleteObjectUndoMultiple(UnityEngine.Object identifier, UnityEngine.Object[] objectsToUndo, string name, int namePriority); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetTransformParent(Transform transform, Transform newParent, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterCreatedObjectUndo(UnityEngine.Object objectToUndo, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DestroyObjectImmediate(UnityEngine.Object objectToUndo); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Component AddComponent(GameObject gameObject, Type type); + public static T AddComponent(GameObject gameObject) where T : Component + { + return Undo.AddComponent(gameObject, typeof(T)) as T; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToUndo, string name); + [Obsolete("Use Undo.RegisterFullObjectHierarchyUndo(Object, string) instead")] + private static void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToUndo) + { + Undo.RegisterFullObjectHierarchyUndo(objectToUndo, "Full Object Hierarchy"); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RecordObject(UnityEngine.Object objectToUndo, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RecordObjects(UnityEngine.Object[] objectsToUndo, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearUndo(UnityEngine.Object identifier); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PerformUndo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PerformRedo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IncrementCurrentGroup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetCurrentGroup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RevertAllInCurrentGroup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RevertAllDownToGroup(int group); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CollapseUndoOperations(int groupIndex); + [Obsolete("Use Undo.RecordObject instead")] + public static void RegisterUndo(UnityEngine.Object objectToUndo, string name) + { + Undo.RegisterCompleteObjectUndo(objectToUndo, name); + } + [Obsolete("Use Undo.RecordObjects instead")] + public static void RegisterUndo(UnityEngine.Object[] objectsToUndo, string name) + { + Undo.RegisterCompleteObjectUndo(objectsToUndo, name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FlushUndoRecordObjects(); + private static UndoPropertyModification[] InvokePostprocessModifications(UndoPropertyModification[] modifications) + { + if (Undo.postprocessModifications != null) + { + return Undo.postprocessModifications(modifications); + } + return modifications; + } + private static void Internal_CallWillFlushUndoRecord() + { + if (Undo.willFlushUndoRecord != null) + { + Undo.willFlushUndoRecord(); + } + } + private static void Internal_CallUndoRedoPerformed() + { + if (Undo.undoRedoPerformed != null) + { + Undo.undoRedoPerformed(); + } + } + [Obsolete("Use Undo.RecordObject instead")] + public static void SetSnapshotTarget(UnityEngine.Object objectToUndo, string name) + { + } + [Obsolete("Use Undo.RecordObject instead")] + public static void SetSnapshotTarget(UnityEngine.Object[] objectsToUndo, string name) + { + } + [Obsolete("Use Undo.RecordObject instead")] + public static void ClearSnapshotTarget() + { + } + [Obsolete("Use Undo.RecordObject instead")] + public static void CreateSnapshot() + { + } + [Obsolete("Use Undo.RecordObject instead")] + public static void RestoreSnapshot() + { + } + [Obsolete("Use Undo.RecordObject instead")] + public static void RegisterSnapshot() + { + } + [Obsolete("Use DestroyObjectImmediate, RegisterCreatedObjectUndo or RegisterUndo instead.")] + public static void RegisterSceneUndo(string name) + { + } + } +} diff --git a/UnityEditor/UnityEditor/UndoPropertyModification.cs b/UnityEditor/UnityEditor/UndoPropertyModification.cs new file mode 100644 index 00000000..c1ccfda5 --- /dev/null +++ b/UnityEditor/UnityEditor/UndoPropertyModification.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEditor +{ + public struct UndoPropertyModification + { + public PropertyModification propertyModification; + private int m_KeepPrefabOverride; + public bool keepPrefabOverride + { + get + { + return this.m_KeepPrefabOverride != 0; + } + set + { + this.m_KeepPrefabOverride = ((!value) ? 0 : 1); + } + } + } +} diff --git a/UnityEditor/UnityEditor/UndoSnapshot.cs b/UnityEditor/UnityEditor/UndoSnapshot.cs new file mode 100644 index 00000000..ee9804de --- /dev/null +++ b/UnityEditor/UnityEditor/UndoSnapshot.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Obsolete("Use Undo.RecordObject before modifying the object instead")] + public sealed class UndoSnapshot + { + public UndoSnapshot(UnityEngine.Object[] objectsToUndo) + { + } + public void Restore() + { + } + public void Dispose() + { + } + } +} diff --git a/UnityEditor/UnityEditor/UnityStats.cs b/UnityEditor/UnityEditor/UnityStats.cs new file mode 100644 index 00000000..9ee15151 --- /dev/null +++ b/UnityEditor/UnityEditor/UnityStats.cs @@ -0,0 +1,150 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class UnityStats + { + public static extern int drawCalls + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int batchedDrawCalls + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int batches + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int triangles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int vertices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int shadowCasters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int renderTextureChanges + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float frameTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float renderTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int renderTextureCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int renderTextureBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int usedTextureMemorySize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int usedTextureCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string screenRes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int screenBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int vboTotal + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int vboTotalBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int vboUploads + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int vboUploadBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int ibUploads + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int ibUploadBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int visibleSkinnedMeshes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int visibleAnimations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetNetworkStats(int i); + } +} diff --git a/UnityEditor/UnityEditor/Unsupported.cs b/UnityEditor/UnityEditor/Unsupported.cs new file mode 100644 index 00000000..d178b811 --- /dev/null +++ b/UnityEditor/UnityEditor/Unsupported.cs @@ -0,0 +1,175 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Unsupported + { + public struct ProgressiveMesh + { + internal IntPtr opaquePtr; + public static void Create(Mesh src, out Unsupported.ProgressiveMesh pm) + { + pm.opaquePtr = Unsupported.ProgressiveMesh.CreateImpl(src); + } + public static void Destroy(ref Unsupported.ProgressiveMesh pm) + { + Unsupported.ProgressiveMesh.DestroyImpl(pm.opaquePtr); + pm.opaquePtr = IntPtr.Zero; + } + public static void CreateInitialGeometry(Unsupported.ProgressiveMesh pm, Mesh mesh) + { + Unsupported.ProgressiveMesh.CreateInitialGeometryImpl(pm.opaquePtr, mesh); + } + public static void UpdateMesh(Unsupported.ProgressiveMesh pm, int targetTriCount, Mesh mesh) + { + Unsupported.ProgressiveMesh.UpdateMeshImpl(pm.opaquePtr, targetTriCount, mesh); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern IntPtr CreateImpl(Mesh src); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DestroyImpl(IntPtr pmOpaque); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void CreateInitialGeometryImpl(IntPtr pmOpaque, Mesh target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateMeshImpl(IntPtr pmOpaque, int targetTriCount, Mesh target); + } + private static bool s_FakeNonDeveloperBuild = EditorPrefs.GetBool("FakeNonDeveloperBuild", false); + internal static bool fakeNonDeveloperBuild + { + get + { + return Unsupported.s_FakeNonDeveloperBuild; + } + set + { + Unsupported.s_FakeNonDeveloperBuild = value; + EditorPrefs.SetBool("FakeNonDeveloperBuild", value); + } + } + internal static Vector3 MakeNiceVector3(Vector3 vector) + { + return Unsupported.INTERNAL_CALL_MakeNiceVector3(ref vector); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_MakeNiceVector3(ref Vector3 vector); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CaptureScreenshotImmediate(string filePath, int x, int y, int width, int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern NETVersion GetNETVersion(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetSubmenusCommands(string menuPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Type GetTypeFromFullName(string fullName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetSubmenus(string menuPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetSubmenusIncludingSeparators(string menuPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PrepareObjectContextMenu(UnityEngine.Object c, int contextUserData); + public static bool IsDeveloperBuild() + { + return Unsupported.IsDeveloperBuildInternal() && !Unsupported.s_FakeNonDeveloperBuild; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool IsDeveloperBuildInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsBleedingEdgeBuild(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsDestroyScriptableObject(ScriptableObject target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsNativeCodeBuiltInReleaseMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetBaseUnityDeveloperFolder(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopPlayingImmediately(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SceneTrackerFlushDirty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAllowCursorHide(bool allow); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAllowCursorLock(bool allow); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetRenderSettingsUseFogNoDirty(bool fog); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetQualitySettingsShadowDistanceTemporarily(float distance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteGameObjectSelection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyGameObjectsToPasteboard(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PasteGameObjectsFromPasteboard(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetSerializedAssetInterfaceSingleton(string className); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DuplicateGameObjectsUsingPasteboard(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CopyComponentToPasteboard(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PasteComponentFromPasteboard(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PasteComponentValuesFromPasteboard(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyStateToPasteboard(State state, AnimatorController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyStateMachineToPasteboard(StateMachine stateMachine, AnimatorController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PasteToStateMachineFromPasteboard(StateMachine sm, AnimatorController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasStateMachineDataInPasteboard(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SmartReset(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string ResolveSymlinks(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetApplicationSettingCompressAssetsOnImport(bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetApplicationSettingCompressAssetsOnImport(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetLocalIdentifierInFile(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsHiddenFile(string path); + } +} diff --git a/UnityEditor/UnityEditor/UnwrapParam.cs b/UnityEditor/UnityEditor/UnwrapParam.cs new file mode 100644 index 00000000..a93da910 --- /dev/null +++ b/UnityEditor/UnityEditor/UnwrapParam.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public struct UnwrapParam + { + public float angleError; + public float areaError; + public float hardAngle; + public float packMargin; + internal int recollectVertices; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDefaults(out UnwrapParam param); + } +} diff --git a/UnityEditor/UnityEditor/Unwrapping.cs b/UnityEditor/UnityEditor/Unwrapping.cs new file mode 100644 index 00000000..83434442 --- /dev/null +++ b/UnityEditor/UnityEditor/Unwrapping.cs @@ -0,0 +1,30 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Unwrapping + { + public static Vector2[] GeneratePerTriangleUV(Mesh src) + { + UnwrapParam settings = default(UnwrapParam); + UnwrapParam.SetDefaults(out settings); + return Unwrapping.GeneratePerTriangleUV(src, settings); + } + public static Vector2[] GeneratePerTriangleUV(Mesh src, UnwrapParam settings) + { + return Unwrapping.GeneratePerTriangleUVImpl(src, settings); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Vector2[] GeneratePerTriangleUVImpl(Mesh src, UnwrapParam settings); + public static void GenerateSecondaryUVSet(Mesh src) + { + MeshUtility.SetPerTriangleUV2(src, Unwrapping.GeneratePerTriangleUV(src)); + } + public static void GenerateSecondaryUVSet(Mesh src, UnwrapParam settings) + { + MeshUtility.SetPerTriangleUV2(src, Unwrapping.GeneratePerTriangleUV(src, settings)); + } + } +} diff --git a/UnityEditor/UnityEditor/UploadingBuild.cs b/UnityEditor/UnityEditor/UploadingBuild.cs new file mode 100644 index 00000000..43b6aeba --- /dev/null +++ b/UnityEditor/UnityEditor/UploadingBuild.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal struct UploadingBuild + { + public string displayName; + public string url; + public UploadingBuildStatus status; + public float progress; + } +} diff --git a/UnityEditor/UnityEditor/UploadingBuildStatus.cs b/UnityEditor/UnityEditor/UploadingBuildStatus.cs new file mode 100644 index 00000000..3a4cbc43 --- /dev/null +++ b/UnityEditor/UnityEditor/UploadingBuildStatus.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + internal enum UploadingBuildStatus + { + Authorizing, + Authorized, + Uploading, + Uploaded, + UploadFailed + } +} diff --git a/UnityEditor/UnityEditor/UploadingBuildsMonitor.cs b/UnityEditor/UnityEditor/UploadingBuildsMonitor.cs new file mode 100644 index 00000000..3e6326f3 --- /dev/null +++ b/UnityEditor/UnityEditor/UploadingBuildsMonitor.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class UploadingBuildsMonitor : ScriptableObject + { + private class Content + { + public GUIContent m_ProgressBarText = EditorGUIUtility.TextContent("UploadingBuildsMonitor.ProgressBarText"); + public GUIContent m_NoSessionDialogHeader = EditorGUIUtility.TextContent("UploadingBuildsMonitor.NoSessionDialogHeader"); + public GUIContent m_NoSessionDialogText = EditorGUIUtility.TextContent("UploadingBuildsMonitor.NoSessionDialogText"); + public GUIContent m_NoSessionDialogButtonOK = EditorGUIUtility.TextContent("UploadingBuildsMonitor.NoSessionDialogButtonOK"); + public GUIContent m_OverwriteDialogHeader = EditorGUIUtility.TextContent("UploadingBuildsMonitor.OverwriteDialogHeader"); + public GUIContent m_OverwriteDialogText = EditorGUIUtility.TextContent("UploadingBuildsMonitor.OverwriteDialogText"); + public GUIContent m_OverwriteDialogButtonOK = EditorGUIUtility.TextContent("UploadingBuildsMonitor.OverwriteDialogButtonOK"); + public GUIContent m_OverwriteDialogButtonCancel = EditorGUIUtility.TextContent("UploadingBuildsMonitor.OverwriteDialogButtonCancel"); + public GUIContent m_OverwriteDialogButtonVersion = EditorGUIUtility.TextContent("UploadingBuildsMonitor.OverwriteDialogButtonVersion"); + } + private static UploadingBuildsMonitor.Content s_Content; + private static UploadingBuildsMonitor s_UploadingBuildsMonitor; + private UploadingBuild[] m_UploadingBuilds = new UploadingBuild[0]; + private Dictionary m_ProgressSmoothers = new Dictionary(); + private bool m_DidInit; + private UploadingBuildsMonitor() + { + if (UploadingBuildsMonitor.s_Content == null) + { + UploadingBuildsMonitor.s_Content = new UploadingBuildsMonitor.Content(); + } + } + public static void Activate() + { + if (UploadingBuildsMonitor.s_UploadingBuildsMonitor == null) + { + ScriptableObject.CreateInstance(typeof(UploadingBuildsMonitor)); + } + } + public static void Deactivate() + { + UnityEngine.Object.DestroyImmediate(UploadingBuildsMonitor.s_UploadingBuildsMonitor); + } + public static string GetActiveSessionID() + { + return (!string.IsNullOrEmpty(AssetStoreClient.ActiveSessionID)) ? (AssetStoreClient.ActiveSessionID + InternalEditorUtility.GetAuthToken()) : string.Empty; + } + public static void HandleNoSession(string displayName) + { + UploadingBuildsMonitor.Activate(); + AssetStoreLoginWindow.Login(UploadingBuildsMonitor.s_Content.m_NoSessionDialogText.text, delegate(string errorMessage) + { + if (string.IsNullOrEmpty(errorMessage)) + { + UploadingBuildsUtility.ResumeBuildUpload(displayName); + } + else + { + UploadingBuildsUtility.RemoveUploadingBuild(displayName); + } + }); + } + public static void OverwritePrompt(string displayName) + { + int num = EditorUtility.DisplayDialogComplex(UploadingBuildsMonitor.s_Content.m_OverwriteDialogHeader.text, UploadingBuildsMonitor.s_Content.m_OverwriteDialogText.text, UploadingBuildsMonitor.s_Content.m_OverwriteDialogButtonOK.text, UploadingBuildsMonitor.s_Content.m_OverwriteDialogButtonCancel.text, UploadingBuildsMonitor.s_Content.m_OverwriteDialogButtonVersion.text); + if (num == 1) + { + UploadingBuildsUtility.RemoveUploadingBuild(displayName); + AsyncProgressBar.Clear(); + UploadingBuildsMonitor.s_UploadingBuildsMonitor.SyncToState(); + } + else + { + UploadingBuildsUtility.ResumeBuildUpload(displayName, num == 0); + } + } + private void OnEnable() + { + UploadingBuildsMonitor.s_UploadingBuildsMonitor = this; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + this.SyncToState(); + } + private void OnDisable() + { + UploadingBuildsMonitor.s_UploadingBuildsMonitor = null; + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + public static void InternalStateChanged() + { + if (UploadingBuildsMonitor.s_UploadingBuildsMonitor != null) + { + UploadingBuildsMonitor.s_UploadingBuildsMonitor.SyncToState(); + } + } + private void SyncToState() + { + this.m_UploadingBuilds = UploadingBuildsUtility.GetUploadingBuilds(); + } + private ValueSmoother GetProgressSmoother(string url) + { + ValueSmoother valueSmoother; + this.m_ProgressSmoothers.TryGetValue(url, out valueSmoother); + if (valueSmoother == null) + { + valueSmoother = new ValueSmoother(); + this.m_ProgressSmoothers[url] = valueSmoother; + } + return valueSmoother; + } + private void UploadSmoothing() + { + if (this.m_ProgressSmoothers.Count > 0) + { + bool flag = false; + List list = null; + foreach (KeyValuePair current in this.m_ProgressSmoothers) + { + current.Value.Update(); + if (current.Value.GetSmoothValue() < 1f) + { + flag = true; + } + else + { + if (list == null) + { + list = new List(); + } + list.Add(current.Key); + } + } + if (list != null) + { + foreach (string current2 in list) + { + this.m_ProgressSmoothers.Remove(current2); + } + } + if (flag) + { + this.SyncToState(); + } + } + } + private void Update() + { + if (!this.m_DidInit) + { + this.SyncToState(); + this.m_DidInit = true; + } + this.UploadSmoothing(); + if (this.m_UploadingBuilds.Length > 0) + { + this.UpdateBuild(ref this.m_UploadingBuilds[0]); + } + else + { + UploadingBuildsMonitor.Deactivate(); + } + } + private void UpdateBuild(ref UploadingBuild build) + { + switch (build.status) + { + case UploadingBuildStatus.Authorizing: + case UploadingBuildStatus.Authorized: + AsyncProgressBar.Display(UploadingBuildsMonitor.s_Content.m_ProgressBarText.text, 0f); + break; + case UploadingBuildStatus.Uploading: + { + ValueSmoother progressSmoother = this.GetProgressSmoother(build.url); + progressSmoother.SetTargetValue(build.progress); + AsyncProgressBar.Display(UploadingBuildsMonitor.s_Content.m_ProgressBarText.text, progressSmoother.GetSmoothValue()); + break; + } + case UploadingBuildStatus.Uploaded: + case UploadingBuildStatus.UploadFailed: + UploadingBuildsUtility.RemoveUploadingBuild(build.displayName); + AsyncProgressBar.Clear(); + this.SyncToState(); + break; + default: + Debug.LogError("Unhandled enum"); + break; + } + } + } +} diff --git a/UnityEditor/UnityEditor/UploadingBuildsUtility.cs b/UnityEditor/UnityEditor/UploadingBuildsUtility.cs new file mode 100644 index 00000000..d6e809bf --- /dev/null +++ b/UnityEditor/UnityEditor/UploadingBuildsUtility.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class UploadingBuildsUtility + { + internal static void UploadBuild(string buildPath, bool autoRun) + { + UploadingBuildsUtility.UploadBuild(buildPath, 0, autoRun); + } + internal static void UploadBuild(string buildPath, int overwriteHandling, bool autoRun) + { + UploadingBuildsUtility.UploadBuild(buildPath, PlayerSettings.productName, overwriteHandling, autoRun); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UploadBuild(string buildPath, string displayName, int overwriteHandling, bool autoRun); + internal static bool ResumeBuildUpload(string displayName) + { + return UploadingBuildsUtility.ResumeBuildUpload(displayName, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool ResumeBuildUpload(string displayName, bool replace); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern UploadingBuild[] GetUploadingBuilds(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void RemoveUploadingBuild(string displayName); + } +} diff --git a/UnityEditor/UnityEditor/ValueSmoother.cs b/UnityEditor/UnityEditor/ValueSmoother.cs new file mode 100644 index 00000000..e8170a7a --- /dev/null +++ b/UnityEditor/UnityEditor/ValueSmoother.cs @@ -0,0 +1,44 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ValueSmoother + { + private float m_TargetValue; + private float m_CurrentValue; + private float m_LastUpdateTime; + public ValueSmoother() + { + this.m_TargetValue = 0f; + this.m_CurrentValue = 0f; + this.m_LastUpdateTime = Time.realtimeSinceStartup; + } + public float GetSmoothValue() + { + return this.m_CurrentValue; + } + public void SetTargetValue(float value) + { + this.m_TargetValue = value; + if (value == 0f) + { + this.m_CurrentValue = 0f; + } + } + public void Update() + { + if (this.m_CurrentValue < 1f) + { + float num = Mathf.Clamp(Time.realtimeSinceStartup - this.m_LastUpdateTime, 0f, 0.1f); + float num2 = 1f; + float num3 = num2 * num; + this.m_CurrentValue = this.m_CurrentValue * (1f - num3) + this.m_TargetValue * num3; + if (this.m_CurrentValue > 0.995f) + { + this.m_CurrentValue = 1f; + } + } + this.m_LastUpdateTime = Time.realtimeSinceStartup; + } + } +} diff --git a/UnityEditor/UnityEditor/VelocityModuleUI.cs b/UnityEditor/UnityEditor/VelocityModuleUI.cs new file mode 100644 index 00000000..11d09191 --- /dev/null +++ b/UnityEditor/UnityEditor/VelocityModuleUI.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class VelocityModuleUI : ModuleUI + { + private class Texts + { + public GUIContent x = new GUIContent("X"); + public GUIContent y = new GUIContent("Y"); + public GUIContent z = new GUIContent("Z"); + public GUIContent space = new GUIContent("Space", "Specifies if the velocity values are in local space (rotated with the transform) or world space."); + public string[] spaces = new string[] + { + "Local", + "World" + }; + } + private SerializedMinMaxCurve m_X; + private SerializedMinMaxCurve m_Y; + private SerializedMinMaxCurve m_Z; + private SerializedProperty m_InWorldSpace; + private static VelocityModuleUI.Texts s_Texts; + public VelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "VelocityModule", displayName) + { + this.m_ToolTip = "Controls the velocity of each particle during its lifetime."; + } + protected override void Init() + { + if (this.m_X != null) + { + return; + } + if (VelocityModuleUI.s_Texts == null) + { + VelocityModuleUI.s_Texts = new VelocityModuleUI.Texts(); + } + this.m_X = new SerializedMinMaxCurve(this, VelocityModuleUI.s_Texts.x, "x", ModuleUI.kUseSignedRange); + this.m_Y = new SerializedMinMaxCurve(this, VelocityModuleUI.s_Texts.y, "y", ModuleUI.kUseSignedRange); + this.m_Z = new SerializedMinMaxCurve(this, VelocityModuleUI.s_Texts.z, "z", ModuleUI.kUseSignedRange); + this.m_InWorldSpace = base.GetProperty("inWorldSpace"); + } + public override void OnInspectorGUI(ParticleSystem s) + { + if (VelocityModuleUI.s_Texts == null) + { + VelocityModuleUI.s_Texts = new VelocityModuleUI.Texts(); + } + base.GUITripleMinMaxCurve(GUIContent.none, VelocityModuleUI.s_Texts.x, this.m_X, VelocityModuleUI.s_Texts.y, this.m_Y, VelocityModuleUI.s_Texts.z, this.m_Z, null); + ModuleUI.GUIBoolAsPopup(VelocityModuleUI.s_Texts.space, this.m_InWorldSpace, VelocityModuleUI.s_Texts.spaces); + } + public override void UpdateCullingSupportedString(ref string text) + { + this.Init(); + if (!this.m_X.SupportsProcedural() || !this.m_Y.SupportsProcedural() || !this.m_Z.SupportsProcedural()) + { + text += "\n\tLifetime velocity curves use too many keys."; + } + } + } +} diff --git a/UnityEditor/UnityEditor/VertexSnapping.cs b/UnityEditor/UnityEditor/VertexSnapping.cs new file mode 100644 index 00000000..cb5c27ec --- /dev/null +++ b/UnityEditor/UnityEditor/VertexSnapping.cs @@ -0,0 +1,127 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class VertexSnapping + { + private static Vector3 s_VertexSnappingOffset = Vector3.zero; + public static void HandleKeyAndMouseMove(int id) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseMove: + if (Tools.vertexDragging) + { + VertexSnapping.EnableVertexSnapping(id); + current.Use(); + } + break; + case EventType.KeyDown: + if (current.keyCode == KeyCode.V) + { + if (!Tools.vertexDragging && !current.shift) + { + VertexSnapping.EnableVertexSnapping(id); + } + current.Use(); + } + break; + case EventType.KeyUp: + if (current.keyCode == KeyCode.V) + { + if (current.shift) + { + Tools.vertexDragging = !Tools.vertexDragging; + } + else + { + if (Tools.vertexDragging) + { + Tools.vertexDragging = false; + } + } + if (Tools.vertexDragging) + { + VertexSnapping.EnableVertexSnapping(id); + } + else + { + VertexSnapping.DisableVertexSnapping(id); + } + current.Use(); + } + break; + } + } + private static void EnableVertexSnapping(int id) + { + Tools.vertexDragging = true; + if (GUIUtility.hotControl == id) + { + Tools.handleOffset = VertexSnapping.s_VertexSnappingOffset; + } + else + { + VertexSnapping.UpdateVertexSnappingOffset(); + VertexSnapping.s_VertexSnappingOffset = Tools.handleOffset; + } + } + private static void DisableVertexSnapping(int id) + { + Tools.vertexDragging = false; + Tools.handleOffset = Vector3.zero; + if (GUIUtility.hotControl != id) + { + VertexSnapping.s_VertexSnappingOffset = Vector3.zero; + } + } + private static void UpdateVertexSnappingOffset() + { + Event current = Event.current; + Tools.vertexDragging = true; + Transform[] transforms = Selection.GetTransforms((SelectionMode)14); + HandleUtility.ignoreRaySnapObjects = null; + Vector3 vector = VertexSnapping.FindNearestPivot(transforms, current.mousePosition); + Vector3 vector2; + bool flag = HandleUtility.FindNearestVertex(current.mousePosition, transforms, out vector2); + float magnitude = (HandleUtility.WorldToGUIPoint(vector2) - current.mousePosition).magnitude; + float magnitude2 = (HandleUtility.WorldToGUIPoint(vector) - current.mousePosition).magnitude; + Vector3 a; + if (flag && magnitude < magnitude2) + { + a = vector2; + } + else + { + a = vector; + } + Tools.handleOffset = Vector3.zero; + Tools.handleOffset = a - Tools.handlePosition; + } + private static Vector3 FindNearestPivot(Transform[] transforms, Vector2 screenPosition) + { + bool flag = false; + Vector3 vector = Vector3.zero; + for (int i = 0; i < transforms.Length; i++) + { + Transform transform = transforms[i]; + Vector3 b = VertexSnapping.ScreenToWorld(screenPosition, transform); + if (!flag || (vector - b).magnitude > (transform.position - b).magnitude) + { + vector = transform.position; + flag = true; + } + } + return vector; + } + private static Vector3 ScreenToWorld(Vector2 screen, Transform target) + { + Ray ray = HandleUtility.GUIPointToWorldRay(screen); + float distance = 0f; + Plane plane = new Plane(target.forward, target.position); + plane.Raycast(ray, out distance); + return ray.GetPoint(distance); + } + } +} diff --git a/UnityEditor/UnityEditor/VerticalGrid.cs b/UnityEditor/UnityEditor/VerticalGrid.cs new file mode 100644 index 00000000..1ccc4846 --- /dev/null +++ b/UnityEditor/UnityEditor/VerticalGrid.cs @@ -0,0 +1,173 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class VerticalGrid + { + private int m_Columns = 1; + private int m_Rows; + private float m_Height; + private float m_HorizontalSpacing; + public int columns + { + get + { + return this.m_Columns; + } + } + public int rows + { + get + { + return this.m_Rows; + } + } + public float height + { + get + { + return this.m_Height; + } + } + public float horizontalSpacing + { + get + { + return this.m_HorizontalSpacing; + } + } + public float fixedWidth + { + get; + set; + } + public Vector2 itemSize + { + get; + set; + } + public float verticalSpacing + { + get; + set; + } + public float minHorizontalSpacing + { + get; + set; + } + 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; + } + public void InitNumRowsAndColumns(int itemCount, int maxNumRows) + { + if (this.useFixedHorizontalSpacing) + { + this.m_Columns = this.CalcColumns(); + this.m_HorizontalSpacing = this.fixedHorizontalSpacing; + this.m_Rows = Mathf.Min(maxNumRows, this.CalcRows(itemCount)); + this.m_Height = (float)this.m_Rows * (this.itemSize.y + this.verticalSpacing) - this.verticalSpacing + this.topMargin + this.bottomMargin; + } + else + { + this.m_Columns = this.CalcColumns(); + this.m_HorizontalSpacing = Mathf.Max(0f, (this.fixedWidth - ((float)this.m_Columns * this.itemSize.x + this.leftMargin + this.rightMargin)) / (float)this.m_Columns); + this.m_Rows = Mathf.Min(maxNumRows, this.CalcRows(itemCount)); + if (this.m_Rows == 1) + { + this.m_HorizontalSpacing = this.minHorizontalSpacing; + } + this.m_Height = (float)this.m_Rows * (this.itemSize.y + this.verticalSpacing) - this.verticalSpacing + this.topMargin + this.bottomMargin; + } + } + public int CalcColumns() + { + float num = (!this.useFixedHorizontalSpacing) ? this.minHorizontalSpacing : this.fixedHorizontalSpacing; + int a = (int)Mathf.Floor((this.fixedWidth - this.leftMargin - this.rightMargin) / (this.itemSize.x + num)); + return Mathf.Max(a, 1); + } + public int CalcRows(int itemCount) + { + int num = (int)Mathf.Ceil((float)itemCount / (float)this.CalcColumns()); + if (num < 0) + { + return 2147483647; + } + return num; + } + public Rect CalcRect(int itemIdx, float yOffset) + { + float num = Mathf.Floor((float)(itemIdx / this.columns)); + float num2 = (float)itemIdx - num * (float)this.columns; + if (this.useFixedHorizontalSpacing) + { + return new Rect(this.leftMargin + num2 * (this.itemSize.x + this.fixedHorizontalSpacing), num * (this.itemSize.y + this.verticalSpacing) + this.topMargin + yOffset, this.itemSize.x, this.itemSize.y); + } + return new Rect(this.leftMargin + this.horizontalSpacing * 0.5f + num2 * (this.itemSize.x + this.horizontalSpacing), num * (this.itemSize.y + this.verticalSpacing) + this.topMargin + yOffset, this.itemSize.x, this.itemSize.y); + } + public int GetMaxVisibleItems(float height) + { + int num = (int)Mathf.Ceil((height - this.topMargin - this.bottomMargin) / (this.itemSize.y + this.verticalSpacing)); + return num * this.columns; + } + public bool IsVisibleInScrollView(float scrollViewHeight, float scrollPos, float gridStartY, int maxIndex, out int startIndex, out int endIndex) + { + startIndex = (endIndex = 0); + float num = scrollPos + scrollViewHeight; + float num2 = gridStartY + this.topMargin; + if (num2 > num) + { + return false; + } + if (num2 + this.height < scrollPos) + { + return false; + } + float num3 = this.itemSize.y + this.verticalSpacing; + int num4 = Mathf.FloorToInt((scrollPos - num2) / num3); + startIndex = num4 * this.columns; + startIndex = Mathf.Clamp(startIndex, 0, maxIndex); + int num5 = Mathf.FloorToInt((num - num2) / num3); + endIndex = (num5 + 1) * this.columns - 1; + endIndex = Mathf.Clamp(endIndex, 0, maxIndex); + return true; + } + public override string ToString() + { + return string.Format("VerticalGrid: rows {0}, columns {1}, fixedWidth {2}, itemSize {3}", new object[] + { + this.rows, + this.columns, + this.fixedWidth, + this.itemSize + }); + } + } +} diff --git a/UnityEditor/UnityEditor/VerticalGridWithSplitter.cs b/UnityEditor/UnityEditor/VerticalGridWithSplitter.cs new file mode 100644 index 00000000..51135aab --- /dev/null +++ b/UnityEditor/UnityEditor/VerticalGridWithSplitter.cs @@ -0,0 +1,150 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class VerticalGridWithSplitter + { + private int m_Columns = 1; + private int m_Rows; + private float m_Height; + private float m_HorizontalSpacing; + private int m_SplitAfterRow; + private float m_CurrentSplitHeight; + private float m_LastSplitUpdate; + private float m_TargetSplitHeight; + public int columns + { + get + { + return this.m_Columns; + } + } + public int rows + { + get + { + return this.m_Rows; + } + } + public float height + { + get + { + return this.m_Height; + } + } + public float horizontalSpacing + { + get + { + return this.m_HorizontalSpacing; + } + } + public float fixedWidth + { + get; + set; + } + public Vector2 itemSize + { + get; + set; + } + public float verticalSpacing + { + get; + set; + } + public float minHorizontalSpacing + { + get; + set; + } + public float topMargin + { + get; + set; + } + public float bottomMargin + { + get; + set; + } + public float rightMargin + { + get; + set; + } + public float leftMargin + { + get; + set; + } + public void InitNumRowsAndColumns(int itemCount, int maxNumRows) + { + this.m_Columns = (int)Mathf.Floor((this.fixedWidth - this.leftMargin - this.rightMargin) / (this.itemSize.x + this.minHorizontalSpacing)); + this.m_Columns = Mathf.Max(this.m_Columns, 1); + this.m_HorizontalSpacing = 0f; + if (this.m_Columns > 1) + { + this.m_HorizontalSpacing = (this.fixedWidth - ((float)this.m_Columns * this.itemSize.x + this.leftMargin + this.rightMargin)) / (float)(this.m_Columns - 1); + } + this.m_Rows = Mathf.Min(maxNumRows, (int)Mathf.Ceil((float)itemCount / (float)this.m_Columns)); + this.m_Height = (float)this.m_Rows * (this.itemSize.y + this.verticalSpacing) - this.verticalSpacing + this.topMargin + this.bottomMargin; + } + public Rect CalcRect(int itemIdx, float yOffset) + { + float num = Mathf.Floor((float)(itemIdx / this.columns)); + float num2 = (float)itemIdx - num * (float)this.columns; + return new Rect(num2 * (this.itemSize.x + this.horizontalSpacing) + this.leftMargin, num * (this.itemSize.y + this.verticalSpacing) + this.topMargin + yOffset, this.itemSize.x, this.itemSize.y); + } + public int GetMaxVisibleItems(float height) + { + int num = (int)Mathf.Ceil((height - this.topMargin - this.bottomMargin) / (this.itemSize.y + this.verticalSpacing)); + return num * this.columns; + } + public void ResetSplit() + { + this.m_SplitAfterRow = -1; + this.m_CurrentSplitHeight = 0f; + this.m_LastSplitUpdate = -1f; + this.m_TargetSplitHeight = 0f; + } + public void OpenSplit(int splitAfterRowIndex, int numItems) + { + int num = (int)Mathf.Ceil((float)numItems / (float)this.m_Columns); + float targetSplitHeight = (float)num * (this.itemSize.y + this.verticalSpacing) - this.verticalSpacing + this.topMargin + this.bottomMargin; + this.m_SplitAfterRow = splitAfterRowIndex; + this.m_TargetSplitHeight = targetSplitHeight; + this.m_LastSplitUpdate = Time.realtimeSinceStartup; + } + public Rect CalcSplitRect(int splitIndex, float yOffset) + { + Rect result = new Rect(0f, 0f, 0f, 0f); + return result; + } + public void CloseSplit() + { + this.m_TargetSplitHeight = 0f; + } + public bool UpdateSplitAnimationOnGUI() + { + if (this.m_SplitAfterRow != -1) + { + float num = Time.realtimeSinceStartup - this.m_LastSplitUpdate; + this.m_CurrentSplitHeight = num * this.m_TargetSplitHeight; + this.m_LastSplitUpdate = Time.realtimeSinceStartup; + if (this.m_CurrentSplitHeight != this.m_TargetSplitHeight && Event.current.type == EventType.Repaint) + { + this.m_CurrentSplitHeight = Mathf.MoveTowards(this.m_CurrentSplitHeight, this.m_TargetSplitHeight, 0.03f); + if (this.m_CurrentSplitHeight == 0f && this.m_TargetSplitHeight == 0f) + { + this.ResetSplit(); + } + return true; + } + } + return false; + } + } +} diff --git a/UnityEditor/UnityEditor/VerticalLayout.cs b/UnityEditor/UnityEditor/VerticalLayout.cs new file mode 100644 index 00000000..b5c5dfb0 --- /dev/null +++ b/UnityEditor/UnityEditor/VerticalLayout.cs @@ -0,0 +1,21 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class VerticalLayout : IDisposable + { + private static readonly VerticalLayout instance = new VerticalLayout(); + private VerticalLayout() + { + } + void IDisposable.Dispose() + { + GUILayout.EndVertical(); + } + public static IDisposable DoLayout() + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + return VerticalLayout.instance; + } + } +} diff --git a/UnityEditor/UnityEditor/View.cs b/UnityEditor/UnityEditor/View.cs new file mode 100644 index 00000000..67cccb48 --- /dev/null +++ b/UnityEditor/UnityEditor/View.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + internal class View : ScriptableObject + { + [SerializeField] + private MonoReloadableIntPtr m_ViewPtr; + [SerializeField] + private View[] m_Children = new View[0]; + [NonSerialized] + private View m_Parent; + [NonSerialized] + private ContainerWindow m_Window; + [SerializeField] + private Rect m_Position = new Rect(0f, 0f, 100f, 100f); + [SerializeField] + internal Vector2 m_MinSize; + [SerializeField] + internal Vector2 m_MaxSize; + public Vector2 minSize + { + get + { + return this.m_MinSize; + } + } + public Vector2 maxSize + { + get + { + return this.m_MaxSize; + } + } + public View[] allChildren + { + get + { + ArrayList arrayList = new ArrayList(); + View[] children = this.m_Children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + arrayList.AddRange(view.allChildren); + } + arrayList.Add(this); + return (View[])arrayList.ToArray(typeof(View)); + } + } + public Rect position + { + get + { + return this.m_Position; + } + set + { + this.SetPosition(value); + } + } + public Rect windowPosition + { + get + { + if (this.m_Parent == null) + { + return this.position; + } + Rect windowPosition = this.parent.windowPosition; + return new Rect(windowPosition.x + this.position.x, windowPosition.y + this.position.y, this.position.width, this.position.height); + } + } + public Rect screenPosition + { + get + { + Rect windowPosition = this.windowPosition; + if (this.window != null) + { + Vector2 vector = this.window.WindowToScreenPoint(Vector2.zero); + windowPosition.x += vector.x; + windowPosition.y += vector.y; + } + return windowPosition; + } + } + public ContainerWindow window + { + get + { + return this.m_Window; + } + } + public View parent + { + get + { + return this.m_Parent; + } + } + public View[] children + { + get + { + return this.m_Children; + } + } + public View() + { + base.hideFlags = HideFlags.DontSave; + } + internal virtual void Reflow() + { + View[] children = this.children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + view.Reflow(); + } + } + internal string DebugHierarchy(int level) + { + string text = string.Empty; + string text2 = string.Empty; + for (int i = 0; i < level; i++) + { + text += " "; + } + text2 = string.Concat(new object[] + { + text2, + text, + this.ToString(), + " p:", + this.position + }); + if (this.children.Length > 0) + { + text2 += " {\n"; + View[] children = this.children; + for (int j = 0; j < children.Length; j++) + { + View view = children[j]; + text2 += view.DebugHierarchy(level + 2); + } + text2 = text2 + text + " }\n"; + } + else + { + text2 += "\n"; + } + return text2; + } + internal virtual void Initialize(ContainerWindow win) + { + this.SetWindow(win); + View[] children = this.m_Children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + view.m_Parent = this; + view.Initialize(win); + } + } + internal void SetMinMaxSizes(Vector2 min, Vector2 max) + { + if (this.minSize == min && this.maxSize == max) + { + return; + } + this.m_MinSize = min; + this.m_MaxSize = max; + if (this.m_Parent) + { + this.m_Parent.ChildrenMinMaxChanged(); + } + if (this.window && this.window.mainView == this) + { + this.window.SetMinMaxSizes(min, max); + } + } + protected virtual void ChildrenMinMaxChanged() + { + } + protected virtual void SetPosition(Rect newPos) + { + this.m_Position = newPos; + } + internal void SetPositionOnly(Rect newPos) + { + this.m_Position = newPos; + } + public int IndexOfChild(View child) + { + int num = 0; + View[] children = this.m_Children; + for (int i = 0; i < children.Length; i++) + { + View x = children[i]; + if (x == child) + { + return num; + } + num++; + } + return -1; + } + public void OnDestroy() + { + View[] children = this.m_Children; + for (int i = 0; i < children.Length; i++) + { + View obj = children[i]; + UnityEngine.Object.DestroyImmediate(obj, true); + } + } + public void AddChild(View child) + { + this.AddChild(child, this.m_Children.Length); + } + public virtual void AddChild(View child, int idx) + { + Array.Resize(ref this.m_Children, this.m_Children.Length + 1); + if (idx != this.m_Children.Length - 1) + { + Array.Copy(this.m_Children, idx, this.m_Children, idx + 1, this.m_Children.Length - idx - 1); + } + this.m_Children[idx] = child; + if (child.m_Parent) + { + child.m_Parent.RemoveChild(child); + } + child.m_Parent = this; + child.SetWindowRecurse(this.window); + this.ChildrenMinMaxChanged(); + } + public virtual void RemoveChild(View child) + { + int num = Array.IndexOf(this.m_Children, child); + if (num == -1) + { + Debug.LogError("Unable to remove child - it's not IN the view"); + } + else + { + this.RemoveChild(num); + } + } + public virtual void RemoveChild(int idx) + { + View view = this.m_Children[idx]; + view.m_Parent = null; + view.SetWindowRecurse(null); + Array.Copy(this.m_Children, idx + 1, this.m_Children, idx, this.m_Children.Length - idx - 1); + Array.Resize(ref this.m_Children, this.m_Children.Length - 1); + this.ChildrenMinMaxChanged(); + } + protected virtual void SetWindow(ContainerWindow win) + { + this.m_Window = win; + } + internal void SetWindowRecurse(ContainerWindow win) + { + this.SetWindow(win); + View[] children = this.m_Children; + for (int i = 0; i < children.Length; i++) + { + View view = children[i]; + view.SetWindowRecurse(win); + } + } + protected virtual bool OnFocus() + { + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ViewTool.cs b/UnityEditor/UnityEditor/ViewTool.cs new file mode 100644 index 00000000..09dec6d0 --- /dev/null +++ b/UnityEditor/UnityEditor/ViewTool.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + public enum ViewTool + { + None = -1, + Orbit, + Pan, + Zoom, + FPS + } +} diff --git a/UnityEditor/UnityEditor/VisualStudioVersion.cs b/UnityEditor/UnityEditor/VisualStudioVersion.cs new file mode 100644 index 00000000..97d8b8c0 --- /dev/null +++ b/UnityEditor/UnityEditor/VisualStudioVersion.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal enum VisualStudioVersion + { + Invalid, + VisualStudio2008 = 9, + VisualStudio2010, + VisualStudio2012 + } +} diff --git a/UnityEditor/UnityEditor/VisualizationBlendTree.cs b/UnityEditor/UnityEditor/VisualizationBlendTree.cs new file mode 100644 index 00000000..5b6e7cab --- /dev/null +++ b/UnityEditor/UnityEditor/VisualizationBlendTree.cs @@ -0,0 +1,107 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class VisualizationBlendTree + { + private AnimatorController m_Controller; + private StateMachine m_StateMachine; + private State m_State; + private BlendTree m_BlendTree; + private Animator m_Animator; + private bool m_ControllerIsDirty; + public Animator animator + { + get + { + return this.m_Animator; + } + } + public void Init(BlendTree blendTree, Animator animator) + { + this.m_BlendTree = blendTree; + this.m_Animator = animator; + this.m_Animator.logWarnings = false; + this.m_Animator.fireEvents = false; + this.m_Animator.enabled = false; + this.m_Animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; + this.CreateStateMachine(); + } + protected virtual void ControllerDirty() + { + this.m_ControllerIsDirty = true; + } + private void CreateParameters() + { + int parameterCount = this.m_Controller.parameterCount; + for (int i = 0; i < parameterCount; i++) + { + this.m_Controller.RemoveParameter(0); + } + for (int j = 0; j < this.m_BlendTree.recursiveBlendParameterCount; j++) + { + this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(j), AnimatorControllerParameterType.Float); + } + } + private void CreateStateMachine() + { + if (this.m_Controller == null) + { + this.m_Controller = new AnimatorController(); + this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.AddLayer("preview"); + this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + this.CreateParameters(); + this.m_State = this.m_StateMachine.AddState("preview"); + this.m_State.SetMotionInternal(this.m_BlendTree); + this.m_State.iKOnFeet = false; + this.m_State.hideFlags = HideFlags.DontSave; + AnimatorController.SetAnimatorController(this.m_Animator, this.m_Controller); + AnimatorController expr_A7 = this.m_Controller; + expr_A7.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_A7.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + this.m_ControllerIsDirty = false; + } + } + private void ClearStateMachine() + { + if (this.m_Animator != null) + { + AnimatorController.SetAnimatorController(this.m_Animator, null); + } + if (this.m_Controller != null) + { + AnimatorController expr_34 = this.m_Controller; + expr_34.OnAnimatorControllerDirty = (Action)Delegate.Remove(expr_34.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + } + UnityEngine.Object.DestroyImmediate(this.m_Controller); + UnityEngine.Object.DestroyImmediate(this.m_State); + this.m_StateMachine = null; + this.m_Controller = null; + this.m_State = null; + } + public void Reset() + { + this.ClearStateMachine(); + this.CreateStateMachine(); + } + public void Destroy() + { + this.ClearStateMachine(); + } + public void Update() + { + if (this.m_ControllerIsDirty) + { + this.Reset(); + } + for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) + { + string recursiveBlendParameter = this.m_BlendTree.GetRecursiveBlendParameter(i); + float inputBlendValue = this.m_BlendTree.GetInputBlendValue(recursiveBlendParameter); + this.animator.SetFloat(recursiveBlendParameter, inputBlendValue); + } + this.animator.EvaluateSM(); + } + } +} diff --git a/UnityEditor/UnityEditor/WebCamTextureInspector.cs b/UnityEditor/UnityEditor/WebCamTextureInspector.cs new file mode 100644 index 00000000..3c51ec89 --- /dev/null +++ b/UnityEditor/UnityEditor/WebCamTextureInspector.cs @@ -0,0 +1,91 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(WebCamTexture))] + internal class WebCamTextureInspector : Editor + { + private static GUIContent[] s_PlayIcons = new GUIContent[2]; + private Vector2 m_Pos; + public override void OnInspectorGUI() + { + WebCamTexture webCamTexture = this.target as WebCamTexture; + EditorGUILayout.LabelField("Requested FPS", webCamTexture.requestedFPS.ToString(), new GUILayoutOption[0]); + EditorGUILayout.LabelField("Requested Width", webCamTexture.requestedWidth.ToString(), new GUILayoutOption[0]); + EditorGUILayout.LabelField("Requested Height", webCamTexture.requestedHeight.ToString(), new GUILayoutOption[0]); + EditorGUILayout.LabelField("Device Name", webCamTexture.deviceName, new GUILayoutOption[0]); + } + private static void Init() + { + WebCamTextureInspector.s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff"); + WebCamTextureInspector.s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn"); + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override void OnPreviewSettings() + { + WebCamTextureInspector.Init(); + GUI.enabled = !Application.isPlaying; + WebCamTexture webCamTexture = this.target as WebCamTexture; + bool flag = PreviewGUI.CycleButton((!webCamTexture.isPlaying) ? 0 : 1, WebCamTextureInspector.s_PlayIcons) != 0; + if (flag != webCamTexture.isPlaying) + { + if (flag) + { + webCamTexture.Stop(); + webCamTexture.Play(); + } + else + { + webCamTexture.Pause(); + } + } + GUI.enabled = true; + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (Event.current.type == EventType.Repaint) + { + background.Draw(r, false, false, false, false); + } + WebCamTexture webCamTexture = this.target as WebCamTexture; + float num = Mathf.Min(Mathf.Min(r.width / (float)webCamTexture.width, r.height / (float)webCamTexture.height), 1f); + Rect rect = new Rect(r.x, r.y, (float)webCamTexture.width * num, (float)webCamTexture.height * num); + PreviewGUI.BeginScrollView(r, this.m_Pos, rect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); + GUI.DrawTexture(rect, webCamTexture, ScaleMode.StretchToFill, false); + this.m_Pos = PreviewGUI.EndScrollView(); + if (webCamTexture.isPlaying) + { + GUIView.current.Repaint(); + } + if (Application.isPlaying) + { + if (webCamTexture.isPlaying) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10f, r.width, 20f), "Can't pause preview when in play mode"); + } + else + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10f, r.width, 20f), "Can't start preview when in play mode"); + } + } + } + public void OnDisable() + { + WebCamTexture webCamTexture = this.target as WebCamTexture; + if (!Application.isPlaying && webCamTexture != null) + { + webCamTexture.Stop(); + } + } + public override string GetInfoString() + { + Texture texture = this.target as Texture; + string str = texture.width.ToString() + "x" + texture.height.ToString(); + TextureFormat textureFormat = TextureUtil.GetTextureFormat(texture); + return str + " " + TextureUtil.GetTextureFormatString(textureFormat); + } + } +} diff --git a/UnityEditor/UnityEditor/WebScriptObject.cs b/UnityEditor/UnityEditor/WebScriptObject.cs new file mode 100644 index 00000000..a663cb43 --- /dev/null +++ b/UnityEditor/UnityEditor/WebScriptObject.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class WebScriptObject : IDisposable + { + private IntPtr webScriptObjectWrapper; + public void Dispose() + { + this.DestroyScriptObject(); + } + ~WebScriptObject() + { + this.DestroyScriptObject(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void DestroyScriptObject(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern object MonoObjectFromJSON(string json); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern WebScriptObject EvalJavaScript(string script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern WebScriptObject InvokeMethodArray(string method, object[] args); + public WebScriptObject InvokeMethod(string method, params object[] args) + { + return this.InvokeMethodArray(method, args); + } + public WebScriptObject Invoke(params object[] args) + { + object[] array = new object[args.Length + 1]; + args.CopyTo(array, 1); + array[0] = this; + return this.InvokeMethodArray("call", array); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern WebScriptObject Internal_GetKey(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetKey(string key, object value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Remove(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern WebScriptObject Internal_GetIndex(int i); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetIndex(int i, object value); + public WebScriptObject Get(int key) + { + return this.Internal_GetIndex(key); + } + public WebScriptObject Get(string key) + { + WebScriptObject webScriptObject = this; + string[] array = key.Split(new char[] + { + '.' + }); + for (int i = 0; i < array.Length; i++) + { + string key2 = array[i]; + webScriptObject = webScriptObject.Internal_GetKey(key2); + if (webScriptObject == null) + { + break; + } + } + return webScriptObject; + } + public T Get(int key) + { + return this.Internal_GetIndex(key).Convert(); + } + public T Get(string key) + { + return this.Get(key).Convert(); + } + public void Set(int key, T value) + { + this.Internal_SetIndex(key, value); + } + public void Set(string key, T value) + { + this.Internal_SetKey(key, value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern object ConvertToType(Type t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool IsValid(); + public T Convert() + { + return (T)((object)this.ConvertToType(typeof(T))); + } + [ExcludeFromDocs] + public string GetAsJSON(string key) + { + int indent = 0; + return this.GetAsJSON(key, indent); + } + public string GetAsJSON(string key, [DefaultValue("0")] int indent) + { + return this.Internal_GetKey(key).ToJSON(indent); + } + [ExcludeFromDocs] + public string GetAsJSON(int i) + { + int indent = 0; + return this.GetAsJSON(i, indent); + } + public string GetAsJSON(int i, [DefaultValue("0")] int indent) + { + return this.Internal_GetIndex(i).ToJSON(indent); + } + public void SetFromJSON(string key, string value) + { + this.Internal_SetKey(key, this.ParseJSON(value)); + } + public void SetFromJSON(int i, string value) + { + this.Internal_SetIndex(i, this.ParseJSON(value)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string ToJSON([DefaultValue("0")] int indent); + [ExcludeFromDocs] + public string ToJSON() + { + int indent = 0; + return this.ToJSON(indent); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public override extern string ToString(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern WebScriptObject ParseJSON(string json); + public static implicit operator bool(WebScriptObject o) + { + return o != null && o.IsValid() && o.Convert(); + } + public static implicit operator int(WebScriptObject o) + { + return o.Convert(); + } + public static implicit operator float(WebScriptObject o) + { + return o.Convert(); + } + public static implicit operator double(WebScriptObject o) + { + return o.Convert(); + } + public static implicit operator string(WebScriptObject o) + { + if (o == null || !o.IsValid()) + { + return string.Empty; + } + return o.ToString(); + } + } +} diff --git a/UnityEditor/UnityEditor/WebView.cs b/UnityEditor/UnityEditor/WebView.cs new file mode 100644 index 00000000..c0b22118 --- /dev/null +++ b/UnityEditor/UnityEditor/WebView.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class WebView : ScriptableObject + { + [SerializeField] + private MonoReloadableIntPtr webViewWrapper; + internal extern Texture2D texture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern WebScriptObject windowScriptObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool needsRepaint + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public WebView(int width, int height, bool showResizeHandle) + { + this.InitWebView(width, height, showResizeHandle); + } + public WebView(int width, int height, string url) + { + this.InitWebView(width, height, false); + this.LoadURL(url); + } + public void OnDestroy() + { + this.DestroyWebView(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void DestroyWebView(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InitWebView(int width, int height, bool showResizeHandle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void LoadURL(string url); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void LoadFile(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool IntPtrIsNull(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetDelegateObject(ScriptableObject value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetWebkitControlsGlobalLocation(int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Resize(int width, int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InjectMouseDown(int x, int y, int button, int clickCount); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Cut(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Copy(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Paste(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SelectAll(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InjectMouseUp(int x, int y, int button, int clickCount); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InjectMouseMove(int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InjectMouseDrag(int x, int y, int button); + internal void InjectScrollWheel(int x, int y, Vector2 delta) + { + WebView.INTERNAL_CALL_InjectScrollWheel(this, x, y, ref delta); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_InjectScrollWheel(WebView self, int x, int y, ref Vector2 delta); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InjectKeyboardEvent(Event e); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Focus(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UnFocus(); + internal bool InjectEvent(Event e, Rect position) + { + switch (e.type) + { + case EventType.MouseDown: + this.InjectMouseDown((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), (Application.platform != RuntimePlatform.OSXEditor || !e.control || e.button != 0) ? e.button : 1, e.clickCount); + goto IL_1D5; + case EventType.MouseUp: + this.InjectMouseUp((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), (Application.platform != RuntimePlatform.OSXEditor || !e.control || e.button != 0) ? e.button : 1, e.clickCount); + goto IL_1D5; + case EventType.MouseMove: + this.InjectMouseMove((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y)); + goto IL_1D5; + case EventType.MouseDrag: + this.InjectMouseDrag((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), e.button); + goto IL_1D5; + case EventType.KeyDown: + break; + case EventType.KeyUp: + break; + case EventType.ScrollWheel: + this.InjectScrollWheel((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), e.delta); + goto IL_1D5; + default: + return false; + } + this.InjectKeyboardEvent(e); + IL_1D5: + if (Event.current == null) + { + GUIUtility.ExitGUI(); + } + return true; + } + public void DoGUI(Rect position) + { + int controlID = GUIUtility.GetControlID(this.GetHashCode(), FocusType.Native, position); + EventType type = Event.current.type; + switch (type) + { + case EventType.MouseDown: + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); + this.SetWebkitControlsGlobalLocation((int)vector.x, (int)vector.y); + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = controlID; + } + goto IL_251; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + } + goto IL_251; + case EventType.MouseMove: + case EventType.KeyDown: + case EventType.KeyUp: + case EventType.ScrollWheel: + { + IL_43: + string commandName; + if (type == EventType.ValidateCommand) + { + commandName = Event.current.commandName; + if (commandName != null) + { + if (WebView.<>f__switch$map1A == null) + { + WebView.<>f__switch$map1A = new Dictionary(4) + { + + { + "Cut", + 0 + }, + + { + "Copy", + 0 + }, + + { + "Paste", + 0 + }, + + { + "SelectAll", + 0 + } + }; + } + int num; + if (WebView.<>f__switch$map1A.TryGetValue(commandName, out num)) + { + if (num == 0) + { + Event.current.Use(); + } + } + } + return; + } + if (type != EventType.ExecuteCommand) + { + goto IL_251; + } + commandName = Event.current.commandName; + switch (commandName) + { + case "Cut": + this.Cut(); + break; + case "Copy": + this.Copy(); + break; + case "Paste": + this.Paste(); + break; + case "SelectAll": + this.SelectAll(); + break; + } + return; + } + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Event.current.Use(); + } + goto IL_251; + case EventType.Repaint: + GUI.DrawTexture(position, this.texture); + return; + case EventType.Layout: + this.Resize((int)position.width, (int)position.height); + return; + } + goto IL_43; + IL_251: + if (this.InjectEvent(Event.current, position)) + { + Event.current.Use(); + } + else + { + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + } + } + } + public void DoGUILayout(params GUILayoutOption[] options) + { + Rect rect = GUILayoutUtility.GetRect(new GUIContent(), EditorStyles.textField, options); + if (Event.current.type != EventType.Layout && Event.current.type != EventType.MouseUp) + { + this.Resize((int)rect.width, (int)rect.height); + this.DoGUI(rect); + } + } + public void Back() + { + this.windowScriptObject.EvalJavaScript("history.back();"); + } + public void Forward() + { + this.windowScriptObject.EvalJavaScript("history.forward();"); + } + public void Reload() + { + this.windowScriptObject.EvalJavaScript("document.location.reload(true);"); + } + public static implicit operator bool(WebView exists) + { + return exists != null && !exists.IntPtrIsNull(); + } + } +} diff --git a/UnityEditor/UnityEditor/WelcomeScreen.cs b/UnityEditor/UnityEditor/WelcomeScreen.cs new file mode 100644 index 00000000..7a4a294b --- /dev/null +++ b/UnityEditor/UnityEditor/WelcomeScreen.cs @@ -0,0 +1,167 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class WelcomeScreen : EditorWindow + { + private class Styles + { + public GUIContent unityLogo = EditorGUIUtility.IconContent("UnityLogo"); + public GUIContent mainHeader = EditorGUIUtility.IconContent("WelcomeScreen.MainHeader"); + public GUIContent mainText = EditorGUIUtility.TextContent("WelcomeScreen.MainText"); + public GUIContent videoTutLogo = EditorGUIUtility.IconContent("WelcomeScreen.VideoTutLogo"); + public GUIContent videoTutHeader = EditorGUIUtility.TextContent("WelcomeScreen.VideoTutHeader"); + public GUIContent videoTutText = EditorGUIUtility.TextContent("WelcomeScreen.VideoTutText"); + public GUIContent unityBasicsLogo = EditorGUIUtility.IconContent("WelcomeScreen.UnityBasicsLogo"); + public GUIContent unityBasicsHeader = EditorGUIUtility.TextContent("WelcomeScreen.UnityBasicsHeader"); + public GUIContent unityBasicsText = EditorGUIUtility.TextContent("WelcomeScreen.UnityBasicsText"); + public GUIContent unityForumLogo = EditorGUIUtility.IconContent("WelcomeScreen.UnityForumLogo"); + public GUIContent unityForumHeader = EditorGUIUtility.TextContent("WelcomeScreen.UnityForumHeader"); + public GUIContent unityForumText = EditorGUIUtility.TextContent("WelcomeScreen.UnityForumText"); + public GUIContent unityAnswersLogo = EditorGUIUtility.IconContent("WelcomeScreen.UnityAnswersLogo"); + public GUIContent unityAnswersHeader = EditorGUIUtility.TextContent("WelcomeScreen.UnityAnswersHeader"); + public GUIContent unityAnswersText = EditorGUIUtility.TextContent("WelcomeScreen.UnityAnswersText"); + public GUIContent assetStoreLogo = EditorGUIUtility.IconContent("WelcomeScreen.AssetStoreLogo"); + public GUIContent assetStoreHeader = EditorGUIUtility.TextContent("WelcomeScreen.AssetStoreHeader"); + public GUIContent assetStoreText = EditorGUIUtility.TextContent("WelcomeScreen.AssetStoreText"); + public GUIContent showAtStartupText = EditorGUIUtility.TextContent("WelcomeScreen.ShowAtStartup"); + } + private const string kVideoTutURL = "http://unity3d.com/learn/tutorials/modules/"; + private const string kUnityBasicsHelp = "file:///unity/Manual/UnityBasics.html"; + private const string kUnityAnswersURL = "http://answers.unity3d.com/"; + private const string kUnityForumURL = "http://forum.unity3d.com/"; + private const string kAssetStoreURL = "home/?ref=http%3a%2f%2fUnityEditor.unity3d.com%2fWelcomeScreen"; + private const float kItemHeight = 55f; + private static WelcomeScreen.Styles styles; + private static bool s_ShowAtStartup; + private static int s_ShowCount; + private static void DoShowWelcomeScreen(string how) + { + WelcomeScreen.s_ShowCount++; + EditorPrefs.SetInt("WelcomeScreenShowCount", WelcomeScreen.s_ShowCount); + Analytics.Track(string.Format("/WelcomeScreen/Show/{0}/{1}", how, WelcomeScreen.s_ShowCount)); + EditorWindow.GetWindowWithRect(new Rect(0f, 0f, 570f, 440f), true, "Welcome To Unity"); + } + private static void ShowWelcomeScreen() + { + WelcomeScreen.DoShowWelcomeScreen("Manual"); + } + private static void ShowWelcomeScreenAtStartup() + { + WelcomeScreen.LoadLogos(); + if (WelcomeScreen.s_ShowAtStartup) + { + WelcomeScreen.DoShowWelcomeScreen("Startup"); + } + } + private static void LoadLogos() + { + if (WelcomeScreen.styles == null) + { + WelcomeScreen.s_ShowAtStartup = (EditorPrefs.GetInt("ShowWelcomeAtStartup4", 1) != 0); + WelcomeScreen.s_ShowCount = EditorPrefs.GetInt("WelcomeScreenShowCount", 0); + WelcomeScreen.styles = new WelcomeScreen.Styles(); + } + } + public void OnGUI() + { + WelcomeScreen.LoadLogos(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUI.Box(new Rect(13f, 8f, (float)WelcomeScreen.styles.unityLogo.image.width, (float)WelcomeScreen.styles.unityLogo.image.height), WelcomeScreen.styles.unityLogo, GUIStyle.none); + GUILayout.Space(15f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(120f); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(WelcomeScreen.styles.mainHeader, new GUILayoutOption[0]); + GUILayout.Label(WelcomeScreen.styles.mainText, "WordWrappedLabel", new GUILayoutOption[] + { + GUILayout.Width(300f) + }); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.Space(8f); + this.ShowEntry(WelcomeScreen.styles.videoTutLogo, "http://unity3d.com/learn/tutorials/modules/", WelcomeScreen.styles.videoTutHeader, WelcomeScreen.styles.videoTutText, "VideoTutorials"); + this.ShowEntry(WelcomeScreen.styles.unityBasicsLogo, "file:///unity/Manual/UnityBasics.html", WelcomeScreen.styles.unityBasicsHeader, WelcomeScreen.styles.unityBasicsText, "UnityBasics"); + this.ShowEntry(WelcomeScreen.styles.unityAnswersLogo, "http://answers.unity3d.com/", WelcomeScreen.styles.unityAnswersHeader, WelcomeScreen.styles.unityAnswersText, "UnityAnswers"); + this.ShowEntry(WelcomeScreen.styles.unityForumLogo, "http://forum.unity3d.com/", WelcomeScreen.styles.unityForumHeader, WelcomeScreen.styles.unityForumText, "UnityForum"); + this.ShowEntry(WelcomeScreen.styles.assetStoreLogo, "home/?ref=http%3a%2f%2fUnityEditor.unity3d.com%2fWelcomeScreen", WelcomeScreen.styles.assetStoreHeader, WelcomeScreen.styles.assetStoreText, "AssetStore"); + GUILayout.FlexibleSpace(); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Height(20f) + }); + GUILayout.FlexibleSpace(); + GUI.changed = false; + WelcomeScreen.s_ShowAtStartup = GUILayout.Toggle(WelcomeScreen.s_ShowAtStartup, WelcomeScreen.styles.showAtStartupText, new GUILayoutOption[0]); + if (GUI.changed) + { + EditorPrefs.SetInt("ShowWelcomeAtStartup4", (!WelcomeScreen.s_ShowAtStartup) ? 0 : 1); + if (WelcomeScreen.s_ShowAtStartup) + { + Analytics.Track(string.Format("/WelcomeScreen/EnableAtStartup/{0}", WelcomeScreen.s_ShowCount)); + } + else + { + Analytics.Track(string.Format("/WelcomeScreen/DisableAtStartup/{0}", WelcomeScreen.s_ShowCount)); + } + WelcomeScreen.s_ShowCount = 0; + EditorPrefs.SetInt("WelcomeScreenShowCount", 0); + } + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + private void ShowEntry(GUIContent logo, string url, GUIContent header, GUIContent text, string analyticsAction) + { + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Height(55f) + }); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Width(120f) + }); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(logo, GUIStyle.none, new GUILayoutOption[0])) + { + this.ShowHelpPageOrBrowseURL(url, analyticsAction); + } + EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); + GUILayout.Space(10f); + GUILayout.EndHorizontal(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (GUILayout.Button(header, "HeaderLabel", new GUILayoutOption[0])) + { + this.ShowHelpPageOrBrowseURL(url, analyticsAction); + } + EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); + GUILayout.Label(text, "WordWrappedLabel", new GUILayoutOption[] + { + GUILayout.Width(400f) + }); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + private void ShowHelpPageOrBrowseURL(string url, string analyticsAction) + { + Analytics.Track(string.Format("/WelcomeScreen/OpenURL/{0}/{1}", analyticsAction, WelcomeScreen.s_ShowCount)); + if (url.StartsWith("file")) + { + Help.ShowHelpPage(url); + } + else + { + if (url.StartsWith("home/")) + { + AssetStore.Open(url); + GUIUtility.ExitGUI(); + } + else + { + Help.BrowseURL(url); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/WheelColliderEditor.cs b/UnityEditor/UnityEditor/WheelColliderEditor.cs new file mode 100644 index 00000000..3b1fdd23 --- /dev/null +++ b/UnityEditor/UnityEditor/WheelColliderEditor.cs @@ -0,0 +1,40 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(WheelCollider))] + internal class WheelColliderEditor : Collider3DEditorBase + { + private SerializedProperty m_Center; + private SerializedProperty m_Radius; + private SerializedProperty m_SuspensionDistance; + private SerializedProperty m_SuspensionSpring; + private SerializedProperty m_Mass; + private SerializedProperty m_ForwardFriction; + private SerializedProperty m_SidewaysFriction; + public override void OnEnable() + { + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_SuspensionDistance = base.serializedObject.FindProperty("m_SuspensionDistance"); + this.m_SuspensionSpring = base.serializedObject.FindProperty("m_SuspensionSpring"); + this.m_Mass = base.serializedObject.FindProperty("m_Mass"); + this.m_ForwardFriction = base.serializedObject.FindProperty("m_ForwardFriction"); + this.m_SidewaysFriction = base.serializedObject.FindProperty("m_SidewaysFriction"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Mass, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SuspensionDistance, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + EditorGUILayout.Space(); + StructPropertyGUILayout.JointSpring(this.m_SuspensionSpring, new GUILayoutOption[0]); + StructPropertyGUILayout.WheelFrictionCurve(this.m_ForwardFriction, new GUILayoutOption[0]); + StructPropertyGUILayout.WheelFrictionCurve(this.m_SidewaysFriction, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/WheelJoint2DEditor.cs b/UnityEditor/UnityEditor/WheelJoint2DEditor.cs new file mode 100644 index 00000000..a49dbf06 --- /dev/null +++ b/UnityEditor/UnityEditor/WheelJoint2DEditor.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(WheelJoint2D))] + internal class WheelJoint2DEditor : AnchoredJoint2DEditor + { + public new void OnSceneGUI() + { + WheelJoint2D wheelJoint2D = (WheelJoint2D)this.target; + if (!wheelJoint2D.enabled) + { + return; + } + Vector3 vector = Joint2DEditorBase.TransformPoint(wheelJoint2D.transform, wheelJoint2D.anchor); + Vector3 vector2 = vector; + Vector3 vector3 = vector; + Vector3 vector4 = Joint2DEditorBase.RotateVector2(Vector3.right, -wheelJoint2D.suspension.angle - wheelJoint2D.transform.eulerAngles.z); + Handles.color = Color.green; + vector4 *= HandleUtility.GetHandleSize(vector) * 0.3f; + vector2 += vector4; + vector3 -= vector4; + Joint2DEditorBase.DrawAALine(vector2, vector3); + base.OnSceneGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/WindInspector.cs b/UnityEditor/UnityEditor/WindInspector.cs new file mode 100644 index 00000000..eef293d2 --- /dev/null +++ b/UnityEditor/UnityEditor/WindInspector.cs @@ -0,0 +1,29 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(WindZone))] + internal class WindInspector : Editor + { + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + GUI.enabled = true; + WindZone windZone = this.target as WindZone; + if (windZone == null) + { + GUILayout.Label("Error: Not a WindZode", new GUILayoutOption[0]); + return; + } + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_Mode"), new GUILayoutOption[0]); + GUI.enabled = (windZone.mode == WindZoneMode.Spherical); + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_Radius"), new GUILayoutOption[0]); + GUI.enabled = true; + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindMain"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindTurbulence"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindPulseMagnitude"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindPulseFrequency"), new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/WindowFocusState.cs b/UnityEditor/UnityEditor/WindowFocusState.cs new file mode 100644 index 00000000..3f33f601 --- /dev/null +++ b/UnityEditor/UnityEditor/WindowFocusState.cs @@ -0,0 +1,32 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class WindowFocusState : ScriptableObject + { + private static WindowFocusState m_Instance; + internal string m_LastWindowTypeInSameDock = string.Empty; + internal bool m_WasMaximizedBeforePlay; + internal bool m_CurrentlyInPlayMode; + internal static WindowFocusState instance + { + get + { + if (WindowFocusState.m_Instance == null) + { + WindowFocusState.m_Instance = (UnityEngine.Object.FindObjectOfType(typeof(WindowFocusState)) as WindowFocusState); + } + if (WindowFocusState.m_Instance == null) + { + WindowFocusState.m_Instance = ScriptableObject.CreateInstance(); + } + return WindowFocusState.m_Instance; + } + } + private void OnEnable() + { + base.hideFlags = HideFlags.HideAndDontSave; + WindowFocusState.m_Instance = this; + } + } +} diff --git a/UnityEditor/UnityEditor/WindowLayout.cs b/UnityEditor/UnityEditor/WindowLayout.cs new file mode 100644 index 00000000..26a634bd --- /dev/null +++ b/UnityEditor/UnityEditor/WindowLayout.cs @@ -0,0 +1,685 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class WindowLayout + { + private const string kMaximizeRestoreFile = "CurrentMaximizeLayout.dwlt"; + internal static PrefKey s_MaximizeKey = new PrefKey("Window/Maximize View", "# "); + private static bool ms_IsLoadingWindowLayout = false; + internal static string layoutsPreferencesPath + { + get + { + return InternalEditorUtility.unityPreferencesFolder + "/Layouts"; + } + } + internal static string layoutsProjectPath + { + get + { + return Directory.GetCurrentDirectory() + "/Library"; + } + } + public static void WarnBrokenRepaint() + { + if (!WindowLayout.ms_IsLoadingWindowLayout) + { + UnityEngine.Debug.LogError("WindowLayouts are invalid. Please use 'Window -> Layouts -> Revert Factory Settings...' menu to fix it."); + } + } + private static void ShowWindowImmediate(EditorWindow win) + { + win.Show(true); + } + internal static EditorWindow FindEditorWindowOfType(Type type) + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(type); + if (array.Length > 0) + { + return array[0] as EditorWindow; + } + return null; + } + [DebuggerHidden] + private static IEnumerable FindEditorWindowsOfType() where T : class + { + WindowLayout.c__Iterator3 c__Iterator = new WindowLayout.c__Iterator3(); + WindowLayout.c__Iterator3 expr_07 = c__Iterator; + expr_07.$PC = -2; + return expr_07; + } + internal static void CheckWindowConsistency() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(EditorWindow)); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + EditorWindow editorWindow = (EditorWindow)array2[i]; + if (editorWindow.m_Parent == null) + { + UnityEngine.Debug.LogError("Invalid editor window " + editorWindow.GetType()); + } + } + } + internal static EditorWindow TryGetLastFocusedWindowInSameDock() + { + Type type = null; + string lastWindowTypeInSameDock = WindowFocusState.instance.m_LastWindowTypeInSameDock; + if (lastWindowTypeInSameDock != string.Empty) + { + type = Type.GetType(lastWindowTypeInSameDock); + } + GameView gameView = WindowLayout.FindEditorWindowOfType(typeof(GameView)) as GameView; + if (type != null && gameView && gameView.m_Parent != null && gameView.m_Parent is DockArea) + { + object[] array = Resources.FindObjectsOfTypeAll(type); + DockArea y = gameView.m_Parent as DockArea; + for (int i = 0; i < array.Length; i++) + { + EditorWindow editorWindow = array[i] as EditorWindow; + if (editorWindow && editorWindow.m_Parent == y) + { + return editorWindow; + } + } + } + return null; + } + internal static void SaveCurrentFocusedWindowInSameDock(EditorWindow windowToBeFocused) + { + if (windowToBeFocused.m_Parent != null && windowToBeFocused.m_Parent is DockArea) + { + DockArea dockArea = windowToBeFocused.m_Parent as DockArea; + EditorWindow actualView = dockArea.actualView; + if (actualView) + { + WindowFocusState.instance.m_LastWindowTypeInSameDock = actualView.GetType().ToString(); + } + } + } + internal static void FindFirstGameViewAndSetToMaximizeOnPlay() + { + GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); + if (gameView) + { + gameView.maximizeOnPlay = true; + } + } + internal static EditorWindow TryFocusAppropriateWindow(bool enteringPlaymode) + { + if (enteringPlaymode) + { + GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); + if (gameView) + { + WindowLayout.SaveCurrentFocusedWindowInSameDock(gameView); + gameView.Focus(); + } + return gameView; + } + EditorWindow editorWindow = WindowLayout.TryGetLastFocusedWindowInSameDock(); + if (editorWindow) + { + editorWindow.ShowTab(); + } + return editorWindow; + } + internal static EditorWindow GetMaximizedWindow() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(MaximizedHostView)); + if (array.Length != 0) + { + MaximizedHostView maximizedHostView = array[0] as MaximizedHostView; + if (maximizedHostView.actualView) + { + return maximizedHostView.actualView; + } + } + return null; + } + internal static EditorWindow ShowAppropriateViewOnEnterExitPlaymode(bool entering) + { + if (WindowFocusState.instance.m_CurrentlyInPlayMode == entering) + { + return null; + } + WindowFocusState.instance.m_CurrentlyInPlayMode = entering; + EditorWindow maximizedWindow = WindowLayout.GetMaximizedWindow(); + if (entering) + { + WindowFocusState.instance.m_WasMaximizedBeforePlay = (maximizedWindow != null); + if (maximizedWindow != null) + { + return maximizedWindow; + } + } + else + { + if (WindowFocusState.instance.m_WasMaximizedBeforePlay) + { + return maximizedWindow; + } + } + if (maximizedWindow) + { + WindowLayout.Unmaximize(maximizedWindow); + } + EditorWindow editorWindow = WindowLayout.TryFocusAppropriateWindow(entering); + if (editorWindow) + { + return editorWindow; + } + if (entering) + { + EditorWindow editorWindow2 = WindowLayout.FindEditorWindowOfType(typeof(SceneView)); + GameView gameView; + if (editorWindow2 && editorWindow2.m_Parent is DockArea) + { + DockArea dockArea = editorWindow2.m_Parent as DockArea; + if (dockArea) + { + WindowFocusState.instance.m_LastWindowTypeInSameDock = editorWindow2.GetType().ToString(); + gameView = ScriptableObject.CreateInstance(); + dockArea.AddTab(gameView); + return gameView; + } + } + gameView = ScriptableObject.CreateInstance(); + gameView.Show(true); + gameView.Focus(); + return gameView; + } + return editorWindow; + } + internal static bool IsMaximized(EditorWindow window) + { + return window.m_Parent is MaximizedHostView; + } + internal static void MaximizeKeyHandler() + { + if ((WindowLayout.s_MaximizeKey.activated || Event.current.type == EditorGUIUtility.magnifyGestureEventType) && GUIUtility.hotControl == 0) + { + EventType type = Event.current.type; + Event.current.Use(); + EditorWindow mouseOverWindow = EditorWindow.mouseOverWindow; + if (mouseOverWindow && !(mouseOverWindow is PreviewWindow)) + { + if (type == EditorGUIUtility.magnifyGestureEventType) + { + if ((double)Event.current.delta.x < -0.05) + { + if (WindowLayout.IsMaximized(mouseOverWindow)) + { + WindowLayout.Unmaximize(mouseOverWindow); + } + } + else + { + if ((double)Event.current.delta.x > 0.05 && !WindowLayout.IsMaximized(mouseOverWindow)) + { + WindowLayout.Maximize(mouseOverWindow); + } + } + } + else + { + if (WindowLayout.IsMaximized(mouseOverWindow)) + { + WindowLayout.Unmaximize(mouseOverWindow); + } + else + { + WindowLayout.Maximize(mouseOverWindow); + } + } + } + } + } + public static void Unmaximize(EditorWindow win) + { + HostView parent = win.m_Parent; + if (parent == null) + { + UnityEngine.Debug.LogError("Host view was not found"); + WindowLayout.RevertFactorySettings(); + return; + } + WindowLayout.ms_IsLoadingWindowLayout = true; + UnityEngine.Object[] array = InternalEditorUtility.LoadSerializedFileAndForget(Path.Combine(WindowLayout.layoutsProjectPath, "CurrentMaximizeLayout.dwlt")); + WindowLayout.ms_IsLoadingWindowLayout = false; + if (array.Length < 2) + { + UnityEngine.Debug.Log("Maximized serialized file backup not found"); + WindowLayout.RevertFactorySettings(); + return; + } + SplitView splitView = array[0] as SplitView; + EditorWindow editorWindow = array[1] as EditorWindow; + if (splitView == null) + { + UnityEngine.Debug.Log("Maximization failed because the root split view was not found"); + WindowLayout.RevertFactorySettings(); + return; + } + ContainerWindow window = win.m_Parent.window; + if (window == null) + { + UnityEngine.Debug.Log("Maximization failed because the root split view has no container window"); + WindowLayout.RevertFactorySettings(); + return; + } + try + { + ContainerWindow.SetFreezeDisplay(true); + if (!parent.parent) + { + throw new Exception(); + } + int idx = parent.parent.IndexOfChild(parent); + Rect position = parent.position; + View parent2 = parent.parent; + parent2.RemoveChild(idx); + parent2.AddChild(splitView, idx); + splitView.position = position; + DockArea dockArea = editorWindow.m_Parent as DockArea; + int idx2 = dockArea.m_Panes.IndexOf(editorWindow); + parent.actualView = null; + win.m_Parent = null; + dockArea.AddTab(idx2, win); + dockArea.RemoveTab(editorWindow); + UnityEngine.Object.DestroyImmediate(editorWindow); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + UnityEngine.Object @object = array2[i]; + EditorWindow editorWindow2 = @object as EditorWindow; + if (editorWindow2 != null) + { + editorWindow2.MakeParentsSettingsMatchMe(); + } + } + parent2.Initialize(parent2.window); + parent2.position = parent2.position; + splitView.Reflow(); + UnityEngine.Object.DestroyImmediate(parent); + win.Focus(); + window.DisplayAllViews(); + win.m_Parent.MakeVistaDWMHappyDance(); + } + catch (Exception arg) + { + UnityEngine.Debug.Log("Maximization failed: " + arg); + WindowLayout.RevertFactorySettings(); + } + try + { + if (Application.platform == RuntimePlatform.OSXEditor && SystemInfo.operatingSystem.Contains("10.7") && SystemInfo.graphicsDeviceVendor.Contains("ATI")) + { + UnityEngine.Object[] array3 = Resources.FindObjectsOfTypeAll(typeof(GUIView)); + for (int j = 0; j < array3.Length; j++) + { + GUIView gUIView = (GUIView)array3[j]; + gUIView.Repaint(); + } + } + } + finally + { + ContainerWindow.SetFreezeDisplay(false); + } + } + public static void AddSplitViewAndChildrenRecurse(View splitview, ArrayList list) + { + list.Add(splitview); + DockArea dockArea = splitview as DockArea; + if (dockArea != null) + { + list.AddRange(dockArea.m_Panes); + } + HostView x = splitview as DockArea; + if (x != null) + { + list.Add(dockArea.actualView); + } + View[] children = splitview.children; + for (int i = 0; i < children.Length; i++) + { + View splitview2 = children[i]; + WindowLayout.AddSplitViewAndChildrenRecurse(splitview2, list); + } + } + public static void SaveSplitViewAndChildren(View splitview, EditorWindow win, string path) + { + ArrayList arrayList = new ArrayList(); + WindowLayout.AddSplitViewAndChildrenRecurse(splitview, arrayList); + arrayList.Remove(splitview); + arrayList.Remove(win); + arrayList.Insert(0, splitview); + arrayList.Insert(1, win); + InternalEditorUtility.SaveToSerializedFileAndForget(arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[], path, false); + } + public static void Maximize(EditorWindow win) + { + View view = WindowLayout.MaximizePrepare(win); + if (view) + { + WindowLayout.MaximizePresent(win, view); + } + } + public static View MaximizePrepare(EditorWindow win) + { + View parent = win.m_Parent.parent; + View view = parent; + while (parent != null && parent is SplitView) + { + view = parent; + parent = parent.parent; + } + DockArea dockArea = win.m_Parent as DockArea; + if (dockArea == null) + { + return null; + } + if (parent == null) + { + return null; + } + MainWindow x = view.parent as MainWindow; + if (x == null) + { + return null; + } + ContainerWindow window = win.m_Parent.window; + if (window == null) + { + return null; + } + int num = dockArea.m_Panes.IndexOf(win); + if (num == -1) + { + return null; + } + dockArea.selected = num; + WindowLayout.SaveSplitViewAndChildren(view, win, Path.Combine(WindowLayout.layoutsProjectPath, "CurrentMaximizeLayout.dwlt")); + dockArea.m_Panes[num] = null; + MaximizedHostView maximizedHostView = ScriptableObject.CreateInstance(); + int idx = parent.IndexOfChild(view); + Rect position = view.position; + parent.RemoveChild(view); + parent.AddChild(maximizedHostView, idx); + maximizedHostView.position = position; + maximizedHostView.actualView = win; + return view; + } + public static void MaximizePresent(EditorWindow win, View rootSplit) + { + ContainerWindow.SetFreezeDisplay(true); + UnityEngine.Object.DestroyImmediate(rootSplit, true); + win.Focus(); + WindowLayout.CheckWindowConsistency(); + ContainerWindow window = win.m_Parent.window; + window.DisplayAllViews(); + win.m_Parent.MakeVistaDWMHappyDance(); + ContainerWindow.SetFreezeDisplay(false); + } + public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated) + { + Rect position = default(Rect); + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow)); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + ContainerWindow containerWindow = (ContainerWindow)array2[i]; + if (containerWindow.showMode == ShowMode.MainWindow) + { + position = containerWindow.position; + } + } + try + { + ContainerWindow.SetFreezeDisplay(true); + WindowLayout.CloseWindows(); + WindowLayout.ms_IsLoadingWindowLayout = true; + UnityEngine.Object[] array3 = InternalEditorUtility.LoadSerializedFileAndForget(path); + WindowLayout.ms_IsLoadingWindowLayout = false; + ContainerWindow containerWindow2 = null; + ContainerWindow containerWindow3 = null; + UnityEngine.Object[] array4 = array3; + for (int j = 0; j < array4.Length; j++) + { + UnityEngine.Object @object = array4[j]; + ContainerWindow containerWindow4 = @object as ContainerWindow; + if (containerWindow4 != null && containerWindow4.showMode == ShowMode.MainWindow) + { + containerWindow3 = containerWindow4; + if ((double)position.width != 0.0) + { + containerWindow2 = containerWindow4; + containerWindow2.position = position; + } + } + } + int num = 0; + UnityEngine.Object[] array5 = array3; + for (int k = 0; k < array5.Length; k++) + { + UnityEngine.Object object2 = array5[k]; + if (object2 == null) + { + UnityEngine.Debug.LogError("Error while reading window layout: window #" + num + " is null"); + throw new Exception(); + } + if (object2.GetType() == null) + { + UnityEngine.Debug.LogError(string.Concat(new object[] + { + "Error while reading window layout: window #", + num, + " type is null, instanceID=", + object2.GetInstanceID() + })); + throw new Exception(); + } + if (newProjectLayoutWasCreated) + { + MethodInfo method = object2.GetType().GetMethod("OnNewProjectLayoutWasCreated", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + if (method != null) + { + method.Invoke(object2, null); + } + } + num++; + } + if (containerWindow2) + { + containerWindow2.position = position; + containerWindow2.OnResize(); + } + if (containerWindow3 == null) + { + UnityEngine.Debug.LogError("Error while reading window layout: no main window found"); + throw new Exception(); + } + containerWindow3.Show(containerWindow3.showMode, true, true); + UnityEngine.Object[] array6 = array3; + for (int l = 0; l < array6.Length; l++) + { + UnityEngine.Object object3 = array6[l]; + EditorWindow editorWindow = object3 as EditorWindow; + if (editorWindow) + { + editorWindow.minSize = editorWindow.minSize; + } + ContainerWindow containerWindow5 = object3 as ContainerWindow; + if (containerWindow5 && containerWindow5 != containerWindow3) + { + containerWindow5.Show(containerWindow5.showMode, true, true); + } + } + } + catch (Exception arg) + { + UnityEngine.Debug.LogError("Failed to load window layout: " + arg); + switch (EditorUtility.DisplayDialogComplex("Failed to load window layout.", "This can happen if layout contains custom windows and there are compile errors in the project.", "Load Default Layout", "Quit", "Revert Factory Settings")) + { + case 0: + WindowLayout.LoadDefaultLayout(); + break; + case 1: + EditorApplication.Exit(0); + break; + case 2: + WindowLayout.RevertFactorySettings(); + break; + } + return false; + } + finally + { + WindowLayout.ms_IsLoadingWindowLayout = false; + ContainerWindow.SetFreezeDisplay(false); + if (Path.GetExtension(path) == ".wlt") + { + Toolbar.lastLoadedLayoutName = Path.GetFileNameWithoutExtension(path); + } + else + { + Toolbar.lastLoadedLayoutName = null; + } + } + return true; + } + private static void LoadDefaultLayout() + { + InternalEditorUtility.LoadDefaultLayout(); + } + public static void CloseWindows() + { + try + { + TooltipView.Close(); + } + catch (Exception) + { + } + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow)); + UnityEngine.Object[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + ContainerWindow containerWindow = (ContainerWindow)array2[i]; + try + { + containerWindow.Close(); + } + catch (Exception) + { + } + } + UnityEngine.Object[] array3 = Resources.FindObjectsOfTypeAll(typeof(EditorWindow)); + if (array3.Length != 0) + { + string text = string.Empty; + UnityEngine.Object[] array4 = array3; + for (int j = 0; j < array4.Length; j++) + { + EditorWindow editorWindow = (EditorWindow)array4[j]; + text = text + "\n" + editorWindow.GetType().Name; + UnityEngine.Object.DestroyImmediate(editorWindow, true); + } + UnityEngine.Debug.LogError("Failed to destroy editor windows: #" + array3.Length + text); + } + UnityEngine.Object[] array5 = Resources.FindObjectsOfTypeAll(typeof(View)); + if (array5.Length != 0) + { + string text2 = string.Empty; + UnityEngine.Object[] array6 = array5; + for (int k = 0; k < array6.Length; k++) + { + View view = (View)array6[k]; + text2 = text2 + "\n" + view.GetType().Name; + UnityEngine.Object.DestroyImmediate(view, true); + } + UnityEngine.Debug.LogError("Failed to destroy views: #" + array5.Length + text2); + } + } + public static void SaveWindowLayout(string path) + { + TooltipView.Close(); + ArrayList arrayList = new ArrayList(); + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(EditorWindow)); + UnityEngine.Object[] array2 = Resources.FindObjectsOfTypeAll(typeof(ContainerWindow)); + UnityEngine.Object[] array3 = Resources.FindObjectsOfTypeAll(typeof(View)); + UnityEngine.Object[] array4 = array2; + for (int i = 0; i < array4.Length; i++) + { + ContainerWindow containerWindow = (ContainerWindow)array4[i]; + if (!containerWindow.m_DontSaveToLayout) + { + arrayList.Add(containerWindow); + } + } + UnityEngine.Object[] array5 = array3; + for (int j = 0; j < array5.Length; j++) + { + View view = (View)array5[j]; + if (!(view.window != null) || !view.window.m_DontSaveToLayout) + { + arrayList.Add(view); + } + } + UnityEngine.Object[] array6 = array; + for (int k = 0; k < array6.Length; k++) + { + EditorWindow editorWindow = (EditorWindow)array6[k]; + if (!(editorWindow.m_Parent != null) || !(editorWindow.m_Parent.window != null) || !editorWindow.m_Parent.window.m_DontSaveToLayout) + { + arrayList.Add(editorWindow); + } + } + InternalEditorUtility.SaveToSerializedFileAndForget(arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[], path, false); + } + public static void EnsureMainWindowHasBeenLoaded() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(MainWindow)); + if (array.Length == 0) + { + MainWindow.MakeMain(); + } + } + internal static MainWindow FindMainWindow() + { + UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(MainWindow)); + if (array.Length == 0) + { + UnityEngine.Debug.LogError("No Main Window found!"); + return null; + } + return array[0] as MainWindow; + } + public static void SaveGUI() + { + View view = WindowLayout.FindMainWindow(); + Rect screenPosition = view.screenPosition; + SaveWindowLayout windowWithRect = EditorWindow.GetWindowWithRect(new Rect(screenPosition.xMax - 180f, screenPosition.y + 20f, 200f, 48f), true, "Save Window Layout"); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + } + private static void RevertFactorySettings() + { + InternalEditorUtility.RevertFactoryLayoutSettings(true); + } + public static void DeleteGUI() + { + View view = WindowLayout.FindMainWindow(); + Rect screenPosition = view.screenPosition; + DeleteWindowLayout windowWithRect = EditorWindow.GetWindowWithRect(new Rect(screenPosition.xMax - 180f, screenPosition.y + 20f, 200f, 150f), true, "Delete Window Layout"); + windowWithRect.m_Parent.window.m_DontSaveToLayout = true; + } + } +} diff --git a/UnityEditor/UnityEditor/WrapModeFixed.cs b/UnityEditor/UnityEditor/WrapModeFixed.cs new file mode 100644 index 00000000..a8d6cdf5 --- /dev/null +++ b/UnityEditor/UnityEditor/WrapModeFixed.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + internal enum WrapModeFixed + { + Default, + Once, + Loop, + ClampForever = 8, + PingPong = 4 + } +} diff --git a/UnityEditor/UnityEditor/WrapModeFixedCurve.cs b/UnityEditor/UnityEditor/WrapModeFixedCurve.cs new file mode 100644 index 00000000..5ca2f72a --- /dev/null +++ b/UnityEditor/UnityEditor/WrapModeFixedCurve.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + internal enum WrapModeFixedCurve + { + Clamp = 8, + Loop = 2, + PingPong = 4 + } +} diff --git a/UnityEditor/UnityEditor/XboxBuildSubtarget.cs b/UnityEditor/UnityEditor/XboxBuildSubtarget.cs new file mode 100644 index 00000000..03d98964 --- /dev/null +++ b/UnityEditor/UnityEditor/XboxBuildSubtarget.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum XboxBuildSubtarget + { + Development, + Master, + Debug + } +} diff --git a/UnityEditor/UnityEditor/XboxOneRunMethod.cs b/UnityEditor/UnityEditor/XboxOneRunMethod.cs new file mode 100644 index 00000000..8c2a2837 --- /dev/null +++ b/UnityEditor/UnityEditor/XboxOneRunMethod.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum XboxOneRunMethod + { + Push, + Pull + } +} diff --git a/UnityEditor/UnityEditor/XboxRunMethod.cs b/UnityEditor/UnityEditor/XboxRunMethod.cs new file mode 100644 index 00000000..68642bdb --- /dev/null +++ b/UnityEditor/UnityEditor/XboxRunMethod.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum XboxRunMethod + { + HDD, + DiscEmuFast, + DiscEmuAccurate + } +} diff --git a/UnityEditor/UnityEditor/ZoomableArea.cs b/UnityEditor/UnityEditor/ZoomableArea.cs new file mode 100644 index 00000000..deb23fd8 --- /dev/null +++ b/UnityEditor/UnityEditor/ZoomableArea.cs @@ -0,0 +1,689 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [Serializable] + internal class ZoomableArea + { + [Serializable] + public class Styles + { + public GUIStyle horizontalScrollbar; + public GUIStyle horizontalMinMaxScrollbarThumb; + public GUIStyle horizontalScrollbarLeftButton; + public GUIStyle horizontalScrollbarRightButton; + public GUIStyle verticalScrollbar; + public GUIStyle verticalMinMaxScrollbarThumb; + public GUIStyle verticalScrollbarUpButton; + public GUIStyle verticalScrollbarDownButton; + public float sliderWidth; + public float visualSliderWidth; + public Styles(bool minimalGUI) + { + if (minimalGUI) + { + this.visualSliderWidth = 0f; + this.sliderWidth = 15f; + } + else + { + this.visualSliderWidth = 15f; + this.sliderWidth = 15f; + } + } + public void InitGUIStyles(bool minimalGUI) + { + if (minimalGUI) + { + this.horizontalMinMaxScrollbarThumb = "MiniMinMaxSliderHorizontal"; + this.horizontalScrollbarLeftButton = GUIStyle.none; + this.horizontalScrollbarRightButton = GUIStyle.none; + this.horizontalScrollbar = GUIStyle.none; + this.verticalMinMaxScrollbarThumb = "MiniMinMaxSlidervertical"; + this.verticalScrollbarUpButton = GUIStyle.none; + this.verticalScrollbarDownButton = GUIStyle.none; + this.verticalScrollbar = GUIStyle.none; + } + else + { + this.horizontalMinMaxScrollbarThumb = "horizontalMinMaxScrollbarThumb"; + this.horizontalScrollbarLeftButton = "horizontalScrollbarLeftbutton"; + this.horizontalScrollbarRightButton = "horizontalScrollbarRightbutton"; + this.horizontalScrollbar = GUI.skin.horizontalScrollbar; + this.verticalMinMaxScrollbarThumb = "verticalMinMaxScrollbarThumb"; + this.verticalScrollbarUpButton = "verticalScrollbarUpbutton"; + this.verticalScrollbarDownButton = "verticalScrollbarDownbutton"; + this.verticalScrollbar = GUI.skin.verticalScrollbar; + } + } + } + private static Vector2 m_MouseDownPosition = new Vector2(-1000000f, -1000000f); + private static int zoomableAreaHash = "ZoomableArea".GetHashCode(); + private bool m_HRangeLocked; + private bool m_VRangeLocked; + private float m_HRangeMin = float.NegativeInfinity; + private float m_HRangeMax = float.PositiveInfinity; + private float m_VRangeMin = float.NegativeInfinity; + private float m_VRangeMax = float.PositiveInfinity; + private float m_HScaleMin = 0.001f; + private float m_HScaleMax = 100000f; + private float m_VScaleMin = 0.001f; + private float m_VScaleMax = 100000f; + private bool m_ScaleWithWindow; + private bool m_HSlider = true; + private bool m_VSlider = true; + private bool m_IgnoreScrollWheelUntilClicked; + private Rect m_DrawArea = new Rect(0f, 0f, 100f, 100f); + internal Vector2 m_Scale = new Vector2(1f, -1f); + internal Vector2 m_Translation = new Vector2(0f, 0f); + private float m_MarginLeft; + private float m_MarginRight; + private float m_MarginTop; + private float m_MarginBottom; + private Rect m_LastShownAreaInsideMargins = new Rect(0f, 0f, 100f, 100f); + private int verticalScrollbarID; + private int horizontalScrollbarID; + private bool m_MinimalGUI; + private ZoomableArea.Styles styles; + public bool hRangeLocked + { + get + { + return this.m_HRangeLocked; + } + set + { + this.m_HRangeLocked = value; + } + } + public bool vRangeLocked + { + get + { + return this.m_VRangeLocked; + } + set + { + this.m_VRangeLocked = value; + } + } + public float hRangeMin + { + get + { + return this.m_HRangeMin; + } + set + { + this.m_HRangeMin = value; + } + } + public float hRangeMax + { + get + { + return this.m_HRangeMax; + } + set + { + this.m_HRangeMax = value; + } + } + public float vRangeMin + { + get + { + return this.m_VRangeMin; + } + set + { + this.m_VRangeMin = value; + } + } + public float vRangeMax + { + get + { + return this.m_VRangeMax; + } + set + { + this.m_VRangeMax = value; + } + } + public bool scaleWithWindow + { + get + { + return this.m_ScaleWithWindow; + } + set + { + this.m_ScaleWithWindow = value; + } + } + public bool hSlider + { + get + { + return this.m_HSlider; + } + set + { + Rect rect = this.rect; + this.m_HSlider = value; + this.rect = rect; + } + } + public bool vSlider + { + get + { + return this.m_VSlider; + } + set + { + Rect rect = this.rect; + this.m_VSlider = value; + this.rect = rect; + } + } + public bool ignoreScrollWheelUntilClicked + { + get + { + return this.m_IgnoreScrollWheelUntilClicked; + } + set + { + this.m_IgnoreScrollWheelUntilClicked = value; + } + } + public Vector2 scale + { + get + { + return this.m_Scale; + } + } + public float margin + { + set + { + this.m_MarginBottom = value; + this.m_MarginTop = value; + this.m_MarginRight = value; + this.m_MarginLeft = value; + } + } + public float leftmargin + { + get + { + return this.m_MarginLeft; + } + set + { + this.m_MarginLeft = value; + } + } + public float rightmargin + { + get + { + return this.m_MarginRight; + } + set + { + this.m_MarginRight = value; + } + } + public float topmargin + { + get + { + return this.m_MarginTop; + } + set + { + this.m_MarginTop = value; + } + } + public float bottommargin + { + get + { + return this.m_MarginBottom; + } + set + { + this.m_MarginBottom = value; + } + } + public Rect rect + { + get + { + return new Rect(this.drawRect.x, this.drawRect.y, this.drawRect.width + ((!this.m_VSlider) ? 0f : this.styles.visualSliderWidth), this.drawRect.height + ((!this.m_HSlider) ? 0f : this.styles.visualSliderWidth)); + } + set + { + Rect rect = new Rect(value.x, value.y, value.width - ((!this.m_VSlider) ? 0f : this.styles.visualSliderWidth), value.height - ((!this.m_HSlider) ? 0f : this.styles.visualSliderWidth)); + if (rect != this.m_DrawArea) + { + if (this.m_ScaleWithWindow) + { + this.m_DrawArea = rect; + this.shownAreaInsideMargins = this.m_LastShownAreaInsideMargins; + } + else + { + this.m_Translation += new Vector2((rect.width - this.m_DrawArea.width) / 2f, (rect.height - this.m_DrawArea.height) / 2f); + this.m_DrawArea = rect; + } + } + this.EnforceScaleAndRange(); + } + } + public Rect drawRect + { + get + { + return this.m_DrawArea; + } + } + public Rect shownArea + { + get + { + return new Rect(-this.m_Translation.x / this.m_Scale.x, -(this.m_Translation.y - this.drawRect.height) / this.m_Scale.y, this.drawRect.width / this.m_Scale.x, this.drawRect.height / -this.m_Scale.y); + } + set + { + this.m_Scale.x = this.drawRect.width / value.width; + this.m_Scale.y = -this.drawRect.height / value.height; + this.m_Translation.x = -value.x * this.m_Scale.x; + this.m_Translation.y = this.drawRect.height - value.y * this.m_Scale.y; + this.EnforceScaleAndRange(); + } + } + public Rect shownAreaInsideMargins + { + get + { + return this.shownAreaInsideMarginsInternal; + } + set + { + this.shownAreaInsideMarginsInternal = value; + this.EnforceScaleAndRange(); + } + } + private Rect shownAreaInsideMarginsInternal + { + get + { + float num = this.leftmargin / this.m_Scale.x; + float num2 = this.rightmargin / this.m_Scale.x; + float num3 = this.topmargin / this.m_Scale.y; + float num4 = this.bottommargin / this.m_Scale.y; + Rect shownArea = this.shownArea; + shownArea.x += num; + shownArea.y -= num3; + shownArea.width -= num + num2; + shownArea.height += num3 + num4; + return shownArea; + } + set + { + this.m_Scale.x = (this.drawRect.width - this.leftmargin - this.rightmargin) / value.width; + this.m_Scale.y = -(this.drawRect.height - this.topmargin - this.bottommargin) / value.height; + this.m_Translation.x = -value.x * this.m_Scale.x + this.leftmargin; + this.m_Translation.y = this.drawRect.height - value.y * this.m_Scale.y - this.topmargin; + } + } + public virtual Bounds drawingBounds + { + get + { + bool flag = this.hRangeMin > float.NegativeInfinity && this.hRangeMax < float.PositiveInfinity; + bool flag2 = this.vRangeMin > float.NegativeInfinity && this.vRangeMax < float.PositiveInfinity; + return new Bounds(new Vector3((!flag) ? 0f : ((this.hRangeMin + this.hRangeMax) * 0.5f), (!flag2) ? 0f : ((this.vRangeMin + this.hRangeMax) * 0.5f), 0f), new Vector3((!flag) ? 2f : (this.hRangeMax - this.hRangeMin), (!flag2) ? 2f : (this.vRangeMax - this.vRangeMin), 1f)); + } + } + public Matrix4x4 drawingToViewMatrix + { + get + { + return Matrix4x4.TRS(this.m_Translation, Quaternion.identity, new Vector3(this.m_Scale.x, this.m_Scale.y, 1f)); + } + } + public Vector2 mousePositionInDrawing + { + get + { + return this.ViewToDrawingTransformPoint(Event.current.mousePosition); + } + } + public ZoomableArea() + { + this.m_MinimalGUI = false; + this.styles = new ZoomableArea.Styles(false); + } + public ZoomableArea(bool minimalGUI) + { + this.m_MinimalGUI = minimalGUI; + this.styles = new ZoomableArea.Styles(minimalGUI); + } + internal void SetDrawRectHack(Rect r, bool scrollbars) + { + this.m_DrawArea = r; + this.m_VSlider = scrollbars; + this.m_HSlider = scrollbars; + } + public void OnEnable() + { + this.styles = new ZoomableArea.Styles(this.m_MinimalGUI); + } + public void SetShownHRangeInsideMargins(float min, float max) + { + this.m_Scale.x = (this.drawRect.width - this.leftmargin - this.rightmargin) / (max - min); + this.m_Translation.x = -min * this.m_Scale.x + this.leftmargin; + this.EnforceScaleAndRange(); + } + public void SetShownHRange(float min, float max) + { + this.m_Scale.x = this.drawRect.width / (max - min); + this.m_Translation.x = -min * this.m_Scale.x; + this.EnforceScaleAndRange(); + } + public void SetShownVRangeInsideMargins(float min, float max) + { + this.m_Scale.y = -(this.drawRect.height - this.topmargin - this.bottommargin) / (max - min); + this.m_Translation.y = this.drawRect.height - min * this.m_Scale.y - this.topmargin; + this.EnforceScaleAndRange(); + } + public void SetShownVRange(float min, float max) + { + this.m_Scale.y = -this.drawRect.height / (max - min); + this.m_Translation.y = this.drawRect.height - min * this.m_Scale.y; + this.EnforceScaleAndRange(); + } + public Vector2 DrawingToViewTransformPoint(Vector2 lhs) + { + return new Vector2(lhs.x * this.m_Scale.x + this.m_Translation.x, lhs.y * this.m_Scale.y + this.m_Translation.y); + } + public Vector3 DrawingToViewTransformPoint(Vector3 lhs) + { + return new Vector3(lhs.x * this.m_Scale.x + this.m_Translation.x, lhs.y * this.m_Scale.y + this.m_Translation.y, 0f); + } + public Vector2 ViewToDrawingTransformPoint(Vector2 lhs) + { + return new Vector2((lhs.x - this.m_Translation.x) / this.m_Scale.x, (lhs.y - this.m_Translation.y) / this.m_Scale.y); + } + public Vector3 ViewToDrawingTransformPoint(Vector3 lhs) + { + return new Vector3((lhs.x - this.m_Translation.x) / this.m_Scale.x, (lhs.y - this.m_Translation.y) / this.m_Scale.y, 0f); + } + public Vector2 DrawingToViewTransformVector(Vector2 lhs) + { + return new Vector2(lhs.x * this.m_Scale.x, lhs.y * this.m_Scale.y); + } + public Vector3 DrawingToViewTransformVector(Vector3 lhs) + { + return new Vector3(lhs.x * this.m_Scale.x, lhs.y * this.m_Scale.y, 0f); + } + public Vector2 ViewToDrawingTransformVector(Vector2 lhs) + { + return new Vector2(lhs.x / this.m_Scale.x, lhs.y / this.m_Scale.y); + } + public Vector3 ViewToDrawingTransformVector(Vector3 lhs) + { + return new Vector3(lhs.x / this.m_Scale.x, lhs.y / this.m_Scale.y, 0f); + } + public Vector2 NormalizeInViewSpace(Vector2 vec) + { + vec = Vector2.Scale(vec, this.m_Scale); + vec /= vec.magnitude; + return Vector2.Scale(vec, new Vector2(1f / this.m_Scale.x, 1f / this.m_Scale.y)); + } + private bool IsZoomEvent() + { + return Event.current.button == 1 && Event.current.alt; + } + private bool IsPanEvent() + { + return (Event.current.button == 0 && Event.current.alt) || (Event.current.button == 2 && !Event.current.command); + } + public void BeginViewGUI() + { + if (this.styles.horizontalScrollbar == null) + { + this.styles.InitGUIStyles(this.m_MinimalGUI); + } + this.HandleZoomAndPanEvents(this.m_DrawArea); + this.horizontalScrollbarID = GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive); + this.verticalScrollbarID = GUIUtility.GetControlID(EditorGUIExt.s_MinMaxSliderHash, FocusType.Passive); + if (!this.m_MinimalGUI || Event.current.type != EventType.Repaint) + { + this.SliderGUI(); + } + } + public void HandleZoomAndPanEvents(Rect area) + { + GUILayout.BeginArea(area); + area.x = 0f; + area.y = 0f; + int controlID = GUIUtility.GetControlID(ZoomableArea.zoomableAreaHash, FocusType.Native, area); + switch (Event.current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (area.Contains(Event.current.mousePosition)) + { + GUIUtility.keyboardControl = controlID; + if (this.IsZoomEvent() || this.IsPanEvent()) + { + GUIUtility.hotControl = controlID; + ZoomableArea.m_MouseDownPosition = this.mousePositionInDrawing; + Event.current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + ZoomableArea.m_MouseDownPosition = new Vector2(-1000000f, -1000000f); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + if (this.IsZoomEvent()) + { + this.Zoom(ZoomableArea.m_MouseDownPosition, false); + Event.current.Use(); + } + else + { + if (this.IsPanEvent()) + { + this.Pan(); + Event.current.Use(); + } + } + } + break; + case EventType.ScrollWheel: + if (area.Contains(Event.current.mousePosition)) + { + if (!this.m_IgnoreScrollWheelUntilClicked || GUIUtility.keyboardControl == controlID) + { + this.Zoom(this.mousePositionInDrawing, true); + Event.current.Use(); + } + } + break; + } + GUILayout.EndArea(); + } + public void EndViewGUI() + { + if (this.m_MinimalGUI && Event.current.type == EventType.Repaint) + { + this.SliderGUI(); + } + } + private void SliderGUI() + { + if (!this.m_HSlider && !this.m_VSlider) + { + return; + } + Bounds drawingBounds = this.drawingBounds; + Rect shownAreaInsideMargins = this.shownAreaInsideMargins; + float num = this.styles.sliderWidth - this.styles.visualSliderWidth; + float num2 = (!this.vSlider || !this.hSlider) ? 0f : num; + if (this.m_HSlider) + { + Rect position = new Rect(this.drawRect.x + 1f, this.drawRect.yMax - num, this.drawRect.width - num2, this.styles.sliderWidth); + float width = shownAreaInsideMargins.width; + float xMin = shownAreaInsideMargins.xMin; + EditorGUIExt.MinMaxScroller(position, this.horizontalScrollbarID, ref xMin, ref width, drawingBounds.min.x, drawingBounds.max.x, float.NegativeInfinity, float.PositiveInfinity, this.styles.horizontalScrollbar, this.styles.horizontalMinMaxScrollbarThumb, this.styles.horizontalScrollbarLeftButton, this.styles.horizontalScrollbarRightButton, true); + float num3 = xMin; + float num4 = xMin + width; + if (num3 > shownAreaInsideMargins.xMin) + { + num3 = Mathf.Min(num3, num4 - this.m_HScaleMin); + } + if (num4 < shownAreaInsideMargins.xMax) + { + num4 = Mathf.Max(num4, num3 + this.m_HScaleMin); + } + this.SetShownHRangeInsideMargins(num3, num4); + } + if (this.m_VSlider) + { + Rect position2 = new Rect(this.drawRect.xMax - num, this.drawRect.y, this.styles.sliderWidth, this.drawRect.height - num2); + float height = shownAreaInsideMargins.height; + float num5 = -shownAreaInsideMargins.yMax; + EditorGUIExt.MinMaxScroller(position2, this.verticalScrollbarID, ref num5, ref height, -drawingBounds.max.y, -drawingBounds.min.y, float.NegativeInfinity, float.PositiveInfinity, this.styles.verticalScrollbar, this.styles.verticalMinMaxScrollbarThumb, this.styles.verticalScrollbarUpButton, this.styles.verticalScrollbarDownButton, false); + float num3 = -(num5 + height); + float num4 = -num5; + if (num3 > shownAreaInsideMargins.yMin) + { + num3 = Mathf.Min(num3, num4 - this.m_VScaleMin); + } + if (num4 < shownAreaInsideMargins.yMax) + { + num4 = Mathf.Max(num4, num3 + this.m_VScaleMin); + } + this.SetShownVRangeInsideMargins(num3, num4); + } + } + private void Pan() + { + if (!this.m_HRangeLocked) + { + this.m_Translation.x = this.m_Translation.x + Event.current.delta.x; + } + if (!this.m_VRangeLocked) + { + this.m_Translation.y = this.m_Translation.y + Event.current.delta.y; + } + this.EnforceScaleAndRange(); + } + private void Zoom(Vector2 zoomAround, bool scrollwhell) + { + float num = Event.current.delta.x + Event.current.delta.y; + if (scrollwhell) + { + num = -num; + } + float num2 = Mathf.Max(0.01f, 1f + num * 0.01f); + if (!this.m_HRangeLocked) + { + this.m_Translation.x = this.m_Translation.x - zoomAround.x * (num2 - 1f) * this.m_Scale.x; + this.m_Scale.x = this.m_Scale.x * num2; + } + if (!this.m_VRangeLocked) + { + this.m_Translation.y = this.m_Translation.y - zoomAround.y * (num2 - 1f) * this.m_Scale.y; + this.m_Scale.y = this.m_Scale.y * num2; + } + this.EnforceScaleAndRange(); + } + private void EnforceScaleAndRange() + { + float hScaleMin = this.m_HScaleMin; + float vScaleMin = this.m_VScaleMin; + float value = this.m_HScaleMax; + float value2 = this.m_VScaleMax; + if (this.hRangeMax != float.PositiveInfinity && this.hRangeMin != float.NegativeInfinity) + { + value = Mathf.Min(this.m_HScaleMax, this.hRangeMax - this.hRangeMin); + } + if (this.vRangeMax != float.PositiveInfinity && this.vRangeMin != float.NegativeInfinity) + { + value2 = Mathf.Min(this.m_VScaleMax, this.vRangeMax - this.vRangeMin); + } + Rect lastShownAreaInsideMargins = this.m_LastShownAreaInsideMargins; + Rect shownAreaInsideMargins = this.shownAreaInsideMargins; + if (shownAreaInsideMargins == lastShownAreaInsideMargins) + { + return; + } + float num = 1E-05f; + if (shownAreaInsideMargins.width < lastShownAreaInsideMargins.width - num) + { + float t = Mathf.InverseLerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, hScaleMin); + shownAreaInsideMargins = new Rect(Mathf.Lerp(lastShownAreaInsideMargins.x, shownAreaInsideMargins.x, t), shownAreaInsideMargins.y, Mathf.Lerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, t), shownAreaInsideMargins.height); + } + if (shownAreaInsideMargins.height < lastShownAreaInsideMargins.height - num) + { + float t2 = Mathf.InverseLerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, vScaleMin); + shownAreaInsideMargins = new Rect(shownAreaInsideMargins.x, Mathf.Lerp(lastShownAreaInsideMargins.y, shownAreaInsideMargins.y, t2), shownAreaInsideMargins.width, Mathf.Lerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, t2)); + } + if (shownAreaInsideMargins.width > lastShownAreaInsideMargins.width + num) + { + float t3 = Mathf.InverseLerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, value); + shownAreaInsideMargins = new Rect(Mathf.Lerp(lastShownAreaInsideMargins.x, shownAreaInsideMargins.x, t3), shownAreaInsideMargins.y, Mathf.Lerp(lastShownAreaInsideMargins.width, shownAreaInsideMargins.width, t3), shownAreaInsideMargins.height); + } + if (shownAreaInsideMargins.height > lastShownAreaInsideMargins.height + num) + { + float t4 = Mathf.InverseLerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, value2); + shownAreaInsideMargins = new Rect(shownAreaInsideMargins.x, Mathf.Lerp(lastShownAreaInsideMargins.y, shownAreaInsideMargins.y, t4), shownAreaInsideMargins.width, Mathf.Lerp(lastShownAreaInsideMargins.height, shownAreaInsideMargins.height, t4)); + } + if (shownAreaInsideMargins.xMin < this.hRangeMin) + { + shownAreaInsideMargins.x = this.hRangeMin; + } + if (shownAreaInsideMargins.xMax > this.hRangeMax) + { + shownAreaInsideMargins.x = this.hRangeMax - shownAreaInsideMargins.width; + } + if (shownAreaInsideMargins.yMin < this.vRangeMin) + { + shownAreaInsideMargins.y = this.vRangeMin; + } + if (shownAreaInsideMargins.yMax > this.vRangeMax) + { + shownAreaInsideMargins.y = this.vRangeMax - shownAreaInsideMargins.height; + } + this.shownAreaInsideMarginsInternal = shownAreaInsideMargins; + this.m_LastShownAreaInsideMargins = shownAreaInsideMargins; + } + public float PixelToTime(float pixelX, Rect rect) + { + return (pixelX - rect.x) * this.shownArea.width / rect.width + this.shownArea.x; + } + public float TimeToPixel(float time, Rect rect) + { + return (time - this.shownArea.x) / this.shownArea.width * rect.width + rect.x; + } + public float PixelDeltaToTime(Rect rect) + { + return this.shownArea.width / rect.width; + } + } +} diff --git a/UnityEditor/UnityEditor/iOSLaunchScreenType.cs b/UnityEditor/UnityEditor/iOSLaunchScreenType.cs new file mode 100644 index 00000000..d6f13cb7 --- /dev/null +++ b/UnityEditor/UnityEditor/iOSLaunchScreenType.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor +{ + internal enum iOSLaunchScreenType + { + Default, + None, + ImageAndBackgroundRelative, + ImageAndBackgroundConstant, + CustomXib + } +} diff --git a/UnityEditor/UnityEditor/iOSSdkVersion.cs b/UnityEditor/UnityEditor/iOSSdkVersion.cs new file mode 100644 index 00000000..853ef6c4 --- /dev/null +++ b/UnityEditor/UnityEditor/iOSSdkVersion.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum iOSSdkVersion + { + DeviceSDK = 988, + SimulatorSDK + } +} diff --git a/UnityEditor/UnityEditor/iOSShowActivityIndicatorOnLoading.cs b/UnityEditor/UnityEditor/iOSShowActivityIndicatorOnLoading.cs new file mode 100644 index 00000000..b8c684fa --- /dev/null +++ b/UnityEditor/UnityEditor/iOSShowActivityIndicatorOnLoading.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum iOSShowActivityIndicatorOnLoading + { + WhiteLarge, + White, + Gray, + DontShow = -1 + } +} diff --git a/UnityEditor/UnityEditor/iOSStatusBarStyle.cs b/UnityEditor/UnityEditor/iOSStatusBarStyle.cs new file mode 100644 index 00000000..3e07eccb --- /dev/null +++ b/UnityEditor/UnityEditor/iOSStatusBarStyle.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum iOSStatusBarStyle + { + Default, + BlackTranslucent, + BlackOpaque + } +} diff --git a/UnityEditor/UnityEditor/iOSTargetDevice.cs b/UnityEditor/UnityEditor/iOSTargetDevice.cs new file mode 100644 index 00000000..fd4f5983 --- /dev/null +++ b/UnityEditor/UnityEditor/iOSTargetDevice.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum iOSTargetDevice + { + iPhoneOnly, + iPadOnly, + iPhoneAndiPad + } +} diff --git a/UnityEditor/UnityEditor/iOSTargetOSVersion.cs b/UnityEditor/UnityEditor/iOSTargetOSVersion.cs new file mode 100644 index 00000000..829724b6 --- /dev/null +++ b/UnityEditor/UnityEditor/iOSTargetOSVersion.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEditor +{ + public enum iOSTargetOSVersion + { + iOS_4_0 = 10, + iOS_4_1 = 12, + iOS_4_2 = 14, + iOS_4_3 = 16, + iOS_5_0 = 18, + iOS_5_1 = 20, + iOS_6_0 = 22, + iOS_7_0 = 24, + iOS_7_1 = 26, + iOS_8_0 = 28, + iOS_8_1 = 30, + Unknown = 999 + } +} diff --git a/UnityEditor/UnityEditor/iOSTargetResolution.cs b/UnityEditor/UnityEditor/iOSTargetResolution.cs new file mode 100644 index 00000000..635e13de --- /dev/null +++ b/UnityEditor/UnityEditor/iOSTargetResolution.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public enum iOSTargetResolution + { + Native, + ResolutionAutoPerformance = 3, + ResolutionAutoQuality, + Resolution320p, + Resolution640p, + Resolution768p + } +} diff --git a/UnityEditor/UnityEditor/iPhoneArchitecture.cs b/UnityEditor/UnityEditor/iPhoneArchitecture.cs new file mode 100644 index 00000000..4a5af6b6 --- /dev/null +++ b/UnityEditor/UnityEditor/iPhoneArchitecture.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum iPhoneArchitecture + { + ARMv7, + ARM64, + Universal + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/AssetModificationHook.cs b/UnityEditor/UnityEditorInternal.VersionControl/AssetModificationHook.cs new file mode 100644 index 00000000..df3e03f5 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/AssetModificationHook.cs @@ -0,0 +1,87 @@ +using System; +using UnityEditor; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditorInternal.VersionControl +{ + public class AssetModificationHook + { + private static Asset GetStatusCachedIfPossible(string from) + { + Asset asset = Provider.CacheStatus(from); + if (asset == null || asset.IsState(Asset.States.Updating)) + { + Task task = Provider.Status(from, false); + task.Wait(); + asset = Provider.CacheStatus(from); + } + return asset; + } + public static AssetMoveResult OnWillMoveAsset(string from, string to) + { + if (!Provider.enabled) + { + return AssetMoveResult.DidNotMove; + } + Asset statusCachedIfPossible = AssetModificationHook.GetStatusCachedIfPossible(from); + if (statusCachedIfPossible == null || !statusCachedIfPossible.IsUnderVersionControl) + { + return AssetMoveResult.DidNotMove; + } + if (statusCachedIfPossible.IsState(Asset.States.OutOfSync)) + { + Debug.LogError("Cannot move version controlled file that is not up to date. Please get latest changes from server"); + return AssetMoveResult.FailedMove; + } + if (statusCachedIfPossible.IsState(Asset.States.DeletedRemote)) + { + Debug.LogError("Cannot move version controlled file that is deleted on server. Please get latest changes from server"); + return AssetMoveResult.FailedMove; + } + if (statusCachedIfPossible.IsState(Asset.States.CheckedOutRemote)) + { + Debug.LogError("Cannot move version controlled file that is checked out on server. Please get latest changes from server"); + return AssetMoveResult.FailedMove; + } + if (statusCachedIfPossible.IsState(Asset.States.LockedRemote)) + { + Debug.LogError("Cannot move version controlled file that is locked on server. Please get latest changes from server"); + return AssetMoveResult.FailedMove; + } + Task task = Provider.Move(from, to); + task.Wait(); + return (AssetMoveResult)((!task.success) ? 1 : task.resultCode); + } + public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option) + { + if (!Provider.enabled) + { + return AssetDeleteResult.DidNotDelete; + } + Task task = Provider.Delete(assetPath); + task.SetCompletionAction(CompletionAction.UpdatePendingWindow); + task.Wait(); + return (!task.success) ? AssetDeleteResult.FailedDelete : AssetDeleteResult.DidNotDelete; + } + public static bool IsOpenForEdit(string assetPath, out string message) + { + message = string.Empty; + if (!Provider.enabled) + { + return true; + } + if (string.IsNullOrEmpty(assetPath)) + { + return true; + } + Asset asset = Provider.GetAssetByPath(assetPath); + if (asset == null) + { + Task task = Provider.Status(assetPath, false); + task.Wait(); + asset = ((task.assetList.Count <= 0) ? null : task.assetList[0]); + } + return asset != null && Provider.IsOpenForEdit(asset); + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ChangeSetContextMenu.cs b/UnityEditor/UnityEditorInternal.VersionControl/ChangeSetContextMenu.cs new file mode 100644 index 00000000..a91c1708 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/ChangeSetContextMenu.cs @@ -0,0 +1,111 @@ +using System; +using UnityEditor.VersionControl; +namespace UnityEditorInternal.VersionControl +{ + public class ChangeSetContextMenu + { + private static ChangeSet GetChangeSet(ChangeSets changes) + { + if (changes.Count == 0) + { + return null; + } + return changes[0]; + } + private static bool SubmitTest(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + return selectedChangeSets.Count > 0 && Provider.SubmitIsValid(selectedChangeSets[0], null); + } + private static void Submit(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + if (changeSet != null) + { + WindowChange.Open(changeSet, new AssetList(), true); + } + } + private static bool RevertTest(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + return selectedChangeSets.Count > 0; + } + private static void Revert(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + if (changeSet != null) + { + WindowRevert.Open(changeSet); + } + } + private static bool RevertUnchangedTest(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + return selectedChangeSets.Count > 0; + } + private static void RevertUnchanged(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + Provider.RevertChangeSets(selectedChangeSets, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool ResolveTest(int userData) + { + return ListControl.FromID(userData).SelectedChangeSets.Count > 0; + } + private static void Resolve(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + if (changeSet != null) + { + WindowResolve.Open(changeSet); + } + } + private static bool NewChangeSetTest(int userDatad) + { + return Provider.isActive; + } + private static void NewChangeSet(int userData) + { + WindowChange.Open(new AssetList(), false); + } + private static bool EditChangeSetTest(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + if (selectedChangeSets.Count == 0) + { + return false; + } + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + return changeSet.id != "-1" && Provider.SubmitIsValid(selectedChangeSets[0], null); + } + private static void EditChangeSet(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + if (changeSet != null) + { + WindowChange.Open(changeSet, new AssetList(), false); + } + } + private static bool DeleteChangeSetTest(int userData) + { + ListControl listControl = ListControl.FromID(userData); + ChangeSets selectedChangeSets = listControl.SelectedChangeSets; + if (selectedChangeSets.Count == 0) + { + return false; + } + ChangeSet changeSet = ChangeSetContextMenu.GetChangeSet(selectedChangeSets); + ListItem changeSetItem = listControl.GetChangeSetItem(changeSet); + return (changeSetItem == null || !changeSetItem.HasChildren || changeSetItem.FirstChild.Asset == null || !(changeSetItem.FirstChild.Name != "Empty change list")) && changeSet.id != "-1" && Provider.DeleteChangeSetsIsValid(selectedChangeSets); + } + private static void DeleteChangeSet(int userData) + { + ChangeSets selectedChangeSets = ListControl.FromID(userData).SelectedChangeSets; + Provider.DeleteChangeSets(selectedChangeSets).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs b/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs new file mode 100644 index 00000000..dd8d9962 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs @@ -0,0 +1,1194 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditorInternal.VersionControl +{ + [Serializable] + public class ListControl + { + public enum SelectDirection + { + Up, + Down, + Current + } + [Serializable] + public class ListState + { + [SerializeField] + public float Scroll; + [SerializeField] + public List Expanded = new List(); + } + public delegate void ExpandDelegate(ChangeSet expand, ListItem item); + public delegate void DragDelegate(ChangeSet target); + public delegate void ActionDelegate(ListItem item, int actionIdx); + private const float c_lineHeight = 16f; + private const float c_scrollWidth = 14f; + private const string c_changeKeyPrefix = "_chkeyprfx_"; + private ListControl.ExpandDelegate expandDelegate; + private ListControl.DragDelegate dragDelegate; + private ListControl.ActionDelegate actionDelegate; + private ListItem root = new ListItem(); + private ListItem active; + private List visibleList = new List(); + private Texture2D blueTex; + private Texture2D greyTex; + private Texture2D yellowTex; + [SerializeField] + private ListControl.ListState m_listState; + private Dictionary pathSearch = new Dictionary(); + private Texture2D defaultIcon; + private bool readOnly; + private bool scrollVisible; + private string menuFolder; + private string menuDefault; + private bool dragAcceptOnly; + private ListItem dragTarget; + private int dragCount; + private ListControl.SelectDirection dragAdjust = ListControl.SelectDirection.Current; + private Dictionary selectList = new Dictionary(); + private ListItem singleSelect; + private GUIContent calcSizeTmpContent = new GUIContent(); + [NonSerialized] + private int uniqueID; + private static int s_uniqueIDCount = 1; + private static Dictionary s_uniqueIDList = new Dictionary(); + public ListControl.ListState listState + { + get + { + if (this.m_listState == null) + { + this.m_listState = new ListControl.ListState(); + } + return this.m_listState; + } + } + public ListControl.ExpandDelegate ExpandEvent + { + get + { + return this.expandDelegate; + } + set + { + this.expandDelegate = value; + } + } + public ListControl.DragDelegate DragEvent + { + get + { + return this.dragDelegate; + } + set + { + this.dragDelegate = value; + } + } + public ListControl.ActionDelegate ActionEvent + { + get + { + return this.actionDelegate; + } + set + { + this.actionDelegate = value; + } + } + public ListItem Root + { + get + { + return this.root; + } + } + public AssetList SelectedAssets + { + get + { + AssetList assetList = new AssetList(); + foreach (KeyValuePair current in this.selectList) + { + if (current.Value.Item is Asset) + { + assetList.Add(current.Value.Item as Asset); + } + } + return assetList; + } + } + public ChangeSets SelectedChangeSets + { + get + { + ChangeSets changeSets = new ChangeSets(); + foreach (KeyValuePair current in this.selectList) + { + if (current.Value != null && current.Value.Item is ChangeSet) + { + changeSets.Add(current.Value.Item as ChangeSet); + } + } + return changeSets; + } + } + public bool ReadOnly + { + get + { + return this.readOnly; + } + set + { + this.readOnly = value; + } + } + public string MenuFolder + { + get + { + return this.menuFolder; + } + set + { + this.menuFolder = value; + } + } + public string MenuDefault + { + get + { + return this.menuDefault; + } + set + { + this.menuDefault = value; + } + } + public bool DragAcceptOnly + { + get + { + return this.dragAcceptOnly; + } + set + { + this.dragAcceptOnly = value; + } + } + public int Size + { + get + { + return this.visibleList.Count; + } + } + public ListControl() + { + this.uniqueID = ListControl.s_uniqueIDCount++; + ListControl.s_uniqueIDList.Add(this.uniqueID, this); + this.active = this.root; + this.Clear(); + } + public static ListControl FromID(int id) + { + ListControl result; + try + { + result = ListControl.s_uniqueIDList[id]; + } + catch + { + result = null; + } + return result; + } + ~ListControl() + { + ListControl.s_uniqueIDList.Remove(this.uniqueID); + } + public ListItem FindItemWithIdentifier(int identifier) + { + return this.root.FindWithIdentifierRecurse(identifier); + } + public ListItem Add(ListItem parent, string name, Asset asset) + { + ListItem listItem = (parent == null) ? this.root : parent; + ListItem listItem2 = new ListItem(); + listItem2.Name = name; + listItem2.Asset = asset; + listItem.Add(listItem2); + if (listItem2.Asset == null) + { + return listItem2; + } + if (listItem2.Asset.path.Length > 0) + { + this.pathSearch[listItem2.Asset.path.ToLower()] = listItem2; + } + return listItem2; + } + public ListItem Add(ListItem parent, string name, ChangeSet change) + { + ListItem listItem = (parent == null) ? this.root : parent; + ListItem listItem2 = new ListItem(); + listItem2.Name = name; + listItem2.Change = (change ?? new ChangeSet(name)); + listItem.Add(listItem2); + this.pathSearch["_chkeyprfx_" + change.id.ToString()] = listItem2; + return listItem2; + } + internal ListItem GetChangeSetItem(ChangeSet change) + { + if (change == null) + { + return null; + } + for (ListItem listItem = this.root.FirstChild; listItem != null; listItem = listItem.Next) + { + ChangeSet changeSet = listItem.Item as ChangeSet; + if (changeSet != null && changeSet.id == change.id) + { + return listItem; + } + } + return null; + } + public void Clear() + { + this.root.Clear(); + this.pathSearch.Clear(); + this.root.Name = "ROOT"; + this.root.Expanded = true; + } + public void Refresh() + { + this.Refresh(true); + } + public void Refresh(bool updateExpanded) + { + if (updateExpanded) + { + this.LoadExpanded(this.root); + this.root.Name = "ROOT"; + this.root.Expanded = true; + this.listState.Expanded.Clear(); + this.CallExpandedEvent(this.root, false); + } + this.SelectedRefresh(); + } + public void Sync() + { + this.SelectedClear(); + UnityEngine.Object[] objects = Selection.objects; + for (int i = 0; i < objects.Length; i++) + { + UnityEngine.Object @object = objects[i]; + if (AssetDatabase.IsMainAsset(@object)) + { + string str = Application.dataPath.Substring(0, Application.dataPath.Length - 6); + string path = str + AssetDatabase.GetAssetOrScenePath(@object); + ListItem listItem = this.PathSearchFind(path); + if (listItem != null) + { + this.SelectedAdd(listItem); + } + } + } + } + public bool OnGUI(Rect area, bool focus) + { + bool flag = false; + this.CreateResources(); + Event current = Event.current; + int openCount = this.active.OpenCount; + int num = (int)(area.height / 16f); + if (current.type == EventType.ScrollWheel) + { + flag = true; + this.listState.Scroll += current.delta.y; + this.listState.Scroll = Mathf.Clamp(this.listState.Scroll, 0f, (float)(openCount - num)); + } + if (openCount > num) + { + Rect position = new Rect(area.x + area.width - 14f, area.y, 14f, area.height); + area.width -= 14f; + float scroll = this.listState.Scroll; + this.listState.Scroll = GUI.VerticalScrollbar(position, this.listState.Scroll, (float)num, 0f, (float)openCount); + this.listState.Scroll = Mathf.Clamp(this.listState.Scroll, 0f, (float)(openCount - num)); + if (scroll != this.listState.Scroll) + { + flag = true; + } + if (!this.scrollVisible) + { + this.scrollVisible = true; + } + } + else + { + if (this.scrollVisible) + { + this.scrollVisible = false; + } + } + this.UpdateVisibleList(area, this.listState.Scroll); + if (focus && !this.readOnly) + { + if (current.isKey) + { + flag = true; + this.HandleKeyInput(current); + } + this.HandleSelectAll(); + flag = (this.HandleMouse(area) || flag); + if (current.type == EventType.DragUpdated && area.Contains(current.mousePosition)) + { + if (current.mousePosition.y < area.y + 16f) + { + this.listState.Scroll = Mathf.Clamp(this.listState.Scroll - 1f, 0f, (float)(openCount - num)); + } + else + { + if (current.mousePosition.y > area.y + area.height - 16f) + { + this.listState.Scroll = Mathf.Clamp(this.listState.Scroll + 1f, 0f, (float)(openCount - num)); + } + } + } + } + this.DrawItems(area, focus); + return flag; + } + private bool HandleMouse(Rect area) + { + Event current = Event.current; + bool result = false; + bool flag = area.Contains(current.mousePosition); + if (current.type == EventType.MouseDown && flag) + { + result = true; + this.dragCount = 0; + GUIUtility.keyboardControl = 0; + this.singleSelect = this.GetItemAt(area, current.mousePosition); + if (this.singleSelect != null && !this.singleSelect.Dummy) + { + if (current.button == 0 && current.clickCount > 1 && this.singleSelect.Asset != null) + { + this.singleSelect.Asset.Edit(); + } + if (current.button < 2) + { + float num = area.x + (float)((this.singleSelect.Indent - 1) * 18); + if (current.mousePosition.x >= num && current.mousePosition.x < num + 16f && this.singleSelect.CanExpand) + { + this.singleSelect.Expanded = !this.singleSelect.Expanded; + this.CallExpandedEvent(this.singleSelect, true); + this.singleSelect = null; + } + else + { + if (current.control || current.command) + { + if (current.button == 1) + { + this.SelectedAdd(this.singleSelect); + } + else + { + this.SelectedToggle(this.singleSelect); + } + this.singleSelect = null; + } + else + { + if (current.shift) + { + this.SelectionFlow(this.singleSelect); + this.singleSelect = null; + } + else + { + if (!this.IsSelected(this.singleSelect)) + { + this.SelectedSet(this.singleSelect); + this.singleSelect = null; + } + } + } + } + } + } + else + { + if (current.button == 0) + { + this.SelectedClear(); + this.singleSelect = null; + } + } + } + else + { + if ((current.type == EventType.MouseUp || current.type == EventType.ContextClick) && flag) + { + GUIUtility.keyboardControl = 0; + this.singleSelect = this.GetItemAt(area, current.mousePosition); + this.dragCount = 0; + result = true; + if (this.singleSelect != null && !this.singleSelect.Dummy) + { + if (current.type == EventType.ContextClick) + { + this.singleSelect = null; + if (this.IsSelectedFolder() && !string.IsNullOrEmpty(this.menuFolder)) + { + ListControl.s_uniqueIDList[this.uniqueID] = this; + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), this.menuFolder, new MenuCommand(null, this.uniqueID)); + } + else + { + if (!string.IsNullOrEmpty(this.menuDefault)) + { + ListControl.s_uniqueIDList[this.uniqueID] = this; + EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), this.menuDefault, new MenuCommand(null, this.uniqueID)); + } + } + } + else + { + if (current.type != EventType.ContextClick && current.button == 0 && !current.control && !current.command && !current.shift && this.IsSelected(this.singleSelect)) + { + this.SelectedSet(this.singleSelect); + this.singleSelect = null; + } + } + } + } + } + if (current.type == EventType.MouseDrag && flag) + { + this.dragCount++; + if (this.dragCount > 2 && Selection.objects.Length > 0) + { + DragAndDrop.PrepareStartDrag(); + if (this.singleSelect != null) + { + DragAndDrop.objectReferences = new UnityEngine.Object[] + { + this.singleSelect.Asset.Load() + }; + } + else + { + DragAndDrop.objectReferences = Selection.objects; + } + DragAndDrop.StartDrag("Move"); + } + } + if (current.type == EventType.DragUpdated) + { + result = true; + DragAndDrop.visualMode = DragAndDropVisualMode.Move; + this.dragTarget = this.GetItemAt(area, current.mousePosition); + if (this.dragTarget != null) + { + if (this.IsSelected(this.dragTarget)) + { + this.dragTarget = null; + } + else + { + if (this.dragAcceptOnly) + { + if (!this.dragTarget.CanAccept) + { + this.dragTarget = null; + } + } + else + { + bool flag2 = !this.dragTarget.CanAccept || this.dragTarget.PrevOpenVisible != this.dragTarget.Parent; + bool flag3 = !this.dragTarget.CanAccept || this.dragTarget.NextOpenVisible != this.dragTarget.FirstChild; + float num2 = (!this.dragTarget.CanAccept) ? 8f : 2f; + int num3 = (int)((current.mousePosition.y - area.y) / 16f); + float num4 = area.y + (float)num3 * 16f; + this.dragAdjust = ListControl.SelectDirection.Current; + if (flag2 && current.mousePosition.y <= num4 + num2) + { + this.dragAdjust = ListControl.SelectDirection.Up; + } + else + { + if (flag3 && current.mousePosition.y >= num4 + 16f - num2) + { + this.dragAdjust = ListControl.SelectDirection.Down; + } + } + } + } + } + } + if (current.type == EventType.DragPerform && this.dragTarget != null) + { + ListItem listItem = (this.dragAdjust != ListControl.SelectDirection.Current) ? this.dragTarget.Parent : this.dragTarget; + if (this.dragDelegate != null && listItem != null && listItem.CanAccept) + { + this.dragDelegate(listItem.Change); + } + this.dragTarget = null; + } + if (current.type == EventType.DragExited) + { + this.dragTarget = null; + } + return result; + } + private void DrawItems(Rect area, bool focus) + { + float num = area.y; + foreach (ListItem current in this.visibleList) + { + float num2 = area.x + (float)((current.Indent - 1) * 18); + bool selected = !this.readOnly && this.IsSelected(current); + if (current.Parent != null && current.Parent.Parent != null && current.Parent.Parent.Parent == null) + { + num2 -= 16f; + } + this.DrawItem(current, area, num2, num, focus, selected); + num += 16f; + } + } + private void HandleSelectAll() + { + if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == "SelectAll") + { + Event.current.Use(); + } + else + { + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "SelectAll") + { + this.SelectedAll(); + Event.current.Use(); + } + } + } + private void CreateResources() + { + if (this.blueTex == null) + { + this.blueTex = new Texture2D(1, 1); + this.blueTex.SetPixel(0, 0, new Color(0.23f, 0.35f, 0.55f)); + this.blueTex.hideFlags = HideFlags.HideAndDontSave; + this.blueTex.name = "BlueTex"; + this.blueTex.Apply(); + } + if (this.greyTex == null) + { + this.greyTex = new Texture2D(1, 1); + this.greyTex.SetPixel(0, 0, new Color(0.3f, 0.3f, 0.3f)); + this.greyTex.hideFlags = HideFlags.HideAndDontSave; + this.greyTex.name = "GrayTex"; + this.greyTex.Apply(); + } + if (this.yellowTex == null) + { + this.yellowTex = new Texture2D(1, 1); + this.yellowTex.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.2f)); + this.yellowTex.name = "YellowTex"; + this.yellowTex.hideFlags = HideFlags.HideAndDontSave; + this.yellowTex.Apply(); + } + if (this.defaultIcon == null) + { + this.defaultIcon = EditorGUIUtility.LoadIcon("vcs_document"); + this.defaultIcon.hideFlags = HideFlags.HideAndDontSave; + } + } + private void HandleKeyInput(Event e) + { + if (e.type != EventType.KeyDown) + { + return; + } + if (this.selectList.Count == 0) + { + return; + } + if (e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.DownArrow) + { + ListItem listItem; + if (e.keyCode == KeyCode.UpArrow) + { + listItem = this.SelectedFirstIn(this.active); + if (listItem != null) + { + listItem = listItem.PrevOpenSkip; + } + } + else + { + listItem = this.SelectedLastIn(this.active); + if (listItem != null) + { + listItem = listItem.NextOpenSkip; + } + } + if (listItem != null) + { + if (!this.ScrollUpTo(listItem)) + { + this.ScrollDownTo(listItem); + } + if (e.shift) + { + this.SelectionFlow(listItem); + } + else + { + this.SelectedSet(listItem); + } + } + } + if (e.keyCode == KeyCode.LeftArrow || e.keyCode == KeyCode.RightArrow) + { + ListItem listItem2 = this.SelectedCurrentIn(this.active); + listItem2.Expanded = (e.keyCode == KeyCode.RightArrow); + this.CallExpandedEvent(listItem2, true); + } + if (e.keyCode == KeyCode.Return && GUIUtility.keyboardControl == 0) + { + ListItem listItem3 = this.SelectedCurrentIn(this.active); + listItem3.Asset.Edit(); + } + } + private void DrawItem(ListItem item, Rect area, float x, float y, bool focus, bool selected) + { + bool flag = item == this.dragTarget; + bool flag2 = selected; + if (selected) + { + Texture2D image = (!focus) ? this.greyTex : this.blueTex; + GUI.DrawTexture(new Rect(area.x, y, area.width, 16f), image, ScaleMode.StretchToFill, false); + } + else + { + if (flag) + { + ListControl.SelectDirection selectDirection = this.dragAdjust; + if (selectDirection != ListControl.SelectDirection.Up) + { + if (selectDirection != ListControl.SelectDirection.Down) + { + if (item.CanAccept) + { + GUI.DrawTexture(new Rect(area.x, y, area.width, 16f), this.yellowTex, ScaleMode.StretchToFill, false); + flag2 = true; + } + } + else + { + GUI.DrawTexture(new Rect(x, y + 16f - 1f, area.width, 2f), this.yellowTex, ScaleMode.StretchToFill, false); + } + } + else + { + if (item.PrevOpenVisible != item.Parent) + { + GUI.DrawTexture(new Rect(x, y - 1f, area.width, 2f), this.yellowTex, ScaleMode.StretchToFill, false); + } + } + } + else + { + if (this.dragTarget != null && item == this.dragTarget.Parent && this.dragAdjust != ListControl.SelectDirection.Current) + { + GUI.DrawTexture(new Rect(area.x, y, area.width, 16f), this.yellowTex, ScaleMode.StretchToFill, false); + flag2 = true; + } + } + } + if (item.HasActions) + { + for (int i = 0; i < item.Actions.Length; i++) + { + this.calcSizeTmpContent.text = item.Actions[i]; + Vector2 vector = GUI.skin.button.CalcSize(this.calcSizeTmpContent); + if (GUI.Button(new Rect(x, y, vector.x, 16f), item.Actions[i])) + { + this.actionDelegate(item, i); + } + x += vector.x + 4f; + } + } + if (item.CanExpand) + { + EditorGUI.Foldout(new Rect(x, y, 16f, 16f), item.Expanded, GUIContent.none); + } + Texture texture = item.Icon; + Color color = GUI.color; + Color contentColor = GUI.contentColor; + if (item.Dummy) + { + GUI.color = new Color(0.65f, 0.65f, 0.65f); + } + if (!item.Dummy) + { + if (texture == null) + { + texture = InternalEditorUtility.GetIconForFile(item.Name); + } + Rect rect = new Rect(x + 14f, y, 16f, 16f); + if (texture != null) + { + GUI.DrawTexture(rect, texture); + } + if (item.Asset != null) + { + Rect itemRect = rect; + itemRect.width += 12f; + itemRect.x -= 6f; + Overlay.DrawOverlay(item.Asset, itemRect); + } + } + if (flag2) + { + GUI.contentColor = new Color(3f, 3f, 3f); + GUI.Label(new Rect(x + 32f, y, area.width - (x + 32f), 18f), this.DisplayName(item)); + } + else + { + GUI.Label(new Rect(x + 32f, y, area.width - (x + 32f), 18f), this.DisplayName(item)); + } + GUI.contentColor = contentColor; + GUI.color = color; + } + private void UpdateVisibleList(Rect area, float scrollPos) + { + float num = area.y; + float num2 = area.y + area.height - 16f; + ListItem nextOpenVisible = this.active.NextOpenVisible; + this.visibleList.Clear(); + for (float num3 = 0f; num3 < scrollPos; num3 += 1f) + { + if (nextOpenVisible == null) + { + return; + } + nextOpenVisible = nextOpenVisible.NextOpenVisible; + } + ListItem listItem = nextOpenVisible; + while (listItem != null && num < num2) + { + this.visibleList.Add(listItem); + num += 16f; + listItem = listItem.NextOpenVisible; + } + } + private ListItem GetItemAt(Rect area, Vector2 pos) + { + int num = (int)((pos.y - area.y) / 16f); + if (num >= 0 && num < this.visibleList.Count) + { + return this.visibleList[num]; + } + return null; + } + private bool ScrollUpTo(ListItem item) + { + int num = (int)this.listState.Scroll; + ListItem listItem = (this.visibleList.Count <= 0) ? null : this.visibleList[0]; + while (listItem != null && num >= 0) + { + if (listItem == item) + { + this.listState.Scroll = (float)num; + return true; + } + num--; + listItem = listItem.PrevOpenVisible; + } + return false; + } + private bool ScrollDownTo(ListItem item) + { + int num = (int)this.listState.Scroll; + ListItem listItem = (this.visibleList.Count <= 0) ? null : this.visibleList[this.visibleList.Count - 1]; + while (listItem != null && num >= 0) + { + if (listItem == item) + { + this.listState.Scroll = (float)num; + return true; + } + num++; + listItem = listItem.NextOpenVisible; + } + return false; + } + private void LoadExpanded(ListItem item) + { + if (item.Change != null) + { + item.Expanded = this.listState.Expanded.Contains(item.Change.id); + } + for (ListItem listItem = item.FirstChild; listItem != null; listItem = listItem.Next) + { + this.LoadExpanded(listItem); + } + } + private void CallExpandedEvent(ListItem item, bool remove) + { + if (item.Change != null) + { + if (item.Expanded) + { + if (this.expandDelegate != null) + { + this.expandDelegate(item.Change, item); + } + this.listState.Expanded.Add(item.Change.id); + } + else + { + if (remove) + { + this.listState.Expanded.Remove(item.Change.id); + } + } + } + for (ListItem listItem = item.FirstChild; listItem != null; listItem = listItem.Next) + { + this.CallExpandedEvent(listItem, remove); + } + } + private ListItem PathSearchFind(string path) + { + ListItem result; + try + { + result = this.pathSearch[path.ToLower()]; + } + catch + { + result = null; + } + return result; + } + private void PathSearchUpdate(ListItem item) + { + if (item.Asset != null && item.Asset.path.Length > 0) + { + this.pathSearch.Add(item.Asset.path.ToLower(), item); + } + else + { + if (item.Change != null) + { + this.pathSearch.Add("_chkeyprfx_" + item.Change.id.ToString(), item); + return; + } + } + for (ListItem listItem = item.FirstChild; listItem != null; listItem = listItem.Next) + { + this.PathSearchUpdate(listItem); + } + } + private bool IsSelected(ListItem item) + { + if (item.Asset != null) + { + return this.selectList.ContainsKey(item.Asset.path.ToLower()); + } + return item.Change != null && this.selectList.ContainsKey("_chkeyprfx_" + item.Change.id.ToString()); + } + private bool IsSelectedFolder() + { + foreach (KeyValuePair current in this.selectList) + { + if (current.Value != null && current.Value.Asset != null && !current.Value.Asset.isFolder) + { + return false; + } + } + return true; + } + private void SelectedClear() + { + this.selectList.Clear(); + Selection.activeObject = null; + Selection.instanceIDs = new int[0]; + } + private void SelectedRefresh() + { + Dictionary dictionary = new Dictionary(); + foreach (KeyValuePair current in this.selectList) + { + dictionary[current.Key] = this.PathSearchFind(current.Key); + } + this.selectList = dictionary; + } + public void SelectedSet(ListItem item) + { + if (item.Dummy) + { + return; + } + this.SelectedClear(); + if (item.Asset != null) + { + this.SelectedAdd(item); + } + else + { + if (item.Change != null) + { + this.selectList["_chkeyprfx_" + item.Change.id.ToString()] = item; + } + } + } + public void SelectedAll() + { + this.SelectedClear(); + this.SelectedAllHelper(this.Root); + } + private void SelectedAllHelper(ListItem _root) + { + for (ListItem listItem = _root.FirstChild; listItem != null; listItem = listItem.Next) + { + if (listItem.HasChildren) + { + this.SelectedAllHelper(listItem); + } + if (listItem.Asset != null) + { + this.SelectedAdd(listItem); + } + } + } + private ListItem GetTwin(ListItem item) + { + string text = item.Asset.path.ToLower(); + if (item.Next != null && item.Next.Asset.path.ToLower() == text.TrimEnd(new char[] + { + '/' + }) + ".meta") + { + return item.Next; + } + if (item.Prev != null && item.Prev.Asset.path.ToLower().TrimEnd(new char[] + { + '/' + }) + ".meta" == text) + { + return item.Prev; + } + return null; + } + public void SelectedAdd(ListItem item) + { + if (item.Dummy) + { + return; + } + ListItem listItem = this.SelectedCurrentIn(this.active); + if (item.Exclusive || (listItem != null && listItem.Exclusive)) + { + this.SelectedSet(item); + return; + } + string text = item.Asset.path.ToLower(); + int count = this.selectList.Count; + this.selectList[text] = item; + ListItem twin = this.GetTwin(item); + if (twin != null) + { + this.selectList[twin.Asset.path.ToLower()] = twin; + } + if (count == this.selectList.Count) + { + return; + } + int[] instanceIDs = Selection.instanceIDs; + int num = 0; + if (instanceIDs != null) + { + num = instanceIDs.Length; + } + text = ((!text.EndsWith(".meta")) ? text : text.Substring(0, text.Length - 5)); + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(text.TrimEnd(new char[] + { + '/' + })); + if (mainAssetInstanceID != 0) + { + int[] array = new int[num + 1]; + array[num] = mainAssetInstanceID; + Array.Copy(instanceIDs, array, num); + Selection.instanceIDs = array; + } + } + private void SelectedRemove(ListItem item) + { + string text = item.Asset.path.ToLower(); + this.selectList.Remove(text); + this.selectList.Remove((!text.EndsWith(".meta")) ? (text + ".meta") : text.Substring(0, text.Length - 5)); + text = ((!text.EndsWith(".meta")) ? text : text.Substring(0, text.Length - 5)); + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(text.TrimEnd(new char[] + { + '/' + })); + int[] instanceIDs = Selection.instanceIDs; + if (mainAssetInstanceID != 0 && instanceIDs.Length > 0) + { + int num = Array.IndexOf(instanceIDs, mainAssetInstanceID); + if (num < 0) + { + return; + } + int[] array = new int[instanceIDs.Length - 1]; + Array.Copy(instanceIDs, array, num); + if (num < instanceIDs.Length - 1) + { + Array.Copy(instanceIDs, num + 1, array, num, instanceIDs.Length - num - 1); + } + Selection.instanceIDs = array; + } + } + private void SelectedToggle(ListItem item) + { + if (this.IsSelected(item)) + { + this.SelectedRemove(item); + } + else + { + this.SelectedAdd(item); + } + } + private void SelectionFlow(ListItem item) + { + if (this.selectList.Count == 0) + { + this.SelectedSet(item); + } + else + { + if (!this.SelectionFlowDown(item)) + { + this.SelectionFlowUp(item); + } + } + } + private bool SelectionFlowUp(ListItem item) + { + ListItem listItem = item; + for (ListItem listItem2 = item; listItem2 != null; listItem2 = listItem2.PrevOpenVisible) + { + if (this.IsSelected(listItem2)) + { + listItem = listItem2; + } + } + if (item == listItem) + { + return false; + } + this.SelectedClear(); + this.SelectedAdd(listItem); + for (ListItem listItem2 = item; listItem2 != listItem; listItem2 = listItem2.PrevOpenVisible) + { + this.SelectedAdd(listItem2); + } + return true; + } + private bool SelectionFlowDown(ListItem item) + { + ListItem listItem = item; + for (ListItem listItem2 = item; listItem2 != null; listItem2 = listItem2.NextOpenVisible) + { + if (this.IsSelected(listItem2)) + { + listItem = listItem2; + } + } + if (item == listItem) + { + return false; + } + this.SelectedClear(); + this.SelectedAdd(listItem); + for (ListItem listItem2 = item; listItem2 != listItem; listItem2 = listItem2.NextOpenVisible) + { + this.SelectedAdd(listItem2); + } + return true; + } + private ListItem SelectedCurrentIn(ListItem root) + { + foreach (KeyValuePair current in this.selectList) + { + if (current.Value.IsChildOf(root)) + { + return current.Value; + } + } + return null; + } + private ListItem SelectedFirstIn(ListItem root) + { + ListItem listItem = this.SelectedCurrentIn(root); + for (ListItem listItem2 = listItem; listItem2 != null; listItem2 = listItem2.PrevOpenVisible) + { + if (this.IsSelected(listItem2)) + { + listItem = listItem2; + } + } + return listItem; + } + private ListItem SelectedLastIn(ListItem root) + { + ListItem listItem = this.SelectedCurrentIn(root); + for (ListItem listItem2 = listItem; listItem2 != null; listItem2 = listItem2.NextOpenVisible) + { + if (this.IsSelected(listItem2)) + { + listItem = listItem2; + } + } + return listItem; + } + private string DisplayName(ListItem item) + { + string text = item.Name; + string text2 = string.Empty; + while (text2 == string.Empty) + { + int num = text.IndexOf('\n'); + if (num < 0) + { + break; + } + text2 = text.Substring(0, num).Trim(); + text = text.Substring(num + 1); + } + if (text2 != string.Empty) + { + text = text2; + } + text = text.Trim(); + if (text == string.Empty && item.Change != null) + { + text = item.Change.id.ToString() + " " + item.Change.description; + } + return text; + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ListItem.cs b/UnityEditor/UnityEditorInternal.VersionControl/ListItem.cs new file mode 100644 index 00000000..7f647def --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/ListItem.cs @@ -0,0 +1,467 @@ +using System; +using UnityEditor; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditorInternal.VersionControl +{ + public class ListItem + { + private ListItem parent; + private ListItem firstChild; + private ListItem lastChild; + private ListItem prev; + private ListItem next; + private Texture icon; + private string name; + private int indent; + private bool expanded; + private bool exclusive; + private bool dummy; + private bool hidden; + private bool accept; + private object item; + private string[] actions; + private int identifier; + public Texture Icon + { + get + { + Asset asset = this.item as Asset; + if (this.icon == null && asset != null) + { + return AssetDatabase.GetCachedIcon(asset.path); + } + return this.icon; + } + set + { + this.icon = value; + } + } + public int Identifier + { + get + { + return this.identifier; + } + } + public string Name + { + get + { + return this.name; + } + set + { + this.name = value; + } + } + public int Indent + { + get + { + return this.indent; + } + set + { + this.SetIntent(this, value); + } + } + public object Item + { + get + { + return this.item; + } + set + { + this.item = value; + } + } + public Asset Asset + { + get + { + return this.item as Asset; + } + set + { + this.item = value; + } + } + public ChangeSet Change + { + get + { + return this.item as ChangeSet; + } + set + { + this.item = value; + } + } + public bool Expanded + { + get + { + return this.expanded; + } + set + { + this.expanded = value; + } + } + public bool Exclusive + { + get + { + return this.exclusive; + } + set + { + this.exclusive = value; + } + } + public bool Dummy + { + get + { + return this.dummy; + } + set + { + this.dummy = value; + } + } + public bool Hidden + { + get + { + return this.hidden; + } + set + { + this.hidden = value; + } + } + public bool HasChildren + { + get + { + return this.FirstChild != null; + } + } + public bool HasActions + { + get + { + return this.actions != null && this.actions.Length != 0; + } + } + public string[] Actions + { + get + { + return this.actions; + } + set + { + this.actions = value; + } + } + public bool CanExpand + { + get + { + return this.item is ChangeSet || this.HasChildren; + } + } + public bool CanAccept + { + get + { + return this.accept; + } + set + { + this.accept = value; + } + } + public int OpenCount + { + get + { + if (!this.Expanded) + { + return 0; + } + int num = 0; + for (ListItem listItem = this.firstChild; listItem != null; listItem = listItem.next) + { + if (!listItem.Hidden) + { + num++; + num += listItem.OpenCount; + } + } + return num; + } + } + public int ChildCount + { + get + { + int num = 0; + for (ListItem listItem = this.firstChild; listItem != null; listItem = listItem.next) + { + num++; + } + return num; + } + } + public ListItem Parent + { + get + { + return this.parent; + } + } + public ListItem FirstChild + { + get + { + return this.firstChild; + } + } + public ListItem LastChild + { + get + { + return this.lastChild; + } + } + public ListItem Prev + { + get + { + return this.prev; + } + } + public ListItem Next + { + get + { + return this.next; + } + } + public ListItem PrevOpen + { + get + { + for (ListItem listItem = this.prev; listItem != null; listItem = listItem.lastChild) + { + if (listItem.lastChild == null || !listItem.Expanded) + { + return listItem; + } + } + if (this.parent != null && this.parent.parent != null) + { + return this.parent; + } + return null; + } + } + public ListItem NextOpen + { + get + { + if (this.Expanded && this.firstChild != null) + { + return this.firstChild; + } + if (this.next != null) + { + return this.next; + } + for (ListItem listItem = this.parent; listItem != null; listItem = listItem.parent) + { + if (listItem.Next != null) + { + return listItem.Next; + } + } + return null; + } + } + public ListItem PrevOpenSkip + { + get + { + ListItem prevOpen = this.PrevOpen; + while (prevOpen != null && (prevOpen.Dummy || prevOpen.Hidden)) + { + prevOpen = prevOpen.PrevOpen; + } + return prevOpen; + } + } + public ListItem NextOpenSkip + { + get + { + ListItem nextOpen = this.NextOpen; + while (nextOpen != null && (nextOpen.Dummy || nextOpen.Hidden)) + { + nextOpen = nextOpen.NextOpen; + } + return nextOpen; + } + } + public ListItem PrevOpenVisible + { + get + { + ListItem prevOpen = this.PrevOpen; + while (prevOpen != null && prevOpen.Hidden) + { + prevOpen = prevOpen.PrevOpen; + } + return prevOpen; + } + } + public ListItem NextOpenVisible + { + get + { + ListItem nextOpen = this.NextOpen; + while (nextOpen != null && nextOpen.Hidden) + { + nextOpen = nextOpen.NextOpen; + } + return nextOpen; + } + } + public ListItem() + { + this.Clear(); + this.identifier = Provider.GenerateID(); + } + ~ListItem() + { + this.Clear(); + } + public bool HasPath() + { + Asset asset = this.item as Asset; + return asset != null && asset.path != null; + } + public bool IsChildOf(ListItem listItem) + { + for (ListItem listItem2 = this.Parent; listItem2 != null; listItem2 = listItem2.Parent) + { + if (listItem2 == listItem) + { + return true; + } + } + return false; + } + public void Clear() + { + this.parent = null; + this.firstChild = null; + this.lastChild = null; + this.prev = null; + this.next = null; + this.icon = null; + this.name = string.Empty; + this.indent = 0; + this.expanded = false; + this.exclusive = false; + this.dummy = false; + this.accept = false; + this.item = null; + } + public void Add(ListItem listItem) + { + listItem.parent = this; + listItem.next = null; + listItem.prev = this.lastChild; + listItem.Indent = this.indent + 1; + if (this.firstChild == null) + { + this.firstChild = listItem; + } + if (this.lastChild != null) + { + this.lastChild.next = listItem; + } + this.lastChild = listItem; + } + public bool Remove(ListItem listItem) + { + if (listItem == null) + { + return false; + } + if (listItem.parent != this) + { + return false; + } + if (listItem == this.firstChild) + { + this.firstChild = listItem.next; + } + if (listItem == this.lastChild) + { + this.lastChild = listItem.prev; + } + if (listItem.prev != null) + { + listItem.prev.next = listItem.next; + } + if (listItem.next != null) + { + listItem.next.prev = listItem.prev; + } + listItem.parent = null; + listItem.prev = null; + listItem.next = null; + return true; + } + public void RemoveAll() + { + for (ListItem listItem = this.firstChild; listItem != null; listItem = listItem.next) + { + listItem.parent = null; + } + this.firstChild = null; + this.lastChild = null; + } + public ListItem FindWithIdentifierRecurse(int inIdentifier) + { + if (this.Identifier == inIdentifier) + { + return this; + } + for (ListItem listItem = this.firstChild; listItem != null; listItem = listItem.next) + { + ListItem listItem2 = listItem.FindWithIdentifierRecurse(inIdentifier); + if (listItem2 != null) + { + return listItem2; + } + } + return null; + } + private void SetIntent(ListItem listItem, int indent) + { + listItem.indent = indent; + for (ListItem listItem2 = listItem.FirstChild; listItem2 != null; listItem2 = listItem2.Next) + { + this.SetIntent(listItem2, indent + 1); + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs b/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs new file mode 100644 index 00000000..fb019eb4 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs @@ -0,0 +1,119 @@ +using System; +using UnityEditor; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditorInternal.VersionControl +{ + public class Overlay + { + private static Asset m_Asset; + private static Rect m_ItemRect; + private static string m_IconPrefix; + public static Rect GetOverlayRect(Rect itemRect) + { + if (itemRect.width > itemRect.height) + { + itemRect.x += 16f; + itemRect.width = 20f; + } + else + { + itemRect.width = 12f; + } + itemRect.height = itemRect.width; + return itemRect; + } + public static void DrawOverlay(Asset asset, Rect itemRect) + { + if (asset == null) + { + return; + } + if (Event.current.type != EventType.Repaint) + { + return; + } + Overlay.m_Asset = asset; + Overlay.m_ItemRect = itemRect; + Overlay.m_IconPrefix = EditorSettings.externalVersionControl; + if (Overlay.m_IconPrefix == ExternalVersionControl.Disabled || Overlay.m_IconPrefix == ExternalVersionControl.AutoDetect || Overlay.m_IconPrefix == ExternalVersionControl.Generic || Overlay.m_IconPrefix == ExternalVersionControl.AssetServer) + { + return; + } + Overlay.DrawOverlays(); + } + private static void DrawOverlay(Asset.States state, Rect iconRect) + { + Rect atlasRectForState = Provider.GetAtlasRectForState((int)state); + if (atlasRectForState.width == 0f) + { + return; + } + Texture2D overlayAtlas = Provider.overlayAtlas; + if (overlayAtlas == null) + { + return; + } + GUI.DrawTextureWithTexCoords(iconRect, overlayAtlas, atlasRectForState); + } + private static void DrawOverlays() + { + float num = 16f; + float num2 = 1f; + float num3 = 4f; + float num4 = -4f; + Rect iconRect = new Rect(Overlay.m_ItemRect.x - num2, Overlay.m_ItemRect.y - num3, num, num); + Rect iconRect2 = new Rect(Overlay.m_ItemRect.xMax - num + num2, Overlay.m_ItemRect.y - num3, num, num); + Rect iconRect3 = new Rect(Overlay.m_ItemRect.x - num2, Overlay.m_ItemRect.yMax - num + num3, num, num); + Rect iconRect4 = new Rect(Overlay.m_ItemRect.xMax - num + num4, Overlay.m_ItemRect.yMax - num + num3, num, num); + if (Overlay.IsState(Asset.States.AddedLocal)) + { + Overlay.DrawOverlay(Asset.States.AddedLocal, iconRect); + } + if (Overlay.IsState(Asset.States.AddedRemote)) + { + Overlay.DrawOverlay(Asset.States.AddedRemote, iconRect2); + } + if (Overlay.IsState(Asset.States.CheckedOutLocal) && !Overlay.IsState(Asset.States.LockedLocal) && !Overlay.IsState(Asset.States.AddedLocal)) + { + Overlay.DrawOverlay(Asset.States.CheckedOutLocal, iconRect); + } + if (Overlay.IsState(Asset.States.CheckedOutRemote) && !Overlay.IsState(Asset.States.LockedRemote) && !Overlay.IsState(Asset.States.AddedRemote)) + { + Overlay.DrawOverlay(Asset.States.CheckedOutRemote, iconRect2); + } + if (Overlay.IsState(Asset.States.DeletedLocal)) + { + Overlay.DrawOverlay(Asset.States.DeletedLocal, iconRect); + } + if (Overlay.IsState(Asset.States.DeletedRemote)) + { + Overlay.DrawOverlay(Asset.States.DeletedRemote, iconRect2); + } + if (Overlay.IsState(Asset.States.Local) && !Overlay.IsState(Asset.States.OutOfSync) && !Overlay.IsState(Asset.States.Synced) && !Overlay.IsState(Asset.States.AddedLocal)) + { + Overlay.DrawOverlay(Asset.States.Local, iconRect3); + } + if (Overlay.IsState(Asset.States.LockedLocal)) + { + Overlay.DrawOverlay(Asset.States.LockedLocal, iconRect); + } + if (Overlay.IsState(Asset.States.LockedRemote)) + { + Overlay.DrawOverlay(Asset.States.LockedRemote, iconRect2); + } + if (Overlay.IsState(Asset.States.OutOfSync)) + { + Overlay.DrawOverlay(Asset.States.OutOfSync, iconRect4); + } + if (Overlay.IsState(Asset.States.Conflicted)) + { + Overlay.DrawOverlay(Asset.States.Conflicted, iconRect3); + } + } + private static bool IsState(Asset.States state) + { + return Overlay.m_Asset.IsState(state); + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs b/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs new file mode 100644 index 00000000..2006fc6c --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs @@ -0,0 +1,92 @@ +using System; +using UnityEditor; +using UnityEditor.VersionControl; +namespace UnityEditorInternal.VersionControl +{ + public class PendingWindowContextMenu + { + private static bool SubmitTest(int userData) + { + return Provider.SubmitIsValid(null, ListControl.FromID(userData).SelectedAssets); + } + private static void Submit(int userData) + { + WindowChange.Open(ListControl.FromID(userData).SelectedAssets, true); + } + private static bool RevertTest(int userData) + { + return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Normal); + } + private static void Revert(int userData) + { + WindowRevert.Open(ListControl.FromID(userData).SelectedAssets); + } + private static bool RevertUnchangedTest(int userData) + { + return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Normal); + } + private static void RevertUnchanged(int userData) + { + AssetList selectedAssets = ListControl.FromID(userData).SelectedAssets; + Provider.Revert(selectedAssets, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool ResolveTest(int userData) + { + return Provider.ResolveIsValid(ListControl.FromID(userData).SelectedAssets); + } + private static void Resolve(int userData) + { + WindowResolve.Open(ListControl.FromID(userData).SelectedAssets); + } + private static bool LockTest(int userData) + { + return Provider.LockIsValid(ListControl.FromID(userData).SelectedAssets); + } + private static void Lock(int userData) + { + AssetList selectedAssets = ListControl.FromID(userData).SelectedAssets; + Provider.Lock(selectedAssets, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool UnlockTest(int userData) + { + return Provider.UnlockIsValid(ListControl.FromID(userData).SelectedAssets); + } + private static void Unlock(int userData) + { + AssetList selectedAssets = ListControl.FromID(userData).SelectedAssets; + Provider.Lock(selectedAssets, false).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool DiffHeadTest(int userData) + { + return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); + } + private static void DiffHead(int userData) + { + Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, false); + } + private static bool DiffHeadWithMetaTest(int userData) + { + return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); + } + private static void DiffHeadWithMeta(int userData) + { + Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, true); + } + private static bool ShowInExplorerTest(int userData) + { + return ListControl.FromID(userData).SelectedAssets.Count > 0; + } + private static void ShowInExplorer(int userDatad) + { + EditorApplication.ExecuteMenuItem("Assets/Show in Explorer"); + } + private static bool NewChangeSetTest(int userData) + { + return Provider.isActive; + } + private static void NewChangeSet(int userData) + { + WindowChange.Open(ListControl.FromID(userData).SelectedAssets, false); + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ProjectContextMenu.cs b/UnityEditor/UnityEditorInternal.VersionControl/ProjectContextMenu.cs new file mode 100644 index 00000000..55005c25 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/ProjectContextMenu.cs @@ -0,0 +1,119 @@ +using System; +using UnityEditor; +using UnityEditor.VersionControl; +namespace UnityEditorInternal.VersionControl +{ + public class ProjectContextMenu + { + private static bool GetLatestTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.GetLatestIsValid(assetListFromSelection); + } + private static void GetLatest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.GetLatest(assetListFromSelection).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool SubmitTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.SubmitIsValid(null, assetListFromSelection); + } + private static void Submit(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + WindowChange.Open(assetListFromSelection, true); + } + private static bool CheckOutTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.CheckoutIsValid(assetListFromSelection); + } + private static void CheckOut(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.Checkout(assetListFromSelection, CheckoutMode.Both).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool MarkAddTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.AddIsValid(assetListFromSelection); + } + private static void MarkAdd(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.Add(assetListFromSelection, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool RevertTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.RevertIsValid(assetListFromSelection, RevertMode.Normal); + } + private static void Revert(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + WindowRevert.Open(assetListFromSelection); + } + private static bool RevertUnchangedTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.RevertIsValid(assetListFromSelection, RevertMode.Normal); + } + private static void RevertUnchanged(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.Revert(assetListFromSelection, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool ResolveTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.ResolveIsValid(assetListFromSelection); + } + private static void Resolve(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + WindowResolve.Open(assetListFromSelection); + } + private static bool LockTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.LockIsValid(assetListFromSelection); + } + private static void Lock(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.Lock(assetListFromSelection, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool UnlockTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.UnlockIsValid(assetListFromSelection); + } + private static void Unlock(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.Lock(assetListFromSelection, false).SetCompletionAction(CompletionAction.UpdatePendingWindow); + } + private static bool DiffHeadTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.DiffIsValid(assetListFromSelection); + } + private static void DiffHead(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.DiffHead(assetListFromSelection, false); + } + private static bool DiffHeadWithMetaTest(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + return Provider.enabled && Provider.DiffIsValid(assetListFromSelection); + } + private static void DiffHeadWithMeta(MenuCommand cmd) + { + AssetList assetListFromSelection = Provider.GetAssetListFromSelection(); + Provider.DiffHead(assetListFromSelection, true); + } + } +} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ProjectHooks.cs b/UnityEditor/UnityEditorInternal.VersionControl/ProjectHooks.cs new file mode 100644 index 00000000..787129b3 --- /dev/null +++ b/UnityEditor/UnityEditorInternal.VersionControl/ProjectHooks.cs @@ -0,0 +1,21 @@ +using System; +using UnityEditor.VersionControl; +using UnityEngine; +namespace UnityEditorInternal.VersionControl +{ + internal class ProjectHooks + { + public static void OnProjectWindowItem(string guid, Rect drawRect) + { + if (!Provider.isActive) + { + return; + } + Overlay.DrawOverlay(Provider.GetAssetByGUID(guid), drawRect); + } + public static Rect GetOverlayRect(Rect drawRect) + { + return Overlay.GetOverlayRect(drawRect); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopup.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopup.cs new file mode 100644 index 00000000..56dc2be7 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopup.cs @@ -0,0 +1,90 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AddCurvesPopup : EditorWindow + { + private const float k_WindowPadding = 3f; + internal static AnimationWindowState s_State; + private static AddCurvesPopup s_AddCurvesPopup; + private static long s_LastClosedTime; + private static AddCurvesPopupHierarchy s_Hierarchy; + private static Vector2 windowSize = new Vector2(240f, 250f); + internal static UnityEngine.Object animatableObject + { + get; + set; + } + internal static GameObject gameObject + { + get; + set; + } + internal static string path + { + get + { + return AnimationUtility.CalculateTransformPath(AddCurvesPopup.gameObject.transform, AddCurvesPopup.s_State.m_RootGameObject.transform); + } + } + private void Init(Rect buttonRect) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + base.ShowAsDropDown(buttonRect, AddCurvesPopup.windowSize, new PopupLocationHelper.PopupLocation[] + { + PopupLocationHelper.PopupLocation.Right + }); + } + private void OnDisable() + { + AddCurvesPopup.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + AddCurvesPopup.s_AddCurvesPopup = null; + AddCurvesPopup.s_Hierarchy = null; + } + internal static void AddNewCurve(AddCurvesPopupPropertyNode node) + { + if (!AnimationWindow.EnsureAllHaveClips()) + { + return; + } + AnimationWindowUtility.CreateDefaultCurves(AddCurvesPopup.s_State, node.curveBindings); + TreeViewItem treeViewItem = (!(node.parent.displayName == "GameObject")) ? node.parent.parent : node.parent; + AddCurvesPopup.s_State.m_hierarchyState.selectedIDs.Clear(); + AddCurvesPopup.s_State.m_hierarchyState.selectedIDs.Add(treeViewItem.id); + AddCurvesPopup.s_State.m_HierarchyData.SetExpanded(treeViewItem, true); + AddCurvesPopup.s_State.m_HierarchyData.SetExpanded(node.parent.id, true); + AddCurvesPopup.s_State.m_CurveEditorIsDirty = true; + } + internal static bool ShowAtPosition(Rect buttonRect, AnimationWindowState state) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= AddCurvesPopup.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (AddCurvesPopup.s_AddCurvesPopup == null) + { + AddCurvesPopup.s_AddCurvesPopup = ScriptableObject.CreateInstance(); + } + AddCurvesPopup.s_State = state; + AddCurvesPopup.s_AddCurvesPopup.Init(buttonRect); + return true; + } + return false; + } + internal void OnGUI() + { + if (Event.current.type == EventType.Layout) + { + return; + } + if (AddCurvesPopup.s_Hierarchy == null) + { + AddCurvesPopup.s_Hierarchy = new AddCurvesPopupHierarchy(AddCurvesPopup.s_State); + } + Rect position = new Rect(1f, 1f, AddCurvesPopup.windowSize.x - 3f, AddCurvesPopup.windowSize.y - 3f); + GUI.Box(new Rect(0f, 0f, AddCurvesPopup.windowSize.x, AddCurvesPopup.windowSize.y), GUIContent.none, new GUIStyle("grey_border")); + AddCurvesPopup.s_Hierarchy.OnGUI(position, this); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupGameObjectNode.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupGameObjectNode.cs new file mode 100644 index 00000000..1b9937a4 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupGameObjectNode.cs @@ -0,0 +1,12 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupGameObjectNode : TreeViewItem + { + public AddCurvesPopupGameObjectNode(GameObject gameObject, TreeViewItem parent, string displayName) : base(gameObject.GetInstanceID(), (parent == null) ? -1 : (parent.depth + 1), parent, displayName) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs new file mode 100644 index 00000000..718082ce --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs @@ -0,0 +1,45 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupHierarchy + { + private TreeView m_TreeView; + private TreeViewState m_TreeViewState; + private AddCurvesPopupHierarchyDataSource m_TreeViewDataSource; + private AnimationWindowState state + { + get; + set; + } + public AddCurvesPopupHierarchy(AnimationWindowState state) + { + this.state = state; + } + public void OnGUI(Rect position, EditorWindow owner) + { + this.InitIfNeeded(owner, position); + this.m_TreeView.OnEvent(); + this.m_TreeView.OnGUI(position, GUIUtility.GetControlID(FocusType.Keyboard)); + } + public void InitIfNeeded(EditorWindow owner, Rect rect) + { + if (this.m_TreeViewState == null) + { + this.m_TreeViewState = new TreeViewState(); + this.m_TreeView = new TreeView(owner, this.m_TreeViewState); + this.m_TreeView.deselectOnUnhandledMouseDown = true; + this.m_TreeViewDataSource = new AddCurvesPopupHierarchyDataSource(this.m_TreeView, this.state); + TreeViewGUI gui = new AddCurvesPopupHierarchyGUI(this.m_TreeView, this.state, owner); + this.m_TreeView.Init(rect, this.m_TreeViewDataSource, gui, new AssetOrGameObjectTreeViewDragging(this.m_TreeView, HierarchyType.GameObjects)); + this.m_TreeViewDataSource.UpdateData(); + return; + } + } + internal virtual bool IsRenamingNodeAllowed(TreeViewItem node) + { + return false; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyDataSource.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyDataSource.cs new file mode 100644 index 00000000..8277079a --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyDataSource.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupHierarchyDataSource : TreeViewDataSource + { + private AnimationWindowState state + { + get; + set; + } + public static bool showEntireHierarchy + { + get; + set; + } + public AddCurvesPopupHierarchyDataSource(TreeView treeView, AnimationWindowState animationWindowState) : base(treeView) + { + base.showRootNode = false; + base.rootIsCollapsable = false; + this.state = animationWindowState; + } + private void SetupRootNodeSettings() + { + base.showRootNode = false; + this.SetExpanded(this.root, true); + } + public override void FetchData() + { + if (AddCurvesPopup.gameObject == null) + { + return; + } + this.AddGameObjectToHierarchy(AddCurvesPopup.gameObject, null); + this.SetupRootNodeSettings(); + this.m_NeedRefreshVisibleFolders = true; + } + private TreeViewItem AddGameObjectToHierarchy(GameObject gameObject, TreeViewItem parent) + { + string path = AnimationUtility.CalculateTransformPath(gameObject.transform, this.state.m_RootGameObject.transform); + TreeViewItem treeViewItem = new AddCurvesPopupGameObjectNode(gameObject, parent, gameObject.name); + List list = new List(); + if (parent == null) + { + this.m_RootItem = treeViewItem; + } + EditorCurveBinding[] animatableBindings = AnimationUtility.GetAnimatableBindings(gameObject, this.state.m_RootGameObject); + List list2 = new List(); + for (int i = 0; i < animatableBindings.Length; i++) + { + EditorCurveBinding editorCurveBinding = animatableBindings[i]; + list2.Add(editorCurveBinding); + if (editorCurveBinding.propertyName == "m_IsActive") + { + if (editorCurveBinding.path != string.Empty) + { + TreeViewItem treeViewItem2 = this.CreateNode(list2.ToArray(), treeViewItem); + if (treeViewItem2 != null) + { + list.Add(treeViewItem2); + } + list2.Clear(); + } + else + { + list2.Clear(); + } + } + else + { + bool flag = i == animatableBindings.Length - 1; + bool flag2 = false; + if (!flag) + { + flag2 = (animatableBindings[i + 1].type != editorCurveBinding.type); + } + if (AnimationWindowUtility.IsCurveCreated(this.state.m_ActiveAnimationClip, editorCurveBinding)) + { + list2.Remove(editorCurveBinding); + } + if ((flag || flag2) && list2.Count > 0) + { + list.Add(this.AddAnimatableObjectToHierarchy(this.state.m_RootGameObject, list2.ToArray(), treeViewItem, path)); + list2.Clear(); + } + } + } + if (AddCurvesPopupHierarchyDataSource.showEntireHierarchy) + { + for (int j = 0; j < gameObject.transform.childCount; j++) + { + Transform child = gameObject.transform.GetChild(j); + TreeViewItem treeViewItem3 = this.AddGameObjectToHierarchy(child.gameObject, treeViewItem); + if (treeViewItem3 != null) + { + list.Add(treeViewItem3); + } + } + } + TreeViewUtility.SetChildParentReferences(list, treeViewItem); + return treeViewItem; + } + private static string GetClassName(GameObject root, EditorCurveBinding binding) + { + UnityEngine.Object animatedObject = AnimationUtility.GetAnimatedObject(root, binding); + if (animatedObject) + { + return ObjectNames.GetInspectorTitle(animatedObject); + } + return binding.type.Name; + } + private TreeViewItem AddAnimatableObjectToHierarchy(GameObject root, EditorCurveBinding[] curveBindings, TreeViewItem parentNode, string path) + { + TreeViewItem treeViewItem = new AddCurvesPopupObjectNode(parentNode, path, AddCurvesPopupHierarchyDataSource.GetClassName(root, curveBindings[0])); + treeViewItem.icon = AssetPreview.GetMiniThumbnail(AnimationUtility.GetAnimatedObject(root, curveBindings[0])); + List list = new List(); + List list2 = new List(); + for (int i = 0; i < curveBindings.Length; i++) + { + EditorCurveBinding item = curveBindings[i]; + list2.Add(item); + if (i == curveBindings.Length - 1 || AnimationWindowUtility.GetPropertyGroupName(curveBindings[i + 1].propertyName) != AnimationWindowUtility.GetPropertyGroupName(item.propertyName)) + { + TreeViewItem treeViewItem2 = this.CreateNode(list2.ToArray(), treeViewItem); + if (treeViewItem2 != null) + { + list.Add(treeViewItem2); + } + list2.Clear(); + } + } + list.Sort(); + TreeViewUtility.SetChildParentReferences(list, treeViewItem); + return treeViewItem; + } + private TreeViewItem CreateNode(EditorCurveBinding[] curveBindings, TreeViewItem parentNode) + { + AddCurvesPopupPropertyNode addCurvesPopupPropertyNode = new AddCurvesPopupPropertyNode(parentNode, curveBindings); + if (AnimationWindowUtility.IsRectTransformPosition(addCurvesPopupPropertyNode.curveBindings[0])) + { + addCurvesPopupPropertyNode.curveBindings = new EditorCurveBinding[] + { + addCurvesPopupPropertyNode.curveBindings[2] + }; + } + addCurvesPopupPropertyNode.icon = parentNode.icon; + return addCurvesPopupPropertyNode; + } + public void UpdateData() + { + this.m_TreeView.ReloadData(); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs new file mode 100644 index 00000000..36109c11 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs @@ -0,0 +1,60 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupHierarchyGUI : TreeViewGUI + { + private const float plusButtonWidth = 17f; + public EditorWindow owner; + private GUIStyle plusButtonStyle = new GUIStyle("OL Plus"); + private GUIStyle plusButtonBackgroundStyle = new GUIStyle("Tag MenuItem"); + public AnimationWindowState state + { + get; + set; + } + public bool showPlusButton + { + get; + set; + } + public AddCurvesPopupHierarchyGUI(TreeView treeView, AnimationWindowState state, EditorWindow owner) : base(treeView) + { + this.owner = owner; + this.state = state; + } + public override Rect OnRowGUI(TreeViewItem node, int row, float rowWidth, bool selected, bool focused) + { + Rect result = base.OnRowGUI(node, row, rowWidth, selected, focused); + Rect position = new Rect(rowWidth - 17f, result.yMin, 17f, this.plusButtonStyle.fixedHeight); + AddCurvesPopupPropertyNode addCurvesPopupPropertyNode = node as AddCurvesPopupPropertyNode; + if (addCurvesPopupPropertyNode == null || addCurvesPopupPropertyNode.curveBindings == null || addCurvesPopupPropertyNode.curveBindings.Length == 0) + { + return result; + } + GUI.Box(position, GUIContent.none, this.plusButtonBackgroundStyle); + if (GUI.Button(position, GUIContent.none, this.plusButtonStyle)) + { + AddCurvesPopup.AddNewCurve(addCurvesPopupPropertyNode); + this.owner.Close(); + this.m_TreeView.ReloadData(); + } + return result; + } + protected override void SyncFakeItem() + { + } + protected override void RenameEnded() + { + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item != null) + { + return item.icon; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupObjectNode.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupObjectNode.cs new file mode 100644 index 00000000..298f0c9c --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupObjectNode.cs @@ -0,0 +1,11 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupObjectNode : TreeViewItem + { + public AddCurvesPopupObjectNode(TreeViewItem parent, string path, string className) : base((path + className).GetHashCode(), parent.depth + 1, parent, className) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupPropertyNode.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupPropertyNode.cs new file mode 100644 index 00000000..53763f87 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupPropertyNode.cs @@ -0,0 +1,28 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class AddCurvesPopupPropertyNode : TreeViewItem + { + public EditorCurveBinding[] curveBindings; + public AddCurvesPopupPropertyNode(TreeViewItem parent, EditorCurveBinding[] curveBindings) : base(curveBindings[0].GetHashCode(), parent.depth + 1, parent, AnimationWindowUtility.NicifyPropertyGroupName(curveBindings[0].type, AnimationWindowUtility.GetPropertyGroupName(curveBindings[0].propertyName))) + { + this.curveBindings = curveBindings; + } + public override int CompareTo(TreeViewItem other) + { + if (other is AddCurvesPopupPropertyNode) + { + if (this.displayName.Contains("Rotation") && other.displayName.Contains("Position")) + { + return 1; + } + if (this.displayName.Contains("Position") && other.displayName.Contains("Rotation")) + { + return -1; + } + } + return base.CompareTo(other); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationCurvePreviewCache.cs b/UnityEditor/UnityEditorInternal/AnimationCurvePreviewCache.cs new file mode 100644 index 00000000..4747bcea --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationCurvePreviewCache.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class AnimationCurvePreviewCache + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearCache(); + public static Texture2D GetPropertyPreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, Color color) + { + return AnimationCurvePreviewCache.INTERNAL_CALL_GetPropertyPreview(previewWidth, previewHeight, useCurveRanges, ref curveRanges, property, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D INTERNAL_CALL_GetPropertyPreview(int previewWidth, int previewHeight, bool useCurveRanges, ref Rect curveRanges, SerializedProperty property, ref Color color); + public static Texture2D GetPropertyPreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, SerializedProperty property2, Color color) + { + return AnimationCurvePreviewCache.INTERNAL_CALL_GetPropertyPreviewRegion(previewWidth, previewHeight, useCurveRanges, ref curveRanges, property, property2, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D INTERNAL_CALL_GetPropertyPreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, ref Rect curveRanges, SerializedProperty property, SerializedProperty property2, ref Color color); + public static Texture2D GetCurvePreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, Color color) + { + return AnimationCurvePreviewCache.INTERNAL_CALL_GetCurvePreview(previewWidth, previewHeight, useCurveRanges, ref curveRanges, curve, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D INTERNAL_CALL_GetCurvePreview(int previewWidth, int previewHeight, bool useCurveRanges, ref Rect curveRanges, AnimationCurve curve, ref Color color); + public static Texture2D GetCurvePreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, Color color) + { + return AnimationCurvePreviewCache.INTERNAL_CALL_GetCurvePreviewRegion(previewWidth, previewHeight, useCurveRanges, ref curveRanges, curve, curve2, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D INTERNAL_CALL_GetCurvePreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, ref Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, ref Color color); + public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Rect curveRanges) + { + if (property2 == null) + { + return AnimationCurvePreviewCache.GetPropertyPreview(previewWidth, previewHeight, true, curveRanges, property, color); + } + return AnimationCurvePreviewCache.GetPropertyPreviewRegion(previewWidth, previewHeight, true, curveRanges, property, property2, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color) + { + if (property2 == null) + { + return AnimationCurvePreviewCache.GetPropertyPreview(previewWidth, previewHeight, false, default(Rect), property, color); + } + return AnimationCurvePreviewCache.GetPropertyPreviewRegion(previewWidth, previewHeight, false, default(Rect), property, property2, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Rect curveRanges) + { + return AnimationCurvePreviewCache.GetCurvePreviewRegion(previewWidth, previewHeight, true, curveRanges, curve, curve2, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color) + { + return AnimationCurvePreviewCache.GetCurvePreviewRegion(previewWidth, previewHeight, false, default(Rect), curve, curve2, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Rect curveRanges) + { + return AnimationCurvePreviewCache.GetPropertyPreview(previewWidth, previewHeight, true, curveRanges, property, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color) + { + return AnimationCurvePreviewCache.GetPropertyPreview(previewWidth, previewHeight, false, default(Rect), property, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Rect curveRanges) + { + return AnimationCurvePreviewCache.GetCurvePreview(previewWidth, previewHeight, true, curveRanges, curve, color); + } + public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color) + { + return AnimationCurvePreviewCache.GetCurvePreview(previewWidth, previewHeight, false, default(Rect), curve, color); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationKeyTime.cs b/UnityEditor/UnityEditorInternal/AnimationKeyTime.cs new file mode 100644 index 00000000..b4733553 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationKeyTime.cs @@ -0,0 +1,68 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + internal struct AnimationKeyTime + { + private float m_FrameRate; + private int m_Frame; + private float m_Time; + public float time + { + get + { + return this.m_Time; + } + } + public int frame + { + get + { + return this.m_Frame; + } + } + public float frameRate + { + get + { + return this.m_FrameRate; + } + } + public float frameFloor + { + get + { + return ((float)this.frame - 0.5f) / this.frameRate; + } + } + public float frameCeiling + { + get + { + return ((float)this.frame + 0.5f) / this.frameRate; + } + } + public static AnimationKeyTime Time(float time, float frameRate) + { + return new AnimationKeyTime + { + m_Time = time, + m_FrameRate = frameRate, + m_Frame = Mathf.RoundToInt(time * frameRate) + }; + } + public static AnimationKeyTime Frame(int frame, float frameRate) + { + return new AnimationKeyTime + { + m_Time = (float)frame / frameRate, + m_FrameRate = frameRate, + m_Frame = frame + }; + } + public bool ContainsTime(float time) + { + return time >= this.frameFloor && time < this.frameCeiling; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationRecording.cs b/UnityEditor/UnityEditorInternal/AnimationRecording.cs new file mode 100644 index 00000000..9f8489a2 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationRecording.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationRecording + { + private static bool HasAnyRecordableModifications(GameObject root, UndoPropertyModification[] modifications) + { + for (int i = 0; i < modifications.Length; i++) + { + EditorCurveBinding editorCurveBinding; + if (AnimationUtility.PropertyModificationToEditorCurveBinding(modifications[i].propertyModification, root, out editorCurveBinding) != null) + { + return true; + } + } + return false; + } + private static PropertyModification FindPropertyModification(GameObject root, UndoPropertyModification[] modifications, EditorCurveBinding binding) + { + for (int i = 0; i < modifications.Length; i++) + { + EditorCurveBinding lhs; + AnimationUtility.PropertyModificationToEditorCurveBinding(modifications[i].propertyModification, root, out lhs); + if (lhs == binding) + { + return modifications[i].propertyModification; + } + } + return null; + } + public static UndoPropertyModification[] Process(AnimationWindowState state, UndoPropertyModification[] modifications) + { + GameObject rootGameObject = state.m_RootGameObject; + AnimationClip activeAnimationClip = state.m_ActiveAnimationClip; + Animator component = rootGameObject.GetComponent(); + if (!AnimationRecording.HasAnyRecordableModifications(rootGameObject, modifications)) + { + return modifications; + } + List list = new List(); + for (int i = 0; i < modifications.Length; i++) + { + EditorCurveBinding binding = default(EditorCurveBinding); + PropertyModification propertyModification = modifications[i].propertyModification; + Type type = AnimationUtility.PropertyModificationToEditorCurveBinding(propertyModification, rootGameObject, out binding); + if (type != null) + { + if (component != null && component.isHuman && binding.type == typeof(Transform) && component.IsBoneTransform(propertyModification.target as Transform)) + { + Debug.LogWarning("Keyframing for humanoid rig is not supported!", propertyModification.target as Transform); + } + else + { + AnimationMode.AddPropertyModification(binding, propertyModification, modifications[i].keepPrefabOverride); + EditorCurveBinding[] array = RotationCurveInterpolation.RemapAnimationBindingForAddKey(binding, activeAnimationClip); + if (array != null) + { + for (int j = 0; j < array.Length; j++) + { + AnimationRecording.AddKey(state, array[j], type, AnimationRecording.FindPropertyModification(rootGameObject, modifications, array[j])); + } + } + else + { + AnimationRecording.AddKey(state, binding, type, propertyModification); + } + } + } + else + { + list.Add(modifications[i]); + } + } + return list.ToArray(); + } + private static bool ValueFromPropertyModification(PropertyModification modification, EditorCurveBinding binding, out object outObject) + { + if (modification == null) + { + outObject = null; + return false; + } + if (binding.isPPtrCurve) + { + outObject = modification.objectReference; + return true; + } + float num; + if (float.TryParse(modification.value, out num)) + { + outObject = num; + return true; + } + outObject = null; + return false; + } + private static void AddKey(AnimationWindowState state, EditorCurveBinding binding, Type type, PropertyModification modification) + { + GameObject rootGameObject = state.m_RootGameObject; + AnimationClip activeAnimationClip = state.m_ActiveAnimationClip; + AnimationWindowCurve animationWindowCurve = new AnimationWindowCurve(activeAnimationClip, binding, type); + object currentValue = AnimationWindowUtility.GetCurrentValue(rootGameObject, binding); + object value = null; + if (animationWindowCurve.length == 0 && state.m_Frame != 0) + { + if (!AnimationRecording.ValueFromPropertyModification(modification, binding, out value)) + { + value = currentValue; + } + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, value, type, AnimationKeyTime.Frame(0, activeAnimationClip.frameRate)); + } + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, currentValue, type, AnimationKeyTime.Frame(state.m_Frame, activeAnimationClip.frameRate)); + state.SaveCurve(animationWindowCurve); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowCurve.cs b/UnityEditor/UnityEditorInternal/AnimationWindowCurve.cs new file mode 100644 index 00000000..90a7b7b7 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowCurve.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowCurve : IComparable + { + public const float timeEpsilon = 1E-05f; + public List m_Keyframes; + public Type m_ValueType; + private EditorCurveBinding m_Binding; + public EditorCurveBinding binding + { + get + { + return this.m_Binding; + } + } + public bool isPPtrCurve + { + get + { + return this.m_Binding.isPPtrCurve; + } + } + public string propertyName + { + get + { + return this.m_Binding.propertyName; + } + } + public string path + { + get + { + return this.m_Binding.path; + } + } + public Type type + { + get + { + return this.m_Binding.type; + } + } + public int length + { + get + { + return this.m_Keyframes.Count; + } + } + public int depth + { + get + { + return (this.path.Length <= 0) ? 0 : this.path.Split(new char[] + { + '/' + }).Length; + } + } + public AnimationWindowCurve(AnimationClip clip, EditorCurveBinding binding, Type valueType) + { + binding = RotationCurveInterpolation.RemapAnimationBindingForRotationCurves(binding, clip); + this.m_Binding = binding; + this.m_ValueType = valueType; + this.LoadKeyframes(clip); + } + public void LoadKeyframes(AnimationClip clip) + { + this.m_Keyframes = new List(); + if (!this.m_Binding.isPPtrCurve) + { + AnimationCurve editorCurve = AnimationUtility.GetEditorCurve(clip, this.binding); + int num = 0; + while (editorCurve != null && num < editorCurve.length) + { + this.m_Keyframes.Add(new AnimationWindowKeyframe(this, editorCurve[num])); + num++; + } + } + else + { + ObjectReferenceKeyframe[] objectReferenceCurve = AnimationUtility.GetObjectReferenceCurve(clip, this.binding); + int num2 = 0; + while (objectReferenceCurve != null && num2 < objectReferenceCurve.Length) + { + this.m_Keyframes.Add(new AnimationWindowKeyframe(this, objectReferenceCurve[num2])); + num2++; + } + } + } + public override int GetHashCode() + { + return this.m_Binding.GetHashCode(); + } + public int CompareTo(AnimationWindowCurve obj) + { + bool flag = this.path.Equals(obj.path); + if (!flag && this.depth != obj.depth) + { + return (this.depth >= obj.depth) ? 1 : -1; + } + bool flag2 = this.type == typeof(Transform) && obj.type == typeof(Transform) && flag; + bool flag3 = (this.type == typeof(Transform) || obj.type == typeof(Transform)) && flag; + if (flag2) + { + string nicePropertyGroupDisplayName = AnimationWindowUtility.GetNicePropertyGroupDisplayName(typeof(Transform), AnimationWindowUtility.GetPropertyGroupName(this.propertyName)); + string nicePropertyGroupDisplayName2 = AnimationWindowUtility.GetNicePropertyGroupDisplayName(typeof(Transform), AnimationWindowUtility.GetPropertyGroupName(obj.propertyName)); + if (nicePropertyGroupDisplayName.Contains("Position") && nicePropertyGroupDisplayName2.Contains("Rotation")) + { + return -1; + } + if (nicePropertyGroupDisplayName.Contains("Rotation") && nicePropertyGroupDisplayName2.Contains("Position")) + { + return 1; + } + } + else + { + if (flag3) + { + if (this.type == typeof(Transform)) + { + return -1; + } + return 1; + } + else + { + if (this.path == obj.path && obj.type == this.type) + { + int componentIndex = AnimationWindowUtility.GetComponentIndex(obj.propertyName); + int componentIndex2 = AnimationWindowUtility.GetComponentIndex(this.propertyName); + if (componentIndex != -1 && componentIndex2 != -1 && this.propertyName.Substring(0, this.propertyName.Length - 2) == obj.propertyName.Substring(0, obj.propertyName.Length - 2)) + { + return componentIndex2 - componentIndex; + } + } + } + } + return (this.path + this.type + this.propertyName).CompareTo(obj.path + obj.type + obj.propertyName); + } + public AnimationCurve ToAnimationCurve() + { + int count = this.m_Keyframes.Count; + AnimationCurve animationCurve = new AnimationCurve(); + List list = new List(); + float num = -3.40282347E+38f; + for (int i = 0; i < count; i++) + { + if (Mathf.Abs(this.m_Keyframes[i].time - num) > 1E-05f) + { + list.Add(new Keyframe(this.m_Keyframes[i].time, (float)this.m_Keyframes[i].value, this.m_Keyframes[i].m_InTangent, this.m_Keyframes[i].m_OutTangent) + { + tangentMode = this.m_Keyframes[i].m_TangentMode + }); + num = this.m_Keyframes[i].time; + } + } + animationCurve.keys = list.ToArray(); + return animationCurve; + } + public ObjectReferenceKeyframe[] ToObjectCurve() + { + int count = this.m_Keyframes.Count; + List list = new List(); + float num = -3.40282347E+38f; + for (int i = 0; i < count; i++) + { + if (Mathf.Abs(this.m_Keyframes[i].time - num) > 1E-05f) + { + ObjectReferenceKeyframe item = default(ObjectReferenceKeyframe); + item.time = this.m_Keyframes[i].time; + item.value = (UnityEngine.Object)this.m_Keyframes[i].value; + num = item.time; + list.Add(item); + } + } + return list.ToArray(); + } + public AnimationWindowKeyframe FindKeyAtTime(AnimationKeyTime keyTime) + { + int keyframeIndex = this.GetKeyframeIndex(keyTime); + if (keyframeIndex == -1) + { + return null; + } + return this.m_Keyframes[keyframeIndex]; + } + public void AddKeyframe(AnimationWindowKeyframe key, AnimationKeyTime keyTime) + { + this.RemoveKeyframe(keyTime); + this.m_Keyframes.Add(key); + this.m_Keyframes.Sort((AnimationWindowKeyframe a, AnimationWindowKeyframe b) => a.time.CompareTo(b.time)); + } + public void RemoveKeyframe(AnimationKeyTime time) + { + for (int i = this.m_Keyframes.Count - 1; i >= 0; i--) + { + if (time.ContainsTime(this.m_Keyframes[i].time)) + { + this.m_Keyframes.RemoveAt(i); + } + } + } + public bool HasKeyframe(AnimationKeyTime time) + { + return this.GetKeyframeIndex(time) != -1; + } + public int GetKeyframeIndex(AnimationKeyTime time) + { + for (int i = 0; i < this.m_Keyframes.Count; i++) + { + if (time.ContainsTime(this.m_Keyframes[i].time)) + { + return i; + } + } + return -1; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchy.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchy.cs new file mode 100644 index 00000000..aa3cab51 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchy.cs @@ -0,0 +1,47 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchy + { + private TreeView m_TreeView; + public AnimationWindowState state + { + get; + set; + } + public AnimationWindowHierarchy(AnimationWindowState state, EditorWindow owner, Rect position) + { + this.state = state; + this.Init(owner, position); + } + public void OnGUI(Rect position, EditorWindow owner) + { + this.m_TreeView.OnEvent(); + this.m_TreeView.OnGUI(position, GUIUtility.GetControlID(FocusType.Keyboard)); + } + public void Init(EditorWindow owner, Rect rect) + { + if (this.state.m_hierarchyState == null) + { + this.state.m_hierarchyState = new AnimationWindowHierarchyState(); + } + this.m_TreeView = new TreeView(owner, this.state.m_hierarchyState); + this.state.m_HierarchyData = new AnimationWindowHierarchyDataSource(this.m_TreeView, this.state); + this.m_TreeView.Init(rect, this.state.m_HierarchyData, new AnimationWindowHierarchyGUI(this.m_TreeView, this.state), new AnimationWindowHierarchyDragging()); + this.m_TreeView.deselectOnUnhandledMouseDown = true; + TreeView expr_92 = this.m_TreeView; + expr_92.selectionChangedCallback = (Action)Delegate.Combine(expr_92.selectionChangedCallback, new Action(this.state.OnHierarchySelectionChanged)); + this.m_TreeView.ReloadData(); + } + internal virtual bool IsRenamingNodeAllowed(TreeViewItem node) + { + return true; + } + public bool IsIDVisible(int id) + { + return this.m_TreeView != null && this.m_TreeView.IsVisible(id); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyAddButtonNode.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyAddButtonNode.cs new file mode 100644 index 00000000..d0456a5c --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyAddButtonNode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyAddButtonNode : AnimationWindowHierarchyNode + { + public AnimationWindowHierarchyAddButtonNode() : base(0, -1, null, null, null, null, string.Empty) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDataSource.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDataSource.cs new file mode 100644 index 00000000..075b60f4 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDataSource.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyDataSource : TreeViewDataSource + { + private AnimationWindowState state + { + get; + set; + } + public bool showAll + { + get; + set; + } + public AnimationWindowHierarchyDataSource(TreeView treeView, AnimationWindowState animationWindowState) : base(treeView) + { + this.state = animationWindowState; + } + private void SetupRootNodeSettings() + { + base.showRootNode = false; + base.rootIsCollapsable = false; + this.SetExpanded(this.m_RootItem, true); + } + private AnimationWindowHierarchyNode GetEmptyRootNode() + { + return new AnimationWindowHierarchyNode(0, -1, null, null, string.Empty, string.Empty, "root"); + } + public override void FetchData() + { + this.m_RootItem = this.GetEmptyRootNode(); + this.SetupRootNodeSettings(); + if (this.state.m_ActiveGameObject == null || this.state.m_RootGameObject == null) + { + return; + } + List list = new List(); + if (this.state.allCurves.Count > 0) + { + list.Add(new AnimationWindowHierarchyMasterNode()); + } + list.AddRange(this.CreateTreeFromCurves()); + list.Add(new AnimationWindowHierarchyAddButtonNode()); + TreeViewUtility.SetChildParentReferences(new List(list.ToArray()), this.root); + this.m_NeedRefreshVisibleFolders = true; + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return !(item is AnimationWindowHierarchyAddButtonNode) && !(item is AnimationWindowHierarchyMasterNode) && (item as AnimationWindowHierarchyNode).path.Length != 0; + } + public List CreateTreeFromCurves() + { + List list = new List(); + List list2 = new List(); + AnimationWindowCurve[] array = this.state.allCurves.ToArray(); + for (int i = 0; i < array.Length; i++) + { + AnimationWindowCurve animationWindowCurve = array[i]; + AnimationWindowCurve animationWindowCurve2 = (i >= array.Length - 1) ? null : array[i + 1]; + list2.Add(animationWindowCurve); + bool flag = animationWindowCurve2 != null && AnimationWindowUtility.GetPropertyGroupName(animationWindowCurve2.propertyName) == AnimationWindowUtility.GetPropertyGroupName(animationWindowCurve.propertyName); + bool flag2 = animationWindowCurve2 != null && animationWindowCurve.path.Equals(animationWindowCurve2.path) && animationWindowCurve.type == animationWindowCurve2.type; + if (i == array.Length - 1 || !flag || !flag2) + { + if (list2.Count > 1) + { + list.Add(this.AddPropertyGroupToHierarchy(list2.ToArray(), (AnimationWindowHierarchyNode)this.m_RootItem)); + } + else + { + list.Add(this.AddPropertyToHierarchy(list2[0], (AnimationWindowHierarchyNode)this.m_RootItem)); + } + list2.Clear(); + } + } + return list; + } + private AnimationWindowHierarchyPropertyGroupNode AddPropertyGroupToHierarchy(AnimationWindowCurve[] curves, AnimationWindowHierarchyNode parentNode) + { + List list = new List(); + Type type = curves[0].type; + AnimationWindowHierarchyPropertyGroupNode animationWindowHierarchyPropertyGroupNode = new AnimationWindowHierarchyPropertyGroupNode(type, AnimationWindowUtility.GetPropertyGroupName(curves[0].propertyName), curves[0].path, parentNode); + animationWindowHierarchyPropertyGroupNode.icon = this.GetIcon(curves[0].binding); + animationWindowHierarchyPropertyGroupNode.indent = curves[0].depth; + animationWindowHierarchyPropertyGroupNode.curves = curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve curve = curves[i]; + AnimationWindowHierarchyPropertyNode animationWindowHierarchyPropertyNode = this.AddPropertyToHierarchy(curve, animationWindowHierarchyPropertyGroupNode); + animationWindowHierarchyPropertyNode.displayName = AnimationWindowUtility.GetPropertyDisplayName(animationWindowHierarchyPropertyNode.propertyName); + list.Add(animationWindowHierarchyPropertyNode); + } + TreeViewUtility.SetChildParentReferences(new List(list.ToArray()), animationWindowHierarchyPropertyGroupNode); + return animationWindowHierarchyPropertyGroupNode; + } + private AnimationWindowHierarchyPropertyNode AddPropertyToHierarchy(AnimationWindowCurve curve, AnimationWindowHierarchyNode parentNode) + { + AnimationWindowHierarchyPropertyNode animationWindowHierarchyPropertyNode = new AnimationWindowHierarchyPropertyNode(curve.type, curve.propertyName, curve.path, parentNode, curve.binding, curve.isPPtrCurve); + if (parentNode.icon != null) + { + animationWindowHierarchyPropertyNode.icon = parentNode.icon; + } + else + { + animationWindowHierarchyPropertyNode.icon = this.GetIcon(curve.binding); + } + animationWindowHierarchyPropertyNode.indent = curve.depth; + animationWindowHierarchyPropertyNode.curves = new AnimationWindowCurve[] + { + curve + }; + return animationWindowHierarchyPropertyNode; + } + public Texture2D GetIcon(EditorCurveBinding curveBinding) + { + if (this.state.m_RootGameObject != null) + { + UnityEngine.Object animatedObject = AnimationUtility.GetAnimatedObject(this.state.m_RootGameObject, curveBinding); + if (animatedObject != null) + { + return AssetPreview.GetMiniThumbnail(AnimationUtility.GetAnimatedObject(this.state.m_RootGameObject, curveBinding)); + } + } + return AssetPreview.GetMiniTypeThumbnail(curveBinding.type); + } + public void UpdateData() + { + this.m_TreeView.ReloadData(); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDragging.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDragging.cs new file mode 100644 index 00000000..4083177c --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyDragging.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyDragging : ITreeViewDragging + { + public bool drawRowMarkerAbove + { + get; + set; + } + public void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) + { + } + public bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bool firstItem) + { + return false; + } + public void DragCleanup(bool revertExpanded) + { + } + public int GetDropTargetControlID() + { + return 0; + } + public int GetRowMarkerControlID() + { + return 0; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs new file mode 100644 index 00000000..0fa52672 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs @@ -0,0 +1,807 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyGUI : TreeViewGUI + { + private const float k_RowRightOffset = 10f; + private const float k_PlusButtonWidth = 17f; + private const float k_TallModeButtonWidth = 17f; + private const float k_ValueFieldWidth = 50f; + private const float k_ValueFieldOffsetFromRightSide = 75f; + private const float k_ColorIndicatorTopMargin = 3f; + public const float k_DopeSheetRowHeight = 16f; + public const float k_DopeSheetRowHeightTall = 32f; + public const float k_AddCurveButtonNodeHeight = 40f; + public const float k_RowBackgroundColorBrightness = 0.28f; + private GUIStyle plusButtonStyle; + private GUIStyle animationRowEvenStyle; + private GUIStyle animationRowOddStyle; + private GUIStyle animationSelectionTextField; + private GUIStyle animationLineStyle; + private GUIStyle animationCurveDropdown; + private AnimationWindowHierarchyNode m_RenamedNode; + private Color m_LightSkinPropertyTextColor = new Color(0.35f, 0.35f, 0.35f); + private static Color k_KeyColorInDopesheetMode = new Color(0.7f, 0.7f, 0.7f, 1f); + private static Color k_KeyColorForNonCurves = new Color(0.7f, 0.7f, 0.7f, 0.5f); + private static Color k_LeftoverCurveColor = Color.yellow; + internal static int s_WasInsideValueRectFrame = -1; + public AnimationWindowState state + { + get; + set; + } + public AnimationWindowHierarchyGUI(TreeView treeView, AnimationWindowState state) : base(treeView) + { + this.state = state; + } + protected override void InitStyles() + { + base.InitStyles(); + if (this.plusButtonStyle == null) + { + this.plusButtonStyle = new GUIStyle("OL Plus"); + } + if (this.animationRowEvenStyle == null) + { + this.animationRowEvenStyle = new GUIStyle("AnimationRowEven"); + } + if (this.animationRowOddStyle == null) + { + this.animationRowOddStyle = new GUIStyle("AnimationRowOdd"); + } + if (this.animationSelectionTextField == null) + { + this.animationSelectionTextField = new GUIStyle("AnimationSelectionTextField"); + } + if (this.animationLineStyle == null) + { + this.animationLineStyle = new GUIStyle(TreeViewGUI.s_Styles.lineStyle); + this.animationLineStyle.padding.left = 0; + } + if (this.animationCurveDropdown == null) + { + this.animationCurveDropdown = new GUIStyle("AnimPropDropdown"); + } + } + protected void DoNodeGUI(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, int row) + { + this.InitStyles(); + if (node is AnimationWindowHierarchyMasterNode) + { + return; + } + float indent = this.k_BaseIndent + (float)(node.depth + node.indent) * this.k_IndentWidth; + if (node is AnimationWindowHierarchyAddButtonNode) + { + if (Event.current.type == EventType.MouseMove && AnimationWindowHierarchyGUI.s_WasInsideValueRectFrame >= 0) + { + if (AnimationWindowHierarchyGUI.s_WasInsideValueRectFrame >= Time.frameCount - 1) + { + Event.current.Use(); + } + else + { + AnimationWindowHierarchyGUI.s_WasInsideValueRectFrame = -1; + } + } + bool flag = this.state.m_ActiveGameObject && AnimationWindowUtility.GameObjectIsAnimatable(this.state.m_ActiveGameObject, this.state.m_ActiveAnimationClip); + EditorGUI.BeginDisabledGroup(!flag); + this.DoAddCurveButton(rect); + EditorGUI.EndDisabledGroup(); + } + else + { + this.DoRowBackground(rect, row); + this.DoIconAndName(rect, node, selected, focused, indent); + this.DoFoldout(node, rect, indent); + EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); + this.DoValueField(rect, node, row); + this.HandleContextMenu(rect, node); + EditorGUI.EndDisabledGroup(); + this.DoCurveDropdown(rect, node); + this.DoCurveColorIndicator(rect, node); + } + EditorGUIUtility.SetIconSize(Vector2.zero); + } + public override void BeginRowGUI() + { + base.BeginRowGUI(); + this.HandleDelete(); + } + private void DoAddCurveButton(Rect rect) + { + float num = 24f; + float num2 = 10f; + Rect rect2 = new Rect(rect.xMin + num, rect.yMin + num2, rect.width - num * 2f, rect.height - num2 * 2f); + if (GUI.Button(rect2, "Add Curve")) + { + if (!this.state.m_AnimationWindow.EnsureAnimationMode()) + { + return; + } + AddCurvesPopup.gameObject = this.state.m_RootGameObject; + AddCurvesPopupHierarchyDataSource.showEntireHierarchy = true; + if (AddCurvesPopup.ShowAtPosition(rect2, this.state)) + { + GUIUtility.ExitGUI(); + } + } + } + private void DoRowBackground(Rect rect, int row) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (row % 2 == 0) + { + this.animationRowEvenStyle.Draw(rect, false, false, false, false); + } + else + { + this.animationRowOddStyle.Draw(rect, false, false, false, false); + } + } + private void DoFoldout(AnimationWindowHierarchyNode node, Rect rect, float indent) + { + if (this.m_TreeView.data.IsExpandable(node)) + { + Rect position = rect; + position.x = indent; + position.width = this.k_FoldoutWidth; + EditorGUI.BeginChangeCheck(); + bool flag = GUI.Toggle(position, this.m_TreeView.data.IsExpanded(node), GUIContent.none, TreeViewGUI.s_Styles.foldout); + if (EditorGUI.EndChangeCheck()) + { + if (Event.current.alt) + { + this.m_TreeView.data.SetExpandedWithChildren(node, flag); + } + else + { + this.m_TreeView.data.SetExpanded(node, flag); + } + if (flag) + { + this.m_TreeView.UserExpandedNode(node); + } + } + } + else + { + AnimationWindowHierarchyPropertyNode animationWindowHierarchyPropertyNode = node as AnimationWindowHierarchyPropertyNode; + AnimationWindowHierarchyState animationWindowHierarchyState = this.m_TreeView.state as AnimationWindowHierarchyState; + if (animationWindowHierarchyPropertyNode != null && animationWindowHierarchyPropertyNode.isPptrNode) + { + Rect position2 = rect; + position2.x = indent; + position2.width = this.k_FoldoutWidth; + EditorGUI.BeginChangeCheck(); + bool flag2 = animationWindowHierarchyState.getTallMode(animationWindowHierarchyPropertyNode); + flag2 = GUI.Toggle(position2, flag2, GUIContent.none, TreeViewGUI.s_Styles.foldout); + if (EditorGUI.EndChangeCheck()) + { + animationWindowHierarchyState.setTallMode(animationWindowHierarchyPropertyNode, flag2); + } + } + } + } + private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool selected, bool focused, float indent) + { + EditorGUIUtility.SetIconSize(new Vector2(13f, 13f)); + int itemControlID = TreeView.GetItemControlID(node); + if (Event.current.type == EventType.Repaint) + { + bool flag = this.m_TreeView.dragging.GetDropTargetControlID() == itemControlID && this.m_TreeView.data.CanBeParent(node); + this.animationLineStyle.Draw(rect, GUIContent.none, flag, flag, selected, focused); + if (AnimationMode.InAnimationMode()) + { + rect.width -= 77f; + } + bool flag2 = AnimationWindowUtility.IsNodeLeftOverCurve(node, this.state.m_RootGameObject); + if (node.depth == 0) + { + Transform x = this.state.m_RootGameObject.transform.Find(node.path); + if (x == null) + { + flag2 = true; + } + GUIContent content = new GUIContent(this.GetGameObjectName(node.path) + " : " + node.displayName, this.GetIconForNode(node)); + Color textColor = this.animationLineStyle.normal.textColor; + Color color = (!EditorGUIUtility.isProSkin) ? Color.black : (Color.gray * 1.35f); + color = ((!flag2) ? color : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); + this.SetStyleTextColor(this.animationLineStyle, color); + rect.xMin += (float)((int)(indent + this.k_FoldoutWidth)); + this.animationLineStyle.Draw(rect, content, flag, flag, selected, focused); + this.SetStyleTextColor(this.animationLineStyle, textColor); + } + else + { + TreeViewGUI.s_Styles.content.text = node.displayName; + Texture iconForNode = this.GetIconForNode(node); + TreeViewGUI.s_Styles.content.image = iconForNode; + Color textColor2 = this.animationLineStyle.normal.textColor; + Color color2 = (!EditorGUIUtility.isProSkin) ? this.m_LightSkinPropertyTextColor : Color.gray; + color2 = ((!flag2) ? color2 : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); + this.SetStyleTextColor(this.animationLineStyle, color2); + rect.xMin += (float)((int)(indent + this.k_IndentWidth + this.k_FoldoutWidth)); + this.animationLineStyle.Draw(rect, TreeViewGUI.s_Styles.content, flag, flag, selected, focused); + this.SetStyleTextColor(this.animationLineStyle, textColor2); + if (this.m_TreeView.dragging.GetRowMarkerControlID() == itemControlID) + { + this.m_DraggingInsertionMarkerRect = new Rect(rect.x + indent + this.k_FoldoutWidth, rect.y, rect.width - indent, rect.height); + } + } + } + if (this.IsRenaming(node.id)) + { + base.GetRenameOverlay().editFieldRect = new Rect(rect.x + this.k_IndentWidth, rect.y, rect.width - this.k_IndentWidth - 1f, rect.height); + } + } + private string GetGameObjectName(string path) + { + if (string.IsNullOrEmpty(path)) + { + return this.state.m_RootGameObject.name; + } + string[] array = path.Split(new char[] + { + '/' + }); + return array[array.Length - 1]; + } + private string GetPathWithoutChildmostGameObject(string path) + { + if (string.IsNullOrEmpty(path)) + { + return string.Empty; + } + int num = path.LastIndexOf('/'); + return path.Substring(0, num + 1); + } + private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row) + { + if (!AnimationMode.InAnimationMode()) + { + return; + } + EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); + if (node is AnimationWindowHierarchyPropertyNode) + { + AnimationWindowCurve[] curves = this.state.GetCurves(node, false); + if (curves == null || curves.Length == 0) + { + return; + } + AnimationWindowCurve animationWindowCurve = curves[0]; + object currentValue = AnimationWindowUtility.GetCurrentValue(this.state.m_RootGameObject, animationWindowCurve.binding); + Type editorCurveValueType = AnimationUtility.GetEditorCurveValueType(this.state.m_RootGameObject, animationWindowCurve.binding); + if (currentValue is float) + { + float num = (float)currentValue; + Rect position = new Rect(rect.xMax - 75f, rect.y, 50f, rect.height); + if (Event.current.type == EventType.MouseMove && position.Contains(Event.current.mousePosition)) + { + AnimationWindowHierarchyGUI.s_WasInsideValueRectFrame = Time.frameCount; + } + EditorGUI.BeginChangeCheck(); + if (editorCurveValueType == typeof(bool)) + { + num = (float)((!EditorGUI.Toggle(position, num != 0f)) ? 0 : 1); + } + else + { + int controlID = GUIUtility.GetControlID(123456544, FocusType.Keyboard, position); + bool flag = GUIUtility.keyboardControl == controlID && EditorGUIUtility.editingTextField && Event.current.type == EventType.KeyDown && (Event.current.character == '\n' || Event.current.character == '\u0003'); + num = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, new Rect(0f, 0f, 0f, 0f), controlID, num, EditorGUI.kFloatFieldFormatString, this.animationSelectionTextField, false); + if (flag) + { + GUI.changed = true; + Event.current.Use(); + } + } + if (float.IsInfinity(num) || float.IsNaN(num)) + { + num = 0f; + } + if (EditorGUI.EndChangeCheck()) + { + AnimationWindowKeyframe animationWindowKeyframe = null; + foreach (AnimationWindowKeyframe current in animationWindowCurve.m_Keyframes) + { + if (Mathf.Approximately(current.time, this.state.time.time)) + { + animationWindowKeyframe = current; + } + } + if (animationWindowKeyframe == null) + { + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, num, editorCurveValueType, this.state.time); + } + else + { + animationWindowKeyframe.value = num; + } + this.state.SaveCurve(animationWindowCurve); + } + } + } + EditorGUI.EndDisabledGroup(); + } + private void DoCurveDropdown(Rect rect, AnimationWindowHierarchyNode node) + { + rect = new Rect(rect.xMax - 10f - 12f, rect.yMin + 2f, 22f, 12f); + if (GUI.Button(rect, GUIContent.none, this.animationCurveDropdown)) + { + this.state.SelectHierarchyItem(node.id, false, false); + this.state.m_AnimationWindow.RefreshShownCurves(true); + GenericMenu genericMenu = this.GenerateMenu(new AnimationWindowHierarchyNode[] + { + node + }.ToList()); + genericMenu.DropDown(rect); + Event.current.Use(); + } + } + private void DoCurveColorIndicator(Rect rect, AnimationWindowHierarchyNode node) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color = GUI.color; + if (!this.state.m_ShowCurveEditor) + { + GUI.color = AnimationWindowHierarchyGUI.k_KeyColorInDopesheetMode; + } + else + { + if (node.curves.Length == 1 && !node.curves[0].isPPtrCurve) + { + GUI.color = CurveUtility.GetPropertyColor(node.curves[0].binding.propertyName); + } + else + { + GUI.color = AnimationWindowHierarchyGUI.k_KeyColorForNonCurves; + } + } + bool flag = false; + if (AnimationMode.InAnimationMode()) + { + AnimationWindowCurve[] curves = node.curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (animationWindowCurve.m_Keyframes.Any((AnimationWindowKeyframe key) => this.state.time.ContainsTime(key.time))) + { + flag = true; + } + } + } + Texture texture = (!flag) ? CurveUtility.GetIconCurve() : CurveUtility.GetIconKey(); + rect = new Rect(rect.xMax - 10f - (float)(texture.width / 2) - 5f, rect.yMin + 3f, (float)texture.width, (float)texture.height); + GUI.DrawTexture(rect, texture, ScaleMode.ScaleToFit, true, 1f); + GUI.color = color; + } + private void HandleDelete() + { + if (this.m_TreeView.HasFocus()) + { + EventType type = Event.current.type; + if (type != EventType.KeyDown) + { + if (type == EventType.ExecuteCommand) + { + if (Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.RemoveCurvesFromSelectedNodes(); + } + Event.current.Use(); + } + } + } + else + { + if (Event.current.keyCode == KeyCode.Backspace || Event.current.keyCode == KeyCode.Delete) + { + this.RemoveCurvesFromSelectedNodes(); + Event.current.Use(); + } + } + } + } + private void HandleContextMenu(Rect rect, AnimationWindowHierarchyNode node) + { + if (Event.current.type != EventType.ContextClick) + { + return; + } + if (rect.Contains(Event.current.mousePosition)) + { + this.state.SelectHierarchyItem(node.id, false, true); + this.state.m_AnimationWindow.RefreshShownCurves(true); + this.GenerateMenu(this.state.selectedHierarchyNodes).ShowAsContext(); + Event.current.Use(); + } + } + private GenericMenu GenerateMenu(List interactedNodes) + { + List curvesAffectedByNodes = this.GetCurvesAffectedByNodes(interactedNodes, false); + List curvesAffectedByNodes2 = this.GetCurvesAffectedByNodes(interactedNodes, true); + bool flag = curvesAffectedByNodes.Count == 1 && AnimationWindowUtility.ForceGrouping(curvesAffectedByNodes[0].binding); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent((curvesAffectedByNodes.Count <= 1 && !flag) ? "Remove Property" : "Remove Properties"), false, new GenericMenu.MenuFunction(this.RemoveCurvesFromSelectedNodes)); + bool flag2 = true; + EditorCurveBinding[] array = new EditorCurveBinding[curvesAffectedByNodes2.Count]; + for (int i = 0; i < curvesAffectedByNodes.Count; i++) + { + array[i] = curvesAffectedByNodes2[i].binding; + } + RotationCurveInterpolation.Mode rotationInterpolationMode = this.GetRotationInterpolationMode(array); + if (rotationInterpolationMode == RotationCurveInterpolation.Mode.Undefined) + { + flag2 = false; + } + else + { + foreach (AnimationWindowHierarchyNode current in interactedNodes) + { + if (!(current is AnimationWindowHierarchyPropertyGroupNode)) + { + flag2 = false; + } + } + } + if (flag2) + { + genericMenu.AddItem(new GUIContent("Interpolation/Euler Angles"), rotationInterpolationMode == RotationCurveInterpolation.Mode.Baked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), RotationCurveInterpolation.Mode.Baked); + genericMenu.AddItem(new GUIContent("Interpolation/Quaternion"), rotationInterpolationMode == RotationCurveInterpolation.Mode.NonBaked, new GenericMenu.MenuFunction2(this.ChangeRotationInterpolation), RotationCurveInterpolation.Mode.NonBaked); + } + if (AnimationMode.InAnimationMode()) + { + genericMenu.AddSeparator(string.Empty); + bool flag3 = true; + bool flag4 = true; + bool flag5 = true; + foreach (AnimationWindowCurve current2 in curvesAffectedByNodes) + { + if (!current2.HasKeyframe(this.state.time)) + { + flag3 = false; + } + else + { + flag4 = false; + if (!current2.isPPtrCurve) + { + flag5 = false; + } + } + } + string text = "Add Key"; + if (flag3) + { + genericMenu.AddDisabledItem(new GUIContent(text)); + } + else + { + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.AddKeysAtCurrentTime), curvesAffectedByNodes); + } + text = "Delete Key"; + if (flag4) + { + genericMenu.AddDisabledItem(new GUIContent(text)); + } + else + { + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.DeleteKeysAtCurrentTime), curvesAffectedByNodes); + } + if (!flag5) + { + genericMenu.AddSeparator(string.Empty); + List list = new List(); + foreach (AnimationWindowCurve current3 in curvesAffectedByNodes) + { + if (!current3.isPPtrCurve) + { + int keyframeIndex = current3.GetKeyframeIndex(this.state.time); + if (keyframeIndex != -1) + { + CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.state.m_ActiveAnimationClip, current3.binding); + int curveID = CurveUtility.GetCurveID(this.state.m_ActiveAnimationClip, current3.binding); + list.Add(new KeyIdentifier(curveRenderer, curveID, keyframeIndex)); + } + } + } + CurveMenuManager curveMenuManager = new CurveMenuManager(this.state.m_AnimationWindow); + curveMenuManager.AddTangentMenuItems(genericMenu, list); + } + } + return genericMenu; + } + private void AddKeysAtCurrentTime(object obj) + { + this.AddKeysAtCurrentTime((List)obj); + } + private void AddKeysAtCurrentTime(List curves) + { + foreach (AnimationWindowCurve current in curves) + { + AnimationWindowUtility.AddKeyframeToCurve(this.state, current, this.state.time); + } + } + private void DeleteKeysAtCurrentTime(object obj) + { + this.DeleteKeysAtCurrentTime((List)obj); + } + private void DeleteKeysAtCurrentTime(List curves) + { + foreach (AnimationWindowCurve current in curves) + { + current.RemoveKeyframe(this.state.time); + this.state.SaveCurve(current); + } + } + private void ChangeRotationInterpolation(object interpolationMode) + { + RotationCurveInterpolation.Mode mode = (RotationCurveInterpolation.Mode)((int)interpolationMode); + AnimationWindowCurve[] array = this.state.activeCurves.ToArray(); + EditorCurveBinding[] array2 = new EditorCurveBinding[array.Length]; + for (int i = 0; i < array.Length; i++) + { + array2[i] = array[i].binding; + } + RotationCurveInterpolation.SetInterpolation(this.state.m_ActiveAnimationClip, array2, mode); + this.MaintainTreeviewStateAfterRotationInterpolation(mode); + this.state.m_HierarchyData.ReloadData(); + } + private void RemoveCurvesFromSelectedNodes() + { + this.RemoveCurvesFromNodes(this.state.selectedHierarchyNodes); + } + private void RemoveCurvesFromNodes(List nodes) + { + foreach (AnimationWindowHierarchyNode current in nodes) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = current; + if (animationWindowHierarchyNode.parent is AnimationWindowHierarchyPropertyGroupNode) + { + EditorCurveBinding? binding = animationWindowHierarchyNode.binding; + if (binding.HasValue) + { + EditorCurveBinding? binding2 = animationWindowHierarchyNode.binding; + if (AnimationWindowUtility.ForceGrouping(binding2.Value)) + { + animationWindowHierarchyNode = (AnimationWindowHierarchyNode)animationWindowHierarchyNode.parent; + } + } + } + AnimationWindowCurve[] array; + if (animationWindowHierarchyNode is AnimationWindowHierarchyPropertyGroupNode || animationWindowHierarchyNode is AnimationWindowHierarchyPropertyNode) + { + array = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType, animationWindowHierarchyNode.propertyName); + } + else + { + array = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType); + } + AnimationWindowCurve[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + AnimationWindowCurve curve = array2[i]; + this.state.RemoveCurve(curve); + } + } + this.m_TreeView.ReloadData(); + } + private List GetCurvesAffectedByNodes(List nodes, bool includeLinkedCurves) + { + List list = new List(); + foreach (AnimationWindowHierarchyNode current in nodes) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = current; + if (animationWindowHierarchyNode.parent is AnimationWindowHierarchyPropertyGroupNode) + { + if (!includeLinkedCurves) + { + EditorCurveBinding? binding = animationWindowHierarchyNode.binding; + if (!binding.HasValue) + { + goto IL_6B; + } + EditorCurveBinding? binding2 = animationWindowHierarchyNode.binding; + if (!AnimationWindowUtility.ForceGrouping(binding2.Value)) + { + goto IL_6B; + } + } + animationWindowHierarchyNode = (AnimationWindowHierarchyNode)animationWindowHierarchyNode.parent; + } + IL_6B: + if (animationWindowHierarchyNode is AnimationWindowHierarchyPropertyGroupNode || animationWindowHierarchyNode is AnimationWindowHierarchyPropertyNode) + { + list.AddRange(AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType, animationWindowHierarchyNode.propertyName)); + } + else + { + list.AddRange(AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType)); + } + } + return list.Distinct().ToList(); + } + private void MaintainTreeviewStateAfterRotationInterpolation(RotationCurveInterpolation.Mode newMode) + { + List selectedIDs = this.state.m_hierarchyState.selectedIDs; + List expandedIDs = this.state.m_hierarchyState.expandedIDs; + List list = new List(); + List list2 = new List(); + for (int i = 0; i < selectedIDs.Count; i++) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = this.state.m_HierarchyData.FindItem(selectedIDs[i]) as AnimationWindowHierarchyNode; + if (animationWindowHierarchyNode != null && !animationWindowHierarchyNode.propertyName.Equals(RotationCurveInterpolation.GetPrefixForInterpolation(newMode))) + { + string oldValue = animationWindowHierarchyNode.propertyName.Split(new char[] + { + '.' + })[0]; + string str = animationWindowHierarchyNode.propertyName.Replace(oldValue, RotationCurveInterpolation.GetPrefixForInterpolation(newMode)); + list.Add(selectedIDs[i]); + list2.Add((animationWindowHierarchyNode.path + animationWindowHierarchyNode.animatableObjectType.Name + str).GetHashCode()); + } + } + for (int j = 0; j < list.Count; j++) + { + if (selectedIDs.Contains(list[j])) + { + int index = selectedIDs.IndexOf(list[j]); + selectedIDs[index] = list2[j]; + } + if (expandedIDs.Contains(list[j])) + { + int index2 = expandedIDs.IndexOf(list[j]); + expandedIDs[index2] = list2[j]; + } + if (this.state.m_hierarchyState.lastClickedID == list[j]) + { + this.state.m_hierarchyState.lastClickedID = list2[j]; + } + } + this.state.m_hierarchyState.selectedIDs = new List(selectedIDs); + this.state.m_hierarchyState.expandedIDs = new List(expandedIDs); + } + private RotationCurveInterpolation.Mode GetRotationInterpolationMode(EditorCurveBinding[] curves) + { + if (curves == null || curves.Length == 0) + { + return RotationCurveInterpolation.Mode.Undefined; + } + RotationCurveInterpolation.Mode modeFromCurveData = RotationCurveInterpolation.GetModeFromCurveData(curves[0]); + for (int i = 1; i < curves.Length; i++) + { + RotationCurveInterpolation.Mode modeFromCurveData2 = RotationCurveInterpolation.GetModeFromCurveData(curves[i]); + if (modeFromCurveData != modeFromCurveData2) + { + return RotationCurveInterpolation.Mode.Undefined; + } + } + return modeFromCurveData; + } + private void SetStyleTextColor(GUIStyle style, Color color) + { + style.normal.textColor = color; + style.focused.textColor = color; + style.active.textColor = color; + style.hover.textColor = color; + } + public override void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) + { + firstRowVisible = 0; + lastRowVisible = rows.Count - 1; + } + public override float GetTopPixelOfRow(int row, List rows) + { + float num = 0f; + int num2 = 0; + while (num2 < row && num2 < rows.Count) + { + AnimationWindowHierarchyNode node = rows[num2] as AnimationWindowHierarchyNode; + num += this.GetNodeHeight(node); + num2++; + } + return num; + } + public float GetNodeHeight(AnimationWindowHierarchyNode node) + { + if (node is AnimationWindowHierarchyAddButtonNode) + { + return 40f; + } + AnimationWindowHierarchyState animationWindowHierarchyState = this.m_TreeView.state as AnimationWindowHierarchyState; + return (!animationWindowHierarchyState.getTallMode(node)) ? 16f : 32f; + } + public override Vector2 GetTotalSize(List rows) + { + float num = 0f; + for (int i = 0; i < rows.Count; i++) + { + AnimationWindowHierarchyNode node = rows[i] as AnimationWindowHierarchyNode; + num += this.GetNodeHeight(node); + } + return new Vector2(1f, num); + } + public override Rect OnRowGUI(TreeViewItem node, int row, float rowWidth, bool selected, bool focused) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = node as AnimationWindowHierarchyNode; + float? topPixel = animationWindowHierarchyNode.topPixel; + if (!topPixel.HasValue) + { + animationWindowHierarchyNode.topPixel = new float?(this.GetTopPixelOfRow(row, this.m_TreeView.data.GetVisibleRows())); + } + float nodeHeight = this.GetNodeHeight(animationWindowHierarchyNode); + float arg_5F_1 = 0f; + float? topPixel2 = animationWindowHierarchyNode.topPixel; + Rect rect = new Rect(arg_5F_1, topPixel2.Value, rowWidth, nodeHeight); + this.DoNodeGUI(rect, animationWindowHierarchyNode, selected, focused, row); + return rect; + } + public override bool BeginRename(TreeViewItem item, float delay) + { + this.m_RenamedNode = (item as AnimationWindowHierarchyNode); + return base.GetRenameOverlay().BeginRename(this.GetGameObjectName(this.m_RenamedNode.path), item.id, delay); + } + protected override void SyncFakeItem() + { + } + protected override void RenameEnded() + { + string name = base.GetRenameOverlay().name; + string originalName = base.GetRenameOverlay().originalName; + if (name != originalName) + { + AnimationWindowCurve[] curves = this.m_RenamedNode.curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + string newPath = this.RenamePath(animationWindowCurve.path, name); + EditorCurveBinding renamedBinding = AnimationWindowUtility.GetRenamedBinding(animationWindowCurve.binding, newPath); + if (AnimationWindowUtility.CurveExists(renamedBinding, this.state.allCurves.ToArray())) + { + Debug.LogWarning("Curve already exists, renaming cancelled."); + } + else + { + AnimationWindowUtility.RenameCurvePath(animationWindowCurve, renamedBinding, this.state.m_ActiveAnimationClip); + } + } + } + this.m_RenamedNode = null; + } + private string RenamePath(string oldPath, string newGameObjectName) + { + if (oldPath.Length > 0) + { + string text = this.GetPathWithoutChildmostGameObject(oldPath); + if (text.Length > 0) + { + text += "/"; + } + return text + newGameObjectName; + } + return newGameObjectName; + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item != null) + { + return item.icon; + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyMasterNode.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyMasterNode.cs new file mode 100644 index 00000000..a6247dea --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyMasterNode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyMasterNode : AnimationWindowHierarchyNode + { + public AnimationWindowHierarchyMasterNode() : base(0, -1, null, null, null, null, string.Empty) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyNode.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyNode.cs new file mode 100644 index 00000000..fab719fd --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyNode.cs @@ -0,0 +1,22 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyNode : TreeViewItem + { + public string path; + public Type animatableObjectType; + public string propertyName; + public EditorCurveBinding? binding; + public AnimationWindowCurve[] curves; + public float? topPixel; + public int indent; + public AnimationWindowHierarchyNode(int instanceID, int depth, TreeViewItem parent, Type animatableObjectType, string propertyName, string path, string displayName) : base(instanceID, depth, parent, displayName) + { + this.displayName = displayName; + this.animatableObjectType = animatableObjectType; + this.propertyName = propertyName; + this.path = path; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyGroupNode.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyGroupNode.cs new file mode 100644 index 00000000..2bb752b7 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyGroupNode.cs @@ -0,0 +1,11 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyPropertyGroupNode : AnimationWindowHierarchyNode + { + public AnimationWindowHierarchyPropertyGroupNode(Type animatableObjectType, string propertyName, string path, TreeViewItem parent) : base(AnimationWindowUtility.GetPropertyNodeID(path, animatableObjectType, propertyName), (parent == null) ? -1 : (parent.depth + 1), parent, animatableObjectType, AnimationWindowUtility.GetPropertyGroupName(propertyName), path, AnimationWindowUtility.GetNicePropertyGroupDisplayName(animatableObjectType, propertyName)) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyNode.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyNode.cs new file mode 100644 index 00000000..4e9814c6 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyPropertyNode.cs @@ -0,0 +1,14 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class AnimationWindowHierarchyPropertyNode : AnimationWindowHierarchyNode + { + public bool isPptrNode; + public AnimationWindowHierarchyPropertyNode(Type animatableObjectType, string propertyName, string path, TreeViewItem parent, EditorCurveBinding binding, bool isPptrNode) : base(AnimationWindowUtility.GetPropertyNodeID(path, animatableObjectType, propertyName), (parent == null) ? -1 : (parent.depth + 1), parent, animatableObjectType, propertyName, path, AnimationWindowUtility.GetNicePropertyDisplayName(animatableObjectType, propertyName)) + { + this.binding = new EditorCurveBinding?(binding); + this.isPptrNode = isPptrNode; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyState.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyState.cs new file mode 100644 index 00000000..0fdba0ee --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyState.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +namespace UnityEditorInternal +{ + [Serializable] + internal class AnimationWindowHierarchyState : TreeViewState + { + public List m_TallInstanceIDs = new List(); + public bool getTallMode(AnimationWindowHierarchyNode node) + { + return this.m_TallInstanceIDs.Contains(node.id); + } + public void setTallMode(AnimationWindowHierarchyNode node, bool tallMode) + { + if (tallMode) + { + this.m_TallInstanceIDs.Add(node.id); + } + else + { + this.m_TallInstanceIDs.Remove(node.id); + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowKeyframe.cs b/UnityEditor/UnityEditorInternal/AnimationWindowKeyframe.cs new file mode 100644 index 00000000..7c821601 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowKeyframe.cs @@ -0,0 +1,97 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AnimationWindowKeyframe + { + public float m_InTangent; + public float m_OutTangent; + public int m_TangentMode; + public int m_TimeHash; + private int m_Hash; + private float m_time; + private object m_value; + private AnimationWindowCurve m_curve; + public float time + { + get + { + return this.m_time; + } + set + { + this.m_time = value; + this.m_Hash = 0; + this.m_TimeHash = value.GetHashCode(); + } + } + public object value + { + get + { + return this.m_value; + } + set + { + this.m_value = value; + this.m_Hash = 0; + } + } + public AnimationWindowCurve curve + { + get + { + return this.m_curve; + } + set + { + this.m_curve = value; + this.m_Hash = 0; + } + } + public bool isPPtrCurve + { + get + { + return this.curve.isPPtrCurve; + } + } + 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_TangentMode = key.m_TangentMode; + } + public AnimationWindowKeyframe(AnimationWindowCurve curve, Keyframe key) + { + this.time = key.time; + this.value = key.value; + this.curve = curve; + this.m_InTangent = key.inTangent; + this.m_OutTangent = key.outTangent; + this.m_TangentMode = key.tangentMode; + } + public AnimationWindowKeyframe(AnimationWindowCurve curve, ObjectReferenceKeyframe key) + { + this.time = key.time; + this.value = key.value; + this.curve = curve; + } + public int GetHash() + { + if (this.m_Hash == 0) + { + this.m_Hash = this.curve.GetHashCode(); + this.m_Hash = 33 * this.m_Hash + this.time.GetHashCode(); + } + return this.m_Hash; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowState.cs b/UnityEditor/UnityEditorInternal/AnimationWindowState.cs new file mode 100644 index 00000000..2a6e87f4 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowState.cs @@ -0,0 +1,887 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + [Serializable] + internal class AnimationWindowState + { + public enum RefreshType + { + None, + CurvesOnly, + Everything + } + [SerializeField] + public AnimationWindowHierarchyState m_hierarchyState; + [SerializeField] + public AnimationClip m_ActiveAnimationClip; + [SerializeField] + public GameObject m_ActiveGameObject; + [SerializeField] + public GameObject m_RootGameObject; + [SerializeField] + public GameObject m_AnimatedGameObject; + [SerializeField] + public bool m_AnimationIsPlaying; + [SerializeField] + public bool m_ShowCurveEditor; + [SerializeField] + public bool m_CurveEditorIsDirty; + [SerializeField] + public float m_PlayTime; + [SerializeField] + public int m_Frame; + [SerializeField] + private Hashtable m_SelectedKeyHashes; + [SerializeField] + private int m_ActiveKeyframeHash; + [SerializeField] + private Rect m_ShownTimeArea = new Rect(0f, 0f, 2f, 2f); + [SerializeField] + private Rect m_ShownTimeAreaInsideMargins = new Rect(0f, 0f, 2f, 2f); + public Action m_OnHierarchySelectionChanged; + public AnimationWindowHierarchyDataSource m_HierarchyData; + public AnimationWindow m_AnimationWindow; + private List m_AllCurvesCache; + private List m_ActiveCurvesCache; + private List m_dopelinesCache; + private List m_SelectedKeysCache; + private AnimationWindowKeyframe m_ActiveKeyframeCache; + private HashSet m_ModifiedCurves = new HashSet(); + private EditorCurveBinding? m_lastAddedCurveBinding; + private EditorWindow m_Window; + private int m_PreviousRefreshHash; + private AnimationWindowState.RefreshType m_Refresh; + private TimeArea m_timeArea; + public AnimationWindowState.RefreshType refresh + { + get + { + return this.m_Refresh; + } + set + { + if (this.m_Refresh < value) + { + this.m_Refresh = value; + } + } + } + public List allCurves + { + get + { + if (this.m_AllCurvesCache == null) + { + this.m_AllCurvesCache = new List(); + if (this.m_ActiveAnimationClip != null && this.m_ActiveGameObject != null) + { + EditorCurveBinding[] curveBindings = AnimationUtility.GetCurveBindings(this.m_ActiveAnimationClip); + EditorCurveBinding[] objectReferenceCurveBindings = AnimationUtility.GetObjectReferenceCurveBindings(this.m_ActiveAnimationClip); + EditorCurveBinding[] array = curveBindings; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding editorCurveBinding = array[i]; + if (AnimationWindowUtility.ShouldShowAnimationWindowCurve(editorCurveBinding)) + { + this.m_AllCurvesCache.Add(new AnimationWindowCurve(this.m_ActiveAnimationClip, editorCurveBinding, AnimationUtility.GetEditorCurveValueType(this.m_RootGameObject, editorCurveBinding))); + } + } + EditorCurveBinding[] array2 = objectReferenceCurveBindings; + for (int j = 0; j < array2.Length; j++) + { + EditorCurveBinding binding = array2[j]; + this.m_AllCurvesCache.Add(new AnimationWindowCurve(this.m_ActiveAnimationClip, binding, AnimationUtility.GetEditorCurveValueType(this.m_RootGameObject, binding))); + } + this.m_AllCurvesCache.Sort(); + } + } + return this.m_AllCurvesCache; + } + } + public List activeCurves + { + get + { + if (this.m_ActiveCurvesCache == null) + { + this.m_ActiveCurvesCache = new List(); + if (this.m_hierarchyState != null && this.m_HierarchyData != null) + { + foreach (int current in this.m_hierarchyState.selectedIDs) + { + TreeViewItem treeViewItem = this.m_HierarchyData.FindItem(current); + AnimationWindowHierarchyNode animationWindowHierarchyNode = treeViewItem as AnimationWindowHierarchyNode; + if (animationWindowHierarchyNode != null) + { + AnimationWindowCurve[] curves = this.GetCurves(animationWindowHierarchyNode, true); + AnimationWindowCurve[] array = curves; + for (int i = 0; i < array.Length; i++) + { + AnimationWindowCurve item = array[i]; + if (!this.m_ActiveCurvesCache.Contains(item)) + { + this.m_ActiveCurvesCache.Add(item); + } + } + } + } + } + } + return this.m_ActiveCurvesCache; + } + } + public List dopelines + { + get + { + if (this.m_dopelinesCache == null) + { + this.m_dopelinesCache = new List(); + if (this.m_HierarchyData != null) + { + foreach (TreeViewItem current in this.m_HierarchyData.GetVisibleRows()) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = current as AnimationWindowHierarchyNode; + if (animationWindowHierarchyNode != null && !(animationWindowHierarchyNode is AnimationWindowHierarchyAddButtonNode)) + { + AnimationWindowCurve[] curves; + if (current is AnimationWindowHierarchyMasterNode) + { + curves = this.allCurves.ToArray(); + } + else + { + curves = this.GetCurves(animationWindowHierarchyNode, true); + } + DopeLine dopeLine = new DopeLine(current.id, curves); + dopeLine.tallMode = this.m_hierarchyState.getTallMode(animationWindowHierarchyNode); + dopeLine.objectType = animationWindowHierarchyNode.animatableObjectType; + dopeLine.hasChildren = !(animationWindowHierarchyNode is AnimationWindowHierarchyPropertyNode); + dopeLine.isMasterDopeline = (current is AnimationWindowHierarchyMasterNode); + this.m_dopelinesCache.Add(dopeLine); + } + } + } + } + return this.m_dopelinesCache; + } + } + public List selectedHierarchyNodes + { + get + { + List list = new List(); + if (this.m_HierarchyData != null) + { + foreach (int current in this.m_hierarchyState.selectedIDs) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = (AnimationWindowHierarchyNode)this.m_HierarchyData.FindItem(current); + if (animationWindowHierarchyNode != null && !(animationWindowHierarchyNode is AnimationWindowHierarchyAddButtonNode)) + { + list.Add(animationWindowHierarchyNode); + } + } + } + return list; + } + } + public AnimationWindowKeyframe activeKeyframe + { + get + { + if (this.m_ActiveKeyframeCache == null) + { + foreach (AnimationWindowCurve current in this.allCurves) + { + foreach (AnimationWindowKeyframe current2 in current.m_Keyframes) + { + if (current2.GetHash() == this.m_ActiveKeyframeHash) + { + this.m_ActiveKeyframeCache = current2; + } + } + } + } + return this.m_ActiveKeyframeCache; + } + set + { + this.m_ActiveKeyframeCache = null; + this.m_ActiveKeyframeHash = ((value == null) ? 0 : value.GetHash()); + } + } + public List selectedKeys + { + get + { + if (this.m_SelectedKeysCache == null) + { + this.m_SelectedKeysCache = new List(); + foreach (AnimationWindowCurve current in this.allCurves) + { + foreach (AnimationWindowKeyframe current2 in current.m_Keyframes) + { + if (this.KeyIsSelected(current2)) + { + this.m_SelectedKeysCache.Add(current2); + } + } + } + } + return this.m_SelectedKeysCache; + } + } + private Hashtable selectedKeyHashes + { + get + { + Hashtable arg_1B_0; + if ((arg_1B_0 = this.m_SelectedKeyHashes) == null) + { + arg_1B_0 = (this.m_SelectedKeyHashes = new Hashtable()); + } + return arg_1B_0; + } + set + { + this.m_SelectedKeyHashes = value; + } + } + public bool IsReadOnly + { + get + { + return !this.m_ActiveAnimationClip || !this.IsEditable; + } + } + public bool IsEditable + { + get + { + return this.m_ActiveGameObject && (!this.m_ActiveAnimationClip || (this.m_ActiveAnimationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None) && !this.IsPrefab; + } + } + public bool IsClipEditable + { + get + { + return this.m_ActiveAnimationClip && (this.m_ActiveAnimationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None && AssetDatabase.IsOpenForEdit(this.m_ActiveAnimationClip); + } + } + public bool IsPrefab + { + get + { + return this.m_ActiveGameObject && (EditorUtility.IsPersistent(this.m_ActiveGameObject) || (this.m_ActiveGameObject.hideFlags & HideFlags.NotEditable) != HideFlags.None); + } + } + public bool AnimatorIsOptimized + { + get + { + if (!this.m_RootGameObject) + { + return false; + } + Animator component = this.m_RootGameObject.GetComponent(); + return component != null && component.isOptimizable && !component.hasTransformHierarchy; + } + } + public float frameRate + { + get + { + if (this.m_ActiveAnimationClip == null) + { + return 60f; + } + return this.m_ActiveAnimationClip.frameRate; + } + set + { + if (this.m_ActiveAnimationClip != null && value > 0f && value <= 10000f) + { + foreach (AnimationWindowCurve current in this.allCurves) + { + foreach (AnimationWindowKeyframe current2 in current.m_Keyframes) + { + int frame = AnimationKeyTime.Time(current2.time, this.frameRate).frame; + current2.time = AnimationKeyTime.Frame(frame, value).time; + } + this.SaveCurve(current); + } + this.m_ActiveAnimationClip.frameRate = value; + this.m_CurveEditorIsDirty = true; + } + } + } + public TimeArea timeArea + { + get + { + return this.m_timeArea; + } + set + { + if (value != this.m_timeArea && value != null) + { + value.SetShownHRangeInsideMargins(this.m_ShownTimeAreaInsideMargins.xMin, this.m_ShownTimeAreaInsideMargins.xMax); + } + this.m_timeArea = value; + if (this.m_timeArea != null) + { + this.m_ShownTimeAreaInsideMargins = this.m_timeArea.shownAreaInsideMargins; + this.m_ShownTimeArea = this.m_timeArea.shownArea; + } + } + } + public float pixelPerSecond + { + get + { + return this.timeArea.m_Scale.x; + } + } + public float zeroTimePixel + { + get + { + return this.timeArea.shownArea.xMin * this.timeArea.m_Scale.x * -1f; + } + } + public float minTime + { + get + { + return this.m_ShownTimeArea.xMin; + } + } + public float maxTime + { + get + { + return this.m_ShownTimeArea.xMax; + } + } + public float timeSpan + { + get + { + return this.maxTime - this.minTime; + } + } + public float minFrame + { + get + { + return this.minTime * this.frameRate; + } + } + public float maxFrame + { + get + { + return this.maxTime * this.frameRate; + } + } + public float frameSpan + { + get + { + return this.timeSpan * this.frameRate; + } + } + public AnimationKeyTime time + { + get + { + return AnimationKeyTime.Frame(this.m_Frame, this.frameRate); + } + } + public void OnGUI() + { + this.RefreshHashCheck(); + this.Refresh(); + } + private void RefreshHashCheck() + { + int refreshHash = this.GetRefreshHash(); + if (this.m_PreviousRefreshHash != refreshHash) + { + this.refresh = AnimationWindowState.RefreshType.Everything; + this.m_PreviousRefreshHash = refreshHash; + } + } + private int GetRefreshHash() + { + return ((!(this.m_ActiveAnimationClip != null)) ? 0 : this.m_ActiveAnimationClip.GetHashCode()) ^ ((!(this.m_RootGameObject != null)) ? 0 : this.m_RootGameObject.GetHashCode()) ^ ((this.m_hierarchyState == null) ? 0 : this.m_hierarchyState.expandedIDs.Count) ^ ((this.m_hierarchyState == null) ? 0 : this.m_hierarchyState.m_TallInstanceIDs.Count) ^ ((!this.m_ShowCurveEditor) ? 0 : 1); + } + public void OnEnable(EditorWindow window) + { + this.m_Window = window; + AnimationUtility.onCurveWasModified = (AnimationUtility.OnCurveWasModified)Delegate.Combine(AnimationUtility.onCurveWasModified, new AnimationUtility.OnCurveWasModified(this.CurveWasModified)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public void OnDisable() + { + this.m_Window = null; + AnimationUtility.onCurveWasModified = (AnimationUtility.OnCurveWasModified)Delegate.Remove(AnimationUtility.onCurveWasModified, new AnimationUtility.OnCurveWasModified(this.CurveWasModified)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + } + public void UndoRedoPerformed() + { + this.refresh = AnimationWindowState.RefreshType.Everything; + } + private void CurveWasModified(AnimationClip clip, EditorCurveBinding binding, AnimationUtility.CurveModifiedType type) + { + if (clip != this.m_ActiveAnimationClip) + { + return; + } + if (type == AnimationUtility.CurveModifiedType.CurveModified) + { + bool flag = false; + int hashCode = binding.GetHashCode(); + foreach (AnimationWindowCurve current in this.allCurves) + { + int hashCode2 = current.binding.GetHashCode(); + if (hashCode2 == hashCode) + { + this.m_ModifiedCurves.Add(hashCode2); + flag = true; + } + } + if (flag) + { + this.refresh = AnimationWindowState.RefreshType.CurvesOnly; + } + else + { + this.m_lastAddedCurveBinding = new EditorCurveBinding?(binding); + this.refresh = AnimationWindowState.RefreshType.Everything; + } + } + else + { + this.refresh = AnimationWindowState.RefreshType.Everything; + } + } + public void SaveCurve(AnimationWindowCurve curve) + { + curve.m_Keyframes.Sort((AnimationWindowKeyframe a, AnimationWindowKeyframe b) => a.time.CompareTo(b.time)); + Undo.RegisterCompleteObjectUndo(this.m_ActiveAnimationClip, "Edit Curve"); + if (curve.isPPtrCurve) + { + ObjectReferenceKeyframe[] array = curve.ToObjectCurve(); + if (array.Length == 0) + { + array = null; + } + AnimationUtility.SetObjectReferenceCurve(this.m_ActiveAnimationClip, curve.binding, array); + } + else + { + AnimationCurve animationCurve = curve.ToAnimationCurve(); + if (animationCurve.keys.Length == 0) + { + animationCurve = null; + } + else + { + QuaternionCurveTangentCalculation.UpdateTangentsFromMode(animationCurve, this.m_ActiveAnimationClip, curve.binding); + } + AnimationUtility.SetEditorCurve(this.m_ActiveAnimationClip, curve.binding, animationCurve); + } + this.Repaint(); + } + public void SaveSelectedKeys(List currentSelectedKeys) + { + List list = new List(); + foreach (AnimationWindowKeyframe current in currentSelectedKeys) + { + if (!list.Contains(current.curve)) + { + list.Add(current.curve); + } + List list2 = new List(); + foreach (AnimationWindowKeyframe current2 in current.curve.m_Keyframes) + { + if (!currentSelectedKeys.Contains(current2) && AnimationKeyTime.Time(current.time, this.frameRate).frame == AnimationKeyTime.Time(current2.time, this.frameRate).frame) + { + list2.Add(current2); + } + } + foreach (AnimationWindowKeyframe current3 in list2) + { + current.curve.m_Keyframes.Remove(current3); + } + } + foreach (AnimationWindowCurve current4 in list) + { + this.SaveCurve(current4); + } + } + public void RemoveCurve(AnimationWindowCurve curve) + { + Undo.RegisterCompleteObjectUndo(this.m_ActiveAnimationClip, "Remove Curve"); + if (curve.isPPtrCurve) + { + AnimationUtility.SetObjectReferenceCurve(this.m_ActiveAnimationClip, curve.binding, null); + } + else + { + AnimationUtility.SetEditorCurve(this.m_ActiveAnimationClip, curve.binding, null); + } + } + public bool AnyKeyIsSelected(DopeLine dopeline) + { + foreach (AnimationWindowKeyframe current in dopeline.keys) + { + if (this.KeyIsSelected(current)) + { + return true; + } + } + return false; + } + public bool KeyIsSelected(AnimationWindowKeyframe keyframe) + { + return this.selectedKeyHashes.Contains(keyframe.GetHash()); + } + public void SelectKey(AnimationWindowKeyframe keyframe) + { + int hash = keyframe.GetHash(); + if (!this.selectedKeyHashes.Contains(hash)) + { + this.selectedKeyHashes.Add(hash, hash); + } + this.m_SelectedKeysCache = null; + } + public void UnselectKey(AnimationWindowKeyframe keyframe) + { + int hash = keyframe.GetHash(); + if (this.selectedKeyHashes.Contains(hash)) + { + this.selectedKeyHashes.Remove(hash); + } + this.m_SelectedKeysCache = null; + } + public void DeleteSelectedKeys() + { + if (this.selectedKeys.Count == 0) + { + return; + } + foreach (AnimationWindowKeyframe current in this.selectedKeys) + { + this.UnselectKey(current); + current.curve.m_Keyframes.Remove(current); + this.SaveCurve(current.curve); + } + } + public void MoveSelectedKeys(float deltaTime) + { + this.MoveSelectedKeys(deltaTime, false); + } + public void MoveSelectedKeys(float deltaTime, bool snapToFrame) + { + this.MoveSelectedKeys(deltaTime, snapToFrame, true); + } + public void MoveSelectedKeys(float deltaTime, bool snapToFrame, bool saveToClip) + { + List list = new List(this.selectedKeys); + foreach (AnimationWindowKeyframe current in list) + { + current.time += deltaTime; + if (snapToFrame) + { + current.time = this.SnapToFrame(current.time, !saveToClip); + } + } + if (saveToClip) + { + this.SaveSelectedKeys(list); + } + this.ClearKeySelections(); + foreach (AnimationWindowKeyframe current2 in list) + { + this.SelectKey(current2); + } + } + public void ClearKeySelections() + { + this.selectedKeyHashes.Clear(); + this.m_SelectedKeysCache = null; + } + private void ReloadModifiedDopelineCache() + { + if (this.m_dopelinesCache == null) + { + return; + } + foreach (DopeLine current in this.m_dopelinesCache) + { + AnimationWindowCurve[] curves = current.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (this.m_ModifiedCurves.Contains(animationWindowCurve.binding.GetHashCode())) + { + current.LoadKeyframes(); + } + } + } + } + private void ReloadModifiedAnimationCurveCache() + { + if (this.m_AllCurvesCache == null) + { + return; + } + foreach (AnimationWindowCurve current in this.m_AllCurvesCache) + { + if (this.m_ModifiedCurves.Contains(current.binding.GetHashCode())) + { + current.LoadKeyframes(this.m_ActiveAnimationClip); + } + } + } + private void Refresh() + { + if (this.refresh == AnimationWindowState.RefreshType.Everything) + { + CurveRendererCache.ClearCurveRendererCache(); + this.m_ActiveKeyframeCache = null; + this.m_AllCurvesCache = null; + this.m_ActiveCurvesCache = null; + this.m_CurveEditorIsDirty = true; + this.m_dopelinesCache = null; + this.m_SelectedKeysCache = null; + if (this.refresh == AnimationWindowState.RefreshType.Everything && this.m_HierarchyData != null) + { + this.m_HierarchyData.UpdateData(); + } + EditorCurveBinding? lastAddedCurveBinding = this.m_lastAddedCurveBinding; + if (lastAddedCurveBinding.HasValue) + { + EditorCurveBinding? lastAddedCurveBinding2 = this.m_lastAddedCurveBinding; + this.OnNewCurveAdded(lastAddedCurveBinding2.Value); + } + if (this.activeCurves.Count == 0 && this.dopelines.Count > 0) + { + this.SelectHierarchyItem(this.dopelines[0], false, false); + } + this.m_Refresh = AnimationWindowState.RefreshType.None; + } + else + { + if (this.refresh == AnimationWindowState.RefreshType.CurvesOnly) + { + this.m_ActiveKeyframeCache = null; + this.m_ActiveCurvesCache = null; + this.m_SelectedKeysCache = null; + this.ReloadModifiedAnimationCurveCache(); + this.ReloadModifiedDopelineCache(); + CurveRendererCache.ClearCurveRendererCache(); + this.m_CurveEditorIsDirty = true; + this.m_Refresh = AnimationWindowState.RefreshType.None; + this.m_ModifiedCurves.Clear(); + } + } + } + private void OnNewCurveAdded(EditorCurveBinding newCurve) + { + string propertyGroupName = AnimationWindowUtility.GetPropertyGroupName(newCurve.propertyName); + int propertyNodeID = AnimationWindowUtility.GetPropertyNodeID(newCurve.path, newCurve.type, propertyGroupName); + this.SelectHierarchyItem(propertyNodeID, false, false); + if (newCurve.isPPtrCurve) + { + this.m_hierarchyState.m_TallInstanceIDs.Add(propertyNodeID); + } + this.m_lastAddedCurveBinding = null; + } + public void Repaint() + { + if (this.m_Window != null) + { + this.m_Window.Repaint(); + } + } + public AnimationWindowCurve[] GetCurves(AnimationWindowHierarchyNode hierarchyNode, bool entireHierarchy) + { + return AnimationWindowUtility.FilterCurves(this.allCurves.ToArray(), hierarchyNode.path, hierarchyNode.animatableObjectType, hierarchyNode.propertyName); + } + public List GetAggregateKeys(AnimationWindowHierarchyNode hierarchyNode) + { + DopeLine dopeLine = this.dopelines.FirstOrDefault((DopeLine e) => e.m_HierarchyNodeID == hierarchyNode.id); + if (dopeLine == null) + { + return null; + } + return dopeLine.keys; + } + public void OnHierarchySelectionChanged(int[] selectedInstanceIDs) + { + this.HandleHierarchySelectionChanged(selectedInstanceIDs, true); + this.m_OnHierarchySelectionChanged(); + } + public void HandleHierarchySelectionChanged(int[] selectedInstanceIDs, bool triggerSceneSelectionSync) + { + this.m_CurveEditorIsDirty = true; + this.m_ActiveCurvesCache = null; + if (triggerSceneSelectionSync) + { + this.SyncSceneSelection(selectedInstanceIDs); + } + } + public void SelectHierarchyItem(DopeLine dopeline, bool additive) + { + this.SelectHierarchyItem(dopeline.m_HierarchyNodeID, additive, true); + } + public void SelectHierarchyItem(DopeLine dopeline, bool additive, bool triggerSceneSelectionSync) + { + this.SelectHierarchyItem(dopeline.m_HierarchyNodeID, additive, triggerSceneSelectionSync); + } + public void SelectHierarchyItem(int hierarchyNodeID, bool additive, bool triggerSceneSelectionSync) + { + if (!additive) + { + this.ClearHierarchySelection(); + } + this.m_hierarchyState.selectedIDs.Add(hierarchyNodeID); + int[] selectedInstanceIDs = this.m_hierarchyState.selectedIDs.ToArray(); + this.HandleHierarchySelectionChanged(selectedInstanceIDs, triggerSceneSelectionSync); + } + public void UnSelectHierarchyItem(DopeLine dopeline) + { + this.UnSelectHierarchyItem(dopeline.m_HierarchyNodeID); + } + public void UnSelectHierarchyItem(int hierarchyNodeID) + { + this.m_hierarchyState.selectedIDs.Remove(hierarchyNodeID); + } + public void ClearHierarchySelection() + { + this.m_hierarchyState.selectedIDs.Clear(); + } + private void SyncSceneSelection(int[] selectedNodeIDs) + { + List list = new List(); + for (int i = 0; i < selectedNodeIDs.Length; i++) + { + int id = selectedNodeIDs[i]; + AnimationWindowHierarchyNode animationWindowHierarchyNode = this.m_HierarchyData.FindItem(id) as AnimationWindowHierarchyNode; + if (!(this.m_RootGameObject == null) && animationWindowHierarchyNode != null) + { + if (!(animationWindowHierarchyNode is AnimationWindowHierarchyMasterNode)) + { + Transform transform = this.m_RootGameObject.transform.Find(animationWindowHierarchyNode.path); + if (transform != null && this.m_RootGameObject != null && this.m_RootGameObject.transform == AnimationWindowUtility.GetClosestAnimationComponentInParents(transform)) + { + list.Add(transform.gameObject.GetInstanceID()); + } + } + } + } + Selection.instanceIDs = list.ToArray(); + } + public float PixelToTime(float pixel) + { + return this.PixelToTime(pixel, false); + } + public float PixelToTime(float pixel, bool snapToFrame) + { + float num = pixel - this.zeroTimePixel; + if (snapToFrame) + { + return this.SnapToFrame(num / this.pixelPerSecond); + } + return num / this.pixelPerSecond; + } + public float TimeToPixel(float time) + { + return this.TimeToPixel(time, false); + } + public float TimeToPixel(float time, bool snapToFrame) + { + return ((!snapToFrame) ? time : this.SnapToFrame(time)) * this.pixelPerSecond + this.zeroTimePixel; + } + public float SnapToFrame(float time) + { + return Mathf.Round(time * this.frameRate) / this.frameRate; + } + public float SnapToFrame(float time, bool preventHashCollision) + { + if (preventHashCollision) + { + return Mathf.Round(time * this.frameRate) / this.frameRate + 0.01f / this.frameRate; + } + return this.SnapToFrame(time); + } + public string FormatFrame(int frame, int frameDigits) + { + return (frame / (int)this.frameRate).ToString() + ":" + ((float)frame % this.frameRate).ToString().PadLeft(frameDigits, '0'); + } + public float TimeToFrame(float time) + { + return time * this.frameRate; + } + public float FrameToTime(float frame) + { + return frame / this.frameRate; + } + public float FrameToTimeFloor(float frame) + { + return (frame - 0.5f) / this.frameRate; + } + public float FrameToTimeCeiling(float frame) + { + return (frame + 0.5f) / this.frameRate; + } + public int TimeToFrameFloor(float time) + { + return Mathf.FloorToInt(this.TimeToFrame(time)); + } + public int TimeToFrameRound(float time) + { + return Mathf.RoundToInt(this.TimeToFrame(time)); + } + public float GetTimeSeconds() + { + if (this.m_AnimationIsPlaying) + { + return this.m_PlayTime; + } + return this.FrameToTime((float)this.m_Frame); + } + public float FrameToPixel(float i, Rect rect) + { + return (i - this.minFrame) * rect.width / this.frameSpan; + } + public float FrameDeltaToPixel(Rect rect) + { + return rect.width / this.frameSpan; + } + public float TimeToPixel(float time, Rect rect) + { + return this.FrameToPixel(time * this.frameRate, rect); + } + public float PixelToTime(float pixelX, Rect rect) + { + return pixelX * this.timeSpan / rect.width + this.minTime; + } + public float PixelDeltaToTime(Rect rect) + { + return this.timeSpan / rect.width; + } + public float SnapTimeToWholeFPS(float time) + { + return Mathf.Round(time * this.frameRate) / this.frameRate; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs b/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs new file mode 100644 index 00000000..da9b3e89 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs @@ -0,0 +1,433 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal static class AnimationWindowUtility + { + public static void CreateDefaultCurves(AnimationWindowState state, EditorCurveBinding[] properties) + { + AnimationClip activeAnimationClip = state.m_ActiveAnimationClip; + GameObject rootGameObject = state.m_RootGameObject; + properties = RotationCurveInterpolation.ConvertRotationPropertiesToDefaultInterpolation(state.m_ActiveAnimationClip, properties); + EditorCurveBinding[] array = properties; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding binding = array[i]; + state.SaveCurve(AnimationWindowUtility.CreateDefaultCurve(activeAnimationClip, rootGameObject, binding)); + } + } + public static AnimationWindowCurve CreateDefaultCurve(AnimationClip clip, GameObject rootGameObject, EditorCurveBinding binding) + { + Type editorCurveValueType = AnimationUtility.GetEditorCurveValueType(rootGameObject, binding); + AnimationWindowCurve animationWindowCurve = new AnimationWindowCurve(clip, binding, editorCurveValueType); + object currentValue = AnimationWindowUtility.GetCurrentValue(rootGameObject, binding); + if (clip.length == 0f) + { + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, currentValue, editorCurveValueType, AnimationKeyTime.Time(0f, clip.frameRate)); + } + else + { + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, currentValue, editorCurveValueType, AnimationKeyTime.Time(0f, clip.frameRate)); + AnimationWindowUtility.AddKeyframeToCurve(animationWindowCurve, currentValue, editorCurveValueType, AnimationKeyTime.Time(clip.length, clip.frameRate)); + } + return animationWindowCurve; + } + public static bool ShouldShowAnimationWindowCurve(EditorCurveBinding curveBinding) + { + return !AnimationWindowUtility.IsTransformType(curveBinding.type) || !curveBinding.propertyName.EndsWith(".w"); + } + public static bool IsNodeLeftOverCurve(AnimationWindowHierarchyNode node, GameObject rootGameObject) + { + if (rootGameObject == null) + { + return false; + } + EditorCurveBinding? binding = node.binding; + if (binding.HasValue) + { + EditorCurveBinding? binding2 = node.binding; + return AnimationUtility.GetEditorCurveValueType(rootGameObject, binding2.Value) == null; + } + if (node.hasChildren) + { + using (List.Enumerator enumerator = node.children.GetEnumerator()) + { + if (enumerator.MoveNext()) + { + TreeViewItem current = enumerator.Current; + return AnimationWindowUtility.IsNodeLeftOverCurve(current as AnimationWindowHierarchyNode, rootGameObject); + } + } + return false; + } + return false; + } + public static void AddSelectedKeyframes(AnimationWindowState state, AnimationKeyTime time) + { + foreach (AnimationWindowCurve current in state.activeCurves) + { + AnimationWindowUtility.AddKeyframeToCurve(state, current, time); + } + } + public static AnimationWindowKeyframe AddKeyframeToCurve(AnimationWindowState state, AnimationWindowCurve curve, AnimationKeyTime time) + { + object currentValue = AnimationWindowUtility.GetCurrentValue(state.m_RootGameObject, curve.binding); + Type editorCurveValueType = AnimationUtility.GetEditorCurveValueType(state.m_RootGameObject, curve.binding); + AnimationWindowKeyframe result = AnimationWindowUtility.AddKeyframeToCurve(curve, currentValue, editorCurveValueType, time); + state.SaveCurve(curve); + return result; + } + public static AnimationWindowKeyframe AddKeyframeToCurve(AnimationWindowCurve curve, object value, Type type, AnimationKeyTime time) + { + AnimationWindowKeyframe animationWindowKeyframe = curve.FindKeyAtTime(time); + if (animationWindowKeyframe != null) + { + animationWindowKeyframe.value = value; + return animationWindowKeyframe; + } + AnimationWindowKeyframe animationWindowKeyframe2 = new AnimationWindowKeyframe(); + animationWindowKeyframe2.time = time.time; + if (curve.isPPtrCurve) + { + animationWindowKeyframe2.value = value; + animationWindowKeyframe2.curve = curve; + curve.AddKeyframe(animationWindowKeyframe2, time); + } + else + { + if (type == typeof(bool) || type == typeof(float)) + { + AnimationCurve animationCurve = curve.ToAnimationCurve(); + Keyframe key = new Keyframe(time.time, (float)value); + if (type == typeof(bool)) + { + CurveUtility.SetKeyTangentMode(ref key, 0, TangentMode.Stepped); + CurveUtility.SetKeyTangentMode(ref key, 1, TangentMode.Stepped); + CurveUtility.SetKeyBroken(ref key, true); + animationWindowKeyframe2.m_TangentMode = key.tangentMode; + animationWindowKeyframe2.m_InTangent = float.PositiveInfinity; + animationWindowKeyframe2.m_OutTangent = float.PositiveInfinity; + } + else + { + int num = animationCurve.AddKey(key); + if (num != -1) + { + CurveUtility.SetKeyModeFromContext(animationCurve, num); + animationWindowKeyframe2.m_TangentMode = animationCurve[num].tangentMode; + } + } + animationWindowKeyframe2.value = value; + animationWindowKeyframe2.curve = curve; + curve.AddKeyframe(animationWindowKeyframe2, time); + } + } + return animationWindowKeyframe2; + } + public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, bool entireHierarchy) + { + List list = new List(); + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (animationWindowCurve.path.Equals(path) || (entireHierarchy && animationWindowCurve.path.Contains(path))) + { + list.Add(animationWindowCurve); + } + } + return list.ToArray(); + } + public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType) + { + List list = new List(); + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (animationWindowCurve.path.Equals(path) && animationWindowCurve.type == animatableObjectType) + { + list.Add(animationWindowCurve); + } + } + return list.ToArray(); + } + public static bool IsCurveCreated(AnimationClip clip, EditorCurveBinding binding) + { + if (binding.isPPtrCurve) + { + return AnimationUtility.GetObjectReferenceCurve(clip, binding) != null; + } + if (AnimationWindowUtility.IsRectTransformPosition(binding)) + { + binding.propertyName = binding.propertyName.Replace(".x", ".z").Replace(".y", ".z"); + } + return AnimationUtility.GetEditorCurve(clip, binding) != null; + } + public static bool IsRectTransformPosition(EditorCurveBinding curveBinding) + { + return curveBinding.type == typeof(RectTransform) && AnimationWindowUtility.GetPropertyGroupName(curveBinding.propertyName) == "m_LocalPosition"; + } + public static bool ContainsFloatKeyframes(List keyframes) + { + if (keyframes == null || keyframes.Count == 0) + { + return false; + } + foreach (AnimationWindowKeyframe current in keyframes) + { + if (!current.isPPtrCurve) + { + return true; + } + } + return false; + } + public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType, string propertyName) + { + List list = new List(); + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (animationWindowCurve.path.Equals(path) && animationWindowCurve.type == animatableObjectType && (animationWindowCurve.propertyName.Equals(propertyName) || animationWindowCurve.propertyName.Contains(propertyName))) + { + list.Add(animationWindowCurve); + } + } + return list.ToArray(); + } + public static object GetCurrentValue(GameObject rootGameObject, EditorCurveBinding curveBinding) + { + if (curveBinding.isPPtrCurve) + { + UnityEngine.Object result; + AnimationUtility.GetObjectReferenceValue(rootGameObject, curveBinding, out result); + return result; + } + float num; + AnimationUtility.GetFloatValue(rootGameObject, curveBinding, out num); + return num; + } + public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, GameObject gameObject, Type valueType) + { + EditorCurveBinding[] animatableBindings = AnimationUtility.GetAnimatableBindings(root, gameObject); + List list = new List(); + EditorCurveBinding[] array = animatableBindings; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding editorCurveBinding = array[i]; + if (AnimationUtility.GetEditorCurveValueType(root, editorCurveBinding) == valueType) + { + list.Add(editorCurveBinding); + } + } + return list.ToArray(); + } + public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, GameObject gameObject, Type objectType, Type valueType) + { + EditorCurveBinding[] animatableBindings = AnimationUtility.GetAnimatableBindings(root, gameObject); + List list = new List(); + EditorCurveBinding[] array = animatableBindings; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding editorCurveBinding = array[i]; + if (editorCurveBinding.type == objectType && AnimationUtility.GetEditorCurveValueType(root, editorCurveBinding) == valueType) + { + list.Add(editorCurveBinding); + } + } + return list.ToArray(); + } + public static bool CurveExists(EditorCurveBinding binding, AnimationWindowCurve[] curves) + { + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (binding.propertyName == animationWindowCurve.binding.propertyName && binding.type == animationWindowCurve.binding.type && binding.path == animationWindowCurve.binding.path) + { + return true; + } + } + return false; + } + public static EditorCurveBinding GetRenamedBinding(EditorCurveBinding binding, string newPath) + { + return new EditorCurveBinding + { + path = newPath, + propertyName = binding.propertyName, + type = binding.type + }; + } + public static void RenameCurvePath(AnimationWindowCurve curve, EditorCurveBinding newBinding, AnimationClip clip) + { + AnimationUtility.SetEditorCurve(clip, curve.binding, null); + AnimationUtility.SetEditorCurve(clip, newBinding, curve.ToAnimationCurve()); + } + public static string GetPropertyDisplayName(string propertyName) + { + propertyName = propertyName.Replace("m_LocalPosition", "Position"); + propertyName = propertyName.Replace("m_LocalScale", "Scale"); + propertyName = propertyName.Replace("m_LocalRotation", "Rotation"); + propertyName = propertyName.Replace("localEulerAnglesBaked", "Rotation"); + propertyName = propertyName.Replace("localEulerAngles", "Rotation"); + propertyName = propertyName.Replace("m_Materials.Array.data", "Material Reference"); + propertyName = ObjectNames.NicifyVariableName(propertyName); + propertyName = propertyName.Replace("m_", string.Empty); + return propertyName; + } + public static bool ShouldPrefixWithTypeName(Type animatableObjectType, string propertyName) + { + return animatableObjectType != typeof(Transform) && animatableObjectType != typeof(RectTransform) && (animatableObjectType != typeof(SpriteRenderer) || !(propertyName == "m_Sprite")); + } + public static string GetNicePropertyDisplayName(Type animatableObjectType, string propertyName) + { + if (AnimationWindowUtility.ShouldPrefixWithTypeName(animatableObjectType, propertyName)) + { + return ObjectNames.NicifyVariableName(animatableObjectType.Name) + "." + AnimationWindowUtility.GetPropertyDisplayName(propertyName); + } + return AnimationWindowUtility.GetPropertyDisplayName(propertyName); + } + public static string GetNicePropertyGroupDisplayName(Type animatableObjectType, string propertyGroupName) + { + if (AnimationWindowUtility.ShouldPrefixWithTypeName(animatableObjectType, propertyGroupName)) + { + return ObjectNames.NicifyVariableName(animatableObjectType.Name) + "." + AnimationWindowUtility.NicifyPropertyGroupName(animatableObjectType, propertyGroupName); + } + return AnimationWindowUtility.NicifyPropertyGroupName(animatableObjectType, propertyGroupName); + } + public static string NicifyPropertyGroupName(Type animatableObjectType, string propertyGroupName) + { + string text = AnimationWindowUtility.GetPropertyGroupName(AnimationWindowUtility.GetPropertyDisplayName(propertyGroupName)); + if (animatableObjectType == typeof(RectTransform) & text.Equals("Position")) + { + text = "Position (Z)"; + } + return text; + } + public static int GetComponentIndex(string name) + { + if (name.Length < 3 || name[name.Length - 2] != '.') + { + return -1; + } + char c = name[name.Length - 1]; + char c2 = c; + switch (c2) + { + case 'r': + return 0; + case 's': + case 't': + case 'u': + case 'v': + IL_61: + if (c2 == 'a') + { + return 3; + } + if (c2 == 'b') + { + return 2; + } + if (c2 != 'g') + { + return -1; + } + return 1; + case 'w': + return 3; + case 'x': + return 0; + case 'y': + return 1; + case 'z': + return 2; + } + goto IL_61; + } + public static string GetPropertyGroupName(string propertyName) + { + if (AnimationWindowUtility.GetComponentIndex(propertyName) != -1) + { + return propertyName.Substring(0, propertyName.Length - 2); + } + return propertyName; + } + public static float GetNextKeyframeTime(AnimationWindowCurve[] curves, float currentTime, float frameRate) + { + float num = 3.40282347E+38f; + float val = currentTime + 1f / frameRate; + bool flag = false; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + foreach (AnimationWindowKeyframe current in animationWindowCurve.m_Keyframes) + { + if (current.time < num && current.time > currentTime) + { + num = Math.Max(current.time, val); + flag = true; + } + } + } + return (!flag) ? currentTime : num; + } + public static float GetPreviousKeyframeTime(AnimationWindowCurve[] curves, float currentTime, float frameRate) + { + float num = -3.40282347E+38f; + float b = Mathf.Max(0f, currentTime - 1f / frameRate); + bool flag = false; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + foreach (AnimationWindowKeyframe current in animationWindowCurve.m_Keyframes) + { + if (current.time > num && current.time < currentTime) + { + num = Mathf.Min(current.time, b); + flag = true; + } + } + } + return (!flag) ? currentTime : num; + } + public static bool GameObjectIsAnimatable(GameObject gameObject, AnimationClip animationClip) + { + return !(gameObject == null) && (gameObject.hideFlags & HideFlags.NotEditable) == HideFlags.None && !EditorUtility.IsPersistent(gameObject) && (!(animationClip != null) || ((animationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None && AssetDatabase.IsOpenForEdit(animationClip))); + } + public static int GetPropertyNodeID(string path, Type type, string propertyName) + { + return (path + type.Name + propertyName).GetHashCode(); + } + public static Transform GetClosestAnimationComponentInParents(Transform tr) + { + while (!tr.animation && !tr.GetComponent()) + { + if (tr == tr.root) + { + return null; + } + tr = tr.parent; + } + return tr; + } + public static bool IsTransformType(Type type) + { + return type == typeof(Transform) || type == typeof(RectTransform); + } + public static bool ForceGrouping(EditorCurveBinding binding) + { + if (binding.type == typeof(Transform)) + { + return true; + } + if (binding.type == typeof(RectTransform)) + { + string propertyGroupName = AnimationWindowUtility.GetPropertyGroupName(binding.propertyName); + return propertyGroupName == "m_LocalPosition" || propertyGroupName == "m_LocalScale" || propertyGroupName == "m_LocalRotation" || propertyGroupName == "localEulerAnglesBaked" || propertyGroupName == "localEulerAngles"; + } + return false; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorCondition.cs b/UnityEditor/UnityEditorInternal/AnimatorCondition.cs new file mode 100644 index 00000000..d198da77 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorCondition.cs @@ -0,0 +1,97 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AnimatorCondition + { + private Transition m_Transition; + private int m_Index; + private bool m_Valid; + public TransitionConditionMode mode + { + get + { + return (!this.checkValid()) ? ((TransitionConditionMode)0) : this.m_Transition.GetConditionMode(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Transition.SetConditionMode(this.m_Index, value); + } + } + } + public string parameter + { + get + { + return (!this.checkValid()) ? string.Empty : this.m_Transition.GetConditionParameter(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Transition.SetConditionParameter(this.m_Index, value); + } + } + } + public float threshold + { + get + { + return (!this.checkValid()) ? 0f : this.m_Transition.GetParameterTreshold(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Transition.SetParameterTreshold(this.m_Index, value); + } + } + } + public float exitTime + { + get + { + return (!this.checkValid()) ? 0f : this.m_Transition.GetExitTime(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Transition.SetExitTime(this.m_Index, value); + } + } + } + internal AnimatorCondition(Transition transition, int index) + { + this.m_Transition = transition; + this.m_Index = index; + transition.onRemovedCondition = (Transition.RemovedCondition)Delegate.Combine(transition.onRemovedCondition, new Transition.RemovedCondition(this.RemoveCondition)); + this.m_Valid = true; + } + private bool checkValid() + { + if (!this.m_Valid) + { + Debug.LogError("AnimatorCondition is not valid anymore. It was removed"); + return false; + } + return true; + } + private void RemoveCondition(int index) + { + if (index == this.m_Index) + { + this.m_Valid = false; + } + else + { + if (index < this.m_Index) + { + this.m_Index--; + } + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorController.cs b/UnityEditor/UnityEditorInternal/AnimatorController.cs new file mode 100644 index 00000000..8c0ff384 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorController.cs @@ -0,0 +1,250 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AnimatorController : RuntimeAnimatorController + { + internal delegate void RemovedParameter(int index); + internal delegate void RemovedLayer(int index); + private const string kControllerExtension = "controller"; + public Action OnAnimatorControllerDirty; + internal AnimatorController.RemovedParameter onRemovedParameter; + internal AnimatorController.RemovedLayer onRemovedLayer; + public extern int layerCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int parameterCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool isAssetBundled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public AnimatorController() + { + AnimatorController.Internal_Create(this); + } + internal string GetDefaultBlendTreeParameter() + { + for (int i = 0; i < this.parameterCount; i++) + { + if (this.GetParameterType(i) == AnimatorControllerParameterType.Float) + { + return this.GetParameterName(i); + } + } + return "Blend"; + } + internal static void OnInvalidateAnimatorController(AnimatorController controller) + { + if (controller.OnAnimatorControllerDirty != null) + { + controller.OnAnimatorControllerDirty(); + } + } + public static AnimatorController CreateAnimatorControllerAtPath(string path) + { + AnimatorController animatorController = new AnimatorController(); + animatorController.name = Path.GetFileName(path); + AssetDatabase.CreateAsset(animatorController, path); + animatorController.AddLayer("Base Layer"); + return animatorController; + } + public static AnimationClip AllocateAnimatorClip(string name) + { + AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true); + animationClip.name = name; + return animationClip; + } + public static AnimatorController CreateAnimatorControllerForClip(AnimationClip clip, GameObject animatedObject) + { + string text = AssetDatabase.GetAssetPath(clip); + if (string.IsNullOrEmpty(text)) + { + return null; + } + text = Path.Combine(FileUtil.DeleteLastPathNameComponent(text), animatedObject.name + ".controller"); + text = AssetDatabase.GenerateUniqueAssetPath(text); + if (string.IsNullOrEmpty(text)) + { + return null; + } + return AnimatorController.CreateAnimatorControllerAtPathWithClip(text, clip); + } + public static State AddAnimationClipToController(AnimatorController controller, AnimationClip clip) + { + StateMachine layerStateMachine = controller.GetLayerStateMachine(0); + Vector3 position = (layerStateMachine.stateCount <= 0) ? new Vector3(200f, 0f, 0f) : (layerStateMachine.GetState(layerStateMachine.stateCount - 1).position + new Vector3(35f, 65f)); + State state = layerStateMachine.AddState(clip.name); + state.position = position; + state.SetAnimationClip(clip); + return state; + } + public static AnimatorController CreateAnimatorControllerAtPathWithClip(string path, AnimationClip clip) + { + AnimatorController animatorController = AnimatorController.CreateAnimatorControllerAtPath(path); + State state = animatorController.GetLayerStateMachine(0).AddState(clip.name); + state.SetAnimationClip(clip); + return animatorController; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorController mono); + public AnimatorControllerLayer GetLayer(int index) + { + return (!this.ValidateLayerIndex(index)) ? null : new AnimatorControllerLayer(this, index); + } + public AnimatorControllerLayer AddLayer(string name) + { + this.AddLayerInternal(name); + return this.GetLayer(this.layerCount - 1); + } + public void RemoveLayer(int index) + { + if (this.onRemovedLayer != null) + { + this.onRemovedLayer(index); + } + this.RemoveLayerInternal(index); + } + public AnimatorControllerParameter GetParameter(int index) + { + return (!this.ValidateParameterIndex(index)) ? null : new AnimatorControllerParameter(this, index); + } + public AnimatorControllerParameter AddParameter(string name, AnimatorControllerParameterType type) + { + this.AddParameterInternal(name, type); + return this.GetParameter(this.parameterCount - 1); + } + public void RemoveParameter(int index) + { + if (this.onRemovedParameter != null) + { + this.onRemovedParameter(index); + } + this.RemoveParameterInternal(index); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int FindParameter(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AnimatorController GetEffectiveAnimatorController(Animator behavior); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnimatorController(Animator behavior, AnimatorController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern UnityEngine.Object[] CollectObjectsUsingParameter(string parameterName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveLayerInternal(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveParameterInternal(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddParameterInternal(string name, AnimatorControllerParameterType type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddLayerInternal(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool ValidateLayerIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool ValidateParameterIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetLayerName(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerName(int index, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern StateMachine GetLayerStateMachine(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerStateMachine(int index, StateMachine value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AvatarMask GetLayerMask(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerMask(int index, AvatarMask value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimatorLayerBlendingMode GetLayerBlendingMode(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerBlendingMode(int index, AnimatorLayerBlendingMode value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int GetLayerSyncedIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerSyncedIndex(int index, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int GetLayerMotionSetIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool GetLayerIKPass(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerIKPass(int index, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool GetSyncedLayerAffectsTiming(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetSyncedLayerAffectsTiming(int index, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetLayerDefaultWeight(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLayerDefaultWeight(int index, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetParameterName(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterName(int index, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimatorControllerParameterType GetParameterType(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterType(int index, AnimatorControllerParameterType value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetParameterDefaultFloat(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterDefaultFloat(int index, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int GetParameterDefaultInt(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterDefaultInt(int index, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool GetParameterDefaultBool(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterDefaultBool(int index, bool value); + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs new file mode 100644 index 00000000..633bdce4 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs @@ -0,0 +1,153 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AnimatorControllerLayer + { + private AnimatorController m_Controller; + private int m_Index; + private bool m_Valid; + public string name + { + get + { + return (!this.checkValid()) ? string.Empty : this.m_Controller.GetLayerName(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerName(this.m_Index, value); + } + } + } + public StateMachine stateMachine + { + get + { + return (!this.checkValid()) ? null : this.m_Controller.GetLayerStateMachine(this.m_Index); + } + } + public AvatarMask avatarMask + { + get + { + return (!this.checkValid()) ? null : this.m_Controller.GetLayerMask(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerMask(this.m_Index, value); + } + } + } + public AnimatorLayerBlendingMode blendingMode + { + get + { + return (!this.checkValid()) ? AnimatorLayerBlendingMode.Override : this.m_Controller.GetLayerBlendingMode(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerBlendingMode(this.m_Index, value); + } + } + } + public int syncedLayerIndex + { + get + { + return (!this.checkValid()) ? 0 : this.m_Controller.GetLayerSyncedIndex(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerSyncedIndex(this.m_Index, value); + } + } + } + public int motionSetIndex + { + get + { + return (!this.checkValid()) ? 0 : this.m_Controller.GetLayerMotionSetIndex(this.m_Index); + } + } + public bool iKPass + { + get + { + return this.checkValid() && this.m_Controller.GetLayerIKPass(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerIKPass(this.m_Index, value); + } + } + } + public float defaultWeight + { + get + { + return (!this.checkValid()) ? 0f : this.m_Controller.GetLayerDefaultWeight(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetLayerDefaultWeight(this.m_Index, value); + } + } + } + public bool syncedLayerAffectsTiming + { + get + { + return this.checkValid() && this.m_Controller.GetSyncedLayerAffectsTiming(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetSyncedLayerAffectsTiming(this.m_Index, value); + } + } + } + public AnimatorControllerLayer(AnimatorController controller, int index) + { + this.m_Controller = controller; + this.m_Index = index; + controller.onRemovedLayer = (AnimatorController.RemovedLayer)Delegate.Combine(controller.onRemovedLayer, new AnimatorController.RemovedLayer(this.RemoveLayer)); + this.m_Valid = true; + } + private bool checkValid() + { + if (!this.m_Valid) + { + Debug.LogError("AnimatorControllerLayer is not valid anymore. It was removed"); + return false; + } + return true; + } + private void RemoveLayer(int index) + { + if (index == this.m_Index) + { + this.m_Valid = false; + } + else + { + if (index < this.m_Index) + { + this.m_Index--; + } + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs new file mode 100644 index 00000000..6491fe5d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs @@ -0,0 +1,111 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AnimatorControllerParameter + { + private AnimatorController m_Controller; + private int m_Index; + private bool m_Valid; + public string name + { + get + { + return (!this.checkValid()) ? string.Empty : this.m_Controller.GetParameterName(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetParameterName(this.m_Index, value); + } + } + } + public AnimatorControllerParameterType type + { + get + { + return (!this.checkValid()) ? AnimatorControllerParameterType.Float : this.m_Controller.GetParameterType(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetParameterType(this.m_Index, value); + } + } + } + public float defaultFloat + { + get + { + return (!this.checkValid()) ? 0f : this.m_Controller.GetParameterDefaultFloat(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetParameterDefaultFloat(this.m_Index, value); + } + } + } + public int defaultInt + { + get + { + return (!this.checkValid()) ? 0 : this.m_Controller.GetParameterDefaultInt(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetParameterDefaultInt(this.m_Index, value); + } + } + } + public bool defaultBool + { + get + { + return this.checkValid() && this.m_Controller.GetParameterDefaultBool(this.m_Index); + } + set + { + if (this.checkValid()) + { + this.m_Controller.SetParameterDefaultBool(this.m_Index, value); + } + } + } + public AnimatorControllerParameter(AnimatorController controller, int index) + { + this.m_Controller = controller; + this.m_Index = index; + this.m_Valid = true; + controller.onRemovedParameter = (AnimatorController.RemovedParameter)Delegate.Combine(controller.onRemovedParameter, new AnimatorController.RemovedParameter(this.RemoveParameter)); + } + private bool checkValid() + { + if (!this.m_Valid) + { + Debug.LogError("AnimatorControllerParameter is not valid anymore. It was removed"); + return false; + } + return true; + } + private void RemoveParameter(int index) + { + if (index == this.m_Index) + { + this.m_Valid = false; + } + else + { + if (index < this.m_Index) + { + this.m_Index--; + } + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs new file mode 100644 index 00000000..d6880970 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditorInternal +{ + public enum AnimatorControllerParameterType + { + Float = 1, + Int = 3, + Bool, + Trigger = 9 + } +} diff --git a/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs b/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs new file mode 100644 index 00000000..3c14f173 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditorInternal +{ + public enum AnimatorLayerBlendingMode + { + Override, + Additive + } +} diff --git a/UnityEditor/UnityEditorInternal/AssemblyStripper.cs b/UnityEditor/UnityEditorInternal/AssemblyStripper.cs new file mode 100644 index 00000000..6c0fc32b --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AssemblyStripper.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AssemblyStripper + { + private readonly string[] _assemblies; + private readonly string[] _searchDirs; + internal static string MonoLinkerPath + { + get + { + RuntimePlatform platform = Application.platform; + if (platform != RuntimePlatform.WindowsEditor) + { + return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Tools/UnusedByteCodeStripper/UnusedBytecodeStripper.exe"); + } + return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Tools/UnusedBytecodeStripper.exe"); + } + } + internal static string MonoLinker2Path + { + get + { + return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Tools/UnusedByteCodeStripper2/UnusedBytecodeStripper2.exe"); + } + } + internal static string BlacklistPath + { + get + { + return Path.Combine(Path.GetDirectoryName(AssemblyStripper.MonoLinkerPath), "native_link.xml"); + } + } + private AssemblyStripper(string[] assemblies, string[] searchDirs) + { + this._assemblies = assemblies; + this._searchDirs = searchDirs; + } + internal static bool Strip(string[] assemblies, string[] searchDirs, string outputFolder, string workingDirectory, out string output, out string error, string monoLinkerPath, string descriptorsFolder, IEnumerable additionalBlacklist) + { + return new AssemblyStripper(assemblies, searchDirs).Strip(outputFolder, workingDirectory, out output, out error, monoLinkerPath, descriptorsFolder, additionalBlacklist); + } + private bool Strip(string outputFolder, string workingDirectory, out string output, out string error, string monoLinkerPath, string descriptorsFolder, IEnumerable additionalBlacklist) + { + this.BackupInputFolderIfNeeded(outputFolder); + return this.StripAssembliesTo(outputFolder, workingDirectory, out output, out error, monoLinkerPath, descriptorsFolder, additionalBlacklist); + } + private void BackupInputFolderIfNeeded(string outputFolder) + { + string fullOutput = AssemblyStripper.FullPathOf(outputFolder); + if (( + from a in this._assemblies + select AssemblyStripper.FullPathOf(Path.GetDirectoryName(a))).All((string p) => string.Compare(p, fullOutput) != 0)) + { + return; + } + string text = Path.Combine(outputFolder, "not-stripped"); + FileUtil.CreateOrCleanDirectory(text); + string[] files = Directory.GetFiles(outputFolder); + for (int i = 0; i < files.Length; i++) + { + string text2 = files[i]; + File.Copy(text2, Path.Combine(text, Path.GetFileName(text2))); + } + } + private static string FullPathOf(string dir) + { + return Path.GetFullPath(dir).TrimEnd(new char[] + { + '\\' + }); + } + private bool StripAssembliesTo(string outputFolder, string workingDirectory, out string output, out string error, string linkerPath, string descriptorsFolder, IEnumerable additionalBlacklist) + { + if (!Directory.Exists(outputFolder)) + { + Directory.CreateDirectory(outputFolder); + } + additionalBlacklist = ( + from s in additionalBlacklist + select (!Path.IsPathRooted(s)) ? Path.Combine(workingDirectory, s) : s).Where(new Func(File.Exists)); + IEnumerable enumerable = + from s in Directory.GetFiles("Assets", "link.xml", SearchOption.AllDirectories) + select Path.Combine(Directory.GetCurrentDirectory(), s); + foreach (string current in enumerable) + { + Console.WriteLine("UserBlackList: " + current); + } + additionalBlacklist = additionalBlacklist.Concat(enumerable); + List list = new List + { + "-out \"" + outputFolder + "\"", + "-l none", + "-c link", + "-x \"" + AssemblyStripper.BlacklistPath + "\"", + "-f \"" + descriptorsFolder + "\"" + }; + list.AddRange( + from path in additionalBlacklist + select "-x \"" + path + "\""); + list.AddRange( + from d in this._searchDirs + select "-d \"" + d + "\""); + list.AddRange( + from assembly in this._assemblies + select "-a \"" + Path.GetFullPath(assembly) + "\""); + return AssemblyStripper.RunAssemblyLinker(list, out output, out error, linkerPath, workingDirectory); + } + private static bool RunAssemblyLinker(IEnumerable args, out string @out, out string err, string linkerPath, string workingDirectory) + { + string text = args.Aggregate((string buff, string s) => buff + " " + s); + Console.WriteLine("Invoking UnusedByteCodeStripper2 with arguments: " + text); + Runner.RunManagedProgram(linkerPath, text, workingDirectory, null); + @out = string.Empty; + err = string.Empty; + return true; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AssetStore.cs b/UnityEditor/UnityEditorInternal/AssetStore.cs new file mode 100644 index 00000000..469f8d8f --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AssetStore.cs @@ -0,0 +1,19 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + public sealed class AssetStore + { + public static void Open(string assetStoreURL) + { + if (assetStoreURL != string.Empty) + { + AssetStoreWindow.OpenURL(assetStoreURL); + } + else + { + AssetStoreWindow.Init(); + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs b/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs new file mode 100644 index 00000000..796266cc --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AssetStoreToolUtils + { + public static bool PreviewAssetStoreAssetBundleInInspector(AssetBundle bundle, AssetStoreAsset info) + { + info.id = 0; + info.previewAsset = bundle.mainAsset; + AssetStoreAssetSelection.Clear(); + AssetStoreAssetSelection.AddAssetInternal(info); + Selection.activeObject = AssetStoreAssetInspector.Instance; + AssetStoreAssetInspector.Instance.Repaint(); + return true; + } + public static void UpdatePreloadingInternal() + { + AssetStoreUtils.UpdatePreloading(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BuildAssetStoreAssetBundle(UnityEngine.Object targetObject, string targetPath); + } +} diff --git a/UnityEditor/UnityEditorInternal/AvatarMask.cs b/UnityEditor/UnityEditorInternal/AvatarMask.cs new file mode 100644 index 00000000..44f5d54d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AvatarMask.cs @@ -0,0 +1,72 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class AvatarMask : UnityEngine.Object + { + public extern int humanoidBodyPartCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int transformCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool hasFeetIK + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AvatarMask(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetHumanoidBodyPartActive(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetHumanoidBodyPartActive(int index, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetTransformPath(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTransformPath(int index, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetTransformActive(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTransformActive(int index, bool value); + public void Reset() + { + for (int i = 0; i < this.humanoidBodyPartCount; i++) + { + this.SetHumanoidBodyPartActive(i, true); + } + this.transformCount = 0; + } + public void Copy(AvatarMask other) + { + for (int i = 0; i < this.humanoidBodyPartCount; i++) + { + this.SetHumanoidBodyPartActive(i, other.GetHumanoidBodyPartActive(i)); + } + this.transformCount = other.transformCount; + for (int j = 0; j < other.transformCount; j++) + { + this.SetTransformPath(j, other.GetTransformPath(j)); + this.SetTransformActive(j, other.GetTransformActive(j)); + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/BaseIl2CppPlatformProvider.cs b/UnityEditor/UnityEditorInternal/BaseIl2CppPlatformProvider.cs new file mode 100644 index 00000000..8b840d35 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/BaseIl2CppPlatformProvider.cs @@ -0,0 +1,146 @@ +using System; +using System.IO; +using System.Linq; +using Unity.DataContract; +using UnityEditor; +using UnityEditor.Modules; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class BaseIl2CppPlatformProvider : IIl2CppPlatformProvider + { + public virtual BuildTarget target + { + get; + private set; + } + public virtual string libraryFolder + { + get; + private set; + } + public virtual bool emitNullChecks + { + get + { + return true; + } + } + public virtual bool enableStackTraces + { + get + { + return true; + } + } + public virtual bool enableArrayBoundsCheck + { + get + { + return true; + } + } + public virtual bool compactMode + { + get + { + return false; + } + } + public virtual bool loadSymbols + { + get + { + return false; + } + } + public virtual string[] includePaths + { + get + { + return new string[] + { + this.GetFolderInPackageOrDefault("bdwgc/include"), + this.GetFolderInPackageOrDefault("libil2cpp/include") + }; + } + } + public virtual string[] libraryPaths + { + get + { + return new string[] + { + this.GetFileInPackageOrDefault("bdwgc/lib/bdwgc." + this.staticLibraryExtension), + this.GetFileInPackageOrDefault("libil2cpp/lib/libil2cpp." + this.staticLibraryExtension) + }; + } + } + public virtual string nativeLibraryFileName + { + get + { + return null; + } + } + public virtual string staticLibraryExtension + { + get + { + return "a"; + } + } + public virtual string il2CppFolder + { + get + { + Unity.DataContract.PackageInfo packageInfo = BaseIl2CppPlatformProvider.FindIl2CppPackage(); + if (packageInfo == null) + { + return Path.GetFullPath(Path.Combine(EditorApplication.applicationContentsPath, (Application.platform != RuntimePlatform.OSXEditor) ? "il2cpp" : "Frameworks/il2cpp")); + } + return packageInfo.basePath; + } + } + public virtual bool usePrecompiledHeader + { + get + { + return false; + } + } + public BaseIl2CppPlatformProvider(BuildTarget target, string libraryFolder) + { + this.target = target; + this.libraryFolder = libraryFolder; + } + public virtual INativeCompiler CreateNativeCompiler() + { + return null; + } + protected string GetFolderInPackageOrDefault(string path) + { + Unity.DataContract.PackageInfo packageInfo = BaseIl2CppPlatformProvider.FindIl2CppPackage(); + if (packageInfo == null) + { + return Path.Combine(this.libraryFolder, path); + } + string text = Path.Combine(packageInfo.basePath, path); + return Directory.Exists(text) ? text : Path.Combine(this.libraryFolder, path); + } + protected string GetFileInPackageOrDefault(string path) + { + Unity.DataContract.PackageInfo packageInfo = BaseIl2CppPlatformProvider.FindIl2CppPackage(); + if (packageInfo == null) + { + return Path.Combine(this.libraryFolder, path); + } + string text = Path.Combine(packageInfo.basePath, path); + return File.Exists(text) ? text : Path.Combine(this.libraryFolder, path); + } + private static Unity.DataContract.PackageInfo FindIl2CppPackage() + { + return ModuleManager.packageManager.unityExtensions.FirstOrDefault((Unity.DataContract.PackageInfo e) => e.name == "IL2CPP"); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/BaseObjectTools.cs b/UnityEditor/UnityEditorInternal/BaseObjectTools.cs new file mode 100644 index 00000000..7672c1b5 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/BaseObjectTools.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class BaseObjectTools + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string ClassIDToString(int ID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int StringToClassID(string classString); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int StringToClassIDCaseInsensitive(string classString); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsBaseObject(int ID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsDerivedFromClassID(int classID, int derivedFromClassID); + } +} diff --git a/UnityEditor/UnityEditorInternal/BlendTree.cs b/UnityEditor/UnityEditorInternal/BlendTree.cs new file mode 100644 index 00000000..69ffbc1b --- /dev/null +++ b/UnityEditor/UnityEditorInternal/BlendTree.cs @@ -0,0 +1,136 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class BlendTree : Motion + { + public extern string blendParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string blendParameterY + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern BlendTreeType blendType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int childCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool automaticThresholds + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern int recursiveBlendParameterCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private BlendTree() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveChild(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern BlendTree AddNewBlendTree(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddAnimationClip(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Motion GetMotion(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector2 GetChildPosition(int index); + public void SetChildPosition(int index, Vector2 val) + { + BlendTree.INTERNAL_CALL_SetChildPosition(this, index, ref val); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetChildPosition(BlendTree self, int index, ref Vector2 val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SortChildren(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetChildThreshold(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetChildThreshold(int index, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetChildTimeScale(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetChildTimeScale(int index, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetRecursiveBlendParameter(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetRecursiveBlendParameterMin(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetRecursiveBlendParameterMax(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetInputBlendValue(string blendValueName, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetInputBlendValue(string blendValueName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetMotion(int index, Motion motion); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimationClip[] GetAnimationClipsFlattened(); + } +} diff --git a/UnityEditor/UnityEditorInternal/BlendTreePreviewUtility.cs b/UnityEditor/UnityEditorInternal/BlendTreePreviewUtility.cs new file mode 100644 index 00000000..4b36b233 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/BlendTreePreviewUtility.cs @@ -0,0 +1,22 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class BlendTreePreviewUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetRootBlendTreeChildWeights(Animator animator, int layerIndex, int stateHash, float[] weightArray); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CalculateRootBlendTreeChildWeights(Animator animator, int layerIndex, int stateHash, float[] weightArray, float blendX, float blendY); + public static void CalculateBlendTexture(Animator animator, int layerIndex, int stateHash, Texture2D blendTexture, Texture2D[] weightTextures, Rect rect) + { + BlendTreePreviewUtility.INTERNAL_CALL_CalculateBlendTexture(animator, layerIndex, stateHash, blendTexture, weightTextures, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_CalculateBlendTexture(Animator animator, int layerIndex, int stateHash, Texture2D blendTexture, Texture2D[] weightTextures, ref Rect rect); + } +} diff --git a/UnityEditor/UnityEditorInternal/BlendTreeType.cs b/UnityEditor/UnityEditorInternal/BlendTreeType.cs new file mode 100644 index 00000000..0cd311ec --- /dev/null +++ b/UnityEditor/UnityEditorInternal/BlendTreeType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditorInternal +{ + public enum BlendTreeType + { + Simple, + SimpleDirectional2D, + FreeformDirectional2D, + FreeformCartesian2D + } +} diff --git a/UnityEditor/UnityEditorInternal/Button.cs b/UnityEditor/UnityEditorInternal/Button.cs new file mode 100644 index 00000000..738a01ef --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Button.cs @@ -0,0 +1,58 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Button + { + public static bool Do(int id, Vector3 position, Quaternion direction, float size, float pickSize, Handles.DrawCapFunction capFunc) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (HandleUtility.nearestControl == id) + { + GUIUtility.hotControl = id; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + if (HandleUtility.nearestControl == id) + { + return true; + } + } + break; + case EventType.MouseMove: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + HandleUtility.Repaint(); + } + break; + case EventType.Repaint: + { + Color color = Handles.color; + if (HandleUtility.nearestControl == id && GUI.enabled) + { + Handles.color = Handles.selectedColor; + } + capFunc(id, position, direction, size); + Handles.color = color; + break; + } + case EventType.Layout: + if (GUI.enabled) + { + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position, pickSize)); + } + break; + } + return false; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/CameraUtility.cs b/UnityEditor/UnityEditorInternal/CameraUtility.cs new file mode 100644 index 00000000..ebaa368c --- /dev/null +++ b/UnityEditor/UnityEditorInternal/CameraUtility.cs @@ -0,0 +1,21 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class CameraUtility + { + public static bool DoesAnyCameraUseDeferred() + { + bool result = false; + Camera[] allCameras = Camera.allCameras; + for (int i = 0; i < allCameras.Length; i++) + { + if (allCameras[i].actualRenderingPath == RenderingPath.DeferredLighting) + { + result = true; + } + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/CanAppendBuild.cs b/UnityEditor/UnityEditorInternal/CanAppendBuild.cs new file mode 100644 index 00000000..9a8f565d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/CanAppendBuild.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + public enum CanAppendBuild + { + Unsupported, + Yes, + No + } +} diff --git a/UnityEditor/UnityEditorInternal/Chart.cs b/UnityEditor/UnityEditorInternal/Chart.cs new file mode 100644 index 00000000..c9dd1cbd --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Chart.cs @@ -0,0 +1,728 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Chart + { + internal enum ChartAction + { + None, + Activated, + Closed + } + internal enum ChartType + { + StackedFill, + Line + } + internal class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle leftPane = "ProfilerLeftPane"; + public GUIStyle rightPane = "ProfilerRightPane"; + public GUIStyle paneSubLabel = "ProfilerPaneSubLabel"; + public GUIStyle closeButton = "WinBtnCloseWin"; + public GUIStyle whiteLabel = "ProfilerBadge"; + public GUIStyle selectedLabel = "ProfilerSelectedLabel"; + } + public const float kSideWidth = 170f; + private const int kDistFromTopToFirstLabel = 20; + private const int kLabelHeight = 11; + private const int kCloseButtonSize = 13; + private const float kLabelXOffset = 40f; + private const float kWarningLabelHeightOffset = 43f; + private static int s_ChartHash = "Charts".GetHashCode(); + private Vector3[] m_CachedLineData; + private string m_ChartSettingsName; + private static Chart.Styles ms_Styles = null; + private int m_DragItemIndex = -1; + private Vector2 m_DragDownPos; + private int[] m_ChartOrderBackup; + private int m_MouseDownIndex = -1; + public string m_NotSupportedWarning; + public void LoadAndBindSettings(string chartSettingsName, ChartData cdata) + { + this.m_ChartSettingsName = chartSettingsName; + this.LoadChartsSettings(cdata); + } + private int MoveSelectedFrame(int selectedFrame, ChartData cdata, int direction) + { + int numberOfFrames = cdata.NumberOfFrames; + int num = selectedFrame + direction; + if (num < cdata.firstSelectableFrame || num > cdata.firstFrame + numberOfFrames) + { + return selectedFrame; + } + return num; + } + private int DoFrameSelectionDrag(float x, Rect r, ChartData cdata, int len) + { + int num = Mathf.RoundToInt((x - r.x) / r.width * (float)len - 0.5f); + GUI.changed = true; + return Mathf.Clamp(num + cdata.firstFrame, cdata.firstSelectableFrame, cdata.firstFrame + len); + } + private int HandleFrameSelectionEvents(int selectedFrame, int chartControlID, Rect chartFrame, ChartData cdata, int len) + { + Event current = Event.current; + switch (current.type) + { + case EventType.MouseDown: + if (chartFrame.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = chartControlID; + GUIUtility.hotControl = chartControlID; + selectedFrame = this.DoFrameSelectionDrag(current.mousePosition.x, chartFrame, cdata, len); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == chartControlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == chartControlID) + { + selectedFrame = this.DoFrameSelectionDrag(current.mousePosition.x, chartFrame, cdata, len); + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == chartControlID && selectedFrame >= 0) + { + if (current.keyCode == KeyCode.LeftArrow) + { + selectedFrame = this.MoveSelectedFrame(selectedFrame, cdata, -1); + current.Use(); + } + else + { + if (current.keyCode == KeyCode.RightArrow) + { + selectedFrame = this.MoveSelectedFrame(selectedFrame, cdata, 1); + current.Use(); + } + } + } + break; + } + return selectedFrame; + } + public int DoGUI(Chart.ChartType type, int selectedFrame, ChartData cdata, bool active, GUIContent icon, out Chart.ChartAction action) + { + action = Chart.ChartAction.None; + if (cdata == null) + { + return selectedFrame; + } + int numberOfFrames = cdata.NumberOfFrames; + if (Chart.ms_Styles == null) + { + Chart.ms_Styles = new Chart.Styles(); + } + int controlID = GUIUtility.GetControlID(Chart.s_ChartHash, FocusType.Keyboard); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, Chart.ms_Styles.background, new GUILayoutOption[] + { + GUILayout.MinHeight(120f) + }); + Rect rect2 = rect; + rect2.x += 170f; + rect2.width -= 170f; + Event current = Event.current; + if (current.GetTypeForControl(controlID) == EventType.MouseDown && rect.Contains(current.mousePosition)) + { + action = Chart.ChartAction.Activated; + } + if (this.m_DragItemIndex == -1) + { + selectedFrame = this.HandleFrameSelectionEvents(selectedFrame, controlID, rect2, cdata, numberOfFrames); + } + Rect rect3 = rect2; + rect3.x -= 170f; + rect3.width = 170f; + if (current.type == EventType.Repaint) + { + Chart.ms_Styles.rightPane.Draw(rect2, false, false, active, false); + Chart.ms_Styles.leftPane.Draw(rect3, EditorGUIUtility.TempContent(icon.text), false, false, active, false); + if (this.m_NotSupportedWarning == null) + { + rect2.height -= 1f; + if (type == Chart.ChartType.StackedFill) + { + this.DrawChartStacked(selectedFrame, cdata, rect2); + } + else + { + this.DrawChartLine(selectedFrame, cdata, rect2); + } + } + else + { + Rect position = rect2; + position.x += 56.1000023f; + position.y += 43f; + GUI.Label(position, this.m_NotSupportedWarning, EditorStyles.boldLabel); + } + rect3.x += 10f; + rect3.y += 10f; + GUIStyle.none.Draw(rect3, EditorGUIUtility.TempContent(icon.image), false, false, false, false); + rect3.x += 40f; + this.DrawLabelDragger(type, rect3, cdata); + } + else + { + rect3.y += 10f; + this.LabelDraggerDrag(controlID, type, cdata, rect3, active); + } + if (GUI.Button(new Rect(rect.x + 170f - 13f - 2f, rect.y + 2f, 13f, 13f), GUIContent.none, Chart.ms_Styles.closeButton)) + { + action = Chart.ChartAction.Closed; + } + return selectedFrame; + } + private void DrawSelectedFrame(int selectedFrame, ChartData cdata, Rect r) + { + if (selectedFrame - cdata.firstSelectableFrame >= 0) + { + float num = (float)cdata.NumberOfFrames; + selectedFrame -= cdata.firstFrame; + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(7); + GL.Color(new Color(1f, 1f, 1f, 0.6f)); + GL.Vertex3(r.x + r.width / num * (float)selectedFrame, r.y + 1f, 0f); + GL.Vertex3(r.x + r.width / num * (float)selectedFrame + r.width / num, r.y + 1f, 0f); + GL.Color(new Color(1f, 1f, 1f, 0.7f)); + GL.Vertex3(r.x + r.width / num * (float)selectedFrame + r.width / num, r.yMax, 0f); + GL.Vertex3(r.x + r.width / num * (float)selectedFrame, r.yMax, 0f); + GL.End(); + } + } + private void DrawChartLine(int selectedFrame, ChartData cdata, Rect r) + { + for (int i = 0; i < cdata.charts.Length; i++) + { + this.DrawChartItemLine(r, cdata, i); + } + this.DrawSelectedFrame(selectedFrame, cdata, r); + this.DrawLabelsLine(selectedFrame, cdata, r); + } + private void DrawChartStacked(int selectedFrame, ChartData cdata, Rect r) + { + HandleUtility.handleWireMaterial.SetPass(0); + float[] sumbuf = new float[cdata.NumberOfFrames]; + for (int i = 0; i < cdata.charts.Length; i++) + { + if (cdata.hasOverlay) + { + this.DrawChartItemStackedOverlay(r, i, cdata, sumbuf); + } + this.DrawChartItemStacked(r, i, cdata, sumbuf); + } + this.DrawSelectedFrame(selectedFrame, cdata, r); + this.DrawGridStacked(r, cdata); + this.DrawLabelsStacked(selectedFrame, cdata, r); + if (!cdata.hasOverlay) + { + return; + } + string text = ProfilerDriver.selectedPropertyPath; + if (text.Length > 0) + { + int num = text.LastIndexOf('/'); + if (num != -1) + { + text = text.Substring(num + 1); + } + GUIContent content = EditorGUIUtility.TempContent("Selected: " + text); + Vector2 vector = EditorStyles.whiteBoldLabel.CalcSize(content); + EditorGUI.DropShadowLabel(new Rect(r.x + r.width - vector.x - 3f, r.y + 3f, vector.x, vector.y), content, Chart.ms_Styles.selectedLabel); + } + } + private void DoLabel(float x, float y, string text, float alignment) + { + GUIContent content = new GUIContent(text); + Vector2 vector = Chart.ms_Styles.whiteLabel.CalcSize(content); + Rect position = new Rect(x + vector.x * alignment, y, vector.x, vector.y); + EditorGUI.DoDropShadowLabel(position, content, Chart.ms_Styles.whiteLabel, 0.3f); + } + private static void CorrectLabelPositions(float[] ypositions, float[] heights, float maxHeight) + { + int num = 5; + for (int i = 0; i < num; i++) + { + bool flag = false; + for (int j = 0; j < ypositions.Length; j++) + { + if (heights[j] > 0f) + { + float num2 = heights[j] / 2f; + for (int k = j + 2; k < ypositions.Length; k += 2) + { + if (heights[k] > 0f) + { + float num3 = ypositions[j] - ypositions[k]; + float num4 = (heights[j] + heights[k]) / 2f; + if (Mathf.Abs(num3) < num4) + { + num3 = (num4 - Mathf.Abs(num3)) / 2f * Mathf.Sign(num3); + ypositions[j] += num3; + ypositions[k] -= num3; + flag = true; + } + } + } + if (ypositions[j] + num2 > maxHeight) + { + ypositions[j] = maxHeight - num2; + } + if (ypositions[j] - num2 < 0f) + { + ypositions[j] = num2; + } + } + } + if (!flag) + { + break; + } + } + } + private static float GetLabelHeight(string text) + { + GUIContent content = new GUIContent(text); + return Chart.ms_Styles.whiteLabel.CalcSize(content).y; + } + private void DrawLabelsStacked(int selectedFrame, ChartData cdata, Rect r) + { + if (cdata.selectedLabels == null) + { + return; + } + int numberOfFrames = cdata.NumberOfFrames; + if (selectedFrame < cdata.firstSelectableFrame || selectedFrame >= cdata.firstFrame + numberOfFrames) + { + return; + } + selectedFrame -= cdata.firstFrame; + float x = r.x + r.width / (float)numberOfFrames * (float)selectedFrame; + float num = cdata.scale[0] * r.height; + float[] array = new float[cdata.charts.Length]; + float[] array2 = new float[array.Length]; + float num2 = 0f; + for (int i = 0; i < cdata.charts.Length; i++) + { + array[i] = -1f; + array2[i] = 0f; + int num3 = cdata.chartOrder[i]; + if (cdata.charts[num3].enabled) + { + float num4 = cdata.charts[num3].data[selectedFrame]; + if (num4 != -1f) + { + float num5 = (!cdata.hasOverlay) ? num4 : cdata.charts[num3].overlayData[selectedFrame]; + if (num5 * num > 5f) + { + array[i] = (num2 + num5 * 0.5f) * num; + array2[i] = Chart.GetLabelHeight(cdata.selectedLabels[num3]); + } + num2 += num4; + } + } + } + Chart.CorrectLabelPositions(array, array2, r.height); + for (int j = 0; j < cdata.charts.Length; j++) + { + if (array2[j] > 0f) + { + int num6 = cdata.chartOrder[j]; + Color color = cdata.charts[num6].color; + GUI.contentColor = color * 0.8f + Color.white * 0.2f; + float alignment = ((num6 & 1) != 0) ? 0.05f : -1.05f; + this.DoLabel(x, r.y + r.height - array[j] - 8f, cdata.selectedLabels[num6], alignment); + } + } + GUI.contentColor = Color.white; + } + private void DrawGridStacked(Rect r, ChartData cdata) + { + if (cdata.grid == null || cdata.gridLabels == null) + { + return; + } + GL.Begin(1); + GL.Color(new Color(1f, 1f, 1f, 0.2f)); + for (int i = 0; i < cdata.grid.Length; i++) + { + float num = r.y + r.height - cdata.grid[i] * cdata.scale[0] * r.height; + if (num > r.y) + { + GL.Vertex3(r.x + 80f, num, 0f); + GL.Vertex3(r.x + r.width, num, 0f); + } + } + GL.End(); + for (int j = 0; j < cdata.grid.Length; j++) + { + float num2 = r.y + r.height - cdata.grid[j] * cdata.scale[0] * r.height; + if (num2 > r.y) + { + this.DoLabel(r.x + 5f, num2 - 8f, cdata.gridLabels[j], 0f); + } + } + } + private void DrawLabelsLine(int selectedFrame, ChartData cdata, Rect r) + { + if (cdata.selectedLabels == null) + { + return; + } + int numberOfFrames = cdata.NumberOfFrames; + if (selectedFrame < cdata.firstSelectableFrame || selectedFrame >= cdata.firstFrame + numberOfFrames) + { + return; + } + selectedFrame -= cdata.firstFrame; + float[] array = new float[cdata.charts.Length]; + float[] array2 = new float[array.Length]; + for (int i = 0; i < cdata.charts.Length; i++) + { + array[i] = -1f; + array2[i] = 0f; + float num = cdata.charts[i].data[selectedFrame]; + if (num != -1f) + { + array[i] = num * cdata.scale[i] * r.height; + array2[i] = Chart.GetLabelHeight(cdata.selectedLabels[i]); + } + } + Chart.CorrectLabelPositions(array, array2, r.height); + float x = r.x + r.width / (float)numberOfFrames * (float)selectedFrame; + for (int j = 0; j < cdata.charts.Length; j++) + { + if (array2[j] > 0f) + { + Color color = cdata.charts[j].color; + GUI.contentColor = (color + Color.white) * 0.5f; + float alignment = ((j & 1) != 0) ? 0.05f : -1.05f; + this.DoLabel(x, r.y + r.height - array[j] - 8f, cdata.selectedLabels[j], alignment); + } + } + GUI.contentColor = Color.white; + } + private void DrawChartItemLine(Rect r, ChartData cdata, int index) + { + if (!cdata.charts[index].enabled) + { + return; + } + Color color = cdata.charts[index].color; + int numberOfFrames = cdata.NumberOfFrames; + int num = -cdata.firstFrame; + num = Mathf.Clamp(num, 0, numberOfFrames); + int num2 = numberOfFrames - num; + if (num2 <= 0) + { + return; + } + if (this.m_CachedLineData == null || numberOfFrames > this.m_CachedLineData.Length) + { + this.m_CachedLineData = new Vector3[numberOfFrames]; + } + float num3 = r.width / (float)numberOfFrames; + float num4 = r.x + num3 * 0.5f + (float)num * num3; + float height = r.height; + float y = r.y; + int i = num; + while (i < numberOfFrames) + { + float num5 = y + height; + if (cdata.charts[index].data[i] != -1f) + { + float num6 = cdata.charts[index].data[i] * cdata.scale[index] * height; + num5 -= num6; + } + this.m_CachedLineData[i - num].Set(num4, num5, 0f); + i++; + num4 += num3; + } + Handles.color = color; + Handles.DrawAAPolyLine(2f, num2, this.m_CachedLineData); + } + private void DrawChartItemStacked(Rect r, int index, ChartData cdata, float[] sumbuf) + { + int numberOfFrames = cdata.NumberOfFrames; + float num = r.width / (float)numberOfFrames; + index = cdata.chartOrder[index]; + if (!cdata.charts[index].enabled) + { + return; + } + Color color = cdata.charts[index].color; + if (cdata.hasOverlay) + { + color.r *= 0.9f; + color.g *= 0.9f; + color.b *= 0.9f; + color.a *= 0.4f; + } + Color c = color; + c.r *= 0.8f; + c.g *= 0.8f; + c.b *= 0.8f; + c.a *= 0.8f; + GL.Begin(5); + float num2 = r.x + num * 0.5f; + float height = r.height; + float y = r.y; + int i = 0; + while (i < numberOfFrames) + { + float num3 = y + height - sumbuf[i]; + float num4 = cdata.charts[index].data[i]; + if (num4 != -1f) + { + float num5 = num4 * cdata.scale[0] * height; + if (num3 - num5 < r.yMin) + { + num5 = num3 - r.yMin; + } + GL.Color(color); + GL.Vertex3(num2, num3 - num5, 0f); + GL.Color(c); + GL.Vertex3(num2, num3, 0f); + sumbuf[i] += num5; + } + i++; + num2 += num; + } + GL.End(); + } + private void DrawChartItemStackedOverlay(Rect r, int index, ChartData cdata, float[] sumbuf) + { + int numberOfFrames = cdata.NumberOfFrames; + float num = r.width / (float)numberOfFrames; + index = cdata.chartOrder[index]; + if (!cdata.charts[index].enabled) + { + return; + } + Color color = cdata.charts[index].color; + Color c = color; + c.r *= 0.8f; + c.g *= 0.8f; + c.b *= 0.8f; + c.a *= 0.8f; + GL.Begin(5); + float num2 = r.x + num * 0.5f; + float height = r.height; + float y = r.y; + int i = 0; + while (i < numberOfFrames) + { + float num3 = y + height - sumbuf[i]; + float num4 = cdata.charts[index].overlayData[i]; + if (num4 != -1f) + { + float num5 = num4 * cdata.scale[0] * height; + GL.Color(color); + GL.Vertex3(num2, num3 - num5, 0f); + GL.Color(c); + GL.Vertex3(num2, num3, 0f); + } + i++; + num2 += num; + } + GL.End(); + } + private void DrawLabelDragger(Chart.ChartType type, Rect r, ChartData cdata) + { + Vector2 mousePosition = Event.current.mousePosition; + if (type == Chart.ChartType.StackedFill) + { + int num = 0; + int i = cdata.charts.Length - 1; + while (i >= 0) + { + Rect position = (this.m_DragItemIndex != i) ? new Rect(r.x, r.y + 20f + (float)(num * 11), 170f, 11f) : new Rect(r.x, mousePosition.y - this.m_DragDownPos.y, 170f, 11f); + if (cdata.charts[cdata.chartOrder[i]].enabled) + { + GUI.backgroundColor = cdata.charts[cdata.chartOrder[i]].color; + } + else + { + GUI.backgroundColor = Color.black; + } + GUI.Label(position, cdata.charts[cdata.chartOrder[i]].name, Chart.ms_Styles.paneSubLabel); + i--; + num++; + } + } + else + { + for (int j = 0; j < cdata.charts.Length; j++) + { + Rect position2 = new Rect(r.x, r.y + 20f + (float)(j * 11), 170f, 11f); + GUI.backgroundColor = cdata.charts[j].color; + GUI.Label(position2, cdata.charts[j].name, Chart.ms_Styles.paneSubLabel); + } + } + GUI.backgroundColor = Color.white; + } + private void LabelDraggerDrag(int chartControlID, Chart.ChartType chartType, ChartData cdata, Rect r, bool active) + { + if (chartType == Chart.ChartType.Line || !active) + { + return; + } + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(chartControlID); + if (typeForControl != EventType.MouseDown && typeForControl != EventType.MouseUp && typeForControl != EventType.KeyDown && typeForControl != EventType.MouseDrag) + { + return; + } + if (typeForControl == EventType.KeyDown && current.keyCode == KeyCode.Escape && this.m_DragItemIndex != -1) + { + GUIUtility.hotControl = 0; + Array.Copy(this.m_ChartOrderBackup, cdata.chartOrder, this.m_ChartOrderBackup.Length); + this.m_DragItemIndex = -1; + current.Use(); + } + int num = 0; + int i = cdata.charts.Length - 1; + while (i >= 0) + { + if ((current.type == EventType.MouseUp && this.m_MouseDownIndex != -1) || current.type == EventType.MouseDown) + { + Rect rect = new Rect(r.x + 10f + 40f, r.y + 20f + (float)(num * 11), 9f, 9f); + if (rect.Contains(current.mousePosition)) + { + this.m_DragItemIndex = -1; + if (current.type == EventType.MouseUp && this.m_MouseDownIndex == i) + { + this.m_MouseDownIndex = -1; + cdata.charts[cdata.chartOrder[i]].enabled = !cdata.charts[cdata.chartOrder[i]].enabled; + if (chartType == Chart.ChartType.StackedFill) + { + this.SaveChartsSettingsEnabled(cdata); + } + } + else + { + this.m_MouseDownIndex = i; + } + current.Use(); + } + } + if (current.type == EventType.MouseDown) + { + Rect rect2 = new Rect(r.x, r.y + 20f + (float)(num * 11), 170f, 11f); + if (rect2.Contains(current.mousePosition)) + { + this.m_MouseDownIndex = -1; + this.m_DragItemIndex = i; + this.m_DragDownPos = current.mousePosition; + this.m_DragDownPos.x = this.m_DragDownPos.x - rect2.x; + this.m_DragDownPos.y = this.m_DragDownPos.y - rect2.y; + this.m_ChartOrderBackup = new int[cdata.chartOrder.Length]; + Array.Copy(cdata.chartOrder, this.m_ChartOrderBackup, this.m_ChartOrderBackup.Length); + GUIUtility.hotControl = chartControlID; + Event.current.Use(); + } + } + else + { + if (this.m_DragItemIndex != -1 && typeForControl == EventType.MouseDrag && i != this.m_DragItemIndex) + { + float y = current.mousePosition.y; + float num2 = r.y + 20f + (float)(num * 11); + if (y >= num2 && y < num2 + 11f) + { + int num3 = cdata.chartOrder[i]; + cdata.chartOrder[i] = cdata.chartOrder[this.m_DragItemIndex]; + cdata.chartOrder[this.m_DragItemIndex] = num3; + this.m_DragItemIndex = i; + this.SaveChartsSettingsOrder(cdata); + } + } + } + i--; + num++; + } + if (typeForControl == EventType.MouseDrag && this.m_DragItemIndex != -1) + { + current.Use(); + } + if (typeForControl == EventType.MouseUp && GUIUtility.hotControl == chartControlID) + { + GUIUtility.hotControl = 0; + this.m_DragItemIndex = -1; + current.Use(); + } + } + private void LoadChartsSettings(ChartData cdata) + { + if (string.IsNullOrEmpty(this.m_ChartSettingsName)) + { + return; + } + string @string = EditorPrefs.GetString(this.m_ChartSettingsName + "Order"); + if (!string.IsNullOrEmpty(@string)) + { + try + { + string[] array = @string.Split(new char[] + { + ',' + }); + if (array.Length == cdata.charts.Length) + { + for (int i = 0; i < cdata.charts.Length; i++) + { + cdata.chartOrder[i] = int.Parse(array[i]); + } + } + } + catch (FormatException) + { + } + } + @string = EditorPrefs.GetString(this.m_ChartSettingsName + "Visible"); + for (int j = 0; j < cdata.charts.Length; j++) + { + if (j < @string.Length && @string[j] == '0') + { + cdata.charts[j].enabled = false; + } + } + } + private void SaveChartsSettingsOrder(ChartData cdata) + { + if (string.IsNullOrEmpty(this.m_ChartSettingsName)) + { + return; + } + string text = string.Empty; + for (int i = 0; i < cdata.charts.Length; i++) + { + if (text.Length != 0) + { + text += ","; + } + text += cdata.chartOrder[i]; + } + EditorPrefs.SetString(this.m_ChartSettingsName + "Order", text); + } + private void SaveChartsSettingsEnabled(ChartData cdata) + { + string text = string.Empty; + for (int i = 0; i < cdata.charts.Length; i++) + { + text += ((!cdata.charts[i].enabled) ? '0' : '1'); + } + EditorPrefs.SetString(this.m_ChartSettingsName + "Visible", text); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ChartData.cs b/UnityEditor/UnityEditorInternal/ChartData.cs new file mode 100644 index 00000000..1f55c70d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ChartData.cs @@ -0,0 +1,46 @@ +using System; +namespace UnityEditorInternal +{ + internal class ChartData + { + public ChartSeries[] charts; + public int[] chartOrder; + public float[] scale; + public float[] grid; + public string[] gridLabels; + public string[] selectedLabels; + public int firstFrame; + public int firstSelectableFrame; + public bool hasOverlay; + public int NumberOfFrames + { + get + { + return this.charts[0].data.Length; + } + } + public void Assign(ChartSeries[] items, int firstFrame, int firstSelectableFrame) + { + this.charts = items; + this.firstFrame = firstFrame; + this.firstSelectableFrame = firstSelectableFrame; + if (this.chartOrder == null || this.chartOrder.Length != items.Length) + { + this.chartOrder = new int[items.Length]; + for (int i = 0; i < this.chartOrder.Length; i++) + { + this.chartOrder[i] = this.chartOrder.Length - 1 - i; + } + } + } + public void AssignScale(float[] scale) + { + this.scale = scale; + } + public void SetGrid(float[] grid, string[] labels) + { + this.grid = grid; + this.gridLabels = labels; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ChartSeries.cs b/UnityEditor/UnityEditorInternal/ChartSeries.cs new file mode 100644 index 00000000..decacf8f --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ChartSeries.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class ChartSeries + { + public string identifierName; + public string name; + public float[] data; + public float[] overlayData; + public Color color; + public bool enabled; + public ChartSeries(string name, int len, Color clr) + { + this.name = name; + this.identifierName = name; + this.data = new float[len]; + this.overlayData = null; + this.color = clr; + this.enabled = true; + } + public void CreateOverlayData() + { + this.overlayData = new float[this.data.Length]; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ComponentUtility.cs b/UnityEditor/UnityEditorInternal/ComponentUtility.cs new file mode 100644 index 00000000..3e8de877 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ComponentUtility.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class ComponentUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool MoveComponentUp(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool MoveComponentDown(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CopyComponent(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PasteComponentValues(Component component); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PasteComponentAsNew(GameObject go); + } +} diff --git a/UnityEditor/UnityEditorInternal/Disc.cs b/UnityEditor/UnityEditorInternal/Disc.cs new file mode 100644 index 00000000..9f56d506 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Disc.cs @@ -0,0 +1,147 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Disc + { + private static Vector2 s_StartMousePosition; + private static Vector2 s_CurrentMousePosition; + private static Vector3 s_StartPosition; + private static Vector3 s_StartAxis; + private static Quaternion s_StartRotation; + private static float s_RotationDist; + public static Quaternion Do(int id, Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) + { + if (Mathf.Abs(Vector3.Dot(Camera.current.transform.forward, axis)) > 0.999f) + { + cutoffPlane = false; + } + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + Tools.LockHandlePosition(); + if (cutoffPlane) + { + Vector3 normalized = Vector3.Cross(axis, Camera.current.transform.forward).normalized; + Disc.s_StartPosition = HandleUtility.ClosestPointToArc(position, axis, normalized, 180f, size); + } + else + { + Disc.s_StartPosition = HandleUtility.ClosestPointToDisc(position, axis, size); + } + Disc.s_RotationDist = 0f; + Disc.s_StartRotation = rotation; + Disc.s_StartAxis = axis; + Disc.s_CurrentMousePosition = (Disc.s_StartMousePosition = Event.current.mousePosition); + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + Tools.UnlockHandlePosition(); + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + bool flag = EditorGUI.actionKey && current.shift; + if (flag) + { + if (HandleUtility.ignoreRaySnapObjects == null) + { + Handles.SetupIgnoreRaySnapObjects(); + } + object obj = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(current.mousePosition)); + if (obj != null && (double)Vector3.Dot(axis.normalized, rotation * Vector3.forward) < 0.999) + { + Vector3 vector = ((RaycastHit)obj).point - position; + Vector3 forward = vector - Vector3.Dot(vector, axis.normalized) * axis.normalized; + rotation = Quaternion.LookRotation(forward, rotation * Vector3.up); + } + } + else + { + Vector3 normalized2 = Vector3.Cross(axis, position - Disc.s_StartPosition).normalized; + Disc.s_CurrentMousePosition += current.delta; + Disc.s_RotationDist = HandleUtility.CalcLineTranslation(Disc.s_StartMousePosition, Disc.s_CurrentMousePosition, Disc.s_StartPosition, normalized2) / size * 30f; + Disc.s_RotationDist = Handles.SnapValue(Disc.s_RotationDist, snap); + rotation = Quaternion.AngleAxis(Disc.s_RotationDist * -1f, Disc.s_StartAxis) * Disc.s_StartRotation; + } + GUI.changed = true; + current.Use(); + } + break; + case EventType.KeyDown: + if (current.keyCode == KeyCode.Escape && GUIUtility.hotControl == id) + { + Tools.UnlockHandlePosition(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + if (GUIUtility.hotControl == id) + { + Color color2 = Handles.color; + Vector3 normalized3 = (Disc.s_StartPosition - position).normalized; + Handles.color = Handles.secondaryColor; + Handles.DrawLine(position, position + normalized3 * size * 1.1f); + float angle = Mathf.Repeat(-Disc.s_RotationDist - 180f, 360f) - 180f; + Vector3 a = Quaternion.AngleAxis(angle, axis) * normalized3; + Handles.DrawLine(position, position + a * size * 1.1f); + Handles.color = Handles.secondaryColor * new Color(1f, 1f, 1f, 0.2f); + Handles.DrawSolidArc(position, axis, normalized3, angle, size); + Handles.color = color2; + } + if (cutoffPlane) + { + Vector3 normalized4 = Vector3.Cross(axis, Camera.current.transform.forward).normalized; + Handles.DrawWireArc(position, axis, normalized4, 180f, size); + } + else + { + Handles.DrawWireDisc(position, axis, size); + } + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + { + float distance; + if (cutoffPlane) + { + Vector3 normalized5 = Vector3.Cross(axis, Camera.current.transform.forward).normalized; + distance = HandleUtility.DistanceToArc(position, axis, normalized5, 180f, size) / 2f; + } + else + { + distance = HandleUtility.DistanceToDisc(position, axis, size) / 2f; + } + HandleUtility.AddControl(id, distance); + break; + } + } + return rotation; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/DopeLine.cs b/UnityEditor/UnityEditorInternal/DopeLine.cs new file mode 100644 index 00000000..7ed8220a --- /dev/null +++ b/UnityEditor/UnityEditorInternal/DopeLine.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class DopeLine + { + public static GUIStyle dopekeyStyle = "Dopesheetkeyframe"; + public Rect position; + public AnimationWindowCurve[] m_Curves; + public List keys; + public int m_HierarchyNodeID; + public Type objectType; + public bool tallMode; + public bool hasChildren; + public bool isMasterDopeline; + public Type valueType + { + get + { + if (this.m_Curves.Length > 0) + { + Type valueType = this.m_Curves[0].m_ValueType; + for (int i = 1; i < this.m_Curves.Length; i++) + { + if (this.m_Curves[i].m_ValueType != valueType) + { + return null; + } + } + return valueType; + } + return null; + } + } + public bool isPptrDopeline + { + get + { + if (this.m_Curves.Length > 0) + { + for (int i = 0; i < this.m_Curves.Length; i++) + { + if (!this.m_Curves[i].isPPtrCurve) + { + return false; + } + } + return true; + } + return false; + } + } + public DopeLine(int hierarchyNodeId, AnimationWindowCurve[] curves) + { + this.m_HierarchyNodeID = hierarchyNodeId; + this.m_Curves = curves; + this.LoadKeyframes(); + } + public void LoadKeyframes() + { + this.keys = new List(); + AnimationWindowCurve[] curves = this.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + foreach (AnimationWindowKeyframe current in animationWindowCurve.m_Keyframes) + { + this.keys.Add(current); + } + } + this.keys.Sort((AnimationWindowKeyframe a, AnimationWindowKeyframe b) => a.time.CompareTo(b.time)); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs b/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs new file mode 100644 index 00000000..d1d34b11 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs @@ -0,0 +1,1259 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class DopeSheetEditor : TimeArea + { + private struct DrawElement + { + public Rect position; + public Color color; + public Texture2D texture; + public DrawElement(Rect position, Color color, Texture2D texture) + { + this.position = position; + this.color = color; + this.texture = texture; + } + } + internal class DopeSheetSelectionRect + { + private enum SelectionType + { + Normal, + Additive, + Subtractive + } + private Vector2 m_SelectStartPoint; + private Vector2 m_SelectMousePoint; + private bool m_ValidRect; + private DopeSheetEditor owner; + public readonly GUIStyle createRect = "U2D.createRect"; + private static int s_RectSelectionID = GUIUtility.GetPermanentControlID(); + public DopeSheetSelectionRect(DopeSheetEditor owner) + { + this.owner = owner; + } + public void OnGUI(Rect position) + { + Event current = Event.current; + Vector2 mousePosition = current.mousePosition; + int num = DopeSheetEditor.DopeSheetSelectionRect.s_RectSelectionID; + switch (current.GetTypeForControl(num)) + { + case EventType.MouseDown: + if (current.button == 0 && position.Contains(mousePosition)) + { + GUIUtility.hotControl = num; + this.m_SelectStartPoint = mousePosition; + this.m_ValidRect = false; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == num && current.button == 0) + { + if (this.m_ValidRect) + { + if (!Event.current.control) + { + this.owner.state.ClearKeySelections(); + } + float frameRate = this.owner.state.frameRate; + Rect currentTimeRect = this.GetCurrentTimeRect(); + AnimationKeyTime animationKeyTime = AnimationKeyTime.Time(currentTimeRect.xMin, frameRate); + AnimationKeyTime animationKeyTime2 = AnimationKeyTime.Time(currentTimeRect.xMax, frameRate); + GUI.changed = true; + this.owner.state.ClearHierarchySelection(); + List list = new List(); + List list2 = new List(); + foreach (DopeLine current2 in this.owner.state.dopelines) + { + if (current2.position.yMin >= currentTimeRect.yMin && current2.position.yMax <= currentTimeRect.yMax) + { + foreach (AnimationWindowKeyframe current3 in current2.keys) + { + AnimationKeyTime animationKeyTime3 = AnimationKeyTime.Time(current3.time, frameRate); + if (((!current2.tallMode && animationKeyTime3.frame >= animationKeyTime.frame && animationKeyTime3.frame <= animationKeyTime2.frame) || (current2.tallMode && animationKeyTime3.frame >= animationKeyTime.frame && animationKeyTime3.frame < animationKeyTime2.frame)) && !list2.Contains(current3) && !list.Contains(current3)) + { + if (!this.owner.state.KeyIsSelected(current3)) + { + list2.Add(current3); + } + else + { + if (this.owner.state.KeyIsSelected(current3)) + { + list.Add(current3); + } + } + } + } + } + } + if (list2.Count == 0) + { + foreach (AnimationWindowKeyframe current4 in list) + { + this.owner.state.UnselectKey(current4); + } + } + foreach (AnimationWindowKeyframe current5 in list2) + { + this.owner.state.SelectKey(current5); + } + foreach (DopeLine current6 in this.owner.state.dopelines) + { + if (this.owner.state.AnyKeyIsSelected(current6)) + { + this.owner.state.SelectHierarchyItem(current6, true, false); + } + } + } + else + { + this.owner.state.ClearKeySelections(); + } + current.Use(); + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == num) + { + this.m_ValidRect = (Mathf.Abs((mousePosition - this.m_SelectStartPoint).x) > 1f); + if (this.m_ValidRect) + { + this.m_SelectMousePoint = new Vector2(mousePosition.x, mousePosition.y); + } + current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == num && this.m_ValidRect) + { + EditorStyles.selectionRect.Draw(this.GetCurrentPixelRect(), GUIContent.none, false, false, false, false); + } + break; + } + } + public Rect GetCurrentPixelRect() + { + float num = 16f; + Rect result = EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint); + result.xMin = this.owner.state.TimeToPixel(this.owner.state.PixelToTime(result.xMin, true), true); + result.xMax = this.owner.state.TimeToPixel(this.owner.state.PixelToTime(result.xMax, true), true); + result.yMin = Mathf.Floor(result.yMin / num) * num; + result.yMax = (Mathf.Floor(result.yMax / num) + 1f) * num; + return result; + } + public Rect GetCurrentTimeRect() + { + float num = 16f; + Rect result = EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint); + result.xMin = this.owner.state.PixelToTime(result.xMin, true); + result.xMax = this.owner.state.PixelToTime(result.xMax, true); + result.yMin = Mathf.Floor(result.yMin / num) * num; + result.yMax = (Mathf.Floor(result.yMax / num) + 1f) * num; + return result; + } + } + internal class DopeSheetPopup + { + private Rect position; + private static int s_width = 96; + private static int s_height = 112; + private Rect backgroundRect; + public DopeSheetPopup(Rect position) + { + this.position = position; + } + public void OnGUI(AnimationWindowState state, AnimationWindowKeyframe keyframe) + { + if (keyframe.isPPtrCurve) + { + return; + } + this.backgroundRect = this.position; + this.backgroundRect.x = state.TimeToPixel(keyframe.time) + this.position.x - (float)(DopeSheetEditor.DopeSheetPopup.s_width / 2); + this.backgroundRect.y = this.backgroundRect.y + 16f; + this.backgroundRect.width = (float)DopeSheetEditor.DopeSheetPopup.s_width; + this.backgroundRect.height = (float)DopeSheetEditor.DopeSheetPopup.s_height; + Rect rect = this.backgroundRect; + rect.height = 16f; + Rect rect2 = this.backgroundRect; + rect2.y += 16f; + rect2.height = (float)DopeSheetEditor.DopeSheetPopup.s_width; + GUI.Box(this.backgroundRect, string.Empty); + GUI.Box(rect2, AssetPreview.GetAssetPreview((UnityEngine.Object)keyframe.value)); + EditorGUI.BeginChangeCheck(); + UnityEngine.Object value = EditorGUI.ObjectField(rect, (UnityEngine.Object)keyframe.value, keyframe.curve.m_ValueType, false); + if (EditorGUI.EndChangeCheck()) + { + keyframe.value = value; + state.SaveCurve(keyframe.curve); + } + } + } + private const int k_KeyframeOffset = -4; + private const int k_PptrKeyframeOffset = -1; + private EditorWindow m_Owner; + private AnimationWindowState state; + private List m_KeyframeClipboard; + private DopeSheetEditor.DopeSheetSelectionRect m_SelectionRect; + private Texture m_DefaultDopeKeyIcon; + private float m_DragStartTime; + private bool m_MousedownOnKeyframe; + private bool m_IsDragging; + private bool m_IsDraggingPlayheadStarted; + private bool m_IsDraggingPlayhead; + public Bounds m_Bounds = new Bounds(Vector3.zero, Vector3.zero); + private List selectedKeysDrawBuffer; + private List unselectedKeysDrawBuffer; + private List dragdropKeysDrawBuffer; + public bool m_SpritePreviewLoading; + public int m_SpritePreviewCacheSize; + public float contentHeight + { + get + { + float num = 0f; + foreach (DopeLine current in this.state.dopelines) + { + num += ((!current.tallMode) ? 16f : 32f); + } + num += 40f; + return num; + } + } + public override Bounds drawingBounds + { + get + { + return this.m_Bounds; + } + } + internal int assetPreviewManagerID + { + get + { + return this.m_Owner.GetInstanceID(); + } + } + public DopeSheetEditor(AnimationWindowState state, EditorWindow owner) : base(false) + { + this.state = state; + this.m_Owner = owner; + this.m_DefaultDopeKeyIcon = EditorGUIUtility.LoadIcon("blendKey"); + this.m_KeyframeClipboard = new List(); + base.hSlider = true; + base.vSlider = false; + base.vRangeLocked = true; + base.hRangeMin = 0f; + base.margin = 40f; + base.scaleWithWindow = true; + base.ignoreScrollWheelUntilClicked = false; + base.hTicks.SetTickModulosForFrameRate(state.frameRate); + } + internal void OnDestroy() + { + AssetPreview.DeletePreviewTextureManagerByID(this.assetPreviewManagerID); + } + public void OnGUI(Rect position, Vector2 scrollPosition) + { + EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + this.HandleDragAndDropToEmptyArea(); + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); + GUIClip.Push(position, scrollPosition, Vector2.zero, false); + Rect position2 = new Rect(0f, 0f, position.width, position.height); + Rect rect = this.DopelinesGUI(position2, scrollPosition); + if (GUI.enabled) + { + this.HandleKeyboard(); + this.HandleDragging(); + this.HandleSelectionRect(rect); + this.HandleDelete(); + } + GUIClip.Pop(); + EditorGUI.EndDisabledGroup(); + } + public void RecalculateBounds() + { + if (this.state.m_ActiveAnimationClip) + { + this.m_Bounds.SetMinMax(new Vector3(this.state.m_ActiveAnimationClip.startTime, 0f, 0f), new Vector3(this.state.m_ActiveAnimationClip.stopTime, 0f, 0f)); + } + } + private Rect DopelinesGUI(Rect position, Vector2 scrollPosition) + { + Color color = GUI.color; + Rect position2 = position; + this.selectedKeysDrawBuffer = new List(); + this.unselectedKeysDrawBuffer = new List(); + this.dragdropKeysDrawBuffer = new List(); + if (Event.current.type == EventType.Repaint) + { + this.m_SpritePreviewLoading = false; + } + if (Event.current.type == EventType.MouseDown) + { + this.m_IsDragging = false; + } + this.UpdateSpritePreviewCacheSize(); + foreach (DopeLine current in this.state.dopelines) + { + current.position = position2; + current.position.height = ((!current.tallMode) ? 16f : 32f); + if ((current.position.yMin + scrollPosition.y >= position.yMin && current.position.yMin + scrollPosition.y <= position.yMax) || (current.position.yMax + scrollPosition.y >= position.yMin && current.position.yMax + scrollPosition.y <= position.yMax)) + { + Event current2 = Event.current; + EventType type = current2.type; + switch (type) + { + case EventType.Repaint: + this.DopeLineRepaint(current); + goto IL_1B7; + case EventType.Layout: + IL_14B: + if (type == EventType.MouseDown) + { + this.HandleMouseDown(current); + goto IL_1B7; + } + if (type != EventType.MouseUp) + { + goto IL_1B7; + } + if (current2.button == 1 && !this.m_IsDraggingPlayhead) + { + this.HandleContextMenu(current); + } + goto IL_1B7; + case EventType.DragUpdated: + case EventType.DragPerform: + if (this.state.IsEditable) + { + this.HandleDragAndDrop(current); + } + goto IL_1B7; + } + goto IL_14B; + } + IL_1B7: + position2.y += current.position.height; + } + if (Event.current.type == EventType.MouseUp) + { + this.m_IsDraggingPlayheadStarted = false; + this.m_IsDraggingPlayhead = false; + } + Rect rect = new Rect(position.xMin, position.yMin, position.width, position2.yMax - position.yMin); + this.DrawGrid(rect); + if (AnimationMode.InAnimationMode()) + { + this.DrawPlayhead(rect); + } + this.DrawElements(this.unselectedKeysDrawBuffer); + this.DrawElements(this.selectedKeysDrawBuffer); + this.DrawElements(this.dragdropKeysDrawBuffer); + GUI.color = color; + return rect; + } + private void DrawGrid(Rect position) + { + this.state.m_AnimationWindow.TimeLineGUI(position, true, false, true); + } + private void DrawPlayhead(Rect position) + { + float x = this.state.TimeToPixel(this.state.GetTimeSeconds()); + AnimationWindow.DrawPlayHead(new Vector2(x, 0f), new Vector2(x, position.height), 1f); + } + private void UpdateSpritePreviewCacheSize() + { + int num = 1; + foreach (DopeLine current in this.state.dopelines) + { + if (current.tallMode && current.isPptrDopeline) + { + num += current.keys.Count; + } + } + num += DragAndDrop.objectReferences.Length; + if (num > this.m_SpritePreviewCacheSize) + { + AssetPreview.SetPreviewTextureCacheSize(num, this.assetPreviewManagerID); + this.m_SpritePreviewCacheSize = num; + } + } + private void DrawElements(List elements) + { + Color color = GUI.color; + Color color2 = Color.white; + GUI.color = color2; + Texture defaultDopeKeyIcon = this.m_DefaultDopeKeyIcon; + foreach (DopeSheetEditor.DrawElement current in elements) + { + if (current.color != color2) + { + color2 = ((!GUI.enabled) ? (current.color * 0.8f) : current.color); + GUI.color = color2; + } + if (current.texture != null) + { + GUI.DrawTexture(current.position, current.texture); + } + else + { + Rect position = new Rect(current.position.center.x - (float)(defaultDopeKeyIcon.width / 2) - 1.5f, current.position.center.y - (float)(defaultDopeKeyIcon.height / 2), (float)defaultDopeKeyIcon.width, (float)defaultDopeKeyIcon.height); + GUI.DrawTexture(position, defaultDopeKeyIcon, ScaleMode.ScaleToFit, true, 1f); + } + } + GUI.color = color; + } + private void DopeLineRepaint(DopeLine dopeline) + { + Color color = GUI.color; + AnimationWindowHierarchyNode animationWindowHierarchyNode = (AnimationWindowHierarchyNode)this.state.m_HierarchyData.FindItem(dopeline.m_HierarchyNodeID); + bool flag = animationWindowHierarchyNode != null && animationWindowHierarchyNode.depth > 0; + Color color2 = (!flag) ? Color.gray.AlphaMultiplied(0.16f) : Color.gray.AlphaMultiplied(0.05f); + if (!dopeline.isMasterDopeline) + { + DopeSheetEditor.DrawBox(dopeline.position, color2); + } + else + { + AnimationWindow.ms_Styles.eventBackground.Draw(dopeline.position, false, false, false, false); + } + int? num = null; + int count = dopeline.keys.Count; + for (int i = 0; i < count; i++) + { + AnimationWindowKeyframe animationWindowKeyframe = dopeline.keys[i]; + if (!(num == animationWindowKeyframe.m_TimeHash)) + { + num = new int?(animationWindowKeyframe.m_TimeHash); + Rect rect = this.GetKeyframeRect(dopeline, animationWindowKeyframe); + color2 = ((!dopeline.isMasterDopeline) ? Color.gray.RGBMultiplied(1.2f) : Color.gray.RGBMultiplied(0.85f)); + Texture2D texture2D = null; + if (animationWindowKeyframe.isPPtrCurve && dopeline.tallMode) + { + texture2D = ((animationWindowKeyframe.value != null) ? AssetPreview.GetAssetPreview(((UnityEngine.Object)animationWindowKeyframe.value).GetInstanceID(), this.assetPreviewManagerID) : null); + } + if (texture2D != null) + { + rect = this.GetPreviewRectFromKeyFrameRect(rect); + color2 = Color.white.AlphaMultiplied(0.5f); + } + else + { + if (animationWindowKeyframe.value != null && animationWindowKeyframe.isPPtrCurve && dopeline.tallMode) + { + this.m_SpritePreviewLoading = true; + } + } + if (Application.platform == RuntimePlatform.WindowsEditor) + { + rect.xMin -= 0.01f; + } + if (this.AnyKeyIsSelectedAtTime(dopeline, i)) + { + color2 = ((!dopeline.tallMode || !dopeline.isPptrDopeline) ? new Color(0.34f, 0.52f, 0.85f, 1f) : Color.white); + if (dopeline.isMasterDopeline) + { + color2 = color2.RGBMultiplied(0.85f); + } + this.selectedKeysDrawBuffer.Add(new DopeSheetEditor.DrawElement(rect, color2, texture2D)); + } + else + { + this.unselectedKeysDrawBuffer.Add(new DopeSheetEditor.DrawElement(rect, color2, texture2D)); + } + } + } + if (this.state.IsEditable && this.DoDragAndDrop(dopeline, dopeline.position, false)) + { + float num2 = Mathf.Max(this.state.PixelToTime(Event.current.mousePosition.x), 0f); + Color color3 = Color.gray.RGBMultiplied(1.2f); + Texture2D texture2D2 = null; + UnityEngine.Object[] sortedDragAndDropObjectReferences = this.GetSortedDragAndDropObjectReferences(); + for (int j = 0; j < sortedDragAndDropObjectReferences.Length; j++) + { + UnityEngine.Object @object = sortedDragAndDropObjectReferences[j]; + Rect rect2 = this.GetDragAndDropRect(dopeline, this.state.TimeToPixel(num2)); + if (dopeline.isPptrDopeline && dopeline.tallMode) + { + texture2D2 = AssetPreview.GetAssetPreview(@object.GetInstanceID(), this.assetPreviewManagerID); + } + if (texture2D2 != null) + { + rect2 = this.GetPreviewRectFromKeyFrameRect(rect2); + color3 = Color.white.AlphaMultiplied(0.5f); + } + this.dragdropKeysDrawBuffer.Add(new DopeSheetEditor.DrawElement(rect2, color3, texture2D2)); + num2 += 1f / this.state.frameRate; + } + } + GUI.color = color; + } + private Rect GetPreviewRectFromKeyFrameRect(Rect keyframeRect) + { + keyframeRect.width -= 2f; + keyframeRect.height -= 2f; + keyframeRect.xMin += 2f; + keyframeRect.yMin += 2f; + return keyframeRect; + } + private Rect GetDragAndDropRect(DopeLine dopeline, float screenX) + { + Rect keyframeRect = this.GetKeyframeRect(dopeline, 0f); + float keyframeOffset = this.GetKeyframeOffset(dopeline); + float time = this.state.PixelToTime(screenX - keyframeRect.width * 0.5f, true); + keyframeRect.center = new Vector2(this.state.TimeToPixel(time) + keyframeRect.width * 0.5f + keyframeOffset, keyframeRect.center.y); + return keyframeRect; + } + private static void DrawBox(Rect position, Color color) + { + Color color2 = GUI.color; + GUI.color = color; + DopeLine.dopekeyStyle.Draw(position, GUIContent.none, 0, false); + GUI.color = color2; + } + private static void DrawLine(Vector2 p1, Vector2 p2, Color color) + { + HandleUtility.handleWireMaterial.SetPass(0); + GL.Begin(1); + GL.Color(color); + GL.Vertex(new Vector3(p1.x, p1.y, 0f)); + GL.Vertex(new Vector3(p2.x, p2.y, 0f)); + GL.End(); + GL.Color(Color.white); + } + private GenericMenu GenerateMenu(DopeLine dopeline, bool clickedEmpty) + { + GenericMenu genericMenu = new GenericMenu(); + if (AnimationMode.InAnimationMode()) + { + string text = "Add Key"; + if (clickedEmpty) + { + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.AddKeyToDopeline), dopeline); + } + else + { + genericMenu.AddDisabledItem(new GUIContent(text)); + } + text = ((this.state.selectedKeys.Count <= 1) ? "Delete Key" : "Delete Keys"); + if (this.state.selectedKeys.Count > 0) + { + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction(this.DeleteSelectedKeys)); + } + else + { + genericMenu.AddDisabledItem(new GUIContent(text)); + } + if (AnimationWindowUtility.ContainsFloatKeyframes(this.state.selectedKeys)) + { + genericMenu.AddSeparator(string.Empty); + List list = new List(); + foreach (AnimationWindowKeyframe current in this.state.selectedKeys) + { + if (!current.isPPtrCurve) + { + int keyframeIndex = current.curve.GetKeyframeIndex(AnimationKeyTime.Time(current.time, this.state.frameRate)); + if (keyframeIndex != -1) + { + CurveRenderer curveRenderer = CurveRendererCache.GetCurveRenderer(this.state.m_ActiveAnimationClip, current.curve.binding); + int curveID = CurveUtility.GetCurveID(this.state.m_ActiveAnimationClip, current.curve.binding); + list.Add(new KeyIdentifier(curveRenderer, curveID, keyframeIndex)); + } + } + } + CurveMenuManager curveMenuManager = new CurveMenuManager(this.state.m_AnimationWindow); + curveMenuManager.AddTangentMenuItems(genericMenu, list); + } + } + return genericMenu; + } + private void HandleDragging() + { + int controlID = GUIUtility.GetControlID("dopesheetdrag".GetHashCode(), FocusType.Passive, default(Rect)); + if ((Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseUp) && this.m_MousedownOnKeyframe) + { + if (Event.current.type == EventType.MouseDrag && !Event.current.control && !Event.current.shift && !this.m_IsDragging && this.state.selectedKeys.Count > 0) + { + this.m_IsDragging = true; + this.m_IsDraggingPlayheadStarted = true; + GUIUtility.hotControl = controlID; + this.m_DragStartTime = this.state.PixelToTime(Event.current.mousePosition.x); + Event.current.Use(); + } + float num = 3.40282347E+38f; + foreach (AnimationWindowKeyframe current in this.state.selectedKeys) + { + num = Mathf.Min(current.time, num); + } + float num2 = this.state.SnapToFrame(this.state.PixelToTime(Event.current.mousePosition.x)); + float deltaTime = Mathf.Max(num2 - this.m_DragStartTime, num * -1f); + if (this.m_IsDragging && !Mathf.Approximately(num2, this.m_DragStartTime)) + { + this.m_DragStartTime = num2; + this.state.MoveSelectedKeys(deltaTime, true, false); + if (this.state.activeKeyframe != null) + { + this.state.m_Frame = this.state.TimeToFrameFloor(this.state.activeKeyframe.time); + } + Event.current.Use(); + } + if (Event.current.type == EventType.MouseUp) + { + if (this.m_IsDragging && GUIUtility.hotControl == controlID) + { + this.state.MoveSelectedKeys(deltaTime, true, true); + Event.current.Use(); + this.m_IsDragging = false; + } + this.m_MousedownOnKeyframe = false; + GUIUtility.hotControl = 0; + } + } + if (this.m_IsDraggingPlayheadStarted && Event.current.type == EventType.MouseDrag && Event.current.button == 1) + { + this.m_IsDraggingPlayhead = true; + int frame = this.state.m_Frame; + if (!this.m_IsDragging) + { + frame = this.state.TimeToFrameFloor(this.state.SnapToFrame(this.state.PixelToTime(Event.current.mousePosition.x))); + } + this.state.m_AnimationWindow.PreviewFrame(frame); + Event.current.Use(); + } + } + private void HandleKeyboard() + { + if (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand) + { + string commandName = Event.current.commandName; + switch (commandName) + { + case "Copy": + if (Event.current.type == EventType.ExecuteCommand) + { + this.HandleCopy(); + } + Event.current.Use(); + break; + case "Paste": + if (Event.current.type == EventType.ExecuteCommand) + { + this.HandlePaste(); + } + Event.current.Use(); + break; + case "SelectAll": + if (Event.current.type == EventType.ExecuteCommand) + { + this.HandleSelectAll(); + } + Event.current.Use(); + break; + case "FrameSelected": + if (Event.current.type == EventType.ExecuteCommand) + { + this.FrameSelected(); + } + Event.current.Use(); + break; + } + } + } + private void HandleCopy() + { + float num = 3.40282347E+38f; + this.m_KeyframeClipboard.Clear(); + foreach (AnimationWindowKeyframe current in this.state.selectedKeys) + { + this.m_KeyframeClipboard.Add(new AnimationWindowKeyframe(current)); + if (current.time < num) + { + num = current.time; + } + } + foreach (AnimationWindowKeyframe current2 in this.m_KeyframeClipboard) + { + current2.time -= num; + } + } + private void HandlePaste() + { + this.state.ClearKeySelections(); + foreach (AnimationWindowKeyframe current in this.m_KeyframeClipboard) + { + AnimationWindowKeyframe animationWindowKeyframe = new AnimationWindowKeyframe(current); + animationWindowKeyframe.time += this.state.GetTimeSeconds(); + animationWindowKeyframe.curve.m_Keyframes.Add(animationWindowKeyframe); + this.state.SelectKey(animationWindowKeyframe); + this.state.SaveCurve(current.curve); + } + } + private void HandleSelectAll() + { + foreach (DopeLine current in this.state.dopelines) + { + foreach (AnimationWindowKeyframe current2 in current.keys) + { + this.state.SelectKey(current2); + } + this.state.SelectHierarchyItem(current, true, false); + } + } + private void HandleDelete() + { + EventType type = Event.current.type; + if (type != EventType.ValidateCommand && type != EventType.ExecuteCommand) + { + if (type == EventType.KeyDown) + { + if (Event.current.keyCode == KeyCode.Backspace || Event.current.keyCode == KeyCode.Delete) + { + this.state.DeleteSelectedKeys(); + Event.current.Use(); + } + } + } + else + { + if (Event.current.commandName == "SoftDelete" || Event.current.commandName == "Delete") + { + if (Event.current.type == EventType.ExecuteCommand) + { + this.state.DeleteSelectedKeys(); + } + Event.current.Use(); + } + } + } + private void HandleSelectionRect(Rect rect) + { + if (this.m_SelectionRect == null) + { + this.m_SelectionRect = new DopeSheetEditor.DopeSheetSelectionRect(this); + } + if (!this.m_MousedownOnKeyframe) + { + this.m_SelectionRect.OnGUI(rect); + } + } + private void HandleDragAndDropToEmptyArea() + { + Event current = Event.current; + if (current.type != EventType.DragPerform && current.type != EventType.DragUpdated) + { + return; + } + if (!DopeSheetEditor.ValidateDragAndDropObjects() || this.state.m_ActiveGameObject == null) + { + return; + } + if (DragAndDrop.objectReferences[0].GetType() != typeof(Sprite) && DragAndDrop.objectReferences[0].GetType() != typeof(Texture2D)) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + return; + } + if (current.type == EventType.DragPerform && !this.state.m_AnimationWindow.EnsureAnimationMode()) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + return; + } + if (this.DopelineForValueTypeExists(typeof(Sprite))) + { + return; + } + if (current.type == EventType.DragPerform) + { + EditorCurveBinding? spriteBinding = this.CreateNewPptrDopeline(typeof(Sprite)); + if (spriteBinding.HasValue) + { + this.DoSpriteDropAfterGeneratingNewDopeline(spriteBinding); + } + } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + current.Use(); + } + private void DoSpriteDropAfterGeneratingNewDopeline(EditorCurveBinding? spriteBinding) + { + if (DragAndDrop.objectReferences.Length == 1) + { + Analytics.Event("Sprite Drag and Drop", "Drop single sprite into empty dopesheet", "null", 1); + } + else + { + Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites into empty dopesheet", "null", 1); + } + AnimationWindowCurve animationWindowCurve = new AnimationWindowCurve(this.state.m_ActiveAnimationClip, spriteBinding.Value, typeof(Sprite)); + this.state.SaveCurve(animationWindowCurve); + this.PeformDragAndDrop(animationWindowCurve, 0f); + } + private bool DopelineForValueTypeExists(Type valueType) + { + string value = AnimationUtility.CalculateTransformPath(this.state.m_ActiveGameObject.transform, this.state.m_RootGameObject.transform); + foreach (DopeLine current in this.state.dopelines) + { + if (current.valueType == valueType) + { + AnimationWindowHierarchyNode animationWindowHierarchyNode = (AnimationWindowHierarchyNode)this.state.m_HierarchyData.FindItem(current.m_HierarchyNodeID); + if (animationWindowHierarchyNode != null && animationWindowHierarchyNode.path.Equals(value)) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + return true; + } + } + } + return false; + } + private EditorCurveBinding? CreateNewPptrDopeline(Type valueType) + { + EditorCurveBinding[] animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, valueType); + if (animatableProperties.Length == 0 && valueType == typeof(Sprite)) + { + return this.CreateNewSpriteRendererDopeline(); + } + if (animatableProperties.Length == 1) + { + return new EditorCurveBinding?(animatableProperties[0]); + } + List list = new List(); + EditorCurveBinding[] array = animatableProperties; + for (int i = 0; i < array.Length; i++) + { + EditorCurveBinding editorCurveBinding = array[i]; + list.Add(editorCurveBinding.type.Name); + } + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(list.ToArray()), -1, new EditorUtility.SelectMenuItemFunction(this.SelectTypeForCreatingNewPptrDopeline), animatableProperties); + return null; + } + private void SelectTypeForCreatingNewPptrDopeline(object userData, string[] options, int selected) + { + EditorCurveBinding[] array = userData as EditorCurveBinding[]; + if (array.Length > selected) + { + this.DoSpriteDropAfterGeneratingNewDopeline(new EditorCurveBinding?(array[selected])); + } + } + private EditorCurveBinding? CreateNewSpriteRendererDopeline() + { + if (!this.state.m_ActiveGameObject.GetComponent()) + { + this.state.m_ActiveGameObject.AddComponent(); + } + EditorCurveBinding[] animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, typeof(SpriteRenderer), typeof(Sprite)); + if (animatableProperties.Length == 1) + { + return new EditorCurveBinding?(animatableProperties[0]); + } + Debug.LogError("Unable to create animatable SpriteRenderer component"); + return null; + } + private void HandleDragAndDrop(DopeLine dopeline) + { + Event current = Event.current; + if (current.type != EventType.DragPerform && current.type != EventType.DragUpdated) + { + return; + } + if (this.DoDragAndDrop(dopeline, dopeline.position, current.type == EventType.DragPerform)) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + current.Use(); + } + else + { + DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; + } + } + private void HandleMouseDown(DopeLine dopeline) + { + Event current = Event.current; + this.state.m_AnimationWindow.EnsureAnimationMode(); + if (!current.control && !current.shift) + { + foreach (AnimationWindowKeyframe current2 in dopeline.keys) + { + if (this.GetKeyframeRect(dopeline, current2).Contains(current.mousePosition) && !this.state.KeyIsSelected(current2)) + { + this.state.ClearKeySelections(); + break; + } + } + } + float num = this.state.PixelToTime(Event.current.mousePosition.x); + float num2 = num; + if (Event.current.shift) + { + foreach (AnimationWindowKeyframe current3 in dopeline.keys) + { + if (this.state.KeyIsSelected(current3)) + { + if (current3.time < num) + { + num = current3.time; + } + if (current3.time > num2) + { + num2 = current3.time; + } + } + } + } + bool flag = false; + foreach (AnimationWindowKeyframe current4 in dopeline.keys) + { + if (this.GetKeyframeRect(dopeline, current4).Contains(current.mousePosition)) + { + flag = true; + if (!this.state.KeyIsSelected(current4)) + { + if (Event.current.shift) + { + foreach (AnimationWindowKeyframe current5 in dopeline.keys) + { + if (current5 == current4 || (current5.time > num && current5.time < num2)) + { + this.state.SelectKey(current5); + } + } + } + else + { + this.state.SelectKey(current4); + } + this.state.SelectHierarchyItem(dopeline, current.control || current.shift); + } + else + { + if (current.control) + { + this.state.UnselectKey(current4); + } + } + this.state.activeKeyframe = current4; + this.m_MousedownOnKeyframe = true; + this.state.m_Frame = this.state.TimeToFrameFloor(this.state.activeKeyframe.time); + current.Use(); + } + } + if (dopeline.position.Contains(Event.current.mousePosition)) + { + if (current.clickCount == 2 && current.button == 0 && !Event.current.shift && !Event.current.control) + { + this.HandleDopelineDoubleclick(dopeline); + } + if (current.button == 1) + { + float time = this.state.PixelToTime(Event.current.mousePosition.x, true); + AnimationKeyTime animationKeyTime = AnimationKeyTime.Time(time, this.state.frameRate); + this.state.m_Frame = animationKeyTime.frame; + if (!flag) + { + this.state.ClearKeySelections(); + this.m_IsDraggingPlayheadStarted = true; + HandleUtility.Repaint(); + current.Use(); + } + } + } + } + private void HandleDopelineDoubleclick(DopeLine dopeline) + { + this.state.ClearKeySelections(); + float time = this.state.PixelToTime(Event.current.mousePosition.x, true); + AnimationKeyTime time2 = AnimationKeyTime.Time(time, this.state.frameRate); + AnimationWindowCurve[] curves = dopeline.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve curve = curves[i]; + AnimationWindowKeyframe keyframe = AnimationWindowUtility.AddKeyframeToCurve(this.state, curve, time2); + this.state.SelectKey(keyframe); + } + this.state.m_Frame = time2.frame; + Event.current.Use(); + } + private void HandleContextMenu(DopeLine dopeline) + { + if (!dopeline.position.Contains(Event.current.mousePosition)) + { + return; + } + bool clickedEmpty = true; + foreach (AnimationWindowKeyframe current in dopeline.keys) + { + if (this.GetKeyframeRect(dopeline, current).Contains(Event.current.mousePosition)) + { + clickedEmpty = false; + break; + } + } + this.state.m_AnimationWindow.RefreshShownCurves(true); + this.GenerateMenu(dopeline, clickedEmpty).ShowAsContext(); + } + private Rect GetKeyframeRect(DopeLine dopeline, AnimationWindowKeyframe keyframe) + { + return this.GetKeyframeRect(dopeline, this.state.SnapToFrame(keyframe.time)); + } + private Rect GetKeyframeRect(DopeLine dopeline, float time) + { + if (dopeline.isPptrDopeline && dopeline.tallMode) + { + return new Rect(this.state.TimeToPixel(time) + this.GetKeyframeOffset(dopeline), dopeline.position.yMin, dopeline.position.height, dopeline.position.height); + } + return new Rect(this.state.TimeToPixel(time) + this.GetKeyframeOffset(dopeline), dopeline.position.yMin, 10f, dopeline.position.height); + } + private float GetKeyframeOffset(DopeLine dopeline) + { + if (dopeline.isPptrDopeline && dopeline.tallMode) + { + return -1f; + } + return -4f; + } + public void FrameClip() + { + if (!this.state.m_ActiveAnimationClip) + { + return; + } + float max = Mathf.Max(this.state.m_ActiveAnimationClip.length, 1f); + base.SetShownHRangeInsideMargins(0f, max); + } + public void FrameSelected() + { + float num = 3.40282347E+38f; + float num2 = -3.40282347E+38f; + bool flag = this.state.selectedKeys.Count > 0; + if (flag) + { + foreach (AnimationWindowKeyframe current in this.state.selectedKeys) + { + num = Mathf.Min(current.time, num); + num2 = Mathf.Max(current.time, num2); + } + } + bool flag2 = !flag; + if (!flag) + { + bool flag3 = this.state.m_hierarchyState.selectedIDs.Count > 0; + if (flag3) + { + foreach (AnimationWindowCurve current2 in this.state.activeCurves) + { + int count = current2.m_Keyframes.Count; + if (count > 1) + { + num = Mathf.Min(current2.m_Keyframes[0].time, num); + num2 = Mathf.Max(current2.m_Keyframes[count - 1].time, num2); + flag2 = false; + } + } + } + } + if (flag2) + { + this.FrameClip(); + } + else + { + float num3 = this.state.FrameToTime(Mathf.Min(4f, this.state.frameRate)); + num3 = Mathf.Min(num3, Mathf.Max(this.state.m_ActiveAnimationClip.length, this.state.FrameToTime(4f))); + num2 = Mathf.Max(num2, num + num3); + base.SetShownHRangeInsideMargins(num, num2); + } + } + private bool DoDragAndDrop(DopeLine dopeLine, Rect position, bool perform) + { + return this.DoDragAndDrop(dopeLine, position, false, perform); + } + private bool DoDragAndDrop(DopeLine dopeLine, bool perform) + { + return this.DoDragAndDrop(dopeLine, default(Rect), true, perform); + } + private bool DoDragAndDrop(DopeLine dopeLine, Rect position, bool ignoreMousePosition, bool perform) + { + if (!ignoreMousePosition && !position.Contains(Event.current.mousePosition)) + { + return false; + } + if (!DopeSheetEditor.ValidateDragAndDropObjects()) + { + return false; + } + Type type = DragAndDrop.objectReferences[0].GetType(); + AnimationWindowCurve animationWindowCurve = null; + if (dopeLine.valueType == type) + { + animationWindowCurve = dopeLine.m_Curves[0]; + } + else + { + AnimationWindowCurve[] curves = dopeLine.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve2 = curves[i]; + if (animationWindowCurve2.isPPtrCurve) + { + if (animationWindowCurve2.m_ValueType == type) + { + animationWindowCurve = animationWindowCurve2; + } + if (animationWindowCurve2.m_ValueType == typeof(Sprite) && SpriteUtility.GetSpriteFromDraggedPathsOrObjects() != null) + { + animationWindowCurve = animationWindowCurve2; + type = typeof(Sprite); + } + } + } + } + bool result = true; + if (animationWindowCurve != null) + { + if (perform) + { + if (DragAndDrop.objectReferences.Length == 1) + { + Analytics.Event("Sprite Drag and Drop", "Drop single sprite into existing dopeline", "null", 1); + } + else + { + Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites into existing dopeline", "null", 1); + } + Rect dragAndDropRect = this.GetDragAndDropRect(dopeLine, Event.current.mousePosition.x); + float time = this.state.PixelToTime(dragAndDropRect.xMin, true); + AnimationWindowCurve curveOfType = this.GetCurveOfType(dopeLine, type); + this.PeformDragAndDrop(curveOfType, time); + } + } + else + { + result = false; + } + return result; + } + private void PeformDragAndDrop(AnimationWindowCurve targetCurve, float time) + { + if (DragAndDrop.objectReferences.Length == 0 || targetCurve == null) + { + return; + } + this.state.ClearKeySelections(); + UnityEngine.Object[] sortedDragAndDropObjectReferences = this.GetSortedDragAndDropObjectReferences(); + UnityEngine.Object[] array = sortedDragAndDropObjectReferences; + for (int i = 0; i < array.Length; i++) + { + UnityEngine.Object @object = array[i]; + UnityEngine.Object object2 = @object; + if (object2 is Texture2D) + { + object2 = SpriteUtility.TextureToSprite(@object as Texture2D); + } + this.CreateNewPPtrKeyframe(time, object2, targetCurve); + time += 1f / this.state.m_ActiveAnimationClip.frameRate; + } + this.state.SaveCurve(targetCurve); + DragAndDrop.AcceptDrag(); + } + private UnityEngine.Object[] GetSortedDragAndDropObjectReferences() + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + Array.Sort(objectReferences, (UnityEngine.Object a, UnityEngine.Object b) => EditorUtility.NaturalCompare(a.name, b.name)); + return objectReferences; + } + private void CreateNewPPtrKeyframe(float time, UnityEngine.Object value, AnimationWindowCurve targetCurve) + { + AnimationWindowKeyframe animationWindowKeyframe = new AnimationWindowKeyframe(targetCurve, new ObjectReferenceKeyframe + { + time = time, + value = value + }); + AnimationKeyTime keyTime = AnimationKeyTime.Time(animationWindowKeyframe.time, this.state.frameRate); + targetCurve.AddKeyframe(animationWindowKeyframe, keyTime); + this.state.SelectKey(animationWindowKeyframe); + } + private static bool ValidateDragAndDropObjects() + { + if (DragAndDrop.objectReferences.Length == 0) + { + return false; + } + for (int i = 0; i < DragAndDrop.objectReferences.Length; i++) + { + UnityEngine.Object @object = DragAndDrop.objectReferences[i]; + if (@object == null) + { + return false; + } + if (i < DragAndDrop.objectReferences.Length - 1) + { + UnityEngine.Object object2 = DragAndDrop.objectReferences[i + 1]; + bool flag = (@object is Texture2D || @object is Sprite) && (object2 is Texture2D || object2 is Sprite); + if (@object.GetType() != object2.GetType() && !flag) + { + return false; + } + } + } + return true; + } + private AnimationWindowCurve GetCurveOfType(DopeLine dopeLine, Type type) + { + AnimationWindowCurve[] curves = dopeLine.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve animationWindowCurve = curves[i]; + if (animationWindowCurve.m_ValueType == type) + { + return animationWindowCurve; + } + } + return null; + } + private bool AnyKeyIsSelectedAtTime(DopeLine dopeLine, int keyIndex) + { + int timeHash = dopeLine.keys[keyIndex].m_TimeHash; + int count = dopeLine.keys.Count; + for (int i = keyIndex; i < count; i++) + { + AnimationWindowKeyframe animationWindowKeyframe = dopeLine.keys[i]; + if (animationWindowKeyframe.m_TimeHash != timeHash) + { + return false; + } + if (this.state.KeyIsSelected(animationWindowKeyframe)) + { + return true; + } + } + return false; + } + private void AddKeyToDopeline(object obj) + { + this.AddKeyToDopeline((DopeLine)obj); + } + private void AddKeyToDopeline(DopeLine dopeLine) + { + this.state.ClearKeySelections(); + AnimationWindowCurve[] curves = dopeLine.m_Curves; + for (int i = 0; i < curves.Length; i++) + { + AnimationWindowCurve curve = curves[i]; + AnimationWindowKeyframe keyframe = AnimationWindowUtility.AddKeyframeToCurve(this.state, curve, this.state.time); + this.state.SelectKey(keyframe); + } + } + private void DeleteSelectedKeys() + { + this.state.DeleteSelectedKeys(); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/EditorResourcesUtility.cs b/UnityEditor/UnityEditorInternal/EditorResourcesUtility.cs new file mode 100644 index 00000000..25c8d4dd --- /dev/null +++ b/UnityEditor/UnityEditorInternal/EditorResourcesUtility.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class EditorResourcesUtility + { + public static extern string lightSkinSourcePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string darkSkinSourcePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string fontsPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string brushesPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string iconsPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string generatedIconsPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string folderIconName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string emptyFolderIconName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/FreeMove.cs b/UnityEditor/UnityEditorInternal/FreeMove.cs new file mode 100644 index 00000000..dd1915c6 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FreeMove.cs @@ -0,0 +1,139 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class FreeMove + { + private static Vector2 s_StartMousePosition; + private static Vector2 s_CurrentMousePosition; + private static Vector3 s_StartPosition; + public static Vector3 Do(int id, Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.DrawCapFunction capFunc) + { + Vector3 position2 = Handles.matrix.MultiplyPoint(position); + Matrix4x4 matrix = Handles.matrix; + VertexSnapping.HandleKeyAndMouseMove(id); + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + FreeMove.s_CurrentMousePosition = (FreeMove.s_StartMousePosition = current.mousePosition); + FreeMove.s_StartPosition = position; + HandleUtility.ignoreRaySnapObjects = null; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + HandleUtility.ignoreRaySnapObjects = null; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + bool flag = EditorGUI.actionKey && current.shift; + if (flag) + { + if (HandleUtility.ignoreRaySnapObjects == null) + { + Handles.SetupIgnoreRaySnapObjects(); + } + object obj = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(current.mousePosition)); + if (obj != null) + { + RaycastHit raycastHit = (RaycastHit)obj; + float d = 0f; + if (Tools.pivotMode == PivotMode.Center) + { + float num = HandleUtility.CalcRayPlaceOffset(HandleUtility.ignoreRaySnapObjects, raycastHit.normal); + if (num != float.PositiveInfinity) + { + d = Vector3.Dot(position, raycastHit.normal) - num; + } + } + position = Handles.s_InverseMatrix.MultiplyPoint(raycastHit.point + raycastHit.normal * d); + } + else + { + flag = false; + } + } + if (!flag) + { + FreeMove.s_CurrentMousePosition += new Vector2(current.delta.x, -current.delta.y); + Vector3 vector = Camera.current.WorldToScreenPoint(Handles.s_Matrix.MultiplyPoint(FreeMove.s_StartPosition)); + vector += FreeMove.s_CurrentMousePosition - FreeMove.s_StartMousePosition; + position = Handles.s_InverseMatrix.MultiplyPoint(Camera.current.ScreenToWorldPoint(vector)); + if (Camera.current.transform.forward == Vector3.forward || Camera.current.transform.forward == -Vector3.forward) + { + position.z = FreeMove.s_StartPosition.z; + } + if (Camera.current.transform.forward == Vector3.up || Camera.current.transform.forward == -Vector3.up) + { + position.y = FreeMove.s_StartPosition.y; + } + if (Camera.current.transform.forward == Vector3.right || Camera.current.transform.forward == -Vector3.right) + { + position.x = FreeMove.s_StartPosition.x; + } + if (Tools.vertexDragging) + { + if (HandleUtility.ignoreRaySnapObjects == null) + { + Handles.SetupIgnoreRaySnapObjects(); + } + Vector3 v; + if (HandleUtility.FindNearestVertex(current.mousePosition, null, out v)) + { + position = Handles.s_InverseMatrix.MultiplyPoint(v); + } + } + if (EditorGUI.actionKey && !current.shift) + { + Vector3 b = position - FreeMove.s_StartPosition; + b.x = Handles.SnapValue(b.x, snap.x); + b.y = Handles.SnapValue(b.y, snap.y); + b.z = Handles.SnapValue(b.z, snap.z); + position = FreeMove.s_StartPosition + b; + } + } + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + Handles.matrix = Matrix4x4.identity; + capFunc(id, position2, Camera.current.transform.rotation, size); + Handles.matrix = matrix; + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + Handles.matrix = Matrix4x4.identity; + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position2, size * 1.2f)); + Handles.matrix = matrix; + break; + } + return position; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/FreeRotate.cs b/UnityEditor/UnityEditorInternal/FreeRotate.cs new file mode 100644 index 00000000..bc2e93b0 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FreeRotate.cs @@ -0,0 +1,106 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class FreeRotate + { + private static Vector2 s_CurrentMousePosition; + public static Quaternion Do(int id, Quaternion rotation, Vector3 position, float size) + { + Vector3 vector = Handles.matrix.MultiplyPoint(position); + Matrix4x4 matrix = Handles.matrix; + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + Tools.LockHandlePosition(); + FreeRotate.s_CurrentMousePosition = current.mousePosition; + HandleUtility.ignoreRaySnapObjects = null; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + Tools.UnlockHandlePosition(); + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + bool flag = EditorGUI.actionKey && current.shift; + if (flag) + { + if (HandleUtility.ignoreRaySnapObjects == null) + { + Handles.SetupIgnoreRaySnapObjects(); + } + object obj = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(current.mousePosition)); + if (obj != null) + { + Quaternion quaternion = Quaternion.LookRotation(((RaycastHit)obj).point - position); + if (Tools.pivotRotation == PivotRotation.Global) + { + Transform activeTransform = Selection.activeTransform; + if (activeTransform) + { + Quaternion rhs = Quaternion.Inverse(activeTransform.rotation) * rotation; + quaternion *= rhs; + } + } + rotation = quaternion; + } + } + else + { + FreeRotate.s_CurrentMousePosition += current.delta; + Vector3 vector2 = Camera.current.transform.TransformDirection(new Vector3(-current.delta.y, -current.delta.x, 0f)); + rotation = Quaternion.AngleAxis(current.delta.magnitude, vector2.normalized) * rotation; + } + GUI.changed = true; + current.Use(); + } + break; + case EventType.KeyDown: + if (current.keyCode == KeyCode.Escape && GUIUtility.hotControl == id) + { + Tools.UnlockHandlePosition(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + Handles.matrix = Matrix4x4.identity; + Handles.DrawWireDisc(vector, Camera.current.transform.forward, size); + Handles.matrix = matrix; + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + Handles.matrix = Matrix4x4.identity; + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(vector, size) + 5f); + Handles.matrix = matrix; + break; + } + return rotation; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/GradientPreviewCache.cs b/UnityEditor/UnityEditorInternal/GradientPreviewCache.cs new file mode 100644 index 00000000..7cb925a0 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/GradientPreviewCache.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class GradientPreviewCache + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearCache(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetPropertyPreview(SerializedProperty property); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetGradientPreview(Gradient curve); + } +} diff --git a/UnityEditor/UnityEditorInternal/IIl2CppPlatformProvider.cs b/UnityEditor/UnityEditorInternal/IIl2CppPlatformProvider.cs new file mode 100644 index 00000000..6d994551 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/IIl2CppPlatformProvider.cs @@ -0,0 +1,53 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + internal interface IIl2CppPlatformProvider + { + BuildTarget target + { + get; + } + bool emitNullChecks + { + get; + } + bool enableStackTraces + { + get; + } + bool enableArrayBoundsCheck + { + get; + } + bool compactMode + { + get; + } + bool loadSymbols + { + get; + } + string nativeLibraryFileName + { + get; + } + string il2CppFolder + { + get; + } + bool usePrecompiledHeader + { + get; + } + string[] includePaths + { + get; + } + string[] libraryPaths + { + get; + } + INativeCompiler CreateNativeCompiler(); + } +} diff --git a/UnityEditor/UnityEditorInternal/IL2CPPBuilder.cs b/UnityEditor/UnityEditorInternal/IL2CPPBuilder.cs new file mode 100644 index 00000000..2eef4648 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/IL2CPPBuilder.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using UnityEditor; +using UnityEditor.Scripting.Compilers; +namespace UnityEditorInternal +{ + internal class IL2CPPBuilder + { + private readonly string m_TempFolder; + private readonly string m_StagingAreaData; + private readonly IIl2CppPlatformProvider m_PlatformProvider; + private readonly Action m_ModifyOutputBeforeCompile; + private readonly RuntimeClassRegistry m_RuntimeClassRegistry; + private string[] Il2CppBlacklistPaths + { + get + { + return new string[] + { + Path.Combine("..", "platform_native_link.xml") + }; + } + } + public IL2CPPBuilder(string tempFolder, string stagingAreaData, IIl2CppPlatformProvider platformProvider, Action modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry) + { + this.m_TempFolder = tempFolder; + this.m_StagingAreaData = stagingAreaData; + this.m_PlatformProvider = platformProvider; + this.m_ModifyOutputBeforeCompile = modifyOutputBeforeCompile; + this.m_RuntimeClassRegistry = runtimeClassRegistry; + } + public void Run() + { + string cppOutputDirectoryInStagingArea = this.GetCppOutputDirectoryInStagingArea(); + string fullPath = Path.GetFullPath(Path.Combine(this.m_StagingAreaData, "Managed")); + string[] files = Directory.GetFiles(fullPath); + for (int i = 0; i < files.Length; i++) + { + string fileName = files[i]; + FileInfo fileInfo = new FileInfo(fileName); + fileInfo.IsReadOnly = false; + } + this.PatchAssemblies(); + this.StripAssemblies(this.GetUserAssemblies(fullPath), fullPath); + this.ConvertPlayerDlltoCpp(this.GetUserAssembliesOrUnityEngine(fullPath), cppOutputDirectoryInStagingArea, fullPath); + if (this.m_ModifyOutputBeforeCompile != null) + { + this.m_ModifyOutputBeforeCompile(cppOutputDirectoryInStagingArea); + } + INativeCompiler nativeCompiler = this.m_PlatformProvider.CreateNativeCompiler(); + if (nativeCompiler != null) + { + string text = Path.Combine(this.m_StagingAreaData, "Native"); + Directory.CreateDirectory(text); + text = Path.Combine(text, this.m_PlatformProvider.nativeLibraryFileName); + List list = new List(this.m_PlatformProvider.includePaths); + list.Add(cppOutputDirectoryInStagingArea); + this.m_PlatformProvider.CreateNativeCompiler().CompileDynamicLibrary(text, NativeCompiler.AllSourceFilesIn(cppOutputDirectoryInStagingArea), list, this.m_PlatformProvider.libraryPaths, new string[0]); + } + } + private string[] GetUserAssembliesOrUnityEngine(string managedDir) + { + string[] array = this.GetUserAssemblies(managedDir); + if (array.Length == 0) + { + array = Directory.GetFiles(managedDir, "UnityEngine.dll", SearchOption.TopDirectoryOnly); + } + return array; + } + private bool HasStrippingInformation() + { + return this.m_RuntimeClassRegistry != null && this.m_RuntimeClassRegistry.UsedTypePerUserAssembly != null; + } + private bool ShouldAddUGUIAsUserAssembly() + { + return !this.HasStrippingInformation() || this.m_RuntimeClassRegistry.IsUGUIUsed(); + } + private string[] GetUserAssemblies(string managedDir) + { + return ( + from s in this.m_RuntimeClassRegistry.GetUserAssemblies() + select Path.Combine(managedDir, s)).ToArray(); + } + private IEnumerable GetAssembliesInDirectory(string assemblyName, string managedDir) + { + return Directory.GetFiles(managedDir, assemblyName, SearchOption.TopDirectoryOnly); + } + public string GetCppOutputDirectoryInStagingArea() + { + return Path.Combine(this.m_TempFolder, "il2cppOutput"); + } + private void PatchAssemblies() + { + string fullPath = Path.GetFullPath(this.m_StagingAreaData + "/Managed"); + string text = fullPath + "/mscorlib.dll"; + string text2 = fullPath + "/mscorlib.unpatched.dll"; + File.Move(text, text2); + File.Copy(this.m_PlatformProvider.il2CppFolder + "/replacements.dll", fullPath + "/replacements.dll"); + Runner.RunManagedProgram(this.m_PlatformProvider.il2CppFolder + "/AssemblyPatcher/AssemblyPatcher.exe", string.Format("-a \"{0}\" -o \"{1}\" -c \"{2}\" --log-config \"{3}\" -s \"{4}\"", new object[] + { + text2, + text, + this.m_PlatformProvider.il2CppFolder + "/assemblypatcher_config.txt", + this.m_PlatformProvider.il2CppFolder + "/AssemblyPatcher.Log.Config.xml", + Path.GetFullPath(this.m_StagingAreaData + "/Managed") + })); + File.Delete(text2); + } + private void ConvertPlayerDlltoCpp(ICollection userAssemblies, string outputDirectory, string workingDirectory) + { + if (userAssemblies.Count == 0) + { + Directory.CreateDirectory(outputDirectory); + return; + } + string il2CppExe = this.GetIl2CppExe(); + List list = new List(); + list.Add("--copy-level=None"); + list.Add("--enable-generic-sharing"); + list.Add("--enable-unity-event-support"); + if (this.m_PlatformProvider.usePrecompiledHeader) + { + list.Add("--use-precompiled-header"); + } + if (this.m_PlatformProvider.emitNullChecks) + { + list.Add("--emit-null-checks"); + } + if (this.m_PlatformProvider.enableStackTraces) + { + list.Add("--enable-stacktrace"); + } + if (this.m_PlatformProvider.enableArrayBoundsCheck) + { + list.Add("--enable-array-bounds-check"); + } + if (this.m_PlatformProvider.compactMode) + { + list.Add("--output-format=Compact"); + } + if (this.m_PlatformProvider.loadSymbols) + { + list.Add("--enable-symbol-loading"); + } + string empty = string.Empty; + if (PlayerSettings.GetPropertyOptionalString("additionalIl2CppArgs", ref empty)) + { + list.Add(empty); + } + List source = new List(userAssemblies) + { + outputDirectory + }; + list.AddRange( + from arg in source + select "\"" + Path.GetFullPath(arg) + "\""); + string text = list.Aggregate(string.Empty, (string current, string arg) => current + arg + " "); + Console.WriteLine("Invoking il2cpp with arguments: " + text); + Runner.RunManagedProgram(il2CppExe, text, workingDirectory, new Il2CppOutputParser()); + } + private void StripAssemblies(string[] assemblies, string managedAssemblyFolderPath) + { + List list = new List(); + list.AddRange(assemblies); + string[] assembliesToStrip = list.ToArray(); + string[] searchDirs = new string[] + { + managedAssemblyFolderPath + }; + this.RunAssemblyStripper(assemblies, managedAssemblyFolderPath, assembliesToStrip, searchDirs, AssemblyStripper.MonoLinker2Path); + } + private void RunAssemblyStripper(IEnumerable assemblies, string managedAssemblyFolderPath, string[] assembliesToStrip, string[] searchDirs, string monoLinkerPath) + { + IEnumerable enumerable = this.Il2CppBlacklistPaths; + if (this.m_RuntimeClassRegistry != null) + { + enumerable = enumerable.Concat(new string[] + { + this.WriteMethodsToPreserveBlackList() + }); + } + string text; + string text2; + if (AssemblyStripper.Strip(assembliesToStrip, searchDirs, managedAssemblyFolderPath, managedAssemblyFolderPath, out text, out text2, monoLinkerPath, Path.Combine(this.m_PlatformProvider.il2CppFolder, "LinkerDescriptors"), enumerable)) + { + return; + } + throw new Exception(string.Concat(new object[] + { + "Error in stripping assemblies: ", + assemblies, + ", ", + text2 + })); + } + private string WriteMethodsToPreserveBlackList() + { + string text = Directory.GetCurrentDirectory() + "/" + this.m_StagingAreaData + "/methods_pointedto_by_uievents.xml"; + File.WriteAllText(text, this.GetMethodPreserveBlacklistContents()); + return text; + } + private string GetMethodPreserveBlacklistContents() + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine(""); + IEnumerable> enumerable = + from m in this.m_RuntimeClassRegistry.GetMethodsToPreserve() + group m by m.assembly; + foreach (IGrouping current in enumerable) + { + stringBuilder.AppendLine(string.Format("\t", current.Key)); + IEnumerable> enumerable2 = + from m in current + group m by m.fullTypeName; + foreach (IGrouping current2 in enumerable2) + { + stringBuilder.AppendLine(string.Format("\t\t", current2.Key)); + foreach (RuntimeClassRegistry.MethodDescription current3 in current2) + { + stringBuilder.AppendLine(string.Format("\t\t\t", current3.methodName)); + } + stringBuilder.AppendLine("\t\t"); + } + stringBuilder.AppendLine("\t"); + } + stringBuilder.AppendLine(""); + return stringBuilder.ToString(); + } + private string GetIl2CppExe() + { + return this.m_PlatformProvider.il2CppFolder + "/il2cpp.exe"; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/IL2CPPUtils.cs b/UnityEditor/UnityEditorInternal/IL2CPPUtils.cs new file mode 100644 index 00000000..ff416f88 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/IL2CPPUtils.cs @@ -0,0 +1,34 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class IL2CPPUtils + { + internal static string editorIl2cppFolder + { + get + { + string path = (Application.platform != RuntimePlatform.OSXEditor) ? "il2cpp" : "Frameworks/il2cpp"; + return Path.GetFullPath(Path.Combine(EditorApplication.applicationContentsPath, path)); + } + } + internal static IIl2CppPlatformProvider PlatformProviderForNotModularPlatform(BuildTarget target, bool developmentBuild) + { + throw new Exception("Platform unsupported, or already modular."); + } + internal static IL2CPPBuilder RunIl2Cpp(string tempFolder, string stagingAreaData, IIl2CppPlatformProvider platformProvider, Action modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry) + { + IL2CPPBuilder iL2CPPBuilder = new IL2CPPBuilder(tempFolder, stagingAreaData, platformProvider, modifyOutputBeforeCompile, runtimeClassRegistry); + iL2CPPBuilder.Run(); + return iL2CPPBuilder; + } + internal static IL2CPPBuilder RunIl2Cpp(string stagingAreaData, IIl2CppPlatformProvider platformProvider, Action modifyOutputBeforeCompile, RuntimeClassRegistry runtimeClassRegistry) + { + IL2CPPBuilder iL2CPPBuilder = new IL2CPPBuilder(stagingAreaData, stagingAreaData, platformProvider, modifyOutputBeforeCompile, runtimeClassRegistry); + iL2CPPBuilder.Run(); + return iL2CPPBuilder; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs b/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs new file mode 100644 index 00000000..0bfcc78e --- /dev/null +++ b/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditorInternal +{ + internal interface IProfilerWindowController + { + void SetSelectedPropertyPath(string path); + void ClearSelectedPropertyPath(); + ProfilerProperty CreateProperty(bool details); + void Repaint(); + } +} diff --git a/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs b/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs new file mode 100644 index 00000000..efd132bc --- /dev/null +++ b/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs @@ -0,0 +1,1170 @@ +using NUnit.Framework; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEditor.Scripting; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditorInternal +{ + public sealed class InternalEditorUtility + { + public enum HierarchyDropMode + { + kHierarchyDragNormal, + kHierarchyDropUpon, + kHierarchyDropBetween, + kHierarchyDropAfterParent = 4 + } + public static extern bool inBatchMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isHumanControllingUs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int[] expandedProjectWindowItems + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string[] tags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] layers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern string[] sortingLayerNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern int[] sortingLayerUniqueIDs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string unityPreferencesFolder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float defaultScreenWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float defaultScreenHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float defaultWebScreenWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float defaultWebScreenHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float remoteScreenWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float remoteScreenHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool ignoreInspectorChanges + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Texture2D GetIconForFile(string fileName) + { + int num = fileName.LastIndexOf('.'); + string text = (num != -1) ? fileName.Substring(num + 1).ToLower() : string.Empty; + string text2 = text; + switch (text2) + { + case "boo": + return EditorGUIUtility.FindTexture("boo Script Icon"); + case "cginc": + return EditorGUIUtility.FindTexture("CGProgram Icon"); + case "cs": + return EditorGUIUtility.FindTexture("cs Script Icon"); + case "guiskin": + return EditorGUIUtility.FindTexture("GUISkin Icon"); + case "js": + return EditorGUIUtility.FindTexture("Js Script Icon"); + case "mat": + return EditorGUIUtility.FindTexture("Material Icon"); + case "prefab": + return EditorGUIUtility.FindTexture("PrefabNormal Icon"); + case "shader": + return EditorGUIUtility.FindTexture("Shader Icon"); + case "txt": + return EditorGUIUtility.FindTexture("TextAsset Icon"); + case "unity": + return EditorGUIUtility.FindTexture("SceneAsset Icon"); + case "asset": + case "prefs": + return EditorGUIUtility.FindTexture("GameManager Icon"); + case "anim": + return EditorGUIUtility.FindTexture("Animation Icon"); + case "meta": + return EditorGUIUtility.FindTexture("MetaFile Icon"); + case "ttf": + case "otf": + case "fon": + case "fnt": + return EditorGUIUtility.FindTexture("Font Icon"); + 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": + return EditorGUIUtility.FindTexture("AudioClip Icon"); + 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": + return EditorGUIUtility.FindTexture("Texture Icon"); + 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("Mesh Icon"); + 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 "m4v": + case "mjp": + case "mov": + case "movie": + case "mp21": + case "mp4": + case "mpe": + case "mpeg": + case "mpg": + case "mpv2": + case "ogm": + case "qt": + case "rm": + case "rmvb": + case "wmw": + case "xvid": + return EditorGUIUtility.FindTexture("MovieTexture Icon"); + case "colors": + case "gradients": + case "curves": + case "curvesnormalized": + case "particlecurves": + case "particlecurvessigned": + case "particledoublecurves": + case "particledoublecurvessigned": + return EditorGUIUtility.FindTexture("ScriptableObject Icon"); + } + return EditorGUIUtility.FindTexture("DefaultAsset Icon"); + } + public static string[] GetEditorSettingsList(string prefix, int count) + { + ArrayList arrayList = new ArrayList(); + for (int i = 1; i <= count; i++) + { + string @string = EditorPrefs.GetString(prefix + i, "defaultValue"); + if (@string == "defaultValue") + { + break; + } + arrayList.Add(@string); + } + return arrayList.ToArray(typeof(string)) as string[]; + } + public static void SaveEditorSettingsList(string prefix, string[] aList, int count) + { + for (int i = 0; i < aList.Length; i++) + { + EditorPrefs.SetString(prefix + (i + 1), aList[i]); + } + for (int i = aList.Length + 1; i <= count; i++) + { + EditorPrefs.DeleteKey(prefix + i); + } + } + public static Camera[] GetSceneViewCameras() + { + return SceneView.GetAllSceneCameras(); + } + public static void ShowGameView() + { + WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true); + } + public static List GetNewSelection(int clickedInstanceID, List allInstanceIDs, List selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection) + { + List list = new List(); + bool flag = Event.current.shift || (EditorGUI.actionKey && useShiftAsActionKey); + bool flag2 = EditorGUI.actionKey && !useShiftAsActionKey; + if (!allowMultiSelection) + { + flag2 = (flag = false); + } + if (flag2) + { + list.AddRange(selectedInstanceIDs); + if (list.Contains(clickedInstanceID)) + { + list.Remove(clickedInstanceID); + } + else + { + list.Add(clickedInstanceID); + } + } + else + { + if (flag) + { + if (clickedInstanceID == lastClickedInstanceID) + { + return selectedInstanceIDs; + } + int num; + int num2; + if (!InternalEditorUtility.GetFirstAndLastSelected(allInstanceIDs, selectedInstanceIDs, out num, out num2)) + { + list.Add(clickedInstanceID); + return list; + } + int num3 = -1; + int num4 = -1; + for (int i = 0; i < allInstanceIDs.Count; i++) + { + if (allInstanceIDs[i] == clickedInstanceID) + { + num3 = i; + } + if (lastClickedInstanceID != 0 && allInstanceIDs[i] == lastClickedInstanceID) + { + num4 = i; + } + } + Assert.That(num3 != -1); + int num5 = 0; + if (num4 != -1) + { + num5 = ((num3 <= num4) ? -1 : 1); + } + int num6; + int num7; + if (num3 > num2) + { + num6 = num; + num7 = num3; + } + else + { + if (num3 >= num && num3 < num2) + { + if (num5 > 0) + { + num6 = num3; + num7 = num2; + } + else + { + num6 = num; + num7 = num3; + } + } + else + { + num6 = num3; + num7 = num2; + } + } + for (int j = num6; j <= num7; j++) + { + list.Add(allInstanceIDs[j]); + } + } + else + { + if (keepMultiSelection && selectedInstanceIDs.Contains(clickedInstanceID)) + { + list.AddRange(selectedInstanceIDs); + return list; + } + list.Add(clickedInstanceID); + } + } + return list; + } + private static bool GetFirstAndLastSelected(List allInstanceIDs, List selectedInstanceIDs, out int firstIndex, out int lastIndex) + { + firstIndex = -1; + lastIndex = -1; + for (int i = 0; i < allInstanceIDs.Count; i++) + { + if (selectedInstanceIDs.Contains(allInstanceIDs[i])) + { + if (firstIndex == -1) + { + firstIndex = i; + } + lastIndex = i; + } + } + return firstIndex != -1 && lastIndex != -1; + } + public static bool IsValidFileName(string filename) + { + string text = InternalEditorUtility.RemoveInvalidCharsFromFileName(filename, false); + return !(text != filename) && !string.IsNullOrEmpty(text); + } + public static string RemoveInvalidCharsFromFileName(string filename, bool logIfInvalidChars) + { + if (string.IsNullOrEmpty(filename)) + { + return filename; + } + filename = filename.Trim(); + if (string.IsNullOrEmpty(filename)) + { + return filename; + } + string text = new string(Path.GetInvalidFileNameChars()); + string text2 = string.Empty; + bool flag = false; + string text3 = filename; + for (int i = 0; i < text3.Length; i++) + { + char c = text3[i]; + if (text.IndexOf(c) == -1) + { + text2 += c; + } + else + { + flag = true; + } + } + if (flag && logIfInvalidChars) + { + string displayStringOfInvalidCharsOfFileName = InternalEditorUtility.GetDisplayStringOfInvalidCharsOfFileName(filename); + if (displayStringOfInvalidCharsOfFileName.Length > 0) + { + Debug.LogWarning(string.Format("A filename cannot contain the following character{0}: {1}", (displayStringOfInvalidCharsOfFileName.Length <= 1) ? string.Empty : "s", displayStringOfInvalidCharsOfFileName)); + } + } + return text2; + } + public static string GetDisplayStringOfInvalidCharsOfFileName(string filename) + { + if (string.IsNullOrEmpty(filename)) + { + return string.Empty; + } + string text = new string(Path.GetInvalidFileNameChars()); + string text2 = string.Empty; + for (int i = 0; i < filename.Length; i++) + { + char c = filename[i]; + if (text.IndexOf(c) >= 0 && text2.IndexOf(c) == -1) + { + if (text2.Length > 0) + { + text2 += " "; + } + text2 += c; + } + } + return text2; + } + internal static bool IsScriptOrAssembly(string filename) + { + if (string.IsNullOrEmpty(filename)) + { + return false; + } + string text = Path.GetExtension(filename).ToLower(); + if (text != null) + { + if (InternalEditorUtility.<>f__switch$map6 == null) + { + InternalEditorUtility.<>f__switch$map6 = new Dictionary(5) + { + + { + ".cs", + 0 + }, + + { + ".js", + 0 + }, + + { + ".boo", + 0 + }, + + { + ".dll", + 1 + }, + + { + ".exe", + 1 + } + }; + } + int num; + if (InternalEditorUtility.<>f__switch$map6.TryGetValue(text, out num)) + { + if (num == 0) + { + return true; + } + if (num == 1) + { + return AssemblyHelper.IsManagedAssembly(filename); + } + } + } + return false; + } + internal static T ParentHasComponent(Transform trans) where T : Component + { + if (!(trans != null)) + { + return (T)((object)null); + } + T component = trans.GetComponent(); + if (component) + { + return component; + } + return InternalEditorUtility.ParentHasComponent(trans.parent); + } + internal static IEnumerable GetAllScriptGUIDs() + { + return + from asset in AssetDatabase.GetAllAssetPaths() + where InternalEditorUtility.IsScriptOrAssembly(asset) + select AssetDatabase.AssetPathToGUID(asset); + } + public static bool DetectDotNetDll(string path) + { + bool result; + using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) + { + using (BinaryReader binaryReader = new BinaryReader(stream)) + { + if (stream.Length < 64L) + { + result = false; + } + else + { + stream.Position = 60L; + uint num = binaryReader.ReadUInt32(); + if (num == 0u) + { + num = 128u; + } + if ((ulong)num > (ulong)(stream.Length - 256L)) + { + result = false; + } + else + { + stream.Position = (long)((ulong)num); + uint num2 = binaryReader.ReadUInt32(); + if (num2 != 17744u) + { + result = false; + } + else + { + stream.Position += 20L; + ushort num3 = binaryReader.ReadUInt16(); + if (num3 != 267 && num3 != 523) + { + result = false; + } + else + { + ushort num4 = (ushort)((ulong)num + (ulong)((num3 != 267) ? 248L : 232L)); + stream.Position = (long)num4; + if (binaryReader.ReadUInt32() == 0u) + { + result = false; + } + else + { + result = true; + } + } + } + } + } + } + } + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BumpMapSettingsFixingWindowReportResult(int result); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BumpMapTextureNeedsFixing(Material material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FixNormalmapTexture(Material material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetEditorAssemblyPath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetEngineAssemblyPath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CalculateHashForObjectsAndDependencies(UnityEngine.Object[] objects); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExecuteCommandOnKeyWindow(string commandName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Material[] InstantiateMaterialsInEditMode(Renderer renderer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern CanAppendBuild BuildCanBeAppended(BuildTarget target, string location); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void RegisterExtensionDll(string dllLocation, string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetupCustomDll(string dllName, string dllLocation); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Assembly LoadAssemblyWrapper(string dllName, string dllLocation); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPlatformPath(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AddScriptComponentUnchecked(GameObject gameObject, MonoScript script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RequestScriptReload(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SwitchSkinAndRepaintAllViews(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RepaintAllViews(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetIsInspectorExpanded(UnityEngine.Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetIsInspectorExpanded(UnityEngine.Object obj, bool isExpanded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SaveToSerializedFileAndForget(UnityEngine.Object[] obj, string path, bool allowTextSerialization); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object[] LoadSerializedFileAndForget(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern DragAndDropVisualMode ProjectWindowDrag(HierarchyProperty property, bool perform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern DragAndDropVisualMode HierarchyWindowDrag(HierarchyProperty property, bool perform, InternalEditorUtility.HierarchyDropMode options); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern DragAndDropVisualMode InspectorWindowDrag(UnityEngine.Object[] targets, bool perform); + public static DragAndDropVisualMode SceneViewDrag(UnityEngine.Object dropUpon, Vector3 worldPosition, Vector2 viewportPosition, bool perform) + { + return InternalEditorUtility.INTERNAL_CALL_SceneViewDrag(dropUpon, ref worldPosition, ref viewportPosition, perform); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern DragAndDropVisualMode INTERNAL_CALL_SceneViewDrag(UnityEngine.Object dropUpon, ref Vector3 worldPosition, ref Vector2 viewportPosition, bool perform); + public static void SetRectTransformTemporaryRect(RectTransform rectTransform, Rect rect) + { + InternalEditorUtility.INTERNAL_CALL_SetRectTransformTemporaryRect(rectTransform, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetRectTransformTemporaryRect(RectTransform rectTransform, ref Rect rect); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasMaint(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasPro(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasAdvancedLicenseOnBuildTarget(BuildTarget target); + public static Rect GetBoundsOfDesktopAtPoint(Vector2 pos) + { + return InternalEditorUtility.INTERNAL_CALL_GetBoundsOfDesktopAtPoint(ref pos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_GetBoundsOfDesktopAtPoint(ref Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetSortingLayerName(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetSortingLayerNameFromUniqueID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSortingLayerUserID(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSortingLayerCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetSortingLayerName(int index, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetSortingLayerLocked(int index, bool locked); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetSortingLayerLocked(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsSortingLayerDefault(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void AddSortingLayer(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateSortingLayersOrder(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetSpriteOuterUV(Sprite sprite, bool getAtlasData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetObjectFromInstanceID(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetClassIDWithoutLoadingObject(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern UnityEngine.Object GetLoadedObjectFromInstanceID(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetLayerName(int layer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetExternalScriptEditor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetExternalScriptEditorArgs(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ReloadWindowLayoutMenu(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RevertFactoryLayoutSettings(bool quitOnCancel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadDefaultLayout(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetupShaderMenu(Material material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetFullUnityVersion(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUnityBuildBranch(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetUnityVersionDate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetUnityRevision(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsUnityBeta(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUnityCopyright(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetLicenseInfo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int[] GetLicenseFlags(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetAuthToken(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenEditorConsole(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetGameObjectInstanceIDFromComponent(int instanceID); + public static Color[] ReadScreenPixel(Vector2 pixelPos, int sizex, int sizey) + { + return InternalEditorUtility.INTERNAL_CALL_ReadScreenPixel(ref pixelPos, sizex, sizey); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Color[] INTERNAL_CALL_ReadScreenPixel(ref Vector2 pixelPos, int sizex, int sizey); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenPlayerConsole(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Resolution GetDesktopResolution(); + public static string TextifyEvent(Event evt) + { + if (evt == null) + { + return "none"; + } + KeyCode keyCode = evt.keyCode; + string str; + switch (keyCode) + { + case KeyCode.Keypad0: + str = "[0]"; + goto IL_2E8; + case KeyCode.Keypad1: + str = "[1]"; + goto IL_2E8; + case KeyCode.Keypad2: + str = "[2]"; + goto IL_2E8; + case KeyCode.Keypad3: + str = "[3]"; + goto IL_2E8; + case KeyCode.Keypad4: + str = "[4]"; + goto IL_2E8; + case KeyCode.Keypad5: + str = "[5]"; + goto IL_2E8; + case KeyCode.Keypad6: + str = "[6]"; + goto IL_2E8; + case KeyCode.Keypad7: + str = "[7]"; + goto IL_2E8; + case KeyCode.Keypad8: + str = "[8]"; + goto IL_2E8; + case KeyCode.Keypad9: + str = "[9]"; + goto IL_2E8; + case KeyCode.KeypadPeriod: + str = "[.]"; + goto IL_2E8; + case KeyCode.KeypadDivide: + str = "[/]"; + goto IL_2E8; + case KeyCode.KeypadMultiply: + IL_C5: + if (keyCode == KeyCode.Backspace) + { + str = "backspace"; + goto IL_2E8; + } + if (keyCode == KeyCode.Return) + { + str = "return"; + goto IL_2E8; + } + if (keyCode == KeyCode.Escape) + { + str = "[esc]"; + goto IL_2E8; + } + if (keyCode != KeyCode.Delete) + { + str = string.Empty + evt.keyCode; + goto IL_2E8; + } + str = "delete"; + goto IL_2E8; + case KeyCode.KeypadMinus: + str = "[-]"; + goto IL_2E8; + case KeyCode.KeypadPlus: + str = "[+]"; + goto IL_2E8; + case KeyCode.KeypadEnter: + str = "enter"; + goto IL_2E8; + case KeyCode.KeypadEquals: + str = "[=]"; + goto IL_2E8; + case KeyCode.UpArrow: + str = "up"; + goto IL_2E8; + case KeyCode.DownArrow: + str = "down"; + goto IL_2E8; + case KeyCode.RightArrow: + str = "right"; + goto IL_2E8; + case KeyCode.LeftArrow: + str = "left"; + goto IL_2E8; + case KeyCode.Insert: + str = "insert"; + goto IL_2E8; + case KeyCode.Home: + str = "home"; + goto IL_2E8; + case KeyCode.End: + str = "end"; + goto IL_2E8; + case KeyCode.PageUp: + str = "page up"; + goto IL_2E8; + case KeyCode.PageDown: + str = "page down"; + goto IL_2E8; + case KeyCode.F1: + str = "F1"; + goto IL_2E8; + case KeyCode.F2: + str = "F2"; + goto IL_2E8; + case KeyCode.F3: + str = "F3"; + goto IL_2E8; + case KeyCode.F4: + str = "F4"; + goto IL_2E8; + case KeyCode.F5: + str = "F5"; + goto IL_2E8; + case KeyCode.F6: + str = "F6"; + goto IL_2E8; + case KeyCode.F7: + str = "F7"; + goto IL_2E8; + case KeyCode.F8: + str = "F8"; + goto IL_2E8; + case KeyCode.F9: + str = "F9"; + goto IL_2E8; + case KeyCode.F10: + str = "F10"; + goto IL_2E8; + case KeyCode.F11: + str = "F11"; + goto IL_2E8; + case KeyCode.F12: + str = "F12"; + goto IL_2E8; + case KeyCode.F13: + str = "F13"; + goto IL_2E8; + case KeyCode.F14: + str = "F14"; + goto IL_2E8; + case KeyCode.F15: + str = "F15"; + goto IL_2E8; + } + goto IL_C5; + IL_2E8: + string str2 = string.Empty; + if (evt.alt) + { + str2 += "Alt+"; + } + if (evt.command) + { + str2 += ((Application.platform != RuntimePlatform.OSXEditor) ? "Ctrl+" : "Cmd+"); + } + if (evt.control) + { + str2 += "Ctrl+"; + } + if (evt.shift) + { + str2 += "Shift+"; + } + return str2 + str; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAvailableDiffTools(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetNoDiffToolsDetectedMessage(); + public static Bounds TransformBounds(Bounds b, Transform t) + { + return InternalEditorUtility.INTERNAL_CALL_TransformBounds(ref b, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Bounds INTERNAL_CALL_TransformBounds(ref Bounds b, Transform t); + public static void SetCustomLighting(Light[] lights, Color ambient) + { + InternalEditorUtility.INTERNAL_CALL_SetCustomLighting(lights, ref ambient); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetCustomLighting(Light[] lights, ref Color ambient); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemoveCustomLighting(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CalculateShouldEnableLights(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasFullscreenCamera(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetCursor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Bounds CalculateSelectionBounds(bool usePivotOnlyForParticles); + internal static Bounds CalculateSelectionBoundsInSpace(Vector3 position, Quaternion rotation, bool rectBlueprintMode) + { + Quaternion rotation2 = Quaternion.Inverse(rotation); + Vector3 vector = new Vector3(3.40282347E+38f, 3.40282347E+38f, 3.40282347E+38f); + Vector3 vector2 = new Vector3(-3.40282347E+38f, -3.40282347E+38f, -3.40282347E+38f); + Vector3[] array = new Vector3[2]; + GameObject[] gameObjects = Selection.gameObjects; + for (int i = 0; i < gameObjects.Length; i++) + { + GameObject gameObject = gameObjects[i]; + Bounds localBounds = InternalEditorUtility.GetLocalBounds(gameObject); + array[0] = localBounds.min; + array[1] = localBounds.max; + for (int j = 0; j < 2; j++) + { + for (int k = 0; k < 2; k++) + { + for (int l = 0; l < 2; l++) + { + Vector3 vector3 = new Vector3(array[j].x, array[k].y, array[l].z); + if (rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(gameObject.transform)) + { + Vector3 localPosition = gameObject.transform.localPosition; + localPosition.z = 0f; + vector3 = gameObject.transform.parent.TransformPoint(vector3 + localPosition); + } + else + { + vector3 = gameObject.transform.TransformPoint(vector3); + } + vector3 = rotation2 * (vector3 - position); + for (int m = 0; m < 3; m++) + { + vector[m] = Mathf.Min(vector[m], vector3[m]); + vector2[m] = Mathf.Max(vector2[m], vector3[m]); + } + } + } + } + } + return new Bounds((vector + vector2) * 0.5f, vector2 - vector); + } + internal static bool SupportsRectLayout(Transform tr) + { + return !(tr == null) && !(tr.parent == null) && !(tr.GetComponent() == null) && !(tr.parent.GetComponent() == null); + } + private static Bounds GetLocalBounds(GameObject gameObject) + { + RectTransform component = gameObject.GetComponent(); + if (component) + { + return new Bounds(component.rect.center, component.rect.size); + } + Renderer component2 = gameObject.GetComponent(); + if (component2 is MeshRenderer) + { + MeshFilter component3 = component2.GetComponent(); + if (component3 != null && component3.sharedMesh != null) + { + return component3.sharedMesh.bounds; + } + } + if (component2 is SpriteRenderer) + { + SpriteRenderer spriteRenderer = component2 as SpriteRenderer; + if (spriteRenderer.sprite != null) + { + Bounds bounds = spriteRenderer.sprite.bounds; + Vector3 size = bounds.size; + size.z = 0f; + bounds.size = size; + return bounds; + } + } + return new Bounds(Vector3.zero, Vector3.zero); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OnGameViewFocus(bool focus); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool OpenFileAtLineExternal(string filename, int line); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern MonoIsland[] GetMonoIslands(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Xbox360GenerateSPAConfig(string spaPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Xbox360SaveSplashScreenToFile(Texture2D image, string spaPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CanConnectToCacheServer(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetCrashReportFolder(); + [ExcludeFromDocs] + internal static bool RunningUnderWindows8() + { + bool orHigher = true; + return InternalEditorUtility.RunningUnderWindows8(orHigher); + } + internal static bool RunningUnderWindows8([DefaultValue("true")] bool orHigher) + { + if (Application.platform != RuntimePlatform.WindowsEditor) + { + return false; + } + OperatingSystem oSVersion = Environment.OSVersion; + int major = oSVersion.Version.Major; + int minor = oSVersion.Version.Minor; + if (orHigher) + { + return major > 6 || (major == 6 && minor >= 2); + } + return major == 6 && minor == 2; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int DetermineDepthOrder(Transform lhs, Transform rhs); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ShowPackageManagerWindow(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void AuxWindowManager_OnAssemblyReload(); + } +} diff --git a/UnityEditor/UnityEditorInternal/InternalGraphUtility.cs b/UnityEditor/UnityEditorInternal/InternalGraphUtility.cs new file mode 100644 index 00000000..cca02280 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/InternalGraphUtility.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class InternalGraphUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GenerateGraphName(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int[] AllGraphsOnGameObject(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int[] AllGraphsInScene(); + } +} diff --git a/UnityEditor/UnityEditorInternal/InternalSpriteUtility.cs b/UnityEditor/UnityEditorInternal/InternalSpriteUtility.cs new file mode 100644 index 00000000..daa655f8 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/InternalSpriteUtility.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class InternalSpriteUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Rect[] GenerateAutomaticSpriteRectangles(Texture2D texture, int minRectSize, int extrudeSize); + public static Rect[] GenerateGridSpriteRectangles(Texture2D texture, Vector2 offset, Vector2 size, Vector2 padding) + { + return InternalSpriteUtility.INTERNAL_CALL_GenerateGridSpriteRectangles(texture, ref offset, ref size, ref padding); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect[] INTERNAL_CALL_GenerateGridSpriteRectangles(Texture2D texture, ref Vector2 offset, ref Vector2 size, ref Vector2 padding); + } +} diff --git a/UnityEditor/UnityEditorInternal/JSONParseException.cs b/UnityEditor/UnityEditorInternal/JSONParseException.cs new file mode 100644 index 00000000..19f40ee5 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/JSONParseException.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + internal class JSONParseException : Exception + { + public JSONParseException(string msg) : base(msg) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/JSONParser.cs b/UnityEditor/UnityEditorInternal/JSONParser.cs new file mode 100644 index 00000000..cc7ba937 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/JSONParser.cs @@ -0,0 +1,370 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class JSONParser + { + private string json; + private int line; + private int linechar; + private int len; + private int idx; + private int pctParsed; + private char cur; + private static char[] endcodes = new char[] + { + '\\', + '"' + }; + public JSONParser(string jsondata) + { + this.json = jsondata + " "; + this.line = 1; + this.linechar = 1; + this.len = this.json.Length; + this.idx = 0; + this.pctParsed = 0; + } + public static JSONValue SimpleParse(string jsondata) + { + JSONParser jSONParser = new JSONParser(jsondata); + try + { + return jSONParser.Parse(); + } + catch (JSONParseException ex) + { + Debug.LogError(ex.Message); + } + return new JSONValue(null); + } + public JSONValue Parse() + { + this.cur = this.json[this.idx]; + return this.ParseValue(); + } + private char Next() + { + if (this.cur == '\n') + { + this.line++; + this.linechar = 0; + } + this.idx++; + if (this.idx >= this.len) + { + throw new JSONParseException("End of json while parsing at " + this.PosMsg()); + } + this.linechar++; + int num = (int)((float)this.idx * 100f / (float)this.len); + if (num != this.pctParsed) + { + this.pctParsed = num; + } + this.cur = this.json[this.idx]; + return this.cur; + } + private void SkipWs() + { + string text = " \n\t\r"; + while (text.IndexOf(this.cur) != -1) + { + this.Next(); + } + } + private string PosMsg() + { + return "line " + this.line.ToString() + ", column " + this.linechar.ToString(); + } + private JSONValue ParseValue() + { + this.SkipWs(); + char c = this.cur; + switch (c) + { + case '"': + return this.ParseString(); + case '#': + case '$': + case '%': + case '&': + case '\'': + case '(': + case ')': + case '*': + case '+': + case ',': + case '.': + case '/': + IL_76: + if (c == '[') + { + return this.ParseArray(); + } + if (c == 'f' || c == 'n' || c == 't') + { + return this.ParseConstant(); + } + if (c != '{') + { + throw new JSONParseException("Cannot parse json value starting with '" + this.json.Substring(this.idx, 5) + "' at " + this.PosMsg()); + } + return this.ParseDict(); + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return this.ParseNumber(); + } + goto IL_76; + } + private JSONValue ParseArray() + { + this.Next(); + this.SkipWs(); + List list = new List(); + while (this.cur != ']') + { + list.Add(this.ParseValue()); + this.SkipWs(); + if (this.cur == ',') + { + this.Next(); + this.SkipWs(); + } + } + this.Next(); + return new JSONValue(list); + } + private JSONValue ParseDict() + { + this.Next(); + this.SkipWs(); + Dictionary dictionary = new Dictionary(); + while (this.cur != '}') + { + JSONValue jSONValue = this.ParseValue(); + if (!jSONValue.IsString()) + { + throw new JSONParseException("Key not string type at " + this.PosMsg()); + } + this.SkipWs(); + if (this.cur != ':') + { + throw new JSONParseException("Missing dict entry delimiter ':' at " + this.PosMsg()); + } + this.Next(); + dictionary.Add(jSONValue.AsString(), this.ParseValue()); + this.SkipWs(); + if (this.cur == ',') + { + this.Next(); + this.SkipWs(); + } + } + this.Next(); + return new JSONValue(dictionary); + } + private JSONValue ParseString() + { + string text = string.Empty; + this.Next(); + while (this.idx < this.len) + { + int num = this.json.IndexOfAny(JSONParser.endcodes, this.idx); + if (num < 0) + { + throw new JSONParseException("missing '\"' to end string at " + this.PosMsg()); + } + text += this.json.Substring(this.idx, num - this.idx); + if (this.json[num] == '"') + { + this.cur = this.json[num]; + this.idx = num; + break; + } + num++; + if (num >= this.len) + { + throw new JSONParseException("End of json while parsing while parsing string at " + this.PosMsg()); + } + char c = this.json[num]; + char c2 = c; + switch (c2) + { + case 'n': + text += '\n'; + goto IL_2AE; + case 'o': + case 'p': + case 'q': + case 's': + IL_F7: + if (c2 != '"') + { + if (c2 != '/') + { + if (c2 != '\\') + { + if (c2 == 'b') + { + text += '\b'; + goto IL_2AE; + } + if (c2 != 'f') + { + throw new JSONParseException(string.Concat(new object[] + { + "Invalid escape char '", + c, + "' near ", + this.PosMsg() + })); + } + text += '\f'; + goto IL_2AE; + } + } + } + text += c; + goto IL_2AE; + case 'r': + text += '\r'; + goto IL_2AE; + case 't': + text += '\t'; + goto IL_2AE; + case 'u': + { + string text2 = string.Empty; + if (num + 4 >= this.len) + { + throw new JSONParseException("End of json while parsing while parsing unicode char near " + this.PosMsg()); + } + text2 += this.json[num + 1]; + text2 += this.json[num + 2]; + text2 += this.json[num + 3]; + text2 += this.json[num + 4]; + try + { + int num2 = int.Parse(text2, NumberStyles.AllowHexSpecifier); + text += (char)num2; + } + catch (FormatException) + { + throw new JSONParseException("Invalid unicode escape char near " + this.PosMsg()); + } + num += 4; + goto IL_2AE; + } + } + goto IL_F7; + IL_2AE: + this.idx = num + 1; + } + if (this.idx >= this.len) + { + throw new JSONParseException("End of json while parsing while parsing string near " + this.PosMsg()); + } + this.cur = this.json[this.idx]; + this.Next(); + return new JSONValue(text); + } + private JSONValue ParseNumber() + { + string text = string.Empty; + if (this.cur == '-') + { + text = "-"; + this.Next(); + } + while (this.cur >= '0' && this.cur <= '9') + { + text += this.cur; + this.Next(); + } + if (this.cur == '.') + { + this.Next(); + text += '.'; + while (this.cur >= '0' && this.cur <= '9') + { + text += this.cur; + this.Next(); + } + } + if (this.cur == 'e' || this.cur == 'E') + { + text += "e"; + this.Next(); + if (this.cur != '-' && this.cur != '+') + { + text += this.cur; + this.Next(); + } + while (this.cur >= '0') + { + if (this.cur > '9') + { + break; + } + text += this.cur; + this.Next(); + } + } + JSONValue result; + try + { + float num = Convert.ToSingle(text); + result = new JSONValue(num); + } + catch (Exception) + { + throw new JSONParseException("Cannot convert string to float : '" + text + "' at " + this.PosMsg()); + } + return result; + } + private JSONValue ParseConstant() + { + string a = string.Empty; + a = string.Concat(new object[] + { + string.Empty, + this.cur, + this.Next(), + this.Next(), + this.Next() + }); + this.Next(); + if (a == "true") + { + return new JSONValue(true); + } + if (a == "fals") + { + if (this.cur == 'e') + { + this.Next(); + return new JSONValue(false); + } + } + else + { + if (a == "null") + { + return new JSONValue(null); + } + } + throw new JSONParseException("Invalid token at " + this.PosMsg()); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/JSONTypeException.cs b/UnityEditor/UnityEditorInternal/JSONTypeException.cs new file mode 100644 index 00000000..775d901b --- /dev/null +++ b/UnityEditor/UnityEditorInternal/JSONTypeException.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + internal class JSONTypeException : Exception + { + public JSONTypeException(string msg) : base(msg) + { + } + } +} diff --git a/UnityEditor/UnityEditorInternal/JSONValue.cs b/UnityEditor/UnityEditorInternal/JSONValue.cs new file mode 100644 index 00000000..28e95c80 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/JSONValue.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +namespace UnityEditorInternal +{ + internal struct JSONValue + { + private object data; + public JSONValue this[string index] + { + get + { + Dictionary dictionary = this.AsDict(); + return dictionary[index]; + } + set + { + if (this.data == null) + { + this.data = new Dictionary(); + } + Dictionary dictionary = this.AsDict(); + dictionary[index] = value; + } + } + public JSONValue(object o) + { + this.data = o; + } + public bool IsString() + { + return this.data is string; + } + public bool IsFloat() + { + return this.data is float; + } + public bool IsList() + { + return this.data is List; + } + public bool IsDict() + { + return this.data is Dictionary; + } + public bool IsBool() + { + return this.data is bool; + } + public bool IsNull() + { + return this.data == null; + } + public object AsObject() + { + return this.data; + } + public string AsString(bool nothrow) + { + if (this.data is string) + { + return (string)this.data; + } + if (!nothrow) + { + throw new JSONTypeException("Tried to read non-string json value as string"); + } + return string.Empty; + } + public string AsString() + { + return this.AsString(false); + } + public float AsFloat(bool nothrow) + { + if (this.data is float) + { + return (float)this.data; + } + if (!nothrow) + { + throw new JSONTypeException("Tried to read non-float json value as float"); + } + return 0f; + } + public float AsFloat() + { + return this.AsFloat(false); + } + public bool AsBool(bool nothrow) + { + if (this.data is bool) + { + return (bool)this.data; + } + if (!nothrow) + { + throw new JSONTypeException("Tried to read non-bool json value as bool"); + } + return false; + } + public bool AsBool() + { + return this.AsBool(false); + } + public List AsList(bool nothrow) + { + if (this.data is List) + { + return (List)this.data; + } + if (!nothrow) + { + throw new JSONTypeException("Tried to read " + this.data.GetType().Name + " json value as list"); + } + return null; + } + public List AsList() + { + return this.AsList(false); + } + public Dictionary AsDict(bool nothrow) + { + if (this.data is Dictionary) + { + return (Dictionary)this.data; + } + if (!nothrow) + { + throw new JSONTypeException("Tried to read non-dictionary json value as dictionary"); + } + return null; + } + public Dictionary AsDict() + { + return this.AsDict(false); + } + public static JSONValue NewString(string val) + { + return new JSONValue(val); + } + public static JSONValue NewFloat(float val) + { + return new JSONValue(val); + } + public static JSONValue NewDict() + { + return new JSONValue(new Dictionary()); + } + public static JSONValue NewList() + { + return new JSONValue(new List()); + } + public static JSONValue NewBool(bool val) + { + return new JSONValue(val); + } + public static JSONValue NewNull() + { + return new JSONValue(null); + } + public bool ContainsKey(string index) + { + return this.IsDict() && this.AsDict().ContainsKey(index); + } + public JSONValue Get(string key) + { + if (!this.IsDict()) + { + return new JSONValue(null); + } + JSONValue result = this; + string[] array = key.Split(new char[] + { + '.' + }); + for (int i = 0; i < array.Length; i++) + { + string index = array[i]; + if (!result.ContainsKey(index)) + { + return new JSONValue(null); + } + result = result[index]; + } + return result; + } + public void Set(string key, string value) + { + if (value == null) + { + this[key] = JSONValue.NewNull(); + return; + } + this[key] = JSONValue.NewString(value); + } + public void Set(string key, float value) + { + this[key] = JSONValue.NewFloat(value); + } + public void Set(string key, bool value) + { + this[key] = JSONValue.NewBool(value); + } + public void Add(string value) + { + List list = this.AsList(); + if (value == null) + { + list.Add(JSONValue.NewNull()); + return; + } + list.Add(JSONValue.NewString(value)); + } + public void Add(float value) + { + List list = this.AsList(); + list.Add(JSONValue.NewFloat(value)); + } + public void Add(bool value) + { + List list = this.AsList(); + list.Add(JSONValue.NewBool(value)); + } + public override string ToString() + { + if (this.IsString()) + { + return "\"" + JSONValue.EncodeString(this.AsString()) + "\""; + } + if (this.IsFloat()) + { + return this.AsFloat().ToString(); + } + if (this.IsList()) + { + string str = "["; + string str2 = string.Empty; + foreach (JSONValue current in this.AsList()) + { + str = str + str2 + current.ToString(); + str2 = ", "; + } + return str + "]"; + } + if (this.IsDict()) + { + string text = "{"; + string text2 = string.Empty; + foreach (KeyValuePair current2 in this.AsDict()) + { + string text3 = text; + text = string.Concat(new object[] + { + text3, + text2, + '"', + JSONValue.EncodeString(current2.Key), + "\" : ", + current2.Value.ToString() + }); + text2 = ", "; + } + return text + "}"; + } + if (this.IsBool()) + { + return (!this.AsBool()) ? "false" : "true"; + } + if (this.IsNull()) + { + return "null"; + } + throw new JSONTypeException("Cannot serialize json value of unknown type"); + } + private static string EncodeString(string str) + { + str = str.Replace("\"", "\\\""); + str = str.Replace("\\", "\\\\"); + str = str.Replace("\b", "\\b"); + str = str.Replace("\f", "\\f"); + str = str.Replace("\n", "\\n"); + str = str.Replace("\r", "\\r"); + str = str.Replace("\t", "\\t"); + return str; + } + public static implicit operator JSONValue(string s) + { + return new JSONValue(s); + } + public static implicit operator JSONValue(float s) + { + return new JSONValue(s); + } + public static implicit operator JSONValue(bool s) + { + return new JSONValue(s); + } + public static implicit operator JSONValue(int s) + { + return new JSONValue((float)s); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/LogEntries.cs b/UnityEditor/UnityEditorInternal/LogEntries.cs new file mode 100644 index 00000000..78d300a3 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/LogEntries.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class LogEntries + { + public static extern int consoleFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenEntryFile(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetStatusText(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStatusMask(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int StartGettingEntries(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetConsoleFlag(int bit, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void EndGettingEntries(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetCountsByType(ref int errorCount, ref int warningCount, ref int logCount); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetFirstTwoLinesEntryTextAndModeInternal(int row, ref int mask, ref string outString); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetEntryInternal(int row, LogEntry outputEntry); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetEntryCount(int row); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStatusViewErrorIndex(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClickStatusBar(int count); + } +} diff --git a/UnityEditor/UnityEditorInternal/LogEntry.cs b/UnityEditor/UnityEditorInternal/LogEntry.cs new file mode 100644 index 00000000..8b408d62 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/LogEntry.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditorInternal +{ + [StructLayout(LayoutKind.Sequential)] + internal sealed class LogEntry + { + public string condition; + public int errorNum; + public string file; + public int line; + public int mode; + public int instanceID; + public int identifier; + public int isWorldPlaying; + } +} diff --git a/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs b/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs new file mode 100644 index 00000000..08dd0bbb --- /dev/null +++ b/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs @@ -0,0 +1,87 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal static class MaterialAnimationUtility + { + private const string kMaterialPrefix = "material."; + private static UndoPropertyModification[] CreateUndoPropertyModifications(int count, UnityEngine.Object target) + { + UndoPropertyModification[] array = new UndoPropertyModification[count]; + for (int i = 0; i < array.Length; i++) + { + array[i].propertyModification = new PropertyModification(); + array[i].propertyModification.target = target; + } + return array; + } + private static void SetupPropertyModification(string name, float value, UndoPropertyModification prop) + { + prop.propertyModification.propertyPath = "material." + name; + prop.propertyModification.value = value.ToString(); + } + private static void ApplyMaterialModificationToAnimationRecording(MaterialProperty materialProp, UnityEngine.Object target, float value) + { + UndoPropertyModification[] array = MaterialAnimationUtility.CreateUndoPropertyModifications(1, target); + MaterialAnimationUtility.SetupPropertyModification(materialProp.name, value, array[0]); + Undo.postprocessModifications(array); + } + private static void ApplyMaterialModificationToAnimationRecording(MaterialProperty materialProp, UnityEngine.Object target, Color color) + { + UndoPropertyModification[] array = MaterialAnimationUtility.CreateUndoPropertyModifications(4, target); + MaterialAnimationUtility.SetupPropertyModification(materialProp.name + ".r", color.r, array[0]); + MaterialAnimationUtility.SetupPropertyModification(materialProp.name + ".g", color.g, array[1]); + MaterialAnimationUtility.SetupPropertyModification(materialProp.name + ".b", color.b, array[2]); + MaterialAnimationUtility.SetupPropertyModification(materialProp.name + ".a", color.a, array[3]); + Undo.postprocessModifications(array); + } + private static void ApplyMaterialModificationToAnimationRecording(string name, UnityEngine.Object target, Vector4 vec) + { + UndoPropertyModification[] array = MaterialAnimationUtility.CreateUndoPropertyModifications(4, target); + MaterialAnimationUtility.SetupPropertyModification(name + ".x", vec.x, array[0]); + MaterialAnimationUtility.SetupPropertyModification(name + ".y", vec.y, array[1]); + MaterialAnimationUtility.SetupPropertyModification(name + ".z", vec.z, array[2]); + MaterialAnimationUtility.SetupPropertyModification(name + ".w", vec.w, array[3]); + Undo.postprocessModifications(array); + } + public static bool IsAnimated(MaterialProperty materialProp, Renderer target) + { + if (materialProp.type == MaterialProperty.PropType.Texture) + { + return AnimationMode.IsPropertyAnimated(target, "material." + materialProp.name + "_ST"); + } + return AnimationMode.IsPropertyAnimated(target, "material." + materialProp.name); + } + public static bool ApplyMaterialModificationToAnimationRecording(MaterialProperty materialProp, int changedMask, Renderer target, object oldValue) + { + MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock(); + target.GetPropertyBlock(materialPropertyBlock); + materialProp.WriteToMaterialPropertyBlock(materialPropertyBlock, changedMask); + target.SetPropertyBlock(materialPropertyBlock); + switch (materialProp.type) + { + case MaterialProperty.PropType.Color: + MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (Color)oldValue); + return true; + case MaterialProperty.PropType.Vector: + MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (Vector4)oldValue); + return true; + case MaterialProperty.PropType.Float: + case MaterialProperty.PropType.Range: + MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (float)oldValue); + return true; + case MaterialProperty.PropType.Texture: + if (MaterialProperty.IsTextureOffsetAndScaleChangedMask(changedMask)) + { + string name = materialProp.name + "_ST"; + MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(name, target, (Vector4)oldValue); + return true; + } + return false; + default: + return false; + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/MemoryInfoGCReason.cs b/UnityEditor/UnityEditorInternal/MemoryInfoGCReason.cs new file mode 100644 index 00000000..7548be19 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/MemoryInfoGCReason.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditorInternal +{ + public enum MemoryInfoGCReason + { + SceneObject, + BuiltinResource, + MarkedDontSave, + AssetMarkedDirtyInEditor, + SceneAssetReferencedByNativeCodeOnly = 5, + SceneAssetReferenced, + AssetReferencedByNativeCodeOnly = 8, + AssetReferenced, + NotApplicable + } +} diff --git a/UnityEditor/UnityEditorInternal/MonoScripts.cs b/UnityEditor/UnityEditorInternal/MonoScripts.cs new file mode 100644 index 00000000..9c9a5c50 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/MonoScripts.cs @@ -0,0 +1,14 @@ +using System; +using UnityEditor; +namespace UnityEditorInternal +{ + public static class MonoScripts + { + public static MonoScript CreateMonoScript(string scriptContents, string className, string nameSpace, string assemblyName, bool isEditorScript) + { + MonoScript monoScript = new MonoScript(); + monoScript.Init(scriptContents, className, nameSpace, assemblyName, isEditorScript); + return monoScript; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/NativeProgram.cs b/UnityEditor/UnityEditorInternal/NativeProgram.cs new file mode 100644 index 00000000..2f89bc2a --- /dev/null +++ b/UnityEditor/UnityEditorInternal/NativeProgram.cs @@ -0,0 +1,24 @@ +using System; +using System.Diagnostics; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class NativeProgram : Program + { + public NativeProgram(string executable, string arguments) + { + ProcessStartInfo startInfo = new ProcessStartInfo + { + Arguments = arguments, + CreateNoWindow = true, + FileName = executable, + RedirectStandardError = true, + RedirectStandardOutput = true, + WorkingDirectory = Application.dataPath + "/..", + UseShellExecute = false + }; + this._process.StartInfo = startInfo; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ObjectMemoryInfo.cs b/UnityEditor/UnityEditorInternal/ObjectMemoryInfo.cs new file mode 100644 index 00000000..f3ab5a0f --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ObjectMemoryInfo.cs @@ -0,0 +1,16 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditorInternal +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class ObjectMemoryInfo + { + public int instanceId; + public int memorySize; + public int count; + public int reason; + public string name; + public string className; + } +} diff --git a/UnityEditor/UnityEditorInternal/ObjectMemoryStackInfo.cs b/UnityEditor/UnityEditorInternal/ObjectMemoryStackInfo.cs new file mode 100644 index 00000000..c0d55a6d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ObjectMemoryStackInfo.cs @@ -0,0 +1,16 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEditorInternal +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class ObjectMemoryStackInfo + { + public bool expanded; + public bool sorted; + public int allocated; + public int ownedAllocated; + public ObjectMemoryStackInfo[] callerSites; + public string name; + } +} diff --git a/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs b/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs new file mode 100644 index 00000000..e4eae41f --- /dev/null +++ b/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using UnityEditor; +namespace UnityEditorInternal +{ + internal class PostProcessNaclPlayer + { + private static bool s_ChromeFailedToLaunch; + private static string ProgramFilesx86 + { + get + { + if (IntPtr.Size == 8 || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))) + { + return Environment.GetEnvironmentVariable("ProgramFiles(x86)"); + } + return Environment.GetEnvironmentVariable("ProgramFiles"); + } + } + private static bool IsWindows + { + get + { + return Environment.OSVersion.Platform != PlatformID.Unix; + } + } + private static string BrowserPath + { + get + { + if (PostProcessNaclPlayer.IsWindows) + { + string text = Path.Combine(PostProcessNaclPlayer.ProgramFilesx86, Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe")))); + if (File.Exists(text)) + { + return text; + } + string text2 = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; + if (File.Exists(text2)) + { + return text2; + } + string text3 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe")))); + if (File.Exists(text3)) + { + return text3; + } + throw new Exception("Cannot find Chrome"); + } + else + { + string text4 = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; + if (File.Exists(text4)) + { + return text4; + } + throw new Exception("Cannot find Chrome"); + } + } + } + internal static void Launch(BuildTarget target, string targetfile) + { + targetfile = Path.GetFullPath(targetfile); + byte[] buffer = (!PostProcessNaclPlayer.IsWindows) ? Encoding.UTF8.GetBytes(targetfile) : Encoding.Unicode.GetBytes(targetfile); + byte[] array = new SHA256Managed().ComputeHash(buffer); + string text = string.Empty; + for (int i = 0; i < 16; i++) + { + text += (char)(97 + (array[i] >> 4)); + text += (char)(97 + (array[i] & 15)); + } + string text2 = string.Concat(new string[] + { + "chrome-extension://", + text, + "/", + Path.GetFileName(targetfile), + "_nacl.html" + }); + do + { + PostProcessNaclPlayer.s_ChromeFailedToLaunch = false; + Process process = new Process(); + process.StartInfo.FileName = PostProcessNaclPlayer.BrowserPath; + process.StartInfo.Arguments = string.Concat(new string[] + { + " --load-extension=\"", + targetfile, + "\" \"", + text2, + "\"" + }); + process.StartInfo.UseShellExecute = false; + process.Start(); + Thread.Sleep(5000); + PostProcessNaclPlayer.s_ChromeFailedToLaunch = process.HasExited; + if (PostProcessNaclPlayer.s_ChromeFailedToLaunch) + { + if (PostProcessNaclPlayer.IsWindows) + { + PostProcessNaclPlayer.s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Is Google Chrome already running?", "If Chrome is already running, you will only be able to test content which has been installed into Chrome before. If your content is not showing in Chrome, please quit Chrome and try again.", "Try again", "Cancel"); + } + else + { + PostProcessNaclPlayer.s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Could not start Google Chrome. Is it already running?", "Please quit any running instances of Chrome and try again.", "Try again", "Cancel"); + } + } + } + while (PostProcessNaclPlayer.s_ChromeFailedToLaunch); + } + private static void StripPhysicsFiles(string path, bool stripPhysics) + { + string[] files = Directory.GetFiles(path); + string[] array = files; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + if (text.Contains("_nophysx")) + { + if (stripPhysics) + { + string text2 = text.Replace("_nophysx", string.Empty); + File.Delete(text2); + File.Move(text, text2); + } + else + { + File.Delete(text); + } + } + } + string[] directories = Directory.GetDirectories(path); + string[] array2 = directories; + for (int j = 0; j < array2.Length; j++) + { + string path2 = array2[j]; + PostProcessNaclPlayer.StripPhysicsFiles(path2, stripPhysics); + } + } + internal static void PostProcess(BuildOptions options, string installPath, string downloadWebplayerUrl, int width, int height) + { + PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); + string fileName = Path.GetFileName(installPath); + string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.NaCl, BuildOptions.None); + string text = "unity_nacl_files_3.x.x"; + string text2 = Path.Combine(installPath, text); + string from = Path.Combine(playbackEngineDirectory, "unity_nacl_files"); + if (Directory.Exists(text2)) + { + FileUtil.DeleteFileOrDirectory(text2); + } + FileUtil.CopyFileOrDirectory(from, text2); + PostProcessNaclPlayer.StripPhysicsFiles(text2, PlayerSettings.stripPhysics); + string from2 = Path.Combine(playbackEngineDirectory, "template.html"); + string text3 = Path.Combine(installPath, fileName + "_nacl.html"); + if (File.Exists(text3)) + { + FileUtil.DeleteFileOrDirectory(text3); + } + FileUtil.CopyFileOrDirectory(from2, text3); + string from3 = Path.Combine(playbackEngineDirectory, "template.json"); + string text4 = Path.Combine(installPath, "manifest.json"); + if (File.Exists(text4)) + { + FileUtil.DeleteFileOrDirectory(text4); + } + FileUtil.CopyFileOrDirectory(from3, text4); + List list = new List(); + list.Add("%UNITY_WIDTH%"); + list.Add(width.ToString()); + list.Add("%UNITY_HEIGHT%"); + list.Add(height.ToString()); + list.Add("%UNITY_WEB_NAME%"); + list.Add(PlayerSettings.productName); + list.Add("%UNITY_WEB_PATH%"); + list.Add(fileName + ".unity3d"); + list.Add("%UNITY_WEB_HTML_PATH%"); + list.Add(fileName + "_nacl.html"); + list.Add("%UNITY_NACL_PARAMETERS%"); + list.Add(((options & BuildOptions.Development) == BuildOptions.None) ? string.Empty : "softexceptions=\"1\""); + list.Add("%UNITY_NACL_ENGINE_PATH%"); + list.Add(text); + list.Add("%UNITY_BETA_WARNING%"); + list.Add((!InternalEditorUtility.IsUnityBeta()) ? string.Empty : "\r\n\t\t

Built with beta version of Unity.

"); + string[] templateCustomKeys = PlayerSettings.templateCustomKeys; + for (int i = 0; i < templateCustomKeys.Length; i++) + { + string text5 = templateCustomKeys[i]; + list.Add("%UNITY_CUSTOM_" + text5.ToUpper() + "%"); + list.Add(PlayerSettings.GetTemplateCustomValue(text5)); + } + FileUtil.ReplaceText(text3, list.ToArray()); + FileUtil.ReplaceText(text4, list.ToArray()); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerArea.cs b/UnityEditor/UnityEditorInternal/ProfilerArea.cs new file mode 100644 index 00000000..25009a20 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerArea.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditorInternal +{ + public enum ProfilerArea + { + CPU, + GPU, + Rendering, + Memory, + Audio, + Physics, + Physics2D, + AreaCount + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerChart.cs b/UnityEditor/UnityEditorInternal/ProfilerChart.cs new file mode 100644 index 00000000..5f08e493 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerChart.cs @@ -0,0 +1,47 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class ProfilerChart + { + public ProfilerArea m_Area; + public Chart.ChartType m_Type; + public float m_DataScale; + public Chart m_Chart; + public ChartData m_Data; + public ChartSeries[] m_Series; + public bool m_Active; + public GUIContent m_Icon; + public ProfilerChart(ProfilerArea area, Chart.ChartType type, float dataScale, int seriesCount) + { + this.m_Area = area; + this.m_Type = type; + this.m_DataScale = dataScale; + this.m_Chart = new Chart(); + this.m_Data = new ChartData(); + this.m_Series = new ChartSeries[seriesCount]; + this.m_Active = EditorPrefs.GetBool("ProfilerChart" + area, true); + this.m_Icon = EditorGUIUtility.TextContent("Profiler." + Enum.GetName(typeof(ProfilerArea), area)); + } + public int DoChartGUI(int currentFrame, ProfilerArea currentArea, out Chart.ChartAction action) + { + if (Event.current.type == EventType.Repaint) + { + string[] array = new string[this.m_Series.Length]; + for (int i = 0; i < this.m_Series.Length; i++) + { + string propertyName = (!this.m_Data.hasOverlay) ? this.m_Series[i].identifierName : ("Selected" + this.m_Series[i].identifierName); + int statisticsIdentifier = ProfilerDriver.GetStatisticsIdentifier(propertyName); + array[i] = ProfilerDriver.GetFormattedStatisticsValue(currentFrame, statisticsIdentifier); + } + this.m_Data.selectedLabels = array; + } + return this.m_Chart.DoGUI(this.m_Type, currentFrame, this.m_Data, currentArea == this.m_Area, this.m_Icon, out action); + } + public void LoadAndBindSettings() + { + this.m_Chart.LoadAndBindSettings("ProfilerChart" + this.m_Area, this.m_Data); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerColors.cs b/UnityEditor/UnityEditorInternal/ProfilerColors.cs new file mode 100644 index 00000000..a6f5c4f8 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerColors.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class ProfilerColors + { + internal static Color[] colors = new Color[] + { + new Color(0.4831376f, 0.6211768f, 0.0219608f, 1f), + new Color(0.2070592f, 0.5333336f, 0.6556864f, 1f), + new Color(0.8f, 0.4423528f, 0f, 1f), + new Color(0.4486272f, 0.4078432f, 0.050196f, 1f), + new Color(0.7749016f, 0.6368624f, 0.0250984f, 1f), + new Color(0.5333336f, 0.16f, 0.0282352f, 1f), + new Color(0.3827448f, 0.2886272f, 0.5239216f, 1f), + new Color(0.279216f, 0.4078432f, 0.5835296f, 1f) + }; + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerColumn.cs b/UnityEditor/UnityEditorInternal/ProfilerColumn.cs new file mode 100644 index 00000000..28a2bfc3 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerColumn.cs @@ -0,0 +1,21 @@ +using System; +namespace UnityEditorInternal +{ + public enum ProfilerColumn + { + FunctionName, + TotalPercent, + SelfPercent, + Calls, + GCMemory, + TotalTime, + SelfTime, + DrawCalls, + TotalGPUTime, + SelfGPUTime, + TotalGPUPercent, + SelfGPUPercent, + WarningCount, + ObjectName + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerDriver.cs b/UnityEditor/UnityEditorInternal/ProfilerDriver.cs new file mode 100644 index 00000000..cf7f4096 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerDriver.cs @@ -0,0 +1,159 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class ProfilerDriver + { + public static extern int firstFrameIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int lastFrameIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int maxHistoryLength + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string selectedPropertyPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool profileEditor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool deepProfiling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int connectedProfiler + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string miniMemoryOverview + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern uint usedHeapSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern uint objectCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isGPUProfilerBuggyOnDriver + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isGPUProfilerSupportedByOS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isGPUProfilerSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BeginFrame(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void EndFrame(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNextFrameIndex(int frame); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPreviousFrameIndex(int frame); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetFormattedStatisticsValue(int frame, int identifier); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetStatisticsValues(int identifier, int firstFrame, float scale, float[] buffer, out float maxValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearAllFrames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAllStatisticsProperties(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetGraphStatisticsPropertiesForArea(ProfilerArea area); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStatisticsIdentifier(string propertyName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void CaptureHeapshot(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int[] GetAvailableProfilers(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetConnectionIdentifier(int guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsIdentifierConnectable(int guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsIdentifierOnLocalhost(int guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsConnectionEditor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DirectIPConnect(string IP); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DirectURLConnect(string url); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetOverviewText(ProfilerArea profilerArea, int frame); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RequestObjectMemoryInfo(); + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs b/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs new file mode 100644 index 00000000..e53c0944 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs @@ -0,0 +1,83 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class ProfilerFrameDataIterator + { + private IntPtr m_Ptr; + public extern int group + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string path + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int id + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float frameTimeMS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float startTimeMS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float durationMS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProfilerFrameDataIterator(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~ProfilerFrameDataIterator() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Next(bool enterChildren); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetThreadCount(int frame); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern double GetFrameStartS(int frame); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetThreadName(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetRoot(int frame, int threadIdx); + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs new file mode 100644 index 00000000..20957cd9 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs @@ -0,0 +1,645 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class ProfilerHierarchyGUI + { + internal class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle header = "OL title"; + public GUIStyle rightHeader = "OL title TextRight"; + public GUIStyle entryEven = "OL EntryBackEven"; + public GUIStyle entryOdd = "OL EntryBackOdd"; + public GUIStyle numberLabel = "OL Label"; + public GUIStyle foldout = "IN foldout"; + } + private const float kRowHeight = 16f; + private const float kFoldoutSize = 14f; + private const float kIndent = 16f; + private const float kSmallMargin = 4f; + private const float kBaseIndent = 4f; + private const int kFirst = -999999; + private const int kLast = 999999; + private const float kScrollbarWidth = 16f; + private static int hierarchyViewHash = "HierarchyView".GetHashCode(); + private static ProfilerHierarchyGUI.Styles ms_Styles; + private IProfilerWindowController m_Window; + private SplitterState m_Splitter; + private ProfilerColumn[] m_ColumnsToShow; + private string[] m_ColumnNames; + private bool[] m_VisibleColumns; + private float[] m_SplitterRelativeSizes; + private int[] m_SplitterMinWidths; + private string m_ColumnSettingsName; + private Vector2 m_TextScroll = Vector2.zero; + private GUIContent[] m_HeaderContent; + private SerializedStringTable m_ExpandedHash = new SerializedStringTable(); + private bool m_ExpandAll; + private int m_ScrollViewHeight; + private int m_DoScroll; + private int m_SelectedIndex = -1; + private bool m_DetailPane; + private ProfilerColumn m_SortType = ProfilerColumn.TotalTime; + private string m_DetailViewSelectedProperty = string.Empty; + private static ProfilerHierarchyGUI.Styles styles + { + get + { + ProfilerHierarchyGUI.Styles arg_17_0; + if ((arg_17_0 = ProfilerHierarchyGUI.ms_Styles) == null) + { + arg_17_0 = (ProfilerHierarchyGUI.ms_Styles = new ProfilerHierarchyGUI.Styles()); + } + return arg_17_0; + } + } + public int selectedIndex + { + get + { + return this.m_SelectedIndex; + } + set + { + this.m_SelectedIndex = value; + } + } + public ProfilerColumn sortType + { + get + { + return this.m_SortType; + } + private set + { + this.m_SortType = value; + } + } + public ProfilerHierarchyGUI(IProfilerWindowController window, string columnSettingsName, ProfilerColumn[] columnsToShow, string[] columnNames, bool detailPane, ProfilerColumn sort) + { + this.m_Window = window; + this.m_ColumnNames = columnNames; + this.m_ColumnSettingsName = columnSettingsName; + this.m_ColumnsToShow = columnsToShow; + this.m_DetailPane = detailPane; + this.m_SortType = sort; + this.m_HeaderContent = new GUIContent[columnNames.Length]; + this.m_Splitter = null; + for (int i = 0; i < this.m_HeaderContent.Length; i++) + { + this.m_HeaderContent[i] = EditorGUIUtility.TextContent(this.m_ColumnNames[i]); + } + if (columnsToShow.Length != columnNames.Length) + { + throw new ArgumentException("Number of columns to show does not match number of column names."); + } + this.m_VisibleColumns = new bool[columnNames.Length]; + for (int j = 0; j < this.m_VisibleColumns.Length; j++) + { + this.m_VisibleColumns[j] = true; + } + } + private void SetupSplitter() + { + if (this.m_Splitter != null && this.m_SplitterMinWidths != null) + { + return; + } + this.m_SplitterRelativeSizes = new float[this.m_ColumnNames.Length]; + this.m_SplitterMinWidths = new int[this.m_ColumnNames.Length]; + for (int i = 0; i < this.m_SplitterRelativeSizes.Length; i++) + { + this.m_SplitterMinWidths[i] = (int)ProfilerHierarchyGUI.styles.header.CalcSize(this.m_HeaderContent[i]).x; + this.m_SplitterRelativeSizes[i] = 70f; + if (this.m_HeaderContent[i].image != null) + { + this.m_SplitterRelativeSizes[i] = 1f; + } + } + if (this.m_ColumnsToShow[0] == ProfilerColumn.FunctionName) + { + this.m_SplitterRelativeSizes[0] = 400f; + this.m_SplitterMinWidths[0] = 100; + } + this.m_Splitter = new SplitterState(this.m_SplitterRelativeSizes, this.m_SplitterMinWidths, null); + string @string = EditorPrefs.GetString(this.m_ColumnSettingsName); + for (int j = 0; j < this.m_ColumnNames.Length; j++) + { + if (j < @string.Length && @string[j] == '0') + { + this.SetColumnVisible(j, false); + } + } + } + public ProfilerProperty GetDetailedProperty(ProfilerProperty property) + { + bool enterChildren = true; + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + while (property.Next(enterChildren)) + { + string propertyPath = property.propertyPath; + if (propertyPath == selectedPropertyPath) + { + ProfilerProperty profilerProperty = new ProfilerProperty(); + profilerProperty.InitializeDetailProperty(property); + return profilerProperty; + } + if (property.HasChildren) + { + enterChildren = this.IsExpanded(propertyPath); + } + } + return null; + } + private void DoScroll() + { + this.m_DoScroll = 2; + } + private void MoveSelection(int steps) + { + int num = this.m_SelectedIndex + steps; + if (num < 0) + { + num = 0; + } + ProfilerProperty profilerProperty = this.m_Window.CreateProperty(this.m_DetailPane); + if (this.m_DetailPane) + { + ProfilerProperty detailedProperty = this.GetDetailedProperty(profilerProperty); + profilerProperty.Cleanup(); + profilerProperty = detailedProperty; + } + if (profilerProperty == null) + { + return; + } + bool enterChildren = true; + int num2 = 0; + int instanceId = -1; + while (profilerProperty.Next(enterChildren)) + { + if (this.m_DetailPane && profilerProperty.instanceIDs != null && profilerProperty.instanceIDs.Length > 0 && profilerProperty.instanceIDs[0] != 0) + { + instanceId = profilerProperty.instanceIDs[0]; + } + if (num2 == num) + { + break; + } + if (profilerProperty.HasChildren) + { + enterChildren = (!this.m_DetailPane && this.IsExpanded(profilerProperty.propertyPath)); + } + num2++; + } + if (this.m_DetailPane) + { + this.m_DetailViewSelectedProperty = ProfilerHierarchyGUI.DetailViewSelectedPropertyPath(profilerProperty, instanceId); + } + else + { + this.m_Window.SetSelectedPropertyPath(profilerProperty.propertyPath); + } + profilerProperty.Cleanup(); + } + private void SetExpanded(string expandedName, bool expanded) + { + if (expanded != this.IsExpanded(expandedName)) + { + if (expanded) + { + this.m_ExpandedHash.Set(expandedName); + } + else + { + this.m_ExpandedHash.Remove(expandedName); + } + } + } + private void HandleKeyboard(int id) + { + Event current = Event.current; + if (current.GetTypeForControl(id) != EventType.KeyDown || id != GUIUtility.keyboardControl) + { + return; + } + switch (current.keyCode) + { + case KeyCode.UpArrow: + this.MoveSelection(-1); + goto IL_16A; + case KeyCode.DownArrow: + this.MoveSelection(1); + goto IL_16A; + case KeyCode.RightArrow: + this.SetExpanded(ProfilerDriver.selectedPropertyPath, true); + goto IL_16A; + case KeyCode.LeftArrow: + this.SetExpanded(ProfilerDriver.selectedPropertyPath, false); + goto IL_16A; + case KeyCode.Home: + this.MoveSelection(-999999); + goto IL_16A; + case KeyCode.End: + this.MoveSelection(999999); + goto IL_16A; + case KeyCode.PageUp: + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_TextScroll.y = this.m_TextScroll.y - (float)this.m_ScrollViewHeight; + if (this.m_TextScroll.y < 0f) + { + this.m_TextScroll.y = 0f; + } + current.Use(); + return; + } + this.MoveSelection(-Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f)); + goto IL_16A; + case KeyCode.PageDown: + if (Application.platform == RuntimePlatform.OSXEditor) + { + this.m_TextScroll.y = this.m_TextScroll.y + (float)this.m_ScrollViewHeight; + current.Use(); + return; + } + this.MoveSelection(Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f)); + goto IL_16A; + } + return; + IL_16A: + this.DoScroll(); + current.Use(); + } + private void DrawColumnsHeader() + { + bool flag = false; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (Event.current.type == EventType.MouseDown && Event.current.button == 1) + { + flag = true; + Event.current.type = EventType.Used; + } + SplitterGUILayout.BeginHorizontalSplit(this.m_Splitter, EditorStyles.toolbar, new GUILayoutOption[0]); + for (int i = 0; i < this.m_ColumnNames.Length; i++) + { + this.DrawTitle(this.m_HeaderContent[i], i); + } + SplitterGUILayout.EndHorizontalSplit(); + GUILayout.Box(string.Empty, ProfilerHierarchyGUI.ms_Styles.header, new GUILayoutOption[] + { + GUILayout.Width(16f) + }); + GUILayout.EndHorizontal(); + if (flag) + { + Event.current.type = EventType.MouseDown; + this.HandleHeaderMouse(GUILayoutUtility.GetLastRect()); + } + } + private bool IsExpanded(string expanded) + { + return this.m_ExpandAll || this.m_ExpandedHash.Contains(expanded); + } + private void SetExpanded(ProfilerProperty property, bool expanded) + { + this.SetExpanded(property.propertyPath, expanded); + } + private int DrawProfilingData(ProfilerProperty property, int id) + { + this.m_SelectedIndex = -1; + bool enterChildren = true; + int num = 0; + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + while (property.Next(enterChildren)) + { + string propertyPath = property.propertyPath; + bool flag = (!this.m_DetailPane) ? (propertyPath == selectedPropertyPath) : (this.m_DetailViewSelectedProperty != string.Empty && this.m_DetailViewSelectedProperty == ProfilerHierarchyGUI.DetailViewSelectedPropertyPath(property)); + if (flag) + { + this.m_SelectedIndex = num; + } + bool flag2 = Event.current.type != EventType.Layout; + flag2 &= (this.m_ScrollViewHeight == 0 || ((float)num * 16f <= (float)this.m_ScrollViewHeight + this.m_TextScroll.y && (float)(num + 1) * 16f > this.m_TextScroll.y)); + if (flag2) + { + enterChildren = this.DrawProfileDataItem(property, num, flag, id); + } + else + { + enterChildren = (property.HasChildren && this.IsExpanded(propertyPath)); + } + num++; + } + return num; + } + private void UnselectIfClickedOnEmptyArea(int rowCount) + { + Rect rect = GUILayoutUtility.GetRect(GUIClip.visibleRect.width, 16f * (float)rowCount, new GUILayoutOption[] + { + GUILayout.MinHeight(16f * (float)rowCount) + }); + if (Event.current.type != EventType.MouseDown || Event.current.mousePosition.y <= rect.y || Event.current.mousePosition.y >= (float)Screen.height) + { + return; + } + if (!this.m_DetailPane) + { + this.m_Window.ClearSelectedPropertyPath(); + } + else + { + this.m_DetailViewSelectedProperty = string.Empty; + } + Event.current.Use(); + } + private void HandleHeaderMouse(Rect columnHeaderRect) + { + Event current = Event.current; + if (current.type != EventType.MouseDown || current.button != 1 || !columnHeaderRect.Contains(current.mousePosition)) + { + return; + } + GUIUtility.hotControl = 0; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, this.m_ColumnNames, this.GetVisibleDropDownIndexList(), new EditorUtility.SelectMenuItemFunction(this.ColumnContextClick), null); + current.Use(); + } + private void SetColumnVisible(int index, bool enabled) + { + this.SetupSplitter(); + if (index == 0) + { + return; + } + if (this.m_VisibleColumns[index] == enabled) + { + return; + } + this.m_VisibleColumns[index] = enabled; + int num = 0; + for (int i = 0; i < index; i++) + { + if (this.ColIsVisible(i)) + { + num++; + } + } + if (enabled) + { + ArrayUtility.Insert(ref this.m_Splitter.relativeSizes, num, this.m_SplitterRelativeSizes[index]); + ArrayUtility.Insert(ref this.m_Splitter.minSizes, num, this.m_SplitterMinWidths[index]); + } + else + { + ArrayUtility.RemoveAt(ref this.m_Splitter.relativeSizes, num); + ArrayUtility.RemoveAt(ref this.m_Splitter.minSizes, num); + } + this.m_Splitter = new SplitterState(this.m_Splitter.relativeSizes, this.m_Splitter.minSizes, null); + this.SaveColumns(); + } + private int[] GetVisibleDropDownIndexList() + { + List list = new List(); + for (int i = 0; i < this.m_ColumnNames.Length; i++) + { + if (this.m_VisibleColumns[i]) + { + list.Add(i); + } + } + return list.ToArray(); + } + private void SaveColumns() + { + string text = string.Empty; + for (int i = 0; i < this.m_VisibleColumns.Length; i++) + { + text += ((!this.ColIsVisible(i)) ? '0' : '1'); + } + EditorPrefs.SetString(this.m_ColumnSettingsName, text); + } + private bool ColIsVisible(int index) + { + return index >= 0 && index <= this.m_VisibleColumns.Length && this.m_VisibleColumns[index]; + } + private void ColumnContextClick(object userData, string[] options, int selected) + { + this.SetColumnVisible(selected, !this.ColIsVisible(selected)); + } + private void DrawTextColumn(ref Rect currentRect, string text, int index, float margin, bool selected) + { + if (index != 0) + { + currentRect.x += (float)this.m_Splitter.realSizes[index - 1]; + } + currentRect.x += margin; + currentRect.width = (float)this.m_Splitter.realSizes[index] - margin; + ProfilerHierarchyGUI.styles.numberLabel.Draw(currentRect, text, false, false, false, selected); + currentRect.x -= margin; + } + private static string DetailViewSelectedPropertyPath(ProfilerProperty property) + { + if (property == null || property.instanceIDs == null || property.instanceIDs.Length == 0 || property.instanceIDs[0] == 0) + { + return string.Empty; + } + return ProfilerHierarchyGUI.DetailViewSelectedPropertyPath(property, property.instanceIDs[0]); + } + private static string DetailViewSelectedPropertyPath(ProfilerProperty property, int instanceId) + { + return property.propertyPath + "/" + instanceId; + } + private bool DrawProfileDataItem(ProfilerProperty property, int rowCount, bool selected, int id) + { + bool flag = false; + Event current = Event.current; + Rect rect = new Rect(1f, 16f * (float)rowCount, GUIClip.visibleRect.width, 16f); + Rect position = rect; + GUIStyle gUIStyle = (rowCount % 2 != 0) ? ProfilerHierarchyGUI.styles.entryOdd : ProfilerHierarchyGUI.styles.entryEven; + if (current.type == EventType.Repaint) + { + gUIStyle.Draw(position, GUIContent.none, false, false, selected, false); + } + float num = (float)property.depth * 16f + 4f; + if (property.HasChildren) + { + flag = this.IsExpanded(property.propertyPath); + GUI.changed = false; + num -= 14f; + Rect position2 = new Rect(num, position.y, 14f, 16f); + flag = GUI.Toggle(position2, flag, GUIContent.none, ProfilerHierarchyGUI.styles.foldout); + if (GUI.changed) + { + this.SetExpanded(property, flag); + } + num += 16f; + } + if (current.type == EventType.Repaint) + { + this.DrawTextColumn(ref position, property.GetColumn(this.m_ColumnsToShow[0]), 0, (this.m_ColumnsToShow[0] != ProfilerColumn.FunctionName) ? 4f : num, selected); + ProfilerHierarchyGUI.styles.numberLabel.alignment = TextAnchor.MiddleRight; + int num2 = 1; + for (int i = 1; i < this.m_VisibleColumns.Length; i++) + { + if (this.ColIsVisible(i)) + { + position.x += (float)this.m_Splitter.realSizes[num2 - 1]; + position.width = (float)this.m_Splitter.realSizes[num2] - 4f; + num2++; + ProfilerHierarchyGUI.styles.numberLabel.Draw(position, property.GetColumn(this.m_ColumnsToShow[i]), false, false, false, selected); + } + } + ProfilerHierarchyGUI.styles.numberLabel.alignment = TextAnchor.MiddleLeft; + } + if (current.type == EventType.MouseDown && rect.Contains(current.mousePosition)) + { + GUIUtility.hotControl = 0; + if (!EditorGUI.actionKey) + { + if (this.m_DetailPane) + { + if (current.clickCount == 1 && property.instanceIDs.Length > 0) + { + string text = ProfilerHierarchyGUI.DetailViewSelectedPropertyPath(property); + if (this.m_DetailViewSelectedProperty != text) + { + this.m_DetailViewSelectedProperty = text; + UnityEngine.Object @object = EditorUtility.InstanceIDToObject(property.instanceIDs[0]); + if (@object is Component) + { + @object = ((Component)@object).gameObject; + } + EditorGUIUtility.PingObject(@object.GetInstanceID()); + } + else + { + this.m_DetailViewSelectedProperty = string.Empty; + } + } + else + { + if (current.clickCount == 2) + { + ProfilerHierarchyGUI.SelectObjectsInHierarchyView(property); + this.m_DetailViewSelectedProperty = ProfilerHierarchyGUI.DetailViewSelectedPropertyPath(property); + } + } + } + else + { + if (property.propertyPath == ProfilerDriver.selectedPropertyPath) + { + this.m_Window.ClearSelectedPropertyPath(); + } + else + { + this.m_Window.SetSelectedPropertyPath(property.propertyPath); + } + } + this.DoScroll(); + } + else + { + if (!this.m_DetailPane) + { + this.m_Window.ClearSelectedPropertyPath(); + } + else + { + this.m_DetailViewSelectedProperty = string.Empty; + } + } + GUIUtility.keyboardControl = id; + current.Use(); + } + if (selected && GUIUtility.keyboardControl == id && current.type == EventType.KeyDown && (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter)) + { + ProfilerHierarchyGUI.SelectObjectsInHierarchyView(property); + } + return flag; + } + private static void SelectObjectsInHierarchyView(ProfilerProperty property) + { + int[] instanceIDs = property.instanceIDs; + List list = new List(); + int[] array = instanceIDs; + for (int i = 0; i < array.Length; i++) + { + int instanceID = array[i]; + UnityEngine.Object @object = EditorUtility.InstanceIDToObject(instanceID); + Component component = @object as Component; + if (component != null) + { + list.Add(component.gameObject); + } + else + { + if (@object != null) + { + list.Add(@object); + } + } + } + if (list.Count != 0) + { + Selection.objects = list.ToArray(); + } + } + private void DrawTitle(GUIContent name, int index) + { + if (!this.ColIsVisible(index)) + { + return; + } + ProfilerColumn profilerColumn = this.m_ColumnsToShow[index]; + bool value = this.sortType == profilerColumn; + bool flag = (index != 0) ? GUILayout.Toggle(value, name, ProfilerHierarchyGUI.styles.rightHeader, new GUILayoutOption[] + { + GUILayout.Width((float)this.m_SplitterMinWidths[index]) + }) : GUILayout.Toggle(value, name, ProfilerHierarchyGUI.styles.header, new GUILayoutOption[0]); + if (flag) + { + this.sortType = profilerColumn; + } + } + private void DoScrolling() + { + if (this.m_DoScroll > 0) + { + this.m_DoScroll--; + if (this.m_DoScroll == 0) + { + float num = 16f * (float)this.m_SelectedIndex; + float min = num - (float)this.m_ScrollViewHeight + 16f; + this.m_TextScroll.y = Mathf.Clamp(this.m_TextScroll.y, min, num); + } + else + { + this.m_Window.Repaint(); + } + } + } + public void DoGUI(ProfilerProperty property, bool expandAll) + { + this.m_ExpandAll = expandAll; + this.SetupSplitter(); + this.DoScrolling(); + int controlID = GUIUtility.GetControlID(ProfilerHierarchyGUI.hierarchyViewHash, FocusType.Passive); + this.DrawColumnsHeader(); + this.m_TextScroll = EditorGUILayout.BeginScrollView(this.m_TextScroll, ProfilerHierarchyGUI.ms_Styles.background, new GUILayoutOption[0]); + int rowCount = this.DrawProfilingData(property, controlID); + property.Cleanup(); + this.UnselectIfClickedOnEmptyArea(rowCount); + if (Event.current.type == EventType.Repaint) + { + this.m_ScrollViewHeight = (int)GUIClip.visibleRect.height; + } + GUILayout.EndScrollView(); + this.HandleKeyboard(controlID); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerMemoryView.cs b/UnityEditor/UnityEditorInternal/ProfilerMemoryView.cs new file mode 100644 index 00000000..103bb9f6 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerMemoryView.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditorInternal +{ + public enum ProfilerMemoryView + { + Simple, + Detailed + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerProperty.cs b/UnityEditor/UnityEditorInternal/ProfilerProperty.cs new file mode 100644 index 00000000..4723b179 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerProperty.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class ProfilerProperty + { + private IntPtr m_Ptr; + public extern bool HasChildren + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool onlyShowGPUSamples + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int[] instanceIDs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string propertyPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string frameFPS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string frameTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string frameGpuTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool frameDataReady + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProfilerProperty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~ProfilerProperty() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Cleanup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Next(bool enterChildren); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetRoot(int frame, ProfilerColumn profilerSortColumn, ProfilerViewType viewType); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InitializeDetailProperty(ProfilerProperty source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetTooltip(ProfilerColumn column); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetColumn(ProfilerColumn column); + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs b/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs new file mode 100644 index 00000000..2ea54e4e --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs @@ -0,0 +1,400 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + [Serializable] + internal class ProfilerTimelineGUI + { + internal class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle tooltip = "AnimationEventTooltip"; + public GUIStyle tooltipArrow = "AnimationEventTooltipArrow"; + public GUIStyle bar; + internal Styles() + { + this.bar = new GUIStyle(EditorStyles.miniButton); + this.bar.margin = new RectOffset(0, 0, 0, 0); + this.bar.padding = new RectOffset(0, 0, 0, 0); + this.bar.border = new RectOffset(1, 1, 1, 1); + GUIStyleState arg_B8_0 = this.bar.normal; + Texture2D texture2D = EditorGUIUtility.whiteTexture; + this.bar.active.background = texture2D; + texture2D = texture2D; + this.bar.hover.background = texture2D; + arg_B8_0.background = texture2D; + GUIStyleState arg_F3_0 = this.bar.normal; + Color color = Color.black; + this.bar.active.textColor = color; + color = color; + this.bar.hover.textColor = color; + arg_F3_0.textColor = color; + } + } + private const float kSmallWidth = 7f; + private const float kTextFadeStartWidth = 50f; + private const float kTextFadeOutWidth = 20f; + private const float kTextLongWidth = 200f; + private const float kLineHeight = 16f; + private static ProfilerTimelineGUI.Styles ms_Styles; + [NonSerialized] + private ZoomableArea m_TimeArea; + private IProfilerWindowController m_Window; + private int m_SelectedThread; + private int m_SelectedID = -1; + private float m_SelectedTime; + private float m_SelectedDur; + private static ProfilerTimelineGUI.Styles styles + { + get + { + ProfilerTimelineGUI.Styles arg_17_0; + if ((arg_17_0 = ProfilerTimelineGUI.ms_Styles) == null) + { + arg_17_0 = (ProfilerTimelineGUI.ms_Styles = new ProfilerTimelineGUI.Styles()); + } + return arg_17_0; + } + } + public ProfilerTimelineGUI(IProfilerWindowController window) + { + this.m_Window = window; + } + private float GetThreadY(Rect r, int thread, int threadCount) + { + if (thread > 0) + { + thread += 2; + } + return r.y + r.height / (float)(threadCount + 2) * (float)thread; + } + private void DrawGrid(Rect r, int threadCount, float frameTime) + { + HandleUtility.handleWireMaterial.SetPass(0); + float num = 16.66667f; + GL.Begin(1); + GL.Color(new Color(1f, 1f, 1f, 0.2f)); + for (int i = 0; i < threadCount; i++) + { + float threadY = this.GetThreadY(r, i, threadCount); + GL.Vertex3(r.x, threadY, 0f); + GL.Vertex3(r.x + r.width, threadY, 0f); + } + float num3; + for (float num2 = num; num2 <= frameTime; num2 += num) + { + num3 = this.m_TimeArea.TimeToPixel(num2, r); + GL.Vertex3(num3, r.y, 0f); + GL.Vertex3(num3, r.y + r.height, 0f); + } + GL.Color(new Color(1f, 1f, 1f, 0.8f)); + num3 = this.m_TimeArea.TimeToPixel(0f, r); + GL.Vertex3(num3, r.y, 0f); + GL.Vertex3(num3, r.y + r.height, 0f); + num3 = this.m_TimeArea.TimeToPixel(frameTime, r); + GL.Vertex3(num3, r.y, 0f); + GL.Vertex3(num3, r.y + r.height, 0f); + GL.End(); + GUI.color = new Color(1f, 1f, 1f, 0.4f); + for (float num2 = 0f; num2 <= frameTime; num2 += num) + { + num3 = this.m_TimeArea.TimeToPixel(num2, r); + GUI.Label(new Rect(num3, r.yMax - 16f, 200f, 16f), string.Format("{0:f1}ms ({1:f0}FPS)", num2, 1000f / num2)); + } + GUI.color = new Color(1f, 1f, 1f, 1f); + num3 = this.m_TimeArea.TimeToPixel(frameTime, r); + GUI.Label(new Rect(num3, r.yMax - 16f, 200f, 16f), string.Format("{0:f1}ms ({1:f0}FPS)", frameTime, 1000f / frameTime)); + } + private void DrawSmallGroup(float x1, float x2, float y, int size) + { + if (x2 - x1 < 1f) + { + return; + } + GUI.color = new Color(0.5f, 0.5f, 0.5f, 0.7f); + GUI.contentColor = Color.white; + GUIContent content = GUIContent.none; + if (x2 - x1 > 20f) + { + content = new GUIContent(size + " items"); + } + GUI.Label(new Rect(x1, y, x2 - x1, 14f), content, ProfilerTimelineGUI.styles.bar); + } + private static float TimeToPixelCached(float time, float rectWidthDivShownWidth, float shownX, float rectX) + { + return (time - shownX) * rectWidthDivShownWidth + rectX; + } + private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threadIdx, float timeOffset, bool ghost) + { + float num = (!ghost) ? 7f : 21f; + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + bool enterChildren = true; + Color color = GUI.color; + Color contentColor = GUI.contentColor; + Color[] colors = ProfilerColors.colors; + bool flag = false; + float x = -1f; + float num2 = -1f; + float num3 = -1f; + int num4 = 0; + float num5 = -1f; + string text = null; + r.height -= 1f; + GUI.BeginGroup(r); + float num6 = 0f; + r.y = num6; + r.x = num6; + if (!ghost) + { + GUI.Label(new Rect(r.x, r.y + r.height * 0.5f - 8f, r.width, 16f), iter.GetThreadName()); + } + Rect shownArea = this.m_TimeArea.shownArea; + float rectWidthDivShownWidth = r.width / shownArea.width; + float x2 = r.x; + float x3 = shownArea.x; + while (iter.Next(enterChildren)) + { + enterChildren = true; + float num7 = iter.startTimeMS + timeOffset * 1000f; + float durationMS = iter.durationMS; + float num8 = Mathf.Max(durationMS, 0.0003f); + float num9 = ProfilerTimelineGUI.TimeToPixelCached(num7, rectWidthDivShownWidth, x3, x2); + float num10 = ProfilerTimelineGUI.TimeToPixelCached(num7 + num8, rectWidthDivShownWidth, x3, x2) - 1f; + float num11 = num10 - num9; + if (num9 > r.x + r.width || num10 < r.x) + { + enterChildren = false; + } + else + { + float num12 = (float)(iter.depth - 1); + float num13 = r.y + num12 * 16f; + if (flag) + { + bool flag2 = false; + if (num11 >= num) + { + flag2 = true; + } + if (num3 != num13) + { + flag2 = true; + } + if (num9 - num2 > 6f) + { + flag2 = true; + } + if (flag2) + { + this.DrawSmallGroup(x, num2, num3, num4); + flag = false; + } + } + if (num11 < num) + { + enterChildren = false; + if (!flag) + { + flag = true; + num3 = num13; + x = num9; + num4 = 0; + } + num2 = num10; + num4++; + } + else + { + int id = iter.id; + string path = iter.path; + bool flag3 = path == selectedPropertyPath && !ghost; + if (this.m_SelectedID >= 0) + { + flag3 &= (id == this.m_SelectedID); + } + flag3 &= (threadIdx == this.m_SelectedThread); + Color white = Color.white; + Color color2 = colors[iter.group % colors.Length]; + color2.a = ((!flag3) ? 0.75f : 1f); + if (ghost) + { + color2.a = 0.4f; + white.a = 0.5f; + } + string text2 = iter.name; + if (flag3) + { + text = text2; + this.m_SelectedTime = num7; + this.m_SelectedDur = durationMS; + num5 = num13 + 16f; + } + if (num11 < 20f) + { + text2 = string.Empty; + } + else + { + if (num11 < 50f && !flag3) + { + white.a *= (num11 - 20f) / 30f; + } + if (num11 > 200f) + { + text2 += string.Format(" ({0:f2}ms)", durationMS); + } + } + GUI.color = color2; + GUI.contentColor = white; + if (GUI.Button(new Rect(num9, num13, num11, 14f), text2, ProfilerTimelineGUI.styles.bar)) + { + this.m_Window.SetSelectedPropertyPath(path); + this.m_SelectedThread = threadIdx; + this.m_SelectedID = id; + } + flag = false; + } + } + } + if (flag) + { + this.DrawSmallGroup(x, num2, num3, num4); + } + GUI.color = color; + GUI.contentColor = contentColor; + if (text != null && threadIdx == this.m_SelectedThread) + { + string text3 = string.Format(((double)this.m_SelectedDur < 1.0) ? "{0}\n{1:f3}ms" : "{0}\n{1:f2}ms", text, this.m_SelectedDur); + GUIContent content = new GUIContent(text3); + GUIStyle tooltip = ProfilerTimelineGUI.styles.tooltip; + Vector2 vector = tooltip.CalcSize(content); + float num14 = this.m_TimeArea.TimeToPixel(this.m_SelectedTime + this.m_SelectedDur * 0.5f, r); + if (num14 < r.x) + { + num14 = r.x + 20f; + } + if (num14 > r.xMax) + { + num14 = r.xMax - 20f; + } + Rect position; + if (num5 + 6f + vector.y < r.yMax) + { + position = new Rect(num14 - 32f, num5, 50f, 7f); + GUI.Label(position, GUIContent.none, ProfilerTimelineGUI.styles.tooltipArrow); + } + position = new Rect(num14, num5 + 6f, vector.x, vector.y); + if (position.xMax > r.xMax + 20f) + { + position.x = r.xMax - position.width + 20f; + } + if (position.yMax > r.yMax) + { + position.y = r.yMax - position.height; + } + if (position.y < r.y) + { + position.y = r.y; + } + GUI.Label(position, content, tooltip); + } + if (Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition)) + { + this.m_Window.ClearSelectedPropertyPath(); + this.m_SelectedID = -1; + this.m_SelectedThread = threadIdx; + Event.current.Use(); + } + GUI.EndGroup(); + } + private void PerformFrameSelected(float frameMS) + { + float num = this.m_SelectedTime; + float num2 = this.m_SelectedDur; + if (this.m_SelectedID < 0 || num2 <= 0f) + { + num = 0f; + num2 = frameMS; + } + this.m_TimeArea.SetShownHRange(num - num2 * 0.1f, num + num2 * 1.1f); + } + private void HandleFrameSelected(float frameMS) + { + Event current = Event.current; + if ((current.type == EventType.ValidateCommand || current.type == EventType.ExecuteCommand) && current.commandName == "FrameSelected") + { + bool flag = current.type == EventType.ExecuteCommand; + if (flag) + { + this.PerformFrameSelected(frameMS); + } + current.Use(); + } + } + private void DoProfilerFrame(int frameIndex, Rect fullRect, bool ghost, ref int threadCount, ref double startTime) + { + ProfilerFrameDataIterator profilerFrameDataIterator = new ProfilerFrameDataIterator(); + int threadCount2 = profilerFrameDataIterator.GetThreadCount(frameIndex); + double frameStartS = profilerFrameDataIterator.GetFrameStartS(frameIndex); + if (ghost && threadCount2 != threadCount) + { + return; + } + if (!ghost) + { + threadCount = threadCount2; + startTime = frameStartS; + } + for (int i = 0; i < threadCount; i++) + { + Rect r = fullRect; + r.y = this.GetThreadY(fullRect, i, threadCount); + r.height = this.GetThreadY(fullRect, i + 1, threadCount) - r.y; + profilerFrameDataIterator.SetRoot(frameIndex, i); + if (i == 0 && !ghost) + { + this.DrawGrid(fullRect, threadCount, profilerFrameDataIterator.frameTimeMS); + this.HandleFrameSelected(profilerFrameDataIterator.frameTimeMS); + } + this.DrawProfilingData(profilerFrameDataIterator, r, i, (float)(frameStartS - startTime), ghost); + } + } + public void DoGUI(int frameIndex, float width, float ypos, float height) + { + Rect drawRect = new Rect(0f, ypos, width, height); + if (this.m_TimeArea == null) + { + this.m_TimeArea = new ZoomableArea(); + this.m_TimeArea.hRangeLocked = false; + this.m_TimeArea.vRangeLocked = true; + this.m_TimeArea.hSlider = true; + this.m_TimeArea.vSlider = false; + this.m_TimeArea.scaleWithWindow = true; + this.m_TimeArea.rect = drawRect; + this.m_TimeArea.SetShownHRangeInsideMargins(-2f, 33.3f); + this.m_TimeArea.OnEnable(); + } + this.m_TimeArea.rect = drawRect; + this.m_TimeArea.BeginViewGUI(); + this.m_TimeArea.EndViewGUI(); + drawRect = this.m_TimeArea.drawRect; + int num = 0; + double num2 = 0.0; + this.DoProfilerFrame(frameIndex, drawRect, false, ref num, ref num2); + bool enabled = GUI.enabled; + GUI.enabled = false; + int previousFrameIndex = ProfilerDriver.GetPreviousFrameIndex(frameIndex); + if (previousFrameIndex != -1) + { + this.DoProfilerFrame(previousFrameIndex, drawRect, true, ref num, ref num2); + } + int nextFrameIndex = ProfilerDriver.GetNextFrameIndex(frameIndex); + if (nextFrameIndex != -1) + { + this.DoProfilerFrame(nextFrameIndex, drawRect, true, ref num, ref num2); + } + GUI.enabled = enabled; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerViewType.cs b/UnityEditor/UnityEditorInternal/ProfilerViewType.cs new file mode 100644 index 00000000..09c8e4c6 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerViewType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditorInternal +{ + public enum ProfilerViewType + { + Hierarchy, + Timeline, + RawHierarchy + } +} diff --git a/UnityEditor/UnityEditorInternal/RegistryUtil.cs b/UnityEditor/UnityEditorInternal/RegistryUtil.cs new file mode 100644 index 00000000..7fefbfd6 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/RegistryUtil.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class RegistryUtil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetRegistryStringValue32(string subKey, string valueName); + } +} diff --git a/UnityEditor/UnityEditorInternal/ReorderableList.cs b/UnityEditor/UnityEditorInternal/ReorderableList.cs new file mode 100644 index 00000000..bcfe4b2c --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ReorderableList.cs @@ -0,0 +1,651 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public class ReorderableList + { + public class Defaults + { + private const int buttonWidth = 25; + public const int padding = 6; + public const int dragHandleWidth = 20; + public GUIContent iconToolbarPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add to list"); + public GUIContent iconToolbarPlusMore = EditorGUIUtility.IconContent("Toolbar Plus More", "Choose to add to list"); + public GUIContent iconToolbarMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove selection from list"); + public readonly GUIStyle draggingHandle = "RL DragHandle"; + public readonly GUIStyle headerBackground = "RL Header"; + public readonly GUIStyle footerBackground = "RL Footer"; + public readonly GUIStyle boxBackground = "RL Background"; + public readonly GUIStyle preButton = "RL FooterButton"; + public GUIStyle elementBackground = new GUIStyle("RL Element"); + public void DrawFooter(Rect rect, ReorderableList list) + { + float xMax = rect.xMax; + float num = xMax - 8f; + if (list.displayAdd) + { + num -= 25f; + } + if (list.displayRemove) + { + num -= 25f; + } + rect = new Rect(num, rect.y, xMax - num, rect.height); + Rect rect2 = new Rect(num + 4f, rect.y - 3f, 25f, 13f); + Rect position = new Rect(xMax - 29f, rect.y - 3f, 25f, 13f); + if (Event.current.type == EventType.Repaint) + { + this.footerBackground.Draw(rect, false, false, false, false); + } + if (list.displayAdd && GUI.Button(rect2, (list.onAddDropdownCallback == null) ? this.iconToolbarPlus : this.iconToolbarPlusMore, this.preButton)) + { + if (list.onAddDropdownCallback != null) + { + list.onAddDropdownCallback(rect2, list); + } + else + { + if (list.onAddCallback != null) + { + list.onAddCallback(list); + } + else + { + this.DoAddButton(list); + } + } + if (list.onChangedCallback != null) + { + list.onChangedCallback(list); + } + } + if (list.displayRemove) + { + EditorGUI.BeginDisabledGroup(list.index < 0 || list.index >= list.count || (list.onCanRemoveCallback != null && !list.onCanRemoveCallback(list))); + if (GUI.Button(position, this.iconToolbarMinus, this.preButton)) + { + if (list.onRemoveCallback == null) + { + this.DoRemoveButton(list); + } + else + { + list.onRemoveCallback(list); + } + if (list.onChangedCallback != null) + { + list.onChangedCallback(list); + } + } + EditorGUI.EndDisabledGroup(); + } + } + public void DoAddButton(ReorderableList list) + { + if (list.serializedProperty != null) + { + list.serializedProperty.arraySize++; + list.index = list.serializedProperty.arraySize - 1; + } + else + { + Type elementType = list.list.GetType().GetElementType(); + if (elementType == typeof(string)) + { + list.index = list.list.Add(string.Empty); + } + else + { + if (elementType != null && elementType.GetConstructor(Type.EmptyTypes) == null) + { + Debug.LogError("Cannot add element. Type " + elementType.ToString() + " has no default constructor. Implement a default constructor or implement your own add behaviour."); + } + else + { + if (list.list.GetType().GetGenericArguments()[0] != null) + { + list.index = list.list.Add(Activator.CreateInstance(list.list.GetType().GetGenericArguments()[0])); + } + else + { + if (elementType != null) + { + list.index = list.list.Add(Activator.CreateInstance(elementType)); + } + else + { + Debug.LogError("Cannot add element of type Null."); + } + } + } + } + } + } + public void DoRemoveButton(ReorderableList list) + { + if (list.serializedProperty != null) + { + list.serializedProperty.DeleteArrayElementAtIndex(list.index); + if (list.index >= list.serializedProperty.arraySize - 1) + { + list.index = list.serializedProperty.arraySize - 1; + } + } + else + { + list.list.RemoveAt(list.index); + if (list.index >= list.list.Count - 1) + { + list.index = list.list.Count - 1; + } + } + } + public void DrawHeaderBackground(Rect headerRect) + { + if (Event.current.type == EventType.Repaint) + { + this.headerBackground.Draw(headerRect, false, false, false, false); + } + } + public void DrawHeader(Rect headerRect, SerializedObject serializedObject, SerializedProperty element, IList elementList) + { + EditorGUI.LabelField(headerRect, EditorGUIUtility.TempContent((element == null) ? "IList" : "Serialized Property")); + } + public void DrawElementBackground(Rect rect, bool selected, bool focused, bool draggable) + { + if (Event.current.type == EventType.Repaint) + { + this.elementBackground.Draw(rect, false, selected, selected, focused); + if (draggable) + { + this.draggingHandle.Draw(new Rect(rect.x + 5f, rect.y + 7f, 10f, rect.height - (rect.height - 7f)), false, false, false, false); + } + } + } + public void DrawElement(Rect rect, SerializedProperty element, object listItem, bool selected, bool focused, bool draggable) + { + EditorGUI.LabelField(rect, EditorGUIUtility.TempContent((element == null) ? listItem.ToString() : element.displayName)); + } + public void DrawNoneElement(Rect rect, bool draggable) + { + EditorGUI.LabelField(rect, EditorGUIUtility.TempContent("List is Empty")); + } + } + public delegate void HeaderCallbackDelegate(Rect rect); + public delegate void ElementCallbackDelegate(Rect rect, int index, bool isActive, bool isFocused); + public delegate void ReorderCallbackDelegate(ReorderableList list); + public delegate void SelectCallbackDelegate(ReorderableList list); + public delegate void AddCallbackDelegate(ReorderableList list); + public delegate void AddDropdownCallbackDelegate(Rect buttonRect, ReorderableList list); + public delegate void RemoveCallbackDelegate(ReorderableList list); + public delegate void ChangedCallbackDelegate(ReorderableList list); + public delegate bool CanRemoveCallbackDelegate(ReorderableList list); + public ReorderableList.HeaderCallbackDelegate drawHeaderCallback; + public ReorderableList.ElementCallbackDelegate drawElementCallback; + public ReorderableList.ReorderCallbackDelegate onReorderCallback; + public ReorderableList.SelectCallbackDelegate onSelectCallback; + public ReorderableList.AddCallbackDelegate onAddCallback; + public ReorderableList.AddDropdownCallbackDelegate onAddDropdownCallback; + public ReorderableList.RemoveCallbackDelegate onRemoveCallback; + public ReorderableList.CanRemoveCallbackDelegate onCanRemoveCallback; + public ReorderableList.ChangedCallbackDelegate onChangedCallback; + private int m_ActiveElement = -1; + private float m_DragOffset; + private GUISlideGroup m_SlideGroup; + private SerializedObject m_SerializedObject; + private SerializedProperty m_Elements; + private IList m_ElementList; + private bool m_Draggable; + private float m_DraggedY; + private bool m_Dragging; + private List m_NonDragTargetIndices; + private bool m_DisplayHeader; + public bool displayAdd; + public bool displayRemove; + private int id = -1; + private static ReorderableList.Defaults s_Defaults; + public float elementHeight = 21f; + public float headerHeight = 18f; + public float footerHeight = 13f; + public static ReorderableList.Defaults defaultBehaviours + { + get + { + return ReorderableList.s_Defaults; + } + } + public SerializedProperty serializedProperty + { + get + { + return this.m_Elements; + } + set + { + this.m_Elements = value; + } + } + public IList list + { + get + { + return this.m_ElementList; + } + set + { + this.m_ElementList = value; + } + } + public int index + { + get + { + return this.m_ActiveElement; + } + set + { + this.m_ActiveElement = value; + } + } + public bool draggable + { + get + { + return this.m_Draggable; + } + set + { + this.m_Draggable = value; + } + } + public int count + { + get + { + if (this.m_Elements == null) + { + return this.m_ElementList.Count; + } + if (!this.m_Elements.hasMultipleDifferentValues) + { + return this.m_Elements.arraySize; + } + int num = this.m_Elements.arraySize; + UnityEngine.Object[] targetObjects = this.m_Elements.serializedObject.targetObjects; + for (int i = 0; i < targetObjects.Length; i++) + { + UnityEngine.Object obj = targetObjects[i]; + SerializedObject serializedObject = new SerializedObject(obj); + SerializedProperty serializedProperty = serializedObject.FindProperty(this.m_Elements.propertyPath); + num = Math.Min(serializedProperty.arraySize, num); + } + return num; + } + } + public ReorderableList(IList elements, Type elementType) + { + this.InitList(null, null, elements, true, true, true, true); + } + public ReorderableList(IList elements, Type elementType, bool draggable, bool displayHeader, bool displayAddButton, bool displayRemoveButton) + { + this.InitList(null, null, elements, draggable, displayHeader, displayAddButton, displayRemoveButton); + } + public ReorderableList(SerializedObject serializedObject, SerializedProperty elements) + { + this.InitList(serializedObject, elements, null, true, true, true, true); + } + public ReorderableList(SerializedObject serializedObject, SerializedProperty elements, bool draggable, bool displayHeader, bool displayAddButton, bool displayRemoveButton) + { + this.InitList(serializedObject, elements, null, draggable, displayHeader, displayAddButton, displayRemoveButton); + } + private void InitList(SerializedObject serializedObject, SerializedProperty elements, IList elementList, bool draggable, bool displayHeader, bool displayAddButton, bool displayRemoveButton) + { + this.id = GUIUtility.GetPermanentControlID(); + this.m_SerializedObject = serializedObject; + this.m_Elements = elements; + this.m_ElementList = elementList; + this.m_Draggable = draggable; + this.m_Dragging = false; + this.m_SlideGroup = new GUISlideGroup(); + this.displayAdd = displayAddButton; + this.m_DisplayHeader = displayHeader; + this.displayRemove = displayRemoveButton; + if (this.m_Elements != null && !this.m_Elements.editable) + { + this.m_Draggable = false; + } + if (this.m_Elements != null && !this.m_Elements.isArray) + { + Debug.LogError("Input elements should be an Array SerializedProperty"); + } + } + private Rect GetContentRect(Rect rect) + { + Rect result = rect; + if (this.draggable) + { + result.xMin += 20f; + } + else + { + result.xMin += 6f; + } + result.xMax -= 6f; + return result; + } + public void DoLayoutList() + { + if (ReorderableList.s_Defaults == null) + { + ReorderableList.s_Defaults = new ReorderableList.Defaults(); + } + Rect rect = GUILayoutUtility.GetRect(0f, this.headerHeight, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + Rect rect2 = GUILayoutUtility.GetRect(10f, this.GetListElementHeight(), new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + Rect rect3 = GUILayoutUtility.GetRect(4f, this.footerHeight, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + this.DoListHeader(rect); + this.DoListElements(rect2); + this.DoListFooter(rect3); + } + public void DoList(Rect rect) + { + if (ReorderableList.s_Defaults == null) + { + ReorderableList.s_Defaults = new ReorderableList.Defaults(); + } + Rect headerRect = new Rect(rect.x, rect.y, rect.width, this.headerHeight); + Rect listRect = new Rect(rect.x, headerRect.y + headerRect.height, rect.width, this.GetListElementHeight()); + Rect footerRect = new Rect(rect.x, listRect.y + listRect.height, rect.width, this.footerHeight); + this.DoListHeader(headerRect); + this.DoListElements(listRect); + this.DoListFooter(footerRect); + } + public float GetHeight() + { + float num = 0f; + num += this.GetListElementHeight(); + num += this.headerHeight; + return num + this.footerHeight; + } + private float GetListElementHeight() + { + int num = this.count; + if (num == 0) + { + num = 1; + } + return this.elementHeight * (float)num + 7f; + } + private void DoListElements(Rect listRect) + { + int count = this.count; + if (Event.current.type == EventType.Repaint) + { + ReorderableList.s_Defaults.boxBackground.Draw(listRect, false, false, false, false); + } + listRect.yMin += 2f; + listRect.yMax -= 3f; + Rect rect = listRect; + rect.height = this.elementHeight; + Rect rect2 = rect; + if (((this.m_Elements != null && this.m_Elements.isArray) || this.m_ElementList != null) && count > 0) + { + if (this.IsDragging() && Event.current.type == EventType.Repaint) + { + int index = this.CalculateRowIndex(); + this.m_NonDragTargetIndices.Clear(); + for (int i = 0; i < count; i++) + { + if (i != this.m_ActiveElement) + { + this.m_NonDragTargetIndices.Add(i); + } + } + this.m_NonDragTargetIndices.Insert(index, -1); + for (int j = 0; j < this.m_NonDragTargetIndices.Count; j++) + { + if (this.m_NonDragTargetIndices[j] != -1) + { + rect.y = listRect.y + (float)j * this.elementHeight; + rect = this.m_SlideGroup.GetRect(this.m_NonDragTargetIndices[j], rect); + ReorderableList.s_Defaults.DrawElementBackground(rect, false, false, this.m_Draggable); + rect2 = this.GetContentRect(rect); + if (this.drawElementCallback == null) + { + if (this.m_Elements != null) + { + ReorderableList.s_Defaults.DrawElement(rect2, this.m_Elements.GetArrayElementAtIndex(this.m_NonDragTargetIndices[j]), null, false, false, this.m_Draggable); + } + else + { + ReorderableList.s_Defaults.DrawElement(rect2, null, this.m_ElementList[this.m_NonDragTargetIndices[j]], false, false, this.m_Draggable); + } + } + else + { + this.drawElementCallback(rect2, this.m_NonDragTargetIndices[j], false, false); + } + } + } + rect.y = this.m_DraggedY - this.m_DragOffset + listRect.y; + ReorderableList.s_Defaults.DrawElementBackground(rect, true, true, this.m_Draggable); + rect2 = this.GetContentRect(rect); + if (this.drawElementCallback == null) + { + if (this.m_Elements != null) + { + ReorderableList.s_Defaults.DrawElement(rect2, this.m_Elements.GetArrayElementAtIndex(this.m_ActiveElement), null, true, true, this.m_Draggable); + } + else + { + ReorderableList.s_Defaults.DrawElement(rect2, null, this.m_ElementList[this.m_ActiveElement], true, true, this.m_Draggable); + } + } + else + { + this.drawElementCallback(rect2, this.m_ActiveElement, true, true); + } + } + else + { + for (int k = 0; k < count; k++) + { + bool flag = k == this.m_ActiveElement; + bool flag2 = k == this.m_ActiveElement && GUIUtility.keyboardControl == this.id; + rect.y = listRect.y + (float)k * this.elementHeight; + ReorderableList.s_Defaults.DrawElementBackground(rect, flag, flag2, this.m_Draggable); + rect2 = this.GetContentRect(rect); + if (this.drawElementCallback == null) + { + if (this.m_Elements != null) + { + ReorderableList.s_Defaults.DrawElement(rect2, this.m_Elements.GetArrayElementAtIndex(k), null, flag, flag2, this.m_Draggable); + } + else + { + ReorderableList.s_Defaults.DrawElement(rect2, null, this.m_ElementList[k], flag, flag2, this.m_Draggable); + } + } + else + { + this.drawElementCallback(rect2, k, flag, flag2); + } + } + } + this.DoDraggingAndSelection(listRect); + } + else + { + rect.y = listRect.y; + ReorderableList.s_Defaults.DrawElementBackground(rect, false, false, false); + rect2 = rect; + rect2.xMin += 6f; + rect2.xMax -= 6f; + ReorderableList.s_Defaults.DrawNoneElement(rect2, this.m_Draggable); + } + } + private void DoListHeader(Rect headerRect) + { + if (Event.current.type == EventType.Repaint) + { + ReorderableList.s_Defaults.DrawHeaderBackground(headerRect); + } + headerRect.xMin += 6f; + headerRect.xMax -= 6f; + headerRect.height -= 2f; + headerRect.y += 1f; + if (this.drawHeaderCallback == null && this.m_DisplayHeader) + { + ReorderableList.s_Defaults.DrawHeader(headerRect, this.m_SerializedObject, this.m_Elements, this.m_ElementList); + } + else + { + if (this.drawHeaderCallback != null) + { + this.drawHeaderCallback(headerRect); + } + } + } + private void DoListFooter(Rect footerRect) + { + if (this.displayAdd || this.displayRemove) + { + ReorderableList.s_Defaults.DrawFooter(footerRect, this); + } + } + private void DoDraggingAndSelection(Rect listRect) + { + Event current = Event.current; + int activeElement = this.m_ActiveElement; + switch (current.GetTypeForControl(this.id)) + { + case EventType.MouseDown: + if (listRect.Contains(Event.current.mousePosition)) + { + EditorGUI.EndEditingActiveTextField(); + this.m_ActiveElement = Mathf.FloorToInt((Event.current.mousePosition.y - listRect.y) / this.elementHeight); + if (this.m_Draggable) + { + this.m_DragOffset = Event.current.mousePosition.y - listRect.y - (float)this.m_ActiveElement * this.elementHeight; + this.UpdateDraggedY(listRect); + GUIUtility.hotControl = this.id; + this.m_Dragging = true; + this.m_SlideGroup.Reset(); + this.m_NonDragTargetIndices = new List(); + } + GUIUtility.keyboardControl = this.id; + current.Use(); + } + break; + case EventType.MouseUp: + if (this.m_Draggable && GUIUtility.hotControl == this.id) + { + current.Use(); + this.m_Dragging = false; + int num = this.CalculateRowIndex(); + if (this.m_ActiveElement != num) + { + if (this.m_SerializedObject != null && this.m_Elements != null) + { + this.m_Elements.MoveArrayElement(this.m_ActiveElement, num); + this.m_SerializedObject.ApplyModifiedProperties(); + this.m_SerializedObject.Update(); + } + else + { + if (this.m_ElementList != null) + { + object value = this.m_ElementList[this.m_ActiveElement]; + for (int i = 0; i < this.m_ElementList.Count - 1; i++) + { + if (i >= this.m_ActiveElement) + { + this.m_ElementList[i] = this.m_ElementList[i + 1]; + } + } + for (int j = this.m_ElementList.Count - 1; j > 0; j--) + { + if (j > num) + { + this.m_ElementList[j] = this.m_ElementList[j - 1]; + } + } + this.m_ElementList[num] = value; + } + } + this.m_ActiveElement = num; + if (this.onReorderCallback != null) + { + this.onReorderCallback(this); + } + if (this.onChangedCallback != null) + { + this.onChangedCallback(this); + } + } + GUIUtility.hotControl = 0; + this.m_NonDragTargetIndices = null; + } + break; + case EventType.MouseDrag: + if (this.m_Draggable && GUIUtility.hotControl == this.id) + { + this.UpdateDraggedY(listRect); + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.keyboardControl != this.id) + { + return; + } + if (current.keyCode == KeyCode.DownArrow) + { + this.m_ActiveElement++; + current.Use(); + } + if (current.keyCode == KeyCode.UpArrow) + { + this.m_ActiveElement--; + current.Use(); + } + if (current.keyCode == KeyCode.Escape && GUIUtility.hotControl == this.id) + { + GUIUtility.hotControl = 0; + this.m_Dragging = false; + current.Use(); + } + this.m_ActiveElement = Mathf.Clamp(this.m_ActiveElement, 0, (this.m_Elements == null) ? (this.m_ElementList.Count - 1) : (this.m_Elements.arraySize - 1)); + break; + } + if (this.m_ActiveElement != activeElement && this.onSelectCallback != null) + { + this.onSelectCallback(this); + } + } + private void UpdateDraggedY(Rect listRect) + { + this.m_DraggedY = Mathf.Clamp(Event.current.mousePosition.y - listRect.y, this.m_DragOffset, listRect.height - (this.elementHeight - this.m_DragOffset)); + } + private int CalculateRowIndex() + { + int num = (this.m_Elements == null) ? this.m_ElementList.Count : this.m_Elements.arraySize; + return Mathf.Clamp(Mathf.FloorToInt(this.m_DraggedY / this.elementHeight), 0, num - 1); + } + private bool IsDragging() + { + return this.m_Dragging; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/Runner.cs b/UnityEditor/UnityEditorInternal/Runner.cs new file mode 100644 index 00000000..01399b28 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Runner.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Scripting; +using UnityEditor.Scripting.Compilers; +using UnityEditor.Utils; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Runner + { + internal static void RunManagedProgram(string exe, string args) + { + Runner.RunManagedProgram(exe, args, Application.dataPath + "/..", null); + } + internal static void RunManagedProgram(string exe, string args, string workingDirectory, CompilerOutputParserBase parser) + { + using (ManagedProgram managedProgram = new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, args)) + { + managedProgram.GetProcessStartInfo().WorkingDirectory = workingDirectory; + managedProgram.Start(); + managedProgram.WaitForExit(); + if (managedProgram.ExitCode != 0) + { + if (parser != null) + { + string[] errorOutput = managedProgram.GetErrorOutput(); + string[] standardOutput = managedProgram.GetStandardOutput(); + IEnumerable enumerable = parser.Parse(errorOutput, standardOutput, true); + foreach (CompilerMessage current in enumerable) + { + Debug.LogPlayerBuildError(current.message, current.file, current.line, current.column); + } + } + Debug.LogError(string.Concat(new string[] + { + "Failed running ", + exe, + " ", + args, + "\n\n", + managedProgram.GetAllOutput() + })); + throw new Exception(string.Format("{0} did not run properly!", exe)); + } + } + } + public static void RunNativeProgram(string exe, string args) + { + using (NativeProgram nativeProgram = new NativeProgram(exe, args)) + { + nativeProgram.Start(); + nativeProgram.WaitForExit(); + if (nativeProgram.ExitCode != 0) + { + Debug.LogError(string.Concat(new string[] + { + "Failed running ", + exe, + " ", + args, + "\n\n", + nativeProgram.GetAllOutput() + })); + throw new Exception(string.Format("{0} did not run properly!", exe)); + } + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/Slider1D.cs b/UnityEditor/UnityEditorInternal/Slider1D.cs new file mode 100644 index 00000000..3a8f9ad0 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Slider1D.cs @@ -0,0 +1,82 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Slider1D + { + private static Vector2 s_StartMousePosition; + private static Vector2 s_CurrentMousePosition; + private static Vector3 s_StartPosition; + internal static Vector3 Do(int id, Vector3 position, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) + { + return Slider1D.Do(id, position, direction, direction, size, drawFunc, snap); + } + internal static Vector3 Do(int id, Vector3 position, Vector3 handleDirection, Vector3 slideDirection, float size, Handles.DrawCapFunction drawFunc, float snap) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) && GUIUtility.hotControl == 0) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + Slider1D.s_CurrentMousePosition = (Slider1D.s_StartMousePosition = current.mousePosition); + Slider1D.s_StartPosition = position; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + Slider1D.s_CurrentMousePosition += current.delta; + float num = HandleUtility.CalcLineTranslation(Slider1D.s_StartMousePosition, Slider1D.s_CurrentMousePosition, Slider1D.s_StartPosition, slideDirection); + num = Handles.SnapValue(num, snap); + Vector3 a = Handles.matrix.MultiplyVector(slideDirection); + Vector3 v = Handles.s_Matrix.MultiplyPoint(Slider1D.s_StartPosition) + a * num; + position = Handles.s_InverseMatrix.MultiplyPoint(v); + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl && GUI.enabled) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + drawFunc(id, position, Quaternion.LookRotation(handleDirection), size); + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + if (drawFunc == new Handles.DrawCapFunction(Handles.ArrowCap)) + { + HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + slideDirection * size)); + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + slideDirection * size, size * 0.2f)); + } + else + { + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position, size * 0.2f)); + } + break; + } + return position; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/Slider2D.cs b/UnityEditor/UnityEditorInternal/Slider2D.cs new file mode 100644 index 00000000..4bb11295 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Slider2D.cs @@ -0,0 +1,144 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class Slider2D + { + private static Vector2 s_CurrentMousePosition; + private static Vector3 s_StartPosition; + private static Vector2 s_StartPlaneOffset; + public static Vector3 Do(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap, bool drawHelper) + { + return Slider2D.Do(id, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); + } + public static Vector3 Do(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap, bool drawHelper) + { + return Slider2D.Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); + } + public static Vector3 Do(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, bool drawHelper) + { + bool changed = GUI.changed; + GUI.changed = false; + Vector2 vector = Slider2D.CalcDeltaAlongDirections(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + if (GUI.changed) + { + handlePos = Slider2D.s_StartPosition + slideDir1 * vector.x + slideDir2 * vector.y; + } + GUI.changed |= changed; + return handlePos; + } + private static Vector2 CalcDeltaAlongDirections(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, bool drawHelper) + { + Vector2 vector = new Vector2(0f, 0f); + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) && GUIUtility.hotControl == 0) + { + Plane plane = new Plane(Handles.matrix.MultiplyVector(handleDir), Handles.matrix.MultiplyPoint(handlePos)); + Ray ray = HandleUtility.GUIPointToWorldRay(current.mousePosition); + float distance = 0f; + plane.Raycast(ray, out distance); + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + Slider2D.s_CurrentMousePosition = current.mousePosition; + Slider2D.s_StartPosition = handlePos; + Vector3 a = Handles.s_InverseMatrix.MultiplyPoint(ray.GetPoint(distance)); + Vector3 lhs = a - handlePos; + Slider2D.s_StartPlaneOffset.x = Vector3.Dot(lhs, slideDir1); + Slider2D.s_StartPlaneOffset.y = Vector3.Dot(lhs, slideDir2); + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + Slider2D.s_CurrentMousePosition += current.delta; + Vector3 a2 = Handles.matrix.MultiplyPoint(handlePos); + Vector3 normalized = Handles.matrix.MultiplyVector(slideDir1).normalized; + Vector3 normalized2 = Handles.matrix.MultiplyVector(slideDir2).normalized; + Ray ray2 = HandleUtility.GUIPointToWorldRay(Slider2D.s_CurrentMousePosition); + Plane plane2 = new Plane(a2, a2 + normalized, a2 + normalized2); + float distance2 = 0f; + if (plane2.Raycast(ray2, out distance2)) + { + Vector3 point = Handles.s_InverseMatrix.MultiplyPoint(ray2.GetPoint(distance2)); + vector.x = HandleUtility.PointOnLineParameter(point, Slider2D.s_StartPosition, slideDir1); + vector.y = HandleUtility.PointOnLineParameter(point, Slider2D.s_StartPosition, slideDir2); + vector -= Slider2D.s_StartPlaneOffset; + if (snap.x > 0f || snap.y > 0f) + { + vector.x = Handles.SnapValue(vector.x, snap.x); + vector.y = Handles.SnapValue(vector.y, snap.y); + } + GUI.changed = true; + } + current.Use(); + } + break; + case EventType.Repaint: + if (drawFunc != null) + { + Vector3 vector2 = handlePos + offset; + Quaternion rotation = Quaternion.LookRotation(handleDir, slideDir1); + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + drawFunc(id, vector2, rotation, handleSize); + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + if (drawHelper && GUIUtility.hotControl == id) + { + Vector3[] array = new Vector3[4]; + float d = handleSize * 10f; + array[0] = vector2 + (slideDir1 * d + slideDir2 * d); + array[1] = array[0] - slideDir1 * d * 2f; + array[2] = array[1] - slideDir2 * d * 2f; + array[3] = array[2] + slideDir1 * d * 2f; + Color color2 = Handles.color; + Handles.color = Color.white; + float num = 0.6f; + Handles.DrawSolidRectangleWithOutline(array, new Color(1f, 1f, 1f, 0.05f), new Color(num, num, num, 0.4f)); + Handles.color = color2; + } + } + break; + case EventType.Layout: + if (drawFunc == new Handles.DrawCapFunction(Handles.ArrowCap)) + { + HandleUtility.AddControl(id, HandleUtility.DistanceToLine(handlePos + offset, handlePos + handleDir * handleSize)); + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(handlePos + offset + handleDir * handleSize, handleSize * 0.2f)); + } + else + { + if (drawFunc == new Handles.DrawCapFunction(Handles.RectangleCap)) + { + HandleUtility.AddControl(id, HandleUtility.DistanceToRectangle(handlePos + offset, Quaternion.LookRotation(handleDir, slideDir1), handleSize)); + } + else + { + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(handlePos + offset, handleSize * 0.5f)); + } + } + break; + } + return vector; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/SliderScale.cs b/UnityEditor/UnityEditorInternal/SliderScale.cs new file mode 100644 index 00000000..5da12542 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/SliderScale.cs @@ -0,0 +1,143 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class SliderScale + { + private static float s_StartScale; + private static float s_ScaleDrawLength = 1f; + private static float s_ValueDrag; + private static Vector2 s_StartMousePosition; + private static Vector2 s_CurrentMousePosition; + public static float DoAxis(int id, float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + SliderScale.s_CurrentMousePosition = (SliderScale.s_StartMousePosition = current.mousePosition); + SliderScale.s_StartScale = scale; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + SliderScale.s_CurrentMousePosition += current.delta; + float num = 1f + HandleUtility.CalcLineTranslation(SliderScale.s_StartMousePosition, SliderScale.s_CurrentMousePosition, position, direction) / size; + num = Handles.SnapValue(num, snap); + scale = SliderScale.s_StartScale * num; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + float num2 = size; + if (GUIUtility.hotControl == id) + { + num2 = size * scale / SliderScale.s_StartScale; + } + Handles.CubeCap(id, position + direction * num2 * SliderScale.s_ScaleDrawLength, rotation, size * 0.1f); + Handles.DrawLine(position, position + direction * (num2 * SliderScale.s_ScaleDrawLength - size * 0.05f)); + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + direction * size)); + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + direction * size, size * 0.2f)); + break; + } + return scale; + } + public static float DoCenter(int id, float value, Vector3 position, Quaternion rotation, float size, Handles.DrawCapFunction capFunc, float snap) + { + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + SliderScale.s_StartScale = value; + SliderScale.s_ValueDrag = 0f; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + SliderScale.s_ScaleDrawLength = 1f; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + SliderScale.s_ValueDrag += HandleUtility.niceMouseDelta * 0.01f; + value = (Handles.SnapValue(SliderScale.s_ValueDrag, snap) + 1f) * SliderScale.s_StartScale; + SliderScale.s_ScaleDrawLength = value / SliderScale.s_StartScale; + GUI.changed = true; + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape) + { + value = SliderScale.s_StartScale; + SliderScale.s_ScaleDrawLength = 1f; + GUIUtility.hotControl = 0; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + { + Color color = Color.white; + if (id == GUIUtility.keyboardControl) + { + color = Handles.color; + Handles.color = Handles.selectedColor; + } + capFunc(id, position, rotation, size * 0.15f); + if (id == GUIUtility.keyboardControl) + { + Handles.color = color; + } + break; + } + case EventType.Layout: + HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position, size * 0.15f)); + break; + } + return value; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/SpriteEditorHandles.cs b/UnityEditor/UnityEditorInternal/SpriteEditorHandles.cs new file mode 100644 index 00000000..a9672a8d --- /dev/null +++ b/UnityEditor/UnityEditorInternal/SpriteEditorHandles.cs @@ -0,0 +1,304 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public static class SpriteEditorHandles + { + private static Vector2 s_CurrentMousePosition; + private static Vector2 s_DragStartScreenPosition; + private static Vector2 s_DragScreenOffset; + private static int s_RectSelectionID = GUIUtility.GetPermanentControlID(); + internal static Vector2 PointSlider(Vector2 pos, MouseCursor cursor, GUIStyle dragDot, GUIStyle dragDotActive) + { + int controlID = GUIUtility.GetControlID("Slider1D".GetHashCode(), FocusType.Keyboard); + Vector2 vector = Handles.matrix.MultiplyPoint(pos); + Rect rect = new Rect(vector.x - dragDot.fixedWidth * 0.5f, vector.y - dragDot.fixedHeight * 0.5f, dragDot.fixedWidth, dragDot.fixedHeight); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.Repaint) + { + if (GUIUtility.hotControl == controlID) + { + dragDotActive.Draw(rect, GUIContent.none, controlID); + } + else + { + dragDot.Draw(rect, GUIContent.none, controlID); + } + } + return SpriteEditorHandles.ScaleSlider(pos, cursor, rect); + } + internal static Vector2 ScaleSlider(Vector2 pos, MouseCursor cursor, Rect cursorRect) + { + int controlID = GUIUtility.GetControlID("Slider1D".GetHashCode(), FocusType.Keyboard); + return SpriteEditorHandles.ScaleSlider(controlID, pos, cursor, cursorRect); + } + private static Vector2 ScaleSlider(int id, Vector2 pos, MouseCursor cursor, Rect cursorRect) + { + Vector2 b = Handles.matrix.MultiplyPoint(pos); + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (current.button == 0 && cursorRect.Contains(Event.current.mousePosition) && !current.alt) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + SpriteEditorHandles.s_CurrentMousePosition = current.mousePosition; + SpriteEditorHandles.s_DragStartScreenPosition = current.mousePosition; + SpriteEditorHandles.s_DragScreenOffset = SpriteEditorHandles.s_CurrentMousePosition - b; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + SpriteEditorHandles.s_CurrentMousePosition += current.delta; + Vector2 a = pos; + pos = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_CurrentMousePosition); + if (!Mathf.Approximately((a - pos).magnitude, 0f)) + { + GUI.changed = true; + } + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape) + { + pos = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_DragStartScreenPosition - SpriteEditorHandles.s_DragScreenOffset); + GUIUtility.hotControl = 0; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(cursorRect, cursor, id); + break; + } + return pos; + } + internal static Vector2 PivotSlider(Rect sprite, Vector2 pos, GUIStyle pivotDot, GUIStyle pivotDotActive) + { + int controlID = GUIUtility.GetControlID("Slider1D".GetHashCode(), FocusType.Keyboard); + pos = new Vector2(sprite.xMin + sprite.width * pos.x, sprite.yMin + sprite.height * pos.y); + Vector2 vector = Handles.matrix.MultiplyPoint(pos); + Rect position = new Rect(vector.x - pivotDot.fixedWidth * 0.5f, vector.y - pivotDot.fixedHeight * 0.5f, pivotDotActive.fixedWidth, pivotDotActive.fixedHeight); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0 && position.Contains(Event.current.mousePosition) && !current.alt) + { + int num = controlID; + GUIUtility.keyboardControl = num; + GUIUtility.hotControl = num; + SpriteEditorHandles.s_CurrentMousePosition = current.mousePosition; + SpriteEditorHandles.s_DragStartScreenPosition = current.mousePosition; + Vector2 b = Handles.matrix.MultiplyPoint(pos); + SpriteEditorHandles.s_DragScreenOffset = SpriteEditorHandles.s_CurrentMousePosition - b; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + SpriteEditorHandles.s_CurrentMousePosition += current.delta; + Vector2 a = pos; + Vector3 vector2 = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_CurrentMousePosition - SpriteEditorHandles.s_DragScreenOffset); + pos = new Vector2(vector2.x, vector2.y); + if (!Mathf.Approximately((a - pos).magnitude, 0f)) + { + GUI.changed = true; + } + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == controlID && current.keyCode == KeyCode.Escape) + { + pos = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_DragStartScreenPosition - SpriteEditorHandles.s_DragScreenOffset); + GUIUtility.hotControl = 0; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(position, MouseCursor.Arrow, controlID); + if (GUIUtility.hotControl == controlID) + { + pivotDotActive.Draw(position, GUIContent.none, controlID); + } + else + { + pivotDot.Draw(position, GUIContent.none, controlID); + } + break; + } + pos = new Vector2((pos.x - sprite.xMin) / sprite.width, (pos.y - sprite.yMin) / sprite.height); + return pos; + } + internal static Rect SliderRect(Rect pos) + { + int controlID = GUIUtility.GetControlID("SliderRect".GetHashCode(), FocusType.Keyboard); + Event current = Event.current; + if (SpriteEditorWindow.s_OneClickDragStarted && current.type == EventType.Repaint) + { + SpriteEditorHandles.HandleSliderRectMouseDown(controlID, current, pos); + SpriteEditorWindow.s_OneClickDragStarted = false; + } + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (current.button == 0 && pos.Contains(Handles.s_InverseMatrix.MultiplyPoint(Event.current.mousePosition)) && !current.alt) + { + SpriteEditorHandles.HandleSliderRectMouseDown(controlID, current, pos); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + SpriteEditorHandles.s_CurrentMousePosition += current.delta; + Vector2 center = pos.center; + pos.center = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_CurrentMousePosition - SpriteEditorHandles.s_DragScreenOffset); + if (!Mathf.Approximately((center - pos.center).magnitude, 0f)) + { + GUI.changed = true; + } + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == controlID && current.keyCode == KeyCode.Escape) + { + pos.center = Handles.s_InverseMatrix.MultiplyPoint(SpriteEditorHandles.s_DragStartScreenPosition - SpriteEditorHandles.s_DragScreenOffset); + GUIUtility.hotControl = 0; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + { + Vector2 vector = Handles.s_InverseMatrix.MultiplyPoint(new Vector2(pos.xMin, pos.yMin)); + Vector2 vector2 = Handles.s_InverseMatrix.MultiplyPoint(new Vector2(pos.xMax, pos.yMax)); + EditorGUIUtility.AddCursorRect(new Rect(vector.x, vector.y, vector2.x - vector.x, vector2.y - vector.y), MouseCursor.Arrow, controlID); + break; + } + } + return pos; + } + internal static void HandleSliderRectMouseDown(int id, Event evt, Rect pos) + { + GUIUtility.keyboardControl = id; + GUIUtility.hotControl = id; + SpriteEditorHandles.s_CurrentMousePosition = evt.mousePosition; + SpriteEditorHandles.s_DragStartScreenPosition = evt.mousePosition; + Vector2 b = Handles.matrix.MultiplyPoint(pos.center); + SpriteEditorHandles.s_DragScreenOffset = SpriteEditorHandles.s_CurrentMousePosition - b; + EditorGUIUtility.SetWantsMouseJumping(1); + } + internal static Rect RectCreator(float textureWidth, float textureHeight, GUIStyle rectStyle) + { + Event current = Event.current; + Vector2 mousePosition = current.mousePosition; + int num = SpriteEditorHandles.s_RectSelectionID; + Rect result = default(Rect); + switch (current.GetTypeForControl(num)) + { + case EventType.MouseDown: + if (current.button == 0) + { + GUIUtility.hotControl = num; + Rect rect = new Rect(0f, 0f, textureWidth, textureHeight); + Vector2 v = Handles.s_InverseMatrix.MultiplyPoint(mousePosition); + v.x = Mathf.Min(Mathf.Max(v.x, rect.xMin), rect.xMax); + v.y = Mathf.Min(Mathf.Max(v.y, rect.yMin), rect.yMax); + SpriteEditorHandles.s_DragStartScreenPosition = Handles.s_Matrix.MultiplyPoint(v); + SpriteEditorHandles.s_CurrentMousePosition = mousePosition; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == num && current.button == 0) + { + if (SpriteEditorHandles.ValidRect(SpriteEditorHandles.s_DragStartScreenPosition, SpriteEditorHandles.s_CurrentMousePosition)) + { + result = SpriteEditorHandles.GetCurrentRect(false, textureWidth, textureHeight, SpriteEditorHandles.s_DragStartScreenPosition, SpriteEditorHandles.s_CurrentMousePosition); + GUI.changed = true; + current.Use(); + } + GUIUtility.hotControl = 0; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == num) + { + SpriteEditorHandles.s_CurrentMousePosition = new Vector2(mousePosition.x, mousePosition.y); + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == num && current.keyCode == KeyCode.Escape) + { + GUIUtility.hotControl = 0; + GUI.changed = true; + current.Use(); + } + break; + case EventType.Repaint: + if (GUIUtility.hotControl == num && SpriteEditorHandles.ValidRect(SpriteEditorHandles.s_DragStartScreenPosition, SpriteEditorHandles.s_CurrentMousePosition)) + { + SpriteEditorUtility.BeginLines(Color.green * 1.5f); + SpriteEditorUtility.DrawBox(SpriteEditorHandles.GetCurrentRect(false, textureWidth, textureHeight, SpriteEditorHandles.s_DragStartScreenPosition, SpriteEditorHandles.s_CurrentMousePosition)); + SpriteEditorUtility.EndLines(); + } + break; + } + return result; + } + private static bool ValidRect(Vector2 startPoint, Vector2 endPoint) + { + return Mathf.Abs((endPoint - startPoint).x) > 5f && Mathf.Abs((endPoint - startPoint).y) > 5f; + } + private static Rect GetCurrentRect(bool screenSpace, float textureWidth, float textureHeight, Vector2 startPoint, Vector2 endPoint) + { + Rect rect = EditorGUIExt.FromToRect(Handles.s_InverseMatrix.MultiplyPoint(startPoint), Handles.s_InverseMatrix.MultiplyPoint(endPoint)); + rect = SpriteEditorUtility.ClampedRect(SpriteEditorUtility.RoundToInt(rect), new Rect(0f, 0f, textureWidth, textureHeight), false); + if (screenSpace) + { + Vector2 vector = Handles.matrix.MultiplyPoint(new Vector2(rect.xMin, rect.yMin)); + Vector2 vector2 = Handles.matrix.MultiplyPoint(new Vector2(rect.xMax, rect.yMax)); + rect = new Rect(vector.x, vector.y, vector2.x - vector.x, vector2.y - vector.y); + } + return rect; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/SpriteEditorMenu.cs b/UnityEditor/UnityEditorInternal/SpriteEditorMenu.cs new file mode 100644 index 00000000..8325f329 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/SpriteEditorMenu.cs @@ -0,0 +1,184 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class SpriteEditorMenu : EditorWindow + { + private enum SlicingType + { + Automatic, + Grid + } + private class Styles + { + public GUIStyle background = "grey_border"; + public GUIStyle notice; + public Styles() + { + this.notice = new GUIStyle(GUI.skin.label); + this.notice.alignment = TextAnchor.MiddleCenter; + this.notice.wordWrap = true; + } + } + public readonly string[] spriteAlignmentOptions = new string[] + { + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom").text, + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight").text + }; + public readonly string[] slicingMethodOptions = new string[] + { + EditorGUIUtility.TextContent("SpriteEditor.Slicing.DeleteAll").text, + EditorGUIUtility.TextContent("SpriteEditor.Slicing.Smart").text, + EditorGUIUtility.TextContent("SpriteEditor.Slicing.Safe").text + }; + public static SpriteEditorMenu s_SpriteEditorMenu; + private static SpriteEditorMenu.Styles s_Styles; + private static long s_LastClosedTime; + private static int s_Selected; + private static Vector2 s_GridSpriteSize = new Vector2(64f, 64f); + private static Vector2 s_GridSpriteOffset = new Vector2(0f, 0f); + private static Vector2 s_GridSpritePadding = new Vector2(0f, 0f); + private static int s_AutoSlicingMethod = 0; + private static int s_SpriteAlignment; + private static SpriteEditorMenu.SlicingType s_SlicingType; + public static SpriteEditorWindow s_SpriteEditor; + private void Init(Rect buttonRect) + { + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); + float y = 120f; + Vector2 windowSize = new Vector2(300f, y); + base.ShowAsDropDown(buttonRect, windowSize); + } + private void OnDisable() + { + SpriteEditorMenu.s_LastClosedTime = DateTime.Now.Ticks / 10000L; + SpriteEditorMenu.s_SpriteEditorMenu = null; + } + internal static bool ShowAtPosition(Rect buttonRect) + { + long num = DateTime.Now.Ticks / 10000L; + if (num >= SpriteEditorMenu.s_LastClosedTime + 50L) + { + Event.current.Use(); + if (SpriteEditorMenu.s_SpriteEditorMenu == null) + { + SpriteEditorMenu.s_SpriteEditorMenu = ScriptableObject.CreateInstance(); + } + SpriteEditorMenu.s_SpriteEditorMenu.Init(buttonRect); + return true; + } + return false; + } + private void OnGUI() + { + if (SpriteEditorMenu.s_Styles == null) + { + SpriteEditorMenu.s_Styles = new SpriteEditorMenu.Styles(); + } + GUILayout.Space(4f); + EditorGUIUtility.labelWidth = 124f; + EditorGUIUtility.wideMode = true; + GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, SpriteEditorMenu.s_Styles.background); + SpriteEditorMenu.s_SlicingType = (SpriteEditorMenu.SlicingType)EditorGUILayout.EnumPopup("Type", SpriteEditorMenu.s_SlicingType, new GUILayoutOption[0]); + SpriteEditorMenu.SlicingType slicingType = SpriteEditorMenu.s_SlicingType; + if (slicingType != SpriteEditorMenu.SlicingType.Automatic) + { + if (slicingType == SpriteEditorMenu.SlicingType.Grid) + { + this.OnGridGUI(); + } + } + else + { + this.OnAutomaticGUI(); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(EditorGUIUtility.labelWidth + 4f); + if (GUILayout.Button("Slice", new GUILayoutOption[0])) + { + this.DoSlicing(); + } + GUILayout.EndHorizontal(); + } + private void DoSlicing() + { + this.DoAnalytics(); + SpriteEditorMenu.SlicingType slicingType = SpriteEditorMenu.s_SlicingType; + if (slicingType != SpriteEditorMenu.SlicingType.Automatic) + { + if (slicingType == SpriteEditorMenu.SlicingType.Grid) + { + this.DoGridSlicing(); + } + } + else + { + this.DoAutomaticSlicing(); + } + } + private void DoAnalytics() + { + Analytics.Event("Sprite Editor", "Slice", "Type", (int)SpriteEditorMenu.s_SlicingType); + if (SpriteEditorMenu.s_SpriteEditor.originalTexture != null) + { + Analytics.Event("Sprite Editor", "Slice", "Texture Width", SpriteEditorMenu.s_SpriteEditor.originalTexture.width); + Analytics.Event("Sprite Editor", "Slice", "Texture Height", SpriteEditorMenu.s_SpriteEditor.originalTexture.height); + } + if (SpriteEditorMenu.s_SlicingType == SpriteEditorMenu.SlicingType.Automatic) + { + Analytics.Event("Sprite Editor", "Slice", "Auto Slicing Method", SpriteEditorMenu.s_AutoSlicingMethod); + } + else + { + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Size X", (int)SpriteEditorMenu.s_GridSpriteSize.x); + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Size Y", (int)SpriteEditorMenu.s_GridSpriteSize.y); + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Offset X", (int)SpriteEditorMenu.s_GridSpriteOffset.x); + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Offset Y", (int)SpriteEditorMenu.s_GridSpriteOffset.y); + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Padding X", (int)SpriteEditorMenu.s_GridSpritePadding.x); + Analytics.Event("Sprite Editor", "Slice", "Grid Slicing Padding Y", (int)SpriteEditorMenu.s_GridSpritePadding.y); + } + } + private void OnGridGUI() + { + SpriteEditorMenu.s_GridSpriteSize = EditorGUILayout.Vector2Field("Pixel Size", SpriteEditorMenu.s_GridSpriteSize, new GUILayoutOption[0]); + SpriteEditorMenu.s_GridSpriteSize.x = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpriteSize.x, 1, 4096); + SpriteEditorMenu.s_GridSpriteSize.y = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpriteSize.y, 1, 4096); + SpriteEditorMenu.s_GridSpriteOffset = EditorGUILayout.Vector2Field("Offset", SpriteEditorMenu.s_GridSpriteOffset, new GUILayoutOption[0]); + SpriteEditorMenu.s_GridSpriteOffset.x = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpriteOffset.x, 0, 4096); + SpriteEditorMenu.s_GridSpriteOffset.y = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpriteOffset.y, 0, 4096); + SpriteEditorMenu.s_GridSpritePadding = EditorGUILayout.Vector2Field("Padding", SpriteEditorMenu.s_GridSpritePadding, new GUILayoutOption[0]); + SpriteEditorMenu.s_GridSpritePadding.x = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpritePadding.x, 0, 4096); + SpriteEditorMenu.s_GridSpritePadding.y = (float)Mathf.Clamp((int)SpriteEditorMenu.s_GridSpritePadding.y, 0, 4096); + SpriteEditorMenu.s_SpriteAlignment = EditorGUILayout.Popup("Pivot", SpriteEditorMenu.s_SpriteAlignment, this.spriteAlignmentOptions, new GUILayoutOption[0]); + GUILayout.Space(2f); + } + private void OnAutomaticGUI() + { + float num = 38f; + if (SpriteEditorMenu.s_SpriteEditor.originalTexture != null && TextureUtil.IsCompressedTextureFormat(SpriteEditorMenu.s_SpriteEditor.originalTexture.format)) + { + EditorGUILayout.LabelField("To obtain more accurate slicing results, manual slicing is recommended!", SpriteEditorMenu.s_Styles.notice, new GUILayoutOption[0]); + num -= 31f; + } + SpriteEditorMenu.s_SpriteAlignment = EditorGUILayout.Popup("Pivot", SpriteEditorMenu.s_SpriteAlignment, this.spriteAlignmentOptions, new GUILayoutOption[0]); + SpriteEditorMenu.s_AutoSlicingMethod = EditorGUILayout.Popup("Method", SpriteEditorMenu.s_AutoSlicingMethod, this.slicingMethodOptions, new GUILayoutOption[0]); + GUILayout.Space(num); + } + private void DoAutomaticSlicing() + { + SpriteEditorMenu.s_SpriteEditor.DoAutomaticSlicing(4, SpriteEditorMenu.s_SpriteAlignment, (SpriteEditorWindow.AutoSlicingMethod)SpriteEditorMenu.s_AutoSlicingMethod); + } + private void DoGridSlicing() + { + SpriteEditorMenu.s_SpriteEditor.DoGridSlicing(SpriteEditorMenu.s_GridSpriteSize, SpriteEditorMenu.s_GridSpriteOffset, SpriteEditorMenu.s_GridSpritePadding, SpriteEditorMenu.s_SpriteAlignment); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs b/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs new file mode 100644 index 00000000..31395b94 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs @@ -0,0 +1,131 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal static class SpriteEditorUtility + { + public static Vector2 GetPivotValue(SpriteAlignment alignment, Vector2 customOffset) + { + switch (alignment) + { + case SpriteAlignment.Center: + return new Vector2(0.5f, 0.5f); + case SpriteAlignment.TopLeft: + return new Vector2(0f, 1f); + case SpriteAlignment.TopCenter: + return new Vector2(0.5f, 1f); + case SpriteAlignment.TopRight: + return new Vector2(1f, 1f); + case SpriteAlignment.LeftCenter: + return new Vector2(0f, 0.5f); + case SpriteAlignment.RightCenter: + return new Vector2(1f, 0.5f); + case SpriteAlignment.BottomLeft: + return new Vector2(0f, 0f); + case SpriteAlignment.BottomCenter: + return new Vector2(0.5f, 0f); + case SpriteAlignment.BottomRight: + return new Vector2(1f, 0f); + case SpriteAlignment.Custom: + return customOffset; + default: + return Vector2.zero; + } + } + public static Rect RoundedRect(Rect rect) + { + return new Rect((float)Mathf.RoundToInt(rect.xMin), (float)Mathf.RoundToInt(rect.yMin), (float)Mathf.RoundToInt(rect.width), (float)Mathf.RoundToInt(rect.height)); + } + public static Rect RoundToInt(Rect r) + { + r.xMin = (float)Mathf.RoundToInt(r.xMin); + r.yMin = (float)Mathf.RoundToInt(r.yMin); + r.xMax = (float)Mathf.RoundToInt(r.xMax); + r.yMax = (float)Mathf.RoundToInt(r.yMax); + return r; + } + public static Rect ClampedRect(Rect rect, Rect clamp, bool maintainSize) + { + Rect result = new Rect(rect); + if (maintainSize) + { + Vector2 center = rect.center; + if (center.x + Mathf.Abs(rect.width) * 0.5f > clamp.xMax) + { + center.x = clamp.xMax - rect.width * 0.5f; + } + if (center.x - Mathf.Abs(rect.width) * 0.5f < clamp.xMin) + { + center.x = clamp.xMin + rect.width * 0.5f; + } + if (center.y + Mathf.Abs(rect.height) * 0.5f > clamp.yMax) + { + center.y = clamp.yMax - rect.height * 0.5f; + } + if (center.y - Mathf.Abs(rect.height) * 0.5f < clamp.yMin) + { + center.y = clamp.yMin + rect.height * 0.5f; + } + result.center = center; + } + else + { + if (result.width > 0f) + { + result.xMin = Mathf.Max(rect.xMin, clamp.xMin); + result.xMax = Mathf.Min(rect.xMax, clamp.xMax); + } + else + { + result.xMin = Mathf.Min(rect.xMin, clamp.xMax); + result.xMax = Mathf.Max(rect.xMax, clamp.xMin); + } + if (result.height > 0f) + { + result.yMin = Mathf.Max(rect.yMin, clamp.yMin); + result.yMax = Mathf.Min(rect.yMax, clamp.yMax); + } + else + { + result.yMin = Mathf.Min(rect.yMin, clamp.yMax); + result.yMax = Mathf.Max(rect.yMax, clamp.yMin); + } + } + result.width = Mathf.Abs(result.width); + result.height = Mathf.Abs(result.height); + return result; + } + public static void DrawBox(Rect position) + { + Vector3[] array = new Vector3[5]; + int num = 0; + array[num++] = new Vector3(position.xMin, position.yMin, 0f); + array[num++] = new Vector3(position.xMax, position.yMin, 0f); + array[num++] = new Vector3(position.xMax, position.yMax, 0f); + array[num++] = new Vector3(position.xMin, position.yMax, 0f); + SpriteEditorUtility.DrawLine(array[0], array[1]); + SpriteEditorUtility.DrawLine(array[1], array[2]); + SpriteEditorUtility.DrawLine(array[2], array[3]); + SpriteEditorUtility.DrawLine(array[3], array[0]); + } + public static void DrawLine(Vector3 p1, Vector3 p2) + { + GL.Vertex(p1); + GL.Vertex(p2); + } + public static void BeginLines(Color color) + { + HandleUtility.handleWireMaterial.SetPass(0); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(color); + } + public static void EndLines() + { + GL.End(); + GL.PopMatrix(); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/State.cs b/UnityEditor/UnityEditorInternal/State.cs new file mode 100644 index 00000000..451bba37 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/State.cs @@ -0,0 +1,140 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Internal; +namespace UnityEditorInternal +{ + public sealed class State : UnityEngine.Object + { + public extern string uniqueName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int uniqueNameHash + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mirror + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool iKOnFeet + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string tag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern StateMachine stateMachine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 position + { + get + { + Vector3 result; + this.INTERNAL_get_position(out result); + return result; + } + set + { + this.INTERNAL_set_position(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_position(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_position(ref Vector3 value); + [ExcludeFromDocs] + public Motion GetMotion() + { + AnimatorControllerLayer layer = null; + return this.GetMotion(layer); + } + public Motion GetMotion([DefaultValue("null")] AnimatorControllerLayer layer) + { + return this.GetMotionInternal((layer == null) ? 0 : layer.motionSetIndex); + } + [ExcludeFromDocs] + public void SetAnimationClip(AnimationClip clip) + { + AnimatorControllerLayer layer = null; + this.SetAnimationClip(clip, layer); + } + public void SetAnimationClip(AnimationClip clip, [DefaultValue("null")] AnimatorControllerLayer layer) + { + this.SetMotionInternal(clip, (layer == null) ? 0 : layer.motionSetIndex); + } + [ExcludeFromDocs] + public BlendTree CreateBlendTree() + { + AnimatorControllerLayer layer = null; + return this.CreateBlendTree(layer); + } + public BlendTree CreateBlendTree([DefaultValue("null")] AnimatorControllerLayer layer) + { + return this.CreateBlendTreeInternal((layer == null) ? 0 : layer.motionSetIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetMotionInternal(Motion motion, [DefaultValue("0")] int motionSetIndex); + [ExcludeFromDocs] + internal void SetMotionInternal(Motion motion) + { + int motionSetIndex = 0; + this.SetMotionInternal(motion, motionSetIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Motion GetMotionInternal([DefaultValue("0")] int motionSetIndex); + [ExcludeFromDocs] + internal Motion GetMotionInternal() + { + int motionSetIndex = 0; + return this.GetMotionInternal(motionSetIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern BlendTree CreateBlendTreeInternal([DefaultValue("0")] int motionSetIndex); + [ExcludeFromDocs] + internal BlendTree CreateBlendTreeInternal() + { + int motionSetIndex = 0; + return this.CreateBlendTreeInternal(motionSetIndex); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/StateMachine.cs b/UnityEditor/UnityEditorInternal/StateMachine.cs new file mode 100644 index 00000000..7aaae419 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/StateMachine.cs @@ -0,0 +1,280 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class StateMachine : UnityEngine.Object + { + internal IEnumerable states + { + get + { + State[] array = new State[this.stateCount]; + for (int i = 0; i < this.stateCount; i++) + { + array[i] = this.GetState(i); + } + return array; + } + } + internal List statesRecursive + { + get + { + List list = new List(); + list.AddRange(this.states); + for (int i = 0; i < this.stateMachineCount; i++) + { + list.AddRange(this.GetStateMachine(i).statesRecursive); + } + return list; + } + } + internal IEnumerable stateMachines + { + get + { + StateMachine[] array = new StateMachine[this.stateMachineCount]; + for (int i = 0; i < this.stateMachineCount; i++) + { + array[i] = this.GetStateMachine(i); + } + return array; + } + } + internal List stateMachinesRecursive + { + get + { + List list = new List(); + list.AddRange(this.stateMachines); + for (int i = 0; i < this.stateMachineCount; i++) + { + list.AddRange(this.GetStateMachine(i).stateMachinesRecursive); + } + return list; + } + } + internal List transitions + { + get + { + List statesRecursive = this.statesRecursive; + List list = new List(); + foreach (State current in statesRecursive) + { + list.AddRange(this.GetTransitionsFromState(current)); + } + list.AddRange(this.GetTransitionsFromState(null)); + return list; + } + } + public extern int stateCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int stateMachineCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern State defaultState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 anyStatePosition + { + get + { + Vector3 result; + this.INTERNAL_get_anyStatePosition(out result); + return result; + } + set + { + this.INTERNAL_set_anyStatePosition(ref value); + } + } + public Vector3 parentStateMachinePosition + { + get + { + Vector3 result; + this.INTERNAL_get_parentStateMachinePosition(out result); + return result; + } + set + { + this.INTERNAL_set_parentStateMachinePosition(ref value); + } + } + public extern int motionSetCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int transitionCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal Vector3 GetStateMachinePosition(StateMachine stateMachine) + { + for (int i = 0; i < this.stateMachineCount; i++) + { + if (stateMachine == this.GetStateMachine(i)) + { + return this.GetStateMachinePosition(i); + } + } + Assert.Fail(string.Concat(new string[] + { + "Can't find state machine (", + stateMachine.name, + ") in parent state machine (", + base.name, + ")." + })); + return Vector3.zero; + } + internal void SetStateMachinePosition(StateMachine stateMachine, Vector3 position) + { + for (int i = 0; i < this.stateMachineCount; i++) + { + if (stateMachine == this.GetStateMachine(i)) + { + this.SetStateMachinePosition(i, position); + return; + } + } + Assert.Fail(string.Concat(new string[] + { + "Can't find state machine (", + stateMachine.name, + ") in parent state machine (", + base.name, + ")." + })); + } + internal State CreateState(Vector3 position) + { + Undo.RegisterCompleteObjectUndo(this, "State added"); + State state = this.AddState("New State"); + state.position = position; + return state; + } + internal State FindState(string stateUniqueName) + { + return this.statesRecursive.Find((State s) => s.uniqueName == stateUniqueName); + } + internal State FindState(int stateUniqueNameHash) + { + return this.statesRecursive.Find((State s) => s.uniqueNameHash == stateUniqueNameHash); + } + internal Transition FindTransition(string transitionUniqueName) + { + return this.transitions.Find((Transition t) => t.uniqueName == transitionUniqueName); + } + internal Transition FindTransition(int transitionUniqueName) + { + return this.transitions.Find((Transition t) => t.uniqueNameHash == transitionUniqueName); + } + internal bool HasState(State state) + { + return this.statesRecursive.Any((State s) => s == state); + } + internal bool IsDirectParent(StateMachine stateMachine) + { + return this.stateMachines.Any((StateMachine sm) => sm == stateMachine); + } + internal bool HasStateMachine(StateMachine child) + { + return this.stateMachinesRecursive.Any((StateMachine sm) => sm == child); + } + internal bool HasTransition(State stateA, State stateB) + { + return this.GetTransitionsFromState(stateA).Any((Transition t) => t.dstState == stateB) || this.GetTransitionsFromState(stateB).Any((Transition t) => t.dstState == stateA); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern State GetState(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern State AddState(string stateName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveState(State state); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern StateMachine GetStateMachine(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern StateMachine AddStateMachine(string stateMachineName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveStateMachine(StateMachine stateMachine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transition AddTransition(State src, State dst); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transition AddAnyStateTransition(State dst); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveTransition(Transition transition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anyStatePosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anyStatePosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_parentStateMachinePosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_parentStateMachinePosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector3 GetStateMachinePosition(int i); + public void SetStateMachinePosition(int i, Vector3 pos) + { + StateMachine.INTERNAL_CALL_SetStateMachinePosition(this, i, ref pos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetStateMachinePosition(StateMachine self, int i, ref Vector3 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transition[] GetTransitionsFromState(State srcState); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MoveState(State state, StateMachine target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MoveStateMachine(StateMachine stateMachine, StateMachine target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasState(State state, bool recursive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasStateMachine(StateMachine state, bool recursive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTransitionsFromState(State srcState, Transition[] transitions); + } +} diff --git a/UnityEditor/UnityEditorInternal/Transition.cs b/UnityEditor/UnityEditorInternal/Transition.cs new file mode 100644 index 00000000..b32f4567 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/Transition.cs @@ -0,0 +1,162 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class Transition : UnityEngine.Object + { + internal delegate void RemovedCondition(int index); + private static readonly GUIContent s_TransitionTempContent = new GUIContent(); + internal Transition.RemovedCondition onRemovedCondition; + public extern string uniqueName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int uniqueNameHash + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int conditionCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float duration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float offset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool atomic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool solo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mute + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool canTransitionToSelf + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern State srcState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern State dstState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern string shortDisplayName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public GUIContent GetTransitionContentForRect(Rect rect) + { + Transition.s_TransitionTempContent.text = this.uniqueName; + if (EditorStyles.label.CalcSize(Transition.s_TransitionTempContent).x > rect.width) + { + Transition.s_TransitionTempContent.text = this.shortDisplayName; + } + return Transition.s_TransitionTempContent; + } + public AnimatorCondition GetCondition(int index) + { + return (!this.ValidateConditionIndex(index)) ? null : new AnimatorCondition(this, index); + } + public AnimatorCondition AddCondition() + { + this.AddConditionInternal(); + return this.GetCondition(this.conditionCount - 1); + } + public void RemoveCondition(int index) + { + if (this.onRemovedCondition != null) + { + this.onRemovedCondition(index); + } + this.RemoveConditionInternal(index); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddConditionInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveConditionInternal(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool ValidateConditionIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern TransitionConditionMode GetConditionMode(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetConditionMode(int index, TransitionConditionMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetConditionParameter(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetConditionParameter(int index, string eventName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetParameterTreshold(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameterTreshold(int index, float threshold); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetExitTime(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetExitTime(int index, float exit); + } +} diff --git a/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs b/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs new file mode 100644 index 00000000..05c3da40 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditorInternal +{ + public enum TransitionConditionMode + { + If = 1, + IfNot, + Greater, + Less, + ExitTime, + Equals, + NotEqual + } +} diff --git a/UnityEditor/UnityEditorInternal/UnityEventDrawer.cs b/UnityEditor/UnityEditorInternal/UnityEventDrawer.cs new file mode 100644 index 00000000..8a566e53 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/UnityEventDrawer.cs @@ -0,0 +1,670 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using UnityEditor; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditorInternal +{ + [CustomPropertyDrawer(typeof(UnityEventBase), true)] + public class UnityEventDrawer : PropertyDrawer + { + protected class State + { + internal ReorderableList m_ReorderableList; + public int lastSelectedIndex; + } + private class Styles + { + public readonly GUIContent iconToolbarMinus = EditorGUIUtility.IconContent("Toolbar Minus"); + public readonly GUIStyle genericFieldStyle = EditorStyles.label; + public readonly GUIStyle removeButton = "InvisibleButton"; + } + private struct ValidMethodMap + { + public UnityEngine.Object target; + public MethodInfo methodInfo; + public PersistentListenerMode mode; + } + private struct UnityEventFunction + { + private readonly SerializedProperty m_Listener; + private readonly UnityEngine.Object m_Target; + private readonly MethodInfo m_Method; + private readonly PersistentListenerMode m_Mode; + public UnityEventFunction(SerializedProperty listener, UnityEngine.Object target, MethodInfo method, PersistentListenerMode mode) + { + this.m_Listener = listener; + this.m_Target = target; + this.m_Method = method; + this.m_Mode = mode; + } + public void Assign() + { + SerializedProperty serializedProperty = this.m_Listener.FindPropertyRelative("m_Target"); + SerializedProperty serializedProperty2 = this.m_Listener.FindPropertyRelative("m_MethodName"); + SerializedProperty serializedProperty3 = this.m_Listener.FindPropertyRelative("m_Mode"); + SerializedProperty serializedProperty4 = this.m_Listener.FindPropertyRelative("m_Arguments"); + serializedProperty.objectReferenceValue = this.m_Target; + serializedProperty2.stringValue = this.m_Method.Name; + serializedProperty3.enumValueIndex = (int)this.m_Mode; + if (this.m_Mode == PersistentListenerMode.Object) + { + SerializedProperty serializedProperty5 = serializedProperty4.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName"); + ParameterInfo[] parameters = this.m_Method.GetParameters(); + if (parameters.Length == 1 && typeof(UnityEngine.Object).IsAssignableFrom(parameters[0].ParameterType)) + { + serializedProperty5.stringValue = parameters[0].ParameterType.AssemblyQualifiedName; + } + else + { + serializedProperty5.stringValue = typeof(UnityEngine.Object).AssemblyQualifiedName; + } + } + this.ValidateObjectParamater(serializedProperty4, this.m_Mode); + this.m_Listener.m_SerializedObject.ApplyModifiedProperties(); + } + private void ValidateObjectParamater(SerializedProperty arguments, PersistentListenerMode mode) + { + SerializedProperty serializedProperty = arguments.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName"); + SerializedProperty serializedProperty2 = arguments.FindPropertyRelative("m_ObjectArgument"); + UnityEngine.Object objectReferenceValue = serializedProperty2.objectReferenceValue; + if (mode != PersistentListenerMode.Object) + { + serializedProperty.stringValue = typeof(UnityEngine.Object).AssemblyQualifiedName; + serializedProperty2.objectReferenceValue = null; + return; + } + if (objectReferenceValue == null) + { + return; + } + Type type = Type.GetType(serializedProperty.stringValue, false); + if (!typeof(UnityEngine.Object).IsAssignableFrom(type) || !type.IsInstanceOfType(objectReferenceValue)) + { + serializedProperty2.objectReferenceValue = null; + } + } + public void Clear() + { + SerializedProperty serializedProperty = this.m_Listener.FindPropertyRelative("m_MethodName"); + serializedProperty.stringValue = null; + SerializedProperty serializedProperty2 = this.m_Listener.FindPropertyRelative("m_Mode"); + serializedProperty2.enumValueIndex = 1; + this.m_Listener.m_SerializedObject.ApplyModifiedProperties(); + } + } + private const string kNoFunctionString = "No Function"; + private const string kInstancePath = "m_Target"; + private const string kCallStatePath = "m_CallState"; + private const string kArgumentsPath = "m_Arguments"; + private const string kModePath = "m_Mode"; + private const string kMethodNamePath = "m_MethodName"; + private const string kFloatArgument = "m_FloatArgument"; + private const string kIntArgument = "m_IntArgument"; + private const string kObjectArgument = "m_ObjectArgument"; + private const string kStringArgument = "m_StringArgument"; + private const string kBoolArgument = "m_BoolArgument"; + private const string kObjectArgumentAssemblyTypeName = "m_ObjectArgumentAssemblyTypeName"; + private const int kExtraSpacing = 9; + private UnityEventDrawer.Styles m_Styles; + private string m_Text; + private UnityEventBase m_DummyEvent; + private SerializedProperty m_Prop; + private SerializedProperty m_ListenersArray; + private ReorderableList m_ReorderableList; + private int m_LastSelectedIndex; + private Dictionary m_States = new Dictionary(); + private static string GetEventParams(UnityEventBase evt) + { + MethodInfo methodInfo = evt.FindMethod("Invoke", evt, PersistentListenerMode.EventDefined, null); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(" ("); + Type[] array = ( + from x in methodInfo.GetParameters() + select x.ParameterType).ToArray(); + for (int i = 0; i < array.Length; i++) + { + stringBuilder.Append(array[i].Name); + if (i < array.Length - 1) + { + stringBuilder.Append(", "); + } + } + stringBuilder.Append(")"); + return stringBuilder.ToString(); + } + private UnityEventDrawer.State GetState(SerializedProperty prop) + { + string propertyPath = prop.propertyPath; + UnityEventDrawer.State state; + this.m_States.TryGetValue(propertyPath, out state); + if (state == null) + { + state = new UnityEventDrawer.State(); + SerializedProperty elements = prop.FindPropertyRelative("m_PersistentCalls.m_Calls"); + state.m_ReorderableList = new ReorderableList(prop.serializedObject, elements, false, true, true, true); + state.m_ReorderableList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawEventHeader); + state.m_ReorderableList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawEventListener); + state.m_ReorderableList.onSelectCallback = new ReorderableList.SelectCallbackDelegate(this.SelectEventListener); + state.m_ReorderableList.onReorderCallback = new ReorderableList.ReorderCallbackDelegate(this.EndDragChild); + state.m_ReorderableList.onAddCallback = new ReorderableList.AddCallbackDelegate(this.AddEventListener); + state.m_ReorderableList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveButton); + state.m_ReorderableList.elementHeight = 43f; + this.m_States[propertyPath] = state; + } + return state; + } + private UnityEventDrawer.State RestoreState(SerializedProperty property) + { + UnityEventDrawer.State state = this.GetState(property); + this.m_ListenersArray = state.m_ReorderableList.serializedProperty; + this.m_ReorderableList = state.m_ReorderableList; + this.m_LastSelectedIndex = state.lastSelectedIndex; + return state; + } + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + this.m_Prop = property; + this.m_Text = label.text; + UnityEventDrawer.State state = this.RestoreState(property); + this.OnGUI(position); + state.lastSelectedIndex = this.m_LastSelectedIndex; + } + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + this.RestoreState(property); + float result = 0f; + if (this.m_ReorderableList != null) + { + result = this.m_ReorderableList.GetHeight(); + } + return result; + } + public void OnGUI(Rect position) + { + if (this.m_ListenersArray == null || !this.m_ListenersArray.isArray) + { + return; + } + this.m_DummyEvent = UnityEventDrawer.GetDummyEvent(this.m_Prop); + if (this.m_DummyEvent == null) + { + return; + } + if (this.m_Styles == null) + { + this.m_Styles = new UnityEventDrawer.Styles(); + } + if (this.m_ReorderableList != null) + { + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + this.m_ReorderableList.DoList(position); + EditorGUI.indentLevel = indentLevel; + } + } + protected virtual void DrawEventHeader(Rect headerRect) + { + headerRect.height = 16f; + string text = ((!string.IsNullOrEmpty(this.m_Text)) ? this.m_Text : "Event") + UnityEventDrawer.GetEventParams(this.m_DummyEvent); + GUI.Label(headerRect, text); + } + private static PersistentListenerMode GetMode(SerializedProperty mode) + { + return (PersistentListenerMode)mode.enumValueIndex; + } + private void DrawEventListener(Rect rect, int index, bool isactive, bool isfocused) + { + SerializedProperty arrayElementAtIndex = this.m_ListenersArray.GetArrayElementAtIndex(index); + rect.y += 1f; + Rect[] rowRects = this.GetRowRects(rect); + Rect position = rowRects[0]; + Rect position2 = rowRects[1]; + Rect rect2 = rowRects[2]; + Rect position3 = rowRects[3]; + SerializedProperty property = arrayElementAtIndex.FindPropertyRelative("m_CallState"); + SerializedProperty mode = arrayElementAtIndex.FindPropertyRelative("m_Mode"); + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Arguments"); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("m_Target"); + SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("m_MethodName"); + Color backgroundColor = GUI.backgroundColor; + GUI.backgroundColor = Color.white; + EditorGUI.PropertyField(position, property, GUIContent.none); + EditorGUI.BeginChangeCheck(); + GUI.Box(position2, GUIContent.none); + EditorGUI.PropertyField(position2, serializedProperty2, GUIContent.none); + if (EditorGUI.EndChangeCheck()) + { + serializedProperty3.stringValue = null; + } + PersistentListenerMode mode2 = UnityEventDrawer.GetMode(mode); + SerializedProperty serializedProperty4; + switch (mode2) + { + case PersistentListenerMode.Object: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_ObjectArgument"); + break; + case PersistentListenerMode.Int: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_IntArgument"); + break; + case PersistentListenerMode.Float: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_FloatArgument"); + break; + case PersistentListenerMode.String: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_StringArgument"); + break; + case PersistentListenerMode.Bool: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_BoolArgument"); + break; + default: + serializedProperty4 = serializedProperty.FindPropertyRelative("m_IntArgument"); + break; + } + string stringValue = serializedProperty.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue; + Type type = typeof(UnityEngine.Object); + if (!string.IsNullOrEmpty(stringValue)) + { + type = (Type.GetType(stringValue, false) ?? typeof(UnityEngine.Object)); + } + if (mode2 == PersistentListenerMode.Object) + { + EditorGUI.BeginChangeCheck(); + UnityEngine.Object objectReferenceValue = EditorGUI.ObjectField(position3, GUIContent.none, serializedProperty4.objectReferenceValue, type, true); + if (EditorGUI.EndChangeCheck()) + { + serializedProperty4.objectReferenceValue = objectReferenceValue; + } + } + else + { + if (mode2 != PersistentListenerMode.Void && mode2 != PersistentListenerMode.EventDefined) + { + EditorGUI.PropertyField(position3, serializedProperty4, GUIContent.none); + } + } + EditorGUI.BeginDisabledGroup(serializedProperty2.objectReferenceValue == null); + EditorGUI.BeginProperty(rect2, GUIContent.none, serializedProperty3); + GUIContent content; + if (EditorGUI.showMixedValue) + { + content = EditorGUI.mixedValueContent; + } + else + { + StringBuilder stringBuilder = new StringBuilder(); + if (serializedProperty2.objectReferenceValue == null || string.IsNullOrEmpty(serializedProperty3.stringValue)) + { + stringBuilder.Append("No Function"); + } + else + { + if (!UnityEventDrawer.IsPersistantListenerValid(this.m_DummyEvent, serializedProperty3.stringValue, serializedProperty2.objectReferenceValue, UnityEventDrawer.GetMode(mode), type)) + { + string arg = "UnknownComponent"; + UnityEngine.Object objectReferenceValue2 = serializedProperty2.objectReferenceValue; + if (objectReferenceValue2 != null) + { + arg = objectReferenceValue2.GetType().Name; + } + stringBuilder.Append(string.Format("", arg, serializedProperty3.stringValue)); + } + else + { + stringBuilder.Append(serializedProperty2.objectReferenceValue.GetType().Name); + if (!string.IsNullOrEmpty(serializedProperty3.stringValue)) + { + stringBuilder.Append("."); + if (serializedProperty3.stringValue.StartsWith("set_")) + { + stringBuilder.Append(serializedProperty3.stringValue.Substring(4)); + } + else + { + stringBuilder.Append(serializedProperty3.stringValue); + } + } + } + } + content = GUIContent.Temp(stringBuilder.ToString()); + } + if (GUI.Button(rect2, content, EditorStyles.popup)) + { + UnityEventDrawer.BuildPopupList(serializedProperty2.objectReferenceValue, this.m_DummyEvent, arrayElementAtIndex).DropDown(rect2); + } + EditorGUI.EndProperty(); + EditorGUI.EndDisabledGroup(); + GUI.backgroundColor = backgroundColor; + } + private Rect[] GetRowRects(Rect rect) + { + Rect[] array = new Rect[4]; + rect.height = 16f; + rect.y += 2f; + Rect rect2 = rect; + rect2.width *= 0.3f; + Rect rect3 = rect2; + rect3.y += EditorGUIUtility.singleLineHeight + 2f; + Rect rect4 = rect; + rect4.xMin = rect3.xMax + 5f; + Rect rect5 = rect4; + rect5.y += EditorGUIUtility.singleLineHeight + 2f; + array[0] = rect2; + array[1] = rect3; + array[2] = rect4; + array[3] = rect5; + return array; + } + private void RemoveButton(ReorderableList list) + { + ReorderableList.defaultBehaviours.DoRemoveButton(list); + this.m_LastSelectedIndex = list.index; + } + private void AddEventListener(ReorderableList list) + { + if (this.m_ListenersArray.hasMultipleDifferentValues) + { + UnityEngine.Object[] targetObjects = this.m_ListenersArray.serializedObject.targetObjects; + for (int i = 0; i < targetObjects.Length; i++) + { + UnityEngine.Object obj = targetObjects[i]; + SerializedObject serializedObject = new SerializedObject(obj); + SerializedProperty serializedProperty = serializedObject.FindProperty(this.m_ListenersArray.propertyPath); + serializedProperty.arraySize++; + serializedObject.ApplyModifiedProperties(); + } + this.m_ListenersArray.serializedObject.SetIsDifferentCacheDirty(); + this.m_ListenersArray.serializedObject.Update(); + list.index = list.serializedProperty.arraySize - 1; + } + else + { + ReorderableList.defaultBehaviours.DoAddButton(list); + } + this.m_LastSelectedIndex = list.index; + SerializedProperty arrayElementAtIndex = this.m_ListenersArray.GetArrayElementAtIndex(list.index); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("m_CallState"); + SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("m_Target"); + SerializedProperty serializedProperty4 = arrayElementAtIndex.FindPropertyRelative("m_MethodName"); + SerializedProperty serializedProperty5 = arrayElementAtIndex.FindPropertyRelative("m_Mode"); + SerializedProperty serializedProperty6 = arrayElementAtIndex.FindPropertyRelative("m_Arguments"); + serializedProperty2.enumValueIndex = 2; + serializedProperty3.objectReferenceValue = null; + serializedProperty4.stringValue = null; + serializedProperty5.enumValueIndex = 1; + serializedProperty6.FindPropertyRelative("m_FloatArgument").floatValue = 0f; + serializedProperty6.FindPropertyRelative("m_IntArgument").intValue = 0; + serializedProperty6.FindPropertyRelative("m_ObjectArgument").objectReferenceValue = null; + serializedProperty6.FindPropertyRelative("m_StringArgument").stringValue = null; + serializedProperty6.FindPropertyRelative("m_ObjectArgumentAssemblyTypeName").stringValue = null; + } + private void SelectEventListener(ReorderableList list) + { + this.m_LastSelectedIndex = list.index; + } + private void EndDragChild(ReorderableList list) + { + this.m_LastSelectedIndex = list.index; + } + private static UnityEventBase GetDummyEvent(SerializedProperty prop) + { + string stringValue = prop.FindPropertyRelative("m_TypeName").stringValue; + Type type = Type.GetType(stringValue, false); + if (type == null) + { + return new UnityEvent(); + } + return Activator.CreateInstance(type) as UnityEventBase; + } + private static IEnumerable CalculateMethodMap(UnityEngine.Object target, Type[] t, bool allowSubclasses) + { + List list = new List(); + if (target == null || t == null) + { + return list; + } + Type type = target.GetType(); + List list2 = ( + from x in type.GetMethods() + where !x.IsSpecialName + select x).ToList(); + IEnumerable source = type.GetProperties().AsEnumerable(); + source = + from x in source + where x.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length == 0 && x.GetSetMethod() != null + select x; + list2.AddRange( + from x in source + select x.GetSetMethod()); + foreach (MethodInfo current in list2) + { + ParameterInfo[] parameters = current.GetParameters(); + if (parameters.Length == t.Length) + { + if (current.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length <= 0) + { + if (current.ReturnType == typeof(void)) + { + bool flag = true; + for (int i = 0; i < t.Length; i++) + { + if (!parameters[i].ParameterType.IsAssignableFrom(t[i])) + { + flag = false; + } + if (allowSubclasses && t[i].IsAssignableFrom(parameters[i].ParameterType)) + { + flag = true; + } + } + if (flag) + { + list.Add(new UnityEventDrawer.ValidMethodMap + { + target = target, + methodInfo = current + }); + } + } + } + } + } + return list; + } + public static bool IsPersistantListenerValid(UnityEventBase dummyEvent, string methodName, UnityEngine.Object uObject, PersistentListenerMode modeEnum, Type argumentType) + { + return !(uObject == null) && !string.IsNullOrEmpty(methodName) && dummyEvent.FindMethod(methodName, uObject, modeEnum, argumentType) != null; + } + private static GenericMenu BuildPopupList(UnityEngine.Object target, UnityEventBase dummyEvent, SerializedProperty listener) + { + UnityEngine.Object @object = target; + if (@object is Component) + { + @object = (target as Component).gameObject; + } + SerializedProperty serializedProperty = listener.FindPropertyRelative("m_MethodName"); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("No Function"), string.IsNullOrEmpty(serializedProperty.stringValue), new GenericMenu.MenuFunction2(UnityEventDrawer.ClearEventFunction), new UnityEventDrawer.UnityEventFunction(listener, null, null, PersistentListenerMode.EventDefined)); + if (@object == null) + { + return genericMenu; + } + genericMenu.AddSeparator(string.Empty); + Type type = dummyEvent.GetType(); + MethodInfo method = type.GetMethod("Invoke"); + Type[] delegateArgumentsTypes = ( + from x in method.GetParameters() + select x.ParameterType).ToArray(); + UnityEventDrawer.GeneratePopUpForType(genericMenu, @object, false, listener, delegateArgumentsTypes); + if (@object is GameObject) + { + Component[] components = (@object as GameObject).GetComponents(); + List list = ( + from c in components + where c != null + select c.GetType().Name into x + group x by x into g + where g.Count() > 1 + select g.Key).ToList(); + Component[] array = components; + for (int i = 0; i < array.Length; i++) + { + Component component = array[i]; + if (!(component == null)) + { + UnityEventDrawer.GeneratePopUpForType(genericMenu, component, list.Contains(component.GetType().Name), listener, delegateArgumentsTypes); + } + } + } + return genericMenu; + } + private static void GeneratePopUpForType(GenericMenu menu, UnityEngine.Object target, bool useFullTargetName, SerializedProperty listener, Type[] delegateArgumentsTypes) + { + List list = new List(); + string text = (!useFullTargetName) ? target.GetType().Name : target.GetType().FullName; + bool flag = false; + if (delegateArgumentsTypes.Length != 0) + { + UnityEventDrawer.GetMethodsForTargetAndMode(target, delegateArgumentsTypes, list, PersistentListenerMode.EventDefined); + if (list.Count > 0) + { + menu.AddDisabledItem(new GUIContent(text + "/Dynamic " + string.Join(", ", ( + from e in delegateArgumentsTypes + select UnityEventDrawer.GetTypeName(e)).ToArray()))); + UnityEventDrawer.AddMethodsToMenu(menu, listener, list, text); + flag = true; + } + } + list.Clear(); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[] + { + typeof(float) + }, list, PersistentListenerMode.Float); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[] + { + typeof(int) + }, list, PersistentListenerMode.Int); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[] + { + typeof(string) + }, list, PersistentListenerMode.String); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[] + { + typeof(bool) + }, list, PersistentListenerMode.Bool); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[] + { + typeof(UnityEngine.Object) + }, list, PersistentListenerMode.Object); + UnityEventDrawer.GetMethodsForTargetAndMode(target, new Type[0], list, PersistentListenerMode.Void); + if (list.Count > 0) + { + if (flag) + { + menu.AddItem(new GUIContent(text + "/ "), false, null); + } + if (delegateArgumentsTypes.Length != 0) + { + menu.AddDisabledItem(new GUIContent(text + "/Static Parameters")); + } + UnityEventDrawer.AddMethodsToMenu(menu, listener, list, text); + } + } + private static void AddMethodsToMenu(GenericMenu menu, SerializedProperty listener, List methods, string targetName) + { + IEnumerable enumerable = + from e in methods + orderby (!e.methodInfo.Name.StartsWith("set_")) ? 1 : 0, e.methodInfo.Name + select e; + foreach (UnityEventDrawer.ValidMethodMap current in enumerable) + { + UnityEventDrawer.AddFunctionsForScript(menu, listener, current, targetName); + } + } + private static void GetMethodsForTargetAndMode(UnityEngine.Object target, Type[] delegateArgumentsTypes, List methods, PersistentListenerMode mode) + { + IEnumerable enumerable = UnityEventDrawer.CalculateMethodMap(target, delegateArgumentsTypes, mode == PersistentListenerMode.Object); + foreach (UnityEventDrawer.ValidMethodMap current in enumerable) + { + UnityEventDrawer.ValidMethodMap item = current; + item.mode = mode; + methods.Add(item); + } + } + private static void AddFunctionsForScript(GenericMenu menu, SerializedProperty listener, UnityEventDrawer.ValidMethodMap method, string targetName) + { + PersistentListenerMode mode = method.mode; + UnityEngine.Object objectReferenceValue = listener.FindPropertyRelative("m_Target").objectReferenceValue; + string stringValue = listener.FindPropertyRelative("m_MethodName").stringValue; + PersistentListenerMode mode2 = UnityEventDrawer.GetMode(listener.FindPropertyRelative("m_Mode")); + SerializedProperty serializedProperty = listener.FindPropertyRelative("m_Arguments").FindPropertyRelative("m_ObjectArgumentAssemblyTypeName"); + StringBuilder stringBuilder = new StringBuilder(); + int num = method.methodInfo.GetParameters().Length; + for (int i = 0; i < num; i++) + { + ParameterInfo parameterInfo = method.methodInfo.GetParameters()[i]; + stringBuilder.Append(string.Format("{0}", UnityEventDrawer.GetTypeName(parameterInfo.ParameterType))); + if (i < num - 1) + { + stringBuilder.Append(", "); + } + } + bool flag = objectReferenceValue == method.target && stringValue == method.methodInfo.Name && mode == mode2; + if (flag && mode == PersistentListenerMode.Object && method.methodInfo.GetParameters().Length == 1) + { + flag &= (method.methodInfo.GetParameters()[0].ParameterType.AssemblyQualifiedName == serializedProperty.stringValue); + } + string formattedMethodName = UnityEventDrawer.GetFormattedMethodName(targetName, method.methodInfo.Name, stringBuilder.ToString(), mode == PersistentListenerMode.EventDefined); + menu.AddItem(new GUIContent(formattedMethodName), flag, new GenericMenu.MenuFunction2(UnityEventDrawer.SetEventFunction), new UnityEventDrawer.UnityEventFunction(listener, method.target, method.methodInfo, mode)); + } + private static string GetTypeName(Type t) + { + if (t == typeof(int)) + { + return "int"; + } + if (t == typeof(float)) + { + return "float"; + } + if (t == typeof(string)) + { + return "string"; + } + if (t == typeof(bool)) + { + return "bool"; + } + return t.Name; + } + private static string GetFormattedMethodName(string targetName, string methodName, string args, bool dynamic) + { + if (dynamic) + { + if (methodName.StartsWith("set_")) + { + return string.Format("{0}/{1}", targetName, methodName.Substring(4)); + } + return string.Format("{0}/{1}", targetName, methodName); + } + else + { + if (methodName.StartsWith("set_")) + { + return string.Format("{0}/{2} {1}", targetName, methodName.Substring(4), args); + } + return string.Format("{0}/{1} ({2})", targetName, methodName, args); + } + } + private static void SetEventFunction(object source) + { + ((UnityEventDrawer.UnityEventFunction)source).Assign(); + } + private static void ClearEventFunction(object source) + { + ((UnityEventDrawer.UnityEventFunction)source).Clear(); + } + } +} diff --git a/UnityEditor/ValidationResult.cs b/UnityEditor/ValidationResult.cs new file mode 100644 index 00000000..93cc6086 --- /dev/null +++ b/UnityEditor/ValidationResult.cs @@ -0,0 +1,9 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Scripting.Compilers; +internal struct ValidationResult +{ + public bool Success; + public IValidationRule Rule; + public IEnumerable CompilerMessages; +} diff --git a/UnityEditor/WinRTUtils.cs b/UnityEditor/WinRTUtils.cs new file mode 100644 index 00000000..eb8c5eae --- /dev/null +++ b/UnityEditor/WinRTUtils.cs @@ -0,0 +1,9 @@ +using System; +using UnityEditor; +internal class WinRTUtils +{ + public static string GetProcessorArchitecture(BuildTarget target) + { + return "x86"; + } +} diff --git a/UnityEditor/WindowsDesktopStandalonePostProcessor.cs b/UnityEditor/WindowsDesktopStandalonePostProcessor.cs new file mode 100644 index 00000000..2317dc62 --- /dev/null +++ b/UnityEditor/WindowsDesktopStandalonePostProcessor.cs @@ -0,0 +1,88 @@ +using System; +using System.IO; +using UnityEditor; +using UnityEditor.Modules; +using UnityEditor.WindowsStandalone; +using UnityEditorInternal; +internal class WindowsDesktopStandalonePostProcessor : DesktopStandalonePostProcessor +{ + protected override string DestinationFolderForInstallingIntoBuildsFolder + { + get + { + string str = (!base.Development) ? "win32_nondevelopment" : "win32_development"; + return "build/WindowsStandaloneSupport/Variations/" + str + "/Data"; + } + } + private string FullDataFolderPath + { + get + { + return Path.Combine(base.DestinationFolder, this.DestinationFileWithoutExtension + "_Data"); + } + } + private string DestinationFileWithoutExtension + { + get + { + return FileUtil.UnityGetFileNameWithoutExtension(this.FullPathToExe); + } + } + private string FullPathToExe + { + get + { + return this.m_PostProcessArgs.installPath; + } + } + protected override string StagingAreaPluginsFolder + { + get + { + return base.StagingArea + "/Data/Plugins"; + } + } + public WindowsDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) + { + } + protected override void RenameFilesInStagingArea() + { + string fileName = Path.GetFileName(this.m_PostProcessArgs.installPath); + FileUtil.MoveFileOrDirectory(base.StagingArea + "/player_win.exe", base.StagingArea + "/" + fileName); + FileUtil.MoveFileOrDirectory(base.StagingArea + "/Data", base.StagingArea + "/" + Path.GetFileNameWithoutExtension(fileName) + "_Data"); + } + protected override void DeleteDestination() + { + FileUtil.DeleteFileOrDirectory(this.FullPathToExe); + FileUtil.DeleteFileOrDirectory(this.FullDataFolderPath); + FileUtil.DeleteFileOrDirectory(Path.Combine(base.DestinationFolder, "UnityPlayer_Symbols.pdb")); + } + protected override string GetVariationName() + { + if (this.m_PostProcessArgs.target == BuildTarget.StandaloneGLESEmu) + { + return "glesemulator"; + } + return base.GetVariationName(); + } + protected override string PlatformStringFor(BuildTarget target) + { + if (target == BuildTarget.StandaloneWindows) + { + return "win32"; + } + if (target != BuildTarget.StandaloneWindows64) + { + throw new ArgumentException("Unexpected target: " + target); + } + return "win64"; + } + protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) + { + if (target != BuildTarget.StandaloneWindows && target != BuildTarget.StandaloneWindows64) + { + throw new Exception("Build target not supported."); + } + return new WindowsStandaloneIl2CppPlatformProvider(target, base.DataFolder, base.Development); + } +} diff --git a/UnityEngine/AOT/MonoPInvokeCallbackAttribute.cs b/UnityEngine/AOT/MonoPInvokeCallbackAttribute.cs new file mode 100644 index 00000000..948f8aa9 --- /dev/null +++ b/UnityEngine/AOT/MonoPInvokeCallbackAttribute.cs @@ -0,0 +1,11 @@ +using System; +namespace AOT +{ + [AttributeUsage(AttributeTargets.Method)] + public class MonoPInvokeCallbackAttribute : Attribute + { + public MonoPInvokeCallbackAttribute(Type type) + { + } + } +} diff --git a/UnityEngine/Properties/AssemblyInfo.cs b/UnityEngine/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..db26cd2d --- /dev/null +++ b/UnityEngine/Properties/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +[assembly: AssemblyVersion("0.0.0.0")] +[assembly: InternalsVisibleTo("Unity.PureCSharpTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] +[assembly: InternalsVisibleTo("UnityEditor.Graphs")] +[assembly: InternalsVisibleTo("UnityEditor.Xbox360.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor")] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] diff --git a/UnityEngine/UnityEngine.Events/ArgumentCache.cs b/UnityEngine/UnityEngine.Events/ArgumentCache.cs new file mode 100644 index 00000000..ccd40b12 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/ArgumentCache.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine.Serialization; +namespace UnityEngine.Events +{ + [Serializable] + internal class ArgumentCache + { + [FormerlySerializedAs("objectArgument"), SerializeField] + private UnityEngine.Object m_ObjectArgument; + [FormerlySerializedAs("objectArgumentAssemblyTypeName"), SerializeField] + private string m_ObjectArgumentAssemblyTypeName; + [FormerlySerializedAs("intArgument"), SerializeField] + private int m_IntArgument; + [FormerlySerializedAs("floatArgument"), SerializeField] + private float m_FloatArgument; + [FormerlySerializedAs("stringArgument"), SerializeField] + private string m_StringArgument; + [SerializeField] + private bool m_BoolArgument; + public UnityEngine.Object unityObjectArgument + { + get + { + return this.m_ObjectArgument; + } + set + { + this.m_ObjectArgument = value; + this.m_ObjectArgumentAssemblyTypeName = ((!(value != null)) ? string.Empty : value.GetType().AssemblyQualifiedName); + } + } + public string unityObjectArgumentAssemblyTypeName + { + get + { + return this.m_ObjectArgumentAssemblyTypeName; + } + } + public int intArgument + { + get + { + return this.m_IntArgument; + } + set + { + this.m_IntArgument = value; + } + } + public float floatArgument + { + get + { + return this.m_FloatArgument; + } + set + { + this.m_FloatArgument = value; + } + } + public string stringArgument + { + get + { + return this.m_StringArgument; + } + set + { + this.m_StringArgument = value; + } + } + public bool boolArgument + { + get + { + return this.m_BoolArgument; + } + set + { + this.m_BoolArgument = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine.Events/BaseInvokableCall.cs b/UnityEngine/UnityEngine.Events/BaseInvokableCall.cs new file mode 100644 index 00000000..6cfafd94 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/BaseInvokableCall.cs @@ -0,0 +1,39 @@ +using System; +using System.Reflection; +namespace UnityEngine.Events +{ + internal abstract class BaseInvokableCall + { + protected BaseInvokableCall() + { + } + protected BaseInvokableCall(object target, MethodInfo function) + { + if (target == null) + { + throw new ArgumentNullException("target"); + } + if (function == null) + { + throw new ArgumentNullException("function"); + } + } + public abstract void Invoke(object[] args); + protected static void ThrowOnInvalidArg(object arg) + { + if (arg != null && !(arg is T)) + { + throw new ArgumentException(UnityString.Format("Passed argument 'args[0]' is of the wrong type. Type:{0} Expected:{1}", new object[] + { + arg.GetType(), + typeof(T) + })); + } + } + protected static bool AllowInvoke(Delegate @delegate) + { + return @delegate.Method.IsStatic || @delegate.Target != null; + } + public abstract bool Find(object targetObj, MethodInfo method); + } +} diff --git a/UnityEngine/UnityEngine.Events/CachedInvokableCall.cs b/UnityEngine/UnityEngine.Events/CachedInvokableCall.cs new file mode 100644 index 00000000..fa363945 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/CachedInvokableCall.cs @@ -0,0 +1,17 @@ +using System; +using System.Reflection; +namespace UnityEngine.Events +{ + internal class CachedInvokableCall : InvokableCall + { + private readonly object[] m_Arg1 = new object[1]; + public CachedInvokableCall(UnityEngine.Object target, MethodInfo theFunction, T argument) : base(target, theFunction) + { + this.m_Arg1[0] = argument; + } + public override void Invoke(object[] args) + { + base.Invoke(this.m_Arg1); + } + } +} diff --git a/UnityEngine/UnityEngine.Events/InvokableCall.cs b/UnityEngine/UnityEngine.Events/InvokableCall.cs new file mode 100644 index 00000000..7036ac1b --- /dev/null +++ b/UnityEngine/UnityEngine.Events/InvokableCall.cs @@ -0,0 +1,207 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +namespace UnityEngine.Events +{ + internal class InvokableCall : BaseInvokableCall + { + private event UnityAction Delegate + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.Delegate = (UnityAction)System.Delegate.Remove(this.Delegate, value); + } + } + public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction) as UnityAction); + } + public InvokableCall(UnityAction action) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, action); + } + public override void Invoke(object[] args) + { + if (BaseInvokableCall.AllowInvoke(this.Delegate)) + { + this.Delegate(); + } + } + public override bool Find(object targetObj, MethodInfo method) + { + return this.Delegate.Target == targetObj && this.Delegate.Method == method; + } + } + internal class InvokableCall : BaseInvokableCall + { + protected event UnityAction Delegate + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.Delegate = (UnityAction)System.Delegate.Remove(this.Delegate, value); + } + } + public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction) as UnityAction); + } + public InvokableCall(UnityAction callback) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, callback); + } + public override void Invoke(object[] args) + { + if (args.Length != 1) + { + throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); + } + BaseInvokableCall.ThrowOnInvalidArg(args[0]); + if (BaseInvokableCall.AllowInvoke(this.Delegate)) + { + this.Delegate((T1)((object)args[0])); + } + } + public override bool Find(object targetObj, MethodInfo method) + { + return this.Delegate.Target == targetObj && this.Delegate.Method == method; + } + } + internal class InvokableCall : BaseInvokableCall + { + protected event UnityAction Delegate + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.Delegate = (UnityAction)System.Delegate.Remove(this.Delegate, value); + } + } + public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) + { + this.Delegate = (System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction) as UnityAction); + } + public InvokableCall(UnityAction action) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, action); + } + public override void Invoke(object[] args) + { + if (args.Length != 2) + { + throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); + } + BaseInvokableCall.ThrowOnInvalidArg(args[0]); + BaseInvokableCall.ThrowOnInvalidArg(args[1]); + if (BaseInvokableCall.AllowInvoke(this.Delegate)) + { + this.Delegate((T1)((object)args[0]), (T2)((object)args[1])); + } + } + public override bool Find(object targetObj, MethodInfo method) + { + return this.Delegate.Target == targetObj && this.Delegate.Method == method; + } + } + internal class InvokableCall : BaseInvokableCall + { + protected event UnityAction Delegate + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.Delegate = (UnityAction)System.Delegate.Remove(this.Delegate, value); + } + } + public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction) as UnityAction); + } + public InvokableCall(UnityAction action) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, action); + } + public override void Invoke(object[] args) + { + if (args.Length != 3) + { + throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); + } + BaseInvokableCall.ThrowOnInvalidArg(args[0]); + BaseInvokableCall.ThrowOnInvalidArg(args[1]); + BaseInvokableCall.ThrowOnInvalidArg(args[2]); + if (BaseInvokableCall.AllowInvoke(this.Delegate)) + { + this.Delegate((T1)((object)args[0]), (T2)((object)args[1]), (T3)((object)args[2])); + } + } + public override bool Find(object targetObj, MethodInfo method) + { + return this.Delegate.Target == targetObj && this.Delegate.Method == method; + } + } + internal class InvokableCall : BaseInvokableCall + { + protected event UnityAction Delegate + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.Delegate = (UnityAction)System.Delegate.Remove(this.Delegate, value); + } + } + public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction) as UnityAction); + } + public InvokableCall(UnityAction action) + { + this.Delegate = (UnityAction)System.Delegate.Combine(this.Delegate, action); + } + public override void Invoke(object[] args) + { + if (args.Length != 4) + { + throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); + } + BaseInvokableCall.ThrowOnInvalidArg(args[0]); + BaseInvokableCall.ThrowOnInvalidArg(args[1]); + BaseInvokableCall.ThrowOnInvalidArg(args[2]); + BaseInvokableCall.ThrowOnInvalidArg(args[3]); + if (BaseInvokableCall.AllowInvoke(this.Delegate)) + { + this.Delegate((T1)((object)args[0]), (T2)((object)args[1]), (T3)((object)args[2]), (T4)((object)args[3])); + } + } + public override bool Find(object targetObj, MethodInfo method) + { + return this.Delegate.Target == targetObj && this.Delegate.Method == method; + } + } +} diff --git a/UnityEngine/UnityEngine.Events/InvokableCallList.cs b/UnityEngine/UnityEngine.Events/InvokableCallList.cs new file mode 100644 index 00000000..a8e92ca8 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/InvokableCallList.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +namespace UnityEngine.Events +{ + internal class InvokableCallList + { + private readonly List m_PersistentCalls = new List(); + private readonly List m_RuntimeCalls = new List(); + private readonly List m_ExecutingCalls = new List(); + public int Count + { + get + { + return this.m_PersistentCalls.Count + this.m_RuntimeCalls.Count; + } + } + public void AddPersistentInvokableCall(BaseInvokableCall call) + { + this.m_PersistentCalls.Add(call); + } + public void AddListener(BaseInvokableCall call) + { + this.m_RuntimeCalls.Add(call); + } + public void RemoveListener(object targetObj, MethodInfo method) + { + List list = new List(); + for (int i = 0; i < this.m_RuntimeCalls.Count; i++) + { + if (this.m_RuntimeCalls[i].Find(targetObj, method)) + { + list.Add(this.m_RuntimeCalls[i]); + } + } + this.m_RuntimeCalls.RemoveAll(new Predicate(list.Contains)); + } + public void Clear() + { + this.m_RuntimeCalls.Clear(); + } + public void ClearPersistent() + { + this.m_PersistentCalls.Clear(); + } + public void Invoke(object[] parameters) + { + this.m_ExecutingCalls.AddRange(this.m_PersistentCalls); + this.m_ExecutingCalls.AddRange(this.m_RuntimeCalls); + for (int i = 0; i < this.m_ExecutingCalls.Count; i++) + { + this.m_ExecutingCalls[i].Invoke(parameters); + } + this.m_ExecutingCalls.Clear(); + } + } +} diff --git a/UnityEngine/UnityEngine.Events/PersistentCall.cs b/UnityEngine/UnityEngine.Events/PersistentCall.cs new file mode 100644 index 00000000..3270d213 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/PersistentCall.cs @@ -0,0 +1,142 @@ +using System; +using System.Reflection; +using UnityEngine.Serialization; +namespace UnityEngine.Events +{ + [Serializable] + internal class PersistentCall + { + [FormerlySerializedAs("instance"), SerializeField] + private UnityEngine.Object m_Target; + [FormerlySerializedAs("methodName"), SerializeField] + private string m_MethodName; + [FormerlySerializedAs("mode"), SerializeField] + private PersistentListenerMode m_Mode; + [FormerlySerializedAs("arguments"), SerializeField] + private ArgumentCache m_Arguments = new ArgumentCache(); + [FormerlySerializedAs("enabled"), FormerlySerializedAs("m_Enabled"), SerializeField] + private UnityEventCallState m_CallState = UnityEventCallState.RuntimeOnly; + public UnityEngine.Object target + { + get + { + return this.m_Target; + } + } + public string methodName + { + get + { + return this.m_MethodName; + } + } + public PersistentListenerMode mode + { + get + { + return this.m_Mode; + } + set + { + this.m_Mode = value; + } + } + public ArgumentCache arguments + { + get + { + return this.m_Arguments; + } + } + public UnityEventCallState callState + { + get + { + return this.m_CallState; + } + set + { + this.m_CallState = value; + } + } + public bool IsValid() + { + return this.target != null && !string.IsNullOrEmpty(this.methodName); + } + public BaseInvokableCall GetRuntimeCall(UnityEventBase theEvent) + { + if (this.m_CallState == UnityEventCallState.RuntimeOnly && !Application.isPlaying) + { + return null; + } + if (this.m_CallState == UnityEventCallState.Off || theEvent == null) + { + return null; + } + MethodInfo methodInfo = theEvent.FindMethod(this); + if (methodInfo == null) + { + return null; + } + switch (this.m_Mode) + { + case PersistentListenerMode.EventDefined: + return theEvent.GetDelegate(this.target, methodInfo); + case PersistentListenerMode.Void: + return new InvokableCall(this.target, methodInfo); + case PersistentListenerMode.Object: + return PersistentCall.GetObjectCall(this.target, methodInfo, this.m_Arguments); + case PersistentListenerMode.Int: + return new CachedInvokableCall(this.target, methodInfo, this.m_Arguments.intArgument); + case PersistentListenerMode.Float: + return new CachedInvokableCall(this.target, methodInfo, this.m_Arguments.floatArgument); + case PersistentListenerMode.String: + return new CachedInvokableCall(this.target, methodInfo, this.m_Arguments.stringArgument); + case PersistentListenerMode.Bool: + return new CachedInvokableCall(this.target, methodInfo, this.m_Arguments.boolArgument); + default: + return null; + } + } + private static BaseInvokableCall GetObjectCall(UnityEngine.Object target, MethodInfo method, ArgumentCache arguments) + { + Type type = typeof(UnityEngine.Object); + if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName)) + { + type = (Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, false) ?? typeof(UnityEngine.Object)); + } + Type typeFromHandle = typeof(CachedInvokableCall<>); + Type type2 = typeFromHandle.MakeGenericType(new Type[] + { + type + }); + ConstructorInfo constructor = type2.GetConstructor(new Type[] + { + typeof(UnityEngine.Object), + typeof(MethodInfo), + type + }); + UnityEngine.Object @object = arguments.unityObjectArgument; + if (@object != null && !type.IsAssignableFrom(@object.GetType())) + { + @object = null; + } + return constructor.Invoke(new object[] + { + target, + method, + @object + }) as BaseInvokableCall; + } + public void RegisterPersistentListener(UnityEngine.Object ttarget, string mmethodName) + { + this.m_Target = ttarget; + this.m_MethodName = mmethodName; + } + public void UnregisterPersistentListener() + { + this.m_MethodName = string.Empty; + this.m_Target = null; + } + } +} diff --git a/UnityEngine/UnityEngine.Events/PersistentCallGroup.cs b/UnityEngine/UnityEngine.Events/PersistentCallGroup.cs new file mode 100644 index 00000000..3de5daf0 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/PersistentCallGroup.cs @@ -0,0 +1,125 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Serialization; +namespace UnityEngine.Events +{ + [Serializable] + internal class PersistentCallGroup + { + [FormerlySerializedAs("m_Listeners"), SerializeField] + private List m_Calls; + public int Count + { + get + { + return this.m_Calls.Count; + } + } + public PersistentCallGroup() + { + this.m_Calls = new List(); + } + public PersistentCall GetListener(int index) + { + return this.m_Calls[index]; + } + public IEnumerable GetListeners() + { + return this.m_Calls; + } + public void AddListener() + { + this.m_Calls.Add(new PersistentCall()); + } + public void AddListener(PersistentCall call) + { + this.m_Calls.Add(call); + } + public void RemoveListener(int index) + { + this.m_Calls.RemoveAt(index); + } + public void Clear() + { + this.m_Calls.Clear(); + } + public void RegisterEventPersistentListener(int index, UnityEngine.Object targetObj, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.EventDefined; + } + public void RegisterVoidPersistentListener(int index, UnityEngine.Object targetObj, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.Void; + } + public void RegisterObjectPersistentListener(int index, UnityEngine.Object targetObj, UnityEngine.Object argument, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.Object; + listener.arguments.unityObjectArgument = argument; + } + public void RegisterIntPersistentListener(int index, UnityEngine.Object targetObj, int argument, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.Int; + listener.arguments.intArgument = argument; + } + public void RegisterFloatPersistentListener(int index, UnityEngine.Object targetObj, float argument, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.Float; + listener.arguments.floatArgument = argument; + } + public void RegisterStringPersistentListener(int index, UnityEngine.Object targetObj, string argument, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.String; + listener.arguments.stringArgument = argument; + } + public void RegisterBoolPersistentListener(int index, UnityEngine.Object targetObj, bool argument, string methodName) + { + PersistentCall listener = this.GetListener(index); + listener.RegisterPersistentListener(targetObj, methodName); + listener.mode = PersistentListenerMode.Bool; + listener.arguments.boolArgument = argument; + } + public void UnregisterPersistentListener(int index) + { + PersistentCall listener = this.GetListener(index); + listener.UnregisterPersistentListener(); + } + public void RemoveListeners(UnityEngine.Object target, string methodName) + { + List list = new List(); + for (int i = 0; i < this.m_Calls.Count; i++) + { + if (this.m_Calls[i].target == target && this.m_Calls[i].methodName == methodName) + { + list.Add(this.m_Calls[i]); + } + } + this.m_Calls.RemoveAll(new Predicate(list.Contains)); + } + public void Initialize(InvokableCallList invokableList, UnityEventBase unityEventBase) + { + foreach (PersistentCall current in this.m_Calls) + { + if (current.IsValid()) + { + BaseInvokableCall runtimeCall = current.GetRuntimeCall(unityEventBase); + if (runtimeCall != null) + { + invokableList.AddPersistentInvokableCall(runtimeCall); + } + } + } + } + } +} diff --git a/UnityEngine/UnityEngine.Events/PersistentListenerMode.cs b/UnityEngine/UnityEngine.Events/PersistentListenerMode.cs new file mode 100644 index 00000000..424147d9 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/PersistentListenerMode.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine.Events +{ + [Serializable] + public enum PersistentListenerMode + { + EventDefined, + Void, + Object, + Int, + Float, + String, + Bool + } +} diff --git a/UnityEngine/UnityEngine.Events/UnityAction.cs b/UnityEngine/UnityEngine.Events/UnityAction.cs new file mode 100644 index 00000000..8b3f320d --- /dev/null +++ b/UnityEngine/UnityEngine.Events/UnityAction.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Events +{ + public delegate void UnityAction(); + public delegate void UnityAction(T0 arg0); + public delegate void UnityAction(T0 arg0, T1 arg1); + public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2); + public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2, T3 arg3); +} diff --git a/UnityEngine/UnityEngine.Events/UnityEvent.cs b/UnityEngine/UnityEngine.Events/UnityEvent.cs new file mode 100644 index 00000000..bfed4ae6 --- /dev/null +++ b/UnityEngine/UnityEngine.Events/UnityEvent.cs @@ -0,0 +1,253 @@ +using System; +using System.Reflection; +namespace UnityEngine.Events +{ + [Serializable] + public class UnityEvent : UnityEventBase + { + private readonly object[] m_InvokeArray = new object[0]; + public void AddListener(UnityAction call) + { + base.AddCall(UnityEvent.GetDelegate(call)); + } + public void RemoveListener(UnityAction call) + { + base.RemoveListener(call.Target, call.Method); + } + protected override MethodInfo FindMethod_Impl(string name, object targetObj) + { + return UnityEventBase.GetValidMethodInfo(targetObj, name, new Type[0]); + } + internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) + { + return new InvokableCall(target, theFunction); + } + private static BaseInvokableCall GetDelegate(UnityAction action) + { + return new InvokableCall(action); + } + public void Invoke() + { + base.Invoke(this.m_InvokeArray); + } + internal void AddPersistentListener(UnityAction call) + { + int persistentEventCount = base.GetPersistentEventCount(); + base.AddPersistentListener(); + this.RegisterPersistentListener(persistentEventCount, call); + } + internal void RegisterPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + base.RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); + } + } + [Serializable] + public abstract class UnityEvent : UnityEventBase + { + private readonly object[] m_InvokeArray = new object[1]; + public void AddListener(UnityAction call) + { + base.AddCall(UnityEvent.GetDelegate(call)); + } + public void RemoveListener(UnityAction call) + { + base.RemoveListener(call.Target, call.Method); + } + protected override MethodInfo FindMethod_Impl(string name, object targetObj) + { + return UnityEventBase.GetValidMethodInfo(targetObj, name, new Type[] + { + typeof(T0) + }); + } + internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) + { + return new InvokableCall(target, theFunction); + } + private static BaseInvokableCall GetDelegate(UnityAction action) + { + return new InvokableCall(action); + } + public void Invoke(T0 arg0) + { + this.m_InvokeArray[0] = arg0; + base.Invoke(this.m_InvokeArray); + } + internal void AddPersistentListener(UnityAction call) + { + int persistentEventCount = base.GetPersistentEventCount(); + base.AddPersistentListener(); + this.RegisterPersistentListener(persistentEventCount, call); + } + internal void RegisterPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + base.RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); + } + } + [Serializable] + public abstract class UnityEvent : UnityEventBase + { + private readonly object[] m_InvokeArray = new object[2]; + public void AddListener(UnityAction call) + { + base.AddCall(UnityEvent.GetDelegate(call)); + } + public void RemoveListener(UnityAction call) + { + base.RemoveListener(call.Target, call.Method); + } + protected override MethodInfo FindMethod_Impl(string name, object targetObj) + { + return UnityEventBase.GetValidMethodInfo(targetObj, name, new Type[] + { + typeof(T0), + typeof(T1) + }); + } + internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) + { + return new InvokableCall(target, theFunction); + } + private static BaseInvokableCall GetDelegate(UnityAction action) + { + return new InvokableCall(action); + } + public void Invoke(T0 arg0, T1 arg1) + { + this.m_InvokeArray[0] = arg0; + this.m_InvokeArray[1] = arg1; + base.Invoke(this.m_InvokeArray); + } + internal void AddPersistentListener(UnityAction call) + { + int persistentEventCount = base.GetPersistentEventCount(); + base.AddPersistentListener(); + this.RegisterPersistentListener(persistentEventCount, call); + } + internal void RegisterPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + base.RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); + } + } + [Serializable] + public abstract class UnityEvent : UnityEventBase + { + private readonly object[] m_InvokeArray = new object[3]; + public void AddListener(UnityAction call) + { + base.AddCall(UnityEvent.GetDelegate(call)); + } + public void RemoveListener(UnityAction call) + { + base.RemoveListener(call.Target, call.Method); + } + protected override MethodInfo FindMethod_Impl(string name, object targetObj) + { + return UnityEventBase.GetValidMethodInfo(targetObj, name, new Type[] + { + typeof(T0), + typeof(T1), + typeof(T2) + }); + } + internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) + { + return new InvokableCall(target, theFunction); + } + private static BaseInvokableCall GetDelegate(UnityAction action) + { + return new InvokableCall(action); + } + public void Invoke(T0 arg0, T1 arg1, T2 arg2) + { + this.m_InvokeArray[0] = arg0; + this.m_InvokeArray[1] = arg1; + this.m_InvokeArray[2] = arg2; + base.Invoke(this.m_InvokeArray); + } + internal void AddPersistentListener(UnityAction call) + { + int persistentEventCount = base.GetPersistentEventCount(); + base.AddPersistentListener(); + this.RegisterPersistentListener(persistentEventCount, call); + } + internal void RegisterPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + base.RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); + } + } + [Serializable] + public abstract class UnityEvent : UnityEventBase + { + private readonly object[] m_InvokeArray = new object[4]; + public void AddListener(UnityAction call) + { + base.AddCall(UnityEvent.GetDelegate(call)); + } + public void RemoveListener(UnityAction call) + { + base.RemoveListener(call.Target, call.Method); + } + protected override MethodInfo FindMethod_Impl(string name, object targetObj) + { + return UnityEventBase.GetValidMethodInfo(targetObj, name, new Type[] + { + typeof(T0), + typeof(T1), + typeof(T2), + typeof(T3) + }); + } + internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) + { + return new InvokableCall(target, theFunction); + } + private static BaseInvokableCall GetDelegate(UnityAction action) + { + return new InvokableCall(action); + } + public void Invoke(T0 arg0, T1 arg1, T2 arg2, T3 arg3) + { + this.m_InvokeArray[0] = arg0; + this.m_InvokeArray[1] = arg1; + this.m_InvokeArray[2] = arg2; + this.m_InvokeArray[3] = arg3; + base.Invoke(this.m_InvokeArray); + } + internal void AddPersistentListener(UnityAction call) + { + int persistentEventCount = base.GetPersistentEventCount(); + base.AddPersistentListener(); + this.RegisterPersistentListener(persistentEventCount, call); + } + internal void RegisterPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + base.RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); + } + } +} diff --git a/UnityEngine/UnityEngine.Events/UnityEventBase.cs b/UnityEngine/UnityEngine.Events/UnityEventBase.cs new file mode 100644 index 00000000..1ed6d19e --- /dev/null +++ b/UnityEngine/UnityEngine.Events/UnityEventBase.cs @@ -0,0 +1,366 @@ +using System; +using System.Reflection; +using UnityEngine.Serialization; +namespace UnityEngine.Events +{ + [Serializable] + public abstract class UnityEventBase : ISerializationCallbackReceiver + { + private InvokableCallList m_Calls; + [FormerlySerializedAs("m_PersistentListeners"), SerializeField] + private PersistentCallGroup m_PersistentCalls; + [SerializeField] + private string m_TypeName; + private bool m_CallsDirty = true; + protected UnityEventBase() + { + this.m_Calls = new InvokableCallList(); + this.m_PersistentCalls = new PersistentCallGroup(); + this.m_TypeName = base.GetType().AssemblyQualifiedName; + } + void ISerializationCallbackReceiver.OnBeforeSerialize() + { + } + void ISerializationCallbackReceiver.OnAfterDeserialize() + { + this.DirtyPersistentCalls(); + this.m_TypeName = base.GetType().AssemblyQualifiedName; + } + protected abstract MethodInfo FindMethod_Impl(string name, object targetObj); + internal abstract BaseInvokableCall GetDelegate(object target, MethodInfo theFunction); + internal MethodInfo FindMethod(PersistentCall call) + { + Type argumentType = typeof(UnityEngine.Object); + if (!string.IsNullOrEmpty(call.arguments.unityObjectArgumentAssemblyTypeName)) + { + argumentType = (Type.GetType(call.arguments.unityObjectArgumentAssemblyTypeName, false) ?? typeof(UnityEngine.Object)); + } + return this.FindMethod(call.methodName, call.target, call.mode, argumentType); + } + internal MethodInfo FindMethod(string name, object listener, PersistentListenerMode mode, Type argumentType) + { + switch (mode) + { + case PersistentListenerMode.EventDefined: + return this.FindMethod_Impl(name, listener); + case PersistentListenerMode.Void: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[0]); + case PersistentListenerMode.Object: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[] + { + argumentType ?? typeof(UnityEngine.Object) + }); + case PersistentListenerMode.Int: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[] + { + typeof(int) + }); + case PersistentListenerMode.Float: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[] + { + typeof(float) + }); + case PersistentListenerMode.String: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[] + { + typeof(string) + }); + case PersistentListenerMode.Bool: + return UnityEventBase.GetValidMethodInfo(listener, name, new Type[] + { + typeof(bool) + }); + default: + return null; + } + } + public int GetPersistentEventCount() + { + return this.m_PersistentCalls.Count; + } + public UnityEngine.Object GetPersistentTarget(int index) + { + PersistentCall listener = this.m_PersistentCalls.GetListener(index); + return (listener == null) ? null : listener.target; + } + public string GetPersistentMethodName(int index) + { + PersistentCall listener = this.m_PersistentCalls.GetListener(index); + return (listener == null) ? string.Empty : listener.methodName; + } + private void DirtyPersistentCalls() + { + this.m_Calls.ClearPersistent(); + this.m_CallsDirty = true; + } + private void RebuildPersistentCallsIfNeeded() + { + if (this.m_CallsDirty) + { + this.m_PersistentCalls.Initialize(this.m_Calls, this); + this.m_CallsDirty = false; + } + } + public void SetPersistentListenerState(int index, UnityEventCallState state) + { + PersistentCall listener = this.m_PersistentCalls.GetListener(index); + if (listener != null) + { + listener.callState = state; + } + this.DirtyPersistentCalls(); + } + protected void AddListener(object targetObj, MethodInfo method) + { + this.m_Calls.AddListener(this.GetDelegate(targetObj, method)); + } + internal void AddCall(BaseInvokableCall call) + { + this.m_Calls.AddListener(call); + } + protected void RemoveListener(object targetObj, MethodInfo method) + { + this.m_Calls.RemoveListener(targetObj, method); + } + public void RemoveAllListeners() + { + this.m_Calls.Clear(); + } + protected void Invoke(object[] parameters) + { + this.RebuildPersistentCallsIfNeeded(); + this.m_Calls.Invoke(parameters); + } + public override string ToString() + { + return base.ToString() + " " + base.GetType().FullName; + } + public static MethodInfo GetValidMethodInfo(object obj, string functionName, Type[] argumentTypes) + { + Type type = obj.GetType(); + while (type != typeof(object) && type != null) + { + MethodInfo method = type.GetMethod(functionName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, argumentTypes, null); + if (method != null) + { + ParameterInfo[] parameters = method.GetParameters(); + bool flag = true; + int num = 0; + ParameterInfo[] array = parameters; + for (int i = 0; i < array.Length; i++) + { + ParameterInfo parameterInfo = array[i]; + Type type2 = argumentTypes[num]; + Type parameterType = parameterInfo.ParameterType; + flag = (type2.IsPrimitive == parameterType.IsPrimitive); + if (!flag) + { + break; + } + num++; + } + if (flag) + { + return method; + } + } + type = type.BaseType; + } + return null; + } + protected bool ValidateRegistration(MethodInfo method, object targetObj, PersistentListenerMode mode) + { + return this.ValidateRegistration(method, targetObj, mode, typeof(UnityEngine.Object)); + } + protected bool ValidateRegistration(MethodInfo method, object targetObj, PersistentListenerMode mode, Type argumentType) + { + if (method == null) + { + throw new ArgumentNullException("method", UnityString.Format("Can not register null method on {0} for callback!", new object[] + { + targetObj + })); + } + UnityEngine.Object @object = targetObj as UnityEngine.Object; + if (@object == null || @object.GetInstanceID() == 0) + { + throw new ArgumentException(UnityString.Format("Could not register callback {0} on {1}. The class {2} does not derive from UnityEngine.Object", new object[] + { + method.Name, + targetObj, + (targetObj != null) ? targetObj.GetType().ToString() : "null" + })); + } + if (method.IsStatic) + { + throw new ArgumentException(UnityString.Format("Could not register listener {0} on {1} static functions are not supported.", new object[] + { + method, + base.GetType() + })); + } + if (this.FindMethod(method.Name, targetObj, mode, argumentType) == null) + { + Debug.LogWarning(UnityString.Format("Could not register listener {0}.{1} on {2} the method could not be found.", new object[] + { + targetObj, + method, + base.GetType() + })); + return false; + } + return true; + } + internal void AddPersistentListener() + { + this.m_PersistentCalls.AddListener(); + } + protected void RegisterPersistentListener(int index, object targetObj, MethodInfo method) + { + if (!this.ValidateRegistration(method, targetObj, PersistentListenerMode.EventDefined)) + { + return; + } + this.m_PersistentCalls.RegisterEventPersistentListener(index, targetObj as UnityEngine.Object, method.Name); + this.DirtyPersistentCalls(); + } + internal void RemovePersistentListener(UnityEngine.Object target, MethodInfo method) + { + if (method == null || method.IsStatic || target == null || target.GetInstanceID() == 0) + { + return; + } + this.m_PersistentCalls.RemoveListeners(target, method.Name); + this.DirtyPersistentCalls(); + } + internal void RemovePersistentListener(int index) + { + this.m_PersistentCalls.RemoveListener(index); + this.DirtyPersistentCalls(); + } + internal void UnregisterPersistentListener(int index) + { + this.m_PersistentCalls.UnregisterPersistentListener(index); + this.DirtyPersistentCalls(); + } + internal void AddVoidPersistentListener(UnityAction call) + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterVoidPersistentListener(persistentEventCount, call); + } + internal void RegisterVoidPersistentListener(int index, UnityAction call) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.Void)) + { + return; + } + this.m_PersistentCalls.RegisterVoidPersistentListener(index, call.Target as UnityEngine.Object, call.Method.Name); + this.DirtyPersistentCalls(); + } + internal void AddIntPersistentListener(UnityAction call, int argument) + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterIntPersistentListener(persistentEventCount, call, argument); + } + internal void RegisterIntPersistentListener(int index, UnityAction call, int argument) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.Int)) + { + return; + } + this.m_PersistentCalls.RegisterIntPersistentListener(index, call.Target as UnityEngine.Object, argument, call.Method.Name); + this.DirtyPersistentCalls(); + } + internal void AddFloatPersistentListener(UnityAction call, float argument) + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterFloatPersistentListener(persistentEventCount, call, argument); + } + internal void RegisterFloatPersistentListener(int index, UnityAction call, float argument) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.Float)) + { + return; + } + this.m_PersistentCalls.RegisterFloatPersistentListener(index, call.Target as UnityEngine.Object, argument, call.Method.Name); + this.DirtyPersistentCalls(); + } + internal void AddBoolPersistentListener(UnityAction call, bool argument) + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterBoolPersistentListener(persistentEventCount, call, argument); + } + internal void RegisterBoolPersistentListener(int index, UnityAction call, bool argument) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.Bool)) + { + return; + } + this.m_PersistentCalls.RegisterBoolPersistentListener(index, call.Target as UnityEngine.Object, argument, call.Method.Name); + this.DirtyPersistentCalls(); + } + internal void AddStringPersistentListener(UnityAction call, string argument) + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterStringPersistentListener(persistentEventCount, call, argument); + } + internal void RegisterStringPersistentListener(int index, UnityAction call, string argument) + { + if (call == null) + { + Debug.LogWarning("Registering a Listener requires an action"); + return; + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.String)) + { + return; + } + this.m_PersistentCalls.RegisterStringPersistentListener(index, call.Target as UnityEngine.Object, argument, call.Method.Name); + this.DirtyPersistentCalls(); + } + internal void AddObjectPersistentListener(UnityAction call, T argument) where T : UnityEngine.Object + { + int persistentEventCount = this.GetPersistentEventCount(); + this.AddPersistentListener(); + this.RegisterObjectPersistentListener(persistentEventCount, call, argument); + } + internal void RegisterObjectPersistentListener(int index, UnityAction call, T argument) where T : UnityEngine.Object + { + if (call == null) + { + throw new ArgumentNullException("call", "Registering a Listener requires a non null call"); + } + if (!this.ValidateRegistration(call.Method, call.Target, PersistentListenerMode.Object, (!(argument == null)) ? argument.GetType() : typeof(UnityEngine.Object))) + { + return; + } + this.m_PersistentCalls.RegisterObjectPersistentListener(index, call.Target as UnityEngine.Object, argument, call.Method.Name); + this.DirtyPersistentCalls(); + } + } +} diff --git a/UnityEngine/UnityEngine.Events/UnityEventCallState.cs b/UnityEngine/UnityEngine.Events/UnityEventCallState.cs new file mode 100644 index 00000000..5d3df66e --- /dev/null +++ b/UnityEngine/UnityEngine.Events/UnityEventCallState.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.Events +{ + public enum UnityEventCallState + { + Off, + EditorAndRuntime, + RuntimeOnly + } +} diff --git a/UnityEngine/UnityEngine.Flash/ActionScript.cs b/UnityEngine/UnityEngine.Flash/ActionScript.cs new file mode 100644 index 00000000..27ba9351 --- /dev/null +++ b/UnityEngine/UnityEngine.Flash/ActionScript.cs @@ -0,0 +1,21 @@ +using System; +using System.Diagnostics; +namespace UnityEngine.Flash +{ + [NotConverted] + public sealed class ActionScript + { + [Conditional("UNITY_FLASH")] + public static void Import(string package) + { + } + [Conditional("UNITY_FLASH")] + public static void Statement(string formatString, params object[] arguments) + { + } + public static T Expression(string formatString, params object[] arguments) + { + throw new InvalidOperationException(); + } + } +} diff --git a/UnityEngine/UnityEngine.Flash/FlashPlayer.cs b/UnityEngine/UnityEngine.Flash/FlashPlayer.cs new file mode 100644 index 00000000..6323e1c4 --- /dev/null +++ b/UnityEngine/UnityEngine.Flash/FlashPlayer.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEngine.Flash +{ + public sealed class FlashPlayer + { + public static string TargetVersion + { + get + { + return FlashPlayer.GetUnityAppConstants("TargetFlashPlayerVersion"); + } + } + public static string TargetSwfVersion + { + get + { + return FlashPlayer.GetUnityAppConstants("TargetSwfVersion"); + } + } + internal static string GetUnityAppConstants(string name) + { + return ActionScript.Expression("UnityNative.getUnityAppConstants()[{0}]", new object[] + { + name + }); + } + } +} diff --git a/UnityEngine/UnityEngine.Internal/DefaultValueAttribute.cs b/UnityEngine/UnityEngine.Internal/DefaultValueAttribute.cs new file mode 100644 index 00000000..da0f6cf0 --- /dev/null +++ b/UnityEngine/UnityEngine.Internal/DefaultValueAttribute.cs @@ -0,0 +1,42 @@ +using System; +namespace UnityEngine.Internal +{ + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)] + [Serializable] + public class DefaultValueAttribute : Attribute + { + private object DefaultValue; + public object Value + { + get + { + return this.DefaultValue; + } + } + public DefaultValueAttribute(string value) + { + this.DefaultValue = value; + } + public override bool Equals(object obj) + { + DefaultValueAttribute defaultValueAttribute = obj as DefaultValueAttribute; + if (defaultValueAttribute == null) + { + return false; + } + if (this.DefaultValue == null) + { + return defaultValueAttribute.Value == null; + } + return this.DefaultValue.Equals(defaultValueAttribute.Value); + } + public override int GetHashCode() + { + if (this.DefaultValue == null) + { + return base.GetHashCode(); + } + return this.DefaultValue.GetHashCode(); + } + } +} diff --git a/UnityEngine/UnityEngine.Internal/ExcludeFromDocsAttribute.cs b/UnityEngine/UnityEngine.Internal/ExcludeFromDocsAttribute.cs new file mode 100644 index 00000000..c910c010 --- /dev/null +++ b/UnityEngine/UnityEngine.Internal/ExcludeFromDocsAttribute.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Internal +{ + [AttributeUsage(AttributeTargets.Method)] + [Serializable] + public class ExcludeFromDocsAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine.Rendering/BlendMode.cs b/UnityEngine/UnityEngine.Rendering/BlendMode.cs new file mode 100644 index 00000000..b72f047d --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/BlendMode.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum BlendMode + { + Zero, + One, + DstColor, + SrcColor, + OneMinusDstColor, + SrcAlpha, + OneMinusSrcColor, + DstAlpha, + OneMinusDstAlpha, + SrcAlphaSaturate, + OneMinusSrcAlpha + } +} diff --git a/UnityEngine/UnityEngine.Rendering/BlendOp.cs b/UnityEngine/UnityEngine.Rendering/BlendOp.cs new file mode 100644 index 00000000..d5ecba82 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/BlendOp.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum BlendOp + { + Add, + Subtract, + ReverseSubtract, + Min, + Max, + LogicalClear, + LogicalSet, + LogicalCopy, + LogicalCopyInverted, + LogicalNoop, + LogicalInvert, + LogicalAnd, + LogicalNand, + LogicalOr, + LogicalNor, + LogicalXor, + LogicalEquivalence, + LogicalAndReverse, + LogicalAndInverted, + LogicalOrReverse, + LogicalOrInverted + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ColorWriteMask.cs b/UnityEngine/UnityEngine.Rendering/ColorWriteMask.cs new file mode 100644 index 00000000..a36e61b2 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ColorWriteMask.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine.Rendering +{ + [Flags] + public enum ColorWriteMask + { + Alpha = 1, + Blue = 2, + Green = 4, + Red = 8, + All = 15 + } +} diff --git a/UnityEngine/UnityEngine.Rendering/CompareFunction.cs b/UnityEngine/UnityEngine.Rendering/CompareFunction.cs new file mode 100644 index 00000000..b640b02b --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/CompareFunction.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum CompareFunction + { + Disabled, + Never, + Less, + Equal, + LessEqual, + Greater, + NotEqual, + GreaterEqual, + Always + } +} diff --git a/UnityEngine/UnityEngine.Rendering/CullMode.cs b/UnityEngine/UnityEngine.Rendering/CullMode.cs new file mode 100644 index 00000000..03a81257 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/CullMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum CullMode + { + Off, + Front, + Back + } +} diff --git a/UnityEngine/UnityEngine.Rendering/StencilOp.cs b/UnityEngine/UnityEngine.Rendering/StencilOp.cs new file mode 100644 index 00000000..352fe09e --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/StencilOp.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum StencilOp + { + Keep, + Zero, + Replace, + IncrementSaturate, + DecrementSaturate, + Invert, + IncrementWrap, + DecrementWrap + } +} diff --git a/UnityEngine/UnityEngine.Serialization/DictionarySerializationSurrogate.cs b/UnityEngine/UnityEngine.Serialization/DictionarySerializationSurrogate.cs new file mode 100644 index 00000000..474066f9 --- /dev/null +++ b/UnityEngine/UnityEngine.Serialization/DictionarySerializationSurrogate.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +namespace UnityEngine.Serialization +{ + internal class DictionarySerializationSurrogate : ISerializationSurrogate + { + public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) + { + Dictionary dictionary = (Dictionary)obj; + dictionary.GetObjectData(info, context); + } + public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) + { + IEqualityComparer comparer = (IEqualityComparer)info.GetValue("Comparer", typeof(IEqualityComparer)); + Dictionary dictionary = new Dictionary(comparer); + if (info.MemberCount > 3) + { + KeyValuePair[] array = (KeyValuePair[])info.GetValue("KeyValuePairs", typeof(KeyValuePair[])); + if (array != null) + { + KeyValuePair[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + KeyValuePair keyValuePair = array2[i]; + dictionary.Add(keyValuePair.Key, keyValuePair.Value); + } + } + } + return dictionary; + } + } +} diff --git a/UnityEngine/UnityEngine.Serialization/FormerlySerializedAsAttribute.cs b/UnityEngine/UnityEngine.Serialization/FormerlySerializedAsAttribute.cs new file mode 100644 index 00000000..a546bedd --- /dev/null +++ b/UnityEngine/UnityEngine.Serialization/FormerlySerializedAsAttribute.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine.Serialization +{ + [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)] + public class FormerlySerializedAsAttribute : Attribute + { + private string m_oldName; + public string oldName + { + get + { + return this.m_oldName; + } + } + public FormerlySerializedAsAttribute(string oldName) + { + this.m_oldName = oldName; + } + } +} diff --git a/UnityEngine/UnityEngine.Serialization/ListSerializationSurrogate.cs b/UnityEngine/UnityEngine.Serialization/ListSerializationSurrogate.cs new file mode 100644 index 00000000..544363ec --- /dev/null +++ b/UnityEngine/UnityEngine.Serialization/ListSerializationSurrogate.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections; +using System.Runtime.Serialization; +namespace UnityEngine.Serialization +{ + internal class ListSerializationSurrogate : ISerializationSurrogate + { + public static readonly ISerializationSurrogate Default = new ListSerializationSurrogate(); + public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) + { + IList list = (IList)obj; + info.AddValue("_size", list.Count); + info.AddValue("_items", ListSerializationSurrogate.ArrayFromGenericList(list)); + info.AddValue("_version", 0); + } + public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) + { + IList list = (IList)Activator.CreateInstance(obj.GetType()); + int @int = info.GetInt32("_size"); + if (@int == 0) + { + return list; + } + IEnumerator enumerator = ((IEnumerable)info.GetValue("_items", typeof(IEnumerable))).GetEnumerator(); + for (int i = 0; i < @int; i++) + { + if (!enumerator.MoveNext()) + { + throw new InvalidOperationException(); + } + list.Add(enumerator.Current); + } + return list; + } + private static Array ArrayFromGenericList(IList list) + { + Array array = Array.CreateInstance(list.GetType().GetGenericArguments()[0], list.Count); + list.CopyTo(array, 0); + return array; + } + } +} diff --git a/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs b/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs new file mode 100644 index 00000000..e582641d --- /dev/null +++ b/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine.Serialization +{ + internal class SerializationHelper + { + private static bool alreadyWarned; + public static void LogSerializationDepthWarning(string namespaze, string name) + { + if (SerializationHelper.alreadyWarned) + { + return; + } + SerializationHelper.alreadyWarned = true; + string str = (namespaze.Length <= 0) ? name : (namespaze + "." + name); + Debug.LogWarning("Serialization of " + str + " has too many depth levels. This means you have fallen of a performance cliff. Check the Serialization section of the docs for more details about this problem and how to fix it."); + } + } +} diff --git a/UnityEngine/UnityEngine.Serialization/UnitySurrogateSelector.cs b/UnityEngine/UnityEngine.Serialization/UnitySurrogateSelector.cs new file mode 100644 index 00000000..40ecac01 --- /dev/null +++ b/UnityEngine/UnityEngine.Serialization/UnitySurrogateSelector.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +namespace UnityEngine.Serialization +{ + public class UnitySurrogateSelector : ISurrogateSelector + { + public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) + { + if (type.IsGenericType) + { + Type genericTypeDefinition = type.GetGenericTypeDefinition(); + if (genericTypeDefinition == typeof(List<>)) + { + selector = this; + return ListSerializationSurrogate.Default; + } + if (genericTypeDefinition == typeof(Dictionary<, >)) + { + selector = this; + Type type2 = typeof(DictionarySerializationSurrogate<, >).MakeGenericType(type.GetGenericArguments()); + return (ISerializationSurrogate)Activator.CreateInstance(type2); + } + } + selector = null; + return null; + } + public void ChainSelector(ISurrogateSelector selector) + { + throw new NotImplementedException(); + } + public ISurrogateSelector GetNextSelector() + { + throw new NotImplementedException(); + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.GameCenter/GameCenterPlatform.cs b/UnityEngine/UnityEngine.SocialPlatforms.GameCenter/GameCenterPlatform.cs new file mode 100644 index 00000000..a1d622ac --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.GameCenter/GameCenterPlatform.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine.SocialPlatforms.GameCenter +{ + public class GameCenterPlatform : Local + { + public static void ResetAllAchievements(Action callback) + { + Debug.Log("ResetAllAchievements - no effect in editor"); + callback(true); + } + public static void ShowDefaultAchievementCompletionBanner(bool value) + { + Debug.Log("ShowDefaultAchievementCompletionBanner - no effect in editor"); + } + public static void ShowLeaderboardUI(string leaderboardID, TimeScope timeScope) + { + Debug.Log("ShowLeaderboardUI - no effect in editor"); + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/Achievement.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Achievement.cs new file mode 100644 index 00000000..c1f58282 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Achievement.cs @@ -0,0 +1,91 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class Achievement : IAchievement + { + private bool m_Completed; + private bool m_Hidden; + private DateTime m_LastReportedDate; + public string id + { + get; + set; + } + public double percentCompleted + { + get; + set; + } + public bool completed + { + get + { + return this.m_Completed; + } + } + public bool hidden + { + get + { + return this.m_Hidden; + } + } + public DateTime lastReportedDate + { + get + { + return this.m_LastReportedDate; + } + } + public Achievement(string id, double percentCompleted, bool completed, bool hidden, DateTime lastReportedDate) + { + this.id = id; + this.percentCompleted = percentCompleted; + this.m_Completed = completed; + this.m_Hidden = hidden; + this.m_LastReportedDate = lastReportedDate; + } + public Achievement(string id, double percent) + { + this.id = id; + this.percentCompleted = percent; + this.m_Hidden = false; + this.m_Completed = false; + this.m_LastReportedDate = DateTime.MinValue; + } + public Achievement() : this("unknown", 0.0) + { + } + public override string ToString() + { + return string.Concat(new object[] + { + this.id, + " - ", + this.percentCompleted, + " - ", + this.completed, + " - ", + this.hidden, + " - ", + this.lastReportedDate + }); + } + public void ReportProgress(Action callback) + { + ActivePlatform.Instance.ReportProgress(this.id, this.percentCompleted, callback); + } + public void SetCompleted(bool value) + { + this.m_Completed = value; + } + public void SetHidden(bool value) + { + this.m_Hidden = value; + } + public void SetLastReportedDate(DateTime date) + { + this.m_LastReportedDate = date; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/AchievementDescription.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/AchievementDescription.cs new file mode 100644 index 00000000..084b1104 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/AchievementDescription.cs @@ -0,0 +1,91 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class AchievementDescription : IAchievementDescription + { + private string m_Title; + private Texture2D m_Image; + private string m_AchievedDescription; + private string m_UnachievedDescription; + private bool m_Hidden; + private int m_Points; + public string id + { + get; + set; + } + public string title + { + get + { + return this.m_Title; + } + } + public Texture2D image + { + get + { + return this.m_Image; + } + } + public string achievedDescription + { + get + { + return this.m_AchievedDescription; + } + } + public string unachievedDescription + { + get + { + return this.m_UnachievedDescription; + } + } + public bool hidden + { + get + { + return this.m_Hidden; + } + } + public int points + { + get + { + return this.m_Points; + } + } + public AchievementDescription(string id, string title, Texture2D image, string achievedDescription, string unachievedDescription, bool hidden, int points) + { + this.id = id; + this.m_Title = title; + this.m_Image = image; + this.m_AchievedDescription = achievedDescription; + this.m_UnachievedDescription = unachievedDescription; + this.m_Hidden = hidden; + this.m_Points = points; + } + public override string ToString() + { + return string.Concat(new object[] + { + this.id, + " - ", + this.title, + " - ", + this.achievedDescription, + " - ", + this.unachievedDescription, + " - ", + this.points, + " - ", + this.hidden + }); + } + public void SetImage(Texture2D image) + { + this.m_Image = image; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/Leaderboard.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Leaderboard.cs new file mode 100644 index 00000000..999e75b9 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Leaderboard.cs @@ -0,0 +1,135 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class Leaderboard : ILeaderboard + { + private bool m_Loading; + private IScore m_LocalUserScore; + private uint m_MaxRange; + private IScore[] m_Scores; + private string m_Title; + private string[] m_UserIDs; + public bool loading + { + get + { + return ActivePlatform.Instance.GetLoading(this); + } + } + public string id + { + get; + set; + } + public UserScope userScope + { + get; + set; + } + public Range range + { + get; + set; + } + public TimeScope timeScope + { + get; + set; + } + public IScore localUserScore + { + get + { + return this.m_LocalUserScore; + } + } + public uint maxRange + { + get + { + return this.m_MaxRange; + } + } + public IScore[] scores + { + get + { + return this.m_Scores; + } + } + public string title + { + get + { + return this.m_Title; + } + } + public Leaderboard() + { + this.id = "Invalid"; + this.range = new Range(1, 10); + this.userScope = UserScope.Global; + this.timeScope = TimeScope.AllTime; + this.m_Loading = false; + this.m_LocalUserScore = new Score("Invalid", 0L); + this.m_MaxRange = 0u; + this.m_Scores = new Score[0]; + this.m_Title = "Invalid"; + this.m_UserIDs = new string[0]; + } + public void SetUserFilter(string[] userIDs) + { + this.m_UserIDs = userIDs; + } + public override string ToString() + { + return string.Concat(new object[] + { + "ID: '", + this.id, + "' Title: '", + this.m_Title, + "' Loading: '", + this.m_Loading, + "' Range: [", + this.range.from, + ",", + this.range.count, + "] MaxRange: '", + this.m_MaxRange, + "' Scores: '", + this.m_Scores.Length, + "' UserScope: '", + this.userScope, + "' TimeScope: '", + this.timeScope, + "' UserFilter: '", + this.m_UserIDs.Length + }); + } + public void LoadScores(Action callback) + { + ActivePlatform.Instance.LoadScores(this, callback); + } + public void SetLocalUserScore(IScore score) + { + this.m_LocalUserScore = score; + } + public void SetMaxRange(uint maxRange) + { + this.m_MaxRange = maxRange; + } + public void SetScores(IScore[] scores) + { + this.m_Scores = scores; + } + public void SetTitle(string title) + { + this.m_Title = title; + } + public string[] GetUserFilter() + { + return this.m_UserIDs; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/LocalUser.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/LocalUser.cs new file mode 100644 index 00000000..2f2c2da2 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/LocalUser.cs @@ -0,0 +1,57 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class LocalUser : UserProfile, ILocalUser, IUserProfile + { + private IUserProfile[] m_Friends; + private bool m_Authenticated; + private bool m_Underage; + public IUserProfile[] friends + { + get + { + return this.m_Friends; + } + } + public bool authenticated + { + get + { + return this.m_Authenticated; + } + } + public bool underage + { + get + { + return this.m_Underage; + } + } + public LocalUser() + { + this.m_Friends = new UserProfile[0]; + this.m_Authenticated = false; + this.m_Underage = false; + } + public void Authenticate(Action callback) + { + ActivePlatform.Instance.Authenticate(this, callback); + } + public void LoadFriends(Action callback) + { + ActivePlatform.Instance.LoadFriends(this, callback); + } + public void SetFriends(IUserProfile[] friends) + { + this.m_Friends = friends; + } + public void SetAuthenticated(bool value) + { + this.m_Authenticated = value; + } + public void SetUnderage(bool value) + { + this.m_Underage = value; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/Score.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Score.cs new file mode 100644 index 00000000..8641de0e --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/Score.cs @@ -0,0 +1,100 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class Score : IScore + { + private DateTime m_Date; + private string m_FormattedValue; + private string m_UserID; + private int m_Rank; + public string leaderboardID + { + get; + set; + } + public long value + { + get; + set; + } + public DateTime date + { + get + { + return this.m_Date; + } + } + public string formattedValue + { + get + { + return this.m_FormattedValue; + } + } + public string userID + { + get + { + return this.m_UserID; + } + } + public int rank + { + get + { + return this.m_Rank; + } + } + public Score() : this("unkown", -1L) + { + } + public Score(string leaderboardID, long value) : this(leaderboardID, value, "0", DateTime.Now, string.Empty, -1) + { + } + public Score(string leaderboardID, long value, string userID, DateTime date, string formattedValue, int rank) + { + this.leaderboardID = leaderboardID; + this.value = value; + this.m_UserID = userID; + this.m_Date = date; + this.m_FormattedValue = formattedValue; + this.m_Rank = rank; + } + public override string ToString() + { + return string.Concat(new object[] + { + "Rank: '", + this.m_Rank, + "' Value: '", + this.value, + "' Category: '", + this.leaderboardID, + "' PlayerID: '", + this.m_UserID, + "' Date: '", + this.m_Date + }); + } + public void ReportScore(Action callback) + { + ActivePlatform.Instance.ReportScore(this.value, this.leaderboardID, callback); + } + public void SetDate(DateTime date) + { + this.m_Date = date; + } + public void SetFormattedValue(string value) + { + this.m_FormattedValue = value; + } + public void SetUserID(string userID) + { + this.m_UserID = userID; + } + public void SetRank(int rank) + { + this.m_Rank = rank; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms.Impl/UserProfile.cs b/UnityEngine/UnityEngine.SocialPlatforms.Impl/UserProfile.cs new file mode 100644 index 00000000..b5795839 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms.Impl/UserProfile.cs @@ -0,0 +1,99 @@ +using System; +namespace UnityEngine.SocialPlatforms.Impl +{ + public class UserProfile : IUserProfile + { + protected string m_UserName; + protected string m_ID; + protected bool m_IsFriend; + protected UserState m_State; + protected Texture2D m_Image; + public string userName + { + get + { + return this.m_UserName; + } + } + public string id + { + get + { + return this.m_ID; + } + } + public bool isFriend + { + get + { + return this.m_IsFriend; + } + } + public UserState state + { + get + { + return this.m_State; + } + } + public Texture2D image + { + get + { + return this.m_Image; + } + } + public UserProfile() + { + this.m_UserName = "Uninitialized"; + this.m_ID = "0"; + this.m_IsFriend = false; + this.m_State = UserState.Offline; + this.m_Image = new Texture2D(32, 32); + } + public UserProfile(string name, string id, bool friend) : this(name, id, friend, UserState.Offline, new Texture2D(0, 0)) + { + } + public UserProfile(string name, string id, bool friend, UserState state, Texture2D image) + { + this.m_UserName = name; + this.m_ID = id; + this.m_IsFriend = friend; + this.m_State = state; + this.m_Image = image; + } + public override string ToString() + { + return string.Concat(new object[] + { + this.id, + " - ", + this.userName, + " - ", + this.isFriend, + " - ", + this.state + }); + } + public void SetUserName(string name) + { + this.m_UserName = name; + } + public void SetUserID(string id) + { + this.m_ID = id; + } + public void SetImage(Texture2D image) + { + this.m_Image = image; + } + public void SetIsFriend(bool value) + { + this.m_IsFriend = value; + } + public void SetState(UserState state) + { + this.m_State = state; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/ActivePlatform.cs b/UnityEngine/UnityEngine.SocialPlatforms/ActivePlatform.cs new file mode 100644 index 00000000..efebca9f --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/ActivePlatform.cs @@ -0,0 +1,27 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + internal static class ActivePlatform + { + private static ISocialPlatform _active; + internal static ISocialPlatform Instance + { + get + { + if (ActivePlatform._active == null) + { + ActivePlatform._active = ActivePlatform.SelectSocialPlatform(); + } + return ActivePlatform._active; + } + set + { + ActivePlatform._active = value; + } + } + private static ISocialPlatform SelectSocialPlatform() + { + return new Local(); + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/IAchievement.cs b/UnityEngine/UnityEngine.SocialPlatforms/IAchievement.cs new file mode 100644 index 00000000..900805a7 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/IAchievement.cs @@ -0,0 +1,30 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface IAchievement + { + string id + { + get; + set; + } + double percentCompleted + { + get; + set; + } + bool completed + { + get; + } + bool hidden + { + get; + } + DateTime lastReportedDate + { + get; + } + void ReportProgress(Action callback); + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/IAchievementDescription.cs b/UnityEngine/UnityEngine.SocialPlatforms/IAchievementDescription.cs new file mode 100644 index 00000000..27c94d09 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/IAchievementDescription.cs @@ -0,0 +1,36 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface IAchievementDescription + { + string id + { + get; + set; + } + string title + { + get; + } + Texture2D image + { + get; + } + string achievedDescription + { + get; + } + string unachievedDescription + { + get; + } + bool hidden + { + get; + } + int points + { + get; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/ILeaderboard.cs b/UnityEngine/UnityEngine.SocialPlatforms/ILeaderboard.cs new file mode 100644 index 00000000..51018d4a --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/ILeaderboard.cs @@ -0,0 +1,49 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface ILeaderboard + { + bool loading + { + get; + } + string id + { + get; + set; + } + UserScope userScope + { + get; + set; + } + Range range + { + get; + set; + } + TimeScope timeScope + { + get; + set; + } + IScore localUserScore + { + get; + } + uint maxRange + { + get; + } + IScore[] scores + { + get; + } + string title + { + get; + } + void SetUserFilter(string[] userIDs); + void LoadScores(Action callback); + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/ILocalUser.cs b/UnityEngine/UnityEngine.SocialPlatforms/ILocalUser.cs new file mode 100644 index 00000000..2387684d --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/ILocalUser.cs @@ -0,0 +1,21 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface ILocalUser : IUserProfile + { + IUserProfile[] friends + { + get; + } + bool authenticated + { + get; + } + bool underage + { + get; + } + void Authenticate(Action callback); + void LoadFriends(Action callback); + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/IScore.cs b/UnityEngine/UnityEngine.SocialPlatforms/IScore.cs new file mode 100644 index 00000000..f423f2b5 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/IScore.cs @@ -0,0 +1,34 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface IScore + { + string leaderboardID + { + get; + set; + } + long value + { + get; + set; + } + DateTime date + { + get; + } + string formattedValue + { + get; + } + string userID + { + get; + } + int rank + { + get; + } + void ReportScore(Action callback); + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/ISocialPlatform.cs b/UnityEngine/UnityEngine.SocialPlatforms/ISocialPlatform.cs new file mode 100644 index 00000000..0b2932c5 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/ISocialPlatform.cs @@ -0,0 +1,25 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface ISocialPlatform + { + ILocalUser localUser + { + get; + } + void LoadUsers(string[] userIDs, Action callback); + void ReportProgress(string achievementID, double progress, Action callback); + void LoadAchievementDescriptions(Action callback); + void LoadAchievements(Action callback); + IAchievement CreateAchievement(); + void ReportScore(long score, string board, Action callback); + void LoadScores(string leaderboardID, Action callback); + ILeaderboard CreateLeaderboard(); + void ShowAchievementsUI(); + void ShowLeaderboardUI(); + void Authenticate(ILocalUser user, Action callback); + void LoadFriends(ILocalUser user, Action callback); + void LoadScores(ILeaderboard board, Action callback); + bool GetLoading(ILeaderboard board); + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/IUserProfile.cs b/UnityEngine/UnityEngine.SocialPlatforms/IUserProfile.cs new file mode 100644 index 00000000..d99cc4ac --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/IUserProfile.cs @@ -0,0 +1,27 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public interface IUserProfile + { + string userName + { + get; + } + string id + { + get; + } + bool isFriend + { + get; + } + UserState state + { + get; + } + Texture2D image + { + get; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/Local.cs b/UnityEngine/UnityEngine.SocialPlatforms/Local.cs new file mode 100644 index 00000000..8dd7330b --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/Local.cs @@ -0,0 +1,308 @@ +using System; +using System.Collections.Generic; +using UnityEngine.SocialPlatforms.Impl; +namespace UnityEngine.SocialPlatforms +{ + public class Local : ISocialPlatform + { + private static LocalUser m_LocalUser; + private List m_Friends = new List(); + private List m_Users = new List(); + private List m_AchievementDescriptions = new List(); + private List m_Achievements = new List(); + private List m_Leaderboards = new List(); + private Texture2D m_DefaultTexture; + public ILocalUser localUser + { + get + { + if (Local.m_LocalUser == null) + { + Local.m_LocalUser = new LocalUser(); + } + return Local.m_LocalUser; + } + } + void ISocialPlatform.Authenticate(ILocalUser user, Action callback) + { + LocalUser localUser = (LocalUser)user; + this.m_DefaultTexture = this.CreateDummyTexture(32, 32); + this.PopulateStaticData(); + localUser.SetAuthenticated(true); + localUser.SetUnderage(false); + localUser.SetUserID("1000"); + localUser.SetUserName("Lerpz"); + localUser.SetImage(this.m_DefaultTexture); + if (callback != null) + { + callback(true); + } + } + void ISocialPlatform.LoadFriends(ILocalUser user, Action callback) + { + if (!this.VerifyUser()) + { + return; + } + ((LocalUser)user).SetFriends(this.m_Friends.ToArray()); + if (callback != null) + { + callback(true); + } + } + void ISocialPlatform.LoadScores(ILeaderboard board, Action callback) + { + if (!this.VerifyUser()) + { + return; + } + Leaderboard leaderboard = (Leaderboard)board; + foreach (Leaderboard current in this.m_Leaderboards) + { + if (current.id == leaderboard.id) + { + leaderboard.SetTitle(current.title); + leaderboard.SetScores(current.scores); + leaderboard.SetMaxRange((uint)current.scores.Length); + } + } + this.SortScores(leaderboard); + this.SetLocalPlayerScore(leaderboard); + if (callback != null) + { + callback(true); + } + } + bool ISocialPlatform.GetLoading(ILeaderboard board) + { + return this.VerifyUser() && ((Leaderboard)board).loading; + } + public void LoadUsers(string[] userIDs, Action callback) + { + List list = new List(); + if (!this.VerifyUser()) + { + return; + } + for (int i = 0; i < userIDs.Length; i++) + { + string b = userIDs[i]; + foreach (UserProfile current in this.m_Users) + { + if (current.id == b) + { + list.Add(current); + } + } + foreach (UserProfile current2 in this.m_Friends) + { + if (current2.id == b) + { + list.Add(current2); + } + } + } + callback(list.ToArray()); + } + public void ReportProgress(string id, double progress, Action callback) + { + if (!this.VerifyUser()) + { + return; + } + foreach (Achievement current in this.m_Achievements) + { + if (current.id == id && current.percentCompleted <= progress) + { + if (progress >= 100.0) + { + current.SetCompleted(true); + } + current.SetHidden(false); + current.SetLastReportedDate(DateTime.Now); + current.percentCompleted = progress; + if (callback != null) + { + callback(true); + } + return; + } + } + foreach (AchievementDescription current2 in this.m_AchievementDescriptions) + { + if (current2.id == id) + { + bool completed = progress >= 100.0; + Achievement item = new Achievement(id, progress, completed, false, DateTime.Now); + this.m_Achievements.Add(item); + if (callback != null) + { + callback(true); + } + return; + } + } + Debug.LogError("Achievement ID not found"); + if (callback != null) + { + callback(false); + } + } + public void LoadAchievementDescriptions(Action callback) + { + if (!this.VerifyUser()) + { + return; + } + if (callback != null) + { + callback(this.m_AchievementDescriptions.ToArray()); + } + } + public void LoadAchievements(Action callback) + { + if (!this.VerifyUser()) + { + return; + } + if (callback != null) + { + callback(this.m_Achievements.ToArray()); + } + } + public void ReportScore(long score, string board, Action callback) + { + if (!this.VerifyUser()) + { + return; + } + foreach (Leaderboard current in this.m_Leaderboards) + { + if (current.id == board) + { + current.SetScores(new List((Score[])current.scores) + { + new Score(board, score, this.localUser.id, DateTime.Now, score + " points", 0) + }.ToArray()); + if (callback != null) + { + callback(true); + } + return; + } + } + Debug.LogError("Leaderboard not found"); + if (callback != null) + { + callback(false); + } + } + public void LoadScores(string leaderboardID, Action callback) + { + if (!this.VerifyUser()) + { + return; + } + foreach (Leaderboard current in this.m_Leaderboards) + { + if (current.id == leaderboardID) + { + this.SortScores(current); + if (callback != null) + { + callback(current.scores); + } + return; + } + } + Debug.LogError("Leaderboard not found"); + if (callback != null) + { + callback(new Score[0]); + } + } + private void SortScores(Leaderboard board) + { + List list = new List((Score[])board.scores); + list.Sort((Score s1, Score s2) => s2.value.CompareTo(s1.value)); + for (int i = 0; i < list.Count; i++) + { + list[i].SetRank(i + 1); + } + } + private void SetLocalPlayerScore(Leaderboard board) + { + IScore[] scores = board.scores; + for (int i = 0; i < scores.Length; i++) + { + Score score = (Score)scores[i]; + if (score.userID == this.localUser.id) + { + board.SetLocalUserScore(score); + break; + } + } + } + public void ShowAchievementsUI() + { + Debug.Log("ShowAchievementsUI not implemented"); + } + public void ShowLeaderboardUI() + { + Debug.Log("ShowLeaderboardUI not implemented"); + } + public ILeaderboard CreateLeaderboard() + { + return new Leaderboard(); + } + public IAchievement CreateAchievement() + { + return new Achievement(); + } + private bool VerifyUser() + { + if (!this.localUser.authenticated) + { + Debug.LogError("Must authenticate first"); + return false; + } + return true; + } + private void PopulateStaticData() + { + this.m_Friends.Add(new UserProfile("Fred", "1001", true, UserState.Online, this.m_DefaultTexture)); + this.m_Friends.Add(new UserProfile("Julia", "1002", true, UserState.Online, this.m_DefaultTexture)); + this.m_Friends.Add(new UserProfile("Jeff", "1003", true, UserState.Online, this.m_DefaultTexture)); + this.m_Users.Add(new UserProfile("Sam", "1004", false, UserState.Offline, this.m_DefaultTexture)); + this.m_Users.Add(new UserProfile("Max", "1005", false, UserState.Offline, this.m_DefaultTexture)); + this.m_AchievementDescriptions.Add(new AchievementDescription("Achievement01", "First achievement", this.m_DefaultTexture, "Get first achievement", "Received first achievement", false, 10)); + this.m_AchievementDescriptions.Add(new AchievementDescription("Achievement02", "Second achievement", this.m_DefaultTexture, "Get second achievement", "Received second achievement", false, 20)); + this.m_AchievementDescriptions.Add(new AchievementDescription("Achievement03", "Third achievement", this.m_DefaultTexture, "Get third achievement", "Received third achievement", false, 15)); + Leaderboard leaderboard = new Leaderboard(); + leaderboard.SetTitle("High Scores"); + leaderboard.id = "Leaderboard01"; + leaderboard.SetScores(new List + { + new Score("Leaderboard01", 300L, "1001", DateTime.Now.AddDays(-1.0), "300 points", 1), + new Score("Leaderboard01", 255L, "1002", DateTime.Now.AddDays(-1.0), "255 points", 2), + new Score("Leaderboard01", 55L, "1003", DateTime.Now.AddDays(-1.0), "55 points", 3), + new Score("Leaderboard01", 10L, "1004", DateTime.Now.AddDays(-1.0), "10 points", 4) + }.ToArray()); + this.m_Leaderboards.Add(leaderboard); + } + private Texture2D CreateDummyTexture(int width, int height) + { + Texture2D texture2D = new Texture2D(width, height); + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width; j++) + { + Color color = ((j & i) <= 0) ? Color.gray : Color.white; + texture2D.SetPixel(j, i, color); + } + } + texture2D.Apply(); + return texture2D; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/Range.cs b/UnityEngine/UnityEngine.SocialPlatforms/Range.cs new file mode 100644 index 00000000..83ebceea --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/Range.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public struct Range + { + public int from; + public int count; + public Range(int fromValue, int valueCount) + { + this.from = fromValue; + this.count = valueCount; + } + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/TimeScope.cs b/UnityEngine/UnityEngine.SocialPlatforms/TimeScope.cs new file mode 100644 index 00000000..383e07ad --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/TimeScope.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public enum TimeScope + { + Today, + Week, + AllTime + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/UserScope.cs b/UnityEngine/UnityEngine.SocialPlatforms/UserScope.cs new file mode 100644 index 00000000..28c71df5 --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/UserScope.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public enum UserScope + { + Global, + FriendsOnly + } +} diff --git a/UnityEngine/UnityEngine.SocialPlatforms/UserState.cs b/UnityEngine/UnityEngine.SocialPlatforms/UserState.cs new file mode 100644 index 00000000..cfbd466a --- /dev/null +++ b/UnityEngine/UnityEngine.SocialPlatforms/UserState.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine.SocialPlatforms +{ + public enum UserState + { + Online, + OnlineAndAway, + OnlineAndBusy, + Offline, + Playing + } +} diff --git a/UnityEngine/UnityEngine.Sprites/DataUtility.cs b/UnityEngine/UnityEngine.Sprites/DataUtility.cs new file mode 100644 index 00000000..0efe4fe8 --- /dev/null +++ b/UnityEngine/UnityEngine.Sprites/DataUtility.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.Sprites +{ + public sealed class DataUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetInnerUV(Sprite sprite); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetOuterUV(Sprite sprite); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetPadding(Sprite sprite); + public static Vector2 GetMinSize(Sprite sprite) + { + Vector2 result; + DataUtility.Internal_GetMinSize(sprite, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetMinSize(Sprite sprite, out Vector2 output); + } +} diff --git a/UnityEngine/UnityEngine.csproj b/UnityEngine/UnityEngine.csproj new file mode 100644 index 00000000..373dd3a0 --- /dev/null +++ b/UnityEngine/UnityEngine.csproj @@ -0,0 +1,611 @@ + + + + {731BEF47-7B99-4BB3-86B7-595906204083} + Debug + AnyCPU + Library + UnityEngine + v4.0 + 4 + + + + AnyCPU + + + bin\Debug\ + true + full + false + + + bin\Release\ + true + pdbonly + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/UnityEngine/UnityEngine/ADBannerView.cs b/UnityEngine/UnityEngine/ADBannerView.cs new file mode 100644 index 00000000..074e6c1b --- /dev/null +++ b/UnityEngine/UnityEngine/ADBannerView.cs @@ -0,0 +1,181 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ADBannerView + { + public enum Layout + { + Top, + Bottom, + TopLeft = 0, + TopRight = 4, + TopCenter = 8, + BottomLeft = 1, + BottomRight = 5, + BottomCenter = 9, + CenterLeft = 2, + CenterRight = 6, + Center = 10, + Manual = -1 + } + public enum Type + { + Banner, + MediumRect + } + public delegate void BannerWasClickedDelegate(); + public delegate void BannerWasLoadedDelegate(); + private ADBannerView.Layout _layout; + private IntPtr _bannerView; + private static bool _AlwaysFalseDummy; + public static event ADBannerView.BannerWasClickedDelegate onBannerWasClicked + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Combine(ADBannerView.onBannerWasClicked, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Remove(ADBannerView.onBannerWasClicked, value); + } + } + public static event ADBannerView.BannerWasLoadedDelegate onBannerWasLoaded + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Combine(ADBannerView.onBannerWasLoaded, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Remove(ADBannerView.onBannerWasLoaded, value); + } + } + public bool loaded + { + get + { + return ADBannerView.Native_BannerAdLoaded(this._bannerView); + } + } + public bool visible + { + get + { + return ADBannerView.Native_BannerAdVisible(this._bannerView); + } + set + { + ADBannerView.Native_ShowBanner(this._bannerView, value); + } + } + public ADBannerView.Layout layout + { + get + { + return this._layout; + } + set + { + this._layout = value; + ADBannerView.Native_LayoutBanner(this._bannerView, (int)this._layout); + } + } + public Vector2 position + { + get + { + Vector2 v; + ADBannerView.Native_BannerPosition(this._bannerView, out v); + return this.OSToScreenCoords(v); + } + set + { + Vector2 pos = new Vector2(value.x / (float)Screen.width, value.y / (float)Screen.height); + ADBannerView.Native_MoveBanner(this._bannerView, pos); + } + } + public Vector2 size + { + get + { + Vector2 v; + ADBannerView.Native_BannerSize(this._bannerView, out v); + return this.OSToScreenCoords(v); + } + } + public ADBannerView(ADBannerView.Type type, ADBannerView.Layout layout) + { + if (ADBannerView._AlwaysFalseDummy) + { + ADBannerView.FireBannerWasClicked(); + ADBannerView.FireBannerWasLoaded(); + } + this._bannerView = ADBannerView.Native_CreateBanner((int)type, (int)layout); + } + public static bool IsAvailable(ADBannerView.Type type) + { + return ADBannerView.Native_BannerTypeAvailable((int)type); + } + ~ADBannerView() + { + ADBannerView.Native_DestroyBanner(this._bannerView); + } + private Vector2 OSToScreenCoords(Vector2 v) + { + return new Vector2(v.x * (float)Screen.width, v.y * (float)Screen.height); + } + private static void FireBannerWasClicked() + { + if (ADBannerView.onBannerWasClicked != null) + { + ADBannerView.onBannerWasClicked(); + } + } + private static void FireBannerWasLoaded() + { + if (ADBannerView.onBannerWasLoaded != null) + { + ADBannerView.onBannerWasLoaded(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr Native_CreateBanner(int type, int layout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ShowBanner(IntPtr view, bool show); + private static void Native_MoveBanner(IntPtr view, Vector2 pos) + { + ADBannerView.INTERNAL_CALL_Native_MoveBanner(view, ref pos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Native_MoveBanner(IntPtr view, ref Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_LayoutBanner(IntPtr view, int layout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerTypeAvailable(int type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_BannerPosition(IntPtr view, out Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_BannerSize(IntPtr view, out Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerAdLoaded(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerAdVisible(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_DestroyBanner(IntPtr view); + } +} diff --git a/UnityEngine/UnityEngine/ADInterstitialAd.cs b/UnityEngine/UnityEngine/ADInterstitialAd.cs new file mode 100644 index 00000000..d5b0e6e2 --- /dev/null +++ b/UnityEngine/UnityEngine/ADInterstitialAd.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ADInterstitialAd + { + public delegate void InterstitialWasLoadedDelegate(); + private IntPtr interstitialView; + private static bool _AlwaysFalseDummy; + public static event ADInterstitialAd.InterstitialWasLoadedDelegate onInterstitialWasLoaded + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Combine(ADInterstitialAd.onInterstitialWasLoaded, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Remove(ADInterstitialAd.onInterstitialWasLoaded, value); + } + } + public static bool isAvailable + { + get + { + return ADInterstitialAd.Native_InterstitialAvailable(); + } + } + public bool loaded + { + get + { + return ADInterstitialAd.Native_InterstitialAdLoaded(this.interstitialView); + } + } + public ADInterstitialAd(bool autoReload) + { + this.CtorImpl(autoReload); + } + public ADInterstitialAd() + { + this.CtorImpl(false); + } + private void CtorImpl(bool autoReload) + { + if (ADInterstitialAd._AlwaysFalseDummy) + { + ADInterstitialAd.FireInterstitialWasLoaded(); + } + this.interstitialView = ADInterstitialAd.Native_CreateInterstitial(autoReload); + } + ~ADInterstitialAd() + { + ADInterstitialAd.Native_DestroyInterstitial(this.interstitialView); + } + public void Show() + { + if (this.loaded) + { + ADInterstitialAd.Native_ShowInterstitial(this.interstitialView); + } + else + { + Debug.Log("Calling ADInterstitialAd.Show() when the ad is not loaded"); + } + } + public void ReloadAd() + { + ADInterstitialAd.Native_ReloadInterstitial(this.interstitialView); + } + private static void FireInterstitialWasLoaded() + { + if (ADInterstitialAd.onInterstitialWasLoaded != null) + { + ADInterstitialAd.onInterstitialWasLoaded(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr Native_CreateInterstitial(bool autoReload); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ShowInterstitial(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ReloadInterstitial(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_InterstitialAdLoaded(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_InterstitialAvailable(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_DestroyInterstitial(IntPtr view); + } +} diff --git a/UnityEngine/UnityEngine/AccelerationEvent.cs b/UnityEngine/UnityEngine/AccelerationEvent.cs new file mode 100644 index 00000000..98ca4619 --- /dev/null +++ b/UnityEngine/UnityEngine/AccelerationEvent.cs @@ -0,0 +1,23 @@ +using System; +namespace UnityEngine +{ + public struct AccelerationEvent + { + private Vector3 m_Acceleration; + private float m_TimeDelta; + public Vector3 acceleration + { + get + { + return this.m_Acceleration; + } + } + public float deltaTime + { + get + { + return this.m_TimeDelta; + } + } + } +} diff --git a/UnityEngine/UnityEngine/AddComponentMenu.cs b/UnityEngine/UnityEngine/AddComponentMenu.cs new file mode 100644 index 00000000..f47c98c0 --- /dev/null +++ b/UnityEngine/UnityEngine/AddComponentMenu.cs @@ -0,0 +1,33 @@ +using System; +namespace UnityEngine +{ + public sealed class AddComponentMenu : Attribute + { + private string m_AddComponentMenu; + private int m_Ordering; + public string componentMenu + { + get + { + return this.m_AddComponentMenu; + } + } + public int componentOrder + { + get + { + return this.m_Ordering; + } + } + public AddComponentMenu(string menuName) + { + this.m_AddComponentMenu = menuName; + this.m_Ordering = 0; + } + public AddComponentMenu(string menuName, int order) + { + this.m_AddComponentMenu = menuName; + this.m_Ordering = order; + } + } +} diff --git a/UnityEngine/UnityEngine/AnchoredJoint2D.cs b/UnityEngine/UnityEngine/AnchoredJoint2D.cs new file mode 100644 index 00000000..1c6a3f1b --- /dev/null +++ b/UnityEngine/UnityEngine/AnchoredJoint2D.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class AnchoredJoint2D : Joint2D + { + public Vector2 anchor + { + get + { + Vector2 result; + this.INTERNAL_get_anchor(out result); + return result; + } + set + { + this.INTERNAL_set_anchor(ref value); + } + } + public Vector2 connectedAnchor + { + get + { + Vector2 result; + this.INTERNAL_get_connectedAnchor(out result); + return result; + } + set + { + this.INTERNAL_set_connectedAnchor(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anchor(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anchor(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_connectedAnchor(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_connectedAnchor(ref Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/AndroidActivityIndicatorStyle.cs b/UnityEngine/UnityEngine/AndroidActivityIndicatorStyle.cs new file mode 100644 index 00000000..3cf1cd70 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidActivityIndicatorStyle.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum AndroidActivityIndicatorStyle + { + DontShow = -1, + Large, + InversedLarge, + Small, + InversedSmall + } +} diff --git a/UnityEngine/UnityEngine/AndroidInput.cs b/UnityEngine/UnityEngine/AndroidInput.cs new file mode 100644 index 00000000..0394da33 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidInput.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AndroidInput + { + public static extern int touchCountSecondary + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool secondaryTouchEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int secondaryTouchWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int secondaryTouchHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private AndroidInput() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Touch GetSecondaryTouch(int index); + } +} diff --git a/UnityEngine/UnityEngine/AndroidJNI.cs b/UnityEngine/UnityEngine/AndroidJNI.cs new file mode 100644 index 00000000..4df17943 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJNI.cs @@ -0,0 +1,444 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AndroidJNI + { + private AndroidJNI() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int AttachCurrentThread(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int DetachCurrentThread(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetVersion(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr FindClass(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr FromReflectedMethod(IntPtr refMethod); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr FromReflectedField(IntPtr refField); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToReflectedMethod(IntPtr clazz, IntPtr methodID, bool isStatic); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToReflectedField(IntPtr clazz, IntPtr fieldID, bool isStatic); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetSuperclass(IntPtr clazz); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsAssignableFrom(IntPtr clazz1, IntPtr clazz2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int Throw(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int ThrowNew(IntPtr clazz, string message); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ExceptionOccurred(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExceptionDescribe(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExceptionClear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FatalError(string message); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int PushLocalFrame(int capacity); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr PopLocalFrame(IntPtr result); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewGlobalRef(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteGlobalRef(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewLocalRef(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteLocalRef(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsSameObject(IntPtr obj1, IntPtr obj2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int EnsureLocalCapacity(int capacity); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr AllocObject(IntPtr clazz); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewObject(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetObjectClass(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsInstanceOf(IntPtr obj, IntPtr clazz); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetMethodID(IntPtr clazz, string name, string sig); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetFieldID(IntPtr clazz, string name, string sig); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetStaticMethodID(IntPtr clazz, string name, string sig); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetStaticFieldID(IntPtr clazz, string name, string sig); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewStringUTF(string bytes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStringUTFLength(IntPtr str); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetStringUTFChars(IntPtr str); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CallStringMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr CallObjectMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CallIntMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CallBooleanMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short CallShortMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte CallByteMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char CallCharMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float CallFloatMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double CallDoubleMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long CallLongMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CallVoidMethod(IntPtr obj, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetStringField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetObjectField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetBooleanField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte GetByteField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char GetCharField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short GetShortField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetIntField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long GetLongField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetFloatField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double GetDoubleField(IntPtr obj, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStringField(IntPtr obj, IntPtr fieldID, string val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetObjectField(IntPtr obj, IntPtr fieldID, IntPtr val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetBooleanField(IntPtr obj, IntPtr fieldID, bool val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetByteField(IntPtr obj, IntPtr fieldID, byte val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetCharField(IntPtr obj, IntPtr fieldID, char val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetShortField(IntPtr obj, IntPtr fieldID, short val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetIntField(IntPtr obj, IntPtr fieldID, int val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLongField(IntPtr obj, IntPtr fieldID, long val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetFloatField(IntPtr obj, IntPtr fieldID, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDoubleField(IntPtr obj, IntPtr fieldID, double val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string CallStaticStringMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr CallStaticObjectMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CallStaticIntMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CallStaticBooleanMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short CallStaticShortMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte CallStaticByteMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char CallStaticCharMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float CallStaticFloatMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double CallStaticDoubleMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long CallStaticLongMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CallStaticVoidMethod(IntPtr clazz, IntPtr methodID, jvalue[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetStaticStringField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetStaticObjectField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetStaticBooleanField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte GetStaticByteField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char GetStaticCharField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short GetStaticShortField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetStaticIntField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long GetStaticLongField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetStaticFloatField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double GetStaticDoubleField(IntPtr clazz, IntPtr fieldID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticStringField(IntPtr clazz, IntPtr fieldID, string val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticObjectField(IntPtr clazz, IntPtr fieldID, IntPtr val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticBooleanField(IntPtr clazz, IntPtr fieldID, bool val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticByteField(IntPtr clazz, IntPtr fieldID, byte val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticCharField(IntPtr clazz, IntPtr fieldID, char val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticShortField(IntPtr clazz, IntPtr fieldID, short val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticIntField(IntPtr clazz, IntPtr fieldID, int val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticLongField(IntPtr clazz, IntPtr fieldID, long val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticFloatField(IntPtr clazz, IntPtr fieldID, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticDoubleField(IntPtr clazz, IntPtr fieldID, double val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToBooleanArray(bool[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToByteArray(byte[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToCharArray(char[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToShortArray(short[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToIntArray(int[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToLongArray(long[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToFloatArray(float[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToDoubleArray(double[] array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr ToObjectArray(IntPtr[] array, IntPtr arrayClass); + public static IntPtr ToObjectArray(IntPtr[] array) + { + return AndroidJNI.ToObjectArray(array, IntPtr.Zero); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool[] FromBooleanArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte[] FromByteArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char[] FromCharArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short[] FromShortArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int[] FromIntArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long[] FromLongArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float[] FromFloatArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double[] FromDoubleArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr[] FromObjectArray(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetArrayLength(IntPtr array); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewBooleanArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewByteArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewCharArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewShortArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewIntArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewLongArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewFloatArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewDoubleArray(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr NewObjectArray(int size, IntPtr clazz, IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetBooleanArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern byte GetByteArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern char GetCharArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern short GetShortArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetIntArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern long GetLongArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetFloatArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern double GetDoubleArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetObjectArrayElement(IntPtr array, int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetBooleanArrayElement(IntPtr array, int index, byte val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetByteArrayElement(IntPtr array, int index, sbyte val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetCharArrayElement(IntPtr array, int index, char val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetShortArrayElement(IntPtr array, int index, short val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetIntArrayElement(IntPtr array, int index, int val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLongArrayElement(IntPtr array, int index, long val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetFloatArrayElement(IntPtr array, int index, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDoubleArrayElement(IntPtr array, int index, double val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetObjectArrayElement(IntPtr array, int index, IntPtr obj); + } +} diff --git a/UnityEngine/UnityEngine/AndroidJNIHelper.cs b/UnityEngine/UnityEngine/AndroidJNIHelper.cs new file mode 100644 index 00000000..0d8fc40d --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJNIHelper.cs @@ -0,0 +1,116 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class AndroidJNIHelper + { + public static extern bool debug + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + private AndroidJNIHelper() + { + } + [ExcludeFromDocs] + public static IntPtr GetConstructorID(IntPtr javaClass) + { + string empty = string.Empty; + return AndroidJNIHelper.GetConstructorID(javaClass, empty); + } + public static IntPtr GetConstructorID(IntPtr javaClass, [DefaultValue("\"\"")] string signature) + { + return _AndroidJNIHelper.GetConstructorID(javaClass, signature); + } + [ExcludeFromDocs] + public static IntPtr GetMethodID(IntPtr javaClass, string methodName, string signature) + { + bool isStatic = false; + return AndroidJNIHelper.GetMethodID(javaClass, methodName, signature, isStatic); + } + [ExcludeFromDocs] + public static IntPtr GetMethodID(IntPtr javaClass, string methodName) + { + bool isStatic = false; + string empty = string.Empty; + return AndroidJNIHelper.GetMethodID(javaClass, methodName, empty, isStatic); + } + public static IntPtr GetMethodID(IntPtr javaClass, string methodName, [DefaultValue("\"\"")] string signature, [DefaultValue("false")] bool isStatic) + { + return _AndroidJNIHelper.GetMethodID(javaClass, methodName, signature, isStatic); + } + [ExcludeFromDocs] + public static IntPtr GetFieldID(IntPtr javaClass, string fieldName, string signature) + { + bool isStatic = false; + return AndroidJNIHelper.GetFieldID(javaClass, fieldName, signature, isStatic); + } + [ExcludeFromDocs] + public static IntPtr GetFieldID(IntPtr javaClass, string fieldName) + { + bool isStatic = false; + string empty = string.Empty; + return AndroidJNIHelper.GetFieldID(javaClass, fieldName, empty, isStatic); + } + public static IntPtr GetFieldID(IntPtr javaClass, string fieldName, [DefaultValue("\"\"")] string signature, [DefaultValue("false")] bool isStatic) + { + return _AndroidJNIHelper.GetFieldID(javaClass, fieldName, signature, isStatic); + } + public static IntPtr CreateJavaRunnable(AndroidJavaRunnable jrunnable) + { + return _AndroidJNIHelper.CreateJavaRunnable(jrunnable); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr CreateJavaProxy(AndroidJavaProxy proxy); + public static IntPtr ConvertToJNIArray(Array array) + { + return _AndroidJNIHelper.ConvertToJNIArray(array); + } + public static jvalue[] CreateJNIArgArray(object[] args) + { + return _AndroidJNIHelper.CreateJNIArgArray(args); + } + public static void DeleteJNIArgArray(object[] args, jvalue[] jniArgs) + { + _AndroidJNIHelper.DeleteJNIArgArray(args, jniArgs); + } + public static IntPtr GetConstructorID(IntPtr jclass, object[] args) + { + return _AndroidJNIHelper.GetConstructorID(jclass, args); + } + public static IntPtr GetMethodID(IntPtr jclass, string methodName, object[] args, bool isStatic) + { + return _AndroidJNIHelper.GetMethodID(jclass, methodName, args, isStatic); + } + public static string GetSignature(object obj) + { + return _AndroidJNIHelper.GetSignature(obj); + } + public static string GetSignature(object[] args) + { + return _AndroidJNIHelper.GetSignature(args); + } + public static ArrayType ConvertFromJNIArray(IntPtr array) + { + return _AndroidJNIHelper.ConvertFromJNIArray(array); + } + public static IntPtr GetMethodID(IntPtr jclass, string methodName, object[] args, bool isStatic) + { + return _AndroidJNIHelper.GetMethodID(jclass, methodName, args, isStatic); + } + public static IntPtr GetFieldID(IntPtr jclass, string fieldName, bool isStatic) + { + return _AndroidJNIHelper.GetFieldID(jclass, fieldName, isStatic); + } + public static string GetSignature(object[] args) + { + return _AndroidJNIHelper.GetSignature(args); + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJNISafe.cs b/UnityEngine/UnityEngine/AndroidJNISafe.cs new file mode 100644 index 00000000..051442d6 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJNISafe.cs @@ -0,0 +1,1218 @@ +using System; +namespace UnityEngine +{ + internal class AndroidJNISafe + { + public static void CheckException() + { + IntPtr intPtr = AndroidJNI.ExceptionOccurred(); + if (intPtr != IntPtr.Zero) + { + AndroidJNI.ExceptionClear(); + IntPtr intPtr2 = AndroidJNI.FindClass("java/lang/Throwable"); + try + { + IntPtr methodID = AndroidJNI.GetMethodID(intPtr2, "toString", "()Ljava/lang/String;"); + throw new AndroidJavaException(AndroidJNI.CallStringMethod(intPtr, methodID, new jvalue[0])); + } + finally + { + AndroidJNISafe.DeleteLocalRef(intPtr); + AndroidJNISafe.DeleteLocalRef(intPtr2); + } + } + } + public static void DeleteGlobalRef(IntPtr globalref) + { + if (globalref != IntPtr.Zero) + { + AndroidJNI.DeleteGlobalRef(globalref); + } + } + public static void DeleteLocalRef(IntPtr localref) + { + if (localref != IntPtr.Zero) + { + AndroidJNI.DeleteLocalRef(localref); + } + } + public static IntPtr NewStringUTF(string bytes) + { + IntPtr result; + try + { + result = AndroidJNI.NewStringUTF(bytes); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static string GetStringUTFChars(IntPtr str) + { + string stringUTFChars; + try + { + stringUTFChars = AndroidJNI.GetStringUTFChars(str); + } + finally + { + AndroidJNISafe.CheckException(); + } + return stringUTFChars; + } + public static IntPtr GetObjectClass(IntPtr ptr) + { + IntPtr objectClass; + try + { + objectClass = AndroidJNI.GetObjectClass(ptr); + } + finally + { + AndroidJNISafe.CheckException(); + } + return objectClass; + } + public static IntPtr GetStaticMethodID(IntPtr clazz, string name, string sig) + { + IntPtr staticMethodID; + try + { + staticMethodID = AndroidJNI.GetStaticMethodID(clazz, name, sig); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticMethodID; + } + public static IntPtr GetMethodID(IntPtr obj, string name, string sig) + { + IntPtr methodID; + try + { + methodID = AndroidJNI.GetMethodID(obj, name, sig); + } + finally + { + AndroidJNISafe.CheckException(); + } + return methodID; + } + public static IntPtr GetFieldID(IntPtr clazz, string name, string sig) + { + IntPtr fieldID; + try + { + fieldID = AndroidJNI.GetFieldID(clazz, name, sig); + } + finally + { + AndroidJNISafe.CheckException(); + } + return fieldID; + } + public static IntPtr GetStaticFieldID(IntPtr clazz, string name, string sig) + { + IntPtr staticFieldID; + try + { + staticFieldID = AndroidJNI.GetStaticFieldID(clazz, name, sig); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticFieldID; + } + public static IntPtr FromReflectedMethod(IntPtr refMethod) + { + IntPtr result; + try + { + result = AndroidJNI.FromReflectedMethod(refMethod); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr FromReflectedField(IntPtr refField) + { + IntPtr result; + try + { + result = AndroidJNI.FromReflectedField(refField); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr FindClass(string name) + { + IntPtr result; + try + { + result = AndroidJNI.FindClass(name); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr NewObject(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + IntPtr result; + try + { + result = AndroidJNI.NewObject(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static void SetStaticObjectField(IntPtr clazz, IntPtr fieldID, IntPtr val) + { + try + { + AndroidJNI.SetStaticObjectField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticStringField(IntPtr clazz, IntPtr fieldID, string val) + { + try + { + AndroidJNI.SetStaticStringField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticCharField(IntPtr clazz, IntPtr fieldID, char val) + { + try + { + AndroidJNI.SetStaticCharField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticDoubleField(IntPtr clazz, IntPtr fieldID, double val) + { + try + { + AndroidJNI.SetStaticDoubleField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticFloatField(IntPtr clazz, IntPtr fieldID, float val) + { + try + { + AndroidJNI.SetStaticFloatField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticLongField(IntPtr clazz, IntPtr fieldID, long val) + { + try + { + AndroidJNI.SetStaticLongField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticShortField(IntPtr clazz, IntPtr fieldID, short val) + { + try + { + AndroidJNI.SetStaticShortField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticByteField(IntPtr clazz, IntPtr fieldID, byte val) + { + try + { + AndroidJNI.SetStaticByteField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticBooleanField(IntPtr clazz, IntPtr fieldID, bool val) + { + try + { + AndroidJNI.SetStaticBooleanField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStaticIntField(IntPtr clazz, IntPtr fieldID, int val) + { + try + { + AndroidJNI.SetStaticIntField(clazz, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static IntPtr GetStaticObjectField(IntPtr clazz, IntPtr fieldID) + { + IntPtr staticObjectField; + try + { + staticObjectField = AndroidJNI.GetStaticObjectField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticObjectField; + } + public static string GetStaticStringField(IntPtr clazz, IntPtr fieldID) + { + string staticStringField; + try + { + staticStringField = AndroidJNI.GetStaticStringField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticStringField; + } + public static char GetStaticCharField(IntPtr clazz, IntPtr fieldID) + { + char staticCharField; + try + { + staticCharField = AndroidJNI.GetStaticCharField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticCharField; + } + public static double GetStaticDoubleField(IntPtr clazz, IntPtr fieldID) + { + double staticDoubleField; + try + { + staticDoubleField = AndroidJNI.GetStaticDoubleField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticDoubleField; + } + public static float GetStaticFloatField(IntPtr clazz, IntPtr fieldID) + { + float staticFloatField; + try + { + staticFloatField = AndroidJNI.GetStaticFloatField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticFloatField; + } + public static long GetStaticLongField(IntPtr clazz, IntPtr fieldID) + { + long staticLongField; + try + { + staticLongField = AndroidJNI.GetStaticLongField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticLongField; + } + public static short GetStaticShortField(IntPtr clazz, IntPtr fieldID) + { + short staticShortField; + try + { + staticShortField = AndroidJNI.GetStaticShortField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticShortField; + } + public static byte GetStaticByteField(IntPtr clazz, IntPtr fieldID) + { + byte staticByteField; + try + { + staticByteField = AndroidJNI.GetStaticByteField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticByteField; + } + public static bool GetStaticBooleanField(IntPtr clazz, IntPtr fieldID) + { + bool staticBooleanField; + try + { + staticBooleanField = AndroidJNI.GetStaticBooleanField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticBooleanField; + } + public static int GetStaticIntField(IntPtr clazz, IntPtr fieldID) + { + int staticIntField; + try + { + staticIntField = AndroidJNI.GetStaticIntField(clazz, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return staticIntField; + } + public static void CallStaticVoidMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + try + { + AndroidJNI.CallStaticVoidMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static IntPtr CallStaticObjectMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + IntPtr result; + try + { + result = AndroidJNI.CallStaticObjectMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static string CallStaticStringMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + string result; + try + { + result = AndroidJNI.CallStaticStringMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static char CallStaticCharMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + char result; + try + { + result = AndroidJNI.CallStaticCharMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static double CallStaticDoubleMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + double result; + try + { + result = AndroidJNI.CallStaticDoubleMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static float CallStaticFloatMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + float result; + try + { + result = AndroidJNI.CallStaticFloatMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static long CallStaticLongMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + long result; + try + { + result = AndroidJNI.CallStaticLongMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static short CallStaticShortMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + short result; + try + { + result = AndroidJNI.CallStaticShortMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static byte CallStaticByteMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + byte result; + try + { + result = AndroidJNI.CallStaticByteMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static bool CallStaticBooleanMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + bool result; + try + { + result = AndroidJNI.CallStaticBooleanMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static int CallStaticIntMethod(IntPtr clazz, IntPtr methodID, jvalue[] args) + { + int result; + try + { + result = AndroidJNI.CallStaticIntMethod(clazz, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static void SetObjectField(IntPtr obj, IntPtr fieldID, IntPtr val) + { + try + { + AndroidJNI.SetObjectField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetStringField(IntPtr obj, IntPtr fieldID, string val) + { + try + { + AndroidJNI.SetStringField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetCharField(IntPtr obj, IntPtr fieldID, char val) + { + try + { + AndroidJNI.SetCharField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetDoubleField(IntPtr obj, IntPtr fieldID, double val) + { + try + { + AndroidJNI.SetDoubleField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetFloatField(IntPtr obj, IntPtr fieldID, float val) + { + try + { + AndroidJNI.SetFloatField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetLongField(IntPtr obj, IntPtr fieldID, long val) + { + try + { + AndroidJNI.SetLongField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetShortField(IntPtr obj, IntPtr fieldID, short val) + { + try + { + AndroidJNI.SetShortField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetByteField(IntPtr obj, IntPtr fieldID, byte val) + { + try + { + AndroidJNI.SetByteField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetBooleanField(IntPtr obj, IntPtr fieldID, bool val) + { + try + { + AndroidJNI.SetBooleanField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static void SetIntField(IntPtr obj, IntPtr fieldID, int val) + { + try + { + AndroidJNI.SetIntField(obj, fieldID, val); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static IntPtr GetObjectField(IntPtr obj, IntPtr fieldID) + { + IntPtr objectField; + try + { + objectField = AndroidJNI.GetObjectField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return objectField; + } + public static string GetStringField(IntPtr obj, IntPtr fieldID) + { + string stringField; + try + { + stringField = AndroidJNI.GetStringField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return stringField; + } + public static char GetCharField(IntPtr obj, IntPtr fieldID) + { + char charField; + try + { + charField = AndroidJNI.GetCharField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return charField; + } + public static double GetDoubleField(IntPtr obj, IntPtr fieldID) + { + double doubleField; + try + { + doubleField = AndroidJNI.GetDoubleField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return doubleField; + } + public static float GetFloatField(IntPtr obj, IntPtr fieldID) + { + float floatField; + try + { + floatField = AndroidJNI.GetFloatField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return floatField; + } + public static long GetLongField(IntPtr obj, IntPtr fieldID) + { + long longField; + try + { + longField = AndroidJNI.GetLongField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return longField; + } + public static short GetShortField(IntPtr obj, IntPtr fieldID) + { + short shortField; + try + { + shortField = AndroidJNI.GetShortField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return shortField; + } + public static byte GetByteField(IntPtr obj, IntPtr fieldID) + { + byte byteField; + try + { + byteField = AndroidJNI.GetByteField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return byteField; + } + public static bool GetBooleanField(IntPtr obj, IntPtr fieldID) + { + bool booleanField; + try + { + booleanField = AndroidJNI.GetBooleanField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return booleanField; + } + public static int GetIntField(IntPtr obj, IntPtr fieldID) + { + int intField; + try + { + intField = AndroidJNI.GetIntField(obj, fieldID); + } + finally + { + AndroidJNISafe.CheckException(); + } + return intField; + } + public static void CallVoidMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + try + { + AndroidJNI.CallVoidMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + } + public static IntPtr CallObjectMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + IntPtr result; + try + { + result = AndroidJNI.CallObjectMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static string CallStringMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + string result; + try + { + result = AndroidJNI.CallStringMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static char CallCharMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + char result; + try + { + result = AndroidJNI.CallCharMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static double CallDoubleMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + double result; + try + { + result = AndroidJNI.CallDoubleMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static float CallFloatMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + float result; + try + { + result = AndroidJNI.CallFloatMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static long CallLongMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + long result; + try + { + result = AndroidJNI.CallLongMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static short CallShortMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + short result; + try + { + result = AndroidJNI.CallShortMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static byte CallByteMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + byte result; + try + { + result = AndroidJNI.CallByteMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static bool CallBooleanMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + bool result; + try + { + result = AndroidJNI.CallBooleanMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static int CallIntMethod(IntPtr obj, IntPtr methodID, jvalue[] args) + { + int result; + try + { + result = AndroidJNI.CallIntMethod(obj, methodID, args); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr[] FromObjectArray(IntPtr array) + { + IntPtr[] result; + try + { + result = AndroidJNI.FromObjectArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static char[] FromCharArray(IntPtr array) + { + char[] result; + try + { + result = AndroidJNI.FromCharArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static double[] FromDoubleArray(IntPtr array) + { + double[] result; + try + { + result = AndroidJNI.FromDoubleArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static float[] FromFloatArray(IntPtr array) + { + float[] result; + try + { + result = AndroidJNI.FromFloatArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static long[] FromLongArray(IntPtr array) + { + long[] result; + try + { + result = AndroidJNI.FromLongArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static short[] FromShortArray(IntPtr array) + { + short[] result; + try + { + result = AndroidJNI.FromShortArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static byte[] FromByteArray(IntPtr array) + { + byte[] result; + try + { + result = AndroidJNI.FromByteArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static bool[] FromBooleanArray(IntPtr array) + { + bool[] result; + try + { + result = AndroidJNI.FromBooleanArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static int[] FromIntArray(IntPtr array) + { + int[] result; + try + { + result = AndroidJNI.FromIntArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToObjectArray(IntPtr[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToObjectArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToObjectArray(IntPtr[] array, IntPtr type) + { + IntPtr result; + try + { + result = AndroidJNI.ToObjectArray(array, type); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToCharArray(char[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToCharArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToDoubleArray(double[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToDoubleArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToFloatArray(float[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToFloatArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToLongArray(long[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToLongArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToShortArray(short[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToShortArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToByteArray(byte[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToByteArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToBooleanArray(bool[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToBooleanArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr ToIntArray(int[] array) + { + IntPtr result; + try + { + result = AndroidJNI.ToIntArray(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return result; + } + public static IntPtr GetObjectArrayElement(IntPtr array, int index) + { + IntPtr objectArrayElement; + try + { + objectArrayElement = AndroidJNI.GetObjectArrayElement(array, index); + } + finally + { + AndroidJNISafe.CheckException(); + } + return objectArrayElement; + } + public static int GetArrayLength(IntPtr array) + { + int arrayLength; + try + { + arrayLength = AndroidJNI.GetArrayLength(array); + } + finally + { + AndroidJNISafe.CheckException(); + } + return arrayLength; + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJavaClass.cs b/UnityEngine/UnityEngine/AndroidJavaClass.cs new file mode 100644 index 00000000..7277ed18 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaClass.cs @@ -0,0 +1,29 @@ +using System; +namespace UnityEngine +{ + public class AndroidJavaClass : AndroidJavaObject + { + internal AndroidJavaClass(IntPtr jclass) + { + if (jclass == IntPtr.Zero) + { + throw new Exception("JNI: Init'd AndroidJavaClass with null ptr!"); + } + this.m_jclass = AndroidJNI.NewGlobalRef(jclass); + this.m_jobject = IntPtr.Zero; + } + public AndroidJavaClass(string className) + { + this._AndroidJavaClass(className); + } + private void _AndroidJavaClass(string className) + { + base.DebugPrint("Creating AndroidJavaClass from " + className); + using (AndroidJavaObject androidJavaObject = AndroidJavaObject.FindClass(className)) + { + this.m_jclass = AndroidJNI.NewGlobalRef(androidJavaObject.GetRawObject()); + this.m_jobject = IntPtr.Zero; + } + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJavaException.cs b/UnityEngine/UnityEngine/AndroidJavaException.cs new file mode 100644 index 00000000..a53f53cc --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaException.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public sealed class AndroidJavaException : Exception + { + internal AndroidJavaException(string message) : base(message) + { + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJavaObject.cs b/UnityEngine/UnityEngine/AndroidJavaObject.cs new file mode 100644 index 00000000..37709e8a --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaObject.cs @@ -0,0 +1,762 @@ +using System; +using System.Text; +namespace UnityEngine +{ + public class AndroidJavaObject : IDisposable + { + private static bool enableDebugPrints; + private bool m_disposed; + protected IntPtr m_jobject; + protected IntPtr m_jclass; + private static AndroidJavaClass s_JavaLangClass; + protected static AndroidJavaClass JavaLangClass + { + get + { + if (AndroidJavaObject.s_JavaLangClass == null) + { + AndroidJavaObject.s_JavaLangClass = new AndroidJavaClass(AndroidJNISafe.FindClass("java/lang/Class")); + } + return AndroidJavaObject.s_JavaLangClass; + } + } + internal AndroidJavaObject(IntPtr jobject) : this() + { + if (jobject == IntPtr.Zero) + { + throw new Exception("JNI: Init'd AndroidJavaObject with null ptr!"); + } + IntPtr objectClass = AndroidJNISafe.GetObjectClass(jobject); + this.m_jobject = AndroidJNI.NewGlobalRef(jobject); + this.m_jclass = AndroidJNI.NewGlobalRef(objectClass); + AndroidJNISafe.DeleteLocalRef(objectClass); + } + internal AndroidJavaObject() + { + } + public AndroidJavaObject(string className, params object[] args) : this() + { + this._AndroidJavaObject(className, args); + } + protected void DebugPrint(string msg) + { + if (!AndroidJavaObject.enableDebugPrints) + { + return; + } + Debug.Log(msg); + } + protected void DebugPrint(string call, string methodName, string signature, object[] args) + { + if (!AndroidJavaObject.enableDebugPrints) + { + return; + } + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + stringBuilder.Append(", "); + stringBuilder.Append((obj != null) ? obj.GetType().ToString() : ""); + } + Debug.Log(string.Concat(new string[] + { + call, + "(\"", + methodName, + "\"", + stringBuilder.ToString(), + ") = ", + signature + })); + } + private void _AndroidJavaObject(string className, params object[] args) + { + this.DebugPrint("Creating AndroidJavaObject from " + className); + if (args == null) + { + args = new object[1]; + } + using (AndroidJavaObject androidJavaObject = AndroidJavaObject.FindClass(className)) + { + this.m_jclass = AndroidJNI.NewGlobalRef(androidJavaObject.GetRawObject()); + jvalue[] array = AndroidJNIHelper.CreateJNIArgArray(args); + try + { + IntPtr constructorID = AndroidJNIHelper.GetConstructorID(this.m_jclass, args); + IntPtr intPtr = AndroidJNISafe.NewObject(this.m_jclass, constructorID, array); + this.m_jobject = AndroidJNI.NewGlobalRef(intPtr); + AndroidJNISafe.DeleteLocalRef(intPtr); + } + finally + { + AndroidJNIHelper.DeleteJNIArgArray(args, array); + } + } + } + ~AndroidJavaObject() + { + this.Dispose(true); + } + protected virtual void Dispose(bool disposing) + { + if (this.m_disposed) + { + return; + } + this.m_disposed = true; + AndroidJNISafe.DeleteGlobalRef(this.m_jobject); + AndroidJNISafe.DeleteGlobalRef(this.m_jclass); + } + protected void _Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + protected void _Call(string methodName, params object[] args) + { + if (args == null) + { + args = new object[1]; + } + IntPtr methodID = AndroidJNIHelper.GetMethodID(this.m_jclass, methodName, args, false); + jvalue[] array = AndroidJNIHelper.CreateJNIArgArray(args); + try + { + AndroidJNISafe.CallVoidMethod(this.m_jobject, methodID, array); + } + finally + { + AndroidJNIHelper.DeleteJNIArgArray(args, array); + } + } + protected ReturnType _Call(string methodName, params object[] args) + { + if (args == null) + { + args = new object[1]; + } + IntPtr methodID = AndroidJNIHelper.GetMethodID(this.m_jclass, methodName, args, false); + jvalue[] array = AndroidJNIHelper.CreateJNIArgArray(args); + ReturnType result; + try + { + if (typeof(ReturnType).IsPrimitive) + { + if (typeof(ReturnType) == typeof(int)) + { + result = (ReturnType)((object)AndroidJNISafe.CallIntMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(bool)) + { + result = (ReturnType)((object)AndroidJNISafe.CallBooleanMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(byte)) + { + result = (ReturnType)((object)AndroidJNISafe.CallByteMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(short)) + { + result = (ReturnType)((object)AndroidJNISafe.CallShortMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(long)) + { + result = (ReturnType)((object)AndroidJNISafe.CallLongMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(float)) + { + result = (ReturnType)((object)AndroidJNISafe.CallFloatMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(double)) + { + result = (ReturnType)((object)AndroidJNISafe.CallDoubleMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(char)) + { + result = (ReturnType)((object)AndroidJNISafe.CallCharMethod(this.m_jobject, methodID, array)); + } + else + { + result = default(ReturnType); + } + } + } + } + } + } + } + } + } + else + { + if (typeof(ReturnType) == typeof(string)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStringMethod(this.m_jobject, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(AndroidJavaClass)) + { + IntPtr jclass = AndroidJNISafe.CallObjectMethod(this.m_jobject, methodID, array); + result = (ReturnType)((object)AndroidJavaObject.AndroidJavaClassDeleteLocalRef(jclass)); + } + else + { + if (typeof(ReturnType) == typeof(AndroidJavaObject)) + { + IntPtr jobject = AndroidJNISafe.CallObjectMethod(this.m_jobject, methodID, array); + result = (ReturnType)((object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(jobject)); + } + else + { + if (!typeof(Array).IsAssignableFrom(typeof(ReturnType))) + { + throw new Exception("JNI: Unknown return type '" + typeof(ReturnType) + "'"); + } + IntPtr array2 = AndroidJNISafe.CallObjectMethod(this.m_jobject, methodID, array); + result = (ReturnType)((object)AndroidJNIHelper.ConvertFromJNIArray(array2)); + } + } + } + } + } + finally + { + AndroidJNIHelper.DeleteJNIArgArray(args, array); + } + return result; + } + protected FieldType _Get(string fieldName) + { + IntPtr fieldID = AndroidJNIHelper.GetFieldID(this.m_jclass, fieldName, false); + if (typeof(FieldType).IsPrimitive) + { + if (typeof(FieldType) == typeof(int)) + { + return (FieldType)((object)AndroidJNISafe.GetIntField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(bool)) + { + return (FieldType)((object)AndroidJNISafe.GetBooleanField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(byte)) + { + return (FieldType)((object)AndroidJNISafe.GetByteField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(short)) + { + return (FieldType)((object)AndroidJNISafe.GetShortField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(long)) + { + return (FieldType)((object)AndroidJNISafe.GetLongField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(float)) + { + return (FieldType)((object)AndroidJNISafe.GetFloatField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(double)) + { + return (FieldType)((object)AndroidJNISafe.GetDoubleField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(char)) + { + return (FieldType)((object)AndroidJNISafe.GetCharField(this.m_jobject, fieldID)); + } + return default(FieldType); + } + else + { + if (typeof(FieldType) == typeof(string)) + { + return (FieldType)((object)AndroidJNISafe.GetStringField(this.m_jobject, fieldID)); + } + if (typeof(FieldType) == typeof(AndroidJavaClass)) + { + IntPtr objectField = AndroidJNISafe.GetObjectField(this.m_jobject, fieldID); + return (FieldType)((object)AndroidJavaObject.AndroidJavaClassDeleteLocalRef(objectField)); + } + if (typeof(FieldType) == typeof(AndroidJavaObject)) + { + IntPtr objectField2 = AndroidJNISafe.GetObjectField(this.m_jobject, fieldID); + return (FieldType)((object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(objectField2)); + } + if (typeof(Array).IsAssignableFrom(typeof(FieldType))) + { + IntPtr objectField3 = AndroidJNISafe.GetObjectField(this.m_jobject, fieldID); + return (FieldType)((object)AndroidJNIHelper.ConvertFromJNIArray(objectField3)); + } + throw new Exception("JNI: Unknown field type '" + typeof(FieldType) + "'"); + } + } + protected void _Set(string fieldName, FieldType val) + { + IntPtr fieldID = AndroidJNIHelper.GetFieldID(this.m_jclass, fieldName, false); + if (typeof(FieldType).IsPrimitive) + { + if (typeof(FieldType) == typeof(int)) + { + AndroidJNISafe.SetIntField(this.m_jobject, fieldID, (int)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(bool)) + { + AndroidJNISafe.SetBooleanField(this.m_jobject, fieldID, (bool)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(byte)) + { + AndroidJNISafe.SetByteField(this.m_jobject, fieldID, (byte)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(short)) + { + AndroidJNISafe.SetShortField(this.m_jobject, fieldID, (short)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(long)) + { + AndroidJNISafe.SetLongField(this.m_jobject, fieldID, (long)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(float)) + { + AndroidJNISafe.SetFloatField(this.m_jobject, fieldID, (float)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(double)) + { + AndroidJNISafe.SetDoubleField(this.m_jobject, fieldID, (double)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(char)) + { + AndroidJNISafe.SetCharField(this.m_jobject, fieldID, (char)((object)val)); + } + } + } + } + } + } + } + } + } + else + { + if (typeof(FieldType) == typeof(string)) + { + AndroidJNISafe.SetStringField(this.m_jobject, fieldID, (string)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(AndroidJavaClass)) + { + AndroidJNISafe.SetObjectField(this.m_jobject, fieldID, ((AndroidJavaClass)((object)val)).m_jclass); + } + else + { + if (typeof(FieldType) == typeof(AndroidJavaObject)) + { + AndroidJNISafe.SetObjectField(this.m_jobject, fieldID, ((AndroidJavaObject)((object)val)).m_jobject); + } + else + { + if (!typeof(Array).IsAssignableFrom(typeof(FieldType))) + { + throw new Exception("JNI: Unknown field type '" + typeof(FieldType) + "'"); + } + IntPtr val2 = AndroidJNIHelper.ConvertToJNIArray((Array)((object)val)); + AndroidJNISafe.SetObjectField(this.m_jclass, fieldID, val2); + } + } + } + } + } + protected void _CallStatic(string methodName, params object[] args) + { + if (args == null) + { + args = new object[1]; + } + IntPtr methodID = AndroidJNIHelper.GetMethodID(this.m_jclass, methodName, args, true); + jvalue[] array = AndroidJNIHelper.CreateJNIArgArray(args); + try + { + AndroidJNISafe.CallStaticVoidMethod(this.m_jclass, methodID, array); + } + finally + { + AndroidJNIHelper.DeleteJNIArgArray(args, array); + } + } + protected ReturnType _CallStatic(string methodName, params object[] args) + { + if (args == null) + { + args = new object[1]; + } + IntPtr methodID = AndroidJNIHelper.GetMethodID(this.m_jclass, methodName, args, true); + jvalue[] array = AndroidJNIHelper.CreateJNIArgArray(args); + ReturnType result; + try + { + if (typeof(ReturnType).IsPrimitive) + { + if (typeof(ReturnType) == typeof(int)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticIntMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(bool)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticBooleanMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(byte)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticByteMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(short)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticShortMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(long)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticLongMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(float)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticFloatMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(double)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticDoubleMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(char)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticCharMethod(this.m_jclass, methodID, array)); + } + else + { + result = default(ReturnType); + } + } + } + } + } + } + } + } + } + else + { + if (typeof(ReturnType) == typeof(string)) + { + result = (ReturnType)((object)AndroidJNISafe.CallStaticStringMethod(this.m_jclass, methodID, array)); + } + else + { + if (typeof(ReturnType) == typeof(AndroidJavaClass)) + { + IntPtr jclass = AndroidJNISafe.CallStaticObjectMethod(this.m_jclass, methodID, array); + result = (ReturnType)((object)AndroidJavaObject.AndroidJavaClassDeleteLocalRef(jclass)); + } + else + { + if (typeof(ReturnType) == typeof(AndroidJavaObject)) + { + IntPtr jobject = AndroidJNISafe.CallStaticObjectMethod(this.m_jclass, methodID, array); + result = (ReturnType)((object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(jobject)); + } + else + { + if (!typeof(Array).IsAssignableFrom(typeof(ReturnType))) + { + throw new Exception("JNI: Unknown return type '" + typeof(ReturnType) + "'"); + } + IntPtr array2 = AndroidJNISafe.CallStaticObjectMethod(this.m_jclass, methodID, array); + result = (ReturnType)((object)AndroidJNIHelper.ConvertFromJNIArray(array2)); + } + } + } + } + } + finally + { + AndroidJNIHelper.DeleteJNIArgArray(args, array); + } + return result; + } + protected FieldType _GetStatic(string fieldName) + { + IntPtr fieldID = AndroidJNIHelper.GetFieldID(this.m_jclass, fieldName, true); + if (typeof(FieldType).IsPrimitive) + { + if (typeof(FieldType) == typeof(int)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticIntField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(bool)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticBooleanField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(byte)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticByteField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(short)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticShortField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(long)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticLongField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(float)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticFloatField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(double)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticDoubleField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(char)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticCharField(this.m_jclass, fieldID)); + } + return default(FieldType); + } + else + { + if (typeof(FieldType) == typeof(string)) + { + return (FieldType)((object)AndroidJNISafe.GetStaticStringField(this.m_jclass, fieldID)); + } + if (typeof(FieldType) == typeof(AndroidJavaClass)) + { + IntPtr staticObjectField = AndroidJNISafe.GetStaticObjectField(this.m_jclass, fieldID); + return (FieldType)((object)AndroidJavaObject.AndroidJavaClassDeleteLocalRef(staticObjectField)); + } + if (typeof(FieldType) == typeof(AndroidJavaObject)) + { + IntPtr staticObjectField2 = AndroidJNISafe.GetStaticObjectField(this.m_jclass, fieldID); + return (FieldType)((object)AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(staticObjectField2)); + } + if (typeof(Array).IsAssignableFrom(typeof(FieldType))) + { + IntPtr staticObjectField3 = AndroidJNISafe.GetStaticObjectField(this.m_jclass, fieldID); + return (FieldType)((object)AndroidJNIHelper.ConvertFromJNIArray(staticObjectField3)); + } + throw new Exception("JNI: Unknown field type '" + typeof(FieldType) + "'"); + } + } + protected void _SetStatic(string fieldName, FieldType val) + { + IntPtr fieldID = AndroidJNIHelper.GetFieldID(this.m_jclass, fieldName, true); + if (typeof(FieldType).IsPrimitive) + { + if (typeof(FieldType) == typeof(int)) + { + AndroidJNISafe.SetStaticIntField(this.m_jclass, fieldID, (int)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(bool)) + { + AndroidJNISafe.SetStaticBooleanField(this.m_jclass, fieldID, (bool)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(byte)) + { + AndroidJNISafe.SetStaticByteField(this.m_jclass, fieldID, (byte)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(short)) + { + AndroidJNISafe.SetStaticShortField(this.m_jclass, fieldID, (short)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(long)) + { + AndroidJNISafe.SetStaticLongField(this.m_jclass, fieldID, (long)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(float)) + { + AndroidJNISafe.SetStaticFloatField(this.m_jclass, fieldID, (float)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(double)) + { + AndroidJNISafe.SetStaticDoubleField(this.m_jclass, fieldID, (double)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(char)) + { + AndroidJNISafe.SetStaticCharField(this.m_jclass, fieldID, (char)((object)val)); + } + } + } + } + } + } + } + } + } + else + { + if (typeof(FieldType) == typeof(string)) + { + AndroidJNISafe.SetStaticStringField(this.m_jclass, fieldID, (string)((object)val)); + } + else + { + if (typeof(FieldType) == typeof(AndroidJavaClass)) + { + AndroidJNISafe.SetStaticObjectField(this.m_jclass, fieldID, ((AndroidJavaClass)((object)val)).m_jclass); + } + else + { + if (typeof(FieldType) == typeof(AndroidJavaObject)) + { + AndroidJNISafe.SetStaticObjectField(this.m_jclass, fieldID, ((AndroidJavaObject)((object)val)).m_jobject); + } + else + { + if (!typeof(Array).IsAssignableFrom(typeof(FieldType))) + { + throw new Exception("JNI: Unknown field type '" + typeof(FieldType) + "'"); + } + IntPtr val2 = AndroidJNIHelper.ConvertToJNIArray((Array)((object)val)); + AndroidJNISafe.SetStaticObjectField(this.m_jclass, fieldID, val2); + } + } + } + } + } + internal static AndroidJavaObject AndroidJavaObjectDeleteLocalRef(IntPtr jobject) + { + AndroidJavaObject result; + try + { + result = new AndroidJavaObject(jobject); + } + finally + { + AndroidJNISafe.DeleteLocalRef(jobject); + } + return result; + } + internal static AndroidJavaClass AndroidJavaClassDeleteLocalRef(IntPtr jclass) + { + AndroidJavaClass result; + try + { + result = new AndroidJavaClass(jclass); + } + finally + { + AndroidJNISafe.DeleteLocalRef(jclass); + } + return result; + } + protected IntPtr _GetRawObject() + { + return this.m_jobject; + } + protected IntPtr _GetRawClass() + { + return this.m_jclass; + } + protected static AndroidJavaObject FindClass(string name) + { + return AndroidJavaObject.JavaLangClass.CallStatic("forName", new object[] + { + name.Replace('/', '.') + }); + } + public void Dispose() + { + this._Dispose(); + } + public void Call(string methodName, params object[] args) + { + this._Call(methodName, args); + } + public void CallStatic(string methodName, params object[] args) + { + this._CallStatic(methodName, args); + } + public FieldType Get(string fieldName) + { + return this._Get(fieldName); + } + public void Set(string fieldName, FieldType val) + { + this._Set(fieldName, val); + } + public FieldType GetStatic(string fieldName) + { + return this._GetStatic(fieldName); + } + public void SetStatic(string fieldName, FieldType val) + { + this._SetStatic(fieldName, val); + } + public IntPtr GetRawObject() + { + return this._GetRawObject(); + } + public IntPtr GetRawClass() + { + return this._GetRawClass(); + } + public ReturnType Call(string methodName, params object[] args) + { + return this._Call(methodName, args); + } + public ReturnType CallStatic(string methodName, params object[] args) + { + return this._CallStatic(methodName, args); + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJavaProxy.cs b/UnityEngine/UnityEngine/AndroidJavaProxy.cs new file mode 100644 index 00000000..d59408fc --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaProxy.cs @@ -0,0 +1,79 @@ +using System; +using System.Reflection; +namespace UnityEngine +{ + public class AndroidJavaProxy + { + public readonly AndroidJavaClass javaInterface; + public AndroidJavaProxy(string javaInterface) : this(new AndroidJavaClass(javaInterface)) + { + } + public AndroidJavaProxy(AndroidJavaClass javaInterface) + { + this.javaInterface = javaInterface; + } + public virtual AndroidJavaObject Invoke(string methodName, object[] args) + { + Exception ex = null; + BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + Type[] array = new Type[args.Length]; + for (int i = 0; i < args.Length; i++) + { + array[i] = ((args[i] != null) ? args[i].GetType() : typeof(AndroidJavaObject)); + } + try + { + MethodInfo method = base.GetType().GetMethod(methodName, bindingAttr, null, array, null); + if (method != null) + { + AndroidJavaObject result = _AndroidJNIHelper.Box(method.Invoke(this, args)); + return result; + } + } + catch (TargetInvocationException ex2) + { + ex = ex2.InnerException; + } + catch (Exception ex3) + { + ex = ex3; + } + string[] array2 = new string[args.Length]; + for (int j = 0; j < array.Length; j++) + { + array2[j] = array[j].ToString(); + } + if (ex != null) + { + throw new TargetInvocationException(string.Concat(new object[] + { + base.GetType(), + ".", + methodName, + "(", + string.Join(",", array2), + ")" + }), ex); + } + throw new Exception(string.Concat(new object[] + { + "No such proxy method: ", + base.GetType(), + ".", + methodName, + "(", + string.Join(",", array2), + ")" + })); + } + public virtual AndroidJavaObject Invoke(string methodName, AndroidJavaObject[] javaArgs) + { + object[] array = new object[javaArgs.Length]; + for (int i = 0; i < javaArgs.Length; i++) + { + array[i] = _AndroidJNIHelper.Unbox(javaArgs[i]); + } + return this.Invoke(methodName, array); + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidJavaRunnable.cs b/UnityEngine/UnityEngine/AndroidJavaRunnable.cs new file mode 100644 index 00000000..eb35261e --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaRunnable.cs @@ -0,0 +1,5 @@ +using System; +namespace UnityEngine +{ + public delegate void AndroidJavaRunnable(); +} diff --git a/UnityEngine/UnityEngine/AndroidJavaRunnableProxy.cs b/UnityEngine/UnityEngine/AndroidJavaRunnableProxy.cs new file mode 100644 index 00000000..ebcb2ca4 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidJavaRunnableProxy.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + internal class AndroidJavaRunnableProxy : AndroidJavaProxy + { + private AndroidJavaRunnable mRunnable; + public AndroidJavaRunnableProxy(AndroidJavaRunnable runnable) : base("java/lang/Runnable") + { + this.mRunnable = runnable; + } + public void run() + { + this.mRunnable(); + } + } +} diff --git a/UnityEngine/UnityEngine/AndroidReflection.cs b/UnityEngine/UnityEngine/AndroidReflection.cs new file mode 100644 index 00000000..50438f27 --- /dev/null +++ b/UnityEngine/UnityEngine/AndroidReflection.cs @@ -0,0 +1,88 @@ +using System; +namespace UnityEngine +{ + internal class AndroidReflection + { + private const string RELECTION_HELPER_CLASS_NAME = "com/unity3d/player/ReflectionHelper"; + private static IntPtr s_ReflectionHelperClass = AndroidJNI.NewGlobalRef(AndroidJNISafe.FindClass("com/unity3d/player/ReflectionHelper")); + private static IntPtr s_ReflectionHelperGetConstructorID = AndroidReflection.GetStaticMethodID("com/unity3d/player/ReflectionHelper", "getConstructorID", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/reflect/Constructor;"); + private static IntPtr s_ReflectionHelperGetMethodID = AndroidReflection.GetStaticMethodID("com/unity3d/player/ReflectionHelper", "getMethodID", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/reflect/Method;"); + private static IntPtr s_ReflectionHelperGetFieldID = AndroidReflection.GetStaticMethodID("com/unity3d/player/ReflectionHelper", "getFieldID", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;Z)Ljava/lang/reflect/Field;"); + private static IntPtr s_ReflectionHelperNewProxyInstance = AndroidReflection.GetStaticMethodID("com/unity3d/player/ReflectionHelper", "newProxyInstance", "(ILjava/lang/Class;)Ljava/lang/Object;"); + private static IntPtr GetStaticMethodID(string clazz, string methodName, string signature) + { + IntPtr intPtr = AndroidJNISafe.FindClass(clazz); + IntPtr staticMethodID; + try + { + staticMethodID = AndroidJNISafe.GetStaticMethodID(intPtr, methodName, signature); + } + finally + { + AndroidJNISafe.DeleteLocalRef(intPtr); + } + return staticMethodID; + } + public static IntPtr GetConstructorMember(IntPtr jclass, string signature) + { + jvalue[] array = new jvalue[2]; + IntPtr result; + try + { + array[0].l = jclass; + array[1].l = AndroidJNISafe.NewStringUTF(signature); + result = AndroidJNISafe.CallStaticObjectMethod(AndroidReflection.s_ReflectionHelperClass, AndroidReflection.s_ReflectionHelperGetConstructorID, array); + } + finally + { + AndroidJNISafe.DeleteLocalRef(array[1].l); + } + return result; + } + public static IntPtr GetMethodMember(IntPtr jclass, string methodName, string signature, bool isStatic) + { + jvalue[] array = new jvalue[4]; + IntPtr result; + try + { + array[0].l = jclass; + array[1].l = AndroidJNISafe.NewStringUTF(methodName); + array[2].l = AndroidJNISafe.NewStringUTF(signature); + array[3].z = isStatic; + result = AndroidJNISafe.CallStaticObjectMethod(AndroidReflection.s_ReflectionHelperClass, AndroidReflection.s_ReflectionHelperGetMethodID, array); + } + finally + { + AndroidJNISafe.DeleteLocalRef(array[1].l); + AndroidJNISafe.DeleteLocalRef(array[2].l); + } + return result; + } + public static IntPtr GetFieldMember(IntPtr jclass, string fieldName, string signature, bool isStatic) + { + jvalue[] array = new jvalue[4]; + IntPtr result; + try + { + array[0].l = jclass; + array[1].l = AndroidJNISafe.NewStringUTF(fieldName); + array[2].l = AndroidJNISafe.NewStringUTF(signature); + array[3].z = isStatic; + result = AndroidJNISafe.CallStaticObjectMethod(AndroidReflection.s_ReflectionHelperClass, AndroidReflection.s_ReflectionHelperGetFieldID, array); + } + finally + { + AndroidJNISafe.DeleteLocalRef(array[1].l); + AndroidJNISafe.DeleteLocalRef(array[2].l); + } + return result; + } + public static IntPtr NewProxyInstance(int delegateHandle, IntPtr interfaze) + { + jvalue[] array = new jvalue[2]; + array[0].i = delegateHandle; + array[1].l = interfaze; + return AndroidJNISafe.CallStaticObjectMethod(AndroidReflection.s_ReflectionHelperClass, AndroidReflection.s_ReflectionHelperNewProxyInstance, array); + } + } +} diff --git a/UnityEngine/UnityEngine/Animation.cs b/UnityEngine/UnityEngine/Animation.cs new file mode 100644 index 00000000..9a93ad99 --- /dev/null +++ b/UnityEngine/UnityEngine/Animation.cs @@ -0,0 +1,320 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Animation : Behaviour, IEnumerable + { + private sealed class Enumerator : IEnumerator + { + private Animation m_Outer; + private int m_CurrentIndex = -1; + public object Current + { + get + { + return this.m_Outer.GetStateAtIndex(this.m_CurrentIndex); + } + } + internal Enumerator(Animation outer) + { + this.m_Outer = outer; + } + public bool MoveNext() + { + int stateCount = this.m_Outer.GetStateCount(); + this.m_CurrentIndex++; + return this.m_CurrentIndex < stateCount; + } + public void Reset() + { + this.m_CurrentIndex = -1; + } + } + public extern AnimationClip clip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool playAutomatically + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern WrapMode wrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public AnimationState this[string name] + { + get + { + return this.GetState(name); + } + } + public extern bool animatePhysics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use cullingType instead")] + public extern bool animateOnlyIfVisible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimationCullingType cullingType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Bounds localBounds + { + get + { + Bounds result; + this.INTERNAL_get_localBounds(out result); + return result; + } + set + { + this.INTERNAL_set_localBounds(ref value); + } + } + public void Stop() + { + Animation.INTERNAL_CALL_Stop(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Stop(Animation self); + public void Stop(string name) + { + this.Internal_StopByName(name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_StopByName(string name); + public void Rewind(string name) + { + this.Internal_RewindByName(name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_RewindByName(string name); + public void Rewind() + { + Animation.INTERNAL_CALL_Rewind(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rewind(Animation self); + public void Sample() + { + Animation.INTERNAL_CALL_Sample(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Sample(Animation self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsPlaying(string name); + [ExcludeFromDocs] + public bool Play() + { + PlayMode mode = PlayMode.StopSameLayer; + return this.Play(mode); + } + public bool Play([DefaultValue("PlayMode.StopSameLayer")] PlayMode mode) + { + return this.PlayDefaultAnimation(mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Play(string animation, [DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); + [ExcludeFromDocs] + public bool Play(string animation) + { + PlayMode mode = PlayMode.StopSameLayer; + return this.Play(animation, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CrossFade(string animation, [DefaultValue("0.3F")] float fadeLength, [DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); + [ExcludeFromDocs] + public void CrossFade(string animation, float fadeLength) + { + PlayMode mode = PlayMode.StopSameLayer; + this.CrossFade(animation, fadeLength, mode); + } + [ExcludeFromDocs] + public void CrossFade(string animation) + { + PlayMode mode = PlayMode.StopSameLayer; + float fadeLength = 0.3f; + this.CrossFade(animation, fadeLength, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Blend(string animation, [DefaultValue("1.0F")] float targetWeight, [DefaultValue("0.3F")] float fadeLength); + [ExcludeFromDocs] + public void Blend(string animation, float targetWeight) + { + float fadeLength = 0.3f; + this.Blend(animation, targetWeight, fadeLength); + } + [ExcludeFromDocs] + public void Blend(string animation) + { + float fadeLength = 0.3f; + float targetWeight = 1f; + this.Blend(animation, targetWeight, fadeLength); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimationState CrossFadeQueued(string animation, [DefaultValue("0.3F")] float fadeLength, [DefaultValue("QueueMode.CompleteOthers")] QueueMode queue, [DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); + [ExcludeFromDocs] + public AnimationState CrossFadeQueued(string animation, float fadeLength, QueueMode queue) + { + PlayMode mode = PlayMode.StopSameLayer; + return this.CrossFadeQueued(animation, fadeLength, queue, mode); + } + [ExcludeFromDocs] + public AnimationState CrossFadeQueued(string animation, float fadeLength) + { + PlayMode mode = PlayMode.StopSameLayer; + QueueMode queue = QueueMode.CompleteOthers; + return this.CrossFadeQueued(animation, fadeLength, queue, mode); + } + [ExcludeFromDocs] + public AnimationState CrossFadeQueued(string animation) + { + PlayMode mode = PlayMode.StopSameLayer; + QueueMode queue = QueueMode.CompleteOthers; + float fadeLength = 0.3f; + return this.CrossFadeQueued(animation, fadeLength, queue, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimationState PlayQueued(string animation, [DefaultValue("QueueMode.CompleteOthers")] QueueMode queue, [DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); + [ExcludeFromDocs] + public AnimationState PlayQueued(string animation, QueueMode queue) + { + PlayMode mode = PlayMode.StopSameLayer; + return this.PlayQueued(animation, queue, mode); + } + [ExcludeFromDocs] + public AnimationState PlayQueued(string animation) + { + PlayMode mode = PlayMode.StopSameLayer; + QueueMode queue = QueueMode.CompleteOthers; + return this.PlayQueued(animation, queue, mode); + } + public void AddClip(AnimationClip clip, string newName) + { + this.AddClip(clip, newName, -2147483648, 2147483647); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddClip(AnimationClip clip, string newName, int firstFrame, int lastFrame, [DefaultValue("false")] bool addLoopFrame); + [ExcludeFromDocs] + public void AddClip(AnimationClip clip, string newName, int firstFrame, int lastFrame) + { + bool addLoopFrame = false; + this.AddClip(clip, newName, firstFrame, lastFrame, addLoopFrame); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveClip(AnimationClip clip); + public void RemoveClip(string clipName) + { + this.RemoveClip2(clipName); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetClipCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void RemoveClip2(string clipName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool PlayDefaultAnimation(PlayMode mode); + [Obsolete("use PlayMode instead of AnimationPlayMode.")] + public bool Play(AnimationPlayMode mode) + { + return this.PlayDefaultAnimation((PlayMode)mode); + } + [Obsolete("use PlayMode instead of AnimationPlayMode.")] + public bool Play(string animation, AnimationPlayMode mode) + { + return this.Play(animation, (PlayMode)mode); + } + public void SyncLayer(int layer) + { + Animation.INTERNAL_CALL_SyncLayer(this, layer); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SyncLayer(Animation self, int layer); + public IEnumerator GetEnumerator() + { + return new Animation.Enumerator(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimationState GetState(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimationState GetStateAtIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int GetStateCount(); + public AnimationClip GetClip(string name) + { + AnimationState state = this.GetState(name); + if (state) + { + return state.clip; + } + return null; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localBounds(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localBounds(ref Bounds value); + } +} diff --git a/UnityEngine/UnityEngine/AnimationBlendMode.cs b/UnityEngine/UnityEngine/AnimationBlendMode.cs new file mode 100644 index 00000000..67a70c14 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationBlendMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum AnimationBlendMode + { + Blend, + Additive + } +} diff --git a/UnityEngine/UnityEngine/AnimationClip.cs b/UnityEngine/UnityEngine/AnimationClip.cs new file mode 100644 index 00000000..b43e93ec --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationClip.cs @@ -0,0 +1,90 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AnimationClip : Motion + { + public extern float length + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern float startTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern float stopTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float frameRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern WrapMode wrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Bounds localBounds + { + get + { + Bounds result; + this.INTERNAL_get_localBounds(out result); + return result; + } + set + { + this.INTERNAL_set_localBounds(ref value); + } + } + public AnimationClip() + { + AnimationClip.Internal_CreateAnimationClip(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAnimationClip([Writable] AnimationClip self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetCurve(string relativePath, Type type, string propertyName, AnimationCurve curve); + public void EnsureQuaternionContinuity() + { + AnimationClip.INTERNAL_CALL_EnsureQuaternionContinuity(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_EnsureQuaternionContinuity(AnimationClip self); + public void ClearCurves() + { + AnimationClip.INTERNAL_CALL_ClearCurves(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearCurves(AnimationClip self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddEvent(AnimationEvent evt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localBounds(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localBounds(ref Bounds value); + } +} diff --git a/UnityEngine/UnityEngine/AnimationClipPair.cs b/UnityEngine/UnityEngine/AnimationClipPair.cs new file mode 100644 index 00000000..5e0934e5 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationClipPair.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class AnimationClipPair + { + public AnimationClip originalClip; + public AnimationClip overrideClip; + } +} diff --git a/UnityEngine/UnityEngine/AnimationCullingType.cs b/UnityEngine/UnityEngine/AnimationCullingType.cs new file mode 100644 index 00000000..e4f21bf4 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationCullingType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum AnimationCullingType + { + AlwaysAnimate, + BasedOnRenderers, + BasedOnClipBounds, + BasedOnUserBounds + } +} diff --git a/UnityEngine/UnityEngine/AnimationCurve.cs b/UnityEngine/UnityEngine/AnimationCurve.cs new file mode 100644 index 00000000..4ebd4fe0 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationCurve.cs @@ -0,0 +1,129 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class AnimationCurve + { + internal IntPtr m_Ptr; + public Keyframe[] keys + { + get + { + return this.GetKeys(); + } + set + { + this.SetKeys(value); + } + } + public Keyframe this[int index] + { + get + { + return this.GetKey_Internal(index); + } + } + public extern int length + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern WrapMode preWrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern WrapMode postWrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AnimationCurve(params Keyframe[] keys) + { + this.Init(keys); + } + public AnimationCurve() + { + this.Init(null); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + ~AnimationCurve() + { + this.Cleanup(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float Evaluate(float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int AddKey(float time, float value); + public int AddKey(Keyframe key) + { + return this.AddKey_Internal(key); + } + private int AddKey_Internal(Keyframe key) + { + return AnimationCurve.INTERNAL_CALL_AddKey_Internal(this, ref key); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_AddKey_Internal(AnimationCurve self, ref Keyframe key); + public int MoveKey(int index, Keyframe key) + { + return AnimationCurve.INTERNAL_CALL_MoveKey(this, index, ref key); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_MoveKey(AnimationCurve self, int index, ref Keyframe key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveKey(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetKeys(Keyframe[] keys); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Keyframe GetKey_Internal(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Keyframe[] GetKeys(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SmoothTangents(int index, float weight); + public static AnimationCurve Linear(float timeStart, float valueStart, float timeEnd, float valueEnd) + { + float num = (valueEnd - valueStart) / (timeEnd - timeStart); + Keyframe[] keys = new Keyframe[] + { + new Keyframe(timeStart, valueStart, 0f, num), + new Keyframe(timeEnd, valueEnd, num, 0f) + }; + return new AnimationCurve(keys); + } + public static AnimationCurve EaseInOut(float timeStart, float valueStart, float timeEnd, float valueEnd) + { + Keyframe[] keys = new Keyframe[] + { + new Keyframe(timeStart, valueStart, 0f, 0f), + new Keyframe(timeEnd, valueEnd, 0f, 0f) + }; + return new AnimationCurve(keys); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(Keyframe[] keys); + } +} diff --git a/UnityEngine/UnityEngine/AnimationEvent.cs b/UnityEngine/UnityEngine/AnimationEvent.cs new file mode 100644 index 00000000..f8699995 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationEvent.cs @@ -0,0 +1,110 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class AnimationEvent + { + [NotRenamed] + internal IntPtr m_Ptr; + private int m_OwnsData; + [Obsolete("Use stringParameter instead")] + public extern string data + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string stringParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float floatParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int intParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Object objectReferenceParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string functionName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern SendMessageOptions messageOptions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimationState animationState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public AnimationEvent() + { + this.m_OwnsData = 1; + this.Create(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Create(); + ~AnimationEvent() + { + if (this.m_OwnsData != 0) + { + this.Destroy(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + } +} diff --git a/UnityEngine/UnityEngine/AnimationInfo.cs b/UnityEngine/UnityEngine/AnimationInfo.cs new file mode 100644 index 00000000..c73ad25b --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct AnimationInfo + { + private int m_ClipInstanceID; + private float m_Weight; + public AnimationClip clip + { + get + { + return (this.m_ClipInstanceID == 0) ? null : AnimationInfo.ClipInstanceToScriptingObject(this.m_ClipInstanceID); + } + } + public float weight + { + get + { + return this.m_Weight; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AnimationClip ClipInstanceToScriptingObject(int instanceID); + } +} diff --git a/UnityEngine/UnityEngine/AnimationPlayMode.cs b/UnityEngine/UnityEngine/AnimationPlayMode.cs new file mode 100644 index 00000000..833541da --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationPlayMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AnimationPlayMode + { + Stop, + Queue, + Mix + } +} diff --git a/UnityEngine/UnityEngine/AnimationState.cs b/UnityEngine/UnityEngine/AnimationState.cs new file mode 100644 index 00000000..4ef8e9d3 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationState.cs @@ -0,0 +1,123 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class AnimationState : TrackedReference + { + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float weight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern WrapMode wrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float normalizedTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float normalizedSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float length + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int layer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimationClip clip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimationBlendMode blendMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddMixingTransform(Transform mix, [DefaultValue("true")] bool recursive); + [ExcludeFromDocs] + public void AddMixingTransform(Transform mix) + { + bool recursive = true; + this.AddMixingTransform(mix, recursive); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveMixingTransform(Transform mix); + } +} diff --git a/UnityEngine/UnityEngine/Animator.cs b/UnityEngine/UnityEngine/Animator.cs new file mode 100644 index 00000000..86f438ab --- /dev/null +++ b/UnityEngine/UnityEngine/Animator.cs @@ -0,0 +1,762 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Animator : Behaviour + { + public extern bool isOptimizable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isHuman + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasRootMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float humanScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3 deltaPosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Quaternion deltaRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 rootPosition + { + get + { + Vector3 result; + this.INTERNAL_get_rootPosition(out result); + return result; + } + set + { + this.INTERNAL_set_rootPosition(ref value); + } + } + public Quaternion rootRotation + { + get + { + Quaternion result; + this.INTERNAL_get_rootRotation(out result); + return result; + } + set + { + this.INTERNAL_set_rootRotation(ref value); + } + } + public extern bool applyRootMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use AnimationMode.updateMode instead")] + public bool animatePhysics + { + get + { + return this.updateMode == AnimatorUpdateMode.AnimatePhysics; + } + set + { + this.updateMode = ((!value) ? AnimatorUpdateMode.Normal : AnimatorUpdateMode.AnimatePhysics); + } + } + public extern AnimatorUpdateMode updateMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasTransformHierarchy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool allowConstantClipSamplingOptimization + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float gravityWeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 bodyPosition + { + get + { + Vector3 result; + this.INTERNAL_get_bodyPosition(out result); + return result; + } + set + { + this.INTERNAL_set_bodyPosition(ref value); + } + } + public Quaternion bodyRotation + { + get + { + Quaternion result; + this.INTERNAL_get_bodyRotation(out result); + return result; + } + set + { + this.INTERNAL_set_bodyRotation(ref value); + } + } + public extern bool stabilizeFeet + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int layerCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float feetPivotActive + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pivotWeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3 pivotPosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isMatchingTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector3 targetPosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Quaternion targetRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern Transform avatarRoot + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AnimatorCullingMode cullingMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float playbackTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float recorderStartTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float recorderStopTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RuntimeAnimatorController runtimeAnimatorController + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Avatar avatar + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool layersAffectMassCenter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float leftFeetBottomHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float rightFeetBottomHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool supportsOnAnimatorMove + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private extern bool isInManagerList + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool logWarnings + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool fireEvents + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public float GetFloat(string name) + { + return this.GetFloatString(name); + } + public float GetFloat(int id) + { + return this.GetFloatID(id); + } + public void SetFloat(string name, float value) + { + this.SetFloatString(name, value); + } + public void SetFloat(string name, float value, float dampTime, float deltaTime) + { + this.SetFloatStringDamp(name, value, dampTime, deltaTime); + } + public void SetFloat(int id, float value) + { + this.SetFloatID(id, value); + } + public void SetFloat(int id, float value, float dampTime, float deltaTime) + { + this.SetFloatIDDamp(id, value, dampTime, deltaTime); + } + public bool GetBool(string name) + { + return this.GetBoolString(name); + } + public bool GetBool(int id) + { + return this.GetBoolID(id); + } + public void SetBool(string name, bool value) + { + this.SetBoolString(name, value); + } + public void SetBool(int id, bool value) + { + this.SetBoolID(id, value); + } + public int GetInteger(string name) + { + return this.GetIntegerString(name); + } + public int GetInteger(int id) + { + return this.GetIntegerID(id); + } + public void SetInteger(string name, int value) + { + this.SetIntegerString(name, value); + } + public void SetInteger(int id, int value) + { + this.SetIntegerID(id, value); + } + public void SetTrigger(string name) + { + this.SetTriggerString(name); + } + public void SetTrigger(int id) + { + this.SetTriggerID(id); + } + public void ResetTrigger(string name) + { + this.ResetTriggerString(name); + } + public void ResetTrigger(int id) + { + this.ResetTriggerID(id); + } + public bool IsParameterControlledByCurve(string name) + { + return this.IsParameterControlledByCurveString(name); + } + public bool IsParameterControlledByCurve(int id) + { + return this.IsParameterControlledByCurveID(id); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rootPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rootPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rootRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rootRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bodyPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_bodyPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bodyRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_bodyRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector3 GetIKPosition(AvatarIKGoal goal); + public void SetIKPosition(AvatarIKGoal goal, Vector3 goalPosition) + { + Animator.INTERNAL_CALL_SetIKPosition(this, goal, ref goalPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetIKPosition(Animator self, AvatarIKGoal goal, ref Vector3 goalPosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Quaternion GetIKRotation(AvatarIKGoal goal); + public void SetIKRotation(AvatarIKGoal goal, Quaternion goalRotation) + { + Animator.INTERNAL_CALL_SetIKRotation(this, goal, ref goalRotation); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetIKRotation(Animator self, AvatarIKGoal goal, ref Quaternion goalRotation); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetIKPositionWeight(AvatarIKGoal goal); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetIKPositionWeight(AvatarIKGoal goal, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetIKRotationWeight(AvatarIKGoal goal); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetIKRotationWeight(AvatarIKGoal goal, float value); + public void SetLookAtPosition(Vector3 lookAtPosition) + { + Animator.INTERNAL_CALL_SetLookAtPosition(this, ref lookAtPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetLookAtPosition(Animator self, ref Vector3 lookAtPosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetLookAtWeight(float weight, [DefaultValue("0.00f")] float bodyWeight, [DefaultValue("1.00f")] float headWeight, [DefaultValue("0.00f")] float eyesWeight, [DefaultValue("0.50f")] float clampWeight); + [ExcludeFromDocs] + public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight) + { + float clampWeight = 0.5f; + this.SetLookAtWeight(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + public void SetLookAtWeight(float weight, float bodyWeight, float headWeight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + this.SetLookAtWeight(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + public void SetLookAtWeight(float weight, float bodyWeight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + float headWeight = 1f; + this.SetLookAtWeight(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + public void SetLookAtWeight(float weight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + float headWeight = 1f; + float bodyWeight = 0f; + this.SetLookAtWeight(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetLayerName(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetLayerWeight(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetLayerWeight(int layerIndex, float weight); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorStateInfo GetCurrentAnimatorStateInfo(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorStateInfo GetNextAnimatorStateInfo(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorTransitionInfo GetAnimatorTransitionInfo(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimationInfo[] GetCurrentAnimationClipState(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimationInfo[] GetNextAnimationClipState(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsInTransition(int layerIndex); + public void MatchTarget(Vector3 matchPosition, Quaternion matchRotation, AvatarTarget targetBodyPart, MatchTargetWeightMask weightMask, float startNormalizedTime, [DefaultValue("1")] float targetNormalizedTime) + { + Animator.INTERNAL_CALL_MatchTarget(this, ref matchPosition, ref matchRotation, targetBodyPart, ref weightMask, startNormalizedTime, targetNormalizedTime); + } + [ExcludeFromDocs] + public void MatchTarget(Vector3 matchPosition, Quaternion matchRotation, AvatarTarget targetBodyPart, MatchTargetWeightMask weightMask, float startNormalizedTime) + { + float targetNormalizedTime = 1f; + Animator.INTERNAL_CALL_MatchTarget(this, ref matchPosition, ref matchRotation, targetBodyPart, ref weightMask, startNormalizedTime, targetNormalizedTime); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MatchTarget(Animator self, ref Vector3 matchPosition, ref Quaternion matchRotation, AvatarTarget targetBodyPart, ref MatchTargetWeightMask weightMask, float startNormalizedTime, float targetNormalizedTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InterruptMatchTarget([DefaultValue("true")] bool completeMatch); + [ExcludeFromDocs] + public void InterruptMatchTarget() + { + bool completeMatch = true; + this.InterruptMatchTarget(completeMatch); + } + [Obsolete("ForceStateNormalizedTime is deprecated. Please use Play or CrossFade instead.")] + public void ForceStateNormalizedTime(float normalizedTime) + { + this.Play(0, 0, normalizedTime); + } + [ExcludeFromDocs] + public void CrossFade(string stateName, float transitionDuration, int layer) + { + float normalizedTime = float.NegativeInfinity; + this.CrossFade(stateName, transitionDuration, layer, normalizedTime); + } + [ExcludeFromDocs] + public void CrossFade(string stateName, float transitionDuration) + { + float normalizedTime = float.NegativeInfinity; + int layer = -1; + this.CrossFade(stateName, transitionDuration, layer, normalizedTime); + } + public void CrossFade(string stateName, float transitionDuration, [DefaultValue("-1")] int layer, [DefaultValue("float.NegativeInfinity")] float normalizedTime) + { + this.CrossFade(Animator.StringToHash(stateName), transitionDuration, layer, normalizedTime); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CrossFade(int stateNameHash, float transitionDuration, [DefaultValue("-1")] int layer, [DefaultValue("float.NegativeInfinity")] float normalizedTime); + [ExcludeFromDocs] + public void CrossFade(int stateNameHash, float transitionDuration, int layer) + { + float normalizedTime = float.NegativeInfinity; + this.CrossFade(stateNameHash, transitionDuration, layer, normalizedTime); + } + [ExcludeFromDocs] + public void CrossFade(int stateNameHash, float transitionDuration) + { + float normalizedTime = float.NegativeInfinity; + int layer = -1; + this.CrossFade(stateNameHash, transitionDuration, layer, normalizedTime); + } + [ExcludeFromDocs] + public void Play(string stateName, int layer) + { + float normalizedTime = float.NegativeInfinity; + this.Play(stateName, layer, normalizedTime); + } + [ExcludeFromDocs] + public void Play(string stateName) + { + float normalizedTime = float.NegativeInfinity; + int layer = -1; + this.Play(stateName, layer, normalizedTime); + } + public void Play(string stateName, [DefaultValue("-1")] int layer, [DefaultValue("float.NegativeInfinity")] float normalizedTime) + { + this.Play(Animator.StringToHash(stateName), layer, normalizedTime); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Play(int stateNameHash, [DefaultValue("-1")] int layer, [DefaultValue("float.NegativeInfinity")] float normalizedTime); + [ExcludeFromDocs] + public void Play(int stateNameHash, int layer) + { + float normalizedTime = float.NegativeInfinity; + this.Play(stateNameHash, layer, normalizedTime); + } + [ExcludeFromDocs] + public void Play(int stateNameHash) + { + float normalizedTime = float.NegativeInfinity; + int layer = -1; + this.Play(stateNameHash, layer, normalizedTime); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTarget(AvatarTarget targetIndex, float targetNormalizedTime); + [Obsolete("use mask and layers to control subset of transfroms in a skeleton", true), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsControlled(Transform transform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool IsBoneTransform(Transform transform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transform GetBoneTransform(HumanBodyBones humanBoneId); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StartPlayback(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StopPlayback(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StartRecording(int frameCount); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StopRecording(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int StringToHash(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetStats(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFloatString(string name, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFloatID(int id, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float GetFloatString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float GetFloatID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetBoolString(string name, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetBoolID(int id, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool GetBoolString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool GetBoolID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetIntegerString(string name, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetIntegerID(int id, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int GetIntegerString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int GetIntegerID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetTriggerString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetTriggerID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void ResetTriggerString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void ResetTriggerID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool IsParameterControlledByCurveString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool IsParameterControlledByCurveID(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFloatStringDamp(string name, float value, float dampTime, float deltaTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFloatIDDamp(int id, float value, float dampTime, float deltaTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void WriteDefaultPose(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Update(float deltaTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Rebind(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void EvaluateSM(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetCurrentStateName(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetNextStateName(int layerIndex); + [Obsolete("GetVector is deprecated.")] + public Vector3 GetVector(string name) + { + return Vector3.zero; + } + [Obsolete("GetVector is deprecated.")] + public Vector3 GetVector(int id) + { + return Vector3.zero; + } + [Obsolete("SetVector is deprecated.")] + public void SetVector(string name, Vector3 value) + { + } + [Obsolete("SetVector is deprecated.")] + public void SetVector(int id, Vector3 value) + { + } + [Obsolete("GetQuaternion is deprecated.")] + public Quaternion GetQuaternion(string name) + { + return Quaternion.identity; + } + [Obsolete("GetQuaternion is deprecated.")] + public Quaternion GetQuaternion(int id) + { + return Quaternion.identity; + } + [Obsolete("SetQuaternion is deprecated.")] + public void SetQuaternion(string name, Quaternion value) + { + } + [Obsolete("SetQuaternion is deprecated.")] + public void SetQuaternion(int id, Quaternion value) + { + } + } +} diff --git a/UnityEngine/UnityEngine/AnimatorCullingMode.cs b/UnityEngine/UnityEngine/AnimatorCullingMode.cs new file mode 100644 index 00000000..7a5fe2b9 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorCullingMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum AnimatorCullingMode + { + AlwaysAnimate, + BasedOnRenderers + } +} diff --git a/UnityEngine/UnityEngine/AnimatorOverrideController.cs b/UnityEngine/UnityEngine/AnimatorOverrideController.cs new file mode 100644 index 00000000..cfef4d84 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorOverrideController.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AnimatorOverrideController : RuntimeAnimatorController + { + internal delegate void OnOverrideControllerDirtyCallback(); + internal AnimatorOverrideController.OnOverrideControllerDirtyCallback OnOverrideControllerDirty; + public extern RuntimeAnimatorController runtimeAnimatorController + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AnimationClip this[string name] + { + get + { + return this.Internal_GetClipByName(name, true); + } + set + { + this.Internal_SetClipByName(name, value); + } + } + public AnimationClip this[AnimationClip clip] + { + get + { + return this.Internal_GetClip(clip, true); + } + set + { + this.Internal_SetClip(clip, value); + } + } + public AnimationClipPair[] clips + { + get + { + AnimationClip[] array = this.GetOriginalClips(); + if (this.ShouldHideDuplicateOriginalClips()) + { + Dictionary dictionary = new Dictionary(array.Length); + AnimationClip[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + AnimationClip key = array2[i]; + dictionary[key] = true; + } + array = new AnimationClip[dictionary.Count]; + dictionary.Keys.CopyTo(array, 0); + } + AnimationClipPair[] array3 = new AnimationClipPair[array.Length]; + for (int j = 0; j < array.Length; j++) + { + array3[j] = new AnimationClipPair(); + array3[j].originalClip = array[j]; + array3[j].overrideClip = this.Internal_GetClip(array[j], false); + } + return array3; + } + set + { + for (int i = 0; i < value.Length; i++) + { + this.Internal_SetClip(value[i].originalClip, value[i].overrideClip); + } + } + } + public AnimatorOverrideController() + { + AnimatorOverrideController.Internal_CreateAnimationSet(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAnimationSet([Writable] AnimatorOverrideController self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AnimationClip Internal_GetClipByName(string name, bool returnEffectiveClip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetClipByName(string name, AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AnimationClip Internal_GetClip(AnimationClip originalClip, bool returnEffectiveClip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetClip(AnimationClip originalClip, AnimationClip overrideClip); + internal static void OnInvalidateOverrideController(AnimatorOverrideController controller) + { + if (controller.OnOverrideControllerDirty != null) + { + controller.OnOverrideControllerDirty(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool ShouldHideDuplicateOriginalClips(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AnimationClip[] GetOriginalClips(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AnimationClip[] GetOverrideClips(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PerformOverrideClipListCleanup(); + } +} diff --git a/UnityEngine/UnityEngine/AnimatorStateInfo.cs b/UnityEngine/UnityEngine/AnimatorStateInfo.cs new file mode 100644 index 00000000..291c5eeb --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorStateInfo.cs @@ -0,0 +1,57 @@ +using System; +namespace UnityEngine +{ + public struct AnimatorStateInfo + { + private int m_Name; + private int m_Path; + private float m_NormalizedTime; + private float m_Length; + private int m_Tag; + private int m_Loop; + public int nameHash + { + get + { + return this.m_Path; + } + } + public float normalizedTime + { + get + { + return this.m_NormalizedTime; + } + } + public float length + { + get + { + return this.m_Length; + } + } + public int tagHash + { + get + { + return this.m_Tag; + } + } + public bool loop + { + get + { + return this.m_Loop != 0; + } + } + public bool IsName(string name) + { + int num = Animator.StringToHash(name); + return num == this.m_Name || num == this.m_Path; + } + public bool IsTag(string tag) + { + return Animator.StringToHash(tag) == this.m_Tag; + } + } +} diff --git a/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs b/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs new file mode 100644 index 00000000..be4cba1f --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs @@ -0,0 +1,39 @@ +using System; +namespace UnityEngine +{ + public struct AnimatorTransitionInfo + { + private int m_Name; + private int m_UserName; + private float m_NormalizedTime; + public int nameHash + { + get + { + return this.m_Name; + } + } + public int userNameHash + { + get + { + return this.m_UserName; + } + } + public float normalizedTime + { + get + { + return this.m_NormalizedTime; + } + } + public bool IsName(string name) + { + return Animator.StringToHash(name) == this.m_Name; + } + public bool IsUserName(string name) + { + return Animator.StringToHash(name) == this.m_UserName; + } + } +} diff --git a/UnityEngine/UnityEngine/AnimatorUpdateMode.cs b/UnityEngine/UnityEngine/AnimatorUpdateMode.cs new file mode 100644 index 00000000..8fd79783 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorUpdateMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AnimatorUpdateMode + { + Normal, + AnimatePhysics, + UnscaledTime + } +} diff --git a/UnityEngine/UnityEngine/AnimatorUtility.cs b/UnityEngine/UnityEngine/AnimatorUtility.cs new file mode 100644 index 00000000..62e4501e --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorUtility.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AnimatorUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OptimizeTransformHierarchy(GameObject go, string[] exposedTransforms); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeoptimizeTransformHierarchy(GameObject go); + } +} diff --git a/UnityEngine/UnityEngine/AnisotropicFiltering.cs b/UnityEngine/UnityEngine/AnisotropicFiltering.cs new file mode 100644 index 00000000..204ff740 --- /dev/null +++ b/UnityEngine/UnityEngine/AnisotropicFiltering.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AnisotropicFiltering + { + Disable, + Enable, + ForceEnable + } +} diff --git a/UnityEngine/UnityEngine/Application.cs b/UnityEngine/UnityEngine/Application.cs new file mode 100644 index 00000000..e310f7f2 --- /dev/null +++ b/UnityEngine/UnityEngine/Application.cs @@ -0,0 +1,434 @@ +using System; +using System.Collections; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Security; +using System.Text; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Application + { + public delegate void LogCallback(string condition, string stackTrace, LogType type); + private static volatile Application.LogCallback s_LogCallback; + public static extern int loadedLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string loadedLevelName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isLoadingLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int levelCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int streamedBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isEditor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isWebPlayer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern RuntimePlatform platform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static bool isMobilePlatform + { + get + { + RuntimePlatform platform = Application.platform; + return platform == RuntimePlatform.IPhonePlayer || platform == RuntimePlatform.Android || platform == RuntimePlatform.WP8Player || platform == RuntimePlatform.BB10Player || platform == RuntimePlatform.TizenPlayer; + } + } + public static bool isConsolePlatform + { + get + { + RuntimePlatform platform = Application.platform; + return platform == RuntimePlatform.PS3 || platform == RuntimePlatform.PS4 || platform == RuntimePlatform.XBOX360 || platform == RuntimePlatform.XboxOne; + } + } + public static extern bool runInBackground + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("use Application.isEditor instead")] + public static bool isPlayer + { + get + { + return !Application.isEditor; + } + } + public static extern string dataPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string streamingAssetsPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [SecurityCritical] + public static extern string persistentDataPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string temporaryCachePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string srcValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string absoluteURL + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Please use absoluteURL instead")] + public static string absoluteUrl + { + get + { + return Application.absoluteURL; + } + } + public static extern string unityVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool webSecurityEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string webSecurityHostUrl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int targetFrameRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern SystemLanguage systemLanguage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ThreadPriority backgroundLoadingPriority + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern NetworkReachability internetReachability + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool genuine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool genuineCheckAvailable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Quit(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CancelQuit(); + public static void LoadLevel(int index) + { + Application.LoadLevelAsync(null, index, false, true); + } + public static void LoadLevel(string name) + { + Application.LoadLevelAsync(name, -1, false, true); + } + public static AsyncOperation LoadLevelAsync(int index) + { + return Application.LoadLevelAsync(null, index, false, false); + } + public static AsyncOperation LoadLevelAsync(string levelName) + { + return Application.LoadLevelAsync(levelName, -1, false, false); + } + public static AsyncOperation LoadLevelAdditiveAsync(int index) + { + return Application.LoadLevelAsync(null, index, true, false); + } + public static AsyncOperation LoadLevelAdditiveAsync(string levelName) + { + return Application.LoadLevelAsync(levelName, -1, true, false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AsyncOperation LoadLevelAsync(string monoLevelName, int index, bool additive, bool mustCompleteNextFrame); + public static void LoadLevelAdditive(int index) + { + Application.LoadLevelAsync(null, index, true, true); + } + public static void LoadLevelAdditive(string name) + { + Application.LoadLevelAsync(name, -1, true, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float GetStreamProgressForLevelByName(string levelName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetStreamProgressForLevel(int levelIndex); + public static float GetStreamProgressForLevel(string levelName) + { + return Application.GetStreamProgressForLevelByName(levelName); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool CanStreamedLevelBeLoadedByName(string levelName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CanStreamedLevelBeLoaded(int levelIndex); + public static bool CanStreamedLevelBeLoaded(string levelName) + { + return Application.CanStreamedLevelBeLoadedByName(levelName); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CaptureScreenshot(string filename, [DefaultValue("0")] int superSize); + [ExcludeFromDocs] + public static void CaptureScreenshot(string filename) + { + int superSize = 0; + Application.CaptureScreenshot(filename, superSize); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasProLicense(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasAdvancedLicense(); + [Obsolete("Use Object.DontDestroyOnLoad instead"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DontDestroyOnLoad(Object mono); + private static string ObjectToJSString(object o) + { + if (o == null) + { + return "null"; + } + if (o is string) + { + string text = o.ToString().Replace("\\", "\\\\"); + text = text.Replace("\"", "\\\""); + text = text.Replace("\n", "\\n"); + text = text.Replace("\r", "\\r"); + text = text.Replace("\0", string.Empty); + text = text.Replace("\u2028", string.Empty); + text = text.Replace("\u2029", string.Empty); + return '"' + text + '"'; + } + if (o is int || o is short || o is uint || o is ushort || o is byte) + { + return o.ToString(); + } + if (o is float) + { + NumberFormatInfo numberFormat = CultureInfo.InvariantCulture.NumberFormat; + return ((float)o).ToString(numberFormat); + } + if (o is double) + { + NumberFormatInfo numberFormat2 = CultureInfo.InvariantCulture.NumberFormat; + return ((double)o).ToString(numberFormat2); + } + if (o is char) + { + if ((char)o == '"') + { + return "\"\\\"\""; + } + return '"' + o.ToString() + '"'; + } + else + { + if (o is IList) + { + IList list = (IList)o; + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("new Array("); + int count = list.Count; + for (int i = 0; i < count; i++) + { + if (i != 0) + { + stringBuilder.Append(", "); + } + stringBuilder.Append(Application.ObjectToJSString(list[i])); + } + stringBuilder.Append(")"); + return stringBuilder.ToString(); + } + return Application.ObjectToJSString(o.ToString()); + } + } + public static void ExternalCall(string functionName, params object[] args) + { + Application.Internal_ExternalCall(Application.BuildInvocationForArguments(functionName, args)); + } + private static string BuildInvocationForArguments(string functionName, params object[] args) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(functionName); + stringBuilder.Append('('); + int num = args.Length; + for (int i = 0; i < num; i++) + { + if (i != 0) + { + stringBuilder.Append(", "); + } + stringBuilder.Append(Application.ObjectToJSString(args[i])); + } + stringBuilder.Append(')'); + stringBuilder.Append(';'); + return stringBuilder.ToString(); + } + public static void ExternalEval(string script) + { + if (script.Length > 0 && script[script.Length - 1] != ';') + { + script += ';'; + } + Application.Internal_ExternalCall(script); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_ExternalCall(string script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetBuildUnityVersion(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetNumericUnityVersion(string version); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OpenURL(string url); + [Obsolete("For internal use only"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CommitSuicide(int mode); + public static void RegisterLogCallback(Application.LogCallback handler) + { + Application.s_LogCallback = handler; + Application.SetLogCallbackDefined(handler != null, false); + } + public static void RegisterLogCallbackThreaded(Application.LogCallback handler) + { + Application.s_LogCallback = handler; + Application.SetLogCallbackDefined(handler != null, true); + } + private static void CallLogCallback(string logString, string stackTrace, LogType type) + { + if (Application.s_LogCallback != null) + { + Application.s_LogCallback(logString, stackTrace, type); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetLogCallbackDefined(bool defined, bool threaded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AsyncOperation RequestUserAuthorization(UserAuthorization mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasUserAuthorization(UserAuthorization mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ReplyToUserAuthorizationRequest(bool reply, [DefaultValue("false")] bool remember); + [ExcludeFromDocs] + internal static void ReplyToUserAuthorizationRequest(bool reply) + { + bool remember = false; + Application.ReplyToUserAuthorizationRequest(reply, remember); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int GetUserAuthorizationRequestMode_Internal(); + internal static UserAuthorization GetUserAuthorizationRequestMode() + { + return (UserAuthorization)Application.GetUserAuthorizationRequestMode_Internal(); + } + } +} diff --git a/UnityEngine/UnityEngine/ArmDoF.cs b/UnityEngine/UnityEngine/ArmDoF.cs new file mode 100644 index 00000000..bd453917 --- /dev/null +++ b/UnityEngine/UnityEngine/ArmDoF.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEngine +{ + internal enum ArmDoF + { + ShoulderDownUp, + ShoulderFrontBack, + ArmDownUp, + ArmFrontBack, + ArmRollInOut, + ForeArmCloseOpen, + ForeArmRollInOut, + HandDownUp, + HandInOut, + LastArmDoF + } +} diff --git a/UnityEngine/UnityEngine/AssemblyIsEditorAssembly.cs b/UnityEngine/UnityEngine/AssemblyIsEditorAssembly.cs new file mode 100644 index 00000000..fc3ccdec --- /dev/null +++ b/UnityEngine/UnityEngine/AssemblyIsEditorAssembly.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Assembly)] + public class AssemblyIsEditorAssembly : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/AssetBundle.cs b/UnityEngine/UnityEngine/AssetBundle.cs new file mode 100644 index 00000000..407f31da --- /dev/null +++ b/UnityEngine/UnityEngine/AssetBundle.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngineInternal; +namespace UnityEngine +{ + public sealed class AssetBundle : Object + { + public extern Object mainAsset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetBundleCreateRequest CreateFromMemory(byte[] binary); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetBundle CreateFromMemoryImmediate(byte[] binary); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AssetBundle CreateFromFile(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Contains(string name); + public Object Load(string name) + { + return this.Load(name, typeof(Object)); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Object Load(string name, Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AssetBundleRequest LoadAsync(string name, Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Object[] LoadAll(Type type); + public Object[] LoadAll() + { + return this.LoadAll(typeof(Object)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Unload(bool unloadAllLoadedObjects); + } +} diff --git a/UnityEngine/UnityEngine/AssetBundleCreateRequest.cs b/UnityEngine/UnityEngine/AssetBundleCreateRequest.cs new file mode 100644 index 00000000..358be469 --- /dev/null +++ b/UnityEngine/UnityEngine/AssetBundleCreateRequest.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AssetBundleCreateRequest : AsyncOperation + { + public extern AssetBundle assetBundle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void DisableCompatibilityChecks(); + } +} diff --git a/UnityEngine/UnityEngine/AssetBundleRequest.cs b/UnityEngine/UnityEngine/AssetBundleRequest.cs new file mode 100644 index 00000000..18838919 --- /dev/null +++ b/UnityEngine/UnityEngine/AssetBundleRequest.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class AssetBundleRequest : AsyncOperation + { + internal AssetBundle m_AssetBundle; + internal string m_Path; + internal Type m_Type; + public Object asset + { + get + { + return this.m_AssetBundle.Load(this.m_Path, this.m_Type); + } + } + } +} diff --git a/UnityEngine/UnityEngine/AsyncOperation.cs b/UnityEngine/UnityEngine/AsyncOperation.cs new file mode 100644 index 00000000..d31a8c0f --- /dev/null +++ b/UnityEngine/UnityEngine/AsyncOperation.cs @@ -0,0 +1,49 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class AsyncOperation : YieldInstruction + { + [NotRenamed] + internal IntPtr m_Ptr; + public extern bool isDone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float progress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int priority + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool allowSceneActivation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalDestroy(); + ~AsyncOperation() + { + this.InternalDestroy(); + } + } +} diff --git a/UnityEngine/UnityEngine/AttributeHelperEngine.cs b/UnityEngine/UnityEngine/AttributeHelperEngine.cs new file mode 100644 index 00000000..4fbddeea --- /dev/null +++ b/UnityEngine/UnityEngine/AttributeHelperEngine.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +namespace UnityEngine +{ + internal class AttributeHelperEngine + { + private static Type GetParentTypeDisallowingMultipleInclusion(Type type) + { + Stack stack = new Stack(); + while (type != null && type != typeof(MonoBehaviour)) + { + stack.Push(type); + type = type.BaseType; + } + while (stack.Count > 0) + { + Type type2 = stack.Pop(); + object[] customAttributes = type2.GetCustomAttributes(typeof(DisallowMultipleComponent), false); + if (customAttributes.Length != 0) + { + return type2; + } + } + return null; + } + private static Type[] GetRequiredComponents(Type klass) + { + List list = null; + while (klass != null && klass != typeof(MonoBehaviour)) + { + object[] customAttributes = klass.GetCustomAttributes(typeof(RequireComponent), false); + for (int i = 0; i < customAttributes.Length; i++) + { + RequireComponent requireComponent = (RequireComponent)customAttributes[i]; + if (list == null && customAttributes.Length == 1 && klass.BaseType == typeof(MonoBehaviour)) + { + return new Type[] + { + requireComponent.m_Type0, + requireComponent.m_Type1, + requireComponent.m_Type2 + }; + } + if (list == null) + { + list = new List(); + } + if (requireComponent.m_Type0 != null) + { + list.Add(requireComponent.m_Type0); + } + if (requireComponent.m_Type1 != null) + { + list.Add(requireComponent.m_Type1); + } + if (requireComponent.m_Type2 != null) + { + list.Add(requireComponent.m_Type2); + } + } + klass = klass.BaseType; + } + if (list == null) + { + return null; + } + return list.ToArray(); + } + private static bool CheckIsEditorScript(Type klass) + { + while (klass != null && klass != typeof(MonoBehaviour)) + { + object[] customAttributes = klass.GetCustomAttributes(typeof(ExecuteInEditMode), false); + if (customAttributes.Length != 0) + { + return true; + } + klass = klass.BaseType; + } + return false; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioChorusFilter.cs b/UnityEngine/UnityEngine/AudioChorusFilter.cs new file mode 100644 index 00000000..7434c5ab --- /dev/null +++ b/UnityEngine/UnityEngine/AudioChorusFilter.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioChorusFilter : Behaviour + { + public extern float dryMix + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wetMix1 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wetMix2 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wetMix3 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float delay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float rate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("feedback is deprecated, this property does nothing.")] + public extern float feedback + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioClip.cs b/UnityEngine/UnityEngine/AudioClip.cs new file mode 100644 index 00000000..aff23bc5 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioClip.cs @@ -0,0 +1,132 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioClip : Object + { + public delegate void PCMReaderCallback(float[] data); + public delegate void PCMSetPositionCallback(int position); + private event AudioClip.PCMReaderCallback m_PCMReaderCallback + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.m_PCMReaderCallback = (AudioClip.PCMReaderCallback)Delegate.Combine(this.m_PCMReaderCallback, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.m_PCMReaderCallback = (AudioClip.PCMReaderCallback)Delegate.Remove(this.m_PCMReaderCallback, value); + } + } + private event AudioClip.PCMSetPositionCallback m_PCMSetPositionCallback + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.m_PCMSetPositionCallback = (AudioClip.PCMSetPositionCallback)Delegate.Combine(this.m_PCMSetPositionCallback, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.m_PCMSetPositionCallback = (AudioClip.PCMSetPositionCallback)Delegate.Remove(this.m_PCMSetPositionCallback, value); + } + } + public extern float length + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int samples + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int channels + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int frequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isReadyToPlay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void GetData(float[] data, int offsetSamples); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetData(float[] data, int offsetSamples); + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream) + { + return AudioClip.Create(name, lengthSamples, channels, frequency, _3D, stream, null, null); + } + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, AudioClip.PCMReaderCallback pcmreadercallback) + { + return AudioClip.Create(name, lengthSamples, channels, frequency, _3D, stream, pcmreadercallback, null); + } + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, AudioClip.PCMReaderCallback pcmreadercallback, AudioClip.PCMSetPositionCallback pcmsetpositioncallback) + { + if (name == null) + { + throw new NullReferenceException(); + } + if (lengthSamples <= 0) + { + throw new ArgumentException("Length of created clip must be larger than 0"); + } + if (channels <= 0) + { + throw new ArgumentException("Number of channels in created clip must be greater than 0"); + } + if (frequency <= 0) + { + throw new ArgumentException("Frequency in created clip must be greater than 0"); + } + AudioClip audioClip = AudioClip.Construct_Internal(); + if (pcmreadercallback != null) + { + AudioClip expr_50 = audioClip; + expr_50.m_PCMReaderCallback = (AudioClip.PCMReaderCallback)Delegate.Combine(expr_50.m_PCMReaderCallback, pcmreadercallback); + } + if (pcmsetpositioncallback != null) + { + AudioClip expr_6F = audioClip; + expr_6F.m_PCMSetPositionCallback = (AudioClip.PCMSetPositionCallback)Delegate.Combine(expr_6F.m_PCMSetPositionCallback, pcmsetpositioncallback); + } + audioClip.Init_Internal(name, lengthSamples, channels, frequency, _3D, stream); + return audioClip; + } + private void InvokePCMReaderCallback_Internal(float[] data) + { + if (this.m_PCMReaderCallback != null) + { + this.m_PCMReaderCallback(data); + } + } + private void InvokePCMSetPositionCallback_Internal(int position) + { + if (this.m_PCMSetPositionCallback != null) + { + this.m_PCMSetPositionCallback(position); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AudioClip Construct_Internal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init_Internal(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream); + } +} diff --git a/UnityEngine/UnityEngine/AudioDistortionFilter.cs b/UnityEngine/UnityEngine/AudioDistortionFilter.cs new file mode 100644 index 00000000..1ac297ed --- /dev/null +++ b/UnityEngine/UnityEngine/AudioDistortionFilter.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioDistortionFilter : Behaviour + { + public extern float distortionLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioEchoFilter.cs b/UnityEngine/UnityEngine/AudioEchoFilter.cs new file mode 100644 index 00000000..4cbe870b --- /dev/null +++ b/UnityEngine/UnityEngine/AudioEchoFilter.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioEchoFilter : Behaviour + { + public extern float delay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float decayRatio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float dryMix + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wetMix + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioHighPassFilter.cs b/UnityEngine/UnityEngine/AudioHighPassFilter.cs new file mode 100644 index 00000000..b7f488fd --- /dev/null +++ b/UnityEngine/UnityEngine/AudioHighPassFilter.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioHighPassFilter : Behaviour + { + public extern float cutoffFrequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float highpassResonaceQ + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioListener.cs b/UnityEngine/UnityEngine/AudioListener.cs new file mode 100644 index 00000000..0419f9c2 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioListener.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioListener : Behaviour + { + public static extern float volume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool pause + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioVelocityUpdateMode velocityUpdateMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetOutputDataHelper(float[] samples, int channel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetSpectrumDataHelper(float[] samples, int channel, FFTWindow window); + [Obsolete("GetOutputData returning a float[] is deprecated, use GetOutputData and pass a pre allocated array instead.")] + public static float[] GetOutputData(int numSamples, int channel) + { + float[] array = new float[numSamples]; + AudioListener.GetOutputDataHelper(array, channel); + return array; + } + public static void GetOutputData(float[] samples, int channel) + { + AudioListener.GetOutputDataHelper(samples, channel); + } + [Obsolete("GetSpectrumData returning a float[] is deprecated, use GetOutputData and pass a pre allocated array instead.")] + public static float[] GetSpectrumData(int numSamples, int channel, FFTWindow window) + { + float[] array = new float[numSamples]; + AudioListener.GetSpectrumDataHelper(array, channel, window); + return array; + } + public static void GetSpectrumData(float[] samples, int channel, FFTWindow window) + { + AudioListener.GetSpectrumDataHelper(samples, channel, window); + } + } +} diff --git a/UnityEngine/UnityEngine/AudioLowPassFilter.cs b/UnityEngine/UnityEngine/AudioLowPassFilter.cs new file mode 100644 index 00000000..420d2075 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioLowPassFilter.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioLowPassFilter : Behaviour + { + public extern float cutoffFrequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lowpassResonaceQ + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioReverbFilter.cs b/UnityEngine/UnityEngine/AudioReverbFilter.cs new file mode 100644 index 00000000..319441c7 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioReverbFilter.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioReverbFilter : Behaviour + { + public extern AudioReverbPreset reverbPreset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float dryLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float room + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float roomHF + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float roomRolloff + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float decayTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float decayHFRatio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reflectionsLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reflectionsDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reverbLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reverbDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float diffusion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float density + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float hfReference + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float roomLF + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lFReference + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioReverbPreset.cs b/UnityEngine/UnityEngine/AudioReverbPreset.cs new file mode 100644 index 00000000..7c294035 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioReverbPreset.cs @@ -0,0 +1,35 @@ +using System; +namespace UnityEngine +{ + public enum AudioReverbPreset + { + Off, + Generic, + PaddedCell, + Room, + Bathroom, + Livingroom, + Stoneroom, + Auditorium, + Concerthall, + Cave, + Arena, + Hangar, + CarpetedHallway, + Hallway, + StoneCorridor, + Alley, + Forest, + City, + Mountains, + Quarry, + Plain, + ParkingLot, + SewerPipe, + Underwater, + Drugged, + Dizzy, + Psychotic, + User + } +} diff --git a/UnityEngine/UnityEngine/AudioReverbZone.cs b/UnityEngine/UnityEngine/AudioReverbZone.cs new file mode 100644 index 00000000..196b8571 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioReverbZone.cs @@ -0,0 +1,161 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioReverbZone : Behaviour + { + public extern float minDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioReverbPreset reverbPreset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int room + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int roomHF + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int roomLF + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float decayTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float decayHFRatio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int reflections + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reflectionsDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int reverb + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reverbDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float HFReference + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float LFReference + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float roomRolloffFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float diffusion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float density + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AudioRolloffMode.cs b/UnityEngine/UnityEngine/AudioRolloffMode.cs new file mode 100644 index 00000000..93c47bd2 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioRolloffMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AudioRolloffMode + { + Logarithmic, + Linear, + Custom + } +} diff --git a/UnityEngine/UnityEngine/AudioSettings.cs b/UnityEngine/UnityEngine/AudioSettings.cs new file mode 100644 index 00000000..1dbb1b99 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioSettings.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AudioSettings + { + public static extern AudioSpeakerMode driverCaps + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern AudioSpeakerMode speakerMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern double dspTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int outputSampleRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetDSPBufferSize(int bufferLength, int numBuffers); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetDSPBufferSize(out int bufferLength, out int numBuffers); + } +} diff --git a/UnityEngine/UnityEngine/AudioSource.cs b/UnityEngine/UnityEngine/AudioSource.cs new file mode 100644 index 00000000..566096a3 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioSource.cs @@ -0,0 +1,327 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class AudioSource : Behaviour + { + public extern float volume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pitch + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int timeSamples + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioClip clip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool loop + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool ignoreListenerVolume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool playOnAwake + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool ignoreListenerPause + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioVelocityUpdateMode velocityUpdateMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float panLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bypassEffects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bypassListenerEffects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bypassReverbZones + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float dopplerLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float spread + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int priority + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mute + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pan + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioRolloffMode rolloffMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("minVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] + public extern float minVolume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("maxVolume is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] + public extern float maxVolume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("rolloffFactor is not supported anymore. Use min-, maxDistance and rolloffMode instead.", true)] + public extern float rolloffFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Play([DefaultValue("0")] ulong delay); + [ExcludeFromDocs] + public void Play() + { + ulong delay = 0uL; + this.Play(delay); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PlayDelayed(float delay); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PlayScheduled(double time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetScheduledStartTime(double time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetScheduledEndTime(double time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Stop(); + public void Pause() + { + AudioSource.INTERNAL_CALL_Pause(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Pause(AudioSource self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PlayOneShot(AudioClip clip, [DefaultValue("1.0F")] float volumeScale); + [ExcludeFromDocs] + public void PlayOneShot(AudioClip clip) + { + float volumeScale = 1f; + this.PlayOneShot(clip, volumeScale); + } + [ExcludeFromDocs] + public static void PlayClipAtPoint(AudioClip clip, Vector3 position) + { + float volume = 1f; + AudioSource.PlayClipAtPoint(clip, position, volume); + } + public static void PlayClipAtPoint(AudioClip clip, Vector3 position, [DefaultValue("1.0F")] float volume) + { + GameObject gameObject = new GameObject("One shot audio"); + gameObject.transform.position = position; + AudioSource audioSource = (AudioSource)gameObject.AddComponent(typeof(AudioSource)); + audioSource.clip = clip; + audioSource.volume = volume; + audioSource.Play(); + Object.Destroy(gameObject, clip.length * Time.timeScale); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetOutputDataHelper(float[] samples, int channel); + [Obsolete("GetOutputData return a float[] is deprecated, use GetOutputData passing a pre allocated array instead.")] + public float[] GetOutputData(int numSamples, int channel) + { + float[] array = new float[numSamples]; + this.GetOutputDataHelper(array, channel); + return array; + } + public void GetOutputData(float[] samples, int channel) + { + this.GetOutputDataHelper(samples, channel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetSpectrumDataHelper(float[] samples, int channel, FFTWindow window); + [Obsolete("GetSpectrumData returning a float[] is deprecated, use GetSpectrumData passing a pre allocated array instead.")] + public float[] GetSpectrumData(int numSamples, int channel, FFTWindow window) + { + float[] array = new float[numSamples]; + this.GetSpectrumDataHelper(array, channel, window); + return array; + } + public void GetSpectrumData(float[] samples, int channel, FFTWindow window) + { + this.GetSpectrumDataHelper(samples, channel, window); + } + } +} diff --git a/UnityEngine/UnityEngine/AudioSpeakerMode.cs b/UnityEngine/UnityEngine/AudioSpeakerMode.cs new file mode 100644 index 00000000..3956c67f --- /dev/null +++ b/UnityEngine/UnityEngine/AudioSpeakerMode.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + public enum AudioSpeakerMode + { + Raw, + Mono, + Stereo, + Quad, + Surround, + Mode5point1, + Mode7point1, + Prologic + } +} diff --git a/UnityEngine/UnityEngine/AudioType.cs b/UnityEngine/UnityEngine/AudioType.cs new file mode 100644 index 00000000..df078423 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioType.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine +{ + public enum AudioType + { + UNKNOWN, + ACC, + AIFF, + IT = 10, + MOD = 12, + MPEG, + OGGVORBIS, + S3M = 17, + WAV = 20, + XM, + XMA, + VAG, + AUDIOQUEUE + } +} diff --git a/UnityEngine/UnityEngine/AudioVelocityUpdateMode.cs b/UnityEngine/UnityEngine/AudioVelocityUpdateMode.cs new file mode 100644 index 00000000..fb6027ef --- /dev/null +++ b/UnityEngine/UnityEngine/AudioVelocityUpdateMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AudioVelocityUpdateMode + { + Auto, + Fixed, + Dynamic + } +} diff --git a/UnityEngine/UnityEngine/Avatar.cs b/UnityEngine/UnityEngine/Avatar.cs new file mode 100644 index 00000000..acd2c64d --- /dev/null +++ b/UnityEngine/UnityEngine/Avatar.cs @@ -0,0 +1,52 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Avatar : Object + { + public extern bool isValid + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isHuman + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetMuscleMinMax(int muscleId, float min, float max); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetParameter(int parameterId, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetAxisLength(int humanId); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Quaternion GetPreRotation(int humanId); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Quaternion GetPostRotation(int humanId); + internal Quaternion GetZYPostQ(int humanId, Quaternion parentQ, Quaternion q) + { + return Avatar.INTERNAL_CALL_GetZYPostQ(this, humanId, ref parentQ, ref q); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_GetZYPostQ(Avatar self, int humanId, ref Quaternion parentQ, ref Quaternion q); + internal Quaternion GetZYRoll(int humanId, Vector3 uvw) + { + return Avatar.INTERNAL_CALL_GetZYRoll(this, humanId, ref uvw); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_GetZYRoll(Avatar self, int humanId, ref Vector3 uvw); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Vector3 GetLimitSign(int humanId); + } +} diff --git a/UnityEngine/UnityEngine/AvatarBuilder.cs b/UnityEngine/UnityEngine/AvatarBuilder.cs new file mode 100644 index 00000000..9421e75e --- /dev/null +++ b/UnityEngine/UnityEngine/AvatarBuilder.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AvatarBuilder + { + public static Avatar BuildHumanAvatar(GameObject go, HumanDescription monoHumanDescription) + { + return AvatarBuilder.INTERNAL_CALL_BuildHumanAvatar(go, ref monoHumanDescription); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Avatar INTERNAL_CALL_BuildHumanAvatar(GameObject go, ref HumanDescription monoHumanDescription); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Avatar BuildGenericAvatar(GameObject go, string rootMotionTransformName); + } +} diff --git a/UnityEngine/UnityEngine/AvatarIKGoal.cs b/UnityEngine/UnityEngine/AvatarIKGoal.cs new file mode 100644 index 00000000..ff16e134 --- /dev/null +++ b/UnityEngine/UnityEngine/AvatarIKGoal.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum AvatarIKGoal + { + LeftFoot, + RightFoot, + LeftHand, + RightHand + } +} diff --git a/UnityEngine/UnityEngine/AvatarTarget.cs b/UnityEngine/UnityEngine/AvatarTarget.cs new file mode 100644 index 00000000..ad0b68ca --- /dev/null +++ b/UnityEngine/UnityEngine/AvatarTarget.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum AvatarTarget + { + Root, + Body, + LeftFoot, + RightFoot, + LeftHand, + RightHand + } +} diff --git a/UnityEngine/UnityEngine/Behaviour.cs b/UnityEngine/UnityEngine/Behaviour.cs new file mode 100644 index 00000000..a4c74ad0 --- /dev/null +++ b/UnityEngine/UnityEngine/Behaviour.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Behaviour : Component + { + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isActiveAndEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + } +} diff --git a/UnityEngine/UnityEngine/BitStream.cs b/UnityEngine/UnityEngine/BitStream.cs new file mode 100644 index 00000000..bd8f4c35 --- /dev/null +++ b/UnityEngine/UnityEngine/BitStream.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class BitStream + { + internal IntPtr m_Ptr; + public extern bool isReading + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isWriting + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serializeb(ref int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serializec(ref char value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serializes(ref short value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serializei(ref int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serializef(ref float value, float maximumDelta); + private void Serializeq(ref Quaternion value, float maximumDelta) + { + BitStream.INTERNAL_CALL_Serializeq(this, ref value, maximumDelta); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Serializeq(BitStream self, ref Quaternion value, float maximumDelta); + private void Serializev(ref Vector3 value, float maximumDelta) + { + BitStream.INTERNAL_CALL_Serializev(this, ref value, maximumDelta); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Serializev(BitStream self, ref Vector3 value, float maximumDelta); + private void Serializen(ref NetworkViewID viewID) + { + BitStream.INTERNAL_CALL_Serializen(this, ref viewID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Serializen(BitStream self, ref NetworkViewID viewID); + public void Serialize(ref bool value) + { + int num = (!value) ? 0 : 1; + this.Serializeb(ref num); + value = (num != 0); + } + public void Serialize(ref char value) + { + this.Serializec(ref value); + } + public void Serialize(ref short value) + { + this.Serializes(ref value); + } + public void Serialize(ref int value) + { + this.Serializei(ref value); + } + [ExcludeFromDocs] + public void Serialize(ref float value) + { + float maxDelta = 1E-05f; + this.Serialize(ref value, maxDelta); + } + public void Serialize(ref float value, [DefaultValue("0.00001F")] float maxDelta) + { + this.Serializef(ref value, maxDelta); + } + [ExcludeFromDocs] + public void Serialize(ref Quaternion value) + { + float maxDelta = 1E-05f; + this.Serialize(ref value, maxDelta); + } + public void Serialize(ref Quaternion value, [DefaultValue("0.00001F")] float maxDelta) + { + this.Serializeq(ref value, maxDelta); + } + [ExcludeFromDocs] + public void Serialize(ref Vector3 value) + { + float maxDelta = 1E-05f; + this.Serialize(ref value, maxDelta); + } + public void Serialize(ref Vector3 value, [DefaultValue("0.00001F")] float maxDelta) + { + this.Serializev(ref value, maxDelta); + } + public void Serialize(ref NetworkPlayer value) + { + int index = value.index; + this.Serializei(ref index); + value.index = index; + } + public void Serialize(ref NetworkViewID viewID) + { + this.Serializen(ref viewID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Serialize(ref string value); + } +} diff --git a/UnityEngine/UnityEngine/BlendWeights.cs b/UnityEngine/UnityEngine/BlendWeights.cs new file mode 100644 index 00000000..eb5c44ac --- /dev/null +++ b/UnityEngine/UnityEngine/BlendWeights.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum BlendWeights + { + OneBone = 1, + TwoBones, + FourBones = 4 + } +} diff --git a/UnityEngine/UnityEngine/BodyDoF.cs b/UnityEngine/UnityEngine/BodyDoF.cs new file mode 100644 index 00000000..6b9ce01b --- /dev/null +++ b/UnityEngine/UnityEngine/BodyDoF.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + internal enum BodyDoF + { + SpineFrontBack, + SpineLeftRight, + SpineRollLeftRight, + ChestFrontBack, + ChestLeftRight, + ChestRollLeftRight, + LastBodyDoF + } +} diff --git a/UnityEngine/UnityEngine/BoneWeight.cs b/UnityEngine/UnityEngine/BoneWeight.cs new file mode 100644 index 00000000..50d0d54c --- /dev/null +++ b/UnityEngine/UnityEngine/BoneWeight.cs @@ -0,0 +1,134 @@ +using System; +namespace UnityEngine +{ + public struct BoneWeight + { + private float m_Weight0; + private float m_Weight1; + private float m_Weight2; + private float m_Weight3; + private int m_BoneIndex0; + private int m_BoneIndex1; + private int m_BoneIndex2; + private int m_BoneIndex3; + public float weight0 + { + get + { + return this.m_Weight0; + } + set + { + this.m_Weight0 = value; + } + } + public float weight1 + { + get + { + return this.m_Weight1; + } + set + { + this.m_Weight1 = value; + } + } + public float weight2 + { + get + { + return this.m_Weight2; + } + set + { + this.m_Weight2 = value; + } + } + public float weight3 + { + get + { + return this.m_Weight3; + } + set + { + this.m_Weight3 = value; + } + } + public int boneIndex0 + { + get + { + return this.m_BoneIndex0; + } + set + { + this.m_BoneIndex0 = value; + } + } + public int boneIndex1 + { + get + { + return this.m_BoneIndex1; + } + set + { + this.m_BoneIndex1 = value; + } + } + public int boneIndex2 + { + get + { + return this.m_BoneIndex2; + } + set + { + this.m_BoneIndex2 = value; + } + } + public int boneIndex3 + { + get + { + return this.m_BoneIndex3; + } + set + { + this.m_BoneIndex3 = value; + } + } + public override int GetHashCode() + { + return this.boneIndex0.GetHashCode() ^ this.boneIndex1.GetHashCode() << 2 ^ this.boneIndex2.GetHashCode() >> 2 ^ this.boneIndex3.GetHashCode() >> 1 ^ this.weight0.GetHashCode() << 5 ^ this.weight1.GetHashCode() << 4 ^ this.weight2.GetHashCode() >> 4 ^ this.weight3.GetHashCode() >> 3; + } + public override bool Equals(object other) + { + if (!(other is BoneWeight)) + { + return false; + } + BoneWeight boneWeight = (BoneWeight)other; + bool arg_CC_0; + if (this.boneIndex0.Equals(boneWeight.boneIndex0) && this.boneIndex1.Equals(boneWeight.boneIndex1) && this.boneIndex2.Equals(boneWeight.boneIndex2) && this.boneIndex3.Equals(boneWeight.boneIndex3)) + { + Vector4 vector = new Vector4(this.weight0, this.weight1, this.weight2, this.weight3); + arg_CC_0 = vector.Equals(new Vector4(boneWeight.weight0, boneWeight.weight1, boneWeight.weight2, boneWeight.weight3)); + } + else + { + arg_CC_0 = false; + } + return arg_CC_0; + } + public static bool operator ==(BoneWeight lhs, BoneWeight rhs) + { + return lhs.boneIndex0 == rhs.boneIndex0 && lhs.boneIndex1 == rhs.boneIndex1 && lhs.boneIndex2 == rhs.boneIndex2 && lhs.boneIndex3 == rhs.boneIndex3 && new Vector4(lhs.weight0, lhs.weight1, lhs.weight2, lhs.weight3) == new Vector4(rhs.weight0, rhs.weight1, rhs.weight2, rhs.weight3); + } + public static bool operator !=(BoneWeight lhs, BoneWeight rhs) + { + return !(lhs == rhs); + } + } +} diff --git a/UnityEngine/UnityEngine/Bounds.cs b/UnityEngine/UnityEngine/Bounds.cs new file mode 100644 index 00000000..58ff57fc --- /dev/null +++ b/UnityEngine/UnityEngine/Bounds.cs @@ -0,0 +1,172 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct Bounds + { + private Vector3 m_Center; + private Vector3 m_Extents; + public Vector3 center + { + get + { + return this.m_Center; + } + set + { + this.m_Center = value; + } + } + public Vector3 size + { + get + { + return this.m_Extents * 2f; + } + set + { + this.m_Extents = value * 0.5f; + } + } + public Vector3 extents + { + get + { + return this.m_Extents; + } + set + { + this.m_Extents = value; + } + } + public Vector3 min + { + get + { + return this.center - this.extents; + } + set + { + this.SetMinMax(value, this.max); + } + } + public Vector3 max + { + get + { + return this.center + this.extents; + } + set + { + this.SetMinMax(this.min, value); + } + } + public Bounds(Vector3 center, Vector3 size) + { + this.m_Center = center; + this.m_Extents = size * 0.5f; + } + public override int GetHashCode() + { + return this.center.GetHashCode() ^ this.extents.GetHashCode() << 2; + } + public override bool Equals(object other) + { + if (!(other is Bounds)) + { + return false; + } + Bounds bounds = (Bounds)other; + return this.center.Equals(bounds.center) && this.extents.Equals(bounds.extents); + } + public void SetMinMax(Vector3 min, Vector3 max) + { + this.extents = (max - min) * 0.5f; + this.center = min + this.extents; + } + public void Encapsulate(Vector3 point) + { + this.SetMinMax(Vector3.Min(this.min, point), Vector3.Max(this.max, point)); + } + public void Encapsulate(Bounds bounds) + { + this.Encapsulate(bounds.center - bounds.extents); + this.Encapsulate(bounds.center + bounds.extents); + } + public void Expand(float amount) + { + amount *= 0.5f; + this.extents += new Vector3(amount, amount, amount); + } + public void Expand(Vector3 amount) + { + this.extents += amount * 0.5f; + } + public bool Intersects(Bounds bounds) + { + return this.min.x <= bounds.max.x && this.max.x >= bounds.min.x && this.min.y <= bounds.max.y && this.max.y >= bounds.min.y && this.min.z <= bounds.max.z && this.max.z >= bounds.min.z; + } + private static bool Internal_Contains(Bounds m, Vector3 point) + { + return Bounds.INTERNAL_CALL_Internal_Contains(ref m, ref point); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_Contains(ref Bounds m, ref Vector3 point); + public bool Contains(Vector3 point) + { + return Bounds.Internal_Contains(this, point); + } + private static float Internal_SqrDistance(Bounds m, Vector3 point) + { + return Bounds.INTERNAL_CALL_Internal_SqrDistance(ref m, ref point); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_Internal_SqrDistance(ref Bounds m, ref Vector3 point); + public float SqrDistance(Vector3 point) + { + return Bounds.Internal_SqrDistance(this, point); + } + private static bool Internal_IntersectRay(ref Ray ray, ref Bounds bounds, out float distance) + { + return Bounds.INTERNAL_CALL_Internal_IntersectRay(ref ray, ref bounds, out distance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_IntersectRay(ref Ray ray, ref Bounds bounds, out float distance); + public bool IntersectRay(Ray ray) + { + float num; + return Bounds.Internal_IntersectRay(ref ray, ref this, out num); + } + public bool IntersectRay(Ray ray, out float distance) + { + return Bounds.Internal_IntersectRay(ref ray, ref this, out distance); + } + public override string ToString() + { + return UnityString.Format("Center: {0}, Extents: {1}", new object[] + { + this.m_Center, + this.m_Extents + }); + } + public string ToString(string format) + { + return UnityString.Format("Center: {0}, Extents: {1}", new object[] + { + this.m_Center.ToString(format), + this.m_Extents.ToString(format) + }); + } + public static bool operator ==(Bounds lhs, Bounds rhs) + { + return lhs.center == rhs.center && lhs.extents == rhs.extents; + } + public static bool operator !=(Bounds lhs, Bounds rhs) + { + return !(lhs == rhs); + } + } +} diff --git a/UnityEngine/UnityEngine/BoxCollider.cs b/UnityEngine/UnityEngine/BoxCollider.cs new file mode 100644 index 00000000..209ec127 --- /dev/null +++ b/UnityEngine/UnityEngine/BoxCollider.cs @@ -0,0 +1,58 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class BoxCollider : Collider + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public Vector3 size + { + get + { + Vector3 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } + [Obsolete("use BoxCollider.size instead.")] + public Vector3 extents + { + get + { + return this.size * 0.5f; + } + set + { + this.size = value * 2f; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/BoxCollider2D.cs b/UnityEngine/UnityEngine/BoxCollider2D.cs new file mode 100644 index 00000000..f8525b80 --- /dev/null +++ b/UnityEngine/UnityEngine/BoxCollider2D.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class BoxCollider2D : Collider2D + { + public Vector2 center + { + get + { + Vector2 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public Vector2 size + { + get + { + Vector2 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/CacheIndex.cs b/UnityEngine/UnityEngine/CacheIndex.cs new file mode 100644 index 00000000..93391e07 --- /dev/null +++ b/UnityEngine/UnityEngine/CacheIndex.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [Obsolete("this API is not for public use.")] + public struct CacheIndex + { + public string name; + public int bytesUsed; + public int expires; + } +} diff --git a/UnityEngine/UnityEngine/Caching.cs b/UnityEngine/UnityEngine/Caching.cs new file mode 100644 index 00000000..8624d117 --- /dev/null +++ b/UnityEngine/UnityEngine/Caching.cs @@ -0,0 +1,115 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Caching + { + [Obsolete("this API is not for public use.")] + public static extern CacheIndex[] index + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern long spaceFree + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern long maximumAvailableDiskSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern long spaceOccupied + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Please use Caching.spaceFree instead")] + public static extern int spaceAvailable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Please use Caching.spaceOccupied instead")] + public static extern int spaceUsed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int expirationDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool ready + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static bool Authorize(string name, string domain, long size, string signature) + { + return Caching.Authorize(name, domain, size, -1, signature); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Authorize(string name, string domain, long size, int expiration, string signature); + [Obsolete("Size is now specified as a long")] + public static bool Authorize(string name, string domain, int size, int expiration, string signature) + { + return Caching.Authorize(name, domain, (long)size, expiration, signature); + } + [Obsolete("Size is now specified as a long")] + public static bool Authorize(string name, string domain, int size, string signature) + { + return Caching.Authorize(name, domain, (long)size, signature); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CleanCache(); + [Obsolete("this API is not for public use."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CleanNamedCache(string name); + [Obsolete("This function is obsolete and has no effect."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DeleteFromCache(string url); + [Obsolete("This function is obsolete and will always return -1. Use IsVersionCached instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetVersionFromCache(string url); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsVersionCached(string url, int version); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool MarkAsUsed(string url, int version); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNoBackupFlag(string url, int version); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetNoBackupFlag(string url, int version); + } +} diff --git a/UnityEngine/UnityEngine/CalendarIdentifier.cs b/UnityEngine/UnityEngine/CalendarIdentifier.cs new file mode 100644 index 00000000..19a8ad9e --- /dev/null +++ b/UnityEngine/UnityEngine/CalendarIdentifier.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine +{ + public enum CalendarIdentifier + { + GregorianCalendar, + BuddhistCalendar, + ChineseCalendar, + HebrewCalendar, + IslamicCalendar, + IslamicCivilCalendar, + JapaneseCalendar, + RepublicOfChinaCalendar, + PersianCalendar, + IndianCalendar, + ISO8601Calendar + } +} diff --git a/UnityEngine/UnityEngine/CalendarUnit.cs b/UnityEngine/UnityEngine/CalendarUnit.cs new file mode 100644 index 00000000..3b17987e --- /dev/null +++ b/UnityEngine/UnityEngine/CalendarUnit.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine +{ + public enum CalendarUnit + { + Era = 2, + Year = 4, + Month = 8, + Day = 16, + Hour = 32, + Minute = 64, + Second = 128, + Week = 256, + Weekday = 512, + WeekdayOrdinal = 1024, + Quarter = 2048 + } +} diff --git a/UnityEngine/UnityEngine/Camera.cs b/UnityEngine/UnityEngine/Camera.cs new file mode 100644 index 00000000..d87fd582 --- /dev/null +++ b/UnityEngine/UnityEngine/Camera.cs @@ -0,0 +1,584 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Camera : Behaviour + { + [Obsolete("use Camera.fieldOfView instead.")] + public float fov + { + get + { + return this.fieldOfView; + } + set + { + this.fieldOfView = value; + } + } + [Obsolete("use Camera.nearClipPlane instead.")] + public float near + { + get + { + return this.nearClipPlane; + } + set + { + this.nearClipPlane = value; + } + } + [Obsolete("use Camera.farClipPlane instead.")] + public float far + { + get + { + return this.farClipPlane; + } + set + { + this.farClipPlane = value; + } + } + public extern float fieldOfView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float nearClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float farClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RenderingPath renderingPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RenderingPath actualRenderingPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hdr + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float orthographicSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool orthographic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TransparencySortMode transparencySortMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool isOrthoGraphic + { + get + { + return this.orthographic; + } + set + { + this.orthographic = value; + } + } + public extern float depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float aspect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int cullingMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int eventMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color backgroundColor + { + get + { + Color result; + this.INTERNAL_get_backgroundColor(out result); + return result; + } + set + { + this.INTERNAL_set_backgroundColor(ref value); + } + } + public Rect rect + { + get + { + Rect result; + this.INTERNAL_get_rect(out result); + return result; + } + set + { + this.INTERNAL_set_rect(ref value); + } + } + public Rect pixelRect + { + get + { + Rect result; + this.INTERNAL_get_pixelRect(out result); + return result; + } + set + { + this.INTERNAL_set_pixelRect(ref value); + } + } + public extern RenderTexture targetTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pixelWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float pixelHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Matrix4x4 cameraToWorldMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_cameraToWorldMatrix(out result); + return result; + } + } + public Matrix4x4 worldToCameraMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_worldToCameraMatrix(out result); + return result; + } + set + { + this.INTERNAL_set_worldToCameraMatrix(ref value); + } + } + public Matrix4x4 projectionMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_projectionMatrix(out result); + return result; + } + set + { + this.INTERNAL_set_projectionMatrix(ref value); + } + } + public Vector3 velocity + { + get + { + Vector3 result; + this.INTERNAL_get_velocity(out result); + return result; + } + } + public extern CameraClearFlags clearFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool stereoEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float stereoSeparation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float stereoConvergence + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Camera main + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Camera current + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Camera[] allCameras + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int allCamerasCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("use Camera.main instead.")] + public static Camera mainCamera + { + get + { + return Camera.main; + } + } + public extern bool useOcclusionCulling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float[] layerCullDistances + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool layerCullSpherical + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern DepthTextureMode depthTextureMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool clearStencilAfterLightingPass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_backgroundColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_backgroundColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_pixelRect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_pixelRect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetTargetBuffersImpl(out RenderBuffer color, out RenderBuffer depth); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetTargetBuffersMRTImpl(RenderBuffer[] color, out RenderBuffer depth); + public void SetTargetBuffers(RenderBuffer colorBuffer, RenderBuffer depthBuffer) + { + this.SetTargetBuffersImpl(out colorBuffer, out depthBuffer); + } + public void SetTargetBuffers(RenderBuffer[] colorBuffer, RenderBuffer depthBuffer) + { + this.SetTargetBuffersMRTImpl(colorBuffer, out depthBuffer); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_cameraToWorldMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldToCameraMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_worldToCameraMatrix(ref Matrix4x4 value); + public void ResetWorldToCameraMatrix() + { + Camera.INTERNAL_CALL_ResetWorldToCameraMatrix(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ResetWorldToCameraMatrix(Camera self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_projectionMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_projectionMatrix(ref Matrix4x4 value); + public void ResetProjectionMatrix() + { + Camera.INTERNAL_CALL_ResetProjectionMatrix(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ResetProjectionMatrix(Camera self); + public void ResetAspect() + { + Camera.INTERNAL_CALL_ResetAspect(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ResetAspect(Camera self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector3 value); + public Vector3 WorldToScreenPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_WorldToScreenPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_WorldToScreenPoint(Camera self, ref Vector3 position); + public Vector3 WorldToViewportPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_WorldToViewportPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_WorldToViewportPoint(Camera self, ref Vector3 position); + public Vector3 ViewportToWorldPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_ViewportToWorldPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ViewportToWorldPoint(Camera self, ref Vector3 position); + public Vector3 ScreenToWorldPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_ScreenToWorldPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ScreenToWorldPoint(Camera self, ref Vector3 position); + public Vector3 ScreenToViewportPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_ScreenToViewportPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ScreenToViewportPoint(Camera self, ref Vector3 position); + public Vector3 ViewportToScreenPoint(Vector3 position) + { + return Camera.INTERNAL_CALL_ViewportToScreenPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ViewportToScreenPoint(Camera self, ref Vector3 position); + public Ray ViewportPointToRay(Vector3 position) + { + return Camera.INTERNAL_CALL_ViewportPointToRay(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Ray INTERNAL_CALL_ViewportPointToRay(Camera self, ref Vector3 position); + public Ray ScreenPointToRay(Vector3 position) + { + return Camera.INTERNAL_CALL_ScreenPointToRay(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Ray INTERNAL_CALL_ScreenPointToRay(Camera self, ref Vector3 position); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetAllCameras(Camera[] cameras); + [Obsolete("use Screen.width instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetScreenWidth(); + [Obsolete("use Screen.height instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetScreenHeight(); + [Obsolete("Camera.DoClear is deprecated and may be removed in the future."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DoClear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Render(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RenderWithShader(Shader shader, string replacementTag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetReplacementShader(Shader shader, string replacementTag); + public void ResetReplacementShader() + { + Camera.INTERNAL_CALL_ResetReplacementShader(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ResetReplacementShader(Camera self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RenderDontRestore(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetupCurrent(Camera cur); + [ExcludeFromDocs] + public bool RenderToCubemap(Cubemap cubemap) + { + int faceMask = 63; + return this.RenderToCubemap(cubemap, faceMask); + } + public bool RenderToCubemap(Cubemap cubemap, [DefaultValue("63")] int faceMask) + { + return this.Internal_RenderToCubemapTexture(cubemap, faceMask); + } + [ExcludeFromDocs] + public bool RenderToCubemap(RenderTexture cubemap) + { + int faceMask = 63; + return this.RenderToCubemap(cubemap, faceMask); + } + public bool RenderToCubemap(RenderTexture cubemap, [DefaultValue("63")] int faceMask) + { + return this.Internal_RenderToCubemapRT(cubemap, faceMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_RenderToCubemapRT(RenderTexture cubemap, int faceMask); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_RenderToCubemapTexture(Cubemap cubemap, int faceMask); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CopyFrom(Camera other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool IsFiltered(GameObject go); + public Matrix4x4 CalculateObliqueMatrix(Vector4 clipPlane) + { + return Camera.INTERNAL_CALL_CalculateObliqueMatrix(this, ref clipPlane); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Matrix4x4 INTERNAL_CALL_CalculateObliqueMatrix(Camera self, ref Vector4 clipPlane); + } +} diff --git a/UnityEngine/UnityEngine/CameraClearFlags.cs b/UnityEngine/UnityEngine/CameraClearFlags.cs new file mode 100644 index 00000000..1b49d226 --- /dev/null +++ b/UnityEngine/UnityEngine/CameraClearFlags.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum CameraClearFlags + { + Skybox = 1, + Color, + SolidColor = 2, + Depth, + Nothing + } +} diff --git a/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs b/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs new file mode 100644 index 00000000..f95a1511 --- /dev/null +++ b/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs @@ -0,0 +1,15 @@ +using System; +using System.Diagnostics; +namespace UnityEngine +{ + [Conditional("UNITY_FLASH")] + internal class CanConvertToFlashAttribute : Attribute + { + public CanConvertToFlashAttribute() + { + } + public CanConvertToFlashAttribute(params string[] members) + { + } + } +} diff --git a/UnityEngine/UnityEngine/Canvas.cs b/UnityEngine/UnityEngine/Canvas.cs new file mode 100644 index 00000000..d59c2832 --- /dev/null +++ b/UnityEngine/UnityEngine/Canvas.cs @@ -0,0 +1,162 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Canvas : Behaviour + { + public delegate void WillRenderCanvases(); + public static event Canvas.WillRenderCanvases willRenderCanvases + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + Canvas.willRenderCanvases = (Canvas.WillRenderCanvases)Delegate.Combine(Canvas.willRenderCanvases, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + Canvas.willRenderCanvases = (Canvas.WillRenderCanvases)Delegate.Remove(Canvas.willRenderCanvases, value); + } + } + public extern RenderMode renderMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isRootCanvas + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Camera worldCamera + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Rect pixelRect + { + get + { + Rect result; + this.INTERNAL_get_pixelRect(out result); + return result; + } + } + public extern float scaleFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float referencePixelsPerUnit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool overridePixelPerfect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool pixelPerfect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float planeDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int renderOrder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool overrideSorting + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int sortingOrder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int sortingLayerID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string sortingLayerName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_pixelRect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Material GetDefaultCanvasMaterial(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Material GetDefaultCanvasTextMaterial(); + private static void SendWillRenderCanvases() + { + if (Canvas.willRenderCanvases != null) + { + Canvas.willRenderCanvases(); + } + } + public static void ForceUpdateCanvases() + { + Canvas.SendWillRenderCanvases(); + } + } +} diff --git a/UnityEngine/UnityEngine/CanvasGroup.cs b/UnityEngine/UnityEngine/CanvasGroup.cs new file mode 100644 index 00000000..ea100d56 --- /dev/null +++ b/UnityEngine/UnityEngine/CanvasGroup.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CanvasGroup : Component, ICanvasRaycastFilter + { + public extern float alpha + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool interactable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool blocksRaycasts + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool ignoreParentGroups + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) + { + return this.blocksRaycasts; + } + } +} diff --git a/UnityEngine/UnityEngine/CanvasRenderer.cs b/UnityEngine/UnityEngine/CanvasRenderer.cs new file mode 100644 index 00000000..ffd56fb3 --- /dev/null +++ b/UnityEngine/UnityEngine/CanvasRenderer.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CanvasRenderer : Component + { + public delegate void OnRequestRebuild(); + public static event CanvasRenderer.OnRequestRebuild onRequestRebuild + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + CanvasRenderer.onRequestRebuild = (CanvasRenderer.OnRequestRebuild)Delegate.Combine(CanvasRenderer.onRequestRebuild, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + CanvasRenderer.onRequestRebuild = (CanvasRenderer.OnRequestRebuild)Delegate.Remove(CanvasRenderer.onRequestRebuild, value); + } + } + public extern bool isMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int relativeDepth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int absoluteDepth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public void SetColor(Color color) + { + CanvasRenderer.INTERNAL_CALL_SetColor(this, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetColor(CanvasRenderer self, ref Color color); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetColor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetAlpha(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAlpha(float alpha); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetMaterial(Material material, Texture texture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Material GetMaterial(); + public void SetVertices(List vertices) + { + if (vertices.Count > 65535) + { + Debug.LogWarning(UnityString.Format("Number of vertices set exceeds {0}, rendering of this element will be skipped", new object[] + { + 65535 + }), this); + vertices.Clear(); + } + this.SetVerticesInternal(vertices); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetVerticesInternal(object vertices); + public void SetVertices(UIVertex[] vertices, int size) + { + if (size > 65535) + { + Debug.LogWarning(UnityString.Format("Number of vertices set exceeds {0}, rendering of this element will be skipped", new object[] + { + 65535 + }), this); + size = 0; + } + this.SetVerticesInternalArray(vertices, size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetVerticesInternalArray(UIVertex[] vertices, int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Clear(); + private static void RequestRefresh() + { + if (CanvasRenderer.onRequestRebuild != null) + { + CanvasRenderer.onRequestRebuild(); + } + } + } +} diff --git a/UnityEngine/UnityEngine/CapsuleCollider.cs b/UnityEngine/UnityEngine/CapsuleCollider.cs new file mode 100644 index 00000000..547c6f18 --- /dev/null +++ b/UnityEngine/UnityEngine/CapsuleCollider.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CapsuleCollider : Collider + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int direction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/CharacterController.cs b/UnityEngine/UnityEngine/CharacterController.cs new file mode 100644 index 00000000..21a4805b --- /dev/null +++ b/UnityEngine/UnityEngine/CharacterController.cs @@ -0,0 +1,110 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CharacterController : Collider + { + public extern bool isGrounded + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 velocity + { + get + { + Vector3 result; + this.INTERNAL_get_velocity(out result); + return result; + } + } + public extern CollisionFlags collisionFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float slopeLimit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float stepOffset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool detectCollisions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool SimpleMove(Vector3 speed) + { + return CharacterController.INTERNAL_CALL_SimpleMove(this, ref speed); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_SimpleMove(CharacterController self, ref Vector3 speed); + public CollisionFlags Move(Vector3 motion) + { + return CharacterController.INTERNAL_CALL_Move(this, ref motion); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern CollisionFlags INTERNAL_CALL_Move(CharacterController self, ref Vector3 motion); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/CharacterInfo.cs b/UnityEngine/UnityEngine/CharacterInfo.cs new file mode 100644 index 00000000..6b6cfef5 --- /dev/null +++ b/UnityEngine/UnityEngine/CharacterInfo.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public struct CharacterInfo + { + public int index; + public Rect uv; + public Rect vert; + public float width; + public int size; + public FontStyle style; + public bool flipped; + } +} diff --git a/UnityEngine/UnityEngine/CharacterJoint.cs b/UnityEngine/UnityEngine/CharacterJoint.cs new file mode 100644 index 00000000..43e7c805 --- /dev/null +++ b/UnityEngine/UnityEngine/CharacterJoint.cs @@ -0,0 +1,160 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CharacterJoint : Joint + { + public Vector3 swingAxis + { + get + { + Vector3 result; + this.INTERNAL_get_swingAxis(out result); + return result; + } + set + { + this.INTERNAL_set_swingAxis(ref value); + } + } + public SoftJointLimit lowTwistLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_lowTwistLimit(out result); + return result; + } + set + { + this.INTERNAL_set_lowTwistLimit(ref value); + } + } + public SoftJointLimit highTwistLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_highTwistLimit(out result); + return result; + } + set + { + this.INTERNAL_set_highTwistLimit(ref value); + } + } + public SoftJointLimit swing1Limit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_swing1Limit(out result); + return result; + } + set + { + this.INTERNAL_set_swing1Limit(ref value); + } + } + public SoftJointLimit swing2Limit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_swing2Limit(out result); + return result; + } + set + { + this.INTERNAL_set_swing2Limit(ref value); + } + } + public Quaternion targetRotation + { + get + { + Quaternion result; + this.INTERNAL_get_targetRotation(out result); + return result; + } + set + { + this.INTERNAL_set_targetRotation(ref value); + } + } + public Vector3 targetAngularVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_targetAngularVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_targetAngularVelocity(ref value); + } + } + public JointDrive rotationDrive + { + get + { + JointDrive result; + this.INTERNAL_get_rotationDrive(out result); + return result; + } + set + { + this.INTERNAL_set_rotationDrive(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_swingAxis(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_swingAxis(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_lowTwistLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_lowTwistLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_highTwistLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_highTwistLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_swing1Limit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_swing1Limit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_swing2Limit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_swing2Limit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetAngularVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetAngularVelocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rotationDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rotationDrive(ref JointDrive value); + } +} diff --git a/UnityEngine/UnityEngine/CircleCollider2D.cs b/UnityEngine/UnityEngine/CircleCollider2D.cs new file mode 100644 index 00000000..1fddc20c --- /dev/null +++ b/UnityEngine/UnityEngine/CircleCollider2D.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class CircleCollider2D : Collider2D + { + public Vector2 center + { + get + { + Vector2 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/ClassLibraryInitializer.cs b/UnityEngine/UnityEngine/ClassLibraryInitializer.cs new file mode 100644 index 00000000..0d6fd2ac --- /dev/null +++ b/UnityEngine/UnityEngine/ClassLibraryInitializer.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + internal static class ClassLibraryInitializer + { + private static void Init() + { + UnityLogWriter.Init(); + } + } +} diff --git a/UnityEngine/UnityEngine/Cloth.cs b/UnityEngine/UnityEngine/Cloth.cs new file mode 100644 index 00000000..a383d665 --- /dev/null +++ b/UnityEngine/UnityEngine/Cloth.cs @@ -0,0 +1,121 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Cloth : Component + { + public extern float bendingStiffness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float stretchingStiffness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float damping + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float thickness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 externalAcceleration + { + get + { + Vector3 result; + this.INTERNAL_get_externalAcceleration(out result); + return result; + } + set + { + this.INTERNAL_set_externalAcceleration(ref value); + } + } + public Vector3 randomAcceleration + { + get + { + Vector3 result; + this.INTERNAL_get_randomAcceleration(out result); + return result; + } + set + { + this.INTERNAL_set_randomAcceleration(ref value); + } + } + public extern bool useGravity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool selfCollision + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector3[] vertices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3[] normals + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_externalAcceleration(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_externalAcceleration(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_randomAcceleration(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_randomAcceleration(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/ClothRenderer.cs b/UnityEngine/UnityEngine/ClothRenderer.cs new file mode 100644 index 00000000..d73877ad --- /dev/null +++ b/UnityEngine/UnityEngine/ClothRenderer.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ClothRenderer : Renderer + { + public extern bool pauseWhenNotVisible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs b/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs new file mode 100644 index 00000000..e30160c9 --- /dev/null +++ b/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public struct ClothSkinningCoefficient + { + public float maxDistance; + public float maxDistanceBias; + public float collisionSphereRadius; + public float collisionSphereDistance; + } +} diff --git a/UnityEngine/UnityEngine/Collider.cs b/UnityEngine/UnityEngine/Collider.cs new file mode 100644 index 00000000..b137816c --- /dev/null +++ b/UnityEngine/UnityEngine/Collider.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Collider : Component + { + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Rigidbody attachedRigidbody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isTrigger + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern PhysicMaterial material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern PhysicMaterial sharedMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Bounds bounds + { + get + { + Bounds result; + this.INTERNAL_get_bounds(out result); + return result; + } + } + public Vector3 ClosestPointOnBounds(Vector3 position) + { + return Collider.INTERNAL_CALL_ClosestPointOnBounds(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ClosestPointOnBounds(Collider self, ref Vector3 position); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bounds(out Bounds value); + private static bool Internal_Raycast(Collider col, Ray ray, out RaycastHit hitInfo, float distance) + { + return Collider.INTERNAL_CALL_Internal_Raycast(col, ref ray, out hitInfo, distance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_Raycast(Collider col, ref Ray ray, out RaycastHit hitInfo, float distance); + public bool Raycast(Ray ray, out RaycastHit hitInfo, float distance) + { + return Collider.Internal_Raycast(this, ray, out hitInfo, distance); + } + } +} diff --git a/UnityEngine/UnityEngine/Collider2D.cs b/UnityEngine/UnityEngine/Collider2D.cs new file mode 100644 index 00000000..17e412da --- /dev/null +++ b/UnityEngine/UnityEngine/Collider2D.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Collider2D : Behaviour + { + public extern bool isTrigger + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Rigidbody2D attachedRigidbody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int shapeCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Bounds bounds + { + get + { + Bounds result; + this.INTERNAL_get_bounds(out result); + return result; + } + } + internal extern ColliderErrorState2D errorState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern PhysicsMaterial2D sharedMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bounds(out Bounds value); + public bool OverlapPoint(Vector2 point) + { + return Collider2D.INTERNAL_CALL_OverlapPoint(this, ref point); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_OverlapPoint(Collider2D self, ref Vector2 point); + } +} diff --git a/UnityEngine/UnityEngine/ColliderErrorState2D.cs b/UnityEngine/UnityEngine/ColliderErrorState2D.cs new file mode 100644 index 00000000..fa42abd3 --- /dev/null +++ b/UnityEngine/UnityEngine/ColliderErrorState2D.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal enum ColliderErrorState2D + { + None, + NoShapes, + RemovedShapes + } +} diff --git a/UnityEngine/UnityEngine/Collision.cs b/UnityEngine/UnityEngine/Collision.cs new file mode 100644 index 00000000..51fb0aec --- /dev/null +++ b/UnityEngine/UnityEngine/Collision.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class Collision + { + internal Vector3 m_RelativeVelocity; + internal Rigidbody m_Rigidbody; + internal Collider m_Collider; + internal ContactPoint[] m_Contacts; + public Vector3 relativeVelocity + { + get + { + return this.m_RelativeVelocity; + } + } + public Rigidbody rigidbody + { + get + { + return this.m_Rigidbody; + } + } + public Collider collider + { + get + { + return this.m_Collider; + } + } + public Transform transform + { + get + { + return (!(this.rigidbody != null)) ? this.collider.transform : this.rigidbody.transform; + } + } + public GameObject gameObject + { + get + { + return (!(this.m_Rigidbody != null)) ? this.m_Collider.gameObject : this.m_Rigidbody.gameObject; + } + } + public ContactPoint[] contacts + { + get + { + return this.m_Contacts; + } + } + [Obsolete("use Collision.relativeVelocity instead.")] + public Vector3 impactForceSum + { + get + { + return this.relativeVelocity; + } + } + [Obsolete("will always return zero.")] + public Vector3 frictionForceSum + { + get + { + return Vector3.zero; + } + } + [Obsolete("Please use Collision.rigidbody, Collision.transform or Collision.collider instead")] + public Component other + { + get + { + return (!(this.m_Rigidbody != null)) ? this.m_Collider : this.m_Rigidbody; + } + } + public virtual IEnumerator GetEnumerator() + { + return this.contacts.GetEnumerator(); + } + } +} diff --git a/UnityEngine/UnityEngine/Collision2D.cs b/UnityEngine/UnityEngine/Collision2D.cs new file mode 100644 index 00000000..53296d29 --- /dev/null +++ b/UnityEngine/UnityEngine/Collision2D.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class Collision2D + { + internal Rigidbody2D m_Rigidbody; + internal Collider2D m_Collider; + internal ContactPoint2D[] m_Contacts; + internal Vector2 m_RelativeVelocity; + public Rigidbody2D rigidbody + { + get + { + return this.m_Rigidbody; + } + } + public Collider2D collider + { + get + { + return this.m_Collider; + } + } + public Transform transform + { + get + { + return (!(this.rigidbody != null)) ? this.collider.transform : this.rigidbody.transform; + } + } + public GameObject gameObject + { + get + { + return (!(this.m_Rigidbody != null)) ? this.m_Collider.gameObject : this.m_Rigidbody.gameObject; + } + } + public ContactPoint2D[] contacts + { + get + { + return this.m_Contacts; + } + } + public Vector2 relativeVelocity + { + get + { + return this.m_RelativeVelocity; + } + } + } +} diff --git a/UnityEngine/UnityEngine/CollisionDetectionMode.cs b/UnityEngine/UnityEngine/CollisionDetectionMode.cs new file mode 100644 index 00000000..5f89b7c4 --- /dev/null +++ b/UnityEngine/UnityEngine/CollisionDetectionMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum CollisionDetectionMode + { + Discrete, + Continuous, + ContinuousDynamic + } +} diff --git a/UnityEngine/UnityEngine/CollisionDetectionMode2D.cs b/UnityEngine/UnityEngine/CollisionDetectionMode2D.cs new file mode 100644 index 00000000..e6f40c4a --- /dev/null +++ b/UnityEngine/UnityEngine/CollisionDetectionMode2D.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum CollisionDetectionMode2D + { + None, + Continuous + } +} diff --git a/UnityEngine/UnityEngine/CollisionFlags.cs b/UnityEngine/UnityEngine/CollisionFlags.cs new file mode 100644 index 00000000..148512a0 --- /dev/null +++ b/UnityEngine/UnityEngine/CollisionFlags.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public enum CollisionFlags + { + None, + Sides, + Above, + Below = 4, + CollidedSides = 1, + CollidedAbove, + CollidedBelow = 4 + } +} diff --git a/UnityEngine/UnityEngine/Color.cs b/UnityEngine/UnityEngine/Color.cs new file mode 100644 index 00000000..f9e4b1c8 --- /dev/null +++ b/UnityEngine/UnityEngine/Color.cs @@ -0,0 +1,252 @@ +using System; +namespace UnityEngine +{ + public struct Color + { + public float r; + public float g; + public float b; + public float a; + public static Color red + { + get + { + return new Color(1f, 0f, 0f, 1f); + } + } + public static Color green + { + get + { + return new Color(0f, 1f, 0f, 1f); + } + } + public static Color blue + { + get + { + return new Color(0f, 0f, 1f, 1f); + } + } + public static Color white + { + get + { + return new Color(1f, 1f, 1f, 1f); + } + } + public static Color black + { + get + { + return new Color(0f, 0f, 0f, 1f); + } + } + public static Color yellow + { + get + { + return new Color(1f, 0.921568632f, 0.0156862754f, 1f); + } + } + public static Color cyan + { + get + { + return new Color(0f, 1f, 1f, 1f); + } + } + public static Color magenta + { + get + { + return new Color(1f, 0f, 1f, 1f); + } + } + public static Color gray + { + get + { + return new Color(0.5f, 0.5f, 0.5f, 1f); + } + } + public static Color grey + { + get + { + return new Color(0.5f, 0.5f, 0.5f, 1f); + } + } + public static Color clear + { + get + { + return new Color(0f, 0f, 0f, 0f); + } + } + public float grayscale + { + get + { + return 0.299f * this.r + 0.587f * this.g + 0.114f * this.b; + } + } + public Color linear + { + get + { + return new Color(Mathf.GammaToLinearSpace(this.r), Mathf.GammaToLinearSpace(this.g), Mathf.GammaToLinearSpace(this.b), this.a); + } + } + public Color gamma + { + get + { + return new Color(Mathf.LinearToGammaSpace(this.r), Mathf.LinearToGammaSpace(this.g), Mathf.LinearToGammaSpace(this.b), this.a); + } + } + public float this[int index] + { + get + { + switch (index) + { + case 0: + return this.r; + case 1: + return this.g; + case 2: + return this.b; + case 3: + return this.a; + default: + throw new IndexOutOfRangeException("Invalid Vector3 index!"); + } + } + set + { + switch (index) + { + case 0: + this.r = value; + break; + case 1: + this.g = value; + break; + case 2: + this.b = value; + break; + case 3: + this.a = value; + break; + default: + throw new IndexOutOfRangeException("Invalid Vector3 index!"); + } + } + } + public Color(float r, float g, float b, float a) + { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + public Color(float r, float g, float b) + { + this.r = r; + this.g = g; + this.b = b; + this.a = 1f; + } + public override string ToString() + { + return UnityString.Format("RGBA({0:F3}, {1:F3}, {2:F3}, {3:F3})", new object[] + { + this.r, + this.g, + this.b, + this.a + }); + } + public string ToString(string format) + { + return UnityString.Format("RGBA({0}, {1}, {2}, {3})", new object[] + { + this.r.ToString(format), + this.g.ToString(format), + this.b.ToString(format), + this.a.ToString(format) + }); + } + public override int GetHashCode() + { + return this.GetHashCode(); + } + public override bool Equals(object other) + { + if (!(other is Color)) + { + return false; + } + Color color = (Color)other; + return this.r.Equals(color.r) && this.g.Equals(color.g) && this.b.Equals(color.b) && this.a.Equals(color.a); + } + public static Color Lerp(Color a, Color b, float t) + { + t = Mathf.Clamp01(t); + return new Color(a.r + (b.r - a.r) * t, a.g + (b.g - a.g) * t, a.b + (b.b - a.b) * t, a.a + (b.a - a.a) * t); + } + internal Color RGBMultiplied(float multiplier) + { + return new Color(this.r * multiplier, this.g * multiplier, this.b * multiplier, this.a); + } + internal Color AlphaMultiplied(float multiplier) + { + return new Color(this.r, this.g, this.b, this.a * multiplier); + } + internal Color RGBMultiplied(Color multiplier) + { + return new Color(this.r * multiplier.r, this.g * multiplier.g, this.b * multiplier.b, this.a); + } + public static Color operator +(Color a, Color b) + { + return new Color(a.r + b.r, a.g + b.g, a.b + b.b, a.a + b.a); + } + public static Color operator -(Color a, Color b) + { + return new Color(a.r - b.r, a.g - b.g, a.b - b.b, a.a - b.a); + } + public static Color operator *(Color a, Color b) + { + return new Color(a.r * b.r, a.g * b.g, a.b * b.b, a.a * b.a); + } + public static Color operator *(Color a, float b) + { + return new Color(a.r * b, a.g * b, a.b * b, a.a * b); + } + public static Color operator *(float b, Color a) + { + return new Color(a.r * b, a.g * b, a.b * b, a.a * b); + } + public static Color operator /(Color a, float b) + { + return new Color(a.r / b, a.g / b, a.b / b, a.a / b); + } + public static bool operator ==(Color lhs, Color rhs) + { + return lhs == rhs; + } + public static bool operator !=(Color lhs, Color rhs) + { + return lhs != rhs; + } + public static implicit operator Vector4(Color c) + { + return new Vector4(c.r, c.g, c.b, c.a); + } + public static implicit operator Color(Vector4 v) + { + return new Color(v.x, v.y, v.z, v.w); + } + } +} diff --git a/UnityEngine/UnityEngine/Color32.cs b/UnityEngine/UnityEngine/Color32.cs new file mode 100644 index 00000000..5a198e3f --- /dev/null +++ b/UnityEngine/UnityEngine/Color32.cs @@ -0,0 +1,51 @@ +using System; +namespace UnityEngine +{ + public struct Color32 + { + public byte r; + public byte g; + public byte b; + public byte a; + public Color32(byte r, byte g, byte b, byte a) + { + this.r = r; + this.g = g; + this.b = b; + this.a = a; + } + public override string ToString() + { + return UnityString.Format("RGBA({0}, {1}, {2}, {3})", new object[] + { + this.r, + this.g, + this.b, + this.a + }); + } + public string ToString(string format) + { + return UnityString.Format("RGBA({0}, {1}, {2}, {3})", new object[] + { + this.r.ToString(format), + this.g.ToString(format), + this.b.ToString(format), + this.a.ToString(format) + }); + } + public static Color32 Lerp(Color32 a, Color32 b, float t) + { + t = Mathf.Clamp01(t); + return new Color32((byte)((float)a.r + (float)(b.r - a.r) * t), (byte)((float)a.g + (float)(b.g - a.g) * t), (byte)((float)a.b + (float)(b.b - a.b) * t), (byte)((float)a.a + (float)(b.a - a.a) * t)); + } + public static implicit operator Color32(Color c) + { + return new Color32((byte)(Mathf.Clamp01(c.r) * 255f), (byte)(Mathf.Clamp01(c.g) * 255f), (byte)(Mathf.Clamp01(c.b) * 255f), (byte)(Mathf.Clamp01(c.a) * 255f)); + } + public static implicit operator Color(Color32 c) + { + return new Color((float)c.r / 255f, (float)c.g / 255f, (float)c.b / 255f, (float)c.a / 255f); + } + } +} diff --git a/UnityEngine/UnityEngine/ColorSpace.cs b/UnityEngine/UnityEngine/ColorSpace.cs new file mode 100644 index 00000000..dedaf474 --- /dev/null +++ b/UnityEngine/UnityEngine/ColorSpace.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum ColorSpace + { + Uninitialized = -1, + Gamma, + Linear + } +} diff --git a/UnityEngine/UnityEngine/CombineInstance.cs b/UnityEngine/UnityEngine/CombineInstance.cs new file mode 100644 index 00000000..f3e7c494 --- /dev/null +++ b/UnityEngine/UnityEngine/CombineInstance.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct CombineInstance + { + private int m_MeshInstanceID; + private int m_SubMeshIndex; + private Matrix4x4 m_Transform; + public Mesh mesh + { + get + { + return this.InternalGetMesh(this.m_MeshInstanceID); + } + set + { + this.m_MeshInstanceID = ((!(value != null)) ? 0 : value.GetInstanceID()); + } + } + public int subMeshIndex + { + get + { + return this.m_SubMeshIndex; + } + set + { + this.m_SubMeshIndex = value; + } + } + public Matrix4x4 transform + { + get + { + return this.m_Transform; + } + set + { + this.m_Transform = value; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Mesh InternalGetMesh(int instanceID); + } +} diff --git a/UnityEngine/UnityEngine/Compass.cs b/UnityEngine/UnityEngine/Compass.cs new file mode 100644 index 00000000..080adc7b --- /dev/null +++ b/UnityEngine/UnityEngine/Compass.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Compass + { + public extern float magneticHeading + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float trueHeading + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float headingAccuracy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3 rawVector + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern double timestamp + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/Component.cs b/UnityEngine/UnityEngine/Component.cs new file mode 100644 index 00000000..ef00f956 --- /dev/null +++ b/UnityEngine/UnityEngine/Component.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEngine +{ + public class Component : Object + { + public Transform transform + { + get + { + return this.InternalGetTransform(); + } + } + public extern Rigidbody rigidbody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Rigidbody2D rigidbody2D + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Camera camera + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Light light + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Animation animation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ConstantForce constantForce + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Renderer renderer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AudioSource audio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern GUIText guiText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern NetworkView networkView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Please use guiTexture instead")] + public extern GUIElement guiElement + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern GUITexture guiTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Collider collider + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Collider2D collider2D + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern HingeJoint hingeJoint + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ParticleEmitter particleEmitter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ParticleSystem particleSystem + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public GameObject gameObject + { + get + { + return this.InternalGetGameObject(); + } + } + [Obsolete("the active property is deprecated on components. Please use gameObject.active instead. If you meant to enable / disable a single component use enabled instead.")] + public extern bool active + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string tag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Transform InternalGetTransform(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern GameObject InternalGetGameObject(); + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Component GetComponent(Type type); + public T GetComponent() where T : Component + { + return this.GetComponent(typeof(T)) as T; + } + public Component GetComponent(string type) + { + return this.gameObject.GetComponent(type); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component GetComponentInChildren(Type t) + { + return this.gameObject.GetComponentInChildren(t); + } + public T GetComponentInChildren() where T : Component + { + return (T)((object)this.GetComponentInChildren(typeof(T))); + } + [ExcludeFromDocs] + public Component[] GetComponentsInChildren(Type t) + { + bool includeInactive = false; + return this.GetComponentsInChildren(t, includeInactive); + } + public Component[] GetComponentsInChildren(Type t, [DefaultValue("false")] bool includeInactive) + { + return this.gameObject.GetComponentsInChildren(t, includeInactive); + } + public T[] GetComponentsInChildren(bool includeInactive) where T : Component + { + return this.gameObject.GetComponentsInChildren(includeInactive); + } + public void GetComponentsInChildren(bool includeInactive, List result) where T : Component + { + this.gameObject.GetComponentsInChildren(includeInactive, result); + } + public T[] GetComponentsInChildren() where T : Component + { + return this.GetComponentsInChildren(false); + } + public void GetComponentsInChildren(List results) where T : Component + { + this.GetComponentsInChildren(false, results); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component GetComponentInParent(Type t) + { + return this.gameObject.GetComponentInParent(t); + } + public T GetComponentInParent() where T : Component + { + return (T)((object)this.GetComponentInParent(typeof(T))); + } + [ExcludeFromDocs] + public Component[] GetComponentsInParent(Type t) + { + bool includeInactive = false; + return this.GetComponentsInParent(t, includeInactive); + } + public Component[] GetComponentsInParent(Type t, [DefaultValue("false")] bool includeInactive) + { + return this.gameObject.GetComponentsInParent(t, includeInactive); + } + public T[] GetComponentsInParent(bool includeInactive) where T : Component + { + return this.gameObject.GetComponentsInParent(includeInactive); + } + public T[] GetComponentsInParent() where T : Component + { + return this.GetComponentsInParent(false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Component[] GetComponents(Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Component[] GetComponentsWithCorrectReturnType(Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetComponentsForListInternal(Type searchType, Type listElementType, bool recursive, bool includeInactive, object resultList); + public T[] GetComponents() where T : Component + { + return (T[])this.GetComponentsWithCorrectReturnType(typeof(T)); + } + public void GetComponents(Type type, List results) + { + this.GetComponentsForListInternal(type, typeof(Component), false, true, results); + } + public void GetComponents(List results) where T : Component + { + this.GetComponentsForListInternal(typeof(T), typeof(T), false, true, results); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool CompareTag(string tag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SendMessageUpwards(string methodName, [DefaultValue("null")] object value, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void SendMessageUpwards(string methodName, object value) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.SendMessageUpwards(methodName, value, options); + } + [ExcludeFromDocs] + public void SendMessageUpwards(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object value = null; + this.SendMessageUpwards(methodName, value, options); + } + public void SendMessageUpwards(string methodName, SendMessageOptions options) + { + this.SendMessageUpwards(methodName, null, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SendMessage(string methodName, [DefaultValue("null")] object value, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void SendMessage(string methodName, object value) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.SendMessage(methodName, value, options); + } + [ExcludeFromDocs] + public void SendMessage(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object value = null; + this.SendMessage(methodName, value, options); + } + public void SendMessage(string methodName, SendMessageOptions options) + { + this.SendMessage(methodName, null, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void BroadcastMessage(string methodName, [DefaultValue("null")] object parameter, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void BroadcastMessage(string methodName, object parameter) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.BroadcastMessage(methodName, parameter, options); + } + [ExcludeFromDocs] + public void BroadcastMessage(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object parameter = null; + this.BroadcastMessage(methodName, parameter, options); + } + public void BroadcastMessage(string methodName, SendMessageOptions options) + { + this.BroadcastMessage(methodName, null, options); + } + } +} diff --git a/UnityEngine/UnityEngine/ComputeBuffer.cs b/UnityEngine/UnityEngine/ComputeBuffer.cs new file mode 100644 index 00000000..43f591e2 --- /dev/null +++ b/UnityEngine/UnityEngine/ComputeBuffer.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; +namespace UnityEngine +{ + public sealed class ComputeBuffer : IDisposable + { + internal IntPtr m_Ptr; + public extern int count + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int stride + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public ComputeBuffer(int count, int stride) : this(count, stride, ComputeBufferType.Default) + { + } + public ComputeBuffer(int count, int stride, ComputeBufferType type) + { + this.m_Ptr = IntPtr.Zero; + ComputeBuffer.InitBuffer(this, count, stride, type); + } + ~ComputeBuffer() + { + this.Dispose(false); + } + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + private void Dispose(bool disposing) + { + ComputeBuffer.DestroyBuffer(this); + this.m_Ptr = IntPtr.Zero; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void InitBuffer(ComputeBuffer buf, int count, int stride, ComputeBufferType type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void DestroyBuffer(ComputeBuffer buf); + public void Release() + { + this.Dispose(); + } + [SecuritySafeCritical] + public void SetData(Array data) + { + this.InternalSetData(data, Marshal.SizeOf(data.GetType().GetElementType())); + } + [SecurityCritical, WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalSetData(Array data, int elemSize); + [SecuritySafeCritical] + public void GetData(Array data) + { + this.InternalGetData(data, Marshal.SizeOf(data.GetType().GetElementType())); + } + [SecurityCritical, WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalGetData(Array data, int elemSize); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyCount(ComputeBuffer src, ComputeBuffer dst, int dstOffset); + } +} diff --git a/UnityEngine/UnityEngine/ComputeBufferType.cs b/UnityEngine/UnityEngine/ComputeBufferType.cs new file mode 100644 index 00000000..09455400 --- /dev/null +++ b/UnityEngine/UnityEngine/ComputeBufferType.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum ComputeBufferType + { + Default = 0, + Raw = 1, + Append = 2, + Counter = 4, + DrawIndirect = 256 + } +} diff --git a/UnityEngine/UnityEngine/ComputeShader.cs b/UnityEngine/UnityEngine/ComputeShader.cs new file mode 100644 index 00000000..91d02fcf --- /dev/null +++ b/UnityEngine/UnityEngine/ComputeShader.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ComputeShader : Object + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int FindKernel(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetFloat(string name, float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetInt(string name, int val); + public void SetVector(string name, Vector4 val) + { + ComputeShader.INTERNAL_CALL_SetVector(this, name, ref val); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetVector(ComputeShader self, string name, ref Vector4 val); + public void SetFloats(string name, params float[] values) + { + this.Internal_SetFloats(name, values); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetFloats(string name, float[] values); + public void SetInts(string name, params int[] values) + { + this.Internal_SetInts(name, values); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetInts(string name, int[] values); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTexture(int kernelIndex, string name, Texture texture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetBuffer(int kernelIndex, string name, ComputeBuffer buffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispatch(int kernelIndex, int threadsX, int threadsY, int threadsZ); + } +} diff --git a/UnityEngine/UnityEngine/ConfigurableJoint.cs b/UnityEngine/UnityEngine/ConfigurableJoint.cs new file mode 100644 index 00000000..3bcef89e --- /dev/null +++ b/UnityEngine/UnityEngine/ConfigurableJoint.cs @@ -0,0 +1,420 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ConfigurableJoint : Joint + { + public Vector3 secondaryAxis + { + get + { + Vector3 result; + this.INTERNAL_get_secondaryAxis(out result); + return result; + } + set + { + this.INTERNAL_set_secondaryAxis(ref value); + } + } + public extern ConfigurableJointMotion xMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ConfigurableJointMotion yMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ConfigurableJointMotion zMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ConfigurableJointMotion angularXMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ConfigurableJointMotion angularYMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ConfigurableJointMotion angularZMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public SoftJointLimit linearLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_linearLimit(out result); + return result; + } + set + { + this.INTERNAL_set_linearLimit(ref value); + } + } + public SoftJointLimit lowAngularXLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_lowAngularXLimit(out result); + return result; + } + set + { + this.INTERNAL_set_lowAngularXLimit(ref value); + } + } + public SoftJointLimit highAngularXLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_highAngularXLimit(out result); + return result; + } + set + { + this.INTERNAL_set_highAngularXLimit(ref value); + } + } + public SoftJointLimit angularYLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_angularYLimit(out result); + return result; + } + set + { + this.INTERNAL_set_angularYLimit(ref value); + } + } + public SoftJointLimit angularZLimit + { + get + { + SoftJointLimit result; + this.INTERNAL_get_angularZLimit(out result); + return result; + } + set + { + this.INTERNAL_set_angularZLimit(ref value); + } + } + public Vector3 targetPosition + { + get + { + Vector3 result; + this.INTERNAL_get_targetPosition(out result); + return result; + } + set + { + this.INTERNAL_set_targetPosition(ref value); + } + } + public Vector3 targetVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_targetVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_targetVelocity(ref value); + } + } + public JointDrive xDrive + { + get + { + JointDrive result; + this.INTERNAL_get_xDrive(out result); + return result; + } + set + { + this.INTERNAL_set_xDrive(ref value); + } + } + public JointDrive yDrive + { + get + { + JointDrive result; + this.INTERNAL_get_yDrive(out result); + return result; + } + set + { + this.INTERNAL_set_yDrive(ref value); + } + } + public JointDrive zDrive + { + get + { + JointDrive result; + this.INTERNAL_get_zDrive(out result); + return result; + } + set + { + this.INTERNAL_set_zDrive(ref value); + } + } + public Quaternion targetRotation + { + get + { + Quaternion result; + this.INTERNAL_get_targetRotation(out result); + return result; + } + set + { + this.INTERNAL_set_targetRotation(ref value); + } + } + public Vector3 targetAngularVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_targetAngularVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_targetAngularVelocity(ref value); + } + } + public extern RotationDriveMode rotationDriveMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public JointDrive angularXDrive + { + get + { + JointDrive result; + this.INTERNAL_get_angularXDrive(out result); + return result; + } + set + { + this.INTERNAL_set_angularXDrive(ref value); + } + } + public JointDrive angularYZDrive + { + get + { + JointDrive result; + this.INTERNAL_get_angularYZDrive(out result); + return result; + } + set + { + this.INTERNAL_set_angularYZDrive(ref value); + } + } + public JointDrive slerpDrive + { + get + { + JointDrive result; + this.INTERNAL_get_slerpDrive(out result); + return result; + } + set + { + this.INTERNAL_set_slerpDrive(ref value); + } + } + public extern JointProjectionMode projectionMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float projectionDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float projectionAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool configuredInWorldSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool swapBodies + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_secondaryAxis(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_secondaryAxis(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_linearLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_linearLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_lowAngularXLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_lowAngularXLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_highAngularXLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_highAngularXLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularYLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularYLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularZLimit(out SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularZLimit(ref SoftJointLimit value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetVelocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_xDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_xDrive(ref JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_yDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_yDrive(ref JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_zDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_zDrive(ref JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_targetAngularVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_targetAngularVelocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularXDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularXDrive(ref JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularYZDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularYZDrive(ref JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_slerpDrive(out JointDrive value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_slerpDrive(ref JointDrive value); + } +} diff --git a/UnityEngine/UnityEngine/ConfigurableJointMotion.cs b/UnityEngine/UnityEngine/ConfigurableJointMotion.cs new file mode 100644 index 00000000..5fe3205c --- /dev/null +++ b/UnityEngine/UnityEngine/ConfigurableJointMotion.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum ConfigurableJointMotion + { + Locked, + Limited, + Free + } +} diff --git a/UnityEngine/UnityEngine/ConnectionTesterStatus.cs b/UnityEngine/UnityEngine/ConnectionTesterStatus.cs new file mode 100644 index 00000000..49c51432 --- /dev/null +++ b/UnityEngine/UnityEngine/ConnectionTesterStatus.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine +{ + public enum ConnectionTesterStatus + { + Error = -2, + Undetermined, + PrivateIPNoNATPunchthrough, + PrivateIPHasNATPunchThrough, + PublicIPIsConnectable, + PublicIPPortBlocked, + PublicIPNoServerStarted, + LimitedNATPunchthroughPortRestricted, + LimitedNATPunchthroughSymmetric, + NATpunchthroughFullCone, + NATpunchthroughAddressRestrictedCone + } +} diff --git a/UnityEngine/UnityEngine/ConstantForce.cs b/UnityEngine/UnityEngine/ConstantForce.cs new file mode 100644 index 00000000..355c57df --- /dev/null +++ b/UnityEngine/UnityEngine/ConstantForce.cs @@ -0,0 +1,84 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ConstantForce : Behaviour + { + public Vector3 force + { + get + { + Vector3 result; + this.INTERNAL_get_force(out result); + return result; + } + set + { + this.INTERNAL_set_force(ref value); + } + } + public Vector3 relativeForce + { + get + { + Vector3 result; + this.INTERNAL_get_relativeForce(out result); + return result; + } + set + { + this.INTERNAL_set_relativeForce(ref value); + } + } + public Vector3 torque + { + get + { + Vector3 result; + this.INTERNAL_get_torque(out result); + return result; + } + set + { + this.INTERNAL_set_torque(ref value); + } + } + public Vector3 relativeTorque + { + get + { + Vector3 result; + this.INTERNAL_get_relativeTorque(out result); + return result; + } + set + { + this.INTERNAL_set_relativeTorque(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_force(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_force(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_relativeForce(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_relativeForce(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_torque(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_torque(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_relativeTorque(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_relativeTorque(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/ConstructorSafeAttribute.cs b/UnityEngine/UnityEngine/ConstructorSafeAttribute.cs new file mode 100644 index 00000000..3a9a0de9 --- /dev/null +++ b/UnityEngine/UnityEngine/ConstructorSafeAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false)] + public class ConstructorSafeAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/ContactPoint.cs b/UnityEngine/UnityEngine/ContactPoint.cs new file mode 100644 index 00000000..32dca647 --- /dev/null +++ b/UnityEngine/UnityEngine/ContactPoint.cs @@ -0,0 +1,39 @@ +using System; +namespace UnityEngine +{ + public struct ContactPoint + { + internal Vector3 m_Point; + internal Vector3 m_Normal; + internal Collider m_ThisCollider; + internal Collider m_OtherCollider; + public Vector3 point + { + get + { + return this.m_Point; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + } + public Collider thisCollider + { + get + { + return this.m_ThisCollider; + } + } + public Collider otherCollider + { + get + { + return this.m_OtherCollider; + } + } + } +} diff --git a/UnityEngine/UnityEngine/ContactPoint2D.cs b/UnityEngine/UnityEngine/ContactPoint2D.cs new file mode 100644 index 00000000..05cb88d3 --- /dev/null +++ b/UnityEngine/UnityEngine/ContactPoint2D.cs @@ -0,0 +1,39 @@ +using System; +namespace UnityEngine +{ + public struct ContactPoint2D + { + internal Vector2 m_Point; + internal Vector2 m_Normal; + internal Collider2D m_Collider; + internal Collider2D m_OtherCollider; + public Vector2 point + { + get + { + return this.m_Point; + } + } + public Vector2 normal + { + get + { + return this.m_Normal; + } + } + public Collider2D collider + { + get + { + return this.m_Collider; + } + } + public Collider2D otherCollider + { + get + { + return this.m_OtherCollider; + } + } + } +} diff --git a/UnityEngine/UnityEngine/ContextMenu.cs b/UnityEngine/UnityEngine/ContextMenu.cs new file mode 100644 index 00000000..bd2984f8 --- /dev/null +++ b/UnityEngine/UnityEngine/ContextMenu.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEngine +{ + public sealed class ContextMenu : Attribute + { + private string m_ItemName; + public string menuItem + { + get + { + return this.m_ItemName; + } + } + public ContextMenu(string name) + { + this.m_ItemName = name; + } + } +} diff --git a/UnityEngine/UnityEngine/ContextMenuItemAttribute.cs b/UnityEngine/UnityEngine/ContextMenuItemAttribute.cs new file mode 100644 index 00000000..ddb7bf52 --- /dev/null +++ b/UnityEngine/UnityEngine/ContextMenuItemAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] + public class ContextMenuItemAttribute : PropertyAttribute + { + public readonly string name; + public readonly string function; + public ContextMenuItemAttribute(string name, string function) + { + this.name = name; + this.function = function; + } + } +} diff --git a/UnityEngine/UnityEngine/ControllerColliderHit.cs b/UnityEngine/UnityEngine/ControllerColliderHit.cs new file mode 100644 index 00000000..40218e56 --- /dev/null +++ b/UnityEngine/UnityEngine/ControllerColliderHit.cs @@ -0,0 +1,90 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class ControllerColliderHit + { + internal CharacterController m_Controller; + internal Collider m_Collider; + internal Vector3 m_Point; + internal Vector3 m_Normal; + internal Vector3 m_MoveDirection; + internal float m_MoveLength; + internal int m_Push; + public CharacterController controller + { + get + { + return this.m_Controller; + } + } + public Collider collider + { + get + { + return this.m_Collider; + } + } + public Rigidbody rigidbody + { + get + { + return this.m_Collider.attachedRigidbody; + } + } + public GameObject gameObject + { + get + { + return this.m_Collider.gameObject; + } + } + public Transform transform + { + get + { + return this.m_Collider.transform; + } + } + public Vector3 point + { + get + { + return this.m_Point; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + } + public Vector3 moveDirection + { + get + { + return this.m_MoveDirection; + } + } + public float moveLength + { + get + { + return this.m_MoveLength; + } + } + private bool push + { + get + { + return this.m_Push != 0; + } + set + { + this.m_Push = ((!value) ? 0 : 1); + } + } + } +} diff --git a/UnityEngine/UnityEngine/Coroutine.cs b/UnityEngine/UnityEngine/Coroutine.cs new file mode 100644 index 00000000..eb208710 --- /dev/null +++ b/UnityEngine/UnityEngine/Coroutine.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class Coroutine : YieldInstruction + { + internal IntPtr m_Ptr; + private Coroutine() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void ReleaseCoroutine(); + ~Coroutine() + { + this.ReleaseCoroutine(); + } + } +} diff --git a/UnityEngine/UnityEngine/CppBodyAttribute.cs b/UnityEngine/UnityEngine/CppBodyAttribute.cs new file mode 100644 index 00000000..c16849c1 --- /dev/null +++ b/UnityEngine/UnityEngine/CppBodyAttribute.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false)] + internal class CppBodyAttribute : Attribute + { + public CppBodyAttribute(string body) + { + } + } +} diff --git a/UnityEngine/UnityEngine/CppDefineAttribute.cs b/UnityEngine/UnityEngine/CppDefineAttribute.cs new file mode 100644 index 00000000..ac51811c --- /dev/null +++ b/UnityEngine/UnityEngine/CppDefineAttribute.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)] + internal class CppDefineAttribute : Attribute + { + public CppDefineAttribute(string symbol, string value) + { + } + } +} diff --git a/UnityEngine/UnityEngine/CppIncludeAttribute.cs b/UnityEngine/UnityEngine/CppIncludeAttribute.cs new file mode 100644 index 00000000..2f098160 --- /dev/null +++ b/UnityEngine/UnityEngine/CppIncludeAttribute.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true)] + internal class CppIncludeAttribute : Attribute + { + public CppIncludeAttribute(string header) + { + } + } +} diff --git a/UnityEngine/UnityEngine/CppInvokeAttribute.cs b/UnityEngine/UnityEngine/CppInvokeAttribute.cs new file mode 100644 index 00000000..8a86bab1 --- /dev/null +++ b/UnityEngine/UnityEngine/CppInvokeAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + internal class CppInvokeAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/CppPropertyAttribute.cs b/UnityEngine/UnityEngine/CppPropertyAttribute.cs new file mode 100644 index 00000000..695f6065 --- /dev/null +++ b/UnityEngine/UnityEngine/CppPropertyAttribute.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + internal class CppPropertyAttribute : Attribute + { + public CppPropertyAttribute(string getter, string setter) + { + } + public CppPropertyAttribute(string getter) + { + } + } +} diff --git a/UnityEngine/UnityEngine/CppPropertyBodyAttribute.cs b/UnityEngine/UnityEngine/CppPropertyBodyAttribute.cs new file mode 100644 index 00000000..6a40cb8f --- /dev/null +++ b/UnityEngine/UnityEngine/CppPropertyBodyAttribute.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] + internal class CppPropertyBodyAttribute : Attribute + { + public CppPropertyBodyAttribute(string getterBody, string setterBody) + { + } + public CppPropertyBodyAttribute(string getterBody) + { + } + } +} diff --git a/UnityEngine/UnityEngine/CrashReport.cs b/UnityEngine/UnityEngine/CrashReport.cs new file mode 100644 index 00000000..348ba89b --- /dev/null +++ b/UnityEngine/UnityEngine/CrashReport.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; +namespace UnityEngine +{ + public sealed class CrashReport + { + private static List internalReports; + private static object reportsLock = new object(); + private readonly string id; + public readonly DateTime time; + public readonly string text; + public static CrashReport[] reports + { + get + { + CrashReport.PopulateReports(); + object obj = CrashReport.reportsLock; + Monitor.Enter(obj); + CrashReport[] result; + try + { + result = CrashReport.internalReports.ToArray(); + } + finally + { + Monitor.Exit(obj); + } + return result; + } + } + public static CrashReport lastReport + { + get + { + CrashReport.PopulateReports(); + object obj = CrashReport.reportsLock; + Monitor.Enter(obj); + try + { + if (CrashReport.internalReports.Count > 0) + { + return CrashReport.internalReports[CrashReport.internalReports.Count - 1]; + } + } + finally + { + Monitor.Exit(obj); + } + return null; + } + } + private CrashReport(string id, DateTime time, string text) + { + this.id = id; + this.time = time; + this.text = text; + } + private static int Compare(CrashReport c1, CrashReport c2) + { + long ticks = c1.time.Ticks; + long ticks2 = c2.time.Ticks; + if (ticks > ticks2) + { + return 1; + } + if (ticks < ticks2) + { + return -1; + } + return 0; + } + private static void PopulateReports() + { + object obj = CrashReport.reportsLock; + Monitor.Enter(obj); + try + { + if (CrashReport.internalReports == null) + { + string[] reports = CrashReport.GetReports(); + CrashReport.internalReports = new List(reports.Length); + string[] array = reports; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + double value; + string text2; + CrashReport.GetReportData(text, out value, out text2); + DateTime dateTime = new DateTime(1970, 1, 1); + DateTime dateTime2 = dateTime.AddSeconds(value); + CrashReport.internalReports.Add(new CrashReport(text, dateTime2, text2)); + } + CrashReport.internalReports.Sort(new Comparison(CrashReport.Compare)); + } + } + finally + { + Monitor.Exit(obj); + } + } + public static void RemoveAll() + { + CrashReport[] reports = CrashReport.reports; + for (int i = 0; i < reports.Length; i++) + { + CrashReport crashReport = reports[i]; + crashReport.Remove(); + } + } + public void Remove() + { + if (CrashReport.RemoveReport(this.id)) + { + object obj = CrashReport.reportsLock; + Monitor.Enter(obj); + try + { + CrashReport.internalReports.Remove(this); + } + finally + { + Monitor.Exit(obj); + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string[] GetReports(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetReportData(string id, out double secondsSinceUnixEpoch, out string text); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool RemoveReport(string id); + } +} diff --git a/UnityEngine/UnityEngine/Cubemap.cs b/UnityEngine/UnityEngine/Cubemap.cs new file mode 100644 index 00000000..4089a426 --- /dev/null +++ b/UnityEngine/UnityEngine/Cubemap.cs @@ -0,0 +1,75 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Cubemap : Texture + { + public extern TextureFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Cubemap(int size, TextureFormat format, bool mipmap) + { + Cubemap.Internal_Create(this, size, format, mipmap); + } + public void SetPixel(CubemapFace face, int x, int y, Color color) + { + Cubemap.INTERNAL_CALL_SetPixel(this, face, x, y, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetPixel(Cubemap self, CubemapFace face, int x, int y, ref Color color); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetPixel(CubemapFace face, int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color[] GetPixels(CubemapFace face, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public Color[] GetPixels(CubemapFace face) + { + int miplevel = 0; + return this.GetPixels(face, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPixels(Color[] colors, CubemapFace face, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public void SetPixels(Color[] colors, CubemapFace face) + { + int miplevel = 0; + this.SetPixels(colors, face, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Apply([DefaultValue("true")] bool updateMipmaps, [DefaultValue("false")] bool makeNoLongerReadable); + [ExcludeFromDocs] + public void Apply(bool updateMipmaps) + { + bool makeNoLongerReadable = false; + this.Apply(updateMipmaps, makeNoLongerReadable); + } + [ExcludeFromDocs] + public void Apply() + { + bool makeNoLongerReadable = false; + bool updateMipmaps = true; + this.Apply(updateMipmaps, makeNoLongerReadable); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] Cubemap mono, int size, TextureFormat format, bool mipmap); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SmoothEdges([DefaultValue("1")] int smoothRegionWidthInPixels); + [ExcludeFromDocs] + public void SmoothEdges() + { + int smoothRegionWidthInPixels = 1; + this.SmoothEdges(smoothRegionWidthInPixels); + } + } +} diff --git a/UnityEngine/UnityEngine/CubemapFace.cs b/UnityEngine/UnityEngine/CubemapFace.cs new file mode 100644 index 00000000..0515d87a --- /dev/null +++ b/UnityEngine/UnityEngine/CubemapFace.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum CubemapFace + { + PositiveX, + NegativeX, + PositiveY, + NegativeY, + PositiveZ, + NegativeZ + } +} diff --git a/UnityEngine/UnityEngine/Cursor.cs b/UnityEngine/UnityEngine/Cursor.cs new file mode 100644 index 00000000..445dfd51 --- /dev/null +++ b/UnityEngine/UnityEngine/Cursor.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Cursor + { + private static void SetCursor(Texture2D texture, CursorMode cursorMode) + { + Cursor.SetCursor(texture, Vector2.zero, cursorMode); + } + public static void SetCursor(Texture2D texture, Vector2 hotspot, CursorMode cursorMode) + { + Cursor.INTERNAL_CALL_SetCursor(texture, ref hotspot, cursorMode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetCursor(Texture2D texture, ref Vector2 hotspot, CursorMode cursorMode); + } +} diff --git a/UnityEngine/UnityEngine/CursorMode.cs b/UnityEngine/UnityEngine/CursorMode.cs new file mode 100644 index 00000000..bf138ccb --- /dev/null +++ b/UnityEngine/UnityEngine/CursorMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum CursorMode + { + Auto, + ForceSoftware + } +} diff --git a/UnityEngine/UnityEngine/Debug.cs b/UnityEngine/UnityEngine/Debug.cs new file mode 100644 index 00000000..4d85dcfa --- /dev/null +++ b/UnityEngine/UnityEngine/Debug.cs @@ -0,0 +1,130 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Debug + { + public static extern bool developerConsoleVisible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool isDebugBuild + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static void DrawLine(Vector3 start, Vector3 end, [DefaultValue("Color.white")] Color color, [DefaultValue("0.0f")] float duration, [DefaultValue("true")] bool depthTest) + { + Debug.INTERNAL_CALL_DrawLine(ref start, ref end, ref color, duration, depthTest); + } + [ExcludeFromDocs] + public static void DrawLine(Vector3 start, Vector3 end, Color color, float duration) + { + bool depthTest = true; + Debug.INTERNAL_CALL_DrawLine(ref start, ref end, ref color, duration, depthTest); + } + [ExcludeFromDocs] + public static void DrawLine(Vector3 start, Vector3 end, Color color) + { + bool depthTest = true; + float duration = 0f; + Debug.INTERNAL_CALL_DrawLine(ref start, ref end, ref color, duration, depthTest); + } + [ExcludeFromDocs] + public static void DrawLine(Vector3 start, Vector3 end) + { + bool depthTest = true; + float duration = 0f; + Color white = Color.white; + Debug.INTERNAL_CALL_DrawLine(ref start, ref end, ref white, duration, depthTest); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawLine(ref Vector3 start, ref Vector3 end, ref Color color, float duration, bool depthTest); + [ExcludeFromDocs] + public static void DrawRay(Vector3 start, Vector3 dir, Color color, float duration) + { + bool depthTest = true; + Debug.DrawRay(start, dir, color, duration, depthTest); + } + [ExcludeFromDocs] + public static void DrawRay(Vector3 start, Vector3 dir, Color color) + { + bool depthTest = true; + float duration = 0f; + Debug.DrawRay(start, dir, color, duration, depthTest); + } + [ExcludeFromDocs] + public static void DrawRay(Vector3 start, Vector3 dir) + { + bool depthTest = true; + float duration = 0f; + Color white = Color.white; + Debug.DrawRay(start, dir, white, duration, depthTest); + } + public static void DrawRay(Vector3 start, Vector3 dir, [DefaultValue("Color.white")] Color color, [DefaultValue("0.0f")] float duration, [DefaultValue("true")] bool depthTest) + { + Debug.DrawLine(start, start + dir, color, duration, depthTest); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Break(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DebugBreak(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Log(int level, string msg, [Writable] Object obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_LogException(Exception exception, [Writable] Object obj); + public static void Log(object message) + { + Debug.Internal_Log(0, (message == null) ? "Null" : message.ToString(), null); + } + public static void Log(object message, Object context) + { + Debug.Internal_Log(0, (message == null) ? "Null" : message.ToString(), context); + } + public static void LogError(object message) + { + Debug.Internal_Log(2, (message == null) ? "Null" : message.ToString(), null); + } + public static void LogError(object message, Object context) + { + Debug.Internal_Log(2, message.ToString(), context); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearDeveloperConsole(); + public static void LogException(Exception exception) + { + Debug.Internal_LogException(exception, null); + } + public static void LogException(Exception exception, Object context) + { + Debug.Internal_LogException(exception, context); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void LogPlayerBuildError(string message, string file, int line, int column); + public static void LogWarning(object message) + { + Debug.Internal_Log(1, message.ToString(), null); + } + public static void LogWarning(object message, Object context) + { + Debug.Internal_Log(1, message.ToString(), context); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void OpenConsoleFile(); + } +} diff --git a/UnityEngine/UnityEngine/DepthTextureMode.cs b/UnityEngine/UnityEngine/DepthTextureMode.cs new file mode 100644 index 00000000..6e464235 --- /dev/null +++ b/UnityEngine/UnityEngine/DepthTextureMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum DepthTextureMode + { + None = 0, + Depth = 1, + DepthNormals = 2 + } +} diff --git a/UnityEngine/UnityEngine/DetailPrototype.cs b/UnityEngine/UnityEngine/DetailPrototype.cs new file mode 100644 index 00000000..9dfbf734 --- /dev/null +++ b/UnityEngine/UnityEngine/DetailPrototype.cs @@ -0,0 +1,153 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class DetailPrototype + { + private GameObject m_Prototype; + private Texture2D m_PrototypeTexture; + private Color m_HealthyColor = new Color(0.2627451f, 0.9764706f, 0.164705887f, 1f); + private Color m_DryColor = new Color(0.8039216f, 0.7372549f, 0.101960786f, 1f); + private float m_MinWidth = 1f; + private float m_MaxWidth = 2f; + private float m_MinHeight = 1f; + private float m_MaxHeight = 2f; + private float m_NoiseSpread = 0.1f; + private float m_BendFactor = 0.1f; + private int m_RenderMode = 2; + private int m_UsePrototypeMesh; + public GameObject prototype + { + get + { + return this.m_Prototype; + } + set + { + this.m_Prototype = value; + } + } + public Texture2D prototypeTexture + { + get + { + return this.m_PrototypeTexture; + } + set + { + this.m_PrototypeTexture = value; + } + } + public float minWidth + { + get + { + return this.m_MinWidth; + } + set + { + this.m_MinWidth = value; + } + } + public float maxWidth + { + get + { + return this.m_MaxWidth; + } + set + { + this.m_MaxWidth = value; + } + } + public float minHeight + { + get + { + return this.m_MinHeight; + } + set + { + this.m_MinHeight = value; + } + } + public float maxHeight + { + get + { + return this.m_MaxHeight; + } + set + { + this.m_MaxHeight = value; + } + } + public float noiseSpread + { + get + { + return this.m_NoiseSpread; + } + set + { + this.m_NoiseSpread = value; + } + } + public float bendFactor + { + get + { + return this.m_BendFactor; + } + set + { + this.m_BendFactor = value; + } + } + public Color healthyColor + { + get + { + return this.m_HealthyColor; + } + set + { + this.m_HealthyColor = value; + } + } + public Color dryColor + { + get + { + return this.m_DryColor; + } + set + { + this.m_DryColor = value; + } + } + public DetailRenderMode renderMode + { + get + { + return (DetailRenderMode)this.m_RenderMode; + } + set + { + this.m_RenderMode = (int)value; + } + } + public bool usePrototypeMesh + { + get + { + return this.m_UsePrototypeMesh != 0; + } + set + { + this.m_UsePrototypeMesh = ((!value) ? 0 : 1); + } + } + } +} diff --git a/UnityEngine/UnityEngine/DetailRenderMode.cs b/UnityEngine/UnityEngine/DetailRenderMode.cs new file mode 100644 index 00000000..f733e655 --- /dev/null +++ b/UnityEngine/UnityEngine/DetailRenderMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum DetailRenderMode + { + GrassBillboard, + VertexLit, + Grass + } +} diff --git a/UnityEngine/UnityEngine/DeviceOrientation.cs b/UnityEngine/UnityEngine/DeviceOrientation.cs new file mode 100644 index 00000000..08706127 --- /dev/null +++ b/UnityEngine/UnityEngine/DeviceOrientation.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public enum DeviceOrientation + { + Unknown, + Portrait, + PortraitUpsideDown, + LandscapeLeft, + LandscapeRight, + FaceUp, + FaceDown + } +} diff --git a/UnityEngine/UnityEngine/DeviceType.cs b/UnityEngine/UnityEngine/DeviceType.cs new file mode 100644 index 00000000..fed283cc --- /dev/null +++ b/UnityEngine/UnityEngine/DeviceType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum DeviceType + { + Unknown, + Handheld, + Console, + Desktop + } +} diff --git a/UnityEngine/UnityEngine/DisallowMultipleComponent.cs b/UnityEngine/UnityEngine/DisallowMultipleComponent.cs new file mode 100644 index 00000000..1055417e --- /dev/null +++ b/UnityEngine/UnityEngine/DisallowMultipleComponent.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class, Inherited = false)] + public sealed class DisallowMultipleComponent : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/Display.cs b/UnityEngine/UnityEngine/Display.cs new file mode 100644 index 00000000..0b2e87bd --- /dev/null +++ b/UnityEngine/UnityEngine/Display.cs @@ -0,0 +1,147 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Display + { + public delegate void DisplaysUpdatedDelegate(); + internal IntPtr nativeDisplay; + public static Display[] displays = new Display[] + { + new Display() + }; + private static Display _mainDisplay = Display.displays[0]; + public static event Display.DisplaysUpdatedDelegate onDisplaysUpdated + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + Display.onDisplaysUpdated = (Display.DisplaysUpdatedDelegate)Delegate.Combine(Display.onDisplaysUpdated, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + Display.onDisplaysUpdated = (Display.DisplaysUpdatedDelegate)Delegate.Remove(Display.onDisplaysUpdated, value); + } + } + public int renderingWidth + { + get + { + int result = 0; + int num = 0; + Display.GetRenderingExtImpl(this.nativeDisplay, out result, out num); + return result; + } + } + public int renderingHeight + { + get + { + int num = 0; + int result = 0; + Display.GetRenderingExtImpl(this.nativeDisplay, out num, out result); + return result; + } + } + public int systemWidth + { + get + { + int result = 0; + int num = 0; + Display.GetSystemExtImpl(this.nativeDisplay, out result, out num); + return result; + } + } + public int systemHeight + { + get + { + int num = 0; + int result = 0; + Display.GetSystemExtImpl(this.nativeDisplay, out num, out result); + return result; + } + } + public RenderBuffer colorBuffer + { + get + { + RenderBuffer result; + RenderBuffer renderBuffer; + Display.GetRenderingBuffersImpl(this.nativeDisplay, out result, out renderBuffer); + return result; + } + } + public RenderBuffer depthBuffer + { + get + { + RenderBuffer renderBuffer; + RenderBuffer result; + Display.GetRenderingBuffersImpl(this.nativeDisplay, out renderBuffer, out result); + return result; + } + } + public static Display main + { + get + { + return Display._mainDisplay; + } + } + internal Display() + { + this.nativeDisplay = new IntPtr(0); + } + internal Display(IntPtr nativeDisplay) + { + this.nativeDisplay = nativeDisplay; + } + static Display() + { + // Note: this type is marked as 'beforefieldinit'. + Display.onDisplaysUpdated = null; + } + public void Activate() + { + Display.ActivateDisplayImpl(this.nativeDisplay); + } + public void SetRenderingResolution(int w, int h) + { + Display.SetRenderingResolutionImpl(this.nativeDisplay, w, h); + } + private static void RecreateDisplayList(IntPtr[] nativeDisplay) + { + Display.displays = new Display[nativeDisplay.Length]; + for (int i = 0; i < nativeDisplay.Length; i++) + { + Display.displays[i] = new Display(nativeDisplay[i]); + } + Display._mainDisplay = Display.displays[0]; + } + private static void FireDisplaysUpdated() + { + if (Display.onDisplaysUpdated != null) + { + Display.onDisplaysUpdated(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetSystemExtImpl(IntPtr nativeDisplay, out int w, out int h); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetRenderingExtImpl(IntPtr nativeDisplay, out int w, out int h); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetRenderingBuffersImpl(IntPtr nativeDisplay, out RenderBuffer color, out RenderBuffer depth); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetRenderingResolutionImpl(IntPtr nativeDisplay, int w, int h); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void ActivateDisplayImpl(IntPtr nativeDisplay); + } +} diff --git a/UnityEngine/UnityEngine/DistanceJoint2D.cs b/UnityEngine/UnityEngine/DistanceJoint2D.cs new file mode 100644 index 00000000..180869fd --- /dev/null +++ b/UnityEngine/UnityEngine/DistanceJoint2D.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class DistanceJoint2D : AnchoredJoint2D + { + public extern float distance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool maxDistanceOnly + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 GetReactionForce(float timeStep) + { + Vector2 result; + DistanceJoint2D.DistanceJoint2D_CUSTOM_INTERNAL_GetReactionForce(this, timeStep, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void DistanceJoint2D_CUSTOM_INTERNAL_GetReactionForce(DistanceJoint2D joint, float timeStep, out Vector2 value); + public float GetReactionTorque(float timeStep) + { + return DistanceJoint2D.INTERNAL_CALL_GetReactionTorque(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetReactionTorque(DistanceJoint2D self, float timeStep); + } +} diff --git a/UnityEngine/UnityEngine/DoF.cs b/UnityEngine/UnityEngine/DoF.cs new file mode 100644 index 00000000..dbefa21c --- /dev/null +++ b/UnityEngine/UnityEngine/DoF.cs @@ -0,0 +1,24 @@ +using System; +namespace UnityEngine +{ + internal enum DoF + { + BodyDoFStart, + HeadDoFStart = 6, + LeftLegDoFStart = 18, + RightLegDoFStart = 26, + LeftArmDoFStart = 34, + RightArmDoFStart = 43, + LeftThumbDoFStart = 52, + LeftIndexDoFStart = 56, + LeftMiddleDoFStart = 60, + LeftRingDoFStart = 64, + LeftLittleDoFStart = 68, + RightThumbDoFStart = 72, + RightIndexDoFStart = 76, + RightMiddleDoFStart = 80, + RightRingDoFStart = 84, + RightLittleDoFStart = 88, + LastDoF = 92 + } +} diff --git a/UnityEngine/UnityEngine/DrivenRectTransformTracker.cs b/UnityEngine/UnityEngine/DrivenRectTransformTracker.cs new file mode 100644 index 00000000..a28ce8e0 --- /dev/null +++ b/UnityEngine/UnityEngine/DrivenRectTransformTracker.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +namespace UnityEngine +{ + public struct DrivenRectTransformTracker + { + private List m_Tracked; + public void Add(Object driver, RectTransform rectTransform, DrivenTransformProperties drivenProperties) + { + if (this.m_Tracked == null) + { + this.m_Tracked = new List(); + } + if (!Application.isPlaying) + { + RuntimeUndo.RecordObject(rectTransform, "Driving RectTransform"); + } + this.m_Tracked.Add(rectTransform); + rectTransform.drivenByObject = driver; + rectTransform.drivenProperties |= drivenProperties; + } + public void Clear() + { + if (this.m_Tracked != null) + { + for (int i = 0; i < this.m_Tracked.Count; i++) + { + if (this.m_Tracked[i] != null) + { + if (!Application.isPlaying) + { + RuntimeUndo.RecordObject(this.m_Tracked[i], "Driving RectTransform"); + } + this.m_Tracked[i].drivenByObject = null; + } + } + this.m_Tracked.Clear(); + } + } + } +} diff --git a/UnityEngine/UnityEngine/DrivenTransformProperties.cs b/UnityEngine/UnityEngine/DrivenTransformProperties.cs new file mode 100644 index 00000000..6d30caec --- /dev/null +++ b/UnityEngine/UnityEngine/DrivenTransformProperties.cs @@ -0,0 +1,33 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum DrivenTransformProperties + { + None = 0, + All = -1, + AnchoredPositionX = 2, + AnchoredPositionY = 4, + AnchoredPositionZ = 8, + Rotation = 16, + ScaleX = 32, + ScaleY = 64, + ScaleZ = 128, + AnchorMinX = 256, + AnchorMinY = 512, + AnchorMaxX = 1024, + AnchorMaxY = 2048, + SizeDeltaX = 4096, + SizeDeltaY = 8192, + PivotX = 16384, + PivotY = 32768, + AnchoredPosition = 6, + AnchoredPosition3D = 14, + Scale = 224, + AnchorMin = 768, + AnchorMax = 3072, + Anchors = 3840, + SizeDelta = 12288, + Pivot = 49152 + } +} diff --git a/UnityEngine/UnityEngine/EdgeCollider2D.cs b/UnityEngine/UnityEngine/EdgeCollider2D.cs new file mode 100644 index 00000000..e028bb69 --- /dev/null +++ b/UnityEngine/UnityEngine/EdgeCollider2D.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class EdgeCollider2D : Collider2D + { + public extern int edgeCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int pointCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector2[] points + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Reset(); + } +} diff --git a/UnityEngine/UnityEngine/Event.cs b/UnityEngine/UnityEngine/Event.cs new file mode 100644 index 00000000..5b78b144 --- /dev/null +++ b/UnityEngine/UnityEngine/Event.cs @@ -0,0 +1,718 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class Event + { + [NotRenamed] + [NonSerialized] + internal IntPtr m_Ptr; + private static Event s_Current; + private static Event s_MasterEvent; + public extern EventType rawType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern EventType type + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 mousePosition + { + get + { + Vector2 result; + this.Internal_GetMousePosition(out result); + return result; + } + set + { + this.Internal_SetMousePosition(value); + } + } + public Vector2 delta + { + get + { + Vector2 result; + this.Internal_GetMouseDelta(out result); + return result; + } + set + { + this.Internal_SetMouseDelta(value); + } + } + [Obsolete("Use HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);", true)] + public Ray mouseRay + { + get + { + return new Ray(Vector3.up, Vector3.up); + } + set + { + } + } + public extern int button + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern EventModifiers modifiers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pressure + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int clickCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern char character + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string commandName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern KeyCode keyCode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool shift + { + get + { + return (this.modifiers & EventModifiers.Shift) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.Shift; + } + else + { + this.modifiers |= EventModifiers.Shift; + } + } + } + public bool control + { + get + { + return (this.modifiers & EventModifiers.Control) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.Control; + } + else + { + this.modifiers |= EventModifiers.Control; + } + } + } + public bool alt + { + get + { + return (this.modifiers & EventModifiers.Alt) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.Alt; + } + else + { + this.modifiers |= EventModifiers.Alt; + } + } + } + public bool command + { + get + { + return (this.modifiers & EventModifiers.Command) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.Command; + } + else + { + this.modifiers |= EventModifiers.Command; + } + } + } + public bool capsLock + { + get + { + return (this.modifiers & EventModifiers.CapsLock) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.CapsLock; + } + else + { + this.modifiers |= EventModifiers.CapsLock; + } + } + } + public bool numeric + { + get + { + return (this.modifiers & EventModifiers.Numeric) != EventModifiers.None; + } + set + { + if (!value) + { + this.modifiers &= ~EventModifiers.Shift; + } + else + { + this.modifiers |= EventModifiers.Shift; + } + } + } + public bool functionKey + { + get + { + return (this.modifiers & EventModifiers.FunctionKey) != EventModifiers.None; + } + } + public static Event current + { + get + { + if (GUIUtility.Internal_GetGUIDepth() > 0) + { + return Event.s_Current; + } + return null; + } + set + { + if (value != null) + { + Event.s_Current = value; + } + else + { + Event.s_Current = Event.s_MasterEvent; + } + Event.Internal_SetNativeEvent(Event.s_Current.m_Ptr); + } + } + public bool isKey + { + get + { + EventType type = this.type; + return type == EventType.KeyDown || type == EventType.KeyUp; + } + } + public bool isMouse + { + get + { + EventType type = this.type; + return type == EventType.MouseMove || type == EventType.MouseDown || type == EventType.MouseUp || type == EventType.MouseDrag; + } + } + public Event() + { + this.Init(); + } + public Event(Event other) + { + if (other == null) + { + throw new ArgumentException("Event to copy from is null."); + } + this.InitCopy(other); + } + private Event(IntPtr ptr) + { + this.InitPtr(ptr); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + ~Event() + { + this.Cleanup(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InitCopy(Event other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InitPtr(IntPtr ptr); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern EventType GetTypeForControl(int controlID); + private void Internal_SetMousePosition(Vector2 value) + { + Event.INTERNAL_CALL_Internal_SetMousePosition(this, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetMousePosition(Event self, ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_GetMousePosition(out Vector2 value); + private void Internal_SetMouseDelta(Vector2 value) + { + Event.INTERNAL_CALL_Internal_SetMouseDelta(this, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetMouseDelta(Event self, ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_GetMouseDelta(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetNativeEvent(IntPtr ptr); + private static void Internal_MakeMasterEventCurrent() + { + if (Event.s_MasterEvent == null) + { + Event.s_MasterEvent = new Event(); + } + Event.s_Current = Event.s_MasterEvent; + Event.Internal_SetNativeEvent(Event.s_MasterEvent.m_Ptr); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Use(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool PopEvent(Event outEvent); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetEventCount(); + public static Event KeyboardEvent(string key) + { + Event @event = new Event(); + @event.type = EventType.KeyDown; + if (key == null || key == string.Empty) + { + return @event; + } + int num = 0; + bool flag; + do + { + flag = true; + if (num >= key.Length) + { + break; + } + char c = key[num]; + switch (c) + { + case '#': + @event.modifiers |= EventModifiers.Shift; + num++; + goto IL_D2; + case '$': + IL_61: + if (c != '^') + { + flag = false; + goto IL_D2; + } + @event.modifiers |= EventModifiers.Control; + num++; + goto IL_D2; + case '%': + @event.modifiers |= EventModifiers.Command; + num++; + goto IL_D2; + case '&': + @event.modifiers |= EventModifiers.Alt; + num++; + goto IL_D2; + } + goto IL_61; + IL_D2:; + } + while (flag); + string text = key.Substring(num, key.Length - num).ToLower(); + string text2 = text; + switch (text2) + { + case "[0]": + @event.character = '0'; + @event.keyCode = KeyCode.Keypad0; + return @event; + case "[1]": + @event.character = '1'; + @event.keyCode = KeyCode.Keypad1; + return @event; + case "[2]": + @event.character = '2'; + @event.keyCode = KeyCode.Keypad2; + return @event; + case "[3]": + @event.character = '3'; + @event.keyCode = KeyCode.Keypad3; + return @event; + case "[4]": + @event.character = '4'; + @event.keyCode = KeyCode.Keypad4; + return @event; + case "[5]": + @event.character = '5'; + @event.keyCode = KeyCode.Keypad5; + return @event; + case "[6]": + @event.character = '6'; + @event.keyCode = KeyCode.Keypad6; + return @event; + case "[7]": + @event.character = '7'; + @event.keyCode = KeyCode.Keypad7; + return @event; + case "[8]": + @event.character = '8'; + @event.keyCode = KeyCode.Keypad8; + return @event; + case "[9]": + @event.character = '9'; + @event.keyCode = KeyCode.Keypad9; + return @event; + case "[.]": + @event.character = '.'; + @event.keyCode = KeyCode.KeypadPeriod; + return @event; + case "[/]": + @event.character = '/'; + @event.keyCode = KeyCode.KeypadDivide; + return @event; + case "[-]": + @event.character = '-'; + @event.keyCode = KeyCode.KeypadMinus; + return @event; + case "[+]": + @event.character = '+'; + @event.keyCode = KeyCode.KeypadPlus; + return @event; + case "[=]": + @event.character = '='; + @event.keyCode = KeyCode.KeypadEquals; + return @event; + case "[equals]": + @event.character = '='; + @event.keyCode = KeyCode.KeypadEquals; + return @event; + case "[enter]": + @event.character = '\n'; + @event.keyCode = KeyCode.KeypadEnter; + return @event; + case "up": + @event.keyCode = KeyCode.UpArrow; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "down": + @event.keyCode = KeyCode.DownArrow; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "left": + @event.keyCode = KeyCode.LeftArrow; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "right": + @event.keyCode = KeyCode.RightArrow; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "insert": + @event.keyCode = KeyCode.Insert; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "home": + @event.keyCode = KeyCode.Home; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "end": + @event.keyCode = KeyCode.End; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "pgup": + @event.keyCode = KeyCode.PageDown; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "page up": + @event.keyCode = KeyCode.PageUp; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "pgdown": + @event.keyCode = KeyCode.PageUp; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "page down": + @event.keyCode = KeyCode.PageDown; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "backspace": + @event.keyCode = KeyCode.Backspace; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "delete": + @event.keyCode = KeyCode.Delete; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "tab": + @event.keyCode = KeyCode.Tab; + return @event; + case "f1": + @event.keyCode = KeyCode.F1; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f2": + @event.keyCode = KeyCode.F2; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f3": + @event.keyCode = KeyCode.F3; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f4": + @event.keyCode = KeyCode.F4; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f5": + @event.keyCode = KeyCode.F5; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f6": + @event.keyCode = KeyCode.F6; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f7": + @event.keyCode = KeyCode.F7; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f8": + @event.keyCode = KeyCode.F8; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f9": + @event.keyCode = KeyCode.F9; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f10": + @event.keyCode = KeyCode.F10; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f11": + @event.keyCode = KeyCode.F11; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f12": + @event.keyCode = KeyCode.F12; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f13": + @event.keyCode = KeyCode.F13; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f14": + @event.keyCode = KeyCode.F14; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "f15": + @event.keyCode = KeyCode.F15; + @event.modifiers |= EventModifiers.FunctionKey; + return @event; + case "[esc]": + @event.keyCode = KeyCode.Escape; + return @event; + case "return": + @event.character = '\n'; + @event.keyCode = KeyCode.Return; + @event.modifiers &= ~EventModifiers.FunctionKey; + return @event; + case "space": + @event.keyCode = KeyCode.Space; + @event.character = ' '; + @event.modifiers &= ~EventModifiers.FunctionKey; + return @event; + } + if (text.Length != 1) + { + try + { + @event.keyCode = (KeyCode)((int)Enum.Parse(typeof(KeyCode), text, true)); + } + catch (ArgumentException) + { + Debug.LogError(UnityString.Format("Unable to find key name that matches '{0}'", new object[] + { + text + })); + } + } + else + { + @event.character = text.ToLower()[0]; + @event.keyCode = (KeyCode)@event.character; + if (@event.modifiers != EventModifiers.None) + { + @event.character = '\0'; + } + } + return @event; + } + public override int GetHashCode() + { + int num = 1; + if (this.isKey) + { + num = (int)((ushort)this.keyCode); + } + if (this.isMouse) + { + num = this.mousePosition.GetHashCode(); + } + return num * 37 | (int)this.modifiers; + } + public override bool Equals(object obj) + { + if (obj == null) + { + return false; + } + if (object.ReferenceEquals(this, obj)) + { + return true; + } + if (obj.GetType() != base.GetType()) + { + return false; + } + Event @event = (Event)obj; + if (this.type != @event.type || this.modifiers != @event.modifiers) + { + return false; + } + if (this.isKey) + { + return this.keyCode == @event.keyCode && this.modifiers == @event.modifiers; + } + return this.isMouse && this.mousePosition == @event.mousePosition; + } + public override string ToString() + { + if (this.isKey) + { + if (this.character == '\0') + { + return UnityString.Format("Event:{0} Character:\\0 Modifiers:{1} KeyCode:{2}", new object[] + { + this.type, + this.modifiers, + this.keyCode + }); + } + return UnityString.Format(string.Concat(new object[] + { + "Event:", + this.type, + " Character:", + (int)this.character, + " Modifiers:", + this.modifiers, + " KeyCode:", + this.keyCode + }), new object[0]); + } + else + { + if (this.isMouse) + { + return UnityString.Format("Event: {0} Position: {1} Modifiers: {2}", new object[] + { + this.type, + this.mousePosition, + this.modifiers + }); + } + if (this.type == EventType.ExecuteCommand || this.type == EventType.ValidateCommand) + { + return UnityString.Format("Event: {0} \"{1}\"", new object[] + { + this.type, + this.commandName + }); + } + return string.Empty + this.type; + } + } + } +} diff --git a/UnityEngine/UnityEngine/EventModifiers.cs b/UnityEngine/UnityEngine/EventModifiers.cs new file mode 100644 index 00000000..ed7328eb --- /dev/null +++ b/UnityEngine/UnityEngine/EventModifiers.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum EventModifiers + { + None = 0, + Shift = 1, + Control = 2, + Alt = 4, + Command = 8, + Numeric = 16, + CapsLock = 32, + FunctionKey = 64 + } +} diff --git a/UnityEngine/UnityEngine/EventType.cs b/UnityEngine/UnityEngine/EventType.cs new file mode 100644 index 00000000..68a20131 --- /dev/null +++ b/UnityEngine/UnityEngine/EventType.cs @@ -0,0 +1,37 @@ +using System; +namespace UnityEngine +{ + public enum EventType + { + MouseDown, + MouseUp, + MouseMove, + MouseDrag, + KeyDown, + KeyUp, + ScrollWheel, + Repaint, + Layout, + DragUpdated, + DragPerform, + DragExited = 15, + Ignore = 11, + Used, + ValidateCommand, + ExecuteCommand, + ContextClick = 16, + mouseDown = 0, + mouseUp, + mouseMove, + mouseDrag, + keyDown, + keyUp, + scrollWheel, + repaint, + layout, + dragUpdated, + dragPerform, + ignore, + used + } +} diff --git a/UnityEngine/UnityEngine/ExecuteInEditMode.cs b/UnityEngine/UnityEngine/ExecuteInEditMode.cs new file mode 100644 index 00000000..0e68fede --- /dev/null +++ b/UnityEngine/UnityEngine/ExecuteInEditMode.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class ExecuteInEditMode : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/ExitGUIException.cs b/UnityEngine/UnityEngine/ExitGUIException.cs new file mode 100644 index 00000000..eea588ff --- /dev/null +++ b/UnityEngine/UnityEngine/ExitGUIException.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class ExitGUIException : Exception + { + } +} diff --git a/UnityEngine/UnityEngine/FFTWindow.cs b/UnityEngine/UnityEngine/FFTWindow.cs new file mode 100644 index 00000000..f5725a07 --- /dev/null +++ b/UnityEngine/UnityEngine/FFTWindow.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum FFTWindow + { + Rectangular, + Triangle, + Hamming, + Hanning, + Blackman, + BlackmanHarris + } +} diff --git a/UnityEngine/UnityEngine/FilterMode.cs b/UnityEngine/UnityEngine/FilterMode.cs new file mode 100644 index 00000000..3da27390 --- /dev/null +++ b/UnityEngine/UnityEngine/FilterMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum FilterMode + { + Point, + Bilinear, + Trilinear + } +} diff --git a/UnityEngine/UnityEngine/FingerDoF.cs b/UnityEngine/UnityEngine/FingerDoF.cs new file mode 100644 index 00000000..1a2a0c53 --- /dev/null +++ b/UnityEngine/UnityEngine/FingerDoF.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + internal enum FingerDoF + { + ProximalDownUp, + ProximalInOut, + IntermediateCloseOpen, + DistalCloseOpen, + LastFingerDoF + } +} diff --git a/UnityEngine/UnityEngine/FixedJoint.cs b/UnityEngine/UnityEngine/FixedJoint.cs new file mode 100644 index 00000000..07a269b7 --- /dev/null +++ b/UnityEngine/UnityEngine/FixedJoint.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class FixedJoint : Joint + { + } +} diff --git a/UnityEngine/UnityEngine/Flare.cs b/UnityEngine/UnityEngine/Flare.cs new file mode 100644 index 00000000..b3561251 --- /dev/null +++ b/UnityEngine/UnityEngine/Flare.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class Flare : Object + { + } +} diff --git a/UnityEngine/UnityEngine/FocusType.cs b/UnityEngine/UnityEngine/FocusType.cs new file mode 100644 index 00000000..1b55c762 --- /dev/null +++ b/UnityEngine/UnityEngine/FocusType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum FocusType + { + Native, + Keyboard, + Passive + } +} diff --git a/UnityEngine/UnityEngine/FogMode.cs b/UnityEngine/UnityEngine/FogMode.cs new file mode 100644 index 00000000..c89501a9 --- /dev/null +++ b/UnityEngine/UnityEngine/FogMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum FogMode + { + Linear = 1, + Exponential, + ExponentialSquared + } +} diff --git a/UnityEngine/UnityEngine/Font.cs b/UnityEngine/UnityEngine/Font.cs new file mode 100644 index 00000000..6245065d --- /dev/null +++ b/UnityEngine/UnityEngine/Font.cs @@ -0,0 +1,130 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Font : Object + { + public delegate void FontTextureRebuildCallback(); + private event Font.FontTextureRebuildCallback m_FontTextureRebuildCallback + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.m_FontTextureRebuildCallback = (Font.FontTextureRebuildCallback)Delegate.Combine(this.m_FontTextureRebuildCallback, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.m_FontTextureRebuildCallback = (Font.FontTextureRebuildCallback)Delegate.Remove(this.m_FontTextureRebuildCallback, value); + } + } + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string[] fontNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CharacterInfo[] characterInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Font.FontTextureRebuildCallback textureRebuildCallback + { + get + { + return this.m_FontTextureRebuildCallback; + } + set + { + this.m_FontTextureRebuildCallback = value; + } + } + public extern bool dynamic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int fontSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Font() + { + Font.Internal_CreateFont(this, null); + } + public Font(string name) + { + Font.Internal_CreateFont(this, name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateFont([Writable] Font _font, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool HasCharacter(char c); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RequestCharactersInTexture(string characters, [DefaultValue("0")] int size, [DefaultValue("FontStyle.Normal")] FontStyle style); + [ExcludeFromDocs] + public void RequestCharactersInTexture(string characters, int size) + { + FontStyle style = FontStyle.Normal; + this.RequestCharactersInTexture(characters, size, style); + } + [ExcludeFromDocs] + public void RequestCharactersInTexture(string characters) + { + FontStyle style = FontStyle.Normal; + int size = 0; + this.RequestCharactersInTexture(characters, size, style); + } + private void InvokeTextureRebuilt_Internal() + { + if (this.m_FontTextureRebuildCallback != null) + { + this.m_FontTextureRebuildCallback(); + } + } + public static int GetMaxVertsForString(string str) + { + return str.Length * 4 + 4; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetCharacterInfo(char ch, out CharacterInfo info, [DefaultValue("0")] int size, [DefaultValue("FontStyle.Normal")] FontStyle style); + [ExcludeFromDocs] + public bool GetCharacterInfo(char ch, out CharacterInfo info, int size) + { + FontStyle style = FontStyle.Normal; + return this.GetCharacterInfo(ch, out info, size, style); + } + [ExcludeFromDocs] + public bool GetCharacterInfo(char ch, out CharacterInfo info) + { + FontStyle style = FontStyle.Normal; + int size = 0; + return this.GetCharacterInfo(ch, out info, size, style); + } + } +} diff --git a/UnityEngine/UnityEngine/FontStyle.cs b/UnityEngine/UnityEngine/FontStyle.cs new file mode 100644 index 00000000..6a1d8449 --- /dev/null +++ b/UnityEngine/UnityEngine/FontStyle.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum FontStyle + { + Normal, + Bold, + Italic, + BoldAndItalic + } +} diff --git a/UnityEngine/UnityEngine/ForceMode.cs b/UnityEngine/UnityEngine/ForceMode.cs new file mode 100644 index 00000000..b0cb94ea --- /dev/null +++ b/UnityEngine/UnityEngine/ForceMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum ForceMode + { + Force, + Acceleration = 5, + Impulse = 1, + VelocityChange + } +} diff --git a/UnityEngine/UnityEngine/ForceMode2D.cs b/UnityEngine/UnityEngine/ForceMode2D.cs new file mode 100644 index 00000000..b6178ba3 --- /dev/null +++ b/UnityEngine/UnityEngine/ForceMode2D.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum ForceMode2D + { + Force, + Impulse + } +} diff --git a/UnityEngine/UnityEngine/FullScreenMovieControlMode.cs b/UnityEngine/UnityEngine/FullScreenMovieControlMode.cs new file mode 100644 index 00000000..e388d570 --- /dev/null +++ b/UnityEngine/UnityEngine/FullScreenMovieControlMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum FullScreenMovieControlMode + { + Full, + Minimal, + CancelOnInput, + Hidden + } +} diff --git a/UnityEngine/UnityEngine/FullScreenMovieScalingMode.cs b/UnityEngine/UnityEngine/FullScreenMovieScalingMode.cs new file mode 100644 index 00000000..4429f614 --- /dev/null +++ b/UnityEngine/UnityEngine/FullScreenMovieScalingMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum FullScreenMovieScalingMode + { + None, + AspectFit, + AspectFill, + Fill + } +} diff --git a/UnityEngine/UnityEngine/GL.cs b/UnityEngine/UnityEngine/GL.cs new file mode 100644 index 00000000..8b914b4a --- /dev/null +++ b/UnityEngine/UnityEngine/GL.cs @@ -0,0 +1,178 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class GL + { + public const int TRIANGLES = 4; + public const int TRIANGLE_STRIP = 5; + public const int QUADS = 7; + public const int LINES = 1; + public static Matrix4x4 modelview + { + get + { + Matrix4x4 result; + GL.INTERNAL_get_modelview(out result); + return result; + } + set + { + GL.INTERNAL_set_modelview(ref value); + } + } + public static extern bool wireframe + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool sRGBWrite + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Vertex3(float x, float y, float z); + public static void Vertex(Vector3 v) + { + GL.INTERNAL_CALL_Vertex(ref v); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Vertex(ref Vector3 v); + public static void Color(Color c) + { + GL.INTERNAL_CALL_Color(ref c); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Color(ref Color c); + public static void TexCoord(Vector3 v) + { + GL.INTERNAL_CALL_TexCoord(ref v); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_TexCoord(ref Vector3 v); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void TexCoord2(float x, float y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void TexCoord3(float x, float y, float z); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MultiTexCoord2(int unit, float x, float y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MultiTexCoord3(int unit, float x, float y, float z); + public static void MultiTexCoord(int unit, Vector3 v) + { + GL.INTERNAL_CALL_MultiTexCoord(unit, ref v); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MultiTexCoord(int unit, ref Vector3 v); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Begin(int mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void End(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadOrtho(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadPixelMatrix(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void LoadPixelMatrixArgs(float left, float right, float bottom, float top); + public static void LoadPixelMatrix(float left, float right, float bottom, float top) + { + GL.LoadPixelMatrixArgs(left, right, bottom, top); + } + public static void Viewport(Rect pixelRect) + { + GL.INTERNAL_CALL_Viewport(ref pixelRect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Viewport(ref Rect pixelRect); + public static void LoadProjectionMatrix(Matrix4x4 mat) + { + GL.INTERNAL_CALL_LoadProjectionMatrix(ref mat); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_LoadProjectionMatrix(ref Matrix4x4 mat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadIdentity(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_modelview(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_modelview(ref Matrix4x4 value); + public static void MultMatrix(Matrix4x4 mat) + { + GL.INTERNAL_CALL_MultMatrix(ref mat); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MultMatrix(ref Matrix4x4 mat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PushMatrix(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PopMatrix(); + public static Matrix4x4 GetGPUProjectionMatrix(Matrix4x4 proj, bool renderIntoTexture) + { + return GL.INTERNAL_CALL_GetGPUProjectionMatrix(ref proj, renderIntoTexture); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Matrix4x4 INTERNAL_CALL_GetGPUProjectionMatrix(ref Matrix4x4 proj, bool renderIntoTexture); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetRevertBackfacing(bool revertBackFaces); + [ExcludeFromDocs] + public static void Clear(bool clearDepth, bool clearColor, Color backgroundColor) + { + float depth = 1f; + GL.Clear(clearDepth, clearColor, backgroundColor, depth); + } + public static void Clear(bool clearDepth, bool clearColor, Color backgroundColor, [DefaultValue("1.0f")] float depth) + { + GL.Internal_Clear(clearDepth, clearColor, backgroundColor, depth); + } + private static void Internal_Clear(bool clearDepth, bool clearColor, Color backgroundColor, float depth) + { + GL.INTERNAL_CALL_Internal_Clear(clearDepth, clearColor, ref backgroundColor, depth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Clear(bool clearDepth, bool clearColor, ref Color backgroundColor, float depth); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearWithSkybox(bool clearDepth, Camera camera); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void InvalidateState(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IssuePluginEvent(int eventID); + } +} diff --git a/UnityEngine/UnityEngine/GUI.cs b/UnityEngine/UnityEngine/GUI.cs new file mode 100644 index 00000000..b9790f93 --- /dev/null +++ b/UnityEngine/UnityEngine/GUI.cs @@ -0,0 +1,1628 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEngine +{ + public class GUI + { + internal sealed class ScrollViewState + { + public Rect position; + public Rect visibleRect; + public Rect viewRect; + public Vector2 scrollPosition; + public bool apply; + public bool hasScrollTo; + internal void ScrollTo(Rect position) + { + this.ScrollTowards(position, float.PositiveInfinity); + } + internal bool ScrollTowards(Rect position, float maxDelta) + { + Vector2 b = this.ScrollNeeded(position); + if (b.sqrMagnitude < 0.0001f) + { + return false; + } + if (maxDelta == 0f) + { + return true; + } + if (b.magnitude > maxDelta) + { + b = b.normalized * maxDelta; + } + this.scrollPosition += b; + this.apply = true; + return true; + } + internal Vector2 ScrollNeeded(Rect position) + { + Rect rect = this.visibleRect; + rect.x += this.scrollPosition.x; + rect.y += this.scrollPosition.y; + float num = position.width - this.visibleRect.width; + if (num > 0f) + { + position.width -= num; + position.x += num * 0.5f; + } + num = position.height - this.visibleRect.height; + if (num > 0f) + { + position.height -= num; + position.y += num * 0.5f; + } + Vector2 zero = Vector2.zero; + if (position.xMax > rect.xMax) + { + zero.x += position.xMax - rect.xMax; + } + else + { + if (position.xMin < rect.xMin) + { + zero.x -= rect.xMin - position.xMin; + } + } + if (position.yMax > rect.yMax) + { + zero.y += position.yMax - rect.yMax; + } + else + { + if (position.yMin < rect.yMin) + { + zero.y -= rect.yMin - position.yMin; + } + } + Rect rect2 = this.viewRect; + rect2.width = Mathf.Max(rect2.width, this.visibleRect.width); + rect2.height = Mathf.Max(rect2.height, this.visibleRect.height); + zero.x = Mathf.Clamp(zero.x, rect2.xMin - this.scrollPosition.x, rect2.xMax - this.visibleRect.width - this.scrollPosition.x); + zero.y = Mathf.Clamp(zero.y, rect2.yMin - this.scrollPosition.y, rect2.yMax - this.visibleRect.height - this.scrollPosition.y); + return zero; + } + } + public delegate void WindowFunction(int id); + private static float scrollStepSize; + private static int scrollControlID; + private static GUISkin s_Skin; + internal static Rect s_ToolTipRect; + private static int boxHash; + private static int repeatButtonHash; + private static int toggleHash; + private static int buttonGridHash; + private static int sliderHash; + private static int beginGroupHash; + private static int scrollviewHash; + private static GenericStack s_ScrollViewStates; + internal static DateTime nextScrollStepTime + { + get; + set; + } + internal static int scrollTroughSide + { + get; + set; + } + public static GUISkin skin + { + get + { + GUIUtility.CheckOnGUI(); + return GUI.s_Skin; + } + set + { + GUIUtility.CheckOnGUI(); + if (!value) + { + value = GUIUtility.GetDefaultSkin(); + } + GUI.s_Skin = value; + value.MakeCurrent(); + } + } + public static Color color + { + get + { + Color result; + GUI.INTERNAL_get_color(out result); + return result; + } + set + { + GUI.INTERNAL_set_color(ref value); + } + } + public static Color backgroundColor + { + get + { + Color result; + GUI.INTERNAL_get_backgroundColor(out result); + return result; + } + set + { + GUI.INTERNAL_set_backgroundColor(ref value); + } + } + public static Color contentColor + { + get + { + Color result; + GUI.INTERNAL_get_contentColor(out result); + return result; + } + set + { + GUI.INTERNAL_set_contentColor(ref value); + } + } + public static extern bool changed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Matrix4x4 matrix + { + get + { + return GUIClip.GetMatrix(); + } + set + { + GUIClip.SetMatrix(value); + } + } + public static string tooltip + { + get + { + string text = GUI.Internal_GetTooltip(); + if (text != null) + { + return text; + } + return string.Empty; + } + set + { + GUI.Internal_SetTooltip(value); + } + } + protected static string mouseTooltip + { + get + { + return GUI.Internal_GetMouseTooltip(); + } + } + protected static Rect tooltipRect + { + get + { + return GUI.s_ToolTipRect; + } + set + { + GUI.s_ToolTipRect = value; + } + } + public static extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + private static extern Material blendMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private static extern Material blitMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern bool usePageScrollbars + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + static GUI() + { + GUI.scrollStepSize = 10f; + GUI.boxHash = "Box".GetHashCode(); + GUI.repeatButtonHash = "repeatButton".GetHashCode(); + GUI.toggleHash = "Toggle".GetHashCode(); + GUI.buttonGridHash = "ButtonGrid".GetHashCode(); + GUI.sliderHash = "Slider".GetHashCode(); + GUI.beginGroupHash = "BeginGroup".GetHashCode(); + GUI.scrollviewHash = "scrollView".GetHashCode(); + GUI.s_ScrollViewStates = new GenericStack(); + GUI.nextScrollStepTime = DateTime.Now; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_color(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_backgroundColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_backgroundColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_contentColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_contentColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetTooltip(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetTooltip(string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetMouseTooltip(); + public static void Label(Rect position, string text) + { + GUI.Label(position, GUIContent.Temp(text), GUI.s_Skin.label); + } + public static void Label(Rect position, Texture image) + { + GUI.Label(position, GUIContent.Temp(image), GUI.s_Skin.label); + } + public static void Label(Rect position, GUIContent content) + { + GUI.Label(position, content, GUI.s_Skin.label); + } + public static void Label(Rect position, string text, GUIStyle style) + { + GUI.Label(position, GUIContent.Temp(text), style); + } + public static void Label(Rect position, Texture image, GUIStyle style) + { + GUI.Label(position, GUIContent.Temp(image), style); + } + public static void Label(Rect position, GUIContent content, GUIStyle style) + { + GUI.DoLabel(position, content, style.m_Ptr); + } + private static void DoLabel(Rect position, GUIContent content, IntPtr style) + { + GUI.INTERNAL_CALL_DoLabel(ref position, content, style); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DoLabel(ref Rect position, GUIContent content, IntPtr style); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void InitializeGUIClipTexture(); + [ExcludeFromDocs] + public static void DrawTexture(Rect position, Texture image, ScaleMode scaleMode, bool alphaBlend) + { + float imageAspect = 0f; + GUI.DrawTexture(position, image, scaleMode, alphaBlend, imageAspect); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect position, Texture image, ScaleMode scaleMode) + { + float imageAspect = 0f; + bool alphaBlend = true; + GUI.DrawTexture(position, image, scaleMode, alphaBlend, imageAspect); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect position, Texture image) + { + float imageAspect = 0f; + bool alphaBlend = true; + ScaleMode scaleMode = ScaleMode.StretchToFill; + GUI.DrawTexture(position, image, scaleMode, alphaBlend, imageAspect); + } + public static void DrawTexture(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("true")] bool alphaBlend, [DefaultValue("0")] float imageAspect) + { + if (Event.current.type == EventType.Repaint) + { + if (image == null) + { + Debug.LogWarning("null texture passed to GUI.DrawTexture"); + return; + } + if (imageAspect == 0f) + { + imageAspect = (float)image.width / (float)image.height; + } + Material mat = (!alphaBlend) ? GUI.blitMaterial : GUI.blendMaterial; + float num = position.width / position.height; + InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); + internalDrawTextureArguments.texture = image; + internalDrawTextureArguments.leftBorder = 0; + internalDrawTextureArguments.rightBorder = 0; + internalDrawTextureArguments.topBorder = 0; + internalDrawTextureArguments.bottomBorder = 0; + internalDrawTextureArguments.color = GUI.color; + internalDrawTextureArguments.mat = mat; + switch (scaleMode) + { + case ScaleMode.StretchToFill: + internalDrawTextureArguments.screenRect = position; + internalDrawTextureArguments.sourceRect = new Rect(0f, 0f, 1f, 1f); + Graphics.DrawTexture(ref internalDrawTextureArguments); + break; + case ScaleMode.ScaleAndCrop: + if (num > imageAspect) + { + float num2 = imageAspect / num; + internalDrawTextureArguments.screenRect = position; + internalDrawTextureArguments.sourceRect = new Rect(0f, (1f - num2) * 0.5f, 1f, num2); + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + else + { + float num3 = num / imageAspect; + internalDrawTextureArguments.screenRect = position; + internalDrawTextureArguments.sourceRect = new Rect(0.5f - num3 * 0.5f, 0f, num3, 1f); + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + break; + case ScaleMode.ScaleToFit: + if (num > imageAspect) + { + float num4 = imageAspect / num; + internalDrawTextureArguments.screenRect = new Rect(position.xMin + position.width * (1f - num4) * 0.5f, position.yMin, num4 * position.width, position.height); + internalDrawTextureArguments.sourceRect = new Rect(0f, 0f, 1f, 1f); + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + else + { + float num5 = num / imageAspect; + internalDrawTextureArguments.screenRect = new Rect(position.xMin, position.yMin + position.height * (1f - num5) * 0.5f, position.width, num5 * position.height); + internalDrawTextureArguments.sourceRect = new Rect(0f, 0f, 1f, 1f); + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + break; + } + } + } + internal static bool CalculateScaledTextureRects(Rect position, ScaleMode scaleMode, float imageAspect, ref Rect outScreenRect, ref Rect outSourceRect) + { + float num = position.width / position.height; + bool result = false; + switch (scaleMode) + { + case ScaleMode.StretchToFill: + outScreenRect = position; + outSourceRect = new Rect(0f, 0f, 1f, 1f); + result = true; + break; + case ScaleMode.ScaleAndCrop: + if (num > imageAspect) + { + float num2 = imageAspect / num; + outScreenRect = position; + outSourceRect = new Rect(0f, (1f - num2) * 0.5f, 1f, num2); + result = true; + } + else + { + float num3 = num / imageAspect; + outScreenRect = position; + outSourceRect = new Rect(0.5f - num3 * 0.5f, 0f, num3, 1f); + result = true; + } + break; + case ScaleMode.ScaleToFit: + if (num > imageAspect) + { + float num4 = imageAspect / num; + outScreenRect = new Rect(position.xMin + position.width * (1f - num4) * 0.5f, position.yMin, num4 * position.width, position.height); + outSourceRect = new Rect(0f, 0f, 1f, 1f); + result = true; + } + else + { + float num5 = num / imageAspect; + outScreenRect = new Rect(position.xMin, position.yMin + position.height * (1f - num5) * 0.5f, position.width, num5 * position.height); + outSourceRect = new Rect(0f, 0f, 1f, 1f); + result = true; + } + break; + } + return result; + } + [ExcludeFromDocs] + public static void DrawTextureWithTexCoords(Rect position, Texture image, Rect texCoords) + { + bool alphaBlend = true; + GUI.DrawTextureWithTexCoords(position, image, texCoords, alphaBlend); + } + public static void DrawTextureWithTexCoords(Rect position, Texture image, Rect texCoords, [DefaultValue("true")] bool alphaBlend) + { + if (Event.current.type == EventType.Repaint) + { + Material mat = (!alphaBlend) ? GUI.blitMaterial : GUI.blendMaterial; + InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); + internalDrawTextureArguments.texture = image; + internalDrawTextureArguments.leftBorder = 0; + internalDrawTextureArguments.rightBorder = 0; + internalDrawTextureArguments.topBorder = 0; + internalDrawTextureArguments.bottomBorder = 0; + internalDrawTextureArguments.color = GUI.color; + internalDrawTextureArguments.mat = mat; + internalDrawTextureArguments.screenRect = position; + internalDrawTextureArguments.sourceRect = texCoords; + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + } + public static void Box(Rect position, string text) + { + GUI.Box(position, GUIContent.Temp(text), GUI.s_Skin.box); + } + public static void Box(Rect position, Texture image) + { + GUI.Box(position, GUIContent.Temp(image), GUI.s_Skin.box); + } + public static void Box(Rect position, GUIContent content) + { + GUI.Box(position, content, GUI.s_Skin.box); + } + public static void Box(Rect position, string text, GUIStyle style) + { + GUI.Box(position, GUIContent.Temp(text), style); + } + public static void Box(Rect position, Texture image, GUIStyle style) + { + GUI.Box(position, GUIContent.Temp(image), style); + } + public static void Box(Rect position, GUIContent content, GUIStyle style) + { + GUIUtility.CheckOnGUI(); + int controlID = GUIUtility.GetControlID(GUI.boxHash, FocusType.Passive); + if (Event.current.type == EventType.Repaint) + { + style.Draw(position, content, controlID); + } + } + public static bool Button(Rect position, string text) + { + return GUI.DoButton(position, GUIContent.Temp(text), GUI.s_Skin.button.m_Ptr); + } + public static bool Button(Rect position, Texture image) + { + return GUI.DoButton(position, GUIContent.Temp(image), GUI.s_Skin.button.m_Ptr); + } + public static bool Button(Rect position, GUIContent content) + { + return GUI.DoButton(position, content, GUI.s_Skin.button.m_Ptr); + } + public static bool Button(Rect position, string text, GUIStyle style) + { + return GUI.DoButton(position, GUIContent.Temp(text), style.m_Ptr); + } + public static bool Button(Rect position, Texture image, GUIStyle style) + { + return GUI.DoButton(position, GUIContent.Temp(image), style.m_Ptr); + } + public static bool Button(Rect position, GUIContent content, GUIStyle style) + { + return GUI.DoButton(position, content, style.m_Ptr); + } + private static bool DoButton(Rect position, GUIContent content, IntPtr style) + { + return GUI.INTERNAL_CALL_DoButton(ref position, content, style); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_DoButton(ref Rect position, GUIContent content, IntPtr style); + public static bool RepeatButton(Rect position, string text) + { + return GUI.DoRepeatButton(position, GUIContent.Temp(text), GUI.s_Skin.button, FocusType.Native); + } + public static bool RepeatButton(Rect position, Texture image) + { + return GUI.DoRepeatButton(position, GUIContent.Temp(image), GUI.s_Skin.button, FocusType.Native); + } + public static bool RepeatButton(Rect position, GUIContent content) + { + return GUI.DoRepeatButton(position, content, GUI.s_Skin.button, FocusType.Native); + } + public static bool RepeatButton(Rect position, string text, GUIStyle style) + { + return GUI.DoRepeatButton(position, GUIContent.Temp(text), style, FocusType.Native); + } + public static bool RepeatButton(Rect position, Texture image, GUIStyle style) + { + return GUI.DoRepeatButton(position, GUIContent.Temp(image), style, FocusType.Native); + } + public static bool RepeatButton(Rect position, GUIContent content, GUIStyle style) + { + return GUI.DoRepeatButton(position, content, style, FocusType.Native); + } + private static bool DoRepeatButton(Rect position, GUIContent content, GUIStyle style, FocusType focusType) + { + GUIUtility.CheckOnGUI(); + int controlID = GUIUtility.GetControlID(GUI.repeatButtonHash, focusType, position); + EventType typeForControl = Event.current.GetTypeForControl(controlID); + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = controlID; + Event.current.Use(); + } + return false; + } + if (typeForControl != EventType.MouseUp) + { + if (typeForControl != EventType.Repaint) + { + return false; + } + style.Draw(position, content, controlID); + return controlID == GUIUtility.hotControl && position.Contains(Event.current.mousePosition); + } + else + { + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + return position.Contains(Event.current.mousePosition); + } + return false; + } + } + public static string TextField(Rect position, string text) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, -1, GUI.skin.textField); + return gUIContent.text; + } + public static string TextField(Rect position, string text, int maxLength) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, maxLength, GUI.skin.textField); + return gUIContent.text; + } + public static string TextField(Rect position, string text, GUIStyle style) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, -1, style); + return gUIContent.text; + } + public static string TextField(Rect position, string text, int maxLength, GUIStyle style) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, true, maxLength, style); + return gUIContent.text; + } + public static string PasswordField(Rect position, string password, char maskChar) + { + return GUI.PasswordField(position, password, maskChar, -1, GUI.skin.textField); + } + public static string PasswordField(Rect position, string password, char maskChar, int maxLength) + { + return GUI.PasswordField(position, password, maskChar, maxLength, GUI.skin.textField); + } + public static string PasswordField(Rect position, string password, char maskChar, GUIStyle style) + { + return GUI.PasswordField(position, password, maskChar, -1, style); + } + public static string PasswordField(Rect position, string password, char maskChar, int maxLength, GUIStyle style) + { + string text = GUI.PasswordFieldGetStrToShow(password, maskChar); + GUIContent gUIContent = GUIContent.Temp(text); + bool changed = GUI.changed; + GUI.changed = false; + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, maxLength, style); + text = ((!GUI.changed) ? password : gUIContent.text); + GUI.changed |= changed; + return text; + } + internal static string PasswordFieldGetStrToShow(string password, char maskChar) + { + return (Event.current.type != EventType.Repaint && Event.current.type != EventType.MouseDown) ? password : string.Empty.PadRight(password.Length, maskChar); + } + public static string TextArea(Rect position, string text) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, true, -1, GUI.skin.textArea); + return gUIContent.text; + } + public static string TextArea(Rect position, string text, int maxLength) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, true, maxLength, GUI.skin.textArea); + return gUIContent.text; + } + public static string TextArea(Rect position, string text, GUIStyle style) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, true, -1, style); + return gUIContent.text; + } + public static string TextArea(Rect position, string text, int maxLength, GUIStyle style) + { + GUIContent gUIContent = GUIContent.Temp(text); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, maxLength, style); + return gUIContent.text; + } + private static string TextArea(Rect position, GUIContent content, int maxLength, GUIStyle style) + { + GUIContent gUIContent = GUIContent.Temp(content.text, content.image); + GUI.DoTextField(position, GUIUtility.GetControlID(FocusType.Keyboard, position), gUIContent, false, maxLength, style); + return gUIContent.text; + } + internal static void DoTextField(Rect position, int id, GUIContent content, bool multiline, int maxLength, GUIStyle style) + { + if (maxLength >= 0 && content.text.Length > maxLength) + { + content.text = content.text.Substring(0, maxLength); + } + GUIUtility.CheckOnGUI(); + TextEditor textEditor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), id); + textEditor.content.text = content.text; + textEditor.SaveBackup(); + textEditor.position = position; + textEditor.style = style; + textEditor.multiline = multiline; + textEditor.controlID = id; + textEditor.ClampPos(); + if (GUIUtility.keyboardControl == id && Event.current.type != EventType.Layout) + { + textEditor.UpdateScrollOffsetIfNeeded(); + } + GUI.HandleTextFieldEventForDesktop(position, id, content, multiline, maxLength, style, textEditor); + } + private static void HandleTextFieldEventForDesktop(Rect position, int id, GUIContent content, bool multiline, int maxLength, GUIStyle style, TextEditor editor) + { + Event current = Event.current; + bool flag = false; + switch (current.type) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) + { + GUIUtility.hotControl = id; + GUIUtility.keyboardControl = id; + editor.m_HasFocus = true; + editor.MoveCursorToPosition(Event.current.mousePosition); + if (Event.current.clickCount == 2 && GUI.skin.settings.doubleClickSelectsWord) + { + editor.SelectCurrentWord(); + editor.DblClickSnap(TextEditor.DblClickSnapping.WORDS); + editor.MouseDragSelectsWholeWords(true); + } + if (Event.current.clickCount == 3 && GUI.skin.settings.tripleClickSelectsLine) + { + editor.SelectCurrentParagraph(); + editor.MouseDragSelectsWholeWords(true); + editor.DblClickSnap(TextEditor.DblClickSnapping.PARAGRAPHS); + } + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + editor.MouseDragSelectsWholeWords(false); + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) + { + if (current.shift) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + } + else + { + editor.SelectToPosition(Event.current.mousePosition); + } + current.Use(); + } + break; + case EventType.KeyDown: + if (GUIUtility.keyboardControl != id) + { + return; + } + if (editor.HandleKeyEvent(current)) + { + current.Use(); + flag = true; + content.text = editor.content.text; + } + else + { + if (current.keyCode == KeyCode.Tab || current.character == '\t') + { + return; + } + char character = current.character; + if (character == '\n' && !multiline && !current.alt) + { + return; + } + Font font = style.font; + if (!font) + { + font = GUI.skin.font; + } + if (font.HasCharacter(character) || character == '\n') + { + editor.Insert(character); + flag = true; + } + else + { + if (character == '\0') + { + if (Input.compositionString.Length > 0) + { + editor.ReplaceSelection(string.Empty); + flag = true; + } + current.Use(); + } + } + } + break; + case EventType.Repaint: + if (GUIUtility.keyboardControl != id) + { + style.Draw(position, content, id, false); + } + else + { + editor.DrawCursor(content.text); + } + break; + } + if (GUIUtility.keyboardControl == id) + { + GUIUtility.textFieldInput = true; + } + if (flag) + { + GUI.changed = true; + content.text = editor.content.text; + if (maxLength >= 0 && content.text.Length > maxLength) + { + content.text = content.text.Substring(0, maxLength); + } + current.Use(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNextControlName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetNameOfFocusedControl(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FocusControl(string name); + public static bool Toggle(Rect position, bool value, string text) + { + return GUI.Toggle(position, value, GUIContent.Temp(text), GUI.s_Skin.toggle); + } + public static bool Toggle(Rect position, bool value, Texture image) + { + return GUI.Toggle(position, value, GUIContent.Temp(image), GUI.s_Skin.toggle); + } + public static bool Toggle(Rect position, bool value, GUIContent content) + { + return GUI.Toggle(position, value, content, GUI.s_Skin.toggle); + } + public static bool Toggle(Rect position, bool value, string text, GUIStyle style) + { + return GUI.Toggle(position, value, GUIContent.Temp(text), style); + } + public static bool Toggle(Rect position, bool value, Texture image, GUIStyle style) + { + return GUI.Toggle(position, value, GUIContent.Temp(image), style); + } + public static bool Toggle(Rect position, bool value, GUIContent content, GUIStyle style) + { + return GUI.DoToggle(position, GUIUtility.GetControlID(GUI.toggleHash, FocusType.Native, position), value, content, style.m_Ptr); + } + public static bool Toggle(Rect position, int id, bool value, GUIContent content, GUIStyle style) + { + return GUI.DoToggle(position, id, value, content, style.m_Ptr); + } + internal static bool DoToggle(Rect position, int id, bool value, GUIContent content, IntPtr style) + { + return GUI.INTERNAL_CALL_DoToggle(ref position, id, value, content, style); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_DoToggle(ref Rect position, int id, bool value, GUIContent content, IntPtr style); + public static int Toolbar(Rect position, int selected, string[] texts) + { + return GUI.Toolbar(position, selected, GUIContent.Temp(texts), GUI.s_Skin.button); + } + public static int Toolbar(Rect position, int selected, Texture[] images) + { + return GUI.Toolbar(position, selected, GUIContent.Temp(images), GUI.s_Skin.button); + } + public static int Toolbar(Rect position, int selected, GUIContent[] content) + { + return GUI.Toolbar(position, selected, content, GUI.s_Skin.button); + } + public static int Toolbar(Rect position, int selected, string[] texts, GUIStyle style) + { + return GUI.Toolbar(position, selected, GUIContent.Temp(texts), style); + } + public static int Toolbar(Rect position, int selected, Texture[] images, GUIStyle style) + { + return GUI.Toolbar(position, selected, GUIContent.Temp(images), style); + } + public static int Toolbar(Rect position, int selected, GUIContent[] contents, GUIStyle style) + { + GUIStyle firstStyle; + GUIStyle midStyle; + GUIStyle lastStyle; + GUI.FindStyles(ref style, out firstStyle, out midStyle, out lastStyle, "left", "mid", "right"); + return GUI.DoButtonGrid(position, selected, contents, contents.Length, style, firstStyle, midStyle, lastStyle); + } + public static int SelectionGrid(Rect position, int selected, string[] texts, int xCount) + { + return GUI.SelectionGrid(position, selected, GUIContent.Temp(texts), xCount, null); + } + public static int SelectionGrid(Rect position, int selected, Texture[] images, int xCount) + { + return GUI.SelectionGrid(position, selected, GUIContent.Temp(images), xCount, null); + } + public static int SelectionGrid(Rect position, int selected, GUIContent[] content, int xCount) + { + return GUI.SelectionGrid(position, selected, content, xCount, null); + } + public static int SelectionGrid(Rect position, int selected, string[] texts, int xCount, GUIStyle style) + { + return GUI.SelectionGrid(position, selected, GUIContent.Temp(texts), xCount, style); + } + public static int SelectionGrid(Rect position, int selected, Texture[] images, int xCount, GUIStyle style) + { + return GUI.SelectionGrid(position, selected, GUIContent.Temp(images), xCount, style); + } + public static int SelectionGrid(Rect position, int selected, GUIContent[] contents, int xCount, GUIStyle style) + { + if (style == null) + { + style = GUI.s_Skin.button; + } + return GUI.DoButtonGrid(position, selected, contents, xCount, style, style, style, style); + } + internal static void FindStyles(ref GUIStyle style, out GUIStyle firstStyle, out GUIStyle midStyle, out GUIStyle lastStyle, string first, string mid, string last) + { + if (style == null) + { + style = GUI.skin.button; + } + string name = style.name; + midStyle = GUI.skin.FindStyle(name + mid); + if (midStyle == null) + { + midStyle = style; + } + firstStyle = GUI.skin.FindStyle(name + first); + if (firstStyle == null) + { + firstStyle = midStyle; + } + lastStyle = GUI.skin.FindStyle(name + last); + if (lastStyle == null) + { + lastStyle = midStyle; + } + } + internal static int CalcTotalHorizSpacing(int xCount, GUIStyle style, GUIStyle firstStyle, GUIStyle midStyle, GUIStyle lastStyle) + { + if (xCount < 2) + { + return 0; + } + if (xCount == 2) + { + return Mathf.Max(firstStyle.margin.right, lastStyle.margin.left); + } + int num = Mathf.Max(midStyle.margin.left, midStyle.margin.right); + return Mathf.Max(firstStyle.margin.right, midStyle.margin.left) + Mathf.Max(midStyle.margin.right, lastStyle.margin.left) + num * (xCount - 3); + } + private static int DoButtonGrid(Rect position, int selected, GUIContent[] contents, int xCount, GUIStyle style, GUIStyle firstStyle, GUIStyle midStyle, GUIStyle lastStyle) + { + GUIUtility.CheckOnGUI(); + int num = contents.Length; + if (num == 0) + { + return selected; + } + if (xCount <= 0) + { + Debug.LogWarning("You are trying to create a SelectionGrid with zero or less elements to be displayed in the horizontal direction. Set xCount to a positive value."); + return selected; + } + int controlID = GUIUtility.GetControlID(GUI.buttonGridHash, FocusType.Native, position); + int num2 = num / xCount; + if (num % xCount != 0) + { + num2++; + } + float num3 = (float)GUI.CalcTotalHorizSpacing(xCount, style, firstStyle, midStyle, lastStyle); + float num4 = (float)(Mathf.Max(style.margin.top, style.margin.bottom) * (num2 - 1)); + float elemWidth = (position.width - num3) / (float)xCount; + float elemHeight = (position.height - num4) / (float)num2; + if (style.fixedWidth != 0f) + { + elemWidth = style.fixedWidth; + } + if (style.fixedHeight != 0f) + { + elemHeight = style.fixedHeight; + } + switch (Event.current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition)) + { + Rect[] array = GUI.CalcMouseRects(position, num, xCount, elemWidth, elemHeight, style, firstStyle, midStyle, lastStyle, false); + if (GUI.GetButtonGridMouseSelection(array, Event.current.mousePosition, true) != -1) + { + GUIUtility.hotControl = controlID; + Event.current.Use(); + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + Rect[] array = GUI.CalcMouseRects(position, num, xCount, elemWidth, elemHeight, style, firstStyle, midStyle, lastStyle, false); + int buttonGridMouseSelection = GUI.GetButtonGridMouseSelection(array, Event.current.mousePosition, true); + GUI.changed = true; + return buttonGridMouseSelection; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Event.current.Use(); + } + break; + case EventType.Repaint: + { + GUIStyle gUIStyle = null; + GUIClip.Push(position, Vector2.zero, Vector2.zero, false); + position = new Rect(0f, 0f, position.width, position.height); + Rect[] array = GUI.CalcMouseRects(position, num, xCount, elemWidth, elemHeight, style, firstStyle, midStyle, lastStyle, false); + int buttonGridMouseSelection2 = GUI.GetButtonGridMouseSelection(array, Event.current.mousePosition, controlID == GUIUtility.hotControl); + bool flag = position.Contains(Event.current.mousePosition); + GUIUtility.mouseUsed |= flag; + for (int i = 0; i < num; i++) + { + GUIStyle gUIStyle2; + if (i != 0) + { + gUIStyle2 = midStyle; + } + else + { + gUIStyle2 = firstStyle; + } + if (i == num - 1) + { + gUIStyle2 = lastStyle; + } + if (num == 1) + { + gUIStyle2 = style; + } + if (i != selected) + { + gUIStyle2.Draw(array[i], contents[i], i == buttonGridMouseSelection2 && (GUI.enabled || controlID == GUIUtility.hotControl) && (controlID == GUIUtility.hotControl || GUIUtility.hotControl == 0), controlID == GUIUtility.hotControl && GUI.enabled, false, false); + } + else + { + gUIStyle = gUIStyle2; + } + } + if (selected < num && selected > -1) + { + gUIStyle.Draw(array[selected], contents[selected], selected == buttonGridMouseSelection2 && (GUI.enabled || controlID == GUIUtility.hotControl) && (controlID == GUIUtility.hotControl || GUIUtility.hotControl == 0), controlID == GUIUtility.hotControl, true, false); + } + if (buttonGridMouseSelection2 >= 0) + { + GUI.tooltip = contents[buttonGridMouseSelection2].tooltip; + } + GUIClip.Pop(); + break; + } + } + return selected; + } + private static Rect[] CalcMouseRects(Rect position, int count, int xCount, float elemWidth, float elemHeight, GUIStyle style, GUIStyle firstStyle, GUIStyle midStyle, GUIStyle lastStyle, bool addBorders) + { + int num = 0; + int num2 = 0; + float num3 = position.xMin; + float num4 = position.yMin; + GUIStyle gUIStyle = style; + Rect[] array = new Rect[count]; + if (count > 1) + { + gUIStyle = firstStyle; + } + for (int i = 0; i < count; i++) + { + if (!addBorders) + { + array[i] = new Rect(num3, num4, elemWidth, elemHeight); + } + else + { + array[i] = gUIStyle.margin.Add(new Rect(num3, num4, elemWidth, elemHeight)); + } + array[i].width = Mathf.Round(array[i].xMax) - Mathf.Round(array[i].x); + array[i].x = Mathf.Round(array[i].x); + GUIStyle gUIStyle2 = midStyle; + if (i == count - 2) + { + gUIStyle2 = lastStyle; + } + num3 += elemWidth + (float)Mathf.Max(gUIStyle.margin.right, gUIStyle2.margin.left); + num2++; + if (num2 >= xCount) + { + num++; + num2 = 0; + num4 += elemHeight + (float)Mathf.Max(style.margin.top, style.margin.bottom); + num3 = position.xMin; + } + } + return array; + } + private static int GetButtonGridMouseSelection(Rect[] buttonRects, Vector2 mousePos, bool findNearest) + { + for (int i = 0; i < buttonRects.Length; i++) + { + if (buttonRects[i].Contains(mousePos)) + { + return i; + } + } + if (!findNearest) + { + return -1; + } + float num = 1E+07f; + int result = -1; + for (int j = 0; j < buttonRects.Length; j++) + { + Rect rect = buttonRects[j]; + Vector2 b = new Vector2(Mathf.Clamp(mousePos.x, rect.xMin, rect.xMax), Mathf.Clamp(mousePos.y, rect.yMin, rect.yMax)); + float sqrMagnitude = (mousePos - b).sqrMagnitude; + if (sqrMagnitude < num) + { + result = j; + num = sqrMagnitude; + } + } + return result; + } + public static float HorizontalSlider(Rect position, float value, float leftValue, float rightValue) + { + return GUI.Slider(position, value, 0f, leftValue, rightValue, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, true, GUIUtility.GetControlID(GUI.sliderHash, FocusType.Native, position)); + } + public static float HorizontalSlider(Rect position, float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb) + { + return GUI.Slider(position, value, 0f, leftValue, rightValue, slider, thumb, true, GUIUtility.GetControlID(GUI.sliderHash, FocusType.Native, position)); + } + public static float VerticalSlider(Rect position, float value, float topValue, float bottomValue) + { + return GUI.Slider(position, value, 0f, topValue, bottomValue, GUI.skin.verticalSlider, GUI.skin.verticalSliderThumb, false, GUIUtility.GetControlID(GUI.sliderHash, FocusType.Native, position)); + } + public static float VerticalSlider(Rect position, float value, float topValue, float bottomValue, GUIStyle slider, GUIStyle thumb) + { + return GUI.Slider(position, value, 0f, topValue, bottomValue, slider, thumb, false, GUIUtility.GetControlID(GUI.sliderHash, FocusType.Native, position)); + } + public static float Slider(Rect position, float value, float size, float start, float end, GUIStyle slider, GUIStyle thumb, bool horiz, int id) + { + GUIUtility.CheckOnGUI(); + SliderHandler sliderHandler = new SliderHandler(position, value, size, start, end, slider, thumb, horiz, id); + return sliderHandler.Handle(); + } + public static float HorizontalScrollbar(Rect position, float value, float size, float leftValue, float rightValue) + { + return GUI.Scroller(position, value, size, leftValue, rightValue, GUI.skin.horizontalScrollbar, GUI.skin.horizontalScrollbarThumb, GUI.skin.horizontalScrollbarLeftButton, GUI.skin.horizontalScrollbarRightButton, true); + } + public static float HorizontalScrollbar(Rect position, float value, float size, float leftValue, float rightValue, GUIStyle style) + { + return GUI.Scroller(position, value, size, leftValue, rightValue, style, GUI.skin.GetStyle(style.name + "thumb"), GUI.skin.GetStyle(style.name + "leftbutton"), GUI.skin.GetStyle(style.name + "rightbutton"), true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InternalRepaintEditorWindow(); + internal static bool ScrollerRepeatButton(int scrollerID, Rect rect, GUIStyle style) + { + bool result = false; + if (GUI.DoRepeatButton(rect, GUIContent.none, style, FocusType.Passive)) + { + bool flag = GUI.scrollControlID != scrollerID; + GUI.scrollControlID = scrollerID; + if (flag) + { + result = true; + GUI.nextScrollStepTime = DateTime.Now.AddMilliseconds(250.0); + } + else + { + if (DateTime.Now >= GUI.nextScrollStepTime) + { + result = true; + GUI.nextScrollStepTime = DateTime.Now.AddMilliseconds(30.0); + } + } + if (Event.current.type == EventType.Repaint) + { + GUI.InternalRepaintEditorWindow(); + } + } + return result; + } + public static float VerticalScrollbar(Rect position, float value, float size, float topValue, float bottomValue) + { + return GUI.Scroller(position, value, size, topValue, bottomValue, GUI.skin.verticalScrollbar, GUI.skin.verticalScrollbarThumb, GUI.skin.verticalScrollbarUpButton, GUI.skin.verticalScrollbarDownButton, false); + } + public static float VerticalScrollbar(Rect position, float value, float size, float topValue, float bottomValue, GUIStyle style) + { + return GUI.Scroller(position, value, size, topValue, bottomValue, style, GUI.skin.GetStyle(style.name + "thumb"), GUI.skin.GetStyle(style.name + "upbutton"), GUI.skin.GetStyle(style.name + "downbutton"), false); + } + private static float Scroller(Rect position, float value, float size, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, GUIStyle leftButton, GUIStyle rightButton, bool horiz) + { + GUIUtility.CheckOnGUI(); + int controlID = GUIUtility.GetControlID(GUI.sliderHash, FocusType.Passive, position); + Rect position2; + Rect rect; + Rect rect2; + if (horiz) + { + position2 = new Rect(position.x + leftButton.fixedWidth, position.y, position.width - leftButton.fixedWidth - rightButton.fixedWidth, position.height); + rect = new Rect(position.x, position.y, leftButton.fixedWidth, position.height); + rect2 = new Rect(position.xMax - rightButton.fixedWidth, position.y, rightButton.fixedWidth, position.height); + } + else + { + position2 = new Rect(position.x, position.y + leftButton.fixedHeight, position.width, position.height - leftButton.fixedHeight - rightButton.fixedHeight); + rect = new Rect(position.x, position.y, position.width, leftButton.fixedHeight); + rect2 = new Rect(position.x, position.yMax - rightButton.fixedHeight, position.width, rightButton.fixedHeight); + } + value = GUI.Slider(position2, value, size, leftValue, rightValue, slider, thumb, horiz, controlID); + bool flag = false; + if (Event.current.type == EventType.MouseUp) + { + flag = true; + } + if (GUI.ScrollerRepeatButton(controlID, rect, leftButton)) + { + value -= GUI.scrollStepSize * ((leftValue >= rightValue) ? -1f : 1f); + } + if (GUI.ScrollerRepeatButton(controlID, rect2, rightButton)) + { + value += GUI.scrollStepSize * ((leftValue >= rightValue) ? -1f : 1f); + } + if (flag && Event.current.type == EventType.Used) + { + GUI.scrollControlID = 0; + } + if (leftValue < rightValue) + { + value = Mathf.Clamp(value, leftValue, rightValue - size); + } + else + { + value = Mathf.Clamp(value, rightValue, leftValue - size); + } + return value; + } + public static void BeginGroup(Rect position) + { + GUI.BeginGroup(position, GUIContent.none, GUIStyle.none); + } + public static void BeginGroup(Rect position, string text) + { + GUI.BeginGroup(position, GUIContent.Temp(text), GUIStyle.none); + } + public static void BeginGroup(Rect position, Texture image) + { + GUI.BeginGroup(position, GUIContent.Temp(image), GUIStyle.none); + } + public static void BeginGroup(Rect position, GUIContent content) + { + GUI.BeginGroup(position, content, GUIStyle.none); + } + public static void BeginGroup(Rect position, GUIStyle style) + { + GUI.BeginGroup(position, GUIContent.none, style); + } + public static void BeginGroup(Rect position, string text, GUIStyle style) + { + GUI.BeginGroup(position, GUIContent.Temp(text), style); + } + public static void BeginGroup(Rect position, Texture image, GUIStyle style) + { + GUI.BeginGroup(position, GUIContent.Temp(image), style); + } + public static void BeginGroup(Rect position, GUIContent content, GUIStyle style) + { + GUIUtility.CheckOnGUI(); + int controlID = GUIUtility.GetControlID(GUI.beginGroupHash, FocusType.Passive); + if (content != GUIContent.none || style != GUIStyle.none) + { + EventType type = Event.current.type; + if (type != EventType.Repaint) + { + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.mouseUsed = true; + } + } + else + { + style.Draw(position, content, controlID); + } + } + GUIClip.Push(position, Vector2.zero, Vector2.zero, false); + } + public static void EndGroup() + { + GUIClip.Pop(); + } + public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect) + { + return GUI.BeginScrollView(position, scrollPosition, viewRect, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView); + } + public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical) + { + return GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView); + } + public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar) + { + return GUI.BeginScrollView(position, scrollPosition, viewRect, false, false, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView); + } + public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar) + { + return GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, null); + } + protected static Vector2 DoBeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background) + { + return GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); + } + internal static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background) + { + GUIUtility.CheckOnGUI(); + if (Event.current.type == EventType.DragUpdated && position.Contains(Event.current.mousePosition)) + { + if (Mathf.Abs(Event.current.mousePosition.y - position.y) < 8f) + { + scrollPosition.y -= 16f; + GUI.InternalRepaintEditorWindow(); + } + else + { + if (Mathf.Abs(Event.current.mousePosition.y - position.yMax) < 8f) + { + scrollPosition.y += 16f; + GUI.InternalRepaintEditorWindow(); + } + } + } + int controlID = GUIUtility.GetControlID(GUI.scrollviewHash, FocusType.Passive); + GUI.ScrollViewState scrollViewState = (GUI.ScrollViewState)GUIUtility.GetStateObject(typeof(GUI.ScrollViewState), controlID); + if (scrollViewState.apply) + { + scrollPosition = scrollViewState.scrollPosition; + scrollViewState.apply = false; + } + scrollViewState.position = position; + scrollViewState.scrollPosition = scrollPosition; + scrollViewState.visibleRect = (scrollViewState.viewRect = viewRect); + scrollViewState.visibleRect.width = position.width; + scrollViewState.visibleRect.height = position.height; + GUI.s_ScrollViewStates.Push(scrollViewState); + Rect screenRect = new Rect(position); + EventType type = Event.current.type; + if (type != EventType.Layout) + { + if (type != EventType.Used) + { + bool flag = alwaysShowVertical; + bool flag2 = alwaysShowHorizontal; + if (flag2 || viewRect.width > screenRect.width) + { + scrollViewState.visibleRect.height = position.height - horizontalScrollbar.fixedHeight + (float)horizontalScrollbar.margin.top; + screenRect.height -= horizontalScrollbar.fixedHeight + (float)horizontalScrollbar.margin.top; + flag2 = true; + } + if (flag || viewRect.height > screenRect.height) + { + scrollViewState.visibleRect.width = position.width - verticalScrollbar.fixedWidth + (float)verticalScrollbar.margin.left; + screenRect.width -= verticalScrollbar.fixedWidth + (float)verticalScrollbar.margin.left; + flag = true; + if (!flag2 && viewRect.width > screenRect.width) + { + scrollViewState.visibleRect.height = position.height - horizontalScrollbar.fixedHeight + (float)horizontalScrollbar.margin.top; + screenRect.height -= horizontalScrollbar.fixedHeight + (float)horizontalScrollbar.margin.top; + flag2 = true; + } + } + if (Event.current.type == EventType.Repaint && background != GUIStyle.none) + { + background.Draw(position, position.Contains(Event.current.mousePosition), false, flag2 && flag, false); + } + if (flag2 && horizontalScrollbar != GUIStyle.none) + { + scrollPosition.x = GUI.HorizontalScrollbar(new Rect(position.x, position.yMax - horizontalScrollbar.fixedHeight, screenRect.width, horizontalScrollbar.fixedHeight), scrollPosition.x, screenRect.width, 0f, viewRect.width, horizontalScrollbar); + } + else + { + GUIUtility.GetControlID(GUI.sliderHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + if (horizontalScrollbar != GUIStyle.none) + { + scrollPosition.x = 0f; + } + else + { + scrollPosition.x = Mathf.Clamp(scrollPosition.x, 0f, Mathf.Max(viewRect.width - position.width, 0f)); + } + } + if (flag && verticalScrollbar != GUIStyle.none) + { + scrollPosition.y = GUI.VerticalScrollbar(new Rect(screenRect.xMax + (float)verticalScrollbar.margin.left, screenRect.y, verticalScrollbar.fixedWidth, screenRect.height), scrollPosition.y, screenRect.height, 0f, viewRect.height, verticalScrollbar); + } + else + { + GUIUtility.GetControlID(GUI.sliderHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + if (verticalScrollbar != GUIStyle.none) + { + scrollPosition.y = 0f; + } + else + { + scrollPosition.y = Mathf.Clamp(scrollPosition.y, 0f, Mathf.Max(viewRect.height - position.height, 0f)); + } + } + } + } + else + { + GUIUtility.GetControlID(GUI.sliderHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.sliderHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + GUIUtility.GetControlID(GUI.repeatButtonHash, FocusType.Passive); + } + GUIClip.Push(screenRect, new Vector2(Mathf.Round(-scrollPosition.x - viewRect.x), Mathf.Round(-scrollPosition.y - viewRect.y)), Vector2.zero, false); + return scrollPosition; + } + public static void EndScrollView() + { + GUI.EndScrollView(true); + } + public static void EndScrollView(bool handleScrollWheel) + { + GUI.ScrollViewState scrollViewState = (GUI.ScrollViewState)GUI.s_ScrollViewStates.Peek(); + GUIUtility.CheckOnGUI(); + GUIClip.Pop(); + GUI.s_ScrollViewStates.Pop(); + if (handleScrollWheel && Event.current.type == EventType.ScrollWheel && scrollViewState.position.Contains(Event.current.mousePosition)) + { + scrollViewState.scrollPosition.x = Mathf.Clamp(scrollViewState.scrollPosition.x + Event.current.delta.x * 20f, 0f, scrollViewState.viewRect.width - scrollViewState.visibleRect.width); + scrollViewState.scrollPosition.y = Mathf.Clamp(scrollViewState.scrollPosition.y + Event.current.delta.y * 20f, 0f, scrollViewState.viewRect.height - scrollViewState.visibleRect.height); + scrollViewState.apply = true; + Event.current.Use(); + } + } + internal static GUI.ScrollViewState GetTopScrollView() + { + if (GUI.s_ScrollViewStates.Count != 0) + { + return (GUI.ScrollViewState)GUI.s_ScrollViewStates.Peek(); + } + return null; + } + public static void ScrollTo(Rect position) + { + GUI.ScrollViewState topScrollView = GUI.GetTopScrollView(); + if (topScrollView != null) + { + topScrollView.ScrollTo(position); + } + } + public static bool ScrollTowards(Rect position, float maxDelta) + { + GUI.ScrollViewState topScrollView = GUI.GetTopScrollView(); + return topScrollView != null && topScrollView.ScrollTowards(position, maxDelta); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, string text) + { + return GUI.DoWindow(id, clientRect, func, GUIContent.Temp(text), GUI.skin.window, GUI.skin, true); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, Texture image) + { + return GUI.DoWindow(id, clientRect, func, GUIContent.Temp(image), GUI.skin.window, GUI.skin, true); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, GUIContent content) + { + return GUI.DoWindow(id, clientRect, func, content, GUI.skin.window, GUI.skin, true); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, string text, GUIStyle style) + { + return GUI.DoWindow(id, clientRect, func, GUIContent.Temp(text), style, GUI.skin, true); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, Texture image, GUIStyle style) + { + return GUI.DoWindow(id, clientRect, func, GUIContent.Temp(image), style, GUI.skin, true); + } + public static Rect Window(int id, Rect clientRect, GUI.WindowFunction func, GUIContent title, GUIStyle style) + { + return GUI.DoWindow(id, clientRect, func, title, style, GUI.skin, true); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, string text) + { + return GUI.DoModalWindow(id, clientRect, func, GUIContent.Temp(text), GUI.skin.window, GUI.skin); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, Texture image) + { + return GUI.DoModalWindow(id, clientRect, func, GUIContent.Temp(image), GUI.skin.window, GUI.skin); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, GUIContent content) + { + return GUI.DoModalWindow(id, clientRect, func, content, GUI.skin.window, GUI.skin); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, string text, GUIStyle style) + { + return GUI.DoModalWindow(id, clientRect, func, GUIContent.Temp(text), style, GUI.skin); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, Texture image, GUIStyle style) + { + return GUI.DoModalWindow(id, clientRect, func, GUIContent.Temp(image), style, GUI.skin); + } + public static Rect ModalWindow(int id, Rect clientRect, GUI.WindowFunction func, GUIContent content, GUIStyle style) + { + return GUI.DoModalWindow(id, clientRect, func, content, style, GUI.skin); + } + private static Rect DoModalWindow(int id, Rect clientRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, GUISkin skin) + { + return GUI.INTERNAL_CALL_DoModalWindow(id, ref clientRect, func, content, style, skin); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_DoModalWindow(int id, ref Rect clientRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, GUISkin skin); + internal static void CallWindowDelegate(GUI.WindowFunction func, int id, GUISkin _skin, int forceRect, float width, float height, GUIStyle style) + { + GUILayoutUtility.SelectIDList(id, true); + GUISkin skin = GUI.skin; + if (Event.current.type == EventType.Layout) + { + if (forceRect != 0) + { + GUILayoutOption[] options = new GUILayoutOption[] + { + GUILayout.Width(width), + GUILayout.Height(height) + }; + GUILayoutUtility.BeginWindow(id, style, options); + } + else + { + GUILayoutUtility.BeginWindow(id, style, null); + } + } + GUI.skin = _skin; + func(id); + if (Event.current.type == EventType.Layout) + { + GUILayoutUtility.Layout(); + } + GUI.skin = skin; + } + private static Rect DoWindow(int id, Rect clientRect, GUI.WindowFunction func, GUIContent title, GUIStyle style, GUISkin skin, bool forceRectOnLayout) + { + return GUI.INTERNAL_CALL_DoWindow(id, ref clientRect, func, title, style, skin, forceRectOnLayout); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_DoWindow(int id, ref Rect clientRect, GUI.WindowFunction func, GUIContent title, GUIStyle style, GUISkin skin, bool forceRectOnLayout); + public static void DragWindow(Rect position) + { + GUI.INTERNAL_CALL_DragWindow(ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DragWindow(ref Rect position); + public static void DragWindow() + { + GUI.DragWindow(new Rect(0f, 0f, 10000f, 10000f)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BringWindowToFront(int windowID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BringWindowToBack(int windowID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FocusWindow(int windowID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnfocusWindow(); + internal static void BeginWindows(int skinMode, int editorWindowInstanceID) + { + GUILayoutGroup topLevel = GUILayoutUtility.current.topLevel; + GenericStack layoutGroups = GUILayoutUtility.current.layoutGroups; + GUILayoutGroup windows = GUILayoutUtility.current.windows; + Matrix4x4 matrix = GUI.matrix; + GUI.Internal_BeginWindows(); + GUI.matrix = matrix; + GUILayoutUtility.current.topLevel = topLevel; + GUILayoutUtility.current.layoutGroups = layoutGroups; + GUILayoutUtility.current.windows = windows; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_BeginWindows(); + internal static void EndWindows() + { + GUILayoutGroup topLevel = GUILayoutUtility.current.topLevel; + GenericStack layoutGroups = GUILayoutUtility.current.layoutGroups; + GUILayoutGroup windows = GUILayoutUtility.current.windows; + GUI.Internal_EndWindows(); + GUILayoutUtility.current.topLevel = topLevel; + GUILayoutUtility.current.layoutGroups = layoutGroups; + GUILayoutUtility.current.windows = windows; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_EndWindows(); + } +} diff --git a/UnityEngine/UnityEngine/GUIAspectSizer.cs b/UnityEngine/UnityEngine/GUIAspectSizer.cs new file mode 100644 index 00000000..3a68769a --- /dev/null +++ b/UnityEngine/UnityEngine/GUIAspectSizer.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEngine +{ + internal sealed class GUIAspectSizer : GUILayoutEntry + { + private float aspect; + public GUIAspectSizer(float aspect, GUILayoutOption[] options) : base(0f, 0f, 0f, 0f, GUIStyle.none) + { + this.aspect = aspect; + this.ApplyOptions(options); + } + public override void CalcHeight() + { + this.minHeight = (this.maxHeight = this.rect.width / this.aspect); + } + } +} diff --git a/UnityEngine/UnityEngine/GUIClip.cs b/UnityEngine/UnityEngine/GUIClip.cs new file mode 100644 index 00000000..c558c9f9 --- /dev/null +++ b/UnityEngine/UnityEngine/GUIClip.cs @@ -0,0 +1,109 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class GUIClip + { + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Rect topmostRect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Rect visibleRect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static void Push(Rect screenRect, Vector2 scrollOffset, Vector2 renderOffset, bool resetOffset) + { + GUIClip.INTERNAL_CALL_Push(ref screenRect, ref scrollOffset, ref renderOffset, resetOffset); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Push(ref Rect screenRect, ref Vector2 scrollOffset, ref Vector2 renderOffset, bool resetOffset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Pop(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect GetTopRect(); + public static Vector2 Unclip(Vector2 pos) + { + GUIClip.Unclip_Vector2(ref pos); + return pos; + } + private static void Unclip_Vector2(ref Vector2 pos) + { + GUIClip.INTERNAL_CALL_Unclip_Vector2(ref pos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Unclip_Vector2(ref Vector2 pos); + public static Rect Unclip(Rect rect) + { + GUIClip.Unclip_Rect(ref rect); + return rect; + } + private static void Unclip_Rect(ref Rect rect) + { + GUIClip.INTERNAL_CALL_Unclip_Rect(ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Unclip_Rect(ref Rect rect); + public static Vector2 Clip(Vector2 absolutePos) + { + GUIClip.Clip_Vector2(ref absolutePos); + return absolutePos; + } + private static void Clip_Vector2(ref Vector2 absolutePos) + { + GUIClip.INTERNAL_CALL_Clip_Vector2(ref absolutePos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Clip_Vector2(ref Vector2 absolutePos); + public static Rect Clip(Rect absoluteRect) + { + GUIClip.Internal_Clip_Rect(ref absoluteRect); + return absoluteRect; + } + private static void Internal_Clip_Rect(ref Rect absoluteRect) + { + GUIClip.INTERNAL_CALL_Internal_Clip_Rect(ref absoluteRect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Clip_Rect(ref Rect absoluteRect); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Reapply(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Matrix4x4 GetMatrix(); + internal static void SetMatrix(Matrix4x4 m) + { + GUIClip.INTERNAL_CALL_SetMatrix(ref m); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetMatrix(ref Matrix4x4 m); + public static Vector2 GetAbsoluteMousePosition() + { + Vector2 result; + GUIClip.Internal_GetAbsoluteMousePosition(out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetAbsoluteMousePosition(out Vector2 output); + } +} diff --git a/UnityEngine/UnityEngine/GUIContent.cs b/UnityEngine/UnityEngine/GUIContent.cs new file mode 100644 index 00000000..9ffb7a7a --- /dev/null +++ b/UnityEngine/UnityEngine/GUIContent.cs @@ -0,0 +1,144 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class GUIContent + { + [SerializeField] + private string m_Text = string.Empty; + [SerializeField] + private Texture m_Image; + [SerializeField] + private string m_Tooltip = string.Empty; + public static GUIContent none = new GUIContent(string.Empty); + private static GUIContent s_Text = new GUIContent(); + private static GUIContent s_Image = new GUIContent(); + private static GUIContent s_TextImage = new GUIContent(); + public string text + { + get + { + return this.m_Text; + } + set + { + this.m_Text = value; + } + } + public Texture image + { + get + { + return this.m_Image; + } + set + { + this.m_Image = value; + } + } + public string tooltip + { + get + { + return this.m_Tooltip; + } + set + { + this.m_Tooltip = value; + } + } + internal int hash + { + get + { + int result = 0; + if (this.m_Text != null && this.m_Text != string.Empty) + { + result = this.m_Text.GetHashCode() * 37; + } + return result; + } + } + public GUIContent() + { + } + public GUIContent(string text) + { + this.m_Text = text; + } + public GUIContent(Texture image) + { + this.m_Image = image; + } + public GUIContent(string text, Texture image) + { + this.m_Text = text; + this.m_Image = image; + } + public GUIContent(string text, string tooltip) + { + this.m_Text = text; + this.m_Tooltip = tooltip; + } + public GUIContent(Texture image, string tooltip) + { + this.m_Image = image; + this.m_Tooltip = tooltip; + } + public GUIContent(string text, Texture image, string tooltip) + { + this.m_Text = text; + this.m_Image = image; + this.m_Tooltip = tooltip; + } + public GUIContent(GUIContent src) + { + this.m_Text = src.m_Text; + this.m_Image = src.m_Image; + this.m_Tooltip = src.m_Tooltip; + } + internal static GUIContent Temp(string t) + { + GUIContent.s_Text.m_Text = t; + return GUIContent.s_Text; + } + internal static GUIContent Temp(Texture i) + { + GUIContent.s_Image.m_Image = i; + return GUIContent.s_Image; + } + internal static GUIContent Temp(string t, Texture i) + { + GUIContent.s_TextImage.m_Text = t; + GUIContent.s_TextImage.m_Image = i; + return GUIContent.s_TextImage; + } + internal static void ClearStaticCache() + { + GUIContent.s_Text.m_Text = null; + GUIContent.s_Image.m_Image = null; + GUIContent.s_TextImage.m_Text = null; + GUIContent.s_TextImage.m_Image = null; + } + internal static GUIContent[] Temp(string[] texts) + { + GUIContent[] array = new GUIContent[texts.Length]; + for (int i = 0; i < texts.Length; i++) + { + array[i] = new GUIContent(texts[i]); + } + return array; + } + internal static GUIContent[] Temp(Texture[] images) + { + GUIContent[] array = new GUIContent[images.Length]; + for (int i = 0; i < images.Length; i++) + { + array[i] = new GUIContent(images[i]); + } + return array; + } + } +} diff --git a/UnityEngine/UnityEngine/GUIElement.cs b/UnityEngine/UnityEngine/GUIElement.cs new file mode 100644 index 00000000..0836bdd2 --- /dev/null +++ b/UnityEngine/UnityEngine/GUIElement.cs @@ -0,0 +1,31 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class GUIElement : Behaviour + { + public bool HitTest(Vector3 screenPosition, [DefaultValue("null")] Camera camera) + { + return GUIElement.INTERNAL_CALL_HitTest(this, ref screenPosition, camera); + } + [ExcludeFromDocs] + public bool HitTest(Vector3 screenPosition) + { + Camera camera = null; + return GUIElement.INTERNAL_CALL_HitTest(this, ref screenPosition, camera); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_HitTest(GUIElement self, ref Vector3 screenPosition, Camera camera); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Rect GetScreenRect([DefaultValue("null")] Camera camera); + [ExcludeFromDocs] + public Rect GetScreenRect() + { + Camera camera = null; + return this.GetScreenRect(camera); + } + } +} diff --git a/UnityEngine/UnityEngine/GUIGridSizer.cs b/UnityEngine/UnityEngine/GUIGridSizer.cs new file mode 100644 index 00000000..b5f95b8c --- /dev/null +++ b/UnityEngine/UnityEngine/GUIGridSizer.cs @@ -0,0 +1,143 @@ +using System; +namespace UnityEngine +{ + internal sealed class GUIGridSizer : GUILayoutEntry + { + private int count; + private int xCount; + private float minButtonWidth = -1f; + private float maxButtonWidth = -1f; + private float minButtonHeight = -1f; + private float maxButtonHeight = -1f; + private int rows + { + get + { + int num = this.count / this.xCount; + if (this.count % this.xCount != 0) + { + num++; + } + return num; + } + } + private GUIGridSizer(GUIContent[] contents, int _xCount, GUIStyle buttonStyle, GUILayoutOption[] options) : base(0f, 0f, 0f, 0f, GUIStyle.none) + { + this.count = contents.Length; + this.xCount = _xCount; + this.ApplyStyleSettings(buttonStyle); + this.ApplyOptions(options); + if (_xCount == 0 || contents.Length == 0) + { + return; + } + float num = (float)(Mathf.Max(buttonStyle.margin.left, buttonStyle.margin.right) * (this.xCount - 1)); + float num2 = (float)(Mathf.Max(buttonStyle.margin.top, buttonStyle.margin.bottom) * (this.rows - 1)); + if (buttonStyle.fixedWidth != 0f) + { + this.minButtonWidth = (this.maxButtonWidth = buttonStyle.fixedWidth); + } + if (buttonStyle.fixedHeight != 0f) + { + this.minButtonHeight = (this.maxButtonHeight = buttonStyle.fixedHeight); + } + if (this.minButtonWidth == -1f) + { + if (this.minWidth != 0f) + { + this.minButtonWidth = (this.minWidth - num) / (float)this.xCount; + } + if (this.maxWidth != 0f) + { + this.maxButtonWidth = (this.maxWidth - num) / (float)this.xCount; + } + } + if (this.minButtonHeight == -1f) + { + if (this.minHeight != 0f) + { + this.minButtonHeight = (this.minHeight - num2) / (float)this.rows; + } + if (this.maxHeight != 0f) + { + this.maxButtonHeight = (this.maxHeight - num2) / (float)this.rows; + } + } + if (this.minButtonHeight == -1f || this.maxButtonHeight == -1f || this.minButtonWidth == -1f || this.maxButtonWidth == -1f) + { + float a = 0f; + float a2 = 0f; + for (int i = 0; i < contents.Length; i++) + { + GUIContent content = contents[i]; + Vector2 vector = buttonStyle.CalcSize(content); + a2 = Mathf.Max(a2, vector.x); + a = Mathf.Max(a, vector.y); + } + if (this.minButtonWidth == -1f) + { + if (this.maxButtonWidth != -1f) + { + this.minButtonWidth = Mathf.Min(a2, this.maxButtonWidth); + } + else + { + this.minButtonWidth = a2; + } + } + if (this.maxButtonWidth == -1f) + { + if (this.minButtonWidth != -1f) + { + this.maxButtonWidth = Mathf.Max(a2, this.minButtonWidth); + } + else + { + this.maxButtonWidth = a2; + } + } + if (this.minButtonHeight == -1f) + { + if (this.maxButtonHeight != -1f) + { + this.minButtonHeight = Mathf.Min(a, this.maxButtonHeight); + } + else + { + this.minButtonHeight = a; + } + } + if (this.maxButtonHeight == -1f) + { + if (this.minButtonHeight != -1f) + { + this.maxHeight = Mathf.Max(this.maxHeight, this.minButtonHeight); + } + this.maxButtonHeight = this.maxHeight; + } + } + this.minWidth = this.minButtonWidth * (float)this.xCount + num; + this.maxWidth = this.maxButtonWidth * (float)this.xCount + num; + this.minHeight = this.minButtonHeight * (float)this.rows + num2; + this.maxHeight = this.maxButtonHeight * (float)this.rows + num2; + } + public static Rect GetRect(GUIContent[] contents, int xCount, GUIStyle style, GUILayoutOption[] options) + { + Rect rect = new Rect(0f, 0f, 0f, 0f); + EventType type = Event.current.type; + if (type != EventType.Layout) + { + if (type == EventType.Used) + { + return GUILayoutEntry.kDummyRect; + } + rect = GUILayoutUtility.current.topLevel.GetNext().rect; + } + else + { + GUILayoutUtility.current.topLevel.Add(new GUIGridSizer(contents, xCount, style, options)); + } + return rect; + } + } +} diff --git a/UnityEngine/UnityEngine/GUILayer.cs b/UnityEngine/UnityEngine/GUILayer.cs new file mode 100644 index 00000000..94a8f1fe --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayer.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class GUILayer : Behaviour + { + public GUIElement HitTest(Vector3 screenPosition) + { + return GUILayer.INTERNAL_CALL_HitTest(this, ref screenPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GUIElement INTERNAL_CALL_HitTest(GUILayer self, ref Vector3 screenPosition); + } +} diff --git a/UnityEngine/UnityEngine/GUILayout.cs b/UnityEngine/UnityEngine/GUILayout.cs new file mode 100644 index 00000000..46fa392f --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayout.cs @@ -0,0 +1,655 @@ +using System; +namespace UnityEngine +{ + public sealed class GUILayout + { + private sealed class LayoutedWindow + { + private GUI.WindowFunction func; + private Rect screenRect; + private GUILayoutOption[] options; + private GUIStyle style; + internal LayoutedWindow(GUI.WindowFunction f, Rect _screenRect, GUIContent _content, GUILayoutOption[] _options, GUIStyle _style) + { + this.func = f; + this.screenRect = _screenRect; + this.options = _options; + this.style = _style; + } + public void DoWindow(int windowID) + { + GUILayoutGroup topLevel = GUILayoutUtility.current.topLevel; + EventType type = Event.current.type; + if (type != EventType.Layout) + { + topLevel.ResetCursor(); + } + else + { + topLevel.resetCoords = true; + topLevel.rect = this.screenRect; + if (this.options != null) + { + topLevel.ApplyOptions(this.options); + } + topLevel.isWindow = true; + topLevel.windowID = windowID; + topLevel.style = this.style; + } + this.func(windowID); + } + } + public static void Label(Texture image, params GUILayoutOption[] options) + { + GUILayout.DoLabel(GUIContent.Temp(image), GUI.skin.label, options); + } + public static void Label(string text, params GUILayoutOption[] options) + { + GUILayout.DoLabel(GUIContent.Temp(text), GUI.skin.label, options); + } + public static void Label(GUIContent content, params GUILayoutOption[] options) + { + GUILayout.DoLabel(content, GUI.skin.label, options); + } + public static void Label(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoLabel(GUIContent.Temp(image), style, options); + } + public static void Label(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoLabel(GUIContent.Temp(text), style, options); + } + public static void Label(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoLabel(content, style, options); + } + private static void DoLabel(GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + GUI.Label(GUILayoutUtility.GetRect(content, style, options), content, style); + } + public static void Box(Texture image, params GUILayoutOption[] options) + { + GUILayout.DoBox(GUIContent.Temp(image), GUI.skin.box, options); + } + public static void Box(string text, params GUILayoutOption[] options) + { + GUILayout.DoBox(GUIContent.Temp(text), GUI.skin.box, options); + } + public static void Box(GUIContent content, params GUILayoutOption[] options) + { + GUILayout.DoBox(content, GUI.skin.box, options); + } + public static void Box(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoBox(GUIContent.Temp(image), style, options); + } + public static void Box(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoBox(GUIContent.Temp(text), style, options); + } + public static void Box(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.DoBox(content, style, options); + } + private static void DoBox(GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + GUI.Box(GUILayoutUtility.GetRect(content, style, options), content, style); + } + public static bool Button(Texture image, params GUILayoutOption[] options) + { + return GUILayout.DoButton(GUIContent.Temp(image), GUI.skin.button, options); + } + public static bool Button(string text, params GUILayoutOption[] options) + { + return GUILayout.DoButton(GUIContent.Temp(text), GUI.skin.button, options); + } + public static bool Button(GUIContent content, params GUILayoutOption[] options) + { + return GUILayout.DoButton(content, GUI.skin.button, options); + } + public static bool Button(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoButton(GUIContent.Temp(image), style, options); + } + public static bool Button(string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoButton(GUIContent.Temp(text), style, options); + } + public static bool Button(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoButton(content, style, options); + } + private static bool DoButton(GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + return GUI.Button(GUILayoutUtility.GetRect(content, style, options), content, style); + } + public static bool RepeatButton(Texture image, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(GUIContent.Temp(image), GUI.skin.button, options); + } + public static bool RepeatButton(string text, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(GUIContent.Temp(text), GUI.skin.button, options); + } + public static bool RepeatButton(GUIContent content, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(content, GUI.skin.button, options); + } + public static bool RepeatButton(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(GUIContent.Temp(image), style, options); + } + public static bool RepeatButton(string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(GUIContent.Temp(text), style, options); + } + public static bool RepeatButton(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoRepeatButton(content, style, options); + } + private static bool DoRepeatButton(GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + return GUI.RepeatButton(GUILayoutUtility.GetRect(content, style, options), content, style); + } + public static string TextField(string text, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, -1, false, GUI.skin.textField, options); + } + public static string TextField(string text, int maxLength, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, maxLength, false, GUI.skin.textField, options); + } + public static string TextField(string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, -1, false, style, options); + } + public static string TextField(string text, int maxLength, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, maxLength, true, style, options); + } + public static string PasswordField(string password, char maskChar, params GUILayoutOption[] options) + { + return GUILayout.PasswordField(password, maskChar, -1, GUI.skin.textField, options); + } + public static string PasswordField(string password, char maskChar, int maxLength, params GUILayoutOption[] options) + { + return GUILayout.PasswordField(password, maskChar, maxLength, GUI.skin.textField, options); + } + public static string PasswordField(string password, char maskChar, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.PasswordField(password, maskChar, -1, style, options); + } + public static string PasswordField(string password, char maskChar, int maxLength, GUIStyle style, params GUILayoutOption[] options) + { + GUIContent content = GUIContent.Temp(GUI.PasswordFieldGetStrToShow(password, maskChar)); + return GUI.PasswordField(GUILayoutUtility.GetRect(content, GUI.skin.textField, options), password, maskChar, maxLength, style); + } + public static string TextArea(string text, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, -1, true, GUI.skin.textArea, options); + } + public static string TextArea(string text, int maxLength, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, maxLength, true, GUI.skin.textArea, options); + } + public static string TextArea(string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, -1, true, style, options); + } + public static string TextArea(string text, int maxLength, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoTextField(text, maxLength, true, style, options); + } + private static string DoTextField(string text, int maxLength, bool multiline, GUIStyle style, GUILayoutOption[] options) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + GUIContent gUIContent = GUIContent.Temp(text); + if (GUIUtility.keyboardControl != controlID) + { + gUIContent = GUIContent.Temp(text); + } + else + { + gUIContent = GUIContent.Temp(text + Input.compositionString); + } + Rect rect = GUILayoutUtility.GetRect(gUIContent, style, options); + if (GUIUtility.keyboardControl == controlID) + { + gUIContent = GUIContent.Temp(text); + } + GUI.DoTextField(rect, controlID, gUIContent, multiline, maxLength, style); + return gUIContent.text; + } + public static bool Toggle(bool value, Texture image, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, GUIContent.Temp(image), GUI.skin.toggle, options); + } + public static bool Toggle(bool value, string text, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, GUIContent.Temp(text), GUI.skin.toggle, options); + } + public static bool Toggle(bool value, GUIContent content, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, content, GUI.skin.toggle, options); + } + public static bool Toggle(bool value, Texture image, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, GUIContent.Temp(image), style, options); + } + public static bool Toggle(bool value, string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, GUIContent.Temp(text), style, options); + } + public static bool Toggle(bool value, GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoToggle(value, content, style, options); + } + private static bool DoToggle(bool value, GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + return GUI.Toggle(GUILayoutUtility.GetRect(content, style, options), value, content, style); + } + public static int Toolbar(int selected, string[] texts, params GUILayoutOption[] options) + { + return GUILayout.Toolbar(selected, GUIContent.Temp(texts), GUI.skin.button, options); + } + public static int Toolbar(int selected, Texture[] images, params GUILayoutOption[] options) + { + return GUILayout.Toolbar(selected, GUIContent.Temp(images), GUI.skin.button, options); + } + public static int Toolbar(int selected, GUIContent[] content, params GUILayoutOption[] options) + { + return GUILayout.Toolbar(selected, content, GUI.skin.button, options); + } + public static int Toolbar(int selected, string[] texts, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.Toolbar(selected, GUIContent.Temp(texts), style, options); + } + public static int Toolbar(int selected, Texture[] images, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.Toolbar(selected, GUIContent.Temp(images), style, options); + } + public static int Toolbar(int selected, GUIContent[] contents, GUIStyle style, params GUILayoutOption[] options) + { + GUIStyle gUIStyle; + GUIStyle gUIStyle2; + GUIStyle gUIStyle3; + GUI.FindStyles(ref style, out gUIStyle, out gUIStyle2, out gUIStyle3, "left", "mid", "right"); + Vector2 vector = default(Vector2); + int num = contents.Length; + GUIStyle gUIStyle4 = (num <= 1) ? style : gUIStyle; + GUIStyle gUIStyle5 = (num <= 1) ? style : gUIStyle2; + GUIStyle gUIStyle6 = (num <= 1) ? style : gUIStyle3; + int num2 = gUIStyle4.margin.left; + for (int i = 0; i < contents.Length; i++) + { + if (i == num - 2) + { + gUIStyle4 = gUIStyle5; + gUIStyle5 = gUIStyle6; + } + if (i == num - 1) + { + gUIStyle4 = gUIStyle6; + } + Vector2 vector2 = gUIStyle4.CalcSize(contents[i]); + if (vector2.x > vector.x) + { + vector.x = vector2.x; + } + if (vector2.y > vector.y) + { + vector.y = vector2.y; + } + if (i == num - 1) + { + num2 += gUIStyle4.margin.right; + } + else + { + num2 += Mathf.Max(gUIStyle4.margin.right, gUIStyle5.margin.left); + } + } + vector.x = vector.x * (float)contents.Length + (float)num2; + return GUI.Toolbar(GUILayoutUtility.GetRect(vector.x, vector.y, style, options), selected, contents, style); + } + public static int SelectionGrid(int selected, string[] texts, int xCount, params GUILayoutOption[] options) + { + return GUILayout.SelectionGrid(selected, GUIContent.Temp(texts), xCount, GUI.skin.button, options); + } + public static int SelectionGrid(int selected, Texture[] images, int xCount, params GUILayoutOption[] options) + { + return GUILayout.SelectionGrid(selected, GUIContent.Temp(images), xCount, GUI.skin.button, options); + } + public static int SelectionGrid(int selected, GUIContent[] content, int xCount, params GUILayoutOption[] options) + { + return GUILayout.SelectionGrid(selected, content, xCount, GUI.skin.button, options); + } + public static int SelectionGrid(int selected, string[] texts, int xCount, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.SelectionGrid(selected, GUIContent.Temp(texts), xCount, style, options); + } + public static int SelectionGrid(int selected, Texture[] images, int xCount, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.SelectionGrid(selected, GUIContent.Temp(images), xCount, style, options); + } + public static int SelectionGrid(int selected, GUIContent[] contents, int xCount, GUIStyle style, params GUILayoutOption[] options) + { + return GUI.SelectionGrid(GUIGridSizer.GetRect(contents, xCount, style, options), selected, contents, xCount, style); + } + public static float HorizontalSlider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) + { + return GUILayout.DoHorizontalSlider(value, leftValue, rightValue, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, options); + } + public static float HorizontalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) + { + return GUILayout.DoHorizontalSlider(value, leftValue, rightValue, slider, thumb, options); + } + private static float DoHorizontalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, GUILayoutOption[] options) + { + return GUI.HorizontalSlider(GUILayoutUtility.GetRect(GUIContent.Temp("mmmm"), slider, options), value, leftValue, rightValue, slider, thumb); + } + public static float VerticalSlider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) + { + return GUILayout.DoVerticalSlider(value, leftValue, rightValue, GUI.skin.verticalSlider, GUI.skin.verticalSliderThumb, options); + } + public static float VerticalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) + { + return GUILayout.DoVerticalSlider(value, leftValue, rightValue, slider, thumb, options); + } + private static float DoVerticalSlider(float value, float leftValue, float rightValue, GUIStyle slider, GUIStyle thumb, params GUILayoutOption[] options) + { + return GUI.VerticalSlider(GUILayoutUtility.GetRect(GUIContent.Temp("\n\n\n\n\n"), slider, options), value, leftValue, rightValue, slider, thumb); + } + public static float HorizontalScrollbar(float value, float size, float leftValue, float rightValue, params GUILayoutOption[] options) + { + return GUILayout.HorizontalScrollbar(value, size, leftValue, rightValue, GUI.skin.horizontalScrollbar, options); + } + public static float HorizontalScrollbar(float value, float size, float leftValue, float rightValue, GUIStyle style, params GUILayoutOption[] options) + { + return GUI.HorizontalScrollbar(GUILayoutUtility.GetRect(GUIContent.Temp("mmmm"), style, options), value, size, leftValue, rightValue, style); + } + public static float VerticalScrollbar(float value, float size, float topValue, float bottomValue, params GUILayoutOption[] options) + { + return GUILayout.VerticalScrollbar(value, size, topValue, bottomValue, GUI.skin.verticalScrollbar, options); + } + public static float VerticalScrollbar(float value, float size, float topValue, float bottomValue, GUIStyle style, params GUILayoutOption[] options) + { + return GUI.VerticalScrollbar(GUILayoutUtility.GetRect(GUIContent.Temp("\n\n\n\n"), style, options), value, size, topValue, bottomValue, style); + } + public static void Space(float pixels) + { + GUIUtility.CheckOnGUI(); + if (GUILayoutUtility.current.topLevel.isVertical) + { + GUILayoutUtility.GetRect(0f, pixels, GUILayoutUtility.spaceStyle, new GUILayoutOption[] + { + GUILayout.Height(pixels) + }); + } + else + { + GUILayoutUtility.GetRect(pixels, 0f, GUILayoutUtility.spaceStyle, new GUILayoutOption[] + { + GUILayout.Width(pixels) + }); + } + } + public static void FlexibleSpace() + { + GUIUtility.CheckOnGUI(); + GUILayoutOption gUILayoutOption; + if (GUILayoutUtility.current.topLevel.isVertical) + { + gUILayoutOption = GUILayout.ExpandHeight(true); + } + else + { + gUILayoutOption = GUILayout.ExpandWidth(true); + } + gUILayoutOption.value = 10000; + GUILayoutUtility.GetRect(0f, 0f, GUILayoutUtility.spaceStyle, new GUILayoutOption[] + { + gUILayoutOption + }); + } + public static void BeginHorizontal(params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(GUIContent.none, GUIStyle.none, options); + } + public static void BeginHorizontal(GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(GUIContent.none, style, options); + } + public static void BeginHorizontal(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(GUIContent.Temp(text), style, options); + } + public static void BeginHorizontal(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(GUIContent.Temp(image), style, options); + } + public static void BeginHorizontal(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayoutGroup gUILayoutGroup = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); + gUILayoutGroup.isVertical = false; + if (style != GUIStyle.none || content != GUIContent.none) + { + GUI.Box(gUILayoutGroup.rect, content, style); + } + } + public static void EndHorizontal() + { + GUILayoutUtility.EndGroup("GUILayout.EndHorizontal"); + GUILayoutUtility.EndLayoutGroup(); + } + public static void BeginVertical(params GUILayoutOption[] options) + { + GUILayout.BeginVertical(GUIContent.none, GUIStyle.none, options); + } + public static void BeginVertical(GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(GUIContent.none, style, options); + } + public static void BeginVertical(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(GUIContent.Temp(text), style, options); + } + public static void BeginVertical(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(GUIContent.Temp(image), style, options); + } + public static void BeginVertical(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayoutGroup gUILayoutGroup = GUILayoutUtility.BeginLayoutGroup(style, options, typeof(GUILayoutGroup)); + gUILayoutGroup.isVertical = true; + if (style != GUIStyle.none) + { + GUI.Box(gUILayoutGroup.rect, content, style); + } + } + public static void EndVertical() + { + GUILayoutUtility.EndGroup("GUILayout.EndVertical"); + GUILayoutUtility.EndLayoutGroup(); + } + public static void BeginArea(Rect screenRect) + { + GUILayout.BeginArea(screenRect, GUIContent.none, GUIStyle.none); + } + public static void BeginArea(Rect screenRect, string text) + { + GUILayout.BeginArea(screenRect, GUIContent.Temp(text), GUIStyle.none); + } + public static void BeginArea(Rect screenRect, Texture image) + { + GUILayout.BeginArea(screenRect, GUIContent.Temp(image), GUIStyle.none); + } + public static void BeginArea(Rect screenRect, GUIContent content) + { + GUILayout.BeginArea(screenRect, GUIContent.none, GUIStyle.none); + } + public static void BeginArea(Rect screenRect, GUIStyle style) + { + GUILayout.BeginArea(screenRect, GUIContent.none, style); + } + public static void BeginArea(Rect screenRect, string text, GUIStyle style) + { + GUILayout.BeginArea(screenRect, GUIContent.Temp(text), style); + } + public static void BeginArea(Rect screenRect, Texture image, GUIStyle style) + { + GUILayout.BeginArea(screenRect, GUIContent.Temp(image), style); + } + public static void BeginArea(Rect screenRect, GUIContent content, GUIStyle style) + { + GUIUtility.CheckOnGUI(); + GUILayoutGroup gUILayoutGroup = GUILayoutUtility.BeginLayoutArea(style, typeof(GUILayoutGroup)); + if (Event.current.type == EventType.Layout) + { + gUILayoutGroup.resetCoords = true; + gUILayoutGroup.minWidth = (gUILayoutGroup.maxWidth = screenRect.width); + gUILayoutGroup.minHeight = (gUILayoutGroup.maxHeight = screenRect.height); + gUILayoutGroup.rect = Rect.MinMaxRect(screenRect.xMin, screenRect.yMin, gUILayoutGroup.rect.xMax, gUILayoutGroup.rect.yMax); + } + GUI.BeginGroup(gUILayoutGroup.rect, content, style); + } + public static void EndArea() + { + GUIUtility.CheckOnGUI(); + if (Event.current.type == EventType.Used) + { + return; + } + GUILayoutUtility.current.layoutGroups.Pop(); + GUILayoutUtility.current.topLevel = (GUILayoutGroup)GUILayoutUtility.current.layoutGroups.Peek(); + GUI.EndGroup(); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, params GUILayoutOption[] options) + { + return GUILayout.BeginScrollView(scrollPosition, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) + { + return GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + return GUILayout.BeginScrollView(scrollPosition, false, false, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle style) + { + GUILayoutOption[] options = null; + return GUILayout.BeginScrollView(scrollPosition, style, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) + { + string name = style.name; + GUIStyle gUIStyle = GUI.skin.FindStyle(name + "VerticalScrollbar"); + if (gUIStyle == null) + { + gUIStyle = GUI.skin.verticalScrollbar; + } + GUIStyle gUIStyle2 = GUI.skin.FindStyle(name + "HorizontalScrollbar"); + if (gUIStyle2 == null) + { + gUIStyle2 = GUI.skin.horizontalScrollbar; + } + return GUILayout.BeginScrollView(scrollPosition, false, false, gUIStyle2, gUIStyle, style, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + return GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, GUI.skin.scrollView, options); + } + public static Vector2 BeginScrollView(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + GUIUtility.CheckOnGUI(); + GUIScrollGroup gUIScrollGroup = (GUIScrollGroup)GUILayoutUtility.BeginLayoutGroup(background, null, typeof(GUIScrollGroup)); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + gUIScrollGroup.resetCoords = true; + gUIScrollGroup.isVertical = true; + gUIScrollGroup.stretchWidth = 1; + gUIScrollGroup.stretchHeight = 1; + gUIScrollGroup.verticalScrollbar = verticalScrollbar; + gUIScrollGroup.horizontalScrollbar = horizontalScrollbar; + gUIScrollGroup.needsVerticalScrollbar = alwaysShowVertical; + gUIScrollGroup.needsHorizontalScrollbar = alwaysShowHorizontal; + gUIScrollGroup.ApplyOptions(options); + } + return GUI.BeginScrollView(gUIScrollGroup.rect, scrollPosition, new Rect(0f, 0f, gUIScrollGroup.clientWidth, gUIScrollGroup.clientHeight), alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); + } + public static void EndScrollView() + { + GUILayout.EndScrollView(true); + } + internal static void EndScrollView(bool handleScrollWheel) + { + GUILayoutUtility.EndGroup("GUILayout.EndScrollView"); + GUILayoutUtility.EndLayoutGroup(); + GUI.EndScrollView(handleScrollWheel); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, string text, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, GUIContent.Temp(text), GUI.skin.window, options); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, Texture image, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, GUIContent.Temp(image), GUI.skin.window, options); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, content, GUI.skin.window, options); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, string text, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, GUIContent.Temp(text), style, options); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, Texture image, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, GUIContent.Temp(image), style, options); + } + public static Rect Window(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayout.DoWindow(id, screenRect, func, content, style, options); + } + private static Rect DoWindow(int id, Rect screenRect, GUI.WindowFunction func, GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + GUIUtility.CheckOnGUI(); + GUILayout.LayoutedWindow @object = new GUILayout.LayoutedWindow(func, screenRect, content, options, style); + return GUI.Window(id, screenRect, new GUI.WindowFunction(@object.DoWindow), content, style); + } + public static GUILayoutOption Width(float width) + { + return new GUILayoutOption(GUILayoutOption.Type.fixedWidth, width); + } + public static GUILayoutOption MinWidth(float minWidth) + { + return new GUILayoutOption(GUILayoutOption.Type.minWidth, minWidth); + } + public static GUILayoutOption MaxWidth(float maxWidth) + { + return new GUILayoutOption(GUILayoutOption.Type.maxWidth, maxWidth); + } + public static GUILayoutOption Height(float height) + { + return new GUILayoutOption(GUILayoutOption.Type.fixedHeight, height); + } + public static GUILayoutOption MinHeight(float minHeight) + { + return new GUILayoutOption(GUILayoutOption.Type.minHeight, minHeight); + } + public static GUILayoutOption MaxHeight(float maxHeight) + { + return new GUILayoutOption(GUILayoutOption.Type.maxHeight, maxHeight); + } + public static GUILayoutOption ExpandWidth(bool expand) + { + return new GUILayoutOption(GUILayoutOption.Type.stretchWidth, (!expand) ? 0 : 1); + } + public static GUILayoutOption ExpandHeight(bool expand) + { + return new GUILayoutOption(GUILayoutOption.Type.stretchHeight, (!expand) ? 0 : 1); + } + } +} diff --git a/UnityEngine/UnityEngine/GUILayoutEntry.cs b/UnityEngine/UnityEngine/GUILayoutEntry.cs new file mode 100644 index 00000000..0389f2fa --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayoutEntry.cs @@ -0,0 +1,176 @@ +using System; +namespace UnityEngine +{ + internal class GUILayoutEntry + { + public float minWidth; + public float maxWidth; + public float minHeight; + public float maxHeight; + public Rect rect = new Rect(0f, 0f, 0f, 0f); + public int stretchWidth; + public int stretchHeight; + private GUIStyle m_Style = GUIStyle.none; + internal static Rect kDummyRect = new Rect(0f, 0f, 1f, 1f); + protected static int indent = 0; + public GUIStyle style + { + get + { + return this.m_Style; + } + set + { + this.m_Style = value; + this.ApplyStyleSettings(value); + } + } + public virtual RectOffset margin + { + get + { + return this.style.margin; + } + } + public GUILayoutEntry(float _minWidth, float _maxWidth, float _minHeight, float _maxHeight, GUIStyle _style) + { + this.minWidth = _minWidth; + this.maxWidth = _maxWidth; + this.minHeight = _minHeight; + this.maxHeight = _maxHeight; + if (_style == null) + { + _style = GUIStyle.none; + } + this.style = _style; + } + public GUILayoutEntry(float _minWidth, float _maxWidth, float _minHeight, float _maxHeight, GUIStyle _style, GUILayoutOption[] options) + { + this.minWidth = _minWidth; + this.maxWidth = _maxWidth; + this.minHeight = _minHeight; + this.maxHeight = _maxHeight; + this.style = _style; + this.ApplyOptions(options); + } + public virtual void CalcWidth() + { + } + public virtual void CalcHeight() + { + } + public virtual void SetHorizontal(float x, float width) + { + this.rect.x = x; + this.rect.width = width; + } + public virtual void SetVertical(float y, float height) + { + this.rect.y = y; + this.rect.height = height; + } + protected virtual void ApplyStyleSettings(GUIStyle style) + { + this.stretchWidth = ((style.fixedWidth != 0f || !style.stretchWidth) ? 0 : 1); + this.stretchHeight = ((style.fixedHeight != 0f || !style.stretchHeight) ? 0 : 1); + this.m_Style = style; + } + public virtual void ApplyOptions(GUILayoutOption[] options) + { + if (options == null) + { + return; + } + for (int i = 0; i < options.Length; i++) + { + GUILayoutOption gUILayoutOption = options[i]; + switch (gUILayoutOption.type) + { + case GUILayoutOption.Type.fixedWidth: + this.minWidth = (this.maxWidth = (float)gUILayoutOption.value); + this.stretchWidth = 0; + break; + case GUILayoutOption.Type.fixedHeight: + this.minHeight = (this.maxHeight = (float)gUILayoutOption.value); + this.stretchHeight = 0; + break; + case GUILayoutOption.Type.minWidth: + this.minWidth = (float)gUILayoutOption.value; + if (this.maxWidth < this.minWidth) + { + this.maxWidth = this.minWidth; + } + break; + case GUILayoutOption.Type.maxWidth: + this.maxWidth = (float)gUILayoutOption.value; + if (this.minWidth > this.maxWidth) + { + this.minWidth = this.maxWidth; + } + this.stretchWidth = 0; + break; + case GUILayoutOption.Type.minHeight: + this.minHeight = (float)gUILayoutOption.value; + if (this.maxHeight < this.minHeight) + { + this.maxHeight = this.minHeight; + } + break; + case GUILayoutOption.Type.maxHeight: + this.maxHeight = (float)gUILayoutOption.value; + if (this.minHeight > this.maxHeight) + { + this.minHeight = this.maxHeight; + } + this.stretchHeight = 0; + break; + case GUILayoutOption.Type.stretchWidth: + this.stretchWidth = (int)gUILayoutOption.value; + break; + case GUILayoutOption.Type.stretchHeight: + this.stretchHeight = (int)gUILayoutOption.value; + break; + } + } + if (this.maxWidth != 0f && this.maxWidth < this.minWidth) + { + this.maxWidth = this.minWidth; + } + if (this.maxHeight != 0f && this.maxHeight < this.minHeight) + { + this.maxHeight = this.minHeight; + } + } + public override string ToString() + { + string text = string.Empty; + for (int i = 0; i < GUILayoutEntry.indent; i++) + { + text += " "; + } + return string.Concat(new object[] + { + text, + UnityString.Format("{1}-{0} (x:{2}-{3}, y:{4}-{5})", new object[] + { + (this.style == null) ? "NULL" : this.style.name, + base.GetType(), + this.rect.x, + this.rect.xMax, + this.rect.y, + this.rect.yMax + }), + " - W: ", + this.minWidth, + "-", + this.maxWidth, + (this.stretchWidth == 0) ? string.Empty : "+", + ", H: ", + this.minHeight, + "-", + this.maxHeight, + (this.stretchHeight == 0) ? string.Empty : "+" + }); + } + } +} diff --git a/UnityEngine/UnityEngine/GUILayoutGroup.cs b/UnityEngine/UnityEngine/GUILayoutGroup.cs new file mode 100644 index 00000000..640f0496 --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayoutGroup.cs @@ -0,0 +1,589 @@ +using System; +using System.Collections.Generic; +namespace UnityEngine +{ + internal class GUILayoutGroup : GUILayoutEntry + { + public List entries = new List(); + public bool isVertical = true; + public bool resetCoords; + public float spacing; + public bool sameSize = true; + public bool isWindow; + public int windowID = -1; + private int cursor; + protected int stretchableCountX = 100; + protected int stretchableCountY = 100; + protected bool userSpecifiedWidth; + protected bool userSpecifiedHeight; + protected float childMinWidth = 100f; + protected float childMaxWidth = 100f; + protected float childMinHeight = 100f; + protected float childMaxHeight = 100f; + private RectOffset m_Margin = new RectOffset(); + public override RectOffset margin + { + get + { + return this.m_Margin; + } + } + public GUILayoutGroup() : base(0f, 0f, 0f, 0f, GUIStyle.none) + { + } + public GUILayoutGroup(GUIStyle _style, GUILayoutOption[] options) : base(0f, 0f, 0f, 0f, _style) + { + if (options != null) + { + this.ApplyOptions(options); + } + this.m_Margin.left = _style.margin.left; + this.m_Margin.right = _style.margin.right; + this.m_Margin.top = _style.margin.top; + this.m_Margin.bottom = _style.margin.bottom; + } + public override void ApplyOptions(GUILayoutOption[] options) + { + if (options == null) + { + return; + } + base.ApplyOptions(options); + for (int i = 0; i < options.Length; i++) + { + GUILayoutOption gUILayoutOption = options[i]; + switch (gUILayoutOption.type) + { + case GUILayoutOption.Type.fixedWidth: + case GUILayoutOption.Type.minWidth: + case GUILayoutOption.Type.maxWidth: + this.userSpecifiedHeight = true; + break; + case GUILayoutOption.Type.fixedHeight: + case GUILayoutOption.Type.minHeight: + case GUILayoutOption.Type.maxHeight: + this.userSpecifiedWidth = true; + break; + case GUILayoutOption.Type.spacing: + this.spacing = (float)((int)gUILayoutOption.value); + break; + } + } + } + protected override void ApplyStyleSettings(GUIStyle style) + { + base.ApplyStyleSettings(style); + RectOffset margin = style.margin; + this.m_Margin.left = margin.left; + this.m_Margin.right = margin.right; + this.m_Margin.top = margin.top; + this.m_Margin.bottom = margin.bottom; + } + public void ResetCursor() + { + this.cursor = 0; + } + public Rect PeekNext() + { + if (this.cursor < this.entries.Count) + { + GUILayoutEntry gUILayoutEntry = this.entries[this.cursor]; + return gUILayoutEntry.rect; + } + throw new ArgumentException(string.Concat(new object[] + { + "Getting control ", + this.cursor, + "'s position in a group with only ", + this.entries.Count, + " controls when doing ", + Event.current.rawType, + "\nAborting" + })); + } + public GUILayoutEntry GetNext() + { + if (this.cursor < this.entries.Count) + { + GUILayoutEntry result = this.entries[this.cursor]; + this.cursor++; + return result; + } + throw new ArgumentException(string.Concat(new object[] + { + "Getting control ", + this.cursor, + "'s position in a group with only ", + this.entries.Count, + " controls when doing ", + Event.current.rawType, + "\nAborting" + })); + } + public Rect GetLast() + { + if (this.cursor == 0) + { + Debug.LogError("You cannot call GetLast immediately after beginning a group."); + return GUILayoutEntry.kDummyRect; + } + if (this.cursor <= this.entries.Count) + { + GUILayoutEntry gUILayoutEntry = this.entries[this.cursor - 1]; + return gUILayoutEntry.rect; + } + Debug.LogError(string.Concat(new object[] + { + "Getting control ", + this.cursor, + "'s position in a group with only ", + this.entries.Count, + " controls when doing ", + Event.current.type + })); + return GUILayoutEntry.kDummyRect; + } + public void Add(GUILayoutEntry e) + { + this.entries.Add(e); + } + public override void CalcWidth() + { + if (this.entries.Count == 0) + { + this.maxWidth = (this.minWidth = (float)base.style.padding.horizontal); + return; + } + this.childMinWidth = 0f; + this.childMaxWidth = 0f; + int num = 0; + int num2 = 0; + this.stretchableCountX = 0; + bool flag = true; + if (this.isVertical) + { + foreach (GUILayoutEntry current in this.entries) + { + current.CalcWidth(); + RectOffset margin = current.margin; + if (current.style != GUILayoutUtility.spaceStyle) + { + if (!flag) + { + num = Mathf.Min(margin.left, num); + num2 = Mathf.Min(margin.right, num2); + } + else + { + num = margin.left; + num2 = margin.right; + flag = false; + } + this.childMinWidth = Mathf.Max(current.minWidth + (float)margin.horizontal, this.childMinWidth); + this.childMaxWidth = Mathf.Max(current.maxWidth + (float)margin.horizontal, this.childMaxWidth); + } + this.stretchableCountX += current.stretchWidth; + } + this.childMinWidth -= (float)(num + num2); + this.childMaxWidth -= (float)(num + num2); + } + else + { + int num3 = 0; + foreach (GUILayoutEntry current2 in this.entries) + { + current2.CalcWidth(); + RectOffset margin2 = current2.margin; + if (current2.style != GUILayoutUtility.spaceStyle) + { + int num4; + if (!flag) + { + num4 = ((num3 <= margin2.left) ? margin2.left : num3); + } + else + { + num4 = 0; + flag = false; + } + this.childMinWidth += current2.minWidth + this.spacing + (float)num4; + this.childMaxWidth += current2.maxWidth + this.spacing + (float)num4; + num3 = margin2.right; + this.stretchableCountX += current2.stretchWidth; + } + else + { + this.childMinWidth += current2.minWidth; + this.childMaxWidth += current2.maxWidth; + this.stretchableCountX += current2.stretchWidth; + } + } + this.childMinWidth -= this.spacing; + this.childMaxWidth -= this.spacing; + if (this.entries.Count != 0) + { + num = this.entries[0].margin.left; + num2 = num3; + } + else + { + num2 = (num = 0); + } + } + float num5; + float num6; + if (base.style != GUIStyle.none || this.userSpecifiedWidth) + { + num5 = (float)Mathf.Max(base.style.padding.left, num); + num6 = (float)Mathf.Max(base.style.padding.right, num2); + } + else + { + this.m_Margin.left = num; + this.m_Margin.right = num2; + num6 = (num5 = 0f); + } + this.minWidth = Mathf.Max(this.minWidth, this.childMinWidth + num5 + num6); + if (this.maxWidth == 0f) + { + this.stretchWidth += this.stretchableCountX + ((!base.style.stretchWidth) ? 0 : 1); + this.maxWidth = this.childMaxWidth + num5 + num6; + } + else + { + this.stretchWidth = 0; + } + this.maxWidth = Mathf.Max(this.maxWidth, this.minWidth); + if (base.style.fixedWidth != 0f) + { + this.maxWidth = (this.minWidth = base.style.fixedWidth); + this.stretchWidth = 0; + } + } + public override void SetHorizontal(float x, float width) + { + base.SetHorizontal(x, width); + if (this.resetCoords) + { + x = 0f; + } + RectOffset padding = base.style.padding; + if (this.isVertical) + { + if (base.style != GUIStyle.none) + { + foreach (GUILayoutEntry current in this.entries) + { + float num = (float)Mathf.Max(current.margin.left, padding.left); + float x2 = x + num; + float num2 = width - (float)Mathf.Max(current.margin.right, padding.right) - num; + if (current.stretchWidth != 0) + { + current.SetHorizontal(x2, num2); + } + else + { + current.SetHorizontal(x2, Mathf.Clamp(num2, current.minWidth, current.maxWidth)); + } + } + } + else + { + float num3 = x - (float)this.margin.left; + float num4 = width + (float)this.margin.horizontal; + foreach (GUILayoutEntry current2 in this.entries) + { + if (current2.stretchWidth != 0) + { + current2.SetHorizontal(num3 + (float)current2.margin.left, num4 - (float)current2.margin.horizontal); + } + else + { + current2.SetHorizontal(num3 + (float)current2.margin.left, Mathf.Clamp(num4 - (float)current2.margin.horizontal, current2.minWidth, current2.maxWidth)); + } + } + } + } + else + { + if (base.style != GUIStyle.none) + { + float num5 = (float)padding.left; + float num6 = (float)padding.right; + if (this.entries.Count != 0) + { + num5 = Mathf.Max(num5, (float)this.entries[0].margin.left); + num6 = Mathf.Max(num6, (float)this.entries[this.entries.Count - 1].margin.right); + } + x += num5; + width -= num6 + num5; + } + float num7 = width - this.spacing * (float)(this.entries.Count - 1); + float t = 0f; + if (this.childMinWidth != this.childMaxWidth) + { + t = Mathf.Clamp((num7 - this.childMinWidth) / (this.childMaxWidth - this.childMinWidth), 0f, 1f); + } + float num8 = 0f; + if (num7 > this.childMaxWidth && this.stretchableCountX > 0) + { + num8 = (num7 - this.childMaxWidth) / (float)this.stretchableCountX; + } + int num9 = 0; + bool flag = true; + foreach (GUILayoutEntry current3 in this.entries) + { + float num10 = Mathf.Lerp(current3.minWidth, current3.maxWidth, t); + num10 += num8 * (float)current3.stretchWidth; + if (current3.style != GUILayoutUtility.spaceStyle) + { + int num11 = current3.margin.left; + if (flag) + { + num11 = 0; + flag = false; + } + int num12 = (num9 <= num11) ? num11 : num9; + x += (float)num12; + num9 = current3.margin.right; + } + current3.SetHorizontal(Mathf.Round(x), Mathf.Round(num10)); + x += num10 + this.spacing; + } + } + } + public override void CalcHeight() + { + if (this.entries.Count == 0) + { + this.maxHeight = (this.minHeight = (float)base.style.padding.vertical); + return; + } + this.childMinHeight = (this.childMaxHeight = 0f); + int num = 0; + int num2 = 0; + this.stretchableCountY = 0; + if (this.isVertical) + { + int num3 = 0; + bool flag = true; + foreach (GUILayoutEntry current in this.entries) + { + current.CalcHeight(); + RectOffset margin = current.margin; + if (current.style != GUILayoutUtility.spaceStyle) + { + int num4; + if (!flag) + { + num4 = Mathf.Max(num3, margin.top); + } + else + { + num4 = 0; + flag = false; + } + this.childMinHeight += current.minHeight + this.spacing + (float)num4; + this.childMaxHeight += current.maxHeight + this.spacing + (float)num4; + num3 = margin.bottom; + this.stretchableCountY += current.stretchHeight; + } + else + { + this.childMinHeight += current.minHeight; + this.childMaxHeight += current.maxHeight; + this.stretchableCountY += current.stretchHeight; + } + } + this.childMinHeight -= this.spacing; + this.childMaxHeight -= this.spacing; + if (this.entries.Count != 0) + { + num = this.entries[0].margin.top; + num2 = num3; + } + else + { + num = (num2 = 0); + } + } + else + { + bool flag2 = true; + foreach (GUILayoutEntry current2 in this.entries) + { + current2.CalcHeight(); + RectOffset margin2 = current2.margin; + if (current2.style != GUILayoutUtility.spaceStyle) + { + if (!flag2) + { + num = Mathf.Min(margin2.top, num); + num2 = Mathf.Min(margin2.bottom, num2); + } + else + { + num = margin2.top; + num2 = margin2.bottom; + flag2 = false; + } + this.childMinHeight = Mathf.Max(current2.minHeight, this.childMinHeight); + this.childMaxHeight = Mathf.Max(current2.maxHeight, this.childMaxHeight); + } + this.stretchableCountY += current2.stretchHeight; + } + } + float num5; + float num6; + if (base.style != GUIStyle.none || this.userSpecifiedHeight) + { + num5 = (float)Mathf.Max(base.style.padding.top, num); + num6 = (float)Mathf.Max(base.style.padding.bottom, num2); + } + else + { + this.m_Margin.top = num; + this.m_Margin.bottom = num2; + num6 = (num5 = 0f); + } + this.minHeight = Mathf.Max(this.minHeight, this.childMinHeight + num5 + num6); + if (this.maxHeight == 0f) + { + this.stretchHeight += this.stretchableCountY + ((!base.style.stretchHeight) ? 0 : 1); + this.maxHeight = this.childMaxHeight + num5 + num6; + } + else + { + this.stretchHeight = 0; + } + this.maxHeight = Mathf.Max(this.maxHeight, this.minHeight); + if (base.style.fixedHeight != 0f) + { + this.maxHeight = (this.minHeight = base.style.fixedHeight); + this.stretchHeight = 0; + } + } + public override void SetVertical(float y, float height) + { + base.SetVertical(y, height); + if (this.entries.Count == 0) + { + return; + } + RectOffset padding = base.style.padding; + if (this.resetCoords) + { + y = 0f; + } + if (this.isVertical) + { + if (base.style != GUIStyle.none) + { + float num = (float)padding.top; + float num2 = (float)padding.bottom; + if (this.entries.Count != 0) + { + num = Mathf.Max(num, (float)this.entries[0].margin.top); + num2 = Mathf.Max(num2, (float)this.entries[this.entries.Count - 1].margin.bottom); + } + y += num; + height -= num2 + num; + } + float num3 = height - this.spacing * (float)(this.entries.Count - 1); + float t = 0f; + if (this.childMinHeight != this.childMaxHeight) + { + t = Mathf.Clamp((num3 - this.childMinHeight) / (this.childMaxHeight - this.childMinHeight), 0f, 1f); + } + float num4 = 0f; + if (num3 > this.childMaxHeight && this.stretchableCountY > 0) + { + num4 = (num3 - this.childMaxHeight) / (float)this.stretchableCountY; + } + int num5 = 0; + bool flag = true; + foreach (GUILayoutEntry current in this.entries) + { + float num6 = Mathf.Lerp(current.minHeight, current.maxHeight, t); + num6 += num4 * (float)current.stretchHeight; + if (current.style != GUILayoutUtility.spaceStyle) + { + int num7 = current.margin.top; + if (flag) + { + num7 = 0; + flag = false; + } + int num8 = (num5 <= num7) ? num7 : num5; + y += (float)num8; + num5 = current.margin.bottom; + } + current.SetVertical(Mathf.Round(y), Mathf.Round(num6)); + y += num6 + this.spacing; + } + } + else + { + if (base.style != GUIStyle.none) + { + foreach (GUILayoutEntry current2 in this.entries) + { + float num9 = (float)Mathf.Max(current2.margin.top, padding.top); + float y2 = y + num9; + float num10 = height - (float)Mathf.Max(current2.margin.bottom, padding.bottom) - num9; + if (current2.stretchHeight != 0) + { + current2.SetVertical(y2, num10); + } + else + { + current2.SetVertical(y2, Mathf.Clamp(num10, current2.minHeight, current2.maxHeight)); + } + } + } + else + { + float num11 = y - (float)this.margin.top; + float num12 = height + (float)this.margin.vertical; + foreach (GUILayoutEntry current3 in this.entries) + { + if (current3.stretchHeight != 0) + { + current3.SetVertical(num11 + (float)current3.margin.top, num12 - (float)current3.margin.vertical); + } + else + { + current3.SetVertical(num11 + (float)current3.margin.top, Mathf.Clamp(num12 - (float)current3.margin.vertical, current3.minHeight, current3.maxHeight)); + } + } + } + } + } + public override string ToString() + { + string text = string.Empty; + string text2 = string.Empty; + for (int i = 0; i < GUILayoutEntry.indent; i++) + { + text2 += " "; + } + string text3 = text; + text = string.Concat(new object[] + { + text3, + base.ToString(), + " Margins: ", + this.childMinHeight, + " {\n" + }); + GUILayoutEntry.indent += 4; + foreach (GUILayoutEntry current in this.entries) + { + text = text + current.ToString() + "\n"; + } + text = text + text2 + "}"; + GUILayoutEntry.indent -= 4; + return text; + } + } +} diff --git a/UnityEngine/UnityEngine/GUILayoutOption.cs b/UnityEngine/UnityEngine/GUILayoutOption.cs new file mode 100644 index 00000000..0b6e3947 --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayoutOption.cs @@ -0,0 +1,31 @@ +using System; +namespace UnityEngine +{ + public sealed class GUILayoutOption + { + internal enum Type + { + fixedWidth, + fixedHeight, + minWidth, + maxWidth, + minHeight, + maxHeight, + stretchWidth, + stretchHeight, + alignStart, + alignMiddle, + alignEnd, + alignJustify, + equalSize, + spacing + } + internal GUILayoutOption.Type type; + internal object value; + internal GUILayoutOption(GUILayoutOption.Type type, object value) + { + this.type = type; + this.value = value; + } + } +} diff --git a/UnityEngine/UnityEngine/GUILayoutUtility.cs b/UnityEngine/UnityEngine/GUILayoutUtility.cs new file mode 100644 index 00000000..2d1a194d --- /dev/null +++ b/UnityEngine/UnityEngine/GUILayoutUtility.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Security; +using UnityEngineInternal; +namespace UnityEngine +{ + public class GUILayoutUtility + { + internal sealed class LayoutCache + { + internal GUILayoutGroup topLevel = new GUILayoutGroup(); + internal GenericStack layoutGroups = new GenericStack(); + internal GUILayoutGroup windows = new GUILayoutGroup(); + internal LayoutCache() + { + this.layoutGroups.Push(this.topLevel); + } + internal LayoutCache(GUILayoutUtility.LayoutCache other) + { + this.topLevel = other.topLevel; + this.layoutGroups = other.layoutGroups; + this.windows = other.windows; + } + } + private static Dictionary storedLayouts = new Dictionary(); + private static Dictionary storedWindows = new Dictionary(); + internal static GUILayoutUtility.LayoutCache current = new GUILayoutUtility.LayoutCache(); + private static Rect kDummyRect = new Rect(0f, 0f, 1f, 1f); + private static GUIStyle s_SpaceStyle; + internal static GUILayoutGroup topLevel + { + get + { + return GUILayoutUtility.current.topLevel; + } + } + internal static GUIStyle spaceStyle + { + get + { + if (GUILayoutUtility.s_SpaceStyle == null) + { + GUILayoutUtility.s_SpaceStyle = new GUIStyle(); + } + GUILayoutUtility.s_SpaceStyle.stretchWidth = false; + return GUILayoutUtility.s_SpaceStyle; + } + } + internal static GUILayoutUtility.LayoutCache SelectIDList(int instanceID, bool isWindow) + { + Dictionary dictionary = (!isWindow) ? GUILayoutUtility.storedLayouts : GUILayoutUtility.storedWindows; + GUILayoutUtility.LayoutCache layoutCache; + if (!dictionary.TryGetValue(instanceID, out layoutCache)) + { + layoutCache = new GUILayoutUtility.LayoutCache(); + dictionary[instanceID] = layoutCache; + } + GUILayoutUtility.current.topLevel = layoutCache.topLevel; + GUILayoutUtility.current.layoutGroups = layoutCache.layoutGroups; + GUILayoutUtility.current.windows = layoutCache.windows; + return layoutCache; + } + internal static void Begin(int instanceID) + { + GUILayoutUtility.LayoutCache layoutCache = GUILayoutUtility.SelectIDList(instanceID, false); + if (Event.current.type == EventType.Layout) + { + GUILayoutUtility.current.topLevel = (layoutCache.topLevel = new GUILayoutGroup()); + GUILayoutUtility.current.layoutGroups.Clear(); + GUILayoutUtility.current.layoutGroups.Push(GUILayoutUtility.current.topLevel); + GUILayoutUtility.current.windows = (layoutCache.windows = new GUILayoutGroup()); + } + else + { + GUILayoutUtility.current.topLevel = layoutCache.topLevel; + GUILayoutUtility.current.layoutGroups = layoutCache.layoutGroups; + GUILayoutUtility.current.windows = layoutCache.windows; + } + } + internal static void BeginWindow(int windowID, GUIStyle style, GUILayoutOption[] options) + { + GUILayoutUtility.LayoutCache layoutCache = GUILayoutUtility.SelectIDList(windowID, true); + if (Event.current.type == EventType.Layout) + { + GUILayoutUtility.current.topLevel = (layoutCache.topLevel = new GUILayoutGroup()); + GUILayoutUtility.current.topLevel.style = style; + GUILayoutUtility.current.topLevel.windowID = windowID; + if (options != null) + { + GUILayoutUtility.current.topLevel.ApplyOptions(options); + } + GUILayoutUtility.current.layoutGroups.Clear(); + GUILayoutUtility.current.layoutGroups.Push(GUILayoutUtility.current.topLevel); + GUILayoutUtility.current.windows = (layoutCache.windows = new GUILayoutGroup()); + } + else + { + GUILayoutUtility.current.topLevel = layoutCache.topLevel; + GUILayoutUtility.current.layoutGroups = layoutCache.layoutGroups; + GUILayoutUtility.current.windows = layoutCache.windows; + } + } + public static void BeginGroup(string GroupName) + { + } + public static void EndGroup(string groupName) + { + } + internal static void Layout() + { + if (GUILayoutUtility.current.topLevel.windowID == -1) + { + GUILayoutUtility.current.topLevel.CalcWidth(); + GUILayoutUtility.current.topLevel.SetHorizontal(0f, Mathf.Min((float)Screen.width, GUILayoutUtility.current.topLevel.maxWidth)); + GUILayoutUtility.current.topLevel.CalcHeight(); + GUILayoutUtility.current.topLevel.SetVertical(0f, Mathf.Min((float)Screen.height, GUILayoutUtility.current.topLevel.maxHeight)); + GUILayoutUtility.LayoutFreeGroup(GUILayoutUtility.current.windows); + } + else + { + GUILayoutUtility.LayoutSingleGroup(GUILayoutUtility.current.topLevel); + GUILayoutUtility.LayoutFreeGroup(GUILayoutUtility.current.windows); + } + } + internal static void LayoutFromEditorWindow() + { + GUILayoutUtility.current.topLevel.CalcWidth(); + GUILayoutUtility.current.topLevel.SetHorizontal(0f, (float)Screen.width); + GUILayoutUtility.current.topLevel.CalcHeight(); + GUILayoutUtility.current.topLevel.SetVertical(0f, (float)Screen.height); + GUILayoutUtility.LayoutFreeGroup(GUILayoutUtility.current.windows); + } + internal static float LayoutFromInspector(float width) + { + if (GUILayoutUtility.current.topLevel != null && GUILayoutUtility.current.topLevel.windowID == -1) + { + GUILayoutUtility.current.topLevel.CalcWidth(); + GUILayoutUtility.current.topLevel.SetHorizontal(0f, width); + GUILayoutUtility.current.topLevel.CalcHeight(); + GUILayoutUtility.current.topLevel.SetVertical(0f, Mathf.Min((float)Screen.height, GUILayoutUtility.current.topLevel.maxHeight)); + float minHeight = GUILayoutUtility.current.topLevel.minHeight; + GUILayoutUtility.LayoutFreeGroup(GUILayoutUtility.current.windows); + return minHeight; + } + if (GUILayoutUtility.current.topLevel != null) + { + GUILayoutUtility.LayoutSingleGroup(GUILayoutUtility.current.topLevel); + } + return 0f; + } + internal static void LayoutFreeGroup(GUILayoutGroup toplevel) + { + using (List.Enumerator enumerator = toplevel.entries.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + GUILayoutGroup i = (GUILayoutGroup)enumerator.Current; + GUILayoutUtility.LayoutSingleGroup(i); + } + } + toplevel.ResetCursor(); + } + private static void LayoutSingleGroup(GUILayoutGroup i) + { + if (!i.isWindow) + { + float minWidth = i.minWidth; + float maxWidth = i.maxWidth; + i.CalcWidth(); + i.SetHorizontal(i.rect.x, Mathf.Clamp(i.maxWidth, minWidth, maxWidth)); + float minHeight = i.minHeight; + float maxHeight = i.maxHeight; + i.CalcHeight(); + i.SetVertical(i.rect.y, Mathf.Clamp(i.maxHeight, minHeight, maxHeight)); + } + else + { + i.CalcWidth(); + Rect rect = GUILayoutUtility.Internal_GetWindowRect(i.windowID); + i.SetHorizontal(rect.x, Mathf.Clamp(rect.width, i.minWidth, i.maxWidth)); + i.CalcHeight(); + i.SetVertical(rect.y, Mathf.Clamp(rect.height, i.minHeight, i.maxHeight)); + GUILayoutUtility.Internal_MoveWindow(i.windowID, i.rect); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect Internal_GetWindowRect(int windowID); + private static void Internal_MoveWindow(int windowID, Rect r) + { + GUILayoutUtility.INTERNAL_CALL_Internal_MoveWindow(windowID, ref r); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_MoveWindow(int windowID, ref Rect r); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect GetWindowsBounds(); + [SecuritySafeCritical] + private static GUILayoutGroup CreateGUILayoutGroupInstanceOfType(Type LayoutType) + { + if (!typeof(GUILayoutGroup).IsAssignableFrom(LayoutType)) + { + throw new ArgumentException("LayoutType needs to be of type GUILayoutGroup"); + } + return (GUILayoutGroup)Activator.CreateInstance(LayoutType); + } + internal static GUILayoutGroup BeginLayoutGroup(GUIStyle style, GUILayoutOption[] options, Type LayoutType) + { + EventType type = Event.current.type; + GUILayoutGroup gUILayoutGroup; + if (type != EventType.Layout && type != EventType.Used) + { + gUILayoutGroup = (GUILayoutUtility.current.topLevel.GetNext() as GUILayoutGroup); + if (gUILayoutGroup == null) + { + throw new ArgumentException("GUILayout: Mismatched LayoutGroup." + Event.current.type); + } + gUILayoutGroup.ResetCursor(); + } + else + { + gUILayoutGroup = GUILayoutUtility.CreateGUILayoutGroupInstanceOfType(LayoutType); + gUILayoutGroup.style = style; + if (options != null) + { + gUILayoutGroup.ApplyOptions(options); + } + GUILayoutUtility.current.topLevel.Add(gUILayoutGroup); + } + GUILayoutUtility.current.layoutGroups.Push(gUILayoutGroup); + GUILayoutUtility.current.topLevel = gUILayoutGroup; + return gUILayoutGroup; + } + internal static void EndLayoutGroup() + { + EventType type = Event.current.type; + GUILayoutUtility.current.layoutGroups.Pop(); + GUILayoutUtility.current.topLevel = (GUILayoutGroup)GUILayoutUtility.current.layoutGroups.Peek(); + } + internal static GUILayoutGroup BeginLayoutArea(GUIStyle style, Type LayoutType) + { + EventType type = Event.current.type; + GUILayoutGroup gUILayoutGroup; + if (type != EventType.Layout && type != EventType.Used) + { + gUILayoutGroup = (GUILayoutUtility.current.windows.GetNext() as GUILayoutGroup); + if (gUILayoutGroup == null) + { + throw new ArgumentException("GUILayout: Mismatched LayoutGroup." + Event.current.type); + } + gUILayoutGroup.ResetCursor(); + } + else + { + gUILayoutGroup = GUILayoutUtility.CreateGUILayoutGroupInstanceOfType(LayoutType); + gUILayoutGroup.style = style; + GUILayoutUtility.current.windows.Add(gUILayoutGroup); + } + GUILayoutUtility.current.layoutGroups.Push(gUILayoutGroup); + GUILayoutUtility.current.topLevel = gUILayoutGroup; + return gUILayoutGroup; + } + internal static GUILayoutGroup DoBeginLayoutArea(GUIStyle style, Type LayoutType) + { + return GUILayoutUtility.BeginLayoutArea(style, LayoutType); + } + public static Rect GetRect(GUIContent content, GUIStyle style) + { + return GUILayoutUtility.DoGetRect(content, style, null); + } + public static Rect GetRect(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetRect(content, style, options); + } + private static Rect DoGetRect(GUIContent content, GUIStyle style, GUILayoutOption[] options) + { + GUIUtility.CheckOnGUI(); + EventType type = Event.current.type; + if (type == EventType.Layout) + { + if (style.isHeightDependantOnWidth) + { + GUILayoutUtility.current.topLevel.Add(new GUIWordWrapSizer(style, content, options)); + } + else + { + Vector2 vector = style.CalcSize(content); + GUILayoutUtility.current.topLevel.Add(new GUILayoutEntry(vector.x, vector.x, vector.y, vector.y, style, options)); + } + return GUILayoutUtility.kDummyRect; + } + if (type != EventType.Used) + { + return GUILayoutUtility.current.topLevel.GetNext().rect; + } + return GUILayoutUtility.kDummyRect; + } + public static Rect GetRect(float width, float height) + { + return GUILayoutUtility.DoGetRect(width, width, height, height, GUIStyle.none, null); + } + public static Rect GetRect(float width, float height, GUIStyle style) + { + return GUILayoutUtility.DoGetRect(width, width, height, height, style, null); + } + public static Rect GetRect(float width, float height, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetRect(width, width, height, height, GUIStyle.none, options); + } + public static Rect GetRect(float width, float height, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetRect(width, width, height, height, style, options); + } + public static Rect GetRect(float minWidth, float maxWidth, float minHeight, float maxHeight) + { + return GUILayoutUtility.DoGetRect(minWidth, maxWidth, minHeight, maxHeight, GUIStyle.none, null); + } + public static Rect GetRect(float minWidth, float maxWidth, float minHeight, float maxHeight, GUIStyle style) + { + return GUILayoutUtility.DoGetRect(minWidth, maxWidth, minHeight, maxHeight, style, null); + } + public static Rect GetRect(float minWidth, float maxWidth, float minHeight, float maxHeight, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetRect(minWidth, maxWidth, minHeight, maxHeight, GUIStyle.none, options); + } + public static Rect GetRect(float minWidth, float maxWidth, float minHeight, float maxHeight, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetRect(minWidth, maxWidth, minHeight, maxHeight, style, options); + } + private static Rect DoGetRect(float minWidth, float maxWidth, float minHeight, float maxHeight, GUIStyle style, GUILayoutOption[] options) + { + EventType type = Event.current.type; + if (type == EventType.Layout) + { + GUILayoutUtility.current.topLevel.Add(new GUILayoutEntry(minWidth, maxWidth, minHeight, maxHeight, style, options)); + return GUILayoutUtility.kDummyRect; + } + if (type != EventType.Used) + { + return GUILayoutUtility.current.topLevel.GetNext().rect; + } + return GUILayoutUtility.kDummyRect; + } + public static Rect GetLastRect() + { + EventType type = Event.current.type; + if (type == EventType.Layout) + { + return GUILayoutUtility.kDummyRect; + } + if (type != EventType.Used) + { + return GUILayoutUtility.current.topLevel.GetLast(); + } + return GUILayoutUtility.kDummyRect; + } + public static Rect GetAspectRect(float aspect) + { + return GUILayoutUtility.DoGetAspectRect(aspect, GUIStyle.none, null); + } + public static Rect GetAspectRect(float aspect, GUIStyle style) + { + return GUILayoutUtility.DoGetAspectRect(aspect, style, null); + } + public static Rect GetAspectRect(float aspect, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetAspectRect(aspect, GUIStyle.none, options); + } + public static Rect GetAspectRect(float aspect, GUIStyle style, params GUILayoutOption[] options) + { + return GUILayoutUtility.DoGetAspectRect(aspect, GUIStyle.none, options); + } + private static Rect DoGetAspectRect(float aspect, GUIStyle style, GUILayoutOption[] options) + { + EventType type = Event.current.type; + if (type == EventType.Layout) + { + GUILayoutUtility.current.topLevel.Add(new GUIAspectSizer(aspect, options)); + return GUILayoutUtility.kDummyRect; + } + if (type != EventType.Used) + { + return GUILayoutUtility.current.topLevel.GetNext().rect; + } + return GUILayoutUtility.kDummyRect; + } + } +} diff --git a/UnityEngine/UnityEngine/GUIScrollGroup.cs b/UnityEngine/UnityEngine/GUIScrollGroup.cs new file mode 100644 index 00000000..ec4b382d --- /dev/null +++ b/UnityEngine/UnityEngine/GUIScrollGroup.cs @@ -0,0 +1,151 @@ +using System; +namespace UnityEngine +{ + internal sealed class GUIScrollGroup : GUILayoutGroup + { + public float calcMinWidth; + public float calcMaxWidth; + public float calcMinHeight; + public float calcMaxHeight; + public float clientWidth; + public float clientHeight; + public bool allowHorizontalScroll = true; + public bool allowVerticalScroll = true; + public bool needsHorizontalScrollbar; + public bool needsVerticalScrollbar; + public GUIStyle horizontalScrollbar; + public GUIStyle verticalScrollbar; + public override void CalcWidth() + { + float minWidth = this.minWidth; + float maxWidth = this.maxWidth; + if (this.allowHorizontalScroll) + { + this.minWidth = 0f; + this.maxWidth = 0f; + } + base.CalcWidth(); + this.calcMinWidth = this.minWidth; + this.calcMaxWidth = this.maxWidth; + if (this.allowHorizontalScroll) + { + if (this.minWidth > 32f) + { + this.minWidth = 32f; + } + if (minWidth != 0f) + { + this.minWidth = minWidth; + } + if (maxWidth != 0f) + { + this.maxWidth = maxWidth; + this.stretchWidth = 0; + } + } + } + public override void SetHorizontal(float x, float width) + { + float num = (!this.needsVerticalScrollbar) ? width : (width - this.verticalScrollbar.fixedWidth - (float)this.verticalScrollbar.margin.left); + if (this.allowHorizontalScroll && num < this.calcMinWidth) + { + this.needsHorizontalScrollbar = true; + this.minWidth = this.calcMinWidth; + this.maxWidth = this.calcMaxWidth; + base.SetHorizontal(x, this.calcMinWidth); + this.rect.width = width; + this.clientWidth = this.calcMinWidth; + } + else + { + this.needsHorizontalScrollbar = false; + if (this.allowHorizontalScroll) + { + this.minWidth = this.calcMinWidth; + this.maxWidth = this.calcMaxWidth; + } + base.SetHorizontal(x, num); + this.rect.width = width; + this.clientWidth = num; + } + } + public override void CalcHeight() + { + float minHeight = this.minHeight; + float maxHeight = this.maxHeight; + if (this.allowVerticalScroll) + { + this.minHeight = 0f; + this.maxHeight = 0f; + } + base.CalcHeight(); + this.calcMinHeight = this.minHeight; + this.calcMaxHeight = this.maxHeight; + if (this.needsHorizontalScrollbar) + { + float num = this.horizontalScrollbar.fixedHeight + (float)this.horizontalScrollbar.margin.top; + this.minHeight += num; + this.maxHeight += num; + } + if (this.allowVerticalScroll) + { + if (this.minHeight > 32f) + { + this.minHeight = 32f; + } + if (minHeight != 0f) + { + this.minHeight = minHeight; + } + if (maxHeight != 0f) + { + this.maxHeight = maxHeight; + this.stretchHeight = 0; + } + } + } + public override void SetVertical(float y, float height) + { + float num = height; + if (this.needsHorizontalScrollbar) + { + num -= this.horizontalScrollbar.fixedHeight + (float)this.horizontalScrollbar.margin.top; + } + if (this.allowVerticalScroll && num < this.calcMinHeight) + { + if (!this.needsHorizontalScrollbar && !this.needsVerticalScrollbar) + { + this.clientWidth = this.rect.width - this.verticalScrollbar.fixedWidth - (float)this.verticalScrollbar.margin.left; + if (this.clientWidth < this.calcMinWidth) + { + this.clientWidth = this.calcMinWidth; + } + float width = this.rect.width; + this.SetHorizontal(this.rect.x, this.clientWidth); + this.CalcHeight(); + this.rect.width = width; + } + float minHeight = this.minHeight; + float maxHeight = this.maxHeight; + this.minHeight = this.calcMinHeight; + this.maxHeight = this.calcMaxHeight; + base.SetVertical(y, this.calcMinHeight); + this.minHeight = minHeight; + this.maxHeight = maxHeight; + this.rect.height = height; + this.clientHeight = this.calcMinHeight; + } + else + { + if (this.allowVerticalScroll) + { + this.minHeight = this.calcMinHeight; + this.maxHeight = this.calcMaxHeight; + } + base.SetVertical(y, num); + this.rect.height = height; + this.clientHeight = num; + } + } + } +} diff --git a/UnityEngine/UnityEngine/GUISettings.cs b/UnityEngine/UnityEngine/GUISettings.cs new file mode 100644 index 00000000..eafe9c38 --- /dev/null +++ b/UnityEngine/UnityEngine/GUISettings.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + [Serializable] + public sealed class GUISettings + { + [SerializeField] + private bool m_DoubleClickSelectsWord = true; + [SerializeField] + private bool m_TripleClickSelectsLine = true; + [SerializeField] + private Color m_CursorColor = Color.white; + [SerializeField] + private float m_CursorFlashSpeed = -1f; + [SerializeField] + private Color m_SelectionColor = new Color(0.5f, 0.5f, 1f); + public bool doubleClickSelectsWord + { + get + { + return this.m_DoubleClickSelectsWord; + } + set + { + this.m_DoubleClickSelectsWord = value; + } + } + public bool tripleClickSelectsLine + { + get + { + return this.m_TripleClickSelectsLine; + } + set + { + this.m_TripleClickSelectsLine = value; + } + } + public Color cursorColor + { + get + { + return this.m_CursorColor; + } + set + { + this.m_CursorColor = value; + } + } + public float cursorFlashSpeed + { + get + { + if (this.m_CursorFlashSpeed >= 0f) + { + return this.m_CursorFlashSpeed; + } + return GUISettings.Internal_GetCursorFlashSpeed(); + } + set + { + this.m_CursorFlashSpeed = value; + } + } + public Color selectionColor + { + get + { + return this.m_SelectionColor; + } + set + { + this.m_SelectionColor = value; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float Internal_GetCursorFlashSpeed(); + } +} diff --git a/UnityEngine/UnityEngine/GUISkin.cs b/UnityEngine/UnityEngine/GUISkin.cs new file mode 100644 index 00000000..50da04cc --- /dev/null +++ b/UnityEngine/UnityEngine/GUISkin.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections; +using System.Collections.Generic; +namespace UnityEngine +{ + [ExecuteInEditMode] + [Serializable] + public sealed class GUISkin : ScriptableObject + { + internal delegate void SkinChangedDelegate(); + [SerializeField] + private Font m_Font; + [SerializeField] + private GUIStyle m_box; + [SerializeField] + private GUIStyle m_button; + [SerializeField] + private GUIStyle m_toggle; + [SerializeField] + private GUIStyle m_label; + [SerializeField] + private GUIStyle m_textField; + [SerializeField] + private GUIStyle m_textArea; + [SerializeField] + private GUIStyle m_window; + [SerializeField] + private GUIStyle m_horizontalSlider; + [SerializeField] + private GUIStyle m_horizontalSliderThumb; + [SerializeField] + private GUIStyle m_verticalSlider; + [SerializeField] + private GUIStyle m_verticalSliderThumb; + [SerializeField] + private GUIStyle m_horizontalScrollbar; + [SerializeField] + private GUIStyle m_horizontalScrollbarThumb; + [SerializeField] + private GUIStyle m_horizontalScrollbarLeftButton; + [SerializeField] + private GUIStyle m_horizontalScrollbarRightButton; + [SerializeField] + private GUIStyle m_verticalScrollbar; + [SerializeField] + private GUIStyle m_verticalScrollbarThumb; + [SerializeField] + private GUIStyle m_verticalScrollbarUpButton; + [SerializeField] + private GUIStyle m_verticalScrollbarDownButton; + [SerializeField] + private GUIStyle m_ScrollView; + [SerializeField] + internal GUIStyle[] m_CustomStyles; + [SerializeField] + private GUISettings m_Settings = new GUISettings(); + internal static GUIStyle ms_Error; + private Dictionary styles; + internal static GUISkin.SkinChangedDelegate m_SkinChanged; + internal static GUISkin current; + public Font font + { + get + { + return this.m_Font; + } + set + { + this.m_Font = value; + if (GUISkin.current == this) + { + GUIStyle.SetDefaultFont(this.m_Font); + } + this.Apply(); + } + } + public GUIStyle box + { + get + { + return this.m_box; + } + set + { + this.m_box = value; + this.Apply(); + } + } + public GUIStyle label + { + get + { + return this.m_label; + } + set + { + this.m_label = value; + this.Apply(); + } + } + public GUIStyle textField + { + get + { + return this.m_textField; + } + set + { + this.m_textField = value; + this.Apply(); + } + } + public GUIStyle textArea + { + get + { + return this.m_textArea; + } + set + { + this.m_textArea = value; + this.Apply(); + } + } + public GUIStyle button + { + get + { + return this.m_button; + } + set + { + this.m_button = value; + this.Apply(); + } + } + public GUIStyle toggle + { + get + { + return this.m_toggle; + } + set + { + this.m_toggle = value; + this.Apply(); + } + } + public GUIStyle window + { + get + { + return this.m_window; + } + set + { + this.m_window = value; + this.Apply(); + } + } + public GUIStyle horizontalSlider + { + get + { + return this.m_horizontalSlider; + } + set + { + this.m_horizontalSlider = value; + this.Apply(); + } + } + public GUIStyle horizontalSliderThumb + { + get + { + return this.m_horizontalSliderThumb; + } + set + { + this.m_horizontalSliderThumb = value; + this.Apply(); + } + } + public GUIStyle verticalSlider + { + get + { + return this.m_verticalSlider; + } + set + { + this.m_verticalSlider = value; + this.Apply(); + } + } + public GUIStyle verticalSliderThumb + { + get + { + return this.m_verticalSliderThumb; + } + set + { + this.m_verticalSliderThumb = value; + this.Apply(); + } + } + public GUIStyle horizontalScrollbar + { + get + { + return this.m_horizontalScrollbar; + } + set + { + this.m_horizontalScrollbar = value; + this.Apply(); + } + } + public GUIStyle horizontalScrollbarThumb + { + get + { + return this.m_horizontalScrollbarThumb; + } + set + { + this.m_horizontalScrollbarThumb = value; + this.Apply(); + } + } + public GUIStyle horizontalScrollbarLeftButton + { + get + { + return this.m_horizontalScrollbarLeftButton; + } + set + { + this.m_horizontalScrollbarLeftButton = value; + this.Apply(); + } + } + public GUIStyle horizontalScrollbarRightButton + { + get + { + return this.m_horizontalScrollbarRightButton; + } + set + { + this.m_horizontalScrollbarRightButton = value; + this.Apply(); + } + } + public GUIStyle verticalScrollbar + { + get + { + return this.m_verticalScrollbar; + } + set + { + this.m_verticalScrollbar = value; + this.Apply(); + } + } + public GUIStyle verticalScrollbarThumb + { + get + { + return this.m_verticalScrollbarThumb; + } + set + { + this.m_verticalScrollbarThumb = value; + this.Apply(); + } + } + public GUIStyle verticalScrollbarUpButton + { + get + { + return this.m_verticalScrollbarUpButton; + } + set + { + this.m_verticalScrollbarUpButton = value; + this.Apply(); + } + } + public GUIStyle verticalScrollbarDownButton + { + get + { + return this.m_verticalScrollbarDownButton; + } + set + { + this.m_verticalScrollbarDownButton = value; + this.Apply(); + } + } + public GUIStyle scrollView + { + get + { + return this.m_ScrollView; + } + set + { + this.m_ScrollView = value; + this.Apply(); + } + } + public GUIStyle[] customStyles + { + get + { + return this.m_CustomStyles; + } + set + { + this.m_CustomStyles = value; + this.Apply(); + } + } + public GUISettings settings + { + get + { + return this.m_Settings; + } + } + internal static GUIStyle error + { + get + { + if (GUISkin.ms_Error == null) + { + GUISkin.ms_Error = new GUIStyle(); + } + return GUISkin.ms_Error; + } + } + public GUISkin() + { + this.m_CustomStyles = new GUIStyle[1]; + } + internal void OnEnable() + { + this.Apply(); + foreach (GUIStyle gUIStyle in this.styles.Values) + { + gUIStyle.CreateObjectReferences(); + } + } + internal void Apply() + { + if (this.m_CustomStyles == null) + { + Debug.Log("custom styles is null"); + } + this.BuildStyleCache(); + } + private void BuildStyleCache() + { + if (this.m_box == null) + { + this.m_box = new GUIStyle(); + } + if (this.m_button == null) + { + this.m_button = new GUIStyle(); + } + if (this.m_toggle == null) + { + this.m_toggle = new GUIStyle(); + } + if (this.m_label == null) + { + this.m_label = new GUIStyle(); + } + if (this.m_window == null) + { + this.m_window = new GUIStyle(); + } + if (this.m_textField == null) + { + this.m_textField = new GUIStyle(); + } + if (this.m_textArea == null) + { + this.m_textArea = new GUIStyle(); + } + if (this.m_horizontalSlider == null) + { + this.m_horizontalSlider = new GUIStyle(); + } + if (this.m_horizontalSliderThumb == null) + { + this.m_horizontalSliderThumb = new GUIStyle(); + } + if (this.m_verticalSlider == null) + { + this.m_verticalSlider = new GUIStyle(); + } + if (this.m_verticalSliderThumb == null) + { + this.m_verticalSliderThumb = new GUIStyle(); + } + if (this.m_horizontalScrollbar == null) + { + this.m_horizontalScrollbar = new GUIStyle(); + } + if (this.m_horizontalScrollbarThumb == null) + { + this.m_horizontalScrollbarThumb = new GUIStyle(); + } + if (this.m_horizontalScrollbarLeftButton == null) + { + this.m_horizontalScrollbarLeftButton = new GUIStyle(); + } + if (this.m_horizontalScrollbarRightButton == null) + { + this.m_horizontalScrollbarRightButton = new GUIStyle(); + } + if (this.m_verticalScrollbar == null) + { + this.m_verticalScrollbar = new GUIStyle(); + } + if (this.m_verticalScrollbarThumb == null) + { + this.m_verticalScrollbarThumb = new GUIStyle(); + } + if (this.m_verticalScrollbarUpButton == null) + { + this.m_verticalScrollbarUpButton = new GUIStyle(); + } + if (this.m_verticalScrollbarDownButton == null) + { + this.m_verticalScrollbarDownButton = new GUIStyle(); + } + if (this.m_ScrollView == null) + { + this.m_ScrollView = new GUIStyle(); + } + this.styles = new Dictionary(StringComparer.OrdinalIgnoreCase); + this.styles["box"] = this.m_box; + this.m_box.name = "box"; + this.styles["button"] = this.m_button; + this.m_button.name = "button"; + this.styles["toggle"] = this.m_toggle; + this.m_toggle.name = "toggle"; + this.styles["label"] = this.m_label; + this.m_label.name = "label"; + this.styles["window"] = this.m_window; + this.m_window.name = "window"; + this.styles["textfield"] = this.m_textField; + this.m_textField.name = "textfield"; + this.styles["textarea"] = this.m_textArea; + this.m_textArea.name = "textarea"; + this.styles["horizontalslider"] = this.m_horizontalSlider; + this.m_horizontalSlider.name = "horizontalslider"; + this.styles["horizontalsliderthumb"] = this.m_horizontalSliderThumb; + this.m_horizontalSliderThumb.name = "horizontalsliderthumb"; + this.styles["verticalslider"] = this.m_verticalSlider; + this.m_verticalSlider.name = "verticalslider"; + this.styles["verticalsliderthumb"] = this.m_verticalSliderThumb; + this.m_verticalSliderThumb.name = "verticalsliderthumb"; + this.styles["horizontalscrollbar"] = this.m_horizontalScrollbar; + this.m_horizontalScrollbar.name = "horizontalscrollbar"; + this.styles["horizontalscrollbarthumb"] = this.m_horizontalScrollbarThumb; + this.m_horizontalScrollbarThumb.name = "horizontalscrollbarthumb"; + this.styles["horizontalscrollbarleftbutton"] = this.m_horizontalScrollbarLeftButton; + this.m_horizontalScrollbarLeftButton.name = "horizontalscrollbarleftbutton"; + this.styles["horizontalscrollbarrightbutton"] = this.m_horizontalScrollbarRightButton; + this.m_horizontalScrollbarRightButton.name = "horizontalscrollbarrightbutton"; + this.styles["verticalscrollbar"] = this.m_verticalScrollbar; + this.m_verticalScrollbar.name = "verticalscrollbar"; + this.styles["verticalscrollbarthumb"] = this.m_verticalScrollbarThumb; + this.m_verticalScrollbarThumb.name = "verticalscrollbarthumb"; + this.styles["verticalscrollbarupbutton"] = this.m_verticalScrollbarUpButton; + this.m_verticalScrollbarUpButton.name = "verticalscrollbarupbutton"; + this.styles["verticalscrollbardownbutton"] = this.m_verticalScrollbarDownButton; + this.m_verticalScrollbarDownButton.name = "verticalscrollbardownbutton"; + this.styles["scrollview"] = this.m_ScrollView; + this.m_ScrollView.name = "scrollview"; + if (this.m_CustomStyles != null) + { + for (int i = 0; i < this.m_CustomStyles.Length; i++) + { + if (this.m_CustomStyles[i] != null) + { + this.styles[this.m_CustomStyles[i].name] = this.m_CustomStyles[i]; + } + } + } + GUISkin.error.stretchHeight = true; + GUISkin.error.normal.textColor = Color.red; + } + public GUIStyle GetStyle(string styleName) + { + GUIStyle gUIStyle = this.FindStyle(styleName); + if (gUIStyle != null) + { + return gUIStyle; + } + Debug.LogWarning(string.Concat(new object[] + { + "Unable to find style '", + styleName, + "' in skin '", + base.name, + "' ", + Event.current.type + })); + return GUISkin.error; + } + public GUIStyle FindStyle(string styleName) + { + if (this == null) + { + Debug.LogError("GUISkin is NULL"); + return null; + } + if (this.styles == null) + { + this.BuildStyleCache(); + } + GUIStyle result; + if (this.styles.TryGetValue(styleName, out result)) + { + return result; + } + return null; + } + internal void MakeCurrent() + { + GUISkin.current = this; + GUIStyle.SetDefaultFont(this.font); + if (GUISkin.m_SkinChanged != null) + { + GUISkin.m_SkinChanged(); + } + } + public IEnumerator GetEnumerator() + { + if (this.styles == null) + { + this.BuildStyleCache(); + } + return this.styles.Values.GetEnumerator(); + } + } +} diff --git a/UnityEngine/UnityEngine/GUIStateObjects.cs b/UnityEngine/UnityEngine/GUIStateObjects.cs new file mode 100644 index 00000000..cc9bf072 --- /dev/null +++ b/UnityEngine/UnityEngine/GUIStateObjects.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Security; +namespace UnityEngine +{ + internal class GUIStateObjects + { + private static Dictionary s_StateCache = new Dictionary(); + [SecuritySafeCritical] + internal static object GetStateObject(Type t, int controlID) + { + object obj; + if (!GUIStateObjects.s_StateCache.TryGetValue(controlID, out obj) || obj.GetType() != t) + { + obj = Activator.CreateInstance(t); + GUIStateObjects.s_StateCache[controlID] = obj; + } + return obj; + } + internal static object QueryStateObject(Type t, int controlID) + { + object obj = GUIStateObjects.s_StateCache[controlID]; + if (t.IsInstanceOfType(obj)) + { + return obj; + } + return null; + } + } +} diff --git a/UnityEngine/UnityEngine/GUIStyle.cs b/UnityEngine/UnityEngine/GUIStyle.cs new file mode 100644 index 00000000..077699cb --- /dev/null +++ b/UnityEngine/UnityEngine/GUIStyle.cs @@ -0,0 +1,707 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class GUIStyle + { + [NotRenamed] + [NonSerialized] + internal IntPtr m_Ptr; + [NonSerialized] + private GUIStyleState m_Normal; + [NonSerialized] + private GUIStyleState m_Hover; + [NonSerialized] + private GUIStyleState m_Active; + [NonSerialized] + private GUIStyleState m_Focused; + [NonSerialized] + private GUIStyleState m_OnNormal; + [NonSerialized] + private GUIStyleState m_OnHover; + [NonSerialized] + private GUIStyleState m_OnActive; + [NonSerialized] + private GUIStyleState m_OnFocused; + [NonSerialized] + private RectOffset m_Border; + [NonSerialized] + private RectOffset m_Padding; + [NonSerialized] + private RectOffset m_Margin; + [NonSerialized] + private RectOffset m_Overflow; + [NonSerialized] + private Font m_FontInternal; + internal static bool showKeyboardFocus = true; + private static GUIStyle s_None; + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public GUIStyleState normal + { + get + { + if (this.m_Normal == null) + { + this.m_Normal = new GUIStyleState(this, this.GetStyleStatePtr(0)); + } + return this.m_Normal; + } + set + { + this.AssignStyleState(0, value.m_Ptr); + } + } + public GUIStyleState hover + { + get + { + if (this.m_Hover == null) + { + this.m_Hover = new GUIStyleState(this, this.GetStyleStatePtr(1)); + } + return this.m_Hover; + } + set + { + this.AssignStyleState(1, value.m_Ptr); + } + } + public GUIStyleState active + { + get + { + if (this.m_Active == null) + { + this.m_Active = new GUIStyleState(this, this.GetStyleStatePtr(2)); + } + return this.m_Active; + } + set + { + this.AssignStyleState(2, value.m_Ptr); + } + } + public GUIStyleState onNormal + { + get + { + if (this.m_OnNormal == null) + { + this.m_OnNormal = new GUIStyleState(this, this.GetStyleStatePtr(4)); + } + return this.m_OnNormal; + } + set + { + this.AssignStyleState(4, value.m_Ptr); + } + } + public GUIStyleState onHover + { + get + { + if (this.m_OnHover == null) + { + this.m_OnHover = new GUIStyleState(this, this.GetStyleStatePtr(5)); + } + return this.m_OnHover; + } + set + { + this.AssignStyleState(5, value.m_Ptr); + } + } + public GUIStyleState onActive + { + get + { + if (this.m_OnActive == null) + { + this.m_OnActive = new GUIStyleState(this, this.GetStyleStatePtr(6)); + } + return this.m_OnActive; + } + set + { + this.AssignStyleState(6, value.m_Ptr); + } + } + public GUIStyleState focused + { + get + { + if (this.m_Focused == null) + { + this.m_Focused = new GUIStyleState(this, this.GetStyleStatePtr(3)); + } + return this.m_Focused; + } + set + { + this.AssignStyleState(3, value.m_Ptr); + } + } + public GUIStyleState onFocused + { + get + { + if (this.m_OnFocused == null) + { + this.m_OnFocused = new GUIStyleState(this, this.GetStyleStatePtr(7)); + } + return this.m_OnFocused; + } + set + { + this.AssignStyleState(7, value.m_Ptr); + } + } + public RectOffset border + { + get + { + if (this.m_Border == null) + { + this.m_Border = new RectOffset(this, this.GetRectOffsetPtr(0)); + } + return this.m_Border; + } + set + { + this.AssignRectOffset(0, value.m_Ptr); + } + } + public RectOffset margin + { + get + { + if (this.m_Margin == null) + { + this.m_Margin = new RectOffset(this, this.GetRectOffsetPtr(1)); + } + return this.m_Margin; + } + set + { + this.AssignRectOffset(1, value.m_Ptr); + } + } + public RectOffset padding + { + get + { + if (this.m_Padding == null) + { + this.m_Padding = new RectOffset(this, this.GetRectOffsetPtr(2)); + } + return this.m_Padding; + } + set + { + this.AssignRectOffset(2, value.m_Ptr); + } + } + public RectOffset overflow + { + get + { + if (this.m_Overflow == null) + { + this.m_Overflow = new RectOffset(this, this.GetRectOffsetPtr(3)); + } + return this.m_Overflow; + } + set + { + this.AssignRectOffset(3, value.m_Ptr); + } + } + public extern ImagePosition imagePosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextAnchor alignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool wordWrap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextClipping clipping + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 contentOffset + { + get + { + Vector2 result; + this.INTERNAL_get_contentOffset(out result); + return result; + } + set + { + this.INTERNAL_set_contentOffset(ref value); + } + } + [Obsolete("Don't use clipOffset - put things inside begingroup instead. This functionality will be removed in a later version.")] + public Vector2 clipOffset + { + get + { + return this.Internal_clipOffset; + } + set + { + this.Internal_clipOffset = value; + } + } + internal Vector2 Internal_clipOffset + { + get + { + Vector2 result; + this.INTERNAL_get_Internal_clipOffset(out result); + return result; + } + set + { + this.INTERNAL_set_Internal_clipOffset(ref value); + } + } + public extern float fixedWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float fixedHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool stretchWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool stretchHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Font font + { + get + { + return this.GetFontInternal(); + } + set + { + this.SetFontInternal(value); + this.m_FontInternal = value; + } + } + public extern int fontSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FontStyle fontStyle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool richText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public float lineHeight + { + get + { + return Mathf.Round(GUIStyle.Internal_GetLineHeight(this.m_Ptr)); + } + } + public static GUIStyle none + { + get + { + if (GUIStyle.s_None == null) + { + GUIStyle.s_None = new GUIStyle(); + } + return GUIStyle.s_None; + } + } + public bool isHeightDependantOnWidth + { + get + { + return this.fixedHeight == 0f && this.wordWrap && this.imagePosition != ImagePosition.ImageOnly; + } + } + public GUIStyle() + { + this.Init(); + } + public GUIStyle(GUIStyle other) + { + this.InitCopy(other); + } + ~GUIStyle() + { + this.Cleanup(); + } + internal void CreateObjectReferences() + { + this.m_FontInternal = this.GetFontInternal(); + this.normal.RefreshAssetReference(); + this.hover.RefreshAssetReference(); + this.active.RefreshAssetReference(); + this.focused.RefreshAssetReference(); + this.onNormal.RefreshAssetReference(); + this.onHover.RefreshAssetReference(); + this.onActive.RefreshAssetReference(); + this.onFocused.RefreshAssetReference(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InitCopy(GUIStyle other); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern IntPtr GetStyleStatePtr(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void AssignStyleState(int idx, IntPtr srcStyleState); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern IntPtr GetRectOffsetPtr(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void AssignRectOffset(int idx, IntPtr srcRectOffset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_contentOffset(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_contentOffset(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_Internal_clipOffset(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_Internal_clipOffset(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float Internal_GetLineHeight(IntPtr target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFontInternal(Font value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Font GetFontInternal(); + private static void Internal_Draw(IntPtr target, Rect position, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) + { + Internal_DrawArguments internal_DrawArguments = default(Internal_DrawArguments); + internal_DrawArguments.target = target; + internal_DrawArguments.position = position; + internal_DrawArguments.isHover = ((!isHover) ? 0 : 1); + internal_DrawArguments.isActive = ((!isActive) ? 0 : 1); + internal_DrawArguments.on = ((!on) ? 0 : 1); + internal_DrawArguments.hasKeyboardFocus = ((!hasKeyboardFocus) ? 0 : 1); + GUIStyle.Internal_Draw(content, ref internal_DrawArguments); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Draw(GUIContent content, ref Internal_DrawArguments arguments); + public void Draw(Rect position, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event"); + return; + } + GUIStyle.Internal_Draw(this.m_Ptr, position, GUIContent.none, isHover, isActive, on, hasKeyboardFocus); + } + public void Draw(Rect position, string text, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event"); + return; + } + GUIStyle.Internal_Draw(this.m_Ptr, position, GUIContent.Temp(text), isHover, isActive, on, hasKeyboardFocus); + } + public void Draw(Rect position, Texture image, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event"); + return; + } + GUIStyle.Internal_Draw(this.m_Ptr, position, GUIContent.Temp(image), isHover, isActive, on, hasKeyboardFocus); + } + public void Draw(Rect position, GUIContent content, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event"); + return; + } + GUIStyle.Internal_Draw(this.m_Ptr, position, content, isHover, isActive, on, hasKeyboardFocus); + } + [ExcludeFromDocs] + public void Draw(Rect position, GUIContent content, int controlID) + { + bool on = false; + this.Draw(position, content, controlID, on); + } + public void Draw(Rect position, GUIContent content, int controlID, [DefaultValue("false")] bool on) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event."); + return; + } + if (content != null) + { + GUIStyle.Internal_Draw2(this.m_Ptr, position, content, controlID, on); + } + else + { + Debug.LogError("Style.Draw may not be called with GUIContent that is null."); + } + } + private static void Internal_Draw2(IntPtr style, Rect position, GUIContent content, int controlID, bool on) + { + GUIStyle.INTERNAL_CALL_Internal_Draw2(style, ref position, content, controlID, on); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Draw2(IntPtr style, ref Rect position, GUIContent content, int controlID, bool on); + internal void DrawPrefixLabel(Rect position, GUIContent content, int controlID) + { + if (content != null) + { + GUIStyle.Internal_DrawPrefixLabel(this.m_Ptr, position, content, controlID, false); + } + else + { + Debug.LogError("Style.DrawPrefixLabel may not be called with GUIContent that is null."); + } + } + private static void Internal_DrawPrefixLabel(IntPtr style, Rect position, GUIContent content, int controlID, bool on) + { + GUIStyle.INTERNAL_CALL_Internal_DrawPrefixLabel(style, ref position, content, controlID, on); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawPrefixLabel(IntPtr style, ref Rect position, GUIContent content, int controlID, bool on); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float Internal_GetCursorFlashOffset(); + private static void Internal_DrawCursor(IntPtr target, Rect position, GUIContent content, int pos, Color cursorColor) + { + GUIStyle.INTERNAL_CALL_Internal_DrawCursor(target, ref position, content, pos, ref cursorColor); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawCursor(IntPtr target, ref Rect position, GUIContent content, int pos, ref Color cursorColor); + public void DrawCursor(Rect position, GUIContent content, int controlID, int Character) + { + Event current = Event.current; + if (current.type == EventType.Repaint) + { + Color cursorColor = new Color(0f, 0f, 0f, 0f); + float cursorFlashSpeed = GUI.skin.settings.cursorFlashSpeed; + float num = (Time.realtimeSinceStartup - GUIStyle.Internal_GetCursorFlashOffset()) % cursorFlashSpeed / cursorFlashSpeed; + if (cursorFlashSpeed == 0f || num < 0.5f) + { + cursorColor = GUI.skin.settings.cursorColor; + } + GUIStyle.Internal_DrawCursor(this.m_Ptr, position, content, Character, cursorColor); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawWithTextSelection(GUIContent content, ref Internal_DrawWithTextSelectionArguments arguments); + internal void DrawWithTextSelection(Rect position, GUIContent content, int controlID, int firstSelectedCharacter, int lastSelectedCharacter, bool drawSelectionAsComposition) + { + if (Event.current.type != EventType.Repaint) + { + Debug.LogError("Style.Draw may not be called if it is not a repaint event"); + return; + } + Event current = Event.current; + Color cursorColor = new Color(0f, 0f, 0f, 0f); + float cursorFlashSpeed = GUI.skin.settings.cursorFlashSpeed; + float num = (Time.realtimeSinceStartup - GUIStyle.Internal_GetCursorFlashOffset()) % cursorFlashSpeed / cursorFlashSpeed; + if (cursorFlashSpeed == 0f || num < 0.5f) + { + cursorColor = GUI.skin.settings.cursorColor; + } + Internal_DrawWithTextSelectionArguments internal_DrawWithTextSelectionArguments = default(Internal_DrawWithTextSelectionArguments); + internal_DrawWithTextSelectionArguments.target = this.m_Ptr; + internal_DrawWithTextSelectionArguments.position = position; + internal_DrawWithTextSelectionArguments.firstPos = firstSelectedCharacter; + internal_DrawWithTextSelectionArguments.lastPos = lastSelectedCharacter; + internal_DrawWithTextSelectionArguments.cursorColor = cursorColor; + internal_DrawWithTextSelectionArguments.selectionColor = GUI.skin.settings.selectionColor; + internal_DrawWithTextSelectionArguments.isHover = ((!position.Contains(current.mousePosition)) ? 0 : 1); + internal_DrawWithTextSelectionArguments.isActive = ((controlID != GUIUtility.hotControl) ? 0 : 1); + internal_DrawWithTextSelectionArguments.on = 0; + internal_DrawWithTextSelectionArguments.hasKeyboardFocus = ((controlID != GUIUtility.keyboardControl || !GUIStyle.showKeyboardFocus) ? 0 : 1); + internal_DrawWithTextSelectionArguments.drawSelectionAsComposition = ((!drawSelectionAsComposition) ? 0 : 1); + GUIStyle.Internal_DrawWithTextSelection(content, ref internal_DrawWithTextSelectionArguments); + } + public void DrawWithTextSelection(Rect position, GUIContent content, int controlID, int firstSelectedCharacter, int lastSelectedCharacter) + { + this.DrawWithTextSelection(position, content, controlID, firstSelectedCharacter, lastSelectedCharacter, false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetDefaultFont(Font font); + public Vector2 GetCursorPixelPosition(Rect position, GUIContent content, int cursorStringIndex) + { + Vector2 result; + GUIStyle.Internal_GetCursorPixelPosition(this.m_Ptr, position, content, cursorStringIndex, out result); + return result; + } + internal static void Internal_GetCursorPixelPosition(IntPtr target, Rect position, GUIContent content, int cursorStringIndex, out Vector2 ret) + { + GUIStyle.INTERNAL_CALL_Internal_GetCursorPixelPosition(target, ref position, content, cursorStringIndex, out ret); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_GetCursorPixelPosition(IntPtr target, ref Rect position, GUIContent content, int cursorStringIndex, out Vector2 ret); + public int GetCursorStringIndex(Rect position, GUIContent content, Vector2 cursorPixelPosition) + { + return GUIStyle.Internal_GetCursorStringIndex(this.m_Ptr, position, content, cursorPixelPosition); + } + internal static int Internal_GetCursorStringIndex(IntPtr target, Rect position, GUIContent content, Vector2 cursorPixelPosition) + { + return GUIStyle.INTERNAL_CALL_Internal_GetCursorStringIndex(target, ref position, content, ref cursorPixelPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_Internal_GetCursorStringIndex(IntPtr target, ref Rect position, GUIContent content, ref Vector2 cursorPixelPosition); + internal int GetNumCharactersThatFitWithinWidth(string text, float width) + { + return GUIStyle.Internal_GetNumCharactersThatFitWithinWidth(this.m_Ptr, text, width); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int Internal_GetNumCharactersThatFitWithinWidth(IntPtr target, string text, float width); + public Vector2 CalcSize(GUIContent content) + { + Vector2 result; + GUIStyle.Internal_CalcSize(this.m_Ptr, content, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Internal_CalcSize(IntPtr target, GUIContent content, out Vector2 ret); + public Vector2 CalcScreenSize(Vector2 contentSize) + { + return new Vector2((this.fixedWidth == 0f) ? Mathf.Ceil(contentSize.x + (float)this.padding.left + (float)this.padding.right) : this.fixedWidth, (this.fixedHeight == 0f) ? Mathf.Ceil(contentSize.y + (float)this.padding.top + (float)this.padding.bottom) : this.fixedHeight); + } + public float CalcHeight(GUIContent content, float width) + { + return GUIStyle.Internal_CalcHeight(this.m_Ptr, content, width); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float Internal_CalcHeight(IntPtr target, GUIContent content, float width); + public void CalcMinMaxWidth(GUIContent content, out float minWidth, out float maxWidth) + { + GUIStyle.Internal_CalcMinMaxWidth(this.m_Ptr, content, out minWidth, out maxWidth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CalcMinMaxWidth(IntPtr target, GUIContent content, out float minWidth, out float maxWidth); + public override string ToString() + { + return UnityString.Format("GUIStyle '{0}'", new object[] + { + this.name + }); + } + public static implicit operator GUIStyle(string str) + { + if (GUISkin.current == null) + { + Debug.LogError("Unable to use a named GUIStyle without a current skin. Most likely you need to move your GUIStyle initialization code to OnGUI"); + return GUISkin.error; + } + return GUISkin.current.GetStyle(str); + } + } +} diff --git a/UnityEngine/UnityEngine/GUIStyleState.cs b/UnityEngine/UnityEngine/GUIStyleState.cs new file mode 100644 index 00000000..3af244f3 --- /dev/null +++ b/UnityEngine/UnityEngine/GUIStyleState.cs @@ -0,0 +1,81 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class GUIStyleState + { + [NotRenamed] + [NonSerialized] + internal IntPtr m_Ptr; + private GUIStyle m_SourceStyle; + [NonSerialized] + private Texture2D m_BackgroundInternal; + public Texture2D background + { + get + { + return this.GetBackgroundInternal(); + } + set + { + this.SetBackgroundInternal(value); + this.m_BackgroundInternal = value; + } + } + public Color textColor + { + get + { + Color result; + this.INTERNAL_get_textColor(out result); + return result; + } + set + { + this.INTERNAL_set_textColor(ref value); + } + } + public GUIStyleState() + { + this.Init(); + } + internal GUIStyleState(GUIStyle sourceStyle, IntPtr source) + { + this.m_SourceStyle = sourceStyle; + this.m_Ptr = source; + this.RefreshAssetReference(); + } + internal void RefreshAssetReference() + { + this.m_BackgroundInternal = this.GetBackgroundInternal(); + } + ~GUIStyleState() + { + if (this.m_SourceStyle == null) + { + this.Cleanup(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetBackgroundInternal(Texture2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Texture2D GetBackgroundInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_textColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_textColor(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/GUIText.cs b/UnityEngine/UnityEngine/GUIText.cs new file mode 100644 index 00000000..059cf005 --- /dev/null +++ b/UnityEngine/UnityEngine/GUIText.cs @@ -0,0 +1,140 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class GUIText : GUIElement + { + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 pixelOffset + { + get + { + Vector2 result; + this.Internal_GetPixelOffset(out result); + return result; + } + set + { + this.Internal_SetPixelOffset(value); + } + } + public extern Font font + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextAlignment alignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextAnchor anchor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lineSpacing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float tabSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int fontSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FontStyle fontStyle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool richText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_GetPixelOffset(out Vector2 output); + private void Internal_SetPixelOffset(Vector2 p) + { + GUIText.INTERNAL_CALL_Internal_SetPixelOffset(this, ref p); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetPixelOffset(GUIText self, ref Vector2 p); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/GUITexture.cs b/UnityEngine/UnityEngine/GUITexture.cs new file mode 100644 index 00000000..f4af3df8 --- /dev/null +++ b/UnityEngine/UnityEngine/GUITexture.cs @@ -0,0 +1,64 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class GUITexture : GUIElement + { + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + public extern Texture texture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Rect pixelInset + { + get + { + Rect result; + this.INTERNAL_get_pixelInset(out result); + return result; + } + set + { + this.INTERNAL_set_pixelInset(ref value); + } + } + public extern RectOffset border + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_pixelInset(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_pixelInset(ref Rect value); + } +} diff --git a/UnityEngine/UnityEngine/GUIUtility.cs b/UnityEngine/UnityEngine/GUIUtility.cs new file mode 100644 index 00000000..b3fec09d --- /dev/null +++ b/UnityEngine/UnityEngine/GUIUtility.cs @@ -0,0 +1,237 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class GUIUtility + { + [NotRenamed] + internal static int s_SkinMode; + [NotRenamed] + internal static int s_OriginalID; + internal static Vector2 s_EditorScreenPointOffset = Vector2.zero; + internal static bool s_HasKeyboardFocus = false; + public static int hotControl + { + get + { + return GUIUtility.Internal_GetHotControl(); + } + set + { + GUIUtility.Internal_SetHotControl(value); + } + } + public static extern int keyboardControl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern string systemCopyBuffer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool mouseUsed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool hasModalWindow + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern bool textFieldInput + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static int GetControlID(FocusType focus) + { + return GUIUtility.GetControlID(0, focus); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetControlID(int hint, FocusType focus); + public static int GetControlID(GUIContent contents, FocusType focus) + { + return GUIUtility.GetControlID(contents.hash, focus); + } + public static int GetControlID(FocusType focus, Rect position) + { + return GUIUtility.Internal_GetNextControlID2(0, focus, position); + } + public static int GetControlID(int hint, FocusType focus, Rect position) + { + return GUIUtility.Internal_GetNextControlID2(hint, focus, position); + } + public static int GetControlID(GUIContent contents, FocusType focus, Rect position) + { + return GUIUtility.Internal_GetNextControlID2(contents.hash, focus, position); + } + private static int Internal_GetNextControlID2(int hint, FocusType focusType, Rect rect) + { + return GUIUtility.INTERNAL_CALL_Internal_GetNextControlID2(hint, focusType, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_Internal_GetNextControlID2(int hint, FocusType focusType, ref Rect rect); + public static object GetStateObject(Type t, int controlID) + { + return GUIStateObjects.GetStateObject(t, controlID); + } + public static object QueryStateObject(Type t, int controlID) + { + return GUIStateObjects.QueryStateObject(t, controlID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetPermanentControlID(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetHotControl(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetHotControl(int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateUndoName(); + public static void ExitGUI() + { + throw new ExitGUIException(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetDidGUIWindowsEatLastEvent(bool value); + internal static GUISkin GetDefaultSkin() + { + return GUIUtility.Internal_GetDefaultSkin(GUIUtility.s_SkinMode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GUISkin Internal_GetDefaultSkin(int skinMode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Object Internal_GetBuiltinSkin(int skin); + internal static GUISkin GetBuiltinSkin(int skin) + { + return GUIUtility.Internal_GetBuiltinSkin(skin) as GUISkin; + } + internal static void BeginGUI(int skinMode, int instanceID, int useGUILayout) + { + GUIUtility.s_SkinMode = skinMode; + GUIUtility.s_OriginalID = instanceID; + GUI.skin = null; + if (useGUILayout != 0) + { + GUILayoutUtility.SelectIDList(instanceID, false); + GUILayoutUtility.Begin(instanceID); + } + GUI.changed = false; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_ExitGUI(); + internal static void EndGUI(int layoutType) + { + try + { + if (Event.current.type == EventType.Layout) + { + switch (layoutType) + { + case 1: + GUILayoutUtility.Layout(); + break; + case 2: + GUILayoutUtility.LayoutFromEditorWindow(); + break; + } + } + GUILayoutUtility.SelectIDList(GUIUtility.s_OriginalID, false); + GUIContent.ClearStaticCache(); + } + finally + { + GUIUtility.Internal_ExitGUI(); + } + } + internal static bool EndGUIFromException(Exception exception) + { + if (exception == null) + { + return false; + } + if (!(exception is ExitGUIException) && !(exception.InnerException is ExitGUIException)) + { + return false; + } + GUIUtility.Internal_ExitGUI(); + return true; + } + internal static void CheckOnGUI() + { + if (GUIUtility.Internal_GetGUIDepth() <= 0) + { + throw new ArgumentException("You can only call GUI functions from inside OnGUI."); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int Internal_GetGUIDepth(); + public static Vector2 GUIToScreenPoint(Vector2 guiPoint) + { + return GUIClip.Unclip(guiPoint) + GUIUtility.s_EditorScreenPointOffset; + } + internal static Rect GUIToScreenRect(Rect guiRect) + { + Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(guiRect.x, guiRect.y)); + guiRect.x = vector.x; + guiRect.y = vector.y; + return guiRect; + } + public static Vector2 ScreenToGUIPoint(Vector2 screenPoint) + { + return GUIClip.Clip(screenPoint) - GUIUtility.s_EditorScreenPointOffset; + } + public static Rect ScreenToGUIRect(Rect screenRect) + { + Vector2 vector = GUIUtility.ScreenToGUIPoint(new Vector2(screenRect.x, screenRect.y)); + screenRect.x = vector.x; + screenRect.y = vector.y; + return screenRect; + } + public static void RotateAroundPivot(float angle, Vector2 pivotPoint) + { + Matrix4x4 matrix = GUI.matrix; + GUI.matrix = Matrix4x4.identity; + Vector2 vector = GUIClip.Unclip(pivotPoint); + Matrix4x4 lhs = Matrix4x4.TRS(vector, Quaternion.Euler(0f, 0f, angle), Vector3.one) * Matrix4x4.TRS(-vector, Quaternion.identity, Vector3.one); + GUI.matrix = lhs * matrix; + } + public static void ScaleAroundPivot(Vector2 scale, Vector2 pivotPoint) + { + Matrix4x4 matrix = GUI.matrix; + Vector2 vector = GUIClip.Unclip(pivotPoint); + Matrix4x4 lhs = Matrix4x4.TRS(vector, Quaternion.identity, new Vector3(scale.x, scale.y, 1f)) * Matrix4x4.TRS(-vector, Quaternion.identity, Vector3.one); + GUI.matrix = lhs * matrix; + } + } +} diff --git a/UnityEngine/UnityEngine/GUIWordWrapSizer.cs b/UnityEngine/UnityEngine/GUIWordWrapSizer.cs new file mode 100644 index 00000000..dc0534fe --- /dev/null +++ b/UnityEngine/UnityEngine/GUIWordWrapSizer.cs @@ -0,0 +1,57 @@ +using System; +namespace UnityEngine +{ + internal sealed class GUIWordWrapSizer : GUILayoutEntry + { + private GUIContent content; + private float forcedMinHeight; + private float forcedMaxHeight; + public GUIWordWrapSizer(GUIStyle _style, GUIContent _content, GUILayoutOption[] options) : base(0f, 0f, 0f, 0f, _style) + { + this.content = new GUIContent(_content); + base.ApplyOptions(options); + this.forcedMinHeight = this.minHeight; + this.forcedMaxHeight = this.maxHeight; + } + public override void CalcWidth() + { + if (this.minWidth == 0f || this.maxWidth == 0f) + { + float minWidth; + float maxWidth; + base.style.CalcMinMaxWidth(this.content, out minWidth, out maxWidth); + if (this.minWidth == 0f) + { + this.minWidth = minWidth; + } + if (this.maxWidth == 0f) + { + this.maxWidth = maxWidth; + } + } + } + public override void CalcHeight() + { + if (this.forcedMinHeight == 0f || this.forcedMaxHeight == 0f) + { + float num = base.style.CalcHeight(this.content, this.rect.width); + if (this.forcedMinHeight == 0f) + { + this.minHeight = num; + } + else + { + this.minHeight = this.forcedMinHeight; + } + if (this.forcedMaxHeight == 0f) + { + this.maxHeight = num; + } + else + { + this.maxHeight = this.forcedMaxHeight; + } + } + } + } +} diff --git a/UnityEngine/UnityEngine/GameObject.cs b/UnityEngine/UnityEngine/GameObject.cs new file mode 100644 index 00000000..bce3731f --- /dev/null +++ b/UnityEngine/UnityEngine/GameObject.cs @@ -0,0 +1,458 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEngine +{ + public sealed class GameObject : Object + { + public extern bool isStatic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool isStaticBatchable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Transform transform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Rigidbody rigidbody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Rigidbody2D rigidbody2D + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Camera camera + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Light light + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Animation animation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ConstantForce constantForce + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Renderer renderer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AudioSource audio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern GUIText guiText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern NetworkView networkView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Please use guiTexture instead")] + public extern GUIElement guiElement + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern GUITexture guiTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Collider collider + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Collider2D collider2D + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern HingeJoint hingeJoint + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ParticleEmitter particleEmitter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ParticleSystem particleSystem + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int layer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.")] + public extern bool active + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool activeSelf + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool activeInHierarchy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string tag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public GameObject gameObject + { + get + { + return this; + } + } + public GameObject(string name) + { + GameObject.Internal_CreateGameObject(this, name); + } + public GameObject() + { + GameObject.Internal_CreateGameObject(this, null); + } + public GameObject(string name, params Type[] components) + { + GameObject.Internal_CreateGameObject(this, name); + for (int i = 0; i < components.Length; i++) + { + Type componentType = components[i]; + this.AddComponent(componentType); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SampleAnimation(AnimationClip animation, float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject CreatePrimitive(PrimitiveType type); + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Component GetComponent(Type type); + public T GetComponent() where T : Component + { + return this.GetComponent(typeof(T)) as T; + } + public Component GetComponent(string type) + { + return this.GetComponentByName(type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Component GetComponentByName(string type); + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component GetComponentInChildren(Type type) + { + if (this.activeInHierarchy) + { + Component component = this.GetComponent(type); + if (component != null) + { + return component; + } + } + Transform transform = this.transform; + if (transform != null) + { + foreach (Transform transform2 in transform) + { + Component componentInChildren = transform2.gameObject.GetComponentInChildren(type); + if (componentInChildren != null) + { + return componentInChildren; + } + } + } + return null; + } + public T GetComponentInChildren() where T : Component + { + return this.GetComponentInChildren(typeof(T)) as T; + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component GetComponentInParent(Type type) + { + if (this.activeInHierarchy) + { + Component component = this.GetComponent(type); + if (component != null) + { + return component; + } + } + Transform parent = this.transform.parent; + if (parent != null) + { + while (parent != null) + { + if (parent.gameObject.activeInHierarchy) + { + Component component2 = parent.gameObject.GetComponent(type); + if (component2 != null) + { + return component2; + } + } + parent = parent.parent; + } + } + return null; + } + public T GetComponentInParent() where T : Component + { + return this.GetComponentInParent(typeof(T)) as T; + } + public void GetComponentsInParent(bool includeInactive, List results) where T : Component + { + this.GetComponentsForListInternal(typeof(T), typeof(T), true, includeInactive, true, results); + } + [CanConvertToFlash] + public Component[] GetComponents(Type type) + { + return this.GetComponentsInternal(type, false, false, true, false); + } + public T[] GetComponents() where T : Component + { + return (T[])this.GetComponentsInternal(typeof(T), true, false, true, false); + } + public void GetComponents(Type type, List results) + { + this.GetComponentsForListInternal(type, typeof(Component), false, true, false, results); + } + public void GetComponents(List results) where T : Component + { + this.GetComponentsForListInternal(typeof(T), typeof(T), false, true, false, results); + } + [ExcludeFromDocs] + public Component[] GetComponentsInChildren(Type type) + { + bool includeInactive = false; + return this.GetComponentsInChildren(type, includeInactive); + } + public Component[] GetComponentsInChildren(Type type, [DefaultValue("false")] bool includeInactive) + { + return this.GetComponentsInternal(type, false, true, includeInactive, false); + } + public T[] GetComponentsInChildren(bool includeInactive) where T : Component + { + return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, false); + } + public void GetComponentsInChildren(bool includeInactive, List results) where T : Component + { + this.GetComponentsForListInternal(typeof(T), typeof(T), true, includeInactive, false, results); + } + public T[] GetComponentsInChildren() where T : Component + { + return this.GetComponentsInChildren(false); + } + public void GetComponentsInChildren(List results) where T : Component + { + this.GetComponentsInChildren(false, results); + } + [ExcludeFromDocs] + public Component[] GetComponentsInParent(Type type) + { + bool includeInactive = false; + return this.GetComponentsInParent(type, includeInactive); + } + public Component[] GetComponentsInParent(Type type, [DefaultValue("false")] bool includeInactive) + { + return this.GetComponentsInternal(type, false, true, includeInactive, true); + } + public T[] GetComponentsInParent(bool includeInactive) where T : Component + { + return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, true); + } + public T[] GetComponentsInParent() where T : Component + { + return this.GetComponentsInParent(false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetComponentsForListInternal(Type searchType, Type listElementType, bool recursive, bool includeInactive, bool reverse, object resultList); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Component[] GetComponentsInternal(Type type, bool isGenericTypeArray, bool recursive, bool includeInactive, bool reverse); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetActive(bool value); + [Obsolete("gameObject.SetActiveRecursively() is obsolete. Use GameObject.SetActive(), which is now inherited by children."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetActiveRecursively(bool state); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool CompareTag(string tag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject FindGameObjectWithTag(string tag); + public static GameObject FindWithTag(string tag) + { + return GameObject.FindGameObjectWithTag(tag); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject[] FindGameObjectsWithTag(string tag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SendMessageUpwards(string methodName, [DefaultValue("null")] object value, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void SendMessageUpwards(string methodName, object value) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.SendMessageUpwards(methodName, value, options); + } + [ExcludeFromDocs] + public void SendMessageUpwards(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object value = null; + this.SendMessageUpwards(methodName, value, options); + } + public void SendMessageUpwards(string methodName, SendMessageOptions options) + { + this.SendMessageUpwards(methodName, null, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SendMessage(string methodName, [DefaultValue("null")] object value, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void SendMessage(string methodName, object value) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.SendMessage(methodName, value, options); + } + [ExcludeFromDocs] + public void SendMessage(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object value = null; + this.SendMessage(methodName, value, options); + } + public void SendMessage(string methodName, SendMessageOptions options) + { + this.SendMessage(methodName, null, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void BroadcastMessage(string methodName, [DefaultValue("null")] object parameter, [DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); + [ExcludeFromDocs] + public void BroadcastMessage(string methodName, object parameter) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + this.BroadcastMessage(methodName, parameter, options); + } + [ExcludeFromDocs] + public void BroadcastMessage(string methodName) + { + SendMessageOptions options = SendMessageOptions.RequireReceiver; + object parameter = null; + this.BroadcastMessage(methodName, parameter, options); + } + public void BroadcastMessage(string methodName, SendMessageOptions options) + { + this.BroadcastMessage(methodName, null, options); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Component AddComponent(string className); + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component AddComponent(Type componentType) + { + return this.Internal_AddComponentWithType(componentType); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Component Internal_AddComponentWithType(Type componentType); + public T AddComponent() where T : Component + { + return this.AddComponent(typeof(T)) as T; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateGameObject([Writable] GameObject mono, string name); + [Obsolete("gameObject.PlayAnimation is not supported anymore. Use animation.Play"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PlayAnimation(AnimationClip animation); + [Obsolete("gameObject.StopAnimation is not supported anymore. Use animation.Stop"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StopAnimation(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject Find(string name); + } +} diff --git a/UnityEngine/UnityEngine/GeometryUtility.cs b/UnityEngine/UnityEngine/GeometryUtility.cs new file mode 100644 index 00000000..10755455 --- /dev/null +++ b/UnityEngine/UnityEngine/GeometryUtility.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class GeometryUtility + { + public static Plane[] CalculateFrustumPlanes(Camera camera) + { + return GeometryUtility.CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix); + } + public static Plane[] CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix) + { + Plane[] array = new Plane[6]; + GeometryUtility.Internal_ExtractPlanes(array, worldToProjectionMatrix); + return array; + } + private static void Internal_ExtractPlanes(Plane[] planes, Matrix4x4 worldToProjectionMatrix) + { + GeometryUtility.INTERNAL_CALL_Internal_ExtractPlanes(planes, ref worldToProjectionMatrix); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_ExtractPlanes(Plane[] planes, ref Matrix4x4 worldToProjectionMatrix); + public static bool TestPlanesAABB(Plane[] planes, Bounds bounds) + { + return GeometryUtility.INTERNAL_CALL_TestPlanesAABB(planes, ref bounds); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_TestPlanesAABB(Plane[] planes, ref Bounds bounds); + } +} diff --git a/UnityEngine/UnityEngine/Gizmos.cs b/UnityEngine/UnityEngine/Gizmos.cs new file mode 100644 index 00000000..cb6d47a9 --- /dev/null +++ b/UnityEngine/UnityEngine/Gizmos.cs @@ -0,0 +1,133 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Gizmos + { + public static Color color + { + get + { + Color result; + Gizmos.INTERNAL_get_color(out result); + return result; + } + set + { + Gizmos.INTERNAL_set_color(ref value); + } + } + public static Matrix4x4 matrix + { + get + { + Matrix4x4 result; + Gizmos.INTERNAL_get_matrix(out result); + return result; + } + set + { + Gizmos.INTERNAL_set_matrix(ref value); + } + } + public static void DrawRay(Ray r) + { + Gizmos.DrawLine(r.origin, r.origin + r.direction); + } + public static void DrawRay(Vector3 from, Vector3 direction) + { + Gizmos.DrawLine(from, from + direction); + } + public static void DrawLine(Vector3 from, Vector3 to) + { + Gizmos.INTERNAL_CALL_DrawLine(ref from, ref to); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawLine(ref Vector3 from, ref Vector3 to); + public static void DrawWireSphere(Vector3 center, float radius) + { + Gizmos.INTERNAL_CALL_DrawWireSphere(ref center, radius); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawWireSphere(ref Vector3 center, float radius); + public static void DrawSphere(Vector3 center, float radius) + { + Gizmos.INTERNAL_CALL_DrawSphere(ref center, radius); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawSphere(ref Vector3 center, float radius); + public static void DrawWireCube(Vector3 center, Vector3 size) + { + Gizmos.INTERNAL_CALL_DrawWireCube(ref center, ref size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawWireCube(ref Vector3 center, ref Vector3 size); + public static void DrawCube(Vector3 center, Vector3 size) + { + Gizmos.INTERNAL_CALL_DrawCube(ref center, ref size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawCube(ref Vector3 center, ref Vector3 size); + public static void DrawIcon(Vector3 center, string name, [DefaultValue("true")] bool allowScaling) + { + Gizmos.INTERNAL_CALL_DrawIcon(ref center, name, allowScaling); + } + [ExcludeFromDocs] + public static void DrawIcon(Vector3 center, string name) + { + bool allowScaling = true; + Gizmos.INTERNAL_CALL_DrawIcon(ref center, name, allowScaling); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawIcon(ref Vector3 center, string name, bool allowScaling); + [ExcludeFromDocs] + public static void DrawGUITexture(Rect screenRect, Texture texture) + { + Material mat = null; + Gizmos.DrawGUITexture(screenRect, texture, mat); + } + public static void DrawGUITexture(Rect screenRect, Texture texture, [DefaultValue("null")] Material mat) + { + Gizmos.DrawGUITexture(screenRect, texture, 0, 0, 0, 0, mat); + } + public static void DrawGUITexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [DefaultValue("null")] Material mat) + { + Gizmos.INTERNAL_CALL_DrawGUITexture(ref screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); + } + [ExcludeFromDocs] + public static void DrawGUITexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder) + { + Material mat = null; + Gizmos.INTERNAL_CALL_DrawGUITexture(ref screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawGUITexture(ref Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Material mat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_color(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_matrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_matrix(ref Matrix4x4 value); + public static void DrawFrustum(Vector3 center, float fov, float maxRange, float minRange, float aspect) + { + Gizmos.INTERNAL_CALL_DrawFrustum(ref center, fov, maxRange, minRange, aspect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawFrustum(ref Vector3 center, float fov, float maxRange, float minRange, float aspect); + } +} diff --git a/UnityEngine/UnityEngine/Gradient.cs b/UnityEngine/UnityEngine/Gradient.cs new file mode 100644 index 00000000..2c247bc9 --- /dev/null +++ b/UnityEngine/UnityEngine/Gradient.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class Gradient + { + internal IntPtr m_Ptr; + public extern GradientColorKey[] colorKeys + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern GradientAlphaKey[] alphaKeys + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal Color constantColor + { + get + { + Color result; + this.INTERNAL_get_constantColor(out result); + return result; + } + set + { + this.INTERNAL_set_constantColor(ref value); + } + } + public Gradient() + { + this.Init(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + ~Gradient() + { + this.Cleanup(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color Evaluate(float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_constantColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_constantColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetKeys(GradientColorKey[] colorKeys, GradientAlphaKey[] alphaKeys); + } +} diff --git a/UnityEngine/UnityEngine/GradientAlphaKey.cs b/UnityEngine/UnityEngine/GradientAlphaKey.cs new file mode 100644 index 00000000..106a9d27 --- /dev/null +++ b/UnityEngine/UnityEngine/GradientAlphaKey.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public struct GradientAlphaKey + { + public float alpha; + public float time; + public GradientAlphaKey(float alpha, float time) + { + this.alpha = alpha; + this.time = time; + } + } +} diff --git a/UnityEngine/UnityEngine/GradientColorKey.cs b/UnityEngine/UnityEngine/GradientColorKey.cs new file mode 100644 index 00000000..9cd64d06 --- /dev/null +++ b/UnityEngine/UnityEngine/GradientColorKey.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public struct GradientColorKey + { + public Color color; + public float time; + public GradientColorKey(Color col, float time) + { + this.color = col; + this.time = time; + } + } +} diff --git a/UnityEngine/UnityEngine/Graphics.cs b/UnityEngine/UnityEngine/Graphics.cs new file mode 100644 index 00000000..6a690c8f --- /dev/null +++ b/UnityEngine/UnityEngine/Graphics.cs @@ -0,0 +1,377 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Graphics + { + public static RenderBuffer activeColorBuffer + { + get + { + RenderBuffer result; + Graphics.GetActiveColorBuffer(out result); + return result; + } + } + public static RenderBuffer activeDepthBuffer + { + get + { + RenderBuffer result; + Graphics.GetActiveDepthBuffer(out result); + return result; + } + } + [Obsolete("Use SystemInfo.graphicsDeviceName instead.")] + public static string deviceName + { + get + { + return SystemInfo.graphicsDeviceName; + } + } + [Obsolete("Use SystemInfo.graphicsDeviceVendor instead.")] + public static string deviceVendor + { + get + { + return SystemInfo.graphicsDeviceVendor; + } + } + [Obsolete("Use SystemInfo.graphicsDeviceVersion instead.")] + public static string deviceVersion + { + get + { + return SystemInfo.graphicsDeviceVersion; + } + } + [Obsolete("Use SystemInfo.supportsVertexPrograms instead.")] + public static bool supportsVertexProgram + { + get + { + return SystemInfo.supportsVertexPrograms; + } + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex) + { + MaterialPropertyBlock properties = null; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera) + { + MaterialPropertyBlock properties = null; + int submeshIndex = 0; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer) + { + MaterialPropertyBlock properties = null; + int submeshIndex = 0; + Camera camera = null; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + } + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, [DefaultValue("null")] Camera camera, [DefaultValue("0")] int submeshIndex, [DefaultValue("null")] MaterialPropertyBlock properties) + { + Internal_DrawMeshTRArguments internal_DrawMeshTRArguments = default(Internal_DrawMeshTRArguments); + internal_DrawMeshTRArguments.position = position; + internal_DrawMeshTRArguments.rotation = rotation; + internal_DrawMeshTRArguments.layer = layer; + internal_DrawMeshTRArguments.submeshIndex = submeshIndex; + internal_DrawMeshTRArguments.castShadows = 1; + internal_DrawMeshTRArguments.receiveShadows = 1; + Graphics.Internal_DrawMeshTR(ref internal_DrawMeshTRArguments, properties, material, mesh, camera); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex) + { + MaterialPropertyBlock properties = null; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera) + { + MaterialPropertyBlock properties = null; + int submeshIndex = 0; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer) + { + MaterialPropertyBlock properties = null; + int submeshIndex = 0; + Camera camera = null; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + } + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, [DefaultValue("null")] Camera camera, [DefaultValue("0")] int submeshIndex, [DefaultValue("null")] MaterialPropertyBlock properties) + { + Internal_DrawMeshMatrixArguments internal_DrawMeshMatrixArguments = default(Internal_DrawMeshMatrixArguments); + internal_DrawMeshMatrixArguments.matrix = matrix; + internal_DrawMeshMatrixArguments.layer = layer; + internal_DrawMeshMatrixArguments.submeshIndex = submeshIndex; + internal_DrawMeshMatrixArguments.castShadows = 1; + internal_DrawMeshMatrixArguments.receiveShadows = 1; + Graphics.Internal_DrawMeshMatrix(ref internal_DrawMeshMatrixArguments, properties, material, mesh, camera); + } + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) + { + Internal_DrawMeshTRArguments internal_DrawMeshTRArguments = default(Internal_DrawMeshTRArguments); + internal_DrawMeshTRArguments.position = position; + internal_DrawMeshTRArguments.rotation = rotation; + internal_DrawMeshTRArguments.layer = layer; + internal_DrawMeshTRArguments.submeshIndex = submeshIndex; + internal_DrawMeshTRArguments.castShadows = ((!castShadows) ? 0 : 1); + internal_DrawMeshTRArguments.receiveShadows = ((!receiveShadows) ? 0 : 1); + Graphics.Internal_DrawMeshTR(ref internal_DrawMeshTRArguments, properties, material, mesh, camera); + } + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) + { + Internal_DrawMeshMatrixArguments internal_DrawMeshMatrixArguments = default(Internal_DrawMeshMatrixArguments); + internal_DrawMeshMatrixArguments.matrix = matrix; + internal_DrawMeshMatrixArguments.layer = layer; + internal_DrawMeshMatrixArguments.submeshIndex = submeshIndex; + internal_DrawMeshMatrixArguments.castShadows = ((!castShadows) ? 0 : 1); + internal_DrawMeshMatrixArguments.receiveShadows = ((!receiveShadows) ? 0 : 1); + Graphics.Internal_DrawMeshMatrix(ref internal_DrawMeshMatrixArguments, properties, material, mesh, camera); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawMeshTR(ref Internal_DrawMeshTRArguments arguments, MaterialPropertyBlock properties, Material material, Mesh mesh, Camera camera); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawMeshMatrix(ref Internal_DrawMeshMatrixArguments arguments, MaterialPropertyBlock properties, Material material, Mesh mesh, Camera camera); + public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation) + { + Graphics.Internal_DrawMeshNow1(mesh, position, rotation, -1); + } + public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) + { + Graphics.Internal_DrawMeshNow1(mesh, position, rotation, materialIndex); + } + public static void DrawMeshNow(Mesh mesh, Matrix4x4 matrix) + { + Graphics.Internal_DrawMeshNow2(mesh, matrix, -1); + } + public static void DrawMeshNow(Mesh mesh, Matrix4x4 matrix, int materialIndex) + { + Graphics.Internal_DrawMeshNow2(mesh, matrix, materialIndex); + } + private static void Internal_DrawMeshNow1(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) + { + Graphics.INTERNAL_CALL_Internal_DrawMeshNow1(mesh, ref position, ref rotation, materialIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawMeshNow1(Mesh mesh, ref Vector3 position, ref Quaternion rotation, int materialIndex); + private static void Internal_DrawMeshNow2(Mesh mesh, Matrix4x4 matrix, int materialIndex) + { + Graphics.INTERNAL_CALL_Internal_DrawMeshNow2(mesh, ref matrix, materialIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawMeshNow2(Mesh mesh, ref Matrix4x4 matrix, int materialIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DrawProcedural(MeshTopology topology, int vertexCount, [DefaultValue("1")] int instanceCount); + [ExcludeFromDocs] + public static void DrawProcedural(MeshTopology topology, int vertexCount) + { + int instanceCount = 1; + Graphics.DrawProcedural(topology, vertexCount, instanceCount); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DrawProceduralIndirect(MeshTopology topology, ComputeBuffer bufferWithArgs, [DefaultValue("0")] int argsOffset); + [ExcludeFromDocs] + public static void DrawProceduralIndirect(MeshTopology topology, ComputeBuffer bufferWithArgs) + { + int argsOffset = 0; + Graphics.DrawProceduralIndirect(topology, bufferWithArgs, argsOffset); + } + internal static void DrawSprite(Sprite sprite, Matrix4x4 matrix, Material material, int layer, Camera camera, Color color, MaterialPropertyBlock properties) + { + Graphics.INTERNAL_CALL_DrawSprite(sprite, ref matrix, material, layer, camera, ref color, properties); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawSprite(Sprite sprite, ref Matrix4x4 matrix, Material material, int layer, Camera camera, ref Color color, MaterialPropertyBlock properties); + [Obsolete("Use Graphics.DrawMeshNow instead.")] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation) + { + Graphics.Internal_DrawMeshNow1(mesh, position, rotation, -1); + } + [Obsolete("Use Graphics.DrawMeshNow instead.")] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) + { + Graphics.Internal_DrawMeshNow1(mesh, position, rotation, materialIndex); + } + [Obsolete("Use Graphics.DrawMeshNow instead.")] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix) + { + Graphics.Internal_DrawMeshNow2(mesh, matrix, -1); + } + [Obsolete("Use Graphics.DrawMeshNow instead.")] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, int materialIndex) + { + Graphics.Internal_DrawMeshNow2(mesh, matrix, materialIndex); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect screenRect, Texture texture) + { + Material mat = null; + Graphics.DrawTexture(screenRect, texture, mat); + } + public static void DrawTexture(Rect screenRect, Texture texture, [DefaultValue("null")] Material mat) + { + Graphics.DrawTexture(screenRect, texture, 0, 0, 0, 0, mat); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder) + { + Material mat = null; + Graphics.DrawTexture(screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); + } + public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [DefaultValue("null")] Material mat) + { + Graphics.DrawTexture(screenRect, texture, new Rect(0f, 0f, 1f, 1f), leftBorder, rightBorder, topBorder, bottomBorder, mat); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder) + { + Material mat = null; + Graphics.DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, mat); + } + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [DefaultValue("null")] Material mat) + { + InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); + internalDrawTextureArguments.screenRect = screenRect; + internalDrawTextureArguments.texture = texture; + internalDrawTextureArguments.sourceRect = sourceRect; + internalDrawTextureArguments.leftBorder = leftBorder; + internalDrawTextureArguments.rightBorder = rightBorder; + internalDrawTextureArguments.topBorder = topBorder; + internalDrawTextureArguments.bottomBorder = bottomBorder; + Color32 color = default(Color32); + color.r = (color.g = (color.b = (color.a = 128))); + internalDrawTextureArguments.color = color; + internalDrawTextureArguments.mat = mat; + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + [ExcludeFromDocs] + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color) + { + Material mat = null; + Graphics.DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, mat); + } + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, [DefaultValue("null")] Material mat) + { + InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); + internalDrawTextureArguments.screenRect = screenRect; + internalDrawTextureArguments.texture = texture; + internalDrawTextureArguments.sourceRect = sourceRect; + internalDrawTextureArguments.leftBorder = leftBorder; + internalDrawTextureArguments.rightBorder = rightBorder; + internalDrawTextureArguments.topBorder = topBorder; + internalDrawTextureArguments.bottomBorder = bottomBorder; + internalDrawTextureArguments.color = color; + internalDrawTextureArguments.mat = mat; + Graphics.DrawTexture(ref internalDrawTextureArguments); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DrawTexture(ref InternalDrawTextureArguments arguments); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Blit(Texture source, RenderTexture dest); + [ExcludeFromDocs] + public static void Blit(Texture source, RenderTexture dest, Material mat) + { + int pass = -1; + Graphics.Blit(source, dest, mat, pass); + } + public static void Blit(Texture source, RenderTexture dest, Material mat, [DefaultValue("-1")] int pass) + { + Graphics.Internal_BlitMaterial(source, dest, mat, pass, true); + } + [ExcludeFromDocs] + public static void Blit(Texture source, Material mat) + { + int pass = -1; + Graphics.Blit(source, mat, pass); + } + public static void Blit(Texture source, Material mat, [DefaultValue("-1")] int pass) + { + Graphics.Internal_BlitMaterial(source, null, mat, pass, false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_BlitMaterial(Texture source, RenderTexture dest, Material mat, int pass, bool setRT); + public static void BlitMultiTap(Texture source, RenderTexture dest, Material mat, params Vector2[] offsets) + { + Graphics.Internal_BlitMultiTap(source, dest, mat, offsets); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_BlitMultiTap(Texture source, RenderTexture dest, Material mat, Vector2[] offsets); + public static void SetRenderTarget(RenderTexture rt) + { + Graphics.Internal_SetRT(rt, 0, -1); + } + public static void SetRenderTarget(RenderTexture rt, int mipLevel) + { + Graphics.Internal_SetRT(rt, mipLevel, -1); + } + public static void SetRenderTarget(RenderTexture rt, int mipLevel, CubemapFace face) + { + Graphics.Internal_SetRT(rt, mipLevel, (int)face); + } + public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer) + { + Graphics.Internal_SetRTBuffer(out colorBuffer, out depthBuffer); + } + public static void SetRenderTarget(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer) + { + Graphics.Internal_SetRTBuffers(colorBuffers, out depthBuffer); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRT(RenderTexture rt, int mipLevel, int face); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRTBuffer(out RenderBuffer colorBuffer, out RenderBuffer depthBuffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRTBuffers(RenderBuffer[] colorBuffers, out RenderBuffer depthBuffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetActiveColorBuffer(out RenderBuffer res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetActiveDepthBuffer(out RenderBuffer res); + public static void SetRandomWriteTarget(int index, RenderTexture uav) + { + Graphics.Internal_SetRandomWriteTargetRT(index, uav); + } + public static void SetRandomWriteTarget(int index, ComputeBuffer uav) + { + Graphics.Internal_SetRandomWriteTargetBuffer(index, uav); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearRandomWriteTargets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRandomWriteTargetRT(int index, RenderTexture uav); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRandomWriteTargetBuffer(int index, ComputeBuffer uav); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetupVertexLights(Light[] lights); + } +} diff --git a/UnityEngine/UnityEngine/Gyroscope.cs b/UnityEngine/UnityEngine/Gyroscope.cs new file mode 100644 index 00000000..999128a6 --- /dev/null +++ b/UnityEngine/UnityEngine/Gyroscope.cs @@ -0,0 +1,97 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Gyroscope + { + private int m_GyroIndex; + public Vector3 rotationRate + { + get + { + return Gyroscope.rotationRate_Internal(this.m_GyroIndex); + } + } + public Vector3 rotationRateUnbiased + { + get + { + return Gyroscope.rotationRateUnbiased_Internal(this.m_GyroIndex); + } + } + public Vector3 gravity + { + get + { + return Gyroscope.gravity_Internal(this.m_GyroIndex); + } + } + public Vector3 userAcceleration + { + get + { + return Gyroscope.userAcceleration_Internal(this.m_GyroIndex); + } + } + public Quaternion attitude + { + get + { + return Gyroscope.attitude_Internal(this.m_GyroIndex); + } + } + public bool enabled + { + get + { + return Gyroscope.getEnabled_Internal(this.m_GyroIndex); + } + set + { + Gyroscope.setEnabled_Internal(this.m_GyroIndex, value); + } + } + public float updateInterval + { + get + { + return Gyroscope.getUpdateInterval_Internal(this.m_GyroIndex); + } + set + { + Gyroscope.setUpdateInterval_Internal(this.m_GyroIndex, value); + } + } + internal Gyroscope(int index) + { + this.m_GyroIndex = index; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 rotationRate_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 rotationRateUnbiased_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 gravity_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 userAcceleration_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion attitude_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool getEnabled_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void setEnabled_Internal(int idx, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float getUpdateInterval_Internal(int idx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void setUpdateInterval_Internal(int idx, float interval); + } +} diff --git a/UnityEngine/UnityEngine/Handheld.cs b/UnityEngine/UnityEngine/Handheld.cs new file mode 100644 index 00000000..86a7cdb9 --- /dev/null +++ b/UnityEngine/UnityEngine/Handheld.cs @@ -0,0 +1,72 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Handheld + { + public static extern bool use32BitDisplayBuffer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static bool PlayFullScreenMovie(string path, [DefaultValue("Color.black")] Color bgColor, [DefaultValue("FullScreenMovieControlMode.Full")] FullScreenMovieControlMode controlMode, [DefaultValue("FullScreenMovieScalingMode.AspectFit")] FullScreenMovieScalingMode scalingMode) + { + return Handheld.INTERNAL_CALL_PlayFullScreenMovie(path, ref bgColor, controlMode, scalingMode); + } + [ExcludeFromDocs] + public static bool PlayFullScreenMovie(string path, Color bgColor, FullScreenMovieControlMode controlMode) + { + FullScreenMovieScalingMode scalingMode = FullScreenMovieScalingMode.AspectFit; + return Handheld.INTERNAL_CALL_PlayFullScreenMovie(path, ref bgColor, controlMode, scalingMode); + } + [ExcludeFromDocs] + public static bool PlayFullScreenMovie(string path, Color bgColor) + { + FullScreenMovieScalingMode scalingMode = FullScreenMovieScalingMode.AspectFit; + FullScreenMovieControlMode controlMode = FullScreenMovieControlMode.Full; + return Handheld.INTERNAL_CALL_PlayFullScreenMovie(path, ref bgColor, controlMode, scalingMode); + } + [ExcludeFromDocs] + public static bool PlayFullScreenMovie(string path) + { + FullScreenMovieScalingMode scalingMode = FullScreenMovieScalingMode.AspectFit; + FullScreenMovieControlMode controlMode = FullScreenMovieControlMode.Full; + Color black = Color.black; + return Handheld.INTERNAL_CALL_PlayFullScreenMovie(path, ref black, controlMode, scalingMode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_PlayFullScreenMovie(string path, ref Color bgColor, FullScreenMovieControlMode controlMode, FullScreenMovieScalingMode scalingMode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Vibrate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetActivityIndicatorStyleImpl(int style); + public static void SetActivityIndicatorStyle(iOSActivityIndicatorStyle style) + { + Handheld.SetActivityIndicatorStyleImpl((int)style); + } + public static void SetActivityIndicatorStyle(AndroidActivityIndicatorStyle style) + { + Handheld.SetActivityIndicatorStyleImpl((int)style); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetActivityIndicatorStyle(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StartActivityIndicator(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopActivityIndicator(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearShaderCache(); + } +} diff --git a/UnityEngine/UnityEngine/HeadDoF.cs b/UnityEngine/UnityEngine/HeadDoF.cs new file mode 100644 index 00000000..285d020c --- /dev/null +++ b/UnityEngine/UnityEngine/HeadDoF.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine +{ + internal enum HeadDoF + { + NeckFrontBack, + NeckLeftRight, + NeckRollLeftRight, + HeadFrontBack, + HeadLeftRight, + HeadRollLeftRight, + LeftEyeDownUp, + LeftEyeInOut, + RightEyeDownUp, + RightEyeInOut, + JawDownUp, + JawLeftRight, + LastHeadDoF + } +} diff --git a/UnityEngine/UnityEngine/HeaderAttribute.cs b/UnityEngine/UnityEngine/HeaderAttribute.cs new file mode 100644 index 00000000..647f6255 --- /dev/null +++ b/UnityEngine/UnityEngine/HeaderAttribute.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] + public class HeaderAttribute : PropertyAttribute + { + public readonly string header; + public HeaderAttribute(string header) + { + this.header = header; + } + } +} diff --git a/UnityEngine/UnityEngine/HideFlags.cs b/UnityEngine/UnityEngine/HideFlags.cs new file mode 100644 index 00000000..8131bf95 --- /dev/null +++ b/UnityEngine/UnityEngine/HideFlags.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum HideFlags + { + None = 0, + HideInHierarchy = 1, + HideInInspector = 2, + DontSave = 4, + NotEditable = 8, + HideAndDontSave = 13 + } +} diff --git a/UnityEngine/UnityEngine/HideInInspector.cs b/UnityEngine/UnityEngine/HideInInspector.cs new file mode 100644 index 00000000..22813fcd --- /dev/null +++ b/UnityEngine/UnityEngine/HideInInspector.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class HideInInspector : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/HingeJoint.cs b/UnityEngine/UnityEngine/HingeJoint.cs new file mode 100644 index 00000000..77a9e40d --- /dev/null +++ b/UnityEngine/UnityEngine/HingeJoint.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class HingeJoint : Joint + { + public JointMotor motor + { + get + { + JointMotor result; + this.INTERNAL_get_motor(out result); + return result; + } + set + { + this.INTERNAL_set_motor(ref value); + } + } + public JointLimits limits + { + get + { + JointLimits result; + this.INTERNAL_get_limits(out result); + return result; + } + set + { + this.INTERNAL_set_limits(ref value); + } + } + public JointSpring spring + { + get + { + JointSpring result; + this.INTERNAL_get_spring(out result); + return result; + } + set + { + this.INTERNAL_set_spring(ref value); + } + } + public extern bool useMotor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useLimits + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useSpring + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float velocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float angle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_motor(out JointMotor value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_motor(ref JointMotor value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_limits(out JointLimits value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_limits(ref JointLimits value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_spring(out JointSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_spring(ref JointSpring value); + } +} diff --git a/UnityEngine/UnityEngine/HingeJoint2D.cs b/UnityEngine/UnityEngine/HingeJoint2D.cs new file mode 100644 index 00000000..f8773519 --- /dev/null +++ b/UnityEngine/UnityEngine/HingeJoint2D.cs @@ -0,0 +1,111 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class HingeJoint2D : AnchoredJoint2D + { + public extern bool useMotor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useLimits + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public JointMotor2D motor + { + get + { + JointMotor2D result; + this.INTERNAL_get_motor(out result); + return result; + } + set + { + this.INTERNAL_set_motor(ref value); + } + } + public JointAngleLimits2D limits + { + get + { + JointAngleLimits2D result; + this.INTERNAL_get_limits(out result); + return result; + } + set + { + this.INTERNAL_set_limits(ref value); + } + } + public extern JointLimitState2D limitState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float referenceAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float jointAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float jointSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_motor(out JointMotor2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_motor(ref JointMotor2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_limits(out JointAngleLimits2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_limits(ref JointAngleLimits2D value); + public Vector2 GetReactionForce(float timeStep) + { + Vector2 result; + HingeJoint2D.HingeJoint2D_CUSTOM_INTERNAL_GetReactionForce(this, timeStep, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void HingeJoint2D_CUSTOM_INTERNAL_GetReactionForce(HingeJoint2D joint, float timeStep, out Vector2 value); + public float GetReactionTorque(float timeStep) + { + return HingeJoint2D.INTERNAL_CALL_GetReactionTorque(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetReactionTorque(HingeJoint2D self, float timeStep); + public float GetMotorTorque(float timeStep) + { + return HingeJoint2D.INTERNAL_CALL_GetMotorTorque(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetMotorTorque(HingeJoint2D self, float timeStep); + } +} diff --git a/UnityEngine/UnityEngine/HorizontalWrapMode.cs b/UnityEngine/UnityEngine/HorizontalWrapMode.cs new file mode 100644 index 00000000..4796208c --- /dev/null +++ b/UnityEngine/UnityEngine/HorizontalWrapMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum HorizontalWrapMode + { + Wrap, + Overflow + } +} diff --git a/UnityEngine/UnityEngine/HostData.cs b/UnityEngine/UnityEngine/HostData.cs new file mode 100644 index 00000000..4d237a34 --- /dev/null +++ b/UnityEngine/UnityEngine/HostData.cs @@ -0,0 +1,129 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class HostData + { + private int m_Nat; + private string m_GameType; + private string m_GameName; + private int m_ConnectedPlayers; + private int m_PlayerLimit; + private string[] m_IP; + private int m_Port; + private int m_PasswordProtected; + private string m_Comment; + private string m_GUID; + public bool useNat + { + get + { + return this.m_Nat != 0; + } + set + { + this.m_Nat = ((!value) ? 0 : 1); + } + } + public string gameType + { + get + { + return this.m_GameType; + } + set + { + this.m_GameType = value; + } + } + public string gameName + { + get + { + return this.m_GameName; + } + set + { + this.m_GameName = value; + } + } + public int connectedPlayers + { + get + { + return this.m_ConnectedPlayers; + } + set + { + this.m_ConnectedPlayers = value; + } + } + public int playerLimit + { + get + { + return this.m_PlayerLimit; + } + set + { + this.m_PlayerLimit = value; + } + } + public string[] ip + { + get + { + return this.m_IP; + } + set + { + this.m_IP = value; + } + } + public int port + { + get + { + return this.m_Port; + } + set + { + this.m_Port = value; + } + } + public bool passwordProtected + { + get + { + return this.m_PasswordProtected != 0; + } + set + { + this.m_PasswordProtected = ((!value) ? 0 : 1); + } + } + public string comment + { + get + { + return this.m_Comment; + } + set + { + this.m_Comment = value; + } + } + public string guid + { + get + { + return this.m_GUID; + } + set + { + this.m_GUID = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/HumanBodyBones.cs b/UnityEngine/UnityEngine/HumanBodyBones.cs new file mode 100644 index 00000000..bdda400c --- /dev/null +++ b/UnityEngine/UnityEngine/HumanBodyBones.cs @@ -0,0 +1,62 @@ +using System; +namespace UnityEngine +{ + public enum HumanBodyBones + { + Hips, + LeftUpperLeg, + RightUpperLeg, + LeftLowerLeg, + RightLowerLeg, + LeftFoot, + RightFoot, + Spine, + Chest, + Neck, + Head, + LeftShoulder, + RightShoulder, + LeftUpperArm, + RightUpperArm, + LeftLowerArm, + RightLowerArm, + LeftHand, + RightHand, + LeftToes, + RightToes, + LeftEye, + RightEye, + Jaw, + LeftThumbProximal, + LeftThumbIntermediate, + LeftThumbDistal, + LeftIndexProximal, + LeftIndexIntermediate, + LeftIndexDistal, + LeftMiddleProximal, + LeftMiddleIntermediate, + LeftMiddleDistal, + LeftRingProximal, + LeftRingIntermediate, + LeftRingDistal, + LeftLittleProximal, + LeftLittleIntermediate, + LeftLittleDistal, + RightThumbProximal, + RightThumbIntermediate, + RightThumbDistal, + RightIndexProximal, + RightIndexIntermediate, + RightIndexDistal, + RightMiddleProximal, + RightMiddleIntermediate, + RightMiddleDistal, + RightRingProximal, + RightRingIntermediate, + RightRingDistal, + RightLittleProximal, + RightLittleIntermediate, + RightLittleDistal, + LastBone + } +} diff --git a/UnityEngine/UnityEngine/HumanBodyPart.cs b/UnityEngine/UnityEngine/HumanBodyPart.cs new file mode 100644 index 00000000..2c6afb8a --- /dev/null +++ b/UnityEngine/UnityEngine/HumanBodyPart.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + internal enum HumanBodyPart + { + BodyStart, + LeftFingerStart = 24, + RightFingerStart = 39, + LastBone = 54 + } +} diff --git a/UnityEngine/UnityEngine/HumanBone.cs b/UnityEngine/UnityEngine/HumanBone.cs new file mode 100644 index 00000000..d024f76d --- /dev/null +++ b/UnityEngine/UnityEngine/HumanBone.cs @@ -0,0 +1,32 @@ +using System; +namespace UnityEngine +{ + public struct HumanBone + { + private string m_BoneName; + private string m_HumanName; + public HumanLimit limit; + public string boneName + { + get + { + return this.m_BoneName; + } + set + { + this.m_BoneName = value; + } + } + public string humanName + { + get + { + return this.m_HumanName; + } + set + { + this.m_HumanName = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/HumanDescription.cs b/UnityEngine/UnityEngine/HumanDescription.cs new file mode 100644 index 00000000..9a870c4b --- /dev/null +++ b/UnityEngine/UnityEngine/HumanDescription.cs @@ -0,0 +1,93 @@ +using System; +namespace UnityEngine +{ + public struct HumanDescription + { + public HumanBone[] human; + public SkeletonBone[] skeleton; + private float m_ArmTwist; + private float m_ForeArmTwist; + private float m_UpperLegTwist; + private float m_LegTwist; + private float m_ArmStretch; + private float m_LegStretch; + private float m_FeetSpacing; + public float upperArmTwist + { + get + { + return this.m_ArmTwist; + } + set + { + this.m_ArmTwist = value; + } + } + public float lowerArmTwist + { + get + { + return this.m_ForeArmTwist; + } + set + { + this.m_ForeArmTwist = value; + } + } + public float upperLegTwist + { + get + { + return this.m_UpperLegTwist; + } + set + { + this.m_UpperLegTwist = value; + } + } + public float lowerLegTwist + { + get + { + return this.m_LegTwist; + } + set + { + this.m_LegTwist = value; + } + } + public float armStretch + { + get + { + return this.m_ArmStretch; + } + set + { + this.m_ArmStretch = value; + } + } + public float legStretch + { + get + { + return this.m_LegStretch; + } + set + { + this.m_LegStretch = value; + } + } + public float feetSpacing + { + get + { + return this.m_FeetSpacing; + } + set + { + this.m_FeetSpacing = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/HumanLimit.cs b/UnityEngine/UnityEngine/HumanLimit.cs new file mode 100644 index 00000000..6ac80670 --- /dev/null +++ b/UnityEngine/UnityEngine/HumanLimit.cs @@ -0,0 +1,67 @@ +using System; +namespace UnityEngine +{ + public struct HumanLimit + { + private Vector3 m_Min; + private Vector3 m_Max; + private Vector3 m_Center; + private float m_AxisLength; + private int m_UseDefaultValues; + public bool useDefaultValues + { + get + { + return this.m_UseDefaultValues != 0; + } + set + { + this.m_UseDefaultValues = ((!value) ? 0 : 1); + } + } + public Vector3 min + { + get + { + return this.m_Min; + } + set + { + this.m_Min = value; + } + } + public Vector3 max + { + get + { + return this.m_Max; + } + set + { + this.m_Max = value; + } + } + public Vector3 center + { + get + { + return this.m_Center; + } + set + { + this.m_Center = value; + } + } + public float axisLength + { + get + { + return this.m_AxisLength; + } + set + { + this.m_AxisLength = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/HumanParameter.cs b/UnityEngine/UnityEngine/HumanParameter.cs new file mode 100644 index 00000000..29a1b86a --- /dev/null +++ b/UnityEngine/UnityEngine/HumanParameter.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + internal enum HumanParameter + { + UpperArmTwist, + LowerArmTwist, + UpperLegTwist, + LowerLegTwist, + ArmStretch, + LegStretch, + FeetSpacing + } +} diff --git a/UnityEngine/UnityEngine/HumanTrait.cs b/UnityEngine/UnityEngine/HumanTrait.cs new file mode 100644 index 00000000..127e2ca4 --- /dev/null +++ b/UnityEngine/UnityEngine/HumanTrait.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class HumanTrait : Object + { + public static extern int MuscleCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] MuscleName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int BoneCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] BoneName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int RequiredBoneCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int MuscleFromBone(int i, int dofIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int BoneFromMuscle(int i); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool RequiredBone(int i); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasCollider(Avatar avatar, int i); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetMuscleDefaultMin(int i); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetMuscleDefaultMax(int i); + } +} diff --git a/UnityEngine/UnityEngine/ICanvasRaycastFilter.cs b/UnityEngine/UnityEngine/ICanvasRaycastFilter.cs new file mode 100644 index 00000000..fb6d904d --- /dev/null +++ b/UnityEngine/UnityEngine/ICanvasRaycastFilter.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + public interface ICanvasRaycastFilter + { + bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera); + } +} diff --git a/UnityEngine/UnityEngine/IMECompositionMode.cs b/UnityEngine/UnityEngine/IMECompositionMode.cs new file mode 100644 index 00000000..79cb01fe --- /dev/null +++ b/UnityEngine/UnityEngine/IMECompositionMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum IMECompositionMode + { + Auto, + On, + Off + } +} diff --git a/UnityEngine/UnityEngine/ISerializationCallbackReceiver.cs b/UnityEngine/UnityEngine/ISerializationCallbackReceiver.cs new file mode 100644 index 00000000..ed476b74 --- /dev/null +++ b/UnityEngine/UnityEngine/ISerializationCallbackReceiver.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public interface ISerializationCallbackReceiver + { + void OnBeforeSerialize(); + void OnAfterDeserialize(); + } +} diff --git a/UnityEngine/UnityEngine/ImageEffectOpaque.cs b/UnityEngine/UnityEngine/ImageEffectOpaque.cs new file mode 100644 index 00000000..c8762e4b --- /dev/null +++ b/UnityEngine/UnityEngine/ImageEffectOpaque.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class ImageEffectOpaque : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/ImageEffectTransformsToLDR.cs b/UnityEngine/UnityEngine/ImageEffectTransformsToLDR.cs new file mode 100644 index 00000000..11bb1006 --- /dev/null +++ b/UnityEngine/UnityEngine/ImageEffectTransformsToLDR.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class ImageEffectTransformsToLDR : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/ImagePosition.cs b/UnityEngine/UnityEngine/ImagePosition.cs new file mode 100644 index 00000000..07046129 --- /dev/null +++ b/UnityEngine/UnityEngine/ImagePosition.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum ImagePosition + { + ImageLeft, + ImageAbove, + ImageOnly, + TextOnly + } +} diff --git a/UnityEngine/UnityEngine/ImplementedInActionScriptAttribute.cs b/UnityEngine/UnityEngine/ImplementedInActionScriptAttribute.cs new file mode 100644 index 00000000..d89c2aa7 --- /dev/null +++ b/UnityEngine/UnityEngine/ImplementedInActionScriptAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Method)] + public class ImplementedInActionScriptAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/Input.cs b/UnityEngine/UnityEngine/Input.cs new file mode 100644 index 00000000..b6c3ac88 --- /dev/null +++ b/UnityEngine/UnityEngine/Input.cs @@ -0,0 +1,313 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Input + { + private static Gyroscope m_MainGyro; + private static LocationService locationServiceInstance; + private static Compass compassInstance; + public static extern bool compensateSensors + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("isGyroAvailable property is deprecated. Please use SystemInfo.supportsGyroscope instead.")] + public static extern bool isGyroAvailable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Gyroscope gyro + { + get + { + if (Input.m_MainGyro == null) + { + Input.m_MainGyro = new Gyroscope(Input.mainGyroIndex_Internal()); + } + return Input.m_MainGyro; + } + } + public static extern Vector3 mousePosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Vector3 mouseScrollDelta + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static bool mousePresent + { + get + { + return !Input.touchSupported; + } + } + public static extern bool simulateMouseWithTouches + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool anyKey + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool anyKeyDown + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string inputString + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Vector3 acceleration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static AccelerationEvent[] accelerationEvents + { + get + { + int accelerationEventCount = Input.accelerationEventCount; + AccelerationEvent[] array = new AccelerationEvent[accelerationEventCount]; + for (int i = 0; i < accelerationEventCount; i++) + { + array[i] = Input.GetAccelerationEvent(i); + } + return array; + } + } + public static extern int accelerationEventCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Touch[] touches + { + get + { + int touchCount = Input.touchCount; + Touch[] array = new Touch[touchCount]; + for (int i = 0; i < touchCount; i++) + { + array[i] = Input.GetTouch(i); + } + return array; + } + } + public static extern int touchCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("eatKeyPressOnTextFieldFocus property is deprecated, and only provided to support legacy behavior.")] + public static extern bool eatKeyPressOnTextFieldFocus + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static bool touchSupported + { + get + { + return false; + } + } + public static extern bool multiTouchEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static LocationService location + { + get + { + if (Input.locationServiceInstance == null) + { + Input.locationServiceInstance = new LocationService(); + } + return Input.locationServiceInstance; + } + } + public static Compass compass + { + get + { + if (Input.compassInstance == null) + { + Input.compassInstance = new Compass(); + } + return Input.compassInstance; + } + } + public static extern DeviceOrientation deviceOrientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern IMECompositionMode imeCompositionMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string compositionString + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool imeIsSelected + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Vector2 compositionCursorPos + { + get + { + Vector2 result; + Input.INTERNAL_get_compositionCursorPos(out result); + return result; + } + set + { + Input.INTERNAL_set_compositionCursorPos(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int mainGyroIndex_Internal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyInt(int key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyUpInt(int key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyUpString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyDownInt(int key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool GetKeyDownString(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetAxis(string axisName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetAxisRaw(string axisName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetButton(string buttonName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetButtonDown(string buttonName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetButtonUp(string buttonName); + public static bool GetKey(string name) + { + return Input.GetKeyString(name); + } + public static bool GetKey(KeyCode key) + { + return Input.GetKeyInt((int)key); + } + public static bool GetKeyDown(string name) + { + return Input.GetKeyDownString(name); + } + public static bool GetKeyDown(KeyCode key) + { + return Input.GetKeyDownInt((int)key); + } + public static bool GetKeyUp(string name) + { + return Input.GetKeyUpString(name); + } + public static bool GetKeyUp(KeyCode key) + { + return Input.GetKeyUpInt((int)key); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetJoystickNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetMouseButton(int button); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetMouseButtonDown(int button); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetMouseButtonUp(int button); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetInputAxes(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AccelerationEvent GetAccelerationEvent(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Touch GetTouch(int index); + [Obsolete("Use ps3 move API instead", true)] + public static Quaternion GetRotation(int deviceID) + { + return Quaternion.identity; + } + [Obsolete("Use ps3 move API instead", true)] + public static Vector3 GetPosition(int deviceID) + { + return Vector3.zero; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_compositionCursorPos(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_compositionCursorPos(ref Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/InteractiveCloth.cs b/UnityEngine/UnityEngine/InteractiveCloth.cs new file mode 100644 index 00000000..51e1144a --- /dev/null +++ b/UnityEngine/UnityEngine/InteractiveCloth.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class InteractiveCloth : Cloth + { + public extern Mesh mesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float friction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float density + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float pressure + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float collisionResponse + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float tearFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float attachmentTearFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float attachmentResponse + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isTeared + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public void AddForceAtPosition(Vector3 force, Vector3 position, float radius, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + InteractiveCloth.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, radius, mode); + } + [ExcludeFromDocs] + public void AddForceAtPosition(Vector3 force, Vector3 position, float radius) + { + ForceMode mode = ForceMode.Force; + InteractiveCloth.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, radius, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddForceAtPosition(InteractiveCloth self, ref Vector3 force, ref Vector3 position, float radius, ForceMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AttachToCollider(Collider collider, [DefaultValue("false")] bool tearable, [DefaultValue("false")] bool twoWayInteraction); + [ExcludeFromDocs] + public void AttachToCollider(Collider collider, bool tearable) + { + bool twoWayInteraction = false; + this.AttachToCollider(collider, tearable, twoWayInteraction); + } + [ExcludeFromDocs] + public void AttachToCollider(Collider collider) + { + bool twoWayInteraction = false; + bool tearable = false; + this.AttachToCollider(collider, tearable, twoWayInteraction); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DetachFromCollider(Collider collider); + } +} diff --git a/UnityEngine/UnityEngine/InternalDrawTextureArguments.cs b/UnityEngine/UnityEngine/InternalDrawTextureArguments.cs new file mode 100644 index 00000000..d0656a56 --- /dev/null +++ b/UnityEngine/UnityEngine/InternalDrawTextureArguments.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + internal struct InternalDrawTextureArguments + { + public Rect screenRect; + public Texture texture; + public Rect sourceRect; + public int leftBorder; + public int rightBorder; + public int topBorder; + public int bottomBorder; + public Color32 color; + public Material mat; + } +} diff --git a/UnityEngine/UnityEngine/InternalEmitParticleArguments.cs b/UnityEngine/UnityEngine/InternalEmitParticleArguments.cs new file mode 100644 index 00000000..a6e42b01 --- /dev/null +++ b/UnityEngine/UnityEngine/InternalEmitParticleArguments.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + internal struct InternalEmitParticleArguments + { + public Vector3 pos; + public Vector3 velocity; + public float size; + public float energy; + public Color color; + public float rotation; + public float angularVelocity; + } +} diff --git a/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs b/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs new file mode 100644 index 00000000..eb92f92a --- /dev/null +++ b/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs @@ -0,0 +1,199 @@ +using System; +using System.Collections; +using System.Collections.Generic; +namespace UnityEngine +{ + internal class InternalStaticBatchingUtility + { + internal class SortGO : IComparer + { + int IComparer.Compare(object a, object b) + { + if (a == b) + { + return 0; + } + Renderer renderer = InternalStaticBatchingUtility.SortGO.GetRenderer(a as GameObject); + Renderer renderer2 = InternalStaticBatchingUtility.SortGO.GetRenderer(b as GameObject); + int num = InternalStaticBatchingUtility.SortGO.GetMaterialId(renderer).CompareTo(InternalStaticBatchingUtility.SortGO.GetMaterialId(renderer2)); + if (num == 0) + { + num = InternalStaticBatchingUtility.SortGO.GetLightmapIndex(renderer).CompareTo(InternalStaticBatchingUtility.SortGO.GetLightmapIndex(renderer2)); + } + return num; + } + private static int GetMaterialId(Renderer renderer) + { + if (renderer == null || renderer.sharedMaterial == null) + { + return 0; + } + return renderer.sharedMaterial.GetInstanceID(); + } + private static int GetLightmapIndex(Renderer renderer) + { + if (renderer == null) + { + return -1; + } + return renderer.lightmapIndex; + } + private static Renderer GetRenderer(GameObject go) + { + if (go == null) + { + return null; + } + MeshFilter meshFilter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; + if (meshFilter == null) + { + return null; + } + return meshFilter.renderer; + } + } + private const int MaxVerticesInBatch = 64000; + private const string CombinedMeshPrefix = "Combined Mesh"; + public static void Combine(GameObject staticBatchRoot) + { + InternalStaticBatchingUtility.Combine(staticBatchRoot, false); + } + public static void Combine(GameObject staticBatchRoot, bool combineOnlyStatic) + { + GameObject[] array = (GameObject[])Object.FindObjectsOfType(typeof(GameObject)); + List list = new List(); + GameObject[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + GameObject gameObject = array2[i]; + if (!(staticBatchRoot != null) || gameObject.transform.IsChildOf(staticBatchRoot.transform)) + { + if (!combineOnlyStatic || gameObject.isStaticBatchable) + { + list.Add(gameObject); + } + } + } + array = list.ToArray(); + if (!Application.HasProLicense() && !Application.HasAdvancedLicense() && staticBatchRoot != null && array.Length > 0) + { + Debug.LogError("Your Unity license is not sufficient for Static Batching."); + } + InternalStaticBatchingUtility.Combine(array, staticBatchRoot); + } + public static void Combine(GameObject[] gos, GameObject staticBatchRoot) + { + Matrix4x4 lhs = Matrix4x4.identity; + Transform staticBatchRootTransform = null; + if (staticBatchRoot) + { + lhs = staticBatchRoot.transform.worldToLocalMatrix; + staticBatchRootTransform = staticBatchRoot.transform; + } + int batchIndex = 0; + int num = 0; + List list = new List(); + List list2 = new List(); + List list3 = new List(); + Array.Sort(gos, new InternalStaticBatchingUtility.SortGO()); + for (int i = 0; i < gos.Length; i++) + { + GameObject gameObject = gos[i]; + MeshFilter meshFilter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; + if (!(meshFilter == null)) + { + if (!(meshFilter.sharedMesh == null)) + { + if (meshFilter.sharedMesh.canAccess) + { + if (!(meshFilter.renderer == null) && meshFilter.renderer.enabled) + { + if (meshFilter.renderer.staticBatchIndex == 0) + { + if (num + meshFilter.sharedMesh.vertexCount > 64000) + { + InternalStaticBatchingUtility.MakeBatch(list, list2, list3, staticBatchRootTransform, batchIndex++); + list.Clear(); + list2.Clear(); + list3.Clear(); + num = 0; + } + MeshSubsetCombineUtility.MeshInstance item = default(MeshSubsetCombineUtility.MeshInstance); + Mesh sharedMesh = meshFilter.sharedMesh; + item.meshInstanceID = sharedMesh.GetInstanceID(); + item.transform = lhs * meshFilter.transform.localToWorldMatrix; + item.lightmapTilingOffset = meshFilter.renderer.lightmapTilingOffset; + list.Add(item); + Material[] array = meshFilter.renderer.sharedMaterials; + if (array.Length > sharedMesh.subMeshCount) + { + Debug.LogWarning(string.Concat(new object[] + { + "Mesh has more materials (", + array.Length, + ") than subsets (", + sharedMesh.subMeshCount, + ")" + })); + Material[] array2 = new Material[sharedMesh.subMeshCount]; + for (int j = 0; j < sharedMesh.subMeshCount; j++) + { + array2[j] = meshFilter.renderer.sharedMaterials[j]; + } + meshFilter.renderer.sharedMaterials = array2; + array = array2; + } + for (int k = 0; k < Math.Min(array.Length, sharedMesh.subMeshCount); k++) + { + list2.Add(new MeshSubsetCombineUtility.SubMeshInstance + { + meshInstanceID = meshFilter.sharedMesh.GetInstanceID(), + vertexOffset = num, + subMeshIndex = k, + gameObjectInstanceID = gameObject.GetInstanceID(), + transform = item.transform + }); + list3.Add(gameObject); + } + num += sharedMesh.vertexCount; + } + } + } + } + } + } + InternalStaticBatchingUtility.MakeBatch(list, list2, list3, staticBatchRootTransform, batchIndex); + } + private static void MakeBatch(List meshes, List subsets, List subsetGOs, Transform staticBatchRootTransform, int batchIndex) + { + if (meshes.Count < 2) + { + return; + } + MeshSubsetCombineUtility.MeshInstance[] meshes2 = meshes.ToArray(); + MeshSubsetCombineUtility.SubMeshInstance[] array = subsets.ToArray(); + string text = "Combined Mesh"; + text = text + " (root: " + ((!(staticBatchRootTransform != null)) ? "scene" : staticBatchRootTransform.name) + ")"; + if (batchIndex > 0) + { + text = text + " " + (batchIndex + 1); + } + Mesh mesh = StaticBatchingUtility.InternalCombineVertices(meshes2, text); + StaticBatchingUtility.InternalCombineIndices(array, mesh); + int num = 0; + for (int i = 0; i < array.Length; i++) + { + MeshSubsetCombineUtility.SubMeshInstance subMeshInstance = array[i]; + GameObject gameObject = subsetGOs[i]; + Mesh sharedMesh = mesh; + MeshFilter meshFilter = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter)); + meshFilter.sharedMesh = sharedMesh; + gameObject.renderer.SetSubsetIndex(subMeshInstance.subMeshIndex, num); + gameObject.renderer.staticBatchRootTransform = staticBatchRootTransform; + gameObject.renderer.enabled = false; + gameObject.renderer.enabled = true; + num++; + } + } + } +} diff --git a/UnityEngine/UnityEngine/Internal_DrawArguments.cs b/UnityEngine/UnityEngine/Internal_DrawArguments.cs new file mode 100644 index 00000000..33948f9f --- /dev/null +++ b/UnityEngine/UnityEngine/Internal_DrawArguments.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + internal struct Internal_DrawArguments + { + public IntPtr target; + public Rect position; + public int isHover; + public int isActive; + public int on; + public int hasKeyboardFocus; + } +} diff --git a/UnityEngine/UnityEngine/Internal_DrawMeshMatrixArguments.cs b/UnityEngine/UnityEngine/Internal_DrawMeshMatrixArguments.cs new file mode 100644 index 00000000..bc169430 --- /dev/null +++ b/UnityEngine/UnityEngine/Internal_DrawMeshMatrixArguments.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + internal struct Internal_DrawMeshMatrixArguments + { + public int layer; + public int submeshIndex; + public Matrix4x4 matrix; + public int castShadows; + public int receiveShadows; + } +} diff --git a/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs b/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs new file mode 100644 index 00000000..3fbf5218 --- /dev/null +++ b/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + internal struct Internal_DrawMeshTRArguments + { + public int layer; + public int submeshIndex; + public Quaternion rotation; + public Vector3 position; + public int castShadows; + public int receiveShadows; + } +} diff --git a/UnityEngine/UnityEngine/Internal_DrawWithTextSelectionArguments.cs b/UnityEngine/UnityEngine/Internal_DrawWithTextSelectionArguments.cs new file mode 100644 index 00000000..1e9f54d0 --- /dev/null +++ b/UnityEngine/UnityEngine/Internal_DrawWithTextSelectionArguments.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine +{ + internal struct Internal_DrawWithTextSelectionArguments + { + public IntPtr target; + public Rect position; + public int firstPos; + public int lastPos; + public Color cursorColor; + public Color selectionColor; + public int isHover; + public int isActive; + public int on; + public int hasKeyboardFocus; + public int drawSelectionAsComposition; + } +} diff --git a/UnityEngine/UnityEngine/Joint.cs b/UnityEngine/UnityEngine/Joint.cs new file mode 100644 index 00000000..ed84159c --- /dev/null +++ b/UnityEngine/UnityEngine/Joint.cs @@ -0,0 +1,110 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Joint : Component + { + public extern Rigidbody connectedBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 axis + { + get + { + Vector3 result; + this.INTERNAL_get_axis(out result); + return result; + } + set + { + this.INTERNAL_set_axis(ref value); + } + } + public Vector3 anchor + { + get + { + Vector3 result; + this.INTERNAL_get_anchor(out result); + return result; + } + set + { + this.INTERNAL_set_anchor(ref value); + } + } + public Vector3 connectedAnchor + { + get + { + Vector3 result; + this.INTERNAL_get_connectedAnchor(out result); + return result; + } + set + { + this.INTERNAL_set_connectedAnchor(ref value); + } + } + public extern bool autoConfigureConnectedAnchor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float breakForce + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float breakTorque + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool enableCollision + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_axis(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_axis(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anchor(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anchor(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_connectedAnchor(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_connectedAnchor(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/Joint2D.cs b/UnityEngine/UnityEngine/Joint2D.cs new file mode 100644 index 00000000..5cbddee3 --- /dev/null +++ b/UnityEngine/UnityEngine/Joint2D.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Joint2D : Behaviour + { + public extern Rigidbody2D connectedBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool collideConnected + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/JointAngleLimits2D.cs b/UnityEngine/UnityEngine/JointAngleLimits2D.cs new file mode 100644 index 00000000..5f9c5d10 --- /dev/null +++ b/UnityEngine/UnityEngine/JointAngleLimits2D.cs @@ -0,0 +1,31 @@ +using System; +namespace UnityEngine +{ + public struct JointAngleLimits2D + { + private float m_LowerAngle; + private float m_UpperAngle; + public float min + { + get + { + return this.m_LowerAngle; + } + set + { + this.m_LowerAngle = value; + } + } + public float max + { + get + { + return this.m_UpperAngle; + } + set + { + this.m_UpperAngle = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointDrive.cs b/UnityEngine/UnityEngine/JointDrive.cs new file mode 100644 index 00000000..f1ceb5d2 --- /dev/null +++ b/UnityEngine/UnityEngine/JointDrive.cs @@ -0,0 +1,55 @@ +using System; +namespace UnityEngine +{ + public struct JointDrive + { + private int m_Mode; + private float m_PositionSpring; + private float m_PositionDamper; + private float m_MaximumForce; + public JointDriveMode mode + { + get + { + return (JointDriveMode)this.m_Mode; + } + set + { + this.m_Mode = (int)value; + } + } + public float positionSpring + { + get + { + return this.m_PositionSpring; + } + set + { + this.m_PositionSpring = value; + } + } + public float positionDamper + { + get + { + return this.m_PositionDamper; + } + set + { + this.m_PositionDamper = value; + } + } + public float maximumForce + { + get + { + return this.m_MaximumForce; + } + set + { + this.m_MaximumForce = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointDriveMode.cs b/UnityEngine/UnityEngine/JointDriveMode.cs new file mode 100644 index 00000000..d2c5113a --- /dev/null +++ b/UnityEngine/UnityEngine/JointDriveMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum JointDriveMode + { + None = 0, + Position = 1, + Velocity = 2, + PositionAndVelocity = 3 + } +} diff --git a/UnityEngine/UnityEngine/JointLimitState2D.cs b/UnityEngine/UnityEngine/JointLimitState2D.cs new file mode 100644 index 00000000..ee4d1df1 --- /dev/null +++ b/UnityEngine/UnityEngine/JointLimitState2D.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum JointLimitState2D + { + Inactive, + LowerLimit, + UpperLimit, + EqualLimits + } +} diff --git a/UnityEngine/UnityEngine/JointLimits.cs b/UnityEngine/UnityEngine/JointLimits.cs new file mode 100644 index 00000000..32d814d9 --- /dev/null +++ b/UnityEngine/UnityEngine/JointLimits.cs @@ -0,0 +1,57 @@ +using System; +namespace UnityEngine +{ + public struct JointLimits + { + private float m_Min; + private float m_MinBounce; + private float m_MinHardness; + private float m_Max; + private float m_MaxBounce; + private float m_MaxHardness; + public float min + { + get + { + return this.m_Min; + } + set + { + this.m_Min = value; + } + } + public float minBounce + { + get + { + return this.m_MinBounce; + } + set + { + this.m_MinBounce = value; + } + } + public float max + { + get + { + return this.m_Max; + } + set + { + this.m_Max = value; + } + } + public float maxBounce + { + get + { + return this.m_MaxBounce; + } + set + { + this.m_MaxBounce = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointMotor.cs b/UnityEngine/UnityEngine/JointMotor.cs new file mode 100644 index 00000000..432673d9 --- /dev/null +++ b/UnityEngine/UnityEngine/JointMotor.cs @@ -0,0 +1,43 @@ +using System; +namespace UnityEngine +{ + public struct JointMotor + { + private float m_TargetVelocity; + private float m_Force; + private bool m_FreeSpin; + public float targetVelocity + { + get + { + return this.m_TargetVelocity; + } + set + { + this.m_TargetVelocity = value; + } + } + public float force + { + get + { + return this.m_Force; + } + set + { + this.m_Force = value; + } + } + public bool freeSpin + { + get + { + return this.m_FreeSpin; + } + set + { + this.m_FreeSpin = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointMotor2D.cs b/UnityEngine/UnityEngine/JointMotor2D.cs new file mode 100644 index 00000000..c7648656 --- /dev/null +++ b/UnityEngine/UnityEngine/JointMotor2D.cs @@ -0,0 +1,31 @@ +using System; +namespace UnityEngine +{ + public struct JointMotor2D + { + private float m_MotorSpeed; + private float m_MaximumMotorTorque; + public float motorSpeed + { + get + { + return this.m_MotorSpeed; + } + set + { + this.m_MotorSpeed = value; + } + } + public float maxMotorTorque + { + get + { + return this.m_MaximumMotorTorque; + } + set + { + this.m_MaximumMotorTorque = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointProjectionMode.cs b/UnityEngine/UnityEngine/JointProjectionMode.cs new file mode 100644 index 00000000..3cf457ac --- /dev/null +++ b/UnityEngine/UnityEngine/JointProjectionMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum JointProjectionMode + { + None, + PositionAndRotation, + PositionOnly + } +} diff --git a/UnityEngine/UnityEngine/JointSpring.cs b/UnityEngine/UnityEngine/JointSpring.cs new file mode 100644 index 00000000..689faec0 --- /dev/null +++ b/UnityEngine/UnityEngine/JointSpring.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public struct JointSpring + { + public float spring; + public float damper; + public float targetPosition; + } +} diff --git a/UnityEngine/UnityEngine/JointSuspension2D.cs b/UnityEngine/UnityEngine/JointSuspension2D.cs new file mode 100644 index 00000000..09303692 --- /dev/null +++ b/UnityEngine/UnityEngine/JointSuspension2D.cs @@ -0,0 +1,43 @@ +using System; +namespace UnityEngine +{ + public struct JointSuspension2D + { + private float m_DampingRatio; + private float m_Frequency; + private float m_Angle; + public float dampingRatio + { + get + { + return this.m_DampingRatio; + } + set + { + this.m_DampingRatio = value; + } + } + public float frequency + { + get + { + return this.m_Frequency; + } + set + { + this.m_Frequency = value; + } + } + public float angle + { + get + { + return this.m_Angle; + } + set + { + this.m_Angle = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/JointTranslationLimits2D.cs b/UnityEngine/UnityEngine/JointTranslationLimits2D.cs new file mode 100644 index 00000000..3d775cb8 --- /dev/null +++ b/UnityEngine/UnityEngine/JointTranslationLimits2D.cs @@ -0,0 +1,31 @@ +using System; +namespace UnityEngine +{ + public struct JointTranslationLimits2D + { + private float m_LowerTranslation; + private float m_UpperTranslation; + public float min + { + get + { + return this.m_LowerTranslation; + } + set + { + this.m_LowerTranslation = value; + } + } + public float max + { + get + { + return this.m_UpperTranslation; + } + set + { + this.m_UpperTranslation = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/KeyCode.cs b/UnityEngine/UnityEngine/KeyCode.cs new file mode 100644 index 00000000..f755753f --- /dev/null +++ b/UnityEngine/UnityEngine/KeyCode.cs @@ -0,0 +1,248 @@ +using System; +namespace UnityEngine +{ + public enum KeyCode + { + None, + Backspace = 8, + Delete = 127, + Tab = 9, + Clear = 12, + Return, + Pause = 19, + Escape = 27, + Space = 32, + Keypad0 = 256, + Keypad1, + Keypad2, + Keypad3, + Keypad4, + Keypad5, + Keypad6, + Keypad7, + Keypad8, + Keypad9, + KeypadPeriod, + KeypadDivide, + KeypadMultiply, + KeypadMinus, + KeypadPlus, + KeypadEnter, + KeypadEquals, + UpArrow, + DownArrow, + RightArrow, + LeftArrow, + Insert, + Home, + End, + PageUp, + PageDown, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + Alpha0 = 48, + Alpha1, + Alpha2, + Alpha3, + Alpha4, + Alpha5, + Alpha6, + Alpha7, + Alpha8, + Alpha9, + Exclaim = 33, + DoubleQuote, + Hash, + Dollar, + Ampersand = 38, + Quote, + LeftParen, + RightParen, + Asterisk, + Plus, + Comma, + Minus, + Period, + Slash, + Colon = 58, + Semicolon, + Less, + Equals, + Greater, + Question, + At, + LeftBracket = 91, + Backslash, + RightBracket, + Caret, + Underscore, + BackQuote, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + Numlock = 300, + CapsLock, + ScrollLock, + RightShift, + LeftShift, + RightControl, + LeftControl, + RightAlt, + LeftAlt, + LeftCommand = 310, + LeftApple = 310, + LeftWindows, + RightCommand = 309, + RightApple = 309, + RightWindows = 312, + AltGr, + Help = 315, + Print, + SysReq, + Break, + Menu, + Mouse0 = 323, + Mouse1, + Mouse2, + Mouse3, + Mouse4, + Mouse5, + Mouse6, + JoystickButton0, + JoystickButton1, + JoystickButton2, + JoystickButton3, + JoystickButton4, + JoystickButton5, + JoystickButton6, + JoystickButton7, + JoystickButton8, + JoystickButton9, + JoystickButton10, + JoystickButton11, + JoystickButton12, + JoystickButton13, + JoystickButton14, + JoystickButton15, + JoystickButton16, + JoystickButton17, + JoystickButton18, + JoystickButton19, + Joystick1Button0, + Joystick1Button1, + Joystick1Button2, + Joystick1Button3, + Joystick1Button4, + Joystick1Button5, + Joystick1Button6, + Joystick1Button7, + Joystick1Button8, + Joystick1Button9, + Joystick1Button10, + Joystick1Button11, + Joystick1Button12, + Joystick1Button13, + Joystick1Button14, + Joystick1Button15, + Joystick1Button16, + Joystick1Button17, + Joystick1Button18, + Joystick1Button19, + Joystick2Button0, + Joystick2Button1, + Joystick2Button2, + Joystick2Button3, + Joystick2Button4, + Joystick2Button5, + Joystick2Button6, + Joystick2Button7, + Joystick2Button8, + Joystick2Button9, + Joystick2Button10, + Joystick2Button11, + Joystick2Button12, + Joystick2Button13, + Joystick2Button14, + Joystick2Button15, + Joystick2Button16, + Joystick2Button17, + Joystick2Button18, + Joystick2Button19, + Joystick3Button0, + Joystick3Button1, + Joystick3Button2, + Joystick3Button3, + Joystick3Button4, + Joystick3Button5, + Joystick3Button6, + Joystick3Button7, + Joystick3Button8, + Joystick3Button9, + Joystick3Button10, + Joystick3Button11, + Joystick3Button12, + Joystick3Button13, + Joystick3Button14, + Joystick3Button15, + Joystick3Button16, + Joystick3Button17, + Joystick3Button18, + Joystick3Button19, + Joystick4Button0, + Joystick4Button1, + Joystick4Button2, + Joystick4Button3, + Joystick4Button4, + Joystick4Button5, + Joystick4Button6, + Joystick4Button7, + Joystick4Button8, + Joystick4Button9, + Joystick4Button10, + Joystick4Button11, + Joystick4Button12, + Joystick4Button13, + Joystick4Button14, + Joystick4Button15, + Joystick4Button16, + Joystick4Button17, + Joystick4Button18, + Joystick4Button19 + } +} diff --git a/UnityEngine/UnityEngine/Keyframe.cs b/UnityEngine/UnityEngine/Keyframe.cs new file mode 100644 index 00000000..f0355b3d --- /dev/null +++ b/UnityEngine/UnityEngine/Keyframe.cs @@ -0,0 +1,83 @@ +using System; +namespace UnityEngine +{ + public struct Keyframe + { + private float m_Time; + private float m_Value; + private float m_InTangent; + private float m_OutTangent; + private int m_TangentMode; + public float time + { + get + { + return this.m_Time; + } + set + { + this.m_Time = value; + } + } + public float value + { + get + { + return this.m_Value; + } + set + { + this.m_Value = value; + } + } + public float inTangent + { + get + { + return this.m_InTangent; + } + set + { + this.m_InTangent = value; + } + } + public float outTangent + { + get + { + return this.m_OutTangent; + } + set + { + this.m_OutTangent = value; + } + } + public int tangentMode + { + get + { + return this.m_TangentMode; + } + set + { + this.m_TangentMode = value; + } + } + public Keyframe(float time, float value) + { + this.m_Time = time; + this.m_Value = value; + this.m_InTangent = 0f; + this.m_OutTangent = 0f; + this.m_TangentMode = 0; + } + public Keyframe(float time, float value, float inTangent, float outTangent) + { + this.m_Time = time; + this.m_Value = value; + this.m_InTangent = inTangent; + this.m_OutTangent = outTangent; + this.m_TangentMode = 0; + } + } +} diff --git a/UnityEngine/UnityEngine/LOD.cs b/UnityEngine/UnityEngine/LOD.cs new file mode 100644 index 00000000..82bc16cb --- /dev/null +++ b/UnityEngine/UnityEngine/LOD.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public struct LOD + { + public float screenRelativeTransitionHeight; + public Renderer[] renderers; + public LOD(float screenRelativeTransitionHeight, Renderer[] renderers) + { + this.screenRelativeTransitionHeight = screenRelativeTransitionHeight; + this.renderers = renderers; + } + } +} diff --git a/UnityEngine/UnityEngine/LODGroup.cs b/UnityEngine/UnityEngine/LODGroup.cs new file mode 100644 index 00000000..aebc5ff3 --- /dev/null +++ b/UnityEngine/UnityEngine/LODGroup.cs @@ -0,0 +1,60 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LODGroup : Component + { + public Vector3 localReferencePoint + { + get + { + Vector3 result; + this.INTERNAL_get_localReferencePoint(out result); + return result; + } + set + { + this.INTERNAL_set_localReferencePoint(ref value); + } + } + public extern float size + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int lodCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localReferencePoint(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localReferencePoint(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RecalculateBounds(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetLODS(LOD[] scriptingLODs); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ForceLOD(int index); + } +} diff --git a/UnityEngine/UnityEngine/LayerMask.cs b/UnityEngine/UnityEngine/LayerMask.cs new file mode 100644 index 00000000..a7157443 --- /dev/null +++ b/UnityEngine/UnityEngine/LayerMask.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct LayerMask + { + private int m_Mask; + public int value + { + get + { + return this.m_Mask; + } + set + { + this.m_Mask = value; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string LayerToName(int layer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int NameToLayer(string layerName); + public static int GetMask(params string[] layerNames) + { + int num = 0; + for (int i = 0; i < layerNames.Length; i++) + { + string layerName = layerNames[i]; + int num2 = LayerMask.NameToLayer(layerName); + if (num2 != 0) + { + num |= 1 << num2; + } + } + return num; + } + public static implicit operator int(LayerMask mask) + { + return mask.m_Mask; + } + public static implicit operator LayerMask(int intVal) + { + LayerMask result; + result.m_Mask = intVal; + return result; + } + } +} diff --git a/UnityEngine/UnityEngine/LegDoF.cs b/UnityEngine/UnityEngine/LegDoF.cs new file mode 100644 index 00000000..28e049d8 --- /dev/null +++ b/UnityEngine/UnityEngine/LegDoF.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + internal enum LegDoF + { + UpperLegFrontBack, + UpperLegInOut, + UpperLegRollInOut, + LegCloseOpen, + LegRollInOut, + FootCloseOpen, + FootInOut, + ToesUpDown, + LastLegDoF + } +} diff --git a/UnityEngine/UnityEngine/LensFlare.cs b/UnityEngine/UnityEngine/LensFlare.cs new file mode 100644 index 00000000..38bfff88 --- /dev/null +++ b/UnityEngine/UnityEngine/LensFlare.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LensFlare : Behaviour + { + public extern Flare flare + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float brightness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float fadeSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/Light.cs b/UnityEngine/UnityEngine/Light.cs new file mode 100644 index 00000000..88917cfc --- /dev/null +++ b/UnityEngine/UnityEngine/Light.cs @@ -0,0 +1,227 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Light : Behaviour + { + public extern LightType type + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + public extern float intensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern LightShadows shadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float shadowStrength + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float shadowBias + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float shadowSoftness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float shadowSoftnessFade + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float range + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float spotAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float cookieSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Texture cookie + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Flare flare + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern LightRenderMode renderMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool alreadyLightmapped + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int cullingMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 areaSize + { + get + { + Vector2 result; + this.INTERNAL_get_areaSize(out result); + return result; + } + set + { + this.INTERNAL_set_areaSize(ref value); + } + } + [Obsolete("Use QualitySettings.pixelLightCount instead.")] + public static extern int pixelLightCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("light.shadowConstantBias was removed, use light.shadowBias", true)] + public float shadowConstantBias + { + get + { + return 0f; + } + set + { + } + } + [Obsolete("light.shadowObjectSizeBias was removed, use light.shadowBias", true)] + public float shadowObjectSizeBias + { + get + { + return 0f; + } + set + { + } + } + [Obsolete("light.attenuate was removed; all lights always attenuate now", true)] + public bool attenuate + { + get + { + return true; + } + set + { + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_areaSize(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_areaSize(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Light[] GetLights(LightType type, int layer); + } +} diff --git a/UnityEngine/UnityEngine/LightProbeGroup.cs b/UnityEngine/UnityEngine/LightProbeGroup.cs new file mode 100644 index 00000000..e20b4d53 --- /dev/null +++ b/UnityEngine/UnityEngine/LightProbeGroup.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LightProbeGroup : Component + { + public extern Vector3[] probePositions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/LightProbes.cs b/UnityEngine/UnityEngine/LightProbes.cs new file mode 100644 index 00000000..9612a756 --- /dev/null +++ b/UnityEngine/UnityEngine/LightProbes.cs @@ -0,0 +1,42 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LightProbes : Object + { + public extern Vector3[] positions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float[] coefficients + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int count + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int cellCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public void GetInterpolatedLightProbe(Vector3 position, Renderer renderer, float[] coefficients) + { + LightProbes.INTERNAL_CALL_GetInterpolatedLightProbe(this, ref position, renderer, coefficients); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_GetInterpolatedLightProbe(LightProbes self, ref Vector3 position, Renderer renderer, float[] coefficients); + } +} diff --git a/UnityEngine/UnityEngine/LightRenderMode.cs b/UnityEngine/UnityEngine/LightRenderMode.cs new file mode 100644 index 00000000..1f8a7ad1 --- /dev/null +++ b/UnityEngine/UnityEngine/LightRenderMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum LightRenderMode + { + Auto, + ForcePixel, + ForceVertex + } +} diff --git a/UnityEngine/UnityEngine/LightShadows.cs b/UnityEngine/UnityEngine/LightShadows.cs new file mode 100644 index 00000000..0c36a94a --- /dev/null +++ b/UnityEngine/UnityEngine/LightShadows.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum LightShadows + { + None, + Hard, + Soft + } +} diff --git a/UnityEngine/UnityEngine/LightType.cs b/UnityEngine/UnityEngine/LightType.cs new file mode 100644 index 00000000..7d084117 --- /dev/null +++ b/UnityEngine/UnityEngine/LightType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum LightType + { + Spot, + Directional, + Point, + Area + } +} diff --git a/UnityEngine/UnityEngine/LightmapData.cs b/UnityEngine/UnityEngine/LightmapData.cs new file mode 100644 index 00000000..d8967ccb --- /dev/null +++ b/UnityEngine/UnityEngine/LightmapData.cs @@ -0,0 +1,45 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class LightmapData + { + internal Texture2D m_Lightmap; + internal Texture2D m_IndirectLightmap; + public Texture2D lightmapFar + { + get + { + return this.m_Lightmap; + } + set + { + this.m_Lightmap = value; + } + } + [Obsolete("Use lightmapFar instead")] + public Texture2D lightmap + { + get + { + return this.m_Lightmap; + } + set + { + this.m_Lightmap = value; + } + } + public Texture2D lightmapNear + { + get + { + return this.m_IndirectLightmap; + } + set + { + this.m_IndirectLightmap = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/LightmapSettings.cs b/UnityEngine/UnityEngine/LightmapSettings.cs new file mode 100644 index 00000000..fe3efbff --- /dev/null +++ b/UnityEngine/UnityEngine/LightmapSettings.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LightmapSettings : Object + { + public static extern LightmapData[] lightmaps + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern LightmapsMode lightmapsMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ColorSpace bakedColorSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern LightProbes lightProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/LightmapsMode.cs b/UnityEngine/UnityEngine/LightmapsMode.cs new file mode 100644 index 00000000..482fb43e --- /dev/null +++ b/UnityEngine/UnityEngine/LightmapsMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum LightmapsMode + { + Single, + Dual, + Directional + } +} diff --git a/UnityEngine/UnityEngine/LineRenderer.cs b/UnityEngine/UnityEngine/LineRenderer.cs new file mode 100644 index 00000000..634eec2c --- /dev/null +++ b/UnityEngine/UnityEngine/LineRenderer.cs @@ -0,0 +1,45 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LineRenderer : Renderer + { + public extern bool useWorldSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public void SetWidth(float start, float end) + { + LineRenderer.INTERNAL_CALL_SetWidth(this, start, end); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetWidth(LineRenderer self, float start, float end); + public void SetColors(Color start, Color end) + { + LineRenderer.INTERNAL_CALL_SetColors(this, ref start, ref end); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetColors(LineRenderer self, ref Color start, ref Color end); + public void SetVertexCount(int count) + { + LineRenderer.INTERNAL_CALL_SetVertexCount(this, count); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetVertexCount(LineRenderer self, int count); + public void SetPosition(int index, Vector3 position) + { + LineRenderer.INTERNAL_CALL_SetPosition(this, index, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetPosition(LineRenderer self, int index, ref Vector3 position); + } +} diff --git a/UnityEngine/UnityEngine/LocalNotification.cs b/UnityEngine/UnityEngine/LocalNotification.cs new file mode 100644 index 00000000..eecb48bb --- /dev/null +++ b/UnityEngine/UnityEngine/LocalNotification.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class LocalNotification + { + private IntPtr notificationWrapper; + private static long m_NSReferenceDateTicks; + public DateTime fireDate + { + get + { + return new DateTime((long)(this.GetFireDate() * 10000000.0) + LocalNotification.m_NSReferenceDateTicks); + } + set + { + this.SetFireDate((double)(value.ToUniversalTime().Ticks - LocalNotification.m_NSReferenceDateTicks) / 10000000.0); + } + } + public extern string timeZone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CalendarUnit repeatInterval + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CalendarIdentifier repeatCalendar + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertLaunchImage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int applicationIconBadgeNumber + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string soundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string defaultSoundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern IDictionary userInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public LocalNotification() + { + this.InitWrapper(); + } + static LocalNotification() + { + // Note: this type is marked as 'beforefieldinit'. + DateTime dateTime = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); + LocalNotification.m_NSReferenceDateTicks = dateTime.Ticks; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern double GetFireDate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFireDate(double dt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~LocalNotification() + { + this.Destroy(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InitWrapper(); + } +} diff --git a/UnityEngine/UnityEngine/LocalNotificationType.cs b/UnityEngine/UnityEngine/LocalNotificationType.cs new file mode 100644 index 00000000..ec352b64 --- /dev/null +++ b/UnityEngine/UnityEngine/LocalNotificationType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum LocalNotificationType + { + None, + Badge, + Sound, + Alert = 4 + } +} diff --git a/UnityEngine/UnityEngine/LocationInfo.cs b/UnityEngine/UnityEngine/LocationInfo.cs new file mode 100644 index 00000000..ea1efc9f --- /dev/null +++ b/UnityEngine/UnityEngine/LocationInfo.cs @@ -0,0 +1,55 @@ +using System; +namespace UnityEngine +{ + public struct LocationInfo + { + private double m_Timestamp; + private float m_Latitude; + private float m_Longitude; + private float m_Altitude; + private float m_HorizontalAccuracy; + private float m_VerticalAccuracy; + public float latitude + { + get + { + return this.m_Latitude; + } + } + public float longitude + { + get + { + return this.m_Longitude; + } + } + public float altitude + { + get + { + return this.m_Altitude; + } + } + public float horizontalAccuracy + { + get + { + return this.m_HorizontalAccuracy; + } + } + public float verticalAccuracy + { + get + { + return this.m_VerticalAccuracy; + } + } + public double timestamp + { + get + { + return this.m_Timestamp; + } + } + } +} diff --git a/UnityEngine/UnityEngine/LocationService.cs b/UnityEngine/UnityEngine/LocationService.cs new file mode 100644 index 00000000..5e2d6552 --- /dev/null +++ b/UnityEngine/UnityEngine/LocationService.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class LocationService + { + public extern bool isEnabledByUser + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern LocationServiceStatus status + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern LocationInfo lastData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Start([DefaultValue("10f")] float desiredAccuracyInMeters, [DefaultValue("10f")] float updateDistanceInMeters); + [ExcludeFromDocs] + public void Start(float desiredAccuracyInMeters) + { + float updateDistanceInMeters = 10f; + this.Start(desiredAccuracyInMeters, updateDistanceInMeters); + } + [ExcludeFromDocs] + public void Start() + { + float updateDistanceInMeters = 10f; + float desiredAccuracyInMeters = 10f; + this.Start(desiredAccuracyInMeters, updateDistanceInMeters); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Stop(); + } +} diff --git a/UnityEngine/UnityEngine/LocationServiceStatus.cs b/UnityEngine/UnityEngine/LocationServiceStatus.cs new file mode 100644 index 00000000..2e3b984a --- /dev/null +++ b/UnityEngine/UnityEngine/LocationServiceStatus.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum LocationServiceStatus + { + Stopped, + Initializing, + Running, + Failed + } +} diff --git a/UnityEngine/UnityEngine/LogType.cs b/UnityEngine/UnityEngine/LogType.cs new file mode 100644 index 00000000..40e29997 --- /dev/null +++ b/UnityEngine/UnityEngine/LogType.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum LogType + { + Error, + Assert, + Warning, + Log, + Exception + } +} diff --git a/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs b/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs new file mode 100644 index 00000000..05dc46d4 --- /dev/null +++ b/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs @@ -0,0 +1,9 @@ +using System; +using System.Diagnostics; +namespace UnityEngine +{ + [Conditional("UNITY_FLASH"), Conditional("UNITY_WINRT")] + internal class MarshallOnlyFirstField : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/MasterServer.cs b/UnityEngine/UnityEngine/MasterServer.cs new file mode 100644 index 00000000..64424c0e --- /dev/null +++ b/UnityEngine/UnityEngine/MasterServer.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class MasterServer + { + public static extern string ipAddress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int port + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int updateRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool dedicatedServer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RequestHostList(string gameTypeName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern HostData[] PollHostList(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterHost(string gameTypeName, string gameName, [DefaultValue("\"\"")] string comment); + [ExcludeFromDocs] + public static void RegisterHost(string gameTypeName, string gameName) + { + string empty = string.Empty; + MasterServer.RegisterHost(gameTypeName, gameName, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnregisterHost(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearHostList(); + } +} diff --git a/UnityEngine/UnityEngine/MasterServerEvent.cs b/UnityEngine/UnityEngine/MasterServerEvent.cs new file mode 100644 index 00000000..a341f9bd --- /dev/null +++ b/UnityEngine/UnityEngine/MasterServerEvent.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum MasterServerEvent + { + RegistrationFailedGameName, + RegistrationFailedGameType, + RegistrationFailedNoServer, + RegistrationSucceeded, + HostListReceived + } +} diff --git a/UnityEngine/UnityEngine/MatchTargetWeightMask.cs b/UnityEngine/UnityEngine/MatchTargetWeightMask.cs new file mode 100644 index 00000000..c99972d7 --- /dev/null +++ b/UnityEngine/UnityEngine/MatchTargetWeightMask.cs @@ -0,0 +1,36 @@ +using System; +namespace UnityEngine +{ + public struct MatchTargetWeightMask + { + private Vector3 m_PositionXYZWeight; + private float m_RotationWeight; + public Vector3 positionXYZWeight + { + get + { + return this.m_PositionXYZWeight; + } + set + { + this.m_PositionXYZWeight = value; + } + } + public float rotationWeight + { + get + { + return this.m_RotationWeight; + } + set + { + this.m_RotationWeight = value; + } + } + public MatchTargetWeightMask(Vector3 positionXYZWeight, float rotationWeight) + { + this.m_PositionXYZWeight = positionXYZWeight; + this.m_RotationWeight = rotationWeight; + } + } +} diff --git a/UnityEngine/UnityEngine/Material.cs b/UnityEngine/UnityEngine/Material.cs new file mode 100644 index 00000000..2fef9a14 --- /dev/null +++ b/UnityEngine/UnityEngine/Material.cs @@ -0,0 +1,276 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class Material : Object + { + public extern Shader shader + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color color + { + get + { + return this.GetColor("_Color"); + } + set + { + this.SetColor("_Color", value); + } + } + public Texture mainTexture + { + get + { + return this.GetTexture("_MainTex"); + } + set + { + this.SetTexture("_MainTex", value); + } + } + public Vector2 mainTextureOffset + { + get + { + return this.GetTextureOffset("_MainTex"); + } + set + { + this.SetTextureOffset("_MainTex", value); + } + } + public Vector2 mainTextureScale + { + get + { + return this.GetTextureScale("_MainTex"); + } + set + { + this.SetTextureScale("_MainTex", value); + } + } + public extern int passCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int renderQueue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string[] shaderKeywords + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Material(string contents) + { + Material.Internal_CreateWithString(this, contents); + } + public Material(Shader shader) + { + Material.Internal_CreateWithShader(this, shader); + } + public Material(Material source) + { + Material.Internal_CreateWithMaterial(this, source); + } + public void SetColor(string propertyName, Color color) + { + this.SetColor(Shader.PropertyToID(propertyName), color); + } + public void SetColor(int nameID, Color color) + { + Material.INTERNAL_CALL_SetColor(this, nameID, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetColor(Material self, int nameID, ref Color color); + public Color GetColor(string propertyName) + { + return this.GetColor(Shader.PropertyToID(propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetColor(int nameID); + public void SetVector(string propertyName, Vector4 vector) + { + this.SetColor(propertyName, new Color(vector.x, vector.y, vector.z, vector.w)); + } + public void SetVector(int nameID, Vector4 vector) + { + this.SetColor(nameID, new Color(vector.x, vector.y, vector.z, vector.w)); + } + public Vector4 GetVector(string propertyName) + { + Color color = this.GetColor(propertyName); + return new Vector4(color.r, color.g, color.b, color.a); + } + public Vector4 GetVector(int nameID) + { + Color color = this.GetColor(nameID); + return new Vector4(color.r, color.g, color.b, color.a); + } + public void SetTexture(string propertyName, Texture texture) + { + this.SetTexture(Shader.PropertyToID(propertyName), texture); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTexture(int nameID, Texture texture); + public Texture GetTexture(string propertyName) + { + return this.GetTexture(Shader.PropertyToID(propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture GetTexture(int nameID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTextureOffset(Material mat, string name, out Vector2 output); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTextureScale(Material mat, string name, out Vector2 output); + public void SetTextureOffset(string propertyName, Vector2 offset) + { + Material.INTERNAL_CALL_SetTextureOffset(this, propertyName, ref offset); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetTextureOffset(Material self, string propertyName, ref Vector2 offset); + public Vector2 GetTextureOffset(string propertyName) + { + Vector2 result; + Material.Internal_GetTextureOffset(this, propertyName, out result); + return result; + } + public void SetTextureScale(string propertyName, Vector2 scale) + { + Material.INTERNAL_CALL_SetTextureScale(this, propertyName, ref scale); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetTextureScale(Material self, string propertyName, ref Vector2 scale); + public Vector2 GetTextureScale(string propertyName) + { + Vector2 result; + Material.Internal_GetTextureScale(this, propertyName, out result); + return result; + } + public void SetMatrix(string propertyName, Matrix4x4 matrix) + { + this.SetMatrix(Shader.PropertyToID(propertyName), matrix); + } + public void SetMatrix(int nameID, Matrix4x4 matrix) + { + Material.INTERNAL_CALL_SetMatrix(this, nameID, ref matrix); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetMatrix(Material self, int nameID, ref Matrix4x4 matrix); + public Matrix4x4 GetMatrix(string propertyName) + { + return this.GetMatrix(Shader.PropertyToID(propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Matrix4x4 GetMatrix(int nameID); + public void SetFloat(string propertyName, float value) + { + this.SetFloat(Shader.PropertyToID(propertyName), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetFloat(int nameID, float value); + public float GetFloat(string propertyName) + { + return this.GetFloat(Shader.PropertyToID(propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetFloat(int nameID); + public void SetInt(string propertyName, int value) + { + this.SetFloat(propertyName, (float)value); + } + public void SetInt(int nameID, int value) + { + this.SetFloat(nameID, (float)value); + } + public int GetInt(string propertyName) + { + return (int)this.GetFloat(propertyName); + } + public int GetInt(int nameID) + { + return (int)this.GetFloat(nameID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetBuffer(string propertyName, ComputeBuffer buffer); + public bool HasProperty(string propertyName) + { + return this.HasProperty(Shader.PropertyToID(propertyName)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool HasProperty(int nameID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetTag(string tag, bool searchFallbacks, [DefaultValue("\"\"")] string defaultValue); + [ExcludeFromDocs] + public string GetTag(string tag, bool searchFallbacks) + { + string empty = string.Empty; + return this.GetTag(tag, searchFallbacks, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Lerp(Material start, Material end, float t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SetPass(int pass); + [Obsolete("Use the Material constructor instead.")] + public static Material Create(string scriptContents) + { + return new Material(scriptContents); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateWithString([Writable] Material mono, string contents); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateWithShader([Writable] Material mono, Shader shader); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateWithMaterial([Writable] Material mono, Material source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CopyPropertiesFromMaterial(Material mat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void EnableKeyword(string keyword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DisableKeyword(string keyword); + } +} diff --git a/UnityEngine/UnityEngine/MaterialPropertyBlock.cs b/UnityEngine/UnityEngine/MaterialPropertyBlock.cs new file mode 100644 index 00000000..516c18df --- /dev/null +++ b/UnityEngine/UnityEngine/MaterialPropertyBlock.cs @@ -0,0 +1,148 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class MaterialPropertyBlock + { + internal IntPtr m_Ptr; + public MaterialPropertyBlock() + { + this.InitBlock(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void InitBlock(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void DestroyBlock(); + ~MaterialPropertyBlock() + { + this.DestroyBlock(); + } + public void SetFloat(string name, float value) + { + this.SetFloat(Shader.PropertyToID(name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetFloat(int nameID, float value); + public void SetVector(string name, Vector4 value) + { + this.SetVector(Shader.PropertyToID(name), value); + } + public void SetVector(int nameID, Vector4 value) + { + MaterialPropertyBlock.INTERNAL_CALL_SetVector(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetVector(MaterialPropertyBlock self, int nameID, ref Vector4 value); + public void SetColor(string name, Color value) + { + this.SetColor(Shader.PropertyToID(name), value); + } + public void SetColor(int nameID, Color value) + { + MaterialPropertyBlock.INTERNAL_CALL_SetColor(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetColor(MaterialPropertyBlock self, int nameID, ref Color value); + public void SetMatrix(string name, Matrix4x4 value) + { + this.SetMatrix(Shader.PropertyToID(name), value); + } + public void SetMatrix(int nameID, Matrix4x4 value) + { + MaterialPropertyBlock.INTERNAL_CALL_SetMatrix(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetMatrix(MaterialPropertyBlock self, int nameID, ref Matrix4x4 value); + public void SetTexture(string name, Texture value) + { + this.SetTexture(Shader.PropertyToID(name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTexture(int nameID, Texture value); + public void AddFloat(string name, float value) + { + this.AddFloat(Shader.PropertyToID(name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddFloat(int nameID, float value); + public void AddVector(string name, Vector4 value) + { + this.AddVector(Shader.PropertyToID(name), value); + } + public void AddVector(int nameID, Vector4 value) + { + MaterialPropertyBlock.INTERNAL_CALL_AddVector(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddVector(MaterialPropertyBlock self, int nameID, ref Vector4 value); + public void AddColor(string name, Color value) + { + this.AddColor(Shader.PropertyToID(name), value); + } + public void AddColor(int nameID, Color value) + { + MaterialPropertyBlock.INTERNAL_CALL_AddColor(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddColor(MaterialPropertyBlock self, int nameID, ref Color value); + public void AddMatrix(string name, Matrix4x4 value) + { + this.AddMatrix(Shader.PropertyToID(name), value); + } + public void AddMatrix(int nameID, Matrix4x4 value) + { + MaterialPropertyBlock.INTERNAL_CALL_AddMatrix(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddMatrix(MaterialPropertyBlock self, int nameID, ref Matrix4x4 value); + public void AddTexture(string name, Texture value) + { + this.AddTexture(Shader.PropertyToID(name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddTexture(int nameID, Texture value); + public float GetFloat(string name) + { + return this.GetFloat(Shader.PropertyToID(name)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetFloat(int nameID); + public Vector4 GetVector(string name) + { + return this.GetVector(Shader.PropertyToID(name)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector4 GetVector(int nameID); + public Matrix4x4 GetMatrix(string name) + { + return this.GetMatrix(Shader.PropertyToID(name)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Matrix4x4 GetMatrix(int nameID); + public Texture GetTexture(string name) + { + return this.GetTexture(Shader.PropertyToID(name)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture GetTexture(int nameID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Clear(); + } +} diff --git a/UnityEngine/UnityEngine/Mathf.cs b/UnityEngine/UnityEngine/Mathf.cs new file mode 100644 index 00000000..609da9f6 --- /dev/null +++ b/UnityEngine/UnityEngine/Mathf.cs @@ -0,0 +1,444 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public struct Mathf + { + public const float PI = 3.14159274f; + public const float Infinity = float.PositiveInfinity; + public const float NegativeInfinity = float.NegativeInfinity; + public const float Deg2Rad = 0.0174532924f; + public const float Rad2Deg = 57.29578f; + public const float Epsilon = 1.401298E-45f; + public static float Sin(float f) + { + return (float)Math.Sin((double)f); + } + public static float Cos(float f) + { + return (float)Math.Cos((double)f); + } + public static float Tan(float f) + { + return (float)Math.Tan((double)f); + } + public static float Asin(float f) + { + return (float)Math.Asin((double)f); + } + public static float Acos(float f) + { + return (float)Math.Acos((double)f); + } + public static float Atan(float f) + { + return (float)Math.Atan((double)f); + } + public static float Atan2(float y, float x) + { + return (float)Math.Atan2((double)y, (double)x); + } + public static float Sqrt(float f) + { + return (float)Math.Sqrt((double)f); + } + public static float Abs(float f) + { + return Math.Abs(f); + } + public static int Abs(int value) + { + return Math.Abs(value); + } + public static float Min(float a, float b) + { + return (a >= b) ? b : a; + } + public static float Min(params float[] values) + { + int num = values.Length; + if (num == 0) + { + return 0f; + } + float num2 = values[0]; + for (int i = 1; i < num; i++) + { + if (values[i] < num2) + { + num2 = values[i]; + } + } + return num2; + } + public static int Min(int a, int b) + { + return (a >= b) ? b : a; + } + public static int Min(params int[] values) + { + int num = values.Length; + if (num == 0) + { + return 0; + } + int num2 = values[0]; + for (int i = 1; i < num; i++) + { + if (values[i] < num2) + { + num2 = values[i]; + } + } + return num2; + } + public static float Max(float a, float b) + { + return (a <= b) ? b : a; + } + public static float Max(params float[] values) + { + int num = values.Length; + if (num == 0) + { + return 0f; + } + float num2 = values[0]; + for (int i = 1; i < num; i++) + { + if (values[i] > num2) + { + num2 = values[i]; + } + } + return num2; + } + public static int Max(int a, int b) + { + return (a <= b) ? b : a; + } + public static int Max(params int[] values) + { + int num = values.Length; + if (num == 0) + { + return 0; + } + int num2 = values[0]; + for (int i = 1; i < num; i++) + { + if (values[i] > num2) + { + num2 = values[i]; + } + } + return num2; + } + public static float Pow(float f, float p) + { + return (float)Math.Pow((double)f, (double)p); + } + public static float Exp(float power) + { + return (float)Math.Exp((double)power); + } + public static float Log(float f, float p) + { + return (float)Math.Log((double)f, (double)p); + } + public static float Log(float f) + { + return (float)Math.Log((double)f); + } + public static float Log10(float f) + { + return (float)Math.Log10((double)f); + } + public static float Ceil(float f) + { + return (float)Math.Ceiling((double)f); + } + public static float Floor(float f) + { + return (float)Math.Floor((double)f); + } + public static float Round(float f) + { + return (float)Math.Round((double)f); + } + public static int CeilToInt(float f) + { + return (int)Math.Ceiling((double)f); + } + public static int FloorToInt(float f) + { + return (int)Math.Floor((double)f); + } + public static int RoundToInt(float f) + { + return (int)Math.Round((double)f); + } + public static float Sign(float f) + { + return (f < 0f) ? -1f : 1f; + } + public static float Clamp(float value, float min, float max) + { + if (value < min) + { + value = min; + } + else + { + if (value > max) + { + value = max; + } + } + return value; + } + public static int Clamp(int value, int min, int max) + { + if (value < min) + { + value = min; + } + else + { + if (value > max) + { + value = max; + } + } + return value; + } + public static float Clamp01(float value) + { + if (value < 0f) + { + return 0f; + } + if (value > 1f) + { + return 1f; + } + return value; + } + public static float Lerp(float from, float to, float t) + { + return from + (to - from) * Mathf.Clamp01(t); + } + public static float LerpAngle(float a, float b, float t) + { + float num = Mathf.Repeat(b - a, 360f); + if (num > 180f) + { + num -= 360f; + } + return a + num * Mathf.Clamp01(t); + } + public static float MoveTowards(float current, float target, float maxDelta) + { + if (Mathf.Abs(target - current) <= maxDelta) + { + return target; + } + return current + Mathf.Sign(target - current) * maxDelta; + } + public static float MoveTowardsAngle(float current, float target, float maxDelta) + { + target = current + Mathf.DeltaAngle(current, target); + return Mathf.MoveTowards(current, target, maxDelta); + } + public static float SmoothStep(float from, float to, float t) + { + t = Mathf.Clamp01(t); + t = -2f * t * t * t + 3f * t * t; + return to * t + from * (1f - t); + } + public static float Gamma(float value, float absmax, float gamma) + { + bool flag = false; + if (value < 0f) + { + flag = true; + } + float num = Mathf.Abs(value); + if (num > absmax) + { + return (!flag) ? num : (-num); + } + float num2 = Mathf.Pow(num / absmax, gamma) * absmax; + return (!flag) ? num2 : (-num2); + } + public static bool Approximately(float a, float b) + { + return Mathf.Abs(b - a) < Mathf.Max(1E-06f * Mathf.Max(Mathf.Abs(a), Mathf.Abs(b)), 1.121039E-44f); + } + [ExcludeFromDocs] + public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) + { + float deltaTime = Time.deltaTime; + return Mathf.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + [ExcludeFromDocs] + public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime) + { + float deltaTime = Time.deltaTime; + float maxSpeed = float.PositiveInfinity; + return Mathf.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, [DefaultValue("Mathf.Infinity")] float maxSpeed, [DefaultValue("Time.deltaTime")] float deltaTime) + { + smoothTime = Mathf.Max(0.0001f, smoothTime); + float num = 2f / smoothTime; + float num2 = num * deltaTime; + float num3 = 1f / (1f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); + float num4 = current - target; + float num5 = target; + float num6 = maxSpeed * smoothTime; + num4 = Mathf.Clamp(num4, -num6, num6); + target = current - num4; + float num7 = (currentVelocity + num * num4) * deltaTime; + currentVelocity = (currentVelocity - num * num7) * num3; + float num8 = target + (num4 + num7) * num3; + if (num5 - current > 0f == num8 > num5) + { + num8 = num5; + currentVelocity = (num8 - num5) / deltaTime; + } + return num8; + } + [ExcludeFromDocs] + public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) + { + float deltaTime = Time.deltaTime; + return Mathf.SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + [ExcludeFromDocs] + public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime) + { + float deltaTime = Time.deltaTime; + float maxSpeed = float.PositiveInfinity; + return Mathf.SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, [DefaultValue("Mathf.Infinity")] float maxSpeed, [DefaultValue("Time.deltaTime")] float deltaTime) + { + target = current + Mathf.DeltaAngle(current, target); + return Mathf.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + public static float Repeat(float t, float length) + { + return t - Mathf.Floor(t / length) * length; + } + public static float PingPong(float t, float length) + { + t = Mathf.Repeat(t, length * 2f); + return length - Mathf.Abs(t - length); + } + public static float InverseLerp(float from, float to, float value) + { + if (from < to) + { + if (value < from) + { + return 0f; + } + if (value > to) + { + return 1f; + } + value -= from; + value /= to - from; + return value; + } + else + { + if (from <= to) + { + return 0f; + } + if (value < to) + { + return 1f; + } + if (value > from) + { + return 0f; + } + return 1f - (value - to) / (from - to); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int ClosestPowerOfTwo(int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GammaToLinearSpace(float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float LinearToGammaSpace(float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsPowerOfTwo(int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int NextPowerOfTwo(int value); + public static float DeltaAngle(float current, float target) + { + float num = Mathf.Repeat(target - current, 360f); + if (num > 180f) + { + num -= 360f; + } + return num; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float PerlinNoise(float x, float y); + internal static bool LineIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) + { + float num = p2.x - p1.x; + float num2 = p2.y - p1.y; + float num3 = p4.x - p3.x; + float num4 = p4.y - p3.y; + float num5 = num * num4 - num2 * num3; + if (num5 == 0f) + { + return false; + } + float num6 = p3.x - p1.x; + float num7 = p3.y - p1.y; + float num8 = (num6 * num4 - num7 * num3) / num5; + result = new Vector2(p1.x + num8 * num, p1.y + num8 * num2); + return true; + } + internal static bool LineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) + { + float num = p2.x - p1.x; + float num2 = p2.y - p1.y; + float num3 = p4.x - p3.x; + float num4 = p4.y - p3.y; + float num5 = num * num4 - num2 * num3; + if (num5 == 0f) + { + return false; + } + float num6 = p3.x - p1.x; + float num7 = p3.y - p1.y; + float num8 = (num6 * num4 - num7 * num3) / num5; + if (num8 < 0f || num8 > 1f) + { + return false; + } + float num9 = (num6 * num2 - num7 * num) / num5; + if (num9 < 0f || num9 > 1f) + { + return false; + } + result = new Vector2(p1.x + num8 * num, p1.y + num8 * num2); + return true; + } + } +} diff --git a/UnityEngine/UnityEngine/Matrix4x4.cs b/UnityEngine/UnityEngine/Matrix4x4.cs new file mode 100644 index 00000000..b1cc56e6 --- /dev/null +++ b/UnityEngine/UnityEngine/Matrix4x4.cs @@ -0,0 +1,411 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct Matrix4x4 + { + public float m00; + public float m10; + public float m20; + public float m30; + public float m01; + public float m11; + public float m21; + public float m31; + public float m02; + public float m12; + public float m22; + public float m32; + public float m03; + public float m13; + public float m23; + public float m33; + public float this[int row, int column] + { + get + { + return this[row + column * 4]; + } + set + { + this[row + column * 4] = value; + } + } + public float this[int index] + { + get + { + switch (index) + { + case 0: + return this.m00; + case 1: + return this.m10; + case 2: + return this.m20; + case 3: + return this.m30; + case 4: + return this.m01; + case 5: + return this.m11; + case 6: + return this.m21; + case 7: + return this.m31; + case 8: + return this.m02; + case 9: + return this.m12; + case 10: + return this.m22; + case 11: + return this.m32; + case 12: + return this.m03; + case 13: + return this.m13; + case 14: + return this.m23; + case 15: + return this.m33; + default: + throw new IndexOutOfRangeException("Invalid matrix index!"); + } + } + set + { + switch (index) + { + case 0: + this.m00 = value; + break; + case 1: + this.m10 = value; + break; + case 2: + this.m20 = value; + break; + case 3: + this.m30 = value; + break; + case 4: + this.m01 = value; + break; + case 5: + this.m11 = value; + break; + case 6: + this.m21 = value; + break; + case 7: + this.m31 = value; + break; + case 8: + this.m02 = value; + break; + case 9: + this.m12 = value; + break; + case 10: + this.m22 = value; + break; + case 11: + this.m32 = value; + break; + case 12: + this.m03 = value; + break; + case 13: + this.m13 = value; + break; + case 14: + this.m23 = value; + break; + case 15: + this.m33 = value; + break; + default: + throw new IndexOutOfRangeException("Invalid matrix index!"); + } + } + } + public Matrix4x4 inverse + { + get + { + return Matrix4x4.Inverse(this); + } + } + public Matrix4x4 transpose + { + get + { + return Matrix4x4.Transpose(this); + } + } + public extern bool isIdentity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Matrix4x4 zero + { + get + { + return new Matrix4x4 + { + m00 = 0f, + m01 = 0f, + m02 = 0f, + m03 = 0f, + m10 = 0f, + m11 = 0f, + m12 = 0f, + m13 = 0f, + m20 = 0f, + m21 = 0f, + m22 = 0f, + m23 = 0f, + m30 = 0f, + m31 = 0f, + m32 = 0f, + m33 = 0f + }; + } + } + public static Matrix4x4 identity + { + get + { + return new Matrix4x4 + { + m00 = 1f, + m01 = 0f, + m02 = 0f, + m03 = 0f, + m10 = 0f, + m11 = 1f, + m12 = 0f, + m13 = 0f, + m20 = 0f, + m21 = 0f, + m22 = 1f, + m23 = 0f, + m30 = 0f, + m31 = 0f, + m32 = 0f, + m33 = 1f + }; + } + } + public override int GetHashCode() + { + return this.GetColumn(0).GetHashCode() ^ this.GetColumn(1).GetHashCode() << 2 ^ this.GetColumn(2).GetHashCode() >> 2 ^ this.GetColumn(3).GetHashCode() >> 1; + } + public override bool Equals(object other) + { + if (!(other is Matrix4x4)) + { + return false; + } + Matrix4x4 matrix4x = (Matrix4x4)other; + return this.GetColumn(0).Equals(matrix4x.GetColumn(0)) && this.GetColumn(1).Equals(matrix4x.GetColumn(1)) && this.GetColumn(2).Equals(matrix4x.GetColumn(2)) && this.GetColumn(3).Equals(matrix4x.GetColumn(3)); + } + public static Matrix4x4 Inverse(Matrix4x4 m) + { + return Matrix4x4.INTERNAL_CALL_Inverse(ref m); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Matrix4x4 INTERNAL_CALL_Inverse(ref Matrix4x4 m); + public static Matrix4x4 Transpose(Matrix4x4 m) + { + return Matrix4x4.INTERNAL_CALL_Transpose(ref m); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Matrix4x4 INTERNAL_CALL_Transpose(ref Matrix4x4 m); + internal static bool Invert(Matrix4x4 inMatrix, out Matrix4x4 dest) + { + return Matrix4x4.INTERNAL_CALL_Invert(ref inMatrix, out dest); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Invert(ref Matrix4x4 inMatrix, out Matrix4x4 dest); + public Vector4 GetColumn(int i) + { + return new Vector4(this[0, i], this[1, i], this[2, i], this[3, i]); + } + public Vector4 GetRow(int i) + { + return new Vector4(this[i, 0], this[i, 1], this[i, 2], this[i, 3]); + } + public void SetColumn(int i, Vector4 v) + { + this[0, i] = v.x; + this[1, i] = v.y; + this[2, i] = v.z; + this[3, i] = v.w; + } + public void SetRow(int i, Vector4 v) + { + this[i, 0] = v.x; + this[i, 1] = v.y; + this[i, 2] = v.z; + this[i, 3] = v.w; + } + public Vector3 MultiplyPoint(Vector3 v) + { + Vector3 result; + result.x = this.m00 * v.x + this.m01 * v.y + this.m02 * v.z + this.m03; + result.y = this.m10 * v.x + this.m11 * v.y + this.m12 * v.z + this.m13; + result.z = this.m20 * v.x + this.m21 * v.y + this.m22 * v.z + this.m23; + float num = this.m30 * v.x + this.m31 * v.y + this.m32 * v.z + this.m33; + num = 1f / num; + result.x *= num; + result.y *= num; + result.z *= num; + return result; + } + public Vector3 MultiplyPoint3x4(Vector3 v) + { + Vector3 result; + result.x = this.m00 * v.x + this.m01 * v.y + this.m02 * v.z + this.m03; + result.y = this.m10 * v.x + this.m11 * v.y + this.m12 * v.z + this.m13; + result.z = this.m20 * v.x + this.m21 * v.y + this.m22 * v.z + this.m23; + return result; + } + public Vector3 MultiplyVector(Vector3 v) + { + Vector3 result; + result.x = this.m00 * v.x + this.m01 * v.y + this.m02 * v.z; + result.y = this.m10 * v.x + this.m11 * v.y + this.m12 * v.z; + result.z = this.m20 * v.x + this.m21 * v.y + this.m22 * v.z; + return result; + } + public static Matrix4x4 Scale(Vector3 v) + { + return new Matrix4x4 + { + m00 = v.x, + m01 = 0f, + m02 = 0f, + m03 = 0f, + m10 = 0f, + m11 = v.y, + m12 = 0f, + m13 = 0f, + m20 = 0f, + m21 = 0f, + m22 = v.z, + m23 = 0f, + m30 = 0f, + m31 = 0f, + m32 = 0f, + m33 = 1f + }; + } + public void SetTRS(Vector3 pos, Quaternion q, Vector3 s) + { + this = Matrix4x4.TRS(pos, q, s); + } + public static Matrix4x4 TRS(Vector3 pos, Quaternion q, Vector3 s) + { + return Matrix4x4.INTERNAL_CALL_TRS(ref pos, ref q, ref s); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Matrix4x4 INTERNAL_CALL_TRS(ref Vector3 pos, ref Quaternion q, ref Vector3 s); + public override string ToString() + { + return UnityString.Format("{0:F5}\t{1:F5}\t{2:F5}\t{3:F5}\n{4:F5}\t{5:F5}\t{6:F5}\t{7:F5}\n{8:F5}\t{9:F5}\t{10:F5}\t{11:F5}\n{12:F5}\t{13:F5}\t{14:F5}\t{15:F5}\n", new object[] + { + this.m00, + this.m01, + this.m02, + this.m03, + this.m10, + this.m11, + this.m12, + this.m13, + this.m20, + this.m21, + this.m22, + this.m23, + this.m30, + this.m31, + this.m32, + this.m33 + }); + } + public string ToString(string format) + { + return UnityString.Format("{0}\t{1}\t{2}\t{3}\n{4}\t{5}\t{6}\t{7}\n{8}\t{9}\t{10}\t{11}\n{12}\t{13}\t{14}\t{15}\n", new object[] + { + this.m00.ToString(format), + this.m01.ToString(format), + this.m02.ToString(format), + this.m03.ToString(format), + this.m10.ToString(format), + this.m11.ToString(format), + this.m12.ToString(format), + this.m13.ToString(format), + this.m20.ToString(format), + this.m21.ToString(format), + this.m22.ToString(format), + this.m23.ToString(format), + this.m30.ToString(format), + this.m31.ToString(format), + this.m32.ToString(format), + this.m33.ToString(format) + }); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Matrix4x4 Ortho(float left, float right, float bottom, float top, float zNear, float zFar); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Matrix4x4 Perspective(float fov, float aspect, float zNear, float zFar); + public static Matrix4x4 operator *(Matrix4x4 lhs, Matrix4x4 rhs) + { + return new Matrix4x4 + { + m00 = lhs.m00 * rhs.m00 + lhs.m01 * rhs.m10 + lhs.m02 * rhs.m20 + lhs.m03 * rhs.m30, + m01 = lhs.m00 * rhs.m01 + lhs.m01 * rhs.m11 + lhs.m02 * rhs.m21 + lhs.m03 * rhs.m31, + m02 = lhs.m00 * rhs.m02 + lhs.m01 * rhs.m12 + lhs.m02 * rhs.m22 + lhs.m03 * rhs.m32, + m03 = lhs.m00 * rhs.m03 + lhs.m01 * rhs.m13 + lhs.m02 * rhs.m23 + lhs.m03 * rhs.m33, + m10 = lhs.m10 * rhs.m00 + lhs.m11 * rhs.m10 + lhs.m12 * rhs.m20 + lhs.m13 * rhs.m30, + m11 = lhs.m10 * rhs.m01 + lhs.m11 * rhs.m11 + lhs.m12 * rhs.m21 + lhs.m13 * rhs.m31, + m12 = lhs.m10 * rhs.m02 + lhs.m11 * rhs.m12 + lhs.m12 * rhs.m22 + lhs.m13 * rhs.m32, + m13 = lhs.m10 * rhs.m03 + lhs.m11 * rhs.m13 + lhs.m12 * rhs.m23 + lhs.m13 * rhs.m33, + m20 = lhs.m20 * rhs.m00 + lhs.m21 * rhs.m10 + lhs.m22 * rhs.m20 + lhs.m23 * rhs.m30, + m21 = lhs.m20 * rhs.m01 + lhs.m21 * rhs.m11 + lhs.m22 * rhs.m21 + lhs.m23 * rhs.m31, + m22 = lhs.m20 * rhs.m02 + lhs.m21 * rhs.m12 + lhs.m22 * rhs.m22 + lhs.m23 * rhs.m32, + m23 = lhs.m20 * rhs.m03 + lhs.m21 * rhs.m13 + lhs.m22 * rhs.m23 + lhs.m23 * rhs.m33, + m30 = lhs.m30 * rhs.m00 + lhs.m31 * rhs.m10 + lhs.m32 * rhs.m20 + lhs.m33 * rhs.m30, + m31 = lhs.m30 * rhs.m01 + lhs.m31 * rhs.m11 + lhs.m32 * rhs.m21 + lhs.m33 * rhs.m31, + m32 = lhs.m30 * rhs.m02 + lhs.m31 * rhs.m12 + lhs.m32 * rhs.m22 + lhs.m33 * rhs.m32, + m33 = lhs.m30 * rhs.m03 + lhs.m31 * rhs.m13 + lhs.m32 * rhs.m23 + lhs.m33 * rhs.m33 + }; + } + public static Vector4 operator *(Matrix4x4 lhs, Vector4 v) + { + Vector4 result; + result.x = lhs.m00 * v.x + lhs.m01 * v.y + lhs.m02 * v.z + lhs.m03 * v.w; + result.y = lhs.m10 * v.x + lhs.m11 * v.y + lhs.m12 * v.z + lhs.m13 * v.w; + result.z = lhs.m20 * v.x + lhs.m21 * v.y + lhs.m22 * v.z + lhs.m23 * v.w; + result.w = lhs.m30 * v.x + lhs.m31 * v.y + lhs.m32 * v.z + lhs.m33 * v.w; + return result; + } + public static bool operator ==(Matrix4x4 lhs, Matrix4x4 rhs) + { + return lhs.GetColumn(0) == rhs.GetColumn(0) && lhs.GetColumn(1) == rhs.GetColumn(1) && lhs.GetColumn(2) == rhs.GetColumn(2) && lhs.GetColumn(3) == rhs.GetColumn(3); + } + public static bool operator !=(Matrix4x4 lhs, Matrix4x4 rhs) + { + return !(lhs == rhs); + } + } +} diff --git a/UnityEngine/UnityEngine/Mesh.cs b/UnityEngine/UnityEngine/Mesh.cs new file mode 100644 index 00000000..fc193980 --- /dev/null +++ b/UnityEngine/UnityEngine/Mesh.cs @@ -0,0 +1,236 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Mesh : Object + { + public extern bool isReadable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool canAccess + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3[] vertices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector3[] normals + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector4[] tangents + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector2[] uv + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector2[] uv2 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2[] uv1 + { + get + { + return this.uv2; + } + set + { + this.uv2 = value; + } + } + public Bounds bounds + { + get + { + Bounds result; + this.INTERNAL_get_bounds(out result); + return result; + } + set + { + this.INTERNAL_set_bounds(ref value); + } + } + public extern Color[] colors + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Color32[] colors32 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int[] triangles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int vertexCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int subMeshCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern BoneWeight[] boneWeights + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Matrix4x4[] bindposes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int blendShapeCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Mesh() + { + Mesh.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] Mesh mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Clear([DefaultValue("true")] bool keepVertexLayout); + [ExcludeFromDocs] + public void Clear() + { + bool keepVertexLayout = true; + this.Clear(keepVertexLayout); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bounds(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_bounds(ref Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RecalculateBounds(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RecalculateNormals(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Optimize(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[] GetTriangles(int submesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTriangles(int[] triangles, int submesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[] GetIndices(int submesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetIndices(int[] indices, MeshTopology topology, int submesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern MeshTopology GetTopology(int submesh); + [Obsolete("Use SetTriangles instead. Internally this function will convert the triangle strip to a list of triangles anyway."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetTriangleStrip(int[] triangles, int submesh); + [Obsolete("Use GetTriangles instead. Internally this function converts a list of triangles to a strip, so it might be slow, it might be a mess."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[] GetTriangleStrip(int submesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CombineMeshes(CombineInstance[] combine, [DefaultValue("true")] bool mergeSubMeshes, [DefaultValue("true")] bool useMatrices); + [ExcludeFromDocs] + public void CombineMeshes(CombineInstance[] combine, bool mergeSubMeshes) + { + bool useMatrices = true; + this.CombineMeshes(combine, mergeSubMeshes, useMatrices); + } + [ExcludeFromDocs] + public void CombineMeshes(CombineInstance[] combine) + { + bool useMatrices = true; + bool mergeSubMeshes = true; + this.CombineMeshes(combine, mergeSubMeshes, useMatrices); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void MarkDynamic(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UploadMeshData(bool markNoLogerReadable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetBlendShapeName(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetBlendShapeIndex(string blendShapeName); + } +} diff --git a/UnityEngine/UnityEngine/MeshCollider.cs b/UnityEngine/UnityEngine/MeshCollider.cs new file mode 100644 index 00000000..0c6359cf --- /dev/null +++ b/UnityEngine/UnityEngine/MeshCollider.cs @@ -0,0 +1,47 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class MeshCollider : Collider + { + [Obsolete("mesh has been replaced with sharedMesh and will be deprecated")] + public Mesh mesh + { + get + { + return this.sharedMesh; + } + set + { + this.sharedMesh = value; + } + } + public extern Mesh sharedMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool convex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool smoothSphereCollisions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/MeshFilter.cs b/UnityEngine/UnityEngine/MeshFilter.cs new file mode 100644 index 00000000..977fcaaf --- /dev/null +++ b/UnityEngine/UnityEngine/MeshFilter.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class MeshFilter : Component + { + public extern Mesh mesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Mesh sharedMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/MeshRenderer.cs b/UnityEngine/UnityEngine/MeshRenderer.cs new file mode 100644 index 00000000..a5f537ca --- /dev/null +++ b/UnityEngine/UnityEngine/MeshRenderer.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class MeshRenderer : Renderer + { + } +} diff --git a/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs b/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs new file mode 100644 index 00000000..f7aec954 --- /dev/null +++ b/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs @@ -0,0 +1,21 @@ +using System; +namespace UnityEngine +{ + internal class MeshSubsetCombineUtility + { + public struct MeshInstance + { + public int meshInstanceID; + public Matrix4x4 transform; + public Vector4 lightmapTilingOffset; + } + public struct SubMeshInstance + { + public int meshInstanceID; + public int vertexOffset; + public int gameObjectInstanceID; + public int subMeshIndex; + public Matrix4x4 transform; + } + } +} diff --git a/UnityEngine/UnityEngine/MeshTopology.cs b/UnityEngine/UnityEngine/MeshTopology.cs new file mode 100644 index 00000000..d164c038 --- /dev/null +++ b/UnityEngine/UnityEngine/MeshTopology.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum MeshTopology + { + Triangles, + Quads = 2, + Lines, + LineStrip, + Points + } +} diff --git a/UnityEngine/UnityEngine/Microphone.cs b/UnityEngine/UnityEngine/Microphone.cs new file mode 100644 index 00000000..493c0642 --- /dev/null +++ b/UnityEngine/UnityEngine/Microphone.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Microphone + { + public static extern string[] devices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AudioClip Start(string deviceName, bool loop, int lengthSec, int frequency); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void End(string deviceName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsRecording(string deviceName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetPosition(string deviceName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetDeviceCaps(string deviceName, out int minFreq, out int maxFreq); + } +} diff --git a/UnityEngine/UnityEngine/MissingComponentException.cs b/UnityEngine/UnityEngine/MissingComponentException.cs new file mode 100644 index 00000000..0c5922d6 --- /dev/null +++ b/UnityEngine/UnityEngine/MissingComponentException.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +namespace UnityEngine +{ + [Serializable] + public class MissingComponentException : SystemException + { + private const int Result = -2147467261; + private string unityStackTrace; + public MissingComponentException() : base("A Unity Runtime error occurred!") + { + base.HResult = -2147467261; + } + public MissingComponentException(string message) : base(message) + { + base.HResult = -2147467261; + } + public MissingComponentException(string message, Exception innerException) : base(message, innerException) + { + base.HResult = -2147467261; + } + protected MissingComponentException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} diff --git a/UnityEngine/UnityEngine/MissingReferenceException.cs b/UnityEngine/UnityEngine/MissingReferenceException.cs new file mode 100644 index 00000000..fca4b3bd --- /dev/null +++ b/UnityEngine/UnityEngine/MissingReferenceException.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +namespace UnityEngine +{ + [Serializable] + public class MissingReferenceException : SystemException + { + private const int Result = -2147467261; + private string unityStackTrace; + public MissingReferenceException() : base("A Unity Runtime error occurred!") + { + base.HResult = -2147467261; + } + public MissingReferenceException(string message) : base(message) + { + base.HResult = -2147467261; + } + public MissingReferenceException(string message, Exception innerException) : base(message, innerException) + { + base.HResult = -2147467261; + } + protected MissingReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} diff --git a/UnityEngine/UnityEngine/MonoBehaviour.cs b/UnityEngine/UnityEngine/MonoBehaviour.cs new file mode 100644 index 00000000..dcdbc800 --- /dev/null +++ b/UnityEngine/UnityEngine/MonoBehaviour.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class MonoBehaviour : Behaviour + { + public extern bool useGUILayout + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern MonoBehaviour(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_CancelInvokeAll(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_IsInvokingAll(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Invoke(string methodName, float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InvokeRepeating(string methodName, float time, float repeatRate); + public void CancelInvoke() + { + this.Internal_CancelInvokeAll(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CancelInvoke(string methodName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsInvoking(string methodName); + public bool IsInvoking() + { + return this.Internal_IsInvokingAll(); + } + public Coroutine StartCoroutine(IEnumerator routine) + { + return this.StartCoroutine_Auto(routine); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Coroutine StartCoroutine_Auto(IEnumerator routine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Coroutine StartCoroutine(string methodName, [DefaultValue("null")] object value); + [ExcludeFromDocs] + public Coroutine StartCoroutine(string methodName) + { + object value = null; + return this.StartCoroutine(methodName, value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StopCoroutine(string methodName); + public void StopCoroutine(IEnumerator routine) + { + this.StopCoroutineViaEnumerator_Auto(routine); + } + public void StopCoroutine(Coroutine routine) + { + this.StopCoroutine_Auto(routine); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void StopCoroutineViaEnumerator_Auto(IEnumerator routine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void StopCoroutine_Auto(Coroutine routine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StopAllCoroutines(); + public static void print(object message) + { + Debug.Log(message); + } + } +} diff --git a/UnityEngine/UnityEngine/Motion.cs b/UnityEngine/UnityEngine/Motion.cs new file mode 100644 index 00000000..ec031e04 --- /dev/null +++ b/UnityEngine/UnityEngine/Motion.cs @@ -0,0 +1,53 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Motion : Object + { + public extern float averageDuration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float averageAngularSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3 averageSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float apparentSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isLooping + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isAnimatorMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isHumanMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool ValidateIfRetargetable(bool showWarning); + } +} diff --git a/UnityEngine/UnityEngine/MovieTexture.cs b/UnityEngine/UnityEngine/MovieTexture.cs new file mode 100644 index 00000000..f4a71975 --- /dev/null +++ b/UnityEngine/UnityEngine/MovieTexture.cs @@ -0,0 +1,62 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class MovieTexture : Texture + { + public extern AudioClip audioClip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool loop + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isReadyToPlay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float duration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public void Play() + { + MovieTexture.INTERNAL_CALL_Play(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Play(MovieTexture self); + public void Stop() + { + MovieTexture.INTERNAL_CALL_Stop(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Stop(MovieTexture self); + public void Pause() + { + MovieTexture.INTERNAL_CALL_Pause(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Pause(MovieTexture self); + } +} diff --git a/UnityEngine/UnityEngine/MultilineAttribute.cs b/UnityEngine/UnityEngine/MultilineAttribute.cs new file mode 100644 index 00000000..4334149d --- /dev/null +++ b/UnityEngine/UnityEngine/MultilineAttribute.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public sealed class MultilineAttribute : PropertyAttribute + { + public readonly int lines; + public MultilineAttribute() + { + this.lines = 3; + } + public MultilineAttribute(int lines) + { + this.lines = lines; + } + } +} diff --git a/UnityEngine/UnityEngine/NPOTSupport.cs b/UnityEngine/UnityEngine/NPOTSupport.cs new file mode 100644 index 00000000..6c6e1c3f --- /dev/null +++ b/UnityEngine/UnityEngine/NPOTSupport.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum NPOTSupport + { + None, + Restricted, + Full + } +} diff --git a/UnityEngine/UnityEngine/NavMesh.cs b/UnityEngine/UnityEngine/NavMesh.cs new file mode 100644 index 00000000..e78cde1b --- /dev/null +++ b/UnityEngine/UnityEngine/NavMesh.cs @@ -0,0 +1,68 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class NavMesh : Object + { + public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int passableMask) + { + return NavMesh.INTERNAL_CALL_Raycast(ref sourcePosition, ref targetPosition, out hit, passableMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Raycast(ref Vector3 sourcePosition, ref Vector3 targetPosition, out NavMeshHit hit, int passableMask); + public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int passableMask, NavMeshPath path) + { + path.ClearCorners(); + return NavMesh.CalculatePathInternal(sourcePosition, targetPosition, passableMask, path); + } + internal static bool CalculatePathInternal(Vector3 sourcePosition, Vector3 targetPosition, int passableMask, NavMeshPath path) + { + return NavMesh.INTERNAL_CALL_CalculatePathInternal(ref sourcePosition, ref targetPosition, passableMask, path); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_CalculatePathInternal(ref Vector3 sourcePosition, ref Vector3 targetPosition, int passableMask, NavMeshPath path); + public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int passableMask) + { + return NavMesh.INTERNAL_CALL_FindClosestEdge(ref sourcePosition, out hit, passableMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_FindClosestEdge(ref Vector3 sourcePosition, out NavMeshHit hit, int passableMask); + public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int allowedMask) + { + return NavMesh.INTERNAL_CALL_SamplePosition(ref sourcePosition, out hit, maxDistance, allowedMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_SamplePosition(ref Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int allowedMask); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLayerCost(int layer, float cost); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetLayerCost(int layer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshLayerFromName(string layerName); + public static NavMeshTriangulation CalculateTriangulation() + { + NavMeshTriangulation result = default(NavMeshTriangulation); + NavMesh.TriangulateInternal(ref result.vertices, ref result.indices, ref result.layers); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void TriangulateInternal(ref Vector3[] vertices, ref int[] indices, ref int[] layers); + [Obsolete("use NavMesh.CalculateTriangulation() instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Triangulate(out Vector3[] vertices, out int[] indices); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AddOffMeshLinks(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RestoreNavMesh(); + } +} diff --git a/UnityEngine/UnityEngine/NavMeshAgent.cs b/UnityEngine/UnityEngine/NavMeshAgent.cs new file mode 100644 index 00000000..111cd9c8 --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshAgent.cs @@ -0,0 +1,389 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class NavMeshAgent : Behaviour + { + public Vector3 destination + { + get + { + Vector3 result; + this.INTERNAL_get_destination(out result); + return result; + } + set + { + this.INTERNAL_set_destination(ref value); + } + } + public extern float stoppingDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 velocity + { + get + { + Vector3 result; + this.INTERNAL_get_velocity(out result); + return result; + } + set + { + this.INTERNAL_set_velocity(ref value); + } + } + public Vector3 nextPosition + { + get + { + Vector3 result; + this.INTERNAL_get_nextPosition(out result); + return result; + } + set + { + this.INTERNAL_set_nextPosition(ref value); + } + } + public Vector3 steeringTarget + { + get + { + Vector3 result; + this.INTERNAL_get_steeringTarget(out result); + return result; + } + } + public Vector3 desiredVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_desiredVelocity(out result); + return result; + } + } + public extern float remainingDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float baseOffset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isOnOffMeshLink + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public OffMeshLinkData currentOffMeshLinkData + { + get + { + return this.GetCurrentOffMeshLinkDataInternal(); + } + } + public OffMeshLinkData nextOffMeshLinkData + { + get + { + return this.GetNextOffMeshLinkDataInternal(); + } + } + public extern bool autoTraverseOffMeshLink + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool autoBraking + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool autoRepath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool pathPending + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isPathStale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern NavMeshPathStatus pathStatus + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 pathEndPosition + { + get + { + Vector3 result; + this.INTERNAL_get_pathEndPosition(out result); + return result; + } + } + public NavMeshPath path + { + get + { + NavMeshPath navMeshPath = new NavMeshPath(); + this.CopyPathTo(navMeshPath); + return navMeshPath; + } + set + { + if (value == null) + { + throw new NullReferenceException(); + } + this.SetPath(value); + } + } + public extern int walkableMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float acceleration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool updatePosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool updateRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ObstacleAvoidanceType obstacleAvoidanceType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int avoidancePriority + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool SetDestination(Vector3 target) + { + return NavMeshAgent.INTERNAL_CALL_SetDestination(this, ref target); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_SetDestination(NavMeshAgent self, ref Vector3 target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_destination(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_destination(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_velocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_nextPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_nextPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_steeringTarget(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_desiredVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ActivateCurrentOffMeshLink(bool activated); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern OffMeshLinkData GetCurrentOffMeshLinkDataInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern OffMeshLinkData GetNextOffMeshLinkDataInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CompleteOffMeshLink(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_pathEndPosition(out Vector3 value); + public bool Warp(Vector3 newPosition) + { + return NavMeshAgent.INTERNAL_CALL_Warp(this, ref newPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Warp(NavMeshAgent self, ref Vector3 newPosition); + public void Move(Vector3 offset) + { + NavMeshAgent.INTERNAL_CALL_Move(this, ref offset); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Move(NavMeshAgent self, ref Vector3 offset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Stop([DefaultValue("false")] bool stopUpdates); + [ExcludeFromDocs] + public void Stop() + { + bool stopUpdates = false; + this.Stop(stopUpdates); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Resume(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ResetPath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SetPath(NavMeshPath path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void CopyPathTo(NavMeshPath path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool FindClosestEdge(out NavMeshHit hit); + public bool Raycast(Vector3 targetPosition, out NavMeshHit hit) + { + return NavMeshAgent.INTERNAL_CALL_Raycast(this, ref targetPosition, out hit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Raycast(NavMeshAgent self, ref Vector3 targetPosition, out NavMeshHit hit); + public bool CalculatePath(Vector3 targetPosition, NavMeshPath path) + { + path.ClearCorners(); + return this.CalculatePathInternal(targetPosition, path); + } + private bool CalculatePathInternal(Vector3 targetPosition, NavMeshPath path) + { + return NavMeshAgent.INTERNAL_CALL_CalculatePathInternal(this, ref targetPosition, path); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_CalculatePathInternal(NavMeshAgent self, ref Vector3 targetPosition, NavMeshPath path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SamplePathPosition(int passableMask, float maxDistance, out NavMeshHit hit); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetLayerCost(int layer, float cost); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetLayerCost(int layer); + } +} diff --git a/UnityEngine/UnityEngine/NavMeshHit.cs b/UnityEngine/UnityEngine/NavMeshHit.cs new file mode 100644 index 00000000..d970ca24 --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshHit.cs @@ -0,0 +1,67 @@ +using System; +namespace UnityEngine +{ + public struct NavMeshHit + { + private Vector3 m_Position; + private Vector3 m_Normal; + private float m_Distance; + private int m_Mask; + private int m_Hit; + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + set + { + this.m_Normal = value; + } + } + public float distance + { + get + { + return this.m_Distance; + } + set + { + this.m_Distance = value; + } + } + public int mask + { + get + { + return this.m_Mask; + } + set + { + this.m_Mask = value; + } + } + public bool hit + { + get + { + return this.m_Hit != 0; + } + set + { + this.m_Hit = ((!value) ? 0 : 1); + } + } + } +} diff --git a/UnityEngine/UnityEngine/NavMeshObstacle.cs b/UnityEngine/UnityEngine/NavMeshObstacle.cs new file mode 100644 index 00000000..ce86edc0 --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshObstacle.cs @@ -0,0 +1,63 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class NavMeshObstacle : Behaviour + { + public extern float height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 velocity + { + get + { + Vector3 result; + this.INTERNAL_get_velocity(out result); + return result; + } + set + { + this.INTERNAL_set_velocity(ref value); + } + } + public extern bool carving + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float carvingMoveThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_velocity(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/NavMeshPath.cs b/UnityEngine/UnityEngine/NavMeshPath.cs new file mode 100644 index 00000000..fa817180 --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshPath.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class NavMeshPath + { + internal IntPtr m_Ptr; + internal Vector3[] m_corners; + public Vector3[] corners + { + get + { + this.CalculateCorners(); + return this.m_corners; + } + } + public extern NavMeshPathStatus status + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern NavMeshPath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void DestroyNavMeshPath(); + ~NavMeshPath() + { + this.DestroyNavMeshPath(); + this.m_Ptr = IntPtr.Zero; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Vector3[] CalculateCornersInternal(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void ClearCornersInternal(); + public void ClearCorners() + { + this.ClearCornersInternal(); + this.m_corners = null; + } + private void CalculateCorners() + { + if (this.m_corners == null) + { + this.m_corners = this.CalculateCornersInternal(); + } + } + } +} diff --git a/UnityEngine/UnityEngine/NavMeshPathStatus.cs b/UnityEngine/UnityEngine/NavMeshPathStatus.cs new file mode 100644 index 00000000..7ba3c9dd --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshPathStatus.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum NavMeshPathStatus + { + PathComplete, + PathPartial, + PathInvalid + } +} diff --git a/UnityEngine/UnityEngine/NavMeshTriangulation.cs b/UnityEngine/UnityEngine/NavMeshTriangulation.cs new file mode 100644 index 00000000..bbc3fee9 --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshTriangulation.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public struct NavMeshTriangulation + { + public Vector3[] vertices; + public int[] indices; + public int[] layers; + } +} diff --git a/UnityEngine/UnityEngine/Network.cs b/UnityEngine/UnityEngine/Network.cs new file mode 100644 index 00000000..dbb8aed4 --- /dev/null +++ b/UnityEngine/UnityEngine/Network.cs @@ -0,0 +1,401 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEngine +{ + public sealed class Network + { + public static extern string incomingPassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern NetworkLogLevel logLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern NetworkPlayer[] connections + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static NetworkPlayer player + { + get + { + NetworkPlayer result; + result.index = Network.Internal_GetPlayer(); + return result; + } + } + public static extern bool isClient + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isServer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern NetworkPeerType peerType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float sendRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool isMessageQueueRunning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static double time + { + get + { + double result; + Network.Internal_GetTime(out result); + return result; + } + } + public static extern int minimumAllocatableViewIDs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("No longer needed. This is now explicitly set in the InitializeServer function call. It is implicitly set when calling Connect depending on if an IP/port combination is used (useNat=false) or a GUID is used(useNat=true).")] + public static extern bool useNat + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string natFacilitatorIP + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int natFacilitatorPort + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string connectionTesterIP + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int connectionTesterPort + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int maxConnections + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string proxyIP + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int proxyPort + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useProxy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string proxyPassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern NetworkConnectionError InitializeServer(int connections, int listenPort, bool useNat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern NetworkConnectionError Internal_InitializeServerDeprecated(int connections, int listenPort); + [Obsolete("Use the IntializeServer(connections, listenPort, useNat) function instead")] + public static NetworkConnectionError InitializeServer(int connections, int listenPort) + { + return Network.Internal_InitializeServerDeprecated(connections, listenPort); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void InitializeSecurity(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern NetworkConnectionError Internal_ConnectToSingleIP(string IP, int remotePort, int localPort, [DefaultValue("\"\"")] string password); + [ExcludeFromDocs] + private static NetworkConnectionError Internal_ConnectToSingleIP(string IP, int remotePort, int localPort) + { + string empty = string.Empty; + return Network.Internal_ConnectToSingleIP(IP, remotePort, localPort, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern NetworkConnectionError Internal_ConnectToGuid(string guid, string password); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern NetworkConnectionError Internal_ConnectToIPs(string[] IP, int remotePort, int localPort, [DefaultValue("\"\"")] string password); + [ExcludeFromDocs] + private static NetworkConnectionError Internal_ConnectToIPs(string[] IP, int remotePort, int localPort) + { + string empty = string.Empty; + return Network.Internal_ConnectToIPs(IP, remotePort, localPort, empty); + } + [ExcludeFromDocs] + public static NetworkConnectionError Connect(string IP, int remotePort) + { + string empty = string.Empty; + return Network.Connect(IP, remotePort, empty); + } + public static NetworkConnectionError Connect(string IP, int remotePort, [DefaultValue("\"\"")] string password) + { + return Network.Internal_ConnectToSingleIP(IP, remotePort, 0, password); + } + [ExcludeFromDocs] + public static NetworkConnectionError Connect(string[] IPs, int remotePort) + { + string empty = string.Empty; + return Network.Connect(IPs, remotePort, empty); + } + public static NetworkConnectionError Connect(string[] IPs, int remotePort, [DefaultValue("\"\"")] string password) + { + return Network.Internal_ConnectToIPs(IPs, remotePort, 0, password); + } + [ExcludeFromDocs] + public static NetworkConnectionError Connect(string GUID) + { + string empty = string.Empty; + return Network.Connect(GUID, empty); + } + public static NetworkConnectionError Connect(string GUID, [DefaultValue("\"\"")] string password) + { + return Network.Internal_ConnectToGuid(GUID, password); + } + [ExcludeFromDocs] + public static NetworkConnectionError Connect(HostData hostData) + { + string empty = string.Empty; + return Network.Connect(hostData, empty); + } + public static NetworkConnectionError Connect(HostData hostData, [DefaultValue("\"\"")] string password) + { + if (hostData == null) + { + throw new NullReferenceException(); + } + if (hostData.guid.Length > 0 && hostData.useNat) + { + return Network.Connect(hostData.guid, password); + } + return Network.Connect(hostData.ip, hostData.port, password); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Disconnect([DefaultValue("200")] int timeout); + [ExcludeFromDocs] + public static void Disconnect() + { + int timeout = 200; + Network.Disconnect(timeout); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CloseConnection(NetworkPlayer target, bool sendDisconnectionNotification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetPlayer(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_AllocateViewID(out NetworkViewID viewID); + public static NetworkViewID AllocateViewID() + { + NetworkViewID result; + Network.Internal_AllocateViewID(out result); + return result; + } + [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] + public static Object Instantiate(Object prefab, Vector3 position, Quaternion rotation, int group) + { + return Network.INTERNAL_CALL_Instantiate(prefab, ref position, ref rotation, group); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Object INTERNAL_CALL_Instantiate(Object prefab, ref Vector3 position, ref Quaternion rotation, int group); + public static void Destroy(NetworkViewID viewID) + { + Network.INTERNAL_CALL_Destroy(ref viewID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Destroy(ref NetworkViewID viewID); + public static void Destroy(GameObject gameObject) + { + if (gameObject != null) + { + NetworkView networkView = gameObject.networkView; + if (networkView != null) + { + Network.Destroy(networkView.viewID); + } + else + { + Debug.LogError("Couldn't destroy game object because no network view is attached to it.", gameObject); + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DestroyPlayerObjects(NetworkPlayer playerID); + private static void Internal_RemoveRPCs(NetworkPlayer playerID, NetworkViewID viewID, uint channelMask) + { + Network.INTERNAL_CALL_Internal_RemoveRPCs(playerID, ref viewID, channelMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_RemoveRPCs(NetworkPlayer playerID, ref NetworkViewID viewID, uint channelMask); + public static void RemoveRPCs(NetworkPlayer playerID) + { + Network.Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, 4294967295u); + } + public static void RemoveRPCs(NetworkPlayer playerID, int group) + { + Network.Internal_RemoveRPCs(playerID, NetworkViewID.unassigned, 1u << group); + } + public static void RemoveRPCs(NetworkViewID viewID) + { + Network.Internal_RemoveRPCs(NetworkPlayer.unassigned, viewID, 4294967295u); + } + public static void RemoveRPCsInGroup(int group) + { + Network.Internal_RemoveRPCs(NetworkPlayer.unassigned, NetworkViewID.unassigned, 1u << group); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetLevelPrefix(int prefix); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetLastPing(NetworkPlayer player); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetAveragePing(NetworkPlayer player); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetReceivingEnabled(NetworkPlayer player, int group, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetSendingGlobal(int group, bool enabled); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetSendingSpecific(NetworkPlayer player, int group, bool enabled); + public static void SetSendingEnabled(int group, bool enabled) + { + Network.Internal_SetSendingGlobal(group, enabled); + } + public static void SetSendingEnabled(NetworkPlayer player, int group, bool enabled) + { + Network.Internal_SetSendingSpecific(player, group, enabled); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTime(out double t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ConnectionTesterStatus TestConnection([DefaultValue("false")] bool forceTest); + [ExcludeFromDocs] + public static ConnectionTesterStatus TestConnection() + { + bool forceTest = false; + return Network.TestConnection(forceTest); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ConnectionTesterStatus TestConnectionNAT([DefaultValue("false")] bool forceTest); + [ExcludeFromDocs] + public static ConnectionTesterStatus TestConnectionNAT() + { + bool forceTest = false; + return Network.TestConnectionNAT(forceTest); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HavePublicAddress(); + } +} diff --git a/UnityEngine/UnityEngine/NetworkConnectionError.cs b/UnityEngine/UnityEngine/NetworkConnectionError.cs new file mode 100644 index 00000000..906acd48 --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkConnectionError.cs @@ -0,0 +1,22 @@ +using System; +namespace UnityEngine +{ + public enum NetworkConnectionError + { + NoError, + RSAPublicKeyMismatch = 21, + InvalidPassword = 23, + ConnectionFailed = 15, + TooManyConnectedPlayers = 18, + ConnectionBanned = 22, + AlreadyConnectedToServer = 16, + AlreadyConnectedToAnotherServer = -1, + CreateSocketOrThreadFailure = -2, + IncorrectParameters = -3, + EmptyConnectTarget = -4, + InternalDirectConnectFailed = -5, + NATTargetNotConnected = 69, + NATTargetConnectionLost = 71, + NATPunchthroughFailed = 73 + } +} diff --git a/UnityEngine/UnityEngine/NetworkDisconnection.cs b/UnityEngine/UnityEngine/NetworkDisconnection.cs new file mode 100644 index 00000000..c9146d98 --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkDisconnection.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum NetworkDisconnection + { + LostConnection = 20, + Disconnected = 19 + } +} diff --git a/UnityEngine/UnityEngine/NetworkLogLevel.cs b/UnityEngine/UnityEngine/NetworkLogLevel.cs new file mode 100644 index 00000000..265c1cdf --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkLogLevel.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum NetworkLogLevel + { + Off, + Informational, + Full = 3 + } +} diff --git a/UnityEngine/UnityEngine/NetworkMessageInfo.cs b/UnityEngine/UnityEngine/NetworkMessageInfo.cs new file mode 100644 index 00000000..c5e8e47f --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkMessageInfo.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct NetworkMessageInfo + { + private double m_TimeStamp; + private NetworkPlayer m_Sender; + private NetworkViewID m_ViewID; + public double timestamp + { + get + { + return this.m_TimeStamp; + } + } + public NetworkPlayer sender + { + get + { + return this.m_Sender; + } + } + public NetworkView networkView + { + get + { + if (this.m_ViewID == NetworkViewID.unassigned) + { + Debug.LogError("No NetworkView is assigned to this NetworkMessageInfo object. Note that this is expected in OnNetworkInstantiate()."); + return this.NullNetworkView(); + } + return NetworkView.Find(this.m_ViewID); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern NetworkView NullNetworkView(); + } +} diff --git a/UnityEngine/UnityEngine/NetworkPeerType.cs b/UnityEngine/UnityEngine/NetworkPeerType.cs new file mode 100644 index 00000000..9a2675de --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkPeerType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum NetworkPeerType + { + Disconnected, + Server, + Client, + Connecting + } +} diff --git a/UnityEngine/UnityEngine/NetworkPlayer.cs b/UnityEngine/UnityEngine/NetworkPlayer.cs new file mode 100644 index 00000000..7db0c83f --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkPlayer.cs @@ -0,0 +1,117 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct NetworkPlayer + { + internal int index; + public string ipAddress + { + get + { + if (this.index == NetworkPlayer.Internal_GetPlayerIndex()) + { + return NetworkPlayer.Internal_GetLocalIP(); + } + return NetworkPlayer.Internal_GetIPAddress(this.index); + } + } + public int port + { + get + { + if (this.index == NetworkPlayer.Internal_GetPlayerIndex()) + { + return NetworkPlayer.Internal_GetLocalPort(); + } + return NetworkPlayer.Internal_GetPort(this.index); + } + } + public string guid + { + get + { + if (this.index == NetworkPlayer.Internal_GetPlayerIndex()) + { + return NetworkPlayer.Internal_GetLocalGUID(); + } + return NetworkPlayer.Internal_GetGUID(this.index); + } + } + public string externalIP + { + get + { + return NetworkPlayer.Internal_GetExternalIP(); + } + } + public int externalPort + { + get + { + return NetworkPlayer.Internal_GetExternalPort(); + } + } + internal static NetworkPlayer unassigned + { + get + { + NetworkPlayer result; + result.index = -1; + return result; + } + } + public NetworkPlayer(string ip, int port) + { + Debug.LogError("Not yet implemented"); + this.index = 0; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetIPAddress(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetPort(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetExternalIP(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetExternalPort(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetLocalIP(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetLocalPort(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetPlayerIndex(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetGUID(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string Internal_GetLocalGUID(); + public override int GetHashCode() + { + return this.index.GetHashCode(); + } + public override bool Equals(object other) + { + return other is NetworkPlayer && ((NetworkPlayer)other).index == this.index; + } + public override string ToString() + { + return this.index.ToString(); + } + public static bool operator ==(NetworkPlayer lhs, NetworkPlayer rhs) + { + return lhs.index == rhs.index; + } + public static bool operator !=(NetworkPlayer lhs, NetworkPlayer rhs) + { + return lhs.index != rhs.index; + } + } +} diff --git a/UnityEngine/UnityEngine/NetworkReachability.cs b/UnityEngine/UnityEngine/NetworkReachability.cs new file mode 100644 index 00000000..5fe833a1 --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkReachability.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum NetworkReachability + { + NotReachable, + ReachableViaCarrierDataNetwork, + ReachableViaLocalAreaNetwork + } +} diff --git a/UnityEngine/UnityEngine/NetworkStateSynchronization.cs b/UnityEngine/UnityEngine/NetworkStateSynchronization.cs new file mode 100644 index 00000000..73becb15 --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkStateSynchronization.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum NetworkStateSynchronization + { + Off, + ReliableDeltaCompressed, + Unreliable + } +} diff --git a/UnityEngine/UnityEngine/NetworkView.cs b/UnityEngine/UnityEngine/NetworkView.cs new file mode 100644 index 00000000..25f063ed --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkView.cs @@ -0,0 +1,96 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class NetworkView : Behaviour + { + public extern Component observed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern NetworkStateSynchronization stateSynchronization + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public NetworkViewID viewID + { + get + { + NetworkViewID result; + this.Internal_GetViewID(out result); + return result; + } + set + { + this.Internal_SetViewID(value); + } + } + public extern int group + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool isMine + { + get + { + return this.viewID.isMine; + } + } + public NetworkPlayer owner + { + get + { + return this.viewID.owner; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_RPC(NetworkView view, string name, RPCMode mode, object[] args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_RPC_Target(NetworkView view, string name, NetworkPlayer target, object[] args); + public void RPC(string name, RPCMode mode, params object[] args) + { + NetworkView.Internal_RPC(this, name, mode, args); + } + public void RPC(string name, NetworkPlayer target, params object[] args) + { + NetworkView.Internal_RPC_Target(this, name, target, args); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_GetViewID(out NetworkViewID viewID); + private void Internal_SetViewID(NetworkViewID viewID) + { + NetworkView.INTERNAL_CALL_Internal_SetViewID(this, ref viewID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_SetViewID(NetworkView self, ref NetworkViewID viewID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SetScope(NetworkPlayer player, bool relevancy); + public static NetworkView Find(NetworkViewID viewID) + { + return NetworkView.INTERNAL_CALL_Find(ref viewID); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern NetworkView INTERNAL_CALL_Find(ref NetworkViewID viewID); + } +} diff --git a/UnityEngine/UnityEngine/NetworkViewID.cs b/UnityEngine/UnityEngine/NetworkViewID.cs new file mode 100644 index 00000000..ae6aeddc --- /dev/null +++ b/UnityEngine/UnityEngine/NetworkViewID.cs @@ -0,0 +1,86 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct NetworkViewID + { + private int a; + private int b; + private int c; + public static extern NetworkViewID unassigned + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public bool isMine + { + get + { + return NetworkViewID.Internal_IsMine(this); + } + } + public NetworkPlayer owner + { + get + { + NetworkPlayer result; + NetworkViewID.Internal_GetOwner(this, out result); + return result; + } + } + internal static bool Internal_IsMine(NetworkViewID value) + { + return NetworkViewID.INTERNAL_CALL_Internal_IsMine(ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_IsMine(ref NetworkViewID value); + internal static void Internal_GetOwner(NetworkViewID value, out NetworkPlayer player) + { + NetworkViewID.INTERNAL_CALL_Internal_GetOwner(ref value, out player); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_GetOwner(ref NetworkViewID value, out NetworkPlayer player); + internal static string Internal_GetString(NetworkViewID value) + { + return NetworkViewID.INTERNAL_CALL_Internal_GetString(ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string INTERNAL_CALL_Internal_GetString(ref NetworkViewID value); + internal static bool Internal_Compare(NetworkViewID lhs, NetworkViewID rhs) + { + return NetworkViewID.INTERNAL_CALL_Internal_Compare(ref lhs, ref rhs); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_Compare(ref NetworkViewID lhs, ref NetworkViewID rhs); + public override int GetHashCode() + { + return this.a ^ this.b ^ this.c; + } + public override bool Equals(object other) + { + if (!(other is NetworkViewID)) + { + return false; + } + NetworkViewID rhs = (NetworkViewID)other; + return NetworkViewID.Internal_Compare(this, rhs); + } + public override string ToString() + { + return NetworkViewID.Internal_GetString(this); + } + public static bool operator ==(NetworkViewID lhs, NetworkViewID rhs) + { + return NetworkViewID.Internal_Compare(lhs, rhs); + } + public static bool operator !=(NetworkViewID lhs, NetworkViewID rhs) + { + return !NetworkViewID.Internal_Compare(lhs, rhs); + } + } +} diff --git a/UnityEngine/UnityEngine/NotConvertedAttribute.cs b/UnityEngine/UnityEngine/NotConvertedAttribute.cs new file mode 100644 index 00000000..552ac3a9 --- /dev/null +++ b/UnityEngine/UnityEngine/NotConvertedAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public sealed class NotConvertedAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs b/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs new file mode 100644 index 00000000..5ce74b2c --- /dev/null +++ b/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), NotConverted] + public sealed class NotFlashValidatedAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/NotRenamedAttribute.cs b/UnityEngine/UnityEngine/NotRenamedAttribute.cs new file mode 100644 index 00000000..156c9817 --- /dev/null +++ b/UnityEngine/UnityEngine/NotRenamedAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), NotConverted] + public sealed class NotRenamedAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/NotificationServices.cs b/UnityEngine/UnityEngine/NotificationServices.cs new file mode 100644 index 00000000..0401adc8 --- /dev/null +++ b/UnityEngine/UnityEngine/NotificationServices.cs @@ -0,0 +1,103 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class NotificationServices + { + public static extern int localNotificationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static LocalNotification[] localNotifications + { + get + { + int localNotificationCount = NotificationServices.localNotificationCount; + LocalNotification[] array = new LocalNotification[localNotificationCount]; + for (int i = 0; i < localNotificationCount; i++) + { + array[i] = NotificationServices.GetLocalNotification(i); + } + return array; + } + } + public static extern LocalNotification[] scheduledLocalNotifications + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int remoteNotificationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static RemoteNotification[] remoteNotifications + { + get + { + int remoteNotificationCount = NotificationServices.remoteNotificationCount; + RemoteNotification[] array = new RemoteNotification[remoteNotificationCount]; + for (int i = 0; i < remoteNotificationCount; i++) + { + array[i] = NotificationServices.GetRemoteNotification(i); + } + return array; + } + } + public static extern RemoteNotificationType enabledRemoteNotificationTypes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern byte[] deviceToken + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string registrationError + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern LocalNotification GetLocalNotification(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ScheduleLocalNotification(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PresentLocalNotificationNow(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CancelLocalNotification(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CancelAllLocalNotifications(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern RemoteNotification GetRemoteNotification(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearLocalNotifications(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearRemoteNotifications(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterForLocalNotificationTypes(LocalNotificationType notificationTypes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterForRemoteNotificationTypes(RemoteNotificationType notificationTypes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnregisterForRemoteNotifications(); + } +} diff --git a/UnityEngine/UnityEngine/Object.cs b/UnityEngine/UnityEngine/Object.cs new file mode 100644 index 00000000..ead35cbd --- /dev/null +++ b/UnityEngine/UnityEngine/Object.cs @@ -0,0 +1,158 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using UnityEngine.Internal; +using UnityEngineInternal; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class Object + { + private ReferenceData m_UnityRuntimeReferenceData; + private string m_UnityRuntimeErrorString; + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern HideFlags hideFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public override bool Equals(object o) + { + return Object.CompareBaseObjects(this, o as Object); + } + public override int GetHashCode() + { + return this.GetInstanceID(); + } + private static bool CompareBaseObjects(Object lhs, Object rhs) + { + return Object.CompareBaseObjectsInternal(lhs, rhs); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool CompareBaseObjectsInternal([Writable] Object lhs, [Writable] Object rhs); + [NotRenamed] + public int GetInstanceID() + { + return this.m_UnityRuntimeReferenceData.instanceID; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Object Internal_CloneSingle(Object data); + private static Object Internal_InstantiateSingle(Object data, Vector3 pos, Quaternion rot) + { + return Object.INTERNAL_CALL_Internal_InstantiateSingle(data, ref pos, ref rot); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Object INTERNAL_CALL_Internal_InstantiateSingle(Object data, ref Vector3 pos, ref Quaternion rot); + [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] + public static Object Instantiate(Object original, Vector3 position, Quaternion rotation) + { + Object.CheckNullArgument(original, "The prefab you want to instantiate is null."); + return Object.Internal_InstantiateSingle(original, position, rotation); + } + [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] + public static Object Instantiate(Object original) + { + Object.CheckNullArgument(original, "The thing you want to instantiate is null."); + return Object.Internal_CloneSingle(original); + } + private static void CheckNullArgument(object arg, string message) + { + if (arg == null) + { + throw new ArgumentException(message); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Destroy(Object obj, [DefaultValue("0.0F")] float t); + [ExcludeFromDocs] + public static void Destroy(Object obj) + { + float t = 0f; + Object.Destroy(obj, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DestroyImmediate(Object obj, [DefaultValue("false")] bool allowDestroyingAssets); + [ExcludeFromDocs] + public static void DestroyImmediate(Object obj) + { + bool allowDestroyingAssets = false; + Object.DestroyImmediate(obj, allowDestroyingAssets); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object[] FindObjectsOfType(Type type); + public static T[] FindObjectsOfType() where T : Object + { + return Resources.ConvertObjects(Object.FindObjectsOfType(typeof(T))); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public static Object FindObjectOfType(Type type) + { + Object[] array = Object.FindObjectsOfType(type); + if (array.Length > 0) + { + return array[0]; + } + return null; + } + public static T FindObjectOfType() where T : Object + { + return (T)((object)Object.FindObjectOfType(typeof(T))); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DontDestroyOnLoad(Object target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DestroyObject(Object obj, [DefaultValue("0.0F")] float t); + [ExcludeFromDocs] + public static void DestroyObject(Object obj) + { + float t = 0f; + Object.DestroyObject(obj, t); + } + [Obsolete("use Object.FindObjectsOfType instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object[] FindSceneObjectsOfType(Type type); + [Obsolete("use Resources.FindObjectsOfTypeAll instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object[] FindObjectsOfTypeIncludingAssets(Type type); + [Obsolete("Please use Resources.FindObjectsOfTypeAll instead")] + public static Object[] FindObjectsOfTypeAll(Type type) + { + return Resources.FindObjectsOfTypeAll(type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public override extern string ToString(); + public static implicit operator bool(Object exists) + { + return !Object.CompareBaseObjects(exists, null); + } + public static bool operator ==(Object x, Object y) + { + return Object.CompareBaseObjects(x, y); + } + public static bool operator !=(Object x, Object y) + { + return !Object.CompareBaseObjects(x, y); + } + } +} diff --git a/UnityEngine/UnityEngine/ObstacleAvoidanceType.cs b/UnityEngine/UnityEngine/ObstacleAvoidanceType.cs new file mode 100644 index 00000000..1377cc0b --- /dev/null +++ b/UnityEngine/UnityEngine/ObstacleAvoidanceType.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum ObstacleAvoidanceType + { + NoObstacleAvoidance, + LowQualityObstacleAvoidance, + MedQualityObstacleAvoidance, + GoodQualityObstacleAvoidance, + HighQualityObstacleAvoidance + } +} diff --git a/UnityEngine/UnityEngine/OcclusionArea.cs b/UnityEngine/UnityEngine/OcclusionArea.cs new file mode 100644 index 00000000..5f5dfa72 --- /dev/null +++ b/UnityEngine/UnityEngine/OcclusionArea.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class OcclusionArea : Component + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public Vector3 size + { + get + { + Vector3 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/OcclusionPortal.cs b/UnityEngine/UnityEngine/OcclusionPortal.cs new file mode 100644 index 00000000..4bb99ccf --- /dev/null +++ b/UnityEngine/UnityEngine/OcclusionPortal.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class OcclusionPortal : Component + { + public extern bool open + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/OffMeshLink.cs b/UnityEngine/UnityEngine/OffMeshLink.cs new file mode 100644 index 00000000..2ee76bd5 --- /dev/null +++ b/UnityEngine/UnityEngine/OffMeshLink.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class OffMeshLink : Component + { + public extern bool activated + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool occupied + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float costOverride + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool biDirectional + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int navMeshLayer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool autoUpdatePositions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Transform startTransform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Transform endTransform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdatePositions(); + } +} diff --git a/UnityEngine/UnityEngine/OffMeshLinkData.cs b/UnityEngine/UnityEngine/OffMeshLinkData.cs new file mode 100644 index 00000000..94b6043e --- /dev/null +++ b/UnityEngine/UnityEngine/OffMeshLinkData.cs @@ -0,0 +1,59 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct OffMeshLinkData + { + private int m_Valid; + private int m_Activated; + private int m_InstanceID; + private OffMeshLinkType m_LinkType; + private Vector3 m_StartPos; + private Vector3 m_EndPos; + public bool valid + { + get + { + return this.m_Valid != 0; + } + } + public bool activated + { + get + { + return this.m_Activated != 0; + } + } + public OffMeshLinkType linkType + { + get + { + return this.m_LinkType; + } + } + public Vector3 startPos + { + get + { + return this.m_StartPos; + } + } + public Vector3 endPos + { + get + { + return this.m_EndPos; + } + } + public OffMeshLink offMeshLink + { + get + { + return this.GetOffMeshLinkInternal(this.m_InstanceID); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern OffMeshLink GetOffMeshLinkInternal(int instanceID); + } +} diff --git a/UnityEngine/UnityEngine/OffMeshLinkType.cs b/UnityEngine/UnityEngine/OffMeshLinkType.cs new file mode 100644 index 00000000..65734022 --- /dev/null +++ b/UnityEngine/UnityEngine/OffMeshLinkType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum OffMeshLinkType + { + LinkTypeManual, + LinkTypeDropDown, + LinkTypeJumpAcross + } +} diff --git a/UnityEngine/UnityEngine/Particle.cs b/UnityEngine/UnityEngine/Particle.cs new file mode 100644 index 00000000..aef03a6b --- /dev/null +++ b/UnityEngine/UnityEngine/Particle.cs @@ -0,0 +1,103 @@ +using System; +namespace UnityEngine +{ + public struct Particle + { + private Vector3 m_Position; + private Vector3 m_Velocity; + private float m_Size; + private float m_Rotation; + private float m_AngularVelocity; + private float m_Energy; + private float m_StartEnergy; + private Color m_Color; + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + public Vector3 velocity + { + get + { + return this.m_Velocity; + } + set + { + this.m_Velocity = value; + } + } + public float energy + { + get + { + return this.m_Energy; + } + set + { + this.m_Energy = value; + } + } + public float startEnergy + { + get + { + return this.m_StartEnergy; + } + set + { + this.m_StartEnergy = value; + } + } + public float size + { + get + { + return this.m_Size; + } + set + { + this.m_Size = value; + } + } + public float rotation + { + get + { + return this.m_Rotation; + } + set + { + this.m_Rotation = value; + } + } + public float angularVelocity + { + get + { + return this.m_AngularVelocity; + } + set + { + this.m_AngularVelocity = value; + } + } + public Color color + { + get + { + return this.m_Color; + } + set + { + this.m_Color = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/ParticleAnimator.cs b/UnityEngine/UnityEngine/ParticleAnimator.cs new file mode 100644 index 00000000..a2051853 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleAnimator.cs @@ -0,0 +1,129 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ParticleAnimator : Component + { + public extern bool doesAnimateColor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 worldRotationAxis + { + get + { + Vector3 result; + this.INTERNAL_get_worldRotationAxis(out result); + return result; + } + set + { + this.INTERNAL_set_worldRotationAxis(ref value); + } + } + public Vector3 localRotationAxis + { + get + { + Vector3 result; + this.INTERNAL_get_localRotationAxis(out result); + return result; + } + set + { + this.INTERNAL_set_localRotationAxis(ref value); + } + } + public extern float sizeGrow + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 rndForce + { + get + { + Vector3 result; + this.INTERNAL_get_rndForce(out result); + return result; + } + set + { + this.INTERNAL_set_rndForce(ref value); + } + } + public Vector3 force + { + get + { + Vector3 result; + this.INTERNAL_get_force(out result); + return result; + } + set + { + this.INTERNAL_set_force(ref value); + } + } + public extern float damping + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool autodestruct + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Color[] colorAnimation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldRotationAxis(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_worldRotationAxis(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localRotationAxis(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localRotationAxis(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rndForce(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rndForce(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_force(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_force(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/ParticleEmitter.cs b/UnityEngine/UnityEngine/ParticleEmitter.cs new file mode 100644 index 00000000..dfe6ffc1 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleEmitter.cs @@ -0,0 +1,245 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ParticleEmitter : Component + { + public extern bool emit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minEnergy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxEnergy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minEmission + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxEmission + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float emitterVelocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 worldVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_worldVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_worldVelocity(ref value); + } + } + public Vector3 localVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_localVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_localVelocity(ref value); + } + } + public Vector3 rndVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_rndVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_rndVelocity(ref value); + } + } + public extern bool useWorldSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool rndRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float rndAngularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Particle[] particles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int particleCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_worldVelocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localVelocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rndVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rndVelocity(ref Vector3 value); + public void ClearParticles() + { + ParticleEmitter.INTERNAL_CALL_ClearParticles(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearParticles(ParticleEmitter self); + public void Emit() + { + this.Emit2((int)Random.Range(this.minEmission, this.maxEmission)); + } + public void Emit(int count) + { + this.Emit2(count); + } + public void Emit(Vector3 pos, Vector3 velocity, float size, float energy, Color color) + { + InternalEmitParticleArguments internalEmitParticleArguments = default(InternalEmitParticleArguments); + internalEmitParticleArguments.pos = pos; + internalEmitParticleArguments.velocity = velocity; + internalEmitParticleArguments.size = size; + internalEmitParticleArguments.energy = energy; + internalEmitParticleArguments.color = color; + internalEmitParticleArguments.rotation = 0f; + internalEmitParticleArguments.angularVelocity = 0f; + this.Emit3(ref internalEmitParticleArguments); + } + public void Emit(Vector3 pos, Vector3 velocity, float size, float energy, Color color, float rotation, float angularVelocity) + { + InternalEmitParticleArguments internalEmitParticleArguments = default(InternalEmitParticleArguments); + internalEmitParticleArguments.pos = pos; + internalEmitParticleArguments.velocity = velocity; + internalEmitParticleArguments.size = size; + internalEmitParticleArguments.energy = energy; + internalEmitParticleArguments.color = color; + internalEmitParticleArguments.rotation = rotation; + internalEmitParticleArguments.angularVelocity = angularVelocity; + this.Emit3(ref internalEmitParticleArguments); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Emit2(int count); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Emit3(ref InternalEmitParticleArguments args); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Simulate(float deltaTime); + } +} diff --git a/UnityEngine/UnityEngine/ParticleRenderMode.cs b/UnityEngine/UnityEngine/ParticleRenderMode.cs new file mode 100644 index 00000000..a584eda5 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleRenderMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum ParticleRenderMode + { + Billboard, + Stretch = 3, + SortedBillboard = 2, + HorizontalBillboard = 4, + VerticalBillboard + } +} diff --git a/UnityEngine/UnityEngine/ParticleRenderer.cs b/UnityEngine/UnityEngine/ParticleRenderer.cs new file mode 100644 index 00000000..4174baba --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleRenderer.cs @@ -0,0 +1,145 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ParticleRenderer : Renderer + { + public extern ParticleRenderMode particleRenderMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lengthScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float velocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float cameraVelocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxParticleSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int uvAnimationXTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int uvAnimationYTile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float uvAnimationCycles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("animatedTextureCount has been replaced by uvAnimationXTile and uvAnimationYTile.")] + public int animatedTextureCount + { + get + { + return this.uvAnimationXTile; + } + set + { + this.uvAnimationXTile = value; + } + } + public float maxPartileSize + { + get + { + return this.maxParticleSize; + } + set + { + this.maxParticleSize = value; + } + } + public extern Rect[] uvTiles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("This function has been removed.", true)] + public AnimationCurve widthCurve + { + get + { + return null; + } + set + { + } + } + [Obsolete("This function has been removed.", true)] + public AnimationCurve heightCurve + { + get + { + return null; + } + set + { + } + } + [Obsolete("This function has been removed.", true)] + public AnimationCurve rotationCurve + { + get + { + return null; + } + set + { + } + } + } +} diff --git a/UnityEngine/UnityEngine/ParticleSystem.cs b/UnityEngine/UnityEngine/ParticleSystem.cs new file mode 100644 index 00000000..8b06a3de --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleSystem.cs @@ -0,0 +1,603 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class ParticleSystem : Component + { + public struct Particle + { + private Vector3 m_Position; + private Vector3 m_Velocity; + private Vector3 m_AnimatedVelocity; + private Vector3 m_AxisOfRotation; + private float m_Rotation; + private float m_AngularVelocity; + private float m_Size; + private Color32 m_Color; + private uint m_RandomSeed; + private float m_Lifetime; + private float m_StartLifetime; + private float m_EmitAccumulator0; + private float m_EmitAccumulator1; + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + public Vector3 velocity + { + get + { + return this.m_Velocity; + } + set + { + this.m_Velocity = value; + } + } + public float lifetime + { + get + { + return this.m_Lifetime; + } + set + { + this.m_Lifetime = value; + } + } + public float startLifetime + { + get + { + return this.m_StartLifetime; + } + set + { + this.m_StartLifetime = value; + } + } + public float size + { + get + { + return this.m_Size; + } + set + { + this.m_Size = value; + } + } + public Vector3 axisOfRotation + { + get + { + return this.m_AxisOfRotation; + } + set + { + this.m_AxisOfRotation = value; + } + } + public float rotation + { + get + { + return this.m_Rotation * 57.29578f; + } + set + { + this.m_Rotation = value * 0.0174532924f; + } + } + public float angularVelocity + { + get + { + return this.m_AngularVelocity * 57.29578f; + } + set + { + this.m_AngularVelocity = value * 0.0174532924f; + } + } + public Color32 color + { + get + { + return this.m_Color; + } + set + { + this.m_Color = value; + } + } + [Obsolete("randomValue property is deprecated. Use randomSeed instead to control random behavior of particles.")] + public float randomValue + { + get + { + return BitConverter.ToSingle(BitConverter.GetBytes(this.m_RandomSeed), 0); + } + set + { + this.m_RandomSeed = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); + } + } + public uint randomSeed + { + get + { + return this.m_RandomSeed; + } + set + { + this.m_RandomSeed = value; + } + } + } + public struct CollisionEvent + { + private Vector3 m_Intersection; + private Vector3 m_Normal; + private Vector3 m_Velocity; + private int m_ColliderInstanceID; + public Vector3 intersection + { + get + { + return this.m_Intersection; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + } + public Vector3 velocity + { + get + { + return this.m_Velocity; + } + } + public Collider collider + { + get + { + return ParticleSystem.InstanceIDToCollider(this.m_ColliderInstanceID); + } + } + } + public extern float startDelay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isStopped + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isPaused + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool loop + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool playOnAwake + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float duration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float playbackSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int particleCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int safeCollisionEventSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool enableEmission + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float emissionRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float startSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float startSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color startColor + { + get + { + Color result; + this.INTERNAL_get_startColor(out result); + return result; + } + set + { + this.INTERNAL_set_startColor(ref value); + } + } + public extern float startRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float startLifetime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float gravityModifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int maxParticles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ParticleSystemSimulationSpace simulationSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern uint randomSeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Collider InstanceIDToCollider(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_startColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_startColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetParticles(ParticleSystem.Particle[] particles, int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetParticles(ParticleSystem.Particle[] particles); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetCollisionEvents(GameObject go, ParticleSystem.CollisionEvent[] collisionEvents); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Simulate(float t, bool restart); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Play(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Stop(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Pause(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_IsAlive(); + [ExcludeFromDocs] + public void Simulate(float t, bool withChildren) + { + bool restart = true; + this.Simulate(t, withChildren, restart); + } + [ExcludeFromDocs] + public void Simulate(float t) + { + bool restart = true; + bool withChildren = true; + this.Simulate(t, withChildren, restart); + } + public void Simulate(float t, [DefaultValue("true")] bool withChildren, [DefaultValue("true")] bool restart) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + particleSystem.Internal_Simulate(t, restart); + } + } + else + { + this.Internal_Simulate(t, restart); + } + } + [ExcludeFromDocs] + public void Play() + { + bool withChildren = true; + this.Play(withChildren); + } + public void Play([DefaultValue("true")] bool withChildren) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + particleSystem.Internal_Play(); + } + } + else + { + this.Internal_Play(); + } + } + [ExcludeFromDocs] + public void Stop() + { + bool withChildren = true; + this.Stop(withChildren); + } + public void Stop([DefaultValue("true")] bool withChildren) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + particleSystem.Internal_Stop(); + } + } + else + { + this.Internal_Stop(); + } + } + [ExcludeFromDocs] + public void Pause() + { + bool withChildren = true; + this.Pause(withChildren); + } + public void Pause([DefaultValue("true")] bool withChildren) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + particleSystem.Internal_Pause(); + } + } + else + { + this.Internal_Pause(); + } + } + [ExcludeFromDocs] + public void Clear() + { + bool withChildren = true; + this.Clear(withChildren); + } + public void Clear([DefaultValue("true")] bool withChildren) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + particleSystem.Internal_Clear(); + } + } + else + { + this.Internal_Clear(); + } + } + [ExcludeFromDocs] + public bool IsAlive() + { + bool withChildren = true; + return this.IsAlive(withChildren); + } + public bool IsAlive([DefaultValue("true")] bool withChildren) + { + if (withChildren) + { + ParticleSystem[] particleSystems = ParticleSystem.GetParticleSystems(this); + ParticleSystem[] array = particleSystems; + for (int i = 0; i < array.Length; i++) + { + ParticleSystem particleSystem = array[i]; + if (particleSystem.Internal_IsAlive()) + { + return true; + } + } + return false; + } + return this.Internal_IsAlive(); + } + public void Emit(int count) + { + ParticleSystem.INTERNAL_CALL_Emit(this, count); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Emit(ParticleSystem self, int count); + public void Emit(Vector3 position, Vector3 velocity, float size, float lifetime, Color32 color) + { + ParticleSystem.Particle particle = default(ParticleSystem.Particle); + particle.position = position; + particle.velocity = velocity; + particle.lifetime = lifetime; + particle.startLifetime = lifetime; + particle.size = size; + particle.rotation = 0f; + particle.angularVelocity = 0f; + particle.color = color; + particle.randomSeed = 5u; + this.Internal_Emit(ref particle); + } + public void Emit(ParticleSystem.Particle particle) + { + this.Internal_Emit(ref particle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Emit(ref ParticleSystem.Particle particle); + internal static ParticleSystem[] GetParticleSystems(ParticleSystem root) + { + if (!root) + { + return null; + } + List list = new List(); + list.Add(root); + ParticleSystem.GetDirectParticleSystemChildrenRecursive(root.transform, list); + return list.ToArray(); + } + private static void GetDirectParticleSystemChildrenRecursive(Transform transform, List particleSystems) + { + foreach (Transform transform2 in transform) + { + ParticleSystem component = transform2.gameObject.GetComponent(); + if (component != null) + { + particleSystems.Add(component); + ParticleSystem.GetDirectParticleSystemChildrenRecursive(transform2, particleSystems); + } + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetupDefaultType(int type); + } +} diff --git a/UnityEngine/UnityEngine/ParticleSystemRenderMode.cs b/UnityEngine/UnityEngine/ParticleSystemRenderMode.cs new file mode 100644 index 00000000..c37f1238 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleSystemRenderMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum ParticleSystemRenderMode + { + Billboard, + Stretch, + HorizontalBillboard, + VerticalBillboard, + Mesh + } +} diff --git a/UnityEngine/UnityEngine/ParticleSystemRenderer.cs b/UnityEngine/UnityEngine/ParticleSystemRenderer.cs new file mode 100644 index 00000000..c94249dd --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleSystemRenderer.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ParticleSystemRenderer : Renderer + { + public extern ParticleSystemRenderMode renderMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lengthScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float velocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float cameraVelocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxParticleSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Mesh mesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool editorEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/ParticleSystemSimulationSpace.cs b/UnityEngine/UnityEngine/ParticleSystemSimulationSpace.cs new file mode 100644 index 00000000..1720a1b6 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleSystemSimulationSpace.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum ParticleSystemSimulationSpace + { + Local, + World + } +} diff --git a/UnityEngine/UnityEngine/PhysicMaterial.cs b/UnityEngine/UnityEngine/PhysicMaterial.cs new file mode 100644 index 00000000..ec4364ac --- /dev/null +++ b/UnityEngine/UnityEngine/PhysicMaterial.cs @@ -0,0 +1,125 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class PhysicMaterial : Object + { + public extern float dynamicFriction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float staticFriction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float bounciness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use PhysicMaterial.bounciness instead", true)] + public float bouncyness + { + get + { + return this.bounciness; + } + set + { + this.bounciness = value; + } + } + public Vector3 frictionDirection2 + { + get + { + Vector3 result; + this.INTERNAL_get_frictionDirection2(out result); + return result; + } + set + { + this.INTERNAL_set_frictionDirection2(ref value); + } + } + public extern float dynamicFriction2 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float staticFriction2 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern PhysicMaterialCombine frictionCombine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern PhysicMaterialCombine bounceCombine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("use PhysicMaterial.frictionDirection2 instead.")] + public Vector3 frictionDirection + { + get + { + return this.frictionDirection2; + } + set + { + this.frictionDirection2 = value; + } + } + public PhysicMaterial() + { + PhysicMaterial.Internal_CreateDynamicsMaterial(this, null); + } + public PhysicMaterial(string name) + { + PhysicMaterial.Internal_CreateDynamicsMaterial(this, name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateDynamicsMaterial([Writable] PhysicMaterial mat, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_frictionDirection2(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_frictionDirection2(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/PhysicMaterialCombine.cs b/UnityEngine/UnityEngine/PhysicMaterialCombine.cs new file mode 100644 index 00000000..bf02e169 --- /dev/null +++ b/UnityEngine/UnityEngine/PhysicMaterialCombine.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum PhysicMaterialCombine + { + Average, + Minimum = 2, + Multiply = 1, + Maximum = 3 + } +} diff --git a/UnityEngine/UnityEngine/Physics.cs b/UnityEngine/UnityEngine/Physics.cs new file mode 100644 index 00000000..f602e9e2 --- /dev/null +++ b/UnityEngine/UnityEngine/Physics.cs @@ -0,0 +1,459 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class Physics + { + public const int kIgnoreRaycastLayer = 4; + public const int kDefaultRaycastLayers = -5; + public const int kAllLayers = -1; + public const int IgnoreRaycastLayer = 4; + public const int DefaultRaycastLayers = -5; + public const int AllLayers = -1; + public static Vector3 gravity + { + get + { + Vector3 result; + Physics.INTERNAL_get_gravity(out result); + return result; + } + set + { + Physics.INTERNAL_set_gravity(ref value); + } + } + public static extern float minPenetrationForPenalty + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float bounceThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Please use bounceThreshold instead.")] + public static float bounceTreshold + { + get + { + return Physics.bounceThreshold; + } + set + { + Physics.bounceThreshold = value; + } + } + public static extern float sleepVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float sleepAngularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maxAngularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int solverIterationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("penetrationPenaltyForce has no effect.")] + public static extern float penetrationPenaltyForce + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_gravity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_gravity(ref Vector3 value); + private static bool Internal_Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float distance, int layermask) + { + return Physics.INTERNAL_CALL_Internal_Raycast(ref origin, ref direction, out hitInfo, distance, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_Raycast(ref Vector3 origin, ref Vector3 direction, out RaycastHit hitInfo, float distance, int layermask); + private static bool Internal_CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float distance, int layermask) + { + return Physics.INTERNAL_CALL_Internal_CapsuleCast(ref point1, ref point2, radius, ref direction, out hitInfo, distance, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_CapsuleCast(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, out RaycastHit hitInfo, float distance, int layermask); + private static bool Internal_RaycastTest(Vector3 origin, Vector3 direction, float distance, int layermask) + { + return Physics.INTERNAL_CALL_Internal_RaycastTest(ref origin, ref direction, distance, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Internal_RaycastTest(ref Vector3 origin, ref Vector3 direction, float distance, int layermask); + [ExcludeFromDocs] + public static bool Raycast(Vector3 origin, Vector3 direction, float distance) + { + int layerMask = -5; + return Physics.Raycast(origin, direction, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Vector3 origin, Vector3 direction) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.Raycast(origin, direction, distance, layerMask); + } + public static bool Raycast(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Internal_RaycastTest(origin, direction, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float distance) + { + int layerMask = -5; + return Physics.Raycast(origin, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.Raycast(origin, direction, out hitInfo, distance, layerMask); + } + public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Internal_Raycast(origin, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Ray ray, float distance) + { + int layerMask = -5; + return Physics.Raycast(ray, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Ray ray) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.Raycast(ray, distance, layerMask); + } + public static bool Raycast(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Raycast(ray.origin, ray.direction, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Ray ray, out RaycastHit hitInfo, float distance) + { + int layerMask = -5; + return Physics.Raycast(ray, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool Raycast(Ray ray, out RaycastHit hitInfo) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.Raycast(ray, out hitInfo, distance, layerMask); + } + public static bool Raycast(Ray ray, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Raycast(ray.origin, ray.direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit[] RaycastAll(Ray ray, float distance) + { + int layerMask = -5; + return Physics.RaycastAll(ray, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit[] RaycastAll(Ray ray) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.RaycastAll(ray, distance, layerMask); + } + public static RaycastHit[] RaycastAll(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.RaycastAll(ray.origin, ray.direction, distance, layerMask); + } + public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layermask) + { + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + } + [ExcludeFromDocs] + public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float distance) + { + int layermask = -5; + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + } + [ExcludeFromDocs] + public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction) + { + int layermask = -5; + float distance = float.PositiveInfinity; + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit[] INTERNAL_CALL_RaycastAll(ref Vector3 origin, ref Vector3 direction, float distance, int layermask); + [ExcludeFromDocs] + public static bool Linecast(Vector3 start, Vector3 end) + { + int layerMask = -5; + return Physics.Linecast(start, end, layerMask); + } + public static bool Linecast(Vector3 start, Vector3 end, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + Vector3 direction = end - start; + return Physics.Raycast(start, direction, direction.magnitude, layerMask); + } + [ExcludeFromDocs] + public static bool Linecast(Vector3 start, Vector3 end, out RaycastHit hitInfo) + { + int layerMask = -5; + return Physics.Linecast(start, end, out hitInfo, layerMask); + } + public static bool Linecast(Vector3 start, Vector3 end, out RaycastHit hitInfo, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + Vector3 direction = end - start; + return Physics.Raycast(start, direction, out hitInfo, direction.magnitude, layerMask); + } + public static Collider[] OverlapSphere(Vector3 position, float radius, [DefaultValue("AllLayers")] int layerMask) + { + return Physics.INTERNAL_CALL_OverlapSphere(ref position, radius, layerMask); + } + [ExcludeFromDocs] + public static Collider[] OverlapSphere(Vector3 position, float radius) + { + int layerMask = -1; + return Physics.INTERNAL_CALL_OverlapSphere(ref position, radius, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider[] INTERNAL_CALL_OverlapSphere(ref Vector3 position, float radius, int layerMask); + [ExcludeFromDocs] + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float distance) + { + int layerMask = -5; + return Physics.CapsuleCast(point1, point2, radius, direction, distance, layerMask); + } + [ExcludeFromDocs] + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.CapsuleCast(point1, point2, radius, direction, distance, layerMask); + } + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + RaycastHit raycastHit; + return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out raycastHit, distance, layerMask); + } + [ExcludeFromDocs] + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float distance) + { + int layerMask = -5; + return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + } + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float distance) + { + int layerMask = -5; + return Physics.SphereCast(origin, radius, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.SphereCast(origin, radius, direction, out hitInfo, distance, layerMask); + } + public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Internal_CapsuleCast(origin, origin, radius, direction, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Ray ray, float radius, float distance) + { + int layerMask = -5; + return Physics.SphereCast(ray, radius, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Ray ray, float radius) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.SphereCast(ray, radius, distance, layerMask); + } + public static bool SphereCast(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + RaycastHit raycastHit; + return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out raycastHit, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, float distance) + { + int layerMask = -5; + return Physics.SphereCast(ray, radius, out hitInfo, distance, layerMask); + } + [ExcludeFromDocs] + public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.SphereCast(ray, radius, out hitInfo, distance, layerMask); + } + public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out hitInfo, distance, layerMask); + } + public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layermask) + { + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + } + [ExcludeFromDocs] + public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float distance) + { + int layermask = -5; + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + } + [ExcludeFromDocs] + public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction) + { + int layermask = -5; + float distance = float.PositiveInfinity; + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit[] INTERNAL_CALL_CapsuleCastAll(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, float distance, int layermask); + [ExcludeFromDocs] + public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, float distance) + { + int layerMask = -5; + return Physics.SphereCastAll(origin, radius, direction, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.SphereCastAll(origin, radius, direction, distance, layerMask); + } + public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.CapsuleCastAll(origin, origin, radius, direction, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit[] SphereCastAll(Ray ray, float radius, float distance) + { + int layerMask = -5; + return Physics.SphereCastAll(ray, radius, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit[] SphereCastAll(Ray ray, float radius) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics.SphereCastAll(ray, radius, distance, layerMask); + } + public static RaycastHit[] SphereCastAll(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.CapsuleCastAll(ray.origin, ray.origin, radius, ray.direction, distance, layerMask); + } + public static bool CheckSphere(Vector3 position, float radius, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics.INTERNAL_CALL_CheckSphere(ref position, radius, layerMask); + } + [ExcludeFromDocs] + public static bool CheckSphere(Vector3 position, float radius) + { + int layerMask = -5; + return Physics.INTERNAL_CALL_CheckSphere(ref position, radius, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_CheckSphere(ref Vector3 position, float radius, int layerMask); + public static bool CheckCapsule(Vector3 start, Vector3 end, float radius, [DefaultValue("DefaultRaycastLayers")] int layermask) + { + return Physics.INTERNAL_CALL_CheckCapsule(ref start, ref end, radius, layermask); + } + [ExcludeFromDocs] + public static bool CheckCapsule(Vector3 start, Vector3 end, float radius) + { + int layermask = -5; + return Physics.INTERNAL_CALL_CheckCapsule(ref start, ref end, radius, layermask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_CheckCapsule(ref Vector3 start, ref Vector3 end, float radius, int layermask); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IgnoreCollision(Collider collider1, Collider collider2, [DefaultValue("true")] bool ignore); + [ExcludeFromDocs] + public static void IgnoreCollision(Collider collider1, Collider collider2) + { + bool ignore = true; + Physics.IgnoreCollision(collider1, collider2, ignore); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IgnoreLayerCollision(int layer1, int layer2, [DefaultValue("true")] bool ignore); + [ExcludeFromDocs] + public static void IgnoreLayerCollision(int layer1, int layer2) + { + bool ignore = true; + Physics.IgnoreLayerCollision(layer1, layer2, ignore); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetIgnoreLayerCollision(int layer1, int layer2); + } +} diff --git a/UnityEngine/UnityEngine/Physics2D.cs b/UnityEngine/UnityEngine/Physics2D.cs new file mode 100644 index 00000000..505a774d --- /dev/null +++ b/UnityEngine/UnityEngine/Physics2D.cs @@ -0,0 +1,997 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class Physics2D + { + public const int IgnoreRaycastLayer = 4; + public const int DefaultRaycastLayers = -5; + public const int AllLayers = -1; + private static List m_LastDisabledRigidbody2D = new List(); + public static extern int velocityIterations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int positionIterations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Vector2 gravity + { + get + { + Vector2 result; + Physics2D.INTERNAL_get_gravity(out result); + return result; + } + set + { + Physics2D.INTERNAL_set_gravity(ref value); + } + } + public static extern bool raycastsHitTriggers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool raycastsStartInColliders + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("This method is deprecated. Use Physics2D.changeStopsCallbacks instead.")] + public static extern bool deleteStopsCallbacks + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool changeStopsCallbacks + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float velocityThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maxLinearCorrection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maxAngularCorrection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maxTranslationSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maxRotationSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float minPenetrationForPenalty + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float baumgarteScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float baumgarteTOIScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float timeToSleep + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float linearSleepTolerance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float angularSleepTolerance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_gravity(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_gravity(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IgnoreCollision(Collider2D collider1, Collider2D collider2, [DefaultValue("true")] bool ignore); + [ExcludeFromDocs] + public static void IgnoreCollision(Collider2D collider1, Collider2D collider2) + { + bool ignore = true; + Physics2D.IgnoreCollision(collider1, collider2, ignore); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetIgnoreCollision(Collider2D collider1, Collider2D collider2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IgnoreLayerCollision(int layer1, int layer2, [DefaultValue("true")] bool ignore); + [ExcludeFromDocs] + public static void IgnoreLayerCollision(int layer1, int layer2) + { + bool ignore = true; + Physics2D.IgnoreLayerCollision(layer1, layer2, ignore); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetIgnoreLayerCollision(int layer1, int layer2); + internal static void SetEditorDragMovement(bool dragging, GameObject[] objs) + { + foreach (Rigidbody2D current in Physics2D.m_LastDisabledRigidbody2D) + { + current.isKinematic = false; + } + Physics2D.m_LastDisabledRigidbody2D.Clear(); + if (!dragging) + { + return; + } + for (int i = 0; i < objs.Length; i++) + { + GameObject gameObject = objs[i]; + Rigidbody2D[] componentsInChildren = gameObject.GetComponentsInChildren(false); + Rigidbody2D[] array = componentsInChildren; + for (int j = 0; j < array.Length; j++) + { + Rigidbody2D rigidbody2D = array[j]; + if (!rigidbody2D.isKinematic) + { + rigidbody2D.isKinematic = true; + Physics2D.m_LastDisabledRigidbody2D.Add(rigidbody2D); + } + } + } + } + private static void Internal_Linecast(Vector2 start, Vector2 end, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit) + { + Physics2D.INTERNAL_CALL_Internal_Linecast(ref start, ref end, layerMask, minDepth, maxDepth, out raycastHit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Linecast(ref Vector2 start, ref Vector2 end, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit); + [ExcludeFromDocs] + public static RaycastHit2D Linecast(Vector2 start, Vector2 end, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.Linecast(start, end, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D Linecast(Vector2 start, Vector2 end, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.Linecast(start, end, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D Linecast(Vector2 start, Vector2 end) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.Linecast(start, end, layerMask, minDepth, maxDepth); + } + public static RaycastHit2D Linecast(Vector2 start, Vector2 end, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + RaycastHit2D result; + Physics2D.Internal_Linecast(start, end, layerMask, minDepth, maxDepth, out result); + return result; + } + public static RaycastHit2D[] LinecastAll(Vector2 start, Vector2 end, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_LinecastAll(ref start, ref end, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] LinecastAll(Vector2 start, Vector2 end, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_LinecastAll(ref start, ref end, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] LinecastAll(Vector2 start, Vector2 end, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_LinecastAll(ref start, ref end, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] LinecastAll(Vector2 start, Vector2 end) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_LinecastAll(ref start, ref end, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit2D[] INTERNAL_CALL_LinecastAll(ref Vector2 start, ref Vector2 end, int layerMask, float minDepth, float maxDepth); + public static int LinecastNonAlloc(Vector2 start, Vector2 end, RaycastHit2D[] results, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_LinecastNonAlloc(ref start, ref end, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int LinecastNonAlloc(Vector2 start, Vector2 end, RaycastHit2D[] results, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_LinecastNonAlloc(ref start, ref end, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int LinecastNonAlloc(Vector2 start, Vector2 end, RaycastHit2D[] results, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_LinecastNonAlloc(ref start, ref end, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int LinecastNonAlloc(Vector2 start, Vector2 end, RaycastHit2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_LinecastNonAlloc(ref start, ref end, results, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_LinecastNonAlloc(ref Vector2 start, ref Vector2 end, RaycastHit2D[] results, int layerMask, float minDepth, float maxDepth); + private static void Internal_Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit) + { + Physics2D.INTERNAL_CALL_Internal_Raycast(ref origin, ref direction, distance, layerMask, minDepth, maxDepth, out raycastHit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_Raycast(ref Vector2 origin, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit); + [ExcludeFromDocs] + public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.Raycast(origin, direction, distance, layerMask, minDepth, maxDepth); + } + public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + RaycastHit2D result; + Physics2D.Internal_Raycast(origin, direction, distance, layerMask, minDepth, maxDepth, out result); + return result; + } + public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] RaycastAll(Vector2 origin, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit2D[] INTERNAL_CALL_RaycastAll(ref Vector2 origin, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth); + public static int RaycastNonAlloc(Vector2 origin, Vector2 direction, RaycastHit2D[] results, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_RaycastNonAlloc(ref origin, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int RaycastNonAlloc(Vector2 origin, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_RaycastNonAlloc(ref origin, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int RaycastNonAlloc(Vector2 origin, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_RaycastNonAlloc(ref origin, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int RaycastNonAlloc(Vector2 origin, Vector2 direction, RaycastHit2D[] results, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_RaycastNonAlloc(ref origin, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int RaycastNonAlloc(Vector2 origin, Vector2 direction, RaycastHit2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_RaycastNonAlloc(ref origin, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_RaycastNonAlloc(ref Vector2 origin, ref Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth, float maxDepth); + private static void Internal_CircleCast(Vector2 origin, float radius, Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit) + { + Physics2D.INTERNAL_CALL_Internal_CircleCast(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth, out raycastHit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_CircleCast(ref Vector2 origin, float radius, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit); + [ExcludeFromDocs] + public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth); + } + public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + RaycastHit2D result; + Physics2D.Internal_CircleCast(origin, radius, direction, distance, layerMask, minDepth, maxDepth, out result); + return result; + } + public static RaycastHit2D[] CircleCastAll(Vector2 origin, float radius, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_CircleCastAll(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] CircleCastAll(Vector2 origin, float radius, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_CircleCastAll(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] CircleCastAll(Vector2 origin, float radius, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_CircleCastAll(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] CircleCastAll(Vector2 origin, float radius, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_CircleCastAll(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] CircleCastAll(Vector2 origin, float radius, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_CircleCastAll(ref origin, radius, ref direction, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit2D[] INTERNAL_CALL_CircleCastAll(ref Vector2 origin, float radius, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth); + public static int CircleCastNonAlloc(Vector2 origin, float radius, Vector2 direction, RaycastHit2D[] results, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_CircleCastNonAlloc(ref origin, radius, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int CircleCastNonAlloc(Vector2 origin, float radius, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_CircleCastNonAlloc(ref origin, radius, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int CircleCastNonAlloc(Vector2 origin, float radius, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_CircleCastNonAlloc(ref origin, radius, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int CircleCastNonAlloc(Vector2 origin, float radius, Vector2 direction, RaycastHit2D[] results, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_CircleCastNonAlloc(ref origin, radius, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int CircleCastNonAlloc(Vector2 origin, float radius, Vector2 direction, RaycastHit2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_CircleCastNonAlloc(ref origin, radius, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_CircleCastNonAlloc(ref Vector2 origin, float radius, ref Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth, float maxDepth); + private static void Internal_BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit) + { + Physics2D.INTERNAL_CALL_Internal_BoxCast(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth, out raycastHit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_BoxCast(ref Vector2 origin, ref Vector2 size, float angle, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth, out RaycastHit2D raycastHit); + [ExcludeFromDocs] + public static RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.BoxCast(origin, size, angle, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.BoxCast(origin, size, angle, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.BoxCast(origin, size, angle, direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.BoxCast(origin, size, angle, direction, distance, layerMask, minDepth, maxDepth); + } + public static RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + RaycastHit2D result; + Physics2D.Internal_BoxCast(origin, size, angle, direction, distance, layerMask, minDepth, maxDepth, out result); + return result; + } + public static RaycastHit2D[] BoxCastAll(Vector2 origin, Vector2 size, float angle, Vector2 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_BoxCastAll(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] BoxCastAll(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_BoxCastAll(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] BoxCastAll(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_BoxCastAll(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] BoxCastAll(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_BoxCastAll(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static RaycastHit2D[] BoxCastAll(Vector2 origin, Vector2 size, float angle, Vector2 direction) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_BoxCastAll(ref origin, ref size, angle, ref direction, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit2D[] INTERNAL_CALL_BoxCastAll(ref Vector2 origin, ref Vector2 size, float angle, ref Vector2 direction, float distance, int layerMask, float minDepth, float maxDepth); + public static int BoxCastNonAlloc(Vector2 origin, Vector2 size, float angle, Vector2 direction, RaycastHit2D[] results, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_BoxCastNonAlloc(ref origin, ref size, angle, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int BoxCastNonAlloc(Vector2 origin, Vector2 size, float angle, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_BoxCastNonAlloc(ref origin, ref size, angle, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int BoxCastNonAlloc(Vector2 origin, Vector2 size, float angle, Vector2 direction, RaycastHit2D[] results, float distance, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_BoxCastNonAlloc(ref origin, ref size, angle, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int BoxCastNonAlloc(Vector2 origin, Vector2 size, float angle, Vector2 direction, RaycastHit2D[] results, float distance) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_BoxCastNonAlloc(ref origin, ref size, angle, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int BoxCastNonAlloc(Vector2 origin, Vector2 size, float angle, Vector2 direction, RaycastHit2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_BoxCastNonAlloc(ref origin, ref size, angle, ref direction, results, distance, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_BoxCastNonAlloc(ref Vector2 origin, ref Vector2 size, float angle, ref Vector2 direction, RaycastHit2D[] results, float distance, int layerMask, float minDepth, float maxDepth); + private static void Internal_GetRayIntersection(Ray ray, float distance, int layerMask, out RaycastHit2D raycastHit) + { + Physics2D.INTERNAL_CALL_Internal_GetRayIntersection(ref ray, distance, layerMask, out raycastHit); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_GetRayIntersection(ref Ray ray, float distance, int layerMask, out RaycastHit2D raycastHit); + [ExcludeFromDocs] + public static RaycastHit2D GetRayIntersection(Ray ray, float distance) + { + int layerMask = -5; + return Physics2D.GetRayIntersection(ray, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit2D GetRayIntersection(Ray ray) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.GetRayIntersection(ray, distance, layerMask); + } + public static RaycastHit2D GetRayIntersection(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + RaycastHit2D result; + Physics2D.Internal_GetRayIntersection(ray, distance, layerMask, out result); + return result; + } + public static RaycastHit2D[] GetRayIntersectionAll(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics2D.INTERNAL_CALL_GetRayIntersectionAll(ref ray, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit2D[] GetRayIntersectionAll(Ray ray, float distance) + { + int layerMask = -5; + return Physics2D.INTERNAL_CALL_GetRayIntersectionAll(ref ray, distance, layerMask); + } + [ExcludeFromDocs] + public static RaycastHit2D[] GetRayIntersectionAll(Ray ray) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_GetRayIntersectionAll(ref ray, distance, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit2D[] INTERNAL_CALL_GetRayIntersectionAll(ref Ray ray, float distance, int layerMask); + public static int GetRayIntersectionNonAlloc(Ray ray, RaycastHit2D[] results, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + { + return Physics2D.INTERNAL_CALL_GetRayIntersectionNonAlloc(ref ray, results, distance, layerMask); + } + [ExcludeFromDocs] + public static int GetRayIntersectionNonAlloc(Ray ray, RaycastHit2D[] results, float distance) + { + int layerMask = -5; + return Physics2D.INTERNAL_CALL_GetRayIntersectionNonAlloc(ref ray, results, distance, layerMask); + } + [ExcludeFromDocs] + public static int GetRayIntersectionNonAlloc(Ray ray, RaycastHit2D[] results) + { + int layerMask = -5; + float distance = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_GetRayIntersectionNonAlloc(ref ray, results, distance, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_GetRayIntersectionNonAlloc(ref Ray ray, RaycastHit2D[] results, float distance, int layerMask); + public static Collider2D OverlapPoint(Vector2 point, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapPoint(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapPoint(Vector2 point, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapPoint(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapPoint(Vector2 point, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapPoint(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapPoint(Vector2 point) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapPoint(ref point, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D INTERNAL_CALL_OverlapPoint(ref Vector2 point, int layerMask, float minDepth, float maxDepth); + public static Collider2D[] OverlapPointAll(Vector2 point, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapPointAll(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapPointAll(Vector2 point, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapPointAll(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapPointAll(Vector2 point, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapPointAll(ref point, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapPointAll(Vector2 point) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapPointAll(ref point, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D[] INTERNAL_CALL_OverlapPointAll(ref Vector2 point, int layerMask, float minDepth, float maxDepth); + public static int OverlapPointNonAlloc(Vector2 point, Collider2D[] results, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapPointNonAlloc(ref point, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapPointNonAlloc(Vector2 point, Collider2D[] results, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapPointNonAlloc(ref point, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapPointNonAlloc(Vector2 point, Collider2D[] results, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapPointNonAlloc(ref point, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapPointNonAlloc(Vector2 point, Collider2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapPointNonAlloc(ref point, results, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_OverlapPointNonAlloc(ref Vector2 point, Collider2D[] results, int layerMask, float minDepth, float maxDepth); + public static Collider2D OverlapCircle(Vector2 point, float radius, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapCircle(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapCircle(Vector2 point, float radius, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircle(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapCircle(Vector2 point, float radius, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircle(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapCircle(Vector2 point, float radius) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapCircle(ref point, radius, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D INTERNAL_CALL_OverlapCircle(ref Vector2 point, float radius, int layerMask, float minDepth, float maxDepth); + public static Collider2D[] OverlapCircleAll(Vector2 point, float radius, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapCircleAll(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapCircleAll(Vector2 point, float radius, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircleAll(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapCircleAll(Vector2 point, float radius, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircleAll(ref point, radius, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapCircleAll(Vector2 point, float radius) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapCircleAll(ref point, radius, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D[] INTERNAL_CALL_OverlapCircleAll(ref Vector2 point, float radius, int layerMask, float minDepth, float maxDepth); + public static int OverlapCircleNonAlloc(Vector2 point, float radius, Collider2D[] results, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapCircleNonAlloc(ref point, radius, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapCircleNonAlloc(Vector2 point, float radius, Collider2D[] results, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircleNonAlloc(ref point, radius, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapCircleNonAlloc(Vector2 point, float radius, Collider2D[] results, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapCircleNonAlloc(ref point, radius, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapCircleNonAlloc(Vector2 point, float radius, Collider2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapCircleNonAlloc(ref point, radius, results, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_OverlapCircleNonAlloc(ref Vector2 point, float radius, Collider2D[] results, int layerMask, float minDepth, float maxDepth); + public static Collider2D OverlapArea(Vector2 pointA, Vector2 pointB, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapArea(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapArea(Vector2 pointA, Vector2 pointB, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapArea(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapArea(Vector2 pointA, Vector2 pointB, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapArea(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D OverlapArea(Vector2 pointA, Vector2 pointB) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapArea(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D INTERNAL_CALL_OverlapArea(ref Vector2 pointA, ref Vector2 pointB, int layerMask, float minDepth, float maxDepth); + public static Collider2D[] OverlapAreaAll(Vector2 pointA, Vector2 pointB, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapAreaAll(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapAreaAll(Vector2 pointA, Vector2 pointB, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapAreaAll(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapAreaAll(Vector2 pointA, Vector2 pointB, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapAreaAll(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static Collider2D[] OverlapAreaAll(Vector2 pointA, Vector2 pointB) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapAreaAll(ref pointA, ref pointB, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider2D[] INTERNAL_CALL_OverlapAreaAll(ref Vector2 pointA, ref Vector2 pointB, int layerMask, float minDepth, float maxDepth); + public static int OverlapAreaNonAlloc(Vector2 pointA, Vector2 pointB, Collider2D[] results, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("-Mathf.Infinity")] float minDepth, [DefaultValue("Mathf.Infinity")] float maxDepth) + { + return Physics2D.INTERNAL_CALL_OverlapAreaNonAlloc(ref pointA, ref pointB, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapAreaNonAlloc(Vector2 pointA, Vector2 pointB, Collider2D[] results, int layerMask, float minDepth) + { + float maxDepth = float.PositiveInfinity; + return Physics2D.INTERNAL_CALL_OverlapAreaNonAlloc(ref pointA, ref pointB, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapAreaNonAlloc(Vector2 pointA, Vector2 pointB, Collider2D[] results, int layerMask) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + return Physics2D.INTERNAL_CALL_OverlapAreaNonAlloc(ref pointA, ref pointB, results, layerMask, minDepth, maxDepth); + } + [ExcludeFromDocs] + public static int OverlapAreaNonAlloc(Vector2 pointA, Vector2 pointB, Collider2D[] results) + { + float maxDepth = float.PositiveInfinity; + float minDepth = float.NegativeInfinity; + int layerMask = -5; + return Physics2D.INTERNAL_CALL_OverlapAreaNonAlloc(ref pointA, ref pointB, results, layerMask, minDepth, maxDepth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_OverlapAreaNonAlloc(ref Vector2 pointA, ref Vector2 pointB, Collider2D[] results, int layerMask, float minDepth, float maxDepth); + } +} diff --git a/UnityEngine/UnityEngine/PhysicsMaterial2D.cs b/UnityEngine/UnityEngine/PhysicsMaterial2D.cs new file mode 100644 index 00000000..938a5e2d --- /dev/null +++ b/UnityEngine/UnityEngine/PhysicsMaterial2D.cs @@ -0,0 +1,37 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class PhysicsMaterial2D : Object + { + public extern float bounciness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float friction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public PhysicsMaterial2D() + { + PhysicsMaterial2D.Internal_Create(this, null); + } + public PhysicsMaterial2D(string name) + { + PhysicsMaterial2D.Internal_Create(this, name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] PhysicsMaterial2D mat, string name); + } +} diff --git a/UnityEngine/UnityEngine/Ping.cs b/UnityEngine/UnityEngine/Ping.cs new file mode 100644 index 00000000..a9873cc1 --- /dev/null +++ b/UnityEngine/UnityEngine/Ping.cs @@ -0,0 +1,37 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Ping + { + private IntPtr pingWrapper; + public extern bool isDone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string ip + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Ping(string address); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DestroyPing(); + ~Ping() + { + this.DestroyPing(); + } + } +} diff --git a/UnityEngine/UnityEngine/Plane.cs b/UnityEngine/UnityEngine/Plane.cs new file mode 100644 index 00000000..138cc235 --- /dev/null +++ b/UnityEngine/UnityEngine/Plane.cs @@ -0,0 +1,82 @@ +using System; +namespace UnityEngine +{ + public struct Plane + { + private Vector3 m_Normal; + private float m_Distance; + public Vector3 normal + { + get + { + return this.m_Normal; + } + set + { + this.m_Normal = value; + } + } + public float distance + { + get + { + return this.m_Distance; + } + set + { + this.m_Distance = value; + } + } + public Plane(Vector3 inNormal, Vector3 inPoint) + { + this.m_Normal = Vector3.Normalize(inNormal); + this.m_Distance = -Vector3.Dot(inNormal, inPoint); + } + public Plane(Vector3 inNormal, float d) + { + this.m_Normal = Vector3.Normalize(inNormal); + this.m_Distance = d; + } + public Plane(Vector3 a, Vector3 b, Vector3 c) + { + this.m_Normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); + this.m_Distance = -Vector3.Dot(this.m_Normal, a); + } + public void SetNormalAndPosition(Vector3 inNormal, Vector3 inPoint) + { + this.normal = Vector3.Normalize(inNormal); + this.distance = -Vector3.Dot(inNormal, inPoint); + } + public void Set3Points(Vector3 a, Vector3 b, Vector3 c) + { + this.normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); + this.distance = -Vector3.Dot(this.normal, a); + } + public float GetDistanceToPoint(Vector3 inPt) + { + return Vector3.Dot(this.normal, inPt) + this.distance; + } + public bool GetSide(Vector3 inPt) + { + return Vector3.Dot(this.normal, inPt) + this.distance > 0f; + } + public bool SameSide(Vector3 inPt0, Vector3 inPt1) + { + float distanceToPoint = this.GetDistanceToPoint(inPt0); + float distanceToPoint2 = this.GetDistanceToPoint(inPt1); + return (distanceToPoint > 0f && distanceToPoint2 > 0f) || (distanceToPoint <= 0f && distanceToPoint2 <= 0f); + } + public bool Raycast(Ray ray, out float enter) + { + float num = Vector3.Dot(ray.direction, this.normal); + float num2 = -Vector3.Dot(ray.origin, this.normal) - this.distance; + if (Mathf.Approximately(num, 0f)) + { + enter = 0f; + return false; + } + enter = num2 / num; + return enter > 0f; + } + } +} diff --git a/UnityEngine/UnityEngine/PlatformSelection.cs b/UnityEngine/UnityEngine/PlatformSelection.cs new file mode 100644 index 00000000..fbfe6e5a --- /dev/null +++ b/UnityEngine/UnityEngine/PlatformSelection.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal enum PlatformSelection + { + Native, + Mac, + Windows + } +} diff --git a/UnityEngine/UnityEngine/PlayMode.cs b/UnityEngine/UnityEngine/PlayMode.cs new file mode 100644 index 00000000..706798f3 --- /dev/null +++ b/UnityEngine/UnityEngine/PlayMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum PlayMode + { + StopSameLayer, + StopAll = 4 + } +} diff --git a/UnityEngine/UnityEngine/PlayerPrefs.cs b/UnityEngine/UnityEngine/PlayerPrefs.cs new file mode 100644 index 00000000..d8a40469 --- /dev/null +++ b/UnityEngine/UnityEngine/PlayerPrefs.cs @@ -0,0 +1,78 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class PlayerPrefs + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool TrySetInt(string key, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool TrySetFloat(string key, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool TrySetSetString(string key, string value); + public static void SetInt(string key, int value) + { + if (!PlayerPrefs.TrySetInt(key, value)) + { + throw new PlayerPrefsException("Could not store preference value"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetInt(string key, [DefaultValue("0")] int defaultValue); + [ExcludeFromDocs] + public static int GetInt(string key) + { + int defaultValue = 0; + return PlayerPrefs.GetInt(key, defaultValue); + } + public static void SetFloat(string key, float value) + { + if (!PlayerPrefs.TrySetFloat(key, value)) + { + throw new PlayerPrefsException("Could not store preference value"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetFloat(string key, [DefaultValue("0.0F")] float defaultValue); + [ExcludeFromDocs] + public static float GetFloat(string key) + { + float defaultValue = 0f; + return PlayerPrefs.GetFloat(key, defaultValue); + } + public static void SetString(string key, string value) + { + if (!PlayerPrefs.TrySetSetString(key, value)) + { + throw new PlayerPrefsException("Could not store preference value"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetString(string key, [DefaultValue("\"\"")] string defaultValue); + [ExcludeFromDocs] + public static string GetString(string key) + { + string empty = string.Empty; + return PlayerPrefs.GetString(key, empty); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasKey(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteKey(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DeleteAll(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Save(); + } +} diff --git a/UnityEngine/UnityEngine/PlayerPrefsException.cs b/UnityEngine/UnityEngine/PlayerPrefsException.cs new file mode 100644 index 00000000..c29bba75 --- /dev/null +++ b/UnityEngine/UnityEngine/PlayerPrefsException.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public sealed class PlayerPrefsException : Exception + { + public PlayerPrefsException(string error) : base(error) + { + } + } +} diff --git a/UnityEngine/UnityEngine/PolygonCollider2D.cs b/UnityEngine/UnityEngine/PolygonCollider2D.cs new file mode 100644 index 00000000..bac398e8 --- /dev/null +++ b/UnityEngine/UnityEngine/PolygonCollider2D.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class PolygonCollider2D : Collider2D + { + public extern Vector2[] points + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int pathCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector2[] GetPath(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPath(int index, Vector2[] points); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetTotalPointCount(); + public void CreatePrimitive(int sides, [DefaultValue("Vector2.one")] Vector2 scale, [DefaultValue("Vector2.zero")] Vector2 offset) + { + PolygonCollider2D.INTERNAL_CALL_CreatePrimitive(this, sides, ref scale, ref offset); + } + [ExcludeFromDocs] + public void CreatePrimitive(int sides, Vector2 scale) + { + Vector2 zero = Vector2.zero; + PolygonCollider2D.INTERNAL_CALL_CreatePrimitive(this, sides, ref scale, ref zero); + } + [ExcludeFromDocs] + public void CreatePrimitive(int sides) + { + Vector2 zero = Vector2.zero; + Vector2 one = Vector2.one; + PolygonCollider2D.INTERNAL_CALL_CreatePrimitive(this, sides, ref one, ref zero); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_CreatePrimitive(PolygonCollider2D self, int sides, ref Vector2 scale, ref Vector2 offset); + } +} diff --git a/UnityEngine/UnityEngine/PrimitiveType.cs b/UnityEngine/UnityEngine/PrimitiveType.cs new file mode 100644 index 00000000..c972d512 --- /dev/null +++ b/UnityEngine/UnityEngine/PrimitiveType.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum PrimitiveType + { + Sphere, + Capsule, + Cylinder, + Cube, + Plane, + Quad + } +} diff --git a/UnityEngine/UnityEngine/ProceduralCacheSize.cs b/UnityEngine/UnityEngine/ProceduralCacheSize.cs new file mode 100644 index 00000000..e8e71d8a --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralCacheSize.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum ProceduralCacheSize + { + Tiny, + Medium, + Heavy, + NoLimit, + None + } +} diff --git a/UnityEngine/UnityEngine/ProceduralLoadingBehavior.cs b/UnityEngine/UnityEngine/ProceduralLoadingBehavior.cs new file mode 100644 index 00000000..cdd899af --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralLoadingBehavior.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum ProceduralLoadingBehavior + { + DoNothing, + Generate, + BakeAndKeep, + BakeAndDiscard, + Cache, + DoNothingAndCache + } +} diff --git a/UnityEngine/UnityEngine/ProceduralMaterial.cs b/UnityEngine/UnityEngine/ProceduralMaterial.cs new file mode 100644 index 00000000..d266526b --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralMaterial.cs @@ -0,0 +1,163 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ProceduralMaterial : Material + { + public extern ProceduralCacheSize cacheSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int animationUpdateRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isProcessing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isCachedDataAvailable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isLoadTimeGenerated + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ProceduralLoadingBehavior loadingBehavior + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool isSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ProceduralProcessorUsage substanceProcessorUsage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string preset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isReadable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public ProceduralMaterial() : base(string.Empty) + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProceduralPropertyDescription[] GetProceduralPropertyDescriptions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool HasProceduralProperty(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetProceduralBoolean(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetProceduralBoolean(string inputName, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetProceduralFloat(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetProceduralFloat(string inputName, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector4 GetProceduralVector(string inputName); + public void SetProceduralVector(string inputName, Vector4 value) + { + ProceduralMaterial.INTERNAL_CALL_SetProceduralVector(this, inputName, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetProceduralVector(ProceduralMaterial self, string inputName, ref Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetProceduralColor(string inputName); + public void SetProceduralColor(string inputName, Color value) + { + ProceduralMaterial.INTERNAL_CALL_SetProceduralColor(this, inputName, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetProceduralColor(ProceduralMaterial self, string inputName, ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetProceduralEnum(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetProceduralEnum(string inputName, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture2D GetProceduralTexture(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetProceduralTexture(string inputName, Texture2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsProceduralPropertyCached(string inputName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void CacheProceduralProperty(string inputName, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ClearCache(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RebuildTextures(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RebuildTexturesImmediately(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopRebuilds(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture[] GetGeneratedTextures(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProceduralTexture GetGeneratedTexture(string textureName); + } +} diff --git a/UnityEngine/UnityEngine/ProceduralOutputType.cs b/UnityEngine/UnityEngine/ProceduralOutputType.cs new file mode 100644 index 00000000..41cdb829 --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralOutputType.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public enum ProceduralOutputType + { + Unknown, + Diffuse, + Normal, + Height, + Emissive, + Specular, + Opacity + } +} diff --git a/UnityEngine/UnityEngine/ProceduralProcessorUsage.cs b/UnityEngine/UnityEngine/ProceduralProcessorUsage.cs new file mode 100644 index 00000000..3d1c983f --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralProcessorUsage.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum ProceduralProcessorUsage + { + Unsupported, + One, + Half, + All + } +} diff --git a/UnityEngine/UnityEngine/ProceduralPropertyDescription.cs b/UnityEngine/UnityEngine/ProceduralPropertyDescription.cs new file mode 100644 index 00000000..b6740c40 --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralPropertyDescription.cs @@ -0,0 +1,19 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class ProceduralPropertyDescription + { + public string name; + public string label; + public string group; + public ProceduralPropertyType type; + public bool hasRange; + public float minimum; + public float maximum; + public float step; + public string[] enumOptions; + public string[] componentLabels; + } +} diff --git a/UnityEngine/UnityEngine/ProceduralPropertyType.cs b/UnityEngine/UnityEngine/ProceduralPropertyType.cs new file mode 100644 index 00000000..6a458754 --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralPropertyType.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + public enum ProceduralPropertyType + { + Boolean, + Float, + Vector2, + Vector3, + Vector4, + Color3, + Color4, + Enum, + Texture + } +} diff --git a/UnityEngine/UnityEngine/ProceduralTexture.cs b/UnityEngine/UnityEngine/ProceduralTexture.cs new file mode 100644 index 00000000..9b7b785c --- /dev/null +++ b/UnityEngine/UnityEngine/ProceduralTexture.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ProceduralTexture : Texture + { + public extern bool hasAlpha + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern TextureFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern ProceduralOutputType GetProceduralOutputType(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern ProceduralMaterial GetProceduralMaterial(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasBeenGenerated(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color32[] GetPixels32(int x, int y, int blockWidth, int blockHeight); + } +} diff --git a/UnityEngine/UnityEngine/Profiler.cs b/UnityEngine/UnityEngine/Profiler.cs new file mode 100644 index 00000000..6e92c002 --- /dev/null +++ b/UnityEngine/UnityEngine/Profiler.cs @@ -0,0 +1,83 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Profiler + { + public static extern bool supported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string logFile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enableBinaryLog + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern uint usedHeapSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Conditional("ENABLE_PROFILER"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AddFramesFromFile(string file); + [Conditional("ENABLE_PROFILER")] + public static void BeginSample(string name) + { + Profiler.BeginSampleOnly(name); + } + [Conditional("ENABLE_PROFILER"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BeginSample(string name, Object targetObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void BeginSampleOnly(string name); + [Conditional("ENABLE_PROFILER"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void EndSample(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetRuntimeMemorySize(Object o); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern uint GetMonoHeapSize(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern uint GetMonoUsedSize(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern uint GetTotalAllocatedMemory(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern uint GetTotalUnusedReservedMemory(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern uint GetTotalReservedMemory(); + } +} diff --git a/UnityEngine/UnityEngine/Projector.cs b/UnityEngine/UnityEngine/Projector.cs new file mode 100644 index 00000000..b02f5949 --- /dev/null +++ b/UnityEngine/UnityEngine/Projector.cs @@ -0,0 +1,102 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Projector : Behaviour + { + public extern float nearClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float farClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float fieldOfView + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float aspectRatio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool isOrthoGraphic + { + get + { + return this.orthographic; + } + set + { + this.orthographic = value; + } + } + public extern bool orthographic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float orthographicSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public float orthoGraphicSize + { + get + { + return this.orthographicSize; + } + set + { + this.orthographicSize = value; + } + } + public extern int ignoreLayers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/PropertyAttribute.cs b/UnityEngine/UnityEngine/PropertyAttribute.cs new file mode 100644 index 00000000..a22fb9d7 --- /dev/null +++ b/UnityEngine/UnityEngine/PropertyAttribute.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public abstract class PropertyAttribute : Attribute + { + public int order + { + get; + set; + } + } +} diff --git a/UnityEngine/UnityEngine/QualityLevel.cs b/UnityEngine/UnityEngine/QualityLevel.cs new file mode 100644 index 00000000..ca423c60 --- /dev/null +++ b/UnityEngine/UnityEngine/QualityLevel.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + [Obsolete("See QualitySettings.names, QualitySettings.SetQualityLevel, and QualitySettings.GetQualityLevel")] + public enum QualityLevel + { + Fastest, + Fast, + Simple, + Good, + Beautiful, + Fantastic + } +} diff --git a/UnityEngine/UnityEngine/QualitySettings.cs b/UnityEngine/UnityEngine/QualitySettings.cs new file mode 100644 index 00000000..e24b4f1a --- /dev/null +++ b/UnityEngine/UnityEngine/QualitySettings.cs @@ -0,0 +1,193 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class QualitySettings : Object + { + public static extern string[] names + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("Use GetQualityLevel and SetQualityLevel")] + public static extern QualityLevel currentLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int pixelLightCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ShadowProjection shadowProjection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int shadowCascades + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float shadowDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int masterTextureLimit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AnisotropicFiltering anisotropicFiltering + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float lodBias + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int maximumLODLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int particleRaycastBudget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool softVegetation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int maxQueuedFrames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int vSyncCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int antiAliasing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ColorSpace desiredColorSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ColorSpace activeColorSpace + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern BlendWeights blendWeights + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetQualityLevel(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetQualityLevel(int index, [DefaultValue("true")] bool applyExpensiveChanges); + [ExcludeFromDocs] + public static void SetQualityLevel(int index) + { + bool applyExpensiveChanges = true; + QualitySettings.SetQualityLevel(index, applyExpensiveChanges); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void IncreaseLevel([DefaultValue("false")] bool applyExpensiveChanges); + [ExcludeFromDocs] + public static void IncreaseLevel() + { + bool applyExpensiveChanges = false; + QualitySettings.IncreaseLevel(applyExpensiveChanges); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DecreaseLevel([DefaultValue("false")] bool applyExpensiveChanges); + [ExcludeFromDocs] + public static void DecreaseLevel() + { + bool applyExpensiveChanges = false; + QualitySettings.DecreaseLevel(applyExpensiveChanges); + } + } +} diff --git a/UnityEngine/UnityEngine/Quaternion.cs b/UnityEngine/UnityEngine/Quaternion.cs new file mode 100644 index 00000000..d772c207 --- /dev/null +++ b/UnityEngine/UnityEngine/Quaternion.cs @@ -0,0 +1,345 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public struct Quaternion + { + public const float kEpsilon = 1E-06f; + public float x; + public float y; + public float z; + public float w; + public float this[int index] + { + get + { + switch (index) + { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new IndexOutOfRangeException("Invalid Quaternion index!"); + } + } + set + { + switch (index) + { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + case 3: + this.w = value; + break; + default: + throw new IndexOutOfRangeException("Invalid Quaternion index!"); + } + } + } + public static Quaternion identity + { + get + { + return new Quaternion(0f, 0f, 0f, 1f); + } + } + public Vector3 eulerAngles + { + get + { + return Quaternion.Internal_ToEulerRad(this) * 57.29578f; + } + set + { + this = Quaternion.Internal_FromEulerRad(value * 0.0174532924f); + } + } + public Quaternion(float x, float y, float z, float w) + { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + public void Set(float new_x, float new_y, float new_z, float new_w) + { + this.x = new_x; + this.y = new_y; + this.z = new_z; + this.w = new_w; + } + public static float Dot(Quaternion a, Quaternion b) + { + return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + public static Quaternion AngleAxis(float angle, Vector3 axis) + { + return Quaternion.INTERNAL_CALL_AngleAxis(angle, ref axis); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_AngleAxis(float angle, ref Vector3 axis); + public void ToAngleAxis(out float angle, out Vector3 axis) + { + Quaternion.Internal_ToAxisAngleRad(this, out axis, out angle); + angle *= 57.29578f; + } + public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection) + { + return Quaternion.INTERNAL_CALL_FromToRotation(ref fromDirection, ref toDirection); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_FromToRotation(ref Vector3 fromDirection, ref Vector3 toDirection); + public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection) + { + this = Quaternion.FromToRotation(fromDirection, toDirection); + } + public static Quaternion LookRotation(Vector3 forward, [DefaultValue("Vector3.up")] Vector3 upwards) + { + return Quaternion.INTERNAL_CALL_LookRotation(ref forward, ref upwards); + } + [ExcludeFromDocs] + public static Quaternion LookRotation(Vector3 forward) + { + Vector3 up = Vector3.up; + return Quaternion.INTERNAL_CALL_LookRotation(ref forward, ref up); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_LookRotation(ref Vector3 forward, ref Vector3 upwards); + [ExcludeFromDocs] + public void SetLookRotation(Vector3 view) + { + Vector3 up = Vector3.up; + this.SetLookRotation(view, up); + } + public void SetLookRotation(Vector3 view, [DefaultValue("Vector3.up")] Vector3 up) + { + this = Quaternion.LookRotation(view, up); + } + public static Quaternion Slerp(Quaternion from, Quaternion to, float t) + { + return Quaternion.INTERNAL_CALL_Slerp(ref from, ref to, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_Slerp(ref Quaternion from, ref Quaternion to, float t); + public static Quaternion Lerp(Quaternion from, Quaternion to, float t) + { + return Quaternion.INTERNAL_CALL_Lerp(ref from, ref to, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_Lerp(ref Quaternion from, ref Quaternion to, float t); + public static Quaternion RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta) + { + float num = Quaternion.Angle(from, to); + if (num == 0f) + { + return to; + } + float t = Mathf.Min(1f, maxDegreesDelta / num); + return Quaternion.UnclampedSlerp(from, to, t); + } + private static Quaternion UnclampedSlerp(Quaternion from, Quaternion to, float t) + { + return Quaternion.INTERNAL_CALL_UnclampedSlerp(ref from, ref to, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_UnclampedSlerp(ref Quaternion from, ref Quaternion to, float t); + public static Quaternion Inverse(Quaternion rotation) + { + return Quaternion.INTERNAL_CALL_Inverse(ref rotation); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_Inverse(ref Quaternion rotation); + public override string ToString() + { + return UnityString.Format("({0:F1}, {1:F1}, {2:F1}, {3:F1})", new object[] + { + this.x, + this.y, + this.z, + this.w + }); + } + public string ToString(string format) + { + return UnityString.Format("({0}, {1}, {2}, {3})", new object[] + { + this.x.ToString(format), + this.y.ToString(format), + this.z.ToString(format), + this.w.ToString(format) + }); + } + public static float Angle(Quaternion a, Quaternion b) + { + float f = Quaternion.Dot(a, b); + return Mathf.Acos(Mathf.Min(Mathf.Abs(f), 1f)) * 2f * 57.29578f; + } + public static Quaternion Euler(float x, float y, float z) + { + return Quaternion.Internal_FromEulerRad(new Vector3(x, y, z) * 0.0174532924f); + } + public static Quaternion Euler(Vector3 euler) + { + return Quaternion.Internal_FromEulerRad(euler * 0.0174532924f); + } + private static Vector3 Internal_ToEulerRad(Quaternion rotation) + { + return Quaternion.INTERNAL_CALL_Internal_ToEulerRad(ref rotation); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_Internal_ToEulerRad(ref Quaternion rotation); + private static Quaternion Internal_FromEulerRad(Vector3 euler) + { + return Quaternion.INTERNAL_CALL_Internal_FromEulerRad(ref euler); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_Internal_FromEulerRad(ref Vector3 euler); + private static void Internal_ToAxisAngleRad(Quaternion q, out Vector3 axis, out float angle) + { + Quaternion.INTERNAL_CALL_Internal_ToAxisAngleRad(ref q, out axis, out angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_ToAxisAngleRad(ref Quaternion q, out Vector3 axis, out float angle); + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public static Quaternion EulerRotation(float x, float y, float z) + { + return Quaternion.Internal_FromEulerRad(new Vector3(x, y, z)); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public static Quaternion EulerRotation(Vector3 euler) + { + return Quaternion.Internal_FromEulerRad(euler); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public void SetEulerRotation(float x, float y, float z) + { + this = Quaternion.Internal_FromEulerRad(new Vector3(x, y, z)); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public void SetEulerRotation(Vector3 euler) + { + this = Quaternion.Internal_FromEulerRad(euler); + } + [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees")] + public Vector3 ToEuler() + { + return Quaternion.Internal_ToEulerRad(this); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public static Quaternion EulerAngles(float x, float y, float z) + { + return Quaternion.Internal_FromEulerRad(new Vector3(x, y, z)); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public static Quaternion EulerAngles(Vector3 euler) + { + return Quaternion.Internal_FromEulerRad(euler); + } + [Obsolete("Use Quaternion.ToAngleAxis instead. This function was deprecated because it uses radians instead of degrees")] + public void ToAxisAngle(out Vector3 axis, out float angle) + { + Quaternion.Internal_ToAxisAngleRad(this, out axis, out angle); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public void SetEulerAngles(float x, float y, float z) + { + this.SetEulerRotation(new Vector3(x, y, z)); + } + [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees")] + public void SetEulerAngles(Vector3 euler) + { + this = Quaternion.EulerRotation(euler); + } + [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees")] + public static Vector3 ToEulerAngles(Quaternion rotation) + { + return Quaternion.Internal_ToEulerRad(rotation); + } + [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees")] + public Vector3 ToEulerAngles() + { + return Quaternion.Internal_ToEulerRad(this); + } + [Obsolete("Use Quaternion.AngleAxis instead. This function was deprecated because it uses radians instead of degrees")] + public static Quaternion AxisAngle(Vector3 axis, float angle) + { + return Quaternion.INTERNAL_CALL_AxisAngle(ref axis, angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Quaternion INTERNAL_CALL_AxisAngle(ref Vector3 axis, float angle); + [Obsolete("Use Quaternion.AngleAxis instead. This function was deprecated because it uses radians instead of degrees")] + public void SetAxisAngle(Vector3 axis, float angle) + { + this = Quaternion.AxisAngle(axis, angle); + } + public override int GetHashCode() + { + return this.x.GetHashCode() ^ this.y.GetHashCode() << 2 ^ this.z.GetHashCode() >> 2 ^ this.w.GetHashCode() >> 1; + } + public override bool Equals(object other) + { + if (!(other is Quaternion)) + { + return false; + } + Quaternion quaternion = (Quaternion)other; + return this.x.Equals(quaternion.x) && this.y.Equals(quaternion.y) && this.z.Equals(quaternion.z) && this.w.Equals(quaternion.w); + } + public static Quaternion operator *(Quaternion lhs, Quaternion rhs) + { + return new Quaternion(lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y, lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z, lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x, lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z); + } + public static Vector3 operator *(Quaternion rotation, Vector3 point) + { + float num = rotation.x * 2f; + float num2 = rotation.y * 2f; + float num3 = rotation.z * 2f; + float num4 = rotation.x * num; + float num5 = rotation.y * num2; + float num6 = rotation.z * num3; + float num7 = rotation.x * num2; + float num8 = rotation.x * num3; + float num9 = rotation.y * num3; + float num10 = rotation.w * num; + float num11 = rotation.w * num2; + float num12 = rotation.w * num3; + Vector3 result; + result.x = (1f - (num5 + num6)) * point.x + (num7 - num12) * point.y + (num8 + num11) * point.z; + result.y = (num7 + num12) * point.x + (1f - (num4 + num6)) * point.y + (num9 - num10) * point.z; + result.z = (num8 - num11) * point.x + (num9 + num10) * point.y + (1f - (num4 + num5)) * point.z; + return result; + } + public static bool operator ==(Quaternion lhs, Quaternion rhs) + { + return Quaternion.Dot(lhs, rhs) > 0.999999f; + } + public static bool operator !=(Quaternion lhs, Quaternion rhs) + { + return Quaternion.Dot(lhs, rhs) <= 0.999999f; + } + } +} diff --git a/UnityEngine/UnityEngine/QueueMode.cs b/UnityEngine/UnityEngine/QueueMode.cs new file mode 100644 index 00000000..37b06b83 --- /dev/null +++ b/UnityEngine/UnityEngine/QueueMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum QueueMode + { + CompleteOthers, + PlayNow = 2 + } +} diff --git a/UnityEngine/UnityEngine/RPC.cs b/UnityEngine/UnityEngine/RPC.cs new file mode 100644 index 00000000..bb769530 --- /dev/null +++ b/UnityEngine/UnityEngine/RPC.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + public sealed class RPC : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/RPCMode.cs b/UnityEngine/UnityEngine/RPCMode.cs new file mode 100644 index 00000000..ff026d95 --- /dev/null +++ b/UnityEngine/UnityEngine/RPCMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum RPCMode + { + Server, + Others, + OthersBuffered = 5, + All = 2, + AllBuffered = 6 + } +} diff --git a/UnityEngine/UnityEngine/Random.cs b/UnityEngine/UnityEngine/Random.cs new file mode 100644 index 00000000..57143d8b --- /dev/null +++ b/UnityEngine/UnityEngine/Random.cs @@ -0,0 +1,79 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Random + { + public static extern int seed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float value + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Vector3 insideUnitSphere + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Vector2 insideUnitCircle + { + get + { + Vector2 result; + Random.GetRandomUnitCircle(out result); + return result; + } + } + public static extern Vector3 onUnitSphere + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Quaternion rotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Quaternion rotationUniform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float Range(float min, float max); + public static int Range(int min, int max) + { + return Random.RandomRangeInt(min, max); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int RandomRangeInt(int min, int max); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void GetRandomUnitCircle(out Vector2 output); + [Obsolete("Use Random.Range instead")] + public static float RandomRange(float min, float max) + { + return Random.Range(min, max); + } + [Obsolete("Use Random.Range instead")] + public static int RandomRange(int min, int max) + { + return Random.Range(min, max); + } + } +} diff --git a/UnityEngine/UnityEngine/RangeAttribute.cs b/UnityEngine/UnityEngine/RangeAttribute.cs new file mode 100644 index 00000000..831d8a1a --- /dev/null +++ b/UnityEngine/UnityEngine/RangeAttribute.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public sealed class RangeAttribute : PropertyAttribute + { + public readonly float min; + public readonly float max; + public RangeAttribute(float min, float max) + { + this.min = min; + this.max = max; + } + } +} diff --git a/UnityEngine/UnityEngine/Ray.cs b/UnityEngine/UnityEngine/Ray.cs new file mode 100644 index 00000000..6b5264b4 --- /dev/null +++ b/UnityEngine/UnityEngine/Ray.cs @@ -0,0 +1,56 @@ +using System; +namespace UnityEngine +{ + public struct Ray + { + private Vector3 m_Origin; + private Vector3 m_Direction; + public Vector3 origin + { + get + { + return this.m_Origin; + } + set + { + this.m_Origin = value; + } + } + public Vector3 direction + { + get + { + return this.m_Direction; + } + set + { + this.m_Direction = value.normalized; + } + } + public Ray(Vector3 origin, Vector3 direction) + { + this.m_Origin = origin; + this.m_Direction = direction.normalized; + } + public Vector3 GetPoint(float distance) + { + return this.m_Origin + this.m_Direction * distance; + } + public override string ToString() + { + return UnityString.Format("Origin: {0}, Dir: {1}", new object[] + { + this.m_Origin, + this.m_Direction + }); + } + public string ToString(string format) + { + return UnityString.Format("Origin: {0}, Dir: {1}", new object[] + { + this.m_Origin.ToString(format), + this.m_Direction.ToString(format) + }); + } + } +} diff --git a/UnityEngine/UnityEngine/Ray2D.cs b/UnityEngine/UnityEngine/Ray2D.cs new file mode 100644 index 00000000..7ca4a8dc --- /dev/null +++ b/UnityEngine/UnityEngine/Ray2D.cs @@ -0,0 +1,56 @@ +using System; +namespace UnityEngine +{ + public struct Ray2D + { + private Vector2 m_Origin; + private Vector2 m_Direction; + public Vector2 origin + { + get + { + return this.m_Origin; + } + set + { + this.m_Origin = value; + } + } + public Vector2 direction + { + get + { + return this.m_Direction; + } + set + { + this.m_Direction = value.normalized; + } + } + public Ray2D(Vector2 origin, Vector2 direction) + { + this.m_Origin = origin; + this.m_Direction = direction.normalized; + } + public Vector2 GetPoint(float distance) + { + return this.m_Origin + this.m_Direction * distance; + } + public override string ToString() + { + return UnityString.Format("Origin: {0}, Dir: {1}", new object[] + { + this.m_Origin, + this.m_Direction + }); + } + public string ToString(string format) + { + return UnityString.Format("Origin: {0}, Dir: {1}", new object[] + { + this.m_Origin.ToString(format), + this.m_Direction.ToString(format) + }); + } + } +} diff --git a/UnityEngine/UnityEngine/RaycastCollider.cs b/UnityEngine/UnityEngine/RaycastCollider.cs new file mode 100644 index 00000000..7ea3837e --- /dev/null +++ b/UnityEngine/UnityEngine/RaycastCollider.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable")] + public sealed class RaycastCollider : Collider + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable")] + public extern float length + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable"), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/RaycastHit.cs b/UnityEngine/UnityEngine/RaycastHit.cs new file mode 100644 index 00000000..bdde329c --- /dev/null +++ b/UnityEngine/UnityEngine/RaycastHit.cs @@ -0,0 +1,145 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct RaycastHit + { + private Vector3 m_Point; + private Vector3 m_Normal; + private int m_FaceID; + private float m_Distance; + private Vector2 m_UV; + private Collider m_Collider; + public Vector3 point + { + get + { + return this.m_Point; + } + set + { + this.m_Point = value; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + set + { + this.m_Normal = value; + } + } + public Vector3 barycentricCoordinate + { + get + { + return new Vector3(1f - (this.m_UV.y + this.m_UV.x), this.m_UV.x, this.m_UV.y); + } + set + { + this.m_UV = value; + } + } + public float distance + { + get + { + return this.m_Distance; + } + set + { + this.m_Distance = value; + } + } + public int triangleIndex + { + get + { + return this.m_FaceID; + } + } + public Vector2 textureCoord + { + get + { + Vector2 result; + RaycastHit.CalculateRaycastTexCoord(out result, this.collider, this.m_UV, this.m_Point, this.m_FaceID, 0); + return result; + } + } + public Vector2 textureCoord2 + { + get + { + Vector2 result; + RaycastHit.CalculateRaycastTexCoord(out result, this.collider, this.m_UV, this.m_Point, this.m_FaceID, 1); + return result; + } + } + [Obsolete("Use textureCoord2 instead")] + public Vector2 textureCoord1 + { + get + { + Vector2 result; + RaycastHit.CalculateRaycastTexCoord(out result, this.collider, this.m_UV, this.m_Point, this.m_FaceID, 1); + return result; + } + } + public Vector2 lightmapCoord + { + get + { + Vector2 result; + RaycastHit.CalculateRaycastTexCoord(out result, this.collider, this.m_UV, this.m_Point, this.m_FaceID, 1); + if (this.collider.renderer != null) + { + Vector4 lightmapTilingOffset = this.collider.renderer.lightmapTilingOffset; + result.x = result.x * lightmapTilingOffset.x + lightmapTilingOffset.z; + result.y = result.y * lightmapTilingOffset.y + lightmapTilingOffset.w; + } + return result; + } + } + public Collider collider + { + get + { + return this.m_Collider; + } + } + public Rigidbody rigidbody + { + get + { + return (!(this.collider != null)) ? null : this.collider.attachedRigidbody; + } + } + public Transform transform + { + get + { + Rigidbody rigidbody = this.rigidbody; + if (rigidbody != null) + { + return rigidbody.transform; + } + if (this.collider != null) + { + return this.collider.transform; + } + return null; + } + } + private static void CalculateRaycastTexCoord(out Vector2 output, Collider col, Vector2 uv, Vector3 point, int face, int index) + { + RaycastHit.INTERNAL_CALL_CalculateRaycastTexCoord(out output, col, ref uv, ref point, face, index); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_CalculateRaycastTexCoord(out Vector2 output, Collider col, ref Vector2 uv, ref Vector3 point, int face, int index); + } +} diff --git a/UnityEngine/UnityEngine/RaycastHit2D.cs b/UnityEngine/UnityEngine/RaycastHit2D.cs new file mode 100644 index 00000000..4a419ab1 --- /dev/null +++ b/UnityEngine/UnityEngine/RaycastHit2D.cs @@ -0,0 +1,114 @@ +using System; +namespace UnityEngine +{ + public struct RaycastHit2D + { + private Vector2 m_Centroid; + private Vector2 m_Point; + private Vector2 m_Normal; + private float m_Distance; + private float m_Fraction; + private Collider2D m_Collider; + public Vector2 centroid + { + get + { + return this.m_Centroid; + } + set + { + this.m_Centroid = value; + } + } + public Vector2 point + { + get + { + return this.m_Point; + } + set + { + this.m_Point = value; + } + } + public Vector2 normal + { + get + { + return this.m_Normal; + } + set + { + this.m_Normal = value; + } + } + public float distance + { + get + { + return this.m_Distance; + } + set + { + this.m_Distance = value; + } + } + public float fraction + { + get + { + return this.m_Fraction; + } + set + { + this.m_Fraction = value; + } + } + public Collider2D collider + { + get + { + return this.m_Collider; + } + } + public Rigidbody2D rigidbody + { + get + { + return (!(this.collider != null)) ? null : this.collider.attachedRigidbody; + } + } + public Transform transform + { + get + { + Rigidbody2D rigidbody = this.rigidbody; + if (rigidbody != null) + { + return rigidbody.transform; + } + if (this.collider != null) + { + return this.collider.transform; + } + return null; + } + } + public int CompareTo(RaycastHit2D other) + { + if (this.collider == null) + { + return 1; + } + if (other.collider == null) + { + return -1; + } + return this.fraction.CompareTo(other.fraction); + } + public static implicit operator bool(RaycastHit2D hit) + { + return hit.collider != null; + } + } +} diff --git a/UnityEngine/UnityEngine/Rect.cs b/UnityEngine/UnityEngine/Rect.cs new file mode 100644 index 00000000..9c47886d --- /dev/null +++ b/UnityEngine/UnityEngine/Rect.cs @@ -0,0 +1,320 @@ +using System; +namespace UnityEngine +{ + public struct Rect + { + private float m_XMin; + private float m_YMin; + private float m_Width; + private float m_Height; + public float x + { + get + { + return this.m_XMin; + } + set + { + this.m_XMin = value; + } + } + public float y + { + get + { + return this.m_YMin; + } + set + { + this.m_YMin = value; + } + } + public Vector2 position + { + get + { + return new Vector2(this.m_XMin, this.m_YMin); + } + set + { + this.m_XMin = value.x; + this.m_YMin = value.y; + } + } + public Vector2 center + { + get + { + return new Vector2(this.x + this.m_Width / 2f, this.y + this.m_Height / 2f); + } + set + { + this.m_XMin = value.x - this.m_Width / 2f; + this.m_YMin = value.y - this.m_Height / 2f; + } + } + public Vector2 min + { + get + { + return new Vector2(this.xMin, this.yMin); + } + set + { + this.xMin = value.x; + this.yMin = value.y; + } + } + public Vector2 max + { + get + { + return new Vector2(this.xMax, this.yMax); + } + set + { + this.xMax = value.x; + this.yMax = value.y; + } + } + public float width + { + get + { + return this.m_Width; + } + set + { + this.m_Width = value; + } + } + public float height + { + get + { + return this.m_Height; + } + set + { + this.m_Height = value; + } + } + public Vector2 size + { + get + { + return new Vector2(this.m_Width, this.m_Height); + } + set + { + this.m_Width = value.x; + this.m_Height = value.y; + } + } + [Obsolete("use xMin")] + public float left + { + get + { + return this.m_XMin; + } + } + [Obsolete("use xMax")] + public float right + { + get + { + return this.m_XMin + this.m_Width; + } + } + [Obsolete("use yMin")] + public float top + { + get + { + return this.m_YMin; + } + } + [Obsolete("use yMax")] + public float bottom + { + get + { + return this.m_YMin + this.m_Height; + } + } + public float xMin + { + get + { + return this.m_XMin; + } + set + { + float xMax = this.xMax; + this.m_XMin = value; + this.m_Width = xMax - this.m_XMin; + } + } + public float yMin + { + get + { + return this.m_YMin; + } + set + { + float yMax = this.yMax; + this.m_YMin = value; + this.m_Height = yMax - this.m_YMin; + } + } + public float xMax + { + get + { + return this.m_Width + this.m_XMin; + } + set + { + this.m_Width = value - this.m_XMin; + } + } + public float yMax + { + get + { + return this.m_Height + this.m_YMin; + } + set + { + this.m_Height = value - this.m_YMin; + } + } + public Rect(float left, float top, float width, float height) + { + this.m_XMin = left; + this.m_YMin = top; + this.m_Width = width; + this.m_Height = height; + } + public Rect(Rect source) + { + this.m_XMin = source.m_XMin; + this.m_YMin = source.m_YMin; + this.m_Width = source.m_Width; + this.m_Height = source.m_Height; + } + public static Rect MinMaxRect(float left, float top, float right, float bottom) + { + return new Rect(left, top, right - left, bottom - top); + } + public void Set(float left, float top, float width, float height) + { + this.m_XMin = left; + this.m_YMin = top; + this.m_Width = width; + this.m_Height = height; + } + public override string ToString() + { + return UnityString.Format("(x:{0:F2}, y:{1:F2}, width:{2:F2}, height:{3:F2})", new object[] + { + this.x, + this.y, + this.width, + this.height + }); + } + public string ToString(string format) + { + return UnityString.Format("(x:{0}, y:{1}, width:{2}, height:{3})", new object[] + { + this.x.ToString(format), + this.y.ToString(format), + this.width.ToString(format), + this.height.ToString(format) + }); + } + public bool Contains(Vector2 point) + { + return point.x >= this.xMin && point.x < this.xMax && point.y >= this.yMin && point.y < this.yMax; + } + public bool Contains(Vector3 point) + { + return point.x >= this.xMin && point.x < this.xMax && point.y >= this.yMin && point.y < this.yMax; + } + public bool Contains(Vector3 point, bool allowInverse) + { + if (!allowInverse) + { + return this.Contains(point); + } + bool flag = false; + if ((this.width < 0f && point.x <= this.xMin && point.x > this.xMax) || (this.width >= 0f && point.x >= this.xMin && point.x < this.xMax)) + { + flag = true; + } + return flag && ((this.height < 0f && point.y <= this.yMin && point.y > this.yMax) || (this.height >= 0f && point.y >= this.yMin && point.y < this.yMax)); + } + private static Rect OrderMinMax(Rect rect) + { + if (rect.xMin > rect.xMax) + { + float xMin = rect.xMin; + rect.xMin = rect.xMax; + rect.xMax = xMin; + } + if (rect.yMin > rect.yMax) + { + float yMin = rect.yMin; + rect.yMin = rect.yMax; + rect.yMax = yMin; + } + return rect; + } + public bool Overlaps(Rect other) + { + return other.xMax > this.xMin && other.xMin < this.xMax && other.yMax > this.yMin && other.yMin < this.yMax; + } + public bool Overlaps(Rect other, bool allowInverse) + { + Rect rect = this; + if (allowInverse) + { + rect = Rect.OrderMinMax(rect); + other = Rect.OrderMinMax(other); + } + return rect.Overlaps(other); + } + public static Vector2 NormalizedToPoint(Rect rectangle, Vector2 normalizedRectCoordinates) + { + return new Vector2(Mathf.Lerp(rectangle.x, rectangle.xMax, normalizedRectCoordinates.x), Mathf.Lerp(rectangle.y, rectangle.yMax, normalizedRectCoordinates.y)); + } + public static Vector2 PointToNormalized(Rect rectangle, Vector2 point) + { + return new Vector2(Mathf.InverseLerp(rectangle.x, rectangle.xMax, point.x), Mathf.InverseLerp(rectangle.y, rectangle.yMax, point.y)); + } + public override int GetHashCode() + { + return this.x.GetHashCode() ^ this.width.GetHashCode() << 2 ^ this.y.GetHashCode() >> 2 ^ this.height.GetHashCode() >> 1; + } + public override bool Equals(object other) + { + if (!(other is Rect)) + { + return false; + } + Rect rect = (Rect)other; + return this.x.Equals(rect.x) && this.y.Equals(rect.y) && this.width.Equals(rect.width) && this.height.Equals(rect.height); + } + public static bool operator !=(Rect lhs, Rect rhs) + { + return lhs.x != rhs.x || lhs.y != rhs.y || lhs.width != rhs.width || lhs.height != rhs.height; + } + public static bool operator ==(Rect lhs, Rect rhs) + { + return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; + } + } +} diff --git a/UnityEngine/UnityEngine/RectOffset.cs b/UnityEngine/UnityEngine/RectOffset.cs new file mode 100644 index 00000000..5e67bc7c --- /dev/null +++ b/UnityEngine/UnityEngine/RectOffset.cs @@ -0,0 +1,117 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class RectOffset + { + [NotRenamed] + [NonSerialized] + internal IntPtr m_Ptr; + private GUIStyle m_SourceStyle; + public extern int left + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int right + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int top + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int bottom + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int horizontal + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int vertical + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public RectOffset() + { + this.Init(); + } + internal RectOffset(GUIStyle sourceStyle, IntPtr source) + { + this.m_SourceStyle = sourceStyle; + this.m_Ptr = source; + } + public RectOffset(int left, int right, int top, int bottom) + { + this.Init(); + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + } + ~RectOffset() + { + if (this.m_SourceStyle == null) + { + this.Cleanup(); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(); + public Rect Add(Rect rect) + { + return RectOffset.INTERNAL_CALL_Add(this, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_Add(RectOffset self, ref Rect rect); + public Rect Remove(Rect rect) + { + return RectOffset.INTERNAL_CALL_Remove(this, ref rect); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Rect INTERNAL_CALL_Remove(RectOffset self, ref Rect rect); + public override string ToString() + { + return UnityString.Format("RectOffset (l:{0} r:{1} t:{2} b:{3})", new object[] + { + this.left, + this.right, + this.top, + this.bottom + }); + } + } +} diff --git a/UnityEngine/UnityEngine/RectTransform.cs b/UnityEngine/UnityEngine/RectTransform.cs new file mode 100644 index 00000000..00f1643a --- /dev/null +++ b/UnityEngine/UnityEngine/RectTransform.cs @@ -0,0 +1,288 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class RectTransform : Transform + { + public enum Edge + { + Left, + Right, + Top, + Bottom + } + public enum Axis + { + Horizontal, + Vertical + } + public delegate void ReapplyDrivenProperties(RectTransform driven); + public static event RectTransform.ReapplyDrivenProperties reapplyDrivenProperties + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + RectTransform.reapplyDrivenProperties = (RectTransform.ReapplyDrivenProperties)Delegate.Combine(RectTransform.reapplyDrivenProperties, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + RectTransform.reapplyDrivenProperties = (RectTransform.ReapplyDrivenProperties)Delegate.Remove(RectTransform.reapplyDrivenProperties, value); + } + } + public Rect rect + { + get + { + Rect result; + this.INTERNAL_get_rect(out result); + return result; + } + } + public Vector2 anchorMin + { + get + { + Vector2 result; + this.INTERNAL_get_anchorMin(out result); + return result; + } + set + { + this.INTERNAL_set_anchorMin(ref value); + } + } + public Vector2 anchorMax + { + get + { + Vector2 result; + this.INTERNAL_get_anchorMax(out result); + return result; + } + set + { + this.INTERNAL_set_anchorMax(ref value); + } + } + public Vector3 anchoredPosition3D + { + get + { + Vector2 anchoredPosition = this.anchoredPosition; + return new Vector3(anchoredPosition.x, anchoredPosition.y, base.localPosition.z); + } + set + { + this.anchoredPosition = new Vector2(value.x, value.y); + Vector3 localPosition = base.localPosition; + localPosition.z = value.z; + base.localPosition = localPosition; + } + } + public Vector2 anchoredPosition + { + get + { + Vector2 result; + this.INTERNAL_get_anchoredPosition(out result); + return result; + } + set + { + this.INTERNAL_set_anchoredPosition(ref value); + } + } + public Vector2 sizeDelta + { + get + { + Vector2 result; + this.INTERNAL_get_sizeDelta(out result); + return result; + } + set + { + this.INTERNAL_set_sizeDelta(ref value); + } + } + public Vector2 pivot + { + get + { + Vector2 result; + this.INTERNAL_get_pivot(out result); + return result; + } + set + { + this.INTERNAL_set_pivot(ref value); + } + } + internal extern Object drivenByObject + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern DrivenTransformProperties drivenProperties + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 offsetMin + { + get + { + return this.anchoredPosition - Vector2.Scale(this.sizeDelta, this.pivot); + } + set + { + Vector2 vector = value - (this.anchoredPosition - Vector2.Scale(this.sizeDelta, this.pivot)); + this.sizeDelta -= vector; + this.anchoredPosition += Vector2.Scale(vector, Vector2.one - this.pivot); + } + } + public Vector2 offsetMax + { + get + { + return this.anchoredPosition + Vector2.Scale(this.sizeDelta, Vector2.one - this.pivot); + } + set + { + Vector2 vector = value - (this.anchoredPosition + Vector2.Scale(this.sizeDelta, Vector2.one - this.pivot)); + this.sizeDelta += vector; + this.anchoredPosition += Vector2.Scale(vector, this.pivot); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rect(out Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anchorMin(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anchorMin(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anchorMax(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anchorMax(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anchoredPosition(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anchoredPosition(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_sizeDelta(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_sizeDelta(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_pivot(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_pivot(ref Vector2 value); + internal static void SendReapplyDrivenProperties(RectTransform driven) + { + if (RectTransform.reapplyDrivenProperties != null) + { + RectTransform.reapplyDrivenProperties(driven); + } + } + public void GetLocalCorners(Vector3[] fourCornersArray) + { + if (fourCornersArray == null || fourCornersArray.Length < 4) + { + Debug.LogError("Calling GetLocalCorners with an array that is null or has less than 4 elements."); + return; + } + Rect rect = this.rect; + float x = rect.x; + float y = rect.y; + float xMax = rect.xMax; + float yMax = rect.yMax; + fourCornersArray[0] = new Vector3(x, y, 0f); + fourCornersArray[1] = new Vector3(x, yMax, 0f); + fourCornersArray[2] = new Vector3(xMax, yMax, 0f); + fourCornersArray[3] = new Vector3(xMax, y, 0f); + } + public void GetWorldCorners(Vector3[] fourCornersArray) + { + if (fourCornersArray == null || fourCornersArray.Length < 4) + { + Debug.LogError("Calling GetWorldCorners with an array that is null or has less than 4 elements."); + return; + } + this.GetLocalCorners(fourCornersArray); + Transform transform = base.transform; + for (int i = 0; i < 4; i++) + { + fourCornersArray[i] = transform.TransformPoint(fourCornersArray[i]); + } + } + internal Rect GetRectInParentSpace() + { + Rect rect = this.rect; + Vector2 a = this.offsetMin + Vector2.Scale(this.pivot, rect.size); + Transform parent = base.transform.parent; + if (parent) + { + RectTransform component = parent.GetComponent(); + if (component) + { + a += Vector2.Scale(this.anchorMin, component.rect.size); + } + } + rect.x += a.x; + rect.y += a.y; + return rect; + } + public void SetInsetAndSizeFromParentEdge(RectTransform.Edge edge, float inset, float size) + { + int index = (edge != RectTransform.Edge.Top && edge != RectTransform.Edge.Bottom) ? 0 : 1; + bool flag = edge == RectTransform.Edge.Top || edge == RectTransform.Edge.Right; + float value = (float)((!flag) ? 0 : 1); + Vector2 vector = this.anchorMin; + vector[index] = value; + this.anchorMin = vector; + vector = this.anchorMax; + vector[index] = value; + this.anchorMax = vector; + Vector2 sizeDelta = this.sizeDelta; + sizeDelta[index] = size; + this.sizeDelta = sizeDelta; + Vector2 anchoredPosition = this.anchoredPosition; + anchoredPosition[index] = ((!flag) ? (inset + size * this.pivot[index]) : (-inset - size * (1f - this.pivot[index]))); + this.anchoredPosition = anchoredPosition; + } + public void SetSizeWithCurrentAnchors(RectTransform.Axis axis, float size) + { + Vector2 sizeDelta = this.sizeDelta; + sizeDelta[(int)axis] = size - this.GetParentSize()[(int)axis] * (this.anchorMax[(int)axis] - this.anchorMin[(int)axis]); + this.sizeDelta = sizeDelta; + } + private Vector2 GetParentSize() + { + RectTransform rectTransform = base.parent as RectTransform; + if (!rectTransform) + { + return Vector2.zero; + } + return rectTransform.rect.size; + } + } +} diff --git a/UnityEngine/UnityEngine/RectTransformUtility.cs b/UnityEngine/UnityEngine/RectTransformUtility.cs new file mode 100644 index 00000000..db05ca0c --- /dev/null +++ b/UnityEngine/UnityEngine/RectTransformUtility.cs @@ -0,0 +1,174 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class RectTransformUtility + { + private static Vector3[] s_Corners = new Vector3[4]; + private RectTransformUtility() + { + } + public static bool RectangleContainsScreenPoint(RectTransform rect, Vector2 screenPoint, Camera cam) + { + return RectTransformUtility.INTERNAL_CALL_RectangleContainsScreenPoint(rect, ref screenPoint, cam); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_RectangleContainsScreenPoint(RectTransform rect, ref Vector2 screenPoint, Camera cam); + public static Vector2 PixelAdjustPoint(Vector2 point, Transform elementTransform, Canvas canvas) + { + Vector2 result; + RectTransformUtility.PixelAdjustPoint(point, elementTransform, canvas, out result); + return result; + } + private static void PixelAdjustPoint(Vector2 point, Transform elementTransform, Canvas canvas, out Vector2 output) + { + RectTransformUtility.INTERNAL_CALL_PixelAdjustPoint(ref point, elementTransform, canvas, out output); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_PixelAdjustPoint(ref Vector2 point, Transform elementTransform, Canvas canvas, out Vector2 output); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Rect PixelAdjustRect(RectTransform rectTransform, Canvas canvas); + public static bool ScreenPointToWorldPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector3 worldPoint) + { + worldPoint = Vector2.zero; + Ray ray = RectTransformUtility.ScreenPointToRay(cam, screenPoint); + Plane plane = new Plane(rect.rotation * Vector3.back, rect.position); + float distance; + if (!plane.Raycast(ray, out distance)) + { + return false; + } + worldPoint = ray.GetPoint(distance); + return true; + } + public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint) + { + localPoint = Vector2.zero; + Vector3 position; + if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, screenPoint, cam, out position)) + { + localPoint = rect.InverseTransformPoint(position); + return true; + } + return false; + } + public static Ray ScreenPointToRay(Camera cam, Vector2 screenPos) + { + if (cam != null) + { + return cam.ScreenPointToRay(screenPos); + } + Vector3 origin = screenPos; + origin.z -= 100f; + return new Ray(origin, Vector3.forward); + } + public static Vector2 WorldToScreenPoint(Camera cam, Vector3 worldPoint) + { + if (cam == null) + { + return new Vector2(worldPoint.x, worldPoint.y); + } + return cam.WorldToScreenPoint(worldPoint); + } + public static Bounds CalculateRelativeRectTransformBounds(Transform root, Transform child) + { + RectTransform[] componentsInChildren = child.GetComponentsInChildren(false); + if (componentsInChildren.Length > 0) + { + Vector3 vector = new Vector3(3.40282347E+38f, 3.40282347E+38f, 3.40282347E+38f); + Vector3 vector2 = new Vector3(-3.40282347E+38f, -3.40282347E+38f, -3.40282347E+38f); + Matrix4x4 worldToLocalMatrix = root.worldToLocalMatrix; + int i = 0; + int num = componentsInChildren.Length; + while (i < num) + { + componentsInChildren[i].GetWorldCorners(RectTransformUtility.s_Corners); + for (int j = 0; j < 4; j++) + { + Vector3 lhs = worldToLocalMatrix.MultiplyPoint3x4(RectTransformUtility.s_Corners[j]); + vector = Vector3.Min(lhs, vector); + vector2 = Vector3.Max(lhs, vector2); + } + i++; + } + Bounds result = new Bounds(vector, Vector3.zero); + result.Encapsulate(vector2); + return result; + } + return new Bounds(Vector3.zero, Vector3.zero); + } + public static Bounds CalculateRelativeRectTransformBounds(Transform trans) + { + return RectTransformUtility.CalculateRelativeRectTransformBounds(trans, trans); + } + public static void FlipLayoutOnAxis(RectTransform rect, int axis, bool keepPositioning, bool recursive) + { + if (rect == null) + { + return; + } + if (recursive) + { + for (int i = 0; i < rect.childCount; i++) + { + RectTransform rectTransform = rect.GetChild(i) as RectTransform; + if (rectTransform != null) + { + RectTransformUtility.FlipLayoutOnAxis(rectTransform, axis, false, true); + } + } + } + Vector2 pivot = rect.pivot; + pivot[axis] = 1f - pivot[axis]; + rect.pivot = pivot; + if (keepPositioning) + { + return; + } + Vector2 anchoredPosition = rect.anchoredPosition; + anchoredPosition[axis] = -anchoredPosition[axis]; + rect.anchoredPosition = anchoredPosition; + Vector2 anchorMin = rect.anchorMin; + Vector2 anchorMax = rect.anchorMax; + float num = anchorMin[axis]; + anchorMin[axis] = 1f - anchorMax[axis]; + anchorMax[axis] = 1f - num; + rect.anchorMin = anchorMin; + rect.anchorMax = anchorMax; + } + public static void FlipLayoutAxes(RectTransform rect, bool keepPositioning, bool recursive) + { + if (rect == null) + { + return; + } + if (recursive) + { + for (int i = 0; i < rect.childCount; i++) + { + RectTransform rectTransform = rect.GetChild(i) as RectTransform; + if (rectTransform != null) + { + RectTransformUtility.FlipLayoutAxes(rectTransform, false, true); + } + } + } + rect.pivot = RectTransformUtility.GetTransposed(rect.pivot); + rect.sizeDelta = RectTransformUtility.GetTransposed(rect.sizeDelta); + if (keepPositioning) + { + return; + } + rect.anchoredPosition = RectTransformUtility.GetTransposed(rect.anchoredPosition); + rect.anchorMin = RectTransformUtility.GetTransposed(rect.anchorMin); + rect.anchorMax = RectTransformUtility.GetTransposed(rect.anchorMax); + } + private static Vector2 GetTransposed(Vector2 input) + { + return new Vector2(input.y, input.x); + } + } +} diff --git a/UnityEngine/UnityEngine/ReferenceData.cs b/UnityEngine/UnityEngine/ReferenceData.cs new file mode 100644 index 00000000..628ec6a4 --- /dev/null +++ b/UnityEngine/UnityEngine/ReferenceData.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + internal struct ReferenceData + { + public int instanceID; + public IntPtr cachedPtr; + } +} diff --git a/UnityEngine/UnityEngine/RemoteNotification.cs b/UnityEngine/UnityEngine/RemoteNotification.cs new file mode 100644 index 00000000..89f00729 --- /dev/null +++ b/UnityEngine/UnityEngine/RemoteNotification.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class RemoteNotification + { + private IntPtr notificationWrapper; + public extern string alertBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int applicationIconBadgeNumber + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string soundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern IDictionary userInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private RemoteNotification() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~RemoteNotification() + { + this.Destroy(); + } + } +} diff --git a/UnityEngine/UnityEngine/RemoteNotificationType.cs b/UnityEngine/UnityEngine/RemoteNotificationType.cs new file mode 100644 index 00000000..f31b126c --- /dev/null +++ b/UnityEngine/UnityEngine/RemoteNotificationType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum RemoteNotificationType + { + None, + Badge, + Sound, + Alert = 4 + } +} diff --git a/UnityEngine/UnityEngine/RenderBuffer.cs b/UnityEngine/UnityEngine/RenderBuffer.cs new file mode 100644 index 00000000..a3bfb9a0 --- /dev/null +++ b/UnityEngine/UnityEngine/RenderBuffer.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public struct RenderBuffer + { + internal int m_RenderTextureInstanceID; + internal IntPtr m_BufferPtr; + } +} diff --git a/UnityEngine/UnityEngine/RenderMode.cs b/UnityEngine/UnityEngine/RenderMode.cs new file mode 100644 index 00000000..c52981dc --- /dev/null +++ b/UnityEngine/UnityEngine/RenderMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum RenderMode + { + ScreenSpaceOverlay, + ScreenSpaceCamera, + WorldSpace + } +} diff --git a/UnityEngine/UnityEngine/RenderSettings.cs b/UnityEngine/UnityEngine/RenderSettings.cs new file mode 100644 index 00000000..ff905d8b --- /dev/null +++ b/UnityEngine/UnityEngine/RenderSettings.cs @@ -0,0 +1,127 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class RenderSettings : Object + { + public static extern bool fog + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern FogMode fogMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color fogColor + { + get + { + Color result; + RenderSettings.INTERNAL_get_fogColor(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_fogColor(ref value); + } + } + public static extern float fogDensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float fogStartDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float fogEndDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color ambientLight + { + get + { + Color result; + RenderSettings.INTERNAL_get_ambientLight(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_ambientLight(ref value); + } + } + public static extern float haloStrength + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float flareStrength + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float flareFadeSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Material skybox + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_fogColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_fogColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_ambientLight(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_ambientLight(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/RenderTexture.cs b/UnityEngine/UnityEngine/RenderTexture.cs new file mode 100644 index 00000000..0d3c6f38 --- /dev/null +++ b/UnityEngine/UnityEngine/RenderTexture.cs @@ -0,0 +1,313 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class RenderTexture : Texture + { + public override int width + { + get + { + return RenderTexture.Internal_GetWidth(this); + } + set + { + RenderTexture.Internal_SetWidth(this, value); + } + } + public override int height + { + get + { + return RenderTexture.Internal_GetHeight(this); + } + set + { + RenderTexture.Internal_SetHeight(this, value); + } + } + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isPowerOfTwo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool sRGB + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern RenderTextureFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useMipMap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool generateMips + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isCubemap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isVolume + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int volumeDepth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int antiAliasing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool enableRandomWrite + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public RenderBuffer colorBuffer + { + get + { + RenderBuffer result; + this.GetColorBuffer(out result); + return result; + } + } + public RenderBuffer depthBuffer + { + get + { + RenderBuffer result; + this.GetDepthBuffer(out result); + return result; + } + } + public static extern RenderTexture active + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use SystemInfo.supportsRenderTextures instead.")] + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public RenderTexture(int width, int height, int depth, RenderTextureFormat format, RenderTextureReadWrite readWrite) + { + RenderTexture.Internal_CreateRenderTexture(this); + this.width = width; + this.height = height; + this.depth = depth; + this.format = format; + bool sRGB = readWrite == RenderTextureReadWrite.sRGB; + if (readWrite == RenderTextureReadWrite.Default) + { + sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); + } + RenderTexture.Internal_SetSRGBReadWrite(this, sRGB); + } + public RenderTexture(int width, int height, int depth, RenderTextureFormat format) + { + RenderTexture.Internal_CreateRenderTexture(this); + this.width = width; + this.height = height; + this.depth = depth; + this.format = format; + RenderTexture.Internal_SetSRGBReadWrite(this, QualitySettings.activeColorSpace == ColorSpace.Linear); + } + public RenderTexture(int width, int height, int depth) + { + RenderTexture.Internal_CreateRenderTexture(this); + this.width = width; + this.height = height; + this.depth = depth; + this.format = RenderTextureFormat.Default; + RenderTexture.Internal_SetSRGBReadWrite(this, QualitySettings.activeColorSpace == ColorSpace.Linear); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateRenderTexture([Writable] RenderTexture rt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern RenderTexture GetTemporary(int width, int height, [DefaultValue("0")] int depthBuffer, [DefaultValue("RenderTextureFormat.Default")] RenderTextureFormat format, [DefaultValue("RenderTextureReadWrite.Default")] RenderTextureReadWrite readWrite, [DefaultValue("1")] int antiAliasing); + [ExcludeFromDocs] + public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite) + { + int antiAliasing = 1; + return RenderTexture.GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + return RenderTexture.GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public static RenderTexture GetTemporary(int width, int height, int depthBuffer) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + RenderTextureFormat format = RenderTextureFormat.Default; + return RenderTexture.GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public static RenderTexture GetTemporary(int width, int height) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + RenderTextureFormat format = RenderTextureFormat.Default; + int depthBuffer = 0; + return RenderTexture.GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ReleaseTemporary(RenderTexture temp); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetWidth(RenderTexture mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetWidth(RenderTexture mono, int width); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetHeight(RenderTexture mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetHeight(RenderTexture mono, int width); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetSRGBReadWrite(RenderTexture mono, bool sRGB); + public bool Create() + { + return RenderTexture.INTERNAL_CALL_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Create(RenderTexture self); + public void Release() + { + RenderTexture.INTERNAL_CALL_Release(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Release(RenderTexture self); + public bool IsCreated() + { + return RenderTexture.INTERNAL_CALL_IsCreated(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_IsCreated(RenderTexture self); + public void DiscardContents() + { + RenderTexture.INTERNAL_CALL_DiscardContents(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DiscardContents(RenderTexture self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DiscardContents(bool discardColor, bool discardDepth); + public void MarkRestoreExpected() + { + RenderTexture.INTERNAL_CALL_MarkRestoreExpected(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MarkRestoreExpected(RenderTexture self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetColorBuffer(out RenderBuffer res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetDepthBuffer(out RenderBuffer res); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetGlobalShaderProperty(string propertyName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTexelOffset(RenderTexture tex, out Vector2 output); + public Vector2 GetTexelOffset() + { + Vector2 result; + RenderTexture.Internal_GetTexelOffset(this, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SupportsStencil(RenderTexture rt); + [Obsolete("RenderTexture.SetBorderColor was removed", true)] + public void SetBorderColor(Color color) + { + } + } +} diff --git a/UnityEngine/UnityEngine/RenderTextureFormat.cs b/UnityEngine/UnityEngine/RenderTextureFormat.cs new file mode 100644 index 00000000..8a952446 --- /dev/null +++ b/UnityEngine/UnityEngine/RenderTextureFormat.cs @@ -0,0 +1,24 @@ +using System; +namespace UnityEngine +{ + public enum RenderTextureFormat + { + ARGB32, + Depth, + ARGBHalf, + RGB565 = 4, + ARGB4444, + ARGB1555, + Default, + DefaultHDR = 9, + ARGBFloat = 11, + RGFloat, + RGHalf, + RFloat, + RHalf, + R8, + ARGBInt, + RGInt, + RInt + } +} diff --git a/UnityEngine/UnityEngine/RenderTextureReadWrite.cs b/UnityEngine/UnityEngine/RenderTextureReadWrite.cs new file mode 100644 index 00000000..cc83854d --- /dev/null +++ b/UnityEngine/UnityEngine/RenderTextureReadWrite.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum RenderTextureReadWrite + { + Default, + Linear, + sRGB + } +} diff --git a/UnityEngine/UnityEngine/Renderer.cs b/UnityEngine/UnityEngine/Renderer.cs new file mode 100644 index 00000000..5a6f4be4 --- /dev/null +++ b/UnityEngine/UnityEngine/Renderer.cs @@ -0,0 +1,213 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Renderer : Component + { + internal extern Transform staticBatchRootTransform + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern int staticBatchIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isPartOfStaticBatch + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Matrix4x4 worldToLocalMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_worldToLocalMatrix(out result); + return result; + } + } + public Matrix4x4 localToWorldMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_localToWorldMatrix(out result); + return result; + } + } + public extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool castShadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool receiveShadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material sharedMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material[] sharedMaterials + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Material[] materials + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Bounds bounds + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int lightmapIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector4 lightmapTilingOffset + { + get + { + Vector4 result; + this.INTERNAL_get_lightmapTilingOffset(out result); + return result; + } + set + { + this.INTERNAL_set_lightmapTilingOffset(ref value); + } + } + public extern bool isVisible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool useLightProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Transform lightProbeAnchor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string sortingLayerName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int sortingLayerID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int sortingOrder + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetSubsetIndex(int index, int subSetIndexForMaterial); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldToLocalMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localToWorldMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_lightmapTilingOffset(out Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_lightmapTilingOffset(ref Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPropertyBlock(MaterialPropertyBlock properties); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void GetPropertyBlock(MaterialPropertyBlock dest); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Render(int material); + } +} diff --git a/UnityEngine/UnityEngine/RenderingPath.cs b/UnityEngine/UnityEngine/RenderingPath.cs new file mode 100644 index 00000000..1977b08e --- /dev/null +++ b/UnityEngine/UnityEngine/RenderingPath.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum RenderingPath + { + UsePlayerSettings = -1, + VertexLit, + Forward, + DeferredLighting + } +} diff --git a/UnityEngine/UnityEngine/RequireComponent.cs b/UnityEngine/UnityEngine/RequireComponent.cs new file mode 100644 index 00000000..63cf32dc --- /dev/null +++ b/UnityEngine/UnityEngine/RequireComponent.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public sealed class RequireComponent : Attribute + { + public Type m_Type0; + public Type m_Type1; + public Type m_Type2; + public RequireComponent(Type requiredComponent) + { + this.m_Type0 = requiredComponent; + } + public RequireComponent(Type requiredComponent, Type requiredComponent2) + { + this.m_Type0 = requiredComponent; + this.m_Type1 = requiredComponent2; + } + public RequireComponent(Type requiredComponent, Type requiredComponent2, Type requiredComponent3) + { + this.m_Type0 = requiredComponent; + this.m_Type1 = requiredComponent2; + this.m_Type2 = requiredComponent3; + } + } +} diff --git a/UnityEngine/UnityEngine/Resolution.cs b/UnityEngine/UnityEngine/Resolution.cs new file mode 100644 index 00000000..50b72c70 --- /dev/null +++ b/UnityEngine/UnityEngine/Resolution.cs @@ -0,0 +1,43 @@ +using System; +namespace UnityEngine +{ + public struct Resolution + { + private int m_Width; + private int m_Height; + private int m_RefreshRate; + public int width + { + get + { + return this.m_Width; + } + set + { + this.m_Width = value; + } + } + public int height + { + get + { + return this.m_Height; + } + set + { + this.m_Height = value; + } + } + public int refreshRate + { + get + { + return this.m_RefreshRate; + } + set + { + this.m_RefreshRate = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/ResourceRequest.cs b/UnityEngine/UnityEngine/ResourceRequest.cs new file mode 100644 index 00000000..ebfd335b --- /dev/null +++ b/UnityEngine/UnityEngine/ResourceRequest.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class ResourceRequest : AsyncOperation + { + internal string m_Path; + internal Type m_Type; + public Object asset + { + get + { + return Resources.Load(this.m_Path, this.m_Type); + } + } + } +} diff --git a/UnityEngine/UnityEngine/Resources.cs b/UnityEngine/UnityEngine/Resources.cs new file mode 100644 index 00000000..7b3ceee6 --- /dev/null +++ b/UnityEngine/UnityEngine/Resources.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngineInternal; +namespace UnityEngine +{ + public sealed class Resources + { + internal static T[] ConvertObjects(Object[] rawObjects) where T : Object + { + if (rawObjects == null) + { + return null; + } + T[] array = new T[rawObjects.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = (T)((object)rawObjects[i]); + } + return array; + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object[] FindObjectsOfTypeAll(Type type); + public static T[] FindObjectsOfTypeAll() where T : Object + { + return Resources.ConvertObjects(Resources.FindObjectsOfTypeAll(typeof(T))); + } + public static Object Load(string path) + { + return Resources.Load(path, typeof(Object)); + } + public static T Load(string path) where T : Object + { + return (T)((object)Resources.Load(path, typeof(T))); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object Load(string path, Type systemTypeInstance); + public static ResourceRequest LoadAsync(string path) + { + return Resources.LoadAsync(path, typeof(Object)); + } + public static ResourceRequest LoadAsync(string path) where T : Object + { + return Resources.LoadAsync(path, typeof(T)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ResourceRequest LoadAsync(string path, Type type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object[] LoadAll(string path, Type systemTypeInstance); + public static Object[] LoadAll(string path) + { + return Resources.LoadAll(path, typeof(Object)); + } + public static T[] LoadAll(string path) where T : Object + { + return Resources.ConvertObjects(Resources.LoadAll(path, typeof(T))); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object GetBuiltinResource(Type type, string path); + public static T GetBuiltinResource(string path) where T : Object + { + return (T)((object)Resources.GetBuiltinResource(typeof(T), path)); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Object LoadAssetAtPath(string assetPath, Type type); + public static T LoadAssetAtPath(string assetPath) where T : Object + { + return (T)((object)Resources.LoadAssetAtPath(assetPath, typeof(T))); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnloadAsset(Object assetToUnload); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern AsyncOperation UnloadUnusedAssets(); + } +} diff --git a/UnityEngine/UnityEngine/Rigidbody.cs b/UnityEngine/UnityEngine/Rigidbody.cs new file mode 100644 index 00000000..12d518a5 --- /dev/null +++ b/UnityEngine/UnityEngine/Rigidbody.cs @@ -0,0 +1,508 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Rigidbody : Component + { + public Vector3 velocity + { + get + { + Vector3 result; + this.INTERNAL_get_velocity(out result); + return result; + } + set + { + this.INTERNAL_set_velocity(ref value); + } + } + public Vector3 angularVelocity + { + get + { + Vector3 result; + this.INTERNAL_get_angularVelocity(out result); + return result; + } + set + { + this.INTERNAL_set_angularVelocity(ref value); + } + } + public extern float drag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularDrag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float mass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useGravity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isKinematic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool freezeRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RigidbodyConstraints constraints + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CollisionDetectionMode collisionDetectionMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 centerOfMass + { + get + { + Vector3 result; + this.INTERNAL_get_centerOfMass(out result); + return result; + } + set + { + this.INTERNAL_set_centerOfMass(ref value); + } + } + public Vector3 worldCenterOfMass + { + get + { + Vector3 result; + this.INTERNAL_get_worldCenterOfMass(out result); + return result; + } + } + public Quaternion inertiaTensorRotation + { + get + { + Quaternion result; + this.INTERNAL_get_inertiaTensorRotation(out result); + return result; + } + set + { + this.INTERNAL_set_inertiaTensorRotation(ref value); + } + } + public Vector3 inertiaTensor + { + get + { + Vector3 result; + this.INTERNAL_get_inertiaTensor(out result); + return result; + } + set + { + this.INTERNAL_set_inertiaTensor(ref value); + } + } + public extern bool detectCollisions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useConeFriction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 position + { + get + { + Vector3 result; + this.INTERNAL_get_position(out result); + return result; + } + set + { + this.INTERNAL_set_position(ref value); + } + } + public Quaternion rotation + { + get + { + Quaternion result; + this.INTERNAL_get_rotation(out result); + return result; + } + set + { + this.INTERNAL_set_rotation(ref value); + } + } + public extern RigidbodyInterpolation interpolation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int solverIterationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float sleepVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float sleepAngularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxAngularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_velocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularVelocity(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularVelocity(ref Vector3 value); + public void SetDensity(float density) + { + Rigidbody.INTERNAL_CALL_SetDensity(this, density); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetDensity(Rigidbody self, float density); + public void AddForce(Vector3 force, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddForce(this, ref force, mode); + } + [ExcludeFromDocs] + public void AddForce(Vector3 force) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddForce(this, ref force, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddForce(Rigidbody self, ref Vector3 force, ForceMode mode); + [ExcludeFromDocs] + public void AddForce(float x, float y, float z) + { + ForceMode mode = ForceMode.Force; + this.AddForce(x, y, z, mode); + } + public void AddForce(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + this.AddForce(new Vector3(x, y, z), mode); + } + public void AddRelativeForce(Vector3 force, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddRelativeForce(this, ref force, mode); + } + [ExcludeFromDocs] + public void AddRelativeForce(Vector3 force) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddRelativeForce(this, ref force, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddRelativeForce(Rigidbody self, ref Vector3 force, ForceMode mode); + [ExcludeFromDocs] + public void AddRelativeForce(float x, float y, float z) + { + ForceMode mode = ForceMode.Force; + this.AddRelativeForce(x, y, z, mode); + } + public void AddRelativeForce(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + this.AddRelativeForce(new Vector3(x, y, z), mode); + } + public void AddTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddTorque(this, ref torque, mode); + } + [ExcludeFromDocs] + public void AddTorque(Vector3 torque) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddTorque(this, ref torque, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddTorque(Rigidbody self, ref Vector3 torque, ForceMode mode); + [ExcludeFromDocs] + public void AddTorque(float x, float y, float z) + { + ForceMode mode = ForceMode.Force; + this.AddTorque(x, y, z, mode); + } + public void AddTorque(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + this.AddTorque(new Vector3(x, y, z), mode); + } + public void AddRelativeTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddRelativeTorque(this, ref torque, mode); + } + [ExcludeFromDocs] + public void AddRelativeTorque(Vector3 torque) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddRelativeTorque(this, ref torque, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddRelativeTorque(Rigidbody self, ref Vector3 torque, ForceMode mode); + [ExcludeFromDocs] + public void AddRelativeTorque(float x, float y, float z) + { + ForceMode mode = ForceMode.Force; + this.AddRelativeTorque(x, y, z, mode); + } + public void AddRelativeTorque(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + this.AddRelativeTorque(new Vector3(x, y, z), mode); + } + public void AddForceAtPosition(Vector3 force, Vector3 position, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode); + } + [ExcludeFromDocs] + public void AddForceAtPosition(Vector3 force, Vector3 position) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddForceAtPosition(Rigidbody self, ref Vector3 force, ref Vector3 position, ForceMode mode); + public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, [DefaultValue("0.0F")] float upwardsModifier, [DefaultValue("ForceMode.Force")] ForceMode mode) + { + Rigidbody.INTERNAL_CALL_AddExplosionForce(this, explosionForce, ref explosionPosition, explosionRadius, upwardsModifier, mode); + } + [ExcludeFromDocs] + public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier) + { + ForceMode mode = ForceMode.Force; + Rigidbody.INTERNAL_CALL_AddExplosionForce(this, explosionForce, ref explosionPosition, explosionRadius, upwardsModifier, mode); + } + [ExcludeFromDocs] + public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius) + { + ForceMode mode = ForceMode.Force; + float upwardsModifier = 0f; + Rigidbody.INTERNAL_CALL_AddExplosionForce(this, explosionForce, ref explosionPosition, explosionRadius, upwardsModifier, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddExplosionForce(Rigidbody self, float explosionForce, ref Vector3 explosionPosition, float explosionRadius, float upwardsModifier, ForceMode mode); + public Vector3 ClosestPointOnBounds(Vector3 position) + { + return Rigidbody.INTERNAL_CALL_ClosestPointOnBounds(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_ClosestPointOnBounds(Rigidbody self, ref Vector3 position); + public Vector3 GetRelativePointVelocity(Vector3 relativePoint) + { + return Rigidbody.INTERNAL_CALL_GetRelativePointVelocity(this, ref relativePoint); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_GetRelativePointVelocity(Rigidbody self, ref Vector3 relativePoint); + public Vector3 GetPointVelocity(Vector3 worldPoint) + { + return Rigidbody.INTERNAL_CALL_GetPointVelocity(this, ref worldPoint); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_GetPointVelocity(Rigidbody self, ref Vector3 worldPoint); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_centerOfMass(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_centerOfMass(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldCenterOfMass(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_inertiaTensorRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_inertiaTensorRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_inertiaTensor(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_inertiaTensor(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_position(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_position(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rotation(ref Quaternion value); + public void MovePosition(Vector3 position) + { + Rigidbody.INTERNAL_CALL_MovePosition(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MovePosition(Rigidbody self, ref Vector3 position); + public void MoveRotation(Quaternion rot) + { + Rigidbody.INTERNAL_CALL_MoveRotation(this, ref rot); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MoveRotation(Rigidbody self, ref Quaternion rot); + public void Sleep() + { + Rigidbody.INTERNAL_CALL_Sleep(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Sleep(Rigidbody self); + public bool IsSleeping() + { + return Rigidbody.INTERNAL_CALL_IsSleeping(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_IsSleeping(Rigidbody self); + public void WakeUp() + { + Rigidbody.INTERNAL_CALL_WakeUp(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_WakeUp(Rigidbody self); + public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance) + { + return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, distance); + } + [ExcludeFromDocs] + public bool SweepTest(Vector3 direction, out RaycastHit hitInfo) + { + float distance = float.PositiveInfinity; + return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, distance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_SweepTest(Rigidbody self, ref Vector3 direction, out RaycastHit hitInfo, float distance); + public RaycastHit[] SweepTestAll(Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance) + { + return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, distance); + } + [ExcludeFromDocs] + public RaycastHit[] SweepTestAll(Vector3 direction) + { + float distance = float.PositiveInfinity; + return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, distance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern RaycastHit[] INTERNAL_CALL_SweepTestAll(Rigidbody self, ref Vector3 direction, float distance); + [Obsolete("use Rigidbody.maxAngularVelocity instead.")] + public void SetMaxAngularVelocity(float a) + { + this.maxAngularVelocity = a; + } + } +} diff --git a/UnityEngine/UnityEngine/Rigidbody2D.cs b/UnityEngine/UnityEngine/Rigidbody2D.cs new file mode 100644 index 00000000..649017be --- /dev/null +++ b/UnityEngine/UnityEngine/Rigidbody2D.cs @@ -0,0 +1,347 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Rigidbody2D : Component + { + public Vector2 position + { + get + { + Vector2 result; + this.INTERNAL_get_position(out result); + return result; + } + set + { + this.INTERNAL_set_position(ref value); + } + } + public extern float rotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 velocity + { + get + { + Vector2 result; + this.INTERNAL_get_velocity(out result); + return result; + } + set + { + this.INTERNAL_set_velocity(ref value); + } + } + public extern float angularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float mass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 centerOfMass + { + get + { + Vector2 result; + this.INTERNAL_get_centerOfMass(out result); + return result; + } + set + { + this.INTERNAL_set_centerOfMass(ref value); + } + } + public Vector2 worldCenterOfMass + { + get + { + Vector2 result; + this.INTERNAL_get_worldCenterOfMass(out result); + return result; + } + } + public extern float inertia + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float drag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularDrag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float gravityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isKinematic + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool fixedAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool simulated + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RigidbodyInterpolation2D interpolation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern RigidbodySleepMode2D sleepMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CollisionDetectionMode2D collisionDetectionMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_position(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_position(ref Vector2 value); + public void MovePosition(Vector2 position) + { + Rigidbody2D.INTERNAL_CALL_MovePosition(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MovePosition(Rigidbody2D self, ref Vector2 position); + public void MoveRotation(float angle) + { + Rigidbody2D.INTERNAL_CALL_MoveRotation(this, angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_MoveRotation(Rigidbody2D self, float angle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_velocity(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_velocity(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_centerOfMass(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_centerOfMass(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldCenterOfMass(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsSleeping(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsAwake(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Sleep(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void WakeUp(); + public void AddForce(Vector2 force, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode) + { + Rigidbody2D.INTERNAL_CALL_AddForce(this, ref force, mode); + } + [ExcludeFromDocs] + public void AddForce(Vector2 force) + { + ForceMode2D mode = ForceMode2D.Force; + Rigidbody2D.INTERNAL_CALL_AddForce(this, ref force, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddForce(Rigidbody2D self, ref Vector2 force, ForceMode2D mode); + public void AddRelativeForce(Vector2 relativeForce, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode) + { + Rigidbody2D.INTERNAL_CALL_AddRelativeForce(this, ref relativeForce, mode); + } + [ExcludeFromDocs] + public void AddRelativeForce(Vector2 relativeForce) + { + ForceMode2D mode = ForceMode2D.Force; + Rigidbody2D.INTERNAL_CALL_AddRelativeForce(this, ref relativeForce, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddRelativeForce(Rigidbody2D self, ref Vector2 relativeForce, ForceMode2D mode); + public void AddForceAtPosition(Vector2 force, Vector2 position, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode) + { + Rigidbody2D.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode); + } + [ExcludeFromDocs] + public void AddForceAtPosition(Vector2 force, Vector2 position) + { + ForceMode2D mode = ForceMode2D.Force; + Rigidbody2D.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, mode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddForceAtPosition(Rigidbody2D self, ref Vector2 force, ref Vector2 position, ForceMode2D mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddTorque(float torque, [DefaultValue("ForceMode2D.Force")] ForceMode2D mode); + [ExcludeFromDocs] + public void AddTorque(float torque) + { + ForceMode2D mode = ForceMode2D.Force; + this.AddTorque(torque, mode); + } + public Vector2 GetPoint(Vector2 point) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetPoint(this, point, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetPoint(Rigidbody2D rigidbody, Vector2 point, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetPoint(rigidbody, ref point, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetPoint(Rigidbody2D rigidbody, ref Vector2 point, out Vector2 value); + public Vector2 GetRelativePoint(Vector2 relativePoint) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetRelativePoint(this, relativePoint, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetRelativePoint(Rigidbody2D rigidbody, Vector2 relativePoint, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativePoint(rigidbody, ref relativePoint, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativePoint(Rigidbody2D rigidbody, ref Vector2 relativePoint, out Vector2 value); + public Vector2 GetVector(Vector2 vector) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetVector(this, vector, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetVector(Rigidbody2D rigidbody, Vector2 vector, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetVector(rigidbody, ref vector, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetVector(Rigidbody2D rigidbody, ref Vector2 vector, out Vector2 value); + public Vector2 GetRelativeVector(Vector2 relativeVector) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetRelativeVector(this, relativeVector, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetRelativeVector(Rigidbody2D rigidbody, Vector2 relativeVector, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativeVector(rigidbody, ref relativeVector, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativeVector(Rigidbody2D rigidbody, ref Vector2 relativeVector, out Vector2 value); + public Vector2 GetPointVelocity(Vector2 point) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetPointVelocity(this, point, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetPointVelocity(Rigidbody2D rigidbody, Vector2 point, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetPointVelocity(rigidbody, ref point, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetPointVelocity(Rigidbody2D rigidbody, ref Vector2 point, out Vector2 value); + public Vector2 GetRelativePointVelocity(Vector2 relativePoint) + { + Vector2 result; + Rigidbody2D.Rigidbody2D_CUSTOM_INTERNAL_GetRelativePointVelocity(this, relativePoint, out result); + return result; + } + private static void Rigidbody2D_CUSTOM_INTERNAL_GetRelativePointVelocity(Rigidbody2D rigidbody, Vector2 relativePoint, out Vector2 value) + { + Rigidbody2D.INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativePointVelocity(rigidbody, ref relativePoint, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Rigidbody2D_CUSTOM_INTERNAL_GetRelativePointVelocity(Rigidbody2D rigidbody, ref Vector2 relativePoint, out Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/RigidbodyConstraints.cs b/UnityEngine/UnityEngine/RigidbodyConstraints.cs new file mode 100644 index 00000000..51dd7767 --- /dev/null +++ b/UnityEngine/UnityEngine/RigidbodyConstraints.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEngine +{ + public enum RigidbodyConstraints + { + None, + FreezePositionX = 2, + FreezePositionY = 4, + FreezePositionZ = 8, + FreezeRotationX = 16, + FreezeRotationY = 32, + FreezeRotationZ = 64, + FreezePosition = 14, + FreezeRotation = 112, + FreezeAll = 126 + } +} diff --git a/UnityEngine/UnityEngine/RigidbodyInterpolation.cs b/UnityEngine/UnityEngine/RigidbodyInterpolation.cs new file mode 100644 index 00000000..3b2d4ecd --- /dev/null +++ b/UnityEngine/UnityEngine/RigidbodyInterpolation.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum RigidbodyInterpolation + { + None, + Interpolate, + Extrapolate + } +} diff --git a/UnityEngine/UnityEngine/RigidbodyInterpolation2D.cs b/UnityEngine/UnityEngine/RigidbodyInterpolation2D.cs new file mode 100644 index 00000000..d3066bf1 --- /dev/null +++ b/UnityEngine/UnityEngine/RigidbodyInterpolation2D.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum RigidbodyInterpolation2D + { + None, + Interpolate, + Extrapolate + } +} diff --git a/UnityEngine/UnityEngine/RigidbodySleepMode2D.cs b/UnityEngine/UnityEngine/RigidbodySleepMode2D.cs new file mode 100644 index 00000000..be73b36b --- /dev/null +++ b/UnityEngine/UnityEngine/RigidbodySleepMode2D.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum RigidbodySleepMode2D + { + NeverSleep, + StartAwake, + StartAsleep + } +} diff --git a/UnityEngine/UnityEngine/RotationDriveMode.cs b/UnityEngine/UnityEngine/RotationDriveMode.cs new file mode 100644 index 00000000..a0b6b40e --- /dev/null +++ b/UnityEngine/UnityEngine/RotationDriveMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum RotationDriveMode + { + XYAndZ, + Slerp + } +} diff --git a/UnityEngine/UnityEngine/RuntimeAnimatorController.cs b/UnityEngine/UnityEngine/RuntimeAnimatorController.cs new file mode 100644 index 00000000..6a612fa6 --- /dev/null +++ b/UnityEngine/UnityEngine/RuntimeAnimatorController.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public class RuntimeAnimatorController : Object + { + } +} diff --git a/UnityEngine/UnityEngine/RuntimePlatform.cs b/UnityEngine/UnityEngine/RuntimePlatform.cs new file mode 100644 index 00000000..5507d05a --- /dev/null +++ b/UnityEngine/UnityEngine/RuntimePlatform.cs @@ -0,0 +1,33 @@ +using System; +namespace UnityEngine +{ + public enum RuntimePlatform + { + OSXEditor, + OSXPlayer, + WindowsPlayer, + OSXWebPlayer, + OSXDashboardPlayer, + WindowsWebPlayer, + WindowsEditor = 7, + IPhonePlayer, + XBOX360 = 10, + PS3 = 9, + Android = 11, + NaCl, + LinuxPlayer, + FlashPlayer = 15, + MetroPlayerX86 = 18, + MetroPlayerX64, + MetroPlayerARM, + WP8Player, + BB10Player, + BlackBerryPlayer = 22, + TizenPlayer, + PSP2, + PS4, + PSMPlayer, + XboxOne, + SamsungTVPlayer + } +} diff --git a/UnityEngine/UnityEngine/RuntimeUndo.cs b/UnityEngine/UnityEngine/RuntimeUndo.cs new file mode 100644 index 00000000..c786d736 --- /dev/null +++ b/UnityEngine/UnityEngine/RuntimeUndo.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class RuntimeUndo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetTransformParent(Transform transform, Transform newParent, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RecordObject(Object objectToUndo, string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RecordObjects(Object[] objectsToUndo, string name); + } +} diff --git a/UnityEngine/UnityEngine/SamsungTV.cs b/UnityEngine/UnityEngine/SamsungTV.cs new file mode 100644 index 00000000..6b1509aa --- /dev/null +++ b/UnityEngine/UnityEngine/SamsungTV.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SamsungTV + { + public enum TouchPadMode + { + Dpad, + Joystick, + Mouse + } + public static extern SamsungTV.TouchPadMode touchPadMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/ScaleMode.cs b/UnityEngine/UnityEngine/ScaleMode.cs new file mode 100644 index 00000000..d40bc063 --- /dev/null +++ b/UnityEngine/UnityEngine/ScaleMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum ScaleMode + { + StretchToFill, + ScaleAndCrop, + ScaleToFit + } +} diff --git a/UnityEngine/UnityEngine/Screen.cs b/UnityEngine/UnityEngine/Screen.cs new file mode 100644 index 00000000..73338800 --- /dev/null +++ b/UnityEngine/UnityEngine/Screen.cs @@ -0,0 +1,136 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Screen + { + public static extern Resolution[] resolutions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Resolution[] GetResolution + { + get + { + return Screen.resolutions; + } + } + public static extern Resolution currentResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool showCursor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool lockCursor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int width + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float dpi + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool fullScreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool autorotateToPortrait + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool autorotateToPortraitUpsideDown + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool autorotateToLandscapeLeft + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool autorotateToLandscapeRight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern ScreenOrientation orientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int sleepTimeout + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetResolution(int width, int height, bool fullscreen, [DefaultValue("0")] int preferredRefreshRate); + [ExcludeFromDocs] + public static void SetResolution(int width, int height, bool fullscreen) + { + int preferredRefreshRate = 0; + Screen.SetResolution(width, height, fullscreen, preferredRefreshRate); + } + } +} diff --git a/UnityEngine/UnityEngine/ScreenOrientation.cs b/UnityEngine/UnityEngine/ScreenOrientation.cs new file mode 100644 index 00000000..c1052b66 --- /dev/null +++ b/UnityEngine/UnityEngine/ScreenOrientation.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + public enum ScreenOrientation + { + Unknown, + Portrait, + PortraitUpsideDown, + LandscapeLeft, + LandscapeRight, + AutoRotation, + Landscape = 3 + } +} diff --git a/UnityEngine/UnityEngine/ScriptableObject.cs b/UnityEngine/UnityEngine/ScriptableObject.cs new file mode 100644 index 00000000..12d7fe62 --- /dev/null +++ b/UnityEngine/UnityEngine/ScriptableObject.cs @@ -0,0 +1,39 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class ScriptableObject : Object + { + public ScriptableObject() + { + ScriptableObject.Internal_CreateScriptableObject(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateScriptableObject([Writable] ScriptableObject self); + [Obsolete("Use EditorUtility.SetDirty instead")] + public void SetDirty() + { + ScriptableObject.INTERNAL_CALL_SetDirty(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetDirty(ScriptableObject self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ScriptableObject CreateInstance(string className); + public static ScriptableObject CreateInstance(Type type) + { + return ScriptableObject.CreateInstanceFromType(type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern ScriptableObject CreateInstanceFromType(Type type); + public static T CreateInstance() where T : ScriptableObject + { + return (T)((object)ScriptableObject.CreateInstance(typeof(T))); + } + } +} diff --git a/UnityEngine/UnityEngine/ScrollWaitDefinitions.cs b/UnityEngine/UnityEngine/ScrollWaitDefinitions.cs new file mode 100644 index 00000000..69b87eaf --- /dev/null +++ b/UnityEngine/UnityEngine/ScrollWaitDefinitions.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + internal static class ScrollWaitDefinitions + { + public const int firstWait = 250; + public const int regularWait = 30; + } +} diff --git a/UnityEngine/UnityEngine/Security.cs b/UnityEngine/UnityEngine/Security.cs new file mode 100644 index 00000000..261fc4cb --- /dev/null +++ b/UnityEngine/UnityEngine/Security.cs @@ -0,0 +1,172 @@ +using Mono.Security; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Security.Cryptography; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Security + { + private const string publicVerificationKey = "uP7lsvrE6fNoQWhUIdJnQrgKoGXBkgWgs5l1xmS9gfyNkFSXgugIpfmN/0YrtL57PezYFXN0CogAnOpOtcUmpcIrh524VL/7bIh+jDUaOCG292PIx92dtzqCTvbUdCYUmaag9VlrdAw05FxYQJi2iZ/X6EiuO1TnqpVNFCDb6pXPAssoO4Uxn9JXBzL0muNRdcmFGRiLp7JQOL7a2aeU9mF9qjMprnww0k8COa6tHdnNWJqaxdFO+Etk3os0ns/gQ2FWrztKemM1Wfu7lk/B1F+V2g0adwlTiuyNHw6to+5VQXWK775RXB9wAGr8KhsVD5IJvmxrdBT8KVEWve+OXQ==AQAB"; + private static List _verifiedAssemblies = new List(); + private static readonly string kSignatureExtension = ".signature"; + private static MethodInfo GetUnityCrossDomainHelperMethod(string methodname) + { + Type type = Types.GetType("UnityEngine.UnityCrossDomainHelper", "CrossDomainPolicyParser, Version=1.0.0.0, Culture=neutral"); + if (type == null) + { + throw new SecurityException("Cant find type UnityCrossDomainHelper"); + } + MethodInfo method = type.GetMethod(methodname); + if (method == null) + { + throw new SecurityException("Cant find " + methodname); + } + return method; + } + internal static string TokenToHex(byte[] token) + { + if (token == null || 8 > token.Length) + { + return string.Empty; + } + return string.Format("{0:x2}{1:x2}{2:x2}{3:x2}{4:x2}{5:x2}{6:x2}{7:x2}", new object[] + { + token[0], + token[1], + token[2], + token[3], + token[4], + token[5], + token[6], + token[7] + }); + } + internal static void ClearVerifiedAssemblies() + { + Security._verifiedAssemblies.Clear(); + } + [SecuritySafeCritical] + public static Assembly LoadAndVerifyAssembly(byte[] assemblyData, string authorizationKey) + { + RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(); + rSACryptoServiceProvider.FromXmlString("uP7lsvrE6fNoQWhUIdJnQrgKoGXBkgWgs5l1xmS9gfyNkFSXgugIpfmN/0YrtL57PezYFXN0CogAnOpOtcUmpcIrh524VL/7bIh+jDUaOCG292PIx92dtzqCTvbUdCYUmaag9VlrdAw05FxYQJi2iZ/X6EiuO1TnqpVNFCDb6pXPAssoO4Uxn9JXBzL0muNRdcmFGRiLp7JQOL7a2aeU9mF9qjMprnww0k8COa6tHdnNWJqaxdFO+Etk3os0ns/gQ2FWrztKemM1Wfu7lk/B1F+V2g0adwlTiuyNHw6to+5VQXWK775RXB9wAGr8KhsVD5IJvmxrdBT8KVEWve+OXQ==AQAB"); + bool flag = false; + SHA1 sHA = SHA1.Create(); + byte[] rgbHash = sHA.ComputeHash(assemblyData); + byte[] rgbSignature = Convert.FromBase64String(authorizationKey); + try + { + flag = rSACryptoServiceProvider.VerifyHash(rgbHash, CryptoConfig.MapNameToOID("SHA1"), rgbSignature); + } + catch (CryptographicException) + { + Debug.LogError("Unable to verify that this assembly has been authorized by Unity. The assembly will not be loaded."); + flag = false; + } + if (!flag) + { + return null; + } + return Security.LoadAndVerifyAssemblyInternal(assemblyData); + } + [SecuritySafeCritical] + public static Assembly LoadAndVerifyAssembly(byte[] assemblyData) + { + if (Application.GetBuildUnityVersion() >= Application.GetNumericUnityVersion("4.5.0a4")) + { + Debug.LogError("Unable to verify assembly data; you must provide an authorization key when loading this assembly."); + return null; + } + return Security.LoadAndVerifyAssemblyInternal(assemblyData); + } + [SecuritySafeCritical] + private static Assembly LoadAndVerifyAssemblyInternal(byte[] assemblyData) + { + Assembly assembly = Assembly.Load(assemblyData); + byte[] publicKey = assembly.GetName().GetPublicKey(); + if (publicKey == null || publicKey.Length == 0) + { + return null; + } + RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(); + rSACryptoServiceProvider.ImportCspBlob(publicKey); + StrongName strongName = new StrongName(rSACryptoServiceProvider); + Assembly result; + using (MemoryStream memoryStream = new MemoryStream(assemblyData)) + { + if (strongName.Verify(memoryStream)) + { + Security._verifiedAssemblies.Add(assembly); + result = assembly; + } + else + { + result = null; + } + } + return result; + } + internal static bool VerifySignature(string file, byte[] publicKey) + { + try + { + string path = file + Security.kSignatureExtension; + if (!File.Exists(path)) + { + bool result = false; + return result; + } + using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider()) + { + rSACryptoServiceProvider.ImportCspBlob(publicKey); + using (SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new SHA1CryptoServiceProvider()) + { + bool result = rSACryptoServiceProvider.VerifyData(File.ReadAllBytes(file), sHA1CryptoServiceProvider, File.ReadAllBytes(path)); + return result; + } + } + } + catch (Exception exception) + { + Debug.LogException(exception); + } + return false; + } + [ExcludeFromDocs] + public static bool PrefetchSocketPolicy(string ip, int atPort) + { + int timeout = 3000; + return Security.PrefetchSocketPolicy(ip, atPort, timeout); + } + public static bool PrefetchSocketPolicy(string ip, int atPort, [DefaultValue("3000")] int timeout) + { + MethodInfo unityCrossDomainHelperMethod = Security.GetUnityCrossDomainHelperMethod("PrefetchSocketPolicy"); + object obj = unityCrossDomainHelperMethod.Invoke(null, new object[] + { + ip, + atPort, + timeout + }); + return (bool)obj; + } + [SecuritySafeCritical] + public static string GetChainOfTrustValue(string name) + { + Assembly callingAssembly = Assembly.GetCallingAssembly(); + if (!Security._verifiedAssemblies.Contains(callingAssembly)) + { + throw new ArgumentException("Calling assembly needs to be verified by Security.LoadAndVerifyAssembly"); + } + byte[] publicKeyToken = callingAssembly.GetName().GetPublicKeyToken(); + return Security.GetChainOfTrustValueInternal(name, Security.TokenToHex(publicKeyToken)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string GetChainOfTrustValueInternal(string name, string publicKeyToken); + } +} diff --git a/UnityEngine/UnityEngine/SelectionBaseAttribute.cs b/UnityEngine/UnityEngine/SelectionBaseAttribute.cs new file mode 100644 index 00000000..899deaf2 --- /dev/null +++ b/UnityEngine/UnityEngine/SelectionBaseAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] + public class SelectionBaseAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/SendMessageOptions.cs b/UnityEngine/UnityEngine/SendMessageOptions.cs new file mode 100644 index 00000000..79581893 --- /dev/null +++ b/UnityEngine/UnityEngine/SendMessageOptions.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum SendMessageOptions + { + RequireReceiver, + DontRequireReceiver + } +} diff --git a/UnityEngine/UnityEngine/SendMouseEvents.cs b/UnityEngine/UnityEngine/SendMouseEvents.cs new file mode 100644 index 00000000..ae934521 --- /dev/null +++ b/UnityEngine/UnityEngine/SendMouseEvents.cs @@ -0,0 +1,185 @@ +using System; +namespace UnityEngine +{ + internal class SendMouseEvents + { + private struct HitInfo + { + public GameObject target; + public Camera camera; + public void SendMessage(string name) + { + this.target.SendMessage(name, null, SendMessageOptions.DontRequireReceiver); + } + public static bool Compare(SendMouseEvents.HitInfo lhs, SendMouseEvents.HitInfo rhs) + { + return lhs.target == rhs.target && lhs.camera == rhs.camera; + } + public static implicit operator bool(SendMouseEvents.HitInfo exists) + { + return exists.target != null && exists.camera != null; + } + } + private const int m_HitIndexGUI = 0; + private const int m_HitIndexPhysics3D = 1; + private const int m_HitIndexPhysics2D = 2; + private static readonly SendMouseEvents.HitInfo[] m_LastHit = new SendMouseEvents.HitInfo[] + { + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo) + }; + private static readonly SendMouseEvents.HitInfo[] m_MouseDownHit = new SendMouseEvents.HitInfo[] + { + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo) + }; + private static readonly SendMouseEvents.HitInfo[] m_CurrentHit = new SendMouseEvents.HitInfo[] + { + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo), + default(SendMouseEvents.HitInfo) + }; + private static readonly RaycastHit2D[] m_MouseRayHits2D = new RaycastHit2D[] + { + default(RaycastHit2D) + }; + private static Camera[] m_Cameras; + [NotRenamed] + private static void DoSendMouseEvents(int mouseUsed, int skipRTCameras) + { + Vector3 mousePosition = Input.mousePosition; + int allCamerasCount = Camera.allCamerasCount; + if (SendMouseEvents.m_Cameras == null || SendMouseEvents.m_Cameras.Length != allCamerasCount) + { + SendMouseEvents.m_Cameras = new Camera[allCamerasCount]; + } + int allCameras = Camera.GetAllCameras(SendMouseEvents.m_Cameras); + for (int i = 0; i < SendMouseEvents.m_CurrentHit.Length; i++) + { + SendMouseEvents.m_CurrentHit[i] = default(SendMouseEvents.HitInfo); + } + if (mouseUsed == 0) + { + for (int j = 0; j < allCameras; j++) + { + Camera camera = SendMouseEvents.m_Cameras[j]; + if (!(camera == null) && (skipRTCameras == 0 || !(camera.targetTexture != null))) + { + if (camera.pixelRect.Contains(mousePosition)) + { + GUILayer component = camera.GetComponent(); + if (component) + { + GUIElement gUIElement = component.HitTest(mousePosition); + if (gUIElement) + { + SendMouseEvents.m_CurrentHit[0].target = gUIElement.gameObject; + SendMouseEvents.m_CurrentHit[0].camera = camera; + } + else + { + SendMouseEvents.m_CurrentHit[0].target = null; + SendMouseEvents.m_CurrentHit[0].camera = null; + } + } + if (camera.eventMask != 0) + { + Ray ray = camera.ScreenPointToRay(mousePosition); + float z = ray.direction.z; + float num = (!Mathf.Approximately(0f, z)) ? Mathf.Abs((camera.farClipPlane - camera.nearClipPlane) / z) : float.PositiveInfinity; + RaycastHit raycastHit; + if (Physics.Raycast(ray, out raycastHit, num + 1f, camera.cullingMask & camera.eventMask & -5)) + { + SendMouseEvents.m_CurrentHit[1].camera = camera; + SendMouseEvents.m_CurrentHit[1].target = ((!raycastHit.rigidbody) ? raycastHit.collider.gameObject : raycastHit.rigidbody.gameObject); + } + else + { + if (camera.clearFlags == CameraClearFlags.Skybox || camera.clearFlags == CameraClearFlags.Color) + { + SendMouseEvents.m_CurrentHit[1].target = null; + SendMouseEvents.m_CurrentHit[1].camera = null; + } + } + if (Physics2D.GetRayIntersectionNonAlloc(ray, SendMouseEvents.m_MouseRayHits2D, num, camera.cullingMask & camera.eventMask & -5) == 1) + { + SendMouseEvents.m_CurrentHit[2].camera = camera; + SendMouseEvents.m_CurrentHit[2].target = ((!SendMouseEvents.m_MouseRayHits2D[0].rigidbody) ? SendMouseEvents.m_MouseRayHits2D[0].collider.gameObject : SendMouseEvents.m_MouseRayHits2D[0].rigidbody.gameObject); + } + else + { + if (camera.clearFlags == CameraClearFlags.Skybox || camera.clearFlags == CameraClearFlags.Color) + { + SendMouseEvents.m_CurrentHit[2].target = null; + SendMouseEvents.m_CurrentHit[2].camera = null; + } + } + } + } + } + } + } + for (int k = 0; k < SendMouseEvents.m_CurrentHit.Length; k++) + { + SendMouseEvents.SendEvents(k, SendMouseEvents.m_CurrentHit[k]); + } + } + private static void SendEvents(int i, SendMouseEvents.HitInfo hit) + { + bool mouseButtonDown = Input.GetMouseButtonDown(0); + bool mouseButton = Input.GetMouseButton(0); + if (mouseButtonDown) + { + if (hit) + { + SendMouseEvents.m_MouseDownHit[i] = hit; + SendMouseEvents.m_MouseDownHit[i].SendMessage("OnMouseDown"); + } + } + else + { + if (!mouseButton) + { + if (SendMouseEvents.m_MouseDownHit[i]) + { + if (SendMouseEvents.HitInfo.Compare(hit, SendMouseEvents.m_MouseDownHit[i])) + { + SendMouseEvents.m_MouseDownHit[i].SendMessage("OnMouseUpAsButton"); + } + SendMouseEvents.m_MouseDownHit[i].SendMessage("OnMouseUp"); + SendMouseEvents.m_MouseDownHit[i] = default(SendMouseEvents.HitInfo); + } + } + else + { + if (SendMouseEvents.m_MouseDownHit[i]) + { + SendMouseEvents.m_MouseDownHit[i].SendMessage("OnMouseDrag"); + } + } + } + if (SendMouseEvents.HitInfo.Compare(hit, SendMouseEvents.m_LastHit[i])) + { + if (hit) + { + hit.SendMessage("OnMouseOver"); + } + } + else + { + if (SendMouseEvents.m_LastHit[i]) + { + SendMouseEvents.m_LastHit[i].SendMessage("OnMouseExit"); + } + if (hit) + { + hit.SendMessage("OnMouseEnter"); + hit.SendMessage("OnMouseOver"); + } + } + SendMouseEvents.m_LastHit[i] = hit; + } + } +} diff --git a/UnityEngine/UnityEngine/SerializeField.cs b/UnityEngine/UnityEngine/SerializeField.cs new file mode 100644 index 00000000..9c33c44e --- /dev/null +++ b/UnityEngine/UnityEngine/SerializeField.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class SerializeField : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/SerializePrivateVariables.cs b/UnityEngine/UnityEngine/SerializePrivateVariables.cs new file mode 100644 index 00000000..0b73ca6d --- /dev/null +++ b/UnityEngine/UnityEngine/SerializePrivateVariables.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [Obsolete("Use SerializeField on the private variables that you want to be serialized instead")] + public sealed class SerializePrivateVariables : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/SetupCoroutine.cs b/UnityEngine/UnityEngine/SetupCoroutine.cs new file mode 100644 index 00000000..595549da --- /dev/null +++ b/UnityEngine/UnityEngine/SetupCoroutine.cs @@ -0,0 +1,32 @@ +using System; +using System.Reflection; +namespace UnityEngine +{ + internal class SetupCoroutine + { + public static object InvokeMember(object behaviour, string name, object variable) + { + object[] args = null; + if (variable != null) + { + args = new object[] + { + variable + }; + } + return behaviour.GetType().InvokeMember(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, behaviour, args, null, null, null); + } + public static object InvokeStatic(Type klass, string name, object variable) + { + object[] args = null; + if (variable != null) + { + args = new object[] + { + variable + }; + } + return klass.InvokeMember(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, args, null, null, null); + } + } +} diff --git a/UnityEngine/UnityEngine/Shader.cs b/UnityEngine/UnityEngine/Shader.cs new file mode 100644 index 00000000..51ff8c65 --- /dev/null +++ b/UnityEngine/UnityEngine/Shader.cs @@ -0,0 +1,123 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Shader : Object + { + public extern bool isSupported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern string customEditor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int maximumLOD + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int globalMaximumLOD + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int renderQueue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Shader Find(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Shader FindBuiltin(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void EnableKeyword(string keyword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void DisableKeyword(string keyword); + public static void SetGlobalColor(string propertyName, Color color) + { + Shader.SetGlobalColor(Shader.PropertyToID(propertyName), color); + } + public static void SetGlobalColor(int nameID, Color color) + { + Shader.INTERNAL_CALL_SetGlobalColor(nameID, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetGlobalColor(int nameID, ref Color color); + public static void SetGlobalVector(string propertyName, Vector4 vec) + { + Shader.SetGlobalColor(propertyName, vec); + } + public static void SetGlobalVector(int nameID, Vector4 vec) + { + Shader.SetGlobalColor(nameID, vec); + } + public static void SetGlobalFloat(string propertyName, float value) + { + Shader.SetGlobalFloat(Shader.PropertyToID(propertyName), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalFloat(int nameID, float value); + public static void SetGlobalInt(string propertyName, int value) + { + Shader.SetGlobalFloat(propertyName, (float)value); + } + public static void SetGlobalInt(int nameID, int value) + { + Shader.SetGlobalFloat(nameID, (float)value); + } + public static void SetGlobalTexture(string propertyName, Texture tex) + { + Shader.SetGlobalTexture(Shader.PropertyToID(propertyName), tex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalTexture(int nameID, Texture tex); + public static void SetGlobalMatrix(string propertyName, Matrix4x4 mat) + { + Shader.SetGlobalMatrix(Shader.PropertyToID(propertyName), mat); + } + public static void SetGlobalMatrix(int nameID, Matrix4x4 mat) + { + Shader.INTERNAL_CALL_SetGlobalMatrix(nameID, ref mat); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetGlobalMatrix(int nameID, ref Matrix4x4 mat); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalTexGenMode(string propertyName, TexGenMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalTextureMatrixName(string propertyName, string matrixName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalBuffer(string propertyName, ComputeBuffer buffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int PropertyToID(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void WarmupAllShaders(); + } +} diff --git a/UnityEngine/UnityEngine/ShadowProjection.cs b/UnityEngine/UnityEngine/ShadowProjection.cs new file mode 100644 index 00000000..c29ab006 --- /dev/null +++ b/UnityEngine/UnityEngine/ShadowProjection.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum ShadowProjection + { + CloseFit, + StableFit + } +} diff --git a/UnityEngine/UnityEngine/SkeletonBone.cs b/UnityEngine/UnityEngine/SkeletonBone.cs new file mode 100644 index 00000000..f5e62e86 --- /dev/null +++ b/UnityEngine/UnityEngine/SkeletonBone.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public struct SkeletonBone + { + public string name; + public Vector3 position; + public Quaternion rotation; + public Vector3 scale; + public int transformModified; + } +} diff --git a/UnityEngine/UnityEngine/SkinQuality.cs b/UnityEngine/UnityEngine/SkinQuality.cs new file mode 100644 index 00000000..572bb49b --- /dev/null +++ b/UnityEngine/UnityEngine/SkinQuality.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum SkinQuality + { + Auto, + Bone1, + Bone2, + Bone4 = 4 + } +} diff --git a/UnityEngine/UnityEngine/SkinnedCloth.cs b/UnityEngine/UnityEngine/SkinnedCloth.cs new file mode 100644 index 00000000..c83f9df7 --- /dev/null +++ b/UnityEngine/UnityEngine/SkinnedCloth.cs @@ -0,0 +1,45 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class SkinnedCloth : Cloth + { + public extern ClothSkinningCoefficient[] coefficients + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float worldVelocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float worldAccelerationScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetEnabledFading(bool enabled, [DefaultValue("0.5f")] float interpolationTime); + [ExcludeFromDocs] + public void SetEnabledFading(bool enabled) + { + float interpolationTime = 0.5f; + this.SetEnabledFading(enabled, interpolationTime); + } + } +} diff --git a/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs b/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs new file mode 100644 index 00000000..eb777efc --- /dev/null +++ b/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class SkinnedMeshRenderer : Renderer + { + public extern Transform[] bones + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Transform rootBone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern SkinQuality quality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Mesh sharedMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Has no effect.")] + public bool skinNormals + { + get + { + return true; + } + set + { + } + } + public extern bool updateWhenOffscreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Bounds localBounds + { + get + { + Bounds result; + this.INTERNAL_get_localBounds(out result); + return result; + } + set + { + this.INTERNAL_set_localBounds(ref value); + } + } + internal extern Transform actualRootBone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localBounds(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localBounds(ref Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void BakeMesh(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetBlendShapeWeight(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetBlendShapeWeight(int index, float value); + } +} diff --git a/UnityEngine/UnityEngine/Skybox.cs b/UnityEngine/UnityEngine/Skybox.cs new file mode 100644 index 00000000..189a24f6 --- /dev/null +++ b/UnityEngine/UnityEngine/Skybox.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Skybox : Behaviour + { + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/SleepTimeout.cs b/UnityEngine/UnityEngine/SleepTimeout.cs new file mode 100644 index 00000000..b194500d --- /dev/null +++ b/UnityEngine/UnityEngine/SleepTimeout.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public sealed class SleepTimeout + { + public const int NeverSleep = -1; + public const int SystemSetting = -2; + } +} diff --git a/UnityEngine/UnityEngine/SliderHandler.cs b/UnityEngine/UnityEngine/SliderHandler.cs new file mode 100644 index 00000000..6ad698ad --- /dev/null +++ b/UnityEngine/UnityEngine/SliderHandler.cs @@ -0,0 +1,262 @@ +using System; +namespace UnityEngine +{ + internal struct SliderHandler + { + private readonly Rect position; + private readonly float currentValue; + private readonly float size; + private readonly float start; + private readonly float end; + private readonly GUIStyle slider; + private readonly GUIStyle thumb; + private readonly bool horiz; + private readonly int id; + public SliderHandler(Rect position, float currentValue, float size, float start, float end, GUIStyle slider, GUIStyle thumb, bool horiz, int id) + { + this.position = position; + this.currentValue = currentValue; + this.size = size; + this.start = start; + this.end = end; + this.slider = slider; + this.thumb = thumb; + this.horiz = horiz; + this.id = id; + } + public float Handle() + { + if (this.slider == null || this.thumb == null) + { + return this.currentValue; + } + switch (this.CurrentEventType()) + { + case EventType.MouseDown: + return this.OnMouseDown(); + case EventType.MouseUp: + return this.OnMouseUp(); + case EventType.MouseDrag: + return this.OnMouseDrag(); + case EventType.Repaint: + return this.OnRepaint(); + } + return this.currentValue; + } + private float OnMouseDown() + { + if (!this.position.Contains(this.CurrentEvent().mousePosition) || this.IsEmptySlider()) + { + return this.currentValue; + } + GUI.scrollTroughSide = 0; + GUIUtility.hotControl = this.id; + this.CurrentEvent().Use(); + if (this.ThumbSelectionRect().Contains(this.CurrentEvent().mousePosition)) + { + this.StartDraggingWithValue(this.ClampedCurrentValue()); + return this.currentValue; + } + GUI.changed = true; + if (this.SupportsPageMovements()) + { + this.SliderState().isDragging = false; + GUI.nextScrollStepTime = SystemClock.now.AddMilliseconds(250.0); + GUI.scrollTroughSide = this.CurrentScrollTroughSide(); + return this.PageMovementValue(); + } + float num = this.ValueForCurrentMousePosition(); + this.StartDraggingWithValue(num); + return this.Clamp(num); + } + private float OnMouseDrag() + { + if (GUIUtility.hotControl != this.id) + { + return this.currentValue; + } + SliderState sliderState = this.SliderState(); + if (!sliderState.isDragging) + { + return this.currentValue; + } + GUI.changed = true; + this.CurrentEvent().Use(); + float num = this.MousePosition() - sliderState.dragStartPos; + float value = sliderState.dragStartValue + num / this.ValuesPerPixel(); + return this.Clamp(value); + } + private float OnMouseUp() + { + if (GUIUtility.hotControl == this.id) + { + this.CurrentEvent().Use(); + GUIUtility.hotControl = 0; + } + return this.currentValue; + } + private float OnRepaint() + { + this.slider.Draw(this.position, GUIContent.none, this.id); + this.thumb.Draw(this.ThumbRect(), GUIContent.none, this.id); + if (GUIUtility.hotControl != this.id || !this.position.Contains(this.CurrentEvent().mousePosition) || this.IsEmptySlider()) + { + return this.currentValue; + } + if (this.ThumbRect().Contains(this.CurrentEvent().mousePosition)) + { + if (GUI.scrollTroughSide != 0) + { + GUIUtility.hotControl = 0; + } + return this.currentValue; + } + GUI.InternalRepaintEditorWindow(); + if (SystemClock.now < GUI.nextScrollStepTime) + { + return this.currentValue; + } + if (this.CurrentScrollTroughSide() != GUI.scrollTroughSide) + { + return this.currentValue; + } + GUI.nextScrollStepTime = SystemClock.now.AddMilliseconds(30.0); + if (this.SupportsPageMovements()) + { + this.SliderState().isDragging = false; + GUI.changed = true; + return this.PageMovementValue(); + } + return this.ClampedCurrentValue(); + } + private EventType CurrentEventType() + { + return this.CurrentEvent().GetTypeForControl(this.id); + } + private int CurrentScrollTroughSide() + { + float num = (!this.horiz) ? this.CurrentEvent().mousePosition.y : this.CurrentEvent().mousePosition.x; + float num2 = (!this.horiz) ? this.ThumbRect().y : this.ThumbRect().x; + return (num <= num2) ? -1 : 1; + } + private bool IsEmptySlider() + { + return this.start == this.end; + } + private bool SupportsPageMovements() + { + return this.size != 0f && GUI.usePageScrollbars; + } + private float PageMovementValue() + { + float num = this.currentValue; + int num2 = (this.start <= this.end) ? 1 : -1; + if (this.MousePosition() > this.PageUpMovementBound()) + { + num += this.size * (float)num2 * 0.9f; + } + else + { + num -= this.size * (float)num2 * 0.9f; + } + return this.Clamp(num); + } + private float PageUpMovementBound() + { + if (this.horiz) + { + return this.ThumbRect().xMax - this.position.x; + } + return this.ThumbRect().yMax - this.position.y; + } + private Event CurrentEvent() + { + return Event.current; + } + private float ValueForCurrentMousePosition() + { + if (this.horiz) + { + return (this.MousePosition() - this.ThumbRect().width * 0.5f) / this.ValuesPerPixel() + this.start - this.size * 0.5f; + } + return (this.MousePosition() - this.ThumbRect().height * 0.5f) / this.ValuesPerPixel() + this.start - this.size * 0.5f; + } + private float Clamp(float value) + { + return Mathf.Clamp(value, this.MinValue(), this.MaxValue()); + } + private Rect ThumbSelectionRect() + { + return this.ThumbRect(); + } + private void StartDraggingWithValue(float dragStartValue) + { + SliderState sliderState = this.SliderState(); + sliderState.dragStartPos = this.MousePosition(); + sliderState.dragStartValue = dragStartValue; + sliderState.isDragging = true; + } + private SliderState SliderState() + { + return (SliderState)GUIUtility.GetStateObject(typeof(SliderState), this.id); + } + private Rect ThumbRect() + { + return (!this.horiz) ? this.VerticalThumbRect() : this.HorizontalThumbRect(); + } + private Rect VerticalThumbRect() + { + float num = this.ValuesPerPixel(); + if (this.start < this.end) + { + return new Rect(this.position.x + (float)this.slider.padding.left, (this.ClampedCurrentValue() - this.start) * num + this.position.y + (float)this.slider.padding.top, this.position.width - (float)this.slider.padding.horizontal, this.size * num + this.ThumbSize()); + } + return new Rect(this.position.x + (float)this.slider.padding.left, (this.ClampedCurrentValue() + this.size - this.start) * num + this.position.y + (float)this.slider.padding.top, this.position.width - (float)this.slider.padding.horizontal, this.size * -num + this.ThumbSize()); + } + private Rect HorizontalThumbRect() + { + float num = this.ValuesPerPixel(); + if (this.start < this.end) + { + return new Rect((this.ClampedCurrentValue() - this.start) * num + this.position.x + (float)this.slider.padding.left, this.position.y + (float)this.slider.padding.top, this.size * num + this.ThumbSize(), this.position.height - (float)this.slider.padding.vertical); + } + return new Rect((this.ClampedCurrentValue() + this.size - this.start) * num + this.position.x + (float)this.slider.padding.left, this.position.y, this.size * -num + this.ThumbSize(), this.position.height); + } + private float ClampedCurrentValue() + { + return this.Clamp(this.currentValue); + } + private float MousePosition() + { + if (this.horiz) + { + return this.CurrentEvent().mousePosition.x - this.position.x; + } + return this.CurrentEvent().mousePosition.y - this.position.y; + } + private float ValuesPerPixel() + { + if (this.horiz) + { + return (this.position.width - (float)this.slider.padding.horizontal - this.ThumbSize()) / (this.end - this.start); + } + return (this.position.height - (float)this.slider.padding.vertical - this.ThumbSize()) / (this.end - this.start); + } + private float ThumbSize() + { + if (this.horiz) + { + return (this.thumb.fixedWidth == 0f) ? ((float)this.thumb.padding.horizontal) : this.thumb.fixedWidth; + } + return (this.thumb.fixedHeight == 0f) ? ((float)this.thumb.padding.vertical) : this.thumb.fixedHeight; + } + private float MaxValue() + { + return Mathf.Max(this.start, this.end) - this.size; + } + private float MinValue() + { + return Mathf.Min(this.start, this.end); + } + } +} diff --git a/UnityEngine/UnityEngine/SliderJoint2D.cs b/UnityEngine/UnityEngine/SliderJoint2D.cs new file mode 100644 index 00000000..2760a1b4 --- /dev/null +++ b/UnityEngine/UnityEngine/SliderJoint2D.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SliderJoint2D : AnchoredJoint2D + { + public extern float angle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useMotor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool useLimits + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public JointMotor2D motor + { + get + { + JointMotor2D result; + this.INTERNAL_get_motor(out result); + return result; + } + set + { + this.INTERNAL_set_motor(ref value); + } + } + public JointTranslationLimits2D limits + { + get + { + JointTranslationLimits2D result; + this.INTERNAL_get_limits(out result); + return result; + } + set + { + this.INTERNAL_set_limits(ref value); + } + } + public extern JointLimitState2D limitState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float referenceAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float jointTranslation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float jointSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_motor(out JointMotor2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_motor(ref JointMotor2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_limits(out JointTranslationLimits2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_limits(ref JointTranslationLimits2D value); + public float GetMotorForce(float timeStep) + { + return SliderJoint2D.INTERNAL_CALL_GetMotorForce(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetMotorForce(SliderJoint2D self, float timeStep); + } +} diff --git a/UnityEngine/UnityEngine/SliderState.cs b/UnityEngine/UnityEngine/SliderState.cs new file mode 100644 index 00000000..e42d1592 --- /dev/null +++ b/UnityEngine/UnityEngine/SliderState.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal class SliderState + { + public float dragStartPos; + public float dragStartValue; + public bool isDragging; + } +} diff --git a/UnityEngine/UnityEngine/Social.cs b/UnityEngine/UnityEngine/Social.cs new file mode 100644 index 00000000..2c86bfad --- /dev/null +++ b/UnityEngine/UnityEngine/Social.cs @@ -0,0 +1,66 @@ +using System; +using UnityEngine.SocialPlatforms; +namespace UnityEngine +{ + public static class Social + { + public static ISocialPlatform Active + { + get + { + return ActivePlatform.Instance; + } + set + { + ActivePlatform.Instance = value; + } + } + public static ILocalUser localUser + { + get + { + return Social.Active.localUser; + } + } + public static void LoadUsers(string[] userIDs, Action callback) + { + Social.Active.LoadUsers(userIDs, callback); + } + public static void ReportProgress(string achievementID, double progress, Action callback) + { + Social.Active.ReportProgress(achievementID, progress, callback); + } + public static void LoadAchievementDescriptions(Action callback) + { + Social.Active.LoadAchievementDescriptions(callback); + } + public static void LoadAchievements(Action callback) + { + Social.Active.LoadAchievements(callback); + } + public static void ReportScore(long score, string board, Action callback) + { + Social.Active.ReportScore(score, board, callback); + } + public static void LoadScores(string leaderboardID, Action callback) + { + Social.Active.LoadScores(leaderboardID, callback); + } + public static ILeaderboard CreateLeaderboard() + { + return Social.Active.CreateLeaderboard(); + } + public static IAchievement CreateAchievement() + { + return Social.Active.CreateAchievement(); + } + public static void ShowAchievementsUI() + { + Social.Active.ShowAchievementsUI(); + } + public static void ShowLeaderboardUI() + { + Social.Active.ShowLeaderboardUI(); + } + } +} diff --git a/UnityEngine/UnityEngine/SoftJointLimit.cs b/UnityEngine/UnityEngine/SoftJointLimit.cs new file mode 100644 index 00000000..5b2b9055 --- /dev/null +++ b/UnityEngine/UnityEngine/SoftJointLimit.cs @@ -0,0 +1,67 @@ +using System; +namespace UnityEngine +{ + public struct SoftJointLimit + { + private float m_Limit; + private float m_Bounciness; + private float m_Spring; + private float m_Damper; + public float limit + { + get + { + return this.m_Limit; + } + set + { + this.m_Limit = value; + } + } + public float spring + { + get + { + return this.m_Spring; + } + set + { + this.m_Spring = value; + } + } + public float damper + { + get + { + return this.m_Damper; + } + set + { + this.m_Damper = value; + } + } + public float bounciness + { + get + { + return this.m_Bounciness; + } + set + { + this.m_Bounciness = value; + } + } + [Obsolete("Use SoftJointLimit.bounciness instead", true)] + public float bouncyness + { + get + { + return this.m_Bounciness; + } + set + { + this.m_Bounciness = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/Space.cs b/UnityEngine/UnityEngine/Space.cs new file mode 100644 index 00000000..59e48dae --- /dev/null +++ b/UnityEngine/UnityEngine/Space.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum Space + { + World, + Self + } +} diff --git a/UnityEngine/UnityEngine/SpaceAttribute.cs b/UnityEngine/UnityEngine/SpaceAttribute.cs new file mode 100644 index 00000000..1b3fa1be --- /dev/null +++ b/UnityEngine/UnityEngine/SpaceAttribute.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] + public class SpaceAttribute : PropertyAttribute + { + public readonly float height; + public SpaceAttribute(float height) + { + this.height = height; + } + } +} diff --git a/UnityEngine/UnityEngine/SparseTexture.cs b/UnityEngine/UnityEngine/SparseTexture.cs new file mode 100644 index 00000000..576b85ea --- /dev/null +++ b/UnityEngine/UnityEngine/SparseTexture.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SparseTexture : Texture + { + public extern int tileWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int tileHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isCreated + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public SparseTexture(int width, int height, TextureFormat format, int mipCount) + { + SparseTexture.Internal_Create(this, width, height, format, mipCount, false); + } + public SparseTexture(int width, int height, TextureFormat format, int mipCount, bool linear) + { + SparseTexture.Internal_Create(this, width, height, format, mipCount, linear); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] SparseTexture mono, int width, int height, TextureFormat format, int mipCount, bool linear); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateTile(int tileX, int tileY, int miplevel, Color32[] data); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateTileRaw(int tileX, int tileY, int miplevel, byte[] data); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UnloadTile(int tileX, int tileY, int miplevel); + } +} diff --git a/UnityEngine/UnityEngine/SphereCollider.cs b/UnityEngine/UnityEngine/SphereCollider.cs new file mode 100644 index 00000000..6ddd82f0 --- /dev/null +++ b/UnityEngine/UnityEngine/SphereCollider.cs @@ -0,0 +1,36 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SphereCollider : Collider + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + } +} diff --git a/UnityEngine/UnityEngine/SplatPrototype.cs b/UnityEngine/UnityEngine/SplatPrototype.cs new file mode 100644 index 00000000..bbc7d507 --- /dev/null +++ b/UnityEngine/UnityEngine/SplatPrototype.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class SplatPrototype + { + private Texture2D m_Texture; + private Texture2D m_NormalMap; + private Vector2 m_TileSize = new Vector2(15f, 15f); + private Vector2 m_TileOffset = new Vector2(0f, 0f); + public Texture2D texture + { + get + { + return this.m_Texture; + } + set + { + this.m_Texture = value; + } + } + public Texture2D normalMap + { + get + { + return this.m_NormalMap; + } + set + { + this.m_NormalMap = value; + } + } + public Vector2 tileSize + { + get + { + return this.m_TileSize; + } + set + { + this.m_TileSize = value; + } + } + public Vector2 tileOffset + { + get + { + return this.m_TileOffset; + } + set + { + this.m_TileOffset = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/SpringJoint.cs b/UnityEngine/UnityEngine/SpringJoint.cs new file mode 100644 index 00000000..c54fde5c --- /dev/null +++ b/UnityEngine/UnityEngine/SpringJoint.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SpringJoint : Joint + { + public extern float spring + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float damper + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float minDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float maxDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/SpringJoint2D.cs b/UnityEngine/UnityEngine/SpringJoint2D.cs new file mode 100644 index 00000000..d98c563f --- /dev/null +++ b/UnityEngine/UnityEngine/SpringJoint2D.cs @@ -0,0 +1,51 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SpringJoint2D : AnchoredJoint2D + { + public extern float distance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float dampingRatio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float frequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 GetReactionForce(float timeStep) + { + Vector2 result; + SpringJoint2D.SpringJoint2D_CUSTOM_INTERNAL_GetReactionForce(this, timeStep, out result); + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SpringJoint2D_CUSTOM_INTERNAL_GetReactionForce(SpringJoint2D joint, float timeStep, out Vector2 value); + public float GetReactionTorque(float timeStep) + { + return SpringJoint2D.INTERNAL_CALL_GetReactionTorque(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetReactionTorque(SpringJoint2D self, float timeStep); + } +} diff --git a/UnityEngine/UnityEngine/Sprite.cs b/UnityEngine/UnityEngine/Sprite.cs new file mode 100644 index 00000000..30d95727 --- /dev/null +++ b/UnityEngine/UnityEngine/Sprite.cs @@ -0,0 +1,112 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Sprite : Object + { + public extern Bounds bounds + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Rect rect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float pixelsPerUnit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Texture2D texture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Rect textureRect + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector2 textureRectOffset + { + get + { + Vector2 result; + Sprite.Internal_GetTextureRectOffset(this, out result); + return result; + } + } + public extern bool packed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern SpritePackingMode packingMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern SpritePackingRotation packingRotation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector4 border + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, [DefaultValue("100.0f")] float pixelsPerUnit, [DefaultValue("0")] uint extrude, [DefaultValue("SpriteMeshType.Tight")] SpriteMeshType meshType, [DefaultValue("Vector4.zero")] Vector4 border) + { + return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref border); + } + [ExcludeFromDocs] + public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType) + { + Vector4 zero = Vector4.zero; + return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref zero); + } + [ExcludeFromDocs] + public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude) + { + Vector4 zero = Vector4.zero; + SpriteMeshType meshType = SpriteMeshType.Tight; + return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref zero); + } + [ExcludeFromDocs] + public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit) + { + Vector4 zero = Vector4.zero; + SpriteMeshType meshType = SpriteMeshType.Tight; + uint extrude = 0u; + return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref zero); + } + [ExcludeFromDocs] + public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot) + { + Vector4 zero = Vector4.zero; + SpriteMeshType meshType = SpriteMeshType.Tight; + uint extrude = 0u; + float pixelsPerUnit = 100f; + return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref zero); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Sprite INTERNAL_CALL_Create(Texture2D texture, ref Rect rect, ref Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType, ref Vector4 border); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTextureRectOffset(Sprite sprite, out Vector2 output); + } +} diff --git a/UnityEngine/UnityEngine/SpriteAlignment.cs b/UnityEngine/UnityEngine/SpriteAlignment.cs new file mode 100644 index 00000000..b81937aa --- /dev/null +++ b/UnityEngine/UnityEngine/SpriteAlignment.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEngine +{ + public enum SpriteAlignment + { + Center, + TopLeft, + TopCenter, + TopRight, + LeftCenter, + RightCenter, + BottomLeft, + BottomCenter, + BottomRight, + Custom + } +} diff --git a/UnityEngine/UnityEngine/SpriteMeshType.cs b/UnityEngine/UnityEngine/SpriteMeshType.cs new file mode 100644 index 00000000..eaf2f74c --- /dev/null +++ b/UnityEngine/UnityEngine/SpriteMeshType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum SpriteMeshType + { + FullRect, + Tight + } +} diff --git a/UnityEngine/UnityEngine/SpritePackingMode.cs b/UnityEngine/UnityEngine/SpritePackingMode.cs new file mode 100644 index 00000000..ddfa293b --- /dev/null +++ b/UnityEngine/UnityEngine/SpritePackingMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum SpritePackingMode + { + Tight, + Rectangle + } +} diff --git a/UnityEngine/UnityEngine/SpritePackingRotation.cs b/UnityEngine/UnityEngine/SpritePackingRotation.cs new file mode 100644 index 00000000..bc69e8ad --- /dev/null +++ b/UnityEngine/UnityEngine/SpritePackingRotation.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum SpritePackingRotation + { + None, + Any = 15 + } +} diff --git a/UnityEngine/UnityEngine/SpriteRenderer.cs b/UnityEngine/UnityEngine/SpriteRenderer.cs new file mode 100644 index 00000000..2ac8f4a9 --- /dev/null +++ b/UnityEngine/UnityEngine/SpriteRenderer.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SpriteRenderer : Renderer + { + public Sprite sprite + { + get + { + return this.GetSprite_INTERNAL(); + } + set + { + this.SetSprite_INTERNAL(value); + } + } + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Sprite GetSprite_INTERNAL(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetSprite_INTERNAL(Sprite sprite); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/StackTraceUtility.cs b/UnityEngine/UnityEngine/StackTraceUtility.cs new file mode 100644 index 00000000..afd428b0 --- /dev/null +++ b/UnityEngine/UnityEngine/StackTraceUtility.cs @@ -0,0 +1,218 @@ +using System; +using System.Diagnostics; +using System.Reflection; +using System.Text; +namespace UnityEngine +{ + public class StackTraceUtility + { + private static string projectFolder = string.Empty; + internal static void SetProjectFolder(string folder) + { + StackTraceUtility.projectFolder = folder; + } + public static string ExtractStackTrace() + { + StackTrace stackTrace = new StackTrace(1, true); + return StackTraceUtility.ExtractFormattedStackTrace(stackTrace).ToString(); + } + private static bool IsSystemStacktraceType(object name) + { + string text = (string)name; + return text.StartsWith("UnityEditor.") || text.StartsWith("UnityEngine.") || text.StartsWith("System.") || text.StartsWith("UnityScript.Lang.") || text.StartsWith("Boo.Lang.") || text.StartsWith("UnityEngine.SetupCoroutine"); + } + public static string ExtractStringFromException(object exception) + { + string empty = string.Empty; + string empty2 = string.Empty; + StackTraceUtility.ExtractStringFromExceptionInternal(exception, out empty, out empty2); + return empty + "\n" + empty2; + } + internal static void ExtractStringFromExceptionInternal(object exceptiono, out string message, out string stackTrace) + { + if (exceptiono == null) + { + throw new ArgumentException("ExtractStringFromExceptionInternal called with null exception"); + } + Exception ex = exceptiono as Exception; + if (ex == null) + { + throw new ArgumentException("ExtractStringFromExceptionInternal called with an exceptoin that was not of type System.Exception"); + } + StringBuilder stringBuilder = new StringBuilder((ex.StackTrace != null) ? (ex.StackTrace.Length * 2) : 512); + message = string.Empty; + string text = string.Empty; + while (ex != null) + { + if (text.Length == 0) + { + text = ex.StackTrace; + } + else + { + text = ex.StackTrace + "\n" + text; + } + string text2 = ex.GetType().Name; + string text3 = string.Empty; + if (ex.Message != null) + { + text3 = ex.Message; + } + if (text3.Trim().Length != 0) + { + text2 += ": "; + text2 += text3; + } + message = text2; + if (ex.InnerException != null) + { + text = "Rethrow as " + text2 + "\n" + text; + } + ex = ex.InnerException; + } + stringBuilder.Append(text + "\n"); + StackTrace stackTrace2 = new StackTrace(1, true); + stringBuilder.Append(StackTraceUtility.ExtractFormattedStackTrace(stackTrace2)); + stackTrace = stringBuilder.ToString(); + } + internal static string PostprocessStacktrace(string oldString, bool stripEngineInternalInformation) + { + if (oldString == null) + { + return string.Empty; + } + string[] array = oldString.Split(new char[] + { + '\n' + }); + StringBuilder stringBuilder = new StringBuilder(oldString.Length); + for (int i = 0; i < array.Length; i++) + { + array[i] = array[i].Trim(); + } + for (int j = 0; j < array.Length; j++) + { + string text = array[j]; + if (text.Length != 0 && text[0] != '\n') + { + if (!text.StartsWith("in (unmanaged)")) + { + if (stripEngineInternalInformation && text.StartsWith("UnityEditor.EditorGUIUtility:RenderGameViewCameras")) + { + break; + } + if (stripEngineInternalInformation && j < array.Length - 1 && StackTraceUtility.IsSystemStacktraceType(text)) + { + if (StackTraceUtility.IsSystemStacktraceType(array[j + 1])) + { + goto IL_261; + } + int num = text.IndexOf(" (at"); + if (num != -1) + { + text = text.Substring(0, num); + } + } + if (text.IndexOf("(wrapper managed-to-native)") == -1) + { + if (text.IndexOf("(wrapper delegate-invoke)") == -1) + { + if (text.IndexOf("at <0x00000> ") == -1) + { + if (!stripEngineInternalInformation || !text.StartsWith("[") || !text.EndsWith("]")) + { + if (text.StartsWith("at ")) + { + text = text.Remove(0, 3); + } + int num2 = text.IndexOf("[0x"); + int num3 = -1; + if (num2 != -1) + { + num3 = text.IndexOf("]", num2); + } + if (num2 != -1 && num3 > num2) + { + text = text.Remove(num2, num3 - num2 + 1); + } + text = text.Replace(" in :0", string.Empty); + text = text.Replace(StackTraceUtility.projectFolder, string.Empty); + text = text.Replace('\\', '/'); + int num4 = text.LastIndexOf(" in "); + if (num4 != -1) + { + text = text.Remove(num4, 5); + text = text.Insert(num4, " (at "); + text = text.Insert(text.Length, ")"); + } + stringBuilder.Append(text + "\n"); + } + } + } + } + } + } + IL_261:; + } + return stringBuilder.ToString(); + } + internal static string ExtractFormattedStackTrace(StackTrace stackTrace) + { + StringBuilder stringBuilder = new StringBuilder(255); + for (int i = 0; i < stackTrace.FrameCount; i++) + { + StackFrame frame = stackTrace.GetFrame(i); + MethodBase method = frame.GetMethod(); + if (method != null) + { + Type declaringType = method.DeclaringType; + if (declaringType != null) + { + string @namespace = declaringType.Namespace; + if (@namespace != null && @namespace.Length != 0) + { + stringBuilder.Append(@namespace); + stringBuilder.Append("."); + } + stringBuilder.Append(declaringType.Name); + stringBuilder.Append(":"); + stringBuilder.Append(method.Name); + stringBuilder.Append("("); + int j = 0; + ParameterInfo[] parameters = method.GetParameters(); + bool flag = true; + while (j < parameters.Length) + { + if (!flag) + { + stringBuilder.Append(", "); + } + else + { + flag = false; + } + stringBuilder.Append(parameters[j].ParameterType.Name); + j++; + } + stringBuilder.Append(")"); + string text = frame.GetFileName(); + if (text != null && (!(declaringType.Name == "Debug") || !(declaringType.Namespace == "UnityEngine"))) + { + stringBuilder.Append(" (at "); + if (text.StartsWith(StackTraceUtility.projectFolder)) + { + text = text.Substring(StackTraceUtility.projectFolder.Length, text.Length - StackTraceUtility.projectFolder.Length); + } + stringBuilder.Append(text); + stringBuilder.Append(":"); + stringBuilder.Append(frame.GetFileLineNumber().ToString()); + stringBuilder.Append(")"); + } + stringBuilder.Append("\n"); + } + } + } + return stringBuilder.ToString(); + } + } +} diff --git a/UnityEngine/UnityEngine/StaticBatchingUtility.cs b/UnityEngine/UnityEngine/StaticBatchingUtility.cs new file mode 100644 index 00000000..47dd1c6e --- /dev/null +++ b/UnityEngine/UnityEngine/StaticBatchingUtility.cs @@ -0,0 +1,22 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class StaticBatchingUtility + { + public static void Combine(GameObject staticBatchRoot) + { + InternalStaticBatchingUtility.Combine(staticBatchRoot); + } + public static void Combine(GameObject[] gos, GameObject staticBatchRoot) + { + InternalStaticBatchingUtility.Combine(gos, staticBatchRoot); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Mesh InternalCombineVertices(MeshSubsetCombineUtility.MeshInstance[] meshes, string meshName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InternalCombineIndices(MeshSubsetCombineUtility.SubMeshInstance[] submeshes, [Writable] Mesh combinedMesh); + } +} diff --git a/UnityEngine/UnityEngine/SystemClock.cs b/UnityEngine/UnityEngine/SystemClock.cs new file mode 100644 index 00000000..44a03ede --- /dev/null +++ b/UnityEngine/UnityEngine/SystemClock.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + internal class SystemClock + { + public static DateTime now + { + get + { + return DateTime.Now; + } + } + } +} diff --git a/UnityEngine/UnityEngine/SystemInfo.cs b/UnityEngine/UnityEngine/SystemInfo.cs new file mode 100644 index 00000000..cd0d6b9f --- /dev/null +++ b/UnityEngine/UnityEngine/SystemInfo.cs @@ -0,0 +1,209 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SystemInfo + { + public static extern string operatingSystem + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string processorType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int processorCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int systemMemorySize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int graphicsMemorySize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string graphicsDeviceName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string graphicsDeviceVendor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int graphicsDeviceID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int graphicsDeviceVendorID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string graphicsDeviceVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int graphicsShaderLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int graphicsPixelFillrate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsShadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsRenderTextures + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsRenderToCubemap + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsImageEffects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supports3DTextures + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsComputeShaders + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsInstancing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsSparseTextures + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int supportedRenderTargetCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int supportsStencil + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsVertexPrograms + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern NPOTSupport npotSupport + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string deviceUniqueIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string deviceName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string deviceModel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsAccelerometer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsGyroscope + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsLocationService + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool supportsVibration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern DeviceType deviceType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int maxTextureSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SupportsRenderTextureFormat(RenderTextureFormat format); + } +} diff --git a/UnityEngine/UnityEngine/SystemLanguage.cs b/UnityEngine/UnityEngine/SystemLanguage.cs new file mode 100644 index 00000000..2a4c3060 --- /dev/null +++ b/UnityEngine/UnityEngine/SystemLanguage.cs @@ -0,0 +1,49 @@ +using System; +namespace UnityEngine +{ + public enum SystemLanguage + { + Afrikaans, + Arabic, + Basque, + Belarusian, + Bulgarian, + Catalan, + Chinese, + Czech, + Danish, + Dutch, + English, + Estonian, + Faroese, + Finnish, + French, + German, + Greek, + Hebrew, + Hugarian, + Icelandic, + Indonesian, + Italian, + Japanese, + Korean, + Latvian, + Lithuanian, + Norwegian, + Polish, + Portuguese, + Romanian, + Russian, + SerboCroatian, + Slovak, + Slovenian, + Spanish, + Swedish, + Thai, + Turkish, + Ukrainian, + Vietnamese, + Unknown, + Hungarian = 18 + } +} diff --git a/UnityEngine/UnityEngine/Terrain.cs b/UnityEngine/UnityEngine/Terrain.cs new file mode 100644 index 00000000..7c8cb7f2 --- /dev/null +++ b/UnityEngine/UnityEngine/Terrain.cs @@ -0,0 +1,608 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + [AddComponentMenu(""), ExecuteInEditMode] + public sealed class Terrain : MonoBehaviour + { + [SerializeField] + private TerrainData m_TerrainData; + [SerializeField] + private float m_TreeDistance = 5000f; + [SerializeField] + private float m_TreeBillboardDistance = 50f; + [SerializeField] + private float m_TreeCrossFadeLength = 5f; + [SerializeField] + private int m_TreeMaximumFullLODCount = 50; + [SerializeField] + private float m_DetailObjectDistance = 80f; + [SerializeField] + private float m_DetailObjectDensity = 1f; + [SerializeField] + private float m_HeightmapPixelError = 5f; + [SerializeField] + private float m_SplatMapDistance = 1000f; + [SerializeField] + private int m_HeightmapMaximumLOD; + [SerializeField] + private bool m_CastShadows = true; + [SerializeField] + private int m_LightmapIndex = -1; + [SerializeField] + private int m_LightmapSize = 1024; + [SerializeField] + private bool m_DrawTreesAndFoliage = true; + [SerializeField] + private bool m_CollectDetailPatches = true; + [SerializeField] + private Material m_MaterialTemplate; + [NonSerialized] + private IntPtr m_TerrainInstance; + private IntPtr InstanceObject + { + get + { + this.MakeSureObjectIsAlive(); + if (this.m_TerrainInstance == IntPtr.Zero) + { + this.m_TerrainInstance = this.Construct(); + this.Internal_SetTerrainData(this.m_TerrainInstance, this.m_TerrainData); + this.Internal_SetTreeDistance(this.m_TerrainInstance, this.m_TreeDistance); + this.Internal_SetTreeBillboardDistance(this.m_TerrainInstance, this.m_TreeBillboardDistance); + this.Internal_SetTreeCrossFadeLength(this.m_TerrainInstance, this.m_TreeCrossFadeLength); + this.Internal_SetTreeMaximumFullLODCount(this.m_TerrainInstance, this.m_TreeMaximumFullLODCount); + this.Internal_SetDetailObjectDistance(this.m_TerrainInstance, this.m_DetailObjectDistance); + this.Internal_SetDetailObjectDensity(this.m_TerrainInstance, this.m_DetailObjectDensity); + this.Internal_SetHeightmapPixelError(this.m_TerrainInstance, this.m_HeightmapPixelError); + this.Internal_SetBasemapDistance(this.m_TerrainInstance, this.m_SplatMapDistance); + this.Internal_SetHeightmapMaximumLOD(this.m_TerrainInstance, this.m_HeightmapMaximumLOD); + this.Internal_SetCastShadows(this.m_TerrainInstance, this.m_CastShadows); + this.Internal_SetLightmapIndex(this.m_TerrainInstance, this.m_LightmapIndex); + this.Internal_SetLightmapSize(this.m_TerrainInstance, this.m_LightmapSize); + this.Internal_SetDrawTreesAndFoliage(this.m_TerrainInstance, this.m_DrawTreesAndFoliage); + this.Internal_SetCollectDetailPatches(this.m_TerrainInstance, this.m_CollectDetailPatches); + this.Internal_SetMaterialTemplate(this.m_TerrainInstance, this.m_MaterialTemplate); + } + return this.m_TerrainInstance; + } + set + { + this.m_TerrainInstance = value; + } + } + public TerrainRenderFlags editorRenderFlags + { + get + { + return (TerrainRenderFlags)this.GetEditorRenderFlags(this.InstanceObject); + } + set + { + this.SetEditorRenderFlags(this.InstanceObject, (int)value); + } + } + public TerrainData terrainData + { + get + { + if (this.m_TerrainData != this.Internal_GetTerrainData(this.InstanceObject)) + { + this.Internal_SetTerrainData(this.InstanceObject, this.m_TerrainData); + } + return this.m_TerrainData; + } + set + { + this.m_TerrainData = value; + this.Internal_SetTerrainData(this.InstanceObject, value); + } + } + public float treeDistance + { + get + { + if (this.m_TreeDistance != this.Internal_GetTreeDistance(this.InstanceObject)) + { + this.Internal_SetTreeDistance(this.InstanceObject, this.m_TreeDistance); + } + return this.m_TreeDistance; + } + set + { + this.m_TreeDistance = value; + this.Internal_SetTreeDistance(this.InstanceObject, value); + } + } + public float treeBillboardDistance + { + get + { + if (this.m_TreeBillboardDistance != this.Internal_GetTreeBillboardDistance(this.InstanceObject)) + { + this.Internal_SetTreeBillboardDistance(this.InstanceObject, this.m_TreeBillboardDistance); + } + return this.m_TreeBillboardDistance; + } + set + { + this.m_TreeBillboardDistance = value; + this.Internal_SetTreeBillboardDistance(this.InstanceObject, value); + } + } + public float treeCrossFadeLength + { + get + { + if (this.m_TreeCrossFadeLength != this.Internal_GetTreeCrossFadeLength(this.InstanceObject)) + { + this.Internal_SetTreeCrossFadeLength(this.InstanceObject, this.m_TreeCrossFadeLength); + } + return this.m_TreeCrossFadeLength; + } + set + { + this.m_TreeCrossFadeLength = value; + this.Internal_SetTreeCrossFadeLength(this.InstanceObject, value); + } + } + public int treeMaximumFullLODCount + { + get + { + if (this.m_TreeMaximumFullLODCount != this.Internal_GetTreeMaximumFullLODCount(this.InstanceObject)) + { + this.Internal_SetTreeMaximumFullLODCount(this.InstanceObject, this.m_TreeMaximumFullLODCount); + } + return this.m_TreeMaximumFullLODCount; + } + set + { + this.m_TreeMaximumFullLODCount = value; + this.Internal_SetTreeMaximumFullLODCount(this.InstanceObject, value); + } + } + public float detailObjectDistance + { + get + { + if (this.m_DetailObjectDistance != this.Internal_GetDetailObjectDistance(this.InstanceObject)) + { + this.Internal_SetDetailObjectDistance(this.InstanceObject, this.m_DetailObjectDistance); + } + return this.m_DetailObjectDistance; + } + set + { + this.m_DetailObjectDistance = value; + this.Internal_SetDetailObjectDistance(this.InstanceObject, value); + } + } + public float detailObjectDensity + { + get + { + if (this.m_DetailObjectDensity != this.Internal_GetDetailObjectDensity(this.InstanceObject)) + { + this.Internal_SetDetailObjectDensity(this.InstanceObject, this.m_DetailObjectDensity); + } + return this.m_DetailObjectDensity; + } + set + { + this.m_DetailObjectDensity = value; + this.Internal_SetDetailObjectDensity(this.InstanceObject, value); + } + } + public float heightmapPixelError + { + get + { + if (this.m_HeightmapPixelError != this.Internal_GetHeightmapPixelError(this.InstanceObject)) + { + this.Internal_SetHeightmapPixelError(this.InstanceObject, this.m_HeightmapPixelError); + } + return this.m_HeightmapPixelError; + } + set + { + this.m_HeightmapPixelError = value; + this.Internal_SetHeightmapPixelError(this.InstanceObject, value); + } + } + public int heightmapMaximumLOD + { + get + { + if (this.m_HeightmapMaximumLOD != this.Internal_GetHeightmapMaximumLOD(this.InstanceObject)) + { + this.Internal_SetHeightmapMaximumLOD(this.InstanceObject, this.m_HeightmapMaximumLOD); + } + return this.m_HeightmapMaximumLOD; + } + set + { + this.m_HeightmapMaximumLOD = value; + this.Internal_SetHeightmapMaximumLOD(this.InstanceObject, value); + } + } + public float basemapDistance + { + get + { + if (this.m_SplatMapDistance != this.Internal_GetBasemapDistance(this.InstanceObject)) + { + this.Internal_SetBasemapDistance(this.InstanceObject, this.m_SplatMapDistance); + } + return this.m_SplatMapDistance; + } + set + { + this.m_SplatMapDistance = value; + this.Internal_SetBasemapDistance(this.InstanceObject, value); + } + } + [Obsolete("use basemapDistance", true)] + public float splatmapDistance + { + get + { + return this.basemapDistance; + } + set + { + this.basemapDistance = value; + } + } + public int lightmapIndex + { + get + { + if (this.m_LightmapIndex != this.Internal_GetLightmapIndex(this.InstanceObject)) + { + this.Internal_SetLightmapIndex(this.InstanceObject, this.m_LightmapIndex); + } + return this.m_LightmapIndex; + } + set + { + this.m_LightmapIndex = value; + this.Internal_SetLightmapIndex(this.InstanceObject, value); + } + } + internal int lightmapSize + { + get + { + if (this.m_LightmapSize != this.Internal_GetLightmapSize(this.InstanceObject)) + { + this.Internal_SetLightmapSize(this.InstanceObject, this.m_LightmapSize); + } + return this.m_LightmapSize; + } + set + { + this.m_LightmapSize = value; + this.Internal_SetLightmapSize(this.InstanceObject, value); + } + } + public bool castShadows + { + get + { + if (this.m_CastShadows != this.Internal_GetCastShadows(this.InstanceObject)) + { + this.Internal_SetCastShadows(this.InstanceObject, this.m_CastShadows); + } + return this.m_CastShadows; + } + set + { + this.m_CastShadows = value; + this.Internal_SetCastShadows(this.InstanceObject, value); + } + } + public Material materialTemplate + { + get + { + if (this.m_MaterialTemplate != this.Internal_GetMaterialTemplate(this.InstanceObject)) + { + this.Internal_SetMaterialTemplate(this.InstanceObject, this.m_MaterialTemplate); + } + return this.m_MaterialTemplate; + } + set + { + this.m_MaterialTemplate = value; + this.Internal_SetMaterialTemplate(this.InstanceObject, value); + } + } + internal bool drawTreesAndFoliage + { + get + { + if (this.m_DrawTreesAndFoliage != this.Internal_GetDrawTreesAndFoliage(this.InstanceObject)) + { + this.Internal_SetDrawTreesAndFoliage(this.InstanceObject, this.m_DrawTreesAndFoliage); + } + return this.m_DrawTreesAndFoliage; + } + set + { + this.m_DrawTreesAndFoliage = value; + this.Internal_SetDrawTreesAndFoliage(this.InstanceObject, value); + } + } + public bool collectDetailPatches + { + get + { + if (this.m_CollectDetailPatches != this.Internal_GetCollectDetailPatches(this.InstanceObject)) + { + this.Internal_SetCollectDetailPatches(this.InstanceObject, this.m_CollectDetailPatches); + } + return this.m_CollectDetailPatches; + } + set + { + this.m_CollectDetailPatches = value; + this.Internal_SetCollectDetailPatches(this.InstanceObject, value); + } + } + public static extern Terrain activeTerrain + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Terrain[] activeTerrains + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private void OnDestroy() + { + this.OnDisable(); + this.Cleanup(this.m_TerrainInstance); + this.m_TerrainInstance = IntPtr.Zero; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void MakeSureObjectIsAlive(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Cleanup(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int GetEditorRenderFlags(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetEditorRenderFlags(IntPtr terrainInstance, int flags); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern TerrainData Internal_GetTerrainData(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTerrainData(IntPtr terrainInstance, TerrainData value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetTreeDistance(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTreeDistance(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetTreeBillboardDistance(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTreeBillboardDistance(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetTreeCrossFadeLength(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTreeCrossFadeLength(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetTreeMaximumFullLODCount(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetTreeMaximumFullLODCount(IntPtr terrainInstance, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetDetailObjectDistance(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetDetailObjectDistance(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetDetailObjectDensity(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetDetailObjectDensity(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetHeightmapPixelError(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetHeightmapPixelError(IntPtr terrainInstance, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetHeightmapMaximumLOD(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetHeightmapMaximumLOD(IntPtr terrainInstance, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern float Internal_GetBasemapDistance(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetBasemapDistance(IntPtr terrainInstance, float value); + private void SetLightmapIndex(int value) + { + this.lightmapIndex = value; + } + private void ShiftLightmapIndex(int offset) + { + this.lightmapIndex += offset; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetLightmapIndex(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetLightmapIndex(IntPtr terrainInstance, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern int Internal_GetLightmapSize(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetLightmapSize(IntPtr terrainInstance, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_GetCastShadows(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetCastShadows(IntPtr terrainInstance, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Material Internal_GetMaterialTemplate(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetMaterialTemplate(IntPtr terrainInstance, Material value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_GetDrawTreesAndFoliage(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetDrawTreesAndFoliage(IntPtr terrainInstance, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_GetCollectDetailPatches(IntPtr terrainInstance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetCollectDetailPatches(IntPtr terrainInstance, bool value); + public float SampleHeight(Vector3 worldPosition) + { + return this.Internal_SampleHeight(this.InstanceObject, worldPosition); + } + private float Internal_SampleHeight(IntPtr terrainInstance, Vector3 worldPosition) + { + return Terrain.INTERNAL_CALL_Internal_SampleHeight(this, terrainInstance, ref worldPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_Internal_SampleHeight(Terrain self, IntPtr terrainInstance, ref Vector3 worldPosition); + internal void ApplyDelayedHeightmapModification() + { + this.Internal_ApplyDelayedHeightmapModification(this.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Internal_ApplyDelayedHeightmapModification(IntPtr terrainInstance); + public void AddTreeInstance(TreeInstance instance) + { + this.Internal_AddTreeInstance(this.InstanceObject, instance); + } + private void Internal_AddTreeInstance(IntPtr terrainInstance, TreeInstance instance) + { + Terrain.INTERNAL_CALL_Internal_AddTreeInstance(this, terrainInstance, ref instance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_AddTreeInstance(Terrain self, IntPtr terrainInstance, ref TreeInstance instance); + public void SetNeighbors(Terrain left, Terrain top, Terrain right, Terrain bottom) + { + this.Internal_SetNeighbors(this.InstanceObject, (!(left != null)) ? IntPtr.Zero : left.InstanceObject, (!(top != null)) ? IntPtr.Zero : top.InstanceObject, (!(right != null)) ? IntPtr.Zero : right.InstanceObject, (!(bottom != null)) ? IntPtr.Zero : bottom.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetNeighbors(IntPtr terrainInstance, IntPtr left, IntPtr top, IntPtr right, IntPtr bottom); + public Vector3 GetPosition() + { + return this.Internal_GetPosition(this.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Vector3 Internal_GetPosition(IntPtr terrainInstance); + public void Flush() + { + this.Internal_Flush(this.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_Flush(IntPtr terrainInstance); + internal void RemoveTrees(Vector2 position, float radius, int prototypeIndex) + { + this.Internal_RemoveTrees(this.InstanceObject, position, radius, prototypeIndex); + } + private void Internal_RemoveTrees(IntPtr terrainInstance, Vector2 position, float radius, int prototypeIndex) + { + Terrain.INTERNAL_CALL_Internal_RemoveTrees(this, terrainInstance, ref position, radius, prototypeIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_RemoveTrees(Terrain self, IntPtr terrainInstance, ref Vector2 position, float radius, int prototypeIndex); + private void OnTerrainChanged(TerrainChangedFlags flags) + { + this.Internal_OnTerrainChanged(this.InstanceObject, flags); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_OnTerrainChanged(IntPtr terrainInstance, TerrainChangedFlags flags); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern IntPtr Construct(); + internal void OnEnable() + { + this.Internal_OnEnable(this.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_OnEnable(IntPtr terrainInstance); + internal void OnDisable() + { + this.Internal_OnDisable(this.InstanceObject); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_OnDisable(IntPtr terrainInstance); + public static GameObject CreateTerrainGameObject(TerrainData assignTerrain) + { + GameObject gameObject = new GameObject("Terrain", new Type[] + { + typeof(Terrain), + typeof(TerrainCollider) + }); + gameObject.isStatic = true; + Terrain terrain = gameObject.GetComponent(typeof(Terrain)) as Terrain; + TerrainCollider terrainCollider = gameObject.GetComponent(typeof(TerrainCollider)) as TerrainCollider; + terrainCollider.terrainData = assignTerrain; + terrain.terrainData = assignTerrain; + terrain.OnEnable(); + return gameObject; + } + private static void ReconnectTerrainData() + { + List list = new List(Terrain.activeTerrains); + foreach (Terrain current in list) + { + if (current.terrainData == null) + { + current.OnDisable(); + } + else + { + if (!current.terrainData.HasUser(current.gameObject)) + { + current.OnDisable(); + current.OnEnable(); + } + } + } + } + } +} diff --git a/UnityEngine/UnityEngine/TerrainChangedFlags.cs b/UnityEngine/UnityEngine/TerrainChangedFlags.cs new file mode 100644 index 00000000..250bfdde --- /dev/null +++ b/UnityEngine/UnityEngine/TerrainChangedFlags.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + [Flags] + internal enum TerrainChangedFlags + { + NoChange = 0, + Heightmap = 1, + TreeInstances = 2, + DelayedHeightmapUpdate = 4, + FlushEverythingImmediately = 8, + RemoveDirtyDetailsImmediately = 16, + WillBeDestroyed = 256 + } +} diff --git a/UnityEngine/UnityEngine/TerrainCollider.cs b/UnityEngine/UnityEngine/TerrainCollider.cs new file mode 100644 index 00000000..70f1d18b --- /dev/null +++ b/UnityEngine/UnityEngine/TerrainCollider.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class TerrainCollider : Collider + { + public extern TerrainData terrainData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/TerrainData.cs b/UnityEngine/UnityEngine/TerrainData.cs new file mode 100644 index 00000000..f6579b5c --- /dev/null +++ b/UnityEngine/UnityEngine/TerrainData.cs @@ -0,0 +1,355 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class TerrainData : Object + { + public extern PhysicMaterial physicMaterial + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int heightmapWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int heightmapHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int heightmapResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector3 heightmapScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 size + { + get + { + Vector3 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } + public extern float wavingGrassStrength + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wavingGrassAmount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float wavingGrassSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color wavingGrassTint + { + get + { + Color result; + this.INTERNAL_get_wavingGrassTint(out result); + return result; + } + set + { + this.INTERNAL_set_wavingGrassTint(ref value); + } + } + public extern int detailWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int detailHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int detailResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int detailResolutionPerPatch + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern DetailPrototype[] detailPrototypes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TreeInstance[] treeInstances + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TreePrototype[] treePrototypes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int alphamapLayers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int alphamapResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int alphamapWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int alphamapHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int baseMapResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + private extern int alphamapTextureCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal Texture2D[] alphamapTextures + { + get + { + Texture2D[] array = new Texture2D[this.alphamapTextureCount]; + for (int i = 0; i < array.Length; i++) + { + array[i] = this.GetAlphamapTexture(i); + } + return array; + } + } + public extern SplatPrototype[] splatPrototypes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public TerrainData() + { + this.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Internal_Create([Writable] TerrainData terrainData); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasUser(GameObject user); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddUser(GameObject user); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveUser(GameObject user); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetHeight(int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetInterpolatedHeight(float x, float y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float[,] GetHeights(int xBase, int yBase, int width, int height); + public void SetHeights(int xBase, int yBase, float[,] heights) + { + if (heights == null) + { + throw new NullReferenceException(); + } + if (xBase + heights.GetLength(1) > this.heightmapWidth || xBase + heights.GetLength(1) < 0 || yBase + heights.GetLength(0) < 0 || xBase < 0 || yBase < 0 || yBase + heights.GetLength(0) > this.heightmapHeight) + { + throw new ArgumentException(UnityString.Format("X or Y base out of bounds. Setting up to {0}x{1} while map size is {2}x{3}", new object[] + { + xBase + heights.GetLength(1), + yBase + heights.GetLength(0), + this.heightmapWidth, + this.heightmapHeight + })); + } + this.Internal_SetHeights(xBase, yBase, heights.GetLength(1), heights.GetLength(0), heights); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetHeights(int xBase, int yBase, int width, int height, float[,] heights); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetHeightsDelayLOD(int xBase, int yBase, int width, int height, float[,] heights); + internal void SetHeightsDelayLOD(int xBase, int yBase, float[,] heights) + { + this.Internal_SetHeightsDelayLOD(xBase, yBase, heights.GetLength(1), heights.GetLength(0), heights); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetSteepness(float x, float y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Vector3 GetInterpolatedNormal(float x, float y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int GetAdjustedSize(int size); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_wavingGrassTint(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_wavingGrassTint(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetDetailResolution(int detailResolution, int resolutionPerPatch); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void ResetDirtyDetails(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RefreshPrototypes(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[] GetSupportedLayers(int xBase, int yBase, int totalWidth, int totalHeight); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int[,] GetDetailLayer(int xBase, int yBase, int width, int height, int layer); + public void SetDetailLayer(int xBase, int yBase, int layer, int[,] details) + { + this.Internal_SetDetailLayer(xBase, yBase, details.GetLength(1), details.GetLength(0), layer, details); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetDetailLayer(int xBase, int yBase, int totalWidth, int totalHeight, int detailIndex, int[,] data); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveTreePrototype(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RecalculateTreePositions(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveDetailPrototype(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float[,,] GetAlphamaps(int x, int y, int width, int height); + public void SetAlphamaps(int x, int y, float[,,] map) + { + if (map.GetLength(2) != this.alphamapLayers) + { + throw new Exception(UnityString.Format("Float array size wrong (layers should be {0})", new object[] + { + this.alphamapLayers + })); + } + this.Internal_SetAlphamaps(x, y, map.GetLength(1), map.GetLength(0), map); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetAlphamaps(int x, int y, int width, int height, float[,,] map); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RecalculateBasemapIfDirty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetBasemapDirty(bool dirty); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Texture2D GetAlphamapTexture(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasTreeInstances(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddTree(out TreeInstance tree); + internal int RemoveTrees(Vector2 position, float radius, int prototypeIndex) + { + return TerrainData.INTERNAL_CALL_RemoveTrees(this, ref position, radius, prototypeIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int INTERNAL_CALL_RemoveTrees(TerrainData self, ref Vector2 position, float radius, int prototypeIndex); + } +} diff --git a/UnityEngine/UnityEngine/TerrainRenderFlags.cs b/UnityEngine/UnityEngine/TerrainRenderFlags.cs new file mode 100644 index 00000000..ee10b896 --- /dev/null +++ b/UnityEngine/UnityEngine/TerrainRenderFlags.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum TerrainRenderFlags + { + heightmap = 1, + trees, + details = 4, + all = 7 + } +} diff --git a/UnityEngine/UnityEngine/TexGenMode.cs b/UnityEngine/UnityEngine/TexGenMode.cs new file mode 100644 index 00000000..12497f5a --- /dev/null +++ b/UnityEngine/UnityEngine/TexGenMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum TexGenMode + { + None, + SphereMap, + Object, + EyeLinear, + CubeReflect, + CubeNormal + } +} diff --git a/UnityEngine/UnityEngine/TextAlignment.cs b/UnityEngine/UnityEngine/TextAlignment.cs new file mode 100644 index 00000000..d58afeb3 --- /dev/null +++ b/UnityEngine/UnityEngine/TextAlignment.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum TextAlignment + { + Left, + Center, + Right + } +} diff --git a/UnityEngine/UnityEngine/TextAnchor.cs b/UnityEngine/UnityEngine/TextAnchor.cs new file mode 100644 index 00000000..08722be7 --- /dev/null +++ b/UnityEngine/UnityEngine/TextAnchor.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + public enum TextAnchor + { + UpperLeft, + UpperCenter, + UpperRight, + MiddleLeft, + MiddleCenter, + MiddleRight, + LowerLeft, + LowerCenter, + LowerRight + } +} diff --git a/UnityEngine/UnityEngine/TextAreaAttribute.cs b/UnityEngine/UnityEngine/TextAreaAttribute.cs new file mode 100644 index 00000000..9d0f7805 --- /dev/null +++ b/UnityEngine/UnityEngine/TextAreaAttribute.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public sealed class TextAreaAttribute : PropertyAttribute + { + public readonly int minLines; + public readonly int maxLines; + public TextAreaAttribute() + { + this.minLines = 3; + this.maxLines = 3; + } + public TextAreaAttribute(int minLines, int maxLines) + { + this.minLines = minLines; + this.maxLines = maxLines; + } + } +} diff --git a/UnityEngine/UnityEngine/TextAsset.cs b/UnityEngine/UnityEngine/TextAsset.cs new file mode 100644 index 00000000..7649eda9 --- /dev/null +++ b/UnityEngine/UnityEngine/TextAsset.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class TextAsset : Object + { + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern byte[] bytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public override string ToString() + { + return this.text; + } + } +} diff --git a/UnityEngine/UnityEngine/TextClipping.cs b/UnityEngine/UnityEngine/TextClipping.cs new file mode 100644 index 00000000..f7eeddb8 --- /dev/null +++ b/UnityEngine/UnityEngine/TextClipping.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum TextClipping + { + Overflow, + Clip + } +} diff --git a/UnityEngine/UnityEngine/TextEditor.cs b/UnityEngine/UnityEngine/TextEditor.cs new file mode 100644 index 00000000..08e22c13 --- /dev/null +++ b/UnityEngine/UnityEngine/TextEditor.cs @@ -0,0 +1,1407 @@ +using System; +using System.Collections.Generic; +namespace UnityEngine +{ + public class TextEditor + { + public enum DblClickSnapping : byte + { + WORDS, + PARAGRAPHS + } + private enum CharacterType + { + LetterLike, + Symbol, + Symbol2, + WhiteSpace + } + private enum TextEditOp + { + MoveLeft, + MoveRight, + MoveUp, + MoveDown, + MoveLineStart, + MoveLineEnd, + MoveTextStart, + MoveTextEnd, + MovePageUp, + MovePageDown, + MoveGraphicalLineStart, + MoveGraphicalLineEnd, + MoveWordLeft, + MoveWordRight, + MoveParagraphForward, + MoveParagraphBackward, + MoveToStartOfNextWord, + MoveToEndOfPreviousWord, + SelectLeft, + SelectRight, + SelectUp, + SelectDown, + SelectTextStart, + SelectTextEnd, + SelectPageUp, + SelectPageDown, + ExpandSelectGraphicalLineStart, + ExpandSelectGraphicalLineEnd, + SelectGraphicalLineStart, + SelectGraphicalLineEnd, + SelectWordLeft, + SelectWordRight, + SelectToEndOfPreviousWord, + SelectToStartOfNextWord, + SelectParagraphBackward, + SelectParagraphForward, + Delete, + Backspace, + DeleteWordBack, + DeleteWordForward, + DeleteLineBack, + Cut, + Copy, + Paste, + SelectAll, + SelectNone, + ScrollStart, + ScrollEnd, + ScrollPageUp, + ScrollPageDown + } + public int pos; + public int selectPos; + public int controlID; + public GUIContent content = new GUIContent(); + public GUIStyle style = GUIStyle.none; + public Rect position; + public bool multiline; + public bool hasHorizontalCursorPos; + public bool isPasswordField; + internal bool m_HasFocus; + public Vector2 scrollOffset = Vector2.zero; + private bool m_TextHeightPotentiallyChanged; + public Vector2 graphicalCursorPos; + public Vector2 graphicalSelectCursorPos; + private bool m_MouseDragSelectsWholeWords; + private int m_DblClickInitPos; + private TextEditor.DblClickSnapping m_DblClickSnap; + private bool m_bJustSelected; + private int m_iAltCursorPos = -1; + private string oldText; + private int oldPos; + private int oldSelectPos; + private static Dictionary s_Keyactions; + public bool hasSelection + { + get + { + return this.pos != this.selectPos; + } + } + public string SelectedText + { + get + { + int length = this.content.text.Length; + if (this.pos > length) + { + this.pos = length; + } + if (this.selectPos > length) + { + this.selectPos = length; + } + if (this.pos == this.selectPos) + { + return string.Empty; + } + if (this.pos < this.selectPos) + { + return this.content.text.Substring(this.pos, this.selectPos - this.pos); + } + return this.content.text.Substring(this.selectPos, this.pos - this.selectPos); + } + } + private void ClearCursorPos() + { + this.hasHorizontalCursorPos = false; + this.m_iAltCursorPos = -1; + } + public void OnFocus() + { + if (this.multiline) + { + this.pos = (this.selectPos = 0); + } + else + { + this.SelectAll(); + } + this.m_HasFocus = true; + } + public void OnLostFocus() + { + this.m_HasFocus = false; + this.scrollOffset = Vector2.zero; + } + private void GrabGraphicalCursorPos() + { + if (!this.hasHorizontalCursorPos) + { + this.graphicalCursorPos = this.style.GetCursorPixelPosition(this.position, this.content, this.pos); + this.graphicalSelectCursorPos = this.style.GetCursorPixelPosition(this.position, this.content, this.selectPos); + this.hasHorizontalCursorPos = false; + } + } + public bool HandleKeyEvent(Event e) + { + this.InitKeyActions(); + EventModifiers modifiers = e.modifiers; + e.modifiers &= ~EventModifiers.CapsLock; + if (TextEditor.s_Keyactions.ContainsKey(e)) + { + TextEditor.TextEditOp operation = TextEditor.s_Keyactions[e]; + this.PerformOperation(operation); + e.modifiers = modifiers; + this.UpdateScrollOffset(); + return true; + } + e.modifiers = modifiers; + return false; + } + public bool DeleteLineBack() + { + if (this.hasSelection) + { + this.DeleteSelection(); + return true; + } + int num = this.pos; + int num2 = num; + while (num2-- != 0) + { + if (this.content.text[num2] == '\n') + { + num = num2 + 1; + break; + } + } + if (num2 == -1) + { + num = 0; + } + if (this.pos != num) + { + this.content.text = this.content.text.Remove(num, this.pos - num); + this.selectPos = (this.pos = num); + return true; + } + return false; + } + public bool DeleteWordBack() + { + if (this.hasSelection) + { + this.DeleteSelection(); + return true; + } + int num = this.FindEndOfPreviousWord(this.pos); + if (this.pos != num) + { + this.content.text = this.content.text.Remove(num, this.pos - num); + this.selectPos = (this.pos = num); + return true; + } + return false; + } + public bool DeleteWordForward() + { + if (this.hasSelection) + { + this.DeleteSelection(); + return true; + } + int num = this.FindStartOfNextWord(this.pos); + if (this.pos < this.content.text.Length) + { + this.content.text = this.content.text.Remove(this.pos, num - this.pos); + return true; + } + return false; + } + public bool Delete() + { + if (this.hasSelection) + { + this.DeleteSelection(); + return true; + } + if (this.pos < this.content.text.Length) + { + this.content.text = this.content.text.Remove(this.pos, 1); + return true; + } + return false; + } + public bool CanPaste() + { + return GUIUtility.systemCopyBuffer.Length != 0; + } + public bool Backspace() + { + if (this.hasSelection) + { + this.DeleteSelection(); + return true; + } + if (this.pos > 0) + { + this.content.text = this.content.text.Remove(this.pos - 1, 1); + this.selectPos = --this.pos; + this.ClearCursorPos(); + return true; + } + return false; + } + public void SelectAll() + { + this.pos = 0; + this.selectPos = this.content.text.Length; + this.ClearCursorPos(); + } + public void SelectNone() + { + this.selectPos = this.pos; + this.ClearCursorPos(); + } + public bool DeleteSelection() + { + int length = this.content.text.Length; + if (this.pos > length) + { + this.pos = length; + } + if (this.selectPos > length) + { + this.selectPos = length; + } + if (this.pos == this.selectPos) + { + return false; + } + if (this.pos < this.selectPos) + { + this.content.text = this.content.text.Substring(0, this.pos) + this.content.text.Substring(this.selectPos, this.content.text.Length - this.selectPos); + this.selectPos = this.pos; + } + else + { + this.content.text = this.content.text.Substring(0, this.selectPos) + this.content.text.Substring(this.pos, this.content.text.Length - this.pos); + this.pos = this.selectPos; + } + this.ClearCursorPos(); + return true; + } + public void ReplaceSelection(string replace) + { + this.DeleteSelection(); + this.content.text = this.content.text.Insert(this.pos, replace); + this.selectPos = (this.pos += replace.Length); + this.ClearCursorPos(); + this.UpdateScrollOffset(); + this.m_TextHeightPotentiallyChanged = true; + } + public void Insert(char c) + { + this.ReplaceSelection(c.ToString()); + } + public void MoveSelectionToAltCursor() + { + if (this.m_iAltCursorPos == -1) + { + return; + } + int iAltCursorPos = this.m_iAltCursorPos; + string selectedText = this.SelectedText; + this.content.text = this.content.text.Insert(iAltCursorPos, selectedText); + if (iAltCursorPos < this.pos) + { + this.pos += selectedText.Length; + this.selectPos += selectedText.Length; + } + this.DeleteSelection(); + this.selectPos = (this.pos = iAltCursorPos); + this.ClearCursorPos(); + this.UpdateScrollOffset(); + } + public void MoveRight() + { + this.ClearCursorPos(); + if (this.selectPos == this.pos) + { + this.pos++; + this.ClampPos(); + this.selectPos = this.pos; + } + else + { + if (this.selectPos > this.pos) + { + this.pos = this.selectPos; + } + else + { + this.selectPos = this.pos; + } + } + this.UpdateScrollOffset(); + } + public void MoveLeft() + { + if (this.selectPos == this.pos) + { + this.pos--; + if (this.pos < 0) + { + this.pos = 0; + } + this.selectPos = this.pos; + } + else + { + if (this.selectPos > this.pos) + { + this.selectPos = this.pos; + } + else + { + this.pos = this.selectPos; + } + } + this.ClearCursorPos(); + this.UpdateScrollOffset(); + } + public void MoveUp() + { + if (this.selectPos < this.pos) + { + this.selectPos = this.pos; + } + else + { + this.pos = this.selectPos; + } + this.GrabGraphicalCursorPos(); + this.graphicalCursorPos.y = this.graphicalCursorPos.y - 1f; + this.pos = (this.selectPos = this.style.GetCursorStringIndex(this.position, this.content, this.graphicalCursorPos)); + if (this.pos <= 0) + { + this.ClearCursorPos(); + } + this.UpdateScrollOffset(); + } + public void MoveDown() + { + if (this.selectPos > this.pos) + { + this.selectPos = this.pos; + } + else + { + this.pos = this.selectPos; + } + this.GrabGraphicalCursorPos(); + this.graphicalCursorPos.y = this.graphicalCursorPos.y + (this.style.lineHeight + 5f); + this.pos = (this.selectPos = this.style.GetCursorStringIndex(this.position, this.content, this.graphicalCursorPos)); + if (this.pos == this.content.text.Length) + { + this.ClearCursorPos(); + } + this.UpdateScrollOffset(); + } + public void MoveLineStart() + { + int num = (this.selectPos >= this.pos) ? this.pos : this.selectPos; + int num2 = num; + while (num2-- != 0) + { + if (this.content.text[num2] == '\n') + { + this.selectPos = (this.pos = num2 + 1); + return; + } + } + this.selectPos = (this.pos = 0); + this.UpdateScrollOffset(); + } + public void MoveLineEnd() + { + int num = (this.selectPos <= this.pos) ? this.pos : this.selectPos; + int i = num; + int length = this.content.text.Length; + while (i < length) + { + if (this.content.text[i] == '\n') + { + this.selectPos = (this.pos = i); + return; + } + i++; + } + this.selectPos = (this.pos = length); + this.UpdateScrollOffset(); + } + public void MoveGraphicalLineStart() + { + this.pos = (this.selectPos = this.GetGraphicalLineStart((this.pos >= this.selectPos) ? this.selectPos : this.pos)); + this.UpdateScrollOffset(); + } + public void MoveGraphicalLineEnd() + { + this.pos = (this.selectPos = this.GetGraphicalLineEnd((this.pos <= this.selectPos) ? this.selectPos : this.pos)); + this.UpdateScrollOffset(); + } + public void MoveTextStart() + { + this.selectPos = (this.pos = 0); + this.UpdateScrollOffset(); + } + public void MoveTextEnd() + { + this.selectPos = (this.pos = this.content.text.Length); + this.UpdateScrollOffset(); + } + public void MoveParagraphForward() + { + this.pos = ((this.pos <= this.selectPos) ? this.selectPos : this.pos); + if (this.pos < this.content.text.Length) + { + this.selectPos = (this.pos = this.content.text.IndexOf('\n', this.pos + 1)); + if (this.pos == -1) + { + this.selectPos = (this.pos = this.content.text.Length); + } + } + this.UpdateScrollOffset(); + } + public void MoveParagraphBackward() + { + this.pos = ((this.pos >= this.selectPos) ? this.selectPos : this.pos); + if (this.pos > 1) + { + this.selectPos = (this.pos = this.content.text.LastIndexOf('\n', this.pos - 2) + 1); + } + else + { + this.selectPos = (this.pos = 0); + } + this.UpdateScrollOffset(); + } + public void MoveCursorToPosition(Vector2 cursorPosition) + { + this.selectPos = this.style.GetCursorStringIndex(this.position, this.content, cursorPosition + this.scrollOffset); + if (!Event.current.shift) + { + this.pos = this.selectPos; + } + this.ClampPos(); + this.UpdateScrollOffset(); + } + public void MoveAltCursorToPosition(Vector2 cursorPosition) + { + this.m_iAltCursorPos = this.style.GetCursorStringIndex(this.position, this.content, cursorPosition + this.scrollOffset); + this.ClampPos(); + this.UpdateScrollOffset(); + } + public bool IsOverSelection(Vector2 cursorPosition) + { + int cursorStringIndex = this.style.GetCursorStringIndex(this.position, this.content, cursorPosition + this.scrollOffset); + return cursorStringIndex < Mathf.Max(this.pos, this.selectPos) && cursorStringIndex > Mathf.Min(this.pos, this.selectPos); + } + public void SelectToPosition(Vector2 cursorPosition) + { + if (!this.m_MouseDragSelectsWholeWords) + { + this.pos = this.style.GetCursorStringIndex(this.position, this.content, cursorPosition + this.scrollOffset); + } + else + { + int num = this.style.GetCursorStringIndex(this.position, this.content, cursorPosition + this.scrollOffset); + if (this.m_DblClickSnap == TextEditor.DblClickSnapping.WORDS) + { + if (num < this.m_DblClickInitPos) + { + this.pos = this.FindEndOfClassification(num, -1); + this.selectPos = this.FindEndOfClassification(this.m_DblClickInitPos, 1); + } + else + { + if (num >= this.content.text.Length) + { + num = this.content.text.Length - 1; + } + this.pos = this.FindEndOfClassification(num, 1); + this.selectPos = this.FindEndOfClassification(this.m_DblClickInitPos - 1, -1); + } + } + else + { + if (num < this.m_DblClickInitPos) + { + if (num > 0) + { + this.pos = this.content.text.LastIndexOf('\n', num - 2) + 1; + } + else + { + this.pos = 0; + } + this.selectPos = this.content.text.LastIndexOf('\n', this.m_DblClickInitPos); + } + else + { + if (num < this.content.text.Length) + { + this.pos = this.content.text.IndexOf('\n', num + 1) + 1; + if (this.pos <= 0) + { + this.pos = this.content.text.Length; + } + } + else + { + this.pos = this.content.text.Length; + } + this.selectPos = this.content.text.LastIndexOf('\n', this.m_DblClickInitPos - 2) + 1; + } + } + } + this.UpdateScrollOffset(); + } + public void SelectLeft() + { + if (this.m_bJustSelected && this.pos > this.selectPos) + { + int num = this.pos; + this.pos = this.selectPos; + this.selectPos = num; + } + this.m_bJustSelected = false; + this.pos--; + if (this.pos < 0) + { + this.pos = 0; + } + this.UpdateScrollOffset(); + } + public void SelectRight() + { + if (this.m_bJustSelected && this.pos < this.selectPos) + { + int num = this.pos; + this.pos = this.selectPos; + this.selectPos = num; + } + this.m_bJustSelected = false; + this.pos++; + int length = this.content.text.Length; + if (this.pos > length) + { + this.pos = length; + } + this.UpdateScrollOffset(); + } + public void SelectUp() + { + this.GrabGraphicalCursorPos(); + this.graphicalCursorPos.y = this.graphicalCursorPos.y - 1f; + this.pos = this.style.GetCursorStringIndex(this.position, this.content, this.graphicalCursorPos); + this.UpdateScrollOffset(); + } + public void SelectDown() + { + this.GrabGraphicalCursorPos(); + this.graphicalCursorPos.y = this.graphicalCursorPos.y + (this.style.lineHeight + 5f); + this.pos = this.style.GetCursorStringIndex(this.position, this.content, this.graphicalCursorPos); + this.UpdateScrollOffset(); + } + public void SelectTextEnd() + { + this.pos = this.content.text.Length; + this.UpdateScrollOffset(); + } + public void SelectTextStart() + { + this.pos = 0; + this.UpdateScrollOffset(); + } + public void MouseDragSelectsWholeWords(bool on) + { + this.m_MouseDragSelectsWholeWords = on; + this.m_DblClickInitPos = this.pos; + } + public void DblClickSnap(TextEditor.DblClickSnapping snapping) + { + this.m_DblClickSnap = snapping; + } + private int GetGraphicalLineStart(int p) + { + Vector2 cursorPixelPosition = this.style.GetCursorPixelPosition(this.position, this.content, p); + cursorPixelPosition.x = 0f; + return this.style.GetCursorStringIndex(this.position, this.content, cursorPixelPosition); + } + private int GetGraphicalLineEnd(int p) + { + Vector2 cursorPixelPosition = this.style.GetCursorPixelPosition(this.position, this.content, p); + cursorPixelPosition.x += 5000f; + return this.style.GetCursorStringIndex(this.position, this.content, cursorPixelPosition); + } + private int FindNextSeperator(int startPos) + { + int length = this.content.text.Length; + while (startPos < length && !TextEditor.isLetterLikeChar(this.content.text[startPos])) + { + startPos++; + } + while (startPos < length && TextEditor.isLetterLikeChar(this.content.text[startPos])) + { + startPos++; + } + return startPos; + } + private static bool isLetterLikeChar(char c) + { + return char.IsLetterOrDigit(c) || c == '\''; + } + private int FindPrevSeperator(int startPos) + { + startPos--; + while (startPos > 0 && !TextEditor.isLetterLikeChar(this.content.text[startPos])) + { + startPos--; + } + while (startPos >= 0 && TextEditor.isLetterLikeChar(this.content.text[startPos])) + { + startPos--; + } + return startPos + 1; + } + public void MoveWordRight() + { + this.pos = ((this.pos <= this.selectPos) ? this.selectPos : this.pos); + this.pos = (this.selectPos = this.FindNextSeperator(this.pos)); + this.ClearCursorPos(); + this.UpdateScrollOffset(); + } + public void MoveToStartOfNextWord() + { + this.ClearCursorPos(); + if (this.pos != this.selectPos) + { + this.MoveRight(); + return; + } + this.pos = (this.selectPos = this.FindStartOfNextWord(this.pos)); + this.UpdateScrollOffset(); + } + public void MoveToEndOfPreviousWord() + { + this.ClearCursorPos(); + if (this.pos != this.selectPos) + { + this.MoveLeft(); + return; + } + this.pos = (this.selectPos = this.FindEndOfPreviousWord(this.pos)); + this.UpdateScrollOffset(); + } + public void SelectToStartOfNextWord() + { + this.ClearCursorPos(); + this.pos = this.FindStartOfNextWord(this.pos); + this.UpdateScrollOffset(); + } + public void SelectToEndOfPreviousWord() + { + this.ClearCursorPos(); + this.pos = this.FindEndOfPreviousWord(this.pos); + this.UpdateScrollOffset(); + } + private TextEditor.CharacterType ClassifyChar(char c) + { + if (char.IsWhiteSpace(c)) + { + return TextEditor.CharacterType.WhiteSpace; + } + if (char.IsLetterOrDigit(c) || c == '\'') + { + return TextEditor.CharacterType.LetterLike; + } + return TextEditor.CharacterType.Symbol; + } + public int FindStartOfNextWord(int p) + { + int length = this.content.text.Length; + if (p == length) + { + return p; + } + char c = this.content.text[p]; + TextEditor.CharacterType characterType = this.ClassifyChar(c); + if (characterType != TextEditor.CharacterType.WhiteSpace) + { + p++; + while (p < length && this.ClassifyChar(this.content.text[p]) == characterType) + { + p++; + } + } + else + { + if (c == '\t' || c == '\n') + { + return p + 1; + } + } + if (p == length) + { + return p; + } + c = this.content.text[p]; + if (c == ' ') + { + while (p < length && char.IsWhiteSpace(this.content.text[p])) + { + p++; + } + } + else + { + if (c == '\t' || c == '\n') + { + return p; + } + } + return p; + } + private int FindEndOfPreviousWord(int p) + { + if (p == 0) + { + return p; + } + p--; + while (p > 0 && this.content.text[p] == ' ') + { + p--; + } + TextEditor.CharacterType characterType = this.ClassifyChar(this.content.text[p]); + if (characterType != TextEditor.CharacterType.WhiteSpace) + { + while (p > 0 && this.ClassifyChar(this.content.text[p - 1]) == characterType) + { + p--; + } + } + return p; + } + public void MoveWordLeft() + { + this.pos = ((this.pos >= this.selectPos) ? this.selectPos : this.pos); + this.pos = this.FindPrevSeperator(this.pos); + this.selectPos = this.pos; + this.UpdateScrollOffset(); + } + public void SelectWordRight() + { + this.ClearCursorPos(); + int num = this.selectPos; + if (this.pos < this.selectPos) + { + this.selectPos = this.pos; + this.MoveWordRight(); + this.selectPos = num; + this.pos = ((this.pos >= this.selectPos) ? this.selectPos : this.pos); + return; + } + this.selectPos = this.pos; + this.MoveWordRight(); + this.selectPos = num; + this.UpdateScrollOffset(); + } + public void SelectWordLeft() + { + this.ClearCursorPos(); + int num = this.selectPos; + if (this.pos > this.selectPos) + { + this.selectPos = this.pos; + this.MoveWordLeft(); + this.selectPos = num; + this.pos = ((this.pos <= this.selectPos) ? this.selectPos : this.pos); + return; + } + this.selectPos = this.pos; + this.MoveWordLeft(); + this.selectPos = num; + this.UpdateScrollOffset(); + } + public void ExpandSelectGraphicalLineStart() + { + this.ClearCursorPos(); + if (this.pos < this.selectPos) + { + this.pos = this.GetGraphicalLineStart(this.pos); + } + else + { + int num = this.pos; + this.pos = this.GetGraphicalLineStart(this.selectPos); + this.selectPos = num; + } + this.UpdateScrollOffset(); + } + public void ExpandSelectGraphicalLineEnd() + { + this.ClearCursorPos(); + if (this.pos > this.selectPos) + { + this.pos = this.GetGraphicalLineEnd(this.pos); + } + else + { + int num = this.pos; + this.pos = this.GetGraphicalLineEnd(this.selectPos); + this.selectPos = num; + } + this.UpdateScrollOffset(); + } + public void SelectGraphicalLineStart() + { + this.ClearCursorPos(); + this.pos = this.GetGraphicalLineStart(this.pos); + this.UpdateScrollOffset(); + } + public void SelectGraphicalLineEnd() + { + this.ClearCursorPos(); + this.pos = this.GetGraphicalLineEnd(this.pos); + this.UpdateScrollOffset(); + } + public void SelectParagraphForward() + { + this.ClearCursorPos(); + bool flag = this.pos < this.selectPos; + if (this.pos < this.content.text.Length) + { + this.pos = this.content.text.IndexOf('\n', this.pos + 1); + if (this.pos == -1) + { + this.pos = this.content.text.Length; + } + if (flag && this.pos > this.selectPos) + { + this.pos = this.selectPos; + } + } + this.UpdateScrollOffset(); + } + public void SelectParagraphBackward() + { + this.ClearCursorPos(); + bool flag = this.pos > this.selectPos; + if (this.pos > 1) + { + this.pos = this.content.text.LastIndexOf('\n', this.pos - 2) + 1; + if (flag && this.pos < this.selectPos) + { + this.pos = this.selectPos; + } + } + else + { + this.selectPos = (this.pos = 0); + } + this.UpdateScrollOffset(); + } + public void SelectCurrentWord() + { + this.ClearCursorPos(); + int length = this.content.text.Length; + this.selectPos = this.pos; + if (length == 0) + { + return; + } + if (this.pos >= length) + { + this.pos = length - 1; + } + if (this.selectPos >= length) + { + this.selectPos--; + } + if (this.pos < this.selectPos) + { + this.pos = this.FindEndOfClassification(this.pos, -1); + this.selectPos = this.FindEndOfClassification(this.selectPos, 1); + } + else + { + this.pos = this.FindEndOfClassification(this.pos, 1); + this.selectPos = this.FindEndOfClassification(this.selectPos, -1); + } + this.m_bJustSelected = true; + this.UpdateScrollOffset(); + } + private int FindEndOfClassification(int p, int dir) + { + int length = this.content.text.Length; + if (p >= length || p < 0) + { + return p; + } + TextEditor.CharacterType characterType = this.ClassifyChar(this.content.text[p]); + while (true) + { + p += dir; + if (p < 0) + { + break; + } + if (p >= length) + { + return length; + } + if (this.ClassifyChar(this.content.text[p]) != characterType) + { + goto Block_4; + } + } + return 0; + Block_4: + if (dir == 1) + { + return p; + } + return p + 1; + } + public void SelectCurrentParagraph() + { + this.ClearCursorPos(); + int length = this.content.text.Length; + if (this.pos < length) + { + this.pos = this.content.text.IndexOf('\n', this.pos); + if (this.pos == -1) + { + this.pos = this.content.text.Length; + } + else + { + this.pos++; + } + } + if (this.selectPos != 0) + { + this.selectPos = this.content.text.LastIndexOf('\n', this.selectPos - 1) + 1; + } + this.UpdateScrollOffset(); + } + public void UpdateScrollOffsetIfNeeded() + { + if (this.m_TextHeightPotentiallyChanged) + { + this.UpdateScrollOffset(); + this.m_TextHeightPotentiallyChanged = false; + } + } + private void UpdateScrollOffset() + { + int cursorStringIndex = this.pos; + this.graphicalCursorPos = this.style.GetCursorPixelPosition(new Rect(0f, 0f, this.position.width, this.position.height), this.content, cursorStringIndex); + Rect rect = this.style.padding.Remove(this.position); + Vector2 vector = new Vector2(this.style.CalcSize(this.content).x, this.style.CalcHeight(this.content, this.position.width)); + if (vector.x < this.position.width) + { + this.scrollOffset.x = 0f; + } + else + { + if (this.graphicalCursorPos.x + 1f > this.scrollOffset.x + rect.width) + { + this.scrollOffset.x = this.graphicalCursorPos.x - rect.width; + } + if (this.graphicalCursorPos.x < this.scrollOffset.x + (float)this.style.padding.left) + { + this.scrollOffset.x = this.graphicalCursorPos.x - (float)this.style.padding.left; + } + } + if (vector.y < rect.height) + { + this.scrollOffset.y = 0f; + } + else + { + if (this.graphicalCursorPos.y + this.style.lineHeight > this.scrollOffset.y + rect.height + (float)this.style.padding.top) + { + this.scrollOffset.y = this.graphicalCursorPos.y - rect.height - (float)this.style.padding.top + this.style.lineHeight; + } + if (this.graphicalCursorPos.y < this.scrollOffset.y + (float)this.style.padding.top) + { + this.scrollOffset.y = this.graphicalCursorPos.y - (float)this.style.padding.top; + } + } + if (this.scrollOffset.y > 0f && vector.y - this.scrollOffset.y < rect.height) + { + this.scrollOffset.y = vector.y - rect.height - (float)this.style.padding.top - (float)this.style.padding.bottom; + } + this.scrollOffset.y = ((this.scrollOffset.y >= 0f) ? this.scrollOffset.y : 0f); + } + public void DrawCursor(string text) + { + string text2 = this.content.text; + int num = this.pos; + if (Input.compositionString.Length > 0) + { + this.content.text = text.Substring(0, this.pos) + Input.compositionString + text.Substring(this.selectPos); + num += Input.compositionString.Length; + } + else + { + this.content.text = text; + } + this.graphicalCursorPos = this.style.GetCursorPixelPosition(new Rect(0f, 0f, this.position.width, this.position.height), this.content, num); + this.UpdateScrollOffset(); + Vector2 contentOffset = this.style.contentOffset; + this.style.contentOffset -= this.scrollOffset; + this.style.Internal_clipOffset = this.scrollOffset; + Input.compositionCursorPos = this.graphicalCursorPos + new Vector2(this.position.x, this.position.y + this.style.lineHeight) - this.scrollOffset; + if (Input.compositionString.Length > 0) + { + this.style.DrawWithTextSelection(this.position, this.content, this.controlID, this.pos, this.pos + Input.compositionString.Length, true); + } + else + { + this.style.DrawWithTextSelection(this.position, this.content, this.controlID, this.pos, this.selectPos); + } + if (this.m_iAltCursorPos != -1) + { + this.style.DrawCursor(this.position, this.content, this.controlID, this.m_iAltCursorPos); + } + this.style.contentOffset = contentOffset; + this.style.Internal_clipOffset = Vector2.zero; + this.content.text = text2; + } + private bool PerformOperation(TextEditor.TextEditOp operation) + { + switch (operation) + { + case TextEditor.TextEditOp.MoveLeft: + this.MoveLeft(); + return false; + case TextEditor.TextEditOp.MoveRight: + this.MoveRight(); + return false; + case TextEditor.TextEditOp.MoveUp: + this.MoveUp(); + return false; + case TextEditor.TextEditOp.MoveDown: + this.MoveDown(); + return false; + case TextEditor.TextEditOp.MoveLineStart: + this.MoveLineStart(); + return false; + case TextEditor.TextEditOp.MoveLineEnd: + this.MoveLineEnd(); + return false; + case TextEditor.TextEditOp.MoveTextStart: + this.MoveTextStart(); + return false; + case TextEditor.TextEditOp.MoveTextEnd: + this.MoveTextEnd(); + return false; + case TextEditor.TextEditOp.MoveGraphicalLineStart: + this.MoveGraphicalLineStart(); + return false; + case TextEditor.TextEditOp.MoveGraphicalLineEnd: + this.MoveGraphicalLineEnd(); + return false; + case TextEditor.TextEditOp.MoveWordLeft: + this.MoveWordLeft(); + return false; + case TextEditor.TextEditOp.MoveWordRight: + this.MoveWordRight(); + return false; + case TextEditor.TextEditOp.MoveParagraphForward: + this.MoveParagraphForward(); + return false; + case TextEditor.TextEditOp.MoveParagraphBackward: + this.MoveParagraphBackward(); + return false; + case TextEditor.TextEditOp.MoveToStartOfNextWord: + this.MoveToStartOfNextWord(); + return false; + case TextEditor.TextEditOp.MoveToEndOfPreviousWord: + this.MoveToEndOfPreviousWord(); + return false; + case TextEditor.TextEditOp.SelectLeft: + this.SelectLeft(); + return false; + case TextEditor.TextEditOp.SelectRight: + this.SelectRight(); + return false; + case TextEditor.TextEditOp.SelectUp: + this.SelectUp(); + return false; + case TextEditor.TextEditOp.SelectDown: + this.SelectDown(); + return false; + case TextEditor.TextEditOp.SelectTextStart: + this.SelectTextStart(); + return false; + case TextEditor.TextEditOp.SelectTextEnd: + this.SelectTextEnd(); + return false; + case TextEditor.TextEditOp.ExpandSelectGraphicalLineStart: + this.ExpandSelectGraphicalLineStart(); + return false; + case TextEditor.TextEditOp.ExpandSelectGraphicalLineEnd: + this.ExpandSelectGraphicalLineEnd(); + return false; + case TextEditor.TextEditOp.SelectGraphicalLineStart: + this.SelectGraphicalLineStart(); + return false; + case TextEditor.TextEditOp.SelectGraphicalLineEnd: + this.SelectGraphicalLineEnd(); + return false; + case TextEditor.TextEditOp.SelectWordLeft: + this.SelectWordLeft(); + return false; + case TextEditor.TextEditOp.SelectWordRight: + this.SelectWordRight(); + return false; + case TextEditor.TextEditOp.SelectToEndOfPreviousWord: + this.SelectToEndOfPreviousWord(); + return false; + case TextEditor.TextEditOp.SelectToStartOfNextWord: + this.SelectToStartOfNextWord(); + return false; + case TextEditor.TextEditOp.SelectParagraphBackward: + this.SelectParagraphBackward(); + return false; + case TextEditor.TextEditOp.SelectParagraphForward: + this.SelectParagraphForward(); + return false; + case TextEditor.TextEditOp.Delete: + return this.Delete(); + case TextEditor.TextEditOp.Backspace: + return this.Backspace(); + case TextEditor.TextEditOp.DeleteWordBack: + return this.DeleteWordBack(); + case TextEditor.TextEditOp.DeleteWordForward: + return this.DeleteWordForward(); + case TextEditor.TextEditOp.DeleteLineBack: + return this.DeleteLineBack(); + case TextEditor.TextEditOp.Cut: + return this.Cut(); + case TextEditor.TextEditOp.Copy: + this.Copy(); + return false; + case TextEditor.TextEditOp.Paste: + return this.Paste(); + case TextEditor.TextEditOp.SelectAll: + this.SelectAll(); + return false; + case TextEditor.TextEditOp.SelectNone: + this.SelectNone(); + return false; + } + Debug.Log("Unimplemented: " + operation); + return false; + } + public void SaveBackup() + { + this.oldText = this.content.text; + this.oldPos = this.pos; + this.oldSelectPos = this.selectPos; + } + public void Undo() + { + this.content.text = this.oldText; + this.pos = this.oldPos; + this.selectPos = this.oldSelectPos; + this.UpdateScrollOffset(); + } + public bool Cut() + { + if (this.isPasswordField) + { + return false; + } + this.Copy(); + return this.DeleteSelection(); + } + public void Copy() + { + if (this.selectPos == this.pos) + { + return; + } + if (this.isPasswordField) + { + return; + } + string systemCopyBuffer; + if (this.pos < this.selectPos) + { + systemCopyBuffer = this.content.text.Substring(this.pos, this.selectPos - this.pos); + } + else + { + systemCopyBuffer = this.content.text.Substring(this.selectPos, this.pos - this.selectPos); + } + GUIUtility.systemCopyBuffer = systemCopyBuffer; + } + public bool Paste() + { + string systemCopyBuffer = GUIUtility.systemCopyBuffer; + if (systemCopyBuffer != string.Empty) + { + this.ReplaceSelection(systemCopyBuffer); + return true; + } + return false; + } + private static void MapKey(string key, TextEditor.TextEditOp action) + { + TextEditor.s_Keyactions[Event.KeyboardEvent(key)] = action; + } + private void InitKeyActions() + { + if (TextEditor.s_Keyactions != null) + { + return; + } + TextEditor.s_Keyactions = new Dictionary(); + TextEditor.MapKey("left", TextEditor.TextEditOp.MoveLeft); + TextEditor.MapKey("right", TextEditor.TextEditOp.MoveRight); + TextEditor.MapKey("up", TextEditor.TextEditOp.MoveUp); + TextEditor.MapKey("down", TextEditor.TextEditOp.MoveDown); + TextEditor.MapKey("#left", TextEditor.TextEditOp.SelectLeft); + TextEditor.MapKey("#right", TextEditor.TextEditOp.SelectRight); + TextEditor.MapKey("#up", TextEditor.TextEditOp.SelectUp); + TextEditor.MapKey("#down", TextEditor.TextEditOp.SelectDown); + TextEditor.MapKey("delete", TextEditor.TextEditOp.Delete); + TextEditor.MapKey("backspace", TextEditor.TextEditOp.Backspace); + TextEditor.MapKey("#backspace", TextEditor.TextEditOp.Backspace); + if (Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXWebPlayer || Application.platform == RuntimePlatform.OSXDashboardPlayer || Application.platform == RuntimePlatform.OSXEditor) + { + TextEditor.MapKey("^left", TextEditor.TextEditOp.MoveGraphicalLineStart); + TextEditor.MapKey("^right", TextEditor.TextEditOp.MoveGraphicalLineEnd); + TextEditor.MapKey("&left", TextEditor.TextEditOp.MoveWordLeft); + TextEditor.MapKey("&right", TextEditor.TextEditOp.MoveWordRight); + TextEditor.MapKey("&up", TextEditor.TextEditOp.MoveParagraphBackward); + TextEditor.MapKey("&down", TextEditor.TextEditOp.MoveParagraphForward); + TextEditor.MapKey("%left", TextEditor.TextEditOp.MoveGraphicalLineStart); + TextEditor.MapKey("%right", TextEditor.TextEditOp.MoveGraphicalLineEnd); + TextEditor.MapKey("%up", TextEditor.TextEditOp.MoveTextStart); + TextEditor.MapKey("%down", TextEditor.TextEditOp.MoveTextEnd); + TextEditor.MapKey("#home", TextEditor.TextEditOp.SelectTextStart); + TextEditor.MapKey("#end", TextEditor.TextEditOp.SelectTextEnd); + TextEditor.MapKey("#^left", TextEditor.TextEditOp.ExpandSelectGraphicalLineStart); + TextEditor.MapKey("#^right", TextEditor.TextEditOp.ExpandSelectGraphicalLineEnd); + TextEditor.MapKey("#^up", TextEditor.TextEditOp.SelectParagraphBackward); + TextEditor.MapKey("#^down", TextEditor.TextEditOp.SelectParagraphForward); + TextEditor.MapKey("#&left", TextEditor.TextEditOp.SelectWordLeft); + TextEditor.MapKey("#&right", TextEditor.TextEditOp.SelectWordRight); + TextEditor.MapKey("#&up", TextEditor.TextEditOp.SelectParagraphBackward); + TextEditor.MapKey("#&down", TextEditor.TextEditOp.SelectParagraphForward); + TextEditor.MapKey("#%left", TextEditor.TextEditOp.ExpandSelectGraphicalLineStart); + TextEditor.MapKey("#%right", TextEditor.TextEditOp.ExpandSelectGraphicalLineEnd); + TextEditor.MapKey("#%up", TextEditor.TextEditOp.SelectTextStart); + TextEditor.MapKey("#%down", TextEditor.TextEditOp.SelectTextEnd); + TextEditor.MapKey("%a", TextEditor.TextEditOp.SelectAll); + TextEditor.MapKey("%x", TextEditor.TextEditOp.Cut); + TextEditor.MapKey("%c", TextEditor.TextEditOp.Copy); + TextEditor.MapKey("%v", TextEditor.TextEditOp.Paste); + TextEditor.MapKey("^d", TextEditor.TextEditOp.Delete); + TextEditor.MapKey("^h", TextEditor.TextEditOp.Backspace); + TextEditor.MapKey("^b", TextEditor.TextEditOp.MoveLeft); + TextEditor.MapKey("^f", TextEditor.TextEditOp.MoveRight); + TextEditor.MapKey("^a", TextEditor.TextEditOp.MoveLineStart); + TextEditor.MapKey("^e", TextEditor.TextEditOp.MoveLineEnd); + TextEditor.MapKey("&delete", TextEditor.TextEditOp.DeleteWordForward); + TextEditor.MapKey("&backspace", TextEditor.TextEditOp.DeleteWordBack); + TextEditor.MapKey("%backspace", TextEditor.TextEditOp.DeleteLineBack); + } + else + { + TextEditor.MapKey("home", TextEditor.TextEditOp.MoveGraphicalLineStart); + TextEditor.MapKey("end", TextEditor.TextEditOp.MoveGraphicalLineEnd); + TextEditor.MapKey("%left", TextEditor.TextEditOp.MoveWordLeft); + TextEditor.MapKey("%right", TextEditor.TextEditOp.MoveWordRight); + TextEditor.MapKey("%up", TextEditor.TextEditOp.MoveParagraphBackward); + TextEditor.MapKey("%down", TextEditor.TextEditOp.MoveParagraphForward); + TextEditor.MapKey("^left", TextEditor.TextEditOp.MoveToEndOfPreviousWord); + TextEditor.MapKey("^right", TextEditor.TextEditOp.MoveToStartOfNextWord); + TextEditor.MapKey("^up", TextEditor.TextEditOp.MoveParagraphBackward); + TextEditor.MapKey("^down", TextEditor.TextEditOp.MoveParagraphForward); + TextEditor.MapKey("#^left", TextEditor.TextEditOp.SelectToEndOfPreviousWord); + TextEditor.MapKey("#^right", TextEditor.TextEditOp.SelectToStartOfNextWord); + TextEditor.MapKey("#^up", TextEditor.TextEditOp.SelectParagraphBackward); + TextEditor.MapKey("#^down", TextEditor.TextEditOp.SelectParagraphForward); + TextEditor.MapKey("#home", TextEditor.TextEditOp.SelectGraphicalLineStart); + TextEditor.MapKey("#end", TextEditor.TextEditOp.SelectGraphicalLineEnd); + TextEditor.MapKey("^delete", TextEditor.TextEditOp.DeleteWordForward); + TextEditor.MapKey("^backspace", TextEditor.TextEditOp.DeleteWordBack); + TextEditor.MapKey("%backspace", TextEditor.TextEditOp.DeleteLineBack); + TextEditor.MapKey("^a", TextEditor.TextEditOp.SelectAll); + TextEditor.MapKey("^x", TextEditor.TextEditOp.Cut); + TextEditor.MapKey("^c", TextEditor.TextEditOp.Copy); + TextEditor.MapKey("^v", TextEditor.TextEditOp.Paste); + TextEditor.MapKey("#delete", TextEditor.TextEditOp.Cut); + TextEditor.MapKey("^insert", TextEditor.TextEditOp.Copy); + TextEditor.MapKey("#insert", TextEditor.TextEditOp.Paste); + } + } + public void ClampPos() + { + if (this.m_HasFocus && this.controlID != GUIUtility.keyboardControl) + { + this.OnLostFocus(); + } + if (!this.m_HasFocus && this.controlID == GUIUtility.keyboardControl) + { + this.OnFocus(); + } + if (this.pos < 0) + { + this.pos = 0; + } + else + { + if (this.pos > this.content.text.Length) + { + this.pos = this.content.text.Length; + } + } + if (this.selectPos < 0) + { + this.selectPos = 0; + } + else + { + if (this.selectPos > this.content.text.Length) + { + this.selectPos = this.content.text.Length; + } + } + if (this.m_iAltCursorPos > this.content.text.Length) + { + this.m_iAltCursorPos = this.content.text.Length; + } + } + } +} diff --git a/UnityEngine/UnityEngine/TextGenerationSettings.cs b/UnityEngine/UnityEngine/TextGenerationSettings.cs new file mode 100644 index 00000000..e8c07d38 --- /dev/null +++ b/UnityEngine/UnityEngine/TextGenerationSettings.cs @@ -0,0 +1,37 @@ +using System; +namespace UnityEngine +{ + public struct TextGenerationSettings + { + public Font font; + public Color color; + public int fontSize; + public float lineSpacing; + public bool richText; + public FontStyle fontStyle; + public TextAnchor textAnchor; + public bool resizeTextForBestFit; + public int resizeTextMinSize; + public int resizeTextMaxSize; + public bool updateBounds; + public VerticalWrapMode verticalOverflow; + public HorizontalWrapMode horizontalOverflow; + public Vector2 generationExtents; + public Vector2 pivot; + public bool generateOutOfBounds; + private bool CompareColors(Color left, Color right) + { + Color32 color = left; + Color32 color2 = right; + return color.Equals(color2); + } + private bool CompareVector2(Vector2 left, Vector2 right) + { + return Mathf.Approximately(left.x, right.x) && Mathf.Approximately(left.y, right.y); + } + public bool Equals(TextGenerationSettings other) + { + return this.CompareColors(this.color, other.color) && this.fontSize == other.fontSize && this.resizeTextMinSize == other.resizeTextMinSize && this.resizeTextMaxSize == other.resizeTextMaxSize && Mathf.Approximately(this.lineSpacing, other.lineSpacing) && this.fontStyle == other.fontStyle && this.richText == other.richText && this.textAnchor == other.textAnchor && this.resizeTextForBestFit == other.resizeTextForBestFit && this.resizeTextMinSize == other.resizeTextMinSize && this.resizeTextMaxSize == other.resizeTextMaxSize && this.resizeTextForBestFit == other.resizeTextForBestFit && this.updateBounds == other.updateBounds && this.horizontalOverflow == other.horizontalOverflow && this.verticalOverflow == other.verticalOverflow && this.CompareVector2(this.generationExtents, other.generationExtents) && this.CompareVector2(this.pivot, other.pivot) && this.font == other.font; + } + } +} diff --git a/UnityEngine/UnityEngine/TextGenerator.cs b/UnityEngine/UnityEngine/TextGenerator.cs new file mode 100644 index 00000000..20a31cb5 --- /dev/null +++ b/UnityEngine/UnityEngine/TextGenerator.cs @@ -0,0 +1,263 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class TextGenerator : IDisposable + { + internal IntPtr m_Ptr; + private string m_LastString; + private TextGenerationSettings m_LastSettings; + private bool m_HasGenerated; + private bool m_LastValid; + private readonly List m_Verts; + private readonly List m_Characters; + private readonly List m_Lines; + private bool m_CachedVerts; + private bool m_CachedCharacters; + private bool m_CachedLines; + private static int s_NextId = 0; + private int m_Id; + private static readonly Dictionary s_Instances = new Dictionary(); + public IList verts + { + get + { + if (!this.m_CachedVerts) + { + this.GetVertices(this.m_Verts); + this.m_CachedVerts = true; + } + return this.m_Verts; + } + } + public IList characters + { + get + { + if (!this.m_CachedCharacters) + { + this.GetCharacters(this.m_Characters); + this.m_CachedCharacters = true; + } + return this.m_Characters; + } + } + public IList lines + { + get + { + if (!this.m_CachedLines) + { + this.GetLines(this.m_Lines); + this.m_CachedLines = true; + } + return this.m_Lines; + } + } + public extern Rect rectExtents + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int vertexCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int characterCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public int characterCountVisible + { + get + { + return (!string.IsNullOrEmpty(this.m_LastString)) ? Mathf.Min(this.m_LastString.Length, Mathf.Max(0, (this.vertexCount - 4) / 4)) : 0; + } + } + public extern int lineCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int fontSizeUsedForBestFit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public TextGenerator() : this(50) + { + } + public TextGenerator(int initialCapacity) + { + this.m_Verts = new List((initialCapacity + 1) * 4); + this.m_Characters = new List(initialCapacity + 1); + this.m_Lines = new List(20); + this.Init(); + Dictionary obj = TextGenerator.s_Instances; + Monitor.Enter(obj); + try + { + this.m_Id = TextGenerator.s_NextId++; + TextGenerator.s_Instances.Add(this.m_Id, new WeakReference(this)); + } + finally + { + Monitor.Exit(obj); + } + } + void IDisposable.Dispose() + { + Dictionary obj = TextGenerator.s_Instances; + Monitor.Enter(obj); + try + { + TextGenerator.s_Instances.Remove(this.m_Id); + } + finally + { + Monitor.Exit(obj); + } + this.Dispose_cpp(); + } + ~TextGenerator() + { + ((IDisposable)this).Dispose(); + } + internal static void InvalidateAll() + { + Dictionary obj = TextGenerator.s_Instances; + Monitor.Enter(obj); + try + { + foreach (KeyValuePair current in TextGenerator.s_Instances) + { + WeakReference value = current.Value; + if (value.IsAlive) + { + (value.Target as TextGenerator).Invalidate(); + } + } + } + finally + { + Monitor.Exit(obj); + } + } + private TextGenerationSettings ValidatedSettings(TextGenerationSettings settings) + { + if (settings.font != null && settings.font.dynamic) + { + return settings; + } + if (settings.fontSize != 0 || settings.fontStyle != FontStyle.Normal) + { + Debug.LogWarning("Font size and style overrides are only supported for dynamic fonts."); + settings.fontSize = 0; + settings.fontStyle = FontStyle.Normal; + } + if (settings.resizeTextForBestFit) + { + Debug.LogWarning("BestFit is only suppoerted for dynamic fonts."); + settings.resizeTextForBestFit = false; + } + return settings; + } + public void Invalidate() + { + this.m_HasGenerated = false; + } + public void GetCharacters(List characters) + { + this.GetCharactersInternal(characters); + } + public void GetLines(List lines) + { + this.GetLinesInternal(lines); + } + public void GetVertices(List vertices) + { + this.GetVerticesInternal(vertices); + } + public float GetPreferredWidth(string str, TextGenerationSettings settings) + { + settings.horizontalOverflow = HorizontalWrapMode.Overflow; + settings.verticalOverflow = VerticalWrapMode.Overflow; + settings.updateBounds = true; + this.Populate(str, settings); + return this.rectExtents.width; + } + public float GetPreferredHeight(string str, TextGenerationSettings settings) + { + settings.verticalOverflow = VerticalWrapMode.Overflow; + settings.updateBounds = true; + this.Populate(str, settings); + return this.rectExtents.height; + } + public bool Populate(string str, TextGenerationSettings settings) + { + if (this.m_HasGenerated && str == this.m_LastString && settings.Equals(this.m_LastSettings)) + { + return this.m_LastValid; + } + return this.PopulateAlways(str, settings); + } + private bool PopulateAlways(string str, TextGenerationSettings settings) + { + this.m_LastString = str; + this.m_HasGenerated = true; + this.m_CachedVerts = false; + this.m_CachedCharacters = false; + this.m_CachedLines = false; + this.m_LastSettings = settings; + TextGenerationSettings textGenerationSettings = this.ValidatedSettings(settings); + this.m_LastValid = this.Populate_Internal(str, textGenerationSettings.font, textGenerationSettings.color, textGenerationSettings.fontSize, textGenerationSettings.lineSpacing, textGenerationSettings.fontStyle, textGenerationSettings.richText, textGenerationSettings.resizeTextForBestFit, textGenerationSettings.resizeTextMinSize, textGenerationSettings.resizeTextMaxSize, textGenerationSettings.verticalOverflow, textGenerationSettings.horizontalOverflow, textGenerationSettings.updateBounds, textGenerationSettings.textAnchor, textGenerationSettings.generationExtents, textGenerationSettings.pivot, textGenerationSettings.generateOutOfBounds); + return this.m_LastValid; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Dispose_cpp(); + internal bool Populate_Internal(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, VerticalWrapMode verticalOverFlow, HorizontalWrapMode horizontalOverflow, bool updateBounds, TextAnchor anchor, Vector2 extents, Vector2 pivot, bool generateOutOfBounds) + { + return this.Populate_Internal_cpp(str, font, color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, (int)verticalOverFlow, (int)horizontalOverflow, updateBounds, anchor, extents.x, extents.y, pivot.x, pivot.y, generateOutOfBounds); + } + internal bool Populate_Internal_cpp(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds) + { + return TextGenerator.INTERNAL_CALL_Populate_Internal_cpp(this, str, font, ref color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, verticalOverFlow, horizontalOverflow, updateBounds, anchor, extentsX, extentsY, pivotX, pivotY, generateOutOfBounds); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Populate_Internal_cpp(TextGenerator self, string str, Font font, ref Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetVerticesInternal(object vertices); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UIVertex[] GetVerticesArray(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetCharactersInternal(object characters); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UICharInfo[] GetCharactersArray(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetLinesInternal(object lines); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UILineInfo[] GetLinesArray(); + } +} diff --git a/UnityEngine/UnityEngine/TextMesh.cs b/UnityEngine/UnityEngine/TextMesh.cs new file mode 100644 index 00000000..c5f66784 --- /dev/null +++ b/UnityEngine/UnityEngine/TextMesh.cs @@ -0,0 +1,126 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class TextMesh : Component + { + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Font font + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int fontSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern FontStyle fontStyle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float offsetZ + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextAlignment alignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextAnchor anchor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float characterSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float lineSpacing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float tabSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool richText + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color color + { + get + { + Color result; + this.INTERNAL_get_color(out result); + return result; + } + set + { + this.INTERNAL_set_color(ref value); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_color(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_color(ref Color value); + } +} diff --git a/UnityEngine/UnityEngine/Texture.cs b/UnityEngine/UnityEngine/Texture.cs new file mode 100644 index 00000000..6894e9fd --- /dev/null +++ b/UnityEngine/UnityEngine/Texture.cs @@ -0,0 +1,111 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Texture : Object + { + public static extern int masterTextureLimit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern AnisotropicFiltering anisotropicFiltering + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public virtual int width + { + get + { + return Texture.Internal_GetWidth(this); + } + set + { + throw new Exception("not implemented"); + } + } + public virtual int height + { + get + { + return Texture.Internal_GetHeight(this); + } + set + { + throw new Exception("not implemented"); + } + } + public extern FilterMode filterMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int anisoLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TextureWrapMode wrapMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float mipMapBias + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 texelSize + { + get + { + Vector2 result; + Texture.Internal_GetTexelSize(this, out result); + return result; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetGlobalAnisotropicFilteringLimits(int forcedMin, int globalMax); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetWidth(Texture mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int Internal_GetHeight(Texture mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetTexelSize(Texture tex, out Vector2 output); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern IntPtr GetNativeTexturePtr(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetNativeTextureID(); + } +} diff --git a/UnityEngine/UnityEngine/Texture2D.cs b/UnityEngine/UnityEngine/Texture2D.cs new file mode 100644 index 00000000..57e174aa --- /dev/null +++ b/UnityEngine/UnityEngine/Texture2D.cs @@ -0,0 +1,235 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Texture2D : Texture + { + public extern int mipmapCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern TextureFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Texture2D whiteTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Texture2D blackTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool alphaIsTransparency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Texture2D(int width, int height) + { + Texture2D.Internal_Create(this, width, height, TextureFormat.ARGB32, true, false, IntPtr.Zero); + } + public Texture2D(int width, int height, TextureFormat format, bool mipmap) + { + Texture2D.Internal_Create(this, width, height, format, mipmap, false, IntPtr.Zero); + } + public Texture2D(int width, int height, TextureFormat format, bool mipmap, bool linear) + { + Texture2D.Internal_Create(this, width, height, format, mipmap, linear, IntPtr.Zero); + } + internal Texture2D(int width, int height, TextureFormat format, bool mipmap, bool linear, IntPtr nativeTex) + { + Texture2D.Internal_Create(this, width, height, format, mipmap, linear, nativeTex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] Texture2D mono, int width, int height, TextureFormat format, bool mipmap, bool linear, IntPtr nativeTex); + public static Texture2D CreateExternalTexture(int width, int height, TextureFormat format, bool mipmap, bool linear, IntPtr nativeTex) + { + return new Texture2D(width, height, format, mipmap, linear, nativeTex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateExternalTexture(IntPtr nativeTex); + public void SetPixel(int x, int y, Color color) + { + Texture2D.INTERNAL_CALL_SetPixel(this, x, y, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetPixel(Texture2D self, int x, int y, ref Color color); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetPixel(int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetPixelBilinear(float u, float v); + [ExcludeFromDocs] + public void SetPixels(Color[] colors) + { + int miplevel = 0; + this.SetPixels(colors, miplevel); + } + public void SetPixels(Color[] colors, [DefaultValue("0")] int miplevel) + { + int num = this.width >> miplevel; + if (num < 1) + { + num = 1; + } + int num2 = this.height >> miplevel; + if (num2 < 1) + { + num2 = 1; + } + this.SetPixels(0, 0, num, num2, colors, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] colors, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] colors) + { + int miplevel = 0; + this.SetPixels(x, y, blockWidth, blockHeight, colors, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPixels32(Color32[] colors, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public void SetPixels32(Color32[] colors) + { + int miplevel = 0; + this.SetPixels32(colors, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool LoadImage(byte[] data); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void LoadRawTextureData(byte[] data); + [ExcludeFromDocs] + public Color[] GetPixels() + { + int miplevel = 0; + return this.GetPixels(miplevel); + } + public Color[] GetPixels([DefaultValue("0")] int miplevel) + { + int num = this.width >> miplevel; + if (num < 1) + { + num = 1; + } + int num2 = this.height >> miplevel; + if (num2 < 1) + { + num2 = 1; + } + return this.GetPixels(0, 0, num, num2, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color[] GetPixels(int x, int y, int blockWidth, int blockHeight, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public Color[] GetPixels(int x, int y, int blockWidth, int blockHeight) + { + int miplevel = 0; + return this.GetPixels(x, y, blockWidth, blockHeight, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color32[] GetPixels32([DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public Color32[] GetPixels32() + { + int miplevel = 0; + return this.GetPixels32(miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Apply([DefaultValue("true")] bool updateMipmaps, [DefaultValue("false")] bool makeNoLongerReadable); + [ExcludeFromDocs] + public void Apply(bool updateMipmaps) + { + bool makeNoLongerReadable = false; + this.Apply(updateMipmaps, makeNoLongerReadable); + } + [ExcludeFromDocs] + public void Apply() + { + bool makeNoLongerReadable = false; + bool updateMipmaps = true; + this.Apply(updateMipmaps, makeNoLongerReadable); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool Resize(int width, int height, TextureFormat format, bool hasMipMap); + public bool Resize(int width, int height) + { + return this.Internal_ResizeWH(width, height); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_ResizeWH(int width, int height); + public void Compress(bool highQuality) + { + Texture2D.INTERNAL_CALL_Compress(this, highQuality); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Compress(Texture2D self, bool highQuality); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Rect[] PackTextures(Texture2D[] textures, int padding, [DefaultValue("2048")] int maximumAtlasSize, [DefaultValue("false")] bool makeNoLongerReadable); + [ExcludeFromDocs] + public Rect[] PackTextures(Texture2D[] textures, int padding, int maximumAtlasSize) + { + bool makeNoLongerReadable = false; + return this.PackTextures(textures, padding, maximumAtlasSize, makeNoLongerReadable); + } + [ExcludeFromDocs] + public Rect[] PackTextures(Texture2D[] textures, int padding) + { + bool makeNoLongerReadable = false; + int maximumAtlasSize = 2048; + return this.PackTextures(textures, padding, maximumAtlasSize, makeNoLongerReadable); + } + public void ReadPixels(Rect source, int destX, int destY, [DefaultValue("true")] bool recalculateMipMaps) + { + Texture2D.INTERNAL_CALL_ReadPixels(this, ref source, destX, destY, recalculateMipMaps); + } + [ExcludeFromDocs] + public void ReadPixels(Rect source, int destX, int destY) + { + bool recalculateMipMaps = true; + Texture2D.INTERNAL_CALL_ReadPixels(this, ref source, destX, destY, recalculateMipMaps); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ReadPixels(Texture2D self, ref Rect source, int destX, int destY, bool recalculateMipMaps); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern byte[] EncodeToPNG(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern byte[] EncodeToJPG(int quality); + public byte[] EncodeToJPG() + { + return this.EncodeToJPG(75); + } + } +} diff --git a/UnityEngine/UnityEngine/Texture3D.cs b/UnityEngine/UnityEngine/Texture3D.cs new file mode 100644 index 00000000..85bb2eef --- /dev/null +++ b/UnityEngine/UnityEngine/Texture3D.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class Texture3D : Texture + { + public extern int depth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern TextureFormat format + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Texture3D(int width, int height, int depth, TextureFormat format, bool mipmap) + { + Texture3D.Internal_Create(this, width, height, depth, format, mipmap); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color[] GetPixels([DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public Color[] GetPixels() + { + int miplevel = 0; + return this.GetPixels(miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPixels(Color[] colors, [DefaultValue("0")] int miplevel); + [ExcludeFromDocs] + public void SetPixels(Color[] colors) + { + int miplevel = 0; + this.SetPixels(colors, miplevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Apply([DefaultValue("true")] bool updateMipmaps); + [ExcludeFromDocs] + public void Apply() + { + bool updateMipmaps = true; + this.Apply(updateMipmaps); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] Texture3D mono, int width, int height, int depth, TextureFormat format, bool mipmap); + } +} diff --git a/UnityEngine/UnityEngine/TextureCompressionQuality.cs b/UnityEngine/UnityEngine/TextureCompressionQuality.cs new file mode 100644 index 00000000..a4a3bba2 --- /dev/null +++ b/UnityEngine/UnityEngine/TextureCompressionQuality.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum TextureCompressionQuality + { + Fast, + Normal = 50, + Best = 100 + } +} diff --git a/UnityEngine/UnityEngine/TextureFormat.cs b/UnityEngine/UnityEngine/TextureFormat.cs new file mode 100644 index 00000000..7cd1df44 --- /dev/null +++ b/UnityEngine/UnityEngine/TextureFormat.cs @@ -0,0 +1,50 @@ +using System; +namespace UnityEngine +{ + public enum TextureFormat + { + Alpha8 = 1, + ARGB4444, + RGB24, + RGBA32, + ARGB32, + RGB565 = 7, + DXT1 = 10, + DXT5 = 12, + RGBA4444, + BGRA32, + PVRTC_RGB2 = 30, + PVRTC_RGBA2, + PVRTC_RGB4, + PVRTC_RGBA4, + ETC_RGB4, + ATC_RGB4, + ATC_RGBA8, + ATF_RGB_DXT1 = 38, + ATF_RGBA_JPG, + ATF_RGB_JPG, + EAC_R, + EAC_R_SIGNED, + EAC_RG, + EAC_RG_SIGNED, + ETC2_RGB, + ETC2_RGBA1, + ETC2_RGBA8, + ASTC_RGB_4x4, + ASTC_RGB_5x5, + ASTC_RGB_6x6, + ASTC_RGB_8x8, + ASTC_RGB_10x10, + ASTC_RGB_12x12, + ASTC_RGBA_4x4, + ASTC_RGBA_5x5, + ASTC_RGBA_6x6, + ASTC_RGBA_8x8, + ASTC_RGBA_10x10, + ASTC_RGBA_12x12, + PVRTC_2BPP_RGB = 30, + PVRTC_2BPP_RGBA, + PVRTC_4BPP_RGB, + PVRTC_4BPP_RGBA + } +} diff --git a/UnityEngine/UnityEngine/TextureWrapMode.cs b/UnityEngine/UnityEngine/TextureWrapMode.cs new file mode 100644 index 00000000..e1ced9a7 --- /dev/null +++ b/UnityEngine/UnityEngine/TextureWrapMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum TextureWrapMode + { + Repeat, + Clamp + } +} diff --git a/UnityEngine/UnityEngine/ThreadPriority.cs b/UnityEngine/UnityEngine/ThreadPriority.cs new file mode 100644 index 00000000..cf289c8f --- /dev/null +++ b/UnityEngine/UnityEngine/ThreadPriority.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum ThreadPriority + { + Low, + BelowNormal, + Normal, + High = 4 + } +} diff --git a/UnityEngine/UnityEngine/ThreadSafeAttribute.cs b/UnityEngine/UnityEngine/ThreadSafeAttribute.cs new file mode 100644 index 00000000..15b9c0e1 --- /dev/null +++ b/UnityEngine/UnityEngine/ThreadSafeAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false)] + public class ThreadSafeAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/Time.cs b/UnityEngine/UnityEngine/Time.cs new file mode 100644 index 00000000..cc24dc5f --- /dev/null +++ b/UnityEngine/UnityEngine/Time.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Time + { + public static extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float timeSinceLevelLoad + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float deltaTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float fixedTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float unscaledTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float unscaledDeltaTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float fixedDeltaTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float maximumDeltaTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float smoothDeltaTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float timeScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int frameCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int renderedFrameCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float realtimeSinceStartup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int captureFramerate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/TooltipAttribute.cs b/UnityEngine/UnityEngine/TooltipAttribute.cs new file mode 100644 index 00000000..fbe80e41 --- /dev/null +++ b/UnityEngine/UnityEngine/TooltipAttribute.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] + public class TooltipAttribute : PropertyAttribute + { + public readonly string tooltip; + public TooltipAttribute(string tooltip) + { + this.tooltip = tooltip; + } + } +} diff --git a/UnityEngine/UnityEngine/Touch.cs b/UnityEngine/UnityEngine/Touch.cs new file mode 100644 index 00000000..f2b8eba8 --- /dev/null +++ b/UnityEngine/UnityEngine/Touch.cs @@ -0,0 +1,63 @@ +using System; +namespace UnityEngine +{ + public struct Touch + { + private int m_FingerId; + private Vector2 m_Position; + private Vector2 m_RawPosition; + private Vector2 m_PositionDelta; + private float m_TimeDelta; + private int m_TapCount; + private TouchPhase m_Phase; + public int fingerId + { + get + { + return this.m_FingerId; + } + } + public Vector2 position + { + get + { + return this.m_Position; + } + } + public Vector2 rawPosition + { + get + { + return this.m_RawPosition; + } + } + public Vector2 deltaPosition + { + get + { + return this.m_PositionDelta; + } + } + public float deltaTime + { + get + { + return this.m_TimeDelta; + } + } + public int tapCount + { + get + { + return this.m_TapCount; + } + } + public TouchPhase phase + { + get + { + return this.m_Phase; + } + } + } +} diff --git a/UnityEngine/UnityEngine/TouchPhase.cs b/UnityEngine/UnityEngine/TouchPhase.cs new file mode 100644 index 00000000..a80f0f33 --- /dev/null +++ b/UnityEngine/UnityEngine/TouchPhase.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public enum TouchPhase + { + Began, + Moved, + Stationary, + Ended, + Canceled + } +} diff --git a/UnityEngine/UnityEngine/TouchScreenKeyboard.cs b/UnityEngine/UnityEngine/TouchScreenKeyboard.cs new file mode 100644 index 00000000..2200c56e --- /dev/null +++ b/UnityEngine/UnityEngine/TouchScreenKeyboard.cs @@ -0,0 +1,158 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class TouchScreenKeyboard + { + [NotRenamed] + [NonSerialized] + internal IntPtr m_Ptr; + public static bool isSupported + { + get + { + switch (Application.platform) + { + case RuntimePlatform.IPhonePlayer: + case RuntimePlatform.Android: + case RuntimePlatform.WP8Player: + case RuntimePlatform.BB10Player: + case RuntimePlatform.TizenPlayer: + return true; + case RuntimePlatform.MetroPlayerX86: + case RuntimePlatform.MetroPlayerX64: + case RuntimePlatform.MetroPlayerARM: + return false; + } + return false; + } + } + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool hideInput + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool active + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool done + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool wasCanceled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Rect area + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool visible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public TouchScreenKeyboard(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder) + { + TouchScreenKeyboard_InternalConstructorHelperArguments touchScreenKeyboard_InternalConstructorHelperArguments = default(TouchScreenKeyboard_InternalConstructorHelperArguments); + touchScreenKeyboard_InternalConstructorHelperArguments.keyboardType = Convert.ToUInt32(keyboardType); + touchScreenKeyboard_InternalConstructorHelperArguments.autocorrection = Convert.ToUInt32(autocorrection); + touchScreenKeyboard_InternalConstructorHelperArguments.multiline = Convert.ToUInt32(multiline); + touchScreenKeyboard_InternalConstructorHelperArguments.secure = Convert.ToUInt32(secure); + touchScreenKeyboard_InternalConstructorHelperArguments.alert = Convert.ToUInt32(alert); + this.TouchScreenKeyboard_InternalConstructorHelper(ref touchScreenKeyboard_InternalConstructorHelperArguments, text, textPlaceholder); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~TouchScreenKeyboard() + { + this.Destroy(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void TouchScreenKeyboard_InternalConstructorHelper(ref TouchScreenKeyboard_InternalConstructorHelperArguments arguments, string text, string textPlaceholder); + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert) + { + string empty = string.Empty; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure) + { + string empty = string.Empty; + bool alert = false; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + bool autocorrection = true; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static TouchScreenKeyboard Open(string text) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + bool autocorrection = true; + TouchScreenKeyboardType keyboardType = TouchScreenKeyboardType.Default; + return TouchScreenKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + public static TouchScreenKeyboard Open(string text, [DefaultValue("TouchScreenKeyboardType.Default")] TouchScreenKeyboardType keyboardType, [DefaultValue("true")] bool autocorrection, [DefaultValue("false")] bool multiline, [DefaultValue("false")] bool secure, [DefaultValue("false")] bool alert, [DefaultValue("\"\"")] string textPlaceholder) + { + return new TouchScreenKeyboard(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); + } + } +} diff --git a/UnityEngine/UnityEngine/TouchScreenKeyboardType.cs b/UnityEngine/UnityEngine/TouchScreenKeyboardType.cs new file mode 100644 index 00000000..e1fced09 --- /dev/null +++ b/UnityEngine/UnityEngine/TouchScreenKeyboardType.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + public enum TouchScreenKeyboardType + { + Default, + ASCIICapable, + NumbersAndPunctuation, + URL, + NumberPad, + PhonePad, + NamePhonePad, + EmailAddress + } +} diff --git a/UnityEngine/UnityEngine/TouchScreenKeyboard_InternalConstructorHelperArguments.cs b/UnityEngine/UnityEngine/TouchScreenKeyboard_InternalConstructorHelperArguments.cs new file mode 100644 index 00000000..c6a1535b --- /dev/null +++ b/UnityEngine/UnityEngine/TouchScreenKeyboard_InternalConstructorHelperArguments.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + internal struct TouchScreenKeyboard_InternalConstructorHelperArguments + { + public uint keyboardType; + public uint autocorrection; + public uint multiline; + public uint secure; + public uint alert; + } +} diff --git a/UnityEngine/UnityEngine/TrackedReference.cs b/UnityEngine/UnityEngine/TrackedReference.cs new file mode 100644 index 00000000..a06b02d6 --- /dev/null +++ b/UnityEngine/UnityEngine/TrackedReference.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class TrackedReference + { + [NotRenamed] + internal IntPtr m_Ptr; + protected TrackedReference() + { + } + public override bool Equals(object o) + { + return o as TrackedReference == this; + } + public override int GetHashCode() + { + return (int)this.m_Ptr; + } + public static bool operator ==(TrackedReference x, TrackedReference y) + { + if (y == null && x == null) + { + return true; + } + if (y == null) + { + return x.m_Ptr == IntPtr.Zero; + } + if (x == null) + { + return y.m_Ptr == IntPtr.Zero; + } + return x.m_Ptr == y.m_Ptr; + } + public static bool operator !=(TrackedReference x, TrackedReference y) + { + return !(x == y); + } + public static implicit operator bool(TrackedReference exists) + { + return exists != null; + } + } +} diff --git a/UnityEngine/UnityEngine/TrailRenderer.cs b/UnityEngine/UnityEngine/TrailRenderer.cs new file mode 100644 index 00000000..c691016e --- /dev/null +++ b/UnityEngine/UnityEngine/TrailRenderer.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class TrailRenderer : Renderer + { + public extern float time + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float startWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float endWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool autodestruct + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/Transform.cs b/UnityEngine/UnityEngine/Transform.cs new file mode 100644 index 00000000..c441e4bd --- /dev/null +++ b/UnityEngine/UnityEngine/Transform.cs @@ -0,0 +1,537 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public class Transform : Component, IEnumerable + { + private sealed class Enumerator : IEnumerator + { + private Transform outer; + private int currentIndex = -1; + public object Current + { + get + { + return this.outer.GetChild(this.currentIndex); + } + } + internal Enumerator(Transform outer) + { + this.outer = outer; + } + public bool MoveNext() + { + int childCount = this.outer.childCount; + return ++this.currentIndex < childCount; + } + public void Reset() + { + this.currentIndex = -1; + } + } + public Vector3 position + { + get + { + Vector3 result; + this.INTERNAL_get_position(out result); + return result; + } + set + { + this.INTERNAL_set_position(ref value); + } + } + public Vector3 localPosition + { + get + { + Vector3 result; + this.INTERNAL_get_localPosition(out result); + return result; + } + set + { + this.INTERNAL_set_localPosition(ref value); + } + } + public Vector3 eulerAngles + { + get + { + return this.rotation.eulerAngles; + } + set + { + this.rotation = Quaternion.Euler(value); + } + } + public Vector3 localEulerAngles + { + get + { + Vector3 result; + this.INTERNAL_get_localEulerAngles(out result); + return result; + } + set + { + this.INTERNAL_set_localEulerAngles(ref value); + } + } + public Vector3 right + { + get + { + return this.rotation * Vector3.right; + } + set + { + this.rotation = Quaternion.FromToRotation(Vector3.right, value); + } + } + public Vector3 up + { + get + { + return this.rotation * Vector3.up; + } + set + { + this.rotation = Quaternion.FromToRotation(Vector3.up, value); + } + } + public Vector3 forward + { + get + { + return this.rotation * Vector3.forward; + } + set + { + this.rotation = Quaternion.LookRotation(value); + } + } + public Quaternion rotation + { + get + { + Quaternion result; + this.INTERNAL_get_rotation(out result); + return result; + } + set + { + this.INTERNAL_set_rotation(ref value); + } + } + public Quaternion localRotation + { + get + { + Quaternion result; + this.INTERNAL_get_localRotation(out result); + return result; + } + set + { + this.INTERNAL_set_localRotation(ref value); + } + } + public Vector3 localScale + { + get + { + Vector3 result; + this.INTERNAL_get_localScale(out result); + return result; + } + set + { + this.INTERNAL_set_localScale(ref value); + } + } + public Transform parent + { + get + { + return this.parentInternal; + } + set + { + if (this is RectTransform) + { + Debug.LogWarning("Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.", this); + } + this.parentInternal = value; + } + } + internal extern Transform parentInternal + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Matrix4x4 worldToLocalMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_worldToLocalMatrix(out result); + return result; + } + } + public Matrix4x4 localToWorldMatrix + { + get + { + Matrix4x4 result; + this.INTERNAL_get_localToWorldMatrix(out result); + return result; + } + } + public extern Transform root + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int childCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Vector3 lossyScale + { + get + { + Vector3 result; + this.INTERNAL_get_lossyScale(out result); + return result; + } + } + public extern bool hasChanged + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + protected Transform() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_position(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_position(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localEulerAngles(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localEulerAngles(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_rotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_rotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localRotation(out Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localRotation(ref Quaternion value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localScale(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_localScale(ref Vector3 value); + public void SetParent(Transform parent) + { + this.SetParent(parent, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetParent(Transform parent, bool worldPositionStays); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_worldToLocalMatrix(out Matrix4x4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_localToWorldMatrix(out Matrix4x4 value); + [ExcludeFromDocs] + public void Translate(Vector3 translation) + { + Space relativeTo = Space.Self; + this.Translate(translation, relativeTo); + } + public void Translate(Vector3 translation, [DefaultValue("Space.Self")] Space relativeTo) + { + if (relativeTo == Space.World) + { + this.position += translation; + } + else + { + this.position += this.TransformDirection(translation); + } + } + [ExcludeFromDocs] + public void Translate(float x, float y, float z) + { + Space relativeTo = Space.Self; + this.Translate(x, y, z, relativeTo); + } + public void Translate(float x, float y, float z, [DefaultValue("Space.Self")] Space relativeTo) + { + this.Translate(new Vector3(x, y, z), relativeTo); + } + public void Translate(Vector3 translation, Transform relativeTo) + { + if (relativeTo) + { + this.position += relativeTo.TransformDirection(translation); + } + else + { + this.position += translation; + } + } + public void Translate(float x, float y, float z, Transform relativeTo) + { + this.Translate(new Vector3(x, y, z), relativeTo); + } + [ExcludeFromDocs] + public void Rotate(Vector3 eulerAngles) + { + Space relativeTo = Space.Self; + this.Rotate(eulerAngles, relativeTo); + } + public void Rotate(Vector3 eulerAngles, [DefaultValue("Space.Self")] Space relativeTo) + { + Quaternion rhs = Quaternion.Euler(eulerAngles.x, eulerAngles.y, eulerAngles.z); + if (relativeTo == Space.Self) + { + this.localRotation *= rhs; + } + else + { + this.rotation *= Quaternion.Inverse(this.rotation) * rhs * this.rotation; + } + } + [ExcludeFromDocs] + public void Rotate(float xAngle, float yAngle, float zAngle) + { + Space relativeTo = Space.Self; + this.Rotate(xAngle, yAngle, zAngle, relativeTo); + } + public void Rotate(float xAngle, float yAngle, float zAngle, [DefaultValue("Space.Self")] Space relativeTo) + { + this.Rotate(new Vector3(xAngle, yAngle, zAngle), relativeTo); + } + internal void RotateAroundInternal(Vector3 axis, float angle) + { + Transform.INTERNAL_CALL_RotateAroundInternal(this, ref axis, angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_RotateAroundInternal(Transform self, ref Vector3 axis, float angle); + [ExcludeFromDocs] + public void Rotate(Vector3 axis, float angle) + { + Space relativeTo = Space.Self; + this.Rotate(axis, angle, relativeTo); + } + public void Rotate(Vector3 axis, float angle, [DefaultValue("Space.Self")] Space relativeTo) + { + if (relativeTo == Space.Self) + { + this.RotateAroundInternal(base.transform.TransformDirection(axis), angle * 0.0174532924f); + } + else + { + this.RotateAroundInternal(axis, angle * 0.0174532924f); + } + } + public void RotateAround(Vector3 point, Vector3 axis, float angle) + { + Vector3 vector = this.position; + Quaternion rotation = Quaternion.AngleAxis(angle, axis); + Vector3 vector2 = vector - point; + vector2 = rotation * vector2; + vector = point + vector2; + this.position = vector; + this.RotateAroundInternal(axis, angle * 0.0174532924f); + } + [ExcludeFromDocs] + public void LookAt(Transform target) + { + Vector3 up = Vector3.up; + this.LookAt(target, up); + } + public void LookAt(Transform target, [DefaultValue("Vector3.up")] Vector3 worldUp) + { + if (target) + { + this.LookAt(target.position, worldUp); + } + } + public void LookAt(Vector3 worldPosition, [DefaultValue("Vector3.up")] Vector3 worldUp) + { + Transform.INTERNAL_CALL_LookAt(this, ref worldPosition, ref worldUp); + } + [ExcludeFromDocs] + public void LookAt(Vector3 worldPosition) + { + Vector3 up = Vector3.up; + Transform.INTERNAL_CALL_LookAt(this, ref worldPosition, ref up); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_LookAt(Transform self, ref Vector3 worldPosition, ref Vector3 worldUp); + public Vector3 TransformDirection(Vector3 direction) + { + return Transform.INTERNAL_CALL_TransformDirection(this, ref direction); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_TransformDirection(Transform self, ref Vector3 direction); + public Vector3 TransformDirection(float x, float y, float z) + { + return this.TransformDirection(new Vector3(x, y, z)); + } + public Vector3 InverseTransformDirection(Vector3 direction) + { + return Transform.INTERNAL_CALL_InverseTransformDirection(this, ref direction); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_InverseTransformDirection(Transform self, ref Vector3 direction); + public Vector3 InverseTransformDirection(float x, float y, float z) + { + return this.InverseTransformDirection(new Vector3(x, y, z)); + } + public Vector3 TransformVector(Vector3 vector) + { + return Transform.INTERNAL_CALL_TransformVector(this, ref vector); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_TransformVector(Transform self, ref Vector3 vector); + public Vector3 TransformVector(float x, float y, float z) + { + return this.TransformVector(new Vector3(x, y, z)); + } + public Vector3 InverseTransformVector(Vector3 vector) + { + return Transform.INTERNAL_CALL_InverseTransformVector(this, ref vector); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_InverseTransformVector(Transform self, ref Vector3 vector); + public Vector3 InverseTransformVector(float x, float y, float z) + { + return this.InverseTransformVector(new Vector3(x, y, z)); + } + public Vector3 TransformPoint(Vector3 position) + { + return Transform.INTERNAL_CALL_TransformPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_TransformPoint(Transform self, ref Vector3 position); + public Vector3 TransformPoint(float x, float y, float z) + { + return this.TransformPoint(new Vector3(x, y, z)); + } + public Vector3 InverseTransformPoint(Vector3 position) + { + return Transform.INTERNAL_CALL_InverseTransformPoint(this, ref position); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_InverseTransformPoint(Transform self, ref Vector3 position); + public Vector3 InverseTransformPoint(float x, float y, float z) + { + return this.InverseTransformPoint(new Vector3(x, y, z)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DetachChildren(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAsFirstSibling(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAsLastSibling(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetSiblingIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetSiblingIndex(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transform Find(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SendTransformChangedScale(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_lossyScale(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsChildOf(Transform parent); + public Transform FindChild(string name) + { + return this.Find(name); + } + public IEnumerator GetEnumerator() + { + return new Transform.Enumerator(this); + } + [Obsolete("use Transform.Rotate instead.")] + public void RotateAround(Vector3 axis, float angle) + { + Transform.INTERNAL_CALL_RotateAround(this, ref axis, angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_RotateAround(Transform self, ref Vector3 axis, float angle); + [Obsolete("use Transform.Rotate instead.")] + public void RotateAroundLocal(Vector3 axis, float angle) + { + Transform.INTERNAL_CALL_RotateAroundLocal(this, ref axis, angle); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_RotateAroundLocal(Transform self, ref Vector3 axis, float angle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Transform GetChild(int index); + [Obsolete("use Transform.childCount instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetChildCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool IsNonUniformScaleTransform(); + } +} diff --git a/UnityEngine/UnityEngine/TransparencySortMode.cs b/UnityEngine/UnityEngine/TransparencySortMode.cs new file mode 100644 index 00000000..664b249d --- /dev/null +++ b/UnityEngine/UnityEngine/TransparencySortMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum TransparencySortMode + { + Default, + Perspective, + Orthographic + } +} diff --git a/UnityEngine/UnityEngine/Tree.cs b/UnityEngine/UnityEngine/Tree.cs new file mode 100644 index 00000000..1cff91f5 --- /dev/null +++ b/UnityEngine/UnityEngine/Tree.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class Tree : Component + { + public extern ScriptableObject data + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/TreeInstance.cs b/UnityEngine/UnityEngine/TreeInstance.cs new file mode 100644 index 00000000..50a6ea70 --- /dev/null +++ b/UnityEngine/UnityEngine/TreeInstance.cs @@ -0,0 +1,91 @@ +using System; +namespace UnityEngine +{ + public struct TreeInstance + { + private Vector3 m_Position; + private float m_WidthScale; + private float m_HeightScale; + private Color32 m_Color; + private Color32 m_LightmapColor; + private int m_Index; + private float m_TemporaryDistance; + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + public float widthScale + { + get + { + return this.m_WidthScale; + } + set + { + this.m_WidthScale = value; + } + } + public float heightScale + { + get + { + return this.m_HeightScale; + } + set + { + this.m_HeightScale = value; + } + } + public Color color + { + get + { + return this.m_Color; + } + set + { + this.m_Color = value; + } + } + public Color lightmapColor + { + get + { + return this.m_LightmapColor; + } + set + { + this.m_LightmapColor = value; + } + } + public int prototypeIndex + { + get + { + return this.m_Index; + } + set + { + this.m_Index = value; + } + } + internal float temporaryDistance + { + get + { + return this.m_TemporaryDistance; + } + set + { + this.m_TemporaryDistance = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/TreePrototype.cs b/UnityEngine/UnityEngine/TreePrototype.cs new file mode 100644 index 00000000..7fc262d0 --- /dev/null +++ b/UnityEngine/UnityEngine/TreePrototype.cs @@ -0,0 +1,33 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class TreePrototype + { + internal GameObject m_Prefab; + internal float m_BendFactor; + public GameObject prefab + { + get + { + return this.m_Prefab; + } + set + { + this.m_Prefab = value; + } + } + public float bendFactor + { + get + { + return this.m_BendFactor; + } + set + { + this.m_BendFactor = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/Types.cs b/UnityEngine/UnityEngine/Types.cs new file mode 100644 index 00000000..9e8ccf06 --- /dev/null +++ b/UnityEngine/UnityEngine/Types.cs @@ -0,0 +1,21 @@ +using System; +using System.Reflection; +namespace UnityEngine +{ + public static class Types + { + public static Type GetType(string typeName, string assemblyName) + { + Type result; + try + { + result = Assembly.Load(assemblyName).GetType(typeName); + } + catch (Exception) + { + result = null; + } + return result; + } + } +} diff --git a/UnityEngine/UnityEngine/UICharInfo.cs b/UnityEngine/UnityEngine/UICharInfo.cs new file mode 100644 index 00000000..76b7d8d8 --- /dev/null +++ b/UnityEngine/UnityEngine/UICharInfo.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public struct UICharInfo + { + public Vector2 cursorPos; + public float charWidth; + } +} diff --git a/UnityEngine/UnityEngine/UILineInfo.cs b/UnityEngine/UnityEngine/UILineInfo.cs new file mode 100644 index 00000000..7ac241b0 --- /dev/null +++ b/UnityEngine/UnityEngine/UILineInfo.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public struct UILineInfo + { + public int startCharIdx; + public int height; + } +} diff --git a/UnityEngine/UnityEngine/UIVertex.cs b/UnityEngine/UnityEngine/UIVertex.cs new file mode 100644 index 00000000..7624ea34 --- /dev/null +++ b/UnityEngine/UnityEngine/UIVertex.cs @@ -0,0 +1,24 @@ +using System; +namespace UnityEngine +{ + public struct UIVertex + { + public Vector3 position; + public Vector3 normal; + public Color32 color; + public Vector2 uv0; + public Vector2 uv1; + public Vector4 tangent; + private static readonly Color32 s_DefaultColor = new Color32(255, 255, 255, 255); + private static readonly Vector4 s_DefaultTangent = new Vector4(1f, 0f, 0f, -1f); + public static UIVertex simpleVert = new UIVertex + { + position = Vector3.zero, + normal = Vector3.back, + tangent = UIVertex.s_DefaultTangent, + color = UIVertex.s_DefaultColor, + uv0 = Vector2.zero, + uv1 = Vector2.zero + }; + } +} diff --git a/UnityEngine/UnityEngine/UnassignedReferenceException.cs b/UnityEngine/UnityEngine/UnassignedReferenceException.cs new file mode 100644 index 00000000..52e2de43 --- /dev/null +++ b/UnityEngine/UnityEngine/UnassignedReferenceException.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +namespace UnityEngine +{ + [Serializable] + public class UnassignedReferenceException : SystemException + { + private const int Result = -2147467261; + private string unityStackTrace; + public UnassignedReferenceException() : base("A Unity Runtime error occurred!") + { + base.HResult = -2147467261; + } + public UnassignedReferenceException(string message) : base(message) + { + base.HResult = -2147467261; + } + public UnassignedReferenceException(string message, Exception innerException) : base(message, innerException) + { + base.HResult = -2147467261; + } + protected UnassignedReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} diff --git a/UnityEngine/UnityEngine/UnhandledExceptionHandler.cs b/UnityEngine/UnityEngine/UnhandledExceptionHandler.cs new file mode 100644 index 00000000..d5e022c0 --- /dev/null +++ b/UnityEngine/UnityEngine/UnhandledExceptionHandler.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class UnhandledExceptionHandler + { + private static void RegisterUECatcher() + { + AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler.HandleUnhandledException); + } + private static void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args) + { + Exception ex = args.ExceptionObject as Exception; + if (ex != null) + { + UnhandledExceptionHandler.PrintException("Unhandled Exception: ", ex); + } + UnhandledExceptionHandler.NativeUnhandledExceptionHandler(); + } + private static void PrintException(string title, Exception e) + { + Debug.LogError(title + e.ToString()); + if (e.InnerException != null) + { + UnhandledExceptionHandler.PrintException("Inner Exception: ", e.InnerException); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void NativeUnhandledExceptionHandler(); + } +} diff --git a/UnityEngine/UnityEngine/UnityException.cs b/UnityEngine/UnityEngine/UnityException.cs new file mode 100644 index 00000000..ddb60146 --- /dev/null +++ b/UnityEngine/UnityEngine/UnityException.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.Serialization; +namespace UnityEngine +{ + [Serializable] + public class UnityException : SystemException + { + private const int Result = -2147467261; + private string unityStackTrace; + public UnityException() : base("A Unity Runtime error occurred!") + { + base.HResult = -2147467261; + } + public UnityException(string message) : base(message) + { + base.HResult = -2147467261; + } + public UnityException(string message, Exception innerException) : base(message, innerException) + { + base.HResult = -2147467261; + } + protected UnityException(SerializationInfo info, StreamingContext context) : base(info, context) + { + } + } +} diff --git a/UnityEngine/UnityEngine/UnityLogWriter.cs b/UnityEngine/UnityEngine/UnityLogWriter.cs new file mode 100644 index 00000000..b46831f2 --- /dev/null +++ b/UnityEngine/UnityEngine/UnityLogWriter.cs @@ -0,0 +1,32 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +namespace UnityEngine +{ + internal sealed class UnityLogWriter : TextWriter + { + public override Encoding Encoding + { + get + { + return Encoding.UTF8; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void WriteStringToUnityLog(string s); + public static void Init() + { + Console.SetOut(new UnityLogWriter()); + } + public override void Write(char value) + { + UnityLogWriter.WriteStringToUnityLog(value.ToString()); + } + public override void Write(string s) + { + UnityLogWriter.WriteStringToUnityLog(s); + } + } +} diff --git a/UnityEngine/UnityEngine/UnityString.cs b/UnityEngine/UnityEngine/UnityString.cs new file mode 100644 index 00000000..95020655 --- /dev/null +++ b/UnityEngine/UnityEngine/UnityString.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + internal sealed class UnityString + { + public static string Format(string fmt, params object[] args) + { + return string.Format(fmt, args); + } + } +} diff --git a/UnityEngine/UnityEngine/UserAuthorization.cs b/UnityEngine/UnityEngine/UserAuthorization.cs new file mode 100644 index 00000000..c95bd66a --- /dev/null +++ b/UnityEngine/UnityEngine/UserAuthorization.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum UserAuthorization + { + WebCam = 1, + Microphone + } +} diff --git a/UnityEngine/UnityEngine/UserAuthorizationDialog.cs b/UnityEngine/UnityEngine/UserAuthorizationDialog.cs new file mode 100644 index 00000000..32ebd7ff --- /dev/null +++ b/UnityEngine/UnityEngine/UserAuthorizationDialog.cs @@ -0,0 +1,142 @@ +using System; +namespace UnityEngine +{ + [AddComponentMenu("")] + internal class UserAuthorizationDialog : MonoBehaviour + { + private const int width = 385; + private const int height = 155; + private Rect windowRect; + private Texture warningIcon; + private void Start() + { + this.warningIcon = (Resources.GetBuiltinResource(typeof(Texture2D), "WarningSign.psd") as Texture2D); + if (Screen.width < 385 || Screen.height < 155) + { + Debug.LogError("Screen is to small to display authorization dialog. Authorization denied."); + Application.ReplyToUserAuthorizationRequest(false); + } + this.windowRect = new Rect((float)(Screen.width / 2 - 192), (float)(Screen.height / 2 - 77), 385f, 155f); + } + private void OnGUI() + { + GUISkin skin = GUI.skin; + GUISkin gUISkin = ScriptableObject.CreateInstance("GUISkin") as GUISkin; + gUISkin.box.normal.background = (Texture2D)Resources.GetBuiltinResource(typeof(Texture2D), "GameSkin/box.png"); + gUISkin.box.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f); + gUISkin.box.padding.left = 6; + gUISkin.box.padding.right = 6; + gUISkin.box.padding.top = 4; + gUISkin.box.padding.bottom = 4; + gUISkin.box.border.left = 6; + gUISkin.box.border.right = 6; + gUISkin.box.border.top = 6; + gUISkin.box.border.bottom = 6; + gUISkin.box.margin.left = 4; + gUISkin.box.margin.right = 4; + gUISkin.box.margin.top = 4; + gUISkin.box.margin.bottom = 4; + gUISkin.button.normal.background = (Texture2D)Resources.GetBuiltinResource(typeof(Texture2D), "GameSkin/button.png"); + gUISkin.button.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f); + gUISkin.button.hover.background = (Texture2D)Resources.GetBuiltinResource(typeof(Texture2D), "GameSkin/button hover.png"); + gUISkin.button.hover.textColor = Color.white; + gUISkin.button.active.background = (Texture2D)Resources.GetBuiltinResource(typeof(Texture2D), "GameSkin/button active.png"); + gUISkin.button.active.textColor = new Color(0.9f, 0.9f, 0.9f, 1f); + gUISkin.button.border.left = 6; + gUISkin.button.border.right = 6; + gUISkin.button.border.top = 6; + gUISkin.button.border.bottom = 6; + gUISkin.button.padding.left = 8; + gUISkin.button.padding.right = 8; + gUISkin.button.padding.top = 4; + gUISkin.button.padding.bottom = 4; + gUISkin.button.margin.left = 4; + gUISkin.button.margin.right = 4; + gUISkin.button.margin.top = 4; + gUISkin.button.margin.bottom = 4; + gUISkin.label.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f); + gUISkin.label.padding.left = 6; + gUISkin.label.padding.right = 6; + gUISkin.label.padding.top = 4; + gUISkin.label.padding.bottom = 4; + gUISkin.label.margin.left = 4; + gUISkin.label.margin.right = 4; + gUISkin.label.margin.top = 4; + gUISkin.label.margin.bottom = 4; + gUISkin.label.alignment = TextAnchor.UpperLeft; + gUISkin.window.normal.background = (Texture2D)Resources.GetBuiltinResource(typeof(Texture2D), "GameSkin/window.png"); + gUISkin.window.normal.textColor = Color.white; + gUISkin.window.border.left = 8; + gUISkin.window.border.right = 8; + gUISkin.window.border.top = 18; + gUISkin.window.border.bottom = 8; + gUISkin.window.padding.left = 8; + gUISkin.window.padding.right = 8; + gUISkin.window.padding.top = 20; + gUISkin.window.padding.bottom = 5; + gUISkin.window.alignment = TextAnchor.UpperCenter; + gUISkin.window.contentOffset = new Vector2(0f, -18f); + GUI.skin = gUISkin; + this.windowRect = GUI.Window(0, this.windowRect, new GUI.WindowFunction(this.DoUserAuthorizationDialog), "Unity Web Player Authorization Request"); + GUI.skin = skin; + } + private void DoUserAuthorizationDialog(int windowID) + { + UserAuthorization userAuthorizationRequestMode = Application.GetUserAuthorizationRequestMode(); + GUILayout.FlexibleSpace(); + GUI.backgroundColor = new Color(0.9f, 0.9f, 0.9f, 0.7f); + GUILayout.BeginHorizontal("box", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(this.warningIcon, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (userAuthorizationRequestMode == (UserAuthorization)3) + { + GUILayout.Label("The content on this site would like to use your\ncomputer's web camera and microphone.\nThese images and sounds may be recorded.", new GUILayoutOption[0]); + } + else + { + if (userAuthorizationRequestMode == UserAuthorization.WebCam) + { + GUILayout.Label("The content on this site would like to use\nyour computer's web camera. The images\nfrom your web camera may be recorded.", new GUILayoutOption[0]); + } + else + { + if (userAuthorizationRequestMode != UserAuthorization.Microphone) + { + return; + } + GUILayout.Label("The content on this site would like to use\nyour computer's microphone. The sounds\nfrom your microphone may be recorded.", new GUILayoutOption[0]); + } + } + GUILayout.FlexibleSpace(); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + GUI.backgroundColor = Color.white; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button("Deny", new GUILayoutOption[0])) + { + Application.ReplyToUserAuthorizationRequest(false); + } + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Always Allow for this Site", new GUILayoutOption[0])) + { + Application.ReplyToUserAuthorizationRequest(true, true); + } + GUILayout.Space(5f); + if (GUILayout.Button("Allow", new GUILayoutOption[0])) + { + Application.ReplyToUserAuthorizationRequest(true); + } + GUILayout.EndHorizontal(); + GUILayout.FlexibleSpace(); + } + } +} diff --git a/UnityEngine/UnityEngine/Vector2.cs b/UnityEngine/UnityEngine/Vector2.cs new file mode 100644 index 00000000..6dc2a5fd --- /dev/null +++ b/UnityEngine/UnityEngine/Vector2.cs @@ -0,0 +1,277 @@ +using System; +using UnityEngine.Internal; +namespace UnityEngine +{ + public struct Vector2 + { + public const float kEpsilon = 1E-05f; + public float x; + public float y; + public float this[int index] + { + get + { + if (index == 0) + { + return this.x; + } + if (index != 1) + { + throw new IndexOutOfRangeException("Invalid Vector2 index!"); + } + return this.y; + } + set + { + if (index != 0) + { + if (index != 1) + { + throw new IndexOutOfRangeException("Invalid Vector2 index!"); + } + this.y = value; + } + else + { + this.x = value; + } + } + } + public Vector2 normalized + { + get + { + Vector2 result = new Vector2(this.x, this.y); + result.Normalize(); + return result; + } + } + public float magnitude + { + get + { + return Mathf.Sqrt(this.x * this.x + this.y * this.y); + } + } + public float sqrMagnitude + { + get + { + return this.x * this.x + this.y * this.y; + } + } + public static Vector2 zero + { + get + { + return new Vector2(0f, 0f); + } + } + public static Vector2 one + { + get + { + return new Vector2(1f, 1f); + } + } + public static Vector2 up + { + get + { + return new Vector2(0f, 1f); + } + } + public static Vector2 right + { + get + { + return new Vector2(1f, 0f); + } + } + public Vector2(float x, float y) + { + this.x = x; + this.y = y; + } + public void Set(float new_x, float new_y) + { + this.x = new_x; + this.y = new_y; + } + public static Vector2 Lerp(Vector2 from, Vector2 to, float t) + { + t = Mathf.Clamp01(t); + return new Vector2(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t); + } + public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta) + { + Vector2 a = target - current; + float magnitude = a.magnitude; + if (magnitude <= maxDistanceDelta || magnitude == 0f) + { + return target; + } + return current + a / magnitude * maxDistanceDelta; + } + public static Vector2 Scale(Vector2 a, Vector2 b) + { + return new Vector2(a.x * b.x, a.y * b.y); + } + public void Scale(Vector2 scale) + { + this.x *= scale.x; + this.y *= scale.y; + } + public void Normalize() + { + float magnitude = this.magnitude; + if (magnitude > 1E-05f) + { + this /= magnitude; + } + else + { + this = Vector2.zero; + } + } + public override string ToString() + { + return UnityString.Format("({0:F1}, {1:F1})", new object[] + { + this.x, + this.y + }); + } + public string ToString(string format) + { + return UnityString.Format("({0}, {1})", new object[] + { + this.x.ToString(format), + this.y.ToString(format) + }); + } + public override int GetHashCode() + { + return this.x.GetHashCode() ^ this.y.GetHashCode() << 2; + } + public override bool Equals(object other) + { + if (!(other is Vector2)) + { + return false; + } + Vector2 vector = (Vector2)other; + return this.x.Equals(vector.x) && this.y.Equals(vector.y); + } + public static float Dot(Vector2 lhs, Vector2 rhs) + { + return lhs.x * rhs.x + lhs.y * rhs.y; + } + public static float Angle(Vector2 from, Vector2 to) + { + return Mathf.Acos(Mathf.Clamp(Vector2.Dot(from.normalized, to.normalized), -1f, 1f)) * 57.29578f; + } + public static float Distance(Vector2 a, Vector2 b) + { + return (a - b).magnitude; + } + public static Vector2 ClampMagnitude(Vector2 vector, float maxLength) + { + if (vector.sqrMagnitude > maxLength * maxLength) + { + return vector.normalized * maxLength; + } + return vector; + } + public static float SqrMagnitude(Vector2 a) + { + return a.x * a.x + a.y * a.y; + } + public float SqrMagnitude() + { + return this.x * this.x + this.y * this.y; + } + public static Vector2 Min(Vector2 lhs, Vector2 rhs) + { + return new Vector2(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y)); + } + public static Vector2 Max(Vector2 lhs, Vector2 rhs) + { + return new Vector2(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y)); + } + [ExcludeFromDocs] + public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime, float maxSpeed) + { + float deltaTime = Time.deltaTime; + return Vector2.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + [ExcludeFromDocs] + public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime) + { + float deltaTime = Time.deltaTime; + float maxSpeed = float.PositiveInfinity; + return Vector2.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime, [DefaultValue("Mathf.Infinity")] float maxSpeed, [DefaultValue("Time.deltaTime")] float deltaTime) + { + smoothTime = Mathf.Max(0.0001f, smoothTime); + float num = 2f / smoothTime; + float num2 = num * deltaTime; + float d = 1f / (1f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); + Vector2 vector = current - target; + Vector2 vector2 = target; + float maxLength = maxSpeed * smoothTime; + vector = Vector2.ClampMagnitude(vector, maxLength); + target = current - vector; + Vector2 vector3 = (currentVelocity + num * vector) * deltaTime; + currentVelocity = (currentVelocity - num * vector3) * d; + Vector2 vector4 = target + (vector + vector3) * d; + if (Vector2.Dot(vector2 - current, vector4 - vector2) > 0f) + { + vector4 = vector2; + currentVelocity = (vector4 - vector2) / deltaTime; + } + return vector4; + } + public static Vector2 operator +(Vector2 a, Vector2 b) + { + return new Vector2(a.x + b.x, a.y + b.y); + } + public static Vector2 operator -(Vector2 a, Vector2 b) + { + return new Vector2(a.x - b.x, a.y - b.y); + } + public static Vector2 operator -(Vector2 a) + { + return new Vector2(-a.x, -a.y); + } + public static Vector2 operator *(Vector2 a, float d) + { + return new Vector2(a.x * d, a.y * d); + } + public static Vector2 operator *(float d, Vector2 a) + { + return new Vector2(a.x * d, a.y * d); + } + public static Vector2 operator /(Vector2 a, float d) + { + return new Vector2(a.x / d, a.y / d); + } + public static bool operator ==(Vector2 lhs, Vector2 rhs) + { + return Vector2.SqrMagnitude(lhs - rhs) < 9.99999944E-11f; + } + public static bool operator !=(Vector2 lhs, Vector2 rhs) + { + return Vector2.SqrMagnitude(lhs - rhs) >= 9.99999944E-11f; + } + public static implicit operator Vector2(Vector3 v) + { + return new Vector2(v.x, v.y); + } + public static implicit operator Vector3(Vector2 v) + { + return new Vector3(v.x, v.y, 0f); + } + } +} diff --git a/UnityEngine/UnityEngine/Vector3.cs b/UnityEngine/UnityEngine/Vector3.cs new file mode 100644 index 00000000..82f56efe --- /dev/null +++ b/UnityEngine/UnityEngine/Vector3.cs @@ -0,0 +1,397 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public struct Vector3 + { + public const float kEpsilon = 1E-05f; + public float x; + public float y; + public float z; + public float this[int index] + { + get + { + switch (index) + { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new IndexOutOfRangeException("Invalid Vector3 index!"); + } + } + set + { + switch (index) + { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + default: + throw new IndexOutOfRangeException("Invalid Vector3 index!"); + } + } + } + public Vector3 normalized + { + get + { + return Vector3.Normalize(this); + } + } + public float magnitude + { + get + { + return Mathf.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + } + public float sqrMagnitude + { + get + { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + } + public static Vector3 zero + { + get + { + return new Vector3(0f, 0f, 0f); + } + } + public static Vector3 one + { + get + { + return new Vector3(1f, 1f, 1f); + } + } + public static Vector3 forward + { + get + { + return new Vector3(0f, 0f, 1f); + } + } + public static Vector3 back + { + get + { + return new Vector3(0f, 0f, -1f); + } + } + public static Vector3 up + { + get + { + return new Vector3(0f, 1f, 0f); + } + } + public static Vector3 down + { + get + { + return new Vector3(0f, -1f, 0f); + } + } + public static Vector3 left + { + get + { + return new Vector3(-1f, 0f, 0f); + } + } + public static Vector3 right + { + get + { + return new Vector3(1f, 0f, 0f); + } + } + [Obsolete("Use Vector3.forward instead.")] + public static Vector3 fwd + { + get + { + return new Vector3(0f, 0f, 1f); + } + } + public Vector3(float x, float y, float z) + { + this.x = x; + this.y = y; + this.z = z; + } + public Vector3(float x, float y) + { + this.x = x; + this.y = y; + this.z = 0f; + } + public static Vector3 Lerp(Vector3 from, Vector3 to, float t) + { + t = Mathf.Clamp01(t); + return new Vector3(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t, from.z + (to.z - from.z) * t); + } + public static Vector3 Slerp(Vector3 from, Vector3 to, float t) + { + return Vector3.INTERNAL_CALL_Slerp(ref from, ref to, t); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_Slerp(ref Vector3 from, ref Vector3 to, float t); + private static void Internal_OrthoNormalize2(ref Vector3 a, ref Vector3 b) + { + Vector3.INTERNAL_CALL_Internal_OrthoNormalize2(ref a, ref b); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_OrthoNormalize2(ref Vector3 a, ref Vector3 b); + private static void Internal_OrthoNormalize3(ref Vector3 a, ref Vector3 b, ref Vector3 c) + { + Vector3.INTERNAL_CALL_Internal_OrthoNormalize3(ref a, ref b, ref c); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_OrthoNormalize3(ref Vector3 a, ref Vector3 b, ref Vector3 c); + public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent) + { + Vector3.Internal_OrthoNormalize2(ref normal, ref tangent); + } + public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent, ref Vector3 binormal) + { + Vector3.Internal_OrthoNormalize3(ref normal, ref tangent, ref binormal); + } + public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta) + { + Vector3 a = target - current; + float magnitude = a.magnitude; + if (magnitude <= maxDistanceDelta || magnitude == 0f) + { + return target; + } + return current + a / magnitude * maxDistanceDelta; + } + public static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta) + { + return Vector3.INTERNAL_CALL_RotateTowards(ref current, ref target, maxRadiansDelta, maxMagnitudeDelta); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_RotateTowards(ref Vector3 current, ref Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta); + [ExcludeFromDocs] + public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime, float maxSpeed) + { + float deltaTime = Time.deltaTime; + return Vector3.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + [ExcludeFromDocs] + public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime) + { + float deltaTime = Time.deltaTime; + float maxSpeed = float.PositiveInfinity; + return Vector3.SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); + } + public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime, [DefaultValue("Mathf.Infinity")] float maxSpeed, [DefaultValue("Time.deltaTime")] float deltaTime) + { + smoothTime = Mathf.Max(0.0001f, smoothTime); + float num = 2f / smoothTime; + float num2 = num * deltaTime; + float d = 1f / (1f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); + Vector3 vector = current - target; + Vector3 vector2 = target; + float maxLength = maxSpeed * smoothTime; + vector = Vector3.ClampMagnitude(vector, maxLength); + target = current - vector; + Vector3 vector3 = (currentVelocity + num * vector) * deltaTime; + currentVelocity = (currentVelocity - num * vector3) * d; + Vector3 vector4 = target + (vector + vector3) * d; + if (Vector3.Dot(vector2 - current, vector4 - vector2) > 0f) + { + vector4 = vector2; + currentVelocity = (vector4 - vector2) / deltaTime; + } + return vector4; + } + public void Set(float new_x, float new_y, float new_z) + { + this.x = new_x; + this.y = new_y; + this.z = new_z; + } + public static Vector3 Scale(Vector3 a, Vector3 b) + { + return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z); + } + public void Scale(Vector3 scale) + { + this.x *= scale.x; + this.y *= scale.y; + this.z *= scale.z; + } + public static Vector3 Cross(Vector3 lhs, Vector3 rhs) + { + return new Vector3(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x); + } + public override int GetHashCode() + { + return this.x.GetHashCode() ^ this.y.GetHashCode() << 2 ^ this.z.GetHashCode() >> 2; + } + public override bool Equals(object other) + { + if (!(other is Vector3)) + { + return false; + } + Vector3 vector = (Vector3)other; + return this.x.Equals(vector.x) && this.y.Equals(vector.y) && this.z.Equals(vector.z); + } + public static Vector3 Reflect(Vector3 inDirection, Vector3 inNormal) + { + return -2f * Vector3.Dot(inNormal, inDirection) * inNormal + inDirection; + } + public static Vector3 Normalize(Vector3 value) + { + float num = Vector3.Magnitude(value); + if (num > 1E-05f) + { + return value / num; + } + return Vector3.zero; + } + public void Normalize() + { + float num = Vector3.Magnitude(this); + if (num > 1E-05f) + { + this /= num; + } + else + { + this = Vector3.zero; + } + } + public override string ToString() + { + return UnityString.Format("({0:F1}, {1:F1}, {2:F1})", new object[] + { + this.x, + this.y, + this.z + }); + } + public string ToString(string format) + { + return UnityString.Format("({0}, {1}, {2})", new object[] + { + this.x.ToString(format), + this.y.ToString(format), + this.z.ToString(format) + }); + } + public static float Dot(Vector3 lhs, Vector3 rhs) + { + return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; + } + public static Vector3 Project(Vector3 vector, Vector3 onNormal) + { + float num = Vector3.Dot(onNormal, onNormal); + if (num < 1.401298E-45f) + { + return Vector3.zero; + } + return onNormal * Vector3.Dot(vector, onNormal) / num; + } + public static Vector3 ProjectOnPlane(Vector3 vector, Vector3 planeNormal) + { + return vector - Vector3.Project(vector, planeNormal); + } + [Obsolete("Use Vector3.ProjectOnPlane instead.")] + public static Vector3 Exclude(Vector3 excludeThis, Vector3 fromThat) + { + return fromThat - Vector3.Project(fromThat, excludeThis); + } + public static float Angle(Vector3 from, Vector3 to) + { + return Mathf.Acos(Mathf.Clamp(Vector3.Dot(from.normalized, to.normalized), -1f, 1f)) * 57.29578f; + } + public static float Distance(Vector3 a, Vector3 b) + { + Vector3 vector = new Vector3(a.x - b.x, a.y - b.y, a.z - b.z); + return Mathf.Sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); + } + public static Vector3 ClampMagnitude(Vector3 vector, float maxLength) + { + if (vector.sqrMagnitude > maxLength * maxLength) + { + return vector.normalized * maxLength; + } + return vector; + } + public static float Magnitude(Vector3 a) + { + return Mathf.Sqrt(a.x * a.x + a.y * a.y + a.z * a.z); + } + public static float SqrMagnitude(Vector3 a) + { + return a.x * a.x + a.y * a.y + a.z * a.z; + } + public static Vector3 Min(Vector3 lhs, Vector3 rhs) + { + return new Vector3(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z)); + } + public static Vector3 Max(Vector3 lhs, Vector3 rhs) + { + return new Vector3(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z)); + } + [Obsolete("Use Vector3.Angle instead. AngleBetween uses radians instead of degrees and was deprecated for this reason")] + public static float AngleBetween(Vector3 from, Vector3 to) + { + return Mathf.Acos(Mathf.Clamp(Vector3.Dot(from.normalized, to.normalized), -1f, 1f)); + } + public static Vector3 operator +(Vector3 a, Vector3 b) + { + return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z); + } + public static Vector3 operator -(Vector3 a, Vector3 b) + { + return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z); + } + public static Vector3 operator -(Vector3 a) + { + return new Vector3(-a.x, -a.y, -a.z); + } + public static Vector3 operator *(Vector3 a, float d) + { + return new Vector3(a.x * d, a.y * d, a.z * d); + } + public static Vector3 operator *(float d, Vector3 a) + { + return new Vector3(a.x * d, a.y * d, a.z * d); + } + public static Vector3 operator /(Vector3 a, float d) + { + return new Vector3(a.x / d, a.y / d, a.z / d); + } + public static bool operator ==(Vector3 lhs, Vector3 rhs) + { + return Vector3.SqrMagnitude(lhs - rhs) < 9.99999944E-11f; + } + public static bool operator !=(Vector3 lhs, Vector3 rhs) + { + return Vector3.SqrMagnitude(lhs - rhs) >= 9.99999944E-11f; + } + } +} diff --git a/UnityEngine/UnityEngine/Vector4.cs b/UnityEngine/UnityEngine/Vector4.cs new file mode 100644 index 00000000..2ceeb31a --- /dev/null +++ b/UnityEngine/UnityEngine/Vector4.cs @@ -0,0 +1,274 @@ +using System; +namespace UnityEngine +{ + public struct Vector4 + { + public const float kEpsilon = 1E-05f; + public float x; + public float y; + public float z; + public float w; + public float this[int index] + { + get + { + switch (index) + { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new IndexOutOfRangeException("Invalid Vector4 index!"); + } + } + set + { + switch (index) + { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + case 3: + this.w = value; + break; + default: + throw new IndexOutOfRangeException("Invalid Vector4 index!"); + } + } + } + public Vector4 normalized + { + get + { + return Vector4.Normalize(this); + } + } + public float magnitude + { + get + { + return Mathf.Sqrt(Vector4.Dot(this, this)); + } + } + public float sqrMagnitude + { + get + { + return Vector4.Dot(this, this); + } + } + public static Vector4 zero + { + get + { + return new Vector4(0f, 0f, 0f, 0f); + } + } + public static Vector4 one + { + get + { + return new Vector4(1f, 1f, 1f, 1f); + } + } + public Vector4(float x, float y, float z, float w) + { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + public Vector4(float x, float y, float z) + { + this.x = x; + this.y = y; + this.z = z; + this.w = 0f; + } + public Vector4(float x, float y) + { + this.x = x; + this.y = y; + this.z = 0f; + this.w = 0f; + } + public void Set(float new_x, float new_y, float new_z, float new_w) + { + this.x = new_x; + this.y = new_y; + this.z = new_z; + this.w = new_w; + } + public static Vector4 Lerp(Vector4 from, Vector4 to, float t) + { + t = Mathf.Clamp01(t); + return new Vector4(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t, from.z + (to.z - from.z) * t, from.w + (to.w - from.w) * t); + } + public static Vector4 MoveTowards(Vector4 current, Vector4 target, float maxDistanceDelta) + { + Vector4 a = target - current; + float magnitude = a.magnitude; + if (magnitude <= maxDistanceDelta || magnitude == 0f) + { + return target; + } + return current + a / magnitude * maxDistanceDelta; + } + public static Vector4 Scale(Vector4 a, Vector4 b) + { + return new Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); + } + public void Scale(Vector4 scale) + { + this.x *= scale.x; + this.y *= scale.y; + this.z *= scale.z; + this.w *= scale.w; + } + public override int GetHashCode() + { + return this.x.GetHashCode() ^ this.y.GetHashCode() << 2 ^ this.z.GetHashCode() >> 2 ^ this.w.GetHashCode() >> 1; + } + public override bool Equals(object other) + { + if (!(other is Vector4)) + { + return false; + } + Vector4 vector = (Vector4)other; + return this.x.Equals(vector.x) && this.y.Equals(vector.y) && this.z.Equals(vector.z) && this.w.Equals(vector.w); + } + public static Vector4 Normalize(Vector4 a) + { + float num = Vector4.Magnitude(a); + if (num > 1E-05f) + { + return a / num; + } + return Vector4.zero; + } + public void Normalize() + { + float num = Vector4.Magnitude(this); + if (num > 1E-05f) + { + this /= num; + } + else + { + this = Vector4.zero; + } + } + public override string ToString() + { + return UnityString.Format("({0:F1}, {1:F1}, {2:F1}, {3:F1})", new object[] + { + this.x, + this.y, + this.z, + this.w + }); + } + public string ToString(string format) + { + return UnityString.Format("({0}, {1}, {2}, {3})", new object[] + { + this.x.ToString(format), + this.y.ToString(format), + this.z.ToString(format), + this.w.ToString(format) + }); + } + public static float Dot(Vector4 a, Vector4 b) + { + return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; + } + public static Vector4 Project(Vector4 a, Vector4 b) + { + return b * Vector4.Dot(a, b) / Vector4.Dot(b, b); + } + public static float Distance(Vector4 a, Vector4 b) + { + return Vector4.Magnitude(a - b); + } + public static float Magnitude(Vector4 a) + { + return Mathf.Sqrt(Vector4.Dot(a, a)); + } + public static float SqrMagnitude(Vector4 a) + { + return Vector4.Dot(a, a); + } + public float SqrMagnitude() + { + return Vector4.Dot(this, this); + } + public static Vector4 Min(Vector4 lhs, Vector4 rhs) + { + return new Vector4(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z), Mathf.Min(lhs.w, rhs.w)); + } + public static Vector4 Max(Vector4 lhs, Vector4 rhs) + { + return new Vector4(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z), Mathf.Max(lhs.w, rhs.w)); + } + public static Vector4 operator +(Vector4 a, Vector4 b) + { + return new Vector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + } + public static Vector4 operator -(Vector4 a, Vector4 b) + { + return new Vector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + } + public static Vector4 operator -(Vector4 a) + { + return new Vector4(-a.x, -a.y, -a.z, -a.w); + } + public static Vector4 operator *(Vector4 a, float d) + { + return new Vector4(a.x * d, a.y * d, a.z * d, a.w * d); + } + public static Vector4 operator *(float d, Vector4 a) + { + return new Vector4(a.x * d, a.y * d, a.z * d, a.w * d); + } + public static Vector4 operator /(Vector4 a, float d) + { + return new Vector4(a.x / d, a.y / d, a.z / d, a.w / d); + } + public static bool operator ==(Vector4 lhs, Vector4 rhs) + { + return Vector4.SqrMagnitude(lhs - rhs) < 9.99999944E-11f; + } + public static bool operator !=(Vector4 lhs, Vector4 rhs) + { + return Vector4.SqrMagnitude(lhs - rhs) >= 9.99999944E-11f; + } + public static implicit operator Vector4(Vector3 v) + { + return new Vector4(v.x, v.y, v.z, 0f); + } + public static implicit operator Vector3(Vector4 v) + { + return new Vector3(v.x, v.y, v.z); + } + public static implicit operator Vector4(Vector2 v) + { + return new Vector4(v.x, v.y, 0f, 0f); + } + public static implicit operator Vector2(Vector4 v) + { + return new Vector2(v.x, v.y); + } + } +} diff --git a/UnityEngine/UnityEngine/VerticalWrapMode.cs b/UnityEngine/UnityEngine/VerticalWrapMode.cs new file mode 100644 index 00000000..8c1bd376 --- /dev/null +++ b/UnityEngine/UnityEngine/VerticalWrapMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum VerticalWrapMode + { + Truncate, + Overflow + } +} diff --git a/UnityEngine/UnityEngine/WWW.cs b/UnityEngine/UnityEngine/WWW.cs new file mode 100644 index 00000000..622ef0e5 --- /dev/null +++ b/UnityEngine/UnityEngine/WWW.cs @@ -0,0 +1,502 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class WWW : IDisposable + { + private static readonly char[] forbiddenCharacters = new char[] + { + '\0', + '\u0001', + '\u0002', + '\u0003', + '\u0004', + '\u0005', + '\u0006', + '\a', + '\b', + '\t', + '\n', + '\v', + '\f', + '\r', + '\u000e', + '\u000f', + '\u0010', + '\u0011', + '\u0012', + '\u0013', + '\u0014', + '\u0015', + '\u0016', + '\u0017', + '\u0018', + '\u0019', + '\u001a', + '\u001b', + '\u001c', + '\u001d', + '\u001e', + '\u001f', + '\u007f' + }; + private static readonly char[] forbiddenCharactersForNames = new char[] + { + ' ' + }; + private static readonly string[] forbiddenHeaderKeys = new string[] + { + "Accept-Charset", + "Accept-Encoding", + "Access-Control-Request-Headers", + "Access-Control-Request-Method", + "Connection", + "Content-Length", + "Cookie", + "Cookie2", + "Date", + "DNT", + "Expect", + "Host", + "Keep-Alive", + "Origin", + "Referer", + "TE", + "Trailer", + "Transfer-Encoding", + "Upgrade", + "User-Agent", + "Via", + "X-Unity-Version" + }; + internal IntPtr m_Ptr; + public Dictionary responseHeaders + { + get + { + if (!this.isDone) + { + throw new UnityException("WWW is not finished downloading yet"); + } + return WWW.ParseHTTPHeaderString(this.responseHeadersString); + } + } + private extern string responseHeadersString + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public string text + { + get + { + if (!this.isDone) + { + throw new UnityException("WWW is not ready downloading yet"); + } + return this.GetTextEncoder().GetString(this.bytes, 0, this.bytes.Length); + } + } + internal static Encoding DefaultEncoding + { + get + { + return Encoding.ASCII; + } + } + [Obsolete("Please use WWW.text instead")] + public string data + { + get + { + return this.text; + } + } + public extern byte[] bytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int size + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string error + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public Texture2D texture + { + get + { + return this.GetTexture(false); + } + } + public Texture2D textureNonReadable + { + get + { + return this.GetTexture(true); + } + } + public AudioClip audioClip + { + get + { + return this.GetAudioClip(true); + } + } + public extern MovieTexture movie + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isDone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float progress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float uploadProgress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int bytesDownloaded + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete(".oggVorbis accessor is deprecated, use .audioClip or GetAudioClip() instead.")] + public extern AudioClip oggVorbis + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string url + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AssetBundle assetBundle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ThreadPriority threadPriority + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public WWW(string url) + { + this.InitWWW(url, null, null); + } + public WWW(string url, WWWForm form) + { + string[] array = WWW.FlattenedHeadersFrom(form.headers); + if (this.enforceWebSecurityRestrictions()) + { + WWW.CheckSecurityOnHeaders(array); + } + this.InitWWW(url, form.data, array); + } + public WWW(string url, byte[] postData) + { + this.InitWWW(url, postData, null); + } + [Obsolete("This overload is deprecated. Use the one with Dictionary argument.")] + public WWW(string url, byte[] postData, Hashtable headers) + { + string[] array = WWW.FlattenedHeadersFrom(headers); + if (this.enforceWebSecurityRestrictions()) + { + WWW.CheckSecurityOnHeaders(array); + } + this.InitWWW(url, postData, array); + } + public WWW(string url, byte[] postData, Dictionary headers) + { + string[] array = WWW.FlattenedHeadersFrom(headers); + if (this.enforceWebSecurityRestrictions()) + { + WWW.CheckSecurityOnHeaders(array); + } + this.InitWWW(url, postData, array); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern WWW(string url, int version, uint crc); + private static void CheckSecurityOnHeaders(string[] headers) + { + bool flag = Application.GetBuildUnityVersion() >= Application.GetNumericUnityVersion("4.3.0b1"); + for (int i = 0; i < headers.Length; i += 2) + { + string[] array = WWW.forbiddenHeaderKeys; + for (int j = 0; j < array.Length; j++) + { + string b = array[j]; + if (string.Equals(headers[i], b, StringComparison.CurrentCultureIgnoreCase)) + { + if (flag) + { + throw new ArgumentException("Cannot overwrite header: " + headers[i]); + } + Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); + } + } + if (headers[i].StartsWith("Sec-") || headers[i].StartsWith("Proxy-")) + { + if (flag) + { + throw new ArgumentException("Cannot overwrite header: " + headers[i]); + } + Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); + } + if (headers[i].IndexOfAny(WWW.forbiddenCharacters) > -1 || headers[i].IndexOfAny(WWW.forbiddenCharactersForNames) > -1 || headers[i + 1].IndexOfAny(WWW.forbiddenCharacters) > -1) + { + if (flag) + { + throw new ArgumentException("Cannot include control characters in a HTTP header, either as key or value."); + } + Debug.LogError("Illegal control characters in header, this will fail in 4.3 and above"); + } + } + } + private static string[] FlattenedHeadersFrom(Hashtable headers) + { + if (headers == null) + { + return null; + } + string[] array = new string[headers.Count * 2]; + int num = 0; + foreach (DictionaryEntry dictionaryEntry in headers) + { + array[num++] = dictionaryEntry.Key.ToString(); + array[num++] = dictionaryEntry.Value.ToString(); + } + return array; + } + private static string[] FlattenedHeadersFrom(Dictionary headers) + { + if (headers == null) + { + return null; + } + string[] array = new string[headers.Count * 2]; + int num = 0; + foreach (KeyValuePair current in headers) + { + array[num++] = current.Key.ToString(); + array[num++] = current.Value.ToString(); + } + return array; + } + internal static Dictionary ParseHTTPHeaderString(string input) + { + if (input == null) + { + throw new ArgumentException("input was null to ParseHTTPHeaderString"); + } + Dictionary dictionary = new Dictionary(); + StringReader stringReader = new StringReader(input); + int num = 0; + while (true) + { + string text = stringReader.ReadLine(); + if (text == null) + { + break; + } + if (num++ == 0 && text.StartsWith("HTTP")) + { + dictionary["STATUS"] = text; + } + else + { + int num2 = text.IndexOf(": "); + if (num2 != -1) + { + string key = text.Substring(0, num2).ToUpper(); + string value = text.Substring(num2 + 2); + dictionary[key] = value; + } + } + } + return dictionary; + } + public void Dispose() + { + this.DestroyWWW(true); + } + ~WWW() + { + this.DestroyWWW(false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void DestroyWWW(bool cancel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InitWWW(string url, byte[] postData, string[] iHeaders); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool enforceWebSecurityRestrictions(); + [ExcludeFromDocs] + public static string EscapeURL(string s) + { + Encoding uTF = Encoding.UTF8; + return WWW.EscapeURL(s, uTF); + } + public static string EscapeURL(string s, [DefaultValue("System.Text.Encoding.UTF8")] Encoding e) + { + if (s == null) + { + return null; + } + if (s == string.Empty) + { + return string.Empty; + } + if (e == null) + { + return null; + } + return WWWTranscoder.URLEncode(s, e); + } + [ExcludeFromDocs] + public static string UnEscapeURL(string s) + { + Encoding uTF = Encoding.UTF8; + return WWW.UnEscapeURL(s, uTF); + } + public static string UnEscapeURL(string s, [DefaultValue("System.Text.Encoding.UTF8")] Encoding e) + { + if (s == null) + { + return null; + } + if (s.IndexOf('%') == -1 && s.IndexOf('+') == -1) + { + return s; + } + return WWWTranscoder.URLDecode(s, e); + } + private Encoding GetTextEncoder() + { + string text = null; + if (this.responseHeaders.TryGetValue("CONTENT-TYPE", out text)) + { + int num = text.IndexOf("charset", StringComparison.OrdinalIgnoreCase); + if (num > -1) + { + int num2 = text.IndexOf('=', num); + if (num2 > -1) + { + string text2 = text.Substring(num2 + 1).Trim().Trim(new char[] + { + '\'', + '"' + }).Trim(); + int num3 = text2.IndexOf(';'); + if (num3 > -1) + { + text2 = text2.Substring(0, num3); + } + try + { + return Encoding.GetEncoding(text2); + } + catch (Exception) + { + Debug.Log("Unsupported encoding: '" + text2 + "'"); + } + } + } + } + return Encoding.UTF8; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Texture2D GetTexture(bool markNonReadable); + public AudioClip GetAudioClip(bool threeD) + { + return this.GetAudioClip(threeD, false); + } + public AudioClip GetAudioClip(bool threeD, bool stream) + { + return this.GetAudioClip(threeD, stream, AudioType.UNKNOWN); + } + public AudioClip GetAudioClip(bool threeD, bool stream, AudioType audioType) + { + return this.GetAudioClipInternal(threeD, stream, false, audioType); + } + public AudioClip GetAudioClipCompressed() + { + return this.GetAudioClipCompressed(true); + } + public AudioClip GetAudioClipCompressed(bool threeD) + { + return this.GetAudioClipCompressed(threeD, AudioType.UNKNOWN); + } + public AudioClip GetAudioClipCompressed(bool threeD, AudioType audioType) + { + return this.GetAudioClipInternal(threeD, false, true, audioType); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AudioClip GetAudioClipInternal(bool threeD, bool stream, bool compressed, AudioType audioType); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void LoadImageIntoTexture(Texture2D tex); + [Obsolete("All blocking WWW functions have been deprecated, please use one of the asynchronous functions instead.", true), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetURL(string url); + [Obsolete("All blocking WWW functions have been deprecated, please use one of the asynchronous functions instead.", true)] + public static Texture2D GetTextureFromURL(string url) + { + return new WWW(url).texture; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void LoadUnityWeb(); + [ExcludeFromDocs] + public static WWW LoadFromCacheOrDownload(string url, int version) + { + uint crc = 0u; + return WWW.LoadFromCacheOrDownload(url, version, crc); + } + public static WWW LoadFromCacheOrDownload(string url, int version, [DefaultValue("0")] uint crc) + { + return new WWW(url, version, crc); + } + } +} diff --git a/UnityEngine/UnityEngine/WWWForm.cs b/UnityEngine/UnityEngine/WWWForm.cs new file mode 100644 index 00000000..1e9ddb8f --- /dev/null +++ b/UnityEngine/UnityEngine/WWWForm.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class WWWForm + { + private List formData; + private List fieldNames; + private List fileNames; + private List types; + private byte[] boundary; + private bool containsFiles; + public Hashtable headers + { + get + { + Hashtable hashtable = new Hashtable(); + if (this.containsFiles) + { + hashtable["Content-Type"] = "multipart/form-data; boundary=\"" + Encoding.UTF8.GetString(this.boundary) + "\""; + } + else + { + hashtable["Content-Type"] = "application/x-www-form-urlencoded"; + } + return hashtable; + } + } + public byte[] data + { + get + { + byte[] result; + if (this.containsFiles) + { + byte[] bytes = WWW.DefaultEncoding.GetBytes("--"); + byte[] bytes2 = WWW.DefaultEncoding.GetBytes("\r\n"); + byte[] bytes3 = WWW.DefaultEncoding.GetBytes("Content-Type: "); + byte[] bytes4 = WWW.DefaultEncoding.GetBytes("Content-disposition: form-data; name=\""); + byte[] bytes5 = WWW.DefaultEncoding.GetBytes("\""); + byte[] bytes6 = WWW.DefaultEncoding.GetBytes("; filename=\""); + using (MemoryStream memoryStream = new MemoryStream(1024)) + { + for (int i = 0; i < this.formData.Count; i++) + { + memoryStream.Write(bytes2, 0, bytes2.Length); + memoryStream.Write(bytes, 0, bytes.Length); + memoryStream.Write(this.boundary, 0, this.boundary.Length); + memoryStream.Write(bytes2, 0, bytes2.Length); + memoryStream.Write(bytes3, 0, bytes3.Length); + byte[] bytes7 = Encoding.UTF8.GetBytes(this.types[i]); + memoryStream.Write(bytes7, 0, bytes7.Length); + memoryStream.Write(bytes2, 0, bytes2.Length); + memoryStream.Write(bytes4, 0, bytes4.Length); + string headerName = Encoding.UTF8.HeaderName; + string text = this.fieldNames[i]; + if (!WWWTranscoder.SevenBitClean(text, Encoding.UTF8) || text.IndexOf("=?") > -1) + { + text = string.Concat(new string[] + { + "=?", + headerName, + "?Q?", + WWWTranscoder.QPEncode(text, Encoding.UTF8), + "?=" + }); + } + byte[] bytes8 = Encoding.UTF8.GetBytes(text); + memoryStream.Write(bytes8, 0, bytes8.Length); + memoryStream.Write(bytes5, 0, bytes5.Length); + if (this.fileNames[i] != null) + { + string text2 = this.fileNames[i]; + if (!WWWTranscoder.SevenBitClean(text2, Encoding.UTF8) || text2.IndexOf("=?") > -1) + { + text2 = string.Concat(new string[] + { + "=?", + headerName, + "?Q?", + WWWTranscoder.QPEncode(text2, Encoding.UTF8), + "?=" + }); + } + byte[] bytes9 = Encoding.UTF8.GetBytes(text2); + memoryStream.Write(bytes6, 0, bytes6.Length); + memoryStream.Write(bytes9, 0, bytes9.Length); + memoryStream.Write(bytes5, 0, bytes5.Length); + } + memoryStream.Write(bytes2, 0, bytes2.Length); + memoryStream.Write(bytes2, 0, bytes2.Length); + byte[] array = this.formData[i]; + memoryStream.Write(array, 0, array.Length); + } + memoryStream.Write(bytes2, 0, bytes2.Length); + memoryStream.Write(bytes, 0, bytes.Length); + memoryStream.Write(this.boundary, 0, this.boundary.Length); + memoryStream.Write(bytes, 0, bytes.Length); + memoryStream.Write(bytes2, 0, bytes2.Length); + result = memoryStream.ToArray(); + return result; + } + } + byte[] bytes10 = WWW.DefaultEncoding.GetBytes("&"); + byte[] bytes11 = WWW.DefaultEncoding.GetBytes("="); + using (MemoryStream memoryStream2 = new MemoryStream(1024)) + { + for (int j = 0; j < this.formData.Count; j++) + { + byte[] array2 = WWWTranscoder.URLEncode(Encoding.UTF8.GetBytes(this.fieldNames[j])); + byte[] toEncode = this.formData[j]; + byte[] array3 = WWWTranscoder.URLEncode(toEncode); + if (j > 0) + { + memoryStream2.Write(bytes10, 0, bytes10.Length); + } + memoryStream2.Write(array2, 0, array2.Length); + memoryStream2.Write(bytes11, 0, bytes11.Length); + memoryStream2.Write(array3, 0, array3.Length); + } + result = memoryStream2.ToArray(); + } + return result; + } + } + public WWWForm() + { + this.formData = new List(); + this.fieldNames = new List(); + this.fileNames = new List(); + this.types = new List(); + this.boundary = new byte[40]; + for (int i = 0; i < 40; i++) + { + int num = Random.Range(48, 110); + if (num > 57) + { + num += 7; + } + if (num > 90) + { + num += 6; + } + this.boundary[i] = (byte)num; + } + } + [ExcludeFromDocs] + public void AddField(string fieldName, string value) + { + Encoding uTF = Encoding.UTF8; + this.AddField(fieldName, value, uTF); + } + public void AddField(string fieldName, string value, [DefaultValue("System.Text.Encoding.UTF8")] Encoding e) + { + this.fieldNames.Add(fieldName); + this.fileNames.Add(null); + this.formData.Add(e.GetBytes(value)); + this.types.Add("text/plain; charset=\"" + e.WebName + "\""); + } + public void AddField(string fieldName, int i) + { + this.AddField(fieldName, i.ToString()); + } + [ExcludeFromDocs] + public void AddBinaryData(string fieldName, byte[] contents, string fileName) + { + string mimeType = null; + this.AddBinaryData(fieldName, contents, fileName, mimeType); + } + [ExcludeFromDocs] + public void AddBinaryData(string fieldName, byte[] contents) + { + string mimeType = null; + string fileName = null; + this.AddBinaryData(fieldName, contents, fileName, mimeType); + } + public void AddBinaryData(string fieldName, byte[] contents, [DefaultValue("null")] string fileName, [DefaultValue("null")] string mimeType) + { + this.containsFiles = true; + bool flag = contents.Length > 8 && contents[0] == 137 && contents[1] == 80 && contents[2] == 78 && contents[3] == 71 && contents[4] == 13 && contents[5] == 10 && contents[6] == 26 && contents[7] == 10; + if (fileName == null) + { + fileName = fieldName + ((!flag) ? ".dat" : ".png"); + } + if (mimeType == null) + { + if (flag) + { + mimeType = "image/png"; + } + else + { + mimeType = "application/octet-stream"; + } + } + this.fieldNames.Add(fieldName); + this.fileNames.Add(fileName); + this.formData.Add(contents); + this.types.Add(mimeType); + } + } +} diff --git a/UnityEngine/UnityEngine/WWWTranscoder.cs b/UnityEngine/UnityEngine/WWWTranscoder.cs new file mode 100644 index 00000000..b3fb5a9a --- /dev/null +++ b/UnityEngine/UnityEngine/WWWTranscoder.cs @@ -0,0 +1,200 @@ +using System; +using System.IO; +using System.Text; +using UnityEngine.Internal; +namespace UnityEngine +{ + internal sealed class WWWTranscoder + { + private static byte[] ucHexChars = WWW.DefaultEncoding.GetBytes("0123456789ABCDEF"); + private static byte[] lcHexChars = WWW.DefaultEncoding.GetBytes("0123456789abcdef"); + private static byte urlEscapeChar = 37; + private static byte urlSpace = 43; + private static byte[] urlForbidden = WWW.DefaultEncoding.GetBytes("@&;:<>=?\"'/\\!#%+$,{}|^[]`"); + private static byte qpEscapeChar = 61; + private static byte qpSpace = 95; + private static byte[] qpForbidden = WWW.DefaultEncoding.GetBytes("&;=?\"'%+_"); + private static byte Hex2Byte(byte[] b, int offset) + { + byte b2 = 0; + for (int i = offset; i < offset + 2; i++) + { + b2 *= 16; + int num = (int)b[i]; + if (num >= 48 && num <= 57) + { + num -= 48; + } + else + { + if (num >= 65 && num <= 75) + { + num -= 55; + } + else + { + if (num >= 97 && num <= 102) + { + num -= 87; + } + } + } + if (num > 15) + { + return 63; + } + b2 += (byte)num; + } + return b2; + } + private static byte[] Byte2Hex(byte b, byte[] hexChars) + { + return new byte[] + { + hexChars[b >> 4], + hexChars[(int)(b & 15)] + }; + } + [ExcludeFromDocs] + public static string URLEncode(string toEncode) + { + Encoding uTF = Encoding.UTF8; + return WWWTranscoder.URLEncode(toEncode, uTF); + } + public static string URLEncode(string toEncode, [DefaultValue("Encoding.UTF8")] Encoding e) + { + byte[] array = WWWTranscoder.Encode(e.GetBytes(toEncode), WWWTranscoder.urlEscapeChar, WWWTranscoder.urlSpace, WWWTranscoder.urlForbidden, false); + return WWW.DefaultEncoding.GetString(array, 0, array.Length); + } + public static byte[] URLEncode(byte[] toEncode) + { + return WWWTranscoder.Encode(toEncode, WWWTranscoder.urlEscapeChar, WWWTranscoder.urlSpace, WWWTranscoder.urlForbidden, false); + } + [ExcludeFromDocs] + public static string QPEncode(string toEncode) + { + Encoding uTF = Encoding.UTF8; + return WWWTranscoder.QPEncode(toEncode, uTF); + } + public static string QPEncode(string toEncode, [DefaultValue("Encoding.UTF8")] Encoding e) + { + byte[] array = WWWTranscoder.Encode(e.GetBytes(toEncode), WWWTranscoder.qpEscapeChar, WWWTranscoder.qpSpace, WWWTranscoder.qpForbidden, true); + return WWW.DefaultEncoding.GetString(array, 0, array.Length); + } + public static byte[] QPEncode(byte[] toEncode) + { + return WWWTranscoder.Encode(toEncode, WWWTranscoder.qpEscapeChar, WWWTranscoder.qpSpace, WWWTranscoder.qpForbidden, true); + } + public static byte[] Encode(byte[] input, byte escapeChar, byte space, byte[] forbidden, bool uppercase) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream(input.Length * 2)) + { + for (int i = 0; i < input.Length; i++) + { + if (input[i] == 32) + { + memoryStream.WriteByte(space); + } + else + { + if (input[i] < 32 || input[i] > 126 || WWWTranscoder.ByteArrayContains(forbidden, input[i])) + { + memoryStream.WriteByte(escapeChar); + memoryStream.Write(WWWTranscoder.Byte2Hex(input[i], (!uppercase) ? WWWTranscoder.lcHexChars : WWWTranscoder.ucHexChars), 0, 2); + } + else + { + memoryStream.WriteByte(input[i]); + } + } + } + result = memoryStream.ToArray(); + } + return result; + } + private static bool ByteArrayContains(byte[] array, byte b) + { + return Array.IndexOf(array, b) != -1; + } + [ExcludeFromDocs] + public static string URLDecode(string toEncode) + { + Encoding uTF = Encoding.UTF8; + return WWWTranscoder.URLDecode(toEncode, uTF); + } + public static string URLDecode(string toEncode, [DefaultValue("Encoding.UTF8")] Encoding e) + { + byte[] array = WWWTranscoder.Decode(WWW.DefaultEncoding.GetBytes(toEncode), WWWTranscoder.urlEscapeChar, WWWTranscoder.urlSpace); + return e.GetString(array, 0, array.Length); + } + public static byte[] URLDecode(byte[] toEncode) + { + return WWWTranscoder.Decode(toEncode, WWWTranscoder.urlEscapeChar, WWWTranscoder.urlSpace); + } + [ExcludeFromDocs] + public static string QPDecode(string toEncode) + { + Encoding uTF = Encoding.UTF8; + return WWWTranscoder.QPDecode(toEncode, uTF); + } + public static string QPDecode(string toEncode, [DefaultValue("Encoding.UTF8")] Encoding e) + { + byte[] array = WWWTranscoder.Decode(WWW.DefaultEncoding.GetBytes(toEncode), WWWTranscoder.qpEscapeChar, WWWTranscoder.qpSpace); + return e.GetString(array, 0, array.Length); + } + public static byte[] QPDecode(byte[] toEncode) + { + return WWWTranscoder.Decode(toEncode, WWWTranscoder.qpEscapeChar, WWWTranscoder.qpSpace); + } + public static byte[] Decode(byte[] input, byte escapeChar, byte space) + { + byte[] result; + using (MemoryStream memoryStream = new MemoryStream(input.Length)) + { + for (int i = 0; i < input.Length; i++) + { + if (input[i] == space) + { + memoryStream.WriteByte(32); + } + else + { + if (input[i] == escapeChar && i + 2 < input.Length) + { + i++; + memoryStream.WriteByte(WWWTranscoder.Hex2Byte(input, i++)); + } + else + { + memoryStream.WriteByte(input[i]); + } + } + } + result = memoryStream.ToArray(); + } + return result; + } + [ExcludeFromDocs] + public static bool SevenBitClean(string s) + { + Encoding uTF = Encoding.UTF8; + return WWWTranscoder.SevenBitClean(s, uTF); + } + public static bool SevenBitClean(string s, [DefaultValue("Encoding.UTF8")] Encoding e) + { + return WWWTranscoder.SevenBitClean(e.GetBytes(s)); + } + public static bool SevenBitClean(byte[] input) + { + for (int i = 0; i < input.Length; i++) + { + if (input[i] < 32 || input[i] > 126) + { + return false; + } + } + return true; + } + } +} diff --git a/UnityEngine/UnityEngine/WaitForEndOfFrame.cs b/UnityEngine/UnityEngine/WaitForEndOfFrame.cs new file mode 100644 index 00000000..44e94d47 --- /dev/null +++ b/UnityEngine/UnityEngine/WaitForEndOfFrame.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class WaitForEndOfFrame : YieldInstruction + { + } +} diff --git a/UnityEngine/UnityEngine/WaitForFixedUpdate.cs b/UnityEngine/UnityEngine/WaitForFixedUpdate.cs new file mode 100644 index 00000000..76dc06b9 --- /dev/null +++ b/UnityEngine/UnityEngine/WaitForFixedUpdate.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public sealed class WaitForFixedUpdate : YieldInstruction + { + } +} diff --git a/UnityEngine/UnityEngine/WaitForSeconds.cs b/UnityEngine/UnityEngine/WaitForSeconds.cs new file mode 100644 index 00000000..bcc85166 --- /dev/null +++ b/UnityEngine/UnityEngine/WaitForSeconds.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public sealed class WaitForSeconds : YieldInstruction + { + internal float m_Seconds; + public WaitForSeconds(float seconds) + { + this.m_Seconds = seconds; + } + } +} diff --git a/UnityEngine/UnityEngine/WeakListenerBindings.cs b/UnityEngine/UnityEngine/WeakListenerBindings.cs new file mode 100644 index 00000000..60a55c92 --- /dev/null +++ b/UnityEngine/UnityEngine/WeakListenerBindings.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + internal sealed class WeakListenerBindings + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void InvokeCallbacks(object inst, GCHandle gchandle, object[] parameters); + } +} diff --git a/UnityEngine/UnityEngine/WebCamDevice.cs b/UnityEngine/UnityEngine/WebCamDevice.cs new file mode 100644 index 00000000..dd05d4fa --- /dev/null +++ b/UnityEngine/UnityEngine/WebCamDevice.cs @@ -0,0 +1,23 @@ +using System; +namespace UnityEngine +{ + public struct WebCamDevice + { + internal string m_Name; + internal int m_Flags; + public string name + { + get + { + return this.m_Name; + } + } + public bool isFrontFacing + { + get + { + return (this.m_Flags & 1) == 1; + } + } + } +} diff --git a/UnityEngine/UnityEngine/WebCamFlags.cs b/UnityEngine/UnityEngine/WebCamFlags.cs new file mode 100644 index 00000000..644232ae --- /dev/null +++ b/UnityEngine/UnityEngine/WebCamFlags.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + public enum WebCamFlags + { + FrontFacing = 1 + } +} diff --git a/UnityEngine/UnityEngine/WebCamTexture.cs b/UnityEngine/UnityEngine/WebCamTexture.cs new file mode 100644 index 00000000..573561ca --- /dev/null +++ b/UnityEngine/UnityEngine/WebCamTexture.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + public sealed class WebCamTexture : Texture + { + public extern bool isPlaying + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string deviceName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float requestedFPS + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int requestedWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int requestedHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isReadable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern WebCamDevice[] devices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int videoRotationAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool videoVerticallyMirrored + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool didUpdateThisFrame + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public WebCamTexture(string deviceName, int requestedWidth, int requestedHeight, int requestedFPS) + { + WebCamTexture.Internal_CreateWebCamTexture(this, deviceName, requestedWidth, requestedHeight, requestedFPS); + } + public WebCamTexture(string deviceName, int requestedWidth, int requestedHeight) + { + WebCamTexture.Internal_CreateWebCamTexture(this, deviceName, requestedWidth, requestedHeight, 0); + } + public WebCamTexture(string deviceName) + { + WebCamTexture.Internal_CreateWebCamTexture(this, deviceName, 0, 0, 0); + } + public WebCamTexture(int requestedWidth, int requestedHeight, int requestedFPS) + { + WebCamTexture.Internal_CreateWebCamTexture(this, string.Empty, requestedWidth, requestedHeight, requestedFPS); + } + public WebCamTexture(int requestedWidth, int requestedHeight) + { + WebCamTexture.Internal_CreateWebCamTexture(this, string.Empty, requestedWidth, requestedHeight, 0); + } + public WebCamTexture() + { + WebCamTexture.Internal_CreateWebCamTexture(this, string.Empty, 0, 0, 0); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateWebCamTexture([Writable] WebCamTexture self, string scriptingDevice, int requestedWidth, int requestedHeight, int maxFramerate); + public void Play() + { + WebCamTexture.INTERNAL_CALL_Play(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Play(WebCamTexture self); + public void Pause() + { + WebCamTexture.INTERNAL_CALL_Pause(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Pause(WebCamTexture self); + public void Stop() + { + WebCamTexture.INTERNAL_CALL_Stop(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Stop(WebCamTexture self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void MarkNonReadable(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color GetPixel(int x, int y); + public Color[] GetPixels() + { + return this.GetPixels(0, 0, this.width, this.height); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color[] GetPixels(int x, int y, int blockWidth, int blockHeight); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Color32[] GetPixels32([DefaultValue("null")] Color32[] colors); + [ExcludeFromDocs] + public Color32[] GetPixels32() + { + Color32[] colors = null; + return this.GetPixels32(colors); + } + } +} diff --git a/UnityEngine/UnityEngine/WheelCollider.cs b/UnityEngine/UnityEngine/WheelCollider.cs new file mode 100644 index 00000000..181530ab --- /dev/null +++ b/UnityEngine/UnityEngine/WheelCollider.cs @@ -0,0 +1,153 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class WheelCollider : Collider + { + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float suspensionDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public JointSpring suspensionSpring + { + get + { + JointSpring result; + this.INTERNAL_get_suspensionSpring(out result); + return result; + } + set + { + this.INTERNAL_set_suspensionSpring(ref value); + } + } + public extern float mass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public WheelFrictionCurve forwardFriction + { + get + { + WheelFrictionCurve result; + this.INTERNAL_get_forwardFriction(out result); + return result; + } + set + { + this.INTERNAL_set_forwardFriction(ref value); + } + } + public WheelFrictionCurve sidewaysFriction + { + get + { + WheelFrictionCurve result; + this.INTERNAL_get_sidewaysFriction(out result); + return result; + } + set + { + this.INTERNAL_set_sidewaysFriction(ref value); + } + } + public extern float motorTorque + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float brakeTorque + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float steerAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isGrounded + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float rpm + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_suspensionSpring(out JointSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_suspensionSpring(ref JointSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_forwardFriction(out WheelFrictionCurve value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_forwardFriction(ref WheelFrictionCurve value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_sidewaysFriction(out WheelFrictionCurve value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_sidewaysFriction(ref WheelFrictionCurve value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetGroundHit(out WheelHit hit); + } +} diff --git a/UnityEngine/UnityEngine/WheelFrictionCurve.cs b/UnityEngine/UnityEngine/WheelFrictionCurve.cs new file mode 100644 index 00000000..73c5b627 --- /dev/null +++ b/UnityEngine/UnityEngine/WheelFrictionCurve.cs @@ -0,0 +1,67 @@ +using System; +namespace UnityEngine +{ + public struct WheelFrictionCurve + { + private float m_ExtremumSlip; + private float m_ExtremumValue; + private float m_AsymptoteSlip; + private float m_AsymptoteValue; + private float m_Stiffness; + public float extremumSlip + { + get + { + return this.m_ExtremumSlip; + } + set + { + this.m_ExtremumSlip = value; + } + } + public float extremumValue + { + get + { + return this.m_ExtremumValue; + } + set + { + this.m_ExtremumValue = value; + } + } + public float asymptoteSlip + { + get + { + return this.m_AsymptoteSlip; + } + set + { + this.m_AsymptoteSlip = value; + } + } + public float asymptoteValue + { + get + { + return this.m_AsymptoteValue; + } + set + { + this.m_AsymptoteValue = value; + } + } + public float stiffness + { + get + { + return this.m_Stiffness; + } + set + { + this.m_Stiffness = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/WheelHit.cs b/UnityEngine/UnityEngine/WheelHit.cs new file mode 100644 index 00000000..46e6faf1 --- /dev/null +++ b/UnityEngine/UnityEngine/WheelHit.cs @@ -0,0 +1,103 @@ +using System; +namespace UnityEngine +{ + public struct WheelHit + { + private Vector3 m_Point; + private Vector3 m_Normal; + private Vector3 m_ForwardDir; + private Vector3 m_SidewaysDir; + private float m_Force; + private float m_ForwardSlip; + private float m_SidewaysSlip; + private Collider m_Collider; + public Collider collider + { + get + { + return this.m_Collider; + } + set + { + this.m_Collider = value; + } + } + public Vector3 point + { + get + { + return this.m_Point; + } + set + { + this.m_Point = value; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + set + { + this.m_Normal = value; + } + } + public Vector3 forwardDir + { + get + { + return this.m_ForwardDir; + } + set + { + this.m_ForwardDir = value; + } + } + public Vector3 sidewaysDir + { + get + { + return this.m_SidewaysDir; + } + set + { + this.m_SidewaysDir = value; + } + } + public float force + { + get + { + return this.m_Force; + } + set + { + this.m_Force = value; + } + } + public float forwardSlip + { + get + { + return this.m_ForwardSlip; + } + set + { + this.m_Force = this.m_ForwardSlip; + } + } + public float sidewaysSlip + { + get + { + return this.m_SidewaysSlip; + } + set + { + this.m_SidewaysSlip = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/WheelJoint2D.cs b/UnityEngine/UnityEngine/WheelJoint2D.cs new file mode 100644 index 00000000..b236c4dc --- /dev/null +++ b/UnityEngine/UnityEngine/WheelJoint2D.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class WheelJoint2D : AnchoredJoint2D + { + public JointSuspension2D suspension + { + get + { + JointSuspension2D result; + this.INTERNAL_get_suspension(out result); + return result; + } + set + { + this.INTERNAL_set_suspension(ref value); + } + } + public extern bool useMotor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public JointMotor2D motor + { + get + { + JointMotor2D result; + this.INTERNAL_get_motor(out result); + return result; + } + set + { + this.INTERNAL_set_motor(ref value); + } + } + public extern float jointTranslation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float jointSpeed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_suspension(out JointSuspension2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_suspension(ref JointSuspension2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_motor(out JointMotor2D value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_motor(ref JointMotor2D value); + public float GetMotorTorque(float timeStep) + { + return WheelJoint2D.INTERNAL_CALL_GetMotorTorque(this, timeStep); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern float INTERNAL_CALL_GetMotorTorque(WheelJoint2D self, float timeStep); + } +} diff --git a/UnityEngine/UnityEngine/WindZone.cs b/UnityEngine/UnityEngine/WindZone.cs new file mode 100644 index 00000000..a6f6b47e --- /dev/null +++ b/UnityEngine/UnityEngine/WindZone.cs @@ -0,0 +1,62 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class WindZone : Component + { + public extern WindZoneMode mode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float radius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float windMain + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float windTurbulence + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float windPulseMagnitude + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float windPulseFrequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/WindZoneMode.cs b/UnityEngine/UnityEngine/WindZoneMode.cs new file mode 100644 index 00000000..2eb8182d --- /dev/null +++ b/UnityEngine/UnityEngine/WindZoneMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + internal enum WindZoneMode + { + Directional, + Spherical + } +} diff --git a/UnityEngine/UnityEngine/WrapMode.cs b/UnityEngine/UnityEngine/WrapMode.cs new file mode 100644 index 00000000..5243007d --- /dev/null +++ b/UnityEngine/UnityEngine/WrapMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum WrapMode + { + Once = 1, + Loop, + PingPong = 4, + Default = 0, + ClampForever = 8, + Clamp = 1 + } +} diff --git a/UnityEngine/UnityEngine/WrapperlessIcall.cs b/UnityEngine/UnityEngine/WrapperlessIcall.cs new file mode 100644 index 00000000..2a88a7bf --- /dev/null +++ b/UnityEngine/UnityEngine/WrapperlessIcall.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + internal class WrapperlessIcall : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/WritableAttribute.cs b/UnityEngine/UnityEngine/WritableAttribute.cs new file mode 100644 index 00000000..3f98b148 --- /dev/null +++ b/UnityEngine/UnityEngine/WritableAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] + internal class WritableAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/YieldInstruction.cs b/UnityEngine/UnityEngine/YieldInstruction.cs new file mode 100644 index 00000000..3cff5055 --- /dev/null +++ b/UnityEngine/UnityEngine/YieldInstruction.cs @@ -0,0 +1,9 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + public class YieldInstruction + { + } +} diff --git a/UnityEngine/UnityEngine/_AndroidJNIHelper.cs b/UnityEngine/UnityEngine/_AndroidJNIHelper.cs new file mode 100644 index 00000000..23519826 --- /dev/null +++ b/UnityEngine/UnityEngine/_AndroidJNIHelper.cs @@ -0,0 +1,792 @@ +using System; +using System.Text; +namespace UnityEngine +{ + internal sealed class _AndroidJNIHelper + { + public static IntPtr CreateJavaProxy(int delegateHandle, AndroidJavaProxy proxy) + { + return AndroidReflection.NewProxyInstance(delegateHandle, proxy.javaInterface.GetRawClass()); + } + public static IntPtr CreateJavaRunnable(AndroidJavaRunnable jrunnable) + { + return AndroidJNIHelper.CreateJavaProxy(new AndroidJavaRunnableProxy(jrunnable)); + } + public static IntPtr InvokeJavaProxyMethod(AndroidJavaProxy proxy, IntPtr jmethodName, IntPtr jargs) + { + int num = 0; + if (jargs != IntPtr.Zero) + { + num = AndroidJNISafe.GetArrayLength(jargs); + } + AndroidJavaObject[] array = new AndroidJavaObject[num]; + for (int i = 0; i < num; i++) + { + IntPtr objectArrayElement = AndroidJNISafe.GetObjectArrayElement(jargs, i); + array[i] = ((!(objectArrayElement != IntPtr.Zero)) ? null : new AndroidJavaObject(objectArrayElement)); + } + IntPtr result; + using (AndroidJavaObject androidJavaObject = proxy.Invoke(AndroidJNI.GetStringUTFChars(jmethodName), array)) + { + if (androidJavaObject == null) + { + result = IntPtr.Zero; + } + else + { + result = AndroidJNI.NewLocalRef(androidJavaObject.GetRawObject()); + } + } + return result; + } + public static jvalue[] CreateJNIArgArray(object[] args) + { + jvalue[] array = new jvalue[args.GetLength(0)]; + int num = 0; + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + if (obj == null) + { + array[num].l = IntPtr.Zero; + } + else + { + if (obj.GetType().IsPrimitive) + { + if (obj is int) + { + array[num].i = (int)obj; + } + else + { + if (obj is bool) + { + array[num].z = (bool)obj; + } + else + { + if (obj is byte) + { + array[num].b = (byte)obj; + } + else + { + if (obj is short) + { + array[num].s = (short)obj; + } + else + { + if (obj is long) + { + array[num].j = (long)obj; + } + else + { + if (obj is float) + { + array[num].f = (float)obj; + } + else + { + if (obj is double) + { + array[num].d = (double)obj; + } + else + { + if (obj is char) + { + array[num].c = (char)obj; + } + } + } + } + } + } + } + } + } + else + { + if (obj is string) + { + array[num].l = AndroidJNISafe.NewStringUTF((string)obj); + } + else + { + if (obj is AndroidJavaClass) + { + array[num].l = ((AndroidJavaClass)obj).GetRawClass(); + } + else + { + if (obj is AndroidJavaObject) + { + array[num].l = ((AndroidJavaObject)obj).GetRawObject(); + } + else + { + if (obj is Array) + { + array[num].l = _AndroidJNIHelper.ConvertToJNIArray((Array)obj); + } + else + { + if (obj is AndroidJavaProxy) + { + array[num].l = AndroidJNIHelper.CreateJavaProxy((AndroidJavaProxy)obj); + } + else + { + if (!(obj is AndroidJavaRunnable)) + { + throw new Exception("JNI; Unknown argument type '" + obj.GetType() + "'"); + } + array[num].l = AndroidJNIHelper.CreateJavaRunnable((AndroidJavaRunnable)obj); + } + } + } + } + } + } + } + num++; + } + return array; + } + public static object UnboxArray(AndroidJavaObject obj) + { + if (obj == null) + { + return null; + } + AndroidJavaClass androidJavaClass = new AndroidJavaClass("java/lang/reflect/Array"); + AndroidJavaObject androidJavaObject = obj.Call("getClass", new object[0]); + AndroidJavaObject androidJavaObject2 = androidJavaObject.Call("getComponentType", new object[0]); + string text = androidJavaObject2.Call("getName", new object[0]); + int num = androidJavaClass.Call("getLength", new object[] + { + obj + }); + Array array; + if (androidJavaObject2.Call("IsPrimitive", new object[0])) + { + if ("I" == text) + { + array = new int[num]; + } + else + { + if ("Z" == text) + { + array = new bool[num]; + } + else + { + if ("B" == text) + { + array = new byte[num]; + } + else + { + if ("S" == text) + { + array = new short[num]; + } + else + { + if ("L" == text) + { + array = new long[num]; + } + else + { + if ("F" == text) + { + array = new float[num]; + } + else + { + if ("D" == text) + { + array = new double[num]; + } + else + { + if (!("C" == text)) + { + throw new Exception("JNI; Unknown argument type '" + text + "'"); + } + array = new char[num]; + } + } + } + } + } + } + } + } + else + { + if ("java.lang.String" == text) + { + array = new string[num]; + } + else + { + if ("java.lang.Class" == text) + { + array = new AndroidJavaClass[num]; + } + else + { + array = new AndroidJavaObject[num]; + } + } + } + for (int i = 0; i < num; i++) + { + array.SetValue(_AndroidJNIHelper.Unbox(androidJavaClass.CallStatic("get", new object[] + { + obj, + i + })), i); + } + return array; + } + public static object Unbox(AndroidJavaObject obj) + { + if (obj == null) + { + return null; + } + AndroidJavaObject androidJavaObject = obj.Call("getClass", new object[0]); + string b = androidJavaObject.Call("getName", new object[0]); + if ("java.lang.Integer" == b) + { + return obj.Call("intValue", new object[0]); + } + if ("java.lang.Boolean" == b) + { + return obj.Call("booleanValue", new object[0]); + } + if ("java.lang.Byte" == b) + { + return obj.Call("byteValue", new object[0]); + } + if ("java.lang.Short" == b) + { + return obj.Call("shortValue", new object[0]); + } + if ("java.lang.Long" == b) + { + return obj.Call("longValue", new object[0]); + } + if ("java.lang.Float" == b) + { + return obj.Call("floatValue", new object[0]); + } + if ("java.lang.Double" == b) + { + return obj.Call("doubleValue", new object[0]); + } + if ("java.lang.Character" == b) + { + return obj.Call("charValue", new object[0]); + } + if ("java.lang.String" == b) + { + return obj.Call("toString", new object[0]); + } + if ("java.lang.Class" == b) + { + return new AndroidJavaClass(obj.GetRawObject()); + } + if (androidJavaObject.Call("isArray", new object[0])) + { + return _AndroidJNIHelper.UnboxArray(obj); + } + return obj; + } + public static AndroidJavaObject Box(object obj) + { + if (obj == null) + { + return null; + } + if (obj.GetType().IsPrimitive) + { + if (obj is int) + { + return new AndroidJavaObject("java.lang.Integer", new object[] + { + (int)obj + }); + } + if (obj is bool) + { + return new AndroidJavaObject("java.lang.Boolean", new object[] + { + (bool)obj + }); + } + if (obj is byte) + { + return new AndroidJavaObject("java.lang.Byte", new object[] + { + (byte)obj + }); + } + if (obj is short) + { + return new AndroidJavaObject("java.lang.Short", new object[] + { + (short)obj + }); + } + if (obj is long) + { + return new AndroidJavaObject("java.lang.Long", new object[] + { + (long)obj + }); + } + if (obj is float) + { + return new AndroidJavaObject("java.lang.Float", new object[] + { + (float)obj + }); + } + if (obj is double) + { + return new AndroidJavaObject("java.lang.Double", new object[] + { + (double)obj + }); + } + if (obj is char) + { + return new AndroidJavaObject("java.lang.Character", new object[] + { + (char)obj + }); + } + throw new Exception("JNI; Unknown argument type '" + obj.GetType() + "'"); + } + else + { + if (obj is string) + { + return new AndroidJavaObject("java.lang.String", new object[] + { + (string)obj + }); + } + if (obj is AndroidJavaClass) + { + return new AndroidJavaObject(((AndroidJavaClass)obj).GetRawClass()); + } + if (obj is AndroidJavaObject) + { + return (AndroidJavaObject)obj; + } + if (obj is Array) + { + return AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(_AndroidJNIHelper.ConvertToJNIArray((Array)obj)); + } + if (obj is AndroidJavaProxy) + { + return AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(AndroidJNIHelper.CreateJavaProxy((AndroidJavaProxy)obj)); + } + if (obj is AndroidJavaRunnable) + { + return AndroidJavaObject.AndroidJavaObjectDeleteLocalRef(AndroidJNIHelper.CreateJavaRunnable((AndroidJavaRunnable)obj)); + } + throw new Exception("JNI; Unknown argument type '" + obj.GetType() + "'"); + } + } + public static void DeleteJNIArgArray(object[] args, jvalue[] jniArgs) + { + int num = 0; + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + if (obj is string || obj is AndroidJavaRunnable || obj is AndroidJavaProxy || obj is Array) + { + AndroidJNISafe.DeleteLocalRef(jniArgs[num].l); + } + num++; + } + } + public static IntPtr ConvertToJNIArray(Array array) + { + Type elementType = array.GetType().GetElementType(); + if (elementType.IsPrimitive) + { + if (elementType == typeof(int)) + { + return AndroidJNISafe.ToIntArray((int[])array); + } + if (elementType == typeof(bool)) + { + return AndroidJNISafe.ToBooleanArray((bool[])array); + } + if (elementType == typeof(byte)) + { + return AndroidJNISafe.ToByteArray((byte[])array); + } + if (elementType == typeof(short)) + { + return AndroidJNISafe.ToShortArray((short[])array); + } + if (elementType == typeof(long)) + { + return AndroidJNISafe.ToLongArray((long[])array); + } + if (elementType == typeof(float)) + { + return AndroidJNISafe.ToFloatArray((float[])array); + } + if (elementType == typeof(double)) + { + return AndroidJNISafe.ToDoubleArray((double[])array); + } + if (elementType == typeof(char)) + { + return AndroidJNISafe.ToCharArray((char[])array); + } + return IntPtr.Zero; + } + else + { + if (elementType == typeof(string)) + { + string[] array2 = (string[])array; + int length = array.GetLength(0); + IntPtr[] array3 = new IntPtr[length]; + for (int i = 0; i < length; i++) + { + array3[i] = AndroidJNISafe.NewStringUTF(array2[i]); + } + IntPtr intPtr = AndroidJNISafe.FindClass("java/lang/String"); + IntPtr result = AndroidJNISafe.ToObjectArray(array3, intPtr); + AndroidJNISafe.DeleteLocalRef(intPtr); + return result; + } + if (elementType == typeof(AndroidJavaObject)) + { + AndroidJavaObject[] array4 = (AndroidJavaObject[])array; + int length2 = array.GetLength(0); + IntPtr[] array5 = new IntPtr[length2]; + IntPtr intPtr2 = AndroidJNISafe.FindClass("java/lang/Object"); + IntPtr intPtr3 = IntPtr.Zero; + for (int j = 0; j < length2; j++) + { + if (array4[j] != null) + { + array5[j] = array4[j].GetRawObject(); + IntPtr rawClass = array4[j].GetRawClass(); + if (intPtr3 != rawClass) + { + if (intPtr3 == IntPtr.Zero) + { + intPtr3 = rawClass; + } + else + { + intPtr3 = intPtr2; + } + } + } + else + { + array5[j] = IntPtr.Zero; + } + } + IntPtr result2 = AndroidJNISafe.ToObjectArray(array5, intPtr3); + AndroidJNISafe.DeleteLocalRef(intPtr2); + return result2; + } + throw new Exception("JNI; Unknown array type '" + elementType + "'"); + } + } + public static ArrayType ConvertFromJNIArray(IntPtr array) + { + Type elementType = typeof(ArrayType).GetElementType(); + if (elementType.IsPrimitive) + { + if (elementType == typeof(int)) + { + return (ArrayType)((object)AndroidJNISafe.FromIntArray(array)); + } + if (elementType == typeof(bool)) + { + return (ArrayType)((object)AndroidJNISafe.FromBooleanArray(array)); + } + if (elementType == typeof(byte)) + { + return (ArrayType)((object)AndroidJNISafe.FromByteArray(array)); + } + if (elementType == typeof(short)) + { + return (ArrayType)((object)AndroidJNISafe.FromShortArray(array)); + } + if (elementType == typeof(long)) + { + return (ArrayType)((object)AndroidJNISafe.FromLongArray(array)); + } + if (elementType == typeof(float)) + { + return (ArrayType)((object)AndroidJNISafe.FromFloatArray(array)); + } + if (elementType == typeof(double)) + { + return (ArrayType)((object)AndroidJNISafe.FromDoubleArray(array)); + } + if (elementType == typeof(char)) + { + return (ArrayType)((object)AndroidJNISafe.FromCharArray(array)); + } + return default(ArrayType); + } + else + { + if (elementType == typeof(string)) + { + IntPtr[] array2 = AndroidJNISafe.FromObjectArray(array); + int length = array2.GetLength(0); + string[] array3 = new string[length]; + for (int i = 0; i < length; i++) + { + array3[i] = AndroidJNISafe.GetStringUTFChars(array2[i]); + } + return (ArrayType)((object)array3); + } + if (elementType == typeof(AndroidJavaObject)) + { + IntPtr[] array4 = AndroidJNISafe.FromObjectArray(array); + int length2 = array4.GetLength(0); + AndroidJavaObject[] array5 = new AndroidJavaObject[length2]; + for (int j = 0; j < length2; j++) + { + array5[j] = new AndroidJavaObject(array4[j]); + } + return (ArrayType)((object)array5); + } + throw new Exception("JNI: Unknown generic array type '" + elementType + "'"); + } + } + public static IntPtr GetConstructorID(IntPtr jclass, object[] args) + { + return AndroidJNIHelper.GetConstructorID(jclass, _AndroidJNIHelper.GetSignature(args)); + } + public static IntPtr GetMethodID(IntPtr jclass, string methodName, object[] args, bool isStatic) + { + return AndroidJNIHelper.GetMethodID(jclass, methodName, _AndroidJNIHelper.GetSignature(args), isStatic); + } + public static IntPtr GetMethodID(IntPtr jclass, string methodName, object[] args, bool isStatic) + { + return AndroidJNIHelper.GetMethodID(jclass, methodName, _AndroidJNIHelper.GetSignature(args), isStatic); + } + public static IntPtr GetFieldID(IntPtr jclass, string fieldName, bool isStatic) + { + return AndroidJNIHelper.GetFieldID(jclass, fieldName, _AndroidJNIHelper.GetSignature(typeof(ReturnType)), isStatic); + } + public static IntPtr GetConstructorID(IntPtr jclass, string signature) + { + IntPtr intPtr = IntPtr.Zero; + IntPtr result; + try + { + intPtr = AndroidReflection.GetConstructorMember(jclass, signature); + result = AndroidJNISafe.FromReflectedMethod(intPtr); + } + catch (Exception ex) + { + IntPtr methodID = AndroidJNISafe.GetMethodID(jclass, "", signature); + if (!(methodID != IntPtr.Zero)) + { + throw ex; + } + result = methodID; + } + finally + { + AndroidJNISafe.DeleteLocalRef(intPtr); + } + return result; + } + public static IntPtr GetMethodID(IntPtr jclass, string methodName, string signature, bool isStatic) + { + IntPtr intPtr = IntPtr.Zero; + IntPtr result; + try + { + intPtr = AndroidReflection.GetMethodMember(jclass, methodName, signature, isStatic); + result = AndroidJNISafe.FromReflectedMethod(intPtr); + } + catch (Exception ex) + { + IntPtr intPtr2 = (!isStatic) ? AndroidJNISafe.GetMethodID(jclass, methodName, signature) : AndroidJNISafe.GetStaticMethodID(jclass, methodName, signature); + if (!(intPtr2 != IntPtr.Zero)) + { + throw ex; + } + result = intPtr2; + } + finally + { + AndroidJNISafe.DeleteLocalRef(intPtr); + } + return result; + } + public static IntPtr GetFieldID(IntPtr jclass, string fieldName, string signature, bool isStatic) + { + IntPtr intPtr = IntPtr.Zero; + IntPtr result; + try + { + intPtr = AndroidReflection.GetFieldMember(jclass, fieldName, signature, isStatic); + result = AndroidJNISafe.FromReflectedField(intPtr); + } + catch (Exception ex) + { + IntPtr intPtr2 = (!isStatic) ? AndroidJNISafe.GetFieldID(jclass, fieldName, signature) : AndroidJNISafe.GetStaticFieldID(jclass, fieldName, signature); + if (!(intPtr2 != IntPtr.Zero)) + { + throw ex; + } + result = intPtr2; + } + finally + { + AndroidJNISafe.DeleteLocalRef(intPtr); + } + return result; + } + public static string GetSignature(object obj) + { + if (obj == null) + { + return "Ljava/lang/Object;"; + } + Type type = (!(obj is Type)) ? obj.GetType() : ((Type)obj); + if (type.IsPrimitive) + { + if (type.Equals(typeof(int))) + { + return "I"; + } + if (type.Equals(typeof(bool))) + { + return "Z"; + } + if (type.Equals(typeof(byte))) + { + return "B"; + } + if (type.Equals(typeof(short))) + { + return "S"; + } + if (type.Equals(typeof(long))) + { + return "J"; + } + if (type.Equals(typeof(float))) + { + return "F"; + } + if (type.Equals(typeof(double))) + { + return "D"; + } + if (type.Equals(typeof(char))) + { + return "C"; + } + return string.Empty; + } + else + { + if (type.Equals(typeof(string))) + { + return "Ljava/lang/String;"; + } + if (obj is AndroidJavaProxy) + { + AndroidJavaObject androidJavaObject = new AndroidJavaObject(((AndroidJavaProxy)obj).javaInterface.GetRawClass()); + return "L" + androidJavaObject.Call("getName", new object[0]) + ";"; + } + if (type.Equals(typeof(AndroidJavaRunnable))) + { + return "Ljava/lang/Runnable;"; + } + if (type.Equals(typeof(AndroidJavaClass))) + { + return "Ljava/lang/Class;"; + } + if (type.Equals(typeof(AndroidJavaObject))) + { + if (obj == type) + { + return "Ljava/lang/Object;"; + } + AndroidJavaObject androidJavaObject2 = (AndroidJavaObject)obj; + using (AndroidJavaObject androidJavaObject3 = androidJavaObject2.Call("getClass", new object[0])) + { + return "L" + androidJavaObject3.Call("getName", new object[0]) + ";"; + } + } + if (!typeof(Array).IsAssignableFrom(type)) + { + throw new Exception(string.Concat(new object[] + { + "JNI: Unknown signature for type '", + type, + "' (obj = ", + obj, + ") ", + (type != obj) ? "instance" : "equal" + })); + } + if (type.GetArrayRank() != 1) + { + throw new Exception("JNI: System.Array in n dimensions is not allowed"); + } + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('['); + stringBuilder.Append(_AndroidJNIHelper.GetSignature(type.GetElementType())); + return stringBuilder.ToString(); + } + } + public static string GetSignature(object[] args) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('('); + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + stringBuilder.Append(_AndroidJNIHelper.GetSignature(obj)); + } + stringBuilder.Append(")V"); + return stringBuilder.ToString(); + } + public static string GetSignature(object[] args) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append('('); + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + stringBuilder.Append(_AndroidJNIHelper.GetSignature(obj)); + } + stringBuilder.Append(')'); + stringBuilder.Append(_AndroidJNIHelper.GetSignature(typeof(ReturnType))); + return stringBuilder.ToString(); + } + } +} diff --git a/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs b/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs new file mode 100644 index 00000000..67b84410 --- /dev/null +++ b/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum iOSActivityIndicatorStyle + { + DontShow = -1, + WhiteLarge, + White, + Gray + } +} diff --git a/UnityEngine/UnityEngine/iPhone.cs b/UnityEngine/UnityEngine/iPhone.cs new file mode 100644 index 00000000..e6c2ae4f --- /dev/null +++ b/UnityEngine/UnityEngine/iPhone.cs @@ -0,0 +1,113 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + public sealed class iPhone + { + public sealed class NSError + { + private IntPtr _nativeError; + public int code + { + get + { + return iPhone.NSError.UnityNSError_Code(this._nativeError); + } + } + public string description + { + get + { + return Marshal.PtrToStringAnsi(iPhone.NSError.UnityNSError_Description(this._nativeError)); + } + } + public string reason + { + get + { + return Marshal.PtrToStringAnsi(iPhone.NSError.UnityNSError_Reason(this._nativeError)); + } + } + private NSError(IntPtr nativeError) + { + this._nativeError = nativeError; + iPhone.UnityNSObject_RetainObject(this._nativeError); + } + [DllImport("__Internal")] + private static extern int UnityNSError_Code(IntPtr errorObj); + [DllImport("__Internal")] + private static extern IntPtr UnityNSError_Description(IntPtr errorObj); + [DllImport("__Internal")] + private static extern IntPtr UnityNSError_Reason(IntPtr errorObj); + ~NSError() + { + iPhone.UnityNSObject_ReleaseObject(this._nativeError); + } + public static iPhone.NSError CreateNSError(IntPtr nativeError) + { + return (!(nativeError == IntPtr.Zero)) ? new iPhone.NSError(nativeError) : null; + } + } + public sealed class NSNotification + { + private IntPtr _nativeNotification; + public string name + { + get + { + return Marshal.PtrToStringAnsi(iPhone.NSNotification.UnityNSNotification_Name(this._nativeNotification)); + } + } + private NSNotification(IntPtr nativeNotification) + { + this._nativeNotification = nativeNotification; + iPhone.UnityNSObject_RetainObject(this._nativeNotification); + } + [DllImport("__Internal")] + private static extern IntPtr UnityNSNotification_Name(IntPtr notificationObj); + ~NSNotification() + { + iPhone.UnityNSObject_ReleaseObject(this._nativeNotification); + } + public static iPhone.NSNotification CreateNSNotification(IntPtr nativeNotification) + { + return (!(nativeNotification == IntPtr.Zero)) ? new iPhone.NSNotification(nativeNotification) : null; + } + } + public static extern iPhoneGeneration generation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string vendorIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string advertisingIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool advertisingTrackingEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [DllImport("__Internal")] + internal static extern void UnityNSObject_RetainObject(IntPtr obj); + [DllImport("__Internal")] + internal static extern void UnityNSObject_ReleaseObject(IntPtr obj); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNoBackupFlag(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetNoBackupFlag(string path); + } +} diff --git a/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs b/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs new file mode 100644 index 00000000..ccad396c --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs @@ -0,0 +1,32 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneAccelerationEvent struct is deprecated. Please use AccelerationEvent instead.")] + public struct iPhoneAccelerationEvent + { + private Vector3 m_Acceleration; + private float m_TimeDelta; + public Vector3 acceleration + { + get + { + return this.m_Acceleration; + } + } + public float deltaTime + { + get + { + return this.m_TimeDelta; + } + } + [Obsolete("timeDelta property is deprecated. Please use iPhoneAccelerationEvent.deltaTime instead.")] + public float timeDelta + { + get + { + return this.m_TimeDelta; + } + } + } +} diff --git a/UnityEngine/UnityEngine/iPhoneGeneration.cs b/UnityEngine/UnityEngine/iPhoneGeneration.cs new file mode 100644 index 00000000..a78ac728 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneGeneration.cs @@ -0,0 +1,35 @@ +using System; +namespace UnityEngine +{ + public enum iPhoneGeneration + { + Unknown, + iPhone, + iPhone3G, + iPhone3GS, + iPodTouch1Gen, + iPodTouch2Gen, + iPodTouch3Gen, + iPad1Gen, + iPhone4, + iPodTouch4Gen, + iPad2Gen, + iPhone4S, + iPad3Gen, + iPhone5, + iPodTouch5Gen, + iPadMini1Gen, + iPad4Gen, + iPhone5C, + iPhone5S, + iPad5Gen, + iPadMini2Gen, + iPhone6, + iPhone6Plus, + iPadMini3Gen, + iPadAir2, + iPhoneUnknown = 10001, + iPadUnknown, + iPodTouchUnknown + } +} diff --git a/UnityEngine/UnityEngine/iPhoneInput.cs b/UnityEngine/UnityEngine/iPhoneInput.cs new file mode 100644 index 00000000..1f80738c --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneInput.cs @@ -0,0 +1,87 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class iPhoneInput + { + [Obsolete("accelerationEvents property is deprecated. Please use Input.accelerationEvents instead.")] + public static iPhoneAccelerationEvent[] accelerationEvents + { + get + { + int accelerationEventCount = iPhoneInput.accelerationEventCount; + iPhoneAccelerationEvent[] array = new iPhoneAccelerationEvent[accelerationEventCount]; + for (int i = 0; i < accelerationEventCount; i++) + { + array[i] = iPhoneInput.GetAccelerationEvent(i); + } + return array; + } + } + [Obsolete("touches property is deprecated. Please use Input.touches instead.")] + public static iPhoneTouch[] touches + { + get + { + int touchCount = iPhoneInput.touchCount; + iPhoneTouch[] array = new iPhoneTouch[touchCount]; + for (int i = 0; i < touchCount; i++) + { + array[i] = iPhoneInput.GetTouch(i); + } + return array; + } + } + [Obsolete("touchCount property is deprecated. Please use Input.touchCount instead.")] + public static extern int touchCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("multiTouchEnabled property is deprecated. Please use Input.multiTouchEnabled instead.")] + public static extern bool multiTouchEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("accelerationEventCount property is deprecated. Please use Input.accelerationEventCount instead.")] + public static extern int accelerationEventCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("acceleration property is deprecated. Please use Input.acceleration instead.")] + public static extern Vector3 acceleration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("orientation property is deprecated. Please use Input.deviceOrientation instead.")] + public static extern iPhoneOrientation orientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("lastLocation property is deprecated. Please use Input.location.lastData instead.")] + public static extern LocationInfo lastLocation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("GetTouch method is deprecated. Please use Input.GetTouch instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern iPhoneTouch GetTouch(int index); + [Obsolete("GetAccelerationEvent method is deprecated. Please use Input.GetAccelerationEvent instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern iPhoneAccelerationEvent GetAccelerationEvent(int index); + } +} diff --git a/UnityEngine/UnityEngine/iPhoneKeyboard.cs b/UnityEngine/UnityEngine/iPhoneKeyboard.cs new file mode 100644 index 00000000..22277e97 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneKeyboard.cs @@ -0,0 +1,134 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine +{ + [Obsolete("iPhoneKeyboard class is deprecated. Please use TouchScreenKeyboard instead.")] + public sealed class iPhoneKeyboard + { + private IntPtr keyboardWrapper; + public extern string text + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool hideInput + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool active + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool done + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern Rect area + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool visible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public iPhoneKeyboard(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder) + { + this.iPhoneKeyboard_InternalConstructorHelper(new iPhoneKeyboard_InternalConstructorHelperArguments + { + text = text, + keyboardType = Convert.ToUInt32(keyboardType), + autocorrection = Convert.ToUInt32(autocorrection), + multiline = Convert.ToUInt32(multiline), + secure = Convert.ToUInt32(secure), + alert = Convert.ToUInt32(alert), + textPlaceholder = textPlaceholder + }); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~iPhoneKeyboard() + { + this.Destroy(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void iPhoneKeyboard_InternalConstructorHelper(iPhoneKeyboard_InternalConstructorHelperArguments arguments); + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert) + { + string empty = string.Empty; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure) + { + string empty = string.Empty; + bool alert = false; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + bool autocorrection = true; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + [ExcludeFromDocs] + public static iPhoneKeyboard Open(string text) + { + string empty = string.Empty; + bool alert = false; + bool secure = false; + bool multiline = false; + bool autocorrection = true; + iPhoneKeyboardType keyboardType = iPhoneKeyboardType.Default; + return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); + } + public static iPhoneKeyboard Open(string text, [DefaultValue("iPhoneKeyboardType.Default")] iPhoneKeyboardType keyboardType, [DefaultValue("true")] bool autocorrection, [DefaultValue("false")] bool multiline, [DefaultValue("false")] bool secure, [DefaultValue("false")] bool alert, [DefaultValue("\"\"")] string textPlaceholder) + { + return new iPhoneKeyboard(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); + } + } +} diff --git a/UnityEngine/UnityEngine/iPhoneKeyboardType.cs b/UnityEngine/UnityEngine/iPhoneKeyboardType.cs new file mode 100644 index 00000000..cad3ab13 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneKeyboardType.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneKeyboardType enumeration is deprecated. Please use TouchScreenKeyboardType instead.")] + public enum iPhoneKeyboardType + { + Default, + ASCIICapable, + NumbersAndPunctuation, + URL, + NumberPad, + PhonePad, + NamePhonePad, + EmailAddress + } +} diff --git a/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs b/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs new file mode 100644 index 00000000..fb5dda9a --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + internal struct iPhoneKeyboard_InternalConstructorHelperArguments + { + public string text; + public string textPlaceholder; + public uint keyboardType; + public uint autocorrection; + public uint multiline; + public uint secure; + public uint alert; + } +} diff --git a/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs b/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs new file mode 100644 index 00000000..7b4dc654 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneMovieControlMode enumeration is deprecated. Please use FullScreenMovieControlMode instead.")] + public enum iPhoneMovieControlMode + { + Full, + Minimal, + CancelOnTouch, + Hidden, + VolumeOnly = 1 + } +} diff --git a/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs b/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs new file mode 100644 index 00000000..61cc6397 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneMovieScalingMode enumeration is deprecated. Please use FullScreenMovieScalingMode instead.")] + public enum iPhoneMovieScalingMode + { + None, + AspectFit, + AspectFill, + Fill + } +} diff --git a/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs b/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs new file mode 100644 index 00000000..e0045aa3 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneNetworkReachability enumeration is deprecated. Please use NetworkReachability instead.")] + public enum iPhoneNetworkReachability + { + NotReachable, + ReachableViaCarrierDataNetwork, + ReachableViaWiFiNetwork + } +} diff --git a/UnityEngine/UnityEngine/iPhoneOrientation.cs b/UnityEngine/UnityEngine/iPhoneOrientation.cs new file mode 100644 index 00000000..f52b2015 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneOrientation.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneOrientation enumeration is deprecated. Please use DeviceOrientation instead.")] + public enum iPhoneOrientation + { + Unknown, + Portrait, + PortraitUpsideDown, + LandscapeLeft, + LandscapeRight, + FaceUp, + FaceDown + } +} diff --git a/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs b/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs new file mode 100644 index 00000000..f7fdc66a --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneScreenOrientation enumeration is deprecated. Please use ScreenOrientation instead.")] + public enum iPhoneScreenOrientation + { + Unknown, + Portrait, + PortraitUpsideDown, + LandscapeLeft, + LandscapeRight, + Landscape = 3 + } +} diff --git a/UnityEngine/UnityEngine/iPhoneSettings.cs b/UnityEngine/UnityEngine/iPhoneSettings.cs new file mode 100644 index 00000000..f0deb31e --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneSettings.cs @@ -0,0 +1,117 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class iPhoneSettings + { + [Obsolete("screenOrientation property is deprecated. Please use Screen.orientation instead.")] + public static extern iPhoneScreenOrientation screenOrientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("verticalOrientation property is deprecated. Please use Screen.orientation instead.")] + public static extern bool verticalOrientation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("screenCanDarken property is deprecated. Please use Screen.sleepTimeout instead.")] + public static extern bool screenCanDarken + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("uniqueIdentifier property is deprecated. Please use SystemInfo.deviceUniqueIdentifier instead.")] + public static extern string uniqueIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("name property is deprecated. Please use SystemInfo.deviceName instead.")] + public static extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("model property is deprecated. Please use SystemInfo.deviceModel instead.")] + public static extern string model + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("systemName property is deprecated. Please use SystemInfo.operatingSystem instead.")] + public static extern string systemName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("systemVersion property is deprecated. Please use SystemInfo.operatingSystem instead.")] + public static extern string systemVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("internetReachability property is deprecated. Please use Application.internetReachability instead.")] + public static extern iPhoneNetworkReachability internetReachability + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("generation property is deprecated. Please use iPhone.generation instead.")] + public static extern iPhoneGeneration generation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("locationServiceStatus property is deprecated. Please use Input.location.status instead.")] + public static extern LocationServiceStatus locationServiceStatus + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("locationServiceEnabledByUser property is deprecated. Please use Input.location.isEnabledByUser instead.")] + public static extern bool locationServiceEnabledByUser + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StartLocationServiceUpdates(float desiredAccuracyInMeters, float updateDistanceInMeters); + [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead.")] + public static void StartLocationServiceUpdates(float desiredAccuracyInMeters) + { + iPhoneSettings.StartLocationServiceUpdates(desiredAccuracyInMeters, 10f); + } + [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead.")] + public static void StartLocationServiceUpdates() + { + iPhoneSettings.StartLocationServiceUpdates(10f, 10f); + } + [Obsolete("StopLocationServiceUpdates method is deprecated. Please use Input.location.Stop instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopLocationServiceUpdates(); + } +} diff --git a/UnityEngine/UnityEngine/iPhoneTouch.cs b/UnityEngine/UnityEngine/iPhoneTouch.cs new file mode 100644 index 00000000..aee4b19a --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneTouch.cs @@ -0,0 +1,72 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneTouch struct is deprecated. Please use Touch instead.")] + public struct iPhoneTouch + { + private int m_FingerId; + private Vector2 m_Position; + private Vector2 m_PositionDelta; + private float m_TimeDelta; + private int m_TapCount; + private iPhoneTouchPhase m_Phase; + public int fingerId + { + get + { + return this.m_FingerId; + } + } + public Vector2 position + { + get + { + return this.m_Position; + } + } + public Vector2 deltaPosition + { + get + { + return this.m_PositionDelta; + } + } + public float deltaTime + { + get + { + return this.m_TimeDelta; + } + } + public int tapCount + { + get + { + return this.m_TapCount; + } + } + public iPhoneTouchPhase phase + { + get + { + return this.m_Phase; + } + } + [Obsolete("positionDelta property is deprecated. Please use iPhoneTouch.deltaPosition instead.")] + public Vector2 positionDelta + { + get + { + return this.m_PositionDelta; + } + } + [Obsolete("timeDelta property is deprecated. Please use iPhoneTouch.deltaTime instead.")] + public float timeDelta + { + get + { + return this.m_TimeDelta; + } + } + } +} diff --git a/UnityEngine/UnityEngine/iPhoneTouchPhase.cs b/UnityEngine/UnityEngine/iPhoneTouchPhase.cs new file mode 100644 index 00000000..f8b56d48 --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneTouchPhase.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + [Obsolete("iPhoneTouchPhase enumeration is deprecated. Please use TouchPhase instead.")] + public enum iPhoneTouchPhase + { + Began, + Moved, + Stationary, + Ended, + Canceled + } +} diff --git a/UnityEngine/UnityEngine/iPhoneUtils.cs b/UnityEngine/UnityEngine/iPhoneUtils.cs new file mode 100644 index 00000000..3349540f --- /dev/null +++ b/UnityEngine/UnityEngine/iPhoneUtils.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class iPhoneUtils + { + [Obsolete("isApplicationGenuine property is deprecated. Please use Application.genuine instead.")] + public static extern bool isApplicationGenuine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("isApplicationGenuineAvailable property is deprecated. Please use Application.genuineCheckAvailable instead.")] + public static extern bool isApplicationGenuineAvailable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovie(string path, Color bgColor, int controlMode, int scalingMode) + { + iPhoneUtils.INTERNAL_CALL_PlayMovie(path, ref bgColor, controlMode, scalingMode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_PlayMovie(string path, ref Color bgColor, int controlMode, int scalingMode); + [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovie(string path, Color bgColor, iPhoneMovieControlMode controlMode, iPhoneMovieScalingMode scalingMode) + { + iPhoneUtils.PlayMovie(path, bgColor, (int)controlMode, (int)scalingMode); + } + [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovie(string path, Color bgColor, iPhoneMovieControlMode controlMode) + { + iPhoneUtils.PlayMovie(path, bgColor, (int)controlMode, 1); + } + [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovie(string path, Color bgColor) + { + iPhoneUtils.PlayMovie(path, bgColor, 0, 1); + } + [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovieURL(string url, Color bgColor, int controlMode, int scalingMode) + { + iPhoneUtils.INTERNAL_CALL_PlayMovieURL(url, ref bgColor, controlMode, scalingMode); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_PlayMovieURL(string url, ref Color bgColor, int controlMode, int scalingMode); + [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovieURL(string url, Color bgColor, iPhoneMovieControlMode controlMode, iPhoneMovieScalingMode scalingMode) + { + iPhoneUtils.PlayMovieURL(url, bgColor, (int)controlMode, (int)scalingMode); + } + [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovieURL(string url, Color bgColor, iPhoneMovieControlMode controlMode) + { + iPhoneUtils.PlayMovieURL(url, bgColor, (int)controlMode, 1); + } + [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + public static void PlayMovieURL(string url, Color bgColor) + { + iPhoneUtils.PlayMovieURL(url, bgColor, 0, 1); + } + [Obsolete("Vibrate method is deprecated. Please use Handheld.Vibrate instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void Vibrate(); + } +} diff --git a/UnityEngine/UnityEngine/jvalue.cs b/UnityEngine/UnityEngine/jvalue.cs new file mode 100644 index 00000000..85bf5d65 --- /dev/null +++ b/UnityEngine/UnityEngine/jvalue.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Explicit)] + public struct jvalue + { + [FieldOffset(0)] + public bool z; + [FieldOffset(0)] + public byte b; + [FieldOffset(0)] + public char c; + [FieldOffset(0)] + public short s; + [FieldOffset(0)] + public int i; + [FieldOffset(0)] + public long j; + [FieldOffset(0)] + public float f; + [FieldOffset(0)] + public double d; + [FieldOffset(0)] + public IntPtr l; + } +} diff --git a/UnityEngine/UnityEngineInternal/FastCallExceptionHandler.cs b/UnityEngine/UnityEngineInternal/FastCallExceptionHandler.cs new file mode 100644 index 00000000..61749a30 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/FastCallExceptionHandler.cs @@ -0,0 +1,5 @@ +using System; +namespace UnityEngineInternal +{ + public delegate void FastCallExceptionHandler(Exception ex); +} diff --git a/UnityEngine/UnityEngineInternal/GenericStack.cs b/UnityEngine/UnityEngineInternal/GenericStack.cs new file mode 100644 index 00000000..c08af39e --- /dev/null +++ b/UnityEngine/UnityEngineInternal/GenericStack.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections; +namespace UnityEngineInternal +{ + public class GenericStack : Stack + { + } +} diff --git a/UnityEngine/UnityEngineInternal/GetMethodDelegate.cs b/UnityEngine/UnityEngineInternal/GetMethodDelegate.cs new file mode 100644 index 00000000..7586a924 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/GetMethodDelegate.cs @@ -0,0 +1,6 @@ +using System; +using System.Reflection; +namespace UnityEngineInternal +{ + public delegate MethodInfo GetMethodDelegate(Type classType, string methodName, bool searchBaseTypes, bool instanceMethod, Type[] methodParamTypes); +} diff --git a/UnityEngine/UnityEngineInternal/Reproduction.cs b/UnityEngine/UnityEngineInternal/Reproduction.cs new file mode 100644 index 00000000..3f12ada6 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/Reproduction.cs @@ -0,0 +1,12 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEngineInternal +{ + public sealed class Reproduction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CaptureScreenshot(); + } +} diff --git a/UnityEngine/UnityEngineInternal/TypeInferenceRuleAttribute.cs b/UnityEngine/UnityEngineInternal/TypeInferenceRuleAttribute.cs new file mode 100644 index 00000000..a2072fd5 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/TypeInferenceRuleAttribute.cs @@ -0,0 +1,21 @@ +using System; +namespace UnityEngineInternal +{ + [AttributeUsage(AttributeTargets.Method)] + [Serializable] + public class TypeInferenceRuleAttribute : Attribute + { + private readonly string _rule; + public TypeInferenceRuleAttribute(TypeInferenceRules rule) : this(rule.ToString()) + { + } + public TypeInferenceRuleAttribute(string rule) + { + this._rule = rule; + } + public override string ToString() + { + return this._rule; + } + } +} diff --git a/UnityEngine/UnityEngineInternal/TypeInferenceRules.cs b/UnityEngine/UnityEngineInternal/TypeInferenceRules.cs new file mode 100644 index 00000000..ee562f53 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/TypeInferenceRules.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngineInternal +{ + public enum TypeInferenceRules + { + TypeReferencedByFirstArgument, + TypeReferencedBySecondArgument, + ArrayOfTypeReferencedByFirstArgument, + TypeOfFirstArgument + } +} From 6465fc9bed158a46f7b900175105fddf21c433ea Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 12:09:38 -0500 Subject: [PATCH 4/9] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae4ba4e1..9783c88d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # UnityDecompiled An unofficial repo of decompiled Unity dll files -This version: 4.6.3f1 (other versions will be put in tags) +This version: 4.6.3f1 Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) From b9ba173a5544e810db6918358be60907416e2a5f Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 12:20:00 -0500 Subject: [PATCH 5/9] Tweaking readme --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9783c88d..0051a96c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # UnityDecompiled -An unofficial repo of decompiled Unity dll files +## An unofficial repo of decompiled Unity dll files -This version: 4.6.3f1 +Currently this is made from decompiling UnityEditor.dll and UnityEngine.dll using ILSpy + +This version: *4.6.3f1* Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) From a845f6c72f1ae13d0dea19d88c190c0ed99332e4 Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Fri, 27 Feb 2015 12:23:28 -0500 Subject: [PATCH 6/9] Tweaking readme again --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0051a96c..a8bc76be 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # UnityDecompiled -## An unofficial repo of decompiled Unity dll files +#### An unofficial repo of decompiled Unity dll files -Currently this is made from decompiling UnityEditor.dll and UnityEngine.dll using ILSpy +This was made by decompiling UnityEditor.dll and UnityEngine.dll using [ILSpy](http://ilspy.net) -This version: *4.6.3f1* +Current version: *4.6.3f1* Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) From 81dc34c058da446298e866d8b28a5b500b4f5b40 Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Sat, 28 Feb 2015 17:38:57 -0500 Subject: [PATCH 7/9] Tweaking readme as usual --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a8bc76be..066a2f73 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ This was made by decompiling UnityEditor.dll and UnityEngine.dll using [ILSpy](http://ilspy.net) -Current version: *4.6.3f1* +Current version: *4.6.3f1* - other versions can be [found in the tags](https://github.com/MattRix/UnityDecompiled/tags) Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) From 3fd845a2f1540d9afc588f647cc091feeb383f54 Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Sat, 28 Feb 2015 17:39:59 -0500 Subject: [PATCH 8/9] Small tweak --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 066a2f73..7a6a3fa4 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ This was made by decompiling UnityEditor.dll and UnityEngine.dll using [ILSpy](http://ilspy.net) -Current version: *4.6.3f1* - other versions can be [found in the tags](https://github.com/MattRix/UnityDecompiled/tags) +Current version: *4.6.3f1* - other versions can be found in the [tags](https://github.com/MattRix/UnityDecompiled/tags) Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) From cc432a3de42b53920d5d5dae85968ff993f4ec0e Mon Sep 17 00:00:00 2001 From: Matt Rix Date: Sat, 28 Feb 2015 17:45:38 -0500 Subject: [PATCH 9/9] Updating to Unity 5.0.0f3 Note that Unity 4.6.3 is still in the tags if you want to check it out instead. --- README.md | 2 +- UnityEditor/AssemblyValidation.cs | 4 +- UnityEditor/DesktopStandalonePostProcessor.cs | 93 +- UnityEditor/FlashDotNetAPIValidationRule.cs | 82 - UnityEditor/FlashFileHelper.cs | 187 - UnityEditor/FlashPostProcessSettings.cs | 136 - UnityEditor/FlashTemplateWriterUtility.cs | 62 - UnityEditor/GendarmeXMLTemplateTags.cs | 73 - UnityEditor/GenerateIconsWithMipLevels.cs | 4 +- .../LinuxDesktopStandalonePostProcessor.cs | 131 - UnityEditor/MxmlcHelper.cs | 69 - UnityEditor/NUnitFrameworkUser.cs | 9 - .../OSXDesktopStandalonePostProcessor.cs | 111 - UnityEditor/ParticleSystemCurveEditor.cs | 3 +- UnityEditor/PostProcessFlashPlayer.cs | 164 - UnityEditor/PostProcessFlashPlayerOptions.cs | 24 - UnityEditor/Properties/AssemblyInfo.cs | 6 + .../SerializedFileContainerPreparer.cs | 71 - UnityEditor/TreeEditor/TreeAOSphere.cs | 2 +- UnityEditor/TreeEditor/TreeData.cs | 2 +- UnityEditor/TreeEditor/TreeEditor.cs | 14 +- UnityEditor/TreeEditor/TreeGroupLeaf.cs | 8 +- .../AnimatorCondition.cs | 43 + .../AnimatorConditionMode.cs | 13 + .../AnimatorController.cs | 336 + .../AnimatorControllerLayer.cs | 176 + .../AnimatorLayerBlendingMode.cs | 9 + .../UnityEditor.Animations/AnimatorState.cs | 238 + .../AnimatorStateMachine.cs | 602 ++ .../AnimatorStateTransition.cs | 79 + .../AnimatorTransition.cs | 16 + .../AnimatorTransitionBase.cs | 103 + .../AvatarMask.cs | 12 +- .../UnityEditor.Animations/BlendTree.cs | 149 + .../BlendTreeType.cs | 7 +- .../ChildAnimatorState.cs | 32 + .../ChildAnimatorStateMachine.cs | 32 + .../UnityEditor.Animations/ChildMotion.cs | 92 + .../MecanimUtilities.cs | 42 + .../PushUndoIfNeeded.cs | 20 + .../StateBehavioursPair.cs | 10 + .../StateMachineBehaviourContext.cs | 14 + .../UnityEditor.Animations/StateMotionPair.cs | 10 + .../TransitionInterruptionSource.cs | 12 + .../AudioEffectParameterPath.cs | 33 + .../AudioGroupParameterPath.cs | 38 + .../UnityEditor.Audio/AudioMixerController.cs | 1130 +++ .../AudioMixerEffectController.cs | 126 + .../AudioMixerEffectPlugin.cs | 53 + .../AudioMixerGroupController.cs | 167 + .../AudioMixerSnapshotController.cs | 58 + .../UnityEditor.Audio/AudioParameterPath.cs | 9 + .../ChangedExposedParameterHandler.cs | 5 + .../ExposedAudioParameter.cs | 9 + .../MixerEffectDefinition.cs | 29 + .../MixerEffectDefinitionReloader.cs | 17 + .../MixerEffectDefinitions.cs | 171 + .../UnityEditor.Audio/MixerEffectParameter.cs | 9 + .../MixerGroupControllerCompareByName.cs | 12 + .../UnityEditor.Audio/MixerGroupView.cs | 9 + .../MixerParameterDefinition.cs | 15 + .../ParameterTransitionType.cs | 13 + .../PostProcessSceneAttribute.cs | 15 + UnityEditor/UnityEditor.Hardware/DevDevice.cs | 54 + .../UnityEditor.Hardware/DevDeviceFeatures.cs | 11 + .../UnityEditor.Hardware/DevDeviceList.cs | 56 + .../UnityEditor.Hardware/DevDeviceState.cs | 9 + UnityEditor/UnityEditor.Hardware/Usb.cs | 29 + UnityEditor/UnityEditor.Hardware/UsbDevice.cs | 28 + .../LinuxStandaloneIl2CppPlatformProvider.cs | 58 - .../DefaultPlayerSettingsEditorExtension.cs | 10 + .../DefaultPluginImporterExtension.cs | 233 + .../IBuildPostprocessor.cs | 5 +- .../IBuildWindowExtension.cs | 14 + UnityEditor/UnityEditor.Modules/IDevice.cs | 11 + .../IPlatformSupportModule.cs | 13 + .../IPluginImporterExtension.cs | 15 + .../IScriptingImplementations.cs | 15 + .../ISettingEditorExtension.cs | 3 + .../IUserAssembliesValidator.cs | 13 + .../UnityEditor.Modules/ModuleManager.cs | 283 +- .../UnityEditor.Modules/ModuleUtils.cs | 17 + .../UnityEditor.Modules/RemoteAddress.cs | 14 + .../UnityEditor.NScreen/NScreenManager.cs | 192 + UnityEditor/UnityEditor.NScreen/RemoteGame.cs | 182 + .../OSXStandaloneIl2CppPlatformProvider.cs | 45 - .../DoCreateAnimatorController.cs | 2 +- .../DoCreateAudioMixer.cs | 23 + .../APIUpdaterHelper.cs | 106 + .../BooCompiler.cs | 14 +- .../BooCompilerOutputParser.cs | 5 + .../BooLanguage.cs | 4 +- .../CSharpLanguage.cs | 22 +- .../Cil2AsOutputParser.cs | 4 +- .../CompilerMessage.cs | 1 + .../CompilerOutputParserBase.cs | 21 +- .../FlexCompilerOutputParser.cs | 17 - .../GendarmeOutputParser.cs | 4 +- .../MicrosoftCSharpCompiler.cs | 91 +- .../MonoCSharpCompiler.cs | 18 +- .../MonoCSharpCompilerOutputParser.cs | 5 + .../MonoScriptCompilerBase.cs | 12 +- .../NormalizedCompilerStatus.cs | 9 + .../NormalizedCompilerStatusCode.cs | 9 + .../ScriptCompilerBase.cs | 2 +- .../SupportedLanguage.cs | 2 +- .../UnityScriptCompiler.cs | 17 +- .../UnityScriptLanguage.cs | 4 +- .../Weaver.cs | 92 + .../UnityEditor.Scripting/APIUpdaterHelper.cs | 139 + .../UnityEditor.Scripting/APIUpdaterLogger.cs | 20 + .../UnityEditor.Scripting/MonoIsland.cs | 2 +- .../UnityEditor.Scripting/PragmaFixing30.cs | 4 +- .../UnityEditor.Scripting/ScriptCompilers.cs | 6 +- .../UnityEditor.Sprites/AtlasSettings.cs | 1 - .../UnityEditor.Sprites/DataUtility.cs | 25 +- .../DefaultPackerPolicy.cs | 13 +- UnityEditor/UnityEditor.Sprites/Packer.cs | 56 +- .../UnityEditor.Sprites/PackerWindow.cs | 16 +- .../UnityEditor.Sprites/SpriteUtility.cs | 35 + .../MonoInstallationFinder.cs | 9 +- .../UnityEditor.Utils/PerformanceChecks.cs | 67 +- UnityEditor/UnityEditor.Utils/Program.cs | 2 +- .../UnityEditor.VersionControl/Asset.cs | 54 +- .../UnityEditor.VersionControl/ChangeSet.cs | 8 +- .../UnityEditor.VersionControl/Message.cs | 14 +- .../UnityEditor.VersionControl/Provider.cs | 300 +- .../UnityEditor.VersionControl/Task.cs | 60 +- .../WindowChange.cs | 28 +- .../WindowPending.cs | 8 +- .../WindowResolve.cs | 4 - ...WindowsStandaloneIl2CppPlatformProvider.cs | 60 - UnityEditor/UnityEditor.csproj | 260 +- UnityEditor/UnityEditor/ASCommitWindow.cs | 6 +- UnityEditor/UnityEditor/ASConfigWindow.cs | 6 +- UnityEditor/UnityEditor/ASHistoryWindow.cs | 6 +- UnityEditor/UnityEditor/ASMainWindow.cs | 20 +- .../ASUpdateConflictResolveWindow.cs | 8 +- UnityEditor/UnityEditor/ASUpdateWindow.cs | 12 +- UnityEditor/UnityEditor/AboutWindow.cs | 30 +- UnityEditor/UnityEditor/AboutWindowNames.cs | 76 +- .../ActionOnDotNetUnhandledException.cs | 9 + UnityEditor/UnityEditor/AddComponentWindow.cs | 67 +- UnityEditor/UnityEditor/AlphabeticalSort.cs | 3 +- UnityEditor/UnityEditor/AndroidBanner.cs | 11 + .../UnityEditor/AndroidBuildSubtarget.cs | 16 +- UnityEditor/UnityEditor/AndroidSdkRoot.cs | 2 +- UnityEditor/UnityEditor/AndroidSdkVersions.cs | 3 +- .../UnityEditor/AndroidTargetDevice.cs | 4 +- .../UnityEditor/AnimationClipEditor.cs | 231 +- .../AnimationClipInfoProperties.cs | 66 +- .../UnityEditor/AnimationEventTimeLine.cs | 1 + UnityEditor/UnityEditor/AnimationSelection.cs | 9 +- UnityEditor/UnityEditor/AnimationUtility.cs | 26 +- UnityEditor/UnityEditor/AnimationWindow.cs | 67 +- UnityEditor/UnityEditor/AnimatorInspector.cs | 71 +- .../AnimatorOverrideControllerInspector.cs | 3 +- UnityEditor/UnityEditor/AnnotationWindow.cs | 1 + UnityEditor/UnityEditor/AppStatusBar.cs | 4 +- UnityEditor/UnityEditor/AssemblyHelper.cs | 126 +- .../UnityEditor/AssemblyTypeInfoGenerator.cs | 140 +- UnityEditor/UnityEditor/AssetBundleBuild.cs | 10 + UnityEditor/UnityEditor/AssetBundleNameGUI.cs | 213 + UnityEditor/UnityEditor/AssetDatabase.cs | 172 +- UnityEditor/UnityEditor/AssetImporter.cs | 22 + .../UnityEditor/AssetImporterInspector.cs | 71 +- .../UnityEditor/AssetImporterTabbedEditor.cs | 21 +- UnityEditor/UnityEditor/AssetInspector.cs | 2 +- .../AssetModificationProcessorInternal.cs | 13 +- UnityEditor/UnityEditor/AssetPopupBackend.cs | 97 + .../AssetPostprocessingInternal.cs | 66 +- UnityEditor/UnityEditor/AssetPreview.cs | 2 +- .../UnityEditor/AssetSelectionPopupMenu.cs | 52 + UnityEditor/UnityEditor/AssetServer.cs | 31 +- UnityEditor/UnityEditor/AssetStoreContext.cs | 407 +- .../UnityEditor/AssetStoreInstaBuyWindow.cs | 12 +- UnityEditor/UnityEditor/AssetStoreWindow.cs | 266 +- .../UnityEditor/AssetsTreeViewDragging.cs | 36 + UnityEditor/UnityEditor/AsyncHTTPClient.cs | 52 +- UnityEditor/UnityEditor/AttachProfilerUI.cs | 175 +- UnityEditor/UnityEditor/AttributeHelper.cs | 109 +- UnityEditor/UnityEditor/AudioClipInspector.cs | 63 +- .../UnityEditor/AudioCurveRendering.cs | 214 + UnityEditor/UnityEditor/AudioFilterGUI.cs | 4 +- .../UnityEditor/AudioGroupDataSource.cs | 55 + .../UnityEditor/AudioGroupTreeViewDragging.cs | 56 + .../UnityEditor/AudioGroupTreeViewGUI.cs | 108 + UnityEditor/UnityEditor/AudioImporter.cs | 184 +- .../UnityEditor/AudioImporterFormat.cs | 2 + .../UnityEditor/AudioImporterInspector.cs | 675 +- .../UnityEditor/AudioImporterLoadType.cs | 8 +- .../AudioImporterSampleSettings.cs | 14 + .../AudioLowPassFilterInspector.cs | 2 +- .../UnityEditor/AudioMixerChannelStripView.cs | 1555 +++ .../UnityEditor/AudioMixerColorCodes.cs | 90 + .../AudioMixerControllerInspector.cs | 28 + .../UnityEditor/AudioMixerDrawUtils.cs | 366 + .../UnityEditor/AudioMixerEffectGUI.cs | 146 + .../UnityEditor/AudioMixerEffectView.cs | 549 + .../AudioMixerExposedParameterView.cs | 158 + .../AudioMixerExposedParametersPopup.cs | 48 + .../UnityEditor/AudioMixerGroupEditor.cs | 71 + .../AudioMixerGroupPopupContext.cs | 23 + .../UnityEditor/AudioMixerGroupSelector.cs | 382 + .../UnityEditor/AudioMixerGroupTreeView.cs | 412 + .../UnityEditor/AudioMixerGroupViewList.cs | 231 + UnityEditor/UnityEditor/AudioMixerItem.cs | 67 + .../UnityEditor/AudioMixerSelection.cs | 79 + .../AudioMixerSnapshotControllerInspector.cs | 12 + .../UnityEditor/AudioMixerSnapshotListView.cs | 267 + .../UnityEditor/AudioMixerTreeViewDragging.cs | 118 + .../UnityEditor/AudioMixerTreeViewNode.cs | 17 + UnityEditor/UnityEditor/AudioMixerUtility.cs | 35 + UnityEditor/UnityEditor/AudioMixerWindow.cs | 808 ++ .../UnityEditor/AudioMixersDataSource.cs | 191 + .../UnityEditor/AudioMixersTreeView.cs | 217 + .../UnityEditor/AudioMixersTreeViewGUI.cs | 118 + .../UnityEditor/AudioSampleRateSetting.cs | 10 + .../UnityEditor/AudioSourceInspector.cs | 150 +- UnityEditor/UnityEditor/AudioUtil.cs | 33 +- UnityEditor/UnityEditor/AvatarEditor.cs | 16 +- .../UnityEditor/AvatarMappingEditor.cs | 53 +- .../UnityEditor/AvatarMaskInspector.cs | 6 +- UnityEditor/UnityEditor/AvatarMaskUtility.cs | 26 +- UnityEditor/UnityEditor/AvatarPreview.cs | 368 +- UnityEditor/UnityEditor/AvatarSetupTool.cs | 6 +- UnityEditor/UnityEditor/AvatarSubEditor.cs | 3 + UnityEditor/UnityEditor/BaseProjectWindow.cs | 1997 ---- .../UnityEditor/BillboardAssetInspector.cs | 212 + .../UnityEditor/BillboardRendererInspector.cs | 33 + UnityEditor/UnityEditor/BlendTreeInspector.cs | 456 +- .../UnityEditor/BoxCollider2DEditor.cs | 14 +- UnityEditor/UnityEditor/BoxEditor.cs | 114 +- UnityEditor/UnityEditor/Brush.cs | 6 +- .../UnityEditor/BuildAssetBundleOptions.cs | 14 +- UnityEditor/UnityEditor/BuildOptions.cs | 1 + UnityEditor/UnityEditor/BuildPipeline.cs | 194 +- UnityEditor/UnityEditor/BuildPlayerWindow.cs | 864 +- UnityEditor/UnityEditor/BuildTarget.cs | 25 +- UnityEditor/UnityEditor/BuildTargetGroup.cs | 10 +- UnityEditor/UnityEditor/BuildVerifier.cs | 6 +- .../UnityEditor/CacheServerPreferences.cs | 6 +- UnityEditor/UnityEditor/CameraEditor.cs | 217 +- UnityEditor/UnityEditor/CanvasEditor.cs | 6 +- .../UnityEditor/CapsuleColliderEditor.cs | 2 +- .../UnityEditor/CharacterControllerEditor.cs | 2 +- .../UnityEditor/CircleCollider2DEditor.cs | 12 +- .../UnityEditor/ClipAnimationInfoCurve.cs | 10 + UnityEditor/UnityEditor/ClothInspector.cs | 1070 +- .../UnityEditor/ClothInspectorState.cs | 22 + UnityEditor/UnityEditor/CodeStrippingUtils.cs | 64 +- .../UnityEditor/Collider2DEditorBase.cs | 37 +- .../UnityEditor/Collider3DEditorBase.cs | 7 +- UnityEditor/UnityEditor/ColliderEditorBase.cs | 106 +- .../UnityEditor/ColliderEditorUtility.cs | 35 + UnityEditor/UnityEditor/CollisionModuleUI.cs | 4 +- UnityEditor/UnityEditor/ColorPicker.cs | 30 +- UnityEditor/UnityEditor/ComplexD.cs | 133 + UnityEditor/UnityEditor/ConsoleWindow.cs | 4 +- UnityEditor/UnityEditor/ContainerWindow.cs | 20 +- .../UnityEditor/CreateBuiltinWindows.cs | 5 + UnityEditor/UnityEditor/CubemapInspector.cs | 159 + UnityEditor/UnityEditor/CubemapPreview.cs | 192 + .../UnityEditor/CubemapTextureInspector.cs | 234 - UnityEditor/UnityEditor/CurveEditor.cs | 52 +- UnityEditor/UnityEditor/CurveEditorWindow.cs | 6 +- .../UnityEditor/CustomLaunchScreenType.cs | 10 + .../UnityEditor/D3D11FullscreenMode.cs | 9 + .../UnityEditor/DefaultAsset.cs | 18 +- .../UnityEditor/DefaultAssetInspector.cs | 16 + .../UnityEditor/DefaultReflectionMode.cs | 9 + UnityEditor/UnityEditor/DeleteWindowLayout.cs | 13 +- .../DesktopPluginImporterExtension.cs | 159 + UnityEditor/UnityEditor/DetailMeshWizard.cs | 20 +- UnityEditor/UnityEditor/DrawCameraMode.cs | 18 +- .../UnityEditor/DrivenRectTransformUndo.cs | 1 + UnityEditor/UnityEditor/DuckVolumeGUI.cs | 336 + .../UnityEditor/EdgeCollider2DEditor.cs | 21 +- UnityEditor/UnityEditor/Editor.cs | 476 +- UnityEditor/UnityEditor/EditorApplication.cs | 38 + UnityEditor/UnityEditor/EditorAssemblies.cs | 77 +- UnityEditor/UnityEditor/EditorGUI.cs | 9031 +++++++++-------- UnityEditor/UnityEditor/EditorGUIExt.cs | 11 +- UnityEditor/UnityEditor/EditorGUIInternal.cs | 4 + UnityEditor/UnityEditor/EditorGUILayout.cs | 448 +- UnityEditor/UnityEditor/EditorGUIUtility.cs | 69 +- .../UnityEditor/EditorMaterialUtility.cs | 3 + .../EditorPluginImporterExtension.cs | 34 + UnityEditor/UnityEditor/EditorSettings.cs | 18 + .../UnityEditor/EditorSettingsInspector.cs | 158 +- UnityEditor/UnityEditor/EditorStyles.cs | 75 +- .../UnityEditor/EditorUserBuildSettings.cs | 74 +- UnityEditor/UnityEditor/EditorUserSettings.cs | 9 + UnityEditor/UnityEditor/EditorUtility.cs | 97 +- UnityEditor/UnityEditor/EditorWindow.cs | 4 +- UnityEditor/UnityEditor/Effector2DEditor.cs | 54 + .../UnityEditor/EventManipulationHandler.cs | 6 +- UnityEditor/UnityEditor/EyeDropper.cs | 2 +- UnityEditor/UnityEditor/FileUtil.cs | 153 +- .../UnityEditor/FlashBuildSubtarget.cs | 14 - UnityEditor/UnityEditor/FlexibleMenu.cs | 29 +- UnityEditor/UnityEditor/FogEditor.cs | 71 + .../UnityEditor/FrameDebuggerWindow.cs | 624 ++ UnityEditor/UnityEditor/GUID.cs | 50 + UnityEditor/UnityEditor/GUIView.cs | 3 + .../UnityEditor/GameObjectInspector.cs | 29 +- .../GameObjectTreeViewDataSource.cs | 83 +- .../UnityEditor/GameObjectTreeViewGUI.cs | 15 +- UnityEditor/UnityEditor/GameObjectUtility.cs | 79 +- ...ging.cs => GameObjectsTreeViewDragging.cs} | 25 +- UnityEditor/UnityEditor/GameView.cs | 43 +- UnityEditor/UnityEditor/GameViewGUI.cs | 67 +- UnityEditor/UnityEditor/GameViewSizes.cs | 5 +- UnityEditor/UnityEditor/GenericMenu.cs | 23 +- UnityEditor/UnityEditor/GraphicsSettings.cs | 8 + .../UnityEditor/GraphicsSettingsInspector.cs | 182 + UnityEditor/UnityEditor/HandleUtility.cs | 53 +- UnityEditor/UnityEditor/Handles.cs | 2453 ++--- UnityEditor/UnityEditor/HierarchyProperty.cs | 13 +- UnityEditor/UnityEditor/HierarchyWindow.cs | 11 - UnityEditor/UnityEditor/Highlighter.cs | 80 +- UnityEditor/UnityEditor/HingeJointEditor.cs | 31 + UnityEditor/UnityEditor/HostView.cs | 11 +- UnityEditor/UnityEditor/IAudioEffectPlugin.cs | 13 + .../UnityEditor/IAudioEffectPluginGUI.cs | 20 + UnityEditor/UnityEditor/IDeviceUtils.cs | 28 + UnityEditor/UnityEditor/IPreviewable.cs | 1 + .../UnityEditor/ITreeViewDataSource.cs | 1 + UnityEditor/UnityEditor/ITreeViewGUI.cs | 8 + UnityEditor/UnityEditor/ImportRawHeightmap.cs | 2 +- UnityEditor/UnityEditor/InitialModuleUI.cs | 4 +- .../InitializeOnLoadMethodAttribute.cs | 8 + UnityEditor/UnityEditor/InspectorState.cs | 9 + UnityEditor/UnityEditor/InspectorWindow.cs | 88 +- UnityEditor/UnityEditor/KnobState.cs | 11 + UnityEditor/UnityEditor/LODGroupEditor.cs | 421 +- UnityEditor/UnityEditor/LODGroupGUI.cs | 238 + UnityEditor/UnityEditor/LayerMatrixGUI.cs | 16 +- .../UnityEditor/LazyTreeViewDataSource.cs | 25 +- .../UnityEditor/LegacyIlluminShaderGUI.cs | 19 + .../UnityEditor/LicenseManagementWindow.cs | 24 +- UnityEditor/UnityEditor/LightEditor.cs | 282 +- UnityEditor/UnityEditor/LightProbeGUI.cs | 4 +- .../UnityEditor/LightProbeGroupEditor.cs | 105 +- .../UnityEditor/LightProbeGroupInspector.cs | 17 + UnityEditor/UnityEditor/LightingEditor.cs | 161 + UnityEditor/UnityEditor/LightingWindow.cs | 688 ++ .../LightingWindowLightmapPreviewTab.cs | 177 + .../UnityEditor/LightingWindowObjectTab.cs | 584 ++ .../UnityEditor/LightmapBakeQuality.cs | 1 + .../UnityEditor/LightmapEditorSettings.cs | 265 +- UnityEditor/UnityEditor/LightmapParameters.cs | 151 + .../UnityEditor/LightmapParametersEditor.cs | 89 + .../UnityEditor/LightmapVisualization.cs | 9 - .../LightmapVisualizationUtility.cs | 23 + UnityEditor/UnityEditor/Lightmapping.cs | 126 + UnityEditor/UnityEditor/LightmappingWindow.cs | 1212 --- .../UnityEditor/LineRendererInspector.cs | 19 + UnityEditor/UnityEditor/MaterialEditor.cs | 1030 +- UnityEditor/UnityEditor/MaterialEnumDrawer.cs | 9 +- .../UnityEditor/MaterialHeaderDecorator.cs | 28 + .../UnityEditor/MaterialKeywordEnumDrawer.cs | 2 +- .../UnityEditor/MaterialPowerSliderDrawer.cs | 11 +- UnityEditor/UnityEditor/MaterialProperty.cs | 5 +- .../UnityEditor/MaterialPropertyDrawer.cs | 112 - .../UnityEditor/MaterialPropertyHandler.cs | 218 + .../UnityEditor/MaterialSpaceDecorator.cs | 24 + .../UnityEditor/MaterialToggleDrawer.cs | 2 +- UnityEditor/UnityEditor/MathUtils.cs | 56 +- UnityEditor/UnityEditor/MecanimUtilities.cs | 86 - UnityEditor/UnityEditor/Menu.cs | 15 + UnityEditor/UnityEditor/MeshColliderEditor.cs | 21 +- UnityEditor/UnityEditor/MeshRendererEditor.cs | 39 +- UnityEditor/UnityEditor/MetroBuildType.cs | 12 - .../MetroCertificatePasswordWindow.cs | 2 +- .../MetroCreateTestCertificateWindow.cs | 6 +- ...Subtarget.cs => MobileTextureSubtarget.cs} | 7 +- UnityEditor/UnityEditor/ModelImporter.cs | 86 +- .../UnityEditor/ModelImporterClipAnimation.cs | 34 +- .../UnityEditor/ModelImporterClipEditor.cs | 49 +- .../UnityEditor/ModelImporterModelEditor.cs | 42 +- .../UnityEditor/ModelImporterRigEditor.cs | 2 +- UnityEditor/UnityEditor/ModelInspector.cs | 88 +- UnityEditor/UnityEditor/ModuleUI.cs | 3 +- .../UnityEditor/MonoAOTRegistration.cs | 57 +- .../UnityEditor/MonoAssemblyStripping.cs | 38 +- UnityEditor/UnityEditor/MonoCrossCompile.cs | 37 +- UnityEditor/UnityEditor/MonoProcessRunner.cs | 68 + UnityEditor/UnityEditor/MonoProcessUtility.cs | 48 +- UnityEditor/UnityEditor/MonoScript.cs | 9 - .../MonoScriptImporterInspector.cs | 38 +- .../UnityEditor/MonoScriptInspector.cs | 3 - .../UnityEditor/MovieImporterInspector.cs | 2 +- .../UnityEditor/MovieTextureInspector.cs | 3 +- .../UnityEditor/NavMeshAgentInspector.cs | 45 +- .../UnityEditor/NavMeshEditorWindow.cs | 532 +- .../UnityEditor/NavMeshObstacleInspector.cs | 64 +- .../NavMeshVisualizationSettings.cs | 60 + .../UnityEditor/NormalCurveRenderer.cs | 2 +- UnityEditor/UnityEditor/ObjectListArea.cs | 18 +- UnityEditor/UnityEditor/ObjectPreview.cs | 3 + UnityEditor/UnityEditor/ObjectPreviewPopup.cs | 60 + UnityEditor/UnityEditor/ObjectSelector.cs | 95 +- .../UnityEditor/ObjectTreeForSelector.cs | 330 + .../UnityEditor/OcclusionCullingWindow.cs | 14 +- .../UnityEditor/OffMeshLinkInspector.cs | 27 +- .../UnityEditor/OtherRenderingEditor.cs | 53 + UnityEditor/UnityEditor/PS4BuildSubtarget.cs | 9 + UnityEditor/UnityEditor/PSMBuildSubtarget.cs | 10 + UnityEditor/UnityEditor/PackageExport.cs | 2 +- UnityEditor/UnityEditor/PackageImport.cs | 62 +- .../UnityEditor/PackageImportTreeView.cs | 41 +- UnityEditor/UnityEditor/ParamEqGUI.cs | 189 + UnityEditor/UnityEditor/ParticleEffectUI.cs | 4 - .../UnityEditor/ParticleRendererEditor.cs | 19 + UnityEditor/UnityEditor/ParticleSystemUI.cs | 7 +- .../UnityEditor/ParticleSystemWindow.cs | 14 +- UnityEditor/UnityEditor/PlaceTreeWizard.cs | 11 +- UnityEditor/UnityEditor/PlayerSettings.cs | 1684 ++- .../UnityEditor/PlayerSettingsEditor.cs | 1642 +-- UnityEditor/UnityEditor/PluginImporter.cs | 82 + .../UnityEditor/PluginImporterInspector.cs | 365 + UnityEditor/UnityEditor/PointEditor.cs | 6 - ...erEditor.cs => PolygonCollider2DEditor.cs} | 27 +- .../UnityEditor/PolygonEditorUtility.cs | 81 +- UnityEditor/UnityEditor/PopupList.cs | 14 +- UnityEditor/UnityEditor/PopupWindow.cs | 2 +- .../UnityEditor/PopupWindowWithoutFocus.cs | 1 + .../UnityEditor/PostprocessBuildPlayer.cs | 164 +- UnityEditor/UnityEditor/PrefabUtility.cs | 6 - UnityEditor/UnityEditor/PreferencesWindow.cs | 143 +- .../UnityEditor/PresetLibraryEditor.cs | 19 +- UnityEditor/UnityEditor/PreviewBlendTree.cs | 50 +- .../UnityEditor/PreviewRenderUtility.cs | 54 +- UnityEditor/UnityEditor/PreviewWindow.cs | 1 + .../ProceduralMaterialInspector.cs | 71 +- .../UnityEditor/ProceduralTextureInspector.cs | 3 +- UnityEditor/UnityEditor/ProfilerChoise.cs | 11 + UnityEditor/UnityEditor/ProfilerWindow.cs | 290 +- UnityEditor/UnityEditor/ProjectBrowser.cs | 143 +- ...ProjectBrowserColumnOneTreeViewDragging.cs | 4 +- UnityEditor/UnityEditor/ProjectWindowUtil.cs | 73 + .../UnityEditor/PropertyHandlerCache.cs | 2 +- .../UnityEditor/QualitySettingsEditor.cs | 95 +- UnityEditor/UnityEditor/RagdollBuilder.cs | 95 +- UnityEditor/UnityEditor/RectSelection.cs | 4 +- .../UnityEditor/ReflectionProbeEditor.cs | 695 ++ UnityEditor/UnityEditor/RenameOverlay.cs | 16 + .../UnityEditor/RenderSettingsInspector.cs | 60 + .../UnityEditor/RenderTextureInspector.cs | 55 +- .../UnityEditor/RenderThumbnailUtility.cs | 8 +- UnityEditor/UnityEditor/RendererEditorBase.cs | 132 + UnityEditor/UnityEditor/RendererModuleUI.cs | 15 +- .../UnityEditor/RuntimeClassRegistry.cs | 18 +- UnityEditor/UnityEditor/SceneFXWindow.cs | 82 +- .../SceneHierarchySortingWindow.cs | 1 + .../UnityEditor/SceneHierarchyWindow.cs | 187 +- UnityEditor/UnityEditor/SceneModeUtility.cs | 8 +- .../UnityEditor/SceneRenderModeWindow.cs | 185 + UnityEditor/UnityEditor/SceneView.cs | 895 +- UnityEditor/UnityEditor/SceneViewMotion.cs | 10 +- UnityEditor/UnityEditor/SceneViewOverlay.cs | 1 + UnityEditor/UnityEditor/SceneViewRotation.cs | 68 +- .../UnityEditor/ScriptAttributeUtility.cs | 1 + .../UnityEditor/ScriptableSingleton.cs | 4 - UnityEditor/UnityEditor/ScriptableWizard.cs | 24 +- UnityEditor/UnityEditor/SearchFilter.cs | 26 +- UnityEditor/UnityEditor/SearchUtility.cs | 10 + .../UnityEditor/SearchableEditorWindow.cs | 31 +- UnityEditor/UnityEditor/Selection.cs | 30 + UnityEditor/UnityEditor/SemanticMergeMode.cs | 10 + .../SerializedFileContainerWriter.cs | 87 - .../UnityEditor/SerializedMinMaxCurve.cs | 2 - UnityEditor/UnityEditor/SerializedModule.cs | 7 + UnityEditor/UnityEditor/SerializedProperty.cs | 22 +- .../UnityEditor/SetResolutionWizard.cs | 2 +- UnityEditor/UnityEditor/Settings.cs | 4 +- UnityEditor/UnityEditor/ShaderGUI.cs | 53 + UnityEditor/UnityEditor/ShaderGUIUtility.cs | 37 + .../UnityEditor/ShaderImporterInspector.cs | 52 +- UnityEditor/UnityEditor/ShaderInspector.cs | 202 +- .../ShaderInspectorPlatformsPopup.cs | 212 + UnityEditor/UnityEditor/ShaderUtil.cs | 94 +- .../ShaderVariantCollectionInspector.cs | 129 + .../UnityEditor/ShadowCascadeSplitGUI.cs | 159 + UnityEditor/UnityEditor/ShapeModuleUI.cs | 68 +- UnityEditor/UnityEditor/SimpleProfiler.cs | 17 +- .../UnityEditor/SkinnedMeshRendererEditor.cs | 42 +- UnityEditor/UnityEditor/SliderLabels.cs | 22 + UnityEditor/UnityEditor/SpeedTreeImporter.cs | 229 + .../UnityEditor/SpeedTreeImporterInspector.cs | 361 + .../UnityEditor/SpeedTreeMaterialInspector.cs | 174 + UnityEditor/UnityEditor/SplitterGUILayout.cs | 2 +- UnityEditor/UnityEditor/SpriteEditorWindow.cs | 210 +- UnityEditor/UnityEditor/SpriteInspector.cs | 31 +- ...erInspector.cs => SpriteRendererEditor.cs} | 29 +- UnityEditor/UnityEditor/SpriteUtility.cs | 52 +- .../UnityEditor/SpriteUtilityWindow.cs | 15 + UnityEditor/UnityEditor/StandardShaderGUI.cs | 386 + UnityEditor/UnityEditor/StaticEditorFlags.cs | 3 +- UnityEditor/UnityEditor/SubstanceImporter.cs | 4 +- .../UnityEditor/SubstanceImporterInspector.cs | 24 +- UnityEditor/UnityEditor/SyncVS.cs | 12 +- .../UnityEditor/TagManagerInspector.cs | 110 +- .../UnityEditor/TerrainEditorUtility.cs | 33 - UnityEditor/UnityEditor/TerrainInspector.cs | 273 +- .../UnityEditor/TerrainInspectorUtil.cs | 2 +- UnityEditor/UnityEditor/TerrainMenus.cs | 4 +- .../UnityEditor/TerrainSplatContextMenus.cs | 19 +- UnityEditor/UnityEditor/TerrainSplatEditor.cs | 75 +- UnityEditor/UnityEditor/TextAssetInspector.cs | 1 + UnityEditor/UnityEditor/Texture3DInspector.cs | 33 +- .../UnityEditor/TextureImportInstructions.cs | 27 - UnityEditor/UnityEditor/TextureImporter.cs | 9 +- .../TextureImporterCubemapConvolution.cs | 10 + .../UnityEditor/TextureImporterFormat.cs | 5 +- .../TextureImporterGenerateCubemap.cs | 3 +- .../UnityEditor/TextureImporterInspector.cs | 358 +- .../UnityEditor/TextureImporterRGBMMode.cs | 11 + .../UnityEditor/TextureImporterSettings.cs | 52 + .../UnityEditor/TextureImporterType.cs | 1 + UnityEditor/UnityEditor/TextureInspector.cs | 157 +- UnityEditor/UnityEditor/TextureUsageMode.cs | 5 +- UnityEditor/UnityEditor/TickTimerHelper.cs | 26 + UnityEditor/UnityEditor/TimeArea.cs | 4 +- UnityEditor/UnityEditor/TimeControl.cs | 11 + .../UnityEditor/TizenBuildSubtarget.cs | 10 - UnityEditor/UnityEditor/Toolbar.cs | 111 +- UnityEditor/UnityEditor/Tools.cs | 14 +- UnityEditor/UnityEditor/TooltipView.cs | 6 +- .../UnityEditor/TrailRendererInspector.cs | 19 + .../UnityEditor/TransformRotationGUI.cs | 19 +- UnityEditor/UnityEditor/TransformSort.cs | 3 +- UnityEditor/UnityEditor/TransitionPreview.cs | 298 +- UnityEditor/UnityEditor/TreeAO.cs | 10 +- UnityEditor/UnityEditor/TreePainter.cs | 96 +- .../UnityEditor/TreePlacementUtility.cs | 39 - UnityEditor/UnityEditor/TreeView.cs | 45 +- UnityEditor/UnityEditor/TreeViewDataSource.cs | 83 +- UnityEditor/UnityEditor/TreeViewDragging.cs | 59 +- .../UnityEditor/TreeViewForAudioMixerGroup.cs | 249 + UnityEditor/UnityEditor/TreeViewGUI.cs | 19 +- UnityEditor/UnityEditor/TreeViewItem.cs | 16 + .../TreeViewItemAlphaNumericSort.cs | 24 + UnityEditor/UnityEditor/TreeViewState.cs | 13 + UnityEditor/UnityEditor/TreeViewUtility.cs | 96 +- UnityEditor/UnityEditor/TreeWizard.cs | 46 +- UnityEditor/UnityEditor/TypeSelection.cs | 2 - UnityEditor/UnityEditor/Undo.cs | 8 +- UnityEditor/UnityEditor/UnityStats.cs | 52 +- UnityEditor/UnityEditor/Unsupported.cs | 28 +- .../UnityEditor/VisualizationBlendTree.cs | 45 +- ...arget.cs => WSABuildAndRunDeployTarget.cs} | 2 +- .../UnityEditor/{MetroSDK.cs => WSASDK.cs} | 2 +- UnityEditor/UnityEditor/WebScriptObject.cs | 174 - UnityEditor/UnityEditor/WebTemplate.cs | 35 + .../UnityEditor/WebTemplateManagerBase.cs | 264 + UnityEditor/UnityEditor/WebView.cs | 249 +- .../UnityEditor/WheelColliderEditor.cs | 10 +- UnityEditor/UnityEditor/WindInspector.cs | 55 +- UnityEditor/UnityEditor/WindowLayout.cs | 19 +- .../UnityEditor/XboxOneDeployMethod.cs | 11 + .../UnityEditor/XboxOneEncryptionLevel.cs | 10 + UnityEditor/UnityEditor/XboxOneRunMethod.cs | 9 - UnityEditor/UnityEditor/ZoomableArea.cs | 156 +- .../UnityEditor/iOSAppInBackgroundBehavior.cs | 10 + .../UnityEditor/iOSLaunchScreenType.cs | 12 - UnityEditor/UnityEditor/iPhoneArchitecture.cs | 10 - .../ListControl.cs | 10 +- .../Overlay.cs | 77 +- .../PendingWindowContextMenu.cs | 4 +- .../AddCurvesPopupHierarchy.cs | 2 +- .../AddCurvesPopupHierarchyGUI.cs | 2 +- .../AnimationWindowHierarchyGUI.cs | 72 +- .../AnimationWindowState.cs | 72 +- .../AnimationWindowUtility.cs | 52 +- .../UnityEditorInternal/AnimatorCondition.cs | 97 - .../UnityEditorInternal/AnimatorController.cs | 245 +- .../AnimatorControllerLayer.cs | 149 +- .../AnimatorControllerParameter.cs | 107 +- .../AnimatorControllerParameterType.cs | 6 +- .../AnimatorLayerBlendingMode.cs | 4 +- .../AssetStoreToolUtils.cs | 6 +- .../AudioProfilerBackend.cs | 34 + .../UnityEditorInternal/AudioProfilerInfo.cs | 24 + .../AudioProfilerInfoHelper.cs | 212 + .../AudioProfilerInfoWrapper.cs | 18 + .../AudioProfilerTreeViewState.cs | 27 + .../UnityEditorInternal/AudioProfilerView.cs | 280 + UnityEditor/UnityEditorInternal/BlendTree.cs | 131 +- .../UnityEditorInternal/CameraUtility.cs | 21 - UnityEditor/UnityEditorInternal/Chart.cs | 16 +- .../UnityEditorInternal/DopeSheetEditor.cs | 42 +- UnityEditor/UnityEditorInternal/EditMode.cs | 259 + .../UnityEditorInternal/FrameDebuggerEvent.cs | 18 + .../FrameDebuggerTreeView.cs | 225 + .../FrameDebuggerUtility.cs | 70 + .../UnityEditorInternal/FrameEventType.cs | 28 + .../IProfilerWindowController.cs | 4 + .../InternalEditorUtility.cs | 1235 +-- UnityEditor/UnityEditorInternal/LogEntries.cs | 2 +- .../MaterialAnimationUtility.cs | 9 +- .../UnityEditorInternal/ModuleMetadata.cs | 18 + .../UnityEditorInternal/PluginsHelper.cs | 29 + .../PostProcessNaclPlayer.cs | 201 - .../UnityEditorInternal/ProfilerAudioView.cs | 11 + .../UnityEditorInternal/ProfilerChart.cs | 55 +- .../UnityEditorInternal/ProfilerDriver.cs | 18 + .../ProfilerFrameDataIterator.cs | 6 + .../ProfilerHierarchyGUI.cs | 432 +- .../UnityEditorInternal/ProfilerProperty.cs | 6 + .../ProfilerTimelineGUI.cs | 171 +- .../UnityEditorInternal/ReorderableList.cs | 207 +- .../ReorderableListWithRenameAndScrollView.cs | 331 + .../ScriptUpdatingManager.cs | 21 + .../SpriteEditorUtility.cs | 2 +- UnityEditor/UnityEditorInternal/State.cs | 135 +- .../UnityEditorInternal/StateMachine.cs | 275 +- UnityEditor/UnityEditorInternal/Transition.cs | 157 +- .../TransitionConditionMode.cs | 14 - UnityEditor/UnityEngine/NScreenBridge.cs | 35 + .../UnityEngine/RuntimeInitializeClassInfo.cs | 45 + .../RuntimeInitializeMethodInfo.cs | 57 + .../RuntimeInitializeOnLoadManager.cs | 23 + .../WindowsDesktopStandalonePostProcessor.cs | 88 - .../AssertionMethodAttribute.cs | 8 + .../BaseTypeRequiredAttribute.cs | 18 + .../CanBeNullAttribute.cs | 8 + .../CannotApplyEqualityOperatorAttribute.cs | 8 + .../ContractAnnotationAttribute.cs | 26 + .../ImplicitUseKindFlags.cs | 13 + .../ImplicitUseTargetFlags.cs | 12 + .../InstantHandleAttribute.cs | 8 + .../InvokerParameterNameAttribute.cs | 8 + .../LinqTunnelAttribute.cs | 8 + .../LocalizationRequiredAttribute.cs | 20 + .../MeansImplicitUseAttribute.cs | 34 + .../NoEnumerationAttribute.cs | 8 + .../JetBrains.Annotations/NotNullAttribute.cs | 8 + ...NotifyPropertyChangedInvocatorAttribute.cs | 20 + .../PathReferenceAttribute.cs | 21 + .../PublicAPIAttribute.cs | 21 + .../JetBrains.Annotations/PureAttribute.cs | 8 + .../StringFormatMethodAttribute.cs | 17 + .../UsedImplicitlyAttribute.cs | 32 + UnityEngine/Properties/AssemblyInfo.cs | 16 + UnityEngine/UnityEngine.Audio/AudioMixer.cs | 46 + .../UnityEngine.Audio/AudioMixerGroup.cs | 17 + .../UnityEngine.Audio/AudioMixerSnapshot.cs | 20 + UnityEngine/UnityEngine.Events/UnityEvent.cs | 25 + UnityEngine/UnityEngine.Flash/ActionScript.cs | 21 - UnityEngine/UnityEngine.Flash/FlashPlayer.cs | 28 - .../UnityEngine.Rendering/AmbientMode.cs | 11 + .../BuiltinRenderTextureType.cs | 19 + .../UnityEngine.Rendering/CameraEvent.cs | 28 + .../UnityEngine.Rendering/CommandBuffer.cs | 275 + .../DefaultReflectionMode.cs | 9 + UnityEngine/UnityEngine.Rendering/PassType.cs | 18 + .../ReflectionProbeBlendInfo.cs | 9 + .../ReflectionProbeClearFlags.cs | 9 + .../ReflectionProbeMode.cs | 10 + .../ReflectionProbeRefreshMode.cs | 10 + .../ReflectionProbeTimeSlicingMode.cs | 10 + .../ReflectionProbeType.cs | 9 + .../ReflectionProbeUsage.cs | 11 + .../RenderBufferLoadAction.cs | 9 + .../RenderBufferStoreAction.cs | 9 + .../RenderTargetIdentifier.cs | 50 + .../ShadowCastingMode.cs | 11 + .../SphericalHarmonicsL2.cs | 370 + .../SerializationHelper.cs | 18 - UnityEngine/UnityEngine.csproj | 129 +- UnityEngine/UnityEngine.iOS/ADBannerView.cs | 181 + .../UnityEngine.iOS/ADInterstitialAd.cs | 98 + .../UnityEngine.iOS/ActivityIndicatorStyle.cs | 11 + .../UnityEngine.iOS/CalendarIdentifier.cs | 18 + UnityEngine/UnityEngine.iOS/CalendarUnit.cs | 18 + UnityEngine/UnityEngine.iOS/Device.cs | 44 + .../UnityEngine.iOS/DeviceGeneration.cs | 36 + .../UnityEngine.iOS/LocalNotification.cs | 144 + .../UnityEngine.iOS/NotificationServices.cs | 104 + .../NotificationType.cs} | 4 +- .../UnityEngine.iOS/RemoteNotification.cs | 50 + UnityEngine/UnityEngine/ADBannerView.cs | 175 +- UnityEngine/UnityEngine/ADInterstitialAd.cs | 92 +- UnityEngine/UnityEngine/AndroidJavaClass.cs | 8 +- UnityEngine/UnityEngine/AndroidJavaObject.cs | 92 +- UnityEngine/UnityEngine/AnimationClip.cs | 45 +- UnityEngine/UnityEngine/AnimationEvent.cs | 211 +- .../UnityEngine/AnimationEventSource.cs | 10 + UnityEngine/UnityEngine/AnimationInfo.cs | 21 +- UnityEngine/UnityEngine/Animator.cs | 241 +- UnityEngine/UnityEngine/AnimatorClipInfo.cs | 27 + .../AnimatorControllerParameter.cs | 83 + .../AnimatorControllerParameterType.cs | 11 + .../UnityEngine/AnimatorCullingMode.cs | 4 +- .../UnityEngine/AnimatorOverrideController.cs | 22 +- .../UnityEngine/AnimatorRecorderMode.cs | 10 + UnityEngine/UnityEngine/AnimatorStateInfo.cs | 18 +- .../UnityEngine/AnimatorTransitionInfo.cs | 35 +- UnityEngine/UnityEngine/Application.cs | 136 +- .../UnityEngine/ApplicationInstallMode.cs | 13 + .../UnityEngine/ApplicationSandboxType.cs | 11 + UnityEngine/UnityEngine/AreaEffector2D.cs | 62 + UnityEngine/UnityEngine/AssetBundle.cs | 174 +- .../UnityEngine/AssetBundleManifest.cs | 23 + UnityEngine/UnityEngine/AssetBundleRequest.cs | 9 +- UnityEngine/UnityEngine/AsyncOperation.cs | 1 - UnityEngine/UnityEngine/AudioClip.cs | 58 +- UnityEngine/UnityEngine/AudioClipLoadType.cs | 10 + .../UnityEngine/AudioCompressionFormat.cs | 13 + UnityEngine/UnityEngine/AudioConfiguration.cs | 12 + UnityEngine/UnityEngine/AudioDataLoadState.cs | 11 + .../UnityEngine/AudioHighPassFilter.cs | 10 + UnityEngine/UnityEngine/AudioLowPassFilter.cs | 10 + UnityEngine/UnityEngine/AudioReverbFilter.cs | 10 + UnityEngine/UnityEngine/AudioSettings.cs | 49 +- UnityEngine/UnityEngine/AudioSource.cs | 71 +- UnityEngine/UnityEngine/AvatarIKHint.cs | 11 + UnityEngine/UnityEngine/BillboardAsset.cs | 71 + ...{ClothRenderer.cs => BillboardRenderer.cs} | 4 +- UnityEngine/UnityEngine/Bounds.cs | 11 + UnityEngine/UnityEngine/BoxCollider2D.cs | 20 +- UnityEngine/UnityEngine/Caching.cs | 40 +- UnityEngine/UnityEngine/CalendarIdentifier.cs | 13 +- UnityEngine/UnityEngine/CalendarUnit.cs | 13 +- UnityEngine/UnityEngine/Camera.cs | 123 +- .../UnityEngine/CanConvertToFlashAttribute.cs | 15 - UnityEngine/UnityEngine/CastHelper.cs | 9 + UnityEngine/UnityEngine/CharacterInfo.cs | 117 + UnityEngine/UnityEngine/CharacterJoint.cs | 116 +- UnityEngine/UnityEngine/CircleCollider2D.cs | 30 +- UnityEngine/UnityEngine/Cloth.cs | 118 +- .../UnityEngine/ClothSkinningCoefficient.cs | 2 - .../UnityEngine/ClothSphereColliderPair.cs | 45 + UnityEngine/UnityEngine/Collider.cs | 19 +- UnityEngine/UnityEngine/Collider2D.cs | 41 + UnityEngine/UnityEngine/Collision2D.cs | 8 + UnityEngine/UnityEngine/Component.cs | 269 +- UnityEngine/UnityEngine/ConfigurableJoint.cs | 57 + UnityEngine/UnityEngine/ConstantForce2D.cs | 55 + UnityEngine/UnityEngine/ContactPoint.cs | 12 +- UnityEngine/UnityEngine/Cursor.cs | 18 + UnityEngine/UnityEngine/CursorLockMode.cs | 10 + UnityEngine/UnityEngine/Debug.cs | 27 + .../UnityEngine/DisableBatchingType.cs | 10 + UnityEngine/UnityEngine/Display.cs | 37 +- UnityEngine/UnityEngine/DynamicGI.cs | 85 + UnityEngine/UnityEngine/Effector2D.cs | 35 + .../UnityEngine/EffectorForceMode2D.cs | 10 + .../UnityEngine/EffectorSelection2D.cs | 9 + .../UnityEngine/EllipsoidParticleEmitter.cs | 10 + UnityEngine/UnityEngine/Event.cs | 5 +- UnityEngine/UnityEngine/FlareLayer.cs | 10 + UnityEngine/UnityEngine/Font.cs | 64 +- UnityEngine/UnityEngine/GL.cs | 11 +- UnityEngine/UnityEngine/GUI.cs | 119 + UnityEngine/UnityEngine/GUIContent.cs | 7 + UnityEngine/UnityEngine/GUILayout.cs | 136 + UnityEngine/UnityEngine/GUISkin.cs | 4 - UnityEngine/UnityEngine/GUIStyle.cs | 19 +- UnityEngine/UnityEngine/GUIStyleState.cs | 11 +- UnityEngine/UnityEngine/GUIUtility.cs | 2 - UnityEngine/UnityEngine/GameObject.cs | 323 +- UnityEngine/UnityEngine/Gizmos.cs | 106 + UnityEngine/UnityEngine/Graphics.cs | 273 +- UnityEngine/UnityEngine/Handheld.cs | 3 +- UnityEngine/UnityEngine/Hash128.cs | 25 + UnityEngine/UnityEngine/HideFlags.cs | 7 +- UnityEngine/UnityEngine/Input.cs | 5 +- UnityEngine/UnityEngine/InteractiveCloth.cs | 119 - .../InternalStaticBatchingUtility.cs | 45 +- .../Internal_DrawMeshTRArguments.cs | 1 + UnityEngine/UnityEngine/Joint.cs | 9 + UnityEngine/UnityEngine/JointLimits.cs | 12 + UnityEngine/UnityEngine/KeyCode.cs | 82 +- UnityEngine/UnityEngine/Light.cs | 20 + UnityEngine/UnityEngine/LightProbes.cs | 24 +- UnityEngine/UnityEngine/LightmapData.cs | 18 +- UnityEngine/UnityEngine/LightmapSettings.cs | 19 +- UnityEngine/UnityEngine/LightmapsMode.cs | 5 +- .../UnityEngine/LightmapsModeLegacy.cs | 10 + UnityEngine/UnityEngine/LocalNotification.cs | 138 +- .../UnityEngine/MarshallOnlyFirstField.cs | 2 +- UnityEngine/UnityEngine/Material.cs | 12 + .../MaterialGlobalIlluminationFlags.cs | 12 + UnityEngine/UnityEngine/Mathf.cs | 11 +- UnityEngine/UnityEngine/Mesh.cs | 47 +- UnityEngine/UnityEngine/MeshCollider.cs | 28 +- .../UnityEngine/MeshParticleEmitter.cs | 10 + UnityEngine/UnityEngine/MeshRenderer.cs | 10 + .../UnityEngine/MeshSubsetCombineUtility.cs | 5 +- UnityEngine/UnityEngine/Motion.cs | 13 +- UnityEngine/UnityEngine/NavMesh.cs | 88 +- UnityEngine/UnityEngine/NavMeshAgent.cs | 42 +- UnityEngine/UnityEngine/NavMeshObstacle.cs | 68 + .../UnityEngine/NavMeshObstacleShape.cs | 9 + UnityEngine/UnityEngine/NavMeshPath.cs | 3 + .../UnityEngine/NavMeshTriangulation.cs | 10 +- UnityEngine/UnityEngine/Network.cs | 6 +- .../UnityEngine/NotFlashValidatedAttribute.cs | 2 +- .../UnityEngine/NotRenamedAttribute.cs | 2 +- .../UnityEngine/NotificationServices.cs | 97 +- UnityEngine/UnityEngine/Object.cs | 143 +- UnityEngine/UnityEngine/OffMeshLink.cs | 10 + .../UnityEngine/ParticleCollisionEvent.cs | 43 + UnityEngine/UnityEngine/ParticleEmitter.cs | 5 +- .../UnityEngine/ParticlePhysicsExtensions.cs | 15 + UnityEngine/UnityEngine/ParticleSystem.cs | 42 +- .../ParticleSystemExtensionsImpl.cs | 14 + UnityEngine/UnityEngine/Physics.cs | 212 +- UnityEngine/UnityEngine/Physics2D.cs | 12 + .../UnityEngine/PhysicsUpdateBehaviour2D.cs | 7 + ...{SkinnedCloth.cs => PlatformEffector2D.cs} | 23 +- UnityEngine/UnityEngine/PointEffector2D.cs | 80 + .../UnityEngine/ProceduralOutputType.cs | 7 +- UnityEngine/UnityEngine/Projector.cs | 27 +- UnityEngine/UnityEngine/QualitySettings.cs | 46 + UnityEngine/UnityEngine/RaycastCollider.cs | 38 - UnityEngine/UnityEngine/RaycastHit.cs | 8 +- UnityEngine/UnityEngine/RectOffset.cs | 1 - UnityEngine/UnityEngine/ReferenceData.cs | 9 - UnityEngine/UnityEngine/ReflectionProbe.cs | 244 + UnityEngine/UnityEngine/RemoteNotification.cs | 44 +- .../UnityEngine/RemoteNotificationType.cs | 1 + UnityEngine/UnityEngine/RenderBuffer.cs | 31 + UnityEngine/UnityEngine/RenderBufferHelper.cs | 20 + UnityEngine/UnityEngine/RenderSettings.cs | 156 + UnityEngine/UnityEngine/RenderTargetSetup.cs | 84 + UnityEngine/UnityEngine/RenderTexture.cs | 2 +- .../UnityEngine/RenderTextureFormat.cs | 6 +- UnityEngine/UnityEngine/Renderer.cs | 89 +- UnityEngine/UnityEngine/RenderingPath.cs | 3 +- UnityEngine/UnityEngine/Rigidbody.cs | 40 +- .../UnityEngine/RuntimeAnimatorController.cs | 7 + .../RuntimeInitializeOnLoadMethodAttribute.cs | 8 + UnityEngine/UnityEngine/RuntimePlatform.cs | 10 +- UnityEngine/UnityEngine/Screen.cs | 43 +- UnityEngine/UnityEngine/Security.cs | 62 +- UnityEngine/UnityEngine/SendMouseEvents.cs | 25 +- UnityEngine/UnityEngine/Shader.cs | 13 +- .../UnityEngine/ShaderVariantCollection.cs | 77 + .../SharedBetweenAnimatorsAttribute.cs | 8 + .../UnityEngine/SkinnedMeshRenderer.cs | 11 - UnityEngine/UnityEngine/SliderHandler.cs | 5 +- UnityEngine/UnityEngine/SoftJointLimit.cs | 22 +- .../UnityEngine/SoftJointLimitSpring.cs | 31 + UnityEngine/UnityEngine/SplatPrototype.cs | 25 + UnityEngine/UnityEngine/Sprite.cs | 33 + UnityEngine/UnityEngine/StackTraceUtility.cs | 4 + .../UnityEngine/StateMachineBehaviour.cs | 28 + UnityEngine/UnityEngine/SurfaceEffector2D.cs | 26 + UnityEngine/UnityEngine/SystemInfo.cs | 27 +- UnityEngine/UnityEngine/SystemLanguage.cs | 2 + UnityEngine/UnityEngine/Terrain.cs | 697 +- UnityEngine/UnityEngine/TerrainData.cs | 37 +- UnityEngine/UnityEngine/TextEditor.cs | 17 +- UnityEngine/UnityEngine/TextGenerator.cs | 142 +- UnityEngine/UnityEngine/Texture.cs | 14 +- UnityEngine/UnityEngine/Texture2D.cs | 19 +- UnityEngine/UnityEngine/TextureFormat.cs | 23 +- .../UnityEngine/TouchScreenKeyboard.cs | 26 +- UnityEngine/UnityEngine/TrackedReference.cs | 1 - UnityEngine/UnityEngine/TransitionType.cs | 10 + UnityEngine/UnityEngine/Tree.cs | 6 + UnityEngine/UnityEngine/TreeInstance.cs | 92 +- .../UnityAPICompatibilityVersionAttribute.cs | 20 + .../UnityEngine/UnityEventQueueSystem.cs | 35 + UnityEngine/UnityEngine/Vector3.cs | 2 +- UnityEngine/UnityEngine/WWW.cs | 237 +- UnityEngine/UnityEngine/WWWForm.cs | 11 +- UnityEngine/UnityEngine/WebCamTexture.cs | 3 +- UnityEngine/UnityEngine/WheelCollider.cs | 30 + UnityEngine/UnityEngine/WindZone.cs | 2 +- UnityEngine/UnityEngine/WindZoneMode.cs | 2 +- .../UnityEngine/iOSActivityIndicatorStyle.cs | 6 +- UnityEngine/UnityEngine/iPhone.cs | 107 +- .../UnityEngine/iPhoneAccelerationEvent.cs | 22 +- UnityEngine/UnityEngine/iPhoneGeneration.cs | 30 +- UnityEngine/UnityEngine/iPhoneInput.cs | 77 +- UnityEngine/UnityEngine/iPhoneKeyboard.cs | 128 +- UnityEngine/UnityEngine/iPhoneKeyboardType.cs | 11 +- ...oard_InternalConstructorHelperArguments.cs | 14 - .../UnityEngine/iPhoneMovieControlMode.cs | 8 +- .../UnityEngine/iPhoneMovieScalingMode.cs | 7 +- .../UnityEngine/iPhoneNetworkReachability.cs | 6 +- UnityEngine/UnityEngine/iPhoneOrientation.cs | 10 +- .../UnityEngine/iPhoneScreenOrientation.cs | 9 +- UnityEngine/UnityEngine/iPhoneSettings.cs | 158 +- UnityEngine/UnityEngine/iPhoneTouch.cs | 58 +- UnityEngine/UnityEngine/iPhoneTouchPhase.cs | 8 +- UnityEngine/UnityEngine/iPhoneUtils.cs | 64 +- .../APIUpdaterRuntimeServices.cs | 71 + .../GIDebugVisualisation.cs | 48 + .../UnityEngineInternal/GITextureType.cs | 15 + .../UnityEngineInternal/LightmapType.cs | 10 + .../UnityEngineInternal/MathfInternal.cs | 10 + 897 files changed, 55829 insertions(+), 25762 deletions(-) delete mode 100644 UnityEditor/FlashDotNetAPIValidationRule.cs delete mode 100644 UnityEditor/FlashFileHelper.cs delete mode 100644 UnityEditor/FlashPostProcessSettings.cs delete mode 100644 UnityEditor/FlashTemplateWriterUtility.cs delete mode 100644 UnityEditor/GendarmeXMLTemplateTags.cs delete mode 100644 UnityEditor/LinuxDesktopStandalonePostProcessor.cs delete mode 100644 UnityEditor/MxmlcHelper.cs delete mode 100644 UnityEditor/NUnitFrameworkUser.cs delete mode 100644 UnityEditor/OSXDesktopStandalonePostProcessor.cs delete mode 100644 UnityEditor/PostProcessFlashPlayer.cs delete mode 100644 UnityEditor/PostProcessFlashPlayerOptions.cs delete mode 100644 UnityEditor/SerializedFileContainerPreparer.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorCondition.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorConditionMode.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorController.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorControllerLayer.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorLayerBlendingMode.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorState.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorStateMachine.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorStateTransition.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorTransition.cs create mode 100644 UnityEditor/UnityEditor.Animations/AnimatorTransitionBase.cs rename UnityEditor/{UnityEditorInternal => UnityEditor.Animations}/AvatarMask.cs (88%) create mode 100644 UnityEditor/UnityEditor.Animations/BlendTree.cs rename UnityEditor/{UnityEditorInternal => UnityEditor.Animations}/BlendTreeType.cs (56%) create mode 100644 UnityEditor/UnityEditor.Animations/ChildAnimatorState.cs create mode 100644 UnityEditor/UnityEditor.Animations/ChildAnimatorStateMachine.cs create mode 100644 UnityEditor/UnityEditor.Animations/ChildMotion.cs create mode 100644 UnityEditor/UnityEditor.Animations/MecanimUtilities.cs create mode 100644 UnityEditor/UnityEditor.Animations/PushUndoIfNeeded.cs create mode 100644 UnityEditor/UnityEditor.Animations/StateBehavioursPair.cs create mode 100644 UnityEditor/UnityEditor.Animations/StateMachineBehaviourContext.cs create mode 100644 UnityEditor/UnityEditor.Animations/StateMotionPair.cs create mode 100644 UnityEditor/UnityEditor.Animations/TransitionInterruptionSource.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioEffectParameterPath.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioGroupParameterPath.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioMixerController.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioMixerEffectController.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioMixerEffectPlugin.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioMixerGroupController.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioMixerSnapshotController.cs create mode 100644 UnityEditor/UnityEditor.Audio/AudioParameterPath.cs create mode 100644 UnityEditor/UnityEditor.Audio/ChangedExposedParameterHandler.cs create mode 100644 UnityEditor/UnityEditor.Audio/ExposedAudioParameter.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerEffectDefinition.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerEffectDefinitionReloader.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerEffectDefinitions.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerEffectParameter.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerGroupControllerCompareByName.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerGroupView.cs create mode 100644 UnityEditor/UnityEditor.Audio/MixerParameterDefinition.cs create mode 100644 UnityEditor/UnityEditor.Audio/ParameterTransitionType.cs create mode 100644 UnityEditor/UnityEditor.Hardware/DevDevice.cs create mode 100644 UnityEditor/UnityEditor.Hardware/DevDeviceFeatures.cs create mode 100644 UnityEditor/UnityEditor.Hardware/DevDeviceList.cs create mode 100644 UnityEditor/UnityEditor.Hardware/DevDeviceState.cs create mode 100644 UnityEditor/UnityEditor.Hardware/Usb.cs create mode 100644 UnityEditor/UnityEditor.Hardware/UsbDevice.cs delete mode 100644 UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor.Modules/DefaultPluginImporterExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/IBuildWindowExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/IDevice.cs create mode 100644 UnityEditor/UnityEditor.Modules/IPluginImporterExtension.cs create mode 100644 UnityEditor/UnityEditor.Modules/IScriptingImplementations.cs create mode 100644 UnityEditor/UnityEditor.Modules/IUserAssembliesValidator.cs create mode 100644 UnityEditor/UnityEditor.Modules/ModuleUtils.cs create mode 100644 UnityEditor/UnityEditor.Modules/RemoteAddress.cs create mode 100644 UnityEditor/UnityEditor.NScreen/NScreenManager.cs create mode 100644 UnityEditor/UnityEditor.NScreen/RemoteGame.cs delete mode 100644 UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAudioMixer.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/APIUpdaterHelper.cs delete mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatus.cs create mode 100644 UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatusCode.cs create mode 100644 UnityEditor/UnityEditor.Scripting/APIUpdaterHelper.cs create mode 100644 UnityEditor/UnityEditor.Scripting/APIUpdaterLogger.cs create mode 100644 UnityEditor/UnityEditor.Sprites/SpriteUtility.cs delete mode 100644 UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs create mode 100644 UnityEditor/UnityEditor/ActionOnDotNetUnhandledException.cs create mode 100644 UnityEditor/UnityEditor/AndroidBanner.cs create mode 100644 UnityEditor/UnityEditor/AssetBundleBuild.cs create mode 100644 UnityEditor/UnityEditor/AssetBundleNameGUI.cs create mode 100644 UnityEditor/UnityEditor/AssetPopupBackend.cs create mode 100644 UnityEditor/UnityEditor/AssetSelectionPopupMenu.cs create mode 100644 UnityEditor/UnityEditor/AssetsTreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/AudioCurveRendering.cs create mode 100644 UnityEditor/UnityEditor/AudioGroupDataSource.cs create mode 100644 UnityEditor/UnityEditor/AudioGroupTreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/AudioGroupTreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/AudioImporterSampleSettings.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerChannelStripView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerColorCodes.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerControllerInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerDrawUtils.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerEffectGUI.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerEffectView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerExposedParameterView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerExposedParametersPopup.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerGroupEditor.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerGroupPopupContext.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerGroupSelector.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerGroupTreeView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerGroupViewList.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerItem.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerSelection.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerSnapshotControllerInspector.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerSnapshotListView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerTreeViewDragging.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerTreeViewNode.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerUtility.cs create mode 100644 UnityEditor/UnityEditor/AudioMixerWindow.cs create mode 100644 UnityEditor/UnityEditor/AudioMixersDataSource.cs create mode 100644 UnityEditor/UnityEditor/AudioMixersTreeView.cs create mode 100644 UnityEditor/UnityEditor/AudioMixersTreeViewGUI.cs create mode 100644 UnityEditor/UnityEditor/AudioSampleRateSetting.cs delete mode 100644 UnityEditor/UnityEditor/BaseProjectWindow.cs create mode 100644 UnityEditor/UnityEditor/BillboardAssetInspector.cs create mode 100644 UnityEditor/UnityEditor/BillboardRendererInspector.cs create mode 100644 UnityEditor/UnityEditor/ClipAnimationInfoCurve.cs create mode 100644 UnityEditor/UnityEditor/ClothInspectorState.cs create mode 100644 UnityEditor/UnityEditor/ColliderEditorUtility.cs create mode 100644 UnityEditor/UnityEditor/ComplexD.cs create mode 100644 UnityEditor/UnityEditor/CubemapInspector.cs create mode 100644 UnityEditor/UnityEditor/CubemapPreview.cs delete mode 100644 UnityEditor/UnityEditor/CubemapTextureInspector.cs create mode 100644 UnityEditor/UnityEditor/CustomLaunchScreenType.cs create mode 100644 UnityEditor/UnityEditor/D3D11FullscreenMode.cs rename UnityEngine/UnityEngine/SamsungTV.cs => UnityEditor/UnityEditor/DefaultAsset.cs (56%) create mode 100644 UnityEditor/UnityEditor/DefaultAssetInspector.cs create mode 100644 UnityEditor/UnityEditor/DefaultReflectionMode.cs create mode 100644 UnityEditor/UnityEditor/DesktopPluginImporterExtension.cs create mode 100644 UnityEditor/UnityEditor/DuckVolumeGUI.cs create mode 100644 UnityEditor/UnityEditor/EditorPluginImporterExtension.cs create mode 100644 UnityEditor/UnityEditor/Effector2DEditor.cs delete mode 100644 UnityEditor/UnityEditor/FlashBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/FogEditor.cs create mode 100644 UnityEditor/UnityEditor/FrameDebuggerWindow.cs create mode 100644 UnityEditor/UnityEditor/GUID.cs rename UnityEditor/UnityEditor/{AssetOrGameObjectTreeViewDragging.cs => GameObjectsTreeViewDragging.cs} (73%) create mode 100644 UnityEditor/UnityEditor/GraphicsSettings.cs create mode 100644 UnityEditor/UnityEditor/GraphicsSettingsInspector.cs delete mode 100644 UnityEditor/UnityEditor/HierarchyWindow.cs create mode 100644 UnityEditor/UnityEditor/HingeJointEditor.cs create mode 100644 UnityEditor/UnityEditor/IAudioEffectPlugin.cs create mode 100644 UnityEditor/UnityEditor/IAudioEffectPluginGUI.cs create mode 100644 UnityEditor/UnityEditor/IDeviceUtils.cs create mode 100644 UnityEditor/UnityEditor/InitializeOnLoadMethodAttribute.cs create mode 100644 UnityEditor/UnityEditor/KnobState.cs create mode 100644 UnityEditor/UnityEditor/LODGroupGUI.cs create mode 100644 UnityEditor/UnityEditor/LegacyIlluminShaderGUI.cs create mode 100644 UnityEditor/UnityEditor/LightingEditor.cs create mode 100644 UnityEditor/UnityEditor/LightingWindow.cs create mode 100644 UnityEditor/UnityEditor/LightingWindowLightmapPreviewTab.cs create mode 100644 UnityEditor/UnityEditor/LightingWindowObjectTab.cs create mode 100644 UnityEditor/UnityEditor/LightmapParameters.cs create mode 100644 UnityEditor/UnityEditor/LightmapParametersEditor.cs create mode 100644 UnityEditor/UnityEditor/LightmapVisualizationUtility.cs delete mode 100644 UnityEditor/UnityEditor/LightmappingWindow.cs create mode 100644 UnityEditor/UnityEditor/LineRendererInspector.cs create mode 100644 UnityEditor/UnityEditor/MaterialHeaderDecorator.cs create mode 100644 UnityEditor/UnityEditor/MaterialPropertyHandler.cs create mode 100644 UnityEditor/UnityEditor/MaterialSpaceDecorator.cs delete mode 100644 UnityEditor/UnityEditor/MecanimUtilities.cs create mode 100644 UnityEditor/UnityEditor/Menu.cs delete mode 100644 UnityEditor/UnityEditor/MetroBuildType.cs rename UnityEditor/UnityEditor/{BlackBerryBuildSubtarget.cs => MobileTextureSubtarget.cs} (52%) create mode 100644 UnityEditor/UnityEditor/MonoProcessRunner.cs create mode 100644 UnityEditor/UnityEditor/ObjectPreviewPopup.cs create mode 100644 UnityEditor/UnityEditor/ObjectTreeForSelector.cs create mode 100644 UnityEditor/UnityEditor/OtherRenderingEditor.cs create mode 100644 UnityEditor/UnityEditor/PS4BuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/PSMBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/ParamEqGUI.cs create mode 100644 UnityEditor/UnityEditor/ParticleRendererEditor.cs create mode 100644 UnityEditor/UnityEditor/PluginImporter.cs create mode 100644 UnityEditor/UnityEditor/PluginImporterInspector.cs rename UnityEditor/UnityEditor/{PolygonColliderEditor.cs => PolygonCollider2DEditor.cs} (67%) create mode 100644 UnityEditor/UnityEditor/ProfilerChoise.cs create mode 100644 UnityEditor/UnityEditor/ReflectionProbeEditor.cs create mode 100644 UnityEditor/UnityEditor/RenderSettingsInspector.cs create mode 100644 UnityEditor/UnityEditor/RendererEditorBase.cs create mode 100644 UnityEditor/UnityEditor/SceneRenderModeWindow.cs create mode 100644 UnityEditor/UnityEditor/SemanticMergeMode.cs delete mode 100644 UnityEditor/UnityEditor/SerializedFileContainerWriter.cs create mode 100644 UnityEditor/UnityEditor/ShaderGUI.cs create mode 100644 UnityEditor/UnityEditor/ShaderGUIUtility.cs create mode 100644 UnityEditor/UnityEditor/ShaderInspectorPlatformsPopup.cs create mode 100644 UnityEditor/UnityEditor/ShaderVariantCollectionInspector.cs create mode 100644 UnityEditor/UnityEditor/ShadowCascadeSplitGUI.cs create mode 100644 UnityEditor/UnityEditor/SliderLabels.cs create mode 100644 UnityEditor/UnityEditor/SpeedTreeImporter.cs create mode 100644 UnityEditor/UnityEditor/SpeedTreeImporterInspector.cs create mode 100644 UnityEditor/UnityEditor/SpeedTreeMaterialInspector.cs rename UnityEditor/UnityEditor/{SpriteRendererInspector.cs => SpriteRendererEditor.cs} (69%) create mode 100644 UnityEditor/UnityEditor/StandardShaderGUI.cs delete mode 100644 UnityEditor/UnityEditor/TextureImportInstructions.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterCubemapConvolution.cs create mode 100644 UnityEditor/UnityEditor/TextureImporterRGBMMode.cs create mode 100644 UnityEditor/UnityEditor/TickTimerHelper.cs delete mode 100644 UnityEditor/UnityEditor/TizenBuildSubtarget.cs create mode 100644 UnityEditor/UnityEditor/TrailRendererInspector.cs delete mode 100644 UnityEditor/UnityEditor/TreePlacementUtility.cs create mode 100644 UnityEditor/UnityEditor/TreeViewForAudioMixerGroup.cs create mode 100644 UnityEditor/UnityEditor/TreeViewItemAlphaNumericSort.cs rename UnityEditor/UnityEditor/{MetroBuildAndRunDeployTarget.cs => WSABuildAndRunDeployTarget.cs} (72%) rename UnityEditor/UnityEditor/{MetroSDK.cs => WSASDK.cs} (81%) delete mode 100644 UnityEditor/UnityEditor/WebScriptObject.cs create mode 100644 UnityEditor/UnityEditor/WebTemplate.cs create mode 100644 UnityEditor/UnityEditor/WebTemplateManagerBase.cs create mode 100644 UnityEditor/UnityEditor/XboxOneDeployMethod.cs create mode 100644 UnityEditor/UnityEditor/XboxOneEncryptionLevel.cs delete mode 100644 UnityEditor/UnityEditor/XboxOneRunMethod.cs create mode 100644 UnityEditor/UnityEditor/iOSAppInBackgroundBehavior.cs delete mode 100644 UnityEditor/UnityEditor/iOSLaunchScreenType.cs delete mode 100644 UnityEditor/UnityEditor/iPhoneArchitecture.cs delete mode 100644 UnityEditor/UnityEditorInternal/AnimatorCondition.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerBackend.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerInfo.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerInfoHelper.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerInfoWrapper.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerTreeViewState.cs create mode 100644 UnityEditor/UnityEditorInternal/AudioProfilerView.cs delete mode 100644 UnityEditor/UnityEditorInternal/CameraUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/EditMode.cs create mode 100644 UnityEditor/UnityEditorInternal/FrameDebuggerEvent.cs create mode 100644 UnityEditor/UnityEditorInternal/FrameDebuggerTreeView.cs create mode 100644 UnityEditor/UnityEditorInternal/FrameDebuggerUtility.cs create mode 100644 UnityEditor/UnityEditorInternal/FrameEventType.cs create mode 100644 UnityEditor/UnityEditorInternal/ModuleMetadata.cs create mode 100644 UnityEditor/UnityEditorInternal/PluginsHelper.cs delete mode 100644 UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs create mode 100644 UnityEditor/UnityEditorInternal/ProfilerAudioView.cs create mode 100644 UnityEditor/UnityEditorInternal/ReorderableListWithRenameAndScrollView.cs create mode 100644 UnityEditor/UnityEditorInternal/ScriptUpdatingManager.cs delete mode 100644 UnityEditor/UnityEditorInternal/TransitionConditionMode.cs create mode 100644 UnityEditor/UnityEngine/NScreenBridge.cs create mode 100644 UnityEditor/UnityEngine/RuntimeInitializeClassInfo.cs create mode 100644 UnityEditor/UnityEngine/RuntimeInitializeMethodInfo.cs create mode 100644 UnityEditor/UnityEngine/RuntimeInitializeOnLoadManager.cs delete mode 100644 UnityEditor/WindowsDesktopStandalonePostProcessor.cs create mode 100644 UnityEngine/JetBrains.Annotations/AssertionMethodAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/BaseTypeRequiredAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/CanBeNullAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/CannotApplyEqualityOperatorAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/ContractAnnotationAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/ImplicitUseKindFlags.cs create mode 100644 UnityEngine/JetBrains.Annotations/ImplicitUseTargetFlags.cs create mode 100644 UnityEngine/JetBrains.Annotations/InstantHandleAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/InvokerParameterNameAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/LinqTunnelAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/LocalizationRequiredAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/MeansImplicitUseAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/NoEnumerationAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/NotNullAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/NotifyPropertyChangedInvocatorAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/PathReferenceAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/PublicAPIAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/PureAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/StringFormatMethodAttribute.cs create mode 100644 UnityEngine/JetBrains.Annotations/UsedImplicitlyAttribute.cs create mode 100644 UnityEngine/UnityEngine.Audio/AudioMixer.cs create mode 100644 UnityEngine/UnityEngine.Audio/AudioMixerGroup.cs create mode 100644 UnityEngine/UnityEngine.Audio/AudioMixerSnapshot.cs delete mode 100644 UnityEngine/UnityEngine.Flash/ActionScript.cs delete mode 100644 UnityEngine/UnityEngine.Flash/FlashPlayer.cs create mode 100644 UnityEngine/UnityEngine.Rendering/AmbientMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/BuiltinRenderTextureType.cs create mode 100644 UnityEngine/UnityEngine.Rendering/CameraEvent.cs create mode 100644 UnityEngine/UnityEngine.Rendering/CommandBuffer.cs create mode 100644 UnityEngine/UnityEngine.Rendering/DefaultReflectionMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/PassType.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeBlendInfo.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeClearFlags.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeRefreshMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeTimeSlicingMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeType.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ReflectionProbeUsage.cs create mode 100644 UnityEngine/UnityEngine.Rendering/RenderBufferLoadAction.cs create mode 100644 UnityEngine/UnityEngine.Rendering/RenderBufferStoreAction.cs create mode 100644 UnityEngine/UnityEngine.Rendering/RenderTargetIdentifier.cs create mode 100644 UnityEngine/UnityEngine.Rendering/ShadowCastingMode.cs create mode 100644 UnityEngine/UnityEngine.Rendering/SphericalHarmonicsL2.cs delete mode 100644 UnityEngine/UnityEngine.Serialization/SerializationHelper.cs create mode 100644 UnityEngine/UnityEngine.iOS/ADBannerView.cs create mode 100644 UnityEngine/UnityEngine.iOS/ADInterstitialAd.cs create mode 100644 UnityEngine/UnityEngine.iOS/ActivityIndicatorStyle.cs create mode 100644 UnityEngine/UnityEngine.iOS/CalendarIdentifier.cs create mode 100644 UnityEngine/UnityEngine.iOS/CalendarUnit.cs create mode 100644 UnityEngine/UnityEngine.iOS/Device.cs create mode 100644 UnityEngine/UnityEngine.iOS/DeviceGeneration.cs create mode 100644 UnityEngine/UnityEngine.iOS/LocalNotification.cs create mode 100644 UnityEngine/UnityEngine.iOS/NotificationServices.cs rename UnityEngine/{UnityEngine/LocalNotificationType.cs => UnityEngine.iOS/NotificationType.cs} (52%) create mode 100644 UnityEngine/UnityEngine.iOS/RemoteNotification.cs create mode 100644 UnityEngine/UnityEngine/AnimationEventSource.cs create mode 100644 UnityEngine/UnityEngine/AnimatorClipInfo.cs create mode 100644 UnityEngine/UnityEngine/AnimatorControllerParameter.cs create mode 100644 UnityEngine/UnityEngine/AnimatorControllerParameterType.cs create mode 100644 UnityEngine/UnityEngine/AnimatorRecorderMode.cs create mode 100644 UnityEngine/UnityEngine/ApplicationInstallMode.cs create mode 100644 UnityEngine/UnityEngine/ApplicationSandboxType.cs create mode 100644 UnityEngine/UnityEngine/AreaEffector2D.cs create mode 100644 UnityEngine/UnityEngine/AssetBundleManifest.cs create mode 100644 UnityEngine/UnityEngine/AudioClipLoadType.cs create mode 100644 UnityEngine/UnityEngine/AudioCompressionFormat.cs create mode 100644 UnityEngine/UnityEngine/AudioConfiguration.cs create mode 100644 UnityEngine/UnityEngine/AudioDataLoadState.cs create mode 100644 UnityEngine/UnityEngine/AvatarIKHint.cs create mode 100644 UnityEngine/UnityEngine/BillboardAsset.cs rename UnityEngine/UnityEngine/{ClothRenderer.cs => BillboardRenderer.cs} (73%) delete mode 100644 UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs create mode 100644 UnityEngine/UnityEngine/CastHelper.cs create mode 100644 UnityEngine/UnityEngine/ClothSphereColliderPair.cs create mode 100644 UnityEngine/UnityEngine/ConstantForce2D.cs create mode 100644 UnityEngine/UnityEngine/CursorLockMode.cs create mode 100644 UnityEngine/UnityEngine/DisableBatchingType.cs create mode 100644 UnityEngine/UnityEngine/DynamicGI.cs create mode 100644 UnityEngine/UnityEngine/Effector2D.cs create mode 100644 UnityEngine/UnityEngine/EffectorForceMode2D.cs create mode 100644 UnityEngine/UnityEngine/EffectorSelection2D.cs create mode 100644 UnityEngine/UnityEngine/EllipsoidParticleEmitter.cs create mode 100644 UnityEngine/UnityEngine/FlareLayer.cs create mode 100644 UnityEngine/UnityEngine/Hash128.cs delete mode 100644 UnityEngine/UnityEngine/InteractiveCloth.cs create mode 100644 UnityEngine/UnityEngine/LightmapsModeLegacy.cs create mode 100644 UnityEngine/UnityEngine/MaterialGlobalIlluminationFlags.cs create mode 100644 UnityEngine/UnityEngine/MeshParticleEmitter.cs create mode 100644 UnityEngine/UnityEngine/NavMeshObstacleShape.cs create mode 100644 UnityEngine/UnityEngine/ParticleCollisionEvent.cs create mode 100644 UnityEngine/UnityEngine/ParticlePhysicsExtensions.cs create mode 100644 UnityEngine/UnityEngine/ParticleSystemExtensionsImpl.cs create mode 100644 UnityEngine/UnityEngine/PhysicsUpdateBehaviour2D.cs rename UnityEngine/UnityEngine/{SkinnedCloth.cs => PlatformEffector2D.cs} (52%) create mode 100644 UnityEngine/UnityEngine/PointEffector2D.cs delete mode 100644 UnityEngine/UnityEngine/RaycastCollider.cs delete mode 100644 UnityEngine/UnityEngine/ReferenceData.cs create mode 100644 UnityEngine/UnityEngine/ReflectionProbe.cs create mode 100644 UnityEngine/UnityEngine/RenderBufferHelper.cs create mode 100644 UnityEngine/UnityEngine/RenderTargetSetup.cs create mode 100644 UnityEngine/UnityEngine/RuntimeInitializeOnLoadMethodAttribute.cs create mode 100644 UnityEngine/UnityEngine/ShaderVariantCollection.cs create mode 100644 UnityEngine/UnityEngine/SharedBetweenAnimatorsAttribute.cs create mode 100644 UnityEngine/UnityEngine/SoftJointLimitSpring.cs create mode 100644 UnityEngine/UnityEngine/StateMachineBehaviour.cs create mode 100644 UnityEngine/UnityEngine/SurfaceEffector2D.cs create mode 100644 UnityEngine/UnityEngine/TransitionType.cs create mode 100644 UnityEngine/UnityEngine/UnityAPICompatibilityVersionAttribute.cs create mode 100644 UnityEngine/UnityEngine/UnityEventQueueSystem.cs delete mode 100644 UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs create mode 100644 UnityEngine/UnityEngineInternal/APIUpdaterRuntimeServices.cs create mode 100644 UnityEngine/UnityEngineInternal/GIDebugVisualisation.cs create mode 100644 UnityEngine/UnityEngineInternal/GITextureType.cs create mode 100644 UnityEngine/UnityEngineInternal/LightmapType.cs create mode 100644 UnityEngine/UnityEngineInternal/MathfInternal.cs diff --git a/README.md b/README.md index 7a6a3fa4..3bf914e2 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ This was made by decompiling UnityEditor.dll and UnityEngine.dll using [ILSpy](http://ilspy.net) -Current version: *4.6.3f1* - other versions can be found in the [tags](https://github.com/MattRix/UnityDecompiled/tags) +Current version: *5.0.0f3* - other versions can be found in the [tags](https://github.com/MattRix/UnityDecompiled/tags) Feel free to either browse the code directly or [download it](https://github.com/MattRix/UnityDecompiled/archive/master.zip) diff --git a/UnityEditor/AssemblyValidation.cs b/UnityEditor/AssemblyValidation.cs index d36c8ebd..4c6586d3 100644 --- a/UnityEditor/AssemblyValidation.cs +++ b/UnityEditor/AssemblyValidation.cs @@ -55,10 +55,10 @@ select AssemblyValidation.CreateValidationRuleWithOptions(t, options) into v [DebuggerHidden] private static IEnumerable ValidationRuleTypesFor(RuntimePlatform platform) { - AssemblyValidation.c__Iterator2 c__Iterator = new AssemblyValidation.c__Iterator2(); + AssemblyValidation.c__Iterator3 c__Iterator = new AssemblyValidation.c__Iterator3(); c__Iterator.platform = platform; c__Iterator.<$>platform = platform; - AssemblyValidation.c__Iterator2 expr_15 = c__Iterator; + AssemblyValidation.c__Iterator3 expr_15 = c__Iterator; expr_15.$PC = -2; return expr_15; } diff --git a/UnityEditor/DesktopStandalonePostProcessor.cs b/UnityEditor/DesktopStandalonePostProcessor.cs index 3c803262..e8e6f596 100644 --- a/UnityEditor/DesktopStandalonePostProcessor.cs +++ b/UnityEditor/DesktopStandalonePostProcessor.cs @@ -3,6 +3,7 @@ using UnityEditor; using UnityEditor.Modules; using UnityEditorInternal; +using UnityEngine; internal abstract class DesktopStandalonePostProcessor { protected BuildPostProcessArgs m_PostProcessArgs; @@ -70,6 +71,9 @@ protected bool Development return (this.m_PostProcessArgs.options & BuildOptions.Development) != BuildOptions.None; } } + protected DesktopStandalonePostProcessor() + { + } protected DesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) { this.m_PostProcessArgs = postProcessArgs; @@ -79,10 +83,82 @@ public void PostProcess() this.SetupStagingArea(); this.CopyStagingAreaIntoDestination(); } + private void CopyNativePlugins() + { + string buildTargetName = BuildPipeline.GetBuildTargetName(this.m_PostProcessArgs.target); + IPluginImporterExtension pluginImporterExtension = new DesktopPluginImporterExtension(); + string stagingAreaPluginsFolder = this.StagingAreaPluginsFolder; + string path = Path.Combine(stagingAreaPluginsFolder, "x86"); + string path2 = Path.Combine(stagingAreaPluginsFolder, "x86_64"); + bool flag = false; + bool flag2 = false; + bool flag3 = false; + PluginImporter[] importers = PluginImporter.GetImporters(this.m_PostProcessArgs.target); + for (int i = 0; i < importers.Length; i++) + { + PluginImporter pluginImporter = importers[i]; + BuildTarget target = this.m_PostProcessArgs.target; + if (pluginImporter.isNativePlugin) + { + if (string.IsNullOrEmpty(pluginImporter.assetPath)) + { + Debug.LogWarning("Got empty plugin importer path for " + this.m_PostProcessArgs.target.ToString()); + } + else + { + if (!flag) + { + Directory.CreateDirectory(stagingAreaPluginsFolder); + flag = true; + } + bool flag4 = Directory.Exists(pluginImporter.assetPath); + string platformData = pluginImporter.GetPlatformData(target, "CPU"); + string text = platformData; + switch (text) + { + case "x86": + if (target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneWindows64 || target == BuildTarget.StandaloneLinux64) + { + goto IL_21A; + } + if (!flag2) + { + Directory.CreateDirectory(path); + flag2 = true; + } + break; + case "x86_64": + if (target != BuildTarget.StandaloneOSXIntel64 && target != BuildTarget.StandaloneOSXUniversal && target != BuildTarget.StandaloneWindows64 && target != BuildTarget.StandaloneLinux64 && target != BuildTarget.StandaloneLinuxUniversal) + { + goto IL_21A; + } + if (!flag3) + { + Directory.CreateDirectory(path2); + flag3 = true; + } + break; + case "None": + goto IL_21A; + } + string text2 = Path.Combine(stagingAreaPluginsFolder, pluginImporterExtension.CalculateFinalPluginPath(buildTargetName, pluginImporter)); + if (flag4) + { + FileUtil.CopyDirectoryRecursive(pluginImporter.assetPath, text2); + } + else + { + FileUtil.UnityFileCopy(pluginImporter.assetPath, text2); + } + } + } + IL_21A:; + } + } protected virtual void SetupStagingArea() { Directory.CreateDirectory(this.DataFolder); - PostprocessBuildPlayer.InstallPlugins(this.StagingAreaPluginsFolder, this.m_PostProcessArgs.target); + this.CopyNativePlugins(); PostprocessBuildPlayer.InstallStreamingAssets(this.DataFolder); if (this.UseIl2Cpp) { @@ -108,18 +184,23 @@ protected virtual void CopyVariationFolderIntoStagingArea() } protected void CopyStagingAreaIntoDestination() { - if (this.InstallingIntoBuildsFolder) + if (!this.InstallingIntoBuildsFolder) { - FileUtil.CopyDirectoryFiltered(this.DataFolder, Unsupported.GetBaseUnityDeveloperFolder() + "/" + this.DestinationFolderForInstallingIntoBuildsFolder, true, (string f) => true, true); + this.DeleteDestination(); + FileUtil.CopyDirectoryFiltered(this.StagingArea, this.DestinationFolder, true, (string f) => true, true); return; } - this.DeleteDestination(); - FileUtil.CopyDirectoryFiltered(this.StagingArea, this.DestinationFolder, true, (string f) => true, true); + string text = Unsupported.GetBaseUnityDeveloperFolder() + "/" + this.DestinationFolderForInstallingIntoBuildsFolder; + if (!Directory.Exists(Path.GetDirectoryName(text))) + { + throw new Exception("Installing in builds folder failed because the player has not been built (You most likely want to enable 'Development build')."); + } + FileUtil.CopyDirectoryFiltered(this.DataFolder, text, true, (string f) => true, true); } protected abstract void DeleteDestination(); protected virtual string GetVariationName() { - return this.PlatformStringFor(this.m_PostProcessArgs.target) + "_" + (((this.m_PostProcessArgs.options & BuildOptions.Development) == BuildOptions.None) ? "nondevelopment" : "development"); + return string.Format("{0}_{1}", this.PlatformStringFor(this.m_PostProcessArgs.target), (!this.Development) ? "nondevelopment" : "development"); } protected abstract string PlatformStringFor(BuildTarget target); protected abstract void RenameFilesInStagingArea(); diff --git a/UnityEditor/FlashDotNetAPIValidationRule.cs b/UnityEditor/FlashDotNetAPIValidationRule.cs deleted file mode 100644 index d4ded628..00000000 --- a/UnityEditor/FlashDotNetAPIValidationRule.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEngine; -[AssemblyValidationRule(RuntimePlatform.FlashPlayer)] -internal class FlashDotNetAPIValidationRule : GendarmeValidationRule -{ - private readonly string _configFilePath; - private readonly FlashFileHelper _fileHelper; - private readonly FlashPostProcessSettings _settings; - public FlashDotNetAPIValidationRule(PostProcessFlashPlayerOptions options) : base(FlashFileHelper.CreateFrom(options).PathForGendarmeExe()) - { - this._fileHelper = FlashFileHelper.CreateFrom(options); - this._settings = FlashPostProcessSettings.CreateFrom(options); - this._configFilePath = Path.GetTempFileName(); - } - ~FlashDotNetAPIValidationRule() - { - File.Delete(this._configFilePath); - } - protected override GendarmeOptions ConfigureGendarme(IEnumerable userAssemblies) - { - string[] array = (userAssemblies as string[]) ?? userAssemblies.ToArray(); - if (array.Length != 0) - { - this.UpdateRulesTemplate(); - } - return new GendarmeOptions - { - ConfigFilePath = this._configFilePath, - RuleSet = "UnityFlash", - UserAssemblies = array - }; - } - private void UpdateRulesTemplate() - { - GendarmeXMLTemplateTags gendarmeXMLTemplateTags = new GendarmeXMLTemplateTags(); - gendarmeXMLTemplateTags.LimitToNamespaces.Add("System"); - gendarmeXMLTemplateTags.WhiteListFiles.Add(this._fileHelper.PathForFileInCil2As("gendarme-whitelist.txt")); - FlashDotNetAPIValidationRule.AddHardcodedWhiteListTypes(gendarmeXMLTemplateTags); - FlashTemplateWriterUtility.WriteGendarmeXMLTemplate(this._settings, this._fileHelper, gendarmeXMLTemplateTags, this._configFilePath); - } - private static void AddHardcodedWhiteListTypes(GendarmeXMLTemplateTags gendarmeXMLTemplateTags) - { - string[] collection = new string[] - { - "System.Array", - "System.Enum", - "System.RuntimeTypeHandle", - "System.IFormattable", - "System.ValueType", - "System.Delegate", - "System.MulticastDelegate", - "System.Runtime.Serialization.ISerializable", - "System.Runtime.Serialization.IDeserializationCallback", - "System.RuntimeFieldHandle", - "System.Runtime.CompilerServices.RuntimeHelpers", - "System.Math", - "System.Func", - "System.Func`1", - "System.Func`2", - "System.Func`3", - "System.Func`4", - "System.Action", - "System.Action`1", - "System.Action`2", - "System.Action`3", - "System.Action`4", - "System.Predicate`1", - "System.Runtime.InteropServices._Exception", - "System.Runtime.InteropServices._Attribute", - "System.Comparison`1", - "System.AsyncCallback", - "System.AttributeTargets", - "System.StringSplitOptions", - "System.EventHandler`1", - "System.EventHandler" - }; - gendarmeXMLTemplateTags.WhiteListTypes.AddRange(collection); - } -} diff --git a/UnityEditor/FlashFileHelper.cs b/UnityEditor/FlashFileHelper.cs deleted file mode 100644 index 09d00e48..00000000 --- a/UnityEditor/FlashFileHelper.cs +++ /dev/null @@ -1,187 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEditor.Scripting.Compilers; -internal class FlashFileHelper -{ - public string ProjectFolder - { - get; - private set; - } - public string InstallPath - { - get; - private set; - } - public string PlayerPackage - { - get; - private set; - } - public string StagingArea - { - get; - private set; - } - private FlashFileHelper(string stagingArea, string playerPackage, string installPath) - { - this.StagingArea = stagingArea; - this.PlayerPackage = playerPackage; - this.InstallPath = installPath; - this.ProjectFolder = Directory.GetCurrentDirectory(); - } - internal IEnumerable GetUserAssemblies() - { - return ( - from s in Directory.GetFiles(this.PathForManagedCode(), "*.dll") - where FlashFileHelper.IsUserCodeAssembly(Path.GetFileName(s)) - select s).ToArray(); - } - internal IEnumerable FindUserSwcs() - { - return this.FindActionScriptDirectoriesInProject().SelectMany((string dir) => Directory.GetFiles(dir, "*.swc", SearchOption.AllDirectories)); - } - internal IEnumerable FindUserSourcePaths() - { - return this.FindActionScriptDirectoriesInProject(); - } - private IEnumerable FindActionScriptDirectoriesInProject() - { - return Directory.GetDirectories(this.Combine(this.ProjectFolder, "Assets"), "ActionScript", SearchOption.AllDirectories); - } - internal string FullPathForUnityNativeSwc(string swcFileName) - { - return this.PrepareFileName(this.Combine(this.PlayerPackage, swcFileName)); - } - internal string GetInstallPath() - { - return this.PrepareFileName(this.InstallPath); - } - private string PathForManagedCode() - { - return this.Combine(this.StagingArea, "Managed"); - } - internal string ProjectName() - { - return Path.GetFileNameWithoutExtension(this.InstallPath); - } - internal void CopyResourcesFromPlayerPackageToStaging() - { - FileUtil.CopyFileOrDirectory(this.Combine(this.PlayerPackage, this.Combine("Resources", "unity default resources")), this.Combine(this.StagingArea, this.Combine("Resources", "unity default resources"))); - } - internal void SaveUnprocessedSwfCopy() - { - FileUtil.CopyFileOrDirectory(this.PathForTempSwf(), this.PathForTempSwf().Replace("temp.swf", "unprocessed.swf")); - } - internal string PathForFlexFrameworks() - { - return this.PathForFlex("frameworks"); - } - internal string PathForUnityEngineDLL() - { - return this.Combine(this.Combine(this.PlayerPackage, "Managed"), "UnityEngine.dll"); - } - internal string PathForConvertedDotNetCode() - { - return this.Combine(this.PathForAs3Code(), "ConvertedDotNetCode"); - } - internal string PathForFileInBuildTools(string file) - { - return this.Combine(this.PathForBuildTools(), file); - } - internal string PathForInstallationDir() - { - return Path.GetDirectoryName(this.InstallPath); - } - internal string PathForFileInInstallPath(string file) - { - return this.Combine(this.PathForInstallationDir(), file); - } - internal string PathForUserBuildAs3() - { - return this.Combine(this.PathForBuildTools(), "UserBuild_AS3"); - } - internal string PathForAs3Code() - { - return this.StagingArea; - } - internal string PathForAs3Src() - { - return this.Combine(this.PathForAs3Code(), "src"); - } - internal string PathForUnityAppDotAs() - { - return this.PrepareFileName(this.Combine(this.PathForUserBuildAs3(), "UnityApp.as")); - } - internal string PathForHtmlInInstallPath() - { - return this.PathForFileInInstallPath(this.ProjectName() + ".html"); - } - internal string PathForCil2AsExe() - { - return this.PathForFileInCil2As("cil2as.exe"); - } - public string PathForFileInCil2As(string file) - { - return this.Combine(this.Combine(this.PathForBuildTools(), "cil2as"), file); - } - internal string PathForGendarmeExe() - { - return this.PathForFileInGendarme("Gendarme.exe"); - } - public string PathForFileInGendarme(string path) - { - return this.Combine(this.Combine(this.PathForBuildTools(), "Gendarme"), path); - } - internal string PathForSwfPostProcessorExe() - { - return this.Combine(this.PathForBuildTools(), "SwfPostProcessor.exe"); - } - internal string PathForMxmlc() - { - return this.PathForFlex(this.Combine("lib", "mxmlc.jar")); - } - internal string PathForFlex(string relativePath) - { - return this.PrepareFileName(this.Combine(this.PathForFlexHome(), relativePath).Replace("\\", "/")); - } - internal string PathForFlexHome() - { - return this.Combine(this.PathForBuildTools(), "Flex"); - } - internal string PathForBuildTools() - { - return this.Combine(this.PlayerPackage, "BuildTools"); - } - internal string PathForTempSwfUnprepared() - { - return this.Combine(this.ProjectFolder, this.Combine(this.StagingArea, "temp.swf")); - } - internal string PathForTempSwf() - { - return this.PrepareFileName(this.PathForTempSwfUnprepared()); - } - internal string Combine(string path1, string path2) - { - return Path.Combine(path1, path2); - } - internal string PrepareFileName(string file) - { - return CommandLineFormatter.PrepareFileName(file); - } - internal static FlashFileHelper CreateWithBuildArguments(string stagingArea, string playerPackage, string installPath) - { - return new FlashFileHelper(stagingArea, playerPackage, installPath); - } - internal static bool IsUserCodeAssembly(string file) - { - return !file.StartsWith("mscorlib.dll") && !file.StartsWith("System.") && !file.StartsWith("Mono.") && !file.StartsWith("UnityEngine.") && !file.StartsWith("Boo.") && !file.StartsWith("UnityScript.") && !file.StartsWith("UnityEngine.UI"); - } - public static FlashFileHelper CreateFrom(PostProcessFlashPlayerOptions options) - { - return FlashFileHelper.CreateWithBuildArguments(options.StagingAreaData, options.PlayerPackage, options.InstallPath); - } -} diff --git a/UnityEditor/FlashPostProcessSettings.cs b/UnityEditor/FlashPostProcessSettings.cs deleted file mode 100644 index d22154b0..00000000 --- a/UnityEditor/FlashPostProcessSettings.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -internal class FlashPostProcessSettings -{ - internal const string UnityFlashConstantNamespace = "UNITY_FLASH"; - public FlashBuildSubtarget FlashBuildSubtarget; - public bool IsDevelopment; - public bool StripPhysics; - public int Width; - public int Height; - internal string GetUnityNativeSwcForSubTarget(bool stripPhysics) - { - string str; - switch (this.FlashBuildSubtarget) - { - case FlashBuildSubtarget.Flash11dot2: - case FlashBuildSubtarget.Flash11dot3: - case FlashBuildSubtarget.Flash11dot4: - case FlashBuildSubtarget.Flash11dot5: - case FlashBuildSubtarget.Flash11dot6: - case FlashBuildSubtarget.Flash11dot7: - case FlashBuildSubtarget.Flash11dot8: - str = "UnityNative11dot2"; - break; - default: - str = "UnityNative11dot2"; - break; - } - if (this.StripPhysics) - { - str += "_nophysx"; - } - return str + ".swc"; - } - internal int GetSwfVersionForPlayerVersion() - { - switch (this.FlashBuildSubtarget) - { - case FlashBuildSubtarget.Flash11dot2: - return 15; - case FlashBuildSubtarget.Flash11dot3: - return 16; - case FlashBuildSubtarget.Flash11dot4: - return 17; - case FlashBuildSubtarget.Flash11dot5: - return 18; - case FlashBuildSubtarget.Flash11dot6: - return 19; - case FlashBuildSubtarget.Flash11dot7: - return 20; - case FlashBuildSubtarget.Flash11dot8: - return 21; - default: - return 15; - } - } - internal string GetTargetPlayerForSubtarget() - { - switch (this.FlashBuildSubtarget) - { - case FlashBuildSubtarget.Flash11dot2: - return "11.2.0"; - case FlashBuildSubtarget.Flash11dot3: - return "11.3.0"; - case FlashBuildSubtarget.Flash11dot4: - return "11.4.0"; - case FlashBuildSubtarget.Flash11dot5: - return "11.5.0"; - case FlashBuildSubtarget.Flash11dot6: - return "11.6.0"; - case FlashBuildSubtarget.Flash11dot7: - return "11.7.0"; - case FlashBuildSubtarget.Flash11dot8: - return "11.8.0"; - default: - return "11.2.0"; - } - } - internal string MxmlcCompileTimeConstants() - { - return FlashPostProcessSettings.CompileTimeConstantsFor(this).Aggregate(string.Empty, (string agg, KeyValuePair value) => agg + string.Format("-define+={0}::{1},{2} ", "UNITY_FLASH", value.Key, FlashPostProcessSettings.EncodeMxmlcConstant(value.Value))); - } - private static Dictionary CompileTimeConstantsFor(FlashPostProcessSettings settings) - { - Dictionary dictionary = new Dictionary - { - - { - "TargetFlashPlayerVersion", - settings.GetTargetPlayerForSubtarget() - }, - - { - "TargetSwfVersion", - settings.GetSwfVersionForPlayerVersion().ToString() - } - }; - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot2, "11dot2", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot3, "11dot3", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot4, "11dot4", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot5, "11dot5", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot6, "11dot6", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot7, "11dot7", dictionary); - FlashPostProcessSettings.AddConfigDefineForFlashPlayerFeatureLevel(settings.FlashBuildSubtarget >= FlashBuildSubtarget.Flash11dot8, "11dot8", dictionary); - return dictionary; - } - private static void AddConfigDefineForFlashPlayerFeatureLevel(bool enabled, string level, IDictionary dict) - { - dict.Add(string.Format("PLAYERFEATURE_LEVEL_{0}", level), enabled); - } - private static string EncodeMxmlcConstant(object value) - { - if (value is string) - { - return string.Format("\"'{0}'\"", value); - } - return value.ToString().ToLower(); - } - public static FlashPostProcessSettings CreateWithBuildArguments(BuildOptions options, int width, int height) - { - return new FlashPostProcessSettings - { - Width = Math.Min(Math.Max(width, 1), 4096), - Height = Math.Min(Math.Max(height, 1), 4096), - StripPhysics = PlayerSettings.stripPhysics, - IsDevelopment = (options & BuildOptions.Development) != BuildOptions.None, - FlashBuildSubtarget = EditorUserBuildSettings.flashBuildSubtarget - }; - } - public static FlashPostProcessSettings CreateFrom(PostProcessFlashPlayerOptions options) - { - return FlashPostProcessSettings.CreateWithBuildArguments(options.Options, options.Width, options.Height); - } -} diff --git a/UnityEditor/FlashTemplateWriterUtility.cs b/UnityEditor/FlashTemplateWriterUtility.cs deleted file mode 100644 index 2b7d8556..00000000 --- a/UnityEditor/FlashTemplateWriterUtility.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -internal class FlashTemplateWriterUtility -{ - private readonly string _outputFile; - private readonly string _templateFile; - private readonly Dictionary _tagsToReplace; - public FlashTemplateWriterUtility(string templateFile, string outputFile, Dictionary tagsToReplace) - { - this._outputFile = outputFile; - this._tagsToReplace = tagsToReplace; - this._templateFile = templateFile; - } - public void WriteTemplate() - { - string seed = File.ReadAllText(this._templateFile); - string contents = this._tagsToReplace.Aggregate(seed, (string current, KeyValuePair kvp) => current.Replace("[%" + kvp.Key + "%]", kvp.Value)); - File.WriteAllText(this._outputFile, contents); - } - public static void WriteGendarmeXMLTemplate(FlashPostProcessSettings settings, FlashFileHelper fileHelper, GendarmeXMLTemplateTags gendarmeXMLTemplateTags, string output) - { - new FlashTemplateWriterUtility(fileHelper.PathForFileInGendarme("rules_template.xml"), output, gendarmeXMLTemplateTags.ToTagsDictionary()).WriteTemplate(); - } - public static void WriteHTMLTemplate(FlashPostProcessSettings settings, FlashFileHelper fileHelper) - { - new FlashTemplateWriterUtility(fileHelper.PathForFileInBuildTools("index.html"), fileHelper.PathForHtmlInInstallPath(), FlashTemplateWriterUtility.GetTagsToReplaceForHTML(settings, fileHelper)).WriteTemplate(); - } - private static Dictionary GetTagsToReplaceForHTML(FlashPostProcessSettings settings, FlashFileHelper fileHelper) - { - int num = settings.Height / 2; - return new Dictionary - { - - { - "hdimy", - num.ToString() - }, - - { - "dimx", - settings.Width.ToString() - }, - - { - "dimy", - settings.Height.ToString() - }, - - { - "swfname", - fileHelper.ProjectName() + ".swf" - }, - - { - "flashplayer_version", - settings.GetTargetPlayerForSubtarget() - } - }; - } -} diff --git a/UnityEditor/GendarmeXMLTemplateTags.cs b/UnityEditor/GendarmeXMLTemplateTags.cs deleted file mode 100644 index 971978d7..00000000 --- a/UnityEditor/GendarmeXMLTemplateTags.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -internal class GendarmeXMLTemplateTags -{ - public bool IncludePrimitiveTypes; - public bool AutomaticallyWhitelistAttributes; - public List WhiteListFiles = new List(); - public List BlackListFiles = new List(); - public List WhiteListAssemblies = new List(); - public List BlackListAssemblies = new List(); - public List LimitToNamespaces = new List(); - public List WhiteListTypes = new List(); - public GendarmeXMLTemplateTags() - { - this.IncludePrimitiveTypes = true; - this.AutomaticallyWhitelistAttributes = true; - } - public Dictionary ToTagsDictionary() - { - return new Dictionary - { - - { - "IncludePrimitiveTypes", - (!this.IncludePrimitiveTypes) ? "0" : "1" - }, - - { - "AutomaticallyWhitelistAttributes", - (!this.AutomaticallyWhitelistAttributes) ? "0" : "1" - }, - - { - "LimitToNamespaces", - this.AggregateIntoString(this.LimitToNamespaces) - }, - - { - "WhiteListTypes", - this.AggregateIntoString(this.WhiteListTypes) - }, - - { - "WhiteListFiles", - this.AggregateIntoString(this.WhiteListFiles) - }, - - { - "BlackListFiles", - this.AggregateIntoString(this.BlackListFiles) - }, - - { - "WhiteListAssemblies", - this.AggregateIntoString(this.WhiteListAssemblies) - }, - - { - "BlackListAssemblies", - this.AggregateIntoString(this.BlackListAssemblies) - } - }; - } - private string AggregateIntoString(IEnumerable list) - { - return list.DefaultIfEmpty().Aggregate(new Func(GendarmeXMLTemplateTags.ToCommaSeparatedString)); - } - private static string ToCommaSeparatedString(string agg, string s) - { - return agg + "," + s; - } -} diff --git a/UnityEditor/GenerateIconsWithMipLevels.cs b/UnityEditor/GenerateIconsWithMipLevels.cs index f6bb1910..69df3bad 100644 --- a/UnityEditor/GenerateIconsWithMipLevels.cs +++ b/UnityEditor/GenerateIconsWithMipLevels.cs @@ -98,6 +98,8 @@ private static void GenerateIconsWithMips(GenerateIconsWithMipLevels.InputData i } private static void GenerateIcon(GenerateIconsWithMipLevels.InputData inputData, string baseName, List assetPathsOfAllIcons) { + string text = inputData.targetFolder + "/" + baseName + " Icon.asset"; + GenerateIconsWithMipLevels.EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(text)); Texture2D texture2D = GenerateIconsWithMipLevels.CreateIconWithMipLevels(inputData, baseName, assetPathsOfAllIcons); if (texture2D == null) { @@ -105,8 +107,6 @@ private static void GenerateIcon(GenerateIconsWithMipLevels.InputData inputData, return; } texture2D.name = baseName + " Icon.png"; - string text = inputData.targetFolder + "/" + baseName + " Icon.asset"; - GenerateIconsWithMipLevels.EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(text)); AssetDatabase.CreateAsset(texture2D, text); inputData.generatedFileNames.Add(text); } diff --git a/UnityEditor/LinuxDesktopStandalonePostProcessor.cs b/UnityEditor/LinuxDesktopStandalonePostProcessor.cs deleted file mode 100644 index bdc94d88..00000000 --- a/UnityEditor/LinuxDesktopStandalonePostProcessor.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using UnityEditor; -using UnityEditor.LinuxStandalone; -using UnityEditor.Modules; -using UnityEditorInternal; -internal class LinuxDesktopStandalonePostProcessor : DesktopStandalonePostProcessor -{ - protected override string StagingAreaPluginsFolder - { - get - { - string text = FileUtil.CombinePaths(new string[] - { - base.StagingArea, - "Data", - "Plugins" - }); - return (base.Target != BuildTarget.StandaloneLinuxUniversal) ? Path.Combine(text, this.ArchitecturePostFixFor(base.Target)) : text; - } - } - private bool Headless - { - get - { - return (this.m_PostProcessArgs.options & BuildOptions.EnableHeadlessMode) != BuildOptions.None; - } - } - private string FullDataFolderPath - { - get - { - return Path.Combine(base.DestinationFolder, Path.GetFileNameWithoutExtension(base.InstallPath) + "_Data"); - } - } - protected override string DestinationFolderForInstallingIntoBuildsFolder - { - get - { - throw new NotSupportedException(); - } - } - public LinuxDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) - { - } - private string ArchitecturePostFixFor(BuildTarget buildTarget) - { - return (buildTarget != BuildTarget.StandaloneLinux64) ? "x86" : "x86_64"; - } - protected override void CopyVariationFolderIntoStagingArea() - { - if (base.Target != BuildTarget.StandaloneLinuxUniversal) - { - base.CopyVariationFolderIntoStagingArea(); - return; - } - BuildTarget[] array = new BuildTarget[] - { - BuildTarget.StandaloneLinux, - BuildTarget.StandaloneLinux64 - }; - for (int i = 0; i < array.Length; i++) - { - BuildTarget buildTarget = array[i]; - string source = FileUtil.CombinePaths(new string[] - { - this.m_PostProcessArgs.playerPackage, - "Variations", - this.VariationNameFor(buildTarget) - }); - FileUtil.CopyDirectoryFiltered(source, base.StagingArea, true, (string f) => true, true); - this.RenameStagingAreaFile("LinuxPlayer", Path.ChangeExtension("LinuxPlayer", this.ArchitecturePostFixFor(buildTarget))); - } - } - protected override void RenameFilesInStagingArea() - { - this.RenameStagingAreaFile("Data", FileUtil.UnityGetFileNameWithoutExtension(base.InstallPath) + "_Data"); - if (base.Target != BuildTarget.StandaloneLinuxUniversal) - { - this.RenameStagingAreaFile("LinuxPlayer", FileUtil.UnityGetFileName(base.InstallPath)); - return; - } - foreach (string current in new BuildTarget[] - { - BuildTarget.StandaloneLinux, - BuildTarget.StandaloneLinux64 - }.Select(new Func(this.ArchitecturePostFixFor))) - { - this.RenameStagingAreaFile(Path.ChangeExtension("LinuxPlayer", current), Path.ChangeExtension(FileUtil.UnityGetFileName(base.InstallPath), current)); - } - } - private void RenameStagingAreaFile(string from, string to) - { - FileUtil.MoveFileOrDirectory(Path.Combine(base.StagingArea, from), Path.Combine(base.StagingArea, to)); - } - protected override string GetVariationName() - { - return this.VariationNameFor(base.Target); - } - private string VariationNameFor(BuildTarget target) - { - return string.Format("{0}_{1}_{2}", this.PlatformStringFor(target), (!this.Headless) ? "withgfx" : "headless", (!base.Development) ? "nondevelopment" : "development"); - } - protected override void DeleteDestination() - { - FileUtil.DeleteFileOrDirectory(Path.ChangeExtension(base.InstallPath, this.ArchitecturePostFixFor(BuildTarget.StandaloneLinux))); - FileUtil.DeleteFileOrDirectory(Path.ChangeExtension(base.InstallPath, this.ArchitecturePostFixFor(BuildTarget.StandaloneLinux64))); - FileUtil.DeleteFileOrDirectory(this.FullDataFolderPath); - } - protected override string PlatformStringFor(BuildTarget target) - { - if (target == BuildTarget.StandaloneLinux64) - { - return "linux64"; - } - if (target == BuildTarget.StandaloneLinuxUniversal) - { - return "universal"; - } - if (target != BuildTarget.StandaloneLinux) - { - throw new ArgumentException("Unexpected target: " + target); - } - return "linux32"; - } - protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) - { - return new LinuxStandaloneIl2CppPlatformProvider(target, base.DataFolder); - } -} diff --git a/UnityEditor/MxmlcHelper.cs b/UnityEditor/MxmlcHelper.cs deleted file mode 100644 index 429ce795..00000000 --- a/UnityEditor/MxmlcHelper.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEditor.Scripting.Compilers; -internal class MxmlcHelper -{ - internal static string[] MxmlcArgumentsFor(FlashPostProcessSettings settings, FlashFileHelper fileHelper) - { - string text = fileHelper.FindUserSwcs().Aggregate(string.Empty, (string current, string includeLib) => current + " -include-libraries=" + fileHelper.PrepareFileName(includeLib)); - string text2 = "-debug=" + ((!settings.IsDevelopment) ? "false" : "true"); - string text3 = "-optimize=" + ((!settings.IsDevelopment) ? "true" : "false"); - string text4 = string.Concat(new object[] - { - "-default-size ", - settings.Width, - " ", - settings.Height - }); - return new string[] - { - "-Xmx768m -Dsun.io.useCanonCaches=false -Duser.region=US -Duser.language=en", - "-jar " + fileHelper.PathForMxmlc(), - "+flexlib=" + fileHelper.PathForFlexFrameworks(), - fileHelper.PathForUnityAppDotAs(), - text2, - text3, - "-include-libraries=" + fileHelper.FullPathForUnityNativeSwc(settings.GetUnityNativeSwcForSubTarget(settings.StripPhysics)), - text, - MxmlcHelper.AllSourcePaths(fileHelper), - "-static-link-runtime-shared-libraries=true", - "-swf-version=" + settings.GetSwfVersionForPlayerVersion(), - text4, - "-omit-trace-statements=false", - "-default-script-limits=1000,60", - "-target-player=" + settings.GetTargetPlayerForSubtarget(), - "-verbose-stacktraces=true", - "-compress=false", - settings.MxmlcCompileTimeConstants(), - "-output=" + fileHelper.PathForTempSwf() - }; - } - internal static string AllSourcePaths(FlashFileHelper fileHelper) - { - IEnumerable paths = new string[] - { - fileHelper.PathForAs3Src(), - fileHelper.PathForConvertedDotNetCode(), - fileHelper.PathForUserBuildAs3() - }.Concat(fileHelper.FindUserSourcePaths()); - return MxmlcHelper.FormatSourcePathsForCmdline(paths); - } - private static string FormatSourcePathsForCmdline(IEnumerable paths) - { - StringBuilder stringBuilder = new StringBuilder(); - bool flag = true; - foreach (string current in paths) - { - if (!flag) - { - stringBuilder.Append(" "); - } - stringBuilder.Append("-source-path="); - stringBuilder.Append(CommandLineFormatter.PrepareFileName(current)); - flag = false; - } - return stringBuilder.ToString(); - } -} diff --git a/UnityEditor/NUnitFrameworkUser.cs b/UnityEditor/NUnitFrameworkUser.cs deleted file mode 100644 index cb86ec30..00000000 --- a/UnityEditor/NUnitFrameworkUser.cs +++ /dev/null @@ -1,9 +0,0 @@ -using NUnit.Framework; -using System; -internal class NUnitFrameworkUser -{ - private void Useit() - { - Assert.AreEqual(1, 1); - } -} diff --git a/UnityEditor/OSXDesktopStandalonePostProcessor.cs b/UnityEditor/OSXDesktopStandalonePostProcessor.cs deleted file mode 100644 index bc475b1d..00000000 --- a/UnityEditor/OSXDesktopStandalonePostProcessor.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.IO; -using UnityEditor; -using UnityEditor.Modules; -using UnityEditor.OSXStandalone; -using UnityEditorInternal; -internal class OSXDesktopStandalonePostProcessor : DesktopStandalonePostProcessor -{ - private string StagingAreaContents - { - get - { - return base.StagingArea + "/UnityPlayer.app/Contents"; - } - } - protected override string DestinationFolderForInstallingIntoBuildsFolder - { - get - { - return "build/MacStandaloneSupport/Variations/macosx32_development/UnityPlayer.app/Contents/Data"; - } - } - protected override string StagingAreaPluginsFolder - { - get - { - return this.StagingAreaContents + "/Plugins"; - } - } - private string InstallNameWithoutExtension - { - get - { - return FileUtil.UnityGetFileNameWithoutExtension(this.m_PostProcessArgs.installPath); - } - } - public OSXDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) - { - } - protected override void RenameFilesInStagingArea() - { - File.Move(this.StagingAreaContents + "/MacOS/UnityPlayer", this.StagingAreaContents + "/MacOS/" + this.InstallNameWithoutExtension); - FileUtil.CopyDirectoryFiltered(base.StagingArea + "/Data", this.StagingAreaContents + "/Data", true, (string f) => true, true); - FileUtil.DeleteFileOrDirectory(base.StagingArea + "/Data"); - if (base.UseIl2Cpp) - { - FileUtil.DeleteFileOrDirectory(this.StagingAreaContents + "/Resources/Data/Managed"); - FileUtil.DeleteFileOrDirectory(this.StagingAreaContents + "/Resources/Data/il2cppOutput"); - } - string text = PostprocessBuildPlayer.GenerateBundleIdentifier(this.m_PostProcessArgs.companyName, this.m_PostProcessArgs.productName); - FileUtil.ReplaceText(this.StagingAreaContents + "/Info.plist", new string[] - { - "UNITY_BUNDLE_IDENTIFIER", - text, - "UnityPlayer", - this.InstallNameWithoutExtension - }); - string to = base.StagingArea + "/" + this.InstallNameWithoutExtension + ".app"; - FileUtil.MoveFileOrDirectory(base.StagingArea + "/UnityPlayer.app", to); - } - protected override void DeleteDestination() - { - FileUtil.DeleteFileOrDirectory(this.m_PostProcessArgs.installPath); - } - protected override string GetVariationName() - { - string arg = "mono"; - if (base.UseIl2Cpp) - { - arg = "il2cpp"; - } - return string.Format("{0}_{1}", base.GetVariationName(), arg); - } - protected override string PlatformStringFor(BuildTarget target) - { - switch (target) - { - case BuildTarget.StandaloneOSXUniversal: - return "universal"; - case (BuildTarget)3: - IL_16: - if (target != BuildTarget.StandaloneOSXIntel64) - { - throw new ArgumentException("Unexpected target: " + target); - } - return "macosx64"; - case BuildTarget.StandaloneOSXIntel: - return "macosx32"; - } - goto IL_16; - } - protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) - { - switch (target) - { - case BuildTarget.StandaloneOSXUniversal: - case BuildTarget.StandaloneOSXIntel: - goto IL_23; - case (BuildTarget)3: - IL_16: - if (target != BuildTarget.StandaloneOSXIntel64) - { - throw new Exception("Build target not supported."); - } - goto IL_23; - } - goto IL_16; - IL_23: - return new OSXStandaloneIl2CppPlatformProvider(target, this.StagingAreaContents + "/Data", base.Development); - } -} diff --git a/UnityEditor/ParticleSystemCurveEditor.cs b/UnityEditor/ParticleSystemCurveEditor.cs index 318b1b17..175c1293 100644 --- a/UnityEditor/ParticleSystemCurveEditor.cs +++ b/UnityEditor/ParticleSystemCurveEditor.cs @@ -453,7 +453,7 @@ private DoubleCurve CreateDoubleCurveFromTopMostCurve() } private void PresetDropDown(Rect rect) { - if (EditorGUI.ButtonMouseDown(rect, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) + if (EditorGUI.ButtonMouseDown(rect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) { DoubleCurve doubleCurve = this.CreateDoubleCurveFromTopMostCurve(); if (doubleCurve != null) @@ -526,6 +526,7 @@ private void PresetCurveButtons(Rect position, Rect curveEditorRect) if (doubleCurve != null) { this.SetTopMostCurve(doubleCurve); + this.m_CurveEditor.ClearSelection(); } } if (Event.current.type == EventType.Repaint) diff --git a/UnityEditor/PostProcessFlashPlayer.cs b/UnityEditor/PostProcessFlashPlayer.cs deleted file mode 100644 index 383cbc9f..00000000 --- a/UnityEditor/PostProcessFlashPlayer.cs +++ /dev/null @@ -1,164 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using UnityEditor; -using UnityEditor.Scripting; -using UnityEditor.Scripting.Compilers; -using UnityEditor.Utils; -using UnityEngine; -internal class PostProcessFlashPlayer -{ - private static FlashPostProcessSettings _settings; - private static FlashFileHelper _fileHelper; - internal static void PostProcess(PostProcessFlashPlayerOptions options) - { - PostProcessFlashPlayer._settings = FlashPostProcessSettings.CreateFrom(options); - PostProcessFlashPlayer._fileHelper = FlashFileHelper.CreateFrom(options); - PostProcessFlashPlayer.CleanWorkingPaths(); - if (!PostProcessFlashPlayer.ValidateAssemblies(options)) - { - return; - } - PostProcessFlashPlayer.RunCil2As(); - PostProcessFlashPlayer.CreateSerializedFileContainer(); - PostProcessFlashPlayer.RunMxmlc(); - PostProcessFlashPlayer.RunSwfPostProcessor(); - PostProcessFlashPlayer.DeleteAndCopyDefaultFiles(); - PostProcessFlashPlayer.WriteHtml(); - if (options.IsAutoRunPlayer) - { - Process.Start(PostProcessFlashPlayer._fileHelper.PathForHtmlInInstallPath()); - } - } - private static bool ValidateAssemblies(PostProcessFlashPlayerOptions options) - { - ValidationResult validationResult = AssemblyValidation.Validate(RuntimePlatform.FlashPlayer, PostProcessFlashPlayer._fileHelper.GetUserAssemblies(), new object[] - { - options - }); - if (validationResult.Success) - { - return true; - } - foreach (CompilerMessage current in validationResult.CompilerMessages) - { - UnityEngine.Debug.LogPlayerBuildError(current.message, current.file, current.line, current.column); - } - throw new Exception("Validation step " + validationResult.Rule + " Failed!"); - } - private static void CleanWorkingPaths() - { - FileUtil.CreateOrCleanDirectory(PostProcessFlashPlayer._fileHelper.PathForConvertedDotNetCode()); - FileUtil.CreateOrCleanDirectory(PostProcessFlashPlayer._fileHelper.PathForAs3Src()); - } - private static void CreateSerializedFileContainer() - { - PostProcessFlashPlayer._fileHelper.CopyResourcesFromPlayerPackageToStaging(); - SerializedFileContainerPreparer.CreateSerializedFileContainer(PostProcessFlashPlayer._fileHelper); - } - private static void RunCil2As() - { - StringBuilder stringBuilder = new StringBuilder("-with-class-index -libid:ConvertedDotNetCode -with-global-package --baseclasslibraries-directory="); - stringBuilder.Append(CommandLineFormatter.PrepareFileName(MonoInstallationFinder.GetProfileDirectory(BuildTarget.FlashPlayer, "unity"))); - stringBuilder.Append(" "); - PostProcessFlashPlayer.AppendUserAssembliesFormattedForCommandLine(stringBuilder); - string value = PostProcessFlashPlayer._fileHelper.PathForConvertedDotNetCode(); - stringBuilder.Append(value); - PostProcessFlashPlayer.StartManagedProgram(stringBuilder.ToString(), new Cil2AsOutputParser(), PostProcessFlashPlayer._fileHelper.PathForCil2AsExe()); - } - private static void AppendUserAssembliesFormattedForCommandLine(StringBuilder cmdline) - { - foreach (string current in PostProcessFlashPlayer._fileHelper.GetUserAssemblies()) - { - cmdline.Append(current); - cmdline.Append(" "); - } - } - private static void RunMxmlc() - { - PostProcessFlashPlayer.StartProgramChecked(new Program(new ProcessStartInfo - { - FileName = "java", - Arguments = string.Join(" ", MxmlcHelper.MxmlcArgumentsFor(PostProcessFlashPlayer._settings, PostProcessFlashPlayer._fileHelper)), - CreateNoWindow = true - }), new FlexCompilerOutputParser(), "java"); - } - private static bool RunSwfPostProcessor() - { - string value = PostProcessFlashPlayer._fileHelper.PathForTempSwf(); - StringBuilder stringBuilder = new StringBuilder(" -nativeskip -upp "); - stringBuilder.Append(value); - stringBuilder.Append(" -o "); - stringBuilder.Append(value); - stringBuilder.Append((!PostProcessFlashPlayer._settings.IsDevelopment) ? " -clzma " : " -cnone "); - stringBuilder.Append(" -inject-telemetry "); - return PostProcessFlashPlayer.StartManagedProgram(stringBuilder.ToString(), new Cil2AsOutputParser(), PostProcessFlashPlayer._fileHelper.PathForSwfPostProcessorExe()); - } - private static void DeleteAndCopyDefaultFiles() - { - FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForHtmlInInstallPath()); - FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("swfobject.js")); - FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("embeddingapi.swc")); - FileUtil.DeleteFileOrDirectory(PostProcessFlashPlayer._fileHelper.InstallPath); - FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForTempSwfUnprepared(), PostProcessFlashPlayer._fileHelper.InstallPath); - FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInBuildTools("swfobject.js"), PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("swfobject.js")); - FileUtil.CopyFileOrDirectory(PostProcessFlashPlayer._fileHelper.PathForFileInBuildTools("UnityShared.swc"), PostProcessFlashPlayer._fileHelper.PathForFileInInstallPath("embeddingapi.swc")); - } - private static void WriteHtml() - { - FlashTemplateWriterUtility.WriteHTMLTemplate(PostProcessFlashPlayer._settings, PostProcessFlashPlayer._fileHelper); - } - private static bool StartManagedProgram(string arguments, UnityScriptCompilerOutputParser parser, string exe) - { - return PostProcessFlashPlayer.StartProgramChecked(new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, arguments), parser, exe); - } - private static bool StartProgramChecked(Program p, CompilerOutputParserBase parser, string exe) - { - bool result; - try - { - p.LogProcessStartInfo(); - try - { - p.Start(); - } - catch - { - throw new Exception("Could not start " + exe); - } - p.WaitForExit(); - if (p.ExitCode != 0) - { - string[] errorOutput = p.GetErrorOutput(); - string[] standardOutput = p.GetStandardOutput(); - PostProcessFlashPlayer.LogCompilerMessages(parser.Parse(errorOutput, standardOutput, true)); - throw new Exception(string.Concat(new string[] - { - exe, - " Failed:", - Environment.NewLine, - p.GetStandardOutputAsString(), - Environment.NewLine, - string.Join(Environment.NewLine, errorOutput) - })); - } - result = true; - } - finally - { - if (p != null) - { - ((IDisposable)p).Dispose(); - } - } - return result; - } - private static void LogCompilerMessages(IEnumerable messages) - { - foreach (CompilerMessage current in messages) - { - UnityEngine.Debug.LogPlayerBuildError(current.message, current.file, current.line, current.column); - } - } -} diff --git a/UnityEditor/PostProcessFlashPlayerOptions.cs b/UnityEditor/PostProcessFlashPlayerOptions.cs deleted file mode 100644 index a66b0fa9..00000000 --- a/UnityEditor/PostProcessFlashPlayerOptions.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using UnityEditor; -internal class PostProcessFlashPlayerOptions -{ - public BuildTarget Target; - public string StagingAreaData; - public string StagingArea; - public string StagingAreaDataManaged; - public string PlayerPackage; - public string InstallPath; - public string CompanyName; - public string ProductName; - public BuildOptions Options; - public RuntimeClassRegistry UsedClassRegistry; - public int Width; - public int Height; - public bool IsAutoRunPlayer - { - get - { - return (this.Options & BuildOptions.AutoRunPlayer) != BuildOptions.None; - } - } -} diff --git a/UnityEditor/Properties/AssemblyInfo.cs b/UnityEditor/Properties/AssemblyInfo.cs index 427084c5..4088b1d0 100644 --- a/UnityEditor/Properties/AssemblyInfo.cs +++ b/UnityEditor/Properties/AssemblyInfo.cs @@ -3,6 +3,8 @@ using System.Runtime.CompilerServices; using UnityEngine; [assembly: AssemblyVersion("0.0.0.0")] +[assembly: InternalsVisibleTo("Unity.PackageManager")] +[assembly: InternalsVisibleTo("Unity.Automation")] [assembly: InternalsVisibleTo("Unity.PureCSharpTests")] [assembly: InternalsVisibleTo("Unity.IntegrationTests")] [assembly: InternalsVisibleTo("UnityEditor.Graphs")] @@ -19,5 +21,9 @@ [assembly: InternalsVisibleTo("UnityEditor.PSP2.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.PS4.Extensions")] [assembly: InternalsVisibleTo("UnityEditor.PSM.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.WebGL.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.LinuxStandalone.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.WindowsStandalone.Extensions")] +[assembly: InternalsVisibleTo("UnityEditor.OSXStandalone.Extensions")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyIsEditorAssembly] diff --git a/UnityEditor/SerializedFileContainerPreparer.cs b/UnityEditor/SerializedFileContainerPreparer.cs deleted file mode 100644 index 8f7d0bee..00000000 --- a/UnityEditor/SerializedFileContainerPreparer.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using UnityEditor; -internal class SerializedFileContainerPreparer -{ - private static string _stagingAreaData; - public static void CreateSerializedFileContainer(FlashFileHelper flashFileHelper) - { - SerializedFileContainerPreparer._stagingAreaData = flashFileHelper.StagingArea; - IEnumerable source = SerializedFileContainerPreparer.FindFilesThatShouldBeEmbedded(); - SerializedFileContainerWriter.SerializedFile[] files = ( - from f in source - select SerializedFileContainerPreparer.GetSerializedFile(f)).ToArray(); - SerializedFileContainerWriter.Write(SerializedFileContainerPreparer._stagingAreaData, files, flashFileHelper.PathForAs3Src()); - } - private static IEnumerable FindFilesThatShouldBeEmbedded() - { - List list = new List - { - "mainData", - "Resources/unity default resources" - }; - string[] patterns = new string[] - { - "\\.assets$", - "level", - "PlayerConnectionConfigFile" - }; - list.AddRange( - from ps in Directory.GetFiles(SerializedFileContainerPreparer._stagingAreaData) - where SerializedFileContainerPreparer.MatchesFilter(ps, patterns) - select ps into f - select Path.GetFileName(f)); - string path = Path.Combine(SerializedFileContainerPreparer._stagingAreaData, "Resources/unity_builtin_extra"); - if (File.Exists(path)) - { - list.Add("Resources/unity_builtin_extra"); - } - return list; - } - private static SerializedFileContainerWriter.SerializedFile GetSerializedFile(string file) - { - long length = new FileInfo(SerializedFileContainerPreparer._stagingAreaData + "/" + file).Length; - return new SerializedFileContainerWriter.SerializedFile - { - Name = file, - FileName = SerializedFileContainerPreparer.GetTextPlaceHolderForFile(file), - FileSize = length - }; - } - private static string GetTextPlaceHolderForFile(string fileName) - { - string str = Environment.CurrentDirectory + "/" + SerializedFileContainerPreparer._stagingAreaData + "/"; - UTF8Encoding uTF8Encoding = new UTF8Encoding(); - string str2 = fileName + "_txt"; - string text = "_UNITY_REPLACEFORFILE__" + str + fileName; - using (FileStream fileStream = new FileStream(SerializedFileContainerPreparer._stagingAreaData + "/" + str2, FileMode.CreateNew)) - { - fileStream.Write(uTF8Encoding.GetBytes(text), 0, uTF8Encoding.GetByteCount(text)); - } - return fileName; - } - private static bool MatchesFilter(string input, IEnumerable patterns) - { - return patterns.Any((string p) => Regex.Match(input, p).Success); - } -} diff --git a/UnityEditor/TreeEditor/TreeAOSphere.cs b/UnityEditor/TreeEditor/TreeAOSphere.cs index 0567c1bc..bb08d297 100644 --- a/UnityEditor/TreeEditor/TreeAOSphere.cs +++ b/UnityEditor/TreeEditor/TreeAOSphere.cs @@ -21,7 +21,7 @@ public float PointOcclusion(Vector3 pos, Vector3 nor) Vector3 rhs = this.position - pos; float sqrMagnitude = rhs.sqrMagnitude; float num = Mathf.Max(0f, sqrMagnitude - this.area); - if (sqrMagnitude > 1.401298E-45f) + if (sqrMagnitude > Mathf.Epsilon) { rhs.Normalize(); } diff --git a/UnityEditor/TreeEditor/TreeData.cs b/UnityEditor/TreeEditor/TreeData.cs index 992abd98..f9d44cc4 100644 --- a/UnityEditor/TreeEditor/TreeData.cs +++ b/UnityEditor/TreeEditor/TreeData.cs @@ -639,7 +639,7 @@ public void UpdateMesh(Matrix4x4 worldToLocalMatrix, out Material[] outMaterials this.mesh.vertices = array; this.mesh.normals = array2; this.mesh.uv = array3; - this.mesh.uv1 = array4; + this.mesh.uv2 = array4; this.mesh.tangents = array5; this.mesh.colors = array6; int[] array7 = new int[list2.Count * 3]; diff --git a/UnityEditor/TreeEditor/TreeEditor.cs b/UnityEditor/TreeEditor/TreeEditor.cs index c0926e03..360f1113 100644 --- a/UnityEditor/TreeEditor/TreeEditor.cs +++ b/UnityEditor/TreeEditor/TreeEditor.cs @@ -185,7 +185,7 @@ private static void CreateNewTree(MenuCommand menuCommand) Undo.RegisterCreatedObjectUndo(gameObject2, "Create New Tree"); Material[] materials; treeData.UpdateMesh(gameObject2.transform.worldToLocalMatrix, out materials); - TreeEditor.AssignMaterials(gameObject2.renderer, materials, true); + TreeEditor.AssignMaterials(gameObject2.GetComponent(), materials, true); Selection.activeObject = gameObject2; } private static TreeData GetTreeData(Tree tree) @@ -210,7 +210,7 @@ private static void PreviewMesh(Tree tree, bool callExitGUI) Profiler.BeginSample("TreeEditor.PreviewMesh"); Material[] materials; treeData.PreviewMesh(tree.transform.worldToLocalMatrix, out materials); - TreeEditor.AssignMaterials(tree.renderer, materials, false); + TreeEditor.AssignMaterials(tree.GetComponent(), materials, false); Profiler.EndSample(); if (callExitGUI) { @@ -257,7 +257,7 @@ private static void UpdateMesh(Tree tree, bool callExitGUI) Profiler.BeginSample("TreeEditor.UpdateMesh"); Material[] materials; treeData.UpdateMesh(tree.transform.worldToLocalMatrix, out materials); - TreeEditor.AssignMaterials(tree.renderer, materials, true); + TreeEditor.AssignMaterials(tree.GetComponent(), materials, true); TreeEditor.s_SavedSourceMaterialsHash = treeData.materialHash; Profiler.EndSample(); if (callExitGUI) @@ -578,11 +578,11 @@ private void FrameSelected(Tree tree) } } Vector3 center = bounds.center; - float size = bounds.size.magnitude + 1f; + float newSize = bounds.size.magnitude + 1f; SceneView lastActiveSceneView = SceneView.lastActiveSceneView; if (lastActiveSceneView) { - lastActiveSceneView.LookAt(center, lastActiveSceneView.rotation, size); + lastActiveSceneView.LookAt(center, lastActiveSceneView.rotation, newSize); } } private void UndoStoreSelected(TreeEditor.EditMode mode) @@ -1842,7 +1842,7 @@ public override void OnInspectorGUI() { return; } - Renderer renderer = tree.renderer; + Renderer component = tree.GetComponent(); this.VerifySelection(treeData); if (TreeEditor.s_SelectedGroup == null) { @@ -1865,7 +1865,7 @@ public override void OnInspectorGUI() } EditorGUILayout.Space(); EditorGUILayout.BeginVertical(EditorStyles.inspectorFullWidthMargins, new GUILayoutOption[0]); - this.InspectorHierachy(treeData, renderer); + this.InspectorHierachy(treeData, component); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); if (TreeEditor.s_SelectedGroup != null) diff --git a/UnityEditor/TreeEditor/TreeGroupLeaf.cs b/UnityEditor/TreeEditor/TreeGroupLeaf.cs index a40db7b3..bbea2c48 100644 --- a/UnityEditor/TreeEditor/TreeGroupLeaf.cs +++ b/UnityEditor/TreeEditor/TreeGroupLeaf.cs @@ -195,9 +195,9 @@ public override void UpdateMesh(List materials, List v } } } - if (this.instanceMesh.renderer != null) + if (this.instanceMesh.GetComponent() != null) { - Material[] sharedMaterials = this.instanceMesh.renderer.sharedMaterials; + Material[] sharedMaterials = this.instanceMesh.GetComponent().sharedMaterials; for (int j = 0; j < sharedMaterials.Length; j++) { TreeGroup.GetMaterialIndex(sharedMaterials[j], materials, false); @@ -323,9 +323,9 @@ private void UpdateNodeMesh(TreeNode node, List materials, List() != null && j < this.instanceMesh.GetComponent().sharedMaterials.Length) { - materialIndex = TreeGroup.GetMaterialIndex(this.instanceMesh.renderer.sharedMaterials[j], materials, false); + materialIndex = TreeGroup.GetMaterialIndex(this.instanceMesh.GetComponent().sharedMaterials[j], materials, false); } else { diff --git a/UnityEditor/UnityEditor.Animations/AnimatorCondition.cs b/UnityEditor/UnityEditor.Animations/AnimatorCondition.cs new file mode 100644 index 00000000..13629b36 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorCondition.cs @@ -0,0 +1,43 @@ +using System; +namespace UnityEditor.Animations +{ + public struct AnimatorCondition + { + private AnimatorConditionMode m_ConditionMode; + private string m_ConditionEvent; + private float m_EventTreshold; + public AnimatorConditionMode mode + { + get + { + return this.m_ConditionMode; + } + set + { + this.m_ConditionMode = value; + } + } + public string parameter + { + get + { + return this.m_ConditionEvent; + } + set + { + this.m_ConditionEvent = value; + } + } + public float threshold + { + get + { + return this.m_EventTreshold; + } + set + { + this.m_EventTreshold = value; + } + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorConditionMode.cs b/UnityEditor/UnityEditor.Animations/AnimatorConditionMode.cs new file mode 100644 index 00000000..698cb421 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorConditionMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor.Animations +{ + public enum AnimatorConditionMode + { + If = 1, + IfNot, + Greater, + Less, + Equals = 6, + NotEqual + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorController.cs b/UnityEditor/UnityEditor.Animations/AnimatorController.cs new file mode 100644 index 00000000..7f9ba79b --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorController.cs @@ -0,0 +1,336 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngineInternal; +namespace UnityEditor.Animations +{ + public sealed class AnimatorController : RuntimeAnimatorController + { + private const string kControllerExtension = "controller"; + internal Action OnAnimatorControllerDirty; + internal static AnimatorController lastActiveController; + internal static int lastActiveLayerIndex; + private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); + public extern AnimatorControllerLayer[] layers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorControllerParameter[] parameters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool isAssetBundled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal bool pushUndo + { + set + { + this.undoHandler.m_PushUndo = value; + } + } + [Obsolete("parameterCount is obsolete. Use parameters.Length instead.", true)] + private int parameterCount + { + get + { + return 0; + } + } + [Obsolete("layerCount is obsolete. Use layers.Length instead.", true)] + private int layerCount + { + get + { + return 0; + } + } + public AnimatorController() + { + AnimatorController.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorController mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AnimatorController GetEffectiveAnimatorController(Animator behavior); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAnimatorController(Animator behavior, AnimatorController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern int IndexOfParameter(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RenameParameter(string prevName, string newName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string MakeUniqueParameterName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string MakeUniqueLayerName(string name); + public static StateMachineBehaviourContext[] FindStateMachineBehaviourContext(StateMachineBehaviour behaviour) + { + return AnimatorController.Internal_FindStateMachineBehaviourContext(behaviour); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CreateStateMachineBehaviour(MonoScript script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CanAddStateMachineBehaviours(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern ScriptableObject Internal_AddStateMachineBehaviourWithType(Type stateMachineBehaviourType, AnimatorState state, int layerIndex); + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public StateMachineBehaviour AddEffectiveStateMachineBehaviour(Type stateMachineBehaviourType, AnimatorState state, int layerIndex) + { + return (StateMachineBehaviour)this.Internal_AddStateMachineBehaviourWithType(stateMachineBehaviourType, state, layerIndex); + } + public T AddEffectiveStateMachineBehaviour(AnimatorState state, int layerIndex) where T : StateMachineBehaviour + { + return this.AddEffectiveStateMachineBehaviour(typeof(T), state, layerIndex) as T; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern UnityEngine.Object[] CollectObjectsUsingParameter(string parameterName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddStateEffectiveBehaviour(AnimatorState state, int layerIndex, int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern StateMachineBehaviourContext[] Internal_FindStateMachineBehaviourContext(ScriptableObject scriptableObject); + internal string GetDefaultBlendTreeParameter() + { + for (int i = 0; i < this.parameters.Length; i++) + { + if (this.parameters[i].type == AnimatorControllerParameterType.Float) + { + return this.parameters[i].name; + } + } + return "Blend"; + } + internal static void OnInvalidateAnimatorController(AnimatorController controller) + { + if (controller.OnAnimatorControllerDirty != null) + { + controller.OnAnimatorControllerDirty(); + } + } + internal AnimatorStateMachine FindEffectiveRootStateMachine(int layerIndex) + { + AnimatorControllerLayer animatorControllerLayer = this.layers[layerIndex]; + while (animatorControllerLayer.syncedLayerIndex != -1) + { + animatorControllerLayer = this.layers[animatorControllerLayer.syncedLayerIndex]; + } + return animatorControllerLayer.stateMachine; + } + public void AddLayer(string name) + { + AnimatorControllerLayer animatorControllerLayer = new AnimatorControllerLayer(); + animatorControllerLayer.name = this.MakeUniqueLayerName(name); + animatorControllerLayer.stateMachine = new AnimatorStateMachine(); + animatorControllerLayer.stateMachine.name = animatorControllerLayer.name; + animatorControllerLayer.stateMachine.hideFlags = HideFlags.HideInHierarchy; + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorControllerLayer.stateMachine, AssetDatabase.GetAssetPath(this)); + } + this.AddLayer(animatorControllerLayer); + } + public void AddLayer(AnimatorControllerLayer layer) + { + this.undoHandler.DoUndo(this, "Layer added"); + AnimatorControllerLayer[] layers = this.layers; + ArrayUtility.Add(ref layers, layer); + this.layers = layers; + } + public void RemoveLayer(int index) + { + this.undoHandler.DoUndo(this, "Layer removed"); + AnimatorControllerLayer[] layers = this.layers; + if (layers[index].syncedLayerIndex == -1 && layers[index].stateMachine != null) + { + layers[index].stateMachine.Clear(); + if (MecanimUtilities.AreSameAsset(this, layers[index].stateMachine)) + { + Undo.DestroyObjectImmediate(layers[index].stateMachine); + } + } + AnimatorControllerLayer[] array = layers; + for (int i = 0; i < array.Length; i++) + { + AnimatorControllerLayer animatorControllerLayer = array[i]; + if (animatorControllerLayer.syncedLayerIndex == index) + { + animatorControllerLayer.syncedLayerIndex = -1; + } + } + ArrayUtility.Remove(ref layers, layers[index]); + this.layers = layers; + } + public void AddParameter(string name, AnimatorControllerParameterType type) + { + this.AddParameter(new AnimatorControllerParameter + { + name = this.MakeUniqueParameterName(name), + type = type + }); + } + public void AddParameter(AnimatorControllerParameter paramater) + { + this.undoHandler.DoUndo(this, "Parameter added"); + AnimatorControllerParameter[] parameters = this.parameters; + ArrayUtility.Add(ref parameters, paramater); + this.parameters = parameters; + } + public void RemoveParameter(int index) + { + this.undoHandler.DoUndo(this, "Parameter removed"); + AnimatorControllerParameter[] parameters = this.parameters; + ArrayUtility.Remove(ref parameters, parameters[index]); + this.parameters = parameters; + } + public void RemoveParameter(AnimatorControllerParameter parameter) + { + this.undoHandler.DoUndo(this, "Parameter removed"); + AnimatorControllerParameter[] parameters = this.parameters; + ArrayUtility.Remove(ref parameters, parameter); + this.parameters = parameters; + } + public AnimatorState AddMotion(Motion motion) + { + return this.AddMotion(motion, 0); + } + public AnimatorState AddMotion(Motion motion, int layerIndex) + { + AnimatorState animatorState = this.layers[layerIndex].stateMachine.AddState(motion.name); + animatorState.motion = motion; + return animatorState; + } + public AnimatorState CreateBlendTreeInController(string name, out BlendTree tree) + { + return this.CreateBlendTreeInController(name, out tree, 0); + } + public AnimatorState CreateBlendTreeInController(string name, out BlendTree tree, int layerIndex) + { + tree = new BlendTree(); + tree.name = name; + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(tree, AssetDatabase.GetAssetPath(this)); + } + AnimatorState animatorState = this.layers[layerIndex].stateMachine.AddState(tree.name); + animatorState.motion = tree; + return animatorState; + } + public static AnimatorController CreateAnimatorControllerAtPath(string path) + { + AnimatorController animatorController = new AnimatorController(); + animatorController.name = Path.GetFileName(path); + AssetDatabase.CreateAsset(animatorController, path); + animatorController.pushUndo = false; + animatorController.AddLayer("Base Layer"); + animatorController.pushUndo = true; + return animatorController; + } + public static AnimationClip AllocateAnimatorClip(string name) + { + AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true); + animationClip.name = name; + return animationClip; + } + internal static AnimatorController CreateAnimatorControllerForClip(AnimationClip clip, GameObject animatedObject) + { + string text = AssetDatabase.GetAssetPath(clip); + if (string.IsNullOrEmpty(text)) + { + return null; + } + text = Path.Combine(FileUtil.DeleteLastPathNameComponent(text), animatedObject.name + ".controller"); + text = AssetDatabase.GenerateUniqueAssetPath(text); + if (string.IsNullOrEmpty(text)) + { + return null; + } + return AnimatorController.CreateAnimatorControllerAtPathWithClip(text, clip); + } + public static AnimatorController CreateAnimatorControllerAtPathWithClip(string path, AnimationClip clip) + { + AnimatorController animatorController = AnimatorController.CreateAnimatorControllerAtPath(path); + animatorController.AddMotion(clip); + return animatorController; + } + public void SetStateEffectiveMotion(AnimatorState state, Motion motion) + { + this.SetStateEffectiveMotion(state, motion, 0); + } + public void SetStateEffectiveMotion(AnimatorState state, Motion motion, int layerIndex) + { + if (this.layers[layerIndex].syncedLayerIndex == -1) + { + this.undoHandler.DoUndo(state, "Set Motion"); + state.motion = motion; + } + else + { + this.undoHandler.DoUndo(this, "Set Motion"); + AnimatorControllerLayer[] layers = this.layers; + layers[layerIndex].SetOverrideMotion(state, motion); + this.layers = layers; + } + } + public Motion GetStateEffectiveMotion(AnimatorState state) + { + return this.GetStateEffectiveMotion(state, 0); + } + public Motion GetStateEffectiveMotion(AnimatorState state, int layerIndex) + { + if (this.layers[layerIndex].syncedLayerIndex == -1) + { + return state.motion; + } + return this.layers[layerIndex].GetOverrideMotion(state); + } + public void SetStateEffectiveBehaviours(AnimatorState state, int layerIndex, StateMachineBehaviour[] behaviours) + { + if (this.layers[layerIndex].syncedLayerIndex == -1) + { + this.undoHandler.DoUndo(state, "Set Behaviours"); + state.behaviours = behaviours; + } + else + { + this.undoHandler.DoUndo(this, "Set Behaviours"); + AnimatorControllerLayer[] layers = this.layers; + layers[layerIndex].SetOverrideBehaviours(state, behaviours); + this.layers = layers; + } + } + public StateMachineBehaviour[] GetStateEffectiveBehaviours(AnimatorState state, int layerIndex) + { + if (this.layers[layerIndex].syncedLayerIndex == -1) + { + return state.behaviours; + } + return this.layers[layerIndex].GetOverrideBehaviours(state); + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorControllerLayer.cs b/UnityEditor/UnityEditor.Animations/AnimatorControllerLayer.cs new file mode 100644 index 00000000..c9bd88e0 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorControllerLayer.cs @@ -0,0 +1,176 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + public sealed class AnimatorControllerLayer + { + private string m_Name; + private AnimatorStateMachine m_StateMachine; + private AvatarMask m_AvatarMask; + private StateMotionPair[] m_Motions; + private StateBehavioursPair[] m_Behaviours; + private AnimatorLayerBlendingMode m_BlendingMode; + private int m_SyncedLayerIndex = -1; + private bool m_IKPass; + private float m_DefaultWeight; + private bool m_SyncedLayerAffectsTiming; + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public AnimatorStateMachine stateMachine + { + get + { + return this.m_StateMachine; + } + set + { + this.m_StateMachine = value; + } + } + public AvatarMask avatarMask + { + get + { + return this.m_AvatarMask; + } + set + { + this.m_AvatarMask = value; + } + } + public AnimatorLayerBlendingMode blendingMode + { + get + { + return this.m_BlendingMode; + } + set + { + this.m_BlendingMode = value; + } + } + public int syncedLayerIndex + { + get + { + return this.m_SyncedLayerIndex; + } + set + { + this.m_SyncedLayerIndex = value; + } + } + public bool iKPass + { + get + { + return this.m_IKPass; + } + set + { + this.m_IKPass = value; + } + } + public float defaultWeight + { + get + { + return this.m_DefaultWeight; + } + set + { + this.m_DefaultWeight = value; + } + } + public bool syncedLayerAffectsTiming + { + get + { + return this.m_SyncedLayerAffectsTiming; + } + set + { + this.m_SyncedLayerAffectsTiming = value; + } + } + public Motion GetOverrideMotion(AnimatorState state) + { + if (this.m_Motions != null) + { + StateMotionPair[] motions = this.m_Motions; + for (int i = 0; i < motions.Length; i++) + { + StateMotionPair stateMotionPair = motions[i]; + if (stateMotionPair.m_State == state) + { + return stateMotionPair.m_Motion; + } + } + } + return null; + } + public void SetOverrideMotion(AnimatorState state, Motion motion) + { + if (this.m_Motions == null) + { + this.m_Motions = new StateMotionPair[0]; + } + for (int i = 0; i < this.m_Motions.Length; i++) + { + if (this.m_Motions[i].m_State == state) + { + this.m_Motions[i].m_Motion = motion; + return; + } + } + StateMotionPair item; + item.m_State = state; + item.m_Motion = motion; + ArrayUtility.Add(ref this.m_Motions, item); + } + public StateMachineBehaviour[] GetOverrideBehaviours(AnimatorState state) + { + if (this.m_Behaviours != null) + { + StateBehavioursPair[] behaviours = this.m_Behaviours; + for (int i = 0; i < behaviours.Length; i++) + { + StateBehavioursPair stateBehavioursPair = behaviours[i]; + if (stateBehavioursPair.m_State == state) + { + return stateBehavioursPair.m_Behaviours; + } + } + } + return new StateMachineBehaviour[0]; + } + public void SetOverrideBehaviours(AnimatorState state, StateMachineBehaviour[] behaviours) + { + if (this.m_Behaviours == null) + { + this.m_Behaviours = new StateBehavioursPair[0]; + } + for (int i = 0; i < this.m_Behaviours.Length; i++) + { + if (this.m_Behaviours[i].m_State == state) + { + this.m_Behaviours[i].m_Behaviours = behaviours; + return; + } + } + StateBehavioursPair item; + item.m_State = state; + item.m_Behaviours = behaviours; + ArrayUtility.Add(ref this.m_Behaviours, item); + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorLayerBlendingMode.cs b/UnityEditor/UnityEditor.Animations/AnimatorLayerBlendingMode.cs new file mode 100644 index 00000000..9899e3f1 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorLayerBlendingMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Animations +{ + public enum AnimatorLayerBlendingMode + { + Override, + Additive + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorState.cs b/UnityEditor/UnityEditor.Animations/AnimatorState.cs new file mode 100644 index 00000000..500e01d2 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorState.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngineInternal; +namespace UnityEditor.Animations +{ + public sealed class AnimatorState : UnityEngine.Object + { + private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); + public extern int nameHash + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Motion motion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mirror + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool iKOnFeet + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool writeDefaultValues + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string tag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorStateTransition[] transitions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern StateMachineBehaviour[] behaviours + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal bool pushUndo + { + set + { + this.undoHandler.m_PushUndo = value; + } + } + [Obsolete("uniqueName does not exist anymore. Consider using .name instead.", true)] + public string uniqueName + { + get + { + return string.Empty; + } + } + [Obsolete("uniqueNameHash does not exist anymore.", true)] + public int uniqueNameHash + { + get + { + return -1; + } + } + public AnimatorState() + { + AnimatorState.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorState mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddBehaviour(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern ScriptableObject Internal_AddStateMachineBehaviourWithType(Type stateMachineBehaviourType); + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType) + { + return (StateMachineBehaviour)this.Internal_AddStateMachineBehaviourWithType(stateMachineBehaviourType); + } + public T AddStateMachineBehaviour() where T : StateMachineBehaviour + { + return this.AddStateMachineBehaviour(typeof(T)) as T; + } + public void AddTransition(AnimatorStateTransition transition) + { + this.undoHandler.DoUndo(this, "Transition added"); + AnimatorStateTransition[] transitions = this.transitions; + ArrayUtility.Add(ref transitions, transition); + this.transitions = transitions; + } + public void RemoveTransition(AnimatorStateTransition transition) + { + this.undoHandler.DoUndo(this, "Transition removed"); + AnimatorStateTransition[] transitions = this.transitions; + ArrayUtility.Remove(ref transitions, transition); + this.transitions = transitions; + if (MecanimUtilities.AreSameAsset(this, transition)) + { + Undo.DestroyObjectImmediate(transition); + } + } + private AnimatorStateTransition AddTransition() + { + AnimatorStateTransition animatorStateTransition = new AnimatorStateTransition(); + animatorStateTransition.hasExitTime = false; + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorStateTransition, AssetDatabase.GetAssetPath(this)); + } + animatorStateTransition.hideFlags = HideFlags.HideInHierarchy; + this.AddTransition(animatorStateTransition); + return animatorStateTransition; + } + public AnimatorStateTransition AddTransition(AnimatorState destinationState) + { + AnimatorStateTransition animatorStateTransition = this.AddTransition(); + animatorStateTransition.destinationState = destinationState; + return animatorStateTransition; + } + public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine) + { + AnimatorStateTransition animatorStateTransition = this.AddTransition(); + animatorStateTransition.destinationStateMachine = destinationStateMachine; + return animatorStateTransition; + } + private void SetDefaultTransitionExitTime(ref AnimatorStateTransition newTransition) + { + newTransition.hasExitTime = true; + if (this.motion != null && this.motion.averageDuration > 0f) + { + float num = 0.25f / this.motion.averageDuration; + newTransition.duration = num; + newTransition.exitTime = 1f - num; + } + } + public AnimatorStateTransition AddTransition(AnimatorState destinationState, bool defaultExitTime) + { + AnimatorStateTransition result = this.AddTransition(destinationState); + if (defaultExitTime) + { + this.SetDefaultTransitionExitTime(ref result); + } + return result; + } + public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine, bool defaultExitTime) + { + AnimatorStateTransition result = this.AddTransition(destinationStateMachine); + if (defaultExitTime) + { + this.SetDefaultTransitionExitTime(ref result); + } + return result; + } + public AnimatorStateTransition AddExitTransition() + { + AnimatorStateTransition animatorStateTransition = this.AddTransition(); + animatorStateTransition.isExit = true; + return animatorStateTransition; + } + public AnimatorStateTransition AddExitTransition(bool defaultExitTime) + { + AnimatorStateTransition animatorStateTransition = this.AddTransition(); + animatorStateTransition.isExit = true; + if (defaultExitTime) + { + this.SetDefaultTransitionExitTime(ref animatorStateTransition); + } + return animatorStateTransition; + } + internal AnimatorStateMachine FindParent(AnimatorStateMachine root) + { + if (root.HasState(this, false)) + { + return root; + } + return root.stateMachinesRecursive.Find((ChildAnimatorStateMachine sm) => sm.stateMachine.HasState(this, false)).stateMachine; + } + internal AnimatorStateTransition FindTransition(AnimatorState destinationState) + { + return new List(this.transitions).Find((AnimatorStateTransition t) => t.destinationState == destinationState); + } + [Obsolete("GetMotion() is obsolete. Use motion", true)] + public Motion GetMotion() + { + return null; + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorStateMachine.cs b/UnityEditor/UnityEditor.Animations/AnimatorStateMachine.cs new file mode 100644 index 00000000..d87c02ae --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorStateMachine.cs @@ -0,0 +1,602 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngineInternal; +namespace UnityEditor.Animations +{ + public sealed class AnimatorStateMachine : UnityEngine.Object + { + private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); + public extern ChildAnimatorState[] states + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ChildAnimatorStateMachine[] stateMachines + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorState defaultState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 anyStatePosition + { + get + { + Vector3 result; + this.INTERNAL_get_anyStatePosition(out result); + return result; + } + set + { + this.INTERNAL_set_anyStatePosition(ref value); + } + } + public Vector3 entryPosition + { + get + { + Vector3 result; + this.INTERNAL_get_entryPosition(out result); + return result; + } + set + { + this.INTERNAL_set_entryPosition(ref value); + } + } + public Vector3 exitPosition + { + get + { + Vector3 result; + this.INTERNAL_get_exitPosition(out result); + return result; + } + set + { + this.INTERNAL_set_exitPosition(ref value); + } + } + public Vector3 parentStateMachinePosition + { + get + { + Vector3 result; + this.INTERNAL_get_parentStateMachinePosition(out result); + return result; + } + set + { + this.INTERNAL_set_parentStateMachinePosition(ref value); + } + } + public extern AnimatorStateTransition[] anyStateTransitions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorTransition[] entryTransitions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern StateMachineBehaviour[] behaviours + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern int transitionCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal bool pushUndo + { + set + { + this.undoHandler.m_PushUndo = value; + } + } + internal List statesRecursive + { + get + { + List list = new List(); + list.AddRange(this.states); + for (int i = 0; i < this.stateMachines.Length; i++) + { + list.AddRange(this.stateMachines[i].stateMachine.statesRecursive); + } + return list; + } + } + internal List stateMachinesRecursive + { + get + { + List list = new List(); + list.AddRange(this.stateMachines); + for (int i = 0; i < this.stateMachines.Length; i++) + { + list.AddRange(this.stateMachines[i].stateMachine.stateMachinesRecursive); + } + return list; + } + } + internal List anyStateTransitionsRecursive + { + get + { + List list = new List(); + list.AddRange(this.anyStateTransitions); + ChildAnimatorStateMachine[] stateMachines = this.stateMachines; + for (int i = 0; i < stateMachines.Length; i++) + { + ChildAnimatorStateMachine childAnimatorStateMachine = stateMachines[i]; + list.AddRange(childAnimatorStateMachine.stateMachine.anyStateTransitionsRecursive); + } + return list; + } + } + [Obsolete("stateCount is obsolete. Use .states.Length instead.", true)] + private int stateCount + { + get + { + return 0; + } + } + [Obsolete("stateMachineCount is obsolete. Use .stateMachines.Length instead.", true)] + private int stateMachineCount + { + get + { + return 0; + } + } + [Obsolete("uniqueNameHash does not exist anymore.", true)] + private int uniqueNameHash + { + get + { + return -1; + } + } + public AnimatorStateMachine() + { + AnimatorStateMachine.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorStateMachine mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_anyStatePosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_anyStatePosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_entryPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_entryPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_exitPosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_exitPosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_parentStateMachinePosition(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_parentStateMachinePosition(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorTransition[] GetStateMachineTransitions(AnimatorStateMachine sourceStateMachine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetStateMachineTransitions(AnimatorStateMachine sourceStateMachine, AnimatorTransition[] transitions); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddBehaviour(int instanceID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern ScriptableObject Internal_AddStateMachineBehaviourWithType(Type stateMachineBehaviourType); + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType) + { + return (StateMachineBehaviour)this.Internal_AddStateMachineBehaviourWithType(stateMachineBehaviourType); + } + public T AddStateMachineBehaviour() where T : StateMachineBehaviour + { + return this.AddStateMachineBehaviour(typeof(T)) as T; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string MakeUniqueStateName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string MakeUniqueStateMachineName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveStateInternal(AnimatorState state); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void RemoveStateMachineInternal(AnimatorStateMachine stateMachine); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MoveState(AnimatorState state, AnimatorStateMachine target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MoveStateMachine(AnimatorStateMachine stateMachine, AnimatorStateMachine target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasState(AnimatorState state, bool recursive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool HasStateMachine(AnimatorStateMachine state, bool recursive); + internal Vector3 GetStatePosition(AnimatorState state) + { + ChildAnimatorState[] states = this.states; + for (int i = 0; i < states.Length; i++) + { + if (state == states[i].state) + { + return states[i].position; + } + } + return Vector3.zero; + } + internal void SetStatePosition(AnimatorState state, Vector3 position) + { + ChildAnimatorState[] states = this.states; + for (int i = 0; i < states.Length; i++) + { + if (state == states[i].state) + { + states[i].position = position; + this.states = states; + return; + } + } + } + internal Vector3 GetStateMachinePosition(AnimatorStateMachine stateMachine) + { + ChildAnimatorStateMachine[] stateMachines = this.stateMachines; + for (int i = 0; i < stateMachines.Length; i++) + { + if (stateMachine == stateMachines[i].stateMachine) + { + return stateMachines[i].position; + } + } + return Vector3.zero; + } + internal void SetStateMachinePosition(AnimatorStateMachine stateMachine, Vector3 position) + { + ChildAnimatorStateMachine[] stateMachines = this.stateMachines; + for (int i = 0; i < stateMachines.Length; i++) + { + if (stateMachine == stateMachines[i].stateMachine) + { + stateMachines[i].position = position; + this.stateMachines = stateMachines; + return; + } + } + } + public AnimatorState AddState(string name) + { + return this.AddState(name, (this.states.Length <= 0) ? new Vector3(200f, 0f, 0f) : (this.states[this.states.Length - 1].position + new Vector3(35f, 65f))); + } + public AnimatorState AddState(string name, Vector3 position) + { + AnimatorState animatorState = new AnimatorState(); + animatorState.hideFlags = HideFlags.HideInHierarchy; + animatorState.name = this.MakeUniqueStateName(name); + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorState, AssetDatabase.GetAssetPath(this)); + } + this.AddState(animatorState, position); + return animatorState; + } + public void AddState(AnimatorState state, Vector3 position) + { + this.undoHandler.DoUndo(this, "State added"); + ChildAnimatorState item = default(ChildAnimatorState); + item.state = state; + item.position = position; + ChildAnimatorState[] states = this.states; + ArrayUtility.Add(ref states, item); + this.states = states; + } + public void RemoveState(AnimatorState state) + { + this.undoHandler.DoUndo(this, "State removed"); + this.undoHandler.DoUndo(state, "State removed"); + this.RemoveStateInternal(state); + } + public AnimatorStateMachine AddStateMachine(string name) + { + return this.AddStateMachine(name, Vector3.zero); + } + public AnimatorStateMachine AddStateMachine(string name, Vector3 position) + { + AnimatorStateMachine animatorStateMachine = new AnimatorStateMachine(); + animatorStateMachine.hideFlags = HideFlags.HideInHierarchy; + animatorStateMachine.name = this.MakeUniqueStateMachineName(name); + this.AddStateMachine(animatorStateMachine, position); + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorStateMachine, AssetDatabase.GetAssetPath(this)); + } + return animatorStateMachine; + } + public void AddStateMachine(AnimatorStateMachine stateMachine, Vector3 position) + { + this.undoHandler.DoUndo(this, "StateMachine " + stateMachine.name + " added"); + ChildAnimatorStateMachine item = default(ChildAnimatorStateMachine); + item.stateMachine = stateMachine; + item.position = position; + ChildAnimatorStateMachine[] stateMachines = this.stateMachines; + ArrayUtility.Add(ref stateMachines, item); + this.stateMachines = stateMachines; + } + public void RemoveStateMachine(AnimatorStateMachine stateMachine) + { + this.undoHandler.DoUndo(this, "StateMachine removed"); + this.undoHandler.DoUndo(stateMachine, "StateMachine removed"); + this.RemoveStateMachineInternal(stateMachine); + } + private AnimatorStateTransition AddAnyStateTransition() + { + this.undoHandler.DoUndo(this, "AnyState Transition Added"); + AnimatorStateTransition[] anyStateTransitions = this.anyStateTransitions; + AnimatorStateTransition animatorStateTransition = new AnimatorStateTransition(); + animatorStateTransition.hasExitTime = false; + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorStateTransition, AssetDatabase.GetAssetPath(this)); + } + animatorStateTransition.hideFlags = HideFlags.HideInHierarchy; + ArrayUtility.Add(ref anyStateTransitions, animatorStateTransition); + this.anyStateTransitions = anyStateTransitions; + return animatorStateTransition; + } + public AnimatorStateTransition AddAnyStateTransition(AnimatorState destinationState) + { + AnimatorStateTransition animatorStateTransition = this.AddAnyStateTransition(); + animatorStateTransition.destinationState = destinationState; + return animatorStateTransition; + } + public AnimatorStateTransition AddAnyStateTransition(AnimatorStateMachine destinationStateMachine) + { + AnimatorStateTransition animatorStateTransition = this.AddAnyStateTransition(); + animatorStateTransition.destinationStateMachine = destinationStateMachine; + return animatorStateTransition; + } + public bool RemoveAnyStateTransition(AnimatorStateTransition transition) + { + if (new List(this.anyStateTransitions).Any((AnimatorStateTransition t) => t == transition)) + { + this.undoHandler.DoUndo(this, "AnyState Transition Removed"); + AnimatorStateTransition[] anyStateTransitions = this.anyStateTransitions; + ArrayUtility.Remove(ref anyStateTransitions, transition); + this.anyStateTransitions = anyStateTransitions; + if (MecanimUtilities.AreSameAsset(this, transition)) + { + Undo.DestroyObjectImmediate(transition); + } + return true; + } + return false; + } + internal void RemoveAnyStateTransitionRecursive(AnimatorStateTransition transition) + { + if (this.RemoveAnyStateTransition(transition)) + { + return; + } + List stateMachinesRecursive = this.stateMachinesRecursive; + foreach (ChildAnimatorStateMachine current in stateMachinesRecursive) + { + if (current.stateMachine.RemoveAnyStateTransition(transition)) + { + break; + } + } + } + public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine) + { + AnimatorStateMachine destinationStateMachine = null; + return this.AddStateMachineTransition(sourceStateMachine, destinationStateMachine); + } + public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorStateMachine destinationStateMachine) + { + this.undoHandler.DoUndo(this, "StateMachine Transition Added"); + AnimatorTransition[] stateMachineTransitions = this.GetStateMachineTransitions(sourceStateMachine); + AnimatorTransition animatorTransition = new AnimatorTransition(); + if (destinationStateMachine) + { + animatorTransition.destinationStateMachine = destinationStateMachine; + } + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorTransition, AssetDatabase.GetAssetPath(this)); + } + animatorTransition.hideFlags = HideFlags.HideInHierarchy; + ArrayUtility.Add(ref stateMachineTransitions, animatorTransition); + this.SetStateMachineTransitions(sourceStateMachine, stateMachineTransitions); + return animatorTransition; + } + public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorState destinationState) + { + AnimatorTransition animatorTransition = this.AddStateMachineTransition(sourceStateMachine); + animatorTransition.destinationState = destinationState; + return animatorTransition; + } + public AnimatorTransition AddStateMachineExitTransition(AnimatorStateMachine sourceStateMachine) + { + AnimatorTransition animatorTransition = this.AddStateMachineTransition(sourceStateMachine); + animatorTransition.isExit = true; + return animatorTransition; + } + public bool RemoveStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorTransition transition) + { + this.undoHandler.DoUndo(this, "StateMachine Transition Removed"); + AnimatorTransition[] stateMachineTransitions = this.GetStateMachineTransitions(sourceStateMachine); + int num = stateMachineTransitions.Length; + ArrayUtility.Remove(ref stateMachineTransitions, transition); + this.SetStateMachineTransitions(sourceStateMachine, stateMachineTransitions); + if (MecanimUtilities.AreSameAsset(this, transition)) + { + Undo.DestroyObjectImmediate(transition); + } + return num != stateMachineTransitions.Length; + } + private AnimatorTransition AddEntryTransition() + { + this.undoHandler.DoUndo(this, "Entry Transition Added"); + AnimatorTransition[] entryTransitions = this.entryTransitions; + AnimatorTransition animatorTransition = new AnimatorTransition(); + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(animatorTransition, AssetDatabase.GetAssetPath(this)); + } + animatorTransition.hideFlags = HideFlags.HideInHierarchy; + ArrayUtility.Add(ref entryTransitions, animatorTransition); + this.entryTransitions = entryTransitions; + return animatorTransition; + } + public AnimatorTransition AddEntryTransition(AnimatorState destinationState) + { + AnimatorTransition animatorTransition = this.AddEntryTransition(); + animatorTransition.destinationState = destinationState; + return animatorTransition; + } + public AnimatorTransition AddEntryTransition(AnimatorStateMachine destinationStateMachine) + { + AnimatorTransition animatorTransition = this.AddEntryTransition(); + animatorTransition.destinationStateMachine = destinationStateMachine; + return animatorTransition; + } + public bool RemoveEntryTransition(AnimatorTransition transition) + { + if (new List(this.entryTransitions).Any((AnimatorTransition t) => t == transition)) + { + this.undoHandler.DoUndo(this, "Entry Transition Removed"); + AnimatorTransition[] entryTransitions = this.entryTransitions; + ArrayUtility.Remove(ref entryTransitions, transition); + this.entryTransitions = entryTransitions; + if (MecanimUtilities.AreSameAsset(this, transition)) + { + Undo.DestroyObjectImmediate(transition); + } + return true; + } + return false; + } + internal ChildAnimatorState FindState(int nameHash) + { + return new List(this.states).Find((ChildAnimatorState s) => s.state.nameHash == nameHash); + } + internal bool HasState(AnimatorState state) + { + return this.statesRecursive.Any((ChildAnimatorState s) => s.state == state); + } + internal bool IsDirectParent(AnimatorStateMachine stateMachine) + { + return this.stateMachines.Any((ChildAnimatorStateMachine sm) => sm.stateMachine == stateMachine); + } + internal bool HasStateMachine(AnimatorStateMachine child) + { + return this.stateMachinesRecursive.Any((ChildAnimatorStateMachine sm) => sm.stateMachine == child); + } + internal bool HasTransition(AnimatorState stateA, AnimatorState stateB) + { + return stateA.transitions.Any((AnimatorStateTransition t) => t.destinationState == stateB) || stateB.transitions.Any((AnimatorStateTransition t) => t.destinationState == stateA); + } + internal AnimatorStateMachine FindParent(AnimatorStateMachine stateMachine) + { + if (this.stateMachines.Any((ChildAnimatorStateMachine childSM) => childSM.stateMachine == stateMachine)) + { + return this; + } + return this.stateMachinesRecursive.Find((ChildAnimatorStateMachine sm) => sm.stateMachine.stateMachines.Any((ChildAnimatorStateMachine childSM) => childSM.stateMachine == stateMachine)).stateMachine; + } + internal AnimatorStateMachine FindStateMachine(string path) + { + AnimatorStateMachine.c__AnonStorey17 c__AnonStorey = new AnimatorStateMachine.c__AnonStorey17(); + c__AnonStorey.smNames = path.Split(new char[] + { + '.' + }); + AnimatorStateMachine animatorStateMachine = this; + int i = 1; + while (i < c__AnonStorey.smNames.Length - 1 && animatorStateMachine != null) + { + int num = Array.FindIndex(animatorStateMachine.stateMachines, (ChildAnimatorStateMachine t) => t.stateMachine.name == c__AnonStorey.smNames[i]); + animatorStateMachine = ((num < 0) ? null : animatorStateMachine.stateMachines[num].stateMachine); + i++; + } + return (!(animatorStateMachine == null)) ? animatorStateMachine : this; + } + internal AnimatorStateMachine FindStateMachine(AnimatorState state) + { + if (this.HasState(state, false)) + { + return this; + } + List stateMachinesRecursive = this.stateMachinesRecursive; + int num = stateMachinesRecursive.FindIndex((ChildAnimatorStateMachine sm) => sm.stateMachine.HasState(state, false)); + return (num < 0) ? null : stateMachinesRecursive[num].stateMachine; + } + internal AnimatorStateTransition FindTransition(AnimatorState destinationState) + { + return new List(this.anyStateTransitions).Find((AnimatorStateTransition t) => t.destinationState == destinationState); + } + [Obsolete("GetTransitionsFromState is obsolete. Use AnimatorState.transitions instead.", true)] + private AnimatorState GetTransitionsFromState(AnimatorState state) + { + return null; + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorStateTransition.cs b/UnityEditor/UnityEditor.Animations/AnimatorStateTransition.cs new file mode 100644 index 00000000..893edd93 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorStateTransition.cs @@ -0,0 +1,79 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Animations +{ + public sealed class AnimatorStateTransition : AnimatorTransitionBase + { + public extern float duration + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float offset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern TransitionInterruptionSource interruptionSource + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool orderedInterruption + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float exitTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasExitTime + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool canTransitionToSelf + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AnimatorStateTransition() + { + AnimatorStateTransition.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorStateTransition mono); + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorTransition.cs b/UnityEditor/UnityEditor.Animations/AnimatorTransition.cs new file mode 100644 index 00000000..5f49d3e6 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorTransition.cs @@ -0,0 +1,16 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Animations +{ + public sealed class AnimatorTransition : AnimatorTransitionBase + { + public AnimatorTransition() + { + AnimatorTransition.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(AnimatorTransition mono); + } +} diff --git a/UnityEditor/UnityEditor.Animations/AnimatorTransitionBase.cs b/UnityEditor/UnityEditor.Animations/AnimatorTransitionBase.cs new file mode 100644 index 00000000..31a027f9 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/AnimatorTransitionBase.cs @@ -0,0 +1,103 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Animations +{ + public class AnimatorTransitionBase : UnityEngine.Object + { + private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); + public extern bool solo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mute + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isExit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorStateMachine destinationStateMachine + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorState destinationState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AnimatorCondition[] conditions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal bool pushUndo + { + set + { + this.undoHandler.m_PushUndo = value; + } + } + public string GetDisplayName(UnityEngine.Object source) + { + return (!(source is AnimatorState)) ? this.GetDisplayNameStateMachineSource(source as AnimatorStateMachine) : this.GetDisplayNameStateSource(source as AnimatorState); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetDisplayNameStateSource(AnimatorState source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetDisplayNameStateMachineSource(AnimatorStateMachine source); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string BuildTransitionName(string source, string destination); + public void AddCondition(AnimatorConditionMode mode, float threshold, string parameter) + { + this.undoHandler.DoUndo(this, "Condition added"); + AnimatorCondition[] conditions = this.conditions; + ArrayUtility.Add(ref conditions, new AnimatorCondition + { + mode = mode, + parameter = parameter, + threshold = threshold + }); + this.conditions = conditions; + } + public void RemoveCondition(AnimatorCondition condition) + { + this.undoHandler.DoUndo(this, "Condition removed"); + AnimatorCondition[] conditions = this.conditions; + ArrayUtility.Remove(ref conditions, condition); + this.conditions = conditions; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AvatarMask.cs b/UnityEditor/UnityEditor.Animations/AvatarMask.cs similarity index 88% rename from UnityEditor/UnityEditorInternal/AvatarMask.cs rename to UnityEditor/UnityEditor.Animations/AvatarMask.cs index 44f5d54d..add9ab59 100644 --- a/UnityEditor/UnityEditorInternal/AvatarMask.cs +++ b/UnityEditor/UnityEditor.Animations/AvatarMask.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; using UnityEngine; -namespace UnityEditorInternal +namespace UnityEditor.Animations { public sealed class AvatarMask : UnityEngine.Object { @@ -47,15 +47,7 @@ internal extern bool hasFeetIK [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetTransformActive(int index, bool value); - public void Reset() - { - for (int i = 0; i < this.humanoidBodyPartCount; i++) - { - this.SetHumanoidBodyPartActive(i, true); - } - this.transformCount = 0; - } - public void Copy(AvatarMask other) + internal void Copy(AvatarMask other) { for (int i = 0; i < this.humanoidBodyPartCount; i++) { diff --git a/UnityEditor/UnityEditor.Animations/BlendTree.cs b/UnityEditor/UnityEditor.Animations/BlendTree.cs new file mode 100644 index 00000000..21215f2a --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/BlendTree.cs @@ -0,0 +1,149 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Animations +{ + public sealed class BlendTree : Motion + { + public extern string blendParameter + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string blendParameterY + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern BlendTreeType blendType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ChildMotion[] children + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern int recursiveBlendParameterCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public BlendTree() + { + BlendTree.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create(BlendTree mono); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SortChildren(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string GetRecursiveBlendParameter(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetRecursiveBlendParameterMin(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetRecursiveBlendParameterMax(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetInputBlendValue(string blendValueName, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetInputBlendValue(string blendValueName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern AnimationClip[] GetAnimationClipsFlattened(); + public void AddChild(Motion motion) + { + this.AddChild(motion, Vector2.zero, 0f); + } + public void AddChild(Motion motion, Vector2 position) + { + this.AddChild(motion, position, 0f); + } + public void AddChild(Motion motion, float threshold) + { + this.AddChild(motion, Vector2.zero, threshold); + } + public void RemoveChild(int index) + { + ChildMotion[] children = this.children; + ArrayUtility.RemoveAt(ref children, index); + this.children = children; + } + internal void AddChild(Motion motion, Vector2 position, float threshold) + { + Undo.RecordObject(this, "Added BlendTree Child"); + ChildMotion[] children = this.children; + ArrayUtility.Add(ref children, new ChildMotion + { + timeScale = 1f, + motion = motion, + position = position, + threshold = threshold, + directBlendParameter = "Blend" + }); + this.children = children; + } + public BlendTree CreateBlendTreeChild(float threshold) + { + return this.CreateBlendTreeChild(Vector2.zero, threshold); + } + public BlendTree CreateBlendTreeChild(Vector2 position) + { + return this.CreateBlendTreeChild(position, 0f); + } + internal bool HasChild(BlendTree childTree, bool recursive) + { + ChildMotion[] children = this.children; + for (int i = 0; i < children.Length; i++) + { + ChildMotion childMotion = children[i]; + if (childMotion.motion == childTree) + { + return true; + } + if (recursive && childMotion.motion is BlendTree && (childMotion.motion as BlendTree).HasChild(childTree, true)) + { + return true; + } + } + return false; + } + internal BlendTree CreateBlendTreeChild(Vector2 position, float threshold) + { + Undo.RecordObject(this, "Created BlendTree Child"); + BlendTree blendTree = new BlendTree(); + blendTree.name = "BlendTree"; + blendTree.hideFlags = HideFlags.HideInHierarchy; + if (AssetDatabase.GetAssetPath(this) != string.Empty) + { + AssetDatabase.AddObjectToAsset(blendTree, AssetDatabase.GetAssetPath(this)); + } + this.AddChild(blendTree, position, threshold); + return blendTree; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/BlendTreeType.cs b/UnityEditor/UnityEditor.Animations/BlendTreeType.cs similarity index 56% rename from UnityEditor/UnityEditorInternal/BlendTreeType.cs rename to UnityEditor/UnityEditor.Animations/BlendTreeType.cs index 0cd311ec..b6cf21c4 100644 --- a/UnityEditor/UnityEditorInternal/BlendTreeType.cs +++ b/UnityEditor/UnityEditor.Animations/BlendTreeType.cs @@ -1,11 +1,12 @@ using System; -namespace UnityEditorInternal +namespace UnityEditor.Animations { public enum BlendTreeType { - Simple, + Simple1D, SimpleDirectional2D, FreeformDirectional2D, - FreeformCartesian2D + FreeformCartesian2D, + Direct } } diff --git a/UnityEditor/UnityEditor.Animations/ChildAnimatorState.cs b/UnityEditor/UnityEditor.Animations/ChildAnimatorState.cs new file mode 100644 index 00000000..f4e4c9b9 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/ChildAnimatorState.cs @@ -0,0 +1,32 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + public struct ChildAnimatorState + { + private AnimatorState m_State; + private Vector3 m_Position; + public AnimatorState state + { + get + { + return this.m_State; + } + set + { + this.m_State = value; + } + } + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/ChildAnimatorStateMachine.cs b/UnityEditor/UnityEditor.Animations/ChildAnimatorStateMachine.cs new file mode 100644 index 00000000..e262e893 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/ChildAnimatorStateMachine.cs @@ -0,0 +1,32 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + public struct ChildAnimatorStateMachine + { + private AnimatorStateMachine m_StateMachine; + private Vector3 m_Position; + public AnimatorStateMachine stateMachine + { + get + { + return this.m_StateMachine; + } + set + { + this.m_StateMachine = value; + } + } + public Vector3 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/ChildMotion.cs b/UnityEditor/UnityEditor.Animations/ChildMotion.cs new file mode 100644 index 00000000..6c9b3ec4 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/ChildMotion.cs @@ -0,0 +1,92 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + public struct ChildMotion + { + private Motion m_Motion; + private float m_Threshold; + private Vector2 m_Position; + private float m_TimeScale; + private float m_CycleOffset; + private string m_DirectBlendParameter; + private bool m_Mirror; + public Motion motion + { + get + { + return this.m_Motion; + } + set + { + this.m_Motion = value; + } + } + public float threshold + { + get + { + return this.m_Threshold; + } + set + { + this.m_Threshold = value; + } + } + public Vector2 position + { + get + { + return this.m_Position; + } + set + { + this.m_Position = value; + } + } + public float timeScale + { + get + { + return this.m_TimeScale; + } + set + { + this.m_TimeScale = value; + } + } + public float cycleOffset + { + get + { + return this.m_CycleOffset; + } + set + { + this.m_CycleOffset = value; + } + } + public string directBlendParameter + { + get + { + return this.m_DirectBlendParameter; + } + set + { + this.m_DirectBlendParameter = value; + } + } + public bool mirror + { + get + { + return this.m_Mirror; + } + set + { + this.m_Mirror = value; + } + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/MecanimUtilities.cs b/UnityEditor/UnityEditor.Animations/MecanimUtilities.cs new file mode 100644 index 00000000..47626f12 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/MecanimUtilities.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor.Animations +{ + internal class MecanimUtilities + { + public static bool StateMachineRelativePath(AnimatorStateMachine parent, AnimatorStateMachine toFind, ref List hierarchy) + { + hierarchy.Add(parent); + if (parent == toFind) + { + return true; + } + for (int i = 0; i < parent.stateMachines.Length; i++) + { + if (MecanimUtilities.StateMachineRelativePath(parent.stateMachines[i].stateMachine, toFind, ref hierarchy)) + { + return true; + } + } + hierarchy.Remove(parent); + return false; + } + internal static bool AreSameAsset(UnityEngine.Object obj1, UnityEngine.Object obj2) + { + return AssetDatabase.GetAssetPath(obj1) == AssetDatabase.GetAssetPath(obj2); + } + internal static void DestroyBlendTreeRecursive(BlendTree blendTree) + { + for (int i = 0; i < blendTree.children.Length; i++) + { + BlendTree blendTree2 = blendTree.children[i].motion as BlendTree; + if (blendTree2 != null && MecanimUtilities.AreSameAsset(blendTree, blendTree2)) + { + MecanimUtilities.DestroyBlendTreeRecursive(blendTree2); + } + } + Undo.DestroyObjectImmediate(blendTree); + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/PushUndoIfNeeded.cs b/UnityEditor/UnityEditor.Animations/PushUndoIfNeeded.cs new file mode 100644 index 00000000..bf647fb2 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/PushUndoIfNeeded.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + internal struct PushUndoIfNeeded + { + internal bool m_PushUndo; + internal PushUndoIfNeeded(bool pushUndo) + { + this.m_PushUndo = pushUndo; + } + internal void DoUndo(UnityEngine.Object target, string undoOperation) + { + if (this.m_PushUndo) + { + Undo.RegisterCompleteObjectUndo(target, undoOperation); + } + } + } +} diff --git a/UnityEditor/UnityEditor.Animations/StateBehavioursPair.cs b/UnityEditor/UnityEditor.Animations/StateBehavioursPair.cs new file mode 100644 index 00000000..eb3d3883 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/StateBehavioursPair.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + internal struct StateBehavioursPair + { + public AnimatorState m_State; + public StateMachineBehaviour[] m_Behaviours; + } +} diff --git a/UnityEditor/UnityEditor.Animations/StateMachineBehaviourContext.cs b/UnityEditor/UnityEditor.Animations/StateMachineBehaviourContext.cs new file mode 100644 index 00000000..7434afa1 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/StateMachineBehaviourContext.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.InteropServices; +using UnityEngine; +namespace UnityEditor.Animations +{ + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public sealed class StateMachineBehaviourContext + { + public AnimatorController animatorController; + public UnityEngine.Object animatorObject; + public int layerIndex; + } +} diff --git a/UnityEditor/UnityEditor.Animations/StateMotionPair.cs b/UnityEditor/UnityEditor.Animations/StateMotionPair.cs new file mode 100644 index 00000000..1a428ed2 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/StateMotionPair.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace UnityEditor.Animations +{ + internal struct StateMotionPair + { + public AnimatorState m_State; + public Motion m_Motion; + } +} diff --git a/UnityEditor/UnityEditor.Animations/TransitionInterruptionSource.cs b/UnityEditor/UnityEditor.Animations/TransitionInterruptionSource.cs new file mode 100644 index 00000000..8ce9e503 --- /dev/null +++ b/UnityEditor/UnityEditor.Animations/TransitionInterruptionSource.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEditor.Animations +{ + public enum TransitionInterruptionSource + { + None, + Source, + Destination, + SourceThenDestination, + DestinationThenSource + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioEffectParameterPath.cs b/UnityEditor/UnityEditor.Audio/AudioEffectParameterPath.cs new file mode 100644 index 00000000..d8b3c82d --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioEffectParameterPath.cs @@ -0,0 +1,33 @@ +using System; +namespace UnityEditor.Audio +{ + internal sealed class AudioEffectParameterPath : AudioGroupParameterPath + { + public AudioMixerEffectController effect; + public AudioEffectParameterPath(AudioMixerGroupController group, AudioMixerEffectController effect, GUID parameter) : base(group, parameter) + { + this.effect = effect; + } + public override string ResolveStringPath(bool getOnlyBasePath) + { + if (getOnlyBasePath) + { + return base.GetBasePath(this.group.GetDisplayString(), this.effect.effectName); + } + if (this.effect.GetGUIDForMixLevel() == this.parameter) + { + return "Mix Level" + base.GetBasePath(this.group.GetDisplayString(), this.effect.effectName); + } + MixerParameterDefinition[] effectParameters = MixerEffectDefinitions.GetEffectParameters(this.effect.effectName); + for (int i = 0; i < effectParameters.Length; i++) + { + GUID gUIDForParameter = this.effect.GetGUIDForParameter(effectParameters[i].name); + if (gUIDForParameter == this.parameter) + { + return effectParameters[i].name + base.GetBasePath(this.group.GetDisplayString(), this.effect.effectName); + } + } + return "Error finding Parameter path."; + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioGroupParameterPath.cs b/UnityEditor/UnityEditor.Audio/AudioGroupParameterPath.cs new file mode 100644 index 00000000..30ed512c --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioGroupParameterPath.cs @@ -0,0 +1,38 @@ +using System; +namespace UnityEditor.Audio +{ + internal class AudioGroupParameterPath : AudioParameterPath + { + public AudioMixerGroupController group; + public AudioGroupParameterPath(AudioMixerGroupController group, GUID parameter) + { + this.group = group; + this.parameter = parameter; + } + public override string ResolveStringPath(bool getOnlyBasePath) + { + if (getOnlyBasePath) + { + return this.GetBasePath(this.group.GetDisplayString(), null); + } + if (this.group.GetGUIDForVolume() == this.parameter) + { + return "Volume" + this.GetBasePath(this.group.GetDisplayString(), null); + } + if (this.group.GetGUIDForPitch() == this.parameter) + { + return "Pitch" + this.GetBasePath(this.group.GetDisplayString(), null); + } + return "Error finding Parameter path."; + } + protected string GetBasePath(string group, string effect) + { + string str = " (of " + group; + if (!string.IsNullOrEmpty(effect)) + { + str = str + "➔" + effect; + } + return str + ")"; + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioMixerController.cs b/UnityEditor/UnityEditor.Audio/AudioMixerController.cs new file mode 100644 index 00000000..0dbaec06 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioMixerController.cs @@ -0,0 +1,1130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Audio; +namespace UnityEditor.Audio +{ + internal sealed class AudioMixerController : AudioMixer + { + public class ConnectionNode + { + public bool visited; + public object groupTail; + public List targets = new List(); + public AudioMixerGroupController group; + public AudioMixerEffectController effect; + public string GetDisplayString() + { + string text = this.group.GetDisplayString(); + if (this.effect != null) + { + text = text + AudioMixerController.s_GroupEffectDisplaySeperator + AudioMixerController.FixNameForPopupMenu(this.effect.effectName); + } + return text; + } + } + [NonSerialized] + public int m_HighlightEffectIndex = -1; + [NonSerialized] + private List m_CachedSelection; + public static float kMinVolume = -80f; + public static float kMaxEffect; + public static float kVolumeWarp = 1.7f; + public static string s_GroupEffectDisplaySeperator = "\\"; + [NonSerialized] + private Dictionary m_ExposedParamPathCache; + public event ChangedExposedParameterHandler ChangedExposedParameter + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + this.ChangedExposedParameter = (ChangedExposedParameterHandler)Delegate.Combine(this.ChangedExposedParameter, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + this.ChangedExposedParameter = (ChangedExposedParameterHandler)Delegate.Remove(this.ChangedExposedParameter, value); + } + } + public AudioMixerGroupController[] allGroups + { + get + { + List list = new List(); + AudioMixerController.GetGroupsRecurse(this.masterGroup, list); + return list.ToArray(); + } + } + public extern int numExposedParameters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ExposedAudioParameter[] exposedParameters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerGroupController masterGroup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerSnapshot startSnapshot + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerSnapshotController TargetSnapshot + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerSnapshotController[] snapshots + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public List CachedSelection + { + get + { + if (this.m_CachedSelection == null) + { + this.m_CachedSelection = new List(); + } + return this.m_CachedSelection; + } + } + public extern int currentViewIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern MixerGroupView[] views + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isSuspended + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private Dictionary exposedParamCache + { + get + { + if (this.m_ExposedParamPathCache == null) + { + this.m_ExposedParamPathCache = new Dictionary(); + } + return this.m_ExposedParamPathCache; + } + } + public AudioMixerController() + { + AudioMixerController.Internal_CreateAudioMixerController(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAudioMixerController(AudioMixerController mono); + private static void GetGroupsRecurse(AudioMixerGroupController group, List groups) + { + groups.Add(group); + AudioMixerGroupController[] children = group.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerController.GetGroupsRecurse(children[i], groups); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetGroupVUInfo(GUID group, bool fader, ref float[] vuLevel, ref float[] vuPeak); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateMuteSolo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void UpdateBypass(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool CurrentViewContainsGroup(GUID group); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool CheckForCyclicReferences(AudioMixer mixer, AudioMixerGroup group); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float GetMaxVolume(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float GetVolumeSplitPoint(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool EditingTargetSnapshot(); + public void OnChangedExposedParameter() + { + if (this.ChangedExposedParameter != null) + { + this.ChangedExposedParameter(); + } + } + public void ClearEventHandlers() + { + if (this.ChangedExposedParameter != null) + { + Delegate[] invocationList = this.ChangedExposedParameter.GetInvocationList(); + for (int i = 0; i < invocationList.Length; i++) + { + Delegate @delegate = invocationList[i]; + this.ChangedExposedParameter = (ChangedExposedParameterHandler)Delegate.Remove(this.ChangedExposedParameter, (ChangedExposedParameterHandler)@delegate); + } + } + } + private string FindUniqueParameterName(string template, ExposedAudioParameter[] parameters) + { + string text = template; + int num = 1; + for (int i = 0; i < parameters.Length; i++) + { + if (text == parameters[i].name) + { + text = template + " " + num++; + i = -1; + } + } + return text; + } + private int SortFuncForExposedParameters(ExposedAudioParameter p1, ExposedAudioParameter p2) + { + return string.CompareOrdinal(this.ResolveExposedParameterPath(p1.guid, true), this.ResolveExposedParameterPath(p2.guid, true)); + } + public void AddExposedParameter(AudioParameterPath path) + { + if (!this.ContainsExposedParameter(path.parameter)) + { + List list = new List(this.exposedParameters); + list.Add(new ExposedAudioParameter + { + name = this.FindUniqueParameterName("MyExposedParam", this.exposedParameters), + guid = path.parameter + }); + list.Sort(new Comparison(this.SortFuncForExposedParameters)); + this.exposedParameters = list.ToArray(); + this.OnChangedExposedParameter(); + this.exposedParamCache[path.parameter] = path; + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + else + { + Debug.LogError("Cannot expose the same parameter more than once!"); + } + } + public bool ContainsExposedParameter(GUID parameter) + { + return ( + from val in this.exposedParameters + where val.guid == parameter + select val).ToArray().Length > 0; + } + public void RemoveExposedParameter(GUID parameter) + { + this.exposedParameters = ( + from val in this.exposedParameters + where val.guid != parameter + select val).ToArray(); + this.OnChangedExposedParameter(); + if (this.exposedParamCache.ContainsKey(parameter)) + { + this.exposedParamCache.Remove(parameter); + } + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + public string ResolveExposedParameterPath(GUID parameter, bool getOnlyBasePath) + { + if (this.exposedParamCache.ContainsKey(parameter)) + { + AudioParameterPath audioParameterPath = this.exposedParamCache[parameter]; + return audioParameterPath.ResolveStringPath(getOnlyBasePath); + } + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + if (current.GetGUIDForVolume() == parameter || current.GetGUIDForPitch() == parameter) + { + AudioGroupParameterPath audioGroupParameterPath = new AudioGroupParameterPath(current, parameter); + this.exposedParamCache[parameter] = audioGroupParameterPath; + string result = audioGroupParameterPath.ResolveStringPath(getOnlyBasePath); + return result; + } + for (int i = 0; i < current.effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = current.effects[i]; + MixerParameterDefinition[] effectParameters = MixerEffectDefinitions.GetEffectParameters(audioMixerEffectController.effectName); + for (int j = 0; j < effectParameters.Length; j++) + { + GUID gUIDForParameter = audioMixerEffectController.GetGUIDForParameter(effectParameters[j].name); + if (gUIDForParameter == parameter) + { + AudioEffectParameterPath audioEffectParameterPath = new AudioEffectParameterPath(current, audioMixerEffectController, parameter); + this.exposedParamCache[parameter] = audioEffectParameterPath; + string result = audioEffectParameterPath.ResolveStringPath(getOnlyBasePath); + return result; + } + } + } + } + return "Error finding Parameter path"; + } + public static AudioMixerController CreateMixerControllerAtPath(string path) + { + AudioMixerController audioMixerController = new AudioMixerController(); + audioMixerController.CreateDefaultAsset(path); + return audioMixerController; + } + public void CreateDefaultAsset(string path) + { + this.masterGroup = new AudioMixerGroupController(this); + this.masterGroup.name = "Master"; + this.masterGroup.PreallocateGUIDs(); + AudioMixerEffectController audioMixerEffectController = new AudioMixerEffectController("Attenuation"); + audioMixerEffectController.PreallocateGUIDs(); + this.masterGroup.InsertEffect(audioMixerEffectController, 0); + AudioMixerSnapshotController audioMixerSnapshotController = new AudioMixerSnapshotController(this); + audioMixerSnapshotController.name = "Snapshot"; + this.snapshots = new AudioMixerSnapshotController[] + { + audioMixerSnapshotController + }; + this.startSnapshot = audioMixerSnapshotController; + UnityEngine.Object[] assets = new UnityEngine.Object[] + { + this, + this.masterGroup, + audioMixerEffectController, + audioMixerSnapshotController + }; + AssetDatabase.CreateAssetFromObjects(assets, path); + } + private void BuildTestSetup(System.Random r, AudioMixerGroupController parent, int minSpan, int maxSpan, int maxGroups, string prefix, ref int numGroups) + { + int num = (numGroups != 0) ? r.Next(minSpan, maxSpan + 1) : maxSpan; + for (int i = 0; i < num; i++) + { + string text = prefix + i; + AudioMixerGroupController audioMixerGroupController = this.CreateNewGroup(text, false); + this.AddChildToParent(audioMixerGroupController, parent); + if (++numGroups >= maxGroups) + { + return; + } + this.BuildTestSetup(r, audioMixerGroupController, minSpan, (maxSpan <= minSpan) ? minSpan : (maxSpan - 1), maxGroups, text, ref numGroups); + } + } + public void BuildTestSetup(int minSpan, int maxSpan, int maxGroups) + { + int num = 0; + this.DeleteGroups(this.masterGroup.children); + this.BuildTestSetup(new System.Random(), this.masterGroup, minSpan, maxSpan, maxGroups, "G", ref num); + } + public List GetAllAudioGroupsSlow() + { + List result = new List(); + if (this.masterGroup != null) + { + this.GetAllAudioGroupsSlowRecurse(this.masterGroup, ref result); + } + return result; + } + private void GetAllAudioGroupsSlowRecurse(AudioMixerGroupController g, ref List groups) + { + groups.Add(g); + AudioMixerGroupController[] children = g.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController g2 = children[i]; + this.GetAllAudioGroupsSlowRecurse(g2, ref groups); + } + } + public bool HasMoreThanOneGroup() + { + return this.masterGroup.children.Length > 0; + } + private bool IsChildOf(AudioMixerGroupController child, List groups) + { + while (child != null) + { + child = this.FindParentGroup(this.masterGroup, child); + if (groups.Contains(child)) + { + return true; + } + } + return false; + } + public bool AreAnyOfTheGroupsInTheListAncestors(List groups) + { + return groups.Any((AudioMixerGroupController g) => this.IsChildOf(g, groups)); + } + private void RemoveAncestorGroups(List groups) + { + groups.RemoveAll((AudioMixerGroupController g) => this.IsChildOf(g, groups)); + object.Equals(this.AreAnyOfTheGroupsInTheListAncestors(groups), false); + } + private void DestroyExposedParametersContainedInEffect(AudioMixerEffectController effect) + { + Undo.RecordObject(this, "Changed Exposed Parameters"); + ExposedAudioParameter[] exposedParameters = this.exposedParameters; + ExposedAudioParameter[] array = exposedParameters; + for (int i = 0; i < array.Length; i++) + { + ExposedAudioParameter exposedAudioParameter = array[i]; + if (effect.ContainsParameterGUID(exposedAudioParameter.guid)) + { + this.RemoveExposedParameter(exposedAudioParameter.guid); + } + } + } + private void DestroyExposedParametersContainedInGroup(AudioMixerGroupController group) + { + Undo.RecordObject(this, "Remove Exposed Parameter"); + ExposedAudioParameter[] exposedParameters = this.exposedParameters; + ExposedAudioParameter[] array = exposedParameters; + for (int i = 0; i < array.Length; i++) + { + ExposedAudioParameter exposedAudioParameter = array[i]; + if (group.GetGUIDForVolume() == exposedAudioParameter.guid || group.GetGUIDForPitch() == exposedAudioParameter.guid) + { + this.RemoveExposedParameter(exposedAudioParameter.guid); + } + } + } + private void DeleteSubGroupRecursive(AudioMixerGroupController group) + { + AudioMixerGroupController[] children = group.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController group2 = children[i]; + this.DeleteSubGroupRecursive(group2); + } + AudioMixerEffectController[] effects = group.effects; + for (int j = 0; j < effects.Length; j++) + { + AudioMixerEffectController audioMixerEffectController = effects[j]; + this.DestroyExposedParametersContainedInEffect(audioMixerEffectController); + Undo.DestroyObjectImmediate(audioMixerEffectController); + } + this.DestroyExposedParametersContainedInGroup(group); + Undo.DestroyObjectImmediate(group); + } + private void DeleteGroupsInternal(List groupsToDelete, List allGroups) + { + foreach (AudioMixerGroupController current in allGroups) + { + IEnumerable enumerable = groupsToDelete.Intersect(current.children); + if (enumerable.Count() > 0) + { + Undo.RegisterCompleteObjectUndo(current, "Delete Group(s)"); + current.children = current.children.Except(enumerable).ToArray(); + } + } + foreach (AudioMixerGroupController current2 in groupsToDelete) + { + this.DeleteSubGroupRecursive(current2); + } + } + public void DeleteGroups(AudioMixerGroupController[] groups) + { + List list = groups.ToList(); + this.RemoveAncestorGroups(list); + this.DeleteGroupsInternal(list, this.GetAllAudioGroupsSlow()); + this.OnUnitySelectionChanged(); + } + public void RemoveEffect(AudioMixerEffectController effect, AudioMixerGroupController group) + { + Undo.RecordObject(group, "Delete Effect"); + List list = new List(group.effects); + list.Remove(effect); + group.effects = list.ToArray(); + this.DestroyExposedParametersContainedInEffect(effect); + Undo.DestroyObjectImmediate(effect); + } + public void OnSubAssetChanged() + { + AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this)); + } + public void CloneNewSnapshotFromTarget(bool storeUndoState) + { + List list = new List(this.snapshots); + AudioMixerSnapshotController audioMixerSnapshotController = UnityEngine.Object.Instantiate(this.TargetSnapshot); + AudioMixerSnapshotController audioMixerSnapshotController2 = audioMixerSnapshotController; + audioMixerSnapshotController2.name = this.TargetSnapshot.name + " - Copy"; + list.Add(audioMixerSnapshotController2); + this.snapshots = list.ToArray(); + this.TargetSnapshot = list[list.Count - 1]; + AssetDatabase.AddObjectToAsset(audioMixerSnapshotController2, this); + if (storeUndoState) + { + Undo.RegisterCreatedObjectUndo(audioMixerSnapshotController2, string.Empty); + } + this.OnSubAssetChanged(); + } + public void RemoveTargetSnapshot() + { + if (this.snapshots.Length < 2) + { + return; + } + AudioMixerSnapshotController targetSnapshot = this.TargetSnapshot; + Undo.RecordObject(this, "Remove Snapshot"); + List list = new List(this.snapshots); + list.Remove(targetSnapshot); + this.snapshots = list.ToArray(); + Undo.DestroyObjectImmediate(targetSnapshot); + this.OnSubAssetChanged(); + } + public void RemoveSnapshot(AudioMixerSnapshotController snapshot) + { + if (this.snapshots.Length < 2) + { + return; + } + Undo.RecordObject(this, "Remove Snapshot"); + List list = new List(this.snapshots); + list.Remove(snapshot); + this.snapshots = list.ToArray(); + Undo.DestroyObjectImmediate(snapshot); + this.OnSubAssetChanged(); + } + public AudioMixerGroupController CreateNewGroup(string name, bool storeUndoState) + { + AudioMixerGroupController audioMixerGroupController = new AudioMixerGroupController(this); + audioMixerGroupController.name = name; + audioMixerGroupController.PreallocateGUIDs(); + AudioMixerEffectController audioMixerEffectController = new AudioMixerEffectController("Attenuation"); + this.AddNewSubAsset(audioMixerEffectController, storeUndoState); + audioMixerEffectController.PreallocateGUIDs(); + audioMixerGroupController.InsertEffect(audioMixerEffectController, 0); + this.AddNewSubAsset(audioMixerGroupController, storeUndoState); + return audioMixerGroupController; + } + public void AddChildToParent(AudioMixerGroupController child, AudioMixerGroupController parent) + { + this.RemoveGroupsFromParent(new AudioMixerGroupController[] + { + child + }, false); + parent.children = new List(parent.children) + { + child + }.ToArray(); + } + private void AddNewSubAsset(UnityEngine.Object obj, bool storeUndoState) + { + AssetDatabase.AddObjectToAsset(obj, this); + if (storeUndoState) + { + Undo.RegisterCreatedObjectUndo(obj, string.Empty); + } + } + public void RemoveGroupsFromParent(AudioMixerGroupController[] groups, bool storeUndoState) + { + List list = groups.ToList(); + this.RemoveAncestorGroups(list); + if (storeUndoState) + { + Undo.RecordObject(this, "Remove group"); + } + foreach (AudioMixerGroupController current in list) + { + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current2 in allAudioGroupsSlow) + { + List list2 = new List(current2.children); + if (list2.Contains(current)) + { + list2.Remove(current); + } + if (current2.children.Length != list2.Count) + { + current2.children = list2.ToArray(); + } + } + } + } + public AudioMixerGroupController FindParentGroup(AudioMixerGroupController node, AudioMixerGroupController group) + { + for (int i = 0; i < node.children.Length; i++) + { + if (node.children[i] == group) + { + return node; + } + AudioMixerGroupController audioMixerGroupController = this.FindParentGroup(node.children[i], group); + if (audioMixerGroupController != null) + { + return audioMixerGroupController; + } + } + return null; + } + public AudioMixerEffectController CopyEffect(AudioMixerEffectController sourceEffect) + { + AudioMixerEffectController audioMixerEffectController = new AudioMixerEffectController(sourceEffect.effectName); + audioMixerEffectController.name = sourceEffect.name; + audioMixerEffectController.PreallocateGUIDs(); + MixerParameterDefinition[] effectParameters = MixerEffectDefinitions.GetEffectParameters(sourceEffect.effectName); + AudioMixerSnapshotController[] snapshots = this.snapshots; + for (int i = 0; i < snapshots.Length; i++) + { + AudioMixerSnapshotController audioMixerSnapshotController = snapshots[i]; + float value; + if (audioMixerSnapshotController.GetValue(sourceEffect.GetGUIDForMixLevel(), out value)) + { + audioMixerSnapshotController.SetValue(audioMixerEffectController.GetGUIDForMixLevel(), value); + } + MixerParameterDefinition[] array = effectParameters; + for (int j = 0; j < array.Length; j++) + { + MixerParameterDefinition mixerParameterDefinition = array[j]; + if (audioMixerSnapshotController.GetValue(sourceEffect.GetGUIDForParameter(mixerParameterDefinition.name), out value)) + { + audioMixerSnapshotController.SetValue(audioMixerEffectController.GetGUIDForParameter(mixerParameterDefinition.name), value); + } + } + } + AssetDatabase.AddObjectToAsset(audioMixerEffectController, this); + return audioMixerEffectController; + } + private AudioMixerGroupController DuplicateGroupRecurse(AudioMixerGroupController sourceGroup) + { + AudioMixerGroupController audioMixerGroupController = new AudioMixerGroupController(this); + List list = new List(); + AudioMixerEffectController[] effects = sourceGroup.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController sourceEffect = effects[i]; + list.Add(this.CopyEffect(sourceEffect)); + } + List list2 = new List(); + AudioMixerGroupController[] children = sourceGroup.children; + for (int j = 0; j < children.Length; j++) + { + AudioMixerGroupController sourceGroup2 = children[j]; + list2.Add(this.DuplicateGroupRecurse(sourceGroup2)); + } + audioMixerGroupController.name = sourceGroup.name + " - Copy"; + audioMixerGroupController.PreallocateGUIDs(); + audioMixerGroupController.effects = list.ToArray(); + audioMixerGroupController.children = list2.ToArray(); + audioMixerGroupController.solo = sourceGroup.solo; + audioMixerGroupController.mute = sourceGroup.mute; + audioMixerGroupController.bypassEffects = sourceGroup.bypassEffects; + AudioMixerSnapshotController[] snapshots = this.snapshots; + for (int k = 0; k < snapshots.Length; k++) + { + AudioMixerSnapshotController audioMixerSnapshotController = snapshots[k]; + float value; + if (audioMixerSnapshotController.GetValue(sourceGroup.GetGUIDForVolume(), out value)) + { + audioMixerSnapshotController.SetValue(audioMixerGroupController.GetGUIDForVolume(), value); + } + if (audioMixerSnapshotController.GetValue(sourceGroup.GetGUIDForPitch(), out value)) + { + audioMixerSnapshotController.SetValue(audioMixerGroupController.GetGUIDForPitch(), value); + } + } + AssetDatabase.AddObjectToAsset(audioMixerGroupController, this); + if (this.CurrentViewContainsGroup(sourceGroup.groupID)) + { + audioMixerGroupController.controller.AddGroupToCurrentView(audioMixerGroupController); + } + return audioMixerGroupController; + } + public List DuplicateGroups(AudioMixerGroupController[] sourceGroups) + { + List list = sourceGroups.ToList(); + this.RemoveAncestorGroups(list); + List list2 = new List(); + foreach (AudioMixerGroupController current in list) + { + AudioMixerGroupController audioMixerGroupController = this.FindParentGroup(this.masterGroup, current); + if (audioMixerGroupController != null && current != null) + { + AudioMixerGroupController item = this.DuplicateGroupRecurse(current); + audioMixerGroupController.children = new List(audioMixerGroupController.children) + { + item + }.ToArray(); + list2.Add(item); + } + } + return list2; + } + public void CopyEffectSettingsToAllSnapshots(AudioMixerGroupController group, int effectIndex, AudioMixerSnapshotController snapshot, bool includeWetParam) + { + AudioMixerSnapshotController[] snapshots = this.snapshots; + for (int i = 0; i < snapshots.Length; i++) + { + if (!(snapshots[i] == snapshot)) + { + AudioMixerEffectController audioMixerEffectController = group.effects[effectIndex]; + MixerParameterDefinition[] effectParameters = MixerEffectDefinitions.GetEffectParameters(audioMixerEffectController.effectName); + if (includeWetParam) + { + GUID gUIDForMixLevel = audioMixerEffectController.GetGUIDForMixLevel(); + float value; + if (snapshot.GetValue(gUIDForMixLevel, out value)) + { + snapshots[i].SetValue(gUIDForMixLevel, value); + } + } + MixerParameterDefinition[] array = effectParameters; + for (int j = 0; j < array.Length; j++) + { + MixerParameterDefinition mixerParameterDefinition = array[j]; + GUID gUIDForParameter = audioMixerEffectController.GetGUIDForParameter(mixerParameterDefinition.name); + float value; + if (snapshot.GetValue(gUIDForParameter, out value)) + { + snapshots[i].SetValue(gUIDForParameter, value); + } + } + } + } + } + public void CopyAllSettingsToAllSnapshots(AudioMixerGroupController group, AudioMixerSnapshotController snapshot) + { + for (int i = 0; i < group.effects.Length; i++) + { + this.CopyEffectSettingsToAllSnapshots(group, i, snapshot, true); + } + AudioMixerSnapshotController[] snapshots = this.snapshots; + for (int j = 0; j < snapshots.Length; j++) + { + if (!(snapshots[j] == snapshot)) + { + AudioMixerSnapshotController snapshot2 = snapshots[j]; + group.SetValueForVolume(this, snapshot2, group.GetValueForVolume(this, snapshot)); + group.SetValueForPitch(this, snapshot2, group.GetValueForPitch(this, snapshot)); + } + } + } + public void CopyAttenuationToAllSnapshots(AudioMixerGroupController group, AudioMixerSnapshotController snapshot) + { + AudioMixerSnapshotController[] snapshots = this.snapshots; + for (int i = 0; i < snapshots.Length; i++) + { + if (!(snapshots[i] == snapshot)) + { + AudioMixerSnapshotController snapshot2 = snapshots[i]; + group.SetValueForVolume(this, snapshot2, group.GetValueForVolume(this, snapshot)); + } + } + } + public void ReparentSelection(AudioMixerGroupController newParent, AudioMixerGroupController insertAfterThisNode, List selection) + { + Undo.RecordObject(newParent, "Change Audio Mixer Group Parent"); + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + if (current.children.Intersect(selection).Any()) + { + Undo.RecordObject(current, string.Empty); + List list = new List(current.children); + foreach (AudioMixerGroupController current2 in selection) + { + list.Remove(current2); + } + current.children = list.ToArray(); + } + } + List list2 = new List(newParent.children); + int index = list2.IndexOf(insertAfterThisNode) + 1; + list2.InsertRange(index, selection); + newParent.children = list2.ToArray(); + } + public static bool InsertEffect(AudioMixerEffectController effect, ref List targetEffects, int targetIndex) + { + if (targetIndex < 0 || targetIndex > targetEffects.Count) + { + Debug.LogError(string.Concat(new object[] + { + "Inserting effect failed! size: ", + targetEffects.Count, + " at index: ", + targetIndex + })); + return false; + } + targetEffects.Insert(targetIndex, effect); + return true; + } + public static bool MoveEffect(ref List sourceEffects, int sourceIndex, ref List targetEffects, int targetIndex) + { + if (sourceEffects == targetEffects) + { + if (targetIndex > sourceIndex) + { + targetIndex--; + } + if (sourceIndex == targetIndex) + { + return false; + } + } + if (sourceIndex < 0 || sourceIndex >= sourceEffects.Count) + { + return false; + } + if (targetIndex < 0 || targetIndex > targetEffects.Count) + { + return false; + } + AudioMixerEffectController item = sourceEffects[sourceIndex]; + sourceEffects.RemoveAt(sourceIndex); + targetEffects.Insert(targetIndex, item); + return true; + } + public static string FixNameForPopupMenu(string s) + { + return s; + } + public void ClearSendConnectionsTo(AudioMixerEffectController sendTarget) + { + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + AudioMixerEffectController[] effects = current.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (audioMixerEffectController.IsSend() && audioMixerEffectController.sendTarget == sendTarget) + { + Undo.RecordObject(audioMixerEffectController, "Clear Send target"); + audioMixerEffectController.sendTarget = null; + } + } + } + } + private static Dictionary BuildTemporaryGraph(List allGroups, AudioMixerGroupController groupWhoseEffectIsChanged, AudioMixerEffectController effectWhoseTargetIsChanged, AudioMixerEffectController targetToTest, AudioMixerGroupController modifiedGroup1, List modifiedGroupEffects1, AudioMixerGroupController modifiedGroup2, List modifiedGroupEffects2) + { + Dictionary dictionary = new Dictionary(); + foreach (AudioMixerGroupController current in allGroups) + { + dictionary[current] = new AudioMixerController.ConnectionNode + { + group = current, + effect = null + }; + object obj = current; + List list = (!(current == modifiedGroup1)) ? ((!(current == modifiedGroup2)) ? current.effects.ToList() : modifiedGroupEffects2) : modifiedGroupEffects1; + foreach (AudioMixerEffectController current2 in list) + { + if (!dictionary.ContainsKey(current2)) + { + dictionary[current2] = new AudioMixerController.ConnectionNode(); + } + dictionary[current2].group = current; + dictionary[current2].effect = current2; + if (!dictionary[obj].targets.Contains(current2)) + { + dictionary[obj].targets.Add(current2); + } + AudioMixerEffectController audioMixerEffectController = (!(current == groupWhoseEffectIsChanged) || !(effectWhoseTargetIsChanged == current2)) ? current2.sendTarget : targetToTest; + if (audioMixerEffectController != null) + { + if (!dictionary.ContainsKey(audioMixerEffectController)) + { + dictionary[audioMixerEffectController] = new AudioMixerController.ConnectionNode(); + dictionary[audioMixerEffectController].group = current; + dictionary[audioMixerEffectController].effect = audioMixerEffectController; + } + if (!dictionary[current2].targets.Contains(audioMixerEffectController)) + { + dictionary[current2].targets.Add(audioMixerEffectController); + } + } + obj = current2; + } + dictionary[current].groupTail = obj; + } + return dictionary; + } + private static void ListTemporaryGraph(Dictionary graph) + { + Debug.Log("Listing temporary graph:"); + int num = 0; + foreach (KeyValuePair current in graph) + { + Debug.Log(string.Format("Node {0}: {1}", num++, current.Value.GetDisplayString())); + int num2 = 0; + foreach (object current2 in current.Value.targets) + { + Debug.Log(string.Format(" Target {0}: {1}", num2++, graph[current2].GetDisplayString())); + } + } + } + private static bool CheckForCycle(object curr, Dictionary graph, List identifiedLoop) + { + AudioMixerController.ConnectionNode connectionNode = graph[curr]; + if (connectionNode.visited) + { + if (identifiedLoop != null) + { + identifiedLoop.Clear(); + identifiedLoop.Add(connectionNode); + } + return true; + } + connectionNode.visited = true; + foreach (object current in connectionNode.targets) + { + if (AudioMixerController.CheckForCycle(current, graph, identifiedLoop)) + { + connectionNode.visited = false; + if (identifiedLoop != null) + { + identifiedLoop.Add(connectionNode); + } + return true; + } + } + connectionNode.visited = false; + return false; + } + public static bool DoesTheTemporaryGraphHaveAnyCycles(List allGroups, List identifiedLoop, Dictionary graph) + { + foreach (AudioMixerGroupController current in allGroups) + { + if (AudioMixerController.CheckForCycle(current, graph, identifiedLoop)) + { + if (identifiedLoop != null) + { + AudioMixerController.ConnectionNode connectionNode = identifiedLoop[0]; + int i = 1; + while (i < identifiedLoop.Count) + { + if (identifiedLoop[i++] == connectionNode) + { + break; + } + } + identifiedLoop.RemoveRange(i, identifiedLoop.Count - i); + identifiedLoop.Reverse(); + } + return true; + } + } + return false; + } + public static bool WillChangeOfEffectTargetCauseFeedback(List allGroups, AudioMixerGroupController groupWhoseEffectIsChanged, int effectWhoseTargetIsChanged, AudioMixerEffectController targetToTest, List identifiedLoop) + { + Dictionary dictionary = AudioMixerController.BuildTemporaryGraph(allGroups, groupWhoseEffectIsChanged, groupWhoseEffectIsChanged.effects[effectWhoseTargetIsChanged], targetToTest, null, null, null, null); + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerGroupController[] children = current.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController key = children[i]; + object groupTail = dictionary[key].groupTail; + if (!dictionary[groupTail].targets.Contains(current)) + { + dictionary[groupTail].targets.Add(current); + } + } + } + return AudioMixerController.DoesTheTemporaryGraphHaveAnyCycles(allGroups, identifiedLoop, dictionary); + } + public static bool WillModificationOfTopologyCauseFeedback(List allGroups, List groupsToBeMoved, AudioMixerGroupController newParentForMovedGroups, List identifiedLoop) + { + Dictionary dictionary = AudioMixerController.BuildTemporaryGraph(allGroups, null, null, null, null, null, null, null); + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerGroupController[] children = current.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController audioMixerGroupController = children[i]; + AudioMixerGroupController item = (!groupsToBeMoved.Contains(audioMixerGroupController)) ? current : newParentForMovedGroups; + object groupTail = dictionary[audioMixerGroupController].groupTail; + if (!dictionary[groupTail].targets.Contains(item)) + { + dictionary[groupTail].targets.Add(item); + } + } + } + return AudioMixerController.DoesTheTemporaryGraphHaveAnyCycles(allGroups, identifiedLoop, dictionary); + } + public static bool WillMovingEffectCauseFeedback(List allGroups, AudioMixerGroupController sourceGroup, int sourceIndex, AudioMixerGroupController targetGroup, int targetIndex, List identifiedLoop) + { + Dictionary dictionary; + if (sourceGroup == targetGroup) + { + List modifiedGroupEffects = sourceGroup.effects.ToList(); + if (!AudioMixerController.MoveEffect(ref modifiedGroupEffects, sourceIndex, ref modifiedGroupEffects, targetIndex)) + { + return false; + } + dictionary = AudioMixerController.BuildTemporaryGraph(allGroups, null, null, null, sourceGroup, modifiedGroupEffects, null, null); + } + else + { + List modifiedGroupEffects2 = sourceGroup.effects.ToList(); + List modifiedGroupEffects3 = targetGroup.effects.ToList(); + if (!AudioMixerController.MoveEffect(ref modifiedGroupEffects2, sourceIndex, ref modifiedGroupEffects3, targetIndex)) + { + return false; + } + dictionary = AudioMixerController.BuildTemporaryGraph(allGroups, null, null, null, sourceGroup, modifiedGroupEffects2, targetGroup, modifiedGroupEffects3); + } + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerGroupController[] children = current.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController key = children[i]; + object groupTail = dictionary[key].groupTail; + if (!dictionary[groupTail].targets.Contains(current)) + { + dictionary[groupTail].targets.Add(current); + } + } + } + return AudioMixerController.DoesTheTemporaryGraphHaveAnyCycles(allGroups, identifiedLoop, dictionary); + } + public static float DbToLin(float x) + { + if (x < AudioMixerController.kMinVolume) + { + return 0f; + } + return Mathf.Pow(10f, x * 0.05f); + } + public void CloneViewFromCurrent() + { + Undo.RecordObject(this, "Create view"); + List list = new List(this.views); + list.Add(new MixerGroupView + { + name = this.views[this.currentViewIndex].name + " - Copy", + guids = this.views[this.currentViewIndex].guids + }); + this.views = list.ToArray(); + this.currentViewIndex = list.Count - 1; + } + public void DeleteView(int index) + { + Undo.RecordObject(this, "Delete view"); + List list = new List(this.views); + list.RemoveAt(index); + this.views = list.ToArray(); + int index2 = Mathf.Clamp(this.currentViewIndex, 0, list.Count - 1); + this.ForceSetView(index2); + } + public void SetView(int index) + { + if (this.currentViewIndex != index) + { + this.ForceSetView(index); + } + } + public void SanitizeGroupViews() + { + List allGroups = this.GetAllAudioGroupsSlow(); + MixerGroupView[] views = this.views; + for (int i = 0; i < views.Length; i++) + { + views[i].guids = ( + from x in views[i].guids + from y in allGroups + select new + { + x, + y + } into <>__TranspIdent0 + where <>__TranspIdent0.y.groupID == <>__TranspIdent0.x + select <>__TranspIdent0.x).ToArray(); + } + this.views = views.ToArray(); + } + public void ForceSetView(int index) + { + this.currentViewIndex = index; + this.SanitizeGroupViews(); + } + public void AddGroupToCurrentView(AudioMixerGroupController group) + { + MixerGroupView[] views = this.views; + List list = views[this.currentViewIndex].guids.ToList(); + list.Add(group.groupID); + views[this.currentViewIndex].guids = list.ToArray(); + this.views = views.ToArray(); + } + public void SetCurrentViewVisibility(GUID[] guids) + { + MixerGroupView[] views = this.views; + views[this.currentViewIndex].guids = guids; + this.views = views.ToArray(); + this.SanitizeGroupViews(); + } + public AudioMixerGroupController[] GetCurrentViewGroupList() + { + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + MixerGroupView view = this.views[this.currentViewIndex]; + return ( + from g in allAudioGroupsSlow + where view.guids.Contains(g.groupID) + select g).ToArray(); + } + public static float VolumeToScreenMapping(float value, float screenRange, bool forward) + { + float num = AudioMixerController.GetVolumeSplitPoint() * screenRange; + float num2 = screenRange - num; + if (forward) + { + return (value <= 0f) ? (Mathf.Pow(value / AudioMixerController.kMinVolume, 1f / AudioMixerController.kVolumeWarp) * num2 + num) : (num - Mathf.Pow(value / AudioMixerController.GetMaxVolume(), 1f / AudioMixerController.kVolumeWarp) * num); + } + return (value >= num) ? (Mathf.Pow((value - num) / num2, AudioMixerController.kVolumeWarp) * AudioMixerController.kMinVolume) : (Mathf.Pow(1f - value / num, AudioMixerController.kVolumeWarp) * AudioMixerController.GetMaxVolume()); + } + public void OnUnitySelectionChanged() + { + List allAudioGroupsSlow = this.GetAllAudioGroupsSlow(); + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(AudioMixerGroupController), SelectionMode.Deep); + this.m_CachedSelection = allAudioGroupsSlow.Intersect( + from g in filtered + select (AudioMixerGroupController)g).ToList(); + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioMixerEffectController.cs b/UnityEditor/UnityEditor.Audio/AudioMixerEffectController.cs new file mode 100644 index 00000000..90fb0d52 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioMixerEffectController.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Audio +{ + internal sealed class AudioMixerEffectController : UnityEngine.Object + { + private int m_LastCachedGroupDisplayNameID; + private string m_DisplayName; + public extern GUID effectID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string effectName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AudioMixerEffectController sendTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool enableWetMix + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bypass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AudioMixerEffectController(string name) + { + AudioMixerEffectController.Internal_CreateAudioMixerEffectController(this, name); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAudioMixerEffectController(AudioMixerEffectController mono, string name); + public bool IsSend() + { + return this.effectName == "Send"; + } + public bool IsReceive() + { + return this.effectName == "Receive"; + } + public bool IsDuckVolume() + { + return this.effectName == "Duck Volume"; + } + public bool IsAttenuation() + { + return this.effectName == "Attenuation"; + } + public bool DisallowsBypass() + { + return this.IsSend() || this.IsReceive() || this.IsDuckVolume() || this.IsAttenuation(); + } + public void ClearCachedDisplayName() + { + this.m_DisplayName = null; + } + public string GetDisplayString(Dictionary effectMap) + { + AudioMixerGroupController audioMixerGroupController = effectMap[this]; + if (audioMixerGroupController.GetInstanceID() != this.m_LastCachedGroupDisplayNameID || this.m_DisplayName == null) + { + this.m_DisplayName = audioMixerGroupController.GetDisplayString() + AudioMixerController.s_GroupEffectDisplaySeperator + AudioMixerController.FixNameForPopupMenu(this.effectName); + this.m_LastCachedGroupDisplayNameID = audioMixerGroupController.GetInstanceID(); + } + return this.m_DisplayName; + } + public string GetSendTargetDisplayString(Dictionary effectMap) + { + return (!(this.sendTarget != null)) ? string.Empty : this.sendTarget.GetDisplayString(effectMap); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PreallocateGUIDs(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern GUID GetGUIDForMixLevel(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetValueForMixLevel(AudioMixerController controller, AudioMixerSnapshotController snapshot); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetValueForMixLevel(AudioMixerController controller, AudioMixerSnapshotController snapshot, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern GUID GetGUIDForParameter(string parameterName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetValueForParameter(AudioMixerController controller, AudioMixerSnapshotController snapshot, string parameterName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetValueForParameter(AudioMixerController controller, AudioMixerSnapshotController snapshot, string parameterName, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetFloatBuffer(AudioMixerController controller, string name, out float[] data, int numsamples); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetCPUUsage(AudioMixerController controller); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool ContainsParameterGUID(GUID guid); + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioMixerEffectPlugin.cs b/UnityEditor/UnityEditor.Audio/AudioMixerEffectPlugin.cs new file mode 100644 index 00000000..f9fc9c5b --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioMixerEffectPlugin.cs @@ -0,0 +1,53 @@ +using System; +using UnityEngine; +namespace UnityEditor.Audio +{ + public class AudioMixerEffectPlugin : IAudioEffectPlugin + { + internal AudioMixerController m_Controller; + internal AudioMixerEffectController m_Effect; + internal MixerParameterDefinition[] m_ParamDefs; + public override bool SetFloatParameter(string name, float value) + { + this.m_Effect.SetValueForParameter(this.m_Controller, this.m_Controller.TargetSnapshot, name, value); + return true; + } + public override bool GetFloatParameter(string name, out float value) + { + value = this.m_Effect.GetValueForParameter(this.m_Controller, this.m_Controller.TargetSnapshot, name); + return true; + } + public override bool GetFloatParameterInfo(string name, out float minRange, out float maxRange, out float defaultValue) + { + MixerParameterDefinition[] paramDefs = this.m_ParamDefs; + for (int i = 0; i < paramDefs.Length; i++) + { + MixerParameterDefinition mixerParameterDefinition = paramDefs[i]; + if (mixerParameterDefinition.name == name) + { + minRange = mixerParameterDefinition.minRange; + maxRange = mixerParameterDefinition.maxRange; + defaultValue = mixerParameterDefinition.defaultValue; + return true; + } + } + minRange = 0f; + maxRange = 1f; + defaultValue = 0.5f; + return false; + } + public override bool GetFloatBuffer(string name, out float[] data, int numsamples) + { + this.m_Effect.GetFloatBuffer(this.m_Controller, name, out data, numsamples); + return true; + } + public override int GetSampleRate() + { + return AudioSettings.outputSampleRate; + } + public override bool IsPluginEditableAndEnabled() + { + return AudioMixerController.EditingTargetSnapshot() && !this.m_Effect.bypass; + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioMixerGroupController.cs b/UnityEditor/UnityEditor.Audio/AudioMixerGroupController.cs new file mode 100644 index 00000000..756fae49 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioMixerGroupController.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Audio; +namespace UnityEditor.Audio +{ + internal sealed class AudioMixerGroupController : AudioMixerGroup + { + public extern GUID groupID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int userColorIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerController controller + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AudioMixerGroupController[] children + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern AudioMixerEffectController[] effects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool mute + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool solo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool bypassEffects + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public AudioMixerGroupController(AudioMixer owner) + { + AudioMixerGroupController.Internal_CreateAudioMixerGroupController(this, owner); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAudioMixerGroupController(AudioMixerGroupController mono, AudioMixer owner); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void PreallocateGUIDs(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern GUID GetGUIDForVolume(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetValueForVolume(AudioMixerController controller, AudioMixerSnapshotController snapshot); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetValueForVolume(AudioMixerController controller, AudioMixerSnapshotController snapshot, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern GUID GetGUIDForPitch(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetValueForPitch(AudioMixerController controller, AudioMixerSnapshotController snapshot); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetValueForPitch(AudioMixerController controller, AudioMixerSnapshotController snapshot, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool HasDependentMixers(); + public void InsertEffect(AudioMixerEffectController effect, int index) + { + List list = new List(this.effects); + list.Add(null); + for (int i = list.Count - 1; i > index; i--) + { + list[i] = list[i - 1]; + } + list[index] = effect; + this.effects = list.ToArray(); + } + public bool HasAttenuation() + { + AudioMixerEffectController[] effects = this.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (audioMixerEffectController.IsAttenuation()) + { + return true; + } + } + return false; + } + public void DumpHierarchy(string title, int level) + { + if (title != string.Empty) + { + Console.WriteLine(title); + } + string str = string.Empty; + int num = level; + while (num-- > 0) + { + str += " "; + } + Console.WriteLine(str + "name=" + base.name); + str += " "; + AudioMixerEffectController[] effects = this.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + Console.WriteLine(str + "effect=" + audioMixerEffectController.ToString()); + } + AudioMixerGroupController[] children = this.children; + for (int j = 0; j < children.Length; j++) + { + AudioMixerGroupController audioMixerGroupController = children[j]; + audioMixerGroupController.DumpHierarchy(string.Empty, level + 1); + } + } + public string GetDisplayString() + { + return base.name; + } + public override string ToString() + { + return base.name; + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioMixerSnapshotController.cs b/UnityEditor/UnityEditor.Audio/AudioMixerSnapshotController.cs new file mode 100644 index 00000000..0b28bfb7 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioMixerSnapshotController.cs @@ -0,0 +1,58 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Audio; +namespace UnityEditor.Audio +{ + internal sealed class AudioMixerSnapshotController : AudioMixerSnapshot + { + public extern GUID snapshotID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public AudioMixerSnapshotController(AudioMixer owner) + { + AudioMixerSnapshotController.Internal_CreateAudioMixerSnapshotController(this, owner); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateAudioMixerSnapshotController(AudioMixerSnapshotController mono, AudioMixer owner); + public void SetValue(GUID guid, float value) + { + AudioMixerSnapshotController.INTERNAL_CALL_SetValue(this, guid, value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetValue(AudioMixerSnapshotController self, GUID guid, float value); + public bool GetValue(GUID guid, out float value) + { + return AudioMixerSnapshotController.INTERNAL_CALL_GetValue(this, guid, out value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_GetValue(AudioMixerSnapshotController self, GUID guid, out float value); + public void SetTransitionTypeOverride(GUID guid, ParameterTransitionType type) + { + AudioMixerSnapshotController.INTERNAL_CALL_SetTransitionTypeOverride(this, guid, type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetTransitionTypeOverride(AudioMixerSnapshotController self, GUID guid, ParameterTransitionType type); + public bool GetTransitionTypeOverride(GUID guid, out ParameterTransitionType type) + { + return AudioMixerSnapshotController.INTERNAL_CALL_GetTransitionTypeOverride(this, guid, out type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_GetTransitionTypeOverride(AudioMixerSnapshotController self, GUID guid, out ParameterTransitionType type); + public void ClearTransitionTypeOverride(GUID guid) + { + AudioMixerSnapshotController.INTERNAL_CALL_ClearTransitionTypeOverride(this, guid); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearTransitionTypeOverride(AudioMixerSnapshotController self, GUID guid); + } +} diff --git a/UnityEditor/UnityEditor.Audio/AudioParameterPath.cs b/UnityEditor/UnityEditor.Audio/AudioParameterPath.cs new file mode 100644 index 00000000..5a9625eb --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/AudioParameterPath.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Audio +{ + internal abstract class AudioParameterPath + { + public GUID parameter; + public abstract string ResolveStringPath(bool getOnlyBasePath); + } +} diff --git a/UnityEditor/UnityEditor.Audio/ChangedExposedParameterHandler.cs b/UnityEditor/UnityEditor.Audio/ChangedExposedParameterHandler.cs new file mode 100644 index 00000000..a8813f92 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/ChangedExposedParameterHandler.cs @@ -0,0 +1,5 @@ +using System; +namespace UnityEditor.Audio +{ + internal delegate void ChangedExposedParameterHandler(); +} diff --git a/UnityEditor/UnityEditor.Audio/ExposedAudioParameter.cs b/UnityEditor/UnityEditor.Audio/ExposedAudioParameter.cs new file mode 100644 index 00000000..1f8c4a11 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/ExposedAudioParameter.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Audio +{ + internal struct ExposedAudioParameter + { + public GUID guid; + public string name; + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerEffectDefinition.cs b/UnityEditor/UnityEditor.Audio/MixerEffectDefinition.cs new file mode 100644 index 00000000..4af1aa64 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerEffectDefinition.cs @@ -0,0 +1,29 @@ +using System; +namespace UnityEditor.Audio +{ + internal class MixerEffectDefinition + { + private readonly string m_EffectName; + private readonly MixerParameterDefinition[] m_Parameters; + public string name + { + get + { + return this.m_EffectName; + } + } + public MixerParameterDefinition[] parameters + { + get + { + return this.m_Parameters; + } + } + public MixerEffectDefinition(string name, MixerParameterDefinition[] parameters) + { + this.m_EffectName = name; + this.m_Parameters = new MixerParameterDefinition[parameters.Length]; + Array.Copy(parameters, this.m_Parameters, parameters.Length); + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerEffectDefinitionReloader.cs b/UnityEditor/UnityEditor.Audio/MixerEffectDefinitionReloader.cs new file mode 100644 index 00000000..5c6db7a8 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerEffectDefinitionReloader.cs @@ -0,0 +1,17 @@ +using System; +namespace UnityEditor.Audio +{ + [InitializeOnLoad] + internal static class MixerEffectDefinitionReloader + { + static MixerEffectDefinitionReloader() + { + MixerEffectDefinitions.Refresh(); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(MixerEffectDefinitionReloader.OnProjectChanged)); + } + private static void OnProjectChanged() + { + MixerEffectDefinitions.Refresh(); + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerEffectDefinitions.cs b/UnityEditor/UnityEditor.Audio/MixerEffectDefinitions.cs new file mode 100644 index 00000000..18e39d96 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerEffectDefinitions.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Audio +{ + internal sealed class MixerEffectDefinitions + { + private static readonly List s_MixerEffectDefinitions = new List(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void ClearDefinitionsRuntime(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void AddDefinitionRuntime(string name, MixerParameterDefinition[] parameters); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAudioEffectNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern MixerParameterDefinition[] GetAudioEffectParameterDesc(string effectName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool EffectCanBeSidechainTarget(AudioMixerEffectController effect); + public static void Refresh() + { + MixerEffectDefinitions.ClearDefinitions(); + MixerEffectDefinitions.RegisterAudioMixerEffect("Attenuation", new MixerParameterDefinition[0]); + MixerEffectDefinitions.RegisterAudioMixerEffect("Send", new MixerParameterDefinition[0]); + MixerEffectDefinitions.RegisterAudioMixerEffect("Receive", new MixerParameterDefinition[0]); + MixerParameterDefinition[] array = new MixerParameterDefinition[] + { + new MixerParameterDefinition + { + name = "Threshold", + units = "dB", + displayScale = 1f, + displayExponent = 1f, + minRange = -80f, + defaultValue = -10f, + description = "Threshold of side-chain level detector" + }, + new MixerParameterDefinition + { + name = "Ratio", + units = "%", + displayScale = 100f, + displayExponent = 1f, + minRange = 0.2f, + maxRange = 10f, + defaultValue = 2f, + description = "Ratio of compression applied when side-chain signal exceeds threshold" + }, + new MixerParameterDefinition + { + name = "Attack Time", + units = "ms", + displayScale = 1000f, + displayExponent = 3f, + maxRange = 10f, + defaultValue = 0.1f, + description = "Level detector attack time" + }, + new MixerParameterDefinition + { + name = "Release Time", + units = "ms", + displayScale = 1000f, + displayExponent = 3f, + maxRange = 10f, + defaultValue = 0.1f, + description = "Level detector release time" + }, + new MixerParameterDefinition + { + name = "Make-up Gain", + units = "dB", + displayScale = 1f, + displayExponent = 1f, + minRange = -80f, + maxRange = 40f, + description = "Make-up gain" + }, + new MixerParameterDefinition + { + name = "Knee", + units = "dB", + displayScale = 1f, + displayExponent = 1f, + maxRange = 50f, + defaultValue = 10f, + description = "Sharpness of compression curve knee" + }, + new MixerParameterDefinition + { + name = "Sidechain Mix", + units = "%", + displayScale = 100f, + displayExponent = 1f, + maxRange = 1f, + defaultValue = 1f, + description = "Sidechain/source mix. If set to 100% the compressor detects level entirely from sidechain signal." + } + }; + MixerEffectDefinitions.RegisterAudioMixerEffect("Duck Volume", array); + MixerEffectDefinitions.AddDefinitionRuntime("Duck Volume", array); + string[] audioEffectNames = MixerEffectDefinitions.GetAudioEffectNames(); + string[] array2 = audioEffectNames; + for (int i = 0; i < array2.Length; i++) + { + string text = array2[i]; + MixerParameterDefinition[] audioEffectParameterDesc = MixerEffectDefinitions.GetAudioEffectParameterDesc(text); + MixerEffectDefinitions.RegisterAudioMixerEffect(text, audioEffectParameterDesc); + } + } + public static bool EffectExists(string name) + { + foreach (MixerEffectDefinition current in MixerEffectDefinitions.s_MixerEffectDefinitions) + { + if (current.name == name) + { + return true; + } + } + return false; + } + public static string[] GetEffectList() + { + string[] array = new string[MixerEffectDefinitions.s_MixerEffectDefinitions.Count]; + for (int i = 0; i < MixerEffectDefinitions.s_MixerEffectDefinitions.Count; i++) + { + array[i] = MixerEffectDefinitions.s_MixerEffectDefinitions[i].name; + } + return array; + } + public static void ClearDefinitions() + { + MixerEffectDefinitions.s_MixerEffectDefinitions.Clear(); + MixerEffectDefinitions.ClearDefinitionsRuntime(); + } + public static MixerParameterDefinition[] GetEffectParameters(string effect) + { + foreach (MixerEffectDefinition current in MixerEffectDefinitions.s_MixerEffectDefinitions) + { + if (current.name == effect) + { + return current.parameters; + } + } + return new MixerParameterDefinition[0]; + } + public static bool RegisterAudioMixerEffect(string name, MixerParameterDefinition[] definitions) + { + foreach (MixerEffectDefinition current in MixerEffectDefinitions.s_MixerEffectDefinitions) + { + if (current.name == name) + { + return false; + } + } + MixerEffectDefinition item = new MixerEffectDefinition(name, definitions); + MixerEffectDefinitions.s_MixerEffectDefinitions.Add(item); + MixerEffectDefinitions.ClearDefinitionsRuntime(); + foreach (MixerEffectDefinition current2 in MixerEffectDefinitions.s_MixerEffectDefinitions) + { + MixerEffectDefinitions.AddDefinitionRuntime(current2.name, current2.parameters); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerEffectParameter.cs b/UnityEditor/UnityEditor.Audio/MixerEffectParameter.cs new file mode 100644 index 00000000..b7eab7af --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerEffectParameter.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Audio +{ + internal struct MixerEffectParameter + { + public string parameterName; + public GUID GUID; + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerGroupControllerCompareByName.cs b/UnityEditor/UnityEditor.Audio/MixerGroupControllerCompareByName.cs new file mode 100644 index 00000000..ccb85c0b --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerGroupControllerCompareByName.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor.Audio +{ + internal class MixerGroupControllerCompareByName : IComparer + { + public int Compare(AudioMixerGroupController x, AudioMixerGroupController y) + { + return StringComparer.InvariantCultureIgnoreCase.Compare(x.GetDisplayString(), y.GetDisplayString()); + } + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerGroupView.cs b/UnityEditor/UnityEditor.Audio/MixerGroupView.cs new file mode 100644 index 00000000..c2092ebf --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerGroupView.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Audio +{ + internal struct MixerGroupView + { + public GUID[] guids; + public string name; + } +} diff --git a/UnityEditor/UnityEditor.Audio/MixerParameterDefinition.cs b/UnityEditor/UnityEditor.Audio/MixerParameterDefinition.cs new file mode 100644 index 00000000..f88bdc91 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/MixerParameterDefinition.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Audio +{ + internal struct MixerParameterDefinition + { + public string name; + public string description; + public string units; + public float displayScale; + public float displayExponent; + public float minRange; + public float maxRange; + public float defaultValue; + } +} diff --git a/UnityEditor/UnityEditor.Audio/ParameterTransitionType.cs b/UnityEditor/UnityEditor.Audio/ParameterTransitionType.cs new file mode 100644 index 00000000..121e50d7 --- /dev/null +++ b/UnityEditor/UnityEditor.Audio/ParameterTransitionType.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor.Audio +{ + internal enum ParameterTransitionType + { + Lerp, + Smoothstep, + Squared, + SquareRoot, + BrickwallStart, + BrickwallEnd + } +} diff --git a/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs b/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs index 113a033e..ff05d087 100644 --- a/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs +++ b/UnityEditor/UnityEditor.Callbacks/PostProcessSceneAttribute.cs @@ -3,13 +3,28 @@ namespace UnityEditor.Callbacks { public sealed class PostProcessSceneAttribute : CallbackOrderAttribute { + private int m_version; + internal int version + { + get + { + return this.m_version; + } + } public PostProcessSceneAttribute() { this.m_CallbackOrder = 1; + this.m_version = 0; } public PostProcessSceneAttribute(int callbackOrder) { this.m_CallbackOrder = callbackOrder; + this.m_version = 0; + } + public PostProcessSceneAttribute(int callbackOrder, int version) + { + this.m_CallbackOrder = callbackOrder; + this.m_version = version; } } } diff --git a/UnityEditor/UnityEditor.Hardware/DevDevice.cs b/UnityEditor/UnityEditor.Hardware/DevDevice.cs new file mode 100644 index 00000000..b3e256d8 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/DevDevice.cs @@ -0,0 +1,54 @@ +using System; +namespace UnityEditor.Hardware +{ + public struct DevDevice + { + public readonly string id; + public readonly string name; + public readonly string type; + public readonly string module; + public readonly DevDeviceState state; + public readonly DevDeviceFeatures features; + public bool isConnected + { + get + { + return this.state == DevDeviceState.Connected; + } + } + public static DevDevice none + { + get + { + return new DevDevice("None", "None", "none", "internal", DevDeviceState.Disconnected, DevDeviceFeatures.None); + } + } + public DevDevice(string id, string name, string type, string module, DevDeviceState state, DevDeviceFeatures features) + { + this.id = id; + this.name = name; + this.type = type; + this.module = module; + this.state = state; + this.features = features; + } + public override string ToString() + { + return string.Concat(new object[] + { + this.name, + " (id:", + this.id, + ", type: ", + this.type, + ", module: ", + this.module, + ", state: ", + this.state, + ", features: ", + this.features, + ")" + }); + } + } +} diff --git a/UnityEditor/UnityEditor.Hardware/DevDeviceFeatures.cs b/UnityEditor/UnityEditor.Hardware/DevDeviceFeatures.cs new file mode 100644 index 00000000..d5df9365 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/DevDeviceFeatures.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.Hardware +{ + [Flags] + public enum DevDeviceFeatures + { + None = 0, + PlayerConnection = 1, + RemoteConnection = 2 + } +} diff --git a/UnityEditor/UnityEditor.Hardware/DevDeviceList.cs b/UnityEditor/UnityEditor.Hardware/DevDeviceList.cs new file mode 100644 index 00000000..9daa0053 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/DevDeviceList.cs @@ -0,0 +1,56 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Hardware +{ + public sealed class DevDeviceList + { + public delegate void OnChangedHandler(); + public static event DevDeviceList.OnChangedHandler Changed + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + DevDeviceList.Changed = (DevDeviceList.OnChangedHandler)Delegate.Combine(DevDeviceList.Changed, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + DevDeviceList.Changed = (DevDeviceList.OnChangedHandler)Delegate.Remove(DevDeviceList.Changed, value); + } + } + public static void OnChanged() + { + if (DevDeviceList.Changed != null) + { + DevDeviceList.Changed(); + } + } + public static bool FindDevice(string deviceId, out DevDevice device) + { + DevDevice[] devices = DevDeviceList.GetDevices(); + for (int i = 0; i < devices.Length; i++) + { + DevDevice devDevice = devices[i]; + if (devDevice.id == deviceId) + { + device = devDevice; + return true; + } + } + device = default(DevDevice); + return false; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern DevDevice[] GetDevices(); + internal static void Update(string target, DevDevice[] devices) + { + DevDeviceList.UpdateInternal(target, devices); + DevDeviceList.OnChanged(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateInternal(string target, DevDevice[] devices); + } +} diff --git a/UnityEditor/UnityEditor.Hardware/DevDeviceState.cs b/UnityEditor/UnityEditor.Hardware/DevDeviceState.cs new file mode 100644 index 00000000..4923a985 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/DevDeviceState.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Hardware +{ + public enum DevDeviceState + { + Disconnected, + Connected + } +} diff --git a/UnityEditor/UnityEditor.Hardware/Usb.cs b/UnityEditor/UnityEditor.Hardware/Usb.cs new file mode 100644 index 00000000..6913bd05 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/Usb.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEditor.Hardware +{ + public sealed class Usb + { + public delegate void OnDevicesChangedHandler(UsbDevice[] devices); + public static event Usb.OnDevicesChangedHandler DevicesChanged + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + Usb.DevicesChanged = (Usb.OnDevicesChangedHandler)Delegate.Combine(Usb.DevicesChanged, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + Usb.DevicesChanged = (Usb.OnDevicesChangedHandler)Delegate.Remove(Usb.DevicesChanged, value); + } + } + public static void OnDevicesChanged(UsbDevice[] devices) + { + if (Usb.DevicesChanged != null && devices != null) + { + Usb.DevicesChanged(devices); + } + } + } +} diff --git a/UnityEditor/UnityEditor.Hardware/UsbDevice.cs b/UnityEditor/UnityEditor.Hardware/UsbDevice.cs new file mode 100644 index 00000000..5f2289e6 --- /dev/null +++ b/UnityEditor/UnityEditor.Hardware/UsbDevice.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEditor.Hardware +{ + public struct UsbDevice + { + public readonly int vendorId; + public readonly int productId; + public readonly int revision; + public readonly string udid; + public readonly string name; + public override string ToString() + { + return string.Concat(new string[] + { + this.name, + " (udid:", + this.udid, + ", vid: ", + this.vendorId.ToString("X4"), + ", pid: ", + this.productId.ToString("X4"), + ", rev: ", + this.revision.ToString("X4"), + ")" + }); + } + } +} diff --git a/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs deleted file mode 100644 index 6fd74818..00000000 --- a/UnityEditor/UnityEditor.LinuxStandalone/LinuxStandaloneIl2CppPlatformProvider.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.IO; -using UnityEditorInternal; -namespace UnityEditor.LinuxStandalone -{ - internal class LinuxStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider - { - public bool platformHasPrecompiledLibIl2Cpp - { - get - { - return false; - } - } - public override bool emitNullChecks - { - get - { - return false; - } - } - public override bool enableStackTraces - { - get - { - return false; - } - } - public override string nativeLibraryFileName - { - get - { - return "libUserAssembly.so"; - } - } - public LinuxStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder) : base(target, Path.Combine(dataFolder, "Libraries")) - { - } - public override INativeCompiler CreateNativeCompiler() - { - BuildTarget target = this.target; - ICompilerSettings settings; - if (target != BuildTarget.StandaloneLinux) - { - if (target != BuildTarget.StandaloneLinux64) - { - throw new Exception("Not sure how to handle Linux universal yet..."); - } - settings = new GccCompilerSettingsx86_64(); - } - else - { - settings = new GccCompilerSettingsx86(); - } - return new GccCompiler(settings); - } - } -} diff --git a/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs b/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs index bb646684..21b2908c 100644 --- a/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs +++ b/UnityEditor/UnityEditor.Modules/DefaultPlayerSettingsEditorExtension.cs @@ -30,5 +30,15 @@ public virtual bool SupportsOrientation() public virtual void SplashSectionGUI() { } + public virtual void IconSectionGUI() + { + } + public virtual bool HasResolutionSection() + { + return false; + } + public virtual void ResolutionSectionGUI(float h, float midWidth, float maxWidth) + { + } } } diff --git a/UnityEditor/UnityEditor.Modules/DefaultPluginImporterExtension.cs b/UnityEditor/UnityEditor.Modules/DefaultPluginImporterExtension.cs new file mode 100644 index 00000000..1d83c8fd --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/DefaultPluginImporterExtension.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Text; +using UnityEngine; +namespace UnityEditor.Modules +{ + internal class DefaultPluginImporterExtension : IPluginImporterExtension + { + internal class Property + { + internal GUIContent name + { + get; + set; + } + internal string key + { + get; + set; + } + internal object defaultValue + { + get; + set; + } + internal Type type + { + get; + set; + } + internal string platformName + { + get; + set; + } + internal object value + { + get; + set; + } + internal Property(string name, string key, object defaultValue, string platformName) : this(new GUIContent(name), key, defaultValue, platformName) + { + } + internal Property(GUIContent name, string key, object defaultValue, string platformName) + { + this.name = name; + this.key = key; + this.defaultValue = defaultValue; + this.type = defaultValue.GetType(); + this.platformName = platformName; + } + internal virtual void Reset(PluginImporterInspector inspector) + { + string platformData = inspector.importer.GetPlatformData(this.platformName, this.key); + try + { + this.value = TypeDescriptor.GetConverter(this.type).ConvertFromString(platformData); + } + catch + { + this.value = this.defaultValue; + if (!string.IsNullOrEmpty(platformData)) + { + Debug.LogWarning(string.Concat(new object[] + { + "Failed to parse value ('", + platformData, + "') for ", + this.key, + ", platform: ", + this.platformName, + ", type: ", + this.type, + ". Default value will be set '", + this.defaultValue, + "'" + })); + } + } + } + internal virtual void Apply(PluginImporterInspector inspector) + { + inspector.importer.SetPlatformData(this.platformName, this.key, this.value.ToString()); + } + internal virtual void OnGUI(PluginImporterInspector inspector) + { + if (this.type == typeof(bool)) + { + this.value = EditorGUILayout.Toggle(this.name, (bool)this.value, new GUILayoutOption[0]); + } + else + { + if (this.type.IsEnum) + { + this.value = EditorGUILayout.EnumPopup(this.name, (Enum)this.value, new GUILayoutOption[0]); + } + else + { + if (this.type != typeof(string)) + { + throw new NotImplementedException("Don't know how to display value."); + } + this.value = EditorGUILayout.TextField(this.name, (string)this.value, new GUILayoutOption[0]); + } + } + } + } + protected bool hasModified; + protected DefaultPluginImporterExtension.Property[] properties; + internal bool propertiesRefreshed; + public DefaultPluginImporterExtension(DefaultPluginImporterExtension.Property[] properties) + { + this.properties = properties; + } + public virtual void ResetValues(PluginImporterInspector inspector) + { + this.hasModified = false; + this.RefreshProperties(inspector); + } + public virtual bool HasModified(PluginImporterInspector inspector) + { + return this.hasModified; + } + public virtual void Apply(PluginImporterInspector inspector) + { + if (!this.propertiesRefreshed) + { + return; + } + DefaultPluginImporterExtension.Property[] array = this.properties; + for (int i = 0; i < array.Length; i++) + { + DefaultPluginImporterExtension.Property property = array[i]; + property.Apply(inspector); + } + } + public virtual void OnEnable(PluginImporterInspector inspector) + { + this.RefreshProperties(inspector); + } + public virtual void OnDisable(PluginImporterInspector inspector) + { + } + public virtual void OnPlatformSettingsGUI(PluginImporterInspector inspector) + { + if (!this.propertiesRefreshed) + { + this.RefreshProperties(inspector); + } + EditorGUI.BeginChangeCheck(); + DefaultPluginImporterExtension.Property[] array = this.properties; + for (int i = 0; i < array.Length; i++) + { + DefaultPluginImporterExtension.Property property = array[i]; + property.OnGUI(inspector); + } + if (EditorGUI.EndChangeCheck()) + { + this.hasModified = true; + } + } + protected virtual void RefreshProperties(PluginImporterInspector inspector) + { + DefaultPluginImporterExtension.Property[] array = this.properties; + for (int i = 0; i < array.Length; i++) + { + DefaultPluginImporterExtension.Property property = array[i]; + property.Reset(inspector); + } + this.propertiesRefreshed = true; + } + public virtual string CalculateFinalPluginPath(string platformName, PluginImporter imp) + { + return Path.GetFileName(imp.assetPath); + } + protected Dictionary> GetCompatiblePlugins(string buildTargetName) + { + PluginImporter[] array = ( + from imp in PluginImporter.GetAllImporters() + where (imp.GetCompatibleWithPlatform(buildTargetName) || imp.GetCompatibleWithAnyPlatform()) && !string.IsNullOrEmpty(imp.assetPath) + select imp).ToArray(); + Dictionary> dictionary = new Dictionary>(); + PluginImporter[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + PluginImporter pluginImporter = array2[i]; + if (!string.IsNullOrEmpty(pluginImporter.assetPath)) + { + string text = this.CalculateFinalPluginPath(buildTargetName, pluginImporter); + if (!string.IsNullOrEmpty(text)) + { + List list = null; + if (!dictionary.TryGetValue(text, out list)) + { + list = new List(); + dictionary[text] = list; + } + list.Add(pluginImporter); + } + } + } + return dictionary; + } + public virtual bool CheckFileCollisions(string buildTargetName) + { + Dictionary> compatiblePlugins = this.GetCompatiblePlugins(buildTargetName); + bool flag = false; + StringBuilder stringBuilder = new StringBuilder(); + foreach (KeyValuePair> current in compatiblePlugins) + { + List value = current.Value; + if (value.Count != 1) + { + flag = true; + stringBuilder.AppendLine(string.Format("Plugin '{0}' is used from several locations:", Path.GetFileName(current.Key))); + foreach (PluginImporter current2 in value) + { + stringBuilder.AppendLine(" " + current2.assetPath + " would be copied to /" + current.Key.Replace("\\", "/")); + } + } + } + if (flag) + { + stringBuilder.AppendLine("Please fix plugin settings and try again."); + Debug.LogError(stringBuilder.ToString()); + } + return flag; + } + } +} diff --git a/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs b/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs index 128dab55..73bab252 100644 --- a/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs +++ b/UnityEditor/UnityEditor.Modules/IBuildPostprocessor.cs @@ -6,7 +6,10 @@ internal interface IBuildPostprocessor void LaunchPlayer(BuildLaunchPlayerArgs args); void PostProcess(BuildPostProcessArgs args); bool SupportsInstallInBuildFolder(); - string GetExtension(); + void PostProcessScriptsOnly(BuildPostProcessArgs args); + bool SupportsScriptsOnlyBuild(); + string GetScriptLayoutFileFromBuild(BuildOptions options, string installPath, string fileName); + string GetExtension(BuildTarget target, BuildOptions options); string[] FindPluginFilesToCopy(string basePluginFolder, out bool shouldRetainStructure); } } diff --git a/UnityEditor/UnityEditor.Modules/IBuildWindowExtension.cs b/UnityEditor/UnityEditor.Modules/IBuildWindowExtension.cs new file mode 100644 index 00000000..b19b8a26 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IBuildWindowExtension.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IBuildWindowExtension + { + void ShowPlatformBuildOptions(); + bool EnabledBuildButton(); + bool EnabledBuildAndRunButton(); + bool ShouldDrawScriptDebuggingCheckbox(); + bool ShouldDrawProfilerCheckbox(); + bool ShouldDrawDevelopmentPlayerCheckbox(); + bool ShouldDrawExplicitNullCheckbox(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/IDevice.cs b/UnityEditor/UnityEditor.Modules/IDevice.cs new file mode 100644 index 00000000..38c7a582 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IDevice.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IDevice + { + RemoteAddress StartRemoteSupport(); + void StopRemoteSupport(); + RemoteAddress StartPlayerConnectionSupport(); + void StopPlayerConnectionSupport(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs b/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs index 7c08d6c2..d2e7fbe0 100644 --- a/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs +++ b/UnityEditor/UnityEditor.Modules/IPlatformSupportModule.cs @@ -11,8 +11,21 @@ string JamTarget { get; } + string[] AssemblyReferencesForUserScripts + { + get; + } IBuildPostprocessor CreateBuildPostprocessor(); + IScriptingImplementations CreateScriptingImplementations(); ISettingEditorExtension CreateSettingsEditorExtension(); IPreferenceWindowExtension CreatePreferenceWindowExtension(); + IBuildWindowExtension CreateBuildWindowExtension(); + IPluginImporterExtension CreatePluginImporterExtension(); + IUserAssembliesValidator CreateUserAssembliesValidatorExtension(); + IDevice CreateDevice(string id); + void OnActivate(); + void OnDeactivate(); + void OnLoad(); + void OnUnload(); } } diff --git a/UnityEditor/UnityEditor.Modules/IPluginImporterExtension.cs b/UnityEditor/UnityEditor.Modules/IPluginImporterExtension.cs new file mode 100644 index 00000000..1fae959a --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IPluginImporterExtension.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IPluginImporterExtension + { + void ResetValues(PluginImporterInspector inspector); + bool HasModified(PluginImporterInspector inspector); + void Apply(PluginImporterInspector inspector); + void OnEnable(PluginImporterInspector inspector); + void OnDisable(PluginImporterInspector inspector); + void OnPlatformSettingsGUI(PluginImporterInspector inspector); + string CalculateFinalPluginPath(string buildTargetName, PluginImporter imp); + bool CheckFileCollisions(string buildTargetName); + } +} diff --git a/UnityEditor/UnityEditor.Modules/IScriptingImplementations.cs b/UnityEditor/UnityEditor.Modules/IScriptingImplementations.cs new file mode 100644 index 00000000..0d08768e --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IScriptingImplementations.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IScriptingImplementations + { + ScriptingImplementation[] Supported + { + get; + } + ScriptingImplementation[] Enabled + { + get; + } + } +} diff --git a/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs b/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs index 7b161981..9079f5f2 100644 --- a/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs +++ b/UnityEditor/UnityEditor.Modules/ISettingEditorExtension.cs @@ -11,5 +11,8 @@ internal interface ISettingEditorExtension void ConfigurationSectionGUI(); bool SupportsOrientation(); void SplashSectionGUI(); + void IconSectionGUI(); + bool HasResolutionSection(); + void ResolutionSectionGUI(float h, float midWidth, float maxWidth); } } diff --git a/UnityEditor/UnityEditor.Modules/IUserAssembliesValidator.cs b/UnityEditor/UnityEditor.Modules/IUserAssembliesValidator.cs new file mode 100644 index 00000000..97a67c75 --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/IUserAssembliesValidator.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor.Modules +{ + internal interface IUserAssembliesValidator + { + bool canRunInBackground + { + get; + } + void Validate(string[] userAssemblies); + void Cleanup(); + } +} diff --git a/UnityEditor/UnityEditor.Modules/ModuleManager.cs b/UnityEditor/UnityEditor.Modules/ModuleManager.cs index ec4a2b42..e64aacf4 100644 --- a/UnityEditor/UnityEditor.Modules/ModuleManager.cs +++ b/UnityEditor/UnityEditor.Modules/ModuleManager.cs @@ -6,6 +6,7 @@ using System.Reflection; using System.Text; using Unity.DataContract; +using UnityEditor.Hardware; using UnityEditor.Utils; using UnityEditorInternal; using UnityEngine; @@ -16,9 +17,13 @@ internal static class ModuleManager [NonSerialized] private static List s_PlatformModules; [NonSerialized] + private static bool s_PlatformModulesInitialized; + [NonSerialized] private static List s_EditorModules; [NonSerialized] private static IPackageManagerModule s_PackageManager; + [NonSerialized] + private static IPlatformSupportModule s_ActivePlatformModule; internal static IPackageManagerModule packageManager { get @@ -27,7 +32,7 @@ internal static IPackageManagerModule packageManager return ModuleManager.s_PackageManager; } } - private static List platformSupportModules + internal static IEnumerable platformSupportModules { get { @@ -50,6 +55,36 @@ private static List editorModules return ModuleManager.s_EditorModules; } } + static ModuleManager() + { + EditorUserBuildSettings.activeBuildTargetChanged = (Action)Delegate.Combine(EditorUserBuildSettings.activeBuildTargetChanged, new Action(ModuleManager.OnActiveBuildTargetChanged)); + } + private static void OnActiveBuildTargetChanged() + { + string targetStringFromBuildTarget = ModuleManager.GetTargetStringFromBuildTarget(EditorUserBuildSettings.activeBuildTarget); + ModuleManager.ChangeActivePlatformModuleTo(targetStringFromBuildTarget); + } + private static void DeactivateActivePlatformModule() + { + if (ModuleManager.s_ActivePlatformModule != null) + { + ModuleManager.s_ActivePlatformModule.OnDeactivate(); + ModuleManager.s_ActivePlatformModule = null; + } + } + private static void ChangeActivePlatformModuleTo(string target) + { + ModuleManager.DeactivateActivePlatformModule(); + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + ModuleManager.s_ActivePlatformModule = current; + current.OnActivate(); + break; + } + } + } internal static bool IsRegisteredModule(string file) { return ModuleManager.s_PackageManager != null && ModuleManager.s_PackageManager.GetType().Assembly.Location.NormalizePath() == file.NormalizePath(); @@ -70,7 +105,14 @@ internal static void Initialize() if (ModuleManager.s_PackageManager == null) { ModuleManager.RegisterPackageManager(); - ModuleManager.LoadUnityExtensions(); + if (ModuleManager.s_PackageManager != null) + { + ModuleManager.LoadUnityExtensions(); + } + else + { + UnityEngine.Debug.LogError("Failed to load package manager"); + } } } private static string CombinePaths(params string[] paths) @@ -90,7 +132,7 @@ private static string CombinePaths(params string[] paths) } return stringBuilder.ToString(); } - private static string RemapDllLocation(string dllLocation) + public static string RemapDllLocation(string dllLocation) { string fileName = Path.GetFileName(dllLocation); string directoryName = Path.GetDirectoryName(dllLocation); @@ -107,10 +149,6 @@ private static string RemapDllLocation(string dllLocation) return dllLocation; } private static void LoadUnityExtensions() - { - ModuleManager.LoadUnityExtensionsWithPM(); - } - private static void LoadUnityExtensionsWithPM() { foreach (Unity.DataContract.PackageInfo current in ModuleManager.s_PackageManager.unityExtensions) { @@ -129,13 +167,17 @@ from f in current.files string text = Path.Combine(current.basePath, current2.Key).NormalizePath(); if (!File.Exists(text)) { - UnityEngine.Debug.LogWarning(string.Format("Missing assembly \t{0} for {1}. Extension support may be incomplete.", current2.Key, current.name)); + UnityEngine.Debug.LogWarningFormat("Missing assembly \t{0} for {1}. Extension support may be incomplete.", new object[] + { + current2.Key, + current.name + }); } else { if (!string.IsNullOrEmpty(current2.Value.guid)) { - InternalEditorUtility.RegisterExtensionDll(text, current2.Value.guid); + InternalEditorUtility.RegisterExtensionDll(text.Replace('\\', '/'), current2.Value.guid); } else { @@ -148,8 +190,28 @@ from f in current.files } internal static void InitializePlatformSupportModules() { + if (ModuleManager.s_PlatformModulesInitialized) + { + Console.WriteLine("Platform modules already initialized, skipping"); + return; + } ModuleManager.Initialize(); ModuleManager.RegisterPlatformSupportModules(); + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + EditorUtility.LoadPlatformSupportModuleNativeDllInternal(current.TargetName); + current.OnLoad(); + } + ModuleManager.OnActiveBuildTargetChanged(); + ModuleManager.s_PlatformModulesInitialized = true; + } + internal static void ShutdownPlatformSupportModules() + { + ModuleManager.DeactivateActivePlatformModule(); + foreach (IPlatformSupportModule current in ModuleManager.s_PlatformModules) + { + current.OnUnload(); + } } internal static void Shutdown() { @@ -267,45 +329,62 @@ private static bool InitializePackageManager(Assembly assembly, Unity.DataContra foreach (Unity.DataContract.PackageInfo current in ModuleManager.s_PackageManager.playbackEngines) { BuildTarget buildTarget = BuildTarget.StandaloneWindows; - try + if (ModuleManager.TryParseBuildTarget(current.name, out buildTarget)) { - buildTarget = (BuildTarget)((int)Enum.Parse(typeof(BuildTarget), current.name)); - } - catch - { - UnityEngine.Debug.LogWarning(string.Format("Couldn't find build target for {0}", current.name)); - continue; - } - Console.WriteLine("Setting {0} v{1} for Unity v{2} to {3}", new object[] - { - buildTarget, - current.version, - current.unityVersion, - current.basePath - }); - foreach (KeyValuePair current2 in - from f in current.files - where f.Value.type == PackageFileType.Dll - select f) - { - string path = Path.Combine(current.basePath, current2.Key).NormalizePath(); - if (!File.Exists(path)) + Console.WriteLine("Setting {0} v{1} for Unity v{2} to {3}", new object[] { - UnityEngine.Debug.LogWarning(string.Format("Missing assembly \t{0} for {1}. Player support may be incomplete.", current.basePath, current.name)); - } - else + buildTarget, + current.version, + current.unityVersion, + current.basePath + }); + foreach (KeyValuePair current2 in + from f in current.files + where f.Value.type == PackageFileType.Dll + select f) { - InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); + string path = Path.Combine(current.basePath, current2.Key).NormalizePath(); + if (!File.Exists(path)) + { + UnityEngine.Debug.LogWarningFormat("Missing assembly \t{0} for {1}. Player support may be incomplete.", new object[] + { + current.basePath, + current.name + }); + } + else + { + InternalEditorUtility.SetupCustomDll(Path.GetFileName(location), location); + } } + BuildPipeline.SetPlaybackEngineDirectory(buildTarget, BuildOptions.None, current.basePath); + InternalEditorUtility.SetPlatformPath(current.basePath); + ModuleManager.s_PackageManager.LoadPackage(current); } - BuildPipeline.SetPlaybackEngineDirectory(buildTarget, BuildOptions.None, current.basePath); - InternalEditorUtility.SetPlatformPath(current.basePath); - ModuleManager.s_PackageManager.LoadPackage(current); } return true; } + private static bool TryParseBuildTarget(string targetString, out BuildTarget target) + { + target = BuildTarget.StandaloneWindows; + try + { + target = (BuildTarget)((int)Enum.Parse(typeof(BuildTarget), targetString)); + return true; + } + catch + { + UnityEngine.Debug.LogWarning(string.Format("Couldn't find build target for {0}", targetString)); + } + return false; + } private static void RegisterPlatformSupportModules() { + if (ModuleManager.s_PlatformModules != null) + { + Console.WriteLine("Modules already registered, not loading"); + return; + } Console.WriteLine("Registering platform support modules:"); Stopwatch stopwatch = Stopwatch.StartNew(); ModuleManager.s_PlatformModules = ModuleManager.RegisterModulesFromLoadedAssemblies(new Func>(ModuleManager.RegisterPlatformSupportModulesFromAssembly)).ToList(); @@ -352,6 +431,46 @@ internal static List GetJamTargets() } return list; } + private static IPlatformSupportModule FindPlatformSupportModule(string moduleName) + { + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == moduleName) + { + return current; + } + } + return null; + } + internal static IDevice GetDevice(string deviceId) + { + DevDevice devDevice; + if (!DevDeviceList.FindDevice(deviceId, out devDevice)) + { + throw new ApplicationException("Couldn't create device API for device: " + deviceId); + } + IPlatformSupportModule platformSupportModule = ModuleManager.FindPlatformSupportModule(devDevice.module); + if (platformSupportModule != null) + { + return platformSupportModule.CreateDevice(deviceId); + } + throw new ApplicationException("Couldn't find module for target: " + devDevice.module); + } + internal static IUserAssembliesValidator GetUserAssembliesValidator(string target) + { + if (target == null) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreateUserAssembliesValidatorExtension(); + } + } + return null; + } internal static IBuildPostprocessor GetBuildPostProcessor(string target) { if (target == null) @@ -399,11 +518,76 @@ internal static List GetPreferenceWindowExtensions() } return list; } + internal static IBuildWindowExtension GetBuildWindowExtension(string target) + { + if (string.IsNullOrEmpty(target)) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreateBuildWindowExtension(); + } + } + return null; + } + internal static IScriptingImplementations GetScriptingImplementations(string target) + { + if (string.IsNullOrEmpty(target)) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreateScriptingImplementations(); + } + } + return null; + } + internal static IScriptingImplementations GetScriptingImplementations(BuildTargetGroup target) + { + return ModuleManager.GetScriptingImplementations(ModuleManager.GetTargetStringFromBuildTargetGroup(target)); + } + internal static IPluginImporterExtension GetPluginImporterExtension(string target) + { + if (target == null) + { + return null; + } + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + if (current.TargetName == target) + { + return current.CreatePluginImporterExtension(); + } + } + return null; + } + internal static IPluginImporterExtension GetPluginImporterExtension(BuildTarget target) + { + return ModuleManager.GetPluginImporterExtension(ModuleManager.GetTargetStringFromBuildTarget(target)); + } + internal static IPluginImporterExtension GetPluginImporterExtension(BuildTargetGroup target) + { + return ModuleManager.GetPluginImporterExtension(ModuleManager.GetTargetStringFromBuildTargetGroup(target)); + } internal static string GetTargetStringFromBuildTarget(BuildTarget target) { switch (target) { - case BuildTarget.iPhone: + case BuildTarget.StandaloneOSXUniversal: + case BuildTarget.StandaloneOSXIntel: + case BuildTarget.StandaloneOSXIntel64: + return "OSXStandalone"; + case BuildTarget.StandaloneWindows: + case BuildTarget.StandaloneGLESEmu: + case BuildTarget.StandaloneWindows64: + return "WindowsStandalone"; + case BuildTarget.iOS: return "iOS"; case BuildTarget.PS3: return "PS3"; @@ -411,6 +595,12 @@ internal static string GetTargetStringFromBuildTarget(BuildTarget target) return "Xbox360"; case BuildTarget.Android: return "Android"; + case BuildTarget.StandaloneLinux: + case BuildTarget.StandaloneLinux64: + case BuildTarget.StandaloneLinuxUniversal: + return "LinuxStandalone"; + case BuildTarget.WebGL: + return "WebGL"; case BuildTarget.MetroPlayer: return "Metro"; case BuildTarget.WP8Player: @@ -436,7 +626,7 @@ internal static string GetTargetStringFromBuildTargetGroup(BuildTargetGroup targ { switch (target) { - case BuildTargetGroup.iPhone: + case BuildTargetGroup.iOS: return "iOS"; case BuildTargetGroup.PS3: return "PS3"; @@ -444,11 +634,13 @@ internal static string GetTargetStringFromBuildTargetGroup(BuildTargetGroup targ return "Xbox360"; case BuildTargetGroup.Android: return "Android"; + case BuildTargetGroup.WebGL: + return "WebGL"; case BuildTargetGroup.Metro: return "Metro"; case BuildTargetGroup.WP8: return "WP8"; - case BuildTargetGroup.BB10: + case BuildTargetGroup.BlackBerry: return "BlackBerry"; case BuildTargetGroup.Tizen: return "Tizen"; @@ -465,5 +657,14 @@ internal static string GetTargetStringFromBuildTargetGroup(BuildTargetGroup targ } return null; } + internal static bool IsPlatformSupported(BuildTarget target) + { + return ModuleManager.GetTargetStringFromBuildTarget(target) != null; + } + internal static bool HaveLicenseForBuildTarget(string targetString) + { + BuildTarget target = BuildTarget.StandaloneWindows; + return ModuleManager.TryParseBuildTarget(targetString, out target) && BuildPipeline.LicenseCheck(target); + } } } diff --git a/UnityEditor/UnityEditor.Modules/ModuleUtils.cs b/UnityEditor/UnityEditor.Modules/ModuleUtils.cs new file mode 100644 index 00000000..d72f663b --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/ModuleUtils.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor.Modules +{ + internal static class ModuleUtils + { + internal static string[] GetAdditionalReferencesForUserScripts() + { + List list = new List(); + foreach (IPlatformSupportModule current in ModuleManager.platformSupportModules) + { + list.AddRange(current.AssemblyReferencesForUserScripts); + } + return list.ToArray(); + } + } +} diff --git a/UnityEditor/UnityEditor.Modules/RemoteAddress.cs b/UnityEditor/UnityEditor.Modules/RemoteAddress.cs new file mode 100644 index 00000000..fae8bb4a --- /dev/null +++ b/UnityEditor/UnityEditor.Modules/RemoteAddress.cs @@ -0,0 +1,14 @@ +using System; +namespace UnityEditor.Modules +{ + internal struct RemoteAddress + { + public string ip; + public int port; + public RemoteAddress(string ip, int port) + { + this.ip = ip; + this.port = port; + } + } +} diff --git a/UnityEditor/UnityEditor.NScreen/NScreenManager.cs b/UnityEditor/UnityEditor.NScreen/NScreenManager.cs new file mode 100644 index 00000000..bb696459 --- /dev/null +++ b/UnityEditor/UnityEditor.NScreen/NScreenManager.cs @@ -0,0 +1,192 @@ +using System; +using System.IO; +using System.Linq; +using UnityEngine; +namespace UnityEditor.NScreen +{ + internal class NScreenManager : ScriptableSingleton + { + [SerializeField] + private int m_LatestId; + [SerializeField] + private bool m_BuildOnPlay = true; + [SerializeField] + private int m_SelectedSizeIndex; + internal bool BuildOnPlay + { + get + { + return this.m_BuildOnPlay || !this.HasBuild; + } + set + { + this.m_BuildOnPlay = value; + } + } + internal bool HasBuild + { + get + { + return Directory.Exists("Temp/NScreen/NScreen.app"); + } + } + internal int SelectedSizeIndex + { + get + { + return this.m_SelectedSizeIndex; + } + set + { + this.m_SelectedSizeIndex = value; + } + } + static NScreenManager() + { + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(NScreenManager.PlayModeStateChanged)); + } + internal void ResetIds() + { + this.m_LatestId = 0; + } + internal int GetNewId() + { + return ++this.m_LatestId; + } + internal static void PlayModeStateChanged() + { + if (EditorApplication.isPaused) + { + return; + } + if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode && Resources.FindObjectsOfTypeAll().Length > 0 && ScriptableSingleton.instance.BuildOnPlay) + { + NScreenManager.Build(); + } + if (EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode) + { + NScreenManager.StartAll(); + } + else + { + if (EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode) + { + NScreenManager.StopAll(); + } + else + { + if (!EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode) + { + NScreenManager.RepaintAllGameViews(); + } + } + } + } + internal static void Init() + { + RemoteGame remoteGame = (RemoteGame)EditorWindow.GetWindow(typeof(RemoteGame)); + if (EditorApplication.isPlaying && !remoteGame.IsRunning()) + { + remoteGame.id = ScriptableSingleton.instance.GetNewId(); + remoteGame.StartGame(); + } + } + internal static void OpenAnotherWindow() + { + RemoteGame remoteGame = ScriptableObject.CreateInstance(); + ContainerWindow[] windows = ContainerWindow.windows; + for (int i = 0; i < windows.Length; i++) + { + ContainerWindow containerWindow = windows[i]; + View[] allChildren = containerWindow.mainView.allChildren; + for (int j = 0; j < allChildren.Length; j++) + { + View view = allChildren[j]; + DockArea dockArea = view as DockArea; + if (!(dockArea == null)) + { + if (dockArea.m_Panes.Any((EditorWindow pane) => pane.GetType() == typeof(RemoteGame))) + { + dockArea.AddTab(remoteGame); + break; + } + } + } + } + remoteGame.Show(); + if (EditorApplication.isPlaying) + { + remoteGame.id = ScriptableSingleton.instance.GetNewId(); + remoteGame.StartGame(); + } + } + internal static void StartAll() + { + ScriptableSingleton.instance.ResetIds(); + RemoteGame[] array = Resources.FindObjectsOfTypeAll(); + for (int i = 0; i < array.Length; i++) + { + RemoteGame remoteGame = array[i]; + remoteGame.id = ScriptableSingleton.instance.GetNewId(); + remoteGame.StartGame(); + } + } + internal static void StopAll() + { + RemoteGame[] array = Resources.FindObjectsOfTypeAll(); + for (int i = 0; i < array.Length; i++) + { + RemoteGame remoteGame = array[i]; + remoteGame.StopGame(); + } + } + internal static void RepaintAllGameViews() + { + RemoteGame[] array = Resources.FindObjectsOfTypeAll(); + for (int i = 0; i < array.Length; i++) + { + RemoteGame remoteGame = array[i]; + remoteGame.Repaint(); + remoteGame.GameViewAspectWasChanged(); + } + } + internal static void Build() + { + string[] array = new string[EditorBuildSettings.scenes.Length]; + int num = 0; + for (int i = 0; i < EditorBuildSettings.scenes.Length; i++) + { + if (EditorBuildSettings.scenes[i].enabled) + { + array[num] = EditorBuildSettings.scenes[i].path; + num++; + } + } + Array.Resize(ref array, num); + Directory.CreateDirectory("Temp/NScreen"); + ResolutionDialogSetting displayResolutionDialog = PlayerSettings.displayResolutionDialog; + bool runInBackground = PlayerSettings.runInBackground; + bool defaultIsFullScreen = PlayerSettings.defaultIsFullScreen; + PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.Disabled; + PlayerSettings.runInBackground = true; + PlayerSettings.defaultIsFullScreen = false; + try + { + if (IntPtr.Size == 4) + { + BuildPipeline.BuildPlayer(array, "Temp/NScreen/NScreen.app", BuildTarget.StandaloneOSXIntel, BuildOptions.None); + } + else + { + BuildPipeline.BuildPlayer(array, "Temp/NScreen/NScreen.app", BuildTarget.StandaloneOSXIntel64, BuildOptions.None); + } + } + finally + { + PlayerSettings.displayResolutionDialog = displayResolutionDialog; + PlayerSettings.runInBackground = runInBackground; + PlayerSettings.defaultIsFullScreen = defaultIsFullScreen; + } + } + } +} diff --git a/UnityEditor/UnityEditor.NScreen/RemoteGame.cs b/UnityEditor/UnityEditor.NScreen/RemoteGame.cs new file mode 100644 index 00000000..f40e922e --- /dev/null +++ b/UnityEditor/UnityEditor.NScreen/RemoteGame.cs @@ -0,0 +1,182 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using UnityEngine; +namespace UnityEditor.NScreen +{ + internal class RemoteGame : EditorWindow, IHasCustomMenu + { + private const float kMaxWidth = 1280f; + private const float kMaxHeight = 720f; + private Process remoteProcess; + public NScreenBridge bridge; + public bool shouldExit = true; + public bool shouldBuild; + public int id; + private int oldWidth; + private int oldHeight; + private Rect remoteViewRect; + private int ToolBarHeight + { + get + { + return 17; + } + } + internal void StartGame() + { + this.DoExitGame(); + base.wantsMouseMove = true; + this.bridge = new NScreenBridge(); + this.bridge.InitServer(this.id); + this.bridge.SetResolution((int)base.minSize.x, (int)base.minSize.y); + this.remoteProcess = new Process(); + this.remoteProcess.EnableRaisingEvents = true; + this.remoteProcess.Exited += new EventHandler(this.HandleExited); + this.remoteProcess.StartInfo.FileName = "Temp/NScreen/NScreen.app/Contents/MacOS/NScreen"; + this.remoteProcess.StartInfo.Arguments = "-nscreenid " + this.id; + this.remoteProcess.StartInfo.UseShellExecute = false; + try + { + this.remoteProcess.Start(); + } + catch (Win32Exception) + { + this.remoteProcess = null; + this.DoExitGame(); + } + this.bridge.StartWatchdogForPid(this.remoteProcess.Id); + this.shouldExit = false; + } + internal bool IsRunning() + { + return !this.shouldExit; + } + internal void StopGame() + { + this.shouldExit = true; + } + private void Update() + { + if (this.shouldExit) + { + this.DoExitGame(); + } + else + { + if (this.bridge != null) + { + if (this.oldWidth != (int)base.position.width || this.oldHeight != (int)base.position.height) + { + int num = (int)Mathf.Clamp(base.position.width, base.minSize.x, 1280f); + int num2 = (int)Mathf.Clamp(base.position.height, base.minSize.y, 720f); + bool flag = true; + this.remoteViewRect = GameViewSizes.GetConstrainedRect(new Rect(0f, 0f, (float)num, (float)num2), ScriptableSingleton.instance.currentGroupType, ScriptableSingleton.instance.SelectedSizeIndex, out flag); + this.remoteViewRect.y = this.remoteViewRect.y + (float)this.ToolBarHeight; + this.remoteViewRect.height = this.remoteViewRect.height - (float)this.ToolBarHeight; + this.bridge.SetResolution((int)this.remoteViewRect.width, (int)this.remoteViewRect.height); + this.oldWidth = (int)base.position.width; + this.oldHeight = (int)base.position.height; + } + this.bridge.Update(); + base.Repaint(); + } + } + if (this.shouldBuild) + { + this.shouldBuild = false; + NScreenManager.Build(); + } + } + private void SelectionCallback(int indexClicked, object objectSelected) + { + if (indexClicked != ScriptableSingleton.instance.SelectedSizeIndex) + { + ScriptableSingleton.instance.SelectedSizeIndex = indexClicked; + NScreenManager.RepaintAllGameViews(); + } + } + internal void GameViewAspectWasChanged() + { + this.oldWidth = 0; + this.oldHeight = 0; + } + private void OnGUI() + { + GUI.color = Color.white; + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + EditorGUILayout.GameViewSizePopup(ScriptableSingleton.instance.currentGroupType, ScriptableSingleton.instance.SelectedSizeIndex, new Action(this.SelectionCallback), EditorStyles.toolbarDropDown, new GUILayoutOption[] + { + GUILayout.Width(160f) + }); + GUILayout.FlexibleSpace(); + GUI.enabled = !Application.isPlaying; + bool buildOnPlay = ScriptableSingleton.instance.BuildOnPlay; + ScriptableSingleton.instance.BuildOnPlay = GUILayout.Toggle(ScriptableSingleton.instance.BuildOnPlay, "Build on Play", EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (buildOnPlay != ScriptableSingleton.instance.BuildOnPlay) + { + NScreenManager.RepaintAllGameViews(); + } + if (GUILayout.Button("Build Now", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.shouldBuild = true; + } + GUI.enabled = Application.isPlaying; + GUILayout.EndHorizontal(); + if (!this.shouldExit && this.bridge != null) + { + Texture2D screenTexture = this.bridge.GetScreenTexture(); + if (screenTexture != null) + { + GUI.DrawTexture(this.remoteViewRect, screenTexture); + } + if (this == EditorWindow.focusedWindow) + { + this.bridge.SetInput((int)Event.current.mousePosition.x - (int)this.remoteViewRect.x, (int)base.position.height - (int)Event.current.mousePosition.y - (int)this.remoteViewRect.y + this.ToolBarHeight - (int)Mathf.Max(0f, base.position.height - 720f), Event.current.button, (int)((!Event.current.isKey) ? ((KeyCode)(-1)) : Event.current.keyCode), (int)Event.current.type); + } + else + { + this.bridge.ResetInput(); + } + } + else + { + GUILayout.Label("Game Stopped", new GUILayoutOption[0]); + } + } + private void HandleExited(object sender, EventArgs e) + { + this.shouldExit = true; + } + internal void DoExitGame() + { + if (this.remoteProcess != null && !this.remoteProcess.HasExited) + { + this.remoteProcess.Kill(); + this.remoteProcess = null; + base.Repaint(); + } + if (this.bridge != null) + { + this.bridge.Shutdown(); + this.bridge = null; + this.oldWidth = 0; + this.oldHeight = 0; + } + base.wantsMouseMove = false; + this.shouldExit = true; + } + private void OnEnable() + { + base.title = "Remote Game"; + } + private void OnDestroy() + { + this.DoExitGame(); + } + public void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Add Tab/Remote Game"), false, new GenericMenu.MenuFunction(NScreenManager.OpenAnotherWindow)); + } + } +} diff --git a/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs deleted file mode 100644 index e7e886ed..00000000 --- a/UnityEditor/UnityEditor.OSXStandalone/OSXStandaloneIl2CppPlatformProvider.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using System.IO; -using UnityEditorInternal; -namespace UnityEditor.OSXStandalone -{ - internal class OSXStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider - { - private readonly bool m_DevelopmentBuild; - public override bool emitNullChecks - { - get - { - return this.m_DevelopmentBuild; - } - } - public override bool enableStackTraces - { - get - { - return this.m_DevelopmentBuild; - } - } - public override string nativeLibraryFileName - { - get - { - return "UserAssembly.dylib"; - } - } - public OSXStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder, bool developmentBuild) : base(target, Path.Combine(dataFolder, "Libraries")) - { - this.m_DevelopmentBuild = developmentBuild; - } - public override INativeCompiler CreateNativeCompiler() - { - BuildTarget target = this.target; - if (target != BuildTarget.StandaloneOSXIntel) - { - throw new Exception("This OSX arch isn't supported yet. " + this.target); - } - ICompilerSettings settings = new ClangCompilerSettingsx86(); - return new ClangCompiler(settings); - } - } -} diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs index a0d2e9b1..a79edf6a 100644 --- a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAnimatorController.cs @@ -1,5 +1,5 @@ using System; -using UnityEditorInternal; +using UnityEditor.Animations; namespace UnityEditor.ProjectWindowCallback { internal class DoCreateAnimatorController : EndNameEditAction diff --git a/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAudioMixer.cs b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAudioMixer.cs new file mode 100644 index 00000000..b62d7735 --- /dev/null +++ b/UnityEditor/UnityEditor.ProjectWindowCallback/DoCreateAudioMixer.cs @@ -0,0 +1,23 @@ +using System; +using UnityEditor.Audio; +using UnityEditorInternal; +namespace UnityEditor.ProjectWindowCallback +{ + internal class DoCreateAudioMixer : EndNameEditAction + { + public override void Action(int instanceId, string pathName, string resourceFile) + { + AudioMixerController audioMixerController = AudioMixerController.CreateMixerControllerAtPath(pathName); + int instanceID; + if (!string.IsNullOrEmpty(resourceFile) && int.TryParse(resourceFile, out instanceID)) + { + AudioMixerGroupController audioMixerGroupController = InternalEditorUtility.GetObjectFromInstanceID(instanceID) as AudioMixerGroupController; + if (audioMixerGroupController != null) + { + audioMixerController.outputAudioMixerGroup = audioMixerGroupController; + } + } + ProjectWindowUtil.ShowCreatedAsset(audioMixerController); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/APIUpdaterHelper.cs b/UnityEditor/UnityEditor.Scripting.Compilers/APIUpdaterHelper.cs new file mode 100644 index 00000000..75dc957b --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/APIUpdaterHelper.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Utils; +using UnityEditor.VersionControl; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Scripting.Compilers +{ + internal class APIUpdaterHelper + { + private const string tempOutputPath = "Temp/ScriptUpdater/"; + public static void UpdateScripts(string responseFile, string sourceExtension) + { + if (!ScriptUpdatingManager.WaitForVCSServerConnection(true)) + { + return; + } + string text = (!Provider.enabled) ? "." : "Temp/ScriptUpdater/"; + APIUpdaterHelper.RunUpdatingProgram("ScriptUpdater.exe", string.Concat(new string[] + { + sourceExtension, + " ", + CommandLineFormatter.PrepareFileName(MonoInstallationFinder.GetFrameWorksFolder()), + " ", + text, + " ", + responseFile + })); + } + private static void RunUpdatingProgram(string executable, string arguments) + { + string executable2 = EditorApplication.applicationContentsPath + "/Tools/ScriptUpdater/" + executable; + ManagedProgram managedProgram = new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.5", executable2, arguments); + managedProgram.LogProcessStartInfo(); + managedProgram.Start(); + managedProgram.WaitForExit(); + Console.WriteLine(string.Join(Environment.NewLine, managedProgram.GetStandardOutput())); + if (managedProgram.ExitCode == 0) + { + APIUpdaterHelper.UpdateFilesInVCIfNeeded(); + } + else + { + APIUpdaterHelper.ReportAPIUpdaterFailure(managedProgram.GetErrorOutput()); + } + } + private static void ReportAPIUpdaterFailure(IEnumerable errorOutput) + { + Console.WriteLine("Failed to run script updater.\n "); + foreach (string current in errorOutput) + { + if (current.StartsWith("unity.console:")) + { + Debug.LogError(current.Substring("unity.console:".Length)); + } + else + { + Console.WriteLine(current); + } + } + ScriptUpdatingManager.ReportExpectedUpdateFailure(); + } + private static void UpdateFilesInVCIfNeeded() + { + if (!Provider.enabled) + { + return; + } + string[] files = Directory.GetFiles("Temp/ScriptUpdater/", "*.*", SearchOption.AllDirectories); + AssetList assetList = new AssetList(); + string[] array = files; + for (int i = 0; i < array.Length; i++) + { + string text = array[i]; + assetList.Add(Provider.GetAssetByPath(text.Replace("Temp/ScriptUpdater/", string.Empty))); + } + Task task = Provider.Checkout(assetList, CheckoutMode.Both); + task.Wait(); + IEnumerable source = + from a in task.assetList + where (a.state & Asset.States.ReadOnly) == Asset.States.ReadOnly + select a; + if (!task.success || source.Any()) + { + string arg_103_0 = "[API Updater] Files cannot be updated (failed to checkout): {0}"; + object[] expr_BA = new object[1]; + expr_BA[0] = ( + from a in source + select string.Concat(new object[] + { + a.fullName, + " (", + a.state, + ")" + })).Aggregate((string acc, string curr) => acc + Environment.NewLine + "\t" + curr); + Debug.LogErrorFormat(arg_103_0, expr_BA); + ScriptUpdatingManager.ReportExpectedUpdateFailure(); + return; + } + FileUtil.CopyDirectoryRecursive("Temp/ScriptUpdater/", ".", true); + FileUtil.DeleteFileOrDirectory("Temp/ScriptUpdater/"); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs index 2fab9535..290bf9be 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompiler.cs @@ -1,13 +1,14 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using UnityEditor.Utils; using UnityEngineInternal; namespace UnityEditor.Scripting.Compilers { internal class BooCompiler : MonoScriptCompilerBase { - public BooCompiler(MonoIsland island) : base(island) + public BooCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } protected override Program StartCompiler() @@ -19,23 +20,20 @@ protected override Program StartCompiler() "-out:" + this._island._output, "-x-type-inference-rule-attribute:" + typeof(TypeInferenceRuleAttribute) }; - list.Add("-debug"); string[] references = this._island._references; for (int i = 0; i < references.Length; i++) { string fileName = references[i]; list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); } - string[] defines = this._island._defines; - for (int j = 0; j < defines.Length; j++) + foreach (string current in this._island._defines.Distinct()) { - string str = defines[j]; - list.Add("-define:" + str); + list.Add("-define:" + current); } string[] files = this._island._files; - for (int k = 0; k < files.Length; k++) + for (int j = 0; j < files.Length; j++) { - string fileName2 = files[k]; + string fileName2 = files[j]; list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); } string compiler = Path.Combine(base.GetProfileDirectory(), "booc.exe"); diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs index 506323bd..755d9a57 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooCompilerOutputParser.cs @@ -5,6 +5,7 @@ namespace UnityEditor.Scripting.Compilers internal class BooCompilerOutputParser : CompilerOutputParserBase { private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*[BU]C(?W|E)(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture); + private static Regex sMissingMember = new Regex("[^']*'(?[^']+)'[^']+'(?[^']+)'", RegexOptions.ExplicitCapture | RegexOptions.Compiled); protected override string GetErrorIdentifier() { return "E"; @@ -13,5 +14,9 @@ protected override Regex GetOutputRegex() { return BooCompilerOutputParser.sCompilerOutput; } + protected override NormalizedCompilerStatus NormalizedStatusFor(Match match) + { + return CompilerOutputParserBase.TryNormalizeCompilerStatus(match, "0019", BooCompilerOutputParser.sMissingMember); + } } } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs index aff96244..44932f70 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/BooLanguage.cs @@ -14,9 +14,9 @@ public override string GetLanguageName() { return "Boo"; } - public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) { - return new BooCompiler(island); + return new BooCompiler(island, runUpdater); } public override string GetNamespace(string fileName) { diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs index 7bdda0d4..f1b2f028 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CSharpLanguage.cs @@ -58,13 +58,27 @@ public override string GetLanguageName() { return "CSharp"; } - public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + internal static bool GetUseMicrosoftCSharpCompiler(BuildTarget targetPlatform, bool buildingForEditor, string assemblyName) { - if (!buildingForEditor && targetPlatform.ToString().Contains("MetroPlayer") && (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCore || (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCorePartially && !island._output.Contains("Assembly-CSharp-firstpass.dll")))) + if (buildingForEditor || targetPlatform != BuildTarget.MetroPlayer) { - return new MicrosoftCSharpCompiler(island); + return false; } - return new MonoCSharpCompiler(island); + assemblyName = Path.GetFileNameWithoutExtension(assemblyName); + PlayerSettings.WSACompilationOverrides compilationOverrides = PlayerSettings.WSA.compilationOverrides; + if (compilationOverrides != PlayerSettings.WSACompilationOverrides.UseNetCore) + { + return compilationOverrides == PlayerSettings.WSACompilationOverrides.UseNetCorePartially && string.Compare(assemblyName, "Assembly-CSharp", true) == 0; + } + return string.Compare(assemblyName, "Assembly-CSharp", true) == 0 || string.Compare(assemblyName, "Assembly-CSharp-firstPass", true) == 0; + } + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) + { + if (CSharpLanguage.GetUseMicrosoftCSharpCompiler(targetPlatform, buildingForEditor, island._output)) + { + return new MicrosoftCSharpCompiler(island, runUpdater); + } + return new MonoCSharpCompiler(island, runUpdater); } public override string GetNamespace(string fileName) { diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs index 74928f32..201fcded 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/Cil2AsOutputParser.cs @@ -9,10 +9,10 @@ internal class Cil2AsOutputParser : UnityScriptCompilerOutputParser [DebuggerHidden] public override IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) { - Cil2AsOutputParser.c__Iterator5 c__Iterator = new Cil2AsOutputParser.c__Iterator5(); + Cil2AsOutputParser.c__Iterator7 c__Iterator = new Cil2AsOutputParser.c__Iterator7(); c__Iterator.errorOutput = errorOutput; c__Iterator.<$>errorOutput = errorOutput; - Cil2AsOutputParser.c__Iterator5 expr_15 = c__Iterator; + Cil2AsOutputParser.c__Iterator7 expr_15 = c__Iterator; expr_15.$PC = -2; return expr_15; } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs index 90be8211..2b7adf43 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerMessage.cs @@ -8,5 +8,6 @@ internal struct CompilerMessage public int line; public int column; public CompilerMessageType type; + public NormalizedCompilerStatus normalizedStatus; } } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs index 8e62079f..3669384a 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/CompilerOutputParserBase.cs @@ -13,7 +13,7 @@ protected static CompilerMessage CreateInternalCompilerErrorMessage(string[] com result.type = CompilerMessageType.Error; result.line = 0; result.column = 0; - result.message = "Internal compiler error. See the console log for more information. output was:" + result.message; + result.normalizedStatus = default(NormalizedCompilerStatus); return result; } protected internal static CompilerMessage CreateCompilerMessageFromMatchedRegex(string line, Match m, string erroridentifier) @@ -24,6 +24,7 @@ protected internal static CompilerMessage CreateCompilerMessageFromMatchedRegex( result.line = int.Parse(m.Groups["line"].Value); result.column = int.Parse(m.Groups["column"].Value); result.type = ((!(m.Groups["type"].Value == erroridentifier)) ? CompilerMessageType.Warning : CompilerMessageType.Error); + result.normalizedStatus = default(NormalizedCompilerStatus); return result; } public virtual IEnumerable Parse(string[] errorOutput, bool compilationHadFailure) @@ -43,6 +44,7 @@ public virtual IEnumerable Parse(string[] errorOutput, string[] if (match.Success) { CompilerMessage item = CompilerOutputParserBase.CreateCompilerMessageFromMatchedRegex(text, match, this.GetErrorIdentifier()); + item.normalizedStatus = this.NormalizedStatusFor(match); if (item.type == CompilerMessageType.Error) { flag = true; @@ -56,7 +58,24 @@ public virtual IEnumerable Parse(string[] errorOutput, string[] } return list; } + protected virtual NormalizedCompilerStatus NormalizedStatusFor(Match match) + { + return default(NormalizedCompilerStatus); + } protected abstract string GetErrorIdentifier(); protected abstract Regex GetOutputRegex(); + protected static NormalizedCompilerStatus TryNormalizeCompilerStatus(Match match, string memberNotFoundError, Regex missingMemberRegex) + { + string value = match.Groups["id"].Value; + NormalizedCompilerStatus result = default(NormalizedCompilerStatus); + if (value != memberNotFoundError) + { + return result; + } + result.code = NormalizedCompilerStatusCode.MemberNotFound; + Match match2 = missingMemberRegex.Match(match.Groups["message"].Value); + result.details = match2.Groups["type_name"].Value + "%" + match2.Groups["member_name"].Value; + return result; + } } } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs deleted file mode 100644 index 55a2f179..00000000 --- a/UnityEditor/UnityEditor.Scripting.Compilers/FlexCompilerOutputParser.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Text.RegularExpressions; -namespace UnityEditor.Scripting.Compilers -{ - internal class FlexCompilerOutputParser : CompilerOutputParserBase - { - private static Regex sCompilerOutput = new Regex("(?.*)\\((?\\d+)\\)\\: col\\: (?\\d+) (?Warning|Error): (?.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled); - protected override Regex GetOutputRegex() - { - return FlexCompilerOutputParser.sCompilerOutput; - } - protected override string GetErrorIdentifier() - { - return "Error"; - } - } -} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs index d71b6a6d..9eba2d6e 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/GendarmeOutputParser.cs @@ -13,10 +13,10 @@ public override IEnumerable Parse(string[] errorOutput, bool co [DebuggerHidden] public override IEnumerable Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure) { - GendarmeOutputParser.c__Iterator6 c__Iterator = new GendarmeOutputParser.c__Iterator6(); + GendarmeOutputParser.c__Iterator8 c__Iterator = new GendarmeOutputParser.c__Iterator8(); c__Iterator.standardOutput = standardOutput; c__Iterator.<$>standardOutput = standardOutput; - GendarmeOutputParser.c__Iterator6 expr_15 = c__Iterator; + GendarmeOutputParser.c__Iterator8 expr_15 = c__Iterator; expr_15.$PC = -2; return expr_15; } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs index 79127f83..5fbca764 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MicrosoftCSharpCompiler.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Linq; using UnityEditor.Utils; using UnityEditorInternal; using UnityEngine; @@ -55,28 +56,28 @@ internal static string ProgramFilesDirectory return result; } } - public MicrosoftCSharpCompiler(MonoIsland island) : base(island) + public MicrosoftCSharpCompiler(MonoIsland island, bool runUpdater) : base(island) { } - internal static string GetNETCoreFrameworkReferencesDirectory(MetroSDK metroSDK) + internal static string GetNETCoreFrameworkReferencesDirectory(WSASDK wsaSDK) { - switch (metroSDK) + switch (wsaSDK) { - case MetroSDK.SDK80: + case WSASDK.SDK80: return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\.NETCore\\v4.5"; - case MetroSDK.SDK81: + case WSASDK.SDK81: return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\.NETCore\\v4.5.1"; - case MetroSDK.PhoneSDK81: + case WSASDK.PhoneSDK81: return MicrosoftCSharpCompiler.ProgramFilesDirectory + "\\Reference Assemblies\\Microsoft\\Framework\\WindowsPhoneApp\\v8.1"; default: - throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + throw new Exception("Unknown Windows SDK: " + wsaSDK.ToString()); } } - private string[] GetNETMetroAssemblies(MetroSDK metroSDK) + private string[] GetNETWSAAssemblies(WSASDK wsaSDK) { - return Directory.GetFiles(MicrosoftCSharpCompiler.GetNETCoreFrameworkReferencesDirectory(metroSDK), "*.dll"); + return Directory.GetFiles(MicrosoftCSharpCompiler.GetNETCoreFrameworkReferencesDirectory(wsaSDK), "*.dll"); } - private string GetNetMetroAssemblyInfoWindows80() + private string GetNetWSAAssemblyInfoWindows80() { return string.Join("\r\n", new string[] { @@ -85,7 +86,7 @@ private string GetNetMetroAssemblyInfoWindows80() "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\".NETCore,Version=v4.5\", FrameworkDisplayName = \".NET for Windows Store apps\")]" }); } - private string GetNetMetroAssemblyInfoWindows81() + private string GetNetWSAAssemblyInfoWindows81() { return string.Join("\r\n", new string[] { @@ -94,7 +95,7 @@ private string GetNetMetroAssemblyInfoWindows81() "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\".NETCore,Version=v4.5.1\", FrameworkDisplayName = \".NET for Windows Store apps (Windows 8.1)\")]" }); } - private string GetNetMetroAssemblyInfoWindowsPhone81() + private string GetNetWSAAssemblyInfoWindowsPhone81() { return string.Join("\r\n", new string[] { @@ -103,56 +104,56 @@ private string GetNetMetroAssemblyInfoWindowsPhone81() "[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(\"WindowsPhoneApp,Version=v8.1\", FrameworkDisplayName = \"Windows Phone 8.1\")]" }); } - private void FillNETCoreCompilerOptions(MetroSDK metroSDK, List arguments, ref string argsPrefix) + private void FillNETCoreCompilerOptions(WSASDK wsaSDK, List arguments, ref string argsPrefix) { argsPrefix = "/noconfig "; arguments.Add("/nostdlib+"); arguments.Add("/define:NETFX_CORE"); - string platformAssemblyPath = MicrosoftCSharpCompiler.GetPlatformAssemblyPath(metroSDK); + string platformAssemblyPath = MicrosoftCSharpCompiler.GetPlatformAssemblyPath(wsaSDK); string arg; - switch (metroSDK) + switch (wsaSDK) { - case MetroSDK.SDK80: + case WSASDK.SDK80: arg = "8.0"; break; - case MetroSDK.SDK81: + case WSASDK.SDK81: arg = "8.1"; break; - case MetroSDK.PhoneSDK81: + case WSASDK.PhoneSDK81: arg = "Phone 8.1"; break; default: - throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.wsaSDK.ToString()); } if (!File.Exists(platformAssemblyPath)) { throw new Exception(string.Format("'{0}' not found, do you have Windows {1} SDK installed?", platformAssemblyPath, arg)); } arguments.Add("/reference:\"" + platformAssemblyPath + "\""); - string[] nETMetroAssemblies = this.GetNETMetroAssemblies(metroSDK); - for (int i = 0; i < nETMetroAssemblies.Length; i++) + string[] nETWSAAssemblies = this.GetNETWSAAssemblies(wsaSDK); + for (int i = 0; i < nETWSAAssemblies.Length; i++) { - string str = nETMetroAssemblies[i]; + string str = nETWSAAssemblies[i]; arguments.Add("/reference:\"" + str + "\""); } string text; string contents; - switch (metroSDK) + switch (wsaSDK) { - case MetroSDK.SDK80: + case WSASDK.SDK80: text = Path.Combine(Path.GetTempPath(), ".NETCore,Version=v4.5.AssemblyAttributes.cs"); - contents = this.GetNetMetroAssemblyInfoWindows80(); + contents = this.GetNetWSAAssemblyInfoWindows80(); break; - case MetroSDK.SDK81: + case WSASDK.SDK81: text = Path.Combine(Path.GetTempPath(), ".NETCore,Version=v4.5.1.AssemblyAttributes.cs"); - contents = this.GetNetMetroAssemblyInfoWindows81(); + contents = this.GetNetWSAAssemblyInfoWindows81(); break; - case MetroSDK.PhoneSDK81: + case WSASDK.PhoneSDK81: text = Path.Combine(Path.GetTempPath(), "WindowsPhoneApp,Version=v8.1.AssemblyAttributes.cs"); - contents = this.GetNetMetroAssemblyInfoWindowsPhone81(); + contents = this.GetNetWSAAssemblyInfoWindowsPhone81(); break; default: - throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.wsaSDK.ToString()); } if (File.Exists(text)) { @@ -171,16 +172,14 @@ private Program StartCompilerImpl(List arguments, string argsPrefix) string fileName = references[i]; arguments.Add("/reference:" + ScriptCompilerBase.PrepareFileName(fileName)); } - string[] defines = this._island._defines; - for (int j = 0; j < defines.Length; j++) + foreach (string current in this._island._defines.Distinct()) { - string str = defines[j]; - arguments.Add("/define:" + str); + arguments.Add("/define:" + current); } string[] files = this._island._files; - for (int k = 0; k < files.Length; k++) + for (int j = 0; j < files.Length; j++) { - string fileName2 = files[k]; + string fileName2 = files[j]; arguments.Add(ScriptCompilerBase.PrepareFileName(fileName2).Replace('/', '\\')); } string text = Path.Combine(MicrosoftCSharpCompiler.WindowsDirectory, "Microsoft.NET\\Framework\\v4.0.30319\\Csc.exe"); @@ -189,10 +188,10 @@ private Program StartCompilerImpl(List arguments, string argsPrefix) throw new Exception("'" + text + "' not found, either .NET 4.5 is not installed or your OS is not Windows 8/8.1."); } base.AddCustomResponseFileIfPresent(arguments, "csc.rsp"); - string str2 = CommandLineFormatter.GenerateResponseFile(arguments); + string str = CommandLineFormatter.GenerateResponseFile(arguments); ProcessStartInfo si = new ProcessStartInfo { - Arguments = argsPrefix + "@" + str2, + Arguments = argsPrefix + "@" + str, FileName = text, CreateNoWindow = true }; @@ -215,9 +214,9 @@ protected override Program StartCompiler() "/optimize+" }); string empty = string.Empty; - if (base.CompilingForMetro() && (PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCore || PlayerSettings.Metro.compilationOverrides == PlayerSettings.MetroCompilationOverrides.UseNetCorePartially)) + if (base.CompilingForWSA() && (PlayerSettings.WSA.compilationOverrides == PlayerSettings.WSACompilationOverrides.UseNetCore || PlayerSettings.WSA.compilationOverrides == PlayerSettings.WSACompilationOverrides.UseNetCorePartially)) { - this.FillNETCoreCompilerOptions(EditorUserBuildSettings.metroSDK, list, ref empty); + this.FillNETCoreCompilerOptions(EditorUserBuildSettings.wsaSDK, list, ref empty); } return this.StartCompilerImpl(list, empty); } @@ -229,26 +228,26 @@ protected override CompilerOutputParserBase CreateOutputParser() { return new MicrosoftCSharpCompilerOutputParser(); } - protected static string GetPlatformAssemblyPath(MetroSDK metroSDK) + protected static string GetPlatformAssemblyPath(WSASDK wsaSDK) { string text; string path; - switch (metroSDK) + switch (wsaSDK) { - case MetroSDK.SDK80: + case WSASDK.SDK80: text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0", "InstallationFolder"); path = "Windows Kits\\8.0"; break; - case MetroSDK.SDK81: + case WSASDK.SDK81: text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.1", "InstallationFolder"); path = "Windows Kits\\8.1"; break; - case MetroSDK.PhoneSDK81: + case WSASDK.PhoneSDK81: text = RegistryUtil.GetRegistryStringValue32("SOFTWARE\\Microsoft\\Microsoft SDKs\\WindowsPhoneApp\\v8.1", "InstallationFolder"); path = "Windows Phone Kits\\8.1"; break; default: - throw new Exception("Unknown Windows SDK: " + EditorUserBuildSettings.metroSDK.ToString()); + throw new Exception("Unknown Windows SDK: " + wsaSDK.ToString()); } if (text == null) { diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs index 2797f9cf..d7c41e3c 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompiler.cs @@ -8,7 +8,7 @@ namespace UnityEditor.Scripting.Compilers { internal class MonoCSharpCompiler : MonoScriptCompilerBase { - public MonoCSharpCompiler(MonoIsland island) : base(island) + public MonoCSharpCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } protected override Program StartCompiler() @@ -26,22 +26,20 @@ protected override Program StartCompiler() string fileName = references[i]; list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); } - string[] defines = this._island._defines; - for (int j = 0; j < defines.Length; j++) + foreach (string current in this._island._defines.Distinct()) { - string str = defines[j]; - list.Add("-define:" + str); + list.Add("-define:" + current); } string[] files = this._island._files; - for (int k = 0; k < files.Length; k++) + for (int j = 0; j < files.Length; j++) { - string fileName2 = files[k]; + string fileName2 = files[j]; list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); } string[] additionalReferences = this.GetAdditionalReferences(); - for (int l = 0; l < additionalReferences.Length; l++) + for (int k = 0; k < additionalReferences.Length; k++) { - string path = additionalReferences[l]; + string path = additionalReferences[k]; string text = Path.Combine(base.GetProfileDirectory(), path); if (File.Exists(text)) { @@ -86,7 +84,7 @@ public static string[] Compile(string[] sources, string[] references, string[] d { MonoIsland island = new MonoIsland(BuildTarget.StandaloneWindows, "unity", sources, references, defines, outputFile); string[] result; - using (MonoCSharpCompiler monoCSharpCompiler = new MonoCSharpCompiler(island)) + using (MonoCSharpCompiler monoCSharpCompiler = new MonoCSharpCompiler(island, false)) { monoCSharpCompiler.BeginCompiling(); while (!monoCSharpCompiler.Poll()) diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs index c6ee3ab1..09291924 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoCSharpCompilerOutputParser.cs @@ -5,6 +5,7 @@ namespace UnityEditor.Scripting.Compilers internal class MonoCSharpCompilerOutputParser : CompilerOutputParserBase { private static Regex sCompilerOutput = new Regex("\\s*(?.*)\\((?\\d+),(?\\d+)\\):\\s*(?warning|error)\\s*(?[^:]*):\\s*(?.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex sMissingMember = new Regex("[^`]*`(?[^']+)'[^`]+`(?[^']+)'", RegexOptions.ExplicitCapture | RegexOptions.Compiled); protected override Regex GetOutputRegex() { return MonoCSharpCompilerOutputParser.sCompilerOutput; @@ -13,5 +14,9 @@ protected override string GetErrorIdentifier() { return "error"; } + protected override NormalizedCompilerStatus NormalizedStatusFor(Match match) + { + return CompilerOutputParserBase.TryNormalizeCompilerStatus(match, "CS0117", MonoCSharpCompilerOutputParser.sMissingMember); + } } } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs index a0cb2458..edb6c484 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/MonoScriptCompilerBase.cs @@ -6,8 +6,10 @@ namespace UnityEditor.Scripting.Compilers { internal abstract class MonoScriptCompilerBase : ScriptCompilerBase { - protected MonoScriptCompilerBase(MonoIsland island) : base(island) + private readonly bool runUpdater; + protected MonoScriptCompilerBase(MonoIsland island, bool runUpdater) : base(island) { + this.runUpdater = runUpdater; } protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments) { @@ -16,9 +18,13 @@ protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments, bool setMonoEnvironmentVariables) { base.AddCustomResponseFileIfPresent(arguments, Path.GetFileNameWithoutExtension(compiler) + ".rsp"); - string str = CommandLineFormatter.GenerateResponseFile(arguments); + string text = CommandLineFormatter.GenerateResponseFile(arguments); + if (this.runUpdater) + { + APIUpdaterHelper.UpdateScripts(text, this._island.GetExtensionOfSourceFiles()); + } string monoInstallation = MonoInstallationFinder.GetMonoInstallation(); - ManagedProgram managedProgram = new ManagedProgram(monoInstallation, this._island._classlib_profile, compiler, " @" + str, setMonoEnvironmentVariables); + ManagedProgram managedProgram = new ManagedProgram(monoInstallation, this._island._classlib_profile, compiler, " @" + text, setMonoEnvironmentVariables); managedProgram.Start(); return managedProgram; } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatus.cs b/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatus.cs new file mode 100644 index 00000000..5b37c367 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatus.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal struct NormalizedCompilerStatus + { + public NormalizedCompilerStatusCode code; + public string details; + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatusCode.cs b/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatusCode.cs new file mode 100644 index 00000000..d2655fbc --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting.Compilers/NormalizedCompilerStatusCode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor.Scripting.Compilers +{ + internal enum NormalizedCompilerStatusCode + { + NotNormalized, + MemberNotFound + } +} diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs b/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs index b3089c12..3f4c1fb6 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/ScriptCompilerBase.cs @@ -25,7 +25,7 @@ protected string[] GetStandardOutput() { return this.process.GetStandardOutput(); } - protected bool CompilingForMetro() + protected bool CompilingForWSA() { return this._island._target == BuildTarget.MetroPlayer; } diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs index b314915c..84901a7a 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/SupportedLanguage.cs @@ -5,7 +5,7 @@ internal abstract class SupportedLanguage { public abstract string GetExtensionICanCompile(); public abstract string GetLanguageName(); - public abstract ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform); + public abstract ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater); public virtual string GetNamespace(string fileName) { return string.Empty; diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs index 40db7af2..52dbbcc7 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptCompiler.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using UnityEditor.Utils; using UnityEngineInternal; @@ -9,7 +10,7 @@ namespace UnityEditor.Scripting.Compilers internal class UnityScriptCompiler : MonoScriptCompilerBase { private static readonly Regex UnityEditorPattern = new Regex("UnityEditor\\.dll$", RegexOptions.ExplicitCapture); - public UnityScriptCompiler(MonoIsland island) : base(island) + public UnityScriptCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } protected override CompilerOutputParserBase CreateOutputParser() @@ -35,16 +36,14 @@ protected override Program StartCompiler() { list.Add("-pragmas:strict,downcast"); } - string[] defines = this._island._defines; - for (int i = 0; i < defines.Length; i++) + foreach (string current in this._island._defines.Distinct()) { - string str = defines[i]; - list.Add("-define:" + str); + list.Add("-define:" + current); } string[] references = this._island._references; - for (int j = 0; j < references.Length; j++) + for (int i = 0; i < references.Length; i++) { - string fileName = references[j]; + string fileName = references[i]; list.Add("-r:" + ScriptCompilerBase.PrepareFileName(fileName)); } bool flag = Array.Exists(this._island._references, new Predicate(UnityScriptCompiler.UnityEditorPattern.IsMatch)); @@ -60,9 +59,9 @@ protected override Program StartCompiler() } } string[] files = this._island._files; - for (int k = 0; k < files.Length; k++) + for (int j = 0; j < files.Length; j++) { - string fileName2 = files[k]; + string fileName2 = files[j]; list.Add(ScriptCompilerBase.PrepareFileName(fileName2)); } string compiler = Path.Combine(base.GetProfileDirectory(), "us.exe"); diff --git a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs index 198c3efc..3caadfb0 100644 --- a/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs +++ b/UnityEditor/UnityEditor.Scripting.Compilers/UnityScriptLanguage.cs @@ -11,9 +11,9 @@ public override string GetLanguageName() { return "UnityScript"; } - public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) { - return new UnityScriptCompiler(island); + return new UnityScriptCompiler(island, runUpdater); } } } diff --git a/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs b/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs index b27effed..bb5fdc3c 100644 --- a/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs +++ b/UnityEditor/UnityEditor.Scripting.Serialization/Weaver.cs @@ -21,6 +21,11 @@ where Weaver.ShouldWeave(Path.GetFileName(f)) Weaver.WeaveInto(current, current, unityEngine, playerPackage); } } + public static bool WeaveUnetFromEditor(string assemblyPath, string destPath, string unityEngine, string unityUNet) + { + Console.WriteLine("WeaveUnetFromEditor " + assemblyPath); + return Weaver.WeaveUNetInto(assemblyPath, assemblyPath, unityEngine, unityUNet); + } public static void WeaveInto(string assemblyPath, string destPath, string unityEngine, string playerPackage) { string arguments = Weaver.CommandLineArgsFor(assemblyPath, destPath, unityEngine); @@ -42,6 +47,89 @@ public static void WeaveInto(string assemblyPath, string destPath, string unityE } } } + public static bool WeaveUNetInto(string assemblyPath, string destPath, string unityEngine, string unityUNet) + { + string text = Weaver.CommandLineArgsFor(assemblyPath, destPath, unityEngine); + text = text + " -unity-unet=" + unityUNet; + string frameWorksFolder = MonoInstallationFinder.GetFrameWorksFolder(); + Console.Write(string.Concat(new string[] + { + "WeaveUNetInto ", + assemblyPath, + " using ", + frameWorksFolder, + "/UNetWeaver/UNetWeaver.exe ", + text + })); + bool result; + using (ManagedProgram managedProgram = Weaver.UNetWeaverProgramWith(text, frameWorksFolder)) + { + try + { + managedProgram.Start(); + } + catch + { + managedProgram.LogProcessStartInfo(); + throw new Exception("Could not start UNetWeaver.exe"); + } + managedProgram.WaitForExit(); + Console.Write(managedProgram.GetAllOutput()); + if (managedProgram.ExitCode == 0) + { + string allOutput = managedProgram.GetAllOutput(); + string text2 = "COMPILE_WARNING "; + string[] array = allOutput.Split(new char[] + { + '\n' + }); + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text3 = array2[i]; + if (text3.Length >= text2.Length) + { + if (text3.Substring(0, text2.Length) == text2) + { + string msg = text3.Substring(text2.Length); + EditorApplication.ReportUNetWeaver("file", msg, false); + } + } + } + result = true; + } + else + { + string allOutput2 = managedProgram.GetAllOutput(); + string text4 = "COMPILE_ERROR "; + string text5 = "COMPILE_WARNING "; + string[] array3 = allOutput2.Split(new char[] + { + '\n' + }); + string[] array4 = array3; + for (int j = 0; j < array4.Length; j++) + { + string text6 = array4[j]; + if (text6.Length >= text5.Length) + { + if (text6.Substring(0, text4.Length) == text4) + { + string msg2 = text6.Substring(text4.Length); + EditorApplication.ReportUNetWeaver("file", msg2, true); + } + if (text6.Substring(0, text5.Length) == text5) + { + string msg3 = text6.Substring(text5.Length); + EditorApplication.ReportUNetWeaver("file", msg3, false); + } + } + } + result = false; + } + } + return result; + } private static string CommandLineArgsFor(string assemblyPath, string destPath, string unityEngine) { return string.Concat(new string[] @@ -58,6 +146,10 @@ private static ManagedProgram SerializationWeaverProgramWith(string arguments, s { return Weaver.ManagedProgramFor(playerPackage + "/SerializationWeaver/SerializationWeaver.exe", arguments); } + private static ManagedProgram UNetWeaverProgramWith(string arguments, string playerPackage) + { + return Weaver.ManagedProgramFor(playerPackage + "/UNetWeaver/UNetWeaver.exe", arguments); + } private static ManagedProgram ManagedProgramFor(string exe, string arguments) { return new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", exe, arguments); diff --git a/UnityEditor/UnityEditor.Scripting/APIUpdaterHelper.cs b/UnityEditor/UnityEditor.Scripting/APIUpdaterHelper.cs new file mode 100644 index 00000000..ab5717d2 --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/APIUpdaterHelper.cs @@ -0,0 +1,139 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using UnityEditor.Scripting.Compilers; +using UnityEditor.Utils; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor.Scripting +{ + internal class APIUpdaterHelper + { + public static bool IsReferenceToMissingObsoleteMember(string namespaceName, string className) + { + Type type = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly a) => a.GetTypes()).FirstOrDefault((Type t) => t.Name == className && t.Namespace == namespaceName && APIUpdaterHelper.IsUpdateable(t)); + return type != null; + } + public static void Run(string commaSeparatedListOfAssemblies) + { + string[] array = commaSeparatedListOfAssemblies.Split(new char[] + { + ',' + }, StringSplitOptions.RemoveEmptyEntries); + APIUpdaterLogger.WriteToFile("Started to update {0} assemblie(s)", new object[] + { + array.Count() + }); + Stopwatch stopwatch = new Stopwatch(); + stopwatch.Start(); + string[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + string text = array2[i]; + if (InternalEditorUtility.DetectDotNetDll(text)) + { + string text2 = APIUpdaterHelper.ResolveAssemblyPath(text); + string text3; + string text4; + int num = APIUpdaterHelper.RunUpdatingProgram("AssemblyUpdater.exe", "-u -a " + text2 + APIUpdaterHelper.APIVersionArgument() + APIUpdaterHelper.AssemblySearchPathArgument(), out text3, out text4); + if (text3.Length > 0) + { + APIUpdaterLogger.WriteToFile("Assembly update output ({0})\r\n{1}", new object[] + { + text2, + text3 + }); + } + if (num < 0) + { + APIUpdaterLogger.WriteErrorToConsole("Error {0} running AssemblyUpdater. Its output is: `{1}`", new object[] + { + num, + text4 + }); + } + } + } + APIUpdaterLogger.WriteToFile("Update finished in {0}s", new object[] + { + stopwatch.Elapsed.TotalSeconds + }); + } + private static string ResolveAssemblyPath(string assemblyPath) + { + return CommandLineFormatter.PrepareFileName(assemblyPath); + } + public static bool DoesAssemblyRequireUpgrade(string assetFullPath) + { + if (!File.Exists(assetFullPath)) + { + return false; + } + if (!InternalEditorUtility.DetectDotNetDll(assetFullPath)) + { + return false; + } + string text; + string text2; + int num = APIUpdaterHelper.RunUpdatingProgram("AssemblyUpdater.exe", string.Concat(new string[] + { + APIUpdaterHelper.TimeStampArgument(), + APIUpdaterHelper.APIVersionArgument(), + "--check-update-required -a ", + CommandLineFormatter.PrepareFileName(assetFullPath), + APIUpdaterHelper.AssemblySearchPathArgument() + }), out text, out text2); + Console.WriteLine("{0}{1}", text, text2); + switch (num) + { + case 0: + case 1: + return false; + case 2: + return true; + default: + UnityEngine.Debug.LogError(text + Environment.NewLine + text2); + return false; + } + } + private static string AssemblySearchPathArgument() + { + return " -s " + CommandLineFormatter.PrepareFileName(APIUpdaterHelper.GetUnityEngineDLLPath()) + ",+" + CommandLineFormatter.PrepareFileName(Application.dataPath); + } + private static string GetUnityEngineDLLPath() + { + return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Managed"); + } + private static int RunUpdatingProgram(string executable, string arguments, out string stdOut, out string stdErr) + { + string executable2 = EditorApplication.applicationContentsPath + "/Tools/ScriptUpdater/" + executable; + ManagedProgram managedProgram = new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), "4.0", executable2, arguments); + managedProgram.LogProcessStartInfo(); + managedProgram.Start(); + managedProgram.WaitForExit(); + stdOut = managedProgram.GetStandardOutputAsString(); + stdErr = string.Join("\r\n", managedProgram.GetErrorOutput()); + return managedProgram.ExitCode; + } + private static string APIVersionArgument() + { + return " --api-version " + Application.unityVersion + " "; + } + private static string TimeStampArgument() + { + return " --timestamp " + DateTime.Now.Ticks + " "; + } + private static bool IsUpdateable(Type type) + { + object[] customAttributes = type.GetCustomAttributes(typeof(ObsoleteAttribute), false); + if (customAttributes.Length != 1) + { + return false; + } + ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute)customAttributes[0]; + return obsoleteAttribute.Message.Contains("UnityUpgradable"); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/APIUpdaterLogger.cs b/UnityEditor/UnityEditor.Scripting/APIUpdaterLogger.cs new file mode 100644 index 00000000..7d97d23d --- /dev/null +++ b/UnityEditor/UnityEditor.Scripting/APIUpdaterLogger.cs @@ -0,0 +1,20 @@ +using System; +using UnityEngine; +namespace UnityEditor.Scripting +{ + internal class APIUpdaterLogger + { + public static void WriteToFile(string msg, params object[] args) + { + Console.WriteLine("[Script API Updater] {0}", string.Format(msg, args)); + } + public static void WriteErrorToConsole(string msg, params object[] args) + { + Debug.LogErrorFormat(msg, args); + } + public static void WriteInfoToConsole(string line) + { + Debug.Log(line); + } + } +} diff --git a/UnityEditor/UnityEditor.Scripting/MonoIsland.cs b/UnityEditor/UnityEditor.Scripting/MonoIsland.cs index be85a31d..5ef60164 100644 --- a/UnityEditor/UnityEditor.Scripting/MonoIsland.cs +++ b/UnityEditor/UnityEditor.Scripting/MonoIsland.cs @@ -20,7 +20,7 @@ public MonoIsland(BuildTarget target, string classlib_profile, string[] files, s } public string GetExtensionOfSourceFiles() { - return ScriptCompilers.GetExtensionOfSourceFile(this._files[0]); + return (this._files.Length <= 0) ? "NA" : ScriptCompilers.GetExtensionOfSourceFile(this._files[0]); } } } diff --git a/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs b/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs index 1a8495c5..589a8ee3 100644 --- a/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs +++ b/UnityEditor/UnityEditor.Scripting/PragmaFixing30.cs @@ -92,12 +92,12 @@ private static bool HasWinLineEndings(string text) [DebuggerHidden] private static IEnumerable SearchRecursive(string dir, string mask) { - PragmaFixing30.c__Iterator4 c__Iterator = new PragmaFixing30.c__Iterator4(); + PragmaFixing30.c__Iterator6 c__Iterator = new PragmaFixing30.c__Iterator6(); c__Iterator.dir = dir; c__Iterator.mask = mask; c__Iterator.<$>dir = dir; c__Iterator.<$>mask = mask; - PragmaFixing30.c__Iterator4 expr_23 = c__Iterator; + PragmaFixing30.c__Iterator6 expr_23 = c__Iterator; expr_23.$PC = -2; return expr_23; } diff --git a/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs b/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs index e60ea62e..3ee55de6 100644 --- a/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs +++ b/UnityEditor/UnityEditor.Scripting/ScriptCompilers.cs @@ -47,7 +47,7 @@ internal static string GetNamespace(string file) } throw new ApplicationException("Unable to find a suitable compiler"); } - internal static ScriptCompilerBase CreateCompilerInstance(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform) + internal static ScriptCompilerBase CreateCompilerInstance(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) { if (island._files.Length == 0) { @@ -57,10 +57,10 @@ internal static ScriptCompilerBase CreateCompilerInstance(MonoIsland island, boo { if (current.GetExtensionICanCompile() == island.GetExtensionOfSourceFiles()) { - return current.CreateCompiler(island, buildingForEditor, targetPlatform); + return current.CreateCompiler(island, buildingForEditor, targetPlatform, runUpdater); } } - throw new ApplicationException("Unable to find a suitable compiler"); + throw new ApplicationException(string.Format("Unable to find a suitable compiler for sources with extension '{0}' (Output assembly: {1})", island.GetExtensionOfSourceFiles(), island._output)); } public static string GetExtensionOfSourceFile(string file) { diff --git a/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs b/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs index e7af954b..f8202788 100644 --- a/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs +++ b/UnityEditor/UnityEditor.Sprites/AtlasSettings.cs @@ -5,7 +5,6 @@ namespace UnityEditor.Sprites public struct AtlasSettings { public TextureFormat format; - public TextureUsageMode usageMode; public ColorSpace colorSpace; public int compressionQuality; public FilterMode filterMode; diff --git a/UnityEditor/UnityEditor.Sprites/DataUtility.cs b/UnityEditor/UnityEditor.Sprites/DataUtility.cs index 4301e5cb..a512403e 100644 --- a/UnityEditor/UnityEditor.Sprites/DataUtility.cs +++ b/UnityEditor/UnityEditor.Sprites/DataUtility.cs @@ -1,31 +1,8 @@ using System; -using System.Runtime.CompilerServices; -using UnityEngine; namespace UnityEditor.Sprites { + [Obsolete("Use UnityEditor.Sprites.SpriteUtility instead (UnityUpgradable)", true)] public sealed class DataUtility { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Texture2D GetSpriteTexture(Sprite sprite, bool getAtlasData); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Vector2[] GetSpriteMesh(Sprite sprite, bool getAtlasData); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Vector2[] GetSpriteUVs(Sprite sprite, bool getAtlasData); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern ushort[] GetSpriteIndices(Sprite sprite, bool getAtlasData); - internal static void GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) - { - DataUtility.INTERNAL_CALL_GenerateOutline(texture, ref rect, detail, alphaTolerance, holeDetection, out paths); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_GenerateOutline(Texture2D texture, ref Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void GenerateOutlineFromSprite(Sprite sprite, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); } } diff --git a/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs b/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs index 6570f3a9..1312974e 100644 --- a/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs +++ b/UnityEditor/UnityEditor.Sprites/DefaultPackerPolicy.cs @@ -40,8 +40,10 @@ public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImpor { int instanceID = textureImporterInstanceIDs[i]; TextureImporter textureImporter = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; - TextureImportInstructions textureImportInstructions = new TextureImportInstructions(); - textureImporter.ReadTextureImportInstructions(textureImportInstructions, target); + TextureFormat format; + ColorSpace colorSpace; + int compressionQuality; + textureImporter.ReadTextureImportInstructions(target, out format, out colorSpace, out compressionQuality); TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(textureImporterSettings); Sprite[] array = ( @@ -55,10 +57,9 @@ select x as Sprite into x Sprite sprite = array2[j]; DefaultPackerPolicy.Entry entry = new DefaultPackerPolicy.Entry(); entry.sprite = sprite; - entry.settings.format = textureImportInstructions.desiredFormat; - entry.settings.usageMode = textureImportInstructions.usageMode; - entry.settings.colorSpace = textureImportInstructions.colorSpace; - entry.settings.compressionQuality = textureImportInstructions.compressionQuality; + entry.settings.format = format; + entry.settings.colorSpace = colorSpace; + entry.settings.compressionQuality = compressionQuality; entry.settings.filterMode = ((!Enum.IsDefined(typeof(FilterMode), textureImporter.filterMode)) ? FilterMode.Bilinear : textureImporter.filterMode); entry.settings.maxWidth = 2048; entry.settings.maxHeight = 2048; diff --git a/UnityEditor/UnityEditor.Sprites/Packer.cs b/UnityEditor/UnityEditor.Sprites/Packer.cs index 64c1434b..e97b6d2b 100644 --- a/UnityEditor/UnityEditor.Sprites/Packer.cs +++ b/UnityEditor/UnityEditor.Sprites/Packer.cs @@ -18,6 +18,12 @@ public enum Execution private static string[] m_policies = null; private static string m_selectedPolicy = null; private static Dictionary m_policyTypeCache = null; + public static extern string[] atlasNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static string[] Policies { get @@ -47,12 +53,28 @@ public static string SelectedPolicy Packer.SetSelectedPolicy(value); } } - public static extern string[] atlasNames + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D[] GetTexturesForAtlas(string atlasName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RebuildAtlasCacheIfNeeded(BuildTarget target, [DefaultValue("false")] bool displayProgressBar, [DefaultValue("Execution.Normal")] Packer.Execution execution); + [ExcludeFromDocs] + public static void RebuildAtlasCacheIfNeeded(BuildTarget target, bool displayProgressBar) { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + Packer.Execution execution = Packer.Execution.Normal; + Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); + } + [ExcludeFromDocs] + public static void RebuildAtlasCacheIfNeeded(BuildTarget target) + { + Packer.Execution execution = Packer.Execution.Normal; + bool displayProgressBar = false; + Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetAtlasDataForSprite(Sprite sprite, out string atlasName, [Writable] out Texture2D atlasTexture); private static void SetSelectedPolicy(string value) { Packer.m_selectedPolicy = value; @@ -83,9 +105,9 @@ private static void RegenerateList() } } } - catch (Exception) + catch (Exception ex) { - Debug.Log(string.Format("SpritePacker failed to get types from {0}.", assembly.FullName)); + Debug.Log(string.Format("SpritePacker failed to get types from {0}. Error: {1}", assembly.FullName, ex.Message)); } } Packer.m_policies = ( @@ -151,27 +173,5 @@ internal static void SaveUnappliedTextureImporterSettings() } } } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Texture2D[] GetTexturesForAtlas(string atlasName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void RebuildAtlasCacheIfNeeded(BuildTarget target, [DefaultValue("false")] bool displayProgressBar, [DefaultValue("Execution.Normal")] Packer.Execution execution); - [ExcludeFromDocs] - public static void RebuildAtlasCacheIfNeeded(BuildTarget target, bool displayProgressBar) - { - Packer.Execution execution = Packer.Execution.Normal; - Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); - } - [ExcludeFromDocs] - public static void RebuildAtlasCacheIfNeeded(BuildTarget target) - { - Packer.Execution execution = Packer.Execution.Normal; - bool displayProgressBar = false; - Packer.RebuildAtlasCacheIfNeeded(target, displayProgressBar, execution); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void GetAtlasDataForSprite(Sprite sprite, out string atlasName, [Writable] out Texture2D atlasTexture); } } diff --git a/UnityEditor/UnityEditor.Sprites/PackerWindow.cs b/UnityEditor/UnityEditor.Sprites/PackerWindow.cs index d03837c2..8ca0b4e0 100644 --- a/UnityEditor/UnityEditor.Sprites/PackerWindow.cs +++ b/UnityEditor/UnityEditor.Sprites/PackerWindow.cs @@ -111,9 +111,13 @@ private bool ValidateIsPackingEnabled() { if (EditorSettings.spritePackerMode == SpritePackerMode.Disabled) { - EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.Label("Sprite packing is disabled. Enable it in Project EditorSettings.", new GUILayoutOption[0]); - EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label("Sprite packing is disabled. Enable it in Edit > Project Settings > Editor.", new GUILayoutOption[0]); + if (GUILayout.Button("Open Project Editor Settings", new GUILayoutOption[0])) + { + EditorApplication.ExecuteMenuItem("Edit/Project Settings/Editor"); + } + EditorGUILayout.EndVertical(); return false; } return true; @@ -291,9 +295,9 @@ protected override void DrawGizmos() { if (this.m_SelectedSprite != null && this.m_Texture != null) { - Vector2[] spriteUVs = DataUtility.GetSpriteUVs(this.m_SelectedSprite, true); - ushort[] spriteIndices = DataUtility.GetSpriteIndices(this.m_SelectedSprite, true); - PackerWindow.Edge[] array = this.FindUniqueEdges(spriteIndices); + Vector2[] spriteUVs = SpriteUtility.GetSpriteUVs(this.m_SelectedSprite, true); + ushort[] triangles = this.m_SelectedSprite.triangles; + PackerWindow.Edge[] array = this.FindUniqueEdges(triangles); SpriteEditorUtility.BeginLines(new Color(0.3921f, 0.5843f, 0.9294f, 0.75f)); PackerWindow.Edge[] array2 = array; for (int i = 0; i < array2.Length; i++) diff --git a/UnityEditor/UnityEditor.Sprites/SpriteUtility.cs b/UnityEditor/UnityEditor.Sprites/SpriteUtility.cs new file mode 100644 index 00000000..e00b3a67 --- /dev/null +++ b/UnityEditor/UnityEditor.Sprites/SpriteUtility.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor.Sprites +{ + public sealed class SpriteUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetSpriteTexture(Sprite sprite, bool getAtlasData); + [Obsolete("Use Sprite.vertices API instead. This data is the same for packed and unpacked sprites.")] + public static Vector2[] GetSpriteMesh(Sprite sprite, bool getAtlasData) + { + return sprite.vertices; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector2[] GetSpriteUVs(Sprite sprite, bool getAtlasData); + [Obsolete("Use Sprite.triangles API instead. This data is the same for packed and unpacked sprites.")] + public static ushort[] GetSpriteIndices(Sprite sprite, bool getAtlasData) + { + return sprite.triangles; + } + internal static void GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) + { + SpriteUtility.INTERNAL_CALL_GenerateOutline(texture, ref rect, detail, alphaTolerance, holeDetection, out paths); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_GenerateOutline(Texture2D texture, ref Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void GenerateOutlineFromSprite(Sprite sprite, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); + } +} diff --git a/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs b/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs index 4c2509ef..d3958bf6 100644 --- a/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs +++ b/UnityEditor/UnityEditor.Utils/MonoInstallationFinder.cs @@ -7,20 +7,21 @@ internal class MonoInstallationFinder { public static string GetFrameWorksFolder() { + string text = FileUtil.NiceWinPath(EditorApplication.applicationPath); if (Application.platform == RuntimePlatform.WindowsEditor) { - return Path.GetDirectoryName(EditorApplication.applicationPath) + "/Data/"; + return Path.Combine(Path.GetDirectoryName(text), "Data"); } if (Application.platform == RuntimePlatform.OSXEditor) { - return EditorApplication.applicationPath + "/Contents/Frameworks/"; + return Path.Combine(text, Path.Combine("Contents", "Frameworks")); } - return Path.GetDirectoryName(EditorApplication.applicationPath) + "/Data/"; + return Path.Combine(Path.GetDirectoryName(text), "Data"); } public static string GetProfileDirectory(BuildTarget target, string profile) { string monoInstallation = MonoInstallationFinder.GetMonoInstallation(); - return Path.Combine(monoInstallation, "lib/mono/" + profile); + return Path.Combine(monoInstallation, Path.Combine("lib", Path.Combine("mono", profile))); } public static string GetMonoInstallation() { diff --git a/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs b/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs index ab90e67c..c9c3c603 100644 --- a/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs +++ b/UnityEditor/UnityEditor.Utils/PerformanceChecks.cs @@ -4,7 +4,7 @@ namespace UnityEditor.Utils { internal class PerformanceChecks { - private static string[] kShadersWithMobileVariants = new string[] + private static readonly string[] kShadersWithMobileVariants = new string[] { "VertexLit", "Diffuse", @@ -18,9 +18,9 @@ internal class PerformanceChecks }; private static bool IsMobileBuildTarget(BuildTarget target) { - return target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.Tizen; + return target == BuildTarget.iOS || target == BuildTarget.Android || target == BuildTarget.Tizen; } - private static string FormattedTextContent(string localeString, params string[] args) + private static string FormattedTextContent(string localeString, params object[] args) { GUIContent gUIContent = EditorGUIUtility.TextContent(localeString); return string.Format(gUIContent.text, args); @@ -37,48 +37,51 @@ public static string CheckMaterial(Material mat, BuildTarget buildTarget) bool flag2 = PerformanceChecks.IsMobileBuildTarget(buildTarget); if (buildTarget == BuildTarget.Android && ShaderUtil.HasClip(mat.shader)) { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderWithClipAndroid", new string[0]); + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderWithClipAndroid", new object[0]); } - if (flag) + if (!(mat.GetTag("PerformanceChecks", true).ToLower() == "false")) { - if (flag2 && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1f, 1f, 1f, 1f)) + if (flag) { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUsesWhiteColor", new string[] + if (flag2 && mat.HasProperty("_Color") && mat.GetColor("_Color") == new Color(1f, 1f, 1f, 1f)) { - "Mobile/" + shaderName - }); + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUsesWhiteColor", new object[] + { + "Mobile/" + shaderName + }); + } + if (flag2 && shaderName.StartsWith("Particles/")) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderHasMobileVariant", new object[] + { + "Mobile/" + shaderName + }); + } + if (shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) + { + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderMobileSkybox", new object[] + { + "Mobile/Skybox" + }); + } } - if (flag2 && shaderName.StartsWith("Particles/")) + if (lOD >= 300 && flag2 && !shaderName.StartsWith("Mobile/")) { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderHasMobileVariant", new string[] - { - "Mobile/" + shaderName - }); + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderExpensive", new object[0]); } - if (shaderName == "RenderFX/Skybox" && mat.HasProperty("_Tint") && mat.GetColor("_Tint") == new Color(0.5f, 0.5f, 0.5f, 0.5f)) + if (shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderMobileSkybox", new string[] + Color color = mat.GetColor("_Emission"); + if (color.r >= 0.5f && color.g >= 0.5f && color.b >= 0.5f) { - "Mobile/Skybox" - }); + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUseUnlit", new object[0]); + } } - } - if (lOD >= 300 && flag2 && !shaderName.StartsWith("Mobile/")) - { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderExpensive", new string[0]); - } - if (shaderName.Contains("VertexLit") && mat.HasProperty("_Emission")) - { - Color color = mat.GetColor("_Emission"); - if (color.r >= 0.5f && color.g >= 0.5f && color.b >= 0.5f) + if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") == null) { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderUseUnlit", new string[0]); + return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderNoNormalMap", new object[0]); } } - if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") == null) - { - return PerformanceChecks.FormattedTextContent("PerformanceChecks.ShaderNoNormalMap", new string[0]); - } return null; } } diff --git a/UnityEditor/UnityEditor.Utils/Program.cs b/UnityEditor/UnityEditor.Utils/Program.cs index 07e3969a..090924d0 100644 --- a/UnityEditor/UnityEditor.Utils/Program.cs +++ b/UnityEditor/UnityEditor.Utils/Program.cs @@ -102,7 +102,7 @@ private static void LogProcessStartInfo(ProcessStartInfo si) public string GetAllOutput() { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.AppendLine("stdout;"); + stringBuilder.AppendLine("stdout:"); string[] standardOutput = this.GetStandardOutput(); for (int i = 0; i < standardOutput.Length; i++) { diff --git a/UnityEditor/UnityEditor.VersionControl/Asset.cs b/UnityEditor/UnityEditor.VersionControl/Asset.cs index cc0eb12d..df6acd56 100644 --- a/UnityEditor/UnityEditor.VersionControl/Asset.cs +++ b/UnityEditor/UnityEditor.VersionControl/Asset.cs @@ -27,20 +27,6 @@ public enum States MetaFile = 32768 } private string m_guid; - internal bool IsUnderVersionControl - { - get - { - return this.IsState(Asset.States.Synced) || this.IsState(Asset.States.OutOfSync) || this.IsState(Asset.States.AddedLocal); - } - } - public string prettyPath - { - get - { - return this.path; - } - } public extern Asset.States state { [WrapperlessIcall] @@ -95,10 +81,37 @@ public extern bool isInCurrentProject [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal bool IsUnderVersionControl + { + get + { + return this.IsState(Asset.States.Synced) || this.IsState(Asset.States.OutOfSync) || this.IsState(Asset.States.AddedLocal); + } + } + public string prettyPath + { + get + { + return this.path; + } + } public Asset(string clientPath) { this.InternalCreateFromString(clientPath); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InternalCreateFromString(string clientPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Asset() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsChildOf(Asset other); internal static bool IsState(Asset.States isThisState, Asset.States partOfThisState) { return (isThisState & partOfThisState) != Asset.States.None; @@ -187,18 +200,5 @@ internal string StateToString() { return Asset.StateToString(this.state); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void InternalCreateFromString(string clientPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Dispose(); - ~Asset() - { - this.Dispose(); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern bool IsChildOf(Asset other); } } diff --git a/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs b/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs index 0a8d94c8..e8f92893 100644 --- a/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs +++ b/UnityEditor/UnityEditor.VersionControl/ChangeSet.cs @@ -34,10 +34,6 @@ public ChangeSet(ChangeSet other) { this.InternalCopyConstruct(other); } - ~ChangeSet() - { - this.Dispose(); - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void InternalCreate(); @@ -53,5 +49,9 @@ public ChangeSet(ChangeSet other) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void Dispose(); + ~ChangeSet() + { + this.Dispose(); + } } } diff --git a/UnityEditor/UnityEditor.VersionControl/Message.cs b/UnityEditor/UnityEditor.VersionControl/Message.cs index 66115bf4..fee418aa 100644 --- a/UnityEditor/UnityEditor.VersionControl/Message.cs +++ b/UnityEditor/UnityEditor.VersionControl/Message.cs @@ -27,6 +27,13 @@ public extern string message [MethodImpl(MethodImplOptions.InternalCall)] get; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Dispose(); + ~Message() + { + this.Dispose(); + } public void Show() { Message.Info(this.message); @@ -35,12 +42,5 @@ private static void Info(string message) { Debug.Log("Version control:\n" + message); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Dispose(); - ~Message() - { - this.Dispose(); - } } } diff --git a/UnityEditor/UnityEditor.VersionControl/Provider.cs b/UnityEditor/UnityEditor.VersionControl/Provider.cs index ae0e694b..812e3ab8 100644 --- a/UnityEditor/UnityEditor.VersionControl/Provider.cs +++ b/UnityEditor/UnityEditor.VersionControl/Provider.cs @@ -65,6 +65,156 @@ internal static extern CustomCommand[] customCommands [MethodImpl(MethodImplOptions.InternalCall)] get; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect GetAtlasRectForState(int state); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Plugin GetActivePlugin(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ConfigField[] GetActiveConfigFields(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsCustomCommandEnabled(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Asset Internal_CacheStatus(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Status(Asset[] assets, bool recursively); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_StatusStrings(string[] assetsProjectPaths, bool recursively); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_StatusAbsolutePath(string assetPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_CheckoutIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Checkout(Asset[] assets, CheckoutMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_CheckoutStrings(string[] assets, CheckoutMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_PromptAndCheckoutIfNeeded(string[] assets, string promptIfCheckoutIsNeeded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Delete(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DeleteAtProjectPath(string assetProjectPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_MoveAsStrings(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_AddIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Add(Asset[] assets, bool recursive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_DeleteChangeSetsIsValid(ChangeSet[] changes); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DeleteChangeSets(ChangeSet[] changesets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_RevertChangeSets(ChangeSet[] changesets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_SubmitIsValid(ChangeSet changeset, Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Submit(ChangeSet changeset, Asset[] assets, string description, bool saveOnly); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_DiffIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_DiffHead(Asset[] assets, bool includingMetaFiles); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_ResolveIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Resolve(Asset[] assets, ResolveMethod resolveMethod); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Merge(Asset[] assets, MergeMethod method); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_LockIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_UnlockIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Lock(Asset[] assets, bool locked); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_RevertIsValid(Asset[] assets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_Revert(Asset[] assets, RevertMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Internal_GetLatestIsValid(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_GetLatest(Asset[] assets); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_SetFileMode(Asset[] assets, FileMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_SetFileModeStrings(string[] assets, FileMode mode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetDescription(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetStatus(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task ChangeSets(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_ChangeSetMove(Asset[] assets, ChangeSet target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task Incoming(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Task Internal_IncomingChangeSetAssets(ChangeSet changeset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsOpenForEdit(Asset asset); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Task UpdateSettings(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Asset GetAssetByPath(string unityPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Asset GetAssetByGUID(string guid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Asset[] Internal_GetAssetArrayFromSelection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GenerateID(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearCache(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InvalidateCache(); internal static Asset CacheStatus(string assetPath) { return Provider.Internal_CacheStatus(assetPath); @@ -390,155 +540,5 @@ public static AssetList GetAssetListFromSelection() } return assetList; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Rect GetAtlasRectForState(int state); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Plugin GetActivePlugin(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern ConfigField[] GetActiveConfigFields(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool IsCustomCommandEnabled(string name); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Asset Internal_CacheStatus(string assetPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Status(Asset[] assets, bool recursively); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_StatusStrings(string[] assetsProjectPaths, bool recursively); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_StatusAbsolutePath(string assetPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_CheckoutIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Checkout(Asset[] assets, CheckoutMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_CheckoutStrings(string[] assets, CheckoutMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_PromptAndCheckoutIfNeeded(string[] assets, string promptIfCheckoutIsNeeded); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Delete(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_DeleteAtProjectPath(string assetProjectPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_MoveAsStrings(string from, string to); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_AddIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Add(Asset[] assets, bool recursive); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_DeleteChangeSetsIsValid(ChangeSet[] changes); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_DeleteChangeSets(ChangeSet[] changesets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_RevertChangeSets(ChangeSet[] changesets, RevertMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_SubmitIsValid(ChangeSet changeset, Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Submit(ChangeSet changeset, Asset[] assets, string description, bool saveOnly); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_DiffIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_DiffHead(Asset[] assets, bool includingMetaFiles); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_ResolveIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Resolve(Asset[] assets, ResolveMethod resolveMethod); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Merge(Asset[] assets, MergeMethod method); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_LockIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_UnlockIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Lock(Asset[] assets, bool locked); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_RevertIsValid(Asset[] assets, RevertMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_Revert(Asset[] assets, RevertMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Internal_GetLatestIsValid(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_GetLatest(Asset[] assets); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_SetFileMode(Asset[] assets, FileMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_SetFileModeStrings(string[] assets, FileMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_ChangeSetDescription(ChangeSet changeset); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_ChangeSetStatus(ChangeSet changeset); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Task ChangeSets(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_ChangeSetMove(Asset[] assets, ChangeSet target); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Task Incoming(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Task Internal_IncomingChangeSetAssets(ChangeSet changeset); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsOpenForEdit(Asset asset); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Task UpdateSettings(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Asset GetAssetByPath(string unityPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Asset GetAssetByGUID(string guid); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Asset[] Internal_GetAssetArrayFromSelection(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GenerateID(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ClearCache(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void InvalidateCache(); } } diff --git a/UnityEditor/UnityEditor.VersionControl/Task.cs b/UnityEditor/UnityEditor.VersionControl/Task.cs index 8fcdc744..d35007a2 100644 --- a/UnityEditor/UnityEditor.VersionControl/Task.cs +++ b/UnityEditor/UnityEditor.VersionControl/Task.cs @@ -6,36 +6,6 @@ namespace UnityEditor.VersionControl public sealed class Task { private IntPtr m_thisDummy; - public AssetList assetList - { - get - { - AssetList assetList = new AssetList(); - Asset[] array = this.Internal_GetAssetList(); - Asset[] array2 = array; - for (int i = 0; i < array2.Length; i++) - { - Asset item = array2[i]; - assetList.Add(item); - } - return assetList; - } - } - public ChangeSets changeSets - { - get - { - ChangeSets changeSets = new ChangeSets(); - ChangeSet[] array = this.Internal_GetChangeSets(); - ChangeSet[] array2 = array; - for (int i = 0; i < array2.Length; i++) - { - ChangeSet item = array2[i]; - changeSets.Add(item); - } - return changeSets; - } - } public extern int userIdentifier { [WrapperlessIcall] @@ -93,6 +63,36 @@ public extern Message[] messages [MethodImpl(MethodImplOptions.InternalCall)] get; } + public AssetList assetList + { + get + { + AssetList assetList = new AssetList(); + Asset[] array = this.Internal_GetAssetList(); + Asset[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + Asset item = array2[i]; + assetList.Add(item); + } + return assetList; + } + } + public ChangeSets changeSets + { + get + { + ChangeSets changeSets = new ChangeSets(); + ChangeSet[] array = this.Internal_GetChangeSets(); + ChangeSet[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + ChangeSet item = array2[i]; + changeSets.Add(item); + } + return changeSets; + } + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void Wait(); diff --git a/UnityEditor/UnityEditor.VersionControl/WindowChange.cs b/UnityEditor/UnityEditor.VersionControl/WindowChange.cs index a0faa198..5556a3e6 100644 --- a/UnityEditor/UnityEditor.VersionControl/WindowChange.cs +++ b/UnityEditor/UnityEditor.VersionControl/WindowChange.cs @@ -20,6 +20,7 @@ internal class WindowChange : EditorWindow private Task taskAdd; private int submitResultCode = 256; private string submitErrorMessage; + private int m_TextAreaControlID; public void OnEnable() { base.position = new Rect(100f, 100f, 700f, 395f); @@ -32,6 +33,10 @@ public void OnEnable() this.submitResultCode = 256; this.submitErrorMessage = null; } + public void OnDisable() + { + this.m_TextAreaControlID = 0; + } public static void Open(AssetList list, bool submit) { WindowChange.Open(null, list, submit); @@ -155,6 +160,11 @@ private void OnSubmitGUI() { GUI.enabled = false; } + Event current = Event.current; + if (current.isKey && current.keyCode == KeyCode.Escape) + { + base.Close(); + } GUILayout.Label("Description", EditorStyles.boldLabel, new GUILayoutOption[0]); if (this.taskStatus != null && this.taskStatus.resultCode != 0) { @@ -194,6 +204,15 @@ private void OnSubmitGUI() { GUILayout.Height(150f) }).Trim(); + if (this.m_TextAreaControlID == 0) + { + this.m_TextAreaControlID = EditorGUIUtility.s_LastControlID; + } + if (this.m_TextAreaControlID != 0) + { + GUIUtility.keyboardControl = this.m_TextAreaControlID; + EditorGUIUtility.editingTextField = true; + } GUI.enabled = true; GUILayout.Label("Files", EditorStyles.boldLabel, new GUILayoutOption[0]); GUILayout.FlexibleSpace(); @@ -231,7 +250,8 @@ private void OnSubmitGUI() { bool enabled = GUI.enabled; GUI.enabled = (this.assetList != null && this.assetList.Count > 0 && !string.IsNullOrEmpty(this.description)); - if (GUILayout.Button("Submit", new GUILayoutOption[0])) + bool flag2 = current.isKey && current.shift && current.keyCode == KeyCode.Return; + if (GUILayout.Button("Submit", new GUILayoutOption[0]) || flag2) { this.Save(true); } @@ -240,10 +260,10 @@ private void OnSubmitGUI() } else { - bool flag2 = (this.submitResultCode & 1) != 0; - GUI.enabled = flag2; + bool flag3 = (this.submitResultCode & 1) != 0; + GUI.enabled = flag3; string text = string.Empty; - if (flag2) + if (flag3) { text = "Finished successfully"; } diff --git a/UnityEditor/UnityEditor.VersionControl/WindowPending.cs b/UnityEditor/UnityEditor.VersionControl/WindowPending.cs index 38c17d7f..c7cac1e2 100644 --- a/UnityEditor/UnityEditor.VersionControl/WindowPending.cs +++ b/UnityEditor/UnityEditor.VersionControl/WindowPending.cs @@ -14,7 +14,6 @@ internal class Styles private const float k_MinIncomingAreaHeight = 50f; private const float k_BottomBarHeight = 17f; private static WindowPending.Styles s_Styles; - private static Texture2D submittedIcon; private static Texture2D changeIcon; private Texture2D syncIcon; private Texture2D refreshIcon; @@ -221,7 +220,7 @@ public static void CloseAllWindows() private void OnIncoming(Task task) { this.CreateStaticResources(); - this.PopulateListControl(this.incomingList, task, WindowPending.submittedIcon); + this.PopulateListControl(this.incomingList, task, this.syncIcon); } private void OnChangeSets(Task task) { @@ -465,9 +464,6 @@ private void CreateResources() this.refreshIcon.hideFlags = HideFlags.HideAndDontSave; this.refreshIcon.name = "RefreshIcon"; } - if (WindowPending.submittedIcon == null) - { - } if (this.header == null) { this.header = "OL Title"; @@ -485,7 +481,7 @@ private void CreateStaticResources() { if (this.syncIcon == null) { - this.syncIcon = EditorGUIUtility.LoadIcon("vcs_sync"); + this.syncIcon = EditorGUIUtility.LoadIcon("vcs_incoming"); this.syncIcon.hideFlags = HideFlags.HideAndDontSave; this.syncIcon.name = "SyncIcon"; } diff --git a/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs b/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs index e1f29e15..53a2928a 100644 --- a/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs +++ b/UnityEditor/UnityEditor.VersionControl/WindowResolve.cs @@ -110,10 +110,6 @@ private void OnGUI() { mergeMethod = MergeMethod.MergeAll; } - if (GUILayout.Button("merging non-conflicts", new GUILayoutOption[0])) - { - mergeMethod = MergeMethod.MergeNonConflicting; - } if (mergeMethod != MergeMethod.MergeNone) { Task task = Provider.Merge(this.resolveList.SelectedAssets, mergeMethod); diff --git a/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs b/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs deleted file mode 100644 index 19707149..00000000 --- a/UnityEditor/UnityEditor.WindowsStandalone/WindowsStandaloneIl2CppPlatformProvider.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.IO; -using UnityEditorInternal; -namespace UnityEditor.WindowsStandalone -{ - internal class WindowsStandaloneIl2CppPlatformProvider : BaseIl2CppPlatformProvider - { - private readonly bool m_DevelopmentBuild; - public override bool emitNullChecks - { - get - { - return this.m_DevelopmentBuild; - } - } - public override bool enableStackTraces - { - get - { - return this.m_DevelopmentBuild; - } - } - public override string nativeLibraryFileName - { - get - { - return "UserAssembly.dll"; - } - } - public override string staticLibraryExtension - { - get - { - return "lib"; - } - } - internal WindowsStandaloneIl2CppPlatformProvider(BuildTarget target, string dataFolder, bool developmentBuild) : base(target, Path.Combine(dataFolder, "Libraries")) - { - this.m_DevelopmentBuild = developmentBuild; - } - public override INativeCompiler CreateNativeCompiler() - { - BuildTarget target = this.target; - ICompilerSettings settings; - if (target != BuildTarget.StandaloneWindows) - { - if (target != BuildTarget.StandaloneWindows64) - { - throw new ArgumentException("Unexpected target: " + this.target); - } - settings = new MSVCCompilerSettingsx64(); - } - else - { - settings = new MSVCCompilerSettingsx86(); - } - return new MSVCCompiler(settings, base.GetFileInPackageOrDefault("libil2cpp/include/libil2cpp.def")); - } - } -} diff --git a/UnityEditor/UnityEditor.csproj b/UnityEditor/UnityEditor.csproj index 6e78a15b..ee8e3bad 100644 --- a/UnityEditor/UnityEditor.csproj +++ b/UnityEditor/UnityEditor.csproj @@ -1,14 +1,13 @@ - + - {A273AAF0-2CB5-491E-9C0D-D66717004282} + {9005D1E2-F526-4A43-9057-4798071329E3} Debug AnyCPU Library UnityEditor - v4.0 + v2.0 4 - AnyCPU @@ -27,10 +26,10 @@ + - - + @@ -45,35 +44,23 @@ - - - - - - - - - - - - @@ -100,29 +87,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + - + + + + + + @@ -132,7 +175,6 @@ - @@ -141,12 +183,16 @@ + + + + @@ -159,6 +205,7 @@ + @@ -193,7 +240,6 @@ - @@ -226,7 +272,6 @@ - @@ -235,14 +280,17 @@ - + + + + + + - - @@ -251,7 +299,12 @@ + + + + + @@ -270,12 +323,14 @@ + - + + @@ -288,7 +343,9 @@ + + @@ -298,16 +355,17 @@ - + + @@ -352,6 +410,8 @@ + + @@ -361,12 +421,13 @@ - + + @@ -386,6 +447,7 @@ + @@ -395,18 +457,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -425,8 +517,8 @@ - - + + @@ -459,12 +551,15 @@ + + + @@ -475,12 +570,14 @@ + - + + @@ -498,13 +595,19 @@ + + + + + + @@ -525,6 +628,7 @@ + @@ -545,6 +649,7 @@ + @@ -556,6 +661,7 @@ + @@ -573,11 +679,11 @@ - + @@ -585,7 +691,9 @@ + + @@ -611,6 +719,9 @@ + + + @@ -626,17 +737,20 @@ - + + + + @@ -645,19 +759,19 @@ + - + - @@ -665,23 +779,32 @@ + + + + + + + + - + + @@ -689,6 +812,7 @@ + @@ -701,19 +825,22 @@ + + + - + @@ -721,13 +848,11 @@ - - - + @@ -749,6 +874,7 @@ + @@ -777,8 +903,10 @@ + + @@ -786,18 +914,21 @@ + + + @@ -815,8 +946,10 @@ + + - + @@ -851,6 +984,7 @@ + @@ -864,6 +998,8 @@ + + @@ -876,9 +1012,12 @@ + + + @@ -905,6 +1044,7 @@ + @@ -925,8 +1065,8 @@ + - @@ -936,10 +1076,15 @@ + + + + + @@ -947,11 +1092,15 @@ + + + + @@ -966,9 +1115,10 @@ - + + @@ -1004,30 +1154,32 @@ + + - + - + @@ -1037,12 +1189,13 @@ - + + @@ -1076,7 +1229,8 @@ - + + @@ -1086,12 +1240,18 @@ + + - + + + + + + - diff --git a/UnityEditor/UnityEditor/ASCommitWindow.cs b/UnityEditor/UnityEditor/ASCommitWindow.cs index 8d4b445c..1adbf0f0 100644 --- a/UnityEditor/UnityEditor/ASCommitWindow.cs +++ b/UnityEditor/UnityEditor/ASCommitWindow.cs @@ -1135,19 +1135,19 @@ private bool ParentViewGUI(ParentViewState pvState, ParentViewState anotherPvSta GUIContent gUIContent = null; if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Undeleted) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Created)) { - gUIContent = ASMainWindow.badgeNew; + gUIContent = ASMainWindow.constants.badgeNew; } else { if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Deleted)) { - gUIContent = ASMainWindow.badgeDelete; + gUIContent = ASMainWindow.constants.badgeDelete; } else { if (ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Renamed) || ASCommitWindow.HasFlag(changeFlags, ChangeFlags.Moved)) { - gUIContent = ASMainWindow.badgeMove; + gUIContent = ASMainWindow.constants.badgeMove; } } } diff --git a/UnityEditor/UnityEditor/ASConfigWindow.cs b/UnityEditor/UnityEditor/ASConfigWindow.cs index 16d1c390..6fdcde49 100644 --- a/UnityEditor/UnityEditor/ASConfigWindow.cs +++ b/UnityEditor/UnityEditor/ASConfigWindow.cs @@ -210,9 +210,9 @@ private void DoConfigGUI() string nameOfFocusedControl = GUI.GetNameOfFocusedControl(); if (nameOfFocusedControl != null) { - if (ASConfigWindow.<>f__switch$mapB == null) + if (ASConfigWindow.<>f__switch$mapD == null) { - ASConfigWindow.<>f__switch$mapB = new Dictionary(2) + ASConfigWindow.<>f__switch$mapD = new Dictionary(2) { { @@ -227,7 +227,7 @@ private void DoConfigGUI() }; } int num; - if (ASConfigWindow.<>f__switch$mapB.TryGetValue(nameOfFocusedControl, out num)) + if (ASConfigWindow.<>f__switch$mapD.TryGetValue(nameOfFocusedControl, out num)) { if (num == 0) { diff --git a/UnityEditor/UnityEditor/ASHistoryWindow.cs b/UnityEditor/UnityEditor/ASHistoryWindow.cs index 8214e097..cdce8c2a 100644 --- a/UnityEditor/UnityEditor/ASHistoryWindow.cs +++ b/UnityEditor/UnityEditor/ASHistoryWindow.cs @@ -504,19 +504,19 @@ private void DrawBadge(Rect offset, ChangeFlags flags, GUIStyle style, GUIConten GUIContent gUIContent = null; if (this.HasFlag(flags, ChangeFlags.Undeleted) || this.HasFlag(flags, ChangeFlags.Created)) { - gUIContent = ASMainWindow.badgeNew; + gUIContent = ASMainWindow.constants.badgeNew; } else { if (this.HasFlag(flags, ChangeFlags.Deleted)) { - gUIContent = ASMainWindow.badgeDelete; + gUIContent = ASMainWindow.constants.badgeDelete; } else { if (this.HasFlag(flags, ChangeFlags.Renamed) || this.HasFlag(flags, ChangeFlags.Moved)) { - gUIContent = ASMainWindow.badgeMove; + gUIContent = ASMainWindow.constants.badgeMove; } } } diff --git a/UnityEditor/UnityEditor/ASMainWindow.cs b/UnityEditor/UnityEditor/ASMainWindow.cs index 3105bddb..56729cd8 100644 --- a/UnityEditor/UnityEditor/ASMainWindow.cs +++ b/UnityEditor/UnityEditor/ASMainWindow.cs @@ -30,6 +30,9 @@ internal class Constants public GUIStyle entryOdd = "CN EntryBackOdd"; public GUIStyle dropDown = "MiniPullDown"; public GUIStyle toggle = "Toggle"; + public GUIContent badgeDelete = EditorGUIUtility.IconContent("AS Badge Delete"); + public GUIContent badgeMove = EditorGUIUtility.IconContent("AS Badge Move"); + public GUIContent badgeNew = EditorGUIUtility.IconContent("AS Badge New"); public Vector2 toggleSize; public Constants() { @@ -41,10 +44,10 @@ public Constants() this.contentBox.overflow = new RectOffset(0, 1, 0, 1); this.contentBox.padding = new RectOffset(8, 8, 7, 7); this.title = new GUIStyle(this.title); - RectOffset arg_202_0 = this.title.padding; + RectOffset arg_232_0 = this.title.padding; int num = this.contentBox.padding.left + 2; this.title.padding.right = num; - arg_202_0.left = num; + arg_232_0.left = num; this.background = new GUIStyle(this.background); this.background.padding.top = 1; } @@ -101,10 +104,7 @@ public bool DoGUI() } } private const ASMainWindow.Page lastMainPage = ASMainWindow.Page.Commit; - private static ASMainWindow.Constants constants = null; - public static GUIContent badgeDelete = EditorGUIUtility.IconContent("AS Badge Delete"); - public static GUIContent badgeMove = EditorGUIUtility.IconContent("AS Badge Move"); - public static GUIContent badgeNew = EditorGUIUtility.IconContent("AS Badge New"); + public static ASMainWindow.Constants constants; public AssetsItem[] sharedCommits; public AssetsItem[] sharedDeletedItems; public Changeset[] sharedChangesets; @@ -910,19 +910,19 @@ private void DoCommitParentView() GUIContent gUIContent = null; if (this.HasFlag(changeFlags, ChangeFlags.Undeleted) || this.HasFlag(changeFlags, ChangeFlags.Created)) { - gUIContent = ASMainWindow.badgeNew; + gUIContent = ASMainWindow.constants.badgeNew; } else { if (this.HasFlag(changeFlags, ChangeFlags.Deleted)) { - gUIContent = ASMainWindow.badgeDelete; + gUIContent = ASMainWindow.constants.badgeDelete; } else { if (this.HasFlag(changeFlags, ChangeFlags.Renamed) || this.HasFlag(changeFlags, ChangeFlags.Moved)) { - gUIContent = ASMainWindow.badgeMove; + gUIContent = ASMainWindow.constants.badgeMove; } } } @@ -1336,7 +1336,7 @@ private void OnGUI() } if (!this.m_CheckedMaint && Event.current.type != EventType.Layout) { - if (!InternalEditorUtility.HasMaint()) + if (!InternalEditorUtility.HasPro()) { base.Close(); GUIUtility.ExitGUI(); diff --git a/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs b/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs index 7093a4d3..f3f2600a 100644 --- a/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs +++ b/UnityEditor/UnityEditor/ASUpdateConflictResolveWindow.cs @@ -178,9 +178,9 @@ private void ContextMenuClick(object userData, string[] options, int selected) string text = this.dropDownMenuItems[selected]; if (text != null) { - if (ASUpdateConflictResolveWindow.<>f__switch$mapE == null) + if (ASUpdateConflictResolveWindow.<>f__switch$map10 == null) { - ASUpdateConflictResolveWindow.<>f__switch$mapE = new Dictionary(2) + ASUpdateConflictResolveWindow.<>f__switch$map10 = new Dictionary(2) { { @@ -195,7 +195,7 @@ private void ContextMenuClick(object userData, string[] options, int selected) }; } int num; - if (ASUpdateConflictResolveWindow.<>f__switch$mapE.TryGetValue(text, out num)) + if (ASUpdateConflictResolveWindow.<>f__switch$map10.TryGetValue(text, out num)) { if (num != 0) { @@ -487,7 +487,7 @@ private void DoDownloadConflictsGUI() }); if (this.deletionConflict[listViewElement.row] && Event.current.type == EventType.Repaint) { - GUIContent badgeDelete = ASMainWindow.badgeDelete; + GUIContent badgeDelete = ASMainWindow.constants.badgeDelete; Rect position2 = new Rect(listViewElement.position.x + (float)this.lvHeaderSplit1.realSizes[0] - (float)badgeDelete.image.width - 5f, listViewElement.position.y + listViewElement.position.height / 2f - (float)(badgeDelete.image.height / 2), (float)badgeDelete.image.width, (float)badgeDelete.image.height); EditorGUIUtility.SetIconSize(Vector2.zero); GUIStyle.none.Draw(position2, badgeDelete, false, false, false, false); diff --git a/UnityEditor/UnityEditor/ASUpdateWindow.cs b/UnityEditor/UnityEditor/ASUpdateWindow.cs index c146a7db..60a47d2e 100644 --- a/UnityEditor/UnityEditor/ASUpdateWindow.cs +++ b/UnityEditor/UnityEditor/ASUpdateWindow.cs @@ -98,9 +98,9 @@ private void ContextMenuClick(object userData, string[] options, int selected) string text = this.dropDownMenuItems[selected]; if (text != null) { - if (ASUpdateWindow.<>f__switch$mapF == null) + if (ASUpdateWindow.<>f__switch$map11 == null) { - ASUpdateWindow.<>f__switch$mapF = new Dictionary(2) + ASUpdateWindow.<>f__switch$map11 = new Dictionary(2) { { @@ -115,7 +115,7 @@ private void ContextMenuClick(object userData, string[] options, int selected) }; } int num; - if (ASUpdateWindow.<>f__switch$mapF.TryGetValue(text, out num)) + if (ASUpdateWindow.<>f__switch$map11.TryGetValue(text, out num)) { if (num != 0) { @@ -391,19 +391,19 @@ public void UpdateGUI() GUIContent gUIContent = null; if (this.HasFlag(changeFlags, ChangeFlags.Undeleted) || this.HasFlag(changeFlags, ChangeFlags.Created)) { - gUIContent = ASMainWindow.badgeNew; + gUIContent = ASMainWindow.constants.badgeNew; } else { if (this.HasFlag(changeFlags, ChangeFlags.Deleted)) { - gUIContent = ASMainWindow.badgeDelete; + gUIContent = ASMainWindow.constants.badgeDelete; } else { if (this.HasFlag(changeFlags, ChangeFlags.Renamed) || this.HasFlag(changeFlags, ChangeFlags.Moved)) { - gUIContent = ASMainWindow.badgeMove; + gUIContent = ASMainWindow.constants.badgeMove; } } } diff --git a/UnityEditor/UnityEditor/AboutWindow.cs b/UnityEditor/UnityEditor/AboutWindow.cs index 4368d68c..04801a08 100644 --- a/UnityEditor/UnityEditor/AboutWindow.cs +++ b/UnityEditor/UnityEditor/AboutWindow.cs @@ -8,7 +8,6 @@ internal class AboutWindow : EditorWindow private const string kSpecialThanksNames = "Thanks to Forest 'Yoggy' Johnson, Graham McAllister, David Janik-Jones, Raimund Schumacher, Alan J. Dickins and Emil 'Humus' Persson"; private static GUIContent s_MonoLogo; private static GUIContent s_AgeiaLogo; - private static GUIContent s_UnityLogo; private static GUIContent s_Header; private readonly string kCreditsNames = string.Join(", ", AboutWindowNames.names); private float m_TextYPos = 120f; @@ -31,7 +30,6 @@ private static void LoadLogos() } AboutWindow.s_MonoLogo = EditorGUIUtility.IconContent("MonoLogo"); AboutWindow.s_AgeiaLogo = EditorGUIUtility.IconContent("AgeiaLogo"); - AboutWindow.s_UnityLogo = EditorGUIUtility.IconContent("UnityLogo"); AboutWindow.s_Header = EditorGUIUtility.IconContent("AboutWindow.MainHeader"); } public void OnEnable() @@ -60,33 +58,34 @@ public void OnGUI() GUILayout.Space(10f); GUILayout.BeginHorizontal(new GUILayoutOption[0]); GUILayout.Space(5f); - GUILayout.Label(AboutWindow.s_UnityLogo, GUIStyle.none, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - }); GUILayout.BeginVertical(new GUILayoutOption[0]); GUILayout.FlexibleSpace(); GUILayout.Label(AboutWindow.s_Header, GUIStyle.none, new GUILayoutOption[0]); this.ListenForSecretCodes(); + string text = string.Empty; + if (InternalEditorUtility.HasPro()) + { + text = " Pro"; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(52f); this.m_ShowDetailedVersion |= Event.current.alt; if (this.m_ShowDetailedVersion) { int unityVersionDate = InternalEditorUtility.GetUnityVersionDate(); DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); string unityBuildBranch = InternalEditorUtility.GetUnityBuildBranch(); - string text = string.Empty; + string text2 = string.Empty; if (unityBuildBranch.Length > 0) { - text = "Branch: " + unityBuildBranch; + text2 = "Branch: " + unityBuildBranch; } - EditorGUILayout.SelectableLabel(string.Concat(new string[] + EditorGUILayout.SelectableLabel(string.Format("Version {0}{1}\n{2:r}\n{3}", new object[] { - "Version ", InternalEditorUtility.GetFullUnityVersion(), - "\n", - string.Format("{0:r}", dateTime.AddSeconds((double)unityVersionDate)), - "\n", - text + text, + dateTime.AddSeconds((double)unityVersionDate), + text2 }), new GUILayoutOption[] { GUILayout.Width(400f), @@ -96,12 +95,13 @@ public void OnGUI() } else { - GUILayout.Label("Version " + Application.unityVersion, new GUILayoutOption[0]); + GUILayout.Label(string.Format("Version {0}{1}", Application.unityVersion, text), new GUILayoutOption[0]); } if (Event.current.type == EventType.ValidateCommand) { return; } + GUILayout.EndHorizontal(); GUILayout.Space(4f); GUILayout.EndVertical(); GUILayout.EndHorizontal(); diff --git a/UnityEditor/UnityEditor/AboutWindowNames.cs b/UnityEditor/UnityEditor/AboutWindowNames.cs index 357cc780..9dd99093 100644 --- a/UnityEditor/UnityEditor/AboutWindowNames.cs +++ b/UnityEditor/UnityEditor/AboutWindowNames.cs @@ -22,10 +22,13 @@ internal static class AboutWindowNames "Alexandra Mariner", "Alexey Abramychev", "Alexey Orlov", + "Alexis Matte", "Alfonso Ortiz Palma Junco", "Allen Foo", "Amanda Rush", + "Amy Dacker", "Amir Ebrahimi", + "Anastasia Konuhova", "Anders Jensen", "Anders Peter Kierbye Johansen", "Andre Gauthier", @@ -49,6 +52,8 @@ internal static class AboutWindowNames "Ante Ilic", "Anthony Yakovlev", "Antony Douglas", + "Antti Klemetti", + "Antti Lindell", "Antti Nieminen", "Antti Tapaninen", "Aras Pranckevičius", @@ -75,6 +80,7 @@ internal static class AboutWindowNames "Bobby Billingsley", "Bobo Bo", "Boram Kim", + "Boris Prikhodskiy", "Brad Robel-Forrest", "Brett Bibby", "Brett Seyler", @@ -88,6 +94,7 @@ internal static class AboutWindowNames "Cathy Yates", "Cecilie Mosfeldt", "Charles Hinshaw", + "Charles Lee", "Charlotte Kaas Larsen", "Chethan Ramachandran", "Chida Chaemchaeng", @@ -101,16 +108,20 @@ internal static class AboutWindowNames "Christopher Owen Hamilton", "Christopher Pope", "Christopher Roblee", + "Christy Cowan", "Chuan Xin Lim", "Claude Comeau", "Claus Petersen", + "Corey Garnett", "Corey Johnson", "Craig Matthew Blum", "Damien Colin Simper", "Dan Adams", + "Dan Weighton", "Dana Greene", "Dana Ramnarine", "Daniel Bratcher", + "Daniel Brauer", "Daniel Collin", "Daniel Dyer", "Daniel Hobley", @@ -132,6 +143,7 @@ internal static class AboutWindowNames "David Takahashi", "Denis Simuntis", "Dennis DeRyke", + "Diane Linzy", "Dmitriy Mindra", "Dmitry Onishchenko", "Dmitry Shtainer", @@ -153,6 +165,7 @@ internal static class AboutWindowNames "Elvira Brodovska", "Elvis Alistar", "Emil Johansen", + "Emilie Napoly", "Emilliza Gutierrez", "Emily Emanuel", "Emma Butler", @@ -167,6 +180,7 @@ internal static class AboutWindowNames "Evan Spytma", "Evon Siok Yee Low", "Ezra Nuite", + "Fang Yang", "Fini Faria Alring", "Florian Penzkofer", "Francis Lauzon Duranceau", @@ -178,6 +192,7 @@ internal static class AboutWindowNames "Graham Dunnett", "Graham Laverty", "Graham Reeves", + "Guillaume Saby", "Gukhwan Ji", "Hanna Yi", "Harry Chng", @@ -191,6 +206,7 @@ internal static class AboutWindowNames "Hindu Buddharaju", "Hiroki Omae", "HoMin Lee", + "Hugh Lee", "Hugh Longworth", "Hui Xiumo", "Hwan-hee Kim", @@ -208,7 +224,9 @@ internal static class AboutWindowNames "Isabelle Jacquinot", "Jaakko Lukkari", "Jack Kieran Paine", + "Jacob Grooss", "Jaehyun Kang", + "Jaeyoung Han", "Jakob Hunsballe", "Jalmari Raippalinna", "James Bouckley", @@ -218,6 +236,7 @@ internal static class AboutWindowNames "Janet Qiu", "Janne Alanen", "Janne Nikula", + "Janni Kjaersgaard", "Jarkko Rajamaki", "Jarko Vihriala", "Jason Chen", @@ -233,10 +252,13 @@ internal static class AboutWindowNames "Jens Fursund", "Jeremy Martin", "Jesper Mortensen", + "Jesse Smith", "Jessica Qian", "Jessika Jackson", + "Jiajia Li", "Jiaqing Wang", "Jiawei Ma", + "Jihyun Oh", "Jinho Mang", "Jinjeong Lee", "Jinn Kim", @@ -244,10 +266,11 @@ internal static class AboutWindowNames "Jiyuan Liao", "Jo Ryall", "Joachim Ante", - "Joana Koyte", + "Joana Kodyte", "JoAnna Matthisen", "Jocelyn Cai", "Joe Robins", + "Joel de Vahl", "Joe Santos", "Joel Packer", "Joen Joensen", @@ -258,6 +281,9 @@ internal static class AboutWindowNames "John Edgar Congote Calle", "John Fallon", "John Goodale", + "John Jones", + "John Park", + "John Riccitiello", "Jonas Christian Drewsen", "Jonas Echterhoff", "Jonas Meyer", @@ -271,6 +297,7 @@ internal static class AboutWindowNames "Joseph Walters", "Josh Naylor", "Joshua Peterson", + "Joyce Law", "Juan Sebastian Muñoz", "Juha Kiili", "Juho Makinen", @@ -291,6 +318,7 @@ internal static class AboutWindowNames "Karen Booth", "Karen Gold", "Karen Riskær Jørgensen", + "Karl Jones", "Karolis Norkunas", "Karsten Nielsen", "Kaspar Daugaard", @@ -311,8 +339,8 @@ internal static class AboutWindowNames "Kiersten Petesch", "Kim Moon-soo", "Kim Steen Riber", - "Kimberly Villaron", "Kimberly Bailey", + "Kimberly Villaron", "Kimberly Verde", "Kimi Wang", "Kirsten Duvall", @@ -327,6 +355,7 @@ internal static class AboutWindowNames "Lars \"Kroll\" Kristensen", "Lars Mølgård Nielsen", "Lars Runov", + "Larus Olafsson", "Lasse Järvensivu", "Lasse Makholm", "Leena Kuitunen", @@ -335,13 +364,15 @@ internal static class AboutWindowNames "Leon Jun", "Leonardo Carneiro", "Levi Bard", - "Li Jiajia", + "Li Zhou", "Liang Zhao", "Liming Zhang", + "Lise Flanding", "Loreta Dilnike", "Louise Skaarup", "Luc Vo Van", "Lucas Meijer", + "Lukas Chodosevicius", "Lukas Dapkus", "Lukasz Paczkowski", "Lárus Ólafsson", @@ -349,14 +380,17 @@ internal static class AboutWindowNames "Mads Kiilerich", "Mads Kjellerup", "Mads Nyholm", + "Maggie Hong", "Maj-Brit Jo Arnested", "Makoto Itoh", "Makoto Sugano", "Mantas Puida", "Marc Cinq Mars", "Marc Eric Quesnel", + "Marc Tanenbaum", "Marco Alvarado", "Marco Trivellato", + "Marcus Dahl Rasmussen", "Marcus Lim", "Marek Turski", "Maria Marcano", @@ -372,28 +406,37 @@ internal static class AboutWindowNames "Martin Sternevald", "Martin Stjernholk Vium", "Martin Troels Eberhardt", + "Marton Ekler", "Marvin Kharrazi", "Massimiliano Mantione", "Massimo Caterino", "Mathieu Muller", "Matt Reynolds", "Matthew Fini", + "Matthew Schell", + "Matthew Wyatt", + "Matti Ahtiainen", "Matti Savolainen", + "Maxim Musich", "Melvin Chay", "Melvyn May", "Michael Birk", "Michael Edmonds", + "Michael Foley", "Michael Herring", "Michael Krarup Nielsen", "Michael Lyashenko", + "Michael Sehgal", "Mickey Maher", "Mika Kuusisto", "Mika Patiala", "Mike Geig", + "Mikhail Zabaluev", "Mikkel \"Frecle\" Fredborg", "Mikko Lehtinen", "Mikko Mononen", "Mikko Strandborg", + "Milian Micov", "Mindaugas Steponavičius", "Minsu Andrew Park", "Mira Cho", @@ -401,6 +444,7 @@ internal static class AboutWindowNames "Monika Madrid", "Morrissey Williams", "Morten Abildgaard", + "Morten Skaaning", "Morten Sommer", "Na'Tosha Bard", "Natalia Sviridova", @@ -427,6 +471,7 @@ internal static class AboutWindowNames "Oren Tversky", "Oscar Pett", "Palaniyandi Jawahar", + "Paolo Gavazzi", "Patrick Bell", "Patrick Curry", "Patrick Williamson", @@ -436,16 +481,18 @@ internal static class AboutWindowNames "Paulius Liekis", "Paulius Puodziunas", "Peden Fitzhugh", + "Peet Lee", "Peijun Zhu", "Pekka Aakko", "Pekka Palmu", "Pengfei Zhang", "Pernille Hansen", + "Pete Moss", "Peter Ejby Dahl Jensen", + "Peter Freese", "Peter Kuhn", "Peter Lee", "Peter Long", - "Pete Moss", "Peter Schmitz", "Petri Nordlund", "Phil McJunkins", @@ -461,6 +508,7 @@ internal static class AboutWindowNames "Qing Feng", "Ralph Hauwert", "Randy Spong", + "Rasmus Bolvig Petersen", "Rasmus \"Razu\" Boserup", "Rasmus Møller Selsmark", "Rebekah Tay Xiao Ping", @@ -469,6 +517,7 @@ internal static class AboutWindowNames "René Damm", "Ricardo Arango", "Rich Skorski", + "Richard Fine", "Richard Sykes", "Rickard Andersson", "Rita Turkowski", @@ -479,6 +528,7 @@ internal static class AboutWindowNames "Robert Cupisz", "Robert Lanciault", "Robert Oates", + "Robertas Cesnauskas", "Rodrigo B. de Oliveira", "Rodrigo Lopez-carrillo", "Rolandas Cinevskis", @@ -490,18 +540,24 @@ internal static class AboutWindowNames "Ruslan Grigoryev", "Rustum bin Dzil Qamar", "Ryan Hintze", + "Ryan Parkinson-Faulkner", "Ryan N. Burke", "Rytis Bieliūnas", "Sakari Pitkänen", "Salley Chan", + "Salvador Jacobi", "Sam Bickley", "Samantha Kalman", "Sampsa Jaatinen", + "Samuli Soderlund", "Sanjay Mistry", "Sara Cannon", + "Sara Lempainen", "Sara Wallman", + "Sarah Stevenson", "Scott Bilas", "Scott Flynn", + "Scott Peterson", "Sean Baggaley", "Sean Riley", "Segrel Koskentausta", @@ -525,6 +581,7 @@ internal static class AboutWindowNames "Simon Holm Nielsen", "Sin Jin Chia", "Skjalm Arrøe", + "Slava Taraskin", "Sonny Myette", "Steen Lund", "Stefan Sandberg", @@ -548,7 +605,9 @@ internal static class AboutWindowNames "Tao Wang", "Tatsuhiko Yamamura", "Tautvydas Žilys", + "Tea Torovic", "Tec Liu", + "Teemu Pohjanlehto", "Tero Heino", "Terry Hendrix II", "Thomas Bentzen", @@ -579,9 +638,12 @@ internal static class AboutWindowNames "Tony Garcia", "Tony Sun", "Torben Jeppesen", + "Torbjorn Laedre", + "Toru Nayuki", "Toshiyuki Mori", "Tracy Erickson", "Tricia Gray", + "Trish Scearce", "Tuomas Peronvuo", "Tuomas Rinta", "Tze Bun Ng", @@ -591,6 +653,9 @@ internal static class AboutWindowNames "Valdemar Bučilko", "Valentin Simonov", "Valerie Cisco", + "Valtteri Heikkilä", + "Vanessa Martinez", + "Vanessa Oliver", "Veli-Pekka Kokkonen", "Venkatesh Subramaniam Pillai", "Veselin Efremov", @@ -607,6 +672,7 @@ internal static class AboutWindowNames "Viraf Zack", "Vitaly Veligursky", "Vlatko Duvnjak", + "Vuokko Salo", "Vytautas Šaltenis", "Ward Vuillemot", "Wayne Johnson", @@ -620,6 +686,7 @@ internal static class AboutWindowNames "Xiangyu Deng", "Xiao Ling Yao", "Xin Zhang", + "Xiumo Hui", "Yan Drugalya", "Yasuyuki Kamata", "Yelena Danziger", @@ -629,6 +696,7 @@ internal static class AboutWindowNames "Young ho Lee", "Younghee Cho", "Youngho Hahm", + "Yuan Gao", "Yuan Kuan Seng", "Yuanxing Cai", "Yue Liu", diff --git a/UnityEditor/UnityEditor/ActionOnDotNetUnhandledException.cs b/UnityEditor/UnityEditor/ActionOnDotNetUnhandledException.cs new file mode 100644 index 00000000..7c1c09de --- /dev/null +++ b/UnityEditor/UnityEditor/ActionOnDotNetUnhandledException.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum ActionOnDotNetUnhandledException + { + SilentExit, + Crash + } +} diff --git a/UnityEditor/UnityEditor/AddComponentWindow.cs b/UnityEditor/UnityEditor/AddComponentWindow.cs index 7a73a54d..974f3b92 100644 --- a/UnityEditor/UnityEditor/AddComponentWindow.cs +++ b/UnityEditor/UnityEditor/AddComponentWindow.cs @@ -13,9 +13,8 @@ internal class AddComponentWindow : EditorWindow { internal enum Language { - JavaScript, CSharp, - Boo + JavaScript } private class Element : IComparable { @@ -91,17 +90,16 @@ private string extension { get { - switch (AddComponentWindow.s_Lang) + AddComponentWindow.Language s_Lang = AddComponentWindow.s_Lang; + if (s_Lang == AddComponentWindow.Language.CSharp) { - case AddComponentWindow.Language.JavaScript: - return "js"; - case AddComponentWindow.Language.CSharp: return "cs"; - case AddComponentWindow.Language.Boo: - return "boo"; - default: + } + if (s_Lang != AddComponentWindow.Language.JavaScript) + { throw new ArgumentOutOfRangeException(); } + return "js"; } } private string templatePath @@ -109,17 +107,16 @@ private string templatePath get { string path = Path.Combine(EditorApplication.applicationContentsPath, "Resources/ScriptTemplates"); - switch (AddComponentWindow.s_Lang) + AddComponentWindow.Language s_Lang = AddComponentWindow.s_Lang; + if (s_Lang == AddComponentWindow.Language.CSharp) { - case AddComponentWindow.Language.JavaScript: - return Path.Combine(path, "80-Javascript-NewBehaviourScript.js.txt"); - case AddComponentWindow.Language.CSharp: return Path.Combine(path, "81-C# Script-NewBehaviourScript.cs.txt"); - case AddComponentWindow.Language.Boo: - return Path.Combine(path, "82-Boo Script-NewBehaviourScript.boo.txt"); - default: + } + if (s_Lang != AddComponentWindow.Language.JavaScript) + { throw new ArgumentOutOfRangeException(); } + return Path.Combine(path, "82-Javascript-NewBehaviourScript.js.txt"); } } public NewScriptElement() : base(1, "New Script") @@ -264,6 +261,7 @@ public Styles() this.previewHeader.padding.bottom += 2; } } + private const AddComponentWindow.Language kDefaultLanguage = AddComponentWindow.Language.CSharp; private const int kHeaderHeight = 30; private const int kWindowHeight = 320; private const int kHelpHeight = 0; @@ -284,6 +282,7 @@ public Styles() private int m_AnimTarget = 1; private long m_LastTime; private bool m_ScrollToSelected; + private string m_DelayedSearch; private string m_Search = string.Empty; internal static string className { @@ -340,6 +339,13 @@ private AddComponentWindow.Element activeElement return children[this.activeParent.selectedIndex]; } } + private bool isAnimating + { + get + { + return this.m_Anim != (float)this.m_AnimTarget; + } + } static AddComponentWindow() { AddComponentWindow.s_DirtyList = true; @@ -347,7 +353,12 @@ static AddComponentWindow() private void OnEnable() { AddComponentWindow.s_AddComponentWindow = this; - AddComponentWindow.s_Lang = (AddComponentWindow.Language)EditorPrefs.GetInt("NewScriptLanguage", 1); + AddComponentWindow.s_Lang = (AddComponentWindow.Language)EditorPrefs.GetInt("NewScriptLanguage", 0); + if (!Enum.IsDefined(typeof(AddComponentWindow.Language), AddComponentWindow.s_Lang)) + { + EditorPrefs.SetInt("NewScriptLanguage", 0); + AddComponentWindow.s_Lang = AddComponentWindow.Language.CSharp; + } this.m_Search = EditorPrefs.GetString("ComponentSearchString", string.Empty); } private void OnDisable() @@ -501,20 +512,28 @@ internal void OnGUI() rect.width -= 16f; GUI.SetNextControlName("ComponentSearch"); EditorGUI.BeginDisabledGroup(this.activeParent is AddComponentWindow.NewScriptElement); - string text = EditorGUI.SearchField(rect, this.m_Search); - EditorGUI.EndDisabledGroup(); - if (text != this.m_Search) + string text = EditorGUI.SearchField(rect, this.m_DelayedSearch ?? this.m_Search); + if (text != this.m_Search || this.m_DelayedSearch != null) { - this.m_Search = text; - EditorPrefs.SetString("ComponentSearchString", this.m_Search); - this.RebuildSearch(); + if (!this.isAnimating) + { + this.m_Search = (this.m_DelayedSearch ?? text); + EditorPrefs.SetString("ComponentSearchString", this.m_Search); + this.RebuildSearch(); + this.m_DelayedSearch = null; + } + else + { + this.m_DelayedSearch = text; + } } + EditorGUI.EndDisabledGroup(); this.ListGUI(this.activeTree, this.m_Anim, this.GetElementRelative(0), this.GetElementRelative(-1)); if (this.m_Anim < 1f) { this.ListGUI(this.activeTree, this.m_Anim + 1f, this.GetElementRelative(-1), this.GetElementRelative(-2)); } - if (this.m_Anim != (float)this.m_AnimTarget && Event.current.type == EventType.Repaint) + if (this.isAnimating && Event.current.type == EventType.Repaint) { long ticks = DateTime.Now.Ticks; float num = (float)(ticks - this.m_LastTime) / 1E+07f; diff --git a/UnityEditor/UnityEditor/AlphabeticalSort.cs b/UnityEditor/UnityEditor/AlphabeticalSort.cs index 8a915150..674244cc 100644 --- a/UnityEditor/UnityEditor/AlphabeticalSort.cs +++ b/UnityEditor/UnityEditor/AlphabeticalSort.cs @@ -4,8 +4,7 @@ namespace UnityEditor { public class AlphabeticalSort : BaseHierarchySort { - private const string kDefaultSorting = "AlphabeticalSorting"; - private GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("AlphabeticalSorting"), "Alphabetical Order"); + private readonly GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("AlphabeticalSorting"), "Alphabetical Order"); public override GUIContent content { get diff --git a/UnityEditor/UnityEditor/AndroidBanner.cs b/UnityEditor/UnityEditor/AndroidBanner.cs new file mode 100644 index 00000000..f7e6e271 --- /dev/null +++ b/UnityEditor/UnityEditor/AndroidBanner.cs @@ -0,0 +1,11 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct AndroidBanner + { + public int width; + public int height; + public Texture2D banner; + } +} diff --git a/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs b/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs index b7779961..1f21ccaf 100644 --- a/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs +++ b/UnityEditor/UnityEditor/AndroidBuildSubtarget.cs @@ -1,14 +1,16 @@ using System; +using System.ComponentModel; namespace UnityEditor { + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("UnityEditor.AndroidBuildSubtarget has been deprecated. Use UnityEngine.MobileTextureSubtarget instead (UnityUpgradable).", true)] public enum AndroidBuildSubtarget { - Generic, - DXT, - PVRTC, - ATC, - ETC, - ETC2, - ASTC + Generic = -1, + DXT = -1, + PVRTC = -1, + ATC = -1, + ETC = -1, + ETC2 = -1, + ASTC = -1 } } diff --git a/UnityEditor/UnityEditor/AndroidSdkRoot.cs b/UnityEditor/UnityEditor/AndroidSdkRoot.cs index 6fb12ed6..4512e9b4 100644 --- a/UnityEditor/UnityEditor/AndroidSdkRoot.cs +++ b/UnityEditor/UnityEditor/AndroidSdkRoot.cs @@ -78,7 +78,7 @@ internal static string Browse(string sdkPath) } internal static bool IsSdkDir(string path) { - return Directory.Exists(Path.Combine(path, "platform-tools")); + return Directory.Exists(Path.Combine(path, "platform-tools")) || File.Exists(Path.Combine(Path.Combine(path, "tools"), "android")) || File.Exists(Path.Combine(Path.Combine(path, "tools"), "android.bat")); } } } diff --git a/UnityEditor/UnityEditor/AndroidSdkVersions.cs b/UnityEditor/UnityEditor/AndroidSdkVersions.cs index 2633377b..303121c2 100644 --- a/UnityEditor/UnityEditor/AndroidSdkVersions.cs +++ b/UnityEditor/UnityEditor/AndroidSdkVersions.cs @@ -13,6 +13,7 @@ public enum AndroidSdkVersions AndroidApiLevel16, AndroidApiLevel17, AndroidApiLevel18, - AndroidApiLevel19 + AndroidApiLevel19, + AndroidApiLevel21 = 21 } } diff --git a/UnityEditor/UnityEditor/AndroidTargetDevice.cs b/UnityEditor/UnityEditor/AndroidTargetDevice.cs index 40698d4a..e0d24e82 100644 --- a/UnityEditor/UnityEditor/AndroidTargetDevice.cs +++ b/UnityEditor/UnityEditor/AndroidTargetDevice.cs @@ -4,9 +4,7 @@ namespace UnityEditor public enum AndroidTargetDevice { FAT, - ARMv6, - Emulator, - ARMv7, + ARMv7 = 3, x86 } } diff --git a/UnityEditor/UnityEditor/AnimationClipEditor.cs b/UnityEditor/UnityEditor/AnimationClipEditor.cs index 4823ece2..aef9fb1d 100644 --- a/UnityEditor/UnityEditor/AnimationClipEditor.cs +++ b/UnityEditor/UnityEditor/AnimationClipEditor.cs @@ -1,4 +1,5 @@ using System; +using UnityEditor.Animations; using UnityEditorInternal; using UnityEngine; namespace UnityEditor @@ -82,15 +83,17 @@ private class Styles public static float s_EventTimelineMax = 1.05f; private AnimationClipInfoProperties m_ClipInfo; private AnimationClip m_Clip; - private AnimatorController m_Controller; - private StateMachine m_StateMachine; - private State m_State; + private UnityEditor.Animations.AnimatorController m_Controller; + private AnimatorStateMachine m_StateMachine; + private AnimatorState m_State; private AvatarPreview m_AvatarPreview; private TimeArea m_TimeArea; private TimeArea m_EventTimeArea; private bool m_DraggingRange; private bool m_DraggingRangeBegin; private bool m_DraggingRangeEnd; + private float m_DraggingStartFrame; + private float m_DraggingStopFrame; private bool m_LoopTime; private bool m_LoopBlend; private bool m_LoopBlendOrientation; @@ -101,10 +104,10 @@ private class Styles private AvatarMask m_Mask; private AvatarMaskInspector m_MaskInspector; private string[] m_ReferenceTransformPaths; - private bool m_ShowCurves; + private static bool m_ShowCurves = false; private EventManipulationHandler m_EventManipulationHandler; - private bool m_ShowEvents; - private bool m_MaskFoldout; + private static bool m_ShowEvents = false; + private static bool m_MaskFoldout = false; private Vector2[][][] m_QualityCurves = new Vector2[4][][]; private bool m_DirtyQualityCurves; private static GUIContent prevKeyContent = EditorGUIUtility.IconContent("Animation.PrevKey"); @@ -131,6 +134,26 @@ public string[] referenceTransformPaths this.m_ReferenceTransformPaths = value; } } + internal static void EditWithImporter(AnimationClip clip) + { + ModelImporter modelImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(clip)) as ModelImporter; + if (modelImporter) + { + Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(modelImporter.assetPath); + ModelImporterEditor modelImporterEditor = Editor.CreateEditor(modelImporter) as ModelImporterEditor; + EditorPrefs.SetInt(modelImporterEditor.GetType().Name + "ActiveEditorIndex", 2); + int value = 0; + ModelImporterClipAnimation[] clipAnimations = modelImporter.clipAnimations; + for (int i = 0; i < clipAnimations.Length; i++) + { + if (clipAnimations[i].name == clip.name) + { + value = i; + } + } + EditorPrefs.SetInt("ModelImporterClipEditor.ActiveClipIndex", value); + } + } private void UpdateEventsPopupClipInfo(AnimationClipInfoProperties info) { UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(AnimationEventPopup)); @@ -152,27 +175,35 @@ private void InitController() { if (this.m_Controller == null) { - this.m_Controller = new AnimatorController(); - this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller = new UnityEditor.Animations.AnimatorController(); + this.m_Controller.pushUndo = false; + this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); - this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + this.m_StateMachine = this.m_Controller.layers[0].stateMachine; + this.m_StateMachine.pushUndo = false; + this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; if (this.m_ClipInfo != null) { this.InitMask(); - this.m_Controller.SetLayerMask(0, this.m_Mask); + UnityEditor.Animations.AnimatorControllerLayer[] layers = this.m_Controller.layers; + layers[0].avatarMask = this.m_Mask; + this.m_Controller.layers = layers; } } if (this.m_State == null) { this.m_State = this.m_StateMachine.AddState("preview"); - this.m_State.SetAnimationClip(this.m_Clip); + this.m_State.pushUndo = false; + UnityEditor.Animations.AnimatorControllerLayer[] layers2 = this.m_Controller.layers; + this.m_State.motion = this.m_Clip; + this.m_Controller.layers = layers2; this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; - this.m_State.hideFlags = HideFlags.DontSave; + this.m_State.hideFlags = HideFlags.HideAndDontSave; } - AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); - if (AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) + UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + if (UnityEditor.Animations.AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) { - AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); } } } @@ -211,13 +242,21 @@ internal override void OnHeaderControlsGUI() else { base.OnHeaderControlsGUI(); + ModelImporter x = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(this.target)) as ModelImporter; + if (x != null && this.m_ClipInfo == null && GUILayout.Button("Edit...", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + AnimationClipEditor.EditWithImporter(this.target as AnimationClip); + } } } private void DestroyController() { if (this.m_AvatarPreview != null && this.m_AvatarPreview.Animator != null) { - AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); + UnityEditor.Animations.AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, null); } UnityEngine.Object.DestroyImmediate(this.m_Controller); UnityEngine.Object.DestroyImmediate(this.m_State); @@ -339,6 +378,7 @@ private void OnDisable() { UnityEngine.Object.DestroyImmediate(this.m_Mask); } + AnimationEventPopup.ClosePopup(); } public override bool HasPreviewGUI() { @@ -396,13 +436,13 @@ public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) { this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; } - float normalizedTime = (this.m_AvatarPreview.timeControl.currentTime - animationClipSettings.startTime) / (animationClipSettings.stopTime - animationClipSettings.startTime); + float normalizedTime = (animationClipSettings.stopTime - animationClipSettings.startTime == 0f) ? 0f : ((this.m_AvatarPreview.timeControl.currentTime - animationClipSettings.startTime) / (animationClipSettings.stopTime - animationClipSettings.startTime)); this.m_AvatarPreview.Animator.Play(0, 0, normalizedTime); this.m_AvatarPreview.Animator.Update(this.m_AvatarPreview.timeControl.deltaTime); } else { - this.m_AvatarPreview.PreviewObject.SampleAnimation(animationClip, this.m_AvatarPreview.timeControl.currentTime); + animationClip.SampleAnimation(this.m_AvatarPreview.PreviewObject, this.m_AvatarPreview.timeControl.currentTime); } } this.m_AvatarPreview.DoAvatarPreview(r, background); @@ -455,18 +495,34 @@ public void ClipRangeGUI(ref float startFrame, ref float stopFrame, out bool cha Handles.color = Color.white; EditorGUI.BeginDisabledGroup(flag); float num5 = startFrame / this.m_Clip.frameRate; - if (this.m_TimeArea.BrowseRuler(rect, controlID, ref num5, 0f, false, "TL InPoint") != TimeArea.TimeRulerDragMode.None) + TimeArea.TimeRulerDragMode timeRulerDragMode = this.m_TimeArea.BrowseRuler(rect, controlID, ref num5, 0f, false, "TL InPoint"); + if (timeRulerDragMode == TimeArea.TimeRulerDragMode.Cancel) { - startFrame = num5 * this.m_Clip.frameRate; - startFrame = MathUtils.RoundBasedOnMinimumDifference(startFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); - changedStart = true; + startFrame = this.m_DraggingStartFrame; + } + else + { + if (timeRulerDragMode != TimeArea.TimeRulerDragMode.None) + { + startFrame = num5 * this.m_Clip.frameRate; + startFrame = MathUtils.RoundBasedOnMinimumDifference(startFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); + changedStart = true; + } } float num6 = stopFrame / this.m_Clip.frameRate; - if (this.m_TimeArea.BrowseRuler(rect, controlID2, ref num6, 0f, false, "TL OutPoint") != TimeArea.TimeRulerDragMode.None) + TimeArea.TimeRulerDragMode timeRulerDragMode2 = this.m_TimeArea.BrowseRuler(rect, controlID2, ref num6, 0f, false, "TL OutPoint"); + if (timeRulerDragMode2 == TimeArea.TimeRulerDragMode.Cancel) { - stopFrame = num6 * this.m_Clip.frameRate; - stopFrame = MathUtils.RoundBasedOnMinimumDifference(stopFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); - changedStop = true; + stopFrame = this.m_DraggingStopFrame; + } + else + { + if (timeRulerDragMode2 != TimeArea.TimeRulerDragMode.None) + { + stopFrame = num6 * this.m_Clip.frameRate; + stopFrame = MathUtils.RoundBasedOnMinimumDifference(stopFrame, this.m_TimeArea.PixelDeltaToTime(rect) * this.m_Clip.frameRate * 10f); + changedStop = true; + } } EditorGUI.EndDisabledGroup(); if (GUIUtility.hotControl == controlID) @@ -499,11 +555,11 @@ public void ClipRangeGUI(ref float startFrame, ref float stopFrame, out bool cha changedStop |= flag2; if (changedStart) { - startFrame = Mathf.Clamp(startFrame, this.m_Clip.startTime * this.m_Clip.frameRate, Mathf.Clamp(stopFrame, startFrame + 0.1f, this.m_Clip.stopTime * this.m_Clip.frameRate)); + startFrame = Mathf.Clamp(startFrame, this.m_Clip.startTime * this.m_Clip.frameRate, Mathf.Clamp(stopFrame, this.m_Clip.startTime * this.m_Clip.frameRate, stopFrame)); } if (changedStop) { - stopFrame = Mathf.Clamp(stopFrame, startFrame + 0.1f, this.m_Clip.stopTime * this.m_Clip.frameRate); + stopFrame = Mathf.Clamp(stopFrame, startFrame, this.m_Clip.stopTime * this.m_Clip.frameRate); } if (changedStart || changedStop) { @@ -608,7 +664,7 @@ public override void OnInspectorGUI() GUILayout.Label(this.m_Clip.frameRate + " FPS", EditorStyles.miniLabel, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); - if (this.m_Clip.isAnimatorMotion) + if (!this.m_Clip.legacy) { this.MuscleClipGUI(); } @@ -697,19 +753,20 @@ private void CurveGUI() { this.m_ClipInfo.SetCurveName(i, text); } - AnimationCurve animationCurve = this.m_ClipInfo.GetCurve(i); - int length = animationCurve.length; + SerializedProperty curveProperty = this.m_ClipInfo.GetCurveProperty(i); + AnimationCurve animationCurveValue = curveProperty.animationCurveValue; + int length = animationCurveValue.length; bool flag = false; int num = length - 1; for (int j = 0; j < length; j++) { - if (Mathf.Abs(animationCurve.keys[j].time - normalizedTime) < 0.0001f) + if (Mathf.Abs(animationCurveValue.keys[j].time - normalizedTime) < 0.0001f) { flag = true; num = j; break; } - if (animationCurve.keys[j].time > normalizedTime) + if (animationCurveValue.keys[j].time > normalizedTime) { num = j; break; @@ -719,7 +776,7 @@ private void CurveGUI() if (GUILayout.Button(AnimationClipEditor.prevKeyContent, new GUILayoutOption[0]) && num > 0) { num--; - this.m_AvatarPreview.timeControl.normalizedTime = animationCurve.keys[num].time; + this.m_AvatarPreview.timeControl.normalizedTime = animationCurveValue.keys[num].time; } if (GUILayout.Button(AnimationClipEditor.nextKeyContent, new GUILayoutOption[0])) { @@ -727,12 +784,12 @@ private void CurveGUI() { num++; } - this.m_AvatarPreview.timeControl.normalizedTime = animationCurve.keys[num].time; + this.m_AvatarPreview.timeControl.normalizedTime = animationCurveValue.keys[num].time; } EditorGUI.BeginDisabledGroup(!flag); string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; EditorGUI.kFloatFieldFormatString = "n3"; - float num2 = animationCurve.Evaluate(normalizedTime); + float num2 = animationCurveValue.Evaluate(normalizedTime); float num3 = EditorGUILayout.FloatField(num2, new GUILayoutOption[] { GUILayout.Width(60f) @@ -744,7 +801,7 @@ private void CurveGUI() { if (flag) { - animationCurve.RemoveKey(num); + animationCurveValue.RemoveKey(num); } flag2 = true; } @@ -756,31 +813,32 @@ private void CurveGUI() EditorGUI.EndDisabledGroup(); if (flag2) { - animationCurve.AddKey(new Keyframe + animationCurveValue.AddKey(new Keyframe { time = normalizedTime, value = num3, inTangent = 0f, outTangent = 0f }); + this.m_ClipInfo.SetCurve(i, animationCurveValue); + AnimationCurvePreviewCache.ClearCache(); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); - animationCurve = EditorGUILayout.CurveField(animationCurve, new GUILayoutOption[] + EditorGUILayout.CurveField(curveProperty, EditorGUI.kCurveColor, default(Rect), new GUILayoutOption[] { GUILayout.Height(40f) }); Rect lastRect = GUILayoutUtility.GetLastRect(); - length = animationCurve.length; + length = animationCurveValue.length; Handles.color = Color.red; Handles.DrawLine(new Vector3(lastRect.x + normalizedTime * lastRect.width, lastRect.y, 0f), new Vector3(lastRect.x + normalizedTime * lastRect.width, lastRect.y + lastRect.height, 0f)); for (int k = 0; k < length; k++) { - float time = animationCurve.keys[k].time; + float time = animationCurveValue.keys[k].time; Handles.color = Color.white; Handles.DrawLine(new Vector3(lastRect.x + time * lastRect.width, lastRect.y + lastRect.height - 10f, 0f), new Vector3(lastRect.x + time * lastRect.width, lastRect.y + lastRect.height, 0f)); } - this.m_ClipInfo.SetCurve(i, animationCurve); } GUILayout.EndHorizontal(); } @@ -841,11 +899,14 @@ private void MuscleClipGUI() this.InitController(); AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(this.m_Clip); bool isHumanMotion = (this.target as Motion).isHumanMotion; - bool flag = isHumanMotion && AnimationUtility.HasMotionCurves(this.m_Clip); + bool flag = AnimationUtility.HasMotionCurves(this.m_Clip); + bool flag2 = AnimationUtility.HasRootCurves(this.m_Clip); + bool flag3 = AnimationUtility.HasGenericRootTransform(this.m_Clip); + bool flag4 = AnimationUtility.HasMotionFloatCurves(this.m_Clip); this.m_StartFrame = ((!this.m_DraggingRange) ? (animationClipSettings.startTime * this.m_Clip.frameRate) : this.m_StartFrame); this.m_StopFrame = ((!this.m_DraggingRange) ? (animationClipSettings.stopTime * this.m_Clip.frameRate) : this.m_StopFrame); - bool flag2 = false; - bool flag3 = false; + bool flag5 = false; + bool flag6 = false; if (this.m_ClipInfo != null) { if (isHumanMotion) @@ -860,7 +921,7 @@ private void MuscleClipGUI() base.Repaint(); } } - this.ClipRangeGUI(ref this.m_StartFrame, ref this.m_StopFrame, out flag2, out flag3); + this.ClipRangeGUI(ref this.m_StartFrame, ref this.m_StopFrame, out flag5, out flag6); } float num = this.m_StartFrame / this.m_Clip.frameRate; float num2 = this.m_StopFrame / this.m_Clip.frameRate; @@ -871,11 +932,11 @@ private void MuscleClipGUI() } this.m_AvatarPreview.timeControl.startTime = num; this.m_AvatarPreview.timeControl.stopTime = num2; - if (flag2) + if (flag5) { this.m_AvatarPreview.timeControl.nextCurrentTime = num; } - if (flag3) + if (flag6) { this.m_AvatarPreview.timeControl.nextCurrentTime = num2; } @@ -892,8 +953,8 @@ private void MuscleClipGUI() EditorGUI.indentLevel--; EditorGUI.EndDisabledGroup(); EditorGUILayout.Space(); - bool flag4 = isHumanMotion && (flag2 || flag3); - if (!flag) + bool flag7 = isHumanMotion && (flag5 || flag6); + if (flag2 && !flag) { GUILayout.Label("Root Transform Rotation", EditorStyles.label, new GUILayoutOption[0]); EditorGUI.indentLevel++; @@ -902,7 +963,7 @@ private void MuscleClipGUI() int num3 = (!animationClipSettings.keepOriginalOrientation) ? 1 : 0; num3 = EditorGUILayout.Popup((!animationClipSettings.loopBlendOrientation) ? AnimationClipEditor.styles.BasedUponStartOrientation : AnimationClipEditor.styles.BasedUponOrientation, num3, (!isHumanMotion) ? AnimationClipEditor.styles.BasedUponRotationOpt : AnimationClipEditor.styles.BasedUponRotationHumanOpt, new GUILayoutOption[0]); animationClipSettings.keepOriginalOrientation = (num3 == 0); - if (flag4) + if (flag7) { EditorGUILayout.GetControlRect(new GUILayoutOption[0]); } @@ -960,7 +1021,7 @@ private void MuscleClipGUI() num5 = EditorGUILayout.Popup((!animationClipSettings.loopBlendPositionY) ? AnimationClipEditor.styles.BasedUponPositionY : AnimationClipEditor.styles.BasedUponStartPositionY, num5, AnimationClipEditor.styles.BasedUponPositionYOpt, new GUILayoutOption[0]); animationClipSettings.keepOriginalPositionY = (num5 == 0); } - if (flag4) + if (flag7) { EditorGUILayout.GetControlRect(new GUILayoutOption[0]); } @@ -981,17 +1042,17 @@ private void MuscleClipGUI() EditorGUILayout.Space(); if (isHumanMotion) { - this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag2, flag3, this.m_QualityCurves[0]); - this.LoopQualityLampAndCurve(controlRect3, muscleClipQualityInfo.loopOrientation, AnimationClipEditor.s_LoopOrientationMeterHint, flag2, flag3, this.m_QualityCurves[1]); - this.LoopQualityLampAndCurve(controlRect4, muscleClipQualityInfo.loopPositionY, AnimationClipEditor.s_LoopPositionYMeterHint, flag2, flag3, this.m_QualityCurves[2]); - this.LoopQualityLampAndCurve(controlRect5, muscleClipQualityInfo.loopPositionXZ, AnimationClipEditor.s_LoopPositionXZMeterHint, flag2, flag3, this.m_QualityCurves[3]); + this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag5, flag6, this.m_QualityCurves[0]); + this.LoopQualityLampAndCurve(controlRect3, muscleClipQualityInfo.loopOrientation, AnimationClipEditor.s_LoopOrientationMeterHint, flag5, flag6, this.m_QualityCurves[1]); + this.LoopQualityLampAndCurve(controlRect4, muscleClipQualityInfo.loopPositionY, AnimationClipEditor.s_LoopPositionYMeterHint, flag5, flag6, this.m_QualityCurves[2]); + this.LoopQualityLampAndCurve(controlRect5, muscleClipQualityInfo.loopPositionXZ, AnimationClipEditor.s_LoopPositionXZMeterHint, flag5, flag6, this.m_QualityCurves[3]); } } if (isHumanMotion) { if (flag) { - this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag2, flag3, this.m_QualityCurves[0]); + this.LoopQualityLampAndCurve(controlRect2, muscleClipQualityInfo.loop, AnimationClipEditor.s_LoopMeterHint, flag5, flag6, this.m_QualityCurves[0]); } animationClipSettings.mirror = EditorGUILayout.Toggle(AnimationClipEditor.styles.Mirror, animationClipSettings.mirror, new GUILayoutOption[0]); } @@ -1000,6 +1061,27 @@ private void MuscleClipGUI() EditorGUILayout.Space(); GUILayout.Label(AnimationClipEditor.styles.MotionCurves, EditorStyles.label, new GUILayoutOption[0]); } + if (this.m_ClipInfo == null && flag3 && !flag4) + { + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (flag) + { + if (GUILayout.Button("Remove Root Motion Curves", new GUILayoutOption[0])) + { + AnimationUtility.SetGenerateMotionCurves(this.m_Clip, false); + } + } + else + { + if (GUILayout.Button("Generate Root Motion Curves", new GUILayoutOption[0])) + { + AnimationUtility.SetGenerateMotionCurves(this.m_Clip, true); + } + } + GUILayout.EndHorizontal(); + } string statsText = this.GetStatsText(); if (statsText != string.Empty) { @@ -1012,7 +1094,7 @@ private void MuscleClipGUI() this.m_MaskInspector.showBody = isHumanMotion; int indentLevel = EditorGUI.indentLevel; bool changed = GUI.changed; - this.m_MaskFoldout = EditorGUILayout.Foldout(this.m_MaskFoldout, AnimationClipEditor.styles.Mask); + AnimationClipEditor.m_MaskFoldout = EditorGUILayout.Foldout(AnimationClipEditor.m_MaskFoldout, AnimationClipEditor.styles.Mask); GUI.changed = changed; if (this.m_ClipInfo.maskType == ClipAnimationMaskType.CreateFromThisModel && !this.IsMaskUpToDate()) { @@ -1029,20 +1111,37 @@ private void MuscleClipGUI() GUILayout.EndVertical(); GUILayout.EndHorizontal(); } - if (this.m_MaskFoldout) + else + { + if (this.m_ClipInfo.maskType == ClipAnimationMaskType.CopyFromOther && this.m_ClipInfo.MaskNeedsUpdating()) + { + GUILayout.BeginHorizontal(EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label("Source Mask has changed since last import. It must be Updated", EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(5f); + if (GUILayout.Button("Update Mask", new GUILayoutOption[0])) + { + this.m_ClipInfo.MaskToClip(this.m_ClipInfo.maskSource); + } + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + } + if (AnimationClipEditor.m_MaskFoldout) { EditorGUI.indentLevel++; this.m_MaskInspector.OnInspectorGUI(); } EditorGUI.indentLevel = indentLevel; } - bool flag5 = InternalEditorUtility.HasPro(); - if (flag5 && this.m_ClipInfo != null) + bool flag8 = InternalEditorUtility.HasProFeaturesEnabled(); + if (flag8 && this.m_ClipInfo != null) { bool changed = GUI.changed; - this.m_ShowCurves = EditorGUILayout.Foldout(this.m_ShowCurves, AnimationClipEditor.styles.Curves); + AnimationClipEditor.m_ShowCurves = EditorGUILayout.Foldout(AnimationClipEditor.m_ShowCurves, AnimationClipEditor.styles.Curves); GUI.changed = changed; - if (this.m_ShowCurves) + if (AnimationClipEditor.m_ShowCurves) { this.CurveGUI(); } @@ -1050,9 +1149,9 @@ private void MuscleClipGUI() if (this.m_ClipInfo != null) { bool changed = GUI.changed; - this.m_ShowEvents = EditorGUILayout.Foldout(this.m_ShowEvents, "Events"); + AnimationClipEditor.m_ShowEvents = EditorGUILayout.Foldout(AnimationClipEditor.m_ShowEvents, "Events"); GUI.changed = changed; - if (this.m_ShowEvents) + if (AnimationClipEditor.m_ShowEvents) { this.EventsGUI(); } @@ -1069,6 +1168,8 @@ private void MuscleClipGUI() animationClipSettings.loopBlendOrientation = false; animationClipSettings.loopBlendPositionY = false; animationClipSettings.loopBlendPositionXZ = false; + this.m_DraggingStartFrame = animationClipSettings.startTime * this.m_Clip.frameRate; + this.m_DraggingStopFrame = animationClipSettings.stopTime * this.m_Clip.frameRate; animationClipSettings.startTime = 0f; animationClipSettings.stopTime = this.m_Clip.length; AnimationUtility.SetAnimationClipSettingsNoDirty(this.m_Clip, animationClipSettings); diff --git a/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs b/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs index 74cb9a5c..5e905571 100644 --- a/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs +++ b/UnityEditor/UnityEditor/AnimationClipInfoProperties.cs @@ -1,5 +1,5 @@ using System; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -259,6 +259,46 @@ private SerializedProperty Get(string property) { return this.m_Property.FindPropertyRelative(property); } + public bool MaskNeedsUpdating() + { + AvatarMask maskSource = this.maskSource; + if (maskSource == null) + { + return false; + } + SerializedProperty serializedProperty = this.Get("bodyMask"); + if (serializedProperty == null || !serializedProperty.isArray) + { + return true; + } + for (int i = 0; i < maskSource.humanoidBodyPartCount; i++) + { + if (maskSource.GetHumanoidBodyPartActive(i) != (serializedProperty.GetArrayElementAtIndex(i).intValue != 0)) + { + return true; + } + } + SerializedProperty serializedProperty2 = this.Get("transformMask"); + if (serializedProperty2 == null || !serializedProperty2.isArray) + { + return true; + } + if (serializedProperty2.arraySize > 0 && maskSource.transformCount != serializedProperty2.arraySize) + { + return true; + } + int arraySize = serializedProperty2.arraySize; + for (int j = 0; j < arraySize; j++) + { + SerializedProperty serializedProperty3 = serializedProperty2.GetArrayElementAtIndex(j).FindPropertyRelative("m_Path"); + SerializedProperty serializedProperty4 = serializedProperty2.GetArrayElementAtIndex(j).FindPropertyRelative("m_Weight"); + if (maskSource.GetTransformPath(j) != serializedProperty3.stringValue || maskSource.GetTransformActive(j) != serializedProperty4.floatValue > 0.5f) + { + return true; + } + } + return false; + } public void MaskFromClip(AvatarMask mask) { SerializedProperty serializedProperty = this.Get("bodyMask"); @@ -321,6 +361,16 @@ public int GetCurveCount() } return result; } + public SerializedProperty GetCurveProperty(int index) + { + SerializedProperty result = null; + SerializedProperty serializedProperty = this.Get("curves"); + if (serializedProperty != null && serializedProperty.isArray) + { + result = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("curve"); + } + return result; + } public string GetCurveName(int index) { string result = string.Empty; @@ -342,19 +392,19 @@ public void SetCurveName(int index, string name) public AnimationCurve GetCurve(int index) { AnimationCurve result = null; - SerializedProperty serializedProperty = this.Get("curves"); - if (serializedProperty != null && serializedProperty.isArray) + SerializedProperty curveProperty = this.GetCurveProperty(index); + if (curveProperty != null) { - result = serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("curve").animationCurveValue; + result = curveProperty.animationCurveValue; } return result; } - public void SetCurve(int index, AnimationCurve curve) + public void SetCurve(int index, AnimationCurve curveValue) { - SerializedProperty serializedProperty = this.Get("curves"); - if (serializedProperty != null && serializedProperty.isArray) + SerializedProperty curveProperty = this.GetCurveProperty(index); + if (curveProperty != null) { - serializedProperty.GetArrayElementAtIndex(index).FindPropertyRelative("curve").animationCurveValue = curve; + curveProperty.animationCurveValue = curveValue; } } public void AddCurve() diff --git a/UnityEditor/UnityEditor/AnimationEventTimeLine.cs b/UnityEditor/UnityEditor/AnimationEventTimeLine.cs index 1f5cdaa5..ff4bcb7b 100644 --- a/UnityEditor/UnityEditor/AnimationEventTimeLine.cs +++ b/UnityEditor/UnityEditor/AnimationEventTimeLine.cs @@ -172,6 +172,7 @@ public void EventLineGUI(Rect rect, AnimationSelection selection, AnimationWindo animationEvent2.time = this.m_EventTimes[k] + zero.x * state.PixelDeltaToTime(rect); animationEvent2.time = Mathf.Max(0f, animationEvent2.time); animationEvent2.time = (float)Mathf.RoundToInt(animationEvent2.time * activeAnimationClip.frameRate) / activeAnimationClip.frameRate; + this.m_EventsAtMouseDown[k] = animationEvent2; } } int[] array3 = new int[this.m_EventsSelected.Length]; diff --git a/UnityEditor/UnityEditor/AnimationSelection.cs b/UnityEditor/UnityEditor/AnimationSelection.cs index 6bb843e8..4c79db6f 100644 --- a/UnityEditor/UnityEditor/AnimationSelection.cs +++ b/UnityEditor/UnityEditor/AnimationSelection.cs @@ -1,6 +1,6 @@ using System; using System.Collections; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -67,7 +67,7 @@ public bool hasAnimationComponent { get { - return this.animatedObject.GetComponent() != null || this.animatedObject.GetComponent() != null; + return this.animatedObject && (this.animatedObject.GetComponent() != null || this.animatedObject.GetComponent() != null); } } public AnimationClip clip @@ -420,7 +420,6 @@ internal static AnimationClip AllocateAndSetupClip(bool useAnimator) AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(animationClip); animationClipSettings.loopTime = true; AnimationUtility.SetAnimationClipSettingsNoDirty(animationClip, animationClipSettings); - AnimationUtility.SetAnimationType(animationClip, ModelImporterAnimationType.Generic); } return animationClip; } @@ -452,7 +451,7 @@ public static AnimationClip AddClipToAnimatorComponent(GameObject animatedObject AnimatorController animatorController = AnimatorController.GetEffectiveAnimatorController(animator); if (!(animatorController == null)) { - AnimatorController.AddAnimationClipToController(animatorController, newClip); + animatorController.AddMotion(newClip); return newClip; } animatorController = AnimatorController.CreateAnimatorControllerForClip(newClip, animatedObject); @@ -473,7 +472,7 @@ private AnimationClip AddClipToAnimationComponent(AnimationClip newClip) AnimationClip[] animationClips = AnimationUtility.GetAnimationClips(this.animatedObject); Array.Resize(ref animationClips, animationClips.Length + 1); animationClips[animationClips.Length - 1] = newClip; - AnimationUtility.SetAnimationClips(this.animatedObject.animation, animationClips); + AnimationUtility.SetAnimationClips(this.animatedObject.GetComponent(), animationClips); return newClip; } private void ChooseClip(AnimationClip newClip) diff --git a/UnityEditor/UnityEditor/AnimationUtility.cs b/UnityEditor/UnityEditor/AnimationUtility.cs index 3b27e890..31770898 100644 --- a/UnityEditor/UnityEditor/AnimationUtility.cs +++ b/UnityEditor/UnityEditor/AnimationUtility.cs @@ -39,7 +39,7 @@ public static AnimationClip[] GetAnimationClips(Animation component) public static extern bool GetObjectReferenceValue(GameObject root, EditorCurveBinding binding, out UnityEngine.Object targetObject); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern UnityEngine.Object GetAnimatedObject(GameObject gameObject, EditorCurveBinding binding); + public static extern UnityEngine.Object GetAnimatedObject(GameObject root, EditorCurveBinding binding); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Type PropertyModificationToEditorCurveBinding(PropertyModification modification, GameObject gameObject, out EditorCurveBinding binding); @@ -133,7 +133,7 @@ public static AnimationCurve GetEditorCurve(AnimationClip clip, string relativeP public static extern AnimationClipSettings GetAnimationClipSettings(AnimationClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void SetAnimationClipSettings(AnimationClip clip, AnimationClipSettings srcClipInfo); + public static extern void SetAnimationClipSettings(AnimationClip clip, AnimationClipSettings srcClipInfo); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetAnimationClipSettingsNoDirty(AnimationClip clip, AnimationClipSettings srcClipInfo); @@ -148,16 +148,28 @@ public static AnimationCurve GetEditorCurve(AnimationClip clip, string relativeP internal static extern bool CurveSupportsProcedural(AnimationCurve curve); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern ModelImporterAnimationType GetAnimationType(AnimationClip clip); + internal static extern AnimationClipStats GetAnimationClipStats(AnimationClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetAnimationType(AnimationClip clip, ModelImporterAnimationType type); + internal static extern bool GetGenerateMotionCurves(AnimationClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern AnimationClipStats GetAnimationClipStats(AnimationClip clip); + internal static extern void SetGenerateMotionCurves(AnimationClip clip, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasGenericRootTransform(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasMotionFloatCurves(AnimationClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasMotionCurves(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasRootCurves(AnimationClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool AmbiguousBinding(string path, int classID, Transform root); [Obsolete("Use AnimationMode.InAnimationMode instead")] public static bool InAnimationMode() { @@ -174,5 +186,9 @@ public static void StopAnimationMode() { AnimationMode.StopAnimationMode(); } + [Obsolete("SetAnimationType is no longer supported", true)] + public static void SetAnimationType(AnimationClip clip, ModelImporterAnimationType type) + { + } } } diff --git a/UnityEditor/UnityEditor/AnimationWindow.cs b/UnityEditor/UnityEditor/AnimationWindow.cs index 40dc87f9..b3c0c2b3 100644 --- a/UnityEditor/UnityEditor/AnimationWindow.cs +++ b/UnityEditor/UnityEditor/AnimationWindow.cs @@ -71,6 +71,10 @@ public Styles() internal static PrefKey kAnimationNextKeyframe = new PrefKey("Animation/Next Keyframe", "&."); internal static PrefKey kAnimationRecordKeyframe = new PrefKey("Animation/Record Keyframe", "k"); internal static PrefKey kAnimationShowCurvesToggle = new PrefKey("Animation/Show curves", "c"); + [NonSerialized] + private bool m_SelectionInitializedNonSerialized; + [SerializeField] + private bool m_SelectionInitializedSerialized; [SerializeField] private SerializedStringTable m_ExpandedFoldouts; [SerializeField] @@ -544,7 +548,7 @@ private GameObject[] GetAnimationComponentsInAllParents(Transform tr) List list = new List(); while (true) { - if (tr.animation || tr.GetComponent()) + if (tr.GetComponent() || tr.GetComponent()) { list.Add(tr.gameObject); } @@ -583,7 +587,7 @@ private void GenerateAnimationSelections() List list = new List(); GameObject gameObject = (!(Selection.activeGameObject != null)) ? this.state.m_ActiveGameObject : Selection.activeGameObject; Transform transform = (!gameObject) ? null : gameObject.transform; - if (transform == null) + if (transform == null && this.state.m_RootGameObject != null) { transform = ((!(this.state.m_RootGameObject != null)) ? null : this.state.m_RootGameObject.transform); this.state.m_ActiveGameObject = this.state.m_RootGameObject; @@ -621,15 +625,16 @@ private void GenerateAnimationSelections() } this.state.m_ActiveAnimationClip = AnimationWindow.m_Selected[0].clip; this.state.m_RootGameObject = AnimationWindow.m_Selected[0].avatarRootObject; - this.state.m_AnimatedGameObject = AnimationWindow.m_Selected[0].animatedObject; } else { - this.state.m_ActiveAnimationClip = null; - this.state.m_RootGameObject = null; - this.state.m_AnimatedGameObject = null; - this.state.m_ActiveGameObject = null; - this.state.refresh = AnimationWindowState.RefreshType.Everything; + if (Selection.activeObject != null) + { + this.state.m_ActiveAnimationClip = null; + this.state.m_RootGameObject = null; + this.state.m_ActiveGameObject = null; + this.state.refresh = AnimationWindowState.RefreshType.Everything; + } } if (flag && flag2) { @@ -698,6 +703,15 @@ private void ResampleAnimation() if (!(animatedObject == null)) { AnimationMode.SampleAnimationClip(animatedObject, clip, this.state.GetTimeSeconds()); + Animation component = animatedObject.GetComponent(); + if (component) + { + AnimationState animationState = component[clip.name]; + if (animationState) + { + animationState.time = this.state.GetTimeSeconds(); + } + } } } } @@ -872,7 +886,7 @@ public void TimeLineGUI(Rect rect, bool onlyDopesheetLines, bool sparseLines, bo GUI.EndGroup(); return; } - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); Color backgroundColor = GUI.backgroundColor; if (sparseLines) @@ -949,7 +963,7 @@ private void SecondaryTickMarksGUI(Rect rect) return; } this.m_CurveEditor.hTicks.SetTickStrengths((float)this.m_CurveEditor.settings.hTickStyle.distMin, (float)this.m_CurveEditor.settings.hTickStyle.distFull, false); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); for (int i = 0; i < this.m_CurveEditor.hTicks.tickLevels; i++) { @@ -978,16 +992,18 @@ public void OnGUI() } this.state.OnGUI(); this.InitAllViews(); - if (this.state.m_ActiveGameObject == null) + if (!this.m_SelectionInitializedNonSerialized) { + if (!this.m_SelectionInitializedSerialized) + { + this.state.m_ShowCurveEditor = false; + this.m_SelectionInitializedSerialized = true; + } AnimationWindow.m_Selected = null; - this.state.m_ShowCurveEditor = false; - } - if (AnimationWindow.m_Selected == null) - { this.OnSelectionChange(); + this.m_SelectionInitializedNonSerialized = true; } - if (AnimationWindow.m_Selected.Length == 0) + if (AnimationWindow.m_Selected != null && AnimationWindow.m_Selected.Length == 0) { this.EndAnimationMode(); } @@ -995,6 +1011,10 @@ public void OnGUI() { return; } + if (this.state.m_ActiveAnimationClip == null && AnimationMode.InAnimationMode()) + { + this.EndAnimationMode(); + } if (this.m_CurveEditorToggleChanged) { this.m_CurveEditorToggleChanged = false; @@ -1104,7 +1124,7 @@ public void OnGUI() this.PreviewFrame(num2); } EditorGUI.EndDisabledGroup(); - EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + EditorGUI.BeginDisabledGroup(!this.state.IsClipEditable); if ((GUILayout.Button(AnimationWindow.ms_Styles.addKeyframeContent, EditorStyles.toolbarButton, new GUILayoutOption[0]) || AnimationWindow.kAnimationRecordKeyframe.activated) && this.EnsureAnimationMode()) { AnimationWindowUtility.AddSelectedKeyframes(this.state, this.state.time); @@ -1147,7 +1167,7 @@ public void OnGUI() EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); GUILayoutUtility.GetRect((float)num, base.position.height - 17f - 18f - 15f); - if (AnimationWindow.m_Selected.Length > 0) + if (AnimationWindow.m_Selected.Length > 0 && AnimationWindow.m_Selected[0].GameObjectIsAnimatable) { this.HierarchyGUI(num, (int)rect4.height - 15); } @@ -1226,7 +1246,7 @@ public void OnGUI() this.HandlePlayhead((float)num, rect2); if (AnimationWindow.m_Selected.Length > 0) { - EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + EditorGUI.BeginDisabledGroup(!this.state.IsClipEditable); this.HandlePlayhead((float)num, rect3); this.m_AnimationEventTimeLine.EventLineGUI(rect3, AnimationWindow.m_Selected[0], this.state, this.m_CurveEditor); EditorGUI.EndDisabledGroup(); @@ -1354,7 +1374,7 @@ public static void DrawPlayHead(Vector2 start, Vector2 end, float alpha) } private static void DrawLine(Vector2 p1, Vector2 p2, Color color) { - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(1); @@ -1370,7 +1390,7 @@ private static void DrawRect(Vector3[] corners, Color color) { return; } - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(7); @@ -1438,6 +1458,11 @@ public void OnSelectionChange() } this.InitSelection(); } + public void OnBecameVisible() + { + this.m_SelectionInitializedNonSerialized = false; + this.m_SelectionInitializedSerialized = false; + } private void SetGridColors() { CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); diff --git a/UnityEditor/UnityEditor/AnimatorInspector.cs b/UnityEditor/UnityEditor/AnimatorInspector.cs index 4677ddb4..cff3d6a5 100644 --- a/UnityEditor/UnityEditor/AnimatorInspector.cs +++ b/UnityEditor/UnityEditor/AnimatorInspector.cs @@ -1,15 +1,64 @@ using System; +using UnityEditor.AnimatedValues; using UnityEngine; +using UnityEngine.Events; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(Animator))] internal class AnimatorInspector : Editor { + private class Styles + { + public GUIContent applyRootMotion = new GUIContent(EditorGUIUtility.TextContent("Apply Root Motion")); + public GUIContent updateMode = new GUIContent(EditorGUIUtility.TextContent("Update Mode")); + public GUIContent cullingMode = new GUIContent(EditorGUIUtility.TextContent("Culling Mode")); + public Styles() + { + this.applyRootMotion.tooltip = "Automatically move the object using the root motion from the animations"; + this.updateMode.tooltip = "Controls when and how often the Animator is updated"; + this.cullingMode.tooltip = "Controls what is updated when the object has been culled"; + } + } private SerializedProperty m_Controller; private SerializedProperty m_Avatar; private SerializedProperty m_ApplyRootMotion; private SerializedProperty m_UpdateMode; private SerializedProperty m_CullingMode; + private SerializedProperty m_WarningMessage; + private AnimBool m_ShowWarningMessage = new AnimBool(); + private bool m_IsRootPositionOrRotationControlledByCurves; + private static AnimatorInspector.Styles styles; + private bool IsWarningMessageEmpty + { + get + { + return this.m_WarningMessage != null && this.m_WarningMessage.stringValue.Length > 0; + } + } + private string WarningMessage + { + get + { + return (this.m_WarningMessage == null) ? string.Empty : this.m_WarningMessage.stringValue; + } + } + private void Init() + { + if (AnimatorInspector.styles == null) + { + AnimatorInspector.styles = new AnimatorInspector.Styles(); + } + this.InitShowOptions(); + } + private void InitShowOptions() + { + this.m_ShowWarningMessage.value = this.IsWarningMessageEmpty; + this.m_ShowWarningMessage.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + private void UpdateShowOptions() + { + this.m_ShowWarningMessage.target = this.IsWarningMessageEmpty; + } private void OnEnable() { this.m_Controller = base.serializedObject.FindProperty("m_Controller"); @@ -17,12 +66,15 @@ private void OnEnable() this.m_ApplyRootMotion = base.serializedObject.FindProperty("m_ApplyRootMotion"); this.m_UpdateMode = base.serializedObject.FindProperty("m_UpdateMode"); this.m_CullingMode = base.serializedObject.FindProperty("m_CullingMode"); + this.m_WarningMessage = base.serializedObject.FindProperty("m_WarningMessage"); + this.Init(); } public override void OnInspectorGUI() { bool flag = base.targets.Length > 1; Animator animator = this.target as Animator; base.serializedObject.UpdateIfDirtyOrScript(); + this.UpdateShowOptions(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_Controller, new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) @@ -36,14 +88,27 @@ public override void OnInspectorGUI() } else { - EditorGUILayout.PropertyField(this.m_ApplyRootMotion, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ApplyRootMotion, AnimatorInspector.styles.applyRootMotion, new GUILayoutOption[0]); + if (Event.current.type == EventType.Layout) + { + this.m_IsRootPositionOrRotationControlledByCurves = animator.isRootPositionOrRotationControlledByCurves; + } + if (!this.m_ApplyRootMotion.boolValue && this.m_IsRootPositionOrRotationControlledByCurves) + { + EditorGUILayout.HelpBox("Root position or rotation are controlled by curves", MessageType.Info, true); + } } - EditorGUILayout.PropertyField(this.m_UpdateMode, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_CullingMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UpdateMode, AnimatorInspector.styles.updateMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CullingMode, AnimatorInspector.styles.cullingMode, new GUILayoutOption[0]); if (!flag) { EditorGUILayout.HelpBox(animator.GetStats(), MessageType.Info, true); } + if (EditorGUILayout.BeginFadeGroup(this.m_ShowWarningMessage.faded)) + { + EditorGUILayout.HelpBox(this.WarningMessage, MessageType.Warning, true); + } + EditorGUILayout.EndFadeGroup(); base.serializedObject.ApplyModifiedProperties(); } } diff --git a/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs b/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs index be505007..7c7bfeed 100644 --- a/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs +++ b/UnityEditor/UnityEditor/AnimatorOverrideControllerInspector.cs @@ -1,4 +1,5 @@ using System; +using UnityEditor.Animations; using UnityEditorInternal; using UnityEngine; namespace UnityEditor @@ -37,7 +38,7 @@ public override void OnInspectorGUI() AnimatorOverrideController animatorOverrideController = this.target as AnimatorOverrideController; RuntimeAnimatorController runtimeAnimatorController = (!this.m_Controller.hasMultipleDifferentValues) ? animatorOverrideController.runtimeAnimatorController : null; EditorGUI.BeginChangeCheck(); - runtimeAnimatorController = (EditorGUILayout.ObjectField("Controller", runtimeAnimatorController, typeof(AnimatorController), false, new GUILayoutOption[0]) as RuntimeAnimatorController); + runtimeAnimatorController = (EditorGUILayout.ObjectField("Controller", runtimeAnimatorController, typeof(UnityEditor.Animations.AnimatorController), false, new GUILayoutOption[0]) as RuntimeAnimatorController); if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < base.targets.Length; i++) diff --git a/UnityEditor/UnityEditor/AnnotationWindow.cs b/UnityEditor/UnityEditor/AnnotationWindow.cs index 78880fa7..0aba3ef2 100644 --- a/UnityEditor/UnityEditor/AnnotationWindow.cs +++ b/UnityEditor/UnityEditor/AnnotationWindow.cs @@ -35,6 +35,7 @@ public Styles() this.columnHeaderStyle = new GUIStyle(EditorStyles.miniLabel); } } + private const float kWindowWidth = 270f; private const float scrollBarWidth = 14f; private const float listElementHeight = 18f; private const float gizmoRightAlign = 23f; diff --git a/UnityEditor/UnityEditor/AppStatusBar.cs b/UnityEditor/UnityEditor/AppStatusBar.cs index 4c02a64b..198137b7 100644 --- a/UnityEditor/UnityEditor/AppStatusBar.cs +++ b/UnityEditor/UnityEditor/AppStatusBar.cs @@ -94,8 +94,8 @@ private void OnGUI() float num = base.position.width - 24f; if (AsyncProgressBar.isShowing) { - num -= 143f; - EditorGUI.ProgressBar(new Rect(num, 0f, 140f, 19f), AsyncProgressBar.progress, AsyncProgressBar.progressInfo); + num -= 188f; + EditorGUI.ProgressBar(new Rect(num, 0f, 185f, 19f), AsyncProgressBar.progress, AsyncProgressBar.progressInfo); } if (isCompiling) { diff --git a/UnityEditor/UnityEditor/AssemblyHelper.cs b/UnityEditor/UnityEditor/AssemblyHelper.cs index 0ff15361..c6446645 100644 --- a/UnityEditor/UnityEditor/AssemblyHelper.cs +++ b/UnityEditor/UnityEditor/AssemblyHelper.cs @@ -6,12 +6,24 @@ using System.Linq; using System.Reflection; using UnityEditor.Modules; +using UnityEditor.Scripting.Compilers; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { - public class AssemblyHelper + internal class AssemblyHelper { private const int kDefaultDepth = 10; + public static bool IsWindowsRuntimeAssembly(string assemblyPath) + { + bool isWindowsRuntime; + using (FileStream fileStream = File.Open(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + AssemblyDefinition assemblyDefinition = AssemblyDefinition.ReadAssembly(fileStream); + isWindowsRuntime = assemblyDefinition.Name.IsWindowsRuntime; + } + return isWindowsRuntime; + } public static void CheckForAssemblyFileNameMismatch(string assemblyPath) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assemblyPath); @@ -28,10 +40,6 @@ public static void CheckForAssemblyFileNameMismatch(string assemblyPath) })); } } - public static bool IsTypeInEditorAssembly(Type t) - { - return t.Assembly.GetCustomAttributes(true).Any((object x) => x is AssemblyIsEditorAssembly); - } public static string[] GetNamesOfAssembliesLoadedInCurrentDomain() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); @@ -91,7 +99,7 @@ private static bool IgnoreAssembly(string assemblyPath, BuildTarget target) { if (target == BuildTarget.WP8Player) { - if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("Microsoft.") != -1) + if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("Microsoft.") != -1 || assemblyPath.IndexOf("platform.dll") != -1) { return true; } @@ -99,7 +107,7 @@ private static bool IgnoreAssembly(string assemblyPath, BuildTarget target) } else { - if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("WinRTLegacy.dll") != -1) + if (assemblyPath.IndexOf("mscorlib.dll") != -1 || assemblyPath.IndexOf("System.") != -1 || assemblyPath.IndexOf("Windows.dll") != -1 || assemblyPath.IndexOf("WinRTLegacy.dll") != -1 || assemblyPath.IndexOf("platform.dll") != -1) { return true; } @@ -122,22 +130,51 @@ private static void AddReferencedAssembliesRecurse(string assemblyPath, List source = ( + from i in PluginImporter.GetImporters(target).Where(delegate(PluginImporter i) + { + string platformData = i.GetPlatformData(target, "CPU"); + return !string.IsNullOrEmpty(platformData) && !string.Equals(platformData, "AnyCPU", StringComparison.InvariantCultureIgnoreCase); + }) + select Path.GetFileName(i.assetPath)).Distinct(); + foreach (AssemblyNameReference referencedAssembly in assemblyDefinitionCached.MainModule.AssemblyReferences) { - if (!(current.Name == "BridgeInterface")) + if (!(referencedAssembly.Name == "BridgeInterface")) { - if (!(current.Name == "WinRTBridge")) + if (!(referencedAssembly.Name == "WinRTBridge")) { - if (!(current.Name == "UnityEngineProxy")) + if (!(referencedAssembly.Name == "UnityEngineProxy")) { - if (!AssemblyHelper.IgnoreAssembly(current.Name + ".dll", target)) + if (!AssemblyHelper.IgnoreAssembly(referencedAssembly.Name + ".dll", target)) { - string text = AssemblyHelper.FindAssemblyName(current.FullName, current.Name, allAssemblyPaths, foldersToSearch, cache); + string text = AssemblyHelper.FindAssemblyName(referencedAssembly.FullName, referencedAssembly.Name, allAssemblyPaths, foldersToSearch, cache); if (text == string.Empty) { - throw new ArgumentException(string.Format("The Assembly {0} is referenced by {1}. But the dll is not allowed to be included or could not be found.", current.Name, assemblyDefinitionCached.MainModule.Assembly.Name.Name)); + bool flag = false; + string[] array = new string[] + { + ".dll", + ".winmd" + }; + string extension; + for (int j = 0; j < array.Length; j++) + { + extension = array[j]; + if (source.Any((string p) => string.Equals(p, referencedAssembly.Name + extension, StringComparison.InvariantCultureIgnoreCase))) + { + flag = true; + break; + } + } + if (!flag) + { + throw new ArgumentException(string.Format("The Assembly {0} is referenced by {1} ('{2}'). But the dll is not allowed to be included or could not be found.", referencedAssembly.Name, assemblyDefinitionCached.MainModule.Assembly.Name.Name, assemblyPath)); + } + } + else + { + AssemblyHelper.AddReferencedAssembliesRecurse(text, alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache, target); } - AssemblyHelper.AddReferencedAssembliesRecurse(text, alreadyFoundAssemblies, allAssemblyPaths, foldersToSearch, cache, target); } } } @@ -254,11 +291,38 @@ public static void ExtractAllClassesThatInheritMonoBehaviourAndScriptableObject( classNamesArray = list.ToArray(); classNameSpacesArray = list2.ToArray(); } - public static AssemblyTypeInfoGenerator.ClassInfo[] ExtractAssemblyTypeInfo(string assemblyPathName) + public static AssemblyTypeInfoGenerator.ClassInfo[] ExtractAssemblyTypeInfo(BuildTarget targetPlatform, bool isEditor, string assemblyPathName, string[] searchDirs) { - AssemblyTypeInfoGenerator assemblyTypeInfoGenerator = new AssemblyTypeInfoGenerator(assemblyPathName); - assemblyTypeInfoGenerator.GatherClassInfo(); - return assemblyTypeInfoGenerator.ClassInfoArray; + if (CSharpLanguage.GetUseMicrosoftCSharpCompiler(targetPlatform, isEditor, assemblyPathName)) + { + WSASDK wSASDK = EditorUserBuildSettings.wsaSDK; + if (wSASDK == WSASDK.UniversalSDK81) + { + wSASDK = WSASDK.SDK81; + } + string nETCoreFrameworkReferencesDirectory = MicrosoftCSharpCompiler.GetNETCoreFrameworkReferencesDirectory(wSASDK); + searchDirs = new List(searchDirs) + { + nETCoreFrameworkReferencesDirectory + }.ToArray(); + } + AssemblyTypeInfoGenerator.ClassInfo[] result; + try + { + AssemblyTypeInfoGenerator assemblyTypeInfoGenerator = new AssemblyTypeInfoGenerator(assemblyPathName, searchDirs); + result = assemblyTypeInfoGenerator.GatherClassInfo(); + } + catch (Exception ex) + { + throw new Exception(string.Concat(new object[] + { + "ExtractAssemblyTypeInfo: Failed to process ", + assemblyPathName, + ", ", + ex + })); + } + return result; } internal static Type[] GetTypesFromAssembly(Assembly assembly) { @@ -280,34 +344,16 @@ internal static Type[] GetTypesFromAssembly(Assembly assembly) [DebuggerHidden] internal static IEnumerable FindImplementors(Assembly assembly) where T : class { - AssemblyHelper.c__Iterator0 c__Iterator = new AssemblyHelper.c__Iterator0(); + AssemblyHelper.c__Iterator1 c__Iterator = new AssemblyHelper.c__Iterator1(); c__Iterator.assembly = assembly; c__Iterator.<$>assembly = assembly; - AssemblyHelper.c__Iterator0 expr_15 = c__Iterator; + AssemblyHelper.c__Iterator1 expr_15 = c__Iterator; expr_15.$PC = -2; return expr_15; } public static bool IsManagedAssembly(string file) { - if (!".dll".Equals(Path.GetExtension(file), StringComparison.OrdinalIgnoreCase)) - { - return false; - } - try - { - using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - BinaryReader binaryReader = new BinaryReader(stream); - stream.Position = 60L; - uint num = binaryReader.ReadUInt32(); - stream.Position = (long)((ulong)(num + 232u)); - return 0uL != binaryReader.ReadUInt64(); - } - } - catch - { - } - return false; + return InternalEditorUtility.DetectDotNetDll(file); } public static bool IsInternalAssembly(string file) { diff --git a/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs b/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs index 13706483..0ad44914 100644 --- a/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs +++ b/UnityEditor/UnityEditor/AssemblyTypeInfoGenerator.cs @@ -1,11 +1,13 @@ using Mono.Cecil; using Mono.Collections.Generic; using System; +using System.Collections; using System.Collections.Generic; using System.Linq; +using Unity.SerializationLogic; namespace UnityEditor { - public class AssemblyTypeInfoGenerator + internal class AssemblyTypeInfoGenerator { public struct FieldInfo { @@ -17,8 +19,41 @@ public struct ClassInfo public string name; public AssemblyTypeInfoGenerator.FieldInfo[] fields; } + private class AssemblyResolver : BaseAssemblyResolver + { + private readonly IDictionary m_Assemblies; + private AssemblyResolver() : this(new Hashtable()) + { + } + private AssemblyResolver(IDictionary assemblyCache) + { + this.m_Assemblies = assemblyCache; + } + public static IAssemblyResolver WithSearchDirs(params string[] searchDirs) + { + AssemblyTypeInfoGenerator.AssemblyResolver assemblyResolver = new AssemblyTypeInfoGenerator.AssemblyResolver(); + for (int i = 0; i < searchDirs.Length; i++) + { + string directory = searchDirs[i]; + assemblyResolver.AddSearchDirectory(directory); + } + return assemblyResolver; + } + public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) + { + AssemblyDefinition assemblyDefinition = (AssemblyDefinition)this.m_Assemblies[name.Name]; + if (assemblyDefinition != null) + { + return assemblyDefinition; + } + assemblyDefinition = base.Resolve(name, parameters); + this.m_Assemblies[name.Name] = assemblyDefinition; + return assemblyDefinition; + } + } private AssemblyDefinition assembly_; private List classes_ = new List(); + private TypeResolver typeResolver = new TypeResolver(null); public AssemblyTypeInfoGenerator.ClassInfo[] ClassInfoArray { get @@ -26,13 +61,33 @@ public AssemblyTypeInfoGenerator.ClassInfo[] ClassInfoArray return this.classes_.ToArray(); } } - public AssemblyTypeInfoGenerator(string assembly) + public AssemblyTypeInfoGenerator(string assembly, string[] searchDirs) { - this.assembly_ = AssemblyDefinition.ReadAssembly(assembly); + this.assembly_ = AssemblyDefinition.ReadAssembly(assembly, new ReaderParameters + { + AssemblyResolver = AssemblyTypeInfoGenerator.AssemblyResolver.WithSearchDirs(searchDirs) + }); } - private string GetFullTypeName(TypeReference type) + private string GetMonoEmbeddedFullTypeNameFor(TypeReference type) { - return type.FullName.Replace('/', '+').Replace('<', '[').Replace('>', ']'); + TypeSpecification typeSpecification = type as TypeSpecification; + string fullName; + if (typeSpecification != null && typeSpecification.IsRequiredModifier) + { + fullName = typeSpecification.ElementType.FullName; + } + else + { + if (type.IsRequiredModifier) + { + fullName = type.GetElementType().FullName; + } + else + { + fullName = type.FullName; + } + } + return fullName.Replace('/', '+').Replace('<', '[').Replace('>', ']'); } private TypeReference ResolveGenericInstanceType(TypeReference typeToResolve, Dictionary genericInstanceTypeMap) { @@ -54,7 +109,7 @@ private TypeReference ResolveGenericInstanceType(TypeReference typeToResolve, Di } private void AddType(TypeReference typeRef, Dictionary genericInstanceTypeMap) { - if (this.classes_.Any((AssemblyTypeInfoGenerator.ClassInfo x) => x.name == this.GetFullTypeName(typeRef))) + if (this.classes_.Any((AssemblyTypeInfoGenerator.ClassInfo x) => x.name == this.GetMonoEmbeddedFullTypeNameFor(typeRef))) { return; } @@ -67,6 +122,14 @@ private void AddType(TypeReference typeRef, Dictionary genericArguments = ((GenericInstanceType)typeRef).GenericArguments; @@ -78,13 +141,33 @@ private void AddType(TypeReference typeRef, Dictionary genericInstanceTypeMap) { @@ -132,20 +215,7 @@ private AssemblyTypeInfoGenerator.FieldInfo[] GetFields(TypeDefinition type, boo } private AssemblyTypeInfoGenerator.FieldInfo? GetFieldInfo(TypeDefinition type, FieldDefinition field, bool isDeclaringTypeGenericInstance, Dictionary genericInstanceTypeMap) { - if (field.IsStatic) - { - return null; - } - if (field.IsInitOnly) - { - return null; - } - if ((ushort)(field.Attributes & FieldAttributes.NotSerialized) != 0) - { - return null; - } - bool flag = field.CustomAttributes.Any((CustomAttribute ca) => ca.AttributeType.Name == "SerializeField"); - if (!field.IsPublic && !flag) + if (!this.WillSerialize(field)) { return null; } @@ -160,10 +230,23 @@ private AssemblyTypeInfoGenerator.FieldInfo[] GetFields(TypeDefinition type, boo { type2 = field.FieldType; } - value.type = this.GetFullTypeName(type2); + value.type = this.GetMonoEmbeddedFullTypeNameFor(type2); return new AssemblyTypeInfoGenerator.FieldInfo?(value); } - public void GatherClassInfo() + private bool WillSerialize(FieldDefinition field) + { + bool result; + try + { + result = UnitySerializationLogic.WillUnitySerialize(field, this.typeResolver); + } + catch (Exception) + { + result = false; + } + return result; + } + public AssemblyTypeInfoGenerator.ClassInfo[] GatherClassInfo() { foreach (ModuleDefinition current in this.assembly_.Modules) { @@ -175,6 +258,7 @@ public void GatherClassInfo() } } } + return this.classes_.ToArray(); } } } diff --git a/UnityEditor/UnityEditor/AssetBundleBuild.cs b/UnityEditor/UnityEditor/AssetBundleBuild.cs new file mode 100644 index 00000000..e277a7a5 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetBundleBuild.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public struct AssetBundleBuild + { + public string assetBundleName; + public string assetBundleVariant; + public string[] assetNames; + } +} diff --git a/UnityEditor/UnityEditor/AssetBundleNameGUI.cs b/UnityEditor/UnityEditor/AssetBundleNameGUI.cs new file mode 100644 index 00000000..b43132da --- /dev/null +++ b/UnityEditor/UnityEditor/AssetBundleNameGUI.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetBundleNameGUI + { + private class Styles + { + private static GUISkin s_DarkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); + public static GUIStyle label = AssetBundleNameGUI.Styles.GetStyle("ControlLabel"); + public static GUIStyle popup = AssetBundleNameGUI.Styles.GetStyle("MiniPopup"); + public static GUIStyle textField = AssetBundleNameGUI.Styles.GetStyle("textField"); + public static Color cursorColor = AssetBundleNameGUI.Styles.s_DarkSkin.settings.cursorColor; + private static GUIStyle GetStyle(string name) + { + return new GUIStyle(AssetBundleNameGUI.Styles.s_DarkSkin.GetStyle(name)); + } + } + private static readonly GUIContent kAssetBundleName = new GUIContent("AssetBundle"); + private static readonly int kAssetBundleNameFieldIdHash = "AssetBundleNameFieldHash".GetHashCode(); + private static readonly int kAssetBundleVariantFieldIdHash = "AssetBundleVariantFieldHash".GetHashCode(); + private bool m_ShowAssetBundleNameTextField; + private bool m_ShowAssetBundleVariantTextField; + public void OnAssetBundleNameGUI(IEnumerable assets) + { + EditorGUIUtility.labelWidth = 90f; + Rect rect = EditorGUILayout.GetControlRect(true, 16f, new GUILayoutOption[0]); + Rect rect2 = rect; + rect.width *= 0.8f; + rect2.xMin += rect.width + 5f; + int controlID = GUIUtility.GetControlID(AssetBundleNameGUI.kAssetBundleNameFieldIdHash, FocusType.Native, rect); + rect = EditorGUI.PrefixLabel(rect, controlID, AssetBundleNameGUI.kAssetBundleName, AssetBundleNameGUI.Styles.label); + if (this.m_ShowAssetBundleNameTextField) + { + this.AssetBundleTextField(rect, controlID, assets, false); + } + else + { + this.AssetBundlePopup(rect, controlID, assets, false); + } + controlID = GUIUtility.GetControlID(AssetBundleNameGUI.kAssetBundleVariantFieldIdHash, FocusType.Native, rect2); + if (this.m_ShowAssetBundleVariantTextField) + { + this.AssetBundleTextField(rect2, controlID, assets, true); + } + else + { + this.AssetBundlePopup(rect2, controlID, assets, true); + } + } + private void ShowNewAssetBundleField(bool isVariant) + { + this.m_ShowAssetBundleNameTextField = !isVariant; + this.m_ShowAssetBundleVariantTextField = isVariant; + EditorGUIUtility.editingTextField = true; + } + private void AssetBundleTextField(Rect rect, int id, IEnumerable assets, bool isVariant) + { + Color cursorColor = GUI.skin.settings.cursorColor; + GUI.skin.settings.cursorColor = AssetBundleNameGUI.Styles.cursorColor; + EditorGUI.BeginChangeCheck(); + string name = EditorGUI.DelayedTextField(rect, id, string.Empty, null, AssetBundleNameGUI.Styles.textField); + if (EditorGUI.EndChangeCheck()) + { + this.SetAssetBundleForAssets(assets, name, isVariant); + this.ShowAssetBundlePopup(); + } + GUI.skin.settings.cursorColor = cursorColor; + if (!EditorGUI.IsEditingTextField() && Event.current.type != EventType.Layout) + { + this.ShowAssetBundlePopup(); + } + } + private void ShowAssetBundlePopup() + { + this.m_ShowAssetBundleNameTextField = false; + this.m_ShowAssetBundleVariantTextField = false; + } + private void AssetBundlePopup(Rect rect, int id, IEnumerable assets, bool isVariant) + { + List list = new List(); + list.Add("None"); + list.Add(string.Empty); + bool flag; + IEnumerable assetBundlesFromAssets = this.GetAssetBundlesFromAssets(assets, isVariant, out flag); + string[] collection = (!isVariant) ? AssetDatabase.GetAllAssetBundleNamesWithoutVariant() : AssetDatabase.GetAllAssetBundleVariants(); + list.AddRange(collection); + list.Add(string.Empty); + int count = list.Count; + list.Add("New..."); + int num = -1; + int num2 = -1; + if (!isVariant) + { + num = list.Count; + list.Add("Remove Unused Names"); + num2 = list.Count; + if (assetBundlesFromAssets.Count() != 0) + { + list.Add("Filter Selected Name" + ((!flag) ? string.Empty : "s")); + } + } + int num3 = 0; + string text = assetBundlesFromAssets.FirstOrDefault(); + if (!string.IsNullOrEmpty(text)) + { + num3 = list.IndexOf(text); + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = flag; + num3 = EditorGUI.DoPopup(rect, id, num3, EditorGUIUtility.TempContent(list.ToArray()), AssetBundleNameGUI.Styles.popup); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + if (num3 == 0) + { + this.SetAssetBundleForAssets(assets, null, isVariant); + } + else + { + if (num3 == count) + { + this.ShowNewAssetBundleField(isVariant); + } + else + { + if (num3 == num) + { + AssetDatabase.RemoveUnusedAssetBundleNames(); + } + else + { + if (num3 == num2) + { + this.FilterSelected(assetBundlesFromAssets); + } + else + { + this.SetAssetBundleForAssets(assets, list[num3], isVariant); + } + } + } + } + } + } + private void FilterSelected(IEnumerable assetBundleNames) + { + SearchFilter searchFilter = new SearchFilter(); + searchFilter.assetBundleNames = ( + from name in assetBundleNames + where !string.IsNullOrEmpty(name) + select name).ToArray(); + if (ProjectBrowser.s_LastInteractedProjectBrowser != null) + { + ProjectBrowser.s_LastInteractedProjectBrowser.SetSearch(searchFilter); + } + else + { + Debug.LogWarning("No Project Browser found to apply AssetBundle filter."); + } + } + private IEnumerable GetAssetBundlesFromAssets(IEnumerable assets, bool isVariant, out bool isMixed) + { + HashSet hashSet = new HashSet(); + string text = null; + isMixed = false; + foreach (UnityEngine.Object current in assets) + { + if (!(current is MonoScript)) + { + AssetImporter atPath = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(current)); + if (!(atPath == null)) + { + string text2 = (!isVariant) ? atPath.assetBundleName : atPath.assetBundleVariant; + if (text != null && text != text2) + { + isMixed = true; + } + text = text2; + if (!string.IsNullOrEmpty(text2)) + { + hashSet.Add(text2); + } + } + } + } + return hashSet; + } + private void SetAssetBundleForAssets(IEnumerable assets, string name, bool isVariant) + { + foreach (UnityEngine.Object current in assets) + { + if (!(current is MonoScript)) + { + AssetImporter atPath = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(current)); + if (!(atPath == null)) + { + if (isVariant) + { + atPath.assetBundleVariant = name; + } + else + { + atPath.assetBundleName = name; + } + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AssetDatabase.cs b/UnityEditor/UnityEditor/AssetDatabase.cs index 4636d8c1..06e5b2fa 100644 --- a/UnityEditor/UnityEditor/AssetDatabase.cs +++ b/UnityEditor/UnityEditor/AssetDatabase.cs @@ -14,67 +14,6 @@ internal static extern bool isLocked [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static string[] FindAssets(string filter) - { - return AssetDatabase.FindAssets(filter, null); - } - public static string[] FindAssets(string filter, string[] searchInFolders) - { - SearchFilter searchFilter = new SearchFilter(); - SearchUtility.ParseSearchString(filter, searchFilter); - if (searchInFolders != null) - { - searchFilter.folders = searchInFolders; - } - return AssetDatabase.FindAssets(searchFilter); - } - private static string[] FindAssets(SearchFilter searchFilter) - { - if (searchFilter.folders != null && searchFilter.folders.Length > 0) - { - return AssetDatabase.SearchInFolders(searchFilter); - } - return AssetDatabase.SearchAllAssets(searchFilter); - } - private static string[] SearchAllAssets(SearchFilter searchFilter) - { - HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); - hierarchyProperty.SetSearchFilter(searchFilter); - hierarchyProperty.Reset(); - List list = new List(); - while (hierarchyProperty.Next(null)) - { - list.Add(hierarchyProperty.guid); - } - return list.ToArray(); - } - private static string[] SearchInFolders(SearchFilter searchFilter) - { - HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); - List list = new List(); - string[] folders = searchFilter.folders; - for (int i = 0; i < folders.Length; i++) - { - string text = folders[i]; - hierarchyProperty.SetSearchFilter(new SearchFilter()); - int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(text); - if (hierarchyProperty.Find(mainAssetInstanceID, null)) - { - hierarchyProperty.SetSearchFilter(searchFilter); - int depth = hierarchyProperty.depth; - int[] expanded = null; - while (hierarchyProperty.NextWithDepthCheck(expanded, depth + 1)) - { - list.Add(hierarchyProperty.guid); - } - } - else - { - Debug.LogWarning("AssetDatabase.FindAssets: Folder not found: '" + text + "'"); - } - } - return list.ToArray(); - } public static bool Contains(UnityEngine.Object obj) { return AssetDatabase.Contains(obj.GetInstanceID()); @@ -140,16 +79,28 @@ public static void ImportAsset(string path) public static extern bool WriteImportSettingsIfDirty(string path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetSubFolders(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsValidFolder(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CreateAsset(UnityEngine.Object asset, string path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void AddObjectToAsset(UnityEngine.Object objectToAdd, string assetPath); + internal static extern void CreateAssetFromObjects(UnityEngine.Object[] assets, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AddObjectToAsset(UnityEngine.Object objectToAdd, string path); public static void AddObjectToAsset(UnityEngine.Object objectToAdd, UnityEngine.Object assetObject) { AssetDatabase.AddObjectToAsset_OBJ_Internal(objectToAdd, assetObject); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void AddInstanceIDToAssetWithRandomFileId(int instanceIDToAdd, UnityEngine.Object assetObject, bool hide); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AddObjectToAsset_OBJ_Internal(UnityEngine.Object newAsset, UnityEngine.Object sameAssetFile); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -167,9 +118,14 @@ public static string GetAssetPath(int instanceID) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetAssetOrScenePath(UnityEngine.Object assetObject); + [Obsolete("GetTextMetaDataPathFromAssetPath has been renamed to GetTextMetaFilePathFromAssetPath (UnityUpgradable).", true)] + public static string GetTextMetaDataPathFromAssetPath(string path) + { + return null; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string GetTextMetaDataPathFromAssetPath(string path); + public static extern string GetTextMetaFilePathFromAssetPath(string path); [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern UnityEngine.Object LoadAssetAtPath(string assetPath, Type type); @@ -279,6 +235,35 @@ internal static Dictionary GetAllLabels() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string[] MatchLabelsPartial(UnityEngine.Object obj, string partial); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAllAssetBundleNames(); + [Obsolete("Method GetAssetBundleNames has been deprecated. Use GetAllAssetBundleNames instead.")] + public string[] GetAssetBundleNames() + { + return AssetDatabase.GetAllAssetBundleNames(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string[] GetAllAssetBundleNamesWithoutVariant(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string[] GetAllAssetBundleVariants(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetUnusedAssetBundleNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool RemoveAssetBundleName(string assetBundleName, bool forceRemove); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemoveUnusedAssetBundleNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAssetPathsFromAssetBundle(string assetBundleName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetAssetPathsFromAssetBundleAndAssetName(string assetBundleName, string assetName); private static string[] GetDependencies(string pathName) { return AssetDatabase.GetDependencies(new string[] @@ -358,5 +343,66 @@ public static T GetBuiltinExtraResource(string path) where T : UnityEngine.Ob { return (T)((object)AssetDatabase.GetBuiltinExtraResource(typeof(T), path)); } + public static string[] FindAssets(string filter) + { + return AssetDatabase.FindAssets(filter, null); + } + public static string[] FindAssets(string filter, string[] searchInFolders) + { + SearchFilter searchFilter = new SearchFilter(); + SearchUtility.ParseSearchString(filter, searchFilter); + if (searchInFolders != null) + { + searchFilter.folders = searchInFolders; + } + return AssetDatabase.FindAssets(searchFilter); + } + private static string[] FindAssets(SearchFilter searchFilter) + { + if (searchFilter.folders != null && searchFilter.folders.Length > 0) + { + return AssetDatabase.SearchInFolders(searchFilter); + } + return AssetDatabase.SearchAllAssets(searchFilter); + } + private static string[] SearchAllAssets(SearchFilter searchFilter) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(searchFilter); + hierarchyProperty.Reset(); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + list.Add(hierarchyProperty.guid); + } + return list.ToArray(); + } + private static string[] SearchInFolders(SearchFilter searchFilter) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + List list = new List(); + string[] folders = searchFilter.folders; + for (int i = 0; i < folders.Length; i++) + { + string text = folders[i]; + hierarchyProperty.SetSearchFilter(new SearchFilter()); + int mainAssetInstanceID = AssetDatabase.GetMainAssetInstanceID(text); + if (hierarchyProperty.Find(mainAssetInstanceID, null)) + { + hierarchyProperty.SetSearchFilter(searchFilter); + int depth = hierarchyProperty.depth; + int[] expanded = null; + while (hierarchyProperty.NextWithDepthCheck(expanded, depth + 1)) + { + list.Add(hierarchyProperty.guid); + } + } + else + { + Debug.LogWarning("AssetDatabase.FindAssets: Folder not found: '" + text + "'"); + } + } + return list.ToArray(); + } } } diff --git a/UnityEditor/UnityEditor/AssetImporter.cs b/UnityEditor/UnityEditor/AssetImporter.cs index 50d26f9c..b666cfa9 100644 --- a/UnityEditor/UnityEditor/AssetImporter.cs +++ b/UnityEditor/UnityEditor/AssetImporter.cs @@ -26,8 +26,30 @@ public extern string userData [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern string assetBundleName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string assetBundleVariant + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern AssetImporter GetAtPath(string path); + public void SaveAndReimport() + { + AssetDatabase.ImportAsset(this.assetPath); + } } } diff --git a/UnityEditor/UnityEditor/AssetImporterInspector.cs b/UnityEditor/UnityEditor/AssetImporterInspector.cs index b43b41aa..ddcb56b1 100644 --- a/UnityEditor/UnityEditor/AssetImporterInspector.cs +++ b/UnityEditor/UnityEditor/AssetImporterInspector.cs @@ -7,13 +7,17 @@ internal abstract class AssetImporterInspector : Editor { private ulong m_AssetTimeStamp; private bool m_MightHaveModified; - internal Editor m_AssetEditor; - internal Editor assetEditor + private Editor m_AssetEditor; + internal virtual Editor assetEditor { get { return this.m_AssetEditor; } + set + { + this.m_AssetEditor = value; + } } internal override string targetTitle { @@ -34,19 +38,15 @@ internal override int referenceTargetIndex this.assetEditor.referenceTargetIndex = value; } } - internal override IPreviewable Preview + internal override IPreviewable preview { get { - if (!this.useAssetDrawPreview) + if (this.useAssetDrawPreview && this.assetEditor != null) { - return base.Preview; + return this.assetEditor; } - if (this.m_Preview == null) - { - return this.assetEditor ?? base.Preview; - } - return this.m_Preview; + return base.preview; } } protected virtual bool useAssetDrawPreview @@ -79,7 +79,7 @@ internal override SerializedObject GetSerializedObjectInternal() } return this.m_SerializedObject; } - public void OnDisable() + public virtual void OnDisable() { AssetImporter assetImporter = this.target as AssetImporter; if (Unsupported.IsDestroyScriptableObject(this) && this.m_MightHaveModified && assetImporter != null && !InternalEditorUtility.ignoreInspectorChanges && this.HasModified() && !this.AssetWasUpdated()) @@ -176,15 +176,13 @@ private static void ImportAssets(string[] paths) AssetDatabase.StopAssetEditing(); } } - protected void ApplyRevertGUI() + protected void RevertButton() { - this.m_MightHaveModified = true; - EditorGUILayout.Space(); - bool enabled = GUI.enabled; - GUI.enabled = (this.HasModified() && enabled); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - if (GUILayout.Button("Revert", new GUILayoutOption[0])) + this.RevertButton("Revert"); + } + protected void RevertButton(string buttonText) + { + if (GUILayout.Button(buttonText, new GUILayoutOption[0])) { this.m_MightHaveModified = false; this.ResetTimeStamp(); @@ -194,20 +192,47 @@ protected void ApplyRevertGUI() Debug.LogError("Importer reports modified values after reset."); } } - bool flag = false; - if (GUILayout.Button("Apply", new GUILayoutOption[0])) + } + protected bool ApplyButton() + { + return this.ApplyButton("Apply"); + } + protected bool ApplyButton(string buttonText) + { + if (GUILayout.Button(buttonText, new GUILayoutOption[0])) { this.ApplyAndImport(); - flag = true; + return true; } + return false; + } + protected virtual bool ApplyRevertGUIButtons() + { + EditorGUI.BeginDisabledGroup(!this.HasModified()); + this.RevertButton(); + bool result = this.ApplyButton(); + EditorGUI.EndDisabledGroup(); + return result; + } + protected void ApplyRevertGUI() + { + this.m_MightHaveModified = true; + EditorGUILayout.Space(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + bool flag = this.ApplyRevertGUIButtons(); if (this.AssetWasUpdated() && Event.current.type != EventType.Layout) { + IPreviewable preview = this.preview; + if (preview != null) + { + preview.ReloadPreviewInstances(); + } this.ResetTimeStamp(); this.ResetValues(); base.Repaint(); } GUILayout.EndHorizontal(); - GUI.enabled = enabled; if (flag) { GUIUtility.ExitGUI(); diff --git a/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs b/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs index 506f8304..e1a288b5 100644 --- a/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs +++ b/UnityEditor/UnityEditor/AssetImporterTabbedEditor.cs @@ -15,6 +15,21 @@ public AssetImporterInspector activeEditor return this.m_ActiveEditor; } } + internal override Editor assetEditor + { + get + { + return base.assetEditor; + } + set + { + base.assetEditor = value; + if (this.activeEditor) + { + this.activeEditor.assetEditor = this.assetEditor; + } + } + } internal virtual void OnEnable() { this.m_ActiveEditorIndex = EditorPrefs.GetInt(base.GetType().Name + "ActiveEditorIndex", 0); @@ -34,10 +49,6 @@ private void OnDestroy() } public override void OnInspectorGUI() { - if (this.m_ActiveEditor.m_AssetEditor == null) - { - this.m_ActiveEditor.m_AssetEditor = base.assetEditor; - } EditorGUI.BeginDisabledGroup(false); GUI.enabled = true; GUILayout.BeginHorizontal(new GUILayoutOption[0]); @@ -51,7 +62,7 @@ public override void OnInspectorGUI() this.m_ActiveEditor = null; UnityEngine.Object.DestroyImmediate(activeEditor); this.m_ActiveEditor = (Editor.CreateEditor(base.targets, this.m_SubEditorTypes[this.m_ActiveEditorIndex]) as AssetImporterInspector); - this.m_ActiveEditor.m_AssetEditor = base.assetEditor; + this.m_ActiveEditor.assetEditor = this.assetEditor; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); diff --git a/UnityEditor/UnityEditor/AssetInspector.cs b/UnityEditor/UnityEditor/AssetInspector.cs index 17c1a477..5c7b6774 100644 --- a/UnityEditor/UnityEditor/AssetInspector.cs +++ b/UnityEditor/UnityEditor/AssetInspector.cs @@ -22,7 +22,7 @@ private AssetInspector() } internal static bool IsAssetServerSetUp() { - return InternalEditorUtility.HasMaint() && ASEditorBackend.SettingsAreValid(); + return InternalEditorUtility.HasPro() && ASEditorBackend.SettingsAreValid(); } private bool HasFlag(ChangeFlags flags, ChangeFlags flagToCheck) { diff --git a/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs b/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs index 20b4afc4..c116ace2 100644 --- a/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs +++ b/UnityEditor/UnityEditor/AssetModificationProcessorInternal.cs @@ -196,15 +196,15 @@ private static void OnWillSaveAssets(string[] assets, out string[] assetsThatSho } private static void RequireTeamLicense() { - if (!InternalEditorUtility.HasMaint()) + if (!InternalEditorUtility.HasPro()) { - throw new MethodAccessException("Requires team license"); + throw new MethodAccessException("Requires Pro license"); } } private static AssetMoveResult OnWillMoveAsset(string fromPath, string toPath, string[] newPaths, string[] NewMetaPaths) { AssetMoveResult assetMoveResult = AssetMoveResult.DidNotMove; - if (!InternalEditorUtility.HasMaint()) + if (!InternalEditorUtility.HasPro()) { return assetMoveResult; } @@ -231,7 +231,7 @@ private static AssetMoveResult OnWillMoveAsset(string fromPath, string toPath, s private static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions options) { AssetDeleteResult assetDeleteResult = AssetDeleteResult.DidNotDelete; - if (!InternalEditorUtility.HasMaint()) + if (!InternalEditorUtility.HasPro()) { return assetDeleteResult; } @@ -294,8 +294,7 @@ internal static bool IsOpenForEdit(string assetPath, out string message) { return true; } - bool flag = true; - flag &= AssetModificationHook.IsOpenForEdit(assetPath, out message); + bool result = AssetModificationHook.IsOpenForEdit(assetPath, out message); MethodInfo[] array = AssetModificationProcessorInternal.GetIsOpenForEditMethods(); for (int i = 0; i < array.Length; i++) { @@ -311,7 +310,7 @@ internal static bool IsOpenForEdit(string assetPath, out string message) return false; } } - return flag; + return result; } internal static void OnStatusUpdated() { diff --git a/UnityEditor/UnityEditor/AssetPopupBackend.cs b/UnityEditor/UnityEditor/AssetPopupBackend.cs new file mode 100644 index 00000000..1b9f148b --- /dev/null +++ b/UnityEditor/UnityEditor/AssetPopupBackend.cs @@ -0,0 +1,97 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetPopupBackend + { + public static void AssetPopup(SerializedProperty serializedProperty, GUIContent label, string fileExtension) where T : UnityEngine.Object, new() + { + bool showMixedValue = EditorGUI.showMixedValue; + EditorGUI.showMixedValue = serializedProperty.hasMultipleDifferentValues; + string objectReferenceTypeString = serializedProperty.objectReferenceTypeString; + GUIContent buttonContent; + if (serializedProperty.hasMultipleDifferentValues) + { + buttonContent = EditorGUI.mixedValueContent; + } + else + { + if (serializedProperty.objectReferenceValue != null) + { + buttonContent = GUIContent.Temp(serializedProperty.objectReferenceStringValue); + } + else + { + buttonContent = GUIContent.Temp("Default"); + } + } + Rect buttonRect; + if (AudioMixerEffectGUI.PopupButton(label, buttonContent, EditorStyles.popup, out buttonRect, new GUILayoutOption[0])) + { + AssetPopupBackend.ShowAssetsPopupMenu(buttonRect, objectReferenceTypeString, serializedProperty, fileExtension); + } + EditorGUI.showMixedValue = showMixedValue; + } + private static void ShowAssetsPopupMenu(Rect buttonRect, string typeName, SerializedProperty serializedProperty, string fileExtension) where T : UnityEngine.Object, new() + { + GenericMenu genericMenu = new GenericMenu(); + int num = (!(serializedProperty.objectReferenceValue != null)) ? 0 : serializedProperty.objectReferenceValue.GetInstanceID(); + genericMenu.AddItem(new GUIContent("Default"), num == 0, new GenericMenu.MenuFunction2(AssetPopupBackend.AssetPopupMenuCallback), new object[] + { + 0, + serializedProperty + }); + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + SearchFilter searchFilter = new SearchFilter + { + classNames = new string[] + { + typeName + } + }; + hierarchyProperty.SetSearchFilter(searchFilter); + hierarchyProperty.Reset(); + while (hierarchyProperty.Next(null)) + { + genericMenu.AddItem(new GUIContent(hierarchyProperty.name), hierarchyProperty.instanceID == num, new GenericMenu.MenuFunction2(AssetPopupBackend.AssetPopupMenuCallback), new object[] + { + hierarchyProperty.instanceID, + serializedProperty + }); + } + int num2 = BaseObjectTools.StringToClassID(typeName); + if (num2 > 0) + { + BuiltinResource[] builtinResourceList = EditorGUIUtility.GetBuiltinResourceList(num2); + BuiltinResource[] array = builtinResourceList; + for (int i = 0; i < array.Length; i++) + { + BuiltinResource builtinResource = array[i]; + genericMenu.AddItem(new GUIContent(builtinResource.m_Name), builtinResource.m_InstanceID == num, new GenericMenu.MenuFunction2(AssetPopupBackend.AssetPopupMenuCallback), new object[] + { + builtinResource.m_InstanceID, + serializedProperty + }); + } + } + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Create New..."), false, delegate + { + T t = Activator.CreateInstance(); + ProjectWindowUtil.CreateAsset(t, "New " + typeName + "." + fileExtension); + serializedProperty.objectReferenceValue = t; + serializedProperty.m_SerializedObject.ApplyModifiedProperties(); + }); + genericMenu.DropDown(buttonRect); + } + private static void AssetPopupMenuCallback(object userData) + { + object[] array = userData as object[]; + int instanceID = (int)array[0]; + SerializedProperty serializedProperty = (SerializedProperty)array[1]; + serializedProperty.objectReferenceValue = EditorUtility.InstanceIDToObject(instanceID); + serializedProperty.m_SerializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs b/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs index 0e58a342..f4fa6292 100644 --- a/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs +++ b/UnityEditor/UnityEditor/AssetPostprocessingInternal.cs @@ -24,7 +24,10 @@ internal class PostprocessStack private static ArrayList m_ImportProcessors; private static void LogPostProcessorMissingDefaultConstructor(Type type) { - Debug.LogError(string.Format("{0} requires a default constructor to be used as an asset post processor", type.ToString())); + Debug.LogErrorFormat("{0} requires a default constructor to be used as an asset post processor", new object[] + { + type + }); } private static void PostprocessAllAssets(string[] importedAssets, string[] addedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPathAssets) { @@ -45,6 +48,16 @@ private static void PostprocessAllAssets(string[] importedAssets, string[] added } SyncVS.PostprocessSyncProject(importedAssets, addedAssets, deletedAssets, movedAssets, movedFromPathAssets); } + private static void PreprocessAssembly(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessAssembly", new string[] + { + pathName + }); + } + } internal static void CallOnGeneratedCSProjectFiles() { foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) @@ -134,6 +147,20 @@ private static void PreprocessMesh(string pathName) AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessModel", null); } } + private static void PreprocessSpeedTree(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessSpeedTree", null); + } + } + private static void PreprocessAnimation(string pathName) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + AttributeHelper.InvokeMemberIfAvailable(target, "OnPreprocessAnimation", null); + } + } private static Material ProcessMeshAssignMaterial(Renderer renderer, Material material) { foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) @@ -173,6 +200,17 @@ private static void PostprocessMesh(GameObject gameObject) AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessModel", args); } } + private static void PostprocessSpeedTree(GameObject gameObject) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + gameObject + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessSpeedTree", args); + } + } private static void PostprocessGameObjectWithUserProperties(GameObject go, string[] prop_names, object[] prop_values) { foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) @@ -232,6 +270,18 @@ private static void PostprocessTexture(Texture2D tex, string pathName) AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessTexture", args); } } + private static void PostprocessSprites(Texture2D tex, string pathName, Sprite[] sprites) + { + foreach (AssetPostprocessor target in AssetPostprocessingInternal.m_ImportProcessors) + { + object[] args = new object[] + { + tex, + sprites + }; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessSprites", args); + } + } private static uint[] GetAudioProcessorVersions() { List list = new List(); @@ -278,5 +328,19 @@ private static void PostprocessAudio(AudioClip tex, string pathName) AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAudio", args); } } + private static void PostprocessAssetbundleNameChanged(string assetPAth, string prevoiusAssetBundleName, string newAssetBundleName) + { + object[] args = new object[] + { + assetPAth, + prevoiusAssetBundleName, + newAssetBundleName + }; + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(AssetPostprocessor))) + { + AssetPostprocessor target = Activator.CreateInstance(current) as AssetPostprocessor; + AttributeHelper.InvokeMemberIfAvailable(target, "OnPostprocessAssetbundleNameChanged", args); + } + } } } diff --git a/UnityEditor/UnityEditor/AssetPreview.cs b/UnityEditor/UnityEditor/AssetPreview.cs index cfdbcf01..2ceaee14 100644 --- a/UnityEditor/UnityEditor/AssetPreview.cs +++ b/UnityEditor/UnityEditor/AssetPreview.cs @@ -42,7 +42,7 @@ internal static bool HasAnyNewPreviewTexturesAvailable() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasAnyNewPreviewTexturesAvailable(int clientID); - internal static void SetPreviewTextureCacheSize(int size) + public static void SetPreviewTextureCacheSize(int size) { AssetPreview.SetPreviewTextureCacheSize(size, 0); } diff --git a/UnityEditor/UnityEditor/AssetSelectionPopupMenu.cs b/UnityEditor/UnityEditor/AssetSelectionPopupMenu.cs new file mode 100644 index 00000000..44fd587c --- /dev/null +++ b/UnityEditor/UnityEditor/AssetSelectionPopupMenu.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal class AssetSelectionPopupMenu + { + public static void Show(Rect buttonRect, string[] classNames, int initialSelectedInstanceID) + { + GenericMenu genericMenu = new GenericMenu(); + List list = AssetSelectionPopupMenu.FindAssetsOfType(classNames); + if (list.Any()) + { + list.Sort((UnityEngine.Object result1, UnityEngine.Object result2) => EditorUtility.NaturalCompare(result1.name, result2.name)); + foreach (UnityEngine.Object current in list) + { + GUIContent content = new GUIContent(current.name); + bool on = current.GetInstanceID() == initialSelectedInstanceID; + genericMenu.AddItem(content, on, new GenericMenu.MenuFunction2(AssetSelectionPopupMenu.SelectCallback), current); + } + } + else + { + genericMenu.AddDisabledItem(new GUIContent("No Audio Mixers found in this project")); + } + genericMenu.DropDown(buttonRect); + } + private static void SelectCallback(object userData) + { + UnityEngine.Object @object = userData as UnityEngine.Object; + if (@object != null) + { + Selection.activeInstanceID = @object.GetInstanceID(); + } + } + private static List FindAssetsOfType(string[] classNames) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(new SearchFilter + { + classNames = classNames + }); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + list.Add(hierarchyProperty.pptrValue); + } + return list; + } + } +} diff --git a/UnityEditor/UnityEditor/AssetServer.cs b/UnityEditor/UnityEditor/AssetServer.cs index b0007e42..2f8bfac9 100644 --- a/UnityEditor/UnityEditor/AssetServer.cs +++ b/UnityEditor/UnityEditor/AssetServer.cs @@ -119,36 +119,7 @@ internal sealed class AssetServer public static extern string UnityGUID(int a, int b, int c, int d); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies, [DefaultValue("true")] bool includeUnmodified, [DefaultValue("false")] bool includeNameConflicts); - [ExcludeFromDocs] - public static string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies, bool includeUnmodified) - { - bool includeNameConflicts = false; - return AssetServer.BuildExportPackageAssetListGUIDs(guids, dependencies, includeUnmodified, includeNameConflicts); - } - [ExcludeFromDocs] - public static string[] BuildExportPackageAssetListGUIDs(string[] guids, bool dependencies) - { - bool includeNameConflicts = false; - bool includeUnmodified = true; - return AssetServer.BuildExportPackageAssetListGUIDs(guids, dependencies, includeUnmodified, includeNameConflicts); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies, [DefaultValue("true")] bool includeUnmodified, [DefaultValue("false")] bool includeNameConflicts); - [ExcludeFromDocs] - public static AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies, bool includeUnmodified) - { - bool includeNameConflicts = false; - return AssetServer.BuildExportPackageAssetListAssetsItems(guids, dependencies, includeUnmodified, includeNameConflicts); - } - [ExcludeFromDocs] - public static AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies) - { - bool includeNameConflicts = false; - bool includeUnmodified = true; - return AssetServer.BuildExportPackageAssetListAssetsItems(guids, dependencies, includeUnmodified, includeNameConflicts); - } + public static extern AssetsItem[] BuildExportPackageAssetListAssetsItems(string[] guids, bool dependencies); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern AssetsItem[] BuildAllExportPackageAssetListAssetsItems(); diff --git a/UnityEditor/UnityEditor/AssetStoreContext.cs b/UnityEditor/UnityEditor/AssetStoreContext.cs index 9ed0c100..8b2609a3 100644 --- a/UnityEditor/UnityEditor/AssetStoreContext.cs +++ b/UnityEditor/UnityEditor/AssetStoreContext.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using UnityEditorInternal; @@ -9,30 +10,158 @@ namespace UnityEditor { internal sealed class AssetStoreContext : ScriptableObject { - private static Regex standardPackageRe = new Regex("/Standard Packages/(Character\\ Controller|Glass\\ Refraction\\ \\(Pro\\ Only\\)|Image\\ Effects\\ \\(Pro\\ Only\\)|Light\\ Cookies|Light\\ Flares|Particles|Physic\\ Materials|Projectors|Scripts|Standard\\ Assets\\ \\(Mobile\\)|Skyboxes|Terrain\\ Assets|Toon\\ Shading|Tree\\ Creator|Water\\ \\(Basic\\)|Water\\ \\(Pro\\ Only\\))\\.unitypackage$", RegexOptions.IgnoreCase); - private static Regex generatedIDRe = new Regex("^\\{(.*)\\}$"); - private static Regex invalidPathChars = new Regex("[^a-zA-Z0-9() _-]"); - public bool docked; - public string initialOpenURL; - public AssetStoreWindow window; - private WebScriptObject JS + public class DownloadInfo { - get + public string url; + public string key; + public string id; + } + public class LabelAndId + { + public string label; + public string id; + public void Initialize(JSONValue json) + { + if (json.ContainsKey("label")) + { + this.label = json["label"].AsString(); + } + if (json.ContainsKey("id")) + { + this.id = json["id"].AsString(); + } + } + public override string ToString() { - return this.window.scriptObject; + return string.Format("{{label={0}, id={1}}}", this.label, this.id); } } - public WebScriptObject packages + public class Link { - get + public string type; + public string id; + public void Initialize(JSONValue json) { - WebScriptObject packageList = this.GetPackageList(); - return packageList.Get("results"); + if (json.ContainsKey("type")) + { + this.type = json["type"].AsString(); + } + if (json.ContainsKey("id")) + { + this.id = json["id"].AsString(); + } + } + public override string ToString() + { + return string.Format("{{type={0}, id={1}}}", this.type, this.id); } } + public class Package + { + public string title; + public string id; + public string version; + public string version_id; + public string local_icon; + public string local_path; + public string pubdate; + public string description; + public AssetStoreContext.LabelAndId publisher; + public AssetStoreContext.LabelAndId category; + public AssetStoreContext.Link link; + public void Initialize(JSONValue json) + { + if (json.ContainsKey("title")) + { + this.title = json["title"].AsString(); + } + if (json.ContainsKey("id")) + { + this.id = json["id"].AsString(); + } + if (json.ContainsKey("version")) + { + this.version = json["version"].AsString(); + } + if (json.ContainsKey("version_id")) + { + this.version_id = json["version_id"].AsString(); + } + if (json.ContainsKey("local_icon")) + { + this.local_icon = json["local_icon"].AsString(); + } + if (json.ContainsKey("local_path")) + { + this.local_path = json["local_path"].AsString(); + } + if (json.ContainsKey("pubdate")) + { + this.pubdate = json["pubdate"].AsString(); + } + if (json.ContainsKey("description")) + { + this.description = json["description"].AsString(); + } + if (json.ContainsKey("publisher")) + { + this.publisher = new AssetStoreContext.LabelAndId(); + this.publisher.Initialize(json["publisher"]); + } + if (json.ContainsKey("category")) + { + this.category = new AssetStoreContext.LabelAndId(); + this.category.Initialize(json["category"]); + } + if (json.ContainsKey("link")) + { + this.link = new AssetStoreContext.Link(); + this.link.Initialize(json["link"]); + } + } + public override string ToString() + { + return string.Format("{{title={0}, id={1}, publisher={2}, category={3}, pubdate={8}, version={4}, version_id={5}, description={9}, link={10}, local_icon={6}, local_path={7}}}", new object[] + { + this.title, + this.id, + this.publisher, + this.category, + this.version, + this.version_id, + this.local_icon, + this.local_path, + this.pubdate, + this.description, + this.link + }); + } + } + public class PackageList + { + public AssetStoreContext.Package[] results; + } + private static Regex standardPackageRe = new Regex("/Standard Packages/(Character\\ Controller|Glass\\ Refraction\\ \\(Pro\\ Only\\)|Image\\ Effects\\ \\(Pro\\ Only\\)|Light\\ Cookies|Light\\ Flares|Particles|Physic\\ Materials|Projectors|Scripts|Standard\\ Assets\\ \\(Mobile\\)|Skyboxes|Terrain\\ Assets|Toon\\ Shading|Tree\\ Creator|Water\\ \\(Basic\\)|Water\\ \\(Pro\\ Only\\))\\.unitypackage$", RegexOptions.IgnoreCase); + private static Regex generatedIDRe = new Regex("^\\{(.*)\\}$"); + private static Regex invalidPathChars = new Regex("[^a-zA-Z0-9() _-]"); + internal bool docked; + internal string initialOpenURL; + internal AssetStoreWindow window; private AssetStoreContext() { } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SessionSetString(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string SessionGetString(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SessionRemoveString(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SessionHasString(string key); public string GetInitialOpenURL() { if (this.initialOpenURL != null) @@ -51,57 +180,6 @@ public int[] GetLicenseFlags() { return InternalEditorUtility.GetLicenseFlags(); } - public void Download(WebScriptObject package, WebScriptObject downloadInfo) - { - string url = downloadInfo.Get("url"); - string key = downloadInfo.Get("key"); - string package_id = downloadInfo.Get("id"); - string package_name = package.Get("title"); - string publisher_name = package.Get("publisher.label"); - string category_name = package.Get("category.label"); - AssetStoreContext.Download(package_id, url, key, package_name, publisher_name, category_name, null); - } - public static string[] PackageStorePath(string publisher_name, string category_name, string package_name, string package_id, string url) - { - string[] array = new string[] - { - publisher_name, - category_name, - package_name - }; - for (int i = 0; i < 3; i++) - { - array[i] = AssetStoreContext.invalidPathChars.Replace(array[i], string.Empty); - } - if (array[2] == string.Empty) - { - array[2] = AssetStoreContext.invalidPathChars.Replace(package_id, string.Empty); - } - if (array[2] == string.Empty) - { - array[2] = AssetStoreContext.invalidPathChars.Replace(url, string.Empty); - } - return array; - } - public static void Download(string package_id, string url, string key, string package_name, string publisher_name, string category_name, AssetStoreUtils.DownloadDoneCallback doneCallback) - { - string[] destination = AssetStoreContext.PackageStorePath(publisher_name, category_name, package_name, package_id, url); - JSONValue jSONValue = JSONParser.SimpleParse(AssetStoreUtils.CheckDownload(package_id, url, destination, key)); - if (jSONValue.Get("in_progress").AsBool(true)) - { - Debug.Log("Will not download " + package_name + ". Download is already in progress."); - return; - } - string a = jSONValue.Get("download.url").AsString(true); - string a2 = jSONValue.Get("download.key").AsString(true); - bool resumeOK = a == url && a2 == key; - JSONValue value = default(JSONValue); - value["url"] = url; - value["key"] = key; - JSONValue jSONValue2 = default(JSONValue); - jSONValue2["download"] = value; - AssetStoreUtils.Download(package_id, url, destination, key, jSONValue2.ToString(), resumeOK, doneCallback); - } public string GetString(string key) { return EditorPrefs.GetString(key); @@ -134,69 +212,9 @@ public void DeleteKey(string key) { EditorPrefs.DeleteKey(key); } - private bool IsBuiltinStandardAsset(string path) - { - return AssetStoreContext.standardPackageRe.IsMatch(path); - } - public WebScriptObject GetPackageList() - { - Dictionary dictionary = new Dictionary(); - WebScriptObject webScriptObject = this.JS.ParseJSON("{}"); - WebScriptObject webScriptObject2 = this.JS.ParseJSON("[]"); - PackageInfo[] packageList = PackageInfo.GetPackageList(); - PackageInfo[] array = packageList; - for (int i = 0; i < array.Length; i++) - { - PackageInfo packageInfo = array[i]; - WebScriptObject webScriptObject3; - if (packageInfo.jsonInfo == string.Empty) - { - webScriptObject3 = this.JS.ParseJSON("{}"); - webScriptObject3.Set("title", Path.GetFileNameWithoutExtension(packageInfo.packagePath)); - webScriptObject3.Set("id", "{" + packageInfo.packagePath + "}"); - if (this.IsBuiltinStandardAsset(packageInfo.packagePath)) - { - webScriptObject3.Set("publisher", this.JS.ParseJSON("{\"label\": \"Unity Technologies\",\"id\": \"1\"}")); - webScriptObject3.Set("category", this.JS.ParseJSON("{\"label\": \"Prefab Packages\",\"id\": \"4\"}")); - webScriptObject3.Set("version", "3.5.0.0"); - webScriptObject3.Set("version_id", "-1"); - } - } - else - { - webScriptObject3 = this.JS.ParseJSON(packageInfo.jsonInfo); - if (webScriptObject3.Get("id") == null) - { - WebScriptObject webScriptObject4 = webScriptObject3.Get("link"); - if (webScriptObject4 != null) - { - webScriptObject3.Set("id", webScriptObject4.Get("id")); - } - else - { - webScriptObject3.Set("id", "{" + packageInfo.packagePath + "}"); - } - } - } - string key = webScriptObject3.Get("id"); - webScriptObject3.Set("local_icon", packageInfo.iconURL); - webScriptObject3.Set("local_path", packageInfo.packagePath); - if (!dictionary.ContainsKey(key) || dictionary[key].Get("version_id") == null || (webScriptObject3.Get("version_id") != null && dictionary[key].Get("version_id") <= webScriptObject3.Get("version_id"))) - { - dictionary[key] = webScriptObject3; - } - } - int num = 0; - foreach (KeyValuePair current in dictionary) - { - webScriptObject2.Set(num++, current.Value); - } - webScriptObject.Set("results", webScriptObject2); - return webScriptObject; - } public int GetSkinIndex() { - return (!EditorGUIUtility.isProSkin) ? 0 : 1; + return EditorGUIUtility.skinIndex; } public bool GetDockedStatus() { @@ -236,49 +254,124 @@ public static bool OpenPackageInternal(string id) Debug.LogError("Unknown package ID " + id); return false; } - public void MakeMenu(WebScriptObject contextMenu) + public void OpenBrowser(string url) { - this.MakeMenu(contextMenu, 0f, 0f); + Application.OpenURL(url); } - public void MakeMenu(WebScriptObject contextMenu, float deltaX, float deltaY) + public void Download(AssetStoreContext.Package package, AssetStoreContext.DownloadInfo downloadInfo) { - WebScriptObject webScriptObject = contextMenu.Get("commands"); - int num = webScriptObject.Get("length"); - string[] array = new string[num]; - string[] array2 = new string[num]; - for (int i = 0; i < webScriptObject.Get("length"); i++) + AssetStoreContext.Download(downloadInfo.id, downloadInfo.url, downloadInfo.key, package.title, package.publisher.label, package.category.label, null); + } + public static void Download(string package_id, string url, string key, string package_name, string publisher_name, string category_name, AssetStoreUtils.DownloadDoneCallback doneCallback) + { + string[] destination = AssetStoreContext.PackageStorePath(publisher_name, category_name, package_name, package_id, url); + JSONValue jSONValue = JSONParser.SimpleParse(AssetStoreUtils.CheckDownload(package_id, url, destination, key)); + if (jSONValue.Get("in_progress").AsBool(true)) { - WebScriptObject webScriptObject2 = webScriptObject.Get(i); - array[i] = webScriptObject2.Get("label"); - array2[i] = webScriptObject2.Get("action"); + Debug.Log("Will not download " + package_name + ". Download is already in progress."); + return; } - Vector2 mousePosition = Event.current.mousePosition; - Rect position = new Rect(mousePosition.x + deltaX, mousePosition.y + deltaY, 0f, 0f); - EditorUtility.DisplayCustomMenu(position, array, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), array2); + string a = jSONValue.Get("download.url").AsString(true); + string a2 = jSONValue.Get("download.key").AsString(true); + bool resumeOK = a == url && a2 == key; + JSONValue value = default(JSONValue); + value["url"] = url; + value["key"] = key; + JSONValue jSONValue2 = default(JSONValue); + jSONValue2["download"] = value; + AssetStoreUtils.Download(package_id, url, destination, key, jSONValue2.ToString(), resumeOK, doneCallback); } - public void OpenBrowser(string url) + public static string[] PackageStorePath(string publisher_name, string category_name, string package_name, string package_id, string url) { - Application.OpenURL(url); + string[] array = new string[] + { + publisher_name, + category_name, + package_name + }; + for (int i = 0; i < 3; i++) + { + array[i] = AssetStoreContext.invalidPathChars.Replace(array[i], string.Empty); + } + if (array[2] == string.Empty) + { + array[2] = AssetStoreContext.invalidPathChars.Replace(package_id, string.Empty); + } + if (array[2] == string.Empty) + { + array[2] = AssetStoreContext.invalidPathChars.Replace(url, string.Empty); + } + return array; } - private void ContextMenuClick(object userData, string[] options, int selected) + public AssetStoreContext.PackageList GetPackageList() { - if (selected >= 0) + Dictionary dictionary = new Dictionary(); + PackageInfo[] packageList = PackageInfo.GetPackageList(); + PackageInfo[] array = packageList; + int i = 0; + while (i < array.Length) { - string[] array = userData as string[]; - this.JS.EvalJavaScript(array[selected]); + PackageInfo packageInfo = array[i]; + AssetStoreContext.Package package = new AssetStoreContext.Package(); + if (packageInfo.jsonInfo == string.Empty) + { + package.title = Path.GetFileNameWithoutExtension(packageInfo.packagePath); + package.id = packageInfo.packagePath; + if (this.IsBuiltinStandardAsset(packageInfo.packagePath)) + { + package.publisher = new AssetStoreContext.LabelAndId + { + label = "Unity Technologies", + id = "1" + }; + package.category = new AssetStoreContext.LabelAndId + { + label = "Prefab Packages", + id = "4" + }; + package.version = "3.5.0.0"; + } + goto IL_144; + } + JSONValue json = JSONParser.SimpleParse(packageInfo.jsonInfo); + if (!json.IsNull()) + { + package.Initialize(json); + if (package.id != null) + { + goto IL_144; + } + JSONValue jSONValue = json.Get("link.id"); + if (!jSONValue.IsNull()) + { + package.id = jSONValue.AsString(); + goto IL_144; + } + package.id = packageInfo.packagePath; + goto IL_144; + } + IL_203: + i++; + continue; + IL_144: + package.local_icon = packageInfo.iconURL; + package.local_path = packageInfo.packagePath; + if (!dictionary.ContainsKey(package.id) || dictionary[package.id].version_id == null || dictionary[package.id].version_id == "-1" || (package.version_id != null && package.version_id != "-1" && int.Parse(dictionary[package.id].version_id) <= int.Parse(package.version_id))) + { + dictionary[package.id] = package; + goto IL_203; + } + goto IL_203; } + AssetStoreContext.Package[] results = dictionary.Values.ToArray(); + return new AssetStoreContext.PackageList + { + results = results + }; + } + private bool IsBuiltinStandardAsset(string path) + { + return AssetStoreContext.standardPackageRe.IsMatch(path); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SessionSetString(string key, string value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string SessionGetString(string key); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SessionRemoveString(string key); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool SessionHasString(string key); } } diff --git a/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs b/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs index cb1b47a6..9e0c1f1c 100644 --- a/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs +++ b/UnityEditor/UnityEditor/AssetStoreInstaBuyWindow.cs @@ -468,7 +468,11 @@ private void DownloadPackage() item.downloadProgress = -1f; if (status != "ok") { - Debug.LogError(string.Format("Error downloading package {0} ({1})", item.packageName, id)); + Debug.LogErrorFormat("Error downloading package {0} ({1})", new object[] + { + item.packageName, + id + }); Debug.LogError(status); this.Close(); return; @@ -479,7 +483,11 @@ private void DownloadPackage() } if (!AssetStoreContext.OpenPackageInternal(id)) { - Debug.LogError(string.Format("Error importing package {0} ({1})", item.packageName, id)); + Debug.LogErrorFormat("Error importing package {0} ({1})", new object[] + { + item.packageName, + id + }); } this.Close(); }); diff --git a/UnityEditor/UnityEditor/AssetStoreWindow.cs b/UnityEditor/UnityEditor/AssetStoreWindow.cs index 341fa3cc..14c7ce64 100644 --- a/UnityEditor/UnityEditor/AssetStoreWindow.cs +++ b/UnityEditor/UnityEditor/AssetStoreWindow.cs @@ -1,25 +1,18 @@ using System; +using System.Text; using UnityEngine; namespace UnityEditor { internal class AssetStoreWindow : EditorWindow, IHasCustomMenu { - private WebView webView; - private AssetStoreContext contextScriptObject; - private bool isProSkin; - private bool isDocked; - private bool isOffline; - private MouseCursor m_SavedCursor; - private int m_SavedCursorCountHack; - private Vector2 minUndockedSize; - private Vector2 minDockedSize; - internal WebScriptObject scriptObject - { - get - { - return this.webView.windowScriptObject; - } - } + internal WebView m_WebView; + private AssetStoreContext m_ContextScriptObject; + private int m_CurrentSkin; + private bool m_IsDocked; + private bool m_IsOffline; + private Vector2 m_MinUndockedSize; + private Vector2 m_MinDockedSize; + private bool m_SyncingFocus; private AssetStoreWindow() { Resolution currentResolution = Screen.currentResolution; @@ -37,7 +30,7 @@ public static void OpenURL(string url) url }); assetStoreWindow.CreateContextObject(); - assetStoreWindow.contextScriptObject.initialOpenURL = url; + assetStoreWindow.m_ContextScriptObject.initialOpenURL = url; } public static AssetStoreWindow Init() { @@ -45,12 +38,11 @@ public static AssetStoreWindow Init() Resolution currentResolution = Screen.currentResolution; int num = (currentResolution.width < 1024) ? currentResolution.width : 1024; int num2 = (currentResolution.height < 896) ? (currentResolution.height - 96) : 800; - window.minUndockedSize = new Vector2((float)num, (float)num2); - window.minDockedSize = new Vector2(512f, 256f); - window.minSize = ((!window.docked) ? window.minUndockedSize : window.minDockedSize); + window.m_MinUndockedSize = new Vector2((float)num, (float)num2); + window.m_MinDockedSize = new Vector2(512f, 256f); + window.minSize = ((!window.docked) ? window.m_MinUndockedSize : window.m_MinDockedSize); window.maxSize = new Vector2(2048f, 2048f); window.Show(); - window.m_SavedCursor = MouseCursor.Arrow; return window; } public virtual void AddItemsToMenu(GenericMenu menu) @@ -63,69 +55,39 @@ public void Logout() } public void Reload() { - if (this.isOffline) + this.m_CurrentSkin = EditorGUIUtility.skinIndex; + this.m_IsDocked = base.docked; + this.m_WebView.Reload(); + } + public void OnLoadError(string url) + { + if (!this.m_WebView) { - this.InitWebView(); + return; } - else + if (this.m_IsOffline) { - this.isProSkin = EditorGUIUtility.isProSkin; - this.isDocked = base.docked; - this.InvokeJSMethod("location", "reload", new object[] + Debug.LogErrorFormat("Unexpected error: Failed to load offline Asset Store page (url={0})", new object[] { - true + url }); + return; } + this.m_IsOffline = true; + this.m_WebView.LoadFile(AssetStoreUtils.GetOfflinePath()); } - private void CreateContextObject() - { - if (this.contextScriptObject == null) - { - this.contextScriptObject = ScriptableObject.CreateInstance(); - this.contextScriptObject.hideFlags = HideFlags.HideAndDontSave; - this.contextScriptObject.window = this; - } - } - private void SetContextObject() + public void OnInitScripting() { - this.CreateContextObject(); - this.contextScriptObject.docked = base.docked; - this.webView.windowScriptObject.Set("context", this.contextScriptObject); - } - private void InitWebView() - { - this.isProSkin = EditorGUIUtility.isProSkin; - this.isDocked = base.docked; - this.isOffline = false; - if (!this.webView) - { - this.webView = ScriptableObject.CreateInstance(); - this.webView.InitWebView((int)base.position.width, (int)base.position.height, false); - this.webView.hideFlags = HideFlags.HideAndDontSave; - this.webView.LoadFile(AssetStoreUtils.GetLoaderPath()); - } - else - { - this.webView.LoadFile(AssetStoreUtils.GetLoaderPath()); - } - this.webView.SetDelegateObject(this); - base.wantsMouseMove = true; + this.SetContextObject(); } - private void OnLoadError(string frameName) + public void OnOpenExternalLink(string url) { - if (!this.webView) + if (url.StartsWith("http://") || url.StartsWith("https://")) { - return; + this.m_ContextScriptObject.OpenBrowser(url); } - if (this.isOffline) - { - Debug.LogError("Unexpected error: Failed to load offline Asset Store page"); - return; - } - this.isOffline = true; - this.webView.LoadFile(AssetStoreUtils.GetOfflinePath()); } - private void OnEnable() + public void OnEnable() { AssetStoreUtils.RegisterDownloadDelegate(this); } @@ -133,108 +95,160 @@ public void OnDisable() { AssetStoreUtils.UnRegisterDownloadDelegate(this); } - private void InvokeJSMethod(string objectName, string name, params object[] args) + public void OnDownloadProgress(string id, string message, int bytes, int total) { - if (!this.webView) - { - return; - } - WebScriptObject webScriptObject = this.webView.windowScriptObject.Get(objectName); - if (webScriptObject == null) + this.InvokeJSMethod("document.AssetStore.pkgs", "OnDownloadProgress", new object[] { - return; - } - webScriptObject.InvokeMethodArray(name, args); + id, + message, + bytes, + total + }); } - private void OnGUI() + public void OnGUI() { - if (!this.webView) + Rect webViewRect = GUIClip.Unclip(new Rect(0f, 0f, base.position.width, base.position.height)); + if (!this.m_WebView) { - this.InitWebView(); + this.InitWebView(webViewRect); } - EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, base.position.width, base.position.height), this.m_SavedCursor); if (Event.current.type == EventType.Layout) { - if (this.webView && this.isProSkin != EditorGUIUtility.isProSkin) + this.m_WebView.SetSizeAndPosition((int)webViewRect.x, (int)webViewRect.y, (int)webViewRect.width, (int)webViewRect.height); + if (this.m_CurrentSkin != EditorGUIUtility.skinIndex) { - this.isProSkin = EditorGUIUtility.isProSkin; + this.m_CurrentSkin = EditorGUIUtility.skinIndex; this.InvokeJSMethod("document.AssetStore", "refreshSkinIndex", new object[0]); - base.Repaint(); } this.UpdateDockStatusIfNeeded(); } - this.webView.DoGUI(new Rect(0f, 0f, base.position.width, base.position.height)); } - private void UpdateDockStatusIfNeeded() + public void UpdateDockStatusIfNeeded() { - if (this.isDocked != base.docked) + if (this.m_IsDocked != base.docked) { - base.minSize = ((!base.docked) ? this.minUndockedSize : this.minDockedSize); - this.isDocked = base.docked; - if (this.contextScriptObject != null) + base.minSize = ((!base.docked) ? this.m_MinUndockedSize : this.m_MinDockedSize); + this.m_IsDocked = base.docked; + if (this.m_ContextScriptObject != null) { - this.contextScriptObject.docked = base.docked; + this.m_ContextScriptObject.docked = base.docked; this.InvokeJSMethod("document.AssetStore", "updateDockStatus", new object[0]); } - base.Repaint(); } } - private void OnReceiveTitle(string iTitle, string frameName) + public void OnFocus() { - base.title = iTitle; - this.SetContextObject(); + this.SetFocus(true); } - private void OnFocus() + public void OnLostFocus() { - if (this.webView) + this.SetFocus(false); + } + public void OnBecameInvisible() + { + if (!this.m_WebView) { - this.webView.Focus(); + return; } + this.m_WebView.SetHostView(null); } - private void OnLostFocus() + public void OnDestroy() { - if (this.webView) + UnityEngine.Object.DestroyImmediate(this.m_WebView); + if (this.m_ContextScriptObject != null) { - this.webView.UnFocus(); + UnityEngine.Object.DestroyImmediate(this.m_ContextScriptObject); } } - public void OnDestroy() + private void InitWebView(Rect webViewRect) { - UnityEngine.Object.DestroyImmediate(this.webView); - if (this.contextScriptObject != null) + this.m_CurrentSkin = EditorGUIUtility.skinIndex; + this.m_IsDocked = base.docked; + this.m_IsOffline = false; + if (!this.m_WebView) { - this.contextScriptObject.window = null; + int x = (int)webViewRect.x; + int y = (int)webViewRect.y; + int width = (int)webViewRect.width; + int height = (int)webViewRect.height; + this.m_WebView = ScriptableObject.CreateInstance(); + this.m_WebView.InitWebView(this.m_Parent, x, y, width, height, false); + this.m_WebView.hideFlags = HideFlags.HideAndDontSave; + if (base.hasFocus) + { + this.SetFocus(true); + } } + this.m_WebView.SetDelegateObject(this); + this.m_WebView.LoadFile(AssetStoreUtils.GetLoaderPath()); } - public void OnDownloadProgress(string id, string message, int bytes, int total) + private void CreateContextObject() { - this.InvokeJSMethod("document.AssetStore.pkgs", "OnDownloadProgress", new object[] + if (this.m_ContextScriptObject != null) { - id, - message, - bytes, - total - }); + return; + } + this.m_ContextScriptObject = ScriptableObject.CreateInstance(); + this.m_ContextScriptObject.hideFlags = HideFlags.HideAndDontSave; + this.m_ContextScriptObject.window = this; } - private void OnWebViewDirty() + private void SetContextObject() { - base.Repaint(); + this.CreateContextObject(); + this.m_ContextScriptObject.docked = base.docked; + this.m_WebView.DefineScriptObject("window.context", this.m_ContextScriptObject); } - private void SetCursor(int cursor) + private void InvokeJSMethod(string objectName, string name, params object[] args) { - if (cursor != (int)this.m_SavedCursor) + if (!this.m_WebView) { - if (cursor != 0 || this.m_SavedCursorCountHack-- <= 0) + return; + } + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append(objectName); + stringBuilder.Append('.'); + stringBuilder.Append(name); + stringBuilder.Append('('); + bool flag = true; + for (int i = 0; i < args.Length; i++) + { + object obj = args[i]; + if (!flag) + { + stringBuilder.Append(','); + } + bool flag2 = obj is string; + if (flag2) { - this.m_SavedCursorCountHack = 1; - this.m_SavedCursor = (MouseCursor)cursor; - base.Repaint(); + stringBuilder.Append('"'); } + stringBuilder.Append(obj); + if (flag2) + { + stringBuilder.Append('"'); + } + flag = false; } - else + stringBuilder.Append(");"); + this.m_WebView.Evaluate(stringBuilder.ToString()); + } + private void SetFocus(bool value) + { + if (this.m_SyncingFocus) { - this.m_SavedCursorCountHack = 1; + return; + } + this.m_SyncingFocus = true; + if (this.m_WebView) + { + if (value) + { + this.m_WebView.SetHostView(this.m_Parent); + this.m_WebView.Show(); + } + this.m_WebView.SetFocus(value); } + this.m_SyncingFocus = false; } } } diff --git a/UnityEditor/UnityEditor/AssetsTreeViewDragging.cs b/UnityEditor/UnityEditor/AssetsTreeViewDragging.cs new file mode 100644 index 00000000..36db5d23 --- /dev/null +++ b/UnityEditor/UnityEditor/AssetsTreeViewDragging.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +namespace UnityEditor +{ + internal class AssetsTreeViewDragging : TreeViewDragging + { + public AssetsTreeViewDragging(TreeView treeView) : base(treeView) + { + } + public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedItem.id, draggedItemIDs); + DragAndDrop.paths = ProjectWindowUtil.GetDragAndDropPaths(draggedItem.id, draggedItemIDs); + if (DragAndDrop.objectReferences.Length > 1) + { + DragAndDrop.StartDrag(""); + } + else + { + string dragAndDropTitle = ObjectNames.GetDragAndDropTitle(InternalEditorUtility.GetObjectFromInstanceID(draggedItem.id)); + DragAndDrop.StartDrag(dragAndDropTitle); + } + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos) + { + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + if (parentItem == null || !hierarchyProperty.Find(parentItem.id, null)) + { + hierarchyProperty = null; + } + return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + } + } +} diff --git a/UnityEditor/UnityEditor/AsyncHTTPClient.cs b/UnityEditor/UnityEditor/AsyncHTTPClient.cs index 4a7a0368..2ed52d77 100644 --- a/UnityEditor/UnityEditor/AsyncHTTPClient.cs +++ b/UnityEditor/UnityEditor/AsyncHTTPClient.cs @@ -22,10 +22,10 @@ internal enum State ABORTED, TIMEOUT } - public delegate void DoneCallback(AsyncHTTPClient client); - public delegate void StatusCallback(AsyncHTTPClient.State status, int bytesDone, int bytesTotal); private delegate void RequestProgressCallback(AsyncHTTPClient.State status, int downloaded, int totalSize); private delegate void RequestDoneCallback(AsyncHTTPClient.State status, int httpStatus); + public delegate void DoneCallback(AsyncHTTPClient client); + public delegate void StatusCallback(AsyncHTTPClient.State status, int bytesDone, int bytesTotal); private IntPtr m_Handle; public AsyncHTTPClient.StatusCallback statusCallback; public AsyncHTTPClient.DoneCallback doneCallback; @@ -128,6 +128,30 @@ public AsyncHTTPClient(string _toUrl, string _method) this.tag = string.Empty; this.statusCallback = null; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate, [DefaultValue("null")] AsyncHTTPClient.RequestProgressCallback progressDelegate); + [ExcludeFromDocs] + private static IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate) + { + AsyncHTTPClient.RequestProgressCallback progressDelegate = null; + return AsyncHTTPClient.SubmitClientRequest(tag, url, headers, method, data, doneDelegate, progressDelegate); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern byte[] GetBytesByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Texture2D GetTextureByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void AbortByTag(string tag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void AbortByHandle(IntPtr handle); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CurlRequestCheck(); public void Abort() { this.state = AsyncHTTPClient.State.ABORTED; @@ -205,29 +229,5 @@ private string EscapeLong(string v) } return stringBuilder.ToString(); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate, [DefaultValue("null")] AsyncHTTPClient.RequestProgressCallback progressDelegate); - [ExcludeFromDocs] - private static IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, AsyncHTTPClient.RequestDoneCallback doneDelegate) - { - AsyncHTTPClient.RequestProgressCallback progressDelegate = null; - return AsyncHTTPClient.SubmitClientRequest(tag, url, headers, method, data, doneDelegate, progressDelegate); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern byte[] GetBytesByHandle(IntPtr handle); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern Texture2D GetTextureByHandle(IntPtr handle); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void AbortByTag(string tag); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void AbortByHandle(IntPtr handle); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CurlRequestCheck(); } } diff --git a/UnityEditor/UnityEditor/AttachProfilerUI.cs b/UnityEditor/UnityEditor/AttachProfilerUI.cs index 552da8c7..a72f49a2 100644 --- a/UnityEditor/UnityEditor/AttachProfilerUI.cs +++ b/UnityEditor/UnityEditor/AttachProfilerUI.cs @@ -1,41 +1,24 @@ using System; using System.Collections.Generic; +using System.Linq; +using UnityEditor.Hardware; using UnityEditorInternal; using UnityEngine; namespace UnityEditor { - internal struct AttachProfilerUI + internal class AttachProfilerUI { + private const int PLAYER_DIRECT_IP_CONNECT_GUID = 65261; + private const int PLAYER_DIRECT_URL_CONNECT_GUID = 65262; private GUIContent m_CurrentProfiler; - private int[] m_ConnectionGuids; - private Rect m_ButtonScreenRect; private static string kEnterIPText = ""; private static GUIContent ms_NotificationMessage; - private static string kiOSOverUSB = "iOS profiler over USB"; private void SelectProfilerClick(object userData, string[] options, int selected) { - if (selected < this.m_ConnectionGuids.Length) + List list = (List)userData; + if (selected < list.Count()) { - int connectedProfiler = this.m_ConnectionGuids[selected]; - ProfilerDriver.connectedProfiler = connectedProfiler; - } - else - { - if (options[selected] == AttachProfilerUI.kEnterIPText) - { - ProfilerIPWindow.Show(this.m_ButtonScreenRect); - } - else - { - if (options[selected] == AttachProfilerUI.kiOSOverUSB) - { - ProfilerDriver.DirectURLConnect("iproxy://"); - } - else - { - AttachProfilerUI.DirectIPConnect(options[selected]); - } - } + list[selected].ConnectTo(); } } public bool IsEditor() @@ -49,10 +32,17 @@ public string GetConnectedProfiler() public static void DirectIPConnect(string ip) { ConsoleWindow.ShowConsoleWindow(true); - AttachProfilerUI.ms_NotificationMessage = new GUIContent("Connecting to IP...(this can take a while)"); + AttachProfilerUI.ms_NotificationMessage = new GUIContent("Connecting to player...(this can take a while)"); ProfilerDriver.DirectIPConnect(ip); AttachProfilerUI.ms_NotificationMessage = null; } + public static void DirectURLConnect(string url) + { + ConsoleWindow.ShowConsoleWindow(true); + AttachProfilerUI.ms_NotificationMessage = new GUIContent("Connecting to player...(this can take a while)"); + ProfilerDriver.DirectURLConnect(url); + AttachProfilerUI.ms_NotificationMessage = null; + } public void OnGUILayout(EditorWindow window) { if (this.m_CurrentProfiler == null) @@ -73,32 +63,35 @@ public void OnGUILayout(EditorWindow window) window.RemoveNotification(); } } - public void OnGUI(Rect connectRect, GUIContent profilerLabel) + private static void AddLastIPProfiler(List profilers) { - if (!EditorGUI.ButtonMouseDown(connectRect, profilerLabel, FocusType.Native, EditorStyles.toolbarDropDown)) + string lastIP = ProfilerIPWindow.GetLastIPString(); + if (string.IsNullOrEmpty(lastIP)) { return; } - int connectedProfiler = ProfilerDriver.connectedProfiler; - this.m_ConnectionGuids = ProfilerDriver.GetAvailableProfilers(); - int num = this.m_ConnectionGuids.Length; - int[] array = new int[1]; - List list = new List(); - List list2 = new List(); - for (int i = 0; i < num; i++) + ProfilerChoise item = default(ProfilerChoise); + item.Name = lastIP; + item.Enabled = true; + item.IsSelected = (() => ProfilerDriver.connectedProfiler == 65261); + item.ConnectTo = delegate { - int num2 = this.m_ConnectionGuids[i]; - string text = ProfilerDriver.GetConnectionIdentifier(num2); - bool flag = ProfilerDriver.IsIdentifierConnectable(num2); - bool flag2 = ProfilerDriver.IsIdentifierOnLocalhost(num2) && text.Contains("MetroPlayerX"); - if (flag2) - { - flag = false; - } - list.Add(flag); - if (!flag) + AttachProfilerUI.DirectIPConnect(lastIP); + }; + profilers.Add(item); + } + private static void AddPlayerProfilers(List profilers) + { + int[] availableProfilers = ProfilerDriver.GetAvailableProfilers(); + for (int i = 0; i < availableProfilers.Length; i++) + { + int guid = availableProfilers[i]; + string text = ProfilerDriver.GetConnectionIdentifier(guid); + bool flag = ProfilerDriver.IsIdentifierOnLocalhost(guid) && text.Contains("MetroPlayerX"); + bool flag2 = !flag && ProfilerDriver.IsIdentifierConnectable(guid); + if (!flag2) { - if (flag2) + if (flag) { text += " (Localhost prohibited)"; } @@ -107,35 +100,85 @@ public void OnGUI(Rect connectRect, GUIContent profilerLabel) text += " (Version mismatch)"; } } - list2.Add(text); - if (num2 == connectedProfiler) + profilers.Add(new ProfilerChoise { - array[0] = i; - } + Name = text, + Enabled = flag2, + IsSelected = () => ProfilerDriver.connectedProfiler == guid, + ConnectTo = delegate + { + ProfilerDriver.connectedProfiler = guid; + } + }); } - string lastIPString = ProfilerIPWindow.GetLastIPString(); - if (!string.IsNullOrEmpty(lastIPString)) + } + private static void AddDeviceProfilers(List profilers) + { + DevDevice[] devices = DevDeviceList.GetDevices(); + for (int i = 0; i < devices.Length; i++) { - if (connectedProfiler == 65261) + DevDevice devDevice = devices[i]; + bool flag = (devDevice.features & DevDeviceFeatures.PlayerConnection) != DevDeviceFeatures.None; + if (devDevice.isConnected && flag) { - array[0] = num; + string url = "device://" + devDevice.id; + profilers.Add(new ProfilerChoise + { + Name = devDevice.name, + Enabled = true, + IsSelected = () => ProfilerDriver.connectedProfiler == 65262 && ProfilerDriver.directConnectionUrl == url, + ConnectTo = delegate + { + AttachProfilerUI.DirectURLConnect(url); + } + }); } - list2.Add(lastIPString); - list.Add(true); } - if (Application.platform == RuntimePlatform.OSXEditor) + } + private void AddEnterIPProfiler(List profilers, Rect buttonScreenRect) + { + ProfilerChoise item = default(ProfilerChoise); + item.Name = AttachProfilerUI.kEnterIPText; + item.Enabled = true; + item.IsSelected = (() => false); + item.ConnectTo = delegate { - if (connectedProfiler == 65262) + ProfilerIPWindow.Show(buttonScreenRect); + }; + profilers.Add(item); + } + public void OnGUI(Rect connectRect, GUIContent profilerLabel) + { + if (!EditorGUI.ButtonMouseDown(connectRect, profilerLabel, FocusType.Native, EditorStyles.toolbarDropDown)) + { + return; + } + List list = new List(); + list.Clear(); + AttachProfilerUI.AddPlayerProfilers(list); + AttachProfilerUI.AddDeviceProfilers(list); + AttachProfilerUI.AddLastIPProfiler(list); + this.AddEnterIPProfiler(list, GUIUtility.GUIToScreenRect(connectRect)); + string[] options = ( + from p in list + select p.Name).ToArray(); + bool[] enabled = ( + from p in list + select p.Enabled).ToArray(); + int num = list.FindIndex((ProfilerChoise p) => p.IsSelected()); + int[] selected; + if (num == -1) + { + selected = new int[0]; + } + else + { + selected = new int[] { - array[0] = num; - } - list2.Add(AttachProfilerUI.kiOSOverUSB); - list.Add(true); + num + }; } - list2.Add(AttachProfilerUI.kEnterIPText); - list.Add(true); - this.m_ButtonScreenRect = GUIUtility.GUIToScreenRect(connectRect); - EditorUtility.DisplayCustomMenu(connectRect, list2.ToArray(), list.ToArray(), array, new EditorUtility.SelectMenuItemFunction(this.SelectProfilerClick), null); + EditorUtility.DisplayCustomMenu(connectRect, options, enabled, selected, new EditorUtility.SelectMenuItemFunction(this.SelectProfilerClick), list); } } } diff --git a/UnityEditor/UnityEditor/AttributeHelper.cs b/UnityEditor/UnityEditor/AttributeHelper.cs index 1fa92a77..74ed5a5e 100644 --- a/UnityEditor/UnityEditor/AttributeHelper.cs +++ b/UnityEditor/UnityEditor/AttributeHelper.cs @@ -1,5 +1,7 @@ using System; using System.Collections; +using System.Collections.Generic; +using System.Linq; using System.Reflection; using UnityEngine; namespace UnityEditor @@ -36,7 +38,7 @@ int IComparer.Compare(object xo, object yo) } private static AttributeHelper.MonoGizmoMethod[] ExtractGizmos(Assembly assembly) { - ArrayList arrayList = new ArrayList(); + List list = new List(); Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); Type[] array = typesFromAssembly; for (int i = 0; i < array.Length; i++) @@ -58,19 +60,19 @@ private static AttributeHelper.MonoGizmoMethod[] ExtractGizmos(Assembly assembly } else { - AttributeHelper.MonoGizmoMethod monoGizmoMethod = default(AttributeHelper.MonoGizmoMethod); + AttributeHelper.MonoGizmoMethod item = default(AttributeHelper.MonoGizmoMethod); if (drawGizmo.drawnType == null) { - monoGizmoMethod.drawnType = parameters[0].ParameterType; + item.drawnType = parameters[0].ParameterType; } else { if (!parameters[0].ParameterType.IsAssignableFrom(drawGizmo.drawnType)) { Debug.LogWarning(string.Format("Method {0}.{1} is marked with the DrawGizmo attribute but the component type it applies to could not be determined.", methodInfo.DeclaringType.FullName, methodInfo.Name)); - goto IL_194; + goto IL_18E; } - monoGizmoMethod.drawnType = drawGizmo.drawnType; + item.drawnType = drawGizmo.drawnType; } if (parameters[1].ParameterType != typeof(GizmoType) && parameters[1].ParameterType != typeof(int)) { @@ -78,27 +80,21 @@ private static AttributeHelper.MonoGizmoMethod[] ExtractGizmos(Assembly assembly } else { - monoGizmoMethod.drawGizmo = methodInfo; - monoGizmoMethod.options = (int)drawGizmo.drawOptions; - arrayList.Add(monoGizmoMethod); + item.drawGizmo = methodInfo; + item.options = (int)drawGizmo.drawOptions; + list.Add(item); } } - IL_194:; + IL_18E:; } } } - AttributeHelper.MonoGizmoMethod[] array3 = new AttributeHelper.MonoGizmoMethod[arrayList.Count]; - int num = 0; - foreach (AttributeHelper.MonoGizmoMethod monoGizmoMethod2 in arrayList) - { - array3[num++] = monoGizmoMethod2; - } - return array3; + return list.ToArray(); } private static AttributeHelper.MonoMenuItem[] ExtractMenuCommands(Assembly assembly) { bool @bool = EditorPrefs.GetBool("InternalMode", false); - Hashtable hashtable = new Hashtable(); + Dictionary dictionary = new Dictionary(); Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); Type[] array = typesFromAssembly; for (int i = 0; i < array.Length; i++) @@ -114,53 +110,44 @@ private static AttributeHelper.MonoMenuItem[] ExtractMenuCommands(Assembly assem while (k < array2.Length) { MenuItem menuItem = (MenuItem)array2[k]; - AttributeHelper.MonoMenuItem monoMenuItem = default(AttributeHelper.MonoMenuItem); - if (hashtable[menuItem.menuItem] != null) - { - monoMenuItem = (AttributeHelper.MonoMenuItem)hashtable[menuItem.menuItem]; - } + AttributeHelper.MonoMenuItem value = (!dictionary.ContainsKey(menuItem.menuItem)) ? default(AttributeHelper.MonoMenuItem) : dictionary[menuItem.menuItem]; if (!menuItem.menuItem.StartsWith("internal:", StringComparison.Ordinal)) { - monoMenuItem.menuItem = menuItem.menuItem; - goto IL_E7; + value.menuItem = menuItem.menuItem; + goto IL_E9; } if (@bool) { - monoMenuItem.menuItem = menuItem.menuItem.Substring(9); - goto IL_E7; + value.menuItem = menuItem.menuItem.Substring(9); + goto IL_E9; } - IL_147: + IL_144: k++; continue; - IL_E7: - monoMenuItem.type = type; + IL_E9: + value.type = type; if (menuItem.validate) { - monoMenuItem.validate = methodInfo.Name; + value.validate = methodInfo.Name; } else { - monoMenuItem.execute = methodInfo.Name; - monoMenuItem.index = j; - monoMenuItem.priority = menuItem.priority; + value.execute = methodInfo.Name; + value.index = j; + value.priority = menuItem.priority; } - hashtable[menuItem.menuItem] = monoMenuItem; - goto IL_147; + dictionary[menuItem.menuItem] = value; + goto IL_144; } } } - AttributeHelper.MonoMenuItem[] array3 = new AttributeHelper.MonoMenuItem[hashtable.Count]; - int num = 0; - foreach (AttributeHelper.MonoMenuItem monoMenuItem2 in hashtable.Values) - { - array3[num++] = monoMenuItem2; - } + AttributeHelper.MonoMenuItem[] array3 = dictionary.Values.ToArray(); Array.Sort(array3, new AttributeHelper.CompareMenuIndex()); return array3; } private static AttributeHelper.MonoMenuItem[] ExtractContextMenu(Type klass) { - Hashtable hashtable = new Hashtable(); + Dictionary dictionary = new Dictionary(); MethodInfo[] methods = klass.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.GetLength(0); i++) { @@ -170,24 +157,14 @@ private static AttributeHelper.MonoMenuItem[] ExtractContextMenu(Type klass) for (int j = 0; j < array.Length; j++) { ContextMenu contextMenu = (ContextMenu)array[j]; - AttributeHelper.MonoMenuItem monoMenuItem = default(AttributeHelper.MonoMenuItem); - if (hashtable[contextMenu.menuItem] != null) - { - monoMenuItem = (AttributeHelper.MonoMenuItem)hashtable[contextMenu.menuItem]; - } - monoMenuItem.menuItem = contextMenu.menuItem; - monoMenuItem.type = klass; - monoMenuItem.execute = methodInfo.Name; - hashtable[contextMenu.menuItem] = monoMenuItem; + AttributeHelper.MonoMenuItem value = (!dictionary.ContainsKey(contextMenu.menuItem)) ? default(AttributeHelper.MonoMenuItem) : dictionary[contextMenu.menuItem]; + value.menuItem = contextMenu.menuItem; + value.type = klass; + value.execute = methodInfo.Name; + dictionary[contextMenu.menuItem] = value; } } - AttributeHelper.MonoMenuItem[] array2 = new AttributeHelper.MonoMenuItem[hashtable.Count]; - int num = 0; - foreach (AttributeHelper.MonoMenuItem monoMenuItem2 in hashtable.Values) - { - array2[num++] = monoMenuItem2; - } - return array2; + return dictionary.Values.ToArray(); } private static string GetComponentMenuName(Type klass) { @@ -221,22 +198,6 @@ internal static ArrayList FindEditorClassesWithAttribute(Type attrib) } return arrayList; } - internal static void InvokeStaticMethod(Type type, string methodName, object[] arguments) - { - MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - if (method != null) - { - method.Invoke(null, arguments); - } - } - internal static void InvokeMethod(Type type, string methodName, object[] arguments) - { - MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - if (method != null) - { - method.Invoke(null, arguments); - } - } internal static object InvokeMemberIfAvailable(object target, string methodName, object[] args) { MethodInfo method = target.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); diff --git a/UnityEditor/UnityEditor/AudioClipInspector.cs b/UnityEditor/UnityEditor/AudioClipInspector.cs index e9669f1b..dcbd1782 100644 --- a/UnityEditor/UnityEditor/AudioClipInspector.cs +++ b/UnityEditor/UnityEditor/AudioClipInspector.cs @@ -60,8 +60,9 @@ public void OnEnable() } public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) { - AudioImporter audioImporter = AssetImporter.GetAtPath(assetPath) as AudioImporter; - if (!audioImporter) + AssetImporter atPath = AssetImporter.GetAtPath(assetPath); + AudioImporter exists = atPath as AudioImporter; + if (!exists) { return null; } @@ -69,7 +70,7 @@ public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Obje Texture2D[] array = new Texture2D[audioClip.channels]; for (int i = 0; i < audioClip.channels; i++) { - array[i] = AudioUtil.GetWaveForm(audioClip, audioImporter, i, (float)width, (float)(height / audioClip.channels)); + array[i] = AudioUtil.GetWaveForm(audioClip, atPath, i, (float)width, (float)(height / audioClip.channels)); } return AudioClipInspector.CombineWaveForms(array); } @@ -114,6 +115,10 @@ public override void OnPreviewSettings() EditorGUI.EndDisabledGroup(); EditorGUI.EndDisabledGroup(); } + public override void ReloadPreviewInstances() + { + AudioUtil.ClearWaveForm(this.target as AudioClip); + } public override void OnPreviewGUI(Rect r, GUIStyle background) { if (AudioClipInspector.s_DefaultIcon == null) @@ -151,14 +156,14 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) int channelCount = AudioUtil.GetChannelCount(audioClip); AudioClipInspector.m_wantedRect = new Rect(r.x, r.y, r.width, r.height); float num2 = AudioClipInspector.m_wantedRect.width / audioClip.length; - if (!AudioUtil.HasPreview(audioClip) && (AudioUtil.IsMOD(audioClip) || AudioUtil.IsMovieAudio(audioClip))) + if (!AudioUtil.HasPreview(audioClip) && (AudioUtil.IsTrackerFile(audioClip) || AudioUtil.IsMovieAudio(audioClip))) { float num3 = (r.height <= 150f) ? (r.y + r.height / 2f - 25f) : (r.y + r.height / 2f - 10f); if (r.width > 64f) { - if (AudioUtil.IsMOD(audioClip)) + if (AudioUtil.IsTrackerFile(audioClip)) { - EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), string.Format("Module file with " + AudioUtil.GetMODChannelCount(audioClip) + " channels.", new object[0])); + EditorGUI.DropShadowLabel(new Rect(r.x, num3, r.width, 20f), string.Format("Module file with " + AudioUtil.GetMusicChannelCount(audioClip) + " channels.", new object[0])); } else { @@ -283,48 +288,26 @@ public override string GetInfoString() AudioClip clip = this.target as AudioClip; int channelCount = AudioUtil.GetChannelCount(clip); string text = (channelCount != 1) ? ((channelCount != 2) ? ((channelCount - 1).ToString() + ".1") : "Stereo") : "Mono"; - string text2 = string.Empty; - if (AudioUtil.GetClipType(clip) != AudioType.MPEG) - { - text2 = string.Concat(new object[] - { - AudioUtil.GetBitsPerSample(clip), - " bit, ", - AudioUtil.GetFrequency(clip), - " Hz, ", - text, - ", " - }); - } - else + string str = string.Concat(new object[] { - text2 = string.Concat(new object[] - { - AudioUtil.GetFrequency(clip), - " Hz, ", - text, - ", " - }); - } + AudioUtil.GetSoundCompressionFormat(clip).ToString(), + ", ", + AudioUtil.GetFrequency(clip), + " Hz, ", + text, + ", " + }); TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)AudioUtil.GetDuration(clip)); if ((uint)AudioUtil.GetDuration(clip) == 4294967295u) { - text2 += "Unlimited"; + str += "Unlimited"; } else { - text2 += string.Format("{0:00}:{1:00}.{2:000}", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); + str += string.Format("{0:00}:{1:00}.{2:000}", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } - text2 += ", "; - text2 += EditorUtility.FormatBytes(AudioUtil.GetSoundSize(clip)); - string text3 = text2; - return string.Concat(new object[] - { - text3, - " (", - AudioUtil.GetClipType(clip), - ")" - }); + str += ", "; + return str + EditorUtility.FormatBytes(AudioUtil.GetSoundSize(clip)); } } } diff --git a/UnityEditor/UnityEditor/AudioCurveRendering.cs b/UnityEditor/UnityEditor/AudioCurveRendering.cs new file mode 100644 index 00000000..4a3222ab --- /dev/null +++ b/UnityEditor/UnityEditor/AudioCurveRendering.cs @@ -0,0 +1,214 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public class AudioCurveRendering + { + public delegate float AudioCurveEvaluator(float x); + public delegate float AudioCurveAndColorEvaluator(float x, out Color col); + public static readonly Color kAudioOrange = new Color(1f, 0.65882355f, 0.02745098f); + private static Vector3[] s_PointCache; + public static Rect BeginCurveFrame(Rect r) + { + AudioCurveRendering.DrawCurveBackground(r); + r = AudioCurveRendering.DrawCurveFrame(r); + GUI.BeginGroup(r); + return new Rect(0f, 0f, r.width, r.height); + } + public static void EndCurveFrame() + { + GUI.EndGroup(); + } + public static Rect DrawCurveFrame(Rect r) + { + if (Event.current.type != EventType.Repaint) + { + return r; + } + EditorStyles.colorPickerBox.Draw(r, false, false, false, false); + 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)); + } + public static void DrawFilledCurve(Rect r, AudioCurveRendering.AudioCurveEvaluator eval, Color curveColor) + { + AudioCurveRendering.DrawFilledCurve(r, delegate(float x, out Color color) + { + color = curveColor; + return eval(x); + }); + } + public static void DrawFilledCurve(Rect r, AudioCurveRendering.AudioCurveAndColorEvaluator eval) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.Begin(1); + float num = 1f / (r.width - 1f); + float num2 = r.height * 0.5f; + Color c; + float num3 = r.y + Mathf.Clamp(num2 - num2 * eval(0.0001f, out c), 0f, r.height); + int num4 = 0; + while ((float)num4 < r.width) + { + float num5 = (float)((int)r.x + num4); + float num6 = r.y + Mathf.Clamp(num2 - num2 * eval((float)num4 * num, out c), 0f, r.height); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num5, (float)((int)Mathf.Ceil(num6))); + AudioMixerDrawUtils.Vertex(num5, r.y + r.height); + if (Mathf.Abs(num3 - num6) <= 1f) + { + GL.Color(new Color(c.r, c.g, c.b, c.a * (Mathf.Ceil(num6) - num6))); + AudioMixerDrawUtils.Vertex(num5, Mathf.Ceil(num6) - 1f); + AudioMixerDrawUtils.Vertex(num5, Mathf.Ceil(num6)); + } + else + { + if (num3 < num6) + { + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num5, Mathf.Ceil(num3)); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num5, Mathf.Ceil(num6)); + } + else + { + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num5 - 1f, Mathf.Ceil(num6)); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num5 - 1f, Mathf.Ceil(num3)); + } + } + num3 = num6; + num4++; + } + GL.End(); + } + public static void DrawSymmetricFilledCurve(Rect r, AudioCurveRendering.AudioCurveAndColorEvaluator eval) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.Begin(1); + float num = 1f / (r.width - 1f); + float num2 = r.height * 0.5f; + float y = r.y; + float num3 = r.y + r.height; + Color c; + float num4 = Mathf.Clamp(num2 - num2 * eval(0.0001f, out c), 0f, num2); + int num5 = 0; + while ((float)num5 < r.width) + { + float num6 = (float)((int)r.x + num5); + float num7 = Mathf.Clamp(num2 - num2 * eval((float)num5 * num, out c), 0f, num2); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num6, y + (float)((int)Mathf.Ceil(num7))); + AudioMixerDrawUtils.Vertex(num6, num3 - (float)((int)Mathf.Ceil(num7))); + if (Mathf.Abs(num4 - num7) <= 1f) + { + GL.Color(new Color(c.r, c.g, c.b, c.a * (Mathf.Ceil(num7) - num7))); + AudioMixerDrawUtils.Vertex(num6, y + Mathf.Ceil(num7) - 1f); + AudioMixerDrawUtils.Vertex(num6, y + Mathf.Ceil(num7)); + AudioMixerDrawUtils.Vertex(num6, num3 - Mathf.Ceil(num7) + 1f); + AudioMixerDrawUtils.Vertex(num6, num3 - Mathf.Ceil(num7)); + } + else + { + if (num4 < num7) + { + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num6, y + Mathf.Ceil(num4)); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num6, y + Mathf.Ceil(num7)); + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num6, num3 - Mathf.Ceil(num4) - 1f); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num6, num3 - Mathf.Ceil(num7) - 1f); + } + else + { + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num6 - 1f, y + Mathf.Ceil(num7)); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num6 - 1f, y + Mathf.Ceil(num4)); + GL.Color(new Color(c.r, c.g, c.b, 0f)); + AudioMixerDrawUtils.Vertex(num6 - 1f, num3 - Mathf.Ceil(num7) - 1f); + GL.Color(c); + AudioMixerDrawUtils.Vertex(num6 - 1f, num3 - Mathf.Ceil(num4) - 1f); + } + } + num4 = num7; + num5++; + } + GL.End(); + } + public static void DrawCurve(Rect r, AudioCurveRendering.AudioCurveEvaluator eval, Color curveColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + int num = (int)r.width; + float num2 = r.height * 0.5f; + float num3 = 1f / (float)(num - 1); + Vector3[] pointCache = AudioCurveRendering.GetPointCache(num); + for (int i = 0; i < num; i++) + { + pointCache[i].x = (float)i + r.x; + pointCache[i].y = num2 - num2 * eval((float)i * num3) + r.y; + pointCache[i].z = 0f; + } + GUI.BeginClip(r); + Handles.color = curveColor; + Handles.DrawAAPolyLine(3f, num, pointCache); + GUI.EndClip(); + } + private static Vector3[] GetPointCache(int numPoints) + { + if (AudioCurveRendering.s_PointCache == null || AudioCurveRendering.s_PointCache.Length != numPoints) + { + AudioCurveRendering.s_PointCache = new Vector3[numPoints]; + } + return AudioCurveRendering.s_PointCache; + } + 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(7); + if (horizontal) + { + GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * blend)); + GL.Vertex3(r.x, r.y, 0f); + GL.Vertex3(r.x + r.width, r.y, 0f); + GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * blend)); + GL.Vertex3(r.x + r.width, r.y + r.height, 0f); + GL.Vertex3(r.x, r.y + r.height, 0f); + } + else + { + GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * blend)); + GL.Vertex3(r.x, r.y + r.height, 0f); + GL.Vertex3(r.x, r.y, 0f); + GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * blend)); + GL.Vertex3(r.x + r.width, r.y, 0f); + GL.Vertex3(r.x + r.width, r.y + r.height, 0f); + } + GL.End(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioFilterGUI.cs b/UnityEditor/UnityEditor/AudioFilterGUI.cs index 9cc3eeb0..7f264196 100644 --- a/UnityEditor/UnityEditor/AudioFilterGUI.cs +++ b/UnityEditor/UnityEditor/AudioFilterGUI.cs @@ -4,7 +4,7 @@ namespace UnityEditor { internal class AudioFilterGUI { - private EditorGUI.VUMeterData[] dataOut; + private EditorGUI.VUMeter.SmoothingData[] dataOut; public void DrawAudioFilterGUI(MonoBehaviour behaviour) { int customFilterChannelCount = AudioUtil.GetCustomFilterChannelCount(behaviour); @@ -12,7 +12,7 @@ public void DrawAudioFilterGUI(MonoBehaviour behaviour) { if (this.dataOut == null) { - this.dataOut = new EditorGUI.VUMeterData[customFilterChannelCount]; + this.dataOut = new EditorGUI.VUMeter.SmoothingData[customFilterChannelCount]; } double num = (double)AudioUtil.GetCustomFilterProcessTime(behaviour) / 1000000.0; float num2 = (float)num / ((float)AudioSettings.outputSampleRate / 1024f / (float)customFilterChannelCount); diff --git a/UnityEditor/UnityEditor/AudioGroupDataSource.cs b/UnityEditor/UnityEditor/AudioGroupDataSource.cs new file mode 100644 index 00000000..1102e958 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioGroupDataSource.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioGroupDataSource : TreeViewDataSource + { + public AudioMixerController m_Controller; + public AudioGroupDataSource(TreeView treeView, AudioMixerController controller) : base(treeView) + { + this.m_Controller = controller; + } + private void AddNodesRecursively(AudioMixerGroupController group, TreeViewItem parent, int depth) + { + List list = new List(); + for (int i = 0; i < group.children.Length; i++) + { + int uniqueNodeID = AudioGroupDataSource.GetUniqueNodeID(group.children[i]); + AudioMixerTreeViewNode audioMixerTreeViewNode = new AudioMixerTreeViewNode(uniqueNodeID, depth, parent, group.children[i].name, group.children[i]); + audioMixerTreeViewNode.parent = parent; + list.Add(audioMixerTreeViewNode); + this.AddNodesRecursively(group.children[i], audioMixerTreeViewNode, depth + 1); + } + parent.children = list; + } + public static int GetUniqueNodeID(AudioMixerGroupController group) + { + return group.GetInstanceID(); + } + public override void FetchData() + { + if (this.m_Controller == null) + { + this.m_RootItem = null; + return; + } + if (this.m_Controller.masterGroup == null) + { + Debug.LogError("The Master group is missing !!!"); + this.m_RootItem = null; + return; + } + int uniqueNodeID = AudioGroupDataSource.GetUniqueNodeID(this.m_Controller.masterGroup); + this.m_RootItem = new AudioMixerTreeViewNode(uniqueNodeID, 0, null, this.m_Controller.masterGroup.name, this.m_Controller.masterGroup); + this.AddNodesRecursively(this.m_Controller.masterGroup, this.m_RootItem, 1); + this.m_NeedRefreshVisibleFolders = true; + } + public override bool IsRenamingItemAllowed(TreeViewItem node) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = node as AudioMixerTreeViewNode; + return !(audioMixerTreeViewNode.group == this.m_Controller.masterGroup); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioGroupTreeViewDragging.cs b/UnityEditor/UnityEditor/AudioGroupTreeViewDragging.cs new file mode 100644 index 00000000..2c8a85f6 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioGroupTreeViewDragging.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioGroupTreeViewDragging : AssetsTreeViewDragging + { + private AudioMixerGroupTreeView m_owner; + public AudioGroupTreeViewDragging(TreeView treeView, AudioMixerGroupTreeView owner) : base(treeView) + { + this.m_owner = owner; + } + public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) + { + if (!EditorApplication.isPlaying) + { + base.StartDrag(draggedItem, draggedItemIDs); + } + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentNode, TreeViewItem targetNode, bool perform, TreeViewDragging.DropPosition dragPos) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = targetNode as AudioMixerTreeViewNode; + AudioMixerTreeViewNode audioMixerTreeViewNode2 = parentNode as AudioMixerTreeViewNode; + List list = new List(DragAndDrop.objectReferences).OfType().ToList(); + if (audioMixerTreeViewNode2 != null && list.Count > 0) + { + List list2 = ( + from i in list + select i.GetInstanceID()).ToList(); + bool flag = this.ValidDrag(parentNode, list2) && !AudioMixerController.WillModificationOfTopologyCauseFeedback(this.m_owner.Controller.GetAllAudioGroupsSlow(), list, audioMixerTreeViewNode2.group, null); + if (perform && flag) + { + AudioMixerGroupController group = audioMixerTreeViewNode2.group; + this.m_owner.Controller.ReparentSelection(group, audioMixerTreeViewNode.group, list); + this.m_owner.ReloadTree(); + this.m_TreeView.SetSelection(list2.ToArray(), true); + } + return (!flag) ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Move; + } + return DragAndDropVisualMode.None; + } + private bool ValidDrag(TreeViewItem parent, List draggedInstanceIDs) + { + for (TreeViewItem treeViewItem = parent; treeViewItem != null; treeViewItem = treeViewItem.parent) + { + if (draggedInstanceIDs.Contains(treeViewItem.id)) + { + return false; + } + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioGroupTreeViewGUI.cs b/UnityEditor/UnityEditor/AudioGroupTreeViewGUI.cs new file mode 100644 index 00000000..3c5ba9c5 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioGroupTreeViewGUI.cs @@ -0,0 +1,108 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioGroupTreeViewGUI : TreeViewGUI + { + private readonly float column1Width = 20f; + private readonly Texture2D k_VisibleON = EditorGUIUtility.FindTexture("VisibilityOn"); + public Action NodeWasToggled; + public AudioMixerController m_Controller; + public AudioGroupTreeViewGUI(TreeView treeView) : base(treeView) + { + this.k_BaseIndent = this.column1Width; + this.k_IconWidth = 0f; + this.k_TopRowMargin = (this.k_BottomRowMargin = 2f); + } + private void OpenGroupContextMenu(AudioMixerTreeViewNode audioNode, bool visible) + { + GenericMenu genericMenu = new GenericMenu(); + if (this.NodeWasToggled != null) + { + genericMenu.AddItem(new GUIContent((!visible) ? "Show Group" : "Hide group"), false, delegate + { + this.NodeWasToggled(audioNode, !visible); + }); + } + genericMenu.AddSeparator(string.Empty); + AudioMixerColorCodes.AddColorItemsToGenericMenu(genericMenu, audioNode.group); + genericMenu.ShowAsContext(); + } + public override Rect OnRowGUI(TreeViewItem node, int row, float rowWidth, bool selected, bool focused) + { + Event current = Event.current; + Rect rect = new Rect(0f, (float)row * this.k_LineHeight + this.k_TopRowMargin, rowWidth, this.k_LineHeight); + this.DoNodeGUI(rect, node, selected, focused, false); + if (this.m_Controller == null) + { + return rect; + } + AudioMixerTreeViewNode audioMixerTreeViewNode = node as AudioMixerTreeViewNode; + if (audioMixerTreeViewNode != null) + { + bool flag = this.m_Controller.CurrentViewContainsGroup(audioMixerTreeViewNode.group.groupID); + float num = 3f; + Rect position = new Rect(rect.x + num, rect.y, 16f, 16f); + Rect rect2 = new Rect(position.x + 1f, position.y + 1f, position.width - 2f, position.height - 2f); + int userColorIndex = audioMixerTreeViewNode.group.userColorIndex; + if (userColorIndex > 0) + { + EditorGUI.DrawRect(new Rect(rect.x, rect2.y, 2f, rect2.height), AudioMixerColorCodes.GetColor(userColorIndex)); + } + EditorGUI.DrawRect(rect2, new Color(0.5f, 0.5f, 0.5f, 0.2f)); + if (flag) + { + GUI.DrawTexture(position, this.k_VisibleON); + } + Rect rect3 = new Rect(2f, rect.y, rect.height, rect.height); + if (current.type == EventType.MouseDown && current.button == 0 && rect3.Contains(current.mousePosition) && this.NodeWasToggled != null) + { + this.NodeWasToggled(audioMixerTreeViewNode, !flag); + } + if (current.type == EventType.ContextClick && position.Contains(current.mousePosition)) + { + this.OpenGroupContextMenu(audioMixerTreeViewNode, flag); + current.Use(); + } + } + return rect; + } + protected override Texture GetIconForNode(TreeViewItem node) + { + if (node != null && node.icon != null) + { + return node.icon; + } + return null; + } + protected override void SyncFakeItem() + { + } + protected override void RenameEnded() + { + bool userAcceptedRename = base.GetRenameOverlay().userAcceptedRename; + if (userAcceptedRename) + { + string name = (!string.IsNullOrEmpty(base.GetRenameOverlay().name)) ? base.GetRenameOverlay().name : base.GetRenameOverlay().originalName; + int userData = base.GetRenameOverlay().userData; + AudioMixerTreeViewNode audioMixerTreeViewNode = this.m_TreeView.FindNode(userData) as AudioMixerTreeViewNode; + if (audioMixerTreeViewNode != null) + { + ObjectNames.SetNameSmartWithInstanceID(userData, name); + AudioMixerEffectController[] effects = audioMixerTreeViewNode.group.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + audioMixerEffectController.ClearCachedDisplayName(); + } + this.m_TreeView.ReloadData(); + if (this.m_Controller != null) + { + this.m_Controller.OnSubAssetChanged(); + } + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioImporter.cs b/UnityEditor/UnityEditor/AudioImporter.cs index c9094477..18e6e984 100644 --- a/UnityEditor/UnityEditor/AudioImporter.cs +++ b/UnityEditor/UnityEditor/AudioImporter.cs @@ -5,7 +5,7 @@ namespace UnityEditor { public sealed class AudioImporter : AssetImporter { - public extern AudioImporterFormat format + public extern AudioImporterSampleSettings defaultSampleSettings { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -14,39 +14,64 @@ public extern AudioImporterFormat format [MethodImpl(MethodImplOptions.InternalCall)] set; } - [Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] - public AudioImporterChannels channels + public extern bool forceToMono + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public bool loadInBackground { get { - return AudioImporterChannels.Automatic; + return this.Internal_GetLoadInBackground(); } set { + this.Internal_SetLoadInBackground(value); } } - public extern int compressionBitrate + public bool preloadAudioData { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.Internal_GetPreloadAudioData(); + } + set + { + this.Internal_SetPreloadAudioData(value); + } } - [Obsolete("Setting/Getting decompressOnLoad is deprecated. Use AudioImporter.loadType instead.", true)] - private bool decompressOnLoad + [Obsolete("Setting and getting the compression format is not used anymore (use compressionFormat in defaultSampleSettings instead). Source audio file is assumed to be PCM Wav.")] + private AudioImporterFormat format { get { - return this.loadType == AudioImporterLoadType.DecompressOnLoad; + return (this.defaultSampleSettings.compressionFormat != AudioCompressionFormat.PCM) ? AudioImporterFormat.Compressed : AudioImporterFormat.Native; } set { - this.loadType = ((!value) ? AudioImporterLoadType.CompressedInMemory : AudioImporterLoadType.DecompressOnLoad); + AudioImporterSampleSettings defaultSampleSettings = this.defaultSampleSettings; + defaultSampleSettings.compressionFormat = ((value != AudioImporterFormat.Native) ? AudioCompressionFormat.Vorbis : AudioCompressionFormat.PCM); + this.defaultSampleSettings = defaultSampleSettings; } } - public extern bool threeD + [Obsolete("Setting and getting import channels is not used anymore (use forceToMono instead)", true)] + public AudioImporterChannels channels + { + get + { + return AudioImporterChannels.Automatic; + } + set + { + } + } + [Obsolete("AudioImporter.compressionBitrate is no longer supported", true)] + public extern int compressionBitrate { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -55,7 +80,8 @@ public extern bool threeD [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern bool forceToMono + [Obsolete("AudioImporter.loopable is no longer supported. All audio assets encoded by Unity are by default loopable.")] + public extern bool loopable { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -64,6 +90,7 @@ public extern bool forceToMono [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("AudioImporter.hardware is no longer supported. All mixing of audio is done by software and only some platforms use hardware acceleration to perform decoding.")] public extern bool hardware { [WrapperlessIcall] @@ -73,18 +100,36 @@ public extern bool hardware [MethodImpl(MethodImplOptions.InternalCall)] set; } - public AudioImporterLoadType loadType + [Obsolete("Setting/Getting decompressOnLoad is deprecated. Use AudioImporterSampleSettings.loadType instead.")] + private bool decompressOnLoad { get { - return (AudioImporterLoadType)this.Internal_GetLoadType(); + return this.defaultSampleSettings.loadType == AudioClipLoadType.DecompressOnLoad; } set { - this.Internal_SetLoadType((int)value); + AudioImporterSampleSettings defaultSampleSettings = this.defaultSampleSettings; + defaultSampleSettings.loadType = ((!value) ? AudioClipLoadType.CompressedInMemory : AudioClipLoadType.DecompressOnLoad); + this.defaultSampleSettings = defaultSampleSettings; } } - public extern bool loopable + [Obsolete("AudioImporter.quality is no longer supported. Use AudioImporterSampleSettings.")] + private float quality + { + get + { + return this.defaultSampleSettings.quality; + } + set + { + AudioImporterSampleSettings defaultSampleSettings = this.defaultSampleSettings; + defaultSampleSettings.quality = value; + this.defaultSampleSettings = defaultSampleSettings; + } + } + [Obsolete("AudioImporter.threeD is no longer supported")] + public extern bool threeD { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -93,80 +138,151 @@ public extern bool loopable [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("AudioImporter.durationMS is deprecated.", true)] internal extern int durationMS { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.frequency is deprecated.", true)] internal extern int frequency { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.origChannelCount is deprecated.", true)] internal extern int origChannelCount { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.origIsCompressible is deprecated.", true)] internal extern bool origIsCompressible { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.origIsMonoForcable is deprecated.", true)] internal extern bool origIsMonoForcable { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.defaultBitrate is deprecated.", true)] internal extern int defaultBitrate { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("AudioImporter.origType is deprecated.", true)] internal AudioType origType { get { - return (AudioType)this.Internal_GetType(); + return AudioType.UNKNOWN; } } + [Obsolete("AudioImporter.origFileSize is deprecated.", true)] internal extern int origFileSize { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal extern int origSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern int compSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public bool ContainsSampleSettingsOverride(string platform) + { + BuildTargetGroup buildTargetGroupByName = BuildPipeline.GetBuildTargetGroupByName(platform); + if (buildTargetGroupByName == BuildTargetGroup.Unknown) + { + Debug.LogError("Unknown platform passed to AudioImporter.ContainsSampleSettingsOverride (" + platform + "), please use one of 'Web', 'Standalone', 'iOS', 'Android', 'WebGL', 'PS3', 'PS4', 'PSP2', 'PSM', 'XBox360', 'XboxOne', 'WP8', 'WSA' or 'BlackBerry'"); + return false; + } + return this.Internal_ContainsSampleSettingsOverride(buildTargetGroupByName); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool Internal_ContainsSampleSettingsOverride(BuildTargetGroup platformGroup); + public AudioImporterSampleSettings GetOverrideSampleSettings(string platform) + { + BuildTargetGroup buildTargetGroupByName = BuildPipeline.GetBuildTargetGroupByName(platform); + if (buildTargetGroupByName == BuildTargetGroup.Unknown) + { + Debug.LogError("Unknown platform passed to AudioImporter.GetOverrideSampleSettings (" + platform + "), please use one of 'Web', 'Standalone', 'iOS', 'Android', 'WebGL', 'PS3', 'PS4', 'PSP2', 'PSM', 'XBox360', 'XboxOne', 'WP8', 'WSA' or 'BlackBerry'"); + return this.defaultSampleSettings; + } + return this.Internal_GetOverrideSampleSettings(buildTargetGroupByName); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetLoadType(int flag); + internal extern AudioImporterSampleSettings Internal_GetOverrideSampleSettings(BuildTargetGroup platformGroup); + public bool SetOverrideSampleSettings(string platform, AudioImporterSampleSettings settings) + { + BuildTargetGroup buildTargetGroupByName = BuildPipeline.GetBuildTargetGroupByName(platform); + if (buildTargetGroupByName == BuildTargetGroup.Unknown) + { + Debug.LogError("Unknown platform passed to AudioImporter.SetOverrideSampleSettings (" + platform + "), please use one of 'Web', 'Standalone', 'iOS', 'Android', 'WebGL', 'PS3', 'PS4', 'PSP2', 'PSM', 'XBox360', 'XboxOne', 'WP8', 'WSA' or 'BlackBerry'"); + return false; + } + return this.Internal_SetOverrideSampleSettings(buildTargetGroupByName, settings); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetLoadType(); + internal extern bool Internal_SetOverrideSampleSettings(BuildTargetGroup platformGroup, AudioImporterSampleSettings settings); + public bool ClearSampleSettingOverride(string platform) + { + BuildTargetGroup buildTargetGroupByName = BuildPipeline.GetBuildTargetGroupByName(platform); + if (buildTargetGroupByName == BuildTargetGroup.Unknown) + { + Debug.LogError("Unknown platform passed to AudioImporter.ClearSampleSettingOverride (" + platform + "), please use one of 'Web', 'Standalone', 'iOS', 'Android', 'WebGL', 'PS3', 'PS4', 'PSP2', 'PSM', 'XBox360', 'XboxOne', 'WP8', 'WSA' or 'BlackBerry'"); + return false; + } + return this.Internal_ClearSampleSettingOverride(buildTargetGroupByName); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void updateOrigData(); + internal extern bool Internal_ClearSampleSettingOverride(BuildTargetGroup platform); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetMinBitrate(int type); + private extern void Internal_SetLoadInBackground(bool flag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_GetLoadInBackground(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Internal_SetPreloadAudioData(bool flag); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool Internal_GetPreloadAudioData(); + [Obsolete("AudioImporter.updateOrigData is deprecated.", true), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void updateOrigData(); + [Obsolete("AudioImporter.minBitrate is deprecated.", true)] internal int minBitrate(AudioType type) { - return this.Internal_GetMinBitrate((int)type); + return 0; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetMaxBitrate(int type); + [Obsolete("AudioImporter.maxBitrate is deprecated.", true)] internal int maxBitrate(AudioType type) { - return this.Internal_GetMaxBitrate((int)type); + return 0; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetType(); } } diff --git a/UnityEditor/UnityEditor/AudioImporterFormat.cs b/UnityEditor/UnityEditor/AudioImporterFormat.cs index c36c6907..79f10772 100644 --- a/UnityEditor/UnityEditor/AudioImporterFormat.cs +++ b/UnityEditor/UnityEditor/AudioImporterFormat.cs @@ -1,6 +1,8 @@ using System; +using System.ComponentModel; namespace UnityEditor { + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("UnityEditor.AudioImporterFormat has been deprecated. Use UnityEngine.AudioCompressionFormat instead.")] public enum AudioImporterFormat { Native = -1, diff --git a/UnityEditor/UnityEditor/AudioImporterInspector.cs b/UnityEditor/UnityEditor/AudioImporterInspector.cs index 768c8435..fd753308 100644 --- a/UnityEditor/UnityEditor/AudioImporterInspector.cs +++ b/UnityEditor/UnityEditor/AudioImporterInspector.cs @@ -1,219 +1,544 @@ using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; using UnityEngine; namespace UnityEditor { - [CustomEditor(typeof(AudioImporter))] + [CanEditMultipleObjects, CustomEditor(typeof(AudioImporter))] internal class AudioImporterInspector : AssetImporterInspector { - private AudioImporterFormat m_format; - private int m_compressionBitrate; - private AudioImporterLoadType m_loadType; - private bool m_3D; - private bool m_Hardware; - private bool m_Loopable; - private bool m_ForceToMono; - private int m_durationMS; - private int m_origchannels; - private bool m_iscompressible; - private AudioType m_type; - private int m_maxbitrate; - private int m_minbitrate; - private AudioType m_compressedType; - private static string[] formatLabels = new string[2]; - internal override bool HasModified() + private static class Styles { - AudioImporter audioImporter = this.target as AudioImporter; - return audioImporter.format != this.m_format || audioImporter.compressionBitrate != this.m_compressionBitrate || audioImporter.loadType != this.m_loadType || audioImporter.threeD != this.m_3D || audioImporter.forceToMono != this.m_ForceToMono || audioImporter.hardware != this.m_Hardware || audioImporter.loopable != this.m_Loopable; + public static readonly string[] kSampleRateStrings = new string[] + { + "8,000 Hz", + "11,025 Hz", + "22,050 Hz", + "44,100 Hz", + "48,000 Hz", + "96,000 Hz", + "192,000 Hz" + }; + public static readonly int[] kSampleRateValues = new int[] + { + 8000, + 11025, + 22050, + 44100, + 48000, + 96000, + 192000 + }; } - internal override void ResetValues() + private struct MultiValueStatus { - AudioImporter audioImporter = this.target as AudioImporter; - this.m_format = audioImporter.format; - this.m_loadType = audioImporter.loadType; - this.m_compressionBitrate = audioImporter.compressionBitrate; - this.m_3D = audioImporter.threeD; - this.m_ForceToMono = audioImporter.forceToMono; - this.m_Hardware = audioImporter.hardware; - this.m_Loopable = audioImporter.loopable; - audioImporter.updateOrigData(); - this.m_durationMS = audioImporter.durationMS; - this.m_origchannels = audioImporter.origChannelCount; - this.m_iscompressible = audioImporter.origIsCompressible; - this.m_type = audioImporter.origType; - if (this.m_durationMS != 0) - { - this.m_compressedType = AudioUtil.GetPlatformConversionType(this.m_type, BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget), AudioImporterFormat.Compressed); - } - this.m_minbitrate = audioImporter.minBitrate(this.m_compressedType) / 1000; - this.m_maxbitrate = audioImporter.maxBitrate(this.m_compressedType) / 1000; + public bool multiLoadType; + public bool multiSampleRateSetting; + public bool multiSampleRateOverride; + public bool multiCompressionFormat; + public bool multiQuality; + public bool multiConversionMode; } - internal override void Apply() + private struct SampleSettingProperties { - AudioImporter audioImporter = this.target as AudioImporter; - audioImporter.format = this.m_format; - audioImporter.loadType = this.m_loadType; - audioImporter.compressionBitrate = this.m_compressionBitrate; - audioImporter.threeD = this.m_3D; - audioImporter.forceToMono = this.m_ForceToMono; - audioImporter.hardware = this.m_Hardware; - audioImporter.loopable = this.m_Loopable; + public AudioImporterSampleSettings settings; + public bool forcedOverrideState; + public bool overrideIsForced; + public bool loadTypeChanged; + public bool sampleRateSettingChanged; + public bool sampleRateOverrideChanged; + public bool compressionFormatChanged; + public bool qualityChanged; + public bool conversionModeChanged; + public bool HasModified() + { + return this.overrideIsForced || this.loadTypeChanged || this.sampleRateSettingChanged || this.sampleRateOverrideChanged || this.compressionFormatChanged || this.qualityChanged || this.conversionModeChanged; + } + public void ClearChangedFlags() + { + this.forcedOverrideState = false; + this.overrideIsForced = false; + this.loadTypeChanged = false; + this.sampleRateSettingChanged = false; + this.sampleRateOverrideChanged = false; + this.compressionFormatChanged = false; + this.qualityChanged = false; + this.conversionModeChanged = false; + } } - public override void OnInspectorGUI() + private enum OverrideStatus { - BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); - AudioImporter audioImporter = this.target as AudioImporter; - if (audioImporter != null) + NoOverrides, + MixedOverrides, + AllOverrides + } + public SerializedProperty m_ForceToMono; + public SerializedProperty m_PreloadAudioData; + public SerializedProperty m_LoadInBackground; + public SerializedProperty m_OrigSize; + public SerializedProperty m_CompSize; + private AudioImporterInspector.SampleSettingProperties m_DefaultSampleSettings; + private Dictionary m_SampleSettingOverrides; + [DebuggerHidden] + private IEnumerable GetAllAudioImporterTargets() + { + AudioImporterInspector.c__Iterator5 c__Iterator = new AudioImporterInspector.c__Iterator5(); + c__Iterator.<>f__this = this; + AudioImporterInspector.c__Iterator5 expr_0E = c__Iterator; + expr_0E.$PC = -2; + return expr_0E; + } + private bool SyncSettingsToBackend() + { + BuildPlayerWindow.BuildPlatform[] array = BuildPlayerWindow.GetValidPlatforms().ToArray(); + foreach (AudioImporter current in this.GetAllAudioImporterTargets()) { - BuildTargetGroup buildTargetGroup2 = buildTargetGroup; - if (buildTargetGroup2 != BuildTargetGroup.FlashPlayer) + AudioImporterSampleSettings defaultSampleSettings = current.defaultSampleSettings; + if (this.m_DefaultSampleSettings.loadTypeChanged) + { + defaultSampleSettings.loadType = this.m_DefaultSampleSettings.settings.loadType; + } + if (this.m_DefaultSampleSettings.sampleRateSettingChanged) + { + defaultSampleSettings.sampleRateSetting = this.m_DefaultSampleSettings.settings.sampleRateSetting; + } + if (this.m_DefaultSampleSettings.sampleRateOverrideChanged) + { + defaultSampleSettings.sampleRateOverride = this.m_DefaultSampleSettings.settings.sampleRateOverride; + } + if (this.m_DefaultSampleSettings.compressionFormatChanged) + { + defaultSampleSettings.compressionFormat = this.m_DefaultSampleSettings.settings.compressionFormat; + } + if (this.m_DefaultSampleSettings.qualityChanged) { - if (buildTargetGroup2 != BuildTargetGroup.PSP2) + defaultSampleSettings.quality = this.m_DefaultSampleSettings.settings.quality; + } + if (this.m_DefaultSampleSettings.conversionModeChanged) + { + defaultSampleSettings.conversionMode = this.m_DefaultSampleSettings.settings.conversionMode; + } + current.defaultSampleSettings = defaultSampleSettings; + BuildPlayerWindow.BuildPlatform[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + BuildPlayerWindow.BuildPlatform buildPlatform = array2[i]; + BuildTargetGroup targetGroup = buildPlatform.targetGroup; + if (this.m_SampleSettingOverrides.ContainsKey(targetGroup)) { - EditorGUI.BeginDisabledGroup(this.m_type == AudioType.MPEG || this.m_type == AudioType.OGGVORBIS || !this.m_iscompressible); - AudioImporterInspector.formatLabels[0] = "Native (" + this.m_type + ")"; - AudioImporterInspector.formatLabels[1] = "Compressed (" + this.m_compressedType + ")"; - int num = EditorGUILayout.Popup("Audio Format", (int)(this.m_format + 1), AudioImporterInspector.formatLabels, new GUILayoutOption[0]); - this.m_format = (AudioImporterFormat)(num - 1); - EditorGUI.EndDisabledGroup(); - this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); - bool flag = this.m_origchannels > 1 && (audioImporter.origIsMonoForcable || (this.m_format == AudioImporterFormat.Compressed && this.m_iscompressible)); - EditorGUI.BeginDisabledGroup(!flag); - this.m_ForceToMono = EditorGUILayout.Toggle("Force to mono", this.m_ForceToMono, new GUILayoutOption[0]); - EditorGUI.EndDisabledGroup(); - if (this.m_format == AudioImporterFormat.Compressed) + AudioImporterInspector.SampleSettingProperties value = this.m_SampleSettingOverrides[targetGroup]; + if (value.overrideIsForced && !value.forcedOverrideState) { - string[] displayedOptions = new string[] - { - "Decompress on load", - "Compressed in memory", - "Stream from disc" - }; - this.m_loadType = (AudioImporterLoadType)EditorGUILayout.Popup("Load type", (int)this.m_loadType, displayedOptions, new GUILayoutOption[0]); + current.Internal_ClearSampleSettingOverride(targetGroup); } else { - string[] displayedOptions = new string[] - { - "Load into memory", - "Stream from disc" - }; - int num2 = Mathf.Clamp(this.m_loadType - AudioImporterLoadType.CompressedInMemory, 0, 1); - EditorGUI.BeginChangeCheck(); - num2 = EditorGUILayout.Popup("Load type", num2, displayedOptions, new GUILayoutOption[0]); - if (EditorGUI.EndChangeCheck()) - { - this.m_loadType = num2 + AudioImporterLoadType.CompressedInMemory; - } - } - EditorGUI.BeginDisabledGroup(buildTargetGroup != BuildTargetGroup.iPhone || this.m_format != AudioImporterFormat.Compressed); - this.m_Hardware = EditorGUILayout.Toggle("Hardware decoding", this.m_Hardware, new GUILayoutOption[0]); - EditorGUI.EndDisabledGroup(); - EditorGUI.BeginDisabledGroup(!this.m_iscompressible || (this.m_compressedType != AudioType.MPEG && this.m_compressedType != AudioType.XMA) || this.m_format != AudioImporterFormat.Compressed); - this.m_Loopable = EditorGUILayout.Toggle(new GUIContent("Gapless looping", "Perform special MPEG encoding and stretch to loop the sound perfectly"), this.m_Loopable, new GUILayoutOption[0]); - EditorGUI.EndDisabledGroup(); - if (this.m_durationMS != 0) - { - EditorGUI.BeginDisabledGroup(this.m_format != AudioImporterFormat.Compressed); - int compressionBitrate; - if (buildTargetGroup == BuildTargetGroup.XBOX360) - { - compressionBitrate = (56 + 2 * this.GetQualityGUI()) * 1000; - } - else - { - compressionBitrate = this.GetBitRateGUI(audioImporter) * 1000; - } - if (GUI.changed) + if (current.Internal_ContainsSampleSettingsOverride(targetGroup) || (value.overrideIsForced && value.forcedOverrideState)) { - this.m_compressionBitrate = compressionBitrate; + AudioImporterSampleSettings settings = current.Internal_GetOverrideSampleSettings(targetGroup); + if (value.loadTypeChanged) + { + settings.loadType = value.settings.loadType; + } + if (value.sampleRateSettingChanged) + { + settings.sampleRateSetting = value.settings.sampleRateSetting; + } + if (value.sampleRateOverrideChanged) + { + settings.sampleRateOverride = value.settings.sampleRateOverride; + } + if (value.compressionFormatChanged) + { + settings.compressionFormat = value.settings.compressionFormat; + } + if (value.qualityChanged) + { + settings.quality = value.settings.quality; + } + if (value.conversionModeChanged) + { + settings.conversionMode = value.settings.conversionMode; + } + current.Internal_SetOverrideSampleSettings(targetGroup, settings); } - EditorGUI.EndDisabledGroup(); - } - else - { - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.Label("Unity failed to import this audio file. Try to reimport.", new GUILayoutOption[0]); - GUILayout.EndHorizontal(); } + this.m_SampleSettingOverrides[targetGroup] = value; } - else + } + } + this.m_DefaultSampleSettings.ClearChangedFlags(); + BuildPlayerWindow.BuildPlatform[] array3 = array; + for (int j = 0; j < array3.Length; j++) + { + BuildPlayerWindow.BuildPlatform buildPlatform2 = array3[j]; + BuildTargetGroup targetGroup2 = buildPlatform2.targetGroup; + if (this.m_SampleSettingOverrides.ContainsKey(targetGroup2)) + { + AudioImporterInspector.SampleSettingProperties value2 = this.m_SampleSettingOverrides[targetGroup2]; + value2.ClearChangedFlags(); + this.m_SampleSettingOverrides[targetGroup2] = value2; + } + } + return true; + } + private bool ResetSettingsFromBackend() + { + if (this.GetAllAudioImporterTargets().Any()) + { + AudioImporter audioImporter = this.GetAllAudioImporterTargets().First(); + this.m_DefaultSampleSettings.settings = audioImporter.defaultSampleSettings; + this.m_DefaultSampleSettings.ClearChangedFlags(); + this.m_SampleSettingOverrides = new Dictionary(); + List validPlatforms = BuildPlayerWindow.GetValidPlatforms(); + foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) + { + BuildTargetGroup targetGroup = current.targetGroup; + foreach (AudioImporter current2 in this.GetAllAudioImporterTargets()) { - GUI.enabled = (this.m_type != AudioType.MPEG && this.m_type != AudioType.OGGVORBIS && this.m_iscompressible); - AudioImporterInspector.formatLabels[0] = "Native (" + this.m_type + ")"; - AudioImporterInspector.formatLabels[1] = "Compressed (" + this.m_compressedType + ")"; - int num3 = EditorGUILayout.Popup("Audio Format", (int)(this.m_format + 1), AudioImporterInspector.formatLabels, new GUILayoutOption[0]); - this.m_format = (AudioImporterFormat)(num3 - 1); - GUI.enabled = true; - this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); - if (this.m_format == AudioImporterFormat.Compressed) + if (current2.Internal_ContainsSampleSettingsOverride(targetGroup)) { - string[] displayedOptions2 = new string[] - { - "Decompress on load", - "Compressed in memory", - "Stream from disc" - }; - this.m_loadType = (AudioImporterLoadType)EditorGUILayout.Popup("Load type", (int)this.m_loadType, displayedOptions2, new GUILayoutOption[0]); - } - else - { - string[] displayedOptions2 = new string[] - { - "Load into memory", - "Stream from disc" - }; - int num4 = Mathf.Clamp(this.m_loadType - AudioImporterLoadType.CompressedInMemory, 0, 1); - EditorGUI.BeginChangeCheck(); - num4 = EditorGUILayout.Popup("Load type", num4, displayedOptions2, new GUILayoutOption[0]); - if (EditorGUI.EndChangeCheck()) - { - this.m_loadType = num4 + AudioImporterLoadType.CompressedInMemory; - } - } - GUI.enabled = (this.m_iscompressible && (this.m_compressedType == AudioType.MPEG || this.m_compressedType == AudioType.XMA || this.m_compressedType == AudioType.VAG) && this.m_format == AudioImporterFormat.Compressed); - this.m_Loopable = EditorGUILayout.Toggle(new GUIContent("Looping", "Encode file for looping"), this.m_Loopable, new GUILayoutOption[0]); - GUI.enabled = true; - if (this.m_durationMS == 0) - { - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.Label("Unity failed to import this audio file. Try to reimport.", new GUILayoutOption[0]); - GUILayout.EndHorizontal(); + AudioImporterInspector.SampleSettingProperties value = default(AudioImporterInspector.SampleSettingProperties); + value.settings = current2.Internal_GetOverrideSampleSettings(targetGroup); + this.m_SampleSettingOverrides[targetGroup] = value; + break; } } + if (!this.m_SampleSettingOverrides.ContainsKey(targetGroup)) + { + AudioImporterInspector.SampleSettingProperties value2 = default(AudioImporterInspector.SampleSettingProperties); + value2.settings = audioImporter.Internal_GetOverrideSampleSettings(targetGroup); + this.m_SampleSettingOverrides[targetGroup] = value2; + } } - else + } + return true; + } + public bool CurrentPlatformHasAutoTranslatedCompression() + { + BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); + foreach (AudioImporter current in this.GetAllAudioImporterTargets()) + { + AudioCompressionFormat compressionFormat = current.defaultSampleSettings.compressionFormat; + if (!current.Internal_ContainsSampleSettingsOverride(buildTargetGroup)) { - this.m_3D = EditorGUILayout.Toggle("3D Sound", this.m_3D, new GUILayoutOption[0]); + AudioCompressionFormat compressionFormat2 = current.Internal_GetOverrideSampleSettings(buildTargetGroup).compressionFormat; + if (compressionFormat != compressionFormat2) + { + return true; + } } } - GUI.enabled = true; - GUI.changed = false; - base.ApplyRevertGUI(); - if (GUI.changed) + return false; + } + public bool IsHardwareSound(AudioCompressionFormat format) + { + return format == AudioCompressionFormat.VAG || format == AudioCompressionFormat.HEVAG; + } + public bool CurrentSelectionContainsHardwareSounds() + { + BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget); + foreach (AudioImporter current in this.GetAllAudioImporterTargets()) + { + if (this.IsHardwareSound(current.Internal_GetOverrideSampleSettings(buildTargetGroup).compressionFormat)) + { + return true; + } + } + return false; + } + public void OnEnable() + { + this.m_ForceToMono = base.serializedObject.FindProperty("m_ForceToMono"); + this.m_PreloadAudioData = base.serializedObject.FindProperty("m_PreloadAudioData"); + this.m_LoadInBackground = base.serializedObject.FindProperty("m_LoadInBackground"); + this.m_OrigSize = base.serializedObject.FindProperty("m_PreviewData.m_OrigSize"); + this.m_CompSize = base.serializedObject.FindProperty("m_PreviewData.m_CompSize"); + this.ResetSettingsFromBackend(); + } + internal override void ResetValues() + { + base.ResetValues(); + this.ResetSettingsFromBackend(); + } + public override void OnInspectorGUI() + { + base.serializedObject.UpdateIfDirtyOrScript(); + bool selectionContainsTrackerFile = false; + foreach (AudioImporter current in this.GetAllAudioImporterTargets()) + { + string assetPath = current.assetPath; + string a = FileUtil.GetPathExtension(assetPath).ToLowerInvariant(); + if (a == "mod" || a == "it" || a == "s3m" || a == "xm") + { + selectionContainsTrackerFile = true; + break; + } + } + this.OnAudioImporterGUI(selectionContainsTrackerFile); + int num = 0; + int num2 = 0; + foreach (AudioImporter current2 in this.GetAllAudioImporterTargets()) + { + num += current2.origSize; + num2 += current2.compSize; + } + GUILayout.Space(10f); + EditorGUILayout.HelpBox(string.Concat(new object[] + { + "Original Size: \t", + num, + " bytes\nImported Size: \t", + num2, + " bytes\nRatio: \t\t", + (100f * (float)num2 / (float)num).ToString("#.00"), + "%" + }), MessageType.Info); + if (this.CurrentPlatformHasAutoTranslatedCompression()) + { + GUILayout.Space(10f); + EditorGUILayout.HelpBox("The selection contains different compression formats to the default settings for the current build platform.", MessageType.Info); + } + if (this.CurrentSelectionContainsHardwareSounds()) { - GUIUtility.ExitGUI(); + GUILayout.Space(10f); + EditorGUILayout.HelpBox("The selection contains sounds that are decompressed in hardware. Advanced mixing is not available for these sounds.", MessageType.Info); } + base.ApplyRevertGUI(); } - private int GetBitRateGUI(AudioImporter importer) + private AudioImporterInspector.MultiValueStatus GetMultiValueStatus(BuildTargetGroup platform) { - int num = (this.m_compressionBitrate >= 0) ? (this.m_compressionBitrate / 1000) : (importer.defaultBitrate / 1000); - int result = EditorGUILayout.IntSlider("Compression (kbps)", num, this.m_minbitrate, this.m_maxbitrate, new GUILayoutOption[0]); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - if (this.m_format == AudioImporterFormat.Compressed) + AudioImporterInspector.MultiValueStatus result; + result.multiLoadType = false; + result.multiSampleRateSetting = false; + result.multiSampleRateOverride = false; + result.multiCompressionFormat = false; + result.multiQuality = false; + result.multiConversionMode = false; + if (this.GetAllAudioImporterTargets().Any()) { - float num2 = (float)this.m_durationMS / 1000f; - int bytes = (int)(num2 * ((float)num * 1000f / 4f)); - GUILayout.Label(string.Format("New file size : {0:000}", EditorUtility.FormatBytes(bytes)), new GUILayoutOption[0]); + AudioImporter audioImporter = this.GetAllAudioImporterTargets().First(); + AudioImporterSampleSettings audioImporterSampleSettings; + if (platform == BuildTargetGroup.Unknown) + { + audioImporterSampleSettings = audioImporter.defaultSampleSettings; + } + else + { + audioImporterSampleSettings = audioImporter.Internal_GetOverrideSampleSettings(platform); + } + foreach (AudioImporter current in this.GetAllAudioImporterTargets().Except(new AudioImporter[] + { + audioImporter + })) + { + AudioImporterSampleSettings audioImporterSampleSettings2; + if (platform == BuildTargetGroup.Unknown) + { + audioImporterSampleSettings2 = current.defaultSampleSettings; + } + else + { + audioImporterSampleSettings2 = current.Internal_GetOverrideSampleSettings(platform); + } + result.multiLoadType |= (audioImporterSampleSettings.loadType != audioImporterSampleSettings2.loadType); + result.multiSampleRateSetting |= (audioImporterSampleSettings.sampleRateSetting != audioImporterSampleSettings2.sampleRateSetting); + result.multiSampleRateOverride |= (audioImporterSampleSettings.sampleRateOverride != audioImporterSampleSettings2.sampleRateOverride); + result.multiCompressionFormat |= (audioImporterSampleSettings.compressionFormat != audioImporterSampleSettings2.compressionFormat); + result.multiQuality |= (audioImporterSampleSettings.quality != audioImporterSampleSettings2.quality); + result.multiConversionMode |= (audioImporterSampleSettings.conversionMode != audioImporterSampleSettings2.conversionMode); + } } - GUILayout.EndHorizontal(); return result; } - private int GetQualityGUI() + private AudioImporterInspector.OverrideStatus GetOverrideStatus(BuildTargetGroup platform) + { + bool flag = false; + bool flag2 = false; + if (this.GetAllAudioImporterTargets().Any()) + { + AudioImporter audioImporter = this.GetAllAudioImporterTargets().First(); + flag2 = audioImporter.Internal_ContainsSampleSettingsOverride(platform); + foreach (AudioImporter current in this.GetAllAudioImporterTargets().Except(new AudioImporter[] + { + audioImporter + })) + { + bool flag3 = current.Internal_ContainsSampleSettingsOverride(platform); + if (flag3 != flag2) + { + flag |= true; + } + flag2 |= flag3; + } + } + if (!flag2) + { + return AudioImporterInspector.OverrideStatus.NoOverrides; + } + if (flag) + { + return AudioImporterInspector.OverrideStatus.MixedOverrides; + } + return AudioImporterInspector.OverrideStatus.AllOverrides; + } + private AudioCompressionFormat[] GetFormatsForPlatform(BuildTargetGroup platform) + { + List list = new List(); + if (platform == BuildTargetGroup.WebGL) + { + list.Add(AudioCompressionFormat.MP3); + return list.ToArray(); + } + list.Add(AudioCompressionFormat.PCM); + if (platform != BuildTargetGroup.PS3 && platform != BuildTargetGroup.PSM && platform != BuildTargetGroup.PSP2) + { + list.Add(AudioCompressionFormat.Vorbis); + } + list.Add(AudioCompressionFormat.ADPCM); + if (platform != BuildTargetGroup.Standalone && platform != BuildTargetGroup.WebPlayer && platform != BuildTargetGroup.Unknown) + { + list.Add(AudioCompressionFormat.MP3); + } + if (platform == BuildTargetGroup.PSM) + { + list.Add(AudioCompressionFormat.VAG); + } + if (platform == BuildTargetGroup.PSP2) + { + list.Add(AudioCompressionFormat.HEVAG); + } + return list.ToArray(); + } + private bool CompressionFormatHasQuality(AudioCompressionFormat format) + { + switch (format) + { + case AudioCompressionFormat.Vorbis: + case AudioCompressionFormat.MP3: + return true; + } + return false; + } + private void OnSampleSettingGUI(BuildTargetGroup platform, AudioImporterInspector.MultiValueStatus status, bool selectionContainsTrackerFile, ref AudioImporterInspector.SampleSettingProperties properties) + { + EditorGUI.showMixedValue = (status.multiLoadType && !properties.loadTypeChanged); + EditorGUI.BeginChangeCheck(); + AudioClipLoadType loadType = (AudioClipLoadType)EditorGUILayout.EnumPopup("Load Type", properties.settings.loadType, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + properties.settings.loadType = loadType; + properties.loadTypeChanged = true; + } + if (!selectionContainsTrackerFile) + { + AudioCompressionFormat[] formatsForPlatform = this.GetFormatsForPlatform(platform); + EditorGUI.showMixedValue = (status.multiCompressionFormat && !properties.compressionFormatChanged); + EditorGUI.BeginChangeCheck(); + AudioCompressionFormat compressionFormat = (AudioCompressionFormat)EditorGUILayout.IntPopup("Compression Format", (int)properties.settings.compressionFormat, Array.ConvertAll(formatsForPlatform, (AudioCompressionFormat value) => value.ToString()), Array.ConvertAll(formatsForPlatform, (AudioCompressionFormat value) => (int)value), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + properties.settings.compressionFormat = compressionFormat; + properties.compressionFormatChanged = true; + } + if (this.CompressionFormatHasQuality(properties.settings.compressionFormat)) + { + EditorGUI.showMixedValue = (status.multiQuality && !properties.qualityChanged); + EditorGUI.BeginChangeCheck(); + int num = EditorGUILayout.IntSlider("Quality", (int)Mathf.Clamp(properties.settings.quality * 100f, 1f, 100f), 1, 100, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + properties.settings.quality = 0.01f * (float)num; + properties.qualityChanged = true; + } + } + EditorGUI.showMixedValue = (status.multiSampleRateSetting && !properties.sampleRateSettingChanged); + EditorGUI.BeginChangeCheck(); + AudioSampleRateSetting sampleRateSetting = (AudioSampleRateSetting)EditorGUILayout.EnumPopup("Sample Rate Setting", properties.settings.sampleRateSetting, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + properties.settings.sampleRateSetting = sampleRateSetting; + properties.sampleRateSettingChanged = true; + } + if (properties.settings.sampleRateSetting == AudioSampleRateSetting.OverrideSampleRate) + { + EditorGUI.showMixedValue = (status.multiSampleRateOverride && !properties.sampleRateOverrideChanged); + EditorGUI.BeginChangeCheck(); + int sampleRateOverride = EditorGUILayout.IntPopup("Sample Rate", (int)properties.settings.sampleRateOverride, AudioImporterInspector.Styles.kSampleRateStrings, AudioImporterInspector.Styles.kSampleRateValues, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + properties.settings.sampleRateOverride = (uint)sampleRateOverride; + properties.sampleRateOverrideChanged = true; + } + } + EditorGUI.showMixedValue = false; + } + } + private void OnAudioImporterGUI(bool selectionContainsTrackerFile) + { + if (!selectionContainsTrackerFile) + { + EditorGUILayout.PropertyField(this.m_ForceToMono, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LoadInBackground, new GUILayoutOption[0]); + } + EditorGUILayout.PropertyField(this.m_PreloadAudioData, new GUILayoutOption[0]); + GUILayout.Space(10f); + BuildPlayerWindow.BuildPlatform[] array = BuildPlayerWindow.GetValidPlatforms().ToArray(); + int num = EditorGUILayout.BeginPlatformGrouping(array, GUIContent.Temp("Default")); + if (num == -1) + { + AudioImporterInspector.MultiValueStatus multiValueStatus = this.GetMultiValueStatus(BuildTargetGroup.Unknown); + this.OnSampleSettingGUI(BuildTargetGroup.Unknown, multiValueStatus, selectionContainsTrackerFile, ref this.m_DefaultSampleSettings); + } + else + { + BuildTargetGroup targetGroup = array[num].targetGroup; + AudioImporterInspector.SampleSettingProperties value = this.m_SampleSettingOverrides[targetGroup]; + AudioImporterInspector.OverrideStatus overrideStatus = this.GetOverrideStatus(targetGroup); + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = (overrideStatus == AudioImporterInspector.OverrideStatus.MixedOverrides && !value.overrideIsForced); + bool flag = (value.overrideIsForced && value.forcedOverrideState) || (!value.overrideIsForced && overrideStatus != AudioImporterInspector.OverrideStatus.NoOverrides); + flag = EditorGUILayout.Toggle("Override for " + array[num].name, flag, new GUILayoutOption[0]); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + value.forcedOverrideState = flag; + value.overrideIsForced = true; + } + AudioImporterInspector.MultiValueStatus multiValueStatus2 = this.GetMultiValueStatus(targetGroup); + bool disabled = (!value.overrideIsForced || !value.forcedOverrideState) && overrideStatus != AudioImporterInspector.OverrideStatus.AllOverrides; + EditorGUI.BeginDisabledGroup(disabled); + this.OnSampleSettingGUI(targetGroup, multiValueStatus2, selectionContainsTrackerFile, ref value); + EditorGUI.EndDisabledGroup(); + this.m_SampleSettingOverrides[targetGroup] = value; + } + EditorGUILayout.EndPlatformGrouping(); + } + internal override bool HasModified() + { + if (base.HasModified()) + { + return true; + } + if (this.m_DefaultSampleSettings.HasModified()) + { + return true; + } + Dictionary.ValueCollection values = this.m_SampleSettingOverrides.Values; + foreach (AudioImporterInspector.SampleSettingProperties current in values) + { + if (current.HasModified()) + { + return true; + } + } + return false; + } + internal override void Apply() { - float num = (this.m_compressionBitrate >= 0) ? (((float)this.m_compressionBitrate / 1000f - 56f) / 2f) : 50f; - int value = (int)Math.Round((double)num); - return EditorGUILayout.IntSlider("XMA Quality (1-100)", value, 1, 100, new GUILayoutOption[0]); + base.Apply(); + this.SyncSettingsToBackend(); } } } diff --git a/UnityEditor/UnityEditor/AudioImporterLoadType.cs b/UnityEditor/UnityEditor/AudioImporterLoadType.cs index f89ed361..c4011db7 100644 --- a/UnityEditor/UnityEditor/AudioImporterLoadType.cs +++ b/UnityEditor/UnityEditor/AudioImporterLoadType.cs @@ -1,10 +1,12 @@ using System; +using System.ComponentModel; namespace UnityEditor { + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("UnityEditor.AudioImporterLoadType has been deprecated. Use UnityEngine.AudioClipLoadType instead (UnityUpgradable).", true)] public enum AudioImporterLoadType { - DecompressOnLoad, - CompressedInMemory, - StreamFromDisc + DecompressOnLoad = -1, + CompressedInMemory = -1, + StreamFromDisc = -1 } } diff --git a/UnityEditor/UnityEditor/AudioImporterSampleSettings.cs b/UnityEditor/UnityEditor/AudioImporterSampleSettings.cs new file mode 100644 index 00000000..122bf659 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioImporterSampleSettings.cs @@ -0,0 +1,14 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public struct AudioImporterSampleSettings + { + public AudioClipLoadType loadType; + public AudioSampleRateSetting sampleRateSetting; + public uint sampleRateOverride; + public AudioCompressionFormat compressionFormat; + public float quality; + public int conversionMode; + } +} diff --git a/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs b/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs index 31ced499..9c43bcb5 100644 --- a/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs +++ b/UnityEditor/UnityEditor/AudioLowPassFilterInspector.cs @@ -25,7 +25,7 @@ public override void OnInspectorGUI() } base.serializedObject.Update(); EditorGUI.BeginChangeCheck(); - AudioSourceInspector.AnimProp(new GUIContent("Cutoff Frequency"), this.m_LowpassLevelCustomCurve, 22000f, 0f); + AudioSourceInspector.AnimProp(new GUIContent("Cutoff Frequency"), this.m_LowpassLevelCustomCurve, 22000f, 0f, true); if (EditorGUI.EndChangeCheck()) { AnimationCurve animationCurveValue = this.m_LowpassLevelCustomCurve.animationCurveValue; diff --git a/UnityEditor/UnityEditor/AudioMixerChannelStripView.cs b/UnityEditor/UnityEditor/AudioMixerChannelStripView.cs new file mode 100644 index 00000000..d8f90b68 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerChannelStripView.cs @@ -0,0 +1,1555 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerChannelStripView + { + [Serializable] + public class State + { + public int m_LastClickedInstanceID; + public Vector2 m_ScrollPos = new Vector2(0f, 0f); + } + public class EffectContext + { + public AudioMixerController controller; + public AudioMixerGroupController group; + public int index; + public string name; + public EffectContext(AudioMixerController controller, AudioMixerGroupController group, int index, string name) + { + this.controller = controller; + this.group = group; + this.index = index; + this.name = name; + } + } + public class ConnectSendContext + { + public AudioMixerEffectController sendEffect; + public AudioMixerEffectController targetEffect; + public ConnectSendContext(AudioMixerEffectController sendEffect, AudioMixerEffectController targetEffect) + { + this.sendEffect = sendEffect; + this.targetEffect = targetEffect; + } + } + private class PatchSlot + { + public AudioMixerGroupController group; + public float x; + public float y; + } + private class BusConnection + { + public AudioMixerEffectController targetEffect; + public float srcX; + public float srcY; + public float mixLevel; + public Color color; + public bool isSend; + public bool isSelected; + public BusConnection(float srcX, float srcY, AudioMixerEffectController targetEffect, float mixLevel, Color col, bool isSend, bool isSelected) + { + this.srcX = srcX; + this.srcY = srcY; + this.targetEffect = targetEffect; + this.mixLevel = mixLevel; + this.color = col; + this.isSend = isSend; + this.isSelected = isSelected; + } + } + private class ChannelStripParams + { + private const float kAddEffectButtonHeight = 16f; + public int index; + public Rect stripRect; + public Rect visibleRect; + public bool visible; + public AudioMixerGroupController group; + public int maxEffects; + public bool drawingBuses; + public bool anySoloActive; + public List busConnections = new List(); + public List rectSelectionGroups = new List(); + public List allGroups; + public List shownGroups; + public int numChannels; + public float[] vuinfo_level = new float[9]; + public float[] vuinfo_peak = new float[9]; + public Dictionary effectMap; + public List bgRects; + public readonly int kHeaderIndex; + public readonly int kVUMeterFaderIndex = 1; + public readonly int kTotalVULevelIndex = 2; + public readonly int kSoloMuteBypassIndex = 3; + public readonly int kEffectStartIndex = 4; + public void Init(AudioMixerController controller, Rect channelStripRect, int maxNumEffects) + { + this.numChannels = controller.GetGroupVUInfo(this.group.groupID, false, ref this.vuinfo_level, ref this.vuinfo_peak); + this.maxEffects = maxNumEffects; + this.bgRects = this.GetBackgroundRects(channelStripRect, this.group, this.maxEffects); + this.stripRect = channelStripRect; + this.stripRect.yMax = this.bgRects[this.bgRects.Count - 1].yMax; + } + private List GetBackgroundRects(Rect r, AudioMixerGroupController group, int maxNumGroups) + { + List list = new List(); + list.AddRange(Enumerable.Repeat(0f, this.kEffectStartIndex)); + list[this.kHeaderIndex] = 22f; + list[this.kVUMeterFaderIndex] = 170f; + list[this.kTotalVULevelIndex] = 17f; + list[this.kSoloMuteBypassIndex] = 30f; + for (int i = 0; i < maxNumGroups; i++) + { + list.Add(16f); + } + list.Add(10f); + List list2 = new List(); + float num = r.y; + using (List.Enumerator enumerator = list.GetEnumerator()) + { + while (enumerator.MoveNext()) + { + int num2 = (int)enumerator.Current; + if (list2.Count > 0) + { + num = num; + } + list2.Add(new Rect(r.x, num, r.width, (float)num2)); + num += (float)num2; + } + } + num += 10f; + list2.Add(new Rect(r.x, num, r.width, 16f)); + return list2; + } + } + private const float k_MinVULevel = -80f; + private const float headerHeight = 22f; + private const float vuHeight = 170f; + private const float dbHeight = 17f; + private const float soloMuteBypassHeight = 30f; + private const float effectHeight = 16f; + private const float spaceBetween = 0f; + private const int channelStripSpacing = 4; + private const float channelStripBaseWidth = 90f; + private const float spaceBetweenMainGroupsAndReferenced = 50f; + private const float kGridTileWidth = 12f; + public static float kVolumeScaleMouseDrag = 1f; + public static float kEffectScaleMouseDrag = 0.3f; + private static Color kMoveColorHighlight = new Color(0.3f, 0.6f, 1f, 0.4f); + private static Color kMoveSlotColHiAllowed = new Color(1f, 1f, 1f, 0.7f); + private static Color kMoveSlotColLoAllowed = new Color(1f, 1f, 1f, 0f); + private static Color kMoveSlotColBorderAllowed = new Color(1f, 1f, 1f, 1f); + private static Color kMoveSlotColHiDisallowed = new Color(1f, 0f, 0f, 0.7f); + private static Color kMoveSlotColLoDisallowed = new Color(0.8f, 0f, 0f, 0f); + private static Color kMoveSlotColBorderDisallowed = new Color(1f, 0f, 0f, 1f); + private static int kRectSelectionHashCode = "RectSelection".GetHashCode(); + private static int kEffectDraggingHashCode = "EffectDragging".GetHashCode(); + private static int kVerticalFaderHash = "VerticalFader".GetHashCode(); + public int m_FocusIndex = -1; + public int m_IndexCounter; + public int m_EffectInteractionControlID; + public int m_RectSelectionControlID; + public float m_MouseDragStartX; + public float m_MouseDragStartY; + public float m_MouseDragStartValue; + public Vector2 m_RectSelectionStartPos = new Vector2(0f, 0f); + public Rect m_RectSelectionRect = new Rect(0f, 0f, 0f, 0f); + private AudioMixerChannelStripView.State m_State; + private AudioMixerController m_Controller; + private MixerGroupControllerCompareByName m_GroupComparer = new MixerGroupControllerCompareByName(); + private bool m_WaitingForDragEvent; + private int m_ChangingWetMixIndex = -1; + private int m_MovingEffectSrcIndex = -1; + private int m_MovingEffectDstIndex = -1; + private Rect m_MovingSrcRect = new Rect(-1f, -1f, 0f, 0f); + private Rect m_MovingDstRect = new Rect(-1f, -1f, 0f, 0f); + private bool m_MovingEffectAllowed; + private AudioMixerGroupController m_MovingSrcGroup; + private AudioMixerGroupController m_MovingDstGroup; + private List m_LastNumChannels = new List(); + private bool m_RequiresRepaint; + private readonly Vector2 channelStripsOffset = new Vector2(15f, 10f); + private static Texture2D m_GridTexture; + private static readonly Color kGridColorDark = new Color(0f, 0f, 0f, 0.18f); + private static readonly Color kGridColorLight = new Color(0f, 0f, 0f, 0.1f); + private static Color hfaderCol1 = new Color(0.2f, 0.2f, 0.2f, 1f); + private static Color hfaderCol2 = new Color(0.4f, 0.4f, 0.4f, 1f); + public GUIStyle sharedGuiStyle = new GUIStyle(); + private GUIContent bypassButtonContent = new GUIContent(string.Empty, "Toggle bypass on this effect"); + private GUIContent headerGUIContent = new GUIContent(); + private GUIContent addText = new GUIContent("Add.."); + [NonSerialized] + private int FrameCounter; + [NonSerialized] + private GUIStyle developerInfoStyle = AudioMixerDrawUtils.BuildGUIStyleForLabel(new Color(1f, 0f, 0f, 0.5f), 20, false, FontStyle.Bold, TextAnchor.MiddleLeft); + [NonSerialized] + private Vector3[] cablepoints = new Vector3[20]; + public bool requiresRepaint + { + get + { + if (this.m_RequiresRepaint) + { + this.m_RequiresRepaint = false; + return true; + } + return false; + } + } + private static Color gridColor + { + get + { + if (EditorGUIUtility.isProSkin) + { + return AudioMixerChannelStripView.kGridColorDark; + } + return AudioMixerChannelStripView.kGridColorLight; + } + } + private AudioMixerDrawUtils.Styles styles + { + get + { + return AudioMixerDrawUtils.styles; + } + } + private Texture2D gridTextureTilable + { + get + { + if (AudioMixerChannelStripView.m_GridTexture == null) + { + AudioMixerChannelStripView.m_GridTexture = AudioMixerChannelStripView.CreateTilableGridTexture(12, 12, new Color(0f, 0f, 0f, 0f), AudioMixerChannelStripView.gridColor); + } + return AudioMixerChannelStripView.m_GridTexture; + } + } + public AudioMixerChannelStripView(AudioMixerChannelStripView.State state) + { + this.m_State = state; + } + private static Texture2D CreateTilableGridTexture(int width, int height, Color backgroundColor, Color lineColor) + { + Color[] array = new Color[width * height]; + for (int i = 0; i < height * width; i++) + { + array[i] = backgroundColor; + } + for (int j = 0; j < height; j++) + { + array[j * width + (width - 1)] = lineColor; + } + for (int k = 0; k < width; k++) + { + array[(height - 1) * width + k] = lineColor; + } + Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, false); + texture2D.hideFlags = HideFlags.HideAndDontSave; + texture2D.SetPixels(array); + texture2D.Apply(); + return texture2D; + } + private void DrawAreaBackground(Rect rect) + { + if (Event.current.type == EventType.Repaint) + { + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, (!EditorGUIUtility.isProSkin) ? 0.2f : 0.6f); + AudioMixerDrawUtils.styles.channelStripAreaBackground.Draw(rect, false, false, false, false); + GUI.color = color; + } + } + private void SetFocus() + { + this.m_FocusIndex = this.m_IndexCounter; + } + private void ClearFocus() + { + this.m_FocusIndex = -1; + } + private bool HasFocus() + { + return this.m_FocusIndex == this.m_IndexCounter; + } + private bool IsFocusActive() + { + return this.m_FocusIndex != -1; + } + public static void InsertEffectPopupCallback(object obj) + { + AudioMixerChannelStripView.EffectContext effectContext = (AudioMixerChannelStripView.EffectContext)obj; + Undo.RecordObject(effectContext.group, "Add effect"); + AudioMixerEffectController audioMixerEffectController = new AudioMixerEffectController(effectContext.name); + effectContext.group.InsertEffect(audioMixerEffectController, effectContext.index); + AssetDatabase.AddObjectToAsset(audioMixerEffectController, effectContext.controller); + audioMixerEffectController.PreallocateGUIDs(); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + public void RemoveEffectPopupCallback(object obj) + { + AudioMixerChannelStripView.EffectContext effectContext = (AudioMixerChannelStripView.EffectContext)obj; + AudioMixerEffectController audioMixerEffectController = effectContext.group.effects[effectContext.index]; + effectContext.controller.ClearSendConnectionsTo(audioMixerEffectController); + effectContext.controller.RemoveEffect(audioMixerEffectController, effectContext.group); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + public static void ConnectSendPopupCallback(object obj) + { + AudioMixerChannelStripView.ConnectSendContext connectSendContext = (AudioMixerChannelStripView.ConnectSendContext)obj; + Undo.RecordObject(connectSendContext.sendEffect, "Change Send Target"); + connectSendContext.sendEffect.sendTarget = connectSendContext.targetEffect; + } + private bool ClipRect(Rect r, Rect clipRect, ref Rect overlap) + { + overlap.x = Mathf.Max(r.x, clipRect.x); + overlap.y = Mathf.Max(r.y, clipRect.y); + overlap.width = Mathf.Min(r.x + r.width, clipRect.x + clipRect.width) - overlap.x; + overlap.height = Mathf.Min(r.y + r.height, clipRect.y + clipRect.height) - overlap.y; + return overlap.width > 0f && overlap.height > 0f; + } + public float VerticalFader(Rect r, float value, int direction, float dragScale, bool drawScaleValues, bool drawMarkerValue, string tooltip, float maxValue, GUIStyle style) + { + Event current = Event.current; + int num = (int)style.fixedHeight; + int num2 = (int)r.height - num; + float num3 = AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(value, AudioMixerController.kMinVolume, maxValue), (float)num2, true); + Rect rect = new Rect(r.x, r.y + (float)((int)num3), r.width, (float)num); + int controlID = GUIUtility.GetControlID(AudioMixerChannelStripView.kVerticalFaderHash, FocusType.Passive); + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (r.Contains(current.mousePosition) && GUIUtility.hotControl == 0) + { + this.m_MouseDragStartY = current.mousePosition.y; + this.m_MouseDragStartValue = num3; + GUIUtility.hotControl = controlID; + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + num3 = Mathf.Clamp(this.m_MouseDragStartValue + dragScale * (current.mousePosition.y - this.m_MouseDragStartY), 0f, (float)num2); + value = Mathf.Clamp(AudioMixerController.VolumeToScreenMapping(num3, (float)num2, false), AudioMixerController.kMinVolume, maxValue); + current.Use(); + } + break; + case EventType.Repaint: + if (drawScaleValues) + { + float num4 = r.y + (float)num / 2f; + float num5 = maxValue; + EditorGUI.BeginDisabledGroup(true); + while (num5 >= AudioMixerController.kMinVolume) + { + float num6 = AudioMixerController.VolumeToScreenMapping(num5, (float)num2, true); + if (num5 / 10f % 2f == 0f) + { + GUI.Label(new Rect(r.x, num4 + num6 - 7f, r.width, 14f), GUIContent.Temp(Mathf.RoundToInt(num5).ToString()), this.styles.vuValue); + } + EditorGUI.DrawRect(new Rect(r.x, num4 + num6 - 1f, 5f, 1f), new Color(0f, 0f, 0f, 0.5f)); + num5 -= 10f; + } + EditorGUI.EndDisabledGroup(); + } + if (drawMarkerValue) + { + style.Draw(rect, GUIContent.Temp(Mathf.RoundToInt(value).ToString()), false, false, false, false); + } + else + { + style.Draw(rect, false, false, false, false); + } + AudioMixerDrawUtils.AddTooltipOverlay(rect, tooltip); + break; + } + return value; + } + public float HorizontalFader(Rect r, float value, float minValue, float maxValue, int direction, float dragScale) + { + this.m_IndexCounter++; + Rect r2 = new Rect(r); + float num = r.width * 0.2f; + float num2 = r2.width - num; + AudioMixerDrawUtils.DrawGradientRect(r2, AudioMixerChannelStripView.hfaderCol1, AudioMixerChannelStripView.hfaderCol2); + Event current = Event.current; + if (current.type == EventType.MouseDown && r2.Contains(current.mousePosition)) + { + this.m_MouseDragStartX = current.mousePosition.x; + this.m_MouseDragStartValue = value; + this.SetFocus(); + } + if (this.HasFocus()) + { + if (current.type == EventType.MouseDrag) + { + value = this.m_MouseDragStartValue + dragScale * (maxValue - minValue) * (current.mousePosition.x - this.m_MouseDragStartX) / num2; + Event.current.Use(); + } + else + { + if (current.type == EventType.MouseUp) + { + this.ClearFocus(); + Event.current.Use(); + } + } + } + value = Mathf.Clamp(value, minValue, maxValue); + r2.x = r.x; + r2.width = r.width; + r2.x = r.x + num2 * ((value - minValue) / (maxValue - minValue)); + r2.width = num; + AudioMixerDrawUtils.DrawGradientRect(r2, AudioMixerChannelStripView.hfaderCol2, AudioMixerChannelStripView.hfaderCol1); + return value; + } + public GUIStyle GetEffectBarStyle(AudioMixerEffectController effect) + { + if (effect.IsSend() || effect.IsReceive() || effect.IsDuckVolume()) + { + return this.styles.sendReturnBar; + } + if (effect.IsAttenuation()) + { + return this.styles.attenuationBar; + } + return this.styles.effectBar; + } + private void EffectSlot(Rect effectRect, AudioMixerSnapshotController snapshot, AudioMixerEffectController effect, int effectIndex, ref int highlightEffectIndex, AudioMixerChannelStripView.ChannelStripParams p, ref Dictionary patchslots) + { + if (effect == null) + { + return; + } + Rect rect = effectRect; + Event current = Event.current; + if (current.type == EventType.Repaint && patchslots != null && (effect.IsSend() || MixerEffectDefinitions.EffectCanBeSidechainTarget(effect))) + { + AudioMixerChannelStripView.PatchSlot patchSlot = new AudioMixerChannelStripView.PatchSlot(); + patchSlot.group = p.group; + patchSlot.x = rect.xMax - (rect.yMax - rect.yMin) * 0.5f; + patchSlot.y = (rect.yMin + rect.yMax) * 0.5f; + patchslots[effect] = patchSlot; + } + bool flag = !effect.DisallowsBypass(); + Rect position = rect; + position.width = 10f; + rect.xMin += 10f; + if (flag && GUI.Button(position, this.bypassButtonContent, GUIStyle.none)) + { + effect.bypass = !effect.bypass; + this.m_Controller.UpdateBypass(); + InspectorWindow.RepaintAllInspectors(); + } + this.m_IndexCounter++; + float num = (!(effect != null)) ? AudioMixerController.kMinVolume : Mathf.Clamp(effect.GetValueForMixLevel(this.m_Controller, snapshot), AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect); + bool flag2 = effect != null && ((effect.IsSend() && effect.sendTarget != null) || effect.enableWetMix); + if (current.type == EventType.Repaint) + { + GUIStyle effectBarStyle = this.GetEffectBarStyle(effect); + float num2 = (!flag2) ? 1f : ((num - AudioMixerController.kMinVolume) / (AudioMixerController.kMaxEffect - AudioMixerController.kMinVolume)); + bool flag3 = (!p.group.bypassEffects && (effect == null || !effect.bypass)) || (effect != null && effect.DisallowsBypass()); + Color color = (!(effect != null)) ? new Color(0f, 0f, 0f, 0.5f) : AudioMixerDrawUtils.GetEffectColor(effect); + if (!flag3) + { + color = new Color(color.r * 0.5f, color.g * 0.5f, color.b * 0.5f); + } + if (flag3) + { + if (num2 < 1f) + { + float num3 = rect.width * num2; + if (num3 < 4f) + { + num3 = Mathf.Max(num3, 2f); + float num4 = 1f - num3 / 4f; + Color color2 = GUI.color; + if (!GUI.enabled) + { + GUI.color = new Color(1f, 1f, 1f, 0.5f); + } + GUI.DrawTextureWithTexCoords(new Rect(rect.x, rect.y, num3, rect.height), effectBarStyle.focused.background, new Rect(num4, 0f, 1f - num4, 1f)); + GUI.color = color2; + } + else + { + effectBarStyle.Draw(new Rect(rect.x, rect.y, num3, rect.height), false, false, false, true); + } + GUI.DrawTexture(new Rect(rect.x + num3, rect.y, rect.width - num3, rect.height), effectBarStyle.onFocused.background, ScaleMode.StretchToFill); + } + else + { + effectBarStyle.Draw(rect, !flag2, false, false, flag2); + } + } + else + { + effectBarStyle.Draw(rect, false, false, false, false); + } + if (flag) + { + this.styles.circularToggle.Draw(new Rect(position.x + 2f, position.y + 5f, position.width - 2f, position.width - 2f), false, false, !effect.bypass, false); + } + if (effect.IsSend() && effect.sendTarget != null) + { + position.y -= 1f; + GUI.Label(position, this.styles.sendString, EditorStyles.miniLabel); + } + EditorGUI.BeginDisabledGroup(!flag3); + string effectSlotName = this.GetEffectSlotName(effect, flag2, snapshot, p); + string effectSlotTooltip = this.GetEffectSlotTooltip(effect, rect, p); + GUI.Label(new Rect(rect.x, rect.y, rect.width - 10f, rect.height), GUIContent.Temp(effectSlotName, effectSlotTooltip), this.styles.effectName); + EditorGUI.EndDisabledGroup(); + } + else + { + this.EffectSlotDragging(effectRect, snapshot, effect, flag2, num, effectIndex, ref highlightEffectIndex, p); + } + } + private string GetEffectSlotName(AudioMixerEffectController effect, bool showLevel, AudioMixerSnapshotController snapshot, AudioMixerChannelStripView.ChannelStripParams p) + { + if (this.m_ChangingWetMixIndex == this.m_IndexCounter && showLevel) + { + return string.Format("{0:F1} dB", effect.GetValueForMixLevel(this.m_Controller, snapshot)); + } + if (effect.IsSend() && effect.sendTarget != null) + { + return effect.GetSendTargetDisplayString(p.effectMap); + } + return effect.effectName; + } + private string GetEffectSlotTooltip(AudioMixerEffectController effect, Rect effectRect, AudioMixerChannelStripView.ChannelStripParams p) + { + if (!effectRect.Contains(Event.current.mousePosition)) + { + return string.Empty; + } + if (effect.IsSend()) + { + if (effect.sendTarget != null) + { + string sendTargetDisplayString = effect.GetSendTargetDisplayString(p.effectMap); + return "Send to: " + sendTargetDisplayString; + } + return this.styles.emptySendSlotGUIContent.tooltip; + } + else + { + if (effect.IsReceive()) + { + return this.styles.returnSlotGUIContent.tooltip; + } + if (effect.IsDuckVolume()) + { + return this.styles.duckVolumeSlotGUIContent.tooltip; + } + if (effect.IsAttenuation()) + { + return this.styles.attenuationSlotGUIContent.tooltip; + } + return this.styles.effectSlotGUIContent.tooltip; + } + } + private void EffectSlotDragging(Rect r, AudioMixerSnapshotController snapshot, AudioMixerEffectController effect, bool showLevel, float level, int effectIndex, ref int highlightEffectIndex, AudioMixerChannelStripView.ChannelStripParams p) + { + Event current = Event.current; + switch (current.GetTypeForControl(this.m_EffectInteractionControlID)) + { + case EventType.MouseDown: + if (r.Contains(current.mousePosition) && current.button == 0 && GUIUtility.hotControl == 0) + { + GUIUtility.hotControl = this.m_EffectInteractionControlID; + this.m_MouseDragStartX = current.mousePosition.x; + this.m_MouseDragStartValue = level; + highlightEffectIndex = effectIndex; + this.m_MovingEffectSrcIndex = -1; + this.m_MovingEffectDstIndex = -1; + this.m_WaitingForDragEvent = true; + this.m_MovingSrcRect = r; + this.m_MovingDstRect = r; + this.m_MovingSrcGroup = p.group; + this.m_MovingDstGroup = p.group; + this.m_MovingEffectAllowed = true; + this.SetFocus(); + Event.current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); + InspectorWindow.RepaintAllInspectors(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == this.m_EffectInteractionControlID && current.button == 0 && p.stripRect.Contains(current.mousePosition)) + { + if (this.m_MovingEffectDstIndex != -1 && this.m_MovingEffectAllowed) + { + if (this.IsDuplicateKeyPressed() && this.CanDuplicateDraggedEffect()) + { + AudioMixerEffectController sourceEffect = this.m_MovingSrcGroup.effects[this.m_MovingEffectSrcIndex]; + AudioMixerEffectController effect2 = this.m_MovingSrcGroup.controller.CopyEffect(sourceEffect); + List list = this.m_MovingDstGroup.effects.ToList(); + if (AudioMixerController.InsertEffect(effect2, ref list, this.m_MovingEffectDstIndex)) + { + this.m_MovingDstGroup.effects = list.ToArray(); + } + } + else + { + if (this.m_MovingSrcGroup == this.m_MovingDstGroup) + { + List list2 = this.m_MovingSrcGroup.effects.ToList(); + if (AudioMixerController.MoveEffect(ref list2, this.m_MovingEffectSrcIndex, ref list2, this.m_MovingEffectDstIndex)) + { + this.m_MovingSrcGroup.effects = list2.ToArray(); + } + } + else + { + if (!this.m_MovingSrcGroup.effects[this.m_MovingEffectSrcIndex].IsAttenuation()) + { + List list3 = this.m_MovingSrcGroup.effects.ToList(); + List list4 = this.m_MovingDstGroup.effects.ToList(); + if (AudioMixerController.MoveEffect(ref list3, this.m_MovingEffectSrcIndex, ref list4, this.m_MovingEffectDstIndex)) + { + this.m_MovingSrcGroup.effects = list3.ToArray(); + this.m_MovingDstGroup.effects = list4.ToArray(); + } + } + } + } + } + this.ClearEffectDragging(ref highlightEffectIndex); + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); + GUIUtility.ExitGUI(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == this.m_EffectInteractionControlID) + { + if (this.HasFocus() && this.m_WaitingForDragEvent) + { + this.m_ChangingWetMixIndex = -1; + if (effectIndex < p.group.effects.Length) + { + if (Mathf.Abs(current.delta.y) > Mathf.Abs(current.delta.x)) + { + this.m_MovingEffectSrcIndex = effectIndex; + this.ClearFocus(); + } + else + { + this.m_ChangingWetMixIndex = this.m_IndexCounter; + } + } + this.m_WaitingForDragEvent = false; + } + if (this.IsMovingEffect() && p.stripRect.Contains(current.mousePosition)) + { + float num = r.height * 0.5f; + float num2 = (effectIndex != 0) ? 0f : (-num); + float num3 = (effectIndex != p.group.effects.Length - 1) ? r.height : (r.height + num); + float num4 = current.mousePosition.y - r.y; + if (num4 >= num2 && num4 <= num3 && effectIndex < p.group.effects.Length) + { + int num5 = (num4 >= num) ? (effectIndex + 1) : effectIndex; + if (num5 != this.m_MovingEffectDstIndex || this.m_MovingDstGroup != p.group) + { + this.m_MovingDstRect.x = r.x; + this.m_MovingDstRect.width = r.width; + this.m_MovingDstRect.y = ((num4 >= num) ? (r.y + r.height) : r.y) - 1f; + this.m_MovingEffectDstIndex = num5; + this.m_MovingDstGroup = p.group; + this.m_MovingEffectAllowed = ((!this.m_MovingSrcGroup.effects[this.m_MovingEffectSrcIndex].IsAttenuation() || !(this.m_MovingSrcGroup != this.m_MovingDstGroup)) && !AudioMixerController.WillMovingEffectCauseFeedback(p.allGroups, this.m_MovingSrcGroup, this.m_MovingEffectSrcIndex, this.m_MovingDstGroup, num5, null) && (!this.IsDuplicateKeyPressed() || this.CanDuplicateDraggedEffect())); + } + current.Use(); + } + } + if (this.IsAdjustingWetMix() && this.HasFocus() && showLevel) + { + this.m_WaitingForDragEvent = false; + float value = AudioMixerChannelStripView.kEffectScaleMouseDrag * HandleUtility.niceMouseDelta + level; + float num6 = Mathf.Clamp(value, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect) - level; + if (num6 != 0f) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change effect level"); + if (effect.IsSend() && this.m_Controller.CachedSelection.Count > 1 && this.m_Controller.CachedSelection.Contains(p.group)) + { + List list5 = new List(); + foreach (AudioMixerGroupController current2 in this.m_Controller.CachedSelection) + { + AudioMixerEffectController[] effects = current2.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (audioMixerEffectController.effectName == effect.effectName && audioMixerEffectController.sendTarget == effect.sendTarget) + { + list5.Add(audioMixerEffectController); + } + } + } + foreach (AudioMixerEffectController current3 in list5) + { + if (!current3.IsSend() || current3.sendTarget != null) + { + current3.SetValueForMixLevel(this.m_Controller, snapshot, Mathf.Clamp(current3.GetValueForMixLevel(this.m_Controller, snapshot) + num6, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect)); + } + } + } + else + { + if (!effect.IsSend() || effect.sendTarget != null) + { + effect.SetValueForMixLevel(this.m_Controller, snapshot, Mathf.Clamp(level + num6, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect)); + } + } + InspectorWindow.RepaintAllInspectors(); + } + current.Use(); + } + } + break; + } + } + private void ClearEffectDragging(ref int highlightEffectIndex) + { + if (GUIUtility.hotControl == this.m_EffectInteractionControlID) + { + GUIUtility.hotControl = 0; + } + this.m_MovingEffectSrcIndex = -1; + this.m_MovingEffectDstIndex = -1; + this.m_MovingSrcRect = new Rect(-1f, -1f, 0f, 0f); + this.m_MovingDstRect = new Rect(-1f, -1f, 0f, 0f); + this.m_MovingSrcGroup = null; + this.m_MovingDstGroup = null; + this.m_ChangingWetMixIndex = -1; + highlightEffectIndex = -1; + this.ClearFocus(); + InspectorWindow.RepaintAllInspectors(); + } + private void UnhandledEffectDraggingEvents(ref int highlightEffectIndex) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(this.m_EffectInteractionControlID); + switch (typeForControl) + { + case EventType.MouseUp: + if (GUIUtility.hotControl == this.m_EffectInteractionControlID && current.button == 0) + { + this.ClearEffectDragging(ref highlightEffectIndex); + current.Use(); + } + return; + case EventType.MouseMove: + IL_29: + if (typeForControl != EventType.Repaint) + { + return; + } + if (this.IsMovingEffect() && current.type == EventType.Repaint) + { + EditorGUI.DrawRect(this.m_MovingSrcRect, AudioMixerChannelStripView.kMoveColorHighlight); + MouseCursor mouse = (!this.IsDuplicateKeyPressed() || !this.m_MovingEffectAllowed) ? MouseCursor.ResizeVertical : MouseCursor.ArrowPlus; + EditorGUIUtility.AddCursorRect(new Rect(current.mousePosition.x - 10f, current.mousePosition.y - 10f, 20f, 20f), mouse, this.m_EffectInteractionControlID); + } + if (this.m_MovingEffectDstIndex != -1 && this.m_MovingDstRect.y >= 0f) + { + float num = 2f; + Color color = (!this.m_MovingEffectAllowed) ? AudioMixerChannelStripView.kMoveSlotColLoDisallowed : AudioMixerChannelStripView.kMoveSlotColLoAllowed; + Color color2 = (!this.m_MovingEffectAllowed) ? AudioMixerChannelStripView.kMoveSlotColHiDisallowed : AudioMixerChannelStripView.kMoveSlotColHiAllowed; + Color color3 = (!this.m_MovingEffectAllowed) ? AudioMixerChannelStripView.kMoveSlotColBorderDisallowed : AudioMixerChannelStripView.kMoveSlotColBorderAllowed; + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingDstRect.x, this.m_MovingDstRect.y - num, this.m_MovingDstRect.width, num), color, color2); + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingDstRect.x, this.m_MovingDstRect.y, this.m_MovingDstRect.width, num), color2, color); + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingDstRect.x, this.m_MovingDstRect.y - 1f, this.m_MovingDstRect.width, 1f), color3, color3); + } + return; + case EventType.MouseDrag: + if (GUIUtility.hotControl == this.m_EffectInteractionControlID) + { + this.m_MovingEffectDstIndex = -1; + this.m_MovingDstRect = new Rect(-1f, -1f, 0f, 0f); + this.m_MovingDstGroup = null; + current.Use(); + } + return; + } + goto IL_29; + } + private bool IsDuplicateKeyPressed() + { + return Event.current.alt; + } + private bool CanDuplicateDraggedEffect() + { + return this.IsMovingEffect() && this.m_MovingSrcGroup != null && !this.m_MovingSrcGroup.effects[this.m_MovingEffectSrcIndex].IsAttenuation(); + } + private bool DoSoloButton(Rect r, AudioMixerGroupController group, List allGroups, List selection) + { + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && r.Contains(current.mousePosition)) + { + if (allGroups.Any((AudioMixerGroupController g) => g.solo)) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change solo state"); + foreach (AudioMixerGroupController current2 in allGroups) + { + current2.solo = false; + } + current.Use(); + return true; + } + } + bool flag = GUI.Toggle(r, group.solo, this.styles.soloGUIContent, AudioMixerDrawUtils.styles.soloToggle); + if (flag != group.solo) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change solo state"); + group.solo = !group.solo; + foreach (AudioMixerGroupController current3 in selection) + { + current3.solo = group.solo; + } + return true; + } + return false; + } + private bool DoMuteButton(Rect r, AudioMixerGroupController group, List allGroups, bool anySoloActive, List selection) + { + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && r.Contains(current.mousePosition)) + { + if (allGroups.Any((AudioMixerGroupController g) => g.mute)) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change mute state"); + if (allGroups.Any((AudioMixerGroupController g) => g.solo)) + { + return false; + } + foreach (AudioMixerGroupController current2 in allGroups) + { + current2.mute = false; + } + current.Use(); + return true; + } + } + Color color = GUI.color; + bool flag = anySoloActive && group.mute; + if (flag) + { + GUI.color = new Color(GUI.color.r, GUI.color.g, GUI.color.b, 0.5f); + } + bool flag2 = GUI.Toggle(r, group.mute, this.styles.muteGUIContent, AudioMixerDrawUtils.styles.muteToggle); + if (flag) + { + GUI.color = color; + } + if (flag2 != group.mute) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change mute state"); + group.mute = !group.mute; + foreach (AudioMixerGroupController current3 in selection) + { + current3.mute = group.mute; + } + return true; + } + return false; + } + private bool DoBypassEffectsButton(Rect r, AudioMixerGroupController group, List allGroups, List selection) + { + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && r.Contains(current.mousePosition)) + { + if (allGroups.Any((AudioMixerGroupController g) => g.bypassEffects)) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change bypass effects state"); + foreach (AudioMixerGroupController current2 in allGroups) + { + current2.bypassEffects = false; + } + current.Use(); + return true; + } + } + bool flag = GUI.Toggle(r, group.bypassEffects, this.styles.bypassGUIContent, AudioMixerDrawUtils.styles.bypassToggle); + if (flag != group.bypassEffects) + { + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change bypass effects state"); + group.bypassEffects = !group.bypassEffects; + foreach (AudioMixerGroupController current3 in selection) + { + current3.bypassEffects = group.bypassEffects; + } + return true; + } + return false; + } + private static bool RectOverlaps(Rect r1, Rect r2) + { + Rect rect = default(Rect); + rect.x = Mathf.Max(r1.x, r2.x); + rect.y = Mathf.Max(r1.y, r2.y); + rect.width = Mathf.Min(r1.x + r1.width, r2.x + r2.width) - rect.x; + rect.height = Mathf.Min(r1.y + r1.height, r2.y + r2.height) - rect.y; + return rect.width > 0f && rect.height > 0f; + } + private bool IsRectSelectionActive() + { + return GUIUtility.hotControl == this.m_RectSelectionControlID; + } + private void GroupClicked(AudioMixerGroupController clickedGroup, AudioMixerChannelStripView.ChannelStripParams p, bool clickedControlInGroup) + { + List list = new List(); + foreach (AudioMixerGroupController current in p.shownGroups) + { + list.Add(current.GetInstanceID()); + } + List list2 = new List(); + foreach (AudioMixerGroupController current2 in this.m_Controller.CachedSelection) + { + list2.Add(current2.GetInstanceID()); + } + int lastClickedInstanceID = this.m_State.m_LastClickedInstanceID; + bool allowMultiSelection = true; + bool keepMultiSelection = Event.current.shift || clickedControlInGroup; + bool useShiftAsActionKey = false; + List newSelection = InternalEditorUtility.GetNewSelection(clickedGroup.GetInstanceID(), list, list2, lastClickedInstanceID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection); + List list3 = ( + from x in p.allGroups + where newSelection.Contains(x.GetInstanceID()) + select x).ToList(); + Selection.objects = list3.ToArray(); + this.m_Controller.OnUnitySelectionChanged(); + InspectorWindow.RepaintAllInspectors(); + } + private void DoAttenuationFader(Rect r, AudioMixerGroupController group, List selection, GUIStyle style) + { + float num = Mathf.Clamp(group.GetValueForVolume(this.m_Controller, this.m_Controller.TargetSnapshot), AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()); + float num2 = this.VerticalFader(r, num, 1, AudioMixerChannelStripView.kVolumeScaleMouseDrag, true, true, this.styles.attenuationFader.tooltip, AudioMixerController.GetMaxVolume(), style); + if (num != num2) + { + float num3 = num2 - num; + Undo.RecordObject(this.m_Controller.TargetSnapshot, "Change volume fader"); + foreach (AudioMixerGroupController current in selection) + { + float num4 = Mathf.Clamp(current.GetValueForVolume(this.m_Controller, this.m_Controller.TargetSnapshot), AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()); + current.SetValueForVolume(this.m_Controller, this.m_Controller.TargetSnapshot, Mathf.Clamp(num4 + num3, AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume())); + } + InspectorWindow.RepaintAllInspectors(); + } + } + internal static void AddEffectItemsToMenu(AudioMixerController controller, AudioMixerGroupController group, int insertIndex, string prefix, GenericMenu pm) + { + string[] effectList = MixerEffectDefinitions.GetEffectList(); + for (int i = 0; i < effectList.Length; i++) + { + if (effectList[i] != "Attenuation" || !group.HasAttenuation()) + { + pm.AddItem(new GUIContent(prefix + AudioMixerController.FixNameForPopupMenu(effectList[i])), false, new GenericMenu.MenuFunction2(AudioMixerChannelStripView.InsertEffectPopupCallback), new AudioMixerChannelStripView.EffectContext(controller, group, insertIndex, effectList[i])); + } + } + } + private void DoEffectSlotInsertEffectPopup(Rect buttonRect, AudioMixerGroupController group, List allGroups, int effectSlotIndex, ref Dictionary effectMap) + { + GenericMenu genericMenu = new GenericMenu(); + if (effectSlotIndex < group.effects.Length) + { + AudioMixerEffectController effect = group.effects[effectSlotIndex]; + if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsReceive() && !effect.IsDuckVolume()) + { + genericMenu.AddItem(new GUIContent("Allow Wet Mixing (causes higher memory usage)"), effect.enableWetMix, delegate + { + effect.enableWetMix = !effect.enableWetMix; + }); + genericMenu.AddItem(new GUIContent("Bypass"), effect.bypass, delegate + { + effect.bypass = !effect.bypass; + this.m_Controller.UpdateBypass(); + InspectorWindow.RepaintAllInspectors(); + }); + genericMenu.AddSeparator(string.Empty); + } + AudioMixerChannelStripView.AddEffectItemsToMenu(group.controller, group, effectSlotIndex, "Add effect before/", genericMenu); + AudioMixerChannelStripView.AddEffectItemsToMenu(group.controller, group, effectSlotIndex + 1, "Add effect after/", genericMenu); + } + else + { + AudioMixerChannelStripView.AddEffectItemsToMenu(group.controller, group, effectSlotIndex, string.Empty, genericMenu); + } + if (effectSlotIndex < group.effects.Length) + { + AudioMixerEffectController audioMixerEffectController = group.effects[effectSlotIndex]; + if (!audioMixerEffectController.IsAttenuation()) + { + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Remove"), false, new GenericMenu.MenuFunction2(this.RemoveEffectPopupCallback), new AudioMixerChannelStripView.EffectContext(this.m_Controller, group, effectSlotIndex, string.Empty)); + bool flag = false; + if (audioMixerEffectController.IsSend()) + { + if (audioMixerEffectController.sendTarget != null) + { + if (!flag) + { + flag = true; + genericMenu.AddSeparator(string.Empty); + } + genericMenu.AddItem(new GUIContent("Disconnect from '" + audioMixerEffectController.GetSendTargetDisplayString(effectMap) + "'"), false, new GenericMenu.MenuFunction2(AudioMixerChannelStripView.ConnectSendPopupCallback), new AudioMixerChannelStripView.ConnectSendContext(audioMixerEffectController, null)); + } + if (!flag) + { + this.AddSeperatorIfAnyReturns(genericMenu, allGroups); + } + AudioMixerChannelStripView.AddMenuItemsForReturns(genericMenu, "Connect to ", effectSlotIndex, group, allGroups, effectMap, audioMixerEffectController, false); + } + } + } + genericMenu.DropDown(buttonRect); + Event.current.Use(); + } + private void AddSeperatorIfAnyReturns(GenericMenu pm, List allGroups) + { + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerEffectController[] effects = current.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (audioMixerEffectController.IsReceive() || audioMixerEffectController.IsDuckVolume()) + { + pm.AddSeparator(string.Empty); + return; + } + } + } + } + public static void AddMenuItemsForReturns(GenericMenu pm, string prefix, int effectIndex, AudioMixerGroupController group, List allGroups, Dictionary effectMap, AudioMixerEffectController effect, bool showCurrent) + { + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerEffectController[] effects = current.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (MixerEffectDefinitions.EffectCanBeSidechainTarget(audioMixerEffectController)) + { + List list = new List(); + if (!AudioMixerController.WillChangeOfEffectTargetCauseFeedback(allGroups, group, effectIndex, audioMixerEffectController, list)) + { + if (showCurrent || effect.sendTarget != audioMixerEffectController) + { + pm.AddItem(new GUIContent(prefix + "'" + audioMixerEffectController.GetDisplayString(effectMap) + "'"), effect.sendTarget == audioMixerEffectController, new GenericMenu.MenuFunction2(AudioMixerChannelStripView.ConnectSendPopupCallback), new AudioMixerChannelStripView.ConnectSendContext(effect, audioMixerEffectController)); + } + } + else + { + string text = "A connection to '" + AudioMixerController.FixNameForPopupMenu(audioMixerEffectController.GetDisplayString(effectMap)) + "' would result in a feedback loop/"; + pm.AddDisabledItem(new GUIContent(text + "Loop: ")); + int num = 1; + foreach (AudioMixerController.ConnectionNode current2 in list) + { + pm.AddDisabledItem(new GUIContent(string.Concat(new object[] + { + text, + num, + ": ", + current2.GetDisplayString(), + "->" + }))); + num++; + } + pm.AddDisabledItem(new GUIContent(text + num + ": ...")); + } + } + } + } + } + public void VUMeter(AudioMixerGroupController group, Rect r, float level, float peak) + { + EditorGUI.VUMeter.VerticalMeter(r, level, peak, EditorGUI.VUMeter.verticalVUTexture, Color.grey); + } + private void DrawBackgrounds(AudioMixerChannelStripView.ChannelStripParams p, bool selected) + { + if (Event.current.type == EventType.Repaint) + { + this.styles.channelStripBg.Draw(p.stripRect, false, false, selected, false); + float num = 0.466666669f; + float num2 = 0.227450982f; + Color color = (!EditorGUIUtility.isProSkin) ? new Color(num, num, num) : new Color(num2, num2, num2); + Rect rect = p.bgRects[p.kEffectStartIndex]; + rect.y -= 1f; + rect.height = 1f; + EditorGUI.DrawRect(rect, color); + } + Rect rect2 = p.bgRects[p.kVUMeterFaderIndex]; + rect2.height = (float)((!EditorGUIUtility.isProSkin) ? 2 : 1); + rect2.y -= rect2.height; + int userColorIndex = p.group.userColorIndex; + if (userColorIndex != 0) + { + EditorGUI.DrawRect(rect2, AudioMixerColorCodes.GetColor(userColorIndex)); + } + } + private void OpenGroupContextMenu(AudioMixerGroupController group) + { + GenericMenu genericMenu = new GenericMenu(); + AudioMixerChannelStripView.AddEffectItemsToMenu(group.controller, group, 0, "Add effect at top/", genericMenu); + AudioMixerChannelStripView.AddEffectItemsToMenu(group.controller, group, group.effects.Length, "Add effect at bottom/", genericMenu); + genericMenu.AddSeparator(string.Empty); + AudioMixerColorCodes.AddColorItemsToGenericMenu(genericMenu, group); + genericMenu.AddSeparator(string.Empty); + genericMenu.ShowAsContext(); + } + private void DrawChannelStrip(AudioMixerChannelStripView.ChannelStripParams p, ref int highlightEffectIndex, ref Dictionary patchslots, bool showBusConnectionsOfSelection) + { + Event current = Event.current; + bool flag = current.type == EventType.MouseDown && p.stripRect.Contains(current.mousePosition); + bool selected = this.m_Controller.CachedSelection.Contains(p.group); + if (this.IsRectSelectionActive() && AudioMixerChannelStripView.RectOverlaps(p.stripRect, this.m_RectSelectionRect)) + { + p.rectSelectionGroups.Add(p.group); + selected = true; + } + this.DrawBackgrounds(p, selected); + GUIContent arg_9B_0 = this.headerGUIContent; + string displayString = p.group.GetDisplayString(); + this.headerGUIContent.tooltip = displayString; + arg_9B_0.text = displayString; + GUI.Label(p.bgRects[p.kHeaderIndex], this.headerGUIContent, AudioMixerDrawUtils.styles.channelStripHeaderStyle); + Rect rect = new RectOffset(-6, 0, 0, -4).Add(p.bgRects[p.kVUMeterFaderIndex]); + float num = 1f; + float num2 = 54f; + float width = rect.width - num2 - num; + Rect vuRect = new Rect(rect.x, rect.y, num2, rect.height); + Rect rect2 = new Rect(vuRect.xMax + num, rect.y, width, rect.height); + float width2 = 29f; + Rect r = new Rect(rect2.x, rect2.y, width2, rect2.height); + Rect rect3 = p.bgRects[p.kSoloMuteBypassIndex]; + GUIStyle channelStripAttenuationMarkerSquare = AudioMixerDrawUtils.styles.channelStripAttenuationMarkerSquare; + EditorGUI.BeginDisabledGroup(!AudioMixerController.EditingTargetSnapshot()); + this.DoVUMeters(vuRect, channelStripAttenuationMarkerSquare.fixedHeight, p); + this.DoAttenuationFader(r, p.group, this.m_Controller.CachedSelection, channelStripAttenuationMarkerSquare); + this.DoTotaldB(p); + this.DoEffectList(p, selected, ref highlightEffectIndex, ref patchslots, showBusConnectionsOfSelection); + EditorGUI.EndDisabledGroup(); + this.DoSoloMuteBypassButtons(rect3, p.group, p.allGroups, this.m_Controller.CachedSelection, p.anySoloActive); + if (flag) + { + this.GroupClicked(p.group, p, current.type == EventType.Used); + } + if (current.type == EventType.ContextClick && p.stripRect.Contains(current.mousePosition)) + { + current.Use(); + this.OpenGroupContextMenu(p.group); + } + } + private void DoTotaldB(AudioMixerChannelStripView.ChannelStripParams p) + { + float num = 50f; + this.styles.totalVULevel.padding.right = (int)((p.stripRect.width - num) * 0.5f); + float num2 = Mathf.Max(p.vuinfo_level[8], -80f); + Rect position = p.bgRects[p.kTotalVULevelIndex]; + GUI.Label(position, string.Format("{0:F1} dB", num2), this.styles.totalVULevel); + } + private void DoEffectList(AudioMixerChannelStripView.ChannelStripParams p, bool selected, ref int highlightEffectIndex, ref Dictionary patchslots, bool showBusConnectionsOfSelection) + { + Event current = Event.current; + for (int i = 0; i < p.maxEffects; i++) + { + Rect rect = p.bgRects[p.kEffectStartIndex + i]; + if (i < p.group.effects.Length) + { + AudioMixerEffectController effect = p.group.effects[i]; + if (p.visible) + { + if (current.type == EventType.ContextClick && rect.Contains(Event.current.mousePosition)) + { + this.ClearFocus(); + this.DoEffectSlotInsertEffectPopup(rect, p.group, p.allGroups, i, ref p.effectMap); + current.Use(); + } + this.EffectSlot(rect, this.m_Controller.TargetSnapshot, effect, i, ref highlightEffectIndex, p, ref patchslots); + } + } + } + if (p.visible) + { + Rect rect2 = p.bgRects[p.bgRects.Count - 1]; + if (current.type == EventType.Repaint) + { + GUI.DrawTextureWithTexCoords(new Rect(rect2.x, rect2.y, rect2.width, rect2.height - 1f), this.styles.effectBar.hover.background, new Rect(0f, 0.5f, 0.1f, 0.1f)); + GUI.Label(rect2, this.addText, this.styles.effectName); + } + if (current.type == EventType.MouseDown && rect2.Contains(Event.current.mousePosition)) + { + this.ClearFocus(); + int effectSlotIndex = p.group.effects.Length; + this.DoEffectSlotInsertEffectPopup(rect2, p.group, p.allGroups, effectSlotIndex, ref p.effectMap); + current.Use(); + } + } + } + private float DoVUMeters(Rect vuRect, float attenuationMarkerHeight, AudioMixerChannelStripView.ChannelStripParams p) + { + float num = 1f; + int num2 = p.numChannels; + if (num2 == 0) + { + if (p.index >= 0 && p.index < this.m_LastNumChannels.Count) + { + num2 = this.m_LastNumChannels[p.index]; + } + } + else + { + while (p.index >= this.m_LastNumChannels.Count) + { + this.m_LastNumChannels.Add(0); + } + this.m_LastNumChannels[p.index] = num2; + } + if (num2 <= 2) + { + vuRect.x = vuRect.xMax - 25f; + vuRect.width = 25f; + } + if (num2 == 0) + { + return vuRect.x; + } + float num3 = Mathf.Floor(attenuationMarkerHeight / 2f); + vuRect.y += num3; + vuRect.height -= 2f * num3; + float num4 = Mathf.Round((vuRect.width - (float)num2 * num) / (float)num2); + Rect r = new Rect(vuRect.xMax - num4, vuRect.y, num4, vuRect.height); + for (int i = num2 - 1; i >= 0; i--) + { + if (i != num2 - 1) + { + r.x -= r.width + num; + } + float level = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(p.vuinfo_level[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true); + float peak = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(p.vuinfo_peak[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true); + this.VUMeter(p.group, r, level, peak); + } + AudioMixerDrawUtils.AddTooltipOverlay(vuRect, this.styles.vuMeterGUIContent.tooltip); + return r.x; + } + private void DoSoloMuteBypassButtons(Rect rect, AudioMixerGroupController group, List allGroups, List selection, bool anySoloActive) + { + float num = 21f; + float num2 = 2f; + float left = rect.x + (rect.width - (num * 3f + num2 * 2f)) * 0.5f; + Rect r = new Rect(left, rect.y, num, num); + bool flag = false; + flag |= this.DoSoloButton(r, group, allGroups, selection); + r.x += num + num2; + flag |= this.DoMuteButton(r, group, allGroups, anySoloActive, selection); + if (flag) + { + this.m_Controller.UpdateMuteSolo(); + } + r.x += num + num2; + if (this.DoBypassEffectsButton(r, group, allGroups, selection)) + { + this.m_Controller.UpdateBypass(); + } + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + this.m_Controller = controller; + } + public void ShowDeveloperOverlays(Rect rect, Event evt, bool show) + { + if (show && Unsupported.IsDeveloperBuild() && evt.type == EventType.Repaint) + { + AudioMixerDrawUtils.ReadOnlyLabel(new Rect(rect.x + 5f, rect.y + 5f, rect.width - 10f, 20f), "Current snapshot: " + this.m_Controller.TargetSnapshot.name, this.developerInfoStyle); + AudioMixerDrawUtils.ReadOnlyLabel(new Rect(rect.x + 5f, rect.y + 25f, rect.width - 10f, 20f), "Frame count: " + this.FrameCounter++, this.developerInfoStyle); + } + } + public static float Lerp(float x1, float x2, float t) + { + return x1 + (x2 - x1) * t; + } + public static void GetCableVertex(float x1, float y1, float x2, float y2, float x3, float y3, float t, out float x, out float y) + { + x = AudioMixerChannelStripView.Lerp(AudioMixerChannelStripView.Lerp(x1, x2, t), AudioMixerChannelStripView.Lerp(x2, x3, t), t); + y = AudioMixerChannelStripView.Lerp(AudioMixerChannelStripView.Lerp(y1, y2, t), AudioMixerChannelStripView.Lerp(y2, y3, t), t); + } + public void OnGUI(Rect rect, bool showReferencedBuses, bool showBusConnections, bool showBusConnectionsOfSelection, List allGroups, Dictionary effectMap, bool sortGroupsAlphabetically, bool showDeveloperOverlays, AudioMixerGroupController scrollToItem) + { + if (this.m_Controller == null) + { + this.DrawAreaBackground(rect); + return; + } + if (Event.current.type == EventType.Layout) + { + return; + } + this.m_RectSelectionControlID = GUIUtility.GetControlID(AudioMixerChannelStripView.kRectSelectionHashCode, FocusType.Passive); + this.m_EffectInteractionControlID = GUIUtility.GetControlID(AudioMixerChannelStripView.kEffectDraggingHashCode, FocusType.Passive); + this.m_IndexCounter = 0; + Event current = Event.current; + List list = this.m_Controller.GetCurrentViewGroupList().ToList(); + if (sortGroupsAlphabetically) + { + list.Sort(this.m_GroupComparer); + } + Rect rect2 = new Rect(this.channelStripsOffset.x, this.channelStripsOffset.y, 90f, 300f); + if (scrollToItem != null) + { + int num = list.IndexOf(scrollToItem); + if (num >= 0) + { + float num2 = (rect2.width + 4f) * (float)num - this.m_State.m_ScrollPos.x; + if (num2 < -20f || num2 > rect.width) + { + AudioMixerChannelStripView.State expr_111_cp_0 = this.m_State; + expr_111_cp_0.m_ScrollPos.x = expr_111_cp_0.m_ScrollPos.x + num2; + } + } + } + List list2 = new List(); + foreach (AudioMixerGroupController current2 in list) + { + AudioMixerEffectController[] effects = current2.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController audioMixerEffectController = effects[i]; + if (audioMixerEffectController.sendTarget != null) + { + AudioMixerGroupController item = effectMap[audioMixerEffectController.sendTarget]; + if (!list2.Contains(item) && !list.Contains(item)) + { + list2.Add(item); + } + } + } + } + List list3 = list2.ToList(); + list3.Sort(this.m_GroupComparer); + int count = list.Count; + if (showReferencedBuses && list3.Count > 0) + { + list.AddRange(list3); + } + int num3 = 1; + foreach (AudioMixerGroupController current3 in list) + { + num3 = Mathf.Max(num3, current3.effects.Length); + } + bool isShowingReferencedGroups = list.Count != count; + Rect contentRect = this.GetContentRect(list, isShowingReferencedGroups, num3); + this.m_State.m_ScrollPos = GUI.BeginScrollView(rect, this.m_State.m_ScrollPos, contentRect); + this.DrawAreaBackground(new Rect(0f, 0f, 10000f, 10000f)); + AudioMixerChannelStripView.ChannelStripParams channelStripParams = new AudioMixerChannelStripView.ChannelStripParams(); + channelStripParams.effectMap = effectMap; + channelStripParams.allGroups = allGroups; + channelStripParams.shownGroups = list; + channelStripParams.anySoloActive = allGroups.Any((AudioMixerGroupController g) => g.solo); + channelStripParams.visibleRect = new Rect(this.m_State.m_ScrollPos.x, this.m_State.m_ScrollPos.y, rect.width, rect.height); + AudioMixerChannelStripView.ChannelStripParams channelStripParams2 = channelStripParams; + Dictionary dictionary = (!showBusConnections) ? null : new Dictionary(); + for (int j = 0; j < list.Count; j++) + { + AudioMixerGroupController group = list[j]; + channelStripParams2.index = j; + channelStripParams2.group = group; + channelStripParams2.drawingBuses = false; + channelStripParams2.visible = AudioMixerChannelStripView.RectOverlaps(channelStripParams2.visibleRect, rect2); + channelStripParams2.Init(this.m_Controller, rect2, num3); + this.DrawChannelStrip(channelStripParams2, ref this.m_Controller.m_HighlightEffectIndex, ref dictionary, showBusConnectionsOfSelection); + if (current.type == EventType.MouseDown && current.button == 0 && channelStripParams2.stripRect.Contains(current.mousePosition)) + { + current.Use(); + } + if (this.IsMovingEffect() && current.type == EventType.MouseDrag && channelStripParams2.stripRect.Contains(current.mousePosition) && GUIUtility.hotControl == this.m_EffectInteractionControlID) + { + this.m_MovingEffectDstIndex = -1; + current.Use(); + } + rect2.x += channelStripParams2.stripRect.width + 4f; + if (showReferencedBuses && j == count - 1 && list.Count > count) + { + rect2.x += 50f; + EditorGUI.BeginDisabledGroup(true); + GUI.Label(new Rect(rect2.x, channelStripParams2.stripRect.yMax, 130f, 22f), this.styles.referencedGroups, this.styles.channelStripHeaderStyle); + EditorGUI.EndDisabledGroup(); + } + } + this.UnhandledEffectDraggingEvents(ref this.m_Controller.m_HighlightEffectIndex); + if (current.type == EventType.Repaint && dictionary != null) + { + foreach (KeyValuePair current4 in dictionary) + { + AudioMixerChannelStripView.PatchSlot value = current4.Value; + bool flag = !showBusConnectionsOfSelection || this.m_Controller.CachedSelection.Contains(value.group); + if (flag) + { + this.styles.circularToggle.Draw(new Rect(value.x - 3f, value.y - 3f, 6f, 6f), false, false, flag, false); + } + } + float num4 = Mathf.Exp(-0.03f * Time.time * Time.time) * 0.1f; + Color color = new Color(0f, 0f, 0f, (!AudioMixerController.EditingTargetSnapshot()) ? 0.05f : 0.1f); + Color color2 = new Color(0f, 0f, 0f, (!AudioMixerController.EditingTargetSnapshot()) ? 0.5f : 1f); + foreach (KeyValuePair current5 in dictionary) + { + AudioMixerEffectController key = current5.Key; + AudioMixerEffectController sendTarget = key.sendTarget; + if (!(sendTarget == null)) + { + AudioMixerChannelStripView.PatchSlot value2 = current5.Value; + if (dictionary.ContainsKey(sendTarget)) + { + AudioMixerChannelStripView.PatchSlot patchSlot = dictionary[sendTarget]; + int num5 = key.GetInstanceID() ^ sendTarget.GetInstanceID(); + float num6 = (float)(num5 & 63) * 0.1f; + float x = Mathf.Abs(patchSlot.x - value2.x) * Mathf.Sin(Time.time * 5f + num6) * num4 + (value2.x + patchSlot.x) * 0.5f; + float y = Mathf.Abs(patchSlot.y - value2.y) * Mathf.Cos(Time.time * 5f + num6) * num4 + Math.Max(value2.y, patchSlot.y) + Mathf.Max(Mathf.Min(0.5f * Math.Abs(patchSlot.y - value2.y), 50f), 50f); + for (int k = 0; k < this.cablepoints.Length; k++) + { + AudioMixerChannelStripView.GetCableVertex(value2.x, value2.y, x, y, patchSlot.x, patchSlot.y, (float)k / (float)(this.cablepoints.Length - 1), out this.cablepoints[k].x, out this.cablepoints[k].y); + } + bool flag2 = showBusConnectionsOfSelection && !this.m_Controller.CachedSelection.Contains(value2.group) && !this.m_Controller.CachedSelection.Contains(patchSlot.group); + Handles.color = ((!flag2) ? color2 : color); + Handles.DrawAAPolyLine(7f, this.cablepoints.Length, this.cablepoints); + if (!flag2) + { + num5 ^= (num5 >> 6 ^ num5 >> 12 ^ num5 >> 18); + Handles.color = new Color((float)(num5 & 3) * 0.15f + 0.55f, (float)(num5 >> 2 & 3) * 0.15f + 0.55f, (float)(num5 >> 4 & 3) * 0.15f + 0.55f, (!AudioMixerController.EditingTargetSnapshot()) ? 0.5f : 1f); + Handles.DrawAAPolyLine(4f, this.cablepoints.Length, this.cablepoints); + Handles.color = new Color(1f, 1f, 1f, (!AudioMixerController.EditingTargetSnapshot()) ? 0.25f : 0.5f); + Handles.DrawAAPolyLine(3f, this.cablepoints.Length, this.cablepoints); + } + } + } + } + } + this.RectSelection(channelStripParams2); + GUI.EndScrollView(true); + AudioMixerDrawUtils.DrawScrollDropShadow(rect, this.m_State.m_ScrollPos.y, contentRect.height); + this.WarningOverlay(allGroups, rect, contentRect); + this.ShowDeveloperOverlays(rect, current, showDeveloperOverlays); + if (!EditorApplication.isPlaying && !this.m_Controller.isSuspended) + { + this.m_RequiresRepaint = true; + } + } + private bool IsMovingEffect() + { + return this.m_MovingEffectSrcIndex != -1; + } + private bool IsAdjustingWetMix() + { + return this.m_ChangingWetMixIndex != -1; + } + private void RectSelection(AudioMixerChannelStripView.ChannelStripParams channelStripParams) + { + Event current = Event.current; + if (current.type == EventType.MouseDown && current.button == 0 && GUIUtility.hotControl == 0) + { + if (!current.shift) + { + Selection.objects = new UnityEngine.Object[0]; + this.m_Controller.OnUnitySelectionChanged(); + } + GUIUtility.hotControl = this.m_RectSelectionControlID; + this.m_RectSelectionStartPos = current.mousePosition; + this.m_RectSelectionRect = new Rect(this.m_RectSelectionStartPos.x, this.m_RectSelectionStartPos.y, 0f, 0f); + Event.current.Use(); + InspectorWindow.RepaintAllInspectors(); + } + if (current.type == EventType.MouseDrag) + { + if (this.IsRectSelectionActive()) + { + this.m_RectSelectionRect.x = Mathf.Min(this.m_RectSelectionStartPos.x, current.mousePosition.x); + this.m_RectSelectionRect.y = Mathf.Min(this.m_RectSelectionStartPos.y, current.mousePosition.y); + this.m_RectSelectionRect.width = Mathf.Max(this.m_RectSelectionStartPos.x, current.mousePosition.x) - this.m_RectSelectionRect.x; + this.m_RectSelectionRect.height = Mathf.Max(this.m_RectSelectionStartPos.y, current.mousePosition.y) - this.m_RectSelectionRect.y; + Event.current.Use(); + } + if (this.m_MovingSrcRect.y >= 0f) + { + Event.current.Use(); + } + } + if (this.IsRectSelectionActive() && current.GetTypeForControl(this.m_RectSelectionControlID) == EventType.MouseUp) + { + List list = (!current.shift) ? new List() : this.m_Controller.CachedSelection; + foreach (AudioMixerGroupController current2 in channelStripParams.rectSelectionGroups) + { + if (!list.Contains(current2)) + { + list.Add(current2); + } + } + Selection.objects = list.ToArray(); + this.m_Controller.OnUnitySelectionChanged(); + GUIUtility.hotControl = 0; + Event.current.Use(); + } + if (current.type == EventType.Repaint && this.IsRectSelectionActive()) + { + Color color = new Color(1f, 1f, 1f, 0.3f); + AudioMixerDrawUtils.DrawGradientRectHorizontal(this.m_RectSelectionRect, color, color); + } + } + private void WarningOverlay(List allGroups, Rect rect, Rect contentRect) + { + int num = 0; + int num2 = 0; + int num3 = 0; + foreach (AudioMixerGroupController current in allGroups) + { + if (current.solo) + { + num++; + } + if (current.mute) + { + num2++; + } + if (current.bypassEffects) + { + num3 += current.effects.Length - 1; + } + else + { + num3 += current.effects.Count((AudioMixerEffectController e) => e.bypass); + } + } + Event current2 = Event.current; + if ((current2.type == EventType.Repaint && num > 0) || num2 > 0 || num3 > 0) + { + string t = "Warning: " + ((num <= 0) ? ((num2 <= 0) ? (num3 + ((num3 <= 1) ? " effect" : " effects") + " currently bypassed") : (num2 + ((num2 <= 1) ? " group" : " groups") + " currently muted")) : (num + ((num <= 1) ? " group" : " groups") + " currently soloed")); + bool flag = contentRect.width > rect.width; + float x = this.styles.warningOverlay.CalcSize(GUIContent.Temp(t)).x; + Rect position = new Rect(rect.x + 5f + Mathf.Max((rect.width - 10f - x) * 0.5f, 0f), rect.yMax - this.styles.warningOverlay.fixedHeight - 5f - ((!flag) ? 0f : 17f), x, this.styles.warningOverlay.fixedHeight); + GUI.Label(position, GUIContent.Temp(t), this.styles.warningOverlay); + } + } + private Rect GetContentRect(List sortedGroups, bool isShowingReferencedGroups, int maxEffects) + { + float num = 239f; + float height = this.channelStripsOffset.y + num + (float)maxEffects * 16f + 10f + 16f + 10f; + float width = this.channelStripsOffset.x * 2f + 94f * (float)sortedGroups.Count + ((!isShowingReferencedGroups) ? 0f : 50f); + return new Rect(0f, 0f, width, height); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerColorCodes.cs b/UnityEditor/UnityEditor/AudioMixerColorCodes.cs new file mode 100644 index 00000000..41d30a17 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerColorCodes.cs @@ -0,0 +1,90 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal static class AudioMixerColorCodes + { + private struct ItemData + { + public AudioMixerGroupController group; + public int index; + } + private static Color[] darkSkinColors = new Color[] + { + new Color(0.5f, 0.5f, 0.5f, 0.2f), + new Color(1f, 0.8156863f, 0f), + new Color(0.9607843f, 0.6117647f, 0.0156862754f), + new Color(1f, 0.294117659f, 0.227450982f), + new Color(1f, 0.380392164f, 0.6117647f), + new Color(0.65882355f, 0.447058827f, 0.7176471f), + new Color(0.0509803928f, 0.6117647f, 0.8235294f), + new Color(0f, 0.745098054f, 0.784313738f), + new Color(0.5411765f, 0.7529412f, 0.003921569f) + }; + private static Color[] lightSkinColors = new Color[] + { + new Color(0.5f, 0.5f, 0.5f, 0.2f), + new Color(1f, 0.8392157f, 0.08627451f), + new Color(0.968627453f, 0.5764706f, 0f), + new Color(1f, 0.294117659f, 0.227450982f), + new Color(1f, 0.380392164f, 0.6117647f), + new Color(0.65882355f, 0.447058827f, 0.7176471f), + new Color(0.0509803928f, 0.6117647f, 0.8235294f), + new Color(0f, 0.709803939f, 0.7254902f), + new Color(0.447058827f, 0.6627451f, 0.09411765f) + }; + private static string[] colorNames = new string[] + { + "No Color", + "Yellow", + "Orange", + "Red", + "Magenta", + "Violet", + "Blue", + "Cyan", + "Green" + }; + private static string[] GetColorNames() + { + return AudioMixerColorCodes.colorNames; + } + private static Color[] GetColors() + { + if (EditorGUIUtility.isProSkin) + { + return AudioMixerColorCodes.darkSkinColors; + } + return AudioMixerColorCodes.lightSkinColors; + } + public static void AddColorItemsToGenericMenu(GenericMenu menu, AudioMixerGroupController group) + { + Color[] colors = AudioMixerColorCodes.GetColors(); + string[] array = AudioMixerColorCodes.GetColorNames(); + for (int i = 0; i < colors.Length; i++) + { + menu.AddItem(new GUIContent(array[i]), i == group.userColorIndex, new GenericMenu.MenuFunction2(AudioMixerColorCodes.ItemCallback), new AudioMixerColorCodes.ItemData + { + group = group, + index = i + }); + } + } + private static void ItemCallback(object data) + { + AudioMixerColorCodes.ItemData itemData = (AudioMixerColorCodes.ItemData)data; + itemData.group.userColorIndex = itemData.index; + } + public static Color GetColor(int index) + { + Color[] colors = AudioMixerColorCodes.GetColors(); + if (index >= 0 && index < colors.Length) + { + return colors[index]; + } + Debug.LogError("Invalid color code index: " + index); + return Color.white; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerControllerInspector.cs b/UnityEditor/UnityEditor/AudioMixerControllerInspector.cs new file mode 100644 index 00000000..a4c04606 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerControllerInspector.cs @@ -0,0 +1,28 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioMixerController))] + internal class AudioMixerControllerInspector : Editor + { + private GUIContent m_EnableSuspendLabel = new GUIContent("Enable Suspend", "Enables/disables suspending of processing in order to save CPU when the RMS signal level falls under the defined threshold (in dB). Mixers resume processing when an AudioSource referencing them starts playing again."); + private GUIContent m_SuspendThresholdLabel = new GUIContent("Suspend Threshold", "The level of the Master Group at which the mixer suspends processing in order to save CPU. Mixers resume processing when an AudioSource referencing them starts playing again."); + private SerializedProperty m_EnableSuspend; + private SerializedProperty m_SuspendThreshold; + public void OnEnable() + { + this.m_SuspendThreshold = base.serializedObject.FindProperty("m_SuspendThreshold"); + this.m_EnableSuspend = base.serializedObject.FindProperty("m_EnableSuspend"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_EnableSuspend, this.m_EnableSuspendLabel, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!this.m_EnableSuspend.boolValue || this.m_EnableSuspend.hasMultipleDifferentValues); + EditorGUILayout.PropertyField(this.m_SuspendThreshold, this.m_SuspendThresholdLabel, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerDrawUtils.cs b/UnityEditor/UnityEditor/AudioMixerDrawUtils.cs new file mode 100644 index 00000000..c5a4b668 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerDrawUtils.cs @@ -0,0 +1,366 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerDrawUtils + { + public class Styles + { + public GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel); + public GUIStyle reorderableListLabel = new GUIStyle("PR Label"); + public GUIStyle regionBg = AudioMixerDrawUtils.Styles.GetStyle("RegionBg"); + public GUIStyle channelStripVUMeterBg = AudioMixerDrawUtils.Styles.GetStyle("ChannelStripVUMeterBg"); + public GUIStyle channelStripAreaBackground = "AnimationCurveEditorBackground"; + public GUIStyle channelStripBg = AudioMixerDrawUtils.Styles.GetStyle("ChannelStripBg"); + public GUIStyle duckingMarker = AudioMixerDrawUtils.Styles.GetStyle("ChannelStripDuckingMarker"); + public GUIStyle channelStripAttenuationMarkerSquare = AudioMixerDrawUtils.Styles.GetStyle("ChannelStripAttenuationMarkerSquare"); + public GUIStyle channelStripHeaderStyle; + public GUIStyle soloToggle = AudioMixerDrawUtils.Styles.GetStyle("SoloToggle"); + public GUIStyle muteToggle = AudioMixerDrawUtils.Styles.GetStyle("MuteToggle"); + public GUIStyle bypassToggle = AudioMixerDrawUtils.Styles.GetStyle("BypassToggle"); + public GUIStyle circularToggle = AudioMixerDrawUtils.Styles.GetStyle("CircularToggle"); + public GUIStyle totalVULevel = new GUIStyle(EditorStyles.label); + public GUIStyle attenuationBar = "ChannelStripAttenuationBar"; + public GUIStyle effectBar = "ChannelStripEffectBar"; + public GUIStyle sendReturnBar = "ChannelStripSendReturnBar"; + public GUIStyle effectName = new GUIStyle(EditorStyles.miniLabel); + public GUIStyle vuValue = new GUIStyle(EditorStyles.miniLabel); + public GUIStyle mixerHeader = new GUIStyle(EditorStyles.largeLabel); + public GUIStyle warningOverlay = AudioMixerDrawUtils.Styles.GetStyle("WarningOverlay"); + public Texture2D scrollShadowTexture = EditorGUIUtility.FindTexture("ScrollShadow"); + public Texture2D leftToRightShadowTexture = EditorGUIUtility.FindTexture("LeftToRightShadow"); + public GUIContent soloGUIContent = new GUIContent(string.Empty, "Adds this group to set of soloed groups"); + public GUIContent muteGUIContent = new GUIContent(string.Empty, "Mutes this group"); + public GUIContent bypassGUIContent = new GUIContent(string.Empty, "Bypasses the effects on this group"); + public GUIContent effectSlotGUIContent = new GUIContent(string.Empty, "Drag horizontally to change wet mix levels or vertically to change order of effects. Note: Enable wet mixing in the context menu."); + public GUIContent attenuationSlotGUIContent = new GUIContent(string.Empty, "Place the attenuation slot in the effect stack where attenuation should take effect"); + public GUIContent emptySendSlotGUIContent = new GUIContent(string.Empty, "Connect to a Receive in the context menu or in the inspector"); + public GUIContent returnSlotGUIContent = new GUIContent(string.Empty, "Connect a Send to this Receive"); + public GUIContent duckVolumeSlotGUIContent = new GUIContent(string.Empty, "Connect a Send to this Duck Volume"); + public GUIContent duckingFaderGUIContent = new GUIContent(string.Empty, "Ducking Fader"); + public GUIContent attenuationFader = new GUIContent(string.Empty, "Attenuation fader"); + public GUIContent vuMeterGUIContent = new GUIContent(string.Empty, "The VU meter shows the current level of the mix of all sounds and subgroups."); + public GUIContent referencedGroups = new GUIContent("Referenced groups", "Mixer groups that are hidden but are referenced by the visible mixer groups are shown here for convenience"); + public GUIContent sendString = new GUIContent("s"); + public Styles() + { + this.headerStyle.alignment = TextAnchor.MiddleLeft; + Texture2D background = this.reorderableListLabel.hover.background; + this.reorderableListLabel.normal.background = background; + this.reorderableListLabel.active.background = background; + this.reorderableListLabel.focused.background = background; + this.reorderableListLabel.onNormal.background = background; + this.reorderableListLabel.onHover.background = background; + this.reorderableListLabel.onActive.background = background; + this.reorderableListLabel.onFocused.background = background; + RectOffset arg_32A_0 = this.reorderableListLabel.padding; + int num = 0; + this.reorderableListLabel.padding.right = num; + arg_32A_0.left = num; + this.reorderableListLabel.alignment = TextAnchor.MiddleLeft; + this.scrollShadowTexture = EditorGUIUtility.FindTexture("ScrollShadow"); + this.channelStripHeaderStyle = new GUIStyle(EditorStyles.boldLabel); + this.channelStripHeaderStyle.alignment = TextAnchor.MiddleLeft; + this.channelStripHeaderStyle.fontSize = 11; + this.channelStripHeaderStyle.fontStyle = FontStyle.Bold; + this.channelStripHeaderStyle.wordWrap = false; + this.channelStripHeaderStyle.clipping = TextClipping.Clip; + this.channelStripHeaderStyle.padding = new RectOffset(4, 4, 4, 4); + this.totalVULevel.alignment = TextAnchor.MiddleRight; + this.totalVULevel.padding.right = 20; + this.effectName.padding.left = 4; + this.effectName.padding.top = 2; + this.vuValue.padding.left = 4; + this.vuValue.padding.right = 4; + this.vuValue.padding.top = 0; + this.vuValue.alignment = TextAnchor.MiddleRight; + this.vuValue.clipping = TextClipping.Overflow; + this.warningOverlay.alignment = TextAnchor.MiddleCenter; + this.mixerHeader.fontStyle = FontStyle.Bold; + this.mixerHeader.fontSize = 17; + this.mixerHeader.margin = new RectOffset(); + this.mixerHeader.padding = new RectOffset(); + this.mixerHeader.alignment = TextAnchor.UpperLeft; + if (EditorGUIUtility.isProSkin) + { + this.mixerHeader.normal.textColor = new Color(0.7f, 0.7f, 0.7f, 1f); + } + else + { + this.mixerHeader.normal.textColor = new Color(0.2f, 0.2f, 0.2f, 1f); + } + } + private static GUIStyle GetStyle(string styleName) + { + return styleName; + } + } + internal const float kSectionHeaderHeight = 22f; + internal const float kSpaceBetweenSections = 10f; + private static float vertexOffset = -1f; + private static readonly Color kAttenuationColor = AudioCurveRendering.kAudioOrange; + private static readonly Color kEffectColor = new Color(0.403921574f, 0.627451f, 0f); + private static readonly Color kSendColor = new Color(0f, 0.5764706f, 0.6666667f); + private static readonly Color kReceiveColor = AudioMixerDrawUtils.kSendColor; + private static readonly Color kDuckVolumeColor = AudioMixerDrawUtils.kSendColor; + public static Color kBackgroundHi = new Color(0.5f, 0.5f, 0.5f); + public static Color kBackgroundLo = new Color(0.3f, 0.3f, 0.3f); + public static Color kBackgroundHiHighlight = new Color(0.6f, 0.6f, 0.6f); + public static Color kBackgroundLoHighlight = new Color(0.4f, 0.4f, 0.4f); + private static AudioMixerDrawUtils.Styles s_Styles; + public static float VertexOffset + { + get + { + if (AudioMixerDrawUtils.vertexOffset == -1f) + { + AudioMixerDrawUtils.DetectVertexOffset(); + } + return AudioMixerDrawUtils.vertexOffset; + } + } + public static AudioMixerDrawUtils.Styles styles + { + get + { + return AudioMixerDrawUtils.s_Styles; + } + } + private static void DetectVertexOffset() + { + AudioMixerDrawUtils.vertexOffset = 0.5f; + } + public static Color GetEffectColor(AudioMixerEffectController effect) + { + if (effect.IsSend()) + { + return (!(effect.sendTarget != null)) ? Color.gray : AudioMixerDrawUtils.kSendColor; + } + if (effect.IsReceive()) + { + return AudioMixerDrawUtils.kReceiveColor; + } + if (effect.IsDuckVolume()) + { + return AudioMixerDrawUtils.kDuckVolumeColor; + } + if (effect.IsAttenuation()) + { + return AudioMixerDrawUtils.kAttenuationColor; + } + return AudioMixerDrawUtils.kEffectColor; + } + public static void InitStyles() + { + if (AudioMixerDrawUtils.s_Styles == null) + { + AudioMixerDrawUtils.s_Styles = new AudioMixerDrawUtils.Styles(); + AudioMixerDrawUtils.DetectVertexOffset(); + } + } + public static float GetAlpha() + { + return (!GUI.enabled) ? 0.7f : 1f; + } + public static void DrawSplitter() + { + Rect rect = GUILayoutUtility.GetRect(1f, 1f); + if (Event.current.type == EventType.Repaint) + { + Color color = (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.12f, 0.12f, 0.12f, 1.333f); + EditorGUI.DrawRect(rect, color); + } + } + public static void Vertex(float x, float y) + { + GL.Vertex3(x + AudioMixerDrawUtils.vertexOffset, y + AudioMixerDrawUtils.vertexOffset, 0f); + } + public static void DrawLine(float x1, float y1, float x2, float y2, Color c) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.Begin(1); + GL.Color(new Color(c.r, c.g, c.b, c.a * AudioMixerDrawUtils.GetAlpha())); + AudioMixerDrawUtils.Vertex(x1, y1); + AudioMixerDrawUtils.Vertex(x2, y2); + GL.End(); + } + public static void DrawGradientRect(Rect r, Color c1, Color c2) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.Begin(7); + GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * AudioMixerDrawUtils.GetAlpha())); + AudioMixerDrawUtils.Vertex(r.x, r.y); + AudioMixerDrawUtils.Vertex(r.x + r.width, r.y); + GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * AudioMixerDrawUtils.GetAlpha())); + AudioMixerDrawUtils.Vertex(r.x + r.width, r.y + r.height); + AudioMixerDrawUtils.Vertex(r.x, r.y + r.height); + GL.End(); + } + public static void DrawGradientRectHorizontal(Rect r, Color c1, Color c2) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.Begin(7); + GL.Color(new Color(c1.r, c1.g, c1.b, c1.a * AudioMixerDrawUtils.GetAlpha())); + AudioMixerDrawUtils.Vertex(r.x + r.width, r.y); + AudioMixerDrawUtils.Vertex(r.x + r.width, r.y + r.height); + GL.Color(new Color(c2.r, c2.g, c2.b, c2.a * AudioMixerDrawUtils.GetAlpha())); + AudioMixerDrawUtils.Vertex(r.x, r.y + r.height); + AudioMixerDrawUtils.Vertex(r.x, r.y); + GL.End(); + } + public static void DrawRegionBg(Rect rect, out Rect headerRect, out Rect contentRect) + { + headerRect = new Rect(rect.x + 2f, rect.y, rect.width - 2f, 22f); + contentRect = new Rect(rect.x, headerRect.yMax, rect.width, rect.height - 22f); + GUI.Label(new RectOffset(1, 1, 1, 1).Add(contentRect), GUIContent.none, EditorStyles.helpBox); + } + public static void HeaderLabel(Rect r, GUIContent text, Texture2D icon) + { + if (icon != null) + { + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); + GUI.Label(r, icon, AudioMixerDrawUtils.styles.headerStyle); + EditorGUIUtility.SetIconSize(Vector2.zero); + r.xMin += 20f; + } + GUI.Label(r, text, AudioMixerDrawUtils.styles.headerStyle); + } + public static GUIStyle BuildGUIStyleForLabel(Color color, int fontSize, bool wrapText, FontStyle fontstyle, TextAnchor anchor) + { + GUIStyle gUIStyle = new GUIStyle(); + gUIStyle.focused.background = gUIStyle.onNormal.background; + gUIStyle.focused.textColor = color; + gUIStyle.alignment = anchor; + gUIStyle.fontSize = fontSize; + gUIStyle.fontStyle = fontstyle; + gUIStyle.wordWrap = wrapText; + gUIStyle.clipping = TextClipping.Clip; + gUIStyle.normal.textColor = color; + gUIStyle.padding = new RectOffset(4, 4, 4, 4); + return gUIStyle; + } + public static void ReadOnlyLabel(Rect r, GUIContent content, GUIStyle style) + { + GUI.Label(r, content, style); + } + public static void ReadOnlyLabel(Rect r, string text, GUIStyle style) + { + GUI.Label(r, GUIContent.Temp(text), style); + } + public static void ReadOnlyLabel(Rect r, string text, GUIStyle style, string tooltipText) + { + GUI.Label(r, GUIContent.Temp(text, tooltipText), style); + } + public static void AddTooltipOverlay(Rect r, string tooltip) + { + GUI.Label(r, GUIContent.Temp(string.Empty, tooltip), AudioMixerDrawUtils.s_Styles.headerStyle); + } + public static void DrawConnection(Color col, float mixLevel, float srcX, float srcY, float dstX, float dstY, float width) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + float num = dstX - srcX; + float num2 = dstY - srcY; + float num3 = width / Mathf.Sqrt(num * num + num2 * num2); + num *= num3; + num2 *= num3; + float num4 = 2f; + float num5 = 1.2f; + Vector3[] array = new Vector3[4]; + array[0] = new Vector3(dstX, dstY); + array[1] = new Vector3(dstX - num4 * num + num5 * num2, dstY - num4 * num2 - num5 * num); + array[2] = new Vector3(dstX - num4 * num - num5 * num2, dstY - num4 * num2 + num5 * num); + array[3] = array[0]; + Color color = new Color(col.r, col.g, col.b, mixLevel * 0.3f + 0.3f); + Shader.SetGlobalColor("_HandleColor", color); + GL.Begin(4); + GL.Color(color); + GL.Vertex(array[0]); + GL.Vertex(array[1]); + GL.Vertex(array[2]); + GL.End(); + Handles.DrawAAPolyLine(width, new Color[] + { + color, + color, + color, + color + }, array); + Handles.DrawAAPolyLine(width, new Color[] + { + new Color(col.r, col.g, col.b, mixLevel), + new Color(col.r, col.g, col.b, mixLevel) + }, new Vector3[] + { + new Vector3(srcX, srcY, 0f), + new Vector3(dstX, dstY, 0f) + }); + } + public static void DrawVerticalShow(Rect rect, bool fadeToTheRight) + { + Rect texCoords = (!fadeToTheRight) ? new Rect(1f, 1f, -1f, -1f) : new Rect(0f, 0f, 1f, 1f); + GUI.DrawTextureWithTexCoords(rect, AudioMixerDrawUtils.styles.leftToRightShadowTexture, texCoords); + } + public static void DrawScrollDropShadow(Rect scrollViewRect, float scrollY, float contentHeight) + { + if (Event.current.type == EventType.Repaint) + { + if (contentHeight <= scrollViewRect.height) + { + return; + } + Color color = GUI.color; + float num = (scrollY <= 10f) ? (scrollY / 10f) : 1f; + if (num < 1f) + { + GUI.color = new Color(1f, 1f, 1f, num); + } + if (num > 0f) + { + GUI.DrawTexture(new Rect(scrollViewRect.x, scrollViewRect.y, scrollViewRect.width, 20f), AudioMixerDrawUtils.styles.scrollShadowTexture); + } + if (num < 1f) + { + GUI.color = color; + } + float num2 = Mathf.Max(contentHeight - scrollViewRect.height, 0f); + float num3 = (num2 - scrollY <= 10f) ? ((num2 - scrollY) / 10f) : 1f; + if (num3 < 1f) + { + GUI.color = new Color(1f, 1f, 1f, num3); + } + if (num3 > 0f) + { + GUI.DrawTextureWithTexCoords(new Rect(scrollViewRect.x, scrollViewRect.yMax - 10f, scrollViewRect.width, 10f), AudioMixerDrawUtils.styles.scrollShadowTexture, new Rect(1f, 1f, -1f, -1f)); + } + if (num3 < 1f) + { + GUI.color = color; + } + } + } + public static void DrawRect(Rect rect, Color color) + { + Color color2 = GUI.color; + GUI.color = color; + GUI.Label(rect, GUIContent.Temp(string.Empty), EditorGUIUtility.whiteTextureStyle); + GUI.color = color2; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerEffectGUI.cs b/UnityEditor/UnityEditor/AudioMixerEffectGUI.cs new file mode 100644 index 00000000..c459037f --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerEffectGUI.cs @@ -0,0 +1,146 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal static class AudioMixerEffectGUI + { + private class ExposedParamContext + { + public AudioMixerController controller; + public AudioParameterPath path; + public ExposedParamContext(AudioMixerController controller, AudioParameterPath path) + { + this.controller = controller; + this.path = path; + } + } + private class ParameterTransitionOverrideContext + { + public AudioMixerController controller; + public GUID parameter; + public ParameterTransitionType type; + public ParameterTransitionOverrideContext(AudioMixerController controller, GUID parameter, ParameterTransitionType type) + { + this.controller = controller; + this.parameter = parameter; + this.type = type; + } + } + private class ParameterTransitionOverrideRemoveContext + { + public AudioMixerController controller; + public GUID parameter; + public ParameterTransitionOverrideRemoveContext(AudioMixerController controller, GUID parameter) + { + this.controller = controller; + this.parameter = parameter; + } + } + private const string kAudioSliderFloatFormat = "F2"; + private const string kExposedParameterUnicodeChar = " ➔"; + private static AudioMixerDrawUtils.Styles styles + { + get + { + return AudioMixerDrawUtils.styles; + } + } + public static void EffectHeader(string text) + { + GUILayout.Label(text, AudioMixerEffectGUI.styles.headerStyle, new GUILayoutOption[0]); + } + public static bool Slider(GUIContent label, ref float value, float displayScale, float displayExponent, string unit, float leftValue, float rightValue, AudioMixerController controller, AudioParameterPath path, params GUILayoutOption[] options) + { + EditorGUI.BeginChangeCheck(); + float fieldWidth = EditorGUIUtility.fieldWidth; + string kFloatFieldFormatString = EditorGUI.kFloatFieldFormatString; + bool flag = controller.ContainsExposedParameter(path.parameter); + EditorGUIUtility.fieldWidth = 70f; + EditorGUI.kFloatFieldFormatString = "F2"; + EditorGUI.s_UnitString = unit; + GUIContent label2 = label; + if (flag) + { + label2 = GUIContent.Temp(label.text + " ➔", label.tooltip); + } + float num = value * displayScale; + num = EditorGUILayout.PowerSlider(label2, num, leftValue * displayScale, rightValue * displayScale, displayExponent, options); + EditorGUI.s_UnitString = null; + EditorGUI.kFloatFieldFormatString = kFloatFieldFormatString; + EditorGUIUtility.fieldWidth = fieldWidth; + if (Event.current.type == EventType.ContextClick && GUILayoutUtility.topLevel.GetLast().Contains(Event.current.mousePosition)) + { + Event.current.Use(); + GenericMenu genericMenu = new GenericMenu(); + if (!flag) + { + genericMenu.AddItem(new GUIContent("Expose '" + path.ResolveStringPath(false) + "' to script"), false, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ExposePopupCallback), new AudioMixerEffectGUI.ExposedParamContext(controller, path)); + } + else + { + genericMenu.AddItem(new GUIContent("Unexpose"), false, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.UnexposePopupCallback), new AudioMixerEffectGUI.ExposedParamContext(controller, path)); + } + ParameterTransitionType parameterTransitionType; + bool transitionTypeOverride = controller.TargetSnapshot.GetTransitionTypeOverride(path.parameter, out parameterTransitionType); + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Linear Snapshot Transition"), parameterTransitionType == ParameterTransitionType.Lerp, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Lerp)); + genericMenu.AddItem(new GUIContent("Smoothstep Snapshot Transition"), parameterTransitionType == ParameterTransitionType.Smoothstep, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Smoothstep)); + genericMenu.AddItem(new GUIContent("Squared Snapshot Transition"), parameterTransitionType == ParameterTransitionType.Squared, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Squared)); + genericMenu.AddItem(new GUIContent("SquareRoot Snapshot Transition"), parameterTransitionType == ParameterTransitionType.SquareRoot, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.SquareRoot)); + genericMenu.AddItem(new GUIContent("BrickwallStart Snapshot Transition"), parameterTransitionType == ParameterTransitionType.BrickwallStart, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallStart)); + genericMenu.AddItem(new GUIContent("BrickwallEnd Snapshot Transition"), parameterTransitionType == ParameterTransitionType.BrickwallEnd, new GenericMenu.MenuFunction2(AudioMixerEffectGUI.ParameterTransitionOverrideCallback), new AudioMixerEffectGUI.ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallEnd)); + genericMenu.AddSeparator(string.Empty); + genericMenu.ShowAsContext(); + } + if (EditorGUI.EndChangeCheck()) + { + value = num / displayScale; + return true; + } + return false; + } + public static void ExposePopupCallback(object obj) + { + AudioMixerEffectGUI.ExposedParamContext exposedParamContext = (AudioMixerEffectGUI.ExposedParamContext)obj; + Undo.RecordObject(exposedParamContext.controller, "Expose Mixer Parameter"); + exposedParamContext.controller.AddExposedParameter(exposedParamContext.path); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + public static void UnexposePopupCallback(object obj) + { + AudioMixerEffectGUI.ExposedParamContext exposedParamContext = (AudioMixerEffectGUI.ExposedParamContext)obj; + Undo.RecordObject(exposedParamContext.controller, "Unexpose Mixer Parameter"); + exposedParamContext.controller.RemoveExposedParameter(exposedParamContext.path.parameter); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + public static void ParameterTransitionOverrideCallback(object obj) + { + AudioMixerEffectGUI.ParameterTransitionOverrideContext parameterTransitionOverrideContext = (AudioMixerEffectGUI.ParameterTransitionOverrideContext)obj; + Undo.RecordObject(parameterTransitionOverrideContext.controller, "Change Parameter Transition Type"); + if (parameterTransitionOverrideContext.type == ParameterTransitionType.Lerp) + { + parameterTransitionOverrideContext.controller.TargetSnapshot.ClearTransitionTypeOverride(parameterTransitionOverrideContext.parameter); + } + else + { + parameterTransitionOverrideContext.controller.TargetSnapshot.SetTransitionTypeOverride(parameterTransitionOverrideContext.parameter, parameterTransitionOverrideContext.type); + } + } + public static bool PopupButton(GUIContent label, GUIContent buttonContent, GUIStyle style, out Rect buttonRect, params GUILayoutOption[] options) + { + if (label != null) + { + Rect rect = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + int controlID = GUIUtility.GetControlID("EditorPopup".GetHashCode(), EditorGUIUtility.native, rect); + buttonRect = EditorGUI.PrefixLabel(rect, controlID, label); + } + else + { + Rect rect2 = GUILayoutUtility.GetRect(buttonContent, style, options); + buttonRect = rect2; + } + return EditorGUI.ButtonMouseDown(buttonRect, buttonContent, FocusType.Passive, style); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerEffectView.cs b/UnityEditor/UnityEditor/AudioMixerEffectView.cs new file mode 100644 index 00000000..c1ba5278 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerEffectView.cs @@ -0,0 +1,549 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerEffectView + { + private static class Texts + { + public static GUIContent editInPlaymode = new GUIContent("Edit in Playmode"); + public static GUIContent pitch = new GUIContent("Pitch"); + public static GUIContent addEffect = new GUIContent("Add Effect"); + public static GUIContent volume = new GUIContent("Volume"); + public static GUIContent sendLevel = new GUIContent("Send level"); + public static GUIContent bus = new GUIContent("Receive"); + public static GUIContent none = new GUIContent("None"); + public static GUIContent wet = new GUIContent("Wet", "Enables/disables wet/dry ratio on this effect. Note that this makes the DSP graph more complex and requires additional CPU and memory, so use it only when necessary."); + public static string dB = "dB"; + public static string percentage = "%"; + public static string cpuFormatString = " - CPU: {0:#0.00}%"; + } + private class EffectDragging + { + private readonly Color kMoveColorBorderAllowed = new Color(1f, 1f, 1f, 1f); + private readonly Color kMoveColorHiAllowed = new Color(1f, 1f, 1f, 0.3f); + private readonly Color kMoveColorLoAllowed = new Color(1f, 1f, 1f, 0f); + private readonly Color kMoveColorBorderDisallowed = new Color(0.8f, 0f, 0f, 1f); + private readonly Color kMoveColorHiDisallowed = new Color(1f, 0f, 0f, 0.3f); + private readonly Color kMoveColorLoDisallowed = new Color(1f, 0f, 0f, 0f); + private readonly int m_DragControlID; + private int m_MovingSrcIndex = -1; + private int m_MovingDstIndex = -1; + private bool m_MovingEffectAllowed; + private float m_MovingPos; + private Rect m_MovingRect = new Rect(0f, 0f, 0f, 0f); + private float m_DragHighlightPos = -1f; + private float m_DragHighlightHeight = 2f; + public int dragControlID + { + get + { + return this.m_DragControlID; + } + } + private bool isDragging + { + get + { + return this.m_MovingSrcIndex != -1 && GUIUtility.hotControl == this.m_DragControlID; + } + } + public EffectDragging() + { + this.m_DragControlID = GUIUtility.GetPermanentControlID(); + } + public bool IsDraggingIndex(int effectIndex) + { + return this.m_MovingSrcIndex == effectIndex && GUIUtility.hotControl == this.m_DragControlID; + } + public void HandleDragElement(int effectIndex, Rect effectRect, Rect dragRect, AudioMixerGroupController group, List allGroups) + { + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(this.m_DragControlID); + if (typeForControl != EventType.MouseDown) + { + if (typeForControl == EventType.Repaint) + { + if (effectIndex == this.m_MovingSrcIndex) + { + EditorGUI.BeginDisabledGroup(true); + AudioMixerDrawUtils.styles.channelStripAreaBackground.Draw(effectRect, false, false, false, false); + EditorGUI.EndDisabledGroup(); + } + } + } + else + { + if (current.button == 0 && dragRect.Contains(current.mousePosition) && GUIUtility.hotControl == 0) + { + this.m_MovingSrcIndex = effectIndex; + this.m_MovingPos = current.mousePosition.y; + this.m_MovingRect = new Rect(effectRect.x, effectRect.y - this.m_MovingPos, effectRect.width, effectRect.height); + GUIUtility.hotControl = this.m_DragControlID; + EditorGUIUtility.SetWantsMouseJumping(1); + current.Use(); + } + } + if (this.isDragging) + { + float num = effectRect.height * 0.5f; + float num2 = current.mousePosition.y - effectRect.y - num; + if (Mathf.Abs(num2) <= num) + { + int num3 = (num2 >= 0f) ? (effectIndex + 1) : effectIndex; + if (num3 != this.m_MovingDstIndex) + { + this.m_DragHighlightPos = ((num2 >= 0f) ? (effectRect.y + effectRect.height) : effectRect.y); + this.m_MovingDstIndex = num3; + this.m_MovingEffectAllowed = !AudioMixerController.WillMovingEffectCauseFeedback(allGroups, group, this.m_MovingSrcIndex, group, num3, null); + } + } + if (this.m_MovingDstIndex == this.m_MovingSrcIndex || this.m_MovingDstIndex == this.m_MovingSrcIndex + 1) + { + this.m_DragHighlightPos = 0f; + } + } + } + public void HandleDragging(Rect totalRect, AudioMixerGroupController group, AudioMixerController controller) + { + if (!this.isDragging) + { + return; + } + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(this.m_DragControlID); + switch (typeForControl) + { + case EventType.MouseUp: + current.Use(); + if (this.m_MovingSrcIndex != -1) + { + if (this.m_MovingDstIndex != -1 && this.m_MovingEffectAllowed) + { + List list = group.effects.ToList(); + if (AudioMixerController.MoveEffect(ref list, this.m_MovingSrcIndex, ref list, this.m_MovingDstIndex)) + { + group.effects = list.ToArray(); + } + } + this.m_MovingSrcIndex = -1; + this.m_MovingDstIndex = -1; + controller.m_HighlightEffectIndex = -1; + if (GUIUtility.hotControl == this.m_DragControlID) + { + GUIUtility.hotControl = 0; + } + EditorGUIUtility.SetWantsMouseJumping(0); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + GUIUtility.ExitGUI(); + } + return; + case EventType.MouseMove: + IL_35: + if (typeForControl != EventType.Repaint) + { + return; + } + if (this.m_DragHighlightPos > 0f) + { + float width = totalRect.width; + Color color = (!this.m_MovingEffectAllowed) ? this.kMoveColorLoDisallowed : this.kMoveColorLoAllowed; + Color color2 = (!this.m_MovingEffectAllowed) ? this.kMoveColorHiDisallowed : this.kMoveColorHiAllowed; + Color color3 = (!this.m_MovingEffectAllowed) ? this.kMoveColorBorderDisallowed : this.kMoveColorBorderAllowed; + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingRect.x, this.m_DragHighlightPos - 15f, width, 15f), color, color2); + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingRect.x, this.m_DragHighlightPos, width, 15f), color2, color); + AudioMixerDrawUtils.DrawGradientRect(new Rect(this.m_MovingRect.x, this.m_DragHighlightPos - this.m_DragHighlightHeight / 2f, width, this.m_DragHighlightHeight), color3, color3); + } + return; + case EventType.MouseDrag: + this.m_MovingPos = current.mousePosition.y; + current.Use(); + return; + } + goto IL_35; + } + } + private const float kMinPitch = 0.01f; + private const float kMaxPitch = 10f; + private const int kLabelWidth = 170; + private const int kTextboxWidth = 70; + private AudioMixerGroupController m_PrevGroup; + private readonly AudioMixerEffectView.EffectDragging m_EffectDragging; + private int m_LastNumChannels; + private AudioMixerEffectPlugin m_SharedPlugin = new AudioMixerEffectPlugin(); + private Dictionary m_CustomEffectGUIs = new Dictionary(); + public AudioMixerEffectView() + { + this.m_EffectDragging = new AudioMixerEffectView.EffectDragging(); + Type pluginType = typeof(IAudioEffectPluginGUI); + Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); + for (int i = 0; i < assemblies.Length; i++) + { + Assembly assembly = assemblies[i]; + try + { + Type[] types = assembly.GetTypes(); + foreach (Type current in + from t in types + where !t.IsAbstract && pluginType.IsAssignableFrom(t) + select t) + { + this.RegisterCustomGUI(Activator.CreateInstance(current) as IAudioEffectPluginGUI); + } + } + catch (Exception) + { + } + } + } + public bool RegisterCustomGUI(IAudioEffectPluginGUI gui) + { + string name = gui.Name; + if (this.m_CustomEffectGUIs.ContainsKey(name)) + { + IAudioEffectPluginGUI audioEffectPluginGUI = this.m_CustomEffectGUIs[name]; + Debug.LogError("Attempt to register custom GUI for plugin " + name + " failed as another plugin is already registered under this name."); + Debug.LogError(string.Concat(new string[] + { + "Plugin trying to register itself: ", + gui.Description, + " (Vendor: ", + gui.Vendor, + ")" + })); + Debug.LogError(string.Concat(new string[] + { + "Plugin already registered: ", + audioEffectPluginGUI.Description, + " (Vendor: ", + audioEffectPluginGUI.Vendor, + ")" + })); + return false; + } + this.m_CustomEffectGUIs[name] = gui; + return true; + } + public void OnGUI(AudioMixerGroupController group) + { + if (group == null) + { + return; + } + AudioMixerController controller = group.controller; + List allAudioGroupsSlow = controller.GetAllAudioGroupsSlow(); + Dictionary dictionary = new Dictionary(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + AudioMixerEffectController[] effects = current.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController key = effects[i]; + dictionary[key] = current; + } + } + Rect totalRect = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + if (EditorApplication.isPlaying) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginChangeCheck(); + GUILayout.Toggle(AudioSettings.editingInPlaymode, AudioMixerEffectView.Texts.editInPlaymode, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.Width(120f) + }); + if (EditorGUI.EndChangeCheck()) + { + AudioSettings.editingInPlaymode = !AudioSettings.editingInPlaymode; + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + EditorGUI.BeginDisabledGroup(!AudioMixerController.EditingTargetSnapshot()); + if (group != this.m_PrevGroup) + { + this.m_PrevGroup = group; + controller.m_HighlightEffectIndex = -1; + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + AudioMixerEffectView.DoInitialModule(group, controller, allAudioGroupsSlow); + for (int j = 0; j < group.effects.Length; j++) + { + this.DoEffectGUI(j, group, allAudioGroupsSlow, dictionary, ref controller.m_HighlightEffectIndex); + } + this.m_EffectDragging.HandleDragging(totalRect, group, controller); + GUILayout.Space(10f); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (EditorGUILayout.ButtonMouseDown(AudioMixerEffectView.Texts.addEffect, FocusType.Passive, GUISkin.current.button, new GUILayoutOption[0])) + { + GenericMenu genericMenu = new GenericMenu(); + Rect last = GUILayoutUtility.topLevel.GetLast(); + AudioMixerChannelStripView.AddEffectItemsToMenu(controller, group, group.effects.Length, string.Empty, genericMenu); + genericMenu.DropDown(last); + } + EditorGUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndVertical(); + } + public static float DoInitialModule(AudioMixerGroupController group, AudioMixerController controller, List allGroups) + { + Rect rect = EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + float valueForPitch = group.GetValueForPitch(controller, controller.TargetSnapshot); + if (AudioMixerEffectGUI.Slider(AudioMixerEffectView.Texts.pitch, ref valueForPitch, 100f, 1f, AudioMixerEffectView.Texts.percentage, 0.01f, 10f, controller, new AudioGroupParameterPath(group, group.GetGUIDForPitch()), new GUILayoutOption[0])) + { + group.SetValueForPitch(controller, controller.TargetSnapshot, valueForPitch); + } + GUILayout.Space(5f); + EditorGUILayout.EndVertical(); + AudioMixerDrawUtils.DrawSplitter(); + return rect.height; + } + public void DoEffectGUI(int effectIndex, AudioMixerGroupController group, List allGroups, Dictionary effectMap, ref int highlightEffectIndex) + { + Event current = Event.current; + AudioMixerController controller = group.controller; + AudioMixerEffectController audioMixerEffectController = group.effects[effectIndex]; + MixerParameterDefinition[] effectParameters = MixerEffectDefinitions.GetEffectParameters(audioMixerEffectController.effectName); + Rect effectRect = EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + bool flag = effectRect.Contains(current.mousePosition); + EventType typeForControl = current.GetTypeForControl(this.m_EffectDragging.dragControlID); + if (typeForControl == EventType.MouseMove && flag && highlightEffectIndex != effectIndex) + { + highlightEffectIndex = effectIndex; + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + Rect rect = GUILayoutUtility.GetRect(1f, 17f); + Rect rect2 = new Rect(rect.x + 6f, rect.y + 5f, 6f, 6f); + Rect position = new Rect(rect.x + 8f + 6f, rect.y, rect.width - 8f - 6f - 14f - 5f, rect.height); + Rect rect3 = new Rect(position.xMax, rect.y, 14f, 14f); + Rect rect4 = new Rect(rect.x, rect.y, rect.width - 14f - 5f, rect.height); + bool flag2 = EditorPrefs.GetBool(AudioMixerGroupEditor.kPrefKeyForShowCpuUsage, false) && EditorUtility.audioProfilingEnabled; + float num = (!EditorGUIUtility.isProSkin) ? 1f : 0.1f; + Color color = new Color(num, num, num, 0.2f); + Color color2 = GUI.color; + GUI.color = color; + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = color2; + Color effectColor = AudioMixerDrawUtils.GetEffectColor(audioMixerEffectController); + EditorGUI.DrawRect(rect2, effectColor); + GUI.Label(position, (!flag2) ? audioMixerEffectController.effectName : (audioMixerEffectController.effectName + string.Format(AudioMixerEffectView.Texts.cpuFormatString, audioMixerEffectController.GetCPUUsage(controller))), EditorStyles.boldLabel); + if (EditorGUI.ButtonMouseDown(rect3, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Passive, EditorStyles.inspectorTitlebarText)) + { + AudioMixerEffectView.ShowEffectContextMenu(group, audioMixerEffectController, effectIndex, controller, rect3); + } + if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) + { + AudioMixerEffectView.ShowEffectContextMenu(group, audioMixerEffectController, effectIndex, controller, new Rect(current.mousePosition.x, rect.y, 1f, rect.height)); + current.Use(); + } + if (typeForControl == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(rect4, MouseCursor.ResizeVertical, this.m_EffectDragging.dragControlID); + } + EditorGUI.BeginDisabledGroup(audioMixerEffectController.bypass || group.bypassEffects); + EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); + if (audioMixerEffectController.IsAttenuation()) + { + EditorGUILayout.BeginVertical(new GUILayoutOption[0]); + float valueForVolume = group.GetValueForVolume(controller, controller.TargetSnapshot); + if (AudioMixerEffectGUI.Slider(AudioMixerEffectView.Texts.volume, ref valueForVolume, 1f, 1f, AudioMixerEffectView.Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume(), controller, new AudioGroupParameterPath(group, group.GetGUIDForVolume()), new GUILayoutOption[0])) + { + group.SetValueForVolume(controller, controller.TargetSnapshot, valueForVolume); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + float[] array = new float[9]; + float[] array2 = new float[9]; + int num2 = group.controller.GetGroupVUInfo(group.groupID, true, ref array, ref array2); + if (current.type == EventType.Layout) + { + this.m_LastNumChannels = num2; + } + else + { + if (num2 != this.m_LastNumChannels) + { + HandleUtility.Repaint(); + } + num2 = this.m_LastNumChannels; + } + GUILayout.Space(4f); + for (int i = 0; i < num2; i++) + { + float value = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(array[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true); + float num3 = 1f - AudioMixerController.VolumeToScreenMapping(Mathf.Clamp(array2[i], AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume()), 1f, true); + EditorGUILayout.VUMeterHorizontal(value, num3, new GUILayoutOption[] + { + GUILayout.Height(10f) + }); + if (!EditorApplication.isPlaying && num3 > 0f) + { + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + } + GUILayout.Space(4f); + EditorGUILayout.EndVertical(); + } + if (audioMixerEffectController.IsSend()) + { + GUIContent buttonContent = (!(audioMixerEffectController.sendTarget == null)) ? GUIContent.Temp(audioMixerEffectController.GetSendTargetDisplayString(effectMap)) : AudioMixerEffectView.Texts.none; + Rect buttonRect; + if (AudioMixerEffectGUI.PopupButton(AudioMixerEffectView.Texts.bus, buttonContent, EditorStyles.popup, out buttonRect, new GUILayoutOption[0])) + { + AudioMixerEffectView.ShowBusPopupMenu(effectIndex, group, allGroups, effectMap, audioMixerEffectController, buttonRect); + } + if (audioMixerEffectController.sendTarget != null) + { + float valueForMixLevel = audioMixerEffectController.GetValueForMixLevel(controller, controller.TargetSnapshot); + if (AudioMixerEffectGUI.Slider(AudioMixerEffectView.Texts.sendLevel, ref valueForMixLevel, 1f, 1f, AudioMixerEffectView.Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect, controller, new AudioEffectParameterPath(group, audioMixerEffectController, audioMixerEffectController.GetGUIDForMixLevel()), new GUILayoutOption[0])) + { + audioMixerEffectController.SetValueForMixLevel(controller, controller.TargetSnapshot, valueForMixLevel); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + } + } + if (MixerEffectDefinitions.EffectCanBeSidechainTarget(audioMixerEffectController)) + { + bool flag3 = false; + foreach (AudioMixerGroupController current2 in allGroups) + { + AudioMixerEffectController[] effects = current2.effects; + for (int j = 0; j < effects.Length; j++) + { + AudioMixerEffectController audioMixerEffectController2 = effects[j]; + if (audioMixerEffectController2.IsSend() && audioMixerEffectController2.sendTarget == audioMixerEffectController) + { + flag3 = true; + break; + } + if (flag3) + { + break; + } + } + if (flag3) + { + break; + } + } + if (!flag3) + { + GUILayout.Label(new GUIContent("No Send sources connected.", EditorGUIUtility.warningIcon), new GUILayoutOption[0]); + } + } + if (audioMixerEffectController.enableWetMix && !audioMixerEffectController.IsReceive() && !audioMixerEffectController.IsDuckVolume() && !audioMixerEffectController.IsAttenuation() && !audioMixerEffectController.IsSend()) + { + float valueForMixLevel2 = audioMixerEffectController.GetValueForMixLevel(controller, controller.TargetSnapshot); + if (AudioMixerEffectGUI.Slider(AudioMixerEffectView.Texts.wet, ref valueForMixLevel2, 1f, 1f, AudioMixerEffectView.Texts.dB, AudioMixerController.kMinVolume, AudioMixerController.kMaxEffect, controller, new AudioEffectParameterPath(group, audioMixerEffectController, audioMixerEffectController.GetGUIDForMixLevel()), new GUILayoutOption[0])) + { + audioMixerEffectController.SetValueForMixLevel(controller, controller.TargetSnapshot, valueForMixLevel2); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + } + bool flag4 = true; + if (this.m_CustomEffectGUIs.ContainsKey(audioMixerEffectController.effectName)) + { + IAudioEffectPluginGUI audioEffectPluginGUI = this.m_CustomEffectGUIs[audioMixerEffectController.effectName]; + this.m_SharedPlugin.m_Controller = controller; + this.m_SharedPlugin.m_Effect = audioMixerEffectController; + this.m_SharedPlugin.m_ParamDefs = effectParameters; + flag4 = audioEffectPluginGUI.OnGUI(this.m_SharedPlugin); + } + if (flag4) + { + MixerParameterDefinition[] array3 = effectParameters; + for (int k = 0; k < array3.Length; k++) + { + MixerParameterDefinition mixerParameterDefinition = array3[k]; + float valueForParameter = audioMixerEffectController.GetValueForParameter(controller, controller.TargetSnapshot, mixerParameterDefinition.name); + if (AudioMixerEffectGUI.Slider(GUIContent.Temp(mixerParameterDefinition.name, mixerParameterDefinition.description), ref valueForParameter, mixerParameterDefinition.displayScale, mixerParameterDefinition.displayExponent, mixerParameterDefinition.units, mixerParameterDefinition.minRange, mixerParameterDefinition.maxRange, controller, new AudioEffectParameterPath(group, audioMixerEffectController, audioMixerEffectController.GetGUIDForParameter(mixerParameterDefinition.name)), new GUILayoutOption[0])) + { + audioMixerEffectController.SetValueForParameter(controller, controller.TargetSnapshot, mixerParameterDefinition.name, valueForParameter); + } + } + if (effectParameters.Length > 0) + { + GUILayout.Space(6f); + } + } + EditorGUI.EndDisabledGroup(); + this.m_EffectDragging.HandleDragElement(effectIndex, effectRect, rect4, group, allGroups); + EditorGUILayout.EndVertical(); + EditorGUILayout.EndVertical(); + AudioMixerDrawUtils.DrawSplitter(); + } + private static void ShowEffectContextMenu(AudioMixerGroupController group, AudioMixerEffectController effect, int effectIndex, AudioMixerController controller, Rect buttonRect) + { + GenericMenu genericMenu = new GenericMenu(); + if (!effect.IsReceive()) + { + if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsDuckVolume()) + { + genericMenu.AddItem(new GUIContent("Allow Wet Mixing (causes higher memory usage)"), effect.enableWetMix, delegate + { + effect.enableWetMix = !effect.enableWetMix; + }); + genericMenu.AddItem(new GUIContent("Bypass"), effect.bypass, delegate + { + effect.bypass = !effect.bypass; + controller.UpdateBypass(); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + }); + genericMenu.AddSeparator(string.Empty); + } + genericMenu.AddItem(new GUIContent("Copy effect settings to all snapshots"), false, delegate + { + Undo.RecordObject(controller, "Copy effect settings to all snapshots"); + if (effect.IsAttenuation()) + { + controller.CopyAttenuationToAllSnapshots(group, controller.TargetSnapshot); + } + else + { + controller.CopyEffectSettingsToAllSnapshots(group, effectIndex, controller.TargetSnapshot, effect.IsSend()); + } + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + }); + if (!effect.IsAttenuation() && !effect.IsSend() && !effect.IsDuckVolume() && effect.enableWetMix) + { + genericMenu.AddItem(new GUIContent("Copy effect settings to all snapshots, including wet level"), false, delegate + { + Undo.RecordObject(controller, "Copy effect settings to all snapshots, including wet level"); + controller.CopyEffectSettingsToAllSnapshots(group, effectIndex, controller.TargetSnapshot, true); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + }); + } + genericMenu.AddSeparator(string.Empty); + } + AudioMixerChannelStripView.AddEffectItemsToMenu(controller, group, effectIndex, "Add effect before/", genericMenu); + AudioMixerChannelStripView.AddEffectItemsToMenu(controller, group, effectIndex + 1, "Add effect after/", genericMenu); + if (!effect.IsAttenuation()) + { + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Remove this effect"), false, delegate + { + controller.ClearSendConnectionsTo(effect); + controller.RemoveEffect(effect, group); + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + }); + } + genericMenu.DropDown(buttonRect); + } + private static void ShowBusPopupMenu(int effectIndex, AudioMixerGroupController group, List allGroups, Dictionary effectMap, AudioMixerEffectController effect, Rect buttonRect) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("None"), false, new GenericMenu.MenuFunction2(AudioMixerChannelStripView.ConnectSendPopupCallback), new AudioMixerChannelStripView.ConnectSendContext(effect, null)); + genericMenu.AddSeparator(string.Empty); + AudioMixerChannelStripView.AddMenuItemsForReturns(genericMenu, string.Empty, effectIndex, group, allGroups, effectMap, effect, true); + if (genericMenu.GetItemCount() == 2) + { + genericMenu.AddDisabledItem(new GUIContent("No valid Receive targets found")); + } + genericMenu.DropDown(buttonRect); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerExposedParameterView.cs b/UnityEditor/UnityEditor/AudioMixerExposedParameterView.cs new file mode 100644 index 00000000..61bd04fa --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerExposedParameterView.cs @@ -0,0 +1,158 @@ +using System; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerExposedParameterView + { + private ReorderableListWithRenameAndScrollView m_ReorderableListWithRenameAndScrollView; + private AudioMixerController m_Controller; + private SerializedObject m_ControllerSerialized; + private ReorderableListWithRenameAndScrollView.State m_State; + private float height + { + get + { + return this.m_ReorderableListWithRenameAndScrollView.list.GetHeight(); + } + } + public AudioMixerExposedParameterView(ReorderableListWithRenameAndScrollView.State state) + { + this.m_State = state; + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + this.m_Controller = controller; + if (this.m_Controller) + { + this.m_Controller.ChangedExposedParameter += new ChangedExposedParameterHandler(this.RecreateListControl); + } + this.RecreateListControl(); + } + public void RecreateListControl() + { + if (this.m_Controller != null) + { + this.m_ControllerSerialized = new SerializedObject(this.m_Controller); + SerializedProperty elements = this.m_ControllerSerialized.FindProperty("m_ExposedParameters"); + ReorderableList reorderableList = new ReorderableList(this.m_ControllerSerialized, elements, false, false, false, false); + reorderableList.onReorderCallback = new ReorderableList.ReorderCallbackDelegate(this.EndDragChild); + ReorderableList expr_57 = reorderableList; + expr_57.drawElementCallback = (ReorderableList.ElementCallbackDelegate)Delegate.Combine(expr_57.drawElementCallback, new ReorderableList.ElementCallbackDelegate(this.DrawElement)); + reorderableList.elementHeight = 16f; + reorderableList.headerHeight = 0f; + reorderableList.footerHeight = 0f; + reorderableList.showDefaultBackground = false; + this.m_ReorderableListWithRenameAndScrollView = new ReorderableListWithRenameAndScrollView(reorderableList, this.m_State); + ReorderableListWithRenameAndScrollView expr_B8 = this.m_ReorderableListWithRenameAndScrollView; + expr_B8.onNameChangedAtIndex = (Action)Delegate.Combine(expr_B8.onNameChangedAtIndex, new Action(this.NameChanged)); + ReorderableListWithRenameAndScrollView expr_DF = this.m_ReorderableListWithRenameAndScrollView; + expr_DF.onDeleteItemAtIndex = (Action)Delegate.Combine(expr_DF.onDeleteItemAtIndex, new Action(this.Delete)); + ReorderableListWithRenameAndScrollView expr_106 = this.m_ReorderableListWithRenameAndScrollView; + expr_106.onGetNameAtIndex = (Func)Delegate.Combine(expr_106.onGetNameAtIndex, new Func(this.GetNameOfElement)); + } + } + public void OnGUI(Rect rect) + { + if (this.m_Controller == null) + { + return; + } + this.m_ReorderableListWithRenameAndScrollView.OnGUI(rect); + } + public void OnContextClick(int itemIndex) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Unexpose"), false, delegate(object data) + { + this.Delete((int)data); + }, itemIndex); + genericMenu.AddItem(new GUIContent("Rename"), false, delegate(object data) + { + this.m_ReorderableListWithRenameAndScrollView.BeginRename((int)data, 0f); + }, itemIndex); + genericMenu.ShowAsContext(); + } + private void DrawElement(Rect rect, int index, bool isActive, bool isFocused) + { + Event current = Event.current; + if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) + { + this.OnContextClick(index); + current.Use(); + } + if (Event.current.type != EventType.Repaint) + { + return; + } + EditorGUI.BeginDisabledGroup(true); + this.m_ReorderableListWithRenameAndScrollView.elementStyleRightAligned.Draw(rect, this.GetInfoString(index), false, false, false, false); + EditorGUI.EndDisabledGroup(); + } + public Vector2 CalcSize() + { + float num = 0f; + for (int i = 0; i < this.m_ReorderableListWithRenameAndScrollView.list.count; i++) + { + float num2 = this.WidthOfRow(i, this.m_ReorderableListWithRenameAndScrollView.elementStyle, this.m_ReorderableListWithRenameAndScrollView.elementStyleRightAligned); + if (num2 > num) + { + num = num2; + } + } + return new Vector2(num, this.height); + } + private string GetInfoString(int index) + { + ExposedAudioParameter exposedAudioParameter = this.m_Controller.exposedParameters[index]; + return this.m_Controller.ResolveExposedParameterPath(exposedAudioParameter.guid, false); + } + private float WidthOfRow(int index, GUIStyle leftStyle, GUIStyle rightStyle) + { + string infoString = this.GetInfoString(index); + Vector2 vector = rightStyle.CalcSize(GUIContent.Temp(infoString)); + return leftStyle.CalcSize(GUIContent.Temp(this.GetNameOfElement(index))).x + vector.x + 25f; + } + private string GetNameOfElement(int index) + { + ExposedAudioParameter exposedAudioParameter = this.m_Controller.exposedParameters[index]; + return exposedAudioParameter.name; + } + public void NameChanged(int index, string newName) + { + if (newName.Length > 64) + { + newName = newName.Substring(0, 64); + Debug.LogWarning(string.Concat(new object[] + { + "Maximum name length of an exposed parameter is ", + 64, + " characters. Name truncated to '", + newName, + "'" + })); + } + ExposedAudioParameter[] exposedParameters = this.m_Controller.exposedParameters; + exposedParameters[index].name = newName; + this.m_Controller.exposedParameters = exposedParameters; + } + private void Delete(int index) + { + if (this.m_Controller != null) + { + Undo.RecordObject(this.m_Controller, "Unexpose Mixer Parameter"); + ExposedAudioParameter exposedAudioParameter = this.m_Controller.exposedParameters[index]; + this.m_Controller.RemoveExposedParameter(exposedAudioParameter.guid); + } + } + public void EndDragChild(ReorderableList list) + { + this.m_ControllerSerialized.ApplyModifiedProperties(); + } + public void OnEvent() + { + this.m_ReorderableListWithRenameAndScrollView.OnEvent(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerExposedParametersPopup.cs b/UnityEditor/UnityEditor/AudioMixerExposedParametersPopup.cs new file mode 100644 index 00000000..6b318ba1 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerExposedParametersPopup.cs @@ -0,0 +1,48 @@ +using System; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerExposedParametersPopup : PopupWindowContent + { + private static GUIContent m_ButtonContent = new GUIContent(string.Empty, "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 ..'."); + private static int m_LastNumExposedParams = -1; + private readonly AudioMixerExposedParameterView m_ExposedParametersView; + private AudioMixerExposedParametersPopup(AudioMixerController controller) + { + this.m_ExposedParametersView = new AudioMixerExposedParameterView(new ReorderableListWithRenameAndScrollView.State()); + this.m_ExposedParametersView.OnMixerControllerChanged(controller); + } + internal static void Popup(AudioMixerController controller, GUIStyle style, params GUILayoutOption[] options) + { + GUIContent buttonContent = AudioMixerExposedParametersPopup.GetButtonContent(controller); + Rect rect = GUILayoutUtility.GetRect(buttonContent, style, options); + if (EditorGUI.ButtonMouseDown(rect, buttonContent, FocusType.Passive, style)) + { + PopupWindow.Show(rect, new AudioMixerExposedParametersPopup(controller)); + } + } + private static GUIContent GetButtonContent(AudioMixerController controller) + { + if (controller.numExposedParameters != AudioMixerExposedParametersPopup.m_LastNumExposedParams) + { + AudioMixerExposedParametersPopup.m_ButtonContent.text = string.Format("Exposed Parameters ({0})", controller.numExposedParameters); + AudioMixerExposedParametersPopup.m_LastNumExposedParams = controller.numExposedParameters; + } + return AudioMixerExposedParametersPopup.m_ButtonContent; + } + public override void OnGUI(Rect rect) + { + this.m_ExposedParametersView.OnEvent(); + this.m_ExposedParametersView.OnGUI(rect); + } + public override Vector2 GetWindowSize() + { + Vector2 result = this.m_ExposedParametersView.CalcSize(); + result.x = Math.Max(result.x, 125f); + result.y = Math.Max(result.y, 23f); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerGroupEditor.cs b/UnityEditor/UnityEditor/AudioMixerGroupEditor.cs new file mode 100644 index 00000000..bc89e18c --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerGroupEditor.cs @@ -0,0 +1,71 @@ +using System; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(AudioMixerGroupController))] + internal class AudioMixerGroupEditor : Editor + { + private AudioMixerEffectView m_EffectView; + private readonly TickTimerHelper m_Ticker = new TickTimerHelper(0.05); + public static readonly string kPrefKeyForShowCpuUsage = "AudioMixerShowCPU"; + private void OnEnable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + private void OnDisable() + { + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + } + public void Update() + { + if (EditorApplication.isPlaying && this.m_Ticker.DoTick()) + { + base.Repaint(); + } + } + public override void OnInspectorGUI() + { + AudioMixerDrawUtils.InitStyles(); + if (this.m_EffectView == null) + { + this.m_EffectView = new AudioMixerEffectView(); + } + AudioMixerGroupController group = this.target as AudioMixerGroupController; + this.m_EffectView.OnGUI(group); + } + public override bool UseDefaultMargins() + { + return false; + } + internal override void DrawHeaderHelpAndSettingsGUI(Rect r) + { + if (this.m_EffectView == null) + { + return; + } + AudioMixerGroupController audioMixerGroupController = this.target as AudioMixerGroupController; + base.DrawHeaderHelpAndSettingsGUI(r); + Rect position = new Rect(r.x + 44f, r.yMax - 20f, r.width - 50f, 15f); + GUI.Label(position, GUIContent.Temp(audioMixerGroupController.controller.name), EditorStyles.miniLabel); + } + [MenuItem("CONTEXT/AudioMixerGroupController/Copy all effect settings to all snapshots")] + private static void CopyAllEffectToSnapshots(MenuCommand command) + { + AudioMixerGroupController audioMixerGroupController = command.context as AudioMixerGroupController; + AudioMixerController controller = audioMixerGroupController.controller; + if (controller == null) + { + return; + } + Undo.RecordObject(controller, "Copy all effect settings to all snapshots"); + controller.CopyAllSettingsToAllSnapshots(audioMixerGroupController, controller.TargetSnapshot); + } + [MenuItem("CONTEXT/AudioMixerGroupController/Toggle CPU usage display (only available on first editor instance)")] + private static void ShowCPUUsage(MenuCommand command) + { + bool @bool = EditorPrefs.GetBool(AudioMixerGroupEditor.kPrefKeyForShowCpuUsage, false); + EditorPrefs.SetBool(AudioMixerGroupEditor.kPrefKeyForShowCpuUsage, !@bool); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerGroupPopupContext.cs b/UnityEditor/UnityEditor/AudioMixerGroupPopupContext.cs new file mode 100644 index 00000000..a3099a68 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerGroupPopupContext.cs @@ -0,0 +1,23 @@ +using System; +using UnityEditor.Audio; +namespace UnityEditor +{ + internal class AudioMixerGroupPopupContext + { + public AudioMixerController controller; + public AudioMixerGroupController[] groups; + public AudioMixerGroupPopupContext(AudioMixerController controller, AudioMixerGroupController group) + { + this.controller = controller; + this.groups = new AudioMixerGroupController[] + { + group + }; + } + public AudioMixerGroupPopupContext(AudioMixerController controller, AudioMixerGroupController[] groups) + { + this.controller = controller; + this.groups = groups; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerGroupSelector.cs b/UnityEditor/UnityEditor/AudioMixerGroupSelector.cs new file mode 100644 index 00000000..e3dc2db4 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerGroupSelector.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerGroupSelector : PopupWindowContent + { + internal class GroupTreeViewGUI : TreeViewGUI + { + private const float k_SpaceBetween = 25f; + private const float k_HeaderHeight = 20f; + private readonly Texture2D k_AudioGroupIcon = EditorGUIUtility.FindTexture("AudioMixerGroup Icon"); + private readonly Texture2D k_AudioListenerIcon = EditorGUIUtility.FindTexture("AudioListener Icon"); + private List m_RowRects = new List(); + public GroupTreeViewGUI(TreeView treeView) : base(treeView) + { + } + public override Rect OnRowGUI(TreeViewItem item, int row, float rowWidth, bool selected, bool focused) + { + Rect rect = this.m_RowRects[row]; + float k_FoldoutWidth = this.k_FoldoutWidth; + if (item.id == 0) + { + this.k_FoldoutWidth = 0f; + } + this.DoNodeGUI(rect, item, selected, focused, false); + if (item.id == 0) + { + this.k_FoldoutWidth = k_FoldoutWidth; + } + bool flag = item.parent == this.m_TreeView.data.root; + bool flag2 = item.id == 0; + if (flag && !flag2) + { + AudioMixerController controller = (item.userData as AudioMixerGroupController).controller; + GUI.Label(new Rect(rect.x + 2f, rect.y - 18f, rect.width, 18f), GUIContent.Temp(controller.name), EditorStyles.boldLabel); + } + return rect; + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item != null && item.icon != null) + { + return item.icon; + } + if (item.id == 0) + { + return this.k_AudioListenerIcon; + } + return this.k_AudioGroupIcon; + } + protected override void SyncFakeItem() + { + } + protected override void RenameEnded() + { + } + private bool IsController(TreeViewItem item) + { + return item.parent == this.m_TreeView.data.root && item.id != 0; + } + public void CalculateRowRects() + { + float width = GUIClip.visibleRect.width; + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + this.m_RowRects = new List(visibleRows.Count); + float num = 0f; + for (int i = 0; i < visibleRows.Count; i++) + { + bool flag = this.IsController(visibleRows[i]); + num += ((!flag) ? 0f : 25f); + float k_LineHeight = this.k_LineHeight; + this.m_RowRects.Add(new Rect(0f, num, width, k_LineHeight)); + num += k_LineHeight; + } + } + public override Vector2 GetTotalSize(List rows) + { + if (this.m_RowRects.Count == 0) + { + return new Vector2(1f, 1f); + } + float maxWidth = base.GetMaxWidth(rows); + return new Vector2(maxWidth + 10f, this.m_RowRects[this.m_RowRects.Count - 1].yMax); + } + public override float GetTopPixelOfRow(int row, List rows) + { + return this.m_RowRects[row].y; + } + public override float GetHeightOfLastRow() + { + return this.m_RowRects[this.m_RowRects.Count - 1].height; + } + public override int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) + { + return (int)Mathf.Floor(heightOfTreeView / this.k_LineHeight); + } + public override void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) + { + if (rows.Count != this.m_RowRects.Count) + { + Debug.LogError("Mismatch in state: rows vs cached rects"); + } + int num = -1; + int num2 = -1; + for (int i = 0; i < this.m_RowRects.Count; i++) + { + bool flag = (this.m_RowRects[i].y > topPixel && this.m_RowRects[i].y < topPixel + heightInPixels) || (this.m_RowRects[i].yMax > topPixel && this.m_RowRects[i].yMax < topPixel + heightInPixels); + if (flag) + { + if (num == -1) + { + num = i; + } + num2 = i; + } + } + if (num != -1 && num2 != -1) + { + firstRowVisible = num; + lastRowVisible = num2; + } + else + { + firstRowVisible = 0; + lastRowVisible = rows.Count - 1; + } + } + } + internal class TreeViewDataSourceForMixers : TreeViewDataSource + { + public AudioMixerController ignoreThisController + { + get; + private set; + } + public TreeViewDataSourceForMixers(TreeView treeView, AudioMixerController ignoreController) : base(treeView) + { + base.showRootNode = false; + base.rootIsCollapsable = false; + this.ignoreThisController = ignoreController; + } + public override void FetchData() + { + int depth = -1; + this.m_RootItem = new TreeViewItem(1010101010, depth, null, "InvisibleRoot"); + base.expandedIDs.Add(this.m_RootItem.id); + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(new SearchFilter + { + classNames = new string[] + { + "AudioMixerController" + } + }); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + AudioMixerController audioMixerController = hierarchyProperty.pptrValue as AudioMixerController; + bool flag = AudioMixerController.CheckForCyclicReferences(this.ignoreThisController, audioMixerController.outputAudioMixerGroup); + if (audioMixerController && audioMixerController != this.ignoreThisController && !flag) + { + list.Add(audioMixerController); + } + } + List list2 = new List(); + list2.Add(new TreeViewItem(0, 0, this.m_RootItem, AudioMixerGroupSelector.s_NoneText)); + foreach (AudioMixerController current in list) + { + list2.Add(this.BuildSubTree(current)); + } + this.m_RootItem.children = list2; + this.SetExpandedIDs(base.expandedIDs.ToArray()); + } + private TreeViewItem BuildSubTree(AudioMixerController controller) + { + AudioMixerGroupController masterGroup = controller.masterGroup; + TreeViewItem treeViewItem = new TreeViewItem(masterGroup.GetInstanceID(), 0, this.m_RootItem, masterGroup.name); + treeViewItem.userData = masterGroup; + this.AddChildrenRecursive(masterGroup, treeViewItem); + return treeViewItem; + } + private void AddChildrenRecursive(AudioMixerGroupController group, TreeViewItem item) + { + item.children = new List(group.children.Length); + for (int i = 0; i < item.children.Count; i++) + { + item.children.Add(new TreeViewItem(group.children[i].GetInstanceID(), item.depth + 1, item, group.children[i].name)); + item.children[i].userData = group.children[i]; + this.AddChildrenRecursive(group.children[i], item.children[i]); + } + } + public AudioMixerGroupController GetGroup(int instanceID) + { + TreeViewItem treeViewItem = this.m_TreeView.FindNode(instanceID); + if (treeViewItem != null) + { + return (AudioMixerGroupController)treeViewItem.userData; + } + return null; + } + public override bool CanBeMultiSelected(TreeViewItem item) + { + return false; + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return false; + } + } + private const int kNoneItemID = 0; + private AudioMixerGroupController m_OriginalSelection; + private TreeView m_TreeView; + private TreeViewState m_TreeViewState; + private string m_SearchFilter; + private bool m_FocusSearchFilter; + private Action m_SelectionCallback; + private AudioMixerController m_IgnoreThisController; + public static string s_NoneText = "Audio Listener"; + private bool m_RecalculateWindowSize; + private Vector2 m_WindowSize = new Vector2(250f, 5f); + public AudioMixerGroupSelector(AudioMixerGroupController originalSelection, AudioMixerController ignoreThisController, Action selectionCallback) + { + this.m_OriginalSelection = originalSelection; + this.m_SelectionCallback = selectionCallback; + this.m_IgnoreThisController = ignoreThisController; + } + private void ResizeWindow() + { + this.m_RecalculateWindowSize = true; + } + private void InitTreeView(Rect rect) + { + this.m_TreeViewState = new TreeViewState(); + this.m_TreeView = new TreeView(base.editorWindow, this.m_TreeViewState); + AudioMixerGroupSelector.GroupTreeViewGUI groupTreeViewGUI = new AudioMixerGroupSelector.GroupTreeViewGUI(this.m_TreeView); + AudioMixerGroupSelector.TreeViewDataSourceForMixers treeViewDataSourceForMixers = new AudioMixerGroupSelector.TreeViewDataSourceForMixers(this.m_TreeView, this.m_IgnoreThisController); + AudioMixerGroupSelector.TreeViewDataSourceForMixers expr_41 = treeViewDataSourceForMixers; + expr_41.onVisibleRowsChanged = (Action)Delegate.Combine(expr_41.onVisibleRowsChanged, new Action(groupTreeViewGUI.CalculateRowRects)); + AudioMixerGroupSelector.TreeViewDataSourceForMixers expr_63 = treeViewDataSourceForMixers; + expr_63.onVisibleRowsChanged = (Action)Delegate.Combine(expr_63.onVisibleRowsChanged, new Action(this.ResizeWindow)); + this.m_TreeView.deselectOnUnhandledMouseDown = true; + this.m_TreeView.Init(rect, treeViewDataSourceForMixers, groupTreeViewGUI, null); + this.m_TreeView.ReloadData(); + this.m_TreeView.selectionChangedCallback = new Action(this.OnItemSelectionChanged); + this.m_TreeView.itemDoubleClickedCallback = new Action(this.OnItemDoubleClicked); + this.m_TreeView.SetSelection(new int[] + { + (!(this.m_OriginalSelection != null)) ? 0 : this.m_OriginalSelection.GetInstanceID() + }, true); + } + public override void OnGUI(Rect rect) + { + if (this.m_TreeView == null) + { + this.InitTreeView(rect); + } + Rect treeViewRect = new Rect(rect.x, 0f, rect.width, rect.height); + this.HandleKeyboard(); + this.TreeViewArea(treeViewRect); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.Cancel(); + } + } + private void OnItemDoubleClicked(int id) + { + base.editorWindow.Close(); + } + private void OnItemSelectionChanged(int[] selection) + { + if (this.m_SelectionCallback != null) + { + AudioMixerGroupController obj = null; + if (selection.Length > 0) + { + obj = this.GetGroupByID(selection[0]); + } + this.m_SelectionCallback(obj); + } + } + private AudioMixerGroupController GetGroupByID(int id) + { + AudioMixerGroupSelector.TreeViewDataSourceForMixers treeViewDataSourceForMixers = this.m_TreeView.data as AudioMixerGroupSelector.TreeViewDataSourceForMixers; + return treeViewDataSourceForMixers.GetGroup(id); + } + private void Repaint() + { + base.editorWindow.Repaint(); + } + private void HandleKeyboard() + { + if (Event.current.type != EventType.KeyDown) + { + return; + } + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.Return && keyCode != KeyCode.KeypadEnter) + { + return; + } + Event.current.Use(); + base.editorWindow.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + } + private void Cancel() + { + if (this.m_SelectionCallback != null) + { + this.m_SelectionCallback(this.m_OriginalSelection); + } + base.editorWindow.Close(); + GUI.changed = true; + GUIUtility.ExitGUI(); + } + private void FilterSettingsChanged() + { + } + private void TreeViewArea(Rect treeViewRect) + { + int controlID = GUIUtility.GetControlID("Tree".GetHashCode(), FocusType.Keyboard); + GUIUtility.keyboardControl = controlID; + bool flag = this.m_TreeView.data.GetVisibleRows().Count > 0; + if (flag) + { + this.m_TreeView.OnGUI(treeViewRect, controlID); + } + else + { + EditorGUI.BeginDisabledGroup(true); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(GUIContent.Temp("No Audio Mixers available"), new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.EndDisabledGroup(); + } + } + private void SearchArea(Rect toolbarRect) + { + GUI.Label(toolbarRect, GUIContent.none, "ObjectPickerToolbar"); + bool flag = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; + GUI.SetNextControlName("SearchFilter"); + string text = EditorGUI.SearchField(new Rect(5f, 5f, toolbarRect.width - 10f, 15f), this.m_SearchFilter); + if (flag && Event.current.type == EventType.Used) + { + if (this.m_SearchFilter == string.Empty) + { + this.Cancel(); + } + this.m_FocusSearchFilter = true; + } + if (text != this.m_SearchFilter || this.m_FocusSearchFilter) + { + this.m_SearchFilter = text; + this.FilterSettingsChanged(); + this.Repaint(); + } + if (this.m_FocusSearchFilter) + { + EditorGUI.FocusTextInControl("SearchFilter"); + this.m_FocusSearchFilter = false; + } + } + public override Vector2 GetWindowSize() + { + if (this.m_RecalculateWindowSize) + { + Vector2 totalSize = this.m_TreeView.gui.GetTotalSize(this.m_TreeView.data.GetVisibleRows()); + float val = 120f; + this.m_WindowSize.x = Math.Max(val, totalSize.x); + float num = 7f; + float max = 600f; + float min = 18f; + this.m_WindowSize.y = Mathf.Clamp(totalSize.y + num, min, max); + this.m_RecalculateWindowSize = false; + } + return this.m_WindowSize; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerGroupTreeView.cs b/UnityEditor/UnityEditor/AudioMixerGroupTreeView.cs new file mode 100644 index 00000000..294ef463 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerGroupTreeView.cs @@ -0,0 +1,412 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerGroupTreeView + { + private class Styles + { + public GUIStyle optionsButton = "PaneOptions"; + public GUIContent header = new GUIContent("Groups", "An Audio Mixer Group is used by e.g Audio Sources to modify the audio output before it reaches the Audio Listener. An Audio Mixer Group will route its output to another Audio Mixer Group if it is made a child of that group. The Master Group will route its output to the Audio Listener if it doesn't route its output into another Mixer."); + public GUIContent addText = new GUIContent("+", "Add child group"); + public Texture2D audioMixerGroupIcon = EditorGUIUtility.FindTexture("AudioMixerGroup Icon"); + } + private AudioMixerController m_Controller; + private AudioGroupDataSource m_AudioGroupTreeDataSource; + private TreeViewState m_AudioGroupTreeState; + private TreeView m_AudioGroupTree; + private int m_TreeViewKeyboardControlID; + private AudioGroupTreeViewGUI m_TreeViewGUI; + private AudioMixerGroupController m_ScrollToItem; + private static AudioMixerGroupTreeView.Styles s_Styles; + public AudioMixerController Controller + { + get + { + return this.m_Controller; + } + } + public AudioMixerGroupController ScrollToItem + { + get + { + return this.m_ScrollToItem; + } + } + public AudioMixerGroupTreeView(AudioMixerWindow mixerWindow, TreeViewState treeState) + { + this.m_AudioGroupTreeState = treeState; + this.m_AudioGroupTree = new TreeView(mixerWindow, this.m_AudioGroupTreeState); + this.m_AudioGroupTree.deselectOnUnhandledMouseDown = false; + TreeView expr_31 = this.m_AudioGroupTree; + expr_31.selectionChangedCallback = (Action)Delegate.Combine(expr_31.selectionChangedCallback, new Action(this.OnTreeSelectionChanged)); + TreeView expr_58 = this.m_AudioGroupTree; + expr_58.contextClickCallback = (Action)Delegate.Combine(expr_58.contextClickCallback, new Action(this.OnTreeViewContextClick)); + TreeView expr_7F = this.m_AudioGroupTree; + expr_7F.expandedStateChanged = (Action)Delegate.Combine(expr_7F.expandedStateChanged, new Action(this.SaveExpandedState)); + this.m_TreeViewGUI = new AudioGroupTreeViewGUI(this.m_AudioGroupTree); + AudioGroupTreeViewGUI expr_B7 = this.m_TreeViewGUI; + expr_B7.NodeWasToggled = (Action)Delegate.Combine(expr_B7.NodeWasToggled, new Action(this.OnNodeToggled)); + this.m_AudioGroupTreeDataSource = new AudioGroupDataSource(this.m_AudioGroupTree, this.m_Controller); + this.m_AudioGroupTree.Init(mixerWindow.position, this.m_AudioGroupTreeDataSource, this.m_TreeViewGUI, new AudioGroupTreeViewDragging(this.m_AudioGroupTree, this)); + this.m_AudioGroupTree.ReloadData(); + } + public void ReloadTree() + { + this.m_AudioGroupTree.ReloadData(); + if (this.m_Controller != null) + { + this.m_Controller.SanitizeGroupViews(); + this.m_Controller.OnSubAssetChanged(); + } + } + public void AddChildGroupPopupCallback(object obj) + { + AudioMixerGroupPopupContext audioMixerGroupPopupContext = (AudioMixerGroupPopupContext)obj; + if (audioMixerGroupPopupContext.groups != null && audioMixerGroupPopupContext.groups.Length > 0) + { + this.AddAudioMixerGroup(audioMixerGroupPopupContext.groups[0]); + } + } + public void AddSiblingGroupPopupCallback(object obj) + { + AudioMixerGroupPopupContext audioMixerGroupPopupContext = (AudioMixerGroupPopupContext)obj; + if (audioMixerGroupPopupContext.groups != null && audioMixerGroupPopupContext.groups.Length > 0) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = this.m_AudioGroupTree.FindNode(audioMixerGroupPopupContext.groups[0].GetInstanceID()) as AudioMixerTreeViewNode; + if (audioMixerTreeViewNode != null) + { + AudioMixerTreeViewNode audioMixerTreeViewNode2 = audioMixerTreeViewNode.parent as AudioMixerTreeViewNode; + this.AddAudioMixerGroup(audioMixerTreeViewNode2.group); + } + } + } + public void AddAudioMixerGroup(AudioMixerGroupController parent) + { + if (parent == null || this.m_Controller == null) + { + return; + } + Undo.RecordObjects(new UnityEngine.Object[] + { + this.m_Controller, + parent + }, "Add Child Group"); + AudioMixerGroupController audioMixerGroupController = this.m_Controller.CreateNewGroup("New Group", true); + this.m_Controller.AddChildToParent(audioMixerGroupController, parent); + this.m_Controller.AddGroupToCurrentView(audioMixerGroupController); + Selection.objects = new AudioMixerGroupController[] + { + audioMixerGroupController + }; + this.m_Controller.OnUnitySelectionChanged(); + this.m_AudioGroupTree.SetSelection(new int[] + { + audioMixerGroupController.GetInstanceID() + }, true); + this.ReloadTree(); + this.m_AudioGroupTree.BeginNameEditing(0f); + } + private static string PluralIfNeeded(int count) + { + return (count <= 1) ? string.Empty : "s"; + } + public void DeleteGroups(List groups, bool recordUndo) + { + foreach (AudioMixerGroupController current in groups) + { + if (current.HasDependentMixers()) + { + if (!EditorUtility.DisplayDialog("Referenced Group", "Deleted group is referenced by another AudioMixer, are you sure?", "Delete", "Cancel")) + { + return; + } + break; + } + } + if (recordUndo) + { + Undo.RegisterCompleteObjectUndo(this.m_Controller, "Delete Group" + AudioMixerGroupTreeView.PluralIfNeeded(groups.Count)); + } + this.m_Controller.DeleteGroups(groups.ToArray()); + this.ReloadTree(); + } + public void DuplicateGroups(List groups, bool recordUndo) + { + if (recordUndo) + { + Undo.RecordObject(this.m_Controller, "Duplicate group" + AudioMixerGroupTreeView.PluralIfNeeded(groups.Count)); + } + List list = this.m_Controller.DuplicateGroups(groups.ToArray()); + if (list.Count > 0) + { + this.ReloadTree(); + int[] array = ( + from audioMixerGroup in list + select audioMixerGroup.GetInstanceID()).ToArray(); + this.m_AudioGroupTree.SetSelection(array, false); + this.m_AudioGroupTree.Frame(array[array.Length - 1], true, false); + } + } + private void DeleteGroupsPopupCallback(object obj) + { + AudioMixerGroupTreeView audioMixerGroupTreeView = (AudioMixerGroupTreeView)obj; + audioMixerGroupTreeView.DeleteGroups(this.GetGroupSelectionWithoutMasterGroup(), true); + } + private void DuplicateGroupPopupCallback(object obj) + { + AudioMixerGroupTreeView audioMixerGroupTreeView = (AudioMixerGroupTreeView)obj; + audioMixerGroupTreeView.DuplicateGroups(this.GetGroupSelectionWithoutMasterGroup(), true); + } + private void RenameGroupCallback(object obj) + { + TreeViewItem treeViewItem = (TreeViewItem)obj; + this.m_AudioGroupTree.SetSelection(new int[] + { + treeViewItem.id + }, false); + this.m_AudioGroupTree.BeginNameEditing(0f); + } + private List GetGroupSelectionWithoutMasterGroup() + { + List audioMixerGroupsFromNodeIDs = this.GetAudioMixerGroupsFromNodeIDs(this.m_AudioGroupTree.GetSelection()); + audioMixerGroupsFromNodeIDs.Remove(this.m_Controller.masterGroup); + return audioMixerGroupsFromNodeIDs; + } + public void OnTreeViewContextClick(int index) + { + TreeViewItem treeViewItem = this.m_AudioGroupTree.FindNode(index); + if (treeViewItem != null) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = treeViewItem as AudioMixerTreeViewNode; + if (audioMixerTreeViewNode != null && audioMixerTreeViewNode.group != null) + { + GenericMenu genericMenu = new GenericMenu(); + if (!EditorApplication.isPlaying) + { + genericMenu.AddItem(new GUIContent("Add child group"), false, new GenericMenu.MenuFunction2(this.AddChildGroupPopupCallback), new AudioMixerGroupPopupContext(this.m_Controller, audioMixerTreeViewNode.group)); + if (audioMixerTreeViewNode.group != this.m_Controller.masterGroup) + { + genericMenu.AddItem(new GUIContent("Add sibling group"), false, new GenericMenu.MenuFunction2(this.AddSiblingGroupPopupCallback), new AudioMixerGroupPopupContext(this.m_Controller, audioMixerTreeViewNode.group)); + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Rename"), false, new GenericMenu.MenuFunction2(this.RenameGroupCallback), treeViewItem); + AudioMixerGroupController[] array = this.GetGroupSelectionWithoutMasterGroup().ToArray(); + genericMenu.AddItem(new GUIContent((array.Length <= 1) ? "Duplicate group (and children)" : "Duplicate groups (and children)"), false, new GenericMenu.MenuFunction2(this.DuplicateGroupPopupCallback), this); + genericMenu.AddItem(new GUIContent((array.Length <= 1) ? "Remove group (and children)" : "Remove groups (and children)"), false, new GenericMenu.MenuFunction2(this.DeleteGroupsPopupCallback), this); + } + } + else + { + genericMenu.AddDisabledItem(new GUIContent("Modifying group topology in play mode is not allowed")); + } + genericMenu.ShowAsContext(); + } + } + } + private void OnNodeToggled(AudioMixerTreeViewNode node, bool nodeWasEnabled) + { + List list = this.GetAudioMixerGroupsFromNodeIDs(this.m_AudioGroupTree.GetSelection()); + if (!list.Contains(node.group)) + { + list = new List + { + node.group + }; + } + List list2 = new List(); + List allAudioGroupsSlow = this.m_Controller.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + bool flag = this.m_Controller.CurrentViewContainsGroup(current.groupID); + bool flag2 = list.Contains(current); + bool flag3 = flag && !flag2; + if (!flag && flag2) + { + flag3 = nodeWasEnabled; + } + if (flag3) + { + list2.Add(current.groupID); + } + } + this.m_Controller.SetCurrentViewVisibility(list2.ToArray()); + } + private List GetAudioMixerGroupsFromNodeIDs(int[] instanceIDs) + { + List list = new List(); + for (int i = 0; i < instanceIDs.Length; i++) + { + int id = instanceIDs[i]; + TreeViewItem treeViewItem = this.m_AudioGroupTree.FindNode(id); + if (treeViewItem != null) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = treeViewItem as AudioMixerTreeViewNode; + if (audioMixerTreeViewNode != null) + { + list.Add(audioMixerTreeViewNode.group); + } + } + } + return list; + } + public void OnTreeSelectionChanged(int[] selection) + { + List audioMixerGroupsFromNodeIDs = this.GetAudioMixerGroupsFromNodeIDs(selection); + Selection.objects = audioMixerGroupsFromNodeIDs.ToArray(); + this.m_Controller.OnUnitySelectionChanged(); + if (audioMixerGroupsFromNodeIDs.Count == 1) + { + this.m_ScrollToItem = audioMixerGroupsFromNodeIDs[0]; + } + InspectorWindow.RepaintAllInspectors(); + } + public void InitSelection(bool revealSelectionAndFrameLastSelected) + { + if (this.m_Controller == null) + { + return; + } + List cachedSelection = this.m_Controller.CachedSelection; + this.m_AudioGroupTree.SetSelection(( + from x in cachedSelection + select x.GetInstanceID()).ToArray(), revealSelectionAndFrameLastSelected); + } + public float GetTotalHeight() + { + if (this.m_Controller == null) + { + return 0f; + } + return this.m_AudioGroupTree.gui.GetTotalSize(this.m_AudioGroupTree.data.GetVisibleRows()).y + 22f; + } + public void OnGUI(Rect rect) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.m_ScrollToItem = null; + if (AudioMixerGroupTreeView.s_Styles == null) + { + AudioMixerGroupTreeView.s_Styles = new AudioMixerGroupTreeView.Styles(); + } + this.m_AudioGroupTree.OnEvent(); + EditorGUI.BeginDisabledGroup(this.m_Controller == null); + Rect r; + Rect rect2; + AudioMixerDrawUtils.DrawRegionBg(rect, out r, out rect2); + AudioMixerDrawUtils.HeaderLabel(r, AudioMixerGroupTreeView.s_Styles.header, AudioMixerGroupTreeView.s_Styles.audioMixerGroupIcon); + EditorGUI.EndDisabledGroup(); + if (this.m_Controller != null) + { + AudioMixerGroupController parent = (this.m_Controller.CachedSelection.Count != 1) ? this.m_Controller.masterGroup : this.m_Controller.CachedSelection[0]; + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + if (GUI.Button(new Rect(r.xMax - 15f, r.y + 3f, 15f, 15f), AudioMixerGroupTreeView.s_Styles.addText, EditorStyles.label)) + { + this.AddAudioMixerGroup(parent); + } + EditorGUI.EndDisabledGroup(); + this.m_AudioGroupTree.OnGUI(rect2, controlID); + AudioMixerDrawUtils.DrawScrollDropShadow(rect2, this.m_AudioGroupTree.state.scrollPos.y, this.m_AudioGroupTree.gui.GetTotalSize(this.m_AudioGroupTree.data.GetVisibleRows()).y); + this.HandleKeyboardEvents(controlID); + this.HandleCommandEvents(controlID); + } + } + private void HandleCommandEvents(int treeViewKeyboardControlID) + { + if (GUIUtility.keyboardControl != treeViewKeyboardControlID) + { + return; + } + EventType type = Event.current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + Event.current.Use(); + if (flag) + { + this.DeleteGroups(this.GetGroupSelectionWithoutMasterGroup(), true); + GUIUtility.ExitGUI(); + } + } + else + { + if (Event.current.commandName == "Duplicate") + { + Event.current.Use(); + if (flag) + { + this.DuplicateGroups(this.GetGroupSelectionWithoutMasterGroup(), true); + } + } + } + } + } + private void HandleKeyboardEvents(int treeViewKeyboardControlID) + { + if (GUIUtility.keyboardControl != treeViewKeyboardControlID) + { + return; + } + Event current = Event.current; + if (current.keyCode == KeyCode.Space && current.type == EventType.KeyDown) + { + int[] selection = this.m_AudioGroupTree.GetSelection(); + if (selection.Length > 0) + { + AudioMixerTreeViewNode audioMixerTreeViewNode = this.m_AudioGroupTree.FindNode(selection[0]) as AudioMixerTreeViewNode; + bool flag = this.m_Controller.CurrentViewContainsGroup(audioMixerTreeViewNode.group.groupID); + this.OnNodeToggled(audioMixerTreeViewNode, !flag); + current.Use(); + } + } + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + if (this.m_Controller != controller) + { + this.m_TreeViewGUI.m_Controller = controller; + this.m_Controller = controller; + this.m_AudioGroupTreeDataSource.m_Controller = controller; + if (controller != null) + { + this.ReloadTree(); + this.InitSelection(false); + this.LoadExpandedState(); + this.m_AudioGroupTree.data.SetExpandedWithChildren(this.m_AudioGroupTree.data.root, true); + } + } + } + private static string GetUniqueAudioMixerName(AudioMixerController controller) + { + return "AudioMixer_" + controller.GetInstanceID(); + } + private void SaveExpandedState() + { + InspectorState.SetIntArray(AudioMixerGroupTreeView.GetUniqueAudioMixerName(this.m_Controller), this.m_AudioGroupTreeState.expandedIDs.ToArray()); + } + private void LoadExpandedState() + { + int[] intArray = InspectorState.GetIntArray(AudioMixerGroupTreeView.GetUniqueAudioMixerName(this.m_Controller), null); + if (intArray != null) + { + this.m_AudioGroupTreeState.expandedIDs = new List(intArray); + } + else + { + this.m_AudioGroupTree.state.expandedIDs = new List(); + this.m_AudioGroupTree.data.SetExpandedWithChildren(this.m_AudioGroupTree.data.root, true); + } + } + public void EndRenaming() + { + this.m_AudioGroupTree.EndNameEditing(true); + } + public void OnUndoRedoPerformed() + { + this.ReloadTree(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerGroupViewList.cs b/UnityEditor/UnityEditor/AudioMixerGroupViewList.cs new file mode 100644 index 00000000..331fa58c --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerGroupViewList.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerGroupViewList + { + private class Styles + { + public GUIContent header = new GUIContent("Views", "A view is the saved visiblity state of the current Mixer Groups. Use views to setup often used combinations of Mixer Groups."); + public GUIContent addButton = new GUIContent("+"); + public Texture2D viewsIcon = EditorGUIUtility.FindTexture("AudioMixerView Icon"); + } + internal class ViewsContexttMenu + { + private class data + { + public int viewIndex; + public AudioMixerGroupViewList list; + } + public static void Show(Rect buttonRect, int viewIndex, AudioMixerGroupViewList list) + { + GenericMenu genericMenu = new GenericMenu(); + AudioMixerGroupViewList.ViewsContexttMenu.data userData = new AudioMixerGroupViewList.ViewsContexttMenu.data + { + viewIndex = viewIndex, + list = list + }; + genericMenu.AddItem(new GUIContent("Rename"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Rename), userData); + genericMenu.AddItem(new GUIContent("Duplicate"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Duplicate), userData); + genericMenu.AddItem(new GUIContent("Delete"), false, new GenericMenu.MenuFunction2(AudioMixerGroupViewList.ViewsContexttMenu.Delete), userData); + genericMenu.DropDown(buttonRect); + } + private static void Rename(object userData) + { + AudioMixerGroupViewList.ViewsContexttMenu.data data = userData as AudioMixerGroupViewList.ViewsContexttMenu.data; + data.list.Rename(data.viewIndex); + } + private static void Duplicate(object userData) + { + AudioMixerGroupViewList.ViewsContexttMenu.data data = userData as AudioMixerGroupViewList.ViewsContexttMenu.data; + data.list.m_Controller.currentViewIndex = data.viewIndex; + data.list.DuplicateCurrentView(); + } + private static void Delete(object userData) + { + AudioMixerGroupViewList.ViewsContexttMenu.data data = userData as AudioMixerGroupViewList.ViewsContexttMenu.data; + data.list.Delete(data.viewIndex); + } + } + private ReorderableListWithRenameAndScrollView m_ReorderableListWithRenameAndScrollView; + private AudioMixerController m_Controller; + private List m_Views; + private readonly ReorderableListWithRenameAndScrollView.State m_State; + private static AudioMixerGroupViewList.Styles s_Styles; + public AudioMixerGroupViewList(ReorderableListWithRenameAndScrollView.State state) + { + this.m_State = state; + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + this.m_Controller = controller; + this.RecreateListControl(); + } + public void OnUndoRedoPerformed() + { + this.RecreateListControl(); + } + public void OnEvent() + { + if (this.m_Controller == null) + { + return; + } + this.m_ReorderableListWithRenameAndScrollView.OnEvent(); + } + private void RecreateListControl() + { + if (this.m_Controller == null) + { + return; + } + this.m_Views = new List(this.m_Controller.views); + if (this.m_Views.Count == 0) + { + MixerGroupView item = default(MixerGroupView); + item.guids = ( + from gr in this.m_Controller.GetAllAudioGroupsSlow() + select gr.groupID).ToArray(); + item.name = "View"; + this.m_Views.Add(item); + this.SaveToBackend(); + } + ReorderableList reorderableList = new ReorderableList(this.m_Views, typeof(MixerGroupView), true, false, false, false); + ReorderableList expr_B2 = reorderableList; + expr_B2.onReorderCallback = (ReorderableList.ReorderCallbackDelegate)Delegate.Combine(expr_B2.onReorderCallback, new ReorderableList.ReorderCallbackDelegate(this.EndDragChild)); + reorderableList.elementHeight = 16f; + reorderableList.headerHeight = 0f; + reorderableList.footerHeight = 0f; + reorderableList.showDefaultBackground = false; + reorderableList.index = this.m_Controller.currentViewIndex; + if (this.m_Controller.currentViewIndex >= reorderableList.count) + { + Debug.LogError(string.Concat(new object[] + { + "State mismatch, currentViewIndex: ", + this.m_Controller.currentViewIndex, + ", num items: ", + reorderableList.count + })); + } + this.m_ReorderableListWithRenameAndScrollView = new ReorderableListWithRenameAndScrollView(reorderableList, this.m_State); + ReorderableListWithRenameAndScrollView expr_17B = this.m_ReorderableListWithRenameAndScrollView; + expr_17B.onSelectionChanged = (Action)Delegate.Combine(expr_17B.onSelectionChanged, new Action(this.SelectionChanged)); + ReorderableListWithRenameAndScrollView expr_1A2 = this.m_ReorderableListWithRenameAndScrollView; + expr_1A2.onNameChangedAtIndex = (Action)Delegate.Combine(expr_1A2.onNameChangedAtIndex, new Action(this.NameChanged)); + ReorderableListWithRenameAndScrollView expr_1C9 = this.m_ReorderableListWithRenameAndScrollView; + expr_1C9.onDeleteItemAtIndex = (Action)Delegate.Combine(expr_1C9.onDeleteItemAtIndex, new Action(this.Delete)); + ReorderableListWithRenameAndScrollView expr_1F0 = this.m_ReorderableListWithRenameAndScrollView; + expr_1F0.onGetNameAtIndex = (Func)Delegate.Combine(expr_1F0.onGetNameAtIndex, new Func(this.GetNameOfElement)); + ReorderableListWithRenameAndScrollView expr_217 = this.m_ReorderableListWithRenameAndScrollView; + expr_217.onCustomDrawElement = (ReorderableList.ElementCallbackDelegate)Delegate.Combine(expr_217.onCustomDrawElement, new ReorderableList.ElementCallbackDelegate(this.CustomDrawElement)); + } + public float GetTotalHeight() + { + if (this.m_Controller == null) + { + return 0f; + } + return this.m_ReorderableListWithRenameAndScrollView.list.GetHeight() + 22f; + } + public void OnGUI(Rect rect) + { + if (AudioMixerGroupViewList.s_Styles == null) + { + AudioMixerGroupViewList.s_Styles = new AudioMixerGroupViewList.Styles(); + } + EditorGUI.BeginDisabledGroup(this.m_Controller == null); + Rect r; + Rect rect2; + AudioMixerDrawUtils.DrawRegionBg(rect, out r, out rect2); + AudioMixerDrawUtils.HeaderLabel(r, AudioMixerGroupViewList.s_Styles.header, AudioMixerGroupViewList.s_Styles.viewsIcon); + EditorGUI.EndDisabledGroup(); + if (this.m_Controller != null) + { + if (this.m_ReorderableListWithRenameAndScrollView.list.index != this.m_Controller.currentViewIndex) + { + this.m_ReorderableListWithRenameAndScrollView.list.index = this.m_Controller.currentViewIndex; + this.m_ReorderableListWithRenameAndScrollView.FrameItem(this.m_Controller.currentViewIndex); + } + this.m_ReorderableListWithRenameAndScrollView.OnGUI(rect2); + if (GUI.Button(new Rect(r.xMax - 15f, r.y + 3f, 15f, 15f), AudioMixerGroupViewList.s_Styles.addButton, EditorStyles.label)) + { + this.Add(); + } + } + } + public void CustomDrawElement(Rect r, int index, bool isActive, bool isFocused) + { + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && r.Contains(current.mousePosition)) + { + AudioMixerGroupViewList.ViewsContexttMenu.Show(r, index, this); + current.Use(); + } + bool isSelected = index == this.m_ReorderableListWithRenameAndScrollView.list.index && !this.m_ReorderableListWithRenameAndScrollView.IsRenamingIndex(index); + this.m_ReorderableListWithRenameAndScrollView.DrawElementText(r, index, isActive, isSelected, isFocused); + } + private void SaveToBackend() + { + this.m_Controller.views = this.m_Views.ToArray(); + } + private void LoadFromBackend() + { + this.m_Views.Clear(); + this.m_Views.AddRange(this.m_Controller.views); + } + private string GetNameOfElement(int index) + { + return this.m_Views[index].name; + } + private void Add() + { + this.m_Controller.CloneViewFromCurrent(); + this.LoadFromBackend(); + int num = this.m_Views.Count - 1; + this.m_Controller.currentViewIndex = num; + this.m_ReorderableListWithRenameAndScrollView.BeginRename(num, 0f); + } + private void Delete(int index) + { + if (this.m_Views.Count <= 1) + { + Debug.Log("Deleting all views is not allowed"); + return; + } + this.m_Controller.DeleteView(index); + this.LoadFromBackend(); + } + public void NameChanged(int index, string newName) + { + this.LoadFromBackend(); + MixerGroupView value = this.m_Views[index]; + value.name = newName; + this.m_Views[index] = value; + this.SaveToBackend(); + } + public void SelectionChanged(int selectedIndex) + { + this.LoadFromBackend(); + this.m_Controller.SetView(selectedIndex); + } + public void EndDragChild(ReorderableList list) + { + this.m_Views = (this.m_ReorderableListWithRenameAndScrollView.list.list as List); + this.SaveToBackend(); + } + private void Rename(int index) + { + this.m_ReorderableListWithRenameAndScrollView.BeginRename(index, 0f); + } + private void DuplicateCurrentView() + { + this.m_Controller.CloneViewFromCurrent(); + this.LoadFromBackend(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerItem.cs b/UnityEditor/UnityEditor/AudioMixerItem.cs new file mode 100644 index 00000000..848d68d2 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerItem.cs @@ -0,0 +1,67 @@ +using System; +using UnityEditor.Audio; +namespace UnityEditor +{ + internal class AudioMixerItem : TreeViewItem + { + private const string kSuspendedText = " - Inactive"; + public AudioMixerController mixer + { + get; + set; + } + public string infoText + { + get; + set; + } + public float labelWidth + { + get; + set; + } + private bool lastSuspendedState + { + get; + set; + } + public AudioMixerItem(int id, int depth, TreeViewItem parent, string displayName, AudioMixerController mixer, string infoText) : base(id, depth, parent, displayName) + { + this.mixer = mixer; + this.infoText = infoText; + this.UpdateSuspendedString(true); + } + public void UpdateSuspendedString(bool force) + { + bool isSuspended = this.mixer.isSuspended; + if (this.lastSuspendedState != isSuspended || force) + { + this.lastSuspendedState = isSuspended; + if (isSuspended) + { + this.AddSuspendedText(); + } + else + { + this.RemoveSuspendedText(); + } + } + } + private void RemoveSuspendedText() + { + int num = this.infoText.IndexOf(" - Inactive", StringComparison.Ordinal); + if (num >= 0) + { + this.infoText = this.infoText.Remove(num, " - Inactive".Length); + } + } + private void AddSuspendedText() + { + int num = this.infoText.IndexOf(" - Inactive", StringComparison.Ordinal); + if (num < 0) + { + this.infoText += " - Inactive"; + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerSelection.cs b/UnityEditor/UnityEditor/AudioMixerSelection.cs new file mode 100644 index 00000000..97500151 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerSelection.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerSelection + { + private AudioMixerController m_Controller; + public List ChannelStripSelection + { + get; + private set; + } + public AudioMixerSelection(AudioMixerController controller) + { + this.m_Controller = controller; + this.ChannelStripSelection = new List(); + this.SyncToUnitySelection(); + } + public void SyncToUnitySelection() + { + if (this.m_Controller != null) + { + this.RefreshCachedChannelStripSelection(); + } + } + public void SetChannelStrips(List newSelection) + { + Selection.objects = newSelection.ToArray(); + } + public void SetSingleChannelStrip(AudioMixerGroupController group) + { + Selection.objects = new AudioMixerGroupController[] + { + group + }; + } + public void ToggleChannelStrip(AudioMixerGroupController group) + { + List list = new List(Selection.objects); + if (list.Contains(group)) + { + list.Remove(group); + } + else + { + list.Add(group); + } + Selection.objects = list.ToArray(); + } + public void ClearChannelStrips() + { + Selection.objects = new UnityEngine.Object[0]; + } + public bool HasSingleChannelStripSelection() + { + return this.ChannelStripSelection.Count == 1; + } + private void RefreshCachedChannelStripSelection() + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(AudioMixerGroupController), SelectionMode.Deep); + this.ChannelStripSelection = new List(); + List allAudioGroupsSlow = this.m_Controller.GetAllAudioGroupsSlow(); + foreach (AudioMixerGroupController current in allAudioGroupsSlow) + { + if (filtered.Contains(current)) + { + this.ChannelStripSelection.Add(current); + } + } + } + public void Sanitize() + { + this.RefreshCachedChannelStripSelection(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerSnapshotControllerInspector.cs b/UnityEditor/UnityEditor/AudioMixerSnapshotControllerInspector.cs new file mode 100644 index 00000000..010a0acb --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerSnapshotControllerInspector.cs @@ -0,0 +1,12 @@ +using System; +using UnityEditor.Audio; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(AudioMixerSnapshotController))] + internal class AudioMixerSnapshotControllerInspector : Editor + { + public override void OnInspectorGUI() + { + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerSnapshotListView.cs b/UnityEditor/UnityEditor/AudioMixerSnapshotListView.cs new file mode 100644 index 00000000..7cc18f3f --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerSnapshotListView.cs @@ -0,0 +1,267 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerSnapshotListView + { + private class Styles + { + public GUIContent starIcon = new GUIContent(EditorGUIUtility.FindTexture("Favorite"), "Start snapshot"); + public GUIContent header = new GUIContent("Snapshots", "A snapshot is a set of values for all parameters in the mixer. When using the mixer you modify parameters in the selected snapshot. Blend between multiple snapshots at runtime."); + public GUIContent addButton = new GUIContent("+"); + public Texture2D snapshotsIcon = EditorGUIUtility.FindTexture("AudioMixerSnapshot Icon"); + } + internal class SnapshotMenu + { + private class data + { + public AudioMixerSnapshotController snapshot; + public AudioMixerSnapshotListView list; + } + public static void Show(Rect buttonRect, AudioMixerSnapshotController snapshot, AudioMixerSnapshotListView list) + { + GenericMenu genericMenu = new GenericMenu(); + AudioMixerSnapshotListView.SnapshotMenu.data userData = new AudioMixerSnapshotListView.SnapshotMenu.data + { + snapshot = snapshot, + list = list + }; + genericMenu.AddItem(new GUIContent("Set as start Snapshot"), false, new GenericMenu.MenuFunction2(AudioMixerSnapshotListView.SnapshotMenu.SetAsStartupSnapshot), userData); + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Rename"), false, new GenericMenu.MenuFunction2(AudioMixerSnapshotListView.SnapshotMenu.Rename), userData); + genericMenu.AddItem(new GUIContent("Duplicate"), false, new GenericMenu.MenuFunction2(AudioMixerSnapshotListView.SnapshotMenu.Duplicate), userData); + genericMenu.AddItem(new GUIContent("Delete"), false, new GenericMenu.MenuFunction2(AudioMixerSnapshotListView.SnapshotMenu.Delete), userData); + genericMenu.DropDown(buttonRect); + } + private static void SetAsStartupSnapshot(object userData) + { + AudioMixerSnapshotListView.SnapshotMenu.data data = userData as AudioMixerSnapshotListView.SnapshotMenu.data; + data.list.SetAsStartupSnapshot(data.snapshot); + } + private static void Rename(object userData) + { + AudioMixerSnapshotListView.SnapshotMenu.data data = userData as AudioMixerSnapshotListView.SnapshotMenu.data; + data.list.Rename(data.snapshot); + } + private static void Duplicate(object userData) + { + AudioMixerSnapshotListView.SnapshotMenu.data data = userData as AudioMixerSnapshotListView.SnapshotMenu.data; + data.list.DuplicateCurrentSnapshot(); + } + private static void Delete(object userData) + { + AudioMixerSnapshotListView.SnapshotMenu.data data = userData as AudioMixerSnapshotListView.SnapshotMenu.data; + data.list.DeleteSnapshot(data.snapshot); + } + } + private ReorderableListWithRenameAndScrollView m_ReorderableListWithRenameAndScrollView; + private AudioMixerController m_Controller; + private List m_Snapshots; + private ReorderableListWithRenameAndScrollView.State m_State; + private static AudioMixerSnapshotListView.Styles s_Styles; + public AudioMixerSnapshotListView(ReorderableListWithRenameAndScrollView.State state) + { + this.m_State = state; + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + this.m_Controller = controller; + this.RecreateListControl(); + } + private int GetSnapshotIndex(AudioMixerSnapshotController snapshot) + { + for (int i = 0; i < this.m_Snapshots.Count; i++) + { + if (this.m_Snapshots[i] == snapshot) + { + return i; + } + } + return 0; + } + private void RecreateListControl() + { + if (this.m_Controller == null) + { + return; + } + this.m_Snapshots = new List(this.m_Controller.snapshots); + this.m_ReorderableListWithRenameAndScrollView = new ReorderableListWithRenameAndScrollView(new ReorderableList(this.m_Snapshots, typeof(AudioMixerSnapshotController), true, false, false, false) + { + onReorderCallback = new ReorderableList.ReorderCallbackDelegate(this.EndDragChild), + elementHeight = 16f, + headerHeight = 0f, + footerHeight = 0f, + showDefaultBackground = false, + index = this.GetSnapshotIndex(this.m_Controller.TargetSnapshot) + }, this.m_State); + ReorderableListWithRenameAndScrollView expr_AB = this.m_ReorderableListWithRenameAndScrollView; + expr_AB.onSelectionChanged = (Action)Delegate.Combine(expr_AB.onSelectionChanged, new Action(this.SelectionChanged)); + ReorderableListWithRenameAndScrollView expr_D2 = this.m_ReorderableListWithRenameAndScrollView; + expr_D2.onNameChangedAtIndex = (Action)Delegate.Combine(expr_D2.onNameChangedAtIndex, new Action(this.NameChanged)); + ReorderableListWithRenameAndScrollView expr_F9 = this.m_ReorderableListWithRenameAndScrollView; + expr_F9.onDeleteItemAtIndex = (Action)Delegate.Combine(expr_F9.onDeleteItemAtIndex, new Action(this.Delete)); + ReorderableListWithRenameAndScrollView expr_120 = this.m_ReorderableListWithRenameAndScrollView; + expr_120.onGetNameAtIndex = (Func)Delegate.Combine(expr_120.onGetNameAtIndex, new Func(this.GetNameOfElement)); + ReorderableListWithRenameAndScrollView expr_147 = this.m_ReorderableListWithRenameAndScrollView; + expr_147.onCustomDrawElement = (ReorderableList.ElementCallbackDelegate)Delegate.Combine(expr_147.onCustomDrawElement, new ReorderableList.ElementCallbackDelegate(this.CustomDrawElement)); + } + private void SaveToBackend() + { + this.m_Controller.snapshots = this.m_Snapshots.ToArray(); + this.m_Controller.OnSubAssetChanged(); + } + private void LoadFromBackend() + { + if (this.m_Controller == null) + { + return; + } + this.m_Snapshots.Clear(); + this.m_Snapshots.AddRange(this.m_Controller.snapshots); + } + public void OnEvent() + { + if (this.m_Controller == null) + { + return; + } + this.m_ReorderableListWithRenameAndScrollView.OnEvent(); + } + public void CustomDrawElement(Rect r, int index, bool isActive, bool isFocused) + { + Event current = Event.current; + if (current.type == EventType.MouseUp && current.button == 1 && r.Contains(current.mousePosition)) + { + AudioMixerSnapshotListView.SnapshotMenu.Show(r, this.m_Snapshots[index], this); + current.Use(); + } + bool isSelected = index == this.m_ReorderableListWithRenameAndScrollView.list.index && !this.m_ReorderableListWithRenameAndScrollView.IsRenamingIndex(index); + r.width -= 19f; + this.m_ReorderableListWithRenameAndScrollView.DrawElementText(r, index, isActive, isSelected, isFocused); + if (this.m_Controller.startSnapshot == this.m_Snapshots[index]) + { + r.x = r.xMax + 5f + 5f; + r.y += (r.height - 14f) / 2f; + float num = 14f; + r.height = num; + r.width = num; + GUI.Label(r, AudioMixerSnapshotListView.s_Styles.starIcon, GUIStyle.none); + } + } + public float GetTotalHeight() + { + if (this.m_Controller == null) + { + return 0f; + } + return this.m_ReorderableListWithRenameAndScrollView.list.GetHeight() + 22f; + } + public void OnGUI(Rect rect) + { + if (AudioMixerSnapshotListView.s_Styles == null) + { + AudioMixerSnapshotListView.s_Styles = new AudioMixerSnapshotListView.Styles(); + } + EditorGUI.BeginDisabledGroup(this.m_Controller == null); + Rect r; + Rect rect2; + AudioMixerDrawUtils.DrawRegionBg(rect, out r, out rect2); + AudioMixerDrawUtils.HeaderLabel(r, AudioMixerSnapshotListView.s_Styles.header, AudioMixerSnapshotListView.s_Styles.snapshotsIcon); + EditorGUI.EndDisabledGroup(); + if (this.m_Controller != null) + { + int snapshotIndex = this.GetSnapshotIndex(this.m_Controller.TargetSnapshot); + if (snapshotIndex != this.m_ReorderableListWithRenameAndScrollView.list.index) + { + this.m_ReorderableListWithRenameAndScrollView.list.index = snapshotIndex; + this.m_ReorderableListWithRenameAndScrollView.FrameItem(snapshotIndex); + } + this.m_ReorderableListWithRenameAndScrollView.OnGUI(rect2); + if (GUI.Button(new Rect(r.xMax - 15f, r.y + 3f, 15f, 15f), AudioMixerSnapshotListView.s_Styles.addButton, EditorStyles.label)) + { + this.Add(); + } + } + } + public void SelectionChanged(int index) + { + if (index >= this.m_Snapshots.Count) + { + index = this.m_Snapshots.Count - 1; + } + this.m_Controller.TargetSnapshot = this.m_Snapshots[index]; + this.UpdateViews(); + } + private string GetNameOfElement(int index) + { + return this.m_Snapshots[index].name; + } + public void NameChanged(int index, string newName) + { + this.m_Snapshots[index].name = newName; + this.SaveToBackend(); + } + private void DuplicateCurrentSnapshot() + { + Undo.RecordObject(this.m_Controller, "Duplicate current snapshot"); + this.m_Controller.CloneNewSnapshotFromTarget(true); + this.LoadFromBackend(); + this.UpdateViews(); + } + private void Add() + { + Undo.RecordObject(this.m_Controller, "Add new snapshot"); + this.m_Controller.CloneNewSnapshotFromTarget(true); + this.LoadFromBackend(); + this.Rename(this.m_Controller.TargetSnapshot); + this.UpdateViews(); + } + private void DeleteSnapshot(AudioMixerSnapshotController snapshot) + { + AudioMixerSnapshotController[] snapshots = this.m_Controller.snapshots; + if (snapshots.Length <= 1) + { + Debug.Log("You must have at least 1 snapshot in an AudioMixer."); + return; + } + this.m_Controller.RemoveSnapshot(snapshot); + this.LoadFromBackend(); + this.m_ReorderableListWithRenameAndScrollView.list.index = this.GetSnapshotIndex(this.m_Controller.TargetSnapshot); + this.UpdateViews(); + } + private void Delete(int index) + { + this.DeleteSnapshot(this.m_Snapshots[index]); + } + public void EndDragChild(ReorderableList list) + { + this.m_Snapshots = (this.m_ReorderableListWithRenameAndScrollView.list.list as List); + this.SaveToBackend(); + } + private void UpdateViews() + { + AudioMixerWindow audioMixerWindow = (AudioMixerWindow)WindowLayout.FindEditorWindowOfType(typeof(AudioMixerWindow)); + if (audioMixerWindow != null) + { + audioMixerWindow.Repaint(); + } + InspectorWindow.RepaintAllInspectors(); + } + private void SetAsStartupSnapshot(AudioMixerSnapshotController snapshot) + { + this.m_Controller.startSnapshot = snapshot; + } + private void Rename(AudioMixerSnapshotController snapshot) + { + this.m_ReorderableListWithRenameAndScrollView.BeginRename(this.GetSnapshotIndex(snapshot), 0f); + } + public void OnUndoRedoPerformed() + { + this.LoadFromBackend(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerTreeViewDragging.cs b/UnityEditor/UnityEditor/AudioMixerTreeViewDragging.cs new file mode 100644 index 00000000..c2275fa7 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerTreeViewDragging.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerTreeViewDragging : TreeViewDragging + { + private class DragData + { + public List m_DraggedItems; + public DragData(List draggedItems) + { + this.m_DraggedItems = draggedItems; + } + } + private const string k_AudioMixerDraggingID = "AudioMixerDragging"; + private Action, AudioMixerController> m_MixersDroppedOnMixerCallback; + public AudioMixerTreeViewDragging(TreeView treeView, Action, AudioMixerController> mixerDroppedOnMixerCallback) : base(treeView) + { + this.m_MixersDroppedOnMixerCallback = mixerDroppedOnMixerCallback; + } + public override void StartDrag(TreeViewItem draggedNode, List draggedNodes) + { + if (EditorApplication.isPlaying) + { + return; + } + List audioMixerItemsFromIDs = this.GetAudioMixerItemsFromIDs(draggedNodes); + DragAndDrop.PrepareStartDrag(); + DragAndDrop.SetGenericData("AudioMixerDragging", new AudioMixerTreeViewDragging.DragData(audioMixerItemsFromIDs)); + DragAndDrop.objectReferences = new UnityEngine.Object[0]; + string title = draggedNodes.Count + " AudioMixer" + ((draggedNodes.Count <= 1) ? string.Empty : "s"); + DragAndDrop.StartDrag(title); + } + public override bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bool firstItem) + { + AudioMixerTreeViewDragging.DragData dragData = DragAndDrop.GetGenericData("AudioMixerDragging") as AudioMixerTreeViewDragging.DragData; + if (dragData == null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.None; + return false; + } + bool flag = targetItem == null; + if (flag && this.m_TreeView.GetTotalRect().Contains(Event.current.mousePosition)) + { + if (this.m_DropData != null) + { + this.m_DropData.dropTargetControlID = 0; + this.m_DropData.rowMarkerControlID = 0; + } + if (Event.current.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + if (this.m_MixersDroppedOnMixerCallback != null) + { + this.m_MixersDroppedOnMixerCallback(this.GetAudioMixersFromItems(dragData.m_DraggedItems), null); + } + } + DragAndDrop.visualMode = DragAndDropVisualMode.Move; + Event.current.Use(); + return false; + } + return base.DragElement(targetItem, targetItemRect, firstItem); + } + public override DragAndDropVisualMode DoDrag(TreeViewItem parentNode, TreeViewItem targetNode, bool perform, TreeViewDragging.DropPosition dragPos) + { + AudioMixerTreeViewDragging.DragData dragData = DragAndDrop.GetGenericData("AudioMixerDragging") as AudioMixerTreeViewDragging.DragData; + if (dragData == null) + { + return DragAndDropVisualMode.None; + } + List draggedItems = dragData.m_DraggedItems; + AudioMixerItem audioMixerItem = parentNode as AudioMixerItem; + if (audioMixerItem != null && dragData != null) + { + List groupsToBeMoved = ( + from i in draggedItems + select i.mixer.masterGroup).ToList(); + List allAudioGroupsSlow = audioMixerItem.mixer.GetAllAudioGroupsSlow(); + bool flag = AudioMixerController.WillModificationOfTopologyCauseFeedback(allAudioGroupsSlow, groupsToBeMoved, audioMixerItem.mixer.masterGroup, null); + bool flag2 = this.ValidDrag(parentNode, draggedItems) && !flag; + if (perform && flag2 && this.m_MixersDroppedOnMixerCallback != null) + { + this.m_MixersDroppedOnMixerCallback(this.GetAudioMixersFromItems(draggedItems), audioMixerItem.mixer); + } + return (!flag2) ? DragAndDropVisualMode.Rejected : DragAndDropVisualMode.Move; + } + return DragAndDropVisualMode.None; + } + private bool ValidDrag(TreeViewItem parent, List draggedItems) + { + List list = ( + from n in draggedItems + select n.id).ToList(); + for (TreeViewItem treeViewItem = parent; treeViewItem != null; treeViewItem = treeViewItem.parent) + { + if (list.Contains(treeViewItem.id)) + { + return false; + } + } + return true; + } + private List GetAudioMixerItemsFromIDs(List draggedMixers) + { + List source = TreeViewUtility.FindItemsInList(draggedMixers, this.m_TreeView.data.GetVisibleRows()); + return source.OfType().ToList(); + } + private List GetAudioMixersFromItems(List draggedItems) + { + return ( + from i in draggedItems + select i.mixer).ToList(); + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerTreeViewNode.cs b/UnityEditor/UnityEditor/AudioMixerTreeViewNode.cs new file mode 100644 index 00000000..1ee5e6dd --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerTreeViewNode.cs @@ -0,0 +1,17 @@ +using System; +using UnityEditor.Audio; +namespace UnityEditor +{ + internal class AudioMixerTreeViewNode : TreeViewItem + { + public AudioMixerGroupController group + { + get; + set; + } + public AudioMixerTreeViewNode(int instanceID, int depth, TreeViewItem parent, string displayName, AudioMixerGroupController group) : base(instanceID, depth, parent, displayName) + { + this.group = group; + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerUtility.cs b/UnityEditor/UnityEditor/AudioMixerUtility.cs new file mode 100644 index 00000000..b8a41295 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerUtility.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Audio; +namespace UnityEditor +{ + internal class AudioMixerUtility + { + public class VisitorFetchInstanceIDs + { + public List instanceIDs = new List(); + public void Visitor(AudioMixerGroupController group) + { + this.instanceIDs.Add(group.GetInstanceID()); + } + } + public static void RepaintAudioMixerAndInspectors() + { + InspectorWindow.RepaintAllInspectors(); + AudioMixerWindow.RepaintAudioMixerWindow(); + } + public static void VisitGroupsRecursivly(AudioMixerGroupController group, Action visitorCallback) + { + AudioMixerGroupController[] children = group.children; + for (int i = 0; i < children.Length; i++) + { + AudioMixerGroupController group2 = children[i]; + AudioMixerUtility.VisitGroupsRecursivly(group2, visitorCallback); + } + if (visitorCallback != null) + { + visitorCallback(group); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixerWindow.cs b/UnityEditor/UnityEditor/AudioMixerWindow.cs new file mode 100644 index 00000000..79766b99 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixerWindow.cs @@ -0,0 +1,808 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixerWindow : EditorWindow, IHasCustomMenu + { + private enum SectionType + { + MixerTree, + GroupTree, + ViewList, + SnapshotList + } + public enum LayoutMode + { + Horizontal, + Vertical + } + [Serializable] + private class Layout + { + [SerializeField] + public SplitterState m_VerticalSplitter; + [SerializeField] + public SplitterState m_HorizontalSplitter; + } + private class GUIContents + { + public GUIContent rms; + public GUIContent editSnapShots; + public GUIContent infoText; + public GUIContent selectAudioMixer; + public GUIContent output; + public GUIStyle toolbarObjectField = new GUIStyle("ShurikenObjectField"); + public GUIStyle toolbarLabel = new GUIStyle(EditorStyles.miniLabel); + public GUIStyle mixerHeader = new GUIStyle(EditorStyles.largeLabel); + public GUIContents() + { + this.rms = new GUIContent("RMS", "Switches between RMS (Root Mean Square) metering and peak metering. RMS is closer to the energy level and perceived loudness of the sound (hence lower than the peak meter), while peak-metering is useful for monitoring spikes in the signal that can cause clipping."); + this.editSnapShots = new GUIContent("Edit in Play Mode", EditorGUIUtility.IconContent("Animation.Record").image, "Edit in playmode and your changes are automatically saved. Note when editting is disabled then live values are shown."); + this.infoText = new GUIContent("Create an AudioMixer asset from the Project Browser to get started"); + this.selectAudioMixer = new GUIContent(string.Empty, "Select an Audio Mixer"); + this.output = new GUIContent("Output", "Select an Audio Mixer Group from another Audio Mixer to output to. If 'None' is selected then output is routed directly to the Audio Listener."); + this.toolbarLabel.alignment = TextAnchor.MiddleLeft; + this.toolbarObjectField.normal.textColor = this.toolbarLabel.normal.textColor; + this.mixerHeader.fontStyle = FontStyle.Bold; + this.mixerHeader.fontSize = 17; + this.mixerHeader.margin = new RectOffset(); + this.mixerHeader.padding = new RectOffset(); + this.mixerHeader.alignment = TextAnchor.MiddleLeft; + if (!EditorGUIUtility.isProSkin) + { + this.mixerHeader.normal.textColor = new Color(0.4f, 0.4f, 0.4f, 1f); + } + else + { + this.mixerHeader.normal.textColor = new Color(0.7f, 0.7f, 0.7f, 1f); + } + } + } + private const float kToolbarHeight = 17f; + private static AudioMixerWindow s_Instance; + private static string kAudioMixerUseRMSMetering = "AudioMixerUseRMSMetering"; + [NonSerialized] + private bool m_Initialized; + private AudioMixerController m_Controller; + private List m_AllControllers; + private AudioMixerChannelStripView.State m_ChannelStripViewState; + private AudioMixerChannelStripView m_ChannelStripView; + private TreeViewState m_AudioGroupTreeState; + private AudioMixerGroupTreeView m_GroupTree; + [SerializeField] + private TreeViewState m_MixersTreeState; + private AudioMixersTreeView m_MixersTree; + private ReorderableListWithRenameAndScrollView.State m_ViewsState; + private AudioMixerGroupViewList m_GroupViews; + private ReorderableListWithRenameAndScrollView.State m_SnapshotState; + private AudioMixerSnapshotListView m_SnapshotListView; + [SerializeField] + private AudioMixerWindow.Layout m_LayoutStripsOnTop; + [SerializeField] + private AudioMixerWindow.Layout m_LayoutStripsOnRight; + [SerializeField] + private AudioMixerWindow.SectionType[] m_SectionOrder = new AudioMixerWindow.SectionType[] + { + AudioMixerWindow.SectionType.MixerTree, + AudioMixerWindow.SectionType.SnapshotList, + AudioMixerWindow.SectionType.GroupTree, + AudioMixerWindow.SectionType.ViewList + }; + [SerializeField] + private AudioMixerWindow.LayoutMode m_LayoutMode = AudioMixerWindow.LayoutMode.Vertical; + [SerializeField] + private bool m_SortGroupsAlphabetically; + [SerializeField] + private bool m_ShowReferencedBuses = true; + [SerializeField] + private bool m_ShowBusConnections; + [SerializeField] + private bool m_ShowBusConnectionsOfSelection; + private Vector2 m_SectionsScrollPosition = Vector2.zero; + private int m_RepaintCounter = 2; + private Vector2 m_LastSize; + private bool m_GroupsRenderedAboveSections = true; + [NonSerialized] + private bool m_ShowDeveloperOverlays; + private readonly TickTimerHelper m_Ticker = new TickTimerHelper(0.05); + private static AudioMixerWindow.GUIContents s_GuiContents; + public AudioMixerController controller + { + get + { + return this.m_Controller; + } + } + private AudioMixerWindow.LayoutMode layoutMode + { + get + { + return this.m_LayoutMode; + } + set + { + this.m_LayoutMode = value; + this.m_RepaintCounter = 2; + } + } + public static void Create() + { + AudioMixerWindow window = EditorWindow.GetWindow(new Type[] + { + typeof(ProjectBrowser) + }); + window.title = "Audio Mixer"; + if (window.m_Pos.width < 400f) + { + window.m_Pos = new Rect(window.m_Pos.x, window.m_Pos.y, 800f, 450f); + } + } + public static void RepaintAudioMixerWindow() + { + if (AudioMixerWindow.s_Instance != null) + { + AudioMixerWindow.s_Instance.Repaint(); + } + } + private void Init() + { + if (this.m_Initialized) + { + return; + } + if (this.m_LayoutStripsOnTop == null) + { + this.m_LayoutStripsOnTop = new AudioMixerWindow.Layout(); + } + if (this.m_LayoutStripsOnTop.m_VerticalSplitter == null || this.m_LayoutStripsOnTop.m_VerticalSplitter.realSizes.Length != 2) + { + this.m_LayoutStripsOnTop.m_VerticalSplitter = new SplitterState(new int[] + { + 65, + 35 + }, new int[] + { + 85, + 105 + }, null); + } + if (this.m_LayoutStripsOnTop.m_HorizontalSplitter == null || this.m_LayoutStripsOnTop.m_HorizontalSplitter.realSizes.Length != 4) + { + this.m_LayoutStripsOnTop.m_HorizontalSplitter = new SplitterState(new int[] + { + 60, + 60, + 60, + 60 + }, new int[] + { + 85, + 85, + 85, + 85 + }, null); + } + if (this.m_LayoutStripsOnRight == null) + { + this.m_LayoutStripsOnRight = new AudioMixerWindow.Layout(); + } + if (this.m_LayoutStripsOnRight.m_HorizontalSplitter == null || this.m_LayoutStripsOnRight.m_HorizontalSplitter.realSizes.Length != 2) + { + this.m_LayoutStripsOnRight.m_HorizontalSplitter = new SplitterState(new int[] + { + 30, + 70 + }, new int[] + { + 160, + 160 + }, null); + } + if (this.m_LayoutStripsOnRight.m_VerticalSplitter == null || this.m_LayoutStripsOnRight.m_VerticalSplitter.realSizes.Length != 4) + { + this.m_LayoutStripsOnRight.m_VerticalSplitter = new SplitterState(new int[] + { + 60, + 60, + 60, + 60 + }, new int[] + { + 100, + 85, + 85, + 85 + }, null); + } + if (this.m_AudioGroupTreeState == null) + { + this.m_AudioGroupTreeState = new TreeViewState(); + } + this.m_GroupTree = new AudioMixerGroupTreeView(this, this.m_AudioGroupTreeState); + if (this.m_MixersTreeState == null) + { + this.m_MixersTreeState = new TreeViewState(); + } + this.m_MixersTree = new AudioMixersTreeView(this, this.m_MixersTreeState, new Func>(this.GetAllControllers)); + if (this.m_ViewsState == null) + { + this.m_ViewsState = new ReorderableListWithRenameAndScrollView.State(); + } + this.m_GroupViews = new AudioMixerGroupViewList(this.m_ViewsState); + if (this.m_SnapshotState == null) + { + this.m_SnapshotState = new ReorderableListWithRenameAndScrollView.State(); + } + this.m_SnapshotListView = new AudioMixerSnapshotListView(this.m_SnapshotState); + if (this.m_ChannelStripViewState == null) + { + this.m_ChannelStripViewState = new AudioMixerChannelStripView.State(); + } + this.m_ChannelStripView = new AudioMixerChannelStripView(this.m_ChannelStripViewState); + this.OnMixerControllerChanged(); + this.m_Initialized = true; + } + private List GetAllControllers() + { + return this.m_AllControllers; + } + private static List FindAllAudioMixerControllers() + { + List list = new List(); + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(new SearchFilter + { + classNames = new string[] + { + "AudioMixerController" + } + }); + while (hierarchyProperty.Next(null)) + { + AudioMixerController audioMixerController = hierarchyProperty.pptrValue as AudioMixerController; + if (audioMixerController) + { + list.Add(audioMixerController); + } + } + return list; + } + public void Awake() + { + this.m_AllControllers = AudioMixerWindow.FindAllAudioMixerControllers(); + if (this.m_MixersTreeState != null) + { + this.m_MixersTreeState.OnAwake(); + this.m_MixersTreeState.selectedIDs = new List(); + } + } + public void OnEnable() + { + AudioMixerWindow.s_Instance = this; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.PlaymodeChanged)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnProjectChanged)); + } + public void OnDisable() + { + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.PlaymodeChanged)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); + EditorApplication.projectWindowChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.projectWindowChanged, new EditorApplication.CallbackFunction(this.OnProjectChanged)); + } + private void PlaymodeChanged() + { + this.m_Ticker.Reset(); + if (this.m_Controller != null) + { + base.Repaint(); + } + this.EndRenaming(); + } + private void OnLostFocus() + { + this.EndRenaming(); + } + private void EndRenaming() + { + if (this.m_GroupTree != null) + { + this.m_GroupTree.EndRenaming(); + } + if (this.m_MixersTree != null) + { + this.m_MixersTree.EndRenaming(); + } + } + public void UndoRedoPerformed() + { + if (this.m_Controller == null) + { + return; + } + this.m_Controller.SanitizeGroupViews(); + this.m_Controller.OnUnitySelectionChanged(); + this.m_Controller.OnSubAssetChanged(); + if (this.m_GroupTree != null) + { + this.m_GroupTree.OnUndoRedoPerformed(); + } + if (this.m_GroupViews != null) + { + this.m_GroupViews.OnUndoRedoPerformed(); + } + if (this.m_SnapshotListView != null) + { + this.m_SnapshotListView.OnUndoRedoPerformed(); + } + if (this.m_MixersTree != null) + { + this.m_MixersTree.OnUndoRedoPerformed(); + } + AudioMixerUtility.RepaintAudioMixerAndInspectors(); + } + private void OnMixerControllerChanged() + { + if (this.m_Controller) + { + this.m_Controller.ClearEventHandlers(); + } + this.m_MixersTree.OnMixerControllerChanged(this.m_Controller); + this.m_GroupTree.OnMixerControllerChanged(this.m_Controller); + this.m_GroupViews.OnMixerControllerChanged(this.m_Controller); + this.m_ChannelStripView.OnMixerControllerChanged(this.m_Controller); + this.m_SnapshotListView.OnMixerControllerChanged(this.m_Controller); + if (this.m_Controller) + { + this.m_Controller.ForceSetView(this.m_Controller.currentViewIndex); + } + } + private void OnProjectChanged() + { + if (this.m_MixersTree == null) + { + this.Init(); + } + this.m_AllControllers = AudioMixerWindow.FindAllAudioMixerControllers(); + this.m_MixersTree.ReloadTree(); + } + public void Update() + { + if (this.m_Ticker.DoTick() && (EditorApplication.isPlaying || (this.m_ChannelStripView != null && this.m_ChannelStripView.requiresRepaint))) + { + base.Repaint(); + } + } + private void DetectControllerChange() + { + AudioMixerController controller = this.m_Controller; + if (Selection.activeObject is AudioMixerController) + { + this.m_Controller = (Selection.activeObject as AudioMixerController); + } + if (this.m_Controller != controller) + { + this.OnMixerControllerChanged(); + } + } + private void OnSelectionChange() + { + if (this.m_Controller != null) + { + this.m_Controller.OnUnitySelectionChanged(); + } + if (this.m_GroupTree != null) + { + this.m_GroupTree.InitSelection(true); + } + base.Repaint(); + } + private Dictionary GetEffectMap(List allGroups) + { + Dictionary dictionary = new Dictionary(); + foreach (AudioMixerGroupController current in allGroups) + { + AudioMixerEffectController[] effects = current.effects; + for (int i = 0; i < effects.Length; i++) + { + AudioMixerEffectController key = effects[i]; + dictionary[key] = current; + } + } + return dictionary; + } + private void DoToolbar() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + GUILayout.FlexibleSpace(); + if (this.m_Controller != null) + { + if (Application.isPlaying) + { + Color backgroundColor = GUI.backgroundColor; + if (AudioSettings.editingInPlaymode) + { + GUI.backgroundColor = AnimationMode.animatedPropertyColor; + } + EditorGUI.BeginChangeCheck(); + AudioSettings.editingInPlaymode = GUILayout.Toggle(AudioSettings.editingInPlaymode, AudioMixerWindow.s_GuiContents.editSnapShots, EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + InspectorWindow.RepaintAllInspectors(); + } + GUI.backgroundColor = backgroundColor; + } + GUILayout.FlexibleSpace(); + AudioMixerExposedParametersPopup.Popup(this.m_Controller, EditorStyles.toolbarPopup, new GUILayoutOption[0]); + } + EditorGUILayout.EndHorizontal(); + } + private void RepaintIfNeeded() + { + if (this.m_RepaintCounter > 0) + { + if (Event.current.type == EventType.Repaint) + { + this.m_RepaintCounter--; + } + base.Repaint(); + } + } + public void OnGUI() + { + this.Init(); + if (AudioMixerWindow.s_GuiContents == null) + { + AudioMixerWindow.s_GuiContents = new AudioMixerWindow.GUIContents(); + } + AudioMixerDrawUtils.InitStyles(); + this.DetectControllerChange(); + this.m_GroupViews.OnEvent(); + this.m_SnapshotListView.OnEvent(); + this.DoToolbar(); + List allGroups; + if (this.m_Controller != null) + { + allGroups = this.m_Controller.GetAllAudioGroupsSlow(); + } + else + { + allGroups = new List(); + } + Dictionary effectMap = this.GetEffectMap(allGroups); + if (this.m_LayoutMode == AudioMixerWindow.LayoutMode.Horizontal) + { + this.LayoutWithStripsOnTop(allGroups, effectMap); + } + else + { + this.LayoutWithStripsOnRightSideOneScrollBar(allGroups, effectMap); + } + if (this.m_LastSize.x != base.position.width || this.m_LastSize.y != base.position.height) + { + this.m_RepaintCounter = 2; + this.m_LastSize = new Vector2(base.position.width, base.position.height); + } + this.RepaintIfNeeded(); + } + private void LayoutWithStripsOnRightSideOneScrollBar(List allGroups, Dictionary effectMap) + { + SplitterState horizontalSplitter = this.m_LayoutStripsOnRight.m_HorizontalSplitter; + SplitterGUILayout.BeginHorizontalSplit(horizontalSplitter, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + SplitterGUILayout.EndHorizontalSplit(); + float num = (float)horizontalSplitter.realSizes[0]; + float width = base.position.width - num; + Rect rect = new Rect(0f, 17f, num, base.position.height - 17f); + Rect rect2 = new Rect(num, 17f, width, rect.height); + if (EditorGUIUtility.isProSkin) + { + EditorGUI.DrawRect(rect, (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 0f) : new Color(0.19f, 0.19f, 0.19f)); + } + float num2 = 10f; + Rect[] array = new Rect[this.m_SectionOrder.Length]; + float num3 = 0f; + for (int i = 0; i < this.m_SectionOrder.Length; i++) + { + num3 += num2; + if (i > 0) + { + num3 += array[i - 1].height; + } + array[i] = new Rect(0f, num3, rect.width, this.GetHeightOfSection(this.m_SectionOrder[i])); + Rect[] expr_155_cp_0 = array; + int expr_155_cp_1 = i; + expr_155_cp_0[expr_155_cp_1].x = expr_155_cp_0[expr_155_cp_1].x + 4f; + Rect[] expr_16F_cp_0 = array; + int expr_16F_cp_1 = i; + expr_16F_cp_0[expr_16F_cp_1].width = expr_16F_cp_0[expr_16F_cp_1].width - 8f; + } + Rect viewRect = new Rect(0f, 0f, 1f, array.Last().yMax); + if (viewRect.height > rect.height) + { + for (int j = 0; j < array.Length; j++) + { + Rect[] expr_1DF_cp_0 = array; + int expr_1DF_cp_1 = j; + expr_1DF_cp_0[expr_1DF_cp_1].width = expr_1DF_cp_0[expr_1DF_cp_1].width - 14f; + } + } + this.m_SectionsScrollPosition = GUI.BeginScrollView(rect, this.m_SectionsScrollPosition, viewRect); + this.DoSections(rect, array, this.m_SectionOrder); + GUI.EndScrollView(); + this.m_ChannelStripView.OnGUI(rect2, this.m_ShowReferencedBuses, this.m_ShowBusConnections, this.m_ShowBusConnectionsOfSelection, allGroups, effectMap, this.m_SortGroupsAlphabetically, this.m_ShowDeveloperOverlays, this.m_GroupTree.ScrollToItem); + EditorGUI.DrawRect(new Rect(rect.xMax - 1f, 17f, 1f, base.position.height - 17f), (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f) : new Color(0.15f, 0.15f, 0.15f)); + } + private void LayoutWithStripsOnTop(List allGroups, Dictionary effectMap) + { + SplitterState horizontalSplitter = this.m_LayoutStripsOnTop.m_HorizontalSplitter; + SplitterState verticalSplitter = this.m_LayoutStripsOnTop.m_VerticalSplitter; + SplitterGUILayout.BeginVerticalSplit(verticalSplitter, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + if (this.m_GroupsRenderedAboveSections) + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + SplitterGUILayout.BeginHorizontalSplit(horizontalSplitter, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.ExpandHeight(true) + }); + if (!this.m_GroupsRenderedAboveSections) + { + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.EndVertical(); + } + SplitterGUILayout.EndHorizontalSplit(); + SplitterGUILayout.EndVerticalSplit(); + float top = (!this.m_GroupsRenderedAboveSections) ? (17f + (float)verticalSplitter.realSizes[0]) : 17f; + float height = (float)((!this.m_GroupsRenderedAboveSections) ? verticalSplitter.realSizes[1] : verticalSplitter.realSizes[0]); + float top2 = this.m_GroupsRenderedAboveSections ? (17f + (float)verticalSplitter.realSizes[0]) : 17f; + float num = (float)(this.m_GroupsRenderedAboveSections ? verticalSplitter.realSizes[1] : verticalSplitter.realSizes[0]); + Rect rect = new Rect(0f, top, base.position.width, height); + Rect totalRectOfSections = new Rect(0f, rect.yMax, base.position.width, base.position.height - rect.height); + Rect[] array = new Rect[this.m_SectionOrder.Length]; + for (int i = 0; i < array.Length; i++) + { + float left = (i <= 0) ? 0f : array[i - 1].xMax; + array[i] = new Rect(left, top2, (float)horizontalSplitter.realSizes[i], num - 12f); + } + Rect[] expr_1F7_cp_0 = array; + int expr_1F7_cp_1 = 0; + expr_1F7_cp_0[expr_1F7_cp_1].x = expr_1F7_cp_0[expr_1F7_cp_1].x + 8f; + Rect[] expr_210_cp_0 = array; + int expr_210_cp_1 = 0; + expr_210_cp_0[expr_210_cp_1].width = expr_210_cp_0[expr_210_cp_1].width - 12f; + Rect[] expr_22E_cp_0 = array; + int expr_22E_cp_1 = array.Length - 1; + expr_22E_cp_0[expr_22E_cp_1].x = expr_22E_cp_0[expr_22E_cp_1].x + 4f; + Rect[] expr_24C_cp_0 = array; + int expr_24C_cp_1 = array.Length - 1; + expr_24C_cp_0[expr_24C_cp_1].width = expr_24C_cp_0[expr_24C_cp_1].width - 12f; + for (int j = 1; j < array.Length - 1; j++) + { + Rect[] expr_26E_cp_0 = array; + int expr_26E_cp_1 = j; + expr_26E_cp_0[expr_26E_cp_1].x = expr_26E_cp_0[expr_26E_cp_1].x + 4f; + Rect[] expr_288_cp_0 = array; + int expr_288_cp_1 = j; + expr_288_cp_0[expr_288_cp_1].width = expr_288_cp_0[expr_288_cp_1].width - 8f; + } + this.DoSections(totalRectOfSections, array, this.m_SectionOrder); + this.m_ChannelStripView.OnGUI(rect, this.m_ShowReferencedBuses, this.m_ShowBusConnections, this.m_ShowBusConnectionsOfSelection, allGroups, effectMap, this.m_SortGroupsAlphabetically, this.m_ShowDeveloperOverlays, this.m_GroupTree.ScrollToItem); + EditorGUI.DrawRect(new Rect(0f, 17f + (float)verticalSplitter.realSizes[0] - 1f, base.position.width, 1f), new Color(0f, 0f, 0f, 0.4f)); + } + private float GetHeightOfSection(AudioMixerWindow.SectionType sectionType) + { + switch (sectionType) + { + case AudioMixerWindow.SectionType.MixerTree: + return this.m_MixersTree.GetTotalHeight(); + case AudioMixerWindow.SectionType.GroupTree: + return this.m_GroupTree.GetTotalHeight(); + case AudioMixerWindow.SectionType.ViewList: + return this.m_GroupViews.GetTotalHeight(); + case AudioMixerWindow.SectionType.SnapshotList: + return this.m_SnapshotListView.GetTotalHeight(); + default: + Debug.LogError("Unhandled enum value"); + return 0f; + } + } + private void DoSections(Rect totalRectOfSections, Rect[] sectionRects, AudioMixerWindow.SectionType[] sectionOrder) + { + Event current = Event.current; + bool flag = this.m_Controller == null || AudioMixerController.EditingTargetSnapshot(); + for (int i = 0; i < sectionOrder.Length; i++) + { + Rect rect = sectionRects[i]; + if (rect.height > 0f) + { + switch (sectionOrder[i]) + { + case AudioMixerWindow.SectionType.MixerTree: + this.m_MixersTree.OnGUI(rect); + break; + case AudioMixerWindow.SectionType.GroupTree: + this.m_GroupTree.OnGUI(rect); + break; + case AudioMixerWindow.SectionType.ViewList: + this.m_GroupViews.OnGUI(rect); + break; + case AudioMixerWindow.SectionType.SnapshotList: + EditorGUI.BeginDisabledGroup(!flag); + this.m_SnapshotListView.OnGUI(rect); + EditorGUI.EndDisabledGroup(); + break; + default: + Debug.LogError("Unhandled enum value"); + break; + } + if (current.type == EventType.ContextClick) + { + Rect rect2 = new Rect(rect.x, rect.y, rect.width - 15f, 22f); + if (rect2.Contains(current.mousePosition)) + { + this.ReorderContextMenu(rect2, i); + current.Use(); + } + } + } + } + } + private void ReorderContextMenu(Rect rect, int sectionIndex) + { + Event current = Event.current; + if (Event.current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) + { + GUIContent content = new GUIContent((this.m_LayoutMode != AudioMixerWindow.LayoutMode.Horizontal) ? "Move Up" : "Move Left"); + GUIContent content2 = new GUIContent((this.m_LayoutMode != AudioMixerWindow.LayoutMode.Horizontal) ? "Move Down" : "Move Right"); + GenericMenu genericMenu = new GenericMenu(); + if (sectionIndex > 1) + { + genericMenu.AddItem(content, false, new GenericMenu.MenuFunction2(this.ChangeSectionOrder), new Vector2((float)sectionIndex, -1f)); + } + else + { + genericMenu.AddDisabledItem(content); + } + if (sectionIndex > 0 && sectionIndex < this.m_SectionOrder.Length - 1) + { + genericMenu.AddItem(content2, false, new GenericMenu.MenuFunction2(this.ChangeSectionOrder), new Vector2((float)sectionIndex, 1f)); + } + else + { + genericMenu.AddDisabledItem(content2); + } + genericMenu.ShowAsContext(); + } + } + private void ChangeSectionOrder(object userData) + { + Vector2 vector = (Vector2)userData; + int num = (int)vector.x; + int num2 = (int)vector.y; + int num3 = Mathf.Clamp(num + num2, 0, this.m_SectionOrder.Length - 1); + if (num3 != num) + { + AudioMixerWindow.SectionType sectionType = this.m_SectionOrder[num]; + this.m_SectionOrder[num] = this.m_SectionOrder[num3]; + this.m_SectionOrder[num3] = sectionType; + } + } + public MixerParameterDefinition ParamDef(string name, string desc, string units, float displayScale, float minRange, float maxRange, float defaultValue) + { + return new MixerParameterDefinition + { + name = name, + description = desc, + units = units, + displayScale = displayScale, + minRange = minRange, + maxRange = maxRange, + defaultValue = defaultValue + }; + } + public virtual void AddItemsToMenu(GenericMenu menu) + { + menu.AddItem(new GUIContent("Sort groups alphabetically"), this.m_SortGroupsAlphabetically, delegate + { + this.m_SortGroupsAlphabetically = !this.m_SortGroupsAlphabetically; + }); + menu.AddItem(new GUIContent("Show referenced buses"), this.m_ShowReferencedBuses, delegate + { + this.m_ShowReferencedBuses = !this.m_ShowReferencedBuses; + }); + menu.AddItem(new GUIContent("Show bus connections"), this.m_ShowBusConnections, delegate + { + this.m_ShowBusConnections = !this.m_ShowBusConnections; + }); + if (this.m_ShowBusConnections) + { + menu.AddItem(new GUIContent("Highlight bus connections of selection"), this.m_ShowBusConnectionsOfSelection, delegate + { + this.m_ShowBusConnectionsOfSelection = !this.m_ShowBusConnectionsOfSelection; + }); + } + menu.AddSeparator(string.Empty); + menu.AddItem(new GUIContent("Vertical layout"), this.layoutMode == AudioMixerWindow.LayoutMode.Vertical, delegate + { + this.layoutMode = AudioMixerWindow.LayoutMode.Vertical; + }); + menu.AddItem(new GUIContent("Horizontal layout"), this.layoutMode == AudioMixerWindow.LayoutMode.Horizontal, delegate + { + this.layoutMode = AudioMixerWindow.LayoutMode.Horizontal; + }); + menu.AddSeparator(string.Empty); + menu.AddItem(new GUIContent("Use RMS metering for display"), EditorPrefs.GetBool(AudioMixerWindow.kAudioMixerUseRMSMetering, true), delegate + { + EditorPrefs.SetBool(AudioMixerWindow.kAudioMixerUseRMSMetering, true); + }); + menu.AddItem(new GUIContent("Use peak metering for display"), !EditorPrefs.GetBool(AudioMixerWindow.kAudioMixerUseRMSMetering, true), delegate + { + EditorPrefs.SetBool(AudioMixerWindow.kAudioMixerUseRMSMetering, false); + }); + if (Unsupported.IsDeveloperBuild()) + { + menu.AddSeparator(string.Empty); + menu.AddItem(new GUIContent("DEVELOPER/Groups Rendered Above"), this.m_GroupsRenderedAboveSections, delegate + { + this.m_GroupsRenderedAboveSections = !this.m_GroupsRenderedAboveSections; + }); + menu.AddItem(new GUIContent("DEVELOPER/Build 10 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(0, 7, 10); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build 20 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(0, 7, 20); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build 40 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(0, 7, 40); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build 80 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(0, 7, 80); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build 160 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(0, 7, 160); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build chain of 10 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(1, 1, 10); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build chain of 20 groups "), false, delegate + { + this.m_Controller.BuildTestSetup(1, 1, 20); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build chain of 40 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(1, 1, 40); + }); + menu.AddItem(new GUIContent("DEVELOPER/Build chain of 80 groups"), false, delegate + { + this.m_Controller.BuildTestSetup(1, 1, 80); + }); + menu.AddItem(new GUIContent("DEVELOPER/Show overlays"), this.m_ShowDeveloperOverlays, delegate + { + this.m_ShowDeveloperOverlays = !this.m_ShowDeveloperOverlays; + }); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixersDataSource.cs b/UnityEditor/UnityEditor/AudioMixersDataSource.cs new file mode 100644 index 00000000..7964b555 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixersDataSource.cs @@ -0,0 +1,191 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +using UnityEngine.Audio; +namespace UnityEditor +{ + internal class AudioMixersDataSource : TreeViewDataSource + { + private Func> m_GetAllControllersCallback; + public AudioMixersDataSource(TreeView treeView, Func> getAllControllersCallback) : base(treeView) + { + base.showRootNode = false; + this.m_GetAllControllersCallback = getAllControllersCallback; + } + public override void FetchData() + { + int depth = -1; + bool flag = this.m_TreeView.state.expandedIDs.Count == 0; + this.m_RootItem = new TreeViewItem(1010101010, depth, null, "InvisibleRoot"); + this.SetExpanded(this.m_RootItem.id, true); + List list = this.m_GetAllControllersCallback(); + this.m_NeedRefreshVisibleFolders = true; + if (list.Count > 0) + { + List list2 = ( + from mixer in list + select new AudioMixerItem(mixer.GetInstanceID(), 0, this.m_RootItem, mixer.name, mixer, AudioMixersDataSource.GetInfoText(mixer))).ToList(); + foreach (AudioMixerItem current in list2) + { + this.SetChildParentOfMixerItem(current, list2); + } + this.SetItemDepthRecursive(this.m_RootItem, -1); + this.SortRecursive(this.m_RootItem); + if (flag) + { + this.m_TreeView.data.SetExpandedWithChildren(this.m_RootItem, true); + } + } + } + private static string GetInfoText(AudioMixerController controller) + { + string result; + if (controller.outputAudioMixerGroup != null) + { + result = string.Format("({0} of {1})", controller.outputAudioMixerGroup.name, controller.outputAudioMixerGroup.audioMixer.name); + } + else + { + result = "(Audio Listener)"; + } + return result; + } + private void SetChildParentOfMixerItem(AudioMixerItem item, List items) + { + if (item.mixer.outputAudioMixerGroup != null) + { + AudioMixer audioMixer = item.mixer.outputAudioMixerGroup.audioMixer; + AudioMixerItem audioMixerItem = TreeViewUtility.FindItemInList(audioMixer.GetInstanceID(), items) as AudioMixerItem; + if (audioMixerItem != null) + { + audioMixerItem.AddChild(item); + } + } + else + { + this.m_RootItem.AddChild(item); + } + } + private void SetItemDepthRecursive(TreeViewItem item, int depth) + { + item.depth = depth; + if (!item.hasChildren) + { + return; + } + foreach (TreeViewItem current in item.children) + { + this.SetItemDepthRecursive(current, depth + 1); + } + } + private void SortRecursive(TreeViewItem item) + { + if (!item.hasChildren) + { + return; + } + item.children.Sort(new TreeViewItemAlphaNumericSort()); + foreach (TreeViewItem current in item.children) + { + this.SortRecursive(current); + } + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return true; + } + public int GetInsertAfterItemIDForNewItem(string newName, TreeViewItem parentItem) + { + int result = parentItem.id; + if (!parentItem.hasChildren) + { + return result; + } + for (int i = 0; i < parentItem.children.Count; i++) + { + int id = parentItem.children[i].id; + string assetPath = AssetDatabase.GetAssetPath(id); + if (EditorUtility.NaturalCompare(Path.GetFileNameWithoutExtension(assetPath), newName) > 0) + { + break; + } + result = id; + } + return result; + } + public override void InsertFakeItem(int id, int parentID, string name, Texture2D icon) + { + TreeViewItem treeViewItem = this.FindItem(id); + if (treeViewItem != null) + { + Debug.LogError(string.Concat(new object[] + { + "Cannot insert fake Item because id is not unique ", + id, + " Item already there: ", + treeViewItem.displayName + })); + return; + } + if (this.FindItem(parentID) != null) + { + this.SetExpanded(parentID, true); + List visibleRows = this.GetVisibleRows(); + int indexOfID = TreeView.GetIndexOfID(visibleRows, parentID); + TreeViewItem treeViewItem2; + if (indexOfID >= 0) + { + treeViewItem2 = visibleRows[indexOfID]; + } + else + { + treeViewItem2 = this.m_RootItem; + } + int num = treeViewItem2.depth + 1; + this.m_FakeItem = new TreeViewItem(id, num, treeViewItem2, name); + this.m_FakeItem.icon = icon; + int insertAfterItemIDForNewItem = this.GetInsertAfterItemIDForNewItem(name, treeViewItem2); + int num2 = TreeView.GetIndexOfID(visibleRows, insertAfterItemIDForNewItem); + if (num2 >= 0) + { + while (++num2 < visibleRows.Count) + { + if (visibleRows[num2].depth <= num) + { + break; + } + } + if (num2 < visibleRows.Count) + { + visibleRows.Insert(num2, this.m_FakeItem); + } + else + { + visibleRows.Add(this.m_FakeItem); + } + } + else + { + if (visibleRows.Count > 0) + { + visibleRows.Insert(0, this.m_FakeItem); + } + else + { + visibleRows.Add(this.m_FakeItem); + } + } + this.m_NeedRefreshVisibleFolders = false; + this.m_TreeView.Frame(this.m_FakeItem.id, true, false); + this.m_TreeView.Repaint(); + } + else + { + Debug.LogError("No parent Item found with ID: " + parentID); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixersTreeView.cs b/UnityEditor/UnityEditor/AudioMixersTreeView.cs new file mode 100644 index 00000000..b2c6b6f8 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixersTreeView.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.Audio; +using UnityEngine; +using UnityEngine.Audio; +namespace UnityEditor +{ + internal class AudioMixersTreeView + { + private class Styles + { + public GUIStyle optionsButton = "PaneOptions"; + public GUIContent header = new GUIContent("Mixers", "All mixers in the project are shown here. By default a mixer outputs to the AudioListener but mixers can also route their output to other mixers. Each mixer shows where it outputs (in parenthesis). To reroute a mixer simply drag the mixer upon another mixer and select a group from the popup."); + public GUIContent addText = new GUIContent("+", "Add mixer asset. The asset will be saved in the same folder as the current selected mixer or if none is selected saved in the Assets folder."); + public Texture2D audioMixerIcon = EditorGUIUtility.FindTexture("AudioMixerController Icon"); + } + private const int kObjectSelectorID = 1212; + private const string kExpandedStateIdentifier = "AudioMixerWindowMixers"; + private TreeView m_TreeView; + private int m_TreeViewKeyboardControlID; + private List m_DraggedMixers; + private static AudioMixersTreeView.Styles s_Styles; + public AudioMixersTreeView(AudioMixerWindow mixerWindow, TreeViewState treeState, Func> getAllControllersCallback) + { + this.m_TreeView = new TreeView(mixerWindow, treeState); + this.m_TreeView.deselectOnUnhandledMouseDown = false; + TreeView expr_25 = this.m_TreeView; + expr_25.selectionChangedCallback = (Action)Delegate.Combine(expr_25.selectionChangedCallback, new Action(this.OnTreeSelectionChanged)); + TreeView expr_4C = this.m_TreeView; + expr_4C.contextClickCallback = (Action)Delegate.Combine(expr_4C.contextClickCallback, new Action(this.OnTreeViewContextClick)); + AudioMixersTreeViewGUI gui = new AudioMixersTreeViewGUI(this.m_TreeView); + AudioMixersDataSource data = new AudioMixersDataSource(this.m_TreeView, getAllControllersCallback); + AudioMixerTreeViewDragging dragging = new AudioMixerTreeViewDragging(this.m_TreeView, new Action, AudioMixerController>(this.OnMixersDroppedOnMixerCallback)); + this.m_TreeView.Init(mixerWindow.position, data, gui, dragging); + this.m_TreeView.ReloadData(); + } + public void ReloadTree() + { + this.m_TreeView.ReloadData(); + this.m_TreeView.Repaint(); + } + public void OnMixerControllerChanged(AudioMixerController controller) + { + if (controller != null) + { + this.m_TreeView.SetSelection(new int[] + { + controller.GetInstanceID() + }, true); + } + } + public void DeleteAudioMixerCallback(object obj) + { + AudioMixerController audioMixerController = (AudioMixerController)obj; + if (audioMixerController != null) + { + Selection.activeObject = audioMixerController; + ProjectBrowser.DeleteSelectedAssets(true); + } + } + public void OnTreeViewContextClick(int index) + { + AudioMixerItem audioMixerItem = (AudioMixerItem)this.m_TreeView.FindNode(index); + if (audioMixerItem != null) + { + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(new GUIContent("Delete AudioMixer"), false, new GenericMenu.MenuFunction2(this.DeleteAudioMixerCallback), audioMixerItem.mixer); + genericMenu.ShowAsContext(); + } + } + public void OnTreeSelectionChanged(int[] selection) + { + Selection.instanceIDs = selection; + } + public float GetTotalHeight() + { + return 22f + Mathf.Max(20f, this.m_TreeView.gui.GetTotalSize(this.m_TreeView.data.GetVisibleRows()).y); + } + public void OnGUI(Rect rect) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + if (AudioMixersTreeView.s_Styles == null) + { + AudioMixersTreeView.s_Styles = new AudioMixersTreeView.Styles(); + } + this.m_TreeView.OnEvent(); + Rect r; + Rect rect2; + AudioMixerDrawUtils.DrawRegionBg(rect, out r, out rect2); + AudioMixerDrawUtils.HeaderLabel(r, AudioMixersTreeView.s_Styles.header, AudioMixersTreeView.s_Styles.audioMixerIcon); + if (GUI.Button(new Rect(r.xMax - 15f, r.y + 3f, 15f, 15f), AudioMixersTreeView.s_Styles.addText, EditorStyles.label)) + { + AudioMixersTreeViewGUI audioMixersTreeViewGUI = this.m_TreeView.gui as AudioMixersTreeViewGUI; + audioMixersTreeViewGUI.BeginCreateNewMixer(); + } + this.m_TreeView.OnGUI(rect2, controlID); + if (this.m_TreeView.data.GetVisibleRows().Count == 0) + { + EditorGUI.BeginDisabledGroup(true); + GUI.Label(new RectOffset(-20, 0, -2, 0).Add(rect2), "No mixers found"); + EditorGUI.EndDisabledGroup(); + } + AudioMixerDrawUtils.DrawScrollDropShadow(rect2, this.m_TreeView.state.scrollPos.y, this.m_TreeView.gui.GetTotalSize(this.m_TreeView.data.GetVisibleRows()).y); + this.HandleCommandEvents(controlID); + this.HandleObjectSelectorResult(); + } + private void HandleCommandEvents(int treeViewKeyboardControlID) + { + if (GUIUtility.keyboardControl != treeViewKeyboardControlID) + { + return; + } + EventType type = Event.current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") + { + Event.current.Use(); + if (flag) + { + ProjectBrowser.DeleteSelectedAssets(true); + } + } + else + { + if (Event.current.commandName == "Duplicate") + { + Event.current.Use(); + if (flag) + { + ProjectWindowUtil.DuplicateSelectedAssets(); + } + } + } + } + } + public void EndRenaming() + { + this.m_TreeView.EndNameEditing(true); + } + public void OnUndoRedoPerformed() + { + this.ReloadTree(); + } + private void OnMixersDroppedOnMixerCallback(List draggedMixers, AudioMixerController droppedUponMixer) + { + int[] array = ( + from i in draggedMixers + select i.GetInstanceID()).ToArray(); + this.m_TreeView.SetSelection(array, true); + Selection.instanceIDs = array; + if (droppedUponMixer == null) + { + Undo.RecordObjects(draggedMixers.ToArray(), "Set output group for mixer" + ((draggedMixers.Count <= 1) ? string.Empty : "s")); + foreach (AudioMixerController current in draggedMixers) + { + current.outputAudioMixerGroup = null; + } + this.ReloadTree(); + } + else + { + this.m_DraggedMixers = draggedMixers; + UnityEngine.Object obj = (draggedMixers.Count != 1) ? null : draggedMixers[0].outputAudioMixerGroup; + ObjectSelector.get.Show(obj, typeof(AudioMixerGroup), null, false, new List + { + droppedUponMixer.GetInstanceID() + }); + ObjectSelector.get.objectSelectorID = 1212; + ObjectSelector.get.title = "Select Output Audio Mixer Group"; + GUIUtility.ExitGUI(); + } + } + private void HandleObjectSelectorResult() + { + Event current = Event.current; + if (current.type == EventType.ExecuteCommand) + { + string commandName = current.commandName; + if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == 1212) + { + if (this.m_DraggedMixers == null || this.m_DraggedMixers.Count == 0) + { + Debug.LogError("Unexpected invalid mixer list used for dragging"); + } + UnityEngine.Object currentObject = ObjectSelector.GetCurrentObject(); + AudioMixerGroup outputAudioMixerGroup = (!(currentObject != null)) ? null : (currentObject as AudioMixerGroup); + Undo.RecordObjects(this.m_DraggedMixers.ToArray(), "Set output group for mixer" + ((this.m_DraggedMixers.Count <= 1) ? string.Empty : "s")); + foreach (AudioMixerController current2 in this.m_DraggedMixers) + { + if (current2 != null) + { + current2.outputAudioMixerGroup = outputAudioMixerGroup; + } + else + { + Debug.LogError("invalid mixer: is null"); + } + } + GUI.changed = true; + current.Use(); + this.ReloadTree(); + int[] selectedIDs = ( + from i in this.m_DraggedMixers + select i.GetInstanceID()).ToArray(); + this.m_TreeView.SetSelection(selectedIDs, true); + } + if (commandName == "ObjectSelectorClosed") + { + this.m_DraggedMixers = null; + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioMixersTreeViewGUI.cs b/UnityEditor/UnityEditor/AudioMixersTreeViewGUI.cs new file mode 100644 index 00000000..61587f89 --- /dev/null +++ b/UnityEditor/UnityEditor/AudioMixersTreeViewGUI.cs @@ -0,0 +1,118 @@ +using System; +using System.Linq; +using UnityEditor.ProjectWindowCallback; +using UnityEngine; +namespace UnityEditor +{ + internal class AudioMixersTreeViewGUI : TreeViewGUI + { + public AudioMixersTreeViewGUI(TreeView treeView) : base(treeView) + { + this.k_IconWidth = 0f; + this.k_TopRowMargin = (this.k_BottomRowMargin = 2f); + } + protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + if (!isPinging) + { + float contentIndent = this.GetContentIndent(item); + rect.x += contentIndent; + rect.width -= contentIndent; + } + AudioMixerItem audioMixerItem = item as AudioMixerItem; + if (audioMixerItem == null) + { + return; + } + GUIStyle gUIStyle = (!useBoldFont) ? TreeViewGUI.s_Styles.lineStyle : TreeViewGUI.s_Styles.lineBoldStyle; + gUIStyle.padding.left = (int)(this.k_IconWidth + base.iconTotalPadding + this.k_SpaceBetweenIconAndText); + gUIStyle.Draw(rect, label, false, false, selected, focused); + audioMixerItem.UpdateSuspendedString(false); + if (audioMixerItem.labelWidth <= 0f) + { + audioMixerItem.labelWidth = gUIStyle.CalcSize(GUIContent.Temp(label)).x; + } + Rect position = rect; + position.x += audioMixerItem.labelWidth + 8f; + EditorGUI.BeginDisabledGroup(true); + gUIStyle.Draw(position, audioMixerItem.infoText, false, false, false, false); + EditorGUI.EndDisabledGroup(); + if (base.iconOverlayGUI != null) + { + Rect arg = rect; + arg.width = this.k_IconWidth + base.iconTotalPadding; + base.iconOverlayGUI(item, arg); + } + } + protected override Texture GetIconForNode(TreeViewItem node) + { + return null; + } + protected CreateAssetUtility GetCreateAssetUtility() + { + return this.m_TreeView.state.createAssetUtility; + } + protected override void RenameEnded() + { + string name = (!string.IsNullOrEmpty(base.GetRenameOverlay().name)) ? base.GetRenameOverlay().name : base.GetRenameOverlay().originalName; + int userData = base.GetRenameOverlay().userData; + bool flag = this.GetCreateAssetUtility().IsCreatingNewAsset(); + bool userAcceptedRename = base.GetRenameOverlay().userAcceptedRename; + if (userAcceptedRename) + { + if (flag) + { + this.GetCreateAssetUtility().EndNewAssetCreation(name); + this.m_TreeView.ReloadData(); + } + else + { + ObjectNames.SetNameSmartWithInstanceID(userData, name); + } + } + } + protected override void ClearRenameAndNewNodeState() + { + this.GetCreateAssetUtility().Clear(); + base.ClearRenameAndNewNodeState(); + } + private AudioMixerItem GetSelectedItem() + { + return this.m_TreeView.FindNode(this.m_TreeView.GetSelection().FirstOrDefault()) as AudioMixerItem; + } + protected override void SyncFakeItem() + { + if (!this.m_TreeView.data.HasFakeItem() && this.GetCreateAssetUtility().IsCreatingNewAsset()) + { + int id = this.m_TreeView.data.root.id; + AudioMixerItem selectedItem = this.GetSelectedItem(); + if (selectedItem != null) + { + id = selectedItem.parent.id; + } + this.m_TreeView.data.InsertFakeItem(this.GetCreateAssetUtility().instanceID, id, this.GetCreateAssetUtility().originalName, this.GetCreateAssetUtility().icon); + } + if (this.m_TreeView.data.HasFakeItem() && !this.GetCreateAssetUtility().IsCreatingNewAsset()) + { + this.m_TreeView.data.RemoveFakeItem(); + } + } + public void BeginCreateNewMixer() + { + this.ClearRenameAndNewNodeState(); + string newAssetResourceFile = string.Empty; + AudioMixerItem selectedItem = this.GetSelectedItem(); + if (selectedItem != null && selectedItem.mixer.outputAudioMixerGroup != null) + { + newAssetResourceFile = selectedItem.mixer.outputAudioMixerGroup.GetInstanceID().ToString(); + } + int num = 0; + this.GetCreateAssetUtility().BeginNewAssetCreation(num, ScriptableObject.CreateInstance(), "NewAudioMixer.mixer", null, newAssetResourceFile); + this.SyncFakeItem(); + if (!base.GetRenameOverlay().BeginRename(this.GetCreateAssetUtility().originalName, num, 0f)) + { + Debug.LogError("Rename not started (when creating new asset)"); + } + } + } +} diff --git a/UnityEditor/UnityEditor/AudioSampleRateSetting.cs b/UnityEditor/UnityEditor/AudioSampleRateSetting.cs new file mode 100644 index 00000000..5849ce6c --- /dev/null +++ b/UnityEditor/UnityEditor/AudioSampleRateSetting.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum AudioSampleRateSetting + { + PreserveSampleRate, + OptimizeSampleRate, + OverrideSampleRate + } +} diff --git a/UnityEditor/UnityEditor/AudioSourceInspector.cs b/UnityEditor/UnityEditor/AudioSourceInspector.cs index 36397b0b..1c8aa434 100644 --- a/UnityEditor/UnityEditor/AudioSourceInspector.cs +++ b/UnityEditor/UnityEditor/AudioSourceInspector.cs @@ -14,9 +14,9 @@ private class AudioCurveWrapper public int id; public Color color; public SerializedProperty curveProp; - public int rangeMin; - public int rangeMax; - public AudioCurveWrapper(AudioSourceInspector.AudioCurveType type, string legend, int id, Color color, SerializedProperty curveProp, int rangeMin, int rangeMax) + public float rangeMin; + public float rangeMax; + public AudioCurveWrapper(AudioSourceInspector.AudioCurveType type, string legend, int id, Color color, SerializedProperty curveProp, float rangeMin, float rangeMax) { this.type = type; this.legend = new GUIContent(legend); @@ -30,22 +30,38 @@ public AudioCurveWrapper(AudioSourceInspector.AudioCurveType type, string legend private enum AudioCurveType { Volume, - Pan, + SpatialBlend, Lowpass, - Spread + Spread, + ReverbZoneMix } internal class Styles { public GUIStyle labelStyle = "ProfilerBadge"; public GUIContent rolloffLabel = new GUIContent("Volume Rolloff", "Which type of rolloff curve to use"); public string controlledByCurveLabel = "Controlled by curve"; - public GUIContent panLevelLabel = new GUIContent("Pan Level", "Sets how much the 3d position affects the pan and attenuation of the sound. If PanLevel is 0, 3D panning and attenuation is ignored."); - public GUIContent spreadLabel = new GUIContent("Spread", "Sets the spread of a 3d sound in speaker space."); + public GUIContent audioClipLabel = new GUIContent("AudioClip", "The AudioClip asset played by the AudioSource. Can be undefined if the AudioSource is generating a live stream of audio via OnAudioFilterRead."); + public GUIContent panStereoLabel = new GUIContent("Stereo Pan", "Only valid for Mono and Stereo AudioClips. Mono sounds will be panned at constant power left and right. Stereo sounds will Stereo sounds have each left/right value faded up and down according to the specified pan value."); + public GUIContent spatialBlendLabel = new GUIContent("Spatial Blend", "Sets how much this AudioSource is treated as a 3D source. 3D sources are affected by spatial position and spread. If 3D Pan Level is 0, all spatial attenuation is ignored."); + public GUIContent reverbZoneMixLabel = new GUIContent("Reverb Zone Mix", "Sets how much of the signal this AudioSource is mixing into the global reverb associated with the zones. [0, 1] is a linear range (like volume) while [1, 1.1] lets you boost the reverb mix by 10 dB."); + public GUIContent dopplerLevelLabel = new GUIContent("Doppler Level", "Specifies how much the pitch is changed based on the relative velocity between AudioListener and AudioSource."); + public GUIContent spreadLabel = new GUIContent("Spread", "Sets the spread of a 3d sound in speaker space"); + public GUIContent outputMixerGroupLabel = new GUIContent("Output", "Set whether the sound should play through an Audio Mixer first or directly to the Audio Listener"); + public GUIContent volumeLabel = new GUIContent("Volume", "Sets the overall volume of the sound."); + public GUIContent pitchLabel = new GUIContent("Pitch", "Sets the frequency of the sound. Use this to slow down or speed up the sound."); + public GUIContent priorityLabel = new GUIContent("Priority", "Sets the priority of the source. Note that a sound with a larger priority value will more likely be stolen by sounds with smaller priority values."); + public GUIContent priorityLeftLabel = new GUIContent("High"); + public GUIContent priorityRightLabel = new GUIContent("Low"); + public GUIContent spatialLeftLabel = new GUIContent("2D"); + public GUIContent spatialRightLabel = new GUIContent("3D"); + public GUIContent panLeftLabel = new GUIContent("Left"); + public GUIContent panRightLabel = new GUIContent("Right"); } private const int kRolloffCurveID = 0; - private const int kPanLevelCurveID = 1; + private const int kSpatialBlendCurveID = 1; private const int kSpreadCurveID = 2; private const int kLowPassCurveID = 3; + private const int kReverbZoneMixCurveID = 4; internal const float kMaxCutoffFrequency = 22000f; private const float EPSILON = 0.0001f; private SerializedProperty m_AudioClip; @@ -64,19 +80,21 @@ internal class Styles private SerializedProperty m_BypassEffects; private SerializedProperty m_BypassListenerEffects; private SerializedProperty m_BypassReverbZones; + private SerializedProperty m_OutputAudioMixerGroup; private SerializedObject m_LowpassObject; private SerializedProperty m_CutoffFrequency; private AudioSourceInspector.AudioCurveWrapper[] m_AudioCurves; + private bool m_RefreshCurveEditor; private CurveEditor m_CurveEditor; private Vector3 m_LastListenerPosition; private static CurveEditorSettings m_CurveEditorSettings = new CurveEditorSettings(); internal static Color kRolloffCurveColor = new Color(0.9f, 0.3f, 0.2f, 1f); - internal static Color kPanLevelCurveColor = new Color(0.25f, 0.7f, 0.2f, 1f); + internal static Color kSpatialCurveColor = new Color(0.25f, 0.7f, 0.2f, 1f); internal static Color kSpreadCurveColor = new Color(0.25f, 0.55f, 0.95f, 1f); internal static Color kLowPassCurveColor = new Color(0.8f, 0.25f, 0.9f, 1f); + internal static Color kReverbZoneMixCurveColor = new Color(0.7f, 0.7f, 0.2f, 1f); internal bool[] m_SelectedCurves = new bool[0]; private bool m_Expanded3D; - private bool m_Expanded2D; private static AudioSourceInspector.Styles ms_Styles; private void OnEnable() { @@ -95,16 +113,18 @@ private void OnEnable() this.m_BypassEffects = base.serializedObject.FindProperty("BypassEffects"); this.m_BypassListenerEffects = base.serializedObject.FindProperty("BypassListenerEffects"); this.m_BypassReverbZones = base.serializedObject.FindProperty("BypassReverbZones"); + this.m_OutputAudioMixerGroup = base.serializedObject.FindProperty("OutputAudioMixerGroup"); this.m_AudioCurves = new AudioSourceInspector.AudioCurveWrapper[] { - new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Volume, "Volume", 0, AudioSourceInspector.kRolloffCurveColor, base.serializedObject.FindProperty("rolloffCustomCurve"), 0, 1), - new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Pan, "Pan", 1, AudioSourceInspector.kPanLevelCurveColor, base.serializedObject.FindProperty("panLevelCustomCurve"), 0, 1), - new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Spread, "Spread", 2, AudioSourceInspector.kSpreadCurveColor, base.serializedObject.FindProperty("spreadCustomCurve"), 0, 1), - new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Lowpass, "Low-Pass", 3, AudioSourceInspector.kLowPassCurveColor, null, 0, 1) + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Volume, "Volume", 0, AudioSourceInspector.kRolloffCurveColor, base.serializedObject.FindProperty("rolloffCustomCurve"), 0f, 1f), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.SpatialBlend, "Spatial Blend", 1, AudioSourceInspector.kSpatialCurveColor, base.serializedObject.FindProperty("panLevelCustomCurve"), 0f, 1f), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Spread, "Spread", 2, AudioSourceInspector.kSpreadCurveColor, base.serializedObject.FindProperty("spreadCustomCurve"), 0f, 1f), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.Lowpass, "Low-Pass", 3, AudioSourceInspector.kLowPassCurveColor, null, 0f, 1f), + new AudioSourceInspector.AudioCurveWrapper(AudioSourceInspector.AudioCurveType.ReverbZoneMix, "Reverb Zone Mix", 4, AudioSourceInspector.kReverbZoneMixCurveColor, base.serializedObject.FindProperty("reverbZoneMixCustomCurve"), 0f, 1.1f) }; AudioSourceInspector.m_CurveEditorSettings.hRangeMin = 0f; AudioSourceInspector.m_CurveEditorSettings.vRangeMin = 0f; - AudioSourceInspector.m_CurveEditorSettings.vRangeMax = 1f; + AudioSourceInspector.m_CurveEditorSettings.vRangeMax = 1.1f; AudioSourceInspector.m_CurveEditorSettings.hRangeMax = 1f; AudioSourceInspector.m_CurveEditorSettings.vSlider = false; AudioSourceInspector.m_CurveEditorSettings.hSlider = false; @@ -120,19 +140,18 @@ private void OnEnable() this.m_CurveEditor.settings = AudioSourceInspector.m_CurveEditorSettings; this.m_CurveEditor.margin = 25f; this.m_CurveEditor.SetShownHRangeInsideMargins(0f, 1f); - this.m_CurveEditor.SetShownVRangeInsideMargins(0f, 1f); + this.m_CurveEditor.SetShownVRangeInsideMargins(0f, 1.1f); this.m_CurveEditor.ignoreScrollWheelUntilClicked = true; this.m_LastListenerPosition = AudioUtil.GetListenerPos(); EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); - this.m_Expanded2D = EditorPrefs.GetBool("AudioSourceExpanded2D", this.m_Expanded2D); this.m_Expanded3D = EditorPrefs.GetBool("AudioSourceExpanded3D", this.m_Expanded3D); } private void OnDisable() { - EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); + this.m_CurveEditor.OnDisable(); Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); - EditorPrefs.SetBool("AudioSourceExpanded2D", this.m_Expanded2D); + EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); EditorPrefs.SetBool("AudioSourceExpanded3D", this.m_Expanded3D); } private CurveWrapper[] GetCurveWrapperArray() @@ -267,7 +286,7 @@ private void Update() } private void UndoRedoPerformed() { - this.m_CurveEditor.animationCurves = this.GetCurveWrapperArray(); + this.m_RefreshCurveEditor = true; } private void HandleLowPassFilter() { @@ -293,7 +312,6 @@ private void HandleLowPassFilter() } public override void OnInspectorGUI() { - bool updateWrappers = false; this.InitStyles(); base.serializedObject.Update(); if (this.m_LowpassObject != null) @@ -311,7 +329,7 @@ public override void OnInspectorGUI() AnimationCurve animationCurveValue = audioCurveWrapper.curveProp.animationCurveValue; if (curveWrapperById == null != audioCurveWrapper.curveProp.hasMultipleDifferentValues) { - updateWrappers = true; + this.m_RefreshCurveEditor = true; } else { @@ -319,13 +337,13 @@ public override void OnInspectorGUI() { if (curveWrapperById.curve.length == 0) { - updateWrappers = true; + this.m_RefreshCurveEditor = true; } else { if (animationCurveValue.length >= 1 && animationCurveValue.keys[0].value != curveWrapperById.curve.keys[0].value) { - updateWrappers = true; + this.m_RefreshCurveEditor = true; } } } @@ -335,50 +353,50 @@ public override void OnInspectorGUI() { if (curveWrapperById != null) { - updateWrappers = true; + this.m_RefreshCurveEditor = true; } } } - this.UpdateWrappersAndLegend(ref updateWrappers); - EditorGUILayout.PropertyField(this.m_AudioClip, new GUILayoutOption[0]); - if (!this.m_AudioClip.hasMultipleDifferentValues && this.m_AudioClip.objectReferenceValue != null) - { - string t; - if (AudioUtil.Is3D(this.m_AudioClip.objectReferenceValue as AudioClip)) - { - t = "This is a 3D Sound."; - } - else - { - t = "This is a 2D Sound."; - } - EditorGUILayout.LabelField(EditorGUIUtility.blankContent, EditorGUIUtility.TempContent(t), EditorStyles.helpBox, new GUILayoutOption[0]); - } + this.UpdateWrappersAndLegend(); + EditorGUILayout.PropertyField(this.m_AudioClip, AudioSourceInspector.ms_Styles.audioClipLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_OutputAudioMixerGroup, AudioSourceInspector.ms_Styles.outputMixerGroupLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Mute, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_BypassEffects, new GUILayoutOption[0]); + bool flag = base.targets.Any((UnityEngine.Object t) => (t as AudioSource).outputAudioMixerGroup != null); + if (flag) + { + EditorGUI.BeginDisabledGroup(true); + } EditorGUILayout.PropertyField(this.m_BypassListenerEffects, new GUILayoutOption[0]); + if (flag) + { + EditorGUI.EndDisabledGroup(); + } EditorGUILayout.PropertyField(this.m_BypassReverbZones, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_PlayOnAwake, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Loop, new GUILayoutOption[0]); EditorGUILayout.Space(); - EditorGUILayout.IntSlider(this.m_Priority, 0, 256, new GUILayoutOption[0]); + EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.priorityLeftLabel, AudioSourceInspector.ms_Styles.priorityRightLabel); + EditorGUILayout.IntSlider(this.m_Priority, 0, 256, AudioSourceInspector.ms_Styles.priorityLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.Slider(this.m_Volume, 0f, 1f, AudioSourceInspector.ms_Styles.volumeLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.Slider(this.m_Pitch, -3f, 3f, AudioSourceInspector.ms_Styles.pitchLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.panLeftLabel, AudioSourceInspector.ms_Styles.panRightLabel); + EditorGUILayout.Slider(this.m_Pan2D, -1f, 1f, AudioSourceInspector.ms_Styles.panStereoLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUIUtility.sliderLabels.SetLabels(AudioSourceInspector.ms_Styles.spatialLeftLabel, AudioSourceInspector.ms_Styles.spatialRightLabel); + AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spatialBlendLabel, this.m_AudioCurves[1].curveProp, 0f, 1f, false); EditorGUILayout.Space(); - EditorGUILayout.Slider(this.m_Volume, 0f, 1f, new GUILayoutOption[0]); - EditorGUILayout.Slider(this.m_Pitch, -3f, 3f, new GUILayoutOption[0]); + AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.reverbZoneMixLabel, this.m_AudioCurves[4].curveProp, 0f, 1.1f, false); EditorGUILayout.Space(); this.m_Expanded3D = EditorGUILayout.Foldout(this.m_Expanded3D, "3D Sound Settings"); if (this.m_Expanded3D) { EditorGUI.indentLevel++; - this.Audio3DGUI(updateWrappers); - EditorGUI.indentLevel--; - } - this.m_Expanded2D = EditorGUILayout.Foldout(this.m_Expanded2D, "2D Sound Settings"); - if (this.m_Expanded2D) - { - EditorGUI.indentLevel++; - this.Audio2DGUI(); + this.Audio3DGUI(); EditorGUI.indentLevel--; } base.serializedObject.ApplyModifiedProperties(); @@ -394,9 +412,9 @@ private static void SetRolloffToTarget(SerializedProperty property, UnityEngine. property.serializedObject.ApplyModifiedProperties(); EditorUtility.ForceReloadInspectors(); } - private void Audio3DGUI(bool updateWrappers) + private void Audio3DGUI() { - EditorGUILayout.Slider(this.m_DopplerLevel, 0f, 5f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_DopplerLevel, 0f, 5f, AudioSourceInspector.ms_Styles.dopplerLevelLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); if (this.m_RolloffMode.hasMultipleDifferentValues || (this.m_RolloffMode.enumValueIndex == 2 && this.m_AudioCurves[0].curveProp.hasMultipleDifferentValues)) @@ -424,8 +442,7 @@ private void Audio3DGUI(bool updateWrappers) } EditorGUI.indentLevel--; } - AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.panLevelLabel, this.m_AudioCurves[1].curveProp, 0f, 1f); - AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spreadLabel, this.m_AudioCurves[2].curveProp, 0f, 360f); + AudioSourceInspector.AnimProp(AudioSourceInspector.ms_Styles.spreadLabel, this.m_AudioCurves[2].curveProp, 0f, 360f, true); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_MaxDistance, new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) @@ -434,7 +451,7 @@ private void Audio3DGUI(bool updateWrappers) } if (EditorGUI.EndChangeCheck()) { - updateWrappers = true; + this.m_RefreshCurveEditor = true; } Rect aspectRect = GUILayoutUtility.GetAspectRect(1.333f, GUI.skin.textField); aspectRect.xMin += EditorGUI.indent; @@ -442,7 +459,7 @@ private void Audio3DGUI(bool updateWrappers) { this.m_CurveEditor.rect = new Rect(aspectRect.x, aspectRect.y, aspectRect.width, aspectRect.height); } - this.UpdateWrappersAndLegend(ref updateWrappers); + this.UpdateWrappersAndLegend(); GUI.Label(this.m_CurveEditor.drawRect, GUIContent.none, "TextField"); this.m_CurveEditor.hRangeLocked = Event.current.shift; this.m_CurveEditor.vRangeLocked = EditorGUI.actionKey; @@ -482,13 +499,13 @@ private void Audio3DGUI(bool updateWrappers) } } } - private void UpdateWrappersAndLegend(ref bool updateWrappers) + private void UpdateWrappersAndLegend() { - if (updateWrappers) + if (this.m_RefreshCurveEditor) { this.m_CurveEditor.animationCurves = this.GetCurveWrapperArray(); this.SyncShownCurvesToLegend(this.GetShownAudioCurves()); - updateWrappers = false; + this.m_RefreshCurveEditor = false; } } private void DrawLegend() @@ -537,10 +554,6 @@ private void DrawLegend() } } } - private void Audio2DGUI() - { - EditorGUILayout.Slider(this.m_Pan2D, -1f, 1f, new GUILayoutOption[0]); - } private List GetShownAudioCurves() { return ( @@ -575,7 +588,7 @@ private void DrawLabel(string label, float value, Rect r) GUI.Label(new Rect(Mathf.Floor(vector3.x - vector.x / 2f), 2f, vector.x, 15f), label, AudioSourceInspector.ms_Styles.labelStyle); GUI.EndGroup(); } - internal static void AnimProp(GUIContent label, SerializedProperty prop, float min, float max) + internal static void AnimProp(GUIContent label, SerializedProperty prop, float min, float max, bool useNormalizedValue) { if (prop.hasMultipleDifferentValues) { @@ -596,12 +609,12 @@ internal static void AnimProp(GUIContent label, SerializedProperty prop, float m if (animationCurveValue.length != 1) { EditorGUI.BeginDisabledGroup(true); - EditorGUILayout.LabelField(label.text, "Controlled by Curve", new GUILayoutOption[0]); + EditorGUILayout.LabelField(label.text, AudioSourceInspector.ms_Styles.controlledByCurveLabel, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); } else { - float num = Mathf.Lerp(min, max, animationCurveValue.keys[0].value); + float num = (!useNormalizedValue) ? animationCurveValue.keys[0].value : Mathf.Lerp(min, max, animationCurveValue.keys[0].value); num = MathUtils.DiscardLeastSignificantDecimal(num); EditorGUI.BeginChangeCheck(); if (max > min) @@ -616,7 +629,7 @@ internal static void AnimProp(GUIContent label, SerializedProperty prop, float m { Keyframe key = animationCurveValue.keys[0]; key.time = 0f; - key.value = Mathf.InverseLerp(min, max, num); + key.value = ((!useNormalizedValue) ? num : Mathf.InverseLerp(min, max, num)); animationCurveValue.MoveKey(0, key); } } @@ -643,6 +656,7 @@ private void OnSceneGUI() Undo.RecordObject(audioSource, "AudioSource Distance"); audioSource.minDistance = minDistance; audioSource.maxDistance = maxDistance; + this.m_RefreshCurveEditor = true; } Handles.color = color; } diff --git a/UnityEditor/UnityEditor/AudioUtil.cs b/UnityEditor/UnityEditor/AudioUtil.cs index 6d41ab1f..298e01ea 100644 --- a/UnityEditor/UnityEditor/AudioUtil.cs +++ b/UnityEditor/UnityEditor/AudioUtil.cs @@ -6,6 +6,15 @@ namespace UnityEditor { internal sealed class AudioUtil { + public static extern bool resetAllAudioClipPlayCountsOnPlay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void PlayClip(AudioClip clip, [DefaultValue("0")] int startSample, [DefaultValue("false")] bool loop); @@ -69,7 +78,10 @@ public static void PlayClip(AudioClip clip) public static extern int GetSoundSize(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Texture2D GetWaveForm(AudioClip clip, AudioImporter importer, int channel, float width, float height); + public static extern AudioCompressionFormat GetSoundCompressionFormat(AudioClip clip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetWaveForm(AudioClip clip, AssetImporter importer, int channel, float width, float height); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Texture2D GetWaveFormFast(AudioClip clip, int channel, int fromSample, int toSample, float width, float height); @@ -81,12 +93,6 @@ public static void PlayClip(AudioClip clip) public static extern bool HasPreview(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsCompressed(AudioClip clip); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsStreamed(AudioClip clip); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern double GetDuration(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -96,16 +102,13 @@ public static void PlayClip(AudioClip clip) public static extern float GetFMODCPUUsage(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool Is3D(AudioClip clip); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool IsMovieAudio(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsMOD(AudioClip clip); + public static extern bool IsTrackerFile(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern int GetMODChannelCount(AudioClip clip); + public static extern int GetMusicChannelCount(AudioClip clip); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern AnimationCurve GetLowpassCurve(AudioLowPassFilter lowPassFilter); @@ -120,12 +123,6 @@ public static void PlayClip(AudioClip clip) public static extern void SetListenerTransform(Transform t); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern AudioType GetClipType(AudioClip clip); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern AudioType GetPlatformConversionType(AudioType inType, BuildTargetGroup targetGroup, AudioImporterFormat format); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HaveAudioCallback(MonoBehaviour behaviour); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/AvatarEditor.cs b/UnityEditor/UnityEditor/AvatarEditor.cs index cb980f7c..cd271696 100644 --- a/UnityEditor/UnityEditor/AvatarEditor.cs +++ b/UnityEditor/UnityEditor/AvatarEditor.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -144,6 +144,10 @@ private void OnEnable() } private void OnDisable() { + if (this.m_EditMode == AvatarEditor.EditMode.Editing) + { + this.editor.Disable(); + } EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, new EditorApplication.CallbackFunction(this.Update)); if (this.m_SerializedObject != null) { @@ -158,7 +162,7 @@ private void OnDestroy() this.SwitchToAssetMode(); } } - private void ShowOriginalObject() + private void SelectAsset() { UnityEngine.Object activeObject; if (this.m_CameFromImportSettings) @@ -279,7 +283,7 @@ internal void SwitchToEditMode() this.ChangeInspectorLock(true); this.m_UserFileName = EditorApplication.currentScene; EditorApplication.NewScene(); - this.m_GameObject = (UnityEngine.Object.Instantiate(this.prefab) as GameObject); + this.m_GameObject = UnityEngine.Object.Instantiate(this.prefab); if (base.serializedObject.FindProperty("m_OptimizeGameObjects").boolValue) { AnimatorUtility.DeoptimizeTransformHierarchy(this.m_GameObject); @@ -333,6 +337,7 @@ internal void SwitchToAssetMode() } this.m_EditMode = AvatarEditor.EditMode.Stopping; this.DestroyEditor(); + this.ChangeInspectorLock(this.m_InspectorLocked); if (!EditorApplication.isUpdating && !Unsupported.IsDestroyScriptableObject(this)) { string currentScene = EditorApplication.currentScene; @@ -373,10 +378,9 @@ internal void SwitchToAssetMode() EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, CleanUpSceneOnDestroy); } } - this.ChangeInspectorLock(this.m_InspectorLocked); this.m_GameObject = null; this.m_ModelBones = null; - this.ShowOriginalObject(); + this.SelectAsset(); if (!this.m_CameFromImportSettings) { this.m_EditMode = AvatarEditor.EditMode.NotEditing; @@ -407,7 +411,7 @@ public void Update() { this.m_SwitchToEditMode = false; this.SwitchToEditMode(); - EditorApplication.RequestRepaintAllViews(); + base.Repaint(); } if (this.m_EditMode == AvatarEditor.EditMode.Editing) { diff --git a/UnityEditor/UnityEditor/AvatarMappingEditor.cs b/UnityEditor/UnityEditor/AvatarMappingEditor.cs index 7b27f98c..1db133b4 100644 --- a/UnityEditor/UnityEditor/AvatarMappingEditor.cs +++ b/UnityEditor/UnityEditor/AvatarMappingEditor.cs @@ -57,6 +57,8 @@ public Styles() protected AvatarSetupTool.BoneWrapper[] m_Bones; internal static int s_SelectedBoneIndex = -1; protected bool m_HasSkinnedMesh; + private Editor m_CurrentTransformEditor; + private bool m_CurrentTransformEditorFoldout; protected int[][] m_BodyPartHumanBone = new int[][] { new int[] @@ -173,6 +175,22 @@ public override void Enable(AvatarEditor inspector) base.Enable(inspector); this.Init(); } + public override void Disable() + { + if (this.m_CurrentTransformEditor != null) + { + UnityEngine.Object.DestroyImmediate(this.m_CurrentTransformEditor); + } + base.Disable(); + } + public override void OnDestroy() + { + if (this.m_CurrentTransformEditor != null) + { + UnityEngine.Object.DestroyImmediate(this.m_CurrentTransformEditor); + } + base.OnDestroy(); + } protected void Init() { if (base.gameObject == null) @@ -184,6 +202,12 @@ protected void Init() this.m_Bones = AvatarSetupTool.GetHumanBones(base.serializedObject, base.modelBones); } this.ValidateMapping(); + if (this.m_CurrentTransformEditor != null) + { + UnityEngine.Object.DestroyImmediate(this.m_CurrentTransformEditor); + this.m_CurrentTransformEditor = null; + } + this.m_CurrentTransformEditorFoldout = true; this.m_HasSkinnedMesh = (base.gameObject.GetComponentInChildren() != null); this.InitPose(); SceneView.RepaintAll(); @@ -314,6 +338,31 @@ public override void OnInspectorGUI() this.TransferPoseIfChanged(); } base.ApplyRevertGUI(); + if (Selection.activeTransform != null) + { + if (this.m_CurrentTransformEditor != null && this.m_CurrentTransformEditor.target != Selection.activeTransform) + { + UnityEngine.Object.DestroyImmediate(this.m_CurrentTransformEditor); + } + if (this.m_CurrentTransformEditor == null) + { + this.m_CurrentTransformEditor = Editor.CreateEditor(Selection.activeTransform); + } + EditorGUILayout.Space(); + this.m_CurrentTransformEditorFoldout = EditorGUILayout.InspectorTitlebar(this.m_CurrentTransformEditorFoldout, Selection.activeTransform); + if (this.m_CurrentTransformEditorFoldout && this.m_CurrentTransformEditor != null) + { + this.m_CurrentTransformEditor.OnInspectorGUI(); + } + } + else + { + if (this.m_CurrentTransformEditor != null) + { + UnityEngine.Object.DestroyImmediate(this.m_CurrentTransformEditor); + this.m_CurrentTransformEditor = null; + } + } } protected void DebugPoseButtons() { @@ -581,7 +630,7 @@ protected BoneState GetBoneState(int i, out string error) error = bone.messageName + " is not a child of " + boneWrapper.messageName + "."; return BoneState.InvalidHierarchy; } - if (i != 23 && boneWrapper.bone != null && boneWrapper.bone != bone.bone && (bone.bone.position - boneWrapper.bone.position).sqrMagnitude < 1.401298E-45f) + if (i != 23 && boneWrapper.bone != null && boneWrapper.bone != bone.bone && (bone.bone.position - boneWrapper.bone.position).sqrMagnitude < Mathf.Epsilon) { error = bone.messageName + " has bone length of zero."; return BoneState.BoneLenghtIsZero; @@ -722,7 +771,7 @@ protected void ApplyTemplate() string boneName = humanTemplate.Find(this.m_Bones[i].humanBoneName); if (boneName.Length > 0) { - Transform bone = base.modelBones.Keys.First((Transform f) => AvatarMappingEditor.MatchName(f.name, boneName)); + Transform bone = base.modelBones.Keys.FirstOrDefault((Transform f) => AvatarMappingEditor.MatchName(f.name, boneName)); this.m_Bones[i].bone = bone; } else diff --git a/UnityEditor/UnityEditor/AvatarMaskInspector.cs b/UnityEditor/UnityEditor/AvatarMaskInspector.cs index 140b3b1e..ed1d8a19 100644 --- a/UnityEditor/UnityEditor/AvatarMaskInspector.cs +++ b/UnityEditor/UnityEditor/AvatarMaskInspector.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -190,6 +190,10 @@ private void UpdateMask(ClipAnimationMaskType maskType) { AvatarMask avatarMask2 = this.target as AvatarMask; avatarMask2.Copy(avatarMask); + if (this.humanTransforms != null) + { + AvatarMaskUtility.SetActiveHumanTransforms(avatarMask2, this.humanTransforms); + } this.FillNodeInfos(avatarMask2); } } diff --git a/UnityEditor/UnityEditor/AvatarMaskUtility.cs b/UnityEditor/UnityEditor/AvatarMaskUtility.cs index 215ab91b..0eacd624 100644 --- a/UnityEditor/UnityEditor/AvatarMaskUtility.cs +++ b/UnityEditor/UnityEditor/AvatarMaskUtility.cs @@ -1,5 +1,5 @@ using System; -using UnityEditorInternal; +using UnityEditor.Animations; namespace UnityEditor { internal class AvatarMaskUtility @@ -23,9 +23,8 @@ public static string[] GetAvatarHumanTransform(SerializedObject so, string[] ref } public static void UpdateTransformMask(AvatarMask mask, string[] refTransformsPath, string[] humanTransforms) { - AvatarMaskUtility.c__AnonStorey50 c__AnonStorey = new AvatarMaskUtility.c__AnonStorey50(); + AvatarMaskUtility.c__AnonStorey69 c__AnonStorey = new AvatarMaskUtility.c__AnonStorey69(); c__AnonStorey.refTransformsPath = refTransformsPath; - mask.Reset(); mask.transformCount = c__AnonStorey.refTransformsPath.Length; int i; for (i = 0; i < c__AnonStorey.refTransformsPath.Length; i++) @@ -35,11 +34,22 @@ public static void UpdateTransformMask(AvatarMask mask, string[] refTransformsPa mask.SetTransformActive(i, value); } } + public static void SetActiveHumanTransforms(AvatarMask mask, string[] humanTransforms) + { + for (int i = 0; i < mask.transformCount; i++) + { + string path = mask.GetTransformPath(i); + if (ArrayUtility.FindIndex(humanTransforms, (string s) => path == s) != -1) + { + mask.SetTransformActive(i, true); + } + } + } private static string[] TokeniseHumanTransformsPath(string[] refTransformsPath, string[] humanTransforms) { - AvatarMaskUtility.c__AnonStorey52 c__AnonStorey = new AvatarMaskUtility.c__AnonStorey52(); - c__AnonStorey.humanTransforms = humanTransforms; - if (c__AnonStorey.humanTransforms == null) + AvatarMaskUtility.c__AnonStorey6C c__AnonStorey6C = new AvatarMaskUtility.c__AnonStorey6C(); + c__AnonStorey6C.humanTransforms = humanTransforms; + if (c__AnonStorey6C.humanTransforms == null) { return null; } @@ -48,9 +58,9 @@ private static string[] TokeniseHumanTransformsPath(string[] refTransformsPath, string.Empty }; int i; - for (i = 0; i < c__AnonStorey.humanTransforms.Length; i++) + for (i = 0; i < c__AnonStorey6C.humanTransforms.Length; i++) { - int num = ArrayUtility.FindIndex(refTransformsPath, (string s) => c__AnonStorey.humanTransforms[i] == FileUtil.GetLastPathNameComponent(s)); + int num = ArrayUtility.FindIndex(refTransformsPath, (string s) => c__AnonStorey6C.humanTransforms[i] == FileUtil.GetLastPathNameComponent(s)); if (num != -1) { int index = array.Length; diff --git a/UnityEditor/UnityEditor/AvatarPreview.cs b/UnityEditor/UnityEditor/AvatarPreview.cs index b2560def..33df48a5 100644 --- a/UnityEditor/UnityEditor/AvatarPreview.cs +++ b/UnityEditor/UnityEditor/AvatarPreview.cs @@ -1,4 +1,5 @@ using System; +using UnityEditor.Animations; using UnityEditorInternal; using UnityEngine; namespace UnityEditor @@ -22,13 +23,20 @@ private enum PreviewPopupOptions DefaultModel, Other } + protected enum ViewTool + { + None, + Pan, + Zoom, + Orbit + } public delegate void OnAvatarChange(); private const string kIkPref = "AvatarpreviewShowIK"; private const string kReferencePref = "AvatarpreviewShowReference"; private const string kSpeedPref = "AvatarpreviewSpeed"; private const float kTimeControlRectHeight = 21f; - private const int kPreviewLayer = 31; private const string s_PreviewStr = "Preview"; + private const string s_PreviewSceneStr = "PreviewSene"; private const float kFloorFadeDuration = 0.2f; private const float kFloorScale = 5f; private const float kFloorScaleSmall = 0.2f; @@ -52,6 +60,7 @@ private enum PreviewPopupOptions private Motion m_SourcePreviewMotion; private Animator m_SourceScenePreviewAnimator; private int m_PreviewHint = "Preview".GetHashCode(); + private int m_PreviewSceneHint = "PreviewSene".GetHashCode(); private Texture2D m_FloorTexture; private Mesh m_FloorPlane; private bool m_ShowReference; @@ -62,11 +71,15 @@ private enum PreviewPopupOptions private float m_PrevFloorHeight; private float m_NextFloorHeight; private Vector2 m_PreviewDir = new Vector2(120f, -20f); + private float m_AvatarScale = 1f; + private float m_ZoomFactor = 1f; + private Vector3 m_PivotPositionOffset = Vector3.zero; private static AvatarPreview.Styles s_Styles; private float m_LastNormalizedTime = -1000f; private float m_LastStartTime = -1000f; private float m_LastStopTime = -1000f; private bool m_NextTargetIsForward = true; + protected AvatarPreview.ViewTool m_ViewTool; public AvatarPreview.OnAvatarChange OnAvatarChangeFunc { set @@ -113,6 +126,62 @@ public ModelImporterAnimationType animationClipType return AvatarPreview.GetAnimationType(this.m_SourcePreviewMotion); } } + public Vector3 bodyPosition + { + get + { + return (!this.Animator || !this.Animator.isHuman) ? GameObjectInspector.GetRenderableCenterRecurse(this.m_PreviewInstance, 2, 8) : this.Animator.bodyPosition; + } + } + protected AvatarPreview.ViewTool viewTool + { + get + { + Event current = Event.current; + if (this.m_ViewTool == AvatarPreview.ViewTool.None) + { + bool flag = current.control && Application.platform == RuntimePlatform.OSXEditor; + bool actionKey = EditorGUI.actionKey; + bool flag2 = !actionKey && !flag && !current.alt; + if ((current.button <= 0 && flag2) || (current.button <= 0 && actionKey) || current.button == 2) + { + this.m_ViewTool = AvatarPreview.ViewTool.Pan; + } + else + { + if ((current.button <= 0 && flag) || (current.button == 1 && current.alt)) + { + this.m_ViewTool = AvatarPreview.ViewTool.Zoom; + } + else + { + if ((current.button <= 0 && current.alt) || current.button == 1) + { + this.m_ViewTool = AvatarPreview.ViewTool.Orbit; + } + } + } + } + return this.m_ViewTool; + } + } + protected MouseCursor currentCursor + { + get + { + switch (this.m_ViewTool) + { + case AvatarPreview.ViewTool.Pan: + return MouseCursor.Pan; + case AvatarPreview.ViewTool.Zoom: + return MouseCursor.Zoom; + case AvatarPreview.ViewTool.Orbit: + return MouseCursor.Orbit; + default: + return MouseCursor.Arrow; + } + } + } public AvatarPreview(Animator previewObjectInScene, Motion objectOnSameAsset) { this.InitInstance(previewObjectInScene, objectOnSameAsset); @@ -135,7 +204,7 @@ private static AnimationClip GetFirstAnimationClipFromMotion(Motion motion) { return animationClip; } - BlendTree blendTree = motion as BlendTree; + UnityEditor.Animations.BlendTree blendTree = motion as UnityEditor.Animations.BlendTree; if (blendTree) { AnimationClip[] animationClipsFlattened = blendTree.GetAnimationClipsFlattened(); @@ -170,11 +239,19 @@ public static ModelImporterAnimationType GetAnimationType(GameObject go) public static ModelImporterAnimationType GetAnimationType(Motion motion) { AnimationClip firstAnimationClipFromMotion = AvatarPreview.GetFirstAnimationClipFromMotion(motion); - if (firstAnimationClipFromMotion) + if (!firstAnimationClipFromMotion) { - return AnimationUtility.GetAnimationType(firstAnimationClipFromMotion); + return ModelImporterAnimationType.None; + } + if (firstAnimationClipFromMotion.legacy) + { + return ModelImporterAnimationType.Legacy; } - return ModelImporterAnimationType.None; + if (firstAnimationClipFromMotion.humanMotion) + { + return ModelImporterAnimationType.Human; + } + return ModelImporterAnimationType.Generic; } public static bool IsValidPreviewGameObject(GameObject target, ModelImporterAnimationType requiredClipType) { @@ -182,7 +259,7 @@ public static bool IsValidPreviewGameObject(GameObject target, ModelImporterAnim { Debug.LogWarning("Can't preview inactive object, using fallback object"); } - return target != null && target.activeSelf && GameObjectInspector.HasRenderablePartsRecurse(target) && AvatarPreview.GetAnimationType(target) == requiredClipType; + return target != null && target.activeSelf && GameObjectInspector.HasRenderablePartsRecurse(target) && (requiredClipType == ModelImporterAnimationType.None || AvatarPreview.GetAnimationType(target) == requiredClipType); } public static GameObject FindBestFittingRenderableGameObjectFromModelAsset(UnityEngine.Object asset, ModelImporterAnimationType animationType) { @@ -207,7 +284,7 @@ private static GameObject CalculatePreviewGameObject(Animator selectedAnimator, { AnimationClip firstAnimationClipFromMotion = AvatarPreview.GetFirstAnimationClipFromMotion(motion); GameObject gameObject = AvatarPreviewSelection.GetPreview(animationType); - if (AvatarPreview.IsValidPreviewGameObject(gameObject, animationType)) + if (AvatarPreview.IsValidPreviewGameObject(gameObject, ModelImporterAnimationType.None)) { return gameObject; } @@ -238,30 +315,39 @@ private static GameObject GetHumanoidFallback() { return (GameObject)EditorGUIUtility.Load("Avatar/DefaultAvatar.fbx"); } + public void ResetPreviewInstance() + { + UnityEngine.Object.DestroyImmediate(this.m_PreviewInstance); + GameObject go = AvatarPreview.CalculatePreviewGameObject(this.m_SourceScenePreviewAnimator, this.m_SourcePreviewMotion, this.animationClipType); + this.SetupBounds(go); + } + private void SetupBounds(GameObject go) + { + this.m_IsValid = (go != null && go != AvatarPreview.GetGenericAnimationFallback()); + if (go != null) + { + this.m_PreviewInstance = EditorUtility.InstantiateForAnimatorPreview(go); + Bounds bounds = new Bounds(this.m_PreviewInstance.transform.position, Vector3.zero); + GameObjectInspector.GetRenderableBoundsRecurse(ref bounds, this.m_PreviewInstance); + this.m_BoundingVolumeScale = Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)); + if (this.Animator && this.Animator.isHuman) + { + this.m_AvatarScale = (this.m_ZoomFactor = this.Animator.humanScale); + } + else + { + this.m_AvatarScale = (this.m_ZoomFactor = this.m_BoundingVolumeScale / 2f); + } + } + } private void InitInstance(Animator scenePreviewObject, Motion motion) { this.m_SourcePreviewMotion = motion; this.m_SourceScenePreviewAnimator = scenePreviewObject; if (this.m_PreviewInstance == null) { - GameObject gameObject = AvatarPreview.CalculatePreviewGameObject(scenePreviewObject, motion, this.animationClipType); - this.m_IsValid = (gameObject != null && gameObject != AvatarPreview.GetGenericAnimationFallback()); - if (gameObject != null) - { - this.m_PreviewInstance = (GameObject)EditorUtility.InstantiateRemoveAllNonAnimationComponents(gameObject, Vector3.zero, Quaternion.identity); - Bounds bounds = new Bounds(this.m_PreviewInstance.transform.position, Vector3.zero); - GameObjectInspector.GetRenderableBoundsRecurse(ref bounds, this.m_PreviewInstance); - this.m_BoundingVolumeScale = Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)); - GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_PreviewInstance); - if (this.Animator) - { - this.Animator.enabled = false; - this.Animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; - this.Animator.applyRootMotion = true; - this.Animator.logWarnings = false; - this.Animator.fireEvents = false; - } - } + GameObject go = AvatarPreview.CalculatePreviewGameObject(scenePreviewObject, motion, this.animationClipType); + this.SetupBounds(go); } if (this.timeControl == null) { @@ -271,25 +357,25 @@ private void InitInstance(Animator scenePreviewObject, Motion motion) { GameObject original = (GameObject)EditorGUIUtility.Load("Avatar/dial_flat.prefab"); this.m_ReferenceInstance = (GameObject)UnityEngine.Object.Instantiate(original, Vector3.zero, Quaternion.identity); - GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_ReferenceInstance); + EditorUtility.InitInstantiatedPreviewRecursive(this.m_ReferenceInstance); } if (this.m_DirectionInstance == null) { GameObject original2 = (GameObject)EditorGUIUtility.Load("Avatar/arrow.fbx"); this.m_DirectionInstance = (GameObject)UnityEngine.Object.Instantiate(original2, Vector3.zero, Quaternion.identity); - GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_DirectionInstance); + EditorUtility.InitInstantiatedPreviewRecursive(this.m_DirectionInstance); } if (this.m_PivotInstance == null) { GameObject original3 = (GameObject)EditorGUIUtility.Load("Avatar/root.fbx"); this.m_PivotInstance = (GameObject)UnityEngine.Object.Instantiate(original3, Vector3.zero, Quaternion.identity); - GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_PivotInstance); + EditorUtility.InitInstantiatedPreviewRecursive(this.m_PivotInstance); } if (this.m_RootInstance == null) { GameObject original4 = (GameObject)EditorGUIUtility.Load("Avatar/root.fbx"); this.m_RootInstance = (GameObject)UnityEngine.Object.Instantiate(original4, Vector3.zero, Quaternion.identity); - GameObjectInspector.InitInstantiatedPreviewRecursive(this.m_RootInstance); + EditorUtility.InitInstantiatedPreviewRecursive(this.m_RootInstance); } this.m_IKOnFeet = EditorPrefs.GetBool("AvatarpreviewShowIK", false); this.m_ShowReference = EditorPrefs.GetBool("AvatarpreviewShowReference", true); @@ -302,7 +388,7 @@ private void Init() { this.m_PreviewUtility = new PreviewRenderUtility(true); this.m_PreviewUtility.m_CameraFieldOfView = 30f; - this.m_PreviewUtility.m_Camera.cullingMask = -2147483648; + this.m_PreviewUtility.m_Camera.cullingMask = 1 << Camera.PreviewCullingLayer; } if (AvatarPreview.s_Styles == null) { @@ -323,22 +409,22 @@ private void Init() this.m_FloorMaterial.mainTexture = this.m_FloorTexture; this.m_FloorMaterial.mainTextureScale = Vector2.one * 5f * 4f; this.m_FloorMaterial.SetVector("_Alphas", new Vector4(0.5f, 0.3f, 0f, 0f)); - this.m_FloorMaterial.hideFlags = HideFlags.DontSave; + this.m_FloorMaterial.hideFlags = HideFlags.HideAndDontSave; this.m_FloorMaterialSmall = new Material(this.m_FloorMaterial); this.m_FloorMaterialSmall.mainTextureScale = Vector2.one * 0.2f * 4f; - this.m_FloorMaterialSmall.hideFlags = HideFlags.DontSave; + this.m_FloorMaterialSmall.hideFlags = HideFlags.HideAndDontSave; } if (this.m_ShadowMaskMaterial == null) { Shader shader2 = EditorGUIUtility.LoadRequired("Previews/PreviewShadowMask.shader") as Shader; this.m_ShadowMaskMaterial = new Material(shader2); - this.m_ShadowMaskMaterial.hideFlags = HideFlags.DontSave; + this.m_ShadowMaskMaterial.hideFlags = HideFlags.HideAndDontSave; } if (this.m_ShadowPlaneMaterial == null) { Shader shader3 = EditorGUIUtility.LoadRequired("Previews/PreviewShadowPlaneClip.shader") as Shader; this.m_ShadowPlaneMaterial = new Material(shader3); - this.m_ShadowPlaneMaterial.hideFlags = HideFlags.DontSave; + this.m_ShadowPlaneMaterial.hideFlags = HideFlags.HideAndDontSave; } } public void OnDestroy() @@ -501,20 +587,17 @@ private RenderTexture RenderPreviewShadowmap(Light light, float scale, Vector3 c public Texture DoRenderPreview(Rect previewRect, GUIStyle background) { this.m_PreviewUtility.BeginPreview(previewRect, background); + Vector3 bodyPosition = this.bodyPosition; Quaternion quaternion; Vector3 vector; Quaternion quaternion2; - Vector3 vector2; Vector3 pivotPos; - float num; if (this.Animator && this.Animator.isHuman) { quaternion = this.Animator.rootRotation; vector = this.Animator.rootPosition; quaternion2 = this.Animator.bodyRotation; - vector2 = this.Animator.bodyPosition; pivotPos = this.Animator.pivotPosition; - num = this.Animator.humanScale; } else { @@ -523,18 +606,14 @@ public Texture DoRenderPreview(Rect previewRect, GUIStyle background) quaternion = this.Animator.rootRotation; vector = this.Animator.rootPosition; quaternion2 = Quaternion.identity; - vector2 = GameObjectInspector.GetRenderableCenterRecurse(this.m_PreviewInstance, 2, 8); pivotPos = Vector3.zero; - num = this.m_BoundingVolumeScale / 2f; } else { quaternion = Quaternion.identity; vector = Vector3.zero; quaternion2 = Quaternion.identity; - vector2 = GameObjectInspector.GetRenderableCenterRecurse(this.m_PreviewInstance, 2, 8); pivotPos = Vector3.zero; - num = this.m_BoundingVolumeScale / 2f; } } bool oldFog = this.SetupPreviewLightingAndFx(); @@ -543,55 +622,55 @@ public Texture DoRenderPreview(Rect previewRect, GUIStyle background) Quaternion directionRot = Quaternion.LookRotation(forward); Vector3 directionPos = vector; Quaternion pivotRot = quaternion; - this.PositionPreviewObjects(pivotRot, pivotPos, quaternion2, vector2, directionRot, quaternion, vector, directionPos, num); - bool flag = Mathf.Abs(this.m_NextFloorHeight - this.m_PrevFloorHeight) > num * 0.01f; + this.PositionPreviewObjects(pivotRot, pivotPos, quaternion2, bodyPosition, directionRot, quaternion, vector, directionPos, this.m_AvatarScale); + bool flag = Mathf.Abs(this.m_NextFloorHeight - this.m_PrevFloorHeight) > this.m_ZoomFactor * 0.01f; + float num2; float num3; - float num4; if (flag) { - float num2 = (this.m_NextFloorHeight >= this.m_PrevFloorHeight) ? 0.8f : 0.2f; - num3 = ((this.timeControl.normalizedTime >= num2) ? this.m_NextFloorHeight : this.m_PrevFloorHeight); - num4 = Mathf.Clamp01(Mathf.Abs(this.timeControl.normalizedTime - num2) / 0.2f); + float num = (this.m_NextFloorHeight >= this.m_PrevFloorHeight) ? 0.8f : 0.2f; + num2 = ((this.timeControl.normalizedTime >= num) ? this.m_NextFloorHeight : this.m_PrevFloorHeight); + num3 = Mathf.Clamp01(Mathf.Abs(this.timeControl.normalizedTime - num) / 0.2f); } else { - num3 = this.m_PrevFloorHeight; - num4 = 1f; + num2 = this.m_PrevFloorHeight; + num3 = 1f; } Quaternion identity = Quaternion.identity; Vector3 position = new Vector3(0f, 0f, 0f); position = this.m_ReferenceInstance.transform.position; - position.y = num3; + position.y = num2; Matrix4x4 matrix; - RenderTexture renderTexture = this.RenderPreviewShadowmap(this.m_PreviewUtility.m_Light[0], num, vector2, position, out matrix); - this.m_PreviewUtility.m_Camera.nearClipPlane = 1f * num; - this.m_PreviewUtility.m_Camera.farClipPlane = 25f * num; + RenderTexture renderTexture = this.RenderPreviewShadowmap(this.m_PreviewUtility.m_Light[0], this.m_BoundingVolumeScale / 2f, bodyPosition, position, out matrix); + this.m_PreviewUtility.m_Camera.nearClipPlane = 0.5f * this.m_ZoomFactor; + this.m_PreviewUtility.m_Camera.farClipPlane = 100f * this.m_AvatarScale; Quaternion rotation = Quaternion.Euler(-this.m_PreviewDir.y, -this.m_PreviewDir.x, 0f); - Vector3 position2 = rotation * (Vector3.forward * -5.5f * num) + vector2; + Vector3 position2 = rotation * (Vector3.forward * -5.5f * this.m_ZoomFactor) + bodyPosition + this.m_PivotPositionOffset; this.m_PreviewUtility.m_Camera.transform.position = position2; this.m_PreviewUtility.m_Camera.transform.rotation = rotation; - position.y = num3; + position.y = num2; Material floorMaterial = this.m_FloorMaterial; - floorMaterial.mainTextureOffset = -floorMaterial.mainTextureScale * 0.5f - new Vector2(position.x, position.z) / num * 0.1f * 4f; + Matrix4x4 matrix2 = Matrix4x4.TRS(position, identity, Vector3.one * 5f * this.m_AvatarScale); + floorMaterial.mainTextureOffset = -new Vector2(position.x, position.z) * 5f * 0.08f * (1f / this.m_AvatarScale); floorMaterial.SetTexture("_ShadowTexture", renderTexture); floorMaterial.SetMatrix("_ShadowTextureMatrix", matrix); - floorMaterial.SetVector("_Alphas", new Vector4(0.5f * num4, 0.3f * num4, 0f, 0f)); - Matrix4x4 matrix2 = Matrix4x4.TRS(position, identity, Vector3.one * num * 5f); - Graphics.DrawMesh(this.m_FloorPlane, matrix2, floorMaterial, 31, this.m_PreviewUtility.m_Camera, 0); + floorMaterial.SetVector("_Alphas", new Vector4(0.5f * num3, 0.3f * num3, 0f, 0f)); + Graphics.DrawMesh(this.m_FloorPlane, matrix2, floorMaterial, Camera.PreviewCullingLayer, this.m_PreviewUtility.m_Camera, 0); if (flag) { bool flag2 = this.m_NextFloorHeight > this.m_PrevFloorHeight; - float num5 = (!flag2) ? this.m_PrevFloorHeight : this.m_NextFloorHeight; + float num4 = (!flag2) ? this.m_PrevFloorHeight : this.m_NextFloorHeight; float from = (!flag2) ? this.m_NextFloorHeight : this.m_PrevFloorHeight; - float num6 = ((num5 != num3) ? 1f : (1f - num4)) * Mathf.InverseLerp(from, num5, vector.y); - position.y = num5; + float num5 = ((num4 != num2) ? 1f : (1f - num3)) * Mathf.InverseLerp(from, num4, vector.y); + position.y = num4; Material floorMaterialSmall = this.m_FloorMaterialSmall; - floorMaterialSmall.mainTextureOffset = -floorMaterialSmall.mainTextureScale * 0.5f - new Vector2(position.x, position.z) / num * 0.1f * 4f; + floorMaterialSmall.mainTextureOffset = -new Vector2(position.x, position.z) * 0.2f * 0.08f; floorMaterialSmall.SetTexture("_ShadowTexture", renderTexture); floorMaterialSmall.SetMatrix("_ShadowTextureMatrix", matrix); - floorMaterialSmall.SetVector("_Alphas", new Vector4(0.5f * num6, 0f, 0f, 0f)); - Matrix4x4 matrix3 = Matrix4x4.TRS(position, identity, Vector3.one * num * 0.2f); - Graphics.DrawMesh(this.m_FloorPlane, matrix3, floorMaterialSmall, 31, this.m_PreviewUtility.m_Camera, 0); + floorMaterialSmall.SetVector("_Alphas", new Vector4(0.5f * num5, 0f, 0f, 0f)); + Matrix4x4 matrix3 = Matrix4x4.TRS(position, identity, Vector3.one * 0.2f * this.m_AvatarScale); + Graphics.DrawMesh(this.m_FloorPlane, matrix3, floorMaterialSmall, Camera.PreviewCullingLayer, this.m_PreviewUtility.m_Camera, 0); } this.SetPreviewCharacterEnabled(true, this.m_ShowReference); this.m_PreviewUtility.m_Camera.Render(); @@ -602,9 +681,9 @@ public Texture DoRenderPreview(Rect previewRect, GUIStyle background) } private bool SetupPreviewLightingAndFx() { - this.m_PreviewUtility.m_Light[0].intensity = 0.7f; + this.m_PreviewUtility.m_Light[0].intensity = 1.4f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); - this.m_PreviewUtility.m_Light[1].intensity = 0.7f; + this.m_PreviewUtility.m_Light[1].intensity = 1.4f; Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); bool fog = RenderSettings.fog; @@ -652,22 +731,6 @@ private void PositionPreviewObjects(Quaternion pivotRot, Vector3 pivotPos, Quate num2 += 1f; } } - if (Mathf.Abs(num2) > Mathf.Max(0.0001f, Mathf.Abs(num * 0.1f))) - { - Debug.LogError(string.Concat(new object[] - { - "Reported delta does not match with progression of time. Check that the OnInteractivePreviewGUI function only updates the Animator on Repaint events.\nlastNormalTime: ", - this.m_LastNormalizedTime, - ", normalizedDelta: ", - num, - ", expectedNormalizedTime: ", - Mathf.Repeat(this.m_LastNormalizedTime + num, 1f), - ", normalizedTime: ", - normalizedTime, - ", difference: ", - num2 - })); - } } this.m_LastNormalizedTime = normalizedTime; this.m_LastStartTime = this.timeControl.startTime; @@ -684,6 +747,77 @@ private void PositionPreviewObjects(Quaternion pivotRot, Vector3 pivotPos, Quate this.Animator.SetTarget(AvatarTarget.Root, (float)((!this.m_NextTargetIsForward) ? 0 : 1)); } } + public void AvatarTimeControlGUI(Rect rect) + { + Rect rect2 = rect; + rect2.height = 21f; + this.timeControl.DoTimeControl(rect2); + rect.y = rect.yMax - 20f; + float num = this.timeControl.currentTime - this.timeControl.startTime; + EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y, rect.width, 20f), string.Format("{0,2}:{1:00} ({2:000.0%})", (int)num, this.Repeat(Mathf.FloorToInt(num * (float)this.fps), this.fps), this.timeControl.normalizedTime)); + } + protected void HandleMouseDown(Event evt, int id, Rect previewRect) + { + if (this.viewTool != AvatarPreview.ViewTool.None && previewRect.Contains(evt.mousePosition)) + { + EditorGUIUtility.SetWantsMouseJumping(1); + evt.Use(); + GUIUtility.hotControl = id; + } + } + protected void HandleMouseUp(Event evt, int id) + { + if (GUIUtility.hotControl == id) + { + this.m_ViewTool = AvatarPreview.ViewTool.None; + GUIUtility.hotControl = 0; + EditorGUIUtility.SetWantsMouseJumping(0); + evt.Use(); + } + } + protected void HandleMouseDrag(Event evt, int id, Rect previewRect) + { + if (this.m_PreviewInstance == null) + { + return; + } + if (GUIUtility.hotControl == id) + { + switch (this.m_ViewTool) + { + case AvatarPreview.ViewTool.Pan: + this.DoAvatarPreviewPan(evt); + break; + case AvatarPreview.ViewTool.Zoom: + this.DoAvatarPreviewZoom(evt, -HandleUtility.niceMouseDeltaZoom * ((!evt.shift) ? 0.5f : 2f)); + break; + case AvatarPreview.ViewTool.Orbit: + this.DoAvatarPreviewOrbit(evt, previewRect); + break; + default: + Debug.Log("Enum value not handled"); + break; + } + } + } + protected void HandleViewTool(Event evt, EventType eventType, int id, Rect previewRect) + { + switch (eventType) + { + case EventType.MouseDown: + this.HandleMouseDown(evt, id, previewRect); + break; + case EventType.MouseUp: + this.HandleMouseUp(evt, id); + break; + case EventType.MouseDrag: + this.HandleMouseDrag(evt, id, previewRect); + break; + case EventType.ScrollWheel: + this.DoAvatarPreviewZoom(evt, HandleUtility.niceMouseDeltaZoom * ((!evt.shift) ? 0.5f : 2f)); + break; + } + } public void DoAvatarPreviewDrag(EventType type) { if (type == EventType.DragUpdated) @@ -696,7 +830,7 @@ public void DoAvatarPreviewDrag(EventType type) { DragAndDrop.visualMode = DragAndDropVisualMode.Link; GameObject gameObject = DragAndDrop.objectReferences[0] as GameObject; - if (gameObject && AvatarPreview.GetAnimationType(gameObject) == this.animationClipType) + if (gameObject) { DragAndDrop.AcceptDrag(); this.SetPreview(gameObject); @@ -704,14 +838,51 @@ public void DoAvatarPreviewDrag(EventType type) } } } - public void AvatarTimeControlGUI(Rect rect) + public void DoAvatarPreviewOrbit(Event evt, Rect previewRect) { - Rect rect2 = rect; - rect2.height = 21f; - this.timeControl.DoTimeControl(rect2); - rect.y = rect.yMax - 20f; - float num = this.timeControl.currentTime - this.timeControl.startTime; - EditorGUI.DropShadowLabel(new Rect(rect.x, rect.y, rect.width, 20f), string.Format("{0,2}:{1:00} ({2:000.0%})", (int)num, this.Repeat(Mathf.FloorToInt(num * (float)this.fps), this.fps), this.timeControl.normalizedTime)); + this.m_PreviewDir -= evt.delta * (float)((!evt.shift) ? 1 : 3) / Mathf.Min(previewRect.width, previewRect.height) * 140f; + this.m_PreviewDir.y = Mathf.Clamp(this.m_PreviewDir.y, -90f, 90f); + evt.Use(); + } + public void DoAvatarPreviewPan(Event evt) + { + Camera camera = this.m_PreviewUtility.m_Camera; + Vector3 vector = camera.WorldToScreenPoint(this.bodyPosition + this.m_PivotPositionOffset); + Vector3 a = new Vector3(-evt.delta.x, evt.delta.y, 0f); + vector += a * Mathf.Lerp(0.25f, 2f, this.m_ZoomFactor * 0.5f); + Vector3 b = camera.ScreenToWorldPoint(vector) - (this.bodyPosition + this.m_PivotPositionOffset); + this.m_PivotPositionOffset += b; + evt.Use(); + } + public void DoAvatarPreviewFrame(Event evt, EventType type, Rect previewRect) + { + if (type == EventType.KeyDown && evt.keyCode == KeyCode.F) + { + this.m_PivotPositionOffset = Vector3.zero; + this.m_ZoomFactor = this.m_AvatarScale; + evt.Use(); + } + if (type == EventType.KeyDown && Event.current.keyCode == KeyCode.G) + { + this.m_PivotPositionOffset = this.GetCurrentMouseWorldPosition(evt, previewRect) - this.bodyPosition; + evt.Use(); + } + } + protected Vector3 GetCurrentMouseWorldPosition(Event evt, Rect previewRect) + { + Camera camera = this.m_PreviewUtility.m_Camera; + float scaleFactor = this.m_PreviewUtility.GetScaleFactor(previewRect.width, previewRect.height); + return camera.ScreenToWorldPoint(new Vector3((evt.mousePosition.x - previewRect.x) * scaleFactor, (previewRect.height - (evt.mousePosition.y - previewRect.y)) * scaleFactor, 0f) + { + z = Vector3.Distance(this.bodyPosition, camera.transform.position) + }); + } + public void DoAvatarPreviewZoom(Event evt, float delta) + { + float num = -delta * 0.05f; + this.m_ZoomFactor += this.m_ZoomFactor * num; + this.m_ZoomFactor = Mathf.Max(this.m_ZoomFactor, this.m_AvatarScale / 10f); + evt.Use(); } public void DoAvatarPreview(Rect rect, GUIStyle background) { @@ -728,7 +899,6 @@ public void DoAvatarPreview(Rect rect, GUIStyle background) Rect rect2 = rect; rect2.yMin += 21f; rect2.height = Mathf.Max(rect2.height, 64f); - this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, rect2); int controlID = GUIUtility.GetControlID(this.m_PreviewHint, FocusType.Native, rect2); Event current = Event.current; EventType typeForControl = current.GetTypeForControl(controlID); @@ -739,13 +909,17 @@ public void DoAvatarPreview(Rect rect, GUIStyle background) } this.AvatarTimeControlGUI(rect); GUI.DrawTexture(position, AvatarPreview.s_Styles.avatarIcon.image); + int controlID2 = GUIUtility.GetControlID(this.m_PreviewSceneHint, FocusType.Native); + typeForControl = current.GetTypeForControl(controlID2); + this.DoAvatarPreviewDrag(typeForControl); + this.HandleViewTool(current, typeForControl, controlID2, rect2); + this.DoAvatarPreviewFrame(current, typeForControl, rect2); if (!this.m_IsValid) { Rect position2 = rect2; position2.yMax -= position2.height / 2f - 16f; EditorGUI.DropShadowLabel(position2, "No model is available for preview.\nPlease drag a model into this Preview Area."); } - this.DoAvatarPreviewDrag(typeForControl); if (current.type == EventType.ExecuteCommand) { string commandName = current.commandName; @@ -755,6 +929,10 @@ public void DoAvatarPreview(Rect rect, GUIStyle background) current.Use(); } } + if (current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(rect2, this.currentCursor); + } } private void SetPreviewAvatarOption(object obj) { diff --git a/UnityEditor/UnityEditor/AvatarSetupTool.cs b/UnityEditor/UnityEditor/AvatarSetupTool.cs index 7661d8c4..8e9256c0 100644 --- a/UnityEditor/UnityEditor/AvatarSetupTool.cs +++ b/UnityEditor/UnityEditor/AvatarSetupTool.cs @@ -639,14 +639,14 @@ public static void ClearSkeletonBoneArray(SerializedObject serializedObject) } public static void AutoSetupOnInstance(GameObject modelPrefab, SerializedObject modelImporterSerializedObject) { - GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab) as GameObject; + GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab); gameObject.hideFlags = HideFlags.HideAndDontSave; AvatarSetupTool.AutoSetup(modelPrefab, gameObject, modelImporterSerializedObject); UnityEngine.Object.DestroyImmediate(gameObject); } public static bool IsPoseValidOnInstance(GameObject modelPrefab, SerializedObject modelImporterSerializedObject) { - GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab) as GameObject; + GameObject gameObject = UnityEngine.Object.Instantiate(modelPrefab); gameObject.hideFlags = HideFlags.HideAndDontSave; Dictionary modelBones = AvatarSetupTool.GetModelBones(gameObject.transform, false, null); AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(modelImporterSerializedObject, modelBones); @@ -760,7 +760,7 @@ public static bool TestAndValidateAutoSetup(GameObject modelAsset) { list = new List(File.ReadAllLines(path)); } - GameObject gameObject = UnityEngine.Object.Instantiate(modelAsset) as GameObject; + GameObject gameObject = UnityEngine.Object.Instantiate(modelAsset); gameObject.hideFlags = HideFlags.HideAndDontSave; Dictionary modelBones = AvatarSetupTool.GetModelBones(gameObject.transform, false, null); AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(serializedObject, modelBones); diff --git a/UnityEditor/UnityEditor/AvatarSubEditor.cs b/UnityEditor/UnityEditor/AvatarSubEditor.cs index 359b0952..30f272b1 100644 --- a/UnityEditor/UnityEditor/AvatarSubEditor.cs +++ b/UnityEditor/UnityEditor/AvatarSubEditor.cs @@ -67,6 +67,9 @@ public virtual void Enable(AvatarEditor inspector) { this.m_Inspector = inspector; } + public virtual void Disable() + { + } public virtual void OnDestroy() { if (this.HasModified()) diff --git a/UnityEditor/UnityEditor/BaseProjectWindow.cs b/UnityEditor/UnityEditor/BaseProjectWindow.cs deleted file mode 100644 index 817fc6c3..00000000 --- a/UnityEditor/UnityEditor/BaseProjectWindow.cs +++ /dev/null @@ -1,1997 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using UnityEditor.ProjectWindowCallback; -using UnityEditorInternal; -using UnityEditorInternal.VersionControl; -using UnityEngine; -namespace UnityEditor -{ - internal class BaseProjectWindow : SearchableEditorWindow - { - private class DropData - { - public int[] expandedArrayBeforeDrag; - public int lastControlID; - public int dropOnControlID; - public int dropPreviousControlID; - public double expandItemBeginTimer; - } - internal class Styles - { - public GUIStyle foldout = "IN Foldout"; - public GUIStyle insertion = "PR Insertion"; - public GUIStyle label = "PR Label"; - public GUIStyle hiLabel = "HI Label"; - public GUIStyle ping = "PR Ping"; - } - private enum NameEditMode - { - None, - Found, - Renaming, - PreImportNaming - } - private const double kDropExpandTimeout = 0.7; - private const float kFoldoutSize = 14f; - private const float kIndent = 16f; - private const float kBaseIndent = 17f; - private static float m_RowHeight = 16f; - private static float m_DropNextToAreaHeight = 6f; - [SerializeField] - private int[] m_ExpandedArray = new int[0]; - private bool m_ProjectViewInternalSelectionChange; - public Vector2 m_ScrollPosition; - public Vector2 m_ScrollPositionFiltered; - [NonSerialized] - private Rect m_ScreenRect; - private PingData m_Ping = new PingData(); - private float m_FocusTime; - private List m_CurrentDragSelectionIDs = new List(); - private BaseProjectWindow.DropData m_DropData; - private bool m_StillWantsNameEditing; - private static Color[] s_HierarchyColors = new Color[] - { - Color.black, - new Color(0f, 0.15f, 0.51f, 1f), - new Color(0.25f, 0.05f, 0.05f, 1f), - Color.black, - Color.white, - new Color(0.67f, 0.76f, 1f), - new Color(1f, 0.71f, 0.71f, 1f), - Color.white - }; - private static Color[] s_DarkColors = new Color[] - { - new Color(0.705f, 0.705f, 0.705f, 1f), - new Color(0.3f, 0.5f, 0.85f, 1f), - new Color(0.7f, 0.4f, 0.4f, 1f), - new Color(0.705f, 0.705f, 0.705f, 1f), - Color.white, - new Color(0.67f, 0.76f, 1f), - new Color(1f, 0.71f, 0.71f, 1f), - Color.white - }; - private Rect m_NameEditRect = new Rect(0f, 0f, 1f, 1f); - private string m_NameEditString = string.Empty; - private int m_EditNameInstanceID; - private BaseProjectWindow.NameEditMode m_RealEditNameMode; - private EndNameEditAction m_EndNameEditAction; - private string m_NewAssetFolder; - private string m_NewAssetName; - private Texture2D m_NewAssetIcon; - private string m_NewAssetExtension; - private int m_NewAssetIndent; - private int m_NewAssetSortInstanceID; - private string m_NewAssetResourceFile; - private bool m_DidSelectSearchResult; - private bool m_NeedsRelayout; - private int m_FrameAfterRelayout; - private FilteredHierarchy m_FilteredHierarchy; - private static BaseProjectWindow.Styles ms_Styles; - private float IconWidth - { - get - { - return (float)((this.m_HierarchyType != HierarchyType.Assets) ? -3 : 14); - } - } - private BaseProjectWindow.NameEditMode m_EditNameMode - { - get - { - return this.m_RealEditNameMode; - } - set - { - if (value == this.m_RealEditNameMode) - { - return; - } - this.m_RealEditNameMode = value; - } - } - private GUIStyle labelStyle - { - get - { - return (this.m_HierarchyType != HierarchyType.Assets) ? BaseProjectWindow.ms_Styles.hiLabel : BaseProjectWindow.ms_Styles.label; - } - } - public IHierarchyProperty GetNewHierarchyProperty() - { - if (this.m_FilteredHierarchy == null) - { - this.m_FilteredHierarchy = new FilteredHierarchy(this.m_HierarchyType); - this.m_FilteredHierarchy.searchFilter = SearchableEditorWindow.CreateFilter(this.m_SearchFilter, this.m_SearchMode); - } - return FilteredHierarchyProperty.CreateHierarchyPropertyForFilter(this.m_FilteredHierarchy); - } - private void SetExpanded(int instanceID, bool expand) - { - Hashtable hashtable = new Hashtable(); - for (int i = 0; i < this.m_ExpandedArray.Length; i++) - { - hashtable.Add(this.m_ExpandedArray[i], null); - } - if (expand != hashtable.Contains(instanceID)) - { - if (expand) - { - hashtable.Add(instanceID, null); - } - else - { - hashtable.Remove(instanceID); - } - this.m_ExpandedArray = new int[hashtable.Count]; - int num = 0; - foreach (int num2 in hashtable.Keys) - { - this.m_ExpandedArray[num] = num2; - num++; - } - } - if (this.m_HierarchyType == HierarchyType.Assets) - { - InternalEditorUtility.expandedProjectWindowItems = this.m_ExpandedArray; - } - } - public void SetExpandedRecurse(int instanceID, bool expand) - { - IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - if (hierarchyProperty.Find(instanceID, this.m_ExpandedArray)) - { - this.SetExpanded(instanceID, expand); - int depth = hierarchyProperty.depth; - while (hierarchyProperty.Next(null) && hierarchyProperty.depth > depth) - { - this.SetExpanded(hierarchyProperty.instanceID, expand); - } - } - } - private void OnFocus() - { - this.m_FocusTime = Time.realtimeSinceStartup; - } - private void OnLostFocus() - { - this.m_StillWantsNameEditing = false; - this.EndNameEditing(); - } - public override void OnEnable() - { - base.OnEnable(); - EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); - } - public override void OnDisable() - { - base.OnDisable(); - EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); - } - private IHierarchyProperty GetFirstSelected() - { - int num = 1000000000; - IHierarchyProperty result = null; - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - int instanceID = instanceIDs[i]; - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray) && newHierarchyProperty.row < num) - { - num = newHierarchyProperty.row; - result = newHierarchyProperty; - } - } - return result; - } - private void OnProjectChange() - { - if (this.m_HierarchyType == HierarchyType.Assets) - { - this.CancelNameEditing(); - if (this.m_FilteredHierarchy != null) - { - this.m_FilteredHierarchy.ResultsChanged(); - } - base.Repaint(); - } - } - private void OnSelectionChange() - { - if (Selection.activeInstanceID != this.m_EditNameInstanceID) - { - this.EndNameEditing(); - } - this.m_StillWantsNameEditing = false; - this.RevealObjects(Selection.instanceIDs); - if (this.m_ProjectViewInternalSelectionChange) - { - this.m_ProjectViewInternalSelectionChange = false; - } - else - { - if (this.m_HierarchyType == HierarchyType.GameObjects) - { - this.FrameObject(Selection.activeInstanceID); - } - } - base.Repaint(); - } - private void OnHierarchyChange() - { - if (this.m_HierarchyType == HierarchyType.GameObjects) - { - this.EndNameEditing(); - if (this.m_FilteredHierarchy != null) - { - this.m_FilteredHierarchy.ResultsChanged(); - } - base.Repaint(); - } - } - private IHierarchyProperty GetLastSelected() - { - int num = -1; - IHierarchyProperty result = null; - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - int instanceID = instanceIDs[i]; - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray) && newHierarchyProperty.row > num) - { - num = newHierarchyProperty.row; - result = newHierarchyProperty; - } - } - return result; - } - private IHierarchyProperty GetActiveSelected() - { - return this.GetFirstSelected(); - } - private IHierarchyProperty GetLast() - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - int num = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); - if (num == 0) - { - return null; - } - newHierarchyProperty.Reset(); - if (newHierarchyProperty.Skip(num, this.m_ExpandedArray)) - { - return newHierarchyProperty; - } - return null; - } - private IHierarchyProperty GetFirst() - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Next(this.m_ExpandedArray)) - { - return newHierarchyProperty; - } - return null; - } - private void OpenAssetSelection() - { - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - int instanceID = instanceIDs[i]; - if (AssetDatabase.Contains(instanceID)) - { - AssetDatabase.OpenAsset(instanceID); - } - } - } - internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) - { - int num = 0; - if (this.m_DidSelectSearchResult && this.GetFirstSelected() != null) - { - num = this.GetFirstSelected().instanceID; - } - base.SetSearchFilter(searchFilter, searchMode, setAll); - if (this.m_FilteredHierarchy == null) - { - this.GetNewHierarchyProperty(); - } - this.m_FilteredHierarchy.searchFilter = SearchableEditorWindow.CreateFilter(searchFilter, searchMode); - if (this.m_DidSelectSearchResult) - { - if (searchFilter == string.Empty) - { - this.m_DidSelectSearchResult = false; - this.m_NeedsRelayout = true; - } - if (num != 0) - { - this.FrameObject(num, false); - } - } - } - internal override void ClickedSearchField() - { - this.EndNameEditing(); - } - private void ProjectWindowTitle() - { - GUILayout.BeginHorizontal("Toolbar", new GUILayoutOption[0]); - if (this.m_HierarchyType == HierarchyType.Assets) - { - this.CreateAssetPopup(); - GUILayout.Space(6f); - } - else - { - this.CreateGameObjectPopup(); - GUILayout.Space(6f); - } - if (this.m_FilteredHierarchy == null) - { - this.GetNewHierarchyProperty(); - } - int controlID = GUIUtility.GetControlID(FocusType.Keyboard); - if (Event.current.GetTypeForControl(controlID) == EventType.KeyDown) - { - KeyCode keyCode = Event.current.keyCode; - switch (keyCode) - { - case KeyCode.KeypadEnter: - case KeyCode.UpArrow: - case KeyCode.DownArrow: - goto IL_C2; - case KeyCode.KeypadEquals: - IL_9F: - if (keyCode != KeyCode.Return) - { - goto IL_C8; - } - goto IL_C2; - case KeyCode.RightArrow: - case KeyCode.LeftArrow: - if (!base.hasSearchFilter) - { - EditorGUILayout.EndHorizontal(); - return; - } - goto IL_C8; - } - goto IL_9F; - IL_C2: - EditorGUILayout.EndHorizontal(); - return; - } - IL_C8: - GUILayout.FlexibleSpace(); - base.SearchFieldGUI(); - GUILayout.EndHorizontal(); - } - private void SearchResultPathGUI() - { - if (!base.hasSearchFilter) - { - return; - } - EditorGUILayout.BeginVertical(EditorStyles.inspectorBig, new GUILayoutOption[0]); - GUILayout.Label("Path:", new GUILayoutOption[0]); - IHierarchyProperty activeSelected = this.GetActiveSelected(); - if (activeSelected != null) - { - IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - hierarchyProperty.Find(activeSelected.instanceID, null); - do - { - EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.Label(hierarchyProperty.icon, new GUILayoutOption[0]); - GUILayout.Label(hierarchyProperty.name, new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - EditorGUILayout.EndHorizontal(); - } - while (hierarchyProperty.Parent()); - } - EditorGUILayout.EndVertical(); - GUILayout.Space(0f); - } - private void OnGUI() - { - if (BaseProjectWindow.ms_Styles == null) - { - BaseProjectWindow.ms_Styles = new BaseProjectWindow.Styles(); - } - this.ProjectWindowTitle(); - Rect rect = GUILayoutUtility.GetRect(0f, (float)Screen.width, 0f, (float)Screen.height); - if (this.m_HierarchyType == HierarchyType.Assets && AssetDatabase.isLocked) - { - Debug.LogError("Repainting while performing asset operations!"); - GUILayout.Label("Performing Asset operations", new GUILayoutOption[0]); - return; - } - this.m_ScreenRect = rect; - EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); - this.HierarchyView(); - this.SearchResultPathGUI(); - EditorGUIUtility.SetIconSize(Vector2.zero); - if (Event.current.type == EventType.Repaint && this.m_NeedsRelayout) - { - this.m_NeedsRelayout = false; - if (this.m_FrameAfterRelayout != 0) - { - this.FrameObject(this.m_FrameAfterRelayout); - this.m_FrameAfterRelayout = 0; - } - } - } - private void EndNameEditing() - { - BaseProjectWindow.NameEditMode editNameMode = this.m_EditNameMode; - if (editNameMode == BaseProjectWindow.NameEditMode.Renaming) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - ObjectNames.SetNameSmartWithInstanceID(this.m_EditNameInstanceID, this.m_NameEditString); - return; - } - if (editNameMode != BaseProjectWindow.NameEditMode.PreImportNaming) - { - return; - } - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - if (this.m_NameEditString == string.Empty) - { - this.m_NameEditString = this.m_NewAssetName; - } - ProjectWindowUtil.EndNameEditAction(this.m_EndNameEditAction, this.m_EditNameInstanceID, this.m_NewAssetFolder + "/" + this.m_NameEditString + this.m_NewAssetExtension, this.m_NewAssetResourceFile); - this.m_EndNameEditAction = null; - } - private void CancelNameEditing() - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - this.m_EndNameEditAction = null; - } - private void BeginNameEditing(int instanceID) - { - if (this.NamingAsset()) - { - this.EndNameEditing(); - } - if (base.hasSearchFilter) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - return; - } - IHierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - hierarchyProperty.Find(instanceID, null); - if (hierarchyProperty.isValid) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.Renaming; - this.m_EditNameInstanceID = instanceID; - EditorGUI.s_RecycledEditor.content.text = hierarchyProperty.name; - EditorGUI.s_RecycledEditor.SelectAll(); - } - else - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - } - } - private void OnPlayModeStateChanged() - { - this.EndNameEditing(); - } - internal void BeginPreimportedNameEditing(int instanceID, EndNameEditAction endAction, string pathName, Texture2D icon, string resourceFile) - { - if (this.NamingAsset()) - { - this.EndNameEditing(); - } - this.m_EndNameEditAction = endAction; - if (!pathName.StartsWith("assets/", StringComparison.CurrentCultureIgnoreCase)) - { - pathName = AssetDatabase.GetUniquePathNameAtSelectedPath(pathName); - } - else - { - pathName = AssetDatabase.GenerateUniqueAssetPath(pathName); - } - this.m_NewAssetFolder = Path.GetDirectoryName(pathName); - this.m_NewAssetIcon = icon; - this.m_NewAssetName = Path.GetFileNameWithoutExtension(pathName); - this.m_NewAssetExtension = Path.GetExtension(pathName); - this.m_NewAssetIndent = 0; - this.m_NewAssetSortInstanceID = 0; - this.m_NewAssetResourceFile = resourceFile; - Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); - if (base.hasSearchFilter) - { - this.m_SearchFilter = string.Empty; - this.m_SearchMode = SearchableEditorWindow.SearchMode.All; - } - int instanceID2 = AssetDatabase.LoadAssetAtPath(this.m_NewAssetFolder, typeof(UnityEngine.Object)).GetInstanceID(); - this.RevealObject(instanceID2); - this.SetExpanded(instanceID2, true); - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - newHierarchyProperty.Reset(); - float num = 0f; - if (!this.m_NewAssetFolder.Equals("assets", StringComparison.CurrentCultureIgnoreCase)) - { - while (newHierarchyProperty.Next(this.m_ExpandedArray)) - { - string assetPath = AssetDatabase.GetAssetPath(newHierarchyProperty.instanceID); - num += BaseProjectWindow.m_RowHeight; - if (string.Equals(assetPath, this.m_NewAssetFolder, StringComparison.CurrentCultureIgnoreCase)) - { - num = this.FindPositionInsideDir(newHierarchyProperty, num); - break; - } - } - } - else - { - num = this.FindPositionInsideDir(newHierarchyProperty, num); - } - float left = 17f + 16f * (float)this.m_NewAssetIndent + this.IconWidth; - this.m_NameEditRect = new Rect(left, num, 100f, BaseProjectWindow.m_RowHeight); - float num2 = num; - float min = num2 - base.position.height + 20f + BaseProjectWindow.m_RowHeight; - this.m_ScrollPosition.y = Mathf.Clamp(this.m_ScrollPosition.y, min, num2); - this.m_EditNameMode = BaseProjectWindow.NameEditMode.PreImportNaming; - this.m_EditNameInstanceID = instanceID; - EditorGUI.s_RecycledEditor.content.text = (this.m_NameEditString = this.m_NewAssetName); - EditorGUI.s_RecycledEditor.SelectAll(); - } - private float FindPositionInsideDir(IHierarchyProperty property, float yPos) - { - this.m_NewAssetIndent = property.depth + 1; - string text = this.m_NewAssetFolder + "/"; - while (property.Next(this.m_ExpandedArray)) - { - string assetPath = AssetDatabase.GetAssetPath(property.instanceID); - string text2 = assetPath + "/"; - if (text2.Length < text.Length || !text2.Substring(0, text.Length).Equals(text, StringComparison.CurrentCultureIgnoreCase)) - { - this.m_NewAssetSortInstanceID = property.instanceID; - break; - } - if (this.m_NewAssetFolder.Equals(Path.GetDirectoryName(assetPath), StringComparison.CurrentCultureIgnoreCase) && EditorUtility.NaturalCompare(Path.GetFileNameWithoutExtension(assetPath), this.m_NewAssetName) > 0) - { - this.m_NewAssetIndent = property.depth; - this.m_NewAssetSortInstanceID = property.instanceID; - break; - } - yPos += BaseProjectWindow.m_RowHeight; - } - return yPos; - } - private bool NamingAsset() - { - return this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming || this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming; - } - private void EditName() - { - if (!this.NamingAsset()) - { - return; - } - Event current = Event.current; - if (current.type == EventType.KeyDown) - { - if (current.keyCode == KeyCode.Escape) - { - current.Use(); - this.CancelNameEditing(); - } - if (current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) - { - current.Use(); - this.EndNameEditing(); - GUIUtility.ExitGUI(); - } - } - GUI.changed = false; - GUIUtility.GetControlID(67897456, FocusType.Passive); - GUI.SetNextControlName("ProjectWindowRenameField"); - EditorGUI.FocusTextInControl("ProjectWindowRenameField"); - GUIStyle textField = EditorStyles.textField; - EditorStyles.s_Current.m_TextField = "PR TextField"; - this.m_NameEditRect.xMax = GUIClip.visibleRect.width; - Rect nameEditRect = this.m_NameEditRect; - this.m_NameEditString = EditorGUI.TextField(nameEditRect, this.m_NameEditString); - EditorStyles.s_Current.m_TextField = textField; - if (current.type == EventType.ScrollWheel) - { - current.Use(); - } - } - private void HierarchyView() - { - if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.KeyDown) - { - this.m_StillWantsNameEditing = false; - } - bool hasFocus = this.m_Parent.hasFocus; - Hashtable hashtable = new Hashtable(); - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - int num = instanceIDs[i]; - hashtable.Add(num, null); - } - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - int num2 = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); - newHierarchyProperty.Reset(); - Rect viewRect = new Rect(0f, 0f, 1f, (float)num2 * BaseProjectWindow.m_RowHeight); - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming) - { - viewRect.height += BaseProjectWindow.m_RowHeight; - } - int num3; - if (base.hasSearchFilter) - { - this.m_ScrollPositionFiltered = GUI.BeginScrollView(this.m_ScreenRect, this.m_ScrollPositionFiltered, viewRect); - num3 = Mathf.RoundToInt(this.m_ScrollPositionFiltered.y) / Mathf.RoundToInt(BaseProjectWindow.m_RowHeight); - } - else - { - this.m_ScrollPosition = GUI.BeginScrollView(this.m_ScreenRect, this.m_ScrollPosition, viewRect); - num3 = Mathf.RoundToInt(this.m_ScrollPosition.y) / Mathf.RoundToInt(BaseProjectWindow.m_RowHeight); - } - this.EditName(); - if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) - { - this.ExecuteCommandGUI(); - if (Event.current.type == EventType.ValidateCommand) - { - GUI.EndScrollView(); - return; - } - } - this.KeyboardGUI(); - if (Event.current.type == EventType.Layout) - { - GUI.EndScrollView(); - return; - } - int num4 = this.ControlIDForProperty(null); - bool flag = false; - float num5 = (float)num3 * BaseProjectWindow.m_RowHeight; - float num6 = this.m_ScreenRect.height + num5 + 16f; - newHierarchyProperty.Skip(num3, this.m_ExpandedArray); - bool flag2 = false; - Rect position = new Rect(0f, 0f, 0f, 0f); - Vector2 mousePosition = Event.current.mousePosition; - GUIContent gUIContent = new GUIContent(); - Event current = Event.current; - int activeInstanceID = Selection.activeInstanceID; - if (!this.NamingAsset()) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.None; - } - GUIStyle labelStyle = this.labelStyle; - Color[] array = (!EditorGUIUtility.isProSkin) ? BaseProjectWindow.s_HierarchyColors : BaseProjectWindow.s_DarkColors; - while (newHierarchyProperty.Next(this.m_ExpandedArray) && num5 <= num6) - { - Rect rect = new Rect(0f, num5, GUIClip.visibleRect.width, BaseProjectWindow.m_RowHeight); - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming && !flag && newHierarchyProperty.instanceID == this.m_NewAssetSortInstanceID) - { - flag = true; - num5 += BaseProjectWindow.m_RowHeight; - rect = new Rect(0f, num5, GUIClip.visibleRect.width, BaseProjectWindow.m_RowHeight); - this.DrawPreImportedIcon(num5); - } - int instanceID = newHierarchyProperty.instanceID; - int num7 = this.ControlIDForProperty(newHierarchyProperty); - float num8 = 17f + 16f * (float)newHierarchyProperty.depth; - if ((current.type == EventType.MouseUp || current.type == EventType.KeyDown) && activeInstanceID == instanceID && Selection.instanceIDs.Length == 1) - { - this.m_NameEditString = newHierarchyProperty.name; - this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); - this.m_EditNameInstanceID = instanceID; - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.None && newHierarchyProperty.isMainRepresentation) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.Found; - } - } - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming && this.m_EditNameInstanceID == instanceID) - { - this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); - } - if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) - { - this.m_NameEditRect = new Rect(rect.x + num8 + this.IconWidth, rect.y, rect.width - num8, rect.height); - this.m_EditNameInstanceID = instanceID; - this.m_NameEditString = newHierarchyProperty.name; - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.None && newHierarchyProperty.isMainRepresentation) - { - this.m_EditNameMode = BaseProjectWindow.NameEditMode.Found; - } - } - if (Event.current.type == EventType.Repaint) - { - if (this.m_HierarchyType == HierarchyType.GameObjects) - { - int colorCode = newHierarchyProperty.colorCode; - Color textColor = array[colorCode & 3]; - Color textColor2 = array[(colorCode & 3) + 4]; - if (colorCode >= 4) - { - textColor.a = (textColor2.a = 0.6f); - } - else - { - textColor.a = (textColor2.a = 1f); - } - labelStyle.normal.textColor = textColor; - labelStyle.focused.textColor = textColor; - labelStyle.hover.textColor = textColor; - labelStyle.active.textColor = textColor; - labelStyle.onNormal.textColor = textColor2; - labelStyle.onHover.textColor = textColor2; - labelStyle.onActive.textColor = textColor2; - labelStyle.onFocused.textColor = textColor2; - } - bool flag3 = this.m_DropData != null && this.m_DropData.dropPreviousControlID == num7; - bool flag4 = this.m_DropData != null && this.m_DropData.dropOnControlID == num7; - gUIContent.text = newHierarchyProperty.name; - gUIContent.image = newHierarchyProperty.icon; - labelStyle.padding.left = (int)num8; - bool flag5 = this.m_CurrentDragSelectionIDs.Contains(instanceID); - bool on = (this.m_CurrentDragSelectionIDs.Count == 0 && hashtable.Contains(instanceID)) || flag5 || (flag5 && (current.control || current.shift) && hashtable.Contains(instanceID)) || (flag5 && hashtable.Contains(instanceID) && hashtable.Contains(this.m_CurrentDragSelectionIDs)); - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Renaming && instanceID == this.m_EditNameInstanceID) - { - gUIContent.text = string.Empty; - on = false; - } - labelStyle.Draw(rect, gUIContent, flag4, flag4, on, hasFocus); - if (flag3) - { - flag2 = true; - position = new Rect(rect.x + num8, rect.y - BaseProjectWindow.m_RowHeight, rect.width - num8, rect.height); - } - } - Rect rect2 = rect; - rect2.x += num8; - rect2.width -= num8; - if (this.m_HierarchyType == HierarchyType.Assets) - { - ProjectHooks.OnProjectWindowItem(newHierarchyProperty.guid, rect2); - if (EditorApplication.projectWindowItemOnGUI != null) - { - EditorApplication.projectWindowItemOnGUI(newHierarchyProperty.guid, rect2); - } - } - if (this.m_HierarchyType == HierarchyType.GameObjects && EditorApplication.hierarchyWindowItemOnGUI != null) - { - EditorApplication.hierarchyWindowItemOnGUI(newHierarchyProperty.instanceID, rect2); - } - if (newHierarchyProperty.hasChildren && !base.hasSearchFilter) - { - bool flag6 = newHierarchyProperty.IsExpanded(this.m_ExpandedArray); - GUI.changed = false; - Rect position2 = new Rect(17f + 16f * (float)newHierarchyProperty.depth - 14f, num5, 14f, BaseProjectWindow.m_RowHeight); - flag6 = GUI.Toggle(position2, flag6, GUIContent.none, BaseProjectWindow.ms_Styles.foldout); - if (GUI.changed) - { - this.EndNameEditing(); - if (Event.current.alt) - { - this.SetExpandedRecurse(instanceID, flag6); - } - else - { - this.SetExpanded(instanceID, flag6); - } - } - } - if (current.type == EventType.MouseDown && Event.current.button == 0 && rect.Contains(Event.current.mousePosition)) - { - if (Event.current.clickCount == 2) - { - AssetDatabase.OpenAsset(instanceID); - if (this.m_HierarchyType != HierarchyType.Assets && SceneView.lastActiveSceneView != null) - { - SceneView.lastActiveSceneView.FrameSelected(); - } - GUIUtility.ExitGUI(); - } - else - { - this.EndNameEditing(); - this.m_CurrentDragSelectionIDs = this.GetSelection(newHierarchyProperty, true); - GUIUtility.hotControl = num7; - GUIUtility.keyboardControl = 0; - DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), num7); - dragAndDropDelay.mouseDownPosition = Event.current.mousePosition; - } - current.Use(); - } - else - { - if (current.type == EventType.MouseDrag && GUIUtility.hotControl == num7) - { - DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), num7); - if (dragAndDropDelay2.CanStartDrag()) - { - this.StartDrag(newHierarchyProperty); - GUIUtility.hotControl = 0; - } - current.Use(); - } - else - { - if (current.type == EventType.MouseUp && GUIUtility.hotControl == num7) - { - if (rect.Contains(current.mousePosition)) - { - if (newHierarchyProperty.isMainRepresentation && Selection.activeInstanceID == newHierarchyProperty.instanceID && Time.realtimeSinceStartup - this.m_FocusTime > 0.5f && !EditorGUIUtility.HasHolddownKeyModifiers(current)) - { - this.m_StillWantsNameEditing = true; - EditorApplication.CallDelayed(new EditorApplication.CallbackFunction(this.BeginMouseEditing), 0.5f); - } - else - { - this.SelectionClick(newHierarchyProperty); - } - GUIUtility.hotControl = 0; - } - this.m_CurrentDragSelectionIDs.Clear(); - current.Use(); - } - else - { - if (current.type == EventType.ContextClick && rect.Contains(current.mousePosition)) - { - current.Use(); - if (this.m_HierarchyType == HierarchyType.GameObjects) - { - this.SelectionClickContextMenu(newHierarchyProperty); - GenericMenu genericMenu = new GenericMenu(); - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupCopy"), false, new GenericMenu.MenuFunction(this.CopyGO)); - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupPaste"), false, new GenericMenu.MenuFunction(this.PasteGO)); - genericMenu.AddSeparator(string.Empty); - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Found && !base.hasSearchFilter) - { - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupRename"), false, new GenericMenu.MenuFunction2(this.RenameGO), newHierarchyProperty.pptrValue); - } - else - { - genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupRename")); - } - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDuplicate"), false, new GenericMenu.MenuFunction(this.DuplicateGO)); - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupDelete"), false, new GenericMenu.MenuFunction(this.DeleteGO)); - genericMenu.AddSeparator(string.Empty); - UnityEngine.Object prefab = PrefabUtility.GetPrefabParent(newHierarchyProperty.pptrValue); - if (prefab != null) - { - genericMenu.AddItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab"), false, delegate - { - Selection.activeObject = prefab; - EditorGUIUtility.PingObject(prefab.GetInstanceID()); - }); - } - else - { - genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("HierarchyPopupSelectPrefab")); - } - genericMenu.ShowAsContext(); - } - } - else - { - if (current.type == EventType.DragUpdated || current.type == EventType.DragPerform) - { - Rect rect3 = rect; - rect3.yMin -= BaseProjectWindow.m_DropNextToAreaHeight * 2f; - if (rect3.Contains(mousePosition)) - { - if (mousePosition.y - rect.y < BaseProjectWindow.m_DropNextToAreaHeight * 0.5f) - { - this.DragElement(newHierarchyProperty, false); - } - else - { - this.DragElement(newHierarchyProperty, true); - } - GUIUtility.hotControl = 0; - } - } - } - } - } - } - num5 += BaseProjectWindow.m_RowHeight; - } - if (flag2) - { - GUIStyle insertion = BaseProjectWindow.ms_Styles.insertion; - if (current.type == EventType.Repaint) - { - insertion.Draw(position, false, false, false, false); - } - } - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.PreImportNaming && this.m_NewAssetSortInstanceID == 0) - { - this.DrawPreImportedIcon(num5 + 16f); - } - this.HandlePing(); - GUI.EndScrollView(); - EventType type = current.type; - switch (type) - { - case EventType.DragUpdated: - if (this.m_SearchFilter == string.Empty) - { - this.DragElement(null, true); - } - else - { - if (this.m_DropData == null) - { - this.m_DropData = new BaseProjectWindow.DropData(); - } - this.m_DropData.dropOnControlID = 0; - this.m_DropData.dropPreviousControlID = 0; - } - return; - case EventType.DragPerform: - this.m_CurrentDragSelectionIDs.Clear(); - this.DragElement(null, true); - return; - case EventType.Ignore: - case EventType.Used: - case EventType.ValidateCommand: - case EventType.ExecuteCommand: - IL_CB2: - switch (type) - { - case EventType.MouseDown: - if (current.button == 0 && this.m_ScreenRect.Contains(current.mousePosition)) - { - GUIUtility.hotControl = num4; - Selection.activeObject = null; - this.EndNameEditing(); - current.Use(); - } - return; - case EventType.MouseUp: - if (GUIUtility.hotControl == num4) - { - GUIUtility.hotControl = 0; - current.Use(); - } - return; - case EventType.MouseMove: - case EventType.MouseDrag: - return; - case EventType.KeyDown: - if (this.m_EditNameMode == BaseProjectWindow.NameEditMode.Found && (((current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter) && Application.platform == RuntimePlatform.OSXEditor) || (current.keyCode == KeyCode.F2 && Application.platform == RuntimePlatform.WindowsEditor))) - { - this.BeginNameEditing(Selection.activeInstanceID); - current.Use(); - } - return; - default: - return; - } - break; - case EventType.DragExited: - this.m_CurrentDragSelectionIDs.Clear(); - this.DragCleanup(true); - return; - case EventType.ContextClick: - if (this.m_HierarchyType == HierarchyType.Assets && this.m_ScreenRect.Contains(current.mousePosition)) - { - EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), "Assets/", null); - current.Use(); - } - return; - } - goto IL_CB2; - } - private void HandlePing() - { - this.m_Ping.HandlePing(); - if (this.m_Ping.isPinging) - { - base.Repaint(); - } - } - private void DrawPreImportedIcon(float offset) - { - if (Event.current.type == EventType.Repaint && this.m_NewAssetIcon) - { - BaseProjectWindow.ms_Styles.label.padding.left = 0; - BaseProjectWindow.ms_Styles.label.Draw(new Rect((float)(this.m_NewAssetIndent * 16) + 17f, offset - 16f, 16f, 16f), EditorGUIUtility.TempContent(this.m_NewAssetIcon), 0); - } - } - private void CopyGO() - { - Unsupported.CopyGameObjectsToPasteboard(); - } - private void PasteGO() - { - Unsupported.PasteGameObjectsFromPasteboard(); - } - private void DuplicateGO() - { - Unsupported.DuplicateGameObjectsUsingPasteboard(); - } - private void RenameGO(object obj) - { - GameObject activeObject = (GameObject)obj; - Selection.activeObject = activeObject; - this.BeginNameEditing(Selection.activeInstanceID); - base.Repaint(); - } - private void DeleteGO() - { - Unsupported.DeleteGameObjectSelection(); - } - private void BeginMouseEditing() - { - if (this.m_StillWantsNameEditing) - { - this.BeginNameEditing(Selection.activeInstanceID); - } - base.Repaint(); - } - private void StartDrag(IHierarchyProperty property) - { - DragAndDrop.PrepareStartDrag(); - DragAndDrop.objectReferences = this.GetDragAndDropObjects(property.pptrValue); - DragAndDrop.paths = this.GetDragAndDropPaths(property.instanceID); - if (DragAndDrop.objectReferences.Length > 1) - { - DragAndDrop.StartDrag(""); - } - else - { - DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(property.pptrValue)); - } - } - private void DragCleanup(bool revertExpanded) - { - if (this.m_DropData != null) - { - if (this.m_DropData.expandedArrayBeforeDrag != null && revertExpanded) - { - this.m_ExpandedArray = this.m_DropData.expandedArrayBeforeDrag; - } - this.m_DropData = null; - base.Repaint(); - } - } - private void DragElement(IHierarchyProperty property, bool dropOnTopOfElement) - { - if (Event.current.type == EventType.DragPerform) - { - IHierarchyProperty hierarchyProperty = property; - DragAndDropVisualMode dragAndDropVisualMode = DragAndDropVisualMode.None; - if (dropOnTopOfElement) - { - dragAndDropVisualMode = this.DoDrag(hierarchyProperty, true); - } - if (dragAndDropVisualMode == DragAndDropVisualMode.None && property != null) - { - hierarchyProperty = this.GetParentProperty(hierarchyProperty); - dragAndDropVisualMode = this.DoDrag(hierarchyProperty, true); - } - if (dragAndDropVisualMode != DragAndDropVisualMode.None) - { - DragAndDrop.AcceptDrag(); - this.DragCleanup(false); - ArrayList arrayList = new ArrayList(); - UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; - for (int i = 0; i < objectReferences.Length; i++) - { - UnityEngine.Object @object = objectReferences[i]; - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty != null && @object != null && newHierarchyProperty.Find(@object.GetInstanceID(), null)) - { - IHierarchyProperty parentProperty = this.GetParentProperty(newHierarchyProperty); - if (parentProperty != null && (hierarchyProperty == null || parentProperty.pptrValue == hierarchyProperty.pptrValue)) - { - arrayList.Add(@object); - } - } - } - if (arrayList.Count > 0) - { - Selection.objects = (UnityEngine.Object[])arrayList.ToArray(typeof(UnityEngine.Object)); - this.RevealObjects(Selection.instanceIDs); - this.FrameObject(Selection.activeInstanceID); - } - GUIUtility.ExitGUI(); - } - else - { - this.DragCleanup(true); - } - } - else - { - if (this.m_DropData == null) - { - this.m_DropData = new BaseProjectWindow.DropData(); - } - this.m_DropData.dropOnControlID = 0; - this.m_DropData.dropPreviousControlID = 0; - int num = this.ControlIDForProperty(property); - if (num != this.m_DropData.lastControlID) - { - this.m_DropData.lastControlID = this.ControlIDForProperty(property); - this.m_DropData.expandItemBeginTimer = (double)Time.realtimeSinceStartup; - } - bool flag = (double)Time.realtimeSinceStartup - this.m_DropData.expandItemBeginTimer > 0.7; - if (property != null && property.hasChildren && flag && !property.IsExpanded(this.m_ExpandedArray)) - { - if (this.m_DropData.expandedArrayBeforeDrag == null) - { - this.m_DropData.expandedArrayBeforeDrag = this.m_ExpandedArray; - } - this.SetExpanded(property.instanceID, true); - } - DragAndDropVisualMode dragAndDropVisualMode2 = DragAndDropVisualMode.None; - if (dropOnTopOfElement) - { - dragAndDropVisualMode2 = this.DoDrag(property, false); - } - if (dragAndDropVisualMode2 != DragAndDropVisualMode.None) - { - this.m_DropData.dropOnControlID = num; - DragAndDrop.visualMode = dragAndDropVisualMode2; - } - else - { - if (property != null && this.m_SearchFilter == string.Empty) - { - IHierarchyProperty parentProperty2 = this.GetParentProperty(property); - dragAndDropVisualMode2 = this.DoDrag(parentProperty2, false); - if (dragAndDropVisualMode2 != DragAndDropVisualMode.None) - { - this.m_DropData.dropPreviousControlID = num; - this.m_DropData.dropOnControlID = this.ControlIDForProperty(parentProperty2); - DragAndDrop.visualMode = dragAndDropVisualMode2; - } - } - } - base.Repaint(); - } - Event.current.Use(); - } - private DragAndDropVisualMode DoDrag(IHierarchyProperty property, bool perform) - { - HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - if (property == null || !hierarchyProperty.Find(property.instanceID, null)) - { - hierarchyProperty = null; - } - if (this.HandleSpriteDragIntoHierarchy(property, perform)) - { - return DragAndDropVisualMode.Link; - } - if (this.m_HierarchyType == HierarchyType.Assets) - { - return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); - } - return InternalEditorUtility.HierarchyWindowDrag(hierarchyProperty, perform, InternalEditorUtility.HierarchyDropMode.kHierarchyDragNormal); - } - private bool HandleSpriteDragIntoHierarchy(IHierarchyProperty property, bool perform) - { - Sprite[] spritesFromDraggedObjects = SpriteUtility.GetSpritesFromDraggedObjects(); - if (spritesFromDraggedObjects.Length == 1) - { - return SpriteUtility.HandleSingleSpriteDragIntoHierarchy(property, spritesFromDraggedObjects[0], perform); - } - return spritesFromDraggedObjects.Length > 1 && SpriteUtility.HandleMultipleSpritesDragIntoHierarchy(property, spritesFromDraggedObjects, perform); - } - private IHierarchyProperty GetPreviousParentProperty(IHierarchyProperty property) - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Find(property.instanceID, this.m_ExpandedArray) && newHierarchyProperty.Previous(this.m_ExpandedArray)) - { - return this.GetParentProperty(newHierarchyProperty); - } - return null; - } - private IHierarchyProperty GetParentProperty(IHierarchyProperty property) - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Find(property.instanceID, this.m_ExpandedArray) && newHierarchyProperty.Parent()) - { - int instanceID = newHierarchyProperty.instanceID; - newHierarchyProperty.Reset(); - if (newHierarchyProperty.Find(instanceID, this.m_ExpandedArray)) - { - return newHierarchyProperty; - } - } - return null; - } - private int ControlIDForProperty(IHierarchyProperty property) - { - if (property != null) - { - return property.instanceID + 10000000; - } - return -1; - } - private string[] GetDragAndDropPaths(int dragged) - { - string assetPath = AssetDatabase.GetAssetPath(dragged); - if (this.m_HierarchyType != HierarchyType.Assets) - { - return new string[0]; - } - ArrayList arrayList = new ArrayList(); - arrayList.AddRange(BaseProjectWindow.GetMainSelectedPaths()); - if (arrayList.Contains(assetPath)) - { - return arrayList.ToArray(typeof(string)) as string[]; - } - return new string[] - { - assetPath - }; - } - private UnityEngine.Object[] GetDragAndDropObjects(UnityEngine.Object dragged) - { - ArrayList arrayList = new ArrayList(); - arrayList.AddRange(this.GetSelectedReferences()); - if (arrayList.Contains(dragged)) - { - return arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]; - } - return new UnityEngine.Object[] - { - dragged - }; - } - private UnityEngine.Object[] GetSelectedReferences() - { - ArrayList arrayList = new ArrayList(); - UnityEngine.Object[] objects = Selection.objects; - for (int i = 0; i < objects.Length; i++) - { - UnityEngine.Object @object = objects[i]; - if (AssetDatabase.Contains(@object) != (this.m_HierarchyType == HierarchyType.GameObjects)) - { - arrayList.Add(@object); - } - } - return arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]; - } - private static string[] GetMainSelectedPaths() - { - ArrayList arrayList = new ArrayList(); - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - int instanceID = instanceIDs[i]; - if (AssetDatabase.IsMainAsset(instanceID)) - { - string assetPath = AssetDatabase.GetAssetPath(instanceID); - arrayList.Add(assetPath); - } - } - return arrayList.ToArray(typeof(string)) as string[]; - } - private void ExecuteCommandGUIHierarchy() - { - bool flag = Event.current.type == EventType.ExecuteCommand; - if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") - { - if (flag) - { - Unsupported.DeleteGameObjectSelection(); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "Duplicate") - { - if (flag) - { - Unsupported.DuplicateGameObjectsUsingPasteboard(); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "Copy") - { - if (flag) - { - Unsupported.CopyGameObjectsToPasteboard(); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "Paste") - { - if (flag) - { - Unsupported.PasteGameObjectsFromPasteboard(); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "SelectAll") - { - if (flag) - { - this.SelectAll(); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - } - } - } - } - } - internal static void DuplicateSelectedAssets() - { - AssetDatabase.Refresh(); - UnityEngine.Object[] objects = Selection.objects; - bool flag = true; - UnityEngine.Object[] array = objects; - for (int i = 0; i < array.Length; i++) - { - UnityEngine.Object @object = array[i]; - AnimationClip animationClip = @object as AnimationClip; - if (animationClip == null || (animationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None || !AssetDatabase.Contains(animationClip)) - { - flag = false; - } - } - ArrayList arrayList = new ArrayList(); - bool flag2 = false; - if (flag) - { - UnityEngine.Object[] array2 = objects; - for (int j = 0; j < array2.Length; j++) - { - UnityEngine.Object object2 = array2[j]; - AnimationClip animationClip2 = object2 as AnimationClip; - if (animationClip2 != null && (animationClip2.hideFlags & HideFlags.NotEditable) != HideFlags.None) - { - string path = AssetDatabase.GetAssetPath(object2); - path = Path.Combine(Path.GetDirectoryName(path), animationClip2.name) + ".anim"; - string text = AssetDatabase.GenerateUniqueAssetPath(path); - AnimationClip animationClip3 = new AnimationClip(); - EditorUtility.CopySerialized(animationClip2, animationClip3); - AssetDatabase.CreateAsset(animationClip3, text); - arrayList.Add(text); - } - } - } - else - { - UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); - UnityEngine.Object[] array3 = filtered; - for (int k = 0; k < array3.Length; k++) - { - UnityEngine.Object assetObject = array3[k]; - string assetPath = AssetDatabase.GetAssetPath(assetObject); - string text2 = AssetDatabase.GenerateUniqueAssetPath(assetPath); - if (text2.Length != 0) - { - flag2 |= !AssetDatabase.CopyAsset(assetPath, text2); - } - else - { - flag2 |= true; - } - if (!flag2) - { - arrayList.Add(text2); - } - } - } - AssetDatabase.Refresh(); - UnityEngine.Object[] array4 = new UnityEngine.Object[arrayList.Count]; - for (int l = 0; l < arrayList.Count; l++) - { - array4[l] = AssetDatabase.LoadMainAssetAtPath(arrayList[l] as string); - } - Selection.objects = array4; - } - private void ExecuteCommandGUIProject() - { - bool flag = Event.current.type == EventType.ExecuteCommand; - if (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete") - { - Event.current.Use(); - if (flag) - { - bool askIfSure = Event.current.commandName == "SoftDelete"; - BaseProjectWindow.DeleteSelectedAssets(askIfSure); - } - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "Duplicate") - { - if (flag) - { - Event.current.Use(); - BaseProjectWindow.DuplicateSelectedAssets(); - GUIUtility.ExitGUI(); - } - else - { - UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); - if (filtered.Length != 0) - { - Event.current.Use(); - } - } - } - else - { - if (Event.current.commandName == "FocusProjectWindow") - { - if (Event.current.type == EventType.ExecuteCommand) - { - this.FrameObject(Selection.activeInstanceID); - Event.current.Use(); - base.Focus(); - GUIUtility.ExitGUI(); - } - else - { - Event.current.Use(); - } - } - else - { - if (Event.current.commandName == "SelectAll") - { - if (Event.current.type == EventType.ExecuteCommand) - { - this.SelectAll(); - } - Event.current.Use(); - } - } - } - } - } - internal static void DeleteSelectedAssets(bool askIfSure) - { - string[] mainSelectedPaths = BaseProjectWindow.GetMainSelectedPaths(); - if (mainSelectedPaths.Length == 0) - { - return; - } - if (askIfSure) - { - string text = "Delete selected asset"; - if (mainSelectedPaths.Length > 1) - { - text += "s"; - } - text += "?"; - if (!EditorUtility.DisplayDialog(text, "You cannot undo this action.", "Delete", "Cancel")) - { - return; - } - } - AssetDatabase.StartAssetEditing(); - string[] array = mainSelectedPaths; - for (int i = 0; i < array.Length; i++) - { - string path = array[i]; - AssetDatabase.MoveAssetToTrash(path); - } - AssetDatabase.StopAssetEditing(); - } - private void SelectAll() - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - List list = new List(); - while (newHierarchyProperty.Next(this.m_ExpandedArray)) - { - list.Add(newHierarchyProperty.instanceID); - } - Selection.instanceIDs = list.ToArray(); - } - internal void PingTargetObject(int targetInstanceID) - { - if (targetInstanceID == 0) - { - return; - } - if (BaseProjectWindow.ms_Styles == null) - { - BaseProjectWindow.ms_Styles = new BaseProjectWindow.Styles(); - } - if (this.FrameObject(targetInstanceID)) - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - int num = newHierarchyProperty.CountRemaining(this.m_ExpandedArray); - IHierarchyProperty newHierarchyProperty2 = this.GetNewHierarchyProperty(); - if (newHierarchyProperty2.Find(targetInstanceID, this.m_ExpandedArray)) - { - int row = newHierarchyProperty2.row; - float top = BaseProjectWindow.m_RowHeight * (float)row; - this.m_Ping.m_TimeStart = Time.realtimeSinceStartup; - this.m_Ping.m_PingStyle = BaseProjectWindow.ms_Styles.ping; - float num2 = ((float)num * BaseProjectWindow.m_RowHeight <= this.m_ScreenRect.height) ? 0f : -16f; - this.m_Ping.m_AvailableWidth = base.position.width + num2; - GUIContent pingContent = new GUIContent(newHierarchyProperty2.name, newHierarchyProperty2.icon); - Vector2 vector = BaseProjectWindow.ms_Styles.ping.CalcSize(pingContent); - vector.y += 3f; - this.m_Ping.m_ContentRect = new Rect(17f + 16f * (float)newHierarchyProperty2.depth, top, vector.x, vector.y); - this.m_Ping.m_ContentDraw = delegate(Rect r) - { - this.DrawPingContent(r, pingContent); - }; - base.Repaint(); - return; - } - } - targetInstanceID = InternalEditorUtility.GetGameObjectInstanceIDFromComponent(targetInstanceID); - if (targetInstanceID != 0) - { - this.PingTargetObject(targetInstanceID); - } - } - private void DrawPingContent(Rect rect, GUIContent content) - { - GUIStyle labelStyle = this.labelStyle; - labelStyle.padding.left = 0; - labelStyle.Draw(rect, content, false, false, false, false); - } - private void ExecuteCommandGUI() - { - if (this.m_HierarchyType == HierarchyType.Assets) - { - this.ExecuteCommandGUIProject(); - } - else - { - this.ExecuteCommandGUIHierarchy(); - } - if (Event.current.commandName == "FrameSelected") - { - if (Event.current.type == EventType.ExecuteCommand) - { - this.FrameObject(Selection.activeInstanceID); - } - Event.current.Use(); - GUIUtility.ExitGUI(); - } - else - { - if (Event.current.commandName == "Find") - { - if (Event.current.type == EventType.ExecuteCommand) - { - base.FocusSearchField(); - } - Event.current.Use(); - } - } - } - public void SelectPrevious() - { - IHierarchyProperty firstSelected = this.GetFirstSelected(); - if (firstSelected != null) - { - if (firstSelected.Previous(this.m_ExpandedArray)) - { - this.FrameObject(firstSelected.instanceID); - this.SelectionClick(firstSelected); - } - } - else - { - if (this.GetLast() != null) - { - Selection.activeInstanceID = this.GetLast().instanceID; - this.FrameObject(Selection.activeInstanceID); - } - } - } - public void SelectNext() - { - IHierarchyProperty lastSelected = this.GetLastSelected(); - if (lastSelected != null) - { - if (lastSelected.Next(this.m_ExpandedArray)) - { - this.SelectionClick(lastSelected); - this.FrameObject(lastSelected.instanceID); - } - } - else - { - if (this.GetFirst() != null) - { - Selection.activeInstanceID = this.GetFirst().instanceID; - this.FrameObject(Selection.activeInstanceID); - } - } - } - private void KeyboardGUI() - { - int controlID = GUIUtility.GetControlID(FocusType.Keyboard); - if (Event.current.GetTypeForControl(controlID) != EventType.KeyDown) - { - return; - } - KeyCode keyCode = Event.current.keyCode; - switch (keyCode) - { - case KeyCode.KeypadEnter: - goto IL_353; - case KeyCode.KeypadEquals: - case KeyCode.Insert: - IL_5E: - if (keyCode != KeyCode.Return) - { - return; - } - goto IL_353; - case KeyCode.UpArrow: - Event.current.Use(); - this.SelectPrevious(); - return; - case KeyCode.DownArrow: - Event.current.Use(); - if (Application.platform == RuntimePlatform.OSXEditor && Event.current.command) - { - this.OpenAssetSelection(); - GUIUtility.ExitGUI(); - } - else - { - this.SelectNext(); - } - return; - case KeyCode.RightArrow: - { - int[] instanceIDs = Selection.instanceIDs; - for (int i = 0; i < instanceIDs.Length; i++) - { - this.SetExpanded(instanceIDs[i], true); - } - Event.current.Use(); - return; - } - case KeyCode.LeftArrow: - { - int[] instanceIDs2 = Selection.instanceIDs; - for (int j = 0; j < instanceIDs2.Length; j++) - { - this.SetExpanded(instanceIDs2[j], false); - } - Event.current.Use(); - return; - } - case KeyCode.Home: - if (this.GetFirst() != null) - { - Selection.activeObject = this.GetFirst().pptrValue; - this.FrameObject(Selection.activeInstanceID); - } - return; - case KeyCode.End: - if (this.GetLast() != null) - { - Selection.activeObject = this.GetLast().pptrValue; - this.FrameObject(Selection.activeInstanceID); - } - return; - case KeyCode.PageUp: - Event.current.Use(); - if (Application.platform == RuntimePlatform.OSXEditor) - { - this.m_ScrollPosition.y = this.m_ScrollPosition.y - this.m_ScreenRect.height; - if (this.m_ScrollPosition.y < 0f) - { - this.m_ScrollPosition.y = 0f; - } - } - else - { - IHierarchyProperty hierarchyProperty = this.GetFirstSelected(); - if (hierarchyProperty != null) - { - int num = 0; - while ((float)num < this.m_ScreenRect.height / BaseProjectWindow.m_RowHeight) - { - if (!hierarchyProperty.Previous(this.m_ExpandedArray)) - { - hierarchyProperty = this.GetFirst(); - break; - } - num++; - } - int instanceID = hierarchyProperty.instanceID; - this.SelectionClick(hierarchyProperty); - this.FrameObject(instanceID); - } - else - { - if (this.GetFirst() != null) - { - Selection.activeObject = this.GetFirst().pptrValue; - this.FrameObject(Selection.activeInstanceID); - } - } - } - return; - case KeyCode.PageDown: - Event.current.Use(); - if (Application.platform == RuntimePlatform.OSXEditor) - { - this.m_ScrollPosition.y = this.m_ScrollPosition.y + this.m_ScreenRect.height; - } - else - { - IHierarchyProperty hierarchyProperty2 = this.GetLastSelected(); - if (hierarchyProperty2 != null) - { - int num2 = 0; - while ((float)num2 < this.m_ScreenRect.height / BaseProjectWindow.m_RowHeight) - { - if (!hierarchyProperty2.Next(this.m_ExpandedArray)) - { - hierarchyProperty2 = this.GetLast(); - break; - } - num2++; - } - int instanceID2 = hierarchyProperty2.instanceID; - this.SelectionClick(hierarchyProperty2); - this.FrameObject(instanceID2); - } - else - { - if (this.GetLast() != null) - { - Selection.activeObject = this.GetLast().pptrValue; - this.FrameObject(Selection.activeInstanceID); - } - } - } - return; - } - goto IL_5E; - IL_353: - if (Application.platform == RuntimePlatform.WindowsEditor) - { - this.OpenAssetSelection(); - GUIUtility.ExitGUI(); - } - } - private bool RevealObject(int targetInstanceID) - { - return this.RevealObject(targetInstanceID, true); - } - private bool RevealObject(int targetInstanceID, bool allowClearSearchFilter) - { - IHierarchyProperty hierarchyProperty = this.GetNewHierarchyProperty(); - if (hierarchyProperty.Find(targetInstanceID, null)) - { - while (hierarchyProperty.Parent()) - { - this.SetExpanded(hierarchyProperty.instanceID, true); - } - return true; - } - if (allowClearSearchFilter) - { - hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - if (hierarchyProperty.Find(targetInstanceID, null)) - { - base.ClearSearchFilter(); - return this.RevealObject(targetInstanceID, true); - } - } - return false; - } - private void RevealObjects(int[] targetInstanceIDs) - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - int[] array = newHierarchyProperty.FindAllAncestors(targetInstanceIDs); - for (int i = 0; i < array.Length; i++) - { - this.SetExpanded(array[i], true); - } - } - internal bool FrameObject(int targetInstanceID) - { - return this.FrameObject(targetInstanceID, true); - } - internal bool FrameObject(int targetInstanceID, bool allowClearSearchFilter) - { - IHierarchyProperty newHierarchyProperty = this.GetNewHierarchyProperty(); - if (this.m_NeedsRelayout) - { - this.m_FrameAfterRelayout = targetInstanceID; - return newHierarchyProperty.Find(targetInstanceID, this.m_ExpandedArray); - } - this.RevealObject(targetInstanceID, allowClearSearchFilter); - newHierarchyProperty = this.GetNewHierarchyProperty(); - if (newHierarchyProperty.Find(targetInstanceID, this.m_ExpandedArray)) - { - int row = newHierarchyProperty.row; - float num = BaseProjectWindow.m_RowHeight * (float)row; - float min = num - this.m_ScreenRect.height + BaseProjectWindow.m_RowHeight; - if (!base.hasSearchFilter) - { - this.m_ScrollPosition.y = Mathf.Clamp(this.m_ScrollPosition.y, min, num); - } - else - { - this.m_ScrollPositionFiltered.y = Mathf.Clamp(this.m_ScrollPositionFiltered.y, min, num); - } - base.Repaint(); - return true; - } - return false; - } - private void SelectionClickContextMenu(IHierarchyProperty property) - { - if (!Selection.Contains(property.instanceID)) - { - Selection.activeInstanceID = property.instanceID; - } - } - private List GetSelection(IHierarchyProperty property, bool mouseDown) - { - List list = new List(); - if (EditorGUI.actionKey) - { - list.AddRange(Selection.instanceIDs); - if (list.Contains(property.instanceID)) - { - list.Remove(property.instanceID); - } - else - { - list.Add(property.instanceID); - } - return list; - } - if (!Event.current.shift) - { - if (mouseDown) - { - list.AddRange(Selection.instanceIDs); - if (list.Contains(property.instanceID)) - { - return list; - } - list.Clear(); - } - list.Add(property.instanceID); - return list; - } - IHierarchyProperty firstSelected = this.GetFirstSelected(); - IHierarchyProperty lastSelected = this.GetLastSelected(); - if (firstSelected == null || !firstSelected.isValid) - { - list.Add(property.instanceID); - return list; - } - IHierarchyProperty hierarchyProperty; - IHierarchyProperty hierarchyProperty2; - if (property.row > lastSelected.row) - { - hierarchyProperty = firstSelected; - hierarchyProperty2 = property; - } - else - { - hierarchyProperty = property; - hierarchyProperty2 = lastSelected; - } - list.Add(hierarchyProperty.instanceID); - while (hierarchyProperty.Next(this.m_ExpandedArray)) - { - list.Add(hierarchyProperty.instanceID); - if (hierarchyProperty.instanceID == hierarchyProperty2.instanceID) - { - break; - } - } - return list; - } - private void SelectionClick(IHierarchyProperty property) - { - List selection = this.GetSelection(property, false); - if (selection.Count == 1) - { - Selection.activeInstanceID = selection[0]; - } - else - { - Selection.instanceIDs = selection.ToArray(); - } - this.m_ProjectViewInternalSelectionChange = true; - if (base.hasSearchFilter) - { - this.m_DidSelectSearchResult = true; - this.m_NeedsRelayout = true; - } - } - private void CreateAssetPopup() - { - GUIContent content = new GUIContent("Create"); - Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.toolbarDropDown, null); - if (Event.current.type == EventType.Repaint) - { - EditorStyles.toolbarDropDown.Draw(rect, content, false, false, false, false); - } - if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) - { - GUIUtility.hotControl = 0; - EditorUtility.DisplayPopupMenu(rect, "Assets/Create", null); - Event.current.Use(); - } - } - private void CreateGameObjectPopup() - { - GUIContent content = new GUIContent("Create"); - Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.toolbarDropDown, null); - if (Event.current.type == EventType.Repaint) - { - EditorStyles.toolbarDropDown.Draw(rect, content, false, false, false, false); - } - if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) - { - GUIUtility.hotControl = 0; - EditorUtility.DisplayPopupMenu(rect, "GameObject/Create Other", null); - Event.current.Use(); - } - } - private void Awake() - { - if (this.m_HierarchyType == HierarchyType.Assets) - { - this.m_ExpandedArray = InternalEditorUtility.expandedProjectWindowItems; - } - } - public new void Show() - { - this.Awake(); - base.Show(); - } - } -} diff --git a/UnityEditor/UnityEditor/BillboardAssetInspector.cs b/UnityEditor/UnityEditor/BillboardAssetInspector.cs new file mode 100644 index 00000000..2b8fad3c --- /dev/null +++ b/UnityEditor/UnityEditor/BillboardAssetInspector.cs @@ -0,0 +1,212 @@ +using System; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(BillboardAsset))] + internal class BillboardAssetInspector : Editor + { + private class GUIStyles + { + public readonly GUIContent m_Width = new GUIContent("Width"); + public readonly GUIContent m_Height = new GUIContent("Height"); + public readonly GUIContent m_Bottom = new GUIContent("Bottom"); + public readonly GUIContent m_ImageCount = new GUIContent("Image Count"); + public readonly GUIContent m_VertexCount = new GUIContent("Vertex Count"); + public readonly GUIContent m_IndexCount = new GUIContent("Index Count"); + public readonly GUIContent m_Material = new GUIContent("Material"); + public readonly GUIContent m_Shaded = new GUIContent("Shaded"); + public readonly GUIContent m_Geometry = new GUIContent("Geometry"); + public readonly GUIStyle m_DropdownButton = new GUIStyle("MiniPopup"); + } + private SerializedProperty m_Width; + private SerializedProperty m_Height; + private SerializedProperty m_Bottom; + private SerializedProperty m_ImageCount; + private SerializedProperty m_VertexCount; + private SerializedProperty m_IndexCount; + private SerializedProperty m_Material; + private bool m_PreviewShaded = true; + private Vector2 m_PreviewDir = new Vector2(-120f, 20f); + private PreviewRenderUtility m_PreviewUtility; + private Mesh m_ShadedMesh; + private Mesh m_GeometryMesh; + private MaterialPropertyBlock m_ShadedMaterialProperties; + private Material m_GeometryMaterial; + private Material m_WireframeMaterial; + private static BillboardAssetInspector.GUIStyles s_Styles; + private static BillboardAssetInspector.GUIStyles Styles + { + get + { + if (BillboardAssetInspector.s_Styles == null) + { + BillboardAssetInspector.s_Styles = new BillboardAssetInspector.GUIStyles(); + } + return BillboardAssetInspector.s_Styles; + } + } + private void OnEnable() + { + this.m_Width = base.serializedObject.FindProperty("width"); + this.m_Height = base.serializedObject.FindProperty("height"); + this.m_Bottom = base.serializedObject.FindProperty("bottom"); + this.m_ImageCount = base.serializedObject.FindProperty("imageTexCoords.Array.size"); + this.m_VertexCount = base.serializedObject.FindProperty("vertices.Array.size"); + this.m_IndexCount = base.serializedObject.FindProperty("indices.Array.size"); + this.m_Material = base.serializedObject.FindProperty("material"); + } + private void OnDisable() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + UnityEngine.Object.DestroyImmediate(this.m_ShadedMesh, true); + UnityEngine.Object.DestroyImmediate(this.m_GeometryMesh, true); + this.m_GeometryMaterial = null; + if (this.m_WireframeMaterial != null) + { + UnityEngine.Object.DestroyImmediate(this.m_WireframeMaterial.shader, true); + UnityEngine.Object.DestroyImmediate(this.m_WireframeMaterial, true); + } + } + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + this.m_ShadedMesh = new Mesh(); + this.m_ShadedMesh.hideFlags = HideFlags.HideAndDontSave; + this.m_ShadedMesh.MarkDynamic(); + this.m_GeometryMesh = new Mesh(); + this.m_GeometryMesh.hideFlags = HideFlags.HideAndDontSave; + this.m_GeometryMesh.MarkDynamic(); + this.m_ShadedMaterialProperties = new MaterialPropertyBlock(); + this.m_GeometryMaterial = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Material.mat") as Material); + this.m_WireframeMaterial = new Material(ModelInspector.WireframeShaderSource); + this.m_WireframeMaterial.hideFlags = HideFlags.HideAndDontSave; + this.m_WireframeMaterial.shader.hideFlags = HideFlags.HideAndDontSave; + EditorUtility.SetCameraAnimateMaterials(this.m_PreviewUtility.m_Camera, true); + } + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.PropertyField(this.m_Width, BillboardAssetInspector.Styles.m_Width, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, BillboardAssetInspector.Styles.m_Height, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Bottom, BillboardAssetInspector.Styles.m_Bottom, new GUILayoutOption[0]); + GUILayout.Space(10f); + EditorGUI.BeginDisabledGroup(true); + EditorGUILayout.PropertyField(this.m_ImageCount, BillboardAssetInspector.Styles.m_ImageCount, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_VertexCount, BillboardAssetInspector.Styles.m_VertexCount, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IndexCount, BillboardAssetInspector.Styles.m_IndexCount, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + EditorGUILayout.PropertyField(this.m_Material, BillboardAssetInspector.Styles.m_Material, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + public override bool HasPreviewGUI() + { + return this.target != null; + } + public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return null; + } + this.InitPreview(); + this.m_PreviewUtility.BeginStaticPreview(new Rect(0f, 0f, (float)width, (float)height)); + this.DoRenderPreview(true); + return this.m_PreviewUtility.EndStaticPreview(); + } + public override void OnPreviewSettings() + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + bool flag = this.m_Material.objectReferenceValue != null; + GUI.enabled = flag; + if (!flag) + { + this.m_PreviewShaded = false; + } + GUIContent content = (!this.m_PreviewShaded) ? BillboardAssetInspector.Styles.m_Geometry : BillboardAssetInspector.Styles.m_Shaded; + Rect rect = GUILayoutUtility.GetRect(content, BillboardAssetInspector.Styles.m_DropdownButton, new GUILayoutOption[] + { + GUILayout.Width(75f) + }); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, BillboardAssetInspector.Styles.m_DropdownButton)) + { + GUIUtility.hotControl = 0; + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(BillboardAssetInspector.Styles.m_Shaded, this.m_PreviewShaded, delegate + { + this.m_PreviewShaded = true; + }); + genericMenu.AddItem(BillboardAssetInspector.Styles.m_Geometry, !this.m_PreviewShaded, delegate + { + this.m_PreviewShaded = false; + }); + genericMenu.DropDown(rect); + } + } + public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Preview requires\nrender texture support"); + } + return; + } + this.InitPreview(); + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + this.DoRenderPreview(this.m_PreviewShaded); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + } + public override string GetInfoString() + { + return string.Format("{0} verts, {1} tris, {2} images", this.m_VertexCount.intValue, this.m_IndexCount.intValue / 3, this.m_ImageCount.intValue); + } + private void DoRenderPreview(bool shaded) + { + BillboardAsset billboardAsset = this.target as BillboardAsset; + Bounds bounds = new Bounds(new Vector3(0f, (this.m_Height.floatValue + this.m_Bottom.floatValue) * 0.5f, 0f), new Vector3(this.m_Width.floatValue, this.m_Height.floatValue, this.m_Width.floatValue)); + float magnitude = bounds.extents.magnitude; + float num = 8f * magnitude; + Quaternion quaternion = Quaternion.Euler(-this.m_PreviewDir.y, -this.m_PreviewDir.x, 0f); + this.m_PreviewUtility.m_Camera.transform.rotation = quaternion; + this.m_PreviewUtility.m_Camera.transform.position = quaternion * (-Vector3.forward * num); + this.m_PreviewUtility.m_Camera.nearClipPlane = num - magnitude * 1.1f; + this.m_PreviewUtility.m_Camera.farClipPlane = num + magnitude * 1.1f; + this.m_PreviewUtility.m_Light[0].intensity = 1.4f; + this.m_PreviewUtility.m_Light[0].transform.rotation = quaternion * Quaternion.Euler(40f, 40f, 0f); + this.m_PreviewUtility.m_Light[1].intensity = 1.4f; + Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); + InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); + if (shaded) + { + billboardAsset.MakeRenderMesh(this.m_ShadedMesh); + billboardAsset.MakeMaterialProperties(this.m_ShadedMaterialProperties, this.m_PreviewUtility.m_Camera, 1f, 1f, 0f); + ModelInspector.RenderMeshPreviewSkipCameraAndLighting(this.m_ShadedMesh, bounds, this.m_PreviewUtility, billboardAsset.material, null, this.m_ShadedMaterialProperties, new Vector2(0f, 0f), -1); + } + else + { + billboardAsset.MakePreviewMesh(this.m_GeometryMesh); + ModelInspector.RenderMeshPreviewSkipCameraAndLighting(this.m_GeometryMesh, bounds, this.m_PreviewUtility, this.m_GeometryMaterial, this.m_WireframeMaterial, null, new Vector2(0f, 0f), -1); + } + InternalEditorUtility.RemoveCustomLighting(); + } + } +} diff --git a/UnityEditor/UnityEditor/BillboardRendererInspector.cs b/UnityEditor/UnityEditor/BillboardRendererInspector.cs new file mode 100644 index 00000000..a3a41ae6 --- /dev/null +++ b/UnityEditor/UnityEditor/BillboardRendererInspector.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(BillboardRenderer))] + internal class BillboardRendererInspector : RendererEditorBase + { + private string[] m_ExcludedProperties; + public override void OnEnable() + { + base.OnEnable(); + base.InitializeProbeFields(); + List list = new List(); + list.AddRange(new string[] + { + "m_CastShadows", + "m_ReceiveShadows", + "m_Materials", + "m_LightmapParameters" + }); + list.AddRange(RendererEditorBase.Probes.GetFieldsStringArray()); + this.m_ExcludedProperties = list.ToArray(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Editor.DrawPropertiesExcluding(base.serializedObject, this.m_ExcludedProperties); + base.RenderProbeFields(); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/BlendTreeInspector.cs b/UnityEditor/UnityEditor/BlendTreeInspector.cs index 772d5af8..4f1c6076 100644 --- a/UnityEditor/UnityEditor/BlendTreeInspector.cs +++ b/UnityEditor/UnityEditor/BlendTreeInspector.cs @@ -4,12 +4,13 @@ using System.Globalization; using System.Linq; using UnityEditor.AnimatedValues; +using UnityEditor.Animations; using UnityEditorInternal; using UnityEngine; using UnityEngine.Events; namespace UnityEditor { - [CustomEditor(typeof(BlendTree))] + [CustomEditor(typeof(UnityEditor.Animations.BlendTree))] internal class BlendTreeInspector : Editor { private class Styles @@ -51,19 +52,19 @@ private enum ChildPropertyToCompute private delegate float GetFloatFromMotion(Motion motion, float mirrorMultiplier); private const int kVisResolution = 64; private static BlendTreeInspector.Styles styles; - internal static AnimatorController currentController = null; + internal static UnityEditor.Animations.AnimatorController currentController = null; internal static Animator currentAnimator = null; - internal static BlendTree parentBlendTree = null; - internal static Action blendTreeHierarchyChanged = null; - internal static Action blendParameterInputChanged = null; + internal static UnityEditor.Animations.BlendTree parentBlendTree = null; + internal static Action blendParameterInputChanged = null; private readonly int m_BlendAnimationID = "BlendAnimationIDHash".GetHashCode(); private readonly int m_ClickDragFloatID = "ClickDragFloatIDHash".GetHashCode(); private ReorderableList m_ReorderableList; private SerializedProperty m_Childs; private SerializedProperty m_BlendParameter; private SerializedProperty m_BlendParameterY; - private BlendTree m_BlendTree; + private UnityEditor.Animations.BlendTree m_BlendTree; private SerializedProperty m_UseAutomaticThresholds; + private SerializedProperty m_NormalizedBlendValues; private SerializedProperty m_MinThreshold; private SerializedProperty m_MaxThreshold; private SerializedProperty m_Name; @@ -72,11 +73,7 @@ private enum ChildPropertyToCompute private AnimBool m_ShowCompute = new AnimBool(); private AnimBool m_ShowAdjust = new AnimBool(); private bool m_ShowGraphValue; - private bool m_HierarchyChanged; - private string m_PrevBlendValueName = string.Empty; - private string m_PrevBlendValueYName = string.Empty; private float[] m_Weights; - private bool m_DirtyVisualization = true; private Texture2D m_BlendTex; private List m_WeightTexs = new List(); private string m_WarningMessage; @@ -102,7 +99,7 @@ private int ParameterCount { get { - return (this.m_BlendType.intValue <= 0) ? 1 : 2; + return (this.m_BlendType.intValue <= 0) ? 1 : ((this.m_BlendType.intValue >= 4) ? 0 : 2); } } public void OnEnable() @@ -111,10 +108,10 @@ public void OnEnable() this.m_BlendParameter = base.serializedObject.FindProperty("m_BlendParameter"); this.m_BlendParameterY = base.serializedObject.FindProperty("m_BlendParameterY"); this.m_UseAutomaticThresholds = base.serializedObject.FindProperty("m_UseAutomaticThresholds"); + this.m_NormalizedBlendValues = base.serializedObject.FindProperty("m_NormalizedBlendValues"); this.m_MinThreshold = base.serializedObject.FindProperty("m_MinThreshold"); this.m_MaxThreshold = base.serializedObject.FindProperty("m_MaxThreshold"); this.m_BlendType = base.serializedObject.FindProperty("m_BlendType"); - this.m_DirtyVisualization = true; } private void Init() { @@ -124,7 +121,7 @@ private void Init() } if (this.m_BlendTree == null) { - this.m_BlendTree = (this.target as BlendTree); + this.m_BlendTree = (this.target as UnityEditor.Animations.BlendTree); } if (BlendTreeInspector.styles == null) { @@ -151,7 +148,7 @@ private void Init() { this.SortByThreshold(); } - this.m_ShowGraphValue = (this.m_Childs.arraySize >= 2); + this.m_ShowGraphValue = ((this.m_BlendType.intValue != 4) ? (this.m_Childs.arraySize >= 2) : (this.m_Childs.arraySize >= 1)); this.m_ShowGraph.value = this.m_ShowGraphValue; this.m_ShowAdjust.value = this.AllMotions(); this.m_ShowCompute.value = !this.m_UseAutomaticThresholds.boolValue; @@ -160,26 +157,24 @@ private void Init() this.m_ShowCompute.valueChanged.AddListener(new UnityAction(base.Repaint)); } this.m_PreviewBlendTree.Init(this.m_BlendTree, BlendTreeInspector.currentAnimator); + bool flag = false; if (this.m_VisInstance == null) { GameObject original = (GameObject)EditorGUIUtility.Load("Avatar/DefaultAvatar.fbx"); - this.m_VisInstance = (GameObject)EditorUtility.InstantiateRemoveAllNonAnimationComponents(original, Vector3.zero, Quaternion.identity); - BlendTreeInspector.InitInstantiatedPreviewRecursive(this.m_VisInstance); + this.m_VisInstance = EditorUtility.InstantiateForAnimatorPreview(original); Renderer[] componentsInChildren = this.m_VisInstance.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { Renderer renderer = componentsInChildren[i]; renderer.enabled = false; } + flag = true; } this.m_VisBlendTree.Init(this.m_BlendTree, this.m_VisInstance.GetComponent()); - } - private static void InitInstantiatedPreviewRecursive(GameObject go) - { - go.hideFlags = HideFlags.HideAndDontSave; - foreach (Transform transform in go.transform) + if (flag && (this.m_BlendType.intValue == 1 || this.m_BlendType.intValue == 2 || this.m_BlendType.intValue == 3)) { - BlendTreeInspector.InitInstantiatedPreviewRecursive(transform.gameObject); + this.UpdateBlendVisualization(); + this.ValidatePositions(); } } internal override void OnHeaderIconGUI(Rect iconRect) @@ -204,7 +199,6 @@ internal override void OnHeaderTitleGUI(Rect titleRect, string header) UnityEngine.Object obj = targets[i]; ObjectNames.SetNameSmart(obj, text); } - this.m_HierarchyChanged = true; } base.serializedObject.ApplyModifiedProperties(); } @@ -212,114 +206,125 @@ internal override void OnHeaderControlsGUI() { EditorGUIUtility.labelWidth = 80f; base.serializedObject.Update(); - EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_BlendType, new GUILayoutOption[0]); - if (EditorGUI.EndChangeCheck()) - { - this.m_DirtyVisualization = true; - } base.serializedObject.ApplyModifiedProperties(); } - private void ParameterGUI() + private List CollectParameters(UnityEditor.Animations.AnimatorController controller) { - EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); - if (this.ParameterCount == 1) - { - EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameter")); - } - else - { - EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameters")); - } List list = new List(); - string blendParameter = this.m_BlendTree.blendParameter; - string blendParameterY = this.m_BlendTree.blendParameterY; - int num = 0; - int num2 = 0; - if (BlendTreeInspector.currentController != null) + if (controller != null) { - for (int i = 0; i < BlendTreeInspector.currentController.parameterCount; i++) + UnityEngine.AnimatorControllerParameter[] parameters = controller.parameters; + for (int i = 0; i < parameters.Length; i++) { - if (BlendTreeInspector.currentController.GetParameterType(i) == AnimatorControllerParameterType.Float) + UnityEngine.AnimatorControllerParameter animatorControllerParameter = parameters[i]; + if (animatorControllerParameter.type == UnityEngine.AnimatorControllerParameterType.Float) { - string parameterName = BlendTreeInspector.currentController.GetParameterName(i); - if (parameterName == blendParameter) - { - num = list.Count; - } - if (parameterName == blendParameterY) - { - num2 = list.Count; - } - list.Add(parameterName); + list.Add(animatorControllerParameter.name); } } } - bool flag = false; - int num3 = EditorGUILayout.Popup(num, list.ToArray(), new GUILayoutOption[0]); - if (num3 != num) + return list; + } + private void ParameterGUI() + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (this.ParameterCount > 1) { - this.m_BlendParameter.stringValue = list[num3]; + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameters")); } - if (this.m_PrevBlendValueName != blendParameter) + else { - this.m_PrevBlendValueName = blendParameter; - flag = true; + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameter")); + } + base.serializedObject.Update(); + string text = this.m_BlendTree.blendParameter; + string text2 = this.m_BlendTree.blendParameterY; + List list = this.CollectParameters(BlendTreeInspector.currentController); + EditorGUI.BeginChangeCheck(); + text = EditorGUILayout.DelayedTextFieldDropDown(text, list.ToArray()); + if (EditorGUI.EndChangeCheck()) + { + this.m_BlendParameter.stringValue = text; } if (this.ParameterCount > 1) { - int num4 = EditorGUILayout.Popup(num2, list.ToArray(), new GUILayoutOption[0]); - if (num4 != num2) - { - this.m_BlendParameterY.stringValue = list[num4]; - } - if (this.m_PrevBlendValueYName != blendParameterY) + EditorGUI.BeginChangeCheck(); + text2 = EditorGUILayout.TextFieldDropDown(text2, list.ToArray()); + if (EditorGUI.EndChangeCheck()) { - this.m_PrevBlendValueYName = blendParameterY; - flag = true; + this.m_BlendParameterY.stringValue = text2; } } - if (flag) - { - this.m_PreviewBlendTree.ResetStateMachine(); - this.m_VisBlendTree.Reset(); - this.m_DirtyVisualization = true; - } + base.serializedObject.ApplyModifiedProperties(); EditorGUILayout.EndHorizontal(); } public override void OnInspectorGUI() { this.Init(); base.serializedObject.Update(); - this.ParameterGUI(); - this.m_ShowGraphValue = (this.m_Childs.arraySize >= 2); + if (this.m_BlendType.intValue != 4) + { + this.ParameterGUI(); + } + this.m_ShowGraphValue = ((this.m_BlendType.intValue != 4) ? (this.m_Childs.arraySize >= 2) : (this.m_Childs.arraySize >= 1)); this.m_ShowGraph.target = this.m_ShowGraphValue; this.m_UseAutomaticThresholds = base.serializedObject.FindProperty("m_UseAutomaticThresholds"); GUI.enabled = true; if (EditorGUILayout.BeginFadeGroup(this.m_ShowGraph.faded)) { - if (this.ParameterCount == 1) + if (this.m_BlendType.intValue == 0) { this.BlendGraph(EditorGUILayout.GetControlRect(false, 40f, BlendTreeInspector.styles.background, new GUILayoutOption[0])); this.ThresholdValues(); } else { - GUILayout.Space(1f); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - Rect aspectRect = GUILayoutUtility.GetAspectRect(1f, new GUILayoutOption[] + if (this.m_BlendType.intValue == 4) + { + for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) + { + string recursiveBlendParameter = this.m_BlendTree.GetRecursiveBlendParameter(i); + float recursiveBlendParameterMin = this.m_BlendTree.GetRecursiveBlendParameterMin(i); + float recursiveBlendParameterMax = this.m_BlendTree.GetRecursiveBlendParameterMax(i); + EditorGUI.BeginChangeCheck(); + float value = EditorGUILayout.Slider(recursiveBlendParameter, this.m_BlendTree.GetInputBlendValue(recursiveBlendParameter), recursiveBlendParameterMin, recursiveBlendParameterMax, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (BlendTreeInspector.parentBlendTree) + { + BlendTreeInspector.parentBlendTree.SetInputBlendValue(recursiveBlendParameter, value); + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(BlendTreeInspector.parentBlendTree); + } + } + this.m_BlendTree.SetInputBlendValue(recursiveBlendParameter, value); + if (BlendTreeInspector.blendParameterInputChanged != null) + { + BlendTreeInspector.blendParameterInputChanged(this.m_BlendTree); + } + } + } + } + else { - GUILayout.MaxWidth(235f) - }); - GUI.Label(new Rect(aspectRect.x - 1f, aspectRect.y - 1f, aspectRect.width + 2f, aspectRect.height + 2f), GUIContent.none, EditorStyles.textField); - GUI.BeginGroup(aspectRect); - aspectRect.x = 0f; - aspectRect.y = 0f; - this.BlendGraph2D(aspectRect); - GUI.EndGroup(); - GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); + GUILayout.Space(1f); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect aspectRect = GUILayoutUtility.GetAspectRect(1f, new GUILayoutOption[] + { + GUILayout.MaxWidth(235f) + }); + GUI.Label(new Rect(aspectRect.x - 1f, aspectRect.y - 1f, aspectRect.width + 2f, aspectRect.height + 2f), GUIContent.none, EditorStyles.textField); + GUI.BeginGroup(aspectRect); + aspectRect.x = 0f; + aspectRect.y = 0f; + this.BlendGraph2D(aspectRect); + GUI.EndGroup(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } } GUILayout.Space(5f); } @@ -328,13 +333,16 @@ public override void OnInspectorGUI() { this.m_ReorderableList.DoLayoutList(); } + if (this.m_BlendType.intValue == 4) + { + EditorGUILayout.PropertyField(this.m_NormalizedBlendValues, EditorGUIUtility.TempContent("Normalized Blend Values"), new GUILayoutOption[0]); + } if (this.m_ShowGraphValue) { GUILayout.Space(10f); this.AutoCompute(); } base.serializedObject.ApplyModifiedProperties(); - this.DoHierarchyChangedCallback(); } private void SetMinMaxThresholds() { @@ -482,14 +490,15 @@ public float ClickDragFloat(Rect position, float value, bool alignRight) text = text.Replace(',', '.'); if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out value)) { - value = (EditorGUI.s_RecycledCurrentEditingFloat = 0f); + EditorGUI.s_RecycledCurrentEditingFloat = 0.0; + value = 0f; return value; } if (float.IsNaN(value)) { value = 0f; } - EditorGUI.s_RecycledCurrentEditingFloat = value; + EditorGUI.s_RecycledCurrentEditingFloat = (double)value; } } } @@ -671,14 +680,14 @@ private void UpdateBlendVisualization() if (this.m_BlendTex == null) { this.m_BlendTex = new Texture2D(64, 64, TextureFormat.RGBA32, false); - this.m_BlendTex.hideFlags = HideFlags.DontSave; + this.m_BlendTex.hideFlags = HideFlags.HideAndDontSave; this.m_BlendTex.wrapMode = TextureWrapMode.Clamp; } while (this.m_WeightTexs.Count < activeMotionPositions.Length) { Texture2D texture2D = new Texture2D(64, 64, TextureFormat.RGBA32, false); texture2D.wrapMode = TextureWrapMode.Clamp; - texture2D.hideFlags = HideFlags.DontSave; + texture2D.hideFlags = HideFlags.HideAndDontSave; this.m_WeightTexs.Add(texture2D); } while (this.m_WeightTexs.Count > activeMotionPositions.Length) @@ -705,9 +714,8 @@ private void UpdateBlendVisualization() } } } - BlendTreePreviewUtility.CalculateBlendTexture(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).nameHash, this.m_BlendTex, array, this.m_BlendRect); + BlendTreePreviewUtility.CalculateBlendTexture(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).fullPathHash, this.m_BlendTex, array, this.m_BlendRect); stopwatch.Stop(); - this.m_DirtyVisualization = false; } private Vector2[] GetMotionPositions() { @@ -800,7 +808,7 @@ private float ConvertFloat(float input, float fromMin, float fromMax, float toMi } private void BlendGraph2D(Rect area) { - if (this.m_DirtyVisualization) + if (this.m_VisBlendTree.controllerDirty) { this.UpdateBlendVisualization(); this.ValidatePositions(); @@ -823,7 +831,7 @@ private void BlendGraph2D(Rect area) { this.m_Weights = new float[num3]; } - BlendTreePreviewUtility.CalculateRootBlendTreeChildWeights(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).nameHash, this.m_Weights, num, num2); + BlendTreePreviewUtility.CalculateRootBlendTreeChildWeights(this.m_VisBlendTree.animator, 0, this.m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).fullPathHash, this.m_Weights, num, num2); num = area.x + Mathf.InverseLerp(vector.x, vector2.x, num) * area.width; num2 = area.y + (1f - Mathf.InverseLerp(vector.y, vector2.y, num2)) * area.height; Rect position = new Rect(num - 5f, num2 - 5f, 11f, 11f); @@ -864,13 +872,6 @@ private void BlendGraph2D(Rect area) current.Use(); GUIUtility.hotControl = 0; this.s_DraggingPoint = false; - for (int k = 0; k < motionPositions.Length; k++) - { - if (this.m_SelectedPoint == k) - { - this.m_DirtyVisualization = true; - } - } } break; case EventType.MouseDrag: @@ -900,9 +901,9 @@ private void BlendGraph2D(Rect area) } else { - for (int l = 0; l < motionPositions.Length; l++) + for (int k = 0; k < motionPositions.Length; k++) { - if (this.m_SelectedPoint == l) + if (this.m_SelectedPoint == k) { Vector2 vector2Value; vector2Value.x = this.ConvertFloat(current.mousePosition.x, area.xMin, area.xMax, vector.x, vector2.x); @@ -912,11 +913,10 @@ private void BlendGraph2D(Rect area) vector2Value.y = MathUtils.RoundBasedOnMinimumDifference(vector2Value.y, minDifference); vector2Value.x = Mathf.Clamp(vector2Value.x, -10000f, 10000f); vector2Value.y = Mathf.Clamp(vector2Value.y, -10000f, 10000f); - SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(l); + SerializedProperty arrayElementAtIndex = this.m_Childs.GetArrayElementAtIndex(k); SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Position"); serializedProperty.vector2Value = vector2Value; current.Use(); - this.m_DirtyVisualization = true; this.s_DraggingPoint = true; } } @@ -944,26 +944,26 @@ private void BlendGraph2D(Rect area) GUI.color = Color.white; if (!this.s_DraggingPoint) { - for (int m = 0; m < motionPositions.Length; m++) + for (int l = 0; l < motionPositions.Length; l++) { - if (motionToActiveMotionIndices[m] >= 0) + if (motionToActiveMotionIndices[l] >= 0) { - this.DrawWeightShape(motionPositions[m], this.m_Weights[motionToActiveMotionIndices[m]], 0); + this.DrawWeightShape(motionPositions[l], this.m_Weights[motionToActiveMotionIndices[l]], 0); } } - for (int n = 0; n < motionPositions.Length; n++) + for (int m = 0; m < motionPositions.Length; m++) { - if (motionToActiveMotionIndices[n] >= 0) + if (motionToActiveMotionIndices[m] >= 0) { - this.DrawWeightShape(motionPositions[n], this.m_Weights[motionToActiveMotionIndices[n]], 1); + this.DrawWeightShape(motionPositions[m], this.m_Weights[motionToActiveMotionIndices[m]], 1); } } } - for (int num4 = 0; num4 < motionPositions.Length; num4++) + for (int n = 0; n < motionPositions.Length; n++) { - Rect position2 = new Rect(motionPositions[num4].x - 6f, motionPositions[num4].y - 6f, 13f, 13f); - bool flag = this.m_ReorderableList.index == num4; - if (motionToActiveMotionIndices[num4] < 0) + Rect position2 = new Rect(motionPositions[n].x - 6f, motionPositions[n].y - 6f, 13f, 13f); + bool flag = this.m_ReorderableList.index == n; + if (motionToActiveMotionIndices[n] < 0) { GUI.color = BlendTreeInspector.s_VisPointEmptyColor; } @@ -1157,15 +1157,13 @@ public void EndDragChild(ReorderableList list) serializedProperty2.floatValue = list2[j]; } base.serializedObject.ApplyModifiedProperties(); - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } private void DrawHeader(Rect headerRect) { headerRect.xMin += 14f; headerRect.y += 1f; headerRect.height = 16f; - Rect[] rowRects = this.GetRowRects(headerRect, this.ParameterCount); + Rect[] rowRects = this.GetRowRects(headerRect, this.m_BlendType.intValue); int num = 0; rowRects[num].xMin = rowRects[num].xMin - 14f; GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Motion"), EditorStyles.label); @@ -1179,10 +1177,18 @@ private void DrawHeader(Rect headerRect) } else { - GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos X"), EditorStyles.label); - num++; - GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos Y"), EditorStyles.label); - num++; + if (this.m_BlendType.intValue == 4) + { + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Parameter"), EditorStyles.label); + num++; + } + else + { + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos X"), EditorStyles.label); + num++; + GUI.Label(rowRects[num], EditorGUIUtility.TempContent("Pos Y"), EditorStyles.label); + num++; + } } GUI.Label(rowRects[num], BlendTreeInspector.styles.speedIcon, BlendTreeInspector.styles.headerIcon); num++; @@ -1204,34 +1210,33 @@ public void RemoveButton(ReorderableList list) list.index = this.m_Childs.arraySize - 1; } this.SetMinMaxThresholds(); - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } - private Rect[] GetRowRects(Rect r, int parameterCount) + private Rect[] GetRowRects(Rect r, int blendType) { - Rect[] array = new Rect[3 + parameterCount]; - float num = r.width; - float num2 = 16f; - num -= num2; - num -= (float)(24 + 4 * (parameterCount - 1)); - float num3 = (float)Mathf.FloorToInt(num * 0.2f); - float num4 = num - num3 * (float)(parameterCount + 1); - float num5 = r.x; - int num6 = 0; - array[num6] = new Rect(num5, r.y, num4, r.height); - num5 += num4 + 8f; - num6++; - for (int i = 0; i < parameterCount; i++) - { - array[num6] = new Rect(num5, r.y, num3, r.height); - num5 += num3 + 4f; - num6++; - } - num5 += 4f; - array[num6] = new Rect(num5, r.y, num3, r.height); - num5 += num3 + 8f; - num6++; - array[num6] = new Rect(num5, r.y, num2, r.height); + int num = (blendType <= 0 || blendType >= 4) ? 1 : 2; + Rect[] array = new Rect[3 + num]; + float num2 = r.width; + float num3 = 16f; + num2 -= num3; + num2 -= (float)(24 + 4 * (num - 1)); + float num4 = (float)Mathf.FloorToInt(num2 * 0.2f); + float num5 = num2 - num4 * (float)(num + 1); + float num6 = r.x; + int num7 = 0; + array[num7] = new Rect(num6, r.y, num5, r.height); + num6 += num5 + 8f; + num7++; + for (int i = 0; i < num; i++) + { + array[num7] = new Rect(num6, r.y, num4, r.height); + num6 += num4 + 4f; + num7++; + } + num6 += 4f; + array[num7] = new Rect(num6, r.y, num4, r.height); + num6 += num4 + 8f; + num7++; + array[num7] = new Rect(num6, r.y, num3, r.height); return array; } public void DrawChild(Rect r, int index, bool isActive, bool isFocused) @@ -1240,29 +1245,24 @@ public void DrawChild(Rect r, int index, bool isActive, bool isFocused) SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("m_Motion"); r.y += 1f; r.height = 16f; - Rect[] rowRects = this.GetRowRects(r, this.ParameterCount); + Rect[] rowRects = this.GetRowRects(r, this.m_BlendType.intValue); int num = 0; EditorGUI.BeginChangeCheck(); - Motion motion = this.m_BlendTree.GetMotion(index); + Motion motion = this.m_BlendTree.children[index].motion; EditorGUI.PropertyField(rowRects[num], serializedProperty, GUIContent.none); num++; - if (EditorGUI.EndChangeCheck()) + if (EditorGUI.EndChangeCheck() && motion is UnityEditor.Animations.BlendTree && motion != serializedProperty.objectReferenceValue as Motion) { - if (motion is BlendTree && motion != serializedProperty.objectReferenceValue as Motion) + if (EditorUtility.DisplayDialog("Changing BlendTree will delete previous BlendTree", "You cannot undo this action.", "Delete", "Cancel")) { - if (EditorUtility.DisplayDialog("Changing BlendTree will delete previous BlendTree", "You cannot undo this action.", "Delete", "Cancel")) - { - MecanimUtilities.DestroyBlendTreeRecursive(motion as BlendTree); - } - else - { - serializedProperty.objectReferenceValue = motion; - } + MecanimUtilities.DestroyBlendTreeRecursive(motion as UnityEditor.Animations.BlendTree); + } + else + { + serializedProperty.objectReferenceValue = motion; } - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } - if (this.ParameterCount == 1) + if (this.m_BlendType.intValue == 0) { SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("m_Threshold"); EditorGUI.BeginDisabledGroup(this.m_UseAutomaticThresholds.boolValue); @@ -1282,21 +1282,37 @@ public void DrawChild(Rect r, int index, bool isActive, bool isFocused) } else { - SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("m_Position"); - Vector2 vector2Value = serializedProperty3.vector2Value; - for (int i = 0; i < 2; i++) + if (this.m_BlendType.intValue == 4) { + List list = this.CollectParameters(BlendTreeInspector.currentController); + ChildMotion[] children = this.m_BlendTree.children; + string text = children[index].directBlendParameter; EditorGUI.BeginChangeCheck(); - string s2 = EditorGUI.DelayedTextField(rowRects[num], vector2Value[i].ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.textField); + text = EditorGUI.TextFieldDropDown(rowRects[num], text, list.ToArray()); num++; - float value; - if (EditorGUI.EndChangeCheck() && float.TryParse(s2, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out value)) + if (EditorGUI.EndChangeCheck()) { - vector2Value[i] = Mathf.Clamp(value, -10000f, 10000f); - serializedProperty3.vector2Value = vector2Value; - base.serializedObject.ApplyModifiedProperties(); - this.m_DirtyVisualization = true; - GUI.changed = true; + children[index].directBlendParameter = text; + this.m_BlendTree.children = children; + } + } + else + { + SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("m_Position"); + Vector2 vector2Value = serializedProperty3.vector2Value; + for (int i = 0; i < 2; i++) + { + EditorGUI.BeginChangeCheck(); + string s2 = EditorGUI.DelayedTextField(rowRects[num], vector2Value[i].ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.textField); + num++; + float value; + if (EditorGUI.EndChangeCheck() && float.TryParse(s2, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out value)) + { + vector2Value[i] = Mathf.Clamp(value, -10000f, 10000f); + serializedProperty3.vector2Value = vector2Value; + base.serializedObject.ApplyModifiedProperties(); + GUI.changed = true; + } } } } @@ -1340,14 +1356,21 @@ private bool AllMotions() } private void AutoCompute() { - if (this.ParameterCount == 1) + if (this.m_BlendType.intValue == 0) { EditorGUILayout.PropertyField(this.m_UseAutomaticThresholds, EditorGUIUtility.TempContent("Automate Thresholds"), new GUILayoutOption[0]); this.m_ShowCompute.target = !this.m_UseAutomaticThresholds.boolValue; } else { - this.m_ShowCompute.target = true; + if (this.m_BlendType.intValue == 4) + { + this.m_ShowCompute.target = false; + } + else + { + this.m_ShowCompute.target = true; + } } this.m_ShowAdjust.target = this.AllMotions(); if (EditorGUILayout.BeginFadeGroup(this.m_ShowCompute.faded)) @@ -1428,6 +1451,8 @@ private void ComputeFromAngularSpeedRadians(object obj) } private void ComputeProperty(BlendTreeInspector.GetFloatFromMotion func, BlendTreeInspector.ChildPropertyToCompute prop) { + float num = 0f; + float[] array = new float[this.m_Childs.arraySize]; this.m_UseAutomaticThresholds.boolValue = false; for (int i = 0; i < this.m_Childs.arraySize; i++) { @@ -1436,11 +1461,13 @@ private void ComputeProperty(BlendTreeInspector.GetFloatFromMotion func, BlendTr Motion motion = serializedProperty.objectReferenceValue as Motion; if (motion != null) { - float num = func(motion, (float)((!serializedProperty2.boolValue) ? 1 : -1)); + float num2 = func(motion, (float)((!serializedProperty2.boolValue) ? 1 : -1)); + array[i] = num2; + num += num2; if (prop == BlendTreeInspector.ChildPropertyToCompute.Threshold) { SerializedProperty serializedProperty3 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Threshold"); - serializedProperty3.floatValue = num; + serializedProperty3.floatValue = num2; } else { @@ -1448,23 +1475,37 @@ private void ComputeProperty(BlendTreeInspector.GetFloatFromMotion func, BlendTr Vector2 vector2Value = serializedProperty4.vector2Value; if (prop == BlendTreeInspector.ChildPropertyToCompute.PositionX) { - vector2Value.x = num; + vector2Value.x = num2; } else { - vector2Value.y = num; + vector2Value.y = num2; } serializedProperty4.vector2Value = vector2Value; } } } - this.m_SerializedObject.ApplyModifiedProperties(); - if (prop == BlendTreeInspector.ChildPropertyToCompute.Threshold) + num /= (float)this.m_Childs.arraySize; + float num3 = 0f; + for (int j = 0; j < array.Length; j++) + { + num3 += Mathf.Pow(array[j] - num, 2f); + } + num3 /= (float)array.Length; + if (num3 < Mathf.Epsilon) + { + UnityEngine.Debug.LogWarning("Could not compute threshold for '" + this.m_BlendTree.name + "' there is not enough data"); + this.m_SerializedObject.Update(); + } + else { - this.SortByThreshold(); - this.SetMinMaxThreshold(); + this.m_SerializedObject.ApplyModifiedProperties(); + if (prop == BlendTreeInspector.ChildPropertyToCompute.Threshold) + { + this.SortByThreshold(); + this.SetMinMaxThreshold(); + } } - this.m_DirtyVisualization = true; } private void ComputePositionsFromVelocity() { @@ -1485,9 +1526,9 @@ private void ComputeTimeScaleFromSpeed() AnimationClip animationClip = serializedProperty.objectReferenceValue as AnimationClip; if (animationClip != null) { - if (animationClip.isAnimatorMotion) + if (!animationClip.legacy) { - if (animationClip.apparentSpeed < 1.401298E-45f) + if (animationClip.apparentSpeed < Mathf.Epsilon) { UnityEngine.Debug.LogWarning("Could not adjust time scale for " + animationClip.name + " because it has no speed"); } @@ -1511,7 +1552,7 @@ private void ResetTimeScale() { SerializedProperty serializedProperty = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion"); AnimationClip animationClip = serializedProperty.objectReferenceValue as AnimationClip; - if (animationClip != null && animationClip.isAnimatorMotion) + if (animationClip != null && !animationClip.legacy) { SerializedProperty serializedProperty2 = this.m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_TimeScale"); serializedProperty2.floatValue = 1f; @@ -1542,8 +1583,6 @@ private void SortByThreshold() } } this.m_SerializedObject.ApplyModifiedProperties(); - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } private void SetMinMaxThreshold() { @@ -1557,22 +1596,17 @@ private void SetMinMaxThreshold() private void AddChildAnimation() { Undo.RegisterCompleteObjectUndo(this.m_BlendTree, "Child animation added"); - this.m_BlendTree.AddAnimationClip(null); - this.SetNewThresholdAndPosition(this.m_BlendTree.childCount - 1); + this.m_BlendTree.AddChild(null); + this.SetNewThresholdAndPosition(this.m_BlendTree.children.Length - 1); this.m_ReorderableList.index = this.m_Childs.arraySize - 1; - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } private void AddBlendTreeCallback() { Undo.RegisterCompleteObjectUndo(this.m_BlendTree, "Child blendtree added"); - BlendTree blendTree = this.m_BlendTree.AddNewBlendTree(); - blendTree.name = "Blend Tree"; + UnityEditor.Animations.BlendTree blendTree = this.m_BlendTree.CreateBlendTreeChild(0f); blendTree.blendParameter = this.m_BlendTree.blendParameter; - this.SetNewThresholdAndPosition(this.m_BlendTree.childCount - 1); + this.SetNewThresholdAndPosition(this.m_BlendTree.children.Length - 1); this.m_ReorderableList.index = this.m_Childs.arraySize - 1; - this.m_HierarchyChanged = true; - this.m_DirtyVisualization = true; } private void SetNewThresholdAndPosition(int index) { @@ -1681,13 +1715,5 @@ public void OnDestroy() UnityEngine.Object.DestroyImmediate(this.m_BlendTex); } } - public void DoHierarchyChangedCallback() - { - if (this.m_HierarchyChanged && BlendTreeInspector.blendTreeHierarchyChanged != null) - { - BlendTreeInspector.blendTreeHierarchyChanged(this.m_BlendTree); - } - this.m_HierarchyChanged = false; - } } } diff --git a/UnityEditor/UnityEditor/BoxCollider2DEditor.cs b/UnityEditor/UnityEditor/BoxCollider2DEditor.cs index bc785d8d..bd159fc7 100644 --- a/UnityEditor/UnityEditor/BoxCollider2DEditor.cs +++ b/UnityEditor/UnityEditor/BoxCollider2DEditor.cs @@ -7,13 +7,9 @@ internal class BoxCollider2DEditor : Collider2DEditorBase { private static readonly int s_BoxHash = "BoxCollider2DEditor".GetHashCode(); private readonly BoxEditor m_BoxEditor = new BoxEditor(true, BoxCollider2DEditor.s_BoxHash, true); - protected SerializedProperty m_Center; - protected SerializedProperty m_Size; public override void OnEnable() { base.OnEnable(); - this.m_Center = base.serializedObject.FindProperty("m_Center"); - this.m_Size = base.serializedObject.FindProperty("m_Size"); this.m_BoxEditor.OnEnable(); this.m_BoxEditor.SetAlwaysDisplayHandles(true); } @@ -21,12 +17,8 @@ public override void OnInspectorGUI() { base.serializedObject.Update(); base.InspectorEditButtonGUI(); - EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Size, new GUILayoutOption[0]); + base.OnInspectorGUI(); base.serializedObject.ApplyModifiedProperties(); - base.CheckColliderErrorState(); } public override void OnDisable() { @@ -40,12 +32,12 @@ public void OnSceneGUI() return; } BoxCollider2D boxCollider2D = (BoxCollider2D)this.target; - Vector3 v = boxCollider2D.center; + Vector3 v = boxCollider2D.offset; Vector3 v2 = boxCollider2D.size; if (this.m_BoxEditor.OnSceneGUI(boxCollider2D.transform, Handles.s_ColliderHandleColor, ref v, ref v2)) { Undo.RecordObject(boxCollider2D, "Modify collider"); - boxCollider2D.center = v; + boxCollider2D.offset = v; boxCollider2D.size = v2; } } diff --git a/UnityEditor/UnityEditor/BoxEditor.cs b/UnityEditor/UnityEditor/BoxEditor.cs index 6d7a6e46..cb8948e0 100644 --- a/UnityEditor/UnityEditor/BoxEditor.cs +++ b/UnityEditor/UnityEditor/BoxEditor.cs @@ -11,16 +11,37 @@ internal class BoxEditor private bool m_UseLossyScale; private bool m_AlwaysDisplayHandles; private bool m_DisableZaxis; + private bool m_AllowNegativeSize = true; + public Handles.DrawCapFunction drawMethodForHandles; + public Func getHandleSizeMethod; + public bool allowNegativeSize + { + get + { + return this.m_AllowNegativeSize; + } + set + { + this.m_AllowNegativeSize = value; + } + } + public float backfaceAlphaMultiplier + { + get; + set; + } public BoxEditor(bool useLossyScale, int controlIdHint) { this.m_UseLossyScale = useLossyScale; this.m_ControlIdHint = controlIdHint; + this.backfaceAlphaMultiplier = Handles.backfaceAlphaMultiplier; } public BoxEditor(bool useLossyScale, int controlIdHint, bool disableZaxis) { this.m_UseLossyScale = useLossyScale; this.m_ControlIdHint = controlIdHint; this.m_DisableZaxis = disableZaxis; + this.backfaceAlphaMultiplier = Handles.backfaceAlphaMultiplier; } public void OnEnable() { @@ -54,6 +75,10 @@ public bool OnSceneGUI(Transform transform, Color color, bool handlesOnly, ref V return this.OnSceneGUI(transform.localToWorldMatrix, color, handlesOnly, ref center, ref size); } public bool OnSceneGUI(Matrix4x4 transform, Color color, bool handlesOnly, ref Vector3 center, ref Vector3 size) + { + return this.OnSceneGUI(transform, color, color, handlesOnly, ref center, ref size); + } + public bool OnSceneGUI(Matrix4x4 transform, Color boxColor, Color midPointHandleColor, bool handlesOnly, ref Vector3 center, ref Vector3 size) { bool flag = GUIUtility.hotControl == this.m_HandleControlID; if (!this.m_AlwaysDisplayHandles && !flag) @@ -64,8 +89,8 @@ public bool OnSceneGUI(Matrix4x4 transform, Color color, bool handlesOnly, ref V } return false; } - Color color2 = Handles.color; - Handles.color = color; + Color color = Handles.color; + Handles.color = boxColor; Vector3 b = center - size * 0.5f; Vector3 a = center + size * 0.5f; Matrix4x4 matrix = Handles.matrix; @@ -73,9 +98,13 @@ public bool OnSceneGUI(Matrix4x4 transform, Color color, bool handlesOnly, ref V int hotControl = GUIUtility.hotControl; if (!handlesOnly) { - this.DrawWireframeBox((a - b) * 0.5f + b, a - b); + this.DrawWireframeBox(center, size); } - this.MidpointHandles(ref b, ref a, Handles.matrix); + Vector3 point = transform.inverse.MultiplyPoint(Camera.current.transform.position); + Bounds bounds = new Bounds(center, size); + bool isCameraInsideBox = bounds.Contains(point); + Handles.color = midPointHandleColor; + this.MidpointHandles(ref b, ref a, Handles.matrix, isCameraInsideBox); if (hotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) { this.m_HandleControlID = GUIUtility.hotControl; @@ -86,7 +115,7 @@ public bool OnSceneGUI(Matrix4x4 transform, Color color, bool handlesOnly, ref V center = (a + b) * 0.5f; size = a - b; } - Handles.color = color2; + Handles.color = color; Handles.matrix = matrix; return changed; } @@ -111,60 +140,79 @@ public void DrawWireframeBox(Vector3 center, Vector3 siz) Handles.DrawLine(array[2], array[7]); Handles.DrawLine(array[3], array[8]); } - private void MidpointHandles(ref Vector3 minPos, ref Vector3 maxPos, Matrix4x4 transform) + private void MidpointHandles(ref Vector3 minPos, ref Vector3 maxPos, Matrix4x4 transform, bool isCameraInsideBox) { Vector3 vector = new Vector3(1f, 0f, 0f); Vector3 localTangent = new Vector3(0f, 1f, 0f); Vector3 vector2 = new Vector3(0f, 0f, 1f); Vector3 vector3 = (maxPos + minPos) * 0.5f; Vector3 localPos = new Vector3(maxPos.x, vector3.y, vector3.z); - maxPos.x = this.MidpointHandle(localPos, localTangent, vector2, transform).x; + Vector3 vector4 = this.MidpointHandle(localPos, localTangent, vector2, transform, isCameraInsideBox); + maxPos.x = ((!this.m_AllowNegativeSize) ? Math.Max(vector4.x, minPos.x) : vector4.x); localPos = new Vector3(minPos.x, vector3.y, vector3.z); - minPos.x = this.MidpointHandle(localPos, localTangent, -vector2, transform).x; + vector4 = this.MidpointHandle(localPos, localTangent, -vector2, transform, isCameraInsideBox); + minPos.x = ((!this.m_AllowNegativeSize) ? Math.Min(vector4.x, maxPos.x) : vector4.x); localPos = new Vector3(vector3.x, maxPos.y, vector3.z); - maxPos.y = this.MidpointHandle(localPos, vector, -vector2, transform).y; + vector4 = this.MidpointHandle(localPos, vector, -vector2, transform, isCameraInsideBox); + maxPos.y = ((!this.m_AllowNegativeSize) ? Math.Max(vector4.y, minPos.y) : vector4.y); localPos = new Vector3(vector3.x, minPos.y, vector3.z); - minPos.y = this.MidpointHandle(localPos, vector, vector2, transform).y; + vector4 = this.MidpointHandle(localPos, vector, vector2, transform, isCameraInsideBox); + minPos.y = ((!this.m_AllowNegativeSize) ? Math.Min(vector4.y, maxPos.y) : vector4.y); if (!this.m_DisableZaxis) { localPos = new Vector3(vector3.x, vector3.y, maxPos.z); - maxPos.z = this.MidpointHandle(localPos, localTangent, -vector, transform).z; + vector4 = this.MidpointHandle(localPos, localTangent, -vector, transform, isCameraInsideBox); + maxPos.z = ((!this.m_AllowNegativeSize) ? Math.Max(vector4.z, minPos.z) : vector4.z); localPos = new Vector3(vector3.x, vector3.y, minPos.z); - minPos.z = this.MidpointHandle(localPos, localTangent, vector, transform).z; + vector4 = this.MidpointHandle(localPos, localTangent, vector, transform, isCameraInsideBox); + minPos.z = ((!this.m_AllowNegativeSize) ? Math.Min(vector4.z, maxPos.z) : vector4.z); } } - private Vector3 MidpointHandle(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform) + private static void DefaultMidPointDrawFunc(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.DotCap(controlID, position, rotation, size); + } + private static float DefaultMidpointGetSizeFunc(Vector3 localPos) + { + return HandleUtility.GetHandleSize(localPos) * 0.03f; + } + private Vector3 MidpointHandle(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, bool isCameraInsideBox) { Color color = Handles.color; float num = 1f; - this.AdjustMidpointHandleColor(localPos, localTangent, localBinormal, transform, num); + this.AdjustMidpointHandleColor(localPos, localTangent, localBinormal, transform, num, isCameraInsideBox); int controlID = GUIUtility.GetControlID(this.m_ControlIdHint, FocusType.Keyboard); if (num > 0f) { Vector3 normalized = Vector3.Cross(localTangent, localBinormal).normalized; - localPos = Slider1D.Do(controlID, localPos, normalized, HandleUtility.GetHandleSize(localPos) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), SnapSettings.scale); + Handles.DrawCapFunction drawFunc = this.drawMethodForHandles ?? new Handles.DrawCapFunction(BoxEditor.DefaultMidPointDrawFunc); + Func func = this.getHandleSizeMethod ?? new Func(BoxEditor.DefaultMidpointGetSizeFunc); + localPos = Slider1D.Do(controlID, localPos, normalized, func(localPos), drawFunc, SnapSettings.scale); } Handles.color = color; return localPos; } - private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, float alphaFactor) + private void AdjustMidpointHandleColor(Vector3 localPos, Vector3 localTangent, Vector3 localBinormal, Matrix4x4 transform, float alphaFactor, bool isCameraInsideBox) { - Vector3 b = transform.MultiplyPoint(localPos); - Vector3 lhs = transform.MultiplyVector(localTangent); - Vector3 rhs = transform.MultiplyVector(localBinormal); - Vector3 normalized = Vector3.Cross(lhs, rhs).normalized; - float num; - if (Camera.current.isOrthoGraphic) - { - num = Vector3.Dot(-Camera.current.transform.forward, normalized); - } - else - { - num = Vector3.Dot((Camera.current.transform.position - b).normalized, normalized); - } - if (num < -0.0001f) + if (!isCameraInsideBox) { - alphaFactor *= Handles.backfaceAlphaMultiplier; + Vector3 b = transform.MultiplyPoint(localPos); + Vector3 lhs = transform.MultiplyVector(localTangent); + Vector3 rhs = transform.MultiplyVector(localBinormal); + Vector3 normalized = Vector3.Cross(lhs, rhs).normalized; + float num; + if (Camera.current.orthographic) + { + num = Vector3.Dot(-Camera.current.transform.forward, normalized); + } + else + { + num = Vector3.Dot((Camera.current.transform.position - b).normalized, normalized); + } + if (num < -0.0001f) + { + alphaFactor *= this.backfaceAlphaMultiplier; + } } if (alphaFactor < 1f) { @@ -259,7 +307,7 @@ private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 Vector3 normalized = transform.MultiplyVector(slideDir1).normalized; Vector3 normalized2 = transform.MultiplyVector(slideDir2).normalized; bool flag; - if (Camera.current.isOrthoGraphic) + if (Camera.current.orthographic) { flag = (Vector3.Dot(-Camera.current.transform.forward, normalized) < 0f && Vector3.Dot(-Camera.current.transform.forward, normalized2) < 0f); } @@ -271,7 +319,7 @@ private void AdjustEdgeHandleColor(Vector3 handlePos, Vector3 slideDir1, Vector3 } if (flag) { - alphaFactor *= Handles.backfaceAlphaMultiplier; + alphaFactor *= this.backfaceAlphaMultiplier; } if (alphaFactor < 1f) { diff --git a/UnityEditor/UnityEditor/Brush.cs b/UnityEditor/UnityEditor/Brush.cs index e45f981e..5f10ae18 100644 --- a/UnityEditor/UnityEditor/Brush.cs +++ b/UnityEditor/UnityEditor/Brush.cs @@ -74,8 +74,6 @@ public void Dispose() { if (this.m_BrushProjector) { - UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.material.shader); - UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.material); UnityEngine.Object.DestroyImmediate(this.m_BrushProjector.gameObject); this.m_BrushProjector = null; } @@ -99,9 +97,7 @@ private void CreatePreviewBrush() this.m_BrushProjector.orthographic = true; this.m_BrushProjector.orthographicSize = 10f; this.m_BrushProjector.transform.Rotate(90f, 0f, 0f); - Material material = new Material("Shader \"Hidden/Terrain Brush Preview\" {\nProperties {\n\t_MainTex (\"Main\", 2D) = \"gray\" { TexGen ObjectLinear }\n\t_CutoutTex (\"Cutout\", 2D) = \"black\" { TexGen ObjectLinear }\n}\nSubshader {\n\tZWrite Off\n\tOffset -1, -1\n\tFog { Mode Off }\n\tAlphaTest Greater 0\n\tColorMask RGB\n\tPass\n\t{\n\t\tBlend SrcAlpha OneMinusSrcAlpha\n\t\tSetTexture [_MainTex]\n\t\t{\n\t\t\tconstantColor (.2,.7,1,.5)\n\t\t\tcombine constant, texture * constant\n\t\t\tMatrix [_Projector]\n\t\t}\n\n\t\tSetTexture [_CutoutTex]\n\t\t{\n\t\t\tcombine previous, previous * texture\n\t\t\tMatrix [_Projector]\n\t\t}\n\t}\n}\n}"); - material.shader.hideFlags = HideFlags.HideAndDontSave; - material.hideFlags = HideFlags.HideAndDontSave; + Material material = EditorGUIUtility.LoadRequired("SceneView/TerrainBrushMaterial.mat") as Material; material.SetTexture("_CutoutTex", (Texture2D)EditorGUIUtility.Load(EditorResourcesUtility.brushesPath + "brush_cutout.png")); this.m_BrushProjector.material = material; this.m_BrushProjector.enabled = false; diff --git a/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs b/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs index 6b36bec3..4be75f67 100644 --- a/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs +++ b/UnityEditor/UnityEditor/BuildAssetBundleOptions.cs @@ -4,10 +4,14 @@ namespace UnityEditor [Flags] public enum BuildAssetBundleOptions { - CollectDependencies = 1048576, - CompleteAssets = 2097152, - DisableWriteTypeTree = 67108864, - DeterministicAssetBundle = 268435456, - UncompressedAssetBundle = 2048 + None = 0, + UncompressedAssetBundle = 1, + CollectDependencies = 2, + CompleteAssets = 4, + DisableWriteTypeTree = 8, + DeterministicAssetBundle = 16, + ForceRebuildAssetBundle = 32, + IgnoreTypeTreeChanges = 64, + AppendHashToAssetBundleName = 128 } } diff --git a/UnityEditor/UnityEditor/BuildOptions.cs b/UnityEditor/UnityEditor/BuildOptions.cs index 790c4c04..e323d684 100644 --- a/UnityEditor/UnityEditor/BuildOptions.cs +++ b/UnityEditor/UnityEditor/BuildOptions.cs @@ -21,6 +21,7 @@ public enum BuildOptions ConnectToHost = 4096, DeployOnline = 8192, EnableHeadlessMode = 16384, + BuildScriptsOnly = 32768, Il2CPP = 65536 } } diff --git a/UnityEditor/UnityEditor/BuildPipeline.cs b/UnityEditor/UnityEditor/BuildPipeline.cs index 2e6b534d..0c4c194d 100644 --- a/UnityEditor/UnityEditor/BuildPipeline.cs +++ b/UnityEditor/UnityEditor/BuildPipeline.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Runtime.CompilerServices; using UnityEditorInternal; using UnityEngine; @@ -18,16 +19,28 @@ public static extern bool isBuildingPlayer internal static extern BuildTargetGroup GetBuildTargetGroup(BuildTarget platform); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern BuildTargetGroup GetBuildTargetGroupByName(string platform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetBuildTargetGroupDisplayName(BuildTargetGroup targetPlatformGroup); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void PushAssetDependencies(); + internal static extern string GetBuildTargetName(BuildTarget targetPlatform); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetEditorTargetName(); + [Obsolete("PushAssetDependencies has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PushAssetDependencies(); + [Obsolete("PopAssetDependencies has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void PopAssetDependencies(); private static void LogBuildExceptionAndExit(string buildFunctionName, Exception exception) { - Debug.LogError(string.Format("Internal Error in {0}:", buildFunctionName)); + Debug.LogErrorFormat("Internal Error in {0}:", new object[] + { + buildFunctionName + }); Debug.LogException(exception); EditorApplication.Exit(1); } @@ -46,23 +59,18 @@ public static string BuildPlayer(string[] levels, string locationPathName, Build } return result; } - [ExcludeFromDocs] - public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target) - { - BuildOptions options = BuildOptions.None; - return BuildPipeline.BuildStreamedSceneAssetBundle(levels, locationPath, target, options); - } - public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, [DefaultValue("0")] BuildOptions options) + [Obsolete("BuildStreamedSceneAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, BuildOptions options) { return BuildPipeline.BuildPlayer(levels, locationPath, target, options | BuildOptions.BuildAdditionalStreamedScenes); } - [ExcludeFromDocs] - public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc) + [Obsolete("BuildStreamedSceneAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target) { - BuildOptions options = BuildOptions.None; - return BuildPipeline.BuildStreamedSceneAssetBundle(levels, locationPath, target, out crc, options); + return BuildPipeline.BuildPlayer(levels, locationPath, target, BuildOptions.BuildAdditionalStreamedScenes); } - public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc, [DefaultValue("0")] BuildOptions options) + [Obsolete("BuildStreamedSceneAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc, BuildOptions options) { crc = 0u; string result; @@ -77,10 +85,15 @@ public static string BuildStreamedSceneAssetBundle(string[] levels, string locat } return result; } + [Obsolete("BuildStreamedSceneAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static string BuildStreamedSceneAssetBundle(string[] levels, string locationPath, BuildTarget target, out uint crc) + { + return BuildPipeline.BuildStreamedSceneAssetBundle(levels, locationPath, target, out crc, BuildOptions.None); + } private static string BuildPlayerInternal(string[] levels, string locationPathName, BuildTarget target, BuildOptions options, out uint crc) { crc = 0u; - if (!InternalEditorUtility.HasPro()) + if (!InternalEditorUtility.HasProFeaturesEnabled()) { Debug.LogError("Building Player from editor scripts requires Unity PRO"); return "Building Player from editor scripts requires Unity PRO"; @@ -94,101 +107,186 @@ private static string BuildPlayerInternal(string[] levels, string locationPathNa [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string BuildPlayerInternalNoCheck(string[] levels, string locationPathName, BuildTarget target, BuildOptions options, bool delayToAfterScriptReload, out uint crc); - [ExcludeFromDocs] + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform) + { + uint num; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out num, assetBundleOptions, targetPlatform); + } + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, BuildAssetBundleOptions assetBundleOptions) { BuildTarget targetPlatform = BuildTarget.WebPlayer; return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, assetBundleOptions, targetPlatform); } - [ExcludeFromDocs] + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName) { - BuildTarget targetPlatform = BuildTarget.WebPlayer; BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; - return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, assetBundleOptions, targetPlatform); + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, assetBundleOptions); } - public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform) { - uint num; - return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out num, assetBundleOptions, targetPlatform); + crc = 0u; + bool result; + try + { + result = BuildPipeline.BuildAssetBundleInternal(mainAsset, assets, null, pathName, assetBundleOptions, targetPlatform, out crc); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundle", exception); + result = false; + } + return result; } - [ExcludeFromDocs] + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions) { BuildTarget targetPlatform = BuildTarget.WebPlayer; return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out crc, assetBundleOptions, targetPlatform); } - [ExcludeFromDocs] + [Obsolete("BuildAssetBundle has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc) + { + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out crc, assetBundleOptions); + } + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform) + { + uint num; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out num, assetBundleOptions, targetPlatform); + } + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions) { BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions, targetPlatform); + } + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName) + { BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; - return BuildPipeline.BuildAssetBundle(mainAsset, assets, pathName, out crc, assetBundleOptions, targetPlatform); + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions); } - public static bool BuildAssetBundle(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string pathName, out uint crc, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform) { crc = 0u; bool result; try { - result = BuildPipeline.BuildAssetBundleInternal(mainAsset, assets, null, pathName, assetBundleOptions, targetPlatform, out crc); + result = BuildPipeline.BuildAssetBundleInternal(null, assets, assetNames, pathName, assetBundleOptions, targetPlatform, out crc); } catch (Exception exception) { - BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundle", exception); + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundleExplicitAssetNames", exception); result = false; } return result; } + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions) + { + BuildTarget targetPlatform = BuildTarget.WebPlayer; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions, targetPlatform); + } + [Obsolete("BuildAssetBundleExplicitAssetNames has been made obsolete. Please use the new AssetBundle build system introduced in 5.0 and check BuildAssetBundles documentation for details.")] + public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc) + { + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; + return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions); + } + internal static bool DoesBuildTargetSupportIl2cpp(BuildTarget target) + { + return BuildPipeline.GetPlaybackEngineDirectory(target, BuildOptions.Il2CPP) != string.Empty; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool BuildAssetBundleInternal(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform, out uint crc); [ExcludeFromDocs] - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions) + public static AssetBundleManifest BuildAssetBundles(string outputPath, BuildAssetBundleOptions assetBundleOptions) { BuildTarget targetPlatform = BuildTarget.WebPlayer; - return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions, targetPlatform); + return BuildPipeline.BuildAssetBundles(outputPath, assetBundleOptions, targetPlatform); } [ExcludeFromDocs] - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName) + public static AssetBundleManifest BuildAssetBundles(string outputPath) { BuildTarget targetPlatform = BuildTarget.WebPlayer; - BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; - return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, assetBundleOptions, targetPlatform); + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.None; + return BuildPipeline.BuildAssetBundles(outputPath, assetBundleOptions, targetPlatform); } - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + public static AssetBundleManifest BuildAssetBundles(string outputPath, [DefaultValue("BuildAssetBundleOptions.None")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) { - uint num; - return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out num, assetBundleOptions, targetPlatform); + if (!Directory.Exists(outputPath)) + { + Debug.LogError("The output path \"" + outputPath + "\" doesn't exist"); + return null; + } + AssetBundleManifest result; + try + { + result = BuildPipeline.BuildAssetBundlesInternal(outputPath, assetBundleOptions, targetPlatform); + } + catch (Exception exception) + { + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundles", exception); + result = null; + } + return result; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AssetBundleManifest BuildAssetBundlesInternal(string outputPath, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform); [ExcludeFromDocs] - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, BuildAssetBundleOptions assetBundleOptions) + public static AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions) { BuildTarget targetPlatform = BuildTarget.WebPlayer; - return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions, targetPlatform); + return BuildPipeline.BuildAssetBundles(outputPath, builds, assetBundleOptions, targetPlatform); } [ExcludeFromDocs] - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc) + public static AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds) { BuildTarget targetPlatform = BuildTarget.WebPlayer; - BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; - return BuildPipeline.BuildAssetBundleExplicitAssetNames(assets, assetNames, pathName, out crc, assetBundleOptions, targetPlatform); + BuildAssetBundleOptions assetBundleOptions = BuildAssetBundleOptions.None; + return BuildPipeline.BuildAssetBundles(outputPath, builds, assetBundleOptions, targetPlatform); } - public static bool BuildAssetBundleExplicitAssetNames(UnityEngine.Object[] assets, string[] assetNames, string pathName, out uint crc, [DefaultValue("BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) + public static AssetBundleManifest BuildAssetBundles(string outputPath, AssetBundleBuild[] builds, [DefaultValue("BuildAssetBundleOptions.None")] BuildAssetBundleOptions assetBundleOptions, [DefaultValue("BuildTarget.WebPlayer")] BuildTarget targetPlatform) { - crc = 0u; - bool result; + if (!Directory.Exists(outputPath)) + { + Debug.LogError("The output path \"" + outputPath + "\" doesn't exist"); + return null; + } + if (builds == null) + { + Debug.LogError("AssetBundleBuild cannot be null."); + return null; + } + AssetBundleManifest result; try { - result = BuildPipeline.BuildAssetBundleInternal(null, assets, assetNames, pathName, assetBundleOptions, targetPlatform, out crc); + result = BuildPipeline.BuildAssetBundlesWithInfoInternal(outputPath, builds, assetBundleOptions, targetPlatform); } catch (Exception exception) { - BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundleExplicitAssetNames", exception); - result = false; + BuildPipeline.LogBuildExceptionAndExit("BuildPipeline.BuildAssetBundles", exception); + result = null; } return result; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool BuildAssetBundleInternal(UnityEngine.Object mainAsset, UnityEngine.Object[] assets, string[] assetNames, string pathName, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform, out uint crc); + private static extern AssetBundleManifest BuildAssetBundlesWithInfoInternal(string outputPath, AssetBundleBuild[] builds, BuildAssetBundleOptions assetBundleOptions, BuildTarget targetPlatform); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetCRCForAssetBundle(string targetPath, out uint crc); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetHashForAssetBundle(string targetPath, out Hash128 hash); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool LicenseCheck(BuildTarget target); diff --git a/UnityEditor/UnityEditor/BuildPlayerWindow.cs b/UnityEditor/UnityEditor/BuildPlayerWindow.cs index c48304b4..d971324b 100644 --- a/UnityEditor/UnityEditor/BuildPlayerWindow.cs +++ b/UnityEditor/UnityEditor/BuildPlayerWindow.cs @@ -25,6 +25,7 @@ public class BuildPlatform public Texture2D smallIcon; public BuildTargetGroup targetGroup; public bool forceShowTarget; + public string tooltip; public BuildTarget DefaultTarget { get @@ -35,8 +36,8 @@ public BuildTarget DefaultTarget return BuildTarget.StandaloneWindows; case BuildTargetGroup.WebPlayer: return BuildTarget.WebPlayer; - case BuildTargetGroup.iPhone: - return BuildTarget.iPhone; + case BuildTargetGroup.iOS: + return BuildTarget.iOS; case BuildTargetGroup.PS3: return BuildTarget.PS3; case BuildTargetGroup.XBOX360: @@ -45,15 +46,13 @@ public BuildTarget DefaultTarget return BuildTarget.Android; case BuildTargetGroup.GLESEmu: return BuildTarget.StandaloneGLESEmu; - case BuildTargetGroup.NaCl: - return BuildTarget.NaCl; - case BuildTargetGroup.FlashPlayer: - return BuildTarget.FlashPlayer; + case BuildTargetGroup.WebGL: + return BuildTarget.WebGL; case BuildTargetGroup.Metro: return BuildTarget.MetroPlayer; case BuildTargetGroup.WP8: return BuildTarget.WP8Player; - case BuildTargetGroup.BB10: + case BuildTargetGroup.BlackBerry: return BuildTarget.BB10; case BuildTargetGroup.Tizen: return BuildTarget.Tizen; @@ -61,8 +60,6 @@ public BuildTarget DefaultTarget return BuildTarget.PSP2; case BuildTargetGroup.PS4: return BuildTarget.PS4; - case BuildTargetGroup.PSM: - return BuildTarget.PSM; case BuildTargetGroup.XboxOne: return BuildTarget.XboxOne; case BuildTargetGroup.SamsungTV: @@ -71,12 +68,16 @@ public BuildTarget DefaultTarget return (BuildTarget)(-1); } } - public BuildPlatform(string locTitle, BuildTargetGroup targetGroup, bool forceShowTarget) + public BuildPlatform(string locTitle, BuildTargetGroup targetGroup, bool forceShowTarget) : this(locTitle, string.Empty, targetGroup, forceShowTarget) + { + } + public BuildPlatform(string locTitle, string tooltip, BuildTargetGroup targetGroup, bool forceShowTarget) { this.targetGroup = targetGroup; - this.name = BuildPipeline.GetBuildTargetGroupName(this.DefaultTarget); + this.name = ((targetGroup == BuildTargetGroup.Unknown) ? string.Empty : BuildPipeline.GetBuildTargetGroupName(this.DefaultTarget)); this.title = EditorGUIUtility.TextContent(locTitle); this.smallIcon = (EditorGUIUtility.IconContent(locTitle + ".Small").image as Texture2D); + this.tooltip = tooltip; this.forceShowTarget = forceShowTarget; } } @@ -85,195 +86,57 @@ private class BuildPlatforms public BuildPlayerWindow.BuildPlatform[] buildPlatforms; public BuildTarget[] standaloneSubtargets; public GUIContent[] standaloneSubtargetStrings; - public SCEBuildSubtarget[] sceSubtargets = new SCEBuildSubtarget[] - { - SCEBuildSubtarget.PCHosted, - SCEBuildSubtarget.HddTitle, - SCEBuildSubtarget.BluRayTitle - }; - public GUIContent[] sceSubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetPCHosted"), - EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetHddTitle"), - EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtargetBluRayTitle") - }; - public PSP2BuildSubtarget[] psp2Subtargets = new PSP2BuildSubtarget[] - { - PSP2BuildSubtarget.PCHosted, - PSP2BuildSubtarget.Package - }; - public GUIContent[] psp2SubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtargetPCHosted"), - EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtargetPackage") - }; - public FlashBuildSubtarget[] flashBuildSubtargets = new FlashBuildSubtarget[] - { - FlashBuildSubtarget.Flash11dot2, - FlashBuildSubtarget.Flash11dot3, - FlashBuildSubtarget.Flash11dot4, - FlashBuildSubtarget.Flash11dot5, - FlashBuildSubtarget.Flash11dot6, - FlashBuildSubtarget.Flash11dot7, - FlashBuildSubtarget.Flash11dot8 - }; - public GUIContent[] flashBuildSubtargetString = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot2"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot3"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot4"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot5"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot6"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot7"), - EditorGUIUtility.TextContent("BuildSettings.FlashSubtarget11dot8") - }; - public MetroBuildType[] metroBuildTypes = new MetroBuildType[] - { - MetroBuildType.VisualStudioCpp, - MetroBuildType.VisualStudioCSharp - }; - public GUIContent[] metroBuildTypeStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.MetroBuildTypeVisualStudioCpp"), - EditorGUIUtility.TextContent("BuildSettings.MetroBuildTypeVisualStudioCSharp") - }; - public MetroSDK[] metroSDKs = new MetroSDK[] - { - MetroSDK.SDK80, - MetroSDK.SDK81, - MetroSDK.PhoneSDK81, - MetroSDK.UniversalSDK81 - }; - public GUIContent[] metroSDKStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.MetroSDK80"), - EditorGUIUtility.TextContent("BuildSettings.MetroSDK81"), - EditorGUIUtility.TextContent("BuildSettings.MetroPhoneSDK81"), - EditorGUIUtility.TextContent("BuildSettings.MetroUniversalSDK81") - }; - public MetroBuildAndRunDeployTarget[] metroBuildAndRunDeployTargets = new MetroBuildAndRunDeployTarget[] - { - MetroBuildAndRunDeployTarget.LocalMachine, - MetroBuildAndRunDeployTarget.WindowsPhone, - MetroBuildAndRunDeployTarget.LocalMachineAndWindowsPhone - }; - public GUIContent[] metroBuildAndRunDeployTargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.DeployTargetLocalMachine"), - EditorGUIUtility.TextContent("BuildSettings.DeployTargetWindowsPhone"), - EditorGUIUtility.TextContent("BuildSettings.DeployTargetBoth") - }; - public XboxBuildSubtarget[] xboxBuildSubtargets = new XboxBuildSubtarget[] - { - XboxBuildSubtarget.Development, - XboxBuildSubtarget.Master, - XboxBuildSubtarget.Debug - }; - public GUIContent[] xboxBuildSubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetDevelopment"), - EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetMaster"), - EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtargetDebug") - }; - public XboxRunMethod[] xboxRunMethods = new XboxRunMethod[] - { - XboxRunMethod.HDD, - XboxRunMethod.DiscEmuFast, - XboxRunMethod.DiscEmuAccurate - }; - public GUIContent[] xboxRunMethodStrings = new GUIContent[] + public GUIContent[] webGLOptimizationLevels = new GUIContent[] { - EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodHDD"), - EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodDiscEmuFast"), - EditorGUIUtility.TextContent("BuildSettings.XboxRunMethodDiscEmuAccurate") - }; - public AndroidBuildSubtarget[] androidBuildSubtargets = new AndroidBuildSubtarget[] - { - AndroidBuildSubtarget.Generic, - AndroidBuildSubtarget.DXT, - AndroidBuildSubtarget.PVRTC, - AndroidBuildSubtarget.ATC, - AndroidBuildSubtarget.ETC, - AndroidBuildSubtarget.ETC2, - AndroidBuildSubtarget.ASTC - }; - public GUIContent[] androidBuildSubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetGeneric"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetDXT"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetPVRTC"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetATC"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetETC"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetETC2"), - EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtargetASTC") - }; - public BlackBerryBuildSubtarget[] blackberryBuildSubtargets = new BlackBerryBuildSubtarget[] - { - BlackBerryBuildSubtarget.Generic, - BlackBerryBuildSubtarget.PVRTC, - BlackBerryBuildSubtarget.ATC, - BlackBerryBuildSubtarget.ETC - }; - public GUIContent[] blackberryBuildSubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetGeneric"), - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetPVRTC"), - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetATC"), - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtargetETC") - }; - public BlackBerryBuildType[] blackberryBuildTypes = new BlackBerryBuildType[] - { - BlackBerryBuildType.Debug, - BlackBerryBuildType.Submission - }; - public GUIContent[] blackberryBuildTypeStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildTypeDebug"), - EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildTypeSubmission") - }; - public TizenBuildSubtarget[] tizenBuildSubtargets = new TizenBuildSubtarget[] - { - TizenBuildSubtarget.Generic, - TizenBuildSubtarget.ATC, - TizenBuildSubtarget.ETC - }; - public GUIContent[] tizenBuildSubtargetStrings = new GUIContent[] - { - EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetGeneric"), - EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetATC"), - EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtargetETC") + EditorGUIUtility.TextContent("BuildSettings.WebGLOptimizationLevel1"), + EditorGUIUtility.TextContent("BuildSettings.WebGLOptimizationLevel2"), + EditorGUIUtility.TextContent("BuildSettings.WebGLOptimizationLevel3") }; internal BuildPlatforms() { - this.buildPlatforms = new List - { - new BuildPlayerWindow.BuildPlatform("BuildSettings.Web", BuildTargetGroup.WebPlayer, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.Standalone", BuildTargetGroup.Standalone, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.iPhone", BuildTargetGroup.iPhone, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.Android", BuildTargetGroup.Android, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.BlackBerry", BuildTargetGroup.BB10, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.Tizen", BuildTargetGroup.Tizen, false), - new BuildPlayerWindow.BuildPlatform("BuildSettings.XBox360", BuildTargetGroup.XBOX360, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.XboxOne", BuildTargetGroup.XboxOne, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.PS3", BuildTargetGroup.PS3, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.PSP2", BuildTargetGroup.PSP2, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.PS4", BuildTargetGroup.PS4, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.PSM", BuildTargetGroup.PSM, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.StandaloneGLESEmu", BuildTargetGroup.GLESEmu, false), - new BuildPlayerWindow.BuildPlatform("BuildSettings.FlashPlayer", BuildTargetGroup.FlashPlayer, false), - new BuildPlayerWindow.BuildPlatform("BuildSettings.Metro", BuildTargetGroup.Metro, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.WP8", BuildTargetGroup.WP8, true), - new BuildPlayerWindow.BuildPlatform("BuildSettings.NaCl", BuildTargetGroup.NaCl, false), - new BuildPlayerWindow.BuildPlatform("BuildSettings.SamsungTV", BuildTargetGroup.SamsungTV, false) - }.ToArray(); + List list = new List(); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Web", BuildTargetGroup.WebPlayer, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Standalone", BuildTargetGroup.Standalone, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.iPhone", BuildTargetGroup.iOS, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Android", BuildTargetGroup.Android, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.BlackBerry", BuildTargetGroup.BlackBerry, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Tizen", BuildTargetGroup.Tizen, false)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.XBox360", BuildTargetGroup.XBOX360, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.XboxOne", BuildTargetGroup.XboxOne, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.PS3", BuildTargetGroup.PS3, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.PSP2", BuildTargetGroup.PSP2, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.PS4", BuildTargetGroup.PS4, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.StandaloneGLESEmu", BuildTargetGroup.GLESEmu, false)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Metro", BuildTargetGroup.Metro, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.WP8", BuildTargetGroup.WP8, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.WebGL", BuildTargetGroup.WebGL, true)); + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.SamsungTV", BuildTargetGroup.SamsungTV, false)); + foreach (BuildPlayerWindow.BuildPlatform current in list) + { + current.tooltip = BuildPipeline.GetBuildTargetGroupDisplayName(current.targetGroup) + " settings"; + } + this.buildPlatforms = list.ToArray(); + this.SetupStandaloneSubtargets(); + } + private void SetupStandaloneSubtargets() + { List list = new List(); - list.Add(BuildTarget.StandaloneWindows); - list.Add(BuildTarget.StandaloneOSXIntel); - list.Add(BuildTarget.StandaloneLinux); List list2 = new List(); - list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneWindows")); - list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneOSXIntel")); - list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneLinux")); + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneWindows))) + { + list.Add(BuildTarget.StandaloneWindows); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneWindows")); + } + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneOSXIntel))) + { + list.Add(BuildTarget.StandaloneOSXIntel); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneOSXIntel")); + } + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneLinux))) + { + list.Add(BuildTarget.StandaloneLinux); + list2.Add(EditorGUIUtility.TextContent("BuildSettings.StandaloneLinux")); + } this.standaloneSubtargets = list.ToArray(); this.standaloneSubtargetStrings = list2.ToArray(); } @@ -394,8 +257,8 @@ public static BuildTarget DefaultTargetForPlatform(BuildTarget target) case BuildTarget.StandaloneLinux64: case BuildTarget.StandaloneLinuxUniversal: return BuildTarget.StandaloneLinux; - case BuildTarget.FlashPlayer: - case (BuildTarget)20: + case (BuildTarget)18: + case BuildTarget.WebGL: case (BuildTarget)22: case (BuildTarget)23: IL_37: @@ -441,7 +304,7 @@ private class Styles public const float kButtonWidth = 110f; private const string kShopURL = "https://store.unity3d.com/shop/"; private const string kDownloadURL = "http://unity3d.com/unity/download/"; - private const string kMailURL = "mailto:sales@unity3d.com"; + private const string kMailURL = "http://unity3d.com/company/sales?type=sales"; public GUIStyle selected = "ServerUpdateChangesetOn"; public GUIStyle box = "OL Box"; public GUIStyle title = "OL title"; @@ -462,12 +325,6 @@ private class Styles public Texture2D activePlatformIcon = EditorGUIUtility.IconContent("BuildSettings.SelectedIcon").image as Texture2D; public GUIContent[,] notLicensedMessages; private GUIContent[,] buildTargetNotInstalled; - public GUIContent sceTarget; - public GUIContent psp2Target; - public GUIContent flashTarget; - public GUIContent metroBuildType; - public GUIContent metroSDK; - public GUIContent metroBuildAndRunDeployTarget; public GUIContent standaloneTarget; public GUIContent architecture; public GUIContent webPlayerStreamed; @@ -475,19 +332,14 @@ private class Styles public GUIContent debugBuild; public GUIContent profileBuild; public GUIContent allowDebugging; - public GUIContent createProject; public GUIContent symlinkiOSLibraries; - public GUIContent xboxBuildSubtarget; - public GUIContent xboxRunMethod; - public GUIContent androidBuildSubtarget; public GUIContent explicitNullChecks; public GUIContent enableHeadlessMode; - public GUIContent blackberryBuildSubtarget; - public GUIContent blackberryBuildType; - public GUIContent tizenBuildSubtarget; + public GUIContent webGLOptimizationLevel; + public GUIContent buildScriptsOnly; public Styles() { - GUIContent[,] expr_128 = new GUIContent[17, 3]; + GUIContent[,] expr_128 = new GUIContent[16, 3]; expr_128[0, 0] = EditorGUIUtility.TextContent("BuildSettings.NoWeb"); expr_128[0, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWebButton"); expr_128[0, 2] = new GUIContent("https://store.unity3d.com/shop/"); @@ -508,80 +360,69 @@ public Styles() expr_128[5, 2] = new GUIContent("https://store.unity3d.com/shop/"); expr_128[6, 0] = EditorGUIUtility.TextContent("BuildSettings.NoXBox360"); expr_128[6, 1] = EditorGUIUtility.TextContent("BuildSettings.NoXBox360Button"); - expr_128[6, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[6, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); expr_128[7, 0] = EditorGUIUtility.TextContent("BuildSettings.NoXboxOne"); expr_128[7, 1] = EditorGUIUtility.TextContent("BuildSettings.NoXboxOneButton"); - expr_128[7, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[7, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); expr_128[8, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPS3"); expr_128[8, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPS3Button"); - expr_128[8, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[8, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); expr_128[9, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPSP2"); expr_128[9, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPSP2Button"); - expr_128[9, 2] = new GUIContent("mailto:sales@unity3d.com"); + expr_128[9, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); expr_128[10, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPS4"); expr_128[10, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPS4Button"); - expr_128[10, 2] = new GUIContent("mailto:sales@unity3d.com"); - expr_128[11, 0] = EditorGUIUtility.TextContent("BuildSettings.NoPSM"); - expr_128[11, 1] = EditorGUIUtility.TextContent("BuildSettings.NoPSMButton"); - expr_128[11, 2] = new GUIContent("mailto:sales@unity3d.com"); - expr_128[12, 0] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmu"); - expr_128[12, 1] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmuButton"); - expr_128[12, 2] = new GUIContent("mailto:sales@unity3d.com"); - expr_128[13, 0] = EditorGUIUtility.TextContent("BuildSettings.NoFlash"); - expr_128[13, 1] = EditorGUIUtility.TextContent("BuildSettings.NoFlashButton"); + expr_128[10, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); + expr_128[11, 0] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmu"); + expr_128[11, 1] = EditorGUIUtility.TextContent("BuildSettings.NoGLESEmuButton"); + expr_128[11, 2] = new GUIContent("http://unity3d.com/company/sales?type=sales"); + expr_128[12, 0] = EditorGUIUtility.TextContent("BuildSettings.NoFlash"); + expr_128[12, 1] = EditorGUIUtility.TextContent("BuildSettings.NoFlashButton"); + expr_128[12, 2] = new GUIContent("https://store.unity3d.com/shop/"); + expr_128[13, 0] = EditorGUIUtility.TextContent("BuildSettings.NoMetro"); + expr_128[13, 1] = EditorGUIUtility.TextContent("BuildSettings.NoMetroButton"); expr_128[13, 2] = new GUIContent("https://store.unity3d.com/shop/"); - expr_128[14, 0] = EditorGUIUtility.TextContent("BuildSettings.NoMetro"); - expr_128[14, 1] = EditorGUIUtility.TextContent("BuildSettings.NoMetroButton"); + expr_128[14, 0] = EditorGUIUtility.TextContent("BuildSettings.NoWP8"); + expr_128[14, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWP8Button"); expr_128[14, 2] = new GUIContent("https://store.unity3d.com/shop/"); - expr_128[15, 0] = EditorGUIUtility.TextContent("BuildSettings.NoWP8"); - expr_128[15, 1] = EditorGUIUtility.TextContent("BuildSettings.NoWP8Button"); + expr_128[15, 0] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTV"); + expr_128[15, 1] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTVButton"); expr_128[15, 2] = new GUIContent("https://store.unity3d.com/shop/"); - expr_128[16, 0] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTV"); - expr_128[16, 1] = EditorGUIUtility.TextContent("BuildSettings.NoSamsungTVButton"); - expr_128[16, 2] = new GUIContent("https://store.unity3d.com/shop/"); this.notLicensedMessages = expr_128; - GUIContent[,] expr_4E4 = new GUIContent[17, 3]; - expr_4E4[0, 0] = EditorGUIUtility.TextContent("BuildSettings.WebNotInstalled"); - expr_4E4[0, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[1, 0] = EditorGUIUtility.TextContent("BuildSettings.StandaloneNotInstalled"); - expr_4E4[1, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[2, 0] = EditorGUIUtility.TextContent("BuildSettings.iPhoneNotInstalled"); - expr_4E4[2, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[3, 0] = EditorGUIUtility.TextContent("BuildSettings.AndroidNotInstalled"); - expr_4E4[3, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[4, 0] = EditorGUIUtility.TextContent("BuildSettings.BlackBerryNotInstalled"); - expr_4E4[4, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[5, 0] = EditorGUIUtility.TextContent("BuildSettings.TizenNotInstalled"); - expr_4E4[5, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[6, 0] = EditorGUIUtility.TextContent("BuildSettings.XBOX360NotInstalled"); - expr_4E4[6, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[7, 0] = EditorGUIUtility.TextContent("BuildSettings.XboxOneNotInstalled"); - expr_4E4[7, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[8, 0] = EditorGUIUtility.TextContent("BuildSettings.PS3NotInstalled"); - expr_4E4[8, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[9, 0] = EditorGUIUtility.TextContent("BuildSettings.PSP2NotInstalled"); - expr_4E4[9, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[10, 0] = EditorGUIUtility.TextContent("BuildSettings.PS4NotInstalled"); - expr_4E4[10, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[11, 0] = EditorGUIUtility.TextContent("BuildSettings.PSMNotInstalled"); - expr_4E4[11, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[12, 0] = EditorGUIUtility.TextContent("BuildSettings.GLESEmuNotInstalled"); - expr_4E4[12, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[13, 0] = EditorGUIUtility.TextContent("BuildSettings.FlashNotInstalled"); - expr_4E4[13, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[14, 0] = EditorGUIUtility.TextContent("BuildSettings.MetroNotInstalled"); - expr_4E4[14, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[15, 0] = EditorGUIUtility.TextContent("BuildSettings.WP8NotInstalled"); - expr_4E4[15, 2] = new GUIContent("http://unity3d.com/unity/download/"); - expr_4E4[16, 0] = EditorGUIUtility.TextContent("BuildSettings.SamsungTVNotInstalled"); - expr_4E4[16, 2] = new GUIContent("http://unity3d.com/unity/download/"); - this.buildTargetNotInstalled = expr_4E4; - this.sceTarget = EditorGUIUtility.TextContent("BuildSettings.SCEBuildSubtarget"); - this.psp2Target = EditorGUIUtility.TextContent("BuildSettings.PSP2BuildSubtarget"); - this.flashTarget = EditorGUIUtility.TextContent("BuildSettings.FlashBuildSubtarget"); - this.metroBuildType = EditorGUIUtility.TextContent("BuildSettings.MetroBuildType"); - this.metroSDK = EditorGUIUtility.TextContent("BuildSettings.MetroSDK"); - this.metroBuildAndRunDeployTarget = EditorGUIUtility.TextContent("BuildSettings.MetroBuildAndRunDeployTarget"); + GUIContent[,] expr_4AB = new GUIContent[16, 3]; + expr_4AB[0, 0] = EditorGUIUtility.TextContent("BuildSettings.WebNotInstalled"); + expr_4AB[0, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[1, 0] = EditorGUIUtility.TextContent("BuildSettings.StandaloneNotInstalled"); + expr_4AB[1, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[2, 0] = EditorGUIUtility.TextContent("BuildSettings.iPhoneNotInstalled"); + expr_4AB[2, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[3, 0] = EditorGUIUtility.TextContent("BuildSettings.AndroidNotInstalled"); + expr_4AB[3, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[4, 0] = EditorGUIUtility.TextContent("BuildSettings.BlackBerryNotInstalled"); + expr_4AB[4, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[5, 0] = EditorGUIUtility.TextContent("BuildSettings.TizenNotInstalled"); + expr_4AB[5, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[6, 0] = EditorGUIUtility.TextContent("BuildSettings.XBOX360NotInstalled"); + expr_4AB[6, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[7, 0] = EditorGUIUtility.TextContent("BuildSettings.XboxOneNotInstalled"); + expr_4AB[7, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[8, 0] = EditorGUIUtility.TextContent("BuildSettings.PS3NotInstalled"); + expr_4AB[8, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[9, 0] = EditorGUIUtility.TextContent("BuildSettings.PSP2NotInstalled"); + expr_4AB[9, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[10, 0] = EditorGUIUtility.TextContent("BuildSettings.PS4NotInstalled"); + expr_4AB[10, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[11, 0] = EditorGUIUtility.TextContent("BuildSettings.GLESEmuNotInstalled"); + expr_4AB[11, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[12, 0] = EditorGUIUtility.TextContent("BuildSettings.FlashNotInstalled"); + expr_4AB[12, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[13, 0] = EditorGUIUtility.TextContent("BuildSettings.MetroNotInstalled"); + expr_4AB[13, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[14, 0] = EditorGUIUtility.TextContent("BuildSettings.WP8NotInstalled"); + expr_4AB[14, 2] = new GUIContent("http://unity3d.com/unity/download/"); + expr_4AB[15, 0] = EditorGUIUtility.TextContent("BuildSettings.SamsungTVNotInstalled"); + expr_4AB[15, 2] = new GUIContent("http://unity3d.com/unity/download/"); + this.buildTargetNotInstalled = expr_4AB; this.standaloneTarget = EditorGUIUtility.TextContent("BuildSettings.StandaloneTarget"); this.architecture = EditorGUIUtility.TextContent("BuildSettings.Architecture"); this.webPlayerStreamed = EditorGUIUtility.TextContent("BuildSettings.WebPlayerStreamed"); @@ -589,16 +430,11 @@ public Styles() this.debugBuild = EditorGUIUtility.TextContent("BuildSettings.DebugBuild"); this.profileBuild = EditorGUIUtility.TextContent("BuildSettings.ConnectProfiler"); this.allowDebugging = EditorGUIUtility.TextContent("BuildSettings.AllowDebugging"); - this.createProject = EditorGUIUtility.TextContent("BuildSettings.ExportAndroidProject"); this.symlinkiOSLibraries = EditorGUIUtility.TextContent("BuildSettings.SymlinkiOSLibraries"); - this.xboxBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.XboxBuildSubtarget"); - this.xboxRunMethod = EditorGUIUtility.TextContent("BuildSettings.XboxRunMethod"); - this.androidBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.AndroidBuildSubtarget"); this.explicitNullChecks = EditorGUIUtility.TextContent("BuildSettings.ExplicitNullChecks"); this.enableHeadlessMode = EditorGUIUtility.TextContent("BuildSettings.EnableHeadlessMode"); - this.blackberryBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildSubtarget"); - this.blackberryBuildType = EditorGUIUtility.TextContent("BuildSettings.BlackBerryBuildType"); - this.tizenBuildSubtarget = EditorGUIUtility.TextContent("BuildSettings.TizenBuildSubtarget"); + this.webGLOptimizationLevel = EditorGUIUtility.TextContent("BuildSettings.WebGLOptimizationLevel"); + this.buildScriptsOnly = EditorGUIUtility.TextContent("BuildSettings.BuildScriptsOnly"); base..ctor(); this.levelStringCounter.alignment = TextAnchor.MiddleRight; } @@ -712,10 +548,31 @@ private static bool IsIl2cppBuild() } private static ScriptingImplementation GetDefaultNonIl2cppBackend() { - return ScriptingImplementation.Mono2x; + IScriptingImplementations scriptingImplementations = ModuleManager.GetScriptingImplementations(EditorUserBuildSettings.selectedBuildTargetGroup); + if (scriptingImplementations == null || scriptingImplementations.Enabled == null || scriptingImplementations.Enabled.Length == 0) + { + return ScriptingImplementation.Mono2x; + } + if (scriptingImplementations.Enabled.Length == 1) + { + return scriptingImplementations.Enabled[0]; + } + ScriptingImplementation result = ScriptingImplementation.Mono2x; + ScriptingImplementation[] enabled = scriptingImplementations.Enabled; + for (int i = 0; i < enabled.Length; i++) + { + ScriptingImplementation scriptingImplementation = enabled[i]; + if (scriptingImplementation != ScriptingImplementation.IL2CPP) + { + result = scriptingImplementation; + break; + } + } + return result; } private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, BuildOptions forceOptions, bool first) { + bool flag = false; if (first && EditorUserBuildSettings.webPlayerDeployOnline && !BuildPlayerWindow.EnsureLoggedInAndBuild(askForBuildLocation, forceOptions)) { return false; @@ -737,14 +594,56 @@ private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, Bui return false; } } - if (buildTarget == BuildTarget.BB10 && (forceOptions & BuildOptions.AutoRunPlayer) != BuildOptions.None && (string.IsNullOrEmpty(PlayerSettings.BlackBerry.authorId) || string.IsNullOrEmpty(PlayerSettings.BlackBerry.deviceAddress) || string.IsNullOrEmpty(PlayerSettings.BlackBerry.devicePassword))) + if (buildTarget == BuildTarget.BB10 && (forceOptions & BuildOptions.AutoRunPlayer) != BuildOptions.None && (string.IsNullOrEmpty(PlayerSettings.BlackBerry.deviceAddress) || string.IsNullOrEmpty(PlayerSettings.BlackBerry.devicePassword))) { Debug.LogError(EditorGUIUtility.TextContent("BuildSettings.BlackBerryValidationFailed").text); return false; } string text = string.Empty; - bool flag = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget) && (Unsupported.IsDeveloperBuild() || BuildPlayerWindow.IsMetroPlayer(buildTarget) || BuildPlayerWindow.IsWP8Player(buildTarget)); - if (!flag) + bool flag2 = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget) && (Unsupported.IsDeveloperBuild() || BuildPlayerWindow.IsMetroPlayer(buildTarget) || BuildPlayerWindow.IsWP8Player(buildTarget)); + BuildOptions buildOptions = forceOptions; + bool development = EditorUserBuildSettings.development; + if (development) + { + buildOptions |= BuildOptions.Development; + } + if (EditorUserBuildSettings.allowDebugging && development) + { + buildOptions |= BuildOptions.AllowDebugging; + } + if (EditorUserBuildSettings.symlinkLibraries) + { + buildOptions |= BuildOptions.SymlinkLibraries; + } + if (EditorUserBuildSettings.exportAsGoogleAndroidProject) + { + buildOptions |= BuildOptions.AcceptExternalModificationsToPlayer; + } + if (EditorUserBuildSettings.webPlayerDeployOnline) + { + buildOptions |= BuildOptions.DeployOnline; + } + if (EditorUserBuildSettings.webPlayerOfflineDeployment) + { + buildOptions |= BuildOptions.WebPlayerOfflineDeployment; + } + if (EditorUserBuildSettings.enableHeadlessMode) + { + buildOptions |= BuildOptions.EnableHeadlessMode; + } + if (EditorUserBuildSettings.connectProfiler && (development || buildTarget == BuildTarget.MetroPlayer || BuildPlayerWindow.IsWP8Player(buildTarget))) + { + buildOptions |= BuildOptions.ConnectWithProfiler; + } + if (EditorUserBuildSettings.buildScriptsOnly) + { + buildOptions |= BuildOptions.BuildScriptsOnly; + } + if (flag2) + { + buildOptions |= BuildOptions.InstallInBuildFolder; + } + if (!flag2) { if (EditorUserBuildSettings.selectedBuildTargetGroup == BuildTargetGroup.WebPlayer && EditorUserBuildSettings.webPlayerDeployOnline) { @@ -758,14 +657,17 @@ private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, Bui } if (!Directory.Exists(text)) { - Debug.LogError(string.Format("Failed to create temporary build directory at {0}", text)); + Debug.LogErrorFormat("Failed to create temporary build directory at {0}", new object[] + { + text + }); return false; } text = text.Replace('\\', '/'); } else { - if (askForBuildLocation && !BuildPlayerWindow.PickBuildLocation(buildTarget)) + if (askForBuildLocation && !BuildPlayerWindow.PickBuildLocation(buildTarget, buildOptions, out flag)) { return false; } @@ -780,10 +682,10 @@ private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, Bui switch (InternalEditorUtility.BuildCanBeAppended(buildTarget, text)) { case CanAppendBuild.Yes: - EditorUserBuildSettings.appendProject = true; + flag = true; break; case CanAppendBuild.No: - if (!BuildPlayerWindow.PickBuildLocation(buildTarget)) + if (!BuildPlayerWindow.PickBuildLocation(buildTarget, buildOptions, out flag)) { return false; } @@ -796,6 +698,10 @@ private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, Bui } } } + if (flag) + { + buildOptions |= BuildOptions.AcceptExternalModificationsToPlayer; + } ArrayList arrayList = new ArrayList(); EditorBuildSettingsScene[] scenes = EditorBuildSettings.scenes; EditorBuildSettingsScene[] array = scenes; @@ -808,50 +714,15 @@ private static bool BuildPlayerWithDefaultSettings(bool askForBuildLocation, Bui } } string[] levels = arrayList.ToArray(typeof(string)) as string[]; - BuildOptions buildOptions = forceOptions; - bool development = EditorUserBuildSettings.development; - if (development) - { - buildOptions |= BuildOptions.Development; - } - if (EditorUserBuildSettings.allowDebugging && development) - { - buildOptions |= BuildOptions.AllowDebugging; - } - if (EditorUserBuildSettings.symlinkLibraries) - { - buildOptions |= BuildOptions.SymlinkLibraries; - } - if (EditorUserBuildSettings.appendProject) - { - buildOptions |= BuildOptions.AcceptExternalModificationsToPlayer; - } - if (EditorUserBuildSettings.webPlayerDeployOnline) - { - buildOptions |= BuildOptions.DeployOnline; - } - if (EditorUserBuildSettings.webPlayerOfflineDeployment) - { - buildOptions |= BuildOptions.WebPlayerOfflineDeployment; - } - if (EditorUserBuildSettings.enableHeadlessMode) - { - buildOptions |= BuildOptions.EnableHeadlessMode; - } - if (EditorUserBuildSettings.connectProfiler && (development || buildTarget == BuildTarget.MetroPlayer || buildTarget == BuildTarget.WP8Player)) - { - buildOptions |= BuildOptions.ConnectWithProfiler; - } - if (flag) - { - buildOptions |= BuildOptions.InstallInBuildFolder; - } bool delayToAfterScriptReload = false; if (EditorUserBuildSettings.activeBuildTarget != buildTarget) { if (!EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget)) { - Debug.LogError(string.Format("Could not switch to build target '{0}'.", BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(buildTarget))); + Debug.LogErrorFormat("Could not switch to build target '{0}'.", new object[] + { + BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(buildTarget) + }); return false; } if (EditorApplication.isCompiling) @@ -1047,7 +918,7 @@ private void ActiveScenesGUI() i++; num3++; } - this.lv.row = -1; + this.lv.row = 0; current.Use(); } EditorBuildSettings.scenes = (arrayList.ToArray(typeof(EditorBuildSettingsScene)) as EditorBuildSettingsScene[]); @@ -1137,6 +1008,7 @@ private void ActiveBuildTargetsGUI() })) { EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget); + GUIUtility.ExitGUI(); } GUI.enabled = BuildPipeline.IsBuildTargetSupported(buildTarget); if (GUILayout.Button(new GUIContent("Player Settings..."), new GUILayoutOption[] @@ -1277,10 +1149,6 @@ internal static bool IsBuildTargetGroupSupported(BuildTarget target) { return target == BuildTarget.StandaloneWindows || BuildPipeline.IsBuildTargetSupported(target); } - internal static bool IsXboxBuildSubtargetDevelopment(XboxBuildSubtarget target) - { - return target != XboxBuildSubtarget.Master; - } private static void RepairSelectedBuildTargetGroup() { BuildTargetGroup selectedBuildTargetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; @@ -1289,18 +1157,53 @@ private static void RepairSelectedBuildTargetGroup() EditorUserBuildSettings.selectedBuildTargetGroup = BuildTargetGroup.WebPlayer; } } + private static bool IsAnyStandaloneModuleLoaded() + { + return ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneLinux)) || ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneOSXIntel)) || ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneWindows)); + } + private static BuildTarget GetBestStandaloneTarget(BuildTarget selectedTarget) + { + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(selectedTarget))) + { + return selectedTarget; + } + if (Application.platform == RuntimePlatform.WindowsEditor && ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneWindows))) + { + return BuildTarget.StandaloneWindows; + } + if (Application.platform == RuntimePlatform.OSXEditor && ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneOSXIntel))) + { + return BuildTarget.StandaloneOSXIntel; + } + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneOSXIntel))) + { + return BuildTarget.StandaloneOSXIntel; + } + if (ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(BuildTarget.StandaloneLinux))) + { + return BuildTarget.StandaloneLinux; + } + return BuildTarget.StandaloneWindows; + } private void ShowBuildTargetSettings() { EditorGUIUtility.labelWidth = Mathf.Min(180f, (base.position.width - 265f) * 0.47f); BuildTarget buildTarget = BuildPlayerWindow.CalculateSelectedBuildTarget(); BuildPlayerWindow.BuildPlatform buildPlatform = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformFromTargetGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + bool flag = BuildPipeline.LicenseCheck(buildTarget); GUILayout.Space(18f); Rect rect = GUILayoutUtility.GetRect(50f, 36f); rect.x += 1f; GUI.Label(new Rect(rect.x + 3f, rect.y + 3f, 32f, 32f), buildPlatform.title.image, GUIStyle.none); GUI.Toggle(rect, false, buildPlatform.title.text, BuildPlayerWindow.styles.platformSelector); GUILayout.Space(10f); - if (!string.IsNullOrEmpty(ModuleManager.GetTargetStringFromBuildTarget(buildTarget)) && ModuleManager.GetBuildPostProcessor(buildTarget) == null) + if (buildPlatform.targetGroup == BuildTargetGroup.WebGL && !BuildPipeline.IsBuildTargetSupported(buildTarget) && IntPtr.Size == 4) + { + GUILayout.Label("Building for WebGL requires a 64-bit Unity editor.", new GUILayoutOption[0]); + BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); + return; + } + if (flag && !string.IsNullOrEmpty(ModuleManager.GetTargetStringFromBuildTarget(buildTarget)) && ModuleManager.GetBuildPostProcessor(buildTarget) == null && (EditorUserBuildSettings.selectedBuildTargetGroup != BuildTargetGroup.Standalone || !BuildPlayerWindow.IsAnyStandaloneModuleLoaded())) { GUILayout.Label("No " + BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(buildTarget) + " module loaded.", new GUILayoutOption[0]); if (GUILayout.Button("Module Manager", EditorStyles.miniButton, new GUILayoutOption[] @@ -1320,7 +1223,7 @@ private void ShowBuildTargetSettings() BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); return; } - if (!BuildPipeline.LicenseCheck(buildTarget)) + if (!flag) { int num = BuildPlayerWindow.s_BuildPlatforms.BuildPlatformIndexFromTargetGroup(buildPlatform.targetGroup); GUILayout.Label(BuildPlayerWindow.styles.notLicensedMessages[num, 0], EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); @@ -1335,44 +1238,54 @@ private void ShowBuildTargetSettings() BuildPlayerWindow.GUIBuildButtons(false, false, false, buildPlatform); return; } + string targetStringFromBuildTargetGroup = ModuleManager.GetTargetStringFromBuildTargetGroup(buildPlatform.targetGroup); + IBuildWindowExtension buildWindowExtension = ModuleManager.GetBuildWindowExtension(targetStringFromBuildTargetGroup); + if (buildWindowExtension != null) + { + buildWindowExtension.ShowPlatformBuildOptions(); + } GUI.changed = false; - switch (buildPlatform.targetGroup) + BuildTargetGroup targetGroup = buildPlatform.targetGroup; + switch (targetGroup) { case BuildTargetGroup.Standalone: { - BuildTarget selectedStandaloneTarget = EditorUserBuildSettings.selectedStandaloneTarget; - int num2 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargets, BuildPlayerWindow.BuildPlatforms.DefaultTargetForPlatform(selectedStandaloneTarget))); + BuildTarget bestStandaloneTarget = BuildPlayerWindow.GetBestStandaloneTarget(EditorUserBuildSettings.selectedStandaloneTarget); + BuildTarget buildTarget2 = EditorUserBuildSettings.selectedStandaloneTarget; + int num2 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargets, BuildPlayerWindow.BuildPlatforms.DefaultTargetForPlatform(bestStandaloneTarget))); int num3 = EditorGUILayout.Popup(BuildPlayerWindow.styles.standaloneTarget, num2, BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargetStrings, new GUILayoutOption[0]); - Dictionary architecturesForPlatform = BuildPlayerWindow.BuildPlatforms.GetArchitecturesForPlatform(selectedStandaloneTarget); - BuildTarget buildTarget2; - if (num3 == num2 && architecturesForPlatform != null) + if (num3 == num2) { - GUIContent[] array = new List(architecturesForPlatform.Keys).ToArray(); - int num4 = 0; - if (num3 == num2) + Dictionary architecturesForPlatform = BuildPlayerWindow.BuildPlatforms.GetArchitecturesForPlatform(bestStandaloneTarget); + if (architecturesForPlatform != null) { - foreach (KeyValuePair current in architecturesForPlatform) + GUIContent[] array = new List(architecturesForPlatform.Keys).ToArray(); + int num4 = 0; + if (num3 == num2) { - if (current.Value == selectedStandaloneTarget) + foreach (KeyValuePair current in architecturesForPlatform) { - num4 = Math.Max(0, Array.IndexOf(array, current.Key)); - break; + if (current.Value == bestStandaloneTarget) + { + num4 = Math.Max(0, Array.IndexOf(array, current.Key)); + break; + } } } + num4 = EditorGUILayout.Popup(BuildPlayerWindow.styles.architecture, num4, array, new GUILayoutOption[0]); + buildTarget2 = architecturesForPlatform[array[num4]]; } - num4 = EditorGUILayout.Popup(BuildPlayerWindow.styles.architecture, num4, array, new GUILayoutOption[0]); - buildTarget2 = architecturesForPlatform[array[num4]]; } else { buildTarget2 = BuildPlayerWindow.s_BuildPlatforms.standaloneSubtargets[num3]; - if (BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget) == BuildTargetGroup.Standalone) - { - EditorUserBuildSettings.SwitchActiveBuildTarget(buildTarget2); - } } - EditorUserBuildSettings.selectedStandaloneTarget = buildTarget2; - break; + if (buildTarget2 != EditorUserBuildSettings.selectedStandaloneTarget) + { + EditorUserBuildSettings.selectedStandaloneTarget = buildTarget2; + GUIUtility.ExitGUI(); + } + goto IL_512; } case BuildTargetGroup.WebPlayer: { @@ -1390,182 +1303,48 @@ private void ShowBuildTargetSettings() } EditorUserBuildSettings.webPlayerOfflineDeployment = EditorGUILayout.Toggle(BuildPlayerWindow.styles.webPlayerOfflineDeployment, EditorUserBuildSettings.webPlayerOfflineDeployment, new GUILayoutOption[0]); GUI.enabled = enabled; - break; + goto IL_512; } - case BuildTargetGroup.iPhone: - if (Application.platform == RuntimePlatform.OSXEditor) - { - EditorUserBuildSettings.symlinkLibraries = EditorGUILayout.Toggle(BuildPlayerWindow.styles.symlinkiOSLibraries, EditorUserBuildSettings.symlinkLibraries, new GUILayoutOption[0]); - } - EditorUserBuildSettings.appendProject = false; - break; - case BuildTargetGroup.PS3: - { - int num5 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.sceSubtargets, EditorUserBuildSettings.sceBuildSubtarget); - if (num5 == -1) - { - num5 = 0; - } - num5 = EditorGUILayout.Popup(BuildPlayerWindow.styles.sceTarget, num5, BuildPlayerWindow.s_BuildPlatforms.sceSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.sceBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.sceSubtargets[num5]; - break; - } - case BuildTargetGroup.XBOX360: - { - int num6 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargets, EditorUserBuildSettings.xboxBuildSubtarget); - if (num6 == -1) + case (BuildTargetGroup)3: + IL_2E0: + if (targetGroup != BuildTargetGroup.WebGL) { - num6 = 0; + goto IL_512; } - num6 = EditorGUILayout.Popup(BuildPlayerWindow.styles.xboxBuildSubtarget, num6, BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.xboxBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.xboxBuildSubtargets[num6]; - num6 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.xboxRunMethods, EditorUserBuildSettings.xboxRunMethod); - if (num6 == -1) - { - num6 = 0; - } - num6 = EditorGUILayout.Popup(BuildPlayerWindow.styles.xboxRunMethod, num6, BuildPlayerWindow.s_BuildPlatforms.xboxRunMethodStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.xboxRunMethod = BuildPlayerWindow.s_BuildPlatforms.xboxRunMethods[num6]; - break; - } - case BuildTargetGroup.Android: - { - int num7 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargets, EditorUserBuildSettings.androidBuildSubtarget); - if (num7 == -1) - { - num7 = 0; - } - num7 = EditorGUILayout.Popup(BuildPlayerWindow.styles.androidBuildSubtarget, num7, BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.androidBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.androidBuildSubtargets[num7]; - bool flag = EditorUserBuildSettings.installInBuildFolder && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget); - bool arg_632_0 = EditorUserBuildSettings.appendProject; - bool flag2 = !flag; - GUI.enabled = flag2; - EditorUserBuildSettings.appendProject = (arg_632_0 & flag2); - EditorUserBuildSettings.appendProject = EditorGUILayout.Toggle(BuildPlayerWindow.styles.createProject, EditorUserBuildSettings.appendProject, new GUILayoutOption[0]); - GUI.enabled = true; - break; - } - case BuildTargetGroup.FlashPlayer: - { - int num8 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargets, EditorUserBuildSettings.flashBuildSubtarget); - if (num8 == -1) - { - num8 = 0; - } - num8 = EditorGUILayout.Popup(BuildPlayerWindow.styles.flashTarget, num8, BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargetString, new GUILayoutOption[0]); - EditorUserBuildSettings.flashBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.flashBuildSubtargets[num8]; - break; - } - case BuildTargetGroup.Metro: - { - int num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroBuildTypes, EditorUserBuildSettings.metroBuildType)); - num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroBuildType, num9, BuildPlayerWindow.s_BuildPlatforms.metroBuildTypeStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.metroBuildType = BuildPlayerWindow.s_BuildPlatforms.metroBuildTypes[num9]; - num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroSDKs, EditorUserBuildSettings.metroSDK)); - num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroSDK, num9, BuildPlayerWindow.s_BuildPlatforms.metroSDKStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.metroSDK = BuildPlayerWindow.s_BuildPlatforms.metroSDKs[num9]; - GUI.enabled = (EditorUserBuildSettings.metroSDK == MetroSDK.UniversalSDK81); - num9 = Math.Max(0, Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargets, EditorUserBuildSettings.metroBuildAndRunDeployTarget)); - num9 = EditorGUILayout.Popup(BuildPlayerWindow.styles.metroBuildAndRunDeployTarget, num9, BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.metroBuildAndRunDeployTarget = BuildPlayerWindow.s_BuildPlatforms.metroBuildAndRunDeployTargets[num9]; - GUI.enabled = true; - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("BuildSettings.MetroDebugging"), new GUILayoutOption[0]); - GUI.enabled = (EditorUserBuildSettings.metroBuildType == MetroBuildType.VisualStudioCSharp || EditorUserBuildSettings.metroBuildType == MetroBuildType.VisualStudioCSharpDX); - EditorUserBuildSettings.metroGenerateReferenceProjects = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("BuildSettings.MetroGenerateReferenceProjects"), EditorUserBuildSettings.metroGenerateReferenceProjects, new GUILayoutOption[0]); - GUI.enabled = true; - break; - } - case BuildTargetGroup.BB10: - { - int num10 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargets, EditorUserBuildSettings.blackberryBuildSubtarget); - if (num10 == -1) - { - num10 = 0; - } - num10 = EditorGUILayout.Popup(BuildPlayerWindow.styles.blackberryBuildSubtarget, num10, BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.blackberryBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.blackberryBuildSubtargets[num10]; - num10 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypes, EditorUserBuildSettings.blackberryBuildType); - if (num10 == -1) - { - num10 = 0; - } - num10 = EditorGUILayout.Popup(BuildPlayerWindow.styles.blackberryBuildType, num10, BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypeStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.blackberryBuildType = BuildPlayerWindow.s_BuildPlatforms.blackberryBuildTypes[num10]; - GUI.enabled = true; - break; - } - case BuildTargetGroup.Tizen: - { - int num11 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargets, EditorUserBuildSettings.tizenBuildSubtarget); - if (num11 == -1) - { - num11 = 0; - } - num11 = EditorGUILayout.Popup(BuildPlayerWindow.styles.tizenBuildSubtarget, num11, BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.tizenBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.tizenBuildSubtargets[num11]; - GUI.enabled = true; - break; - } - case BuildTargetGroup.PSP2: - { - int num12 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.psp2Subtargets, EditorUserBuildSettings.psp2BuildSubtarget); - if (num12 == -1) - { - num12 = 0; - } - num12 = EditorGUILayout.Popup(BuildPlayerWindow.styles.psp2Target, num12, BuildPlayerWindow.s_BuildPlatforms.psp2SubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.psp2BuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.psp2Subtargets[num12]; - break; - } - case BuildTargetGroup.PS4: - { - int num13 = Array.IndexOf(BuildPlayerWindow.s_BuildPlatforms.sceSubtargets, EditorUserBuildSettings.sceBuildSubtarget); - if (num13 == -1) + EditorUserBuildSettings.webGLOptimizationLevel = EditorGUILayout.Popup(BuildPlayerWindow.styles.webGLOptimizationLevel, EditorUserBuildSettings.webGLOptimizationLevel - 1, BuildPlayerWindow.s_BuildPlatforms.webGLOptimizationLevels, new GUILayoutOption[0]) + 1; + goto IL_512; + case BuildTargetGroup.iOS: + if (Application.platform == RuntimePlatform.OSXEditor) { - num13 = 0; + EditorUserBuildSettings.symlinkLibraries = EditorGUILayout.Toggle(BuildPlayerWindow.styles.symlinkiOSLibraries, EditorUserBuildSettings.symlinkLibraries, new GUILayoutOption[0]); } - num13 = EditorGUILayout.Popup(BuildPlayerWindow.styles.sceTarget, num13, BuildPlayerWindow.s_BuildPlatforms.sceSubtargetStrings, new GUILayoutOption[0]); - EditorUserBuildSettings.sceBuildSubtarget = BuildPlayerWindow.s_BuildPlatforms.sceSubtargets[num13]; - break; - } + goto IL_512; } + goto IL_2E0; + IL_512: GUI.enabled = true; - bool flag3 = true; + bool flag2 = buildWindowExtension == null || buildWindowExtension.EnabledBuildButton(); bool enableBuildAndRunButton = false; - bool flag4 = buildTarget != BuildTarget.PS3 && buildTarget != BuildTarget.PSP2 && buildTarget != BuildTarget.PS4 && buildTarget != BuildTarget.PSM && buildTarget != BuildTarget.FlashPlayer && buildTarget != BuildTarget.NaCl && !BuildPlayerWindow.IsMetroPlayer(buildTarget) && !BuildPlayerWindow.IsWP8Player(buildTarget); - bool flag5 = buildTarget == BuildTarget.XBOX360 || buildTarget == BuildTarget.PS3 || buildTarget == BuildTarget.PSP2 || buildTarget == BuildTarget.PS4 || buildTarget == BuildTarget.PSM; - bool flag6 = (buildTarget == BuildTarget.StandaloneLinux || buildTarget == BuildTarget.StandaloneLinux64 || buildTarget == BuildTarget.StandaloneLinuxUniversal) && Application.HasProLicense(); + bool flag3 = (buildWindowExtension == null) ? (buildTarget != BuildTarget.WebGL) : buildWindowExtension.ShouldDrawScriptDebuggingCheckbox(); + bool flag4 = buildWindowExtension != null && buildWindowExtension.ShouldDrawExplicitNullCheckbox(); + bool flag5 = buildWindowExtension == null || buildWindowExtension.ShouldDrawDevelopmentPlayerCheckbox(); + bool flag6 = (buildTarget == BuildTarget.StandaloneLinux || buildTarget == BuildTarget.StandaloneLinux64 || buildTarget == BuildTarget.StandaloneLinuxUniversal) && InternalEditorUtility.HasProFeaturesEnabled(); + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(buildTarget); + bool flag7 = buildPostProcessor != null && buildPostProcessor.SupportsScriptsOnlyBuild(); bool canInstallInBuildFolder = false; - if ((BuildPlayerWindow.IsMetroPlayer(buildTarget) || BuildPlayerWindow.IsWP8Player(buildTarget)) && !InternalEditorUtility.RunningUnderWindows8()) - { - flag3 = false; - GUILayout.Label(EditorGUIUtility.TextContent("BuildSettings.NoWindows8"), EditorStyles.wordWrappedLabel, new GUILayoutOption[0]); - } if (BuildPipeline.IsBuildTargetSupported(buildTarget)) { - bool flag7 = buildTarget == BuildTarget.PS3 && EditorUserBuildSettings.sceBuildSubtarget != SCEBuildSubtarget.PCHosted; - bool flag8 = buildTarget == BuildTarget.PS4 && EditorUserBuildSettings.sceBuildSubtarget != SCEBuildSubtarget.PCHosted; - bool flag9 = buildTarget == BuildTarget.PSP2 && EditorUserBuildSettings.psp2BuildSubtarget != PSP2BuildSubtarget.PCHosted; - bool flag10 = flag7 || flag8 || flag9; - bool flag11 = buildTarget == BuildTarget.PSP2 || BuildTarget.PS4 == buildTarget; - bool flag12 = buildTarget != BuildTarget.FlashPlayer && buildTarget != BuildTarget.NaCl && !BuildPlayerWindow.IsWP8Player(buildTarget); - bool flag13 = !flag10; - GUI.enabled = flag13; - BuildTargetGroup targetGroup = buildPlatform.targetGroup; - if (targetGroup != BuildTargetGroup.XBOX360) + bool flag8 = buildWindowExtension == null || buildWindowExtension.ShouldDrawProfilerCheckbox(); + GUI.enabled = flag5; + if (flag5) { EditorUserBuildSettings.development = EditorGUILayout.Toggle(BuildPlayerWindow.styles.debugBuild, EditorUserBuildSettings.development, new GUILayoutOption[0]); } - else - { - EditorUserBuildSettings.development = BuildPlayerWindow.IsXboxBuildSubtargetDevelopment(EditorUserBuildSettings.xboxBuildSubtarget); - } bool development = EditorUserBuildSettings.development; - GUI.enabled = (flag13 && development); + GUI.enabled = development; GUI.enabled = (GUI.enabled && InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(buildTarget)); GUI.enabled = (GUI.enabled && buildPlatform.targetGroup != BuildTargetGroup.WebPlayer); - if (flag12) + if (flag8) { if (!GUI.enabled) { @@ -1594,11 +1373,11 @@ private void ShowBuildTargetSettings() } EditorUserBuildSettings.connectProfiler = EditorGUILayout.Toggle(BuildPlayerWindow.styles.profileBuild, EditorUserBuildSettings.connectProfiler, new GUILayoutOption[0]); } - GUI.enabled = (flag13 && development); - if (flag4) + GUI.enabled = development; + if (flag3) { bool enabled2 = GUI.enabled; - GUI.enabled = (buildTarget != BuildTarget.iPhone || !BuildPlayerWindow.IsIl2cppBuild()); + GUI.enabled = (buildTarget != BuildTarget.iOS || !BuildPlayerWindow.IsIl2cppBuild()); BuildPlayerWindow.styles.allowDebugging.tooltip = string.Empty; if (!GUI.enabled) { @@ -1607,14 +1386,19 @@ private void ShowBuildTargetSettings() EditorUserBuildSettings.allowDebugging = EditorGUILayout.Toggle(BuildPlayerWindow.styles.allowDebugging, EditorUserBuildSettings.allowDebugging, new GUILayoutOption[0]); GUI.enabled = enabled2; } - if (flag5) + if (flag4) { - GUI.enabled = (!flag13 || !development); + GUI.enabled = !development; if (!GUI.enabled) { EditorUserBuildSettings.explicitNullChecks = true; } EditorUserBuildSettings.explicitNullChecks = EditorGUILayout.Toggle(BuildPlayerWindow.styles.explicitNullChecks, EditorUserBuildSettings.explicitNullChecks, new GUILayoutOption[0]); + GUI.enabled = development; + } + if (flag7) + { + EditorUserBuildSettings.buildScriptsOnly = EditorGUILayout.Toggle(BuildPlayerWindow.styles.buildScriptsOnly, EditorUserBuildSettings.buildScriptsOnly, new GUILayoutOption[0]); } GUI.enabled = !development; if (flag6) @@ -1623,10 +1407,10 @@ private void ShowBuildTargetSettings() } GUI.enabled = true; GUILayout.FlexibleSpace(); - canInstallInBuildFolder = (!flag10 && Unsupported.IsDeveloperBuild() && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget)); - if (flag3) + canInstallInBuildFolder = (Unsupported.IsDeveloperBuild() && PostprocessBuildPlayer.SupportsInstallInBuildFolder(buildTarget)); + if (flag2) { - enableBuildAndRunButton = ((!flag10 && !EditorUserBuildSettings.installInBuildFolder) || flag11); + enableBuildAndRunButton = ((buildWindowExtension == null) ? (!EditorUserBuildSettings.installInBuildFolder) : (buildWindowExtension.EnabledBuildAndRunButton() && !EditorUserBuildSettings.installInBuildFolder)); } } else @@ -1649,14 +1433,17 @@ private void ShowBuildTargetSettings() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } - BuildPlayerWindow.GUIBuildButtons(flag3, enableBuildAndRunButton, canInstallInBuildFolder, buildPlatform); + BuildPlayerWindow.GUIBuildButtons(flag2, enableBuildAndRunButton, canInstallInBuildFolder, buildPlatform); } private static void GUIBuildButtons(bool enableBuildButton, bool enableBuildAndRunButton, bool canInstallInBuildFolder, BuildPlayerWindow.BuildPlatform platform) { GUILayout.FlexibleSpace(); if (canInstallInBuildFolder) { - EditorUserBuildSettings.installInBuildFolder = GUILayout.Toggle(EditorUserBuildSettings.installInBuildFolder, "Install in Builds folder\n(for debugging with source code)", new GUILayoutOption[0]); + EditorUserBuildSettings.installInBuildFolder = GUILayout.Toggle(EditorUserBuildSettings.installInBuildFolder, "Install in Builds folder\n(for debugging with source code)", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); } else { @@ -1664,16 +1451,12 @@ private static void GUIBuildButtons(bool enableBuildButton, bool enableBuildAndR } GUILayout.BeginHorizontal(new GUILayoutOption[0]); GUILayout.FlexibleSpace(); - if (platform.targetGroup == BuildTargetGroup.Android && EditorUserBuildSettings.appendProject) - { - enableBuildAndRunButton = false; - } GUIContent content = BuildPlayerWindow.styles.build; - if (platform.targetGroup == BuildTargetGroup.Android && EditorUserBuildSettings.appendProject) + if (platform.targetGroup == BuildTargetGroup.Android && EditorUserBuildSettings.exportAsGoogleAndroidProject) { content = BuildPlayerWindow.styles.export; } - if (platform.targetGroup == BuildTargetGroup.iPhone && Application.platform != RuntimePlatform.OSXEditor) + if (platform.targetGroup == BuildTargetGroup.iOS && Application.platform != RuntimePlatform.OSXEditor) { enableBuildAndRunButton = false; } @@ -1697,21 +1480,22 @@ private static void GUIBuildButtons(bool enableBuildButton, bool enableBuildAndR } GUILayout.EndHorizontal(); } - private static bool PickBuildLocation(BuildTarget target) + private static bool PickBuildLocation(BuildTarget target, BuildOptions options, out bool updateExistingBuild) { + updateExistingBuild = false; string buildLocation = EditorUserBuildSettings.GetBuildLocation(target); - if (target == BuildTarget.Android && EditorUserBuildSettings.appendProject) + if (target == BuildTarget.Android && EditorUserBuildSettings.exportAsGoogleAndroidProject) { string title = "Export Google Android Project"; string location = EditorUtility.SaveFolderPanel(title, buildLocation, string.Empty); EditorUserBuildSettings.SetBuildLocation(target, location); return true; } - string extensionForBuildTarget = PostprocessBuildPlayer.GetExtensionForBuildTarget(target); + string extensionForBuildTarget = PostprocessBuildPlayer.GetExtensionForBuildTarget(target, options); string directory = FileUtil.DeleteLastPathNameComponent(buildLocation); string lastPathNameComponent = FileUtil.GetLastPathNameComponent(buildLocation); string title2 = "Build " + BuildPlayerWindow.s_BuildPlatforms.GetBuildTargetDisplayName(target); - string text = EditorUtility.SaveBuildPanel(target, title2, directory, lastPathNameComponent, extensionForBuildTarget); + string text = EditorUtility.SaveBuildPanel(target, title2, directory, lastPathNameComponent, extensionForBuildTarget, out updateExistingBuild); if (text == string.Empty) { return false; @@ -1730,7 +1514,7 @@ private static bool PickBuildLocation(BuildTarget target) { Directory.CreateDirectory(path); } - if (target == BuildTarget.iPhone && Application.platform != RuntimePlatform.OSXEditor && !BuildPlayerWindow.FolderIsEmpty(text) && !BuildPlayerWindow.UserWantsToDeleteFiles(text)) + if (target == BuildTarget.iOS && Application.platform != RuntimePlatform.OSXEditor && !BuildPlayerWindow.FolderIsEmpty(text) && !BuildPlayerWindow.UserWantsToDeleteFiles(text)) { return false; } @@ -1746,15 +1530,5 @@ private static bool UserWantsToDeleteFiles(string path) string message = "WARNING: all files and folders located in target folder: '" + path + "' will be deleted by build process."; return EditorUtility.DisplayDialog("Deleting existing files", message, "OK", "Cancel"); } - private static bool MetroAndWP8BuildRequirementsMet(out GUIContent msg) - { - if (!InternalEditorUtility.RunningUnderWindows8()) - { - msg = EditorGUIUtility.TextContent("BuildSettings.NoWindows8"); - return false; - } - msg = null; - return true; - } } } diff --git a/UnityEditor/UnityEditor/BuildTarget.cs b/UnityEditor/UnityEditor/BuildTarget.cs index 57642cec..6db70024 100644 --- a/UnityEditor/UnityEditor/BuildTarget.cs +++ b/UnityEditor/UnityEditor/BuildTarget.cs @@ -3,26 +3,27 @@ namespace UnityEditor { public enum BuildTarget { - WebPlayer = 6, - WebPlayerStreamed, - StandaloneOSXIntel = 4, - StandaloneOSXIntel64 = 27, StandaloneOSXUniversal = 2, - StandaloneWindows = 5, + StandaloneOSXIntel = 4, + StandaloneWindows, + WebPlayer, + WebPlayerStreamed, + iOS = 9, iPhone = 9, PS3, XBOX360, Android = 13, StandaloneGLESEmu, - NaCl = 16, - StandaloneLinux, + StandaloneLinux = 17, + StandaloneWindows64 = 19, + WebGL, + MetroPlayer, + WSAPlayer = 21, StandaloneLinux64 = 24, StandaloneLinuxUniversal, - FlashPlayer = 18, - StandaloneWindows64, - MetroPlayer = 21, - WP8Player = 26, - BB10 = 28, + WP8Player, + StandaloneOSXIntel64, + BB10, BlackBerry = 28, Tizen, PSP2, diff --git a/UnityEditor/UnityEditor/BuildTargetGroup.cs b/UnityEditor/UnityEditor/BuildTargetGroup.cs index e11d327e..21527aed 100644 --- a/UnityEditor/UnityEditor/BuildTargetGroup.cs +++ b/UnityEditor/UnityEditor/BuildTargetGroup.cs @@ -6,17 +6,17 @@ public enum BuildTargetGroup Unknown, Standalone, WebPlayer, + iOS = 4, iPhone = 4, PS3, XBOX360, Android, GLESEmu = 9, - NaCl = 11, - FlashPlayer, - Metro = 14, + WebGL = 13, + Metro, + WSA = 14, WP8, - BB10, - BlackBerry = 16, + BlackBerry, Tizen, PSP2, PS4, diff --git a/UnityEditor/UnityEditor/BuildVerifier.cs b/UnityEditor/UnityEditor/BuildVerifier.cs index a5858006..0b565b85 100644 --- a/UnityEditor/UnityEditor/BuildVerifier.cs +++ b/UnityEditor/UnityEditor/BuildVerifier.cs @@ -47,7 +47,11 @@ protected void VerifyBuildInternal(BuildTarget target, string managedDllFolder) string fileName = Path.GetFileName(text); if (!this.VerifyAssembly(target, fileName)) { - Debug.LogWarning(string.Format("{0} assembly is referenced by user code, but is not supported on {1} platform. Various failures might follow.", fileName, target.ToString())); + Debug.LogWarningFormat("{0} assembly is referenced by user code, but is not supported on {1} platform. Various failures might follow.", new object[] + { + fileName, + target.ToString() + }); } } } diff --git a/UnityEditor/UnityEditor/CacheServerPreferences.cs b/UnityEditor/UnityEditor/CacheServerPreferences.cs index b5dce192..8669cbff 100644 --- a/UnityEditor/UnityEditor/CacheServerPreferences.cs +++ b/UnityEditor/UnityEditor/CacheServerPreferences.cs @@ -29,11 +29,11 @@ public static void WritePreferences() public static void OnGUI() { GUILayout.Space(10f); - if (!InternalEditorUtility.HasMaint()) + if (!InternalEditorUtility.HasPro()) { - GUILayout.Label(EditorGUIUtility.TempContent("You need to have an Asset Server license to use the cache server.", EditorGUIUtility.GetHelpIcon(MessageType.Warning)), EditorStyles.helpBox, new GUILayoutOption[0]); + GUILayout.Label(EditorGUIUtility.TempContent("You need to have a Pro license to use the cache server.", EditorGUIUtility.GetHelpIcon(MessageType.Warning)), EditorStyles.helpBox, new GUILayoutOption[0]); } - EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasMaint()); + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasPro()); if (!CacheServerPreferences.s_PrefsLoaded) { CacheServerPreferences.ReadPreferences(); diff --git a/UnityEditor/UnityEditor/CameraEditor.cs b/UnityEditor/UnityEditor/CameraEditor.cs index 1fc69d3e..8c94502e 100644 --- a/UnityEditor/UnityEditor/CameraEditor.cs +++ b/UnityEditor/UnityEditor/CameraEditor.cs @@ -3,11 +3,17 @@ using UnityEditorInternal; using UnityEngine; using UnityEngine.Events; +using UnityEngine.Rendering; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(Camera))] internal class CameraEditor : Editor { + private class Styles + { + public static GUIContent iconRemove = EditorGUIUtility.IconContent("Toolbar Minus", "Remove command buffer"); + public static GUIStyle invisibleButton = "InvisibleButton"; + } private enum ProjectionType { Perspective, @@ -15,11 +21,25 @@ private enum ProjectionType } private const float kPreviewWindowOffset = 10f; private const float kPreviewNormalizedSize = 0.2f; + private static readonly GUIContent[] kCameraRenderPaths = new GUIContent[] + { + new GUIContent("Use Player Settings"), + new GUIContent("Forward"), + new GUIContent("Deferred"), + new GUIContent("Legacy Vertex Lit"), + new GUIContent("Legacy Deferred (light prepass)") + }; + private static readonly int[] kCameraRenderPathValues = new int[] + { + -1, + 1, + 3, + 0, + 2 + }; private SerializedProperty m_ClearFlags; private SerializedProperty m_BackgroundColor; private SerializedProperty m_NormalizedViewPortRect; - private SerializedProperty m_NearClip; - private SerializedProperty m_FarClip; private SerializedProperty m_FieldOfView; private SerializedProperty m_Orthographic; private SerializedProperty m_OrthographicSize; @@ -29,15 +49,37 @@ private enum ProjectionType private SerializedProperty m_OcclusionCulling; private SerializedProperty m_TargetTexture; private SerializedProperty m_HDR; - private AnimBool m_ShowBGColorOptions = new AnimBool(); - private AnimBool m_ShowOrthoOptions = new AnimBool(); - private AnimBool m_ShowDeferredWarning = new AnimBool(); + private SerializedProperty[] m_NearAndFarClippingPlanes; + private SerializedProperty m_TargetDisplay; + private static readonly GUIContent[] s_GameDisplays = new GUIContent[] + { + new GUIContent("Display 1"), + new GUIContent("Display 2"), + new GUIContent("Display 3"), + new GUIContent("Display 4"), + new GUIContent("Display 5"), + new GUIContent("Display 6"), + new GUIContent("Display 7"), + new GUIContent("Display 8") + }; + private static readonly int[] s_GameDisplayValues = new int[] + { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + }; + private readonly AnimBool m_ShowBGColorOptions = new AnimBool(); + private readonly AnimBool m_ShowOrthoOptions = new AnimBool(); + private readonly AnimBool m_ShowDeferredWarning = new AnimBool(); private Camera m_PreviewCamera; private static readonly Color kGizmoCamera = new Color(0.9137255f, 0.9137255f, 0.9137255f, 0.5019608f); - private GUIContent m_ClipingPlanesLabel = new GUIContent("Clipping Planes"); - private GUIContent m_NearClipPlaneLabel = new GUIContent("Near"); - private GUIContent m_FarClipPlaneLabel = new GUIContent("Far"); - private GUIContent m_ViewportLabel = new GUIContent("Viewport Rect"); + private readonly GUIContent m_ViewportLabel = new GUIContent("Viewport Rect"); + private bool m_CommandBuffersShown = true; private Camera camera { get @@ -49,7 +91,7 @@ private bool deferredWarningValue { get { - return !InternalEditorUtility.HasPro() && (this.camera.renderingPath == RenderingPath.DeferredLighting || (PlayerSettings.renderingPath == RenderingPath.DeferredLighting && this.camera.renderingPath == RenderingPath.UsePlayerSettings)); + return !InternalEditorUtility.HasProFeaturesEnabled() && (this.camera.renderingPath == RenderingPath.DeferredLighting || (PlayerSettings.renderingPath == RenderingPath.DeferredLighting && this.camera.renderingPath == RenderingPath.UsePlayerSettings)) && (this.camera.renderingPath == RenderingPath.DeferredShading || (PlayerSettings.renderingPath == RenderingPath.DeferredShading && this.camera.renderingPath == RenderingPath.UsePlayerSettings)); } } private Camera previewCamera @@ -60,7 +102,8 @@ private Camera previewCamera { this.m_PreviewCamera = EditorUtility.CreateGameObjectWithHideFlags("Preview Camera", HideFlags.HideAndDontSave, new Type[] { - typeof(Camera) + typeof(Camera), + typeof(Skybox) }).GetComponent(); } this.m_PreviewCamera.enabled = false; @@ -72,8 +115,11 @@ public void OnEnable() this.m_ClearFlags = base.serializedObject.FindProperty("m_ClearFlags"); this.m_BackgroundColor = base.serializedObject.FindProperty("m_BackGroundColor"); this.m_NormalizedViewPortRect = base.serializedObject.FindProperty("m_NormalizedViewPortRect"); - this.m_NearClip = base.serializedObject.FindProperty("near clip plane"); - this.m_FarClip = base.serializedObject.FindProperty("far clip plane"); + this.m_NearAndFarClippingPlanes = new SerializedProperty[] + { + base.serializedObject.FindProperty("near clip plane"), + base.serializedObject.FindProperty("far clip plane") + }; this.m_FieldOfView = base.serializedObject.FindProperty("field of view"); this.m_Orthographic = base.serializedObject.FindProperty("orthographic"); this.m_OrthographicSize = base.serializedObject.FindProperty("orthographic size"); @@ -83,6 +129,7 @@ public void OnEnable() this.m_OcclusionCulling = base.serializedObject.FindProperty("m_OcclusionCulling"); this.m_TargetTexture = base.serializedObject.FindProperty("m_TargetTexture"); this.m_HDR = base.serializedObject.FindProperty("m_HDR"); + this.m_TargetDisplay = base.serializedObject.FindProperty("m_TargetDisplay"); Camera camera = (Camera)this.target; this.m_ShowBGColorOptions.value = (!this.m_ClearFlags.hasMultipleDifferentValues && (camera.clearFlags == CameraClearFlags.Color || camera.clearFlags == CameraClearFlags.Skybox)); this.m_ShowOrthoOptions.value = camera.orthographic; @@ -91,12 +138,114 @@ public void OnEnable() this.m_ShowOrthoOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); this.m_ShowDeferredWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); } - private void OnDisable() + internal void OnDisable() { this.m_ShowBGColorOptions.valueChanged.RemoveListener(new UnityAction(base.Repaint)); this.m_ShowOrthoOptions.valueChanged.RemoveListener(new UnityAction(base.Repaint)); this.m_ShowDeferredWarning.valueChanged.RemoveListener(new UnityAction(base.Repaint)); } + private void DepthTextureModeGUI() + { + if (base.targets.Length != 1) + { + return; + } + Camera camera = this.target as Camera; + if (camera == null || camera.depthTextureMode == DepthTextureMode.None) + { + return; + } + bool flag = (camera.depthTextureMode & DepthTextureMode.Depth) != DepthTextureMode.None; + bool flag2 = (camera.depthTextureMode & DepthTextureMode.DepthNormals) != DepthTextureMode.None; + string text = null; + if (flag && flag2) + { + text = "Info: renders Depth & DepthNormals textures"; + } + else + { + if (flag) + { + text = "Info: renders Depth texture"; + } + else + { + if (flag2) + { + text = "Info: renders DepthNormals texture"; + } + } + } + if (text != null) + { + EditorGUILayout.HelpBox(text, MessageType.None, true); + } + } + private static Rect GetRemoveButtonRect(Rect r) + { + Vector2 vector = CameraEditor.Styles.invisibleButton.CalcSize(CameraEditor.Styles.iconRemove); + return new Rect(r.xMax - vector.x, r.y + (float)((int)(r.height / 2f - vector.y / 2f)), vector.x, vector.y); + } + private void CommandBufferGUI() + { + if (base.targets.Length != 1) + { + return; + } + Camera camera = this.target as Camera; + if (camera == null) + { + return; + } + int commandBufferCount = camera.commandBufferCount; + if (commandBufferCount == 0) + { + return; + } + this.m_CommandBuffersShown = GUILayout.Toggle(this.m_CommandBuffersShown, GUIContent.Temp(commandBufferCount + " command buffers"), EditorStyles.foldout, new GUILayoutOption[0]); + if (!this.m_CommandBuffersShown) + { + return; + } + EditorGUI.indentLevel++; + CameraEvent[] array = (CameraEvent[])Enum.GetValues(typeof(CameraEvent)); + for (int i = 0; i < array.Length; i++) + { + CameraEvent cameraEvent = array[i]; + CommandBuffer[] commandBuffers = camera.GetCommandBuffers(cameraEvent); + CommandBuffer[] array2 = commandBuffers; + for (int j = 0; j < array2.Length; j++) + { + CommandBuffer commandBuffer = array2[j]; + using (new GUILayout.HorizontalScope(new GUILayoutOption[0])) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel); + rect.xMin += EditorGUI.indent; + Rect removeButtonRect = CameraEditor.GetRemoveButtonRect(rect); + rect.xMax = removeButtonRect.x; + GUI.Label(rect, string.Format("{0}: {1} ({2})", cameraEvent, commandBuffer.name, EditorUtility.FormatBytes(commandBuffer.sizeInBytes)), EditorStyles.miniLabel); + if (GUI.Button(removeButtonRect, CameraEditor.Styles.iconRemove, CameraEditor.Styles.invisibleButton)) + { + camera.RemoveCommandBuffer(cameraEvent, commandBuffer); + SceneView.RepaintAll(); + GameView.RepaintAll(); + GUIUtility.ExitGUI(); + } + } + } + } + using (new GUILayout.HorizontalScope(new GUILayoutOption[0])) + { + GUILayout.FlexibleSpace(); + if (GUILayout.Button("Remove all", EditorStyles.miniButton, new GUILayoutOption[0])) + { + camera.RemoveAllCommandBuffers(); + SceneView.RepaintAll(); + GameView.RepaintAll(); + } + } + EditorGUI.indentLevel--; + } public override void OnInspectorGUI() { base.serializedObject.Update(); @@ -134,19 +283,11 @@ public override void OnInspectorGUI() } EditorGUILayout.EndFadeGroup(); } - Rect controlRect = EditorGUILayout.GetControlRect(true, 32f, new GUILayoutOption[0]); - controlRect.height = 16f; - GUI.Label(controlRect, this.m_ClipingPlanesLabel); - controlRect.xMin += EditorGUIUtility.labelWidth - 1f; - EditorGUIUtility.labelWidth = 32f; - EditorGUI.PropertyField(controlRect, this.m_NearClip, this.m_NearClipPlaneLabel); - controlRect.y += 16f; - EditorGUI.PropertyField(controlRect, this.m_FarClip, this.m_FarClipPlaneLabel); - EditorGUIUtility.labelWidth = 0f; + EditorGUILayout.PropertiesField(EditorGUI.s_ClipingPlanesLabel, this.m_NearAndFarClippingPlanes, EditorGUI.s_NearAndFarLabels, 35f, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_NormalizedViewPortRect, this.m_ViewportLabel, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUILayout.PropertyField(this.m_Depth, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_RenderingPath, new GUILayoutOption[0]); + EditorGUILayout.IntPopup(this.m_RenderingPath, CameraEditor.kCameraRenderPaths, CameraEditor.kCameraRenderPathValues, EditorGUIUtility.TempContent("Rendering Path"), new GUILayoutOption[0]); if (EditorGUILayout.BeginFadeGroup(this.m_ShowDeferredWarning.faded)) { GUIContent gUIContent = EditorGUIUtility.TextContent("CameraEditor.DeferredProOnly"); @@ -156,6 +297,12 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(this.m_TargetTexture, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_OcclusionCulling, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_HDR, new GUILayoutOption[0]); + if (Display.MultiDisplayLicense()) + { + EditorGUILayout.IntPopup(this.m_TargetDisplay, CameraEditor.s_GameDisplays, CameraEditor.s_GameDisplayValues, EditorGUIUtility.TempContent("Target Display"), new GUILayoutOption[0]); + } + this.DepthTextureModeGUI(); + this.CommandBufferGUI(); base.serializedObject.ApplyModifiedProperties(); } public void OnOverlayGUI(UnityEngine.Object target, SceneView sceneView) @@ -196,13 +343,27 @@ public void OnOverlayGUI(UnityEngine.Object target, SceneView sceneView) if (Event.current.type == EventType.Repaint) { this.previewCamera.CopyFrom(camera); + Skybox component = this.previewCamera.GetComponent(); + if (component) + { + Skybox component2 = camera.GetComponent(); + if (component2 && component2.enabled) + { + component.enabled = true; + component.material = component2.material; + } + else + { + component.enabled = false; + } + } this.previewCamera.targetTexture = null; this.previewCamera.pixelRect = rect2; Handles.EmitGUIGeometryForCamera(camera, this.previewCamera); this.previewCamera.Render(); } } - private static float GetGameViewAspectRatio(Camera fallbackCamera) + private static float GetGameViewAspectRatio() { Vector2 sizeOfMainGameView = GameView.GetSizeOfMainGameView(); if (sizeOfMainGameView.x < 0f) @@ -220,7 +381,7 @@ private static float GetFrustumAspectRatio(Camera camera) return -1f; } float num = rect.width / rect.height; - return CameraEditor.GetGameViewAspectRatio(camera) * num; + return CameraEditor.GetGameViewAspectRatio() * num; } private static bool GetFrustum(Camera camera, Vector3[] near, Vector3[] far, out float frustumAspect) { @@ -233,7 +394,7 @@ private static bool GetFrustum(Camera camera, Vector3[] near, Vector3[] far, out float num4; float num5; float num6; - if (!camera.isOrthoGraphic) + if (!camera.orthographic) { float num = Mathf.Tan(camera.fieldOfView * 0.0174532924f * 0.5f); float num2 = num * frustumAspect; @@ -276,7 +437,7 @@ private static bool GetFrustum(Camera camera, Vector3[] near, Vector3[] far, out } return true; } - private static void RenderGizmo(Camera camera) + internal static void RenderGizmo(Camera camera) { Vector3[] array = new Vector3[4]; Vector3[] array2 = new Vector3[4]; diff --git a/UnityEditor/UnityEditor/CanvasEditor.cs b/UnityEditor/UnityEditor/CanvasEditor.cs index d88871cf..2426585d 100644 --- a/UnityEditor/UnityEditor/CanvasEditor.cs +++ b/UnityEditor/UnityEditor/CanvasEditor.cs @@ -29,8 +29,8 @@ private enum PixelPerfect private GUIContent renderCamera = new GUIContent("Render Camera", "The Camera which will render the canvas. This is also the camera used to send events."); private GUIContent sortingOrder = new GUIContent("Sort Order", "The order in which Screen Space - Overlay canvas will render"); private static string s_RootAndNestedMessage = "Cannot multi-edit root Canvas together with nested Canvas."; - private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingLayer"); - private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingOrder"); + private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("Renderer.SortingLayer"); + private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("Renderer.SortingOrder"); private bool m_AllNested; private bool m_AllRoot; private bool m_AllOverlay; @@ -123,7 +123,7 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(this.m_Camera, this.renderCamera, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_PlaneDistance, new GUILayoutOption[0]); EditorGUILayout.Space(); - EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup, EditorStyles.label); EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); } EditorGUILayout.EndFadeGroup(); diff --git a/UnityEditor/UnityEditor/CapsuleColliderEditor.cs b/UnityEditor/UnityEditor/CapsuleColliderEditor.cs index 27559980..99534108 100644 --- a/UnityEditor/UnityEditor/CapsuleColliderEditor.cs +++ b/UnityEditor/UnityEditor/CapsuleColliderEditor.cs @@ -111,7 +111,7 @@ private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x num = Mathf.Cos(0.7853982f); } float num2; - if (Camera.current.isOrthoGraphic) + if (Camera.current.orthographic) { num2 = Vector3.Dot(-Camera.current.transform.forward, vector); } diff --git a/UnityEditor/UnityEditor/CharacterControllerEditor.cs b/UnityEditor/UnityEditor/CharacterControllerEditor.cs index a903b37b..47d125c0 100644 --- a/UnityEditor/UnityEditor/CharacterControllerEditor.cs +++ b/UnityEditor/UnityEditor/CharacterControllerEditor.cs @@ -121,7 +121,7 @@ private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x num = Mathf.Cos(0.7853982f); } float num2; - if (Camera.current.isOrthoGraphic) + if (Camera.current.orthographic) { num2 = Vector3.Dot(-Camera.current.transform.forward, vector); } diff --git a/UnityEditor/UnityEditor/CircleCollider2DEditor.cs b/UnityEditor/UnityEditor/CircleCollider2DEditor.cs index 42b3eeb5..dfd0d42d 100644 --- a/UnityEditor/UnityEditor/CircleCollider2DEditor.cs +++ b/UnityEditor/UnityEditor/CircleCollider2DEditor.cs @@ -6,25 +6,17 @@ namespace UnityEditor internal class CircleCollider2DEditor : Collider2DEditorBase { private int m_HandleControlID; - protected SerializedProperty m_Center; - protected SerializedProperty m_Radius; public override void OnEnable() { base.OnEnable(); this.m_HandleControlID = -1; - this.m_Center = base.serializedObject.FindProperty("m_Center"); - this.m_Radius = base.serializedObject.FindProperty("m_Radius"); } public override void OnInspectorGUI() { base.serializedObject.Update(); base.InspectorEditButtonGUI(); - EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + base.OnInspectorGUI(); base.serializedObject.ApplyModifiedProperties(); - base.CheckColliderErrorState(); } public void OnSceneGUI() { @@ -43,7 +35,7 @@ public void OnSceneGUI() float num2 = num * circleCollider2D.radius; num2 = Mathf.Abs(num2); num2 = Mathf.Max(num2, 1E-05f); - Vector3 position = circleCollider2D.transform.TransformPoint(circleCollider2D.center); + Vector3 position = circleCollider2D.transform.TransformPoint(circleCollider2D.offset); int hotControl = GUIUtility.hotControl; float num3 = Handles.RadiusHandle(Quaternion.identity, position, num2, true); if (GUI.changed) diff --git a/UnityEditor/UnityEditor/ClipAnimationInfoCurve.cs b/UnityEditor/UnityEditor/ClipAnimationInfoCurve.cs new file mode 100644 index 00000000..b13f051a --- /dev/null +++ b/UnityEditor/UnityEditor/ClipAnimationInfoCurve.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public struct ClipAnimationInfoCurve + { + public string name; + public AnimationCurve curve; + } +} diff --git a/UnityEditor/UnityEditor/ClothInspector.cs b/UnityEditor/UnityEditor/ClothInspector.cs index 574a3cba..61a2421d 100644 --- a/UnityEditor/UnityEditor/ClothInspector.cs +++ b/UnityEditor/UnityEditor/ClothInspector.cs @@ -1,65 +1,149 @@ using System; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { - [CustomEditor(typeof(SkinnedCloth))] + [CanEditMultipleObjects, CustomEditor(typeof(Cloth))] internal class ClothInspector : Editor { + public enum DrawMode + { + MaxDistance = 1, + CollisionSphereDistance + } + public enum ToolMode + { + Select, + Paint + } private enum RectSelectionMode { Replace, Add, Substract } - private enum ToolMode - { - Select, - Paint, - Settings - } - private const int clothToolID = 1200; + private const float kDisabledValue = 3.40282347E+38f; private bool[] m_Selection; private bool[] m_RectSelection; private int m_MouseOver = -1; - private int m_DrawMode = 1; private int m_MeshVerticesPerSelectionVertex; - private Mesh m_SelectionMesh; + private Mesh[] m_SelectionMesh; + private Mesh[] m_SelectedMesh; private Mesh m_VertexMesh; + private Mesh m_VertexMeshSelected; private Vector3[] m_LastVertices; private Vector2 m_SelectStartPoint; private Vector2 m_SelectMousePoint; private bool m_RectSelecting; private bool m_DidSelect; - private bool m_PaintMaxDistanceEnabled; - private bool m_PaintMaxDistanceBiasEnabled; - private bool m_PaintCollisionSphereRadiusEnabled; - private bool m_PaintCollisionSphereDistanceEnabled; - private float m_PaintMaxDistance = 0.2f; - private float m_PaintMaxDistanceBias; - private float m_PaintCollisionSphereRadius = 0.5f; - private float m_PaintCollisionSphereDistance; - private static Material s_SelectionMaterial = null; + private float[] m_MaxVisualizedValue = new float[3]; + private float[] m_MinVisualizedValue = new float[3]; private ClothInspector.RectSelectionMode m_RectSelectionMode = ClothInspector.RectSelectionMode.Add; - private static ClothInspector.ToolMode s_ToolMode = ClothInspector.ToolMode.Settings; - private static int maxVertices; + private static Color s_SelectionColor; + private static Material s_SelectionMaterial = null; + private static Material s_SelectionMaterialBackfaces = null; + private static Material s_SelectedMaterial = null; + private static Texture2D s_ColorTexture = null; + private static int s_MaxVertices; private static GUIContent[] s_ToolIcons = new GUIContent[] { - EditorGUIUtility.IconContent("ClothInspector.SelectTool", "Select vertices and edit their cloth coefficients in the inspector."), - EditorGUIUtility.IconContent("ClothInspector.PaintTool", "Paint cloth coefficients on to vertices."), - EditorGUIUtility.IconContent("ClothInspector.SettingsTool", "Set cloth options.") + EditorGUIUtility.TextContent("ClothInspector.SelectTool"), + EditorGUIUtility.TextContent("ClothInspector.PaintTool") + }; + private static GUIContent[] s_ModeStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("Fixed"), + EditorGUIUtility.TextContent("Max Distance"), + EditorGUIUtility.TextContent("Surface Penetration") }; - private static GUIContent s_ViewIcon = EditorGUIUtility.IconContent("ClothInspector.ViewValue", "Visualize this vertex coefficient value in the scene view."); private static GUIContent s_PaintIcon = EditorGUIUtility.IconContent("ClothInspector.PaintValue", "Change this vertex coefficient value by painting in the scene view."); + private ClothInspectorState state + { + get + { + return ScriptableSingleton.instance; + } + } + private ClothInspector.DrawMode drawMode + { + get + { + return this.state.DrawMode; + } + set + { + if (this.state.DrawMode != value) + { + this.state.DrawMode = value; + this.SetupSelectionMeshColors(); + base.Repaint(); + } + } + } + private Cloth cloth + { + get + { + return (Cloth)this.target; + } + } + public bool editing + { + get + { + return EditMode.editMode == EditMode.SceneViewEditMode.Cloth && EditMode.IsOwner(this); + } + } + private GUIContent GetModeString(ClothInspector.DrawMode mode) + { + return ClothInspector.s_ModeStrings[(int)mode]; + } + private Texture2D GenerateColorTexture(int width) + { + Texture2D texture2D = new Texture2D(width, 1, TextureFormat.ARGB32, false); + texture2D.hideFlags = HideFlags.HideAndDontSave; + texture2D.wrapMode = TextureWrapMode.Clamp; + texture2D.hideFlags = HideFlags.DontSave; + Color[] array = new Color[width]; + for (int i = 0; i < width; i++) + { + array[i] = this.GetGradientColor((float)i / (float)(width - 1)); + } + texture2D.SetPixels(array); + texture2D.Apply(); + return texture2D; + } + public override void OnInspectorGUI() + { + EditMode.DoEditModeInspectorModeButton(EditMode.SceneViewEditMode.Cloth, "Edit Constraints", EditorGUIUtility.IconContent("EditCollider"), this.GetClothBounds(), this); + base.OnInspectorGUI(); + } + private Bounds GetClothBounds() + { + if (this.target is Cloth) + { + Cloth cloth = (Cloth)this.target; + SkinnedMeshRenderer component = cloth.GetComponent(); + if (component != null) + { + return component.bounds; + } + } + return default(Bounds); + } private bool SelectionMeshDirty() { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - SkinnedMeshRenderer component = skinnedCloth.GetComponent(); - Vector3[] vertices = skinnedCloth.vertices; - Quaternion rotation = component.actualRootBone.rotation; - Vector3 position = component.actualRootBone.position; + SkinnedMeshRenderer component = this.cloth.GetComponent(); + Vector3[] vertices = this.cloth.vertices; + Transform actualRootBone = component.actualRootBone; + if (this.m_LastVertices.Length != vertices.Length) + { + return true; + } for (int i = 0; i < this.m_LastVertices.Length; i++) { - if (this.m_LastVertices[i] != rotation * vertices[i] + position) + Vector3 rhs = actualRootBone.rotation * vertices[i] + actualRootBone.position; + if (!(this.m_LastVertices[i] == rhs)) { return true; } @@ -68,343 +152,524 @@ private bool SelectionMeshDirty() } private void GenerateSelectionMesh() { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - SkinnedMeshRenderer component = skinnedCloth.GetComponent(); - Vector3[] vertices = skinnedCloth.vertices; + SkinnedMeshRenderer component = this.cloth.GetComponent(); + Vector3[] vertices = this.cloth.vertices; + int num = vertices.Length; + this.m_Selection = new bool[vertices.Length]; + this.m_RectSelection = new bool[vertices.Length]; if (this.m_SelectionMesh != null) { - UnityEngine.Object.DestroyImmediate(this.m_SelectionMesh); + Mesh[] selectionMesh = this.m_SelectionMesh; + for (int i = 0; i < selectionMesh.Length; i++) + { + Mesh obj = selectionMesh[i]; + UnityEngine.Object.DestroyImmediate(obj); + } + Mesh[] selectedMesh = this.m_SelectedMesh; + for (int j = 0; j < selectedMesh.Length; j++) + { + Mesh obj2 = selectedMesh[j]; + UnityEngine.Object.DestroyImmediate(obj2); + } } - this.m_SelectionMesh = new Mesh(); - this.m_SelectionMesh.hideFlags |= HideFlags.DontSave; - CombineInstance[] array = new CombineInstance[vertices.Length]; + int num2 = num / ClothInspector.s_MaxVertices + 1; + this.m_SelectionMesh = new Mesh[num2]; + this.m_SelectedMesh = new Mesh[num2]; + this.m_LastVertices = new Vector3[num]; this.m_MeshVerticesPerSelectionVertex = this.m_VertexMesh.vertices.Length; - this.m_LastVertices = new Vector3[vertices.Length]; - Quaternion rotation = component.actualRootBone.rotation; - Vector3 position = component.actualRootBone.position; - int num = 0; - while (num < vertices.Length && num < ClothInspector.maxVertices) + Transform actualRootBone = component.actualRootBone; + for (int k = 0; k < num2; k++) { - this.m_LastVertices[num] = rotation * vertices[num] + position; - array[num].mesh = this.m_VertexMesh; - array[num].transform = Matrix4x4.TRS(this.m_LastVertices[num], Quaternion.identity, 0.015f * Vector3.one); - num++; + this.m_SelectionMesh[k] = new Mesh(); + this.m_SelectionMesh[k].hideFlags |= HideFlags.DontSave; + this.m_SelectedMesh[k] = new Mesh(); + this.m_SelectedMesh[k].hideFlags |= HideFlags.DontSave; + int num3 = num - k * ClothInspector.s_MaxVertices; + if (num3 > ClothInspector.s_MaxVertices) + { + num3 = ClothInspector.s_MaxVertices; + } + CombineInstance[] array = new CombineInstance[num3]; + int num4 = k * ClothInspector.s_MaxVertices; + for (int l = 0; l < num3; l++) + { + this.m_LastVertices[num4 + l] = actualRootBone.rotation * vertices[num4 + l] + actualRootBone.position; + array[l].mesh = this.m_VertexMesh; + array[l].transform = Matrix4x4.TRS(this.m_LastVertices[num4 + l], Quaternion.identity, Vector3.one); + } + this.m_SelectionMesh[k].CombineMeshes(array); + for (int m = 0; m < num3; m++) + { + array[m].mesh = this.m_VertexMeshSelected; + } + this.m_SelectedMesh[k].CombineMeshes(array); } - this.m_SelectionMesh.CombineMeshes(array); - this.SetupMeshColors(); + this.SetupSelectionMeshColors(); } private void OnEnable() { if (ClothInspector.s_SelectionMaterial == null) { ClothInspector.s_SelectionMaterial = (EditorGUIUtility.LoadRequired("SceneView/VertexSelectionMaterial.mat") as Material); + ClothInspector.s_SelectionMaterialBackfaces = (EditorGUIUtility.LoadRequired("SceneView/VertexSelectionBackfacesMaterial.mat") as Material); + ClothInspector.s_SelectedMaterial = (EditorGUIUtility.LoadRequired("SceneView/VertexSelectedMaterial.mat") as Material); } - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; - this.m_Selection = new bool[coefficients.Length]; - this.m_RectSelection = new bool[coefficients.Length]; - this.m_VertexMesh = (Mesh)Resources.GetBuiltinResource(typeof(Mesh), "Cube.fbx"); - ClothInspector.maxVertices = 65536 / this.m_VertexMesh.vertices.Length; - if (skinnedCloth.vertices.Length >= ClothInspector.maxVertices) + if (ClothInspector.s_ColorTexture == null) { - Debug.LogWarning("The mesh has too many vertices to be able to edit all skin coefficients. Only the first " + ClothInspector.maxVertices + " vertices will be displayed"); + ClothInspector.s_ColorTexture = this.GenerateColorTexture(100); } + this.m_VertexMesh = new Mesh(); + this.m_VertexMesh.hideFlags |= HideFlags.DontSave; + Mesh mesh = (Mesh)Resources.GetBuiltinResource(typeof(Mesh), "Cube.fbx"); + this.m_VertexMesh.vertices = new Vector3[mesh.vertices.Length]; + this.m_VertexMesh.normals = mesh.normals; + Vector4[] array = new Vector4[mesh.vertices.Length]; + Vector3[] vertices = mesh.vertices; + for (int i = 0; i < mesh.vertices.Length; i++) + { + array[i] = vertices[i] * -0.01f; + } + this.m_VertexMesh.tangents = array; + this.m_VertexMesh.triangles = mesh.triangles; + this.m_VertexMeshSelected = new Mesh(); + this.m_VertexMeshSelected.hideFlags |= HideFlags.DontSave; + this.m_VertexMeshSelected.vertices = this.m_VertexMesh.vertices; + this.m_VertexMeshSelected.normals = this.m_VertexMesh.normals; + for (int j = 0; j < mesh.vertices.Length; j++) + { + array[j] = vertices[j] * -0.02f; + } + this.m_VertexMeshSelected.tangents = array; + this.m_VertexMeshSelected.triangles = this.m_VertexMesh.triangles; + ClothInspector.s_MaxVertices = 65536 / this.m_VertexMesh.vertices.Length; this.GenerateSelectionMesh(); + this.SetupSelectedMeshColors(); } private float GetCoefficient(ClothSkinningCoefficient coefficient) { - switch (this.m_DrawMode) + ClothInspector.DrawMode drawMode = this.drawMode; + if (drawMode == ClothInspector.DrawMode.MaxDistance) { - case 1: return coefficient.maxDistance; - case 2: - return coefficient.maxDistanceBias; - case 3: - return coefficient.collisionSphereRadius; - case 4: - return coefficient.collisionSphereDistance; - default: + } + if (drawMode != ClothInspector.DrawMode.CollisionSphereDistance) + { return 0f; } + return coefficient.collisionSphereDistance; } - private void SetupMeshColors() + private Color GetGradientColor(float val) { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; - Color[] array = new Color[this.m_SelectionMesh.vertices.Length]; - float num = 0f; + if (val < 0.3f) + { + return Color.Lerp(Color.red, Color.magenta, val / 0.2f); + } + if (val < 0.7f) + { + return Color.Lerp(Color.magenta, Color.yellow, (val - 0.2f) / 0.5f); + } + return Color.Lerp(Color.yellow, Color.green, (val - 0.7f) / 0.3f); + } + private void AssignColorsToMeshArray(Color[] colors, Mesh[] meshArray) + { + int num = colors.Length / this.m_MeshVerticesPerSelectionVertex; + int num2 = num / ClothInspector.s_MaxVertices + 1; + for (int i = 0; i < num2; i++) + { + int num3 = num - i * ClothInspector.s_MaxVertices; + if (num3 > ClothInspector.s_MaxVertices) + { + num3 = ClothInspector.s_MaxVertices; + } + Color[] array = new Color[num3 * this.m_MeshVerticesPerSelectionVertex]; + Array.Copy(colors, i * ClothInspector.s_MaxVertices * this.m_MeshVerticesPerSelectionVertex, array, 0, num3 * this.m_MeshVerticesPerSelectionVertex); + meshArray[i].colors = array; + } + } + private void SetupSelectionMeshColors() + { + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; + int num = coefficients.Length; + Color[] array = new Color[num * this.m_MeshVerticesPerSelectionVertex]; float num2 = 0f; + float num3 = 0f; for (int i = 0; i < coefficients.Length; i++) { float coefficient = this.GetCoefficient(coefficients[i]); - if (coefficient < num) - { - num = coefficient; - } - if (coefficient > num2) + if (coefficient < 3.40282347E+38f) { - num2 = coefficient; + if (coefficient < num2) + { + num2 = coefficient; + } + if (coefficient > num3) + { + num3 = coefficient; + } } } - int num3 = 0; - while (num3 < coefficients.Length && num3 < ClothInspector.maxVertices) + for (int j = 0; j < num; j++) { - for (int j = 0; j < this.m_MeshVerticesPerSelectionVertex; j++) + float num4 = this.GetCoefficient(coefficients[j]); + Color color; + if (num4 >= 3.40282347E+38f) { - bool flag = this.m_Selection[num3]; - if (this.m_RectSelecting) + color = Color.black; + } + else + { + if (num3 - num2 != 0f) { - switch (this.m_RectSelectionMode) - { - case ClothInspector.RectSelectionMode.Replace: - flag = this.m_RectSelection[num3]; - break; - case ClothInspector.RectSelectionMode.Add: - flag |= this.m_RectSelection[num3]; - break; - case ClothInspector.RectSelectionMode.Substract: - flag = (flag && !this.m_RectSelection[num3]); - break; - } + num4 = (num4 - num2) / (num3 - num2); } - Color color; - if (flag) + else { - color = Color.red; + num4 = 0f; } - else + color = this.GetGradientColor(num4); + } + for (int k = 0; k < this.m_MeshVerticesPerSelectionVertex; k++) + { + array[j * this.m_MeshVerticesPerSelectionVertex + k] = color; + } + } + this.m_MaxVisualizedValue[(int)this.drawMode] = num3; + this.m_MinVisualizedValue[(int)this.drawMode] = num2; + this.AssignColorsToMeshArray(array, this.m_SelectionMesh); + } + private void SetupSelectedMeshColors() + { + int num = this.cloth.coefficients.Length; + Color[] array = new Color[num * this.m_MeshVerticesPerSelectionVertex]; + for (int i = 0; i < num; i++) + { + bool flag = this.m_Selection[i]; + if (this.m_RectSelecting) + { + switch (this.m_RectSelectionMode) { - float num4; - if (num2 - num != 0f) - { - num4 = (this.GetCoefficient(coefficients[num3]) - num) / (num2 - num); - } - else - { - num4 = 0.5f; - } - if (num4 < 0.5f) - { - color = Color.Lerp(Color.green, Color.yellow, 2f * num4); - } - else - { - color = Color.Lerp(Color.yellow, Color.blue, 2f * num4 - 1f); - } + case ClothInspector.RectSelectionMode.Replace: + flag = this.m_RectSelection[i]; + break; + case ClothInspector.RectSelectionMode.Add: + flag |= this.m_RectSelection[i]; + break; + case ClothInspector.RectSelectionMode.Substract: + flag = (flag && !this.m_RectSelection[i]); + break; } - array[num3 * this.m_MeshVerticesPerSelectionVertex + j] = color; } - num3++; + Color color = (!flag) ? Color.clear : ClothInspector.s_SelectionColor; + for (int j = 0; j < this.m_MeshVerticesPerSelectionVertex; j++) + { + array[i * this.m_MeshVerticesPerSelectionVertex + j] = color; + } } - this.m_SelectionMesh.colors = array; + this.AssignColorsToMeshArray(array, this.m_SelectedMesh); } private void OnDisable() { - UnityEngine.Object.DestroyImmediate(this.m_SelectionMesh); + if (this.m_SelectionMesh != null) + { + Mesh[] selectionMesh = this.m_SelectionMesh; + for (int i = 0; i < selectionMesh.Length; i++) + { + Mesh obj = selectionMesh[i]; + UnityEngine.Object.DestroyImmediate(obj); + } + Mesh[] selectedMesh = this.m_SelectedMesh; + for (int j = 0; j < selectedMesh.Length; j++) + { + Mesh obj2 = selectedMesh[j]; + UnityEngine.Object.DestroyImmediate(obj2); + } + } + UnityEngine.Object.DestroyImmediate(this.m_VertexMesh); + UnityEngine.Object.DestroyImmediate(this.m_VertexMeshSelected); } - private float CoefficientField(string label, float value, bool enabled, int mode) + private float CoefficientField(float value, float useValue, bool enabled, ClothInspector.DrawMode mode) { - bool enabled2 = GUI.enabled; + GUIContent modeString = this.GetModeString(mode); + EditorGUI.BeginDisabledGroup(!enabled); GUILayout.BeginHorizontal(new GUILayoutOption[0]); - if (GUILayout.Toggle(this.m_DrawMode == mode, ClothInspector.s_ViewIcon, "MiniButton", new GUILayoutOption[] + EditorGUI.showMixedValue = (useValue < 0f); + EditorGUI.BeginChangeCheck(); + useValue = (float)((!EditorGUILayout.Toggle(GUIContent.none, useValue != 0f, new GUILayoutOption[0])) ? 0 : 1); + if (EditorGUI.EndChangeCheck()) { - GUILayout.ExpandWidth(false) - })) + if (useValue > 0f) + { + value = 0f; + } + else + { + value = 3.40282347E+38f; + } + this.drawMode = mode; + } + GUILayout.Space(-152f); + EditorGUI.showMixedValue = false; + EditorGUI.BeginDisabledGroup(useValue != 1f); + float num = value; + EditorGUI.showMixedValue = (value < 0f); + EditorGUI.BeginChangeCheck(); + int keyboardControl = GUIUtility.keyboardControl; + if (useValue > 0f) { - this.m_DrawMode = mode; - this.SetupMeshColors(); + num = EditorGUILayout.FloatField(modeString, value, new GUILayoutOption[0]); } - GUI.enabled = enabled; - float result = EditorGUILayout.FloatField(label, value, new GUILayoutOption[0]); - GUI.enabled = enabled2; - GUILayout.EndHorizontal(); - return result; - } - private float PaintField(string label, float value, ref bool enabled, int mode) - { - bool enabled2 = GUI.enabled; - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - if (GUILayout.Toggle(this.m_DrawMode == mode, ClothInspector.s_ViewIcon, "MiniButton", new GUILayoutOption[] + else { - GUILayout.ExpandWidth(false) - })) + EditorGUILayout.FloatField(modeString, 0f, new GUILayoutOption[0]); + } + bool flag = EditorGUI.EndChangeCheck(); + if (flag) { - this.m_DrawMode = mode; - this.SetupMeshColors(); + value = num; + if (value < 0f) + { + value = 0f; + } } - enabled = GUILayout.Toggle(enabled, ClothInspector.s_PaintIcon, "MiniButton", new GUILayoutOption[] + if (flag || keyboardControl != GUIUtility.keyboardControl) { - GUILayout.ExpandWidth(false) - }); - GUI.enabled = enabled; - float result = EditorGUILayout.FloatField(label, value, new GUILayoutOption[0]); - GUI.enabled = enabled2; + this.drawMode = mode; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + if (useValue > 0f) + { + float num2 = this.m_MinVisualizedValue[(int)mode]; + float num3 = this.m_MaxVisualizedValue[(int)mode]; + if (num3 - num2 > 0f) + { + this.DrawColorBox(null, this.GetGradientColor((value - num2) / (num3 - num2))); + } + else + { + this.DrawColorBox(null, this.GetGradientColor((float)((value > num2) ? 1 : 0))); + } + } + else + { + this.DrawColorBox(null, Color.black); + } + EditorGUI.showMixedValue = false; GUILayout.EndHorizontal(); - return result; + return value; } - private void SelectionGUI() + private float PaintField(float value, ref bool enabled, ClothInspector.DrawMode mode) { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - Vector3[] vertices = skinnedCloth.vertices; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + GUIContent modeString = this.GetModeString(mode); GUILayout.BeginHorizontal(new GUILayoutOption[0]); - if (GUILayout.Button("Select All", new GUILayoutOption[0])) + enabled = GUILayout.Toggle(enabled, ClothInspector.s_PaintIcon, "MiniButton", new GUILayoutOption[] { - for (int i = 0; i < vertices.Length; i++) + GUILayout.ExpandWidth(false) + }); + EditorGUI.BeginDisabledGroup(!enabled); + EditorGUI.BeginChangeCheck(); + bool flag = EditorGUILayout.Toggle(GUIContent.none, value < 3.40282347E+38f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (flag) { - this.m_Selection[i] = true; + value = 0f; } - this.SetupMeshColors(); - SceneView.RepaintAll(); + else + { + value = 3.40282347E+38f; + } + this.drawMode = mode; } - if (GUILayout.Button("Select None", new GUILayoutOption[0])) + GUILayout.Space(-162f); + EditorGUI.BeginDisabledGroup(!flag); + float num = value; + int keyboardControl = GUIUtility.keyboardControl; + EditorGUI.BeginChangeCheck(); + if (flag) { - for (int j = 0; j < vertices.Length; j++) + num = EditorGUILayout.FloatField(modeString, value, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.FloatField(modeString, 0f, new GUILayoutOption[0]); + } + if (num < 0f) + { + num = 0f; + } + if (EditorGUI.EndChangeCheck() || keyboardControl != GUIUtility.keyboardControl) + { + this.drawMode = mode; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.EndDisabledGroup(); + if (flag) + { + float num2 = this.m_MinVisualizedValue[(int)mode]; + float num3 = this.m_MaxVisualizedValue[(int)mode]; + if (num3 - num2 > 0f) { - this.m_Selection[j] = false; + this.DrawColorBox(null, this.GetGradientColor((value - num2) / (num3 - num2))); } - this.SetupMeshColors(); - SceneView.RepaintAll(); + else + { + this.DrawColorBox(null, this.GetGradientColor((float)((value > num2) ? 1 : 0))); + } + } + else + { + this.DrawColorBox(null, Color.black); } + GUILayout.EndHorizontal(); + return num; + } + private void SelectionGUI() + { + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; float num = 0f; float num2 = 0f; float num3 = 0f; float num4 = 0f; int num5 = 0; - for (int k = 0; k < coefficients.Length; k++) + bool flag = true; + for (int i = 0; i < this.m_Selection.Length; i++) { - if (this.m_Selection[k]) + if (this.m_Selection[i]) { - num += coefficients[k].maxDistance; - num2 += coefficients[k].maxDistanceBias; - num3 += coefficients[k].collisionSphereRadius; - num4 += coefficients[k].collisionSphereDistance; + if (flag) + { + num = coefficients[i].maxDistance; + num2 = (float)((num >= 3.40282347E+38f) ? 0 : 1); + num3 = coefficients[i].collisionSphereDistance; + num4 = (float)((num3 >= 3.40282347E+38f) ? 0 : 1); + flag = false; + } + if (coefficients[i].maxDistance != num) + { + num = -1f; + } + if (coefficients[i].collisionSphereDistance != num3) + { + num3 = -1f; + } + if (num2 != (float)((coefficients[i].maxDistance >= 3.40282347E+38f) ? 0 : 1)) + { + num2 = -1f; + } + if (num4 != (float)((coefficients[i].collisionSphereDistance >= 3.40282347E+38f) ? 0 : 1)) + { + num4 = -1f; + } num5++; } } - GUILayout.Label(num5 + " selected", new GUILayoutOption[0]); - GUILayout.EndHorizontal(); - GUILayout.Space(5f); - if (num5 > 0) - { - num /= (float)num5; - num2 /= (float)num5; - num3 /= (float)num5; - num4 /= (float)num5; - } - float num6 = this.CoefficientField("max Distance", num, num5 > 0, 1); - float num7 = this.CoefficientField("distance bias", num2, num5 > 0, 2); - float num8 = this.CoefficientField("collsionSphereRadius", num3, num5 > 0, 3); - float num9 = this.CoefficientField("collisionSphereDistance", num4, num5 > 0, 4); - num7 = Mathf.Clamp(num7, -1f, 1f); + float num6 = this.CoefficientField(num, num2, num5 > 0, ClothInspector.DrawMode.MaxDistance); if (num6 != num) { - for (int l = 0; l < coefficients.Length; l++) + for (int j = 0; j < coefficients.Length; j++) { - if (this.m_Selection[l]) + if (this.m_Selection[j]) { - coefficients[l].maxDistance = num6; + coefficients[j].maxDistance = num6; } } - skinnedCloth.coefficients = coefficients; - this.SetupMeshColors(); + this.cloth.coefficients = coefficients; + this.SetupSelectionMeshColors(); + Undo.RegisterCompleteObjectUndo(this.target, "Change Cloth Coefficients"); } - if (num7 != num2) + float num7 = this.CoefficientField(num3, num4, num5 > 0, ClothInspector.DrawMode.CollisionSphereDistance); + if (num7 != num3) { - for (int m = 0; m < coefficients.Length; m++) + for (int k = 0; k < coefficients.Length; k++) { - if (this.m_Selection[m]) + if (this.m_Selection[k]) { - coefficients[m].maxDistanceBias = num7; + coefficients[k].collisionSphereDistance = num7; } } - skinnedCloth.coefficients = coefficients; - this.SetupMeshColors(); + this.cloth.coefficients = coefficients; + this.SetupSelectionMeshColors(); + Undo.RegisterCompleteObjectUndo(this.target, "Change Cloth Coefficients"); } - if (num8 != num3) + EditorGUI.BeginDisabledGroup(true); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (num5 > 0) { - for (int n = 0; n < coefficients.Length; n++) - { - if (this.m_Selection[n]) - { - coefficients[n].collisionSphereRadius = num8; - } - } - skinnedCloth.coefficients = coefficients; - this.SetupMeshColors(); + GUILayout.FlexibleSpace(); + GUILayout.Label(num5 + " selected", new GUILayoutOption[0]); + } + else + { + GUILayout.Label("Select cloth vertices to edit their constraints.", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); } - if (num9 != num4) + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Backspace) { - for (int num10 = 0; num10 < coefficients.Length; num10++) + for (int l = 0; l < coefficients.Length; l++) { - if (this.m_Selection[num10]) + if (this.m_Selection[l]) { - coefficients[num10].collisionSphereDistance = num9; + ClothInspector.DrawMode drawMode = this.drawMode; + if (drawMode != ClothInspector.DrawMode.MaxDistance) + { + if (drawMode == ClothInspector.DrawMode.CollisionSphereDistance) + { + coefficients[l].collisionSphereDistance = 3.40282347E+38f; + } + } + else + { + coefficients[l].maxDistance = 3.40282347E+38f; + } } } - skinnedCloth.coefficients = coefficients; - this.SetupMeshColors(); + this.cloth.coefficients = coefficients; + this.SetupSelectionMeshColors(); } } private void PaintGUI() { - this.m_PaintMaxDistance = this.PaintField("max Distance", this.m_PaintMaxDistance, ref this.m_PaintMaxDistanceEnabled, 1); - this.m_PaintMaxDistanceBias = this.PaintField("distance bias", this.m_PaintMaxDistanceBias, ref this.m_PaintMaxDistanceBiasEnabled, 2); - this.m_PaintMaxDistanceBias = Mathf.Clamp(this.m_PaintMaxDistanceBias, -1f, 1f); - this.m_PaintCollisionSphereRadius = this.PaintField("collsionSphereRadius", this.m_PaintCollisionSphereRadius, ref this.m_PaintCollisionSphereRadiusEnabled, 3); - this.m_PaintCollisionSphereDistance = this.PaintField("collisionSphereDistance", this.m_PaintCollisionSphereDistance, ref this.m_PaintCollisionSphereDistanceEnabled, 4); - } - public override void OnInspectorGUI() - { - ClothInspector.ToolMode toolMode = ClothInspector.s_ToolMode; - if (Tools.current != Tool.None) + this.state.PaintMaxDistance = this.PaintField(this.state.PaintMaxDistance, ref this.state.PaintMaxDistanceEnabled, ClothInspector.DrawMode.MaxDistance); + this.state.PaintCollisionSphereDistance = this.PaintField(this.state.PaintCollisionSphereDistance, ref this.state.PaintCollisionSphereDistanceEnabled, ClothInspector.DrawMode.CollisionSphereDistance); + if (this.state.PaintMaxDistanceEnabled && !this.state.PaintCollisionSphereDistanceEnabled) { - ClothInspector.s_ToolMode = ClothInspector.ToolMode.Settings; + this.drawMode = ClothInspector.DrawMode.MaxDistance; } - ClothInspector.s_ToolMode = (ClothInspector.ToolMode)GUILayout.Toolbar((int)ClothInspector.s_ToolMode, ClothInspector.s_ToolIcons, new GUILayoutOption[0]); - if (ClothInspector.s_ToolMode != toolMode) + else { - GUIUtility.keyboardControl = 0; - if (ClothInspector.s_ToolMode != ClothInspector.ToolMode.Settings) + if (!this.state.PaintMaxDistanceEnabled && this.state.PaintCollisionSphereDistanceEnabled) { - Tools.current = Tool.None; + this.drawMode = ClothInspector.DrawMode.CollisionSphereDistance; } - SceneView.RepaintAll(); - this.SetupMeshColors(); - } - switch (ClothInspector.s_ToolMode) - { - case ClothInspector.ToolMode.Select: - this.SelectionGUI(); - break; - case ClothInspector.ToolMode.Paint: - this.PaintGUI(); - break; - case ClothInspector.ToolMode.Settings: - base.DrawDefaultInspector(); - break; } + EditorGUI.BeginDisabledGroup(true); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Set constraints to paint onto cloth vertices.", new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); } private int GetMouseVertex(Event e) { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - SkinnedMeshRenderer component = skinnedCloth.GetComponent(); - Vector3[] normals = skinnedCloth.normals; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + if (Tools.current != Tool.None) + { + return -1; + } + SkinnedMeshRenderer component = this.cloth.GetComponent(); + Vector3[] normals = this.cloth.normals; + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; Ray ray = HandleUtility.GUIPointToWorldRay(e.mousePosition); float num = 1000f; int result = -1; Quaternion rotation = component.actualRootBone.rotation; - bool flag = false; - if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.renderMode == DrawCameraMode.Wireframe) - { - flag = true; - } for (int i = 0; i < coefficients.Length; i++) { Vector3 lhs = this.m_LastVertices[i] - ray.origin; float sqrMagnitude = Vector3.Cross(lhs, ray.direction).sqrMagnitude; - if ((Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f || flag) && sqrMagnitude < num && sqrMagnitude < 0.00250000018f) + if ((Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f || this.state.ManipulateBackfaces) && sqrMagnitude < num && sqrMagnitude < 0.00250000018f) { num = sqrMagnitude; result = i; @@ -418,30 +683,58 @@ private void DrawVertices() { this.GenerateSelectionMesh(); } - for (int i = 0; i < ClothInspector.s_SelectionMaterial.passCount; i++) + if (this.state.ToolMode == ClothInspector.ToolMode.Select) { - ClothInspector.s_SelectionMaterial.SetPass(i); - Graphics.DrawMeshNow(this.m_SelectionMesh, Matrix4x4.identity); + for (int i = 0; i < ClothInspector.s_SelectedMaterial.passCount; i++) + { + ClothInspector.s_SelectedMaterial.SetPass(i); + Mesh[] selectedMesh = this.m_SelectedMesh; + for (int j = 0; j < selectedMesh.Length; j++) + { + Mesh mesh = selectedMesh[j]; + Graphics.DrawMeshNow(mesh, Matrix4x4.identity); + } + } + } + Material material = (!this.state.ManipulateBackfaces) ? ClothInspector.s_SelectionMaterial : ClothInspector.s_SelectionMaterialBackfaces; + for (int k = 0; k < material.passCount; k++) + { + material.SetPass(k); + Mesh[] selectionMesh = this.m_SelectionMesh; + for (int l = 0; l < selectionMesh.Length; l++) + { + Mesh mesh2 = selectionMesh[l]; + Graphics.DrawMeshNow(mesh2, Matrix4x4.identity); + } } if (this.m_MouseOver != -1) { - Matrix4x4 matrix = Matrix4x4.TRS(this.m_LastVertices[this.m_MouseOver], Quaternion.identity, 0.02f * Vector3.one); - ClothInspector.s_SelectionMaterial.color = this.m_SelectionMesh.colors[this.m_MouseOver * this.m_MeshVerticesPerSelectionVertex]; - for (int j = 0; j < ClothInspector.s_SelectionMaterial.passCount; j++) + Matrix4x4 matrix = Matrix4x4.TRS(this.m_LastVertices[this.m_MouseOver], Quaternion.identity, Vector3.one * 1.2f); + if (this.state.ToolMode == ClothInspector.ToolMode.Select) { - ClothInspector.s_SelectionMaterial.SetPass(j); - Graphics.DrawMeshNow(this.m_VertexMesh, matrix); + material = ClothInspector.s_SelectedMaterial; + material.color = new Color(ClothInspector.s_SelectionColor.r, ClothInspector.s_SelectionColor.g, ClothInspector.s_SelectionColor.b, 0.5f); } - ClothInspector.s_SelectionMaterial.color = Color.white; + else + { + int num = this.m_MouseOver / ClothInspector.s_MaxVertices; + int num2 = this.m_MouseOver - ClothInspector.s_MaxVertices * num; + material.color = this.m_SelectionMesh[num].colors[num2]; + } + for (int m = 0; m < material.passCount; m++) + { + material.SetPass(m); + Graphics.DrawMeshNow(this.m_VertexMeshSelected, matrix); + } + material.color = Color.white; } } private bool UpdateRectSelection() { bool result = false; - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - SkinnedMeshRenderer component = skinnedCloth.GetComponent(); - Vector3[] normals = skinnedCloth.normals; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + SkinnedMeshRenderer component = this.cloth.GetComponent(); + Vector3[] normals = this.cloth.normals; + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; float x = Mathf.Min(this.m_SelectStartPoint.x, this.m_SelectMousePoint.x); float x2 = Mathf.Max(this.m_SelectStartPoint.x, this.m_SelectMousePoint.x); float y = Mathf.Min(this.m_SelectStartPoint.y, this.m_SelectMousePoint.y); @@ -455,20 +748,15 @@ private bool UpdateRectSelection() Plane plane3 = new Plane(ray.origin + ray.direction, ray3.origin + ray3.direction, ray3.origin); Plane plane4 = new Plane(ray4.origin + ray4.direction, ray2.origin + ray2.direction, ray2.origin); Quaternion rotation = component.actualRootBone.rotation; - bool flag = false; - if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.renderMode == DrawCameraMode.Wireframe) - { - flag = true; - } for (int i = 0; i < coefficients.Length; i++) { Vector3 inPt = this.m_LastVertices[i]; - bool flag2 = Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f; - bool flag3 = plane.GetSide(inPt) && plane2.GetSide(inPt) && plane3.GetSide(inPt) && plane4.GetSide(inPt); - flag3 = (flag3 && (flag || flag2)); - if (this.m_RectSelection[i] != flag3) + bool flag = Vector3.Dot(rotation * normals[i], Camera.current.transform.forward) <= 0f; + bool flag2 = plane.GetSide(inPt) && plane2.GetSide(inPt) && plane3.GetSide(inPt) && plane4.GetSide(inPt); + flag2 = (flag2 && (this.state.ManipulateBackfaces || flag)); + if (this.m_RectSelection[i] != flag2) { - this.m_RectSelection[i] = flag3; + this.m_RectSelection[i] = flag2; result = true; } } @@ -476,8 +764,7 @@ private bool UpdateRectSelection() } private void ApplyRectSelection() { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; for (int i = 0; i < coefficients.Length; i++) { switch (this.m_RectSelectionMode) @@ -546,7 +833,7 @@ private void SelectionPreSceneGUI(int id) this.m_Selection[mouseVertex] = true; } this.m_DidSelect = true; - this.SetupMeshColors(); + this.SetupSelectedMeshColors(); base.Repaint(); } else @@ -572,16 +859,16 @@ private void SelectionPreSceneGUI(int id) { if (!this.m_DidSelect && !current.alt && !current.control && !current.command) { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; for (int j = 0; j < coefficients.Length; j++) { this.m_Selection[j] = false; } } } - this.SetupMeshColors(); - base.Repaint(); + GUIUtility.keyboardControl = 0; + this.SetupSelectedMeshColors(); + SceneView.RepaintAll(); } return; case EventType.MouseMove: @@ -592,7 +879,7 @@ private void SelectionPreSceneGUI(int id) } if (this.m_RectSelecting && current.commandName == "ModifierKeysChanged" && (this.RectSelectionModeFromEvent() || this.UpdateRectSelection())) { - this.SetupMeshColors(); + this.SetupSelectedMeshColors(); } return; case EventType.MouseDrag: @@ -603,14 +890,14 @@ private void SelectionPreSceneGUI(int id) EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(this.SendCommandsOnModifierKeys)); this.m_RectSelecting = true; this.RectSelectionModeFromEvent(); - this.SetupMeshColors(); + this.SetupSelectedMeshColors(); } if (this.m_RectSelecting) { this.m_SelectMousePoint = new Vector2(Mathf.Max(current.mousePosition.x, 0f), Mathf.Max(current.mousePosition.y, 0f)); if (this.RectSelectionModeFromEvent() || this.UpdateRectSelection()) { - this.SetupMeshColors(); + this.SetupSelectedMeshColors(); } current.Use(); } @@ -625,8 +912,7 @@ private void PaintPreSceneGUI(int id) EventType typeForControl = current.GetTypeForControl(id); if (typeForControl == EventType.MouseDown || typeForControl == EventType.MouseDrag) { - SkinnedCloth skinnedCloth = (SkinnedCloth)this.target; - ClothSkinningCoefficient[] coefficients = skinnedCloth.coefficients; + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; if (GUIUtility.hotControl != id && (current.alt || current.control || current.command || current.button != 0)) { return; @@ -639,30 +925,21 @@ private void PaintPreSceneGUI(int id) if (mouseVertex != -1) { bool flag = false; - if (this.m_PaintMaxDistanceEnabled && coefficients[mouseVertex].maxDistance != this.m_PaintMaxDistance) - { - coefficients[mouseVertex].maxDistance = this.m_PaintMaxDistance; - flag = true; - } - if (this.m_PaintMaxDistanceBiasEnabled && coefficients[mouseVertex].maxDistanceBias != this.m_PaintMaxDistanceBias) + if (this.state.PaintMaxDistanceEnabled && coefficients[mouseVertex].maxDistance != this.state.PaintMaxDistance) { - coefficients[mouseVertex].maxDistanceBias = this.m_PaintMaxDistanceBias; + coefficients[mouseVertex].maxDistance = this.state.PaintMaxDistance; flag = true; } - if (this.m_PaintCollisionSphereRadiusEnabled && coefficients[mouseVertex].collisionSphereRadius != this.m_PaintCollisionSphereRadius) + if (this.state.PaintCollisionSphereDistanceEnabled && coefficients[mouseVertex].collisionSphereDistance != this.state.PaintCollisionSphereDistance) { - coefficients[mouseVertex].collisionSphereRadius = this.m_PaintCollisionSphereRadius; - flag = true; - } - if (this.m_PaintCollisionSphereDistanceEnabled && coefficients[mouseVertex].collisionSphereDistance != this.m_PaintCollisionSphereDistance) - { - coefficients[mouseVertex].collisionSphereDistance = this.m_PaintCollisionSphereDistance; + coefficients[mouseVertex].collisionSphereDistance = this.state.PaintCollisionSphereDistance; flag = true; } if (flag) { - skinnedCloth.coefficients = coefficients; - this.SetupMeshColors(); + Undo.RegisterCompleteObjectUndo(this.target, "Paint Cloth"); + this.cloth.coefficients = coefficients; + this.SetupSelectionMeshColors(); base.Repaint(); } } @@ -679,15 +956,25 @@ private void PaintPreSceneGUI(int id) } public void OnPreSceneGUI() { - if (ClothInspector.s_ToolMode == ClothInspector.ToolMode.Settings) + if (!this.editing) { return; } + Tools.current = Tool.None; + if (this.state.ToolMode == (ClothInspector.ToolMode)(-1)) + { + this.state.ToolMode = ClothInspector.ToolMode.Select; + } + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; + if (this.m_Selection.Length != coefficients.Length && this.m_Selection.Length != ClothInspector.s_MaxVertices) + { + this.OnEnable(); + } Handles.BeginGUI(); int controlID = GUIUtility.GetControlID(FocusType.Passive); Event current = Event.current; EventType typeForControl = current.GetTypeForControl(controlID); - if (typeForControl != EventType.MouseMove) + if (typeForControl != EventType.MouseMove && typeForControl != EventType.MouseDrag) { if (typeForControl == EventType.Layout) { @@ -703,7 +990,7 @@ public void OnPreSceneGUI() SceneView.RepaintAll(); } } - ClothInspector.ToolMode toolMode = ClothInspector.s_ToolMode; + ClothInspector.ToolMode toolMode = this.state.ToolMode; if (toolMode != ClothInspector.ToolMode.Select) { if (toolMode == ClothInspector.ToolMode.Paint) @@ -719,20 +1006,191 @@ public void OnPreSceneGUI() } public void OnSceneGUI() { - if (ClothInspector.s_ToolMode == ClothInspector.ToolMode.Settings) + if (!this.editing) + { + return; + } + if (Selection.gameObjects.Length > 1) { return; } + ClothInspector.s_SelectionColor = GUI.skin.settings.selectionColor; if (Event.current.type == EventType.Repaint) { this.DrawVertices(); } + Event current = Event.current; + if (current.commandName == "SelectAll") + { + if (current.type == EventType.ValidateCommand) + { + current.Use(); + } + if (current.type == EventType.ExecuteCommand) + { + int num = this.cloth.vertices.Length; + for (int i = 0; i < num; i++) + { + this.m_Selection[i] = true; + } + this.SetupSelectedMeshColors(); + SceneView.RepaintAll(); + this.state.ToolMode = ClothInspector.ToolMode.Select; + current.Use(); + } + } Handles.BeginGUI(); - if (this.m_RectSelecting && ClothInspector.s_ToolMode == ClothInspector.ToolMode.Select && Event.current.type == EventType.Repaint) + if (this.m_RectSelecting && this.state.ToolMode == ClothInspector.ToolMode.Select && Event.current.type == EventType.Repaint) { EditorStyles.selectionRect.Draw(EditorGUIExt.FromToRect(this.m_SelectStartPoint, this.m_SelectMousePoint), GUIContent.none, false, false, false, false); } Handles.EndGUI(); + SceneViewOverlay.Window(new GUIContent("Cloth Constraints"), new SceneViewOverlay.WindowFunction(this.VertexEditing), 0, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + } + public void VisualizationMenuSetMaxDistanceMode() + { + this.drawMode = ClothInspector.DrawMode.MaxDistance; + if (!this.state.PaintMaxDistanceEnabled) + { + this.state.PaintCollisionSphereDistanceEnabled = false; + this.state.PaintMaxDistanceEnabled = true; + } + } + public void VisualizationMenuSetCollisionSphereMode() + { + this.drawMode = ClothInspector.DrawMode.CollisionSphereDistance; + if (!this.state.PaintCollisionSphereDistanceEnabled) + { + this.state.PaintCollisionSphereDistanceEnabled = true; + this.state.PaintMaxDistanceEnabled = false; + } + } + public void VisualizationMenuToggleManipulateBackfaces() + { + this.state.ManipulateBackfaces = !this.state.ManipulateBackfaces; + } + public void DrawColorBox(Texture gradientTex, Color col) + { + if (!GUI.enabled) + { + col = new Color(0.3f, 0.3f, 0.3f, 1f); + EditorGUI.showMixedValue = false; + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Space(5f); + Rect rect = GUILayoutUtility.GetRect(new GUIContent(), GUIStyle.none, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true), + GUILayout.Height(10f) + }); + GUI.Box(rect, GUIContent.none); + rect = new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f); + if (gradientTex) + { + GUI.DrawTexture(rect, gradientTex); + } + else + { + EditorGUIUtility.DrawColorSwatch(rect, col, false); + } + GUILayout.EndVertical(); + } + private bool IsConstrained() + { + ClothSkinningCoefficient[] coefficients = this.cloth.coefficients; + ClothSkinningCoefficient[] array = coefficients; + for (int i = 0; i < array.Length; i++) + { + ClothSkinningCoefficient clothSkinningCoefficient = array[i]; + if (clothSkinningCoefficient.maxDistance < 3.40282347E+38f) + { + return true; + } + if (clothSkinningCoefficient.collisionSphereDistance < 3.40282347E+38f) + { + return true; + } + } + return false; + } + private void VertexEditing(UnityEngine.Object unused, SceneView sceneView) + { + GUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.Width(300f) + }); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label("Visualization: ", new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.BeginVertical(new GUILayoutOption[0]); + if (EditorGUILayout.ButtonMouseDown(this.GetModeString(this.drawMode), FocusType.Passive, EditorStyles.toolbarDropDown, new GUILayoutOption[0])) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + GenericMenu genericMenu = new GenericMenu(); + genericMenu.AddItem(this.GetModeString(ClothInspector.DrawMode.MaxDistance), this.drawMode == ClothInspector.DrawMode.MaxDistance, new GenericMenu.MenuFunction(this.VisualizationMenuSetMaxDistanceMode)); + genericMenu.AddItem(this.GetModeString(ClothInspector.DrawMode.CollisionSphereDistance), this.drawMode == ClothInspector.DrawMode.CollisionSphereDistance, new GenericMenu.MenuFunction(this.VisualizationMenuSetCollisionSphereMode)); + genericMenu.AddSeparator(string.Empty); + genericMenu.AddItem(new GUIContent("Manipulate Backfaces"), this.state.ManipulateBackfaces, new GenericMenu.MenuFunction(this.VisualizationMenuToggleManipulateBackfaces)); + genericMenu.DropDown(last); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(this.m_MinVisualizedValue[(int)this.drawMode].ToString(), new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + this.DrawColorBox(ClothInspector.s_ColorTexture, Color.clear); + GUILayout.Label(this.m_MaxVisualizedValue[(int)this.drawMode].ToString(), new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUILayout.Label("Unconstrained:", new GUILayoutOption[0]); + GUILayout.Space(-24f); + GUILayout.BeginHorizontal(new GUILayoutOption[] + { + GUILayout.Width(20f) + }); + this.DrawColorBox(null, Color.black); + GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.BeginVertical("Box", new GUILayoutOption[0]); + if (Tools.current != Tool.None) + { + this.state.ToolMode = (ClothInspector.ToolMode)(-1); + } + ClothInspector.ToolMode toolMode = this.state.ToolMode; + this.state.ToolMode = (ClothInspector.ToolMode)GUILayout.Toolbar((int)this.state.ToolMode, ClothInspector.s_ToolIcons, new GUILayoutOption[0]); + if (this.state.ToolMode != toolMode) + { + GUIUtility.keyboardControl = 0; + SceneView.RepaintAll(); + this.SetupSelectionMeshColors(); + this.SetupSelectedMeshColors(); + } + ClothInspector.ToolMode toolMode2 = this.state.ToolMode; + if (toolMode2 != ClothInspector.ToolMode.Select) + { + if (toolMode2 == ClothInspector.ToolMode.Paint) + { + Tools.current = Tool.None; + this.PaintGUI(); + } + } + else + { + Tools.current = Tool.None; + this.SelectionGUI(); + } + GUILayout.EndVertical(); + if (!this.IsConstrained()) + { + EditorGUILayout.HelpBox("No constraints have been set up, so the cloth will move freely. Set up vertex constraints here to restrict it.", MessageType.Info); + } + GUILayout.EndVertical(); + GUILayout.Space(-4f); } } } diff --git a/UnityEditor/UnityEditor/ClothInspectorState.cs b/UnityEditor/UnityEditor/ClothInspectorState.cs new file mode 100644 index 00000000..91c71805 --- /dev/null +++ b/UnityEditor/UnityEditor/ClothInspectorState.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ClothInspectorState : ScriptableSingleton + { + [SerializeField] + public ClothInspector.DrawMode DrawMode = ClothInspector.DrawMode.MaxDistance; + [SerializeField] + public bool ManipulateBackfaces; + [SerializeField] + public bool PaintMaxDistanceEnabled = true; + [SerializeField] + public bool PaintCollisionSphereDistanceEnabled; + [SerializeField] + public float PaintMaxDistance = 0.2f; + [SerializeField] + public float PaintCollisionSphereDistance; + [SerializeField] + public ClothInspector.ToolMode ToolMode; + } +} diff --git a/UnityEditor/UnityEditor/CodeStrippingUtils.cs b/UnityEditor/UnityEditor/CodeStrippingUtils.cs index 27121e51..56ee6e5e 100644 --- a/UnityEditor/UnityEditor/CodeStrippingUtils.cs +++ b/UnityEditor/UnityEditor/CodeStrippingUtils.cs @@ -44,14 +44,74 @@ private static HashSet GetClassNames(IEnumerable classIds) } private static HashSet GetAllStrippableModules() { - return new HashSet(); + HashSet hashSet = new HashSet(); + string[] moduleNames = ModuleMetadata.GetModuleNames(); + for (int i = 0; i < moduleNames.Length; i++) + { + string text = moduleNames[i]; + if (ModuleMetadata.GetModuleStrippable(text)) + { + hashSet.Add(text); + } + } + return hashSet; } private static HashSet GetRequiredStrippableModules(HashSet nativeClasses) { - return new HashSet(); + HashSet hashSet = new HashSet(); + string[] moduleNames = ModuleMetadata.GetModuleNames(); + for (int i = 0; i < moduleNames.Length; i++) + { + string text = moduleNames[i]; + if (ModuleMetadata.GetModuleStrippable(text)) + { + HashSet classNames = CodeStrippingUtils.GetClassNames(ModuleMetadata.GetModuleClasses(text)); + if (nativeClasses.Overlaps(classNames)) + { + hashSet.Add(text); + } + } + } + return hashSet; } private static void ExcludeModuleManagers(ref HashSet nativeClasses) { + string[] moduleNames = ModuleMetadata.GetModuleNames(); + int derivedFromClassID = BaseObjectTools.StringToClassID("GlobalGameManager"); + string[] array = moduleNames; + for (int i = 0; i < array.Length; i++) + { + string moduleName = array[i]; + if (ModuleMetadata.GetModuleStrippable(moduleName)) + { + int[] moduleClasses = ModuleMetadata.GetModuleClasses(moduleName); + HashSet hashSet = new HashSet(); + HashSet hashSet2 = new HashSet(); + int[] array2 = moduleClasses; + for (int j = 0; j < array2.Length; j++) + { + int num = array2[j]; + if (BaseObjectTools.IsDerivedFromClassID(num, derivedFromClassID)) + { + hashSet.Add(num); + } + else + { + hashSet2.Add(BaseObjectTools.ClassIDToString(num)); + } + } + if (hashSet2.Count != 0) + { + if (!nativeClasses.Overlaps(hashSet2)) + { + foreach (int current in hashSet) + { + nativeClasses.Remove(BaseObjectTools.ClassIDToString(current)); + } + } + } + } + } } private static HashSet GenerateNativeClassList(RuntimeClassRegistry rcr, string directory, string[] rootAssemblies) { diff --git a/UnityEditor/UnityEditor/Collider2DEditorBase.cs b/UnityEditor/UnityEditor/Collider2DEditorBase.cs index 3628d895..c27777ff 100644 --- a/UnityEditor/UnityEditor/Collider2DEditorBase.cs +++ b/UnityEditor/UnityEditor/Collider2DEditorBase.cs @@ -4,29 +4,11 @@ namespace UnityEditor { internal class Collider2DEditorBase : ColliderEditorBase { - protected SerializedProperty m_Material; - protected SerializedProperty m_IsTrigger; - public virtual void OnEnable() + public override void OnInspectorGUI() { - this.m_Material = base.serializedObject.FindProperty("m_Material"); - this.m_IsTrigger = base.serializedObject.FindProperty("m_IsTrigger"); - } - public virtual void OnDisable() - { - base.editingCollider = false; - } - protected void BeginColliderInspector() - { - base.serializedObject.Update(); - EditorGUI.BeginDisabledGroup(base.targets.Length > 1); - base.InspectorEditButtonGUI(); - EditorGUI.EndDisabledGroup(); - EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); - } - protected void EndColliderInspector() - { - base.serializedObject.ApplyModifiedProperties(); + base.OnInspectorGUI(); + this.CheckColliderErrorState(); + Effector2DEditor.CheckEffectorWarnings(this.target as Collider2D); } protected void CheckColliderErrorState() { @@ -43,5 +25,16 @@ protected void CheckColliderErrorState() EditorGUILayout.HelpBox("The collider did not create any collision shapes as they all failed verification. This could be because they were deemed too small or the vertices were too close. Vertices can also become close under certain rotations or very small scaling.", MessageType.Warning); } } + protected void BeginColliderInspector() + { + base.serializedObject.Update(); + EditorGUI.BeginDisabledGroup(base.targets.Length > 1); + base.InspectorEditButtonGUI(); + EditorGUI.EndDisabledGroup(); + } + protected void EndColliderInspector() + { + base.serializedObject.ApplyModifiedProperties(); + } } } diff --git a/UnityEditor/UnityEditor/Collider3DEditorBase.cs b/UnityEditor/UnityEditor/Collider3DEditorBase.cs index 2e5527f4..66d40c2b 100644 --- a/UnityEditor/UnityEditor/Collider3DEditorBase.cs +++ b/UnityEditor/UnityEditor/Collider3DEditorBase.cs @@ -6,15 +6,12 @@ internal class Collider3DEditorBase : ColliderEditorBase { protected SerializedProperty m_Material; protected SerializedProperty m_IsTrigger; - public virtual void OnEnable() + public override void OnEnable() { + base.OnEnable(); this.m_Material = base.serializedObject.FindProperty("m_Material"); this.m_IsTrigger = base.serializedObject.FindProperty("m_IsTrigger"); } - public virtual void OnDisable() - { - base.editingCollider = false; - } public override void OnInspectorGUI() { base.serializedObject.Update(); diff --git a/UnityEditor/UnityEditor/ColliderEditorBase.cs b/UnityEditor/UnityEditor/ColliderEditorBase.cs index 59bd4ca0..52dc6b79 100644 --- a/UnityEditor/UnityEditor/ColliderEditorBase.cs +++ b/UnityEditor/UnityEditor/ColliderEditorBase.cs @@ -1,49 +1,15 @@ using System; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { internal class ColliderEditorBase : Editor { - private const float k_EditColliderbuttonWidth = 22f; - private const float k_EditColliderbuttonHeight = 22f; - private const float k_SpaceBetweenLabelAndButton = 5f; - protected static ColliderEditorBase s_ActiveColliderEditor; - private static GUIStyle s_EditColliderButtonStyle; - private Tool m_PreviousTool; - private bool m_EditingCollider; public bool editingCollider { get { - if (Tools.current != Tool.None && this.m_EditingCollider) - { - this.editingCollider = false; - } - return this.m_EditingCollider; - } - set - { - if (!this.m_EditingCollider && value) - { - if (ColliderEditorBase.s_ActiveColliderEditor != null) - { - ColliderEditorBase.s_ActiveColliderEditor.editingCollider = false; - } - ColliderEditorBase.s_ActiveColliderEditor = this; - this.m_PreviousTool = Tools.current; - Tools.current = Tool.None; - this.OnEditStart(); - } - else - { - if (this.m_EditingCollider && !value) - { - Tools.current = ((this.m_PreviousTool == Tool.None) ? Tool.Move : this.m_PreviousTool); - ColliderEditorBase.s_ActiveColliderEditor = null; - this.OnEditEnd(); - } - } - this.m_EditingCollider = value; + return EditMode.editMode == EditMode.SceneViewEditMode.Collider && EditMode.IsOwner(this); } } protected virtual void OnEditStart() @@ -52,42 +18,17 @@ protected virtual void OnEditStart() protected virtual void OnEditEnd() { } - protected void InspectorEditButtonGUI() + public virtual void OnEnable() { - if (ColliderEditorBase.s_EditColliderButtonStyle == null) - { - ColliderEditorBase.s_EditColliderButtonStyle = new GUIStyle("Button"); - ColliderEditorBase.s_EditColliderButtonStyle.padding = new RectOffset(0, 0, 0, 0); - ColliderEditorBase.s_EditColliderButtonStyle.margin = new RectOffset(0, 0, 0, 0); - } - Rect controlRect = EditorGUILayout.GetControlRect(true, 22f, new GUILayoutOption[0]); - Rect position = new Rect(controlRect.xMin + EditorGUIUtility.labelWidth, controlRect.yMin, 22f, 22f); - GUIContent content = new GUIContent("Edit Collider"); - Vector2 vector = GUI.skin.label.CalcSize(content); - Rect position2 = new Rect(position.xMax + 5f, controlRect.yMin + (controlRect.height - vector.y) * 0.5f, vector.x, controlRect.height); - EditorGUI.BeginChangeCheck(); - this.editingCollider = GUI.Toggle(position, this.editingCollider, EditorGUIUtility.IconContent("EditCollider"), ColliderEditorBase.s_EditColliderButtonStyle); - GUI.Label(position2, "Edit Collider"); - if (EditorGUI.EndChangeCheck()) - { - this.EditModeChanged(); - } + EditMode.onEditModeStartDelegate = (EditMode.OnEditModeStartFunc)Delegate.Combine(EditMode.onEditModeStartDelegate, new EditMode.OnEditModeStartFunc(this.OnEditModeStart)); } - private void EditModeChanged() + public virtual void OnDisable() { - if (this.editingCollider && SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !ColliderEditorBase.ColliderSeenByCamera(SceneView.lastActiveSceneView.camera, this.target)) - { - SceneView.lastActiveSceneView.Frame(ColliderEditorBase.GetColliderBounds(this.target)); - } - SceneView.RepaintAll(); - } - private static bool ColliderSeenByCamera(Camera camera, UnityEngine.Object collider) - { - return ColliderEditorBase.AnyPointSeenByCamera(camera, ColliderEditorBase.GetColliderVertices(collider)); + EditMode.onEditModeEndDelegate = (EditMode.OnEditModeStopFunc)Delegate.Remove(EditMode.onEditModeEndDelegate, new EditMode.OnEditModeStopFunc(this.OnEditModeEnd)); } - private static Vector3[] GetColliderVertices(UnityEngine.Object collider) + protected void InspectorEditButtonGUI() { - return ColliderEditorBase.BoundsToVertices(ColliderEditorBase.GetColliderBounds(collider)); + EditMode.DoEditModeInspectorModeButton(EditMode.SceneViewEditMode.Collider, "Edit Collider", EditorGUIUtility.IconContent("EditCollider"), ColliderEditorBase.GetColliderBounds(this.target), this); } private static Bounds GetColliderBounds(UnityEngine.Object collider) { @@ -101,36 +42,19 @@ private static Bounds GetColliderBounds(UnityEngine.Object collider) } return default(Bounds); } - private static Vector3[] BoundsToVertices(Bounds bounds) + protected void OnEditModeStart(Editor editor, EditMode.SceneViewEditMode mode) { - return new Vector3[] + if (mode == EditMode.SceneViewEditMode.Collider && editor == this) { - new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), - new Vector3(bounds.min.x, bounds.min.y, bounds.max.z), - new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), - new Vector3(bounds.min.x, bounds.max.y, bounds.max.z), - new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), - new Vector3(bounds.max.x, bounds.min.y, bounds.max.z), - new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), - new Vector3(bounds.max.x, bounds.max.y, bounds.max.z) - }; + this.OnEditStart(); + } } - private static bool AnyPointSeenByCamera(Camera camera, Vector3[] points) + protected void OnEditModeEnd(Editor editor) { - for (int i = 0; i < points.Length; i++) + if (editor == this) { - Vector3 point = points[i]; - if (ColliderEditorBase.PointSeenByCamera(camera, point)) - { - return true; - } + this.OnEditEnd(); } - return false; - } - private static bool PointSeenByCamera(Camera camera, Vector3 point) - { - Vector3 vector = camera.WorldToViewportPoint(point); - return vector.x > 0f && vector.x < 1f && vector.y > 0f && vector.y < 1f; } } } diff --git a/UnityEditor/UnityEditor/ColliderEditorUtility.cs b/UnityEditor/UnityEditor/ColliderEditorUtility.cs new file mode 100644 index 00000000..f4819af7 --- /dev/null +++ b/UnityEditor/UnityEditor/ColliderEditorUtility.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ColliderEditorUtility + { + private const float k_EditColliderbuttonWidth = 22f; + private const float k_EditColliderbuttonHeight = 22f; + private const float k_SpaceBetweenLabelAndButton = 5f; + private static GUIStyle s_EditColliderButtonStyle; + public static bool InspectorEditButtonGUI(bool editing) + { + if (ColliderEditorUtility.s_EditColliderButtonStyle == null) + { + ColliderEditorUtility.s_EditColliderButtonStyle = new GUIStyle("Button"); + ColliderEditorUtility.s_EditColliderButtonStyle.padding = new RectOffset(0, 0, 0, 0); + ColliderEditorUtility.s_EditColliderButtonStyle.margin = new RectOffset(0, 0, 0, 0); + } + EditorGUI.BeginChangeCheck(); + Rect controlRect = EditorGUILayout.GetControlRect(true, 22f, new GUILayoutOption[0]); + Rect position = new Rect(controlRect.xMin + EditorGUIUtility.labelWidth, controlRect.yMin, 22f, 22f); + GUIContent content = new GUIContent("Edit Collider"); + Vector2 vector = GUI.skin.label.CalcSize(content); + Rect position2 = new Rect(position.xMax + 5f, controlRect.yMin + (controlRect.height - vector.y) * 0.5f, vector.x, controlRect.height); + GUILayout.Space(2f); + bool result = GUI.Toggle(position, editing, EditorGUIUtility.IconContent("EditCollider"), ColliderEditorUtility.s_EditColliderButtonStyle); + GUI.Label(position2, "Edit Collider"); + if (EditorGUI.EndChangeCheck()) + { + SceneView.RepaintAll(); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/CollisionModuleUI.cs b/UnityEditor/UnityEditor/CollisionModuleUI.cs index 900e820a..3b7b8946 100644 --- a/UnityEditor/UnityEditor/CollisionModuleUI.cs +++ b/UnityEditor/UnityEditor/CollisionModuleUI.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using UnityEngine; @@ -75,7 +74,6 @@ protected override void Init() for (int i = 0; i < this.m_Planes.Length; i++) { this.m_Planes[i] = base.GetProperty("plane" + i); - Assert.That(this.m_Planes[i] != null); if (i == 0 || this.m_Planes[i].objectReferenceValue != null) { list.Add(this.m_Planes[i]); @@ -343,7 +341,7 @@ private void DrawGrid(Vector3 pos, Vector3 axis1, Vector3 axis2, Vector3 normal, { return; } - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); if (color.a > 0f) { GL.Begin(1); diff --git a/UnityEditor/UnityEditor/ColorPicker.cs b/UnityEditor/UnityEditor/ColorPicker.cs index 0597bc43..865ae5dc 100644 --- a/UnityEditor/UnityEditor/ColorPicker.cs +++ b/UnityEditor/UnityEditor/ColorPicker.cs @@ -41,6 +41,7 @@ private class Styles private const int kSlidersHeight = 82; private const int kColorBoxHeight = 162; private const int kPresetsHeight = 300; + private const float kFixedWindowWidth = 193f; private static ColorPicker s_SharedColorPicker; [SerializeField] private Color m_Color = Color.black; @@ -435,6 +436,17 @@ private static void HSVToRGBArray(Color[] colors) colors[i] = color2; } } + private static void LinearToGammaArray(Color[] colors) + { + int num = colors.Length; + for (int i = 0; i < num; i++) + { + Color color = colors[i]; + Color gamma = color.gamma; + gamma.a = color.a; + colors[i] = gamma; + } + } private void DrawColorSlider(Rect colorSliderRect, Vector2 constantValues) { if (Event.current.type != EventType.Repaint) @@ -491,6 +503,10 @@ private void DrawColorSlider(Rect colorSliderRect, Vector2 constantValues) ColorPicker.FillArea(width, height, pixels, new Color(this.m_R, this.m_G, 0f, 1f), new Color(0f, 0f, 0f, 0f), new Color(0f, 0f, 1f, 0f)); break; } + if (QualitySettings.activeColorSpace == ColorSpace.Linear) + { + ColorPicker.LinearToGammaArray(pixels); + } this.m_ColorSlider.SetPixels(pixels, 0); this.m_ColorSlider.Apply(true); } @@ -502,7 +518,7 @@ public static Texture2D MakeTexture(int width, int height) { hideFlags = HideFlags.HideAndDontSave, wrapMode = TextureWrapMode.Clamp, - hideFlags = HideFlags.DontSave + hideFlags = HideFlags.HideAndDontSave }; } private void DrawColorSpaceBox(Rect colorBoxRect, float constantValue) @@ -561,6 +577,10 @@ private void DrawColorSpaceBox(Rect colorBoxRect, float constantValue) ColorPicker.FillArea(width, height, this.m_Colors, new Color(0f, 0f, this.m_B, 1f), new Color(1f, 0f, 0f, 0f), new Color(0f, 1f, 0f, 0f)); break; } + if (QualitySettings.activeColorSpace == ColorSpace.Linear) + { + ColorPicker.LinearToGammaArray(this.m_Colors); + } this.m_ColorBox.SetPixels(this.m_Colors, 0); this.m_ColorBox.Apply(true); this.m_LastConstant = constantValue; @@ -590,6 +610,7 @@ private void InitIfNeeded() this.m_ColorLibraryEditor.alwaysShowScrollAreaHorizontalLines = false; this.m_ColorLibraryEditor.marginsForGrid = new RectOffset(0, 0, 0, 0); this.m_ColorLibraryEditor.marginsForList = new RectOffset(0, 5, 2, 2); + this.m_ColorLibraryEditor.InitializeGrid(193f - (float)(ColorPicker.styles.background.padding.left + ColorPicker.styles.background.padding.right)); } } private void PresetClickedCallback(int clickCount, object presetObject) @@ -934,10 +955,10 @@ public static void Show(GUIView viewToUpdate, Color col, bool showAlpha) { ColorPicker get = ColorPicker.get; get.title = "Color"; - float x = (float)EditorPrefs.GetInt("CPickerWidth", (int)get.position.width); float y = (float)EditorPrefs.GetInt("CPickerHeight", (int)get.position.height); - get.minSize = new Vector2(x, y); - get.maxSize = new Vector2(x, y); + get.minSize = new Vector2(193f, y); + get.maxSize = new Vector2(193f, y); + get.InitIfNeeded(); get.ShowAuxWindow(); } } @@ -1013,7 +1034,6 @@ public void OnDestroy() { this.m_ColorLibraryEditor.UnloadUsedLibraries(); } - EditorPrefs.SetInt("CPickerWidth", (int)base.position.width); EditorPrefs.SetInt("CPickerHeight", (int)base.position.height); } } diff --git a/UnityEditor/UnityEditor/ComplexD.cs b/UnityEditor/UnityEditor/ComplexD.cs new file mode 100644 index 00000000..e46423c2 --- /dev/null +++ b/UnityEditor/UnityEditor/ComplexD.cs @@ -0,0 +1,133 @@ +using System; +namespace UnityEditor +{ + internal class ComplexD + { + public double real; + public double imag; + public ComplexD(double real, double imag) + { + this.real = real; + this.imag = imag; + } + public static ComplexD Add(ComplexD a, ComplexD b) + { + return new ComplexD(a.real + b.real, a.imag + b.imag); + } + public static ComplexD Add(ComplexD a, double b) + { + return new ComplexD(a.real + b, a.imag); + } + public static ComplexD Add(double a, ComplexD b) + { + return new ComplexD(a + b.real, b.imag); + } + public static ComplexD Sub(ComplexD a, ComplexD b) + { + return new ComplexD(a.real - b.real, a.imag - b.imag); + } + public static ComplexD Sub(ComplexD a, double b) + { + return new ComplexD(a.real - b, a.imag); + } + public static ComplexD Sub(double a, ComplexD b) + { + return new ComplexD(a - b.real, -b.imag); + } + public static ComplexD Mul(ComplexD a, ComplexD b) + { + return new ComplexD(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real); + } + public static ComplexD Mul(ComplexD a, double b) + { + return new ComplexD(a.real * b, a.imag * b); + } + public static ComplexD Mul(double a, ComplexD b) + { + return new ComplexD(a * b.real, a * b.imag); + } + public static ComplexD Div(ComplexD a, ComplexD b) + { + double num = b.real * b.real + b.imag * b.imag; + double num2 = 1.0 / num; + return new ComplexD((a.real * b.real + a.imag * b.imag) * num2, (a.imag * b.real - a.real * b.imag) * num2); + } + public static ComplexD Div(double a, ComplexD b) + { + double num = b.real * b.real + b.imag * b.imag; + double num2 = a / num; + return new ComplexD(num2 * b.real, -num2 * b.imag); + } + public static ComplexD Div(ComplexD a, double b) + { + double num = 1.0 / b; + return new ComplexD(a.real * num, a.imag * num); + } + public static ComplexD Exp(double omega) + { + return new ComplexD(Math.Cos(omega), Math.Sin(omega)); + } + public static ComplexD Pow(ComplexD a, double b) + { + double num = Math.Atan2(a.imag, a.real); + double num2 = Math.Pow(a.Mag2(), b * 0.5); + return new ComplexD(num2 * Math.Cos(num * b), num2 * Math.Sin(num * b)); + } + public double Mag2() + { + return this.real * this.real + this.imag * this.imag; + } + public double Mag() + { + return Math.Sqrt(this.Mag2()); + } + public static ComplexD operator +(ComplexD a, ComplexD b) + { + return ComplexD.Add(a, b); + } + public static ComplexD operator -(ComplexD a, ComplexD b) + { + return ComplexD.Sub(a, b); + } + public static ComplexD operator *(ComplexD a, ComplexD b) + { + return ComplexD.Mul(a, b); + } + public static ComplexD operator /(ComplexD a, ComplexD b) + { + return ComplexD.Div(a, b); + } + public static ComplexD operator +(ComplexD a, double b) + { + return ComplexD.Add(a, b); + } + public static ComplexD operator -(ComplexD a, double b) + { + return ComplexD.Sub(a, b); + } + public static ComplexD operator *(ComplexD a, double b) + { + return ComplexD.Mul(a, b); + } + public static ComplexD operator /(ComplexD a, double b) + { + return ComplexD.Div(a, b); + } + public static ComplexD operator +(double a, ComplexD b) + { + return ComplexD.Add(a, b); + } + public static ComplexD operator -(double a, ComplexD b) + { + return ComplexD.Sub(a, b); + } + public static ComplexD operator *(double a, ComplexD b) + { + return ComplexD.Mul(a, b); + } + public static ComplexD operator /(double a, ComplexD b) + { + return ComplexD.Div(a, b); + } + } +} diff --git a/UnityEditor/UnityEditor/ConsoleWindow.cs b/UnityEditor/UnityEditor/ConsoleWindow.cs index 5ea7d656..a421ab42 100644 --- a/UnityEditor/UnityEditor/ConsoleWindow.cs +++ b/UnityEditor/UnityEditor/ConsoleWindow.cs @@ -371,7 +371,7 @@ private void OnGUI() { if (current.clickCount == 2) { - LogEntries.OpenEntryFile(this.m_ListView.row); + LogEntries.RowGotDoubleClicked(this.m_ListView.row); } flag3 = true; } @@ -421,7 +421,7 @@ private void OnGUI() } if (GUIUtility.keyboardControl == this.m_ListView.ID && current.type == EventType.KeyDown && current.keyCode == KeyCode.Return && this.m_ListView.row != 0) { - LogEntries.OpenEntryFile(this.m_ListView.row); + LogEntries.RowGotDoubleClicked(this.m_ListView.row); Event.current.Use(); } if (current.type != EventType.Layout && ListViewGUI.ilvState.rectHeight != 1) diff --git a/UnityEditor/UnityEditor/ContainerWindow.cs b/UnityEditor/UnityEditor/ContainerWindow.cs index 422f0ffd..8c3a47c2 100644 --- a/UnityEditor/UnityEditor/ContainerWindow.cs +++ b/UnityEditor/UnityEditor/ContainerWindow.cs @@ -133,9 +133,6 @@ public ContainerWindow() public extern void SetInvisible(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetIsDragging(bool dragging); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public extern bool IsZoomed(); internal void ShowPopup() { @@ -306,7 +303,9 @@ private void Load(bool loadPosition) pixelRect.y = EditorPrefs.GetFloat(str + "y", this.m_PixelRect.y); } pixelRect.width = Mathf.Max(EditorPrefs.GetFloat(str + "w", this.m_PixelRect.width), this.m_MinSize.x); + pixelRect.width = Mathf.Min(pixelRect.width, this.m_MaxSize.x); pixelRect.height = Mathf.Max(EditorPrefs.GetFloat(str + "h", this.m_PixelRect.height), this.m_MinSize.y); + pixelRect.height = Mathf.Min(pixelRect.height, this.m_MaxSize.y); this.m_PixelRect = pixelRect; } } @@ -408,11 +407,15 @@ private static void InitIcons() ContainerWindow.s_ButtonMax = "WinBtnMaxWin"; } } - public void HandleEdgesEnd(Rect windowPosition) + private bool MacWindowCanResize(Rect windowPosition) { bool flag = Mathf.Abs(windowPosition.xMax - this.position.width) < 2f; bool flag2 = Mathf.Abs(windowPosition.yMax - this.position.height) < 2f; - if (Event.current.type == EventType.Repaint && ContainerWindow.macEditor && (this.m_MinSize == Vector2.zero || this.m_MinSize != this.m_MaxSize) && flag2 && flag) + return (this.m_MinSize == Vector2.zero || this.m_MinSize != this.m_MaxSize) && flag2 && flag; + } + public void HandleEdgesEnd(Rect windowPosition) + { + if (ContainerWindow.macEditor && Event.current.type == EventType.Repaint && this.MacWindowCanResize(windowPosition)) { if (ContainerWindow.s_WindowResize == null) { @@ -460,7 +463,10 @@ public void HandleEdgesStart(Rect windowPosition) this.ToggleMaximize(); } } - this.DragWindowEdgesMac(left, flag, flag2, bottom, windowPosition); + if (this.MacWindowCanResize(windowPosition)) + { + this.DragWindowEdgesMac(left, flag, flag2, bottom, windowPosition); + } } else { @@ -603,7 +609,6 @@ private void DragEdges(Rect position, IEnumerable edges, Vector2 windo if (position.Contains(current.mousePosition) && GUIUtility.hotControl == 0 && current.button == 0) { GUIUtility.hotControl = controlID; - this.SetIsDragging(true); Event.current.Use(); ContainerWindow.s_LastDragMousePos = GUIUtility.GUIToScreenPoint(current.mousePosition); ContainerWindow.s_DragStartMousePos = ContainerWindow.s_LastDragMousePos; @@ -618,7 +623,6 @@ private void DragEdges(Rect position, IEnumerable edges, Vector2 windo if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; - this.SetIsDragging(false); Event.current.Use(); } break; diff --git a/UnityEditor/UnityEditor/CreateBuiltinWindows.cs b/UnityEditor/UnityEditor/CreateBuiltinWindows.cs index f4d513a0..6579af73 100644 --- a/UnityEditor/UnityEditor/CreateBuiltinWindows.cs +++ b/UnityEditor/UnityEditor/CreateBuiltinWindows.cs @@ -40,6 +40,11 @@ private static void ShowProfilerWindow() { EditorWindow.GetWindow(); } + [MenuItem("Window/Audio Mixer %8", false, 2008)] + private static void ShowAudioMixer() + { + AudioMixerWindow.Create(); + } private static void ShowVersionControl() { if (EditorSettings.externalVersionControl == ExternalVersionControl.AssetServer) diff --git a/UnityEditor/UnityEditor/CubemapInspector.cs b/UnityEditor/UnityEditor/CubemapInspector.cs new file mode 100644 index 00000000..647573bb --- /dev/null +++ b/UnityEditor/UnityEditor/CubemapInspector.cs @@ -0,0 +1,159 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(Cubemap))] + internal class CubemapInspector : TextureInspector + { + private const int kTextureSize = 64; + private static readonly string[] kSizes = new string[] + { + "16", + "32", + "64", + "128", + "256", + "512", + "1024", + "2048" + }; + private static readonly int[] kSizesValues = new int[] + { + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048 + }; + private Texture2D[] m_Images; + protected override void OnEnable() + { + base.OnEnable(); + this.InitTexturesFromCubemap(); + } + protected override void OnDisable() + { + base.OnDisable(); + if (this.m_Images != null) + { + for (int i = 0; i < this.m_Images.Length; i++) + { + if (this.m_Images[i] && !EditorUtility.IsPersistent(this.m_Images[i])) + { + UnityEngine.Object.DestroyImmediate(this.m_Images[i]); + } + } + } + this.m_Images = null; + } + private void InitTexturesFromCubemap() + { + Cubemap cubemap = this.target as Cubemap; + if (cubemap != null) + { + if (this.m_Images == null) + { + this.m_Images = new Texture2D[6]; + } + for (int i = 0; i < this.m_Images.Length; i++) + { + if (this.m_Images[i] && !EditorUtility.IsPersistent(this.m_Images[i])) + { + UnityEngine.Object.DestroyImmediate(this.m_Images[i]); + } + if (TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i)) + { + this.m_Images[i] = TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i); + } + else + { + this.m_Images[i] = new Texture2D(64, 64, TextureFormat.ARGB32, false); + this.m_Images[i].hideFlags = HideFlags.HideAndDontSave; + TextureUtil.CopyCubemapFaceIntoTexture(cubemap, (CubemapFace)i, this.m_Images[i]); + } + } + } + } + public override void OnInspectorGUI() + { + if (this.m_Images == null) + { + this.InitTexturesFromCubemap(); + } + EditorGUIUtility.labelWidth = 50f; + Cubemap cubemap = this.target as Cubemap; + if (cubemap == null) + { + return; + } + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Right\n(+X)", CubemapFace.PositiveX); + this.ShowFace("Left\n(-X)", CubemapFace.NegativeX); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Top\n(+Y)", CubemapFace.PositiveY); + this.ShowFace("Bottom\n(-Y)", CubemapFace.NegativeY); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + this.ShowFace("Front\n(+Z)", CubemapFace.PositiveZ); + this.ShowFace("Back\n(-Z)", CubemapFace.NegativeZ); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + EditorGUIUtility.labelWidth = 0f; + EditorGUILayout.Space(); + EditorGUI.BeginChangeCheck(); + int num = TextureUtil.GetGLWidth(cubemap); + num = EditorGUILayout.IntPopup("Face size", num, CubemapInspector.kSizes, CubemapInspector.kSizesValues, new GUILayoutOption[0]); + int num2 = TextureUtil.CountMipmaps(cubemap); + bool useMipmap = EditorGUILayout.Toggle("MipMaps", num2 > 1, new GUILayoutOption[0]); + bool flag = TextureUtil.GetLinearSampled(cubemap); + flag = EditorGUILayout.Toggle("Linear", flag, new GUILayoutOption[0]); + bool flag2 = TextureUtil.IsCubemapReadable(cubemap); + flag2 = EditorGUILayout.Toggle("Readable", flag2, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (TextureUtil.ReformatCubemap(ref cubemap, num, num, cubemap.format, useMipmap, flag)) + { + this.InitTexturesFromCubemap(); + } + TextureUtil.MarkCubemapReadable(cubemap, flag2); + cubemap.Apply(); + } + } + internal override void OnAssetStoreInspectorGUI() + { + this.OnInspectorGUI(); + } + private void ShowFace(string label, CubemapFace face) + { + Cubemap cubemapRef = this.target as Cubemap; + GUI.changed = false; + Texture2D texture2D = (Texture2D)CubemapInspector.ObjectField(label, this.m_Images[(int)face], typeof(Texture2D), false, new GUILayoutOption[0]); + if (GUI.changed) + { + TextureUtil.CopyTextureIntoCubemapFace(texture2D, cubemapRef, face); + this.m_Images[(int)face] = texture2D; + } + } + public static UnityEngine.Object ObjectField(string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + Rect position = GUILayoutUtility.GetRect(EditorGUIUtility.labelWidth, 32f, EditorStyles.label, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + GUI.Label(position, label, EditorStyles.label); + position = GUILayoutUtility.GetAspectRect(1f, EditorStyles.objectField, new GUILayoutOption[] + { + GUILayout.Width(64f) + }); + UnityEngine.Object result = EditorGUI.ObjectField(position, obj, objType, allowSceneObjects); + GUILayout.EndHorizontal(); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/CubemapPreview.cs b/UnityEditor/UnityEditor/CubemapPreview.cs new file mode 100644 index 00000000..2cb62438 --- /dev/null +++ b/UnityEditor/UnityEditor/CubemapPreview.cs @@ -0,0 +1,192 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class CubemapPreview + { + private enum PreviewType + { + RGB, + Alpha + } + [SerializeField] + private CubemapPreview.PreviewType m_PreviewType; + [SerializeField] + private float m_MipLevel; + private float m_Intensity = 1f; + private PreviewRenderUtility m_PreviewUtility; + private Mesh m_Mesh; + public Vector2 m_PreviewDir = new Vector2(0f, 0f); + private static GUIContent s_SmallZoom; + private static GUIContent s_LargeZoom; + private static GUIContent s_AlphaIcon; + private static GUIContent s_RGBIcon; + private static GUIStyle s_PreButton; + private static GUIStyle s_PreSlider; + private static GUIStyle s_PreSliderThumb; + private static GUIStyle s_PreLabel; + public float mipLevel + { + get + { + return this.m_MipLevel; + } + set + { + this.m_MipLevel = value; + } + } + public void OnDisable() + { + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + } + public float GetMipLevelForRendering(Texture texture) + { + return Mathf.Min(this.m_MipLevel, (float)TextureUtil.CountMipmaps(texture)); + } + public void SetIntensity(float intensity) + { + this.m_Intensity = intensity; + } + private void InitPreview() + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility + { + m_CameraFieldOfView = 30f + }; + } + if (this.m_Mesh == null) + { + this.m_Mesh = PreviewRenderUtility.GetPreviewSphere(); + } + CubemapPreview.s_SmallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); + CubemapPreview.s_LargeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); + CubemapPreview.s_AlphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); + CubemapPreview.s_RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); + CubemapPreview.s_PreButton = "preButton"; + CubemapPreview.s_PreSlider = "preSlider"; + CubemapPreview.s_PreSliderThumb = "preSliderThumb"; + CubemapPreview.s_PreLabel = "preLabel"; + } + public void OnPreviewSettings(UnityEngine.Object[] targets) + { + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + return; + } + GUI.enabled = true; + this.InitPreview(); + bool flag = true; + bool flag2 = true; + bool flag3 = false; + int num = 8; + for (int i = 0; i < targets.Length; i++) + { + Texture texture = (Texture)targets[i]; + num = Mathf.Max(num, TextureUtil.CountMipmaps(texture)); + Cubemap cubemap = texture as Cubemap; + if (cubemap) + { + TextureFormat format = cubemap.format; + if (!TextureUtil.IsAlphaOnlyTextureFormat(format)) + { + flag2 = false; + } + if (TextureUtil.HasAlphaTextureFormat(format) && TextureUtil.GetUsageMode(texture) == TextureUsageMode.Default) + { + flag3 = true; + } + } + else + { + flag3 = true; + flag2 = false; + } + } + if (flag2) + { + this.m_PreviewType = CubemapPreview.PreviewType.Alpha; + flag = false; + } + else + { + if (!flag3) + { + this.m_PreviewType = CubemapPreview.PreviewType.RGB; + flag = false; + } + } + if (flag) + { + GUIContent[] array = new GUIContent[] + { + CubemapPreview.s_RGBIcon, + CubemapPreview.s_AlphaIcon + }; + int previewType = (int)this.m_PreviewType; + if (GUILayout.Button(array[previewType], CubemapPreview.s_PreButton, new GUILayoutOption[0])) + { + this.m_PreviewType = (previewType + CubemapPreview.PreviewType.Alpha) % (CubemapPreview.PreviewType)array.Length; + } + } + GUI.enabled = (num != 1); + GUILayout.Box(CubemapPreview.s_SmallZoom, CubemapPreview.s_PreLabel, new GUILayoutOption[0]); + GUI.changed = false; + this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, CubemapPreview.s_PreSlider, CubemapPreview.s_PreSliderThumb, new GUILayoutOption[] + { + GUILayout.MaxWidth(64f) + })); + GUILayout.Box(CubemapPreview.s_LargeZoom, CubemapPreview.s_PreLabel, new GUILayoutOption[0]); + GUI.enabled = true; + } + public void OnPreviewGUI(Texture t, Rect r, GUIStyle background) + { + if (t == null) + { + return; + } + if (!ShaderUtil.hardwareSupportsRectRenderTexture) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Cubemap preview requires\nrender texture support"); + } + return; + } + this.InitPreview(); + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); + if (Event.current.type != EventType.Repaint) + { + return; + } + this.m_PreviewUtility.BeginPreview(r, background); + bool fog = RenderSettings.fog; + Unsupported.SetRenderSettingsUseFogNoDirty(false); + this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 3f; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; + Quaternion quaternion = Quaternion.Euler(this.m_PreviewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.m_PreviewDir.x, 0f); + Material material = EditorGUIUtility.LoadRequired("Previews/PreviewCubemapMaterial.mat") as Material; + material.mainTexture = t; + material.SetMatrix("_CubemapRotation", Matrix4x4.TRS(Vector3.zero, quaternion, Vector3.one)); + float mipLevelForRendering = this.GetMipLevelForRendering(t); + material.SetFloat("_Mip", mipLevelForRendering); + material.SetFloat("_Alpha", (this.m_PreviewType != CubemapPreview.PreviewType.Alpha) ? 0f : 1f); + material.SetFloat("_Intensity", this.m_Intensity); + this.m_PreviewUtility.DrawMesh(this.m_Mesh, Vector3.zero, quaternion, material, 0); + this.m_PreviewUtility.m_Camera.Render(); + Unsupported.SetRenderSettingsUseFogNoDirty(fog); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); + if (mipLevelForRendering != 0f) + { + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Mip " + mipLevelForRendering); + } + } + } +} diff --git a/UnityEditor/UnityEditor/CubemapTextureInspector.cs b/UnityEditor/UnityEditor/CubemapTextureInspector.cs deleted file mode 100644 index 348d4578..00000000 --- a/UnityEditor/UnityEditor/CubemapTextureInspector.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System; -using UnityEngine; -namespace UnityEditor -{ - [CustomEditor(typeof(Cubemap))] - internal class CubemapTextureInspector : Editor - { - private const int kTextureSize = 64; - private static string[] kSizes = new string[] - { - "16", - "32", - "64", - "128", - "256", - "512", - "1024", - "2048" - }; - private static int[] kSizesValues = new int[] - { - 16, - 32, - 64, - 128, - 256, - 512, - 1024, - 2048 - }; - private PreviewRenderUtility m_PreviewUtility; - private Texture2D[] images; - private Material m_Material; - private Mesh m_Mesh; - public Vector2 previewDir = new Vector2(0f, 0f); - public void OnEnable() - { - this.InitTexturesFromCubemap(); - } - public void OnDisable() - { - if (this.images != null) - { - for (int i = 0; i < 6; i++) - { - if (!EditorUtility.IsPersistent(this.images[i])) - { - UnityEngine.Object.DestroyImmediate(this.images[i]); - } - } - } - this.images = null; - if (this.m_PreviewUtility != null) - { - this.m_PreviewUtility.Cleanup(); - this.m_PreviewUtility = null; - } - if (this.m_Material) - { - UnityEngine.Object.DestroyImmediate(this.m_Material.shader, true); - UnityEngine.Object.DestroyImmediate(this.m_Material, true); - this.m_Material = null; - } - } - private void InitTexturesFromCubemap() - { - Cubemap cubemap = this.target as Cubemap; - if (cubemap != null) - { - if (this.images == null) - { - this.images = new Texture2D[6]; - } - for (int i = 0; i < 6; i++) - { - if (this.images[i] && !EditorUtility.IsPersistent(this.images[i])) - { - UnityEngine.Object.DestroyImmediate(this.images[i]); - } - if (TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i)) - { - this.images[i] = TextureUtil.GetSourceTexture(cubemap, (CubemapFace)i); - } - else - { - this.images[i] = new Texture2D(64, 64, TextureFormat.ARGB32, false); - this.images[i].hideFlags = HideFlags.HideAndDontSave; - TextureUtil.CopyCubemapFaceIntoTexture(cubemap, (CubemapFace)i, this.images[i]); - } - } - } - } - public override void OnInspectorGUI() - { - if (this.images == null) - { - this.InitTexturesFromCubemap(); - } - EditorGUIUtility.labelWidth = 50f; - Cubemap cubemap = this.target as Cubemap; - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - this.ShowFace("Right\n(+X)", CubemapFace.PositiveX); - this.ShowFace("Left\n(-X)", CubemapFace.NegativeX); - GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - this.ShowFace("Top\n(+Y)", CubemapFace.PositiveY); - this.ShowFace("Bottom\n(-Y)", CubemapFace.NegativeY); - GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - this.ShowFace("Front\n(+Z)", CubemapFace.PositiveZ); - this.ShowFace("Back\n(-Z)", CubemapFace.NegativeZ); - GUILayout.EndHorizontal(); - GUILayout.EndVertical(); - EditorGUIUtility.labelWidth = 0f; - EditorGUILayout.Space(); - EditorGUI.BeginChangeCheck(); - int num = TextureUtil.GetGLWidth(cubemap); - num = EditorGUILayout.IntPopup("Face size", num, CubemapTextureInspector.kSizes, CubemapTextureInspector.kSizesValues, new GUILayoutOption[0]); - int num2 = TextureUtil.CountMipmaps(cubemap); - bool useMipmap = EditorGUILayout.Toggle("MipMaps", num2 > 1, new GUILayoutOption[0]); - bool flag = TextureUtil.GetLinearSampled(cubemap); - flag = EditorGUILayout.Toggle("Linear", flag, new GUILayoutOption[0]); - bool flag2 = TextureUtil.IsCubemapReadable(cubemap); - flag2 = EditorGUILayout.Toggle("Readable", flag2, new GUILayoutOption[0]); - if (EditorGUI.EndChangeCheck()) - { - if (TextureUtil.ReformatCubemap(ref cubemap, num, num, cubemap.format, useMipmap, flag)) - { - this.InitTexturesFromCubemap(); - } - TextureUtil.MarkCubemapReadable(cubemap, flag2); - cubemap.Apply(); - } - } - internal override void OnAssetStoreInspectorGUI() - { - this.OnInspectorGUI(); - } - private void ShowFace(string label, CubemapFace face) - { - Cubemap cubemapRef = this.target as Cubemap; - GUI.changed = false; - Texture2D texture2D = (Texture2D)CubemapTextureInspector.ObjectField(label, this.images[(int)face], typeof(Texture2D), false, new GUILayoutOption[0]); - if (GUI.changed) - { - TextureUtil.CopyTextureIntoCubemapFace(texture2D, cubemapRef, face); - this.images[(int)face] = texture2D; - } - } - public static UnityEngine.Object ObjectField(string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) - { - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - Rect position = GUILayoutUtility.GetRect(EditorGUIUtility.labelWidth, 32f, EditorStyles.label, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - }); - GUI.Label(position, label, EditorStyles.label); - position = GUILayoutUtility.GetAspectRect(1f, EditorStyles.objectField, new GUILayoutOption[] - { - GUILayout.Width(64f) - }); - UnityEngine.Object result = EditorGUI.ObjectField(position, obj, objType, allowSceneObjects); - GUILayout.EndHorizontal(); - return result; - } - private void InitPreview() - { - if (this.m_PreviewUtility == null) - { - this.m_PreviewUtility = new PreviewRenderUtility(); - this.m_PreviewUtility.m_CameraFieldOfView = 30f; - this.m_Material = new Material("Shader \"Hidden/CubemapInspector\" {\n Properties {\n\t _MainTex (\"\", Cube) = \"\" { TexGen CubeReflect }\n }\n SubShader {\n Tags { \"ForceSupported\" = \"True\" } \n\t Pass { SetTexture[_MainTex] { matrix [_CubemapRotation] combine texture } }\n }\n Fallback Off\n }"); - this.m_Material.hideFlags = HideFlags.HideAndDontSave; - this.m_Material.shader.hideFlags = HideFlags.HideAndDontSave; - this.m_Material.mainTexture = (this.target as Texture); - } - if (this.m_Mesh == null) - { - GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); - gameObject.SetActive(false); - foreach (Transform transform in gameObject.transform) - { - if (transform.name == "sphere") - { - this.m_Mesh = ((MeshFilter)transform.GetComponent(typeof(MeshFilter))).sharedMesh; - } - } - } - } - public override bool HasPreviewGUI() - { - return this.target != null; - } - public override void OnPreviewSettings() - { - if (!ShaderUtil.hardwareSupportsRectRenderTexture) - { - return; - } - GUI.enabled = true; - this.InitPreview(); - } - public override void OnPreviewGUI(Rect r, GUIStyle background) - { - if (!ShaderUtil.hardwareSupportsRectRenderTexture) - { - if (Event.current.type == EventType.Repaint) - { - EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40f), "Cubemap preview requires\nrender texture support"); - } - return; - } - this.InitPreview(); - this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); - if (Event.current.type != EventType.Repaint) - { - return; - } - this.m_PreviewUtility.BeginPreview(r, background); - bool fog = RenderSettings.fog; - Unsupported.SetRenderSettingsUseFogNoDirty(false); - this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 3f; - this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; - Quaternion quaternion = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); - this.m_Material.SetMatrix("_CubemapRotation", Matrix4x4.TRS(Vector3.zero, quaternion, Vector3.one)); - this.m_PreviewUtility.DrawMesh(this.m_Mesh, Vector3.zero, quaternion, this.m_Material, 0); - this.m_PreviewUtility.m_Camera.Render(); - Unsupported.SetRenderSettingsUseFogNoDirty(fog); - Texture image = this.m_PreviewUtility.EndPreview(); - GUI.DrawTexture(r, image, ScaleMode.StretchToFill, false); - } - } -} diff --git a/UnityEditor/UnityEditor/CurveEditor.cs b/UnityEditor/UnityEditor/CurveEditor.cs index 88de14e3..535c2fe1 100644 --- a/UnityEditor/UnityEditor/CurveEditor.cs +++ b/UnityEditor/UnityEditor/CurveEditor.cs @@ -290,19 +290,15 @@ public CurveWrapper getCurveWrapperById(int id) } return null; } - private void ApplySettings() - { - base.hRangeLocked = base.settings.hRangeLocked; - base.vRangeLocked = base.settings.vRangeLocked; - base.hRangeMin = base.settings.hRangeMin; - base.hRangeMax = base.settings.hRangeMax; - base.vRangeMin = base.settings.vRangeMin; - base.vRangeMax = base.settings.vRangeMax; - base.scaleWithWindow = base.settings.scaleWithWindow; - base.hSlider = base.settings.hSlider; - base.vSlider = base.settings.vSlider; + protected override void ApplySettings() + { + base.ApplySettings(); this.RecalculateBounds(); } + internal void ClearSelection() + { + this.m_Selection.Clear(); + } internal void ClearDisplayedSelection() { this.m_DisplayedSelection = null; @@ -1406,7 +1402,7 @@ private void SelectPoints() HandleUtility.Repaint(); } } - goto IL_3D0; + goto IL_3E3; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { @@ -1414,19 +1410,24 @@ private void SelectPoints() this.s_PickMode = CurveEditor.PickMode.None; Event.current.Use(); } - goto IL_3D0; + goto IL_3E3; case EventType.MouseMove: + { IL_39: if (typeForControl == EventType.Layout) { HandleUtility.AddDefaultControl(controlID); - goto IL_3D0; + goto IL_3E3; } if (typeForControl != EventType.ContextClick) { - goto IL_3D0; + goto IL_3E3; } - if (base.drawRect.Contains(GUIClip.Unclip(Event.current.mousePosition))) + Rect drawRect = base.drawRect; + float num = 0f; + drawRect.y = num; + drawRect.x = num; + if (drawRect.Contains(Event.current.mousePosition)) { Vector2 vector; int curveAtPosition = this.GetCurveAtPosition(base.mousePositionInDrawing, out vector); @@ -1438,7 +1439,8 @@ private void SelectPoints() Event.current.Use(); } } - goto IL_3D0; + goto IL_3E3; + } case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { @@ -1465,17 +1467,17 @@ private void SelectPoints() CurveWrapper curveWrapper = animationCurves[i]; if (!curveWrapper.readOnly && !curveWrapper.hidden) { - int num = 0; + int num2 = 0; Keyframe[] keys = curveWrapper.curve.keys; for (int j = 0; j < keys.Length; j++) { Keyframe keyframe = keys[j]; if (rect.Contains(this.GetGUIPoint(new Vector2(keyframe.time, keyframe.value)))) { - list2.Add(new CurveSelection(curveWrapper.id, this, num)); + list2.Add(new CurveSelection(curveWrapper.id, this, num2)); this.MoveCurveToFront(curveWrapper.id); } - num++; + num2++; } } } @@ -1485,10 +1487,10 @@ private void SelectPoints() } current.Use(); } - goto IL_3D0; + goto IL_3E3; } goto IL_39; - IL_3D0: + IL_3E3: if (this.s_PickMode == CurveEditor.PickMode.Marquee) { GUI.Label(EditorGUIExt.FromToRect(this.s_StartMouseDragPosition, this.s_EndMouseDragPosition), GUIContent.none, this.ms_Styles.selectionRect); @@ -1964,7 +1966,7 @@ private void DrawCurves(CurveWrapper[] curves) { return; } - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); GL.Color(this.m_TangentColor * new Color(1f, 1f, 1f, 0.75f)); foreach (CurveSelection current in list) @@ -2150,7 +2152,7 @@ public void DrawRegion(CurveWrapper curve1, CurveWrapper curve2, bool hasFocus) } } Shader.SetGlobalColor("_HandleColor", color); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(4); int num = list.Count / 3; for (int j = 0; j < num; j++) @@ -2353,7 +2355,7 @@ public void GridGUI() Rect shownArea = base.shownArea; base.hTicks.SetRanges(shownArea.xMin * axisUiScalars.x, shownArea.xMax * axisUiScalars.x, base.drawRect.xMin, base.drawRect.xMax); base.vTicks.SetRanges(shownArea.yMin * axisUiScalars.y, shownArea.yMax * axisUiScalars.y, base.drawRect.yMin, base.drawRect.yMax); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); base.hTicks.SetTickStrengths((float)base.settings.hTickStyle.distMin, (float)base.settings.hTickStyle.distFull, false); float num; diff --git a/UnityEditor/UnityEditor/CurveEditorWindow.cs b/UnityEditor/UnityEditor/CurveEditorWindow.cs index 97f734a9..d690d972 100644 --- a/UnityEditor/UnityEditor/CurveEditorWindow.cs +++ b/UnityEditor/UnityEditor/CurveEditorWindow.cs @@ -425,7 +425,7 @@ private void OnGUI() } private void PresetDropDown(Rect rect) { - if (EditorGUI.ButtonMouseDown(rect, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText) && this.m_Curve != null) + if (EditorGUI.ButtonMouseDown(rect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText) && this.m_Curve != null) { if (this.m_CurvePresets == null) { @@ -490,7 +490,7 @@ private void DoWrapperPopups() Keyframe keyframe = this.m_Curve.keys[0]; Vector3 lhs = new Vector3(keyframe.time, keyframe.value); lhs = this.m_CurveEditor.DrawingToViewTransformPoint(lhs); - Rect position = new Rect(lhs.x - num - 6f, lhs.y, num, 17f); + Rect position = new Rect(lhs.x - num + 30f, lhs.y, num, 17f); WrapMode wrapMode = (this.m_Curve == null) ? WrapMode.Default : this.m_Curve.preWrapMode; wrapMode = (WrapMode)EditorGUI.EnumPopup(position, (WrapModeFixedCurve)wrapMode, CurveEditorWindow.ms_Styles.curveWrapPopup); if (this.m_Curve != null && wrapMode != this.m_Curve.preWrapMode) @@ -502,7 +502,7 @@ private void DoWrapperPopups() keyframe = this.m_Curve.keys[this.m_Curve.length - 1]; lhs = new Vector3(keyframe.time, keyframe.value); lhs = this.m_CurveEditor.DrawingToViewTransformPoint(lhs); - position = new Rect(lhs.x + 6f, lhs.y, num, 17f); + position = new Rect(lhs.x - 30f, lhs.y, num, 17f); wrapMode = ((this.m_Curve == null) ? WrapMode.Default : this.m_Curve.postWrapMode); wrapMode = (WrapMode)EditorGUI.EnumPopup(position, (WrapModeFixedCurve)wrapMode, CurveEditorWindow.ms_Styles.curveWrapPopup); if (this.m_Curve != null && wrapMode != this.m_Curve.postWrapMode) diff --git a/UnityEditor/UnityEditor/CustomLaunchScreenType.cs b/UnityEditor/UnityEditor/CustomLaunchScreenType.cs new file mode 100644 index 00000000..1c75e55e --- /dev/null +++ b/UnityEditor/UnityEditor/CustomLaunchScreenType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + internal enum CustomLaunchScreenType + { + Default, + ImageAndBackground, + CustomXib + } +} diff --git a/UnityEditor/UnityEditor/D3D11FullscreenMode.cs b/UnityEditor/UnityEditor/D3D11FullscreenMode.cs new file mode 100644 index 00000000..69dd8ec7 --- /dev/null +++ b/UnityEditor/UnityEditor/D3D11FullscreenMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum D3D11FullscreenMode + { + ExclusiveMode, + FullscreenWindow + } +} diff --git a/UnityEngine/UnityEngine/SamsungTV.cs b/UnityEditor/UnityEditor/DefaultAsset.cs similarity index 56% rename from UnityEngine/UnityEngine/SamsungTV.cs rename to UnityEditor/UnityEditor/DefaultAsset.cs index 6b1509aa..95c0abcd 100644 --- a/UnityEngine/UnityEngine/SamsungTV.cs +++ b/UnityEditor/UnityEditor/DefaultAsset.cs @@ -1,23 +1,21 @@ using System; using System.Runtime.CompilerServices; -namespace UnityEngine +using UnityEngine; +namespace UnityEditor { - public sealed class SamsungTV + public sealed class DefaultAsset : UnityEngine.Object { - public enum TouchPadMode - { - Dpad, - Joystick, - Mouse - } - public static extern SamsungTV.TouchPadMode touchPadMode + internal extern string message { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; + } + internal extern bool isWarning + { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - set; + get; } } } diff --git a/UnityEditor/UnityEditor/DefaultAssetInspector.cs b/UnityEditor/UnityEditor/DefaultAssetInspector.cs new file mode 100644 index 00000000..7573f0d9 --- /dev/null +++ b/UnityEditor/UnityEditor/DefaultAssetInspector.cs @@ -0,0 +1,16 @@ +using System; +namespace UnityEditor +{ + [CustomEditor(typeof(DefaultAsset))] + internal class DefaultAssetInspector : Editor + { + public override void OnInspectorGUI() + { + DefaultAsset defaultAsset = (DefaultAsset)this.target; + if (defaultAsset.message.Length > 0) + { + EditorGUILayout.HelpBox(defaultAsset.message, (!defaultAsset.isWarning) ? MessageType.Info : MessageType.Warning); + } + } + } +} diff --git a/UnityEditor/UnityEditor/DefaultReflectionMode.cs b/UnityEditor/UnityEditor/DefaultReflectionMode.cs new file mode 100644 index 00000000..fc8fe023 --- /dev/null +++ b/UnityEditor/UnityEditor/DefaultReflectionMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + internal enum DefaultReflectionMode + { + FromSkybox, + Custom + } +} diff --git a/UnityEditor/UnityEditor/DeleteWindowLayout.cs b/UnityEditor/UnityEditor/DeleteWindowLayout.cs index c9a08eb6..d1cd9e19 100644 --- a/UnityEditor/UnityEditor/DeleteWindowLayout.cs +++ b/UnityEditor/UnityEditor/DeleteWindowLayout.cs @@ -7,6 +7,7 @@ namespace UnityEditor { internal class DeleteWindowLayout : EditorWindow { + private const int kMaxLayoutNameLength = 15; internal string[] m_Paths; private Vector2 m_ScrollPos; private void InitializePaths() @@ -31,15 +32,19 @@ private void OnGUI() { this.InitializePaths(); } - this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, "OL Box", new GUILayoutOption[0]); + this.m_ScrollPos = EditorGUILayout.BeginScrollView(this.m_ScrollPos, new GUILayoutOption[0]); string[] paths = this.m_Paths; for (int i = 0; i < paths.Length; i++) { string path = paths[i]; - string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path); - if (GUILayout.Button(fileNameWithoutExtension, new GUILayoutOption[0])) + string text = Path.GetFileNameWithoutExtension(path); + if (text.Length > 15) { - if (Toolbar.lastLoadedLayoutName == fileNameWithoutExtension) + text = text.Substring(0, 15) + "..."; + } + if (GUILayout.Button(text, new GUILayoutOption[0])) + { + if (Toolbar.lastLoadedLayoutName == text) { Toolbar.lastLoadedLayoutName = null; } diff --git a/UnityEditor/UnityEditor/DesktopPluginImporterExtension.cs b/UnityEditor/UnityEditor/DesktopPluginImporterExtension.cs new file mode 100644 index 00000000..e5115ae5 --- /dev/null +++ b/UnityEditor/UnityEditor/DesktopPluginImporterExtension.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor.Modules; +using UnityEngine; +namespace UnityEditor +{ + internal class DesktopPluginImporterExtension : DefaultPluginImporterExtension + { + internal enum DesktopPluginCPUArchitecture + { + None, + AnyCPU, + x86, + x86_64 + } + internal class DesktopSingleCPUProperty : DefaultPluginImporterExtension.Property + { + internal bool isCpuTargetEnabled + { + get + { + return (int)base.value == (int)base.defaultValue; + } + private set + { + base.value = ((!value) ? DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.None : base.defaultValue); + } + } + public DesktopSingleCPUProperty(GUIContent name, string platformName) : this(name, platformName, DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.AnyCPU) + { + } + public DesktopSingleCPUProperty(GUIContent name, string platformName, DesktopPluginImporterExtension.DesktopPluginCPUArchitecture architecture) : base(name, "CPU", architecture, platformName) + { + } + internal override void OnGUI(PluginImporterInspector inspector) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + this.isCpuTargetEnabled = EditorGUILayout.Toggle(base.name, this.isCpuTargetEnabled, new GUILayoutOption[0]); + EditorGUILayout.EndHorizontal(); + } + } + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_WindowsX86; + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_WindowsX86_X64; + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_LinuxX86; + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_LinuxX86_X64; + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_OSXX86; + private DesktopPluginImporterExtension.DesktopSingleCPUProperty m_OSXX86_X64; + public DesktopPluginImporterExtension() : base(null) + { + this.properties = this.GetProperties(); + } + private DefaultPluginImporterExtension.Property[] GetProperties() + { + List list = new List(); + this.m_WindowsX86 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneWindows)); + this.m_WindowsX86_X64 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86_x64"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneWindows64)); + this.m_LinuxX86 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneLinux), DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.x86); + this.m_LinuxX86_X64 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86_x64"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneLinux64), DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.x86_64); + this.m_OSXX86 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneOSXIntel)); + this.m_OSXX86_X64 = new DesktopPluginImporterExtension.DesktopSingleCPUProperty(EditorGUIUtility.TextContent("x86_x64"), BuildPipeline.GetBuildTargetName(BuildTarget.StandaloneOSXIntel64)); + list.Add(this.m_WindowsX86); + list.Add(this.m_WindowsX86_X64); + list.Add(this.m_LinuxX86); + list.Add(this.m_LinuxX86_X64); + list.Add(this.m_OSXX86); + list.Add(this.m_OSXX86_X64); + return list.ToArray(); + } + private DesktopPluginImporterExtension.DesktopPluginCPUArchitecture CalculateMultiCPUArchitecture(bool x86, bool x64) + { + if (x86 && x64) + { + return DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.AnyCPU; + } + if (x86 && !x64) + { + return DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.x86; + } + if (!x86 && x64) + { + return DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.x86_64; + } + return DesktopPluginImporterExtension.DesktopPluginCPUArchitecture.None; + } + private bool IsUsableOnWindows(PluginImporter imp) + { + if (!imp.isNativePlugin) + { + return true; + } + string extension = Path.GetExtension(imp.assetPath); + return extension == ".dll"; + } + private bool IsUsableOnOSX(PluginImporter imp) + { + if (!imp.isNativePlugin) + { + return true; + } + string extension = Path.GetExtension(imp.assetPath); + return extension == ".so" || extension == ".bundle"; + } + private bool IsUsableOnLinux(PluginImporter imp) + { + if (!imp.isNativePlugin) + { + return true; + } + string extension = Path.GetExtension(imp.assetPath); + return extension == ".so"; + } + public override void OnPlatformSettingsGUI(PluginImporterInspector inspector) + { + PluginImporter importer = inspector.importer; + EditorGUI.BeginChangeCheck(); + if (this.IsUsableOnWindows(importer)) + { + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("BuildSettings.StandaloneWindows"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_WindowsX86.OnGUI(inspector); + this.m_WindowsX86_X64.OnGUI(inspector); + EditorGUILayout.Space(); + } + if (this.IsUsableOnLinux(importer)) + { + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("BuildSettings.StandaloneLinux"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_LinuxX86.OnGUI(inspector); + this.m_LinuxX86_X64.OnGUI(inspector); + EditorGUILayout.Space(); + } + if (this.IsUsableOnOSX(importer)) + { + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("BuildSettings.StandaloneOSXIntel"), EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_OSXX86.OnGUI(inspector); + this.m_OSXX86_X64.OnGUI(inspector); + } + if (EditorGUI.EndChangeCheck()) + { + inspector.importer.SetPlatformData(BuildTarget.StandaloneLinuxUniversal, "CPU", this.CalculateMultiCPUArchitecture(this.m_LinuxX86.isCpuTargetEnabled, this.m_LinuxX86_X64.isCpuTargetEnabled).ToString()); + inspector.importer.SetPlatformData(BuildTarget.StandaloneOSXUniversal, "CPU", this.CalculateMultiCPUArchitecture(this.m_OSXX86.isCpuTargetEnabled, this.m_OSXX86_X64.isCpuTargetEnabled).ToString()); + this.hasModified = true; + } + } + public override string CalculateFinalPluginPath(string platformName, PluginImporter imp) + { + string platformData = imp.GetPlatformData(platformName, "CPU"); + if (string.Compare(platformData, "None", true) == 0) + { + return string.Empty; + } + if (!string.IsNullOrEmpty(platformData) && string.Compare(platformData, "AnyCPU", true) != 0) + { + return Path.Combine(platformData, Path.GetFileName(imp.assetPath)); + } + return Path.GetFileName(imp.assetPath); + } + } +} diff --git a/UnityEditor/UnityEditor/DetailMeshWizard.cs b/UnityEditor/UnityEditor/DetailMeshWizard.cs index 2fc67fa9..6018a51f 100644 --- a/UnityEditor/UnityEditor/DetailMeshWizard.cs +++ b/UnityEditor/UnityEditor/DetailMeshWizard.cs @@ -6,8 +6,10 @@ internal class DetailMeshWizard : TerrainWizard { public GameObject m_Detail; public float m_NoiseSpread; - public float m_RandomWidth; - public float m_RandomHeight; + public float m_MinWidth; + public float m_MaxWidth; + public float m_MinHeight; + public float m_MaxHeight; public Color m_HealthyColor; public Color m_DryColor; public DetailMeshRenderMode m_RenderMode; @@ -31,8 +33,10 @@ internal void InitializeDefaults(Terrain terrain, int index) } this.m_Detail = detailPrototype.prototype; this.m_NoiseSpread = detailPrototype.noiseSpread; - this.m_RandomWidth = detailPrototype.maxWidth - 1f; - this.m_RandomHeight = detailPrototype.maxHeight - 1f; + this.m_MinWidth = detailPrototype.minWidth; + this.m_MaxWidth = detailPrototype.maxWidth; + this.m_MinHeight = detailPrototype.minHeight; + this.m_MaxHeight = detailPrototype.maxHeight; this.m_HealthyColor = detailPrototype.healthyColor; this.m_DryColor = detailPrototype.dryColor; switch (detailPrototype.renderMode) @@ -70,10 +74,10 @@ private void DoApply() array[this.m_PrototypeIndex].prototype = this.m_Detail; array[this.m_PrototypeIndex].prototypeTexture = null; array[this.m_PrototypeIndex].noiseSpread = this.m_NoiseSpread; - array[this.m_PrototypeIndex].minWidth = 1f - this.m_RandomWidth; - array[this.m_PrototypeIndex].maxWidth = 1f + this.m_RandomWidth; - array[this.m_PrototypeIndex].minHeight = 1f - this.m_RandomHeight; - array[this.m_PrototypeIndex].maxHeight = 1f + this.m_RandomHeight; + array[this.m_PrototypeIndex].minWidth = this.m_MinWidth; + array[this.m_PrototypeIndex].maxWidth = this.m_MaxWidth; + array[this.m_PrototypeIndex].minHeight = this.m_MinHeight; + array[this.m_PrototypeIndex].maxHeight = this.m_MaxHeight; array[this.m_PrototypeIndex].healthyColor = this.m_HealthyColor; array[this.m_PrototypeIndex].dryColor = this.m_DryColor; if (this.m_RenderMode == DetailMeshRenderMode.Grass) diff --git a/UnityEditor/UnityEditor/DrawCameraMode.cs b/UnityEditor/UnityEditor/DrawCameraMode.cs index 6e4deccf..5d29a89d 100644 --- a/UnityEditor/UnityEditor/DrawCameraMode.cs +++ b/UnityEditor/UnityEditor/DrawCameraMode.cs @@ -7,7 +7,23 @@ public enum DrawCameraMode Textured, Wireframe, TexturedWire, + ShadowCascades, RenderPaths, - LightmapResolution + AlphaChannel, + Overdraw, + Mipmaps, + DeferredDiffuse, + DeferredSpecular, + DeferredSmoothness, + DeferredNormal, + Charting, + Systems, + Albedo, + Emissive, + Irradiance, + Directionality, + Baked, + Clustering, + LitClustering } } diff --git a/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs b/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs index 4afe9d95..0c5c388d 100644 --- a/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs +++ b/UnityEditor/UnityEditor/DrivenRectTransformUndo.cs @@ -8,6 +8,7 @@ internal class DrivenRectTransformUndo static DrivenRectTransformUndo() { Undo.willFlushUndoRecord = (Undo.WillFlushUndoRecord)Delegate.Combine(Undo.willFlushUndoRecord, new Undo.WillFlushUndoRecord(DrivenRectTransformUndo.ForceUpdateCanvases)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(DrivenRectTransformUndo.ForceUpdateCanvases)); } private static void ForceUpdateCanvases() { diff --git a/UnityEditor/UnityEditor/DuckVolumeGUI.cs b/UnityEditor/UnityEditor/DuckVolumeGUI.cs new file mode 100644 index 00000000..410bfdae --- /dev/null +++ b/UnityEditor/UnityEditor/DuckVolumeGUI.cs @@ -0,0 +1,336 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class DuckVolumeGUI : IAudioEffectPluginGUI + { + public enum DragType + { + None, + ThresholdAndKnee, + Ratio, + MakeupGain + } + public static string kThresholdName = "Threshold"; + public static string kRatioName = "Ratio"; + public static string kMakeupGainName = "Make-up Gain"; + public static string kAttackTimeName = "Attack Time"; + public static string kReleaseTimeName = "Release Time"; + public static string kKneeName = "Knee"; + public static GUIStyle textStyle10 = DuckVolumeGUI.BuildGUIStyleForLabel(Color.grey, 10, false, FontStyle.Normal, TextAnchor.MiddleLeft); + private static DuckVolumeGUI.DragType dragtype = DuckVolumeGUI.DragType.None; + public override string Name + { + get + { + return "Duck Volume"; + } + } + public override string Description + { + get + { + return "Volume Ducking"; + } + } + public override string Vendor + { + get + { + return "Unity Technologies"; + } + } + public static GUIStyle BuildGUIStyleForLabel(Color color, int fontSize, bool wrapText, FontStyle fontstyle, TextAnchor anchor) + { + GUIStyle gUIStyle = new GUIStyle(); + gUIStyle.focused.background = gUIStyle.onNormal.background; + gUIStyle.focused.textColor = color; + gUIStyle.alignment = anchor; + gUIStyle.fontSize = fontSize; + gUIStyle.fontStyle = fontstyle; + gUIStyle.wordWrap = wrapText; + gUIStyle.clipping = TextClipping.Overflow; + gUIStyle.normal.textColor = color; + return gUIStyle; + } + public static void DrawText(float x, float y, string text) + { + GUI.Label(new Rect(x, y - 5f, 200f, 10f), new GUIContent(text, string.Empty), DuckVolumeGUI.textStyle10); + } + public static void DrawLine(float x1, float y1, float x2, float y2, Color col) + { + Handles.color = col; + Handles.DrawLine(new Vector3(x1, y1, 0f), new Vector3(x2, y2, 0f)); + } + protected static Color ScaleAlpha(Color col, float blend) + { + return new Color(col.r, col.g, col.b, col.a * blend); + } + protected static void DrawVU(Rect r, float level, float blend, bool topdown) + { + level = 1f - level; + Rect rect = new Rect(r.x + 1f, r.y + 1f + ((!topdown) ? (level * r.height) : 0f), r.width - 2f, r.y - 2f + ((!topdown) ? (r.height - level * r.height) : (level * r.height))); + AudioMixerDrawUtils.DrawRect(r, new Color(0.1f, 0.1f, 0.1f)); + AudioMixerDrawUtils.DrawRect(rect, new Color(0.6f, 0.2f, 0.2f)); + } + private static float EvaluateDuckingVolume(float x, float ratio, float threshold, float makeupGain, float knee, float dbRange, float dbMin) + { + float num = 1f / ratio; + float num2 = (knee <= 0f) ? 0f : ((num - 1f) / (4f * knee)); + float num3 = threshold - knee; + float num4 = x * dbRange + dbMin; + float num5 = num4; + float num6 = num4 - threshold; + if (num6 > -knee && num6 < knee) + { + num6 += knee; + num5 = num6 * (num2 * num6 + 1f) + num3; + } + else + { + if (num6 > 0f) + { + num5 = threshold + num * num6; + } + } + return 2f * (num5 + makeupGain - dbMin) / dbRange - 1f; + } + private static bool CurveDisplay(IAudioEffectPlugin plugin, Rect r0, ref float threshold, ref float ratio, ref float makeupGain, ref float attackTime, ref float releaseTime, ref float knee, float sidechainLevel, float outputLevel, float blend) + { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(FocusType.Passive); + Rect r = AudioCurveRendering.BeginCurveFrame(r0); + float num = 10f; + float min; + float max; + float num2; + plugin.GetFloatParameterInfo(DuckVolumeGUI.kThresholdName, out min, out max, out num2); + float min2; + float max2; + float num3; + plugin.GetFloatParameterInfo(DuckVolumeGUI.kRatioName, out min2, out max2, out num3); + float min3; + float max3; + float num4; + plugin.GetFloatParameterInfo(DuckVolumeGUI.kMakeupGainName, out min3, out max3, out num4); + float min4; + float max4; + float num5; + plugin.GetFloatParameterInfo(DuckVolumeGUI.kKneeName, out min4, out max4, out num5); + float dbRange = 100f; + float dbMin = -80f; + float num6 = r.width * (threshold - dbMin) / dbRange; + bool result = false; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (r.Contains(Event.current.mousePosition) && current.button == 0) + { + DuckVolumeGUI.dragtype = DuckVolumeGUI.DragType.None; + GUIUtility.hotControl = controlID; + EditorGUIUtility.SetWantsMouseJumping(1); + current.Use(); + if (Mathf.Abs(r.x + num6 - current.mousePosition.x) >= 10f) + { + DuckVolumeGUI.dragtype = ((current.mousePosition.x >= r.x + num6) ? DuckVolumeGUI.DragType.Ratio : DuckVolumeGUI.DragType.MakeupGain); + } + else + { + DuckVolumeGUI.dragtype = DuckVolumeGUI.DragType.ThresholdAndKnee; + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + DuckVolumeGUI.dragtype = DuckVolumeGUI.DragType.None; + GUIUtility.hotControl = 0; + EditorGUIUtility.SetWantsMouseJumping(0); + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + float num7 = (!current.alt) ? 1f : 0.25f; + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.ThresholdAndKnee) + { + bool flag = Mathf.Abs(current.delta.x) < Mathf.Abs(current.delta.y); + if (flag) + { + knee = Mathf.Clamp(knee + current.delta.y * 0.5f * num7, min4, max4); + } + else + { + threshold = Mathf.Clamp(threshold + current.delta.x * 0.1f * num7, min, max); + } + } + else + { + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.Ratio) + { + ratio = Mathf.Clamp(ratio + current.delta.y * ((ratio <= 1f) ? 0.003f : 0.05f) * num7, min2, max2); + } + else + { + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.MakeupGain) + { + makeupGain = Mathf.Clamp(makeupGain - current.delta.y * 0.5f * num7, min3, max3); + } + else + { + Debug.LogError("Drag: Unhandled enum"); + } + } + } + result = true; + current.Use(); + } + break; + } + if (current.type == EventType.Repaint) + { + HandleUtility.ApplyWireMaterial(); + float num8 = r.height * (1f - (threshold - dbMin + makeupGain) / dbRange); + Color col2 = new Color(0.7f, 0.7f, 0.7f); + Color black = Color.black; + float duckGradient = 1f / ratio; + float duckThreshold = threshold; + float duckSidechainLevel = sidechainLevel; + float duckMakeupGain = makeupGain; + float duckKnee = knee; + float duckKneeC1 = (knee <= 0f) ? 0f : ((duckGradient - 1f) / (4f * knee)); + float duckKneeC2 = duckThreshold - knee; + AudioCurveRendering.DrawFilledCurve(r, delegate(float x, out Color col) + { + float num16 = x * dbRange + dbMin; + float num17 = num16; + float num18 = num16 - duckThreshold; + col = DuckVolumeGUI.ScaleAlpha((duckSidechainLevel <= num16) ? Color.grey : AudioCurveRendering.kAudioOrange, blend); + if (num18 > -duckKnee && num18 < duckKnee) + { + num18 += duckKnee; + num17 = num18 * (duckKneeC1 * num18 + 1f) + duckKneeC2; + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.ThresholdAndKnee) + { + col = new Color(col.r * 1.2f, col.g * 1.2f, col.b * 1.2f); + } + } + else + { + if (num18 > 0f) + { + num17 = duckThreshold + duckGradient * num18; + } + } + return 2f * (num17 + duckMakeupGain - dbMin) / dbRange - 1f; + }); + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.MakeupGain) + { + AudioCurveRendering.DrawCurve(r, delegate(float x) + { + float num16 = x * dbRange + dbMin; + float num17 = num16; + float num18 = num16 - duckThreshold; + if (num18 > -duckKnee && num18 < duckKnee) + { + num18 += duckKnee; + num17 = num18 * (duckKneeC1 * num18 + 1f) + duckKneeC2; + } + else + { + if (num18 > 0f) + { + num17 = duckThreshold + duckGradient * num18; + } + } + return 2f * (num17 + duckMakeupGain - dbMin) / dbRange - 1f; + }, Color.white); + } + DuckVolumeGUI.textStyle10.normal.textColor = DuckVolumeGUI.ScaleAlpha(col2, blend); + EditorGUI.DrawRect(new Rect(r.x + num6, r.y, 1f, r.height), DuckVolumeGUI.textStyle10.normal.textColor); + DuckVolumeGUI.DrawText(r.x + num6 + 4f, r.y + 6f, string.Format("Threshold: {0:F1} dB", threshold)); + DuckVolumeGUI.textStyle10.normal.textColor = DuckVolumeGUI.ScaleAlpha(black, blend); + DuckVolumeGUI.DrawText(r.x + 4f, r.y + r.height - 10f, (sidechainLevel >= -80f) ? string.Format("Input: {0:F1} dB", sidechainLevel) : "Input: None"); + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.Ratio) + { + float num9 = r.height / r.width; + Handles.DrawAAPolyLine(2f, new Color[] + { + Color.black, + Color.black + }, new Vector3[] + { + new Vector3(r.x + num6 + r.width, r.y + num8 - num9 * r.width, 0f), + new Vector3(r.x + num6 - r.width, r.y + num8 + num9 * r.width, 0f) + }); + Handles.DrawAAPolyLine(3f, new Color[] + { + Color.white, + Color.white + }, new Vector3[] + { + new Vector3(r.x + num6 + r.width, r.y + num8 - num9 * duckGradient * r.width, 0f), + new Vector3(r.x + num6 - r.width, r.y + num8 + num9 * duckGradient * r.width, 0f) + }); + } + else + { + if (DuckVolumeGUI.dragtype == DuckVolumeGUI.DragType.ThresholdAndKnee) + { + float num10 = (threshold - knee - dbMin) / dbRange; + float num11 = (threshold + knee - dbMin) / dbRange; + float num12 = DuckVolumeGUI.EvaluateDuckingVolume(num10, ratio, threshold, makeupGain, knee, dbRange, dbMin); + float num13 = DuckVolumeGUI.EvaluateDuckingVolume(num11, ratio, threshold, makeupGain, knee, dbRange, dbMin); + float num14 = r.yMax - (num12 + 1f) * 0.5f * r.height; + float num15 = r.yMax - (num13 + 1f) * 0.5f * r.height; + EditorGUI.DrawRect(new Rect(r.x + num10 * r.width, num14, 1f, r.height - num14), new Color(0f, 0f, 0f, 0.5f)); + EditorGUI.DrawRect(new Rect(r.x + num11 * r.width - 1f, num15, 1f, r.height - num15), new Color(0f, 0f, 0f, 0.5f)); + EditorGUI.DrawRect(new Rect(r.x + num6 - 1f, r.y, 3f, r.height), Color.white); + } + } + outputLevel = (Mathf.Clamp(outputLevel - makeupGain, dbMin, dbMin + dbRange) - dbMin) / dbRange; + if (EditorApplication.isPlaying) + { + Rect r2 = new Rect(r.x + r.width - num + 2f, r.y + 2f, num - 4f, r.height - 4f); + DuckVolumeGUI.DrawVU(r2, outputLevel, blend, true); + } + } + AudioCurveRendering.EndCurveFrame(); + return result; + } + public override bool OnGUI(IAudioEffectPlugin plugin) + { + float blend = (!plugin.IsPluginEditableAndEnabled()) ? 0.5f : 1f; + float value; + plugin.GetFloatParameter(DuckVolumeGUI.kThresholdName, out value); + float value2; + plugin.GetFloatParameter(DuckVolumeGUI.kRatioName, out value2); + float value3; + plugin.GetFloatParameter(DuckVolumeGUI.kMakeupGainName, out value3); + float value4; + plugin.GetFloatParameter(DuckVolumeGUI.kAttackTimeName, out value4); + float value5; + plugin.GetFloatParameter(DuckVolumeGUI.kReleaseTimeName, out value5); + float value6; + plugin.GetFloatParameter(DuckVolumeGUI.kKneeName, out value6); + float[] array; + plugin.GetFloatBuffer("Metering", out array, 2); + GUILayout.Space(5f); + Rect rect = GUILayoutUtility.GetRect(200f, 160f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (DuckVolumeGUI.CurveDisplay(plugin, rect, ref value, ref value2, ref value3, ref value4, ref value5, ref value6, array[0], array[1], blend)) + { + plugin.SetFloatParameter(DuckVolumeGUI.kThresholdName, value); + plugin.SetFloatParameter(DuckVolumeGUI.kRatioName, value2); + plugin.SetFloatParameter(DuckVolumeGUI.kMakeupGainName, value3); + plugin.SetFloatParameter(DuckVolumeGUI.kAttackTimeName, value4); + plugin.SetFloatParameter(DuckVolumeGUI.kReleaseTimeName, value5); + plugin.SetFloatParameter(DuckVolumeGUI.kKneeName, value6); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs b/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs index 883e6a6c..796fb83a 100644 --- a/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs +++ b/UnityEditor/UnityEditor/EdgeCollider2DEditor.cs @@ -14,27 +14,8 @@ public override void OnEnable() public override void OnInspectorGUI() { base.BeginColliderInspector(); - this.ColliderInfoGUI(); + base.OnInspectorGUI(); base.EndColliderInspector(); - base.CheckColliderErrorState(); - } - private void ColliderInfoGUI() - { - EditorGUI.BeginDisabledGroup(base.targets.Length != 1); - this.m_ShowColliderInfo = EditorGUILayout.Foldout(this.m_ShowColliderInfo, "Collider Info"); - if (this.m_ShowColliderInfo) - { - EdgeCollider2D edgeCollider2D = base.targets[0] as EdgeCollider2D; - if (edgeCollider2D) - { - int pointCount = edgeCollider2D.pointCount; - string label = (!GUI.enabled) ? "---" : (string.Empty + pointCount); - EditorGUI.indentLevel++; - EditorGUILayout.LabelField("Vertices", label, new GUILayoutOption[0]); - EditorGUI.indentLevel--; - } - } - EditorGUI.EndDisabledGroup(); } protected override void OnEditStart() { diff --git a/UnityEditor/UnityEditor/Editor.cs b/UnityEditor/UnityEditor/Editor.cs index 82ff50cf..7f4499ec 100644 --- a/UnityEditor/UnityEditor/Editor.cs +++ b/UnityEditor/UnityEditor/Editor.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine; @@ -19,39 +20,19 @@ public Styles() this.inspectorBig.padding.bottom--; } } - private const float kImageSectionWidth = 44f; internal const float kLineHeight = 16f; - private static Editor.Styles s_Styles; + private const float kImageSectionWidth = 44f; private UnityEngine.Object[] m_Targets; private int m_IsDirty; private int m_ReferenceTargetIndex; private PropertyHandlerCache m_PropertyHandlerCache = new PropertyHandlerCache(); - internal IPreviewable m_Preview; + private IPreviewable m_DummyPreview; internal SerializedObject m_SerializedObject; private OptimizedGUIBlock m_OptimizedBlock; internal InspectorMode m_InspectorMode; internal bool hideInspector; internal static bool m_AllowMultiObjectAccess = true; - internal virtual IPreviewable Preview - { - get - { - if (this.m_Preview == null) - { - ObjectPreview objectPreview = new ObjectPreview(); - objectPreview.Initialize(this.targets); - this.m_Preview = objectPreview; - } - return this.m_Preview; - } - } - internal PropertyHandlerCache propertyHandlerCache - { - get - { - return this.m_PropertyHandlerCache; - } - } + private static Editor.Styles s_Styles; internal bool canEditMultipleObjects { get @@ -131,6 +112,239 @@ internal bool isInspectorDirty this.m_IsDirty = ((!value) ? 0 : 1); } } + internal virtual IPreviewable preview + { + get + { + if (this.m_DummyPreview == null) + { + this.m_DummyPreview = new ObjectPreview(); + this.m_DummyPreview.Initialize(this.targets); + } + return this.m_DummyPreview; + } + } + internal PropertyHandlerCache propertyHandlerCache + { + get + { + return this.m_PropertyHandlerCache; + } + } + [ExcludeFromDocs] + public static Editor CreateEditor(UnityEngine.Object targetObject) + { + Type editorType = null; + return Editor.CreateEditor(targetObject, editorType); + } + public static Editor CreateEditor(UnityEngine.Object targetObject, [DefaultValue("null")] Type editorType) + { + return Editor.CreateEditor(new UnityEngine.Object[] + { + targetObject + }, editorType); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Editor CreateEditor(UnityEngine.Object[] targetObjects, [DefaultValue("null")] Type editorType); + [ExcludeFromDocs] + public static Editor CreateEditor(UnityEngine.Object[] targetObjects) + { + Type editorType = null; + return Editor.CreateEditor(targetObjects, editorType); + } + public static void CreateCachedEditor(UnityEngine.Object targetObject, Type editorType, ref Editor previousEditor) + { + if (previousEditor != null && previousEditor.m_Targets.Length == 1 && previousEditor.m_Targets[0] == targetObject) + { + return; + } + if (previousEditor != null) + { + UnityEngine.Object.DestroyImmediate(previousEditor); + } + previousEditor = Editor.CreateEditor(targetObject, editorType); + } + public static void CreateCachedEditor(UnityEngine.Object[] targetObjects, Type editorType, ref Editor previousEditor) + { + if (previousEditor != null && ArrayUtility.ArrayEquals(previousEditor.m_Targets, targetObjects)) + { + return; + } + if (previousEditor != null) + { + UnityEngine.Object.DestroyImmediate(previousEditor); + } + previousEditor = Editor.CreateEditor(targetObjects, editorType); + } + internal virtual SerializedObject GetSerializedObjectInternal() + { + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(this.targets); + } + return this.m_SerializedObject; + } + private void CleanupPropertyEditor() + { + if (this.m_OptimizedBlock != null) + { + this.m_OptimizedBlock.Dispose(); + this.m_OptimizedBlock = null; + } + if (this.m_SerializedObject != null) + { + this.m_SerializedObject.Dispose(); + this.m_SerializedObject = null; + } + } + private void OnDisableINTERNAL() + { + this.CleanupPropertyEditor(); + } + internal void OnForceReloadInspector() + { + if (this.m_SerializedObject != null) + { + this.m_SerializedObject.SetIsDifferentCacheDirty(); + } + } + internal bool GetOptimizedGUIBlockImplementation(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) + { + if (this.m_OptimizedBlock == null) + { + this.m_OptimizedBlock = new OptimizedGUIBlock(); + } + block = this.m_OptimizedBlock; + if (!isVisible) + { + height = 0f; + return true; + } + if (this.m_SerializedObject == null) + { + this.m_SerializedObject = new SerializedObject(this.targets); + } + else + { + this.m_SerializedObject.Update(); + } + this.m_SerializedObject.inspectorMode = this.m_InspectorMode; + SerializedProperty iterator = this.m_SerializedObject.GetIterator(); + height = 2f; + bool enterChildren = true; + while (iterator.NextVisible(enterChildren)) + { + height += EditorGUI.GetPropertyHeight(iterator, null, true) + 2f; + enterChildren = false; + } + if (height == 2f) + { + height = 0f; + } + return true; + } + internal bool OptimizedInspectorGUIImplementation(Rect contentRect) + { + SerializedProperty iterator = this.m_SerializedObject.GetIterator(); + bool enterChildren = true; + bool enabled = GUI.enabled; + contentRect.xMin += 14f; + contentRect.xMax -= 4f; + contentRect.y += 2f; + while (iterator.NextVisible(enterChildren)) + { + contentRect.height = EditorGUI.GetPropertyHeight(iterator, null, false); + EditorGUI.indentLevel = iterator.depth; + enterChildren = EditorGUI.PropertyField(contentRect, iterator); + contentRect.y += contentRect.height + 2f; + } + GUI.enabled = enabled; + return this.m_SerializedObject.ApplyModifiedProperties(); + } + protected internal static void DrawPropertiesExcluding(SerializedObject obj, params string[] propertyToExclude) + { + SerializedProperty iterator = obj.GetIterator(); + bool enterChildren = true; + while (iterator.NextVisible(enterChildren)) + { + enterChildren = false; + if (!propertyToExclude.Contains(iterator.name)) + { + EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); + } + } + } + public bool DrawDefaultInspector() + { + return this.DoDrawDefaultInspector(); + } + public virtual void OnInspectorGUI() + { + this.DrawDefaultInspector(); + } + public virtual bool RequiresConstantRepaint() + { + return false; + } + internal void InternalSetTargets(UnityEngine.Object[] t) + { + this.m_Targets = t; + } + internal void InternalSetHidden(bool hidden) + { + this.hideInspector = hidden; + } + internal virtual bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) + { + block = null; + height = -1f; + return false; + } + internal virtual bool OnOptimizedInspectorGUI(Rect contentRect) + { + Debug.LogError("Not supported"); + return false; + } + public void Repaint() + { + InspectorWindow.RepaintAllInspectors(); + } + public virtual bool HasPreviewGUI() + { + return this.preview.HasPreviewGUI(); + } + public virtual GUIContent GetPreviewTitle() + { + return this.preview.GetPreviewTitle(); + } + public virtual Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) + { + return null; + } + public virtual void OnPreviewGUI(Rect r, GUIStyle background) + { + this.preview.OnPreviewGUI(r, background); + } + public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + this.OnPreviewGUI(r, background); + } + public virtual void OnPreviewSettings() + { + this.preview.OnPreviewSettings(); + } + public virtual string GetInfoString() + { + return this.preview.GetInfoString(); + } + internal virtual void OnAssetStoreInspectorGUI() + { + } + public virtual void ReloadPreviewInstances() + { + this.preview.ReloadPreviewInstances(); + } internal static bool DoDrawDefaultInspector(SerializedObject obj) { EditorGUI.BeginChangeCheck(); @@ -234,16 +448,11 @@ internal virtual void OnHeaderTitleGUI(Rect titleRect, string header) } internal virtual void DrawHeaderHelpAndSettingsGUI(Rect r) { - if (EditorGUI.s_HelpIcon == null) - { - EditorGUI.s_HelpIcon = EditorGUIUtility.IconContent("_Help"); - EditorGUI.s_TitleSettingsIcon = EditorGUIUtility.IconContent("_Popup"); - } UnityEngine.Object target = this.target; EditorGUI.HelpIconButton(new Rect(r.xMax - 36f, r.y + 5f, 14f, 14f), target); EditorGUI.BeginDisabledGroup(!this.IsEnabled()); Rect position = new Rect(r.xMax - 18f, r.y + 5f, 14f, 14f); - if (EditorGUI.ButtonMouseDown(position, EditorGUI.s_TitleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) + if (EditorGUI.ButtonMouseDown(position, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Native, EditorStyles.inspectorTitlebarText)) { EditorUtility.DisplayObjectContextMenu(position, this.targets, 0); } @@ -257,6 +466,10 @@ private void DrawHeaderFromInsideHierarchy() EditorGUILayout.BeginVertical(style, new GUILayoutOption[0]); } internal static Rect DrawHeaderGUI(Editor editor, string header) + { + return Editor.DrawHeaderGUI(editor, header, 0f); + } + internal static Rect DrawHeaderGUI(Editor editor, string header, float leftMargin) { if (Editor.s_Styles == null) { @@ -267,6 +480,10 @@ internal static Rect DrawHeaderGUI(Editor editor, string header) GUILayout.BeginVertical(new GUILayoutOption[0]); GUILayout.Space(19f); GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (leftMargin > 0f) + { + GUILayout.Space(leftMargin); + } if (editor) { editor.OnHeaderControlsGUI(); @@ -279,8 +496,8 @@ internal static Rect DrawHeaderGUI(Editor editor, string header) GUILayout.EndVertical(); GUILayout.EndHorizontal(); Rect lastRect = GUILayoutUtility.GetLastRect(); - float width = lastRect.width; - Rect rect = new Rect(lastRect.x + 6f, lastRect.y + 6f, 32f, 32f); + Rect r = new Rect(lastRect.x + leftMargin, lastRect.y, lastRect.width - leftMargin, lastRect.height); + Rect rect = new Rect(r.x + 6f, r.y + 6f, 32f, 32f); if (editor) { editor.OnHeaderIconGUI(rect); @@ -289,7 +506,7 @@ internal static Rect DrawHeaderGUI(Editor editor, string header) { GUI.Label(rect, AssetPreview.GetMiniTypeThumbnail(typeof(UnityEngine.Object)), Editor.s_Styles.centerStyle); } - Rect rect2 = new Rect(lastRect.x + 44f, lastRect.y + 6f, width - 44f - 38f - 4f, 16f); + Rect rect2 = new Rect(r.x + 44f, r.y + 6f, r.width - 44f - 38f - 4f, 16f); if (editor) { editor.OnHeaderTitleGUI(rect2, header); @@ -300,10 +517,10 @@ internal static Rect DrawHeaderGUI(Editor editor, string header) } if (editor) { - editor.DrawHeaderHelpAndSettingsGUI(lastRect); + editor.DrawHeaderHelpAndSettingsGUI(r); } Event current = Event.current; - if (editor != null && !editor.IsEnabled() && current.type == EventType.MouseDown && current.button == 1 && lastRect.Contains(current.mousePosition)) + if (editor != null && !editor.IsEnabled() && current.type == EventType.MouseDown && current.button == 1 && r.Contains(current.mousePosition)) { EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), editor.targets, 0); current.Use(); @@ -367,196 +584,5 @@ public void ResetTarget() { this.referenceTargetIndex = 0; } - [ExcludeFromDocs] - public static Editor CreateEditor(UnityEngine.Object obj) - { - Type editorType = null; - return Editor.CreateEditor(obj, editorType); - } - public static Editor CreateEditor(UnityEngine.Object obj, [DefaultValue("null")] Type editorType) - { - return Editor.CreateEditor(new UnityEngine.Object[] - { - obj - }, editorType); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Editor CreateEditor(UnityEngine.Object[] objects, [DefaultValue("null")] Type editorType); - [ExcludeFromDocs] - public static Editor CreateEditor(UnityEngine.Object[] objects) - { - Type editorType = null; - return Editor.CreateEditor(objects, editorType); - } - internal virtual SerializedObject GetSerializedObjectInternal() - { - if (this.m_SerializedObject == null) - { - this.m_SerializedObject = new SerializedObject(this.targets); - } - return this.m_SerializedObject; - } - private void CleanupPropertyEditor() - { - if (this.m_OptimizedBlock != null) - { - this.m_OptimizedBlock.Dispose(); - this.m_OptimizedBlock = null; - } - if (this.m_SerializedObject != null) - { - this.m_SerializedObject.Dispose(); - this.m_SerializedObject = null; - } - } - private void OnDisableINTERNAL() - { - this.CleanupPropertyEditor(); - } - internal void OnForceReloadInspector() - { - if (this.m_SerializedObject != null) - { - this.m_SerializedObject.SetIsDifferentCacheDirty(); - } - } - internal bool GetOptimizedGUIBlockImplementation(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) - { - if (this.m_OptimizedBlock == null) - { - this.m_OptimizedBlock = new OptimizedGUIBlock(); - } - block = this.m_OptimizedBlock; - if (!isVisible) - { - height = 0f; - return true; - } - if (this.m_SerializedObject == null) - { - this.m_SerializedObject = new SerializedObject(this.targets); - } - else - { - this.m_SerializedObject.Update(); - } - this.m_SerializedObject.inspectorMode = this.m_InspectorMode; - SerializedProperty iterator = this.m_SerializedObject.GetIterator(); - height = 2f; - bool enterChildren = true; - while (iterator.NextVisible(enterChildren)) - { - height += EditorGUI.GetPropertyHeight(iterator, null, true) + 2f; - enterChildren = false; - } - if (height == 2f) - { - height = 0f; - } - return true; - } - internal bool OptimizedInspectorGUIImplementation(Rect contentRect) - { - SerializedProperty iterator = this.m_SerializedObject.GetIterator(); - bool enterChildren = true; - bool enabled = GUI.enabled; - contentRect.xMin += 14f; - contentRect.xMax -= 4f; - contentRect.y += 2f; - while (iterator.NextVisible(enterChildren)) - { - contentRect.height = EditorGUI.GetPropertyHeight(iterator, null, false); - EditorGUI.indentLevel = iterator.depth; - enterChildren = EditorGUI.PropertyField(contentRect, iterator); - contentRect.y += contentRect.height + 2f; - } - GUI.enabled = enabled; - return this.m_SerializedObject.ApplyModifiedProperties(); - } - protected internal static void DrawPropertiesExcluding(SerializedObject obj, params string[] propertyToExclude) - { - SerializedProperty iterator = obj.GetIterator(); - int num = 0; - bool enterChildren = true; - while (iterator.NextVisible(enterChildren)) - { - enterChildren = false; - if (num < propertyToExclude.Length && iterator.name == propertyToExclude[num]) - { - num++; - } - else - { - EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]); - } - } - } - public bool DrawDefaultInspector() - { - return this.DoDrawDefaultInspector(); - } - public virtual void OnInspectorGUI() - { - this.DrawDefaultInspector(); - } - public virtual bool RequiresConstantRepaint() - { - return false; - } - internal void InternalSetTargets(UnityEngine.Object[] t) - { - this.m_Targets = t; - } - internal void InternalSetHidden(bool hidden) - { - this.hideInspector = hidden; - } - internal virtual bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out OptimizedGUIBlock block, out float height) - { - block = null; - height = -1f; - return false; - } - internal virtual bool OnOptimizedInspectorGUI(Rect contentRect) - { - Debug.LogError("Not supported"); - return false; - } - public void Repaint() - { - InspectorWindow.RepaintAllInspectors(); - } - public virtual bool HasPreviewGUI() - { - return this.Preview.HasPreviewGUI(); - } - public virtual GUIContent GetPreviewTitle() - { - return this.Preview.GetPreviewTitle(); - } - public virtual Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) - { - return null; - } - public virtual void OnPreviewGUI(Rect r, GUIStyle background) - { - this.Preview.OnPreviewGUI(r, background); - } - public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) - { - this.OnPreviewGUI(r, background); - } - public virtual void OnPreviewSettings() - { - this.Preview.OnPreviewSettings(); - } - public virtual string GetInfoString() - { - return this.Preview.GetInfoString(); - } - internal virtual void OnAssetStoreInspectorGUI() - { - } } } diff --git a/UnityEditor/UnityEditor/EditorApplication.cs b/UnityEditor/UnityEditor/EditorApplication.cs index 791bc1ab..bc0bf112 100644 --- a/UnityEditor/UnityEditor/EditorApplication.cs +++ b/UnityEditor/UnityEditor/EditorApplication.cs @@ -65,6 +65,12 @@ public static extern bool isUpdating [MethodImpl(MethodImplOptions.InternalCall)] get; } + public static extern bool isRemoteConnected + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern string applicationContentsPath { [WrapperlessIcall] @@ -83,6 +89,12 @@ internal static extern UnityEngine.Object tagManager [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal static extern UnityEngine.Object renderSettings + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern double timeSinceStartup { [WrapperlessIcall] @@ -94,12 +106,32 @@ public static extern double timeSinceStartup public static extern void NewScene(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void NewEmptyScene(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool OpenScene(string path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void OpenSceneAdditive(string path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadLevelInPlayMode(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void LoadLevelAdditiveInPlayMode(string path); + public static AsyncOperation LoadLevelAsyncInPlayMode(string path) + { + return EditorApplication.LoadLevelAsyncInPlayMode(path, false); + } + public static AsyncOperation LoadLevelAdditiveAsyncInPlayMode(string path) + { + return EditorApplication.LoadLevelAsyncInPlayMode(path, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AsyncOperation LoadLevelAsyncInPlayMode(string path, bool isAdditive); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool SaveScene([DefaultValue("\"\"")] string path, [DefaultValue("false")] bool saveAsCopy); [ExcludeFromDocs] public static bool SaveScene(string path) @@ -154,6 +186,9 @@ public static void OpenProject(string projectPath, params string[] args) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetSceneRepaintDirty(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MarkSceneDirty(); public static void RepaintProjectWindow() { foreach (ProjectBrowser current in ProjectBrowser.GetAllProjectBrowsers()) @@ -294,5 +329,8 @@ private static void Internal_CallGlobalEventHandler() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Beep(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ReportUNetWeaver(string filename, string msg, bool isError); } } diff --git a/UnityEditor/UnityEditor/EditorAssemblies.cs b/UnityEditor/UnityEditor/EditorAssemblies.cs index 05252f4a..f941b113 100644 --- a/UnityEditor/UnityEditor/EditorAssemblies.cs +++ b/UnityEditor/UnityEditor/EditorAssemblies.cs @@ -8,6 +8,8 @@ namespace UnityEditor { internal static class EditorAssemblies { + internal static List m_RuntimeInitializeClassInfoList; + internal static int m_TotalNumRuntimeInitializeMethods; internal static Assembly[] loadedAssemblies { get; @@ -30,23 +32,78 @@ where klass.IsSubclassOf(parent) private static void SetLoadedEditorAssemblies(Assembly[] assemblies) { EditorAssemblies.loadedAssemblies = assemblies; - EditorAssemblies.RunClassConstructors(); + EditorAssemblies.ProcessInitializeOnLoadAttributes(); } - private static void RunClassConstructors() + private static RuntimeInitializeClassInfo[] GetRuntimeInitializeClassInfos() { - foreach (Type current in EditorAssemblies.loadedTypes) + if (EditorAssemblies.m_RuntimeInitializeClassInfoList == null) { - if (current.IsDefined(typeof(InitializeOnLoadAttribute), false)) + return null; + } + return EditorAssemblies.m_RuntimeInitializeClassInfoList.ToArray(); + } + private static int GetTotalNumRuntimeInitializeMethods() + { + return EditorAssemblies.m_TotalNumRuntimeInitializeMethods; + } + private static void StoreRuntimeInitializeClassInfo(Type type, List methodNames) + { + RuntimeInitializeClassInfo runtimeInitializeClassInfo = new RuntimeInitializeClassInfo(); + runtimeInitializeClassInfo.assemblyName = type.Assembly.GetName().Name.ToString(); + runtimeInitializeClassInfo.className = type.ToString(); + runtimeInitializeClassInfo.methodNames = methodNames.ToArray(); + EditorAssemblies.m_RuntimeInitializeClassInfoList.Add(runtimeInitializeClassInfo); + EditorAssemblies.m_TotalNumRuntimeInitializeMethods += methodNames.Count; + } + private static void ProcessStaticMethodAttributes(Type type) + { + List list = null; + MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + for (int i = 0; i < methods.GetLength(0); i++) + { + MethodInfo methodInfo = methods[i]; + object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), false); + if (customAttributes != null && customAttributes.Length > 0) { - try - { - RuntimeHelpers.RunClassConstructor(current.TypeHandle); - } - catch (TypeInitializationException ex) + if (list == null) { - Debug.LogError(ex.InnerException); + list = new List(); } + list.Add(methodInfo.Name); + } + customAttributes = methodInfo.GetCustomAttributes(typeof(InitializeOnLoadMethodAttribute), false); + if (customAttributes != null && customAttributes.Length > 0) + { + methodInfo.Invoke(null, null); + } + } + if (list != null) + { + EditorAssemblies.StoreRuntimeInitializeClassInfo(type, list); + } + } + private static void ProcessEditorInitializeOnLoad(Type type) + { + try + { + RuntimeHelpers.RunClassConstructor(type.TypeHandle); + } + catch (TypeInitializationException ex) + { + Debug.LogError(ex.InnerException); + } + } + private static void ProcessInitializeOnLoadAttributes() + { + EditorAssemblies.m_TotalNumRuntimeInitializeMethods = 0; + EditorAssemblies.m_RuntimeInitializeClassInfoList = new List(); + foreach (Type current in EditorAssemblies.loadedTypes) + { + if (current.IsDefined(typeof(InitializeOnLoadAttribute), false)) + { + EditorAssemblies.ProcessEditorInitializeOnLoad(current); } + EditorAssemblies.ProcessStaticMethodAttributes(current); } } } diff --git a/UnityEditor/UnityEditor/EditorGUI.cs b/UnityEditor/UnityEditor/EditorGUI.cs index c0470cef..10343565 100644 --- a/UnityEditor/UnityEditor/EditorGUI.cs +++ b/UnityEditor/UnityEditor/EditorGUI.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Reflection; using UnityEditorInternal; using UnityEngine; using UnityEngine.Internal; @@ -9,6 +10,17 @@ namespace UnityEditor { public sealed class EditorGUI { + public class DisabledGroupScope : GUI.Scope + { + public DisabledGroupScope(bool disabled) + { + EditorGUI.BeginDisabledGroup(disabled); + } + protected override void CloseScope() + { + EditorGUI.EndDisabledGroup(); + } + } internal class RecycledTextEditor : TextEditor { internal static bool s_ActuallyEditing; @@ -179,15 +191,492 @@ internal void SetEnumValueDelegate(object userData, string[] options, int select } } } - internal struct VUMeterData + public class PropertyScope : GUI.Scope + { + public GUIContent content + { + get; + protected set; + } + public PropertyScope(Rect totalPosition, GUIContent label, SerializedProperty property) + { + this.content = EditorGUI.BeginProperty(totalPosition, label, property); + } + protected override void CloseScope() + { + EditorGUI.EndProperty(); + } + } + internal sealed class GUIContents + { + private class IconName : Attribute + { + private string m_Name; + public virtual string name + { + get + { + return this.m_Name; + } + } + public IconName(string name) + { + this.m_Name = name; + } + } + [EditorGUI.GUIContents.IconName("_Popup")] + internal static GUIContent titleSettingsIcon + { + get; + private set; + } + [EditorGUI.GUIContents.IconName("_Help")] + internal static GUIContent helpIcon + { + get; + private set; + } + static GUIContents() + { + PropertyInfo[] properties = typeof(EditorGUI.GUIContents).GetProperties(BindingFlags.Static | BindingFlags.NonPublic); + PropertyInfo[] array = properties; + for (int i = 0; i < array.Length; i++) + { + PropertyInfo propertyInfo = array[i]; + EditorGUI.GUIContents.IconName[] array2 = (EditorGUI.GUIContents.IconName[])propertyInfo.GetCustomAttributes(typeof(EditorGUI.GUIContents.IconName), false); + if (array2.Length > 0) + { + string name = array2[0].name; + GUIContent value = EditorGUIUtility.IconContent(name); + propertyInfo.SetValue(null, value, null); + } + } + } + } + internal struct KnobContext + { + private const int kPixelRange = 250; + private readonly Rect position; + private readonly Vector2 knobSize; + private readonly float currentValue; + private readonly float start; + private readonly float end; + private readonly string unit; + private readonly Color activeColor; + private readonly Color backgroundColor; + private readonly bool showValue; + private readonly int id; + private static Material knobMaterial; + 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 (this.KnobState().isEditing && this.CurrentEventType() != EventType.Repaint) + { + return this.DoKeyboardInput(); + } + switch (this.CurrentEventType()) + { + case EventType.MouseDown: + return this.OnMouseDown(); + case EventType.MouseUp: + return this.OnMouseUp(); + case EventType.MouseDrag: + return this.OnMouseDrag(); + case EventType.Repaint: + return this.OnRepaint(); + } + return this.currentValue; + } + private EventType CurrentEventType() + { + return this.CurrentEvent().type; + } + private bool IsEmptyKnob() + { + return this.start == this.end; + } + private Event CurrentEvent() + { + return Event.current; + } + private float Clamp(float value) + { + return Mathf.Clamp(value, this.MinValue(), this.MaxValue()); + } + private float ClampedCurrentValue() + { + return this.Clamp(this.currentValue); + } + private float MaxValue() + { + return Mathf.Max(this.start, this.end); + } + private float MinValue() + { + return Mathf.Min(this.start, this.end); + } + private float GetCurrentValuePercent() + { + return (this.ClampedCurrentValue() - this.MinValue()) / (this.MaxValue() - this.MinValue()); + } + private float MousePosition() + { + return this.CurrentEvent().mousePosition.y - this.position.y; + } + private bool WasDoubleClick() + { + return this.CurrentEventType() == EventType.MouseDown && this.CurrentEvent().clickCount == 2; + } + private float ValuesPerPixel() + { + return 250f / (this.MaxValue() - this.MinValue()); + } + private KnobState KnobState() + { + return (KnobState)GUIUtility.GetStateObject(typeof(KnobState), this.id); + } + private void StartDraggingWithValue(float dragStartValue) + { + KnobState knobState = this.KnobState(); + knobState.dragStartPos = this.MousePosition(); + knobState.dragStartValue = dragStartValue; + knobState.isDragging = true; + } + private float OnMouseDown() + { + if (!this.position.Contains(this.CurrentEvent().mousePosition) || this.KnobState().isEditing || this.IsEmptyKnob()) + { + return this.currentValue; + } + GUIUtility.hotControl = this.id; + if (this.WasDoubleClick()) + { + this.KnobState().isEditing = true; + } + else + { + this.StartDraggingWithValue(this.ClampedCurrentValue()); + } + this.CurrentEvent().Use(); + return this.currentValue; + } + private float OnMouseDrag() + { + if (GUIUtility.hotControl != this.id) + { + return this.currentValue; + } + KnobState knobState = this.KnobState(); + if (!knobState.isDragging) + { + return this.currentValue; + } + GUI.changed = true; + this.CurrentEvent().Use(); + float num = knobState.dragStartPos - this.MousePosition(); + float value = knobState.dragStartValue + num / this.ValuesPerPixel(); + return this.Clamp(value); + } + private float OnMouseUp() + { + if (GUIUtility.hotControl == this.id) + { + this.CurrentEvent().Use(); + GUIUtility.hotControl = 0; + this.KnobState().isDragging = false; + } + return this.currentValue; + } + private void PrintValue() + { + Rect rect = new Rect(this.position.x + this.knobSize.x / 2f - 8f, this.position.y + this.knobSize.y / 2f - 8f, this.position.width, 20f); + string str = this.currentValue.ToString("0.##"); + GUI.Label(rect, str + " " + this.unit); + } + private float DoKeyboardInput() + { + GUI.SetNextControlName("KnobInput"); + GUI.FocusControl("KnobInput"); + EditorGUI.BeginChangeCheck(); + Rect rect = new Rect(this.position.x + this.knobSize.x / 2f - 6f, this.position.y + this.knobSize.y / 2f - 7f, this.position.width, 20f); + GUIStyle none = GUIStyle.none; + none.normal.textColor = new Color(0.703f, 0.703f, 0.703f, 1f); + none.fontStyle = FontStyle.Normal; + string text = EditorGUI.DelayedTextField(rect, this.currentValue.ToString("0.##"), null, none); + if (EditorGUI.EndChangeCheck() && !string.IsNullOrEmpty(text)) + { + this.KnobState().isEditing = false; + float num; + if (float.TryParse(text, out num) && num != this.currentValue) + { + return this.Clamp(num); + } + } + return this.currentValue; + } + private static void CreateKnobMaterial() + { + if (!EditorGUI.KnobContext.knobMaterial) + { + Shader shader = Resources.GetBuiltinResource(typeof(Shader), "Internal-GUITextureClip.shader") as Shader; + EditorGUI.KnobContext.knobMaterial = new Material(shader); + EditorGUI.KnobContext.knobMaterial.hideFlags = HideFlags.HideAndDontSave; + EditorGUI.KnobContext.knobMaterial.mainTexture = EditorGUIUtility.FindTexture("KnobCShape"); + EditorGUI.KnobContext.knobMaterial.name = "Knob Material"; + if (EditorGUI.KnobContext.knobMaterial.mainTexture == null) + { + Debug.Log("Did not find 'KnobCShape'"); + } + } + } + private Vector3 GetUVForPoint(Vector3 point) + { + Vector3 result = new Vector3((point.x - this.position.x) / this.knobSize.x, (point.y - this.position.y - this.knobSize.y) / -this.knobSize.y); + return result; + } + private void VertexPointWithUV(Vector3 point) + { + GL.TexCoord(this.GetUVForPoint(point)); + GL.Vertex(point); + } + private void DrawValueArc(float angle) + { + EditorGUI.KnobContext.CreateKnobMaterial(); + Vector3 point = new Vector3(this.position.x + this.knobSize.x / 2f, this.position.y + this.knobSize.y / 2f, 0f); + Vector3 point2 = new Vector3(this.position.x + this.knobSize.x, this.position.y + this.knobSize.y / 2f, 0f); + Vector3 vector = new Vector3(this.position.x + this.knobSize.x, this.position.y + this.knobSize.y, 0f); + Vector3 vector2 = new Vector3(this.position.x, this.position.y + this.knobSize.y, 0f); + Vector3 vector3 = new Vector3(this.position.x, this.position.y, 0f); + Vector3 point3 = new Vector3(this.position.x + this.knobSize.x, this.position.y, 0f); + EditorGUI.KnobContext.knobMaterial.SetPass(0); + GL.Begin(7); + GL.Color(this.backgroundColor); + this.VertexPointWithUV(vector3); + this.VertexPointWithUV(point3); + this.VertexPointWithUV(vector); + this.VertexPointWithUV(vector2); + GL.End(); + GL.Begin(4); + GL.Color(this.activeColor * ((!GUI.enabled) ? 0.5f : 1f)); + if (angle > 0f) + { + this.VertexPointWithUV(point); + this.VertexPointWithUV(point2); + this.VertexPointWithUV(vector); + Vector3 point4 = vector; + if (angle > 1.57079637f) + { + this.VertexPointWithUV(point); + this.VertexPointWithUV(vector); + this.VertexPointWithUV(vector2); + point4 = vector2; + if (angle > 3.14159274f) + { + this.VertexPointWithUV(point); + this.VertexPointWithUV(vector2); + this.VertexPointWithUV(vector3); + point4 = vector3; + } + } + if (angle == 4.712389f) + { + this.VertexPointWithUV(point); + this.VertexPointWithUV(vector3); + this.VertexPointWithUV(point3); + this.VertexPointWithUV(point); + this.VertexPointWithUV(point3); + this.VertexPointWithUV(point2); + } + else + { + float num = angle + 0.7853982f; + Vector3 point5; + if (angle < 1.57079637f) + { + point5 = vector + new Vector3(this.knobSize.y / 2f * Mathf.Tan(1.57079637f - num) - this.knobSize.x / 2f, 0f, 0f); + } + else + { + if (angle < 3.14159274f) + { + point5 = vector2 + new Vector3(0f, this.knobSize.x / 2f * Mathf.Tan(3.14159274f - num) - this.knobSize.y / 2f, 0f); + } + else + { + point5 = vector3 + new Vector3(-(this.knobSize.y / 2f * Mathf.Tan(4.712389f - num)) + this.knobSize.x / 2f, 0f, 0f); + } + } + this.VertexPointWithUV(point); + this.VertexPointWithUV(point4); + this.VertexPointWithUV(point5); + } + } + GL.End(); + } + private float OnRepaint() + { + this.DrawValueArc(this.GetCurrentValuePercent() * 3.14159274f * 1.5f); + if (this.KnobState().isEditing) + { + return this.DoKeyboardInput(); + } + if (this.showValue) + { + this.PrintValue(); + } + return this.currentValue; + } + } + internal enum ObjectFieldVisualType + { + IconAndText, + LargePreview, + MiniPreivew + } + internal class VUMeter { - public float lastValue; - public float peakValue; - public Texture2D texture; - public float peakValueTime; - public bool IsDone() + public struct SmoothingData + { + public float lastValue; + public float peakValue; + public float peakValueTime; + } + private const float VU_SPLIT = 0.9f; + private static Texture2D s_VerticalVUTexture; + private static Texture2D s_HorizontalVUTexture; + public static Texture2D verticalVUTexture + { + get + { + if (EditorGUI.VUMeter.s_VerticalVUTexture == null) + { + EditorGUI.VUMeter.s_VerticalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureVertical"); + } + return EditorGUI.VUMeter.s_VerticalVUTexture; + } + } + public static Texture2D horizontalVUTexture + { + get + { + if (EditorGUI.VUMeter.s_HorizontalVUTexture == null) + { + EditorGUI.VUMeter.s_HorizontalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureHorizontal"); + } + return EditorGUI.VUMeter.s_HorizontalVUTexture; + } + } + public static void HorizontalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color = GUI.color; + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + GUI.color = new Color(1f, 1f, 1f, (!GUI.enabled) ? 0.5f : 1f); + float num = position.width * value - 2f; + if (num < 2f) + { + num = 2f; + } + Rect position2 = new Rect(position.x + 1f, position.y + 1f, num, position.height - 2f); + Rect texCoords = new Rect(0f, 0f, value, 1f); + GUI.DrawTextureWithTexCoords(position2, foregroundTexture, texCoords); + GUI.color = peakColor; + float num2 = position.width * peak - 2f; + if (num2 < 2f) + { + num2 = 2f; + } + position2 = new Rect(position.x + num2, position.y + 1f, 1f, position.height - 2f); + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + GUI.color = color; + } + public static void VerticalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color = GUI.color; + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + GUI.color = new Color(1f, 1f, 1f, (!GUI.enabled) ? 0.5f : 1f); + float num = (position.height - 2f) * value; + if (num < 2f) + { + num = 2f; + } + Rect position2 = new Rect(position.x + 1f, position.y + position.height - 1f - num, position.width - 2f, num); + Rect texCoords = new Rect(0f, 0f, 1f, value); + GUI.DrawTextureWithTexCoords(position2, foregroundTexture, texCoords); + GUI.color = peakColor; + float num2 = (position.height - 2f) * peak; + if (num2 < 2f) + { + num2 = 2f; + } + position2 = new Rect(position.x + 1f, position.y + position.height - 1f - num2, position.width - 2f, 1f); + GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + GUI.color = color; + } + public static void HorizontalMeter(Rect position, float value, ref EditorGUI.VUMeter.SmoothingData data, Texture2D foregroundTexture, Color peakColor) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + float value2; + float peak; + EditorGUI.VUMeter.SmoothVUMeterData(ref value, ref data, out value2, out peak); + EditorGUI.VUMeter.HorizontalMeter(position, value2, peak, foregroundTexture, peakColor); + } + public static void VerticalMeter(Rect position, float value, ref EditorGUI.VUMeter.SmoothingData data, Texture2D foregroundTexture, Color peakColor) { - return this.lastValue == 0f && this.peakValue == 0f; + if (Event.current.type != EventType.Repaint) + { + return; + } + float value2; + float peak; + EditorGUI.VUMeter.SmoothVUMeterData(ref value, ref data, out value2, out peak); + EditorGUI.VUMeter.VerticalMeter(position, value2, peak, foregroundTexture, peakColor); + } + private static void SmoothVUMeterData(ref float value, ref EditorGUI.VUMeter.SmoothingData data, out float renderValue, out float renderPeak) + { + if (value <= data.lastValue) + { + value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7f); + } + else + { + value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2f); + data.peakValue = value; + data.peakValueTime = Time.realtimeSinceStartup; + } + if (value > 1.11111116f) + { + value = 1.11111116f; + } + if (data.peakValue > 1.11111116f) + { + data.peakValue = 1.11111116f; + } + renderValue = value * 0.9f; + renderPeak = data.peakValue * 0.9f; + data.lastValue = value; } } internal delegate UnityEngine.Object ObjectFieldValidator(UnityEngine.Object[] references, Type objType, SerializedProperty property); @@ -202,19 +691,22 @@ public bool IsDone() internal const float kSingleLineHeight = 16f; internal const float kStructHeaderLineHeight = 16f; internal const float kObjectFieldThumbnailHeight = 64f; + internal const float kObjectFieldMiniThumbnailHeight = 18f; + internal const float kObjectFieldMiniThumbnailWidth = 32f; private const float kIndentPerLevel = 15f; internal const int kControlVerticalSpacing = 2; - private const int kInspTitlebarIconWidth = 16; + internal const int kInspTitlebarIconWidth = 16; + internal const float kNearFarLabelsWidth = 35f; private const int kInspTitlebarToggleWidth = 16; private const int kInspTitlebarSpacing = 2; - private const float VU_SPLIT = 0.9f; + private const string kEmptyDropDownElement = "--empty--"; private static EditorGUI.RecycledTextEditor activeEditor; internal static EditorGUI.DelayedTextEditor s_DelayedTextEditor = new EditorGUI.DelayedTextEditor(); internal static EditorGUI.RecycledTextEditor s_RecycledEditor = new EditorGUI.RecycledTextEditor(); internal static string s_OriginalText = string.Empty; internal static string s_RecycledCurrentEditingString; - internal static float s_RecycledCurrentEditingFloat; - internal static int s_RecycledCurrentEditingInt; + internal static double s_RecycledCurrentEditingFloat; + internal static long s_RecycledCurrentEditingInt; private static bool bKeyEventActive = false; internal static bool s_DragToPosition = true; internal static bool s_Dragged = false; @@ -249,15 +741,18 @@ public bool IsDone() private static int s_ProgressBarHash = "s_ProgressBarHash".GetHashCode(); private static int s_SelectableLabelHash = "s_SelectableLabel".GetHashCode(); private static int s_SortingLayerFieldHash = "s_SortingLayerFieldHash".GetHashCode(); + private static int s_TextFieldDropDownHash = "s_TextFieldDropDown".GetHashCode(); private static int s_DragCandidateState = 0; private static float kDragDeadzone = 16f; private static Vector2 s_DragStartPos; - private static float s_DragStartValue = 0f; - private static int s_DragStartIntValue = 0; - private static float s_DragSensitivity = 0f; + private static double s_DragStartValue = 0.0; + private static long s_DragStartIntValue = 0L; + private static double s_DragSensitivity = 0.0; internal static string kFloatFieldFormatString = "g7"; + internal static string kDoubleFieldFormatString = "g15"; internal static string kIntFieldFormatString = "#######0"; internal static int ms_IndentLevel = 0; + internal static string s_UnitString = string.Empty; private static float[] s_Vector2Floats = new float[2]; private static GUIContent[] s_XYLabels = new GUIContent[] { @@ -284,12 +779,16 @@ public bool IsDone() new GUIContent("W"), new GUIContent("H") }; + internal static readonly GUIContent s_ClipingPlanesLabel = new GUIContent("Clipping Planes"); + internal static readonly GUIContent[] s_NearAndFarLabels = new GUIContent[] + { + new GUIContent("Near"), + new GUIContent("Far") + }; private static int s_ColorPickID; private static int s_CurveID; internal static Color kCurveColor = Color.green; internal static Color kCurveBGColor = new Color(0.337f, 0.337f, 0.337f, 1f); - internal static GUIContent s_HelpIcon; - internal static GUIContent s_TitleSettingsIcon; private static GUIContent s_PropertyFieldTempContent = new GUIContent(); private static GUIContent s_IconDropDown; private static Material s_IconTextureInactive; @@ -304,6 +803,8 @@ public bool IsDone() private static Stack s_PropertyStack = new Stack(); private static Stack s_EnabledStack = new Stack(); private static Stack s_ChangedStack = new Stack(); + internal static readonly string s_AllowedCharactersForFloat = "inftynaeINFTYNAE0123456789.,-"; + internal static readonly string s_AllowedCharactersForInt = "0123456789-"; private static SerializedProperty s_PendingPropertyKeyboardHandling = null; private static SerializedProperty s_PendingPropertyDelete = null; private static Material tmp; @@ -315,8 +816,6 @@ public bool IsDone() private static int s_ButtonMouseDownHash = "ButtonMouseDown".GetHashCode(); private static int s_MouseDeltaReaderHash = "MouseDeltaReader".GetHashCode(); private static Vector2 s_MouseDeltaReaderLastPos; - private static Texture2D s_VerticalVUTexture; - private static Texture2D s_HorizontalVUTexture; public static bool showMixedValue { get @@ -446,4922 +945,5288 @@ internal static bool isCollectingTooltips EditorGUI.s_CollectingToolTips = value; } } - internal static void BeginHandleMixedValueContentColor() + [ExcludeFromDocs] + public static void LabelField(Rect position, string label) { - EditorGUI.s_MixedValueContentColorTemp = GUI.contentColor; - GUI.contentColor = ((!EditorGUI.showMixedValue) ? GUI.contentColor : (GUI.contentColor * EditorGUI.s_MixedValueContentColor)); + GUIStyle label2 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2); } - internal static void EndHandleMixedValueContentColor() + public static void LabelField(Rect position, string label, [DefaultValue("EditorStyles.label")] GUIStyle style) { - GUI.contentColor = EditorGUI.s_MixedValueContentColorTemp; + EditorGUI.LabelField(position, GUIContent.none, EditorGUIUtility.TempContent(label), style); } - internal static bool IsEditingTextField() + [ExcludeFromDocs] + public static void LabelField(Rect position, GUIContent label) { - return EditorGUI.RecycledTextEditor.s_ActuallyEditing; + GUIStyle label2 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2); } - internal static void EndEditingActiveTextField() + public static void LabelField(Rect position, GUIContent label, [DefaultValue("EditorStyles.label")] GUIStyle style) { - if (EditorGUI.activeEditor != null) - { - EditorGUI.activeEditor.EndEditing(); - } + EditorGUI.LabelField(position, GUIContent.none, label, style); } - public static void FocusTextInControl(string name) + [ExcludeFromDocs] + public static void LabelField(Rect position, string label, string label2) { - GUI.FocusControl(name); - EditorGUIUtility.editingTextField = true; + GUIStyle label3 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2, label3); } - internal static void ClearStacks() + public static void LabelField(Rect position, string label, string label2, [DefaultValue("EditorStyles.label")] GUIStyle style) { - EditorGUI.s_EnabledStack.Clear(); - EditorGUI.s_ChangedStack.Clear(); - EditorGUI.s_PropertyStack.Clear(); - ScriptAttributeUtility.s_DrawerStack.Clear(); + EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent(label2), style); } - public static void BeginDisabledGroup(bool disabled) + [ExcludeFromDocs] + public static void LabelField(Rect position, GUIContent label, GUIContent label2) { - EditorGUI.s_EnabledStack.Push(GUI.enabled); - GUI.enabled &= !disabled; + GUIStyle label3 = EditorStyles.label; + EditorGUI.LabelField(position, label, label2, label3); } - public static void EndDisabledGroup() + public static void LabelField(Rect position, GUIContent label, GUIContent label2, [DefaultValue("EditorStyles.label")] GUIStyle style) { - GUI.enabled = EditorGUI.s_EnabledStack.Pop(); + EditorGUI.LabelFieldInternal(position, label, label2, style); } - public static void BeginChangeCheck() + [ExcludeFromDocs] + public static bool ToggleLeft(Rect position, string label, bool value) { - EditorGUI.s_ChangedStack.Push(GUI.changed); - GUI.changed = false; + GUIStyle label2 = EditorStyles.label; + return EditorGUI.ToggleLeft(position, label, value, label2); } - public static bool EndChangeCheck() + public static bool ToggleLeft(Rect position, string label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) { - bool changed = GUI.changed; - GUI.changed |= EditorGUI.s_ChangedStack.Pop(); - return changed; + return EditorGUI.ToggleLeft(position, EditorGUIUtility.TempContent(label), value, labelStyle); } - private static void ShowTextEditorPopupMenu() + [ExcludeFromDocs] + public static bool ToggleLeft(Rect position, GUIContent label, bool value) { - GenericMenu genericMenu = new GenericMenu(); - if (EditorGUI.s_RecycledEditor.hasSelection && !EditorGUI.s_RecycledEditor.isPasswordField) - { - if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) - { - genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Cut", GUIView.current).SendEvent)); - } - genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Copy", GUIView.current).SendEvent)); - } - else - { - if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) - { - genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut")); - } - genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy")); - } - if (EditorGUI.s_RecycledEditor.CanPaste() && EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) - { - genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Paste"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Paste", GUIView.current).SendEvent)); - } - genericMenu.ShowAsContext(); + GUIStyle label2 = EditorStyles.label; + return EditorGUI.ToggleLeft(position, label, value, label2); } - internal static void BeginCollectTooltips() + public static bool ToggleLeft(Rect position, GUIContent label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) { - EditorGUI.isCollectingTooltips = true; + return EditorGUI.ToggleLeftInternal(position, label, value, labelStyle); } - internal static void EndCollectTooltips() + [ExcludeFromDocs] + public static string TextField(Rect position, string text) { - EditorGUI.isCollectingTooltips = false; + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, text, textField); } - public static void DropShadowLabel(Rect position, string text) + public static string TextField(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), "PreOverlayLabel", 0.6f); + return EditorGUI.TextFieldInternal(position, text, style); } - public static void DropShadowLabel(Rect position, GUIContent content) + [ExcludeFromDocs] + public static string TextField(Rect position, string label, string text) { - EditorGUI.DoDropShadowLabel(position, content, "PreOverlayLabel", 0.6f); + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, label, text, textField); } - public static void DropShadowLabel(Rect position, string text, GUIStyle style) + public static string TextField(Rect position, string label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), style, 0.6f); + return EditorGUI.TextField(position, EditorGUIUtility.TempContent(label), text, style); } - public static void DropShadowLabel(Rect position, GUIContent content, GUIStyle style) + [ExcludeFromDocs] + public static string TextField(Rect position, GUIContent label, string text) { - EditorGUI.DoDropShadowLabel(position, content, style, 0.6f); + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextField(position, label, text, textField); } - internal static void DoDropShadowLabel(Rect position, GUIContent content, GUIStyle style, float shadowOpa) + public static string TextField(Rect position, GUIContent label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - if (Event.current.type != EventType.Repaint) - { - return; - } - EditorGUI.DrawLabelShadow(position, content, style, shadowOpa); - style.Draw(position, content, false, false, false, false); + return EditorGUI.TextFieldInternal(position, label, text, style); } - internal static void DrawLabelShadow(Rect position, GUIContent content, GUIStyle style, float shadowOpa) + [ExcludeFromDocs] + public static string TextArea(Rect position, string text) { - Color color = GUI.color; - Color contentColor = GUI.contentColor; - Color backgroundColor = GUI.backgroundColor; - GUI.contentColor = new Color(0f, 0f, 0f, 0f); - style.Draw(position, content, false, false, false, false); - position.y += 1f; - GUI.backgroundColor = new Color(0f, 0f, 0f, 0f); - GUI.contentColor = contentColor; - EditorGUI.Draw4(position, content, 1f, GUI.color.a * shadowOpa, style); - EditorGUI.Draw4(position, content, 2f, GUI.color.a * shadowOpa * 0.42f, style); - GUI.color = color; - GUI.backgroundColor = backgroundColor; + GUIStyle textField = EditorStyles.textField; + return EditorGUI.TextArea(position, text, textField); } - private static void Draw4(Rect position, GUIContent content, float offset, float alpha, GUIStyle style) + public static string TextArea(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - GUI.color = new Color(0f, 0f, 0f, alpha); - position.y -= offset; - style.Draw(position, content, false, false, false, false); - position.y += offset * 2f; - style.Draw(position, content, false, false, false, false); - position.y -= offset; - position.x -= offset; - style.Draw(position, content, false, false, false, false); - position.x += offset * 2f; - style.Draw(position, content, false, false, false, false); + return EditorGUI.TextAreaInternal(position, text, style); } - internal static string DoTextField(EditorGUI.RecycledTextEditor editor, int id, Rect position, string text, GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField) + [ExcludeFromDocs] + public static void SelectableLabel(Rect position, string text) { - Event current = Event.current; - string result = text; - if (text == null) - { - text = string.Empty; - } - if (EditorGUI.showMixedValue) - { - text = string.Empty; - } - if (GUIUtility.keyboardControl == id && GUIView.current.hasFocus && Event.current.type != EventType.Layout) - { - if (editor.IsEditingControl(id)) - { - editor.position = position; - editor.style = style; - editor.controlID = id; - editor.multiline = multiline; - editor.isPasswordField = passwordField; - editor.ClampPos(); - editor.UpdateScrollOffsetIfNeeded(); - } - else - { - if (EditorGUIUtility.editingTextField) - { - editor.BeginEditing(id, text, position, style, multiline, passwordField); - if (GUI.skin.settings.cursorColor.a > 0f) - { - editor.SelectAll(); - } - } - } - } - if (editor.controlID == id && GUIUtility.keyboardControl != id) - { - editor.controlID = 0; - } - bool flag = false; - string text2 = editor.content.text; - EventType typeForControl = current.GetTypeForControl(id); - switch (typeForControl) - { - case EventType.MouseDown: - if (position.Contains(current.mousePosition) && current.button == 0) - { - if (editor.IsEditingControl(id)) - { - if (Event.current.clickCount == 2 && GUI.skin.settings.doubleClickSelectsWord) - { - editor.MoveCursorToPosition(Event.current.mousePosition); - editor.SelectCurrentWord(); - editor.MouseDragSelectsWholeWords(true); - editor.DblClickSnap(TextEditor.DblClickSnapping.WORDS); - EditorGUI.s_DragToPosition = false; - } - else - { - if (Event.current.clickCount == 3 && GUI.skin.settings.tripleClickSelectsLine) - { - editor.MoveCursorToPosition(Event.current.mousePosition); - editor.SelectCurrentParagraph(); - editor.MouseDragSelectsWholeWords(true); - editor.DblClickSnap(TextEditor.DblClickSnapping.PARAGRAPHS); - EditorGUI.s_DragToPosition = false; - } - else - { - editor.MoveCursorToPosition(Event.current.mousePosition); - EditorGUI.s_SelectAllOnMouseUp = false; - } - } - } - else - { - GUIUtility.keyboardControl = id; - editor.BeginEditing(id, text, position, style, multiline, passwordField); - editor.MoveCursorToPosition(Event.current.mousePosition); - if (GUI.skin.settings.cursorColor.a > 0f) - { - EditorGUI.s_SelectAllOnMouseUp = true; - } - } - GUIUtility.hotControl = id; - current.Use(); - } - goto IL_923; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) - { - if (EditorGUI.s_Dragged && EditorGUI.s_DragToPosition) - { - editor.MoveSelectionToAltCursor(); - flag = true; - } - else - { - if (EditorGUI.s_PostPoneMove) - { - editor.MoveCursorToPosition(Event.current.mousePosition); - } - else - { - if (EditorGUI.s_SelectAllOnMouseUp) - { - if (GUI.skin.settings.cursorColor.a > 0f) - { - editor.SelectAll(); - } - EditorGUI.s_SelectAllOnMouseUp = false; - } - } - } - editor.MouseDragSelectsWholeWords(false); - EditorGUI.s_DragToPosition = true; - EditorGUI.s_Dragged = false; - EditorGUI.s_PostPoneMove = false; - if (current.button == 0) - { - GUIUtility.hotControl = 0; - current.Use(); - } - } - goto IL_923; - case EventType.MouseMove: - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_130: - switch (typeForControl) - { - case EventType.ValidateCommand: - if (GUIUtility.keyboardControl == id) - { - string commandName = current.commandName; - switch (commandName) - { - case "Cut": - case "Copy": - if (editor.hasSelection) - { - current.Use(); - } - break; - case "Paste": - if (editor.CanPaste()) - { - current.Use(); - } - break; - case "SelectAll": - current.Use(); - break; - case "UndoRedoPerformed": - editor.content.text = text; - current.Use(); - break; - } - } - goto IL_923; - case EventType.ExecuteCommand: - if (GUIUtility.keyboardControl == id) - { - string commandName = current.commandName; - switch (commandName) - { - case "OnLostFocus": - if (EditorGUI.activeEditor != null) - { - EditorGUI.activeEditor.EndEditing(); - } - current.Use(); - break; - case "Cut": - editor.BeginEditing(id, text, position, style, multiline, passwordField); - editor.Cut(); - flag = true; - break; - case "Copy": - editor.Copy(); - current.Use(); - break; - case "Paste": - editor.BeginEditing(id, text, position, style, multiline, passwordField); - editor.Paste(); - flag = true; - break; - case "SelectAll": - editor.SelectAll(); - current.Use(); - break; - } - } - goto IL_923; - case EventType.DragExited: - goto IL_923; - case EventType.ContextClick: - if (position.Contains(current.mousePosition)) - { - if (!editor.IsEditingControl(id)) - { - GUIUtility.keyboardControl = id; - editor.BeginEditing(id, text, position, style, multiline, passwordField); - editor.MoveCursorToPosition(Event.current.mousePosition); - } - EditorGUI.ShowTextEditorPopupMenu(); - Event.current.Use(); - } - goto IL_923; - default: - goto IL_923; - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - if (!current.shift && editor.hasSelection && EditorGUI.s_DragToPosition) - { - editor.MoveAltCursorToPosition(Event.current.mousePosition); - } - else - { - if (current.shift) - { - editor.MoveCursorToPosition(Event.current.mousePosition); - } - else - { - editor.SelectToPosition(Event.current.mousePosition); - } - EditorGUI.s_DragToPosition = false; - EditorGUI.s_SelectAllOnMouseUp = false; - } - EditorGUI.s_Dragged = true; - current.Use(); - } - goto IL_923; - case EventType.KeyDown: - if (GUIUtility.keyboardControl == id) - { - char character = current.character; - if (editor.IsEditingControl(id) && editor.HandleKeyEvent(current)) - { - current.Use(); - flag = true; - } - else - { - if (current.keyCode == KeyCode.Escape) - { - if (editor.IsEditingControl(id)) - { - if (style == EditorStyles.toolbarSearchField || style == EditorStyles.searchField) - { - EditorGUI.s_OriginalText = string.Empty; - } - editor.content.text = EditorGUI.s_OriginalText; - editor.EndEditing(); - flag = true; - } - } - else - { - if (character == '\n' || character == '\u0003') - { - if (!editor.IsEditingControl(id)) - { - editor.BeginEditing(id, text, position, style, multiline, passwordField); - editor.SelectAll(); - } - else - { - if (multiline && !current.alt && !current.shift && !current.control) - { - editor.Insert(character); - flag = true; - goto IL_923; - } - editor.EndEditing(); - } - current.Use(); - } - else - { - if (character == '\t' || current.keyCode == KeyCode.Tab) - { - if (multiline && editor.IsEditingControl(id)) - { - bool flag2 = !current.alt && !current.shift && !current.control && character == '\t'; - if (flag2) - { - editor.Insert(character); - flag = true; - } - } - } - else - { - if (character != '\u0019' && character != '\u001b') - { - if (editor.IsEditingControl(id)) - { - bool flag3 = (allowedletters == null || allowedletters.IndexOf(character) != -1) && character != '\0'; - if (flag3) - { - editor.Insert(character); - flag = true; - } - else - { - if (Input.compositionString != string.Empty) - { - editor.ReplaceSelection(string.Empty); - flag = true; - } - current.Use(); - } - } - } - } - } - } - } - } - goto IL_923; - case EventType.Repaint: - { - string text3; - if (editor.IsEditingControl(id)) - { - text3 = ((!passwordField) ? editor.content.text : string.Empty.PadRight(editor.content.text.Length, '*')); - } - else - { - if (EditorGUI.showMixedValue) - { - text3 = EditorGUI.s_MixedValueContent.text; - } - else - { - text3 = ((!passwordField) ? text : string.Empty.PadRight(text.Length, '*')); - } - } - if (GUIUtility.hotControl == 0) - { - EditorGUIUtility.AddCursorRect(position, MouseCursor.Text); - } - if (!editor.IsEditingControl(id)) - { - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, EditorGUIUtility.TempContent(text3), id, false); - EditorGUI.EndHandleMixedValueContentColor(); - } - else - { - editor.DrawCursor(text3); - } - goto IL_923; - } - } - goto IL_130; - IL_923: - if (GUIUtility.keyboardControl == id) - { - GUIUtility.textFieldInput = true; - } - changed = false; - if (flag) - { - changed = (text2 != editor.content.text); - current.Use(); - } - if (changed) - { - GUI.changed = true; - return editor.content.text; - } - EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = true; - return result; - } - internal static Event KeyEventField(Rect position, Event evt) - { - return EditorGUI.DoKeyEventField(position, evt, GUI.skin.textField); - } - internal static Event DoKeyEventField(Rect position, Event _event, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_KeyEventFieldHash, FocusType.Native, position); - Event current = Event.current; - switch (current.GetTypeForControl(controlID)) - { - case EventType.MouseDown: - if (position.Contains(current.mousePosition)) - { - GUIUtility.hotControl = controlID; - current.Use(); - if (EditorGUI.bKeyEventActive) - { - EditorGUI.bKeyEventActive = false; - } - else - { - EditorGUI.bKeyEventActive = true; - } - } - return _event; - case EventType.MouseUp: - if (GUIUtility.hotControl == controlID) - { - GUIUtility.hotControl = controlID; - current.Use(); - } - return _event; - case EventType.MouseDrag: - if (GUIUtility.hotControl == controlID) - { - current.Use(); - } - break; - case EventType.KeyDown: - if (GUIUtility.hotControl == controlID && EditorGUI.bKeyEventActive) - { - if (current.character == '\0' && ((current.alt && (current.keyCode == KeyCode.AltGr || current.keyCode == KeyCode.LeftAlt || current.keyCode == KeyCode.RightAlt)) || (current.control && (current.keyCode == KeyCode.LeftControl || current.keyCode == KeyCode.RightControl)) || (current.command && (current.keyCode == KeyCode.LeftCommand || current.keyCode == KeyCode.RightCommand || current.keyCode == KeyCode.LeftWindows || current.keyCode == KeyCode.RightWindows)) || (current.shift && (current.keyCode == KeyCode.LeftShift || current.keyCode == KeyCode.RightShift || current.keyCode == KeyCode.None)))) - { - return _event; - } - EditorGUI.bKeyEventActive = false; - GUI.changed = true; - GUIUtility.hotControl = 0; - Event result = new Event(current); - current.Use(); - return result; - } - break; - case EventType.Repaint: - if (EditorGUI.bKeyEventActive) - { - GUIContent content = EditorGUIUtility.TempContent("[Please press a key]"); - style.Draw(position, content, controlID); - } - else - { - string t = InternalEditorUtility.TextifyEvent(_event); - style.Draw(position, EditorGUIUtility.TempContent(t), controlID); - } - break; - } - return _event; - } - internal static bool DoObjectFoldout(int id, Rect position, UnityEngine.Object[] targetObjs, bool foldout) - { - int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; - position.xMin -= (float)num; - bool enabled = GUI.enabled; - GUI.enabled = true; - Event current = Event.current; - EventType typeForControl = current.GetTypeForControl(id); - switch (typeForControl) - { - case EventType.MouseDown: - if (position.Contains(current.mousePosition)) - { - if (current.button == 1 && targetObjs[0] != null) - { - EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); - current.Use(); - } - else - { - if (current.button == 0 && (Application.platform != RuntimePlatform.OSXEditor || !current.control)) - { - GUIUtility.hotControl = id; - GUIUtility.keyboardControl = id; - DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); - dragAndDropDelay.mouseDownPosition = current.mousePosition; - current.Use(); - } - } - } - goto IL_36B; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) - { - GUIUtility.hotControl = 0; - current.Use(); - if (position.Contains(current.mousePosition)) - { - GUI.changed = true; - foldout = !foldout; - } - } - goto IL_36B; - case EventType.MouseMove: - case EventType.KeyUp: - case EventType.ScrollWheel: - case EventType.Repaint: - case EventType.Layout: - IL_7E: - if (typeForControl != EventType.ContextClick) - { - goto IL_36B; - } - if (position.Contains(current.mousePosition) && targetObjs[0] != null) - { - EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); - current.Use(); - } - goto IL_36B; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); - if (dragAndDropDelay2.CanStartDrag()) - { - GUIUtility.hotControl = 0; - DragAndDrop.PrepareStartDrag(); - DragAndDrop.objectReferences = targetObjs; - if (targetObjs.Length > 1) - { - DragAndDrop.StartDrag(""); - } - else - { - DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(targetObjs[0])); - } - } - current.Use(); - } - goto IL_36B; - case EventType.KeyDown: - if (GUIUtility.keyboardControl == id) - { - if (current.keyCode == KeyCode.LeftArrow) - { - foldout = false; - current.Use(); - } - if (current.keyCode == KeyCode.RightArrow) - { - foldout = true; - current.Use(); - } - } - goto IL_36B; - case EventType.DragUpdated: - if (EditorGUI.s_DragUpdatedOverID == id) - { - if (position.Contains(current.mousePosition)) - { - if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) - { - foldout = true; - HandleUtility.Repaint(); - } - } - else - { - EditorGUI.s_DragUpdatedOverID = 0; - } - } - else - { - if (position.Contains(current.mousePosition)) - { - EditorGUI.s_DragUpdatedOverID = id; - EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; - } - } - if (position.Contains(current.mousePosition)) - { - DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, false); - Event.current.Use(); - } - goto IL_36B; - case EventType.DragPerform: - if (position.Contains(current.mousePosition)) - { - DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, true); - DragAndDrop.AcceptDrag(); - Event.current.Use(); - } - goto IL_36B; - } - goto IL_7E; - IL_36B: - GUI.enabled = enabled; - return foldout; - } - internal static void LabelFieldInternal(Rect position, GUIContent label, GUIContent label2, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Passive, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - if (Event.current.type == EventType.Repaint) - { - style.Draw(position, label2, controlID); - } - } - public static bool Toggle(Rect position, bool value) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); - return EditorGUIInternal.DoToggleForward(EditorGUI.IndentedRect(position), controlID, value, GUIContent.none, EditorStyles.toggle); - } - public static bool Toggle(Rect position, string label, bool value) - { - return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value); - } - public static bool Toggle(Rect position, bool value, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); - return EditorGUIInternal.DoToggleForward(position, controlID, value, GUIContent.none, style); - } - public static bool Toggle(Rect position, string label, bool value, GUIStyle style) - { - return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value, style); - } - public static bool Toggle(Rect position, GUIContent label, bool value) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); - return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, EditorStyles.toggle); - } - public static bool Toggle(Rect position, GUIContent label, bool value, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); - return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, style); - } - internal static bool ToggleLeftInternal(Rect position, GUIContent label, bool value, GUIStyle labelStyle) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); - Rect position2 = EditorGUI.IndentedRect(position); - Rect labelPosition = EditorGUI.IndentedRect(position); - labelPosition.xMin += 13f; - EditorGUI.HandlePrefixLabel(position, labelPosition, label, controlID, labelStyle); - return EditorGUIInternal.DoToggleForward(position2, controlID, value, GUIContent.none, EditorStyles.toggle); - } - internal static bool DoToggle(Rect position, int id, bool value, GUIContent content, GUIStyle style) - { - return EditorGUIInternal.DoToggleForward(position, id, value, content, style); - } - internal static string TextFieldInternal(Rect position, string text, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, false, false); - return text; - } - internal static string TextFieldInternal(Rect position, GUIContent label, string text, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.PrefixLabel(position, controlID, label), text, style, null, out flag, false, false, false); - return text; - } - internal static string ToolbarSearchField(int id, Rect position, string text, bool showWithPopupArrow) - { - Rect position2 = position; - position2.width -= 14f; - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position2, text, (!showWithPopupArrow) ? EditorStyles.toolbarSearchField : EditorStyles.toolbarSearchFieldPopup, null, out flag, false, false, false); - Rect position3 = position; - position3.x += position.width - 14f; - position3.width = 14f; - if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.toolbarSearchFieldCancelButtonEmpty : EditorStyles.toolbarSearchFieldCancelButton) && text != string.Empty) - { - text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); - GUIUtility.keyboardControl = 0; - } - return text; - } - internal static string ToolbarSearchField(Rect position, string[] searchModes, ref int searchMode, string text) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); - return EditorGUI.ToolbarSearchField(controlID, position, searchModes, ref searchMode, text); - } - internal static string ToolbarSearchField(int id, Rect position, string[] searchModes, ref int searchMode, string text) - { - bool flag = searchModes != null; - if (flag) - { - searchMode = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(id, searchMode); - Rect rect = position; - rect.width = 20f; - if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) - { - EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(id); - EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(searchModes), searchMode, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); - if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) - { - Event.current.Use(); - } - } - } - text = EditorGUI.ToolbarSearchField(id, position, text, flag); - if (flag && text == string.Empty && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && Event.current.type == EventType.Repaint) - { - position.width -= 14f; - EditorGUI.BeginDisabledGroup(true); - EditorStyles.toolbarSearchFieldPopup.Draw(position, EditorGUIUtility.TempContent(searchModes[searchMode]), id, false); - EditorGUI.EndDisabledGroup(); - } - return text; - } - internal static string SearchField(Rect position, string text) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); - Rect position2 = position; - position2.width -= 15f; - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, position2, text, EditorStyles.searchField, null, out flag, false, false, false); - Rect position3 = position; - position3.x += position.width - 15f; - position3.width = 15f; - if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.searchFieldCancelButtonEmpty : EditorStyles.searchFieldCancelButton) && text != string.Empty) - { - text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); - GUIUtility.keyboardControl = 0; - } - return text; - } - internal static string ScrollableTextAreaInternal(Rect position, string text, ref Vector2 scrollPosition, GUIStyle style) - { - if (Event.current.type == EventType.Layout) - { - return text; - } - int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); - float height = style.CalcHeight(GUIContent.Temp(text), position.width); - Rect rect = new Rect(0f, 0f, position.width, height); - Vector2 contentOffset = style.contentOffset; - if (position.height < rect.height) - { - Rect position2 = position; - position2.width = GUI.skin.verticalScrollbar.fixedWidth; - position2.height -= 2f; - position2.y += 1f; - position2.x = position.x + position.width - position2.width; - position.width -= position2.width; - height = style.CalcHeight(GUIContent.Temp(text), position.width); - rect = new Rect(0f, 0f, position.width, height); - if (position.Contains(Event.current.mousePosition) && Event.current.type == EventType.ScrollWheel) - { - float value = scrollPosition.y + Event.current.delta.y * 10f; - scrollPosition.y = Mathf.Clamp(value, 0f, rect.height); - Event.current.Use(); - } - scrollPosition.y = GUI.VerticalScrollbar(position2, scrollPosition.y, position.height, 0f, rect.height); - if (!EditorGUI.s_RecycledEditor.IsEditingControl(controlID)) - { - style.contentOffset -= scrollPosition; - style.Internal_clipOffset = scrollPosition; - } - else - { - EditorGUI.s_RecycledEditor.scrollOffset.y = scrollPosition.y; - } - } - EventType type = Event.current.type; - bool flag; - string result = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); - if (type != Event.current.type) - { - scrollPosition = EditorGUI.s_RecycledEditor.scrollOffset; - } - style.contentOffset = contentOffset; - style.Internal_clipOffset = Vector2.zero; - return result; - } - internal static string TextAreaInternal(Rect position, string text, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); - return text; - } - internal static void SelectableLabelInternal(Rect position, string text, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SelectableLabelHash, FocusType.Keyboard, position); - Event current = Event.current; - if (GUIUtility.keyboardControl == controlID && current.GetTypeForControl(controlID) == EventType.KeyDown) - { - KeyCode keyCode = current.keyCode; - switch (keyCode) - { - case KeyCode.UpArrow: - case KeyCode.DownArrow: - case KeyCode.RightArrow: - case KeyCode.LeftArrow: - case KeyCode.Home: - case KeyCode.End: - case KeyCode.PageUp: - case KeyCode.PageDown: - goto IL_A0; - case KeyCode.Insert: - IL_64: - if (keyCode != KeyCode.Space) - { - if (current.character != '\t') - { - current.Use(); - } - goto IL_A0; - } - GUIUtility.hotControl = 0; - GUIUtility.keyboardControl = 0; - goto IL_A0; - } - goto IL_64; - } - IL_A0: - if (current.type == EventType.ExecuteCommand && (current.commandName == "Paste" || current.commandName == "Cut") && GUIUtility.keyboardControl == controlID) - { - current.Use(); - } - Color cursorColor = GUI.skin.settings.cursorColor; - GUI.skin.settings.cursorColor = new Color(0f, 0f, 0f, 0f); - EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = false; - bool flag; - text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); - GUI.skin.settings.cursorColor = cursorColor; - } - public static string DoPasswordField(int id, Rect position, string password, GUIStyle style) - { - bool flag; - return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, password, style, null, out flag, false, false, true); - } - public static string DoPasswordField(int id, Rect position, GUIContent label, string password, GUIStyle style) - { - bool flag; - return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, EditorGUI.PrefixLabel(position, id, label), password, style, null, out flag, false, false, true); - } - internal static string PasswordFieldInternal(Rect position, string password, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); - return EditorGUI.DoPasswordField(controlID, EditorGUI.IndentedRect(position), password, style); - } - internal static string PasswordFieldInternal(Rect position, GUIContent label, string password, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); - return EditorGUI.DoPasswordField(controlID, position, label, password, style); - } - internal static float FloatFieldInternal(Rect position, float value, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); - return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kFloatFieldFormatString, style, false); - } - internal static float FloatFieldInternal(Rect position, GUIContent label, float value, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); - Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); - position.xMax = position2.x; - return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kFloatFieldFormatString, style, true); + GUIStyle label = EditorStyles.label; + EditorGUI.SelectableLabel(position, text, label); } - private static float CalculateFloatDragSensitivity(float value) + public static void SelectableLabel(Rect position, string text, [DefaultValue("EditorStyles.label")] GUIStyle style) { - if (float.IsInfinity(value) || float.IsNaN(value)) - { - return 0f; - } - return Mathf.Max(1f, Mathf.Pow(Mathf.Abs(value), 0.5f)) * 0.03f; + EditorGUI.SelectableLabelInternal(position, text, style); } - private static float CalculateIntDragSensitivity(int value) + [ExcludeFromDocs] + public static string PasswordField(Rect position, string password) { - return Mathf.Max(1f, Mathf.Pow(Mathf.Abs((float)value), 0.5f) * 0.03f); + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, password, textField); } - private static void DragNumberValue(Rect dragHotZone, int id, bool isFloat, ref float floatVal, ref int intVal, float dragSensitivity) + public static string PasswordField(Rect position, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - Event current = Event.current; - switch (current.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (dragHotZone.Contains(current.mousePosition) && current.button == 0) - { - GUIUtility.hotControl = id; - if (EditorGUI.activeEditor != null) - { - EditorGUI.activeEditor.EndEditing(); - } - current.Use(); - GUIUtility.keyboardControl = id; - EditorGUI.s_DragCandidateState = 1; - EditorGUI.s_DragStartValue = floatVal; - EditorGUI.s_DragStartIntValue = intVal; - EditorGUI.s_DragStartPos = current.mousePosition; - EditorGUI.s_DragSensitivity = dragSensitivity; - current.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && EditorGUI.s_DragCandidateState != 0) - { - GUIUtility.hotControl = 0; - EditorGUI.s_DragCandidateState = 0; - current.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - int num = EditorGUI.s_DragCandidateState; - if (num != 1) - { - if (num == 2) - { - if (isFloat) - { - floatVal += HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity; - floatVal = MathUtils.RoundBasedOnMinimumDifference(floatVal, EditorGUI.s_DragSensitivity); - } - else - { - intVal += Mathf.RoundToInt(HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity); - } - GUI.changed = true; - current.Use(); - } - } - else - { - if ((Event.current.mousePosition - EditorGUI.s_DragStartPos).sqrMagnitude > EditorGUI.kDragDeadzone) - { - EditorGUI.s_DragCandidateState = 2; - GUIUtility.keyboardControl = id; - } - current.Use(); - } - } - break; - case EventType.KeyDown: - if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape && EditorGUI.s_DragCandidateState != 0) - { - floatVal = EditorGUI.s_DragStartValue; - intVal = EditorGUI.s_DragStartIntValue; - GUI.changed = true; - GUIUtility.hotControl = 0; - current.Use(); - } - break; - case EventType.Repaint: - EditorGUIUtility.AddCursorRect(dragHotZone, MouseCursor.SlideArrow); - break; - } + return EditorGUI.PasswordFieldInternal(position, password, style); } - internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable) + [ExcludeFromDocs] + public static string PasswordField(Rect position, string label, string password) { - return EditorGUI.DoFloatField(editor, position, dragHotZone, id, value, formatString, style, draggable, (Event.current.GetTypeForControl(id) != EventType.MouseDown) ? 0f : EditorGUI.CalculateFloatDragSensitivity(EditorGUI.s_DragStartValue)); + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, label, password, textField); } - internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + public static string PasswordField(Rect position, string label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - int num = 0; - EditorGUI.DoNumberField(editor, position, dragHotZone, id, true, ref value, ref num, formatString, style, draggable, dragSensitivity); - return value; + return EditorGUI.PasswordField(position, EditorGUIUtility.TempContent(label), password, style); } - internal static int DoIntField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, int value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + [ExcludeFromDocs] + public static string PasswordField(Rect position, GUIContent label, string password) { - float num = 0f; - EditorGUI.DoNumberField(editor, position, dragHotZone, id, false, ref num, ref value, formatString, style, draggable, dragSensitivity); - return value; + GUIStyle textField = EditorStyles.textField; + return EditorGUI.PasswordField(position, label, password, textField); } - internal static void DoNumberField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, bool isFloat, ref float floatVal, ref int intVal, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + public static string PasswordField(Rect position, GUIContent label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { - string allowedletters = (!isFloat) ? "0123456789-" : "inftynaeINFTYNAE0123456789.,-"; - if (draggable) - { - EditorGUI.DragNumberValue(dragHotZone, id, isFloat, ref floatVal, ref intVal, dragSensitivity); - } - Event current = Event.current; - string text; - if (GUIUtility.keyboardControl == id || (current.type == EventType.MouseDown && current.button == 0 && position.Contains(current.mousePosition))) - { - if (!editor.IsEditingControl(id)) - { - text = (EditorGUI.s_RecycledCurrentEditingString = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString))); - } - else - { - text = EditorGUI.s_RecycledCurrentEditingString; - if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") - { - text = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString)); - } - } - } - else - { - text = ((!isFloat) ? intVal.ToString(formatString) : floatVal.ToString(formatString)); - } - if (GUIUtility.keyboardControl == id) - { - bool flag; - text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); - if (flag) - { - GUI.changed = true; - EditorGUI.s_RecycledCurrentEditingString = text; - if (isFloat) - { - string a = text.ToLower(); - if (a == "inf" || a == "infinity") - { - floatVal = float.PositiveInfinity; - } - else - { - if (a == "-inf" || a == "-infinity") - { - floatVal = float.NegativeInfinity; - } - else - { - text = text.Replace(',', '.'); - if (!float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out floatVal)) - { - floatVal = (EditorGUI.s_RecycledCurrentEditingFloat = 0f); - return; - } - if (float.IsNaN(floatVal)) - { - floatVal = 0f; - } - EditorGUI.s_RecycledCurrentEditingFloat = floatVal; - } - } - } - else - { - if (!int.TryParse(text, out intVal)) - { - intVal = (EditorGUI.s_RecycledCurrentEditingInt = 0); - return; - } - EditorGUI.s_RecycledCurrentEditingInt = intVal; - } - } - } - else - { - bool flag; - text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); - } + return EditorGUI.PasswordFieldInternal(position, label, password, style); } - internal static int ArraySizeField(Rect position, GUIContent label, int value, GUIStyle style) + [ExcludeFromDocs] + public static float FloatField(Rect position, float value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ArraySizeFieldHash, FocusType.Keyboard, position); - return EditorGUI.ArraySizeField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, style); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, value, numberField); } - internal static int ArraySizeField(Rect position, int id, int value, GUIStyle style) + public static float FloatField(Rect position, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - EditorGUI.BeginChangeCheck(); - string s = EditorGUI.DelayedTextField(position, id, value.ToString(EditorGUI.kIntFieldFormatString), "0123456789-", style); - if (EditorGUI.EndChangeCheck()) - { - try - { - value = int.Parse(s, CultureInfo.InvariantCulture.NumberFormat); - } - catch (FormatException) - { - } - } - return value; + return EditorGUI.FloatFieldInternal(position, value, style); } - internal static string DelayedTextField(Rect position, string value, string allowedLetters, GUIStyle style) + [ExcludeFromDocs] + public static float FloatField(Rect position, string label, float value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_DelayedTextFieldHash, FocusType.Keyboard, position); - return EditorGUI.DelayedTextField(position, controlID, value, allowedLetters, style); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, label, value, numberField); } - internal static string DelayedTextField(Rect position, int id, string value, string allowedLetters, GUIStyle style) - { - string text; - if (GUIUtility.keyboardControl == id) - { - if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) - { - text = (EditorGUI.s_RecycledCurrentEditingString = value); - } - else - { - text = EditorGUI.s_RecycledCurrentEditingString; - } - Event current = Event.current; - if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") - { - text = value; - } - } - else - { - text = value; - } - bool changed = GUI.changed; - bool flag; - text = EditorGUI.s_DelayedTextEditor.OnGUI(id, text, out flag); - GUI.changed = false; - if (!flag) - { - text = EditorGUI.DoTextField(EditorGUI.s_DelayedTextEditor, id, position, text, style, allowedLetters, out flag, false, false, false); - GUI.changed = false; - if (GUIUtility.keyboardControl == id) - { - if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) - { - if (value != text) - { - GUI.changed = true; - value = text; - } - } - else - { - EditorGUI.s_RecycledCurrentEditingString = text; - } - } - } - else - { - GUI.changed = true; - value = text; - } - GUI.changed |= changed; - return value; + public static float FloatField(Rect position, string label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + { + return EditorGUI.FloatField(position, EditorGUIUtility.TempContent(label), value, style); } - internal static int IntFieldInternal(Rect position, int value, GUIStyle style) + [ExcludeFromDocs] + public static float FloatField(Rect position, GUIContent label, float value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); - return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kIntFieldFormatString, style, false, EditorGUI.CalculateIntDragSensitivity(value)); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.FloatField(position, label, value, numberField); } - internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style) + public static float FloatField(Rect position, GUIContent label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); - Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); - position.xMax = position2.x; - return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kIntFieldFormatString, style, true, EditorGUI.CalculateIntDragSensitivity(value)); + return EditorGUI.FloatFieldInternal(position, label, value, style); } - public static float Slider(Rect position, float value, float leftValue, float rightValue) + [ExcludeFromDocs] + public static double DoubleField(Rect position, double value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); - return EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, value, leftValue, rightValue, EditorGUI.kFloatFieldFormatString); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.DoubleField(position, value, numberField); } - public static float Slider(Rect position, string label, float value, float leftValue, float rightValue) + public static double DoubleField(Rect position, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - return EditorGUI.Slider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + return EditorGUI.DoubleFieldInternal(position, value, style); } - public static float Slider(Rect position, GUIContent label, float value, float leftValue, float rightValue) + [ExcludeFromDocs] + public static double DoubleField(Rect position, string label, double value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); - return EditorGUI.DoSlider(EditorGUI.PrefixLabel(position, controlID, label), EditorGUIUtility.DragZoneRect(position), controlID, value, leftValue, rightValue, EditorGUI.kFloatFieldFormatString); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.DoubleField(position, label, value, numberField); } - internal static float PowerSlider(Rect position, float sliderValue, float min, float max, float power) + public static double DoubleField(Rect position, string label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - float leftValue = EditorGUI.PowPreserveSign(min, 1f / power); - float rightValue = EditorGUI.PowPreserveSign(max, 1f / power); - float num = EditorGUI.PowPreserveSign(sliderValue, 1f / power); - EditorGUI.BeginChangeCheck(); - num = GUI.HorizontalSlider(position, num, leftValue, rightValue); - num = EditorGUI.PowPreserveSign(num, power); - if (!EditorGUI.EndChangeCheck()) - { - num = sliderValue; - } - return num; + return EditorGUI.DoubleField(position, EditorGUIUtility.TempContent(label), value, style); } - internal static float PowerSlider(Rect position, string label, float sliderValue, float min, float max, float power) + [ExcludeFromDocs] + public static double DoubleField(Rect position, GUIContent label, double value) { - return EditorGUI.PowerSlider(position, EditorGUIUtility.TempContent(label), sliderValue, min, max, power); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.DoubleField(position, label, value, numberField); } - internal static float PowerSlider(Rect position, GUIContent label, float sliderValue, float min, float max, float power) + public static double DoubleField(Rect position, GUIContent label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - position = EditorGUI.PrefixLabel(position, 46389, label); - return EditorGUI.PowerSlider(position, sliderValue, min, max, power); + return EditorGUI.DoubleFieldInternal(position, label, value, style); } - private static float PowPreserveSign(float f, float p) + [ExcludeFromDocs] + public static int IntField(Rect position, int value) { - float num = Mathf.Pow(Mathf.Abs(f), p); - return (f >= 0f) ? num : (-num); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, value, numberField); } - private static void DoPropertyContextMenu(SerializedProperty property) + public static int IntField(Rect position, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - GenericMenu genericMenu = new GenericMenu(); - SerializedProperty serializedProperty = property.serializedObject.FindProperty(property.propertyPath); - ScriptAttributeUtility.GetHandler(property).AddMenuItems(property, genericMenu); - if (property.hasMultipleDifferentValues && !property.hasVisibleChildren) - { - TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, serializedProperty, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); - } - if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) - { - genericMenu.AddItem(EditorGUIUtility.TextContent("Revert Value to Prefab"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.SetPrefabOverride), serializedProperty); - } - if (property.propertyPath.LastIndexOf(']') == property.propertyPath.Length - 1) - { - if (genericMenu.GetItemCount() > 0) - { - genericMenu.AddSeparator(string.Empty); - } - genericMenu.AddItem(EditorGUIUtility.TextContent("Duplicate Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DuplicateArrayElement), serializedProperty); - genericMenu.AddItem(EditorGUIUtility.TextContent("Delete Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DeleteArrayElement), serializedProperty); - } - if (Event.current.shift) - { - if (genericMenu.GetItemCount() > 0) - { - genericMenu.AddSeparator(string.Empty); - } - genericMenu.AddItem(EditorGUIUtility.TextContent("Print Property Path"), false, delegate(object e) - { - Debug.Log(((SerializedProperty)e).propertyPath); - }, serializedProperty); - } - Event.current.Use(); - if (genericMenu.GetItemCount() == 0) - { - return; - } - genericMenu.ShowAsContext(); + return EditorGUI.IntFieldInternal(position, value, style); } - public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue) + [ExcludeFromDocs] + public static int IntField(Rect position, string label, int value) { - EditorGUI.Slider(position, property, leftValue, rightValue, property.displayName); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, label, value, numberField); } - public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, string label) + public static int IntField(Rect position, string label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - EditorGUI.Slider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + return EditorGUI.IntField(position, EditorGUIUtility.TempContent(label), value, style); } - public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, GUIContent label) + [ExcludeFromDocs] + public static int IntField(Rect position, GUIContent label, int value) { - label = EditorGUI.BeginProperty(position, label, property); - EditorGUI.BeginChangeCheck(); - float floatValue = EditorGUI.Slider(position, label, property.floatValue, leftValue, rightValue); - if (EditorGUI.EndChangeCheck()) - { - property.floatValue = floatValue; - } - EditorGUI.EndProperty(); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.IntField(position, label, value, numberField); } - public static int IntSlider(Rect position, int value, int leftValue, int rightValue) + public static int IntField(Rect position, GUIContent label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); - return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + return EditorGUI.IntFieldInternal(position, label, value, style); } - public static int IntSlider(Rect position, string label, int value, int leftValue, int rightValue) + [ExcludeFromDocs] + public static long LongField(Rect position, long value) { - return EditorGUI.IntSlider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.LongField(position, value, numberField); } - public static int IntSlider(Rect position, GUIContent label, int value, int leftValue, int rightValue) + public static long LongField(Rect position, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); - return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.PrefixLabel(position, controlID, label), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + return EditorGUI.LongFieldInternal(position, value, style); } - public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue) + [ExcludeFromDocs] + public static long LongField(Rect position, string label, long value) { - EditorGUI.IntSlider(position, property, leftValue, rightValue, property.displayName); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.LongField(position, label, value, numberField); } - public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, string label) + public static long LongField(Rect position, string label, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - EditorGUI.IntSlider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + return EditorGUI.LongField(position, EditorGUIUtility.TempContent(label), value, style); } - public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, GUIContent label) + [ExcludeFromDocs] + public static long LongField(Rect position, GUIContent label, long value) { - label = EditorGUI.BeginProperty(position, label, property); - EditorGUI.BeginChangeCheck(); - int intValue = EditorGUI.IntSlider(position, label, property.intValue, leftValue, rightValue); - if (EditorGUI.EndChangeCheck()) - { - property.intValue = intValue; - } - EditorGUI.EndProperty(); + GUIStyle numberField = EditorStyles.numberField; + return EditorGUI.LongField(position, label, value, numberField); } - private static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString) + public static long LongField(Rect position, GUIContent label, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { - float num = position.width; - if (num >= 65f + EditorGUIUtility.fieldWidth) - { - float num2 = num - 5f - EditorGUIUtility.fieldWidth; - EditorGUI.BeginChangeCheck(); - int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderKnobHash, FocusType.Native, position); - if (GUIUtility.keyboardControl == id && !EditorGUI.s_RecycledEditor.IsEditingControl(id)) - { - GUIUtility.keyboardControl = controlID; - } - value = GUI.Slider(new Rect(position.x, position.y, num2, position.height), value, 0f, left, right, GUI.skin.horizontalSlider, (!EditorGUI.showMixedValue) ? GUI.skin.horizontalSliderThumb : "SliderMixed", true, controlID); - if (GUIUtility.keyboardControl == controlID || GUIUtility.hotControl == controlID) - { - GUIUtility.keyboardControl = id; - } - if (GUIUtility.keyboardControl == id && Event.current.type == EventType.KeyDown && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && (Event.current.keyCode == KeyCode.LeftArrow || Event.current.keyCode == KeyCode.RightArrow)) - { - float num3 = MathUtils.GetClosestPowerOfTen(Mathf.Abs((right - left) * 0.01f)); - if (formatString == EditorGUI.kIntFieldFormatString && num3 < 1f) - { - num3 = 1f; - } - if (Event.current.shift) - { - num3 *= 10f; - } - if (Event.current.keyCode == KeyCode.LeftArrow) - { - value -= num3 * 0.5001f; - } - else - { - value += num3 * 0.5001f; - } - value = MathUtils.RoundToMultipleOf(value, num3); - GUI.changed = true; - Event.current.Use(); - } - if (EditorGUI.EndChangeCheck()) - { - float minDifference = (right - left) / (num2 - (float)GUI.skin.horizontalSlider.padding.horizontal - GUI.skin.horizontalSliderThumb.fixedWidth); - value = MathUtils.RoundBasedOnMinimumDifference(value, minDifference); - if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) - { - EditorGUI.s_RecycledEditor.EndEditing(); - } - } - value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, new Rect(position.x + num2 + 5f, position.y, EditorGUIUtility.fieldWidth, position.height), dragZonePosition, id, value, formatString, EditorStyles.numberField, true); - } - else - { - num = Mathf.Min(EditorGUIUtility.fieldWidth, num); - position.x = position.xMax - num; - position.width = num; - value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, dragZonePosition, id, value, formatString, EditorStyles.numberField, true); - } - value = Mathf.Clamp(value, Mathf.Min(left, right), Mathf.Max(left, right)); - return value; + return EditorGUI.LongFieldInternal(position, label, value, style); } - public static void MinMaxSlider(GUIContent label, Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + [ExcludeFromDocs] + public static int Popup(Rect position, int selectedIndex, string[] displayedOptions) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native); - EditorGUI.DoMinMaxSlider(EditorGUI.PrefixLabel(position, controlID, label), controlID, ref minValue, ref maxValue, minLimit, maxLimit); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); } - public static void MinMaxSlider(Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + public static int Popup(Rect position, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - EditorGUI.DoMinMaxSlider(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native), ref minValue, ref maxValue, minLimit, maxLimit); + return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); } - private static void DoMinMaxSlider(Rect position, int id, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + [ExcludeFromDocs] + public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions) { - float num = maxValue - minValue; - EditorGUI.BeginChangeCheck(); - EditorGUIExt.DoMinMaxSlider(position, id, ref minValue, ref num, minLimit, maxLimit, minLimit, maxLimit, GUI.skin.horizontalSlider, EditorStyles.minMaxHorizontalSliderThumb, true); - if (EditorGUI.EndChangeCheck()) - { - maxValue = minValue + num; - } + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, displayedOptions, style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + } + [ExcludeFromDocs] + public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + } + public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.PopupInternal(position, label, selectedIndex, displayedOptions, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, selected, popup); + } + public static Enum EnumPopup(Rect position, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumPopup(position, GUIContent.none, selected, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, string label, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, label, selected, popup); + } + public static Enum EnumPopup(Rect position, string label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumPopup(position, EditorGUIUtility.TempContent(label), selected, style); + } + [ExcludeFromDocs] + public static Enum EnumPopup(Rect position, GUIContent label, Enum selected) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumPopup(position, label, selected, popup); } - private static int PopupInternal(Rect position, string label, int selectedIndex, string[] displayedOptions, GUIStyle style) + public static Enum EnumPopup(Rect position, GUIContent label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + return EditorGUI.EnumPopupInternal(position, label, selected, style); } - private static int PopupInternal(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, GUIStyle style) + [ExcludeFromDocs] + public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position); - return EditorGUI.DoPopup(EditorGUI.PrefixLabel(position, controlID, label), controlID, selectedIndex, displayedOptions, style); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); } - private static void Popup(Rect position, SerializedProperty property, GUIContent label) + public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - EditorGUI.BeginChangeCheck(); - int enumValueIndex = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.enumValueIndex : -1, EditorGUIUtility.TempContent(property.enumDisplayNames)); - if (EditorGUI.EndChangeCheck()) - { - property.enumValueIndex = enumValueIndex; - } + return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); } - internal static void Popup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, GUIContent label) + [ExcludeFromDocs] + public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) { - label = EditorGUI.BeginProperty(position, label, property); - EditorGUI.BeginChangeCheck(); - int intValue = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.intValue : -1, displayedOptions); - if (EditorGUI.EndChangeCheck()) - { - property.intValue = intValue; - } - EditorGUI.EndProperty(); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); } - private static Enum EnumPopupInternal(Rect position, GUIContent label, Enum selected, GUIStyle style) + public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - Type type = selected.GetType(); - if (!type.IsEnum) - { - throw new Exception("parameter _enum must be of type System.Enum"); - } - string[] names = Enum.GetNames(type); - int num = Array.IndexOf(names, Enum.GetName(type, selected)); - num = EditorGUI.Popup(position, label, num, EditorGUIUtility.TempContent(( - from x in names - select ObjectNames.NicifyVariableName(x)).ToArray()), style); - if (num < 0 || num >= names.Length) - { - return selected; - } - return (Enum)Enum.Parse(type, names[num]); + return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, displayedOptions, optionValues, style); } - private static int IntPopupInternal(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style) + [ExcludeFromDocs] + public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) { - int num; - if (optionValues != null) - { - num = 0; - while (num < optionValues.Length && selectedValue != optionValues[num]) - { - num++; - } - } - else - { - num = selectedValue; - } - num = EditorGUI.PopupInternal(position, label, num, displayedOptions, style); - if (optionValues == null) - { - return num; - } - if (num < 0 || num >= optionValues.Length) - { - return selectedValue; - } - return optionValues[num]; + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); } - internal static void IntPopupInternal(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label) + public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - label = EditorGUI.BeginProperty(position, label, property); - EditorGUI.BeginChangeCheck(); - int intValue = EditorGUI.IntPopupInternal(position, label, property.intValue, displayedOptions, optionValues, EditorStyles.popup); - if (EditorGUI.EndChangeCheck()) - { - property.intValue = intValue; - } - EditorGUI.EndProperty(); + return EditorGUI.IntPopupInternal(position, label, selectedValue, displayedOptions, optionValues, style); } - internal static int DoPopup(Rect position, int controlID, int selected, GUIContent[] popupValues, GUIStyle style) + [ExcludeFromDocs] + public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues) { - selected = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, selected); - GUIContent gUIContent = null; - if (gUIContent == null) - { - if (EditorGUI.showMixedValue) - { - gUIContent = EditorGUI.s_MixedValueContent; - } - else - { - if (selected < 0 || selected >= popupValues.Length) - { - gUIContent = GUIContent.none; - } - else - { - gUIContent = popupValues[selected]; - } - } - } - Event current = Event.current; - EventType type = current.type; - switch (type) - { - case EventType.KeyDown: - if (current.MainActionKeyForControl(controlID)) - { - if (Application.platform == RuntimePlatform.OSXEditor) - { - position.y = position.y - (float)(selected * 16) - 19f; - } - EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); - EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); - current.Use(); - } - return selected; - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_6A: - if (type != EventType.MouseDown) - { - return selected; - } - if (current.button == 0 && position.Contains(current.mousePosition)) - { - if (Application.platform == RuntimePlatform.OSXEditor) - { - position.y = position.y - (float)(selected * 16) - 19f; - } - EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); - EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); - GUIUtility.keyboardControl = controlID; - current.Use(); - } - return selected; - case EventType.Repaint: - { - Font font = style.font; - if (font && EditorGUIUtility.GetBoldDefaultFont() && font == EditorStyles.miniFont) - { - style.font = EditorStyles.miniBoldFont; - } - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, gUIContent, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); - style.font = font; - return selected; - } - } - goto IL_6A; + GUIContent label = null; + EditorGUI.IntPopup(position, property, displayedOptions, optionValues, label); } - internal static string TagFieldInternal(Rect position, string tag, GUIStyle style) + public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("null")] GUIContent label) { - position = EditorGUI.IndentedRect(position); - int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); - Event current = Event.current; - int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); - if (selectedValueForControl != -1) - { - string[] tags = InternalEditorUtility.tags; - if (selectedValueForControl >= tags.Length) - { - ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; - Selection.activeObject = EditorApplication.tagManager; - } - else - { - tag = tags[selectedValueForControl]; - } - } - if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) - { - string[] tags2 = InternalEditorUtility.tags; - int i; - for (i = 0; i < tags2.Length; i++) - { - if (tags2[i] == tag) - { - break; - } - } - ArrayUtility.Add(ref tags2, string.Empty); - ArrayUtility.Add(ref tags2, "Add Tag..."); - EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); - return tag; - } - if (Event.current.type == EventType.Repaint) - { - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, (!EditorGUI.showMixedValue) ? EditorGUIUtility.TempContent(tag) : EditorGUI.s_MixedValueContent, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); - } - return tag; + EditorGUI.IntPopupInternal(position, property, displayedOptions, optionValues, label); } - internal static string TagFieldInternal(Rect position, GUIContent label, string tag, GUIStyle style) + [ExcludeFromDocs] + public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - Event current = Event.current; - int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); - if (selectedValueForControl != -1) - { - string[] tags = InternalEditorUtility.tags; - if (selectedValueForControl >= tags.Length) - { - ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; - Selection.activeObject = EditorApplication.tagManager; - } - else - { - tag = tags[selectedValueForControl]; - } - } - if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) - { - string[] tags2 = InternalEditorUtility.tags; - int i; - for (i = 0; i < tags2.Length; i++) - { - if (tags2[i] == tag) - { - break; - } - } - ArrayUtility.Add(ref tags2, string.Empty); - ArrayUtility.Add(ref tags2, "Add Tag..."); - EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); - return tag; - } - if (Event.current.type == EventType.Repaint) - { - style.Draw(position, EditorGUIUtility.TempContent(tag), controlID, false); - } - return tag; + GUIStyle popup = EditorStyles.popup; + return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); + } + public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.IntPopupInternal(position, EditorGUIUtility.TempContent(label), selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); } - internal static int LayerFieldInternal(Rect position, GUIContent label, int layer, GUIStyle style) + [ExcludeFromDocs] + public static string TagField(Rect position, string tag) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - Event current = Event.current; - bool changed = GUI.changed; - int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); - if (selectedValueForControl != -1) - { - if (selectedValueForControl >= InternalEditorUtility.layers.Length) - { - ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Layers"; - Selection.activeObject = EditorApplication.tagManager; - GUI.changed = changed; - } - else - { - int num = 0; - for (int i = 0; i < 32; i++) - { - if (InternalEditorUtility.GetLayerName(i).Length != 0) - { - if (num == selectedValueForControl) - { - layer = i; - break; - } - num++; - } - } - } - } - if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) - { - int num2 = 0; - for (int j = 0; j < 32; j++) - { - if (InternalEditorUtility.GetLayerName(j).Length != 0) - { - if (j == layer) - { - break; - } - num2++; - } - } - string[] layers = InternalEditorUtility.layers; - ArrayUtility.Add(ref layers, string.Empty); - ArrayUtility.Add(ref layers, "Add Layer..."); - EditorGUI.DoPopup(position, controlID, num2, EditorGUIUtility.TempContent(layers), style); - Event.current.Use(); - return layer; - } - if (current.type == EventType.Repaint) - { - style.Draw(position, EditorGUIUtility.TempContent(InternalEditorUtility.GetLayerName(layer)), controlID, false); - } - return layer; + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, tag, popup); } - internal static int MaskFieldInternal(Rect position, GUIContent label, int mask, string[] displayedOptions, GUIStyle style) + public static string TagField(Rect position, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - return MaskFieldGUI.DoMaskField(position, controlID, mask, displayedOptions, style); + return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(string.Empty), tag, style); } - internal static int MaskFieldInternal(Rect position, int mask, string[] displayedOptions, GUIStyle style) + [ExcludeFromDocs] + public static string TagField(Rect position, string label, string tag) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); - return MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), controlID, mask, displayedOptions, style); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, label, tag, popup); } - internal static Enum EnumMaskFieldInternal(Rect position, GUIContent label, Enum enumValue, GUIStyle style) + public static string TagField(Rect position, string label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - Type type = enumValue.GetType(); - if (!type.IsEnum) - { - throw new Exception("parameter _enum must be of type System.Enum"); - } - int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); - Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); - position.xMax = position2.x; - string[] flagNames = ( - from x in Enum.GetNames(enumValue.GetType()) - select ObjectNames.NicifyVariableName(x)).ToArray(); - return Enum.Parse(enumValue.GetType(), MaskFieldGUI.DoMaskField(position2, controlID, Convert.ToInt32(enumValue), flagNames, style).ToString()) as Enum; + return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(label), tag, style); } - internal static Enum EnumMaskFieldInternal(Rect position, Enum enumValue, GUIStyle style) + [ExcludeFromDocs] + public static string TagField(Rect position, GUIContent label, string tag) { - Type type = enumValue.GetType(); - if (!type.IsEnum) - { - throw new Exception("parameter _enum must be of type System.Enum"); - } - string[] flagNames = ( - from x in Enum.GetNames(enumValue.GetType()) - select ObjectNames.NicifyVariableName(x)).ToArray(); - int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style); - return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + GUIStyle popup = EditorStyles.popup; + return EditorGUI.TagField(position, label, tag, popup); } - internal static Enum EnumMaskField(Rect position, Enum enumValue, GUIStyle style, out int changedFlags, out bool changedToValue) + public static string TagField(Rect position, GUIContent label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - Type type = enumValue.GetType(); - if (!type.IsEnum) - { - throw new Exception("parameter _enum must be of type System.Enum"); - } - string[] flagNames = ( - from x in Enum.GetNames(enumValue.GetType()) - select ObjectNames.NicifyVariableName(x)).ToArray(); - int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style, out changedFlags, out changedToValue); - return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + return EditorGUI.TagFieldInternal(position, label, tag, style); } - public static void ObjectField(Rect position, SerializedProperty property, GUIContent label) + [ExcludeFromDocs] + public static int LayerField(Rect position, int layer) { - EditorGUI.ObjectField(position, property, null, label, EditorStyles.objectField); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, layer, popup); } - public static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label) + public static int LayerField(Rect position, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - EditorGUI.ObjectField(position, property, objType, label, EditorStyles.objectField); + return EditorGUI.LayerFieldInternal(position, GUIContent.none, layer, style); } - internal static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + [ExcludeFromDocs] + public static int LayerField(Rect position, string label, int layer) { - label = EditorGUI.BeginProperty(position, label, property); - EditorGUI.ObjectFieldInternal(position, property, objType, label, style); - EditorGUI.EndProperty(); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, label, layer, popup); } - private static void ObjectFieldInternal(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + public static int LayerField(Rect position, string label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_PPtrHash, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - bool allowSceneObjects = false; - if (property != null) - { - UnityEngine.Object targetObject = property.serializedObject.targetObject; - if (targetObject != null && !EditorUtility.IsPersistent(targetObject)) - { - allowSceneObjects = true; - } - } - EditorGUI.DoObjectField(position, position, controlID, null, null, property, null, allowSceneObjects, style); + return EditorGUI.LayerFieldInternal(position, EditorGUIUtility.TempContent(label), layer, style); } - public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + [ExcludeFromDocs] + public static int LayerField(Rect position, GUIContent label, int layer) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); - return EditorGUI.DoObjectField(EditorGUI.IndentedRect(position), EditorGUI.IndentedRect(position), controlID, obj, objType, null, null, allowSceneObjects); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.LayerField(position, label, layer, popup); } - [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] - public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType) + public static int LayerField(Rect position, GUIContent label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); - return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, true); + return EditorGUI.LayerFieldInternal(position, label, layer, style); } - public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + [ExcludeFromDocs] + public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions) { - return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, allowSceneObjects); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); } - [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] - public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType) + public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, true); + return EditorGUI.MaskFieldInternal(position, label, mask, displayedOptions, style); } - public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + [ExcludeFromDocs] + public static int MaskField(Rect position, string label, int mask, string[] displayedOptions) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - if (EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f) - { - float num = Mathf.Min(position.width, position.height); - position.height = num; - position.xMin = position.xMax - num; - } - return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, allowSceneObjects); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); } - [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] - public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType) + public static int MaskField(Rect position, string label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - return EditorGUI.ObjectField(position, label, obj, objType, true); + return EditorGUI.MaskFieldInternal(position, GUIContent.Temp(label), mask, displayedOptions, style); } - internal static UnityEngine.Object ValidateObjectFieldAssignment(UnityEngine.Object[] references, Type objType, SerializedProperty property) + [ExcludeFromDocs] + public static int MaskField(Rect position, int mask, string[] displayedOptions) { - if (references.Length > 0) - { - bool flag = references[0] != null && references[0].GetType() == typeof(Texture2D); - if (objType == typeof(Sprite) && flag) - { - return SpriteUtility.TextureToSprite(references[0] as Texture2D); - } - if (property != null) - { - if ((property.type == "PPtr" || property.type == "PPtr<$Sprite>") && flag) - { - return SpriteUtility.TextureToSprite(references[0] as Texture2D); - } - if (references[0] != null && property.ValidateObjectReferenceValue(references[0])) - { - return references[0]; - } - if (property.type == "vector" && flag) - { - return SpriteUtility.TextureToSprite(references[0] as Texture2D); - } - } - else - { - if (references[0] != null && references[0].GetType() == typeof(GameObject) && typeof(Component).IsAssignableFrom(objType)) - { - GameObject gameObject = (GameObject)references[0]; - references = gameObject.GetComponents(typeof(Component)); - } - UnityEngine.Object[] array = references; - for (int i = 0; i < array.Length; i++) - { - UnityEngine.Object @object = array[i]; - if (@object != null && objType.IsAssignableFrom(@object.GetType())) - { - return @object; - } - } - } - } - return null; + GUIStyle popup = EditorStyles.popup; + return EditorGUI.MaskField(position, mask, displayedOptions, popup); + } + public static int MaskField(Rect position, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.MaskFieldInternal(position, mask, displayedOptions, style); + } + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, label, enumValue, popup); + } + public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + { + return EditorGUI.EnumMaskFieldInternal(position, label, enumValue, style); + } + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, string label, Enum enumValue) + { + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, label, enumValue, popup); } - private static UnityEngine.Object HandleTextureToSprite(Texture2D tex) + public static Enum EnumMaskField(Rect position, string label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); - for (int i = 0; i < array.Length; i++) - { - if (array[i].GetType() == typeof(Sprite)) - { - return array[i]; - } - } - return tex; + return EditorGUI.EnumMaskFieldInternal(position, EditorGUIUtility.TempContent(label), enumValue, style); } - public static Rect IndentedRect(Rect source) + [ExcludeFromDocs] + public static Enum EnumMaskField(Rect position, Enum enumValue) { - float indent = EditorGUI.indent; - return new Rect(source.x + indent, source.y, source.width - indent, source.height); + GUIStyle popup = EditorStyles.popup; + return EditorGUI.EnumMaskField(position, enumValue, popup); } - public static Vector2 Vector2Field(Rect position, string label, Vector2 value) + public static Enum EnumMaskField(Rect position, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) { - return EditorGUI.Vector2Field(position, EditorGUIUtility.TempContent(label), value); + return EditorGUI.EnumMaskFieldInternal(position, enumValue, style); } - public static Vector2 Vector2Field(Rect position, GUIContent label, Vector2 value) + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, string content) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); - position.height = 16f; - return EditorGUI.Vector2Field(position, value); + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, foldout2); } - private static Vector2 Vector2Field(Rect position, Vector2 value) + public static bool Foldout(Rect position, bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { - EditorGUI.s_Vector2Floats[0] = value.x; - EditorGUI.s_Vector2Floats[1] = value.y; - position.height = 16f; - EditorGUI.BeginChangeCheck(); - EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); - if (EditorGUI.EndChangeCheck()) - { - value.x = EditorGUI.s_Vector2Floats[0]; - value.y = EditorGUI.s_Vector2Floats[1]; - } - return value; + return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), false, style); } - public static Vector3 Vector3Field(Rect position, string label, Vector3 value) + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick) { - return EditorGUI.Vector3Field(position, EditorGUIUtility.TempContent(label), value); + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); } - public static Vector3 Vector3Field(Rect position, GUIContent label, Vector3 value) + public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); - position.height = 16f; - return EditorGUI.Vector3Field(position, value); + return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), toggleOnLabelClick, style); } - private static Vector3 Vector3Field(Rect position, Vector3 value) + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, GUIContent content) { - EditorGUI.s_Vector3Floats[0] = value.x; - EditorGUI.s_Vector3Floats[1] = value.y; - EditorGUI.s_Vector3Floats[2] = value.z; - position.height = 16f; - EditorGUI.BeginChangeCheck(); - EditorGUI.MultiFloatField(position, EditorGUI.s_XYZLabels, EditorGUI.s_Vector3Floats); - if (EditorGUI.EndChangeCheck()) - { - value.x = EditorGUI.s_Vector3Floats[0]; - value.y = EditorGUI.s_Vector3Floats[1]; - value.z = EditorGUI.s_Vector3Floats[2]; - } - return value; + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, foldout2); } - private static void Vector2Field(Rect position, SerializedProperty property, GUIContent label) + public static bool Foldout(Rect position, bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); - position.height = 16f; - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.NextVisible(true); - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); + return EditorGUI.FoldoutInternal(position, foldout, content, false, style); } - private static void Vector3Field(Rect position, SerializedProperty property, GUIContent label) + [ExcludeFromDocs] + public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); - position.height = 16f; - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.NextVisible(true); - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); } - private static void Vector4Field(Rect position, SerializedProperty property, GUIContent label) + public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 4); - position.height = 16f; - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.NextVisible(true); - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZWLabels, serializedProperty); + return EditorGUI.FoldoutInternal(position, foldout, content, toggleOnLabelClick, style); } - public static Vector4 Vector4Field(Rect position, string label, Vector4 value) + [ExcludeFromDocs] + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, int id) { - EditorGUI.s_Vector4Floats[0] = value.x; - EditorGUI.s_Vector4Floats[1] = value.y; - EditorGUI.s_Vector4Floats[2] = value.z; - EditorGUI.s_Vector4Floats[3] = value.w; - position.height = 16f; - GUI.Label(EditorGUI.IndentedRect(position), label, EditorStyles.label); - position.y += 16f; - EditorGUI.BeginChangeCheck(); - EditorGUI.indentLevel++; - EditorGUI.MultiFloatField(position, EditorGUI.s_XYZWLabels, EditorGUI.s_Vector4Floats); - EditorGUI.indentLevel--; - if (EditorGUI.EndChangeCheck()) - { - value.x = EditorGUI.s_Vector4Floats[0]; - value.y = EditorGUI.s_Vector4Floats[1]; - value.z = EditorGUI.s_Vector4Floats[2]; - value.w = EditorGUI.s_Vector4Floats[3]; - } - return value; + GUIStyle label2 = EditorStyles.label; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); } - public static Rect RectField(Rect position, Rect value) + [ExcludeFromDocs] + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label) { - position.height = 16f; - EditorGUI.s_Vector2Floats[0] = value.x; - EditorGUI.s_Vector2Floats[1] = value.y; - EditorGUI.BeginChangeCheck(); - EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); - if (EditorGUI.EndChangeCheck()) - { - value.x = EditorGUI.s_Vector2Floats[0]; - value.y = EditorGUI.s_Vector2Floats[1]; - } - position.y += 16f; - EditorGUI.s_Vector2Floats[0] = value.width; - EditorGUI.s_Vector2Floats[1] = value.height; - EditorGUI.BeginChangeCheck(); - EditorGUI.MultiFloatField(position, EditorGUI.s_WHLabels, EditorGUI.s_Vector2Floats); - if (EditorGUI.EndChangeCheck()) - { - value.width = EditorGUI.s_Vector2Floats[0]; - value.height = EditorGUI.s_Vector2Floats[1]; - } - return value; + GUIStyle label2 = EditorStyles.label; + int id = 0; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); } - public static Rect RectField(Rect position, string label, Rect value) + public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, [DefaultValue("0")] int id, [DefaultValue("EditorStyles.label")] GUIStyle style) { - return EditorGUI.RectField(position, EditorGUIUtility.TempContent(label), value); + EditorGUI.HandlePrefixLabelInternal(totalPosition, labelPosition, label, id, style); } - public static Rect RectField(Rect position, GUIContent label, Rect value) + [ExcludeFromDocs] + public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scaleMode) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); - position.height = 16f; - return EditorGUI.RectField(position, value); + float imageAspect = 0f; + EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); } - private static void RectField(Rect position, SerializedProperty property, GUIContent label) + [ExcludeFromDocs] + public static void DrawTextureAlpha(Rect position, Texture image) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); - position.height = 16f; - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.NextVisible(true); - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); - position.y += 16f; - EditorGUI.MultiPropertyField(position, EditorGUI.s_WHLabels, serializedProperty); + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); } - private static Rect DrawBoundsFieldLabelsAndAdjustPositionForValues(Rect position, bool drawOutside) + public static void DrawTextureAlpha(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) { - if (drawOutside) - { - position.xMin -= 50f; - } - GUI.Label(EditorGUI.IndentedRect(position), "Center:", EditorStyles.label); - position.y += 16f; - GUI.Label(EditorGUI.IndentedRect(position), "Extents:", EditorStyles.label); - position.y -= 16f; - position.xMin += 50f; - return position; + EditorGUI.DrawTextureAlphaInternal(position, image, scaleMode, imageAspect); } - public static Bounds BoundsField(Rect position, Bounds value) + [ExcludeFromDocs] + public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode) { - return EditorGUI.BoundsField(position, GUIContent.none, value); + float imageAspect = 0f; + EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); } - public static Bounds BoundsField(Rect position, GUIContent label, Bounds value) + [ExcludeFromDocs] + public static void DrawTextureTransparent(Rect position, Texture image) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); - if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) - { - position.y += 16f; - } - position.height = 16f; - position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); - value.center = EditorGUI.Vector3Field(position, value.center); - position.y += 16f; - value.extents = EditorGUI.Vector3Field(position, value.extents); - return value; + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); + } + public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + { + EditorGUI.DrawTextureTransparentInternal(position, image, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode) + { + float imageAspect = 0f; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image) + { + float imageAspect = 0f; + ScaleMode scaleMode = ScaleMode.StretchToFill; + Material mat = null; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } + public static void DrawPreviewTexture(Rect position, Texture image, [DefaultValue("null")] Material mat, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + { + EditorGUI.DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect); + } + [ExcludeFromDocs] + public static float GetPropertyHeight(SerializedProperty property, GUIContent label) + { + bool includeChildren = true; + return EditorGUI.GetPropertyHeight(property, label, includeChildren); + } + [ExcludeFromDocs] + public static float GetPropertyHeight(SerializedProperty property) + { + bool includeChildren = true; + GUIContent label = null; + return EditorGUI.GetPropertyHeight(property, label, includeChildren); } - private static void BoundsField(Rect position, SerializedProperty property, GUIContent label) + public static float GetPropertyHeight(SerializedProperty property, [DefaultValue("null")] GUIContent label, [DefaultValue("true")] bool includeChildren) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); - if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) - { - position.y += 16f; - } - position.height = 16f; - position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.NextVisible(true); - serializedProperty.NextVisible(true); - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); - serializedProperty.NextVisible(true); - position.y += 16f; - EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + return EditorGUI.GetPropertyHeightInternal(property, label, includeChildren); } - public static void MultiFloatField(Rect position, GUIContent label, GUIContent[] subLabels, float[] values) + [ExcludeFromDocs] + public static bool PropertyField(Rect position, SerializedProperty property) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); - position.height = 16f; - EditorGUI.MultiFloatField(position, subLabels, values); + bool includeChildren = false; + return EditorGUI.PropertyField(position, property, includeChildren); } - public static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values) + public static bool PropertyField(Rect position, SerializedProperty property, [DefaultValue("false")] bool includeChildren) { - EditorGUI.MultiFloatField(position, subLabels, values, 13f); + return EditorGUI.PropertyFieldInternal(position, property, null, includeChildren); } - internal static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values, float labelWidth) + [ExcludeFromDocs] + public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label) { - int num = values.Length; - float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; - Rect position2 = new Rect(position); - position2.width = num2; - float labelWidth2 = EditorGUIUtility.labelWidth; - int indentLevel = EditorGUI.indentLevel; - EditorGUIUtility.labelWidth = labelWidth; - EditorGUI.indentLevel = 0; - for (int i = 0; i < values.Length; i++) - { - values[i] = EditorGUI.FloatField(position2, subLabels[i], values[i]); - position2.x += num2 + 2f; - } - EditorGUIUtility.labelWidth = labelWidth2; - EditorGUI.indentLevel = indentLevel; + bool includeChildren = false; + return EditorGUI.PropertyField(position, property, label, includeChildren); } - public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, GUIContent label) + public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label, [DefaultValue("false")] bool includeChildren) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); - position.height = 16f; - EditorGUI.MultiPropertyField(position, subLabels, valuesIterator); + return EditorGUI.PropertyFieldInternal(position, property, label, includeChildren); } - public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator) + internal static void BeginHandleMixedValueContentColor() { - EditorGUI.MultiPropertyField(position, subLabels, valuesIterator, 13f, null); + EditorGUI.s_MixedValueContentColorTemp = GUI.contentColor; + GUI.contentColor = ((!EditorGUI.showMixedValue) ? GUI.contentColor : (GUI.contentColor * EditorGUI.s_MixedValueContentColor)); } - internal static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, float labelWidth, bool[] disabledMask) + internal static void EndHandleMixedValueContentColor() { - int num = subLabels.Length; - float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; - Rect position2 = new Rect(position); - position2.width = num2; - float labelWidth2 = EditorGUIUtility.labelWidth; - int indentLevel = EditorGUI.indentLevel; - EditorGUIUtility.labelWidth = labelWidth; - EditorGUI.indentLevel = 0; - for (int i = 0; i < subLabels.Length; i++) - { - if (disabledMask != null) - { - EditorGUI.BeginDisabledGroup(disabledMask[i]); - } - EditorGUI.PropertyField(position2, valuesIterator, subLabels[i]); - if (disabledMask != null) - { - EditorGUI.EndDisabledGroup(); - } - position2.x += num2 + 2f; - valuesIterator.NextVisible(false); - } - EditorGUIUtility.labelWidth = labelWidth2; - EditorGUI.indentLevel = indentLevel; + GUI.contentColor = EditorGUI.s_MixedValueContentColorTemp; } - internal static int CycleButton(Rect position, int selected, GUIContent[] options, GUIStyle style) + internal static bool IsEditingTextField() { - if (selected >= options.Length || selected < 0) - { - selected = 0; - GUI.changed = true; - } - if (GUI.Button(position, options[selected], style)) + return EditorGUI.RecycledTextEditor.s_ActuallyEditing; + } + internal static void EndEditingActiveTextField() + { + if (EditorGUI.activeEditor != null) { - selected++; - GUI.changed = true; - if (selected >= options.Length) - { - selected = 0; - } + EditorGUI.activeEditor.EndEditing(); } - return selected; } - public static Color ColorField(Rect position, Color value) + public static void FocusTextInControl(string name) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); - return EditorGUI.DoColorField(EditorGUI.IndentedRect(position), controlID, value, true, true); + GUI.FocusControl(name); + EditorGUIUtility.editingTextField = true; } - internal static Color ColorField(Rect position, Color value, bool showEyedropper, bool showAlpha) + internal static void ClearStacks() { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); - return EditorGUI.DoColorField(position, controlID, value, showEyedropper, showAlpha); + EditorGUI.s_EnabledStack.Clear(); + EditorGUI.s_ChangedStack.Clear(); + EditorGUI.s_PropertyStack.Clear(); + ScriptAttributeUtility.s_DrawerStack.Clear(); } - public static Color ColorField(Rect position, string label, Color value) + public static void BeginDisabledGroup(bool disabled) { - return EditorGUI.ColorField(position, EditorGUIUtility.TempContent(label), value); + EditorGUI.s_EnabledStack.Push(GUI.enabled); + GUI.enabled &= !disabled; } - public static Color ColorField(Rect position, GUIContent label, Color value) + public static void EndDisabledGroup() { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); - return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, true, true); + GUI.enabled = EditorGUI.s_EnabledStack.Pop(); } - internal static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha) + public static void BeginChangeCheck() { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); - return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, showEyedropper, showAlpha); + EditorGUI.s_ChangedStack.Push(GUI.changed); + GUI.changed = false; } - private static Color DoColorField(Rect position, int id, Color value, bool showEyedropper, bool showAlpha) + public static bool EndChangeCheck() { - Event current = Event.current; - GUIStyle colorField = EditorStyles.colorField; - Color result = value; - value = ((!EditorGUI.showMixedValue) ? value : Color.white); - EventType typeForControl = current.GetTypeForControl(id); - switch (typeForControl) - { - case EventType.KeyDown: - if (current.MainActionKeyForControl(id)) - { - Event.current.Use(); - EditorGUI.showMixedValue = false; - ColorPicker.Show(GUIView.current, value, showAlpha); - GUIUtility.ExitGUI(); - } - return result; - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_47: - if (typeForControl == EventType.ValidateCommand) - { - if (current.commandName == "UndoRedoPerformed" && GUIUtility.keyboardControl == id && ColorPicker.visible) - { - ColorPicker.color = value; - } - return result; - } - if (typeForControl == EventType.ExecuteCommand) - { - if (GUIUtility.keyboardControl == id) - { - string commandName = current.commandName; - switch (commandName) - { - case "EyeDropperUpdate": - HandleUtility.Repaint(); - break; - case "EyeDropperClicked": - { - GUI.changed = true; - HandleUtility.Repaint(); - Color lastPickedColor = EyeDropper.GetLastPickedColor(); - lastPickedColor.a = value.a; - EditorGUI.s_ColorPickID = 0; - return lastPickedColor; - } - case "EyeDropperCancelled": - HandleUtility.Repaint(); - EditorGUI.s_ColorPickID = 0; - break; - case "ColorPickerChanged": - GUI.changed = true; - HandleUtility.Repaint(); - return ColorPicker.color; - } - } - return result; - } - if (typeForControl != EventType.MouseDown) - { - return result; - } - if (showEyedropper) - { - position.width -= 20f; - } - if (position.Contains(current.mousePosition)) - { - GUIUtility.keyboardControl = id; - EditorGUI.showMixedValue = false; - ColorPicker.Show(GUIView.current, value, showAlpha); - GUIUtility.ExitGUI(); - } - if (showEyedropper) - { - position.width += 20f; - if (position.Contains(current.mousePosition)) - { - GUIUtility.keyboardControl = id; - EyeDropper.Start(GUIView.current); - EditorGUI.s_ColorPickID = id; - GUIUtility.ExitGUI(); - } - } - return result; - case EventType.Repaint: - { - Rect position2; - if (showEyedropper) - { - position2 = colorField.padding.Remove(position); - } - else - { - position2 = position; - } - if (showEyedropper && EditorGUI.s_ColorPickID == id) - { - Color pickedColor = EyeDropper.GetPickedColor(); - pickedColor.a = value.a; - EditorGUIUtility.DrawColorSwatch(position2, pickedColor, showAlpha); - } - else - { - EditorGUIUtility.DrawColorSwatch(position2, value, showAlpha); - } - if (showEyedropper) + bool changed = GUI.changed; + GUI.changed |= EditorGUI.s_ChangedStack.Pop(); + return changed; + } + private static void ShowTextEditorPopupMenu() + { + GenericMenu genericMenu = new GenericMenu(); + if (EditorGUI.s_RecycledEditor.hasSelection && !EditorGUI.s_RecycledEditor.isPasswordField) + { + if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) { - colorField.Draw(position, GUIContent.none, id); + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Cut", GUIView.current).SendEvent)); } - else + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Copy", GUIView.current).SendEvent)); + } + else + { + if (EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) { - EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Cut")); } - return result; + genericMenu.AddDisabledItem(EditorGUIUtility.TextContent("TextEditorPopup.Copy")); } + if (EditorGUI.s_RecycledEditor.CanPaste() && EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("TextEditorPopup.Paste"), false, new GenericMenu.MenuFunction(new EditorGUI.PopupMenuEvent("Paste", GUIView.current).SendEvent)); } - goto IL_47; + genericMenu.ShowAsContext(); } - public static AnimationCurve CurveField(Rect position, AnimationCurve value) + internal static void BeginCollectTooltips() { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, EditorGUI.kCurveColor, default(Rect), null); + EditorGUI.isCollectingTooltips = true; } - public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value) + internal static void EndCollectTooltips() { - return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value); + EditorGUI.isCollectingTooltips = false; } - public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value) + public static void DropShadowLabel(Rect position, string text) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, EditorGUI.kCurveColor, default(Rect), null); + EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), "PreOverlayLabel", 0.6f); } - public static AnimationCurve CurveField(Rect position, AnimationCurve value, Color color, Rect ranges) + public static void DropShadowLabel(Rect position, GUIContent content) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, color, ranges, null); + EditorGUI.DoDropShadowLabel(position, content, "PreOverlayLabel", 0.6f); } - public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value, Color color, Rect ranges) + public static void DropShadowLabel(Rect position, string text, GUIStyle style) { - return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value, color, ranges); + EditorGUI.DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), style, 0.6f); } - public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value, Color color, Rect ranges) + public static void DropShadowLabel(Rect position, GUIContent content, GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, color, ranges, null); + EditorGUI.DoDropShadowLabel(position, content, style, 0.6f); } - public static void CurveField(Rect position, SerializedProperty value, Color color, Rect ranges) + internal static void DoDropShadowLabel(Rect position, GUIContent content, GUIStyle style, float shadowOpa) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - EditorGUI.DoCurveField(position, controlID, null, color, ranges, value); + if (Event.current.type != EventType.Repaint) + { + return; + } + EditorGUI.DrawLabelShadow(position, content, style, shadowOpa); + style.Draw(position, content, false, false, false, false); } - private static void SetCurveEditorWindowCurve(AnimationCurve value, SerializedProperty property, Color color) + internal static void DrawLabelShadow(Rect position, GUIContent content, GUIStyle style, float shadowOpa) { - if (property != null) + Color color = GUI.color; + Color contentColor = GUI.contentColor; + Color backgroundColor = GUI.backgroundColor; + GUI.contentColor = new Color(0f, 0f, 0f, 0f); + style.Draw(position, content, false, false, false, false); + position.y += 1f; + GUI.backgroundColor = new Color(0f, 0f, 0f, 0f); + GUI.contentColor = contentColor; + EditorGUI.Draw4(position, content, 1f, GUI.color.a * shadowOpa, style); + EditorGUI.Draw4(position, content, 2f, GUI.color.a * shadowOpa * 0.42f, style); + GUI.color = color; + GUI.backgroundColor = backgroundColor; + } + private static void Draw4(Rect position, GUIContent content, float offset, float alpha, GUIStyle style) + { + GUI.color = new Color(0f, 0f, 0f, alpha); + position.y -= offset; + style.Draw(position, content, false, false, false, false); + position.y += offset * 2f; + style.Draw(position, content, false, false, false, false); + position.y -= offset; + position.x -= offset; + style.Draw(position, content, false, false, false, false); + position.x += offset * 2f; + style.Draw(position, content, false, false, false, false); + } + internal static string DoTextField(EditorGUI.RecycledTextEditor editor, int id, Rect position, string text, GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField) + { + Event current = Event.current; + string result = text; + if (text == null) { - CurveEditorWindow.curve = ((!property.hasMultipleDifferentValues) ? property.animationCurveValue : new AnimationCurve()); + text = string.Empty; } - else + if (EditorGUI.showMixedValue) { - CurveEditorWindow.curve = value; + text = string.Empty; } - CurveEditorWindow.color = color; - } - private static AnimationCurve DoCurveField(Rect position, int id, AnimationCurve value, Color color, Rect ranges, SerializedProperty property) - { - Event current = Event.current; - position.width = Mathf.Max(position.width, 2f); - position.height = Mathf.Max(position.height, 2f); - if (GUIUtility.keyboardControl == id && Event.current.type != EventType.Layout) + if (EditorGUI.HasKeyboardFocus(id) && Event.current.type != EventType.Layout) { - if (EditorGUI.s_CurveID != id) + if (editor.IsEditingControl(id)) { - EditorGUI.s_CurveID = id; - if (CurveEditorWindow.visible) + editor.position = position; + editor.style = style; + editor.controlID = id; + editor.multiline = multiline; + editor.isPasswordField = passwordField; + editor.ClampPos(); + editor.UpdateScrollOffsetIfNeeded(); + } + else + { + if (EditorGUIUtility.editingTextField) + { + editor.BeginEditing(id, text, position, style, multiline, passwordField); + if (GUI.skin.settings.cursorColor.a > 0f) + { + editor.SelectAll(); + } + } + } + } + if (editor.controlID == id && GUIUtility.keyboardControl != id) + { + editor.controlID = 0; + } + bool flag = false; + string text2 = editor.content.text; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.MouseDown: + if (position.Contains(current.mousePosition) && current.button == 0) + { + if (editor.IsEditingControl(id)) + { + if (Event.current.clickCount == 2 && GUI.skin.settings.doubleClickSelectsWord) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + editor.SelectCurrentWord(); + editor.MouseDragSelectsWholeWords(true); + editor.DblClickSnap(TextEditor.DblClickSnapping.WORDS); + EditorGUI.s_DragToPosition = false; + } + else + { + if (Event.current.clickCount == 3 && GUI.skin.settings.tripleClickSelectsLine) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + editor.SelectCurrentParagraph(); + editor.MouseDragSelectsWholeWords(true); + editor.DblClickSnap(TextEditor.DblClickSnapping.PARAGRAPHS); + EditorGUI.s_DragToPosition = false; + } + else + { + editor.MoveCursorToPosition(Event.current.mousePosition); + EditorGUI.s_SelectAllOnMouseUp = false; + } + } + } + else + { + GUIUtility.keyboardControl = id; + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.MoveCursorToPosition(Event.current.mousePosition); + if (GUI.skin.settings.cursorColor.a > 0f) + { + EditorGUI.s_SelectAllOnMouseUp = true; + } + } + GUIUtility.hotControl = id; + current.Use(); + } + goto IL_967; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + if (EditorGUI.s_Dragged && EditorGUI.s_DragToPosition) + { + editor.MoveSelectionToAltCursor(); + flag = true; + } + else + { + if (EditorGUI.s_PostPoneMove) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + } + else + { + if (EditorGUI.s_SelectAllOnMouseUp) + { + if (GUI.skin.settings.cursorColor.a > 0f) + { + editor.SelectAll(); + } + EditorGUI.s_SelectAllOnMouseUp = false; + } + } + } + editor.MouseDragSelectsWholeWords(false); + EditorGUI.s_DragToPosition = true; + EditorGUI.s_Dragged = false; + EditorGUI.s_PostPoneMove = false; + if (current.button == 0) + { + GUIUtility.hotControl = 0; + current.Use(); + } + } + goto IL_967; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_121: + switch (typeForControl) + { + case EventType.ValidateCommand: + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + switch (commandName) + { + case "Cut": + case "Copy": + if (editor.hasSelection) + { + current.Use(); + } + break; + case "Paste": + if (editor.CanPaste()) + { + current.Use(); + } + break; + case "SelectAll": + current.Use(); + break; + case "UndoRedoPerformed": + editor.content.text = text; + current.Use(); + break; + } + } + goto IL_967; + case EventType.ExecuteCommand: + if (GUIUtility.keyboardControl == id) { - EditorGUI.SetCurveEditorWindowCurve(value, property, color); - EditorGUI.ShowCurvePopup(GUIView.current, ranges); + string commandName = current.commandName; + switch (commandName) + { + case "OnLostFocus": + if (EditorGUI.activeEditor != null) + { + EditorGUI.activeEditor.EndEditing(); + } + current.Use(); + break; + case "Cut": + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.Cut(); + flag = true; + break; + case "Copy": + editor.Copy(); + current.Use(); + break; + case "Paste": + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.Paste(); + flag = true; + break; + case "SelectAll": + editor.SelectAll(); + current.Use(); + break; + } } - } - else - { - if (CurveEditorWindow.visible && Event.current.type == EventType.Repaint) + goto IL_967; + case EventType.DragExited: + goto IL_967; + case EventType.ContextClick: + if (position.Contains(current.mousePosition)) { - EditorGUI.SetCurveEditorWindowCurve(value, property, color); - CurveEditorWindow.instance.Repaint(); + if (!editor.IsEditingControl(id)) + { + GUIUtility.keyboardControl = id; + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.MoveCursorToPosition(Event.current.mousePosition); + } + EditorGUI.ShowTextEditorPopupMenu(); + Event.current.Use(); } + goto IL_967; + default: + goto IL_967; } - } - EventType typeForControl = current.GetTypeForControl(id); - switch (typeForControl) - { - case EventType.KeyDown: - if (current.MainActionKeyForControl(id)) + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) { - EditorGUI.s_CurveID = id; - EditorGUI.SetCurveEditorWindowCurve(value, property, color); - EditorGUI.ShowCurvePopup(GUIView.current, ranges); + if (!current.shift && editor.hasSelection && EditorGUI.s_DragToPosition) + { + editor.MoveAltCursorToPosition(Event.current.mousePosition); + } + else + { + if (current.shift) + { + editor.MoveCursorToPosition(Event.current.mousePosition); + } + else + { + editor.SelectToPosition(Event.current.mousePosition); + } + EditorGUI.s_DragToPosition = false; + EditorGUI.s_SelectAllOnMouseUp = !editor.hasSelection; + } + EditorGUI.s_Dragged = true; current.Use(); - GUIUtility.ExitGUI(); } - return value; - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_D3: - if (typeForControl == EventType.MouseDown) + goto IL_967; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) { - if (position.Contains(current.mousePosition)) + char character = current.character; + if (editor.IsEditingControl(id) && editor.HandleKeyEvent(current)) { - EditorGUI.s_CurveID = id; - GUIUtility.keyboardControl = id; - EditorGUI.SetCurveEditorWindowCurve(value, property, color); - EditorGUI.ShowCurvePopup(GUIView.current, ranges); current.Use(); - GUIUtility.ExitGUI(); + flag = true; } - return value; - } - if (typeForControl != EventType.ExecuteCommand) - { - return value; - } - if (EditorGUI.s_CurveID == id) - { - string commandName = current.commandName; - if (commandName != null) + else { - if (EditorGUI.<>f__switch$map3 == null) + if (current.keyCode == KeyCode.Escape) { - EditorGUI.<>f__switch$map3 = new Dictionary(1) + if (editor.IsEditingControl(id)) { - + if (style == EditorStyles.toolbarSearchField || style == EditorStyles.searchField) { - "CurveChanged", - 0 + EditorGUI.s_OriginalText = string.Empty; } - }; + editor.content.text = EditorGUI.s_OriginalText; + editor.EndEditing(); + flag = true; + } } - int num; - if (EditorGUI.<>f__switch$map3.TryGetValue(commandName, out num)) + else { - if (num == 0) + if (character == '\n' || character == '\u0003') { - GUI.changed = true; - AnimationCurvePreviewCache.ClearCache(); - HandleUtility.Repaint(); - if (property != null) + if (!editor.IsEditingControl(id)) { - property.animationCurveValue = CurveEditorWindow.curve; - if (property.hasMultipleDifferentValues) + editor.BeginEditing(id, text, position, style, multiline, passwordField); + editor.SelectAll(); + } + else + { + if (multiline && !current.alt && !current.shift && !current.control) { - Debug.LogError("AnimationCurve SerializedProperty hasMultipleDifferentValues is true after writing."); + editor.Insert(character); + flag = true; + goto IL_967; + } + editor.EndEditing(); + } + current.Use(); + } + else + { + if (character == '\t' || current.keyCode == KeyCode.Tab) + { + if (multiline && editor.IsEditingControl(id)) + { + bool flag2 = allowedletters == null || allowedletters.IndexOf(character) != -1; + bool flag3 = !current.alt && !current.shift && !current.control && character == '\t'; + if (flag3 && flag2) + { + editor.Insert(character); + flag = true; + } + } + } + else + { + if (character != '\u0019' && character != '\u001b') + { + if (editor.IsEditingControl(id)) + { + bool flag4 = (allowedletters == null || allowedletters.IndexOf(character) != -1) && character != '\0'; + if (flag4) + { + editor.Insert(character); + flag = true; + } + else + { + if (Input.compositionString != string.Empty) + { + editor.ReplaceSelection(string.Empty); + flag = true; + } + current.Use(); + } + } } } - return CurveEditorWindow.curve; } } } } - return value; - case EventType.Repaint: - { - Rect position2 = position; - position2.y += 1f; - position2.height -= 1f; - if (ranges != default(Rect)) - { - EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor, ranges); - } - else - { - EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor); - } - EditorStyles.colorPickerBox.Draw(position2, GUIContent.none, id, false); - return value; - } - } - goto IL_D3; - } - private static void ShowCurvePopup(GUIView viewToUpdate, Rect ranges) - { - CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); - if (ranges.width > 0f && ranges.height > 0f && ranges.width != float.PositiveInfinity && ranges.height != float.PositiveInfinity) - { - curveEditorSettings.hRangeMin = ranges.xMin; - curveEditorSettings.hRangeMax = ranges.xMax; - curveEditorSettings.vRangeMin = ranges.yMin; - curveEditorSettings.vRangeMax = ranges.yMax; - } - CurveEditorWindow.instance.Show(GUIView.current, curveEditorSettings); - } - private static bool ValidTargetForIconSelection(UnityEngine.Object[] targets) - { - return (targets[0] as MonoScript || targets[0] as GameObject) && targets.Length == 1; - } - internal static void ObjectIconDropDown(Rect position, UnityEngine.Object[] targets, bool showLabelIcons, Texture2D nullIcon, SerializedProperty iconProperty) - { - if (EditorGUI.s_IconTextureInactive == null) - { - EditorGUI.s_IconTextureInactive = (Material)EditorGUIUtility.LoadRequired("Inspectors/InactiveGUI.mat"); - } - if (Event.current.type == EventType.Repaint) - { - Texture2D texture2D = null; - if (!iconProperty.hasMultipleDifferentValues) - { - texture2D = AssetPreview.GetMiniThumbnail(targets[0]); - } - if (texture2D == null) - { - texture2D = nullIcon; - } - Vector2 vector = new Vector2(position.width, position.height); - if (texture2D) - { - vector.x = Mathf.Min((float)texture2D.width, vector.x); - vector.y = Mathf.Min((float)texture2D.height, vector.y); - } - Rect rect = new Rect(position.x + position.width / 2f - vector.x / 2f, position.y + position.height / 2f - vector.y / 2f, vector.x, vector.y); - GameObject gameObject = targets[0] as GameObject; - bool flag = gameObject && !EditorUtility.IsPersistent(targets[0]) && (!gameObject.activeSelf || !gameObject.activeInHierarchy); - if (flag) - { - Graphics.DrawTexture(rect, texture2D, new Rect(0f, 0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 1f), EditorGUI.s_IconTextureInactive); - } - else - { - GUI.DrawTexture(rect, texture2D); - } - if (EditorGUI.ValidTargetForIconSelection(targets)) - { - if (EditorGUI.s_IconDropDown == null) - { - EditorGUI.s_IconDropDown = EditorGUIUtility.IconContent("Icon Dropdown"); - } - GUIStyle.none.Draw(new Rect(Mathf.Max(position.x + 2f, rect.x - 6f), rect.yMax - rect.height * 0.2f, 13f, 8f), EditorGUI.s_IconDropDown, false, false, false, false); - } - } - if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none) && EditorGUI.ValidTargetForIconSelection(targets) && IconSelector.ShowAtPosition(targets[0], position, showLabelIcons)) - { - GUIUtility.ExitGUI(); - } - } - public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object targetObj) - { - return EditorGUI.InspectorTitlebar(position, foldout, new UnityEngine.Object[] - { - targetObj - }); - } - public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object[] targetObjs) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); - if (EditorGUI.s_TitleSettingsIcon == null) - { - EditorGUI.s_TitleSettingsIcon = EditorGUIUtility.IconContent("_Popup"); - } - GUIStyle inspectorTitlebar = EditorStyles.inspectorTitlebar; - GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText; - Rect rect = new Rect(position.x + (float)inspectorTitlebar.padding.left, position.y + (float)inspectorTitlebar.padding.top, 16f, 16f); - Rect rect2 = new Rect(position.xMax - (float)inspectorTitlebar.padding.right - 2f - 16f, rect.y, 16f, 16f); - Rect position2 = new Rect(rect.xMax + 2f + 2f + 16f, rect.y, 100f, rect.height); - position2.xMax = rect2.xMin - 2f; - int num = -1; - for (int i = 0; i < targetObjs.Length; i++) + goto IL_967; + case EventType.Repaint: { - UnityEngine.Object target = targetObjs[i]; - int objectEnabled = EditorUtility.GetObjectEnabled(target); - if (num == -1) + string text3; + if (editor.IsEditingControl(id)) { - num = objectEnabled; + text3 = ((!passwordField) ? editor.content.text : string.Empty.PadRight(editor.content.text.Length, '*')); } else { - if (num != objectEnabled) + if (EditorGUI.showMixedValue) { - num = -2; + text3 = EditorGUI.s_MixedValueContent.text; + } + else + { + text3 = ((!passwordField) ? text : string.Empty.PadRight(text.Length, '*')); } } - } - if (num != -1) - { - bool flag = AnimationMode.IsPropertyAnimated(targetObjs[0], "m_Enabled"); - bool flag2 = num != 0; - EditorGUI.showMixedValue = (num == -2); - Rect position3 = rect; - position3.x = rect.xMax + 2f; - EditorGUI.BeginChangeCheck(); - Color color = GUI.color; - if (flag) + if (!string.IsNullOrEmpty(EditorGUI.s_UnitString) && !passwordField) { - GUI.color = AnimationMode.animatedPropertyColor; + text3 = text3 + " " + EditorGUI.s_UnitString; } - int controlID2 = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); - flag2 = EditorGUIInternal.DoToggleForward(position3, controlID2, flag2, GUIContent.none, EditorStyles.toggle); - if (flag) + if (GUIUtility.hotControl == 0) { - GUI.color = color; + EditorGUIUtility.AddCursorRect(position, MouseCursor.Text); } - if (EditorGUI.EndChangeCheck()) + if (!editor.IsEditingControl(id)) { - Undo.RecordObjects(targetObjs, ((!flag2) ? "Disable" : "Enable") + " Component" + ((targetObjs.Length <= 1) ? string.Empty : "s")); - for (int j = 0; j < targetObjs.Length; j++) - { - UnityEngine.Object target2 = targetObjs[j]; - EditorUtility.SetObjectEnabled(target2, flag2); - } + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUIUtility.TempContent(text3), id, false); + EditorGUI.EndHandleMixedValueContentColor(); } - EditorGUI.showMixedValue = false; - } - Rect position4 = rect2; - position4.x -= 18f; - if (EditorGUI.HelpIconButton(position4, targetObjs[0])) - { - position2.xMax = position4.xMin - 2f; + else + { + editor.DrawCursor(text3); + } + goto IL_967; } - Event current = Event.current; - Texture2D i2 = null; - if (current.type == EventType.Repaint) - { - i2 = AssetPreview.GetMiniThumbnail(targetObjs[0]); } - if (EditorGUI.ButtonMouseDown(rect, EditorGUIUtility.TempContent(i2), FocusType.Passive, GUIStyle.none) && targetObjs[0] as MonoScript != null && IconSelector.ShowAtPosition(targetObjs[0], rect, true)) + goto IL_121; + IL_967: + if (GUIUtility.keyboardControl == id) { - GUIUtility.ExitGUI(); + GUIUtility.textFieldInput = true; } - EventType type = current.type; - if (type != EventType.MouseDown) + changed = false; + if (flag) { - if (type == EventType.Repaint) - { - inspectorTitlebar.Draw(position, GUIContent.none, controlID, foldout); - position = inspectorTitlebar.padding.Remove(position); - inspectorTitlebarText.Draw(position2, EditorGUIUtility.TempContent(ObjectNames.GetInspectorTitle(targetObjs[0])), controlID, foldout); - inspectorTitlebarText.Draw(rect2, EditorGUI.s_TitleSettingsIcon, controlID, foldout); - } + changed = (text2 != editor.content.text); + current.Use(); } - else + if (changed) { - if (rect2.Contains(current.mousePosition)) - { - EditorUtility.DisplayObjectContextMenu(rect2, targetObjs, 0); - current.Use(); - } + GUI.changed = true; + return editor.content.text; } - return EditorGUI.DoObjectFoldout(controlID, position, targetObjs, foldout); + EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = true; + return result; } - internal static bool HelpIconButton(Rect position, UnityEngine.Object obj) + internal static Event KeyEventField(Rect position, Event evt) { - if (EditorGUI.s_HelpIcon == null) - { - EditorGUI.s_HelpIcon = EditorGUIUtility.IconContent("_Help"); - } - bool flag = Unsupported.IsDeveloperBuild(); - bool defaultToMonoBehaviour = !flag || obj.GetType().Assembly.ToString().StartsWith("Assembly-"); - bool flag2 = Help.HasHelpForObject(obj, defaultToMonoBehaviour); - if (flag2 || flag) - { - Color color = GUI.color; - GUIContent gUIContent = new GUIContent(EditorGUI.s_HelpIcon); - string niceHelpNameForObject = Help.GetNiceHelpNameForObject(obj, defaultToMonoBehaviour); - if (flag && !flag2) - { - GUI.color = Color.yellow; - bool flag3 = obj is MonoBehaviour; - string arg = ((!flag3) ? "sealed partial class-" : "script-") + niceHelpNameForObject; - gUIContent.tooltip = string.Format("Could not find Reference page for {0} ({1}).\nDocs for this object is missing or all docs are missing.\nThis warning only shows up in development builds.", niceHelpNameForObject, arg); - } - else - { - gUIContent.tooltip = string.Format("Open Reference for {0}.", niceHelpNameForObject); - } - if (GUI.Button(position, gUIContent, EditorStyles.inspectorTitlebarText)) - { - Help.ShowHelpForObject(obj); - } - GUI.color = color; - return true; - } - return false; + return EditorGUI.DoKeyEventField(position, evt, GUI.skin.textField); } - internal static bool FoldoutInternal(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, GUIStyle style) + internal static Event DoKeyEventField(Rect position, Event _event, GUIStyle style) { - Rect rect = position; - if (EditorGUIUtility.hierarchyMode) - { - int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; - position.xMin -= (float)num; - } - int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); - EventType eventType = Event.current.type; - if (!GUI.enabled && GUIClip.enabled && (Event.current.rawType == EventType.MouseDown || Event.current.rawType == EventType.MouseDrag || Event.current.rawType == EventType.MouseUp)) - { - eventType = Event.current.rawType; - } - EventType eventType2 = eventType; - switch (eventType2) + int controlID = GUIUtility.GetControlID(EditorGUI.s_KeyEventFieldHash, FocusType.Native, position); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) { case EventType.MouseDown: - if (position.Contains(Event.current.mousePosition) && Event.current.button == 0) - { - int num2 = controlID; - GUIUtility.hotControl = num2; - GUIUtility.keyboardControl = num2; - Event.current.Use(); - } - return foldout; - case EventType.MouseUp: - if (GUIUtility.hotControl == controlID) + if (position.Contains(current.mousePosition)) { - GUIUtility.hotControl = 0; - Event.current.Use(); - Rect rect2 = position; - if (!toggleOnLabelClick) + GUIUtility.hotControl = controlID; + current.Use(); + if (EditorGUI.bKeyEventActive) { - rect2.width = (float)style.padding.left; - rect2.x += EditorGUI.indent; + EditorGUI.bKeyEventActive = false; } - if (rect2.Contains(Event.current.mousePosition)) + else { - GUI.changed = true; - return !foldout; + EditorGUI.bKeyEventActive = true; } } - return foldout; - case EventType.MouseMove: - case EventType.KeyUp: - case EventType.ScrollWheel: - case EventType.Layout: - IL_D8: - if (eventType2 != EventType.DragExited) - { - return foldout; - } - if (EditorGUI.s_DragUpdatedOverID == controlID) + return _event; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) { - EditorGUI.s_DragUpdatedOverID = 0; - Event.current.Use(); + GUIUtility.hotControl = controlID; + current.Use(); } - return foldout; + return _event; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { - Event.current.Use(); + current.Use(); } - return foldout; + break; case EventType.KeyDown: - if (GUIUtility.keyboardControl == controlID) - { - KeyCode keyCode = Event.current.keyCode; - if ((keyCode == KeyCode.LeftArrow && foldout) || (keyCode == KeyCode.RightArrow && !foldout)) - { - foldout = !foldout; - GUI.changed = true; - Event.current.Use(); - } - } - return foldout; - case EventType.Repaint: - { - EditorStyles.foldoutSelected.Draw(position, GUIContent.none, controlID, EditorGUI.s_DragUpdatedOverID == controlID); - Rect position2 = new Rect(position.x + EditorGUI.indent, position.y, EditorGUIUtility.labelWidth - EditorGUI.indent, position.height); - if (EditorGUI.showMixedValue && !foldout) - { - style.Draw(position2, content, controlID, foldout); - EditorGUI.BeginHandleMixedValueContentColor(); - Rect position3 = rect; - position3.xMin += EditorGUIUtility.labelWidth; - EditorStyles.label.Draw(position3, EditorGUI.s_MixedValueContent, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); - } - else - { - style.Draw(position2, content, controlID, foldout); - } - return foldout; - } - case EventType.DragUpdated: - if (EditorGUI.s_DragUpdatedOverID == controlID) + if (GUIUtility.hotControl == controlID && EditorGUI.bKeyEventActive) { - if (position.Contains(Event.current.mousePosition)) - { - if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) - { - foldout = true; - Event.current.Use(); - } - } - else + if (current.character == '\0' && ((current.alt && (current.keyCode == KeyCode.AltGr || current.keyCode == KeyCode.LeftAlt || current.keyCode == KeyCode.RightAlt)) || (current.control && (current.keyCode == KeyCode.LeftControl || current.keyCode == KeyCode.RightControl)) || (current.command && (current.keyCode == KeyCode.LeftCommand || current.keyCode == KeyCode.RightCommand || current.keyCode == KeyCode.LeftWindows || current.keyCode == KeyCode.RightWindows)) || (current.shift && (current.keyCode == KeyCode.LeftShift || current.keyCode == KeyCode.RightShift || current.keyCode == KeyCode.None)))) { - EditorGUI.s_DragUpdatedOverID = 0; + return _event; } + EditorGUI.bKeyEventActive = false; + GUI.changed = true; + GUIUtility.hotControl = 0; + Event result = new Event(current); + current.Use(); + return result; + } + break; + case EventType.Repaint: + if (EditorGUI.bKeyEventActive) + { + GUIContent content = EditorGUIUtility.TempContent("[Please press a key]"); + style.Draw(position, content, controlID); } else { - if (position.Contains(Event.current.mousePosition)) - { - EditorGUI.s_DragUpdatedOverID = controlID; - EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; - Event.current.Use(); - } + string t = InternalEditorUtility.TextifyEvent(_event); + style.Draw(position, EditorGUIUtility.TempContent(t), controlID); } - return foldout; + break; } - goto IL_D8; + return _event; } - public static void ProgressBar(Rect position, float value, string text) + internal static bool DoObjectFoldout(int id, Rect position, UnityEngine.Object[] targetObjs, bool foldout) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ProgressBarHash, EditorGUIUtility.native, position); + int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; + position.xMin -= (float)num; + bool enabled = GUI.enabled; + GUI.enabled = true; Event current = Event.current; - EventType typeForControl = current.GetTypeForControl(controlID); - if (typeForControl == EventType.Repaint) - { - EditorStyles.progressBarBack.Draw(position, false, false, false, false); - Rect position2 = new Rect(position); - value = Mathf.Clamp01(value); - position2.width *= value; - EditorStyles.progressBarBar.Draw(position2, false, false, false, false); - EditorStyles.progressBarText.Draw(position, text, false, false, false, false); - } - } - public static void HelpBox(Rect position, string message, MessageType type) - { - GUI.Label(position, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type)), EditorStyles.helpBox); - } - internal static bool LabelHasContent(GUIContent label) - { - return label == null || label.text != string.Empty || label.image != null; - } - private static void DrawTextDebugHelpers(Rect labelPosition) - { - Color color = GUI.color; - GUI.color = Color.white; - GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.y, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); - GUI.color = Color.cyan; - GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.yMax - 4f, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); - GUI.color = color; - } - internal static void HandlePrefixLabelInternal(Rect totalPosition, Rect labelPosition, GUIContent label, int id, GUIStyle style) - { - if (id == 0 && label != null) - { - EditorGUI.s_PrefixLabel.text = label.text; - EditorGUI.s_PrefixLabel.image = label.image; - EditorGUI.s_PrefixLabel.tooltip = label.tooltip; - EditorGUI.s_PrefixTotalRect = totalPosition; - EditorGUI.s_PrefixRect = labelPosition; - EditorGUI.s_PrefixStyle = style; - return; - } - if (Highlighter.searchMode == HighlightSearchMode.PrefixLabel || Highlighter.searchMode == HighlightSearchMode.Auto) - { - Highlighter.Handle(totalPosition, label.text); - } - EventType type = Event.current.type; - if (type != EventType.MouseDown) + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) { - if (type == EventType.Repaint) + case EventType.MouseDown: + if (position.Contains(current.mousePosition)) { - labelPosition.width += 1f; - style.DrawPrefixLabel(labelPosition, label, id); + if (current.button == 1 && targetObjs[0] != null) + { + EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); + current.Use(); + } + else + { + if (current.button == 0 && (Application.platform != RuntimePlatform.OSXEditor || !current.control)) + { + GUIUtility.hotControl = id; + GUIUtility.keyboardControl = id; + DragAndDropDelay dragAndDropDelay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + dragAndDropDelay.mouseDownPosition = current.mousePosition; + current.Use(); + } + } } - } - else - { - if (Event.current.button == 0 && labelPosition.Contains(Event.current.mousePosition)) + goto IL_36B; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) { - if (EditorGUIUtility.CanHaveKeyboardFocus(id)) + GUIUtility.hotControl = 0; + current.Use(); + if (position.Contains(current.mousePosition)) { - GUIUtility.keyboardControl = id; + GUI.changed = true; + foldout = !foldout; } - EditorGUIUtility.editingTextField = false; - HandleUtility.Repaint(); } - } - EditorGUI.s_PrefixLabel.text = null; - } - public static Rect PrefixLabel(Rect totalPosition, GUIContent label) - { - return EditorGUI.PrefixLabel(totalPosition, 0, label); - } - public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label) - { - if (!EditorGUI.LabelHasContent(label)) - { - return EditorGUI.IndentedRect(totalPosition); - } - Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); - Rect result = new Rect(totalPosition.x + EditorGUIUtility.labelWidth, totalPosition.y, totalPosition.width - EditorGUIUtility.labelWidth, totalPosition.height); - EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, EditorStyles.label); - return result; - } - internal static Rect MultiFieldPrefixLabel(Rect totalPosition, int id, GUIContent label, int columns) - { - if (!EditorGUI.LabelHasContent(label)) - { - return EditorGUI.IndentedRect(totalPosition); - } - if (EditorGUIUtility.wideMode) - { - Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); - Rect result = totalPosition; - result.xMin += EditorGUIUtility.labelWidth; - if (columns > 1) + goto IL_36B; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Repaint: + case EventType.Layout: + IL_7E: + if (typeForControl != EventType.ContextClick) { - labelPosition.width -= 1f; - result.xMin -= 1f; + goto IL_36B; } - if (columns == 2) + if (position.Contains(current.mousePosition) && targetObjs[0] != null) { - float num = (result.width - 4f) / 3f; - result.xMax -= num + 2f; + EditorUtility.DisplayObjectContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), targetObjs, 0); + current.Use(); } - EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id); - return result; - } - Rect labelPosition2 = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, totalPosition.width - EditorGUI.indent, 16f); - Rect result2 = totalPosition; - result2.xMin += EditorGUI.indent + 15f; - result2.yMin += 16f; - EditorGUI.HandlePrefixLabel(totalPosition, labelPosition2, label, id); - return result2; - } - public static GUIContent BeginProperty(Rect totalPosition, GUIContent label, SerializedProperty property) - { - Highlighter.HighlightIdentifier(totalPosition, property.propertyPath); - if (EditorGUI.s_PendingPropertyKeyboardHandling != null) - { - EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); - } - EditorGUI.s_PendingPropertyKeyboardHandling = property; - if (property == null) - { - string message = ((label != null) ? (label.text + ": ") : string.Empty) + "SerializedProperty is null"; - EditorGUI.HelpBox(totalPosition, "null", MessageType.Error); - throw new NullReferenceException(message); - } - EditorGUI.s_PropertyFieldTempContent.text = ((label != null) ? label.text : property.displayName); - EditorGUI.s_PropertyFieldTempContent.tooltip = ((!EditorGUI.isCollectingTooltips) ? null : ((label != null) ? label.tooltip : property.tooltip)); - string tooltip = ScriptAttributeUtility.GetHandler(property).tooltip; - if (tooltip != null) - { - EditorGUI.s_PropertyFieldTempContent.tooltip = tooltip; - } - EditorGUI.s_PropertyFieldTempContent.image = ((label != null) ? label.image : null); - if (Event.current.alt && property.serializedObject.inspectorMode != InspectorMode.Normal) - { - GUIContent arg_12F_0 = EditorGUI.s_PropertyFieldTempContent; - string propertyPath = property.propertyPath; - EditorGUI.s_PropertyFieldTempContent.text = propertyPath; - arg_12F_0.tooltip = propertyPath; - } - bool boldDefaultFont = EditorGUIUtility.GetBoldDefaultFont(); - if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) - { - EditorGUIUtility.SetBoldDefaultFont(property.prefabOverride); - } - EditorGUI.s_PropertyStack.Push(new PropertyGUIData(property, totalPosition, boldDefaultFont, GUI.enabled, GUI.color)); - EditorGUI.showMixedValue = property.hasMultipleDifferentValues; - if (property.isAnimated) - { - Color animatedPropertyColor = AnimationMode.animatedPropertyColor; - animatedPropertyColor.a *= GUI.color.a; - GUI.color = animatedPropertyColor; - } - GUI.enabled &= property.editable; - return EditorGUI.s_PropertyFieldTempContent; - } - public static void EndProperty() - { - EditorGUI.showMixedValue = false; - PropertyGUIData propertyGUIData = EditorGUI.s_PropertyStack.Pop(); - if (Event.current.type == EventType.ContextClick && propertyGUIData.totalPosition.Contains(Event.current.mousePosition)) - { - EditorGUI.DoPropertyContextMenu(propertyGUIData.property); - } - EditorGUIUtility.SetBoldDefaultFont(propertyGUIData.wasBoldDefaultFont); - GUI.enabled = propertyGUIData.wasEnabled; - GUI.color = propertyGUIData.color; - if (EditorGUI.s_PendingPropertyKeyboardHandling != null) - { - EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); - } - if (EditorGUI.s_PendingPropertyDelete != null && EditorGUI.s_PropertyStack.Count == 0) - { - if (EditorGUI.s_PendingPropertyDelete.propertyPath == propertyGUIData.property.propertyPath) + goto IL_36B; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) { - propertyGUIData.property.DeleteCommand(); + DragAndDropDelay dragAndDropDelay2 = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); + if (dragAndDropDelay2.CanStartDrag()) + { + GUIUtility.hotControl = 0; + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = targetObjs; + if (targetObjs.Length > 1) + { + DragAndDrop.StartDrag(""); + } + else + { + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(targetObjs[0])); + } + } + current.Use(); } - else + goto IL_36B; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) { - EditorGUI.s_PendingPropertyDelete.DeleteCommand(); + if (current.keyCode == KeyCode.LeftArrow) + { + foldout = false; + current.Use(); + } + if (current.keyCode == KeyCode.RightArrow) + { + foldout = true; + current.Use(); + } } - EditorGUI.s_PendingPropertyDelete = null; - } - } - private static void DoPropertyFieldKeyboardHandling(SerializedProperty property) - { - if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) - { - if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete")) + goto IL_36B; + case EventType.DragUpdated: + if (EditorGUI.s_DragUpdatedOverID == id) { - if (Event.current.type == EventType.ExecuteCommand) + if (position.Contains(current.mousePosition)) { - EditorGUI.s_PendingPropertyDelete = property.Copy(); + if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) + { + foldout = true; + HandleUtility.Repaint(); + } + } + else + { + EditorGUI.s_DragUpdatedOverID = 0; } - Event.current.Use(); } - if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && Event.current.commandName == "Duplicate") + else { - if (Event.current.type == EventType.ExecuteCommand) + if (position.Contains(current.mousePosition)) { - property.DuplicateCommand(); + EditorGUI.s_DragUpdatedOverID = id; + EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; } - Event.current.Use(); } - } - EditorGUI.s_PendingPropertyKeyboardHandling = null; - } - internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label) - { - EditorGUI.LayerMaskField(position, property, label, EditorStyles.layerMaskField); - } - internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label, GUIStyle style) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_LayerMaskField, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - Event current = Event.current; - if (current.type == EventType.Repaint) - { - if (EditorGUI.showMixedValue) + if (position.Contains(current.mousePosition)) { - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, EditorGUI.s_MixedValueContent, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, false); + Event.current.Use(); } - else + goto IL_36B; + case EventType.DragPerform: + if (position.Contains(current.mousePosition)) { - style.Draw(position, EditorGUIUtility.TempContent(property.layerMaskStringValue), controlID, false); + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(targetObjs, true); + DragAndDrop.AcceptDrag(); + Event.current.Use(); } + goto IL_36B; } - else + goto IL_7E; + IL_36B: + GUI.enabled = enabled; + return foldout; + } + internal static void LabelFieldInternal(Rect position, GUIContent label, GUIContent label2, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Passive, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + if (Event.current.type == EventType.Repaint) { - if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) - { - SerializedProperty userData = property.serializedObject.FindProperty(property.propertyPath); - EditorUtility.DisplayCustomMenu(position, property.GetLayerMaskNames(), (!property.hasMultipleDifferentValues) ? property.GetLayerMaskSelectedIndex() : new int[0], new EditorUtility.SelectMenuItemFunction(EditorGUI.SetLayerMaskValueDelegate), userData); - Event.current.Use(); - } + style.Draw(position, label2, controlID); } } - internal static void SetLayerMaskValueDelegate(object userData, string[] options, int selected) + public static bool Toggle(Rect position, bool value) { - SerializedProperty serializedProperty = (SerializedProperty)userData; - serializedProperty.ToggleLayerMaskAtIndex(selected); - serializedProperty.serializedObject.ApplyModifiedProperties(); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.IndentedRect(position), controlID, value, GUIContent.none, EditorStyles.toggle); } - internal static void ShowRepaints() + public static bool Toggle(Rect position, string label, bool value) { - if (Unsupported.IsDeveloperBuild()) + return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value); + } + public static bool Toggle(Rect position, bool value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(position, controlID, value, GUIContent.none, style); + } + public static bool Toggle(Rect position, string label, bool value, GUIStyle style) + { + return EditorGUI.Toggle(position, EditorGUIUtility.TempContent(label), value, style); + } + public static bool Toggle(Rect position, GUIContent label, bool value) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, EditorStyles.toggle); + } + public static bool Toggle(Rect position, GUIContent label, bool value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + return EditorGUIInternal.DoToggleForward(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, GUIContent.none, style); + } + internal static bool ToggleLeftInternal(Rect position, GUIContent label, bool value, GUIStyle labelStyle) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ToggleHash, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.IndentedRect(position); + Rect labelPosition = EditorGUI.IndentedRect(position); + labelPosition.xMin += 13f; + EditorGUI.HandlePrefixLabel(position, labelPosition, label, controlID, labelStyle); + return EditorGUIInternal.DoToggleForward(position2, controlID, value, GUIContent.none, EditorStyles.toggle); + } + internal static bool DoToggle(Rect position, int id, bool value, GUIContent content, GUIStyle style) + { + return EditorGUIInternal.DoToggleForward(position, id, value, content, style); + } + internal static string TextFieldInternal(Rect position, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, false, false); + return text; + } + internal static string TextFieldInternal(Rect position, GUIContent label, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.PrefixLabel(position, controlID, label), text, style, null, out flag, false, false, false); + return text; + } + internal static string ToolbarSearchField(int id, Rect position, string text, bool showWithPopupArrow) + { + Rect position2 = position; + position2.width -= 14f; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position2, text, (!showWithPopupArrow) ? EditorStyles.toolbarSearchField : EditorStyles.toolbarSearchFieldPopup, null, out flag, false, false, false); + Rect position3 = position; + position3.x += position.width - 14f; + position3.width = 14f; + if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.toolbarSearchFieldCancelButtonEmpty : EditorStyles.toolbarSearchFieldCancelButton) && text != string.Empty) { - Color backgroundColor = GUI.backgroundColor; - GUI.backgroundColor = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); - GUI.Label(new Rect(0f, 0f, 10f, 10f), string.Empty, GUI.skin.button); - GUI.backgroundColor = backgroundColor; + text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); + GUIUtility.keyboardControl = 0; } + return text; } - internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color) + internal static string ToolbarSearchField(Rect position, string[] searchModes, ref int searchMode, string text) { - if (Event.current.type != EventType.Repaint) + int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); + return EditorGUI.ToolbarSearchField(controlID, position, searchModes, ref searchMode, text); + } + internal static string ToolbarSearchField(int id, Rect position, string[] searchModes, ref int searchMode, string text) + { + bool flag = searchModes != null; + if (flag) { - return; + searchMode = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(id, searchMode); + Rect rect = position; + rect.width = 20f; + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) + { + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(id); + EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(searchModes), searchMode, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) + { + Event.current.Use(); + } + } } - if (!EditorGUI.s_Texture) + text = EditorGUI.ToolbarSearchField(id, position, text, flag); + if (flag && text == string.Empty && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && Event.current.type == EventType.Repaint) { - EditorGUI.s_Texture = new Texture2D(1, thickness + 2); - EditorGUI.s_Texture.hideFlags = HideFlags.HideAndDontSave; + position.width -= 14f; + EditorGUI.BeginDisabledGroup(true); + EditorStyles.toolbarSearchFieldPopup.Draw(position, EditorGUIUtility.TempContent(searchModes[searchMode]), id, false); + EditorGUI.EndDisabledGroup(); } - if (thickness != EditorGUI.s_LastThickness) + return text; + } + internal static string SearchField(Rect position, string text) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SearchFieldHash, FocusType.Keyboard, position); + Rect position2 = position; + position2.width -= 15f; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, position2, text, EditorStyles.searchField, null, out flag, false, false, false); + Rect position3 = position; + position3.x += position.width - 15f; + position3.width = 15f; + if (GUI.Button(position3, GUIContent.none, (!(text != string.Empty)) ? EditorStyles.searchFieldCancelButtonEmpty : EditorStyles.searchFieldCancelButton) && text != string.Empty) { - EditorGUI.s_Texture.Resize(1, thickness + 2, TextureFormat.ARGB32, false); - Color[] array = new Color[thickness + 2]; - for (int i = 1; i <= thickness; i++) - { - array[i] = new Color(1f, 1f, 1f, 1f); - } - array[0] = (array[thickness + 1] = new Color(1f, 1f, 1f, 0f)); - EditorGUI.s_Texture.SetPixels(array); - EditorGUI.s_Texture.Apply(); - EditorGUI.s_LastThickness = thickness; + text = (EditorGUI.s_RecycledEditor.content.text = string.Empty); + GUIUtility.keyboardControl = 0; } - EditorGUI.DrawBezier(from, to, fromTangent, toTangent, thickness, color, EditorGUI.s_Texture); + return text; } - internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color, Texture tex) + internal static string ScrollableTextAreaInternal(Rect position, string text, ref Vector2 scrollPosition, GUIStyle style) { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Layout) { - return; + return text; + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); + float height = style.CalcHeight(GUIContent.Temp(text), position.width); + Rect rect = new Rect(0f, 0f, position.width, height); + Vector2 contentOffset = style.contentOffset; + if (position.height < rect.height) + { + Rect position2 = position; + position2.width = GUI.skin.verticalScrollbar.fixedWidth; + position2.height -= 2f; + position2.y += 1f; + position2.x = position.x + position.width - position2.width; + position.width -= position2.width; + height = style.CalcHeight(GUIContent.Temp(text), position.width); + rect = new Rect(0f, 0f, position.width, height); + if (position.Contains(Event.current.mousePosition) && Event.current.type == EventType.ScrollWheel) + { + float value = scrollPosition.y + Event.current.delta.y * 10f; + scrollPosition.y = Mathf.Clamp(value, 0f, rect.height); + Event.current.Use(); + } + scrollPosition.y = GUI.VerticalScrollbar(position2, scrollPosition.y, position.height, 0f, rect.height); + if (!EditorGUI.s_RecycledEditor.IsEditingControl(controlID)) + { + style.contentOffset -= scrollPosition; + style.Internal_clipOffset = scrollPosition; + } + else + { + EditorGUI.s_RecycledEditor.scrollOffset.y = scrollPosition.y; + } } - if (!EditorGUI.tmp) + EventType type = Event.current.type; + bool flag; + string result = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + if (type != Event.current.type) { - EditorGUI.tmp = new Material("Shader \"GuiShader\" {\n\tProperties {\t\t_Color (\",\", Color) = (1,1,1,1)\n\t\t_Tex (\",\", Any) = \"white\" {}\n\t}\tSubShader { Pass {\n\t\tTags { \"ForceSupported\" = \"True\" } \n \t\tZTest Always Cull Off ZWrite Off Lighting Off Color [_Color] \t\tBlend SrcAlpha OneMinusSrcAlpha \t\tSetTexture [_Tex] { combine texture * previous }\t}}\n}"); - EditorGUI.tmp.hideFlags = HideFlags.HideAndDontSave; - EditorGUI.tmp.shader.hideFlags = HideFlags.HideAndDontSave; + scrollPosition = EditorGUI.s_RecycledEditor.scrollOffset; } - EditorGUI.tmp.SetTexture("_Tex", tex); - EditorGUI.tmp.SetColor("_Color", color); - EditorGUI.tmp.SetPass(0); + style.contentOffset = contentOffset; + style.Internal_clipOffset = Vector2.zero; + return result; } - internal static void DrawTextureAlphaInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) + internal static string TextAreaInternal(Rect position, string text, GUIStyle style) { - EditorGUI.DrawPreviewTextureInternal(position, image, EditorGUI.alphaMaterial, scaleMode, imageAspect); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextAreaHash, FocusType.Keyboard, position); + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + return text; } - internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) + internal static void SelectableLabelInternal(Rect position, string text, GUIStyle style) { - if (imageAspect == 0f && image == null) - { - Debug.LogError("Please specify an image or a imageAspect"); - return; - } - if (imageAspect == 0f) + int controlID = GUIUtility.GetControlID(EditorGUI.s_SelectableLabelHash, FocusType.Keyboard, position); + Event current = Event.current; + if (GUIUtility.keyboardControl == controlID && current.GetTypeForControl(controlID) == EventType.KeyDown) { - imageAspect = (float)image.width / (float)image.height; + KeyCode keyCode = current.keyCode; + switch (keyCode) + { + case KeyCode.UpArrow: + case KeyCode.DownArrow: + case KeyCode.RightArrow: + case KeyCode.LeftArrow: + case KeyCode.Home: + case KeyCode.End: + case KeyCode.PageUp: + case KeyCode.PageDown: + goto IL_A0; + case KeyCode.Insert: + IL_64: + if (keyCode != KeyCode.Space) + { + if (current.character != '\t') + { + current.Use(); + } + goto IL_A0; + } + GUIUtility.hotControl = 0; + GUIUtility.keyboardControl = 0; + goto IL_A0; + } + goto IL_64; } - EditorGUI.DrawTransparencyCheckerTexture(position, scaleMode, imageAspect); - if (image != null) + IL_A0: + if (current.type == EventType.ExecuteCommand && (current.commandName == "Paste" || current.commandName == "Cut") && GUIUtility.keyboardControl == controlID) { - Material mat = (QualitySettings.activeColorSpace != ColorSpace.Linear || TextureUtil.GetLinearSampled(image)) ? EditorGUI.transparentMaterial : EditorGUI.gammaCorrectTransparentMaterial; - EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + current.Use(); } + Color cursorColor = GUI.skin.settings.cursorColor; + GUI.skin.settings.cursorColor = new Color(0f, 0f, 0f, 0f); + EditorGUI.RecycledTextEditor.s_AllowContextCutOrPaste = false; + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, string.Empty, out flag, false, true, false); + GUI.skin.settings.cursorColor = cursorColor; } - internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode scaleMode, float imageAspect) + public static string DoPasswordField(int id, Rect position, string password, GUIStyle style) { - Rect position2 = default(Rect); - Rect rect = default(Rect); - GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref position2, ref rect); - GUI.DrawTextureWithTexCoords(position2, EditorGUI.transparentCheckerTexture, new Rect(position2.width * -0.5f / (float)EditorGUI.transparentCheckerTexture.width, position2.height * -0.5f / (float)EditorGUI.transparentCheckerTexture.height, position2.width / (float)EditorGUI.transparentCheckerTexture.width, position2.height / (float)EditorGUI.transparentCheckerTexture.height), false); + bool flag; + return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, password, style, null, out flag, false, false, true); } - internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) + public static string DoPasswordField(int id, Rect position, GUIContent label, string password, GUIStyle style) { - if (Event.current.type == EventType.Repaint) - { - if (imageAspect == 0f) - { - imageAspect = (float)image.width / (float)image.height; - } - if (mat == null) - { - mat = EditorGUI.GetMaterialForSpecialTexture(image); - } - if (mat == null) - { - GUI.DrawTexture(position, image, scaleMode, false, imageAspect); - return; - } - Rect screenRect = default(Rect); - Rect sourceRect = default(Rect); - GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref screenRect, ref sourceRect); - Texture2D texture2D = image as Texture2D; - if (texture2D != null && TextureUtil.GetUsageMode(image) == TextureUsageMode.AlwaysPadded) - { - sourceRect.width *= (float)texture2D.width / (float)TextureUtil.GetGLWidth(texture2D); - sourceRect.height *= (float)texture2D.height / (float)TextureUtil.GetGLHeight(texture2D); - } - Graphics.DrawTexture(screenRect, image, sourceRect, 0, 0, 0, 0, GUI.color, mat); - } + bool flag; + return EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, EditorGUI.PrefixLabel(position, id, label), password, style, null, out flag, false, false, true); } - internal static Material GetMaterialForSpecialTexture(Texture t) + internal static string PasswordFieldInternal(Rect position, string password, GUIStyle style) { - if (!t) - { - return null; - } - TextureUsageMode usageMode = TextureUtil.GetUsageMode(t); - if (usageMode == TextureUsageMode.LightmapRGBM) - { - return EditorGUI.lightmapRGBMMaterial; - } - if (usageMode == TextureUsageMode.LightmapDoubleLDR) - { - return EditorGUI.lightmapDoubleLDRMaterial; - } - if (usageMode == TextureUsageMode.NormalmapPlain || usageMode == TextureUsageMode.NormalmapDXT5nm) - { - return EditorGUI.normalmapMaterial; - } - if (TextureUtil.IsAlphaOnlyTextureFormat(TextureUtil.GetTextureFormat(t))) - { - return EditorGUI.alphaMaterial; - } - if (QualitySettings.activeColorSpace == ColorSpace.Linear && !TextureUtil.GetLinearSampled(t)) - { - return EditorGUI.gammaCorrectMaterial; - } - return null; + int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoPasswordField(controlID, EditorGUI.IndentedRect(position), password, style); } - private static void SetExpandedRecurse(SerializedProperty property, bool expanded) + internal static string PasswordFieldInternal(Rect position, GUIContent label, string password, GUIStyle style) { - SerializedProperty serializedProperty = property.Copy(); - serializedProperty.isExpanded = expanded; - int depth = serializedProperty.depth; - while (serializedProperty.NextVisible(true) && serializedProperty.depth > depth) - { - if (serializedProperty.hasVisibleChildren) - { - serializedProperty.isExpanded = expanded; - } - } + int controlID = GUIUtility.GetControlID(EditorGUI.s_PasswordFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoPasswordField(controlID, position, label, password, style); } - internal static float GetSinglePropertyHeight(SerializedProperty property, GUIContent label) + internal static float FloatFieldInternal(Rect position, float value, GUIStyle style) { - if (property == null) - { - return 16f; - } - SerializedPropertyType propertyType = property.propertyType; - if (propertyType == SerializedPropertyType.Vector3 || propertyType == SerializedPropertyType.Vector2) - { - return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 16f; - } - if (propertyType == SerializedPropertyType.Rect) - { - return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 32f; - } - if (propertyType == SerializedPropertyType.Bounds) - { - return (EditorGUI.LabelHasContent(label) ? 16f : 0f) + 32f; - } - return 16f; + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kFloatFieldFormatString, style, false); } - internal static float GetPropertyHeightInternal(SerializedProperty property, GUIContent label, bool includeChildren) + internal static float FloatFieldInternal(Rect position, GUIContent label, float value, GUIStyle style) { - return ScriptAttributeUtility.GetHandler(property).GetHeight(property, label, includeChildren); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kFloatFieldFormatString, style, true); } - internal static bool HasVisibleChildFields(SerializedProperty property) + internal static double DoubleFieldInternal(Rect position, double value, GUIStyle style) { - switch (property.propertyType) + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoDoubleField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kDoubleFieldFormatString, style, false); + } + internal static double DoubleFieldInternal(Rect position, GUIContent label, double value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoDoubleField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kDoubleFieldFormatString, style, true); + } + private static double CalculateFloatDragSensitivity(double value) + { + if (double.IsInfinity(value) || double.IsNaN(value)) { - case SerializedPropertyType.Vector2: - case SerializedPropertyType.Vector3: - case SerializedPropertyType.Rect: - case SerializedPropertyType.Bounds: - return false; + return 0.0; } - return property.hasVisibleChildren; + return Math.Max(1.0, Math.Pow(Math.Abs(value), 0.5)) * 0.029999999329447746; } - internal static bool PropertyFieldInternal(Rect position, SerializedProperty property, GUIContent label, bool includeChildren) + private static long CalculateIntDragSensitivity(long value) { - return ScriptAttributeUtility.GetHandler(property).OnGUI(position, property, label, includeChildren); + return (long)Math.Max(1.0, Math.Pow(Math.Abs((double)value), 0.5) * 0.029999999329447746); } - internal static bool DefaultPropertyField(Rect position, SerializedProperty property, GUIContent label) + private static void DragNumberValue(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, GUIStyle style, double dragSensitivity) { - label = EditorGUI.BeginProperty(position, label, property); - SerializedPropertyType propertyType = property.propertyType; - bool flag = false; - if (!EditorGUI.HasVisibleChildFields(property)) - { - switch (propertyType) - { - case SerializedPropertyType.Integer: - { - EditorGUI.BeginChangeCheck(); - int intValue = EditorGUI.IntField(position, label, property.intValue); - if (EditorGUI.EndChangeCheck()) - { - property.intValue = intValue; - } - break; - } - case SerializedPropertyType.Boolean: - { - EditorGUI.BeginChangeCheck(); - bool boolValue = EditorGUI.Toggle(position, label, property.boolValue); - if (EditorGUI.EndChangeCheck()) - { - property.boolValue = boolValue; - } - break; - } - case SerializedPropertyType.Float: - { - EditorGUI.BeginChangeCheck(); - float floatValue = EditorGUI.FloatField(position, label, property.floatValue); - if (EditorGUI.EndChangeCheck()) - { - property.floatValue = floatValue; - } - break; - } - case SerializedPropertyType.String: - { - EditorGUI.BeginChangeCheck(); - string stringValue = EditorGUI.TextField(position, label, property.stringValue); - if (EditorGUI.EndChangeCheck()) - { - property.stringValue = stringValue; - } - break; - } - case SerializedPropertyType.Color: + Event current = Event.current; + switch (current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (dragHotZone.Contains(current.mousePosition) && current.button == 0) { - EditorGUI.BeginChangeCheck(); - Color colorValue = EditorGUI.ColorField(position, label, property.colorValue); - if (EditorGUI.EndChangeCheck()) + GUIUtility.hotControl = id; + if (EditorGUI.activeEditor != null) { - property.colorValue = colorValue; + EditorGUI.activeEditor.EndEditing(); } - break; + current.Use(); + GUIUtility.keyboardControl = id; + EditorGUI.s_DragCandidateState = 1; + EditorGUI.s_DragStartValue = doubleVal; + EditorGUI.s_DragStartIntValue = longVal; + EditorGUI.s_DragStartPos = current.mousePosition; + EditorGUI.s_DragSensitivity = dragSensitivity; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(1); } - case SerializedPropertyType.ObjectReference: - EditorGUI.ObjectFieldInternal(position, property, null, label, EditorStyles.objectField); - break; - case SerializedPropertyType.LayerMask: - EditorGUI.LayerMaskField(position, property, label); - break; - case SerializedPropertyType.Enum: - EditorGUI.Popup(position, property, label); - break; - case SerializedPropertyType.Vector2: - EditorGUI.Vector2Field(position, property, label); - break; - case SerializedPropertyType.Vector3: - EditorGUI.Vector3Field(position, property, label); - break; - case SerializedPropertyType.Vector4: - EditorGUI.Vector4Field(position, property, label); - break; - case SerializedPropertyType.Rect: - EditorGUI.RectField(position, property, label); - break; - case SerializedPropertyType.ArraySize: + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == id && EditorGUI.s_DragCandidateState != 0) { - EditorGUI.BeginChangeCheck(); - int intValue2 = EditorGUI.ArraySizeField(position, label, property.intValue, EditorStyles.numberField); - if (EditorGUI.EndChangeCheck()) - { - property.intValue = intValue2; - } - break; + GUIUtility.hotControl = 0; + EditorGUI.s_DragCandidateState = 0; + current.Use(); + EditorGUIUtility.SetWantsMouseJumping(0); } - case SerializedPropertyType.Character: + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == id) { - char[] value = new char[] - { - (char)property.intValue - }; - bool changed = GUI.changed; - GUI.changed = false; - string text = EditorGUI.TextField(position, label, new string(value)); - if (GUI.changed) + int num = EditorGUI.s_DragCandidateState; + if (num != 1) { - if (text.Length == 1) + if (num == 2) { - property.intValue = (int)text[0]; + if (isDouble) + { + doubleVal += (double)HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity; + doubleVal = MathUtils.RoundBasedOnMinimumDifference(doubleVal, EditorGUI.s_DragSensitivity); + } + else + { + longVal += (long)Math.Round((double)HandleUtility.niceMouseDelta * EditorGUI.s_DragSensitivity); + } + GUI.changed = true; + current.Use(); } - else + } + else + { + if ((Event.current.mousePosition - EditorGUI.s_DragStartPos).sqrMagnitude > EditorGUI.kDragDeadzone) { - GUI.changed = false; + EditorGUI.s_DragCandidateState = 2; + GUIUtility.keyboardControl = id; } + current.Use(); } - GUI.changed |= changed; - break; } - case SerializedPropertyType.AnimationCurve: + break; + case EventType.KeyDown: + if (GUIUtility.hotControl == id && current.keyCode == KeyCode.Escape && EditorGUI.s_DragCandidateState != 0) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, EditorGUI.kCurveColor, default(Rect), property); - break; + doubleVal = EditorGUI.s_DragStartValue; + longVal = EditorGUI.s_DragStartIntValue; + GUI.changed = true; + GUIUtility.hotControl = 0; + current.Use(); } - case SerializedPropertyType.Bounds: - EditorGUI.BoundsField(position, property, label); - break; - case SerializedPropertyType.Gradient: + break; + case EventType.Repaint: + EditorGUIUtility.AddCursorRect(dragHotZone, MouseCursor.SlideArrow); + break; + } + } + internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable) + { + return EditorGUI.DoFloatField(editor, position, dragHotZone, id, value, formatString, style, draggable, (Event.current.GetTypeForControl(id) != EventType.MouseDown) ? 0f : ((float)EditorGUI.CalculateFloatDragSensitivity(EditorGUI.s_DragStartValue))); + } + internal static float DoFloatField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + { + long num = 0L; + double value2 = (double)value; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, true, ref value2, ref num, formatString, style, draggable, (double)dragSensitivity); + return MathUtils.ClampToFloat(value2); + } + internal static int DoIntField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, int value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) + { + double num = 0.0; + long value2 = (long)value; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, false, ref num, ref value2, formatString, style, draggable, (double)dragSensitivity); + return MathUtils.ClampToInt(value2); + } + internal static double DoDoubleField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, double value, string formatString, GUIStyle style, bool draggable) + { + return EditorGUI.DoDoubleField(editor, position, dragHotZone, id, value, formatString, style, draggable, (Event.current.GetTypeForControl(id) != EventType.MouseDown) ? 0.0 : EditorGUI.CalculateFloatDragSensitivity(EditorGUI.s_DragStartValue)); + } + internal static double DoDoubleField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, double value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) + { + long num = 0L; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, true, ref value, ref num, formatString, style, draggable, dragSensitivity); + return value; + } + internal static long DoLongField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, long value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) + { + double num = 0.0; + EditorGUI.DoNumberField(editor, position, dragHotZone, id, false, ref num, ref value, formatString, style, draggable, dragSensitivity); + return value; + } + private static bool HasKeyboardFocus(int controlID) + { + return GUIUtility.keyboardControl == controlID && GUIView.current.hasFocus; + } + internal static void DoNumberField(EditorGUI.RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, GUIStyle style, bool draggable, double dragSensitivity) + { + string allowedletters = (!isDouble) ? EditorGUI.s_AllowedCharactersForInt : EditorGUI.s_AllowedCharactersForFloat; + if (draggable) + { + EditorGUI.DragNumberValue(editor, position, dragHotZone, id, isDouble, ref doubleVal, ref longVal, formatString, style, dragSensitivity); + } + Event current = Event.current; + string text; + if (EditorGUI.HasKeyboardFocus(id) || (current.type == EventType.MouseDown && current.button == 0 && position.Contains(current.mousePosition))) + { + if (!editor.IsEditingControl(id)) { - int controlID2 = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); - EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID2, label), controlID2, null, property); - break; + text = (EditorGUI.s_RecycledCurrentEditingString = ((!isDouble) ? longVal.ToString(formatString) : doubleVal.ToString(formatString))); } - default: + else { - int controlID3 = GUIUtility.GetControlID(EditorGUI.s_GenericField, FocusType.Keyboard, position); - EditorGUI.PrefixLabel(position, controlID3, label); - break; - } + text = EditorGUI.s_RecycledCurrentEditingString; + if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") + { + text = ((!isDouble) ? longVal.ToString(formatString) : doubleVal.ToString(formatString)); + } } } else { - Event @event = new Event(Event.current); - flag = property.isExpanded; - EditorGUI.BeginDisabledGroup(!property.editable); - GUIStyle style = (DragAndDrop.activeControlID != -10) ? EditorStyles.foldout : EditorStyles.foldoutPreDrop; - bool flag2 = EditorGUI.Foldout(position, flag, EditorGUI.s_PropertyFieldTempContent, true, style); - EditorGUI.EndDisabledGroup(); - if (flag2 != flag) - { - if (Event.current.alt) - { - EditorGUI.SetExpandedRecurse(property, flag2); - } - else - { - property.isExpanded = flag2; - } - } - flag = flag2; - int s_LastControlID = EditorGUIUtility.s_LastControlID; - EventType type = @event.type; - if (type != EventType.DragUpdated && type != EventType.DragPerform) + text = ((!isDouble) ? longVal.ToString(formatString) : doubleVal.ToString(formatString)); + } + if (GUIUtility.keyboardControl == id) + { + bool flag; + text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); + if (flag) { - if (type == EventType.DragExited) + GUI.changed = true; + EditorGUI.s_RecycledCurrentEditingString = text; + if (isDouble) { - if (GUI.enabled) + string a = text.ToLower(); + if (a == "inf" || a == "infinity") { - HandleUtility.Repaint(); + doubleVal = double.PositiveInfinity; } - } - } - else - { - if (position.Contains(@event.mousePosition) && GUI.enabled) - { - UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; - UnityEngine.Object[] array = new UnityEngine.Object[1]; - bool flag3 = false; - UnityEngine.Object[] array2 = objectReferences; - for (int i = 0; i < array2.Length; i++) + else { - UnityEngine.Object @object = array2[i]; - array[0] = @object; - UnityEngine.Object object2 = EditorGUI.ValidateObjectFieldAssignment(array, null, property); - if (object2 != null) + if (a == "-inf" || a == "-infinity") { - DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - if (@event.type == EventType.DragPerform) + doubleVal = double.NegativeInfinity; + } + else + { + text = text.Replace(',', '.'); + if (!double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out doubleVal)) { - property.AppendFoldoutPPtrValue(object2); - flag3 = true; - DragAndDrop.activeControlID = 0; + doubleVal = (EditorGUI.s_RecycledCurrentEditingFloat = 0.0); + return; } - else + if (double.IsNaN(doubleVal)) { - DragAndDrop.activeControlID = s_LastControlID; + doubleVal = 0.0; } + EditorGUI.s_RecycledCurrentEditingFloat = doubleVal; } } - if (flag3) + } + else + { + if (!long.TryParse(text, out longVal)) { - GUI.changed = true; - DragAndDrop.AcceptDrag(); + longVal = (EditorGUI.s_RecycledCurrentEditingInt = 0L); + return; } + EditorGUI.s_RecycledCurrentEditingInt = longVal; } } } - EditorGUI.EndProperty(); - return flag; - } - internal static void DrawLegend(Rect position, Color color, string label, bool enabled) - { - position = new Rect(position.x + 2f, position.y + 2f, position.width - 2f, position.height - 2f); - Color backgroundColor = GUI.backgroundColor; - if (enabled) + else { - GUI.backgroundColor = color; + bool flag; + text = EditorGUI.DoTextField(editor, id, position, text, style, allowedletters, out flag, false, false, false); } - else + } + internal static int ArraySizeField(Rect position, GUIContent label, int value, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ArraySizeFieldHash, FocusType.Keyboard, position); + return EditorGUI.ArraySizeField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, style); + } + internal static int ArraySizeField(Rect position, int id, int value, GUIStyle style) + { + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(position, id, value.ToString(EditorGUI.kIntFieldFormatString), "0123456789-", style); + if (EditorGUI.EndChangeCheck()) { - GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0.45f); + try + { + value = int.Parse(s, CultureInfo.InvariantCulture.NumberFormat); + } + catch (FormatException) + { + } } - GUI.Label(position, label, "ProfilerPaneSubLabel"); - GUI.backgroundColor = backgroundColor; + return value; } - internal static void SortingLayerField(Rect position, GUIContent label, SerializedProperty layerID, GUIStyle style) + internal static string DelayedTextField(Rect position, string value, string allowedLetters, GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_SortingLayerFieldHash, EditorGUIUtility.native, position); - position = EditorGUI.PrefixLabel(position, controlID, label); - Event current = Event.current; - int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); - if (selectedValueForControl != -1) + int controlID = GUIUtility.GetControlID(EditorGUI.s_DelayedTextFieldHash, FocusType.Keyboard, position); + return EditorGUI.DelayedTextField(position, controlID, value, allowedLetters, style); + } + internal static string DelayedTextField(Rect position, int id, string value, string allowedLetters, GUIStyle style) + { + string text; + if (EditorGUI.HasKeyboardFocus(id)) { - int[] sortingLayerUniqueIDs = InternalEditorUtility.sortingLayerUniqueIDs; - if (selectedValueForControl >= sortingLayerUniqueIDs.Length) + if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) { - ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "SortingLayers"; - Selection.activeObject = EditorApplication.tagManager; + text = (EditorGUI.s_RecycledCurrentEditingString = value); } else { - layerID.intValue = sortingLayerUniqueIDs[selectedValueForControl]; + text = EditorGUI.s_RecycledCurrentEditingString; } - } - if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) - { - int[] sortingLayerUniqueIDs2 = InternalEditorUtility.sortingLayerUniqueIDs; - string[] sortingLayerNames = InternalEditorUtility.sortingLayerNames; - int i; - for (i = 0; i < sortingLayerUniqueIDs2.Length; i++) + Event current = Event.current; + if (current.type == EventType.ValidateCommand && current.commandName == "UndoRedoPerformed") { - if (sortingLayerUniqueIDs2[i] == layerID.intValue) - { - break; - } + text = value; } - ArrayUtility.Add(ref sortingLayerNames, string.Empty); - ArrayUtility.Add(ref sortingLayerNames, "Add Sorting Layer..."); - EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(sortingLayerNames), style); } else { - if (Event.current.type == EventType.Repaint) + text = value; + } + bool changed = GUI.changed; + bool flag; + text = EditorGUI.s_DelayedTextEditor.OnGUI(id, text, out flag); + GUI.changed = false; + if (!flag) + { + text = EditorGUI.DoTextField(EditorGUI.s_DelayedTextEditor, id, position, text, style, allowedLetters, out flag, false, false, false); + GUI.changed = false; + if (GUIUtility.keyboardControl == id) { - GUIContent content; - if (layerID.hasMultipleDifferentValues) + if (!EditorGUI.s_DelayedTextEditor.IsEditingControl(id)) { - content = EditorGUI.mixedValueContent; + if (value != text) + { + GUI.changed = true; + value = text; + } } else { - content = EditorGUIUtility.TempContent(InternalEditorUtility.GetSortingLayerNameFromUniqueID(layerID.intValue)); + EditorGUI.s_RecycledCurrentEditingString = text; } - EditorGUI.showMixedValue = layerID.hasMultipleDifferentValues; - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, content, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); - EditorGUI.showMixedValue = false; } } + else + { + GUI.changed = true; + value = text; + } + GUI.changed |= changed; + return value; } - internal static Gradient GradientField(Rect position, Gradient gradient) + internal static float DelayedFloatField(GUIContent label, float value) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); - return EditorGUI.DoGradientField(position, controlID, gradient, null); + float num = value; + float num2 = num; + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, label); + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(rect, num.ToString(), EditorGUI.s_AllowedCharactersForFloat, EditorStyles.numberField); + if (EditorGUI.EndChangeCheck() && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num2) && num2 != num) + { + value = num2; + GUI.changed = true; + } + return num2; } - internal static Gradient GradientField(string label, Rect position, Gradient gradient) + internal static int DelayedIntField(GUIContent label, int value) { - return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, gradient); + int num = value; + int num2 = num; + Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + rect = EditorGUI.PrefixLabel(rect, label); + EditorGUI.BeginChangeCheck(); + string s = EditorGUI.DelayedTextField(rect, num.ToString(), EditorGUI.s_AllowedCharactersForInt, EditorStyles.numberField); + if (EditorGUI.EndChangeCheck() && int.TryParse(s, out num2) && num2 != num) + { + value = num2; + GUI.changed = true; + } + return num2; } - internal static Gradient GradientField(GUIContent label, Rect position, Gradient gradient) + internal static int IntFieldInternal(Rect position, int value, GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); - return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, gradient, null); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kIntFieldFormatString, style, false, (float)EditorGUI.CalculateIntDragSensitivity((long)value)); } - internal static Gradient GradientField(Rect position, SerializedProperty gradient) + internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); - return EditorGUI.DoGradientField(position, controlID, null, gradient); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoIntField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kIntFieldFormatString, style, true, (float)EditorGUI.CalculateIntDragSensitivity((long)value)); } - internal static Gradient GradientField(string label, Rect position, SerializedProperty property) + internal static long LongFieldInternal(Rect position, long value, GUIStyle style) { - return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, property); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + return EditorGUI.DoLongField(EditorGUI.s_RecycledEditor, EditorGUI.IndentedRect(position), new Rect(0f, 0f, 0f, 0f), controlID, value, EditorGUI.kIntFieldFormatString, style, false, (double)EditorGUI.CalculateIntDragSensitivity(value)); } - internal static Gradient GradientField(GUIContent label, Rect position, SerializedProperty property) + internal static long LongFieldInternal(Rect position, GUIContent label, long value, GUIStyle style) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); - return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, property); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FloatFieldHash, FocusType.Keyboard, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + return EditorGUI.DoLongField(EditorGUI.s_RecycledEditor, position2, position, controlID, value, EditorGUI.kIntFieldFormatString, style, true, (double)EditorGUI.CalculateIntDragSensitivity(value)); } - internal static Gradient DoGradientField(Rect position, int id, Gradient value, SerializedProperty property) + public static float Slider(Rect position, float value, float leftValue, float rightValue) { - Event current = Event.current; - EventType typeForControl = current.GetTypeForControl(id); - switch (typeForControl) + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, value, leftValue, rightValue, EditorGUI.kFloatFieldFormatString); + } + public static float Slider(Rect position, string label, float value, float leftValue, float rightValue) + { + return EditorGUI.Slider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + } + public static float Slider(Rect position, GUIContent label, float value, float leftValue, float rightValue) + { + return EditorGUI.PowerSlider(position, label, value, leftValue, rightValue, 1f); + } + internal static float PowerSlider(Rect position, string label, float sliderValue, float leftValue, float rightValue, float power) + { + return EditorGUI.PowerSlider(position, EditorGUIUtility.TempContent(label), sliderValue, leftValue, rightValue, power); + } + internal static float PowerSlider(Rect position, GUIContent label, float sliderValue, float leftValue, float rightValue, float power) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + Rect dragZonePosition = (!EditorGUI.LabelHasContent(label)) ? default(Rect) : EditorGUIUtility.DragZoneRect(position); + return EditorGUI.DoSlider(position2, dragZonePosition, controlID, sliderValue, leftValue, rightValue, EditorGUI.kFloatFieldFormatString, power); + } + private static float PowPreserveSign(float f, float p) + { + float num = Mathf.Pow(Mathf.Abs(f), p); + return (f >= 0f) ? num : (-num); + } + private static void DoPropertyContextMenu(SerializedProperty property) + { + GenericMenu genericMenu = new GenericMenu(); + SerializedProperty serializedProperty = property.serializedObject.FindProperty(property.propertyPath); + ScriptAttributeUtility.GetHandler(property).AddMenuItems(property, genericMenu); + if (property.hasMultipleDifferentValues && !property.hasVisibleChildren) { - case EventType.KeyDown: - if (GUIUtility.keyboardControl == id && (current.keyCode == KeyCode.Space || current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter)) - { - Event.current.Use(); - Gradient newGradient = (property == null) ? value : property.gradientValue; - GradientPicker.Show(newGradient); - GUIUtility.ExitGUI(); - } - return value; - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_28: - if (typeForControl == EventType.MouseDown) + TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, serializedProperty, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); + } + if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) + { + genericMenu.AddItem(EditorGUIUtility.TextContent("Revert Value to Prefab"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.SetPrefabOverride), serializedProperty); + } + if (property.propertyPath.LastIndexOf(']') == property.propertyPath.Length - 1) + { + if (genericMenu.GetItemCount() > 0) { - if (position.Contains(current.mousePosition)) - { - if (current.button == 0) - { - EditorGUI.s_GradientID = id; - GUIUtility.keyboardControl = id; - Gradient newGradient2 = (property == null) ? value : property.gradientValue; - GradientPicker.Show(newGradient2); - GUIUtility.ExitGUI(); - } - else - { - if (current.button == 1 && property != null) - { - GradientContextMenu.Show(property); - } - } - } - return value; + genericMenu.AddSeparator(string.Empty); } - if (typeForControl != EventType.ExecuteCommand) + genericMenu.AddItem(EditorGUIUtility.TextContent("Duplicate Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DuplicateArrayElement), serializedProperty); + genericMenu.AddItem(EditorGUIUtility.TextContent("Delete Array Element"), false, new GenericMenu.MenuFunction2(TargetChoiceHandler.DeleteArrayElement), serializedProperty); + } + if (Event.current.shift) + { + if (genericMenu.GetItemCount() > 0) { - return value; + genericMenu.AddSeparator(string.Empty); } - if (EditorGUI.s_GradientID == id) + genericMenu.AddItem(EditorGUIUtility.TextContent("Print Property Path"), false, delegate(object e) { - string commandName = current.commandName; - if (commandName != null) - { - if (EditorGUI.<>f__switch$map4 == null) - { - EditorGUI.<>f__switch$map4 = new Dictionary(1) - { - - { - "GradientPickerChanged", - 0 - } - }; - } - int num; - if (EditorGUI.<>f__switch$map4.TryGetValue(commandName, out num)) - { - if (num == 0) - { - GUI.changed = true; - GradientPreviewCache.ClearCache(); - HandleUtility.Repaint(); - if (property != null) - { - property.gradientValue = GradientPicker.gradient; - } - return GradientPicker.gradient; - } - } - } - } - return value; - case EventType.Repaint: + Debug.Log(((SerializedProperty)e).propertyPath); + }, serializedProperty); + } + Event.current.Use(); + if (genericMenu.GetItemCount() == 0) + { + return; + } + genericMenu.ShowAsContext(); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue) + { + EditorGUI.Slider(position, property, leftValue, rightValue, property.displayName); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, string label) + { + EditorGUI.Slider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + } + public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + float floatValue = EditorGUI.Slider(position, label, property.floatValue, leftValue, rightValue); + if (EditorGUI.EndChangeCheck()) + { + property.floatValue = floatValue; + } + EditorGUI.EndProperty(); + } + public static int IntSlider(Rect position, int value, int leftValue, int rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.IndentedRect(position), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + } + public static int IntSlider(Rect position, string label, int value, int leftValue, int rightValue) + { + return EditorGUI.IntSlider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); + } + public static int IntSlider(Rect position, GUIContent label, int value, int leftValue, int rightValue) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderHash, EditorGUIUtility.native, position); + return Mathf.RoundToInt(EditorGUI.DoSlider(EditorGUI.PrefixLabel(position, controlID, label), EditorGUIUtility.DragZoneRect(position), controlID, (float)value, (float)leftValue, (float)rightValue, EditorGUI.kIntFieldFormatString)); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue) + { + EditorGUI.IntSlider(position, property, leftValue, rightValue, property.displayName); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, string label) + { + EditorGUI.IntSlider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); + } + public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.IntSlider(position, label, property.intValue, leftValue, rightValue); + if (EditorGUI.EndChangeCheck()) { - Rect position2 = new Rect(position.x + 1f, position.y + 1f, position.width - 2f, position.height - 2f); - if (property != null) - { - GradientEditor.DrawGradientSwatch(position2, property, Color.white); - } - else - { - GradientEditor.DrawGradientSwatch(position2, value, Color.white); - } - EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); - return value; + property.intValue = intValue; } + EditorGUI.EndProperty(); + } + internal static void DoTwoLabels(Rect rect, GUIContent leftLabel, GUIContent rightLabel, GUIStyle labelStyle) + { + if (Event.current.type != EventType.Repaint) + { + return; } - goto IL_28; + TextAnchor alignment = labelStyle.alignment; + labelStyle.alignment = TextAnchor.UpperLeft; + GUI.Label(rect, leftLabel, labelStyle); + labelStyle.alignment = TextAnchor.UpperRight; + GUI.Label(rect, rightLabel, labelStyle); + labelStyle.alignment = alignment; } - internal static bool ButtonMouseDown(Rect position, GUIContent content, FocusType fType, GUIStyle style) + private static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString) { - int controlID = GUIUtility.GetControlID(EditorGUI.s_ButtonMouseDownHash, fType, position); - Event current = Event.current; - EventType type = current.type; - switch (type) + return EditorGUI.DoSlider(position, dragZonePosition, id, value, left, right, formatString, 1f); + } + private static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString, float power) + { + float num = position.width; + if (num >= 65f + EditorGUIUtility.fieldWidth) { - case EventType.KeyDown: - if (GUIUtility.keyboardControl == controlID && current.character == ' ') - { - Event.current.Use(); - return true; - } - return false; - case EventType.KeyUp: - case EventType.ScrollWheel: - IL_32: - if (type != EventType.MouseDown) + float num2 = num - 5f - EditorGUIUtility.fieldWidth; + EditorGUI.BeginChangeCheck(); + int controlID = GUIUtility.GetControlID(EditorGUI.s_SliderKnobHash, FocusType.Native, position); + if (GUIUtility.keyboardControl == id && !EditorGUI.s_RecycledEditor.IsEditingControl(id)) { - return false; + GUIUtility.keyboardControl = controlID; } - if (position.Contains(current.mousePosition) && current.button == 0) + float start = left; + float end = right; + if (power != 1f) { - Event.current.Use(); - return true; + start = EditorGUI.PowPreserveSign(left, 1f / power); + end = EditorGUI.PowPreserveSign(right, 1f / power); + value = EditorGUI.PowPreserveSign(value, 1f / power); } - return false; - case EventType.Repaint: - if (EditorGUI.showMixedValue) + Rect position2 = new Rect(position.x, position.y, num2, position.height); + value = GUI.Slider(position2, value, 0f, start, end, GUI.skin.horizontalSlider, (!EditorGUI.showMixedValue) ? GUI.skin.horizontalSliderThumb : "SliderMixed", true, controlID); + if (power != 1f) { - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, EditorGUI.s_MixedValueContent, controlID, false); - EditorGUI.EndHandleMixedValueContentColor(); + value = EditorGUI.PowPreserveSign(value, power); } - else + if (EditorGUIUtility.sliderLabels.HasLabels()) { - style.Draw(position, content, controlID, false); + Color color = GUI.color; + GUI.color *= new Color(1f, 1f, 1f, 0.5f); + Rect rect = new Rect(position2.x, position2.y + 10f, position2.width, position2.height); + EditorGUI.DoTwoLabels(rect, EditorGUIUtility.sliderLabels.leftLabel, EditorGUIUtility.sliderLabels.rightLabel, EditorStyles.miniLabel); + GUI.color = color; + EditorGUIUtility.sliderLabels.SetLabels(null, null); } - return false; - } - goto IL_32; - } - internal static bool IconButton(int id, Rect position, GUIContent content, GUIStyle style) - { - GUIUtility.CheckOnGUI(); - switch (Event.current.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (position.Contains(Event.current.mousePosition)) + if (GUIUtility.keyboardControl == controlID || GUIUtility.hotControl == controlID) { - GUIUtility.hotControl = id; - Event.current.Use(); - return true; + GUIUtility.keyboardControl = id; } - return false; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) + if (GUIUtility.keyboardControl == id && Event.current.type == EventType.KeyDown && !EditorGUI.s_RecycledEditor.IsEditingControl(id) && (Event.current.keyCode == KeyCode.LeftArrow || Event.current.keyCode == KeyCode.RightArrow)) { - GUIUtility.hotControl = 0; + float num3 = MathUtils.GetClosestPowerOfTen(Mathf.Abs((right - left) * 0.01f)); + if (formatString == EditorGUI.kIntFieldFormatString && num3 < 1f) + { + num3 = 1f; + } + if (Event.current.shift) + { + num3 *= 10f; + } + if (Event.current.keyCode == KeyCode.LeftArrow) + { + value -= num3 * 0.5001f; + } + else + { + value += num3 * 0.5001f; + } + value = MathUtils.RoundToMultipleOf(value, num3); + GUI.changed = true; Event.current.Use(); - return position.Contains(Event.current.mousePosition); } - return false; - case EventType.MouseDrag: - if (position.Contains(Event.current.mousePosition)) + if (EditorGUI.EndChangeCheck()) { - GUIUtility.hotControl = id; - Event.current.Use(); - return true; + float f = (right - left) / (num2 - (float)GUI.skin.horizontalSlider.padding.horizontal - GUI.skin.horizontalSliderThumb.fixedWidth); + value = MathUtils.RoundBasedOnMinimumDifference(value, Mathf.Abs(f)); + if (EditorGUI.s_RecycledEditor.IsEditingControl(id)) + { + EditorGUI.s_RecycledEditor.EndEditing(); + } } - break; - case EventType.Repaint: - style.Draw(position, content, id); - break; + value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, new Rect(position.x + num2 + 5f, position.y, EditorGUIUtility.fieldWidth, position.height), dragZonePosition, id, value, formatString, EditorStyles.numberField, true); } - return false; - } - internal static Vector2 MouseDeltaReader(Rect position, bool activated) - { - int controlID = GUIUtility.GetControlID(EditorGUI.s_MouseDeltaReaderHash, FocusType.Passive, position); - Event current = Event.current; - switch (current.GetTypeForControl(controlID)) + else { - case EventType.MouseDown: - if (activated && GUIUtility.hotControl == 0 && position.Contains(current.mousePosition) && current.button == 0) - { - GUIUtility.hotControl = controlID; - GUIUtility.keyboardControl = 0; - EditorGUI.s_MouseDeltaReaderLastPos = GUIClip.Unclip(current.mousePosition); - current.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == controlID && current.button == 0) - { - GUIUtility.hotControl = 0; - current.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == controlID) - { - Vector2 a = GUIClip.Unclip(current.mousePosition); - Vector2 result = a - EditorGUI.s_MouseDeltaReaderLastPos; - EditorGUI.s_MouseDeltaReaderLastPos = a; - current.Use(); - return result; - } - break; + num = Mathf.Min(EditorGUIUtility.fieldWidth, num); + position.x = position.xMax - num; + position.width = num; + value = EditorGUI.DoFloatField(EditorGUI.s_RecycledEditor, position, dragZonePosition, id, value, formatString, EditorStyles.numberField, true); } - return Vector2.zero; + value = Mathf.Clamp(value, Mathf.Min(left, right), Mathf.Max(left, right)); + return value; } - internal static void GameViewSizePopup(Rect buttonRect, GameViewSizeGroupType groupType, int selectedIndex, Action itemClickedCallback, GUIStyle guiStyle) + public static void MinMaxSlider(GUIContent label, Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { - GameViewSizeGroup group = ScriptableSingleton.instance.GetGroup(groupType); - string t; - if (selectedIndex >= 0 && selectedIndex < group.GetTotalCount()) + int controlID = GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native); + EditorGUI.DoMinMaxSlider(EditorGUI.PrefixLabel(position, controlID, label), controlID, ref minValue, ref maxValue, minLimit, maxLimit); + } + public static void MinMaxSlider(Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + EditorGUI.DoMinMaxSlider(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MinMaxSliderHash, FocusType.Native), ref minValue, ref maxValue, minLimit, maxLimit); + } + private static void DoMinMaxSlider(Rect position, int id, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + float num = maxValue - minValue; + EditorGUI.BeginChangeCheck(); + EditorGUIExt.DoMinMaxSlider(position, id, ref minValue, ref num, minLimit, maxLimit, minLimit, maxLimit, GUI.skin.horizontalSlider, EditorStyles.minMaxHorizontalSliderThumb, true); + if (EditorGUI.EndChangeCheck()) { - t = group.GetGameViewSize(selectedIndex).displayText; + maxValue = minValue + num; } - else + } + private static int PopupInternal(Rect position, string label, int selectedIndex, string[] displayedOptions, GUIStyle style) + { + return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + } + private static int PopupInternal(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position); + return EditorGUI.DoPopup(EditorGUI.PrefixLabel(position, controlID, label), controlID, selectedIndex, displayedOptions, style); + } + private static void Popup(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.BeginChangeCheck(); + int enumValueIndex = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.enumValueIndex : -1, EditorGUIUtility.TempContent(property.enumDisplayNames)); + if (EditorGUI.EndChangeCheck()) { - t = string.Empty; + property.enumValueIndex = enumValueIndex; } - if (EditorGUI.ButtonMouseDown(buttonRect, GUIContent.Temp(t), FocusType.Passive, guiStyle)) + } + internal static void Popup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.Popup(position, label, (!property.hasMultipleDifferentValues) ? property.intValue : -1, displayedOptions); + if (EditorGUI.EndChangeCheck()) { - IFlexibleMenuItemProvider itemProvider = new GameViewSizesMenuItemProvider(groupType); - FlexibleMenu windowContent = new FlexibleMenu(itemProvider, selectedIndex, new GameViewSizesMenuModifyItemUI(), itemClickedCallback); - PopupWindow.Show(buttonRect, windowContent); + property.intValue = intValue; } + EditorGUI.EndProperty(); } - public static void DrawRect(Rect rect, Color color) + private static Enum EnumPopupInternal(Rect position, GUIContent label, Enum selected, GUIStyle style) { - if (Event.current.type != EventType.Repaint) + Type type = selected.GetType(); + if (!type.IsEnum) { - return; + throw new Exception("parameter _enum must be of type System.Enum"); } - Color color2 = GUI.color; - GUI.color *= color; - GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); - GUI.color = color2; + string[] names = Enum.GetNames(type); + int num = Array.IndexOf(names, Enum.GetName(type, selected)); + num = EditorGUI.Popup(position, label, num, EditorGUIUtility.TempContent(( + from x in names + select ObjectNames.NicifyVariableName(x)).ToArray()), style); + if (num < 0 || num >= names.Length) + { + return selected; + } + return (Enum)Enum.Parse(type, names[num]); } - internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects) + private static int IntPopupInternal(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style) { - return EditorGUI.DoObjectField(position, dropRect, id, obj, objType, property, validator, allowSceneObjects, EditorStyles.objectField); + int num; + if (optionValues != null) + { + num = 0; + while (num < optionValues.Length && selectedValue != optionValues[num]) + { + num++; + } + } + else + { + num = selectedValue; + } + num = EditorGUI.PopupInternal(position, label, num, displayedOptions, style); + if (optionValues == null) + { + return num; + } + if (num < 0 || num >= optionValues.Length) + { + return selectedValue; + } + return optionValues[num]; } - internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) + internal static void IntPopupInternal(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label) { - if (validator == null) + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.IntPopupInternal(position, label, property.intValue, displayedOptions, optionValues, EditorStyles.popup); + if (EditorGUI.EndChangeCheck()) { - validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); + property.intValue = intValue; } + EditorGUI.EndProperty(); + } + internal static void SortingLayerField(Rect position, GUIContent label, SerializedProperty layerID, GUIStyle style, GUIStyle labelStyle) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_SortingLayerFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label, labelStyle); Event current = Event.current; - EventType eventType = current.type; - if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) { - eventType = Event.current.rawType; + int[] sortingLayerUniqueIDs = InternalEditorUtility.sortingLayerUniqueIDs; + if (selectedValueForControl >= sortingLayerUniqueIDs.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "SortingLayers"; + Selection.activeObject = EditorApplication.tagManager; + } + else + { + layerID.intValue = sortingLayerUniqueIDs[selectedValueForControl]; + } } - bool flag = EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f; - Vector2 iconSize = EditorGUIUtility.GetIconSize(); - if (!flag) + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) { - EditorGUIUtility.SetIconSize(new Vector2(12f, 12f)); + int[] sortingLayerUniqueIDs2 = InternalEditorUtility.sortingLayerUniqueIDs; + string[] sortingLayerNames = InternalEditorUtility.sortingLayerNames; + int i; + for (i = 0; i < sortingLayerUniqueIDs2.Length; i++) + { + if (sortingLayerUniqueIDs2[i] == layerID.intValue) + { + break; + } + } + ArrayUtility.Add(ref sortingLayerNames, string.Empty); + ArrayUtility.Add(ref sortingLayerNames, "Add Sorting Layer..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(sortingLayerNames), style); } - EventType eventType2 = eventType; - switch (eventType2) + else { - case EventType.KeyDown: - if (GUIUtility.keyboardControl == id) + if (Event.current.type == EventType.Repaint) { - if (current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete) + GUIContent content; + if (layerID.hasMultipleDifferentValues) { - if (property != null) - { - property.objectReferenceValue = null; - } - else - { - obj = null; - } - GUI.changed = true; - current.Use(); + content = EditorGUI.mixedValueContent; } - if (current.MainActionKeyForControl(id)) + else { - ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); - ObjectSelector.get.objectSelectorID = id; - current.Use(); - GUIUtility.ExitGUI(); + content = EditorGUIUtility.TempContent(InternalEditorUtility.GetSortingLayerNameFromUniqueID(layerID.intValue)); } + EditorGUI.showMixedValue = layerID.hasMultipleDifferentValues; + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, content, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + EditorGUI.showMixedValue = false; } - goto IL_63A; - case EventType.KeyUp: - case EventType.ScrollWheel: - case EventType.Layout: - case EventType.Ignore: - case EventType.Used: - case EventType.ValidateCommand: - IL_CA: - if (eventType2 != EventType.MouseDown) - { - goto IL_63A; - } - if (Event.current.button != 0) + } + } + internal static int DoPopup(Rect position, int controlID, int selected, GUIContent[] popupValues, GUIStyle style) + { + selected = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, selected); + GUIContent gUIContent = null; + if (gUIContent == null) + { + if (EditorGUI.showMixedValue) { - goto IL_63A; + gUIContent = EditorGUI.s_MixedValueContent; } - if (position.Contains(Event.current.mousePosition)) + else { - Rect rect; - if (flag) + if (selected < 0 || selected >= popupValues.Length) { - rect = new Rect(position.xMax - 32f, position.yMax - 14f, 32f, 14f); + gUIContent = GUIContent.none; } else { - rect = new Rect(position.xMax - 15f, position.y, 15f, position.height); + gUIContent = popupValues[selected]; } - EditorGUIUtility.editingTextField = false; - if (rect.Contains(Event.current.mousePosition)) + } + } + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(controlID)) + { + if (Application.platform == RuntimePlatform.OSXEditor) { - if (GUI.enabled) - { - GUIUtility.keyboardControl = id; - ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); - ObjectSelector.get.objectSelectorID = id; - current.Use(); - GUIUtility.ExitGUI(); - } + position.y = position.y - (float)(selected * 16) - 19f; } - else + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); + EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + current.Use(); + } + return selected; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_6A: + if (type != EventType.MouseDown) + { + return selected; + } + if (current.button == 0 && position.Contains(current.mousePosition)) + { + if (Application.platform == RuntimePlatform.OSXEditor) { - UnityEngine.Object @object = (property == null) ? obj : property.objectReferenceValue; - Component component = @object as Component; - if (component) - { - @object = component.gameObject; - } - if (EditorGUI.showMixedValue) - { - @object = null; - } - if (Event.current.clickCount == 1) - { - GUIUtility.keyboardControl = id; - if (@object) - { - EditorGUIUtility.PingObject(@object); - } - current.Use(); - } - else - { - if (Event.current.clickCount == 2) - { - if (@object) - { - AssetDatabase.OpenAsset(@object); - GUIUtility.ExitGUI(); - } - current.Use(); - } - } + position.y = position.y - (float)(selected * 16) - 19f; } + EditorGUI.PopupCallbackInfo.instance = new EditorGUI.PopupCallbackInfo(controlID); + EditorUtility.DisplayCustomMenu(position, popupValues, (!EditorGUI.showMixedValue) ? selected : -1, new EditorUtility.SelectMenuItemFunction(EditorGUI.PopupCallbackInfo.instance.SetEnumValueDelegate), null); + GUIUtility.keyboardControl = controlID; + current.Use(); } - goto IL_63A; + return selected; case EventType.Repaint: { - GUIContent gUIContent; - if (EditorGUI.showMixedValue) + Font font = style.font; + if (font && EditorGUIUtility.GetBoldDefaultFont() && font == EditorStyles.miniFont) { - gUIContent = EditorGUI.s_MixedValueContent; + style.font = EditorStyles.miniBoldFont; + } + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, gUIContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + style.font = font; + return selected; + } + } + goto IL_6A; + } + internal static string TagFieldInternal(Rect position, string tag, GUIStyle style) + { + position = EditorGUI.IndentedRect(position); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + Event current = Event.current; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + string[] tags = InternalEditorUtility.tags; + if (selectedValueForControl >= tags.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; + Selection.activeObject = EditorApplication.tagManager; } else { - if (property != null) - { - gUIContent = EditorGUIUtility.TempContent(property.objectReferenceStringValue, AssetPreview.GetMiniThumbnail(property.objectReferenceValue)); - obj = property.objectReferenceValue; - if (obj != null) - { - UnityEngine.Object[] references = new UnityEngine.Object[] - { - obj - }; - if (validator(references, objType, property) == null) - { - gUIContent = EditorGUIUtility.TempContent("Type mismatch"); - } - } - } - else + tag = tags[selectedValueForControl]; + } + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + string[] tags2 = InternalEditorUtility.tags; + int i; + for (i = 0; i < tags2.Length; i++) + { + if (tags2[i] == tag) { - gUIContent = EditorGUIUtility.ObjectContent(obj, objType); + break; } } - if (flag) + ArrayUtility.Add(ref tags2, string.Empty); + ArrayUtility.Add(ref tags2, "Add Tag..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); + return tag; + } + if (Event.current.type == EventType.Repaint) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, (!EditorGUI.showMixedValue) ? EditorGUIUtility.TempContent(tag) : EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + return tag; + } + internal static string TagFieldInternal(Rect position, GUIContent label, string tag, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + string[] tags = InternalEditorUtility.tags; + if (selectedValueForControl >= tags.Length) { - GUIStyle objectFieldThumb = EditorStyles.objectFieldThumb; - objectFieldThumb.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); - if (obj != null && !EditorGUI.showMixedValue) - { - bool flag2 = obj is Cubemap; - Rect position2 = objectFieldThumb.padding.Remove(position); - if (flag2) - { - position2.x += (position2.width - (float)gUIContent.image.width) / 2f; - position2.y += (position2.height - (float)gUIContent.image.width) / 2f; - GUIStyle.none.Draw(position2, gUIContent.image, false, false, false, false); - } - else - { - Texture2D texture2D = gUIContent.image as Texture2D; - if (texture2D != null && texture2D.alphaIsTransparency) - { - EditorGUI.DrawTextureTransparent(position2, texture2D); - } - else - { - EditorGUI.DrawPreviewTexture(position2, gUIContent.image); - } - } - } - else - { - GUIStyle gUIStyle = objectFieldThumb.name + "Overlay"; - EditorGUI.BeginHandleMixedValueContentColor(); - gUIStyle.Draw(position, gUIContent, id); - EditorGUI.EndHandleMixedValueContentColor(); - } - GUIStyle gUIStyle2 = objectFieldThumb.name + "Overlay2"; - gUIStyle2.Draw(position, EditorGUIUtility.TempContent("Select"), id); + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Tags"; + Selection.activeObject = EditorApplication.tagManager; } else { - EditorGUI.BeginHandleMixedValueContentColor(); - style.Draw(position, gUIContent, id, DragAndDrop.activeControlID == id); - EditorGUI.EndHandleMixedValueContentColor(); + tag = tags[selectedValueForControl]; } - goto IL_63A; } - case EventType.DragUpdated: - case EventType.DragPerform: - if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled) + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + string[] tags2 = InternalEditorUtility.tags; + int i; + for (i = 0; i < tags2.Length; i++) { - UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; - UnityEngine.Object object2 = validator(objectReferences, objType, property); - if (object2 != null && !allowSceneObjects && !EditorUtility.IsPersistent(object2)) + if (tags2[i] == tag) { - object2 = null; + break; } - if (object2 != null) + } + ArrayUtility.Add(ref tags2, string.Empty); + ArrayUtility.Add(ref tags2, "Add Tag..."); + EditorGUI.DoPopup(position, controlID, i, EditorGUIUtility.TempContent(tags2), style); + return tag; + } + if (Event.current.type == EventType.Repaint) + { + style.Draw(position, EditorGUIUtility.TempContent(tag), controlID, false); + } + return tag; + } + internal static int LayerFieldInternal(Rect position, GUIContent label, int layer, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_TagFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + bool changed = GUI.changed; + int selectedValueForControl = EditorGUI.PopupCallbackInfo.GetSelectedValueForControl(controlID, -1); + if (selectedValueForControl != -1) + { + if (selectedValueForControl >= InternalEditorUtility.layers.Length) + { + ((TagManager)EditorApplication.tagManager).m_DefaultExpandedFoldout = "Layers"; + Selection.activeObject = EditorApplication.tagManager; + GUI.changed = changed; + } + else + { + int num = 0; + for (int i = 0; i < 32; i++) { - DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (eventType == EventType.DragPerform) + if (InternalEditorUtility.GetLayerName(i).Length != 0) { - if (property != null) - { - property.objectReferenceValue = object2; - } - else + if (num == selectedValueForControl) { - obj = object2; + layer = i; + break; } - GUI.changed = true; - DragAndDrop.AcceptDrag(); - DragAndDrop.activeControlID = 0; - } - else - { - DragAndDrop.activeControlID = id; + num++; } - Event.current.Use(); } } - goto IL_63A; - case EventType.ExecuteCommand: + } + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) { - string commandName = current.commandName; - if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == id && GUIUtility.keyboardControl == id) + int num2 = 0; + for (int j = 0; j < 32; j++) { - UnityEngine.Object[] references2 = new UnityEngine.Object[] - { - ObjectSelector.GetCurrentObject() - }; - UnityEngine.Object object3 = validator(references2, objType, property); - if (property != null) + if (InternalEditorUtility.GetLayerName(j).Length != 0) { - property.objectReferenceValue = object3; + if (j == layer) + { + break; + } + num2++; } - GUI.changed = true; - current.Use(); - return object3; } - goto IL_63A; + string[] layers = InternalEditorUtility.layers; + ArrayUtility.Add(ref layers, string.Empty); + ArrayUtility.Add(ref layers, "Add Layer..."); + EditorGUI.DoPopup(position, controlID, num2, EditorGUIUtility.TempContent(layers), style); + Event.current.Use(); + return layer; } - case EventType.DragExited: - if (GUI.enabled) + if (current.type == EventType.Repaint) + { + style.Draw(position, EditorGUIUtility.TempContent(InternalEditorUtility.GetLayerName(layer)), controlID, false); + } + return layer; + } + internal static int MaskFieldInternal(Rect position, GUIContent label, int mask, string[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + return MaskFieldGUI.DoMaskField(position, controlID, mask, displayedOptions, style); + } + internal static int MaskFieldInternal(Rect position, int mask, string[] displayedOptions, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + return MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), controlID, mask, displayedOptions, style); + } + internal static Enum EnumMaskFieldInternal(Rect position, GUIContent label, Enum enumValue, GUIStyle style) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position.xMax = position2.x; + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + return Enum.Parse(enumValue.GetType(), MaskFieldGUI.DoMaskField(position2, controlID, Convert.ToInt32(enumValue), flagNames, style).ToString()) as Enum; + } + internal static Enum EnumMaskFieldInternal(Rect position, Enum enumValue, GUIStyle style) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style); + return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + } + internal static Enum EnumMaskField(Rect position, Enum enumValue, GUIStyle style, out int changedFlags, out bool changedToValue) + { + Type type = enumValue.GetType(); + if (!type.IsEnum) + { + throw new Exception("parameter _enum must be of type System.Enum"); + } + string[] flagNames = ( + from x in Enum.GetNames(enumValue.GetType()) + select ObjectNames.NicifyVariableName(x)).ToArray(); + int num = MaskFieldGUI.DoMaskField(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_MaskField, EditorGUIUtility.native, position), Convert.ToInt32(enumValue), flagNames, style, out changedFlags, out changedToValue); + return Enum.Parse(enumValue.GetType(), num.ToString()) as Enum; + } + public static void ObjectField(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.ObjectField(position, property, null, label, EditorStyles.objectField); + } + public static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label) + { + EditorGUI.ObjectField(position, property, objType, label, EditorStyles.objectField); + } + internal static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + { + label = EditorGUI.BeginProperty(position, label, property); + EditorGUI.ObjectFieldInternal(position, property, objType, label, style); + EditorGUI.EndProperty(); + } + private static void ObjectFieldInternal(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_PPtrHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + bool allowSceneObjects = false; + if (property != null) + { + UnityEngine.Object targetObject = property.serializedObject.targetObject; + if (targetObject != null && !EditorUtility.IsPersistent(targetObject)) { - HandleUtility.Repaint(); + allowSceneObjects = true; } - goto IL_63A; } - goto IL_CA; - IL_63A: - EditorGUIUtility.SetIconSize(iconSize); - return obj; + EditorGUI.DoObjectField(position, position, controlID, null, null, property, null, allowSceneObjects, style); } - internal static UnityEngine.Object DoDropField(Rect position, int id, Type objType, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) + public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + return EditorGUI.DoObjectField(EditorGUI.IndentedRect(position), EditorGUI.IndentedRect(position), controlID, obj, objType, null, null, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, UnityEngine.Object obj, Type objType) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, true); + } + public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, allowSceneObjects); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, string label, UnityEngine.Object obj, Type objType) + { + return EditorGUI.ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, true); + } + public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType, bool allowSceneObjects) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + if (EditorGUIUtility.HasObjectThumbnail(objType) && position.height > 16f) + { + float num = Mathf.Min(position.width, position.height); + position.height = num; + position.xMin = position.xMax - num; + } + return EditorGUI.DoObjectField(position, position, controlID, obj, objType, null, null, allowSceneObjects); + } + internal static void GetRectsForMiniThumbnailField(Rect position, out Rect thumbRect, out Rect labelRect) + { + thumbRect = EditorGUI.IndentedRect(position); + thumbRect.y -= 1f; + thumbRect.height = 18f; + thumbRect.width = 32f; + float num = thumbRect.x + 30f; + labelRect = new Rect(num, position.y, thumbRect.x + EditorGUIUtility.labelWidth - num, position.height); + } + internal static UnityEngine.Object MiniThumbnailObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType, EditorGUI.ObjectFieldValidator validator) + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_ObjectFieldHash, EditorGUIUtility.native, position); + Rect rect; + Rect labelPosition; + EditorGUI.GetRectsForMiniThumbnailField(position, out rect, out labelPosition); + EditorGUI.HandlePrefixLabel(position, labelPosition, label, controlID, EditorStyles.label); + return EditorGUI.DoObjectField(rect, rect, controlID, obj, objType, null, validator, false); + } + [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] + public static UnityEngine.Object ObjectField(Rect position, GUIContent label, UnityEngine.Object obj, Type objType) + { + return EditorGUI.ObjectField(position, label, obj, objType, true); + } + internal static UnityEngine.Object ValidateObjectFieldAssignment(UnityEngine.Object[] references, Type objType, SerializedProperty property) { - if (validator == null) - { - validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); - } - Event current = Event.current; - EventType eventType = current.type; - if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) - { - eventType = Event.current.rawType; - } - EventType eventType2 = eventType; - switch (eventType2) + if (references.Length > 0) { - case EventType.Repaint: - style.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); - goto IL_144; - case EventType.Layout: - IL_6B: - if (eventType2 != EventType.DragExited) + bool flag = DragAndDrop.objectReferences.Length > 0; + bool flag2 = references[0] != null && references[0].GetType() == typeof(Texture2D); + if (objType == typeof(Sprite) && flag2 && flag) { - goto IL_144; + return SpriteUtility.TextureToSprite(references[0] as Texture2D); } - if (GUI.enabled) + if (property != null) { - HandleUtility.Repaint(); + if (references[0] != null && property.ValidateObjectReferenceValue(references[0])) + { + return references[0]; + } + if ((property.type == "PPtr" || property.type == "PPtr<$Sprite>" || property.type == "vector") && flag2 && flag) + { + return SpriteUtility.TextureToSprite(references[0] as Texture2D); + } } - goto IL_144; - case EventType.DragUpdated: - case EventType.DragPerform: - if (position.Contains(Event.current.mousePosition) && GUI.enabled) + else { - UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; - UnityEngine.Object @object = validator(objectReferences, objType, null); - if (@object != null && !allowSceneObjects && !EditorUtility.IsPersistent(@object)) + if (references[0] != null && references[0].GetType() == typeof(GameObject) && typeof(Component).IsAssignableFrom(objType)) { - @object = null; + GameObject gameObject = (GameObject)references[0]; + references = gameObject.GetComponents(typeof(Component)); } - if (@object != null) + UnityEngine.Object[] array = references; + for (int i = 0; i < array.Length; i++) { - DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (eventType == EventType.DragPerform) + UnityEngine.Object @object = array[i]; + if (@object != null && objType.IsAssignableFrom(@object.GetType())) { - GUI.changed = true; - DragAndDrop.AcceptDrag(); - DragAndDrop.activeControlID = 0; - Event.current.Use(); return @object; } - DragAndDrop.activeControlID = id; - Event.current.Use(); } } - goto IL_144; } - goto IL_6B; - IL_144: return null; } - internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label) - { - EditorGUI.TargetChoiceField(position, property, label, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); - } - internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label, TargetChoiceHandler.TargetChoiceMenuFunction func) - { - EditorGUI.BeginProperty(position, label, property); - position = EditorGUI.PrefixLabel(position, 0, label); - EditorGUI.BeginHandleMixedValueContentColor(); - if (GUI.Button(position, EditorGUI.mixedValueContent, EditorStyles.popup)) - { - GenericMenu genericMenu = new GenericMenu(); - TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, property, func); - genericMenu.DropDown(position); - } - EditorGUI.EndHandleMixedValueContentColor(); - EditorGUI.EndProperty(); - } - internal static void VUMeterHorizontal(Rect position, float value, ref EditorGUI.VUMeterData data) - { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (!EditorGUI.s_HorizontalVUTexture) - { - EditorGUI.s_HorizontalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureHorizontal"); - } - Color color = GUI.color; - Color contentColor = GUI.contentColor; - Color backgroundColor = GUI.backgroundColor; - if (value < data.lastValue) - { - value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7f); - } - else - { - value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2f); - data.peakValue = value; - data.peakValueTime = Time.realtimeSinceStartup; - } - if (value > 1.11111116f) - { - value = 1.11111116f; - } - if (data.peakValue > 1.11111116f) - { - data.peakValue = 1.11111116f; - } - GUI.contentColor = new Color(0f, 0f, 0f, 0f); - EditorStyles.progressBarBack.Draw(position, false, false, false, false); - float num = position.width * (value * 0.9f) - 2f; - if (num < 2f) - { - num = 2f; - } - Rect position2 = new Rect(position.x + 1f, position.y + 1f, num, position.height - 2f); - Rect texCoords = new Rect(0f, 0f, value * 0.9f, 1f); - GUI.DrawTextureWithTexCoords(position2, EditorGUI.s_HorizontalVUTexture, texCoords); - GUI.color = Color.white; - num = position.width * (data.peakValue * 0.9f) - 2f; - if (num < 2f) - { - num = 2f; - } - position2 = new Rect(position.x + num, position.y + 1f, 1f, position.height - 2f); - if (Time.realtimeSinceStartup - data.peakValueTime < 1f) - { - GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); - } - GUI.backgroundColor = backgroundColor; - GUI.color = color; - GUI.contentColor = contentColor; - data.lastValue = value; - } - internal static void VUMeterVertical(Rect position, float value, ref EditorGUI.VUMeterData data) + private static UnityEngine.Object HandleTextureToSprite(Texture2D tex) { - if (Event.current.type != EventType.Repaint) - { - return; - } - if (!EditorGUI.s_VerticalVUTexture) - { - EditorGUI.s_VerticalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureVertical"); - } - Color color = GUI.color; - Color contentColor = GUI.contentColor; - Color backgroundColor = GUI.backgroundColor; - if (value < data.lastValue) - { - value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7f); - } - else - { - value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2f); - data.peakValue = value; - data.peakValueTime = Time.realtimeSinceStartup; - } - if (value > 1.11111116f) - { - value = 1.11111116f; - } - if (data.peakValue > 1.11111116f) - { - data.peakValue = 1.11111116f; - } - GUI.contentColor = new Color(0f, 0f, 0f, 0f); - EditorStyles.progressBarBack.Draw(position, false, false, false, false); - float num = position.height * (value * 0.9f) - 2f; - if (num < 2f) - { - num = 2f; - } - Rect position2 = new Rect(position.x + 1f, position.y + position.height - num, position.width - 2f, num); - Rect texCoords = new Rect(0f, 0f, 1f, value * 0.9f); - GUI.DrawTextureWithTexCoords(position2, EditorGUI.s_VerticalVUTexture, texCoords); - GUI.color = Color.white; - num = position.height * (data.peakValue * 0.9f) - 2f; - if (num < 2f) - { - num = 2f; - } - position2 = new Rect(position.x + 1f, position.y + position.height - num, position.width - 2f, 1f); - if (Time.realtimeSinceStartup - data.peakValueTime < 1f) + UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); + for (int i = 0; i < array.Length; i++) { - GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); + if (array[i].GetType() == typeof(Sprite)) + { + return array[i]; + } } - GUI.backgroundColor = backgroundColor; - GUI.color = color; - GUI.contentColor = contentColor; - data.lastValue = value; - } - [ExcludeFromDocs] - public static void LabelField(Rect position, string label) - { - GUIStyle label2 = EditorStyles.label; - EditorGUI.LabelField(position, label, label2); - } - public static void LabelField(Rect position, string label, [DefaultValue("EditorStyles.label")] GUIStyle style) - { - EditorGUI.LabelField(position, GUIContent.none, EditorGUIUtility.TempContent(label), style); + return tex; } - [ExcludeFromDocs] - public static void LabelField(Rect position, GUIContent label) + public static Rect IndentedRect(Rect source) { - GUIStyle label2 = EditorStyles.label; - EditorGUI.LabelField(position, label, label2); + float indent = EditorGUI.indent; + return new Rect(source.x + indent, source.y, source.width - indent, source.height); } - public static void LabelField(Rect position, GUIContent label, [DefaultValue("EditorStyles.label")] GUIStyle style) + public static Vector2 Vector2Field(Rect position, string label, Vector2 value) { - EditorGUI.LabelField(position, GUIContent.none, label, style); + return EditorGUI.Vector2Field(position, EditorGUIUtility.TempContent(label), value); } - [ExcludeFromDocs] - public static void LabelField(Rect position, string label, string label2) + public static Vector2 Vector2Field(Rect position, GUIContent label, Vector2 value) { - GUIStyle label3 = EditorStyles.label; - EditorGUI.LabelField(position, label, label2, label3); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + return EditorGUI.Vector2Field(position, value); } - public static void LabelField(Rect position, string label, string label2, [DefaultValue("EditorStyles.label")] GUIStyle style) + private static Vector2 Vector2Field(Rect position, Vector2 value) { - EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent(label2), style); + EditorGUI.s_Vector2Floats[0] = value.x; + EditorGUI.s_Vector2Floats[1] = value.y; + position.height = 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector2Floats[0]; + value.y = EditorGUI.s_Vector2Floats[1]; + } + return value; } - [ExcludeFromDocs] - public static void LabelField(Rect position, GUIContent label, GUIContent label2) + public static Vector3 Vector3Field(Rect position, string label, Vector3 value) { - GUIStyle label3 = EditorStyles.label; - EditorGUI.LabelField(position, label, label2, label3); + return EditorGUI.Vector3Field(position, EditorGUIUtility.TempContent(label), value); } - public static void LabelField(Rect position, GUIContent label, GUIContent label2, [DefaultValue("EditorStyles.label")] GUIStyle style) + public static Vector3 Vector3Field(Rect position, GUIContent label, Vector3 value) { - EditorGUI.LabelFieldInternal(position, label, label2, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + position.height = 16f; + return EditorGUI.Vector3Field(position, value); } - [ExcludeFromDocs] - public static bool ToggleLeft(Rect position, string label, bool value) + private static Vector3 Vector3Field(Rect position, Vector3 value) { - GUIStyle label2 = EditorStyles.label; - return EditorGUI.ToggleLeft(position, label, value, label2); + EditorGUI.s_Vector3Floats[0] = value.x; + EditorGUI.s_Vector3Floats[1] = value.y; + EditorGUI.s_Vector3Floats[2] = value.z; + position.height = 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYZLabels, EditorGUI.s_Vector3Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector3Floats[0]; + value.y = EditorGUI.s_Vector3Floats[1]; + value.z = EditorGUI.s_Vector3Floats[2]; + } + return value; } - public static bool ToggleLeft(Rect position, string label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) + private static void Vector2Field(Rect position, SerializedProperty property, GUIContent label) { - return EditorGUI.ToggleLeft(position, EditorGUIUtility.TempContent(label), value, labelStyle); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); } - [ExcludeFromDocs] - public static bool ToggleLeft(Rect position, GUIContent label, bool value) + private static void Vector3Field(Rect position, SerializedProperty property, GUIContent label) { - GUIStyle label2 = EditorStyles.label; - return EditorGUI.ToggleLeft(position, label, value, label2); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); } - public static bool ToggleLeft(Rect position, GUIContent label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) + private static void Vector4Field(Rect position, SerializedProperty property, GUIContent label) { - return EditorGUI.ToggleLeftInternal(position, label, value, labelStyle); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 4); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZWLabels, serializedProperty); } - [ExcludeFromDocs] - public static string TextField(Rect position, string text) + public static Vector4 Vector4Field(Rect position, string label, Vector4 value) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.TextField(position, text, textField); + EditorGUI.s_Vector4Floats[0] = value.x; + EditorGUI.s_Vector4Floats[1] = value.y; + EditorGUI.s_Vector4Floats[2] = value.z; + EditorGUI.s_Vector4Floats[3] = value.w; + position.height = 16f; + GUI.Label(EditorGUI.IndentedRect(position), label, EditorStyles.label); + position.y += 16f; + EditorGUI.BeginChangeCheck(); + EditorGUI.indentLevel++; + EditorGUI.MultiFloatField(position, EditorGUI.s_XYZWLabels, EditorGUI.s_Vector4Floats); + EditorGUI.indentLevel--; + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector4Floats[0]; + value.y = EditorGUI.s_Vector4Floats[1]; + value.z = EditorGUI.s_Vector4Floats[2]; + value.w = EditorGUI.s_Vector4Floats[3]; + } + return value; } - public static string TextField(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + public static Rect RectField(Rect position, Rect value) { - return EditorGUI.TextFieldInternal(position, text, style); + position.height = 16f; + EditorGUI.s_Vector2Floats[0] = value.x; + EditorGUI.s_Vector2Floats[1] = value.y; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_XYLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.x = EditorGUI.s_Vector2Floats[0]; + value.y = EditorGUI.s_Vector2Floats[1]; + } + position.y += 16f; + EditorGUI.s_Vector2Floats[0] = value.width; + EditorGUI.s_Vector2Floats[1] = value.height; + EditorGUI.BeginChangeCheck(); + EditorGUI.MultiFloatField(position, EditorGUI.s_WHLabels, EditorGUI.s_Vector2Floats); + if (EditorGUI.EndChangeCheck()) + { + value.width = EditorGUI.s_Vector2Floats[0]; + value.height = EditorGUI.s_Vector2Floats[1]; + } + return value; } - [ExcludeFromDocs] - public static string TextField(Rect position, string label, string text) + public static Rect RectField(Rect position, string label, Rect value) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.TextField(position, label, text, textField); + return EditorGUI.RectField(position, EditorGUIUtility.TempContent(label), value); } - public static string TextField(Rect position, string label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + public static Rect RectField(Rect position, GUIContent label, Rect value) { - return EditorGUI.TextField(position, EditorGUIUtility.TempContent(label), text, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + return EditorGUI.RectField(position, value); } - [ExcludeFromDocs] - public static string TextField(Rect position, GUIContent label, string text) + private static void RectField(Rect position, SerializedProperty property, GUIContent label) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.TextField(position, label, text, textField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 2); + position.height = 16f; + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYLabels, serializedProperty); + position.y += 16f; + EditorGUI.MultiPropertyField(position, EditorGUI.s_WHLabels, serializedProperty); } - public static string TextField(Rect position, GUIContent label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + private static Rect DrawBoundsFieldLabelsAndAdjustPositionForValues(Rect position, bool drawOutside) { - return EditorGUI.TextFieldInternal(position, label, text, style); + if (drawOutside) + { + position.xMin -= 53f; + } + GUI.Label(EditorGUI.IndentedRect(position), "Center:", EditorStyles.label); + position.y += 16f; + GUI.Label(EditorGUI.IndentedRect(position), "Extents:", EditorStyles.label); + position.y -= 16f; + position.xMin += 53f; + return position; } - [ExcludeFromDocs] - public static string TextArea(Rect position, string text) + public static Bounds BoundsField(Rect position, Bounds value) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.TextArea(position, text, textField); + return EditorGUI.BoundsField(position, GUIContent.none, value); } - public static string TextArea(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) + public static Bounds BoundsField(Rect position, GUIContent label, Bounds value) { - return EditorGUI.TextAreaInternal(position, text, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) + { + position.y += 16f; + } + position.height = 16f; + position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); + value.center = EditorGUI.Vector3Field(position, value.center); + position.y += 16f; + value.extents = EditorGUI.Vector3Field(position, value.extents); + return value; } - [ExcludeFromDocs] - public static void SelectableLabel(Rect position, string text) + private static void BoundsField(Rect position, SerializedProperty property, GUIContent label) { - GUIStyle label = EditorStyles.label; - EditorGUI.SelectableLabel(position, text, label); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, 3); + if (EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)) + { + position.y += 16f; + } + position.height = 16f; + position = EditorGUI.DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && EditorGUI.LabelHasContent(label)); + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.NextVisible(true); + serializedProperty.NextVisible(true); + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); + serializedProperty.NextVisible(true); + position.y += 16f; + EditorGUI.MultiPropertyField(position, EditorGUI.s_XYZLabels, serializedProperty); } - public static void SelectableLabel(Rect position, string text, [DefaultValue("EditorStyles.label")] GUIStyle style) + public static void MultiFloatField(Rect position, GUIContent label, GUIContent[] subLabels, float[] values) { - EditorGUI.SelectableLabelInternal(position, text, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); + position.height = 16f; + EditorGUI.MultiFloatField(position, subLabels, values); } - [ExcludeFromDocs] - public static string PasswordField(Rect position, string password) + public static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.PasswordField(position, password, textField); + EditorGUI.MultiFloatField(position, subLabels, values, 13f); } - public static string PasswordField(Rect position, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + internal static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values, float labelWidth) { - return EditorGUI.PasswordFieldInternal(position, password, style); + int num = values.Length; + float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; + Rect position2 = new Rect(position); + position2.width = num2; + float labelWidth2 = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = 0; + for (int i = 0; i < values.Length; i++) + { + values[i] = EditorGUI.FloatField(position2, subLabels[i], values[i]); + position2.x += num2 + 2f; + } + EditorGUIUtility.labelWidth = labelWidth2; + EditorGUI.indentLevel = indentLevel; } - [ExcludeFromDocs] - public static string PasswordField(Rect position, string label, string password) + public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, GUIContent label) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.PasswordField(position, label, password, textField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + position = EditorGUI.MultiFieldPrefixLabel(position, controlID, label, subLabels.Length); + position.height = 16f; + EditorGUI.MultiPropertyField(position, subLabels, valuesIterator); } - public static string PasswordField(Rect position, string label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator) { - return EditorGUI.PasswordField(position, EditorGUIUtility.TempContent(label), password, style); + EditorGUI.MultiPropertyField(position, subLabels, valuesIterator, 13f, null); } - [ExcludeFromDocs] - public static string PasswordField(Rect position, GUIContent label, string password) + internal static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, float labelWidth, bool[] disabledMask) { - GUIStyle textField = EditorStyles.textField; - return EditorGUI.PasswordField(position, label, password, textField); + int num = subLabels.Length; + float num2 = (position.width - (float)(num - 1) * 2f) / (float)num; + Rect position2 = new Rect(position); + position2.width = num2; + float labelWidth2 = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUIUtility.labelWidth = labelWidth; + EditorGUI.indentLevel = 0; + for (int i = 0; i < subLabels.Length; i++) + { + if (disabledMask != null) + { + EditorGUI.BeginDisabledGroup(disabledMask[i]); + } + EditorGUI.PropertyField(position2, valuesIterator, subLabels[i]); + if (disabledMask != null) + { + EditorGUI.EndDisabledGroup(); + } + position2.x += num2 + 2f; + valuesIterator.NextVisible(false); + } + EditorGUIUtility.labelWidth = labelWidth2; + EditorGUI.indentLevel = indentLevel; } - public static string PasswordField(Rect position, GUIContent label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) + internal static void PropertiesField(Rect position, GUIContent label, SerializedProperty[] properties, GUIContent[] propertyLabels, float propertyLabelsWidth) { - return EditorGUI.PasswordFieldInternal(position, label, password, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + Rect position2 = EditorGUI.PrefixLabel(position, controlID, label); + position2.height = 16f; + float labelWidth = EditorGUIUtility.labelWidth; + int indentLevel = EditorGUI.indentLevel; + EditorGUIUtility.labelWidth = propertyLabelsWidth; + EditorGUI.indentLevel = 0; + for (int i = 0; i < properties.Length; i++) + { + EditorGUI.PropertyField(position2, properties[i], propertyLabels[i]); + position2.y += 16f; + } + EditorGUI.indentLevel = indentLevel; + EditorGUIUtility.labelWidth = labelWidth; } - [ExcludeFromDocs] - public static float FloatField(Rect position, float value) + internal static int CycleButton(Rect position, int selected, GUIContent[] options, GUIStyle style) { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.FloatField(position, value, numberField); + if (selected >= options.Length || selected < 0) + { + selected = 0; + GUI.changed = true; + } + if (GUI.Button(position, options[selected], style)) + { + selected++; + GUI.changed = true; + if (selected >= options.Length) + { + selected = 0; + } + } + return selected; } - public static float FloatField(Rect position, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + public static Color ColorField(Rect position, Color value) { - return EditorGUI.FloatFieldInternal(position, value, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.IndentedRect(position), controlID, value, true, true); } - [ExcludeFromDocs] - public static float FloatField(Rect position, string label, float value) + internal static Color ColorField(Rect position, Color value, bool showEyedropper, bool showAlpha) { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.FloatField(position, label, value, numberField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(position, controlID, value, showEyedropper, showAlpha); } - public static float FloatField(Rect position, string label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + public static Color ColorField(Rect position, string label, Color value) { - return EditorGUI.FloatField(position, EditorGUIUtility.TempContent(label), value, style); + return EditorGUI.ColorField(position, EditorGUIUtility.TempContent(label), value); } - [ExcludeFromDocs] - public static float FloatField(Rect position, GUIContent label, float value) + public static Color ColorField(Rect position, GUIContent label, Color value) { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.FloatField(position, label, value, numberField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, true, true); } - public static float FloatField(Rect position, GUIContent label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + internal static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha) { - return EditorGUI.FloatFieldInternal(position, label, value, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ColorHash, EditorGUIUtility.native, position); + return EditorGUI.DoColorField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, showEyedropper, showAlpha); } - [ExcludeFromDocs] - public static int IntField(Rect position, int value) - { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.IntField(position, value, numberField); + private static Color DoColorField(Rect position, int id, Color value, bool showEyedropper, bool showAlpha) + { + Event current = Event.current; + GUIStyle colorField = EditorStyles.colorField; + Color result = value; + value = ((!EditorGUI.showMixedValue) ? value : Color.white); + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(id)) + { + Event.current.Use(); + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, showAlpha); + GUIUtility.ExitGUI(); + } + return result; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_47: + if (typeForControl == EventType.ValidateCommand) + { + if (current.commandName == "UndoRedoPerformed" && GUIUtility.keyboardControl == id && ColorPicker.visible) + { + ColorPicker.color = value; + } + return result; + } + if (typeForControl == EventType.ExecuteCommand) + { + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + switch (commandName) + { + case "EyeDropperUpdate": + HandleUtility.Repaint(); + break; + case "EyeDropperClicked": + { + GUI.changed = true; + HandleUtility.Repaint(); + Color lastPickedColor = EyeDropper.GetLastPickedColor(); + lastPickedColor.a = value.a; + EditorGUI.s_ColorPickID = 0; + return lastPickedColor; + } + case "EyeDropperCancelled": + HandleUtility.Repaint(); + EditorGUI.s_ColorPickID = 0; + break; + case "ColorPickerChanged": + GUI.changed = true; + HandleUtility.Repaint(); + return ColorPicker.color; + } + } + return result; + } + if (typeForControl != EventType.MouseDown) + { + return result; + } + if (showEyedropper) + { + position.width -= 20f; + } + if (position.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = id; + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, showAlpha); + GUIUtility.ExitGUI(); + } + if (showEyedropper) + { + position.width += 20f; + if (position.Contains(current.mousePosition)) + { + GUIUtility.keyboardControl = id; + EyeDropper.Start(GUIView.current); + EditorGUI.s_ColorPickID = id; + GUIUtility.ExitGUI(); + } + } + return result; + case EventType.Repaint: + { + Rect position2; + if (showEyedropper) + { + position2 = colorField.padding.Remove(position); + } + else + { + position2 = position; + } + if (showEyedropper && EditorGUI.s_ColorPickID == id) + { + Color pickedColor = EyeDropper.GetPickedColor(); + pickedColor.a = value.a; + EditorGUIUtility.DrawColorSwatch(position2, pickedColor, showAlpha); + } + else + { + EditorGUIUtility.DrawColorSwatch(position2, value, showAlpha); + } + if (showEyedropper) + { + colorField.Draw(position, GUIContent.none, id); + } + else + { + EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); + } + return result; + } + } + goto IL_47; } - public static int IntField(Rect position, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + internal static Color ColorSelector(Rect activatorRect, Rect renderRect, int id, Color value) { - return EditorGUI.IntFieldInternal(position, value, style); + Event current = Event.current; + Color result = value; + value = ((!EditorGUI.showMixedValue) ? value : Color.white); + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(id)) + { + current.Use(); + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, false); + GUIUtility.ExitGUI(); + } + return result; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_3F: + if (typeForControl == EventType.ValidateCommand) + { + if (current.commandName == "UndoRedoPerformed" && GUIUtility.keyboardControl == id && ColorPicker.visible) + { + ColorPicker.color = value; + } + return result; + } + if (typeForControl == EventType.ExecuteCommand) + { + if (GUIUtility.keyboardControl == id) + { + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUI.<>f__switch$map3 == null) + { + EditorGUI.<>f__switch$map3 = new Dictionary(1) + { + + { + "ColorPickerChanged", + 0 + } + }; + } + int num; + if (EditorGUI.<>f__switch$map3.TryGetValue(commandName, out num)) + { + if (num == 0) + { + current.Use(); + GUI.changed = true; + HandleUtility.Repaint(); + return ColorPicker.color; + } + } + } + } + return result; + } + if (typeForControl != EventType.MouseDown) + { + return result; + } + if (activatorRect.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.keyboardControl = id; + EditorGUI.showMixedValue = false; + ColorPicker.Show(GUIView.current, value, false); + GUIUtility.ExitGUI(); + } + return result; + case EventType.Repaint: + if (renderRect.height > 0f && renderRect.width > 0f) + { + EditorGUI.DrawRect(renderRect, value); + } + return result; + } + goto IL_3F; } - [ExcludeFromDocs] - public static int IntField(Rect position, string label, int value) + public static AnimationCurve CurveField(Rect position, AnimationCurve value) { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.IntField(position, label, value, numberField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, EditorGUI.kCurveColor, default(Rect), null); } - public static int IntField(Rect position, string label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value) { - return EditorGUI.IntField(position, EditorGUIUtility.TempContent(label), value, style); + return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value); } - [ExcludeFromDocs] - public static int IntField(Rect position, GUIContent label, int value) + public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value) { - GUIStyle numberField = EditorStyles.numberField; - return EditorGUI.IntField(position, label, value, numberField); + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, EditorGUI.kCurveColor, default(Rect), null); } - public static int IntField(Rect position, GUIContent label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) + public static AnimationCurve CurveField(Rect position, AnimationCurve value, Color color, Rect ranges) { - return EditorGUI.IntFieldInternal(position, label, value, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.IndentedRect(position), controlID, value, color, ranges, null); } - [ExcludeFromDocs] - public static int Popup(Rect position, int selectedIndex, string[] displayedOptions) + public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value, Color color, Rect ranges) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); + return EditorGUI.CurveField(position, EditorGUIUtility.TempContent(label), value, color, ranges); } - public static int Popup(Rect position, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value, Color color, Rect ranges) { - return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + return EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, value, color, ranges, null); } - [ExcludeFromDocs] - public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions) + public static void CurveField(Rect position, SerializedProperty value, Color color, Rect ranges) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.Popup(position, selectedIndex, displayedOptions, popup); + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoCurveField(position, controlID, null, color, ranges, value); } - public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + private static void SetCurveEditorWindowCurve(AnimationCurve value, SerializedProperty property, Color color) { - return EditorGUI.DoPopup(EditorGUI.IndentedRect(position), GUIUtility.GetControlID(EditorGUI.s_PopupHash, EditorGUIUtility.native, position), selectedIndex, displayedOptions, style); + if (property != null) + { + CurveEditorWindow.curve = ((!property.hasMultipleDifferentValues) ? property.animationCurveValue : new AnimationCurve()); + } + else + { + CurveEditorWindow.curve = value; + } + CurveEditorWindow.color = color; } - [ExcludeFromDocs] - public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions) + private static AnimationCurve DoCurveField(Rect position, int id, AnimationCurve value, Color color, Rect ranges, SerializedProperty property) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + Event current = Event.current; + position.width = Mathf.Max(position.width, 2f); + position.height = Mathf.Max(position.height, 2f); + if (GUIUtility.keyboardControl == id && Event.current.type != EventType.Layout) + { + if (EditorGUI.s_CurveID != id) + { + EditorGUI.s_CurveID = id; + if (CurveEditorWindow.visible) + { + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + } + } + else + { + if (CurveEditorWindow.visible && Event.current.type == EventType.Repaint) + { + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + CurveEditorWindow.instance.Repaint(); + } + } + } + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (current.MainActionKeyForControl(id)) + { + EditorGUI.s_CurveID = id; + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + current.Use(); + GUIUtility.ExitGUI(); + } + return value; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_D3: + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(current.mousePosition)) + { + EditorGUI.s_CurveID = id; + GUIUtility.keyboardControl = id; + EditorGUI.SetCurveEditorWindowCurve(value, property, color); + EditorGUI.ShowCurvePopup(GUIView.current, ranges); + current.Use(); + GUIUtility.ExitGUI(); + } + return value; + } + if (typeForControl != EventType.ExecuteCommand) + { + return value; + } + if (EditorGUI.s_CurveID == id) + { + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUI.<>f__switch$map4 == null) + { + EditorGUI.<>f__switch$map4 = new Dictionary(1) + { + + { + "CurveChanged", + 0 + } + }; + } + int num; + if (EditorGUI.<>f__switch$map4.TryGetValue(commandName, out num)) + { + if (num == 0) + { + GUI.changed = true; + AnimationCurvePreviewCache.ClearCache(); + HandleUtility.Repaint(); + if (property != null) + { + property.animationCurveValue = CurveEditorWindow.curve; + if (property.hasMultipleDifferentValues) + { + Debug.LogError("AnimationCurve SerializedProperty hasMultipleDifferentValues is true after writing."); + } + } + return CurveEditorWindow.curve; + } + } + } + } + return value; + case EventType.Repaint: + { + Rect position2 = position; + position2.y += 1f; + position2.height -= 1f; + if (ranges != default(Rect)) + { + EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor, ranges); + } + else + { + EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, EditorGUI.kCurveBGColor); + } + EditorStyles.colorPickerBox.Draw(position2, GUIContent.none, id, false); + return value; + } + } + goto IL_D3; } - public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + private static void ShowCurvePopup(GUIView viewToUpdate, Rect ranges) { - return EditorGUI.PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); + CurveEditorSettings curveEditorSettings = new CurveEditorSettings(); + if (ranges.width > 0f && ranges.height > 0f && ranges.width != float.PositiveInfinity && ranges.height != float.PositiveInfinity) + { + curveEditorSettings.hRangeMin = ranges.xMin; + curveEditorSettings.hRangeMax = ranges.xMax; + curveEditorSettings.vRangeMin = ranges.yMin; + curveEditorSettings.vRangeMax = ranges.yMax; + } + CurveEditorWindow.instance.Show(GUIView.current, curveEditorSettings); } - [ExcludeFromDocs] - public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions) + private static bool ValidTargetForIconSelection(UnityEngine.Object[] targets) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.Popup(position, label, selectedIndex, displayedOptions, popup); + return (targets[0] as MonoScript || targets[0] as GameObject) && targets.Length == 1; } - public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void ObjectIconDropDown(Rect position, UnityEngine.Object[] targets, bool showLabelIcons, Texture2D nullIcon, SerializedProperty iconProperty) { - return EditorGUI.PopupInternal(position, label, selectedIndex, displayedOptions, style); + if (EditorGUI.s_IconTextureInactive == null) + { + EditorGUI.s_IconTextureInactive = (Material)EditorGUIUtility.LoadRequired("Inspectors/InactiveGUI.mat"); + } + if (Event.current.type == EventType.Repaint) + { + Texture2D texture2D = null; + if (!iconProperty.hasMultipleDifferentValues) + { + texture2D = AssetPreview.GetMiniThumbnail(targets[0]); + } + if (texture2D == null) + { + texture2D = nullIcon; + } + Vector2 vector = new Vector2(position.width, position.height); + if (texture2D) + { + vector.x = Mathf.Min((float)texture2D.width, vector.x); + vector.y = Mathf.Min((float)texture2D.height, vector.y); + } + Rect rect = new Rect(position.x + position.width / 2f - vector.x / 2f, position.y + position.height / 2f - vector.y / 2f, vector.x, vector.y); + GameObject gameObject = targets[0] as GameObject; + bool flag = gameObject && !EditorUtility.IsPersistent(targets[0]) && (!gameObject.activeSelf || !gameObject.activeInHierarchy); + if (flag) + { + Graphics.DrawTexture(rect, texture2D, new Rect(0f, 0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 1f), EditorGUI.s_IconTextureInactive); + } + else + { + GUI.DrawTexture(rect, texture2D); + } + if (EditorGUI.ValidTargetForIconSelection(targets)) + { + if (EditorGUI.s_IconDropDown == null) + { + EditorGUI.s_IconDropDown = EditorGUIUtility.IconContent("Icon Dropdown"); + } + GUIStyle.none.Draw(new Rect(Mathf.Max(position.x + 2f, rect.x - 6f), rect.yMax - rect.height * 0.2f, 13f, 8f), EditorGUI.s_IconDropDown, false, false, false, false); + } + } + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none) && EditorGUI.ValidTargetForIconSelection(targets) && IconSelector.ShowAtPosition(targets[0], position, showLabelIcons)) + { + GUIUtility.ExitGUI(); + } } - [ExcludeFromDocs] - public static Enum EnumPopup(Rect position, Enum selected) + public static void InspectorTitlebar(Rect position, UnityEngine.Object[] targetObjs) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumPopup(position, selected, popup); + GUIStyle none = GUIStyle.none; + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + EditorGUI.DoInspectorTitlebar(position, controlID, true, targetObjs, none); } - public static Enum EnumPopup(Rect position, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object targetObj) { - return EditorGUI.EnumPopup(position, GUIContent.none, selected, style); + return EditorGUI.InspectorTitlebar(position, foldout, new UnityEngine.Object[] + { + targetObj + }); } - [ExcludeFromDocs] - public static Enum EnumPopup(Rect position, string label, Enum selected) + public static bool InspectorTitlebar(Rect position, bool foldout, UnityEngine.Object[] targetObjs) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumPopup(position, label, selected, popup); + GUIStyle inspectorTitlebar = EditorStyles.inspectorTitlebar; + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + EditorGUI.DoInspectorTitlebar(position, controlID, foldout, targetObjs, inspectorTitlebar); + return EditorGUI.DoObjectFoldout(controlID, position, targetObjs, foldout); } - public static Enum EnumPopup(Rect position, string label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void DoInspectorTitlebar(Rect position, int id, bool foldout, UnityEngine.Object[] targetObjs, GUIStyle baseStyle) { - return EditorGUI.EnumPopup(position, EditorGUIUtility.TempContent(label), selected, style); + GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText; + Rect rect = new Rect(position.x + (float)baseStyle.padding.left, position.y + (float)baseStyle.padding.top, 16f, 16f); + Rect rect2 = new Rect(position.xMax - (float)baseStyle.padding.right - 2f - 16f, rect.y, 16f, 16f); + Rect position2 = new Rect(rect.xMax + 2f + 2f + 16f, rect.y, 100f, rect.height); + position2.xMax = rect2.xMin - 2f; + int num = -1; + for (int i = 0; i < targetObjs.Length; i++) + { + UnityEngine.Object target = targetObjs[i]; + int objectEnabled = EditorUtility.GetObjectEnabled(target); + if (num == -1) + { + num = objectEnabled; + } + else + { + if (num != objectEnabled) + { + num = -2; + } + } + } + if (num != -1) + { + bool flag = AnimationMode.IsPropertyAnimated(targetObjs[0], "m_Enabled"); + bool flag2 = num != 0; + EditorGUI.showMixedValue = (num == -2); + Rect position3 = rect; + position3.x = rect.xMax + 2f; + EditorGUI.BeginChangeCheck(); + Color color = GUI.color; + if (flag) + { + GUI.color = AnimationMode.animatedPropertyColor; + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + flag2 = EditorGUIInternal.DoToggleForward(position3, controlID, flag2, GUIContent.none, EditorStyles.toggle); + if (flag) + { + GUI.color = color; + } + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObjects(targetObjs, ((!flag2) ? "Disable" : "Enable") + " Component" + ((targetObjs.Length <= 1) ? string.Empty : "s")); + for (int j = 0; j < targetObjs.Length; j++) + { + UnityEngine.Object target2 = targetObjs[j]; + EditorUtility.SetObjectEnabled(target2, flag2); + } + } + EditorGUI.showMixedValue = false; + } + Rect position4 = rect2; + position4.x -= 18f; + if (EditorGUI.HelpIconButton(position4, targetObjs[0])) + { + position2.xMax = position4.xMin - 2f; + } + Event current = Event.current; + Texture2D i2 = null; + if (current.type == EventType.Repaint) + { + i2 = AssetPreview.GetMiniThumbnail(targetObjs[0]); + } + if (EditorGUI.ButtonMouseDown(rect, EditorGUIUtility.TempContent(i2), FocusType.Passive, GUIStyle.none) && targetObjs[0] as MonoScript != null && IconSelector.ShowAtPosition(targetObjs[0], rect, true)) + { + GUIUtility.ExitGUI(); + } + EventType type = current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + baseStyle.Draw(position, GUIContent.none, id, foldout); + position = baseStyle.padding.Remove(position); + inspectorTitlebarText.Draw(position2, EditorGUIUtility.TempContent(ObjectNames.GetInspectorTitle(targetObjs[0])), id, foldout); + inspectorTitlebarText.Draw(rect2, EditorGUI.GUIContents.titleSettingsIcon, id, foldout); + } + } + else + { + if (rect2.Contains(current.mousePosition)) + { + EditorUtility.DisplayObjectContextMenu(rect2, targetObjs, 0); + current.Use(); + } + } } - [ExcludeFromDocs] - public static Enum EnumPopup(Rect position, GUIContent label, Enum selected) + internal static bool ToggleTitlebar(Rect position, GUIContent label, bool foldout, ref bool toggleValue) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumPopup(position, label, selected, popup); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + GUIStyle inspectorTitlebar = EditorStyles.inspectorTitlebar; + GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText; + Rect position2 = new Rect(position.x + (float)inspectorTitlebar.padding.left, position.y + (float)inspectorTitlebar.padding.top, 16f, 16f); + Rect position3 = new Rect(position2.xMax + 2f, position2.y, 200f, 16f); + int controlID2 = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + toggleValue = EditorGUIInternal.DoToggleForward(position2, controlID2, toggleValue, GUIContent.none, EditorStyles.toggle); + if (Event.current.type == EventType.Repaint) + { + inspectorTitlebar.Draw(position, GUIContent.none, controlID, foldout); + position = inspectorTitlebar.padding.Remove(position); + inspectorTitlebarText.Draw(position3, label, controlID, foldout); + } + return EditorGUIInternal.DoToggleForward(EditorGUI.IndentedRect(position), controlID, foldout, GUIContent.none, GUIStyle.none); } - public static Enum EnumPopup(Rect position, GUIContent label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static bool FoldoutTitlebar(Rect position, GUIContent label, bool foldout) { - return EditorGUI.EnumPopupInternal(position, label, selected, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TitlebarHash, EditorGUIUtility.native, position); + if (Event.current.type == EventType.Repaint) + { + GUIStyle inspectorTitlebar = EditorStyles.inspectorTitlebar; + GUIStyle inspectorTitlebarText = EditorStyles.inspectorTitlebarText; + Rect position2 = new Rect(position.x + (float)inspectorTitlebar.padding.left + 2f + 16f, position.y + (float)inspectorTitlebar.padding.top, 200f, 16f); + inspectorTitlebar.Draw(position, GUIContent.none, controlID, foldout); + position = inspectorTitlebar.padding.Remove(position); + inspectorTitlebarText.Draw(position2, EditorGUIUtility.TempContent(label.text), controlID, foldout); + } + return EditorGUIInternal.DoToggleForward(EditorGUI.IndentedRect(position), controlID, foldout, GUIContent.none, GUIStyle.none); } - [ExcludeFromDocs] - public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues) + internal static bool HelpIconButton(Rect position, UnityEngine.Object obj) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); + bool flag = Unsupported.IsDeveloperBuild(); + bool defaultToMonoBehaviour = !flag || obj.GetType().Assembly.ToString().StartsWith("Assembly-"); + bool flag2 = Help.HasHelpForObject(obj, defaultToMonoBehaviour); + if (flag2 || flag) + { + Color color = GUI.color; + GUIContent gUIContent = new GUIContent(EditorGUI.GUIContents.helpIcon); + string niceHelpNameForObject = Help.GetNiceHelpNameForObject(obj, defaultToMonoBehaviour); + if (flag && !flag2) + { + GUI.color = Color.yellow; + bool flag3 = obj is MonoBehaviour; + string arg = ((!flag3) ? "sealed partial class-" : "script-") + niceHelpNameForObject; + gUIContent.tooltip = string.Format("Could not find Reference page for {0} ({1}).\nDocs for this object is missing or all docs are missing.\nThis warning only shows up in development builds.", niceHelpNameForObject, arg); + } + else + { + gUIContent.tooltip = string.Format("Open Reference for {0}.", niceHelpNameForObject); + } + if (GUI.Button(position, gUIContent, EditorStyles.inspectorTitlebarText)) + { + Help.ShowHelpForObject(obj); + } + GUI.color = color; + return true; + } + return false; } - public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static bool FoldoutInternal(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, GUIStyle style) { - return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); + Rect rect = position; + if (EditorGUIUtility.hierarchyMode) + { + int num = EditorStyles.foldout.padding.left - EditorStyles.label.padding.left; + position.xMin -= (float)num; + } + int controlID = GUIUtility.GetControlID(EditorGUI.s_FoldoutHash, EditorGUIUtility.native, position); + EventType eventType = Event.current.type; + if (!GUI.enabled && GUIClip.enabled && (Event.current.rawType == EventType.MouseDown || Event.current.rawType == EventType.MouseDrag || Event.current.rawType == EventType.MouseUp)) + { + eventType = Event.current.rawType; + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition) && Event.current.button == 0) + { + int num2 = controlID; + GUIUtility.hotControl = num2; + GUIUtility.keyboardControl = num2; + Event.current.Use(); + } + return foldout; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + Rect rect2 = position; + if (!toggleOnLabelClick) + { + rect2.width = (float)style.padding.left; + rect2.x += EditorGUI.indent; + } + if (rect2.Contains(Event.current.mousePosition)) + { + GUI.changed = true; + return !foldout; + } + } + return foldout; + case EventType.MouseMove: + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Layout: + IL_D8: + if (eventType2 != EventType.DragExited) + { + return foldout; + } + if (EditorGUI.s_DragUpdatedOverID == controlID) + { + EditorGUI.s_DragUpdatedOverID = 0; + Event.current.Use(); + } + return foldout; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Event.current.Use(); + } + return foldout; + case EventType.KeyDown: + if (GUIUtility.keyboardControl == controlID) + { + KeyCode keyCode = Event.current.keyCode; + if ((keyCode == KeyCode.LeftArrow && foldout) || (keyCode == KeyCode.RightArrow && !foldout)) + { + foldout = !foldout; + GUI.changed = true; + Event.current.Use(); + } + } + return foldout; + case EventType.Repaint: + { + EditorStyles.foldoutSelected.Draw(position, GUIContent.none, controlID, EditorGUI.s_DragUpdatedOverID == controlID); + Rect position2 = new Rect(position.x + EditorGUI.indent, position.y, EditorGUIUtility.labelWidth - EditorGUI.indent, position.height); + if (EditorGUI.showMixedValue && !foldout) + { + style.Draw(position2, content, controlID, foldout); + EditorGUI.BeginHandleMixedValueContentColor(); + Rect position3 = rect; + position3.xMin += EditorGUIUtility.labelWidth; + EditorStyles.label.Draw(position3, EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position2, content, controlID, foldout); + } + return foldout; + } + case EventType.DragUpdated: + if (EditorGUI.s_DragUpdatedOverID == controlID) + { + if (position.Contains(Event.current.mousePosition)) + { + if ((double)Time.realtimeSinceStartup > EditorGUI.s_FoldoutDestTime) + { + foldout = true; + Event.current.Use(); + } + } + else + { + EditorGUI.s_DragUpdatedOverID = 0; + } + } + else + { + if (position.Contains(Event.current.mousePosition)) + { + EditorGUI.s_DragUpdatedOverID = controlID; + EditorGUI.s_FoldoutDestTime = (double)Time.realtimeSinceStartup + 0.7; + Event.current.Use(); + } + } + return foldout; + } + goto IL_D8; } - [ExcludeFromDocs] - public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) + public static void ProgressBar(Rect position, float value, string text) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.IntPopup(position, selectedValue, displayedOptions, optionValues, popup); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ProgressBarHash, EditorGUIUtility.native, position); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(controlID); + if (typeForControl == EventType.Repaint) + { + EditorStyles.progressBarBack.Draw(position, false, false, false, false); + Rect position2 = new Rect(position); + value = Mathf.Clamp01(value); + position2.width *= value; + EditorStyles.progressBarBar.Draw(position2, false, false, false, false); + EditorStyles.progressBarText.Draw(position, text, false, false, false, false); + } } - public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + public static void HelpBox(Rect position, string message, MessageType type) { - return EditorGUI.IntPopup(position, GUIContent.none, selectedValue, displayedOptions, optionValues, style); + GUI.Label(position, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type)), EditorStyles.helpBox); } - [ExcludeFromDocs] - public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) + internal static bool LabelHasContent(GUIContent label) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); + return label == null || label.text != string.Empty || label.image != null; } - public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + private static void DrawTextDebugHelpers(Rect labelPosition) { - return EditorGUI.IntPopupInternal(position, label, selectedValue, displayedOptions, optionValues, style); + Color color = GUI.color; + GUI.color = Color.white; + GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.y, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); + GUI.color = Color.cyan; + GUI.DrawTexture(new Rect(labelPosition.x, labelPosition.yMax - 4f, labelPosition.width, 4f), EditorGUIUtility.whiteTexture); + GUI.color = color; } - [ExcludeFromDocs] - public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues) + internal static void HandlePrefixLabelInternal(Rect totalPosition, Rect labelPosition, GUIContent label, int id, GUIStyle style) { - GUIContent label = null; - EditorGUI.IntPopup(position, property, displayedOptions, optionValues, label); + if (id == 0 && label != null) + { + EditorGUI.s_PrefixLabel.text = label.text; + EditorGUI.s_PrefixLabel.image = label.image; + EditorGUI.s_PrefixLabel.tooltip = label.tooltip; + EditorGUI.s_PrefixTotalRect = totalPosition; + EditorGUI.s_PrefixRect = labelPosition; + EditorGUI.s_PrefixStyle = style; + return; + } + if (Highlighter.searchMode == HighlightSearchMode.PrefixLabel || Highlighter.searchMode == HighlightSearchMode.Auto) + { + Highlighter.Handle(totalPosition, label.text); + } + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + labelPosition.width += 1f; + style.DrawPrefixLabel(labelPosition, label, id); + } + } + else + { + if (Event.current.button == 0 && labelPosition.Contains(Event.current.mousePosition)) + { + if (EditorGUIUtility.CanHaveKeyboardFocus(id)) + { + GUIUtility.keyboardControl = id; + } + EditorGUIUtility.editingTextField = false; + HandleUtility.Repaint(); + } + } + EditorGUI.s_PrefixLabel.text = null; } - public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("null")] GUIContent label) + public static Rect PrefixLabel(Rect totalPosition, GUIContent label) { - EditorGUI.IntPopupInternal(position, property, displayedOptions, optionValues, label); + return EditorGUI.PrefixLabel(totalPosition, 0, label, EditorStyles.label); } - [ExcludeFromDocs] - public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues) + public static Rect PrefixLabel(Rect totalPosition, GUIContent label, GUIStyle style) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.IntPopup(position, label, selectedValue, displayedOptions, optionValues, popup); + return EditorGUI.PrefixLabel(totalPosition, 0, label, style); } - public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) + public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label) { - return EditorGUI.IntPopupInternal(position, EditorGUIUtility.TempContent(label), selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); + return EditorGUI.PrefixLabel(totalPosition, id, label, EditorStyles.label); } - [ExcludeFromDocs] - public static string TagField(Rect position, string tag) + public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label, GUIStyle style) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.TagField(position, tag, popup); + if (!EditorGUI.LabelHasContent(label)) + { + return EditorGUI.IndentedRect(totalPosition); + } + Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); + Rect result = new Rect(totalPosition.x + EditorGUIUtility.labelWidth, totalPosition.y, totalPosition.width - EditorGUIUtility.labelWidth, totalPosition.height); + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, style); + return result; } - public static string TagField(Rect position, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static Rect MultiFieldPrefixLabel(Rect totalPosition, int id, GUIContent label, int columns) { - return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(string.Empty), tag, style); + if (!EditorGUI.LabelHasContent(label)) + { + return EditorGUI.IndentedRect(totalPosition); + } + if (EditorGUIUtility.wideMode) + { + Rect labelPosition = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, EditorGUIUtility.labelWidth - EditorGUI.indent, 16f); + Rect result = totalPosition; + result.xMin += EditorGUIUtility.labelWidth; + if (columns > 1) + { + labelPosition.width -= 1f; + result.xMin -= 1f; + } + if (columns == 2) + { + float num = (result.width - 4f) / 3f; + result.xMax -= num + 2f; + } + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id); + return result; + } + Rect labelPosition2 = new Rect(totalPosition.x + EditorGUI.indent, totalPosition.y, totalPosition.width - EditorGUI.indent, 16f); + Rect result2 = totalPosition; + result2.xMin += EditorGUI.indent + 15f; + result2.yMin += 16f; + EditorGUI.HandlePrefixLabel(totalPosition, labelPosition2, label, id); + return result2; } - [ExcludeFromDocs] - public static string TagField(Rect position, string label, string tag) + public static GUIContent BeginProperty(Rect totalPosition, GUIContent label, SerializedProperty property) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.TagField(position, label, tag, popup); + Highlighter.HighlightIdentifier(totalPosition, property.propertyPath); + if (EditorGUI.s_PendingPropertyKeyboardHandling != null) + { + EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); + } + EditorGUI.s_PendingPropertyKeyboardHandling = property; + if (property == null) + { + string message = ((label != null) ? (label.text + ": ") : string.Empty) + "SerializedProperty is null"; + EditorGUI.HelpBox(totalPosition, "null", MessageType.Error); + throw new NullReferenceException(message); + } + EditorGUI.s_PropertyFieldTempContent.text = ((label != null) ? label.text : property.displayName); + EditorGUI.s_PropertyFieldTempContent.tooltip = ((!EditorGUI.isCollectingTooltips) ? null : ((label != null) ? label.tooltip : property.tooltip)); + string tooltip = ScriptAttributeUtility.GetHandler(property).tooltip; + if (tooltip != null) + { + EditorGUI.s_PropertyFieldTempContent.tooltip = tooltip; + } + EditorGUI.s_PropertyFieldTempContent.image = ((label != null) ? label.image : null); + if (Event.current.alt && property.serializedObject.inspectorMode != InspectorMode.Normal) + { + GUIContent arg_12F_0 = EditorGUI.s_PropertyFieldTempContent; + string propertyPath = property.propertyPath; + EditorGUI.s_PropertyFieldTempContent.text = propertyPath; + arg_12F_0.tooltip = propertyPath; + } + bool boldDefaultFont = EditorGUIUtility.GetBoldDefaultFont(); + if (property.serializedObject.targetObjects.Length == 1 && property.isInstantiatedPrefab) + { + EditorGUIUtility.SetBoldDefaultFont(property.prefabOverride); + } + EditorGUI.s_PropertyStack.Push(new PropertyGUIData(property, totalPosition, boldDefaultFont, GUI.enabled, GUI.color)); + EditorGUI.showMixedValue = property.hasMultipleDifferentValues; + if (property.isAnimated) + { + Color animatedPropertyColor = AnimationMode.animatedPropertyColor; + animatedPropertyColor.a *= GUI.color.a; + GUI.color = animatedPropertyColor; + } + GUI.enabled &= property.editable; + return EditorGUI.s_PropertyFieldTempContent; } - public static string TagField(Rect position, string label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + public static void EndProperty() { - return EditorGUI.TagFieldInternal(position, EditorGUIUtility.TempContent(label), tag, style); + EditorGUI.showMixedValue = false; + PropertyGUIData propertyGUIData = EditorGUI.s_PropertyStack.Pop(); + if (Event.current.type == EventType.ContextClick && propertyGUIData.totalPosition.Contains(Event.current.mousePosition)) + { + EditorGUI.DoPropertyContextMenu(propertyGUIData.property); + } + EditorGUIUtility.SetBoldDefaultFont(propertyGUIData.wasBoldDefaultFont); + GUI.enabled = propertyGUIData.wasEnabled; + GUI.color = propertyGUIData.color; + if (EditorGUI.s_PendingPropertyKeyboardHandling != null) + { + EditorGUI.DoPropertyFieldKeyboardHandling(EditorGUI.s_PendingPropertyKeyboardHandling); + } + if (EditorGUI.s_PendingPropertyDelete != null && EditorGUI.s_PropertyStack.Count == 0) + { + if (EditorGUI.s_PendingPropertyDelete.propertyPath == propertyGUIData.property.propertyPath) + { + propertyGUIData.property.DeleteCommand(); + } + else + { + EditorGUI.s_PendingPropertyDelete.DeleteCommand(); + } + EditorGUI.s_PendingPropertyDelete = null; + } } - [ExcludeFromDocs] - public static string TagField(Rect position, GUIContent label, string tag) + private static void DoPropertyFieldKeyboardHandling(SerializedProperty property) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.TagField(position, label, tag, popup); + if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) + { + if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && (Event.current.commandName == "Delete" || Event.current.commandName == "SoftDelete")) + { + if (Event.current.type == EventType.ExecuteCommand) + { + EditorGUI.s_PendingPropertyDelete = property.Copy(); + } + Event.current.Use(); + } + if (GUIUtility.keyboardControl == EditorGUIUtility.s_LastControlID && Event.current.commandName == "Duplicate") + { + if (Event.current.type == EventType.ExecuteCommand) + { + property.DuplicateCommand(); + } + Event.current.Use(); + } + } + EditorGUI.s_PendingPropertyKeyboardHandling = null; } - public static string TagField(Rect position, GUIContent label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label) { - return EditorGUI.TagFieldInternal(position, label, tag, style); + EditorGUI.LayerMaskField(position, property, label, EditorStyles.layerMaskField); } - [ExcludeFromDocs] - public static int LayerField(Rect position, int layer) + internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label, GUIStyle style) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.LayerField(position, layer, popup); + int controlID = GUIUtility.GetControlID(EditorGUI.s_LayerMaskField, EditorGUIUtility.native, position); + position = EditorGUI.PrefixLabel(position, controlID, label); + Event current = Event.current; + if (current.type == EventType.Repaint) + { + if (EditorGUI.showMixedValue) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUI.s_MixedValueContent, controlID, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position, EditorGUIUtility.TempContent(property.layerMaskStringValue), controlID, false); + } + } + else + { + if ((current.type == EventType.MouseDown && position.Contains(current.mousePosition)) || current.MainActionKeyForControl(controlID)) + { + SerializedProperty userData = property.serializedObject.FindProperty(property.propertyPath); + EditorUtility.DisplayCustomMenu(position, property.GetLayerMaskNames(), (!property.hasMultipleDifferentValues) ? property.GetLayerMaskSelectedIndex() : new int[0], new EditorUtility.SelectMenuItemFunction(EditorGUI.SetLayerMaskValueDelegate), userData); + Event.current.Use(); + } + } } - public static int LayerField(Rect position, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void SetLayerMaskValueDelegate(object userData, string[] options, int selected) { - return EditorGUI.LayerFieldInternal(position, GUIContent.none, layer, style); + SerializedProperty serializedProperty = (SerializedProperty)userData; + serializedProperty.ToggleLayerMaskAtIndex(selected); + serializedProperty.serializedObject.ApplyModifiedProperties(); } - [ExcludeFromDocs] - public static int LayerField(Rect position, string label, int layer) + internal static void ShowRepaints() { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.LayerField(position, label, layer, popup); + if (Unsupported.IsDeveloperBuild()) + { + Color backgroundColor = GUI.backgroundColor; + GUI.backgroundColor = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); + GUI.Label(new Rect(0f, 0f, 10f, 10f), string.Empty, GUI.skin.button); + GUI.backgroundColor = backgroundColor; + } } - public static int LayerField(Rect position, string label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color) { - return EditorGUI.LayerFieldInternal(position, EditorGUIUtility.TempContent(label), layer, style); + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.s_Texture) + { + EditorGUI.s_Texture = new Texture2D(1, thickness + 2); + EditorGUI.s_Texture.hideFlags = HideFlags.HideAndDontSave; + } + if (thickness != EditorGUI.s_LastThickness) + { + EditorGUI.s_Texture.Resize(1, thickness + 2, TextureFormat.ARGB32, false); + Color[] array = new Color[thickness + 2]; + for (int i = 1; i <= thickness; i++) + { + array[i] = new Color(1f, 1f, 1f, 1f); + } + array[0] = (array[thickness + 1] = new Color(1f, 1f, 1f, 0f)); + EditorGUI.s_Texture.SetPixels(array); + EditorGUI.s_Texture.Apply(); + EditorGUI.s_LastThickness = thickness; + } + EditorGUI.DrawBezier(from, to, fromTangent, toTangent, thickness, color, EditorGUI.s_Texture); } - [ExcludeFromDocs] - public static int LayerField(Rect position, GUIContent label, int layer) + internal static void DrawBezier(Vector2 from, Vector2 to, Vector2 fromTangent, Vector2 toTangent, int thickness, Color color, Texture tex) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.LayerField(position, label, layer, popup); + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!EditorGUI.tmp) + { + EditorGUI.tmp = new Material("Shader \"GuiShader\" {\n\tProperties {\t\t_Color (\",\", Color) = (1,1,1,1)\n\t\t_Tex (\",\", Any) = \"white\" {}\n\t}\tSubShader { Pass {\n\t\tTags { \"ForceSupported\" = \"True\" } \n\t\tZTest Always Cull Off ZWrite Off Lighting Off Color [_Color]\t\tBlend SrcAlpha OneMinusSrcAlpha\t\tSetTexture [_Tex] { combine texture * previous }\t}}\n}"); + EditorGUI.tmp.hideFlags = HideFlags.HideAndDontSave; + EditorGUI.tmp.shader.hideFlags = HideFlags.HideAndDontSave; + } + EditorGUI.tmp.SetTexture("_Tex", tex); + EditorGUI.tmp.SetColor("_Color", color); + EditorGUI.tmp.SetPass(0); } - public static int LayerField(Rect position, GUIContent label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void DrawTextureAlphaInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) { - return EditorGUI.LayerFieldInternal(position, label, layer, style); + EditorGUI.DrawPreviewTextureInternal(position, image, EditorGUI.alphaMaterial, scaleMode, imageAspect); } - [ExcludeFromDocs] - public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions) + internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); + if (imageAspect == 0f && image == null) + { + Debug.LogError("Please specify an image or a imageAspect"); + return; + } + if (imageAspect == 0f) + { + imageAspect = (float)image.width / (float)image.height; + } + EditorGUI.DrawTransparencyCheckerTexture(position, scaleMode, imageAspect); + if (image != null) + { + Material mat = (QualitySettings.activeColorSpace != ColorSpace.Linear || TextureUtil.GetLinearSampled(image)) ? EditorGUI.transparentMaterial : EditorGUI.gammaCorrectTransparentMaterial; + EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + } } - public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode scaleMode, float imageAspect) { - return EditorGUI.MaskFieldInternal(position, label, mask, displayedOptions, style); + Rect position2 = default(Rect); + Rect rect = default(Rect); + GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref position2, ref rect); + GUI.DrawTextureWithTexCoords(position2, EditorGUI.transparentCheckerTexture, new Rect(position2.width * -0.5f / (float)EditorGUI.transparentCheckerTexture.width, position2.height * -0.5f / (float)EditorGUI.transparentCheckerTexture.height, position2.width / (float)EditorGUI.transparentCheckerTexture.width, position2.height / (float)EditorGUI.transparentCheckerTexture.height), false); } - [ExcludeFromDocs] - public static int MaskField(Rect position, string label, int mask, string[] displayedOptions) + internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.MaskField(position, label, mask, displayedOptions, popup); + if (Event.current.type == EventType.Repaint) + { + if (imageAspect == 0f) + { + imageAspect = (float)image.width / (float)image.height; + } + if (mat == null) + { + mat = EditorGUI.GetMaterialForSpecialTexture(image); + } + if (mat == null) + { + GUI.DrawTexture(position, image, scaleMode, false, imageAspect); + return; + } + Rect screenRect = default(Rect); + Rect sourceRect = default(Rect); + GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref screenRect, ref sourceRect); + Texture2D texture2D = image as Texture2D; + if (texture2D != null && TextureUtil.GetUsageMode(image) == TextureUsageMode.AlwaysPadded) + { + sourceRect.width *= (float)texture2D.width / (float)TextureUtil.GetGLWidth(texture2D); + sourceRect.height *= (float)texture2D.height / (float)TextureUtil.GetGLHeight(texture2D); + } + Graphics.DrawTexture(screenRect, image, sourceRect, 0, 0, 0, 0, GUI.color, mat); + } } - public static int MaskField(Rect position, string label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static Material GetMaterialForSpecialTexture(Texture t) { - return EditorGUI.MaskFieldInternal(position, GUIContent.Temp(label), mask, displayedOptions, style); + if (!t) + { + return null; + } + TextureUsageMode usageMode = TextureUtil.GetUsageMode(t); + if (usageMode == TextureUsageMode.LightmapRGBM || usageMode == TextureUsageMode.RGBMEncoded) + { + return EditorGUI.lightmapRGBMMaterial; + } + if (usageMode == TextureUsageMode.LightmapDoubleLDR) + { + return EditorGUI.lightmapDoubleLDRMaterial; + } + if (usageMode == TextureUsageMode.NormalmapPlain || usageMode == TextureUsageMode.NormalmapDXT5nm) + { + return EditorGUI.normalmapMaterial; + } + if (TextureUtil.IsAlphaOnlyTextureFormat(TextureUtil.GetTextureFormat(t))) + { + return EditorGUI.alphaMaterial; + } + if (QualitySettings.activeColorSpace == ColorSpace.Linear && !TextureUtil.GetLinearSampled(t)) + { + return EditorGUI.gammaCorrectMaterial; + } + return null; } - [ExcludeFromDocs] - public static int MaskField(Rect position, int mask, string[] displayedOptions) + private static void SetExpandedRecurse(SerializedProperty property, bool expanded) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.MaskField(position, mask, displayedOptions, popup); + SerializedProperty serializedProperty = property.Copy(); + serializedProperty.isExpanded = expanded; + int depth = serializedProperty.depth; + while (serializedProperty.NextVisible(true) && serializedProperty.depth > depth) + { + if (serializedProperty.hasVisibleChildren) + { + serializedProperty.isExpanded = expanded; + } + } } - public static int MaskField(Rect position, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static float GetSinglePropertyHeight(SerializedProperty property, GUIContent label) { - return EditorGUI.MaskFieldInternal(position, mask, displayedOptions, style); + if (property == null) + { + return 16f; + } + SerializedPropertyType propertyType = property.propertyType; + if (propertyType == SerializedPropertyType.Vector3 || propertyType == SerializedPropertyType.Vector2) + { + return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 16f; + } + if (propertyType == SerializedPropertyType.Rect) + { + return ((EditorGUI.LabelHasContent(label) && !EditorGUIUtility.wideMode) ? 16f : 0f) + 32f; + } + if (propertyType == SerializedPropertyType.Bounds) + { + return (EditorGUI.LabelHasContent(label) ? 16f : 0f) + 32f; + } + return 16f; } - [ExcludeFromDocs] - public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue) + internal static float GetPropertyHeightInternal(SerializedProperty property, GUIContent label, bool includeChildren) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumMaskField(position, label, enumValue, popup); + return ScriptAttributeUtility.GetHandler(property).GetHeight(property, label, includeChildren); } - public static Enum EnumMaskField(Rect position, GUIContent label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static bool HasVisibleChildFields(SerializedProperty property) { - return EditorGUI.EnumMaskFieldInternal(position, label, enumValue, style); + switch (property.propertyType) + { + case SerializedPropertyType.Vector2: + case SerializedPropertyType.Vector3: + case SerializedPropertyType.Rect: + case SerializedPropertyType.Bounds: + return false; + } + return property.hasVisibleChildren; } - [ExcludeFromDocs] - public static Enum EnumMaskField(Rect position, string label, Enum enumValue) + internal static bool PropertyFieldInternal(Rect position, SerializedProperty property, GUIContent label, bool includeChildren) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumMaskField(position, label, enumValue, popup); + return ScriptAttributeUtility.GetHandler(property).OnGUI(position, property, label, includeChildren); } - public static Enum EnumMaskField(Rect position, string label, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static bool DefaultPropertyField(Rect position, SerializedProperty property, GUIContent label) { - return EditorGUI.EnumMaskFieldInternal(position, EditorGUIUtility.TempContent(label), enumValue, style); + label = EditorGUI.BeginProperty(position, label, property); + SerializedPropertyType propertyType = property.propertyType; + bool flag = false; + if (!EditorGUI.HasVisibleChildFields(property)) + { + switch (propertyType) + { + case SerializedPropertyType.Integer: + { + EditorGUI.BeginChangeCheck(); + long longValue = EditorGUI.LongField(position, label, property.longValue); + if (EditorGUI.EndChangeCheck()) + { + property.longValue = longValue; + } + break; + } + case SerializedPropertyType.Boolean: + { + EditorGUI.BeginChangeCheck(); + bool boolValue = EditorGUI.Toggle(position, label, property.boolValue); + if (EditorGUI.EndChangeCheck()) + { + property.boolValue = boolValue; + } + break; + } + case SerializedPropertyType.Float: + { + EditorGUI.BeginChangeCheck(); + bool flag2 = property.type == "float"; + double doubleValue = (!flag2) ? EditorGUI.DoubleField(position, label, property.doubleValue) : ((double)EditorGUI.FloatField(position, label, property.floatValue)); + if (EditorGUI.EndChangeCheck()) + { + property.doubleValue = doubleValue; + } + break; + } + case SerializedPropertyType.String: + { + EditorGUI.BeginChangeCheck(); + string stringValue = EditorGUI.TextField(position, label, property.stringValue); + if (EditorGUI.EndChangeCheck()) + { + property.stringValue = stringValue; + } + break; + } + case SerializedPropertyType.Color: + { + EditorGUI.BeginChangeCheck(); + Color colorValue = EditorGUI.ColorField(position, label, property.colorValue); + if (EditorGUI.EndChangeCheck()) + { + property.colorValue = colorValue; + } + break; + } + case SerializedPropertyType.ObjectReference: + EditorGUI.ObjectFieldInternal(position, property, null, label, EditorStyles.objectField); + break; + case SerializedPropertyType.LayerMask: + EditorGUI.LayerMaskField(position, property, label); + break; + case SerializedPropertyType.Enum: + EditorGUI.Popup(position, property, label); + break; + case SerializedPropertyType.Vector2: + EditorGUI.Vector2Field(position, property, label); + break; + case SerializedPropertyType.Vector3: + EditorGUI.Vector3Field(position, property, label); + break; + case SerializedPropertyType.Vector4: + EditorGUI.Vector4Field(position, property, label); + break; + case SerializedPropertyType.Rect: + EditorGUI.RectField(position, property, label); + break; + case SerializedPropertyType.ArraySize: + { + EditorGUI.BeginChangeCheck(); + int intValue = EditorGUI.ArraySizeField(position, label, property.intValue, EditorStyles.numberField); + if (EditorGUI.EndChangeCheck()) + { + property.intValue = intValue; + } + break; + } + case SerializedPropertyType.Character: + { + char[] value = new char[] + { + (char)property.intValue + }; + bool changed = GUI.changed; + GUI.changed = false; + string text = EditorGUI.TextField(position, label, new string(value)); + if (GUI.changed) + { + if (text.Length == 1) + { + property.intValue = (int)text[0]; + } + else + { + GUI.changed = false; + } + } + GUI.changed |= changed; + break; + } + case SerializedPropertyType.AnimationCurve: + { + int controlID = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoCurveField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, EditorGUI.kCurveColor, default(Rect), property); + break; + } + case SerializedPropertyType.Bounds: + EditorGUI.BoundsField(position, property, label); + break; + case SerializedPropertyType.Gradient: + { + int controlID2 = GUIUtility.GetControlID(EditorGUI.s_CurveHash, EditorGUIUtility.native, position); + EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID2, label), controlID2, null, property); + break; + } + default: + { + int controlID3 = GUIUtility.GetControlID(EditorGUI.s_GenericField, FocusType.Keyboard, position); + EditorGUI.PrefixLabel(position, controlID3, label); + break; + } + } + } + else + { + Event @event = new Event(Event.current); + flag = property.isExpanded; + EditorGUI.BeginDisabledGroup(!property.editable); + GUIStyle style = (DragAndDrop.activeControlID != -10) ? EditorStyles.foldout : EditorStyles.foldoutPreDrop; + bool flag3 = EditorGUI.Foldout(position, flag, EditorGUI.s_PropertyFieldTempContent, true, style); + EditorGUI.EndDisabledGroup(); + if (flag3 != flag) + { + if (Event.current.alt) + { + EditorGUI.SetExpandedRecurse(property, flag3); + } + else + { + property.isExpanded = flag3; + } + } + flag = flag3; + int s_LastControlID = EditorGUIUtility.s_LastControlID; + EventType type = @event.type; + if (type != EventType.DragUpdated && type != EventType.DragPerform) + { + if (type == EventType.DragExited) + { + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + } + } + else + { + if (position.Contains(@event.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object[] array = new UnityEngine.Object[1]; + bool flag4 = false; + UnityEngine.Object[] array2 = objectReferences; + for (int i = 0; i < array2.Length; i++) + { + UnityEngine.Object @object = array2[i]; + array[0] = @object; + UnityEngine.Object object2 = EditorGUI.ValidateObjectFieldAssignment(array, null, property); + if (object2 != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + if (@event.type == EventType.DragPerform) + { + property.AppendFoldoutPPtrValue(object2); + flag4 = true; + DragAndDrop.activeControlID = 0; + } + else + { + DragAndDrop.activeControlID = s_LastControlID; + } + } + } + if (flag4) + { + GUI.changed = true; + DragAndDrop.AcceptDrag(); + } + } + } + } + EditorGUI.EndProperty(); + return flag; } - [ExcludeFromDocs] - public static Enum EnumMaskField(Rect position, Enum enumValue) + internal static void DrawLegend(Rect position, Color color, string label, bool enabled) { - GUIStyle popup = EditorStyles.popup; - return EditorGUI.EnumMaskField(position, enumValue, popup); + position = new Rect(position.x + 2f, position.y + 2f, position.width - 2f, position.height - 2f); + Color backgroundColor = GUI.backgroundColor; + if (enabled) + { + GUI.backgroundColor = color; + } + else + { + GUI.backgroundColor = new Color(0.5f, 0.5f, 0.5f, 0.45f); + } + GUI.Label(position, label, "ProfilerPaneSubLabel"); + GUI.backgroundColor = backgroundColor; } - public static Enum EnumMaskField(Rect position, Enum enumValue, [DefaultValue("EditorStyles.popup")] GUIStyle style) + internal static string TextFieldDropDown(Rect position, string text, string[] dropDownElement) { - return EditorGUI.EnumMaskFieldInternal(position, enumValue, style); + return EditorGUI.TextFieldDropDown(position, GUIContent.none, text, dropDownElement); } - [ExcludeFromDocs] - public static bool Foldout(Rect position, bool foldout, string content) + internal static string TextFieldDropDown(Rect position, GUIContent label, string text, string[] dropDownElement) { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUI.Foldout(position, foldout, content, foldout2); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldDropDownHash, FocusType.Keyboard, position); + return EditorGUI.DoTextFieldDropDown(EditorGUI.PrefixLabel(position, controlID, label), controlID, text, dropDownElement, false); } - public static bool Foldout(Rect position, bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + internal static string DelayedTextFieldDropDown(Rect position, string text, string[] dropDownElement) { - return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), false, style); + return EditorGUI.DelayedTextFieldDropDown(position, GUIContent.none, text, dropDownElement); } - [ExcludeFromDocs] - public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick) + internal static string DelayedTextFieldDropDown(Rect position, GUIContent label, string text, string[] dropDownElement) { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); + int controlID = GUIUtility.GetControlID(EditorGUI.s_TextFieldDropDownHash, FocusType.Keyboard, position); + return EditorGUI.DoTextFieldDropDown(EditorGUI.PrefixLabel(position, controlID, label), controlID, text, dropDownElement, true); } - public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + internal static Gradient GradientField(Rect position, Gradient gradient) { - return EditorGUI.FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), toggleOnLabelClick, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(position, controlID, gradient, null); } - [ExcludeFromDocs] - public static bool Foldout(Rect position, bool foldout, GUIContent content) + internal static Gradient GradientField(string label, Rect position, Gradient gradient) { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUI.Foldout(position, foldout, content, foldout2); + return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, gradient); } - public static bool Foldout(Rect position, bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + internal static Gradient GradientField(GUIContent label, Rect position, Gradient gradient) { - return EditorGUI.FoldoutInternal(position, foldout, content, false, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, gradient, null); } - [ExcludeFromDocs] - public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick) + internal static Gradient GradientField(Rect position, SerializedProperty gradient) { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUI.Foldout(position, foldout, content, toggleOnLabelClick, foldout2); + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(position, controlID, null, gradient); } - public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + internal static Gradient GradientField(string label, Rect position, SerializedProperty property) { - return EditorGUI.FoldoutInternal(position, foldout, content, toggleOnLabelClick, style); + return EditorGUI.GradientField(EditorGUIUtility.TempContent(label), position, property); } - [ExcludeFromDocs] - public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, int id) + internal static Gradient GradientField(GUIContent label, Rect position, SerializedProperty property) { - GUIStyle label2 = EditorStyles.label; - EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); + int controlID = GUIUtility.GetControlID(EditorGUI.s_GradientHash, EditorGUIUtility.native, position); + return EditorGUI.DoGradientField(EditorGUI.PrefixLabel(position, controlID, label), controlID, null, property); } - [ExcludeFromDocs] - public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label) + internal static Gradient DoGradientField(Rect position, int id, Gradient value, SerializedProperty property) { - GUIStyle label2 = EditorStyles.label; - int id = 0; - EditorGUI.HandlePrefixLabel(totalPosition, labelPosition, label, id, label2); + Event current = Event.current; + EventType typeForControl = current.GetTypeForControl(id); + switch (typeForControl) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id && (current.keyCode == KeyCode.Space || current.keyCode == KeyCode.Return || current.keyCode == KeyCode.KeypadEnter)) + { + Event.current.Use(); + Gradient newGradient = (property == null) ? value : property.gradientValue; + GradientPicker.Show(newGradient); + GUIUtility.ExitGUI(); + } + return value; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_28: + if (typeForControl == EventType.MouseDown) + { + if (position.Contains(current.mousePosition)) + { + if (current.button == 0) + { + EditorGUI.s_GradientID = id; + GUIUtility.keyboardControl = id; + Gradient newGradient2 = (property == null) ? value : property.gradientValue; + GradientPicker.Show(newGradient2); + GUIUtility.ExitGUI(); + } + else + { + if (current.button == 1 && property != null) + { + GradientContextMenu.Show(property); + } + } + } + return value; + } + if (typeForControl != EventType.ExecuteCommand) + { + return value; + } + if (EditorGUI.s_GradientID == id) + { + string commandName = current.commandName; + if (commandName != null) + { + if (EditorGUI.<>f__switch$map5 == null) + { + EditorGUI.<>f__switch$map5 = new Dictionary(1) + { + + { + "GradientPickerChanged", + 0 + } + }; + } + int num; + if (EditorGUI.<>f__switch$map5.TryGetValue(commandName, out num)) + { + if (num == 0) + { + GUI.changed = true; + GradientPreviewCache.ClearCache(); + HandleUtility.Repaint(); + if (property != null) + { + property.gradientValue = GradientPicker.gradient; + } + return GradientPicker.gradient; + } + } + } + } + return value; + case EventType.Repaint: + { + Rect position2 = new Rect(position.x + 1f, position.y + 1f, position.width - 2f, position.height - 2f); + if (property != null) + { + GradientEditor.DrawGradientSwatch(position2, property, Color.white); + } + else + { + GradientEditor.DrawGradientSwatch(position2, value, Color.white); + } + EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); + return value; + } + } + goto IL_28; } - public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, [DefaultValue("0")] int id, [DefaultValue("EditorStyles.label")] GUIStyle style) + internal static bool ButtonMouseDown(Rect position, GUIContent content, FocusType focusType, GUIStyle style) { - EditorGUI.HandlePrefixLabelInternal(totalPosition, labelPosition, label, id, style); + int controlID = GUIUtility.GetControlID(EditorGUI.s_ButtonMouseDownHash, focusType, position); + return EditorGUI.ButtonMouseDown(controlID, position, content, style); } - [ExcludeFromDocs] - public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scaleMode) + internal static bool ButtonMouseDown(int id, Rect position, GUIContent content, GUIStyle style) { - float imageAspect = 0f; - EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); + Event current = Event.current; + EventType type = current.type; + switch (type) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id && current.character == ' ') + { + Event.current.Use(); + return true; + } + return false; + case EventType.KeyUp: + case EventType.ScrollWheel: + IL_25: + if (type != EventType.MouseDown) + { + return false; + } + if (position.Contains(current.mousePosition) && current.button == 0) + { + Event.current.Use(); + return true; + } + return false; + case EventType.Repaint: + if (EditorGUI.showMixedValue) + { + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, EditorGUI.s_MixedValueContent, id, false); + EditorGUI.EndHandleMixedValueContentColor(); + } + else + { + style.Draw(position, content, id, false); + } + return false; + } + goto IL_25; } - [ExcludeFromDocs] - public static void DrawTextureAlpha(Rect position, Texture image) + internal static bool IconButton(int id, Rect position, GUIContent content, GUIStyle style) { - float imageAspect = 0f; - ScaleMode scaleMode = ScaleMode.StretchToFill; - EditorGUI.DrawTextureAlpha(position, image, scaleMode, imageAspect); + GUIUtility.CheckOnGUI(); + switch (Event.current.GetTypeForControl(id)) + { + case EventType.MouseDown: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = id; + Event.current.Use(); + return true; + } + return false; + case EventType.MouseUp: + if (GUIUtility.hotControl == id) + { + GUIUtility.hotControl = 0; + Event.current.Use(); + return position.Contains(Event.current.mousePosition); + } + return false; + case EventType.MouseDrag: + if (position.Contains(Event.current.mousePosition)) + { + GUIUtility.hotControl = id; + Event.current.Use(); + return true; + } + break; + case EventType.Repaint: + style.Draw(position, content, id); + break; + } + return false; } - public static void DrawTextureAlpha(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + internal static Vector2 MouseDeltaReader(Rect position, bool activated) { - EditorGUI.DrawTextureAlphaInternal(position, image, scaleMode, imageAspect); + int controlID = GUIUtility.GetControlID(EditorGUI.s_MouseDeltaReaderHash, FocusType.Passive, position); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (activated && GUIUtility.hotControl == 0 && position.Contains(current.mousePosition) && current.button == 0) + { + GUIUtility.hotControl = controlID; + GUIUtility.keyboardControl = 0; + EditorGUI.s_MouseDeltaReaderLastPos = GUIClip.Unclip(current.mousePosition); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + Vector2 a = GUIClip.Unclip(current.mousePosition); + Vector2 result = a - EditorGUI.s_MouseDeltaReaderLastPos; + EditorGUI.s_MouseDeltaReaderLastPos = a; + current.Use(); + return result; + } + break; + } + return Vector2.zero; } - [ExcludeFromDocs] - public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode) + internal static bool ButtonWithDropdownList(string buttonName, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options) { - float imageAspect = 0f; - EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); + GUIContent content = EditorGUIUtility.TempContent(buttonName); + return EditorGUI.ButtonWithDropdownList(content, buttonNames, callback, options); } - [ExcludeFromDocs] - public static void DrawTextureTransparent(Rect position, Texture image) + internal static bool ButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options) { - float imageAspect = 0f; - ScaleMode scaleMode = ScaleMode.StretchToFill; - EditorGUI.DrawTextureTransparent(position, image, scaleMode, imageAspect); + Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.dropDownList, options); + Rect rect2 = rect; + rect2.xMin = rect2.xMax - 20f; + if (Event.current.type == EventType.MouseDown && rect2.Contains(Event.current.mousePosition)) + { + GenericMenu genericMenu = new GenericMenu(); + for (int num = 0; num != buttonNames.Length; num++) + { + genericMenu.AddItem(new GUIContent(buttonNames[num]), false, callback, num); + } + genericMenu.DropDown(rect); + Event.current.Use(); + return false; + } + return GUI.Button(rect, content, EditorStyles.dropDownList); } - public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + internal static void GameViewSizePopup(Rect buttonRect, GameViewSizeGroupType groupType, int selectedIndex, Action itemClickedCallback, GUIStyle guiStyle) { - EditorGUI.DrawTextureTransparentInternal(position, image, scaleMode, imageAspect); + GameViewSizeGroup group = ScriptableSingleton.instance.GetGroup(groupType); + string t; + if (selectedIndex >= 0 && selectedIndex < group.GetTotalCount()) + { + t = group.GetGameViewSize(selectedIndex).displayText; + } + else + { + t = string.Empty; + } + if (EditorGUI.ButtonMouseDown(buttonRect, GUIContent.Temp(t), FocusType.Passive, guiStyle)) + { + IFlexibleMenuItemProvider itemProvider = new GameViewSizesMenuItemProvider(groupType); + FlexibleMenu windowContent = new FlexibleMenu(itemProvider, selectedIndex, new GameViewSizesMenuModifyItemUI(), itemClickedCallback); + PopupWindow.Show(buttonRect, windowContent); + } } - [ExcludeFromDocs] - public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode) + public static void DrawRect(Rect rect, Color color) { - float imageAspect = 0f; - EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color2 = GUI.color; + GUI.color *= color; + GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); + GUI.color = color2; } - [ExcludeFromDocs] - public static void DrawPreviewTexture(Rect position, Texture image, Material mat) + internal static float Knob(Rect position, Vector2 knobSize, float currentValue, float start, float end, string unit, Color backgroundColor, Color activeColor, bool showValue, int id) { - float imageAspect = 0f; - ScaleMode scaleMode = ScaleMode.StretchToFill; - EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + EditorGUI.KnobContext knobContext = new EditorGUI.KnobContext(position, knobSize, currentValue, start, end, unit, backgroundColor, activeColor, showValue, id); + return knobContext.Handle(); } - [ExcludeFromDocs] - public static void DrawPreviewTexture(Rect position, Texture image) + internal static float OffsetKnob(Rect position, float currentValue, float start, float end, float median, string unit, Color backgroundColor, Color activeColor, GUIStyle knob, int id) { - float imageAspect = 0f; - ScaleMode scaleMode = ScaleMode.StretchToFill; - Material mat = null; - EditorGUI.DrawPreviewTexture(position, image, mat, scaleMode, imageAspect); + return 0f; } - public static void DrawPreviewTexture(Rect position, Texture image, [DefaultValue("null")] Material mat, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect) + internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects) { - EditorGUI.DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect); + return EditorGUI.DoObjectField(position, dropRect, id, obj, objType, property, validator, allowSceneObjects, EditorStyles.objectField); } - [ExcludeFromDocs] - public static float GetPropertyHeight(SerializedProperty property, GUIContent label) + internal static UnityEngine.Object DoObjectField(Rect position, Rect dropRect, int id, UnityEngine.Object obj, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) { - bool includeChildren = true; - return EditorGUI.GetPropertyHeight(property, label, includeChildren); + if (validator == null) + { + validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); + } + Event current = Event.current; + EventType eventType = current.type; + if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + { + eventType = Event.current.rawType; + } + bool flag = EditorGUIUtility.HasObjectThumbnail(objType); + EditorGUI.ObjectFieldVisualType objectFieldVisualType = EditorGUI.ObjectFieldVisualType.IconAndText; + if (flag && position.height <= 18f && position.width <= 32f) + { + objectFieldVisualType = EditorGUI.ObjectFieldVisualType.MiniPreivew; + } + else + { + if (flag && position.height > 16f) + { + objectFieldVisualType = EditorGUI.ObjectFieldVisualType.LargePreview; + } + } + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + if (objectFieldVisualType == EditorGUI.ObjectFieldVisualType.IconAndText) + { + EditorGUIUtility.SetIconSize(new Vector2(12f, 12f)); + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.KeyDown: + if (GUIUtility.keyboardControl == id) + { + if (current.keyCode == KeyCode.Backspace || current.keyCode == KeyCode.Delete) + { + if (property != null) + { + property.objectReferenceValue = null; + } + else + { + obj = null; + } + GUI.changed = true; + current.Use(); + } + if (current.MainActionKeyForControl(id)) + { + ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); + ObjectSelector.get.objectSelectorID = id; + current.Use(); + GUIUtility.ExitGUI(); + } + } + goto IL_5EB; + case EventType.KeyUp: + case EventType.ScrollWheel: + case EventType.Layout: + case EventType.Ignore: + case EventType.Used: + case EventType.ValidateCommand: + IL_FF: + if (eventType2 != EventType.MouseDown) + { + goto IL_5EB; + } + if (Event.current.button != 0) + { + goto IL_5EB; + } + if (position.Contains(Event.current.mousePosition)) + { + Rect rect; + switch (objectFieldVisualType) + { + case EditorGUI.ObjectFieldVisualType.IconAndText: + rect = new Rect(position.xMax - 15f, position.y, 15f, position.height); + break; + case EditorGUI.ObjectFieldVisualType.LargePreview: + rect = new Rect(position.xMax - 32f, position.yMax - 14f, 32f, 14f); + break; + case EditorGUI.ObjectFieldVisualType.MiniPreivew: + rect = new Rect(position.xMax - 15f, position.y, 15f, position.height); + break; + default: + throw new ArgumentOutOfRangeException(); + } + EditorGUIUtility.editingTextField = false; + if (rect.Contains(Event.current.mousePosition)) + { + if (GUI.enabled) + { + GUIUtility.keyboardControl = id; + ObjectSelector.get.Show(obj, objType, property, allowSceneObjects); + ObjectSelector.get.objectSelectorID = id; + current.Use(); + GUIUtility.ExitGUI(); + } + } + else + { + UnityEngine.Object @object = (property == null) ? obj : property.objectReferenceValue; + Component component = @object as Component; + if (component) + { + @object = component.gameObject; + } + if (EditorGUI.showMixedValue) + { + @object = null; + } + if (Event.current.clickCount == 1) + { + GUIUtility.keyboardControl = id; + if (@object) + { + bool flag2 = current.shift || current.control; + if (!flag2) + { + EditorGUIUtility.PingObject(@object); + } + if (flag2 && @object is Texture) + { + PopupWindowWithoutFocus.Show(new RectOffset(6, 3, 0, 3).Add(position), new ObjectPreviewPopup(@object), new PopupLocationHelper.PopupLocation[] + { + PopupLocationHelper.PopupLocation.Left, + PopupLocationHelper.PopupLocation.Below, + PopupLocationHelper.PopupLocation.Right + }); + } + } + current.Use(); + } + else + { + if (Event.current.clickCount == 2) + { + if (@object) + { + AssetDatabase.OpenAsset(@object); + GUIUtility.ExitGUI(); + } + current.Use(); + } + } + } + } + goto IL_5EB; + case EventType.Repaint: + { + GUIContent content; + if (EditorGUI.showMixedValue) + { + content = EditorGUI.s_MixedValueContent; + } + else + { + if (property != null) + { + content = EditorGUIUtility.TempContent(property.objectReferenceStringValue, AssetPreview.GetMiniThumbnail(property.objectReferenceValue)); + obj = property.objectReferenceValue; + if (obj != null) + { + UnityEngine.Object[] references = new UnityEngine.Object[] + { + obj + }; + if (validator(references, objType, property) == null) + { + content = EditorGUIUtility.TempContent("Type mismatch"); + } + } + } + else + { + content = EditorGUIUtility.ObjectContent(obj, objType); + } + } + switch (objectFieldVisualType) + { + case EditorGUI.ObjectFieldVisualType.IconAndText: + EditorGUI.BeginHandleMixedValueContentColor(); + style.Draw(position, content, id, DragAndDrop.activeControlID == id); + EditorGUI.EndHandleMixedValueContentColor(); + break; + case EditorGUI.ObjectFieldVisualType.LargePreview: + EditorGUI.DrawObjectFieldLargeThumb(position, id, obj, content); + break; + case EditorGUI.ObjectFieldVisualType.MiniPreivew: + EditorGUI.DrawObjectFieldMiniThumb(position, id, obj, content); + break; + default: + throw new ArgumentOutOfRangeException(); + } + goto IL_5EB; + } + case EventType.DragUpdated: + case EventType.DragPerform: + if (dropRect.Contains(Event.current.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object object2 = validator(objectReferences, objType, property); + if (object2 != null && !allowSceneObjects && !EditorUtility.IsPersistent(object2)) + { + object2 = null; + } + if (object2 != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (eventType == EventType.DragPerform) + { + if (property != null) + { + property.objectReferenceValue = object2; + } + else + { + obj = object2; + } + GUI.changed = true; + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = 0; + } + else + { + DragAndDrop.activeControlID = id; + } + Event.current.Use(); + } + } + goto IL_5EB; + case EventType.ExecuteCommand: + { + string commandName = current.commandName; + if (commandName == "ObjectSelectorUpdated" && ObjectSelector.get.objectSelectorID == id && GUIUtility.keyboardControl == id) + { + UnityEngine.Object[] references2 = new UnityEngine.Object[] + { + ObjectSelector.GetCurrentObject() + }; + UnityEngine.Object object3 = validator(references2, objType, property); + if (property != null) + { + property.objectReferenceValue = object3; + } + GUI.changed = true; + current.Use(); + return object3; + } + goto IL_5EB; + } + case EventType.DragExited: + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + goto IL_5EB; + } + goto IL_FF; + IL_5EB: + EditorGUIUtility.SetIconSize(iconSize); + return obj; } - [ExcludeFromDocs] - public static float GetPropertyHeight(SerializedProperty property) + private static void DrawObjectFieldLargeThumb(Rect position, int id, UnityEngine.Object obj, GUIContent content) { - bool includeChildren = true; - GUIContent label = null; - return EditorGUI.GetPropertyHeight(property, label, includeChildren); + GUIStyle objectFieldThumb = EditorStyles.objectFieldThumb; + objectFieldThumb.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); + if (obj != null && !EditorGUI.showMixedValue) + { + bool flag = obj is Cubemap; + Rect position2 = objectFieldThumb.padding.Remove(position); + if (flag) + { + position2.x += (position2.width - (float)content.image.width) / 2f; + position2.y += (position2.height - (float)content.image.width) / 2f; + GUIStyle.none.Draw(position2, content.image, false, false, false, false); + } + else + { + Texture2D texture2D = content.image as Texture2D; + if (texture2D != null && texture2D.alphaIsTransparency) + { + EditorGUI.DrawTextureTransparent(position2, texture2D); + } + else + { + EditorGUI.DrawPreviewTexture(position2, content.image); + } + } + } + else + { + GUIStyle gUIStyle = objectFieldThumb.name + "Overlay"; + EditorGUI.BeginHandleMixedValueContentColor(); + gUIStyle.Draw(position, content, id); + EditorGUI.EndHandleMixedValueContentColor(); + } + GUIStyle gUIStyle2 = objectFieldThumb.name + "Overlay2"; + gUIStyle2.Draw(position, EditorGUIUtility.TempContent("Select"), id); } - public static float GetPropertyHeight(SerializedProperty property, [DefaultValue("null")] GUIContent label, [DefaultValue("true")] bool includeChildren) + private static void DrawObjectFieldMiniThumb(Rect position, int id, UnityEngine.Object obj, GUIContent content) { - return EditorGUI.GetPropertyHeightInternal(property, label, includeChildren); + GUIStyle objectFieldMiniThumb = EditorStyles.objectFieldMiniThumb; + position.width = 32f; + EditorGUI.BeginHandleMixedValueContentColor(); + bool isHover = obj != null; + bool on = DragAndDrop.activeControlID == id; + bool hasKeyboardFocus = GUIUtility.keyboardControl == id; + objectFieldMiniThumb.Draw(position, isHover, false, on, hasKeyboardFocus); + EditorGUI.EndHandleMixedValueContentColor(); + if (obj != null && !EditorGUI.showMixedValue) + { + Rect position2 = new Rect(position.x + 1f, position.y + 1f, position.height - 2f, position.height - 2f); + Texture2D texture2D = content.image as Texture2D; + if (texture2D != null && texture2D.alphaIsTransparency) + { + EditorGUI.DrawTextureTransparent(position2, texture2D); + } + else + { + EditorGUI.DrawPreviewTexture(position2, content.image); + } + if (position2.Contains(Event.current.mousePosition)) + { + GUI.Label(position2, GUIContent.Temp(string.Empty, "Ctrl + Click to show preview")); + } + } } - [ExcludeFromDocs] - public static bool PropertyField(Rect position, SerializedProperty property) + internal static UnityEngine.Object DoDropField(Rect position, int id, Type objType, EditorGUI.ObjectFieldValidator validator, bool allowSceneObjects, GUIStyle style) { - bool includeChildren = false; - return EditorGUI.PropertyField(position, property, includeChildren); + if (validator == null) + { + validator = new EditorGUI.ObjectFieldValidator(EditorGUI.ValidateObjectFieldAssignment); + } + Event current = Event.current; + EventType eventType = current.type; + if (!GUI.enabled && GUIClip.enabled && Event.current.rawType == EventType.MouseDown) + { + eventType = Event.current.rawType; + } + EventType eventType2 = eventType; + switch (eventType2) + { + case EventType.Repaint: + style.Draw(position, GUIContent.none, id, DragAndDrop.activeControlID == id); + goto IL_144; + case EventType.Layout: + IL_6B: + if (eventType2 != EventType.DragExited) + { + goto IL_144; + } + if (GUI.enabled) + { + HandleUtility.Repaint(); + } + goto IL_144; + case EventType.DragUpdated: + case EventType.DragPerform: + if (position.Contains(Event.current.mousePosition) && GUI.enabled) + { + UnityEngine.Object[] objectReferences = DragAndDrop.objectReferences; + UnityEngine.Object @object = validator(objectReferences, objType, null); + if (@object != null && !allowSceneObjects && !EditorUtility.IsPersistent(@object)) + { + @object = null; + } + if (@object != null) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Generic; + if (eventType == EventType.DragPerform) + { + GUI.changed = true; + DragAndDrop.AcceptDrag(); + DragAndDrop.activeControlID = 0; + Event.current.Use(); + return @object; + } + DragAndDrop.activeControlID = id; + Event.current.Use(); + } + } + goto IL_144; + } + goto IL_6B; + IL_144: + return null; } - public static bool PropertyField(Rect position, SerializedProperty property, [DefaultValue("false")] bool includeChildren) + internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label) { - return EditorGUI.PropertyFieldInternal(position, property, null, includeChildren); + EditorGUI.TargetChoiceField(position, property, label, new TargetChoiceHandler.TargetChoiceMenuFunction(TargetChoiceHandler.SetToValueOfTarget)); } - [ExcludeFromDocs] - public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label) + internal static void TargetChoiceField(Rect position, SerializedProperty property, GUIContent label, TargetChoiceHandler.TargetChoiceMenuFunction func) { - bool includeChildren = false; - return EditorGUI.PropertyField(position, property, label, includeChildren); + EditorGUI.BeginProperty(position, label, property); + position = EditorGUI.PrefixLabel(position, 0, label); + EditorGUI.BeginHandleMixedValueContentColor(); + if (GUI.Button(position, EditorGUI.mixedValueContent, EditorStyles.popup)) + { + GenericMenu genericMenu = new GenericMenu(); + TargetChoiceHandler.AddSetToValueOfTargetMenuItems(genericMenu, property, func); + genericMenu.DropDown(position); + } + EditorGUI.EndHandleMixedValueContentColor(); + EditorGUI.EndProperty(); } - public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label, [DefaultValue("false")] bool includeChildren) + internal static string DoTextFieldDropDown(Rect rect, int id, string text, string[] dropDownElements, bool delayed) { - return EditorGUI.PropertyFieldInternal(position, property, label, includeChildren); + Rect position = new Rect(rect.x, rect.y, rect.width - EditorStyles.textFieldDropDown.fixedWidth, rect.height); + Rect rect2 = new Rect(position.xMax, position.y, EditorStyles.textFieldDropDown.fixedWidth, rect.height); + if (delayed) + { + text = EditorGUI.DelayedTextField(position, text, null, EditorStyles.textFieldDropDownText); + } + else + { + bool flag; + text = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, text, EditorStyles.textFieldDropDownText, null, out flag, false, false, false); + } + EditorGUI.BeginChangeCheck(); + Rect arg_B7_0 = rect2; + string arg_B7_1 = string.Empty; + int arg_B7_2 = -1; + string[] arg_B7_3; + if (dropDownElements.Length > 0) + { + arg_B7_3 = dropDownElements; + } + else + { + (arg_B7_3 = new string[1])[0] = "--empty--"; + } + int num = EditorGUI.Popup(arg_B7_0, arg_B7_1, arg_B7_2, arg_B7_3, EditorStyles.textFieldDropDown); + if (EditorGUI.EndChangeCheck() && dropDownElements.Length > 0) + { + text = dropDownElements[num]; + } + return text; } } } diff --git a/UnityEditor/UnityEditor/EditorGUIExt.cs b/UnityEditor/UnityEditor/EditorGUIExt.cs index 00a9a249..9d23e996 100644 --- a/UnityEditor/UnityEditor/EditorGUIExt.cs +++ b/UnityEditor/UnityEditor/EditorGUIExt.cs @@ -221,14 +221,14 @@ internal static void DoMinMaxSlider(Rect position, int id, ref float value, ref { minMaxSliderState = (EditorGUIExt.s_MinMaxSliderState = new EditorGUIExt.MinMaxSliderState()); } + minMaxSliderState.dragStartLimit = startLimit; + minMaxSliderState.dragEndLimit = endLimit; if (position2.Contains(current.mousePosition)) { minMaxSliderState.dragStartPos = num11; minMaxSliderState.dragStartValue = value; minMaxSliderState.dragStartSize = size; minMaxSliderState.dragStartValuesPerPixel = num10; - minMaxSliderState.dragStartLimit = startLimit; - minMaxSliderState.dragEndLimit = endLimit; if (rect.Contains(current.mousePosition)) { minMaxSliderState.whereWeDrag = 1; @@ -296,6 +296,7 @@ internal static void DoMinMaxSlider(Rect position, int id, ref float value, ref minMaxSliderState.dragStartPos = num11; minMaxSliderState.dragStartValue = value; minMaxSliderState.dragStartSize = size; + minMaxSliderState.dragStartValuesPerPixel = num10; minMaxSliderState.whereWeDrag = 0; GUI.changed = true; } @@ -659,9 +660,9 @@ public static HighLevelEvent MultiSelection(Rect rect, Rect[] positions, GUICont string commandName = current.commandName; if (commandName != null) { - if (EditorGUIExt.<>f__switch$map9 == null) + if (EditorGUIExt.<>f__switch$mapB == null) { - EditorGUIExt.<>f__switch$map9 = new Dictionary(1) + EditorGUIExt.<>f__switch$mapB = new Dictionary(1) { { @@ -671,7 +672,7 @@ public static HighLevelEvent MultiSelection(Rect rect, Rect[] positions, GUICont }; } int num; - if (EditorGUIExt.<>f__switch$map9.TryGetValue(commandName, out num)) + if (EditorGUIExt.<>f__switch$mapB.TryGetValue(commandName, out num)) { if (num == 0) { diff --git a/UnityEditor/UnityEditor/EditorGUIInternal.cs b/UnityEditor/UnityEditor/EditorGUIInternal.cs index 7095be38..c0707b99 100644 --- a/UnityEditor/UnityEditor/EditorGUIInternal.cs +++ b/UnityEditor/UnityEditor/EditorGUIInternal.cs @@ -53,5 +53,9 @@ internal static void BeginWindowsForward(int skinMode, int editorWindowInstanceI { GUI.BeginWindows(skinMode, editorWindowInstanceID); } + internal static void AssetPopup(SerializedProperty serializedProperty, GUIContent content, string fileExtension) where T : UnityEngine.Object, new() + { + AssetPopupBackend.AssetPopup(serializedProperty, content, fileExtension); + } } } diff --git a/UnityEditor/UnityEditor/EditorGUILayout.cs b/UnityEditor/UnityEditor/EditorGUILayout.cs index fad66454..2491dac2 100644 --- a/UnityEditor/UnityEditor/EditorGUILayout.cs +++ b/UnityEditor/UnityEditor/EditorGUILayout.cs @@ -5,6 +5,191 @@ namespace UnityEditor { public sealed class EditorGUILayout { + public class ToggleGroupScope : GUI.Scope + { + public bool enabled + { + get; + protected set; + } + public ToggleGroupScope(string label, bool toggle) + { + this.enabled = EditorGUILayout.BeginToggleGroup(label, toggle); + } + public ToggleGroupScope(GUIContent label, bool toggle) + { + this.enabled = EditorGUILayout.BeginToggleGroup(label, toggle); + } + protected override void CloseScope() + { + EditorGUILayout.EndToggleGroup(); + } + } + public class HorizontalScope : GUI.Scope + { + public Rect rect + { + get; + protected set; + } + public HorizontalScope(params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginHorizontal(options); + } + public HorizontalScope(GUIStyle style, params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginHorizontal(style, options); + } + internal HorizontalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginHorizontal(content, style, options); + } + protected override void CloseScope() + { + EditorGUILayout.EndHorizontal(); + } + } + public class VerticalScope : GUI.Scope + { + public Rect rect + { + get; + protected set; + } + public VerticalScope(params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginVertical(options); + } + public VerticalScope(GUIStyle style, params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginVertical(style, options); + } + internal VerticalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + this.rect = EditorGUILayout.BeginVertical(content, style, options); + } + protected override void CloseScope() + { + EditorGUILayout.EndVertical(); + } + } + public class ScrollViewScope : GUI.Scope + { + public Vector2 scrollPosition + { + get; + protected set; + } + public bool handleScrollWheel + { + get; + set; + } + public ScrollViewScope(Vector2 scrollPosition, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, options); + } + public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, options); + } + public ScrollViewScope(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, horizontalScrollbar, verticalScrollbar, options); + } + public ScrollViewScope(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, style, options); + } + public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background, options); + } + internal ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, options); + } + protected override void CloseScope() + { + EditorGUILayout.EndScrollView(this.handleScrollWheel); + } + } + internal class VerticalScrollViewScope : GUI.Scope + { + public Vector2 scrollPosition + { + get; + protected set; + } + public bool handleScrollWheel + { + get; + set; + } + public VerticalScrollViewScope(Vector2 scrollPosition, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginVerticalScrollView(scrollPosition, options); + } + public VerticalScrollViewScope(Vector2 scrollPosition, bool alwaysShowVertical, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginVerticalScrollView(scrollPosition, alwaysShowVertical, verticalScrollbar, background, options); + } + protected override void CloseScope() + { + EditorGUILayout.EndScrollView(this.handleScrollWheel); + } + } + internal class HorizontalScrollViewScope : GUI.Scope + { + public Vector2 scrollPosition + { + get; + protected set; + } + public bool handleScrollWheel + { + get; + set; + } + public HorizontalScrollViewScope(Vector2 scrollPosition, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginHorizontalScrollView(scrollPosition, options); + } + public HorizontalScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, GUIStyle horizontalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = EditorGUILayout.BeginHorizontalScrollView(scrollPosition, alwaysShowHorizontal, horizontalScrollbar, background, options); + } + protected override void CloseScope() + { + EditorGUILayout.EndScrollView(this.handleScrollWheel); + } + } + public class FadeGroupScope : GUI.Scope + { + public bool visible + { + get; + protected set; + } + public FadeGroupScope(float value) + { + this.visible = EditorGUILayout.BeginFadeGroup(value); + } + protected override void CloseScope() + { + EditorGUILayout.EndFadeGroup(); + } + } internal const float kPlatformTabWidth = 30f; internal static Rect s_LastRect; internal static SavedBool s_SelectedDefault = new SavedBool("Platform.ShownDefaultTab", true); @@ -22,6 +207,54 @@ internal static float kLabelFloatMaxW return EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5f; } } + [ExcludeFromDocs] + public static bool Foldout(bool foldout, string content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUILayout.Foldout(foldout, content, foldout2); + } + public static bool Foldout(bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUILayout.Foldout(foldout, EditorGUIUtility.TempContent(content), style); + } + [ExcludeFromDocs] + public static bool Foldout(bool foldout, GUIContent content) + { + GUIStyle foldout2 = EditorStyles.foldout; + return EditorGUILayout.Foldout(foldout, content, foldout2); + } + public static bool Foldout(bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) + { + return EditorGUILayout.FoldoutInternal(foldout, content, style); + } + [ExcludeFromDocs] + public static void PrefixLabel(string label) + { + GUIStyle followingStyle = "Button"; + EditorGUILayout.PrefixLabel(label, followingStyle); + } + public static void PrefixLabel(string label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, EditorStyles.label); + } + public static void PrefixLabel(string label, GUIStyle followingStyle, GUIStyle labelStyle) + { + EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, labelStyle); + } + [ExcludeFromDocs] + public static void PrefixLabel(GUIContent label) + { + GUIStyle followingStyle = "Button"; + EditorGUILayout.PrefixLabel(label, followingStyle); + } + public static void PrefixLabel(GUIContent label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) + { + EditorGUILayout.PrefixLabel(label, followingStyle, EditorStyles.label); + } + public static void PrefixLabel(GUIContent label, GUIStyle followingStyle, GUIStyle labelStyle) + { + EditorGUILayout.PrefixLabelInternal(label, followingStyle, labelStyle); + } public static void LabelField(string label, params GUILayoutOption[] options) { EditorGUILayout.LabelField(GUIContent.none, EditorGUIUtility.TempContent(label), EditorStyles.label, options); @@ -211,10 +444,15 @@ public static string PasswordField(GUIContent label, string password, GUIStyle s Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); return EditorGUI.PasswordField(position, label, password, style); } - internal static void VUMeterHorizontal(float value, ref EditorGUI.VUMeterData data, params GUILayoutOption[] options) + internal static void VUMeterHorizontal(float value, float peak, params GUILayoutOption[] options) { Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options); - EditorGUI.VUMeterHorizontal(position, value, ref data); + EditorGUI.VUMeter.HorizontalMeter(position, value, peak, EditorGUI.VUMeter.horizontalVUTexture, Color.grey); + } + internal static void VUMeterHorizontal(float value, ref EditorGUI.VUMeter.SmoothingData data, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options); + EditorGUI.VUMeter.HorizontalMeter(position, value, ref data, EditorGUI.VUMeter.horizontalVUTexture, Color.grey); } public static float FloatField(float value, params GUILayoutOption[] options) { @@ -246,6 +484,36 @@ public static float FloatField(GUIContent label, float value, GUIStyle style, pa Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); return EditorGUI.FloatField(position, label, value, style); } + public static double DoubleField(double value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options); + return EditorGUI.DoubleField(position, value); + } + public static double DoubleField(double value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.DoubleField(position, value, style); + } + public static double DoubleField(string label, double value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.numberField, options); + return EditorGUI.DoubleField(position, label, value); + } + public static double DoubleField(string label, double value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.DoubleField(position, label, value, style); + } + public static double DoubleField(GUIContent label, double value, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.numberField, options); + return EditorGUI.DoubleField(position, label, value); + } + public static double DoubleField(GUIContent label, double value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.DoubleField(position, label, value, style); + } public static int IntField(int value, params GUILayoutOption[] options) { return EditorGUILayout.IntField(value, EditorStyles.numberField, options); @@ -273,6 +541,33 @@ public static int IntField(GUIContent label, int value, GUIStyle style, params G Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); return EditorGUI.IntField(position, label, value, style); } + public static long LongField(long value, params GUILayoutOption[] options) + { + return EditorGUILayout.LongField(value, EditorStyles.numberField, options); + } + public static long LongField(long value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + return EditorGUI.LongField(position, value, style); + } + public static long LongField(string label, long value, params GUILayoutOption[] options) + { + return EditorGUILayout.LongField(label, value, EditorStyles.numberField, options); + } + public static long LongField(string label, long value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.LongField(position, label, value, style); + } + public static long LongField(GUIContent label, long value, params GUILayoutOption[] options) + { + return EditorGUILayout.LongField(label, value, EditorStyles.numberField, options); + } + public static long LongField(GUIContent label, long value, GUIStyle style, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, style, options); + return EditorGUI.LongField(position, label, value, style); + } public static float Slider(float value, float leftValue, float rightValue, params GUILayoutOption[] options) { Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); @@ -301,10 +596,14 @@ public static void Slider(SerializedProperty property, float leftValue, float ri Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); EditorGUI.Slider(position, property, leftValue, rightValue, label); } - internal static float PowerSlider(float sliderValue, float min, float max, float power, params GUILayoutOption[] options) + internal static float PowerSlider(string label, float value, float leftValue, float rightValue, float power, params GUILayoutOption[] options) { - Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(false, options); - return EditorGUI.PowerSlider(position, sliderValue, min, max, power); + return EditorGUILayout.PowerSlider(EditorGUIUtility.TempContent(label), value, leftValue, rightValue, power, options); + } + internal static float PowerSlider(GUIContent label, float value, float leftValue, float rightValue, float power, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetSliderRect(true, options); + return EditorGUI.PowerSlider(position, label, value, leftValue, rightValue, power); } public static int IntSlider(int value, int leftValue, int rightValue, params GUILayoutOption[] options) { @@ -605,10 +904,23 @@ public static UnityEngine.Object ObjectField(GUIContent label, UnityEngine.Objec } public static UnityEngine.Object ObjectField(GUIContent label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options) { - float height = (!EditorGUIUtility.HasObjectThumbnail(objType)) ? 16f : 64f; + float height; + if (EditorGUIUtility.HasObjectThumbnail(objType)) + { + height = 64f; + } + else + { + height = 16f; + } Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, height, options); return EditorGUI.ObjectField(position, label, obj, objType, allowSceneObjects); } + internal static UnityEngine.Object MiniThumbnailObjectField(GUIContent label, UnityEngine.Object obj, Type objType, EditorGUI.ObjectFieldValidator validator, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, options); + return EditorGUI.MiniThumbnailObjectField(position, label, obj, objType, validator); + } public static Vector2 Vector2Field(string label, Vector2 value, params GUILayoutOption[] options) { Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, ((!EditorGUIUtility.wideMode) ? 16f : 0f) + 16f, EditorStyles.numberField, options); @@ -667,6 +979,13 @@ public static Bounds BoundsField(GUIContent label, Bounds value, params GUILayou Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(flag, height, EditorStyles.numberField, options); return EditorGUI.BoundsField(position, label, value); } + internal static void PropertiesField(GUIContent label, SerializedProperty[] properties, GUIContent[] propertyLabels, float propertyLabelsWidth, params GUILayoutOption[] options) + { + bool hasLabel = EditorGUI.LabelHasContent(label); + float height = 16f * (float)properties.Length; + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(hasLabel, height, EditorStyles.numberField, options); + EditorGUI.PropertiesField(position, label, properties, propertyLabels, propertyLabelsWidth); + } internal static int CycleButton(int selected, GUIContent[] options, GUIStyle style) { if (GUILayout.Button(options[selected], style, new GUILayoutOption[0])) @@ -724,7 +1043,7 @@ public static AnimationCurve CurveField(GUIContent label, AnimationCurve value, Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.colorField, options); return EditorGUI.CurveField(position, label, value, color, ranges); } - private static void CurveField(SerializedProperty value, Color color, Rect ranges, params GUILayoutOption[] options) + internal static void CurveField(SerializedProperty value, Color color, Rect ranges, params GUILayoutOption[] options) { Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.colorField, options); EditorGUI.CurveField(position, value, color, ranges); @@ -737,6 +1056,29 @@ public static bool InspectorTitlebar(bool foldout, UnityEngine.Object[] targetOb { return EditorGUI.InspectorTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), foldout, targetObjs); } + public static void InspectorTitlebar(UnityEngine.Object[] targetObjs) + { + EditorGUI.InspectorTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), targetObjs); + } + internal static bool ToggleTitlebar(bool foldout, GUIContent label, ref bool toggleValue) + { + return EditorGUI.ToggleTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), label, foldout, ref toggleValue); + } + internal static bool ToggleTitlebar(bool foldout, GUIContent label, SerializedProperty property) + { + bool boolValue = property.boolValue; + EditorGUI.BeginChangeCheck(); + foldout = EditorGUI.ToggleTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), label, foldout, ref boolValue); + if (EditorGUI.EndChangeCheck()) + { + property.boolValue = boolValue; + } + return foldout; + } + internal static bool FoldoutTitlebar(bool foldout, GUIContent label) + { + return EditorGUI.FoldoutTitlebar(GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar), label, foldout); + } internal static bool FoldoutInternal(bool foldout, GUIContent content, GUIStyle style) { Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUIUtility.fieldWidth, 16f, 16f, style); @@ -1065,7 +1407,7 @@ internal static int BeginPlatformGrouping(BuildPlayerWindow.BuildPlatform[] plat int num6 = Mathf.RoundToInt((float)(j + 1) * rect.width / (float)num3); position = new Rect(rect.x + (float)num5, rect.y, (float)(num6 - num5), (float)num4); } - if (GUI.Toggle(position, num2 == j, platforms[j].smallIcon, toolbarButton)) + if (GUI.Toggle(position, num2 == j, new GUIContent(platforms[j].smallIcon, platforms[j].tooltip), toolbarButton)) { num2 = j; } @@ -1158,7 +1500,25 @@ internal static bool BitToggleField(string label, SerializedProperty bitFieldPro internal static void SortingLayerField(GUIContent label, SerializedProperty layerID, GUIStyle style) { Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, new GUILayoutOption[0]); - EditorGUI.SortingLayerField(position, label, layerID, style); + EditorGUI.SortingLayerField(position, label, layerID, style, EditorStyles.label); + } + internal static string TextFieldDropDown(string text, string[] dropDownElement) + { + return EditorGUILayout.TextFieldDropDown(GUIContent.none, text, dropDownElement); + } + internal static string TextFieldDropDown(GUIContent label, string text, string[] dropDownElement) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.textField); + return EditorGUI.TextFieldDropDown(rect, label, text, dropDownElement); + } + internal static string DelayedTextFieldDropDown(string text, string[] dropDownElement) + { + return EditorGUILayout.DelayedTextFieldDropDown(GUIContent.none, text, dropDownElement); + } + internal static string DelayedTextFieldDropDown(GUIContent label, string text, string[] dropDownElement) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.textFieldDropDownText); + return EditorGUI.DelayedTextFieldDropDown(rect, label, text, dropDownElement); } internal static Gradient GradientField(Gradient value, params GUILayoutOption[] options) { @@ -1190,14 +1550,30 @@ internal static Gradient GradientField(GUIContent label, SerializedProperty valu Rect position = EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.colorField, options); return EditorGUI.GradientField(label, position, value); } + internal static bool ButtonMouseDown(GUIContent content, FocusType focusType, GUIStyle style, params GUILayoutOption[] options) + { + EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(content, style, options); + return EditorGUI.ButtonMouseDown(EditorGUILayout.s_LastRect, content, focusType, style); + } internal static bool IconButton(int id, GUIContent content, GUIStyle style, params GUILayoutOption[] options) { - return EditorGUI.IconButton(id, GUILayoutUtility.GetRect(content, style, options), content, style); + EditorGUILayout.s_LastRect = GUILayoutUtility.GetRect(content, style, options); + return EditorGUI.IconButton(id, EditorGUILayout.s_LastRect, content, style); } internal static void GameViewSizePopup(GameViewSizeGroupType groupType, int selectedIndex, Action itemClickedCallback, GUIStyle style, params GUILayoutOption[] options) { - Rect controlRect = EditorGUILayout.GetControlRect(false, 16f, style, options); - EditorGUI.GameViewSizePopup(controlRect, groupType, selectedIndex, itemClickedCallback, style); + EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, options); + EditorGUI.GameViewSizePopup(EditorGUILayout.s_LastRect, groupType, selectedIndex, itemClickedCallback, style); + } + internal static void SortingLayerField(GUIContent label, SerializedProperty layerID, GUIStyle style, GUIStyle labelStyle) + { + EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, style, new GUILayoutOption[0]); + EditorGUI.SortingLayerField(EditorGUILayout.s_LastRect, label, layerID, style, labelStyle); + } + public static float Knob(Vector2 knobSize, float value, float minValue, float maxValue, string unit, Color backgroundColor, Color activeColor, bool showValue, params GUILayoutOption[] options) + { + Rect position = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, knobSize.y, options); + return EditorGUI.Knob(position, knobSize, value, minValue, maxValue, unit, backgroundColor, activeColor, showValue, GUIUtility.GetControlID("Knob".GetHashCode(), FocusType.Native, position)); } internal static void TargetChoiceField(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) { @@ -1208,53 +1584,5 @@ internal static void TargetChoiceField(SerializedProperty property, GUIContent l Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.popup, options); EditorGUI.TargetChoiceField(rect, property, label, func); } - [ExcludeFromDocs] - public static bool Foldout(bool foldout, string content) - { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUILayout.Foldout(foldout, content, foldout2); - } - public static bool Foldout(bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) - { - return EditorGUILayout.Foldout(foldout, EditorGUIUtility.TempContent(content), style); - } - [ExcludeFromDocs] - public static bool Foldout(bool foldout, GUIContent content) - { - GUIStyle foldout2 = EditorStyles.foldout; - return EditorGUILayout.Foldout(foldout, content, foldout2); - } - public static bool Foldout(bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) - { - return EditorGUILayout.FoldoutInternal(foldout, content, style); - } - [ExcludeFromDocs] - public static void PrefixLabel(string label) - { - GUIStyle followingStyle = "Button"; - EditorGUILayout.PrefixLabel(label, followingStyle); - } - public static void PrefixLabel(string label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) - { - EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, EditorStyles.label); - } - public static void PrefixLabel(string label, GUIStyle followingStyle, GUIStyle labelStyle) - { - EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent(label), followingStyle, labelStyle); - } - [ExcludeFromDocs] - public static void PrefixLabel(GUIContent label) - { - GUIStyle followingStyle = "Button"; - EditorGUILayout.PrefixLabel(label, followingStyle); - } - public static void PrefixLabel(GUIContent label, [DefaultValue("\"Button\"")] GUIStyle followingStyle) - { - EditorGUILayout.PrefixLabel(label, followingStyle, EditorStyles.label); - } - public static void PrefixLabel(GUIContent label, GUIStyle followingStyle, GUIStyle labelStyle) - { - EditorGUILayout.PrefixLabelInternal(label, followingStyle, labelStyle); - } } } diff --git a/UnityEditor/UnityEditor/EditorGUIUtility.cs b/UnityEditor/UnityEditor/EditorGUIUtility.cs index a52a8cf6..cbfeb610 100644 --- a/UnityEditor/UnityEditor/EditorGUIUtility.cs +++ b/UnityEditor/UnityEditor/EditorGUIUtility.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using UnityEditorInternal; using UnityEngine; +using UnityEngine.Audio; using UnityEngine.Internal; using UnityEngineInternal; namespace UnityEditor @@ -14,6 +15,7 @@ public sealed class EditorGUIUtility : GUIUtility private static Texture2D s_InfoIcon; private static Texture2D s_WarningIcon; private static Texture2D s_ErrorIcon; + internal static SliderLabels sliderLabels; internal static Color kDarkViewBackground; private static GUIContent s_ObjectContent; private static GUIContent s_Text; @@ -238,6 +240,7 @@ internal static EventType rotateGestureEventType static EditorGUIUtility() { EditorGUIUtility.s_FontIsBold = -1; + EditorGUIUtility.sliderLabels = default(SliderLabels); EditorGUIUtility.kDarkViewBackground = new Color(0.22f, 0.22f, 0.22f, 0f); EditorGUIUtility.s_ObjectContent = new GUIContent(); EditorGUIUtility.s_Text = new GUIContent(); @@ -401,7 +404,21 @@ public static GUIContent ObjectContent(UnityEngine.Object obj, Type type) { if (obj) { - EditorGUIUtility.s_ObjectContent.text = obj.name; + if (obj is AudioMixerGroup) + { + EditorGUIUtility.s_ObjectContent.text = obj.name + " (" + ((AudioMixerGroup)obj).audioMixer.name + ")"; + } + else + { + if (obj is AudioMixerSnapshot) + { + EditorGUIUtility.s_ObjectContent.text = obj.name + " (" + ((AudioMixerSnapshot)obj).audioMixer.name + ")"; + } + else + { + EditorGUIUtility.s_ObjectContent.text = obj.name; + } + } EditorGUIUtility.s_ObjectContent.image = AssetPreview.GetMiniThumbnail(obj); } else @@ -573,7 +590,7 @@ private static UnityEngine.Object Load(string filename, Type type) { return @object; } - return EditorGUIUtility.GetEditorAssetBundle().Load(filename, type); + return EditorGUIUtility.GetEditorAssetBundle().LoadAsset(filename, type); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -671,17 +688,21 @@ internal static void ResetGUIState() EditorGUIUtility.wideMode = false; ScriptAttributeUtility.propertyHandlerCache = null; } - public static void RenderGameViewCameras(Rect cameraRect, bool gizmos, bool gui) + public static void RenderGameViewCameras(Rect cameraRect, int targetDisplay, bool gizmos, bool gui) { - EditorGUIUtility.INTERNAL_CALL_RenderGameViewCameras(ref cameraRect, gizmos, gui); + EditorGUIUtility.INTERNAL_CALL_RenderGameViewCameras(ref cameraRect, targetDisplay, gizmos, gui); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_RenderGameViewCameras(ref Rect cameraRect, bool gizmos, bool gui); + private static extern void INTERNAL_CALL_RenderGameViewCameras(ref Rect cameraRect, int targetDisplay, bool gizmos, bool gui); + public static void RenderGameViewCameras(Rect cameraRect, bool gizmos, bool gui) + { + EditorGUIUtility.RenderGameViewCameras(cameraRect, 0, gizmos, gui); + } [Obsolete("Use version without the statsRect (it is not used anymore)")] public static void RenderGameViewCameras(Rect cameraRect, Rect statsRect, bool gizmos, bool gui) { - EditorGUIUtility.RenderGameViewCameras(cameraRect, gizmos, gui); + EditorGUIUtility.RenderGameViewCameras(cameraRect, 0, gizmos, gui); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1048,6 +1069,42 @@ private static void Internal_AddCursorRect(Rect r, MouseCursor m, int controlID) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_Internal_AddCursorRect(ref Rect r, MouseCursor m, int controlID); + internal static Rect HandleHorizontalSplitter(Rect dragRect, float width, float minLeftSide, float minRightSide) + { + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(dragRect, MouseCursor.SplitResizeLeftRight); + } + float num = 0f; + float x = EditorGUI.MouseDeltaReader(dragRect, true).x; + if (x != 0f) + { + dragRect.x += x; + num = Mathf.Clamp(dragRect.x, minLeftSide, width - minRightSide); + } + if (dragRect.x > width - minRightSide) + { + num = width - minRightSide; + } + if (num > 0f) + { + dragRect.x = num; + } + return dragRect; + } + internal static void DrawHorizontalSplitter(Rect dragRect) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + Color color = GUI.color; + Color b = (!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.12f, 0.12f, 0.12f, 1.333f); + GUI.color *= b; + Rect position = new Rect(dragRect.x - 1f, dragRect.y, 1f, dragRect.height); + GUI.DrawTexture(position, EditorGUIUtility.whiteTexture); + GUI.color = color; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CleanCache(string text); diff --git a/UnityEditor/UnityEditor/EditorMaterialUtility.cs b/UnityEditor/UnityEditor/EditorMaterialUtility.cs index e7f15c39..70d5be11 100644 --- a/UnityEditor/UnityEditor/EditorMaterialUtility.cs +++ b/UnityEditor/UnityEditor/EditorMaterialUtility.cs @@ -10,6 +10,9 @@ public sealed class EditorMaterialUtility public static extern void ResetDefaultTextures(Material material, bool overrideSetTextures); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsBackgroundMaterial(Material material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetShaderDefaults(Shader shader, string[] name, Texture[] textures); } } diff --git a/UnityEditor/UnityEditor/EditorPluginImporterExtension.cs b/UnityEditor/UnityEditor/EditorPluginImporterExtension.cs new file mode 100644 index 00000000..42eb3564 --- /dev/null +++ b/UnityEditor/UnityEditor/EditorPluginImporterExtension.cs @@ -0,0 +1,34 @@ +using System; +using UnityEditor.Modules; +namespace UnityEditor +{ + internal class EditorPluginImporterExtension : DefaultPluginImporterExtension + { + internal enum EditorPluginCPUArchitecture + { + AnyCPU, + x86, + x86_64 + } + internal enum EditorPluginOSArchitecture + { + AnyOS, + OSX, + Windows, + Linux + } + private EditorPluginImporterExtension.EditorPluginCPUArchitecture cpu; + private EditorPluginImporterExtension.EditorPluginOSArchitecture os; + public EditorPluginImporterExtension() : base(EditorPluginImporterExtension.GetProperties()) + { + } + private static DefaultPluginImporterExtension.Property[] GetProperties() + { + return new DefaultPluginImporterExtension.Property[] + { + new DefaultPluginImporterExtension.Property(EditorGUIUtility.TextContent("PluginImporter.EditorCPU"), "CPU", EditorPluginImporterExtension.EditorPluginCPUArchitecture.AnyCPU, BuildPipeline.GetEditorTargetName()), + new DefaultPluginImporterExtension.Property(EditorGUIUtility.TextContent("PluginImporter.EditorOS"), "OS", EditorPluginImporterExtension.EditorPluginOSArchitecture.AnyOS, BuildPipeline.GetEditorTargetName()) + }; + } + } +} diff --git a/UnityEditor/UnityEditor/EditorSettings.cs b/UnityEditor/UnityEditor/EditorSettings.cs index 3be1c7d2..413384b6 100644 --- a/UnityEditor/UnityEditor/EditorSettings.cs +++ b/UnityEditor/UnityEditor/EditorSettings.cs @@ -14,6 +14,24 @@ public static extern string unityRemoteDevice [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern string unityRemoteCompression + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string unityRemoteResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern string externalVersionControl { [WrapperlessIcall] diff --git a/UnityEditor/UnityEditor/EditorSettingsInspector.cs b/UnityEditor/UnityEditor/EditorSettingsInspector.cs index 9fd47bee..ad0c157c 100644 --- a/UnityEditor/UnityEditor/EditorSettingsInspector.cs +++ b/UnityEditor/UnityEditor/EditorSettingsInspector.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using UnityEditor.Hardware; using UnityEditor.VersionControl; using UnityEditorInternal; using UnityEngine; @@ -9,52 +11,58 @@ internal class EditorSettingsInspector : Editor { private struct PopupElement { - public readonly bool requiresTeamLicense; + public readonly string id; public readonly bool requiresProLicense; public readonly GUIContent content; public bool Enabled { get { - return (!this.requiresTeamLicense || InternalEditorUtility.HasMaint()) && (!this.requiresProLicense || InternalEditorUtility.HasPro()); + return !this.requiresProLicense || InternalEditorUtility.HasPro(); } } - public PopupElement(string content, bool requiresTeamLicense, bool requiresProLicense) + public PopupElement(string content, bool requiresProLicense) { + this.id = content; this.content = new GUIContent(content); - this.requiresTeamLicense = requiresTeamLicense; this.requiresProLicense = requiresProLicense; } } private EditorSettingsInspector.PopupElement[] vcDefaultPopupList = new EditorSettingsInspector.PopupElement[] { - new EditorSettingsInspector.PopupElement(ExternalVersionControl.Disabled, false, false), - new EditorSettingsInspector.PopupElement(ExternalVersionControl.Generic, false, false), - new EditorSettingsInspector.PopupElement(ExternalVersionControl.AssetServer, true, false) + new EditorSettingsInspector.PopupElement(ExternalVersionControl.Disabled, false), + new EditorSettingsInspector.PopupElement(ExternalVersionControl.Generic, false), + new EditorSettingsInspector.PopupElement(ExternalVersionControl.AssetServer, true) }; private EditorSettingsInspector.PopupElement[] vcPopupList; private EditorSettingsInspector.PopupElement[] serializationPopupList = new EditorSettingsInspector.PopupElement[] { - new EditorSettingsInspector.PopupElement("Mixed", false, false), - new EditorSettingsInspector.PopupElement("Force Binary", false, false), - new EditorSettingsInspector.PopupElement("Force Text", false, false) - }; - private EditorSettingsInspector.PopupElement[] remoteDeviceList = new EditorSettingsInspector.PopupElement[] - { - new EditorSettingsInspector.PopupElement("None", false, false), - new EditorSettingsInspector.PopupElement("Any Android Device", false, false), - new EditorSettingsInspector.PopupElement("Any iOS Device", false, false) + new EditorSettingsInspector.PopupElement("Mixed", false), + new EditorSettingsInspector.PopupElement("Force Binary", false), + new EditorSettingsInspector.PopupElement("Force Text", false) }; private EditorSettingsInspector.PopupElement[] behaviorPopupList = new EditorSettingsInspector.PopupElement[] { - new EditorSettingsInspector.PopupElement("3D", false, false), - new EditorSettingsInspector.PopupElement("2D", false, false) + new EditorSettingsInspector.PopupElement("3D", false), + new EditorSettingsInspector.PopupElement("2D", false) }; private EditorSettingsInspector.PopupElement[] spritePackerPopupList = new EditorSettingsInspector.PopupElement[] { - new EditorSettingsInspector.PopupElement("Disabled", false, false), - new EditorSettingsInspector.PopupElement("Enabled For Builds", false, false), - new EditorSettingsInspector.PopupElement("Always Enabled", false, false) + new EditorSettingsInspector.PopupElement("Disabled", false), + new EditorSettingsInspector.PopupElement("Enabled For Builds", false), + new EditorSettingsInspector.PopupElement("Always Enabled", false) + }; + private EditorSettingsInspector.PopupElement[] remoteDevicePopupList; + private DevDevice[] remoteDeviceList; + private EditorSettingsInspector.PopupElement[] remoteCompressionList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("JPEG", false), + new EditorSettingsInspector.PopupElement("PNG", false) + }; + private EditorSettingsInspector.PopupElement[] remoteResolutionList = new EditorSettingsInspector.PopupElement[] + { + new EditorSettingsInspector.PopupElement("Normal", false), + new EditorSettingsInspector.PopupElement("Downsize", false) }; private string[] logLevelPopupList = new string[] { @@ -63,6 +71,12 @@ public PopupElement(string content, bool requiresTeamLicense, bool requiresProLi "Notice", "Fatal" }; + private string[] semanticMergePopupList = new string[] + { + "Off", + "Premerge", + "Ask" + }; public void OnEnable() { Plugin[] availablePlugins = Plugin.availablePlugins; @@ -72,10 +86,42 @@ public void OnEnable() int i = this.vcDefaultPopupList.Length; while (i < this.vcPopupList.Length) { - this.vcPopupList[i] = new EditorSettingsInspector.PopupElement(availablePlugins[num].name, true, false); + this.vcPopupList[i] = new EditorSettingsInspector.PopupElement(availablePlugins[num].name, true); i++; num++; } + DevDeviceList.Changed += new DevDeviceList.OnChangedHandler(this.OnDeviceListChanged); + this.BuildRemoteDeviceList(); + } + public void OnDisable() + { + DevDeviceList.Changed -= new DevDeviceList.OnChangedHandler(this.OnDeviceListChanged); + } + private void OnDeviceListChanged() + { + this.BuildRemoteDeviceList(); + } + private void BuildRemoteDeviceList() + { + List list = new List(); + List list2 = new List(); + list.Add(DevDevice.none); + list2.Add(new EditorSettingsInspector.PopupElement("None", false)); + list.Add(new DevDevice("Any Android Device", "Any Android Device", "Android", "Android", DevDeviceState.Connected, DevDeviceFeatures.RemoteConnection)); + list2.Add(new EditorSettingsInspector.PopupElement("Any Android Device", false)); + DevDevice[] devices = DevDeviceList.GetDevices(); + for (int i = 0; i < devices.Length; i++) + { + DevDevice item = devices[i]; + bool flag = (item.features & DevDeviceFeatures.RemoteConnection) != DevDeviceFeatures.None; + if (item.isConnected && flag) + { + list.Add(item); + list2.Add(new EditorSettingsInspector.PopupElement(item.name, false)); + } + } + this.remoteDeviceList = list.ToArray(); + this.remoteDevicePopupList = list2.ToArray(); } public override void OnInspectorGUI() { @@ -195,6 +241,7 @@ public override void OnInspectorGUI() } } GUI.enabled = enabled; + EditorUserSettings.semanticMergeMode = (SemanticMergeMode)EditorGUILayout.Popup("Smart merge", (int)EditorUserSettings.semanticMergeMode, this.semanticMergePopupList, new GUILayoutOption[0]); this.DrawOverlayDescriptions(); } GUILayout.Space(10f); @@ -240,26 +287,57 @@ public override void OnInspectorGUI() this.DoPopup(rect, this.spritePackerPopupList, num4, new GenericMenu.MenuFunction2(this.SetSpritePackerMode)); } } + private static int GetIndexById(DevDevice[] elements, string id, int defaultIndex) + { + for (int i = 0; i < elements.Length; i++) + { + if (elements[i].id == id) + { + return i; + } + } + return defaultIndex; + } + private static int GetIndexById(EditorSettingsInspector.PopupElement[] elements, string id, int defaultIndex) + { + for (int i = 0; i < elements.Length; i++) + { + if (elements[i].id == id) + { + return i; + } + } + return defaultIndex; + } private void ShowUnityRemoteGUI(bool editorEnabled) { GUI.enabled = true; GUILayout.Label("Unity Remote", EditorStyles.boldLabel, new GUILayoutOption[0]); GUI.enabled = editorEnabled; string unityRemoteDevice = EditorSettings.unityRemoteDevice; - int num = 0; - for (int i = 0; i < this.remoteDeviceList.Length; i++) - { - if (this.remoteDeviceList[i].content.text == unityRemoteDevice) - { - num = i; - } - } - GUIContent content = new GUIContent(this.remoteDeviceList[num].content); + int indexById = EditorSettingsInspector.GetIndexById(this.remoteDeviceList, unityRemoteDevice, 0); + GUIContent content = new GUIContent(this.remoteDevicePopupList[indexById].content); Rect rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Device")); if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) { - this.DoPopup(rect, this.remoteDeviceList, num, new GenericMenu.MenuFunction2(this.SetUnityRemoteDevice)); + this.DoPopup(rect, this.remoteDevicePopupList, indexById, new GenericMenu.MenuFunction2(this.SetUnityRemoteDevice)); + } + int indexById2 = EditorSettingsInspector.GetIndexById(this.remoteCompressionList, EditorSettings.unityRemoteCompression, 0); + content = new GUIContent(this.remoteCompressionList[indexById2].content); + rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Compression")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.remoteCompressionList, indexById2, new GenericMenu.MenuFunction2(this.SetUnityRemoteCompression)); + } + int indexById3 = EditorSettingsInspector.GetIndexById(this.remoteResolutionList, EditorSettings.unityRemoteResolution, 0); + content = new GUIContent(this.remoteResolutionList[indexById3].content); + rect = GUILayoutUtility.GetRect(content, EditorStyles.popup); + rect = EditorGUI.PrefixLabel(rect, 0, new GUIContent("Resolution")); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Passive, EditorStyles.popup)) + { + this.DoPopup(rect, this.remoteResolutionList, indexById3, new GenericMenu.MenuFunction2(this.SetUnityRemoteResolution)); } } private void DrawOverlayDescriptions() @@ -271,17 +349,23 @@ private void DrawOverlayDescriptions() } GUILayout.Space(10f); GUILayout.Label("Overlay legends", EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); this.DrawOverlayDescription(Asset.States.Local); this.DrawOverlayDescription(Asset.States.OutOfSync); this.DrawOverlayDescription(Asset.States.CheckedOutLocal); this.DrawOverlayDescription(Asset.States.CheckedOutRemote); this.DrawOverlayDescription(Asset.States.DeletedLocal); this.DrawOverlayDescription(Asset.States.DeletedRemote); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); this.DrawOverlayDescription(Asset.States.AddedLocal); this.DrawOverlayDescription(Asset.States.AddedRemote); this.DrawOverlayDescription(Asset.States.Conflicted); this.DrawOverlayDescription(Asset.States.LockedLocal); this.DrawOverlayDescription(Asset.States.LockedRemote); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); } private void DrawOverlayDescription(Asset.States state) { @@ -358,7 +442,15 @@ private void SetAssetSerializationMode(object data) } private void SetUnityRemoteDevice(object data) { - EditorSettings.unityRemoteDevice = this.remoteDeviceList[(int)data].content.text; + EditorSettings.unityRemoteDevice = this.remoteDeviceList[(int)data].id; + } + private void SetUnityRemoteCompression(object data) + { + EditorSettings.unityRemoteCompression = this.remoteCompressionList[(int)data].id; + } + private void SetUnityRemoteResolution(object data) + { + EditorSettings.unityRemoteResolution = this.remoteResolutionList[(int)data].id; } private void SetDefaultBehaviorMode(object data) { diff --git a/UnityEditor/UnityEditor/EditorStyles.cs b/UnityEditor/UnityEditor/EditorStyles.cs index fa4e4e70..8071ff50 100644 --- a/UnityEditor/UnityEditor/EditorStyles.cs +++ b/UnityEditor/UnityEditor/EditorStyles.cs @@ -27,6 +27,7 @@ public sealed class EditorStyles private GUIStyle m_Popup; private GUIStyle m_ObjectField; private GUIStyle m_ObjectFieldThumb; + private GUIStyle m_ObjectFieldMiniThumb; private GUIStyle m_ColorField; private GUIStyle m_LayerMaskField; private GUIStyle m_Toggle; @@ -34,6 +35,8 @@ public sealed class EditorStyles private GUIStyle m_Foldout; private GUIStyle m_FoldoutPreDrop; private GUIStyle m_ToggleGroup; + private GUIStyle m_TextFieldDropDown; + private GUIStyle m_TextFieldDropDownText; internal Font m_StandardFont; internal Font m_BoldFont; internal Font m_MiniFont; @@ -45,6 +48,7 @@ public sealed class EditorStyles private GUIStyle m_ToolbarTextField; private GUIStyle m_InspectorDefaultMargins; private GUIStyle m_InspectorFullWidthMargins; + private GUIStyle m_HelpBox; private GUIStyle m_ToolbarSearchField; private GUIStyle m_ToolbarSearchFieldPopup; private GUIStyle m_ToolbarSearchFieldCancelButton; @@ -54,9 +58,9 @@ public sealed class EditorStyles private GUIStyle m_InspectorTitlebar; private GUIStyle m_InspectorTitlebarText; private GUIStyle m_FoldoutSelected; + private GUIStyle m_Tooltip; private GUIStyle m_NotificationText; private GUIStyle m_NotificationBackground; - private GUIStyle m_HelpBox; private GUIStyle m_AssetLabel; private GUIStyle m_AssetLabelPartial; private GUIStyle m_AssetLabelIcon; @@ -65,9 +69,12 @@ public sealed class EditorStyles private GUIStyle m_SearchFieldCancelButtonEmpty; private GUIStyle m_SelectionRect; private GUIStyle m_MinMaxHorizontalSliderThumb; + private GUIStyle m_DropDownList; private GUIStyle m_ProgressBarBar; private GUIStyle m_ProgressBarText; private GUIStyle m_ProgressBarBack; + private Vector2 m_KnobSize = new Vector2(40f, 40f); + private Vector2 m_MiniKnobSize = new Vector2(29f, 29f); internal static EditorStyles s_Current; private static EditorStyles[] s_CachedStyles = new EditorStyles[2]; public static GUIStyle label @@ -239,6 +246,13 @@ public static GUIStyle objectFieldThumb return EditorStyles.s_Current.m_ObjectFieldThumb; } } + public static GUIStyle objectFieldMiniThumb + { + get + { + return EditorStyles.s_Current.m_ObjectFieldMiniThumb; + } + } public static GUIStyle colorField { get @@ -288,6 +302,20 @@ public static GUIStyle toggleGroup return EditorStyles.s_Current.m_ToggleGroup; } } + internal static GUIStyle textFieldDropDown + { + get + { + return EditorStyles.s_Current.m_TextFieldDropDown; + } + } + internal static GUIStyle textFieldDropDownText + { + get + { + return EditorStyles.s_Current.m_TextFieldDropDownText; + } + } public static Font standardFont { get @@ -365,6 +393,13 @@ public static GUIStyle inspectorFullWidthMargins return EditorStyles.s_Current.m_InspectorFullWidthMargins; } } + public static GUIStyle helpBox + { + get + { + return EditorStyles.s_Current.m_HelpBox; + } + } internal static GUIStyle toolbarSearchField { get @@ -428,25 +463,25 @@ internal static GUIStyle foldoutSelected return EditorStyles.s_Current.m_FoldoutSelected; } } - internal static GUIStyle notificationText + internal static GUIStyle tooltip { get { - return EditorStyles.s_Current.m_NotificationText; + return EditorStyles.s_Current.m_Tooltip; } } - internal static GUIStyle notificationBackground + internal static GUIStyle notificationText { get { - return EditorStyles.s_Current.m_NotificationBackground; + return EditorStyles.s_Current.m_NotificationText; } } - internal static GUIStyle helpBox + internal static GUIStyle notificationBackground { get { - return EditorStyles.s_Current.m_HelpBox; + return EditorStyles.s_Current.m_NotificationBackground; } } internal static GUIStyle assetLabel @@ -505,6 +540,13 @@ internal static GUIStyle minMaxHorizontalSliderThumb return EditorStyles.s_Current.m_MinMaxHorizontalSliderThumb; } } + internal static GUIStyle dropDownList + { + get + { + return EditorStyles.s_Current.m_DropDownList; + } + } internal static GUIStyle progressBarBack { get @@ -526,6 +568,20 @@ internal static GUIStyle progressBarText return EditorStyles.s_Current.m_ProgressBarText; } } + internal static Vector2 knobSize + { + get + { + return EditorStyles.s_Current.m_KnobSize; + } + } + internal static Vector2 miniKnobSize + { + get + { + return EditorStyles.s_Current.m_MiniKnobSize; + } + } internal static void UpdateSkinCache() { EditorStyles.UpdateSkinCache(EditorGUIUtility.skinIndex); @@ -583,6 +639,7 @@ private void InitSharedStyles() this.m_AssetLabelIcon = this.GetStyle("AssetLabel Icon"); this.m_SelectionRect = this.GetStyle("selectionRect"); this.m_MinMaxHorizontalSliderThumb = this.GetStyle("MinMaxHorizontalSliderThumb"); + this.m_DropDownList = this.GetStyle("DropDownButton"); this.m_BoldFont = this.GetStyle("BoldLabel").font; this.m_StandardFont = this.GetStyle("Label").font; this.m_MiniFont = this.GetStyle("MiniLabel").font; @@ -594,6 +651,7 @@ private void InitSharedStyles() this.m_InspectorTitlebar = this.GetStyle("IN Title"); this.m_InspectorTitlebarText = this.GetStyle("IN TitleText"); this.m_ToggleGroup = this.GetStyle("BoldToggle"); + this.m_Tooltip = this.GetStyle("Tooltip"); this.m_NotificationText = this.GetStyle("NotificationText"); this.m_NotificationBackground = this.GetStyle("NotificationBackground"); this.m_Popup = (this.m_LayerMaskField = this.GetStyle("MiniPopup")); @@ -601,11 +659,14 @@ private void InitSharedStyles() this.m_Label = this.GetStyle("ControlLabel"); this.m_ObjectField = this.GetStyle("ObjectField"); this.m_ObjectFieldThumb = this.GetStyle("ObjectFieldThumb"); + this.m_ObjectFieldMiniThumb = this.GetStyle("ObjectFieldMiniThumb"); this.m_Toggle = this.GetStyle("Toggle"); this.m_ToggleMixed = this.GetStyle("ToggleMixed"); this.m_ColorField = this.GetStyle("ColorField"); this.m_Foldout = this.GetStyle("Foldout"); this.m_FoldoutSelected = GUIStyle.none; + this.m_TextFieldDropDown = this.GetStyle("TextFieldDropDown"); + this.m_TextFieldDropDownText = this.GetStyle("TextFieldDropDownText"); this.m_TextArea = new GUIStyle(this.m_TextField); this.m_TextArea.wordWrap = true; this.m_InspectorDefaultMargins = new GUIStyle(); diff --git a/UnityEditor/UnityEditor/EditorUserBuildSettings.cs b/UnityEditor/UnityEditor/EditorUserBuildSettings.cs index e8146915..58c4162f 100644 --- a/UnityEditor/UnityEditor/EditorUserBuildSettings.cs +++ b/UnityEditor/UnityEditor/EditorUserBuildSettings.cs @@ -24,7 +24,7 @@ public static extern BuildTarget selectedStandaloneTarget [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern FlashBuildSubtarget flashBuildSubtarget + public static extern PSMBuildSubtarget psmBuildSubtarget { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -42,6 +42,15 @@ public static extern PSP2BuildSubtarget psp2BuildSubtarget [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern PS4BuildSubtarget ps4BuildSubtarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern SCEBuildSubtarget sceBuildSubtarget { [WrapperlessIcall] @@ -60,6 +69,33 @@ public static extern bool explicitNullChecks [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool needSubmissionMaterials + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool compressWithPsArc + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool forceInstallation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool enableHeadlessMode { [WrapperlessIcall] @@ -69,6 +105,15 @@ public static extern bool enableHeadlessMode [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool buildScriptsOnly + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern XboxBuildSubtarget xboxBuildSubtarget { [WrapperlessIcall] @@ -87,7 +132,7 @@ public static extern XboxRunMethod xboxRunMethod [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern AndroidBuildSubtarget androidBuildSubtarget + public static extern int streamingInstallLaunchRange { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -96,7 +141,7 @@ public static extern AndroidBuildSubtarget androidBuildSubtarget [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern BuildTarget selectedMetroTarget + public static extern XboxOneDeployMethod xboxOneDeployMethod { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -105,7 +150,7 @@ public static extern BuildTarget selectedMetroTarget [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern MetroBuildType metroBuildType + public static extern MobileTextureSubtarget androidBuildSubtarget { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -114,7 +159,7 @@ public static extern MetroBuildType metroBuildType [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern MetroSDK metroSDK + public static extern WSASDK wsaSDK { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -123,7 +168,7 @@ public static extern MetroSDK metroSDK [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern MetroBuildAndRunDeployTarget metroBuildAndRunDeployTarget + public static extern WSABuildAndRunDeployTarget wsaBuildAndRunDeployTarget { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -132,7 +177,7 @@ public static extern MetroBuildAndRunDeployTarget metroBuildAndRunDeployTarget [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern bool metroGenerateReferenceProjects + public static extern bool wsaGenerateReferenceProjects { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -141,7 +186,7 @@ public static extern bool metroGenerateReferenceProjects [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern BlackBerryBuildSubtarget blackberryBuildSubtarget + public static extern MobileTextureSubtarget blackberryBuildSubtarget { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -159,7 +204,7 @@ public static extern BlackBerryBuildType blackberryBuildType [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern TizenBuildSubtarget tizenBuildSubtarget + public static extern MobileTextureSubtarget tizenBuildSubtarget { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -216,6 +261,15 @@ public static extern bool development [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern int webGLOptimizationLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool connectProfiler { [WrapperlessIcall] @@ -234,7 +288,7 @@ public static extern bool allowDebugging [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern bool appendProject + public static extern bool exportAsGoogleAndroidProject { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/EditorUserSettings.cs b/UnityEditor/UnityEditor/EditorUserSettings.cs index cac46898..b136bbe2 100644 --- a/UnityEditor/UnityEditor/EditorUserSettings.cs +++ b/UnityEditor/UnityEditor/EditorUserSettings.cs @@ -50,6 +50,15 @@ internal static extern bool DebugCom [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern SemanticMergeMode semanticMergeMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetConfigValue(string name); diff --git a/UnityEditor/UnityEditor/EditorUtility.cs b/UnityEditor/UnityEditor/EditorUtility.cs index bde5e053..6705e460 100644 --- a/UnityEditor/UnityEditor/EditorUtility.cs +++ b/UnityEditor/UnityEditor/EditorUtility.cs @@ -8,6 +8,21 @@ namespace UnityEditor public sealed class EditorUtility { public delegate void SelectMenuItemFunction(object userData, string[] options, int selected); + public static extern bool audioMasterMute + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool audioProfilingEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RevealInFinder(string path); @@ -16,6 +31,9 @@ public sealed class EditorUtility public static extern void SetDirty(UnityEngine.Object target); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void LoadPlatformSupportModuleNativeDllInternal(string target); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetDirtyIndex(int instanceID); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -48,7 +66,7 @@ public static bool DisplayDialog(string title, string message, string ok) public static extern string SaveFilePanel(string title, string directory, string defaultName, string extension); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string SaveBuildPanel(BuildTarget target, string title, string directory, string defaultName, string extension); + internal static extern string SaveBuildPanel(BuildTarget target, string title, string directory, string defaultName, string extension, out bool updateExistingBuild); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern int NaturalCompare(string a, string b); @@ -109,6 +127,33 @@ public static string GetAssetPath(UnityEngine.Object asset) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern UnityEngine.Object[] CollectDeepHierarchy(UnityEngine.Object[] roots); + internal static void InitInstantiatedPreviewRecursive(GameObject go) + { + go.hideFlags = HideFlags.HideAndDontSave; + go.layer = Camera.PreviewCullingLayer; + foreach (Transform transform in go.transform) + { + EditorUtility.InitInstantiatedPreviewRecursive(transform.gameObject); + } + } + internal static GameObject InstantiateForAnimatorPreview(UnityEngine.Object original) + { + if (original == null) + { + throw new ArgumentException("The prefab you want to instantiate is null."); + } + GameObject gameObject = EditorUtility.InstantiateRemoveAllNonAnimationComponents(original, Vector3.zero, Quaternion.identity) as GameObject; + EditorUtility.InitInstantiatedPreviewRecursive(gameObject); + Animator component = gameObject.GetComponent(); + if (component) + { + component.enabled = false; + component.cullingMode = AnimatorCullingMode.AlwaysAnimate; + component.logWarnings = false; + component.fireEvents = false; + } + return gameObject; + } internal static UnityEngine.Object InstantiateRemoveAllNonAnimationComponents(UnityEngine.Object original, Vector3 position, Quaternion rotation) { if (original == null) @@ -124,12 +169,23 @@ private static UnityEngine.Object Internal_InstantiateRemoveAllNonAnimationCompo [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern UnityEngine.Object INTERNAL_CALL_Internal_InstantiateRemoveAllNonAnimationComponentsSingle(UnityEngine.Object data, ref Vector3 pos, ref Quaternion rot); - [WrapperlessIcall] + [Obsolete("Use EditorUtility.UnloadUnusedAssetsImmediate instead"), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void UnloadUnusedAssets(); - [WrapperlessIcall] + [Obsolete("Use EditorUtility.UnloadUnusedAssetsImmediate instead"), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void UnloadUnusedAssetsIgnoreManagedReferences(); + public static void UnloadUnusedAssetsImmediate() + { + EditorUtility.UnloadUnusedAssetsImmediateInternal(true); + } + public static void UnloadUnusedAssetsImmediate(bool ignoreReferencesFromScript) + { + EditorUtility.UnloadUnusedAssetsImmediateInternal(ignoreReferencesFromScript); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void UnloadUnusedAssetsImmediateInternal(bool ignoreReferencesFromScript); [Obsolete("Use BuildPipeline.BuildAssetBundle instead")] public static bool BuildResourceFile(UnityEngine.Object[] selection, string pathName) { @@ -203,38 +259,52 @@ public static void DisplayCustomMenu(Rect position, GUIContent[] options, int se EditorUtility.DisplayCustomMenu(position, array, selected2, callback, userData); } internal static void DisplayCustomMenu(Rect position, string[] options, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + bool[] separator = new bool[options.Length]; + EditorUtility.DisplayCustomMenuWithSeparators(position, options, separator, selected, callback, userData); + } + internal static void DisplayCustomMenuWithSeparators(Rect position, string[] options, bool[] separator, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) { Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); position.x = vector.x; position.y = vector.y; int[] array = new int[options.Length]; + int[] array2 = new int[options.Length]; for (int i = 0; i < options.Length; i++) { array[i] = 1; + array2[i] = 0; } - EditorUtility.Internal_DisplayCustomMenu(position, options, array, selected, callback, userData); + EditorUtility.Internal_DisplayCustomMenu(position, options, array, array2, selected, callback, userData); EditorUtility.ResetMouseDown(); } internal static void DisplayCustomMenu(Rect position, string[] options, bool[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + { + bool[] separator = new bool[options.Length]; + EditorUtility.DisplayCustomMenuWithSeparators(position, options, enabled, separator, selected, callback, userData); + } + internal static void DisplayCustomMenuWithSeparators(Rect position, string[] options, bool[] enabled, bool[] separator, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) { Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); position.x = vector.x; position.y = vector.y; int[] array = new int[options.Length]; + int[] array2 = new int[options.Length]; for (int i = 0; i < options.Length; i++) { array[i] = ((!enabled[i]) ? 0 : 1); + array2[i] = ((!separator[i]) ? 0 : 1); } - EditorUtility.Internal_DisplayCustomMenu(position, options, array, selected, callback, userData); + EditorUtility.Internal_DisplayCustomMenu(position, options, array, array2, selected, callback, userData); EditorUtility.ResetMouseDown(); } - private static void Internal_DisplayCustomMenu(Rect screenPosition, string[] options, int[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) + private static void Internal_DisplayCustomMenu(Rect screenPosition, string[] options, int[] enabled, int[] separator, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData) { - EditorUtility.INTERNAL_CALL_Internal_DisplayCustomMenu(ref screenPosition, options, enabled, selected, callback, userData); + EditorUtility.INTERNAL_CALL_Internal_DisplayCustomMenu(ref screenPosition, options, enabled, separator, selected, callback, userData); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Internal_DisplayCustomMenu(ref Rect screenPosition, string[] options, int[] enabled, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData); + private static extern void INTERNAL_CALL_Internal_DisplayCustomMenu(ref Rect screenPosition, string[] options, int[] enabled, int[] separator, int[] selected, EditorUtility.SelectMenuItemFunction callback, object userData); internal static void ResetMouseDown() { Tools.s_ButtonDown = -1; @@ -246,9 +316,13 @@ internal static void ResetMouseDown() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void FocusProjectWindow(); + public static string FormatBytes(int bytes) + { + return EditorUtility.FormatBytes((long)bytes); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string FormatBytes(int bytes); + public static extern string FormatBytes(long bytes); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DisplayProgressBar(string title, string info, float progress); @@ -299,7 +373,7 @@ public static string[] CompileCSharp(string[] sources, string[] references, stri public static extern void OpenWithDefaultApp(string fileName); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool MetroCreateTestCertificate(string path, string publisher, string password, bool overwrite); + internal static extern bool WSACreateTestCertificate(string path, string publisher, string password, bool overwrite); [Obsolete("Use PrefabUtility.InstantiatePrefab")] public static UnityEngine.Object InstantiatePrefab(UnityEngine.Object target) { @@ -351,5 +425,8 @@ public static bool ResetToPrefabState(UnityEngine.Object source) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetInvalidFilenameChars(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetActiveNativePlatformSupportModuleName(); } } diff --git a/UnityEditor/UnityEditor/EditorWindow.cs b/UnityEditor/UnityEditor/EditorWindow.cs index 82c25d5f..9e660157 100644 --- a/UnityEditor/UnityEditor/EditorWindow.cs +++ b/UnityEditor/UnityEditor/EditorWindow.cs @@ -363,6 +363,7 @@ internal void MakeParentsSettingsMatchMe() { return; } + this.m_Parent.SetTitle(base.GetType().FullName); this.m_Parent.autoRepaintOnSceneChange = this.m_AutoRepaintOnSceneChange; bool flag = this.m_Parent.antiAlias != this.m_AntiAlias || this.m_Parent.depthBufferBits != this.m_DepthBufferBits; this.m_Parent.antiAlias = this.m_AntiAlias; @@ -743,7 +744,7 @@ internal Rect GetCurrentGameViewRect() internal void SetInternalGameViewRect(Rect rect) { this.m_GameViewRect = rect; - this.MakeParentsSettingsMatchMe(); + this.m_Parent.SetInternalGameViewRect(this.m_GameViewRect); } public bool SendEvent(Event e) { @@ -764,6 +765,7 @@ internal static void CreateNewWindowForEditorWindow(EditorWindow window, Vector2 Rect position = window.m_Parent.borderSize.Add(new Rect(screenPosition.x, screenPosition.y, window.position.width, window.position.height)); containerWindow.position = position; splitView.position = new Rect(0f, 0f, position.width, position.height); + window.MakeParentsSettingsMatchMe(); containerWindow.Show(ShowMode.NormalWindow, loadPosition, showImmediately); containerWindow.OnResize(); } diff --git a/UnityEditor/UnityEditor/Effector2DEditor.cs b/UnityEditor/UnityEditor/Effector2DEditor.cs new file mode 100644 index 00000000..f171f0b3 --- /dev/null +++ b/UnityEditor/UnityEditor/Effector2DEditor.cs @@ -0,0 +1,54 @@ +using System; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(Effector2D), true)] + internal class Effector2DEditor : Editor + { + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + Effector2D effector2D = this.target as Effector2D; + if (effector2D.GetComponents().Any((Collider2D collider) => collider.enabled && collider.usedByEffector)) + { + return; + } + if (effector2D.requiresCollider) + { + EditorGUILayout.HelpBox("This effector will not function until there is at least one enabled 2D collider with 'Used by Effector' checked on this GameObject.", MessageType.Warning); + } + else + { + EditorGUILayout.HelpBox("This effector can optionally work without a 2D collider.", MessageType.Info); + } + } + public static void CheckEffectorWarnings(Collider2D collider) + { + if (!collider.usedByEffector) + { + return; + } + Effector2D component = collider.GetComponent(); + if (component == null || !component.enabled) + { + EditorGUILayout.HelpBox("This collider will not function with an effector until there is at least one enabled 2D effector on this GameObject.", MessageType.Warning); + if (component == null) + { + return; + } + } + if (component.designedForNonTrigger && collider.isTrigger) + { + EditorGUILayout.HelpBox("This collider has 'Is Trigger' checked but this should be unchecked when used with the '" + component.GetType().Name + "' component which is designed to work with collisions.", MessageType.Warning); + } + else + { + if (component.designedForTrigger && !collider.isTrigger) + { + EditorGUILayout.HelpBox("This collider has 'Is Trigger' unchecked but this should be checked when used with the '" + component.GetType().Name + "' component which is designed to work with triggers.", MessageType.Warning); + } + } + } + } +} diff --git a/UnityEditor/UnityEditor/EventManipulationHandler.cs b/UnityEditor/UnityEditor/EventManipulationHandler.cs index 31856dd6..c93515e3 100644 --- a/UnityEditor/UnityEditor/EventManipulationHandler.cs +++ b/UnityEditor/UnityEditor/EventManipulationHandler.cs @@ -174,7 +174,7 @@ private void CheckRectsOnMouseMove(Rect eventLineRect, AnimationEvent[] events, { this.m_HoverEvent = i; this.m_InstantTooltipText = events[this.m_HoverEvent].functionName; - this.m_InstantTooltipPoint = new Vector2(hitRects[this.m_HoverEvent].xMin + (float)((int)(hitRects[this.m_HoverEvent].width / 2f)) + eventLineRect.x, eventLineRect.yMax); + this.m_InstantTooltipPoint = new Vector2(mousePosition.x, mousePosition.y); } } } @@ -190,14 +190,12 @@ public void DrawInstantTooltip(Rect window) { GUIStyle gUIStyle = "AnimationEventTooltip"; Vector2 vector = gUIStyle.CalcSize(new GUIContent(this.m_InstantTooltipText)); - Rect position = new Rect(this.m_InstantTooltipPoint.x - vector.x * 0.5f + 30f, this.m_InstantTooltipPoint.y + 24f, vector.x, vector.y); + Rect position = new Rect(window.x + this.m_InstantTooltipPoint.x, window.y + this.m_InstantTooltipPoint.y, vector.x, vector.y); if (position.xMax > window.width) { position.x = window.width - position.width; } GUI.Label(position, this.m_InstantTooltipText, gUIStyle); - position = new Rect(this.m_InstantTooltipPoint.x - 30f, this.m_InstantTooltipPoint.y, 7f, 25f); - GUI.Label(position, string.Empty, "AnimationEventTooltipArrow"); } } private bool DeleteEvents(ref AnimationEvent[] eventList, bool[] deleteIndices) diff --git a/UnityEditor/UnityEditor/EyeDropper.cs b/UnityEditor/UnityEditor/EyeDropper.cs index cc6c7939..3417754a 100644 --- a/UnityEditor/UnityEditor/EyeDropper.cs +++ b/UnityEditor/UnityEditor/EyeDropper.cs @@ -114,8 +114,8 @@ private void OnGUI() if (Event.current.button == 0) { EyeDropper.s_PickCoordinates = GUIUtility.GUIToScreenPoint(Event.current.mousePosition); - EyeDropper.s_LastPickedColor = EyeDropper.GetPickedColor(); base.window.Close(); + EyeDropper.s_LastPickedColor = EyeDropper.GetPickedColor(); this.SendEvent("EyeDropperClicked"); } break; diff --git a/UnityEditor/UnityEditor/FileUtil.cs b/UnityEditor/UnityEditor/FileUtil.cs index 5906dfc9..9a8c2386 100644 --- a/UnityEditor/UnityEditor/FileUtil.cs +++ b/UnityEditor/UnityEditor/FileUtil.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; @@ -9,74 +8,103 @@ namespace UnityEditor { public sealed class FileUtil { - internal static ArrayList ReadAllText(string path) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DeleteFileOrDirectory(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyFileOrDirectory(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CopyFileOrDirectoryFollowSymlinks(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void MoveFileOrDirectory(string from, string to); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUniqueTempPathInProject(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetActualPathName(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetProjectRelativePath(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetLastPathNameComponent(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string DeleteLastPathNameComponent(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPathExtension(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPathWithoutExtension(string path); + public static void ReplaceFile(string src, string dst) { - ArrayList arrayList = new ArrayList(); - using (StreamReader streamReader = File.OpenText(FileUtil.NiceWinPath(path))) + if (File.Exists(dst)) { - string value = string.Empty; - while ((value = streamReader.ReadLine()) != null) - { - arrayList.Add(value); - } + FileUtil.DeleteFileOrDirectory(dst); } - return arrayList; + FileUtil.CopyFileOrDirectory(src, dst); } - internal static void WriteAllText(string path, ArrayList strings) + public static void ReplaceDirectory(string src, string dst) { - StreamWriter streamWriter = new StreamWriter(FileUtil.NiceWinPath(path)); - foreach (string value in strings) + if (Directory.Exists(dst)) { - streamWriter.WriteLine(value); + FileUtil.DeleteFileOrDirectory(dst); } - streamWriter.Close(); + FileUtil.CopyFileOrDirectory(src, dst); } internal static void ReplaceText(string path, params string[] input) { - ArrayList arrayList = FileUtil.ReadAllText(path); + path = FileUtil.NiceWinPath(path); + string[] array = File.ReadAllLines(path); for (int i = 0; i < input.Length; i += 2) { - for (int j = 0; j < arrayList.Count; j++) + for (int j = 0; j < array.Length; j++) { - string text = (string)arrayList[j]; - arrayList[j] = text.Replace(input[i], input[i + 1]); + array[j] = array[j].Replace(input[i], input[i + 1]); } } - FileUtil.WriteAllText(path, arrayList); + File.WriteAllLines(path, array); } internal static bool ReplaceTextRegex(string path, params string[] input) { bool result = false; - ArrayList arrayList = FileUtil.ReadAllText(path); + path = FileUtil.NiceWinPath(path); + string[] array = File.ReadAllLines(path); for (int i = 0; i < input.Length; i += 2) { - for (int j = 0; j < arrayList.Count; j++) + for (int j = 0; j < array.Length; j++) { - string text = (string)arrayList[j]; - arrayList[j] = Regex.Replace(text, input[i], input[i + 1]); - if (text != (string)arrayList[j]) + string text = array[j]; + array[j] = Regex.Replace(text, input[i], input[i + 1]); + if (text != array[j]) { result = true; } } } - FileUtil.WriteAllText(path, arrayList); + File.WriteAllLines(path, array); return result; } internal static bool AppendTextAfter(string path, string find, string append) { bool result = false; - ArrayList arrayList = FileUtil.ReadAllText(path); - for (int i = 0; i < arrayList.Count; i++) + path = FileUtil.NiceWinPath(path); + List list = new List(File.ReadAllLines(path)); + for (int i = 0; i < list.Count; i++) { - if (((string)arrayList[i]).IndexOf(find) > -1) + if (list[i].Contains(find)) { - arrayList.Insert(i + 1, append); + list.Insert(i + 1, append); result = true; break; } } - FileUtil.WriteAllText(path, arrayList); + File.WriteAllLines(path, list.ToArray()); return result; } internal static void CopyDirectoryRecursive(string source, string target) @@ -166,6 +194,23 @@ internal static void UnityDirectoryDelete(string path, bool recursive) { Directory.Delete(FileUtil.NiceWinPath(path), recursive); } + internal static void UnityDirectoryRemoveReadonlyAttribute(string target_dir) + { + string[] files = Directory.GetFiles(target_dir); + string[] directories = Directory.GetDirectories(target_dir); + string[] array = files; + for (int i = 0; i < array.Length; i++) + { + string path = array[i]; + File.SetAttributes(path, FileAttributes.Normal); + } + string[] array2 = directories; + for (int j = 0; j < array2.Length; j++) + { + string target_dir2 = array2[j]; + FileUtil.UnityDirectoryRemoveReadonlyAttribute(target_dir2); + } + } internal static void MoveFileIfExists(string src, string dst) { if (File.Exists(src)) @@ -274,51 +319,5 @@ internal static void WalkFilesystemRecursively(string path, Action fileC } } } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool DeleteFileOrDirectory(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CopyFileOrDirectory(string from, string to); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CopyFileOrDirectoryFollowSymlinks(string from, string to); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void MoveFileOrDirectory(string from, string to); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string GetUniqueTempPathInProject(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetActualPathName(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string GetProjectRelativePath(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetLastPathNameComponent(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string DeleteLastPathNameComponent(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetPathExtension(string path); - public static void ReplaceFile(string src, string dst) - { - if (File.Exists(dst)) - { - FileUtil.DeleteFileOrDirectory(dst); - } - FileUtil.CopyFileOrDirectory(src, dst); - } - public static void ReplaceDirectory(string src, string dst) - { - if (Directory.Exists(dst)) - { - FileUtil.DeleteFileOrDirectory(dst); - } - FileUtil.CopyFileOrDirectory(src, dst); - } } } diff --git a/UnityEditor/UnityEditor/FlashBuildSubtarget.cs b/UnityEditor/UnityEditor/FlashBuildSubtarget.cs deleted file mode 100644 index 35e3dffc..00000000 --- a/UnityEditor/UnityEditor/FlashBuildSubtarget.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -namespace UnityEditor -{ - public enum FlashBuildSubtarget - { - Flash11dot2, - Flash11dot3, - Flash11dot4, - Flash11dot5, - Flash11dot6, - Flash11dot7, - Flash11dot8 - } -} diff --git a/UnityEditor/UnityEditor/FlexibleMenu.cs b/UnityEditor/UnityEditor/FlexibleMenu.cs index efdb5e7f..21c131d7 100644 --- a/UnityEditor/UnityEditor/FlexibleMenu.cs +++ b/UnityEditor/UnityEditor/FlexibleMenu.cs @@ -40,7 +40,7 @@ private static void Edit(object userData) private FlexibleMenuModifyItemUI m_ModifyItemUI; private readonly Action m_ItemClickedCallback; private Vector2 m_ScrollPosition = Vector2.zero; - private bool m_ShowAddNewPresetItem = true; + private bool m_ShowAddNewPresetItem; private int m_ShowEditWindowForIndex = -1; private int m_HoverIndex; private int[] m_SeperatorIndices; @@ -64,6 +64,7 @@ public FlexibleMenu(IFlexibleMenuItemProvider itemProvider, int selectionIndex, this.m_ItemClickedCallback = itemClickedCallback; this.m_SeperatorIndices = this.m_ItemProvider.GetSeperatorIndices(); this.selectedIndex = selectionIndex; + this.m_ShowAddNewPresetItem = (this.m_ModifyItemUI != null); } public override Vector2 GetWindowSize() { @@ -118,7 +119,7 @@ public override void OnGUI(Rect rect) current.Use(); } } - goto IL_373; + goto IL_389; case EventType.MouseUp: if (GUIUtility.hotControl == num2) { @@ -129,7 +130,7 @@ public override void OnGUI(Rect rect) current.Use(); } } - goto IL_373; + goto IL_389; case EventType.MouseMove: if (rect2.Contains(current.mousePosition)) { @@ -147,7 +148,7 @@ public override void OnGUI(Rect rect) this.Repaint(); } } - goto IL_373; + goto IL_389; case EventType.MouseDrag: case EventType.KeyDown: case EventType.KeyUp: @@ -155,17 +156,17 @@ public override void OnGUI(Rect rect) IL_109: if (type != EventType.ContextClick) { - goto IL_373; + goto IL_389; } if (rect2.Contains(current.mousePosition)) { current.Use(); - if (this.m_ItemProvider.IsModificationAllowed(i)) + if (this.m_ModifyItemUI != null && this.m_ItemProvider.IsModificationAllowed(i)) { FlexibleMenu.ItemContextMenu.Show(i, this); } } - goto IL_373; + goto IL_389; case EventType.Repaint: { bool isHover = false; @@ -180,7 +181,7 @@ public override void OnGUI(Rect rect) this.m_HoverIndex = -1; } } - if (this.m_ModifyItemUI.IsShowing()) + if (this.m_ModifyItemUI != null && this.m_ModifyItemUI.IsShowing()) { isHover = (this.m_ItemProvider.GetItem(i) == this.m_ModifyItemUI.m_Object); } @@ -194,11 +195,11 @@ public override void OnGUI(Rect rect) { EditorGUIUtility.AddCursorRect(rect2, MouseCursor.ArrowMinus); } - goto IL_373; + goto IL_389; } } goto IL_109; - IL_373: + IL_389: num += 18f; if (flag) { @@ -249,6 +250,10 @@ private void Repaint() } private void CreateNewItemButton(Rect itemRect) { + if (this.m_ModifyItemUI == null) + { + return; + } Rect rect = new Rect(itemRect.x + 25f, itemRect.y, 15f, 15f); if (GUI.Button(rect, FlexibleMenu.s_Styles.plusButtonText, "OL Plus")) { @@ -265,6 +270,10 @@ private void CreateNewItemButton(Rect itemRect) } private void EditExistingItem(Rect itemRect, int index) { + if (this.m_ModifyItemUI == null) + { + return; + } itemRect.y -= itemRect.height; itemRect.x += itemRect.width; this.m_ModifyItemUI.Init(FlexibleMenuModifyItemUI.MenuType.Edit, this.m_ItemProvider.GetItem(index), delegate(object obj) diff --git a/UnityEditor/UnityEditor/FogEditor.cs b/UnityEditor/UnityEditor/FogEditor.cs new file mode 100644 index 00000000..72f3f997 --- /dev/null +++ b/UnityEditor/UnityEditor/FogEditor.cs @@ -0,0 +1,71 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(RenderSettings))] + internal class FogEditor : Editor + { + internal class Styles + { + public static readonly GUIContent fogHeader = EditorGUIUtility.TextContent("RenderSettings.FogHeader"); + public static readonly GUIContent fogWarning = EditorGUIUtility.TextContent("RenderSettings.FogWarning"); + public static readonly GUIContent fogDensity = EditorGUIUtility.TextContent("RenderSettings.FogDensity"); + public static readonly GUIContent fogLinearStart = EditorGUIUtility.TextContent("RenderSettings.FogLinearStart"); + public static readonly GUIContent fogLinearEnd = EditorGUIUtility.TextContent("RenderSettings.FogLinearEnd"); + } + private const string kShowEditorKey = "ShowFogEditorFoldout"; + protected SerializedProperty m_Fog; + protected SerializedProperty m_FogColor; + protected SerializedProperty m_FogMode; + protected SerializedProperty m_FogDensity; + protected SerializedProperty m_LinearFogStart; + protected SerializedProperty m_LinearFogEnd; + private bool m_ShowEditor; + public virtual void OnEnable() + { + this.m_Fog = base.serializedObject.FindProperty("m_Fog"); + this.m_FogColor = base.serializedObject.FindProperty("m_FogColor"); + this.m_FogMode = base.serializedObject.FindProperty("m_FogMode"); + this.m_FogDensity = base.serializedObject.FindProperty("m_FogDensity"); + this.m_LinearFogStart = base.serializedObject.FindProperty("m_LinearFogStart"); + this.m_LinearFogEnd = base.serializedObject.FindProperty("m_LinearFogEnd"); + this.m_ShowEditor = InspectorState.GetBool("ShowFogEditorFoldout", false); + } + public virtual void OnDisable() + { + InspectorState.SetBool("ShowFogEditorFoldout", this.m_ShowEditor); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + this.m_ShowEditor = EditorGUILayout.ToggleTitlebar(this.m_ShowEditor, FogEditor.Styles.fogHeader, this.m_Fog); + if (this.m_ShowEditor) + { + EditorGUI.indentLevel++; + EditorGUI.BeginDisabledGroup(!this.m_Fog.boolValue); + EditorGUILayout.PropertyField(this.m_FogColor, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_FogMode, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + FogMode intValue = (FogMode)this.m_FogMode.intValue; + if (intValue != FogMode.Linear) + { + EditorGUILayout.PropertyField(this.m_FogDensity, FogEditor.Styles.fogDensity, new GUILayoutOption[0]); + } + else + { + EditorGUILayout.PropertyField(this.m_LinearFogStart, FogEditor.Styles.fogLinearStart, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LinearFogEnd, FogEditor.Styles.fogLinearEnd, new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + if (SceneView.GetSceneViewRenderingPath() == RenderingPath.DeferredShading) + { + EditorGUILayout.HelpBox(FogEditor.Styles.fogWarning.text, MessageType.Info); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/FrameDebuggerWindow.cs b/UnityEditor/UnityEditor/FrameDebuggerWindow.cs new file mode 100644 index 00000000..5f276f6c --- /dev/null +++ b/UnityEditor/UnityEditor/FrameDebuggerWindow.cs @@ -0,0 +1,624 @@ +using System; +using System.Collections.Generic; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal class FrameDebuggerWindow : EditorWindow + { + internal class Styles + { + public GUIStyle background = "OL Box"; + public GUIStyle header = "OL title"; + public GUIStyle entryEven = "OL EntryBackEven"; + public GUIStyle entryOdd = "OL EntryBackOdd"; + public GUIStyle rowText = "OL Label"; + public GUIStyle rowTextRight = new GUIStyle("OL Label"); + public GUIContent recordButton = new GUIContent(EditorGUIUtility.TextContent("Profiler.Record")); + public GUIContent prevFrame = new GUIContent(EditorGUIUtility.IconContent("Profiler.PrevFrame")); + public GUIContent nextFrame = new GUIContent(EditorGUIUtility.IconContent("Profiler.NextFrame")); + public GUIContent[] headerContent; + public static readonly string[] s_ColumnNames = new string[] + { + "#", + "Type", + "Vertices", + "Indices" + }; + public static readonly GUIContent[] mrtLabels = new GUIContent[] + { + EditorGUIUtility.TextContent("FrameDebugger.RT0"), + EditorGUIUtility.TextContent("FrameDebugger.RT1"), + EditorGUIUtility.TextContent("FrameDebugger.RT2"), + EditorGUIUtility.TextContent("FrameDebugger.RT3"), + EditorGUIUtility.TextContent("FrameDebugger.RT4"), + EditorGUIUtility.TextContent("FrameDebugger.RT5"), + EditorGUIUtility.TextContent("FrameDebugger.RT6"), + EditorGUIUtility.TextContent("FrameDebugger.RT7") + }; + public static readonly GUIContent depthLabel = EditorGUIUtility.TextContent("FrameDebugger.RTDepth"); + public static readonly GUIContent[] channelLabels = new GUIContent[] + { + EditorGUIUtility.TextContent("FrameDebugger.ChannelsAll"), + EditorGUIUtility.TextContent("FrameDebugger.ChannelsR"), + EditorGUIUtility.TextContent("FrameDebugger.ChannelsG"), + EditorGUIUtility.TextContent("FrameDebugger.ChannelsB"), + EditorGUIUtility.TextContent("FrameDebugger.ChannelsA") + }; + public static readonly GUIContent channelHeader = EditorGUIUtility.TextContent("FrameDebugger.Channels"); + public static readonly GUIContent levelsHeader = EditorGUIUtility.TextContent("FrameDebugger.Levels"); + public Styles() + { + this.rowTextRight.alignment = TextAnchor.MiddleRight; + this.recordButton.text = "Enable"; + this.recordButton.tooltip = "Enable Frame Debugging"; + this.prevFrame.tooltip = "Previous event"; + this.nextFrame.tooltip = "Next event"; + this.headerContent = new GUIContent[FrameDebuggerWindow.Styles.s_ColumnNames.Length]; + for (int i = 0; i < this.headerContent.Length; i++) + { + this.headerContent[i] = EditorGUIUtility.TextContent(FrameDebuggerWindow.Styles.s_ColumnNames[i]); + } + } + } + private const float kScrollbarWidth = 16f; + private const float kResizerWidth = 5f; + private const float kMinListWidth = 200f; + private const float kMinDetailsWidth = 200f; + private const float kMinWindowWidth = 240f; + private const float kDetailsMargin = 4f; + private const float kMinPreviewSize = 64f; + private const int kNeedToRepaintFrames = 4; + public static readonly string[] s_FrameEventTypeNames = new string[] + { + "Clear (nothing)", + "Clear (color)", + "Clear (Z)", + "Clear (color+Z)", + "Clear (stencil)", + "Clear (color+stencil)", + "Clear (Z+stencil)", + "Clear (color+Z+stencil)", + "SetRenderTarget", + "Resolve Color", + "Resolve Depth", + "Grab RenderTexture", + "Static Batch", + "Dynamic Batch", + "Draw Mesh", + "Draw Dynamic", + "Draw GL", + "GPU Skinning", + "Draw Procedural", + "Compute Shader", + "Plugin Event" + }; + [SerializeField] + private float m_ListWidth = 300f; + private int m_RepaintFrames = 4; + private PreviewRenderUtility m_PreviewUtility; + public Vector2 m_PreviewDir = new Vector2(120f, -20f); + private Material m_Material; + private Material m_WireMaterial; + [SerializeField] + private TreeViewState m_TreeViewState; + [NonSerialized] + private FrameDebuggerTreeView m_Tree; + [NonSerialized] + private int m_FrameEventsHash; + [NonSerialized] + private int m_RTIndex; + [NonSerialized] + private int m_RTChannel; + [NonSerialized] + private float m_RTBlackLevel; + [NonSerialized] + private float m_RTWhiteLevel = 1f; + private int m_PrevEventsLimit; + private int m_PrevEventsCount; + private static List s_FrameDebuggers = new List(); + private static FrameDebuggerWindow.Styles ms_Styles; + public static FrameDebuggerWindow.Styles styles + { + get + { + FrameDebuggerWindow.Styles arg_17_0; + if ((arg_17_0 = FrameDebuggerWindow.ms_Styles) == null) + { + arg_17_0 = (FrameDebuggerWindow.ms_Styles = new FrameDebuggerWindow.Styles()); + } + return arg_17_0; + } + } + public FrameDebuggerWindow() + { + base.position = new Rect(50f, 50f, 600f, 350f); + base.minSize = new Vector2(400f, 200f); + } + [MenuItem("Window/Frame Debugger", false, 2100)] + public static FrameDebuggerWindow ShowFrameDebuggerWindow() + { + FrameDebuggerWindow frameDebuggerWindow = EditorWindow.GetWindow(typeof(FrameDebuggerWindow)) as FrameDebuggerWindow; + if (frameDebuggerWindow != null) + { + frameDebuggerWindow.title = "Frame Debug"; + frameDebuggerWindow.EnableIfNeeded(); + } + return frameDebuggerWindow; + } + [MenuItem("Window/Frame Debugger", true, 2100)] + public static bool ShowFrameDebuggerWindowValidate() + { + return InternalEditorUtility.HasProFeaturesEnabled(); + } + internal static void RepaintAll() + { + foreach (FrameDebuggerWindow current in FrameDebuggerWindow.s_FrameDebuggers) + { + current.Repaint(); + } + } + internal void ChangeFrameEventLimit(int newLimit) + { + if (newLimit <= 0 || newLimit > FrameDebuggerUtility.count) + { + return; + } + if (newLimit != FrameDebuggerUtility.limit && newLimit > 0) + { + GameObject gameObjectForEvent = FrameDebuggerWindow.GetGameObjectForEvent(newLimit - 1); + if (gameObjectForEvent != null) + { + EditorGUIUtility.PingObject(gameObjectForEvent); + } + } + FrameDebuggerUtility.limit = newLimit; + if (this.m_Tree != null) + { + this.m_Tree.SelectFrameEventIndex(newLimit); + } + } + private static void DisableFrameDebugger() + { + if (FrameDebuggerUtility.enabled) + { + EditorApplication.SetSceneRepaintDirty(); + } + FrameDebuggerUtility.enabled = false; + } + internal void OnDidOpenScene() + { + FrameDebuggerWindow.DisableFrameDebugger(); + } + private void OnPlayModeStateChanged() + { + this.RepaintOnLimitChange(); + } + internal void OnEnable() + { + base.autoRepaintOnSceneChange = true; + FrameDebuggerWindow.s_FrameDebuggers.Add(this); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + this.m_RepaintFrames = 4; + } + internal void OnDisable() + { + if (this.m_WireMaterial != null) + { + UnityEngine.Object.DestroyImmediate(this.m_WireMaterial.shader, true); + UnityEngine.Object.DestroyImmediate(this.m_WireMaterial, true); + } + if (this.m_PreviewUtility != null) + { + this.m_PreviewUtility.Cleanup(); + this.m_PreviewUtility = null; + } + FrameDebuggerWindow.s_FrameDebuggers.Remove(this); + EditorApplication.playmodeStateChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.playmodeStateChanged, new EditorApplication.CallbackFunction(this.OnPlayModeStateChanged)); + FrameDebuggerWindow.DisableFrameDebugger(); + } + public void EnableIfNeeded() + { + if (FrameDebuggerUtility.enabled) + { + return; + } + this.m_RTChannel = 0; + this.m_RTIndex = 0; + this.m_RTBlackLevel = 0f; + this.m_RTWhiteLevel = 1f; + this.ClickEnableFrameDebugger(); + this.RepaintOnLimitChange(); + } + private void ClickEnableFrameDebugger() + { + if (!FrameDebuggerWindow.GraphicsSupportsFrameDebugger()) + { + return; + } + if (!FrameDebuggerUtility.enabled && EditorApplication.isPlaying && !EditorApplication.isPaused) + { + EditorApplication.isPaused = true; + } + FrameDebuggerUtility.enabled = !FrameDebuggerUtility.enabled; + if (FrameDebuggerUtility.enabled) + { + GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); + if (gameView) + { + gameView.ShowTab(); + } + } + this.m_PrevEventsLimit = FrameDebuggerUtility.limit; + this.m_PrevEventsCount = FrameDebuggerUtility.count; + } + private bool DrawToolbar(FrameDebuggerEvent[] descs) + { + bool result = false; + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginDisabledGroup(!FrameDebuggerWindow.GraphicsSupportsFrameDebugger()); + GUILayout.Toggle(FrameDebuggerUtility.enabled, FrameDebuggerWindow.styles.recordButton, EditorStyles.toolbarButton, new GUILayoutOption[] + { + GUILayout.MinWidth(80f) + }); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + this.ClickEnableFrameDebugger(); + result = true; + } + GUI.enabled = FrameDebuggerUtility.enabled; + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginDisabledGroup(FrameDebuggerUtility.count <= 1); + int num = EditorGUILayout.IntSlider(FrameDebuggerUtility.limit, 1, FrameDebuggerUtility.count, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + this.ChangeFrameEventLimit(num); + } + GUILayout.Label(" of " + FrameDebuggerUtility.count, EditorStyles.miniLabel, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(num <= 1); + if (GUILayout.Button(FrameDebuggerWindow.styles.prevFrame, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.ChangeFrameEventLimit(num - 1); + } + EditorGUI.EndDisabledGroup(); + EditorGUI.BeginDisabledGroup(num >= FrameDebuggerUtility.count); + if (GUILayout.Button(FrameDebuggerWindow.styles.nextFrame, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + this.ChangeFrameEventLimit(num + 1); + } + if (this.m_PrevEventsLimit == this.m_PrevEventsCount && FrameDebuggerUtility.count != this.m_PrevEventsCount && FrameDebuggerUtility.limit == this.m_PrevEventsLimit) + { + this.ChangeFrameEventLimit(FrameDebuggerUtility.count); + } + this.m_PrevEventsLimit = FrameDebuggerUtility.limit; + this.m_PrevEventsCount = FrameDebuggerUtility.count; + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + return result; + } + private void DrawMeshPreview(FrameDebuggerEvent curEvent, Rect previewRect, Rect meshInfoRect, Mesh mesh, int meshSubset) + { + if (this.m_PreviewUtility == null) + { + this.m_PreviewUtility = new PreviewRenderUtility(); + this.m_PreviewUtility.m_CameraFieldOfView = 30f; + } + if (this.m_Material == null) + { + this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Material.mat") as Material); + } + if (this.m_WireMaterial == null) + { + this.m_WireMaterial = new Material(ModelInspector.WireframeShaderSource); + this.m_WireMaterial.hideFlags = HideFlags.HideAndDontSave; + this.m_WireMaterial.shader.hideFlags = HideFlags.HideAndDontSave; + } + this.m_PreviewUtility.BeginPreview(previewRect, "preBackground"); + ModelInspector.RenderMeshPreview(mesh, this.m_PreviewUtility, this.m_Material, this.m_WireMaterial, this.m_PreviewDir, meshSubset); + Texture image = this.m_PreviewUtility.EndPreview(); + GUI.DrawTexture(previewRect, image, ScaleMode.StretchToFill, false); + string text = mesh.name; + if (string.IsNullOrEmpty(text)) + { + text = ""; + } + string text2 = string.Concat(new object[] + { + text, + " subset ", + meshSubset, + "\n", + curEvent.vertexCount, + " verts, ", + curEvent.indexCount, + " indices" + }); + EditorGUI.DropShadowLabel(meshInfoRect, text2); + } + internal static GameObject GetGameObjectForEvent(int eventIndex) + { + GameObject result = null; + int frameEventRendererID = FrameDebuggerUtility.GetFrameEventRendererID(eventIndex); + Component component = EditorUtility.InstanceIDToObject(frameEventRendererID) as Component; + if (component != null) + { + result = component.gameObject; + } + return result; + } + private bool DrawEventMesh(int curEventIndex, FrameDebuggerEvent curEvent) + { + int frameEventMeshID = FrameDebuggerUtility.GetFrameEventMeshID(curEventIndex); + if (frameEventMeshID == 0) + { + return false; + } + UnityEngine.Object @object = EditorUtility.InstanceIDToObject(frameEventMeshID); + Mesh mesh = @object as Mesh; + if (mesh == null) + { + return false; + } + Rect rect = GUILayoutUtility.GetRect(10f, 10f, new GUILayoutOption[] + { + GUILayout.ExpandHeight(true) + }); + if (rect.width < 64f || rect.height < 64f) + { + return true; + } + GameObject gameObjectForEvent = FrameDebuggerWindow.GetGameObjectForEvent(curEventIndex); + Rect rect2 = rect; + rect2.yMin = rect2.yMax - EditorGUIUtility.singleLineHeight * 2f; + Rect position = rect2; + rect2.xMin = rect2.center.x; + position.xMax = position.center.x; + if (Event.current.type == EventType.MouseDown) + { + if (rect2.Contains(Event.current.mousePosition)) + { + EditorGUIUtility.PingObject(frameEventMeshID); + Event.current.Use(); + } + if (gameObjectForEvent != null && position.Contains(Event.current.mousePosition)) + { + EditorGUIUtility.PingObject(gameObjectForEvent.GetInstanceID()); + Event.current.Use(); + } + } + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, rect); + if (Event.current.type == EventType.Repaint) + { + int frameEventMeshSubset = FrameDebuggerUtility.GetFrameEventMeshSubset(curEventIndex); + this.DrawMeshPreview(curEvent, rect, rect2, mesh, frameEventMeshSubset); + if (gameObjectForEvent != null) + { + EditorGUI.DropShadowLabel(position, gameObjectForEvent.name); + } + } + return true; + } + private void DrawRenderTargetControls(FrameDebuggerEvent cur) + { + if (cur.rtWidth <= 0 || cur.rtHeight <= 0) + { + return; + } + bool disabled = cur.rtFormat == 1 || cur.rtFormat == 3; + bool flag = cur.rtHasDepthTexture != 0; + short num = cur.rtCount; + if (flag) + { + num += 1; + } + GUILayout.Label("RenderTarget: " + cur.rtName, EditorStyles.boldLabel, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + EditorGUI.BeginDisabledGroup(num <= 1); + GUIContent[] array = new GUIContent[(int)num]; + for (int i = 0; i < (int)cur.rtCount; i++) + { + array[i] = FrameDebuggerWindow.Styles.mrtLabels[i]; + } + if (flag) + { + array[(int)cur.rtCount] = FrameDebuggerWindow.Styles.depthLabel; + } + int num2 = Mathf.Clamp(this.m_RTIndex, 0, (int)(num - 1)); + bool flag2 = num2 != this.m_RTIndex; + this.m_RTIndex = num2; + this.m_RTIndex = EditorGUILayout.Popup(this.m_RTIndex, array, EditorStyles.toolbarPopup, new GUILayoutOption[] + { + GUILayout.Width(70f) + }); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + EditorGUI.BeginDisabledGroup(disabled); + GUILayout.Label(FrameDebuggerWindow.Styles.channelHeader, EditorStyles.miniLabel, new GUILayoutOption[0]); + this.m_RTChannel = GUILayout.Toolbar(this.m_RTChannel, FrameDebuggerWindow.Styles.channelLabels, EditorStyles.toolbarButton, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + GUILayout.Label(FrameDebuggerWindow.Styles.levelsHeader, EditorStyles.miniLabel, new GUILayoutOption[0]); + EditorGUILayout.MinMaxSlider(ref this.m_RTBlackLevel, ref this.m_RTWhiteLevel, 0f, 1f, new GUILayoutOption[] + { + GUILayout.MaxWidth(200f) + }); + if (EditorGUI.EndChangeCheck() || flag2) + { + Vector4 channels = Vector4.zero; + if (this.m_RTChannel == 1) + { + channels.x = 1f; + } + else + { + if (this.m_RTChannel == 2) + { + channels.y = 1f; + } + else + { + if (this.m_RTChannel == 3) + { + channels.z = 1f; + } + else + { + if (this.m_RTChannel == 4) + { + channels.w = 1f; + } + else + { + channels = Vector4.one; + } + } + } + } + int num3 = this.m_RTIndex; + if (num3 >= (int)cur.rtCount) + { + num3 = -1; + } + FrameDebuggerUtility.SetRenderTargetDisplayOptions(num3, channels, this.m_RTBlackLevel, this.m_RTWhiteLevel); + this.RepaintAllNeededThings(); + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.Label(string.Format("{0}x{1} {2}", cur.rtWidth, cur.rtHeight, (RenderTextureFormat)cur.rtFormat), new GUILayoutOption[0]); + if (cur.rtDim == 4) + { + GUILayout.Label("Rendering into cubemap", new GUILayoutOption[0]); + } + if (cur.rtFormat == 3 && SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9")) + { + EditorGUILayout.HelpBox("Rendering into shadowmap on DX9, can't visualize it in the game view properly", MessageType.Info, true); + } + } + private void DrawCurrentEvent(Rect rect, FrameDebuggerEvent[] descs) + { + int num = FrameDebuggerUtility.limit - 1; + if (num < 0 || num >= descs.Length) + { + return; + } + GUILayout.BeginArea(rect); + FrameDebuggerEvent frameDebuggerEvent = descs[num]; + this.DrawRenderTargetControls(frameDebuggerEvent); + GUILayout.Label(string.Format("Event #{0}: {1}", num + 1, FrameDebuggerWindow.s_FrameEventTypeNames[(int)frameDebuggerEvent.type]), EditorStyles.boldLabel, new GUILayoutOption[0]); + if (frameDebuggerEvent.vertexCount > 0 || frameDebuggerEvent.indexCount > 0) + { + int frameEventShaderID = FrameDebuggerUtility.GetFrameEventShaderID(num); + if (frameEventShaderID != 0) + { + Shader shader = EditorUtility.InstanceIDToObject(frameEventShaderID) as Shader; + if (shader != null) + { + int frameEventShaderPassIndex = FrameDebuggerUtility.GetFrameEventShaderPassIndex(num); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (GUILayout.Button(string.Concat(new object[] + { + "Shader: ", + shader.name, + " pass #", + frameEventShaderPassIndex + }), GUI.skin.label, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + EditorGUIUtility.PingObject(shader); + Event.current.Use(); + } + GUILayout.Label(FrameDebuggerUtility.GetFrameEventShaderKeywords(num), EditorStyles.miniLabel, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + } + if (!this.DrawEventMesh(num, frameDebuggerEvent)) + { + GUILayout.Label("Vertices: " + frameDebuggerEvent.vertexCount, new GUILayoutOption[0]); + GUILayout.Label("Indices: " + frameDebuggerEvent.indexCount, new GUILayoutOption[0]); + } + } + GUILayout.EndArea(); + } + private static bool GraphicsSupportsFrameDebugger() + { + return SystemInfo.graphicsMultiThreaded; + } + internal void OnGUI() + { + if (!FrameDebuggerWindow.ShowFrameDebuggerWindowValidate()) + { + EditorGUILayout.HelpBox("Frame Debugger requires a Pro license", MessageType.Warning, true); + return; + } + FrameDebuggerEvent[] frameEvents = FrameDebuggerUtility.GetFrameEvents(); + if (this.m_TreeViewState == null) + { + this.m_TreeViewState = new TreeViewState(); + } + if (this.m_Tree == null) + { + this.m_Tree = new FrameDebuggerTreeView(frameEvents, this.m_TreeViewState, this, default(Rect)); + this.m_FrameEventsHash = FrameDebuggerUtility.eventsHash; + this.m_Tree.m_DataSource.SetExpandedWithChildren(this.m_Tree.m_DataSource.root, true); + } + if (FrameDebuggerUtility.eventsHash != this.m_FrameEventsHash) + { + this.m_Tree.m_DataSource.SetEvents(frameEvents); + this.m_FrameEventsHash = FrameDebuggerUtility.eventsHash; + } + int limit = FrameDebuggerUtility.limit; + bool flag = this.DrawToolbar(frameEvents); + if (!FrameDebuggerUtility.enabled) + { + GUI.enabled = true; + if (!FrameDebuggerWindow.GraphicsSupportsFrameDebugger()) + { + EditorGUILayout.HelpBox("Frame Debugger requires multi-threaded renderer. Usually Unity uses that; if it does not try starting with -force-gfx-mt command line argument.", MessageType.Warning, true); + } + EditorGUILayout.HelpBox("Frame Debugger lets you step through draw calls and see how exactly frame is rendered. Click Enable!", MessageType.Info, true); + } + else + { + float fixedHeight = EditorStyles.toolbar.fixedHeight; + Rect dragRect = new Rect(this.m_ListWidth, fixedHeight, 5f, base.position.height - fixedHeight); + dragRect = EditorGUIUtility.HandleHorizontalSplitter(dragRect, base.position.width, 200f, 200f); + this.m_ListWidth = dragRect.x; + Rect rect = new Rect(0f, fixedHeight, this.m_ListWidth, base.position.height - fixedHeight); + Rect rect2 = new Rect(this.m_ListWidth + 4f, fixedHeight + 4f, base.position.width - this.m_ListWidth - 8f, base.position.height - fixedHeight - 8f); + this.DrawEventsTree(rect); + EditorGUIUtility.DrawHorizontalSplitter(dragRect); + this.DrawCurrentEvent(rect2, frameEvents); + } + if (flag || limit != FrameDebuggerUtility.limit) + { + this.RepaintOnLimitChange(); + } + if (this.m_RepaintFrames > 0) + { + this.m_Tree.SelectFrameEventIndex(FrameDebuggerUtility.limit); + this.RepaintAllNeededThings(); + this.m_RepaintFrames--; + } + } + private void RepaintOnLimitChange() + { + this.m_RepaintFrames = 4; + this.RepaintAllNeededThings(); + } + private void RepaintAllNeededThings() + { + EditorApplication.SetSceneRepaintDirty(); + base.Repaint(); + } + private void DrawEventsTree(Rect rect) + { + this.m_Tree.OnGUI(rect); + } + } +} diff --git a/UnityEditor/UnityEditor/GUID.cs b/UnityEditor/UnityEditor/GUID.cs new file mode 100644 index 00000000..e5a73c0f --- /dev/null +++ b/UnityEditor/UnityEditor/GUID.cs @@ -0,0 +1,50 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public struct GUID + { + private uint m_Value0; + private uint m_Value1; + private uint m_Value2; + private uint m_Value3; + public GUID(string hexRepresentation) + { + this.m_Value0 = 0u; + this.m_Value1 = 0u; + this.m_Value2 = 0u; + this.m_Value3 = 0u; + this.ParseExact(hexRepresentation); + } + public override bool Equals(object obj) + { + GUID x = (GUID)obj; + return x == this; + } + public override int GetHashCode() + { + return this.m_Value0.GetHashCode(); + } + public bool Empty() + { + return this.m_Value0 == 0u && this.m_Value1 == 0u && this.m_Value2 == 0u && this.m_Value3 == 0u; + } + public bool ParseExact(string hex) + { + this.HexToGUIDInternal(hex, ref this); + return !this.Empty(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void HexToGUIDInternal(string hex, ref GUID guid); + public static bool operator ==(GUID x, GUID y) + { + return x.m_Value0 == y.m_Value0 && x.m_Value1 == y.m_Value1 && x.m_Value2 == y.m_Value2 && x.m_Value3 == y.m_Value3; + } + public static bool operator !=(GUID x, GUID y) + { + return !(x == y); + } + } +} diff --git a/UnityEditor/UnityEditor/GUIView.cs b/UnityEditor/UnityEditor/GUIView.cs index b96483c3..61352765 100644 --- a/UnityEditor/UnityEditor/GUIView.cs +++ b/UnityEditor/UnityEditor/GUIView.cs @@ -104,6 +104,9 @@ internal extern bool mouseRayInvisible } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetTitle(string title); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_Init(int depthBits, int antiAlias); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/GameObjectInspector.cs b/UnityEditor/UnityEditor/GameObjectInspector.cs index 5c8af7c3..34a7510f 100644 --- a/UnityEditor/UnityEditor/GameObjectInspector.cs +++ b/UnityEditor/UnityEditor/GameObjectInspector.cs @@ -48,7 +48,6 @@ public Styles() private const float kIconSize = 24f; private const float kLeft = 52f; private const float kToggleSize = 14f; - private const int kPreviewLayer = 31; private SerializedProperty m_Name; private SerializedProperty m_IsActive; private SerializedProperty m_Layer; @@ -375,15 +374,6 @@ private void SetLayer(int layer, bool includeChildren) gameObject.layer = layer; } } - public static void InitInstantiatedPreviewRecursive(GameObject go) - { - go.hideFlags = HideFlags.HideAndDontSave; - go.layer = 31; - foreach (Transform transform in go.transform) - { - GameObjectInspector.InitInstantiatedPreviewRecursive(transform.gameObject); - } - } public static void SetEnabledRecursive(GameObject go, bool enabled) { Renderer[] componentsInChildren = go.GetComponentsInChildren(); @@ -393,6 +383,10 @@ public static void SetEnabledRecursive(GameObject go, bool enabled) renderer.enabled = enabled; } } + public override void ReloadPreviewInstances() + { + this.CreatePreviewInstances(); + } private void CreatePreviewInstances() { this.DestroyPreviewInstances(); @@ -402,16 +396,7 @@ private void CreatePreviewInstances() } for (int i = 0; i < base.targets.Length; i++) { - GameObject gameObject = EditorUtility.InstantiateRemoveAllNonAnimationComponents(base.targets[i], Vector3.zero, Quaternion.identity) as GameObject; - GameObjectInspector.InitInstantiatedPreviewRecursive(gameObject); - Animator animator = gameObject.GetComponent(typeof(Animator)) as Animator; - if (animator) - { - animator.enabled = false; - animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; - animator.logWarnings = false; - animator.fireEvents = false; - } + GameObject gameObject = EditorUtility.InstantiateForAnimatorPreview(base.targets[i]); GameObjectInspector.SetEnabledRecursive(gameObject, false); this.m_PreviewInstances.Add(gameObject); } @@ -434,7 +419,7 @@ private void InitPreview() { this.m_PreviewUtility = new PreviewRenderUtility(true); this.m_PreviewUtility.m_CameraFieldOfView = 30f; - this.m_PreviewUtility.m_Camera.cullingMask = -2147483648; + this.m_PreviewUtility.m_Camera.cullingMask = 1 << Camera.PreviewCullingLayer; this.CreatePreviewInstances(); } } @@ -701,6 +686,7 @@ public void OnSceneDrag(SceneView sceneView) } else { + string uniqueNameForSibling = GameObjectUtility.GetUniqueNameForSibling(null, GameObjectInspector.dragObject.name); GameObjectInspector.dragObject.hideFlags = HideFlags.None; Undo.RegisterCreatedObjectUndo(GameObjectInspector.dragObject, "Place " + GameObjectInspector.dragObject.name); EditorUtility.SetDirty(GameObjectInspector.dragObject); @@ -708,6 +694,7 @@ public void OnSceneDrag(SceneView sceneView) Selection.activeObject = GameObjectInspector.dragObject; HandleUtility.ignoreRaySnapObjects = null; EditorWindow.mouseOverWindow.Focus(); + GameObjectInspector.dragObject.name = uniqueNameForSibling; GameObjectInspector.dragObject = null; current.Use(); } diff --git a/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs b/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs index ff042914..db9cac0a 100644 --- a/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs +++ b/UnityEditor/UnityEditor/GameObjectTreeViewDataSource.cs @@ -6,10 +6,32 @@ namespace UnityEditor { internal class GameObjectTreeViewDataSource : LazyTreeViewDataSource { - public class ComparerData + public class SortingState { - public BaseHierarchySort comparerImpl; - public bool comparerImplementsCompare = true; + private BaseHierarchySort m_HierarchySort; + private bool m_ImplementsCompare; + public BaseHierarchySort sortingObject + { + get + { + return this.m_HierarchySort; + } + set + { + this.m_HierarchySort = value; + if (this.m_HierarchySort != null) + { + this.m_ImplementsCompare = (this.m_HierarchySort.GetType().GetMethod("Compare").DeclaringType != typeof(BaseHierarchySort)); + } + } + } + public bool implementsCompare + { + get + { + return this.m_ImplementsCompare; + } + } } private const double k_LongFetchTime = 0.05; private const double k_FetchDelta = 0.1; @@ -20,7 +42,8 @@ public class ComparerData private int m_SearchMode; private double m_LastFetchTime; private int m_DelayedFetches; - public GameObjectTreeViewDataSource.ComparerData compareData = new GameObjectTreeViewDataSource.ComparerData(); + private bool m_NeedsChildParentReferenceSetup; + public GameObjectTreeViewDataSource.SortingState sortingState = new GameObjectTreeViewDataSource.SortingState(); public string searchString { get @@ -56,28 +79,28 @@ public GameObjectTreeViewDataSource(TreeView treeView, int rootInstanceID, bool this.showRootNode = showRootNode; base.rootIsCollapsable = rootNodeIsCollapsable; } - public int GetLastRootItemID() + internal void SetupChildParentReferencesIfNeeded() { - TreeViewItem treeViewItem = this.m_VisibleRows[this.m_VisibleRows.Count - 1]; - if (treeViewItem != null) + if (this.m_NeedsChildParentReferenceSetup) { - while (treeViewItem.parent != null) - { - if (!base.showRootNode && treeViewItem.parent.id == this.m_RootInstanceID) - { - break; - } - treeViewItem = treeViewItem.parent; - } + this.m_NeedsChildParentReferenceSetup = false; + TreeViewUtility.SetChildParentReferences(this.GetVisibleRows(), this.m_RootItem); } - return treeViewItem.id; + } + public override TreeViewItem FindItem(int id) + { + this.RevealItem(id); + this.SetupChildParentReferencesIfNeeded(); + return base.FindItem(id); } public override void FetchData() { + Profiler.BeginSample("SceneHierarchyWindow.FetchData"); int depth = 0; double timeSinceStartup = EditorApplication.timeSinceStartup; HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); hierarchyProperty.Reset(); + hierarchyProperty.alphaSorted = this.IsUsingAlphaSort(); if (this.m_RootInstanceID != 0) { bool flag = hierarchyProperty.Find(this.m_RootInstanceID, null); @@ -102,8 +125,9 @@ public override void FetchData() hierarchyProperty.SetSearchFilter(this.m_SearchString, this.m_SearchMode); } this.m_VisibleRows = this.CalcVisibleItems(hierarchyProperty, flag2); - TreeViewUtility.SetChildParentReferences(this.m_VisibleRows, this.m_RootItem); - if (this.compareData.comparerImpl != null && this.compareData.comparerImplementsCompare) + this.m_NeedsChildParentReferenceSetup = true; + this.m_NeedRefreshVisibleFolders = false; + if (this.sortingState.sortingObject != null && this.sortingState.implementsCompare) { this.SortVisibleRows(); } @@ -119,8 +143,22 @@ public override void FetchData() this.m_DelayedFetches = 0; } this.m_LastFetchTime = timeSinceStartup; - this.m_NeedRefreshVisibleFolders = false; this.m_TreeView.SetSelection(Selection.instanceIDs, false); + if (SceneHierarchyWindow.s_Debug) + { + Debug.Log(string.Concat(new object[] + { + "Fetch time: ", + num * 1000.0, + " ms, alphaSort = ", + this.IsUsingAlphaSort() + })); + } + Profiler.EndSample(); + } + private bool IsUsingAlphaSort() + { + return this.sortingState.sortingObject.GetType() == typeof(AlphabeticalSort); } private List CalcVisibleItems(HierarchyProperty property, bool hasSearchString) { @@ -137,13 +175,13 @@ private List CalcVisibleItems(HierarchyProperty property, bool has } private GameObjectTreeViewItem CreateTreeViewItem(HierarchyProperty property, bool hasSearchString, int depth, bool shouldDisplay) { - GameObjectTreeViewItem gameObjectTreeViewItem = new GameObjectTreeViewItem(property.instanceID, depth, null, property.name); + GameObjectTreeViewItem gameObjectTreeViewItem = new GameObjectTreeViewItem(property.instanceID, depth, null, string.Empty); gameObjectTreeViewItem.colorCode = property.colorCode; gameObjectTreeViewItem.objectPPTR = property.pptrValue; gameObjectTreeViewItem.shouldDisplay = shouldDisplay; if (!hasSearchString && property.hasChildren) { - gameObjectTreeViewItem.AddChild(null); + gameObjectTreeViewItem.children = LazyTreeViewDataSource.CreateChildListForCollapsedParent(); } return gameObjectTreeViewItem; } @@ -184,7 +222,8 @@ protected override HashSet GetParentsBelow(int id) } private void SortVisibleRows() { - this.SortChildrenRecursively(this.m_RootItem, this.compareData.comparerImpl); + this.SetupChildParentReferencesIfNeeded(); + this.SortChildrenRecursively(this.m_RootItem, this.sortingState.sortingObject); this.m_VisibleRows.Clear(); this.RebuildVisibilityTree(this.m_RootItem, this.m_VisibleRows); } diff --git a/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs b/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs index be7da923..96c54ae7 100644 --- a/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs +++ b/UnityEditor/UnityEditor/GameObjectTreeViewGUI.cs @@ -41,6 +41,17 @@ protected override void InitStyles() GameObjectTreeViewGUI.s_GOStyles = new GameObjectTreeViewGUI.GameObjectStyles(); } } + public override bool BeginRename(TreeViewItem item, float delay) + { + GameObjectTreeViewItem gameObjectTreeViewItem = item as GameObjectTreeViewItem; + UnityEngine.Object objectPPTR = gameObjectTreeViewItem.objectPPTR; + if ((objectPPTR.hideFlags & HideFlags.NotEditable) != HideFlags.None) + { + Debug.LogWarning("Unable to rename a GameObject with HideFlags.NotEditable."); + return false; + } + return base.BeginRename(item, delay); + } protected override void RenameEnded() { string text = (!string.IsNullOrEmpty(base.GetRenameOverlay().name)) ? base.GetRenameOverlay().name : base.GetRenameOverlay().originalName; @@ -54,6 +65,7 @@ protected override void RenameEnded() { treeViewItem.displayName = text; } + EditorApplication.RepaintAnimationWindow(); } } protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) @@ -76,6 +88,7 @@ protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string la { gameObjectTreeViewItem.displayName = "deleted gameobject"; } + label = gameObjectTreeViewItem.displayName; } GUIStyle gUIStyle = TreeViewGUI.s_Styles.lineStyle; if (!gameObjectTreeViewItem.shouldDisplay) @@ -104,7 +117,7 @@ protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string la } } gUIStyle.padding.left = (int)this.k_SpaceBetweenIconAndText; - gUIStyle.Draw(rect, gameObjectTreeViewItem.displayName, false, false, selected, focused); + gUIStyle.Draw(rect, label, false, false, selected, focused); } protected override Texture GetIconForNode(TreeViewItem item) { diff --git a/UnityEditor/UnityEditor/GameObjectUtility.cs b/UnityEditor/UnityEditor/GameObjectUtility.cs index 5fdf960d..431c3a9d 100644 --- a/UnityEditor/UnityEditor/GameObjectUtility.cs +++ b/UnityEditor/UnityEditor/GameObjectUtility.cs @@ -14,6 +14,54 @@ internal enum ShouldIncludeChildren DontIncludeChildren, Cancel } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern StaticEditorFlags GetStaticEditorFlags(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AreStaticEditorFlagsSet(GameObject go, StaticEditorFlags flags); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetStaticEditorFlags(GameObject go, StaticEditorFlags flags); + [Obsolete("GetNavMeshArea instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshLayer(GameObject go); + [Obsolete("GetNavMeshAreaFromName instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshLayerFromName(string name); + [Obsolete("SetNavMeshArea instead."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNavMeshLayer(GameObject go, int areaIndex); + [Obsolete("GetNavMeshAreaNames instead.")] + public static string[] GetNavMeshLayerNames() + { + return GameObjectUtility.GetNavMeshAreaNames(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshArea(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetNavMeshAreaFromName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNavMeshArea(GameObject go, int areaIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetNavMeshAreaNames(); + [Obsolete("use AnimatorUtility.OptimizeTransformHierarchy instead.")] + private static void OptimizeTransformHierarchy(GameObject go) + { + AnimatorUtility.OptimizeTransformHierarchy(go, null); + } + [Obsolete("use AnimatorUtility.DeoptimizeTransformHierarchy instead.")] + private static void DeoptimizeTransformHierarchy(GameObject go) + { + AnimatorUtility.DeoptimizeTransformHierarchy(go); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUniqueNameForSibling(Transform parent, string name); internal static bool ContainsStatic(GameObject[] objects) { if (objects == null || objects.Length == 0) @@ -64,36 +112,5 @@ public static void SetParentAndAlign(GameObject child, GameObject parent) child.transform.localScale = Vector3.one; child.layer = parent.layer; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern StaticEditorFlags GetStaticEditorFlags(GameObject go); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool AreStaticEditorFlagsSet(GameObject go, StaticEditorFlags flags); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetStaticEditorFlags(GameObject go, StaticEditorFlags flags); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern int GetNavMeshLayer(GameObject go); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern int GetNavMeshLayerFromName(string name); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetNavMeshLayer(GameObject go, int layer); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string[] GetNavMeshLayerNames(); - [Obsolete("use AnimatorUtility.OptimizeTransformHierarchy instead.")] - private static void OptimizeTransformHierarchy(GameObject go) - { - AnimatorUtility.OptimizeTransformHierarchy(go, null); - } - [Obsolete("use AnimatorUtility.DeoptimizeTransformHierarchy instead.")] - private static void DeoptimizeTransformHierarchy(GameObject go) - { - AnimatorUtility.DeoptimizeTransformHierarchy(go); - } } } diff --git a/UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs b/UnityEditor/UnityEditor/GameObjectsTreeViewDragging.cs similarity index 73% rename from UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs rename to UnityEditor/UnityEditor/GameObjectsTreeViewDragging.cs index 4fa74181..b4e6e485 100644 --- a/UnityEditor/UnityEditor/AssetOrGameObjectTreeViewDragging.cs +++ b/UnityEditor/UnityEditor/GameObjectsTreeViewDragging.cs @@ -3,26 +3,21 @@ using UnityEditorInternal; namespace UnityEditor { - internal class AssetOrGameObjectTreeViewDragging : TreeViewDragging + internal class GameObjectsTreeViewDragging : TreeViewDragging { - private readonly HierarchyType m_HierarchyType; public bool allowDragBetween { get; set; } - public AssetOrGameObjectTreeViewDragging(TreeView treeView, HierarchyType hierarchyType) : base(treeView) + public GameObjectsTreeViewDragging(TreeView treeView) : base(treeView) { this.allowDragBetween = false; - this.m_HierarchyType = hierarchyType; } public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) { DragAndDrop.PrepareStartDrag(); - if (this.m_HierarchyType == HierarchyType.GameObjects) - { - draggedItemIDs = this.m_TreeView.SortIDsInVisiblityOrder(draggedItemIDs); - } + draggedItemIDs = this.m_TreeView.SortIDsInVisiblityOrder(draggedItemIDs); DragAndDrop.objectReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedItem.id, draggedItemIDs); DragAndDrop.paths = ProjectWindowUtil.GetDragAndDropPaths(draggedItem.id, draggedItemIDs); if (DragAndDrop.objectReferences.Length > 1) @@ -34,17 +29,17 @@ public override void StartDrag(TreeViewItem draggedItem, List draggedItemID string dragAndDropTitle = ObjectNames.GetDragAndDropTitle(InternalEditorUtility.GetObjectFromInstanceID(draggedItem.id)); DragAndDrop.StartDrag(dragAndDropTitle); } + if (this.m_TreeView.data is GameObjectTreeViewDataSource) + { + ((GameObjectTreeViewDataSource)this.m_TreeView.data).SetupChildParentReferencesIfNeeded(); + } } public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPos) { - HierarchyProperty hierarchyProperty = new HierarchyProperty(this.m_HierarchyType); - if (this.m_HierarchyType == HierarchyType.Assets) + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + if (parentItem == null || targetItem == null) { - if (parentItem == null || !hierarchyProperty.Find(parentItem.id, null)) - { - hierarchyProperty = null; - } - return InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); + return InternalEditorUtility.HierarchyWindowDrag(null, perform, InternalEditorUtility.HierarchyDropMode.kHierarchyDropUpon); } if (this.allowDragBetween) { diff --git a/UnityEditor/UnityEditor/GameView.cs b/UnityEditor/UnityEditor/GameView.cs index 4d7d8a08..7c9f867b 100644 --- a/UnityEditor/UnityEditor/GameView.cs +++ b/UnityEditor/UnityEditor/GameView.cs @@ -19,12 +19,25 @@ internal class GameView : EditorWindow private bool m_Stats; [SerializeField] private int[] m_SelectedSizes = new int[0]; + [SerializeField] + private int m_TargetDisplay; private int m_SizeChangeID = -2147483648; private GUIContent gizmosContent = new GUIContent("Gizmos"); private static GUIStyle s_GizmoButtonStyle; private static GUIStyle s_ResolutionWarningStyle; private static List s_GameViews = new List(); private static GameView s_LastFocusedGameView = null; + private static string[] s_GameDisplays = new string[] + { + "Display 1", + "Display 2", + "Display 3", + "Display 4", + "Display 5", + "Display 6", + "Display 7", + "Display 8" + }; private static Rect s_MainGameViewRect = new Rect(0f, 0f, 640f, 480f); private Vector2 m_ShownResolution = Vector2.zero; private AnimBool m_ResolutionTooLargeWarning = new AnimBool(false); @@ -76,6 +89,7 @@ public GameView() base.depthBufferBits = 32; base.antiAlias = -1; base.autoRepaintOnSceneChange = true; + this.m_TargetDisplay = 0; } public void OnValidate() { @@ -234,12 +248,32 @@ private void DoToolbarGUI() this.m_SizeChangeID = ScriptableSingleton.instance.GetChangeID(); } GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + if (Display.MultiDisplayLicense()) + { + this.m_TargetDisplay = EditorGUILayout.Popup(this.m_TargetDisplay, GameView.s_GameDisplays, EditorStyles.toolbarPopup, new GUILayoutOption[] + { + GUILayout.Width(80f) + }); + } EditorGUILayout.GameViewSizePopup(GameView.currentSizeGroupType, this.selectedSizeIndex, new Action(this.SelectionCallback), EditorStyles.toolbarDropDown, new GUILayoutOption[] { GUILayout.Width(160f) }); + if (FrameDebuggerUtility.enabled) + { + GUILayout.FlexibleSpace(); + Color color = GUI.color; + GUI.color *= AnimationMode.animatedPropertyColor; + GUILayout.Label("Frame Debugger on", EditorStyles.miniLabel, new GUILayoutOption[0]); + GUI.color = color; + if (Event.current.type == EventType.Repaint) + { + FrameDebuggerWindow.RepaintAll(); + } + } GUILayout.FlexibleSpace(); this.m_MaximizeOnPlay = GUILayout.Toggle(this.m_MaximizeOnPlay, "Maximize on Play", EditorStyles.toolbarButton, new GUILayoutOption[0]); + EditorUtility.audioMasterMute = GUILayout.Toggle(EditorUtility.audioMasterMute, "Mute audio", EditorStyles.toolbarButton, new GUILayoutOption[0]); this.m_Stats = GUILayout.Toggle(this.m_Stats, "Stats", EditorStyles.toolbarButton, new GUILayoutOption[0]); Rect rect = GUILayoutUtility.GetRect(this.gizmosContent, GameView.s_GizmoButtonStyle); Rect position = new Rect(rect.xMax - (float)GameView.s_GizmoButtonStyle.border.right, rect.y, (float)GameView.s_GizmoButtonStyle.border.right, rect.height); @@ -292,7 +326,14 @@ private void OnGUI() Vector2 s_EditorScreenPointOffset = GUIUtility.s_EditorScreenPointOffset; GUIUtility.s_EditorScreenPointOffset = Vector2.zero; SavedGUIState savedGUIState = SavedGUIState.Create(); - EditorGUIUtility.RenderGameViewCameras(rect, this.m_Gizmos, true); + if (Display.MultiDisplayLicense()) + { + EditorGUIUtility.RenderGameViewCameras(rect, this.m_TargetDisplay, this.m_Gizmos, true); + } + else + { + EditorGUIUtility.RenderGameViewCameras(rect, 0, this.m_Gizmos, true); + } savedGUIState.ApplyAndForget(); GUIUtility.s_EditorScreenPointOffset = s_EditorScreenPointOffset; } diff --git a/UnityEditor/UnityEditor/GameViewGUI.cs b/UnityEditor/UnityEditor/GameViewGUI.cs index 541cf394..5255dbd8 100644 --- a/UnityEditor/UnityEditor/GameViewGUI.cs +++ b/UnityEditor/UnityEditor/GameViewGUI.cs @@ -13,6 +13,7 @@ internal class GameViewGUI private static float m_RenderFrameTime; private static float m_MaxFrameTime; private static GUIStyle s_SectionHeaderStyle; + private static GUIStyle s_LabelStyle; private static GUIStyle sectionHeaderStyle { get @@ -24,6 +25,18 @@ private static GUIStyle sectionHeaderStyle return GameViewGUI.s_SectionHeaderStyle; } } + private static GUIStyle labelStyle + { + get + { + if (GameViewGUI.s_LabelStyle == null) + { + GameViewGUI.s_LabelStyle = new GUIStyle(EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene).label); + GameViewGUI.s_LabelStyle.richText = true; + } + return GameViewGUI.s_LabelStyle; + } + } private static string FormatNumber(int num) { if (num < 1000) @@ -64,40 +77,56 @@ private static void UpdateFrameTime() GameViewGUI.m_FrameCounter = 0; } } + private static string FormatDb(float vol) + { + if (vol == 0f) + { + return "-∞ dB"; + } + return string.Format("{0:F1} dB", 20f * Mathf.Log10(vol)); + } public static void GameViewStatsGUI() { GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); GUI.color = new Color(1f, 1f, 1f, 0.75f); float num = 300f; - float num2 = 200f; + float num2 = 204f; int num3 = Network.connections.Length; if (num3 != 0) { num2 += 220f; } GUILayout.BeginArea(new Rect((float)Screen.width - num - 10f, 27f, num, num2), "Statistics", GUI.skin.window); + GUILayout.Label("Audio:", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); + StringBuilder stringBuilder = new StringBuilder(400); + float audioLevel = UnityStats.audioLevel; + stringBuilder.Append(" Level: " + GameViewGUI.FormatDb(audioLevel) + ((!EditorUtility.audioMasterMute) ? "\n" : " (MUTED)\n")); + stringBuilder.Append(string.Format(" Clipping: {0:F1}%", 100f * UnityStats.audioClippingAmount)); + GUILayout.Label(stringBuilder.ToString(), new GUILayoutOption[0]); + GUI.Label(new Rect(170f, 40f, 120f, 20f), string.Format("DSP load: {0:F1}%", 100f * UnityStats.audioDSPLoad)); + GUI.Label(new Rect(170f, 53f, 120f, 20f), string.Format("Stream load: {0:F1}%", 100f * UnityStats.audioStreamLoad)); GUILayout.Label("Graphics:", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); GameViewGUI.UpdateFrameTime(); string text = string.Format("{0:F1} FPS ({1:F1}ms)", 1f / Mathf.Max(GameViewGUI.m_MaxFrameTime, 1E-05f), GameViewGUI.m_MaxFrameTime * 1000f); - GUI.Label(new Rect(170f, 19f, 120f, 20f), text); - int usedTextureMemorySize = UnityStats.usedTextureMemorySize; - int renderTextureBytes = UnityStats.renderTextureBytes; + GUI.Label(new Rect(170f, 75f, 120f, 20f), text); int screenBytes = UnityStats.screenBytes; - int vboTotalBytes = UnityStats.vboTotalBytes; - int bytes = screenBytes + renderTextureBytes; - int bytes2 = screenBytes + Mathf.Max(usedTextureMemorySize, renderTextureBytes) + vboTotalBytes; - StringBuilder stringBuilder = new StringBuilder(400); - stringBuilder.Append(string.Format(" Main Thread: {0:F1}ms Renderer: {1:F1}ms\n", GameViewGUI.m_ClientFrameTime * 1000f, GameViewGUI.m_RenderFrameTime * 1000f)); - stringBuilder.Append(string.Format(" Draw Calls: {0} \tSaved by batching: {1} \n", UnityStats.drawCalls, UnityStats.batchedDrawCalls - UnityStats.batches)); - stringBuilder.Append(string.Format(" Tris: {0} \tVerts: {1} \n", GameViewGUI.FormatNumber(UnityStats.triangles), GameViewGUI.FormatNumber(UnityStats.vertices))); - stringBuilder.Append(string.Format(" Used Textures: {0} - {1}\n", UnityStats.usedTextureCount, EditorUtility.FormatBytes(usedTextureMemorySize))); - stringBuilder.Append(string.Format(" Render Textures: {0} - {1} \tswitches: {2}\n", UnityStats.renderTextureCount, EditorUtility.FormatBytes(renderTextureBytes), UnityStats.renderTextureChanges)); - stringBuilder.Append(string.Format(" Screen: {0} - {1}\n", UnityStats.screenRes, EditorUtility.FormatBytes(screenBytes))); - stringBuilder.Append(string.Format(" VRAM usage: {0} to {1} (of {2})\n", EditorUtility.FormatBytes(bytes), EditorUtility.FormatBytes(bytes2), EditorUtility.FormatBytes(SystemInfo.graphicsMemorySize * 1024 * 1024))); - stringBuilder.Append(string.Format(" VBO Total: {0} - {1}\n", UnityStats.vboTotal, EditorUtility.FormatBytes(vboTotalBytes))); - stringBuilder.Append(string.Format(" Shadow Casters: {0} \n", UnityStats.shadowCasters)); - stringBuilder.Append(string.Format(" Visible Skinned Meshes: {0} \t Animations: {1}", UnityStats.visibleSkinnedMeshes, UnityStats.visibleAnimations)); - GUILayout.Label(stringBuilder.ToString(), new GUILayoutOption[0]); + int num4 = UnityStats.dynamicBatchedDrawCalls - UnityStats.dynamicBatches; + int num5 = UnityStats.staticBatchedDrawCalls - UnityStats.staticBatches; + StringBuilder stringBuilder2 = new StringBuilder(400); + if (GameViewGUI.m_ClientFrameTime > GameViewGUI.m_RenderFrameTime) + { + stringBuilder2.Append(string.Format(" CPU: main {0:F1}ms render thread {1:F1}ms\n", GameViewGUI.m_ClientFrameTime * 1000f, GameViewGUI.m_RenderFrameTime * 1000f)); + } + else + { + stringBuilder2.Append(string.Format(" CPU: main {0:F1}ms render thread {1:F1}ms\n", GameViewGUI.m_ClientFrameTime * 1000f, GameViewGUI.m_RenderFrameTime * 1000f)); + } + stringBuilder2.Append(string.Format(" Batches: {0} \tSaved by batching: {1}\n", UnityStats.batches, num4 + num5)); + stringBuilder2.Append(string.Format(" Tris: {0} \tVerts: {1} \n", GameViewGUI.FormatNumber(UnityStats.triangles), GameViewGUI.FormatNumber(UnityStats.vertices))); + stringBuilder2.Append(string.Format(" Screen: {0} - {1}\n", UnityStats.screenRes, EditorUtility.FormatBytes(screenBytes))); + stringBuilder2.Append(string.Format(" SetPass calls: {0} \tShadow casters: {1} \n", UnityStats.setPassCalls, UnityStats.shadowCasters)); + stringBuilder2.Append(string.Format(" Visible skinned meshes: {0} Animations: {1}", UnityStats.visibleSkinnedMeshes, UnityStats.visibleAnimations)); + GUILayout.Label(stringBuilder2.ToString(), GameViewGUI.labelStyle, new GUILayoutOption[0]); if (num3 != 0) { GUILayout.Label("Network:", GameViewGUI.sectionHeaderStyle, new GUILayoutOption[0]); diff --git a/UnityEditor/UnityEditor/GameViewSizes.cs b/UnityEditor/UnityEditor/GameViewSizes.cs index b241061c..78e6abe6 100644 --- a/UnityEditor/UnityEditor/GameViewSizes.cs +++ b/UnityEditor/UnityEditor/GameViewSizes.cs @@ -447,9 +447,8 @@ public static GameViewSizeGroupType BuildTargetGroupToGameViewSizeGroup(BuildTar case BuildTargetGroup.Standalone: return GameViewSizeGroupType.Standalone; case BuildTargetGroup.WebPlayer: - case BuildTargetGroup.FlashPlayer: return GameViewSizeGroupType.WebPlayer; - case BuildTargetGroup.iPhone: + case BuildTargetGroup.iOS: return GameViewSizeGroupType.iOS; case BuildTargetGroup.PS3: return GameViewSizeGroupType.PS3; @@ -459,7 +458,7 @@ public static GameViewSizeGroupType BuildTargetGroupToGameViewSizeGroup(BuildTar return GameViewSizeGroupType.Android; case BuildTargetGroup.WP8: return GameViewSizeGroupType.WP8; - case BuildTargetGroup.BB10: + case BuildTargetGroup.BlackBerry: return GameViewSizeGroupType.BB10; case BuildTargetGroup.Tizen: return GameViewSizeGroupType.Tizen; diff --git a/UnityEditor/UnityEditor/GenericMenu.cs b/UnityEditor/UnityEditor/GenericMenu.cs index fd6e0007..2f167df5 100644 --- a/UnityEditor/UnityEditor/GenericMenu.cs +++ b/UnityEditor/UnityEditor/GenericMenu.cs @@ -8,19 +8,22 @@ public sealed class GenericMenu private sealed class MenuItem { public GUIContent content; + public bool separator; public bool on; public GenericMenu.MenuFunction func; public GenericMenu.MenuFunction2 func2; public object userData; - public MenuItem(GUIContent _content, bool _on, GenericMenu.MenuFunction _func) + public MenuItem(GUIContent _content, bool _separator, bool _on, GenericMenu.MenuFunction _func) { this.content = _content; + this.separator = _separator; this.on = _on; this.func = _func; } - public MenuItem(GUIContent _content, bool _on, GenericMenu.MenuFunction2 _func, object _userData) + public MenuItem(GUIContent _content, bool _separator, bool _on, GenericMenu.MenuFunction2 _func, object _userData) { this.content = _content; + this.separator = _separator; this.on = _on; this.func2 = _func; this.userData = _userData; @@ -31,19 +34,19 @@ public MenuItem(GUIContent _content, bool _on, GenericMenu.MenuFunction2 _func, private ArrayList menuItems = new ArrayList(); public void AddItem(GUIContent content, bool on, GenericMenu.MenuFunction func) { - this.menuItems.Add(new GenericMenu.MenuItem(content, on, func)); + this.menuItems.Add(new GenericMenu.MenuItem(content, false, on, func)); } public void AddItem(GUIContent content, bool on, GenericMenu.MenuFunction2 func, object userData) { - this.menuItems.Add(new GenericMenu.MenuItem(content, on, func, userData)); + this.menuItems.Add(new GenericMenu.MenuItem(content, false, on, func, userData)); } public void AddDisabledItem(GUIContent content) { - this.menuItems.Add(new GenericMenu.MenuItem(content, false, null)); + this.menuItems.Add(new GenericMenu.MenuItem(content, false, false, null)); } public void AddSeparator(string path) { - this.menuItems.Add(new GenericMenu.MenuItem(new GUIContent(path), false, null)); + this.menuItems.Add(new GenericMenu.MenuItem(new GUIContent(path), true, false, null)); } public int GetItemCount() { @@ -51,6 +54,10 @@ public int GetItemCount() } public void ShowAsContext() { + if (Event.current == null) + { + return; + } this.DropDown(new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 0f, 0f)); } public void DropDown(Rect position) @@ -58,17 +65,19 @@ public void DropDown(Rect position) string[] array = new string[this.menuItems.Count]; bool[] array2 = new bool[this.menuItems.Count]; ArrayList arrayList = new ArrayList(); + bool[] array3 = new bool[this.menuItems.Count]; for (int i = 0; i < this.menuItems.Count; i++) { GenericMenu.MenuItem menuItem = (GenericMenu.MenuItem)this.menuItems[i]; array[i] = menuItem.content.text; array2[i] = (menuItem.func != null || menuItem.func2 != null); + array3[i] = menuItem.separator; if (menuItem.on) { arrayList.Add(i); } } - EditorUtility.DisplayCustomMenu(position, array, array2, (int[])arrayList.ToArray(typeof(int)), new EditorUtility.SelectMenuItemFunction(this.CatchMenu), null); + EditorUtility.DisplayCustomMenuWithSeparators(position, array, array2, array3, (int[])arrayList.ToArray(typeof(int)), new EditorUtility.SelectMenuItemFunction(this.CatchMenu), null); } internal void Popup(Rect position, int selectedIndex) { diff --git a/UnityEditor/UnityEditor/GraphicsSettings.cs b/UnityEditor/UnityEditor/GraphicsSettings.cs new file mode 100644 index 00000000..9bf41918 --- /dev/null +++ b/UnityEditor/UnityEditor/GraphicsSettings.cs @@ -0,0 +1,8 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal sealed class GraphicsSettings : UnityEngine.Object + { + } +} diff --git a/UnityEditor/UnityEditor/GraphicsSettingsInspector.cs b/UnityEditor/UnityEditor/GraphicsSettingsInspector.cs new file mode 100644 index 00000000..7c85c54a --- /dev/null +++ b/UnityEditor/UnityEditor/GraphicsSettingsInspector.cs @@ -0,0 +1,182 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(GraphicsSettings))] + internal class GraphicsSettingsInspector : Editor + { + internal class Styles + { + public static readonly GUIContent builtinSettings = EditorGUIUtility.TextContent("GraphicsSettings.BuiltinSettings"); + public static readonly GUIContent shaderStrippingSettings = EditorGUIUtility.TextContent("GraphicsSettings.ShaderStrippingSettings"); + public static readonly GUIContent shaderPreloadSettings = EditorGUIUtility.TextContent("GraphicsSettings.ShaderPreloadSettings"); + public static readonly GUIContent lightmapModes = EditorGUIUtility.TextContent("GraphicsSettings.LightmapModes"); + public static readonly GUIContent lightmapPlain = EditorGUIUtility.TextContent("GraphicsSettings.LightmapPlain"); + public static readonly GUIContent lightmapDirCombined = EditorGUIUtility.TextContent("GraphicsSettings.LightmapDirCombined"); + public static readonly GUIContent lightmapDirSeparate = EditorGUIUtility.TextContent("GraphicsSettings.LightmapDirSeparate"); + public static readonly GUIContent lightmapDynamic = EditorGUIUtility.TextContent("GraphicsSettings.LightmapDynamic"); + public static readonly GUIContent lightmapFromScene = EditorGUIUtility.TextContent("GraphicsSettings.LightmapFromScene"); + public static readonly GUIContent fogModes = EditorGUIUtility.TextContent("GraphicsSettings.FogModes"); + public static readonly GUIContent fogLinear = EditorGUIUtility.TextContent("GraphicsSettings.FogLinear"); + public static readonly GUIContent fogExp = EditorGUIUtility.TextContent("GraphicsSettings.FogExp"); + public static readonly GUIContent fogExp2 = EditorGUIUtility.TextContent("GraphicsSettings.FogExp2"); + public static readonly GUIContent fogFromScene = EditorGUIUtility.TextContent("GraphicsSettings.FogFromScene"); + public static readonly GUIContent shaderPreloadSave = EditorGUIUtility.TextContent("GraphicsSettings.ShaderPreloadSave"); + public static readonly GUIContent shaderPreloadClear = EditorGUIUtility.TextContent("GraphicsSettings.ShaderPreloadClear"); + } + internal class BuiltinShaderSettings + { + internal enum BuiltinShaderMode + { + None, + Builtin, + Custom + } + private readonly SerializedProperty m_Mode; + private readonly SerializedProperty m_Shader; + private readonly GUIContent m_Label; + internal BuiltinShaderSettings(string label, string name, SerializedObject serializedObject) + { + this.m_Mode = serializedObject.FindProperty(name + ".m_Mode"); + this.m_Shader = serializedObject.FindProperty(name + ".m_Shader"); + this.m_Label = EditorGUIUtility.TextContent(label); + } + internal void DoGUI() + { + EditorGUILayout.PropertyField(this.m_Mode, this.m_Label, new GUILayoutOption[0]); + if (this.m_Mode.intValue == 2) + { + EditorGUILayout.PropertyField(this.m_Shader, new GUILayoutOption[0]); + } + EditorGUILayout.Space(); + } + } + protected GraphicsSettingsInspector.BuiltinShaderSettings m_Deferred; + protected GraphicsSettingsInspector.BuiltinShaderSettings m_LegacyDeferred; + protected SerializedProperty m_AlwaysIncludedShaders; + protected SerializedProperty m_PreloadedShaders; + protected SerializedProperty m_LightmapStripping; + protected SerializedProperty m_LightmapKeepPlain; + protected SerializedProperty m_LightmapKeepDirCombined; + protected SerializedProperty m_LightmapKeepDirSeparate; + protected SerializedProperty m_LightmapKeepDynamic; + protected SerializedProperty m_FogStripping; + protected SerializedProperty m_FogKeepLinear; + protected SerializedProperty m_FogKeepExp; + protected SerializedProperty m_FogKeepExp2; + public virtual void OnEnable() + { + this.m_Deferred = new GraphicsSettingsInspector.BuiltinShaderSettings("GraphicsSettings.DeferredSettings", "m_Deferred", base.serializedObject); + this.m_LegacyDeferred = new GraphicsSettingsInspector.BuiltinShaderSettings("GraphicsSettings.LegacyDeferredSettings", "m_LegacyDeferred", base.serializedObject); + this.m_AlwaysIncludedShaders = base.serializedObject.FindProperty("m_AlwaysIncludedShaders"); + this.m_AlwaysIncludedShaders.isExpanded = true; + this.m_PreloadedShaders = base.serializedObject.FindProperty("m_PreloadedShaders"); + this.m_PreloadedShaders.isExpanded = true; + this.m_LightmapStripping = base.serializedObject.FindProperty("m_LightmapStripping"); + this.m_LightmapKeepPlain = base.serializedObject.FindProperty("m_LightmapKeepPlain"); + this.m_LightmapKeepDirCombined = base.serializedObject.FindProperty("m_LightmapKeepDirCombined"); + this.m_LightmapKeepDirSeparate = base.serializedObject.FindProperty("m_LightmapKeepDirSeparate"); + this.m_LightmapKeepDynamic = base.serializedObject.FindProperty("m_LightmapKeepDynamic"); + this.m_FogStripping = base.serializedObject.FindProperty("m_FogStripping"); + this.m_FogKeepLinear = base.serializedObject.FindProperty("m_FogKeepLinear"); + this.m_FogKeepExp = base.serializedObject.FindProperty("m_FogKeepExp"); + this.m_FogKeepExp2 = base.serializedObject.FindProperty("m_FogKeepExp2"); + } + private void LightmapStrippingGUI(out bool calcLightmapStripping) + { + calcLightmapStripping = false; + EditorGUILayout.PropertyField(this.m_LightmapStripping, GraphicsSettingsInspector.Styles.lightmapModes, new GUILayoutOption[0]); + if (this.m_LightmapStripping.intValue != 0) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_LightmapKeepPlain, GraphicsSettingsInspector.Styles.lightmapPlain, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LightmapKeepDirCombined, GraphicsSettingsInspector.Styles.lightmapDirCombined, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LightmapKeepDirSeparate, GraphicsSettingsInspector.Styles.lightmapDirSeparate, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LightmapKeepDynamic, GraphicsSettingsInspector.Styles.lightmapDynamic, new GUILayoutOption[0]); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton); + if (GUILayout.Button(GraphicsSettingsInspector.Styles.lightmapFromScene, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + calcLightmapStripping = true; + } + EditorGUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + } + private void FogStrippingGUI(out bool calcFogStripping) + { + calcFogStripping = false; + EditorGUILayout.PropertyField(this.m_FogStripping, GraphicsSettingsInspector.Styles.fogModes, new GUILayoutOption[0]); + if (this.m_FogStripping.intValue != 0) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_FogKeepLinear, GraphicsSettingsInspector.Styles.fogLinear, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_FogKeepExp, GraphicsSettingsInspector.Styles.fogExp, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_FogKeepExp2, GraphicsSettingsInspector.Styles.fogExp2, new GUILayoutOption[0]); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(GUIContent.Temp(" "), EditorStyles.miniButton); + if (GUILayout.Button(GraphicsSettingsInspector.Styles.fogFromScene, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + calcFogStripping = true; + } + EditorGUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + } + private void ShaderPreloadGUI() + { + EditorGUILayout.Space(); + GUILayout.Label(GraphicsSettingsInspector.Styles.shaderPreloadSettings, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PreloadedShaders, true, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(string.Format("Currently tracked: {0} shaders {1} total variants", ShaderUtil.GetCurrentShaderVariantCollectionShaderCount(), ShaderUtil.GetCurrentShaderVariantCollectionVariantCount()), new GUILayoutOption[0]); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + if (GUILayout.Button(GraphicsSettingsInspector.Styles.shaderPreloadSave, EditorStyles.miniButton, new GUILayoutOption[0])) + { + string message = "Save shader variant collection"; + string text = EditorUtility.SaveFilePanelInProject("Save Shader Variant Collection", "NewShaderVariants", "shadervariants", message, ProjectWindowUtil.GetActiveFolderPath()); + if (!string.IsNullOrEmpty(text)) + { + ShaderUtil.SaveCurrentShaderVariantCollection(text); + } + GUIUtility.ExitGUI(); + } + if (GUILayout.Button(GraphicsSettingsInspector.Styles.shaderPreloadClear, EditorStyles.miniButton, new GUILayoutOption[0])) + { + ShaderUtil.ClearCurrentShaderVariantCollection(); + } + EditorGUILayout.EndHorizontal(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + bool flag = false; + bool flag2 = false; + GUILayout.Label(GraphicsSettingsInspector.Styles.builtinSettings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_Deferred.DoGUI(); + this.m_LegacyDeferred.DoGUI(); + EditorGUILayout.PropertyField(this.m_AlwaysIncludedShaders, true, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(GraphicsSettingsInspector.Styles.shaderStrippingSettings, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.LightmapStrippingGUI(out flag); + this.FogStrippingGUI(out flag2); + this.ShaderPreloadGUI(); + base.serializedObject.ApplyModifiedProperties(); + if (flag) + { + ShaderUtil.CalculateLightmapStrippingFromCurrentScene(); + } + if (flag2) + { + ShaderUtil.CalculateFogStrippingFromCurrentScene(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/HandleUtility.cs b/UnityEditor/UnityEditor/HandleUtility.cs index 4adad741..b15ffe03 100644 --- a/UnityEditor/UnityEditor/HandleUtility.cs +++ b/UnityEditor/UnityEditor/HandleUtility.cs @@ -63,6 +63,8 @@ internal void Restore(Camera dest) private static Material s_HandleMaterial; private static Material s_HandleWireMaterial; private static Material s_HandleWireMaterial2D; + private static int s_HandleWireTextureIndex; + private static int s_HandleWireTextureIndex2D; private static Stack s_SavedCameras = new Stack(); internal static Transform[] ignoreRaySnapObjects = null; public static float acceleration @@ -141,15 +143,11 @@ public static Material handleMaterial return HandleUtility.s_HandleMaterial; } } - internal static Material handleWireMaterial + private static Material handleWireMaterial { get { - if (!HandleUtility.s_HandleWireMaterial) - { - HandleUtility.s_HandleWireMaterial = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat"); - HandleUtility.s_HandleWireMaterial2D = (Material)EditorGUIUtility.LoadRequired("SceneView/2DHandleLines.mat"); - } + HandleUtility.InitHandleMaterials(); return (!Camera.current) ? HandleUtility.s_HandleWireMaterial2D : HandleUtility.s_HandleWireMaterial; } } @@ -503,10 +501,10 @@ public static GameObject[] PickRectObjects(Rect rect) public static GameObject[] PickRectObjects(Rect rect, bool selectPrefabRootsOnly) { Camera current = Camera.current; - rect.x /= current.pixelWidth; - rect.width /= current.pixelWidth; - rect.y /= current.pixelHeight; - rect.height /= current.pixelHeight; + rect.x /= (float)current.pixelWidth; + rect.width /= (float)current.pixelWidth; + rect.y /= (float)current.pixelHeight; + rect.height /= (float)current.pixelHeight; return HandleUtility.Internal_PickRectObjects(current, rect, selectPrefabRootsOnly); } internal static GameObject[] Internal_PickRectObjects(Camera cam, Rect rect, bool selectPrefabRoots) @@ -529,13 +527,18 @@ private static bool Internal_FindNearestVertex(Camera cam, Vector2 point, Transf [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool INTERNAL_CALL_Internal_FindNearestVertex(Camera cam, ref Vector2 point, Transform[] objectsToSearch, Transform[] ignoreObjects, out Vector3 vertex); - public static GameObject PickGameObject(Vector2 position, bool selectPrefabRoot) + public static GameObject PickGameObject(Vector2 position, out int materialIndex) { Camera current = Camera.current; int cullingMask = current.cullingMask; position = GUIClip.Unclip(position); position.y = (float)Screen.height - position.y - current.pixelRect.yMin; - GameObject gameObject = HandleUtility.Internal_PickClosestGO(current, cullingMask, position); + return HandleUtility.Internal_PickClosestGO(current, cullingMask, position, out materialIndex); + } + public static GameObject PickGameObject(Vector2 position, bool selectPrefabRoot) + { + int num; + GameObject gameObject = HandleUtility.PickGameObject(position, out num); if (!gameObject || !selectPrefabRoot) { return gameObject; @@ -572,13 +575,33 @@ private static GameObject FindSelectionBase(GameObject go) } return null; } - internal static GameObject Internal_PickClosestGO(Camera cam, int layers, Vector2 position) + internal static GameObject Internal_PickClosestGO(Camera cam, int layers, Vector2 position, out int materialIndex) + { + return HandleUtility.INTERNAL_CALL_Internal_PickClosestGO(cam, layers, ref position, out materialIndex); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GameObject INTERNAL_CALL_Internal_PickClosestGO(Camera cam, int layers, ref Vector2 position, out int materialIndex); + private static void InitHandleMaterials() + { + if (!HandleUtility.s_HandleWireMaterial) + { + HandleUtility.s_HandleWireMaterial = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat"); + HandleUtility.s_HandleWireMaterial2D = (Material)EditorGUIUtility.LoadRequired("SceneView/2DHandleLines.mat"); + HandleUtility.s_HandleWireTextureIndex = ShaderUtil.GetTextureBindingIndex(HandleUtility.s_HandleWireMaterial.shader, Shader.PropertyToID("_MainTex")); + HandleUtility.s_HandleWireTextureIndex2D = ShaderUtil.GetTextureBindingIndex(HandleUtility.s_HandleWireMaterial2D.shader, Shader.PropertyToID("_MainTex")); + } + } + internal static void ApplyWireMaterial() { - return HandleUtility.INTERNAL_CALL_Internal_PickClosestGO(cam, layers, ref position); + Material handleWireMaterial = HandleUtility.handleWireMaterial; + handleWireMaterial.SetPass(0); + int textureIndex = (!Camera.current) ? HandleUtility.s_HandleWireTextureIndex2D : HandleUtility.s_HandleWireTextureIndex; + HandleUtility.Internal_SetHandleWireTextureIndex(textureIndex); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern GameObject INTERNAL_CALL_Internal_PickClosestGO(Camera cam, int layers, ref Vector2 position); + private static extern void Internal_SetHandleWireTextureIndex(int textureIndex); public static void PushCamera(Camera camera) { HandleUtility.s_SavedCameras.Push(new HandleUtility.SavedCamera(camera)); diff --git a/UnityEditor/UnityEditor/Handles.cs b/UnityEditor/UnityEditor/Handles.cs index ab91878d..f74b3ee1 100644 --- a/UnityEditor/UnityEditor/Handles.cs +++ b/UnityEditor/UnityEditor/Handles.cs @@ -8,30 +8,21 @@ namespace UnityEditor { public sealed class Handles { - private enum PlaneHandle - { - xzPlane, - xyPlane, - yzPlane - } internal enum FilterMode { Off, ShowFiltered, ShowRest } + private enum PlaneHandle + { + xzPlane, + xyPlane, + yzPlane + } public delegate void DrawCapFunction(int controlID, Vector3 position, Quaternion rotation, float size); - private const float k_BoneThickness = 0.08f; private const int kMaxDottedLineVertices = 1000; - private static Vector3[] verts = new Vector3[] - { - Vector3.zero, - Vector3.zero, - Vector3.zero, - Vector3.zero - }; - private static bool s_FreeMoveMode = false; - private static Vector3 s_PlanarHandlesOctant = Vector3.one; + private const float k_BoneThickness = 0.08f; internal static PrefColor s_XAxisColor = new PrefColor("Scene/X Axis", 0.858823538f, 0.243137255f, 0.113725491f, 0.93f); internal static PrefColor s_YAxisColor = new PrefColor("Scene/Y Axis", 0.6039216f, 0.9529412f, 0.282352954f, 0.93f); internal static PrefColor s_ZAxisColor = new PrefColor("Scene/Z Axis", 0.227450982f, 0.478431374f, 0.972549f, 0.93f); @@ -69,13 +60,15 @@ internal enum FilterMode internal static Mesh s_ConeMesh; internal static Mesh s_CylinderMesh; internal static Mesh s_QuadMesh; - private static bool currentlyDragging + private static Vector3[] verts = new Vector3[] { - get - { - return GUIUtility.hotControl != 0; - } - } + Vector3.zero, + Vector3.zero, + Vector3.zero, + Vector3.zero + }; + private static bool s_FreeMoveMode = false; + private static Vector3 s_PlanarHandlesOctant = Vector3.one; public static Color xAxisColor { get @@ -177,1442 +170,1544 @@ internal static Color realHandleColor return Handles.s_Color * new Color(1f, 1f, 1f, 0.5f) + ((!Handles.s_Lighting) ? new Color(0f, 0f, 0f, 0f) : new Color(0f, 0f, 0f, 0.5f)); } } - internal static float DistanceToPolygone(Vector3[] vertices) + private static bool currentlyDragging { - return HandleUtility.DistanceToPolyLine(vertices); + get + { + return GUIUtility.hotControl != 0; + } } - internal static void DoBoneHandle(Transform target) + public static Vector3 PositionHandle(Vector3 position, Quaternion rotation) { - Handles.DoBoneHandle(target, null); + return Handles.DoPositionHandle(position, rotation); } - internal static void DoBoneHandle(Transform target, Dictionary validBones) + public static Quaternion RotationHandle(Quaternion rotation, Vector3 position) { - int hashCode = target.name.GetHashCode(); - Event current = Event.current; - bool flag = false; - if (validBones != null) - { - foreach (Transform key in target) - { - if (validBones.ContainsKey(key)) - { - flag = true; - break; - } - } - } - Vector3 position = target.position; - List list = new List(); - if (!flag && target.parent != null) - { - list.Add(target.position + (target.position - target.parent.position) * 0.4f); - } - else - { - foreach (Transform transform in target) - { - if (validBones == null || validBones.ContainsKey(transform)) - { - list.Add(transform.position); - } - } - } - for (int i = 0; i < list.Count; i++) - { - Vector3 vector = list[i]; - switch (current.GetTypeForControl(hashCode)) - { - case EventType.MouseDown: - if ((HandleUtility.nearestControl == hashCode && current.button == 0) || (GUIUtility.keyboardControl == hashCode && current.button == 2)) - { - int num = hashCode; - GUIUtility.keyboardControl = num; - GUIUtility.hotControl = num; - if (current.shift) - { - UnityEngine.Object[] objects = Selection.objects; - if (!ArrayUtility.Contains(objects, target)) - { - ArrayUtility.Add(ref objects, target); - Selection.objects = objects; - } - } - else - { - Selection.activeObject = target; - } - EditorGUIUtility.PingObject(target); - current.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == hashCode && (current.button == 0 || current.button == 2)) - { - GUIUtility.hotControl = 0; - current.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == hashCode) - { - DragAndDrop.PrepareStartDrag(); - DragAndDrop.objectReferences = new UnityEngine.Object[] - { - target - }; - DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(target)); - current.Use(); - } - break; - case EventType.Repaint: - { - float num2 = Vector3.Magnitude(vector - position); - if (num2 > 0f) - { - float num3 = num2 * 0.08f; - if (flag) - { - Handles.DrawBone(vector, position, num3); - } - else - { - Handles.SphereCap(hashCode, position, target.rotation, num3 * 5f); - } - } - break; - } - case EventType.Layout: - { - float num4 = Vector3.Magnitude(vector - position); - float radius = num4 * 0.08f; - Vector3[] boneVertices = Handles.GetBoneVertices(vector, position, radius); - HandleUtility.AddControl(hashCode, Handles.DistanceToPolygone(boneVertices)); - break; - } - } - } + return Handles.DoRotationHandle(rotation, position); } - internal static void DrawBone(Vector3 endPoint, Vector3 basePoint, float size) + public static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) { - Vector3[] boneVertices = Handles.GetBoneVertices(endPoint, basePoint, size); - HandleUtility.handleWireMaterial.SetPass(0); - GL.Begin(4); - GL.Color(Handles.s_Color); - for (int i = 0; i < 3; i++) - { - GL.Vertex(boneVertices[i * 6]); - GL.Vertex(boneVertices[i * 6 + 1]); - GL.Vertex(boneVertices[i * 6 + 2]); - GL.Vertex(boneVertices[i * 6 + 3]); - GL.Vertex(boneVertices[i * 6 + 4]); - GL.Vertex(boneVertices[i * 6 + 5]); - } - GL.End(); - GL.Begin(1); - GL.Color(Handles.s_Color * new Color(1f, 1f, 1f, 0f) + new Color(0f, 0f, 0f, 1f)); - for (int j = 0; j < 3; j++) - { - GL.Vertex(boneVertices[j * 6]); - GL.Vertex(boneVertices[j * 6 + 1]); - GL.Vertex(boneVertices[j * 6 + 1]); - GL.Vertex(boneVertices[j * 6 + 2]); - } - GL.End(); + return Handles.DoScaleHandle(scale, position, rotation, size); } - internal static Vector3[] GetBoneVertices(Vector3 endPoint, Vector3 basePoint, float radius) + public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) { - Vector3 lhs = Vector3.Normalize(endPoint - basePoint); - Vector3 vector = Vector3.Cross(lhs, Vector3.up); - if (Vector3.SqrMagnitude(vector) < 0.1f) - { - vector = Vector3.Cross(lhs, Vector3.right); - } - vector.Normalize(); - Vector3 a = Vector3.Cross(lhs, vector); - Vector3[] array = new Vector3[18]; - float num = 0f; - for (int i = 0; i < 3; i++) - { - float num2 = Mathf.Cos(num); - float num3 = Mathf.Sin(num); - float num4 = Mathf.Cos(num + 2.09439516f); - float num5 = Mathf.Sin(num + 2.09439516f); - Vector3 vector2 = basePoint + vector * (num2 * radius) + a * (num3 * radius); - Vector3 vector3 = basePoint + vector * (num4 * radius) + a * (num5 * radius); - array[i * 6] = endPoint; - array[i * 6 + 1] = vector2; - array[i * 6 + 2] = vector3; - array[i * 6 + 3] = basePoint; - array[i * 6 + 4] = vector3; - array[i * 6 + 5] = vector2; - num += 2.09439516f; - } - return array; + return Handles.DoRadiusHandle(rotation, position, radius, handlesOnly); } - internal static Vector3 DoConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) + public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius) { - Vector3 vector = rotation * Vector3.forward; - Vector3 vector2 = rotation * Vector3.up; - Vector3 vector3 = rotation * Vector3.right; - float num = radiusAngleRange.x; - float num2 = radiusAngleRange.y; - float num3 = radiusAngleRange.z; - num2 = Mathf.Max(0f, num2); - bool changed = GUI.changed; - num3 = Handles.SizeSlider(position, vector, num3); - GUI.changed |= changed; - changed = GUI.changed; - GUI.changed = false; - num = Handles.SizeSlider(position, vector2, num); - num = Handles.SizeSlider(position, -vector2, num); - num = Handles.SizeSlider(position, vector3, num); - num = Handles.SizeSlider(position, -vector3, num); - if (GUI.changed) - { - num = Mathf.Max(0f, num); - } - GUI.changed |= changed; - changed = GUI.changed; - GUI.changed = false; - float num4 = Mathf.Min(1000f, Mathf.Abs(num3 * Mathf.Tan(0.0174532924f * num2)) + num); - num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); - num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); - num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); - num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); - if (GUI.changed) - { - num2 = Mathf.Clamp(57.29578f * Mathf.Atan((num4 - num) / Mathf.Abs(num3)), 0f, 90f); - } - GUI.changed |= changed; - if (num > 0f) - { - Handles.DrawWireDisc(position, vector, num); - } - if (num4 > 0f) - { - Handles.DrawWireDisc(position + num3 * vector, vector, num4); - } - Handles.DrawLine(position + vector2 * num, position + vector * num3 + vector2 * num4); - Handles.DrawLine(position - vector2 * num, position + vector * num3 - vector2 * num4); - Handles.DrawLine(position + vector3 * num, position + vector * num3 + vector3 * num4); - Handles.DrawLine(position - vector3 * num, position + vector * num3 - vector3 * num4); - return new Vector3(num, num2, num3); + return Handles.DoRadiusHandle(rotation, position, radius, false); } - internal static Vector2 DoConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) + internal static Vector2 ConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) { - float num = angleAndRange.x; - float num2 = angleAndRange.y; - float num3 = num2 * rangeScale; - Vector3 vector = rotation * Vector3.forward; - Vector3 vector2 = rotation * Vector3.up; - Vector3 vector3 = rotation * Vector3.right; - bool changed = GUI.changed; - GUI.changed = false; - num3 = Handles.SizeSlider(position, vector, num3); - if (GUI.changed) + return Handles.DoConeHandle(rotation, position, angleAndRange, angleScale, rangeScale, handlesOnly); + } + internal static Vector3 ConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) + { + return Handles.DoConeFrustrumHandle(rotation, position, radiusAngleRange); + } + public static Vector3 Slider(Vector3 position, Vector3 direction) + { + return Handles.Slider(position, direction, HandleUtility.GetHandleSize(position), new Handles.DrawCapFunction(Handles.ArrowCap), -1f); + } + public static Vector3 Slider(Vector3 position, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_SliderHash, FocusType.Keyboard); + return Slider1D.Do(controlID, position, direction, size, drawFunc, snap); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + return UnityEditorInternal.Slider2D.Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); + return UnityEditorInternal.Slider2D.Do(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + { + bool drawHelper = false; + return Handles.Slider2D(id, handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + { + return UnityEditorInternal.Slider2D.Do(id, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + [ExcludeFromDocs] + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap) + { + bool drawHelper = false; + return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + } + public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap, [DefaultValue("false")] bool drawHelper) + { + int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); + return Handles.Slider2D(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); + } + public static Quaternion FreeRotateHandle(Quaternion rotation, Vector3 position, float size) + { + int controlID = GUIUtility.GetControlID(Handles.s_FreeRotateHandleHash, FocusType.Keyboard); + return FreeRotate.Do(controlID, rotation, position, size); + } + public static Vector3 FreeMoveHandle(Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.DrawCapFunction capFunc) + { + int controlID = GUIUtility.GetControlID(Handles.s_FreeMoveHandleHash, FocusType.Keyboard); + return FreeMove.Do(controlID, position, rotation, size, snap, capFunc); + } + public static float ScaleSlider(float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_ScaleSliderHash, FocusType.Keyboard); + return SliderScale.DoAxis(controlID, scale, position, direction, rotation, size, snap); + } + public static float ScaleValueHandle(float value, Vector3 position, Quaternion rotation, float size, Handles.DrawCapFunction capFunc, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_ScaleValueHandleHash, FocusType.Keyboard); + return SliderScale.DoCenter(controlID, value, position, rotation, size, capFunc, snap); + } + public static Quaternion Disc(Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) + { + int controlID = GUIUtility.GetControlID(Handles.s_DiscHash, FocusType.Keyboard); + return UnityEditorInternal.Disc.Do(controlID, rotation, position, axis, size, cutoffPlane, snap); + } + public static bool Button(Vector3 position, Quaternion direction, float size, float pickSize, Handles.DrawCapFunction capFunc) + { + int controlID = GUIUtility.GetControlID(Handles.s_ButtonHash, FocusType.Passive); + return UnityEditorInternal.Button.Do(controlID, position, direction, size, pickSize, capFunc); + } + internal static void SetupIgnoreRaySnapObjects() + { + HandleUtility.ignoreRaySnapObjects = Selection.GetTransforms((SelectionMode)10); + } + public static float SnapValue(float val, float snap) + { + if (EditorGUI.actionKey && snap > 0f) { - num2 = Mathf.Max(0f, num3 / rangeScale); + return Mathf.Round(val / snap) * snap; } - GUI.changed |= changed; - changed = GUI.changed; - GUI.changed = false; - float num4 = num3 * Mathf.Tan(0.0174532924f * num / 2f) * angleScale; - num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); - num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); - num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); - num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); - if (GUI.changed) + return val; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawCameraWithGrid(Camera cam, int renderMode, ref DrawGridParameters gridParam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_DrawCamera(Camera cam, int renderMode); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_FinishDrawingCamera(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_ClearCamera(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Internal_SetCurrentCamera(Camera cam); + internal static void SetSceneViewColors(Color wire, Color wireOverlay, Color active, Color selected) + { + Handles.INTERNAL_CALL_SetSceneViewColors(ref wire, ref wireOverlay, ref active, ref selected); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetSceneViewColors(ref Color wire, ref Color wireOverlay, ref Color active, ref Color selected); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraFx(Camera cam, bool fx); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraFlares(Camera cam, bool flares); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EnableCameraSkybox(Camera cam, bool skybox); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetCameraOnlyDrawMesh(Camera cam); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetupCamera(Camera cam); + internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, float radius) + { + Color color = Handles.color; + Color color2 = color; + color.a *= Handles.backfaceAlphaMultiplier; + Handles.color = color; + Handles.DrawWireDisc(position, axis, radius); + Handles.color = color2; + } + internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, Vector3 from, float degrees, float radius) + { + Handles.DrawWireArc(position, axis, from, degrees, radius); + Color color = Handles.color; + Color color2 = color; + color.a *= Handles.backfaceAlphaMultiplier; + Handles.color = color; + Handles.DrawWireArc(position, axis, from, degrees - 360f, radius); + Handles.color = color2; + } + internal static Matrix4x4 StartCapDraw(Vector3 position, Quaternion rotation, float size) + { + Shader.SetGlobalColor("_HandleColor", Handles.realHandleColor); + Shader.SetGlobalFloat("_HandleSize", size); + Matrix4x4 matrix4x = Handles.matrix * Matrix4x4.TRS(position, rotation, Vector3.one); + Shader.SetGlobalMatrix("_ObjectToWorld", matrix4x); + HandleUtility.handleMaterial.SetPass(0); + return matrix4x; + } + public static void CubeCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) { - num = Mathf.Clamp(57.29578f * Mathf.Atan(num4 / (num3 * angleScale)) * 2f, 0f, 179f); + return; } - GUI.changed |= changed; - if (!handlesOnly) + Graphics.DrawMeshNow(Handles.s_CubeMesh, Handles.StartCapDraw(position, rotation, size)); + } + public static void SphereCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) { - Handles.DrawLine(position, position + vector * num3 + vector2 * num4); - Handles.DrawLine(position, position + vector * num3 - vector2 * num4); - Handles.DrawLine(position, position + vector * num3 + vector3 * num4); - Handles.DrawLine(position, position + vector * num3 - vector3 * num4); - Handles.DrawWireDisc(position + num3 * vector, vector, num4); + return; } - return new Vector2(num, num2); + Graphics.DrawMeshNow(Handles.s_SphereMesh, Handles.StartCapDraw(position, rotation, size)); } - private static float SizeSlider(Vector3 p, Vector3 d, float r) + public static void ConeCap(int controlID, Vector3 position, Quaternion rotation, float size) { - Vector3 vector = p + d * r; - float handleSize = HandleUtility.GetHandleSize(vector); - bool changed = GUI.changed; - GUI.changed = false; - vector = Handles.Slider(vector, d, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); - if (GUI.changed) + if (Event.current.type != EventType.Repaint) { - r = Vector3.Dot(vector - p, d); + return; } - GUI.changed |= changed; - return r; + Graphics.DrawMeshNow(Handles.s_ConeMesh, Handles.StartCapDraw(position, rotation, size)); } - public static Vector3 DoPositionHandle(Vector3 position, Quaternion rotation) + public static void CylinderCap(int controlID, Vector3 position, Quaternion rotation, float size) { - Event current = Event.current; - switch (current.type) + if (Event.current.type != EventType.Repaint) { - case EventType.KeyDown: - if (current.keyCode == KeyCode.V && !Handles.currentlyDragging) - { - Handles.s_FreeMoveMode = true; - } - break; - case EventType.KeyUp: - position = Handles.DoPositionHandle_Internal(position, rotation); - if (current.keyCode == KeyCode.V && !current.shift && !Handles.currentlyDragging) - { - Handles.s_FreeMoveMode = false; - } - return position; - case EventType.Layout: - if (!Handles.currentlyDragging && !Tools.vertexDragging) - { - Handles.s_FreeMoveMode = current.shift; - } - break; + return; } - return Handles.DoPositionHandle_Internal(position, rotation); + Graphics.DrawMeshNow(Handles.s_CylinderMesh, Handles.StartCapDraw(position, rotation, size)); } - private static Vector3 DoPositionHandle_Internal(Vector3 position, Quaternion rotation) + public static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, float size) { - float handleSize = HandleUtility.GetHandleSize(position); - Color color = Handles.color; - bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); - Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); - GUI.SetNextControlName("xAxis"); - position = Handles.Slider(position, rotation * Vector3.right, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.x); - Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); - GUI.SetNextControlName("yAxis"); - position = Handles.Slider(position, rotation * Vector3.up, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.y); - Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); - GUI.SetNextControlName("zAxis"); - position = Handles.Slider(position, rotation * Vector3.forward, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.z); - if (Handles.s_FreeMoveMode) - { - Handles.color = Handles.centerColor; - GUI.SetNextControlName("FreeMoveAxis"); - position = Handles.FreeMoveHandle(position, rotation, handleSize * 0.15f, SnapSettings.move, new Handles.DrawCapFunction(Handles.RectangleCap)); - } - else - { - position = Handles.DoPlanarHandle(Handles.PlaneHandle.xzPlane, position, rotation, handleSize * 0.25f); - position = Handles.DoPlanarHandle(Handles.PlaneHandle.xyPlane, position, rotation, handleSize * 0.25f); - position = Handles.DoPlanarHandle(Handles.PlaneHandle.yzPlane, position, rotation, handleSize * 0.25f); - } - Handles.color = color; - return position; + Handles.RectangleCap(controlID, position, rotation, new Vector2(size, size)); } - private static Vector3 DoPlanarHandle(Handles.PlaneHandle planeID, Vector3 position, Quaternion rotation, float handleSize) + internal static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, Vector2 size) { - int num = 0; - int num2 = 0; - int hint = 0; - bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); - switch (planeID) - { - case Handles.PlaneHandle.xzPlane: - num = 0; - num2 = 2; - Handles.color = ((!flag) ? Handles.yAxisColor : Handles.staticColor); - hint = Handles.s_xzAxisMoveHandleHash; - break; - case Handles.PlaneHandle.xyPlane: - num = 0; - num2 = 1; - Handles.color = ((!flag) ? Handles.zAxisColor : Handles.staticColor); - hint = Handles.s_xyAxisMoveHandleHash; - break; - case Handles.PlaneHandle.yzPlane: - num = 1; - num2 = 2; - Handles.color = ((!flag) ? Handles.xAxisColor : Handles.staticColor); - hint = Handles.s_yzAxisMoveHandleHash; - break; - } - int index = 3 - num2 - num; - Color color = Handles.color; - Matrix4x4 matrix4x = Matrix4x4.TRS(position, rotation, Vector3.one); - Vector3 normalized; - if (Camera.current.orthographic) - { - normalized = matrix4x.inverse.MultiplyVector(SceneView.currentDrawingSceneView.cameraTargetRotation * -Vector3.forward).normalized; - } - else + if (Event.current.type != EventType.Repaint) { - normalized = matrix4x.inverse.MultiplyPoint(SceneView.currentDrawingSceneView.camera.transform.position).normalized; + return; } - int controlID = GUIUtility.GetControlID(hint, FocusType.Keyboard); - if (Mathf.Abs(normalized[index]) < 0.05f && GUIUtility.hotControl != controlID) + Vector3 b = rotation * new Vector3(size.x, 0f, 0f); + Vector3 b2 = rotation * new Vector3(0f, size.y, 0f); + Handles.s_RectangleCapPointsCache[0] = position + b + b2; + Handles.s_RectangleCapPointsCache[1] = position + b - b2; + Handles.s_RectangleCapPointsCache[2] = position - b - b2; + Handles.s_RectangleCapPointsCache[3] = position - b + b2; + Handles.s_RectangleCapPointsCache[4] = position + b + b2; + Handles.DrawPolyLine(Handles.s_RectangleCapPointsCache); + } + public static void SelectionFrame(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) { - Handles.color = color; - return position; + return; } - if (!Handles.currentlyDragging) + Handles.StartCapDraw(position, rotation, size); + Vector3 b = rotation * new Vector3(size, 0f, 0f); + Vector3 b2 = rotation * new Vector3(0f, size, 0f); + Vector3 vector = position - b + b2; + Vector3 vector2 = position + b + b2; + Vector3 vector3 = position + b - b2; + Vector3 vector4 = position - b - b2; + Handles.DrawLine(vector, vector2); + Handles.DrawLine(vector2, vector3); + Handles.DrawLine(vector3, vector4); + Handles.DrawLine(vector4, vector); + } + public static void DotCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) { - Handles.s_PlanarHandlesOctant[num] = (float)((normalized[num] >= -0.01f) ? 1 : -1); - Handles.s_PlanarHandlesOctant[num2] = (float)((normalized[num2] >= -0.01f) ? 1 : -1); + return; } - Vector3 vector = Handles.s_PlanarHandlesOctant; - vector[index] = 0f; - vector = rotation * (vector * handleSize * 0.5f); - Vector3 vector2 = Vector3.zero; - Vector3 vector3 = Vector3.zero; - Vector3 vector4 = Vector3.zero; - vector2[num] = 1f; - vector3[num2] = 1f; - vector4[index] = 1f; - vector2 = rotation * vector2; - vector3 = rotation * vector3; - vector4 = rotation * vector4; - Handles.verts[0] = position + vector + (vector2 + vector3) * handleSize * 0.5f; - Handles.verts[1] = position + vector + (-vector2 + vector3) * handleSize * 0.5f; - Handles.verts[2] = position + vector + (-vector2 - vector3) * handleSize * 0.5f; - Handles.verts[3] = position + vector + (vector2 - vector3) * handleSize * 0.5f; - Handles.DrawSolidRectangleWithOutline(Handles.verts, new Color(Handles.color.r, Handles.color.g, Handles.color.b, 0.1f), new Color(0f, 0f, 0f, 0f)); - position = Handles.Slider2D(controlID, position, vector, vector4, vector2, vector3, handleSize * 0.5f, new Handles.DrawCapFunction(Handles.RectangleCap), new Vector2(SnapSettings.move[num], SnapSettings.move[num2])); - Handles.color = color; - return position; + position = Handles.matrix.MultiplyPoint(position); + Vector3 b = Camera.current.transform.right * size; + Vector3 b2 = Camera.current.transform.up * size; + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.99f); + HandleUtility.ApplyWireMaterial(); + GL.Begin(7); + GL.Color(c); + GL.Vertex(position + b + b2); + GL.Vertex(position + b - b2); + GL.Vertex(position - b - b2); + GL.Vertex(position - b + b2); + GL.End(); } - internal static float DoRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) + public static void CircleCap(int controlID, Vector3 position, Quaternion rotation, float size) { - float num = 90f; - Vector3[] array = new Vector3[] - { - rotation * Vector3.right, - rotation * Vector3.up, - rotation * Vector3.forward, - rotation * -Vector3.right, - rotation * -Vector3.up, - rotation * -Vector3.forward - }; - Vector3 vector; - if (Camera.current.orthographic) + if (Event.current.type != EventType.Repaint) { - vector = Camera.current.transform.forward; - if (!handlesOnly) - { - Handles.DrawWireDisc(position, vector, radius); - for (int i = 0; i < 3; i++) - { - Vector3 normalized = Vector3.Cross(array[i], vector).normalized; - Handles.DrawTwoShadedWireDisc(position, array[i], normalized, 180f, radius); - } - } + return; } - else + Handles.StartCapDraw(position, rotation, size); + Vector3 normal = rotation * new Vector3(0f, 0f, 1f); + Handles.DrawWireDisc(position, normal, size); + } + public static void ArrowCap(int controlID, Vector3 position, Quaternion rotation, float size) + { + if (Event.current.type != EventType.Repaint) { - vector = position - Camera.current.transform.position; - float sqrMagnitude = vector.sqrMagnitude; - float num2 = radius * radius; - float num3 = num2 * num2 / sqrMagnitude; - float num4 = num3 / num2; - if (num4 < 1f) - { - float num5 = Mathf.Sqrt(num2 - num3); - num = Mathf.Atan2(num5, Mathf.Sqrt(num3)) * 57.29578f; - if (!handlesOnly) - { - Handles.DrawWireDisc(position - num2 * vector / sqrMagnitude, vector, num5); - } - } - else - { - num = -1000f; - } - if (!handlesOnly) - { - for (int j = 0; j < 3; j++) - { - if (num4 < 1f) - { - float num6 = Vector3.Angle(vector, array[j]); - num6 = 90f - Mathf.Min(num6, 180f - num6); - float num7 = Mathf.Tan(num6 * 0.0174532924f); - float num8 = Mathf.Sqrt(num3 + num7 * num7 * num3) / radius; - if (num8 < 1f) - { - float num9 = Mathf.Asin(num8) * 57.29578f; - Vector3 vector2 = Vector3.Cross(array[j], vector).normalized; - vector2 = Quaternion.AngleAxis(num9, array[j]) * vector2; - Handles.DrawTwoShadedWireDisc(position, array[j], vector2, (90f - num9) * 2f, radius); - } - else - { - Handles.DrawTwoShadedWireDisc(position, array[j], radius); - } - } - else - { - Handles.DrawTwoShadedWireDisc(position, array[j], radius); - } - } - } + return; } - Color color = Handles.color; - for (int k = 0; k < 6; k++) + Vector3 vector = rotation * Vector3.forward; + Handles.ConeCap(controlID, position + vector * size, Quaternion.LookRotation(vector), size * 0.2f); + Handles.DrawLine(position, position + vector * size * 0.9f); + } + [Obsolete("DrawCylinder has been renamed to CylinderCap.")] + public static void DrawCylinder(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.CylinderCap(controlID, position, rotation, size); + } + [Obsolete("DrawSphere has been renamed to SphereCap.")] + public static void DrawSphere(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.SphereCap(controlID, position, rotation, size); + } + [Obsolete("DrawRectangle has been renamed to RectangleCap.")] + public static void DrawRectangle(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.RectangleCap(controlID, position, rotation, size); + } + [Obsolete("DrawCube has been renamed to CubeCap.")] + public static void DrawCube(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.CubeCap(controlID, position, rotation, size); + } + [Obsolete("DrawArrow has been renamed to ArrowCap.")] + public static void DrawArrow(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.ArrowCap(controlID, position, rotation, size); + } + [Obsolete("DrawCone has been renamed to ConeCap.")] + public static void DrawCone(int controlID, Vector3 position, Quaternion rotation, float size) + { + Handles.ConeCap(controlID, position, rotation, size); + } + public static void DrawLine(Vector3 p1, Vector3 p2) + { + if (Event.current.type != EventType.Repaint) { - int controlID = GUIUtility.GetControlID(Handles.s_RadiusHandleHash, FocusType.Keyboard); - float num10 = Vector3.Angle(array[k], -vector); - if ((num10 > 5f && num10 < 175f) || GUIUtility.hotControl == controlID) - { - Color color2 = color; - if (num10 > num + 5f) - { - color2.a = Mathf.Clamp01(Handles.backfaceAlphaMultiplier * color.a * 2f); - } - else - { - color2.a = Mathf.Clamp01(color.a * 2f); - } - Handles.color = color2; - Vector3 vector3 = position + radius * array[k]; - bool changed = GUI.changed; - GUI.changed = false; - vector3 = Slider1D.Do(controlID, vector3, array[k], HandleUtility.GetHandleSize(vector3) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); - if (GUI.changed) - { - radius = Vector3.Distance(vector3, position); - } - GUI.changed |= changed; - } + return; } - Handles.color = color; - return radius; + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.ApplyWireMaterial(); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + GL.Vertex(p1); + GL.Vertex(p2); + GL.End(); + GL.PopMatrix(); } - internal static Vector2 DoRectHandles(Quaternion rotation, Vector3 position, Vector2 size) + public static void DrawPolyLine(params Vector3[] points) { - Vector3 b = rotation * Vector3.forward; - Vector3 vector = rotation * Vector3.up; - Vector3 vector2 = rotation * Vector3.right; - float num = 0.5f * size.x; - float num2 = 0.5f * size.y; - Vector3 vector3 = position + vector * num2 + vector2 * num; - Vector3 vector4 = position - vector * num2 + vector2 * num; - Vector3 vector5 = position - vector * num2 - vector2 * num; - Vector3 vector6 = position + vector * num2 - vector2 * num; - Handles.DrawLine(vector3, vector4); - Handles.DrawLine(vector4, vector5); - Handles.DrawLine(vector5, vector6); - Handles.DrawLine(vector6, vector3); - Color color = Handles.color; - color.a = Mathf.Clamp01(color.a * 2f); - Handles.color = color; - num2 = Handles.SizeSlider(position, vector, num2); - num2 = Handles.SizeSlider(position, -vector, num2); - num = Handles.SizeSlider(position, vector2, num); - num = Handles.SizeSlider(position, -vector2, num); - if ((Tools.current != Tool.Move && Tools.current != Tool.Scale) || Tools.pivotRotation != PivotRotation.Local) + if (Event.current.type != EventType.Repaint) { - Handles.DrawLine(position, position + b); + return; + } + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.ApplyWireMaterial(); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + for (int i = 1; i < points.Length; i++) + { + GL.Vertex(points[i]); + GL.Vertex(points[i - 1]); } - size.x = 2f * num; - size.y = 2f * num2; - return size; + GL.End(); + GL.PopMatrix(); } - public static Quaternion DoRotationHandle(Quaternion rotation, Vector3 position) + public static void DrawDottedLine(Vector3 p1, Vector3 p2, float screenSpaceSize) { - float handleSize = HandleUtility.GetHandleSize(position); - Color color = Handles.color; - bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); - Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); - rotation = Handles.Disc(rotation, position, rotation * Vector3.right, handleSize, true, SnapSettings.rotation); - Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); - rotation = Handles.Disc(rotation, position, rotation * Vector3.up, handleSize, true, SnapSettings.rotation); - Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); - rotation = Handles.Disc(rotation, position, rotation * Vector3.forward, handleSize, true, SnapSettings.rotation); - if (!flag) + Camera current = Camera.current; + if (!current || Event.current.type != EventType.Repaint) { - Handles.color = Handles.centerColor; - rotation = Handles.Disc(rotation, position, Camera.current.transform.forward, handleSize * 1.1f, false, 0f); - rotation = Handles.FreeRotateHandle(rotation, position, handleSize); + return; } - Handles.color = color; - return rotation; - } - public static Vector3 DoScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) - { - bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); - Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); - scale.x = Handles.ScaleSlider(scale.x, position, rotation * Vector3.right, rotation, size, SnapSettings.scale); - Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); - scale.y = Handles.ScaleSlider(scale.y, position, rotation * Vector3.up, rotation, size, SnapSettings.scale); - Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); - scale.z = Handles.ScaleSlider(scale.z, position, rotation * Vector3.forward, rotation, size, SnapSettings.scale); - Handles.color = Handles.centerColor; - EditorGUI.BeginChangeCheck(); - float num = Handles.ScaleValueHandle(scale.x, position, rotation, size, new Handles.DrawCapFunction(Handles.CubeCap), SnapSettings.scale); - if (EditorGUI.EndChangeCheck()) + Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); + HandleUtility.ApplyWireMaterial(); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(1); + GL.Color(c); + Vector3 vector = current.WorldToScreenPoint(p1); + Vector3 vector2 = current.WorldToScreenPoint(p2); + float num = Vector2.Distance(vector, vector2); + int num2 = Mathf.CeilToInt(num / screenSpaceSize); + num2 = Mathf.Min(num2, 1000); + screenSpaceSize = num / (float)num2; + for (int i = 0; i < num2; i += 2) { - float num2 = num / scale.x; - scale.x = num; - scale.y *= num2; - scale.z *= num2; + GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)i * screenSpaceSize / num))); + GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)(i + 1) * screenSpaceSize / num))); } - return scale; + GL.End(); + GL.PopMatrix(); } - internal static float DoSimpleRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool hemisphere) + internal static void DrawAAPolyLine(Color[] colors, Vector3[] points) { - Vector3 vector = rotation * Vector3.forward; - Vector3 vector2 = rotation * Vector3.up; - Vector3 vector3 = rotation * Vector3.right; - bool changed = GUI.changed; - GUI.changed = false; - radius = Handles.SizeSlider(position, vector, radius); - if (!hemisphere) - { - radius = Handles.SizeSlider(position, -vector, radius); - } - if (GUI.changed) + Handles.DoDrawAAPolyLine(colors, points, -1, null, 2f, 0.75f); + } + internal static void DrawAAPolyLine(float width, Color[] colors, Vector3[] points) + { + Handles.DoDrawAAPolyLine(colors, points, -1, null, width, 0.75f); + } + public static void DrawAAPolyLine(params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, null, 2f, 0.75f); + } + public static void DrawAAPolyLine(float width, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, null, width, 0.75f); + } + public static void DrawAAPolyLine(Texture2D lineTex, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, lineTex, (float)(lineTex.height / 2), 0.99f); + } + public static void DrawAAPolyLine(float width, int actualNumberOfPoints, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, actualNumberOfPoints, null, width, 0.75f); + } + public static void DrawAAPolyLine(Texture2D lineTex, float width, params Vector3[] points) + { + Handles.DoDrawAAPolyLine(null, points, -1, lineTex, width, 0.99f); + } + private static void DoDrawAAPolyLine(Color[] colors, Vector3[] points, int actualNumberOfPoints, Texture2D lineTex, float width, float alpha) + { + if (Event.current.type != EventType.Repaint) { - radius = Mathf.Max(0f, radius); + return; } - GUI.changed |= changed; - changed = GUI.changed; - GUI.changed = false; - radius = Handles.SizeSlider(position, vector2, radius); - radius = Handles.SizeSlider(position, -vector2, radius); - radius = Handles.SizeSlider(position, vector3, radius); - radius = Handles.SizeSlider(position, -vector3, radius); - if (GUI.changed) + HandleUtility.ApplyWireMaterial(); + Color color = new Color(1f, 1f, 1f, alpha); + if (colors != null) { - radius = Mathf.Max(0f, radius); + for (int i = 0; i < colors.Length; i++) + { + colors[i] *= color; + } } - GUI.changed |= changed; - if (radius > 0f) + else { - Handles.DrawWireDisc(position, vector, radius); - Handles.DrawWireArc(position, vector2, -vector3, (float)((!hemisphere) ? 360 : 180), radius); - Handles.DrawWireArc(position, vector3, vector2, (float)((!hemisphere) ? 360 : 180), radius); + color *= Handles.s_Color; } - return radius; + Handles.Internal_DrawAAPolyLine(colors, points, color, actualNumberOfPoints, lineTex, width, Handles.matrix); } - public static Vector3 PositionHandle(Vector3 position, Quaternion rotation) + private static void Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width, Matrix4x4 toWorld) { - return Handles.DoPositionHandle(position, rotation); + Handles.INTERNAL_CALL_Internal_DrawAAPolyLine(colors, points, ref defaultColor, actualNumberOfPoints, texture, width, ref toWorld); } - public static Quaternion RotationHandle(Quaternion rotation, Vector3 position) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, ref Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width, ref Matrix4x4 toWorld); + public static void DrawAAConvexPolygon(params Vector3[] points) { - return Handles.DoRotationHandle(rotation, position); + Handles.DoDrawAAConvexPolygon(points, -1, 1f); } - public static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) + private static void DoDrawAAConvexPolygon(Vector3[] points, int actualNumberOfPoints, float alpha) { - return Handles.DoScaleHandle(scale, position, rotation, size); + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + Color defaultColor = new Color(1f, 1f, 1f, alpha) * Handles.s_Color; + Handles.Internal_DrawAAConvexPolygon(points, defaultColor, actualNumberOfPoints, Handles.matrix); } - public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) + private static void Internal_DrawAAConvexPolygon(Vector3[] points, Color defaultColor, int actualNumberOfPoints, Matrix4x4 toWorld) { - return Handles.DoRadiusHandle(rotation, position, radius, handlesOnly); + Handles.INTERNAL_CALL_Internal_DrawAAConvexPolygon(points, ref defaultColor, actualNumberOfPoints, ref toWorld); } - public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawAAConvexPolygon(Vector3[] points, ref Color defaultColor, int actualNumberOfPoints, ref Matrix4x4 toWorld); + public static void DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) { - return Handles.DoRadiusHandle(rotation, position, radius, false); + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + Handles.Internal_DrawBezier(startPosition, endPosition, startTangent, endTangent, color, texture, width, Handles.matrix); } - internal static Vector2 ConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) + private static void Internal_DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width, Matrix4x4 toWorld) { - return Handles.DoConeHandle(rotation, position, angleAndRange, angleScale, rangeScale, handlesOnly); + Handles.INTERNAL_CALL_Internal_DrawBezier(ref startPosition, ref endPosition, ref startTangent, ref endTangent, ref color, texture, width, ref toWorld); } - internal static Vector3 ConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Internal_DrawBezier(ref Vector3 startPosition, ref Vector3 endPosition, ref Vector3 startTangent, ref Vector3 endTangent, ref Color color, Texture2D texture, float width, ref Matrix4x4 toWorld); + public static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) { - return Handles.DoConeFrustrumHandle(rotation, position, radiusAngleRange); + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + Handles.DrawWireArc(center, normal, from, 360f, radius); } - public static Vector3 Slider(Vector3 position, Vector3 direction) + public static void DrawWireArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) { - return Handles.Slider(position, direction, HandleUtility.GetHandleSize(position), new Handles.DrawCapFunction(Handles.ArrowCap), -1f); + Vector3[] array = new Vector3[60]; + Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); + Handles.DrawPolyLine(array); } - public static Vector3 Slider(Vector3 position, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) + public static void DrawSolidRectangleWithOutline(Vector3[] verts, Color faceColor, Color outlineColor) { - int controlID = GUIUtility.GetControlID(Handles.s_SliderHash, FocusType.Keyboard); - return Slider1D.Do(controlID, position, direction, size, drawFunc, snap); + if (Event.current.type != EventType.Repaint) + { + return; + } + HandleUtility.ApplyWireMaterial(); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + if (faceColor.a > 0f) + { + Color c = faceColor * Handles.color; + GL.Begin(4); + for (int i = 0; i < 2; i++) + { + GL.Color(c); + GL.Vertex(verts[i * 2]); + GL.Vertex(verts[i * 2 + 1]); + GL.Vertex(verts[(i * 2 + 2) % 4]); + GL.Vertex(verts[i * 2]); + GL.Vertex(verts[(i * 2 + 2) % 4]); + GL.Vertex(verts[i * 2 + 1]); + } + GL.End(); + } + if (outlineColor.a > 0f) + { + Color c2 = outlineColor * Handles.color; + GL.Begin(1); + GL.Color(c2); + for (int j = 0; j < 4; j++) + { + GL.Vertex(verts[j]); + GL.Vertex(verts[(j + 1) % 4]); + } + GL.End(); + } + GL.PopMatrix(); } - [ExcludeFromDocs] - public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + public static void DrawSolidDisc(Vector3 center, Vector3 normal, float radius) { - bool drawHelper = false; - return Handles.Slider2D(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + Vector3 from = Vector3.Cross(normal, Vector3.up); + if (from.sqrMagnitude < 0.001f) + { + from = Vector3.Cross(normal, Vector3.right); + } + Handles.DrawSolidArc(center, normal, from, 360f, radius); } - public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + public static void DrawSolidArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) { - return UnityEditorInternal.Slider2D.Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + if (Event.current.type != EventType.Repaint) + { + return; + } + Vector3[] array = new Vector3[60]; + Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); + Shader.SetGlobalColor("_HandleColor", Handles.color * new Color(1f, 1f, 1f, 0.5f)); + Shader.SetGlobalFloat("_HandleSize", 1f); + HandleUtility.ApplyWireMaterial(); + GL.PushMatrix(); + GL.MultMatrix(Handles.matrix); + GL.Begin(4); + for (int i = 1; i < array.Length; i++) + { + GL.Color(Handles.color); + GL.Vertex(center); + GL.Vertex(array[i - 1]); + GL.Vertex(array[i]); + GL.Vertex(center); + GL.Vertex(array[i]); + GL.Vertex(array[i - 1]); + } + GL.End(); + GL.PopMatrix(); + } + internal static void SetDiscSectionPoints(Vector3[] dest, int count, Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + { + from.Normalize(); + Quaternion rotation = Quaternion.AngleAxis(angle / (float)(count - 1), normal); + Vector3 vector = from * radius; + for (int i = 0; i < count; i++) + { + dest[i] = center + vector; + vector = rotation * vector; + } } - [ExcludeFromDocs] - public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + internal static void Init() { - bool drawHelper = false; - return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + if (!Handles.s_CubeMesh) + { + GameObject gameObject = (GameObject)EditorGUIUtility.Load("SceneView/HandlesGO.fbx"); + if (!gameObject) + { + Debug.Log("ARGH - We couldn't find SceneView/HandlesGO.fbx"); + } + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + MeshFilter component = transform.GetComponent(); + string name = transform.name; + switch (name) + { + case "Cube": + Handles.s_CubeMesh = component.sharedMesh; + break; + case "Sphere": + Handles.s_SphereMesh = component.sharedMesh; + break; + case "Cone": + Handles.s_ConeMesh = component.sharedMesh; + break; + case "Cylinder": + Handles.s_CylinderMesh = component.sharedMesh; + break; + case "Quad": + Handles.s_QuadMesh = component.sharedMesh; + break; + } + } + if (Application.platform == RuntimePlatform.WindowsEditor) + { + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Bold.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small Bold.ttf")); + Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Big.ttf")); + } + } } - public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + private static void ReplaceFontForWindows(Font font) { - int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); - return UnityEditorInternal.Slider2D.Do(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + if (font.name.Contains("Bold")) + { + font.fontNames = new string[] + { + "Verdana Bold", + "Tahoma Bold" + }; + } + else + { + font.fontNames = new string[] + { + "Verdana", + "Tahoma" + }; + } + font.hideFlags = HideFlags.HideAndDontSave; } - [ExcludeFromDocs] - public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap) + public static void Label(Vector3 position, string text) { - bool drawHelper = false; - return Handles.Slider2D(id, handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + Handles.Label(position, EditorGUIUtility.TempContent(text), GUI.skin.label); } - public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, Vector2 snap, [DefaultValue("false")] bool drawHelper) + public static void Label(Vector3 position, Texture image) { - return UnityEditorInternal.Slider2D.Do(id, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + Handles.Label(position, EditorGUIUtility.TempContent(image), GUI.skin.label); } - [ExcludeFromDocs] - public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap) + public static void Label(Vector3 position, GUIContent content) { - bool drawHelper = false; - return Handles.Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); + Handles.Label(position, content, GUI.skin.label); } - public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.DrawCapFunction drawFunc, float snap, [DefaultValue("false")] bool drawHelper) + public static void Label(Vector3 position, string text, GUIStyle style) { - int controlID = GUIUtility.GetControlID(Handles.s_Slider2DHash, FocusType.Keyboard); - return Handles.Slider2D(controlID, handlePos, new Vector3(0f, 0f, 0f), handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); + Handles.Label(position, EditorGUIUtility.TempContent(text), style); } - public static Quaternion FreeRotateHandle(Quaternion rotation, Vector3 position, float size) + public static void Label(Vector3 position, GUIContent content, GUIStyle style) { - int controlID = GUIUtility.GetControlID(Handles.s_FreeRotateHandleHash, FocusType.Keyboard); - return FreeRotate.Do(controlID, rotation, position, size); + Handles.BeginGUI(); + GUI.Label(HandleUtility.WorldPointToSizedRect(position, content, style), content, style); + Handles.EndGUI(); } - public static Vector3 FreeMoveHandle(Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.DrawCapFunction capFunc) + internal static Rect GetCameraRect(Rect position) { - int controlID = GUIUtility.GetControlID(Handles.s_FreeMoveHandleHash, FocusType.Keyboard); - return FreeMove.Do(controlID, position, rotation, size, snap, capFunc); + Rect rect = GUIClip.Unclip(position); + Rect result = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + return result; } - public static float ScaleSlider(float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) + public static Vector2 GetMainGameViewSize() { - int controlID = GUIUtility.GetControlID(Handles.s_ScaleSliderHash, FocusType.Keyboard); - return SliderScale.DoAxis(controlID, scale, position, direction, rotation, size, snap); + return GameView.GetSizeOfMainGameView(); } - public static float ScaleValueHandle(float value, Vector3 position, Quaternion rotation, float size, Handles.DrawCapFunction capFunc, float snap) + public static void ClearCamera(Rect position, Camera camera) { - int controlID = GUIUtility.GetControlID(Handles.s_ScaleValueHandleHash, FocusType.Keyboard); - return SliderScale.DoCenter(controlID, value, position, rotation, size, capFunc, snap); + Event current = Event.current; + if (camera.targetTexture == null) + { + Rect rect = GUIClip.Unclip(position); + Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + camera.pixelRect = pixelRect; + } + else + { + camera.rect = new Rect(0f, 0f, 1f, 1f); + } + if (current.type == EventType.Repaint) + { + Handles.Internal_ClearCamera(camera); + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } } - public static Quaternion Disc(Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) + internal static void DrawCameraImpl(Rect position, Camera camera, DrawCameraMode drawMode, bool drawGrid, DrawGridParameters gridParam, bool finish) { - int controlID = GUIUtility.GetControlID(Handles.s_DiscHash, FocusType.Keyboard); - return UnityEditorInternal.Disc.Do(controlID, rotation, position, axis, size, cutoffPlane, snap); + Event current = Event.current; + if (current.type == EventType.Repaint) + { + if (camera.targetTexture == null) + { + Rect rect = GUIClip.Unclip(position); + camera.pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + } + else + { + camera.rect = new Rect(0f, 0f, 1f, 1f); + } + if (drawMode == DrawCameraMode.Normal) + { + RenderTexture targetTexture = camera.targetTexture; + camera.targetTexture = RenderTexture.active; + camera.Render(); + camera.targetTexture = targetTexture; + } + else + { + if (drawGrid) + { + Handles.Internal_DrawCameraWithGrid(camera, (int)drawMode, ref gridParam); + } + else + { + Handles.Internal_DrawCamera(camera, (int)drawMode); + } + if (finish) + { + Handles.Internal_FinishDrawingCamera(camera); + } + } + } + else + { + Handles.Internal_SetCurrentCamera(camera); + } } - public static bool Button(Vector3 position, Quaternion direction, float size, float pickSize, Handles.DrawCapFunction capFunc) + internal static void DrawCamera(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) { - int controlID = GUIUtility.GetControlID(Handles.s_ButtonHash, FocusType.Passive); - return UnityEditorInternal.Button.Do(controlID, position, direction, size, pickSize, capFunc); + Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, true); } - internal static void SetupIgnoreRaySnapObjects() + internal static void DrawCameraStep1(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) { - HandleUtility.ignoreRaySnapObjects = Selection.GetTransforms((SelectionMode)10); + Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, false); } - public static float SnapValue(float val, float snap) + internal static void DrawCameraStep2(Camera camera, DrawCameraMode drawMode) { - if (EditorGUI.actionKey && snap > 0f) + if (Event.current.type == EventType.Repaint && drawMode != DrawCameraMode.Normal) { - return Mathf.Round(val / snap) * snap; + Handles.Internal_FinishDrawingCamera(camera); } - return val; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_DrawCameraWithGrid(Camera cam, int renderMode, ref DrawGridParameters gridParam); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_DrawCamera(Camera cam, int renderMode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_FinishDrawingCamera(Camera cam); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_ClearCamera(Camera cam); + internal static extern bool DrawCameraTonemap(Camera camera, RenderTexture srcRT, RenderTexture dstRT); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void Internal_SetCurrentCamera(Camera cam); - internal static void SetSceneViewColors(Color wire, Color wireOverlay, Color active, Color selected) + internal static extern void EmitGUIGeometryForCamera(Camera source, Camera dest); + [ExcludeFromDocs] + public static void DrawCamera(Rect position, Camera camera) { - Handles.INTERNAL_CALL_SetSceneViewColors(ref wire, ref wireOverlay, ref active, ref selected); + DrawCameraMode drawMode = DrawCameraMode.Normal; + Handles.DrawCamera(position, camera, drawMode); + } + public static void DrawCamera(Rect position, Camera camera, [DefaultValue("DrawCameraMode.Normal")] DrawCameraMode drawMode) + { + Handles.DrawCameraImpl(position, camera, drawMode, false, default(DrawGridParameters), true); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetSceneViewColors(ref Color wire, ref Color wireOverlay, ref Color active, ref Color selected); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void EnableCameraFx(Camera cam, bool fx); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void EnableCameraFlares(Camera cam, bool flares); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void EnableCameraSkybox(Camera cam, bool skybox); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void SetCameraOnlyDrawMesh(Camera cam); + internal static extern void SetCameraFilterMode(Camera camera, Handles.FilterMode mode); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_SetupCamera(Camera cam); - internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, float radius) - { - Color color = Handles.color; - Color color2 = color; - color.a *= Handles.backfaceAlphaMultiplier; - Handles.color = color; - Handles.DrawWireDisc(position, axis, radius); - Handles.color = color2; - } - internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, Vector3 from, float degrees, float radius) - { - Handles.DrawWireArc(position, axis, from, degrees, radius); - Color color = Handles.color; - Color color2 = color; - color.a *= Handles.backfaceAlphaMultiplier; - Handles.color = color; - Handles.DrawWireArc(position, axis, from, degrees - 360f, radius); - Handles.color = color2; - } - internal static Matrix4x4 StartCapDraw(Vector3 position, Quaternion rotation, float size) - { - Shader.SetGlobalColor("_HandleColor", Handles.realHandleColor); - Shader.SetGlobalFloat("_HandleSize", size); - Matrix4x4 matrix4x = Handles.matrix * Matrix4x4.TRS(position, rotation, Vector3.one); - Shader.SetGlobalMatrix("_ObjectToWorld", matrix4x); - HandleUtility.handleMaterial.SetPass(0); - return matrix4x; - } - public static void CubeCap(int controlID, Vector3 position, Quaternion rotation, float size) - { - if (Event.current.type != EventType.Repaint) - { - return; - } - Graphics.DrawMeshNow(Handles.s_CubeMesh, Handles.StartCapDraw(position, rotation, size)); - } - public static void SphereCap(int controlID, Vector3 position, Quaternion rotation, float size) + internal static extern Handles.FilterMode GetCameraFilterMode(Camera camera); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void DrawCameraFade(Camera camera, float fade); + public static void SetCamera(Camera camera) { - if (Event.current.type != EventType.Repaint) + if (Event.current.type == EventType.Repaint) { - return; + Handles.Internal_SetupCamera(camera); } - Graphics.DrawMeshNow(Handles.s_SphereMesh, Handles.StartCapDraw(position, rotation, size)); - } - public static void ConeCap(int controlID, Vector3 position, Quaternion rotation, float size) - { - if (Event.current.type != EventType.Repaint) + else { - return; + Handles.Internal_SetCurrentCamera(camera); } - Graphics.DrawMeshNow(Handles.s_ConeMesh, Handles.StartCapDraw(position, rotation, size)); } - public static void CylinderCap(int controlID, Vector3 position, Quaternion rotation, float size) + public static void SetCamera(Rect position, Camera camera) { - if (Event.current.type != EventType.Repaint) + Rect rect = GUIClip.Unclip(position); + Event current = Event.current; + Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + camera.pixelRect = pixelRect; + if (current.type == EventType.Repaint) { - return; + Handles.Internal_SetupCamera(camera); } - Graphics.DrawMeshNow(Handles.s_CylinderMesh, Handles.StartCapDraw(position, rotation, size)); - } - public static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, float size) - { - Handles.RectangleCap(controlID, position, rotation, new Vector2(size, size)); - } - internal static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, Vector2 size) - { - if (Event.current.type != EventType.Repaint) + else { - return; + Handles.Internal_SetCurrentCamera(camera); } - Vector3 b = rotation * new Vector3(size.x, 0f, 0f); - Vector3 b2 = rotation * new Vector3(0f, size.y, 0f); - Handles.s_RectangleCapPointsCache[0] = position + b + b2; - Handles.s_RectangleCapPointsCache[1] = position + b - b2; - Handles.s_RectangleCapPointsCache[2] = position - b - b2; - Handles.s_RectangleCapPointsCache[3] = position - b + b2; - Handles.s_RectangleCapPointsCache[4] = position + b + b2; - Handles.DrawPolyLine(Handles.s_RectangleCapPointsCache); } - public static void SelectionFrame(int controlID, Vector3 position, Quaternion rotation, float size) + public static void BeginGUI() { - if (Event.current.type != EventType.Repaint) + if (Camera.current && Event.current.type == EventType.Repaint) { - return; + GUIClip.Reapply(); } - Handles.StartCapDraw(position, rotation, size); - Vector3 b = rotation * new Vector3(size, 0f, 0f); - Vector3 b2 = rotation * new Vector3(0f, size, 0f); - Vector3 vector = position - b + b2; - Vector3 vector2 = position + b + b2; - Vector3 vector3 = position + b - b2; - Vector3 vector4 = position - b - b2; - Handles.DrawLine(vector, vector2); - Handles.DrawLine(vector2, vector3); - Handles.DrawLine(vector3, vector4); - Handles.DrawLine(vector4, vector); } - public static void DotCap(int controlID, Vector3 position, Quaternion rotation, float size) + [Obsolete("Please use BeginGUI() with GUILayout.BeginArea(position) / GUILayout.EndArea()")] + public static void BeginGUI(Rect position) { - if (Event.current.type != EventType.Repaint) - { - return; - } - position = Handles.matrix.MultiplyPoint(position); - Vector3 b = Camera.current.transform.right * size; - Vector3 b2 = Camera.current.transform.up * size; - Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.99f); - HandleUtility.handleWireMaterial.SetPass(0); - GL.Begin(7); - GL.Color(c); - GL.Vertex(position + b + b2); - GL.Vertex(position + b - b2); - GL.Vertex(position - b - b2); - GL.Vertex(position - b + b2); - GL.End(); + GUILayout.BeginArea(position); } - public static void CircleCap(int controlID, Vector3 position, Quaternion rotation, float size) + public static void EndGUI() { - if (Event.current.type != EventType.Repaint) + Camera current = Camera.current; + if (current && Event.current.type == EventType.Repaint) { - return; + Handles.Internal_SetupCamera(current); } - Handles.StartCapDraw(position, rotation, size); - Vector3 normal = rotation * new Vector3(0f, 0f, 1f); - Handles.DrawWireDisc(position, normal, size); } - public static void ArrowCap(int controlID, Vector3 position, Quaternion rotation, float size) + internal static void ShowStaticLabelIfNeeded(Vector3 pos) { - if (Event.current.type != EventType.Repaint) + if (!Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects)) { - return; + Handles.color = Color.white; + GUIStyle gUIStyle = "SC ViewAxisLabel"; + gUIStyle.alignment = TextAnchor.MiddleLeft; + gUIStyle.fixedWidth = 0f; + Handles.BeginGUI(); + Rect position = HandleUtility.WorldPointToSizedRect(pos, EditorGUIUtility.TempContent("Static"), gUIStyle); + position.x += 10f; + position.y += 10f; + GUI.Label(position, EditorGUIUtility.TempContent("Static"), gUIStyle); + Handles.EndGUI(); } - Vector3 vector = rotation * Vector3.forward; - Handles.ConeCap(controlID, position + vector * size, Quaternion.LookRotation(vector), size * 0.2f); - Handles.DrawLine(position, position + vector * size * 0.9f); } - [Obsolete("DrawCylinder has been renamed to CylinderCap.")] - public static void DrawCylinder(int controlID, Vector3 position, Quaternion rotation, float size) - { - Handles.CylinderCap(controlID, position, rotation, size); - } - [Obsolete("DrawSphere has been renamed to SphereCap.")] - public static void DrawSphere(int controlID, Vector3 position, Quaternion rotation, float size) - { - Handles.SphereCap(controlID, position, rotation, size); - } - [Obsolete("DrawRectangle has been renamed to RectangleCap.")] - public static void DrawRectangle(int controlID, Vector3 position, Quaternion rotation, float size) + private static Vector3[] Internal_MakeBezierPoints(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, int division) { - Handles.RectangleCap(controlID, position, rotation, size); + return Handles.INTERNAL_CALL_Internal_MakeBezierPoints(ref startPosition, ref endPosition, ref startTangent, ref endTangent, division); } - [Obsolete("DrawCube has been renamed to CubeCap.")] - public static void DrawCube(int controlID, Vector3 position, Quaternion rotation, float size) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3[] INTERNAL_CALL_Internal_MakeBezierPoints(ref Vector3 startPosition, ref Vector3 endPosition, ref Vector3 startTangent, ref Vector3 endTangent, int division); + public static Vector3[] MakeBezierPoints(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, int division) { - Handles.CubeCap(controlID, position, rotation, size); + return Handles.Internal_MakeBezierPoints(startPosition, endPosition, startTangent, endTangent, division); } - [Obsolete("DrawArrow has been renamed to ArrowCap.")] - public static void DrawArrow(int controlID, Vector3 position, Quaternion rotation, float size) + internal static float DistanceToPolygone(Vector3[] vertices) { - Handles.ArrowCap(controlID, position, rotation, size); + return HandleUtility.DistanceToPolyLine(vertices); } - [Obsolete("DrawCone has been renamed to ConeCap.")] - public static void DrawCone(int controlID, Vector3 position, Quaternion rotation, float size) + internal static void DoBoneHandle(Transform target) { - Handles.ConeCap(controlID, position, rotation, size); + Handles.DoBoneHandle(target, null); } - public static void DrawLine(Vector3 p1, Vector3 p2) + internal static void DoBoneHandle(Transform target, Dictionary validBones) { - if (Event.current.type != EventType.Repaint) + int hashCode = target.name.GetHashCode(); + Event current = Event.current; + bool flag = false; + if (validBones != null) { - return; + foreach (Transform key in target) + { + if (validBones.ContainsKey(key)) + { + flag = true; + break; + } + } } - Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - GL.Begin(1); - GL.Color(c); - GL.Vertex(p1); - GL.Vertex(p2); - GL.End(); - GL.PopMatrix(); - } - public static void DrawPolyLine(params Vector3[] points) - { - if (Event.current.type != EventType.Repaint) + Vector3 position = target.position; + List list = new List(); + if (!flag && target.parent != null) { - return; + list.Add(target.position + (target.position - target.parent.position) * 0.4f); } - Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - GL.Begin(1); - GL.Color(c); - for (int i = 1; i < points.Length; i++) + else { - GL.Vertex(points[i]); - GL.Vertex(points[i - 1]); + foreach (Transform transform in target) + { + if (validBones == null || validBones.ContainsKey(transform)) + { + list.Add(transform.position); + } + } + } + for (int i = 0; i < list.Count; i++) + { + Vector3 vector = list[i]; + switch (current.GetTypeForControl(hashCode)) + { + case EventType.MouseDown: + if ((HandleUtility.nearestControl == hashCode && current.button == 0) || (GUIUtility.keyboardControl == hashCode && current.button == 2)) + { + int num = hashCode; + GUIUtility.keyboardControl = num; + GUIUtility.hotControl = num; + if (current.shift) + { + UnityEngine.Object[] objects = Selection.objects; + if (!ArrayUtility.Contains(objects, target)) + { + ArrayUtility.Add(ref objects, target); + Selection.objects = objects; + } + } + else + { + Selection.activeObject = target; + } + EditorGUIUtility.PingObject(target); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == hashCode && (current.button == 0 || current.button == 2)) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == hashCode) + { + DragAndDrop.PrepareStartDrag(); + DragAndDrop.objectReferences = new UnityEngine.Object[] + { + target + }; + DragAndDrop.StartDrag(ObjectNames.GetDragAndDropTitle(target)); + current.Use(); + } + break; + case EventType.Repaint: + { + float num2 = Vector3.Magnitude(vector - position); + if (num2 > 0f) + { + float num3 = num2 * 0.08f; + if (flag) + { + Handles.DrawBone(vector, position, num3); + } + else + { + Handles.SphereCap(hashCode, position, target.rotation, num3 * 5f); + } + } + break; + } + case EventType.Layout: + { + float num4 = Vector3.Magnitude(vector - position); + float radius = num4 * 0.08f; + Vector3[] boneVertices = Handles.GetBoneVertices(vector, position, radius); + HandleUtility.AddControl(hashCode, Handles.DistanceToPolygone(boneVertices)); + break; + } + } } - GL.End(); - GL.PopMatrix(); } - public static void DrawDottedLine(Vector3 p1, Vector3 p2, float screenSpaceSize) + internal static void DrawBone(Vector3 endPoint, Vector3 basePoint, float size) { - Camera current = Camera.current; - if (!current || Event.current.type != EventType.Repaint) + Vector3[] boneVertices = Handles.GetBoneVertices(endPoint, basePoint, size); + HandleUtility.ApplyWireMaterial(); + GL.Begin(4); + GL.Color(Handles.s_Color); + for (int i = 0; i < 3; i++) { - return; + GL.Vertex(boneVertices[i * 6]); + GL.Vertex(boneVertices[i * 6 + 1]); + GL.Vertex(boneVertices[i * 6 + 2]); + GL.Vertex(boneVertices[i * 6 + 3]); + GL.Vertex(boneVertices[i * 6 + 4]); + GL.Vertex(boneVertices[i * 6 + 5]); } - Color c = Handles.s_Color * new Color(1f, 1f, 1f, 0.75f); - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); + GL.End(); GL.Begin(1); - GL.Color(c); - Vector3 vector = current.WorldToScreenPoint(p1); - Vector3 vector2 = current.WorldToScreenPoint(p2); - float num = Vector2.Distance(vector, vector2); - int num2 = Mathf.CeilToInt(num / screenSpaceSize); - num2 = Mathf.Min(num2, 1000); - screenSpaceSize = num / (float)num2; - for (int i = 0; i < num2; i += 2) + GL.Color(Handles.s_Color * new Color(1f, 1f, 1f, 0f) + new Color(0f, 0f, 0f, 1f)); + for (int j = 0; j < 3; j++) { - GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)i * screenSpaceSize / num))); - GL.Vertex(current.ScreenToWorldPoint(Vector3.Lerp(vector, vector2, (float)(i + 1) * screenSpaceSize / num))); + GL.Vertex(boneVertices[j * 6]); + GL.Vertex(boneVertices[j * 6 + 1]); + GL.Vertex(boneVertices[j * 6 + 1]); + GL.Vertex(boneVertices[j * 6 + 2]); } GL.End(); - GL.PopMatrix(); - } - internal static void DrawAAPolyLine(Color[] colors, Vector3[] points) - { - Handles.DoDrawAAPolyLine(colors, points, -1, null, 2f, 0.75f); - } - internal static void DrawAAPolyLine(float width, Color[] colors, Vector3[] points) - { - Handles.DoDrawAAPolyLine(colors, points, -1, null, width, 0.75f); - } - public static void DrawAAPolyLine(params Vector3[] points) - { - Handles.DoDrawAAPolyLine(null, points, -1, null, 2f, 0.75f); - } - public static void DrawAAPolyLine(float width, params Vector3[] points) - { - Handles.DoDrawAAPolyLine(null, points, -1, null, width, 0.75f); - } - public static void DrawAAPolyLine(Texture2D lineTex, params Vector3[] points) - { - Handles.DoDrawAAPolyLine(null, points, -1, lineTex, (float)(lineTex.height / 2), 0.99f); - } - public static void DrawAAPolyLine(float width, int actualNumberOfPoints, params Vector3[] points) - { - Handles.DoDrawAAPolyLine(null, points, actualNumberOfPoints, null, width, 0.75f); - } - public static void DrawAAPolyLine(Texture2D lineTex, float width, params Vector3[] points) - { - Handles.DoDrawAAPolyLine(null, points, -1, lineTex, width, 0.99f); } - private static void DoDrawAAPolyLine(Color[] colors, Vector3[] points, int actualNumberOfPoints, Texture2D lineTex, float width, float alpha) + internal static Vector3[] GetBoneVertices(Vector3 endPoint, Vector3 basePoint, float radius) { - if (Event.current.type != EventType.Repaint) - { - return; - } - HandleUtility.handleWireMaterial.SetPass(0); - Color color = new Color(1f, 1f, 1f, alpha); - if (colors != null) - { - for (int i = 0; i < colors.Length; i++) - { - colors[i] *= color; - } - } - else + Vector3 lhs = Vector3.Normalize(endPoint - basePoint); + Vector3 vector = Vector3.Cross(lhs, Vector3.up); + if (Vector3.SqrMagnitude(vector) < 0.1f) { - color *= Handles.s_Color; + vector = Vector3.Cross(lhs, Vector3.right); } - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - Handles.Internal_DrawAAPolyLine(colors, points, color, actualNumberOfPoints, lineTex, width); - GL.PopMatrix(); - } - private static void Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width) - { - Handles.INTERNAL_CALL_Internal_DrawAAPolyLine(colors, points, ref defaultColor, actualNumberOfPoints, texture, width); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Internal_DrawAAPolyLine(Color[] colors, Vector3[] points, ref Color defaultColor, int actualNumberOfPoints, Texture2D texture, float width); - public static void DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) - { - if (Event.current.type != EventType.Repaint) + vector.Normalize(); + Vector3 a = Vector3.Cross(lhs, vector); + Vector3[] array = new Vector3[18]; + float num = 0f; + for (int i = 0; i < 3; i++) { - return; + float num2 = Mathf.Cos(num); + float num3 = Mathf.Sin(num); + float num4 = Mathf.Cos(num + 2.09439516f); + float num5 = Mathf.Sin(num + 2.09439516f); + Vector3 vector2 = basePoint + vector * (num2 * radius) + a * (num3 * radius); + Vector3 vector3 = basePoint + vector * (num4 * radius) + a * (num5 * radius); + array[i * 6] = endPoint; + array[i * 6 + 1] = vector2; + array[i * 6 + 2] = vector3; + array[i * 6 + 3] = basePoint; + array[i * 6 + 4] = vector3; + array[i * 6 + 5] = vector2; + num += 2.09439516f; } - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - Handles.Internal_DrawBezier(startPosition, endPosition, startTangent, endTangent, color, texture, width); - GL.PopMatrix(); - } - private static void Internal_DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) - { - Handles.INTERNAL_CALL_Internal_DrawBezier(ref startPosition, ref endPosition, ref startTangent, ref endTangent, ref color, texture, width); + return array; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Internal_DrawBezier(ref Vector3 startPosition, ref Vector3 endPosition, ref Vector3 startTangent, ref Vector3 endTangent, ref Color color, Texture2D texture, float width); - public static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) + internal static Vector3 DoConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange) { - Vector3 from = Vector3.Cross(normal, Vector3.up); - if (from.sqrMagnitude < 0.001f) + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + float num = radiusAngleRange.x; + float num2 = radiusAngleRange.y; + float num3 = radiusAngleRange.z; + num2 = Mathf.Max(0f, num2); + bool changed = GUI.changed; + num3 = Handles.SizeSlider(position, vector, num3); + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + num = Handles.SizeSlider(position, vector2, num); + num = Handles.SizeSlider(position, -vector2, num); + num = Handles.SizeSlider(position, vector3, num); + num = Handles.SizeSlider(position, -vector3, num); + if (GUI.changed) { - from = Vector3.Cross(normal, Vector3.right); + num = Mathf.Max(0f, num); } - Handles.DrawWireArc(center, normal, from, 360f, radius); - } - public static void DrawWireArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) - { - Vector3[] array = new Vector3[60]; - Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); - Handles.DrawPolyLine(array); - } - public static void DrawSolidRectangleWithOutline(Vector3[] verts, Color faceColor, Color outlineColor) - { - if (Event.current.type != EventType.Repaint) + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + float num4 = Mathf.Min(1000f, Mathf.Abs(num3 * Mathf.Tan(0.0174532924f * num2)) + num); + num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); + if (GUI.changed) { - return; + num2 = Mathf.Clamp(57.29578f * Mathf.Atan((num4 - num) / Mathf.Abs(num3)), 0f, 90f); } - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - if (faceColor.a > 0f) + GUI.changed |= changed; + if (num > 0f) { - Color c = faceColor * Handles.color; - GL.Begin(4); - for (int i = 0; i < 2; i++) - { - GL.Color(c); - GL.Vertex(verts[i * 2]); - GL.Vertex(verts[i * 2 + 1]); - GL.Vertex(verts[(i * 2 + 2) % 4]); - GL.Vertex(verts[i * 2]); - GL.Vertex(verts[(i * 2 + 2) % 4]); - GL.Vertex(verts[i * 2 + 1]); - } - GL.End(); + Handles.DrawWireDisc(position, vector, num); } - if (outlineColor.a > 0f) + if (num4 > 0f) { - Color c2 = outlineColor * Handles.color; - GL.Begin(1); - GL.Color(c2); - for (int j = 0; j < 4; j++) - { - GL.Vertex(verts[j]); - GL.Vertex(verts[(j + 1) % 4]); - } - GL.End(); + Handles.DrawWireDisc(position + num3 * vector, vector, num4); } - GL.PopMatrix(); + Handles.DrawLine(position + vector2 * num, position + vector * num3 + vector2 * num4); + Handles.DrawLine(position - vector2 * num, position + vector * num3 - vector2 * num4); + Handles.DrawLine(position + vector3 * num, position + vector * num3 + vector3 * num4); + Handles.DrawLine(position - vector3 * num, position + vector * num3 - vector3 * num4); + return new Vector3(num, num2, num3); } - public static void DrawSolidDisc(Vector3 center, Vector3 normal, float radius) + internal static Vector2 DoConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) { - Vector3 from = Vector3.Cross(normal, Vector3.up); - if (from.sqrMagnitude < 0.001f) + float num = angleAndRange.x; + float num2 = angleAndRange.y; + float num3 = num2 * rangeScale; + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + bool changed = GUI.changed; + GUI.changed = false; + num3 = Handles.SizeSlider(position, vector, num3); + if (GUI.changed) { - from = Vector3.Cross(normal, Vector3.right); + num2 = Mathf.Max(0f, num3 / rangeScale); } - Handles.DrawSolidArc(center, normal, from, 360f, radius); - } - public static void DrawSolidArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) - { - if (Event.current.type != EventType.Repaint) + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + float num4 = num3 * Mathf.Tan(0.0174532924f * num / 2f) * angleScale; + num4 = Handles.SizeSlider(position + vector * num3, vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector2, num4); + num4 = Handles.SizeSlider(position + vector * num3, vector3, num4); + num4 = Handles.SizeSlider(position + vector * num3, -vector3, num4); + if (GUI.changed) { - return; + num = Mathf.Clamp(57.29578f * Mathf.Atan(num4 / (num3 * angleScale)) * 2f, 0f, 179f); } - Vector3[] array = new Vector3[60]; - Handles.SetDiscSectionPoints(array, 60, center, normal, from, angle, radius); - Shader.SetGlobalColor("_HandleColor", Handles.color * new Color(1f, 1f, 1f, 0.5f)); - Shader.SetGlobalFloat("_HandleSize", 1f); - HandleUtility.handleWireMaterial.SetPass(0); - GL.PushMatrix(); - GL.MultMatrix(Handles.matrix); - GL.Begin(4); - for (int i = 1; i < array.Length; i++) + GUI.changed |= changed; + if (!handlesOnly) { - GL.Color(Handles.color); - GL.Vertex(center); - GL.Vertex(array[i - 1]); - GL.Vertex(array[i]); - GL.Vertex(center); - GL.Vertex(array[i]); - GL.Vertex(array[i - 1]); + Handles.DrawLine(position, position + vector * num3 + vector2 * num4); + Handles.DrawLine(position, position + vector * num3 - vector2 * num4); + Handles.DrawLine(position, position + vector * num3 + vector3 * num4); + Handles.DrawLine(position, position + vector * num3 - vector3 * num4); + Handles.DrawWireDisc(position + num3 * vector, vector, num4); } - GL.End(); - GL.PopMatrix(); + return new Vector2(num, num2); } - internal static void SetDiscSectionPoints(Vector3[] dest, int count, Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) + private static float SizeSlider(Vector3 p, Vector3 d, float r) { - from.Normalize(); - Quaternion rotation = Quaternion.AngleAxis(angle / (float)(count - 1), normal); - Vector3 vector = from * radius; - for (int i = 0; i < count; i++) + Vector3 vector = p + d * r; + float handleSize = HandleUtility.GetHandleSize(vector); + bool changed = GUI.changed; + GUI.changed = false; + vector = Handles.Slider(vector, d, handleSize * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + if (GUI.changed) { - dest[i] = center + vector; - vector = rotation * vector; + r = Vector3.Dot(vector - p, d); } + GUI.changed |= changed; + return r; } - internal static void Init() + public static Vector3 DoPositionHandle(Vector3 position, Quaternion rotation) { - if (!Handles.s_CubeMesh) + Event current = Event.current; + switch (current.type) { - GameObject gameObject = (GameObject)EditorGUIUtility.Load("SceneView/HandlesGO.fbx"); - if (!gameObject) + case EventType.KeyDown: + if (current.keyCode == KeyCode.V && !Handles.currentlyDragging) { - Debug.Log("ARGH - We couldn't find SceneView/HandlesGO.fbx"); + Handles.s_FreeMoveMode = true; } - gameObject.SetActive(false); - foreach (Transform transform in gameObject.transform) + break; + case EventType.KeyUp: + position = Handles.DoPositionHandle_Internal(position, rotation); + if (current.keyCode == KeyCode.V && !current.shift && !Handles.currentlyDragging) { - string name = transform.name; - switch (name) - { - case "Cube": - Handles.s_CubeMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; - break; - case "Sphere": - Handles.s_SphereMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; - break; - case "Cone": - Handles.s_ConeMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; - break; - case "Cylinder": - Handles.s_CylinderMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; - break; - case "Quad": - Handles.s_QuadMesh = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; - break; - } + Handles.s_FreeMoveMode = false; } - if (Application.platform == RuntimePlatform.WindowsEditor) + return position; + case EventType.Layout: + if (!Handles.currentlyDragging && !Tools.vertexDragging) { - Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande.ttf")); - Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Bold.ttf")); - Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small.ttf")); - Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Small Bold.ttf")); - Handles.ReplaceFontForWindows((Font)EditorGUIUtility.LoadRequired(EditorResourcesUtility.fontsPath + "Lucida Grande Big.ttf")); + Handles.s_FreeMoveMode = current.shift; } + break; } + return Handles.DoPositionHandle_Internal(position, rotation); } - private static void ReplaceFontForWindows(Font font) + private static Vector3 DoPositionHandle_Internal(Vector3 position, Quaternion rotation) { - if (font.name.Contains("Bold")) + float handleSize = HandleUtility.GetHandleSize(position); + Color color = Handles.color; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("xAxis"); + position = Handles.Slider(position, rotation * Vector3.right, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.x); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("yAxis"); + position = Handles.Slider(position, rotation * Vector3.up, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.y); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + GUI.SetNextControlName("zAxis"); + position = Handles.Slider(position, rotation * Vector3.forward, handleSize, new Handles.DrawCapFunction(Handles.ArrowCap), SnapSettings.move.z); + if (Handles.s_FreeMoveMode) { - font.fontNames = new string[] - { - "Verdana Bold", - "Tahoma Bold" - }; + Handles.color = Handles.centerColor; + GUI.SetNextControlName("FreeMoveAxis"); + position = Handles.FreeMoveHandle(position, rotation, handleSize * 0.15f, SnapSettings.move, new Handles.DrawCapFunction(Handles.RectangleCap)); } else { - font.fontNames = new string[] - { - "Verdana", - "Tahoma" - }; + position = Handles.DoPlanarHandle(Handles.PlaneHandle.xzPlane, position, rotation, handleSize * 0.25f); + position = Handles.DoPlanarHandle(Handles.PlaneHandle.xyPlane, position, rotation, handleSize * 0.25f); + position = Handles.DoPlanarHandle(Handles.PlaneHandle.yzPlane, position, rotation, handleSize * 0.25f); } - font.hideFlags = HideFlags.HideAndDontSave; - } - public static void Label(Vector3 position, string text) - { - Handles.Label(position, EditorGUIUtility.TempContent(text), GUI.skin.label); - } - public static void Label(Vector3 position, Texture image) - { - Handles.Label(position, EditorGUIUtility.TempContent(image), GUI.skin.label); - } - public static void Label(Vector3 position, GUIContent content) - { - Handles.Label(position, content, GUI.skin.label); - } - public static void Label(Vector3 position, string text, GUIStyle style) - { - Handles.Label(position, EditorGUIUtility.TempContent(text), style); - } - public static void Label(Vector3 position, GUIContent content, GUIStyle style) - { - Handles.BeginGUI(); - GUI.Label(HandleUtility.WorldPointToSizedRect(position, content, style), content, style); - Handles.EndGUI(); - } - internal static Rect GetCameraRect(Rect position) - { - Rect rect = GUIClip.Unclip(position); - Rect result = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); - return result; - } - public static Vector2 GetMainGameViewSize() - { - return GameView.GetSizeOfMainGameView(); + Handles.color = color; + return position; } - public static void ClearCamera(Rect position, Camera camera) + private static Vector3 DoPlanarHandle(Handles.PlaneHandle planeID, Vector3 position, Quaternion rotation, float handleSize) { - Event current = Event.current; - if (camera.targetTexture == null) + int num = 0; + int num2 = 0; + int hint = 0; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + switch (planeID) { - Rect rect = GUIClip.Unclip(position); - Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); - camera.pixelRect = pixelRect; + case Handles.PlaneHandle.xzPlane: + num = 0; + num2 = 2; + Handles.color = ((!flag) ? Handles.yAxisColor : Handles.staticColor); + hint = Handles.s_xzAxisMoveHandleHash; + break; + case Handles.PlaneHandle.xyPlane: + num = 0; + num2 = 1; + Handles.color = ((!flag) ? Handles.zAxisColor : Handles.staticColor); + hint = Handles.s_xyAxisMoveHandleHash; + break; + case Handles.PlaneHandle.yzPlane: + num = 1; + num2 = 2; + Handles.color = ((!flag) ? Handles.xAxisColor : Handles.staticColor); + hint = Handles.s_yzAxisMoveHandleHash; + break; + } + int index = 3 - num2 - num; + Color color = Handles.color; + Matrix4x4 matrix4x = Matrix4x4.TRS(position, rotation, Vector3.one); + Vector3 normalized; + if (Camera.current.orthographic) + { + normalized = matrix4x.inverse.MultiplyVector(SceneView.currentDrawingSceneView.cameraTargetRotation * -Vector3.forward).normalized; } else { - camera.rect = new Rect(0f, 0f, 1f, 1f); + normalized = matrix4x.inverse.MultiplyPoint(SceneView.currentDrawingSceneView.camera.transform.position).normalized; } - if (current.type == EventType.Repaint) + int controlID = GUIUtility.GetControlID(hint, FocusType.Keyboard); + if (Mathf.Abs(normalized[index]) < 0.05f && GUIUtility.hotControl != controlID) { - Handles.Internal_ClearCamera(camera); + Handles.color = color; + return position; } - else + if (!Handles.currentlyDragging) { - Handles.Internal_SetCurrentCamera(camera); + Handles.s_PlanarHandlesOctant[num] = (float)((normalized[num] >= -0.01f) ? 1 : -1); + Handles.s_PlanarHandlesOctant[num2] = (float)((normalized[num2] >= -0.01f) ? 1 : -1); } + Vector3 vector = Handles.s_PlanarHandlesOctant; + vector[index] = 0f; + vector = rotation * (vector * handleSize * 0.5f); + Vector3 vector2 = Vector3.zero; + Vector3 vector3 = Vector3.zero; + Vector3 vector4 = Vector3.zero; + vector2[num] = 1f; + vector3[num2] = 1f; + vector4[index] = 1f; + vector2 = rotation * vector2; + vector3 = rotation * vector3; + vector4 = rotation * vector4; + Handles.verts[0] = position + vector + (vector2 + vector3) * handleSize * 0.5f; + Handles.verts[1] = position + vector + (-vector2 + vector3) * handleSize * 0.5f; + Handles.verts[2] = position + vector + (-vector2 - vector3) * handleSize * 0.5f; + Handles.verts[3] = position + vector + (vector2 - vector3) * handleSize * 0.5f; + Handles.DrawSolidRectangleWithOutline(Handles.verts, new Color(Handles.color.r, Handles.color.g, Handles.color.b, 0.1f), new Color(0f, 0f, 0f, 0f)); + position = Handles.Slider2D(controlID, position, vector, vector4, vector2, vector3, handleSize * 0.5f, new Handles.DrawCapFunction(Handles.RectangleCap), new Vector2(SnapSettings.move[num], SnapSettings.move[num2])); + Handles.color = color; + return position; } - internal static void DrawCameraImpl(Rect position, Camera camera, DrawCameraMode drawMode, bool drawGrid, DrawGridParameters gridParam, bool finish) + internal static float DoRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) { - Event current = Event.current; - if (current.type == EventType.Repaint) + float num = 90f; + Vector3[] array = new Vector3[] { - if (camera.targetTexture == null) + rotation * Vector3.right, + rotation * Vector3.up, + rotation * Vector3.forward, + rotation * -Vector3.right, + rotation * -Vector3.up, + rotation * -Vector3.forward + }; + Vector3 vector; + if (Camera.current.orthographic) + { + vector = Camera.current.transform.forward; + if (!handlesOnly) { - Rect rect = GUIClip.Unclip(position); - camera.pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); + Handles.DrawWireDisc(position, vector, radius); + for (int i = 0; i < 3; i++) + { + Vector3 normalized = Vector3.Cross(array[i], vector).normalized; + Handles.DrawTwoShadedWireDisc(position, array[i], normalized, 180f, radius); + } + } + } + else + { + vector = position - Camera.current.transform.position; + float sqrMagnitude = vector.sqrMagnitude; + float num2 = radius * radius; + float num3 = num2 * num2 / sqrMagnitude; + float num4 = num3 / num2; + if (num4 < 1f) + { + float num5 = Mathf.Sqrt(num2 - num3); + num = Mathf.Atan2(num5, Mathf.Sqrt(num3)) * 57.29578f; + if (!handlesOnly) + { + Handles.DrawWireDisc(position - num2 * vector / sqrMagnitude, vector, num5); + } } else { - camera.rect = new Rect(0f, 0f, 1f, 1f); + num = -1000f; } - if (drawMode == DrawCameraMode.Normal) + if (!handlesOnly) { - RenderTexture targetTexture = camera.targetTexture; - camera.targetTexture = RenderTexture.active; - camera.Render(); - camera.targetTexture = targetTexture; + for (int j = 0; j < 3; j++) + { + if (num4 < 1f) + { + float num6 = Vector3.Angle(vector, array[j]); + num6 = 90f - Mathf.Min(num6, 180f - num6); + float num7 = Mathf.Tan(num6 * 0.0174532924f); + float num8 = Mathf.Sqrt(num3 + num7 * num7 * num3) / radius; + if (num8 < 1f) + { + float num9 = Mathf.Asin(num8) * 57.29578f; + Vector3 vector2 = Vector3.Cross(array[j], vector).normalized; + vector2 = Quaternion.AngleAxis(num9, array[j]) * vector2; + Handles.DrawTwoShadedWireDisc(position, array[j], vector2, (90f - num9) * 2f, radius); + } + else + { + Handles.DrawTwoShadedWireDisc(position, array[j], radius); + } + } + else + { + Handles.DrawTwoShadedWireDisc(position, array[j], radius); + } + } } - else + } + Color color = Handles.color; + for (int k = 0; k < 6; k++) + { + int controlID = GUIUtility.GetControlID(Handles.s_RadiusHandleHash, FocusType.Keyboard); + float num10 = Vector3.Angle(array[k], -vector); + if ((num10 > 5f && num10 < 175f) || GUIUtility.hotControl == controlID) { - if (drawGrid) + Color color2 = color; + if (num10 > num + 5f) { - Handles.Internal_DrawCameraWithGrid(camera, (int)drawMode, ref gridParam); + color2.a = Mathf.Clamp01(Handles.backfaceAlphaMultiplier * color.a * 2f); } else { - Handles.Internal_DrawCamera(camera, (int)drawMode); + color2.a = Mathf.Clamp01(color.a * 2f); } - if (finish) + Handles.color = color2; + Vector3 vector3 = position + radius * array[k]; + bool changed = GUI.changed; + GUI.changed = false; + vector3 = Slider1D.Do(controlID, vector3, array[k], HandleUtility.GetHandleSize(vector3) * 0.03f, new Handles.DrawCapFunction(Handles.DotCap), 0f); + if (GUI.changed) { - Handles.Internal_FinishDrawingCamera(camera); + radius = Vector3.Distance(vector3, position); } + GUI.changed |= changed; } } - else - { - Handles.Internal_SetCurrentCamera(camera); - } - } - internal static void DrawCamera(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) - { - Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, true); - } - internal static void DrawCameraStep1(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) - { - Handles.DrawCameraImpl(position, camera, drawMode, true, gridParam, false); + Handles.color = color; + return radius; } - internal static void DrawCameraStep2(Camera camera, DrawCameraMode drawMode) + internal static Vector2 DoRectHandles(Quaternion rotation, Vector3 position, Vector2 size) { - if (Event.current.type == EventType.Repaint && drawMode != DrawCameraMode.Normal) + Vector3 b = rotation * Vector3.forward; + Vector3 vector = rotation * Vector3.up; + Vector3 vector2 = rotation * Vector3.right; + float num = 0.5f * size.x; + float num2 = 0.5f * size.y; + Vector3 vector3 = position + vector * num2 + vector2 * num; + Vector3 vector4 = position - vector * num2 + vector2 * num; + Vector3 vector5 = position - vector * num2 - vector2 * num; + Vector3 vector6 = position + vector * num2 - vector2 * num; + Handles.DrawLine(vector3, vector4); + Handles.DrawLine(vector4, vector5); + Handles.DrawLine(vector5, vector6); + Handles.DrawLine(vector6, vector3); + Color color = Handles.color; + color.a = Mathf.Clamp01(color.a * 2f); + Handles.color = color; + num2 = Handles.SizeSlider(position, vector, num2); + num2 = Handles.SizeSlider(position, -vector, num2); + num = Handles.SizeSlider(position, vector2, num); + num = Handles.SizeSlider(position, -vector2, num); + if ((Tools.current != Tool.Move && Tools.current != Tool.Scale) || Tools.pivotRotation != PivotRotation.Local) { - Handles.Internal_FinishDrawingCamera(camera); + Handles.DrawLine(position, position + b); } + size.x = 2f * num; + size.y = 2f * num2; + return size; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void EmitGUIGeometryForCamera(Camera source, Camera dest); - [ExcludeFromDocs] - public static void DrawCamera(Rect position, Camera camera) + public static Quaternion DoRotationHandle(Quaternion rotation, Vector3 position) { - DrawCameraMode drawMode = DrawCameraMode.Normal; - Handles.DrawCamera(position, camera, drawMode); + float handleSize = HandleUtility.GetHandleSize(position); + Color color = Handles.color; + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.right, handleSize, true, SnapSettings.rotation); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.up, handleSize, true, SnapSettings.rotation); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + rotation = Handles.Disc(rotation, position, rotation * Vector3.forward, handleSize, true, SnapSettings.rotation); + if (!flag) + { + Handles.color = Handles.centerColor; + rotation = Handles.Disc(rotation, position, Camera.current.transform.forward, handleSize * 1.1f, false, 0f); + rotation = Handles.FreeRotateHandle(rotation, position, handleSize); + } + Handles.color = color; + return rotation; } - public static void DrawCamera(Rect position, Camera camera, [DefaultValue("DrawCameraMode.Normal")] DrawCameraMode drawMode) + public static Vector3 DoScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) { - Handles.DrawCameraImpl(position, camera, drawMode, false, default(DrawGridParameters), true); + bool flag = !Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects); + Handles.color = ((!flag) ? Handles.xAxisColor : Color.Lerp(Handles.xAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.x = Handles.ScaleSlider(scale.x, position, rotation * Vector3.right, rotation, size, SnapSettings.scale); + Handles.color = ((!flag) ? Handles.yAxisColor : Color.Lerp(Handles.yAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.y = Handles.ScaleSlider(scale.y, position, rotation * Vector3.up, rotation, size, SnapSettings.scale); + Handles.color = ((!flag) ? Handles.zAxisColor : Color.Lerp(Handles.zAxisColor, Handles.staticColor, Handles.staticBlend)); + scale.z = Handles.ScaleSlider(scale.z, position, rotation * Vector3.forward, rotation, size, SnapSettings.scale); + Handles.color = Handles.centerColor; + EditorGUI.BeginChangeCheck(); + float num = Handles.ScaleValueHandle(scale.x, position, rotation, size, new Handles.DrawCapFunction(Handles.CubeCap), SnapSettings.scale); + if (EditorGUI.EndChangeCheck()) + { + float num2 = num / scale.x; + scale.x = num; + scale.y *= num2; + scale.z *= num2; + } + return scale; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void SetCameraFilterMode(Camera camera, Handles.FilterMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Handles.FilterMode GetCameraFilterMode(Camera camera); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void DrawCameraFade(Camera camera, float fade); - public static void SetCamera(Camera camera) + internal static float DoSimpleEdgeHandle(Quaternion rotation, Vector3 position, float radius) { - if (Event.current.type == EventType.Repaint) + Vector3 vector = rotation * Vector3.right; + EditorGUI.BeginChangeCheck(); + radius = Handles.SizeSlider(position, vector, radius); + radius = Handles.SizeSlider(position, -vector, radius); + if (EditorGUI.EndChangeCheck()) { - Handles.Internal_SetupCamera(camera); + radius = Mathf.Max(0f, radius); } - else + if (radius > 0f) { - Handles.Internal_SetCurrentCamera(camera); + Handles.DrawLine(position - vector * radius, position + vector * radius); } + return radius; } - public static void SetCamera(Rect position, Camera camera) + internal static void DoSimpleRadiusArcHandleXY(Quaternion rotation, Vector3 position, ref float radius, ref float arc) { - Rect rect = GUIClip.Unclip(position); - Event current = Event.current; - Rect pixelRect = new Rect(rect.xMin, (float)Screen.height - rect.yMax, rect.width, rect.height); - camera.pixelRect = pixelRect; - if (current.type == EventType.Repaint) + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + Vector3 a = Quaternion.Euler(0f, 0f, arc) * vector3; + EditorGUI.BeginChangeCheck(); + if (arc < 315f) { - Handles.Internal_SetupCamera(camera); + radius = Handles.SizeSlider(position, vector3, radius); } - else + if (arc > 135f) { - Handles.Internal_SetCurrentCamera(camera); + radius = Handles.SizeSlider(position, vector2, radius); } - } - public static void BeginGUI() - { - if (Camera.current && Event.current.type == EventType.Repaint) + if (arc > 225f) { - GUIClip.Reapply(); + radius = Handles.SizeSlider(position, -vector3, radius); } - } - [Obsolete("Please use BeginGUI() with GUILayout.BeginArea(position) / GUILayout.EndArea()")] - public static void BeginGUI(Rect position) - { - GUILayout.BeginArea(position); - } - public static void EndGUI() - { - Camera current = Camera.current; - if (current && Event.current.type == EventType.Repaint) + if (arc > 315f) { - Handles.Internal_SetupCamera(current); + radius = Handles.SizeSlider(position, -vector2, radius); + } + if (EditorGUI.EndChangeCheck()) + { + radius = Mathf.Max(0f, radius); + } + if (radius > 0f) + { + Handles.DrawWireArc(position, vector, vector3, arc, radius); + if (arc < 360f) + { + Handles.DrawLine(position, vector3 * radius); + Handles.DrawLine(position, a * radius); + } + else + { + Handles.DrawDottedLine(position, vector3 * radius, 5f); + } + Vector3 vector4 = a * radius; + float handleSize = HandleUtility.GetHandleSize(vector4); + EditorGUI.BeginChangeCheck(); + Vector3 rhs = Handles.FreeMoveHandle(vector4, Quaternion.identity, handleSize * 0.03f, SnapSettings.move, new Handles.DrawCapFunction(Handles.CircleCap)); + if (EditorGUI.EndChangeCheck()) + { + arc += Mathf.Atan2(Vector3.Dot(vector, Vector3.Cross(vector4, rhs)), Vector3.Dot(vector4, rhs)) * 57.29578f; + } } } - internal static void ShowStaticLabelIfNeeded(Vector3 pos) + internal static float DoSimpleRadiusHandle(Quaternion rotation, Vector3 position, float radius, bool hemisphere) { - if (!Tools.s_Hidden && EditorApplication.isPlaying && GameObjectUtility.ContainsStatic(Selection.gameObjects)) + Vector3 vector = rotation * Vector3.forward; + Vector3 vector2 = rotation * Vector3.up; + Vector3 vector3 = rotation * Vector3.right; + bool changed = GUI.changed; + GUI.changed = false; + radius = Handles.SizeSlider(position, vector, radius); + if (!hemisphere) { - Handles.color = Color.white; - GUIStyle gUIStyle = "SC ViewAxisLabel"; - gUIStyle.alignment = TextAnchor.MiddleLeft; - gUIStyle.fixedWidth = 0f; - Handles.BeginGUI(); - Rect position = HandleUtility.WorldPointToSizedRect(pos, EditorGUIUtility.TempContent("Static"), gUIStyle); - position.x += 10f; - position.y += 10f; - GUI.Label(position, EditorGUIUtility.TempContent("Static"), gUIStyle); - Handles.EndGUI(); + radius = Handles.SizeSlider(position, -vector, radius); + } + if (GUI.changed) + { + radius = Mathf.Max(0f, radius); + } + GUI.changed |= changed; + changed = GUI.changed; + GUI.changed = false; + radius = Handles.SizeSlider(position, vector2, radius); + radius = Handles.SizeSlider(position, -vector2, radius); + radius = Handles.SizeSlider(position, vector3, radius); + radius = Handles.SizeSlider(position, -vector3, radius); + if (GUI.changed) + { + radius = Mathf.Max(0f, radius); } + GUI.changed |= changed; + if (radius > 0f) + { + Handles.DrawWireDisc(position, vector, radius); + Handles.DrawWireArc(position, vector2, -vector3, (float)((!hemisphere) ? 360 : 180), radius); + Handles.DrawWireArc(position, vector3, vector2, (float)((!hemisphere) ? 360 : 180), radius); + } + return radius; } } } diff --git a/UnityEditor/UnityEditor/HierarchyProperty.cs b/UnityEditor/UnityEditor/HierarchyProperty.cs index 9cf3c70f..fe5adec4 100644 --- a/UnityEditor/UnityEditor/HierarchyProperty.cs +++ b/UnityEditor/UnityEditor/HierarchyProperty.cs @@ -60,6 +60,15 @@ public extern string guid [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern bool alphaSorted + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool isValid { [WrapperlessIcall] @@ -140,11 +149,11 @@ public void SetSearchFilter(string searchString, int mode) } internal void SetSearchFilter(SearchFilter filter) { - this.SetSearchFilterINTERNAL(filter.SplitNameFilter(), filter.classNames, filter.assetLabels, filter.referencingInstanceIDs, filter.showAllHits); + this.SetSearchFilterINTERNAL(filter.SplitNameFilter(), filter.classNames, filter.assetLabels, filter.assetBundleNames, filter.referencingInstanceIDs, filter.showAllHits); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void SetSearchFilterINTERNAL(string[] nameFilters, string[] classNames, string[] assetLabels, int[] referencingInstanceIDs, bool showAllHits); + private extern void SetSearchFilterINTERNAL(string[] nameFilters, string[] classNames, string[] assetLabels, string[] assetBundleNames, int[] referencingInstanceIDs, bool showAllHits); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern int[] FindAllAncestors(int[] instanceIDs); diff --git a/UnityEditor/UnityEditor/HierarchyWindow.cs b/UnityEditor/UnityEditor/HierarchyWindow.cs deleted file mode 100644 index 497a9726..00000000 --- a/UnityEditor/UnityEditor/HierarchyWindow.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -namespace UnityEditor -{ - internal class HierarchyWindow : BaseProjectWindow - { - public HierarchyWindow() - { - this.m_HierarchyType = HierarchyType.GameObjects; - } - } -} diff --git a/UnityEditor/UnityEditor/Highlighter.cs b/UnityEditor/UnityEditor/Highlighter.cs index 02d1e1ed..df154b79 100644 --- a/UnityEditor/UnityEditor/Highlighter.cs +++ b/UnityEditor/UnityEditor/Highlighter.cs @@ -15,6 +15,21 @@ public sealed class Highlighter private static float s_LastTime; private static Rect s_RepaintRegion; private static GUIStyle s_HighlightStyle; + internal static extern HighlightSearchMode searchMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool searching + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } private static GUIStyle highlightStyle { get @@ -64,21 +79,35 @@ private set Highlighter.internal_set_activeRect(value); } } - internal static extern HighlightSearchMode searchMode + internal static void Handle(Rect position, string text) { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + Highlighter.INTERNAL_CALL_Handle(ref position, text); } - internal static extern bool searching + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Handle(ref Rect position, string text); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string internal_get_activeText(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void internal_set_activeText(string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Rect internal_get_activeRect(); + internal static void internal_set_activeRect(Rect value) { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + Highlighter.INTERNAL_CALL_internal_set_activeRect(ref value); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_internal_set_activeRect(ref Rect value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool internal_get_activeVisible(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void internal_set_activeVisible(bool value); public static void Stop() { Highlighter.active = false; @@ -253,34 +282,5 @@ internal static void ControlHighlightGUI(GUIView self) GUI.color = color; GUI.matrix = matrix; } - internal static void Handle(Rect position, string text) - { - Highlighter.INTERNAL_CALL_Handle(ref position, text); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Handle(ref Rect position, string text); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string internal_get_activeText(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void internal_set_activeText(string value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Rect internal_get_activeRect(); - internal static void internal_set_activeRect(Rect value) - { - Highlighter.INTERNAL_CALL_internal_set_activeRect(ref value); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_internal_set_activeRect(ref Rect value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool internal_get_activeVisible(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void internal_set_activeVisible(bool value); } } diff --git a/UnityEditor/UnityEditor/HingeJointEditor.cs b/UnityEditor/UnityEditor/HingeJointEditor.cs new file mode 100644 index 00000000..c39af9a8 --- /dev/null +++ b/UnityEditor/UnityEditor/HingeJointEditor.cs @@ -0,0 +1,31 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(HingeJoint))] + internal class HingeJointEditor : Editor + { + public override void OnInspectorGUI() + { + base.DrawDefaultInspector(); + string text = string.Empty; + JointLimits limits = ((HingeJoint)this.target).limits; + if (limits.min < -180f || limits.min > 180f) + { + text += "Min Limit needs to be within [-180,180]."; + } + if (limits.max < -180f || limits.max > 180f) + { + text = text + ((!string.IsNullOrEmpty(text)) ? "\n" : string.Empty) + "Max Limit needs to be within [-180,180]."; + } + if (limits.max < limits.min) + { + text = text + ((!string.IsNullOrEmpty(text)) ? "\n" : string.Empty) + "Max Limit needs to be larger or equal to the Min Limit."; + } + if (!string.IsNullOrEmpty(text)) + { + EditorGUILayout.HelpBox(text, MessageType.Warning); + } + } + } +} diff --git a/UnityEditor/UnityEditor/HostView.cs b/UnityEditor/UnityEditor/HostView.cs index 13048119..5ec49a1a 100644 --- a/UnityEditor/UnityEditor/HostView.cs +++ b/UnityEditor/UnityEditor/HostView.cs @@ -186,8 +186,15 @@ protected void RegisterSelectedPane() { EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, new EditorApplication.CallbackFunction(this.m_ActualView.CheckForWindowRepaint)); } - this.Invoke("OnBecameVisible"); - this.Invoke("OnFocus"); + try + { + this.Invoke("OnBecameVisible"); + this.Invoke("OnFocus"); + } + catch (TargetInvocationException ex) + { + Debug.LogError(ex.InnerException.GetType().Name + ":" + ex.InnerException.Message); + } } protected void DeregisterSelectedPane(bool clearActualView) { diff --git a/UnityEditor/UnityEditor/IAudioEffectPlugin.cs b/UnityEditor/UnityEditor/IAudioEffectPlugin.cs new file mode 100644 index 00000000..24fb99ab --- /dev/null +++ b/UnityEditor/UnityEditor/IAudioEffectPlugin.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEditor +{ + public abstract class IAudioEffectPlugin + { + public abstract bool SetFloatParameter(string name, float value); + public abstract bool GetFloatParameter(string name, out float value); + public abstract bool GetFloatParameterInfo(string name, out float minRange, out float maxRange, out float defaultValue); + public abstract bool GetFloatBuffer(string name, out float[] data, int numsamples); + public abstract int GetSampleRate(); + public abstract bool IsPluginEditableAndEnabled(); + } +} diff --git a/UnityEditor/UnityEditor/IAudioEffectPluginGUI.cs b/UnityEditor/UnityEditor/IAudioEffectPluginGUI.cs new file mode 100644 index 00000000..160a94a0 --- /dev/null +++ b/UnityEditor/UnityEditor/IAudioEffectPluginGUI.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEditor +{ + public abstract class IAudioEffectPluginGUI + { + public abstract string Name + { + get; + } + public abstract string Description + { + get; + } + public abstract string Vendor + { + get; + } + public abstract bool OnGUI(IAudioEffectPlugin plugin); + } +} diff --git a/UnityEditor/UnityEditor/IDeviceUtils.cs b/UnityEditor/UnityEditor/IDeviceUtils.cs new file mode 100644 index 00000000..17635bd8 --- /dev/null +++ b/UnityEditor/UnityEditor/IDeviceUtils.cs @@ -0,0 +1,28 @@ +using System; +using UnityEditor.Modules; +namespace UnityEditor +{ + internal static class IDeviceUtils + { + internal static RemoteAddress StartRemoteSupport(string deviceId) + { + IDevice device = ModuleManager.GetDevice(deviceId); + return device.StartRemoteSupport(); + } + internal static void StopRemoteSupport(string deviceId) + { + IDevice device = ModuleManager.GetDevice(deviceId); + device.StopRemoteSupport(); + } + internal static RemoteAddress StartPlayerConnectionSupport(string deviceId) + { + IDevice device = ModuleManager.GetDevice(deviceId); + return device.StartPlayerConnectionSupport(); + } + internal static void StopPlayerConnectionSupport(string deviceId) + { + IDevice device = ModuleManager.GetDevice(deviceId); + device.StopPlayerConnectionSupport(); + } + } +} diff --git a/UnityEditor/UnityEditor/IPreviewable.cs b/UnityEditor/UnityEditor/IPreviewable.cs index 6af3faff..bb9e9210 100644 --- a/UnityEditor/UnityEditor/IPreviewable.cs +++ b/UnityEditor/UnityEditor/IPreviewable.cs @@ -18,5 +18,6 @@ UnityEngine.Object target void OnInteractivePreviewGUI(Rect r, GUIStyle background); void OnPreviewSettings(); string GetInfoString(); + void ReloadPreviewInstances(); } } diff --git a/UnityEditor/UnityEditor/ITreeViewDataSource.cs b/UnityEditor/UnityEditor/ITreeViewDataSource.cs index 56d4c272..c6aec7af 100644 --- a/UnityEditor/UnityEditor/ITreeViewDataSource.cs +++ b/UnityEditor/UnityEditor/ITreeViewDataSource.cs @@ -24,5 +24,6 @@ TreeViewItem root void InsertFakeItem(int id, int parentID, string name, Texture2D icon); void RemoveFakeItem(); bool HasFakeItem(); + void OnSearchChanged(); } } diff --git a/UnityEditor/UnityEditor/ITreeViewGUI.cs b/UnityEditor/UnityEditor/ITreeViewGUI.cs index 36c135b0..c3854bd8 100644 --- a/UnityEditor/UnityEditor/ITreeViewGUI.cs +++ b/UnityEditor/UnityEditor/ITreeViewGUI.cs @@ -9,6 +9,14 @@ float halfDropBetweenHeight { get; } + float topRowMargin + { + get; + } + float bottomRowMargin + { + get; + } Vector2 GetTotalSize(List rows); void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible); float GetTopPixelOfRow(int row, List rows); diff --git a/UnityEditor/UnityEditor/ImportRawHeightmap.cs b/UnityEditor/UnityEditor/ImportRawHeightmap.cs index 7a2827cc..eba86808 100644 --- a/UnityEditor/UnityEditor/ImportRawHeightmap.cs +++ b/UnityEditor/UnityEditor/ImportRawHeightmap.cs @@ -78,7 +78,7 @@ internal void OnWizardCreate() { base.isValid = false; base.errorString = "Heightmaps above 4096x4096 in resolution are not supported"; - Debug.LogError("Heightmaps above 4096x4096 in resolution are not supported"); + Debug.LogError(base.errorString); } if (File.Exists(this.m_Path) && base.isValid) { diff --git a/UnityEditor/UnityEditor/InitialModuleUI.cs b/UnityEditor/UnityEditor/InitialModuleUI.cs index 559144af..80242315 100644 --- a/UnityEditor/UnityEditor/InitialModuleUI.cs +++ b/UnityEditor/UnityEditor/InitialModuleUI.cs @@ -6,7 +6,7 @@ internal class InitialModuleUI : ModuleUI { private class Texts { - public GUIContent duration = new GUIContent("Duration", "The length of time the Particle System is emitting partcles, if the system is looping, this indicates the length of one cycle."); + public GUIContent duration = new GUIContent("Duration", "The length of time the Particle System is emitting particles, if the system is looping, this indicates the length of one cycle."); public GUIContent looping = new GUIContent("Looping", "If true, the emission cycle will repeat after the duration."); public GUIContent prewarm = new GUIContent("Prewarm", "When played a prewarmed system will be in a state as if it had emitted one loop cycle. Can only be used if the system is looping."); public GUIContent startDelay = new GUIContent("Start Delay", "Delay in seconds that this Particle System will wait before emitting particles. Cannot be used together with a prewarmed looping system."); @@ -17,7 +17,7 @@ private class Texts public GUIContent size = new GUIContent("Start Size", "The start size of particles."); public GUIContent rotation = new GUIContent("Start Rotation", "The start rotation of particles in degrees."); public GUIContent autoplay = new GUIContent("Play On Awake", "If enabled, the system will start playing automatically."); - public GUIContent gravity = new GUIContent("Gravity Multiplier", "Scales the gravity defined in Physics Manager"); + public GUIContent gravity = new GUIContent("Gravity Modifier", "Scales the gravity defined in Physics Manager"); public GUIContent inheritvelocity = new GUIContent("Inherit Velocity", "Applies the current directional velocity of the Transform to newly emitted particles."); public GUIContent simulationSpace = new GUIContent("Simulation Space", "Makes particle positions simulate in worldspace or local space. In local space they stay relative to the Transform."); public string[] simulationSpaces = new string[] diff --git a/UnityEditor/UnityEditor/InitializeOnLoadMethodAttribute.cs b/UnityEditor/UnityEditor/InitializeOnLoadMethodAttribute.cs new file mode 100644 index 00000000..164924f0 --- /dev/null +++ b/UnityEditor/UnityEditor/InitializeOnLoadMethodAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEditor +{ + [AttributeUsage(AttributeTargets.Method)] + public class InitializeOnLoadMethodAttribute : Attribute + { + } +} diff --git a/UnityEditor/UnityEditor/InspectorState.cs b/UnityEditor/UnityEditor/InspectorState.cs index 9ac57aa2..582fdfce 100644 --- a/UnityEditor/UnityEditor/InspectorState.cs +++ b/UnityEditor/UnityEditor/InspectorState.cs @@ -58,5 +58,14 @@ internal static Vector3 GetVector3(string key, Vector3 defaultValue) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void EraseVector3(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetIntArray(string key, int[] value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int[] GetIntArray(string key, int[] defaultValue); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void EraseIntArray(string key); } } diff --git a/UnityEditor/UnityEditor/InspectorWindow.cs b/UnityEditor/UnityEditor/InspectorWindow.cs index 8972400c..1f1d32a7 100644 --- a/UnityEditor/UnityEditor/InspectorWindow.cs +++ b/UnityEditor/UnityEditor/InspectorWindow.cs @@ -41,6 +41,7 @@ public Styles() internal const int kInspectorPaddingRight = 4; public Vector2 m_ScrollPosition; public InspectorMode m_InspectorMode; + private static bool s_FlushOptimizedGUI; private static readonly List m_AllInspectors = new List(); private bool m_ResetKeyboardControl; protected ActiveEditorTracker m_Tracker; @@ -52,6 +53,7 @@ public Styles() [SerializeField] private PreviewWindow m_PreviewWindow; private LabelGUI m_LabelGUI = new LabelGUI(); + private AssetBundleNameGUI m_AssetBundleNameGUI = new AssetBundleNameGUI(); private TypeSelectionList m_TypeSelectionList; private double m_lastRenderedTime; private List m_Previews; @@ -114,7 +116,6 @@ protected virtual void OnEnable() protected virtual void OnDisable() { InspectorWindow.m_AllInspectors.Remove(this); - this.m_LabelGUI.OnDisable(); } private void OnLostFocus() { @@ -224,6 +225,7 @@ protected virtual void CreateTracker() { if (this.m_Tracker != null) { + this.m_Tracker.inspectorMode = this.m_InspectorMode; return; } ActiveEditorTracker sharedTracker = ActiveEditorTracker.sharedTracker; @@ -310,6 +312,7 @@ protected virtual void OnGUI() } InspectorWindow.s_CurrentInspectorWindow = this; Editor[] activeEditors = this.m_Tracker.activeEditors; + this.AssignAssetEditor(activeEditors); Profiler.BeginSample("InspectorWindow.DrawEditors()"); this.DrawEditors(activeEditors); Profiler.EndSample(); @@ -371,19 +374,22 @@ public IPreviewable GetEditorThatControlsPreview(IPreviewable[] editors) { if (!EditorUtility.IsPersistent(previewable3.target) || !(AssetDatabase.GetAssetPath(previewable3.target) != AssetDatabase.GetAssetPath(editors[0].target))) { - if (previewable3.HasPreviewGUI()) + if (!(editors[0] is AssetImporterInspector) || previewable3 is AssetImporterInspector) { - if (previewable3 == lastInteractedEditor) + if (previewable3.HasPreviewGUI()) { - return previewable3; - } - if (previewable2 == null && previewable3.GetType() == type) - { - previewable2 = previewable3; - } - if (previewable == null) - { - previewable = previewable3; + if (previewable3 == lastInteractedEditor) + { + return previewable3; + } + if (previewable2 == null && previewable3.GetType() == type) + { + previewable2 = previewable3; + } + if (previewable == null) + { + previewable = previewable3; + } } } } @@ -415,9 +421,12 @@ public IPreviewable[] GetEditorsWithPreviews(Editor[] editors) { if (!this.ShouldCullEditor(editors, num)) { - if (editor.HasPreviewGUI()) + if (!(editors[0] is AssetImporterInspector) || editor is AssetImporterInspector) { - list.Add(editor); + if (editor.HasPreviewGUI()) + { + list.Add(editor); + } } } } @@ -531,6 +540,7 @@ private void DrawPreviewAndLabels() bool flag = editorThatControlsPreview != null && editorThatControlsPreview.HasPreviewGUI() && this.m_PreviewWindow == null; UnityEngine.Object[] inspectedAssets = this.GetInspectedAssets(); bool flag2 = inspectedAssets.Length > 0; + bool flag3 = inspectedAssets.Any((UnityEngine.Object a) => !(a is MonoScript) && AssetDatabase.IsMainAsset(a)); if (!flag && !flag2) { return; @@ -596,8 +606,11 @@ private void DrawPreviewAndLabels() } else { - position2.xMin = position2.x + InspectorWindow.styles.preToolbar2.CalcSize(content).x + 3f; - GUI.Label(lastRect, content, InspectorWindow.styles.preToolbar2); + float a2 = position2.xMax - lastRect.xMin - 3f - 20f; + float width = Mathf.Min(a2, InspectorWindow.styles.preToolbar2.CalcSize(content).x); + Rect position4 = new Rect(lastRect.x, lastRect.y, width, lastRect.height); + position2.xMin = position4.xMax + 3f; + GUI.Label(position4, content, InspectorWindow.styles.preToolbar2); } if (flag && Event.current.type == EventType.Repaint) { @@ -615,12 +628,12 @@ private void DrawPreviewAndLabels() float height; if (flag) { - Rect position4 = base.position; + Rect position5 = base.position; if (EditorSettings.externalVersionControl != ExternalVersionControl.Disabled && EditorSettings.externalVersionControl != ExternalVersionControl.AutoDetect && EditorSettings.externalVersionControl != ExternalVersionControl.Generic) { - position4.height -= 17f; + position5.height -= 17f; } - height = this.m_PreviewResizer.ResizeHandle(position4, 100f, 100f, 17f, lastRect); + height = this.m_PreviewResizer.ResizeHandle(position5, 100f, 100f, 17f, lastRect); } else { @@ -648,6 +661,10 @@ private void DrawPreviewAndLabels() this.m_LabelGUI.OnLabelGUI(inspectedAssets); EditorGUI.EndDisabledGroup(); } + if (flag3) + { + this.m_AssetBundleNameGUI.OnAssetBundleNameGUI(inspectedAssets); + } GUILayout.EndVertical(); } protected UnityEngine.Object[] GetTargetsForPreview(IPreviewable previewEditor) @@ -765,6 +782,13 @@ private void DrawVCSShortInfo() } } } + protected void AssignAssetEditor(Editor[] editors) + { + if (editors.Length > 1 && editors[0] is AssetImporterInspector) + { + (editors[0] as AssetImporterInspector).assetEditor = editors[1]; + } + } private void DrawEditors(Editor[] editors) { if (editors.Length == 0) @@ -773,7 +797,7 @@ private void DrawEditors(Editor[] editors) } UnityEngine.Object inspectedObject = this.GetInspectedObject(); string empty = string.Empty; - bool forceDirty = false; + bool forceDirty = InspectorWindow.s_FlushOptimizedGUI; if (Event.current.type == EventType.Repaint && inspectedObject != null && this.m_IsOpenForEdit != AssetDatabase.IsOpenForEdit(inspectedObject, out empty)) { this.m_IsOpenForEdit = !this.m_IsOpenForEdit; @@ -785,9 +809,19 @@ private void DrawEditors(Editor[] editors) dockArea.tabStyle = "dragtabbright"; } GUILayout.Space(0f); - if (editors.Length > 1 && editors[0] is AssetImporterInspector) + if (inspectedObject is Material) { - (editors[0] as AssetImporterInspector).m_AssetEditor = editors[1]; + int num = 0; + while (num <= 1 && num < editors.Length) + { + MaterialEditor materialEditor = editors[num] as MaterialEditor; + if (materialEditor != null) + { + materialEditor.forceVisible = true; + break; + } + num++; + } } bool eyeDropperDirty = Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "EyeDropperUpdate"; Editor.m_AllowMultiObjectAccess = true; @@ -814,6 +848,10 @@ private void DrawEditors(Editor[] editors) GUI.Label(new Rect(0f, 0f, position.width, position.height), "Imported Object", "OL Title"); GUI.EndGroup(); } + if (Event.current.type == EventType.Repaint) + { + InspectorWindow.s_FlushOptimizedGUI = false; + } } private void DrawEditor(Editor editor, int editorIndex, bool forceDirty, ref bool showImportedObjectBarNext, ref Rect importedObjectBarRect, bool eyeDropperDirty) { @@ -836,7 +874,7 @@ private void DrawEditor(Editor editor, int editorIndex, bool forceDirty, ref boo { flag = (visible == 1); } - bool flag2 = forceDirty || editor.isInspectorDirty || eyeDropperDirty; + bool flag2 = forceDirty || editor.isInspectorDirty || eyeDropperDirty || InspectorWindow.s_FlushOptimizedGUI; if (Event.current.type == EventType.Repaint) { editor.isInspectorDirty = false; @@ -1113,6 +1151,10 @@ internal static void ShowWindow() { EditorWindow.GetWindow(typeof(InspectorWindow)); } + private static void FlushOptimizedGUI() + { + InspectorWindow.s_FlushOptimizedGUI = true; + } private void Update() { if (this.m_Tracker == null || this.m_Tracker.activeEditors == null) diff --git a/UnityEditor/UnityEditor/KnobState.cs b/UnityEditor/UnityEditor/KnobState.cs new file mode 100644 index 00000000..1924af19 --- /dev/null +++ b/UnityEditor/UnityEditor/KnobState.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal class KnobState + { + public float dragStartPos; + public float dragStartValue; + public bool isDragging; + public bool isEditing; + } +} diff --git a/UnityEditor/UnityEditor/LODGroupEditor.cs b/UnityEditor/UnityEditor/LODGroupEditor.cs index 3b4c9bc8..55b4bcb9 100644 --- a/UnityEditor/UnityEditor/LODGroupEditor.cs +++ b/UnityEditor/UnityEditor/LODGroupEditor.cs @@ -8,81 +8,17 @@ namespace UnityEditor [CustomEditor(typeof(LODGroup))] internal class LODGroupEditor : Editor { - private class Styles - { - public const int kSceneLabelHalfWidth = 100; - public const int kSceneLabelHeight = 45; - public const int kSceneHeaderOffset = 40; - public const int kSliderBarHeight = 30; - public const int kRenderersButtonHeight = 60; - public const int kButtonPadding = 2; - public const int kDeleteButtonSize = 20; - public const int kSelectedLODRangePadding = 3; - public const int kRenderAreaForegroundPadding = 3; - public readonly GUIStyle m_LODSliderBG = "LODSliderBG"; - public readonly GUIStyle m_LODSliderRange = "LODSliderRange"; - public readonly GUIStyle m_LODSliderRangeSelected = "LODSliderRangeSelected"; - public readonly GUIStyle m_LODSliderText = "LODSliderText"; - public readonly GUIStyle m_LODSliderTextSelected = "LODSliderTextSelected"; - public readonly GUIStyle m_LODStandardButton = "Button"; - public readonly GUIStyle m_LODRendererButton = "LODRendererButton"; - public readonly GUIStyle m_LODRendererAddButton = "LODRendererAddButton"; - public readonly GUIStyle m_LODRendererRemove = "LODRendererRemove"; - public readonly GUIStyle m_LODBlackBox = "LODBlackBox"; - public readonly GUIStyle m_LODCameraLine = "LODCameraLine"; - public readonly GUIStyle m_LODSceneText = "LODSceneText"; - public readonly GUIStyle m_LODRenderersText = "LODRenderersText"; - public readonly GUIStyle m_LODLevelNotifyText = "LODLevelNotifyText"; - public readonly GUIContent m_IconRendererPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add New Renderers"); - public readonly GUIContent m_IconRendererMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove Renderer"); - public readonly GUIContent m_CameraIcon = EditorGUIUtility.IconContent("Camera Icon"); - public readonly GUIContent m_UploadToImporter = new GUIContent("Upload to Importer", "Upload the modified screen percentages to the model importer."); - public readonly GUIContent m_UploadToImporterDisabled = new GUIContent("Upload to Importer", "Number of LOD's in the scene instance differ from the number of LOD's in the imported model."); - public readonly GUIContent m_RecalculateBounds = new GUIContent("Bounds", "Recalculate bounds for the current LOD group."); - public readonly GUIContent m_LightmapScale = new GUIContent("Lightmap Scale", "Set the lightmap scale to match the LOD percentages"); - public readonly GUIContent m_RendersTitle = new GUIContent("Renderers:"); - } - private class LODInfo - { - private float m_ScreenPercentage; - public readonly int m_LODLevel; - public Rect m_ButtonPosition; - public Rect m_RangePosition; - public float ScreenPercent - { - get - { - return LODGroupEditor.DelinearizeScreenPercentage(this.m_ScreenPercentage); - } - set - { - this.m_ScreenPercentage = LODGroupEditor.LinearizeScreenPercentage(value); - } - } - public float RawScreenPercent - { - get - { - return this.m_ScreenPercentage; - } - } - public LODInfo(int lodLevel, float screenPercentage) - { - this.m_LODLevel = lodLevel; - this.m_ScreenPercentage = screenPercentage; - } - } private class LODAction { public delegate void Callback(); private readonly float m_Percentage; - private readonly List m_LODs; + private readonly List m_LODs; private readonly Vector2 m_ClickedPosition; private readonly SerializedObject m_ObjectRef; private readonly LODGroupEditor.LODAction.Callback m_Callback; - public LODAction(List loDs, float percentage, Vector2 clickedPosition, SerializedObject objectRef, LODGroupEditor.LODAction.Callback callback) + public LODAction(List lods, float percentage, Vector2 clickedPosition, SerializedObject objectRef, LODGroupEditor.LODAction.Callback callback) { - this.m_LODs = loDs; + this.m_LODs = lods; this.m_Percentage = percentage; this.m_ClickedPosition = clickedPosition; this.m_ObjectRef = objectRef; @@ -96,11 +32,11 @@ public void InsertLOD() return; } int num = -1; - foreach (LODGroupEditor.LODInfo current in this.m_LODs) + foreach (LODGroupGUI.LODInfo current in this.m_LODs) { if (this.m_Percentage > current.RawScreenPercent) { - num = current.m_LODLevel; + num = current.LODLevel; break; } } @@ -129,12 +65,12 @@ public void DeleteLOD() { return; } - foreach (LODGroupEditor.LODInfo current in this.m_LODs) + foreach (LODGroupGUI.LODInfo current in this.m_LODs) { - int arraySize = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", current.m_LODLevel)).arraySize; + int arraySize = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", current.LODLevel)).arraySize; if (current.m_RangePosition.Contains(this.m_ClickedPosition) && (arraySize == 0 || EditorUtility.DisplayDialog("Delete LOD", "Are you sure you wish to delete this LOD?", "Yes", "No"))) { - SerializedProperty serializedProperty = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}]", current.m_LODLevel)); + SerializedProperty serializedProperty = this.m_ObjectRef.FindProperty(string.Format("m_LODs.Array.data[{0}]", current.LODLevel)); serializedProperty.DeleteCommand(); this.m_ObjectRef.ApplyModifiedProperties(); if (this.m_Callback != null) @@ -160,19 +96,8 @@ public LODLightmapScale(float scale, List renderers) private const string kLODDataPath = "m_LODs.Array.data[{0}]"; private const string kPixelHeightDataPath = "m_LODs.Array.data[{0}].screenRelativeHeight"; private const string kRenderRootPath = "m_LODs.Array.data[{0}].renderers"; - private static readonly Color[] kLODColors = new Color[] - { - new Color(0.4831376f, 0.6211768f, 0.0219608f, 1f), - new Color(0.279216f, 0.4078432f, 0.5835296f, 1f), - new Color(0.2070592f, 0.5333336f, 0.6556864f, 1f), - new Color(0.5333336f, 0.16f, 0.0282352f, 1f), - new Color(0.3827448f, 0.2886272f, 0.5239216f, 1f), - new Color(0.8f, 0.4423528f, 0f, 1f), - new Color(0.4486272f, 0.4078432f, 0.050196f, 1f), - new Color(0.7749016f, 0.6368624f, 0.0250984f, 1f) - }; - private static readonly Color kCulledLODColor = new Color(0.4f, 0f, 0f, 1f); - private static LODGroupEditor.Styles s_Styles; + private const string kFadeModeDataPath = "m_LODs.Array.data[{0}].fadeMode"; + private const string kTransitionPixelHeightDataPath = "m_LODs.Array.data[{0}].fadeTransitionWidth"; private SerializedObject m_Object; private int m_SelectedLODSlider = -1; private int m_SelectedLOD = -1; @@ -232,16 +157,12 @@ public void OnSceneGUI() { return; } - if (LODGroupEditor.s_Styles == null) - { - LODGroupEditor.s_Styles = new LODGroupEditor.Styles(); - } Camera camera = SceneView.lastActiveSceneView.camera; LODGroup lODGroup = this.target as LODGroup; Vector3 vector = lODGroup.transform.TransformPoint(lODGroup.localReferencePoint); LODVisualizationInformation lODVisualizationInformation = LODUtility.CalculateVisualizationData(camera, lODGroup, -1); float worldSpaceSize = lODVisualizationInformation.worldSpaceSize; - Handles.color = ((lODVisualizationInformation.activeLODLevel == -1) ? LODGroupEditor.kCulledLODColor : LODGroupEditor.kLODColors[lODVisualizationInformation.activeLODLevel]); + Handles.color = ((lODVisualizationInformation.activeLODLevel == -1) ? LODGroupGUI.kCulledLODColor : LODGroupGUI.kLODColors[lODVisualizationInformation.activeLODLevel]); Handles.SelectionFrame(0, vector, camera.transform.rotation, worldSpaceSize / 2f); Vector3 b = camera.transform.right * worldSpaceSize / 2f; Vector3 b2 = camera.transform.up * worldSpaceSize / 2f; @@ -260,7 +181,7 @@ public void OnSceneGUI() } Handles.BeginGUI(); GUI.Label(position, GUIContent.none, EditorStyles.notificationBackground); - EditorGUI.DoDropShadowLabel(position, GUIContent.Temp((lODVisualizationInformation.activeLODLevel < 0) ? "Culled" : ("LOD " + lODVisualizationInformation.activeLODLevel)), LODGroupEditor.s_Styles.m_LODLevelNotifyText, 0.3f); + EditorGUI.DoDropShadowLabel(position, GUIContent.Temp((lODVisualizationInformation.activeLODLevel < 0) ? "Culled" : ("LOD " + lODVisualizationInformation.activeLODLevel)), LODGroupGUI.Styles.m_LODLevelNotifyText, 0.3f); Handles.EndGUI(); } public void Update() @@ -269,24 +190,12 @@ public void Update() { return; } - if (!Mathf.Approximately(0f, Vector3.Distance(SceneView.lastActiveSceneView.camera.transform.position, this.m_LastCameraPos))) + if (SceneView.lastActiveSceneView.camera.transform.position != this.m_LastCameraPos) { this.m_LastCameraPos = SceneView.lastActiveSceneView.camera.transform.position; base.Repaint(); } } - private static float DelinearizeScreenPercentage(float percentage) - { - if (Mathf.Approximately(0f, percentage)) - { - return 0f; - } - return Mathf.Sqrt(percentage); - } - private static float LinearizeScreenPercentage(float percentage) - { - return percentage * percentage; - } private ModelImporter GetImporter() { return AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(this.target))) as ModelImporter; @@ -299,83 +208,76 @@ public override void OnInspectorGUI() EditorGUILayout.HelpBox("LOD only available in Unity Pro", MessageType.Warning); GUI.enabled = false; } - if (LODGroupEditor.s_Styles == null) - { - LODGroupEditor.s_Styles = new LODGroupEditor.Styles(); - } this.m_Object.Update(); this.m_NumberOfLODs = this.m_Object.FindProperty("m_LODs").arraySize; + if (this.m_SelectedLOD >= this.m_NumberOfLODs) + { + this.m_SelectedLOD = this.m_NumberOfLODs - 1; + } if (this.m_NumberOfLODs > 0 && this.activeLOD >= 0) { SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); - for (int i = serializedProperty.arraySize - 1; i >= 0; i--) + for (int k = serializedProperty.arraySize - 1; k >= 0; k--) { - SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("renderer"); + SerializedProperty serializedProperty2 = serializedProperty.GetArrayElementAtIndex(k).FindPropertyRelative("renderer"); Renderer x = serializedProperty2.objectReferenceValue as Renderer; if (x == null) { - serializedProperty.DeleteArrayElementAtIndex(i); + serializedProperty.DeleteArrayElementAtIndex(k); } } } - GUILayout.Space(17f); + GUILayout.Space(18f); Rect rect = GUILayoutUtility.GetRect(0f, 30f, new GUILayoutOption[] { GUILayout.ExpandWidth(true) }); - List list = new List(); - float num = -1f; - for (int j = 0; j < this.m_NumberOfLODs; j++) - { - SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", j)); - LODGroupEditor.LODInfo lODInfo = new LODGroupEditor.LODInfo(j, serializedProperty3.floatValue); - lODInfo.m_ButtonPosition = LODGroupEditor.CalcLODButton(rect, lODInfo.ScreenPercent); - float startPercent = (j - 1 >= 0) ? num : 1f; - lODInfo.m_RangePosition = LODGroupEditor.CalcLODRange(rect, startPercent, lODInfo.ScreenPercent); - num = lODInfo.ScreenPercent; - list.Add(lODInfo); - } - GUILayout.Space(8f); + List list = LODGroupGUI.CreateLODInfos(this.m_NumberOfLODs, rect, (int i) => string.Format("LOD {0}", i), (int i) => this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", i)).floatValue); this.DrawLODLevelSlider(rect, list); - GUILayout.Space(8f); + GUILayout.Space(16f); GUILayout.Label(string.Format("LODBias of {0:0.00} active", QualitySettings.lodBias), EditorStyles.boldLabel, new GUILayoutOption[0]); if (this.m_NumberOfLODs > 0 && this.activeLOD >= 0 && this.activeLOD < this.m_NumberOfLODs) { + SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].fadeMode", this.activeLOD)); + EditorGUILayout.PropertyField(serializedProperty3, new GUILayoutOption[0]); + if (serializedProperty3.intValue == 2) + { + EditorGUILayout.PropertyField(this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].fadeTransitionWidth", this.activeLOD)), new GUILayoutOption[0]); + } this.DrawRenderersInfo(Screen.width / 60); } GUILayout.Space(8f); GUILayout.BeginHorizontal(new GUILayoutOption[0]); GUILayout.Label("Recalculate:", EditorStyles.boldLabel, new GUILayoutOption[0]); - if (GUILayout.Button(LODGroupEditor.s_Styles.m_RecalculateBounds, new GUILayoutOption[0])) + if (GUILayout.Button(LODGroupGUI.Styles.m_RecalculateBounds, new GUILayoutOption[0])) { LODUtility.CalculateLODGroupBoundingBox(this.target as LODGroup); } - if (GUILayout.Button(LODGroupEditor.s_Styles.m_LightmapScale, new GUILayoutOption[0])) + if (GUILayout.Button(LODGroupGUI.Styles.m_LightmapScale, new GUILayoutOption[0])) { this.SendPercentagesToLightmapScale(); } GUILayout.EndHorizontal(); GUILayout.Space(5f); - bool flag = PrefabUtility.GetPrefabType(this.target) == PrefabType.ModelPrefabInstance; - if (flag) + ModelImporter modelImporter = (PrefabUtility.GetPrefabType(this.target) != PrefabType.ModelPrefabInstance) ? null : this.GetImporter(); + if (modelImporter != null) { - ModelImporter importer = this.GetImporter(); - SerializedObject serializedObject = new SerializedObject(importer); + SerializedObject serializedObject = new SerializedObject(modelImporter); SerializedProperty serializedProperty4 = serializedObject.FindProperty("m_LODScreenPercentages"); - bool flag2 = serializedProperty4.isArray && serializedProperty4.arraySize == list.Count; + bool flag = serializedProperty4.isArray && serializedProperty4.arraySize == list.Count; bool enabled2 = GUI.enabled; - if (!flag2) + if (!flag) { GUI.enabled = false; } - if (importer != null && GUILayout.Button((!flag2) ? LODGroupEditor.s_Styles.m_UploadToImporterDisabled : LODGroupEditor.s_Styles.m_UploadToImporter, new GUILayoutOption[0])) + if (modelImporter != null && GUILayout.Button((!flag) ? LODGroupGUI.Styles.m_UploadToImporterDisabled : LODGroupGUI.Styles.m_UploadToImporter, new GUILayoutOption[0])) { - for (int k = 0; k < serializedProperty4.arraySize; k++) + for (int j = 0; j < serializedProperty4.arraySize; j++) { - serializedProperty4.GetArrayElementAtIndex(k).floatValue = list[k].RawScreenPercent; + serializedProperty4.GetArrayElementAtIndex(j).floatValue = list[j].RawScreenPercent; } serializedObject.ApplyModifiedProperties(); - AssetDatabase.ImportAsset(importer.assetPath); + AssetDatabase.ImportAsset(modelImporter.assetPath); } GUI.enabled = enabled2; } @@ -384,10 +286,10 @@ public override void OnInspectorGUI() } private void DrawRenderersInfo(int horizontalNumber) { - Rect rect = GUILayoutUtility.GetRect(LODGroupEditor.s_Styles.m_RendersTitle, LODGroupEditor.s_Styles.m_LODSliderTextSelected); + Rect rect = GUILayoutUtility.GetRect(LODGroupGUI.Styles.m_RendersTitle, LODGroupGUI.Styles.m_LODSliderTextSelected); if (Event.current.type == EventType.Repaint) { - EditorStyles.label.Draw(rect, LODGroupEditor.s_Styles.m_RendersTitle, false, false, false, false); + EditorStyles.label.Draw(rect, LODGroupGUI.Styles.m_RendersTitle, false, false, false, false); } SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].renderers", this.activeLOD)); int num = serializedProperty.arraySize + 1; @@ -428,8 +330,8 @@ private void HandleAddRenderer(Rect position, IEnumerable alreadyDrawn, Re switch (type) { case EventType.Repaint: - LODGroupEditor.s_Styles.m_LODStandardButton.Draw(position, GUIContent.none, false, false, false, false); - LODGroupEditor.s_Styles.m_LODRendererAddButton.Draw(new Rect(position.x - 2f, position.y, position.width, position.height), "Add", false, false, false, false); + LODGroupGUI.Styles.m_LODStandardButton.Draw(position, GUIContent.none, false, false, false, false); + LODGroupGUI.Styles.m_LODRendererAddButton.Draw(new Rect(position.x - 2f, position.y, position.width, position.height), "Add", false, false, false, false); return; case EventType.Layout: case EventType.Ignore: @@ -485,10 +387,14 @@ from go in DragAndDrop.objectReferences string commandName = evt.commandName; if (commandName == "ObjectSelectorClosed" && ObjectSelector.get.objectSelectorID == "LODGroupSelector".GetHashCode()) { - this.AddGameObjectRenderers(this.GetRenderers(new List + GameObject gameObject = ObjectSelector.GetCurrentObject() as GameObject; + if (gameObject != null) { - ObjectSelector.GetCurrentObject() as GameObject - }, true), true); + this.AddGameObjectRenderers(this.GetRenderers(new List + { + gameObject + }, true), true); + } evt.Use(); GUIUtility.ExitGUI(); } @@ -528,19 +434,18 @@ private void DrawRendererButton(Rect position, int rendererIndex) content = new GUIContent(ObjectNames.NicifyVariableName(renderer.GetType().Name), renderer.gameObject.name); } } - LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); - GUIStyle gUIStyle = "LODRendererButton"; - gUIStyle.Draw(new Rect(position.x + 2f, position.y + 2f, position.width - 4f, position.height - 4f), content, false, false, false, false); + LODGroupGUI.Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); + LODGroupGUI.Styles.m_LODRendererButton.Draw(new Rect(position.x + 2f, position.y + 2f, position.width - 4f, position.height - 4f), content, false, false, false, false); } else { - LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); - LODGroupEditor.s_Styles.m_LODRendererButton.Draw(position, "", false, false, false, false); + LODGroupGUI.Styles.m_LODBlackBox.Draw(position, GUIContent.none, false, false, false, false); + LODGroupGUI.Styles.m_LODRendererButton.Draw(position, "", false, false, false, false); } if (!this.m_IsPrefab) { - LODGroupEditor.s_Styles.m_LODBlackBox.Draw(position2, GUIContent.none, false, false, false, false); - LODGroupEditor.s_Styles.m_LODRendererRemove.Draw(position2, LODGroupEditor.s_Styles.m_IconRendererMinus, false, false, false, false); + LODGroupGUI.Styles.m_LODBlackBox.Draw(position2, GUIContent.none, false, false, false, false); + LODGroupGUI.Styles.m_LODRendererRemove.Draw(position2, LODGroupGUI.Styles.m_IconRendererMinus, false, false, false, false); } } } @@ -585,7 +490,7 @@ from go in selectedGameObjects { if (EditorUtility.IsPersistent(current)) { - GameObject gameObject = UnityEngine.Object.Instantiate(current) as GameObject; + GameObject gameObject = UnityEngine.Object.Instantiate(current); if (gameObject != null) { gameObject.transform.parent = lodGroup.transform; @@ -656,21 +561,21 @@ private void DeletedLOD() } private static void UpdateCamera(float desiredPercentage, LODGroup group) { - Vector3 position = group.transform.TransformPoint(group.localReferencePoint); + Vector3 pos = group.transform.TransformPoint(group.localReferencePoint); float num = LODUtility.CalculateDistance(SceneView.lastActiveSceneView.camera, (desiredPercentage > 0f) ? desiredPercentage : 1E-06f, group); if (SceneView.lastActiveSceneView.camera.orthographic) { num = Mathf.Sqrt(num * num * (1f + SceneView.lastActiveSceneView.camera.aspect)); } - SceneView.lastActiveSceneView.LookAtDirect(position, SceneView.lastActiveSceneView.camera.transform.rotation, num); + SceneView.lastActiveSceneView.LookAtDirect(pos, SceneView.lastActiveSceneView.camera.transform.rotation, num); } - private void UpdateSelectedLODFromCamera(IEnumerable lods, float cameraPercent) + private void UpdateSelectedLODFromCamera(IEnumerable lods, float cameraPercent) { - foreach (LODGroupEditor.LODInfo current in lods) + foreach (LODGroupGUI.LODInfo current in lods) { if (cameraPercent > current.RawScreenPercent) { - this.m_SelectedLOD = current.m_LODLevel; + this.m_SelectedLOD = current.LODLevel; break; } } @@ -678,9 +583,9 @@ private void UpdateSelectedLODFromCamera(IEnumerable lod private static float GetCameraPercentForCurrentQualityLevel(float clickPosition, float sliderStart, float sliderWidth) { float percentage = Mathf.Clamp(1f - (clickPosition - sliderStart) / sliderWidth, 0.01f, 1f); - return LODGroupEditor.LinearizeScreenPercentage(percentage); + return LODGroupGUI.LinearizeScreenPercentage(percentage); } - private void DrawLODLevelSlider(Rect sliderPosition, List lods) + private void DrawLODLevelSlider(Rect sliderPosition, List lods) { int controlID = GUIUtility.GetControlID(this.m_LODSliderId, FocusType.Passive); int controlID2 = GUIUtility.GetControlID(this.m_CameraSliderId, FocusType.Passive); @@ -705,7 +610,7 @@ private void DrawLODLevelSlider(Rect sliderPosition, List 0 && lods[lods.Count - 1].ScreenPercent < num) @@ -718,15 +623,15 @@ private void DrawLODLevelSlider(Rect sliderPosition, List collection = + IOrderedEnumerable collection = from lod in lods where lod.ScreenPercent > 0.5f select lod into x - orderby x.m_LODLevel descending + orderby x.LODLevel descending select x; - IOrderedEnumerable collection2 = + IOrderedEnumerable collection2 = from lod in lods where lod.ScreenPercent <= 0.5f select lod into x - orderby x.m_LODLevel + orderby x.LODLevel select x; - List list = new List(); + List list = new List(); list.AddRange(collection); list.AddRange(collection2); - foreach (LODGroupEditor.LODInfo current3 in list) + foreach (LODGroupGUI.LODInfo current3 in list) { if (current3.m_ButtonPosition.Contains(current.mousePosition)) { - this.m_SelectedLODSlider = current3.m_LODLevel; + this.m_SelectedLODSlider = current3.LODLevel; flag3 = true; if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) { @@ -780,17 +685,17 @@ orderby x.m_LODLevel } if (!flag3) { - foreach (LODGroupEditor.LODInfo current4 in lods) + foreach (LODGroupGUI.LODInfo current4 in lods) { if (current4.m_RangePosition.Contains(current.mousePosition)) { - this.m_SelectedLOD = current4.m_LODLevel; + this.m_SelectedLOD = current4.LODLevel; break; } } } } - goto IL_851; + goto IL_7C2; } case EventType.MouseUp: if (GUIUtility.hotControl == controlID) @@ -804,7 +709,7 @@ orderby x.m_LODLevel } current.Use(); } - goto IL_851; + goto IL_7C2; case EventType.MouseMove: case EventType.KeyDown: case EventType.KeyUp: @@ -813,52 +718,41 @@ orderby x.m_LODLevel IL_75: if (typeForControl != EventType.DragExited) { - goto IL_851; + goto IL_7C2; } current.Use(); - goto IL_851; + goto IL_7C2; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID && this.m_SelectedLODSlider >= 0 && lods[this.m_SelectedLODSlider] != null) { current.Use(); float num2 = Mathf.Clamp01(1f - (current.mousePosition.x - sliderPosition.x) / sliderPosition.width); - this.SetSelectedLODLevelPercentage(num2 - 0.001f, lods); + LODGroupGUI.SetSelectedLODLevelPercentage(num2 - 0.001f, this.m_SelectedLODSlider, lods); + SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods[this.m_SelectedLODSlider].LODLevel)); + serializedProperty.floatValue = lods[this.m_SelectedLODSlider].RawScreenPercent; if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) { - LODGroupEditor.UpdateCamera(LODGroupEditor.LinearizeScreenPercentage(num2), lODGroup); + LODGroupEditor.UpdateCamera(LODGroupGUI.LinearizeScreenPercentage(num2), lODGroup); SceneView.RepaintAll(); } } - goto IL_851; + goto IL_7C2; case EventType.Repaint: - { - Rect rect2 = sliderPosition; - rect2.width += 2f; - rect2.height += 2f; - rect2.center -= new Vector2(1f, 1f); - LODGroupEditor.s_Styles.m_LODSliderBG.Draw(sliderPosition, GUIContent.none, false, false, false, false); - for (int i = 0; i < lods.Count; i++) - { - LODGroupEditor.LODInfo currentLOD = lods[i]; - this.DrawLODRange(currentLOD, (i != 0) ? lods[i - 1].RawScreenPercent : 1f); - LODGroupEditor.DrawLODButton(currentLOD); - } - LODGroupEditor.DrawCulledRange(sliderPosition, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].RawScreenPercent); - goto IL_851; - } + LODGroupGUI.DrawLODSlider(sliderPosition, lods, this.activeLOD); + goto IL_7C2; case EventType.DragUpdated: case EventType.DragPerform: { int num3 = -2; - foreach (LODGroupEditor.LODInfo current5 in lods) + foreach (LODGroupGUI.LODInfo current5 in lods) { if (current5.m_RangePosition.Contains(current.mousePosition)) { - num3 = current5.m_LODLevel; + num3 = current5.LODLevel; break; } } - if (num3 == -2 && LODGroupEditor.GetCulledBox(sliderPosition, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].ScreenPercent).Contains(current.mousePosition)) + if (num3 == -2 && LODGroupGUI.GetCulledBox(sliderPosition, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].ScreenPercent).Contains(current.mousePosition)) { num3 = -1; } @@ -877,17 +771,17 @@ from go in DragAndDrop.objectReferences IEnumerable renderers = this.GetRenderers(selectedGameObjects, true); if (num3 == -1) { - SerializedProperty serializedProperty = this.m_Object.FindProperty("m_LODs"); - serializedProperty.arraySize++; - SerializedProperty serializedProperty2 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count)); + SerializedProperty serializedProperty2 = this.m_Object.FindProperty("m_LODs"); + serializedProperty2.arraySize++; + SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count)); if (lods.Count == 0) { - serializedProperty2.floatValue = 0.5f; + serializedProperty3.floatValue = 0.5f; } else { - SerializedProperty serializedProperty3 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count - 1)); - serializedProperty2.floatValue = serializedProperty3.floatValue / 2f; + SerializedProperty serializedProperty4 = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods.Count - 1)); + serializedProperty3.floatValue = serializedProperty4.floatValue / 2f; } this.m_SelectedLOD = lods.Count; this.AddGameObjectRenderers(renderers, false); @@ -900,26 +794,26 @@ from go in DragAndDrop.objectReferences } } current.Use(); - goto IL_851; + goto IL_7C2; } - goto IL_851; + goto IL_7C2; } } goto IL_75; - IL_851: + IL_7C2: if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !this.m_IsPrefab) { Camera camera = SceneView.lastActiveSceneView.camera; float num4 = LODUtility.CalculateVisualizationData(camera, lODGroup, -1).activeRelativeScreenSize / QualitySettings.lodBias; - float value = LODGroupEditor.DelinearizeScreenPercentage(num4); + float value = LODGroupGUI.DelinearizeScreenPercentage(num4); Vector3 normalized = (SceneView.lastActiveSceneView.camera.transform.position - ((LODGroup)this.target).transform.position).normalized; if (Vector3.Dot(camera.transform.forward, normalized) > 0f) { value = 1f; } - Rect rect3 = LODGroupEditor.CalcLODButton(sliderPosition, Mathf.Clamp01(value)); - Rect position = new Rect(rect3.center.x - 15f, rect3.y - 25f, 32f, 32f); - Rect position2 = new Rect(rect3.center.x - 1f, rect3.y, 2f, rect3.height); + Rect rect2 = LODGroupGUI.CalcLODButton(sliderPosition, Mathf.Clamp01(value)); + Rect position = new Rect(rect2.center.x - 15f, rect2.y - 25f, 32f, 32f); + Rect position2 = new Rect(rect2.center.x - 1f, rect2.y, 2f, rect2.height); Rect position3 = new Rect(position.center.x - 5f, position2.yMax, 35f, 20f); switch (current.GetTypeForControl(controlID2)) { @@ -960,110 +854,21 @@ from go in DragAndDrop.objectReferences { Color backgroundColor = GUI.backgroundColor; GUI.backgroundColor = new Color(backgroundColor.r, backgroundColor.g, backgroundColor.b, 0.8f); - LODGroupEditor.s_Styles.m_LODCameraLine.Draw(position2, false, false, false, false); + LODGroupGUI.Styles.m_LODCameraLine.Draw(position2, false, false, false, false); GUI.backgroundColor = backgroundColor; - GUI.Label(position, LODGroupEditor.s_Styles.m_CameraIcon, GUIStyle.none); - LODGroupEditor.s_Styles.m_LODSliderText.Draw(position3, string.Format("{0:0}%", Mathf.Clamp01(num4) * 100f), false, false, false, false); + GUI.Label(position, LODGroupGUI.Styles.m_CameraIcon, GUIStyle.none); + LODGroupGUI.Styles.m_LODSliderText.Draw(position3, string.Format("{0:0}%", Mathf.Clamp01(num4) * 100f), false, false, false, false); break; } } } } - private void SetSelectedLODLevelPercentage(float newScreenPercentage, List lods) - { - IEnumerable source = - from lod in lods - where lod.m_LODLevel == lods[this.m_SelectedLODSlider].m_LODLevel + 1 - select lod; - float num = 0f; - if (source.FirstOrDefault() != null) - { - num = source.FirstOrDefault().ScreenPercent; - } - IEnumerable source2 = - from lod in lods - where lod.m_LODLevel == lods[this.m_SelectedLODSlider].m_LODLevel - 1 - select lod; - float num2 = 1f; - if (source2.FirstOrDefault() != null) - { - num2 = source2.FirstOrDefault().ScreenPercent; - } - num2 = Mathf.Clamp01(num2); - num = Mathf.Clamp01(num); - lods[this.m_SelectedLODSlider].ScreenPercent = Mathf.Clamp(newScreenPercentage, num, num2); - SerializedProperty serializedProperty = this.m_Object.FindProperty(string.Format("m_LODs.Array.data[{0}].screenRelativeHeight", lods[this.m_SelectedLODSlider].m_LODLevel)); - serializedProperty.floatValue = lods[this.m_SelectedLODSlider].RawScreenPercent; - } - private static void DrawLODButton(LODGroupEditor.LODInfo currentLOD) - { - EditorGUIUtility.AddCursorRect(currentLOD.m_ButtonPosition, MouseCursor.ResizeHorizontal); - } - private void DrawLODRange(LODGroupEditor.LODInfo currentLOD, float previousLODPercentage) - { - Color backgroundColor = GUI.backgroundColor; - string text = string.Format("LOD: {0}\n{1:0}%", currentLOD.m_LODLevel, previousLODPercentage * 100f); - if (currentLOD.m_LODLevel == this.activeLOD) - { - Rect rangePosition = currentLOD.m_RangePosition; - rangePosition.width -= 6f; - rangePosition.height -= 6f; - rangePosition.center += new Vector2(3f, 3f); - LODGroupEditor.s_Styles.m_LODSliderRangeSelected.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); - GUI.backgroundColor = LODGroupEditor.kLODColors[currentLOD.m_LODLevel]; - if (rangePosition.width > 0f) - { - LODGroupEditor.s_Styles.m_LODSliderRange.Draw(rangePosition, GUIContent.none, false, false, false, false); - } - LODGroupEditor.s_Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); - } - else - { - GUI.backgroundColor = LODGroupEditor.kLODColors[currentLOD.m_LODLevel]; - GUI.backgroundColor *= 0.6f; - LODGroupEditor.s_Styles.m_LODSliderRange.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); - LODGroupEditor.s_Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); - } - GUI.backgroundColor = backgroundColor; - } - private static Rect GetCulledBox(Rect totalRect, float previousLODPercentage) - { - Rect result = LODGroupEditor.CalcLODRange(totalRect, previousLODPercentage, 0f); - result.height -= 2f; - result.width -= 1f; - result.center += new Vector2(0f, 1f); - return result; - } - private static void DrawCulledRange(Rect totalRect, float previousLODPercentage) - { - if (Mathf.Approximately(previousLODPercentage, 0f)) - { - return; - } - Rect culledBox = LODGroupEditor.GetCulledBox(totalRect, LODGroupEditor.DelinearizeScreenPercentage(previousLODPercentage)); - Color color = GUI.color; - GUI.color = LODGroupEditor.kCulledLODColor; - LODGroupEditor.s_Styles.m_LODSliderRange.Draw(culledBox, GUIContent.none, false, false, false, false); - GUI.color = color; - string text = string.Format("Culled\n{0:0}%", previousLODPercentage * 100f); - LODGroupEditor.s_Styles.m_LODSliderText.Draw(culledBox, text, false, false, false, false); - } private static float CalculatePercentageFromBar(Rect totalRect, Vector2 clickPosition) { clickPosition.x -= totalRect.x; totalRect.x = 0f; return (totalRect.width <= 0f) ? 0f : (1f - clickPosition.x / totalRect.width); } - private static Rect CalcLODButton(Rect totalRect, float percentage) - { - return new Rect(totalRect.x + Mathf.Round(totalRect.width * (1f - percentage)) - 5f, totalRect.y, 10f, totalRect.height); - } - private static Rect CalcLODRange(Rect totalRect, float startPercent, float endPercent) - { - float num = Mathf.Round(totalRect.width * (1f - startPercent)); - float num2 = Mathf.Round(totalRect.width * (1f - endPercent)); - return new Rect(totalRect.x + num, totalRect.y, num2 - num, totalRect.height); - } private void SendPercentagesToLightmapScale() { List list = new List(); @@ -1178,19 +983,19 @@ protected void DoRenderPreview() this.m_PreviewUtility.m_Camera.transform.LookAt(bounds.center); this.m_PreviewUtility.m_Camera.nearClipPlane = 0.05f; this.m_PreviewUtility.m_Camera.farClipPlane = 1000f; - this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].intensity = 1f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); - this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + this.m_PreviewUtility.m_Light[1].intensity = 1f; Color ambient = new Color(0.2f, 0.2f, 0.2f, 0f); InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); foreach (MeshFilter current in list) { for (int j = 0; j < current.sharedMesh.subMeshCount; j++) { - if (j < current.renderer.sharedMaterials.Length) + if (j < current.GetComponent().sharedMaterials.Length) { Matrix4x4 matrix = Matrix4x4.TRS(current.transform.position, current.transform.rotation, current.transform.localScale); - this.m_PreviewUtility.DrawMesh(current.sharedMesh, matrix, current.renderer.sharedMaterials[j], j); + this.m_PreviewUtility.DrawMesh(current.sharedMesh, matrix, current.GetComponent().sharedMaterials[j], j); } } } diff --git a/UnityEditor/UnityEditor/LODGroupGUI.cs b/UnityEditor/UnityEditor/LODGroupGUI.cs new file mode 100644 index 00000000..fcc0cc00 --- /dev/null +++ b/UnityEditor/UnityEditor/LODGroupGUI.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal static class LODGroupGUI + { + public class GUIStyles + { + public readonly GUIStyle m_LODSliderBG = "LODSliderBG"; + public readonly GUIStyle m_LODSliderRange = "LODSliderRange"; + public readonly GUIStyle m_LODSliderRangeSelected = "LODSliderRangeSelected"; + public readonly GUIStyle m_LODSliderText = "LODSliderText"; + public readonly GUIStyle m_LODSliderTextSelected = "LODSliderTextSelected"; + public readonly GUIStyle m_LODStandardButton = "Button"; + public readonly GUIStyle m_LODRendererButton = "LODRendererButton"; + public readonly GUIStyle m_LODRendererAddButton = "LODRendererAddButton"; + public readonly GUIStyle m_LODRendererRemove = "LODRendererRemove"; + public readonly GUIStyle m_LODBlackBox = "LODBlackBox"; + public readonly GUIStyle m_LODCameraLine = "LODCameraLine"; + public readonly GUIStyle m_LODSceneText = "LODSceneText"; + public readonly GUIStyle m_LODRenderersText = "LODRenderersText"; + public readonly GUIStyle m_LODLevelNotifyText = "LODLevelNotifyText"; + public readonly GUIContent m_IconRendererPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add New Renderers"); + public readonly GUIContent m_IconRendererMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove Renderer"); + public readonly GUIContent m_CameraIcon = EditorGUIUtility.IconContent("Camera Icon"); + public readonly GUIContent m_UploadToImporter = new GUIContent("Upload to Importer", "Upload the modified screen percentages to the model importer."); + public readonly GUIContent m_UploadToImporterDisabled = new GUIContent("Upload to Importer", "Number of LOD's in the scene instance differ from the number of LOD's in the imported model."); + public readonly GUIContent m_RecalculateBounds = new GUIContent("Bounds", "Recalculate bounds for the current LOD group."); + public readonly GUIContent m_LightmapScale = new GUIContent("Lightmap Scale", "Set the lightmap scale to match the LOD percentages"); + public readonly GUIContent m_RendersTitle = new GUIContent("Renderers:"); + } + public class LODInfo + { + public Rect m_ButtonPosition; + public Rect m_RangePosition; + public int LODLevel + { + get; + private set; + } + public string LODName + { + get; + private set; + } + public float RawScreenPercent + { + get; + set; + } + public float ScreenPercent + { + get + { + return LODGroupGUI.DelinearizeScreenPercentage(this.RawScreenPercent); + } + set + { + this.RawScreenPercent = LODGroupGUI.LinearizeScreenPercentage(value); + } + } + public LODInfo(int lodLevel, string name, float screenPercentage) + { + this.LODLevel = lodLevel; + this.LODName = name; + this.RawScreenPercent = screenPercentage; + } + } + public const int kSceneLabelHalfWidth = 100; + public const int kSceneLabelHeight = 45; + public const int kSceneHeaderOffset = 40; + public const int kSliderBarTopMargin = 18; + public const int kSliderBarHeight = 30; + public const int kSliderBarBottomMargin = 16; + public const int kRenderersButtonHeight = 60; + public const int kButtonPadding = 2; + public const int kDeleteButtonSize = 20; + public const int kSelectedLODRangePadding = 3; + public const int kRenderAreaForegroundPadding = 3; + public static readonly Color[] kLODColors = new Color[] + { + new Color(0.4831376f, 0.6211768f, 0.0219608f, 1f), + new Color(0.279216f, 0.4078432f, 0.5835296f, 1f), + new Color(0.2070592f, 0.5333336f, 0.6556864f, 1f), + new Color(0.5333336f, 0.16f, 0.0282352f, 1f), + new Color(0.3827448f, 0.2886272f, 0.5239216f, 1f), + new Color(0.8f, 0.4423528f, 0f, 1f), + new Color(0.4486272f, 0.4078432f, 0.050196f, 1f), + new Color(0.7749016f, 0.6368624f, 0.0250984f, 1f) + }; + public static readonly Color kCulledLODColor = new Color(0.4f, 0f, 0f, 1f); + private static LODGroupGUI.GUIStyles s_Styles; + public static LODGroupGUI.GUIStyles Styles + { + get + { + if (LODGroupGUI.s_Styles == null) + { + LODGroupGUI.s_Styles = new LODGroupGUI.GUIStyles(); + } + return LODGroupGUI.s_Styles; + } + } + public static float DelinearizeScreenPercentage(float percentage) + { + if (Mathf.Approximately(0f, percentage)) + { + return 0f; + } + return Mathf.Sqrt(percentage); + } + public static float LinearizeScreenPercentage(float percentage) + { + return percentage * percentage; + } + public static Rect CalcLODButton(Rect totalRect, float percentage) + { + return new Rect(totalRect.x + Mathf.Round(totalRect.width * (1f - percentage)) - 5f, totalRect.y, 10f, totalRect.height); + } + public static Rect GetCulledBox(Rect totalRect, float previousLODPercentage) + { + Rect result = LODGroupGUI.CalcLODRange(totalRect, previousLODPercentage, 0f); + result.height -= 2f; + result.width -= 1f; + result.center += new Vector2(0f, 1f); + return result; + } + public static List CreateLODInfos(int numLODs, Rect area, Func nameGen, Func heightGen) + { + List list = new List(); + for (int i = 0; i < numLODs; i++) + { + LODGroupGUI.LODInfo lODInfo = new LODGroupGUI.LODInfo(i, nameGen(i), heightGen(i)); + lODInfo.m_ButtonPosition = LODGroupGUI.CalcLODButton(area, lODInfo.ScreenPercent); + float startPercent = (i != 0) ? list[i - 1].ScreenPercent : 1f; + lODInfo.m_RangePosition = LODGroupGUI.CalcLODRange(area, startPercent, lODInfo.ScreenPercent); + list.Add(lODInfo); + } + return list; + } + public static void SetSelectedLODLevelPercentage(float newScreenPercentage, int lod, List lods) + { + float num = 0f; + LODGroupGUI.LODInfo lODInfo = lods.FirstOrDefault((LODGroupGUI.LODInfo x) => x.LODLevel == lods[lod].LODLevel + 1); + if (lODInfo != null) + { + num = lODInfo.ScreenPercent; + } + float num2 = 1f; + LODGroupGUI.LODInfo lODInfo2 = lods.FirstOrDefault((LODGroupGUI.LODInfo x) => x.LODLevel == lods[lod].LODLevel - 1); + if (lODInfo2 != null) + { + num2 = lODInfo2.ScreenPercent; + } + num2 = Mathf.Clamp01(num2); + num = Mathf.Clamp01(num); + lods[lod].ScreenPercent = Mathf.Clamp(newScreenPercentage, num, num2); + } + public static void DrawLODSlider(Rect area, IList lods, int selectedLevel) + { + LODGroupGUI.Styles.m_LODSliderBG.Draw(area, GUIContent.none, false, false, false, false); + for (int i = 0; i < lods.Count; i++) + { + LODGroupGUI.LODInfo currentLOD = lods[i]; + LODGroupGUI.DrawLODRange(currentLOD, (i != 0) ? lods[i - 1].RawScreenPercent : 1f, i == selectedLevel); + LODGroupGUI.DrawLODButton(currentLOD); + } + LODGroupGUI.DrawCulledRange(area, (lods.Count <= 0) ? 1f : lods[lods.Count - 1].RawScreenPercent); + } + public static void DrawMixedValueLODSlider(Rect area) + { + LODGroupGUI.Styles.m_LODSliderBG.Draw(area, GUIContent.none, false, false, false, false); + Rect culledBox = LODGroupGUI.GetCulledBox(area, 1f); + Color color = GUI.color; + GUI.color = LODGroupGUI.kLODColors[1] * 0.6f; + LODGroupGUI.Styles.m_LODSliderRange.Draw(culledBox, GUIContent.none, false, false, false, false); + GUI.color = color; + GUIStyle style = new GUIStyle(EditorStyles.whiteLargeLabel) + { + alignment = TextAnchor.MiddleCenter + }; + GUI.Label(area, "---", style); + } + private static Rect CalcLODRange(Rect totalRect, float startPercent, float endPercent) + { + float num = Mathf.Round(totalRect.width * (1f - startPercent)); + float num2 = Mathf.Round(totalRect.width * (1f - endPercent)); + return new Rect(totalRect.x + num, totalRect.y, num2 - num, totalRect.height); + } + private static void DrawLODButton(LODGroupGUI.LODInfo currentLOD) + { + EditorGUIUtility.AddCursorRect(currentLOD.m_ButtonPosition, MouseCursor.ResizeHorizontal); + } + private static void DrawLODRange(LODGroupGUI.LODInfo currentLOD, float previousLODPercentage, bool isSelected) + { + Color backgroundColor = GUI.backgroundColor; + string text = string.Format("{0}\n{1:0}%", currentLOD.LODName, previousLODPercentage * 100f); + if (isSelected) + { + Rect rangePosition = currentLOD.m_RangePosition; + rangePosition.width -= 6f; + rangePosition.height -= 6f; + rangePosition.center += new Vector2(3f, 3f); + LODGroupGUI.Styles.m_LODSliderRangeSelected.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); + GUI.backgroundColor = LODGroupGUI.kLODColors[currentLOD.LODLevel]; + if (rangePosition.width > 0f) + { + LODGroupGUI.Styles.m_LODSliderRange.Draw(rangePosition, GUIContent.none, false, false, false, false); + } + LODGroupGUI.Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); + } + else + { + GUI.backgroundColor = LODGroupGUI.kLODColors[currentLOD.LODLevel]; + GUI.backgroundColor *= 0.6f; + LODGroupGUI.Styles.m_LODSliderRange.Draw(currentLOD.m_RangePosition, GUIContent.none, false, false, false, false); + LODGroupGUI.Styles.m_LODSliderText.Draw(currentLOD.m_RangePosition, text, false, false, false, false); + } + GUI.backgroundColor = backgroundColor; + } + private static void DrawCulledRange(Rect totalRect, float previousLODPercentage) + { + if (Mathf.Approximately(previousLODPercentage, 0f)) + { + return; + } + Rect culledBox = LODGroupGUI.GetCulledBox(totalRect, LODGroupGUI.DelinearizeScreenPercentage(previousLODPercentage)); + Color color = GUI.color; + GUI.color = LODGroupGUI.kCulledLODColor; + LODGroupGUI.Styles.m_LODSliderRange.Draw(culledBox, GUIContent.none, false, false, false, false); + GUI.color = color; + string text = string.Format("Culled\n{0:0}%", previousLODPercentage * 100f); + LODGroupGUI.Styles.m_LODSliderText.Draw(culledBox, text, false, false, false, false); + } + } +} diff --git a/UnityEditor/UnityEditor/LayerMatrixGUI.cs b/UnityEditor/UnityEditor/LayerMatrixGUI.cs index bb7e189c..b0fa8301 100644 --- a/UnityEditor/UnityEditor/LayerMatrixGUI.cs +++ b/UnityEditor/UnityEditor/LayerMatrixGUI.cs @@ -25,9 +25,9 @@ public static void DoGUI(string title, ref bool show, ref Vector2 scrollPos, Lay scrollPos = GUILayout.BeginScrollView(scrollPos, new GUILayoutOption[] { GUILayout.MinHeight(120f), - GUILayout.MaxHeight((float)(100 + (num + 1) * 15)) + GUILayout.MaxHeight((float)(100 + (num + 1) * 16)) }); - Rect rect = GUILayoutUtility.GetRect((float)(15 * num + 100), 100f); + Rect rect = GUILayoutUtility.GetRect((float)(16 * num + 100), 100f); Rect topmostRect = GUIClip.topmostRect; Vector2 vector = GUIClip.Unclip(new Vector2(rect.x, rect.y)); int num2 = 0; @@ -35,18 +35,18 @@ public static void DoGUI(string title, ref bool show, ref Vector2 scrollPos, Lay { if (LayerMask.LayerToName(j) != string.Empty) { - float num3 = (float)(130 + (num - num2) * 15) - (topmostRect.width + scrollPos.x); + float num3 = (float)(130 + (num - num2) * 16) - (topmostRect.width + scrollPos.x); if (num3 < 0f) { num3 = 0f; } - Vector3 pos = new Vector3((float)(130 + 15 * (num - num2)) + vector.y + vector.x + scrollPos.y - num3, vector.y + scrollPos.y, 0f); + Vector3 pos = new Vector3((float)(130 + 16 * (num - num2)) + vector.y + vector.x + scrollPos.y - num3, vector.y + scrollPos.y, 0f); GUI.matrix = Matrix4x4.TRS(pos, Quaternion.identity, Vector3.one) * Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, 90f), Vector3.one); if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9.0")) { GUI.matrix *= Matrix4x4.TRS(new Vector3(-0.5f, -0.5f, 0f), Quaternion.identity, Vector3.one); } - GUI.Label(new Rect(2f - vector.x - scrollPos.y, scrollPos.y - num3, 100f, 15f), LayerMask.LayerToName(j), "RightLabel"); + GUI.Label(new Rect(2f - vector.x - scrollPos.y, scrollPos.y - num3, 100f, 16f), LayerMask.LayerToName(j), "RightLabel"); num2++; } } @@ -57,8 +57,8 @@ public static void DoGUI(string title, ref bool show, ref Vector2 scrollPos, Lay if (LayerMask.LayerToName(k) != string.Empty) { int num4 = 0; - Rect rect2 = GUILayoutUtility.GetRect((float)(30 + 15 * num + 100), 15f); - GUI.Label(new Rect(rect2.x + 30f, rect2.y, 100f, 15f), LayerMask.LayerToName(k), "RightLabel"); + Rect rect2 = GUILayoutUtility.GetRect((float)(30 + 16 * num + 100), 16f); + GUI.Label(new Rect(rect2.x + 30f, rect2.y, 100f, 16f), LayerMask.LayerToName(k), "RightLabel"); for (int l = 31; l >= 0; l--) { if (LayerMask.LayerToName(l) != string.Empty) @@ -67,7 +67,7 @@ public static void DoGUI(string title, ref bool show, ref Vector2 scrollPos, Lay { GUIContent content = new GUIContent(string.Empty, LayerMask.LayerToName(k) + "/" + LayerMask.LayerToName(l)); bool flag = getValue(k, l); - bool flag2 = GUI.Toggle(new Rect(130f + rect2.x + (float)(num4 * 15), rect2.y, 15f, 15f), flag, content); + bool flag2 = GUI.Toggle(new Rect(130f + rect2.x + (float)(num4 * 16), rect2.y, 16f, 16f), flag, content); if (flag2 != flag) { setValue(k, l, flag2); diff --git a/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs b/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs index ec0fdf66..fb4b8912 100644 --- a/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs +++ b/UnityEditor/UnityEditor/LazyTreeViewDataSource.cs @@ -9,13 +9,24 @@ internal abstract class LazyTreeViewDataSource : TreeViewDataSource public LazyTreeViewDataSource(TreeView treeView) : base(treeView) { } + public static List CreateChildListForCollapsedParent() + { + return new List + { + null + }; + } + public static bool IsChildListForACollapsedParent(List childList) + { + return childList != null && childList.Count == 1 && childList[0] == null; + } protected abstract HashSet GetParentsAbove(int id); protected abstract HashSet GetParentsBelow(int id); - public override TreeViewItem FindItem(int id) + protected virtual void RevealItem(int itemID) { HashSet hashSet = new HashSet(base.expandedIDs); int count = hashSet.Count; - HashSet parentsAbove = this.GetParentsAbove(id); + HashSet parentsAbove = this.GetParentsAbove(itemID); hashSet.UnionWith(parentsAbove); if (count != hashSet.Count) { @@ -25,7 +36,11 @@ public override TreeViewItem FindItem(int id) this.FetchData(); } } - return base.FindItem(id); + } + public override TreeViewItem FindItem(int itemID) + { + this.RevealItem(itemID); + return base.FindItem(itemID); } public override void SetExpandedWithChildren(TreeViewItem item, bool expand) { @@ -56,6 +71,10 @@ public override List GetVisibleRows() { this.FetchData(); this.m_NeedRefreshVisibleFolders = false; + if (this.onVisibleRowsChanged != null) + { + this.onVisibleRowsChanged(); + } this.m_TreeView.Repaint(); } return this.m_VisibleRows; diff --git a/UnityEditor/UnityEditor/LegacyIlluminShaderGUI.cs b/UnityEditor/UnityEditor/LegacyIlluminShaderGUI.cs new file mode 100644 index 00000000..0bef512f --- /dev/null +++ b/UnityEditor/UnityEditor/LegacyIlluminShaderGUI.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class LegacyIlluminShaderGUI : ShaderGUI + { + public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) + { + base.OnGUI(materialEditor, props); + materialEditor.LightmapEmissionProperty(0); + UnityEngine.Object[] targets = materialEditor.targets; + for (int i = 0; i < targets.Length; i++) + { + Material material = (Material)targets[i]; + material.globalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; + } + } + } +} diff --git a/UnityEditor/UnityEditor/LicenseManagementWindow.cs b/UnityEditor/UnityEditor/LicenseManagementWindow.cs index 28ca1d3f..2587baab 100644 --- a/UnityEditor/UnityEditor/LicenseManagementWindow.cs +++ b/UnityEditor/UnityEditor/LicenseManagementWindow.cs @@ -26,6 +26,18 @@ private static LicenseManagementWindow Window return LicenseManagementWindow.win; } } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CheckForUpdates(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ActivateNewLicense(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ManualActivation(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ReturnLicense(); private static void ShowWindow() { Resolution currentResolution = Screen.currentResolution; @@ -104,17 +116,5 @@ private void OnGUI() GUILayout.FlexibleSpace(); GUILayout.EndArea(); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CheckForUpdates(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ActivateNewLicense(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ManualActivation(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ReturnLicense(); } } diff --git a/UnityEditor/UnityEditor/LightEditor.cs b/UnityEditor/UnityEditor/LightEditor.cs index 3899d833..4d9c689f 100644 --- a/UnityEditor/UnityEditor/LightEditor.cs +++ b/UnityEditor/UnityEditor/LightEditor.cs @@ -8,19 +8,40 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(Light))] internal class LightEditor : Editor { + private class Styles + { + public readonly GUIContent LightBounceIntensity = EditorGUIUtility.TextContent("LightmapEditor.Light.BounceIntensity"); + public readonly GUIContent ShadowType = new GUIContent("Shadow Type", "Shadow cast options"); + public readonly GUIContent BakedShadowRadius = new GUIContent("Baked Shadow Radius"); + public readonly GUIContent BakedShadowAngle = new GUIContent("Baked Shadow Angle"); + public readonly string NoShadowsWarning = EditorGUIUtility.TextContent("LightEditor.NoShadowsWarning").text; + public readonly GUIContent LightmappingModeLabel = new GUIContent("Baking"); + public readonly GUIContent[] LightmappingModes = new GUIContent[] + { + new GUIContent("Realtime"), + new GUIContent("Baked"), + new GUIContent("Mixed") + }; + public readonly int[] LightmappingModeValues = new int[] + { + 4, + 2, + 1 + }; + } private SerializedProperty m_Type; private SerializedProperty m_Range; private SerializedProperty m_SpotAngle; private SerializedProperty m_CookieSize; private SerializedProperty m_Color; private SerializedProperty m_Intensity; + private SerializedProperty m_BounceIntensity; private SerializedProperty m_Cookie; private SerializedProperty m_ShadowsType; private SerializedProperty m_ShadowsStrength; private SerializedProperty m_ShadowsResolution; private SerializedProperty m_ShadowsBias; - private SerializedProperty m_ShadowsSoftness; - private SerializedProperty m_ShadowsSoftnessFade; + private SerializedProperty m_ShadowsNormalBias; private SerializedProperty m_Halo; private SerializedProperty m_Flare; private SerializedProperty m_RenderMode; @@ -28,16 +49,21 @@ internal class LightEditor : Editor private SerializedProperty m_Lightmapping; private SerializedProperty m_AreaSizeX; private SerializedProperty m_AreaSizeY; + private SerializedProperty m_BakedShadowRadius; + private SerializedProperty m_BakedShadowAngle; private AnimBool m_ShowSpotOptions = new AnimBool(); private AnimBool m_ShowPointOptions = new AnimBool(); - private AnimBool m_ShowSoftOptions = new AnimBool(); private AnimBool m_ShowDirOptions = new AnimBool(); private AnimBool m_ShowAreaOptions = new AnimBool(); + private AnimBool m_ShowRuntimeOptions = new AnimBool(); private AnimBool m_ShowShadowOptions = new AnimBool(); private AnimBool m_ShowShadowWarning = new AnimBool(); - private AnimBool m_ShowForwardShadowsWarning = new AnimBool(); private AnimBool m_ShowAreaWarning = new AnimBool(); - private bool m_UsingDeferred; + private AnimBool m_ShowIndirectWarning = new AnimBool(); + private AnimBool m_ShowBakingWarning = new AnimBool(); + private AnimBool m_BakedShadowAngleOptions = new AnimBool(); + private AnimBool m_BakedShadowRadiusOptions = new AnimBool(); + private static LightEditor.Styles s_Styles; internal static Color kGizmoLight = new Color(0.996078432f, 0.992156863f, 0.533333361f, 0.5019608f); internal static Color kGizmoDisabledLight = new Color(0.5294118f, 0.454901963f, 0.196078435f, 0.5019608f); private bool typeIsSame @@ -61,25 +87,25 @@ private Light light return this.target as Light; } } - private bool spotOptionsValue + private bool isBakedOrMixed { get { - return this.typeIsSame && this.light.type == LightType.Spot; + return this.m_Lightmapping.intValue != 4; } } - private bool pointOptionsValue + private bool spotOptionsValue { get { - return this.typeIsSame && this.light.type == LightType.Point; + return this.typeIsSame && this.light.type == LightType.Spot; } } - private bool softOptionsValue + private bool pointOptionsValue { get { - return this.shadowTypeIsSame && this.typeIsSame && this.light.shadows == LightShadows.Soft && this.light.type == LightType.Directional; + return this.typeIsSame && this.light.type == LightType.Point; } } private bool dirOptionsValue @@ -96,6 +122,27 @@ private bool areaOptionsValue return this.typeIsSame && this.light.type == LightType.Area; } } + private bool runtimeOptionsValue + { + get + { + return this.typeIsSame && this.light.type != LightType.Area && this.m_Lightmapping.intValue != 2; + } + } + private bool bakedShadowRadius + { + get + { + return this.typeIsSame && (this.light.type == LightType.Point || this.light.type == LightType.Spot) && this.isBakedOrMixed; + } + } + private bool bakedShadowAngle + { + get + { + return this.typeIsSame && this.light.type == LightType.Directional && this.isBakedOrMixed; + } + } private bool shadowOptionsValue { get @@ -107,55 +154,56 @@ private bool shadowWarningValue { get { - return this.typeIsSame && !InternalEditorUtility.HasPro() && this.light.type != LightType.Directional; + return this.typeIsSame && !InternalEditorUtility.HasProFeaturesEnabled() && this.light.type != LightType.Directional; } } - private bool forwardWarningValue + private bool areaWarningValue { get { - return this.typeIsSame && !this.m_UsingDeferred && this.light.type != LightType.Directional; + return this.typeIsSame && !InternalEditorUtility.HasProFeaturesEnabled() && this.light.type == LightType.Area; } } - private bool areaWarningValue + private bool bounceWarningValue { get { - return this.typeIsSame && !InternalEditorUtility.HasPro() && this.light.type == LightType.Area; + return this.typeIsSame && InternalEditorUtility.HasProFeaturesEnabled() && (this.light.type == LightType.Point || this.light.type == LightType.Spot) && this.m_Lightmapping.intValue == 4 && this.m_BounceIntensity.floatValue > 0f; } } - private void InitShowOptions() + private bool bakingWarningValue { - this.m_ShowSpotOptions.value = this.spotOptionsValue; - this.m_ShowPointOptions.value = this.pointOptionsValue; - this.m_ShowSoftOptions.value = this.softOptionsValue; - this.m_ShowDirOptions.value = this.dirOptionsValue; - this.m_ShowAreaOptions.value = this.areaOptionsValue; - this.m_ShowShadowOptions.value = this.shadowOptionsValue; - this.m_ShowShadowWarning.value = this.shadowWarningValue; - this.m_ShowForwardShadowsWarning.value = this.forwardWarningValue; - this.m_ShowAreaWarning.value = this.areaWarningValue; - this.m_ShowSpotOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowPointOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowDirOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowAreaOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowShadowOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowShadowWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowForwardShadowsWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowSoftOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowAreaWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); + get + { + return !Lightmapping.bakedLightmapsEnabled && this.isBakedOrMixed; + } } - private void UpdateShowOptions() + private void SetOptions(AnimBool animBool, bool initialize, bool targetValue) { - this.m_ShowSpotOptions.target = this.spotOptionsValue; - this.m_ShowPointOptions.target = this.pointOptionsValue; - this.m_ShowSoftOptions.target = this.softOptionsValue; - this.m_ShowDirOptions.target = this.dirOptionsValue; - this.m_ShowAreaOptions.target = this.areaOptionsValue; - this.m_ShowShadowOptions.target = this.shadowOptionsValue; - this.m_ShowShadowWarning.target = this.shadowWarningValue; - this.m_ShowForwardShadowsWarning.target = this.forwardWarningValue; - this.m_ShowAreaWarning.target = this.areaWarningValue; + if (initialize) + { + animBool.value = targetValue; + animBool.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + else + { + animBool.target = targetValue; + } + } + private void UpdateShowOptions(bool initialize) + { + this.SetOptions(this.m_ShowSpotOptions, initialize, this.spotOptionsValue); + this.SetOptions(this.m_ShowPointOptions, initialize, this.pointOptionsValue); + this.SetOptions(this.m_ShowDirOptions, initialize, this.dirOptionsValue); + this.SetOptions(this.m_ShowAreaOptions, initialize, this.areaOptionsValue); + this.SetOptions(this.m_ShowShadowOptions, initialize, this.shadowOptionsValue); + this.SetOptions(this.m_ShowShadowWarning, initialize, this.shadowWarningValue); + this.SetOptions(this.m_ShowAreaWarning, initialize, this.areaWarningValue); + this.SetOptions(this.m_ShowIndirectWarning, initialize, this.bounceWarningValue); + this.SetOptions(this.m_ShowBakingWarning, initialize, this.bakingWarningValue); + this.SetOptions(this.m_ShowRuntimeOptions, initialize, this.runtimeOptionsValue); + this.SetOptions(this.m_BakedShadowAngleOptions, initialize, this.bakedShadowAngle); + this.SetOptions(this.m_BakedShadowRadiusOptions, initialize, this.bakedShadowRadius); } private void OnEnable() { @@ -165,13 +213,13 @@ private void OnEnable() this.m_CookieSize = base.serializedObject.FindProperty("m_CookieSize"); this.m_Color = base.serializedObject.FindProperty("m_Color"); this.m_Intensity = base.serializedObject.FindProperty("m_Intensity"); + this.m_BounceIntensity = base.serializedObject.FindProperty("m_BounceIntensity"); this.m_Cookie = base.serializedObject.FindProperty("m_Cookie"); this.m_ShadowsType = base.serializedObject.FindProperty("m_Shadows.m_Type"); this.m_ShadowsStrength = base.serializedObject.FindProperty("m_Shadows.m_Strength"); this.m_ShadowsResolution = base.serializedObject.FindProperty("m_Shadows.m_Resolution"); this.m_ShadowsBias = base.serializedObject.FindProperty("m_Shadows.m_Bias"); - this.m_ShadowsSoftness = base.serializedObject.FindProperty("m_Shadows.m_Softness"); - this.m_ShadowsSoftnessFade = base.serializedObject.FindProperty("m_Shadows.m_SoftnessFade"); + this.m_ShadowsNormalBias = base.serializedObject.FindProperty("m_Shadows.m_NormalBias"); this.m_Halo = base.serializedObject.FindProperty("m_DrawHalo"); this.m_Flare = base.serializedObject.FindProperty("m_Flare"); this.m_RenderMode = base.serializedObject.FindProperty("m_RenderMode"); @@ -179,20 +227,37 @@ private void OnEnable() this.m_Lightmapping = base.serializedObject.FindProperty("m_Lightmapping"); this.m_AreaSizeX = base.serializedObject.FindProperty("m_AreaSize.x"); this.m_AreaSizeY = base.serializedObject.FindProperty("m_AreaSize.y"); - this.InitShowOptions(); - this.m_UsingDeferred = CameraUtility.DoesAnyCameraUseDeferred(); + this.m_BakedShadowRadius = base.serializedObject.FindProperty("m_ShadowRadius"); + this.m_BakedShadowAngle = base.serializedObject.FindProperty("m_ShadowAngle"); + this.UpdateShowOptions(true); } public override void OnInspectorGUI() { + if (LightEditor.s_Styles == null) + { + LightEditor.s_Styles = new LightEditor.Styles(); + } base.serializedObject.Update(); - this.UpdateShowOptions(); + this.UpdateShowOptions(false); EditorGUILayout.PropertyField(this.m_Type, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowAreaOptions.faded)) + { + EditorGUILayout.IntPopup(this.m_Lightmapping, LightEditor.s_Styles.LightmappingModes, LightEditor.s_Styles.LightmappingModeValues, LightEditor.s_Styles.LightmappingModeLabel, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBakingWarning.faded)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("LightEditor.GIBakingDisabledWarning"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Space(); bool flag = this.m_ShowDirOptions.isAnimating && this.m_ShowAreaOptions.isAnimating && (this.m_ShowDirOptions.target || this.m_ShowAreaOptions.target); float value = (!flag) ? (1f - Mathf.Max(this.m_ShowDirOptions.faded, this.m_ShowAreaOptions.faded)) : 0f; if (EditorGUILayout.BeginFadeGroup(this.m_ShowAreaWarning.faded)) { - GUIContent gUIContent = EditorGUIUtility.TextContent("LightEditor.AreaLightsProOnly"); - EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + GUIContent gUIContent2 = EditorGUIUtility.TextContent("LightEditor.AreaLightsProOnly"); + EditorGUILayout.HelpBox(gUIContent2.text, MessageType.Warning, false); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(value)) @@ -205,67 +270,82 @@ public override void OnInspectorGUI() EditorGUILayout.Slider(this.m_SpotAngle, 1f, 179f, new GUILayoutOption[0]); } EditorGUILayout.EndFadeGroup(); - EditorGUILayout.Space(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowAreaOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_AreaSizeX, new GUIContent("Width"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AreaSizeY, new GUIContent("Height"), new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); EditorGUILayout.PropertyField(this.m_Color, new GUILayoutOption[0]); EditorGUILayout.Slider(this.m_Intensity, 0f, 8f, new GUILayoutOption[0]); - if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowAreaOptions.faded)) + EditorGUILayout.Slider(this.m_BounceIntensity, 0f, 8f, LightEditor.s_Styles.LightBounceIntensity, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowIndirectWarning.faded)) + { + GUIContent gUIContent3 = EditorGUIUtility.TextContent("LightEditor.NoIndirectShadowsWarnings"); + EditorGUILayout.HelpBox(gUIContent3.text, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + this.ShadowsGUI(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowRuntimeOptions.faded)) { EditorGUILayout.PropertyField(this.m_Cookie, new GUILayoutOption[0]); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowDirOptions.faded)) - { - EditorGUILayout.PropertyField(this.m_CookieSize, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - EditorGUILayout.Space(); - EditorGUILayout.PropertyField(this.m_ShadowsType, new GUIContent("Shadow Type", "Shadow cast options"), new GUILayoutOption[0]); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowOptions.faded)) - { - EditorGUI.indentLevel++; - if (EditorGUILayout.BeginFadeGroup(this.m_ShowForwardShadowsWarning.faded)) - { - GUIContent gUIContent2 = EditorGUIUtility.TextContent("LightEditor.ForwardRenderingShadowsWarning"); - EditorGUILayout.HelpBox(gUIContent2.text, MessageType.Warning, false); - } - EditorGUILayout.EndFadeGroup(); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowWarning.faded)) - { - GUIContent gUIContent3 = EditorGUIUtility.TextContent("LightEditor.NoShadowsWarning"); - EditorGUILayout.HelpBox(gUIContent3.text, MessageType.Warning, false); - } - EditorGUILayout.EndFadeGroup(); - if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowShadowWarning.faded)) - { - EditorGUILayout.Slider(this.m_ShadowsStrength, 0f, 1f, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_ShadowsResolution, new GUILayoutOption[0]); - EditorGUILayout.Slider(this.m_ShadowsBias, 0f, 2f, new GUILayoutOption[0]); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowSoftOptions.faded)) - { - EditorGUILayout.Slider(this.m_ShadowsSoftness, 1f, 8f, new GUILayoutOption[0]); - EditorGUILayout.Slider(this.m_ShadowsSoftnessFade, 0.1f, 5f, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - } - EditorGUILayout.EndFadeGroup(); - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - EditorGUILayout.Space(); - EditorGUILayout.PropertyField(this.m_Halo, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Flare, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_RenderMode, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Lightmapping, new GUILayoutOption[0]); } EditorGUILayout.EndFadeGroup(); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowAreaOptions.faded)) + if (EditorGUILayout.BeginFadeGroup(this.m_ShowRuntimeOptions.faded * this.m_ShowDirOptions.faded)) { - EditorGUILayout.PropertyField(this.m_AreaSizeX, new GUIContent("Width"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_AreaSizeY, new GUIContent("Height"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CookieSize, new GUILayoutOption[0]); } EditorGUILayout.EndFadeGroup(); + EditorGUILayout.PropertyField(this.m_Halo, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Flare, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_RenderMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]); EditorGUILayout.Space(); + if (SceneView.currentDrawingSceneView != null && !SceneView.currentDrawingSceneView.m_SceneLighting) + { + GUIContent gUIContent4 = EditorGUIUtility.TextContent("LightEditor.LightingDisabledInSceneViewWarning"); + EditorGUILayout.HelpBox(gUIContent4.text, MessageType.Warning, false); + } base.serializedObject.ApplyModifiedProperties(); } + private void ShadowsGUI() + { + float num = 1f - this.m_ShowAreaOptions.faded; + if (EditorGUILayout.BeginFadeGroup(num)) + { + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_ShadowsType, LightEditor.s_Styles.ShadowType, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel++; + num *= this.m_ShowShadowOptions.faded; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowWarning.faded * num)) + { + EditorGUILayout.HelpBox(LightEditor.s_Styles.NoShadowsWarning, MessageType.Warning, false); + } + EditorGUILayout.EndFadeGroup(); + num *= 1f - this.m_ShowShadowWarning.faded; + if (EditorGUILayout.BeginFadeGroup(num * this.m_ShowRuntimeOptions.faded)) + { + EditorGUILayout.Slider(this.m_ShadowsStrength, 0f, 1f, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ShadowsResolution, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ShadowsBias, 0f, 2f, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ShadowsNormalBias, 0f, 3f, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(num * this.m_BakedShadowRadiusOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_BakedShadowRadius, LightEditor.s_Styles.BakedShadowRadius, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(num * this.m_BakedShadowAngleOptions.faded)) + { + EditorGUILayout.Slider(this.m_BakedShadowAngle, 0f, 90f, LightEditor.s_Styles.BakedShadowAngle, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + } private void OnSceneGUI() { Light light = (Light)this.target; diff --git a/UnityEditor/UnityEditor/LightProbeGUI.cs b/UnityEditor/UnityEditor/LightProbeGUI.cs index 758ec566..43b802a7 100644 --- a/UnityEditor/UnityEditor/LightProbeGUI.cs +++ b/UnityEditor/UnityEditor/LightProbeGUI.cs @@ -4,12 +4,12 @@ namespace UnityEditor { internal class LightProbeGUI { - private const int kLightProbeCoefficientCount = 27; - private const float kDuplicateEpsilonSq = 0.1f; public void DisplayControls(SceneView sceneView) { LightmapVisualization.showLightProbeLocations = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.ShowProbes"), LightmapVisualization.showLightProbeLocations, new GUILayoutOption[0]); + EditorGUI.indentLevel++; LightmapVisualization.showLightProbeCells = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.ShowCells"), LightmapVisualization.showLightProbeCells, new GUILayoutOption[0]); + EditorGUI.indentLevel--; } } } diff --git a/UnityEditor/UnityEditor/LightProbeGroupEditor.cs b/UnityEditor/UnityEditor/LightProbeGroupEditor.cs index a6e5d8de..789b97c1 100644 --- a/UnityEditor/UnityEditor/LightProbeGroupEditor.cs +++ b/UnityEditor/UnityEditor/LightProbeGroupEditor.cs @@ -8,8 +8,6 @@ namespace UnityEditor { internal class LightProbeGroupEditor : IEditablePoint { - private const int kLightProbeCoefficientCount = 27; - private const float kDuplicateEpsilonSq = 0.1f; private bool m_Editing; private List m_SourcePositions; private List m_Selection = new List(); @@ -268,7 +266,6 @@ public void PushProbePositions() { this.m_Group.probePositions = this.m_SourcePositions.ToArray(); this.m_SerializedSelectedProbes.m_Selection = this.m_Selection; - LightmappingWindow.ProbePositionsChanged(); } } private void DrawTetrahedra() @@ -283,6 +280,54 @@ private void DrawTetrahedra() this.m_ShouldRecalculateTetrahedra = false; } } + public void HandleEditMenuHotKeyCommands() + { + if (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand) + { + bool flag = Event.current.type == EventType.ExecuteCommand; + string commandName = Event.current.commandName; + switch (commandName) + { + case "SoftDelete": + case "Delete": + if (flag) + { + this.RemoveSelectedProbes(); + } + Event.current.Use(); + break; + case "Duplicate": + if (flag) + { + this.DuplicateSelectedProbes(); + } + Event.current.Use(); + break; + case "SelectAll": + if (flag) + { + this.SelectAllProbes(); + } + Event.current.Use(); + break; + case "Cut": + if (flag) + { + this.CopySelectedProbes(); + this.RemoveSelectedProbes(); + } + Event.current.Use(); + break; + case "Copy": + if (flag) + { + this.CopySelectedProbes(); + } + Event.current.Use(); + break; + } + } + } public static void TetrahedralizeSceneProbes(out Vector3[] positions, out int[] indices) { LightProbeGroup[] array = UnityEngine.Object.FindObjectsOfType(typeof(LightProbeGroup)) as LightProbeGroup[]; @@ -369,51 +414,7 @@ public bool OnSceneGUI(Transform transform) { return this.m_Editing; } - if (Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand) - { - bool flag3 = Event.current.type == EventType.ExecuteCommand; - string commandName = Event.current.commandName; - switch (commandName) - { - case "SoftDelete": - case "Delete": - if (flag3) - { - this.RemoveSelectedProbes(); - } - Event.current.Use(); - break; - case "Duplicate": - if (flag3) - { - this.DuplicateSelectedProbes(); - } - Event.current.Use(); - break; - case "SelectAll": - if (flag3) - { - this.SelectAllProbes(); - } - Event.current.Use(); - break; - case "Cut": - if (flag3) - { - this.CopySelectedProbes(); - this.RemoveSelectedProbes(); - } - Event.current.Use(); - break; - case "Copy": - if (flag3) - { - this.CopySelectedProbes(); - } - Event.current.Use(); - break; - } - } + this.HandleEditMenuHotKeyCommands(); if (this.m_Editing && PointEditor.MovePoints(this, transform, this.m_Selection)) { Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] @@ -473,6 +474,14 @@ public Vector3[] GetSelectedPositions() } return array; } + public void UpdateSelectedPosition(int idx, Vector3 position) + { + if (idx > this.SelectedCount - 1) + { + return; + } + this.m_SourcePositions[this.m_Selection[idx]] = position; + } public IEnumerable GetPositions() { return this.m_SourcePositions; diff --git a/UnityEditor/UnityEditor/LightProbeGroupInspector.cs b/UnityEditor/UnityEditor/LightProbeGroupInspector.cs index f95fd165..cb1c1107 100644 --- a/UnityEditor/UnityEditor/LightProbeGroupInspector.cs +++ b/UnityEditor/UnityEditor/LightProbeGroupInspector.cs @@ -50,6 +50,7 @@ public void OnDisable() } private void UndoRedoPerformed() { + this.m_Editor.PullProbePositions(); this.m_Editor.MarkTetrahedraDirty(); } public override void OnInspectorGUI() @@ -94,6 +95,18 @@ public override void OnInspectorGUI() } GUILayout.EndVertical(); GUILayout.EndHorizontal(); + if (this.m_Editor.SelectedCount == 1) + { + Vector3 vector = this.m_Editor.GetSelectedPositions()[0]; + GUIContent label = new GUIContent("Probe Position", "The local position of this probe relative to the parent group."); + Vector3 vector2 = EditorGUILayout.Vector3Field(label, vector, new GUILayoutOption[0]); + if (vector2 != vector) + { + this.StartEditProbes(); + this.m_Editor.UpdateSelectedPosition(0, vector2); + } + } + this.m_Editor.HandleEditMenuHotKeyCommands(); this.m_Editor.PushProbePositions(); EditorGUI.EndDisabledGroup(); if (!flag) @@ -104,6 +117,10 @@ public override void OnInspectorGUI() } private void InternalOnSceneView() { + if (!EditorGUIUtility.IsGizmosAllowedForObject(this.target)) + { + return; + } if (SceneView.lastActiveSceneView != null && this.m_ShouldFocus) { this.m_ShouldFocus = false; diff --git a/UnityEditor/UnityEditor/LightingEditor.cs b/UnityEditor/UnityEditor/LightingEditor.cs new file mode 100644 index 00000000..86cfc4d4 --- /dev/null +++ b/UnityEditor/UnityEditor/LightingEditor.cs @@ -0,0 +1,161 @@ +using System; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(RenderSettings))] + internal class LightingEditor : Editor + { + internal class Styles + { + public static readonly GUIContent environmentHeader = EditorGUIUtility.TextContent("RenderSettings.EnvironmentHeader"); + public static readonly GUIContent sunLabel = EditorGUIUtility.TextContent("RenderSettings.SunLabel"); + public static readonly GUIContent skyboxLabel = EditorGUIUtility.TextContent("RenderSettings.SkyboxLabel"); + public static readonly GUIContent ambientIntensity = EditorGUIUtility.TextContent("RenderSettings.AmbientIntensity"); + public static readonly GUIContent reflectionIntensity = EditorGUIUtility.TextContent("RenderSettings.ReflectionIntensity"); + public static readonly GUIContent reflectionBounces = EditorGUIUtility.TextContent("RenderSettings.ReflectionBounces"); + public static readonly GUIContent skyboxWarning = EditorGUIUtility.TextContent("RenderSettings.SkyboxWarning"); + public static readonly GUIContent createLight = EditorGUIUtility.TextContent("RenderSettings.CreateLight"); + public static readonly GUIContent ambientModeLabel = EditorGUIUtility.TextContent("RenderSettings.AmbientModeLabel"); + public static readonly GUIContent ambientUp = EditorGUIUtility.TextContent("RenderSettings.AmbientUp"); + public static readonly GUIContent ambientMid = EditorGUIUtility.TextContent("RenderSettings.AmbientMid"); + public static readonly GUIContent ambientDown = EditorGUIUtility.TextContent("RenderSettings.AmbientDown"); + public static readonly GUIContent ambient = EditorGUIUtility.TextContent("RenderSettings.Ambient"); + public static readonly GUIContent reflectionModeLabel = EditorGUIUtility.TextContent("RenderSettings.ReflectionModeLabel"); + public static readonly GUIContent customReflection = EditorGUIUtility.TextContent("RenderSettings.CustomReflection"); + public static readonly GUIContent skyLightColor = EditorGUIUtility.TextContent("LightmapEditor.SkyLightColor"); + public static readonly GUIContent skyboxTint = EditorGUIUtility.TextContent("LightmapEditor.SkyboxTint"); + public static readonly GUIContent SkyLightBaked = EditorGUIUtility.TextContent("LightmapEditor.SkyLightBaked"); + public static readonly GUIContent defaultReflectionResolution = EditorGUIUtility.TextContent("RenderSettings.DefaultReflectionResolution"); + public static int[] defaultReflectionSizesValues = new int[] + { + 128, + 256, + 512, + 1024 + }; + public static GUIContent[] defaultReflectionSizes = ( + from n in LightingEditor.Styles.defaultReflectionSizesValues + select new GUIContent(n.ToString())).ToArray(); + } + private const string kShowLightingEditorKey = "ShowLightingEditor"; + private static readonly GUIContent[] kFullAmbientModes = new GUIContent[] + { + EditorGUIUtility.TextContent("RenderSettings.AmbientMode.Skybox"), + EditorGUIUtility.TextContent("RenderSettings.AmbientMode.Gradient"), + EditorGUIUtility.TextContent("RenderSettings.AmbientMode.Color") + }; + private static readonly int[] kFullAmbientModeValues = new int[] + { + 0, + 1, + 3 + }; + protected SerializedProperty m_Sun; + protected SerializedProperty m_AmbientMode; + protected SerializedProperty m_AmbientSkyColor; + protected SerializedProperty m_AmbientEquatorColor; + protected SerializedProperty m_AmbientGroundColor; + protected SerializedProperty m_AmbientIntensity; + protected SerializedProperty m_ReflectionIntensity; + protected SerializedProperty m_ReflectionBounces; + protected SerializedProperty m_SkyboxMaterial; + protected SerializedProperty m_DefaultReflectionMode; + protected SerializedProperty m_DefaultReflectionResolution; + protected SerializedProperty m_CustomReflection; + protected SerializedObject m_lightmapSettings; + protected SerializedProperty m_EnvironmentLightingMode; + private bool m_ShowEditor; + public virtual void OnEnable() + { + this.m_Sun = base.serializedObject.FindProperty("m_Sun"); + this.m_AmbientMode = base.serializedObject.FindProperty("m_AmbientMode"); + this.m_AmbientSkyColor = base.serializedObject.FindProperty("m_AmbientSkyColor"); + this.m_AmbientEquatorColor = base.serializedObject.FindProperty("m_AmbientEquatorColor"); + this.m_AmbientGroundColor = base.serializedObject.FindProperty("m_AmbientGroundColor"); + this.m_AmbientIntensity = base.serializedObject.FindProperty("m_AmbientIntensity"); + this.m_ReflectionIntensity = base.serializedObject.FindProperty("m_ReflectionIntensity"); + this.m_ReflectionBounces = base.serializedObject.FindProperty("m_ReflectionBounces"); + this.m_SkyboxMaterial = base.serializedObject.FindProperty("m_SkyboxMaterial"); + this.m_DefaultReflectionMode = base.serializedObject.FindProperty("m_DefaultReflectionMode"); + this.m_DefaultReflectionResolution = base.serializedObject.FindProperty("m_DefaultReflectionResolution"); + this.m_CustomReflection = base.serializedObject.FindProperty("m_CustomReflection"); + this.m_lightmapSettings = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + this.m_EnvironmentLightingMode = this.m_lightmapSettings.FindProperty("m_GISettings.m_EnvironmentLightingMode"); + this.m_ShowEditor = InspectorState.GetBool("ShowLightingEditor", true); + } + public virtual void OnDisable() + { + InspectorState.SetBool("ShowLightingEditor", this.m_ShowEditor); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + this.m_lightmapSettings.Update(); + EditorGUILayout.Space(); + this.m_ShowEditor = EditorGUILayout.FoldoutTitlebar(this.m_ShowEditor, LightingEditor.Styles.environmentHeader); + if (!this.m_ShowEditor) + { + return; + } + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_SkyboxMaterial, LightingEditor.Styles.skyboxLabel, new GUILayoutOption[0]); + Material material = this.m_SkyboxMaterial.objectReferenceValue as Material; + if (material && !EditorMaterialUtility.IsBackgroundMaterial(material)) + { + EditorGUILayout.HelpBox(LightingEditor.Styles.skyboxWarning.text, MessageType.Warning); + } + EditorGUILayout.PropertyField(this.m_Sun, LightingEditor.Styles.sunLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.IntPopup(this.m_AmbientMode, LightingEditor.kFullAmbientModes, LightingEditor.kFullAmbientModeValues, LightingEditor.Styles.ambientModeLabel, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + switch (this.m_AmbientMode.intValue) + { + case 0: + if (material == null) + { + EditorGUILayout.PropertyField(this.m_AmbientSkyColor, LightingEditor.Styles.ambient, new GUILayoutOption[0]); + } + break; + case 1: + EditorGUILayout.PropertyField(this.m_AmbientSkyColor, LightingEditor.Styles.ambientUp, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AmbientEquatorColor, LightingEditor.Styles.ambientMid, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AmbientGroundColor, LightingEditor.Styles.ambientDown, new GUILayoutOption[0]); + break; + case 3: + EditorGUILayout.PropertyField(this.m_AmbientSkyColor, LightingEditor.Styles.ambient, new GUILayoutOption[0]); + break; + } + EditorGUI.indentLevel--; + EditorGUILayout.Slider(this.m_AmbientIntensity, 0f, 1f, LightingEditor.Styles.ambientIntensity, new GUILayoutOption[0]); + bool flag = Lightmapping.realtimeLightmapsEnabled && Lightmapping.bakedLightmapsEnabled; + EditorGUI.BeginDisabledGroup(!flag); + EditorGUILayout.PropertyField(this.m_EnvironmentLightingMode, LightingEditor.Styles.SkyLightBaked, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_DefaultReflectionMode, LightingEditor.Styles.reflectionModeLabel, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + DefaultReflectionMode intValue = (DefaultReflectionMode)this.m_DefaultReflectionMode.intValue; + if (intValue != DefaultReflectionMode.FromSkybox) + { + if (intValue == DefaultReflectionMode.Custom) + { + EditorGUILayout.PropertyField(this.m_CustomReflection, LightingEditor.Styles.customReflection, new GUILayoutOption[0]); + } + } + else + { + EditorGUILayout.IntPopup(this.m_DefaultReflectionResolution, LightingEditor.Styles.defaultReflectionSizes, LightingEditor.Styles.defaultReflectionSizesValues, LightingEditor.Styles.defaultReflectionResolution, new GUILayoutOption[] + { + GUILayout.MinWidth(40f) + }); + } + EditorGUI.indentLevel--; + EditorGUILayout.Slider(this.m_ReflectionIntensity, 0f, 1f, LightingEditor.Styles.reflectionIntensity, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_ReflectionBounces, 1, 5, LightingEditor.Styles.reflectionBounces, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + base.serializedObject.ApplyModifiedProperties(); + this.m_lightmapSettings.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/LightingWindow.cs b/UnityEditor/UnityEditor/LightingWindow.cs new file mode 100644 index 00000000..6264de1d --- /dev/null +++ b/UnityEditor/UnityEditor/LightingWindow.cs @@ -0,0 +1,688 @@ +using System; +using System.Collections.Generic; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +using UnityEngineInternal; +namespace UnityEditor +{ + internal class LightingWindow : EditorWindow + { + private enum Mode + { + ObjectSettings, + BakeSettings, + Maps + } + private enum BakeMode + { + BakeReflectionProbes, + Clear + } + private class Styles + { + public GUIContent[] ModeToggles = new GUIContent[] + { + EditorGUIUtility.TextContent("LightmapEditor.ObjectSettings"), + EditorGUIUtility.TextContent("LightmapEditor.BakeSettings"), + EditorGUIUtility.TextContent("LightmapEditor.Maps") + }; + public int[] RuntimeCPUUsageValues = new int[] + { + 25, + 50, + 75, + 100 + }; + public GUIContent[] RuntimeCPUUsageStrings = new GUIContent[] + { + EditorGUIUtility.TextContent("LightmapEditor.RuntimeCPUUsage.Low"), + EditorGUIUtility.TextContent("LightmapEditor.RuntimeCPUUsage.Medium"), + EditorGUIUtility.TextContent("LightmapEditor.RuntimeCPUUsage.High"), + EditorGUIUtility.TextContent("LightmapEditor.RuntimeCPUUsage.Unlimited") + }; + public GUIContent RuntimeCPUUsage = EditorGUIUtility.TextContent("LightmapEditor.RuntimeCPUUsage"); + public GUIContent RealtimeGILabel = EditorGUIUtility.TextContent("LightmapEditor.RealtimeGILabel"); + public GUIContent BakedGILabel = EditorGUIUtility.TextContent("LightmapEditor.BakedGILabel"); + public GUIContent GeneralGILabel = EditorGUIUtility.TextContent("LightmapEditor.GeneralGILabel"); + public GUIContent ContinuousBakeLabel = EditorGUIUtility.TextContent("LightmapEditor.ContinuousBakeLabel"); + public GUIContent BuildLabel = EditorGUIUtility.TextContent("LightmapEditor.BuildLabel"); + public GUIContent IndirectResolution = EditorGUIUtility.TextContent("LightmapEditor.IndirectResolution"); + public GUIContent UpdateRealtimeProbeLabel = EditorGUIUtility.TextContent("LightmapEditor.UpdateRealtimeProbes"); + public GUIContent BounceScale = EditorGUIUtility.TextContent("LightmapEditor.BounceScale"); + public GUIContent UpdateThreshold = EditorGUIUtility.TextContent("LightmapEditor.UpdateThreshold"); + public GUIContent AlbedoBoost = EditorGUIUtility.TextContent("LightmapEditor.AlbedoBoost"); + public GUIContent IndirectOutputScale = EditorGUIUtility.TextContent("LightmapEditor.IndirectOutputScale"); + public GUIContent Resolution = EditorGUIUtility.TextContent("LightmapEditor.Resolution"); + public GUIContent BakeResolution = EditorGUIUtility.TextContent("LightmapEditor.BakeResolution"); + public GUIContent ConcurrentJobs = EditorGUIUtility.TextContent("LightmapEditor.ConcurrentJobs"); + public GUIContent ForceWhiteAlbedo = EditorGUIUtility.TextContent("LightmapEditor.ForceWhiteAlbedo"); + public GUIContent ForceUpdates = EditorGUIUtility.TextContent("LightmapEditor.ForceUpdates"); + public GUIContent AmbientOcclusion = EditorGUIUtility.TextContent("LightmapEditor.AmbientOcclusion"); + public GUIContent AOMaxDistance = EditorGUIUtility.TextContent("LightmapEditor.AOMaxDistance"); + public GUIContent DirectionalMode = EditorGUIUtility.TextContent("LightmapEditor.DirectionalMode"); + public GUIContent NoDirectionalSpecularInSM2AndGLES2 = EditorGUIUtility.TextContent("LightmapEditor.NoDirectionalSpecularInSM2AndGLES2"); + public GUIContent Padding = EditorGUIUtility.TextContent("LightmapEditor.Padding"); + public GUIContent MaxAtlasSize = EditorGUIUtility.TextContent("LightmapEditor.MaxAtlasSize"); + public GUIContent TextureCompression = EditorGUIUtility.TextContent("LightmapEditor.TextureCompression"); + public GUIContent FinalGather = EditorGUIUtility.TextContent("LightmapEditor.FinalGather"); + public GUIContent FinalGatherRayCount = EditorGUIUtility.TextContent("LightmapEditor.FinalGatherRayCount"); + public GUIContent DefaultLightmapParameters = EditorGUIUtility.TextContent("LightmapEditor.DefaultLightmapParameters"); + public GUIContent SceneViewLightmapDisplay = EditorGUIUtility.TextContent("LightmapEditor.SceneViewLightmapDisplay"); + public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; + } + private const string kGlobalIlluminationUnityManualPage = "file:///unity/Manual/GlobalIllumination.html"; + private const string kShowRealtimeSettingsKey = "ShowRealtimeLightingSettings"; + private const string kShowBakeSettingsKey = "ShowBakedLightingSettings"; + private const string kShowGeneralSettingsKey = "ShowGeneralLightingSettings"; + private const float kToolbarPadding = 38f; + private GUIContent[] kConcurrentJobsTypeStrings = new GUIContent[] + { + new GUIContent("Min"), + new GUIContent("Low"), + new GUIContent("High") + }; + private int[] kConcurrentJobsTypeValues = new int[] + { + 0, + 1, + 2 + }; + private float kButtonWidth = 120f; + private GUIContent[] kModeStrings = new GUIContent[] + { + new GUIContent("Non Directional"), + new GUIContent("Directional"), + new GUIContent("Directional Specular") + }; + private int[] kModeValues = new int[] + { + 0, + 1, + 2 + }; + private GUIContent[] kMaxAtlasSizeStrings = new GUIContent[] + { + new GUIContent("32"), + new GUIContent("64"), + new GUIContent("128"), + new GUIContent("256"), + new GUIContent("512"), + new GUIContent("1024"), + new GUIContent("2048"), + new GUIContent("4096") + }; + private int[] kMaxAtlasSizeValues = new int[] + { + 32, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096 + }; + private static string[] s_BakeModeOptions = new string[] + { + "Bake Reflection Probes", + "Clear Baked Data" + }; + private LightingWindow.Mode m_Mode = LightingWindow.Mode.BakeSettings; + private Vector2 m_ScrollPosition = Vector2.zero; + private LightingWindowObjectTab m_ObjectTab; + private LightingWindowLightmapPreviewTab m_LightmapPreviewTab; + private AnimBool m_ShowIndirectResolution = new AnimBool(); + private bool m_ShowDevOptions; + private PreviewResizer m_PreviewResizer = new PreviewResizer(); + private Editor m_LightingEditor; + private Editor m_FogEditor; + private Editor m_OtherRenderingEditor; + private static bool s_IsVisible = false; + private bool m_ShowRealtimeSettings; + private bool m_ShowBakeSettings; + private bool m_ShowGeneralSettings; + private static LightingWindow.Styles s_Styles; + private static LightingWindow.Styles styles + { + get + { + LightingWindow.Styles arg_17_0; + if ((arg_17_0 = LightingWindow.s_Styles) == null) + { + arg_17_0 = (LightingWindow.s_Styles = new LightingWindow.Styles()); + } + return arg_17_0; + } + } + private UnityEngine.Object renderSettings + { + get + { + return RenderSettings.GetRenderSettings(); + } + } + private Editor lightingEditor + { + get + { + Editor.CreateCachedEditor(this.renderSettings, typeof(LightingEditor), ref this.m_LightingEditor); + return this.m_LightingEditor; + } + } + private Editor fogEditor + { + get + { + Editor.CreateCachedEditor(this.renderSettings, typeof(FogEditor), ref this.m_FogEditor); + return this.m_FogEditor; + } + } + private Editor otherRenderingEditor + { + get + { + Editor.CreateCachedEditor(this.renderSettings, typeof(OtherRenderingEditor), ref this.m_OtherRenderingEditor); + return this.m_OtherRenderingEditor; + } + } + private void OnEnable() + { + this.m_LightmapPreviewTab = new LightingWindowLightmapPreviewTab(); + this.m_ObjectTab = new LightingWindowObjectTab(); + this.m_ObjectTab.OnEnable(this); + this.m_ShowRealtimeSettings = InspectorState.GetBool("ShowRealtimeLightingSettings", true); + this.m_ShowBakeSettings = InspectorState.GetBool("ShowBakedLightingSettings", true); + this.m_ShowGeneralSettings = InspectorState.GetBool("ShowGeneralLightingSettings", true); + this.UpdateAnimatedBools(true); + base.autoRepaintOnSceneChange = true; + this.m_PreviewResizer.Init("LightmappingPreview"); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + base.Repaint(); + } + private void UpdateAnimatedBools(bool initialize) + { + this.SetOptions(this.m_ShowIndirectResolution, initialize, !Lightmapping.realtimeLightmapsEnabled); + } + private void SetOptions(AnimBool animBool, bool initialize, bool targetValue) + { + if (initialize) + { + animBool.value = targetValue; + animBool.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + else + { + animBool.target = targetValue; + } + } + private void OnDisable() + { + this.ClearCachedProperties(); + this.m_ObjectTab.OnDisable(); + InspectorState.SetBool("ShowRealtimeLightingSettings", this.m_ShowRealtimeSettings); + InspectorState.SetBool("ShowBakedLightingSettings", this.m_ShowBakeSettings); + InspectorState.SetBool("ShowGeneralLightingSettings", this.m_ShowGeneralSettings); + EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); + } + private void ClearCachedProperties() + { + UnityEngine.Object.DestroyImmediate(this.m_LightingEditor); + this.m_LightingEditor = null; + UnityEngine.Object.DestroyImmediate(this.m_FogEditor); + this.m_FogEditor = null; + UnityEngine.Object.DestroyImmediate(this.m_OtherRenderingEditor); + this.m_OtherRenderingEditor = null; + } + private void OnBecameVisible() + { + if (LightingWindow.s_IsVisible) + { + return; + } + LightingWindow.s_IsVisible = true; + LightmapVisualization.enabled = true; + LightingWindow.RepaintSceneAndGameViews(); + } + private void OnBecameInvisible() + { + LightingWindow.s_IsVisible = false; + LightmapVisualization.enabled = false; + LightingWindow.RepaintSceneAndGameViews(); + } + private void OnSelectionChange() + { + this.m_LightmapPreviewTab.UpdateLightmapSelection(); + if (this.m_Mode == LightingWindow.Mode.ObjectSettings || this.m_Mode == LightingWindow.Mode.Maps) + { + base.Repaint(); + } + } + internal static void RepaintSceneAndGameViews() + { + SceneView.RepaintAll(); + GameView.RepaintAll(); + } + private void OnGUI() + { + this.UpdateAnimatedBools(false); + EditorGUIUtility.labelWidth = 130f; + EditorGUILayout.Space(); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(38f); + this.ModeToggle(); + GUILayout.FlexibleSpace(); + this.DrawHelpGUI(); + if (this.m_Mode == LightingWindow.Mode.BakeSettings) + { + this.DrawSettingsGUI(); + } + EditorGUILayout.EndHorizontal(); + EditorGUILayout.Space(); + this.m_ScrollPosition = EditorGUILayout.BeginScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); + switch (this.m_Mode) + { + case LightingWindow.Mode.ObjectSettings: + this.m_ObjectTab.ObjectSettings(); + break; + case LightingWindow.Mode.BakeSettings: + this.lightingEditor.OnInspectorGUI(); + this.EnlightenBakeSettings(); + this.fogEditor.OnInspectorGUI(); + this.otherRenderingEditor.OnInspectorGUI(); + break; + case LightingWindow.Mode.Maps: + this.m_LightmapPreviewTab.Maps(); + break; + } + EditorGUILayout.EndScrollView(); + EditorGUILayout.Space(); + GUI.enabled = !EditorApplication.isPlayingOrWillChangePlaymode; + this.Buttons(); + GUI.enabled = true; + EditorGUILayout.Space(); + this.Summary(); + this.PreviewSection(); + } + private void DrawHelpGUI() + { + Rect rect = GUILayoutUtility.GetRect(16f, 16f); + GUIContent content = new GUIContent(EditorGUI.GUIContents.helpIcon); + if (GUI.Button(rect, content, GUIStyle.none)) + { + Help.ShowHelpPage("file:///unity/Manual/GlobalIllumination.html"); + } + } + private void DrawSettingsGUI() + { + Rect rect = GUILayoutUtility.GetRect(16f, 16f); + if (EditorGUI.ButtonMouseDown(rect, EditorGUI.GUIContents.titleSettingsIcon, FocusType.Native, GUIStyle.none)) + { + EditorUtility.DisplayCustomMenu(rect, new GUIContent[] + { + new GUIContent("Reset") + }, -1, new EditorUtility.SelectMenuItemFunction(this.ResetSettings), null); + } + } + private void ResetSettings(object userData, string[] options, int selected) + { + RenderSettings.Reset(); + LightmapEditorSettings.Reset(); + LightmapSettings.Reset(); + } + private void PreviewSection() + { + EditorGUILayout.BeginHorizontal(GUIContent.none, "preToolbar", new GUILayoutOption[] + { + GUILayout.Height(17f) + }); + GUILayout.FlexibleSpace(); + GUI.Label(GUILayoutUtility.GetLastRect(), "Preview", "preToolbar2"); + EditorGUILayout.EndHorizontal(); + float num = this.m_PreviewResizer.ResizeHandle(base.position, 100f, 250f, 17f); + Rect r = new Rect(0f, base.position.height - num, base.position.width, num); + switch (this.m_Mode) + { + case LightingWindow.Mode.ObjectSettings: + if (Selection.activeGameObject) + { + this.m_ObjectTab.ObjectPreview(r); + } + break; + case LightingWindow.Mode.Maps: + if (num > 0f) + { + this.m_LightmapPreviewTab.LightmapPreview(r); + } + break; + } + } + private void ModeToggle() + { + float width = base.position.width - 76f; + this.m_Mode = (LightingWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, LightingWindow.styles.ModeToggles, "LargeButton", new GUILayoutOption[] + { + GUILayout.Width(width) + }); + } + private void DeveloperBuildEnlightenSettings(SerializedObject so) + { + if (!Unsupported.IsDeveloperBuild()) + { + return; + } + this.m_ShowDevOptions = EditorGUILayout.Foldout(this.m_ShowDevOptions, "Debug [internal]"); + if (this.m_ShowDevOptions) + { + SerializedProperty property = so.FindProperty("m_GISettings.m_BounceScale"); + SerializedProperty property2 = so.FindProperty("m_GISettings.m_TemporalCoherenceThreshold"); + EditorGUI.indentLevel++; + Lightmapping.concurrentJobsType = (Lightmapping.ConcurrentJobsType)EditorGUILayout.IntPopup(LightingWindow.styles.ConcurrentJobs, (int)Lightmapping.concurrentJobsType, this.kConcurrentJobsTypeStrings, this.kConcurrentJobsTypeValues, new GUILayoutOption[0]); + Lightmapping.enlightenForceUpdates = EditorGUILayout.Toggle(LightingWindow.styles.ForceUpdates, Lightmapping.enlightenForceUpdates, new GUILayoutOption[0]); + Lightmapping.enlightenForceWhiteAlbedo = EditorGUILayout.Toggle(LightingWindow.styles.ForceWhiteAlbedo, Lightmapping.enlightenForceWhiteAlbedo, new GUILayoutOption[0]); + Lightmapping.filterMode = (FilterMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Filter Mode"), Lightmapping.filterMode, new GUILayoutOption[0]); + EditorGUILayout.Slider(property, 0f, 10f, LightingWindow.styles.BounceScale, new GUILayoutOption[0]); + EditorGUILayout.Slider(property2, 0f, 1f, LightingWindow.styles.UpdateThreshold, new GUILayoutOption[0]); + if (GUILayout.Button("Clear disk cache", new GUILayoutOption[] + { + GUILayout.Width(this.kButtonWidth) + })) + { + Lightmapping.Clear(); + Lightmapping.ClearDiskCache(); + } + if (GUILayout.Button("Print state to console", new GUILayoutOption[] + { + GUILayout.Width(this.kButtonWidth) + })) + { + Lightmapping.PrintStateToConsole(); + } + if (GUILayout.Button("Reset albedo/emissive", new GUILayoutOption[] + { + GUILayout.Width(this.kButtonWidth) + })) + { + GIDebugVisualisation.ResetRuntimeInputTextures(); + } + if (GUILayout.Button("Reset environment", new GUILayoutOption[] + { + GUILayout.Width(this.kButtonWidth) + })) + { + DynamicGI.UpdateEnvironment(); + } + EditorGUI.indentLevel--; + } + } + private void EnlightenBakeSettings() + { + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + SerializedProperty enableRealtimeGI = serializedObject.FindProperty("m_GISettings.m_EnableRealtimeLightmaps"); + SerializedProperty enableBakedGI = serializedObject.FindProperty("m_GISettings.m_EnableBakedLightmaps"); + this.RealtimeGUI(serializedObject, enableRealtimeGI, enableBakedGI); + this.BakedGUI(serializedObject, enableRealtimeGI, enableBakedGI); + this.GeneralSettingsGUI(serializedObject, enableRealtimeGI, enableBakedGI); + serializedObject.ApplyModifiedProperties(); + } + private void GeneralSettingsGUI(SerializedObject so, SerializedProperty enableRealtimeGI, SerializedProperty enableBakedGI) + { + this.m_ShowGeneralSettings = EditorGUILayout.FoldoutTitlebar(this.m_ShowGeneralSettings, LightingWindow.styles.GeneralGILabel); + if (!this.m_ShowGeneralSettings) + { + return; + } + SerializedProperty property = so.FindProperty("m_GISettings.m_AlbedoBoost"); + SerializedProperty property2 = so.FindProperty("m_GISettings.m_IndirectOutputScale"); + SerializedProperty property3 = so.FindProperty("m_LightmapEditorSettings.m_TextureWidth"); + SerializedProperty prop = so.FindProperty("m_LightmapEditorSettings.m_LightmapParameters"); + SerializedProperty serializedProperty = so.FindProperty("m_LightmapsMode"); + bool flag = enableBakedGI.boolValue || enableRealtimeGI.boolValue; + EditorGUI.BeginDisabledGroup(!flag); + EditorGUI.indentLevel++; + EditorGUILayout.IntPopup(serializedProperty, this.kModeStrings, this.kModeValues, LightingWindow.s_Styles.DirectionalMode, new GUILayoutOption[0]); + if (serializedProperty.intValue == 2) + { + EditorGUILayout.HelpBox(LightingWindow.s_Styles.NoDirectionalSpecularInSM2AndGLES2.text, MessageType.Warning); + } + EditorGUILayout.Slider(property2, 0f, 5f, LightingWindow.styles.IndirectOutputScale, new GUILayoutOption[0]); + EditorGUILayout.Slider(property, 1f, 10f, LightingWindow.styles.AlbedoBoost, new GUILayoutOption[0]); + if (LightingWindowObjectTab.LightmapParametersGUI(prop, LightingWindow.styles.DefaultLightmapParameters)) + { + this.m_Mode = LightingWindow.Mode.ObjectSettings; + } + EditorGUILayout.IntPopup(property3, this.kMaxAtlasSizeStrings, this.kMaxAtlasSizeValues, LightingWindow.styles.MaxAtlasSize, new GUILayoutOption[0]); + this.DeveloperBuildEnlightenSettings(so); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; + } + private void BakedGUI(SerializedObject so, SerializedProperty enableRealtimeGI, SerializedProperty enableBakedGI) + { + this.m_ShowBakeSettings = EditorGUILayout.ToggleTitlebar(this.m_ShowBakeSettings, LightingWindow.styles.BakedGILabel, enableBakedGI); + if (!this.m_ShowBakeSettings) + { + return; + } + SerializedProperty resolution = so.FindProperty("m_LightmapEditorSettings.m_Resolution"); + SerializedProperty resolution2 = so.FindProperty("m_LightmapEditorSettings.m_BakeResolution"); + SerializedProperty property = so.FindProperty("m_LightmapEditorSettings.m_Padding"); + SerializedProperty serializedProperty = so.FindProperty("m_LightmapEditorSettings.m_CompAOExponent"); + SerializedProperty serializedProperty2 = so.FindProperty("m_LightmapEditorSettings.m_AOMaxDistance"); + SerializedProperty property2 = so.FindProperty("m_LightmapEditorSettings.m_TextureCompression"); + SerializedProperty serializedProperty3 = so.FindProperty("m_LightmapEditorSettings.m_FinalGather"); + SerializedProperty property3 = so.FindProperty("m_LightmapEditorSettings.m_FinalGatherRayCount"); + EditorGUI.indentLevel++; + EditorGUI.BeginDisabledGroup(!enableBakedGI.boolValue); + LightingWindow.DrawLightmapResolutionField(resolution2, LightingWindow.styles.BakeResolution); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property, LightingWindow.styles.Padding, new GUILayoutOption[0]); + GUILayout.Label(" texels", LightingWindow.styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + EditorGUILayout.PropertyField(property2, LightingWindow.s_Styles.TextureCompression, new GUILayoutOption[0]); + EditorGUILayout.Space(); + this.m_ShowIndirectResolution.target = !enableRealtimeGI.boolValue; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowIndirectResolution.faded)) + { + LightingWindow.DrawLightmapResolutionField(resolution, LightingWindow.styles.IndirectResolution); + EditorGUILayout.Space(); + } + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.Slider(serializedProperty, 0f, 1f, LightingWindow.styles.AmbientOcclusion, new GUILayoutOption[0]); + if (serializedProperty.floatValue > 0f) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(serializedProperty2, LightingWindow.styles.AOMaxDistance, new GUILayoutOption[0]); + if (serializedProperty2.floatValue < 0f) + { + serializedProperty2.floatValue = 0f; + } + EditorGUI.indentLevel--; + } + EditorGUILayout.PropertyField(serializedProperty3, LightingWindow.s_Styles.FinalGather, new GUILayoutOption[0]); + if (serializedProperty3.boolValue) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(property3, LightingWindow.styles.FinalGatherRayCount, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; + } + private void RealtimeGUI(SerializedObject so, SerializedProperty enableRealtimeGI, SerializedProperty enableBakedGI) + { + this.m_ShowRealtimeSettings = EditorGUILayout.ToggleTitlebar(this.m_ShowRealtimeSettings, LightingWindow.styles.RealtimeGILabel, enableRealtimeGI); + if (!this.m_ShowRealtimeSettings) + { + return; + } + SerializedProperty property = so.FindProperty("m_RuntimeCPUUsage"); + SerializedProperty resolution = so.FindProperty("m_LightmapEditorSettings.m_Resolution"); + EditorGUI.indentLevel++; + EditorGUI.BeginDisabledGroup(!enableRealtimeGI.boolValue); + LightingWindow.DrawLightmapResolutionField(resolution, LightingWindow.styles.Resolution); + EditorGUILayout.IntPopup(property, LightingWindow.styles.RuntimeCPUUsageStrings, LightingWindow.styles.RuntimeCPUUsageValues, LightingWindow.styles.RuntimeCPUUsage, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; + } + private static void DrawLightmapResolutionField(SerializedProperty resolution, GUIContent label) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PropertyField(resolution, label, new GUILayoutOption[0]); + GUILayout.Label(" texels per unit", LightingWindow.styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + private void BakeDropDownCallback(object data) + { + LightingWindow.BakeMode bakeMode = (LightingWindow.BakeMode)((int)data); + LightingWindow.BakeMode bakeMode2 = bakeMode; + if (bakeMode2 != LightingWindow.BakeMode.BakeReflectionProbes) + { + if (bakeMode2 == LightingWindow.BakeMode.Clear) + { + this.DoClear(); + } + } + else + { + this.DoBakeReflectionProbes(); + } + } + private void Buttons() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + EditorGUI.BeginChangeCheck(); + bool flag = Lightmapping.giWorkflowMode == Lightmapping.GIWorkflowMode.Iterative; + flag = GUILayout.Toggle(flag, LightingWindow.styles.ContinuousBakeLabel, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + Lightmapping.giWorkflowMode = ((!flag) ? Lightmapping.GIWorkflowMode.OnDemand : Lightmapping.GIWorkflowMode.Iterative); + InspectorWindow.RepaintAllInspectors(); + } + EditorGUI.BeginDisabledGroup(flag); + bool flag2 = flag || !Lightmapping.isRunning; + if (flag2) + { + if (EditorGUI.ButtonWithDropdownList(LightingWindow.styles.BuildLabel, LightingWindow.s_BakeModeOptions, new GenericMenu.MenuFunction2(this.BakeDropDownCallback), new GUILayoutOption[] + { + GUILayout.Width(180f) + })) + { + this.DoBake(); + GUIUtility.ExitGUI(); + } + } + else + { + if (GUILayout.Button("Cancel", new GUILayoutOption[] + { + GUILayout.Width(this.kButtonWidth) + })) + { + Lightmapping.Cancel(); + Analytics.Track("/LightMapper/Cancel"); + } + } + EditorGUI.EndDisabledGroup(); + GUILayout.EndHorizontal(); + } + private void DoBake() + { + Analytics.Track("/LightMapper/Start"); + Analytics.Event("LightMapper", "Mode", LightmapSettings.lightmapsMode.ToString(), 1); + Analytics.Event("LightMapper", "Button", "BakeScene", 1); + Lightmapping.BakeAsync(); + } + private void DoClear() + { + Lightmapping.Clear(); + Analytics.Track("/LightMapper/Clear"); + } + private void DoBakeReflectionProbes() + { + Lightmapping.BakeAllReflectionProbesSnapshots(); + Analytics.Track("/LightMapper/BakeAllReflectionProbesSnapshots"); + } + private void Summary() + { + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + int num = 0; + int num2 = 0; + Dictionary dictionary = new Dictionary(); + bool flag = false; + LightmapData[] lightmaps = LightmapSettings.lightmaps; + for (int i = 0; i < lightmaps.Length; i++) + { + LightmapData lightmapData = lightmaps[i]; + if (!(lightmapData.lightmapFar == null)) + { + num2++; + Vector2 vector = new Vector2((float)lightmapData.lightmapFar.width, (float)lightmapData.lightmapFar.height); + if (dictionary.ContainsKey(vector)) + { + Dictionary dictionary2; + Dictionary expr_7C = dictionary2 = dictionary; + Vector2 key; + Vector2 expr_81 = key = vector; + int num3 = dictionary2[key]; + expr_7C[expr_81] = num3 + 1; + } + else + { + dictionary.Add(vector, 1); + } + num += TextureUtil.GetStorageMemorySize(lightmapData.lightmapFar); + if (lightmapData.lightmapNear) + { + num += TextureUtil.GetStorageMemorySize(lightmapData.lightmapNear); + flag = true; + } + } + } + string text = string.Concat(new object[] + { + num2, + (!flag) ? " non-directional" : " directional", + " lightmap", + (num2 != 1) ? "s" : string.Empty + }); + bool flag2 = true; + foreach (KeyValuePair current in dictionary) + { + text += ((!flag2) ? ", " : ": "); + flag2 = false; + if (current.Value > 1) + { + text = text + current.Value + "x"; + } + string text2 = text; + text = string.Concat(new object[] + { + text2, + current.Key.x, + "x", + current.Key.y, + "px" + }); + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(text + " ", LightingWindow.styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.BeginVertical(new GUILayoutOption[0]); + GUILayout.Label(EditorUtility.FormatBytes(num), LightingWindow.styles.labelStyle, new GUILayoutOption[0]); + GUILayout.Label((num2 != 0) ? string.Empty : "No Lightmaps", LightingWindow.styles.labelStyle, new GUILayoutOption[0]); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + } + [MenuItem("Window/Lighting", false, 2098)] + private static void CreateLightingWindow() + { + LightingWindow window = EditorWindow.GetWindow(); + window.title = EditorGUIUtility.TextContent("LightmapEditor.WindowTitle").text; + window.minSize = new Vector2(300f, 360f); + window.Show(); + } + } +} diff --git a/UnityEditor/UnityEditor/LightingWindowLightmapPreviewTab.cs b/UnityEditor/UnityEditor/LightingWindowLightmapPreviewTab.cs new file mode 100644 index 00000000..dd850449 --- /dev/null +++ b/UnityEditor/UnityEditor/LightingWindowLightmapPreviewTab.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections; +using UnityEngine; +namespace UnityEditor +{ + internal class LightingWindowLightmapPreviewTab + { + private class Styles + { + public GUIStyle selectedLightmapHighlight = "LightmapEditorSelectedHighlight"; + public GUIContent LightProbes = EditorGUIUtility.TextContent("LightmapEditor.LightProbes"); + public GUIContent LightmapSnapshot = EditorGUIUtility.TextContent("LightmapEditor.LightmapSnapshot"); + public GUIContent MapsArraySize = EditorGUIUtility.TextContent("LightmapEditor.MapsArraySize"); + } + private Vector2 m_ScrollPositionLightmaps = Vector2.zero; + private Vector2 m_ScrollPositionMaps = Vector2.zero; + private int m_SelectedLightmap = -1; + private static LightingWindowLightmapPreviewTab.Styles s_Styles; + private static void Header(ref Rect rect, float headerHeight, float headerLeftMargin, float maxLightmaps) + { + Rect rect2 = GUILayoutUtility.GetRect(rect.width, headerHeight); + rect2.width = rect.width / maxLightmaps; + rect2.y -= rect.height; + rect.y += headerHeight; + rect2.x += headerLeftMargin; + EditorGUI.DropShadowLabel(rect2, "Intensity"); + rect2.x += rect2.width; + EditorGUI.DropShadowLabel(rect2, "Directionality"); + } + private void MenuSelectLightmapUsers(Rect rect, int lightmapIndex) + { + if (Event.current.type == EventType.ContextClick && rect.Contains(Event.current.mousePosition)) + { + string[] texts = new string[] + { + "Select Lightmap Users" + }; + Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); + EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(texts), -1, new EditorUtility.SelectMenuItemFunction(this.SelectLightmapUsers), lightmapIndex); + Event.current.Use(); + } + } + private void SelectLightmapUsers(object userData, string[] options, int selected) + { + int num = (int)userData; + ArrayList arrayList = new ArrayList(); + MeshRenderer[] array = UnityEngine.Object.FindObjectsOfType(typeof(MeshRenderer)) as MeshRenderer[]; + MeshRenderer[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + MeshRenderer meshRenderer = array2[i]; + if (meshRenderer != null && meshRenderer.lightmapIndex == num) + { + arrayList.Add(meshRenderer.gameObject); + } + } + Terrain[] array3 = UnityEngine.Object.FindObjectsOfType(typeof(Terrain)) as Terrain[]; + Terrain[] array4 = array3; + for (int j = 0; j < array4.Length; j++) + { + Terrain terrain = array4[j]; + if (terrain != null && terrain.lightmapIndex == num) + { + arrayList.Add(terrain.gameObject); + } + } + Selection.objects = (arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); + } + public void LightmapPreview(Rect r) + { + if (LightingWindowLightmapPreviewTab.s_Styles == null) + { + LightingWindowLightmapPreviewTab.s_Styles = new LightingWindowLightmapPreviewTab.Styles(); + } + bool flag = true; + GUI.Box(r, string.Empty, "PreBackground"); + this.m_ScrollPositionLightmaps = EditorGUILayout.BeginScrollView(this.m_ScrollPositionLightmaps, new GUILayoutOption[] + { + GUILayout.Height(r.height) + }); + int num = 0; + float num2 = 2f; + LightmapData[] lightmaps = LightmapSettings.lightmaps; + for (int i = 0; i < lightmaps.Length; i++) + { + LightmapData lightmapData = lightmaps[i]; + if (lightmapData.lightmapFar == null && lightmapData.lightmapNear == null) + { + num++; + } + else + { + int num3 = (!lightmapData.lightmapFar) ? -1 : Math.Max(lightmapData.lightmapFar.width, lightmapData.lightmapFar.height); + int num4 = (!lightmapData.lightmapNear) ? -1 : Math.Max(lightmapData.lightmapNear.width, lightmapData.lightmapNear.height); + Texture2D texture2D = (num3 <= num4) ? lightmapData.lightmapNear : lightmapData.lightmapFar; + GUILayoutOption[] options = new GUILayoutOption[] + { + GUILayout.MaxWidth((float)texture2D.width * num2), + GUILayout.MaxHeight((float)texture2D.height) + }; + Rect aspectRect = GUILayoutUtility.GetAspectRect((float)texture2D.width * num2 / (float)texture2D.height, options); + if (flag) + { + LightingWindowLightmapPreviewTab.Header(ref aspectRect, 20f, 6f, num2); + flag = false; + } + aspectRect.width /= num2; + EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapFar); + this.MenuSelectLightmapUsers(aspectRect, num); + if (lightmapData.lightmapNear) + { + aspectRect.x += aspectRect.width; + EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapNear); + this.MenuSelectLightmapUsers(aspectRect, num); + } + num++; + } + } + EditorGUILayout.EndScrollView(); + } + public void UpdateLightmapSelection() + { + Terrain terrain = null; + MeshRenderer component; + if (Selection.activeGameObject == null || ((component = Selection.activeGameObject.GetComponent()) == null && (terrain = Selection.activeGameObject.GetComponent()) == null)) + { + this.m_SelectedLightmap = -1; + return; + } + this.m_SelectedLightmap = ((!(component != null)) ? terrain.lightmapIndex : component.lightmapIndex); + } + public void Maps() + { + if (LightingWindowLightmapPreviewTab.s_Styles == null) + { + LightingWindowLightmapPreviewTab.s_Styles = new LightingWindowLightmapPreviewTab.Styles(); + } + GUI.changed = false; + if (Lightmapping.giWorkflowMode == Lightmapping.GIWorkflowMode.OnDemand) + { + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + SerializedProperty property = serializedObject.FindProperty("m_LightmapSnapshot"); + EditorGUILayout.PropertyField(property, LightingWindowLightmapPreviewTab.s_Styles.LightmapSnapshot, new GUILayoutOption[0]); + serializedObject.ApplyModifiedProperties(); + } + GUILayout.Space(10f); + LightmapData[] lightmaps = LightmapSettings.lightmaps; + EditorGUI.BeginDisabledGroup(true); + this.m_ScrollPositionMaps = GUILayout.BeginScrollView(this.m_ScrollPositionMaps, new GUILayoutOption[0]); + for (int i = 0; i < lightmaps.Length; i++) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUILayout.Label(i.ToString(), new GUILayoutOption[0]); + GUILayout.Space(5f); + lightmaps[i].lightmapFar = this.LightmapField(lightmaps[i].lightmapFar, i); + GUILayout.Space(10f); + lightmaps[i].lightmapNear = this.LightmapField(lightmaps[i].lightmapNear, i); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + } + GUILayout.EndScrollView(); + EditorGUI.EndDisabledGroup(); + } + private Texture2D LightmapField(Texture2D lightmap, int index) + { + Rect rect = GUILayoutUtility.GetRect(100f, 100f, EditorStyles.objectField); + this.MenuSelectLightmapUsers(rect, index); + Texture2D result = EditorGUI.ObjectField(rect, lightmap, typeof(Texture2D), false) as Texture2D; + if (index == this.m_SelectedLightmap && Event.current.type == EventType.Repaint) + { + LightingWindowLightmapPreviewTab.s_Styles.selectedLightmapHighlight.Draw(rect, false, false, false, false); + } + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/LightingWindowObjectTab.cs b/UnityEditor/UnityEditor/LightingWindowObjectTab.cs new file mode 100644 index 00000000..9fea4e80 --- /dev/null +++ b/UnityEditor/UnityEditor/LightingWindowObjectTab.cs @@ -0,0 +1,584 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEngine; +using UnityEngine.Events; +using UnityEngineInternal; +namespace UnityEditor +{ + internal class LightingWindowObjectTab + { + private class Styles + { + public GUIContent PreserveUVs = EditorGUIUtility.TextContent("LightmapEditor.PreserveUVs"); + public GUIContent ImportantGI = EditorGUIUtility.TextContent("LightmapEditor.ImportantGI"); + public GUIContent AutoUVMaxDistance = EditorGUIUtility.TextContent("LightmapEditor.AutoUVMaxDistance"); + public GUIContent AutoUVMaxAngle = EditorGUIUtility.TextContent("LightmapEditor.AutoUVMaxAngle"); + public GUIContent LightmapParameters = EditorGUIUtility.TextContent("LightmapEditor.LightmapParameters"); + public GUIContent AtlasTilingX = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingX"); + public GUIContent AtlasTilingY = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingY"); + public GUIContent AtlasOffsetX = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetX"); + public GUIContent AtlasOffsetY = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetY"); + public GUIContent ClampedSize = EditorGUIUtility.TextContent("LightmapEditor.ClampedSize"); + public GUIContent ClampedPackingResolution = EditorGUIUtility.TextContent("LightmapEditor.ClampedPackingResolution"); + public GUIContent ZeroAreaPackingMesh = EditorGUIUtility.TextContent("LightmapEditor.ZeroAreaPackingMesh"); + public GUIContent NoNormalsNoLightmapping = EditorGUIUtility.TextContent("LightmapEditor.NoNormalsNoLightmapping"); + public GUIContent Atlas = EditorGUIUtility.TextContent("LightmapEditor.Atlas"); + public GUIContent RealtimeLM = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLM"); + public GUIContent ChunkSize = EditorGUIUtility.TextContent("LightmapEditor.ChunkSize"); + public GUIContent EmptySelection = EditorGUIUtility.TextContent("LightmapEditor.EmptySelection"); + public GUIContent ScaleInLightmap = EditorGUIUtility.TextContent("LightmapEditor.ScaleInLightmap"); + public GUIContent TerrainLightmapSize = EditorGUIUtility.TextContent("LightmapEditor.Terrain.LightmapSize"); + public GUIContent AtlasIndex = EditorGUIUtility.TextContent("LightmapEditor.AtlasIndex"); + public GUIContent RealtimeLMResolution = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLMResolution"); + public GUIContent RealtimeLMInstanceResolution = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLMInstanceResolution"); + public GUIContent RealtimeLMInputSystemHash = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLMInputSystemHash"); + public GUIContent RealtimeLMInstanceHash = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLMInstanceHash"); + public GUIContent RealtimeLMGeometryHash = EditorGUIUtility.TextContent("LightmapEditor.RealtimeLMGeometryHash"); + } + private GITextureType[] kObjectPreviewTextureTypes = new GITextureType[] + { + GITextureType.Charting, + GITextureType.Albedo, + GITextureType.Emissive, + GITextureType.Irradiance, + GITextureType.Directionality, + GITextureType.Baked, + GITextureType.BakedDirectional + }; + private static GUIContent[] kObjectPreviewTextureOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Charting"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Albedo"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Emissive"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Irradiance"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Directionality"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.Baked"), + EditorGUIUtility.TextContent("LightmapEditor.ObjectPreviewTextureOptions.BakedDirectional") + }; + private static LightingWindowObjectTab.Styles s_Styles; + private ZoomableArea m_ZoomablePreview; + private GUIContent m_SelectedObjectPreviewTexture; + private int m_PreviousSelection; + private bool m_ShowBakedLM; + private bool m_ShowRealtimeLM; + private bool m_HasSeparateIndirectUV; + private AnimBool m_ShowClampedSize = new AnimBool(); + private Editor m_LightEditor; + private Editor m_LightmapParametersEditor; + public void OnEnable(EditorWindow window) + { + this.m_ShowClampedSize.value = false; + this.m_ShowClampedSize.valueChanged.AddListener(new UnityAction(window.Repaint)); + } + public void OnDisable() + { + UnityEngine.Object.DestroyImmediate(this.m_LightEditor); + UnityEngine.Object.DestroyImmediate(this.m_LightmapParametersEditor); + } + private Editor GetLightEditor(Light[] lights) + { + Editor.CreateCachedEditor(lights, typeof(LightEditor), ref this.m_LightEditor); + return this.m_LightEditor; + } + private Editor GetLightmapParametersEditor(UnityEngine.Object[] lights) + { + Editor.CreateCachedEditor(lights, typeof(LightmapParametersEditor), ref this.m_LightmapParametersEditor); + return this.m_LightmapParametersEditor; + } + public void ObjectPreview(Rect r) + { + if (r.height <= 0f) + { + return; + } + if (LightingWindowObjectTab.s_Styles == null) + { + LightingWindowObjectTab.s_Styles = new LightingWindowObjectTab.Styles(); + } + List list = new List(); + GITextureType[] array = this.kObjectPreviewTextureTypes; + for (int i = 0; i < array.Length; i++) + { + GITextureType textureType = array[i]; + list.Add(LightmapVisualizationUtility.GetGITexture(textureType)); + } + if (list.Count == 0) + { + return; + } + if (this.m_ZoomablePreview == null) + { + this.m_ZoomablePreview = new ZoomableArea(true); + this.m_ZoomablePreview.hRangeMin = 0f; + this.m_ZoomablePreview.vRangeMin = 0f; + this.m_ZoomablePreview.hRangeMax = 1f; + this.m_ZoomablePreview.vRangeMax = 1f; + this.m_ZoomablePreview.SetShownHRange(0f, 1f); + this.m_ZoomablePreview.SetShownVRange(0f, 1f); + this.m_ZoomablePreview.uniformScale = true; + this.m_ZoomablePreview.scaleWithWindow = true; + } + GUI.Box(r, string.Empty, "PreBackground"); + Rect position = new Rect(r); + position.y += 1f; + position.height = 18f; + GUI.Box(position, string.Empty, EditorStyles.toolbar); + Rect rect = new Rect(r); + rect.y += 1f; + rect.height = 18f; + rect.width = 120f; + Rect rect2 = new Rect(r); + rect2.yMin += rect.height; + rect2.yMax -= 14f; + rect2.width -= 11f; + int num = Array.IndexOf(LightingWindowObjectTab.kObjectPreviewTextureOptions, this.m_SelectedObjectPreviewTexture); + if (num < 0) + { + num = 0; + } + num = EditorGUI.Popup(rect, num, LightingWindowObjectTab.kObjectPreviewTextureOptions, EditorStyles.toolbarPopup); + if (num >= LightingWindowObjectTab.kObjectPreviewTextureOptions.Length) + { + num = 0; + } + this.m_SelectedObjectPreviewTexture = LightingWindowObjectTab.kObjectPreviewTextureOptions[num]; + LightmapType lightmapType = (this.kObjectPreviewTextureTypes[num] != GITextureType.Baked && this.kObjectPreviewTextureTypes[num] != GITextureType.BakedDirectional) ? LightmapType.DynamicLightmap : LightmapType.StaticLightmap; + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + SerializedProperty serializedProperty = serializedObject.FindProperty("m_LightmapsMode"); + bool flag = (this.kObjectPreviewTextureTypes[num] == GITextureType.Baked || this.kObjectPreviewTextureTypes[num] == GITextureType.BakedDirectional) && serializedProperty.intValue == 2; + if (flag) + { + GUIContent gUIContent = GUIContent.Temp("Indirect"); + Rect position2 = rect; + position2.x += rect.width; + position2.width = EditorStyles.toolbarButton.CalcSize(gUIContent).x; + this.m_HasSeparateIndirectUV = GUI.Toggle(position2, this.m_HasSeparateIndirectUV, gUIContent.text, EditorStyles.toolbarButton); + } + Event current = Event.current; + EventType type = current.type; + if (type != EventType.ValidateCommand && type != EventType.ExecuteCommand) + { + if (type == EventType.Repaint) + { + Texture2D texture2D = list[num]; + if (texture2D && Event.current.type == EventType.Repaint) + { + Rect rect3 = new Rect(0f, 0f, (float)texture2D.width, (float)texture2D.height); + rect3 = this.ResizeRectToFit(rect3, rect2); + rect3 = this.CenterToRect(rect3, rect2); + rect3 = this.ScaleRectByZoomableArea(rect3, this.m_ZoomablePreview); + Rect position3 = new Rect(rect3); + position3.x += 3f; + position3.y += rect2.y + 20f; + Rect drawableArea = new Rect(rect2); + drawableArea.y += rect.height + 3f; + float num2 = drawableArea.y - 14f; + position3.y -= num2; + drawableArea.y -= num2; + texture2D.filterMode = FilterMode.Point; + GITextureType textureType2 = this.kObjectPreviewTextureTypes[num]; + bool drawSpecularUV = flag && this.m_HasSeparateIndirectUV; + LightmapVisualizationUtility.DrawTextureWithUVOverlay(texture2D, Selection.activeGameObject, drawableArea, position3, textureType2, drawSpecularUV); + } + } + } + else + { + if (Event.current.commandName == "FrameSelected") + { + Vector4 lightmapTilingOffset = LightmapVisualizationUtility.GetLightmapTilingOffset(lightmapType); + Vector2 vector = new Vector2(lightmapTilingOffset.z, lightmapTilingOffset.w); + Vector2 lhs = vector + new Vector2(lightmapTilingOffset.x, lightmapTilingOffset.y); + vector = Vector2.Max(vector, Vector2.zero); + lhs = Vector2.Min(lhs, Vector2.one); + float y = 1f - vector.y; + vector.y = 1f - lhs.y; + lhs.y = y; + Rect shownArea = new Rect(vector.x, vector.y, lhs.x - vector.x, lhs.y - vector.y); + shownArea.x -= Mathf.Clamp(shownArea.height - shownArea.width, 0f, 3.40282347E+38f) / 2f; + shownArea.y -= Mathf.Clamp(shownArea.width - shownArea.height, 0f, 3.40282347E+38f) / 2f; + float num3 = Mathf.Max(shownArea.width, shownArea.height); + shownArea.height = num3; + shownArea.width = num3; + if (flag && this.m_HasSeparateIndirectUV) + { + shownArea.x += 0.5f; + } + this.m_ZoomablePreview.shownArea = shownArea; + Event.current.Use(); + } + } + if (this.m_PreviousSelection != Selection.activeInstanceID) + { + this.m_PreviousSelection = Selection.activeInstanceID; + this.m_ZoomablePreview.SetShownHRange(0f, 1f); + this.m_ZoomablePreview.SetShownVRange(0f, 1f); + } + Rect rect4 = new Rect(r); + rect4.yMin += rect.height; + this.m_ZoomablePreview.rect = rect4; + this.m_ZoomablePreview.BeginViewGUI(); + this.m_ZoomablePreview.EndViewGUI(); + GUILayoutUtility.GetRect(r.width, r.height); + } + public bool EditLights() + { + GameObject[] array; + Light[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length == 0) + { + return false; + } + EditorGUILayout.InspectorTitlebar(selectedObjectsOfType); + this.GetLightEditor(selectedObjectsOfType).OnInspectorGUI(); + GUILayout.Space(10f); + return true; + } + public bool EditLightmapParameters() + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(LightmapParameters), SelectionMode.Unfiltered); + if (filtered.Length == 0) + { + return false; + } + EditorGUILayout.MultiSelectionObjectTitleBar(filtered); + this.GetLightmapParametersEditor(filtered).OnInspectorGUI(); + GUILayout.Space(10f); + return true; + } + public bool EditTerrains() + { + GameObject[] array; + Terrain[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); + if (array.Length == 0) + { + return false; + } + EditorGUILayout.InspectorTitlebar(selectedObjectsOfType); + SerializedObject serializedObject = new SerializedObject(array); + EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject.FindProperty("m_StaticEditorFlags"), 1)); + if (GUI.enabled) + { + this.ShowTerrainChunks(selectedObjectsOfType); + } + SerializedObject serializedObject2 = new SerializedObject(selectedObjectsOfType.ToArray()); + float lightmapScale = this.LightmapScaleGUI(serializedObject2, 1f); + TerrainData terrainData = selectedObjectsOfType[0].terrainData; + float cachedSurfaceArea = (!(terrainData != null)) ? 0f : (terrainData.size.x * terrainData.size.z); + this.ShowClampedSizeInLightmapGUI(lightmapScale, cachedSurfaceArea); + LightingWindowObjectTab.LightmapParametersGUI(serializedObject2.FindProperty("m_LightmapParameters"), LightingWindowObjectTab.s_Styles.LightmapParameters); + if (GUI.enabled && selectedObjectsOfType.Length == 1 && selectedObjectsOfType[0].terrainData != null) + { + this.ShowBakePerformanceWarning(serializedObject2, selectedObjectsOfType[0]); + } + this.m_ShowBakedLM = EditorGUILayout.Foldout(this.m_ShowBakedLM, LightingWindowObjectTab.s_Styles.Atlas); + if (this.m_ShowBakedLM) + { + this.ShowAtlasGUI(serializedObject2); + } + this.m_ShowRealtimeLM = EditorGUILayout.Foldout(this.m_ShowRealtimeLM, LightingWindowObjectTab.s_Styles.RealtimeLM); + if (this.m_ShowRealtimeLM) + { + this.ShowRealtimeLMGUI(selectedObjectsOfType[0]); + } + serializedObject.ApplyModifiedProperties(); + serializedObject2.ApplyModifiedProperties(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + return true; + } + public bool EditRenderers() + { + GameObject[] array; + Renderer[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[] + { + typeof(MeshRenderer), + typeof(SkinnedMeshRenderer) + }); + if (array.Length == 0) + { + return false; + } + EditorGUILayout.InspectorTitlebar(selectedObjectsOfType); + SerializedObject serializedObject = new SerializedObject(array); + EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject.FindProperty("m_StaticEditorFlags"), 1)); + SerializedObject serializedObject2 = new SerializedObject(selectedObjectsOfType); + float num = LightmapVisualization.GetLightmapLODLevelScale(selectedObjectsOfType[0]); + for (int i = 1; i < selectedObjectsOfType.Length; i++) + { + if (!Mathf.Approximately(num, LightmapVisualization.GetLightmapLODLevelScale(selectedObjectsOfType[i]))) + { + num = 1f; + } + } + float lightmapScale = this.LightmapScaleGUI(serializedObject2, num) * LightmapVisualization.GetLightmapLODLevelScale(selectedObjectsOfType[0]); + float cachedSurfaceArea = (!(selectedObjectsOfType[0] is MeshRenderer)) ? InternalMeshUtil.GetCachedSkinnedMeshSurfaceArea(selectedObjectsOfType[0] as SkinnedMeshRenderer) : InternalMeshUtil.GetCachedMeshSurfaceArea(selectedObjectsOfType[0] as MeshRenderer); + this.ShowClampedSizeInLightmapGUI(lightmapScale, cachedSurfaceArea); + this.RendererUVSettings(serializedObject2); + LightingWindowObjectTab.LightmapParametersGUI(serializedObject2.FindProperty("m_LightmapParameters"), LightingWindowObjectTab.s_Styles.LightmapParameters); + this.m_ShowBakedLM = EditorGUILayout.Foldout(this.m_ShowBakedLM, LightingWindowObjectTab.s_Styles.Atlas); + if (this.m_ShowBakedLM) + { + this.ShowAtlasGUI(serializedObject2); + } + this.m_ShowRealtimeLM = EditorGUILayout.Foldout(this.m_ShowRealtimeLM, LightingWindowObjectTab.s_Styles.RealtimeLM); + if (this.m_ShowRealtimeLM) + { + this.ShowRealtimeLMGUI(serializedObject2, selectedObjectsOfType[0]); + } + if (LightmapEditorSettings.HasZeroAreaMesh(selectedObjectsOfType[0])) + { + EditorGUILayout.HelpBox(LightingWindowObjectTab.s_Styles.ZeroAreaPackingMesh.text, MessageType.Warning); + } + if (LightmapEditorSettings.HasClampedResolution(selectedObjectsOfType[0])) + { + EditorGUILayout.HelpBox(LightingWindowObjectTab.s_Styles.ClampedPackingResolution.text, MessageType.Warning); + } + if (!LightingWindowObjectTab.HasNormals(selectedObjectsOfType[0])) + { + EditorGUILayout.HelpBox(LightingWindowObjectTab.s_Styles.NoNormalsNoLightmapping.text, MessageType.Warning); + } + serializedObject.ApplyModifiedProperties(); + serializedObject2.ApplyModifiedProperties(); + EditorGUI.EndDisabledGroup(); + GUILayout.Space(10f); + return true; + } + public void ObjectSettings() + { + if (LightingWindowObjectTab.s_Styles == null) + { + LightingWindowObjectTab.s_Styles = new LightingWindowObjectTab.Styles(); + } + SceneModeUtility.SearchBar(new Type[] + { + typeof(Light), + typeof(Renderer), + typeof(Terrain) + }); + EditorGUILayout.Space(); + bool flag = false; + flag |= this.EditRenderers(); + flag |= this.EditLightmapParameters(); + flag |= this.EditLights(); + if (!(flag | this.EditTerrains())) + { + GUILayout.Label(LightingWindowObjectTab.s_Styles.EmptySelection, EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private Rect ResizeRectToFit(Rect rect, Rect to) + { + float a = to.width / rect.width; + float b = to.height / rect.height; + float num = Mathf.Min(a, b); + float width = (float)((int)Mathf.Round(rect.width * num)); + float height = (float)((int)Mathf.Round(rect.height * num)); + return new Rect(rect.x, rect.y, width, height); + } + private Rect CenterToRect(Rect rect, Rect to) + { + float num = Mathf.Clamp((float)((int)(to.width - rect.width)) / 2f, 0f, 2.14748365E+09f); + float num2 = Mathf.Clamp((float)((int)(to.height - rect.height)) / 2f, 0f, 2.14748365E+09f); + return new Rect(rect.x + num, rect.y + num2, rect.width, rect.height); + } + private Rect ScaleRectByZoomableArea(Rect rect, ZoomableArea zoomableArea) + { + float num = -(zoomableArea.shownArea.x / zoomableArea.shownArea.width) * rect.width; + float num2 = (zoomableArea.shownArea.y - (1f - zoomableArea.shownArea.height)) / zoomableArea.shownArea.height * rect.height; + float width = rect.width / zoomableArea.shownArea.width; + float height = rect.height / zoomableArea.shownArea.height; + return new Rect(rect.x + num, rect.y + num2, width, height); + } + private void RendererUVSettings(SerializedObject so) + { + SerializedProperty serializedProperty = so.FindProperty("m_PreserveUVs"); + EditorGUILayout.PropertyField(serializedProperty, LightingWindowObjectTab.s_Styles.PreserveUVs, new GUILayoutOption[0]); + bool boolValue = serializedProperty.boolValue; + EditorGUI.BeginDisabledGroup(boolValue); + SerializedProperty serializedProperty2 = so.FindProperty("m_AutoUVMaxDistance"); + EditorGUILayout.PropertyField(serializedProperty2, LightingWindowObjectTab.s_Styles.AutoUVMaxDistance, new GUILayoutOption[0]); + if (serializedProperty2.floatValue < 0f) + { + serializedProperty2.floatValue = 0f; + } + EditorGUILayout.Slider(so.FindProperty("m_AutoUVMaxAngle"), 0f, 180f, LightingWindowObjectTab.s_Styles.AutoUVMaxAngle, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUILayout.PropertyField(so.FindProperty("m_ImportantGI"), LightingWindowObjectTab.s_Styles.ImportantGI, new GUILayoutOption[0]); + } + private void ShowClampedSizeInLightmapGUI(float lightmapScale, float cachedSurfaceArea) + { + float num = Mathf.Sqrt(cachedSurfaceArea) * LightmapEditorSettings.bakeResolution * lightmapScale; + float num2 = (float)Math.Min(LightmapEditorSettings.maxAtlasWidth, LightmapEditorSettings.maxAtlasHeight); + this.m_ShowClampedSize.target = (num > num2); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowClampedSize.faded)) + { + GUILayout.Label(LightingWindowObjectTab.s_Styles.ClampedSize, EditorStyles.helpBox, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + } + private float LightmapScaleGUI(SerializedObject so, float lodScale) + { + SerializedProperty serializedProperty = so.FindProperty("m_ScaleInLightmap"); + float num = lodScale * serializedProperty.floatValue; + Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); + EditorGUI.BeginProperty(controlRect, LightingWindowObjectTab.s_Styles.ScaleInLightmap, serializedProperty); + EditorGUI.BeginChangeCheck(); + num = EditorGUI.FloatField(controlRect, LightingWindowObjectTab.s_Styles.ScaleInLightmap, num); + if (EditorGUI.EndChangeCheck()) + { + serializedProperty.floatValue = Mathf.Max(num / lodScale, 0f); + } + EditorGUI.EndProperty(); + return num; + } + private void ShowAtlasGUI(SerializedObject so) + { + EditorGUI.indentLevel++; + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.AtlasIndex, new GUIContent(so.FindProperty("m_LightmapIndex").intValue.ToString()), new GUILayoutOption[0]); + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.AtlasTilingX, new GUIContent(so.FindProperty("m_LightmapTilingOffset.x").floatValue.ToString()), new GUILayoutOption[0]); + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.AtlasTilingY, new GUIContent(so.FindProperty("m_LightmapTilingOffset.y").floatValue.ToString()), new GUILayoutOption[0]); + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.AtlasOffsetX, new GUIContent(so.FindProperty("m_LightmapTilingOffset.z").floatValue.ToString()), new GUILayoutOption[0]); + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.AtlasOffsetY, new GUIContent(so.FindProperty("m_LightmapTilingOffset.w").floatValue.ToString()), new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + private void ShowRealtimeLMGUI(SerializedObject so, Renderer renderer) + { + EditorGUI.indentLevel++; + Hash128 hash; + if (LightmapEditorSettings.GetInstanceHash(renderer, out hash)) + { + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMInstanceHash, new GUIContent(hash.ToString()), new GUILayoutOption[0]); + } + Hash128 hash2; + if (LightmapEditorSettings.GetGeometryHash(renderer, out hash2)) + { + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMGeometryHash, new GUIContent(hash2.ToString()), new GUILayoutOption[0]); + } + int num; + int num2; + if (LightmapEditorSettings.GetInstanceResolution(renderer, out num, out num2)) + { + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMInstanceResolution, new GUIContent(num.ToString() + "x" + num2.ToString()), new GUILayoutOption[0]); + } + Hash128 hash3; + if (LightmapEditorSettings.GetInputSystemHash(renderer, out hash3)) + { + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMInputSystemHash, new GUIContent(hash3.ToString()), new GUILayoutOption[0]); + } + int num3; + int num4; + if (LightmapEditorSettings.GetSystemResolution(renderer, out num3, out num4)) + { + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMResolution, new GUIContent(num3.ToString() + "x" + num4.ToString()), new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + } + private static bool HasNormals(Renderer renderer) + { + Mesh mesh = null; + if (renderer is MeshRenderer) + { + MeshFilter component = renderer.GetComponent(); + if (component != null) + { + mesh = component.sharedMesh; + } + } + else + { + if (renderer is SkinnedMeshRenderer) + { + mesh = (renderer as SkinnedMeshRenderer).sharedMesh; + } + } + return InternalMeshUtil.HasNormals(mesh); + } + private void ShowTerrainChunks(Terrain[] terrains) + { + int num = 0; + int num2 = 0; + for (int i = 0; i < terrains.Length; i++) + { + Terrain terrain = terrains[i]; + int num3 = 0; + int num4 = 0; + Lightmapping.GetTerrainGIChunks(terrain, ref num3, ref num4); + if (num == 0 && num2 == 0) + { + num = num3; + num2 = num4; + } + else + { + if (num != num3 || num2 != num4) + { + num2 = (num = 0); + break; + } + } + } + if (num * num2 > 1) + { + GUILayout.Label(string.Format("Terrain is chunked up into {0} instances for baking.", num * num2), EditorStyles.helpBox, new GUILayoutOption[0]); + } + } + private void ShowBakePerformanceWarning(SerializedObject so, Terrain terrain) + { + float x = terrain.terrainData.size.x; + float z = terrain.terrainData.size.z; + LightmapParameters lightmapParameters = ((LightmapParameters)so.FindProperty("m_LightmapParameters").objectReferenceValue) ?? new LightmapParameters(); + float num = x * lightmapParameters.resolution * LightmapEditorSettings.resolution; + float num2 = z * lightmapParameters.resolution * LightmapEditorSettings.resolution; + if (num > 512f || num2 > 512f) + { + EditorGUILayout.HelpBox("Baking resolution for this terrain probably is TOO HIGH. Try use a lower resolution parameter set otherwise it may take long or even infinite time to bake and memory consumption during baking may get greatly increased as well.", MessageType.Warning); + } + float num3 = num * lightmapParameters.clusterResolution; + float num4 = num2 * lightmapParameters.clusterResolution; + float num5 = (float)terrain.terrainData.heightmapResolution / num3; + float num6 = (float)terrain.terrainData.heightmapResolution / num4; + if (num5 > 51.2f || num6 > 51.2f) + { + EditorGUILayout.HelpBox("Baking resolution for this terrain probably is TOO LOW. If it takes long time in Clustering stage, try use a higher resolution parameter set.", MessageType.Warning); + } + } + private void ShowRealtimeLMGUI(Terrain terrain) + { + EditorGUI.indentLevel++; + int num; + int num2; + int num3; + int num4; + if (LightmapEditorSettings.GetTerrainSystemResolution(terrain, out num, out num2, out num3, out num4)) + { + string text = num.ToString() + "x" + num2.ToString(); + if (num3 > 1 || num4 > 1) + { + text += string.Format(" ({0}x{1} chunks)", num3, num4); + } + EditorGUILayout.LabelField(LightingWindowObjectTab.s_Styles.RealtimeLMResolution, new GUIContent(text), new GUILayoutOption[0]); + } + EditorGUI.indentLevel--; + } + public static bool LightmapParametersGUI(SerializedProperty prop, GUIContent content) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUIInternal.AssetPopup(prop, content, "giparams"); + EditorGUI.BeginDisabledGroup(prop.objectReferenceValue == null); + bool result = false; + if (GUILayout.Button("Edit...", EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + Selection.activeObject = prop.objectReferenceValue; + result = true; + } + EditorGUI.EndDisabledGroup(); + EditorGUILayout.EndHorizontal(); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/LightmapBakeQuality.cs b/UnityEditor/UnityEditor/LightmapBakeQuality.cs index bd1d0d9a..dbd2704f 100644 --- a/UnityEditor/UnityEditor/LightmapBakeQuality.cs +++ b/UnityEditor/UnityEditor/LightmapBakeQuality.cs @@ -1,6 +1,7 @@ using System; namespace UnityEditor { + [Obsolete("LightmapBakeQuality has been deprecated.", false)] public enum LightmapBakeQuality { High, diff --git a/UnityEditor/UnityEditor/LightmapEditorSettings.cs b/UnityEditor/UnityEditor/LightmapEditorSettings.cs index c1e037a1..9db73b5a 100644 --- a/UnityEditor/UnityEditor/LightmapEditorSettings.cs +++ b/UnityEditor/UnityEditor/LightmapEditorSettings.cs @@ -5,7 +5,7 @@ namespace UnityEditor { public sealed class LightmapEditorSettings { - public static extern float bounceBoost + public static extern int maxAtlasWidth { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -14,7 +14,7 @@ public static extern float bounceBoost [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern float bounceIntensity + public static extern int maxAtlasHeight { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -23,7 +23,7 @@ public static extern float bounceIntensity [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern int maxAtlasWidth + public static extern float resolution { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -32,7 +32,7 @@ public static extern int maxAtlasWidth [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern int maxAtlasHeight + public static extern float bakeResolution { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -41,7 +41,7 @@ public static extern int maxAtlasHeight [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern float resolution + public static extern bool textureCompression { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -50,7 +50,7 @@ public static extern float resolution [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern float lastUsedResolution + public static extern float aoMaxDistance { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -59,142 +59,199 @@ public static extern float lastUsedResolution [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static Color skyLightColor + public static extern int padding + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("LightmapEditorSettings.aoContrast has been deprecated.", false)] + public static float aoContrast { get { - Color result; - LightmapEditorSettings.INTERNAL_get_skyLightColor(out result); - return result; + return 0f; } set { - LightmapEditorSettings.INTERNAL_set_skyLightColor(ref value); } } - public static extern float skyLightIntensity + [Obsolete("LightmapEditorSettings.aoAmount has been deprecated.", false)] + public static float aoAmount { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern LightmapBakeQuality quality + [Obsolete("LightmapEditorSettings.lockAtlas has been deprecated.", false)] + public static bool lockAtlas { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return false; + } + set + { + } } - public static extern bool textureCompression + [Obsolete("LightmapEditorSettings.skyLightColor has been deprecated.", false)] + public static Color skyLightColor { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return Color.black; + } + set + { + } } - public static extern int bounces + [Obsolete("LightmapEditorSettings.skyLightIntensity has been deprecated.", false)] + public static float skyLightIntensity { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern int finalGatherRays + [Obsolete("LightmapEditorSettings.quality has been deprecated.", false)] + public static LightmapBakeQuality quality { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return LightmapBakeQuality.High; + } + set + { + } } - public static extern float finalGatherContrastThreshold + [Obsolete("LightmapEditorSettings.bounceBoost has been deprecated.", false)] + public static float bounceBoost { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern float finalGatherGradientThreshold + [Obsolete("LightmapEditorSettings.finalGatherRays has been deprecated.", false)] + public static int finalGatherRays { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0; + } + set + { + } } - public static extern int finalGatherInterpolationPoints + [Obsolete("LightmapEditorSettings.finalGatherContrastThreshold has been deprecated.", false)] + public static float finalGatherContrastThreshold { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern float aoAmount + [Obsolete("LightmapEditorSettings.finalGatherGradientThreshold has been deprecated.", false)] + public static float finalGatherGradientThreshold { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern float aoMaxDistance + [Obsolete("LightmapEditorSettings.finalGatherInterpolationPoints has been deprecated.", false)] + public static int finalGatherInterpolationPoints { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0; + } + set + { + } } - public static extern float aoContrast + [Obsolete("LightmapEditorSettings.lastUsedResolution has been deprecated.", false)] + public static float lastUsedResolution { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } - public static extern bool lockAtlas + [Obsolete("LightmapEditorSettings.bounces has been deprecated.", false)] + public static int bounces { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0; + } + set + { + } } - public static extern int padding + [Obsolete("LightmapEditorSettings.bounceIntensity has been deprecated.", false)] + public static float bounceIntensity { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return 0f; + } + set + { + } } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_get_skyLightColor(out Color value); + internal static extern void Reset(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool IsLightmappedOrDynamicLightmappedForRendering(Renderer renderer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasZeroAreaMesh(Renderer renderer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool HasClampedResolution(Renderer renderer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetSystemResolution(Renderer renderer, out int width, out int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetTerrainSystemResolution(Terrain terrain, out int width, out int height, out int numChunksInX, out int numChunksInY); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetInstanceResolution(Renderer renderer, out int width, out int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetInputSystemHash(Renderer renderer, out Hash128 inputSystemHash); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetInstanceHash(Renderer renderer, out Hash128 instanceHash); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_set_skyLightColor(ref Color value); + internal static extern bool GetGeometryHash(Renderer renderer, out Hash128 geometryHash); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern UnityEngine.Object GetLightmapSettings(); diff --git a/UnityEditor/UnityEditor/LightmapParameters.cs b/UnityEditor/UnityEditor/LightmapParameters.cs new file mode 100644 index 00000000..bde56b3f --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapParameters.cs @@ -0,0 +1,151 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class LightmapParameters : UnityEngine.Object + { + public extern float resolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float clusterResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int irradianceBudget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int irradianceQuality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float backFaceTolerance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float modellingTolerance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float edgeStitching + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int systemTag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool isTransparent + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int AOQuality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int AOAntiAliasingSamples + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int blurRadius + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int directLightQuality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int antiAliasingSamples + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int bakedLightmapTag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public LightmapParameters() + { + LightmapParameters.Internal_CreateLightmapParameters(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateLightmapParameters([Writable] LightmapParameters self); + } +} diff --git a/UnityEditor/UnityEditor/LightmapParametersEditor.cs b/UnityEditor/UnityEditor/LightmapParametersEditor.cs new file mode 100644 index 00000000..38afc1fd --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapParametersEditor.cs @@ -0,0 +1,89 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(LightmapParameters))] + internal class LightmapParametersEditor : Editor + { + private class Styles + { + public static readonly GUIContent precomputedRealtimeGIContent = EditorGUIUtility.TextContent("LightmapEditor.RealtimeGILabel"); + public static readonly GUIContent resolutionContent = EditorGUIUtility.TextContent("LightmapParametersEditor.Resolution"); + public static readonly GUIContent clusterResolutionContent = EditorGUIUtility.TextContent("LightmapParametersEditor.ClusterResolution"); + public static readonly GUIContent irradianceBudgetContent = EditorGUIUtility.TextContent("LightmapParametersEditor.IrradianceBudget"); + public static readonly GUIContent irradianceQualityContent = EditorGUIUtility.TextContent("LightmapParametersEditor.IrradianceQuality"); + public static readonly GUIContent backFaceToleranceContent = EditorGUIUtility.TextContent("LightmapParametersEditor.BackFaceTolerance"); + public static readonly GUIContent modellingToleranceContent = EditorGUIUtility.TextContent("LightmapParametersEditor.ModellingTolerance"); + public static readonly GUIContent edgeStitchingContent = EditorGUIUtility.TextContent("LightmapParametersEditor.EdgeStitching"); + public static readonly GUIContent systemTagContent = EditorGUIUtility.TextContent("LightmapParametersEditor.SystemTag"); + public static readonly GUIContent bakedGIContent = EditorGUIUtility.TextContent("LightmapEditor.BakedGILabel"); + public static readonly GUIContent blurRadiusContent = EditorGUIUtility.TextContent("LightmapParametersEditor.BlurRadius"); + public static readonly GUIContent antiAliasingSamplesContent = EditorGUIUtility.TextContent("LightmapParametersEditor.AntiAliasingSamples"); + public static readonly GUIContent directLightQualityContent = EditorGUIUtility.TextContent("LightmapParametersEditor.DirectLightQuality"); + public static readonly GUIContent bakedAOContent = EditorGUIUtility.TextContent("LightmapParametersEditor.BakedAO"); + public static readonly GUIContent aoQualityContent = EditorGUIUtility.TextContent("LightmapParametersEditor.AOQuality"); + public static readonly GUIContent aoAntiAliasingSamplesContent = EditorGUIUtility.TextContent("LightmapParametersEditor.AOAntiAliasingSamples"); + public static readonly GUIContent isTransparent = EditorGUIUtility.TextContent("LightmapParametersEditor.IsTransparent"); + public static readonly GUIContent bakedLightmapTagContent = EditorGUIUtility.TextContent("LightmapParametersEditor.BakedLightmapTag"); + } + private SerializedProperty m_Resolution; + private SerializedProperty m_ClusterResolution; + private SerializedProperty m_IrradianceBudget; + private SerializedProperty m_IrradianceQuality; + private SerializedProperty m_BackFaceTolerance; + private SerializedProperty m_ModellingTolerance; + private SerializedProperty m_EdgeStitching; + private SerializedProperty m_SystemTag; + private SerializedProperty m_IsTransparent; + private SerializedProperty m_AOQuality; + private SerializedProperty m_AOAntiAliasingSamples; + private SerializedProperty m_BlurRadius; + private SerializedProperty m_AntiAliasingSamples; + private SerializedProperty m_DirectLightQuality; + private SerializedProperty m_BakedLightmapTag; + public void OnEnable() + { + this.m_Resolution = base.serializedObject.FindProperty("resolution"); + this.m_ClusterResolution = base.serializedObject.FindProperty("clusterResolution"); + this.m_IrradianceBudget = base.serializedObject.FindProperty("irradianceBudget"); + this.m_IrradianceQuality = base.serializedObject.FindProperty("irradianceQuality"); + this.m_BackFaceTolerance = base.serializedObject.FindProperty("backFaceTolerance"); + this.m_ModellingTolerance = base.serializedObject.FindProperty("modellingTolerance"); + this.m_EdgeStitching = base.serializedObject.FindProperty("edgeStitching"); + this.m_IsTransparent = base.serializedObject.FindProperty("isTransparent"); + this.m_SystemTag = base.serializedObject.FindProperty("systemTag"); + this.m_AOQuality = base.serializedObject.FindProperty("AOQuality"); + this.m_AOAntiAliasingSamples = base.serializedObject.FindProperty("AOAntiAliasingSamples"); + this.m_BlurRadius = base.serializedObject.FindProperty("blurRadius"); + this.m_AntiAliasingSamples = base.serializedObject.FindProperty("antiAliasingSamples"); + this.m_DirectLightQuality = base.serializedObject.FindProperty("directLightQuality"); + this.m_BakedLightmapTag = base.serializedObject.FindProperty("bakedLightmapTag"); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + GUILayout.Label(LightmapParametersEditor.Styles.precomputedRealtimeGIContent, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Resolution, LightmapParametersEditor.Styles.resolutionContent, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ClusterResolution, 0.1f, 1f, LightmapParametersEditor.Styles.clusterResolutionContent, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_IrradianceBudget, 32, 2048, LightmapParametersEditor.Styles.irradianceBudgetContent, new GUILayoutOption[0]); + EditorGUILayout.IntSlider(this.m_IrradianceQuality, 512, 131072, LightmapParametersEditor.Styles.irradianceQualityContent, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_BackFaceTolerance, 0f, 1f, LightmapParametersEditor.Styles.backFaceToleranceContent, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_ModellingTolerance, 0f, 1f, LightmapParametersEditor.Styles.modellingToleranceContent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_EdgeStitching, LightmapParametersEditor.Styles.edgeStitchingContent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IsTransparent, LightmapParametersEditor.Styles.isTransparent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SystemTag, LightmapParametersEditor.Styles.systemTagContent, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(LightmapParametersEditor.Styles.bakedGIContent, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BlurRadius, LightmapParametersEditor.Styles.blurRadiusContent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AntiAliasingSamples, LightmapParametersEditor.Styles.antiAliasingSamplesContent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DirectLightQuality, LightmapParametersEditor.Styles.directLightQualityContent, new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(LightmapParametersEditor.Styles.bakedAOContent, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AOQuality, LightmapParametersEditor.Styles.aoQualityContent, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AOAntiAliasingSamples, LightmapParametersEditor.Styles.aoAntiAliasingSamplesContent, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_BakedLightmapTag, LightmapParametersEditor.Styles.bakedLightmapTagContent, new GUILayoutOption[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/LightmapVisualization.cs b/UnityEditor/UnityEditor/LightmapVisualization.cs index bb2419a9..10507ca1 100644 --- a/UnityEditor/UnityEditor/LightmapVisualization.cs +++ b/UnityEditor/UnityEditor/LightmapVisualization.cs @@ -14,15 +14,6 @@ public static extern bool enabled [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern float shadowDistance - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public static extern bool useLightmaps { [WrapperlessIcall] diff --git a/UnityEditor/UnityEditor/LightmapVisualizationUtility.cs b/UnityEditor/UnityEditor/LightmapVisualizationUtility.cs new file mode 100644 index 00000000..662d77d1 --- /dev/null +++ b/UnityEditor/UnityEditor/LightmapVisualizationUtility.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngineInternal; +namespace UnityEditor +{ + internal sealed class LightmapVisualizationUtility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Vector4 GetLightmapTilingOffset(LightmapType lightmapType); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Texture2D GetGITexture(GITextureType textureType); + public static void DrawTextureWithUVOverlay(Texture2D texture, GameObject gameObject, Rect drawableArea, Rect position, GITextureType textureType, bool drawSpecularUV) + { + LightmapVisualizationUtility.INTERNAL_CALL_DrawTextureWithUVOverlay(texture, gameObject, ref drawableArea, ref position, textureType, drawSpecularUV); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawTextureWithUVOverlay(Texture2D texture, GameObject gameObject, ref Rect drawableArea, ref Rect position, GITextureType textureType, bool drawSpecularUV); + } +} diff --git a/UnityEditor/UnityEditor/Lightmapping.cs b/UnityEditor/UnityEditor/Lightmapping.cs index 9e4d45c1..2394066c 100644 --- a/UnityEditor/UnityEditor/Lightmapping.cs +++ b/UnityEditor/UnityEditor/Lightmapping.cs @@ -5,6 +5,104 @@ namespace UnityEditor { public sealed class Lightmapping { + internal enum ConcurrentJobsType + { + Min, + Low, + High + } + public enum GIWorkflowMode + { + Iterative, + OnDemand, + Legacy + } + public delegate void OnCompletedFunction(); + public static Lightmapping.OnCompletedFunction completed; + public static extern Lightmapping.GIWorkflowMode giWorkflowMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool realtimeLightmapsEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool bakedLightmapsEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool openRLEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern Lightmapping.ConcurrentJobsType concurrentJobsType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern long diskCacheSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern string diskCachePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern bool enlightenForceWhiteAlbedo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool enlightenForceUpdates + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern FilterMode filterMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool isRunning { [WrapperlessIcall] @@ -13,6 +111,15 @@ public static extern bool isRunning } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearDiskCache(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateCachePath(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void PrintStateToConsole(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool BakeAsync(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -32,11 +139,30 @@ public static extern bool isRunning [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Cancel(); + private static void Internal_CallCompletedFunctions() + { + if (Lightmapping.completed != null) + { + Lightmapping.completed(); + } + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Clear(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Tetrahedralize(Vector3[] positions, out int[] outIndices, out Vector3[] outPositions); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BakeReflectionProbe(ReflectionProbe probe, string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool BakeReflectionProbeSnapshot(ReflectionProbe probe); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool BakeAllReflectionProbesSnapshots(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetTerrainGIChunks(Terrain terrain, ref int numChunksX, ref int numChunksY); } } diff --git a/UnityEditor/UnityEditor/LightmappingWindow.cs b/UnityEditor/UnityEditor/LightmappingWindow.cs deleted file mode 100644 index 02099832..00000000 --- a/UnityEditor/UnityEditor/LightmappingWindow.cs +++ /dev/null @@ -1,1212 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEditor.AnimatedValues; -using UnityEditorInternal; -using UnityEngine; -using UnityEngine.Events; -namespace UnityEditor -{ - internal class LightmappingWindow : EditorWindow, IHasCustomMenu - { - private enum Mode - { - ObjectSettings, - BakeSettings, - Maps - } - private enum BakeMode - { - BakeScene, - BakeSelected, - BakeProbes - } - private class Styles - { - public GUIContent[] ModeToggles = new GUIContent[] - { - EditorGUIUtility.TextContent("LightmapEditor.ObjectSettings"), - EditorGUIUtility.TextContent("LightmapEditor.BakeSettings"), - EditorGUIUtility.TextContent("LightmapEditor.Maps") - }; - public GUIContent UseDualInForward = EditorGUIUtility.TextContent("LightmapEditor.UseDualInForward"); - public GUIContent SkyLightColor = EditorGUIUtility.TextContent("LightmapEditor.SkyLightColor"); - public GUIContent LODSurfaceDistance = EditorGUIUtility.TextContent("LightmapEditor.LODSurfaceDistance"); - public GUIContent SkyLightIntensity = EditorGUIUtility.TextContent("LightmapEditor.SkyLightIntensity"); - public GUIContent Bounces = EditorGUIUtility.TextContent("LightmapEditor.Bounces"); - public GUIContent BounceBoost = EditorGUIUtility.TextContent("LightmapEditor.BounceBoost"); - public GUIContent BounceIntensity = EditorGUIUtility.TextContent("LightmapEditor.BounceIntensity"); - public GUIContent Quality = EditorGUIUtility.TextContent("LightmapEditor.Quality"); - public GUIContent FinalGatherRays = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.Rays"); - public GUIContent FinalGatherContrastThreshold = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.ContrastThreshold"); - public GUIContent FinalGatherGradientThreshold = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.GradientThreshold"); - public GUIContent FinalGatherInterpolationPoints = EditorGUIUtility.TextContent("LightmapEditor.FinalGather.InterpolationPoints"); - public GUIContent Resolution = EditorGUIUtility.TextContent("LightmapEditor.Resolution"); - public GUIContent EmptySelection = EditorGUIUtility.TextContent("LightmapEditor.EmptySelection"); - public GUIContent ScaleInLightmap = EditorGUIUtility.TextContent("LightmapEditor.ScaleInLightmap"); - public GUIContent Static = EditorGUIUtility.TextContent("LightmapEditor.Static"); - public GUIContent LightShadows = EditorGUIUtility.TextContent("LightmapEditor.Light.Shadows"); - public GUIContent LightIndirectIntensity = EditorGUIUtility.TextContent("LightmapEditor.Light.IndirectIntensity"); - public GUIContent LightShadowSamples = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowSamples"); - public GUIContent LightShadowRadius = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowRadius"); - public GUIContent LightShadowAngle = EditorGUIUtility.TextContent("LightmapEditor.Light.ShadowAngle"); - public GUIContent TerrainLightmapSize = EditorGUIUtility.TextContent("LightmapEditor.Terrain.LightmapSize"); - public GUIContent AO = EditorGUIUtility.TextContent("LightmapEditor.AO"); - public GUIContent AOMaxDistance = EditorGUIUtility.TextContent("LightmapEditor.AOMaxDistance"); - public GUIContent AOContrast = EditorGUIUtility.TextContent("LightmapEditor.AOContrast"); - public GUIContent MapsArraySize = EditorGUIUtility.TextContent("LightmapEditor.MapsArraySize"); - public GUIContent Mode = EditorGUIUtility.TextContent("LightmapEditor.Mode"); - public GUIContent LockAtlas = EditorGUIUtility.TextContent("LightmapEditor.LockAtlas"); - public GUIContent Atlas = EditorGUIUtility.TextContent("LightmapEditor.Atlas"); - public GUIContent AtlasIndex = EditorGUIUtility.TextContent("LightmapEditor.AtlasIndex"); - public GUIContent AtlasTilingX = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingX"); - public GUIContent AtlasTilingY = EditorGUIUtility.TextContent("LightmapEditor.AtlasTilingY"); - public GUIContent AtlasOffsetX = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetX"); - public GUIContent AtlasOffsetY = EditorGUIUtility.TextContent("LightmapEditor.AtlasOffsetY"); - public GUIContent TextureCompression = EditorGUIUtility.TextContent("LightmapEditor.TextureCompression"); - public GUIContent ClampedSize = EditorGUIUtility.TextContent("LightmapEditor.ClampedSize"); - public GUIContent NoNormalsNoLightmapping = EditorGUIUtility.TextContent("LightmapEditor.NoNormalsNoLightmapping"); - public GUIContent DirectionalLightmapsProOnly = EditorGUIUtility.TextContent("LightmapEditor.DirectionalLightmapsProOnly"); - public GUIContent IncorrectLightProbePositions = EditorGUIUtility.TextContent("LightmapEditor.IncorrectLightProbePositions"); - public GUIContent Padding = EditorGUIUtility.TextContent("LightmapEditor.Padding"); - public GUIContent LightProbes = EditorGUIUtility.TextContent("LightmapEditor.LightProbes"); - public GUIStyle selectedLightmapHighlight = "LightmapEditorSelectedHighlight"; - public GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; - public GUIStyle dropDownButton = "DropDownButton"; - } - private const string kBakeModeKey = "LightmapEditor.BakeMode"; - private const string kBeastSettingsFileName = "BeastSettings.xml"; - private int[] kModeValues = new int[] - { - 0, - 1, - 2 - }; - private GUIContent[] kModeStrings = new GUIContent[] - { - new GUIContent("Single Lightmaps"), - new GUIContent("Dual Lightmaps"), - new GUIContent("Directional Lightmaps") - }; - private GUIContent[] kBouncesStrings = new GUIContent[] - { - new GUIContent("0"), - new GUIContent("1"), - new GUIContent("2"), - new GUIContent("3"), - new GUIContent("4") - }; - private int[] kBouncesValues = new int[] - { - 0, - 1, - 2, - 3, - 4 - }; - private GUIContent[] kQualityStrings = new GUIContent[] - { - new GUIContent("High"), - new GUIContent("Low") - }; - private int[] kQualityValues = new int[] - { - 0, - 1 - }; - private GUIContent[] kShadowTypeStrings = new GUIContent[] - { - new GUIContent("Off"), - new GUIContent("On (Realtime: Hard Shadows)"), - new GUIContent("On (Realtime: Soft Shadows)") - }; - private int[] kShadowTypeValues = new int[] - { - 0, - 1, - 2 - }; - private GUIContent[] kTerrainLightmapSizeStrings = new GUIContent[] - { - new GUIContent("0"), - new GUIContent("32"), - new GUIContent("64"), - new GUIContent("128"), - new GUIContent("256"), - new GUIContent("512"), - new GUIContent("1024"), - new GUIContent("2048"), - new GUIContent("4096") - }; - private int[] kTerrainLightmapSizeValues = new int[] - { - 0, - 32, - 64, - 128, - 256, - 512, - 1024, - 2048, - 4096 - }; - private static LightmappingWindow s_LightmappingWindow; - private readonly LightProbeGUI m_LightProbeEditor = new LightProbeGUI(); - private Vector2 m_ScrollPosition = Vector2.zero; - private Vector2 m_ScrollPositionLightmaps = Vector2.zero; - private Vector2 m_ScrollPositionMaps = Vector2.zero; - private float m_OldResolution = -1f; - private LightmappingWindow.Mode m_Mode; - private int m_SelectedLightmap = -1; - private float m_BakeStartTime = -1f; - private string m_LastBakeTimeString = string.Empty; - private AnimBool m_ShowDualOptions = new AnimBool(); - private AnimBool m_ShowFinalGather = new AnimBool(); - private AnimBool m_ShowShadowOptions = new AnimBool(); - private AnimBool m_ShowShadowAngleOrSize = new AnimBool(); - private AnimBool m_ShowAO = new AnimBool(); - private AnimBool m_ShowClampedSize = new AnimBool(); - private AnimBool m_ShowColorSpaceWarning = new AnimBool(); - private AnimBool m_ShowAreaLight = new AnimBool(); - private bool m_ShowAtlas; - private int m_LastAmountOfLights; - private PreviewResizer m_PreviewResizer = new PreviewResizer(); - private bool m_ProbePositionsChanged = true; - private bool m_IncorrectProbePositions; - private static LightmappingWindow.Styles s_Styles; - private float m_OldQualitySettingsShadowDistance = -1f; - private float m_ShadowDistance = -1f; - private static bool s_IsVisible; - private LightmappingWindow.BakeMode bakeMode - { - get - { - return (LightmappingWindow.BakeMode)EditorPrefs.GetInt("LightmapEditor.BakeMode", 0); - } - set - { - EditorPrefs.SetInt("LightmapEditor.BakeMode", (int)value); - } - } - private static bool colorSpaceWarningValue - { - get - { - return LightmapSettings.bakedColorSpace != QualitySettings.desiredColorSpace && LightmapSettings.lightmaps.Length > 0; - } - } - public static void ProbePositionsChanged() - { - if (LightmappingWindow.s_LightmappingWindow) - { - LightmappingWindow.s_LightmappingWindow.m_ProbePositionsChanged = true; - } - } - private void OnEnable() - { - LightmappingWindow.s_LightmappingWindow = this; - this.m_ShowDualOptions.value = (LightmapSettings.lightmapsMode == LightmapsMode.Dual); - this.m_ShowFinalGather.value = (LightmapEditorSettings.bounces > 0 && InternalEditorUtility.HasPro()); - this.m_ShowShadowOptions.value = true; - this.m_ShowShadowAngleOrSize.value = true; - this.m_ShowAO.value = (LightmapEditorSettings.aoAmount > 0f); - this.m_ShowClampedSize.value = false; - this.m_ShowColorSpaceWarning.value = LightmappingWindow.colorSpaceWarningValue; - this.m_ShowAreaLight.value = false; - this.m_ShowDualOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowFinalGather.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowShadowOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowShadowAngleOrSize.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowAO.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowClampedSize.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowColorSpaceWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); - this.m_ShowAreaLight.valueChanged.AddListener(new UnityAction(base.Repaint)); - base.autoRepaintOnSceneChange = true; - this.m_PreviewResizer.Init("LightmappingPreview"); - EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); - base.Repaint(); - } - private void OnDisable() - { - LightmappingWindow.s_LightmappingWindow = null; - EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); - } - private void OnBecameVisible() - { - if (LightmappingWindow.s_IsVisible) - { - return; - } - LightmappingWindow.s_IsVisible = true; - LightmapVisualization.enabled = true; - LightmapVisualization.showLightProbes = true; - if (this.m_OldQualitySettingsShadowDistance != QualitySettings.shadowDistance) - { - this.m_ShadowDistance = QualitySettings.shadowDistance; - this.m_OldQualitySettingsShadowDistance = this.m_ShadowDistance; - } - LightmapVisualization.shadowDistance = this.m_ShadowDistance; - SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); - LightmappingWindow.RepaintSceneAndGameViews(); - } - private void OnBecameInvisible() - { - LightmappingWindow.s_IsVisible = false; - LightmapVisualization.enabled = false; - LightmapVisualization.showLightProbes = false; - this.m_OldQualitySettingsShadowDistance = QualitySettings.shadowDistance; - SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); - LightmappingWindow.RepaintSceneAndGameViews(); - } - private void OnSelectionChange() - { - this.UpdateLightmapSelection(); - if (this.m_Mode == LightmappingWindow.Mode.ObjectSettings || this.m_Mode == LightmappingWindow.Mode.Maps) - { - base.Repaint(); - } - } - private static void LightmappingDone() - { - if (LightmappingWindow.s_LightmappingWindow) - { - LightmappingWindow.s_LightmappingWindow.MarkEndTime(); - LightmappingWindow.s_LightmappingWindow.Repaint(); - } - Analytics.Track("/LightMapper/Created"); - } - private static void RepaintSceneAndGameViews() - { - SceneView.RepaintAll(); - GameView.RepaintAll(); - } - private void OnGUI() - { - if (LightmappingWindow.s_Styles == null) - { - LightmappingWindow.s_Styles = new LightmappingWindow.Styles(); - } - EditorGUIUtility.labelWidth = 130f; - EditorGUILayout.Space(); - this.ModeToggle(); - EditorGUILayout.Space(); - this.m_ShowColorSpaceWarning.target = LightmappingWindow.colorSpaceWarningValue; - if (EditorGUILayout.BeginFadeGroup(this.m_ShowColorSpaceWarning.faded)) - { - GUIContent gUIContent = EditorGUIUtility.TextContent("LightEditor.WrongColorSpaceWarning"); - EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning); - } - EditorGUILayout.EndFadeGroup(); - this.m_ScrollPosition = EditorGUILayout.BeginScrollView(this.m_ScrollPosition, new GUILayoutOption[0]); - switch (this.m_Mode) - { - case LightmappingWindow.Mode.ObjectSettings: - this.ObjectSettings(); - break; - case LightmappingWindow.Mode.BakeSettings: - this.BakeSettings(); - break; - case LightmappingWindow.Mode.Maps: - this.Maps(); - break; - } - EditorGUILayout.EndScrollView(); - EditorGUILayout.Space(); - if (this.m_ProbePositionsChanged && Event.current.type == EventType.Layout) - { - Vector3[] array; - int[] array2; - LightProbeGroupEditor.TetrahedralizeSceneProbes(out array, out array2); - this.m_IncorrectProbePositions = (array.Length > 0 && array2.Length == 0); - this.m_ProbePositionsChanged = false; - } - if (this.m_IncorrectProbePositions) - { - EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.IncorrectLightProbePositions.text, MessageType.Warning); - } - GUI.enabled = !EditorApplication.isPlayingOrWillChangePlaymode; - this.Buttons(); - GUI.enabled = true; - EditorGUILayout.Space(); - this.Summary(); - EditorGUILayout.BeginHorizontal(GUIContent.none, "preToolbar", new GUILayoutOption[] - { - GUILayout.Height(17f) - }); - GUILayout.FlexibleSpace(); - GUI.Label(GUILayoutUtility.GetLastRect(), "Preview", "preToolbar2"); - EditorGUILayout.EndHorizontal(); - float num = this.m_PreviewResizer.ResizeHandle(base.position, 100f, 250f, 17f); - if (num > 0f) - { - this.Lightmaps(new Rect(0f, base.position.height - num, base.position.width, num)); - } - } - private void ModeToggle() - { - this.m_Mode = (LightmappingWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, LightmappingWindow.s_Styles.ModeToggles, "LargeButton", new GUILayoutOption[0]); - } - public void OnSceneViewGUI(SceneView sceneView) - { - if (!LightmappingWindow.s_IsVisible) - { - return; - } - SceneViewOverlay.Window(new GUIContent("Lightmap Display"), new SceneViewOverlay.WindowFunction(this.DisplayControls), 200, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); - } - private void OnDidOpenScene() - { - } - private void DisplayControls(UnityEngine.Object target, SceneView sceneView) - { - EditorGUIUtility.labelWidth = 110f; - bool useLightmaps = LightmapVisualization.useLightmaps; - if (useLightmaps != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.UseLightmaps"), useLightmaps, new GUILayoutOption[0])) - { - LightmapVisualization.useLightmaps = !useLightmaps; - LightmappingWindow.RepaintSceneAndGameViews(); - } - float num = Mathf.Max(EditorGUILayout.FloatField(EditorGUIUtility.TextContent("LightmapEditor.ShadowDistance"), this.m_ShadowDistance, new GUILayoutOption[0]), 0f); - if (num != this.m_ShadowDistance) - { - this.m_ShadowDistance = num; - LightmapVisualization.shadowDistance = this.m_ShadowDistance; - LightmappingWindow.RepaintSceneAndGameViews(); - } - if (sceneView) - { - DrawCameraMode renderMode = sceneView.renderMode; - bool flag = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.VisualiseResolution"), renderMode == DrawCameraMode.LightmapResolution, new GUILayoutOption[0]); - if (flag && renderMode != DrawCameraMode.LightmapResolution) - { - sceneView.renderMode = DrawCameraMode.LightmapResolution; - sceneView.Repaint(); - } - else - { - if (!flag && renderMode == DrawCameraMode.LightmapResolution) - { - sceneView.renderMode = DrawCameraMode.Textured; - sceneView.Repaint(); - } - } - this.m_LightProbeEditor.DisplayControls(sceneView); - } - else - { - bool enabled = GUI.enabled; - GUI.enabled = false; - EditorGUILayout.Toggle(EditorGUIUtility.TextContent("LightmapEditor.DisplayControls.VisualiseResolution"), false, new GUILayoutOption[0]); - GUI.enabled = enabled; - } - } - private float LightmapScaleGUI(SerializedObject so, Renderer[] renderers) - { - float num = LightmapVisualization.GetLightmapLODLevelScale(renderers[0]); - for (int i = 1; i < renderers.Length; i++) - { - if (!Mathf.Approximately(num, LightmapVisualization.GetLightmapLODLevelScale(renderers[i]))) - { - num = 1f; - } - } - SerializedProperty serializedProperty = so.FindProperty("m_ScaleInLightmap"); - float num2 = num * serializedProperty.floatValue; - Rect controlRect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); - EditorGUI.BeginProperty(controlRect, null, serializedProperty); - EditorGUI.BeginChangeCheck(); - num2 = EditorGUI.FloatField(controlRect, LightmappingWindow.s_Styles.ScaleInLightmap, num2); - if (EditorGUI.EndChangeCheck()) - { - serializedProperty.floatValue = Mathf.Max(num2 / num, 0f); - } - EditorGUI.EndProperty(); - return LightmapVisualization.GetLightmapLODLevelScale(renderers[0]) * num2; - } - private bool HasNormals(Renderer renderer) - { - Mesh mesh = null; - if (renderer is MeshRenderer) - { - MeshFilter component = renderer.GetComponent(); - if (component != null) - { - mesh = component.sharedMesh; - } - } - else - { - if (renderer is SkinnedMeshRenderer) - { - mesh = (renderer as SkinnedMeshRenderer).sharedMesh; - } - } - return InternalMeshUtil.HasNormals(mesh); - } - private void ObjectSettings() - { - bool flag = true; - SceneModeUtility.SearchBar(new Type[] - { - typeof(Light), - typeof(Renderer), - typeof(Terrain) - }); - EditorGUILayout.Space(); - GameObject[] array; - Renderer[] selectedObjectsOfType = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[] - { - typeof(MeshRenderer), - typeof(SkinnedMeshRenderer) - }); - if (array.Length > 0) - { - flag = false; - EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType); - SerializedObject serializedObject = new SerializedObject(array); - EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject.FindProperty("m_StaticEditorFlags"), 1)); - SerializedObject serializedObject2 = new SerializedObject(selectedObjectsOfType); - float num = this.LightmapScaleGUI(serializedObject2, selectedObjectsOfType); - float f = (!(selectedObjectsOfType[0] is MeshRenderer)) ? InternalMeshUtil.GetCachedSkinnedMeshSurfaceArea(selectedObjectsOfType[0] as SkinnedMeshRenderer) : InternalMeshUtil.GetCachedMeshSurfaceArea(selectedObjectsOfType[0] as MeshRenderer); - float num2 = Mathf.Sqrt(f) * LightmapEditorSettings.resolution * num; - float num3 = (float)Math.Min(LightmapEditorSettings.maxAtlasWidth, LightmapEditorSettings.maxAtlasHeight); - this.m_ShowClampedSize.target = (num2 > num3); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowClampedSize.faded)) - { - GUILayout.Label(LightmappingWindow.s_Styles.ClampedSize, EditorStyles.helpBox, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - this.m_ShowAtlas = EditorGUILayout.Foldout(this.m_ShowAtlas, LightmappingWindow.s_Styles.Atlas); - if (this.m_ShowAtlas) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapIndex"), LightmappingWindow.s_Styles.AtlasIndex, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.x"), LightmappingWindow.s_Styles.AtlasTilingX, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.y"), LightmappingWindow.s_Styles.AtlasTilingY, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.z"), LightmappingWindow.s_Styles.AtlasOffsetX, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedObject2.FindProperty("m_LightmapTilingOffset.w"), LightmappingWindow.s_Styles.AtlasOffsetY, new GUILayoutOption[0]); - EditorGUI.indentLevel--; - } - if (!this.HasNormals(selectedObjectsOfType[0])) - { - EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.NoNormalsNoLightmapping.text, MessageType.Warning); - } - serializedObject.ApplyModifiedProperties(); - serializedObject2.ApplyModifiedProperties(); - EditorGUI.EndDisabledGroup(); - GUILayout.Space(10f); - } - Light[] selectedObjectsOfType2 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); - if (array.Length > 0) - { - flag = false; - EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType2.ToArray()); - SerializedObject serializedObject3 = new SerializedObject(selectedObjectsOfType2.ToArray()); - SerializedProperty serializedProperty = serializedObject3.FindProperty("m_Type"); - bool flag2 = !serializedProperty.hasMultipleDifferentValues && selectedObjectsOfType2[0].type == LightType.Area; - if (this.m_LastAmountOfLights > 0) - { - this.m_ShowAreaLight.target = flag2; - } - else - { - this.m_ShowAreaLight.value = flag2; - } - SerializedProperty serializedProperty2 = serializedObject3.FindProperty("m_Lightmapping"); - if (EditorGUILayout.BeginFadeGroup(1f - this.m_ShowAreaLight.faded)) - { - EditorGUILayout.PropertyField(serializedProperty2, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - EditorGUI.BeginDisabledGroup(serializedProperty2.intValue == 0); - EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_Color"), new GUILayoutOption[0]); - EditorGUILayout.Slider(serializedObject3.FindProperty("m_Intensity"), 0f, 8f, new GUILayoutOption[0]); - if (InternalEditorUtility.HasPro()) - { - EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_IndirectIntensity"), LightmappingWindow.s_Styles.LightIndirectIntensity, new GUILayoutOption[0]); - } - EditorGUILayout.IntPopup(serializedObject3.FindProperty("m_Shadows.m_Type"), this.kShadowTypeStrings, this.kShadowTypeValues, LightmappingWindow.s_Styles.LightShadows, new GUILayoutOption[0]); - this.m_ShowShadowOptions.target = (selectedObjectsOfType2[0].shadows != LightShadows.None); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowOptions.faded)) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(serializedObject3.FindProperty("m_ShadowSamples"), LightmappingWindow.s_Styles.LightShadowSamples, new GUILayoutOption[0]); - this.m_ShowShadowAngleOrSize.target = (selectedObjectsOfType2[0].type != LightType.Area); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowShadowAngleOrSize.faded)) - { - if (selectedObjectsOfType2[0].type == LightType.Directional) - { - EditorGUILayout.Slider(serializedObject3.FindProperty("m_ShadowAngle"), 0f, 90f, LightmappingWindow.s_Styles.LightShadowAngle, new GUILayoutOption[0]); - } - else - { - EditorGUILayout.Slider(serializedObject3.FindProperty("m_ShadowRadius"), 0f, 2f, LightmappingWindow.s_Styles.LightShadowRadius, new GUILayoutOption[0]); - } - } - EditorGUILayout.EndFadeGroup(); - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - serializedObject3.ApplyModifiedProperties(); - EditorGUI.EndDisabledGroup(); - GUILayout.Space(10f); - } - this.m_LastAmountOfLights = selectedObjectsOfType2.Length; - Terrain[] selectedObjectsOfType3 = SceneModeUtility.GetSelectedObjectsOfType(out array, new Type[0]); - if (array.Length > 0) - { - flag = false; - EditorGUILayout.MultiSelectionObjectTitleBar(selectedObjectsOfType3); - SerializedObject serializedObject4 = new SerializedObject(array); - EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Lightmap Static", serializedObject4.FindProperty("m_StaticEditorFlags"), 1)); - SerializedObject serializedObject5 = new SerializedObject(selectedObjectsOfType3.ToArray()); - SerializedProperty serializedProperty3 = serializedObject5.FindProperty("m_LightmapSize"); - bool flag3 = false; - int intValue = serializedProperty3.intValue; - EditorGUILayout.IntPopup(serializedProperty3, this.kTerrainLightmapSizeStrings, this.kTerrainLightmapSizeValues, LightmappingWindow.s_Styles.TerrainLightmapSize, new GUILayoutOption[0]); - flag3 |= (intValue != serializedProperty3.intValue); - this.m_ShowAtlas = EditorGUILayout.Foldout(this.m_ShowAtlas, LightmappingWindow.s_Styles.Atlas); - if (this.m_ShowAtlas) - { - EditorGUI.indentLevel++; - SerializedProperty serializedProperty4 = serializedObject5.FindProperty("m_LightmapIndex"); - int intValue2 = serializedProperty4.intValue; - EditorGUILayout.PropertyField(serializedProperty4, LightmappingWindow.s_Styles.AtlasIndex, new GUILayoutOption[0]); - flag3 |= (intValue2 != serializedProperty4.intValue); - EditorGUI.indentLevel--; - } - serializedObject4.ApplyModifiedProperties(); - serializedObject5.ApplyModifiedProperties(); - if (flag3) - { - Terrain[] array2 = selectedObjectsOfType3; - for (int i = 0; i < array2.Length; i++) - { - Terrain terrain = array2[i]; - if (terrain != null) - { - terrain.Flush(); - } - } - } - EditorGUI.EndDisabledGroup(); - GUILayout.Space(10f); - } - if (flag) - { - GUILayout.Label(LightmappingWindow.s_Styles.EmptySelection, EditorStyles.helpBox, new GUILayoutOption[0]); - } - } - private void BakeSettings() - { - SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); - SerializedProperty property = serializedObject.FindProperty("m_LightmapsMode"); - SerializedProperty property2 = serializedObject.FindProperty("m_UseDualLightmapsInForward"); - SerializedProperty property3 = serializedObject.FindProperty("m_LightmapEditorSettings.m_SkyLightColor"); - SerializedProperty serializedProperty = serializedObject.FindProperty("m_LightmapEditorSettings.m_SkyLightIntensity"); - SerializedProperty serializedProperty2 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Bounces"); - SerializedProperty property4 = serializedObject.FindProperty("m_LightmapEditorSettings.m_BounceBoost"); - SerializedProperty property5 = serializedObject.FindProperty("m_LightmapEditorSettings.m_BounceIntensity"); - SerializedProperty serializedProperty3 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Quality"); - SerializedProperty serializedProperty4 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherRays"); - SerializedProperty serializedProperty5 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherContrastThreshold"); - SerializedProperty property6 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherGradientThreshold"); - SerializedProperty property7 = serializedObject.FindProperty("m_LightmapEditorSettings.m_FinalGatherInterpolationPoints"); - SerializedProperty serializedProperty6 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOAmount"); - SerializedProperty serializedProperty7 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOMaxDistance"); - SerializedProperty property8 = serializedObject.FindProperty("m_LightmapEditorSettings.m_AOContrast"); - SerializedProperty serializedProperty8 = serializedObject.FindProperty("m_LightmapEditorSettings.m_LockAtlas"); - SerializedProperty serializedProperty9 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Resolution"); - SerializedProperty property9 = serializedObject.FindProperty("m_LightmapEditorSettings.m_Padding"); - SerializedProperty property10 = serializedObject.FindProperty("m_LightmapEditorSettings.m_LODSurfaceMappingDistance"); - bool flag = this.BeastSettingsFileOverride(); - EditorGUILayout.IntPopup(property, this.kModeStrings, this.kModeValues, LightmappingWindow.s_Styles.Mode, new GUILayoutOption[0]); - this.m_ShowDualOptions.target = (LightmapSettings.lightmapsMode == LightmapsMode.Dual); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowDualOptions.faded)) - { - EditorGUILayout.PropertyField(property2, LightmappingWindow.s_Styles.UseDualInForward, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - GUILayout.Space(5f); - GUI.enabled = !flag; - int intValue = serializedProperty3.intValue; - EditorGUILayout.IntPopup(serializedProperty3, this.kQualityStrings, this.kQualityValues, LightmappingWindow.s_Styles.Quality, new GUILayoutOption[0]); - if (serializedProperty3.intValue != intValue) - { - if (serializedProperty3.intValue == 0) - { - serializedProperty4.intValue = 1000; - serializedProperty5.floatValue = 0.05f; - } - else - { - serializedProperty4.intValue = 200; - serializedProperty5.floatValue = 0.1f; - } - } - GUILayout.Space(5f); - if (InternalEditorUtility.HasPro()) - { - EditorGUILayout.IntPopup(serializedProperty2, this.kBouncesStrings, this.kBouncesValues, LightmappingWindow.s_Styles.Bounces, new GUILayoutOption[0]); - } - else - { - bool enabled = GUI.enabled; - GUI.enabled = false; - string[] displayedOptions = new string[] - { - "0" - }; - EditorGUILayout.IntPopup(LightmappingWindow.s_Styles.Bounces.text, 0, displayedOptions, this.kBouncesValues, new GUILayoutOption[0]); - GUI.enabled = enabled; - } - this.m_ShowFinalGather.target = (serializedProperty2.intValue > 0 && InternalEditorUtility.HasPro()); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowFinalGather.faded)) - { - EditorGUILayout.PropertyField(property3, LightmappingWindow.s_Styles.SkyLightColor, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedProperty, LightmappingWindow.s_Styles.SkyLightIntensity, new GUILayoutOption[0]); - if (serializedProperty.floatValue < 0f) - { - serializedProperty.floatValue = 0f; - } - EditorGUILayout.Slider(property4, 0f, 4f, LightmappingWindow.s_Styles.BounceBoost, new GUILayoutOption[0]); - EditorGUILayout.Slider(property5, 0f, 5f, LightmappingWindow.s_Styles.BounceIntensity, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedProperty4, LightmappingWindow.s_Styles.FinalGatherRays, new GUILayoutOption[0]); - if (serializedProperty4.intValue < 1) - { - serializedProperty4.intValue = 1; - } - EditorGUILayout.Slider(serializedProperty5, 0f, 0.5f, LightmappingWindow.s_Styles.FinalGatherContrastThreshold, new GUILayoutOption[0]); - EditorGUILayout.Slider(property6, 0f, 1f, LightmappingWindow.s_Styles.FinalGatherGradientThreshold, new GUILayoutOption[0]); - EditorGUILayout.IntSlider(property7, 15, 30, LightmappingWindow.s_Styles.FinalGatherInterpolationPoints, new GUILayoutOption[0]); - } - EditorGUILayout.EndFadeGroup(); - GUI.enabled = true; - GUILayout.Space(5f); - EditorGUILayout.Slider(serializedProperty6, 0f, 1f, LightmappingWindow.s_Styles.AO, new GUILayoutOption[0]); - this.m_ShowAO.target = (serializedProperty6.floatValue > 0f); - if (EditorGUILayout.BeginFadeGroup(this.m_ShowAO.faded)) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(serializedProperty7, LightmappingWindow.s_Styles.AOMaxDistance, new GUILayoutOption[0]); - if (serializedProperty7.floatValue < 0f) - { - serializedProperty7.floatValue = 0f; - } - EditorGUILayout.Slider(property8, 0f, 2f, LightmappingWindow.s_Styles.AOContrast, new GUILayoutOption[0]); - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - GUILayout.Space(5f); - EditorGUILayout.PropertyField(property10, LightmappingWindow.s_Styles.LODSurfaceDistance, new GUILayoutOption[0]); - GUILayout.Space(20f); - EditorGUILayout.PropertyField(serializedProperty8, LightmappingWindow.s_Styles.LockAtlas, new GUILayoutOption[0]); - GUI.enabled = !serializedProperty8.boolValue; - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedProperty9, LightmappingWindow.s_Styles.Resolution, new GUILayoutOption[0]); - if (serializedProperty9.floatValue != this.m_OldResolution) - { - serializedProperty9.floatValue = ((serializedProperty9.floatValue <= 0f) ? 0f : serializedProperty9.floatValue); - SceneView.RepaintAll(); - this.m_OldResolution = serializedProperty9.floatValue; - } - GUILayout.Label(" texels per world unit", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PropertyField(property9, LightmappingWindow.s_Styles.Padding, new GUILayoutOption[0]); - GUILayout.Label(" texels", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.EndHorizontal(); - GUI.enabled = true; - serializedObject.ApplyModifiedProperties(); - } - private void UpdateLightmapSelection() - { - Terrain terrain = null; - MeshRenderer component; - if (Selection.activeGameObject == null || ((component = Selection.activeGameObject.GetComponent()) == null && (terrain = Selection.activeGameObject.GetComponent()) == null)) - { - this.m_SelectedLightmap = -1; - return; - } - this.m_SelectedLightmap = ((!(component != null)) ? terrain.lightmapIndex : component.lightmapIndex); - } - private Texture2D LightmapField(Texture2D lightmap, int index) - { - Rect rect = GUILayoutUtility.GetRect(100f, 100f, EditorStyles.objectField); - this.MenuSelectLightmapUsers(rect, index); - Texture2D result = EditorGUI.ObjectField(rect, lightmap, typeof(Texture2D), false) as Texture2D; - if (index == this.m_SelectedLightmap && Event.current.type == EventType.Repaint) - { - LightmappingWindow.s_Styles.selectedLightmapHighlight.Draw(rect, false, false, false, false); - } - return result; - } - private void Maps() - { - GUI.changed = false; - SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); - SerializedProperty property = serializedObject.FindProperty("m_LightProbes"); - EditorGUILayout.PropertyField(property, LightmappingWindow.s_Styles.LightProbes, new GUILayoutOption[0]); - serializedObject.ApplyModifiedProperties(); - GUILayout.Space(10f); - LightmapData[] lightmaps = LightmapSettings.lightmaps; - Rect rect = GUILayoutUtility.GetRect(100f, 100f, 16f, 16f, EditorStyles.numberField); - int num = Mathf.Clamp(EditorGUI.ArraySizeField(rect, LightmappingWindow.s_Styles.MapsArraySize, LightmapSettings.lightmaps.Length, EditorStyles.numberField), 0, 254); - this.Compress(); - this.m_ScrollPositionMaps = GUILayout.BeginScrollView(this.m_ScrollPositionMaps, new GUILayoutOption[0]); - for (int i = 0; i < lightmaps.Length; i++) - { - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - GUILayout.Label(i.ToString(), new GUILayoutOption[0]); - GUILayout.Space(5f); - lightmaps[i].lightmapFar = this.LightmapField(lightmaps[i].lightmapFar, i); - GUILayout.Space(10f); - lightmaps[i].lightmapNear = this.LightmapField(lightmaps[i].lightmapNear, i); - GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); - } - GUILayout.EndScrollView(); - if (GUI.changed) - { - if (num != lightmaps.Length) - { - LightmapData[] array = Array.CreateInstance(typeof(LightmapData), num) as LightmapData[]; - Array.Copy(lightmaps, array, Mathf.Min(lightmaps.Length, num)); - for (int j = lightmaps.Length; j < num; j++) - { - array[j] = new LightmapData(); - } - LightmapSettings.lightmaps = array; - } - else - { - LightmapSettings.lightmaps = lightmaps; - } - LightmappingWindow.RepaintSceneAndGameViews(); - } - } - private void Compress() - { - bool flag = true; - LightmapData[] lightmaps = LightmapSettings.lightmaps; - Texture2D texture2D = null; - LightmapData[] array = lightmaps; - for (int i = 0; i < array.Length; i++) - { - LightmapData lightmapData = array[i]; - if (lightmapData.lightmapFar != null) - { - texture2D = lightmapData.lightmapFar; - break; - } - if (lightmapData.lightmapNear != null) - { - texture2D = lightmapData.lightmapNear; - break; - } - } - if (texture2D != null) - { - string assetPath = AssetDatabase.GetAssetPath(texture2D); - TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; - if (textureImporter != null) - { - flag = (textureImporter.textureFormat == TextureImporterFormat.AutomaticCompressed); - } - } - bool flag2 = EditorGUILayout.Toggle(LightmappingWindow.s_Styles.TextureCompression, flag, new GUILayoutOption[0]); - if (flag2 != flag) - { - UnityEngine.Object[] objects = new UnityEngine.Object[0]; - Selection.objects = objects; - LightmapData[] array2 = lightmaps; - for (int j = 0; j < array2.Length; j++) - { - LightmapData lightmapData2 = array2[j]; - string assetPath2 = AssetDatabase.GetAssetPath(lightmapData2.lightmapFar); - TextureImporter textureImporter2 = AssetImporter.GetAtPath(assetPath2) as TextureImporter; - if (textureImporter2 != null) - { - textureImporter2.textureFormat = ((!flag2) ? TextureImporterFormat.AutomaticTruecolor : TextureImporterFormat.AutomaticCompressed); - AssetDatabase.ImportAsset(assetPath2); - } - string assetPath3 = AssetDatabase.GetAssetPath(lightmapData2.lightmapNear); - TextureImporter textureImporter3 = AssetImporter.GetAtPath(assetPath3) as TextureImporter; - if (textureImporter3 != null) - { - textureImporter3.textureFormat = ((!flag2) ? TextureImporterFormat.AutomaticTruecolor : TextureImporterFormat.AutomaticCompressed); - AssetDatabase.ImportAsset(assetPath3); - } - } - } - } - private void MarkStartTime() - { - this.m_BakeStartTime = Time.realtimeSinceStartup; - } - private void MarkEndTime() - { - if (this.m_BakeStartTime < 0f || Time.realtimeSinceStartup - this.m_BakeStartTime < 0f) - { - this.m_LastBakeTimeString = string.Empty; - return; - } - try - { - TimeSpan timeSpan = TimeSpan.FromSeconds((double)(Time.realtimeSinceStartup - this.m_BakeStartTime)); - this.m_LastBakeTimeString = string.Concat(new string[] - { - "Last bake took ", - (timeSpan.Days <= 0) ? string.Empty : (timeSpan.Days + "."), - (timeSpan.Hours <= 0 && timeSpan.Days <= 0) ? string.Empty : (timeSpan.Hours.ToString("00") + ":"), - timeSpan.Minutes.ToString("00"), - ":", - timeSpan.Seconds.ToString("00") - }); - } - catch (Exception) - { - this.m_LastBakeTimeString = string.Empty; - } - } - private void Buttons() - { - float width = 120f; - bool flag = LightmapSettings.lightmapsMode == LightmapsMode.Directional && !InternalEditorUtility.HasPro(); - if (flag) - { - EditorGUILayout.HelpBox(LightmappingWindow.s_Styles.DirectionalLightmapsProOnly.text, MessageType.Warning); - } - EditorGUI.BeginDisabledGroup(flag); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.FlexibleSpace(); - if (GUILayout.Button("Clear", new GUILayoutOption[] - { - GUILayout.Width(width) - })) - { - Lightmapping.Clear(); - Analytics.Track("/LightMapper/Clear"); - } - if (!Lightmapping.isRunning) - { - if (this.BakeButton(new GUILayoutOption[] - { - GUILayout.Width(width) - })) - { - this.DoBake(); - GUIUtility.ExitGUI(); - } - } - else - { - if (GUILayout.Button("Cancel", new GUILayoutOption[] - { - GUILayout.Width(width) - })) - { - Lightmapping.Cancel(); - this.m_BakeStartTime = -1f; - Analytics.Track("/LightMapper/Cancel"); - } - } - GUILayout.EndHorizontal(); - EditorGUI.EndDisabledGroup(); - } - private void DoBake() - { - LightmapsMode lightmapsMode = LightmapSettings.lightmapsMode; - Analytics.Track("/LightMapper/Start"); - Analytics.Event("LightMapper", "Mode", lightmapsMode.ToString(), 1); - this.MarkStartTime(); - switch (this.bakeMode) - { - case LightmappingWindow.BakeMode.BakeScene: - Analytics.Event("LightMapper", "Button", "BakeScene", 1); - Lightmapping.BakeAsync(); - break; - case LightmappingWindow.BakeMode.BakeSelected: - Analytics.Event("LightMapper", "Button", "BakeSelected", 1); - Lightmapping.BakeSelectedAsync(); - break; - case LightmappingWindow.BakeMode.BakeProbes: - Analytics.Event("LightMapper", "Button", "BakeProbes", 1); - Lightmapping.BakeLightProbesOnlyAsync(); - break; - } - } - private bool BakeButton(params GUILayoutOption[] options) - { - GUIContent content = EditorGUIUtility.TempContent(ObjectNames.NicifyVariableName(this.bakeMode.ToString())); - Rect rect = GUILayoutUtility.GetRect(content, LightmappingWindow.s_Styles.dropDownButton, options); - Rect rect2 = rect; - rect2.xMin = rect2.xMax - 20f; - if (Event.current.type == EventType.MouseDown && rect2.Contains(Event.current.mousePosition)) - { - GenericMenu genericMenu = new GenericMenu(); - string[] names = Enum.GetNames(typeof(LightmappingWindow.BakeMode)); - int num = Array.IndexOf(names, Enum.GetName(typeof(LightmappingWindow.BakeMode), this.bakeMode)); - int num2 = 0; - foreach (string current in - from x in names - select ObjectNames.NicifyVariableName(x)) - { - genericMenu.AddItem(new GUIContent(current), num2 == num, new GenericMenu.MenuFunction2(this.BakeDropDownCallback), num2++); - } - genericMenu.DropDown(rect); - Event.current.Use(); - return false; - } - return GUI.Button(rect, content, LightmappingWindow.s_Styles.dropDownButton); - } - private void BakeDropDownCallback(object data) - { - this.bakeMode = (LightmappingWindow.BakeMode)((int)data); - this.DoBake(); - } - private void Summary() - { - GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); - if (this.m_LastBakeTimeString != string.Empty) - { - GUILayout.Label(this.m_LastBakeTimeString, LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - } - int num = 0; - int num2 = 0; - Dictionary dictionary = new Dictionary(); - bool flag = false; - LightmapData[] lightmaps = LightmapSettings.lightmaps; - for (int i = 0; i < lightmaps.Length; i++) - { - LightmapData lightmapData = lightmaps[i]; - if (!(lightmapData.lightmapFar == null)) - { - num2++; - Vector2 vector = new Vector2((float)lightmapData.lightmapFar.width, (float)lightmapData.lightmapFar.height); - if (dictionary.ContainsKey(vector)) - { - Dictionary dictionary2; - Dictionary expr_AC = dictionary2 = dictionary; - Vector2 key; - Vector2 expr_B1 = key = vector; - int num3 = dictionary2[key]; - expr_AC[expr_B1] = num3 + 1; - } - else - { - dictionary.Add(vector, 1); - } - num += TextureUtil.GetRuntimeMemorySize(lightmapData.lightmapFar); - if (lightmapData.lightmapNear) - { - num += TextureUtil.GetRuntimeMemorySize(lightmapData.lightmapNear); - flag = true; - } - } - } - string text = string.Concat(new object[] - { - num2, - (!flag) ? " single" : " dual", - " lightmap", - (num2 != 1) ? "s" : string.Empty - }); - bool flag2 = true; - foreach (KeyValuePair current in dictionary) - { - text += ((!flag2) ? ", " : ": "); - flag2 = false; - if (current.Value > 1) - { - text = text + current.Value + "x"; - } - string text2 = text; - text = string.Concat(new object[] - { - text2, - current.Key.x, - "x", - current.Key.y, - "px" - }); - } - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.Label(text + " ", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.Label("Color space ", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.EndVertical(); - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.Label(EditorUtility.FormatBytes(num), LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.Label((num2 != 0) ? (string.Empty + LightmapSettings.bakedColorSpace) : "No Lightmaps", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - GUILayout.EndVertical(); - } - private static void Header(ref Rect rect, float headerHeight, float headerLeftMargin, float maxLightmaps, LightmapsMode lightmapsMode) - { - Rect rect2 = GUILayoutUtility.GetRect(rect.width, headerHeight); - rect2.width = rect.width / maxLightmaps; - rect2.y -= rect.height; - rect.y += headerHeight; - rect2.x += headerLeftMargin; - if (lightmapsMode == LightmapsMode.Directional) - { - EditorGUI.DropShadowLabel(rect2, "color"); - rect2.x += rect2.width; - EditorGUI.DropShadowLabel(rect2, "scale"); - } - else - { - EditorGUI.DropShadowLabel(rect2, "far"); - rect2.x += rect2.width; - EditorGUI.DropShadowLabel(rect2, "near"); - } - } - private void Lightmaps(Rect r) - { - bool flag = true; - GUI.Box(r, string.Empty, "PreBackground"); - this.m_ScrollPositionLightmaps = EditorGUILayout.BeginScrollView(this.m_ScrollPositionLightmaps, new GUILayoutOption[] - { - GUILayout.Height(r.height) - }); - int num = 0; - LightmapsMode lightmapsMode = LightmapSettings.lightmapsMode; - float num2 = 2f; - LightmapData[] lightmaps = LightmapSettings.lightmaps; - for (int i = 0; i < lightmaps.Length; i++) - { - LightmapData lightmapData = lightmaps[i]; - if (lightmapData.lightmapFar == null) - { - num++; - } - else - { - GUILayoutOption[] options = new GUILayoutOption[] - { - GUILayout.MaxWidth((float)lightmapData.lightmapFar.width * num2), - GUILayout.MaxHeight((float)lightmapData.lightmapFar.height) - }; - Rect aspectRect = GUILayoutUtility.GetAspectRect((float)lightmapData.lightmapFar.width * num2 / (float)lightmapData.lightmapFar.height, options); - if (flag) - { - LightmappingWindow.Header(ref aspectRect, 20f, 6f, num2, lightmapsMode); - flag = false; - } - aspectRect.width /= num2; - EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapFar); - this.MenuSelectLightmapUsers(aspectRect, num); - if (lightmapData.lightmapNear) - { - aspectRect.x += aspectRect.width; - EditorGUI.DrawPreviewTexture(aspectRect, lightmapData.lightmapNear); - this.MenuSelectLightmapUsers(aspectRect, num); - } - num++; - } - } - EditorGUILayout.EndScrollView(); - } - private void MenuSelectLightmapUsers(Rect rect, int lightmapIndex) - { - if (Event.current.type == EventType.ContextClick && rect.Contains(Event.current.mousePosition)) - { - string[] texts = new string[] - { - "Select Lightmap Users" - }; - Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); - EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(texts), -1, new EditorUtility.SelectMenuItemFunction(this.SelectLightmapUsers), lightmapIndex); - Event.current.Use(); - } - } - private void SelectLightmapUsers(object userData, string[] options, int selected) - { - int num = (int)userData; - ArrayList arrayList = new ArrayList(); - MeshRenderer[] array = UnityEngine.Object.FindObjectsOfType(typeof(MeshRenderer)) as MeshRenderer[]; - MeshRenderer[] array2 = array; - for (int i = 0; i < array2.Length; i++) - { - MeshRenderer meshRenderer = array2[i]; - if (meshRenderer != null && meshRenderer.lightmapIndex == num) - { - arrayList.Add(meshRenderer.gameObject); - } - } - Terrain[] array3 = UnityEngine.Object.FindObjectsOfType(typeof(Terrain)) as Terrain[]; - Terrain[] array4 = array3; - for (int j = 0; j < array4.Length; j++) - { - Terrain terrain = array4[j]; - if (terrain != null && terrain.lightmapIndex == num) - { - arrayList.Add(terrain.gameObject); - } - } - Selection.objects = (arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); - } - public virtual void AddItemsToMenu(GenericMenu menu) - { - menu.AddItem(new GUIContent("Generate Beast settings file"), false, new GenericMenu.MenuFunction(this.GenerateBeastSettingsFile)); - } - private void GenerateBeastSettingsFile() - { - string lightmapAssetsPath = this.GetLightmapAssetsPath(); - string text = lightmapAssetsPath + "/BeastSettings.xml"; - if (lightmapAssetsPath.Length == 0) - { - Debug.LogWarning("Scene hasn't been saved yet, can't generate settings file."); - return; - } - if (File.Exists(text)) - { - Debug.LogWarning("Beast settings file already exists for this scene."); - return; - } - Directory.CreateDirectory(lightmapAssetsPath); - AssetDatabase.ImportAsset(lightmapAssetsPath); - FileUtil.CopyFileOrDirectory(EditorApplication.applicationContentsPath + "/Resources/BeastSettings.xml", text); - AssetDatabase.ImportAsset(text); - } - private string GetLightmapAssetsPath() - { - string currentScene = EditorApplication.currentScene; - return currentScene.Substring(0, Mathf.Max(0, currentScene.Length - 6)); - } - private bool BeastSettingsFileOverride() - { - string text = this.GetLightmapAssetsPath() + "/BeastSettings.xml"; - if (!File.Exists(text)) - { - return false; - } - GUILayout.Space(5f); - GUILayout.BeginVertical(GUI.skin.box, new GUILayoutOption[0]); - GUILayout.Label("Bake settings will be overridden by BeastSettings.xml", LightmappingWindow.s_Styles.labelStyle, new GUILayoutOption[0]); - if (GUILayout.Button("Open", new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - })) - { - AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath(text)); - } - GUILayout.EndVertical(); - GUILayout.Space(5f); - return true; - } - [MenuItem("Window/Lightmapping", false, 2098)] - private static void CreateLightmapEditor() - { - LightmappingWindow window = EditorWindow.GetWindow(); - window.title = EditorGUIUtility.TextContent("LightmapEditor.WindowTitle").text; - window.minSize = new Vector2(300f, 360f); - window.Show(); - } - } -} diff --git a/UnityEditor/UnityEditor/LineRendererInspector.cs b/UnityEditor/UnityEditor/LineRendererInspector.cs new file mode 100644 index 00000000..88575947 --- /dev/null +++ b/UnityEditor/UnityEditor/LineRendererInspector.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(LineRenderer))] + internal class LineRendererInspector : RendererEditorBase + { + public override void OnEnable() + { + base.OnEnable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Editor.DrawPropertiesExcluding(this.m_SerializedObject, new string[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialEditor.cs b/UnityEditor/UnityEditor/MaterialEditor.cs index 36d886a6..fafe21aa 100644 --- a/UnityEditor/UnityEditor/MaterialEditor.cs +++ b/UnityEditor/UnityEditor/MaterialEditor.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; using UnityEditor.Utils; using UnityEditorInternal; using UnityEngine; @@ -7,46 +8,115 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(Material))] public class MaterialEditor : Editor { + private static class Styles + { + public static readonly GUIStyle kReflectionProbePickerStyle = "PaneOptions"; + public static string[] lightmapEmissiveStrings = new string[] + { + "None", + "Realtime", + "Baked" + }; + public static int[] lightmapEmissiveValues = new int[] + { + 0, + 1, + 2 + }; + public static string lightmapEmissiveLabel = "Global Illumination"; + } private enum PreviewType { Mesh, - Plane + Plane, + Skybox + } + internal class ReflectionProbePicker : PopupWindowContent + { + private ReflectionProbe m_SelectedReflectionProbe; + public Transform Target + { + get + { + return (!(this.m_SelectedReflectionProbe != null)) ? null : this.m_SelectedReflectionProbe.transform; + } + } + public override Vector2 GetWindowSize() + { + return new Vector2(170f, 48f); + } + public void OnEnable() + { + this.m_SelectedReflectionProbe = (EditorUtility.InstanceIDToObject(InspectorState.GetInt("PreviewReflectionProbe", 0)) as ReflectionProbe); + } + public void OnDisable() + { + InspectorState.SetInt("PreviewReflectionProbe", (!this.m_SelectedReflectionProbe) ? 0 : this.m_SelectedReflectionProbe.GetInstanceID()); + } + public override void OnGUI(Rect rc) + { + EditorGUILayout.LabelField("Select Reflection Probe", EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.Space(); + this.m_SelectedReflectionProbe = (EditorGUILayout.ObjectField(string.Empty, this.m_SelectedReflectionProbe, typeof(ReflectionProbe), true, new GUILayoutOption[0]) as ReflectionProbe); + } } private class ForwardApplyMaterialModification { - private Renderer renderer; - public ForwardApplyMaterialModification(Renderer r) + private readonly Renderer renderer; + private bool isMaterialEditable; + public ForwardApplyMaterialModification(Renderer r, bool inIsMaterialEditable) { this.renderer = r; + this.isMaterialEditable = inIsMaterialEditable; } public bool DidModifyAnimationModeMaterialProperty(MaterialProperty property, int changedMask, object previousValue) { - return MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(property, changedMask, this.renderer, previousValue); + bool flag = MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(property, changedMask, this.renderer, previousValue); + return flag || !this.isMaterialEditable; } } - private const int kSpacingUnderTexture = 6; + private const float kSpacingUnderTexture = 6f; + private const float kWarningMessageHeight = 33f; + private const float kMiniWarningMessageHeight = 27f; + public const int kMiniTextureFieldLabelIndentLevel = 2; + private const float kSpaceBetweenFlexibleAreaAndField = 5f; private bool m_IsVisible; - private SerializedProperty m_Shader; + private static int s_ControlHash = "EditorTextField".GetHashCode(); + private Shader m_Shader; private string m_InfoMessage; private Vector2 m_PreviewDir = new Vector2(0f, -20f); private int m_SelectedMesh; private int m_TimeUpdate; private int m_LightMode = 1; + private static readonly GUIContent s_TilingText = new GUIContent("Tiling"); + private static readonly GUIContent s_OffsetText = new GUIContent("Offset"); + private ShaderGUI m_CustomShaderGUI; + [NonSerialized] + private bool m_TriedCreatingCustomGUI; + private bool m_InsidePropertiesGUI; + private Renderer m_RendererForAnimationMode; + private Color m_PreviousGUIColor; + private MaterialEditor.ReflectionProbePicker m_ReflectionProbePicker = new MaterialEditor.ReflectionProbePicker(); private MaterialProperty.TexDim m_DesiredTexdim; private PreviewRenderUtility m_PreviewUtility; - private static Mesh[] s_Meshes = new Mesh[4]; - private static Mesh s_PlaneMesh = null; - private static GUIContent[] s_MeshIcons = new GUIContent[4]; - private static GUIContent[] s_LightIcons = new GUIContent[2]; - private static GUIContent[] s_TimeIcons = new GUIContent[2]; + private static readonly Mesh[] s_Meshes = new Mesh[4]; + private static Mesh s_PlaneMesh; + private static readonly GUIContent[] s_MeshIcons = new GUIContent[4]; + private static readonly GUIContent[] s_LightIcons = new GUIContent[2]; + private static readonly GUIContent[] s_TimeIcons = new GUIContent[2]; + internal bool forceVisible + { + get; + set; + } public bool isVisible { get { - return this.m_IsVisible; + return this.forceVisible || this.m_IsVisible; } } - private MaterialEditor.PreviewType GetPreviewType(Material mat) + private static MaterialEditor.PreviewType GetPreviewType(Material mat) { if (mat == null) { @@ -57,9 +127,17 @@ private MaterialEditor.PreviewType GetPreviewType(Material mat) { return MaterialEditor.PreviewType.Plane; } + if (a == "skybox") + { + return MaterialEditor.PreviewType.Skybox; + } + if (mat.shader != null && mat.shader.name.Contains("Skybox")) + { + return MaterialEditor.PreviewType.Skybox; + } return MaterialEditor.PreviewType.Mesh; } - private bool DoesPreviewAllowRotation(MaterialEditor.PreviewType type) + private static bool DoesPreviewAllowRotation(MaterialEditor.PreviewType type) { return type != MaterialEditor.PreviewType.Plane; } @@ -67,35 +145,45 @@ public void SetShader(Shader shader) { this.SetShader(shader, true); } - public void SetShader(Shader shader, bool registerUndo) + public void SetShader(Shader newShader, bool registerUndo) { bool flag = false; - Shader shader2 = this.m_Shader.objectReferenceValue as Shader; - if (shader2 != null && shader2.customEditor != shader.customEditor) + ShaderGUI customShaderGUI = this.m_CustomShaderGUI; + string oldEditorName = (!(this.m_Shader != null)) ? string.Empty : this.m_Shader.customEditor; + this.CreateCustomShaderGUI(newShader, oldEditorName); + this.m_Shader = newShader; + if (customShaderGUI != this.m_CustomShaderGUI) { flag = true; } - this.m_Shader.objectReferenceValue = shader; - base.serializedObject.ApplyModifiedProperties(); UnityEngine.Object[] targets = base.targets; for (int i = 0; i < targets.Length; i++) { Material material = (Material)targets[i]; - if (material.shader.customEditor != shader.customEditor) + Shader shader = material.shader; + Undo.RecordObject(material, "Assign shader"); + if (this.m_CustomShaderGUI != null) { - flag = true; + this.m_CustomShaderGUI.AssignNewShaderToMaterial(material, shader, newShader); + } + else + { + material.shader = newShader; } - Undo.RecordObject(material, "Assign shader"); - material.shader = shader; EditorMaterialUtility.ResetDefaultTextures(material, false); MaterialEditor.ApplyMaterialPropertyDrawers(material); } if (flag && ActiveEditorTracker.sharedTracker != null) { - ActiveEditorTracker.sharedTracker.ForceRebuild(); + InspectorWindow[] allInspectorWindows = InspectorWindow.GetAllInspectorWindows(); + for (int j = 0; j < allInspectorWindows.Length; j++) + { + InspectorWindow inspectorWindow = allInspectorWindows[j]; + inspectorWindow.GetTracker().ForceRebuild(); + } } } - private void OnSelectedShaderPopup(string command, Shader shader) + internal void OnSelectedShaderPopup(string command, Shader shader) { base.serializedObject.Update(); if (shader != null) @@ -104,14 +192,27 @@ private void OnSelectedShaderPopup(string command, Shader shader) } this.PropertiesChanged(); } + private bool HasMultipleMixedShaderValues() + { + bool result = false; + Shader shader = (base.targets[0] as Material).shader; + for (int i = 1; i < base.targets.Length; i++) + { + if (shader != (base.targets[i] as Material).shader) + { + result = true; + break; + } + } + return result; + } private void ShaderPopup(GUIStyle style) { bool enabled = GUI.enabled; - Shader shader = this.m_Shader.objectReferenceValue as Shader; Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); rect = EditorGUI.PrefixLabel(rect, 47385, EditorGUIUtility.TempContent("Shader")); - EditorGUI.showMixedValue = this.m_Shader.hasMultipleDifferentValues; - GUIContent content = EditorGUIUtility.TempContent((!(shader != null)) ? "No Shader Selected" : shader.name); + EditorGUI.showMixedValue = this.HasMultipleMixedShaderValues(); + GUIContent content = EditorGUIUtility.TempContent((!(this.m_Shader != null)) ? "No Shader Selected" : this.m_Shader.name); if (EditorGUI.ButtonMouseDown(rect, content, EditorGUIUtility.native, style)) { EditorGUI.showMixedValue = false; @@ -126,11 +227,15 @@ private void ShaderPopup(GUIStyle style) public virtual void Awake() { this.m_IsVisible = InternalEditorUtility.GetIsInspectorExpanded(this.target); + if (MaterialEditor.GetPreviewType(this.target as Material) == MaterialEditor.PreviewType.Skybox) + { + this.m_PreviewDir = new Vector2(0f, 50f); + } } public override void OnInspectorGUI() { base.serializedObject.Update(); - if (this.m_IsVisible && !this.m_Shader.hasMultipleDifferentValues && this.m_Shader.objectReferenceValue != null && this.PropertiesGUI()) + if (this.isVisible && this.m_Shader != null && !this.HasMultipleMixedShaderValues() && this.PropertiesGUI()) { this.PropertiesChanged(); } @@ -149,13 +254,22 @@ public void PropertiesChanged() } protected override void OnHeaderGUI() { - Rect position = Editor.DrawHeaderGUI(this, this.targetTitle); + Rect position = Editor.DrawHeaderGUI(this, this.targetTitle, (!this.forceVisible) ? 10f : 0f); int controlID = GUIUtility.GetControlID(45678, FocusType.Passive); bool flag = EditorGUI.DoObjectFoldout(controlID, position, base.targets, this.m_IsVisible); - if (flag != this.m_IsVisible) + if (!this.forceVisible) { - this.m_IsVisible = flag; - InternalEditorUtility.SetIsInspectorExpanded(this.target, flag); + if (flag != this.m_IsVisible) + { + this.m_IsVisible = flag; + InternalEditorUtility.SetIsInspectorExpanded(this.target, flag); + } + if (Event.current.type == EventType.Repaint) + { + Rect position2 = new Rect(position.xMin + 3f, position.yMax - 17f, 15f, 15f); + bool flag2 = GUIUtility.hotControl == controlID; + EditorStyles.foldout.Draw(position2, flag2, flag2, this.m_IsVisible, false); + } } } internal override void OnHeaderControlsGUI() @@ -164,12 +278,12 @@ internal override void OnHeaderControlsGUI() EditorGUI.BeginDisabledGroup(!this.IsEnabled()); EditorGUIUtility.labelWidth = 50f; this.ShaderPopup("MiniPulldown"); - if (!this.m_Shader.hasMultipleDifferentValues && this.m_Shader.objectReferenceValue != null && (this.m_Shader.objectReferenceValue.hideFlags & HideFlags.DontSave) == HideFlags.None && GUILayout.Button("Edit...", EditorStyles.miniButton, new GUILayoutOption[] + if (this.m_Shader != null && this.HasMultipleMixedShaderValues() && (this.m_Shader.hideFlags & HideFlags.DontSave) == HideFlags.None && GUILayout.Button("Edit...", EditorStyles.miniButton, new GUILayoutOption[] { GUILayout.ExpandWidth(false) })) { - AssetDatabase.OpenAsset(this.m_Shader.objectReferenceValue); + AssetDatabase.OpenAsset(this.m_Shader); } EditorGUI.EndDisabledGroup(); } @@ -177,10 +291,10 @@ internal override void OnHeaderControlsGUI() public float GetFloat(string propertyName, out bool hasMixedValue) { hasMixedValue = false; - float @float = (base.targets[0] as Material).GetFloat(propertyName); + float @float = ((Material)base.targets[0]).GetFloat(propertyName); for (int i = 1; i < base.targets.Length; i++) { - if ((base.targets[i] as Material).GetFloat(propertyName) != @float) + if (((Material)base.targets[i]).GetFloat(propertyName) != @float) { hasMixedValue = true; break; @@ -202,10 +316,10 @@ public void SetFloat(string propertyName, float value) public Color GetColor(string propertyName, out bool hasMixedValue) { hasMixedValue = false; - Color color = (base.targets[0] as Material).GetColor(propertyName); + Color color = ((Material)base.targets[0]).GetColor(propertyName); for (int i = 1; i < base.targets.Length; i++) { - if ((base.targets[i] as Material).GetColor(propertyName) != color) + if (((Material)base.targets[i]).GetColor(propertyName) != color) { hasMixedValue = true; break; @@ -227,10 +341,10 @@ public void SetColor(string propertyName, Color value) public Vector4 GetVector(string propertyName, out bool hasMixedValue) { hasMixedValue = false; - Vector4 vector = (base.targets[0] as Material).GetVector(propertyName); + Vector4 vector = ((Material)base.targets[0]).GetVector(propertyName); for (int i = 1; i < base.targets.Length; i++) { - if ((base.targets[i] as Material).GetVector(propertyName) != vector) + if (((Material)base.targets[i]).GetVector(propertyName) != vector) { hasMixedValue = true; break; @@ -252,10 +366,10 @@ public void SetVector(string propertyName, Vector4 value) public Texture GetTexture(string propertyName, out bool hasMixedValue) { hasMixedValue = false; - Texture texture = (base.targets[0] as Material).GetTexture(propertyName); + Texture texture = ((Material)base.targets[0]).GetTexture(propertyName); for (int i = 1; i < base.targets.Length; i++) { - if ((base.targets[i] as Material).GetTexture(propertyName) != texture) + if (((Material)base.targets[i]).GetTexture(propertyName) != texture) { hasMixedValue = true; break; @@ -278,10 +392,10 @@ public Vector2 GetTextureScale(string propertyName, out bool hasMixedValueX, out { hasMixedValueX = false; hasMixedValueY = false; - Vector2 textureScale = (base.targets[0] as Material).GetTextureScale(propertyName); + Vector2 textureScale = ((Material)base.targets[0]).GetTextureScale(propertyName); for (int i = 1; i < base.targets.Length; i++) { - Vector2 textureScale2 = (base.targets[i] as Material).GetTextureScale(propertyName); + Vector2 textureScale2 = ((Material)base.targets[i]).GetTextureScale(propertyName); if (textureScale2.x != textureScale.x) { hasMixedValueX = true; @@ -302,10 +416,10 @@ public Vector2 GetTextureOffset(string propertyName, out bool hasMixedValueX, ou { hasMixedValueX = false; hasMixedValueY = false; - Vector2 textureOffset = (base.targets[0] as Material).GetTextureOffset(propertyName); + Vector2 textureOffset = ((Material)base.targets[0]).GetTextureOffset(propertyName); for (int i = 1; i < base.targets.Length; i++) { - Vector2 textureOffset2 = (base.targets[i] as Material).GetTextureOffset(propertyName); + Vector2 textureOffset2 = ((Material)base.targets[i]).GetTextureOffset(propertyName); if (textureOffset2.x != textureOffset.x) { hasMixedValueX = true; @@ -351,12 +465,19 @@ public float RangeProperty(MaterialProperty prop, string label) return this.RangeProperty(propertyRect, prop, label); } public float RangeProperty(Rect position, MaterialProperty prop, string label) + { + float power = (!(prop.name == "_Shininess")) ? 1f : 5f; + return MaterialEditor.DoPowerRangeProperty(position, prop, label, power); + } + internal static float DoPowerRangeProperty(Rect position, MaterialProperty prop, string label, float power) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = prop.hasMixedValue; - float power = (!(prop.name == "_Shininess")) ? 1f : 5f; + float labelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 0f; float floatValue = EditorGUI.PowerSlider(position, label, prop.floatValue, prop.rangeLimits.x, prop.rangeLimits.y, power); EditorGUI.showMixedValue = false; + EditorGUIUtility.labelWidth = labelWidth; if (EditorGUI.EndChangeCheck()) { prop.floatValue = floatValue; @@ -414,38 +535,53 @@ public Vector4 VectorProperty(Rect position, MaterialProperty prop, string label } return prop.vectorValue; } - internal static void TextureScaleOffsetProperty(Rect position, MaterialProperty property) + public void TextureScaleOffsetProperty(MaterialProperty property) + { + Rect controlRect = EditorGUILayout.GetControlRect(true, 32f, EditorStyles.layerMaskField, new GUILayoutOption[0]); + this.TextureScaleOffsetProperty(controlRect, property, false); + } + public float TextureScaleOffsetProperty(Rect position, MaterialProperty property) + { + return this.TextureScaleOffsetProperty(position, property, true); + } + public float TextureScaleOffsetProperty(Rect position, MaterialProperty property, bool partOfTexturePropertyControl) { + this.BeginAnimatedCheck(property); EditorGUI.BeginChangeCheck(); int mixedValueMask = property.mixedValueMask >> 1; - Vector4 textureScaleAndOffset = MaterialEditor.TextureScaleOffsetProperty(position, property.textureScaleAndOffset, mixedValueMask); + Vector4 textureScaleAndOffset = MaterialEditor.TextureScaleOffsetProperty(position, property.textureScaleAndOffset, mixedValueMask, partOfTexturePropertyControl); if (EditorGUI.EndChangeCheck()) { property.textureScaleAndOffset = textureScaleAndOffset; } + this.EndAnimatedCheck(); + return 32f; } - private Texture TexturePropertyBody(Rect position, MaterialProperty prop, string label) + private Texture TexturePropertyBody(Rect position, MaterialProperty prop) { - position.xMin = position.xMax - 64f; + if (prop.type != MaterialProperty.PropType.Texture) + { + throw new ArgumentException(string.Format("The MaterialProperty '{0}' should be of type 'Texture' (its type is '{1})'", prop.name, prop.type)); + } this.m_DesiredTexdim = prop.textureDimension; Type objType; switch (this.m_DesiredTexdim) { case MaterialProperty.TexDim.Tex2D: objType = typeof(Texture); - goto IL_8F; + goto IL_AA; case MaterialProperty.TexDim.Tex3D: objType = typeof(Texture3D); - goto IL_8F; + goto IL_AA; case MaterialProperty.TexDim.Cube: objType = typeof(Cubemap); - goto IL_8F; + goto IL_AA; case MaterialProperty.TexDim.Any: objType = typeof(Texture); - goto IL_8F; + goto IL_AA; } objType = null; - IL_8F: + IL_AA: bool enabled = GUI.enabled; EditorGUI.BeginChangeCheck(); if ((prop.flags & MaterialProperty.PropFlags.PerRendererData) != MaterialProperty.PropFlags.None) @@ -453,7 +589,8 @@ private Texture TexturePropertyBody(Rect position, MaterialProperty prop, string GUI.enabled = false; } EditorGUI.showMixedValue = prop.hasMixedValue; - Texture textureValue = EditorGUI.DoObjectField(position, position, GUIUtility.GetControlID(12354, EditorGUIUtility.native, position), prop.textureValue, objType, null, new EditorGUI.ObjectFieldValidator(this.TextureValidator), false) as Texture; + int controlID = GUIUtility.GetControlID(12354, EditorGUIUtility.native, position); + Texture textureValue = EditorGUI.DoObjectField(position, position, controlID, prop.textureValue, objType, null, new EditorGUI.ObjectFieldValidator(this.TextureValidator), false) as Texture; EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { @@ -464,133 +601,127 @@ private Texture TexturePropertyBody(Rect position, MaterialProperty prop, string } public Texture TextureProperty(MaterialProperty prop, string label) { - return this.TextureProperty(prop, label, true); + bool scaleOffset = (prop.flags & MaterialProperty.PropFlags.NoScaleOffset) == MaterialProperty.PropFlags.None; + return this.TextureProperty(prop, label, scaleOffset); } public Texture TextureProperty(MaterialProperty prop, string label, bool scaleOffset) { Rect propertyRect = this.GetPropertyRect(prop, label, true); return this.TextureProperty(propertyRect, prop, label, scaleOffset); } - private static bool DoesNeedNormalMapFix(MaterialProperty prop) + public bool HelpBoxWithButton(GUIContent messageContent, GUIContent buttonContent) { - if (prop.name != "_BumpMap") + Rect rect = GUILayoutUtility.GetRect(messageContent, EditorStyles.helpBox); + GUILayoutUtility.GetRect(1f, 25f); + rect.height += 25f; + GUI.Label(rect, messageContent, EditorStyles.helpBox); + Rect position = new Rect(rect.xMax - 60f - 4f, rect.yMax - 20f - 4f, 60f, 20f); + return GUI.Button(position, buttonContent); + } + public void TextureCompatibilityWarning(MaterialProperty prop) + { + if (InternalEditorUtility.BumpMapTextureNeedsFixing(prop) && this.HelpBoxWithButton(EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingWarning"), EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingButton"))) { - return false; + InternalEditorUtility.FixNormalmapTexture(prop); } - UnityEngine.Object[] targets = prop.targets; - for (int i = 0; i < targets.Length; i++) + bool flag = false; + if (InternalEditorUtility.HDRTextureNeedsFixing(prop, out flag)) { - Material material = (Material)targets[i]; - if (InternalEditorUtility.BumpMapTextureNeedsFixing(material)) + if (flag) { - return true; + if (this.HelpBoxWithButton(EditorGUIUtility.TextContent("MaterialInspector.HDRTextureFixingWarning"), EditorGUIUtility.TextContent("MaterialInspector.HDRTextureFixingButton"))) + { + InternalEditorUtility.FixHDRTexture(prop); + } + } + else + { + EditorGUILayout.HelpBox(EditorGUIUtility.TextContent("MaterialInspector.HDRTextureFixingWarning").text, MessageType.Warning); } } - return false; + } + public Texture TexturePropertyMiniThumbnail(Rect position, MaterialProperty prop, string label, string tooltip) + { + this.BeginAnimatedCheck(prop); + Rect position2; + Rect labelPosition; + EditorGUI.GetRectsForMiniThumbnailField(position, out position2, out labelPosition); + EditorGUI.HandlePrefixLabel(position, labelPosition, GUIContent.Temp(label, tooltip), 0, EditorStyles.label); + this.EndAnimatedCheck(); + Texture result = this.TexturePropertyBody(position2, prop); + Rect rect = position; + rect.y += position.height; + rect.height = 27f; + this.TextureCompatibilityWarning(prop); + return result; + } + public Rect GetTexturePropertyCustomArea(Rect position) + { + EditorGUI.indentLevel++; + position.height = MaterialEditor.GetTextureFieldHeight(); + Rect rect = position; + rect.yMin += 16f; + rect.xMax -= EditorGUIUtility.fieldWidth + 2f; + rect = EditorGUI.IndentedRect(rect); + EditorGUI.indentLevel--; + return rect; + } + public Texture TextureProperty(Rect position, MaterialProperty prop, string label) + { + bool scaleOffset = (prop.flags & MaterialProperty.PropFlags.NoScaleOffset) == MaterialProperty.PropFlags.None; + return this.TextureProperty(position, prop, label, scaleOffset); } public Texture TextureProperty(Rect position, MaterialProperty prop, string label, bool scaleOffset) { - if (this.target is ProceduralMaterial) - { - UnityEngine.Object[] targets = base.targets; - for (int i = 0; i < targets.Length; i++) - { - Material material = (Material)targets[i]; - if (SubstanceImporter.IsProceduralTextureSlot(material, material.GetTexture(prop.name), prop.name)) - { - break; - } - } - } - EditorGUI.PrefixLabel(position, EditorGUIUtility.TempContent(label)); - float height = position.height - 64f - 6f; - position.height = 64f; + return this.TextureProperty(position, prop, label, string.Empty, scaleOffset); + } + public Texture TextureProperty(Rect position, MaterialProperty prop, string label, string tooltip, bool scaleOffset) + { + EditorGUI.PrefixLabel(position, GUIContent.Temp(label, tooltip)); + position.height = MaterialEditor.GetTextureFieldHeight(); Rect position2 = position; position2.xMin = position2.xMax - EditorGUIUtility.fieldWidth; - Texture result = this.TexturePropertyBody(position2, prop, label); + Texture result = this.TexturePropertyBody(position2, prop); if (scaleOffset) { - EditorGUI.indentLevel++; - Rect rect = position; - rect.yMin += 16f; - rect.xMax -= EditorGUIUtility.fieldWidth + 2f; - rect = EditorGUI.IndentedRect(rect); - EditorGUI.indentLevel--; - MaterialEditor.TextureScaleOffsetProperty(rect, prop); - } - if (MaterialEditor.DoesNeedNormalMapFix(prop)) - { - Rect rect2 = position; - rect2.y += rect2.height; - rect2.height = height; - rect2.yMin += 4f; - EditorGUI.indentLevel++; - rect2 = EditorGUI.IndentedRect(rect2); - EditorGUI.indentLevel--; - GUI.Box(rect2, GUIContent.none, EditorStyles.helpBox); - rect2 = EditorStyles.helpBox.padding.Remove(rect2); - Rect position3 = rect2; - position3.width -= 60f; - GUI.Label(position3, EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingWarning"), EditorStyles.wordWrappedMiniLabel); - position3 = rect2; - position3.xMin += position3.width - 60f; - position3.y += 2f; - position3.height -= 4f; - if (GUI.Button(position3, EditorGUIUtility.TextContent("MaterialInspector.BumpMapFixingButton"))) - { - UnityEngine.Object[] targets2 = base.targets; - for (int j = 0; j < targets2.Length; j++) - { - Material material2 = (Material)targets2[j]; - if (InternalEditorUtility.BumpMapTextureNeedsFixing(material2)) - { - InternalEditorUtility.FixNormalmapTexture(material2); - } - } - } + this.TextureScaleOffsetProperty(this.GetTexturePropertyCustomArea(position), prop); } + GUILayout.Space(-6f); + this.TextureCompatibilityWarning(prop); + GUILayout.Space(6f); return result; } - internal static Vector4 TextureScaleOffsetProperty(Rect position, Vector4 scaleOffset, int mixedValueMask) - { - Rect rect = default(Rect); - Rect rect6; - Rect rect5; - Rect rect4; - Rect rect3; - Rect rect2 = rect3 = (rect4 = (rect5 = (rect6 = rect))); - position.y = position.yMax - 48f + 3f; - rect5.x = position.x; - rect5.width = 10f; - rect6.x = rect5.xMax + 2f; - rect6.width = (position.xMax - rect6.x - 2f) / 2f; - rect.x = rect6.xMax + 2f; - rect.xMax = position.xMax; - rect3.y = position.y; - rect3.height = 16f; - rect2 = rect3; - rect2.y += 16f; - rect4 = rect2; - rect4.y += 16f; - GUI.Label(new Rect(rect5.x, rect2.y, rect5.width, rect2.height), "x", EditorStyles.miniLabel); - GUI.Label(new Rect(rect5.x, rect4.y, rect5.width, rect4.height), "y", EditorStyles.miniLabel); - GUI.Label(new Rect(rect6.x, rect3.y, rect6.width, rect3.height), "Tiling", EditorStyles.miniLabel); - GUI.Label(new Rect(rect.x, rect3.y, rect.width, rect3.height), "Offset", EditorStyles.miniLabel); - for (int i = 0; i < 2; i++) - { - int num = i; - EditorGUI.showMixedValue = ((mixedValueMask & 1 << num) != 0); - Rect rect7 = (i != 0) ? rect4 : rect2; - scaleOffset[num] = EditorGUI.FloatField(new Rect(rect6.x, rect7.y, rect6.width, rect7.height), scaleOffset[num], EditorStyles.miniTextField); - } - for (int j = 0; j < 2; j++) - { - int num2 = j + 2; - EditorGUI.showMixedValue = ((mixedValueMask & 1 << num2) != 0); - Rect rect8 = (j != 0) ? rect4 : rect2; - scaleOffset[num2] = EditorGUI.FloatField(new Rect(rect.x, rect8.y, rect.width, rect8.height), scaleOffset[num2], EditorStyles.miniTextField); - } - return scaleOffset; + public static Vector4 TextureScaleOffsetProperty(Rect position, Vector4 scaleOffset) + { + return MaterialEditor.TextureScaleOffsetProperty(position, scaleOffset, 0, false); + } + public static Vector4 TextureScaleOffsetProperty(Rect position, Vector4 scaleOffset, bool partOfTexturePropertyControl) + { + return MaterialEditor.TextureScaleOffsetProperty(position, scaleOffset, 0, partOfTexturePropertyControl); + } + internal static Vector4 TextureScaleOffsetProperty(Rect position, Vector4 scaleOffset, int mixedValueMask, bool partOfTexturePropertyControl) + { + Vector2 value = new Vector2(scaleOffset.x, scaleOffset.y); + Vector2 value2 = new Vector2(scaleOffset.z, scaleOffset.w); + float num = EditorGUIUtility.labelWidth; + float left = position.x + num; + float left2 = position.x + EditorGUI.indent; + if (partOfTexturePropertyControl) + { + num = 65f; + left = position.x + num; + left2 = position.x; + position.y = position.yMax - 32f; + } + Rect totalPosition = new Rect(left2, position.y, num, 16f); + Rect position2 = new Rect(left, position.y, position.width - num, 16f); + EditorGUI.PrefixLabel(totalPosition, MaterialEditor.s_TilingText); + value = EditorGUI.Vector2Field(position2, GUIContent.none, value); + totalPosition.y += 16f; + position2.y += 16f; + EditorGUI.PrefixLabel(totalPosition, MaterialEditor.s_OffsetText); + value2 = EditorGUI.Vector2Field(position2, GUIContent.none, value2); + return new Vector4(value.x, value.y, value2.x, value2.y); } public float GetPropertyHeight(MaterialProperty prop) { @@ -598,12 +729,21 @@ public float GetPropertyHeight(MaterialProperty prop) } public float GetPropertyHeight(MaterialProperty prop, string label) { - MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); - if (drawer != null) + float num = 0f; + MaterialPropertyHandler handler = MaterialPropertyHandler.GetHandler(((Material)this.target).shader, prop.name); + if (handler != null) { - return drawer.GetPropertyHeight(prop, label ?? prop.displayName, this); + num = handler.GetPropertyHeight(prop, label ?? prop.displayName, this); + if (handler.propertyDrawer != null) + { + return num; + } } - return MaterialEditor.GetDefaultPropertyHeight(prop); + return num + MaterialEditor.GetDefaultPropertyHeight(prop); + } + private static float GetTextureFieldHeight() + { + return 64f; } public static float GetDefaultPropertyHeight(MaterialProperty prop) { @@ -613,43 +753,136 @@ public static float GetDefaultPropertyHeight(MaterialProperty prop) } if (prop.type == MaterialProperty.PropType.Texture) { - float num = 70f; - if (MaterialEditor.DoesNeedNormalMapFix(prop)) - { - num += 36f; - } - return num; + return MaterialEditor.GetTextureFieldHeight() + 6f; } return 16f; } private Rect GetPropertyRect(MaterialProperty prop, string label, bool ignoreDrawer) { + float num = 0f; if (!ignoreDrawer) { - MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); - if (drawer != null) + MaterialPropertyHandler handler = MaterialPropertyHandler.GetHandler(((Material)this.target).shader, prop.name); + if (handler != null) { - return EditorGUILayout.GetControlRect(true, drawer.GetPropertyHeight(prop, label ?? prop.displayName, this), EditorStyles.layerMaskField, new GUILayoutOption[0]); + num = handler.GetPropertyHeight(prop, label ?? prop.displayName, this); + if (handler.propertyDrawer != null) + { + return EditorGUILayout.GetControlRect(true, num, EditorStyles.layerMaskField, new GUILayoutOption[0]); + } } } - return EditorGUILayout.GetControlRect(true, MaterialEditor.GetDefaultPropertyHeight(prop), EditorStyles.layerMaskField, new GUILayoutOption[0]); + return EditorGUILayout.GetControlRect(true, num + MaterialEditor.GetDefaultPropertyHeight(prop), EditorStyles.layerMaskField, new GUILayoutOption[0]); + } + public void BeginAnimatedCheck(MaterialProperty prop) + { + if (this.m_RendererForAnimationMode == null) + { + return; + } + this.m_PreviousGUIColor = GUI.color; + if (MaterialAnimationUtility.IsAnimated(prop, this.m_RendererForAnimationMode)) + { + GUI.color = AnimationMode.animatedPropertyColor; + } + } + public void EndAnimatedCheck() + { + if (this.m_RendererForAnimationMode == null) + { + return; + } + GUI.color = this.m_PreviousGUIColor; } public void ShaderProperty(MaterialProperty prop, string label) + { + this.ShaderProperty(prop, label, 0); + } + public void ShaderProperty(MaterialProperty prop, string label, int labelIndent) { Rect propertyRect = this.GetPropertyRect(prop, label, false); - this.ShaderProperty(propertyRect, prop, label); + this.ShaderProperty(propertyRect, prop, label, labelIndent); } public void ShaderProperty(Rect position, MaterialProperty prop, string label) { - MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer((this.target as Material).shader, prop.name); - if (drawer != null) + this.ShaderProperty(position, prop, label, 0); + } + public void ShaderProperty(Rect position, MaterialProperty prop, string label, int labelIndent) + { + this.BeginAnimatedCheck(prop); + EditorGUI.indentLevel += labelIndent; + this.ShaderPropertyInternal(position, prop, label); + EditorGUI.indentLevel -= labelIndent; + this.EndAnimatedCheck(); + } + public void LightmapEmissionProperty() + { + this.LightmapEmissionProperty(0); + } + public void LightmapEmissionProperty(int labelIndent) + { + Rect controlRect = EditorGUILayout.GetControlRect(true, 16f, EditorStyles.layerMaskField, new GUILayoutOption[0]); + this.LightmapEmissionProperty(controlRect, labelIndent); + } + private static int GetGlobalIlluminationInt(MaterialGlobalIlluminationFlags flags) + { + int result = 0; + if ((flags & MaterialGlobalIlluminationFlags.RealtimeEmissive) != MaterialGlobalIlluminationFlags.None) { - float labelWidth = EditorGUIUtility.labelWidth; - float fieldWidth = EditorGUIUtility.fieldWidth; - drawer.OnGUI(position, prop, label ?? prop.displayName, this); - EditorGUIUtility.labelWidth = labelWidth; - EditorGUIUtility.fieldWidth = fieldWidth; - return; + result = 1; + } + else + { + if ((flags & MaterialGlobalIlluminationFlags.BakedEmissive) != MaterialGlobalIlluminationFlags.None) + { + result = 2; + } + } + return result; + } + public void LightmapEmissionProperty(Rect position, int labelIndent) + { + EditorGUI.indentLevel += labelIndent; + UnityEngine.Object[] targets = base.targets; + Material material = (Material)this.target; + int num = MaterialEditor.GetGlobalIlluminationInt(material.globalIlluminationFlags); + bool showMixedValue = false; + for (int i = 1; i < targets.Length; i++) + { + Material material2 = (Material)targets[i]; + if (MaterialEditor.GetGlobalIlluminationInt(material2.globalIlluminationFlags) != num) + { + showMixedValue = true; + } + } + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = showMixedValue; + num = EditorGUI.IntPopup(position, MaterialEditor.Styles.lightmapEmissiveLabel, num, MaterialEditor.Styles.lightmapEmissiveStrings, MaterialEditor.Styles.lightmapEmissiveValues); + EditorGUI.showMixedValue = false; + if (EditorGUI.EndChangeCheck()) + { + UnityEngine.Object[] array = targets; + for (int j = 0; j < array.Length; j++) + { + Material material3 = (Material)array[j]; + MaterialGlobalIlluminationFlags materialGlobalIlluminationFlags = material3.globalIlluminationFlags; + materialGlobalIlluminationFlags &= ~(MaterialGlobalIlluminationFlags.RealtimeEmissive | MaterialGlobalIlluminationFlags.BakedEmissive); + materialGlobalIlluminationFlags |= (MaterialGlobalIlluminationFlags)num; + material3.globalIlluminationFlags = materialGlobalIlluminationFlags; + } + } + EditorGUI.indentLevel -= labelIndent; + } + private void ShaderPropertyInternal(Rect position, MaterialProperty prop, string label) + { + MaterialPropertyHandler handler = MaterialPropertyHandler.GetHandler(((Material)this.target).shader, prop.name); + if (handler != null) + { + handler.OnGUI(ref position, prop, label ?? prop.displayName, this); + if (handler.propertyDrawer != null) + { + return; + } } this.DefaultShaderProperty(position, prop, label); } @@ -675,7 +908,7 @@ public void DefaultShaderProperty(Rect position, MaterialProperty prop, string l this.RangeProperty(position, prop, label); break; case MaterialProperty.PropType.Texture: - this.TextureProperty(position, prop, label, true); + this.TextureProperty(position, prop, label); break; default: GUI.Label(position, string.Concat(new object[] @@ -716,7 +949,7 @@ public Vector4 VectorProperty(string propertyName, string label) public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim) { MaterialProperty materialProperty = MaterialEditor.GetMaterialProperty(base.targets, propertyName); - return this.TextureProperty(materialProperty, label, true); + return this.TextureProperty(materialProperty, label); } [Obsolete("Use TextureProperty with MaterialProperty instead.")] public Texture TextureProperty(string propertyName, string label, ShaderUtil.ShaderPropertyTexDim texDim, bool scaleOffset) @@ -760,64 +993,132 @@ private static Renderer GetAssociatedRenderFromInspector() } return null; } - private Renderer PrepareMaterialPropertiesForAnimationMode(MaterialProperty[] properties) + public static Renderer PrepareMaterialPropertiesForAnimationMode(MaterialProperty[] properties, bool isMaterialEditable) { - if (!AnimationMode.InAnimationMode()) - { - return null; - } + bool flag = AnimationMode.InAnimationMode(); Renderer associatedRenderFromInspector = MaterialEditor.GetAssociatedRenderFromInspector(); if (associatedRenderFromInspector != null) { - MaterialEditor.ForwardApplyMaterialModification @object = new MaterialEditor.ForwardApplyMaterialModification(associatedRenderFromInspector); + MaterialEditor.ForwardApplyMaterialModification @object = new MaterialEditor.ForwardApplyMaterialModification(associatedRenderFromInspector, isMaterialEditable); MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock(); associatedRenderFromInspector.GetPropertyBlock(materialPropertyBlock); for (int i = 0; i < properties.Length; i++) { MaterialProperty materialProperty = properties[i]; materialProperty.ReadFromMaterialPropertyBlock(materialPropertyBlock); - materialProperty.applyPropertyCallback = new MaterialProperty.ApplyPropertyCallback(@object.DidModifyAnimationModeMaterialProperty); + if (flag) + { + materialProperty.applyPropertyCallback = new MaterialProperty.ApplyPropertyCallback(@object.DidModifyAnimationModeMaterialProperty); + } } } - return associatedRenderFromInspector; + if (flag) + { + return associatedRenderFromInspector; + } + return null; } - public bool PropertiesGUI() + public void SetDefaultGUIWidths() { EditorGUIUtility.fieldWidth = 64f; EditorGUIUtility.labelWidth = GUIClip.visibleRect.width - EditorGUIUtility.fieldWidth - 17f; - EditorGUI.BeginChangeCheck(); - if (this.m_InfoMessage != null) + } + private bool IsMaterialEditor(string customEditorName) + { + string value = "UnityEditor." + customEditorName; + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = 0; i < loadedAssemblies.Length; i++) { - EditorGUILayout.HelpBox(this.m_InfoMessage, MessageType.Info); + Assembly assembly = loadedAssemblies[i]; + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + for (int j = 0; j < array.Length; j++) + { + Type type = array[j]; + if ((type.FullName.Equals(customEditorName, StringComparison.Ordinal) || type.FullName.Equals(value, StringComparison.Ordinal)) && typeof(MaterialEditor).IsAssignableFrom(type)) + { + return true; + } + } + } + return false; + } + private void CreateCustomShaderGUI(Shader shader, string oldEditorName) + { + if (shader == null || string.IsNullOrEmpty(shader.customEditor)) + { + this.m_CustomShaderGUI = null; + return; + } + if (oldEditorName == shader.customEditor) + { + return; + } + this.m_CustomShaderGUI = ShaderGUIUtility.CreateShaderGUI(shader.customEditor); + if (this.m_CustomShaderGUI == null && !this.IsMaterialEditor(shader.customEditor)) + { + Debug.LogWarning("MaterialEditor: Could not create custom UI from the CustomEditor: '" + base.name + "' of the shader. Does the class name include its namespace? And does the class either derive from ShaderGUI or MaterialEditor?"); + } + } + public bool PropertiesGUI() + { + if (this.m_InsidePropertiesGUI) + { + Debug.LogWarning("PropertiesGUI() is being called recursivly. If you want to render the default gui for shader properties then call PropertiesDefaultGUI() instead"); + return false; } + EditorGUI.BeginChangeCheck(); MaterialProperty[] materialProperties = MaterialEditor.GetMaterialProperties(base.targets); - Renderer renderer = this.PrepareMaterialPropertiesForAnimationMode(materialProperties); - float num = 0f; - for (int i = 0; i < materialProperties.Length; i++) + this.m_RendererForAnimationMode = MaterialEditor.PrepareMaterialPropertiesForAnimationMode(materialProperties, GUI.enabled); + bool enabled = GUI.enabled; + if (this.m_RendererForAnimationMode != null) + { + GUI.enabled = true; + } + this.m_InsidePropertiesGUI = true; + try { - if ((materialProperties[i].flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) + if (this.m_CustomShaderGUI != null) { - num += this.GetPropertyHeight(materialProperties[i], materialProperties[i].displayName) + 2f; + this.m_CustomShaderGUI.OnGUI(this, materialProperties); + } + else + { + this.PropertiesDefaultGUI(materialProperties); } } - Rect controlRect = EditorGUILayout.GetControlRect(true, num, EditorStyles.layerMaskField, new GUILayoutOption[0]); - for (int j = 0; j < materialProperties.Length; j++) + catch (Exception) + { + GUI.enabled = enabled; + this.m_InsidePropertiesGUI = false; + this.m_RendererForAnimationMode = null; + throw; + } + GUI.enabled = enabled; + this.m_InsidePropertiesGUI = false; + this.m_RendererForAnimationMode = null; + return EditorGUI.EndChangeCheck(); + } + public void PropertiesDefaultGUI(MaterialProperty[] props) + { + this.SetDefaultGUIWidths(); + if (this.m_InfoMessage != null) { - if ((materialProperties[j].flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) + EditorGUILayout.HelpBox(this.m_InfoMessage, MessageType.Info); + } + else + { + GUIUtility.GetControlID(MaterialEditor.s_ControlHash, FocusType.Passive, new Rect(0f, 0f, 0f, 0f)); + } + for (int i = 0; i < props.Length; i++) + { + if ((props[i].flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) { - float propertyHeight = this.GetPropertyHeight(materialProperties[j], materialProperties[j].displayName); - controlRect.height = propertyHeight; - Color color = GUI.color; - if (renderer != null && MaterialAnimationUtility.IsAnimated(materialProperties[j], renderer)) - { - GUI.color = AnimationMode.animatedPropertyColor; - } - this.ShaderProperty(controlRect, materialProperties[j], materialProperties[j].displayName); - GUI.color = color; - controlRect.y += propertyHeight + 2f; + float propertyHeight = this.GetPropertyHeight(props[i], props[i].displayName); + Rect controlRect = EditorGUILayout.GetControlRect(true, propertyHeight, EditorStyles.layerMaskField, new GUILayoutOption[0]); + this.ShaderProperty(controlRect, props[i], props[i].displayName); } } - return EditorGUI.EndChangeCheck(); } public static void ApplyMaterialPropertyDrawers(Material material) { @@ -842,10 +1143,10 @@ public static void ApplyMaterialPropertyDrawers(UnityEngine.Object[] targets) MaterialProperty[] materialProperties = MaterialEditor.GetMaterialProperties(targets); for (int i = 0; i < materialProperties.Length; i++) { - MaterialPropertyDrawer drawer = MaterialPropertyDrawer.GetDrawer(shader, materialProperties[i].name); - if (drawer != null) + MaterialPropertyHandler handler = MaterialPropertyHandler.GetHandler(shader, materialProperties[i].name); + if (handler != null && handler.propertyDrawer != null) { - drawer.Apply(materialProperties[i]); + handler.propertyDrawer.Apply(materialProperties[i]); } } } @@ -879,20 +1180,21 @@ private void Init() gameObject.SetActive(false); foreach (Transform transform in gameObject.transform) { + MeshFilter component = transform.GetComponent(); string name = transform.name; switch (name) { case "sphere": - MaterialEditor.s_Meshes[0] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + MaterialEditor.s_Meshes[0] = component.sharedMesh; continue; case "cube": - MaterialEditor.s_Meshes[1] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + MaterialEditor.s_Meshes[1] = component.sharedMesh; continue; case "cylinder": - MaterialEditor.s_Meshes[2] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + MaterialEditor.s_Meshes[2] = component.sharedMesh; continue; case "torus": - MaterialEditor.s_Meshes[3] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + MaterialEditor.s_Meshes[3] = component.sharedMesh; continue; } Debug.Log("Something is wrong, weird object found: " + transform.name); @@ -908,7 +1210,28 @@ private void Init() MaterialEditor.s_PlaneMesh = (Resources.GetBuiltinResource(typeof(Mesh), "Quad.fbx") as Mesh); } } - public sealed override void OnPreviewSettings() + public override void OnPreviewSettings() + { + if (this.m_CustomShaderGUI != null) + { + this.m_CustomShaderGUI.OnMaterialPreviewSettingsGUI(this); + } + else + { + this.DefaultPreviewSettingsGUI(); + } + } + private bool PreviewSettingsMenuButton(out Rect buttonRect) + { + buttonRect = GUILayoutUtility.GetRect(14f, 24f, 14f, 20f); + Rect position = new Rect(buttonRect.x + (buttonRect.width - 16f) / 2f, buttonRect.y + (buttonRect.height - 6f) / 2f, 16f, 6f); + if (Event.current.type == EventType.Repaint) + { + MaterialEditor.Styles.kReflectionProbePickerStyle.Draw(position, false, false, false, false); + } + return EditorGUI.ButtonMouseDown(buttonRect, GUIContent.none, FocusType.Passive, GUIStyle.none); + } + public void DefaultPreviewSettingsGUI() { if (!ShaderUtil.hardwareSupportsRectRenderTexture) { @@ -916,12 +1239,17 @@ public sealed override void OnPreviewSettings() } this.Init(); Material mat = this.target as Material; - MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); + MaterialEditor.PreviewType previewType = MaterialEditor.GetPreviewType(mat); if (base.targets.Length > 1 || previewType == MaterialEditor.PreviewType.Mesh) { this.m_TimeUpdate = PreviewGUI.CycleButton(this.m_TimeUpdate, MaterialEditor.s_TimeIcons); this.m_SelectedMesh = PreviewGUI.CycleButton(this.m_SelectedMesh, MaterialEditor.s_MeshIcons); this.m_LightMode = PreviewGUI.CycleButton(this.m_LightMode, MaterialEditor.s_LightIcons); + Rect activatorRect; + if (this.PreviewSettingsMenuButton(out activatorRect)) + { + PopupWindow.Show(activatorRect, this.m_ReflectionProbePicker); + } } } public sealed override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) @@ -942,39 +1270,60 @@ private void DoRenderPreview() return; } Material mat = this.target as Material; - MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); + MaterialEditor.PreviewType previewType = MaterialEditor.GetPreviewType(mat); this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 5f; this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; Color ambient; if (this.m_LightMode == 0) { - this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].intensity = 1f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f); this.m_PreviewUtility.m_Light[1].intensity = 0f; ambient = new Color(0.2f, 0.2f, 0.2f, 0f); } else { - this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].intensity = 1f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); - this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + this.m_PreviewUtility.m_Light[1].intensity = 1f; ambient = new Color(0.2f, 0.2f, 0.2f, 0f); } InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); - Quaternion rot = Quaternion.identity; - if (this.DoesPreviewAllowRotation(previewType)) + Quaternion quaternion = Quaternion.identity; + if (MaterialEditor.DoesPreviewAllowRotation(previewType)) { - rot = Quaternion.Euler(this.m_PreviewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.m_PreviewDir.x, 0f); + quaternion = Quaternion.Euler(this.m_PreviewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.m_PreviewDir.x, 0f); } Mesh mesh = MaterialEditor.s_Meshes[this.m_SelectedMesh]; - if (previewType == MaterialEditor.PreviewType.Plane) + switch (previewType) { + case MaterialEditor.PreviewType.Mesh: + this.m_PreviewUtility.m_Camera.transform.position = Quaternion.Inverse(quaternion) * this.m_PreviewUtility.m_Camera.transform.position; + this.m_PreviewUtility.m_Camera.transform.LookAt(Vector3.zero); + quaternion = Quaternion.identity; + break; + case MaterialEditor.PreviewType.Plane: mesh = MaterialEditor.s_PlaneMesh; + break; + case MaterialEditor.PreviewType.Skybox: + mesh = null; + this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.Inverse(quaternion); + this.m_PreviewUtility.m_Camera.fieldOfView = 120f; + break; + } + if (mesh != null) + { + this.m_PreviewUtility.DrawMesh(mesh, Vector3.zero, quaternion, mat, 0, null, this.m_ReflectionProbePicker.Target); } - this.m_PreviewUtility.DrawMesh(mesh, Vector3.zero, rot, mat, 0); bool fog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); this.m_PreviewUtility.m_Camera.Render(); + if (previewType == MaterialEditor.PreviewType.Skybox) + { + GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear); + InternalEditorUtility.DrawSkyboxMaterial(mat, this.m_PreviewUtility.m_Camera); + GL.sRGBWrite = false; + } Unsupported.SetRenderSettingsUseFogNoDirty(fog); InternalEditorUtility.RemoveCustomLighting(); } @@ -986,7 +1335,29 @@ public override bool RequiresConstantRepaint() { return this.m_TimeUpdate == 1; } + public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) + { + if (this.m_CustomShaderGUI != null) + { + this.m_CustomShaderGUI.OnMaterialInteractivePreviewGUI(this, r, background); + } + else + { + base.OnInteractivePreviewGUI(r, background); + } + } public override void OnPreviewGUI(Rect r, GUIStyle background) + { + if (this.m_CustomShaderGUI != null) + { + this.m_CustomShaderGUI.OnMaterialPreviewGUI(this, r, background); + } + else + { + this.DefaultPreviewGUI(r, background); + } + } + public void DefaultPreviewGUI(Rect r, GUIStyle background) { if (!ShaderUtil.hardwareSupportsRectRenderTexture) { @@ -998,8 +1369,8 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) } this.Init(); Material mat = this.target as Material; - MaterialEditor.PreviewType previewType = this.GetPreviewType(mat); - if (this.DoesPreviewAllowRotation(previewType)) + MaterialEditor.PreviewType previewType = MaterialEditor.GetPreviewType(mat); + if (MaterialEditor.DoesPreviewAllowRotation(previewType)) { this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); } @@ -1014,9 +1385,11 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) } public virtual void OnEnable() { - this.m_Shader = base.serializedObject.FindProperty("m_Shader"); + this.m_Shader = (base.serializedObject.FindProperty("m_Shader").objectReferenceValue as Shader); + this.CreateCustomShaderGUI(this.m_Shader, string.Empty); Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoPerformed)); this.PropertiesChanged(); + this.m_ReflectionProbePicker.OnEnable(); } public virtual void UndoRedoPerformed() { @@ -1028,6 +1401,7 @@ public virtual void UndoRedoPerformed() } public virtual void OnDisable() { + this.m_ReflectionProbePicker.OnDisable(); if (this.m_PreviewUtility != null) { this.m_PreviewUtility.Cleanup(); @@ -1042,29 +1416,187 @@ internal void OnSceneDrag(SceneView sceneView) { return; } - GameObject gameObject = HandleUtility.PickGameObject(current.mousePosition, false); - if (!gameObject || !gameObject.renderer) + int materialIndex = -1; + GameObject gameObject = HandleUtility.PickGameObject(current.mousePosition, out materialIndex); + if (EditorMaterialUtility.IsBackgroundMaterial(this.target as Material)) { - return; + this.HandleSkybox(gameObject, current); + } + else + { + if (gameObject && gameObject.GetComponent()) + { + this.HandleRenderer(gameObject.GetComponent(), materialIndex, current); + } + } + } + internal void HandleSkybox(GameObject go, Event evt) + { + bool flag = !go; + bool flag2 = false; + if (!flag || evt.type == EventType.DragExited) + { + evt.Use(); + } + else + { + EventType type = evt.type; + if (type != EventType.DragUpdated) + { + if (type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + flag2 = true; + } + } + else + { + DragAndDrop.visualMode = DragAndDropVisualMode.Link; + flag2 = true; + } + } + if (flag2) + { + Undo.RecordObject(UnityEngine.Object.FindObjectOfType(), "Assign Skybox Material"); + RenderSettings.skybox = (this.target as Material); + evt.Use(); } - EventType type = current.type; + } + internal void HandleRenderer(Renderer r, int materialIndex, Event evt) + { + bool flag = false; + EventType type = evt.type; if (type != EventType.DragUpdated) { if (type == EventType.DragPerform) { DragAndDrop.AcceptDrag(); - Undo.RecordObject(gameObject.renderer, "Set Material"); - gameObject.renderer.sharedMaterial = (this.target as Material); - current.Use(); + flag = true; } } else { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - Undo.RecordObject(gameObject.renderer, "Set Material"); - gameObject.renderer.sharedMaterial = (this.target as Material); - current.Use(); + flag = true; } + if (flag) + { + Undo.RecordObject(r, "Assign Material"); + Material[] sharedMaterials = r.sharedMaterials; + bool alt = evt.alt; + bool flag2 = materialIndex >= 0 && materialIndex < r.sharedMaterials.Length; + if (!alt && flag2) + { + sharedMaterials[materialIndex] = (this.target as Material); + } + else + { + for (int i = 0; i < sharedMaterials.Length; i++) + { + sharedMaterials[i] = (this.target as Material); + } + } + r.sharedMaterials = sharedMaterials; + evt.Use(); + } + } + public void TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp) + { + this.TexturePropertySingleLine(label, textureProp, null, null); + } + public void TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1) + { + this.TexturePropertySingleLine(label, textureProp, extraProperty1, null); + } + public void TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1, MaterialProperty extraProperty2) + { + Rect controlRectForSingleLine = this.GetControlRectForSingleLine(); + this.TexturePropertyMiniThumbnail(controlRectForSingleLine, textureProp, label.text, label.tooltip); + if (extraProperty1 == null && extraProperty2 == null) + { + return; + } + if (extraProperty1 != null && extraProperty2 != null) + { + if (extraProperty1.type == MaterialProperty.PropType.Color) + { + this.ExtraPropertyAfterTexture(this.GetFlexibleRectBetweenFieldAndRightEdge(controlRectForSingleLine), extraProperty2); + this.ExtraPropertyAfterTexture(this.GetLeftAlignedFieldRect(controlRectForSingleLine), extraProperty1); + } + else + { + this.ExtraPropertyAfterTexture(this.GetRightAlignedFieldRect(controlRectForSingleLine), extraProperty2); + this.ExtraPropertyAfterTexture(this.GetFlexibleRectBetweenLabelAndField(controlRectForSingleLine), extraProperty1); + } + } + else + { + MaterialProperty materialProperty = extraProperty1 ?? extraProperty2; + if (materialProperty.type == MaterialProperty.PropType.Color) + { + this.ExtraPropertyAfterTexture(this.GetLeftAlignedFieldRect(controlRectForSingleLine), materialProperty); + } + else + { + this.ExtraPropertyAfterTexture(this.GetRectAfterLabelWidth(controlRectForSingleLine), materialProperty); + } + } + } + public void TexturePropertyTwoLines(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1, GUIContent label2, MaterialProperty extraProperty2) + { + if (extraProperty2 == null) + { + this.TexturePropertySingleLine(label, textureProp, extraProperty1); + return; + } + Rect controlRectForSingleLine = this.GetControlRectForSingleLine(); + this.TexturePropertyMiniThumbnail(controlRectForSingleLine, textureProp, label.text, label.tooltip); + Rect r = this.GetRectAfterLabelWidth(controlRectForSingleLine); + if (extraProperty1.type == MaterialProperty.PropType.Color) + { + r = this.GetLeftAlignedFieldRect(controlRectForSingleLine); + } + this.ExtraPropertyAfterTexture(r, extraProperty1); + Rect controlRectForSingleLine2 = this.GetControlRectForSingleLine(); + this.ShaderProperty(controlRectForSingleLine2, extraProperty2, label2.text, 3); + } + private Rect GetControlRectForSingleLine() + { + return EditorGUILayout.GetControlRect(true, 18f, EditorStyles.layerMaskField, new GUILayoutOption[0]); + } + private void ExtraPropertyAfterTexture(Rect r, MaterialProperty property) + { + if ((property.type == MaterialProperty.PropType.Float || property.type == MaterialProperty.PropType.Color) && r.width > EditorGUIUtility.fieldWidth) + { + float labelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = r.width - EditorGUIUtility.fieldWidth; + this.ShaderProperty(r, property, " "); + EditorGUIUtility.labelWidth = labelWidth; + return; + } + this.ShaderProperty(r, property, string.Empty); + } + private Rect GetRightAlignedFieldRect(Rect r) + { + return new Rect(r.xMax - EditorGUIUtility.fieldWidth, r.y, EditorGUIUtility.fieldWidth, EditorGUIUtility.singleLineHeight); + } + private Rect GetLeftAlignedFieldRect(Rect r) + { + return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, EditorGUIUtility.fieldWidth, EditorGUIUtility.singleLineHeight); + } + private Rect GetFlexibleRectBetweenLabelAndField(Rect r) + { + return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, r.width - EditorGUIUtility.labelWidth - EditorGUIUtility.fieldWidth - 5f, EditorGUIUtility.singleLineHeight); + } + private Rect GetFlexibleRectBetweenFieldAndRightEdge(Rect r) + { + Rect rectAfterLabelWidth = this.GetRectAfterLabelWidth(r); + rectAfterLabelWidth.xMin += EditorGUIUtility.fieldWidth + 5f; + return rectAfterLabelWidth; + } + private Rect GetRectAfterLabelWidth(Rect r) + { + return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, r.width - EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight); } } } diff --git a/UnityEditor/UnityEditor/MaterialEnumDrawer.cs b/UnityEditor/UnityEditor/MaterialEnumDrawer.cs index 8f360c98..d3029f92 100644 --- a/UnityEditor/UnityEditor/MaterialEnumDrawer.cs +++ b/UnityEditor/UnityEditor/MaterialEnumDrawer.cs @@ -6,8 +6,8 @@ namespace UnityEditor { internal class MaterialEnumDrawer : MaterialPropertyDrawer { - public readonly string[] names; - public readonly int[] values; + private readonly string[] names; + private readonly int[] values; public MaterialEnumDrawer(string enumName) { Type[] source = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly x) => AssemblyHelper.GetTypesFromAssembly(x)).ToArray(); @@ -24,7 +24,10 @@ public MaterialEnumDrawer(string enumName) } catch (Exception) { - Debug.LogWarning(string.Format("Failed to create MaterialEnum, enum {0} not found", enumName)); + Debug.LogWarningFormat("Failed to create MaterialEnum, enum {0} not found", new object[] + { + enumName + }); throw; } } diff --git a/UnityEditor/UnityEditor/MaterialHeaderDecorator.cs b/UnityEditor/UnityEditor/MaterialHeaderDecorator.cs new file mode 100644 index 00000000..f72aae3f --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialHeaderDecorator.cs @@ -0,0 +1,28 @@ +using System; +using System.Globalization; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialHeaderDecorator : MaterialPropertyDrawer + { + private readonly string header; + public MaterialHeaderDecorator(string header) + { + this.header = header; + } + public MaterialHeaderDecorator(float headerAsNumber) + { + this.header = headerAsNumber.ToString(CultureInfo.InvariantCulture); + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + return 24f; + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + position.y += 8f; + position = EditorGUI.IndentedRect(position); + GUI.Label(position, this.header, EditorStyles.boldLabel); + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs b/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs index 384828ae..649a702e 100644 --- a/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs +++ b/UnityEditor/UnityEditor/MaterialKeywordEnumDrawer.cs @@ -4,7 +4,7 @@ namespace UnityEditor { internal class MaterialKeywordEnumDrawer : MaterialPropertyDrawer { - public readonly string[] keywords; + private readonly string[] keywords; public MaterialKeywordEnumDrawer(string kw1) : this(new string[] { kw1 diff --git a/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs b/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs index c31382da..182d7383 100644 --- a/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs +++ b/UnityEditor/UnityEditor/MaterialPowerSliderDrawer.cs @@ -4,7 +4,7 @@ namespace UnityEditor { internal class MaterialPowerSliderDrawer : MaterialPropertyDrawer { - public readonly float power; + private readonly float power; public MaterialPowerSliderDrawer(float power) { this.power = power; @@ -25,14 +25,7 @@ public override void OnGUI(Rect position, MaterialProperty prop, string label, M EditorGUI.LabelField(position, label2, EditorStyles.helpBox); return; } - EditorGUI.BeginChangeCheck(); - EditorGUI.showMixedValue = prop.hasMixedValue; - float floatValue = EditorGUI.PowerSlider(position, label, prop.floatValue, prop.rangeLimits.x, prop.rangeLimits.y, this.power); - EditorGUI.showMixedValue = false; - if (EditorGUI.EndChangeCheck()) - { - prop.floatValue = floatValue; - } + MaterialEditor.DoPowerRangeProperty(position, prop, label, this.power); } } } diff --git a/UnityEditor/UnityEditor/MaterialProperty.cs b/UnityEditor/UnityEditor/MaterialProperty.cs index b1c0113a..78f0e413 100644 --- a/UnityEditor/UnityEditor/MaterialProperty.cs +++ b/UnityEditor/UnityEditor/MaterialProperty.cs @@ -28,7 +28,10 @@ public enum PropFlags { None = 0, HideInInspector = 1, - PerRendererData = 2 + PerRendererData = 2, + NoScaleOffset = 4, + Normal = 8, + HDR = 16 } public delegate bool ApplyPropertyCallback(MaterialProperty prop, int changeMask, object previousValue); private UnityEngine.Object[] m_Targets; diff --git a/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs b/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs index 2641f854..3e231d2e 100644 --- a/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs +++ b/UnityEditor/UnityEditor/MaterialPropertyDrawer.cs @@ -1,13 +1,9 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.RegularExpressions; using UnityEngine; namespace UnityEditor { public abstract class MaterialPropertyDrawer { - internal static Dictionary s_PropertyDrawers = new Dictionary(); public virtual void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) { EditorGUI.LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent("No GUI Implemented")); @@ -19,113 +15,5 @@ public virtual float GetPropertyHeight(MaterialProperty prop, string label, Mate public virtual void Apply(MaterialProperty prop) { } - private static string GetPropertyString(Shader shader, string name) - { - if (shader == null) - { - return string.Empty; - } - return shader.GetInstanceID() + "_" + name; - } - internal static void InvalidatePropertyCache(Shader shader) - { - if (shader == null) - { - return; - } - string value = shader.GetInstanceID() + "_"; - List list = new List(); - foreach (string current in MaterialPropertyDrawer.s_PropertyDrawers.Keys) - { - if (current.StartsWith(value)) - { - list.Add(current); - } - } - foreach (string current2 in list) - { - MaterialPropertyDrawer.s_PropertyDrawers.Remove(current2); - } - } - private static MaterialPropertyDrawer CreatePropertyDrawer(Type klass, string argsText) - { - if (string.IsNullOrEmpty(argsText)) - { - return Activator.CreateInstance(klass) as MaterialPropertyDrawer; - } - string[] array = argsText.Split(new char[] - { - ',' - }); - object[] array2 = new object[array.Length]; - for (int i = 0; i < array.Length; i++) - { - string text = array[i].Trim(); - float num; - if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num)) - { - array2[i] = num; - } - else - { - array2[i] = text; - } - } - return Activator.CreateInstance(klass, array2) as MaterialPropertyDrawer; - } - private static MaterialPropertyDrawer GetShaderPropertyDrawer(Shader shader, string name) - { - string shaderPropertyAttribute = ShaderUtil.GetShaderPropertyAttribute(shader, name); - if (string.IsNullOrEmpty(shaderPropertyAttribute)) - { - return null; - } - string text = shaderPropertyAttribute; - string text2 = string.Empty; - Match match = Regex.Match(shaderPropertyAttribute, "(\\w+)\\s*\\((.*)\\)"); - if (match.Success) - { - text = match.Groups[1].Value; - text2 = match.Groups[2].Value.Trim(); - } - foreach (Type current in EditorAssemblies.SubclassesOf(typeof(MaterialPropertyDrawer))) - { - if (!(current.Name == text) && !(current.Name == text + "Drawer")) - { - if (!(current.Name == "Material" + text + "Drawer")) - { - continue; - } - } - try - { - MaterialPropertyDrawer result = MaterialPropertyDrawer.CreatePropertyDrawer(current, text2); - return result; - } - catch (Exception) - { - Debug.LogWarning(string.Format("Failed to create material drawer {0} with arguments '{1}'", text, text2)); - MaterialPropertyDrawer result = null; - return result; - } - } - return null; - } - internal static MaterialPropertyDrawer GetDrawer(Shader shader, string name) - { - if (shader == null) - { - return null; - } - string propertyString = MaterialPropertyDrawer.GetPropertyString(shader, name); - MaterialPropertyDrawer shaderPropertyDrawer; - if (MaterialPropertyDrawer.s_PropertyDrawers.TryGetValue(propertyString, out shaderPropertyDrawer)) - { - return shaderPropertyDrawer; - } - shaderPropertyDrawer = MaterialPropertyDrawer.GetShaderPropertyDrawer(shader, name); - MaterialPropertyDrawer.s_PropertyDrawers[propertyString] = shaderPropertyDrawer; - return shaderPropertyDrawer; - } } } diff --git a/UnityEditor/UnityEditor/MaterialPropertyHandler.cs b/UnityEditor/UnityEditor/MaterialPropertyHandler.cs new file mode 100644 index 00000000..1f6f55c5 --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialPropertyHandler.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialPropertyHandler + { + private MaterialPropertyDrawer m_PropertyDrawer; + private List m_DecoratorDrawers; + private static Dictionary s_PropertyHandlers = new Dictionary(); + public MaterialPropertyDrawer propertyDrawer + { + get + { + return this.m_PropertyDrawer; + } + } + public bool IsEmpty() + { + return this.m_PropertyDrawer == null && (this.m_DecoratorDrawers == null || this.m_DecoratorDrawers.Count == 0); + } + public void OnGUI(ref Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + float num = position.height; + position.height = 0f; + if (this.m_DecoratorDrawers != null) + { + foreach (MaterialPropertyDrawer current in this.m_DecoratorDrawers) + { + position.height = current.GetPropertyHeight(prop, label, editor); + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + current.OnGUI(position, prop, label, editor); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + position.y += position.height; + num -= position.height; + } + } + position.height = num; + if (this.m_PropertyDrawer != null) + { + float labelWidth = EditorGUIUtility.labelWidth; + float fieldWidth = EditorGUIUtility.fieldWidth; + this.m_PropertyDrawer.OnGUI(position, prop, label, editor); + EditorGUIUtility.labelWidth = labelWidth; + EditorGUIUtility.fieldWidth = fieldWidth; + } + } + public float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + float num = 0f; + if (this.m_DecoratorDrawers != null) + { + foreach (MaterialPropertyDrawer current in this.m_DecoratorDrawers) + { + num += current.GetPropertyHeight(prop, label, editor); + } + } + if (this.m_PropertyDrawer != null) + { + num += this.m_PropertyDrawer.GetPropertyHeight(prop, label, editor); + } + return num; + } + private static string GetPropertyString(Shader shader, string name) + { + if (shader == null) + { + return string.Empty; + } + return shader.GetInstanceID() + "_" + name; + } + internal static void InvalidatePropertyCache(Shader shader) + { + if (shader == null) + { + return; + } + string value = shader.GetInstanceID() + "_"; + List list = new List(); + foreach (string current in MaterialPropertyHandler.s_PropertyHandlers.Keys) + { + if (current.StartsWith(value)) + { + list.Add(current); + } + } + foreach (string current2 in list) + { + MaterialPropertyHandler.s_PropertyHandlers.Remove(current2); + } + } + private static MaterialPropertyDrawer CreatePropertyDrawer(Type klass, string argsText) + { + if (string.IsNullOrEmpty(argsText)) + { + return Activator.CreateInstance(klass) as MaterialPropertyDrawer; + } + string[] array = argsText.Split(new char[] + { + ',' + }); + object[] array2 = new object[array.Length]; + for (int i = 0; i < array.Length; i++) + { + string text = array[i].Trim(); + float num; + if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num)) + { + array2[i] = num; + } + else + { + array2[i] = text; + } + } + return Activator.CreateInstance(klass, array2) as MaterialPropertyDrawer; + } + private static MaterialPropertyDrawer GetShaderPropertyDrawer(string attrib, out bool isDecorator) + { + isDecorator = false; + string text = attrib; + string text2 = string.Empty; + Match match = Regex.Match(attrib, "(\\w+)\\s*\\((.*)\\)"); + if (match.Success) + { + text = match.Groups[1].Value; + text2 = match.Groups[2].Value.Trim(); + } + foreach (Type current in EditorAssemblies.SubclassesOf(typeof(MaterialPropertyDrawer))) + { + if (!(current.Name == text) && !(current.Name == text + "Drawer") && !(current.Name == "Material" + text + "Drawer") && !(current.Name == text + "Decorator")) + { + if (!(current.Name == "Material" + text + "Decorator")) + { + continue; + } + } + try + { + isDecorator = current.Name.EndsWith("Decorator"); + MaterialPropertyDrawer result = MaterialPropertyHandler.CreatePropertyDrawer(current, text2); + return result; + } + catch (Exception) + { + Debug.LogWarningFormat("Failed to create material drawer {0} with arguments '{1}'", new object[] + { + text, + text2 + }); + MaterialPropertyDrawer result = null; + return result; + } + } + return null; + } + private static MaterialPropertyHandler GetShaderPropertyHandler(Shader shader, string name) + { + string[] shaderPropertyAttributes = ShaderUtil.GetShaderPropertyAttributes(shader, name); + if (shaderPropertyAttributes == null || shaderPropertyAttributes.Length == 0) + { + return null; + } + MaterialPropertyHandler materialPropertyHandler = new MaterialPropertyHandler(); + string[] array = shaderPropertyAttributes; + for (int i = 0; i < array.Length; i++) + { + string attrib = array[i]; + bool flag; + MaterialPropertyDrawer shaderPropertyDrawer = MaterialPropertyHandler.GetShaderPropertyDrawer(attrib, out flag); + if (shaderPropertyDrawer != null) + { + if (flag) + { + if (materialPropertyHandler.m_DecoratorDrawers == null) + { + materialPropertyHandler.m_DecoratorDrawers = new List(); + } + materialPropertyHandler.m_DecoratorDrawers.Add(shaderPropertyDrawer); + } + else + { + if (materialPropertyHandler.m_PropertyDrawer != null) + { + Debug.LogWarning(string.Format("Shader property {0} already has a property drawer", name), shader); + } + materialPropertyHandler.m_PropertyDrawer = shaderPropertyDrawer; + } + } + } + return materialPropertyHandler; + } + internal static MaterialPropertyHandler GetHandler(Shader shader, string name) + { + if (shader == null) + { + return null; + } + string propertyString = MaterialPropertyHandler.GetPropertyString(shader, name); + MaterialPropertyHandler materialPropertyHandler; + if (MaterialPropertyHandler.s_PropertyHandlers.TryGetValue(propertyString, out materialPropertyHandler)) + { + return materialPropertyHandler; + } + materialPropertyHandler = MaterialPropertyHandler.GetShaderPropertyHandler(shader, name); + if (materialPropertyHandler != null && materialPropertyHandler.IsEmpty()) + { + materialPropertyHandler = null; + } + MaterialPropertyHandler.s_PropertyHandlers[propertyString] = materialPropertyHandler; + return materialPropertyHandler; + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialSpaceDecorator.cs b/UnityEditor/UnityEditor/MaterialSpaceDecorator.cs new file mode 100644 index 00000000..1b9aac5f --- /dev/null +++ b/UnityEditor/UnityEditor/MaterialSpaceDecorator.cs @@ -0,0 +1,24 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class MaterialSpaceDecorator : MaterialPropertyDrawer + { + private readonly float height; + public MaterialSpaceDecorator() + { + this.height = 6f; + } + public MaterialSpaceDecorator(float height) + { + this.height = height; + } + public override float GetPropertyHeight(MaterialProperty prop, string label, MaterialEditor editor) + { + return this.height; + } + public override void OnGUI(Rect position, MaterialProperty prop, string label, MaterialEditor editor) + { + } + } +} diff --git a/UnityEditor/UnityEditor/MaterialToggleDrawer.cs b/UnityEditor/UnityEditor/MaterialToggleDrawer.cs index d00bf80b..e0c2cd6d 100644 --- a/UnityEditor/UnityEditor/MaterialToggleDrawer.cs +++ b/UnityEditor/UnityEditor/MaterialToggleDrawer.cs @@ -4,7 +4,7 @@ namespace UnityEditor { internal class MaterialToggleDrawer : MaterialPropertyDrawer { - public readonly string keyword; + private readonly string keyword; public MaterialToggleDrawer() { } diff --git a/UnityEditor/UnityEditor/MathUtils.cs b/UnityEditor/UnityEditor/MathUtils.cs index bc5a6f6a..9d3cbddd 100644 --- a/UnityEditor/UnityEditor/MathUtils.cs +++ b/UnityEditor/UnityEditor/MathUtils.cs @@ -5,6 +5,30 @@ namespace UnityEditor public class MathUtils { private const int kMaxDecimals = 15; + internal static float ClampToFloat(double value) + { + if (value < -3.4028234663852886E+38) + { + return -3.40282347E+38f; + } + if (value > 3.4028234663852886E+38) + { + return 3.40282347E+38f; + } + return (float)value; + } + internal static int ClampToInt(long value) + { + if (value < -2147483648L) + { + return -2147483648; + } + if (value > 2147483647L) + { + return 2147483647; + } + return (int)value; + } internal static float RoundToMultipleOf(float value, float roundingValue) { if (roundingValue == 0f) @@ -25,6 +49,10 @@ internal static int GetNumberOfDecimalsForMinimumDifference(float minDifference) { return Mathf.Clamp(-Mathf.FloorToInt(Mathf.Log10(minDifference)), 0, 15); } + internal static int GetNumberOfDecimalsForMinimumDifference(double minDifference) + { + return (int)Math.Max(0.0, -Math.Floor(Math.Log10(minDifference))); + } internal static float RoundBasedOnMinimumDifference(float valueToRound, float minDifference) { if (minDifference == 0f) @@ -33,11 +61,33 @@ internal static float RoundBasedOnMinimumDifference(float valueToRound, float mi } return (float)Math.Round((double)valueToRound, MathUtils.GetNumberOfDecimalsForMinimumDifference(minDifference), MidpointRounding.AwayFromZero); } + internal static double RoundBasedOnMinimumDifference(double valueToRound, double minDifference) + { + if (minDifference == 0.0) + { + return MathUtils.DiscardLeastSignificantDecimal(valueToRound); + } + return Math.Round(valueToRound, MathUtils.GetNumberOfDecimalsForMinimumDifference(minDifference), MidpointRounding.AwayFromZero); + } internal static float DiscardLeastSignificantDecimal(float v) { int digits = Mathf.Clamp((int)(5f - Mathf.Log10(Mathf.Abs(v))), 0, 15); return (float)Math.Round((double)v, digits, MidpointRounding.AwayFromZero); } + internal static double DiscardLeastSignificantDecimal(double v) + { + int digits = Math.Max(0, (int)(5.0 - Math.Log10(Math.Abs(v)))); + double result; + try + { + result = Math.Round(v, digits); + } + catch (ArgumentOutOfRangeException) + { + result = 0.0; + } + return result; + } public static float GetQuatLength(Quaternion q) { return Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); @@ -241,7 +291,7 @@ public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out f float num = Vector3.Dot(vector, vector); float num2 = Vector3.Dot(vector2, vector2); float num3 = Vector3.Dot(vector2, rhs); - if (num <= 1.401298E-45f && num2 <= 1.401298E-45f) + if (num <= Mathf.Epsilon && num2 <= Mathf.Epsilon) { squaredDist = Vector3.Dot(p1 - origin, p1 - origin); s = 0f; @@ -249,7 +299,7 @@ public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out f return p1; } float num4; - if (num <= 1.401298E-45f) + if (num <= Mathf.Epsilon) { s = 0f; num4 = num3 / num2; @@ -258,7 +308,7 @@ public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out f else { float num5 = Vector3.Dot(vector, rhs); - if (num2 <= 1.401298E-45f) + if (num2 <= Mathf.Epsilon) { num4 = 0f; s = Mathf.Clamp(-num5 / num, 0f, 1f); diff --git a/UnityEditor/UnityEditor/MecanimUtilities.cs b/UnityEditor/UnityEditor/MecanimUtilities.cs deleted file mode 100644 index 6a1b0942..00000000 --- a/UnityEditor/UnityEditor/MecanimUtilities.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using UnityEditorInternal; -using UnityEngine; -namespace UnityEditor -{ - internal class MecanimUtilities - { - public static bool HasChildMotion(Motion parent, Motion motion) - { - if (parent == motion) - { - return true; - } - if (parent is BlendTree) - { - BlendTree blendTree = parent as BlendTree; - int childCount = blendTree.childCount; - for (int i = 0; i < childCount; i++) - { - if (MecanimUtilities.HasChildMotion(blendTree.GetMotion(i), motion)) - { - return true; - } - } - } - return false; - } - public static bool StateMachineRelativePath(StateMachine parent, StateMachine toFind, ref List hierarchy) - { - hierarchy.Add(parent); - if (parent == toFind) - { - return true; - } - for (int i = 0; i < parent.stateMachineCount; i++) - { - if (MecanimUtilities.StateMachineRelativePath(parent.GetStateMachine(i), toFind, ref hierarchy)) - { - return true; - } - } - hierarchy.Remove(parent); - return false; - } - internal static bool AreSameAsset(UnityEngine.Object obj1, UnityEngine.Object obj2) - { - return AssetDatabase.GetAssetPath(obj1) == AssetDatabase.GetAssetPath(obj2); - } - internal static void DestroyStateMachineRecursive(StateMachine stateMachine) - { - for (int i = 0; i < stateMachine.stateMachineCount; i++) - { - StateMachine stateMachine2 = stateMachine.GetStateMachine(i); - if (MecanimUtilities.AreSameAsset(stateMachine, stateMachine2)) - { - MecanimUtilities.DestroyStateMachineRecursive(stateMachine2); - } - } - for (int j = 0; j < stateMachine.stateCount; j++) - { - for (int k = 0; k < stateMachine.motionSetCount; k++) - { - BlendTree blendTree = stateMachine.GetState(j).GetMotionInternal(k) as BlendTree; - if (blendTree != null && MecanimUtilities.AreSameAsset(stateMachine, blendTree)) - { - MecanimUtilities.DestroyBlendTreeRecursive(blendTree); - } - } - } - Undo.DestroyObjectImmediate(stateMachine); - } - internal static void DestroyBlendTreeRecursive(BlendTree blendTree) - { - for (int i = 0; i < blendTree.childCount; i++) - { - BlendTree blendTree2 = blendTree.GetMotion(i) as BlendTree; - if (blendTree2 != null && MecanimUtilities.AreSameAsset(blendTree, blendTree2)) - { - MecanimUtilities.DestroyBlendTreeRecursive(blendTree2); - } - } - Undo.DestroyObjectImmediate(blendTree); - } - } -} diff --git a/UnityEditor/UnityEditor/Menu.cs b/UnityEditor/UnityEditor/Menu.cs new file mode 100644 index 00000000..3ba74bf3 --- /dev/null +++ b/UnityEditor/UnityEditor/Menu.cs @@ -0,0 +1,15 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class Menu + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetChecked(string menuPath, bool isChecked); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetChecked(string menuPath); + } +} diff --git a/UnityEditor/UnityEditor/MeshColliderEditor.cs b/UnityEditor/UnityEditor/MeshColliderEditor.cs index 9e8f23d0..139a959b 100644 --- a/UnityEditor/UnityEditor/MeshColliderEditor.cs +++ b/UnityEditor/UnityEditor/MeshColliderEditor.cs @@ -5,23 +5,34 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(MeshCollider))] internal class MeshColliderEditor : Collider3DEditorBase { + private static class Texts + { + public static GUIContent isTriggerText = new GUIContent("Is Trigger", "Is this collider a trigger? Triggers are only supported on convex colliders."); + public static GUIContent convextText = new GUIContent("Convex", "Is this collider convex?"); + } private SerializedProperty m_Mesh; private SerializedProperty m_Convex; - private SerializedProperty m_SmoothSphereCollisions; public override void OnEnable() { base.OnEnable(); this.m_Mesh = base.serializedObject.FindProperty("m_Mesh"); this.m_Convex = base.serializedObject.FindProperty("m_Convex"); - this.m_SmoothSphereCollisions = base.serializedObject.FindProperty("m_SmoothSphereCollisions"); } public override void OnInspectorGUI() { base.serializedObject.Update(); - EditorGUILayout.PropertyField(this.m_IsTrigger, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_Convex, MeshColliderEditor.Texts.convextText, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && !this.m_Convex.boolValue) + { + this.m_IsTrigger.boolValue = false; + } + EditorGUI.indentLevel++; + EditorGUI.BeginDisabledGroup(!this.m_Convex.boolValue); + EditorGUILayout.PropertyField(this.m_IsTrigger, MeshColliderEditor.Texts.isTriggerText, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; EditorGUILayout.PropertyField(this.m_Material, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Convex, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_SmoothSphereCollisions, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Mesh, new GUILayoutOption[0]); base.serializedObject.ApplyModifiedProperties(); } diff --git a/UnityEditor/UnityEditor/MeshRendererEditor.cs b/UnityEditor/UnityEditor/MeshRendererEditor.cs index 1a47608a..95f7696c 100644 --- a/UnityEditor/UnityEditor/MeshRendererEditor.cs +++ b/UnityEditor/UnityEditor/MeshRendererEditor.cs @@ -1,33 +1,40 @@ using System; +using System.Collections.Generic; using UnityEngine; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(MeshRenderer))] - internal class MeshRendererEditor : Editor + internal class MeshRendererEditor : RendererEditorBase { - private SerializedProperty m_UseLightProbes; - private SerializedProperty m_LightProbeAnchor; - public void OnEnable() + private string[] m_ExcludedProperties; + public override void OnEnable() { - this.m_UseLightProbes = base.serializedObject.FindProperty("m_UseLightProbes"); - this.m_LightProbeAnchor = base.serializedObject.FindProperty("m_LightProbeAnchor"); + base.OnEnable(); + base.InitializeProbeFields(); + List list = new List(); + list.Add("m_LightmapParameters"); + list.AddRange(RendererEditorBase.Probes.GetFieldsStringArray()); + this.m_ExcludedProperties = list.ToArray(); } public override void OnInspectorGUI() { base.serializedObject.Update(); - Editor.DrawPropertiesExcluding(base.serializedObject, new string[] + Editor.DrawPropertiesExcluding(base.serializedObject, this.m_ExcludedProperties); + SerializedProperty serializedProperty = base.serializedObject.FindProperty("m_Materials"); + if (!serializedProperty.hasMultipleDifferentValues) { - "m_UseLightProbes", - "m_LightProbeAnchor" - }); - EditorGUILayout.PropertyField(this.m_UseLightProbes, new GUILayoutOption[0]); - if (this.m_UseLightProbes.boolValue) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(this.m_LightProbeAnchor, new GUIContent("Anchor Override", this.m_LightProbeAnchor.tooltip), new GUILayoutOption[0]); - EditorGUI.indentLevel--; + MeshRendererEditor.DisplayMaterialWarning(base.serializedObject, serializedProperty); } + base.RenderProbeFields(); base.serializedObject.ApplyModifiedProperties(); } + private static void DisplayMaterialWarning(SerializedObject obj, SerializedProperty property) + { + MeshFilter component = ((MeshRenderer)obj.targetObject).GetComponent(); + if (component != null && component.sharedMesh != null && property.arraySize > component.sharedMesh.subMeshCount) + { + EditorGUILayout.HelpBox("This renderer has more materials than the Mesh has submeshes. Multiple materials will be applied to the same submesh, which costs performance. Consider using multiple shader passes.", MessageType.Warning, true); + } + } } } diff --git a/UnityEditor/UnityEditor/MetroBuildType.cs b/UnityEditor/UnityEditor/MetroBuildType.cs deleted file mode 100644 index 3e23634c..00000000 --- a/UnityEditor/UnityEditor/MetroBuildType.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -namespace UnityEditor -{ - public enum MetroBuildType - { - AppX, - VisualStudioCpp, - VisualStudioCSharp, - VisualStudioCppDX, - VisualStudioCSharpDX - } -} diff --git a/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs b/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs index eb0a5c20..9cf63605 100644 --- a/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs +++ b/UnityEditor/UnityEditor/MetroCertificatePasswordWindow.cs @@ -75,7 +75,7 @@ public void OnGUI() this.message = GUIContent.none; try { - if (PlayerSettings.Metro.SetCertificate(this.path, this.password)) + if (PlayerSettings.WSA.SetCertificate(this.path, this.password)) { flag = true; } diff --git a/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs b/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs index d9bae8db..c8d6e02a 100644 --- a/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs +++ b/UnityEditor/UnityEditor/MetroCreateTestCertificateWindow.cs @@ -23,7 +23,7 @@ public static void Show(string publisher) { MetroCreateTestCertificateWindow[] array = (MetroCreateTestCertificateWindow[])Resources.FindObjectsOfTypeAll(typeof(MetroCreateTestCertificateWindow)); MetroCreateTestCertificateWindow metroCreateTestCertificateWindow = (array.Length <= 0) ? ScriptableObject.CreateInstance() : array[0]; - metroCreateTestCertificateWindow.path = Path.Combine(Application.dataPath, "MetroTestCertificate.pfx").Replace('\\', '/'); + metroCreateTestCertificateWindow.path = Path.Combine(Application.dataPath, "WSATestCertificate.pfx").Replace('\\', '/'); metroCreateTestCertificateWindow.publisher = publisher; metroCreateTestCertificateWindow.password = string.Empty; metroCreateTestCertificateWindow.confirm = metroCreateTestCertificateWindow.password; @@ -126,9 +126,9 @@ public void OnGUI() { try { - EditorUtility.MetroCreateTestCertificate(this.path, this.publisher, this.password, true); + EditorUtility.WSACreateTestCertificate(this.path, this.publisher, this.password, true); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); - if (!PlayerSettings.Metro.SetCertificate(FileUtil.GetProjectRelativePath(this.path), this.password)) + if (!PlayerSettings.WSA.SetCertificate(FileUtil.GetProjectRelativePath(this.path), this.password)) { this.message = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreatePasswordInvalid"); } diff --git a/UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs b/UnityEditor/UnityEditor/MobileTextureSubtarget.cs similarity index 52% rename from UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs rename to UnityEditor/UnityEditor/MobileTextureSubtarget.cs index 59101db1..10ef3d57 100644 --- a/UnityEditor/UnityEditor/BlackBerryBuildSubtarget.cs +++ b/UnityEditor/UnityEditor/MobileTextureSubtarget.cs @@ -1,11 +1,14 @@ using System; namespace UnityEditor { - public enum BlackBerryBuildSubtarget + public enum MobileTextureSubtarget { Generic, + DXT, PVRTC, ATC, - ETC + ETC, + ETC2, + ASTC } } diff --git a/UnityEditor/UnityEditor/ModelImporter.cs b/UnityEditor/UnityEditor/ModelImporter.cs index e251f168..dabbc179 100644 --- a/UnityEditor/UnityEditor/ModelImporter.cs +++ b/UnityEditor/UnityEditor/ModelImporter.cs @@ -1,10 +1,10 @@ using System; using System.Runtime.CompilerServices; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { - public sealed class ModelImporter : AssetImporter + public class ModelImporter : AssetImporter { [Obsolete("Use importMaterials, materialName and materialSearch instead")] public extern ModelImporterGenerateMaterials generateMaterials @@ -67,6 +67,18 @@ public extern bool useFileUnits [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float fileScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isFileScaleUsed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern bool importBlendShapes { [WrapperlessIcall] @@ -166,7 +178,7 @@ public extern ModelImporterGenerateAnimations generateAnimations [MethodImpl(MethodImplOptions.InternalCall)] set; } - internal extern TakeInfo[] importedTakeInfos + public extern TakeInfo[] importedTakeInfos { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -342,6 +354,62 @@ public extern ModelImporterAnimationType animationType [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern string motionNodeName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Avatar sourceAvatar + { + get + { + return this.sourceAvatarInternal; + } + set + { + Avatar sourceAvatarInternal = value; + if (value != null) + { + ModelImporter modelImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(value)) as ModelImporter; + if (modelImporter != null) + { + this.humanDescription = modelImporter.humanDescription; + } + else + { + Debug.LogError("Avatar must be from a ModelImporter, otherwise use ModelImporter.humanDescription"); + sourceAvatarInternal = null; + } + } + this.sourceAvatarInternal = sourceAvatarInternal; + } + } + internal extern Avatar sourceAvatarInternal + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public HumanDescription humanDescription + { + get + { + HumanDescription result; + this.INTERNAL_get_humanDescription(out result); + return result; + } + set + { + this.INTERNAL_set_humanDescription(ref value); + } + } [Obsolete("splitAnimations has been deprecated please use clipAnimations instead.", true)] public bool splitAnimations { @@ -362,6 +430,12 @@ public extern ModelImporterClipAnimation[] clipAnimations [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern ModelImporterClipAnimation[] defaultClipAnimations + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } internal extern bool isAssetOlderOr42 { [WrapperlessIcall] @@ -370,6 +444,12 @@ internal extern bool isAssetOlderOr42 } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_humanDescription(out HumanDescription value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_humanDescription(ref HumanDescription value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void UpdateSkeletonPose(SkeletonBone[] skeletonBones, SerializedProperty serializedProperty); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs b/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs index 21a85516..81538104 100644 --- a/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs +++ b/UnityEditor/UnityEditor/ModelImporterClipAnimation.cs @@ -1,6 +1,6 @@ using System; using System.Runtime.InteropServices; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -29,6 +29,9 @@ public sealed class ModelImporterClipAnimation private int m_Mirror; private int m_MaskType; private AvatarMask m_MaskSource; + private AnimationEvent[] m_AnimationEvents; + private ClipAnimationInfoCurve[] m_AdditionnalCurves; + private bool m_MaskNeedsUpdating; public string takeName { get @@ -260,6 +263,35 @@ public AvatarMask maskSource this.m_MaskSource = value; } } + public AnimationEvent[] events + { + get + { + return this.m_AnimationEvents; + } + set + { + this.m_AnimationEvents = value; + } + } + public ClipAnimationInfoCurve[] curves + { + get + { + return this.m_AdditionnalCurves; + } + set + { + this.m_AdditionnalCurves = value; + } + } + public bool maskNeedsUpdating + { + get + { + return this.m_MaskNeedsUpdating; + } + } public override bool Equals(object o) { ModelImporterClipAnimation modelImporterClipAnimation = o as ModelImporterClipAnimation; diff --git a/UnityEditor/UnityEditor/ModelImporterClipEditor.cs b/UnityEditor/UnityEditor/ModelImporterClipEditor.cs index 8de6c85d..d0f67a3a 100644 --- a/UnityEditor/UnityEditor/ModelImporterClipEditor.cs +++ b/UnityEditor/UnityEditor/ModelImporterClipEditor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using UnityEditor.Animations; using UnityEditorInternal; using UnityEngine; namespace UnityEditor @@ -62,7 +63,7 @@ public Styles() private SerializedProperty m_LegacyGenerateAnimations; private SerializedProperty m_MotionNodeName; private GUIContent[] m_MotionNodeList; - private bool motionNodeFoldout; + private static bool motionNodeFoldout; private ReorderableList m_ClipList; private static ModelImporterClipEditor.Styles styles; private ModelImporter singleImporter @@ -130,26 +131,32 @@ public void OnEnable() { this.SetupDefaultClips(); } + this.selectedClipIndex = EditorPrefs.GetInt("ModelImporterClipEditor.ActiveClipIndex", 0); this.ValidateClipSelectionIndex(); + EditorPrefs.SetInt("ModelImporterClipEditor.ActiveClipIndex", this.selectedClipIndex); if (this.m_AnimationClipEditor != null && this.selectedClipIndex >= 0) { this.SyncClipEditor(); } - if (this.selectedClipIndex == -1 && this.m_ClipAnimations.arraySize != 0) + if (this.m_ClipAnimations.arraySize != 0) { - this.SelectClip(0); + this.SelectClip(this.selectedClipIndex); } - this.m_MotionNodeName = base.serializedObject.FindProperty("m_MotionNodeName"); string[] transformPaths = this.singleImporter.transformPaths; - this.m_MotionNodeList = new GUIContent[transformPaths.Length]; + this.m_MotionNodeList = new GUIContent[transformPaths.Length + 1]; + this.m_MotionNodeList[0] = new GUIContent(""); for (int i = 0; i < transformPaths.Length; i++) { - this.m_MotionNodeList[i] = new GUIContent(transformPaths[i]); - } - if (this.m_MotionNodeList.Length > 0) - { - this.m_MotionNodeList[0] = new GUIContent("None"); + if (i == 0) + { + this.m_MotionNodeList[1] = new GUIContent(""); + } + else + { + this.m_MotionNodeList[i + 1] = new GUIContent(transformPaths[i]); + } } + this.m_MotionNodeName = base.serializedObject.FindProperty("m_MotionNodeName"); this.motionNodeIndex = ArrayUtility.FindIndex(this.m_MotionNodeList, (GUIContent content) => content.text == this.m_MotionNodeName.stringValue); this.motionNodeIndex = ((this.motionNodeIndex >= 1) ? this.motionNodeIndex : 0); } @@ -204,7 +211,7 @@ private void ValidateClipSelectionIndex() { if (this.selectedClipIndex > this.m_ClipAnimations.arraySize - 1) { - this.selectedClipIndex = -1; + this.selectedClipIndex = 0; } } public void OnDestroy() @@ -239,7 +246,7 @@ private void AnimationClipGUI() GUILayout.Label(ModelImporterClipEditor.styles.clipMultiEditInfo, EditorStyles.helpBox, new GUILayoutOption[0]); } Profiler.EndSample(); - if (InternalEditorUtility.HasPro()) + if (InternalEditorUtility.HasProFeaturesEnabled()) { this.RootMotionNodeSettings(); } @@ -347,10 +354,10 @@ private void AnimationSettings() } private void RootMotionNodeSettings() { - if (this.animationType == ModelImporterAnimationType.Human) + if (this.animationType == ModelImporterAnimationType.Human || this.animationType == ModelImporterAnimationType.Generic) { - this.motionNodeFoldout = EditorGUILayout.Foldout(this.motionNodeFoldout, ModelImporterClipEditor.styles.MotionSetting); - if (this.motionNodeFoldout) + ModelImporterClipEditor.motionNodeFoldout = EditorGUILayout.Foldout(ModelImporterClipEditor.motionNodeFoldout, ModelImporterClipEditor.styles.MotionSetting); + if (ModelImporterClipEditor.motionNodeFoldout) { EditorGUI.BeginChangeCheck(); this.motionNodeIndex = EditorGUILayout.Popup(ModelImporterClipEditor.styles.MotionNode, this.motionNodeIndex, this.m_MotionNodeList, new GUILayoutOption[0]); @@ -426,14 +433,14 @@ private void SelectClipInList(ReorderableList list) } private void DrawClipElement(Rect rect, int index, bool selected, bool focused) { - AnimationClipInfoProperties animationClipInfoAtIndex = this.GetAnimationClipInfoAtIndex(index); + AnimationClipInfoProperties animationClipInfoProperties = this.m_ClipList.list[index] as AnimationClipInfoProperties; rect.xMax -= 90f; - GUI.Label(rect, animationClipInfoAtIndex.name, EditorStyles.label); + GUI.Label(rect, animationClipInfoProperties.name, EditorStyles.label); rect.x = rect.xMax; rect.width = 45f; - GUI.Label(rect, animationClipInfoAtIndex.firstFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); + GUI.Label(rect, animationClipInfoProperties.firstFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); rect.x = rect.xMax; - GUI.Label(rect, animationClipInfoAtIndex.lastFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); + GUI.Label(rect, animationClipInfoProperties.lastFrame.ToString("0.0"), ModelImporterClipEditor.styles.numberStyle); } private void DrawClipHeader(Rect rect) { @@ -470,7 +477,7 @@ private void AnimationSplitTable() { GUILayout.Space(5f); AnimationClip animationClip = this.m_AnimationClipEditor.target as AnimationClip; - if (animationClip.isAnimatorMotion) + if (!animationClip.legacy) { this.GetSelectedClipInfo().AssignToPreviewClip(animationClip); } @@ -504,7 +511,7 @@ private void AnimationSplitTable() } } this.m_AnimationClipEditor.OnInspectorGUI(); - if (animationClip.isAnimatorMotion) + if (!animationClip.legacy) { this.GetSelectedClipInfo().ExtractFromPreviewClip(animationClip); } diff --git a/UnityEditor/UnityEditor/ModelImporterModelEditor.cs b/UnityEditor/UnityEditor/ModelImporterModelEditor.cs index 1d3b6926..791c60c6 100644 --- a/UnityEditor/UnityEditor/ModelImporterModelEditor.cs +++ b/UnityEditor/UnityEditor/ModelImporterModelEditor.cs @@ -9,6 +9,7 @@ private class Styles public GUIContent Meshes = EditorGUIUtility.TextContent("ModelImporter.Meshes"); public GUIContent ScaleFactor = EditorGUIUtility.TextContent("ModelImporter.ScaleFactor"); public GUIContent UseFileUnits = EditorGUIUtility.TextContent("ModelImporter.UseFileUnits"); + public GUIContent FileScaleFactor = EditorGUIUtility.TextContent("ModelImporter.FileScaleFactor"); public GUIContent ImportBlendShapes = EditorGUIUtility.TextContent("ModelImporter.ImportBlendShapes"); public GUIContent GenerateColliders = EditorGUIUtility.TextContent("ModelImporter.GenerateColliders"); public GUIContent SwapUVChannels = EditorGUIUtility.TextContent("ModelImporter.SwapUVChannels"); @@ -42,6 +43,7 @@ private class Styles new GUIContent("High") }; public GUIContent OptimizeMeshForGPU = EditorGUIUtility.TextContent("ModelImporterOptimizeMesh"); + public GUIContent KeepQuads = EditorGUIUtility.TextContent("ModelImporterKeepQuads"); public GUIContent IsReadable = EditorGUIUtility.TextContent("ModelImporterIsReadable"); public GUIContent Materials = EditorGUIUtility.TextContent("ModelImporterMaterials"); public GUIContent ImportMaterials = EditorGUIUtility.TextContent("ModelImporterMatImportMaterials"); @@ -124,12 +126,12 @@ public Styles() private SerializedProperty m_MaterialName; private SerializedProperty m_MaterialSearch; private SerializedProperty m_GlobalScale; + private SerializedProperty m_FileScale; private SerializedProperty m_MeshCompression; private SerializedProperty m_ImportBlendShapes; private SerializedProperty m_AddColliders; private SerializedProperty m_SwapUVChannels; private SerializedProperty m_GenerateSecondaryUV; - private SerializedProperty m_UseFileUnits; private SerializedProperty m_SecondaryUVAngleDistortion; private SerializedProperty m_SecondaryUVAreaDistortion; private SerializedProperty m_SecondaryUVHardAngle; @@ -140,24 +142,25 @@ public Styles() private SerializedProperty m_TangentImportMode; private SerializedProperty m_OptimizeMeshForGPU; private SerializedProperty m_IsReadable; + private SerializedProperty m_KeepQuads; private static ModelImporterModelEditor.Styles styles; private void UpdateShowAllMaterialNameOptions() { this.m_MaterialName = base.serializedObject.FindProperty("m_MaterialName"); this.m_ShowAllMaterialNameOptions = (this.m_MaterialName.intValue == 3); } - private void OnEnable() + internal virtual void OnEnable() { this.m_ImportMaterials = base.serializedObject.FindProperty("m_ImportMaterials"); this.m_MaterialName = base.serializedObject.FindProperty("m_MaterialName"); this.m_MaterialSearch = base.serializedObject.FindProperty("m_MaterialSearch"); this.m_GlobalScale = base.serializedObject.FindProperty("m_GlobalScale"); + this.m_FileScale = base.serializedObject.FindProperty("m_FileScale"); this.m_MeshCompression = base.serializedObject.FindProperty("m_MeshCompression"); this.m_ImportBlendShapes = base.serializedObject.FindProperty("m_ImportBlendShapes"); this.m_AddColliders = base.serializedObject.FindProperty("m_AddColliders"); this.m_SwapUVChannels = base.serializedObject.FindProperty("swapUVChannels"); this.m_GenerateSecondaryUV = base.serializedObject.FindProperty("generateSecondaryUV"); - this.m_UseFileUnits = base.serializedObject.FindProperty("m_UseFileUnits"); this.m_SecondaryUVAngleDistortion = base.serializedObject.FindProperty("secondaryUVAngleDistortion"); this.m_SecondaryUVAreaDistortion = base.serializedObject.FindProperty("secondaryUVAreaDistortion"); this.m_SecondaryUVHardAngle = base.serializedObject.FindProperty("secondaryUVHardAngle"); @@ -168,6 +171,7 @@ private void OnEnable() this.m_TangentImportMode = base.serializedObject.FindProperty("tangentImportMode"); this.m_OptimizeMeshForGPU = base.serializedObject.FindProperty("optimizeMeshForGPU"); this.m_IsReadable = base.serializedObject.FindProperty("m_IsReadable"); + this.m_KeepQuads = base.serializedObject.FindProperty("keepQuads"); this.UpdateShowAllMaterialNameOptions(); } internal override void ResetValues() @@ -189,20 +193,7 @@ public override void OnInspectorGUI() } GUILayout.Label(ModelImporterModelEditor.styles.Meshes, EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_GlobalScale, ModelImporterModelEditor.styles.ScaleFactor, new GUILayoutOption[0]); - bool flag = true; - UnityEngine.Object[] targets = base.targets; - for (int i = 0; i < targets.Length; i++) - { - ModelImporter modelImporter = (ModelImporter)targets[i]; - if (!modelImporter.isUseFileUnitsSupported) - { - flag = false; - } - } - if (flag) - { - EditorGUILayout.PropertyField(this.m_UseFileUnits, ModelImporterModelEditor.styles.UseFileUnits, new GUILayoutOption[0]); - } + EditorGUILayout.PropertyField(this.m_FileScale, ModelImporterModelEditor.styles.FileScaleFactor, new GUILayoutOption[0]); EditorGUILayout.Popup(this.m_MeshCompression, ModelImporterModelEditor.styles.MeshCompressionOpt, ModelImporterModelEditor.styles.MeshCompressionLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_IsReadable, ModelImporterModelEditor.styles.IsReadable, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_OptimizeMeshForGPU, ModelImporterModelEditor.styles.OptimizeMeshForGPU, new GUILayoutOption[0]); @@ -232,14 +223,14 @@ public override void OnInspectorGUI() EditorGUI.indentLevel--; } GUILayout.Label(ModelImporterModelEditor.styles.TangentSpace, EditorStyles.boldLabel, new GUILayoutOption[0]); - bool flag2 = true; - UnityEngine.Object[] targets2 = base.targets; - for (int j = 0; j < targets2.Length; j++) + bool flag = true; + UnityEngine.Object[] targets = base.targets; + for (int i = 0; i < targets.Length; i++) { - ModelImporter modelImporter2 = (ModelImporter)targets2[j]; - if (!modelImporter2.isTangentImportSupported) + ModelImporter modelImporter = (ModelImporter)targets[i]; + if (!modelImporter.isTangentImportSupported) { - flag2 = false; + flag = false; } } EditorGUI.BeginChangeCheck(); @@ -247,14 +238,14 @@ public override void OnInspectorGUI() if (EditorGUI.EndChangeCheck()) { this.m_TangentImportMode.intValue = this.m_NormalImportMode.intValue; - if (!flag2 && this.m_TangentImportMode.intValue == 0) + if (!flag && this.m_TangentImportMode.intValue == 0) { this.m_TangentImportMode.intValue = 1; } } GUIContent[] displayedOptions = ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsAll; ModelImporterTangentSpaceMode[] array = ModelImporterModelEditor.styles.TangentSpaceModeOptEnumsAll; - if (this.m_NormalImportMode.intValue == 1 || !flag2) + if (this.m_NormalImportMode.intValue == 1 || !flag) { displayedOptions = ModelImporterModelEditor.styles.TangentSpaceModeOptLabelsCalculate; array = ModelImporterModelEditor.styles.TangentSpaceModeOptEnumsCalculate; @@ -287,6 +278,7 @@ public override void OnInspectorGUI() EditorGUI.BeginDisabledGroup(this.m_TangentImportMode.intValue != 1); EditorGUILayout.PropertyField(this.m_SplitTangentsAcrossSeams, ModelImporterModelEditor.styles.SplitTangents, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); + EditorGUILayout.PropertyField(this.m_KeepQuads, ModelImporterModelEditor.styles.KeepQuads, new GUILayoutOption[0]); GUILayout.Label(ModelImporterModelEditor.styles.Materials, EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_ImportMaterials, ModelImporterModelEditor.styles.ImportMaterials, new GUILayoutOption[0]); string text; diff --git a/UnityEditor/UnityEditor/ModelImporterRigEditor.cs b/UnityEditor/UnityEditor/ModelImporterRigEditor.cs index 9eb7f245..a6f4d7cc 100644 --- a/UnityEditor/UnityEditor/ModelImporterRigEditor.cs +++ b/UnityEditor/UnityEditor/ModelImporterRigEditor.cs @@ -558,7 +558,7 @@ internal override void Apply() bool flag = component && !component.hasTransformHierarchy; if (flag) { - gameObject = (UnityEngine.Object.Instantiate(gameObject) as GameObject); + gameObject = UnityEngine.Object.Instantiate(gameObject); AnimatorUtility.DeoptimizeTransformHierarchy(gameObject); } AvatarSetupTool.AutoSetupOnInstance(gameObject, serializedObject3); diff --git a/UnityEditor/UnityEditor/ModelInspector.cs b/UnityEditor/UnityEditor/ModelInspector.cs index 2b9e0327..5d2f6882 100644 --- a/UnityEditor/UnityEditor/ModelInspector.cs +++ b/UnityEditor/UnityEditor/ModelInspector.cs @@ -9,15 +9,16 @@ internal class ModelInspector : Editor private PreviewRenderUtility m_PreviewUtility; private Material m_Material; private Material m_WireMaterial; - public Vector2 previewDir = new Vector2(120f, -20f); + public Vector2 previewDir = new Vector2(-120f, 20f); + internal static readonly string WireframeShaderSource = "Shader \"Hidden/ModelInspectorWireframe\" {\nSubShader {\n\tTags { \"ForceSupported\" = \"True\" }\n\tColor (0,0,0,0.3) Blend SrcAlpha OneMinusSrcAlpha\n\tZTest LEqual ZWrite Off\n\tOffset -1, -1\n\tPass { Cull Off }\n}}"; private void Init() { if (this.m_PreviewUtility == null) { this.m_PreviewUtility = new PreviewRenderUtility(); this.m_PreviewUtility.m_CameraFieldOfView = 30f; - this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Diffuse.mat") as Material); - this.m_WireMaterial = new Material("Shader \"Hidden/ModelInspectorWireframe\" {\nSubShader {\n\tTags { \"ForceSupported\" = \"True\" } \n\tColor (0,0,0,0.3) Blend SrcAlpha OneMinusSrcAlpha\n\tZTest LEqual ZWrite Off\n\tOffset -1, -1\n\tPass { Cull Off }\n}}"); + this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Material.mat") as Material); + this.m_WireMaterial = new Material(ModelInspector.WireframeShaderSource); this.m_WireMaterial.hideFlags = HideFlags.HideAndDontSave; this.m_WireMaterial.shader.hideFlags = HideFlags.HideAndDontSave; } @@ -31,42 +32,77 @@ public override void OnPreviewSettings() GUI.enabled = true; this.Init(); } - private void DoRenderPreview() + internal static void RenderMeshPreview(Mesh mesh, PreviewRenderUtility previewUtility, Material litMaterial, Material wireMaterial, Vector2 direction, int meshSubset) { - Mesh mesh = this.target as Mesh; + if (mesh == null || previewUtility == null) + { + return; + } Bounds bounds = mesh.bounds; float magnitude = bounds.extents.magnitude; - float num = magnitude * 4f; - this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * num; - this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; - this.m_PreviewUtility.m_Camera.nearClipPlane = num - magnitude * 1.1f; - this.m_PreviewUtility.m_Camera.farClipPlane = num + magnitude * 1.1f; - this.m_PreviewUtility.m_Light[0].intensity = 0.7f; - this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); - this.m_PreviewUtility.m_Light[1].intensity = 0.7f; + float num = 4f * magnitude; + previewUtility.m_Camera.transform.position = -Vector3.forward * num; + previewUtility.m_Camera.transform.rotation = Quaternion.identity; + previewUtility.m_Camera.nearClipPlane = num - magnitude * 1.1f; + previewUtility.m_Camera.farClipPlane = num + magnitude * 1.1f; + previewUtility.m_Light[0].intensity = 1.4f; + previewUtility.m_Light[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f); + previewUtility.m_Light[1].intensity = 1.4f; Color ambient = new Color(0.1f, 0.1f, 0.1f, 0f); - InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); - Quaternion quaternion = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); + InternalEditorUtility.SetCustomLighting(previewUtility.m_Light, ambient); + ModelInspector.RenderMeshPreviewSkipCameraAndLighting(mesh, bounds, previewUtility, litMaterial, wireMaterial, null, direction, meshSubset); + InternalEditorUtility.RemoveCustomLighting(); + } + internal static void RenderMeshPreviewSkipCameraAndLighting(Mesh mesh, Bounds bounds, PreviewRenderUtility previewUtility, Material litMaterial, Material wireMaterial, MaterialPropertyBlock customProperties, Vector2 direction, int meshSubset) + { + if (mesh == null || previewUtility == null) + { + return; + } + Quaternion quaternion = Quaternion.Euler(direction.y, 0f, 0f) * Quaternion.Euler(0f, direction.x, 0f); Vector3 pos = quaternion * -bounds.center; bool fog = RenderSettings.fog; Unsupported.SetRenderSettingsUseFogNoDirty(false); int subMeshCount = mesh.subMeshCount; - this.m_PreviewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; - for (int i = 0; i < subMeshCount; i++) + if (litMaterial != null) { - this.m_PreviewUtility.DrawMesh(mesh, pos, quaternion, this.m_Material, i); + previewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; + if (meshSubset < 0 || meshSubset >= subMeshCount) + { + for (int i = 0; i < subMeshCount; i++) + { + previewUtility.DrawMesh(mesh, pos, quaternion, litMaterial, i, customProperties); + } + } + else + { + previewUtility.DrawMesh(mesh, pos, quaternion, litMaterial, meshSubset, customProperties); + } + previewUtility.m_Camera.Render(); } - this.m_PreviewUtility.m_Camera.Render(); - this.m_PreviewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; - ShaderUtil.wireframeMode = true; - for (int j = 0; j < subMeshCount; j++) + if (wireMaterial != null) { - this.m_PreviewUtility.DrawMesh(mesh, pos, quaternion, this.m_WireMaterial, j); + previewUtility.m_Camera.clearFlags = CameraClearFlags.Nothing; + GL.wireframe = true; + if (meshSubset < 0 || meshSubset >= subMeshCount) + { + for (int j = 0; j < subMeshCount; j++) + { + previewUtility.DrawMesh(mesh, pos, quaternion, wireMaterial, j, customProperties); + } + } + else + { + previewUtility.DrawMesh(mesh, pos, quaternion, wireMaterial, meshSubset, customProperties); + } + previewUtility.m_Camera.Render(); + GL.wireframe = false; } - this.m_PreviewUtility.m_Camera.Render(); Unsupported.SetRenderSettingsUseFogNoDirty(fog); - ShaderUtil.wireframeMode = false; - InternalEditorUtility.RemoveCustomLighting(); + } + private void DoRenderPreview() + { + ModelInspector.RenderMeshPreview(this.target as Mesh, this.m_PreviewUtility, this.m_Material, this.m_WireMaterial, this.previewDir, -1); } public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height) { diff --git a/UnityEditor/UnityEditor/ModuleUI.cs b/UnityEditor/UnityEditor/ModuleUI.cs index 0e86ddea..d4085733 100644 --- a/UnityEditor/UnityEditor/ModuleUI.cs +++ b/UnityEditor/UnityEditor/ModuleUI.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using UnityEngine; @@ -51,6 +50,7 @@ public ColorCallbackData(bool state, SerializedProperty bp) protected const int kPlusAddRemoveButtonSpacing = 5; protected const int kSpacingSubLabel = 4; protected const int kSubLabelWidth = 10; + protected const string kFormatString = "g7"; public ParticleSystemUI m_ParticleSystemUI; private string m_DisplayName; protected string m_ToolTip = string.Empty; @@ -548,7 +548,6 @@ public static void GUIMinMaxSlider(GUIContent label, SerializedProperty vec2Prop } public static bool GUIBoolAsPopup(GUIContent label, SerializedProperty boolProp, string[] options) { - Assert.That(options.Length == 2); Rect rect = ModuleUI.GetControlRect(13); rect = ModuleUI.PrefixLabel(rect, label); int num = (!boolProp.boolValue) ? 0 : 1; diff --git a/UnityEditor/UnityEditor/MonoAOTRegistration.cs b/UnityEditor/UnityEditor/MonoAOTRegistration.cs index ecb4ab80..88ff2554 100644 --- a/UnityEditor/UnityEditor/MonoAOTRegistration.cs +++ b/UnityEditor/UnityEditor/MonoAOTRegistration.cs @@ -58,30 +58,55 @@ public static HashSet BuildReferencedTypeList(AssemblyDefinition[] assem } return hashSet; } - public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string librariesFolder, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker) + public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget buildTarget, string file, CrossCompileOptions crossCompileOptions, bool advancedLic, string targetDevice, bool stripping, RuntimeClassRegistry usedClassRegistry, AssemblyReferenceChecker checker) { - using (TextWriter textWriter = new StreamWriter(Path.Combine(librariesFolder, "RegisterMonoModules.cpp"))) + using (TextWriter textWriter = new StreamWriter(file)) { string[] assemblyFileNames = checker.GetAssemblyFileNames(); AssemblyDefinition[] assemblyDefinitions = checker.GetAssemblyDefinitions(); bool flag = (crossCompileOptions & CrossCompileOptions.FastICall) != CrossCompileOptions.Dynamic; ArrayList arrayList = MonoAOTRegistration.BuildNativeMethodList(assemblyDefinitions); - if (buildTarget == BuildTarget.iPhone) + if (buildTarget == BuildTarget.iOS) { textWriter.WriteLine("#include \"RegisterMonoModules.h\""); + textWriter.WriteLine("#include "); } textWriter.WriteLine(string.Empty); + textWriter.WriteLine("#if defined(TARGET_IPHONE_SIMULATOR) && TARGET_IPHONE_SIMULATOR"); + textWriter.WriteLine("\t#define DECL_USER_FUNC(f) void f() __attribute__((weak_import))"); + textWriter.WriteLine("\t#define REGISTER_USER_FUNC(f)\\"); + textWriter.WriteLine("\t\tdo {\\"); + textWriter.WriteLine("\t\tif(f != NULL)\\"); + textWriter.WriteLine("\t\t\tmono_dl_register_symbol(#f, (void*)f);\\"); + textWriter.WriteLine("\t\telse\\"); + textWriter.WriteLine("\t\t\t::printf_console(\"Symbol '%s' not found. Maybe missing implementation for Simulator?\\n\", #f);\\"); + textWriter.WriteLine("\t\t}while(0)"); + textWriter.WriteLine("#else"); + textWriter.WriteLine("\t#define DECL_USER_FUNC(f) void f() "); + textWriter.WriteLine("\t#if !defined(__arm64__)"); + textWriter.WriteLine("\t#define REGISTER_USER_FUNC(f) mono_dl_register_symbol(#f, (void*)&f)"); + textWriter.WriteLine("\t#else"); + textWriter.WriteLine("\t\t#define REGISTER_USER_FUNC(f)"); + textWriter.WriteLine("\t#endif"); + textWriter.WriteLine("#endif"); textWriter.WriteLine("extern \"C\"\n{"); textWriter.WriteLine("\ttypedef void* gpointer;"); textWriter.WriteLine("\ttypedef int gboolean;"); - textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)"); - if (buildTarget == BuildTarget.iPhone) + if (buildTarget == BuildTarget.iOS) { textWriter.WriteLine("\tconst char*\t\t\tUnityIPhoneRuntimeVersion = \"{0}\";", Application.unityVersion); textWriter.WriteLine("\tvoid\t\t\t\tmono_dl_register_symbol (const char* name, void *addr);"); - textWriter.WriteLine("\textern int \t\t\tmono_ficall_flag;"); + textWriter.WriteLine("#if !defined(__arm64__)"); + textWriter.WriteLine("\textern int\t\t\tmono_ficall_flag;"); + textWriter.WriteLine("#endif"); } textWriter.WriteLine("\tvoid\t\t\t\tmono_aot_register_module(gpointer *aot_info);"); + textWriter.WriteLine("#if !(__ORBIS__)"); + textWriter.WriteLine("#define DLL_EXPORT"); + textWriter.WriteLine("#else"); + textWriter.WriteLine("#define DLL_EXPORT __declspec(dllexport)"); + textWriter.WriteLine("#endif"); + textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)"); textWriter.WriteLine("\textern gboolean\t\tmono_aot_only;"); for (int i = 0; i < assemblyFileNames.Length; i++) { @@ -95,14 +120,14 @@ public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget textWriter.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)"); foreach (string arg2 in arrayList) { - textWriter.WriteLine("\tvoid\t{0}();", arg2); + textWriter.WriteLine("\tDECL_USER_FUNC({0});", arg2); } textWriter.WriteLine("}"); - textWriter.WriteLine("void RegisterMonoModules()"); + textWriter.WriteLine("DLL_EXPORT void RegisterMonoModules()"); textWriter.WriteLine("{"); - textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR)"); + textWriter.WriteLine("#if !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)"); textWriter.WriteLine("\tmono_aot_only = true;"); - if (buildTarget == BuildTarget.iPhone) + if (buildTarget == BuildTarget.iOS) { textWriter.WriteLine("\tmono_ficall_flag = {0};", (!flag) ? "false" : "true"); } @@ -116,15 +141,15 @@ public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget text2 = text2.Replace(" ", "_"); textWriter.WriteLine("\tmono_aot_register_module(mono_aot_module_{0}_info);", text2); } + textWriter.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR) && !defined(__arm64__)"); textWriter.WriteLine(string.Empty); - if (buildTarget == BuildTarget.iPhone) + if (buildTarget == BuildTarget.iOS) { foreach (string arg3 in arrayList) { - textWriter.WriteLine("\tmono_dl_register_symbol(\"{0}\", (void*)&{0});", arg3); + textWriter.WriteLine("\tREGISTER_USER_FUNC({0});", arg3); } } - textWriter.WriteLine("#endif // !(TARGET_IPHONE_SIMULATOR)"); textWriter.WriteLine("}"); textWriter.WriteLine(string.Empty); AssemblyDefinition assemblyDefinition2 = null; @@ -135,7 +160,7 @@ public static void WriteCPlusPlusFileForStaticAOTModuleRegistration(BuildTarget assemblyDefinition2 = assemblyDefinitions[k]; } } - if (buildTarget == BuildTarget.iPhone) + if (buildTarget == BuildTarget.iOS) { AssemblyDefinition[] assemblies = new AssemblyDefinition[] { @@ -239,6 +264,10 @@ private static void GenerateInternalCallMethod(TypeDefinition typeDefinition, Me string text2 = string.Format("\tRegister_{0}_{1}_{2} ();", typeDefinition.Namespace, typeDefinition.Name, method.Name); text2 = text2.Replace('.', '_'); text = text.Replace('.', '_'); + if (text2.Contains("UnityEngine.Serialization")) + { + return; + } output.WriteLine(text); output.WriteLine(text2); } diff --git a/UnityEditor/UnityEditor/MonoAssemblyStripping.cs b/UnityEditor/UnityEditor/MonoAssemblyStripping.cs index 1816e3cf..6c1c5c02 100644 --- a/UnityEditor/UnityEditor/MonoAssemblyStripping.cs +++ b/UnityEditor/UnityEditor/MonoAssemblyStripping.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Linq; using UnityEditor.Utils; using UnityEngine; namespace UnityEditor @@ -151,32 +150,41 @@ public static void MonoLink(BuildTarget buildTarget, string managedLibrariesDire ProcessStartInfo expr_110 = process.StartInfo; expr_110.Arguments = expr_110.Arguments + " -x \"" + text5 + "\""; } + string text6 = Path.Combine(Path.GetDirectoryName(text2), "native_link.xml"); + if (File.Exists(text6)) + { + ProcessStartInfo expr_151 = process.StartInfo; + expr_151.Arguments = expr_151.Arguments + " -x \"" + text6 + "\""; + } string[] files = Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "link.xml", SearchOption.AllDirectories); string[] array = files; for (int j = 0; j < array.Length; j++) { string str2 = array[j]; - ProcessStartInfo expr_161 = process.StartInfo; - expr_161.Arguments = expr_161.Arguments + " -x \"" + str2 + "\""; + ProcessStartInfo expr_1A2 = process.StartInfo; + expr_1A2.Arguments = expr_1A2.Arguments + " -x \"" + str2 + "\""; } if (usedClasses != null) { text = MonoAssemblyStripping.GenerateBlackList(managedLibrariesDirectory, usedClasses, allAssemblies); - ProcessStartInfo expr_1A5 = process.StartInfo; - expr_1A5.Arguments = expr_1A5.Arguments + " -x \"" + text + "\""; + ProcessStartInfo expr_1E6 = process.StartInfo; + expr_1E6.Arguments = expr_1E6.Arguments + " -x \"" + text + "\""; } MonoProcessUtility.RunMonoProcess(process, "assemblies stripper", Path.Combine(text4, "mscorlib.dll")); - if (buildTarget == BuildTarget.FlashPlayer) - { - IEnumerable files2 = - from _ in input - select Path.GetFileName(_); - MonoAssemblyStripping.CopyFiles(files2, text4, managedLibrariesDirectory); - } - else + MonoAssemblyStripping.DeleteAllDllsFrom(managedLibrariesDirectory); + MonoAssemblyStripping.CopyAllDlls(managedLibrariesDirectory, text4); + string[] files2 = Directory.GetFiles(managedLibrariesDirectory); + for (int k = 0; k < files2.Length; k++) { - MonoAssemblyStripping.DeleteAllDllsFrom(managedLibrariesDirectory); - MonoAssemblyStripping.CopyAllDlls(managedLibrariesDirectory, text4); + string text7 = files2[k]; + if (text7.Contains(".mdb")) + { + string path = text7.Replace(".mdb", string.Empty); + if (!File.Exists(path)) + { + FileUtil.DeleteFileOrDirectory(text7); + } + } } if (text != null) { diff --git a/UnityEditor/UnityEditor/MonoCrossCompile.cs b/UnityEditor/UnityEditor/MonoCrossCompile.cs index 5a1212aa..57e070b9 100644 --- a/UnityEditor/UnityEditor/MonoCrossCompile.cs +++ b/UnityEditor/UnityEditor/MonoCrossCompile.cs @@ -71,7 +71,7 @@ public static void CrossCompileAOTDirectory(BuildTarget buildTarget, CrossCompil string output = Path.Combine(targetCrossCompiledASMFolder, fileName + ".s"); if (EditorUtility.DisplayCancelableProgressBar("Building Player", "AOT cross compile " + fileName, 0.95f)) { - return; + throw new OperationCanceledException(); } MonoCrossCompile.CrossCompileAOT(buildTarget, text, sourceAssembliesFolder, crossCompileOptions, fileName, output, additionalOptions); } @@ -136,23 +136,20 @@ where Path.GetExtension(path) == ".dll" long num4 = (long)Math.Min(1800000, (count + 3) * 1000 * 30); foreach (string current in list3) { - if (!(Path.GetExtension(current) != ".dll")) + string fileName = Path.GetFileName(current); + string output = Path.Combine(targetCrossCompiledASMFolder, fileName + ".s"); + MonoCrossCompile.JobCompileAOT jobCompileAOT = new MonoCrossCompile.JobCompileAOT(buildTarget, crossCompilerPath, sourceAssembliesFolder, crossCompileOptions, fileName, output, additionalOptions); + list.Add(jobCompileAOT); + list2.Add(jobCompileAOT.m_doneEvent); + ThreadPool.QueueUserWorkItem(new WaitCallback(jobCompileAOT.ThreadPoolCallback)); + if (list2.Count >= Environment.ProcessorCount) { - string fileName = Path.GetFileName(current); - string output = Path.Combine(targetCrossCompiledASMFolder, fileName + ".s"); - MonoCrossCompile.JobCompileAOT jobCompileAOT = new MonoCrossCompile.JobCompileAOT(buildTarget, crossCompilerPath, sourceAssembliesFolder, crossCompileOptions, fileName, output, additionalOptions); - list.Add(jobCompileAOT); - list2.Add(jobCompileAOT.m_doneEvent); - ThreadPool.QueueUserWorkItem(new WaitCallback(jobCompileAOT.ThreadPoolCallback)); - if (list2.Count >= Environment.ProcessorCount) + flag = MonoCrossCompile.WaitForBuildOfFile(list2, ref num4); + MonoCrossCompile.DisplayAOTProgressBar(count, num3); + num3++; + if (!flag) { - flag = MonoCrossCompile.WaitForBuildOfFile(list2, ref num4); - MonoCrossCompile.DisplayAOTProgressBar(count, num3); - num3++; - if (!flag) - { - break; - } + break; } } } @@ -170,7 +167,11 @@ where Path.GetExtension(path) == ".dll" { if (current2.m_Exception != null) { - UnityEngine.Debug.LogError(string.Format("Cross compilation job {0} failed.\n{1}", current2.m_input, current2.m_Exception.ToString())); + UnityEngine.Debug.LogErrorFormat("Cross compilation job {0} failed.\n{1}", new object[] + { + current2.m_input, + current2.m_Exception + }); flag = false; } } @@ -216,7 +217,7 @@ private static void CrossCompileAOT(BuildTarget target, string crossCompilerAbso text += "nodebug,"; } } - if (target != BuildTarget.iPhone) + if (target != BuildTarget.iOS) { text += "print-skipped,"; } diff --git a/UnityEditor/UnityEditor/MonoProcessRunner.cs b/UnityEditor/UnityEditor/MonoProcessRunner.cs new file mode 100644 index 00000000..629b8a5c --- /dev/null +++ b/UnityEditor/UnityEditor/MonoProcessRunner.cs @@ -0,0 +1,68 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +namespace UnityEditor +{ + internal class MonoProcessRunner + { + public StringBuilder Output = new StringBuilder(string.Empty); + public StringBuilder Error = new StringBuilder(string.Empty); + public bool Run(Process process) + { + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + Thread thread = new Thread(new ParameterizedThreadStart(this.ReadOutput)); + Thread thread2 = new Thread(new ParameterizedThreadStart(this.ReadErrors)); + process.Start(); + thread.Start(process); + thread2.Start(process); + bool result = process.WaitForExit(600000); + DateTime now = DateTime.Now; + while ((thread.IsAlive || thread2.IsAlive) && (DateTime.Now - now).TotalMilliseconds < 5.0) + { + Thread.Sleep(0); + } + if (thread.IsAlive) + { + thread.Abort(); + } + if (thread2.IsAlive) + { + thread2.Abort(); + } + thread.Join(); + thread2.Join(); + return result; + } + private void ReadOutput(object process) + { + Process process2 = process as Process; + try + { + using (StreamReader standardOutput = process2.StandardOutput) + { + this.Output.Append(standardOutput.ReadToEnd()); + } + } + catch (ThreadAbortException) + { + } + } + private void ReadErrors(object process) + { + Process process2 = process as Process; + try + { + using (StreamReader standardError = process2.StandardError) + { + this.Error.Append(standardError.ReadToEnd()); + } + } + catch (ThreadAbortException) + { + } + } + } +} diff --git a/UnityEditor/UnityEditor/MonoProcessUtility.cs b/UnityEditor/UnityEditor/MonoProcessUtility.cs index 3c5cafd6..89c310b4 100644 --- a/UnityEditor/UnityEditor/MonoProcessUtility.cs +++ b/UnityEditor/UnityEditor/MonoProcessUtility.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using System.IO; -using System.Text; using UnityEngine; namespace UnityEditor { @@ -9,11 +8,6 @@ internal class MonoProcessUtility { public static string ProcessToString(Process process) { - string text = string.Empty; - foreach (string text2 in process.StartInfo.EnvironmentVariables.Keys) - { - text += string.Format("{0} = '{1}'\n", text2, process.StartInfo.EnvironmentVariables[text2]); - } return string.Concat(new string[] { process.StartInfo.FileName, @@ -21,38 +15,15 @@ public static string ProcessToString(Process process) process.StartInfo.Arguments, " current dir : ", process.StartInfo.WorkingDirectory, - "\n Env: ", - text + "\n" }); } public static void RunMonoProcess(Process process, string name, string resultingFile) { - StringBuilder output = new StringBuilder(string.Empty); - StringBuilder error = new StringBuilder(string.Empty); - process.StartInfo.RedirectStandardOutput = true; - process.StartInfo.RedirectStandardError = true; - process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs dataLine) - { - if (!string.IsNullOrEmpty(dataLine.Data)) - { - output.Append(dataLine.Data); - } - }; - process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs dataLine) - { - if (!string.IsNullOrEmpty(dataLine.Data)) - { - error.Append(dataLine.Data); - } - }; - process.Start(); - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - bool flag = process.WaitForExit(300000); + MonoProcessRunner monoProcessRunner = new MonoProcessRunner(); + bool flag = monoProcessRunner.Run(process); if (process.ExitCode != 0 || !File.Exists(resultingFile)) { - process.CancelOutputRead(); - process.CancelErrorRead(); string text = string.Concat(new object[] { "Failed ", @@ -70,10 +41,17 @@ public static void RunMonoProcess(Process process, string name, string resulting { text2, "stdout:\n", - output, - "\n\n" + monoProcessRunner.Output, + "\n" + }); + text2 = text; + text = string.Concat(new object[] + { + text2, + "stderr:\n", + monoProcessRunner.Error, + "\n" }); - text = text + "stderr:\n" + error; Console.WriteLine(text); throw new UnityException(text); } diff --git a/UnityEditor/UnityEditor/MonoScript.cs b/UnityEditor/UnityEditor/MonoScript.cs index d28ae044..4130c522 100644 --- a/UnityEditor/UnityEditor/MonoScript.cs +++ b/UnityEditor/UnityEditor/MonoScript.cs @@ -5,15 +5,6 @@ namespace UnityEditor { public sealed class MonoScript : TextAsset { - internal extern ScriptableObject editorGraphData - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern MonoScript(); diff --git a/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs b/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs index 83dea313..6e8c3f79 100644 --- a/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs +++ b/UnityEditor/UnityEditor/MonoScriptImporterInspector.cs @@ -14,7 +14,7 @@ internal class MonoScriptImporterInspector : AssetImporterInspector private SerializedProperty m_Icon; internal override void OnHeaderControlsGUI() { - TextAsset textAsset = base.assetEditor.target as TextAsset; + TextAsset textAsset = this.assetEditor.target as TextAsset; GUILayout.FlexibleSpace(); if (GUILayout.Button("Open...", EditorStyles.miniButton, new GUILayoutOption[0])) { @@ -31,10 +31,10 @@ internal override void OnHeaderIconGUI(Rect iconRect) { if (this.m_Icon == null) { - this.m_TargetObject = new SerializedObject(base.assetEditor.targets); + this.m_TargetObject = new SerializedObject(this.assetEditor.targets); this.m_Icon = this.m_TargetObject.FindProperty("m_Icon"); } - EditorGUI.ObjectIconDropDown(iconRect, base.assetEditor.targets, true, null, this.m_Icon); + EditorGUI.ObjectIconDropDown(iconRect, this.assetEditor.targets, true, null, this.m_Icon); } [MenuItem("CONTEXT/MonoImporter/Reset")] private static void ResetDefaultReferences(MenuCommand command) @@ -43,9 +43,13 @@ private static void ResetDefaultReferences(MenuCommand command) monoImporter.SetDefaultReferences(new string[0], new UnityEngine.Object[0]); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter)); } + private static bool IsTypeCompatible(Type type) + { + return type != null && type.IsSubclassOf(typeof(MonoBehaviour)); + } private void ShowFieldInfo(Type type, MonoImporter importer, List names, List objects, ref bool didModify) { - if (type == null || !type.IsSubclassOf(typeof(MonoBehaviour))) + if (!MonoScriptImporterInspector.IsTypeCompatible(type)) { return; } @@ -58,20 +62,20 @@ private void ShowFieldInfo(Type type, MonoImporter importer, List names, FieldInfo fieldInfo = array[i]; if (fieldInfo.IsPublic) { - goto IL_77; + goto IL_67; } object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(SerializeField), true); if (customAttributes != null && customAttributes.Length != 0) { - goto IL_77; + goto IL_67; } - IL_FC: + IL_EC: i++; continue; - IL_77: + IL_67: if (!fieldInfo.FieldType.IsSubclassOf(typeof(UnityEngine.Object)) && fieldInfo.FieldType != typeof(UnityEngine.Object)) { - goto IL_FC; + goto IL_EC; } UnityEngine.Object defaultReference = importer.GetDefaultReference(fieldInfo.Name); UnityEngine.Object @object = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(fieldInfo.Name), defaultReference, fieldInfo.FieldType, false, new GUILayoutOption[0]); @@ -80,31 +84,35 @@ private void ShowFieldInfo(Type type, MonoImporter importer, List names, if (defaultReference != @object) { didModify = true; - goto IL_FC; + goto IL_EC; } - goto IL_FC; + goto IL_EC; } } public override void OnInspectorGUI() { - Vector2 iconSize = EditorGUIUtility.GetIconSize(); - EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); MonoImporter monoImporter = this.target as MonoImporter; MonoScript script = monoImporter.GetScript(); if (script) { + Type @class = script.GetClass(); + if (!MonoScriptImporterInspector.IsTypeCompatible(@class)) + { + EditorGUILayout.HelpBox("No MonoBehaviour scripts in the file, or their names do not match the file name.", MessageType.Info); + } + Vector2 iconSize = EditorGUIUtility.GetIconSize(); + EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); List list = new List(); List list2 = new List(); bool flag = false; - Type @class = script.GetClass(); this.ShowFieldInfo(@class, monoImporter, list, list2, ref flag); + EditorGUIUtility.SetIconSize(iconSize); if (flag) { monoImporter.SetDefaultReferences(list.ToArray(), list2.ToArray()); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter)); } } - EditorGUIUtility.SetIconSize(iconSize); } } } diff --git a/UnityEditor/UnityEditor/MonoScriptInspector.cs b/UnityEditor/UnityEditor/MonoScriptInspector.cs index 5c2f9896..b263faec 100644 --- a/UnityEditor/UnityEditor/MonoScriptInspector.cs +++ b/UnityEditor/UnityEditor/MonoScriptInspector.cs @@ -4,8 +4,5 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(MonoScript))] internal class MonoScriptInspector : TextAssetInspector { - protected override void OnHeaderGUI() - { - } } } diff --git a/UnityEditor/UnityEditor/MovieImporterInspector.cs b/UnityEditor/UnityEditor/MovieImporterInspector.cs index a79d6c1d..69a70821 100644 --- a/UnityEditor/UnityEditor/MovieImporterInspector.cs +++ b/UnityEditor/UnityEditor/MovieImporterInspector.cs @@ -49,7 +49,7 @@ public override void OnInspectorGUI() GUILayout.EndVertical(); } base.ApplyRevertGUI(); - MovieTexture movieTexture = base.assetEditor.target as MovieTexture; + MovieTexture movieTexture = this.assetEditor.target as MovieTexture; if (movieTexture && movieTexture.loop) { EditorGUILayout.Space(); diff --git a/UnityEditor/UnityEditor/MovieTextureInspector.cs b/UnityEditor/UnityEditor/MovieTextureInspector.cs index 564214a7..9aa707ce 100644 --- a/UnityEditor/UnityEditor/MovieTextureInspector.cs +++ b/UnityEditor/UnityEditor/MovieTextureInspector.cs @@ -74,8 +74,9 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) } } } - public void OnDisable() + protected override void OnDisable() { + base.OnDisable(); MovieTexture movieTexture = this.target as MovieTexture; if (!Application.isPlaying && movieTexture != null) { diff --git a/UnityEditor/UnityEditor/NavMeshAgentInspector.cs b/UnityEditor/UnityEditor/NavMeshAgentInspector.cs index 12d76e33..d6d3f6eb 100644 --- a/UnityEditor/UnityEditor/NavMeshAgentInspector.cs +++ b/UnityEditor/UnityEditor/NavMeshAgentInspector.cs @@ -5,6 +5,13 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(NavMeshAgent))] internal class NavMeshAgentInspector : Editor { + private class Styles + { + public readonly GUIContent m_AgentSizeHeader = new GUIContent("Agent Size"); + public readonly GUIContent m_AgentSteeringHeader = new GUIContent("Steering"); + public readonly GUIContent m_AgentAvoidanceHeader = new GUIContent("Obstacle Avoidance"); + public readonly GUIContent m_AgentPathFindingHeader = new GUIContent("Path Finding"); + } private SerializedProperty m_WalkableMask; private SerializedProperty m_Radius; private SerializedProperty m_Speed; @@ -18,6 +25,7 @@ internal class NavMeshAgentInspector : Editor private SerializedProperty m_BaseOffset; private SerializedProperty m_ObstacleAvoidanceType; private SerializedProperty m_AvoidancePriority; + private static NavMeshAgentInspector.Styles s_Styles; private void OnEnable() { this.m_WalkableMask = base.serializedObject.FindProperty("m_WalkableMask"); @@ -36,26 +44,37 @@ private void OnEnable() } public override void OnInspectorGUI() { + if (NavMeshAgentInspector.s_Styles == null) + { + NavMeshAgentInspector.s_Styles = new NavMeshAgentInspector.Styles(); + } base.serializedObject.Update(); + EditorGUILayout.LabelField(NavMeshAgentInspector.s_Styles.m_AgentSizeHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BaseOffset, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.LabelField(NavMeshAgentInspector.s_Styles.m_AgentSteeringHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Speed, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Acceleration, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_AngularSpeed, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_Acceleration, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_StoppingDistance, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_AutoTraverseOffMeshLink, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_AutoBraking, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.LabelField(NavMeshAgentInspector.s_Styles.m_AgentAvoidanceHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ObstacleAvoidanceType, GUIContent.Temp("Quality"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AvoidancePriority, GUIContent.Temp("Priority"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.LabelField(NavMeshAgentInspector.s_Styles.m_AgentPathFindingHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_AutoTraverseOffMeshLink, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_AutoRepath, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_BaseOffset, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_ObstacleAvoidanceType, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_AvoidancePriority, new GUILayoutOption[0]); - string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); + string[] navMeshAreaNames = GameObjectUtility.GetNavMeshAreaNames(); int intValue = this.m_WalkableMask.intValue; int num = 0; - for (int i = 0; i < navMeshLayerNames.Length; i++) + for (int i = 0; i < navMeshAreaNames.Length; i++) { - int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]); - if ((1 << navMeshLayerFromName & intValue) > 0) + int navMeshAreaFromName = GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[i]); + if ((1 << navMeshAreaFromName & intValue) > 0) { num |= 1 << i; } @@ -63,7 +82,7 @@ public override void OnInspectorGUI() Rect rect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMinW, EditorGUILayout.kLabelFloatMaxW, 16f, 16f, EditorStyles.layerMaskField); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.m_WalkableMask.hasMultipleDifferentValues; - int num2 = EditorGUI.MaskField(rect, "NavMesh Walkable", num, navMeshLayerNames, EditorStyles.layerMaskField); + int num2 = EditorGUI.MaskField(rect, "Area Mask", num, navMeshAreaNames, EditorStyles.layerMaskField); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { @@ -74,11 +93,11 @@ public override void OnInspectorGUI() else { int num3 = 0; - for (int j = 0; j < navMeshLayerNames.Length; j++) + for (int j = 0; j < navMeshAreaNames.Length; j++) { if ((num2 >> j & 1) > 0) { - num3 |= 1 << GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[j]); + num3 |= 1 << GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[j]); } } this.m_WalkableMask.intValue = num3; diff --git a/UnityEditor/UnityEditor/NavMeshEditorWindow.cs b/UnityEditor/UnityEditor/NavMeshEditorWindow.cs index 4e30df3b..3a8b4525 100644 --- a/UnityEditor/UnityEditor/NavMeshEditorWindow.cs +++ b/UnityEditor/UnityEditor/NavMeshEditorWindow.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { @@ -10,7 +11,7 @@ private enum Mode { ObjectSettings, BakeSettings, - LayerSettings + AreaSettings } private class Styles { @@ -22,20 +23,22 @@ private class Styles public readonly GUIContent m_AgentJumpContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.JumpDistance"); public readonly GUIContent m_AgentPlacementContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.HeightMesh"); public readonly GUIContent m_MinRegionAreaContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.MinRegionArea"); - public readonly GUIContent m_WidthInaccuracyContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.WidthInaccuracy"); - public readonly GUIContent m_HeightInaccuracyContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.HeightInaccuracy"); - public readonly GUIContent m_GeneralHeader = new GUIContent("General"); + public readonly GUIContent m_ManualCellSizeContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.ManualCellSize"); + public readonly GUIContent m_CellSizeContent = EditorGUIUtility.TextContent("NavMeshEditorWindow.CellSize"); + public readonly GUIContent m_AgentSizeHeader = new GUIContent("Baked Agent Size"); public readonly GUIContent m_OffmeshHeader = new GUIContent("Generated Off Mesh Links"); public readonly GUIContent m_AdvancedHeader = new GUIContent("Advanced"); + public readonly GUIContent m_NameLabel = new GUIContent("Name"); + public readonly GUIContent m_CostLabel = new GUIContent("Cost"); public readonly GUIContent[] m_ModeToggles = new GUIContent[] { EditorGUIUtility.TextContent("NavmeshEditor.ObjectSettings"), EditorGUIUtility.TextContent("NavmeshEditor.BakeSettings"), - EditorGUIUtility.TextContent("NavmeshEditor.LayerSettings") + EditorGUIUtility.TextContent("NavmeshEditor.AreaSettings") }; } private const string kRootPath = "m_BuildSettings."; - private static NavMeshEditorWindow s_MsNavMeshEditorWindow; + private static NavMeshEditorWindow s_NavMeshEditorWindow; private SerializedObject m_Object; private SerializedProperty m_AgentRadius; private SerializedProperty m_AgentHeight; @@ -43,15 +46,21 @@ private class Styles private SerializedProperty m_AgentClimb; private SerializedProperty m_LedgeDropHeight; private SerializedProperty m_MaxJumpAcrossDistance; - private SerializedProperty m_AccuratePlacement; private SerializedProperty m_MinRegionArea; - private SerializedProperty m_WidthInaccuracy; - private SerializedProperty m_HeightInaccuracy; + private SerializedProperty m_ManualCellSize; + private SerializedProperty m_CellSize; + private SerializedProperty m_AccuratePlacement; + private SerializedObject m_NavMeshAreasObject; + private SerializedProperty m_Areas; private static NavMeshEditorWindow.Styles s_Styles; private Vector2 m_ScrollPos = Vector2.zero; - private bool m_HasSelectedNavMeshAgents; - private NavMeshEditorWindow.Mode m_Mode; + private int m_SelectedNavMeshAgentCount; + private int m_SelectedNavMeshObstacleCount; private bool m_Advanced; + private bool m_HasPendingAgentDebugInfo; + private bool m_HasRepaintedForPendingAgentDebugInfo; + private ReorderableList m_AreasList; + private NavMeshEditorWindow.Mode m_Mode; [MenuItem("Window/Navigation", false, 2100)] public static void SetupWindow() { @@ -64,11 +73,11 @@ public static void SetupWindow() } public void OnEnable() { - NavMeshEditorWindow.s_MsNavMeshEditorWindow = this; - NavMeshEditorWindow.s_Styles = new NavMeshEditorWindow.Styles(); + NavMeshEditorWindow.s_NavMeshEditorWindow = this; this.Init(); EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Combine(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); + this.UpdateSelectedAgentAndObstacleState(); base.Repaint(); } private void Init() @@ -80,31 +89,52 @@ private void Init() this.m_LedgeDropHeight = this.m_Object.FindProperty("m_BuildSettings.ledgeDropHeight"); this.m_AgentClimb = this.m_Object.FindProperty("m_BuildSettings.agentClimb"); this.m_MaxJumpAcrossDistance = this.m_Object.FindProperty("m_BuildSettings.maxJumpAcrossDistance"); - this.m_AccuratePlacement = this.m_Object.FindProperty("m_BuildSettings.accuratePlacement"); this.m_MinRegionArea = this.m_Object.FindProperty("m_BuildSettings.minRegionArea"); - this.m_WidthInaccuracy = this.m_Object.FindProperty("m_BuildSettings.widthInaccuracy"); - this.m_HeightInaccuracy = this.m_Object.FindProperty("m_BuildSettings.heightInaccuracy"); + this.m_ManualCellSize = this.m_Object.FindProperty("m_BuildSettings.manualCellSize"); + this.m_CellSize = this.m_Object.FindProperty("m_BuildSettings.cellSize"); + this.m_AccuratePlacement = this.m_Object.FindProperty("m_BuildSettings.accuratePlacement"); + UnityEngine.Object serializedAssetInterfaceSingleton = Unsupported.GetSerializedAssetInterfaceSingleton("NavMeshAreas"); + this.m_NavMeshAreasObject = new SerializedObject(serializedAssetInterfaceSingleton); + this.m_Areas = this.m_NavMeshAreasObject.FindProperty("areas"); + if (this.m_AreasList == null && this.m_NavMeshAreasObject != null && this.m_Areas != null) + { + this.m_AreasList = new ReorderableList(this.m_NavMeshAreasObject, this.m_Areas, false, false, false, false); + this.m_AreasList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawAreaListElement); + this.m_AreasList.drawHeaderCallback = new ReorderableList.HeaderCallbackDelegate(this.DrawAreaListHeader); + this.m_AreasList.elementHeight = EditorGUIUtility.singleLineHeight + 2f; + } + } + private int Bit(int a, int b) + { + return (a & 1 << b) >> b; + } + private Color GetAreaColor(int i) + { + if (i == 0) + { + return new Color(0f, 0.75f, 1f, 0.5f); + } + int num = (this.Bit(i, 4) + this.Bit(i, 1) * 2 + 1) * 63; + int num2 = (this.Bit(i, 3) + this.Bit(i, 2) * 2 + 1) * 63; + int num3 = (this.Bit(i, 5) + this.Bit(i, 0) * 2 + 1) * 63; + return new Color((float)num / 255f, (float)num2 / 255f, (float)num3 / 255f, 0.5f); } public void OnDisable() { - NavMeshEditorWindow.s_MsNavMeshEditorWindow = null; + NavMeshEditorWindow.s_NavMeshEditorWindow = null; EditorApplication.searchChanged = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.searchChanged, new EditorApplication.CallbackFunction(base.Repaint)); SceneView.onSceneGUIDelegate = (SceneView.OnSceneFunc)Delegate.Remove(SceneView.onSceneGUIDelegate, new SceneView.OnSceneFunc(this.OnSceneViewGUI)); } + private void UpdateSelectedAgentAndObstacleState() + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(NavMeshAgent), (SelectionMode)12); + UnityEngine.Object[] filtered2 = Selection.GetFiltered(typeof(NavMeshObstacle), (SelectionMode)12); + this.m_SelectedNavMeshAgentCount = filtered.Length; + this.m_SelectedNavMeshObstacleCount = filtered2.Length; + } private void OnSelectionChange() { - this.m_HasSelectedNavMeshAgents = false; - Transform[] transforms = Selection.GetTransforms((SelectionMode)12); - Transform[] array = transforms; - for (int i = 0; i < array.Length; i++) - { - Transform transform = array[i]; - if (transform.gameObject.GetComponent() != null) - { - this.m_HasSelectedNavMeshAgents = true; - break; - } - } + this.UpdateSelectedAgentAndObstacleState(); this.m_ScrollPos = Vector2.zero; if (this.m_Mode == NavMeshEditorWindow.Mode.ObjectSettings) { @@ -115,14 +145,113 @@ private void ModeToggle() { this.m_Mode = (NavMeshEditorWindow.Mode)GUILayout.Toolbar((int)this.m_Mode, NavMeshEditorWindow.s_Styles.m_ModeToggles, "LargeButton", new GUILayoutOption[0]); } + private void GetAreaListRects(Rect rect, out Rect stripeRect, out Rect labelRect, out Rect nameRect, out Rect costRect) + { + float num = EditorGUIUtility.singleLineHeight * 0.8f; + float num2 = EditorGUIUtility.singleLineHeight * 5f; + float num3 = EditorGUIUtility.singleLineHeight * 4f; + float num4 = rect.width - num - num2 - num3; + float num5 = rect.x; + stripeRect = new Rect(num5, rect.y, num - 4f, rect.height); + num5 += num; + labelRect = new Rect(num5, rect.y, num2 - 4f, rect.height); + num5 += num2; + nameRect = new Rect(num5, rect.y, num4 - 4f, rect.height); + num5 += num4; + costRect = new Rect(num5, rect.y, num3, rect.height); + } + private void DrawAreaListHeader(Rect rect) + { + Rect rect2; + Rect rect3; + Rect position; + Rect position2; + this.GetAreaListRects(rect, out rect2, out rect3, out position, out position2); + GUI.Label(position, NavMeshEditorWindow.s_Styles.m_NameLabel); + GUI.Label(position2, NavMeshEditorWindow.s_Styles.m_CostLabel); + } + private void DrawAreaListElement(Rect rect, int index, bool selected, bool focused) + { + SerializedProperty arrayElementAtIndex = this.m_Areas.GetArrayElementAtIndex(index); + if (arrayElementAtIndex == null) + { + return; + } + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("name"); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("cost"); + if (serializedProperty == null || serializedProperty2 == null) + { + return; + } + rect.height -= 2f; + bool flag; + bool flag2; + bool flag3; + switch (index) + { + case 0: + flag = true; + flag2 = false; + flag3 = true; + break; + case 1: + flag = true; + flag2 = false; + flag3 = false; + break; + case 2: + flag = true; + flag2 = false; + flag3 = true; + break; + default: + flag = false; + flag2 = true; + flag3 = true; + break; + } + Rect rect2; + Rect position; + Rect position2; + Rect position3; + this.GetAreaListRects(rect, out rect2, out position, out position2, out position3); + bool enabled = GUI.enabled; + Color areaColor = this.GetAreaColor(index); + Color color = new Color(areaColor.r * 0.1f, areaColor.g * 0.1f, areaColor.b * 0.1f, 0.6f); + EditorGUI.DrawRect(rect2, areaColor); + EditorGUI.DrawRect(new Rect(rect2.x, rect2.y, 1f, rect2.height), color); + EditorGUI.DrawRect(new Rect(rect2.x + rect2.width - 1f, rect2.y, 1f, rect2.height), color); + EditorGUI.DrawRect(new Rect(rect2.x + 1f, rect2.y, rect2.width - 2f, 1f), color); + EditorGUI.DrawRect(new Rect(rect2.x + 1f, rect2.y + rect2.height - 1f, rect2.width - 2f, 1f), color); + if (flag) + { + GUI.Label(position, EditorGUIUtility.TempContent("Built-in " + index)); + } + else + { + GUI.Label(position, EditorGUIUtility.TempContent("User " + index)); + } + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUI.BeginChangeCheck(); + GUI.enabled = (enabled && flag2); + EditorGUI.PropertyField(position2, serializedProperty, GUIContent.none); + GUI.enabled = (enabled && flag3); + EditorGUI.PropertyField(position3, serializedProperty2, GUIContent.none); + GUI.enabled = enabled; + EditorGUI.indentLevel = indentLevel; + } public void OnGUI() { if (this.m_Object.targetObject == null) { this.Init(); } + if (NavMeshEditorWindow.s_Styles == null) + { + NavMeshEditorWindow.s_Styles = new NavMeshEditorWindow.Styles(); + } this.m_Object.Update(); - EditorGUIUtility.labelWidth = 130f; EditorGUILayout.Space(); this.ModeToggle(); EditorGUILayout.Space(); @@ -135,8 +264,8 @@ public void OnGUI() case NavMeshEditorWindow.Mode.BakeSettings: this.BakeSettings(); break; - case NavMeshEditorWindow.Mode.LayerSettings: - this.LayerSettings(); + case NavMeshEditorWindow.Mode.AreaSettings: + this.AreaSettings(); break; } EditorGUILayout.EndScrollView(); @@ -174,10 +303,14 @@ public void OnSceneViewGUI(SceneView sceneView) return; } SceneViewOverlay.Window(new GUIContent("Navmesh Display"), new SceneViewOverlay.WindowFunction(NavMeshEditorWindow.DisplayControls), 300, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); - if (this.m_HasSelectedNavMeshAgents) + if (this.m_SelectedNavMeshAgentCount > 0) { SceneViewOverlay.Window(new GUIContent("Agent Display"), new SceneViewOverlay.WindowFunction(NavMeshEditorWindow.DisplayAgentControls), 300, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); } + if (this.m_SelectedNavMeshObstacleCount > 0) + { + SceneViewOverlay.Window(new GUIContent("Obstacle Display"), new SceneViewOverlay.WindowFunction(NavMeshEditorWindow.DisplayObstacleControls), 300, SceneViewOverlay.WindowDisplayOption.OneWindowPerTarget); + } } private static void DisplayControls(UnityEngine.Object target, SceneView sceneView) { @@ -197,15 +330,65 @@ private static void DisplayControls(UnityEngine.Object target, SceneView sceneVi flag = true; } EditorGUI.EndDisabledGroup(); + if (Unsupported.IsDeveloperBuild()) + { + GUILayout.Label("Internal", new GUILayoutOption[0]); + bool showNavMeshPortals = NavMeshVisualizationSettings.showNavMeshPortals; + if (showNavMeshPortals != EditorGUILayout.Toggle(new GUIContent("Show NavMesh Portals"), showNavMeshPortals, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showNavMeshPortals = !showNavMeshPortals; + flag = true; + } + bool showNavMeshLinks = NavMeshVisualizationSettings.showNavMeshLinks; + if (showNavMeshLinks != EditorGUILayout.Toggle(new GUIContent("Show NavMesh Links"), showNavMeshLinks, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showNavMeshLinks = !showNavMeshLinks; + flag = true; + } + bool showProximityGrid = NavMeshVisualizationSettings.showProximityGrid; + if (showProximityGrid != EditorGUILayout.Toggle(new GUIContent("Show Proximity Grid"), showProximityGrid, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showProximityGrid = !showProximityGrid; + flag = true; + } + bool showHeightMeshBVTree = NavMeshVisualizationSettings.showHeightMeshBVTree; + if (showHeightMeshBVTree != EditorGUILayout.Toggle(new GUIContent("Show HeightMesh BV-Tree"), showHeightMeshBVTree, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showHeightMeshBVTree = !showHeightMeshBVTree; + flag = true; + } + } if (flag) { NavMeshEditorWindow.RepaintSceneAndGameViews(); } } + private void OnInspectorUpdate() + { + if (this.m_SelectedNavMeshAgentCount > 0) + { + if (this.m_HasPendingAgentDebugInfo != NavMeshVisualizationSettings.hasPendingAgentDebugInfo) + { + if (!this.m_HasRepaintedForPendingAgentDebugInfo) + { + this.m_HasRepaintedForPendingAgentDebugInfo = true; + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + } + else + { + this.m_HasRepaintedForPendingAgentDebugInfo = false; + } + } + } private static void DisplayAgentControls(UnityEngine.Object target, SceneView sceneView) { EditorGUIUtility.labelWidth = 150f; bool flag = false; + if (Event.current.type == EventType.Layout) + { + NavMeshEditorWindow.s_NavMeshEditorWindow.m_HasPendingAgentDebugInfo = NavMeshVisualizationSettings.hasPendingAgentDebugInfo; + } bool showAgentPath = NavMeshVisualizationSettings.showAgentPath; if (showAgentPath != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentPath"), showAgentPath, new GUILayoutOption[0])) { @@ -230,6 +413,55 @@ private static void DisplayAgentControls(UnityEngine.Object target, SceneView sc NavMeshVisualizationSettings.showAgentWalls = !showAgentWalls; flag = true; } + bool showAgentAvoidance = NavMeshVisualizationSettings.showAgentAvoidance; + if (showAgentAvoidance != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowAgentAvoidance"), showAgentAvoidance, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showAgentAvoidance = !showAgentAvoidance; + flag = true; + } + if (showAgentAvoidance) + { + if (NavMeshEditorWindow.s_NavMeshEditorWindow.m_HasPendingAgentDebugInfo) + { + EditorGUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.MaxWidth(165f) + }); + EditorGUILayout.HelpBox("Avoidance display is not valid until after next game update.", MessageType.Warning); + EditorGUILayout.EndVertical(); + } + if (NavMeshEditorWindow.s_NavMeshEditorWindow.m_SelectedNavMeshAgentCount > 10) + { + EditorGUILayout.BeginVertical(new GUILayoutOption[] + { + GUILayout.MaxWidth(165f) + }); + EditorGUILayout.HelpBox(string.Concat(new object[] + { + "Avoidance visualization can be drawn for ", + 10, + " agents (", + NavMeshEditorWindow.s_NavMeshEditorWindow.m_SelectedNavMeshAgentCount, + " selected)." + }), MessageType.Warning); + EditorGUILayout.EndVertical(); + } + } + if (flag) + { + NavMeshEditorWindow.RepaintSceneAndGameViews(); + } + } + private static void DisplayObstacleControls(UnityEngine.Object target, SceneView sceneView) + { + EditorGUIUtility.labelWidth = 150f; + bool flag = false; + bool showObstacleCarveHull = NavMeshVisualizationSettings.showObstacleCarveHull; + if (showObstacleCarveHull != EditorGUILayout.Toggle(EditorGUIUtility.TextContent("NavMeshEditorWindow.ShowObstacleCarveHull"), showObstacleCarveHull, new GUILayoutOption[0])) + { + NavMeshVisualizationSettings.showObstacleCarveHull = !showObstacleCarveHull; + flag = true; + } if (flag) { NavMeshEditorWindow.RepaintSceneAndGameViews(); @@ -245,9 +477,9 @@ private void ResetBakeSettings() } public static void BackgroundTaskStatusChanged() { - if (NavMeshEditorWindow.s_MsNavMeshEditorWindow != null) + if (NavMeshEditorWindow.s_NavMeshEditorWindow != null) { - NavMeshEditorWindow.s_MsNavMeshEditorWindow.Repaint(); + NavMeshEditorWindow.s_NavMeshEditorWindow.Repaint(); } } private static IEnumerable GetObjectsRecurse(GameObject root) @@ -281,17 +513,17 @@ private static bool SelectionHasChildren() { return Selection.gameObjects.Any((GameObject obj) => obj.transform.childCount > 0); } - private static void SetNavMeshLayer(int layer, bool includeChildren) + private static void SetNavMeshArea(int area, bool includeChildren) { List objects = NavMeshEditorWindow.GetObjects(includeChildren); if (objects.Count <= 0) { return; } - Undo.RecordObjects(objects.ToArray(), "Change NavMesh layer"); + Undo.RecordObjects(objects.ToArray(), "Change NavMesh area"); foreach (GameObject current in objects) { - GameObjectUtility.SetNavMeshLayer(current, layer); + GameObjectUtility.SetNavMeshArea(current, area); } } private static void ObjectSettings() @@ -326,50 +558,140 @@ private static void ObjectSettings(UnityEngine.Object[] components, GameObject[] EditorGUILayout.MultiSelectionObjectTitleBar(components); SerializedObject serializedObject = new SerializedObject(gos); EditorGUI.BeginDisabledGroup(!SceneModeUtility.StaticFlagField("Navigation Static", serializedObject.FindProperty("m_StaticEditorFlags"), 8)); - SceneModeUtility.StaticFlagField("OffMeshLink Generation", serializedObject.FindProperty("m_StaticEditorFlags"), 32); + SceneModeUtility.StaticFlagField("Generate OffMeshLinks", serializedObject.FindProperty("m_StaticEditorFlags"), 32); SerializedProperty serializedProperty = serializedObject.FindProperty("m_NavMeshLayer"); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = serializedProperty.hasMultipleDifferentValues; - string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); - int navMeshLayer = GameObjectUtility.GetNavMeshLayer(gos[0]); + string[] navMeshAreaNames = GameObjectUtility.GetNavMeshAreaNames(); + int navMeshArea = GameObjectUtility.GetNavMeshArea(gos[0]); int selectedIndex = -1; - for (int i = 0; i < navMeshLayerNames.Length; i++) + for (int i = 0; i < navMeshAreaNames.Length; i++) { - if (GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]) == navMeshLayer) + if (GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[i]) == navMeshArea) { selectedIndex = i; break; } } - int num = EditorGUILayout.Popup("Navigation Layer", selectedIndex, navMeshLayerNames, new GUILayoutOption[0]); + int num = EditorGUILayout.Popup("Navigation Area", selectedIndex, navMeshAreaNames, new GUILayoutOption[0]); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { - int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[num]); - GameObjectUtility.ShouldIncludeChildren shouldIncludeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(Selection.gameObjects, "Change Navigation Layer", "Do you want change the navigation layer to " + navMeshLayerNames[num] + " for all the child objects as well?"); + int navMeshAreaFromName = GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[num]); + GameObjectUtility.ShouldIncludeChildren shouldIncludeChildren = GameObjectUtility.DisplayUpdateChildrenDialogIfNeeded(Selection.gameObjects, "Change Navigation Area", "Do you want change the navigation area to " + navMeshAreaNames[num] + " for all the child objects as well?"); if (shouldIncludeChildren != GameObjectUtility.ShouldIncludeChildren.Cancel) { - serializedProperty.intValue = navMeshLayerFromName; - NavMeshEditorWindow.SetNavMeshLayer(navMeshLayerFromName, shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); + serializedProperty.intValue = navMeshAreaFromName; + NavMeshEditorWindow.SetNavMeshArea(navMeshAreaFromName, shouldIncludeChildren == GameObjectUtility.ShouldIncludeChildren.IncludeChildren); } } EditorGUI.EndDisabledGroup(); serializedObject.ApplyModifiedProperties(); } + private void DrawAgentDiagram(Rect rect, float agentRadius, float agentHeight, float agentClimb, float agentSlope) + { + if (Event.current.type != EventType.Repaint) + { + return; + } + float num = 0.35f; + float num2 = 15f; + float num3 = rect.height - num2 * 2f; + float num4 = Mathf.Min(num3 / (agentHeight + agentRadius * 2f * num), num3 / (agentRadius * 2f)); + float num5 = agentHeight * num4; + float num6 = agentRadius * num4; + float num7 = agentClimb * num4; + float num8 = rect.xMin + rect.width * 0.5f; + float num9 = rect.yMax - num2 - num6 * num; + Vector3[] array = new Vector3[40]; + Vector3[] array2 = new Vector3[20]; + Vector3[] array3 = new Vector3[20]; + for (int i = 0; i < 20; i++) + { + float f = (float)i / 19f * 3.14159274f; + float num10 = Mathf.Cos(f); + float num11 = Mathf.Sin(f); + array[i] = new Vector3(num8 + num10 * num6, num9 - num5 - num11 * num6 * num, 0f); + array[i + 20] = new Vector3(num8 - num10 * num6, num9 + num11 * num6 * num, 0f); + array2[i] = new Vector3(num8 - num10 * num6, num9 - num5 + num11 * num6 * num, 0f); + array3[i] = new Vector3(num8 - num10 * num6, num9 - num7 + num11 * num6 * num, 0f); + } + Color color = Handles.color; + float xMin = rect.xMin; + float num12 = num9 - num7; + float num13 = num8 - num3 * 0.75f; + float y = num9; + float num14 = num8 + num3 * 0.75f; + float num15 = num9; + float num16 = num14; + float num17 = num15; + float num18 = rect.xMax - num14; + num16 += Mathf.Cos(agentSlope * 0.0174532924f) * num18; + num17 -= Mathf.Sin(agentSlope * 0.0174532924f) * num18; + Vector3[] points = new Vector3[] + { + new Vector3(xMin, num9, 0f), + new Vector3(num16, num9, 0f) + }; + Vector3[] points2 = new Vector3[] + { + new Vector3(xMin, num12, 0f), + new Vector3(num13, num12, 0f), + new Vector3(num13, y, 0f), + new Vector3(num14, num15, 0f), + new Vector3(num16, num17, 0f) + }; + Handles.color = ((!EditorGUIUtility.isProSkin) ? new Color(1f, 1f, 1f, 0.5f) : new Color(0f, 0f, 0f, 0.5f)); + Handles.DrawAAPolyLine(2f, points); + Handles.color = ((!EditorGUIUtility.isProSkin) ? new Color(0f, 0f, 0f, 0.5f) : new Color(1f, 1f, 1f, 0.5f)); + Handles.DrawAAPolyLine(3f, points2); + Handles.color = Color.Lerp(new Color(0f, 0.75f, 1f, 1f), new Color(0.5f, 0.5f, 0.5f, 0.5f), 0.2f); + Handles.DrawAAConvexPolygon(array); + Handles.color = new Color(0f, 0f, 0f, 0.5f); + Handles.DrawAAPolyLine(2f, array3); + Handles.color = new Color(1f, 1f, 1f, 0.4f); + Handles.DrawAAPolyLine(2f, array2); + Vector3[] points3 = new Vector3[] + { + new Vector3(num8, num9 - num5, 0f), + new Vector3(num8 + num6, num9 - num5, 0f) + }; + Handles.color = new Color(0f, 0f, 0f, 0.5f); + Handles.DrawAAPolyLine(2f, points3); + GUI.Label(new Rect(num8 + num6 + 5f, num9 - num5 * 0.5f - 10f, 150f, 20f), string.Format("H = {0}", agentHeight)); + GUI.Label(new Rect(num8, num9 - num5 - num6 * num - 15f, 150f, 20f), string.Format("R = {0}", agentRadius)); + GUI.Label(new Rect((xMin + num13) * 0.5f - 20f, num12 - 15f, 150f, 20f), string.Format("{0}", agentClimb)); + GUI.Label(new Rect(num14 + 20f, num15 - 15f, 150f, 20f), string.Format("{0}°", agentSlope)); + Handles.color = color; + } private void BakeSettings() { - EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_GeneralHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_AgentSizeHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + Rect controlRect = EditorGUILayout.GetControlRect(false, 120f, new GUILayoutOption[0]); + this.DrawAgentDiagram(controlRect, this.m_AgentRadius.floatValue, this.m_AgentHeight.floatValue, this.m_AgentClimb.floatValue, this.m_AgentSlope.floatValue); float num = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentRadiusContent, this.m_AgentRadius.floatValue, new GUILayoutOption[0]); if (num >= 0.001f && !Mathf.Approximately(num - this.m_AgentRadius.floatValue, 0f)) { this.m_AgentRadius.floatValue = num; + if (!this.m_ManualCellSize.boolValue) + { + this.m_CellSize.floatValue = 2f * this.m_AgentRadius.floatValue / 6f; + } + } + if (this.m_AgentRadius.floatValue < 0.05f && !this.m_ManualCellSize.boolValue) + { + EditorGUILayout.HelpBox("The agent radius you've set is really small, this can slow down the build.\nIf you intended to allow the agent to move close to the borders and walls, please adjust voxel size in advaced settings to ensure correct bake.", MessageType.Warning); } float num2 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentHeightContent, this.m_AgentHeight.floatValue, new GUILayoutOption[0]); if (num2 >= 0.001f && !Mathf.Approximately(num2 - this.m_AgentHeight.floatValue, 0f)) { this.m_AgentHeight.floatValue = num2; } - EditorGUILayout.Slider(this.m_AgentSlope, 0f, 90f, NavMeshEditorWindow.s_Styles.m_AgentSlopeContent, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_AgentSlope, 0f, 60f, NavMeshEditorWindow.s_Styles.m_AgentSlopeContent, new GUILayoutOption[0]); + if (this.m_AgentSlope.floatValue > 60f) + { + EditorGUILayout.HelpBox("The maximum slope should be set to less than " + 60f + " degrees to prevent NavMesh build artifacts on slopes. ", MessageType.Warning); + } float num3 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentClimbContent, this.m_AgentClimb.floatValue, new GUILayoutOption[0]); if (num3 >= 0f && !Mathf.Approximately(this.m_AgentClimb.floatValue - num3, 0f)) { @@ -379,9 +701,28 @@ private void BakeSettings() { EditorGUILayout.HelpBox("Step height should be less than agent height.\nClamping step height to " + this.m_AgentHeight.floatValue + ".", MessageType.Warning); } + float floatValue = this.m_CellSize.floatValue; + float num4 = floatValue * 0.5f; + int num5 = (int)Mathf.Ceil(this.m_AgentClimb.floatValue / num4); + float num6 = Mathf.Tan(this.m_AgentSlope.floatValue / 180f * 3.14159274f) * floatValue; + int num7 = (int)Mathf.Ceil(num6 * 2f / num4); + if (num7 > num5) + { + float f = (float)num5 * num4 / (floatValue * 2f); + float num8 = Mathf.Atan(f) / 3.14159274f * 180f; + float num9 = (float)(num7 - 1) * num4; + EditorGUILayout.HelpBox(string.Concat(new string[] + { + "Step Height conflicts with Max Slope. This makes some slopes unwalkable.\nConsider decreasing Max Slope to < ", + num8.ToString("0.0"), + " degrees.\nOr, increase Step Height to > ", + num9.ToString("0.00"), + "." + }), MessageType.Warning); + } EditorGUILayout.Space(); EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_OffmeshHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); - bool flag = !Application.HasProLicense(); + bool flag = !InternalEditorUtility.HasProFeaturesEnabled(); if (flag) { EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); @@ -395,15 +736,15 @@ private void BakeSettings() } GUI.enabled = false; } - float num4 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentDropContent, this.m_LedgeDropHeight.floatValue, new GUILayoutOption[0]); - if (num4 >= 0f && !Mathf.Approximately(num4 - this.m_LedgeDropHeight.floatValue, 0f)) + float num10 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentDropContent, this.m_LedgeDropHeight.floatValue, new GUILayoutOption[0]); + if (num10 >= 0f && !Mathf.Approximately(num10 - this.m_LedgeDropHeight.floatValue, 0f)) { - this.m_LedgeDropHeight.floatValue = num4; + this.m_LedgeDropHeight.floatValue = num10; } - float num5 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentJumpContent, this.m_MaxJumpAcrossDistance.floatValue, new GUILayoutOption[0]); - if (num5 >= 0f && !Mathf.Approximately(num5 - this.m_MaxJumpAcrossDistance.floatValue, 0f)) + float num11 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentJumpContent, this.m_MaxJumpAcrossDistance.floatValue, new GUILayoutOption[0]); + if (num11 >= 0f && !Mathf.Approximately(num11 - this.m_MaxJumpAcrossDistance.floatValue, 0f)) { - this.m_MaxJumpAcrossDistance.floatValue = num5; + this.m_MaxJumpAcrossDistance.floatValue = num11; } if (flag) { @@ -413,25 +754,78 @@ private void BakeSettings() this.m_Advanced = GUILayout.Toggle(this.m_Advanced, NavMeshEditorWindow.s_Styles.m_AdvancedHeader, EditorStyles.foldout, new GUILayoutOption[0]); if (this.m_Advanced) { - float num6 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_MinRegionAreaContent, this.m_MinRegionArea.floatValue, new GUILayoutOption[0]); - if (num6 >= 0f && num6 != this.m_MinRegionArea.floatValue) + EditorGUI.indentLevel++; + bool flag2 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_ManualCellSizeContent, this.m_ManualCellSize.boolValue, new GUILayoutOption[0]); + if (flag2 != this.m_ManualCellSize.boolValue) + { + this.m_ManualCellSize.boolValue = flag2; + if (!flag2) + { + this.m_CellSize.floatValue = 2f * this.m_AgentRadius.floatValue / 6f; + } + } + EditorGUI.BeginDisabledGroup(!this.m_ManualCellSize.boolValue); + EditorGUI.indentLevel++; + float num12 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_CellSizeContent, this.m_CellSize.floatValue, new GUILayoutOption[0]); + if (num12 > 0f && !Mathf.Approximately(num12 - this.m_CellSize.floatValue, 0f)) + { + this.m_CellSize.floatValue = Math.Max(0.01f, num12); + } + if (num12 < 0.01f) + { + EditorGUILayout.HelpBox("The voxel size should be larger than 0.01.", MessageType.Warning); + } + float num13 = (this.m_CellSize.floatValue <= 0f) ? 0f : (this.m_AgentRadius.floatValue / this.m_CellSize.floatValue); + EditorGUILayout.LabelField(" ", num13.ToString("0.00") + " voxels per agent radius", EditorStyles.miniLabel, new GUILayoutOption[0]); + if (this.m_ManualCellSize.boolValue) { - this.m_MinRegionArea.floatValue = num6; + float num14 = this.m_CellSize.floatValue * 0.5f; + if ((int)Mathf.Floor(this.m_AgentHeight.floatValue / num14) > 250) + { + EditorGUILayout.HelpBox("The number of voxels per agent height is too high. This will reduce the accuracy of the navmesh. Consider using voxel size of at least " + (this.m_AgentHeight.floatValue / 250f / 0.5f).ToString("0.000") + ".", MessageType.Warning); + } + if (num13 < 1f) + { + EditorGUILayout.HelpBox("The number of voxels per agent radius is too small. The agent may not avoid walls and ledges properly. Consider using voxel size of at least " + (this.m_AgentRadius.floatValue / 2f).ToString("0.000") + " (2 voxels per agent radius).", MessageType.Warning); + } + else + { + if (num13 > 8f) + { + EditorGUILayout.HelpBox("The number of voxels per agent radius is too high. It can cause excessive build times. Consider using voxel size closer to " + (this.m_AgentRadius.floatValue / 8f).ToString("0.000") + " (8 voxels per radius).", MessageType.Warning); + } + } } - EditorGUILayout.Slider(this.m_WidthInaccuracy, 1f, 100f, NavMeshEditorWindow.s_Styles.m_WidthInaccuracyContent, new GUILayoutOption[0]); - EditorGUILayout.Slider(this.m_HeightInaccuracy, 1f, 100f, NavMeshEditorWindow.s_Styles.m_HeightInaccuracyContent, new GUILayoutOption[0]); - bool flag2 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_AgentPlacementContent, this.m_AccuratePlacement.boolValue, new GUILayoutOption[0]); - if (flag2 != this.m_AccuratePlacement.boolValue) + if (this.m_ManualCellSize.boolValue) { - this.m_AccuratePlacement.boolValue = flag2; + EditorGUILayout.HelpBox("Voxel size controls how accurately the navigation mesh is generated from the level geometry. A good voxel size is 2-4 voxels per agent radius. Making voxel size smaller will increase build time.", MessageType.None); } + EditorGUI.indentLevel--; + EditorGUI.EndDisabledGroup(); + EditorGUILayout.Space(); + float num15 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_MinRegionAreaContent, this.m_MinRegionArea.floatValue, new GUILayoutOption[0]); + if (num15 >= 0f && num15 != this.m_MinRegionArea.floatValue) + { + this.m_MinRegionArea.floatValue = num15; + } + EditorGUILayout.Space(); + bool flag3 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_AgentPlacementContent, this.m_AccuratePlacement.boolValue, new GUILayoutOption[0]); + if (flag3 != this.m_AccuratePlacement.boolValue) + { + this.m_AccuratePlacement.boolValue = flag3; + } + EditorGUI.indentLevel--; } } - private void LayerSettings() + private void AreaSettings() { - UnityEngine.Object serializedAssetInterfaceSingleton = Unsupported.GetSerializedAssetInterfaceSingleton("NavMeshLayers"); - SerializedObject obj = new SerializedObject(serializedAssetInterfaceSingleton); - Editor.DoDrawDefaultInspector(obj); + if (this.m_NavMeshAreasObject == null || this.m_AreasList == null) + { + return; + } + this.m_NavMeshAreasObject.Update(); + this.m_AreasList.DoLayoutList(); + this.m_NavMeshAreasObject.ApplyModifiedProperties(); } private static void BakeButtons() { diff --git a/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs b/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs index a0a0cddf..cec0865b 100644 --- a/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs +++ b/UnityEditor/UnityEditor/NavMeshObstacleInspector.cs @@ -1,33 +1,77 @@ using System; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(NavMeshObstacle))] internal class NavMeshObstacleInspector : Editor { - private SerializedProperty m_Radius; - private SerializedProperty m_Height; - private SerializedProperty m_MoveThreshold; + private SerializedProperty m_Shape; + private SerializedProperty m_Center; + private SerializedProperty m_Extents; private SerializedProperty m_Carve; + private SerializedProperty m_MoveThreshold; + private SerializedProperty m_TimeToStationary; + private SerializedProperty m_CarveOnlyStationary; private void OnEnable() { - this.m_Radius = base.serializedObject.FindProperty("m_Radius"); - this.m_Height = base.serializedObject.FindProperty("m_Height"); - this.m_MoveThreshold = base.serializedObject.FindProperty("m_MoveThreshold"); + this.m_Shape = base.serializedObject.FindProperty("m_Shape"); + this.m_Center = base.serializedObject.FindProperty("m_Center"); + this.m_Extents = base.serializedObject.FindProperty("m_Extents"); this.m_Carve = base.serializedObject.FindProperty("m_Carve"); + this.m_MoveThreshold = base.serializedObject.FindProperty("m_MoveThreshold"); + this.m_TimeToStationary = base.serializedObject.FindProperty("m_TimeToStationary"); + this.m_CarveOnlyStationary = base.serializedObject.FindProperty("m_CarveOnlyStationary"); } public override void OnInspectorGUI() { base.serializedObject.Update(); - EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_Height, new GUILayoutOption[0]); - if (!Application.HasProLicense()) + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_Shape, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + base.serializedObject.ApplyModifiedProperties(); + (this.target as NavMeshObstacle).FitExtents(); + base.serializedObject.Update(); + } + EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); + if (this.m_Shape.enumValueIndex == 0) + { + EditorGUI.BeginChangeCheck(); + float num = EditorGUILayout.FloatField("Radius", this.m_Extents.vector3Value.x, new GUILayoutOption[0]); + float num2 = EditorGUILayout.FloatField("Height", this.m_Extents.vector3Value.y * 2f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_Extents.vector3Value = new Vector3(num, num2 / 2f, num); + } + } + else + { + if (this.m_Shape.enumValueIndex == 1) + { + EditorGUI.BeginChangeCheck(); + Vector3 vector = this.m_Extents.vector3Value * 2f; + vector = EditorGUILayout.Vector3Field("Size", vector, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_Extents.vector3Value = vector / 2f; + } + } + } + if (!InternalEditorUtility.HasProFeaturesEnabled()) { EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); GUI.enabled = false; } - EditorGUILayout.PropertyField(this.m_MoveThreshold, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Carve, new GUILayoutOption[0]); + if (this.m_Carve.boolValue) + { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_MoveThreshold, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_TimeToStationary, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CarveOnlyStationary, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } base.serializedObject.ApplyModifiedProperties(); } } diff --git a/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs b/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs index 071626b7..4ba14771 100644 --- a/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs +++ b/UnityEditor/UnityEditor/NavMeshVisualizationSettings.cs @@ -32,6 +32,42 @@ public static extern bool showHeightMesh [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool showNavMeshPortals + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showNavMeshLinks + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showProximityGrid + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showHeightMeshBVTree + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool hasHeightMesh { [WrapperlessIcall] @@ -74,5 +110,29 @@ public static extern bool showAgentWalls [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool showAgentAvoidance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool showObstacleCarveHull + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool hasPendingAgentDebugInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } } } diff --git a/UnityEditor/UnityEditor/NormalCurveRenderer.cs b/UnityEditor/UnityEditor/NormalCurveRenderer.cs index 49fd60d6..14b5f808 100644 --- a/UnityEditor/UnityEditor/NormalCurveRenderer.cs +++ b/UnityEditor/UnityEditor/NormalCurveRenderer.cs @@ -198,7 +198,7 @@ public static void DrawPolyLine(Matrix4x4 transform, float minDistance, params V return; } Color c = Handles.color * new Color(1f, 1f, 1f, 0.75f); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(1); diff --git a/UnityEditor/UnityEditor/ObjectListArea.cs b/UnityEditor/UnityEditor/ObjectListArea.cs index 6009ffc9..95c40acb 100644 --- a/UnityEditor/UnityEditor/ObjectListArea.cs +++ b/UnityEditor/UnityEditor/ObjectListArea.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; @@ -1208,7 +1207,6 @@ private void DrawSubAssetBackground(int beginIndex, int endIndex, float yOffset) } private void DrawItem(Rect position, FilteredHierarchy.FilterResult filterItem, BuiltinResource builtinResource, bool isFolderBrowsing) { - Assert.IsTrue((filterItem != null && builtinResource == null) || (builtinResource != null && filterItem == null)); Event current = Event.current; Rect selectionRect = position; int num = 0; @@ -1669,6 +1667,7 @@ public void InitBuiltinResources() this.InitBuiltinAssetType(typeof(Font)); this.InitBuiltinAssetType(typeof(Shader)); this.InitBuiltinAssetType(typeof(Sprite)); + this.InitBuiltinAssetType(typeof(LightmapParameters)); } public void PrintBuiltinResourcesAvailable() { @@ -1718,10 +1717,6 @@ public int IndexOfNewText(string newText, bool isCreatingNewFolder, bool folders } public int IndexOf(int instanceID) { - if (instanceID == 0) - { - return -1; - } int num = 0; if (this.m_ShowNoneItem) { @@ -1731,6 +1726,13 @@ public int IndexOf(int instanceID) } num++; } + else + { + if (instanceID == 0) + { + return -1; + } + } FilteredHierarchy.FilterResult[] results = this.m_FilteredHierarchy.results; for (int i = 0; i < results.Length; i++) { @@ -2766,7 +2768,7 @@ private void DoOffsetSelectionSpecialKeys(int idx, int maxIndex) } else { - this.m_SelectionOffset = maxIndex - 1 - idx; + this.m_SelectionOffset = maxIndex - idx; } } else @@ -2779,7 +2781,7 @@ private void DoOffsetSelectionSpecialKeys(int idx, int maxIndex) return; } this.m_SelectionOffset = Mathf.RoundToInt(this.m_TotalRect.height / num) * columns; - int num2 = maxIndex - idx - 1; + int num2 = maxIndex - idx; this.m_SelectionOffset = Mathf.Min(Mathf.FloorToInt((float)num2 / (float)columns) * columns, this.m_SelectionOffset); } } diff --git a/UnityEditor/UnityEditor/ObjectPreview.cs b/UnityEditor/UnityEditor/ObjectPreview.cs index 8d284945..0e55ba87 100644 --- a/UnityEditor/UnityEditor/ObjectPreview.cs +++ b/UnityEditor/UnityEditor/ObjectPreview.cs @@ -96,6 +96,9 @@ public void DrawPreview(Rect previewArea) { ObjectPreview.DrawPreview(this, previewArea, this.m_Targets); } + public virtual void ReloadPreviewInstances() + { + } internal static void DrawPreview(IPreviewable defaultPreview, Rect previewArea, UnityEngine.Object[] targets) { if (ObjectPreview.s_Styles == null) diff --git a/UnityEditor/UnityEditor/ObjectPreviewPopup.cs b/UnityEditor/UnityEditor/ObjectPreviewPopup.cs new file mode 100644 index 00000000..74b17d00 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectPreviewPopup.cs @@ -0,0 +1,60 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ObjectPreviewPopup : PopupWindowContent + { + internal class Styles + { + public readonly GUIStyle toolbar = "preToolbar"; + public readonly GUIStyle toolbarText = "preToolbar2"; + public GUIStyle background = "preBackground"; + } + private const float kToolbarHeight = 17f; + private readonly Editor m_Editor; + private readonly GUIContent m_ObjectName; + private ObjectPreviewPopup.Styles s_Styles; + public ObjectPreviewPopup(UnityEngine.Object previewObject) + { + if (previewObject == null) + { + Debug.LogError("ObjectPreviewPopup: Check object is not null, before trying to show it!"); + return; + } + this.m_ObjectName = new GUIContent(previewObject.name, AssetDatabase.GetAssetPath(previewObject)); + this.m_Editor = Editor.CreateEditor(previewObject); + } + public override void OnClose() + { + if (this.m_Editor != null) + { + UnityEngine.Object.DestroyImmediate(this.m_Editor); + } + } + public override void OnGUI(Rect rect) + { + if (this.m_Editor == null) + { + base.editorWindow.Close(); + return; + } + if (this.s_Styles == null) + { + this.s_Styles = new ObjectPreviewPopup.Styles(); + } + GUILayout.BeginArea(new Rect(rect.x, rect.y, rect.width, 17f), this.s_Styles.toolbar); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + this.m_Editor.OnPreviewSettings(); + EditorGUILayout.EndHorizontal(); + GUILayout.EndArea(); + GUI.Label(new Rect(rect.x + 5f, rect.y, rect.width - 140f, 17f), this.m_ObjectName, this.s_Styles.toolbarText); + Rect r = new Rect(rect.x, rect.y + 17f, rect.width, rect.height - 17f); + this.m_Editor.OnPreviewGUI(r, this.s_Styles.background); + } + public override Vector2 GetWindowSize() + { + return new Vector2(300f, 317f); + } + } +} diff --git a/UnityEditor/UnityEditor/ObjectSelector.cs b/UnityEditor/UnityEditor/ObjectSelector.cs index 988817f6..792f3ea8 100644 --- a/UnityEditor/UnityEditor/ObjectSelector.cs +++ b/UnityEditor/UnityEditor/ObjectSelector.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using UnityEditor.AnimatedValues; using UnityEngine; using UnityEngine.Events; @@ -34,8 +35,10 @@ private class Styles private EditorCache m_EditorCache; private GUIView m_DelegateView; private PreviewResizer m_PreviewResizer = new PreviewResizer(); + private List m_AllowedIDs; private ObjectListAreaState m_ListAreaState; private ObjectListArea m_ListArea; + private ObjectTreeForSelector m_ObjectTreeWithSearch = new ObjectTreeForSelector(); private float m_ToolbarHeight = 44f; private float m_PreviewSize; private float m_TopSize; @@ -49,6 +52,13 @@ private Rect listPosition return new Rect(0f, this.m_ToolbarHeight, base.position.width, Mathf.Max(0f, this.m_TopSize - this.m_ToolbarHeight)); } } + public List allowedInstanceIDs + { + get + { + return this.m_AllowedIDs; + } + } public static ObjectSelector get { get @@ -91,12 +101,16 @@ private ObjectSelector() { base.hideFlags = HideFlags.DontSave; } + private bool IsUsingTreeView() + { + return this.m_ObjectTreeWithSearch.IsInitialized(); + } private int GetSelectedInstanceID() { - int[] selection = this.m_ListArea.GetSelection(); - if (selection.Length >= 1) + int[] array = (!this.IsUsingTreeView()) ? this.m_ListArea.GetSelection() : this.m_ObjectTreeWithSearch.GetSelection(); + if (array.Length >= 1) { - return selection[0]; + return array[0]; } return 0; } @@ -142,12 +156,11 @@ public void SetupPreview() this.m_ShowWidePreview.value = flag3; arg_52_0.target = flag3; } - private void ItemSelectedCallback(bool doubleClicked) + private void ListAreaItemSelectedCallback(bool doubleClicked) { if (doubleClicked) { - base.Close(); - GUIUtility.ExitGUI(); + this.ItemWasDoubleClicked(); } else { @@ -170,7 +183,6 @@ private static bool GuessIfUserIsLookingForAnAsset(string requiredClassName, boo "ProceduralMaterial", "Mesh", "PhysicMaterial", - "PhysicsMaterial2D", "GUISkin", "Shader", "TerrainData", @@ -180,7 +192,9 @@ private static bool GuessIfUserIsLookingForAnAsset(string requiredClassName, boo "RenderTexture", "Texture2D", "ProceduralTexture", - "Sprite" + "Sprite", + "AudioMixerGroup", + "AudioMixerSnapshot" }; if (checkGameObject && requiredClassName == "GameObject") { @@ -208,10 +222,19 @@ private void FilterSettingsChanged() } this.m_ListArea.Init(this.listPosition, (!this.m_IsShowingAssets) ? HierarchyType.GameObjects : HierarchyType.Assets, searchFilter, true); } + private static bool ShouldTreeViewBeUsed(string className) + { + return className == "AudioMixerGroup"; + } public void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects) + { + this.Show(obj, requiredType, property, allowSceneObjects, null); + } + internal void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty property, bool allowSceneObjects, List allowedInstanceIDs) { this.m_AllowSceneObjects = allowSceneObjects; this.m_IsShowingAssets = true; + this.m_AllowedIDs = allowedInstanceIDs; string text = string.Empty; if (property != null) { @@ -268,21 +291,41 @@ public void Show(UnityEngine.Object obj, Type requiredType, SerializedProperty p ContainerWindow.SetFreezeDisplay(false); this.m_FocusSearchFilter = true; this.m_Parent.AddToAuxWindowList(); - this.InitIfNeeded(); + int num = (!(obj != null)) ? 0 : obj.GetInstanceID(); if (property != null && property.hasMultipleDifferentValues) { - this.m_ListArea.InitSelection(new int[0]); + num = 0; + } + if (ObjectSelector.ShouldTreeViewBeUsed(text)) + { + this.m_ObjectTreeWithSearch.Init(base.position, this, new UnityAction(this.CreateAndSetTreeView), new UnityAction(this.TreeViewSelection), new UnityAction(this.ItemWasDoubleClicked), num, 0); } else { - int num = (!(obj != null)) ? 0 : obj.GetInstanceID(); + this.InitIfNeeded(); this.m_ListArea.InitSelection(new int[] { num }); - this.m_ListArea.Frame(num, true, false); + if (num != 0) + { + this.m_ListArea.Frame(num, true, false); + } } } + private void ItemWasDoubleClicked() + { + base.Close(); + GUIUtility.ExitGUI(); + } + private void CreateAndSetTreeView(ObjectTreeForSelector.TreeSelectorData data) + { + TreeViewForAudioMixerGroup.CreateAndSetTreeView(data); + } + private void TreeViewSelection(TreeViewItem item) + { + this.SendEvent("ObjectSelectorUpdated", true); + } private void InitIfNeeded() { if (this.m_ListAreaState == null) @@ -301,7 +344,7 @@ private void InitIfNeeded() ObjectListArea expr_82 = this.m_ListArea; expr_82.repaintCallback = (Action)Delegate.Combine(expr_82.repaintCallback, new Action(base.Repaint)); ObjectListArea expr_A9 = this.m_ListArea; - expr_A9.itemSelectedCallback = (Action)Delegate.Combine(expr_A9.itemSelectedCallback, new Action(this.ItemSelectedCallback)); + expr_A9.itemSelectedCallback = (Action)Delegate.Combine(expr_A9.itemSelectedCallback, new Action(this.ListAreaItemSelectedCallback)); this.m_ListArea.gridSize = this.m_StartGridSize.value; SearchFilter searchFilter = new SearchFilter(); searchFilter.nameFilter = this.m_SearchFilter; @@ -623,8 +666,29 @@ private void OnDestroy() { this.m_ListArea.OnDestroy(); } + this.m_ObjectTreeWithSearch.Clear(); } private void OnGUI() + { + this.HandleKeyboard(); + if (this.m_ObjectTreeWithSearch.IsInitialized()) + { + this.OnObjectTreeGUI(); + } + else + { + this.OnObjectGridGUI(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + this.Cancel(); + } + } + private void OnObjectTreeGUI() + { + this.m_ObjectTreeWithSearch.OnGUI(new Rect(0f, 0f, base.position.width, base.position.height)); + } + private void OnObjectGridGUI() { this.InitIfNeeded(); if (this.m_Styles == null) @@ -640,15 +704,10 @@ private void OnGUI() EditorPrefs.SetFloat("ObjectSelectorWidth", position.width); EditorPrefs.SetFloat("ObjectSelectorHeight", position.height); GUI.BeginGroup(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none); - this.HandleKeyboard(); this.m_ListArea.HandleKeyboard(false); this.SearchArea(); this.GridListArea(); this.PreviewArea(); - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) - { - this.Cancel(); - } GUI.EndGroup(); GUI.Label(new Rect(base.position.width * 0.5f - 16f, base.position.height - this.m_PreviewSize + 2f, 32f, this.m_Styles.bottomResize.fixedHeight), GUIContent.none, this.m_Styles.bottomResize); } diff --git a/UnityEditor/UnityEditor/ObjectTreeForSelector.cs b/UnityEditor/UnityEditor/ObjectTreeForSelector.cs new file mode 100644 index 00000000..4be707e7 --- /dev/null +++ b/UnityEditor/UnityEditor/ObjectTreeForSelector.cs @@ -0,0 +1,330 @@ +using System; +using System.Linq; +using System.Text; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [Serializable] + internal class ObjectTreeForSelector + { + internal class TreeSelectorData + { + public ObjectTreeForSelector objectTreeForSelector; + public EditorWindow editorWindow; + public TreeViewState state; + public Rect treeViewRect; + public int userData; + } + [Serializable] + public class SelectionEvent : UnityEvent + { + } + [Serializable] + public class TreeViewNeededEvent : UnityEvent + { + } + [Serializable] + public class DoubleClickedEvent : UnityEvent + { + } + private class Styles + { + public GUIStyle searchBg = new GUIStyle("ProjectBrowserTopBarBg"); + public GUIStyle bottomBarBg = new GUIStyle("ProjectBrowserBottomBarBg"); + public Styles() + { + this.searchBg.border = new RectOffset(0, 0, 2, 2); + this.searchBg.fixedHeight = 0f; + this.bottomBarBg.alignment = TextAnchor.MiddleLeft; + this.bottomBarBg.fontSize = EditorStyles.label.fontSize; + this.bottomBarBg.padding = new RectOffset(5, 5, 0, 0); + } + } + private const string kSearchFieldTag = "TreeSearchField"; + private const float kBottomBarHeight = 17f; + private const float kTopBarHeight = 27f; + private EditorWindow m_Owner; + private TreeView m_TreeView; + private TreeViewState m_TreeViewState; + private bool m_FocusSearchFilter; + private int m_ErrorCounter; + private int m_OriginalSelectedID; + private int m_UserData; + private int m_LastSelectedID = -1; + private string m_SelectedPath = string.Empty; + private ObjectTreeForSelector.SelectionEvent m_SelectionEvent; + private ObjectTreeForSelector.TreeViewNeededEvent m_TreeViewNeededEvent; + private ObjectTreeForSelector.DoubleClickedEvent m_DoubleClickedEvent; + private static ObjectTreeForSelector.Styles s_Styles; + public bool IsInitialized() + { + return this.m_Owner != null; + } + public void Init(Rect position, EditorWindow owner, UnityAction treeViewNeededCallback, UnityAction selectionCallback, UnityAction doubleClickedCallback, int initialSelectedTreeViewItemID, int userData) + { + this.Clear(); + this.m_Owner = owner; + this.m_TreeViewNeededEvent = new ObjectTreeForSelector.TreeViewNeededEvent(); + this.m_TreeViewNeededEvent.AddPersistentListener(treeViewNeededCallback, UnityEventCallState.EditorAndRuntime); + this.m_SelectionEvent = new ObjectTreeForSelector.SelectionEvent(); + this.m_SelectionEvent.AddPersistentListener(selectionCallback, UnityEventCallState.EditorAndRuntime); + this.m_DoubleClickedEvent = new ObjectTreeForSelector.DoubleClickedEvent(); + this.m_DoubleClickedEvent.AddPersistentListener(doubleClickedCallback, UnityEventCallState.EditorAndRuntime); + this.m_OriginalSelectedID = initialSelectedTreeViewItemID; + this.m_UserData = userData; + this.m_FocusSearchFilter = true; + this.EnsureTreeViewIsValid(this.GetTreeViewRect(position)); + if (this.m_TreeView != null) + { + this.m_TreeView.SetSelection(new int[] + { + this.m_OriginalSelectedID + }, true); + if (this.m_OriginalSelectedID == 0) + { + this.m_TreeView.data.SetExpandedWithChildren(this.m_TreeView.data.root, true); + } + } + } + public void Clear() + { + this.m_Owner = null; + this.m_TreeViewNeededEvent = null; + this.m_SelectionEvent = null; + this.m_DoubleClickedEvent = null; + this.m_OriginalSelectedID = 0; + this.m_UserData = 0; + this.m_TreeView = null; + this.m_TreeViewState = null; + this.m_ErrorCounter = 0; + this.m_FocusSearchFilter = false; + } + public int[] GetSelection() + { + if (this.m_TreeView != null) + { + return this.m_TreeView.GetSelection(); + } + return new int[0]; + } + public void SetTreeView(TreeView treeView) + { + this.m_TreeView = treeView; + TreeView expr_0D = this.m_TreeView; + expr_0D.selectionChangedCallback = (Action)Delegate.Remove(expr_0D.selectionChangedCallback, new Action(this.OnItemSelectionChanged)); + TreeView expr_34 = this.m_TreeView; + expr_34.selectionChangedCallback = (Action)Delegate.Combine(expr_34.selectionChangedCallback, new Action(this.OnItemSelectionChanged)); + TreeView expr_5B = this.m_TreeView; + expr_5B.itemDoubleClickedCallback = (Action)Delegate.Remove(expr_5B.itemDoubleClickedCallback, new Action(this.OnItemDoubleClicked)); + TreeView expr_82 = this.m_TreeView; + expr_82.itemDoubleClickedCallback = (Action)Delegate.Combine(expr_82.itemDoubleClickedCallback, new Action(this.OnItemDoubleClicked)); + } + private bool EnsureTreeViewIsValid(Rect treeViewRect) + { + if (this.m_TreeViewState == null) + { + this.m_TreeViewState = new TreeViewState(); + } + if (this.m_TreeView == null) + { + ObjectTreeForSelector.TreeSelectorData arg = new ObjectTreeForSelector.TreeSelectorData + { + state = this.m_TreeViewState, + treeViewRect = treeViewRect, + userData = this.m_UserData, + objectTreeForSelector = this, + editorWindow = this.m_Owner + }; + this.m_TreeViewNeededEvent.Invoke(arg); + if (this.m_TreeView != null && this.m_TreeView.data.root == null) + { + this.m_TreeView.ReloadData(); + } + if (this.m_TreeView == null) + { + if (this.m_ErrorCounter == 0) + { + Debug.LogError("ObjectTreeSelector is missing its tree view. Ensure to call 'SetTreeView()' when the treeViewNeededCallback is invoked!"); + this.m_ErrorCounter++; + } + return false; + } + } + return true; + } + private Rect GetTreeViewRect(Rect position) + { + return new Rect(0f, 27f, position.width, position.height - 17f - 27f); + } + public void OnGUI(Rect position) + { + if (ObjectTreeForSelector.s_Styles == null) + { + ObjectTreeForSelector.s_Styles = new ObjectTreeForSelector.Styles(); + } + Rect rect = new Rect(0f, 0f, position.width, position.height); + Rect toolbarRect = new Rect(rect.x, rect.y, rect.width, 27f); + Rect bottomRect = new Rect(rect.x, rect.yMax - 17f, rect.width, 17f); + Rect treeViewRect = this.GetTreeViewRect(position); + if (!this.EnsureTreeViewIsValid(treeViewRect)) + { + return; + } + int controlID = GUIUtility.GetControlID("Tree".GetHashCode(), FocusType.Keyboard); + this.HandleCommandEvents(); + this.HandleKeyboard(controlID); + this.SearchArea(toolbarRect); + this.TreeViewArea(treeViewRect, controlID); + this.BottomBar(bottomRect); + } + private void BottomBar(Rect bottomRect) + { + int num = this.m_TreeView.GetSelection().FirstOrDefault(); + if (num != this.m_LastSelectedID) + { + this.m_LastSelectedID = num; + this.m_SelectedPath = string.Empty; + TreeViewItem treeViewItem = this.m_TreeView.FindNode(num); + if (treeViewItem != null) + { + StringBuilder stringBuilder = new StringBuilder(); + TreeViewItem treeViewItem2 = treeViewItem; + while (treeViewItem2 != null && treeViewItem2 != this.m_TreeView.data.root) + { + if (treeViewItem2 != treeViewItem) + { + stringBuilder.Insert(0, "/"); + } + stringBuilder.Insert(0, treeViewItem2.displayName); + treeViewItem2 = treeViewItem2.parent; + } + this.m_SelectedPath = stringBuilder.ToString(); + } + } + GUI.Label(bottomRect, GUIContent.none, ObjectTreeForSelector.s_Styles.bottomBarBg); + if (!string.IsNullOrEmpty(this.m_SelectedPath)) + { + GUI.Label(bottomRect, GUIContent.Temp(this.m_SelectedPath), EditorStyles.miniLabel); + } + } + private void OnItemDoubleClicked(int id) + { + if (this.m_DoubleClickedEvent != null) + { + this.m_DoubleClickedEvent.Invoke(); + } + } + private void OnItemSelectionChanged(int[] selection) + { + if (this.m_SelectionEvent != null) + { + TreeViewItem item = null; + if (selection.Length > 0) + { + item = this.m_TreeView.FindNode(selection[0]); + } + this.FireSelectionEvent(item); + } + } + private void HandleKeyboard(int treeViewControlID) + { + if (Event.current.type != EventType.KeyDown) + { + return; + } + KeyCode keyCode = Event.current.keyCode; + if (keyCode != KeyCode.UpArrow && keyCode != KeyCode.DownArrow) + { + return; + } + bool flag = GUI.GetNameOfFocusedControl() == "TreeSearchField"; + if (flag) + { + GUIUtility.keyboardControl = treeViewControlID; + if (this.m_TreeView.IsLastClickedPartOfVisibleRows()) + { + this.FrameSelectedTreeViewItem(); + } + else + { + this.m_TreeView.OffsetSelection(1); + } + Event.current.Use(); + } + } + private void FrameSelectedTreeViewItem() + { + this.m_TreeView.Frame(this.m_TreeView.state.lastClickedID, true, false); + } + private void HandleCommandEvents() + { + Event current = Event.current; + if (current.type != EventType.ExecuteCommand && current.type != EventType.ValidateCommand) + { + return; + } + if (current.commandName == "FrameSelected") + { + if (current.type == EventType.ExecuteCommand && this.m_TreeView.HasSelection()) + { + this.m_TreeView.searchString = string.Empty; + this.FrameSelectedTreeViewItem(); + } + current.Use(); + GUIUtility.ExitGUI(); + } + if (current.commandName == "Find") + { + if (current.type == EventType.ExecuteCommand) + { + this.FocusSearchField(); + } + current.Use(); + } + } + private void FireSelectionEvent(TreeViewItem item) + { + if (this.m_SelectionEvent != null) + { + this.m_SelectionEvent.Invoke(item); + } + } + private void TreeViewArea(Rect treeViewRect, int treeViewControlID) + { + bool flag = this.m_TreeView.data.GetVisibleRows().Count > 0; + if (flag) + { + this.m_TreeView.OnGUI(treeViewRect, treeViewControlID); + } + } + private void SearchArea(Rect toolbarRect) + { + GUI.Label(toolbarRect, GUIContent.none, ObjectTreeForSelector.s_Styles.searchBg); + bool flag = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; + GUI.SetNextControlName("TreeSearchField"); + string text = EditorGUI.SearchField(new Rect(5f, 5f, toolbarRect.width - 10f, 15f), this.m_TreeView.searchString); + if (flag && Event.current.type == EventType.Used && this.m_TreeView.searchString != string.Empty) + { + this.m_FocusSearchFilter = true; + } + if (text != this.m_TreeView.searchString || this.m_FocusSearchFilter) + { + this.m_TreeView.searchString = text; + HandleUtility.Repaint(); + } + if (this.m_FocusSearchFilter) + { + EditorGUI.FocusTextInControl("TreeSearchField"); + if (Event.current.type == EventType.Repaint) + { + this.m_FocusSearchFilter = false; + } + } + } + internal void FocusSearchField() + { + this.m_FocusSearchFilter = true; + } + } +} diff --git a/UnityEditor/UnityEditor/OcclusionCullingWindow.cs b/UnityEditor/UnityEditor/OcclusionCullingWindow.cs index 94246e7c..e45c1660 100644 --- a/UnityEditor/UnityEditor/OcclusionCullingWindow.cs +++ b/UnityEditor/UnityEditor/OcclusionCullingWindow.cs @@ -64,10 +64,6 @@ private void OnSelectionChange() base.Repaint(); } } - private void Awake() - { - this.SetDefaultComputationParameters(); - } private void OnEnable() { OcclusionCullingWindow.ms_OcclusionCullingWindow = this; @@ -107,7 +103,7 @@ private static void GenerateWindow() [MenuItem("Window/Occlusion Culling", true, 2099)] public static bool SetupWindowValidate() { - return InternalEditorUtility.HasPro(); + return InternalEditorUtility.HasProFeaturesEnabled(); } private void SummaryGUI() { @@ -216,11 +212,6 @@ private void CameraSelectionGUI() GUILayout.Label(OcclusionCullingWindow.s_Styles.emptyCameraSelection, EditorStyles.helpBox, new GUILayoutOption[0]); } } - private void SetDefaultComputationParameters() - { - GUIUtility.keyboardControl = 0; - StaticOcclusionCulling.SetDefaultOcclusionBakeSettings(); - } private void BakeSettings() { float width = 150f; @@ -229,7 +220,8 @@ private void BakeSettings() GUILayout.Width(width) })) { - this.SetDefaultComputationParameters(); + GUIUtility.keyboardControl = 0; + StaticOcclusionCulling.SetDefaultOcclusionBakeSettings(); } GUILayout.Label(OcclusionCullingWindow.s_Styles.defaultParameterText.tooltip, EditorStyles.helpBox, new GUILayoutOption[0]); EditorGUI.BeginChangeCheck(); diff --git a/UnityEditor/UnityEditor/OffMeshLinkInspector.cs b/UnityEditor/UnityEditor/OffMeshLinkInspector.cs index 73724f3d..e960a8ec 100644 --- a/UnityEditor/UnityEditor/OffMeshLinkInspector.cs +++ b/UnityEditor/UnityEditor/OffMeshLinkInspector.cs @@ -1,11 +1,12 @@ using System; +using UnityEditorInternal; using UnityEngine; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(OffMeshLink))] internal class OffMeshLinkInspector : Editor { - private SerializedProperty m_NavMeshLayer; + private SerializedProperty m_AreaIndex; private SerializedProperty m_Start; private SerializedProperty m_End; private SerializedProperty m_CostOverride; @@ -14,7 +15,7 @@ internal class OffMeshLinkInspector : Editor private SerializedProperty m_AutoUpdatePositions; private void OnEnable() { - this.m_NavMeshLayer = base.serializedObject.FindProperty("m_NavMeshLayer"); + this.m_AreaIndex = base.serializedObject.FindProperty("m_AreaIndex"); this.m_Start = base.serializedObject.FindProperty("m_Start"); this.m_End = base.serializedObject.FindProperty("m_End"); this.m_CostOverride = base.serializedObject.FindProperty("m_CostOverride"); @@ -24,7 +25,7 @@ private void OnEnable() } public override void OnInspectorGUI() { - if (!Application.HasProLicense()) + if (!InternalEditorUtility.HasProFeaturesEnabled()) { EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning); GUI.enabled = false; @@ -36,30 +37,30 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(this.m_BiDirectional, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Activated, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_AutoUpdatePositions, new GUILayoutOption[0]); - this.SelectNavMeshLayer(); + this.SelectNavMeshArea(); base.serializedObject.ApplyModifiedProperties(); } - private void SelectNavMeshLayer() + private void SelectNavMeshArea() { EditorGUI.BeginChangeCheck(); - EditorGUI.showMixedValue = this.m_NavMeshLayer.hasMultipleDifferentValues; - string[] navMeshLayerNames = GameObjectUtility.GetNavMeshLayerNames(); - int intValue = this.m_NavMeshLayer.intValue; + EditorGUI.showMixedValue = this.m_AreaIndex.hasMultipleDifferentValues; + string[] navMeshAreaNames = GameObjectUtility.GetNavMeshAreaNames(); + int intValue = this.m_AreaIndex.intValue; int selectedIndex = -1; - for (int i = 0; i < navMeshLayerNames.Length; i++) + for (int i = 0; i < navMeshAreaNames.Length; i++) { - if (GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[i]) == intValue) + if (GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[i]) == intValue) { selectedIndex = i; break; } } - int num = EditorGUILayout.Popup("Navigation Layer", selectedIndex, navMeshLayerNames, new GUILayoutOption[0]); + int num = EditorGUILayout.Popup("Navigation Area", selectedIndex, navMeshAreaNames, new GUILayoutOption[0]); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { - int navMeshLayerFromName = GameObjectUtility.GetNavMeshLayerFromName(navMeshLayerNames[num]); - this.m_NavMeshLayer.intValue = navMeshLayerFromName; + int navMeshAreaFromName = GameObjectUtility.GetNavMeshAreaFromName(navMeshAreaNames[num]); + this.m_AreaIndex.intValue = navMeshAreaFromName; } } } diff --git a/UnityEditor/UnityEditor/OtherRenderingEditor.cs b/UnityEditor/UnityEditor/OtherRenderingEditor.cs new file mode 100644 index 00000000..f947d415 --- /dev/null +++ b/UnityEditor/UnityEditor/OtherRenderingEditor.cs @@ -0,0 +1,53 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(RenderSettings))] + internal class OtherRenderingEditor : Editor + { + internal class Styles + { + public static readonly GUIContent otherHeader = EditorGUIUtility.TextContent("RenderSettings.OtherHeader"); + } + private const string kShowEditorKey = "ShowOtherRenderingEditorFoldout"; + protected SerializedProperty m_HaloStrength; + protected SerializedProperty m_FlareStrength; + protected SerializedProperty m_FlareFadeSpeed; + protected SerializedProperty m_HaloTexture; + protected SerializedProperty m_SpotCookie; + private bool m_ShowEditor; + public virtual void OnEnable() + { + this.m_HaloStrength = base.serializedObject.FindProperty("m_HaloStrength"); + this.m_FlareStrength = base.serializedObject.FindProperty("m_FlareStrength"); + this.m_FlareFadeSpeed = base.serializedObject.FindProperty("m_FlareFadeSpeed"); + this.m_HaloTexture = base.serializedObject.FindProperty("m_HaloTexture"); + this.m_SpotCookie = base.serializedObject.FindProperty("m_SpotCookie"); + this.m_ShowEditor = InspectorState.GetBool("ShowOtherRenderingEditorFoldout", false); + } + public virtual void OnDisable() + { + InspectorState.SetBool("ShowOtherRenderingEditorFoldout", this.m_ShowEditor); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + EditorGUILayout.Space(); + this.m_ShowEditor = EditorGUILayout.FoldoutTitlebar(this.m_ShowEditor, OtherRenderingEditor.Styles.otherHeader); + if (!this.m_ShowEditor) + { + return; + } + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_HaloTexture, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_HaloStrength, 0f, 1f, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_FlareFadeSpeed, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_FlareStrength, 0f, 1f, new GUILayoutOption[0]); + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(this.m_SpotCookie, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/PS4BuildSubtarget.cs b/UnityEditor/UnityEditor/PS4BuildSubtarget.cs new file mode 100644 index 00000000..2d96c44c --- /dev/null +++ b/UnityEditor/UnityEditor/PS4BuildSubtarget.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEditor +{ + public enum PS4BuildSubtarget + { + PCHosted, + Package + } +} diff --git a/UnityEditor/UnityEditor/PSMBuildSubtarget.cs b/UnityEditor/UnityEditor/PSMBuildSubtarget.cs new file mode 100644 index 00000000..32ce0319 --- /dev/null +++ b/UnityEditor/UnityEditor/PSMBuildSubtarget.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum PSMBuildSubtarget + { + DevAssistant, + Master, + Intermediate + } +} diff --git a/UnityEditor/UnityEditor/PackageExport.cs b/UnityEditor/UnityEditor/PackageExport.cs index a2f9b70c..618ee193 100644 --- a/UnityEditor/UnityEditor/PackageExport.cs +++ b/UnityEditor/UnityEditor/PackageExport.cs @@ -199,7 +199,7 @@ private void CheckChildren(AssetsItem parentAI) private void FrameLastGUIRect() { Rect lastRect = GUILayoutUtility.GetLastRect(); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); GL.Color(PackageExport.ms_Constants.lineColor); GL.Vertex3(lastRect.xMax + 1f, lastRect.y, 0f); diff --git a/UnityEditor/UnityEditor/PackageImport.cs b/UnityEditor/UnityEditor/PackageImport.cs index 8c445552..7b17eb1b 100644 --- a/UnityEditor/UnityEditor/PackageImport.cs +++ b/UnityEditor/UnityEditor/PackageImport.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using UnityEngine; namespace UnityEditor { @@ -15,14 +16,15 @@ internal class Constants public GUIStyle topBarBg = new GUIStyle("ProjectBrowserHeaderBgTop"); public GUIStyle textureIconDropShadow = "ProjectBrowserTextureIconDropShadow"; public Color lineColor; + public GUIContent badgeNew = EditorGUIUtility.IconContent("AS Badge New"); public Constants() { this.lineColor = ((!EditorGUIUtility.isProSkin) ? new Color(0.4f, 0.4f, 0.4f) : new Color(0.1f, 0.1f, 0.1f)); this.topBarBg.fixedHeight = 0f; - RectOffset arg_D7_0 = this.topBarBg.border; + RectOffset arg_E7_0 = this.topBarBg.border; int num = 2; this.topBarBg.border.bottom = num; - arg_D7_0.top = num; + arg_E7_0.top = num; this.title.fontStyle = FontStyle.Bold; this.title.alignment = TextAnchor.MiddleLeft; } @@ -42,6 +44,7 @@ public Constants() private static Texture2D s_PackageIcon; private static Texture2D s_Preview; private static string s_LastPreviewPath; + private static readonly char[] s_InvalidPathChars = Path.GetInvalidPathChars(); private static PackageImport.Constants ms_Constants; public PackageImport() { @@ -49,6 +52,10 @@ public PackageImport() } public static void ShowImportPackage(string packagePath, AssetsItem[] items, string packageIconPath) { + if (!PackageImport.ValidateInput(items)) + { + return; + } PackageImport window = EditorWindow.GetWindow(true, "Importing package"); window.Init(packagePath, items, packageIconPath); } @@ -263,5 +270,56 @@ public static Texture2D GetPreview(string previewPath) } return PackageImport.s_Preview; } + private static bool ValidateInput(AssetsItem[] items) + { + string text; + if (!PackageImport.IsAllFilePathsValid(items, out text)) + { + text += "\nDo you want to import the valid file paths of the package or cancel importing?"; + return EditorUtility.DisplayDialog("Invalid file path found", text, "Import", "Cancel importing"); + } + return true; + } + private static bool IsAllFilePathsValid(AssetsItem[] assetItems, out string errorMessage) + { + for (int i = 0; i < assetItems.Length; i++) + { + AssetsItem assetsItem = assetItems[i]; + if (assetsItem.assetIsDir != 1) + { + char c; + int num; + if (PackageImport.HasInvalidCharInFilePath(assetsItem.pathName, out c, out num)) + { + errorMessage = string.Format("Invalid character found in file path: '{0}'. Invalid ascii value: {1} (at character index {2}).", assetsItem.pathName, (int)c, num); + return false; + } + } + } + errorMessage = string.Empty; + return true; + } + private static bool HasInvalidCharInFilePath(string filePath, out char invalidChar, out int invalidCharIndex) + { + for (int i = 0; i < filePath.Length; i++) + { + char c = filePath[i]; + if (PackageImport.s_InvalidPathChars.Contains(c)) + { + invalidChar = c; + invalidCharIndex = i; + return true; + } + } + invalidChar = ' '; + invalidCharIndex = -1; + return false; + } + public static bool HasInvalidCharInFilePath(string filePath) + { + char c; + int num; + return PackageImport.HasInvalidCharInFilePath(filePath, out c, out num); + } } } diff --git a/UnityEditor/UnityEditor/PackageImportTreeView.cs b/UnityEditor/UnityEditor/PackageImportTreeView.cs index b48ccf12..ac918cbd 100644 --- a/UnityEditor/UnityEditor/PackageImportTreeView.cs +++ b/UnityEditor/UnityEditor/PackageImportTreeView.cs @@ -34,8 +34,24 @@ public PackageImportTreeViewItem(int id, int depth, TreeViewItem parent, string } private class PackageImportTreeViewGUI : TreeViewGUI { - private static Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + internal class Constants + { + public Texture2D folderIcon = EditorGUIUtility.FindTexture(EditorResourcesUtility.folderIconName); + public GUIContent badgeNew = EditorGUIUtility.IconContent("AS Badge New"); + } + private PackageImportTreeView.PackageImportTreeViewGUI.Constants m_Constants; public Action itemWasToggled; + internal PackageImportTreeView.PackageImportTreeViewGUI.Constants constants + { + get + { + if (this.m_Constants == null) + { + this.m_Constants = new PackageImportTreeView.PackageImportTreeViewGUI.Constants(); + } + return this.m_Constants; + } + } public int showPreviewForID { get; @@ -97,7 +113,7 @@ public override Rect OnRowGUI(TreeViewItem node, int row, float rowWidth, bool s } if (packageImportTreeViewItem.item.exists == 0) { - Texture image = ASMainWindow.badgeNew.image; + Texture image = this.constants.badgeNew.image; GUI.DrawTexture(new Rect(rect.xMax - (float)image.width - 6f, rect.y + (rect.height - (float)image.height) / 2f, (float)image.width, (float)image.height), image); } } @@ -123,7 +139,7 @@ protected override Texture GetIconForNode(TreeViewItem item) PackageImportTreeView.PackageImportTreeViewItem packageImportTreeViewItem = item as PackageImportTreeView.PackageImportTreeViewItem; if (packageImportTreeViewItem.isFolder) { - return PackageImportTreeView.PackageImportTreeViewGUI.folderIcon; + return this.constants.folderIcon; } return InternalEditorUtility.GetIconForFile(packageImportTreeViewItem.item.pathName); } @@ -176,16 +192,19 @@ public override void FetchData() AssetsItem assetsItem2 = assetItems2[j]; if (assetsItem2.assetIsDir != 1) { - string fileName = Path.GetFileName(assetsItem2.pathName); - string directoryName = Path.GetDirectoryName(assetsItem2.pathName); - TreeViewItem treeViewItem = this.EnsureFolderPath(directoryName, dictionary, treeViewFolders, flag); - if (treeViewItem != null) + if (!PackageImport.HasInvalidCharInFilePath(assetsItem2.pathName)) { - int hashCode = assetsItem2.pathName.GetHashCode(); - treeViewItem.AddChild(new PackageImportTreeView.PackageImportTreeViewItem(hashCode, treeViewItem.depth + 1, treeViewItem, fileName) + string fileName = Path.GetFileName(assetsItem2.pathName); + string directoryName = Path.GetDirectoryName(assetsItem2.pathName); + TreeViewItem treeViewItem = this.EnsureFolderPath(directoryName, dictionary, treeViewFolders, flag); + if (treeViewItem != null) { - item = assetsItem2 - }); + int hashCode = assetsItem2.pathName.GetHashCode(); + treeViewItem.AddChild(new PackageImportTreeView.PackageImportTreeViewItem(hashCode, treeViewItem.depth + 1, treeViewItem, fileName) + { + item = assetsItem2 + }); + } } } } diff --git a/UnityEditor/UnityEditor/ParamEqGUI.cs b/UnityEditor/UnityEditor/ParamEqGUI.cs new file mode 100644 index 00000000..66bfa951 --- /dev/null +++ b/UnityEditor/UnityEditor/ParamEqGUI.cs @@ -0,0 +1,189 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class ParamEqGUI : IAudioEffectPluginGUI + { + private const bool useLogScale = true; + public static string kCenterFreqName = "Center freq"; + public static string kOctaveRangeName = "Octave range"; + public static string kFrequencyGainName = "Frequency gain"; + public static GUIStyle textStyle10 = ParamEqGUI.BuildGUIStyleForLabel(Color.grey, 10, false, FontStyle.Normal, TextAnchor.MiddleCenter); + public override string Name + { + get + { + return "ParamEQ"; + } + } + public override string Description + { + get + { + return "Parametric equalizer"; + } + } + public override string Vendor + { + get + { + return "Firelight Technologies"; + } + } + public static GUIStyle BuildGUIStyleForLabel(Color color, int fontSize, bool wrapText, FontStyle fontstyle, TextAnchor anchor) + { + GUIStyle gUIStyle = new GUIStyle(); + gUIStyle.focused.background = gUIStyle.onNormal.background; + gUIStyle.focused.textColor = color; + gUIStyle.alignment = anchor; + gUIStyle.fontSize = fontSize; + gUIStyle.fontStyle = fontstyle; + gUIStyle.wordWrap = wrapText; + gUIStyle.clipping = TextClipping.Overflow; + gUIStyle.normal.textColor = color; + return gUIStyle; + } + private static void DrawFrequencyTickMarks(Rect r, float samplerate, bool logScale, Color col) + { + ParamEqGUI.textStyle10.normal.textColor = col; + float num = r.x; + float num2 = 60f; + for (float num3 = 0f; num3 < 1f; num3 += 0.01f) + { + float num4 = (float)ParamEqGUI.MapNormalizedFrequency((double)num3, (double)samplerate, logScale, true); + float num5 = r.x + num3 * r.width; + if (num5 - num > num2) + { + EditorGUI.DrawRect(new Rect(num5, r.yMax - 5f, 1f, 5f), col); + GUI.Label(new Rect(num5, r.yMax - 22f, 1f, 15f), (num4 >= 1000f) ? string.Format("{0:F0} kHz", num4 * 0.001f) : string.Format("{0:F0} Hz", num4), ParamEqGUI.textStyle10); + num = num5; + } + } + } + protected static Color ScaleAlpha(Color col, float blend) + { + return new Color(col.r, col.g, col.b, col.a * blend); + } + private static double MapNormalizedFrequency(double f, double sr, bool useLogScale, bool forward) + { + double num = 0.5 * sr; + if (!useLogScale) + { + return (!forward) ? (f / num) : (f * num); + } + if (forward) + { + return 10.0 * Math.Pow(num / 10.0, f); + } + return Math.Log(f / 10.0) / Math.Log(num / 10.0); + } + private static bool ParamEqualizerCurveEditor(IAudioEffectPlugin plugin, Rect r, ref float centerFreq, ref float bandwidth, ref float gain, float blend) + { + Event current = Event.current; + int controlID = GUIUtility.GetControlID(FocusType.Passive); + r = AudioCurveRendering.BeginCurveFrame(r); + float min; + float max; + float num; + plugin.GetFloatParameterInfo(ParamEqGUI.kCenterFreqName, out min, out max, out num); + float min2; + float max2; + float num2; + plugin.GetFloatParameterInfo(ParamEqGUI.kOctaveRangeName, out min2, out max2, out num2); + float min3; + float max3; + float num3; + plugin.GetFloatParameterInfo(ParamEqGUI.kFrequencyGainName, out min3, out max3, out num3); + bool result = false; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (r.Contains(Event.current.mousePosition) && current.button == 0) + { + GUIUtility.hotControl = controlID; + EditorGUIUtility.SetWantsMouseJumping(1); + current.Use(); + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID && current.button == 0) + { + GUIUtility.hotControl = 0; + EditorGUIUtility.SetWantsMouseJumping(0); + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + float num4 = (!Event.current.alt) ? 1f : 0.25f; + centerFreq = Mathf.Clamp((float)ParamEqGUI.MapNormalizedFrequency(ParamEqGUI.MapNormalizedFrequency((double)centerFreq, (double)plugin.GetSampleRate(), true, false) + (double)(current.delta.x / r.width), (double)plugin.GetSampleRate(), true, true), min, max); + if (Event.current.shift) + { + bandwidth = Mathf.Clamp(bandwidth - current.delta.y * 0.02f * num4, min2, max2); + } + else + { + gain = Mathf.Clamp(gain - current.delta.y * 0.01f * num4, min3, max3); + } + result = true; + current.Use(); + } + break; + } + if (Event.current.type == EventType.Repaint) + { + float num5 = (float)ParamEqGUI.MapNormalizedFrequency((double)centerFreq, (double)plugin.GetSampleRate(), true, false); + EditorGUI.DrawRect(new Rect(num5 * r.width + r.x, r.y, 1f, r.height), (GUIUtility.hotControl != controlID) ? new Color(0.4f, 0.4f, 0.4f) : new Color(0.6f, 0.6f, 0.6f)); + HandleUtility.ApplyWireMaterial(); + double num6 = 3.1415926; + double wm = -2.0 * num6 / (double)plugin.GetSampleRate(); + double num7 = 2.0 * num6 * (double)centerFreq / (double)plugin.GetSampleRate(); + double num8 = 1.0 / (double)bandwidth; + double num9 = (double)gain; + double num10 = Math.Sin(num7) / (2.0 * num8); + double b0 = 1.0 + num10 * num9; + double b1 = -2.0 * Math.Cos(num7); + double b2 = 1.0 - num10 * num9; + double a0 = 1.0 + num10 / num9; + double a1 = -2.0 * Math.Cos(num7); + double a2 = 1.0 - num10 / num9; + AudioCurveRendering.DrawCurve(r, delegate(float x) + { + double num11 = ParamEqGUI.MapNormalizedFrequency((double)x, (double)plugin.GetSampleRate(), true, true); + ComplexD a = ComplexD.Exp(wm * num11); + ComplexD a2 = a * (a * b2 + b1) + b0; + ComplexD b = a * (a * a2 + a1) + a0; + ComplexD complexD = a2 / b; + double num12 = Math.Log10(complexD.Mag2()); + return (float)(0.5 * num12); + }, ParamEqGUI.ScaleAlpha(AudioCurveRendering.kAudioOrange, blend)); + } + ParamEqGUI.DrawFrequencyTickMarks(r, (float)plugin.GetSampleRate(), true, new Color(1f, 1f, 1f, 0.3f * blend)); + AudioCurveRendering.EndCurveFrame(); + return result; + } + public override bool OnGUI(IAudioEffectPlugin plugin) + { + float blend = (!plugin.IsPluginEditableAndEnabled()) ? 0.5f : 1f; + float value; + plugin.GetFloatParameter(ParamEqGUI.kCenterFreqName, out value); + float value2; + plugin.GetFloatParameter(ParamEqGUI.kOctaveRangeName, out value2); + float value3; + plugin.GetFloatParameter(ParamEqGUI.kFrequencyGainName, out value3); + GUILayout.Space(5f); + Rect rect = GUILayoutUtility.GetRect(200f, 100f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (ParamEqGUI.ParamEqualizerCurveEditor(plugin, rect, ref value, ref value2, ref value3, blend)) + { + plugin.SetFloatParameter(ParamEqGUI.kCenterFreqName, value); + plugin.SetFloatParameter(ParamEqGUI.kOctaveRangeName, value2); + plugin.SetFloatParameter(ParamEqGUI.kFrequencyGainName, value3); + } + return true; + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleEffectUI.cs b/UnityEditor/UnityEditor/ParticleEffectUI.cs index 2eb5884b..5b7255dc 100644 --- a/UnityEditor/UnityEditor/ParticleEffectUI.cs +++ b/UnityEditor/UnityEditor/ParticleEffectUI.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; @@ -67,7 +66,6 @@ internal static ParticleEffectUI.Texts texts public ParticleEffectUI(ParticleEffectUIOwner owner) { this.m_Owner = owner; - Assert.That(this.m_Owner is ParticleSystemInspector || this.m_Owner is ParticleSystemWindow); } private bool ShouldManagePlaybackState(ParticleSystem root) { @@ -274,7 +272,6 @@ public void PlayOnAwakeChanged(bool newPlayOnAwake) { ParticleSystemUI particleSystemUI = emitters[i]; InitialModuleUI initialModuleUI = particleSystemUI.m_Modules[0] as InitialModuleUI; - Assert.That(initialModuleUI != null); initialModuleUI.m_PlayOnAwake.boolValue = newPlayOnAwake; particleSystemUI.ApplyProperties(); } @@ -694,7 +691,6 @@ private void WindowCurveEditorGUI(bool verticalLayout) else { EditorWindow editorWindow = (EditorWindow)this.m_Owner; - Assert.That(editorWindow != null); rect = GUILayoutUtility.GetRect(editorWindow.position.width - this.m_EmitterAreaWidth, editorWindow.position.height - 17f); } this.ResizeHandling(verticalLayout); diff --git a/UnityEditor/UnityEditor/ParticleRendererEditor.cs b/UnityEditor/UnityEditor/ParticleRendererEditor.cs new file mode 100644 index 00000000..9ce8abc4 --- /dev/null +++ b/UnityEditor/UnityEditor/ParticleRendererEditor.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(ParticleRenderer))] + internal class ParticleRendererEditor : RendererEditorBase + { + public override void OnEnable() + { + base.OnEnable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Editor.DrawPropertiesExcluding(base.serializedObject, new string[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/ParticleSystemUI.cs b/UnityEditor/UnityEditor/ParticleSystemUI.cs index f1dd93ac..eb3c8af1 100644 --- a/UnityEditor/UnityEditor/ParticleSystemUI.cs +++ b/UnityEditor/UnityEditor/ParticleSystemUI.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using UnityEngine; @@ -62,12 +61,11 @@ private void InitRendererUI() ParticleSystemRenderer particleSystemRenderer = this.GetParticleSystemRenderer(); if (particleSystemRenderer == null) { - this.m_ParticleSystem.gameObject.AddComponent("ParticleSystemRenderer"); + this.m_ParticleSystem.gameObject.AddComponent(); } particleSystemRenderer = this.GetParticleSystemRenderer(); if (particleSystemRenderer != null) { - Assert.That(this.m_Modules[this.m_Modules.Length - 1] == null); this.m_RendererSerializedObject = new SerializedObject(particleSystemRenderer); this.m_Modules[this.m_Modules.Length - 1] = new RendererModuleUI(this, this.m_RendererSerializedObject, ParticleSystemUI.s_ModuleNames[ParticleSystemUI.s_ModuleNames.Length - 1]); EditorUtility.SetSelectedWireframeHidden(particleSystemRenderer, !ParticleEffectUI.m_ShowWireframe); @@ -528,9 +526,6 @@ private void EmitterMenuCallback(object obj) case 2: EditorGUIUtility.PingObject(this.m_ParticleSystem); break; - default: - Assert.That("Enum not handled!".Length == 0); - break; } } private void ShowEmitterMenu() diff --git a/UnityEditor/UnityEditor/ParticleSystemWindow.cs b/UnityEditor/UnityEditor/ParticleSystemWindow.cs index 1cee9c29..d2c1d3f2 100644 --- a/UnityEditor/UnityEditor/ParticleSystemWindow.cs +++ b/UnityEditor/UnityEditor/ParticleSystemWindow.cs @@ -13,11 +13,7 @@ private class Texts private ParticleSystem m_Target; private ParticleEffectUI m_ParticleEffectUI; private bool m_IsVisible; - private static GUIContent[] s_Icons = new GUIContent[] - { - EditorGUIUtility.IconContent("HorizontalSplit"), - EditorGUIUtility.IconContent("VerticalSplit") - }; + private static GUIContent[] s_Icons; private static ParticleSystemWindow.Texts s_Texts; private ParticleSystemWindow() { @@ -239,6 +235,14 @@ private void OnGUI() { ParticleSystemWindow.s_Texts = new ParticleSystemWindow.Texts(); } + if (ParticleSystemWindow.s_Icons == null) + { + ParticleSystemWindow.s_Icons = new GUIContent[] + { + EditorGUIUtility.IconContent("HorizontalSplit"), + EditorGUIUtility.IconContent("VerticalSplit") + }; + } if (this.m_Target == null && (Selection.activeGameObject != null || ParticleSystemEditorUtils.lockedParticleSystem != null)) { this.InitEffectUI(); diff --git a/UnityEditor/UnityEditor/PlaceTreeWizard.cs b/UnityEditor/UnityEditor/PlaceTreeWizard.cs index 93f13962..4587b8d4 100644 --- a/UnityEditor/UnityEditor/PlaceTreeWizard.cs +++ b/UnityEditor/UnityEditor/PlaceTreeWizard.cs @@ -4,14 +4,23 @@ namespace UnityEditor { internal class PlaceTreeWizard : TerrainWizard { + private const int kMaxNumberOfTrees = 1000000; public int numberOfTrees = 10000; + public bool keepExistingTrees = true; public void OnEnable() { base.minSize = new Vector2(250f, 150f); } private void OnWizardCreate() { - TreePlacementUtility.PlaceRandomTrees(this.m_Terrain.terrainData, this.numberOfTrees); + if (this.numberOfTrees > 1000000) + { + base.isValid = false; + base.errorString = string.Format("Mass placing more than {0} trees is not supported", 1000000); + Debug.LogError(base.errorString); + return; + } + TreePainter.MassPlaceTrees(this.m_Terrain.terrainData, this.numberOfTrees, true, this.keepExistingTrees); this.m_Terrain.Flush(); } } diff --git a/UnityEditor/UnityEditor/PlayerSettings.cs b/UnityEditor/UnityEditor/PlayerSettings.cs index 372586df..046f2917 100644 --- a/UnityEditor/UnityEditor/PlayerSettings.cs +++ b/UnityEditor/UnityEditor/PlayerSettings.cs @@ -1,14 +1,1114 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.Internal; namespace UnityEditor { public sealed class PlayerSettings : UnityEngine.Object { + public sealed class XboxOne + { + public static extern string ProductId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string UpdateKey + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string SandboxId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string ContentId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string TitleId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string SCID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool EnableVariableGPU + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool DisableKinectGpuReservation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string GameOsOverridePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string PackagingOverridePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern XboxOneEncryptionLevel PackagingEncryption + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string AppManifestOverridePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool IsContentPackage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string Version + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string Description + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string[] SocketNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string[] AllowedProductIds + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern uint PersistentLocalStorageSize + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static void SetCapability(string capability, bool value) + { + PlayerSettings.SetPropertyBool(capability, value, BuildTargetGroup.XboxOne); + } + public static bool GetCapability(string capability) + { + bool result; + try + { + bool flag = false; + PlayerSettings.GetPropertyOptionalBool(capability, ref flag, BuildTargetGroup.XboxOne); + result = flag; + } + catch + { + result = false; + } + return result; + } + internal static void SetSupportedLanguage(string language, bool enabled) + { + PlayerSettings.SetPropertyBool(language, enabled, BuildTargetGroup.XboxOne); + } + internal static bool GetSupportedLanguage(string language) + { + bool result; + try + { + bool flag = false; + PlayerSettings.GetPropertyOptionalBool(language, ref flag, BuildTargetGroup.XboxOne); + result = flag; + } + catch + { + result = false; + } + return result; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemoveSocketDefinition(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetSocketDefinition(string name, string port, int protocol, int[] usages, string templateName, int sessionRequirment, int[] deviceUsages); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetSocketDefinition(string name, out string port, out int protocol, out int[] usages, out string templateName, out int sessionRequirment, out int[] deviceUsages); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RemoveAllowedProductId(string id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool AddAllowedProductId(string id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UpdateAllowedProductId(int idx, string id); + public static void SetGameRating(string name, int value) + { + PlayerSettings.SetPropertyInt(name, value, BuildTargetGroup.XboxOne); + } + public static int GetGameRating(string name) + { + int result; + try + { + int num = 0; + PlayerSettings.GetPropertyOptionalInt(name, ref num, BuildTargetGroup.XboxOne); + result = num; + } + catch + { + result = 0; + } + return result; + } + } + public sealed class PS3 + { + public static extern Texture2D ps3SplashScreen + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int videoMemoryForVertexBuffers + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int videoMemoryForAudio + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool EnableVerboseMemoryStats + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool UseSPUForUmbra + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool EnableMoveSupport + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool DisableDolbyEncoding + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string titleConfigPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string dlcConfigPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string thumbnailPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string backgroundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string soundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npTrophyCommId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int npAgeRating + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npCommunicationPassphrase + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npTrophyCommSig + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npTrophyPackagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int bootCheckMaxSaveGameSizeKB + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool trialMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int saveGameSlots + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public sealed class PS4 + { + public enum PS4AppCategory + { + Application + } + public enum PS4RemotePlayKeyAssignment + { + None = -1, + PatternA, + PatternB, + PatternC, + PatternD + } + public enum PS4EnterButtonAssignment + { + CircleButton, + CrossButton + } + public static extern string npTrophyPackPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int npAgeRating + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npTitleSecret + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int parentalLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int applicationParameter1 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int applicationParameter2 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int applicationParameter3 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int applicationParameter4 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string passcode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string monoEnv + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool playerPrefsSupport + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string contentID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PS4.PS4AppCategory category + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int appType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string masterVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string appVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PS4.PS4RemotePlayKeyAssignment remotePlayKeyAssignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PS4.PS4EnterButtonAssignment enterButtonAssignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string paramSfxPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int videoOutPixelFormat + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int videoOutResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string PronunciationXMLPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string PronunciationSIGPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string BackgroundImagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string StartupImagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string SaveDataImagePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string BGMPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string ShareFilePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string NPtitleDatPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool pnSessions + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool pnPresence + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool pnFriends + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool pnGameCustomData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } + public sealed class PSVita + { + public enum PSVitaPowerMode + { + ModeA, + ModeB, + ModeC + } + public enum PSVitaTvBootMode + { + Default, + PSVitaBootablePSVitaTvBootable, + PSVitaBootablePSVitaTvNotBootable + } + public enum PSVitaEnterButtonAssignment + { + Default, + CircleButton, + CrossButton + } + public enum PSVitaAppCategory + { + Application, + ApplicationPatch + } + public enum PSVitaDRMType + { + PaidFor, + Free + } + public static extern string npTrophyPackPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PSVita.PSVitaPowerMode powerMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool acquireBGM + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool npSupportGBMorGJP + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PSVita.PSVitaTvBootMode tvBootMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool tvDisableEmu + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool upgradable + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool healthWarning + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool useLibLocation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool infoBarOnStartup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool infoBarColor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PSVita.PSVitaEnterButtonAssignment enterButtonAssignment + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int saveDataQuota + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int parentalLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string shortTitle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string contentID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PSVita.PSVitaAppCategory category + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string masterVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string appVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool AllowTwitterDialog + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int npAgeRating + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npCommunicationsID + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npCommsPassphrase + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string npCommsSig + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string paramSfxPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string manualPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string liveAreaGatePath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string liveAreaBackroundPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string liveAreaPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string liveAreaTrialPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string patchChangeInfoPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string patchOriginalPackage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string packagePassword + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string keystoneFile + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.PSVita.PSVitaDRMType drmType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int storageType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int mediaCapacity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } public sealed class Android { - public static extern bool use24BitDepthBuffer + public static extern bool disableDepthAndStencilBuffers { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -17,6 +1117,17 @@ public static extern bool use24BitDepthBuffer [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("This has been replaced by disableDepthAndStencilBuffers")] + public static bool use24BitDepthBuffer + { + get + { + return !PlayerSettings.Android.disableDepthAndStencilBuffers; + } + set + { + } + } public static extern int bundleVersionCode { [WrapperlessIcall] @@ -62,6 +1173,33 @@ public static extern bool forceSDCardPermission [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool androidTVCompatibility + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool androidIsGame + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal static extern bool androidBannerEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } internal static extern bool createWallpaper { [WrapperlessIcall] @@ -149,6 +1287,15 @@ public static extern AndroidShowActivityIndicatorOnLoading showActivityIndicator [MethodImpl(MethodImplOptions.InternalCall)] set; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern AndroidBanner[] GetAndroidBanners(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Texture2D GetAndroidBannerForHeight(int height); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetAndroidBanners(Texture2D[] banners); } public sealed class iOS { @@ -233,7 +1380,19 @@ public static extern iOSStatusBarStyle statusBarStyle [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern bool exitOnSuspend + [Obsolete("use appInBackgroundBehavior")] + public static bool exitOnSuspend + { + get + { + return PlayerSettings.iOS.appInBackgroundBehavior == iOSAppInBackgroundBehavior.Exit; + } + set + { + PlayerSettings.iOS.appInBackgroundBehavior = iOSAppInBackgroundBehavior.Exit; + } + } + public static extern iOSAppInBackgroundBehavior appInBackgroundBehavior { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -252,7 +1411,7 @@ public static extern iOSShowActivityIndicatorOnLoading showActivityIndicatorOnLo set; } } - public enum MetroApplicationShowName + public enum WSAApplicationShowName { NotSet, AllLogos, @@ -260,24 +1419,24 @@ public enum MetroApplicationShowName StandardLogoOnly, WideLogoOnly } - public enum MetroDefaultTileSize + public enum WSADefaultTileSize { NotSet, Medium, Wide } - public enum MetroApplicationForegroundText + public enum WSAApplicationForegroundText { Light = 1, Dark } - public enum MetroCompilationOverrides + public enum WSACompilationOverrides { None, UseNetCore, UseNetCorePartially } - public enum MetroCapability + public enum WSACapability { EnterpriseAuthentication, InternetClient, @@ -291,9 +1450,10 @@ public enum MetroCapability WebCam, Proximity, Microphone, - Location + Location, + HumanInterfaceDevice } - public sealed class Metro + public sealed class WSA { public static extern string packageName { @@ -347,17 +1507,17 @@ public static Version packageVersion Version result; try { - result = new Version(PlayerSettingsEditor.ValidateMetroPackageVersion(PlayerSettings.Metro.packageVersionRaw)); + result = new Version(PlayerSettings.WSA.ValidatePackageVersion(PlayerSettings.WSA.packageVersionRaw)); } catch (Exception ex) { - throw new Exception(string.Format("{0}, the raw string was {1}", ex.Message, PlayerSettings.Metro.packageVersionRaw)); + throw new Exception(string.Format("{0}, the raw string was {1}", ex.Message, PlayerSettings.WSA.packageVersionRaw)); } return result; } set { - PlayerSettings.Metro.packageVersionRaw = value.ToString(); + PlayerSettings.WSA.packageVersionRaw = value.ToString(); } } private static extern string packageVersionRaw @@ -406,7 +1566,7 @@ public static DateTime? certificateNotAfter { get { - long certificateNotAfterRaw = PlayerSettings.Metro.certificateNotAfterRaw; + long certificateNotAfterRaw = PlayerSettings.WSA.certificateNotAfterRaw; if (certificateNotAfterRaw != 0L) { return new DateTime?(DateTime.FromFileTime(certificateNotAfterRaw)); @@ -780,7 +1940,7 @@ public static extern string tileShortName [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern PlayerSettings.MetroApplicationShowName tileShowName + public static extern PlayerSettings.WSAApplicationShowName tileShowName { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -816,16 +1976,7 @@ public static extern bool wideTileShowName [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern PlayerSettings.MetroDefaultTileSize defaultTileSize - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public static extern PlayerSettings.MetroCompilationOverrides compilationOverrides + public static extern PlayerSettings.WSADefaultTileSize defaultTileSize { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -834,7 +1985,7 @@ public static extern PlayerSettings.MetroCompilationOverrides compilationOverrid [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern PlayerSettings.MetroApplicationForegroundText tileForegroundText + public static extern PlayerSettings.WSACompilationOverrides compilationOverrides { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -843,7 +1994,7 @@ public static extern PlayerSettings.MetroApplicationForegroundText tileForegroun [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern string[] unprocessedPlugins + public static extern PlayerSettings.WSAApplicationForegroundText tileForegroundText { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -857,12 +2008,12 @@ public static Color tileBackgroundColor get { Color result; - PlayerSettings.Metro.INTERNAL_get_tileBackgroundColor(out result); + PlayerSettings.WSA.INTERNAL_get_tileBackgroundColor(out result); return result; } set { - PlayerSettings.Metro.INTERNAL_set_tileBackgroundColor(ref value); + PlayerSettings.WSA.INTERNAL_set_tileBackgroundColor(ref value); } } public static extern bool enableIndependentInputSource @@ -887,18 +2038,18 @@ public static Color? splashScreenBackgroundColor { get { - if (PlayerSettings.Metro.splashScreenUseBackgroundColor) + if (PlayerSettings.WSA.splashScreenUseBackgroundColor) { - return new Color?(PlayerSettings.Metro.splashScreenBackgroundColorRaw); + return new Color?(PlayerSettings.WSA.splashScreenBackgroundColorRaw); } return null; } set { - PlayerSettings.Metro.splashScreenUseBackgroundColor = value.HasValue; + PlayerSettings.WSA.splashScreenUseBackgroundColor = value.HasValue; if (value.HasValue) { - PlayerSettings.Metro.splashScreenBackgroundColorRaw = value.Value; + PlayerSettings.WSA.splashScreenBackgroundColorRaw = value.Value; } } } @@ -916,13 +2067,22 @@ private static Color splashScreenBackgroundColorRaw get { Color result; - PlayerSettings.Metro.INTERNAL_get_splashScreenBackgroundColorRaw(out result); + PlayerSettings.WSA.INTERNAL_get_splashScreenBackgroundColorRaw(out result); return result; } set { - PlayerSettings.Metro.INTERNAL_set_splashScreenBackgroundColorRaw(ref value); + PlayerSettings.WSA.INTERNAL_set_splashScreenBackgroundColorRaw(ref value); + } + } + internal static string ValidatePackageVersion(string value) + { + Regex regex = new Regex("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); + if (regex.IsMatch(value)) + { + return value; } + return "1.0.0.0"; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -939,32 +2099,42 @@ private static Color splashScreenBackgroundColorRaw [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_set_splashScreenBackgroundColorRaw(ref Color value); - public static void SetCapability(PlayerSettings.MetroCapability capability, bool enabled) + public static void SetCapability(PlayerSettings.WSACapability capability, bool value) { - PlayerSettings.Metro.InternalSetCapability(capability.ToString(), enabled); + PlayerSettings.WSA.InternalSetCapability(capability.ToString(), value.ToString()); } - public static bool GetCapability(PlayerSettings.MetroCapability capability) + public static bool GetCapability(PlayerSettings.WSACapability capability) { - return PlayerSettings.Metro.InternalGetCapability(capability.ToString()); + string text = PlayerSettings.WSA.InternalGetCapability(capability.ToString()); + if (string.IsNullOrEmpty(text)) + { + return false; + } + bool result; + try + { + result = (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(text); + } + catch + { + Debug.LogError(string.Concat(new string[] + { + "Failed to parse value ('", + capability.ToString(), + ",", + text, + "') to bool type." + })); + result = false; + } + return result; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void InternalSetCapability(string name, bool enabled); + private static extern void InternalSetCapability(string name, string value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool InternalGetCapability(string name); - } - public sealed class WP8 - { - public static extern string[] unprocessedPlugins - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } + private static extern string InternalGetCapability(string name); } public sealed class BlackBerry { @@ -1022,15 +2192,6 @@ public static extern string tokenAuthorId [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern string authorId - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public static extern string cskPassword { [WrapperlessIcall] @@ -1051,12 +2212,6 @@ public static extern string saveLogPath } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetAuthorIDOverride(bool enable); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsAuthorIDOverride(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasSharedPermissions(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1143,9 +2298,49 @@ public static extern string certificatePassword [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetMicrophonePermissions(bool enable); } - public sealed class PS3 + public sealed class PSM { - public static extern int videoMemoryForVertexBuffers + } + public sealed class SamsungTV + { + public enum SamsungTVProductCategories + { + Games, + Videos, + Sports, + Lifestyle, + Information, + Education, + Kids + } + public static extern string deviceAddress + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string productDescription + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string productAuthor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string productAuthorEmail { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1154,10 +2349,16 @@ public static extern int videoMemoryForVertexBuffers [MethodImpl(MethodImplOptions.InternalCall)] set; } - } - public sealed class SamsungTV - { - public static extern string deviceAddress + public static extern string productLink + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern PlayerSettings.SamsungTV.SamsungTVProductCategories productCategory { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1192,6 +2393,26 @@ public static extern string productName [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static string cloudProjectId + { + get + { + return PlayerSettings.cloudProjectIdRaw; + } + internal set + { + PlayerSettings.cloudProjectIdRaw = value; + } + } + private static extern string cloudProjectIdRaw + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static Guid productGUID { get @@ -1313,7 +2534,7 @@ public static extern bool resizableWindow [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern bool stripPhysics + public static extern bool bakeCollisionMeshes { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1349,7 +2570,7 @@ public static extern D3D9FullscreenMode d3d9FullscreenMode [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern bool d3d11ForceExclusiveMode + public static extern D3D11FullscreenMode d3d11FullscreenMode { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -1405,15 +2626,6 @@ public static extern Texture2D resolutionDialogBanner [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern string locationUsageDescription - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public static extern string iPhoneBundleIdentifier { [WrapperlessIcall] @@ -1582,149 +2794,56 @@ public static extern bool xboxEnableAvatar [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern string ps3TitleConfigPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3DLCConfigPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3ThumbnailPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3BackgroundPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3SoundPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3TrophyCommId - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3NpCommunicationPassphrase - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3TrophyCommSig - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string ps3TrophyPackagePath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern int ps3BootCheckMaxSaveGameSizeKB - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern bool ps3TrialMode - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern int ps3SaveGameSlots - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string psp2NPTrophyPackPath - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string psp2NPCommsID + public static extern int xboxOneResolution { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern string psp2NPCommsPassphrase + public static extern bool enableInternalProfiler { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public static extern string psp2NPCommsSig - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public static extern string psp2ParamSfxPath + public static extern ActionOnDotNetUnhandledException actionOnDotNetUnhandledException { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public static extern string psp2PackagePassword - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public static extern string psp2DLCConfigPath + public static extern bool logObjCUncaughtExceptions { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public static extern string psp2ThumbnailPath - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public static extern string psp2BackgroundPath + public static extern bool enableCrashReportAPI { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public static extern string psp2SoundPath - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public static extern string psp2TrophyCommId + public static extern string locationUsageDescription { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public static extern string psp2TrophyPackagePath - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } public static extern string bundleIdentifier { @@ -1744,15 +2863,6 @@ public static extern string bundleVersion [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern string shortBundleVersion - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public static extern bool statusBarHidden { [WrapperlessIcall] @@ -1939,6 +3049,15 @@ public static extern bool useDirect3D11 [MethodImpl(MethodImplOptions.InternalCall)] set; } + internal static extern bool submitAnalytics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool stereoscopic3D { [WrapperlessIcall] @@ -1970,12 +3089,59 @@ internal static SerializedProperty FindProperty(string name) } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool GetPropertyOptionalInt(string name, ref int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target); + internal static extern void SetPropertyIntInternal(string name, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InitializePropertyIntInternal(string name, int value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetPropertyIntInternal(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPropertyBoolInternal(string name, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InitializePropertyBoolInternal(string name, bool value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool GetPropertyBoolInternal(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPropertyStringInternal(string name, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void InitializePropertyStringInternal(string name, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPropertyStringInternal(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern string GetPropertyNameForBuildTargetGroupInternal(BuildTargetGroup target, string name); + internal static string GetPropertyNameForBuildTarget(BuildTargetGroup target, string name) + { + string propertyNameForBuildTargetGroupInternal = PlayerSettings.GetPropertyNameForBuildTargetGroupInternal(target, name); + if (propertyNameForBuildTargetGroupInternal != string.Empty) + { + return propertyNameForBuildTargetGroupInternal; + } + throw new ArgumentException("Failed to get property name for the given target."); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void AddEnum(string className, string propertyName, int value, string valueName); [ExcludeFromDocs] - public static bool GetPropertyOptionalInt(string name, ref int value) + public static void SetPropertyInt(string name, int value) { BuildTargetGroup target = BuildTargetGroup.Unknown; - return PlayerSettings.GetPropertyOptionalInt(name, ref value, target); + PlayerSettings.SetPropertyInt(name, value, target); + } + public static void SetPropertyInt(string name, int value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.SetPropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + public static void SetPropertyInt(string name, int value, BuildTarget target) + { + PlayerSettings.SetPropertyInt(name, value, BuildPipeline.GetBuildTargetGroup(target)); } [ExcludeFromDocs] public static int GetPropertyInt(string name) @@ -1983,42 +3149,95 @@ public static int GetPropertyInt(string name) BuildTargetGroup target = BuildTargetGroup.Unknown; return PlayerSettings.GetPropertyInt(name, target); } - public static int GetPropertyInt(string name, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + public static int GetPropertyInt(string name, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) { return PlayerSettings.GetPropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name)); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetPropertyIntInternal(string name); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void SetPropertyIntInternal(string name, int value); - public static void SetPropertyInt(string name, int value, BuildTarget target) + public static extern bool GetPropertyOptionalInt(string name, ref int value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target); + [ExcludeFromDocs] + public static bool GetPropertyOptionalInt(string name, ref int value) { - PlayerSettings.SetPropertyInt(name, value, BuildPipeline.GetBuildTargetGroup(target)); + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyOptionalInt(name, ref value, target); } [ExcludeFromDocs] - public static void SetPropertyInt(string name, int value) + internal static void InitializePropertyInt(string name, int value) { BuildTargetGroup target = BuildTargetGroup.Unknown; - PlayerSettings.SetPropertyInt(name, value, target); + PlayerSettings.InitializePropertyInt(name, value, target); } - public static void SetPropertyInt(string name, int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + internal static void InitializePropertyInt(string name, int value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) { - PlayerSettings.SetPropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + PlayerSettings.InitializePropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + [ExcludeFromDocs] + public static void SetPropertyBool(string name, bool value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.SetPropertyBool(name, value, target); + } + public static void SetPropertyBool(string name, bool value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.SetPropertyBoolInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + public static void SetPropertyBool(string name, bool value, BuildTarget target) + { + PlayerSettings.SetPropertyBool(name, value, BuildPipeline.GetBuildTargetGroup(target)); + } + [ExcludeFromDocs] + public static bool GetPropertyBool(string name) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyBool(name, target); + } + public static bool GetPropertyBool(string name, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + return PlayerSettings.GetPropertyBoolInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name)); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void InitializePropertyIntInternal(string name, int value); + public static extern bool GetPropertyOptionalBool(string name, ref bool value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target); [ExcludeFromDocs] - internal static void InitializePropertyInt(string name, int value) + public static bool GetPropertyOptionalBool(string name, ref bool value) { BuildTargetGroup target = BuildTargetGroup.Unknown; - PlayerSettings.InitializePropertyInt(name, value, target); + return PlayerSettings.GetPropertyOptionalBool(name, ref value, target); + } + [ExcludeFromDocs] + internal static void InitializePropertyBool(string name, bool value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.InitializePropertyBool(name, value, target); } - internal static void InitializePropertyInt(string name, int value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + internal static void InitializePropertyBool(string name, bool value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) { - PlayerSettings.InitializePropertyIntInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + PlayerSettings.InitializePropertyBoolInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + [ExcludeFromDocs] + public static void SetPropertyString(string name, string value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.SetPropertyString(name, value, target); + } + public static void SetPropertyString(string name, string value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.SetPropertyStringInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + public static void SetPropertyString(string name, string value, BuildTarget target) + { + PlayerSettings.SetPropertyString(name, value, BuildPipeline.GetBuildTargetGroup(target)); + } + [ExcludeFromDocs] + public static string GetPropertyString(string name) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + return PlayerSettings.GetPropertyString(name, target); + } + public static string GetPropertyString(string name, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + return PlayerSettings.GetPropertyStringInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name)); } [ExcludeFromDocs] public static bool GetPropertyOptionalString(string name, ref string value) @@ -2026,7 +3245,7 @@ public static bool GetPropertyOptionalString(string name, ref string value) BuildTargetGroup target = BuildTargetGroup.Unknown; return PlayerSettings.GetPropertyOptionalString(name, ref value, target); } - public static bool GetPropertyOptionalString(string name, ref string value, [DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + public static bool GetPropertyOptionalString(string name, ref string value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) { string propertyOptionalStringInternal = PlayerSettings.GetPropertyOptionalStringInternal(name, target); if (propertyOptionalStringInternal == null) @@ -2039,17 +3258,32 @@ public static bool GetPropertyOptionalString(string name, ref string value, [Def [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern string GetPropertyOptionalStringInternal(string name, BuildTargetGroup target); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetPropertyNameForBuildTargetGroupInternal(BuildTargetGroup target, string name); - internal static string GetPropertyNameForBuildTarget(BuildTargetGroup target, string name) + [ExcludeFromDocs] + internal static void InitializePropertyString(string name, string value) { - string propertyNameForBuildTargetGroupInternal = PlayerSettings.GetPropertyNameForBuildTargetGroupInternal(target, name); - if (propertyNameForBuildTargetGroupInternal != string.Empty) + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.InitializePropertyString(name, value, target); + } + internal static void InitializePropertyString(string name, string value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + PlayerSettings.InitializePropertyStringInternal(PlayerSettings.GetPropertyNameForBuildTarget(target, name), value); + } + [ExcludeFromDocs] + internal static void InitializePropertyEnum(string name, object value) + { + BuildTargetGroup target = BuildTargetGroup.Unknown; + PlayerSettings.InitializePropertyEnum(name, value, target); + } + internal static void InitializePropertyEnum(string name, object value, [UnityEngine.Internal.DefaultValue("BuildTargetGroup.Unknown")] BuildTargetGroup target) + { + string propertyNameForBuildTarget = PlayerSettings.GetPropertyNameForBuildTarget(target, name); + string[] names = Enum.GetNames(value.GetType()); + Array values = Enum.GetValues(value.GetType()); + for (int i = 0; i < names.Length; i++) { - return propertyNameForBuildTargetGroupInternal; + PlayerSettings.AddEnum("PlayerSettings", propertyNameForBuildTarget, (int)values.GetValue(i), names[i]); } - throw new ArgumentException("Failed to get property name for the given target."); + PlayerSettings.InitializePropertyIntInternal(propertyNameForBuildTarget, (int)value); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/PlayerSettingsEditor.cs b/UnityEditor/UnityEditor/PlayerSettingsEditor.cs index 1b2acdc9..bb9353a4 100644 --- a/UnityEditor/UnityEditor/PlayerSettingsEditor.cs +++ b/UnityEditor/UnityEditor/PlayerSettingsEditor.cs @@ -1,9 +1,6 @@ using System; -using System.Collections; -using System.Collections.Generic; using System.IO; -using System.Text; -using System.Text.RegularExpressions; +using System.Linq; using UnityEditor.AnimatedValues; using UnityEditor.Modules; using UnityEditorInternal; @@ -16,8 +13,6 @@ internal class PlayerSettingsEditor : Editor { private class Styles { - public GUIStyle thumbnail = "IN ThumbnailShadow"; - public GUIStyle thumbnailLabel = "IN ThumbnailSelection"; public GUIStyle categoryBox = new GUIStyle(EditorStyles.helpBox); public GUIContent colorSpaceWarning = EditorGUIUtility.TextContent("PlayerSettings.ActiveColorSpaceWarning"); public GUIContent cursorHotspot = EditorGUIUtility.TextContent("PlayerSettings.CursorHotspot"); @@ -30,174 +25,55 @@ public Styles() } private enum FakeEnum { - WebplayerSubset, - FlashPlayerSubset + WebplayerSubset } - internal class WebPlayerTemplate + internal class WebPlayerTemplateManager : WebTemplateManagerBase { - private static PlayerSettingsEditor.WebPlayerTemplate[] s_Templates; - private static GUIContent[] s_TemplateGUIThumbnails; - private string m_Path; - private string m_Name; - private Texture2D m_Thumbnail; - private string[] m_CustomKeys; - public string[] CustomKeys + private const string kWebTemplateDefaultIconResource = "BuildSettings.Web.Small"; + public override string customTemplatesFolder { get { - return this.m_CustomKeys; + return Path.Combine(Application.dataPath.Replace('/', Path.DirectorySeparatorChar), "WebPlayerTemplates"); } } - public static PlayerSettingsEditor.WebPlayerTemplate[] Templates + public override string builtinTemplatesFolder { get { - if (PlayerSettingsEditor.WebPlayerTemplate.s_Templates == null || PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails == null) - { - PlayerSettingsEditor.WebPlayerTemplate.BuildTemplateList(); - } - return PlayerSettingsEditor.WebPlayerTemplate.s_Templates; + return Path.Combine(Path.Combine(EditorApplication.applicationContentsPath.Replace('/', Path.DirectorySeparatorChar), "Resources"), "WebPlayerTemplates"); } } - public static GUIContent[] TemplateGUIThumbnails + public override Texture2D defaultIcon { get { - if (PlayerSettingsEditor.WebPlayerTemplate.s_Templates == null || PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails == null) - { - PlayerSettingsEditor.WebPlayerTemplate.BuildTemplateList(); - } - return PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails; - } - } - public static int GetTemplateIndex(string path) - { - for (int i = 0; i < PlayerSettingsEditor.WebPlayerTemplate.Templates.Length; i++) - { - if (path.Equals(PlayerSettingsEditor.WebPlayerTemplate.Templates[i].ToString())) - { - return i; - } - } - return 0; - } - public static void ClearTemplates() - { - PlayerSettingsEditor.WebPlayerTemplate.s_Templates = null; - PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails = null; - } - private static void BuildTemplateList() - { - List list = new List(); - string path = Path.Combine(Application.dataPath.Replace('/', Path.DirectorySeparatorChar), "WebPlayerTemplates"); - if (Directory.Exists(path)) - { - list.AddRange(PlayerSettingsEditor.WebPlayerTemplate.ListTemplates(path)); - } - string path2 = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath.Replace('/', Path.DirectorySeparatorChar), "Resources"), "WebPlayerTemplates"); - if (Directory.Exists(path2)) - { - list.AddRange(PlayerSettingsEditor.WebPlayerTemplate.ListTemplates(path2)); - } - else - { - Debug.LogError("Did not find built-in templates."); - } - PlayerSettingsEditor.WebPlayerTemplate.s_Templates = list.ToArray(); - PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails = new GUIContent[PlayerSettingsEditor.WebPlayerTemplate.s_Templates.Length]; - for (int i = 0; i < PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails.Length; i++) - { - PlayerSettingsEditor.WebPlayerTemplate.s_TemplateGUIThumbnails[i] = PlayerSettingsEditor.WebPlayerTemplate.s_Templates[i].ToGUIContent(); + return (Texture2D)EditorGUIUtility.IconContent("BuildSettings.Web.Small").image; } } - private static PlayerSettingsEditor.WebPlayerTemplate Load(string path) - { - if (!Directory.Exists(path) || Directory.GetFiles(path, "index.*").Length < 1) - { - return null; - } - string[] array = path.Split(new char[] - { - Path.DirectorySeparatorChar - }); - PlayerSettingsEditor.WebPlayerTemplate webPlayerTemplate = new PlayerSettingsEditor.WebPlayerTemplate(); - webPlayerTemplate.m_Name = array[array.Length - 1]; - if (array.Length > 3 && array[array.Length - 3].Equals("Assets")) - { - webPlayerTemplate.m_Path = "PROJECT:" + webPlayerTemplate.m_Name; - } - else - { - webPlayerTemplate.m_Path = "APPLICATION:" + webPlayerTemplate.m_Name; - } - string[] files = Directory.GetFiles(path, "thumbnail.*"); - if (files.Length > 0) - { - webPlayerTemplate.m_Thumbnail = new Texture2D(2, 2); - webPlayerTemplate.m_Thumbnail.LoadImage(File.ReadAllBytes(files[0])); - } - List list = new List(); - Regex regex = new Regex("\\%UNITY_CUSTOM_([A-Z_]+)\\%"); - MatchCollection matchCollection = regex.Matches(File.ReadAllText(Directory.GetFiles(path, "index.*")[0])); - foreach (Match match in matchCollection) - { - string text = match.Value.Substring("%UNITY_CUSTOM_".Length); - text = text.Substring(0, text.Length - 1); - if (!list.Contains(text)) - { - list.Add(text); - } - } - webPlayerTemplate.m_CustomKeys = list.ToArray(); - return webPlayerTemplate; - } - private static List ListTemplates(string path) - { - List list = new List(); - string[] directories = Directory.GetDirectories(path); - string[] array = directories; - for (int i = 0; i < array.Length; i++) - { - string path2 = array[i]; - PlayerSettingsEditor.WebPlayerTemplate webPlayerTemplate = PlayerSettingsEditor.WebPlayerTemplate.Load(path2); - if (webPlayerTemplate != null) - { - list.Add(webPlayerTemplate); - } - } - return list; - } - public override bool Equals(object other) - { - return other is PlayerSettingsEditor.WebPlayerTemplate && other.ToString().Equals(this.ToString()); - } - public override int GetHashCode() - { - return base.GetHashCode() ^ this.m_Path.GetHashCode(); - } - public override string ToString() - { - return this.m_Path; - } - public GUIContent ToGUIContent() - { - return new GUIContent(this.m_Name, (!(this.m_Thumbnail == null)) ? this.m_Thumbnail : ((Texture2D)EditorGUIUtility.IconContent("BuildSettings.Web.Small").image)); - } } private const int kSlotSize = 64; private const int kMaxPreviewSize = 96; private const int kIconSpacing = 6; - private const string kWebPlayerTemplateDefaultIconResource = "BuildSettings.Web.Small"; - private const float kWebPlayerTemplateGridPadding = 15f; - private const float kThumbnailSize = 80f; - private const float kThumbnailLabelHeight = 20f; - private const float kThumbnailPadding = 5f; private static PlayerSettingsEditor.Styles s_Styles; + private static GUIContent[] kRenderPaths = new GUIContent[] + { + new GUIContent("Forward"), + new GUIContent("Deferred"), + new GUIContent("Legacy Vertex Lit"), + new GUIContent("Legacy Deferred (light prepass)") + }; + private static int[] kRenderPathValues = new int[] + { + 1, + 3, + 0, + 2 + }; private SavedInt m_SelectedSection = new SavedInt("PlayerSettings.ShownSection", -1); private BuildPlayerWindow.BuildPlatform[] validPlatforms; - private SerializedProperty m_IPhoneBundleIdentifier; - private SerializedProperty m_IPhoneBundleVersion; - private SerializedProperty m_IPhoneShortBundleVersion; + private SerializedProperty m_ApplicationBundleIdentifier; + private SerializedProperty m_ApplicationBundleVersion; private SerializedProperty m_IPhoneApplicationDisplayName; private SerializedProperty m_LocationUsageDescription; private SerializedProperty m_ApiCompatibilityLevel; @@ -211,7 +87,7 @@ public GUIContent ToGUIContent() private SerializedProperty m_AllowedAutoRotateToLandscapeLeft; private SerializedProperty m_UseOSAutoRotation; private SerializedProperty m_Use32BitDisplayBuffer; - private SerializedProperty m_Use24BitDepthBuffer; + private SerializedProperty m_DisableDepthAndStencilBuffers; private SerializedProperty m_iosShowActivityIndicatorOnLoading; private SerializedProperty m_androidShowActivityIndicatorOnLoading; private SerializedProperty m_IPhoneSdkVersion; @@ -221,15 +97,19 @@ public GUIContent ToGUIContent() private SerializedProperty m_UIRequiresPersistentWiFi; private SerializedProperty m_UIStatusBarHidden; private SerializedProperty m_UIStatusBarStyle; - private SerializedProperty m_UIExitOnSuspend; - private SerializedProperty m_EnableHWStatistics; + private SerializedProperty m_IOSAppInBackgroundBehavior; + private SerializedProperty m_SubmitAnalytics; private SerializedProperty m_TargetDevice; private SerializedProperty m_TargetGlesGraphics; private SerializedProperty m_TargetIOSGraphics; - private SerializedProperty m_TargetResolution; private SerializedProperty m_AccelerometerFrequency; + private SerializedProperty m_TargetResolution; private SerializedProperty m_OverrideIPodMusic; private SerializedProperty m_PrepareIOSForRecording; + private SerializedProperty m_EnableInternalProfiler; + private SerializedProperty m_ActionOnDotNetUnhandledException; + private SerializedProperty m_LogObjCUncaughtExceptions; + private SerializedProperty m_EnableCrashReportAPI; private SerializedProperty m_XboxTitleId; private SerializedProperty m_XboxImageXexPath; private SerializedProperty m_XboxSpaPath; @@ -248,80 +128,8 @@ public GUIContent ToGUIContent() private SerializedProperty m_XboxEnableFitness; private SerializedProperty m_XboxAdditionalTitleMemorySize; private SerializedProperty m_XboxEnableGuest; - private SerializedProperty m_PS3TitleConfigPath; - private SerializedProperty m_PS3DLCConfigPath; - private SerializedProperty m_PS3ThumbnailPath; - private SerializedProperty m_PS3BackgroundPath; - private SerializedProperty m_PS3SoundPath; - private SerializedProperty m_PS3TrophyCommId; - private SerializedProperty m_PS3NpCommunicationPassphrase; - private SerializedProperty m_PS3TrophyPackagePath; - private SerializedProperty m_PS3BootCheckMaxSaveGameSizeKB; - private SerializedProperty m_PS3TrophyCommSig; - private SerializedProperty m_PS3TrialMode; - private SerializedProperty m_PS3SaveGameSlots; - private SerializedProperty m_PSP2SplashScreen; - private SerializedProperty m_PSP2LiveAreaGate; - private SerializedProperty m_PSP2LiveAreaBackground; - private SerializedProperty m_PSP2NPCommsID; - private SerializedProperty m_PSP2NPCommsPassphrase; - private SerializedProperty m_PSP2NPCommsSig; - private SerializedProperty m_PSP2TrophyPackPath; - private SerializedProperty m_PSP2ParamSfxPath; - private SerializedProperty m_PSP2PackagePassword; - private SerializedProperty m_FlashStrippingLevel; private SerializedProperty m_VideoMemoryForVertexBuffers; - private SerializedProperty m_MetroPackageName; - private SerializedProperty m_MetroPackageLogo; - private SerializedProperty m_MetroPackageLogo140; - private SerializedProperty m_MetroPackageLogo180; - private SerializedProperty m_MetroPackageLogo240; - private SerializedProperty m_MetroPackageVersion; - private SerializedProperty m_MetroApplicationDescription; - private SerializedProperty m_MetroTileShortName; - private SerializedProperty m_MetroTileBackgroundColor; - private SerializedProperty m_MetroStoreTileLogo80; - private SerializedProperty m_MetroStoreTileLogo; - private SerializedProperty m_MetroStoreTileLogo140; - private SerializedProperty m_MetroStoreTileLogo180; - private SerializedProperty m_MetroStoreTileWideLogo80; - private SerializedProperty m_MetroStoreTileWideLogo; - private SerializedProperty m_MetroStoreTileWideLogo140; - private SerializedProperty m_MetroStoreTileWideLogo180; - private SerializedProperty m_MetroStoreTileSmallLogo80; - private SerializedProperty m_MetroStoreTileSmallLogo; - private SerializedProperty m_MetroStoreTileSmallLogo140; - private SerializedProperty m_MetroStoreTileSmallLogo180; - private SerializedProperty m_MetroStoreSmallTile80; - private SerializedProperty m_MetroStoreSmallTile; - private SerializedProperty m_MetroStoreSmallTile140; - private SerializedProperty m_MetroStoreSmallTile180; - private SerializedProperty m_MetroStoreLargeTile80; - private SerializedProperty m_MetroStoreLargeTile; - private SerializedProperty m_MetroStoreLargeTile140; - private SerializedProperty m_MetroStoreLargeTile180; - private SerializedProperty m_MetroStoreSplashScreenImage; - private SerializedProperty m_MetroStoreSplashScreenImage140; - private SerializedProperty m_MetroStoreSplashScreenImage180; - private SerializedProperty m_MetroPhoneAppIcon; - private SerializedProperty m_MetroPhoneAppIcon140; - private SerializedProperty m_MetroPhoneAppIcon240; - private SerializedProperty m_MetroPhoneSmallTile; - private SerializedProperty m_MetroPhoneSmallTile140; - private SerializedProperty m_MetroPhoneSmallTile240; - private SerializedProperty m_MetroPhoneMediumTile; - private SerializedProperty m_MetroPhoneMediumTile140; - private SerializedProperty m_MetroPhoneMediumTile240; - private SerializedProperty m_MetroPhoneWideTile; - private SerializedProperty m_MetroPhoneWideTile140; - private SerializedProperty m_MetroPhoneWideTile240; - private SerializedProperty m_MetroPhoneSplashScreenImage; - private SerializedProperty m_MetroPhoneSplashScreenImage140; - private SerializedProperty m_MetroPhoneSplashScreenImage240; - private SerializedProperty m_MetroUnprocessedPlugins; - private SerializedProperty m_MetroEnableIndependentInputSource; - private SerializedProperty m_MetroEnableLowLatencyPresentationAPI; - private SerializedProperty m_WP8UnprocessedPlugins; + private SerializedProperty m_ps3SplashScreen; private SerializedProperty m_CompanyName; private SerializedProperty m_ProductName; private SerializedProperty m_DefaultCursor; @@ -340,12 +148,14 @@ public GUIContent ToGUIContent() private SerializedProperty m_DefaultIsFullScreen; private SerializedProperty m_DefaultIsNativeResolution; private SerializedProperty m_UsePlayerLog; + private SerializedProperty m_PreloadShaders; + private SerializedProperty m_PreloadedAssets; + private SerializedProperty m_BakeCollisionMeshes; private SerializedProperty m_ResizableWindow; - private SerializedProperty m_StripPhysics; private SerializedProperty m_UseMacAppStoreValidation; private SerializedProperty m_MacFullscreenMode; private SerializedProperty m_D3D9FullscreenMode; - private SerializedProperty m_D3D11ForceExclusiveMode; + private SerializedProperty m_D3D11FullscreenMode; private SerializedProperty m_VisibleInBackground; private SerializedProperty m_ForceSingleInstance; private SerializedProperty m_RunInBackground; @@ -355,19 +165,21 @@ public GUIContent ToGUIContent() private SerializedProperty m_SkinOnGPU; private SerializedProperty m_FirstStreamedLevelWithResources; private SerializedProperty m_WebPlayerTemplate; + private PlayerSettingsEditor.WebPlayerTemplateManager m_WebPlayerTemplateManager = new PlayerSettingsEditor.WebPlayerTemplateManager(); private int selectedPlatform; private int scriptingDefinesControlID; - private AnimBool[] m_SectionAnimators = new AnimBool[5]; + private AnimBool[] m_SectionAnimators = new AnimBool[6]; private readonly AnimBool m_ShowDeferredWarning = new AnimBool(); private readonly AnimBool m_ShowDefaultIsNativeResolution = new AnimBool(); private readonly AnimBool m_ShowResolution = new AnimBool(); private static Texture2D s_WarningIcon; - private Vector2 capScrollViewPosition = Vector2.zero; - private static readonly Regex metroPackageNameRegex = new Regex("^[A-Za-z0-9\\.\\-]{2,49}[A-Za-z0-9\\-]$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - private static readonly Regex metroPackageVersionRegex = new Regex("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); private bool IsMobileTarget(BuildTargetGroup targetGroup) { - return targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.Tizen; + return targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BlackBerry || targetGroup == BuildTargetGroup.Tizen || targetGroup == BuildTargetGroup.SamsungTV; + } + private static bool IsWP8Player(BuildTargetGroup target) + { + return target == BuildTargetGroup.WP8; } public SerializedProperty FindPropertyAssert(string name) { @@ -381,18 +193,6 @@ public SerializedProperty FindPropertyAssert(string name) private void OnEnable() { this.validPlatforms = BuildPlayerWindow.GetValidPlatforms().ToArray(); - this.m_PS3TitleConfigPath = this.FindPropertyAssert("ps3TitleConfigPath"); - this.m_PS3DLCConfigPath = this.FindPropertyAssert("ps3DLCConfigPath"); - this.m_PS3ThumbnailPath = this.FindPropertyAssert("ps3ThumbnailPath"); - this.m_PS3BackgroundPath = this.FindPropertyAssert("ps3BackgroundPath"); - this.m_PS3SoundPath = this.FindPropertyAssert("ps3SoundPath"); - this.m_PS3TrophyCommId = this.FindPropertyAssert("ps3TrophyCommId"); - this.m_PS3NpCommunicationPassphrase = this.FindPropertyAssert("ps3NpCommunicationPassphrase"); - this.m_PS3TrophyPackagePath = this.FindPropertyAssert("ps3TrophyPackagePath"); - this.m_PS3BootCheckMaxSaveGameSizeKB = this.FindPropertyAssert("ps3BootCheckMaxSaveGameSizeKB"); - this.m_PS3TrophyCommSig = this.FindPropertyAssert("ps3TrophyCommSig"); - this.m_PS3TrialMode = this.FindPropertyAssert("ps3TrialMode"); - this.m_PS3SaveGameSlots = this.FindPropertyAssert("ps3SaveGameSlots"); this.m_IPhoneSdkVersion = this.FindPropertyAssert("iPhoneSdkVersion"); this.m_IPhoneTargetOSVersion = this.FindPropertyAssert("iPhoneTargetOSVersion"); this.m_IPhoneStrippingLevel = this.FindPropertyAssert("iPhoneStrippingLevel"); @@ -413,19 +213,30 @@ private void OnEnable() this.m_MobileMTRendering = this.FindPropertyAssert("m_MobileMTRendering"); this.m_StripUnusedMeshComponents = this.FindPropertyAssert("StripUnusedMeshComponents"); this.m_FirstStreamedLevelWithResources = this.FindPropertyAssert("firstStreamedLevelWithResources"); - this.m_IPhoneBundleIdentifier = this.FindPropertyAssert("iPhoneBundleIdentifier"); - this.m_IPhoneBundleVersion = this.FindPropertyAssert("iPhoneBundleVersion"); - this.m_IPhoneShortBundleVersion = this.FindPropertyAssert("iPhoneShortBundleVersion"); + this.m_ApplicationBundleIdentifier = base.serializedObject.FindProperty("bundleIdentifier"); + if (this.m_ApplicationBundleIdentifier == null) + { + this.m_ApplicationBundleIdentifier = this.FindPropertyAssert("iPhoneBundleIdentifier"); + } + this.m_ApplicationBundleVersion = base.serializedObject.FindProperty("bundleVersion"); + if (this.m_ApplicationBundleVersion == null) + { + this.m_ApplicationBundleVersion = this.FindPropertyAssert("iPhoneBundleVersion"); + } this.m_TargetResolution = this.FindPropertyAssert("targetResolution"); this.m_AccelerometerFrequency = this.FindPropertyAssert("accelerometerFrequency"); this.m_OverrideIPodMusic = this.FindPropertyAssert("Override IPod Music"); this.m_PrepareIOSForRecording = this.FindPropertyAssert("Prepare IOS For Recording"); this.m_UIRequiresPersistentWiFi = this.FindPropertyAssert("uIRequiresPersistentWiFi"); - this.m_UIExitOnSuspend = this.FindPropertyAssert("uIExitOnSuspend"); - this.m_EnableHWStatistics = this.FindPropertyAssert("enableHWStatistics"); + this.m_IOSAppInBackgroundBehavior = this.FindPropertyAssert("iosAppInBackgroundBehavior"); + this.m_SubmitAnalytics = this.FindPropertyAssert("submitAnalytics"); this.m_ApiCompatibilityLevel = this.FindPropertyAssert("apiCompatibilityLevel"); this.m_AotOptions = this.FindPropertyAssert("aotOptions"); this.m_LocationUsageDescription = this.FindPropertyAssert("locationUsageDescription"); + this.m_EnableInternalProfiler = this.FindPropertyAssert("enableInternalProfiler"); + this.m_ActionOnDotNetUnhandledException = this.FindPropertyAssert("actionOnDotNetUnhandledException"); + this.m_LogObjCUncaughtExceptions = this.FindPropertyAssert("logObjCUncaughtExceptions"); + this.m_EnableCrashReportAPI = this.FindPropertyAssert("enableCrashReportAPI"); this.m_DefaultScreenWidth = this.FindPropertyAssert("defaultScreenWidth"); this.m_DefaultScreenHeight = this.FindPropertyAssert("defaultScreenHeight"); this.m_DefaultScreenWidthWeb = this.FindPropertyAssert("defaultScreenWidthWeb"); @@ -438,7 +249,7 @@ private void OnEnable() this.m_AllowedAutoRotateToLandscapeLeft = this.FindPropertyAssert("allowedAutorotateToLandscapeLeft"); this.m_UseOSAutoRotation = this.FindPropertyAssert("useOSAutorotation"); this.m_Use32BitDisplayBuffer = this.FindPropertyAssert("use32BitDisplayBuffer"); - this.m_Use24BitDepthBuffer = this.FindPropertyAssert("use24BitDepthBuffer"); + this.m_DisableDepthAndStencilBuffers = this.FindPropertyAssert("disableDepthAndStencilBuffers"); this.m_iosShowActivityIndicatorOnLoading = this.FindPropertyAssert("iosShowActivityIndicatorOnLoading"); this.m_androidShowActivityIndicatorOnLoading = this.FindPropertyAssert("androidShowActivityIndicatorOnLoading"); this.m_DefaultIsFullScreen = this.FindPropertyAssert("defaultIsFullScreen"); @@ -451,11 +262,13 @@ private void OnEnable() this.m_TargetIOSGraphics = this.FindPropertyAssert("targetIOSGraphics"); this.m_TargetDevice = this.FindPropertyAssert("targetDevice"); this.m_UsePlayerLog = this.FindPropertyAssert("usePlayerLog"); + this.m_PreloadShaders = this.FindPropertyAssert("preloadShaders"); + this.m_PreloadedAssets = this.FindPropertyAssert("preloadedAssets"); + this.m_BakeCollisionMeshes = this.FindPropertyAssert("bakeCollisionMeshes"); this.m_ResizableWindow = this.FindPropertyAssert("resizableWindow"); - this.m_StripPhysics = this.FindPropertyAssert("stripPhysics"); this.m_UseMacAppStoreValidation = this.FindPropertyAssert("useMacAppStoreValidation"); this.m_D3D9FullscreenMode = this.FindPropertyAssert("d3d9FullscreenMode"); - this.m_D3D11ForceExclusiveMode = this.FindPropertyAssert("d3d11ForceExclusiveMode"); + this.m_D3D11FullscreenMode = this.FindPropertyAssert("d3d11FullscreenMode"); this.m_VisibleInBackground = this.FindPropertyAssert("visibleInBackground"); this.m_MacFullscreenMode = this.FindPropertyAssert("macFullscreenMode"); this.m_SkinOnGPU = this.FindPropertyAssert("gpuSkinning"); @@ -478,72 +291,8 @@ private void OnEnable() this.m_XboxDeployHeadOrientation = this.FindPropertyAssert("xboxDeployKinectHeadOrientation"); this.m_XboxDeployKinectHeadPosition = this.FindPropertyAssert("xboxDeployKinectHeadPosition"); this.m_XboxEnableGuest = this.FindPropertyAssert("xboxEnableGuest"); - this.m_FlashStrippingLevel = this.FindPropertyAssert("flashStrippingLevel"); - this.m_PSP2SplashScreen = this.FindPropertyAssert("psp2Splashimage"); - this.m_PSP2LiveAreaGate = this.FindPropertyAssert("psp2LiveAreaGate"); - this.m_PSP2LiveAreaBackground = this.FindPropertyAssert("psp2LiveAreaBackround"); - this.m_PSP2NPCommsID = this.FindPropertyAssert("psp2NPCommsID"); - this.m_PSP2NPCommsPassphrase = this.FindPropertyAssert("psp2NPCommsPassphrase"); - this.m_PSP2NPCommsSig = this.FindPropertyAssert("psp2NPCommsSig"); - this.m_PSP2TrophyPackPath = this.FindPropertyAssert("psp2NPTrophyPackPath"); - this.m_PSP2ParamSfxPath = this.FindPropertyAssert("psp2ParamSfxPath"); - this.m_PSP2PackagePassword = this.FindPropertyAssert("psp2PackagePassword"); this.m_VideoMemoryForVertexBuffers = this.FindPropertyAssert("videoMemoryForVertexBuffers"); - this.m_MetroPackageName = this.FindPropertyAssert("metroPackageName"); - this.m_MetroPackageName.stringValue = this.ValidateMetroPackageName(this.m_MetroPackageName.stringValue); - this.m_MetroPackageLogo = this.FindPropertyAssert("metroPackageLogo"); - this.m_MetroPackageLogo140 = this.FindPropertyAssert("metroPackageLogo140"); - this.m_MetroPackageLogo180 = this.FindPropertyAssert("metroPackageLogo180"); - this.m_MetroPackageLogo240 = this.FindPropertyAssert("metroPackageLogo240"); - this.m_MetroPackageVersion = this.FindPropertyAssert("metroPackageVersion"); - this.m_MetroPackageVersion.stringValue = PlayerSettingsEditor.ValidateMetroPackageVersion(this.m_MetroPackageVersion.stringValue); - this.m_MetroApplicationDescription = this.FindPropertyAssert("metroApplicationDescription"); - this.m_MetroApplicationDescription.stringValue = this.ValidateMetroApplicationDescription(this.m_MetroApplicationDescription.stringValue); - this.m_MetroStoreTileLogo80 = this.FindPropertyAssert("metroStoreTileLogo80"); - this.m_MetroStoreTileLogo = this.FindPropertyAssert("metroStoreTileLogo"); - this.m_MetroStoreTileLogo140 = this.FindPropertyAssert("metroStoreTileLogo140"); - this.m_MetroStoreTileLogo180 = this.FindPropertyAssert("metroStoreTileLogo180"); - this.m_MetroStoreTileWideLogo80 = this.FindPropertyAssert("metroStoreTileWideLogo80"); - this.m_MetroStoreTileWideLogo = this.FindPropertyAssert("metroStoreTileWideLogo"); - this.m_MetroStoreTileWideLogo140 = this.FindPropertyAssert("metroStoreTileWideLogo140"); - this.m_MetroStoreTileWideLogo180 = this.FindPropertyAssert("metroStoreTileWideLogo180"); - this.m_MetroStoreTileSmallLogo80 = this.FindPropertyAssert("metroStoreTileSmallLogo80"); - this.m_MetroStoreTileSmallLogo = this.FindPropertyAssert("metroStoreTileSmallLogo"); - this.m_MetroStoreTileSmallLogo140 = this.FindPropertyAssert("metroStoreTileSmallLogo140"); - this.m_MetroStoreTileSmallLogo180 = this.FindPropertyAssert("metroStoreTileSmallLogo180"); - this.m_MetroStoreSmallTile80 = this.FindPropertyAssert("metroStoreSmallTile80"); - this.m_MetroStoreSmallTile = this.FindPropertyAssert("metroStoreSmallTile"); - this.m_MetroStoreSmallTile140 = this.FindPropertyAssert("metroStoreSmallTile140"); - this.m_MetroStoreSmallTile180 = this.FindPropertyAssert("metroStoreSmallTile180"); - this.m_MetroStoreLargeTile80 = this.FindPropertyAssert("metroStoreLargeTile80"); - this.m_MetroStoreLargeTile = this.FindPropertyAssert("metroStoreLargeTile"); - this.m_MetroStoreLargeTile140 = this.FindPropertyAssert("metroStoreLargeTile140"); - this.m_MetroStoreLargeTile180 = this.FindPropertyAssert("metroStoreLargeTile180"); - this.m_MetroStoreSplashScreenImage = this.FindPropertyAssert("metroStoreSplashScreenImage"); - this.m_MetroStoreSplashScreenImage140 = this.FindPropertyAssert("metroStoreSplashScreenImage140"); - this.m_MetroStoreSplashScreenImage180 = this.FindPropertyAssert("metroStoreSplashScreenImage180"); - this.m_MetroPhoneAppIcon = this.FindPropertyAssert("metroPhoneAppIcon"); - this.m_MetroPhoneAppIcon140 = this.FindPropertyAssert("metroPhoneAppIcon140"); - this.m_MetroPhoneAppIcon240 = this.FindPropertyAssert("metroPhoneAppIcon240"); - this.m_MetroPhoneSmallTile = this.FindPropertyAssert("metroPhoneSmallTile"); - this.m_MetroPhoneSmallTile140 = this.FindPropertyAssert("metroPhoneSmallTile140"); - this.m_MetroPhoneSmallTile240 = this.FindPropertyAssert("metroPhoneSmallTile240"); - this.m_MetroPhoneMediumTile = this.FindPropertyAssert("metroPhoneMediumTile"); - this.m_MetroPhoneMediumTile140 = this.FindPropertyAssert("metroPhoneMediumTile140"); - this.m_MetroPhoneMediumTile240 = this.FindPropertyAssert("metroPhoneMediumTile240"); - this.m_MetroPhoneWideTile = this.FindPropertyAssert("metroPhoneWideTile"); - this.m_MetroPhoneWideTile140 = this.FindPropertyAssert("metroPhoneWideTile140"); - this.m_MetroPhoneWideTile240 = this.FindPropertyAssert("metroPhoneWideTile240"); - this.m_MetroPhoneSplashScreenImage = this.FindPropertyAssert("metroPhoneSplashScreenImage"); - this.m_MetroPhoneSplashScreenImage140 = this.FindPropertyAssert("metroPhoneSplashScreenImage140"); - this.m_MetroPhoneSplashScreenImage240 = this.FindPropertyAssert("metroPhoneSplashScreenImage240"); - this.m_MetroTileShortName = this.FindPropertyAssert("metroTileShortName"); - this.m_MetroTileShortName.stringValue = this.ValidateMetroTileShortName(this.m_MetroTileShortName.stringValue); - this.m_MetroTileBackgroundColor = this.FindPropertyAssert("metroTileBackgroundColor"); - this.m_MetroUnprocessedPlugins = this.FindPropertyAssert("metroUnprocessedPlugins"); - this.m_MetroEnableIndependentInputSource = this.FindPropertyAssert("metroEnableIndependentInputSource"); - this.m_MetroEnableLowLatencyPresentationAPI = this.FindPropertyAssert("metroEnableLowLatencyPresentationAPI"); - this.m_WP8UnprocessedPlugins = this.FindPropertyAssert("wp8UnprocessedPlugins"); + this.m_ps3SplashScreen = this.FindPropertyAssert("ps3SplashScreen"); BuildPlayerWindow.BuildPlatform[] array = this.validPlatforms; for (int i = 0; i < array.Length; i++) { @@ -559,7 +308,7 @@ private void OnEnable() { this.m_SectionAnimators[j] = new AnimBool(this.m_SelectedSection.value == j, new UnityAction(base.Repaint)); } - this.m_ShowDeferredWarning.value = (!InternalEditorUtility.HasPro() && PlayerSettings.renderingPath == RenderingPath.DeferredLighting); + this.m_ShowDeferredWarning.value = (!InternalEditorUtility.HasProFeaturesEnabled() && (PlayerSettings.renderingPath == RenderingPath.DeferredLighting || PlayerSettings.renderingPath == RenderingPath.DeferredLighting)); this.m_ShowDefaultIsNativeResolution.value = this.m_DefaultIsFullScreen.boolValue; this.m_ShowResolution.value = (!this.m_DefaultIsFullScreen.boolValue || !this.m_DefaultIsNativeResolution.boolValue); this.m_ShowDeferredWarning.valueChanged.AddListener(new UnityAction(base.Repaint)); @@ -568,7 +317,7 @@ private void OnEnable() } private void OnDisable() { - PlayerSettingsEditor.WebPlayerTemplate.ClearTemplates(); + this.m_WebPlayerTemplateManager.ClearTemplates(); } public override bool UseDefaultMargins() { @@ -581,7 +330,7 @@ public override void OnInspectorGUI() PlayerSettingsEditor.s_Styles = new PlayerSettingsEditor.Styles(); } base.serializedObject.Update(); - this.m_ShowDeferredWarning.target = (!InternalEditorUtility.HasPro() && PlayerSettings.renderingPath == RenderingPath.DeferredLighting); + this.m_ShowDeferredWarning.target = (!InternalEditorUtility.HasProFeaturesEnabled() && PlayerSettings.renderingPath == RenderingPath.DeferredLighting); EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins, new GUILayoutOption[0]); this.CommonSettings(); EditorGUILayout.EndVertical(); @@ -606,8 +355,9 @@ public override void OnInspectorGUI() string targetStringFromBuildTargetGroup = ModuleManager.GetTargetStringFromBuildTargetGroup(targetGroup); ISettingEditorExtension editorSettingsExtension = ModuleManager.GetEditorSettingsExtension(targetStringFromBuildTargetGroup); this.ResolutionSectionGUI(targetGroup, editorSettingsExtension); - this.IconSectionGUI(targetGroup); + this.IconSectionGUI(targetGroup, editorSettingsExtension); this.SplashSectionGUI(buildPlatform, targetGroup, editorSettingsExtension); + this.DebugAndCrashReportingGUI(buildPlatform, targetGroup, editorSettingsExtension); this.OtherSectionGUI(buildPlatform, targetGroup, editorSettingsExtension); this.PublishSectionGUI(targetGroup, editorSettingsExtension); EditorGUILayout.EndPlatformGrouping(); @@ -668,7 +418,7 @@ private void ShowSharedNote() { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.SharedSettingsFootnote"), EditorStyles.miniLabel, new GUILayoutOption[0]); } - private void IconSectionGUI(BuildTargetGroup targetGroup) + private void IconSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) { GUI.changed = false; if (this.BeginSettingsBox(1, EditorGUIUtility.TextContent("PlayerSettings.IconHeader"))) @@ -684,20 +434,14 @@ private void IconSectionGUI(BuildTargetGroup targetGroup) platform = buildPlatform.name; } bool enabled = GUI.enabled; - if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.WP8) + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.WebPlayer || PlayerSettingsEditor.IsWP8Player(targetGroup) || targetGroup == BuildTargetGroup.SamsungTV) { this.ShowNoSettings(); EditorGUILayout.Space(); } else { - if (targetGroup == BuildTargetGroup.Metro) - { - float num = 16f; - float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; - this.MetroLogoSection(num2, num2, num, num); - } - else + if (targetGroup != BuildTargetGroup.Metro) { Texture2D[] array = PlayerSettings.GetIconsForPlatform(platform); int[] iconSizesForPlatform = PlayerSettings.GetIconSizesForPlatform(platform); @@ -732,16 +476,16 @@ private void IconSectionGUI(BuildTargetGroup targetGroup) GUI.changed = false; for (int i = 0; i < iconSizesForPlatform.Length; i++) { - int num3 = Mathf.Min(96, iconSizesForPlatform[i]); - Rect rect = GUILayoutUtility.GetRect(64f, (float)(Mathf.Max(64, num3) + 6)); - float num4 = Mathf.Min(rect.width, EditorGUIUtility.labelWidth + 4f + 64f + 6f + 96f); + int num = Mathf.Min(96, iconSizesForPlatform[i]); + Rect rect = GUILayoutUtility.GetRect(64f, (float)(Mathf.Max(64, num) + 6)); + float num2 = Mathf.Min(rect.width, EditorGUIUtility.labelWidth + 4f + 64f + 6f + 96f); string text = iconSizesForPlatform[i] + "x" + iconSizesForPlatform[i]; - GUI.Label(new Rect(rect.x, rect.y, num4 - 96f - 64f - 12f, 20f), text); + GUI.Label(new Rect(rect.x, rect.y, num2 - 96f - 64f - 12f, 20f), text); if (flag2) { - array[i] = (Texture2D)EditorGUI.ObjectField(new Rect(rect.x + num4 - 96f - 64f - 6f, rect.y, 64f, 64f), array[i], typeof(Texture2D), false); + array[i] = (Texture2D)EditorGUI.ObjectField(new Rect(rect.x + num2 - 96f - 64f - 6f, rect.y, 64f, 64f), array[i], typeof(Texture2D), false); } - Rect position = new Rect(rect.x + num4 - 96f, rect.y, (float)num3, (float)num3); + Rect position = new Rect(rect.x + num2 - 96f, rect.y, (float)num, (float)num); Texture2D iconForPlatformAtSize = PlayerSettings.GetIconForPlatformAtSize(platform, iconSizesForPlatform[i]); if (iconForPlatformAtSize != null) { @@ -757,13 +501,17 @@ private void IconSectionGUI(BuildTargetGroup targetGroup) PlayerSettings.SetIconsForPlatform(platform, array); } GUI.enabled = enabled; - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_UIPrerenderedIcon, EditorGUIUtility.TextContent("PlayerSettings.UIPrerenderedIcon"), new GUILayoutOption[0]); EditorGUILayout.Space(); } } } + if (settingsExtension != null) + { + settingsExtension.IconSectionGUI(); + } } this.EndSettingsBox(); } @@ -777,7 +525,7 @@ private void SplashSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTar this.m_ResolutionDialogBanner.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.ResolutionDialogBanner"), (Texture2D)this.m_ResolutionDialogBanner.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); EditorGUILayout.Space(); } - if (targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.NaCl || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.WP8) + if (targetGroup == BuildTargetGroup.WebPlayer || PlayerSettingsEditor.IsWP8Player(targetGroup)) { this.ShowNoSettings(); EditorGUILayout.Space(); @@ -787,24 +535,19 @@ private void SplashSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTar this.m_XboxSplashScreen.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.XboxSplashScreen"), (Texture2D)this.m_XboxSplashScreen.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); EditorGUILayout.Space(); } - if (targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM) + if (targetGroup == BuildTargetGroup.PS3) { - this.m_PSP2SplashScreen.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2SplashScreen"), (Texture2D)this.m_PSP2SplashScreen.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); + this.m_ps3SplashScreen.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.ps3SplashScreen"), (Texture2D)this.m_ps3SplashScreen.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); EditorGUILayout.Space(); } - EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget)); - if (targetGroup == BuildTargetGroup.Metro) - { - float num = 16f; - float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; - this.MetroSplashScreenSection(num2, num2, num, num); - } + bool flag = InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget) || targetGroup == BuildTargetGroup.iOS; + EditorGUI.BeginDisabledGroup(!flag); if (settingsExtension != null) { settingsExtension.SplashSectionGUI(); } EditorGUI.EndDisabledGroup(); - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android) { this.ShowSharedNote(); } @@ -816,7 +559,14 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt GUI.changed = false; if (this.BeginSettingsBox(0, EditorGUIUtility.TextContent("PlayerSettings.ResolutionHeader"))) { - if (targetGroup == BuildTargetGroup.Standalone) + if (settingsExtension != null) + { + float h = 16f; + float midWidth = 80f + EditorGUIUtility.fieldWidth + 5f; + float maxWidth = 80f + EditorGUIUtility.fieldWidth + 5f; + settingsExtension.ResolutionSectionGUI(h, midWidth, maxWidth); + } + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.SamsungTV) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ResolutionSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_DefaultIsFullScreen, new GUILayoutOption[0]); @@ -825,42 +575,63 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt { EditorGUILayout.PropertyField(this.m_DefaultIsNativeResolution, new GUILayoutOption[0]); } - EditorGUILayout.EndFadeGroup(); + if (this.m_ShowDefaultIsNativeResolution.faded != 0f && this.m_ShowDefaultIsNativeResolution.faded != 1f) + { + EditorGUILayout.EndFadeGroup(); + } this.m_ShowResolution.target = (!this.m_DefaultIsFullScreen.boolValue || !this.m_DefaultIsNativeResolution.boolValue); if (EditorGUILayout.BeginFadeGroup(this.m_ShowResolution.faded)) { + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_DefaultScreenWidth, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenWidth"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && this.m_DefaultScreenWidth.intValue < 1) + { + this.m_DefaultScreenWidth.intValue = 1; + } + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_DefaultScreenHeight, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenHeight"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && this.m_DefaultScreenHeight.intValue < 1) + { + this.m_DefaultScreenHeight.intValue = 1; + } + } + if (this.m_ShowResolution.faded != 0f && this.m_ShowResolution.faded != 1f) + { + EditorGUILayout.EndFadeGroup(); } - EditorGUILayout.EndFadeGroup(); } - if (targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.FlashPlayer || targetGroup == BuildTargetGroup.NaCl) + if (targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.WebGL) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ResolutionSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_DefaultScreenWidthWeb, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenWidthWeb"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && this.m_DefaultScreenWidthWeb.intValue < 1) + { + this.m_DefaultScreenWidthWeb.intValue = 1; + } + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_DefaultScreenHeightWeb, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenHeightWeb"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck() && this.m_DefaultScreenHeightWeb.intValue < 1) + { + this.m_DefaultScreenHeightWeb.intValue = 1; + } } if (targetGroup == BuildTargetGroup.XBOX360) { this.ShowNoSettings(); EditorGUILayout.Space(); } - if (targetGroup == BuildTargetGroup.Metro) - { - this.ShowNoSettings(); - EditorGUILayout.Space(); - } - if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.BB10) + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.BlackBerry || targetGroup == BuildTargetGroup.WebGL) { EditorGUILayout.PropertyField(this.m_RunInBackground, EditorGUIUtility.TextContent("PlayerSettings.RunInBackground"), new GUILayoutOption[0]); } - if (targetGroup == BuildTargetGroup.iPhone || (settingsExtension != null && settingsExtension.SupportsOrientation()) || targetGroup == BuildTargetGroup.WP8) + if ((settingsExtension != null && settingsExtension.SupportsOrientation()) || PlayerSettingsEditor.IsWP8Player(targetGroup)) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ScreenOrientationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_DefaultScreenOrientation, EditorGUIUtility.TextContent("PlayerSettings.DefaultScreenOrientation"), new GUILayoutOption[0]); if (this.m_DefaultScreenOrientation.enumValueIndex == 4) { - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_UseOSAutoRotation, EditorGUIUtility.TextContent("PlayerSettings.UseOSAutorotation"), new GUILayoutOption[0]); } @@ -878,14 +649,14 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt EditorGUI.indentLevel--; } } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android) { if (targetGroup != BuildTargetGroup.WP8) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.StatusBarSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_UIStatusBarHidden, EditorGUIUtility.TextContent("PlayerSettings.UIStatusBarHidden"), new GUILayoutOption[0]); } - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_UIStatusBarStyle, EditorGUIUtility.TextContent("PlayerSettings.UIStatusBarStyle"), new GUILayoutOption[0]); EditorGUILayout.Space(); @@ -901,17 +672,17 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt EditorGUILayout.PropertyField(this.m_ResizableWindow, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_UseMacAppStoreValidation, EditorGUIUtility.TempContent("Mac App Store Validation"), new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_MacFullscreenMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_D3D9FullscreenMode, EditorGUIUtility.TempContent("D3D9 Fullscreen Mode"), new GUILayoutOption[0]); bool useDirect3D = PlayerSettings.useDirect3D11; - bool flag = this.m_D3D9FullscreenMode.intValue == 0; - if (useDirect3D) - { - this.m_D3D9FullscreenMode.intValue = 1; - } + bool flag = true; EditorGUI.BeginDisabledGroup(useDirect3D); - EditorGUILayout.PropertyField(this.m_D3D9FullscreenMode, EditorGUIUtility.TempContent("D3D9 Fullscreen Mode"), new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!useDirect3D); - EditorGUILayout.PropertyField(this.m_D3D11ForceExclusiveMode, new GUIContent("D3D11 Force Exclusive Mode", "Only recommended to fix Oculus vsync. There are known issues with alt-tab."), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_D3D11FullscreenMode, EditorGUIUtility.TempContent("D3D11 Fullscreen Mode"), new GUILayoutOption[0]); + if (PlayerSettings.d3d11FullscreenMode == D3D11FullscreenMode.ExclusiveMode) + { + EditorGUILayout.HelpBox(EditorGUIUtility.TextContent("PlayerSettings.DX11ExclusiveFullscreenWarning").text, MessageType.Info); + } EditorGUI.EndDisabledGroup(); if (!useDirect3D && flag) { @@ -927,55 +698,18 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt if (targetGroup == BuildTargetGroup.WebPlayer) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WebPlayerTemplateSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); - if (PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length < 1) - { - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.NoTemplatesFound"), new GUILayoutOption[0]); - } - else - { - int num = Mathf.Min((int)Mathf.Max(((float)Screen.width - 30f) / 80f, 1f), PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length); - int num2 = Mathf.Max((int)Mathf.Ceil((float)PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails.Length / (float)num), 1); - bool changed = GUI.changed; - this.m_WebPlayerTemplate.stringValue = PlayerSettingsEditor.WebPlayerTemplate.Templates[PlayerSettingsEditor.ThumbnailList(GUILayoutUtility.GetRect((float)num * 80f, (float)num2 * 100f, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - }), PlayerSettingsEditor.WebPlayerTemplate.GetTemplateIndex(this.m_WebPlayerTemplate.stringValue), PlayerSettingsEditor.WebPlayerTemplate.TemplateGUIThumbnails, num)].ToString(); - bool flag2 = !changed && GUI.changed; - bool changed2 = GUI.changed; - GUI.changed = false; - string[] templateCustomKeys = PlayerSettings.templateCustomKeys; - for (int i = 0; i < templateCustomKeys.Length; i++) - { - string text = templateCustomKeys[i]; - string text2 = PlayerSettings.GetTemplateCustomValue(text); - text2 = EditorGUILayout.TextField(PlayerSettingsEditor.PrettyTemplateKeyName(text), text2, new GUILayoutOption[0]); - PlayerSettings.SetTemplateCustomValue(text, text2); - } - if (GUI.changed) - { - base.serializedObject.Update(); - } - GUI.changed |= changed2; - if (flag2) - { - GUIUtility.hotControl = 0; - GUIUtility.keyboardControl = 0; - base.serializedObject.ApplyModifiedProperties(); - PlayerSettings.templateCustomKeys = PlayerSettingsEditor.WebPlayerTemplate.Templates[PlayerSettingsEditor.WebPlayerTemplate.GetTemplateIndex(this.m_WebPlayerTemplate.stringValue)].CustomKeys; - base.serializedObject.Update(); - } - } + this.m_WebPlayerTemplateManager.SelectionUI(this.m_WebPlayerTemplate); EditorGUILayout.Space(); } if (this.IsMobileTarget(targetGroup)) { - if (targetGroup != BuildTargetGroup.Tizen) + if (targetGroup != BuildTargetGroup.Tizen && targetGroup != BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_Use32BitDisplayBuffer, EditorGUIUtility.TextContent("PlayerSettings.Use32BitDisplayBuffer"), new GUILayoutOption[0]); } - EditorGUILayout.PropertyField(this.m_Use24BitDepthBuffer, EditorGUIUtility.TextContent("PlayerSettings.Use24BitDepthBuffer"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DisableDepthAndStencilBuffers, EditorGUIUtility.TextContent("PlayerSettings.DisableDepthAndStencilBuffers"), new GUILayoutOption[0]); } - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_iosShowActivityIndicatorOnLoading, EditorGUIUtility.TextContent("PlayerSettings.iosShowActivityIndicatorOnLoading"), new GUILayoutOption[0]); } @@ -983,7 +717,7 @@ public void ResolutionSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExt { EditorGUILayout.PropertyField(this.m_androidShowActivityIndicatorOnLoading, EditorGUIUtility.TextContent("PlayerSettings.androidShowActivityIndicatorOnLoading"), new GUILayoutOption[0]); } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android) + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android) { EditorGUILayout.Space(); } @@ -1050,6 +784,26 @@ private void DX11SettingGUI(BuildTargetGroup targetGroup) } } } + public void DebugAndCrashReportingGUI(BuildPlayerWindow.BuildPlatform platform, BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) + { + if (targetGroup != BuildTargetGroup.iOS) + { + return; + } + GUI.changed = false; + if (this.BeginSettingsBox(3, EditorGUIUtility.TextContent("PlayerSettings.DebugAndCrashReportingHeader"))) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.DebugSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_EnableInternalProfiler, EditorGUIUtility.TextContent("PlayerSettings.EnableInternalProfiler"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.CrashReportingSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ActionOnDotNetUnhandledException, EditorGUIUtility.TextContent("PlayerSettings.ActionOnDotNetUnhandledException"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LogObjCUncaughtExceptions, EditorGUIUtility.TextContent("PlayerSettings.LogObjCUncaughtExceptions"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_EnableCrashReportAPI, EditorGUIUtility.TextContent("PlayerSettings.EnableCrashReportAPI"), new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + this.EndSettingsBox(); + } public static void BuildDisabledEnumPopup(GUIContent selected, string uiString) { EditorGUI.BeginDisabledGroup(true); @@ -1082,13 +836,13 @@ public static int BuildEnumPopup(int value, string uiString, string textPrefi public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) { GUI.changed = false; - if (this.BeginSettingsBox(3, EditorGUIUtility.TextContent("PlayerSettings.OtherHeader"))) + if (this.BeginSettingsBox(4, EditorGUIUtility.TextContent("PlayerSettings.OtherHeader"))) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.RenderingSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); - if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || this.IsMobileTarget(targetGroup)) + if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || this.IsMobileTarget(targetGroup) || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.PS4) { bool flag = this.IsMobileTarget(targetGroup); - EditorGUILayout.PropertyField((!flag) ? this.m_RenderingPath : this.m_MobileRenderingPath, EditorGUIUtility.TextContent("PlayerSettings.RenderingPath"), new GUILayoutOption[0]); + EditorGUILayout.IntPopup((!flag) ? this.m_RenderingPath : this.m_MobileRenderingPath, PlayerSettingsEditor.kRenderPaths, PlayerSettingsEditor.kRenderPathValues, EditorGUIUtility.TextContent("PlayerSettings.RenderingPath"), new GUILayoutOption[0]); } if (targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer) { @@ -1099,15 +853,17 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge } EditorGUILayout.EndFadeGroup(); } - if ((targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.XBOX360) && InternalEditorUtility.HasPro()) + if ((targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PS4 || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.XBOX360) && InternalEditorUtility.HasProFeaturesEnabled()) { + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); EditorGUILayout.PropertyField(this.m_ActiveColorSpace, EditorGUIUtility.TextContent("PlayerSettings.ActiveColorSpace"), new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); if (QualitySettings.activeColorSpace != QualitySettings.desiredColorSpace) { EditorGUILayout.HelpBox(PlayerSettingsEditor.s_Styles.colorSpaceWarning.text, MessageType.Warning); } } - if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.Android) + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.SamsungTV) { if (this.IsMobileTarget(targetGroup)) { @@ -1118,6 +874,20 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge this.m_MTRendering.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.MultithreadedRendering"), this.m_MTRendering.boolValue, new GUILayoutOption[0]); } } + else + { + if (targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM) + { + if (Unsupported.IsDeveloperBuild()) + { + this.m_MTRendering.boolValue = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.MultithreadedRendering"), this.m_MTRendering.boolValue, new GUILayoutOption[0]); + } + else + { + this.m_MTRendering.boolValue = true; + } + } + } this.DX11SettingGUI(targetGroup); bool flag2 = targetGroup != BuildTargetGroup.PS3; bool flag3 = targetGroup != BuildTargetGroup.PS3 && targetGroup != BuildTargetGroup.XBOX360; @@ -1158,14 +928,14 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge Undo.RecordObject(this.target, "Changed Batching Settings"); PlayerSettings.SetBatchingForPlatform(platform.DefaultTarget, num, num2); } - if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Metro) + if (targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.Standalone || targetGroup == BuildTargetGroup.WebPlayer || targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PS4 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.Metro) { bool flag5 = InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(platform.DefaultTarget); EditorGUI.BeginDisabledGroup(!flag5); if (GUI.enabled) { EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(this.m_SkinOnGPU, EditorGUIUtility.TextContent("PlayerSettings.GPUSkinning"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SkinOnGPU, EditorGUIUtility.TextContent((targetGroup == BuildTargetGroup.PS4) ? "PlayerSettings.ComputeSkinning" : "PlayerSettings.GPUSkinning"), new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) { ShaderUtil.RecreateSkinnedMeshResources(); @@ -1205,106 +975,107 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge EditorGUILayout.PropertyField(this.m_FirstStreamedLevelWithResources, EditorGUIUtility.TextContent("PlayerSettings.FirstStreamedLevelWithResources"), new GUILayoutOption[0]); EditorGUILayout.Space(); } - if (targetGroup == BuildTargetGroup.iPhone || (settingsExtension != null && settingsExtension.HasIdentificationGUI())) + if (settingsExtension != null && settingsExtension.HasIdentificationGUI()) { GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.IdentificationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_IPhoneBundleIdentifier, EditorGUIUtility.TextContent("PlayerSettings.IPhoneBundleIdentifier"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_IPhoneBundleVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneBundleVersion"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_IPhoneShortBundleVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneShortBundleVersion"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ApplicationBundleIdentifier, EditorGUIUtility.TextContent("PlayerSettings.bundleIdentifier"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ApplicationBundleVersion, EditorGUIUtility.TextContent("PlayerSettings.bundleVersion"), new GUILayoutOption[0]); if (settingsExtension != null) { settingsExtension.IdentificationSectionGUI(); } EditorGUILayout.Space(); } - if (targetGroup != BuildTargetGroup.FlashPlayer) + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ConfigurationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); + string targetStringFromBuildTargetGroup = ModuleManager.GetTargetStringFromBuildTargetGroup(targetGroup); + IScriptingImplementations scriptingImplementations = ModuleManager.GetScriptingImplementations(targetStringFromBuildTargetGroup); + if (scriptingImplementations == null) + { + PlayerSettingsEditor.BuildDisabledEnumPopup(EditorGUIUtility.TextContent("PlayerSettings.ScriptingBackend.Default"), "PlayerSettings.ScriptingBackend"); + } + else { - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ConfigurationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); - if (targetGroup == BuildTargetGroup.iPhone) + ScriptingImplementation[] enabled = scriptingImplementations.Enabled; + int propertyInt = PlayerSettings.GetPropertyInt("ScriptingBackend", targetGroup); + int num3 = PlayerSettingsEditor.BuildEnumPopup(propertyInt, "PlayerSettings.ScriptingBackend", "PlayerSettings.ScriptingBackend", enabled); + if (num3 != propertyInt) { - ScriptingImplementation[] options = new ScriptingImplementation[] - { - ScriptingImplementation.Mono2x, - ScriptingImplementation.IL2CPP - }; - iPhoneArchitecture[] options2 = new iPhoneArchitecture[] - { - iPhoneArchitecture.ARMv7, - iPhoneArchitecture.ARM64, - iPhoneArchitecture.Universal - }; - int num3 = 0; - PlayerSettings.GetPropertyOptionalInt("ScriptingBackend", ref num3, targetGroup); - int num4 = PlayerSettingsEditor.BuildEnumPopup(num3, "PlayerSettings.ScriptingBackend", "PlayerSettings.ScriptingBackend", options); - if (num4 != num3) - { - PlayerSettings.SetPropertyInt("ScriptingBackend", num4, targetGroup); - } - int propertyInt = PlayerSettings.GetPropertyInt("Architecture", targetGroup); - int num5; - if (num3 == 1) - { - num5 = PlayerSettingsEditor.BuildEnumPopup(propertyInt, "PlayerSettings.iOS.Architecture", null, options2); - } - else - { - num5 = 0; - PlayerSettingsEditor.BuildDisabledEnumPopup(new GUIContent("ARMv7"), "PlayerSettings.iOS.Architecture"); - } - if (num5 != propertyInt) - { - PlayerSettings.SetPropertyInt("Architecture", num5, targetGroup); - } + PlayerSettings.SetPropertyInt("ScriptingBackend", num3, targetGroup); } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.WP8) + if (enabled.Any((ScriptingImplementation backend) => backend == ScriptingImplementation.IL2CPP)) { - if (targetGroup == BuildTargetGroup.iPhone) - { - EditorGUILayout.PropertyField(this.m_TargetDevice, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_TargetResolution, EditorGUIUtility.TextContent("PlayerSettings.TargetResolution"), new GUILayoutOption[0]); - } - if (targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10) + bool flag6 = false; + PlayerSettings.GetPropertyOptionalBool("UseIl2CppPrecompiledHeader", ref flag6, targetGroup); + bool flag7 = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.UseIl2CppPrecompiledHeader"), flag6, new GUILayoutOption[0]); + if (flag7 != flag6) { - EditorGUILayout.PropertyField(this.m_TargetGlesGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetGlesGraphics"), new GUILayoutOption[0]); + PlayerSettings.SetPropertyBool("UseIl2CppPrecompiledHeader", flag7, targetGroup); } - else - { - if (targetGroup == BuildTargetGroup.iPhone) - { - EditorGUILayout.PropertyField(this.m_TargetIOSGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetIOSGraphics"), new GUILayoutOption[0]); - } - } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.WP8) - { - EditorGUILayout.PropertyField(this.m_AccelerometerFrequency, EditorGUIUtility.TextContent("PlayerSettings.AccelerometerFrequency"), new GUILayoutOption[0]); - } - if (targetGroup == BuildTargetGroup.iPhone) + } + } + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.Metro || targetGroup == BuildTargetGroup.BlackBerry || PlayerSettingsEditor.IsWP8Player(targetGroup)) + { + if (targetGroup == BuildTargetGroup.iOS) + { + EditorGUILayout.PropertyField(this.m_TargetDevice, new GUILayoutOption[0]); + if ((this.m_TargetDevice.intValue == 1 || this.m_TargetDevice.intValue == 2) && this.m_IPhoneTargetOSVersion.intValue <= 6) { - EditorGUILayout.PropertyField(this.m_LocationUsageDescription, EditorGUIUtility.TextContent("PlayerSettings.IOSLocationUsageDescription"), new GUILayoutOption[0]); + this.m_IPhoneTargetOSVersion.intValue = 7; } - if (targetGroup == BuildTargetGroup.iPhone) + EditorGUILayout.PropertyField(this.m_TargetResolution, EditorGUIUtility.TextContent("PlayerSettings.TargetResolution"), new GUILayoutOption[0]); + } + if (targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BlackBerry) + { + EditorGUILayout.PropertyField(this.m_TargetGlesGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetGlesGraphics"), new GUILayoutOption[0]); + } + else + { + if (targetGroup == BuildTargetGroup.iOS) { - EditorGUILayout.PropertyField(this.m_OverrideIPodMusic, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_PrepareIOSForRecording, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_UIRequiresPersistentWiFi, EditorGUIUtility.TextContent("PlayerSettings.UIRequiresPersistentWiFi"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_UIExitOnSuspend, EditorGUIUtility.TextContent("PlayerSettings.UIExitOnSuspend"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_EnableHWStatistics, EditorGUIUtility.TextContent("PlayerSettings.enableHWStatistics"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_TargetIOSGraphics, EditorGUIUtility.TextContent("PlayerSettings.TargetIOSGraphics"), new GUILayoutOption[0]); } } - if (settingsExtension != null) + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Metro || PlayerSettingsEditor.IsWP8Player(targetGroup)) { - settingsExtension.ConfigurationSectionGUI(); + EditorGUILayout.PropertyField(this.m_AccelerometerFrequency, EditorGUIUtility.TextContent("PlayerSettings.AccelerometerFrequency"), new GUILayoutOption[0]); } - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.scriptingDefineSymbols"), new GUILayoutOption[0]); - EditorGUI.BeginChangeCheck(); - string defines = EditorGUILayout.DelayedTextField(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup), null, EditorStyles.textField, new GUILayoutOption[0]); - this.scriptingDefinesControlID = EditorGUIUtility.s_LastControlID; - if (EditorGUI.EndChangeCheck()) + if (targetGroup == BuildTargetGroup.iOS) { - PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines); + EditorGUILayout.PropertyField(this.m_LocationUsageDescription, EditorGUIUtility.TextContent("PlayerSettings.IOSLocationUsageDescription"), new GUILayoutOption[0]); } - EditorGUILayout.Space(); + if (targetGroup == BuildTargetGroup.iOS) + { + EditorGUILayout.PropertyField(this.m_OverrideIPodMusic, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PrepareIOSForRecording, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UIRequiresPersistentWiFi, EditorGUIUtility.TextContent("PlayerSettings.UIRequiresPersistentWiFi"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IOSAppInBackgroundBehavior, EditorGUIUtility.TextContent("PlayerSettings.iosAppInBackgroundBehavior"), new GUILayoutOption[0]); + } + } + EditorGUI.BeginDisabledGroup(!Application.HasProLicense()); + bool flag8 = !this.m_SubmitAnalytics.boolValue; + bool flag9 = EditorGUILayout.Toggle(EditorGUIUtility.TextContent("PlayerSettings.submitAnalytics"), flag8, new GUILayoutOption[0]); + if (flag8 != flag9) + { + this.m_SubmitAnalytics.boolValue = !flag9; + } + if (!Application.HasProLicense()) + { + this.m_SubmitAnalytics.boolValue = true; + } + EditorGUI.EndDisabledGroup(); + if (settingsExtension != null) + { + settingsExtension.ConfigurationSectionGUI(); + } + EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.scriptingDefineSymbols"), new GUILayoutOption[0]); + EditorGUI.BeginChangeCheck(); + string defines = EditorGUILayout.DelayedTextField(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup), null, EditorStyles.textField, new GUILayoutOption[0]); + this.scriptingDefinesControlID = EditorGUIUtility.s_LastControlID; + if (EditorGUI.EndChangeCheck()) + { + PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines); } + EditorGUILayout.Space(); GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.OptimizationSubHeader"), EditorStyles.boldLabel, new GUILayoutOption[0]); if (targetGroup == BuildTargetGroup.WebPlayer) { @@ -1312,32 +1083,23 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge } else { - if (targetGroup == BuildTargetGroup.FlashPlayer) - { - this.ShowDisabledFakeEnumPopup(PlayerSettingsEditor.FakeEnum.FlashPlayerSubset); - EditorGUILayout.PropertyField(this.m_FlashStrippingLevel, EditorGUIUtility.TextContent("PlayerSettings.flashStrippingLevel"), new GUILayoutOption[0]); - } - else + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_ApiCompatibilityLevel, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) { - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(this.m_ApiCompatibilityLevel, new GUILayoutOption[0]); - if (EditorGUI.EndChangeCheck()) - { - PlayerSettings.SetApiCompatibilityInternal(this.m_ApiCompatibilityLevel.intValue); - } + PlayerSettings.SetApiCompatibilityInternal(this.m_ApiCompatibilityLevel.intValue); } } - if (targetGroup == BuildTargetGroup.NaCl || targetGroup == BuildTargetGroup.FlashPlayer) - { - EditorGUILayout.PropertyField(this.m_StripPhysics, EditorGUIUtility.TextContent("PlayerSettings.StripPhysics"), new GUILayoutOption[0]); - } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2) + EditorGUILayout.PropertyField(this.m_BakeCollisionMeshes, EditorGUIUtility.TextContent("PlayerSettings.BakeCollisionMeshes"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PreloadShaders, EditorGUIUtility.TextContent("PlayerSettings.PreloadShaders"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_PreloadedAssets, EditorGUIUtility.TextContent("PlayerSettings.PreloadedAssets"), true, new GUILayoutOption[0]); + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PS4 || targetGroup == BuildTargetGroup.PSP2) { EditorGUILayout.PropertyField(this.m_AotOptions, EditorGUIUtility.TextContent("PlayerSettings.aotOptions"), new GUILayoutOption[0]); } - if (targetGroup == BuildTargetGroup.iPhone || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BB10 || targetGroup == BuildTargetGroup.Tizen || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne) + if (targetGroup == BuildTargetGroup.iOS || targetGroup == BuildTargetGroup.Android || targetGroup == BuildTargetGroup.BlackBerry || targetGroup == BuildTargetGroup.Tizen || targetGroup == BuildTargetGroup.WebGL || targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PS4 || targetGroup == BuildTargetGroup.XBOX360 || targetGroup == BuildTargetGroup.XboxOne) { - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_IPhoneSdkVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneSdkVersion"), new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_IPhoneTargetOSVersion, EditorGUIUtility.TextContent("PlayerSettings.IPhoneTargetOSVersion"), new GUILayoutOption[0]); @@ -1357,7 +1119,7 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge EditorGUILayout.IntPopup(EditorGUIUtility.TextContent("PlayerSettings.IPhoneStrippingLevel"), 0, displayedOptions, optionValues, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); } - if (targetGroup == BuildTargetGroup.iPhone) + if (targetGroup == BuildTargetGroup.iOS) { EditorGUILayout.PropertyField(this.m_IPhoneScriptCallOptimization, EditorGUIUtility.TextContent("PlayerSettings.IPhoneScriptCallOptimization"), new GUILayoutOption[0]); } @@ -1367,10 +1129,28 @@ public void OtherSectionGUI(BuildPlayerWindow.BuildPlatform platform, BuildTarge } EditorGUILayout.Space(); } - EditorGUILayout.PropertyField(this.m_StripUnusedMeshComponents, EditorGUIUtility.TextContent("PlayerSettings.StripUnusedMeshComponents"), new GUILayoutOption[0]); + if (targetGroup != BuildTargetGroup.PSM) + { + EditorGUILayout.PropertyField(this.m_StripUnusedMeshComponents, EditorGUIUtility.TextContent("PlayerSettings.StripUnusedMeshComponents"), new GUILayoutOption[0]); + } if (targetGroup == BuildTargetGroup.PS3 || targetGroup == BuildTargetGroup.PSP2 || targetGroup == BuildTargetGroup.PSM) { + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_VideoMemoryForVertexBuffers, EditorGUIUtility.TextContent("PlayerSettings.VideoMemoryForVertexBuffers"), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + if (this.m_VideoMemoryForVertexBuffers.intValue < 0) + { + this.m_VideoMemoryForVertexBuffers.intValue = 0; + } + else + { + if (this.m_VideoMemoryForVertexBuffers.intValue > 192) + { + this.m_VideoMemoryForVertexBuffers.intValue = 192; + } + } + } } EditorGUILayout.Space(); this.ShowSharedNote(); @@ -1388,25 +1168,67 @@ private void AutoAssignProperty(SerializedProperty property, string packageDir, } } } - private void ShowBrowseableProperty(SerializedProperty property, string textContent, string extension, string dir, float kLabelFloatMinW, float kLabelFloatMaxW, float h) + public void BrowseablePathProperty(string propertyLabel, SerializedProperty property, string browsePanelTitle, string extension, string dir) { - bool flag = textContent.Length != 0; - if (flag) + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(EditorGUIUtility.TextContent(propertyLabel)); + GUIContent content = new GUIContent("..."); + Vector2 vector = GUI.skin.GetStyle("Button").CalcSize(content); + if (GUILayout.Button(content, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.MaxWidth(vector.x) + })) { - GUILayout.Label(EditorGUIUtility.TextContent(textContent), EditorStyles.boldLabel, new GUILayoutOption[0]); + GUI.FocusControl(string.Empty); + string text = EditorGUIUtility.TextContent(browsePanelTitle).text; + string text2 = (!string.IsNullOrEmpty(dir)) ? (dir.Replace('\\', '/') + "/") : (Directory.GetCurrentDirectory().Replace('\\', '/') + "/"); + string text3 = string.Empty; + if (string.IsNullOrEmpty(extension)) + { + text3 = EditorUtility.OpenFolderPanel(text, text2, string.Empty); + } + else + { + text3 = EditorUtility.OpenFilePanel(text, text2, extension); + } + if (text3.StartsWith(text2)) + { + text3 = text3.Substring(text2.Length); + } + if (!string.IsNullOrEmpty(text3)) + { + property.stringValue = text3; + base.serializedObject.ApplyModifiedProperties(); + GUIUtility.ExitGUI(); + } } - Rect rect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, h, h, EditorStyles.layerMaskField, null); - float labelWidth = EditorGUIUtility.labelWidth; - Rect position = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth - EditorGUI.indent, rect.height); - Rect position2 = new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, rect.height); - string text = (property.stringValue.Length != 0) ? property.stringValue : "Not selected."; - EditorGUI.TextArea(position2, text, EditorStyles.label); - if (GUI.Button(position, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) + GUIContent gUIContent; + if (string.IsNullOrEmpty(property.stringValue)) + { + gUIContent = EditorGUIUtility.TextContent("Not selected."); + EditorGUI.BeginDisabledGroup(true); + } + else { - property.stringValue = FileUtil.GetLastPathNameComponent(EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, dir, extension)); + gUIContent = EditorGUIUtility.TempContent(property.stringValue); + EditorGUI.BeginDisabledGroup(false); + } + EditorGUI.BeginChangeCheck(); + GUILayoutOption[] options = new GUILayoutOption[] + { + GUILayout.Width(32f), + GUILayout.ExpandWidth(true) + }; + string value = EditorGUILayout.TextArea(gUIContent.text, options); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck() && string.IsNullOrEmpty(value)) + { + property.stringValue = string.Empty; base.serializedObject.ApplyModifiedProperties(); + GUI.FocusControl(string.Empty); GUIUtility.ExitGUI(); } + EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } internal static void BuildFileBoxButton(SerializedProperty prop, string uiString, string directory, string ext) @@ -1439,165 +1261,20 @@ internal static void BuildFileBoxButton(SerializedProperty prop, string uiString } public void PublishSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) { - if (targetGroup != BuildTargetGroup.Metro && targetGroup != BuildTargetGroup.WP8 && targetGroup != BuildTargetGroup.XBOX360 && targetGroup != BuildTargetGroup.PS3 && targetGroup != BuildTargetGroup.PSP2 && targetGroup != BuildTargetGroup.PSM && (settingsExtension == null || !settingsExtension.HasPublishSection())) + if (targetGroup != BuildTargetGroup.Metro && targetGroup != BuildTargetGroup.XBOX360 && targetGroup != BuildTargetGroup.PS3 && targetGroup != BuildTargetGroup.PSP2 && targetGroup != BuildTargetGroup.PSM && (settingsExtension == null || !settingsExtension.HasPublishSection())) { return; } GUI.changed = false; - if (this.BeginSettingsBox(4, EditorGUIUtility.TextContent("PlayerSettings.PublishingHeader"))) + if (this.BeginSettingsBox(5, EditorGUIUtility.TextContent("PlayerSettings.PublishingHeader"))) { - string text = "Assets"; string directory = FileUtil.DeleteLastPathNameComponent(Application.dataPath); - float num = 16f; - float num2 = 80f + EditorGUIUtility.fieldWidth + 5f; - float num3 = 80f + EditorGUIUtility.fieldWidth + 5f; + float h = 16f; + float midWidth = 80f + EditorGUIUtility.fieldWidth + 5f; + float maxWidth = 80f + EditorGUIUtility.fieldWidth + 5f; if (settingsExtension != null) { - settingsExtension.PublishSectionGUI(num, num2, num3); - } - if (targetGroup == BuildTargetGroup.Metro) - { - this.PublishSectionGUIMetro(num2, num3, num, num); - } - if (targetGroup == BuildTargetGroup.WP8) - { - this.PublishSectionGUIWP8(num2, num3, num, num); - } - if (targetGroup == BuildTargetGroup.PS3) - { - string text2 = Path.Combine(Application.dataPath, "PS3 Submission Package"); - if (Directory.Exists(text2)) - { - this.AutoAssignProperty(this.m_PS3TitleConfigPath, text2, "TITLECONFIG.XML"); - this.AutoAssignProperty(this.m_PS3DLCConfigPath, text2, "DLCconfig.txt"); - this.AutoAssignProperty(this.m_PS3ThumbnailPath, text2, "ICON0.PNG"); - this.AutoAssignProperty(this.m_PS3BackgroundPath, text2, "BACKGROUND0.PNG"); - this.AutoAssignProperty(this.m_PS3TrophyPackagePath, text2, "TROPHY.TRP"); - this.AutoAssignProperty(this.m_PS3SoundPath, text2, "SDN0.AT3"); - } - else - { - text2 = text; - } - this.ShowBrowseableProperty(this.m_PS3TitleConfigPath, "PlayerSettings.ps3TitleConfigPath", "xml", text2, num2, num3, num); - this.ShowBrowseableProperty(this.m_PS3DLCConfigPath, "PlayerSettings.ps3DLCConfigPath", "txt", text2, num2, num3, num); - this.ShowBrowseableProperty(this.m_PS3ThumbnailPath, "PlayerSettings.ps3ThumbnailPath", "png", text2, num2, num3, num); - this.ShowBrowseableProperty(this.m_PS3BackgroundPath, "PlayerSettings.ps3BackgroundPath", "png", text2, num2, num3, num); - this.ShowBrowseableProperty(this.m_PS3SoundPath, "PlayerSettings.ps3SoundPath", "at3", text2, num2, num3, num); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyPackagePath"), EditorStyles.boldLabel, new GUILayoutOption[0]); - this.ShowBrowseableProperty(this.m_PS3TrophyPackagePath, string.Empty, "trp", text2, num2, num3, num); - EditorGUILayout.PropertyField(this.m_PS3TrophyCommId, EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyCommId"), new GUILayoutOption[0]); - this.m_PS3NpCommunicationPassphrase.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.ps3NpCommunicationPassphrase"), this.m_PS3NpCommunicationPassphrase.stringValue, new GUILayoutOption[] - { - GUILayout.Height(280f) - }); - this.m_PS3TrophyCommSig.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.ps3TrophyCommSig"), this.m_PS3TrophyCommSig.stringValue, new GUILayoutOption[] - { - GUILayout.Height(280f) - }); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.ps3TitleSettings"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_PS3TrialMode, EditorGUIUtility.TextContent("PlayerSettings.ps3TrialMode"), new GUILayoutOption[0]); - this.m_PS3BootCheckMaxSaveGameSizeKB.intValue = EditorGUILayout.IntField(EditorGUIUtility.TextContent("PlayerSettings.ps3BootCheckMaxSaveGameSizeKB"), this.m_PS3BootCheckMaxSaveGameSizeKB.intValue, new GUILayoutOption[0]); - this.m_PS3SaveGameSlots.intValue = EditorGUILayout.IntField(EditorGUIUtility.TextContent("PlayerSettings.ps3SaveGameSlots"), this.m_PS3SaveGameSlots.intValue, new GUILayoutOption[0]); - } - if (targetGroup == BuildTargetGroup.PSP2) - { - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveArea"), EditorStyles.boldLabel, new GUILayoutOption[0]); - this.m_PSP2LiveAreaBackground.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveAreaBackround"), (Texture2D)this.m_PSP2LiveAreaBackground.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); - this.m_PSP2LiveAreaGate.objectReferenceValue = EditorGUILayout.ObjectField(EditorGUIUtility.TextContent("PlayerSettings.psp2LiveAreaGate"), (Texture2D)this.m_PSP2LiveAreaGate.objectReferenceValue, typeof(Texture2D), false, new GUILayoutOption[0]); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2NP"), EditorStyles.boldLabel, new GUILayoutOption[0]); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2NPTrophyPath"), new GUILayoutOption[0]); - Rect rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); - GUIContent gUIContent; - if (this.m_PSP2TrophyPackPath.stringValue.Length == 0) - { - gUIContent = EditorGUIUtility.TextContent("Not selected."); - EditorGUI.BeginDisabledGroup(true); - } - else - { - gUIContent = EditorGUIUtility.TempContent(this.m_PSP2TrophyPackPath.stringValue); - EditorGUI.BeginDisabledGroup(false); - } - float labelWidth = EditorGUIUtility.labelWidth; - Rect position = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth - EditorGUI.indent, rect.height); - Rect position2 = new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, rect.height); - EditorGUI.TextArea(position2, gUIContent.text, EditorStyles.label); - EditorGUI.EndDisabledGroup(); - if (GUI.Button(position, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) - { - string text3 = Directory.GetCurrentDirectory().Replace('\\', '/'); - this.m_PSP2TrophyPackPath.stringValue = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, text3, "trp"); - text3 += "/"; - if (this.m_PSP2TrophyPackPath.stringValue.StartsWith(text3)) - { - this.m_PSP2TrophyPackPath.stringValue = this.m_PSP2TrophyPackPath.stringValue.Substring(text3.Length); - } - base.serializedObject.ApplyModifiedProperties(); - GUIUtility.ExitGUI(); - } - EditorGUILayout.PropertyField(this.m_PSP2NPCommsID, EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsID"), new GUILayoutOption[0]); - this.m_PSP2NPCommsPassphrase.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsPassphrase"), this.m_PSP2NPCommsPassphrase.stringValue, new GUILayoutOption[] - { - GUILayout.Height(280f) - }); - this.m_PSP2NPCommsSig.stringValue = EditorGUILayout.TextField(EditorGUIUtility.TextContent("PlayerSettings.psp2NPCommsSig"), this.m_PSP2NPCommsSig.stringValue, new GUILayoutOption[] - { - GUILayout.Height(280f) - }); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2PackageParams"), EditorStyles.boldLabel, new GUILayoutOption[0]); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.psp2ParamSfxPath"), new GUILayoutOption[0]); - rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); - GUIContent gUIContent2; - if (this.m_PSP2ParamSfxPath.stringValue.Length == 0) - { - gUIContent2 = EditorGUIUtility.TextContent("Not selected."); - EditorGUI.BeginDisabledGroup(true); - } - else - { - gUIContent2 = EditorGUIUtility.TempContent(this.m_PSP2ParamSfxPath.stringValue); - EditorGUI.BeginDisabledGroup(false); - } - float labelWidth2 = EditorGUIUtility.labelWidth; - Rect position3 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth2 - EditorGUI.indent, rect.height); - Rect position4 = new Rect(rect.x + labelWidth2, rect.y, rect.width - labelWidth2, rect.height); - EditorGUI.TextArea(position4, gUIContent2.text, EditorStyles.label); - EditorGUI.EndDisabledGroup(); - if (GUI.Button(position3, EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric"))) - { - string text4 = Directory.GetCurrentDirectory().Replace('\\', '/'); - this.m_PSP2ParamSfxPath.stringValue = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.BrowseGeneric").text, text4, "sfx"); - text4 += "/"; - if (this.m_PSP2ParamSfxPath.stringValue.StartsWith(text4)) - { - this.m_PSP2ParamSfxPath.stringValue = this.m_PSP2ParamSfxPath.stringValue.Substring(text4.Length); - } - base.serializedObject.ApplyModifiedProperties(); - GUIUtility.ExitGUI(); - } - EditorGUILayout.PropertyField(this.m_PSP2PackagePassword, EditorGUIUtility.TextContent("PlayerSettings.psp2PackagePassword"), new GUILayoutOption[0]); - if (this.m_PSP2PackagePassword.stringValue.Length == 0) - { - System.Random random = new System.Random(); - StringBuilder stringBuilder = new StringBuilder(); - string text5 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - for (int i = 0; i < 32; i++) - { - int index = random.Next(text5.Length); - stringBuilder.Append(text5[index]); - } - this.m_PSP2PackagePassword.stringValue = stringBuilder.ToString(); - base.serializedObject.ApplyModifiedProperties(); - } - else - { - if (this.m_PSP2PackagePassword.stringValue.Length != 32) - { - GUIContent content = EditorGUIUtility.TextContent("PlayerSettings.psp2PasswordBadLength"); - GUILayout.Label(content, EditorStyles.miniLabel, new GUILayoutOption[0]); - } - } + settingsExtension.PublishSectionGUI(h, midWidth, maxWidth); } if (targetGroup == BuildTargetGroup.PSM) { @@ -1614,48 +1291,17 @@ public void PublishSectionGUI(BuildTargetGroup targetGroup, ISettingEditorExtens EditorGUILayout.PropertyField(this.m_XboxTitleId, EditorGUIUtility.TextContent("PlayerSettings.XboxTitleId"), new GUILayoutOption[0]); EditorGUILayout.Space(); GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxImageConversion"), EditorStyles.boldLabel, new GUILayoutOption[0]); - Rect rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); - float labelWidth3 = EditorGUIUtility.labelWidth; - Rect position5 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth3 - EditorGUI.indent, rect.height); - Rect position6 = new Rect(rect.x + labelWidth3, rect.y, rect.width - labelWidth3, rect.height); - string text6 = (this.m_XboxImageXexPath.stringValue.Length != 0) ? this.m_XboxImageXexPath.stringValue : "Not selected."; - EditorGUI.TextArea(position6, text6, EditorStyles.label); - if (GUI.Button(position5, EditorGUIUtility.TextContent("PlayerSettings.XboxImageXEXFile"))) - { - string text7 = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.XboxImageXEXFile").text, directory, "cfg"); - this.m_XboxImageXexPath.stringValue = text7; - text7 = FileUtil.GetProjectRelativePath(text7); - if (text7 != string.Empty) - { - this.m_XboxImageXexPath.stringValue = text7; - } - base.serializedObject.ApplyModifiedProperties(); - GUIUtility.ExitGUI(); - } + PlayerSettingsEditor.BuildFileBoxButton(this.m_XboxImageXexPath, "PlayerSettings.XboxImageXEXFile", directory, "cfg", null); EditorGUILayout.Space(); GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.XboxLive"), EditorStyles.boldLabel, new GUILayoutOption[0]); - rect = GUILayoutUtility.GetRect(num2, num3, num, num, EditorStyles.layerMaskField, null); - float labelWidth4 = EditorGUIUtility.labelWidth; - Rect position7 = new Rect(rect.x + EditorGUI.indent, rect.y, labelWidth4 - EditorGUI.indent, rect.height); - Rect position8 = new Rect(rect.x + labelWidth4, rect.y, rect.width - labelWidth4, rect.height); - string text8 = (this.m_XboxSpaPath.stringValue.Length != 0) ? this.m_XboxSpaPath.stringValue : "Not selected."; - EditorGUI.TextArea(position8, text8, EditorStyles.label); - if (GUI.Button(position7, EditorGUIUtility.TextContent("PlayerSettings.XboxSpaFile"))) + Action onSelect = delegate { - string text9 = EditorUtility.OpenFilePanel(EditorGUIUtility.TextContent("PlayerSettings.XboxSpaFile").text, directory, "spa"); - this.m_XboxSpaPath.stringValue = text9; - text9 = FileUtil.GetProjectRelativePath(text9); - if (text9 != string.Empty) - { - this.m_XboxSpaPath.stringValue = text9; - } if (this.m_XboxTitleId.stringValue.Length == 0) { Debug.LogWarning("Title id must be present when using a SPA file."); } - base.serializedObject.ApplyModifiedProperties(); - GUIUtility.ExitGUI(); - } + }; + PlayerSettingsEditor.BuildFileBoxButton(this.m_XboxSpaPath, "PlayerSettings.XboxSpaFile", directory, "spa", onSelect); if (this.m_XboxSpaPath.stringValue.Length > 0) { bool boolValue = this.m_XboxGenerateSpa.boolValue; @@ -1740,571 +1386,5 @@ private static void ShowWarning(GUIContent warningMessage) GUILayout.Label(warningMessage, EditorStyles.wordWrappedMiniLabel, new GUILayoutOption[0]); GUILayout.EndVertical(); } - public void PublishSectionGUIMetro(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) - { - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroPackaging"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroPackageName, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageName"), new GUILayoutOption[0]); - this.m_MetroPackageName.stringValue = this.ValidateMetroPackageName(this.m_MetroPackageName.stringValue); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroPackageDisplayName"), new GUIContent(this.m_ProductName.stringValue), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroPackageVersion, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageVersion"), new GUILayoutOption[0]); - this.m_MetroPackageVersion.stringValue = PlayerSettingsEditor.ValidateMetroPackageVersion(this.m_MetroPackageVersion.stringValue); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroPackagePublisherDisplayName"), new GUIContent(this.m_CompanyName.stringValue), new GUILayoutOption[0]); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificate"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificatePublisher"), new GUIContent(PlayerSettings.Metro.certificateSubject), new GUILayoutOption[0]); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateIssuer"), new GUIContent(PlayerSettings.Metro.certificateIssuer), new GUILayoutOption[0]); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateNotAfter"), new GUIContent((!PlayerSettings.Metro.certificateNotAfter.HasValue) ? null : PlayerSettings.Metro.certificateNotAfter.Value.ToShortDateString()), new GUILayoutOption[0]); - Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); - Rect position = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); - string text = PlayerSettings.Metro.certificatePath; - GUIContent content; - if (string.IsNullOrEmpty(text)) - { - content = EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateSelect"); - } - else - { - content = new GUIContent(FileUtil.GetLastPathNameComponent(text), text); - } - if (GUI.Button(position, content)) - { - text = EditorUtility.OpenFilePanel(null, Application.dataPath, "pfx").Replace('\\', '/'); - string projectRelativePath = FileUtil.GetProjectRelativePath(text); - if (string.IsNullOrEmpty(projectRelativePath) && !string.IsNullOrEmpty(text)) - { - Debug.LogError("Certificate path '" + Path.GetFullPath(text) + "' has to be relative to " + Path.GetFullPath(Application.dataPath + "\\..")); - } - else - { - try - { - if (!PlayerSettings.Metro.SetCertificate(text, null)) - { - MetroCertificatePasswordWindow.Show(text); - } - } - catch (UnityException ex) - { - Debug.LogError(ex.Message); - } - } - } - Rect rect2 = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); - Rect position2 = new Rect(rect2.x + EditorGUIUtility.labelWidth, rect2.y, rect2.width - EditorGUIUtility.labelWidth, rect2.height); - if (GUI.Button(position2, EditorGUIUtility.TextContent("PlayerSettings.MetroCertificateCreate"))) - { - MetroCreateTestCertificateWindow.Show(this.m_CompanyName.stringValue); - } - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroApplication"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.LabelField(EditorGUIUtility.TextContent("PlayerSettings.MetroApplicationDisplayName"), new GUIContent(this.m_ProductName.stringValue), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroApplicationDescription, EditorGUIUtility.TextContent("PlayerSettings.MetroApplicationDescription"), new GUILayoutOption[0]); - this.m_MetroApplicationDescription.stringValue = this.ValidateMetroApplicationDescription(this.m_MetroApplicationDescription.stringValue); - EditorGUILayout.Space(); - GUILayout.Label("Compilation", EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettings.Metro.compilationOverrides = (PlayerSettings.MetroCompilationOverrides)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroCompilationOverrides"), PlayerSettings.Metro.compilationOverrides, new GUILayoutOption[0]); - EditorGUILayout.Space(); - GUILayout.Label("Misc", EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroUnprocessedPlugins, EditorGUIUtility.TextContent("PlayerSettings.MetroUnprocessedPlugins"), true, new GUILayoutOption[0]); - EditorGUILayout.Space(); - EditorGUILayout.PropertyField(this.m_MetroEnableIndependentInputSource, EditorGUIUtility.TextContent("PlayerSettings.MetroEnableIndependentInputSource"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroEnableLowLatencyPresentationAPI, EditorGUIUtility.TextContent("PlayerSettings.MetroEnableLowLatencyPresentationAPI"), new GUILayoutOption[0]); - GUILayout.Label("Capabilities", EditorStyles.boldLabel, new GUILayoutOption[0]); - this.capScrollViewPosition = GUILayout.BeginScrollView(this.capScrollViewPosition, EditorStyles.helpBox, new GUILayoutOption[] - { - GUILayout.MinHeight(200f) - }); - IEnumerator enumerator = Enum.GetValues(typeof(PlayerSettings.MetroCapability)).GetEnumerator(); - try - { - while (enumerator.MoveNext()) - { - PlayerSettings.MetroCapability metroCapability = (PlayerSettings.MetroCapability)((int)enumerator.Current); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - bool enabled = GUILayout.Toggle(PlayerSettings.Metro.GetCapability(metroCapability), metroCapability.ToString(), new GUILayoutOption[] - { - GUILayout.MinWidth(150f) - }); - PlayerSettings.Metro.SetCapability(metroCapability, enabled); - GUILayout.EndHorizontal(); - } - } - finally - { - IDisposable disposable = enumerator as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } - } - GUILayout.EndScrollView(); - } - private static void ImageField(SerializedProperty property, GUIContent label, float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight, int imageWidth, int imageHeight) - { - Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); - Rect position = new Rect(rect.x - EditorGUI.indent, rect.y, EditorGUIUtility.labelWidth - EditorGUI.indent, rect.height); - Rect position2 = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); - EditorGUI.LabelField(position, label); - GUIContent content; - if (string.IsNullOrEmpty(property.stringValue)) - { - content = EditorGUIUtility.TextContent("PlayerSettings.MetroImageSelect"); - } - else - { - content = new GUIContent(FileUtil.GetLastPathNameComponent(property.stringValue), property.stringValue); - } - if (GUI.Button(position2, content)) - { - string text = EditorUtility.OpenFilePanel(null, Application.dataPath, "png").Replace('\\', '/'); - if (string.IsNullOrEmpty(text)) - { - property.stringValue = text; - } - else - { - if (!PlayerSettingsEditor.ValidateImage(text, imageWidth, imageHeight)) - { - property.stringValue = string.Empty; - return; - } - property.stringValue = text; - } - text = FileUtil.GetProjectRelativePath(text); - if (!string.IsNullOrEmpty(text)) - { - property.stringValue = text; - } - } - } - private static bool ValidateImage(string imageFile, int width, int height) - { - Texture2D texture2D = new Texture2D(1, 1); - texture2D.LoadImage(File.ReadAllBytes(imageFile)); - int width2 = texture2D.width; - int height2 = texture2D.height; - UnityEngine.Object.DestroyImmediate(texture2D); - if (width2 != width || height2 != height) - { - Debug.LogError(string.Format("Invalid image size ({0}x{1}), should be {2}x{3}", new object[] - { - width2, - height2, - width, - height - })); - return false; - } - return true; - } - private string ValidateMetroPackageName(string value) - { - if (PlayerSettingsEditor.IsValidMetroPackageName(value)) - { - return value; - } - return this.GetDefaultMetroPackageName(); - } - private static bool IsValidMetroPackageName(string value) - { - if (!PlayerSettingsEditor.metroPackageNameRegex.IsMatch(value)) - { - return false; - } - string text = value.ToUpper(); - if (text != null) - { - if (PlayerSettingsEditor.<>f__switch$map15 == null) - { - PlayerSettingsEditor.<>f__switch$map15 = new Dictionary(22) - { - - { - "CON", - 0 - }, - - { - "PRN", - 0 - }, - - { - "AUX", - 0 - }, - - { - "NUL", - 0 - }, - - { - "COM1", - 0 - }, - - { - "COM2", - 0 - }, - - { - "COM3", - 0 - }, - - { - "COM4", - 0 - }, - - { - "COM5", - 0 - }, - - { - "COM6", - 0 - }, - - { - "COM7", - 0 - }, - - { - "COM8", - 0 - }, - - { - "COM9", - 0 - }, - - { - "LPT1", - 0 - }, - - { - "LPT2", - 0 - }, - - { - "LPT3", - 0 - }, - - { - "LPT4", - 0 - }, - - { - "LPT5", - 0 - }, - - { - "LPT6", - 0 - }, - - { - "LPT7", - 0 - }, - - { - "LPT8", - 0 - }, - - { - "LPT9", - 0 - } - }; - } - int num; - if (PlayerSettingsEditor.<>f__switch$map15.TryGetValue(text, out num)) - { - if (num == 0) - { - return false; - } - } - } - return true; - } - private string GetDefaultMetroPackageName() - { - string text = this.m_ProductName.stringValue; - if (text != null) - { - StringBuilder stringBuilder = new StringBuilder(text.Length); - for (int i = 0; i < text.Length; i++) - { - char c = text[i]; - if (char.IsLetterOrDigit(c) || c == '-') - { - stringBuilder.Append(c); - } - else - { - if (c == '.' && i != text.Length - 1) - { - stringBuilder.Append(c); - } - } - } - text = stringBuilder.ToString(); - } - if (!PlayerSettingsEditor.IsValidMetroPackageName(text)) - { - text = "DefaultPackageName"; - } - return text; - } - internal static string ValidateMetroPackageVersion(string value) - { - if (PlayerSettingsEditor.metroPackageVersionRegex.IsMatch(value)) - { - return value; - } - return "1.0.0.0"; - } - private string ValidateMetroApplicationDescription(string value) - { - if (string.IsNullOrEmpty(value)) - { - return this.m_ProductName.stringValue; - } - return value; - } - private string ValidateMetroTileShortName(string value) - { - if (string.IsNullOrEmpty(value)) - { - value = this.m_ProductName.stringValue; - } - if (value != null && value.Length > 13) - { - return value.Substring(0, 13).TrimEnd(new char[] - { - ' ' - }); - } - return value; - } - private void MetroLogoSection(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) - { - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogo"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 50, 50); - PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 70, 70); - PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 90, 90); - PlayerSettingsEditor.ImageField(this.m_MetroPackageLogo240, EditorGUIUtility.TextContent("PlayerSettings.MetroPackageLogoScale240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 120, 120); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroTileShortName, EditorGUIUtility.TextContent("PlayerSettings.MetroTileShortName"), new GUILayoutOption[0]); - this.m_MetroTileShortName.stringValue = this.ValidateMetroTileShortName(this.m_MetroTileShortName.stringValue); - PlayerSettings.MetroApplicationShowName tileShowName = PlayerSettings.Metro.tileShowName; - if (tileShowName != PlayerSettings.MetroApplicationShowName.NotSet) - { - switch (tileShowName) - { - case PlayerSettings.MetroApplicationShowName.AllLogos: - PlayerSettings.Metro.mediumTileShowName = true; - PlayerSettings.Metro.largeTileShowName = true; - PlayerSettings.Metro.wideTileShowName = true; - break; - case PlayerSettings.MetroApplicationShowName.StandardLogoOnly: - PlayerSettings.Metro.mediumTileShowName = true; - PlayerSettings.Metro.largeTileShowName = true; - break; - case PlayerSettings.MetroApplicationShowName.WideLogoOnly: - PlayerSettings.Metro.wideTileShowName = true; - break; - } - PlayerSettings.Metro.tileShowName = PlayerSettings.MetroApplicationShowName.NotSet; - } - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroTileShowName"), new GUILayoutOption[0]); - PlayerSettings.Metro.mediumTileShowName = GUILayout.Toggle(PlayerSettings.Metro.mediumTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), new GUILayoutOption[0]); - PlayerSettings.Metro.largeTileShowName = GUILayout.Toggle(PlayerSettings.Metro.largeTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroLargeTile"), new GUILayoutOption[0]); - PlayerSettings.Metro.wideTileShowName = GUILayout.Toggle(PlayerSettings.Metro.wideTileShowName, EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), new GUILayoutOption[0]); - PlayerSettings.Metro.tileForegroundText = (PlayerSettings.MetroApplicationForegroundText)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroTileForegroundText"), PlayerSettings.Metro.tileForegroundText, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_MetroTileBackgroundColor, EditorGUIUtility.TextContent("PlayerSettings.MetroTileBackgroundColor"), new GUILayoutOption[0]); - PlayerSettings.Metro.defaultTileSize = (PlayerSettings.MetroDefaultTileSize)EditorGUILayout.EnumPopup(EditorGUIUtility.TextContent("PlayerSettings.MetroDefaultTileSize"), PlayerSettings.Metro.defaultTileSize, new GUILayoutOption[0]); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WindowsTiles"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallLogo"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 24, 24); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 30, 30); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 42, 42); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileSmallLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallLogoScale180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 54, 54); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 120, 120); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 150, 150); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 210, 210); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileLogo180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 270, 270); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 248, 120); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 150); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 210); - PlayerSettingsEditor.ImageField(this.m_MetroStoreTileWideLogo180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreTileWideLogo180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 558, 270); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 56, 56); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 70, 70); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 98, 98); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSmallTile180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSmallTile180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 126, 126); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroLargeTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile80, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile80"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 248, 248); - PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile100"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 310); - PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 434); - PlayerSettingsEditor.ImageField(this.m_MetroStoreLargeTile180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreLargeTile180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 558, 558); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.WindowsPhoneTiles"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroAppIcon"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 44, 44); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 62, 62); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneAppIcon240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneAppIcon240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 106, 106); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroSmallTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 71, 71); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 99, 99); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSmallTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSmallTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 170, 170); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroMediumTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 150, 150); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 210, 210); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneMediumTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneMediumTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 360, 360); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWideTile"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 310, 150); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 434, 210); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneWideTile240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneWideTile240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 744, 360); - EditorGUILayout.Space(); - } - private void MetroSplashScreenSection(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) - { - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWindows"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 620, 300); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage140, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 868, 420); - PlayerSettingsEditor.ImageField(this.m_MetroStoreSplashScreenImage180, EditorGUIUtility.TextContent("PlayerSettings.MetroStoreSplashScreenImage180"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 1116, 540); - EditorGUILayout.Space(); - GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.MetroWindowsPhone"), EditorStyles.boldLabel, new GUILayoutOption[0]); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 480, 800); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage140, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage140"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 672, 1120); - PlayerSettingsEditor.ImageField(this.m_MetroPhoneSplashScreenImage240, EditorGUIUtility.TextContent("PlayerSettings.MetroPhoneSplashScreenImage240"), kLabelMaxWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, 1152, 1920); - EditorGUILayout.Space(); - bool hasValue = PlayerSettings.Metro.splashScreenBackgroundColor.HasValue; - bool flag = EditorGUILayout.BeginToggleGroup(EditorGUIUtility.TextContent("PlayerSettings.MetroSplashScreenOverwriteBackgroundColor"), hasValue); - Rect rect = GUILayoutUtility.GetRect(kLabelMinWidth, kLabelMaxWidth, kLabelMinHeight, kLabelMaxHeight, EditorStyles.layerMaskField); - Rect position = new Rect(rect.x - EditorGUI.indent, rect.y, EditorGUIUtility.labelWidth - EditorGUI.indent, rect.height); - Rect position2 = new Rect(rect.x + EditorGUIUtility.labelWidth, rect.y, rect.width - EditorGUIUtility.labelWidth, rect.height); - EditorGUI.LabelField(position, EditorGUIUtility.TextContent("PlayerSettings.MetroSplashScreenBackgroundColor")); - if (flag != hasValue) - { - if (flag) - { - PlayerSettings.Metro.splashScreenBackgroundColor = new Color?(PlayerSettings.Metro.tileBackgroundColor); - } - else - { - PlayerSettings.Metro.splashScreenBackgroundColor = null; - } - } - if (flag) - { - PlayerSettings.Metro.splashScreenBackgroundColor = new Color?(EditorGUI.ColorField(position2, PlayerSettings.Metro.splashScreenBackgroundColor.Value)); - } - else - { - EditorGUI.ColorField(position2, PlayerSettings.Metro.tileBackgroundColor); - } - EditorGUILayout.EndToggleGroup(); - } - public void PublishSectionGUIWP8(float kLabelMinWidth, float kLabelMaxWidth, float kLabelMinHeight, float kLabelMaxHeight) - { - EditorGUILayout.PropertyField(this.m_WP8UnprocessedPlugins, EditorGUIUtility.TextContent("PlayerSettings.WP8UnprocessedPlugins"), true, new GUILayoutOption[0]); - } - private static string PrettyTemplateKeyName(string name) - { - string[] array = name.Split(new char[] - { - '_' - }); - array[0] = PlayerSettingsEditor.UppercaseFirst(array[0].ToLower()); - for (int i = 1; i < array.Length; i++) - { - array[i] = array[i].ToLower(); - } - return string.Join(" ", array); - } - private static string UppercaseFirst(string target) - { - if (string.IsNullOrEmpty(target)) - { - return string.Empty; - } - return char.ToUpper(target[0]) + target.Substring(1); - } - private static int ThumbnailList(Rect rect, int selection, GUIContent[] thumbnails, int maxRowItems) - { - int num = 0; - int i = 0; - while (i < thumbnails.Length) - { - int num2 = 0; - while (num2 < maxRowItems && i < thumbnails.Length) - { - if (PlayerSettingsEditor.ThumbnailListItem(new Rect(rect.x + (float)num2 * 80f, rect.y + (float)num * 100f, 80f, 100f), i == selection, thumbnails[i])) - { - selection = i; - } - num2++; - i++; - } - num++; - } - return selection; - } - private static bool ThumbnailListItem(Rect rect, bool selected, GUIContent content) - { - EventType type = Event.current.type; - if (type != EventType.MouseDown) - { - if (type == EventType.Repaint) - { - Rect position = new Rect(rect.x + 5f, rect.y + 5f, rect.width - 10f, rect.height - 20f - 10f); - PlayerSettingsEditor.s_Styles.thumbnail.Draw(position, content.image, false, false, selected, selected); - PlayerSettingsEditor.s_Styles.thumbnailLabel.Draw(new Rect(rect.x, rect.y + rect.height - 20f, rect.width, 20f), content.text, false, false, selected, selected); - } - } - else - { - if (rect.Contains(Event.current.mousePosition)) - { - if (!selected) - { - GUI.changed = true; - } - selected = true; - Event.current.Use(); - } - } - return selected; - } } } diff --git a/UnityEditor/UnityEditor/PluginImporter.cs b/UnityEditor/UnityEditor/PluginImporter.cs new file mode 100644 index 00000000..a4d550dc --- /dev/null +++ b/UnityEditor/UnityEditor/PluginImporter.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditor +{ + public sealed class PluginImporter : AssetImporter + { + public extern bool isNativePlugin + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetCompatibleWithAnyPlatform(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetCompatibleWithAnyPlatform(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetCompatibleWithEditor(bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetCompatibleWithEditor(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetIsPreloaded(bool isPreloaded); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern bool GetIsPreloaded(); + public void SetCompatibleWithPlatform(BuildTarget platform, bool enable) + { + this.SetCompatibleWithPlatform(BuildPipeline.GetBuildTargetName(platform), enable); + } + public bool GetCompatibleWithPlatform(BuildTarget platform) + { + return this.GetCompatibleWithPlatform(BuildPipeline.GetBuildTargetName(platform)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetCompatibleWithPlatform(string platformName, bool enable); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetCompatibleWithPlatform(string platformName); + public void SetPlatformData(BuildTarget platform, string key, string value) + { + this.SetPlatformData(BuildPipeline.GetBuildTargetName(platform), key, value); + } + public string GetPlatformData(BuildTarget platform, string key) + { + return this.GetPlatformData(BuildPipeline.GetBuildTargetName(platform), key); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetPlatformData(string platformName, string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetPlatformData(string platformName, string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetEditorData(string key, string value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetEditorData(string key); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern PluginImporter[] GetAllImporters(); + public static PluginImporter[] GetImporters(string platformName) + { + return ( + from imp in PluginImporter.GetAllImporters() + where (imp.GetCompatibleWithPlatform(platformName) || imp.GetCompatibleWithAnyPlatform()) && !string.IsNullOrEmpty(imp.assetPath) + select imp).ToArray(); + } + public static PluginImporter[] GetImporters(BuildTarget platform) + { + return PluginImporter.GetImporters(BuildPipeline.GetBuildTargetName(platform)); + } + } +} diff --git a/UnityEditor/UnityEditor/PluginImporterInspector.cs b/UnityEditor/UnityEditor/PluginImporterInspector.cs new file mode 100644 index 00000000..cf0bfe50 --- /dev/null +++ b/UnityEditor/UnityEditor/PluginImporterInspector.cs @@ -0,0 +1,365 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEditor.Modules; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(PluginImporter))] + internal class PluginImporterInspector : AssetImporterInspector + { + private bool hasModified; + private bool compatibleWithAnyPlatform; + private bool compatibleWithEditor; + private bool isPreloaded; + private bool[] compatibleWithPlatform = new bool[PluginImporterInspector.GetPlatformGroupArraySize()]; + private Vector2 informationScrollPosition = Vector2.zero; + private Dictionary pluginInformation; + private EditorPluginImporterExtension editorExtension = new EditorPluginImporterExtension(); + private DesktopPluginImporterExtension desktopExtension = new DesktopPluginImporterExtension(); + private IPluginImporterExtension[] _additionalExtensions; + internal override bool showImportedObject + { + get + { + return false; + } + } + internal IPluginImporterExtension[] additionalExtensions + { + get + { + if (this._additionalExtensions == null) + { + this._additionalExtensions = new IPluginImporterExtension[] + { + this.editorExtension, + this.desktopExtension + }; + } + return this._additionalExtensions; + } + } + internal PluginImporter importer + { + get + { + return this.target as PluginImporter; + } + } + private bool compatibleWithStandalone + { + get + { + return this.compatibleWithPlatform[4] || this.compatibleWithPlatform[27] || this.compatibleWithPlatform[2] || this.compatibleWithPlatform[5] || this.compatibleWithPlatform[17] || this.compatibleWithPlatform[24] || this.compatibleWithPlatform[25] || this.compatibleWithPlatform[19]; + } + set + { + bool[] arg_5A_0 = this.compatibleWithPlatform; + int arg_5A_1 = 4; + bool[] arg_58_0 = this.compatibleWithPlatform; + int arg_58_1 = 27; + bool[] arg_54_0 = this.compatibleWithPlatform; + int arg_54_1 = 2; + bool[] arg_50_0 = this.compatibleWithPlatform; + int arg_50_1 = 5; + bool[] arg_4C_0 = this.compatibleWithPlatform; + int arg_4C_1 = 17; + bool[] arg_48_0 = this.compatibleWithPlatform; + int arg_48_1 = 24; + bool[] arg_44_0 = this.compatibleWithPlatform; + int arg_44_1 = 25; + this.compatibleWithPlatform[19] = value; + arg_5A_0[arg_5A_1] = (arg_58_0[arg_58_1] = (arg_54_0[arg_54_1] = (arg_50_0[arg_50_1] = (arg_4C_0[arg_4C_1] = (arg_48_0[arg_48_1] = (arg_44_0[arg_44_1] = value)))))); + } + } + private static bool IgnorePlatform(BuildTarget platform) + { + return platform == BuildTarget.StandaloneGLESEmu; + } + private static int GetPlatformGroupArraySize() + { + int num = 0; + IEnumerator enumerator = Enum.GetValues(typeof(BuildTarget)).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + BuildTarget buildTarget = (BuildTarget)((int)enumerator.Current); + if (num < (int)(buildTarget + 1)) + { + num = (int)(buildTarget + 1); + } + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + return num; + } + private static bool IsStandaloneTarget(BuildTarget target) + { + return target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal || target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneLinux || target == BuildTarget.StandaloneLinux64 || target == BuildTarget.StandaloneLinuxUniversal || target == BuildTarget.StandaloneWindows64; + } + private static List GetValidBuildTargets() + { + List list = new List(); + IEnumerator enumerator = Enum.GetValues(typeof(BuildTarget)).GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + BuildTarget buildTarget = (BuildTarget)((int)enumerator.Current); + if (!PluginImporterInspector.IgnorePlatform(buildTarget) && !list.Contains(buildTarget)) + { + if (!ModuleManager.IsPlatformSupported(buildTarget) || ModuleManager.IsPlatformSupportLoaded(ModuleManager.GetTargetStringFromBuildTarget(buildTarget))) + { + list.Add(buildTarget); + } + } + } + } + finally + { + IDisposable disposable = enumerator as IDisposable; + if (disposable != null) + { + disposable.Dispose(); + } + } + return list; + } + private BuildPlayerWindow.BuildPlatform[] GetBuildPlayerValidPlatforms() + { + List validPlatforms = BuildPlayerWindow.GetValidPlatforms(); + List list = new List(); + if (this.compatibleWithAnyPlatform || this.compatibleWithEditor) + { + list.Add(new BuildPlayerWindow.BuildPlatform("BuildSettings.Editor", "Editor settings", BuildTargetGroup.Unknown, true) + { + name = BuildPipeline.GetEditorTargetName() + }); + } + foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) + { + if (!PluginImporterInspector.IgnorePlatform(current.DefaultTarget)) + { + if (current.targetGroup == BuildTargetGroup.Standalone) + { + if (!this.compatibleWithAnyPlatform && !this.compatibleWithStandalone) + { + continue; + } + } + else + { + if (!this.compatibleWithAnyPlatform && !this.compatibleWithPlatform[(int)current.DefaultTarget]) + { + continue; + } + if (ModuleManager.GetPluginImporterExtension(current.targetGroup) == null) + { + continue; + } + } + list.Add(current); + } + } + return list.ToArray(); + } + internal override void ResetValues() + { + base.ResetValues(); + this.hasModified = false; + this.compatibleWithAnyPlatform = this.importer.GetCompatibleWithAnyPlatform(); + this.compatibleWithEditor = this.importer.GetCompatibleWithEditor(); + this.isPreloaded = this.importer.GetIsPreloaded(); + IPluginImporterExtension[] additionalExtensions = this.additionalExtensions; + for (int i = 0; i < additionalExtensions.Length; i++) + { + IPluginImporterExtension pluginImporterExtension = additionalExtensions[i]; + pluginImporterExtension.ResetValues(this); + } + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + this.compatibleWithPlatform[(int)current] = this.importer.GetCompatibleWithPlatform(current); + IPluginImporterExtension pluginImporterExtension2 = ModuleManager.GetPluginImporterExtension(current); + if (pluginImporterExtension2 != null) + { + pluginImporterExtension2.ResetValues(this); + } + } + } + internal override bool HasModified() + { + bool flag = this.hasModified || base.HasModified(); + IPluginImporterExtension[] additionalExtensions = this.additionalExtensions; + for (int i = 0; i < additionalExtensions.Length; i++) + { + IPluginImporterExtension pluginImporterExtension = additionalExtensions[i]; + flag |= pluginImporterExtension.HasModified(this); + } + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + IPluginImporterExtension pluginImporterExtension2 = ModuleManager.GetPluginImporterExtension(current); + if (pluginImporterExtension2 != null) + { + flag |= pluginImporterExtension2.HasModified(this); + } + } + return flag; + } + internal override void Apply() + { + base.Apply(); + this.importer.SetCompatibleWithAnyPlatform(this.compatibleWithAnyPlatform); + this.importer.SetCompatibleWithEditor(this.compatibleWithEditor); + this.importer.SetIsPreloaded(this.isPreloaded); + IPluginImporterExtension[] additionalExtensions = this.additionalExtensions; + for (int i = 0; i < additionalExtensions.Length; i++) + { + IPluginImporterExtension pluginImporterExtension = additionalExtensions[i]; + pluginImporterExtension.Apply(this); + } + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + this.importer.SetCompatibleWithPlatform(current, this.compatibleWithPlatform[(int)current]); + IPluginImporterExtension pluginImporterExtension2 = ModuleManager.GetPluginImporterExtension(current); + if (pluginImporterExtension2 != null) + { + pluginImporterExtension2.Apply(this); + } + } + } + private void OnEnable() + { + IPluginImporterExtension[] additionalExtensions = this.additionalExtensions; + for (int i = 0; i < additionalExtensions.Length; i++) + { + IPluginImporterExtension pluginImporterExtension = additionalExtensions[i]; + pluginImporterExtension.OnEnable(this); + } + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + IPluginImporterExtension pluginImporterExtension2 = ModuleManager.GetPluginImporterExtension(current); + if (pluginImporterExtension2 != null) + { + pluginImporterExtension2.OnEnable(this); + pluginImporterExtension2.ResetValues(this); + } + } + PluginImporter pluginImporter = (PluginImporter)this.target; + this.pluginInformation = new Dictionary(); + this.pluginInformation["Path"] = pluginImporter.assetPath; + this.pluginInformation["Type"] = ((!pluginImporter.isNativePlugin) ? "Managed" : "Native"); + } + private new void OnDisable() + { + base.OnDisable(); + IPluginImporterExtension[] additionalExtensions = this.additionalExtensions; + for (int i = 0; i < additionalExtensions.Length; i++) + { + IPluginImporterExtension pluginImporterExtension = additionalExtensions[i]; + pluginImporterExtension.OnDisable(this); + } + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + IPluginImporterExtension pluginImporterExtension2 = ModuleManager.GetPluginImporterExtension(current); + if (pluginImporterExtension2 != null) + { + pluginImporterExtension2.OnDisable(this); + } + } + } + private void ShowGeneralOptions() + { + EditorGUI.BeginChangeCheck(); + this.compatibleWithAnyPlatform = GUILayout.Toggle(this.compatibleWithAnyPlatform, "Any Platform", new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(this.compatibleWithAnyPlatform); + this.compatibleWithEditor = GUILayout.Toggle(this.compatibleWithEditor, "Editor", new GUILayoutOption[0]); + this.compatibleWithStandalone = GUILayout.Toggle(this.compatibleWithStandalone, "Standalone", new GUILayoutOption[0]); + foreach (BuildTarget current in PluginImporterInspector.GetValidBuildTargets()) + { + if (!PluginImporterInspector.IsStandaloneTarget(current)) + { + this.compatibleWithPlatform[(int)current] = GUILayout.Toggle(this.compatibleWithPlatform[(int)current], current.ToString(), new GUILayoutOption[0]); + } + } + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + this.hasModified = true; + } + } + private void ShowEditorSettings() + { + this.editorExtension.OnPlatformSettingsGUI(this); + } + public override void OnInspectorGUI() + { + EditorGUI.BeginDisabledGroup(false); + BuildPlayerWindow.BuildPlatform[] buildPlayerValidPlatforms = this.GetBuildPlayerValidPlatforms(); + GUILayout.Label("Select platforms for plugin", EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.BeginVertical(GUI.skin.box, new GUILayoutOption[0]); + this.ShowGeneralOptions(); + EditorGUILayout.EndVertical(); + EditorGUI.BeginChangeCheck(); + if (EditorGUI.EndChangeCheck()) + { + this.hasModified = true; + } + GUILayout.Space(10f); + if (buildPlayerValidPlatforms.Length > 0) + { + GUILayout.Label("Platform settings", EditorStyles.boldLabel, new GUILayoutOption[0]); + int num = EditorGUILayout.BeginPlatformGrouping(buildPlayerValidPlatforms, null); + if (buildPlayerValidPlatforms[num].name == BuildPipeline.GetEditorTargetName()) + { + this.ShowEditorSettings(); + } + else + { + BuildTargetGroup targetGroup = buildPlayerValidPlatforms[num].targetGroup; + if (targetGroup == BuildTargetGroup.Standalone) + { + this.desktopExtension.OnPlatformSettingsGUI(this); + } + else + { + IPluginImporterExtension pluginImporterExtension = ModuleManager.GetPluginImporterExtension(targetGroup); + if (pluginImporterExtension != null) + { + pluginImporterExtension.OnPlatformSettingsGUI(this); + } + } + } + EditorGUILayout.EndPlatformGrouping(); + } + EditorGUI.EndDisabledGroup(); + base.ApplyRevertGUI(); + GUILayout.Label("Information", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.informationScrollPosition = EditorGUILayout.BeginVerticalScrollView(this.informationScrollPosition, new GUILayoutOption[0]); + foreach (KeyValuePair current in this.pluginInformation) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(current.Key, new GUILayoutOption[] + { + GUILayout.Width(50f) + }); + GUILayout.TextField(current.Value, new GUILayoutOption[0]); + GUILayout.EndHorizontal(); + } + EditorGUILayout.EndScrollView(); + GUILayout.FlexibleSpace(); + if (this.importer.isNativePlugin) + { + EditorGUILayout.HelpBox("Once a native plugin is loaded from script, it's never unloaded. If you deselect a native plugin and it's already loaded, please restart Unity.", MessageType.Warning); + } + } + } +} diff --git a/UnityEditor/UnityEditor/PointEditor.cs b/UnityEditor/UnityEditor/PointEditor.cs index 0ca20580..5945ff67 100644 --- a/UnityEditor/UnityEditor/PointEditor.cs +++ b/UnityEditor/UnityEditor/PointEditor.cs @@ -9,14 +9,8 @@ internal class PointEditor private static Vector2 s_StartMouseDragPosition; private static List s_StartDragSelection; private static bool s_DidDrag; - private static Mesh s_Mesh; private static Vector3 s_EditingScale = Vector3.one; private static Quaternion s_EditingRotation = Quaternion.identity; - private static Mesh GetMesh() - { - PointEditor.s_Mesh = (PointEditor.s_Mesh ?? (Resources.GetBuiltinResource(typeof(Mesh), "New-Sphere.fbx") as Mesh)); - return PointEditor.s_Mesh; - } public static bool MovePoints(IEditablePoint points, Transform cloudTransform, List selection) { if (selection.Count == 0) diff --git a/UnityEditor/UnityEditor/PolygonColliderEditor.cs b/UnityEditor/UnityEditor/PolygonCollider2DEditor.cs similarity index 67% rename from UnityEditor/UnityEditor/PolygonColliderEditor.cs rename to UnityEditor/UnityEditor/PolygonCollider2DEditor.cs index a6a97311..0fb8b064 100644 --- a/UnityEditor/UnityEditor/PolygonColliderEditor.cs +++ b/UnityEditor/UnityEditor/PolygonCollider2DEditor.cs @@ -6,9 +6,9 @@ namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(PolygonCollider2D))] - internal class PolygonColliderEditor : Collider2DEditorBase + internal class PolygonCollider2DEditor : Collider2DEditorBase { - private PolygonEditorUtility m_PolyUtility = new PolygonEditorUtility(); + private readonly PolygonEditorUtility m_PolyUtility = new PolygonEditorUtility(); private bool m_ShowColliderInfo; public override void OnEnable() { @@ -18,9 +18,8 @@ public override void OnInspectorGUI() { this.HandleDragAndDrop(); base.BeginColliderInspector(); - this.ColliderInfoGUI(); + base.OnInspectorGUI(); base.EndColliderInspector(); - base.CheckColliderErrorState(); } private void HandleDragAndDrop() { @@ -45,7 +44,7 @@ from target in base.targets select target as PolygonCollider2D) { Vector2[][] array; - DataUtility.GenerateOutlineFromSprite(sprite, 0.25f, 200, true, out array); + UnityEditor.Sprites.SpriteUtility.GenerateOutlineFromSprite(sprite, 0.25f, 200, true, out array); current2.pathCount = array.Length; for (int i = 0; i < array.Length; i++) { @@ -60,24 +59,6 @@ from target in base.targets } DragAndDrop.visualMode = DragAndDropVisualMode.Rejected; } - private void ColliderInfoGUI() - { - EditorGUI.BeginDisabledGroup(base.targets.Length != 1); - this.m_ShowColliderInfo = EditorGUILayout.Foldout(this.m_ShowColliderInfo, "Collider Info"); - if (this.m_ShowColliderInfo) - { - PolygonCollider2D polygonCollider2D = base.targets[0] as PolygonCollider2D; - if (polygonCollider2D) - { - int totalPointCount = polygonCollider2D.GetTotalPointCount(); - string label = (!GUI.enabled) ? "---" : (string.Empty + totalPointCount); - EditorGUI.indentLevel++; - EditorGUILayout.LabelField("Vertices", label, new GUILayoutOption[0]); - EditorGUI.indentLevel--; - } - } - EditorGUI.EndDisabledGroup(); - } protected override void OnEditStart() { if (this.target == null) diff --git a/UnityEditor/UnityEditor/PolygonEditorUtility.cs b/UnityEditor/UnityEditor/PolygonEditorUtility.cs index 95b402fa..77364a75 100644 --- a/UnityEditor/UnityEditor/PolygonEditorUtility.cs +++ b/UnityEditor/UnityEditor/PolygonEditorUtility.cs @@ -92,6 +92,7 @@ public void OnSceneGUI() { return; } + Vector2 offset = this.m_ActiveCollider.offset; Event current = Event.current; this.m_DeleteMode = (current.command || current.control); Transform transform = this.m_ActiveCollider.transform; @@ -108,7 +109,7 @@ public void OnSceneGUI() int num; int num2; float num3; - if (PolygonEditor.GetNearestPoint(vector, out num, out num2, out num3)) + if (PolygonEditor.GetNearestPoint(vector - offset, out num, out num2, out num3)) { this.m_SelectedPath = num; this.m_SelectedVertex = num2; @@ -119,7 +120,7 @@ public void OnSceneGUI() this.m_SelectedPath = -1; } int selectedEdgeVertex; - if (PolygonEditor.GetNearestEdge(vector, out num, out num2, out selectedEdgeVertex, out num3, this.m_LoopingCollider)) + if (PolygonEditor.GetNearestEdge(vector - offset, out num, out num2, out selectedEdgeVertex, out num3, this.m_LoopingCollider)) { this.m_SelectedEdgePath = num; this.m_SelectedEdgeVertex0 = num2; @@ -144,9 +145,10 @@ public void OnSceneGUI() bool flag2 = false; if (this.m_SelectedPath != -1 && this.m_SelectedEdgePath != -1) { - Vector2 v; - PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out v); - Vector3 position = transform.TransformPoint(v); + Vector2 vector2; + PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out vector2); + vector2 += offset; + Vector3 position = transform.TransformPoint(vector2); float num4 = HandleUtility.GetHandleSize(position) * 0.2f; flag2 = (this.m_SelectedEdgeDistance < this.m_SelectedDistance - num4); flag = !flag2; @@ -173,29 +175,31 @@ public void OnSceneGUI() bool flag3 = false; if (flag2 && !this.m_DeleteMode) { - Vector2 vector2; - PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex0, out vector2); Vector2 vector3; - PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, out vector3); - Vector3 vector4 = transform.TransformPoint(vector2); + PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex0, out vector3); + Vector2 vector4; + PolygonEditor.GetPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, out vector4); + vector3 += offset; + vector4 += offset; Vector3 vector5 = transform.TransformPoint(vector3); - vector4.z = (vector5.z = 0f); + Vector3 vector6 = transform.TransformPoint(vector4); + vector5.z = (vector6.z = 0f); Handles.color = Color.green; Handles.DrawAAPolyLine(4f, new Vector3[] { - vector4, - vector5 + vector5, + vector6 }); Handles.color = Color.white; - Vector2 v2 = this.GetNearestPointOnEdge(transform.TransformPoint(vector), vector4, vector5); + Vector2 v = this.GetNearestPointOnEdge(transform.TransformPoint(vector), vector5, vector6); EditorGUI.BeginChangeCheck(); - float handleSize = HandleUtility.GetHandleSize(v2) * 0.04f; + float handleSize = HandleUtility.GetHandleSize(v) * 0.04f; Handles.color = Color.green; - v2 = Handles.Slider2D(v2, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); + v = Handles.Slider2D(v, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); Handles.color = Color.white; if (EditorGUI.EndChangeCheck()) { - PolygonEditor.InsertPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, (vector2 + vector3) / 2f); + PolygonEditor.InsertPoint(this.m_SelectedEdgePath, this.m_SelectedEdgeVertex1, (vector3 + vector4) / 2f - offset); this.m_SelectedPath = this.m_SelectedEdgePath; this.m_SelectedVertex = this.m_SelectedEdgeVertex1; this.m_SelectedDistance = 0f; @@ -205,12 +209,13 @@ public void OnSceneGUI() } if (flag) { - Vector2 vector6; - PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out vector6); - Vector3 vector7 = transform.TransformPoint(vector6); - vector7.z = 0f; - Vector2 a = HandleUtility.WorldToGUIPoint(vector7); - float handleSize2 = HandleUtility.GetHandleSize(vector7) * 0.04f; + Vector2 vector7; + PolygonEditor.GetPoint(this.m_SelectedPath, this.m_SelectedVertex, out vector7); + vector7 += offset; + Vector3 vector8 = transform.TransformPoint(vector7); + vector8.z = 0f; + Vector2 a = HandleUtility.WorldToGUIPoint(vector8); + float handleSize2 = HandleUtility.GetHandleSize(vector8) * 0.04f; if ((this.m_DeleteMode && current.type == EventType.MouseDown && Vector2.Distance(a, Event.current.mousePosition) < 50f) || this.DeleteCommandEvent(current)) { if (current.type != EventType.ValidateCommand) @@ -227,18 +232,19 @@ public void OnSceneGUI() } EditorGUI.BeginChangeCheck(); Handles.color = ((!this.m_DeleteMode) ? Color.green : Color.red); - Vector3 vector8 = Handles.Slider2D(vector7, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize2, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); + Vector3 vector9 = Handles.Slider2D(vector8, new Vector3(0f, 0f, 1f), new Vector3(1f, 0f, 0f), new Vector3(0f, 1f, 0f), handleSize2, new Handles.DrawCapFunction(Handles.DotCap), Vector3.zero); Handles.color = Color.white; if (EditorGUI.EndChangeCheck() && !this.m_DeleteMode) { - vector6 = transform.InverseTransformPoint(vector8); - PolygonEditor.TestPointMove(this.m_SelectedPath, this.m_SelectedVertex, vector6, out this.m_LeftIntersect, out this.m_RightIntersect, this.m_LoopingCollider); - PolygonEditor.SetPoint(this.m_SelectedPath, this.m_SelectedVertex, vector6); + vector7 = transform.InverseTransformPoint(vector9); + vector7 -= offset; + PolygonEditor.TestPointMove(this.m_SelectedPath, this.m_SelectedVertex, vector7, out this.m_LeftIntersect, out this.m_RightIntersect, this.m_LoopingCollider); + PolygonEditor.SetPoint(this.m_SelectedPath, this.m_SelectedVertex, vector7); flag3 = true; } if (!flag3) { - this.DrawEdgesForSelectedPoint(vector8, transform, this.m_LeftIntersect, this.m_RightIntersect, this.m_LoopingCollider); + this.DrawEdgesForSelectedPoint(vector9, transform, this.m_LeftIntersect, this.m_RightIntersect, this.m_LoopingCollider); } } if (flag3) @@ -273,13 +279,16 @@ private void DrawEdgesForSelectedPoint(Vector3 worldPos, Transform transform, bo num2 = 0; flag2 = loop; } - Vector2 v; - PolygonEditor.GetPoint(this.m_SelectedPath, num, out v); - Vector2 v2; - PolygonEditor.GetPoint(this.m_SelectedPath, num2, out v2); - Vector3 vector = transform.TransformPoint(v); - Vector3 vector2 = transform.TransformPoint(v2); - vector.z = (vector2.z = worldPos.z); + Vector2 offset = this.m_ActiveCollider.offset; + Vector2 vector; + PolygonEditor.GetPoint(this.m_SelectedPath, num, out vector); + Vector2 vector2; + PolygonEditor.GetPoint(this.m_SelectedPath, num2, out vector2); + vector += offset; + vector2 += offset; + Vector3 vector3 = transform.TransformPoint(vector); + Vector3 vector4 = transform.TransformPoint(vector2); + vector3.z = (vector4.z = worldPos.z); float width = 4f; if (flag) { @@ -287,7 +296,7 @@ private void DrawEdgesForSelectedPoint(Vector3 worldPos, Transform transform, bo Handles.DrawAAPolyLine(width, new Vector3[] { worldPos, - vector + vector3 }); } if (flag2) @@ -296,7 +305,7 @@ private void DrawEdgesForSelectedPoint(Vector3 worldPos, Transform transform, bo Handles.DrawAAPolyLine(width, new Vector3[] { worldPos, - vector2 + vector4 }); } Handles.color = Color.white; diff --git a/UnityEditor/UnityEditor/PopupList.cs b/UnityEditor/UnityEditor/PopupList.cs index 5d95b9be..ae2ca1a5 100644 --- a/UnityEditor/UnityEditor/PopupList.cs +++ b/UnityEditor/UnityEditor/PopupList.cs @@ -167,15 +167,15 @@ public int GetFilteredCount(string prefix) } public PopupList.ListElement NewOrMatchingElement(string label) { - PopupList.ListElement listElement = ( - from element in this.m_ListElements - where element.text.Equals(label, StringComparison.OrdinalIgnoreCase) - select element).DefaultIfEmpty(null).FirstOrDefault(); - if (listElement == null) + foreach (PopupList.ListElement current in this.m_ListElements) { - listElement = new PopupList.ListElement(label, false, -1f); - this.m_ListElements.Add(listElement); + if (current.text.Equals(label, StringComparison.OrdinalIgnoreCase)) + { + return current; + } } + PopupList.ListElement listElement = new PopupList.ListElement(label, false, -1f); + this.m_ListElements.Add(listElement); return listElement; } } diff --git a/UnityEditor/UnityEditor/PopupWindow.cs b/UnityEditor/UnityEditor/PopupWindow.cs index d4628e4c..022e9eef 100644 --- a/UnityEditor/UnityEditor/PopupWindow.cs +++ b/UnityEditor/UnityEditor/PopupWindow.cs @@ -62,10 +62,10 @@ private void FitWindowToContent() { this.m_LastWantedSize = windowSize; Rect dropDownRect = this.m_Parent.window.GetDropDownRect(this.m_ActivatorRect, windowSize, windowSize); - this.m_Pos = dropDownRect; Vector2 vector = new Vector2(dropDownRect.width, dropDownRect.height); base.maxSize = vector; base.minSize = vector; + base.position = dropDownRect; } } private void OnDisable() diff --git a/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs b/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs index dac71521..0b787e0a 100644 --- a/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs +++ b/UnityEditor/UnityEditor/PopupWindowWithoutFocus.cs @@ -45,6 +45,7 @@ public static void Hide() private void Init(Rect activatorRect, PopupWindowContent windowContent, PopupLocationHelper.PopupLocation[] locationPriorityOrder) { this.m_WindowContent = windowContent; + this.m_WindowContent.editorWindow = this; this.m_ActivatorRect = GUIUtility.GUIToScreenRect(activatorRect); this.m_LastWantedSize = windowContent.GetWindowSize(); this.m_LocationPriorityOrder = locationPriorityOrder; diff --git a/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs b/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs index 6f14635f..35af3037 100644 --- a/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs +++ b/UnityEditor/UnityEditor/PostprocessBuildPlayer.cs @@ -4,7 +4,6 @@ using System.IO; using UnityEditor.Modules; using UnityEditor.Utils; -using UnityEditorInternal; using UnityEngine; namespace UnityEditor { @@ -237,36 +236,28 @@ internal static void InstallStreamingAssets(string stagingAreaDataPath) FileUtil.CopyDirectoryRecursiveForPostprocess("Assets/StreamingAssets", Path.Combine(stagingAreaDataPath, "StreamingAssets"), true); } } - public static string GetExtensionForBuildTarget(BuildTarget target) + public static string GetScriptLayoutFileFromBuild(BuildOptions options, BuildTarget target, string installPath, string fileName) { IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); if (buildPostProcessor != null) { - return buildPostProcessor.GetExtension(); + return buildPostProcessor.GetScriptLayoutFileFromBuild(options, installPath, fileName); } - switch (target) + return string.Empty; + } + public static bool SupportsScriptsOnlyBuild(BuildTarget target) + { + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + return buildPostProcessor != null && buildPostProcessor.SupportsScriptsOnlyBuild(); + } + public static string GetExtensionForBuildTarget(BuildTarget target, BuildOptions options) + { + IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); + if (buildPostProcessor == null) { - case BuildTarget.StandaloneOSXUniversal: - case BuildTarget.StandaloneOSXIntel: - case BuildTarget.StandaloneOSXIntel64: - return "app"; - case BuildTarget.StandaloneWindows: - case BuildTarget.StandaloneGLESEmu: - case BuildTarget.StandaloneWindows64: - return "exe"; - case BuildTarget.WebPlayer: - case BuildTarget.WebPlayerStreamed: return string.Empty; - case BuildTarget.StandaloneLinux: - case BuildTarget.StandaloneLinux64: - case BuildTarget.StandaloneLinuxUniversal: - return PostprocessBuildPlayer.GetArchitectureForTarget(target); - case BuildTarget.FlashPlayer: - return "swf"; - case BuildTarget.MetroPlayer: - return (EditorUserBuildSettings.metroBuildType != MetroBuildType.AppX) ? string.Empty : "appx"; } - return string.Empty; + return buildPostProcessor.GetExtension(target, options); } public static bool SupportsInstallInBuildFolder(BuildTarget target) { @@ -277,45 +268,28 @@ public static bool SupportsInstallInBuildFolder(BuildTarget target) } switch (target) { - case BuildTarget.WP8Player: - case BuildTarget.StandaloneOSXIntel64: - case BuildTarget.PSP2: - case BuildTarget.PSM: + case BuildTarget.PS3: + case BuildTarget.Android: return true; - case BuildTarget.BB10: - case BuildTarget.Tizen: - case BuildTarget.PS4: - IL_3B: + case BuildTarget.XBOX360: + case (BuildTarget)12: + IL_2F: switch (target) { - case BuildTarget.PS3: - case BuildTarget.Android: - case BuildTarget.StandaloneGLESEmu: + case BuildTarget.PSP2: + case BuildTarget.PSM: return true; - case BuildTarget.XBOX360: - case (BuildTarget)12: - IL_58: - switch (target) + case BuildTarget.PS4: + IL_44: + if (target != BuildTarget.MetroPlayer && target != BuildTarget.WP8Player) { - case BuildTarget.StandaloneOSXUniversal: - case BuildTarget.StandaloneOSXIntel: - case BuildTarget.StandaloneWindows: - return true; - case (BuildTarget)3: - IL_70: - switch (target) - { - case BuildTarget.StandaloneWindows64: - case BuildTarget.MetroPlayer: - return true; - } return false; } - goto IL_70; + return true; } - goto IL_58; + goto IL_44; } - goto IL_3B; + goto IL_2F; } public static void Launch(BuildTarget target, string path, string productName, BuildOptions options) { @@ -329,15 +303,9 @@ public static void Launch(BuildTarget target, string path, string productName, B args.productName = productName; args.options = options; buildPostProcessor.LaunchPlayer(args); + return; } - else - { - if (target != BuildTarget.NaCl) - { - throw new UnityException(string.Format("Launching {0} build target via mono is not supported", target)); - } - PostProcessNaclPlayer.Launch(target, path); - } + throw new UnityException(string.Format("Launching {0} build target via mono is not supported", target)); } public static void Postprocess(BuildTarget target, string installPath, string companyName, string productName, int width, int height, string downloadWebplayerUrl, string manualDownloadWebplayerUrl, BuildOptions options, RuntimeClassRegistry usedClassRegistry) { @@ -350,69 +318,29 @@ public static void Postprocess(BuildTarget target, string installPath, string co { throw new Exception(installPath + " must not be an empty string"); } - BuildPostProcessArgs buildPostProcessArgs = new BuildPostProcessArgs - { - target = target, - stagingAreaData = stagingAreaData, - stagingArea = stagingArea, - stagingAreaDataManaged = stagingAreaDataManaged, - playerPackage = playbackEngineDirectory, - installPath = installPath, - companyName = companyName, - productName = productName, - productGUID = PlayerSettings.productGUID, - options = options, - usedClassRegistry = usedClassRegistry - }; IBuildPostprocessor buildPostProcessor = ModuleManager.GetBuildPostProcessor(target); if (buildPostProcessor != null) { - buildPostProcessor.PostProcess(buildPostProcessArgs); + BuildPostProcessArgs args; + args.target = target; + args.stagingAreaData = stagingAreaData; + args.stagingArea = stagingArea; + args.stagingAreaDataManaged = stagingAreaDataManaged; + args.playerPackage = playbackEngineDirectory; + args.installPath = installPath; + args.companyName = companyName; + args.productName = productName; + args.productGUID = PlayerSettings.productGUID; + args.options = options; + args.usedClassRegistry = usedClassRegistry; + buildPostProcessor.PostProcess(args); return; } - switch (target) + if (target != BuildTarget.WebPlayer && target != BuildTarget.WebPlayerStreamed) { - case BuildTarget.StandaloneOSXUniversal: - case BuildTarget.StandaloneOSXIntel: - case BuildTarget.StandaloneOSXIntel64: - new OSXDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); - return; - case BuildTarget.StandaloneWindows: - case BuildTarget.StandaloneGLESEmu: - case BuildTarget.StandaloneWindows64: - new WindowsDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); - return; - case BuildTarget.WebPlayer: - case BuildTarget.WebPlayerStreamed: - PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); - return; - case BuildTarget.NaCl: - PostProcessNaclPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); - return; - case BuildTarget.StandaloneLinux: - case BuildTarget.StandaloneLinux64: - case BuildTarget.StandaloneLinuxUniversal: - new LinuxDesktopStandalonePostProcessor(buildPostProcessArgs).PostProcess(); - return; - case BuildTarget.FlashPlayer: - PostProcessFlashPlayer.PostProcess(new PostProcessFlashPlayerOptions - { - Target = target, - StagingAreaData = stagingAreaData, - StagingArea = stagingArea, - StagingAreaDataManaged = stagingAreaDataManaged, - PlayerPackage = playbackEngineDirectory, - InstallPath = installPath, - CompanyName = companyName, - ProductName = productName, - Options = options, - UsedClassRegistry = usedClassRegistry, - Width = width, - Height = height - }); - return; + throw new UnityException(string.Format("Build target '{0}' not supported", target)); } - throw new UnityException(string.Format("Build target '{0}' not supported", target)); + PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); } internal static string ExecuteSystemProcess(string command, string args, string workingdir) { @@ -438,7 +366,7 @@ internal static string GetArchitectureForTarget(BuildTarget target) { case BuildTarget.StandaloneLinux: goto IL_40; - case BuildTarget.FlashPlayer: + case (BuildTarget)18: IL_17: if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneWindows) { diff --git a/UnityEditor/UnityEditor/PrefabUtility.cs b/UnityEditor/UnityEditor/PrefabUtility.cs index 71fdcc96..6bccf8e5 100644 --- a/UnityEditor/UnityEditor/PrefabUtility.cs +++ b/UnityEditor/UnityEditor/PrefabUtility.cs @@ -31,12 +31,6 @@ public sealed class PrefabUtility public static extern void MergeAllPrefabInstances(UnityEngine.Object targetObject); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool IsPrefabExploded(UnityEngine.Object targetObject); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void SetIsPrefabExploded(UnityEngine.Object targetObject, bool exploded); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DisconnectPrefabInstance(UnityEngine.Object targetObject); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/PreferencesWindow.cs b/UnityEditor/UnityEditor/PreferencesWindow.cs index a899cf5c..62c01c6f 100644 --- a/UnityEditor/UnityEditor/PreferencesWindow.cs +++ b/UnityEditor/UnityEditor/PreferencesWindow.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; @@ -22,6 +21,7 @@ internal class Constants public GUIStyle selected = "ServerUpdateChangesetOn"; public GUIStyle keysElement = "PreferencesKeysElement"; public GUIStyle sectionHeader = new GUIStyle(EditorStyles.largeLabel); + public GUIStyle cacheFolderLocation = new GUIStyle(GUI.skin.label); public Constants() { this.sectionScrollView = new GUIStyle(this.sectionScrollView); @@ -38,8 +38,21 @@ public Constants() { this.sectionHeader.normal.textColor = new Color(0.7f, 0.7f, 0.7f, 1f); } + this.cacheFolderLocation.wordWrap = true; } } + internal class Styles + { + public static readonly GUIContent browse = EditorGUIUtility.TextContent("PreferencesWindow.Browse"); + public static readonly GUIContent maxCacheSize = EditorGUIUtility.TextContent("PreferencesWindow.GICache.MaxCacheSize"); + public static readonly GUIContent customCacheLocation = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CustomCacheLocation"); + public static readonly GUIContent cacheFolderLocation = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CacheFolderLocation"); + public static readonly GUIContent cacheCompression = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CacheCompression"); + public static readonly GUIContent cantChangeCacheSettings = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CantChangeCacheSettings"); + public static readonly GUIContent cleanCache = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CleanCache"); + public static readonly GUIContent browseGICacheLocation = EditorGUIUtility.TextContent("PreferencesWindow.GICache.BrowseGICacheLocation"); + public static readonly GUIContent cacheSizeIs = EditorGUIUtility.TextContent("PreferencesWindow.GICache.CacheSize"); + } private class Section { public GUIContent content; @@ -60,6 +73,13 @@ public Section(GUIContent content, PreferencesWindow.OnGUIDelegate guiFunc) this.guiFunc = guiFunc; } } + private struct GICacheSettings + { + public bool m_EnableCustomPath; + public int m_MaximumSize; + public string m_CachePath; + public int m_CompressionLevel; + } private class RefString { public string str; @@ -98,7 +118,7 @@ public AppsListUserData(string[] paths, PreferencesWindow.RefString str, Action private static PreferencesWindow.Constants constants = null; private List prefWinExtensions; private bool m_AutoRefresh; - private bool m_AlwaysShowProjectWizard; + private bool m_ReopenLastUsedProjectOnStartup; private bool m_CompressAssetsOnImport; private bool m_UseOSColorPicker; private bool m_EnableEditorAnalytics; @@ -106,6 +126,7 @@ public AppsListUserData(string[] paths, PreferencesWindow.RefString str, Action private bool m_VerifySavingAssets; private bool m_AllowAttachedDebuggingOfEditor; private bool m_AllowAttachedDebuggingOfEditorStateChangedThisSession; + private PreferencesWindow.GICacheSettings m_GICacheSettings; private PreferencesWindow.RefString m_ScriptEditorPath = new PreferencesWindow.RefString(string.Empty); private string m_ScriptEditorArgs = string.Empty; private PreferencesWindow.RefString m_ImageAppPath = new PreferencesWindow.RefString(string.Empty); @@ -169,6 +190,7 @@ private void OnEnable() this.m_Sections.Add(new PreferencesWindow.Section("External Tools", new PreferencesWindow.OnGUIDelegate(this.ShowExternalApplications))); this.m_Sections.Add(new PreferencesWindow.Section("Colors", new PreferencesWindow.OnGUIDelegate(this.ShowColors))); this.m_Sections.Add(new PreferencesWindow.Section("Keys", new PreferencesWindow.OnGUIDelegate(this.ShowKeys))); + this.m_Sections.Add(new PreferencesWindow.Section("GI Cache", new PreferencesWindow.OnGUIDelegate(this.ShowGICache))); this.m_RefreshCustomPreferences = true; } private void AddCustomSections() @@ -206,7 +228,7 @@ private void OnGUI() this.AddCustomSections(); this.m_RefreshCustomPreferences = false; } - EditorGUIUtility.labelWidth = 180f; + EditorGUIUtility.labelWidth = 200f; if (PreferencesWindow.constants == null) { PreferencesWindow.constants = new PreferencesWindow.Constants(); @@ -303,7 +325,7 @@ private void ShowExternalApplications() GUILayout.Space(10f); this.FilePopup("Image application", this.m_ImageAppPath, ref this.m_ImageAppDisplayNames, ref this.m_ImageApps, this.m_ImageAppPath, null); GUILayout.Space(10f); - EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasMaint()); + EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasPro()); this.m_DiffToolIndex = EditorGUILayout.Popup("Revision Control Diff/Merge", this.m_DiffToolIndex, this.m_DiffTools, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); if (this.m_noDiffToolsMessage != string.Empty) @@ -351,7 +373,7 @@ private void ShowGeneral() { GUILayout.Space(10f); this.m_AutoRefresh = EditorGUILayout.Toggle("Auto Refresh", this.m_AutoRefresh, new GUILayoutOption[0]); - this.m_AlwaysShowProjectWizard = EditorGUILayout.Toggle("Always Show Project Wizard", this.m_AlwaysShowProjectWizard, new GUILayoutOption[0]); + this.m_ReopenLastUsedProjectOnStartup = EditorGUILayout.Toggle("Load Previous Project on Startup", this.m_ReopenLastUsedProjectOnStartup, new GUILayoutOption[0]); bool compressAssetsOnImport = this.m_CompressAssetsOnImport; this.m_CompressAssetsOnImport = EditorGUILayout.Toggle("Compress Assets on Import", compressAssetsOnImport, new GUILayoutOption[0]); if (GUI.changed && this.m_CompressAssetsOnImport != compressAssetsOnImport) @@ -362,17 +384,24 @@ private void ShowGeneral() { this.m_UseOSColorPicker = EditorGUILayout.Toggle("OS X Color Picker", this.m_UseOSColorPicker, new GUILayoutOption[0]); } - this.m_EnableEditorAnalytics = EditorGUILayout.Toggle("Editor Analytics", this.m_EnableEditorAnalytics, new GUILayoutOption[0]); - bool flag = false; + bool flag = Application.HasProLicense(); + EditorGUI.BeginDisabledGroup(!flag); + this.m_EnableEditorAnalytics = !EditorGUILayout.Toggle("Disable Editor Analytics (Pro Only)", !this.m_EnableEditorAnalytics, new GUILayoutOption[0]); + if (!flag && !this.m_EnableEditorAnalytics) + { + this.m_EnableEditorAnalytics = true; + } + EditorGUI.EndDisabledGroup(); + bool flag2 = false; EditorGUI.BeginChangeCheck(); this.m_ShowAssetStoreSearchHits = EditorGUILayout.Toggle("Show Asset Store search hits", this.m_ShowAssetStoreSearchHits, new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) { - flag = true; + flag2 = true; } this.m_VerifySavingAssets = EditorGUILayout.Toggle("Verify Saving Assets", this.m_VerifySavingAssets, new GUILayoutOption[0]); - EditorGUI.BeginDisabledGroup(!InternalEditorUtility.HasPro()); - int num = EditorGUILayout.Popup("Skin (Pro Only)", EditorGUIUtility.isProSkin ? 1 : 0, new string[] + EditorGUI.BeginDisabledGroup(!flag); + int num = EditorGUILayout.Popup("Editor Skin", EditorGUIUtility.isProSkin ? 1 : 0, new string[] { "Light", "Dark" @@ -389,7 +418,7 @@ private void ShowGeneral() { EditorApplication.DirtyHierarchyWindowSorting(); } - if (flag) + if (flag2) { ProjectBrowser.ShowAssetStoreHitsWhileSearchingLocalAssetsChanged(); } @@ -502,7 +531,6 @@ private void ShowKeys() { '/' }); - Assert.AreEqual(array.Length, 2, "Unexpected Split: " + this.m_SelectedKey.Name); GUILayout.Label(array[0], "boldLabel", new GUILayoutOption[0]); GUILayout.Label(array[1], "boldLabel", new GUILayoutOption[0]); GUILayout.BeginHorizontal(new GUILayoutOption[0]); @@ -617,6 +645,66 @@ private void ShowColors() EditorApplication.RequestRepaintAllViews(); } } + private void ShowGICache() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(PreferencesWindow.Styles.maxCacheSize, EditorStyles.popup); + this.m_GICacheSettings.m_MaximumSize = EditorGUILayout.IntSlider(this.m_GICacheSettings.m_MaximumSize, 5, 100, new GUILayoutOption[0]); + this.WritePreferences(); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + if (Lightmapping.isRunning) + { + GUIContent gUIContent = EditorGUIUtility.TextContent(PreferencesWindow.Styles.cantChangeCacheSettings.text); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, true); + } + GUILayout.EndHorizontal(); + EditorGUI.BeginDisabledGroup(Lightmapping.isRunning); + this.m_GICacheSettings.m_EnableCustomPath = EditorGUILayout.Toggle(PreferencesWindow.Styles.customCacheLocation, this.m_GICacheSettings.m_EnableCustomPath, new GUILayoutOption[0]); + if (this.m_GICacheSettings.m_EnableCustomPath) + { + GUIStyle popup = EditorStyles.popup; + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel(PreferencesWindow.Styles.cacheFolderLocation, popup); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, popup); + GUIContent content = (!string.IsNullOrEmpty(this.m_GICacheSettings.m_CachePath)) ? new GUIContent(this.m_GICacheSettings.m_CachePath) : PreferencesWindow.Styles.browse; + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, popup)) + { + string cachePath = this.m_GICacheSettings.m_CachePath; + string text = EditorUtility.OpenFolderPanel(PreferencesWindow.Styles.browseGICacheLocation.text, cachePath, string.Empty); + if (!string.IsNullOrEmpty(text)) + { + this.m_GICacheSettings.m_CachePath = text; + this.WritePreferences(); + } + } + GUILayout.EndHorizontal(); + } + else + { + this.m_GICacheSettings.m_CachePath = string.Empty; + } + this.m_GICacheSettings.m_CompressionLevel = ((!EditorGUILayout.Toggle(PreferencesWindow.Styles.cacheCompression, this.m_GICacheSettings.m_CompressionLevel == 1, new GUILayoutOption[0])) ? 0 : 1); + if (GUILayout.Button(PreferencesWindow.Styles.cleanCache, new GUILayoutOption[] + { + GUILayout.Width(120f) + })) + { + Lightmapping.Clear(); + Lightmapping.ClearDiskCache(); + } + if (Lightmapping.diskCacheSize >= 0L) + { + GUILayout.Label(PreferencesWindow.Styles.cacheSizeIs.text + " " + EditorUtility.FormatBytes(Lightmapping.diskCacheSize), new GUILayoutOption[0]); + } + else + { + GUILayout.Label(PreferencesWindow.Styles.cacheSizeIs.text + " is being calculated...", new GUILayoutOption[0]); + } + GUILayout.Label(PreferencesWindow.Styles.cacheFolderLocation.text + ":", new GUILayoutOption[0]); + GUILayout.Label(Lightmapping.diskCachePath, PreferencesWindow.constants.cacheFolderLocation, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + } private void WriteRecentAppsList(string[] paths, string path, string prefsKey) { int num = 0; @@ -651,17 +739,22 @@ private void WritePreferences() this.WriteRecentAppsList(this.m_ScriptApps, this.m_ScriptEditorPath, "RecentlyUsedScriptApp"); this.WriteRecentAppsList(this.m_ImageApps, this.m_ImageAppPath, "RecentlyUsedImageApp"); EditorPrefs.SetBool("kAutoRefresh", this.m_AutoRefresh); - EditorPrefs.SetBool("AlwaysShowProjectWizard", this.m_AlwaysShowProjectWizard); + EditorPrefs.SetBool("ReopenLastUsedProjectOnStartup", this.m_ReopenLastUsedProjectOnStartup); EditorPrefs.SetBool("UseOSColorPicker", this.m_UseOSColorPicker); EditorPrefs.SetBool("EnableEditorAnalytics", this.m_EnableEditorAnalytics); EditorPrefs.SetBool("ShowAssetStoreSearchHits", this.m_ShowAssetStoreSearchHits); EditorPrefs.SetBool("VerifySavingAssets", this.m_VerifySavingAssets); EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", this.m_AllowAttachedDebuggingOfEditor); EditorPrefs.SetBool("AllowAlphaNumericHierarchy", this.m_AllowAlphaNumericHierarchy); + EditorPrefs.SetBool("GICacheEnableCustomPath", this.m_GICacheSettings.m_EnableCustomPath); + EditorPrefs.SetInt("GICacheMaximumSizeGB", this.m_GICacheSettings.m_MaximumSize); + EditorPrefs.SetString("GICacheFolder", this.m_GICacheSettings.m_CachePath); + EditorPrefs.SetInt("GICacheCompressionLevel", this.m_GICacheSettings.m_CompressionLevel); foreach (IPreferenceWindowExtension current in this.prefWinExtensions) { current.WritePreferences(); } + Lightmapping.UpdateCachePath(); } private static void SetupDefaultPreferences() { @@ -703,7 +796,7 @@ private void ReadPreferences() this.m_ScriptAppDisplayNames = this.BuildFriendlyAppNameList(this.m_ScriptApps, "MonoDevelop (built-in)"); this.m_ImageAppDisplayNames = this.BuildFriendlyAppNameList(this.m_ImageApps, "Open by file extension"); this.m_DiffTools = InternalEditorUtility.GetAvailableDiffTools(); - if ((this.m_DiffTools == null || this.m_DiffTools.Length == 0) && InternalEditorUtility.HasMaint()) + if ((this.m_DiffTools == null || this.m_DiffTools.Length == 0) && InternalEditorUtility.HasPro()) { this.m_noDiffToolsMessage = InternalEditorUtility.GetNoDiffToolsDetectedMessage(); } @@ -714,11 +807,15 @@ private void ReadPreferences() this.m_DiffToolIndex = 0; } this.m_AutoRefresh = EditorPrefs.GetBool("kAutoRefresh"); - this.m_AlwaysShowProjectWizard = EditorPrefs.GetBool("AlwaysShowProjectWizard"); + this.m_ReopenLastUsedProjectOnStartup = EditorPrefs.GetBool("ReopenLastUsedProjectOnStartup"); this.m_UseOSColorPicker = EditorPrefs.GetBool("UseOSColorPicker"); this.m_EnableEditorAnalytics = EditorPrefs.GetBool("EnableEditorAnalytics", true); this.m_ShowAssetStoreSearchHits = EditorPrefs.GetBool("ShowAssetStoreSearchHits", true); this.m_VerifySavingAssets = EditorPrefs.GetBool("VerifySavingAssets", false); + this.m_GICacheSettings.m_EnableCustomPath = EditorPrefs.GetBool("GICacheEnableCustomPath"); + this.m_GICacheSettings.m_CachePath = EditorPrefs.GetString("GICacheFolder"); + this.m_GICacheSettings.m_MaximumSize = EditorPrefs.GetInt("GICacheMaximumSizeGB"); + this.m_GICacheSettings.m_CompressionLevel = EditorPrefs.GetInt("GICacheCompressionLevel"); this.m_AllowAttachedDebuggingOfEditor = EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true); this.m_AllowAlphaNumericHierarchy = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); this.m_CompressAssetsOnImport = Unsupported.GetApplicationSettingCompressAssetsOnImport(); @@ -755,17 +852,17 @@ private void AppsListClick(object userData, string[] options, int selected) } private void FilePopup(string label, string selectedString, ref string[] names, ref string[] paths, PreferencesWindow.RefString outString, Action onChanged) { - GUIStyle gUIStyle = "MiniPopup"; + GUIStyle popup = EditorStyles.popup; GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PrefixLabel(label, gUIStyle); + EditorGUILayout.PrefixLabel(label, popup); int[] array = new int[] { Array.IndexOf(paths, selectedString) }; GUIContent content = new GUIContent(names[array[0]]); - Rect rect = GUILayoutUtility.GetRect(GUIContent.none, gUIStyle); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, popup); PreferencesWindow.AppsListUserData userData = new PreferencesWindow.AppsListUserData(paths, outString, onChanged); - if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, gUIStyle)) + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, popup)) { ArrayUtility.Add(ref names, "Browse..."); EditorUtility.DisplayCustomMenu(rect, names, array, new EditorUtility.SelectMenuItemFunction(this.AppsListClick), userData); @@ -774,13 +871,13 @@ private void FilePopup(string label, string selectedString, ref string[] names, } private void AndroidSdkLocation() { - GUIStyle gUIStyle = "MiniPopup"; + GUIStyle popup = EditorStyles.popup; GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PrefixLabel("Android SDK Location", gUIStyle); + EditorGUILayout.PrefixLabel("Android SDK Location", popup); string text = (!string.IsNullOrEmpty(this.m_AndroidSdkPath)) ? this.m_AndroidSdkPath : "Browse..."; GUIContent content = new GUIContent(text); - Rect rect = GUILayoutUtility.GetRect(GUIContent.none, gUIStyle); - if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, gUIStyle)) + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, popup); + if (EditorGUI.ButtonMouseDown(rect, content, FocusType.Native, popup)) { string text2 = AndroidSdkRoot.Browse(this.m_AndroidSdkPath); if (!string.IsNullOrEmpty(text2)) diff --git a/UnityEditor/UnityEditor/PresetLibraryEditor.cs b/UnityEditor/UnityEditor/PresetLibraryEditor.cs index 51feb64c..4d0b8c59 100644 --- a/UnityEditor/UnityEditor/PresetLibraryEditor.cs +++ b/UnityEditor/UnityEditor/PresetLibraryEditor.cs @@ -404,12 +404,24 @@ public PresetLibraryEditor(ScriptableObjectSaveLoadHelper helper, PresetLibra this.marginsForGrid = new RectOffset(5, 5, 5, 5); this.m_PresetLibraryFileLocation = PresetLibraryLocations.GetFileLocationFromPath(this.currentLibraryWithoutExtension); } - private void Repaint() + public void InitializeGrid(float availableWidth) { - HandleUtility.Repaint(); + T currentLib = this.GetCurrentLib(); + if (currentLib != null) + { + if (availableWidth > 0f) + { + this.SetupGrid(availableWidth, currentLib.Count()); + } + } + else + { + Debug.LogError("Could not load preset library " + this.currentLibraryWithoutExtension); + } } - private void InitIfNeeded() + private void Repaint() { + HandleUtility.Repaint(); } private void ValidateNoExtension(string value) { @@ -505,7 +517,6 @@ public void OnGUI(Rect rect, object presetObject) { PresetLibraryEditor.s_Styles = new PresetLibraryEditor.Styles(); } - this.InitIfNeeded(); Rect rect2 = new Rect(rect.x, rect.y, rect.width, this.topAreaHeight); Rect rect3 = new Rect(rect.x, rect2.yMax, rect.width, rect.height - this.topAreaHeight); this.TopArea(rect2); diff --git a/UnityEditor/UnityEditor/PreviewBlendTree.cs b/UnityEditor/UnityEditor/PreviewBlendTree.cs index 31c95cfa..fd984c4d 100644 --- a/UnityEditor/UnityEditor/PreviewBlendTree.cs +++ b/UnityEditor/UnityEditor/PreviewBlendTree.cs @@ -1,5 +1,5 @@ using System; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -7,8 +7,8 @@ internal class PreviewBlendTree { private AnimatorController m_Controller; private AvatarPreview m_AvatarPreview; - private StateMachine m_StateMachine; - private State m_State; + private AnimatorStateMachine m_StateMachine; + private AnimatorState m_State; private BlendTree m_BlendTree; private bool m_ControllerIsDirty; private bool m_PrevIKOnFeet; @@ -36,14 +36,9 @@ public void Init(BlendTree blendTree, Animator animator) } public void CreateParameters() { - int parameterCount = this.m_Controller.parameterCount; - for (int i = 0; i < parameterCount; i++) + for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) { - this.m_Controller.RemoveParameter(0); - } - for (int j = 0; j < this.m_BlendTree.recursiveBlendParameterCount; j++) - { - this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(j), AnimatorControllerParameterType.Float); + this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(i), AnimatorControllerParameterType.Float); } } private void CreateStateMachine() @@ -53,17 +48,21 @@ private void CreateStateMachine() if (this.m_Controller == null) { this.m_Controller = new AnimatorController(); - this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("preview"); - this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + this.m_StateMachine = this.m_Controller.layers[0].stateMachine; + this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("preview"); - this.m_State.SetMotionInternal(this.m_BlendTree); + this.m_State.pushUndo = false; + this.m_State.motion = this.m_BlendTree; this.m_State.iKOnFeet = this.m_AvatarPreview.IKOnFeet; - this.m_State.hideFlags = HideFlags.DontSave; + this.m_State.hideFlags = HideFlags.HideAndDontSave; + this.m_Controller.hideFlags = HideFlags.HideAndDontSave; + this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); - AnimatorController expr_D7 = this.m_Controller; - expr_D7.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_D7.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + AnimatorController expr_10F = this.m_Controller; + expr_10F.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_10F.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); this.m_ControllerIsDirty = false; } if (AnimatorController.GetEffectiveAnimatorController(this.m_AvatarPreview.Animator) != this.m_Controller) @@ -118,13 +117,16 @@ private void UpdateAvatarState() { return; } - Animator animator = this.m_AvatarPreview.Animator; - if (animator) + if (this.m_AvatarPreview.PreviewObject == null || this.m_ControllerIsDirty) { - if (this.m_ControllerIsDirty) + this.m_AvatarPreview.ResetPreviewInstance(); + if (this.m_AvatarPreview.PreviewObject) { this.ResetStateMachine(); } + } + if (this.m_AvatarPreview.Animator) + { if (this.m_PrevIKOnFeet != this.m_AvatarPreview.IKOnFeet) { this.m_PrevIKOnFeet = this.m_AvatarPreview.IKOnFeet; @@ -136,21 +138,21 @@ private void UpdateAvatarState() this.m_AvatarPreview.Animator.rootPosition = rootPosition; this.m_AvatarPreview.Animator.rootRotation = rootRotation; } - if (animator) + if (this.m_AvatarPreview.Animator) { for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) { string recursiveBlendParameter = this.m_BlendTree.GetRecursiveBlendParameter(i); float inputBlendValue = this.m_BlendTree.GetInputBlendValue(recursiveBlendParameter); - animator.SetFloat(recursiveBlendParameter, inputBlendValue); + this.m_AvatarPreview.Animator.SetFloat(recursiveBlendParameter, inputBlendValue); } } this.m_AvatarPreview.timeControl.loop = true; float num = 1f; float num2 = 0f; - if (animator.layerCount > 0) + if (this.m_AvatarPreview.Animator.layerCount > 0) { - AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); + AnimatorStateInfo currentAnimatorStateInfo = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(0); num = currentAnimatorStateInfo.length; num2 = currentAnimatorStateInfo.normalizedTime; } @@ -172,7 +174,7 @@ private void UpdateAvatarState() } } } - animator.Update(num3); + this.m_AvatarPreview.Animator.Update(num3); } } public void TestForReset() diff --git a/UnityEditor/UnityEditor/PreviewRenderUtility.cs b/UnityEditor/UnityEditor/PreviewRenderUtility.cs index fbf77577..bef374bc 100644 --- a/UnityEditor/UnityEditor/PreviewRenderUtility.cs +++ b/UnityEditor/UnityEditor/PreviewRenderUtility.cs @@ -1,5 +1,6 @@ using System; using UnityEngine; +using UnityEngine.Rendering; namespace UnityEditor { public class PreviewRenderUtility @@ -20,7 +21,7 @@ public PreviewRenderUtility(bool renderFullScene) { typeof(Camera) }); - this.m_Camera = gameObject.camera; + this.m_Camera = gameObject.GetComponent(); this.m_Camera.fieldOfView = this.m_CameraFieldOfView; this.m_Camera.enabled = false; this.m_Camera.clearFlags = CameraClearFlags.Depth; @@ -39,9 +40,9 @@ public PreviewRenderUtility(bool renderFullScene) { typeof(Light) }); - this.m_Light[i] = gameObject2.light; + this.m_Light[i] = gameObject2.GetComponent(); this.m_Light[i].type = LightType.Directional; - this.m_Light[i].intensity = 0.5f; + this.m_Light[i].intensity = 1f; this.m_Light[i].enabled = false; } this.m_Light[0].color = SceneView.kSceneViewFrontLight; @@ -92,18 +93,16 @@ private void InitPreview(Rect r) UnityEngine.Object.DestroyImmediate(this.m_RenderTextureGammaCorrect); this.m_RenderTextureGammaCorrect = null; } - float a = (float)(Mathf.Max(Mathf.Min(num * 2, 1024), num) / num); - float b = (float)(Mathf.Max(Mathf.Min(num2 * 2, 1024), num2) / num2); - float num3 = Mathf.Min(a, b); + float scaleFactor = this.GetScaleFactor((float)num, (float)num2); bool flag = QualitySettings.activeColorSpace == ColorSpace.Linear; - this.m_RenderTexture = new RenderTexture((int)((float)num * num3), (int)((float)num2 * num3), 16, RenderTextureFormat.ARGB32, (!flag) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB); + this.m_RenderTexture = new RenderTexture((int)((float)num * scaleFactor), (int)((float)num2 * scaleFactor), 16, RenderTextureFormat.ARGB32, (!flag) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB); this.m_RenderTexture.hideFlags = HideFlags.HideAndDontSave; - this.m_RenderTextureGammaCorrect = new RenderTexture((int)((float)num * num3), (int)((float)num2 * num3), 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + this.m_RenderTextureGammaCorrect = new RenderTexture((int)((float)num * scaleFactor), (int)((float)num2 * scaleFactor), 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); this.m_RenderTextureGammaCorrect.hideFlags = HideFlags.HideAndDontSave; this.m_Camera.targetTexture = this.m_RenderTexture; } - float num4 = (this.m_RenderTexture.width > 0) ? Mathf.Max(1f, (float)this.m_RenderTexture.height / (float)this.m_RenderTexture.width) : 1f; - this.m_Camera.fieldOfView = Mathf.Atan(num4 * Mathf.Tan(this.m_CameraFieldOfView * 0.5f * 0.0174532924f)) * 57.29578f * 2f; + float num3 = (this.m_RenderTexture.width > 0) ? Mathf.Max(1f, (float)this.m_RenderTexture.height / (float)this.m_RenderTexture.width) : 1f; + this.m_Camera.fieldOfView = Mathf.Atan(num3 * Mathf.Tan(this.m_CameraFieldOfView * 0.5f * 0.0174532924f)) * 57.29578f * 2f; this.m_SavedState = new SavedRenderTargetState(); EditorGUIUtility.SetRenderTextureNoViewport(this.m_RenderTexture); GL.LoadOrtho(); @@ -112,6 +111,12 @@ private void InitPreview(Rect r) ShaderUtil.rawScissorRect = new Rect(0f, 0f, (float)this.m_RenderTexture.width, (float)this.m_RenderTexture.height); GL.Clear(true, true, new Color(0f, 0f, 0f, 0f)); } + public float GetScaleFactor(float width, float height) + { + float a = Mathf.Max(Mathf.Min(width * 2f, 1024f), width) / width; + float b = Mathf.Max(Mathf.Min(height * 2f, 1024f), height) / height; + return Mathf.Min(a, b); + } public void BeginStaticPreview(Rect r) { this.InitPreview(r); @@ -171,15 +176,40 @@ public Texture2D EndStaticPreview() } public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex) { - Graphics.DrawMesh(mesh, pos, rot, mat, 1, this.m_Camera, subMeshIndex); + this.DrawMesh(mesh, pos, rot, mat, subMeshIndex, null); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material mat, int subMeshIndex) { - Graphics.DrawMesh(mesh, matrix, mat, 1, this.m_Camera, subMeshIndex); + this.DrawMesh(mesh, matrix, mat, subMeshIndex, null); + } + public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties) + { + Graphics.DrawMesh(mesh, pos, rot, mat, 1, this.m_Camera, subMeshIndex, customProperties); + } + public void DrawMesh(Mesh mesh, Vector3 pos, Quaternion rot, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties, Transform probeAnchor) + { + Graphics.DrawMesh(mesh, pos, rot, mat, 1, this.m_Camera, subMeshIndex, customProperties, ShadowCastingMode.Off, false, probeAnchor); + } + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material mat, int subMeshIndex, MaterialPropertyBlock customProperties) + { + Graphics.DrawMesh(mesh, matrix, mat, 1, this.m_Camera, subMeshIndex, customProperties); } public void DrawSprite(Sprite frame, Matrix4x4 matrix, Material mat, Color color) { Graphics.DrawSprite(frame, matrix, mat, 1, this.m_Camera, color, null); } + internal static Mesh GetPreviewSphere() + { + GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); + gameObject.SetActive(false); + foreach (Transform transform in gameObject.transform) + { + if (transform.name == "sphere") + { + return transform.GetComponent().sharedMesh; + } + } + return null; + } } } diff --git a/UnityEditor/UnityEditor/PreviewWindow.cs b/UnityEditor/UnityEditor/PreviewWindow.cs index 9db57ba3..dd13152d 100644 --- a/UnityEditor/UnityEditor/PreviewWindow.cs +++ b/UnityEditor/UnityEditor/PreviewWindow.cs @@ -39,6 +39,7 @@ protected override void OnGUI() Editor.m_AllowMultiObjectAccess = true; this.CreateTracker(); this.CreatePreviewables(); + base.AssignAssetEditor(this.m_Tracker.activeEditors); IPreviewable[] editorsWithPreviews = base.GetEditorsWithPreviews(this.m_Tracker.activeEditors); IPreviewable editorThatControlsPreview = base.GetEditorThatControlsPreview(editorsWithPreviews); bool flag = editorThatControlsPreview != null && editorThatControlsPreview.HasPreviewGUI(); diff --git a/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs b/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs index fefc996e..5379e2a7 100644 --- a/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs +++ b/UnityEditor/UnityEditor/ProceduralMaterialInspector.cs @@ -454,6 +454,7 @@ private void GeneratedTextures() { this.OffsetScaleGUI(ProceduralMaterialInspector.m_Material); } + GUILayout.Space(5f); EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); this.ShowTextureSizeGUI(); EditorGUI.EndDisabledGroup(); @@ -521,65 +522,21 @@ protected void OffsetScaleGUI(ProceduralMaterial material) { return; } - GUILayoutOption gUILayoutOption = GUILayout.Width(10f); - GUILayoutOption gUILayoutOption2 = GUILayout.MinWidth(32f); - GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.BeginVertical(new GUILayoutOption[0]); Vector2 materialScale = ProceduralMaterialInspector.m_Importer.GetMaterialScale(material); - Vector2 lhs = materialScale; Vector2 materialOffset = ProceduralMaterialInspector.m_Importer.GetMaterialOffset(material); - Vector2 lhs2 = materialOffset; - GUILayout.BeginHorizontal(new GUILayoutOption[] - { - GUILayout.ExpandWidth(true) - }); - GUILayout.Space(8f); - GUILayout.FlexibleSpace(); - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.Label(string.Empty, EditorStyles.miniLabel, new GUILayoutOption[] - { - gUILayoutOption - }); - GUILayout.Label("x", EditorStyles.miniLabel, new GUILayoutOption[] - { - gUILayoutOption - }); - GUILayout.Label("y", EditorStyles.miniLabel, new GUILayoutOption[] - { - gUILayoutOption - }); - GUILayout.EndVertical(); - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.Label("Tiling", EditorStyles.miniLabel, new GUILayoutOption[0]); - materialScale.x = EditorGUILayout.FloatField(materialScale.x, EditorStyles.miniTextField, new GUILayoutOption[] - { - gUILayoutOption2 - }); - materialScale.y = EditorGUILayout.FloatField(materialScale.y, EditorStyles.miniTextField, new GUILayoutOption[] - { - gUILayoutOption2 - }); - GUILayout.EndVertical(); - GUILayout.BeginVertical(new GUILayoutOption[0]); - GUILayout.Label("Offset", EditorStyles.miniLabel, new GUILayoutOption[0]); - materialOffset.x = EditorGUILayout.FloatField(materialOffset.x, EditorStyles.miniTextField, new GUILayoutOption[] - { - gUILayoutOption2 - }); - materialOffset.y = EditorGUILayout.FloatField(materialOffset.y, EditorStyles.miniTextField, new GUILayoutOption[] - { - gUILayoutOption2 - }); - GUILayout.EndVertical(); + Vector4 scaleOffset = new Vector4(materialScale.x, materialScale.y, materialOffset.x, materialOffset.y); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(10f); + Rect rect = GUILayoutUtility.GetRect(100f, 10000f, 32f, 32f); GUILayout.EndHorizontal(); - if (lhs != materialScale || lhs2 != materialOffset) + EditorGUI.BeginChangeCheck(); + scaleOffset = MaterialEditor.TextureScaleOffsetProperty(rect, scaleOffset); + if (EditorGUI.EndChangeCheck()) { this.RecordForUndo(material, ProceduralMaterialInspector.m_Importer, "Modify " + material.name + "'s Tiling/Offset"); - ProceduralMaterialInspector.m_Importer.SetMaterialOffset(material, materialOffset); - ProceduralMaterialInspector.m_Importer.SetMaterialScale(material, materialScale); + ProceduralMaterialInspector.m_Importer.SetMaterialScale(material, new Vector2(scaleOffset.x, scaleOffset.y)); + ProceduralMaterialInspector.m_Importer.SetMaterialOffset(material, new Vector2(scaleOffset.z, scaleOffset.w)); } - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); } protected void InputOptions(ProceduralMaterial material) { @@ -674,7 +631,6 @@ protected void ShowProceduralTexturesGUI(ProceduralMaterial material) } GUILayout.Space(4f); EditorGUILayout.EndHorizontal(); - GUILayout.FlexibleSpace(); } protected void ShowGeneratedTexturesGUI(ProceduralMaterial material) { @@ -737,7 +693,12 @@ private void ShowAlphaSourceGUI(ProceduralMaterial material, ProceduralTexture t "Height (A)", "Emissive (A)", "Specular (A)", - "Opacity (A)" + "Opacity (A)", + "Smoothness (A)", + "Amb. Occlusion (A)", + "Detail Mask (A)", + "Metallic (A)", + "Roughness (A)" }; EditorGUILayout.Space(); EditorGUILayout.Space(); diff --git a/UnityEditor/UnityEditor/ProceduralTextureInspector.cs b/UnityEditor/UnityEditor/ProceduralTextureInspector.cs index 85c825aa..7cfe6777 100644 --- a/UnityEditor/UnityEditor/ProceduralTextureInspector.cs +++ b/UnityEditor/UnityEditor/ProceduralTextureInspector.cs @@ -7,8 +7,9 @@ namespace UnityEditor internal class ProceduralTextureInspector : TextureInspector { private bool m_MightHaveModified; - public void OnDisable() + protected override void OnDisable() { + base.OnDisable(); if (!EditorApplication.isPlaying && !InternalEditorUtility.ignoreInspectorChanges && this.m_MightHaveModified) { this.m_MightHaveModified = false; diff --git a/UnityEditor/UnityEditor/ProfilerChoise.cs b/UnityEditor/UnityEditor/ProfilerChoise.cs new file mode 100644 index 00000000..c92c303d --- /dev/null +++ b/UnityEditor/UnityEditor/ProfilerChoise.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + internal struct ProfilerChoise + { + public string Name; + public bool Enabled; + public Func IsSelected; + public Action ConnectTo; + } +} diff --git a/UnityEditor/UnityEditor/ProfilerWindow.cs b/UnityEditor/UnityEditor/ProfilerWindow.cs index 97504606..7e3c48e8 100644 --- a/UnityEditor/UnityEditor/ProfilerWindow.cs +++ b/UnityEditor/UnityEditor/ProfilerWindow.cs @@ -13,6 +13,8 @@ internal class Styles public GUIContent profileEditor = EditorGUIUtility.TextContent("Profiler.ProfileEditor"); public GUIContent noData = EditorGUIUtility.TextContent("Profiler.NoFrameDataAvailable"); public GUIContent noLicense = EditorGUIUtility.TextContent("Profiler.NoLicense"); + public GUIContent frameDebugger = EditorGUIUtility.TextContent("Profiler.FrameDebugger"); + public GUIContent noFrameDebugger = EditorGUIUtility.TextContent("Profiler.NoFrameDebugger"); public GUIContent profilerRecord = EditorGUIUtility.TextContent("Profiler.Record"); public GUIContent prevFrame = EditorGUIUtility.IconContent("Profiler.PrevFrame"); public GUIContent nextFrame = EditorGUIUtility.IconContent("Profiler.NextFrame"); @@ -46,8 +48,10 @@ public Styles() private const string kProfilerGPUColumnSettings = "VisibleProfilerGPUColumns"; private const string kProfilerGPUDetailColumnSettings = "VisibleProfilerGPUDetailColumns"; private const string kProfilerVisibleGraphsSettings = "VisibleProfilerGraphs"; - internal const string kPrefCharts = "ProfilerChart"; + private const string kSearchControlName = "ProfilerSearchField"; private static ProfilerWindow.Styles ms_Styles; + private bool m_FocusSearchField; + private string m_SearchString = string.Empty; private bool m_HasProfilerLicense; private SplitterState m_VertSplit = new SplitterState(new float[] { @@ -69,16 +73,19 @@ public Styles() }, null); [SerializeField] private bool m_Recording = true; - private AttachProfilerUI m_AttachProfilerUI = default(AttachProfilerUI); + private AttachProfilerUI m_AttachProfilerUI = new AttachProfilerUI(); private Vector2 m_GraphPos = Vector2.zero; private Vector2[] m_PaneScroll = new Vector2[7]; + private string m_ActiveNativePlatformSupportModule; private static List m_ProfilerWindows = new List(); private ProfilerViewType m_ViewType; private ProfilerArea m_CurrentArea; private ProfilerMemoryView m_ShowDetailedMemoryPane; + private ProfilerAudioView m_ShowDetailedAudioPane; private int m_CurrentFrame = -1; private int m_LastFrameFromTick = -1; private int m_PrevLastFrame = -1; + private int m_LastAudioProfilerFrame = -1; private ProfilerChart[] m_Charts; private float[] m_ChartOldMax = new float[] { @@ -93,6 +100,11 @@ public Styles() private ProfilerTimelineGUI m_CPUTimelineGUI; private MemoryTreeList m_ReferenceListView; private MemoryTreeListClickable m_MemoryListView; + [SerializeField] + private AudioProfilerTreeViewState m_AudioProfilerTreeViewState; + private AudioProfilerView m_AudioProfilerView; + private AudioProfilerBackend m_AudioProfilerBackend; + private static readonly int s_HashControlID = "ProfilerSearchField".GetHashCode(); private bool wantsMemoryRefresh { get @@ -183,10 +195,30 @@ public ProfilerProperty CreateProperty(bool details) profilerProperty.onlyShowGPUSamples = (this.m_CurrentArea == ProfilerArea.GPU); return profilerProperty; } + public int GetActiveVisibleFrameIndex() + { + return (this.m_CurrentFrame != -1) ? this.m_CurrentFrame : this.m_LastFrameFromTick; + } + public void SetSearch(string searchString) + { + this.m_SearchString = ((!string.IsNullOrEmpty(searchString)) ? searchString : string.Empty); + } + public string GetSearch() + { + return this.m_SearchString; + } + public bool IsSearching() + { + return !string.IsNullOrEmpty(this.m_SearchString) && this.m_SearchString.Length > 0; + } private void OnEnable() { ProfilerWindow.m_ProfilerWindows.Add(this); - this.m_HasProfilerLicense = InternalEditorUtility.HasPro(); + this.m_HasProfilerLicense = InternalEditorUtility.HasProFeaturesEnabled(); + this.Initialize(); + } + private void Initialize() + { int len = ProfilerDriver.maxHistoryLength - 1; this.m_Charts = new ProfilerChart[7]; Color[] colors = ProfilerColors.colors; @@ -225,6 +257,15 @@ private void OnEnable() profilerChart2.LoadAndBindSettings(); } } + private void CheckForPlatformModuleChange() + { + if (this.m_ActiveNativePlatformSupportModule != EditorUtility.GetActiveNativePlatformSupportModuleName()) + { + ProfilerDriver.ResetHistory(); + this.Initialize(); + this.m_ActiveNativePlatformSupportModule = EditorUtility.GetActiveNativePlatformSupportModuleName(); + } + } private void OnDisable() { ProfilerWindow.m_ProfilerWindows.Remove(this); @@ -344,43 +385,89 @@ private static void DrawEmptyCPUOrRenderingDetailPane() private void DrawCPUOrRenderingToolbar(ProfilerProperty property) { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); - string[] displayedOptions; - int[] optionValues; - if (!Unsupported.IsDeveloperBuild()) + string[] displayedOptions = new string[] { - displayedOptions = new string[] - { - "Hierarchy", - "Raw Hierarchy" - }; - optionValues = new int[] - { - 0, - 2 - }; - } - else + "Hierarchy", + "Timeline", + "Raw Hierarchy" + }; + int[] optionValues = new int[] { - displayedOptions = new string[] - { - "Hierarchy", - "Timeline", - "Raw Hierarchy" - }; - optionValues = new int[] - { - 0, - 1, - 2 - }; - } + 0, + 1, + 2 + }; this.m_ViewType = (ProfilerViewType)EditorGUILayout.IntPopup((int)this.m_ViewType, displayedOptions, optionValues, EditorStyles.toolbarDropDown, new GUILayoutOption[] { GUILayout.Width(100f) }); GUILayout.FlexibleSpace(); GUILayout.Label(string.Format("CPU:{0}ms GPU:{1}ms", property.frameTime, property.frameGpuTime), EditorStyles.miniLabel, new GUILayoutOption[0]); + GUI.enabled = (ProfilerDriver.GetNextFrameIndex(this.m_CurrentFrame) == -1); + if (GUILayout.Button((!GUI.enabled) ? ProfilerWindow.ms_Styles.noFrameDebugger : ProfilerWindow.ms_Styles.frameDebugger, EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + FrameDebuggerWindow frameDebuggerWindow = FrameDebuggerWindow.ShowFrameDebuggerWindow(); + frameDebuggerWindow.EnableIfNeeded(); + } + GUI.enabled = true; + GUILayout.FlexibleSpace(); + this.SearchFieldGUI(); EditorGUILayout.EndHorizontal(); + this.HandleCommandEvents(); + } + private void HandleCommandEvents() + { + Event current = Event.current; + EventType type = current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + if (Event.current.commandName == "Find") + { + if (flag) + { + this.m_FocusSearchField = true; + } + current.Use(); + } + } + } + internal void SearchFieldGUI() + { + Event current = Event.current; + Rect rect = GUILayoutUtility.GetRect(50f, 300f, 16f, 16f, EditorStyles.toolbarSearchField); + if (this.m_ViewType == ProfilerViewType.Timeline) + { + return; + } + GUI.SetNextControlName("ProfilerSearchField"); + if (this.m_FocusSearchField) + { + EditorGUI.FocusTextInControl("ProfilerSearchField"); + if (Event.current.type == EventType.Repaint) + { + this.m_FocusSearchField = false; + } + } + if (current.type == EventType.KeyDown && current.keyCode == KeyCode.Escape && GUI.GetNameOfFocusedControl() == "ProfilerSearchField") + { + this.m_SearchString = string.Empty; + } + if (current.type == EventType.KeyDown && (current.keyCode == KeyCode.DownArrow || current.keyCode == KeyCode.UpArrow) && GUI.GetNameOfFocusedControl() == "ProfilerSearchField") + { + this.m_CPUHierarchyGUI.SelectFirstRow(); + this.m_CPUHierarchyGUI.SetKeyboardFocus(); + base.Repaint(); + current.Use(); + } + bool flag = this.m_CPUHierarchyGUI.selectedIndex != -1; + EditorGUI.BeginChangeCheck(); + int controlID = GUIUtility.GetControlID(ProfilerWindow.s_HashControlID, FocusType.Keyboard, base.position); + this.m_SearchString = EditorGUI.ToolbarSearchField(controlID, rect, this.m_SearchString, false); + if (EditorGUI.EndChangeCheck() && !this.IsSearching() && GUIUtility.keyboardControl == 0 && flag) + { + this.m_CPUHierarchyGUI.FrameSelection(); + } } private static bool CheckFrameData(ProfilerProperty property) { @@ -412,7 +499,7 @@ private void DrawCPUOrRenderingPane(ProfilerHierarchyGUI mainPane, ProfilerHiera SplitterGUILayout.BeginHorizontalSplit(this.m_ViewSplit, new GUILayoutOption[0]); GUILayout.BeginVertical(new GUILayoutOption[0]); bool expandAll = false; - mainPane.DoGUI(profilerProperty, expandAll); + mainPane.DoGUI(profilerProperty, this.m_SearchString, expandAll); profilerProperty.Cleanup(); GUILayout.EndVertical(); GUILayout.BeginVertical(new GUILayoutOption[0]); @@ -421,7 +508,7 @@ private void DrawCPUOrRenderingPane(ProfilerHierarchyGUI mainPane, ProfilerHiera profilerProperty2.Cleanup(); if (detailedProperty != null) { - detailPane.DoGUI(detailedProperty, expandAll); + detailPane.DoGUI(detailedProperty, string.Empty, expandAll); detailedProperty.Cleanup(); } else @@ -458,6 +545,114 @@ private static Rect GenerateRect(ref int row, int indent) row++; return result; } + private void DrawAudioPane() + { + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); + ProfilerAudioView profilerAudioView = this.m_ShowDetailedAudioPane; + if (GUILayout.Toggle(profilerAudioView == ProfilerAudioView.Stats, "Stats", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + profilerAudioView = ProfilerAudioView.Stats; + } + if (GUILayout.Toggle(profilerAudioView == ProfilerAudioView.Channels, "Channels", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + profilerAudioView = ProfilerAudioView.Channels; + } + if (GUILayout.Toggle(profilerAudioView == ProfilerAudioView.Groups, "Groups", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + profilerAudioView = ProfilerAudioView.Groups; + } + if (GUILayout.Toggle(profilerAudioView == ProfilerAudioView.ChannelsAndGroups, "Channels and groups", EditorStyles.toolbarButton, new GUILayoutOption[0])) + { + profilerAudioView = ProfilerAudioView.ChannelsAndGroups; + } + if (profilerAudioView != this.m_ShowDetailedAudioPane) + { + this.m_ShowDetailedAudioPane = profilerAudioView; + this.m_LastAudioProfilerFrame = -1; + } + if (this.m_ShowDetailedAudioPane == ProfilerAudioView.Stats) + { + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + this.DrawOverviewText(this.m_CurrentArea); + } + else + { + GUILayout.Space(5f); + bool flag = GUILayout.Toggle(AudioUtil.resetAllAudioClipPlayCountsOnPlay, "Reset play count on play", EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (flag != AudioUtil.resetAllAudioClipPlayCountsOnPlay) + { + AudioUtil.resetAllAudioClipPlayCountsOnPlay = flag; + } + if (Unsupported.IsDeveloperBuild()) + { + GUILayout.Space(5f); + bool @bool = EditorPrefs.GetBool("AudioProfilerShowAllGroups"); + bool flag2 = GUILayout.Toggle(@bool, "Show all groups (dev-builds only)", EditorStyles.toolbarButton, new GUILayoutOption[0]); + if (@bool != flag2) + { + EditorPrefs.SetBool("AudioProfilerShowAllGroups", flag2); + } + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + Rect rect = GUILayoutUtility.GetRect(20f, 20000f, 10f, 10000f); + Rect position = new Rect(rect.x, rect.y, 230f, rect.height); + Rect rect2 = new Rect(position.xMax, rect.y, rect.width - position.width, rect.height); + string overviewText = ProfilerDriver.GetOverviewText(this.m_CurrentArea, this.GetActiveVisibleFrameIndex()); + Vector2 vector = EditorStyles.wordWrappedLabel.CalcSize(GUIContent.Temp(overviewText)); + this.m_PaneScroll[(int)this.m_CurrentArea] = GUI.BeginScrollView(position, this.m_PaneScroll[(int)this.m_CurrentArea], new Rect(0f, 0f, vector.x, vector.y)); + GUI.Box(position, string.Empty, ProfilerWindow.ms_Styles.background); + GUI.Label(new Rect(3f, 3f, vector.x, vector.y), overviewText, EditorStyles.wordWrappedLabel); + GUI.EndScrollView(); + EditorGUI.DrawRect(new Rect(position.xMax - 1f, position.y, 1f, position.height), Color.black); + if (this.m_AudioProfilerTreeViewState == null) + { + this.m_AudioProfilerTreeViewState = new AudioProfilerTreeViewState(); + } + if (this.m_AudioProfilerBackend == null) + { + this.m_AudioProfilerBackend = new AudioProfilerBackend(this.m_AudioProfilerTreeViewState); + } + ProfilerProperty profilerProperty = this.CreateProperty(false); + if (ProfilerWindow.CheckFrameData(profilerProperty)) + { + if (this.m_CurrentFrame == -1 || this.m_LastAudioProfilerFrame != this.m_CurrentFrame) + { + this.m_LastAudioProfilerFrame = this.m_CurrentFrame; + AudioProfilerInfo[] audioProfilerInfo = profilerProperty.GetAudioProfilerInfo(); + if (audioProfilerInfo != null && audioProfilerInfo.Length > 0) + { + List list = new List(); + AudioProfilerInfo[] array = audioProfilerInfo; + for (int i = 0; i < array.Length; i++) + { + AudioProfilerInfo info = array[i]; + bool flag3 = (info.flags & 64) != 0; + if (this.m_ShowDetailedAudioPane != ProfilerAudioView.Channels || !flag3) + { + if (this.m_ShowDetailedAudioPane != ProfilerAudioView.Groups || flag3) + { + list.Add(new AudioProfilerInfoWrapper(info, profilerProperty.GetAudioProfilerNameByOffset(info.assetNameOffset), profilerProperty.GetAudioProfilerNameByOffset(info.objectNameOffset), this.m_ShowDetailedAudioPane == ProfilerAudioView.Channels)); + } + } + } + this.m_AudioProfilerBackend.SetData(list); + if (this.m_AudioProfilerView == null) + { + this.m_AudioProfilerView = new AudioProfilerView(this, this.m_AudioProfilerTreeViewState); + this.m_AudioProfilerView.Init(rect2, this.m_AudioProfilerBackend); + } + } + } + if (this.m_AudioProfilerView != null) + { + this.m_AudioProfilerView.OnGUI(rect2, this.m_ShowDetailedAudioPane == ProfilerAudioView.Channels); + } + } + profilerProperty.Cleanup(); + } + } private static void DrawBackground(int row, bool selected) { Rect position = new Rect(1f, 16f * (float)row, GUIClip.visibleRect.width, 16f); @@ -591,6 +786,7 @@ private void UpdateCharts() int statisticsIdentifier = ProfilerDriver.GetStatisticsIdentifier(profilerChart.m_Series[j].identifierName); float num4; ProfilerDriver.GetStatisticsValues(statisticsIdentifier, num2, profilerChart.m_DataScale, profilerChart.m_Series[j].data, out num4); + num4 = Mathf.Max(num4, 0.0001f); float num5; if (profilerChart.m_Type == Chart.ChartType.Line) { @@ -695,8 +891,7 @@ private void UpdateCharts() } private void AddAreaClick(object userData, string[] options, int selected) { - this.m_Charts[selected].m_Active = true; - EditorPrefs.SetBool("ProfilerChart" + (ProfilerArea)selected, true); + this.m_Charts[selected].active = true; } private void DrawMainToolbar() { @@ -713,7 +908,7 @@ private void DrawMainToolbar() for (int i = 0; i < num; i++) { array[i] = ((ProfilerArea)i).ToString(); - array2[i] = !this.m_Charts[i].m_Active; + array2[i] = !this.m_Charts[i].active; } EditorUtility.DisplayCustomMenu(rect, array, array2, null, new EditorUtility.SelectMenuItemFunction(this.AddAreaClick), null); } @@ -761,10 +956,6 @@ private void FrameNavigationControls() this.m_LastFrameFromTick = ProfilerDriver.lastFrameIndex; } } - private int GetActiveVisibleFrameIndex() - { - return (this.m_CurrentFrame != -1) ? this.m_CurrentFrame : this.m_LastFrameFromTick; - } private static void DrawOtherToolbar() { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); @@ -796,6 +987,7 @@ private void SetCurrentFrame(int frame) } private void OnGUI() { + this.CheckForPlatformModuleChange(); if (ProfilerWindow.ms_Styles == null) { ProfilerWindow.ms_Styles = new ProfilerWindow.Styles(); @@ -818,7 +1010,7 @@ private void OnGUI() for (int i = 0; i < this.m_Charts.Length; i++) { ProfilerChart profilerChart = this.m_Charts[i]; - if (profilerChart.m_Active) + if (profilerChart.active) { num = profilerChart.DoChartGUI(num, this.m_CurrentArea, out array[i]); } @@ -832,7 +1024,7 @@ private void OnGUI() for (int j = 0; j < this.m_Charts.Length; j++) { ProfilerChart profilerChart2 = this.m_Charts[j]; - if (profilerChart2.m_Active) + if (profilerChart2.active) { if (array[j] == Chart.ChartAction.Closed) { @@ -840,8 +1032,7 @@ private void OnGUI() { this.m_CurrentArea = ProfilerArea.CPU; } - profilerChart2.m_Active = false; - EditorPrefs.SetBool("ProfilerChart" + (ProfilerArea)j, false); + profilerChart2.active = false; } else { @@ -868,16 +1059,19 @@ private void OnGUI() { case ProfilerArea.CPU: this.DrawCPUOrRenderingPane(this.m_CPUHierarchyGUI, this.m_CPUDetailHierarchyGUI, this.m_CPUTimelineGUI); - goto IL_257; + goto IL_255; case ProfilerArea.GPU: this.DrawCPUOrRenderingPane(this.m_GPUHierarchyGUI, this.m_GPUDetailHierarchyGUI, null); - goto IL_257; + goto IL_255; case ProfilerArea.Memory: this.DrawMemoryPane(this.m_ViewSplit); - goto IL_257; + goto IL_255; + case ProfilerArea.Audio: + this.DrawAudioPane(); + goto IL_255; } this.DrawPane(this.m_CurrentArea); - IL_257: + IL_255: GUILayout.EndVertical(); SplitterGUILayout.EndVerticalSplit(); } diff --git a/UnityEditor/UnityEditor/ProjectBrowser.cs b/UnityEditor/UnityEditor/ProjectBrowser.cs index 66d8d230..b1c7250e 100644 --- a/UnityEditor/UnityEditor/ProjectBrowser.cs +++ b/UnityEditor/UnityEditor/ProjectBrowser.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; @@ -83,26 +82,20 @@ private BreadCrumbListMenu(string subFolder) { this.m_SubFolder = subFolder; } - public static List GetSubFolders(string folder) - { - if (Directory.Exists(folder)) - { - return new List(Directory.GetDirectories(folder)); - } - return new List(); - } internal static void Show(string folder, string currentSubFolder, Rect activatorRect, ProjectBrowser caller) { ProjectBrowser.BreadCrumbListMenu.m_Caller = caller; - List subFolders = ProjectBrowser.BreadCrumbListMenu.GetSubFolders(folder); + string[] subFolders = AssetDatabase.GetSubFolders(folder); GenericMenu genericMenu = new GenericMenu(); - if (subFolders.Count >= 0) + if (subFolders.Length >= 0) { currentSubFolder = Path.GetFileName(currentSubFolder); - foreach (string current in subFolders) + string[] array = subFolders; + for (int i = 0; i < array.Length; i++) { - string fileName = Path.GetFileName(current); - genericMenu.AddItem(new GUIContent(fileName), fileName == currentSubFolder, new GenericMenu.MenuFunction(new ProjectBrowser.BreadCrumbListMenu(current).SelectSubFolder)); + string text = array[i]; + string fileName = Path.GetFileName(text); + genericMenu.AddItem(new GUIContent(fileName), fileName == currentSubFolder, new GenericMenu.MenuFunction(new ProjectBrowser.BreadCrumbListMenu(text).SelectSubFolder)); genericMenu.ShowAsContext(); } } @@ -338,17 +331,18 @@ private void EnsureValidFolders() } else { - if (!string.IsNullOrEmpty(text)) + string text2 = text; + for (int j = 0; j < 30; j++) { - string text2 = text; - for (int j = 0; j < 30; j++) + if (string.IsNullOrEmpty(text2)) { - text2 = Path.GetDirectoryName(text2); - if (!string.IsNullOrEmpty(text2) && Directory.Exists(text2)) - { - hashSet.Add(text2); - break; - } + break; + } + text2 = Path.GetDirectoryName(text2); + if (!string.IsNullOrEmpty(text2) && Directory.Exists(text2)) + { + hashSet.Add(text2); + break; } } } @@ -446,6 +440,16 @@ public void Init() this.RefreshSearchText(); this.DefaultSetup(); } + public void SetSearch(string searchString) + { + this.SetSearch(SearchFilter.CreateSearchFilterFromString(searchString)); + } + public void SetSearch(SearchFilter searchFilter) + { + this.m_SearchFilter = searchFilter; + this.m_SearchFieldText = searchFilter.FilterToSearchFieldString(); + this.TopBarSearchSettingsChanged(); + } private void SetSearchViewState(ProjectBrowser.SearchViewState state) { switch (state) @@ -629,7 +633,7 @@ private void InitViewMode(ProjectBrowser.ViewMode viewMode) string guid = AssetDatabase.AssetPathToGUID("Assets"); AssetsTreeViewDataSource assetsTreeViewDataSource = new AssetsTreeViewDataSource(this.m_AssetTree, AssetDatabase.GetInstanceIDFromGUID(guid), false, false); assetsTreeViewDataSource.foldersFirst = this.GetShouldShowFoldersFirst(); - this.m_AssetTree.Init(this.m_TreeViewRect, assetsTreeViewDataSource, new AssetsTreeViewGUI(this.m_AssetTree), new AssetOrGameObjectTreeViewDragging(this.m_AssetTree, HierarchyType.Assets)); + this.m_AssetTree.Init(this.m_TreeViewRect, assetsTreeViewDataSource, new AssetsTreeViewGUI(this.m_AssetTree), new AssetsTreeViewDragging(this.m_AssetTree)); this.m_AssetTree.ReloadData(); } else @@ -638,14 +642,14 @@ private void InitViewMode(ProjectBrowser.ViewMode viewMode) { this.m_FolderTree = new TreeView(this, this.m_FolderTreeState); this.m_FolderTree.deselectOnUnhandledMouseDown = false; - TreeView expr_1C3 = this.m_FolderTree; - expr_1C3.selectionChangedCallback = (Action)Delegate.Combine(expr_1C3.selectionChangedCallback, new Action(this.FolderTreeSelectionCallback)); - TreeView expr_1EA = this.m_FolderTree; - expr_1EA.contextClickCallback = (Action)Delegate.Combine(expr_1EA.contextClickCallback, new Action(this.FolderTreeViewContextClick)); - TreeView expr_211 = this.m_FolderTree; - expr_211.onGUIRowCallback = (Action)Delegate.Combine(expr_211.onGUIRowCallback, new Action(this.OnGUIAssetCallback)); - TreeView expr_238 = this.m_FolderTree; - expr_238.dragEndedCallback = (Action)Delegate.Combine(expr_238.dragEndedCallback, new Action(this.FolderTreeDragEnded)); + TreeView expr_1C2 = this.m_FolderTree; + expr_1C2.selectionChangedCallback = (Action)Delegate.Combine(expr_1C2.selectionChangedCallback, new Action(this.FolderTreeSelectionCallback)); + TreeView expr_1E9 = this.m_FolderTree; + expr_1E9.contextClickCallback = (Action)Delegate.Combine(expr_1E9.contextClickCallback, new Action(this.FolderTreeViewContextClick)); + TreeView expr_210 = this.m_FolderTree; + expr_210.onGUIRowCallback = (Action)Delegate.Combine(expr_210.onGUIRowCallback, new Action(this.OnGUIAssetCallback)); + TreeView expr_237 = this.m_FolderTree; + expr_237.dragEndedCallback = (Action)Delegate.Combine(expr_237.dragEndedCallback, new Action(this.FolderTreeDragEnded)); this.m_FolderTree.Init(this.m_TreeViewRect, new ProjectBrowserColumnOneTreeViewDataSource(this.m_FolderTree), new ProjectBrowserColumnOneTreeViewGUI(this.m_FolderTree), new ProjectBrowserColumnOneTreeViewDragging(this.m_FolderTree)); this.m_FolderTree.ReloadData(); } @@ -693,6 +697,7 @@ private string[] GetTypesDisplayNames() { "AnimationClip", "AudioClip", + "AudioMixer", "Font", "GUISkin", "Material", @@ -1408,7 +1413,6 @@ private bool HandleCommandEventsForTreeView() { if (itemType == ProjectBrowser.ItemType.SavedFilter) { - Assert.That(selection.Length == 1); ProjectBrowser.DeleteFilter(selection[0]); } else @@ -1479,7 +1483,7 @@ private bool HandleCommandEvents() if (flag) { Event.current.Use(); - BaseProjectWindow.DuplicateSelectedAssets(); + ProjectWindowUtil.DuplicateSelectedAssets(); GUIUtility.ExitGUI(); } else @@ -1734,7 +1738,6 @@ private void OnGUI() GUIUtility.keyboardControl = this.m_TreeViewKeyboardControlID; } this.m_AssetTree.OnGUI(this.m_TreeViewRect, this.m_TreeViewKeyboardControlID); - ProjectBrowser.HandleUnusedAssetDragEvents(this.m_TreeViewRect); } } else @@ -1748,21 +1751,14 @@ private void OnGUI() this.BreadCrumbBar(); } this.m_FolderTree.OnGUI(this.m_TreeViewRect, this.m_TreeViewKeyboardControlID); - if (current.type == EventType.Repaint) - { - Color color = GUI.color; - GUI.color *= ((!EditorGUIUtility.isProSkin) ? new Color(0.6f, 0.6f, 0.6f, 1.333f) : new Color(0.12f, 0.12f, 0.12f, 1.333f)); - Rect position2 = new Rect(this.m_ListAreaRect.x - 1f, this.m_ToolbarHeight, 1f, this.m_TreeViewRect.height); - GUI.DrawTexture(position2, EditorGUIUtility.whiteTexture); - GUI.color = color; - } + EditorGUIUtility.DrawHorizontalSplitter(new Rect(this.m_ListAreaRect.x, this.m_ToolbarHeight, 1f, this.m_TreeViewRect.height)); this.m_ListArea.OnGUI(this.m_ListAreaRect, this.m_ListKeyboardControlID); if (this.m_SearchFilter.GetState() == SearchFilter.State.FolderBrowsing && this.m_ListArea.numItemsDisplayed == 0) { Vector2 vector = EditorStyles.label.CalcSize(ProjectBrowser.s_Styles.m_EmptyFolderText); - Rect position3 = new Rect(this.m_ListAreaRect.x + 2f + Mathf.Max(0f, (this.m_ListAreaRect.width - vector.x) * 0.5f), this.m_ListAreaRect.y + 10f, vector.x, 20f); + Rect position2 = new Rect(this.m_ListAreaRect.x + 2f + Mathf.Max(0f, (this.m_ListAreaRect.width - vector.x) * 0.5f), this.m_ListAreaRect.y + 10f, vector.x, 20f); EditorGUI.BeginDisabledGroup(true); - GUI.Label(position3, ProjectBrowser.s_Styles.m_EmptyFolderText, EditorStyles.label); + GUI.Label(position2, ProjectBrowser.s_Styles.m_EmptyFolderText, EditorStyles.label); EditorGUI.EndDisabledGroup(); } } @@ -1818,30 +1814,9 @@ private void HandleContextClickInListArea(Rect listRect) } } } - private static void HandleUnusedAssetDragEvents(Rect rect) - { - Event current = Event.current; - EventType type = current.type; - if (type == EventType.DragUpdated || type == EventType.DragPerform) - { - if (rect.Contains(current.mousePosition)) - { - int assetsFolderInstanceID = ProjectBrowserColumnOneTreeViewDataSource.GetAssetsFolderInstanceID(); - HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); - if (!hierarchyProperty.Find(assetsFolderInstanceID, null)) - { - hierarchyProperty = null; - } - bool perform = current.type == EventType.DragPerform; - DragAndDrop.visualMode = InternalEditorUtility.ProjectWindowDrag(hierarchyProperty, perform); - current.Use(); - } - } - } private void AssetTreeViewContextClick(int clickedNodeInstanceID) { Event current = Event.current; - Assert.That(current.type == EventType.ContextClick); if (clickedNodeInstanceID == 0 && this.m_AssetTree.GetSelection().Length > 0) { int[] array = new int[0]; @@ -1854,7 +1829,6 @@ private void AssetTreeViewContextClick(int clickedNodeInstanceID) private void FolderTreeViewContextClick(int clickedNodeInstanceID) { Event current = Event.current; - Assert.That(current.type == EventType.ContextClick); if (SavedSearchFilters.IsSavedFilter(clickedNodeInstanceID)) { if (clickedNodeInstanceID != SavedSearchFilters.GetRootInstanceID()) @@ -1925,7 +1899,7 @@ public virtual void AddItemsToMenu(GenericMenu menu) if (this.m_EnableOldAssetTree) { GUIContent content = new GUIContent("One Column Layout"); - GUIContent content2 = new GUIContent("Two Columns Layout"); + GUIContent content2 = new GUIContent("Two Column Layout"); menu.AddItem(content, this.m_ViewMode == ProjectBrowser.ViewMode.OneColumn, new GenericMenu.MenuFunction(this.SetOneColumn)); if (base.position.width >= 230f) { @@ -1951,34 +1925,15 @@ private void ResizeHandling(float width, float height) { return; } - Rect position = new Rect(this.m_DirectoriesAreaWidth, this.m_ToolbarHeight, 5f, height); - if (Event.current.type == EventType.Repaint) - { - EditorGUIUtility.AddCursorRect(position, MouseCursor.SplitResizeLeftRight); - } - float num = 0f; - float x = EditorGUI.MouseDeltaReader(position, true).x; - if (x != 0f) - { - this.m_DirectoriesAreaWidth += x; - float max = width - this.k_MinDirectoriesAreaWidth; - num = Mathf.Clamp(this.m_DirectoriesAreaWidth, this.k_MinDirectoriesAreaWidth, max); - } - float num2 = 230f - this.k_MinDirectoriesAreaWidth; - if (width - this.m_DirectoriesAreaWidth < num2) - { - num = width - num2; - } - if (num > 0f) - { - this.m_DirectoriesAreaWidth = num; - } - float num3 = base.position.width - this.m_DirectoriesAreaWidth; - if (num3 != this.m_LastListWidth) + Rect dragRect = new Rect(this.m_DirectoriesAreaWidth, this.m_ToolbarHeight, 5f, height); + dragRect = EditorGUIUtility.HandleHorizontalSplitter(dragRect, base.position.width, this.k_MinDirectoriesAreaWidth, 230f - this.k_MinDirectoriesAreaWidth); + this.m_DirectoriesAreaWidth = dragRect.x; + float num = base.position.width - this.m_DirectoriesAreaWidth; + if (num != this.m_LastListWidth) { this.RefreshSplittedSelectedPath(); } - this.m_LastListWidth = num3; + this.m_LastListWidth = num; } private void ButtonSaveFilter() { @@ -2233,7 +2188,7 @@ private void BreadCrumbBar() text2 += text3; this.m_BreadCrumbs.Add(new KeyValuePair(new GUIContent(text3), text2)); } - this.m_BreadCrumbLastFolderHasSubFolders = (ProjectBrowser.BreadCrumbListMenu.GetSubFolders(text).Count > 0); + this.m_BreadCrumbLastFolderHasSubFolders = (AssetDatabase.GetSubFolders(text).Length > 0); } GUI.Label(this.m_ListHeaderRect, GUIContent.none, ProjectBrowser.s_Styles.topBarBg); Rect listHeaderRect = this.m_ListHeaderRect; diff --git a/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs index ecb46ca8..59fbb00a 100644 --- a/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs +++ b/UnityEditor/UnityEditor/ProjectBrowserColumnOneTreeViewDragging.cs @@ -3,9 +3,9 @@ using UnityEngine; namespace UnityEditor { - internal class ProjectBrowserColumnOneTreeViewDragging : AssetOrGameObjectTreeViewDragging + internal class ProjectBrowserColumnOneTreeViewDragging : AssetsTreeViewDragging { - public ProjectBrowserColumnOneTreeViewDragging(TreeView treeView) : base(treeView, HierarchyType.Assets) + public ProjectBrowserColumnOneTreeViewDragging(TreeView treeView) : base(treeView) { } public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) diff --git a/UnityEditor/UnityEditor/ProjectWindowUtil.cs b/UnityEditor/UnityEditor/ProjectWindowUtil.cs index a51c1fe4..5ea71a1a 100644 --- a/UnityEditor/UnityEditor/ProjectWindowUtil.cs +++ b/UnityEditor/UnityEditor/ProjectWindowUtil.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; @@ -94,6 +95,11 @@ private static void CreateAnimatorController() Texture2D icon = EditorGUIUtility.IconContent("AnimatorController Icon").image as Texture2D; ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Animator Controller.controller", icon, null); } + private static void CreateAudioMixer() + { + Texture2D icon = EditorGUIUtility.IconContent("AudioMixerController Icon").image as Texture2D; + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "NewAudioMixer.mixer", icon, null); + } internal static UnityEngine.Object CreateScriptAssetFromTemplate(string pathName, string resourceFile) { string fullPath = Path.GetFullPath(pathName); @@ -256,5 +262,72 @@ public static string[] GetBaseFolders(string[] folders) } return list.ToArray(); } + internal static void DuplicateSelectedAssets() + { + AssetDatabase.Refresh(); + UnityEngine.Object[] objects = Selection.objects; + bool flag = true; + UnityEngine.Object[] array = objects; + for (int i = 0; i < array.Length; i++) + { + UnityEngine.Object @object = array[i]; + AnimationClip animationClip = @object as AnimationClip; + if (animationClip == null || (animationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None || !AssetDatabase.Contains(animationClip)) + { + flag = false; + } + } + ArrayList arrayList = new ArrayList(); + bool flag2 = false; + if (flag) + { + UnityEngine.Object[] array2 = objects; + for (int j = 0; j < array2.Length; j++) + { + UnityEngine.Object object2 = array2[j]; + AnimationClip animationClip2 = object2 as AnimationClip; + if (animationClip2 != null && (animationClip2.hideFlags & HideFlags.NotEditable) != HideFlags.None) + { + string path = AssetDatabase.GetAssetPath(object2); + path = Path.Combine(Path.GetDirectoryName(path), animationClip2.name) + ".anim"; + string text = AssetDatabase.GenerateUniqueAssetPath(path); + AnimationClip animationClip3 = new AnimationClip(); + EditorUtility.CopySerialized(animationClip2, animationClip3); + AssetDatabase.CreateAsset(animationClip3, text); + arrayList.Add(text); + } + } + } + else + { + UnityEngine.Object[] filtered = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets); + UnityEngine.Object[] array3 = filtered; + for (int k = 0; k < array3.Length; k++) + { + UnityEngine.Object assetObject = array3[k]; + string assetPath = AssetDatabase.GetAssetPath(assetObject); + string text2 = AssetDatabase.GenerateUniqueAssetPath(assetPath); + if (text2.Length != 0) + { + flag2 |= !AssetDatabase.CopyAsset(assetPath, text2); + } + else + { + flag2 |= true; + } + if (!flag2) + { + arrayList.Add(text2); + } + } + } + AssetDatabase.Refresh(); + UnityEngine.Object[] array4 = new UnityEngine.Object[arrayList.Count]; + for (int l = 0; l < arrayList.Count; l++) + { + array4[l] = AssetDatabase.LoadMainAssetAtPath(arrayList[l] as string); + } + Selection.objects = array4; + } } } diff --git a/UnityEditor/UnityEditor/PropertyHandlerCache.cs b/UnityEditor/UnityEditor/PropertyHandlerCache.cs index 058acdab..23eeae46 100644 --- a/UnityEditor/UnityEditor/PropertyHandlerCache.cs +++ b/UnityEditor/UnityEditor/PropertyHandlerCache.cs @@ -26,7 +26,7 @@ private static int GetPropertyHash(SerializedProperty property) { return 0; } - int num = property.serializedObject.targetObject.GetInstanceID() ^ property.arrayIndexLessPropertyPath.GetHashCode(); + int num = property.serializedObject.targetObject.GetInstanceID() ^ property.hashCodeForPropertyPathWithoutArrayIndex; if (property.propertyType == SerializedPropertyType.ObjectReference) { num ^= property.objectReferenceInstanceIDValue; diff --git a/UnityEditor/UnityEditor/QualitySettingsEditor.cs b/UnityEditor/UnityEditor/QualitySettingsEditor.cs index 08a15319..99d52910 100644 --- a/UnityEditor/UnityEditor/QualitySettingsEditor.cs +++ b/UnityEditor/UnityEditor/QualitySettingsEditor.cs @@ -20,6 +20,7 @@ private static class Styles public static readonly GUIContent kPlatformTooltip = new GUIContent(string.Empty, "Allow quality setting on platform"); public static readonly GUIContent kIconTrash = EditorGUIUtility.IconContent("TreeEditor.Trash", "Delete Level"); public static readonly GUIContent kSoftParticlesHint = EditorGUIUtility.TextContent("QualitySettings.SoftParticlesHint"); + public static readonly GUIContent kBillboardsFaceCameraPos = EditorGUIUtility.TextContent("QualitySettings.BillboardsFaceCameraPos"); public static readonly GUIStyle kListEvenBg = "ObjectPickerResultsOdd"; public static readonly GUIStyle kListOddBg = "ObjectPickerResultsEven"; public static readonly GUIStyle kDefaultDropdown = "QualitySettingsDefault"; @@ -380,7 +381,7 @@ private void SoftParticlesHintGUI() return; } RenderingPath actualRenderingPath = main.actualRenderingPath; - if (actualRenderingPath == RenderingPath.DeferredLighting) + if (actualRenderingPath == RenderingPath.DeferredLighting || actualRenderingPath == RenderingPath.DeferredShading) { return; } @@ -390,6 +391,47 @@ private void SoftParticlesHintGUI() } EditorGUILayout.HelpBox(QualitySettingsEditor.Styles.kSoftParticlesHint.text, MessageType.Warning, false); } + private void DrawCascadeSplitGUI(ref SerializedProperty shadowCascadeSplit) + { + float[] array = null; + Type typeFromHandle = typeof(T); + if (typeFromHandle == typeof(float)) + { + array = new float[] + { + shadowCascadeSplit.floatValue + }; + } + else + { + if (typeFromHandle == typeof(Vector3)) + { + Vector3 vector3Value = shadowCascadeSplit.vector3Value; + array = new float[] + { + Mathf.Clamp(vector3Value[0], 0f, 1f), + Mathf.Clamp(vector3Value[1] - vector3Value[0], 0f, 1f), + Mathf.Clamp(vector3Value[2] - vector3Value[1], 0f, 1f) + }; + } + } + if (array != null) + { + ShadowCascadeSplitGUI.HandleCascadeSliderGUI(ref array); + if (typeFromHandle == typeof(float)) + { + shadowCascadeSplit.floatValue = array[0]; + } + else + { + Vector3 vector3Value2 = default(Vector3); + vector3Value2[0] = array[0]; + vector3Value2[1] = vector3Value2[0] + array[1]; + vector3Value2[2] = vector3Value2[1] + array[2]; + shadowCascadeSplit.vector3Value = vector3Value2; + } + } + } public override void OnInspectorGUI() { if (EditorApplication.isPlayingOrWillChangePlaymode) @@ -413,17 +455,21 @@ public override void OnInspectorGUI() SerializedProperty property2 = arrayElementAtIndex.FindPropertyRelative("shadows"); SerializedProperty property3 = arrayElementAtIndex.FindPropertyRelative("shadowResolution"); SerializedProperty property4 = arrayElementAtIndex.FindPropertyRelative("shadowProjection"); - SerializedProperty property5 = arrayElementAtIndex.FindPropertyRelative("shadowCascades"); - SerializedProperty property6 = arrayElementAtIndex.FindPropertyRelative("shadowDistance"); - SerializedProperty property7 = arrayElementAtIndex.FindPropertyRelative("blendWeights"); - SerializedProperty property8 = arrayElementAtIndex.FindPropertyRelative("textureQuality"); - SerializedProperty property9 = arrayElementAtIndex.FindPropertyRelative("anisotropicTextures"); - SerializedProperty property10 = arrayElementAtIndex.FindPropertyRelative("antiAliasing"); - SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("softParticles"); - SerializedProperty property11 = arrayElementAtIndex.FindPropertyRelative("vSyncCount"); - SerializedProperty property12 = arrayElementAtIndex.FindPropertyRelative("lodBias"); - SerializedProperty property13 = arrayElementAtIndex.FindPropertyRelative("maximumLODLevel"); - SerializedProperty property14 = arrayElementAtIndex.FindPropertyRelative("particleRaycastBudget"); + SerializedProperty serializedProperty2 = arrayElementAtIndex.FindPropertyRelative("shadowCascades"); + SerializedProperty property5 = arrayElementAtIndex.FindPropertyRelative("shadowDistance"); + SerializedProperty serializedProperty3 = arrayElementAtIndex.FindPropertyRelative("shadowCascade2Split"); + SerializedProperty serializedProperty4 = arrayElementAtIndex.FindPropertyRelative("shadowCascade4Split"); + SerializedProperty property6 = arrayElementAtIndex.FindPropertyRelative("blendWeights"); + SerializedProperty property7 = arrayElementAtIndex.FindPropertyRelative("textureQuality"); + SerializedProperty property8 = arrayElementAtIndex.FindPropertyRelative("anisotropicTextures"); + SerializedProperty property9 = arrayElementAtIndex.FindPropertyRelative("antiAliasing"); + SerializedProperty serializedProperty5 = arrayElementAtIndex.FindPropertyRelative("softParticles"); + SerializedProperty property10 = arrayElementAtIndex.FindPropertyRelative("realtimeReflectionProbes"); + SerializedProperty property11 = arrayElementAtIndex.FindPropertyRelative("billboardsFaceCameraPosition"); + SerializedProperty property12 = arrayElementAtIndex.FindPropertyRelative("vSyncCount"); + SerializedProperty property13 = arrayElementAtIndex.FindPropertyRelative("lodBias"); + SerializedProperty property14 = arrayElementAtIndex.FindPropertyRelative("maximumLODLevel"); + SerializedProperty property15 = arrayElementAtIndex.FindPropertyRelative("particleRaycastBudget"); if (string.IsNullOrEmpty(serializedProperty.stringValue)) { serializedProperty.stringValue = "Level " + num; @@ -432,28 +478,41 @@ public override void OnInspectorGUI() GUILayout.Space(10f); GUILayout.Label(EditorGUIUtility.TempContent("Rendering"), EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property7, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property8, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property9, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(property10, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(serializedProperty2, new GUILayoutOption[0]); - if (serializedProperty2.boolValue) + EditorGUILayout.PropertyField(serializedProperty5, new GUILayoutOption[0]); + if (serializedProperty5.boolValue) { this.SoftParticlesHintGUI(); } + EditorGUILayout.PropertyField(property10, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property11, QualitySettingsEditor.Styles.kBillboardsFaceCameraPos, new GUILayoutOption[0]); GUILayout.Space(10f); GUILayout.Label(EditorGUIUtility.TempContent("Shadows"), EditorStyles.boldLabel, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property2, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property3, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property4, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property5, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(property6, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(serializedProperty2, new GUILayoutOption[0]); + if (serializedProperty2.intValue == 2) + { + this.DrawCascadeSplitGUI(ref serializedProperty3); + } + else + { + if (serializedProperty2.intValue == 4) + { + this.DrawCascadeSplitGUI(ref serializedProperty4); + } + } GUILayout.Space(10f); GUILayout.Label(EditorGUIUtility.TempContent("Other"), EditorStyles.boldLabel, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(property7, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(property11, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property6, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property12, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property13, new GUILayoutOption[0]); EditorGUILayout.PropertyField(property14, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(property15, new GUILayoutOption[0]); if (this.m_Dragging != null && this.m_Dragging.m_Position != this.m_Dragging.m_StartPosition) { this.m_QualitySettingsProperty.MoveArrayElement(this.m_Dragging.m_StartPosition, this.m_Dragging.m_Position); diff --git a/UnityEditor/UnityEditor/RagdollBuilder.cs b/UnityEditor/UnityEditor/RagdollBuilder.cs index 3f6044eb..366fdf5c 100644 --- a/UnityEditor/UnityEditor/RagdollBuilder.cs +++ b/UnityEditor/UnityEditor/RagdollBuilder.cs @@ -22,7 +22,7 @@ private class BoneInfo public float density; public float summedMass; } - public Transform root; + public Transform pelvis; public Transform leftHips; public Transform leftKnee; public Transform leftFoot; @@ -75,14 +75,14 @@ private string CheckConsistency() } private void OnDrawGizmos() { - if (this.root) + if (this.pelvis) { Gizmos.color = Color.red; - Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.right)); + Gizmos.DrawRay(this.pelvis.position, this.pelvis.TransformDirection(this.right)); Gizmos.color = Color.green; - Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.up)); + Gizmos.DrawRay(this.pelvis.position, this.pelvis.TransformDirection(this.up)); Gizmos.color = Color.blue; - Gizmos.DrawRay(this.root.position, this.root.TransformDirection(this.forward)); + Gizmos.DrawRay(this.pelvis.position, this.pelvis.TransformDirection(this.forward)); } } [MenuItem("GameObject/3D Object/Ragdoll...", false, 2000)] @@ -98,15 +98,15 @@ private void DecomposeVector(out Vector3 normalCompo, out Vector3 tangentCompo, } private void CalculateAxes() { - if (this.head != null && this.root != null) + if (this.head != null && this.pelvis != null) { - this.up = RagdollBuilder.CalculateDirectionAxis(this.root.InverseTransformPoint(this.head.position)); + this.up = RagdollBuilder.CalculateDirectionAxis(this.pelvis.InverseTransformPoint(this.head.position)); } - if (this.rightElbow != null && this.root != null) + if (this.rightElbow != null && this.pelvis != null) { Vector3 vector; Vector3 point; - this.DecomposeVector(out vector, out point, this.root.InverseTransformPoint(this.rightElbow.position), this.up); + this.DecomposeVector(out vector, out point, this.pelvis.InverseTransformPoint(this.rightElbow.position), this.up); this.right = RagdollBuilder.CalculateDirectionAxis(point); } this.forward = Vector3.Cross(this.right, this.up); @@ -131,22 +131,22 @@ private void OnWizardUpdate() } private void PrepareBones() { - if (this.root) + if (this.pelvis) { - this.worldRight = this.root.TransformDirection(this.right); - this.worldUp = this.root.TransformDirection(this.up); - this.worldForward = this.root.TransformDirection(this.forward); + this.worldRight = this.pelvis.TransformDirection(this.right); + this.worldUp = this.pelvis.TransformDirection(this.up); + this.worldForward = this.pelvis.TransformDirection(this.forward); } this.bones = new ArrayList(); this.rootBone = new RagdollBuilder.BoneInfo(); - this.rootBone.name = "Root"; - this.rootBone.anchor = this.root; + this.rootBone.name = "Pelvis"; + this.rootBone.anchor = this.pelvis; this.rootBone.parent = null; this.rootBone.density = 2.5f; this.bones.Add(this.rootBone); - this.AddMirroredJoint("Hips", this.leftHips, this.rightHips, "Root", this.worldRight, this.worldForward, -20f, 70f, 30f, typeof(CapsuleCollider), 0.3f, 1.5f); + this.AddMirroredJoint("Hips", this.leftHips, this.rightHips, "Pelvis", this.worldRight, this.worldForward, -20f, 70f, 30f, typeof(CapsuleCollider), 0.3f, 1.5f); this.AddMirroredJoint("Knee", this.leftKnee, this.rightKnee, "Hips", this.worldRight, this.worldForward, -80f, 0f, 0f, typeof(CapsuleCollider), 0.25f, 1.5f); - this.AddJoint("Middle Spine", this.middleSpine, "Root", this.worldRight, this.worldForward, -20f, 20f, 10f, null, 1f, 2.5f); + this.AddJoint("Middle Spine", this.middleSpine, "Pelvis", this.worldRight, this.worldForward, -20f, 20f, 10f, null, 1f, 2.5f); this.AddMirroredJoint("Arm", this.leftArm, this.rightArm, "Middle Spine", this.worldUp, this.worldForward, -70f, 10f, 50f, typeof(CapsuleCollider), 0.25f, 1f); this.AddMirroredJoint("Elbow", this.leftElbow, this.rightElbow, "Arm", this.worldForward, this.worldUp, -90f, 0f, 0f, typeof(CapsuleCollider), 0.2f, 1f); this.AddJoint("Head", this.head, "Middle Spine", this.worldRight, this.worldForward, -40f, 25f, 25f, null, 1f, 1f); @@ -160,7 +160,6 @@ private void OnWizardCreate() this.BuildBodies(); this.BuildJoints(); this.CalculateMass(); - this.CalculateSpringDampers(); } private RagdollBuilder.BoneInfo FindBone(string name) { @@ -249,7 +248,7 @@ private void BuildCapsules() } } } - CapsuleCollider capsuleCollider = (CapsuleCollider)boneInfo.anchor.gameObject.AddComponent("CapsuleCollider"); + CapsuleCollider capsuleCollider = boneInfo.anchor.gameObject.AddComponent(); capsuleCollider.direction = num; Vector3 zero = Vector3.zero; zero[num] = num2 * 0.5f; @@ -293,8 +292,8 @@ private void BuildBodies() { foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) { - boneInfo.anchor.gameObject.AddComponent("Rigidbody"); - boneInfo.anchor.rigidbody.mass = boneInfo.density; + boneInfo.anchor.gameObject.AddComponent(); + boneInfo.anchor.GetComponent().mass = boneInfo.density; } } private void BuildJoints() @@ -303,13 +302,15 @@ private void BuildJoints() { if (boneInfo.parent != null) { - CharacterJoint characterJoint = (CharacterJoint)boneInfo.anchor.gameObject.AddComponent("CharacterJoint"); + CharacterJoint characterJoint = boneInfo.anchor.gameObject.AddComponent(); boneInfo.joint = characterJoint; characterJoint.axis = RagdollBuilder.CalculateDirectionAxis(boneInfo.anchor.InverseTransformDirection(boneInfo.axis)); characterJoint.swingAxis = RagdollBuilder.CalculateDirectionAxis(boneInfo.anchor.InverseTransformDirection(boneInfo.normalAxis)); characterJoint.anchor = Vector3.zero; - characterJoint.connectedBody = boneInfo.parent.anchor.rigidbody; + characterJoint.connectedBody = boneInfo.parent.anchor.GetComponent(); + characterJoint.enablePreprocessing = false; SoftJointLimit softJointLimit = default(SoftJointLimit); + softJointLimit.contactDistance = 0f; softJointLimit.limit = boneInfo.minLimit; characterJoint.lowTwistLimit = softJointLimit; softJointLimit.limit = boneInfo.maxLimit; @@ -323,7 +324,7 @@ private void BuildJoints() } private void CalculateMassRecurse(RagdollBuilder.BoneInfo bone) { - float num = bone.anchor.rigidbody.mass; + float num = bone.anchor.GetComponent().mass; foreach (RagdollBuilder.BoneInfo boneInfo in bone.children) { this.CalculateMassRecurse(boneInfo); @@ -337,28 +338,10 @@ private void CalculateMass() float num = this.totalMass / this.rootBone.summedMass; foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) { - boneInfo.anchor.rigidbody.mass *= num; + boneInfo.anchor.GetComponent().mass *= num; } this.CalculateMassRecurse(this.rootBone); } - private JointDrive CalculateSpringDamper(float frequency, float damping, float mass) - { - return new JointDrive - { - positionSpring = 9f * frequency * frequency * mass, - positionDamper = 4.5f * frequency * damping * mass - }; - } - private void CalculateSpringDampers() - { - foreach (RagdollBuilder.BoneInfo boneInfo in this.bones) - { - if (boneInfo.joint) - { - boneInfo.joint.rotationDrive = this.CalculateSpringDamper(this.strength / 100f, 1f, boneInfo.summedMass); - } - } - } private static void CalculateDirection(Vector3 point, out int direction, out float distance) { direction = 0; @@ -465,45 +448,45 @@ private Bounds GetBreastBounds(Transform relativeTo) } private void AddBreastColliders() { - if (this.middleSpine != null && this.root != null) + if (this.middleSpine != null && this.pelvis != null) { - Bounds bounds = this.Clip(this.GetBreastBounds(this.root), this.root, this.middleSpine, false); - BoxCollider boxCollider = (BoxCollider)this.root.gameObject.AddComponent("BoxCollider"); + Bounds bounds = this.Clip(this.GetBreastBounds(this.pelvis), this.pelvis, this.middleSpine, false); + BoxCollider boxCollider = this.pelvis.gameObject.AddComponent(); boxCollider.center = bounds.center; boxCollider.size = bounds.size; bounds = this.Clip(this.GetBreastBounds(this.middleSpine), this.middleSpine, this.middleSpine, true); - boxCollider = (BoxCollider)this.middleSpine.gameObject.AddComponent("BoxCollider"); + boxCollider = this.middleSpine.gameObject.AddComponent(); boxCollider.center = bounds.center; boxCollider.size = bounds.size; } else { Bounds bounds2 = default(Bounds); - bounds2.Encapsulate(this.root.InverseTransformPoint(this.leftHips.position)); - bounds2.Encapsulate(this.root.InverseTransformPoint(this.rightHips.position)); - bounds2.Encapsulate(this.root.InverseTransformPoint(this.leftArm.position)); - bounds2.Encapsulate(this.root.InverseTransformPoint(this.rightArm.position)); + bounds2.Encapsulate(this.pelvis.InverseTransformPoint(this.leftHips.position)); + bounds2.Encapsulate(this.pelvis.InverseTransformPoint(this.rightHips.position)); + bounds2.Encapsulate(this.pelvis.InverseTransformPoint(this.leftArm.position)); + bounds2.Encapsulate(this.pelvis.InverseTransformPoint(this.rightArm.position)); Vector3 size = bounds2.size; size[RagdollBuilder.SmallestComponent(bounds2.size)] = size[RagdollBuilder.LargestComponent(bounds2.size)] / 2f; - BoxCollider boxCollider2 = (BoxCollider)this.root.gameObject.AddComponent("BoxCollider"); + BoxCollider boxCollider2 = this.pelvis.gameObject.AddComponent(); boxCollider2.center = bounds2.center; boxCollider2.size = size; } } private void AddHeadCollider() { - if (this.head.collider) + if (this.head.GetComponent()) { - UnityEngine.Object.Destroy(this.head.collider); + UnityEngine.Object.Destroy(this.head.GetComponent()); } float num = Vector3.Distance(this.leftArm.transform.position, this.rightArm.transform.position); num /= 4f; - SphereCollider sphereCollider = (SphereCollider)this.head.gameObject.AddComponent("SphereCollider"); + SphereCollider sphereCollider = this.head.gameObject.AddComponent(); sphereCollider.radius = num; Vector3 zero = Vector3.zero; int index; float num2; - RagdollBuilder.CalculateDirection(this.head.InverseTransformPoint(this.root.position), out index, out num2); + RagdollBuilder.CalculateDirection(this.head.InverseTransformPoint(this.pelvis.position), out index, out num2); if (num2 > 0f) { zero[index] = -num; diff --git a/UnityEditor/UnityEditor/RectSelection.cs b/UnityEditor/UnityEditor/RectSelection.cs index 69a9d3ce..8a86203d 100644 --- a/UnityEditor/UnityEditor/RectSelection.cs +++ b/UnityEditor/UnityEditor/RectSelection.cs @@ -259,12 +259,12 @@ private static void UpdateSelection(UnityEngine.Object[] existingSelection, Unit Dictionary dictionary = new Dictionary(existingSelection.Length); for (int j = 0; j < existingSelection.Length; j++) { - GameObject key = (GameObject)existingSelection[j]; + UnityEngine.Object key = existingSelection[j]; dictionary.Add(key, false); } for (int k = 0; k < newObjects.Length; k++) { - GameObject key2 = (GameObject)newObjects[k]; + UnityEngine.Object key2 = newObjects[k]; if (dictionary.ContainsKey(key2)) { dictionary.Remove(key2); diff --git a/UnityEditor/UnityEditor/ReflectionProbeEditor.cs b/UnityEditor/UnityEditor/ReflectionProbeEditor.cs new file mode 100644 index 00000000..52c8641e --- /dev/null +++ b/UnityEditor/UnityEditor/ReflectionProbeEditor.cs @@ -0,0 +1,695 @@ +using System; +using System.IO; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.Rendering; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(ReflectionProbe))] + internal class ReflectionProbeEditor : Editor + { + private static class Styles + { + public static GUIStyle richTextMiniLabel; + public static string bakeButtonText; + public static string editBoundsText; + public static string[] bakeCustomButtonsText; + public static string[] bakeButtonsText; + public static GUIContent runtimeSettingsHeader; + public static GUIContent backgroundColorText; + public static GUIContent clearFlagsText; + public static GUIContent intensityText; + public static GUIContent resolutionText; + public static GUIContent captureCubemapHeaderText; + public static GUIContent boxProjectionText; + public static GUIContent sizeText; + public static GUIContent centerText; + public static GUIContent skipFramesText; + public static GUIContent customCubemapText; + public static GUIContent editorUpdateText; + public static GUIContent importanceText; + public static GUIContent renderDynamicObjects; + public static GUIContent timeSlicing; + public static GUIContent refreshMode; + public static GUIContent typeText; + public static GUIContent[] reflectionProbeMode; + public static int[] reflectionProbeModeValues; + public static int[] renderTextureSizesValues; + public static GUIContent[] renderTextureSizes; + public static GUIContent[] clearFlags; + public static int[] clearFlagsValues; + public static GUIContent[] toolContents; + public static EditMode.SceneViewEditMode[] sceneViewEditModes; + public static string baseSceneEditingToolText; + public static GUIContent[] toolNames; + public static GUIStyle commandStyle; + static Styles() + { + ReflectionProbeEditor.Styles.richTextMiniLabel = new GUIStyle(EditorStyles.miniLabel); + ReflectionProbeEditor.Styles.bakeButtonText = "Bake"; + ReflectionProbeEditor.Styles.editBoundsText = "Edit Bounds"; + ReflectionProbeEditor.Styles.bakeCustomButtonsText = new string[] + { + "Bake as new Cubemap..." + }; + ReflectionProbeEditor.Styles.bakeButtonsText = new string[] + { + "Bake All Reflection Probes" + }; + ReflectionProbeEditor.Styles.runtimeSettingsHeader = new GUIContent("Runtime settings", "These settings are used by objects when they render with the cubemap of this probe"); + ReflectionProbeEditor.Styles.backgroundColorText = new GUIContent("Background", "Camera clears the screen to this color before rendering."); + ReflectionProbeEditor.Styles.clearFlagsText = new GUIContent("Clear Flags"); + ReflectionProbeEditor.Styles.intensityText = new GUIContent("Intensity"); + ReflectionProbeEditor.Styles.resolutionText = new GUIContent("Resolution"); + ReflectionProbeEditor.Styles.captureCubemapHeaderText = new GUIContent("Cubemap capture settings"); + ReflectionProbeEditor.Styles.boxProjectionText = new GUIContent("Box Projection", "Box projection is useful for reflections in enclosed spaces where some parrallax and movement in the reflection is wanted. If not set then cubemap reflection will we treated as coming infinite far away. And within this zone objects with the Standard shader will receive this probe's cubemap."); + ReflectionProbeEditor.Styles.sizeText = new GUIContent("Size"); + ReflectionProbeEditor.Styles.centerText = new GUIContent("Probe Origin"); + ReflectionProbeEditor.Styles.skipFramesText = new GUIContent("Skip frames"); + ReflectionProbeEditor.Styles.customCubemapText = new GUIContent("Cubemap"); + ReflectionProbeEditor.Styles.editorUpdateText = new GUIContent("Editor Update"); + ReflectionProbeEditor.Styles.importanceText = new GUIContent("Importance"); + ReflectionProbeEditor.Styles.renderDynamicObjects = new GUIContent("Dynamic Objects", "If enabled dynamic objects are also rendered into the cubemap"); + ReflectionProbeEditor.Styles.timeSlicing = new GUIContent("Time Slicing", "If enabled this probe will update over several frames, to help reduce the impact on the frame rate"); + ReflectionProbeEditor.Styles.refreshMode = new GUIContent("Refresh Mode", "Controls how this probe refreshes in the Player"); + ReflectionProbeEditor.Styles.typeText = new GUIContent("Type", "'Baked Cubemap' uses the 'Continous Baking' mode from the Lighting window. If it is enabled then baking is automatic otherwise manual bake is needed (use the bake button below). \n'Custom' can be used if a custom cubemap is wanted. \n'Realtime' can be used to dynamically re-render the cubemap during runtime (via scripting)."); + ReflectionProbeEditor.Styles.reflectionProbeMode = new GUIContent[] + { + new GUIContent("Baked"), + new GUIContent("Custom"), + new GUIContent("Realtime") + }; + ReflectionProbeEditor.Styles.reflectionProbeModeValues = new int[] + { + 0, + 2, + 1 + }; + ReflectionProbeEditor.Styles.renderTextureSizesValues = new int[] + { + 16, + 32, + 64, + 128, + 256, + 512, + 1024, + 2048 + }; + ReflectionProbeEditor.Styles.renderTextureSizes = ( + from n in ReflectionProbeEditor.Styles.renderTextureSizesValues + select new GUIContent(n.ToString())).ToArray(); + ReflectionProbeEditor.Styles.clearFlags = new GUIContent[] + { + new GUIContent("Skybox"), + new GUIContent("Solid Color") + }; + ReflectionProbeEditor.Styles.clearFlagsValues = new int[] + { + 1, + 2 + }; + ReflectionProbeEditor.Styles.toolContents = new GUIContent[] + { + EditorGUIUtility.IconContent("EditCollider"), + EditorGUIUtility.IconContent("MoveTool") + }; + ReflectionProbeEditor.Styles.sceneViewEditModes = new EditMode.SceneViewEditMode[] + { + EditMode.SceneViewEditMode.ReflectionProbeBox, + EditMode.SceneViewEditMode.ReflectionProbeOrigin + }; + ReflectionProbeEditor.Styles.baseSceneEditingToolText = "Probe Scene Editing Mode: "; + ReflectionProbeEditor.Styles.toolNames = new GUIContent[] + { + new GUIContent(ReflectionProbeEditor.Styles.baseSceneEditingToolText + "Box Projection Bounds", string.Empty), + new GUIContent(ReflectionProbeEditor.Styles.baseSceneEditingToolText + "Probe Origin", string.Empty) + }; + ReflectionProbeEditor.Styles.commandStyle = "Command"; + ReflectionProbeEditor.Styles.richTextMiniLabel.richText = true; + } + } + private static ReflectionProbeEditor s_LastInteractedEditor; + private SerializedProperty m_Mode; + private SerializedProperty m_RefreshMode; + private SerializedProperty m_TimeSlicingMode; + private SerializedProperty m_Resolution; + private SerializedProperty m_ShadowDistance; + private SerializedProperty m_Importance; + private SerializedProperty m_BoxSize; + private SerializedProperty m_BoxOffset; + private SerializedProperty m_CullingMask; + private SerializedProperty m_ClearFlags; + private SerializedProperty m_BackgroundColor; + private SerializedProperty m_HDR; + private SerializedProperty m_BoxProjection; + private SerializedProperty m_IntensityMultiplier; + private SerializedProperty m_CustomBakedTexture; + private SerializedProperty m_RenderDynamicObjects; + private SerializedProperty m_UseOcclusionCulling; + private SerializedProperty[] m_NearAndFarProperties; + private static Mesh s_SphereMesh; + private static Mesh s_PlaneMesh; + private Material m_ReflectiveMaterial; + private Vector3 m_OldTransformPosition = Vector3.zero; + private float m_MipLevelPreview; + private static int s_BoxHash = "ReflectionProbeEditorHash".GetHashCode(); + private BoxEditor m_BoxEditor = new BoxEditor(true, ReflectionProbeEditor.s_BoxHash); + internal static Color kGizmoReflectionProbe = new Color(1f, 0.8980392f, 0.5803922f, 0.5019608f); + internal static Color kGizmoHandleReflectionProbe = new Color(1f, 0.8980392f, 0.6666667f, 1f); + private readonly AnimBool m_ShowProbeModeRealtimeOptions = new AnimBool(); + private readonly AnimBool m_ShowProbeModeCustomOptions = new AnimBool(); + private readonly AnimBool m_ShowBoxOptions = new AnimBool(); + private TextureInspector m_CubemapEditor; + private bool sceneViewEditing + { + get + { + return this.IsReflectionProbeEditMode(EditMode.editMode) && EditMode.IsOwner(this); + } + } + private ReflectionProbe reflectionProbeTarget + { + get + { + return (ReflectionProbe)this.target; + } + } + private ReflectionProbeMode reflectionProbeMode + { + get + { + return this.reflectionProbeTarget.mode; + } + } + private static Mesh sphereMesh + { + get + { + Mesh arg_2B_0; + if ((arg_2B_0 = ReflectionProbeEditor.s_SphereMesh) == null) + { + arg_2B_0 = (ReflectionProbeEditor.s_SphereMesh = (Resources.GetBuiltinResource(typeof(Mesh), "New-Sphere.fbx") as Mesh)); + } + return arg_2B_0; + } + } + private static Mesh planeMesh + { + get + { + Mesh arg_2B_0; + if ((arg_2B_0 = ReflectionProbeEditor.s_PlaneMesh) == null) + { + arg_2B_0 = (ReflectionProbeEditor.s_PlaneMesh = (Resources.GetBuiltinResource(typeof(Mesh), "New-Plane.fbx") as Mesh)); + } + return arg_2B_0; + } + } + private Material reflectiveMaterial + { + get + { + if (this.m_ReflectiveMaterial == null) + { + this.m_ReflectiveMaterial = (Material)UnityEngine.Object.Instantiate(EditorGUIUtility.Load("Previews/PreviewCubemapMaterial.mat")); + this.m_ReflectiveMaterial.hideFlags = HideFlags.HideAndDontSave; + } + return this.m_ReflectiveMaterial; + } + } + private bool IsReflectionProbeEditMode(EditMode.SceneViewEditMode editMode) + { + return editMode == EditMode.SceneViewEditMode.ReflectionProbeBox || editMode == EditMode.SceneViewEditMode.ReflectionProbeOrigin; + } + public void OnEnable() + { + this.m_Mode = base.serializedObject.FindProperty("m_Mode"); + this.m_RefreshMode = base.serializedObject.FindProperty("m_RefreshMode"); + this.m_TimeSlicingMode = base.serializedObject.FindProperty("m_TimeSlicingMode"); + this.m_Resolution = base.serializedObject.FindProperty("m_Resolution"); + this.m_NearAndFarProperties = new SerializedProperty[] + { + base.serializedObject.FindProperty("m_NearClip"), + base.serializedObject.FindProperty("m_FarClip") + }; + this.m_ShadowDistance = base.serializedObject.FindProperty("m_ShadowDistance"); + this.m_Importance = base.serializedObject.FindProperty("m_Importance"); + this.m_BoxSize = base.serializedObject.FindProperty("m_BoxSize"); + this.m_BoxOffset = base.serializedObject.FindProperty("m_BoxOffset"); + this.m_CullingMask = base.serializedObject.FindProperty("m_CullingMask"); + this.m_ClearFlags = base.serializedObject.FindProperty("m_ClearFlags"); + this.m_BackgroundColor = base.serializedObject.FindProperty("m_BackGroundColor"); + this.m_HDR = base.serializedObject.FindProperty("m_HDR"); + this.m_BoxProjection = base.serializedObject.FindProperty("m_BoxProjection"); + this.m_IntensityMultiplier = base.serializedObject.FindProperty("m_IntensityMultiplier"); + this.m_CustomBakedTexture = base.serializedObject.FindProperty("m_CustomBakedTexture"); + this.m_RenderDynamicObjects = base.serializedObject.FindProperty("m_RenderDynamicObjects"); + this.m_UseOcclusionCulling = base.serializedObject.FindProperty("m_UseOcclusionCulling"); + ReflectionProbe reflectionProbe = this.target as ReflectionProbe; + this.m_ShowProbeModeRealtimeOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowProbeModeCustomOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowBoxOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowProbeModeRealtimeOptions.value = (reflectionProbe.mode == ReflectionProbeMode.Realtime); + this.m_ShowProbeModeCustomOptions.value = (reflectionProbe.mode == ReflectionProbeMode.Custom); + this.m_ShowBoxOptions.value = (!this.m_BoxSize.hasMultipleDifferentValues && !this.m_BoxOffset.hasMultipleDifferentValues && reflectionProbe.type == ReflectionProbeType.Cube); + this.m_BoxEditor.OnEnable(); + this.m_BoxEditor.SetAlwaysDisplayHandles(true); + this.m_BoxEditor.allowNegativeSize = false; + this.m_OldTransformPosition = ((ReflectionProbe)this.target).transform.position; + } + public void OnDisable() + { + this.m_BoxEditor.OnDisable(); + UnityEngine.Object.DestroyImmediate(this.m_ReflectiveMaterial); + UnityEngine.Object.DestroyImmediate(this.m_CubemapEditor); + } + private void BakeCustomReflectionProbe(ReflectionProbe probe, bool usePreviousAssetPath) + { + string text = string.Empty; + if (usePreviousAssetPath) + { + text = AssetDatabase.GetAssetPath(probe.customBakedTexture); + } + string text2 = (!probe.hdr) ? "png" : "exr"; + if (string.IsNullOrEmpty(text) || Path.GetExtension(text) != "." + text2) + { + string text3 = FileUtil.GetPathWithoutExtension(EditorApplication.currentScene); + if (string.IsNullOrEmpty(text3)) + { + text3 = "Assets"; + } + else + { + if (!Directory.Exists(text3)) + { + Directory.CreateDirectory(text3); + } + } + string text4 = probe.name + ((!probe.hdr) ? "-reflection" : "-reflectionHDR") + "." + text2; + text4 = Path.GetFileNameWithoutExtension(AssetDatabase.GenerateUniqueAssetPath(Path.Combine(text3, text4))); + text = EditorUtility.SaveFilePanelInProject("Save reflection probe's cubemap.", text4, text2, string.Empty, text3); + if (string.IsNullOrEmpty(text)) + { + return; + } + } + EditorUtility.DisplayProgressBar("Reflection Probes", "Baking " + text, 0.5f); + if (!Lightmapping.BakeReflectionProbe(probe, text)) + { + Debug.LogError("Failed to bake reflection probe to " + text); + } + EditorUtility.ClearProgressBar(); + } + private void OnBakeCustomButton(object data) + { + int num = (int)data; + ReflectionProbe probe = this.target as ReflectionProbe; + if (num == 0) + { + this.BakeCustomReflectionProbe(probe, false); + } + } + private void OnBakeButton(object data) + { + if ((int)data == 0) + { + Lightmapping.BakeAllReflectionProbesSnapshots(); + } + } + private void DoBakeButton() + { + if (this.reflectionProbeTarget.mode == ReflectionProbeMode.Realtime) + { + EditorGUILayout.HelpBox("Baking of this reflection probe should be initiated from the scripting API because the type is 'Realtime'", MessageType.Info); + if (!QualitySettings.realtimeReflectionProbes) + { + EditorGUILayout.HelpBox("Realtime reflection probes are disabled in Quality Settings", MessageType.Warning); + } + return; + } + if (this.reflectionProbeTarget.mode == ReflectionProbeMode.Baked && Lightmapping.giWorkflowMode != Lightmapping.GIWorkflowMode.OnDemand) + { + EditorGUILayout.HelpBox("Baking of this reflection probe is automatic because this probe's type is 'Baked' and the Lighting window is using 'Continous Baking'. The cubemap created is stored in the GI cache.", MessageType.Info); + return; + } + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Space(EditorGUIUtility.labelWidth); + switch (this.reflectionProbeMode) + { + case ReflectionProbeMode.Baked: + EditorGUI.BeginDisabledGroup(!this.reflectionProbeTarget.enabled); + if (EditorGUI.ButtonWithDropdownList(ReflectionProbeEditor.Styles.bakeButtonText, ReflectionProbeEditor.Styles.bakeButtonsText, new GenericMenu.MenuFunction2(this.OnBakeButton), new GUILayoutOption[0])) + { + Lightmapping.BakeReflectionProbeSnapshot(this.reflectionProbeTarget); + GUIUtility.ExitGUI(); + } + EditorGUI.EndDisabledGroup(); + break; + case ReflectionProbeMode.Custom: + if (EditorGUI.ButtonWithDropdownList(ReflectionProbeEditor.Styles.bakeButtonText, ReflectionProbeEditor.Styles.bakeCustomButtonsText, new GenericMenu.MenuFunction2(this.OnBakeCustomButton), new GUILayoutOption[0])) + { + this.BakeCustomReflectionProbe(this.reflectionProbeTarget, true); + GUIUtility.ExitGUI(); + } + break; + } + GUILayout.EndHorizontal(); + } + private void DoToolbar() + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + GUI.changed = false; + EditMode.SceneViewEditMode editMode = EditMode.editMode; + EditorGUI.BeginChangeCheck(); + EditMode.DoInspectorToolbar(ReflectionProbeEditor.Styles.sceneViewEditModes, ReflectionProbeEditor.Styles.toolContents, this.GetBounds(), this); + if (EditorGUI.EndChangeCheck()) + { + ReflectionProbeEditor.s_LastInteractedEditor = this; + } + if (editMode != EditMode.editMode) + { + EditMode.SceneViewEditMode editMode2 = EditMode.editMode; + if (editMode2 == EditMode.SceneViewEditMode.ReflectionProbeOrigin) + { + this.m_OldTransformPosition = ((ReflectionProbe)this.target).transform.position; + } + if (Toolbar.get != null) + { + Toolbar.get.Repaint(); + } + } + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); + string text = ReflectionProbeEditor.Styles.baseSceneEditingToolText; + if (this.sceneViewEditing) + { + int num = ArrayUtility.IndexOf(ReflectionProbeEditor.Styles.sceneViewEditModes, EditMode.editMode); + if (num >= 0) + { + text = ReflectionProbeEditor.Styles.toolNames[num].text; + } + } + GUILayout.Label(text, ReflectionProbeEditor.Styles.richTextMiniLabel, new GUILayoutOption[0]); + GUILayout.EndVertical(); + EditorGUILayout.Space(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + if (base.targets.Length == 1) + { + this.DoToolbar(); + } + this.m_ShowProbeModeRealtimeOptions.target = (this.reflectionProbeMode == ReflectionProbeMode.Realtime); + this.m_ShowProbeModeCustomOptions.target = (this.reflectionProbeMode == ReflectionProbeMode.Custom); + EditorGUILayout.IntPopup(this.m_Mode, ReflectionProbeEditor.Styles.reflectionProbeMode, ReflectionProbeEditor.Styles.reflectionProbeModeValues, ReflectionProbeEditor.Styles.typeText, new GUILayoutOption[0]); + if (!this.m_Mode.hasMultipleDifferentValues) + { + EditorGUI.indentLevel++; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowProbeModeCustomOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_RenderDynamicObjects, ReflectionProbeEditor.Styles.renderDynamicObjects, new GUILayoutOption[0]); + this.m_CustomBakedTexture.objectReferenceValue = EditorGUILayout.ObjectField(ReflectionProbeEditor.Styles.customCubemapText, this.m_CustomBakedTexture.objectReferenceValue, typeof(Cubemap), false, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowProbeModeRealtimeOptions.faded)) + { + EditorGUILayout.PropertyField(this.m_RefreshMode, ReflectionProbeEditor.Styles.refreshMode, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_TimeSlicingMode, ReflectionProbeEditor.Styles.timeSlicing, new GUILayoutOption[0]); + EditorGUILayout.Space(); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + } + EditorGUILayout.Space(); + GUILayout.Label(ReflectionProbeEditor.Styles.runtimeSettingsHeader, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(this.m_Importance, ReflectionProbeEditor.Styles.importanceText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_IntensityMultiplier, ReflectionProbeEditor.Styles.intensityText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BoxProjection, ReflectionProbeEditor.Styles.boxProjectionText, new GUILayoutOption[0]); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBoxOptions.faded)) + { + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(this.m_BoxSize, ReflectionProbeEditor.Styles.sizeText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BoxOffset, ReflectionProbeEditor.Styles.centerText, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + Vector3 vector3Value = this.m_BoxOffset.vector3Value; + Vector3 vector3Value2 = this.m_BoxSize.vector3Value; + if (this.ValidateAABB(ref vector3Value, ref vector3Value2)) + { + this.m_BoxOffset.vector3Value = vector3Value; + this.m_BoxSize.vector3Value = vector3Value2; + } + } + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + GUILayout.Label(ReflectionProbeEditor.Styles.captureCubemapHeaderText, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + EditorGUILayout.IntPopup(this.m_Resolution, ReflectionProbeEditor.Styles.renderTextureSizes, ReflectionProbeEditor.Styles.renderTextureSizesValues, ReflectionProbeEditor.Styles.resolutionText, new GUILayoutOption[] + { + GUILayout.MinWidth(40f) + }); + EditorGUILayout.PropertyField(this.m_HDR, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ShadowDistance, new GUILayoutOption[0]); + EditorGUILayout.IntPopup(this.m_ClearFlags, ReflectionProbeEditor.Styles.clearFlags, ReflectionProbeEditor.Styles.clearFlagsValues, ReflectionProbeEditor.Styles.clearFlagsText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_BackgroundColor, ReflectionProbeEditor.Styles.backgroundColorText, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_UseOcclusionCulling, new GUILayoutOption[0]); + EditorGUILayout.PropertiesField(EditorGUI.s_ClipingPlanesLabel, this.m_NearAndFarProperties, EditorGUI.s_NearAndFarLabels, 35f, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + this.DoBakeButton(); + EditorGUILayout.Space(); + base.serializedObject.ApplyModifiedProperties(); + } + private Bounds GetBounds() + { + if (this.target is ReflectionProbe) + { + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + return reflectionProbe.bounds; + } + return default(Bounds); + } + private bool ValidPreviewSetup() + { + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + return reflectionProbe != null && reflectionProbe.texture != null; + } + public override bool HasPreviewGUI() + { + if (base.targets.Length > 1) + { + return false; + } + if (this.ValidPreviewSetup()) + { + Editor cubemapEditor = this.m_CubemapEditor; + Editor.CreateCachedEditor(((ReflectionProbe)this.target).texture, null, ref cubemapEditor); + this.m_CubemapEditor = (cubemapEditor as TextureInspector); + } + return true; + } + public override void OnPreviewSettings() + { + if (!this.ValidPreviewSetup()) + { + return; + } + this.m_CubemapEditor.mipLevel = this.m_MipLevelPreview; + EditorGUI.BeginChangeCheck(); + this.m_CubemapEditor.OnPreviewSettings(); + if (EditorGUI.EndChangeCheck()) + { + EditorApplication.SetSceneRepaintDirty(); + this.m_MipLevelPreview = this.m_CubemapEditor.mipLevel; + } + } + public override void OnPreviewGUI(Rect position, GUIStyle style) + { + if (!this.ValidPreviewSetup()) + { + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Color color = GUI.color; + GUI.color = new Color(1f, 1f, 1f, 0.5f); + GUILayout.Label("Reflection Probe not baked yet", new GUILayoutOption[0]); + GUI.color = color; + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + return; + } + ReflectionProbe reflectionProbe = this.target as ReflectionProbe; + if (reflectionProbe != null && reflectionProbe.texture != null && base.targets.Length == 1) + { + Editor cubemapEditor = this.m_CubemapEditor; + Editor.CreateCachedEditor(reflectionProbe.texture, null, ref cubemapEditor); + this.m_CubemapEditor = (cubemapEditor as TextureInspector); + } + if (this.m_CubemapEditor != null) + { + this.m_CubemapEditor.SetCubemapIntensity(this.GetProbeIntensity((ReflectionProbe)this.target)); + this.m_CubemapEditor.OnPreviewGUI(position, style); + } + } + private float GetProbeIntensity(ReflectionProbe p) + { + if (p == null || p.texture == null) + { + return 1f; + } + float num = p.intensity; + if (TextureUtil.GetTextureColorSpaceString(p.texture) == "Linear") + { + num = Mathf.LinearToGammaSpace(num); + } + return num; + } + public void OnPreSceneGUI() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + if (!this.reflectiveMaterial) + { + return; + } + Matrix4x4 matrix = default(Matrix4x4); + Material reflectiveMaterial = this.reflectiveMaterial; + if (reflectionProbe.type == ReflectionProbeType.Cube) + { + float value = 0f; + TextureInspector cubemapEditor = this.m_CubemapEditor; + if (cubemapEditor) + { + value = cubemapEditor.GetMipLevelForRendering(); + } + reflectiveMaterial.mainTexture = reflectionProbe.texture; + reflectiveMaterial.SetMatrix("_CubemapRotation", Matrix4x4.identity); + reflectiveMaterial.SetFloat("_Mip", value); + reflectiveMaterial.SetFloat("_Alpha", 0f); + reflectiveMaterial.SetFloat("_Intensity", this.GetProbeIntensity(reflectionProbe)); + float num = reflectionProbe.transform.lossyScale.magnitude * 0.5f; + matrix.SetTRS(reflectionProbe.transform.position, Quaternion.identity, new Vector3(num, num, num)); + Graphics.DrawMesh(ReflectionProbeEditor.sphereMesh, matrix, this.reflectiveMaterial, 0, SceneView.currentDrawingSceneView.camera); + } + else + { + reflectiveMaterial.SetTexture("_MainTex", reflectionProbe.texture); + reflectiveMaterial.SetFloat("_ReflectionProbeType", 1f); + reflectiveMaterial.SetFloat("_Intensity", 1f); + Vector3 s = default(Vector3); + s = reflectionProbe.transform.lossyScale * 0.2f; + s.x *= -1f; + s.z *= -1f; + matrix.SetTRS(reflectionProbe.transform.position, reflectionProbe.transform.rotation * Quaternion.AngleAxis(90f, Vector3.right), s); + Graphics.DrawMesh(ReflectionProbeEditor.planeMesh, matrix, this.reflectiveMaterial, 0, SceneView.currentDrawingSceneView.camera); + } + } + private bool ValidateAABB(ref Vector3 center, ref Vector3 size) + { + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + Vector3 position = reflectionProbe.transform.position; + Bounds bounds = new Bounds(center + position, size); + if (bounds.Contains(position)) + { + return false; + } + bounds.Encapsulate(position); + center = bounds.center - position; + size = bounds.size; + return true; + } + [DrawGizmo(GizmoType.Active)] + private static void RenderBoxGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType) + { + if (ReflectionProbeEditor.s_LastInteractedEditor == null) + { + return; + } + if (ReflectionProbeEditor.s_LastInteractedEditor.sceneViewEditing && EditMode.editMode == EditMode.SceneViewEditMode.ReflectionProbeBox) + { + Color color = Gizmos.color; + Gizmos.color = ReflectionProbeEditor.kGizmoReflectionProbe; + Gizmos.DrawCube(reflectionProbe.transform.position + reflectionProbe.center, -1f * reflectionProbe.size); + Gizmos.color = color; + } + } + public void OnSceneGUI() + { + if (!this.sceneViewEditing) + { + return; + } + EditMode.SceneViewEditMode editMode = EditMode.editMode; + if (editMode != EditMode.SceneViewEditMode.ReflectionProbeBox) + { + if (editMode == EditMode.SceneViewEditMode.ReflectionProbeOrigin) + { + this.DoOriginEditing(); + } + } + else + { + this.DoBoxEditing(); + } + } + private void DoOriginEditing() + { + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + Vector3 position = reflectionProbe.transform.position; + Vector3 size = reflectionProbe.size; + Vector3 center = reflectionProbe.center + position; + EditorGUI.BeginChangeCheck(); + Vector3 vector = Handles.PositionHandle(position, Quaternion.identity); + bool flag = EditorGUI.EndChangeCheck(); + if (!flag) + { + vector = position; + flag = ((this.m_OldTransformPosition - vector).magnitude > 1E-05f); + if (flag) + { + center = reflectionProbe.center + this.m_OldTransformPosition; + } + } + if (flag) + { + Undo.RecordObject(reflectionProbe, "Modified Reflection Probe Origin"); + Bounds bounds = new Bounds(center, size); + vector = bounds.ClosestPoint(vector); + Vector3 vector2 = vector; + reflectionProbe.transform.position = vector2; + this.m_OldTransformPosition = vector2; + reflectionProbe.center = bounds.center - vector; + EditorUtility.SetDirty(this.target); + } + } + private void DoBoxEditing() + { + ReflectionProbe reflectionProbe = (ReflectionProbe)this.target; + Vector3 position = reflectionProbe.transform.position; + Vector3 size = reflectionProbe.size; + Vector3 a = reflectionProbe.center + position; + if (this.m_BoxEditor.OnSceneGUI(Matrix4x4.identity, ReflectionProbeEditor.kGizmoReflectionProbe, ReflectionProbeEditor.kGizmoHandleReflectionProbe, true, ref a, ref size)) + { + Undo.RecordObject(reflectionProbe, "Modified Reflection Probe AABB"); + Vector3 center = a - position; + this.ValidateAABB(ref center, ref size); + reflectionProbe.size = size; + reflectionProbe.center = center; + EditorUtility.SetDirty(this.target); + } + } + } +} diff --git a/UnityEditor/UnityEditor/RenameOverlay.cs b/UnityEditor/UnityEditor/RenameOverlay.cs index 77a16d30..2138fee4 100644 --- a/UnityEditor/UnityEditor/RenameOverlay.cs +++ b/UnityEditor/UnityEditor/RenameOverlay.cs @@ -28,6 +28,8 @@ internal class RenameOverlay private GUIView m_ClientGUIView; [NonSerialized] private Rect m_LastScreenPosition; + [NonSerialized] + private bool m_UndoRedoWasPerformed; private string k_RenameOverlayFocusName = "RenameOverlayField"; private double s_RenameEndedTime; private static GUIStyle s_DefaultTextFieldStyle = null; @@ -128,9 +130,12 @@ private void BeginRenameInternalCallback() this.RepaintClientView(); } this.m_IsWaitingForDelay = false; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoWasPerformed)); + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Combine(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoWasPerformed)); } public void EndRename(bool acceptChanges) { + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoWasPerformed)); if (!this.m_IsRenaming) { return; @@ -162,6 +167,11 @@ public void Clear() this.m_UserData = 0; this.m_IsWaitingForDelay = false; this.m_OriginalEventType = EventType.Ignore; + Undo.undoRedoPerformed = (Undo.UndoRedoCallback)Delegate.Remove(Undo.undoRedoPerformed, new Undo.UndoRedoCallback(this.UndoRedoWasPerformed)); + } + private void UndoRedoWasPerformed() + { + this.m_UndoRedoWasPerformed = true; } public bool HasKeyboardFocus() { @@ -206,6 +216,12 @@ public bool OnGUI(GUIStyle textFieldStyle) { return false; } + if (this.m_UndoRedoWasPerformed) + { + this.m_UndoRedoWasPerformed = false; + this.EndRename(false); + return false; + } if (this.m_EditFieldRect.width <= 0f || this.m_EditFieldRect.height <= 0f || this.m_TextFieldControlID == 0) { HandleUtility.Repaint(); diff --git a/UnityEditor/UnityEditor/RenderSettingsInspector.cs b/UnityEditor/UnityEditor/RenderSettingsInspector.cs new file mode 100644 index 00000000..37a6267e --- /dev/null +++ b/UnityEditor/UnityEditor/RenderSettingsInspector.cs @@ -0,0 +1,60 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CustomEditor(typeof(RenderSettings))] + internal class RenderSettingsInspector : Editor + { + private Editor m_LightingEditor; + private Editor m_FogEditor; + private Editor m_OtherRenderingEditor; + private Editor lightingEditor + { + get + { + Editor arg_2B_0; + if ((arg_2B_0 = this.m_LightingEditor) == null) + { + arg_2B_0 = (this.m_LightingEditor = Editor.CreateEditor(this.target, typeof(LightingEditor))); + } + return arg_2B_0; + } + } + private Editor fogEditor + { + get + { + Editor arg_2B_0; + if ((arg_2B_0 = this.m_FogEditor) == null) + { + arg_2B_0 = (this.m_FogEditor = Editor.CreateEditor(this.target, typeof(FogEditor))); + } + return arg_2B_0; + } + } + private Editor otherRenderingEditor + { + get + { + Editor arg_2B_0; + if ((arg_2B_0 = this.m_OtherRenderingEditor) == null) + { + arg_2B_0 = (this.m_OtherRenderingEditor = Editor.CreateEditor(this.target, typeof(OtherRenderingEditor))); + } + return arg_2B_0; + } + } + public virtual void OnEnable() + { + this.m_LightingEditor = null; + this.m_FogEditor = null; + this.m_OtherRenderingEditor = null; + } + public override void OnInspectorGUI() + { + this.lightingEditor.OnInspectorGUI(); + this.fogEditor.OnInspectorGUI(); + this.otherRenderingEditor.OnInspectorGUI(); + } + } +} diff --git a/UnityEditor/UnityEditor/RenderTextureInspector.cs b/UnityEditor/UnityEditor/RenderTextureInspector.cs index 36346249..8f9764df 100644 --- a/UnityEditor/UnityEditor/RenderTextureInspector.cs +++ b/UnityEditor/UnityEditor/RenderTextureInspector.cs @@ -5,71 +5,40 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(RenderTexture))] internal class RenderTextureInspector : TextureInspector { - private static GUIContent[] kRenderTextureAntiAliasing = new GUIContent[] + private static readonly GUIContent[] kRenderTextureAntiAliasing = new GUIContent[] { new GUIContent("None"), new GUIContent("2 samples"), new GUIContent("4 samples"), new GUIContent("8 samples") }; - private static int[] kRenderTextureAntiAliasingValues = new int[] + private static readonly int[] kRenderTextureAntiAliasingValues = new int[] { 1, 2, 4, 8 }; - private static GUIContent[] kRenderTextureDepths = new GUIContent[] - { - new GUIContent("None"), - new GUIContent("16 bit"), - new GUIContent("24 bit") - }; - private static int[] kRenderTextureDepthsValues = new int[] - { - 0, - 1, - 2 - }; private SerializedProperty m_Width; private SerializedProperty m_Height; + private SerializedProperty m_ColorFormat; private SerializedProperty m_DepthFormat; private SerializedProperty m_AntiAliasing; - private static string[] kTextureFormatsStrings = new string[] - { - "RGBA 32bit", - "Depth", - "RGBA 64bit FP", - "Shadowmap", - "RGB 16bit", - "RGBA 16bit", - "RGBA 16bit (5-1)", - string.Empty, - "RGBA 32bit (10-2)", - string.Empty, - "RGBA 64bit", - "RGBA 128bit FP", - "RG 64bit FP", - "RG 32bit FP", - "R 32bit FP", - "R 16bit FP", - "R 8bit" - }; protected override void OnEnable() { base.OnEnable(); this.m_Width = base.serializedObject.FindProperty("m_Width"); this.m_Height = base.serializedObject.FindProperty("m_Height"); this.m_AntiAliasing = base.serializedObject.FindProperty("m_AntiAliasing"); + this.m_ColorFormat = base.serializedObject.FindProperty("m_ColorFormat"); this.m_DepthFormat = base.serializedObject.FindProperty("m_DepthFormat"); } public override void OnInspectorGUI() { base.serializedObject.Update(); - RenderTexture renderTexture = this.target as RenderTexture; GUI.changed = false; GUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PrefixLabel("Size", "MiniPopup"); + EditorGUILayout.PrefixLabel("Size", EditorStyles.popup); EditorGUILayout.PropertyField(this.m_Width, GUIContent.none, new GUILayoutOption[] { GUILayout.MinWidth(40f) @@ -82,8 +51,10 @@ public override void OnInspectorGUI() GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); EditorGUILayout.IntPopup(this.m_AntiAliasing, RenderTextureInspector.kRenderTextureAntiAliasing, RenderTextureInspector.kRenderTextureAntiAliasingValues, EditorGUIUtility.TempContent("Anti-Aliasing"), new GUILayoutOption[0]); - EditorGUILayout.IntPopup(this.m_DepthFormat, RenderTextureInspector.kRenderTextureDepths, RenderTextureInspector.kRenderTextureDepthsValues, EditorGUIUtility.TempContent("Depth Buffer"), new GUILayoutOption[0]); - if (GUI.changed) + EditorGUILayout.PropertyField(this.m_ColorFormat, EditorGUIUtility.TempContent("Color Format"), new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_DepthFormat, EditorGUIUtility.TempContent("Depth Buffer"), new GUILayoutOption[0]); + RenderTexture renderTexture = this.target as RenderTexture; + if (GUI.changed && renderTexture != null) { renderTexture.Release(); } @@ -95,13 +66,13 @@ public override void OnInspectorGUI() public override string GetInfoString() { RenderTexture renderTexture = this.target as RenderTexture; - string str = renderTexture.width.ToString() + "x" + renderTexture.height.ToString(); + string text = renderTexture.width + "x" + renderTexture.height; if (!renderTexture.isPowerOfTwo) { - str += "(NPOT)"; + text += "(NPOT)"; } - str = str + " " + RenderTextureInspector.kTextureFormatsStrings[(int)renderTexture.format]; - return str + " " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySize(renderTexture)); + text = text + " " + renderTexture.format; + return text + " " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySize(renderTexture)); } } } diff --git a/UnityEditor/UnityEditor/RenderThumbnailUtility.cs b/UnityEditor/UnityEditor/RenderThumbnailUtility.cs index 685b218c..b873097f 100644 --- a/UnityEditor/UnityEditor/RenderThumbnailUtility.cs +++ b/UnityEditor/UnityEditor/RenderThumbnailUtility.cs @@ -6,7 +6,7 @@ internal class RenderThumbnailUtility { public static Bounds CalculateVisibleBounds(GameObject prefab) { - return prefab.renderer.bounds; + return prefab.GetComponent().bounds; } public static Texture2D Render(GameObject prefab) { @@ -14,7 +14,7 @@ public static Texture2D Render(GameObject prefab) { return null; } - if (prefab.renderer == null) + if (prefab.GetComponent() == null) { return null; } @@ -63,7 +63,7 @@ public static Texture2D Render(GameObject prefab) string dependency = ShaderUtil.GetDependency(material.shader, "BillboardShader"); if (dependency != null && dependency != string.Empty) { - material = (UnityEngine.Object.Instantiate(material) as Material); + material = UnityEngine.Object.Instantiate(material); material.shader = Shader.Find(dependency); material.hideFlags = HideFlags.HideAndDontSave; } @@ -71,7 +71,7 @@ public static Texture2D Render(GameObject prefab) { if (material.SetPass(k)) { - renderer.Render(j); + renderer.RenderNow(j); } } if (material != sharedMaterials[j]) diff --git a/UnityEditor/UnityEditor/RendererEditorBase.cs b/UnityEditor/UnityEditor/RendererEditorBase.cs new file mode 100644 index 00000000..88d451ac --- /dev/null +++ b/UnityEditor/UnityEditor/RendererEditorBase.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; +namespace UnityEditor +{ + internal class RendererEditorBase : Editor + { + internal class Probes + { + internal SerializedProperty m_UseLightProbes; + internal SerializedProperty m_ReflectionProbeUsage; + internal SerializedProperty m_ProbeAnchor; + private GUIContent m_UseLightProbesStyle = EditorGUIUtility.TextContent("Renderer.UseLightProbes"); + private GUIContent m_ReflectionProbeUsageStyle = EditorGUIUtility.TextContent("Renderer.ReflectionProbeUsage"); + private GUIContent m_ProbeAnchorStyle = EditorGUIUtility.TextContent("Renderer.ProbeAnchor"); + private List m_BlendInfo = new List(); + internal void Initialize(SerializedObject serializedObject, bool initializeLightProbes) + { + if (initializeLightProbes) + { + this.m_UseLightProbes = serializedObject.FindProperty("m_UseLightProbes"); + } + this.m_ReflectionProbeUsage = serializedObject.FindProperty("m_ReflectionProbeUsage"); + this.m_ProbeAnchor = serializedObject.FindProperty("m_ProbeAnchor"); + } + internal void Initialize(SerializedObject serializedObject) + { + this.Initialize(serializedObject, true); + } + internal void OnGUI(Renderer renderer, bool useMiniStyle) + { + if (this.m_UseLightProbes != null) + { + EditorGUI.BeginDisabledGroup(LightmapEditorSettings.IsLightmappedOrDynamicLightmappedForRendering(renderer)); + if (!useMiniStyle) + { + EditorGUILayout.PropertyField(this.m_UseLightProbes, this.m_UseLightProbesStyle, new GUILayoutOption[0]); + } + else + { + ModuleUI.GUIToggle(this.m_UseLightProbesStyle, this.m_UseLightProbes); + } + EditorGUI.EndDisabledGroup(); + } + if (!useMiniStyle) + { + this.m_ReflectionProbeUsage.intValue = (int)((ReflectionProbeUsage)EditorGUILayout.EnumPopup(this.m_ReflectionProbeUsageStyle, (ReflectionProbeUsage)this.m_ReflectionProbeUsage.intValue, new GUILayoutOption[0])); + } + else + { + ModuleUI.GUIPopup(this.m_ReflectionProbeUsageStyle, this.m_ReflectionProbeUsage, Enum.GetNames(typeof(ReflectionProbeUsage))); + } + bool flag = this.m_ReflectionProbeUsage.intValue != 0; + if ((this.m_UseLightProbes != null && this.m_UseLightProbes.boolValue) || flag) + { + EditorGUI.indentLevel++; + if (!useMiniStyle) + { + EditorGUILayout.PropertyField(this.m_ProbeAnchor, this.m_ProbeAnchorStyle, new GUILayoutOption[0]); + } + else + { + ModuleUI.GUIObject(this.m_ProbeAnchorStyle, this.m_ProbeAnchor); + } + if (flag) + { + renderer.GetClosestReflectionProbes(this.m_BlendInfo); + RendererEditorBase.Probes.ShowClosestReflectionProbes(this.m_BlendInfo); + } + EditorGUI.indentLevel--; + } + } + internal static void ShowClosestReflectionProbes(List blendInfos) + { + float num = 20f; + float num2 = 60f; + EditorGUI.BeginDisabledGroup(true); + for (int i = 0; i < blendInfos.Count; i++) + { + Rect rect = GUILayoutUtility.GetRect(0f, 16f); + rect = EditorGUI.IndentedRect(rect); + float width = rect.width - num - num2; + Rect position = rect; + position.width = num; + GUI.Label(position, "#" + i, EditorStyles.miniLabel); + position.x += position.width; + position.width = width; + EditorGUI.ObjectField(position, blendInfos[i].probe, typeof(ReflectionProbe), true); + position.x += position.width; + position.width = num2; + GUI.Label(position, "Weight " + blendInfos[i].weight.ToString("f2"), EditorStyles.miniLabel); + } + EditorGUI.EndDisabledGroup(); + } + internal static string[] GetFieldsStringArray() + { + return new string[] + { + "m_UseLightProbes", + "m_ReflectionProbeUsage", + "m_ProbeAnchor" + }; + } + } + private SerializedProperty m_SortingOrder; + private SerializedProperty m_SortingLayerID; + private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("Renderer.SortingLayer"); + private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("Renderer.SortingOrder"); + protected RendererEditorBase.Probes m_Probes; + public virtual void OnEnable() + { + this.m_SortingOrder = base.serializedObject.FindProperty("m_SortingOrder"); + this.m_SortingLayerID = base.serializedObject.FindProperty("m_SortingLayerID"); + } + protected void RenderSortingLayerFields() + { + EditorGUILayout.Space(); + EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup, EditorStyles.label); + EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + } + protected void InitializeProbeFields() + { + this.m_Probes = new RendererEditorBase.Probes(); + this.m_Probes.Initialize(base.serializedObject); + } + protected void RenderProbeFields() + { + this.m_Probes.OnGUI((Renderer)this.target, false); + } + } +} diff --git a/UnityEditor/UnityEditor/RendererModuleUI.cs b/UnityEditor/UnityEditor/RendererModuleUI.cs index b0de871b..c2073321 100644 --- a/UnityEditor/UnityEditor/RendererModuleUI.cs +++ b/UnityEditor/UnityEditor/RendererModuleUI.cs @@ -28,6 +28,8 @@ private class Texts public GUIContent castShadows = new GUIContent("Cast Shadows", "Only opaque materials cast shadows"); public GUIContent receiveShadows = new GUIContent("Receive Shadows", "Only opaque materials receive shadows"); public GUIContent normalDirection = new GUIContent("Normal Direction", "Value between 0.0 and 1.0. If 1.0 is used, normals will point towards camera. If 0.0 is used, normals will point out in the corner direction of the particle."); + public GUIContent sortingLayer = EditorGUIUtility.TextContent("Renderer.SortingLayer"); + public GUIContent sortingOrder = EditorGUIUtility.TextContent("Renderer.SortingOrder"); public string[] particleTypes = new string[] { "Billboard", @@ -48,6 +50,8 @@ private class Texts private SerializedProperty m_CastShadows; private SerializedProperty m_ReceiveShadows; private SerializedProperty m_Material; + private SerializedProperty m_SortingOrder; + private SerializedProperty m_SortingLayerID; private SerializedProperty m_RenderMode; private SerializedProperty[] m_Meshes = new SerializedProperty[4]; private SerializedProperty[] m_ShownMeshes; @@ -58,6 +62,7 @@ private class Texts private SerializedProperty m_SortMode; private SerializedProperty m_SortingFudge; private SerializedProperty m_NormalDirection; + private RendererEditorBase.Probes m_Probes; private static RendererModuleUI.Texts s_Texts; public RendererModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ParticleSystemRenderer", displayName, ModuleUI.VisibilityState.VisibleAndFolded) { @@ -72,6 +77,8 @@ protected override void Init() this.m_CastShadows = base.GetProperty0("m_CastShadows"); this.m_ReceiveShadows = base.GetProperty0("m_ReceiveShadows"); this.m_Material = base.GetProperty0("m_Materials.Array.data[0]"); + this.m_SortingOrder = base.GetProperty0("m_SortingOrder"); + this.m_SortingLayerID = base.GetProperty0("m_SortingLayerID"); this.m_RenderMode = base.GetProperty0("m_RenderMode"); this.m_MaxParticleSize = base.GetProperty0("m_MaxParticleSize"); this.m_CameraVelocityScale = base.GetProperty0("m_CameraVelocityScale"); @@ -80,6 +87,8 @@ protected override void Init() this.m_SortingFudge = base.GetProperty0("m_SortingFudge"); this.m_SortMode = base.GetProperty0("m_SortMode"); this.m_NormalDirection = base.GetProperty0("m_NormalDirection"); + this.m_Probes = new RendererEditorBase.Probes(); + this.m_Probes.Initialize(base.serializedObject, false); this.m_Meshes[0] = base.GetProperty0("m_Mesh"); this.m_Meshes[1] = base.GetProperty0("m_Mesh1"); this.m_Meshes[2] = base.GetProperty0("m_Mesh2"); @@ -133,9 +142,13 @@ public override void OnInspectorGUI(ParticleSystem s) } ModuleUI.GUIPopup(RendererModuleUI.s_Texts.sortMode, this.m_SortMode, RendererModuleUI.s_Texts.sortTypes); ModuleUI.GUIFloat(RendererModuleUI.s_Texts.sortingFudge, this.m_SortingFudge); - ModuleUI.GUIToggle(RendererModuleUI.s_Texts.castShadows, this.m_CastShadows); + ModuleUI.GUIPopup(RendererModuleUI.s_Texts.castShadows, this.m_CastShadows, this.m_CastShadows.enumDisplayNames); ModuleUI.GUIToggle(RendererModuleUI.s_Texts.receiveShadows, this.m_ReceiveShadows); ModuleUI.GUIFloat(RendererModuleUI.s_Texts.maxParticleSize, this.m_MaxParticleSize); + EditorGUILayout.Space(); + EditorGUILayout.SortingLayerField(RendererModuleUI.s_Texts.sortingLayer, this.m_SortingLayerID, ParticleSystemStyles.Get().popup, ParticleSystemStyles.Get().label); + ModuleUI.GUIInt(RendererModuleUI.s_Texts.sortingOrder, this.m_SortingOrder); + this.m_Probes.OnGUI(s.GetComponent(), true); } private void DoListOfMeshesGUI() { diff --git a/UnityEditor/UnityEditor/RuntimeClassRegistry.cs b/UnityEditor/UnityEditor/RuntimeClassRegistry.cs index 669bff56..e20b03b2 100644 --- a/UnityEditor/UnityEditor/RuntimeClassRegistry.cs +++ b/UnityEditor/UnityEditor/RuntimeClassRegistry.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using UnityEditorInternal; using UnityEngine; +using UnityEngine.Audio; namespace UnityEditor { internal class RuntimeClassRegistry @@ -251,6 +252,7 @@ protected void InitRuntimeClassRegistry() this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimationClip), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimationEvent)); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AsyncOperation)); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Resources), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(CacheIndex)); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Keyframe)); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(RenderTexture)); @@ -271,14 +273,17 @@ protected void InitRuntimeClassRegistry() this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(Canvas), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(RectTransform), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AssemblyIsEditorAssembly), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SharedBetweenAnimatorsAttribute), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimatorStateInfo), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimatorTransitionInfo), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AnimatorClipInfo), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(SkeletonBone), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(HumanBone), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UIVertex), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UICharInfo), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(UILineInfo), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AudioClip), "all"); + this.AddManagedDependenciesForFunctionalityGroup("Runtime", typeof(AudioMixer), "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", "iPhone", "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNI", "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", "AndroidJNIHelper", "all"); @@ -303,16 +308,16 @@ protected void InitRuntimeClassRegistry() { this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SamsungTV", "all"); } - if (buildTargetGroup == BuildTargetGroup.iPhone) + if (buildTargetGroup == BuildTargetGroup.iOS) { this.AddManagedDependenciesForFunctionalityGroup("Runtime", "iPhoneKeyboard"); } - if (buildTargetGroup == BuildTargetGroup.iPhone || (buildTargetGroup == BuildTargetGroup.Standalone && (this.buildTarget == BuildTarget.StandaloneOSXIntel || this.buildTarget == BuildTarget.StandaloneOSXIntel64 || this.buildTarget == BuildTarget.StandaloneOSXUniversal))) + if (buildTargetGroup == BuildTargetGroup.iOS || (buildTargetGroup == BuildTargetGroup.Standalone && (this.buildTarget == BuildTarget.StandaloneOSXIntel || this.buildTarget == BuildTarget.StandaloneOSXIntel64 || this.buildTarget == BuildTarget.StandaloneOSXUniversal))) { this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SocialPlatforms.GameCenter.GameCenterPlatform", "all"); this.AddManagedDependenciesForFunctionalityGroup("Runtime", "SocialPlatforms.GameCenter.GcLeaderboard", "all"); } - if (buildTargetGroup == BuildTargetGroup.iPhone || buildTargetGroup == BuildTargetGroup.Android || buildTargetGroup == BuildTargetGroup.BB10 || buildTargetGroup == BuildTargetGroup.WP8 || buildTargetGroup == BuildTargetGroup.Tizen) + if (buildTargetGroup == BuildTargetGroup.iOS || buildTargetGroup == BuildTargetGroup.Android || buildTargetGroup == BuildTargetGroup.BlackBerry || buildTargetGroup == BuildTargetGroup.WP8 || buildTargetGroup == BuildTargetGroup.Metro || buildTargetGroup == BuildTargetGroup.Tizen) { this.AddManagedDependenciesForFunctionalityGroup("Runtime", "TouchScreenKeyboard"); } @@ -364,6 +369,13 @@ protected void InitRuntimeClassRegistry() { this.AddManagedBaseClass("UnityEngine.AndroidJavaProxy"); } + string[] dontStripClassNames = RuntimeInitializeOnLoadManager.dontStripClassNames; + string[] array = dontStripClassNames; + for (int i = 0; i < array.Length; i++) + { + string className = array[i]; + this.AddManagedBaseClass(className); + } } internal void AddMethodToPreserve(string assembly, string @namespace, string klassName, string methodName) { diff --git a/UnityEditor/UnityEditor/SceneFXWindow.cs b/UnityEditor/UnityEditor/SceneFXWindow.cs index cbe66032..91a79b10 100644 --- a/UnityEditor/UnityEditor/SceneFXWindow.cs +++ b/UnityEditor/UnityEditor/SceneFXWindow.cs @@ -2,101 +2,79 @@ using UnityEngine; namespace UnityEditor { - internal class SceneFXWindow : EditorWindow + internal class SceneFXWindow : PopupWindowContent { private class Styles { - public GUIStyle background = "grey_border"; - public GUIStyle menuItem = "MenuItem"; + public readonly GUIStyle menuItem = "MenuItem"; } private const float kFrameWidth = 1f; private static SceneFXWindow s_SceneFXWindow; - private static long s_LastClosedTime; private static SceneFXWindow.Styles s_Styles; - private SceneView m_SceneView; - private SceneFXWindow() + private readonly SceneView m_SceneView; + public SceneFXWindow(SceneView sceneView) { - base.hideFlags = HideFlags.DontSave; - base.wantsMouseMove = true; + this.m_SceneView = sceneView; } - private float GetHeight() + public override Vector2 GetWindowSize() { - return 64f; + float y = 66f; + Vector2 result = new Vector2(160f, y); + return result; } - private void OnDisable() + public override void OnGUI(Rect rect) { - SceneFXWindow.s_LastClosedTime = DateTime.Now.Ticks / 10000L; - SceneFXWindow.s_SceneFXWindow = null; - } - internal static bool ShowAtPosition(Rect buttonRect, SceneView view) - { - long num = DateTime.Now.Ticks / 10000L; - if (num >= SceneFXWindow.s_LastClosedTime + 50L) + if (this.m_SceneView == null || this.m_SceneView.m_SceneViewState == null) { - Event.current.Use(); - if (SceneFXWindow.s_SceneFXWindow == null) - { - SceneFXWindow.s_SceneFXWindow = ScriptableObject.CreateInstance(); - } - SceneFXWindow.s_SceneFXWindow.Init(buttonRect, view); - return true; + return; } - return false; - } - private void Init(Rect buttonRect, SceneView view) - { - buttonRect = GUIUtility.GUIToScreenRect(buttonRect); - this.m_SceneView = view; - float num = 2f + this.GetHeight(); - num = Mathf.Min(num, 900f); - Vector2 windowSize = new Vector2(150f, num); - base.ShowAsDropDown(buttonRect, windowSize); - } - internal void OnGUI() - { if (Event.current.type == EventType.Layout) { return; } + if (SceneFXWindow.s_Styles == null) + { + SceneFXWindow.s_Styles = new SceneFXWindow.Styles(); + } + this.Draw(rect); if (Event.current.type == EventType.MouseMove) { Event.current.Use(); } - if (SceneFXWindow.s_Styles == null) + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) { - SceneFXWindow.s_Styles = new SceneFXWindow.Styles(); + base.editorWindow.Close(); + GUIUtility.ExitGUI(); } - this.Draw(this.GetHeight()); - GUI.Label(new Rect(0f, 0f, base.position.width, base.position.height), GUIContent.none, SceneFXWindow.s_Styles.background); } - private void Draw(float height) + private void Draw(Rect rect) { if (this.m_SceneView == null || this.m_SceneView.m_SceneViewState == null) { return; } - Rect rect = new Rect(1f, 1f, base.position.width - 2f, 16f); + Rect rect2 = new Rect(1f, 1f, rect.width - 2f, 16f); SceneView.SceneViewState state = this.m_SceneView.m_SceneViewState; - this.DrawListElement(rect, "Skybox", state.showSkybox, delegate(bool value) + this.DrawListElement(rect2, "Skybox", state.showSkybox, delegate(bool value) { state.showSkybox = value; }); - rect.y += 16f; - this.DrawListElement(rect, "Fog", state.showFog, delegate(bool value) + rect2.y += 16f; + this.DrawListElement(rect2, "Fog", state.showFog, delegate(bool value) { state.showFog = value; }); - rect.y += 16f; - this.DrawListElement(rect, "Flares", state.showFlares, delegate(bool value) + rect2.y += 16f; + this.DrawListElement(rect2, "Flares", state.showFlares, delegate(bool value) { state.showFlares = value; }); - rect.y += 16f; - this.DrawListElement(rect, "Animated Materials", state.showMaterialUpdate, delegate(bool value) + rect2.y += 16f; + this.DrawListElement(rect2, "Animated Materials", state.showMaterialUpdate, delegate(bool value) { state.showMaterialUpdate = value; }); - rect.y += 16f; + rect2.y += 16f; } private void DrawListElement(Rect rect, string toggleName, bool value, Action setValue) { diff --git a/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs b/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs index 1d43936c..f2ef9307 100644 --- a/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs +++ b/UnityEditor/UnityEditor/SceneHierarchySortingWindow.cs @@ -12,6 +12,7 @@ private class Styles } public class InputData { + public string m_TypeName; public string m_Name; public bool m_Selected; } diff --git a/UnityEditor/UnityEditor/SceneHierarchyWindow.cs b/UnityEditor/UnityEditor/SceneHierarchyWindow.cs index a6cdd01f..a6b3336e 100644 --- a/UnityEditor/UnityEditor/SceneHierarchyWindow.cs +++ b/UnityEditor/UnityEditor/SceneHierarchyWindow.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Reflection; using UnityEditorInternal; using UnityEngine; @@ -11,10 +12,10 @@ private class Styles { private const string kCustomSorting = "CustomSorting"; private const string kWarningSymbol = "console.warnicon.sml"; - private const string kWarningMessage = "Custom fetch is taking a lot of time. Could effect editor frame rate."; + private const string kWarningMessage = "The current sorting method is taking a lot of time. Consider using 'Transform Sort' in playmode for better performance."; public GUIContent defaultSortingContent = new GUIContent(EditorGUIUtility.FindTexture("CustomSorting")); public GUIContent createContent = new GUIContent("Create"); - public GUIContent fetchWarning = new GUIContent(string.Empty, EditorGUIUtility.FindTexture("console.warnicon.sml"), "Custom fetch is taking a lot of time. Could effect editor frame rate."); + public GUIContent fetchWarning = new GUIContent(string.Empty, EditorGUIUtility.FindTexture("console.warnicon.sml"), "The current sorting method is taking a lot of time. Consider using 'Transform Sort' in playmode for better performance."); public GUIStyle MiniButton; public Styles() { @@ -32,12 +33,11 @@ public Styles() private string m_CurrentSortMethod = string.Empty; [NonSerialized] private int m_LastFramedID = -1; - private List m_SortFunctionNames; - private Dictionary m_SortFunctions; + private Dictionary m_SortingObjects; private bool m_AllowAlphaNumericalSort; - private bool m_AllowManualSort; [NonSerialized] private bool m_DidSelectSearchResult; + public static bool s_Debug = false; private string currentSortMethod { get @@ -47,29 +47,21 @@ private string currentSortMethod set { this.m_CurrentSortMethod = value; - if (!this.m_SortFunctions.ContainsKey(this.m_CurrentSortMethod)) + if (!this.m_SortingObjects.ContainsKey(this.m_CurrentSortMethod)) { - if (this.m_AllowManualSort) - { - this.m_CurrentSortMethod = "TransformSort"; - } - else - { - this.m_CurrentSortMethod = "AlphabeticalSort"; - } + this.m_CurrentSortMethod = this.GetNameForType(typeof(TransformSort)); } - GameObjectTreeViewDataSource gameObjectTreeViewDataSource = this.treeView.data as GameObjectTreeViewDataSource; - gameObjectTreeViewDataSource.compareData.comparerImpl = this.m_SortFunctions[this.m_CurrentSortMethod]; - gameObjectTreeViewDataSource.compareData.comparerImplementsCompare = (gameObjectTreeViewDataSource.compareData.comparerImpl.GetType().GetMethod("Compare").DeclaringType != typeof(BaseHierarchySort)); - AssetOrGameObjectTreeViewDragging assetOrGameObjectTreeViewDragging = this.treeView.dragging as AssetOrGameObjectTreeViewDragging; - assetOrGameObjectTreeViewDragging.allowDragBetween = !gameObjectTreeViewDataSource.compareData.comparerImplementsCompare; + GameObjectTreeViewDataSource gameObjectTreeViewDataSource = (GameObjectTreeViewDataSource)this.treeView.data; + gameObjectTreeViewDataSource.sortingState.sortingObject = this.m_SortingObjects[this.m_CurrentSortMethod]; + GameObjectsTreeViewDragging gameObjectsTreeViewDragging = (GameObjectsTreeViewDragging)this.treeView.dragging; + gameObjectsTreeViewDragging.allowDragBetween = !gameObjectTreeViewDataSource.sortingState.implementsCompare; } } private bool hasSortMethods { get { - return this.m_SortFunctions.Count > 1; + return this.m_SortingObjects.Count > 1; } } private Rect treeViewRect @@ -114,15 +106,34 @@ private void Init() TreeView expr_AF = this.m_TreeView; expr_AF.dragEndedCallback = (Action)Delegate.Combine(expr_AF.dragEndedCallback, new Action(this.OnDragEndedCallback)); this.m_TreeView.deselectOnUnhandledMouseDown = true; - GameObjectTreeViewDataSource data = new GameObjectTreeViewDataSource(this.m_TreeView, 0, false, false); - ITreeViewDragging dragging = new AssetOrGameObjectTreeViewDragging(this.m_TreeView, HierarchyType.GameObjects); - ITreeViewGUI gui = new GameObjectTreeViewGUI(this.m_TreeView, false); - this.m_TreeView.Init(this.treeViewRect, data, gui, dragging); - this.m_AllowAlphaNumericalSort = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); - this.m_AllowManualSort = EditorPrefs.GetBool("AllowManualHierarchy", true); + GameObjectTreeViewDataSource gameObjectTreeViewDataSource = new GameObjectTreeViewDataSource(this.m_TreeView, 0, false, false); + GameObjectsTreeViewDragging dragging = new GameObjectsTreeViewDragging(this.m_TreeView); + GameObjectTreeViewGUI gui = new GameObjectTreeViewGUI(this.m_TreeView, false); + this.m_TreeView.Init(this.treeViewRect, gameObjectTreeViewDataSource, gui, dragging); + gameObjectTreeViewDataSource.searchMode = (int)this.m_SearchMode; + gameObjectTreeViewDataSource.searchString = this.m_SearchFilter; + this.m_AllowAlphaNumericalSort = (EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false) || InternalEditorUtility.inBatchMode); this.SetUpSortMethodLists(); this.m_TreeView.ReloadData(); } + internal void SelectPrevious() + { + this.m_TreeView.OffsetSelection(-1); + } + internal void SelectNext() + { + this.m_TreeView.OffsetSelection(1); + } + public UnityEngine.Object[] GetCurrentVisibleObjects() + { + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + UnityEngine.Object[] array = new UnityEngine.Object[visibleRows.Count]; + for (int i = 0; i < visibleRows.Count; i++) + { + array[i] = ((GameObjectTreeViewItem)visibleRows[i]).objectPPTR; + } + return array; + } private void Awake() { this.m_HierarchyType = HierarchyType.GameObjects; @@ -215,7 +226,7 @@ public void ReloadData() } public void SearchChanged() { - GameObjectTreeViewDataSource gameObjectTreeViewDataSource = this.treeView.data as GameObjectTreeViewDataSource; + GameObjectTreeViewDataSource gameObjectTreeViewDataSource = (GameObjectTreeViewDataSource)this.treeView.data; if (gameObjectTreeViewDataSource.searchMode == (int)base.searchMode && gameObjectTreeViewDataSource.searchString == this.m_SearchFilter) { return; @@ -230,10 +241,6 @@ public void SearchChanged() } private void OnSelectionChange() { - if (!this.treeView.IsVisible(Selection.activeInstanceID) && !string.IsNullOrEmpty(this.m_SearchFilter)) - { - base.ClearSearchFilter(); - } this.treeView.SetSelection(Selection.instanceIDs, true); base.Repaint(); } @@ -251,14 +258,13 @@ private float DoSearchResultPathGUI() GUILayout.FlexibleSpace(); Rect rect = EditorGUILayout.BeginVertical(EditorStyles.inspectorBig, new GUILayoutOption[0]); GUILayout.Label("Path:", new GUILayoutOption[0]); - int num = 1; if (this.m_TreeView.HasSelection()) { - TreeViewItem treeViewItem = this.m_TreeView.FindNode(this.m_TreeView.GetSelection()[0]); - if (treeViewItem != null) + int instanceID = this.m_TreeView.GetSelection()[0]; + IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); + hierarchyProperty.Find(instanceID, null); + if (hierarchyProperty.isValid) { - IHierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.GameObjects); - hierarchyProperty.Find(treeViewItem.id, null); do { EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); @@ -266,7 +272,6 @@ private float DoSearchResultPathGUI() GUILayout.Label(hierarchyProperty.name, new GUILayoutOption[0]); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); - num++; } while (hierarchyProperty.Parent()); } @@ -284,41 +289,17 @@ private void DoTreeView(float searchPathHeight) Rect treeViewRect = this.treeViewRect; treeViewRect.height -= searchPathHeight; this.treeView.OnGUI(treeViewRect, this.m_TreeViewKeyboardControlID); - this.HandleUnusedDragEvents(this.treeViewRect); - } - private void HandleUnusedDragEvents(Rect rect) - { - Event current = Event.current; - EventType type = current.type; - if (type == EventType.DragUpdated || type == EventType.DragPerform) - { - if (rect.Contains(current.mousePosition)) - { - bool flag = current.type == EventType.DragPerform; - DragAndDrop.visualMode = InternalEditorUtility.HierarchyWindowDrag(null, flag, InternalEditorUtility.HierarchyDropMode.kHierarchyDropUpon); - if (flag && DragAndDrop.visualMode != DragAndDropVisualMode.None) - { - DragAndDrop.AcceptDrag(); - List list = new List(DragAndDrop.objectReferences); - int[] array = new int[list.Count]; - for (int i = 0; i < list.Count; i++) - { - if (!(list[i] == null)) - { - array[i] = list[i].GetInstanceID(); - } - } - this.OnDragEndedCallback(array, false); - } - current.Use(); - } - } } private void DoToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar, new GUILayoutOption[0]); this.CreateGameObjectPopup(); GUILayout.Space(6f); + if (SceneHierarchyWindow.s_Debug) + { + GUILayout.Label(string.Empty + this.m_TreeView.data.GetVisibleRows().Count, EditorStyles.miniLabel, new GUILayoutOption[0]); + GUILayout.Space(6f); + } GUILayout.FlexibleSpace(); Event current = Event.current; if (base.hasSearchFilterFocus && current.type == EventType.KeyDown && (current.keyCode == KeyCode.DownArrow || current.keyCode == KeyCode.UpArrow)) @@ -339,7 +320,7 @@ private void DoToolbar() GUILayout.Space(6f); if (this.hasSortMethods) { - if (Application.isPlaying && (this.treeView.data as GameObjectTreeViewDataSource).isFetchAIssue) + if (Application.isPlaying && ((GameObjectTreeViewDataSource)this.treeView.data).isFetchAIssue) { GUILayout.Toggle(false, SceneHierarchyWindow.s_Styles.fetchWarning, SceneHierarchyWindow.s_Styles.MiniButton, new GUILayoutOption[0]); } @@ -402,71 +383,79 @@ private void SortMethodsDropDown() { if (this.hasSortMethods) { - GUIContent gUIContent = this.m_SortFunctions[this.currentSortMethod].content; + GUIContent gUIContent = this.m_SortingObjects[this.currentSortMethod].content; if (gUIContent == null) { gUIContent = SceneHierarchyWindow.s_Styles.defaultSortingContent; gUIContent.tooltip = this.currentSortMethod; } Rect rect = GUILayoutUtility.GetRect(gUIContent, EditorStyles.toolbarButton); - if (EditorGUI.ButtonMouseDown(rect, gUIContent, FocusType.Passive, EditorStyles.toolbarButton) && SceneHierarchySortingWindow.ShowAtPosition(new Vector2(rect.x, rect.y + rect.height), this.m_SortFunctionNames, new SceneHierarchySortingWindow.OnSelectCallback(this.SortFunctionCallback))) + if (EditorGUI.ButtonMouseDown(rect, gUIContent, FocusType.Passive, EditorStyles.toolbarButton)) { - GUIUtility.ExitGUI(); + List list = new List(); + foreach (KeyValuePair current in this.m_SortingObjects) + { + list.Add(new SceneHierarchySortingWindow.InputData + { + m_TypeName = current.Key, + m_Name = ObjectNames.NicifyVariableName(current.Key), + m_Selected = current.Key == this.m_CurrentSortMethod + }); + } + if (SceneHierarchySortingWindow.ShowAtPosition(new Vector2(rect.x, rect.y + rect.height), list, new SceneHierarchySortingWindow.OnSelectCallback(this.SortFunctionCallback))) + { + GUIUtility.ExitGUI(); + } } } } private void SetUpSortMethodLists() { - this.m_SortFunctionNames = new List(); - this.m_SortFunctions = new Dictionary(); + this.m_SortingObjects = new Dictionary(); Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; for (int i = 0; i < loadedAssemblies.Length; i++) { Assembly assembly = loadedAssemblies[i]; foreach (BaseHierarchySort current in AssemblyHelper.FindImplementors(assembly)) { - string text = current.ToString(); - int num = text.LastIndexOf('.'); - if (num > -1) + if (current.GetType() != typeof(AlphabeticalSort) || this.m_AllowAlphaNumericalSort) { - text = text.Substring(num + 1); - } - if (!(text == "TransformSort") || this.m_AllowManualSort) - { - if (!(text == "AlphabeticalSort") || this.m_AllowAlphaNumericalSort) - { - this.m_SortFunctions.Add(text, current); - SceneHierarchySortingWindow.InputData inputData = new SceneHierarchySortingWindow.InputData(); - inputData.m_Name = text; - this.m_SortFunctionNames.Add(inputData); - } + string nameForType = this.GetNameForType(current.GetType()); + this.m_SortingObjects.Add(nameForType, current); } } } this.currentSortMethod = this.m_CurrentSortMethod; - foreach (SceneHierarchySortingWindow.InputData current2 in this.m_SortFunctionNames) - { - if (current2.m_Name == this.m_CurrentSortMethod) - { - current2.m_Selected = true; - break; - } - } + } + private string GetNameForType(Type type) + { + return type.Name; } private void SortFunctionCallback(SceneHierarchySortingWindow.InputData data) { - foreach (SceneHierarchySortingWindow.InputData current in this.m_SortFunctionNames) + this.SetSortFunction(data.m_TypeName); + } + public void SetSortFunction(Type sortType) + { + this.SetSortFunction(this.GetNameForType(sortType)); + } + private void SetSortFunction(string sortTypeName) + { + if (!this.m_SortingObjects.ContainsKey(sortTypeName)) { - current.m_Selected = (current == data); + Debug.LogError("Invalid search type name: " + sortTypeName); + return; + } + this.currentSortMethod = sortTypeName; + if (this.treeView.GetSelection().Any()) + { + this.treeView.Frame(this.treeView.GetSelection().First(), true, false); } - this.currentSortMethod = data.m_Name; - this.treeView.SetSelection(this.treeView.GetSelection(), true); this.treeView.ReloadData(); } public void DirtySortingMethods() { this.m_AllowAlphaNumericalSort = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false); - this.m_AllowManualSort = EditorPrefs.GetBool("AllowManualHierarchy", true); this.SetUpSortMethodLists(); this.treeView.SetSelection(this.treeView.GetSelection(), true); this.treeView.ReloadData(); diff --git a/UnityEditor/UnityEditor/SceneModeUtility.cs b/UnityEditor/UnityEditor/SceneModeUtility.cs index bd8ed65a..3dcad4ff 100644 --- a/UnityEditor/UnityEditor/SceneModeUtility.cs +++ b/UnityEditor/UnityEditor/SceneModeUtility.cs @@ -107,15 +107,15 @@ public static Type SearchBar(params Type[] types) { Type type = types[i]; Texture2D i2; - if (type == typeof(Terrain)) + if (type == typeof(Renderer)) { - i2 = (EditorGUIUtility.IconContent("Terrain Icon").image as Texture2D); + i2 = (EditorGUIUtility.IconContent("MeshRenderer Icon").image as Texture2D); } else { - if (type == typeof(Renderer)) + if (type == typeof(Terrain)) { - i2 = (EditorGUIUtility.IconContent("MeshRenderer Icon").image as Texture2D); + i2 = (EditorGUIUtility.IconContent("Terrain Icon").image as Texture2D); } else { diff --git a/UnityEditor/UnityEditor/SceneRenderModeWindow.cs b/UnityEditor/UnityEditor/SceneRenderModeWindow.cs new file mode 100644 index 00000000..cce99928 --- /dev/null +++ b/UnityEditor/UnityEditor/SceneRenderModeWindow.cs @@ -0,0 +1,185 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class SceneRenderModeWindow : PopupWindowContent + { + private class Styles + { + public static readonly GUIStyle sMenuItem = "MenuItem"; + public static readonly GUIStyle sSeparator = "sv_iconselector_sep"; + public static readonly GUIContent sShadedHeader = EditorGUIUtility.TextContent("SceneRenderMode.Headers.ShadingMode"); + public static readonly GUIContent sMiscellaneous = EditorGUIUtility.TextContent("SceneRenderMode.Headers.Miscellaneous"); + public static readonly GUIContent sDeferredHeader = EditorGUIUtility.TextContent("SceneRenderMode.Headers.Deferred"); + public static readonly GUIContent sGlobalIlluminationHeader = EditorGUIUtility.TextContent("SceneRenderMode.Headers.GlobalIllumination"); + public static readonly GUIContent sResolutionToggle = EditorGUIUtility.TextContent("SceneRenderMode.Headers.ResolutionToggle"); + public static readonly GUIContent[] sRenderModeOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("SceneRenderMode.Options.Shaded"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Wireframe"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.ShadedWireframe"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.ShadowCascades"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.RenderPaths"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.AlphaChannel"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Overdraw"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Mipmaps"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.DeferredAlbedo"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.DeferredSpecular"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.DeferredSmoothness"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.DeferredNormal"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Charting"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Systems"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Albedo"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Emissive"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Irradiance"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Directionality"), + EditorGUIUtility.TextContent("SceneRenderMode.Options.Baked"), + new GUIContent("Clustering [internal]"), + new GUIContent("Lit Clustering [internal]") + }; + } + private const float m_WindowWidth = 205f; + private const int kMenuHeaderCount = 4; + private const int kNumInternalRenderModes = 2; + private const float kSeparatorHeight = 3f; + private const float kFrameWidth = 1f; + private const float kHeaderHorizontalPadding = 5f; + private const float kHeaderVerticalPadding = 1f; + private const float kShowLightmapResolutionHeight = 22f; + private const float kTogglePadding = 7f; + private readonly float m_WindowHeight = (float)SceneRenderModeWindow.sMenuRowCount * 16f + 9f + 22f; + private static readonly int sRenderModeCount = (!Unsupported.IsDeveloperBuild()) ? (SceneRenderModeWindow.Styles.sRenderModeOptions.Length - 2) : SceneRenderModeWindow.Styles.sRenderModeOptions.Length; + private static readonly int sMenuRowCount = SceneRenderModeWindow.sRenderModeCount + 4; + private SerializedProperty m_EnableRealtimeGI; + private SerializedProperty m_EnableBakedGI; + private readonly SceneView m_SceneView; + public SceneRenderModeWindow(SceneView sceneView) + { + this.m_SceneView = sceneView; + } + public override Vector2 GetWindowSize() + { + return new Vector2(205f, this.m_WindowHeight); + } + public override void OnOpen() + { + SerializedObject serializedObject = new SerializedObject(LightmapEditorSettings.GetLightmapSettings()); + this.m_EnableRealtimeGI = serializedObject.FindProperty("m_GISettings.m_EnableRealtimeLightmaps"); + this.m_EnableBakedGI = serializedObject.FindProperty("m_GISettings.m_EnableBakedLightmaps"); + } + public override void OnGUI(Rect rect) + { + if (this.m_SceneView == null || this.m_SceneView.m_SceneViewState == null) + { + return; + } + if (Event.current.type == EventType.Layout) + { + return; + } + this.Draw(base.editorWindow, rect.width); + if (Event.current.type == EventType.MouseMove) + { + Event.current.Use(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + base.editorWindow.Close(); + GUIUtility.ExitGUI(); + } + } + private void DrawSeparator(ref Rect rect) + { + Rect position = rect; + position.x += 5f; + position.y += 3f; + position.width -= 10f; + position.height = 3f; + GUI.Label(position, GUIContent.none, SceneRenderModeWindow.Styles.sSeparator); + rect.y += 3f; + } + private void DrawHeader(ref Rect rect, GUIContent label) + { + Rect position = rect; + position.y += 1f; + position.x += 5f; + position.width = EditorStyles.miniLabel.CalcSize(label).x; + position.height = EditorStyles.miniLabel.CalcSize(label).y; + GUI.Label(position, label, EditorStyles.miniLabel); + rect.y += 16f; + } + private void Draw(EditorWindow caller, float listElementWidth) + { + Rect rect = new Rect(0f, 0f, listElementWidth, 16f); + this.DrawHeader(ref rect, SceneRenderModeWindow.Styles.sShadedHeader); + for (int i = 0; i < SceneRenderModeWindow.sRenderModeCount; i++) + { + DrawCameraMode drawCameraMode = (DrawCameraMode)i; + DrawCameraMode drawCameraMode2 = drawCameraMode; + if (drawCameraMode2 != DrawCameraMode.ShadowCascades) + { + if (drawCameraMode2 != DrawCameraMode.DeferredDiffuse) + { + if (drawCameraMode2 == DrawCameraMode.Charting) + { + this.DrawSeparator(ref rect); + this.DrawHeader(ref rect, SceneRenderModeWindow.Styles.sGlobalIlluminationHeader); + } + } + else + { + this.DrawSeparator(ref rect); + this.DrawHeader(ref rect, SceneRenderModeWindow.Styles.sDeferredHeader); + } + } + else + { + this.DrawSeparator(ref rect); + this.DrawHeader(ref rect, SceneRenderModeWindow.Styles.sMiscellaneous); + } + EditorGUI.BeginDisabledGroup(this.IsModeDisabled(drawCameraMode)); + this.DoOneMode(caller, ref rect, drawCameraMode); + EditorGUI.EndDisabledGroup(); + } + bool disabled = this.m_SceneView.renderMode < DrawCameraMode.Charting || this.IsModeDisabled(this.m_SceneView.renderMode); + this.DoResolutionToggle(rect, disabled); + } + private bool IsModeDisabled(DrawCameraMode mode) + { + return (!this.m_EnableBakedGI.boolValue && mode == DrawCameraMode.Baked) || (!this.m_EnableRealtimeGI.boolValue && !this.m_EnableBakedGI.boolValue && mode >= DrawCameraMode.Charting); + } + private void DoResolutionToggle(Rect rect, bool disabled) + { + GUI.Label(new Rect(1f, rect.y, 203f, 22f), string.Empty, EditorStyles.inspectorBig); + rect.y += 3f; + rect.x += 7f; + EditorGUI.BeginDisabledGroup(disabled); + EditorGUI.BeginChangeCheck(); + bool showResolution = GUI.Toggle(rect, LightmapVisualization.showResolution, SceneRenderModeWindow.Styles.sResolutionToggle); + if (EditorGUI.EndChangeCheck()) + { + LightmapVisualization.showResolution = showResolution; + SceneView.RepaintAll(); + } + EditorGUI.EndDisabledGroup(); + } + private void DoOneMode(EditorWindow caller, ref Rect rect, DrawCameraMode drawCameraMode) + { + EditorGUI.BeginDisabledGroup(!this.m_SceneView.CheckDrawModeForRenderingPath(drawCameraMode)); + EditorGUI.BeginChangeCheck(); + GUI.Toggle(rect, this.m_SceneView.renderMode == drawCameraMode, SceneRenderModeWindow.GetGUIContent(drawCameraMode), SceneRenderModeWindow.Styles.sMenuItem); + if (EditorGUI.EndChangeCheck()) + { + this.m_SceneView.renderMode = drawCameraMode; + this.m_SceneView.Repaint(); + GUIUtility.ExitGUI(); + } + rect.y += 16f; + EditorGUI.EndDisabledGroup(); + } + public static GUIContent GetGUIContent(DrawCameraMode drawCameraMode) + { + return SceneRenderModeWindow.Styles.sRenderModeOptions[(int)drawCameraMode]; + } + } +} diff --git a/UnityEditor/UnityEditor/SceneView.cs b/UnityEditor/UnityEditor/SceneView.cs index 68b19493..1e1bda36 100644 --- a/UnityEditor/UnityEditor/SceneView.cs +++ b/UnityEditor/UnityEditor/SceneView.cs @@ -56,6 +56,7 @@ internal enum DraggingLockedState LookAt } public delegate void OnSceneFunc(SceneView sceneView); + private const float kDefaultViewSize = 10f; private const float kOrthoThresholdAngle = 3f; private const float kOneOverSqrt2 = 0.707106769f; private const double k_MaxDoubleKeypressTime = 0.5; @@ -63,11 +64,11 @@ internal enum DraggingLockedState public const float kToolbarHeight = 17f; private static SceneView s_LastActiveSceneView; private static SceneView s_CurrentDrawingSceneView; - private static PrefColor kSceneViewBackground = new PrefColor("Scene/Background", 0.278431f, 0.278431f, 0.278431f, 0f); - private static PrefColor kSceneViewWire = new PrefColor("Scene/Wireframe", 0f, 0f, 0f, 0.5f); - private static PrefColor kSceneViewWireOverlay = new PrefColor("Scene/Wireframe Overlay", 0f, 0f, 0f, 0.25f); - private static PrefColor kSceneViewWireActive = new PrefColor("Scene/Wireframe Active", 0.490196079f, 0.6901961f, 0.980392158f, 0.372549027f); - private static PrefColor kSceneViewWireSelected = new PrefColor("Scene/Wireframe Selected", 0.368627459f, 0.466666669f, 0.607843161f, 0.25f); + private static readonly PrefColor kSceneViewBackground = new PrefColor("Scene/Background", 0.278431f, 0.278431f, 0.278431f, 0f); + private static readonly PrefColor kSceneViewWire = new PrefColor("Scene/Wireframe", 0f, 0f, 0f, 0.5f); + private static readonly PrefColor kSceneViewWireOverlay = new PrefColor("Scene/Wireframe Overlay", 0f, 0f, 0f, 0.25f); + private static readonly PrefColor kSceneViewWireActive = new PrefColor("Scene/Wireframe Active", 0.490196079f, 0.6901961f, 0.980392158f, 0.372549027f); + private static readonly PrefColor kSceneViewWireSelected = new PrefColor("Scene/Wireframe Selected", 0.368627459f, 0.466666669f, 0.607843161f, 0.25f); internal static Color kSceneViewFrontLight = new Color(0.769f, 0.769f, 0.769f, 1f); internal static Color kSceneViewUpLight = new Color(0.212f, 0.227f, 0.259f, 1f); internal static Color kSceneViewMidLight = new Color(0.114f, 0.125f, 0.133f, 1f); @@ -75,41 +76,24 @@ internal enum DraggingLockedState [NonSerialized] private static readonly Quaternion kDefaultRotation = Quaternion.LookRotation(new Vector3(-1f, -0.7f, -1f)); [NonSerialized] - private static readonly float kDefaultViewSize = 10f; - [NonSerialized] private static readonly Vector3 kDefaultPivot = Vector3.zero; [NonSerialized] private ActiveEditorTracker m_Tracker; - public bool m_SceneLighting; + [SerializeField] + public bool m_SceneLighting = true; public double lastFramingTime; - private static PrefKey k2DMode = new PrefKey("Tools/2D Mode", "2"); + private static readonly PrefKey k2DMode = new PrefKey("Tools/2D Mode", "2"); private static bool waitingFor2DModeKeyUp; [SerializeField] private bool m_2DMode; internal UnityEngine.Object m_OneClickDragObject; [NonSerialized] public bool m_AudioPlay; - private static SceneView s_AudioSceneView = null; + private static SceneView s_AudioSceneView; [SerializeField] private AnimVector3 m_Position = new AnimVector3(SceneView.kDefaultPivot); - private static string[] s_RenderModes = new string[] - { - "Textured", - "Wireframe", - "Textured Wire", - "Render Paths", - "Lightmap Resolution" - }; - private static string[] s_OverlayModes = new string[] - { - "RGB", - "Alpha", - "Overdraw", - "Mipmaps" - }; public static SceneView.OnSceneFunc onSceneGUIDelegate; public DrawCameraMode m_RenderMode; - public int m_OverlayMode; [SerializeField] internal SceneView.SceneViewState m_SceneViewState; [SerializeField] @@ -119,7 +103,7 @@ internal enum DraggingLockedState [SerializeField] internal AnimQuaternion m_Rotation = new AnimQuaternion(SceneView.kDefaultRotation); [SerializeField] - private AnimFloat m_Size = new AnimFloat(SceneView.kDefaultViewSize); + private AnimFloat m_Size = new AnimFloat(10f); [SerializeField] internal AnimBool m_Ortho = new AnimBool(); [NonSerialized] @@ -129,27 +113,29 @@ internal enum DraggingLockedState [SerializeField] private bool m_LastSceneViewOrtho; private static MouseCursor s_LastCursor = MouseCursor.Arrow; - private static List s_MouseRects = new List(); - private bool s_DraggingCursorIsCashed; + private static readonly List s_MouseRects = new List(); + private bool s_DraggingCursorIsCached; [NonSerialized] private Light[] m_Light = new Light[3]; private RectSelection m_RectSelection; private static ArrayList s_SceneViews = new ArrayList(); private static Material s_AlphaOverlayMaterial; + private static Material s_DeferredOverlayMaterial; private static Shader s_ShowOverdrawShader; private static Shader s_ShowMipsShader; private static Shader s_ShowLightmapsShader; private static Shader s_AuraShader; private static Shader s_GrayScaleShader; private static Texture2D s_MipColorsTexture; - private static GUIContent s_Fx = new GUIContent("Effects"); - private static GUIContent s_Lighting = EditorGUIUtility.IconContent("SceneviewLighting"); - private static GUIContent s_AudioPlay = EditorGUIUtility.IconContent("SceneviewAudio"); - private static GUIContent s_GizmosContent = new GUIContent("Gizmos"); - private static GUIContent s_2DMode = new GUIContent("2D"); + private GUIContent m_Lighting; + private GUIContent m_Fx; + private GUIContent m_AudioPlayContent; + private GUIContent m_GizmosContent; + private GUIContent m_2DModeContent; private static Tool s_CurrentTool; private double m_StartSearchFilterTime = -1.0; - private RenderTexture m_SearchFilterTexture; + private RenderTexture m_SceneTargetTexture; + private RenderTexture m_SceneTargetTextureLDR; private int m_MainViewControlID; [SerializeField] private Shader m_ReplacementShader; @@ -350,8 +336,6 @@ internal Vector3 cameraTargetPosition public SceneView() { this.m_HierarchyType = HierarchyType.GameObjects; - base.depthBufferBits = 32; - base.antiAlias = -1; } internal static void AddCursorRect(Rect rect, MouseCursor cursor) { @@ -401,28 +385,32 @@ public static void RepaintAll() sceneView.Repaint(); } } - internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + internal override void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode mode, bool setAll) { if (this.m_SearchFilter == string.Empty || searchFilter == string.Empty) { this.m_StartSearchFilterTime = EditorApplication.timeSinceStartup; } - base.SetSearchFilter(searchFilter, searchMode, setAll); + base.SetSearchFilter(searchFilter, mode, setAll); } - private void OnFocus() + internal void OnFocus() { if (!Application.isPlaying && this.m_AudioPlay) { this.ToggleAudio(); } } - private void OnLostFocus() + internal void OnLostFocus() { GameView gameView = (GameView)WindowLayout.FindEditorWindowOfType(typeof(GameView)); if (gameView && gameView.m_Parent != null && this.m_Parent != null && gameView.m_Parent == this.m_Parent) { gameView.m_Parent.backgroundValid = false; } + if (SceneView.s_LastActiveSceneView == this) + { + SceneViewMotion.ResetMotion(); + } } public override void OnEnable() { @@ -445,46 +433,31 @@ public override void OnEnable() base.wantsMouseMove = true; base.dontClearBackground = true; SceneView.s_SceneViews.Add(this); + this.m_Lighting = EditorGUIUtility.IconContent("SceneviewLighting"); + this.m_Fx = EditorGUIUtility.IconContent("SceneviewFx"); + this.m_AudioPlayContent = EditorGUIUtility.IconContent("SceneviewAudio"); + this.m_GizmosContent = new GUIContent("Gizmos"); + this.m_2DModeContent = new GUIContent("2D"); this.m_SceneViewOverlay = new SceneViewOverlay(this); EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(SceneView.RepaintAll)); this.m_DraggingLockedState = SceneView.DraggingLockedState.NotDragging; + this.CreateSceneCameraAndLights(); base.OnEnable(); } - private void Awake() + internal void Awake() { if (this.m_SceneViewState == null) { this.m_SceneViewState = new SceneView.SceneViewState(); } - if (!BuildPipeline.isBuildingPlayer) + if (this.m_2DMode || EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) { - this.m_SceneLighting = InternalEditorUtility.CalculateShouldEnableLights(); - } - if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) - { - this.m_2DMode = true; this.m_LastSceneViewRotation = Quaternion.LookRotation(new Vector3(-1f, -0.7f, -1f)); this.m_LastSceneViewOrtho = false; this.m_Rotation.value = Quaternion.identity; this.m_Ortho.value = true; - } - } - private static void OnForceEnableLights() - { - foreach (SceneView sceneView in SceneView.s_SceneViews) - { - sceneView.m_SceneLighting = true; - } - } - private void OnDidOpenScene() - { - if (BuildPipeline.isBuildingPlayer) - { - return; - } - foreach (SceneView sceneView in SceneView.s_SceneViews) - { - sceneView.m_SceneLighting = InternalEditorUtility.CalculateShouldEnableLights(); + this.m_2DMode = true; + this.LookAt(this.pivot, Quaternion.identity, this.size, true, true); } } internal static void PlaceGameObjectInFrontOfSceneView(GameObject go) @@ -548,48 +521,50 @@ public void OnDestroy() this.ToggleAudio(); } } - private void DoStatusBarGUI() + private void DoToolbarGUI() { GUILayout.BeginHorizontal("toolbar", new GUILayoutOption[0]); - this.m_RenderMode = (DrawCameraMode)EditorGUILayout.Popup((int)this.m_RenderMode, SceneView.s_RenderModes, "ToolbarPopup", new GUILayoutOption[] + GUIContent gUIContent = SceneRenderModeWindow.GetGUIContent(this.m_RenderMode); + Rect rect = GUILayoutUtility.GetRect(gUIContent, EditorStyles.toolbarDropDown, new GUILayoutOption[] { GUILayout.Width(120f) }); - EditorGUILayout.Space(); - bool enabled = GUI.enabled; - GUI.enabled = string.IsNullOrEmpty(this.m_SearchFilter); - this.m_OverlayMode = EditorGUILayout.Popup(this.m_OverlayMode, SceneView.s_OverlayModes, "ToolbarPopup", new GUILayoutOption[] + if (EditorGUI.ButtonMouseDown(rect, gUIContent, FocusType.Passive, EditorStyles.toolbarDropDown)) { - GUILayout.Width(70f) - }); - GUI.enabled = enabled; + Rect last = GUILayoutUtility.topLevel.GetLast(); + PopupWindow.Show(last, new SceneRenderModeWindow(this)); + GUIUtility.ExitGUI(); + } EditorGUILayout.Space(); - this.in2DMode = GUILayout.Toggle(this.in2DMode, SceneView.s_2DMode, "toolbarbutton", new GUILayoutOption[0]); - this.m_SceneLighting = GUILayout.Toggle(this.m_SceneLighting, SceneView.s_Lighting, "toolbarbutton", new GUILayoutOption[0]); + this.in2DMode = GUILayout.Toggle(this.in2DMode, this.m_2DModeContent, "toolbarbutton", new GUILayoutOption[0]); + EditorGUILayout.Space(); + this.m_SceneLighting = GUILayout.Toggle(this.m_SceneLighting, this.m_Lighting, "toolbarbutton", new GUILayoutOption[0]); + if (this.renderMode == DrawCameraMode.ShadowCascades) + { + this.m_SceneLighting = true; + } GUI.enabled = !Application.isPlaying; GUI.changed = false; - this.m_AudioPlay = GUILayout.Toggle(this.m_AudioPlay, SceneView.s_AudioPlay, EditorStyles.toolbarButton, new GUILayoutOption[0]); + this.m_AudioPlay = GUILayout.Toggle(this.m_AudioPlay, this.m_AudioPlayContent, EditorStyles.toolbarButton, new GUILayoutOption[0]); if (GUI.changed) { this.ToggleAudio(); } GUI.enabled = true; - Rect rect = GUILayoutUtility.GetRect(SceneView.s_Fx, this.effectsDropDownStyle); - Rect position = new Rect(rect.xMax - (float)this.effectsDropDownStyle.border.right, rect.y, (float)this.effectsDropDownStyle.border.right, rect.height); + Rect rect2 = GUILayoutUtility.GetRect(this.m_Fx, this.effectsDropDownStyle); + Rect position = new Rect(rect2.xMax - (float)this.effectsDropDownStyle.border.right, rect2.y, (float)this.effectsDropDownStyle.border.right, rect2.height); if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none)) { - Rect last = GUILayoutUtility.topLevel.GetLast(); - if (SceneFXWindow.ShowAtPosition(last, this)) - { - GUIUtility.ExitGUI(); - } + Rect last2 = GUILayoutUtility.topLevel.GetLast(); + PopupWindow.Show(last2, new SceneFXWindow(this)); + GUIUtility.ExitGUI(); } - bool flag = GUI.Toggle(rect, this.m_SceneViewState.IsAllOn(), SceneView.s_Fx, this.effectsDropDownStyle); + bool flag = GUI.Toggle(rect2, this.m_SceneViewState.IsAllOn(), this.m_Fx, this.effectsDropDownStyle); if (flag != this.m_SceneViewState.IsAllOn()) { this.m_SceneViewState.Toggle(flag); } - GUILayout.Space(6f); + EditorGUILayout.Space(); GUILayout.FlexibleSpace(); if (this.m_MainViewControlID != GUIUtility.keyboardControl && Event.current.type == EventType.KeyDown && !string.IsNullOrEmpty(this.m_SearchFilter)) { @@ -610,17 +585,17 @@ private void DoStatusBarGUI() return; } } - Rect rect2 = GUILayoutUtility.GetRect(SceneView.s_GizmosContent, EditorStyles.toolbarDropDown); - if (EditorGUI.ButtonMouseDown(rect2, SceneView.s_GizmosContent, FocusType.Passive, EditorStyles.toolbarDropDown)) + Rect rect3 = GUILayoutUtility.GetRect(this.m_GizmosContent, EditorStyles.toolbarDropDown); + if (EditorGUI.ButtonMouseDown(rect3, this.m_GizmosContent, FocusType.Passive, EditorStyles.toolbarDropDown)) { - Rect last2 = GUILayoutUtility.topLevel.GetLast(); - if (AnnotationWindow.ShowAtPosition(last2, false)) + Rect last3 = GUILayoutUtility.topLevel.GetLast(); + if (AnnotationWindow.ShowAtPosition(last3, false)) { GUIUtility.ExitGUI(); } } GUILayout.Space(6f); - base.SearchFieldGUI(); + base.SearchFieldGUI(EditorGUILayout.kLabelFloatMaxW); GUILayout.EndHorizontal(); } private void ToggleAudio() @@ -662,7 +637,7 @@ public void OnSelectionChange() base.Repaint(); } [MenuItem("GameObject/Set as first sibling %=")] - private static void MenuMoveToFront() + internal static void MenuMoveToFront() { Transform[] transforms = Selection.transforms; for (int i = 0; i < transforms.Length; i++) @@ -673,7 +648,7 @@ private static void MenuMoveToFront() } } [MenuItem("GameObject/Set as first sibling %=", true)] - private static bool ValidateMenuMoveToFront() + internal static bool ValidateMenuMoveToFront() { if (Selection.activeTransform != null) { @@ -683,7 +658,7 @@ private static bool ValidateMenuMoveToFront() return false; } [MenuItem("GameObject/Set as last sibling %-")] - private static void MenuMoveToBack() + internal static void MenuMoveToBack() { Transform[] transforms = Selection.transforms; for (int i = 0; i < transforms.Length; i++) @@ -694,7 +669,7 @@ private static void MenuMoveToBack() } } [MenuItem("GameObject/Set as last sibling %-", true)] - private static bool ValidateMenuMoveToBack() + internal static bool ValidateMenuMoveToBack() { if (Selection.activeTransform != null) { @@ -704,7 +679,7 @@ private static bool ValidateMenuMoveToBack() return false; } [MenuItem("GameObject/Move To View %&f")] - private static void MenuMoveToView() + internal static void MenuMoveToView() { if (SceneView.ValidateMoveToView()) { @@ -717,7 +692,7 @@ private static bool ValidateMoveToView() return SceneView.s_LastActiveSceneView != null && Selection.transforms.Length != 0; } [MenuItem("GameObject/Align With View %#f")] - private static void MenuAlignWithView() + internal static void MenuAlignWithView() { if (SceneView.ValidateAlignWithView()) { @@ -725,12 +700,12 @@ private static void MenuAlignWithView() } } [MenuItem("GameObject/Align With View %#f", true)] - private static bool ValidateAlignWithView() + internal static bool ValidateAlignWithView() { return SceneView.s_LastActiveSceneView != null && Selection.activeTransform != null; } [MenuItem("GameObject/Align View to Selected")] - private static void MenuAlignViewToSelected() + internal static void MenuAlignViewToSelected() { if (SceneView.ValidateAlignViewToSelected()) { @@ -738,12 +713,12 @@ private static void MenuAlignViewToSelected() } } [MenuItem("GameObject/Align View to Selected", true)] - private static bool ValidateAlignViewToSelected() + internal static bool ValidateAlignViewToSelected() { return SceneView.s_LastActiveSceneView != null && Selection.activeTransform != null; } [MenuItem("GameObject/Toggle Active State &#a")] - private static void ActivateSelection() + internal static void ActivateSelection() { if (Selection.activeTransform != null) { @@ -758,7 +733,7 @@ private static void ActivateSelection() } } [MenuItem("GameObject/Toggle Active State &#a", true)] - private static bool ValidateActivateSelection() + internal static bool ValidateActivateSelection() { return Selection.activeTransform != null; } @@ -793,7 +768,7 @@ private static void CreateMipColorsTexture() } SceneView.s_MipColorsTexture.filterMode = FilterMode.Trilinear; SceneView.s_MipColorsTexture.Apply(false); - Shader.SetGlobalTexture("__SceneViewMipcolorsTexture", SceneView.s_MipColorsTexture); + Shader.SetGlobalTexture("_SceneViewMipcolorsTexture", SceneView.s_MipColorsTexture); } public void SetSceneViewFiltering(bool enable) { @@ -803,15 +778,14 @@ private bool UseSceneFiltering() { return !string.IsNullOrEmpty(this.m_SearchFilter) || this.m_RequestedSceneViewFiltering; } - private void OnGUI() + internal bool SceneViewIsRenderingHDR() { - SceneView.s_CurrentDrawingSceneView = this; - if (Event.current.type == EventType.Repaint) - { - SceneView.s_MouseRects.Clear(); - } - Color color = GUI.color; - if (Event.current.type == EventType.MouseDown || Event.current.type == EventType.MouseDrag) + return !this.UseSceneFiltering() && this.m_Camera != null && this.m_Camera.hdr; + } + private void HandleClickAndDragToFocus() + { + Event current = Event.current; + if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag) { SceneView.s_LastActiveSceneView = this; } @@ -822,238 +796,375 @@ private void OnGUI() SceneView.s_LastActiveSceneView = this; } } - if (Event.current.type == EventType.MouseDrag) + if (current.type == EventType.MouseDrag) { this.draggingLocked = SceneView.DraggingLockedState.Dragging; } else { - if (Event.current.type == EventType.MouseUp) + if (current.type == EventType.MouseUp) { this.draggingLocked = SceneView.DraggingLockedState.LookAt; } } - if (Event.current.type == EventType.MouseDown) + if (current.type == EventType.MouseDown) { - Tools.s_ButtonDown = Event.current.button; - if (Event.current.button == 1 && Application.platform == RuntimePlatform.OSXEditor) + Tools.s_ButtonDown = current.button; + if (current.button == 1 && Application.platform == RuntimePlatform.OSXEditor) { base.Focus(); } } - if (Event.current.type == EventType.Layout) - { - this.m_ShowSceneViewWindows = (SceneView.lastActiveSceneView == this); - } - this.m_SceneViewOverlay.Begin(); - bool fog = RenderSettings.fog; - float shadowDistance = QualitySettings.shadowDistance; + } + private void SetupFogAndShadowDistance(out bool oldFog, out float oldShadowDistance) + { + oldFog = RenderSettings.fog; + oldShadowDistance = QualitySettings.shadowDistance; if (Event.current.type == EventType.Repaint) { if (!this.m_SceneViewState.showFog) { Unsupported.SetRenderSettingsUseFogNoDirty(false); } - if (this.m_Camera.isOrthoGraphic) + if (this.m_Camera.orthographic) { Unsupported.SetQualitySettingsShadowDistanceTemporarily(QualitySettings.shadowDistance + 0.5f * this.cameraDistance); } } - this.DoStatusBarGUI(); - GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); - EditorGUIUtility.labelWidth = 100f; - this.SetupCamera(); - RenderingPath renderingPath = this.m_Camera.renderingPath; - if (!this.m_SceneLighting) + } + private void RestoreFogAndShadowDistance(bool oldFog, float oldShadowDistance) + { + if (Event.current.type == EventType.Repaint) { - this.m_Light[0].transform.rotation = this.m_Camera.transform.rotation; - if (Event.current.type == EventType.Repaint) - { - InternalEditorUtility.SetCustomLighting(this.m_Light, SceneView.kSceneViewMidLight); - } + Unsupported.SetRenderSettingsUseFogNoDirty(oldFog); + Unsupported.SetQualitySettingsShadowDistanceTemporarily(oldShadowDistance); } - GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); - Rect rect = new Rect(0f, 0f, base.position.width, base.position.height - 17f); - if (Tools.viewToolActive && Event.current.type == EventType.Repaint) + } + private void CreateCameraTargetTexture(Rect cameraRect, bool hdr) + { + bool flag = QualitySettings.activeColorSpace == ColorSpace.Linear; + int num = Mathf.Max(1, QualitySettings.antiAliasing); + if (this.IsSceneCameraDeferred()) { - MouseCursor mouseCursor = MouseCursor.Arrow; - switch (Tools.viewTool) + num = 1; + } + RenderTextureFormat renderTextureFormat = (!hdr) ? RenderTextureFormat.ARGB32 : RenderTextureFormat.ARGBHalf; + if (this.m_SceneTargetTexture != null) + { + bool flag2; + if (hdr) { - case ViewTool.Orbit: - mouseCursor = MouseCursor.Orbit; - break; - case ViewTool.Pan: - mouseCursor = MouseCursor.Pan; - break; - case ViewTool.Zoom: - mouseCursor = MouseCursor.Zoom; - break; - case ViewTool.FPS: - mouseCursor = MouseCursor.FPS; - break; + flag2 = (this.m_SceneTargetTextureLDR != null && flag == this.m_SceneTargetTextureLDR.sRGB); } - if (mouseCursor != MouseCursor.Arrow) + else { - SceneView.AddCursorRect(new Rect(0f, 17f, base.position.width, base.position.height - 17f), mouseCursor); + flag2 = (this.m_SceneTargetTextureLDR == null && flag == this.m_SceneTargetTexture.sRGB); } - } - if (this.UseSceneFiltering()) - { - EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); - if (this.m_SearchFilterTexture == null) + if (this.m_SceneTargetTexture.format != renderTextureFormat || this.m_SceneTargetTexture.antiAliasing != num || !flag2) { - this.m_SearchFilterTexture = new RenderTexture(0, 0, 24); - this.m_SearchFilterTexture.hideFlags = HideFlags.HideAndDontSave; + UnityEngine.Object.DestroyImmediate(this.m_SceneTargetTexture); + this.m_SceneTargetTexture = null; + UnityEngine.Object.DestroyImmediate(this.m_SceneTargetTextureLDR); + this.m_SceneTargetTextureLDR = null; } - Rect cameraRect = Handles.GetCameraRect(rect); - if (this.m_SearchFilterTexture.width != (int)cameraRect.width || this.m_SearchFilterTexture.height != (int)cameraRect.height) + } + Rect cameraRect2 = Handles.GetCameraRect(cameraRect); + int num2 = (int)cameraRect2.width; + int num3 = (int)cameraRect2.height; + if (this.m_SceneTargetTexture == null) + { + this.m_SceneTargetTexture = new RenderTexture(0, 0, 24, renderTextureFormat); + this.m_SceneTargetTexture.name = "SceneView RT"; + this.m_SceneTargetTexture.antiAliasing = num; + this.m_SceneTargetTexture.hideFlags = HideFlags.HideAndDontSave; + } + if (this.m_SceneTargetTexture.width != num2 || this.m_SceneTargetTexture.height != num3) + { + this.m_SceneTargetTexture.Release(); + this.m_SceneTargetTexture.width = num2; + this.m_SceneTargetTexture.height = num3; + } + this.m_SceneTargetTexture.Create(); + if (hdr) + { + if (this.m_SceneTargetTextureLDR == null) { - this.m_SearchFilterTexture.Release(); - this.m_SearchFilterTexture.width = (int)cameraRect.width; - this.m_SearchFilterTexture.height = (int)cameraRect.height; + this.m_SceneTargetTextureLDR = new RenderTexture(0, 0, 0, RenderTextureFormat.ARGB32); + this.m_SceneTargetTextureLDR.name = "SceneView LDR RT"; + this.m_SceneTargetTextureLDR.antiAliasing = num; + this.m_SceneTargetTextureLDR.hideFlags = HideFlags.HideAndDontSave; } - this.m_Camera.targetTexture = this.m_SearchFilterTexture; - if (this.m_Camera.actualRenderingPath == RenderingPath.DeferredLighting) + if (this.m_SceneTargetTextureLDR.width != num2 || this.m_SceneTargetTextureLDR.height != num3) { - this.m_Camera.renderingPath = RenderingPath.Forward; + this.m_SceneTargetTextureLDR.Release(); + this.m_SceneTargetTextureLDR.width = num2; + this.m_SceneTargetTextureLDR.height = num3; } + this.m_SceneTargetTextureLDR.Create(); } - else + } + internal bool IsSceneCameraDeferred() + { + return !(this.m_Camera == null) && (this.m_Camera.actualRenderingPath == RenderingPath.DeferredLighting || this.m_Camera.actualRenderingPath == RenderingPath.DeferredShading); + } + internal static bool DoesCameraDrawModeSupportDeferred(DrawCameraMode mode) + { + return mode == DrawCameraMode.Normal || mode == DrawCameraMode.Textured || mode == DrawCameraMode.ShadowCascades || mode == DrawCameraMode.RenderPaths || mode == DrawCameraMode.AlphaChannel || mode == DrawCameraMode.DeferredDiffuse || mode == DrawCameraMode.DeferredSpecular || mode == DrawCameraMode.DeferredSmoothness || mode == DrawCameraMode.DeferredNormal; + } + internal static bool DoesCameraDrawModeSupportHDR(DrawCameraMode mode) + { + return mode != DrawCameraMode.Overdraw && mode != DrawCameraMode.Mipmaps; + } + private void PrepareCameraTargetTexture(Rect cameraRect) + { + EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); + bool hdr = this.SceneViewIsRenderingHDR(); + this.CreateCameraTargetTexture(cameraRect, hdr); + this.m_Camera.targetTexture = this.m_SceneTargetTexture; + if ((this.UseSceneFiltering() || !SceneView.DoesCameraDrawModeSupportDeferred(this.m_RenderMode)) && this.IsSceneCameraDeferred()) { - this.m_Camera.targetTexture = null; + this.m_Camera.renderingPath = RenderingPath.Forward; } - float verticalFOV = this.GetVerticalFOV(90f); - float fieldOfView = this.m_Camera.fieldOfView; - this.m_Camera.fieldOfView = verticalFOV; - Handles.ClearCamera(rect, this.m_Camera); - this.m_Camera.fieldOfView = fieldOfView; - this.m_Camera.cullingMask = Tools.visibleLayers; - if (!this.UseSceneFiltering()) + } + private void PrepareCameraReplacementShader() + { + if (Event.current.type != EventType.Repaint) { - Handles.SetCamera(rect, this.m_Camera); - this.CallOnPreSceneGUI(); + return; } - if (Event.current.type == EventType.Repaint) + Handles.SetSceneViewColors(SceneView.kSceneViewWire, SceneView.kSceneViewWireOverlay, SceneView.kSceneViewWireActive, SceneView.kSceneViewWireSelected); + if (this.m_RenderMode == DrawCameraMode.Overdraw) { - Handles.SetSceneViewColors(SceneView.kSceneViewWire, SceneView.kSceneViewWireOverlay, SceneView.kSceneViewWireActive, SceneView.kSceneViewWireSelected); - if (this.m_OverlayMode == 2) + if (!SceneView.s_ShowOverdrawShader) { - if (!SceneView.s_ShowOverdrawShader) - { - SceneView.s_ShowOverdrawShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowOverdraw.shader") as Shader); - } - this.m_Camera.SetReplacementShader(SceneView.s_ShowOverdrawShader, "RenderType"); + SceneView.s_ShowOverdrawShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowOverdraw.shader") as Shader); } - else + this.m_Camera.SetReplacementShader(SceneView.s_ShowOverdrawShader, "RenderType"); + } + else + { + if (this.m_RenderMode == DrawCameraMode.Mipmaps) { - if (this.m_OverlayMode == 3) + if (!SceneView.s_ShowMipsShader) { - if (!SceneView.s_ShowMipsShader) - { - SceneView.s_ShowMipsShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowMips.shader") as Shader); - } - if (SceneView.s_ShowMipsShader.isSupported) - { - SceneView.CreateMipColorsTexture(); - this.m_Camera.SetReplacementShader(SceneView.s_ShowMipsShader, "RenderType"); - } - else - { - this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); - } + SceneView.s_ShowMipsShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowMips.shader") as Shader); + } + if (SceneView.s_ShowMipsShader != null && SceneView.s_ShowMipsShader.isSupported) + { + SceneView.CreateMipColorsTexture(); + this.m_Camera.SetReplacementShader(SceneView.s_ShowMipsShader, "RenderType"); } else { - if (this.m_OverlayMode == 4) - { - if (!SceneView.s_ShowLightmapsShader) - { - SceneView.s_ShowLightmapsShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewShowLightmap.shader") as Shader); - } - if (SceneView.s_ShowLightmapsShader.isSupported) - { - this.m_Camera.SetReplacementShader(SceneView.s_ShowLightmapsShader, "RenderType"); - } - else - { - this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); - } - } - else - { - this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); - } + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); } } + else + { + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + } } - this.m_MainViewControlID = GUIUtility.GetControlID(FocusType.Keyboard); - if (Event.current.GetTypeForControl(this.m_MainViewControlID) == EventType.MouseDown) + } + private bool SceneCameraRendersIntoRT() + { + return this.m_Camera.targetTexture != null || HandleUtility.CameraNeedsToRenderIntoRT(this.m_Camera); + } + private void DoDrawCamera(Rect cameraRect, out bool pushedGUIClip) + { + pushedGUIClip = false; + if (!this.m_Camera.gameObject.activeInHierarchy) { - GUIUtility.keyboardControl = this.m_MainViewControlID; + return; } - if (this.m_Camera.gameObject.activeInHierarchy) + DrawGridParameters gridParam = this.grid.PrepareGridRender(this.camera, this.pivot, this.m_Rotation.target, this.m_Size.value, this.m_Ortho.target, AnnotationUtility.showGrid); + Event current = Event.current; + if (this.UseSceneFiltering()) { - DrawGridParameters gridParam = this.grid.PrepareGridRender(this.camera, this.pivot, this.m_Rotation.target, this.m_Size.value, this.m_Ortho.target, AnnotationUtility.showGrid); - if (this.UseSceneFiltering()) + if (current.type == EventType.Repaint) { - if (Event.current.type == EventType.Repaint) + Handles.EnableCameraFx(this.m_Camera, true); + Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowRest); + float num = Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - this.m_StartSearchFilterTime)); + Handles.DrawCamera(cameraRect, this.m_Camera, this.m_RenderMode); + Handles.DrawCameraFade(this.m_Camera, num); + Handles.EnableCameraFx(this.m_Camera, false); + Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowFiltered); + if (!SceneView.s_AuraShader) { - Handles.EnableCameraFx(this.m_Camera, true); - Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowRest); - float num = Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - this.m_StartSearchFilterTime)); - Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode); - Handles.DrawCameraFade(this.m_Camera, num); - RenderTexture.active = null; - Handles.EnableCameraFx(this.m_Camera, false); - Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.ShowFiltered); - if (!SceneView.s_AuraShader) - { - SceneView.s_AuraShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader); - } - this.m_Camera.SetReplacementShader(SceneView.s_AuraShader, string.Empty); - Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode); - this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); - Handles.DrawCamera(rect, this.m_Camera, this.m_RenderMode, gridParam); - if (num < 1f) - { - base.Repaint(); - } + SceneView.s_AuraShader = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader); + } + this.m_Camera.SetReplacementShader(SceneView.s_AuraShader, string.Empty); + Handles.DrawCamera(cameraRect, this.m_Camera, this.m_RenderMode); + this.m_Camera.SetReplacementShader(this.m_ReplacementShader, this.m_ReplacementString); + Handles.DrawCamera(cameraRect, this.m_Camera, this.m_RenderMode, gridParam); + if (num < 1f) + { + base.Repaint(); } - Rect position = rect; - GUI.EndGroup(); - GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); - GUI.DrawTexture(position, this.m_SearchFilterTexture, ScaleMode.StretchToFill, false, 0f); - Handles.SetCamera(rect, this.m_Camera); - this.HandleSelectionAndOnSceneGUI(); } - else + if (current.type == EventType.Repaint) + { + RenderTexture.active = null; + } + GUI.EndGroup(); + GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); + if (current.type == EventType.Repaint) { - Handles.DrawCameraStep1(rect, this.m_Camera, this.m_RenderMode, gridParam); - this.DrawAlphaOverlay(); + GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear); + GUI.DrawTexture(cameraRect, this.m_SceneTargetTexture, ScaleMode.StretchToFill, false, 0f); + GL.sRGBWrite = false; } + Handles.SetCamera(cameraRect, this.m_Camera); + this.HandleSelectionAndOnSceneGUI(); } - if (!this.m_SceneLighting && Event.current.type == EventType.Repaint) + else + { + if (this.SceneCameraRendersIntoRT()) + { + GUIClip.Push(new Rect(0f, 0f, base.position.width, base.position.height), Vector2.zero, Vector2.zero, true); + pushedGUIClip = true; + } + Handles.DrawCameraStep1(cameraRect, this.m_Camera, this.m_RenderMode, gridParam); + this.DrawRenderModeOverlay(cameraRect); + } + } + private void DoClearCamera(Rect cameraRect) + { + float verticalFOV = this.GetVerticalFOV(90f); + float fieldOfView = this.m_Camera.fieldOfView; + this.m_Camera.fieldOfView = verticalFOV; + Handles.ClearCamera(cameraRect, this.m_Camera); + this.m_Camera.fieldOfView = fieldOfView; + } + private void SetupCustomSceneLighting() + { + if (this.m_SceneLighting) + { + return; + } + this.m_Light[0].transform.rotation = this.m_Camera.transform.rotation; + if (Event.current.type == EventType.Repaint) + { + InternalEditorUtility.SetCustomLighting(this.m_Light, SceneView.kSceneViewMidLight); + } + } + private void CleanupCustomSceneLighting() + { + if (this.m_SceneLighting) + { + return; + } + if (Event.current.type == EventType.Repaint) { InternalEditorUtility.RemoveCustomLighting(); } + } + private void HandleViewToolCursor() + { + if (!Tools.viewToolActive || Event.current.type != EventType.Repaint) + { + return; + } + MouseCursor mouseCursor = MouseCursor.Arrow; + switch (Tools.viewTool) + { + case ViewTool.Orbit: + mouseCursor = MouseCursor.Orbit; + break; + case ViewTool.Pan: + mouseCursor = MouseCursor.Pan; + break; + case ViewTool.Zoom: + mouseCursor = MouseCursor.Zoom; + break; + case ViewTool.FPS: + mouseCursor = MouseCursor.FPS; + break; + } + if (mouseCursor != MouseCursor.Arrow) + { + SceneView.AddCursorRect(new Rect(0f, 17f, base.position.width, base.position.height - 17f), mouseCursor); + } + } + private void DoTonemapping() + { + if (Event.current.type != EventType.Repaint) + { + return; + } + if (!this.SceneViewIsRenderingHDR()) + { + return; + } + Camera mainCamera = SceneView.GetMainCamera(); + if (mainCamera == null || !Handles.DrawCameraTonemap(mainCamera, this.m_SceneTargetTexture, this.m_SceneTargetTextureLDR)) + { + Graphics.Blit(this.m_SceneTargetTexture, this.m_SceneTargetTextureLDR); + } + Graphics.SetRenderTarget(this.m_SceneTargetTextureLDR.colorBuffer, this.m_SceneTargetTexture.depthBuffer); + } + private void DoOnPreSceneGUICallbacks(Rect cameraRect) + { if (this.UseSceneFiltering()) { - EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + return; } - if (Event.current.type == EventType.ExecuteCommand || Event.current.type == EventType.ValidateCommand) + Handles.SetCamera(cameraRect, this.m_Camera); + this.CallOnPreSceneGUI(); + } + internal void OnGUI() + { + Event current = Event.current; + if (current.type == EventType.Repaint) { - this.CommandsGUI(); + SceneView.s_MouseRects.Clear(); + Profiler.BeginSample("SceneView.Repaint"); } - if (Event.current.type == EventType.Repaint) + Color color = GUI.color; + this.HandleClickAndDragToFocus(); + if (current.type == EventType.Layout) { - Unsupported.SetRenderSettingsUseFogNoDirty(fog); - Unsupported.SetQualitySettingsShadowDistanceTemporarily(shadowDistance); + this.m_ShowSceneViewWindows = (SceneView.lastActiveSceneView == this); } - this.m_Camera.renderingPath = renderingPath; + this.m_SceneViewOverlay.Begin(); + bool oldFog; + float oldShadowDistance; + this.SetupFogAndShadowDistance(out oldFog, out oldShadowDistance); + this.DoToolbarGUI(); + GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); + EditorGUIUtility.labelWidth = 100f; + this.SetupCamera(); + RenderingPath renderingPath = this.m_Camera.renderingPath; + this.SetupCustomSceneLighting(); + GUI.BeginGroup(new Rect(0f, 17f, base.position.width, base.position.height - 17f)); + Rect rect = new Rect(0f, 0f, base.position.width, base.position.height - 17f); + this.HandleViewToolCursor(); + this.PrepareCameraTargetTexture(rect); + this.DoClearCamera(rect); + this.m_Camera.cullingMask = Tools.visibleLayers; + this.DoOnPreSceneGUICallbacks(rect); + this.PrepareCameraReplacementShader(); + this.m_MainViewControlID = GUIUtility.GetControlID(FocusType.Keyboard); + if (current.GetTypeForControl(this.m_MainViewControlID) == EventType.MouseDown) + { + GUIUtility.keyboardControl = this.m_MainViewControlID; + } + bool flag; + this.DoDrawCamera(rect, out flag); + this.CleanupCustomSceneLighting(); if (!this.UseSceneFiltering()) { Handles.DrawCameraStep2(this.m_Camera, this.m_RenderMode); + this.DoTonemapping(); + this.HandleSelectionAndOnSceneGUI(); } + EditorUtility.SetTemporarilyAllowIndieRenderTexture(false); + if (current.type == EventType.ExecuteCommand || current.type == EventType.ValidateCommand) + { + this.CommandsGUI(); + } + this.RestoreFogAndShadowDistance(oldFog, oldShadowDistance); + this.m_Camera.renderingPath = renderingPath; if (this.UseSceneFiltering()) { Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.ShowFiltered); @@ -1062,85 +1173,130 @@ private void OnGUI() { Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.Off); } + this.DefaultHandles(); if (!this.UseSceneFiltering()) { - this.HandleSelectionAndOnSceneGUI(); + if (current.type == EventType.Repaint) + { + Profiler.BeginSample("SceneView.BlitRT"); + Graphics.SetRenderTarget(null); + } + if (flag) + { + GUIClip.Pop(); + } + if (current.type == EventType.Repaint) + { + GL.sRGBWrite = (QualitySettings.activeColorSpace == ColorSpace.Linear); + GUI.DrawTexture(rect, (!this.m_Camera.hdr) ? this.m_SceneTargetTexture : this.m_SceneTargetTextureLDR, ScaleMode.StretchToFill, false); + GL.sRGBWrite = false; + Profiler.EndSample(); + } } - this.DefaultHandles(); Handles.SetCameraFilterMode(Camera.current, Handles.FilterMode.Off); Handles.SetCameraFilterMode(this.m_Camera, Handles.FilterMode.Off); this.HandleDragging(); this.svRot.HandleContextClick(this); this.svRot.OnGUI(this); - SceneViewMotion.ArrowKeys(this); - SceneViewMotion.DoViewTool(this.camera.transform, this); + if (SceneView.s_LastActiveSceneView == this) + { + SceneViewMotion.ArrowKeys(this); + SceneViewMotion.DoViewTool(this.camera.transform, this); + } + this.Handle2DModeSwitch(); + GUI.EndGroup(); + GUI.color = color; + this.m_SceneViewOverlay.End(); + this.HandleMouseCursor(); + if (current.type == EventType.Repaint) + { + Profiler.EndSample(); + } + } + private void Handle2DModeSwitch() + { + Event current = Event.current; if (SceneView.k2DMode.activated && !SceneView.waitingFor2DModeKeyUp) { SceneView.waitingFor2DModeKeyUp = true; this.in2DMode = !this.in2DMode; - Event.current.Use(); + current.Use(); } else { - if (Event.current.type == EventType.KeyUp && Event.current.keyCode == SceneView.k2DMode.KeyboardEvent.keyCode) + if (current.type == EventType.KeyUp && current.keyCode == SceneView.k2DMode.KeyboardEvent.keyCode) { SceneView.waitingFor2DModeKeyUp = false; } } - GUI.EndGroup(); - GUI.color = color; - this.m_SceneViewOverlay.End(); + } + private void HandleMouseCursor() + { + Event current = Event.current; if (GUIUtility.hotControl == 0) { - this.s_DraggingCursorIsCashed = false; + this.s_DraggingCursorIsCached = false; } - Rect rect2 = new Rect(0f, 0f, base.position.width, base.position.height); - if (!this.s_DraggingCursorIsCashed) + Rect rect = new Rect(0f, 0f, base.position.width, base.position.height); + if (!this.s_DraggingCursorIsCached) { - MouseCursor mouseCursor2 = MouseCursor.Arrow; - if (Event.current.type == EventType.MouseMove || Event.current.type == EventType.Repaint) + MouseCursor mouseCursor = MouseCursor.Arrow; + if (current.type == EventType.MouseMove || current.type == EventType.Repaint) { - foreach (SceneView.CursorRect current in SceneView.s_MouseRects) + foreach (SceneView.CursorRect current2 in SceneView.s_MouseRects) { - if (current.rect.Contains(Event.current.mousePosition)) + if (current2.rect.Contains(current.mousePosition)) { - mouseCursor2 = current.cursor; - rect2 = current.rect; + mouseCursor = current2.cursor; + rect = current2.rect; } } if (GUIUtility.hotControl != 0) { - this.s_DraggingCursorIsCashed = true; + this.s_DraggingCursorIsCached = true; } - if (mouseCursor2 != SceneView.s_LastCursor) + if (mouseCursor != SceneView.s_LastCursor) { - SceneView.s_LastCursor = mouseCursor2; + SceneView.s_LastCursor = mouseCursor; InternalEditorUtility.ResetCursor(); base.Repaint(); } } } - if (Event.current.type == EventType.Repaint && SceneView.s_LastCursor != MouseCursor.Arrow) + if (current.type == EventType.Repaint && SceneView.s_LastCursor != MouseCursor.Arrow) { - EditorGUIUtility.AddCursorRect(rect2, SceneView.s_LastCursor); + EditorGUIUtility.AddCursorRect(rect, SceneView.s_LastCursor); } } - private void DrawAlphaOverlay() + private void DrawRenderModeOverlay(Rect cameraRect) { - if (this.m_OverlayMode != 1) + if (this.m_RenderMode == DrawCameraMode.AlphaChannel) { - return; - } - if (!SceneView.s_AlphaOverlayMaterial) - { - SceneView.s_AlphaOverlayMaterial = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAlphaMaterial.mat") as Material); + if (!SceneView.s_AlphaOverlayMaterial) + { + SceneView.s_AlphaOverlayMaterial = (EditorGUIUtility.LoadRequired("SceneView/SceneViewAlphaMaterial.mat") as Material); + } + Handles.BeginGUI(); + if (Event.current.type == EventType.Repaint) + { + Graphics.DrawTexture(cameraRect, EditorGUIUtility.whiteTexture, SceneView.s_AlphaOverlayMaterial); + } + Handles.EndGUI(); } - Handles.BeginGUI(); - if (Event.current.type == EventType.Repaint) + if (this.m_RenderMode == DrawCameraMode.DeferredDiffuse || this.m_RenderMode == DrawCameraMode.DeferredSpecular || this.m_RenderMode == DrawCameraMode.DeferredSmoothness || this.m_RenderMode == DrawCameraMode.DeferredNormal) { - Graphics.DrawTexture(new Rect(0f, 0f, base.position.width, base.position.height), EditorGUIUtility.whiteTexture, SceneView.s_AlphaOverlayMaterial); + if (!SceneView.s_DeferredOverlayMaterial) + { + SceneView.s_DeferredOverlayMaterial = (EditorGUIUtility.LoadRequired("SceneView/SceneViewDeferredMaterial.mat") as Material); + } + Handles.BeginGUI(); + if (Event.current.type == EventType.Repaint) + { + SceneView.s_DeferredOverlayMaterial.SetInt("_DisplayMode", this.m_RenderMode - DrawCameraMode.DeferredDiffuse); + Graphics.DrawTexture(cameraRect, EditorGUIUtility.whiteTexture, SceneView.s_DeferredOverlayMaterial); + } + Handles.EndGUI(); } - Handles.EndGUI(); } private void HandleSelectionAndOnSceneGUI() { @@ -1180,27 +1336,58 @@ private void ResetIfNaN() this.m_Rotation.value = Quaternion.identity; } } - internal static RenderingPath GetSceneViewRenderingPath() + internal static Camera GetMainCamera() { Camera main = Camera.main; if (main != null) { - return main.renderingPath; + return main; } Camera[] allCameras = Camera.allCameras; if (allCameras != null && allCameras.Length == 1) { - return allCameras[0].renderingPath; + return allCameras[0]; + } + return null; + } + internal static RenderingPath GetSceneViewRenderingPath() + { + Camera mainCamera = SceneView.GetMainCamera(); + if (mainCamera != null) + { + return mainCamera.renderingPath; } return RenderingPath.UsePlayerSettings; } - private void SetupCamera() + internal bool CheckDrawModeForRenderingPath(DrawCameraMode mode) + { + RenderingPath actualRenderingPath = this.m_Camera.actualRenderingPath; + return (mode != DrawCameraMode.DeferredDiffuse && mode != DrawCameraMode.DeferredSpecular && mode != DrawCameraMode.DeferredSmoothness && mode != DrawCameraMode.DeferredNormal) || actualRenderingPath == RenderingPath.DeferredShading; + } + private void SetSceneCameraHDRAndDepthModes() { - if (!this.m_Camera) + if (!this.m_SceneLighting || !SceneView.DoesCameraDrawModeSupportHDR(this.m_RenderMode)) + { + this.m_Camera.hdr = false; + this.m_Camera.depthTextureMode = DepthTextureMode.None; + this.m_Camera.clearStencilAfterLightingPass = false; + return; + } + Camera mainCamera = SceneView.GetMainCamera(); + if (mainCamera == null) { - this.Setup(); + this.m_Camera.hdr = false; + this.m_Camera.depthTextureMode = DepthTextureMode.None; + this.m_Camera.clearStencilAfterLightingPass = false; + return; } - if (this.m_OverlayMode == 2) + this.m_Camera.hdr = mainCamera.hdr; + this.m_Camera.depthTextureMode = mainCamera.depthTextureMode; + this.m_Camera.clearStencilAfterLightingPass = mainCamera.clearStencilAfterLightingPass; + } + private void SetupCamera() + { + if (this.m_RenderMode == DrawCameraMode.Overdraw) { this.m_Camera.backgroundColor = Color.black; } @@ -1227,6 +1414,11 @@ private void SetupCamera() this.m_Camera.nearClipPlane = num2 * 5E-06f; this.m_Camera.farClipPlane = num2; this.m_Camera.renderingPath = SceneView.GetSceneViewRenderingPath(); + if (!this.CheckDrawModeForRenderingPath(this.m_RenderMode)) + { + this.m_RenderMode = DrawCameraMode.Textured; + } + this.SetSceneCameraHDRAndDepthModes(); Handles.EnableCameraFlares(this.m_Camera, this.m_SceneViewState.showFlares); Handles.EnableCameraSkybox(this.m_Camera, this.m_SceneViewState.showSkybox); this.m_Light[0].transform.position = this.m_Camera.transform.position; @@ -1280,63 +1472,63 @@ internal float GetVerticalOrthoSize() { return this.size * 0.707106769f / Mathf.Sqrt(this.m_Camera.aspect); } - public void LookAt(Vector3 position) + public void LookAt(Vector3 pos) { this.FixNegativeSize(); - this.m_Position.target = position; + this.m_Position.target = pos; } - public void LookAt(Vector3 position, Quaternion rotation) + public void LookAt(Vector3 pos, Quaternion rot) { this.FixNegativeSize(); - this.m_Position.target = position; - this.m_Rotation.target = rotation; - this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + this.m_Position.target = pos; + this.m_Rotation.target = rot; + this.svRot.UpdateGizmoLabel(this, rot * Vector3.forward, this.m_Ortho.target); } - public void LookAtDirect(Vector3 position, Quaternion rotation) + public void LookAtDirect(Vector3 pos, Quaternion rot) { this.FixNegativeSize(); - this.m_Position.value = position; - this.m_Rotation.value = rotation; - this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + this.m_Position.value = pos; + this.m_Rotation.value = rot; + this.svRot.UpdateGizmoLabel(this, rot * Vector3.forward, this.m_Ortho.target); } - public void LookAt(Vector3 position, Quaternion rotation, float size) + public void LookAt(Vector3 pos, Quaternion rot, float newSize) { this.FixNegativeSize(); - this.m_Position.target = position; - this.m_Rotation.target = rotation; - this.m_Size.target = Mathf.Abs(size); - this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + this.m_Position.target = pos; + this.m_Rotation.target = rot; + this.m_Size.target = Mathf.Abs(newSize); + this.svRot.UpdateGizmoLabel(this, rot * Vector3.forward, this.m_Ortho.target); } - public void LookAtDirect(Vector3 position, Quaternion rotation, float size) + public void LookAtDirect(Vector3 pos, Quaternion rot, float newSize) { this.FixNegativeSize(); - this.m_Position.value = position; - this.m_Rotation.value = rotation; - this.m_Size.value = Mathf.Abs(size); - this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + this.m_Position.value = pos; + this.m_Rotation.value = rot; + this.m_Size.value = Mathf.Abs(newSize); + this.svRot.UpdateGizmoLabel(this, rot * Vector3.forward, this.m_Ortho.target); } - public void LookAt(Vector3 position, Quaternion rotation, float size, bool orthographic) + public void LookAt(Vector3 pos, Quaternion rot, float newSize, bool ortho) { - this.LookAt(position, rotation, size, orthographic, false); + this.LookAt(pos, rot, newSize, ortho, false); } - public void LookAt(Vector3 position, Quaternion rotation, float size, bool orthographic, bool instant) + public void LookAt(Vector3 pos, Quaternion rot, float newSize, bool ortho, bool instant) { this.FixNegativeSize(); if (instant) { - this.m_Position.value = position; - this.m_Rotation.value = rotation; - this.m_Size.value = Mathf.Abs(size); - this.m_Ortho.value = orthographic; + this.m_Position.value = pos; + this.m_Rotation.value = rot; + this.m_Size.value = Mathf.Abs(newSize); + this.m_Ortho.value = ortho; } else { - this.m_Position.target = position; - this.m_Rotation.target = rotation; - this.m_Size.target = Mathf.Abs(size); - this.m_Ortho.target = orthographic; + this.m_Position.target = pos; + this.m_Rotation.target = rot; + this.m_Size.target = Mathf.Abs(newSize); + this.m_Ortho.target = ortho; } - this.svRot.UpdateGizmoLabel(this, rotation * Vector3.forward, this.m_Ortho.target); + this.svRot.UpdateGizmoLabel(this, rot * Vector3.forward, this.m_Ortho.target); } private void DefaultHandles() { @@ -1572,7 +1764,7 @@ public bool FrameSelected(bool lockView) { this.viewIsLockedToObject = lockView; this.FixNegativeSize(); - Bounds bounds = InternalEditorUtility.CalculateSelectionBounds(false); + Bounds bounds = InternalEditorUtility.CalculateSelectionBounds(false, Tools.pivotMode == PivotMode.Pivot); Editor[] activeEditors = this.GetActiveEditors(); for (int i = 0; i < activeEditors.Length; i++) { @@ -1581,13 +1773,13 @@ public bool FrameSelected(bool lockView) if (method != null) { object obj = method.Invoke(editor, null); - if (obj != null && obj is bool && (bool)obj) + if (obj is bool && (bool)obj) { MethodInfo method2 = editor.GetType().GetMethod("OnGetFrameBounds", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); if (method2 != null) { object obj2 = method2.Invoke(editor, null); - if (obj2 != null && obj2 is Bounds) + if (obj2 is Bounds) { bounds = (Bounds)obj2; } @@ -1611,15 +1803,15 @@ internal bool Frame(Bounds bounds) this.LookAt(bounds.center, this.m_Rotation.target, num * 2.2f, this.m_Ortho.value, EditorApplication.isPlaying); return true; } - private void Setup() + private void CreateSceneCameraAndLights() { GameObject gameObject = EditorUtility.CreateGameObjectWithHideFlags("SceneCamera", HideFlags.HideAndDontSave, new Type[] { typeof(Camera) }); - gameObject.AddComponent("FlareLayer"); - gameObject.AddComponent("HaloLayer"); - this.m_Camera = gameObject.camera; + gameObject.AddComponentInternal("FlareLayer"); + gameObject.AddComponentInternal("HaloLayer"); + this.m_Camera = gameObject.GetComponent(); this.m_Camera.enabled = false; for (int i = 0; i < 3; i++) { @@ -1627,9 +1819,9 @@ private void Setup() { typeof(Light) }); - this.m_Light[i] = gameObject2.light; + this.m_Light[i] = gameObject2.GetComponent(); this.m_Light[i].type = LightType.Directional; - this.m_Light[i].intensity = 0.5f; + this.m_Light[i].intensity = 1f; this.m_Light[i].enabled = false; } this.m_Light[0].color = SceneView.kSceneViewFrontLight; @@ -1685,6 +1877,7 @@ private void ResetOnSceneGUIState() } private void CallOnPreSceneGUI() { + SceneView.s_CurrentDrawingSceneView = this; Editor[] activeEditors = this.GetActiveEditors(); for (int i = 0; i < activeEditors.Length; i++) { @@ -1762,7 +1955,7 @@ private void ResetToDefaults(EditorBehaviorMode behaviorMode) this.m_2DMode = true; this.m_Rotation.value = Quaternion.identity; this.m_Position.value = SceneView.kDefaultPivot; - this.m_Size.value = SceneView.kDefaultViewSize; + this.m_Size.value = 10f; this.m_Ortho.value = true; this.m_LastSceneViewRotation = SceneView.kDefaultRotation; this.m_LastSceneViewOrtho = false; @@ -1772,7 +1965,7 @@ private void ResetToDefaults(EditorBehaviorMode behaviorMode) this.m_2DMode = false; this.m_Rotation.value = SceneView.kDefaultRotation; this.m_Position.value = SceneView.kDefaultPivot; - this.m_Size.value = SceneView.kDefaultViewSize; + this.m_Size.value = 10f; this.m_Ortho.value = false; } internal void OnNewProjectLayoutWasCreated() diff --git a/UnityEditor/UnityEditor/SceneViewMotion.cs b/UnityEditor/UnityEditor/SceneViewMotion.cs index 42c8055c..0acedabe 100644 --- a/UnityEditor/UnityEditor/SceneViewMotion.cs +++ b/UnityEditor/UnityEditor/SceneViewMotion.cs @@ -243,12 +243,12 @@ private static void HandleMouseUp(SceneView view, int id, int button, int clickC if (button == 2 && !SceneViewMotion.s_Dragged && SceneViewMotion.RaycastWorld(Event.current.mousePosition, out raycastHit)) { Vector3 b = view.pivot - view.rotation * Vector3.forward * view.cameraDistance; - float size = view.size; + float newSize = view.size; if (!view.orthographic) { - size = view.size * Vector3.Dot(raycastHit.point - b, view.rotation * Vector3.forward) / view.cameraDistance; + newSize = view.size * Vector3.Dot(raycastHit.point - b, view.rotation * Vector3.forward) / view.cameraDistance; } - view.LookAt(raycastHit.point, view.rotation, size); + view.LookAt(raycastHit.point, view.rotation, newSize); } Event.current.Use(); } @@ -528,5 +528,9 @@ private static void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) } Event.current.Use(); } + public static void ResetMotion() + { + SceneViewMotion.s_Motion = Vector3.zero; + } } } diff --git a/UnityEditor/UnityEditor/SceneViewOverlay.cs b/UnityEditor/UnityEditor/SceneViewOverlay.cs index 35af7ff8..3a7968ee 100644 --- a/UnityEditor/UnityEditor/SceneViewOverlay.cs +++ b/UnityEditor/UnityEditor/SceneViewOverlay.cs @@ -8,6 +8,7 @@ internal class SceneViewOverlay public enum Ordering { Camera = -100, + Cloth = 0, OcclusionCulling = 100, Lightmapping = 200, NavMesh = 300, diff --git a/UnityEditor/UnityEditor/SceneViewRotation.cs b/UnityEditor/UnityEditor/SceneViewRotation.cs index b2a960ef..95d8ba50 100644 --- a/UnityEditor/UnityEditor/SceneViewRotation.cs +++ b/UnityEditor/UnityEditor/SceneViewRotation.cs @@ -22,7 +22,6 @@ public Styles() } } private const int kRotationSize = 100; - private const int kRotationTop = 14; private const int kRotationMenuInset = 22; private static Quaternion[] kDirectionRotations = new Quaternion[] { @@ -60,9 +59,9 @@ public Styles() private int currentDir = 7; private AnimBool[] dirVisible = new AnimBool[] { - new AnimBool(), - new AnimBool(), - new AnimBool() + new AnimBool(true), + new AnimBool(true), + new AnimBool(true) }; private AnimBool[] dirNameVisible = new AnimBool[] { @@ -189,12 +188,12 @@ internal void HandleContextClick(SceneView view) Event current = Event.current; if (current.type == EventType.MouseDown && current.button == 1) { - int num = Mathf.Min(Screen.width, Screen.height - 14); + int num = Mathf.Min(Screen.width, Screen.height); if (num < 100) { return; } - Rect rect = new Rect((float)(Screen.width - 100 + 22), 20f, 56f, 56f); + Rect rect = new Rect((float)(Screen.width - 100 + 22), 22f, 56f, 56f); if (rect.Contains(current.mousePosition)) { this.DisplayContextMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), view); @@ -238,6 +237,27 @@ private void ContextMenuDelegate(object userData, string[] options, int selected { this.ViewSetOrtho(sceneView, !sceneView.orthographic); } + else + { + if (selected == 10) + { + sceneView.LookAt(sceneView.pivot, Quaternion.LookRotation(new Vector3(-1f, -0.7f, -1f)), sceneView.size, sceneView.orthographic); + } + else + { + if (selected == 11) + { + sceneView.LookAt(sceneView.pivot, Quaternion.LookRotation(new Vector3(1f, -0.7f, -1f)), sceneView.size, sceneView.orthographic); + } + else + { + if (selected == 12) + { + sceneView.LookAt(sceneView.pivot, Quaternion.LookRotation(new Vector3(1f, -0.7f, 1f)), sceneView.size, sceneView.orthographic); + } + } + } + } } } } @@ -266,11 +286,15 @@ private void DrawIsoStatusSymbol(Vector3 center, SceneView view, float alpha) } internal void OnGUI(SceneView view) { - int num = Mathf.Min(Screen.width, Screen.height - 14); + int num = Mathf.Min(Screen.width, Screen.height); if (num < 100) { return; } + if (Event.current.type == EventType.Repaint) + { + Profiler.BeginSample("SceneView.AxisSelector"); + } Camera camera = view.camera; HandleUtility.PushCamera(camera); if (camera.orthographic) @@ -283,10 +307,10 @@ internal void OnGUI(SceneView view) camera.nearClipPlane = 0.1f; camera.farClipPlane = 10f; camera.fieldOfView = view.m_Ortho.Fade(70f, 0f); - SceneView.AddCursorRect(new Rect((float)(Screen.width - 100), -14f, 100f, 148f), MouseCursor.Arrow); - Handles.SetCamera(new Rect((float)(Screen.width - 100), -14f, 100f, 128f), camera); + SceneView.AddCursorRect(new Rect((float)(Screen.width - 100 + 22), 22f, 56f, 102f), MouseCursor.Arrow); + Handles.SetCamera(new Rect((float)(Screen.width - 100), 0f, 100f, 100f), camera); Handles.BeginGUI(); - Rect rect = new Rect((float)(Screen.width - 100 + 17), 88f, 66f, 16f); + Rect rect = new Rect((float)(Screen.width - 100 + 17), 92f, 66f, 16f); if (!view.in2DMode && GUI.Button(rect, string.Empty, SceneViewRotation.styles.viewLabelStyleLeftAligned)) { if (Event.current.button == 1) @@ -326,15 +350,21 @@ internal void OnGUI(SceneView view) { Color centerColor = Handles.centerColor; centerColor.a *= this.dirNameVisible[num5].faded; - GUI.color = centerColor; - GUI.Label(position, SceneViewRotation.kDirNames[num5], SceneViewRotation.styles.viewLabelStyleLeftAligned); + if (centerColor.a > 0f) + { + GUI.color = centerColor; + GUI.Label(position, SceneViewRotation.kDirNames[num5], SceneViewRotation.styles.viewLabelStyleLeftAligned); + } } num5++; } Color centerColor2 = Handles.centerColor; centerColor2.a *= this.faded2Dgray * this.m_Visible.faded; - GUI.color = centerColor2; - GUI.Label(rect, SceneViewRotation.kDirNames[num2], SceneViewRotation.styles.viewLabelStyleCentered); + if (centerColor2.a > 0f) + { + GUI.color = centerColor2; + GUI.Label(rect, SceneViewRotation.kDirNames[num2], SceneViewRotation.styles.viewLabelStyleCentered); + } if (this.faded2Dgray < 1f) { this.DrawIsoStatusSymbol(new Vector3(position.x - 8f, position.y + 8.5f, 0f), view, 1f - this.faded2Dgray); @@ -419,15 +449,19 @@ internal void OnGUI(SceneView view) } HandleUtility.PopCamera(camera); Handles.SetCamera(camera); + if (Event.current.type == EventType.Repaint) + { + Profiler.EndSample(); + } } private void ViewAxisDirection(SceneView view, int dir) { - bool orthographic = view.orthographic; + bool ortho = view.orthographic; if (Event.current != null && (Event.current.shift || Event.current.button == 2)) { - orthographic = true; + ortho = true; } - view.LookAt(view.pivot, SceneViewRotation.kDirectionRotations[dir], view.size, orthographic); + view.LookAt(view.pivot, SceneViewRotation.kDirectionRotations[dir], view.size, ortho); this.SwitchDirNameVisible(dir); } private void ViewSetOrtho(SceneView view, bool ortho) diff --git a/UnityEditor/UnityEditor/ScriptAttributeUtility.cs b/UnityEditor/UnityEditor/ScriptAttributeUtility.cs index 0559e573..554b3cdb 100644 --- a/UnityEditor/UnityEditor/ScriptAttributeUtility.cs +++ b/UnityEditor/UnityEditor/ScriptAttributeUtility.cs @@ -38,6 +38,7 @@ private static void PopulateBuiltinAttributes() { ScriptAttributeUtility.s_BuiltinAttributes = new Dictionary>(); ScriptAttributeUtility.AddBuiltinAttribute("GUIText", "m_Text", new MultilineAttribute()); + ScriptAttributeUtility.AddBuiltinAttribute("TextMesh", "m_Text", new MultilineAttribute()); } private static void AddBuiltinAttribute(string componentTypeName, string propertyPath, PropertyAttribute attr) { diff --git a/UnityEditor/UnityEditor/ScriptableSingleton.cs b/UnityEditor/UnityEditor/ScriptableSingleton.cs index a8fb7072..ab77fa7d 100644 --- a/UnityEditor/UnityEditor/ScriptableSingleton.cs +++ b/UnityEditor/UnityEditor/ScriptableSingleton.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.IO; using UnityEditorInternal; @@ -28,12 +27,10 @@ protected ScriptableSingleton() else { ScriptableSingleton.s_Instance = (this as T); - Assert.That(ScriptableSingleton.s_Instance != null); } } private static void CreateAndLoad() { - Assert.That(ScriptableSingleton.s_Instance == null); string filePath = ScriptableSingleton.GetFilePath(); if (!string.IsNullOrEmpty(filePath)) { @@ -44,7 +41,6 @@ private static void CreateAndLoad() T t = ScriptableObject.CreateInstance(); t.hideFlags = HideFlags.HideAndDontSave; } - Assert.That(ScriptableSingleton.s_Instance != null); } protected virtual void Save(bool saveAsText) { diff --git a/UnityEditor/UnityEditor/ScriptableWizard.cs b/UnityEditor/UnityEditor/ScriptableWizard.cs index 35c44536..d693697f 100644 --- a/UnityEditor/UnityEditor/ScriptableWizard.cs +++ b/UnityEditor/UnityEditor/ScriptableWizard.cs @@ -92,18 +92,9 @@ private void OnGUI() { GUILayout.ExpandHeight(true) }); - if (this.m_Inspector == null) - { - this.m_Inspector = ScriptableObject.CreateInstance(); - this.m_Inspector.hideFlags = HideFlags.HideAndDontSave; - this.m_Inspector.InternalSetTargets(new UnityEngine.Object[] - { - this - }); - } this.m_ScrollPosition = EditorGUILayout.BeginVerticalScrollView(this.m_ScrollPosition, false, GUI.skin.verticalScrollbar, "OL Box", new GUILayoutOption[0]); GUIUtility.GetControlID(645789, FocusType.Passive); - bool flag = this.m_Inspector.DrawDefaultInspector(); + bool flag = this.DrawWizardGUI(); EditorGUILayout.EndScrollView(); GUILayout.BeginVertical(new GUILayoutOption[0]); if (this.m_ErrorString != string.Empty) @@ -165,6 +156,19 @@ private void OnGUI() this.InvokeWizardUpdate(); } } + protected virtual bool DrawWizardGUI() + { + if (this.m_Inspector == null) + { + this.m_Inspector = ScriptableObject.CreateInstance(); + this.m_Inspector.hideFlags = HideFlags.HideAndDontSave; + this.m_Inspector.InternalSetTargets(new UnityEngine.Object[] + { + this + }); + } + return this.m_Inspector.DrawDefaultInspector(); + } public static T DisplayWizard(string title) where T : ScriptableWizard { return ScriptableWizard.DisplayWizard(title, "Create", string.Empty); diff --git a/UnityEditor/UnityEditor/SearchFilter.cs b/UnityEditor/UnityEditor/SearchFilter.cs index 6c0cf615..c48cba06 100644 --- a/UnityEditor/UnityEditor/SearchFilter.cs +++ b/UnityEditor/UnityEditor/SearchFilter.cs @@ -28,6 +28,8 @@ public enum State [SerializeField] private string[] m_AssetLabels = new string[0]; [SerializeField] + private string[] m_AssetBundleNames = new string[0]; + [SerializeField] private int[] m_ReferencingInstanceIDs = new int[0]; [SerializeField] private bool m_ShowAllHits; @@ -68,6 +70,17 @@ public string[] assetLabels this.m_AssetLabels = value; } } + public string[] assetBundleNames + { + get + { + return this.m_AssetBundleNames; + } + set + { + this.m_AssetBundleNames = value; + } + } public int[] referencingInstanceIDs { get @@ -117,6 +130,7 @@ public void ClearSearch() this.m_NameFilter = string.Empty; this.m_ClassNames = new string[0]; this.m_AssetLabels = new string[0]; + this.m_AssetBundleNames = new string[0]; this.m_ReferencingInstanceIDs = new int[0]; this.m_ShowAllHits = false; } @@ -126,7 +140,7 @@ private bool IsNullOrEmtpy(T[] list) } public SearchFilter.State GetState() { - bool flag = !string.IsNullOrEmpty(this.m_NameFilter) || !this.IsNullOrEmtpy(this.m_AssetLabels) || !this.IsNullOrEmtpy(this.m_ClassNames) || !this.IsNullOrEmtpy(this.m_ReferencingInstanceIDs); + bool flag = !string.IsNullOrEmpty(this.m_NameFilter) || !this.IsNullOrEmtpy(this.m_AssetLabels) || !this.IsNullOrEmtpy(this.m_ClassNames) || !this.IsNullOrEmtpy(this.m_AssetBundleNames) || !this.IsNullOrEmtpy(this.m_ReferencingInstanceIDs); bool flag2 = !this.IsNullOrEmtpy(this.m_Folders); if (flag) { @@ -177,6 +191,11 @@ public bool SetNewFilter(SearchFilter newFilter) this.m_AssetLabels = newFilter.m_AssetLabels; result = true; } + if (newFilter.m_AssetBundleNames != this.m_AssetBundleNames) + { + this.m_AssetBundleNames = newFilter.m_AssetBundleNames; + result = true; + } if (newFilter.m_ReferencingInstanceIDs != this.m_ReferencingInstanceIDs) { this.m_ReferencingInstanceIDs = newFilter.m_ReferencingInstanceIDs; @@ -202,6 +221,10 @@ public override string ToString() { text = text + "[Labels: " + this.m_AssetLabels[0] + "]"; } + if (this.m_AssetBundleNames != null && this.m_AssetBundleNames.Length > 0) + { + text = text + "[AssetBundleNames: " + this.m_AssetBundleNames[0] + "]"; + } string text2; if (this.m_ClassNames != null && this.m_ClassNames.Length > 0) { @@ -249,6 +272,7 @@ internal string FilterToSearchFieldString() } this.AddToString("t:", this.m_ClassNames, ref text); this.AddToString("l:", this.m_AssetLabels, ref text); + this.AddToString("b:", this.m_AssetBundleNames, ref text); return text; } private void AddToString(string prefix, T[] list, ref string result) diff --git a/UnityEditor/UnityEditor/SearchUtility.cs b/UnityEditor/UnityEditor/SearchUtility.cs index 71984792..eea494a0 100644 --- a/UnityEditor/UnityEditor/SearchUtility.cs +++ b/UnityEditor/UnityEditor/SearchUtility.cs @@ -84,6 +84,16 @@ internal static bool ParseSingleWord(string searchString, SearchFilter filter, i }.ToArray(); result = true; } + num = searchString.IndexOf("b:"); + if (num >= 0) + { + string item3 = searchString.Substring(num + 2); + filter.assetBundleNames = new List(filter.assetBundleNames) + { + item3 + }.ToArray(); + result = true; + } num = searchString.IndexOf("ref:"); if (num >= 0) { diff --git a/UnityEditor/UnityEditor/SearchableEditorWindow.cs b/UnityEditor/UnityEditor/SearchableEditorWindow.cs index bec984ce..af228b70 100644 --- a/UnityEditor/UnityEditor/SearchableEditorWindow.cs +++ b/UnityEditor/UnityEditor/SearchableEditorWindow.cs @@ -11,7 +11,8 @@ public enum SearchMode All, Name, Type, - Label + Label, + AssetBundleName } public enum SearchModeHierarchyWindow { @@ -77,6 +78,10 @@ internal static SearchFilter CreateFilter(string searchString, SearchableEditorW { searchString }; + searchFilter.assetBundleNames = new string[] + { + searchString + }; searchFilter.showAllHits = true; } break; @@ -95,6 +100,12 @@ internal static SearchFilter CreateFilter(string searchString, SearchableEditorW searchString }; break; + case SearchableEditorWindow.SearchMode.AssetBundleName: + searchFilter.assetBundleNames = new string[] + { + searchString + }; + break; } return searchFilter; } @@ -167,9 +178,9 @@ internal void SelectPreviousSearchResult() { foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) { - if (current is BaseProjectWindow && current.m_HierarchyType == this.m_HierarchyType) + if (current is SceneHierarchyWindow) { - ((BaseProjectWindow)current).SelectPrevious(); + ((SceneHierarchyWindow)current).SelectPrevious(); break; } } @@ -178,16 +189,16 @@ internal void SelectNextSearchResult() { foreach (SearchableEditorWindow current in SearchableEditorWindow.searchableWindows) { - if (current is BaseProjectWindow && current.m_HierarchyType == this.m_HierarchyType) + if (current is SceneHierarchyWindow) { - ((BaseProjectWindow)current).SelectNext(); + ((SceneHierarchyWindow)current).SelectNext(); break; } } } - internal virtual void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode searchMode, bool setAll) + internal virtual void SetSearchFilter(string searchFilter, SearchableEditorWindow.SearchMode mode, bool setAll) { - this.m_SearchMode = searchMode; + this.m_SearchMode = mode; this.m_SearchFilter = searchFilter; if (setAll) { @@ -207,7 +218,11 @@ internal virtual void ClickedSearchField() } internal void SearchFieldGUI() { - Rect rect = GUILayoutUtility.GetRect(0f, EditorGUILayout.kLabelFloatMaxW * 1.5f, 16f, 16f, EditorStyles.toolbarSearchField); + this.SearchFieldGUI(EditorGUILayout.kLabelFloatMaxW * 1.5f); + } + internal void SearchFieldGUI(float maxWidth) + { + Rect rect = GUILayoutUtility.GetRect(EditorGUILayout.kLabelFloatMaxW * 0.2f, maxWidth, 16f, 16f, EditorStyles.toolbarSearchField); if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { this.ClickedSearchField(); diff --git a/UnityEditor/UnityEditor/Selection.cs b/UnityEditor/UnityEditor/Selection.cs index 7f29f118..5ff6b986 100644 --- a/UnityEditor/UnityEditor/Selection.cs +++ b/UnityEditor/UnityEditor/Selection.cs @@ -1,5 +1,6 @@ using System; using System.Collections; +using System.Collections.Generic; using System.Runtime.CompilerServices; using UnityEngine; namespace UnityEditor @@ -92,6 +93,35 @@ public static bool Contains(UnityEngine.Object obj) { return Selection.Contains(obj.GetInstanceID()); } + internal static void Add(int instanceID) + { + List list = new List(Selection.instanceIDs); + if (list.IndexOf(instanceID) < 0) + { + list.Add(instanceID); + Selection.instanceIDs = list.ToArray(); + } + } + internal static void Add(UnityEngine.Object obj) + { + if (obj != null) + { + Selection.Add(obj.GetInstanceID()); + } + } + internal static void Remove(int instanceID) + { + List list = new List(Selection.instanceIDs); + list.Remove(instanceID); + Selection.instanceIDs = list.ToArray(); + } + internal static void Remove(UnityEngine.Object obj) + { + if (obj != null) + { + Selection.Remove(obj.GetInstanceID()); + } + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Transform[] GetTransforms(SelectionMode mode); diff --git a/UnityEditor/UnityEditor/SemanticMergeMode.cs b/UnityEditor/UnityEditor/SemanticMergeMode.cs new file mode 100644 index 00000000..a748a050 --- /dev/null +++ b/UnityEditor/UnityEditor/SemanticMergeMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum SemanticMergeMode + { + Off, + Premerge, + Ask + } +} diff --git a/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs b/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs deleted file mode 100644 index 4bafc867..00000000 --- a/UnityEditor/UnityEditor/SerializedFileContainerWriter.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -namespace UnityEditor -{ - internal static class SerializedFileContainerWriter - { - internal class SerializedFile - { - public string Name; - public string FileName; - public long FileSize; - } - public static void Write(string filepath, IEnumerable files, string outputdir) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(SerializedFileContainerWriter.GetHead()); - filepath = Environment.CurrentDirectory + "/" + filepath; - filepath = filepath.Replace("\\", "/"); - foreach (SerializedFileContainerWriter.SerializedFile current in files) - { - stringBuilder.Append(SerializedFileContainerWriter.GetFieldDeclarationForFile(filepath, current.FileName)); - } - stringBuilder.Append(SerializedFileContainerWriter.GetConstructor(files)); - stringBuilder.Append(SerializedFileContainerWriter.GetTail()); - File.WriteAllText(Path.Combine(outputdir, "ProjectSerializedFileContainer.as"), stringBuilder.ToString()); - } - private static string GetHead() - { - return "\npackage\n{\n import flash.utils.ByteArray;\n import flash.utils.Dictionary;\n import flash.utils.Endian;\n import UnityEngine.*;\n\t\timport com.unity.SerializedFileContainer;\n\n public class ProjectSerializedFileContainer extends SerializedFileContainer\n {\n \n"; - } - private static string GetFieldDeclarationForFile(string filepath, string file) - { - return string.Concat(new string[] - { - " [Embed(\"", - filepath, - "/", - file, - "_txt\", mimeType=\"application/octet-stream\")]\n private var ", - SerializedFileContainerWriter.GetTypeNameForFile(file), - ":Class;\n\n" - }); - } - private static string GetConstructor(IEnumerable files) - { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.Append(" \n public function ProjectSerializedFileContainer()\n {\n files = new Dictionary();\n"); - foreach (SerializedFileContainerWriter.SerializedFile current in files) - { - stringBuilder.AppendLine(string.Concat(new object[] - { - "files[\"", - current.Name, - "\"] = ", - SerializedFileContainerWriter.GetArrayOfByteArrays(current) - })); - stringBuilder.AppendLine(string.Concat(new object[] - { - "fileSizes[\"", - current.Name, - "\"] = ", - current.FileSize - })); - } - stringBuilder.Append("}"); - return stringBuilder.ToString(); - } - private static StringBuilder GetArrayOfByteArrays(SerializedFileContainerWriter.SerializedFile file) - { - StringBuilder stringBuilder = new StringBuilder(string.Empty); - stringBuilder.Append("new " + SerializedFileContainerWriter.GetTypeNameForFile(file.Name) + "() as ByteArray"); - return stringBuilder; - } - private static string GetTypeNameForFile(string file) - { - file = file.Replace("/", "_"); - file = file.Replace(" ", "_"); - return file.Replace(".", "_"); - } - private static string GetTail() - { - return "\t}\n}\n"; - } - } -} diff --git a/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs b/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs index dc92bc1c..cc7d6c1d 100644 --- a/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs +++ b/UnityEditor/UnityEditor/SerializedMinMaxCurve.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using UnityEditorInternal; using UnityEngine; @@ -185,7 +184,6 @@ public bool OnCurveAreaMouseDown(int button, Rect drawRect, Rect curveRanges) } public ParticleSystemCurveEditor.CurveData CreateCurveData(Color color) { - Assert.That(this.state != MinMaxCurveState.k_Scalar); return new ParticleSystemCurveEditor.CurveData(this.GetUniqueCurveName(), this.m_DisplayName, this.GetMinCurve(), this.maxCurve, color, this.m_SignedRange, new CurveWrapper.GetAxisScalarsCallback(this.GetAxisScalars), new CurveWrapper.SetAxisScalarsCallback(this.SetAxisScalars), this.m_Module.foldout); } private SerializedProperty GetMinCurve() diff --git a/UnityEditor/UnityEditor/SerializedModule.cs b/UnityEditor/UnityEditor/SerializedModule.cs index ceb111d1..9017f8d6 100644 --- a/UnityEditor/UnityEditor/SerializedModule.cs +++ b/UnityEditor/UnityEditor/SerializedModule.cs @@ -6,6 +6,13 @@ internal class SerializedModule { protected string m_ModuleName; private SerializedObject m_Object; + internal SerializedObject serializedObject + { + get + { + return this.m_Object; + } + } public SerializedModule(SerializedObject o, string name) { this.m_Object = o; diff --git a/UnityEditor/UnityEditor/SerializedProperty.cs b/UnityEditor/UnityEditor/SerializedProperty.cs index 43eff151..9557f2d5 100644 --- a/UnityEditor/UnityEditor/SerializedProperty.cs +++ b/UnityEditor/UnityEditor/SerializedProperty.cs @@ -67,7 +67,7 @@ public extern string propertyPath [MethodImpl(MethodImplOptions.InternalCall)] get; } - internal extern string arrayIndexLessPropertyPath + internal extern int hashCodeForPropertyPathWithoutArrayIndex { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -136,6 +136,15 @@ public extern int intValue [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern long longValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool boolValue { [WrapperlessIcall] @@ -154,6 +163,15 @@ public extern float floatValue [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern double doubleValue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern string stringValue { [WrapperlessIcall] @@ -469,7 +487,7 @@ public SerializedProperty GetEndProperty([DefaultValue("false")] bool includeInv [DebuggerHidden] public IEnumerator GetEnumerator() { - SerializedProperty.c__Iterator7 c__Iterator = new SerializedProperty.c__Iterator7(); + SerializedProperty.c__Iterator0 c__Iterator = new SerializedProperty.c__Iterator0(); c__Iterator.<>f__this = this; return c__Iterator; } diff --git a/UnityEditor/UnityEditor/SetResolutionWizard.cs b/UnityEditor/UnityEditor/SetResolutionWizard.cs index c295e334..da934dfa 100644 --- a/UnityEditor/UnityEditor/SetResolutionWizard.cs +++ b/UnityEditor/UnityEditor/SetResolutionWizard.cs @@ -32,7 +32,7 @@ private void OnWizardCreate() { base.isValid = false; base.errorString = "Heightmaps above 4096x4096 in resolution are not supported"; - Debug.LogError("Heightmaps above 4096x4096 in resolution are not supported"); + Debug.LogError(base.errorString); return; } List list = new List(); diff --git a/UnityEditor/UnityEditor/Settings.cs b/UnityEditor/UnityEditor/Settings.cs index f28f9531..3721b62e 100644 --- a/UnityEditor/UnityEditor/Settings.cs +++ b/UnityEditor/UnityEditor/Settings.cs @@ -34,8 +34,8 @@ internal static void Set(string name, T value) where T : IPrefType [DebuggerHidden] internal static IEnumerable> Prefs() where T : IPrefType { - Settings.c__Iterator1 c__Iterator = new Settings.c__Iterator1(); - Settings.c__Iterator1 expr_07 = c__Iterator; + Settings.c__Iterator2 c__Iterator = new Settings.c__Iterator2(); + Settings.c__Iterator2 expr_07 = c__Iterator; expr_07.$PC = -2; return expr_07; } diff --git a/UnityEditor/UnityEditor/ShaderGUI.cs b/UnityEditor/UnityEditor/ShaderGUI.cs new file mode 100644 index 00000000..21b6c7cf --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderGUI.cs @@ -0,0 +1,53 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + public abstract class ShaderGUI + { + public virtual void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) + { + materialEditor.PropertiesDefaultGUI(properties); + } + public virtual void OnMaterialPreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) + { + materialEditor.DefaultPreviewGUI(r, background); + } + public virtual void OnMaterialInteractivePreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) + { + materialEditor.DefaultPreviewGUI(r, background); + } + public virtual void OnMaterialPreviewSettingsGUI(MaterialEditor materialEditor) + { + materialEditor.DefaultPreviewSettingsGUI(); + } + public virtual void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) + { + material.shader = newShader; + } + protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties) + { + return ShaderGUI.FindProperty(propertyName, properties, true); + } + protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties, bool propertyIsMandatory) + { + for (int i = 0; i < properties.Length; i++) + { + if (properties[i] != null && properties[i].name == propertyName) + { + return properties[i]; + } + } + if (propertyIsMandatory) + { + throw new ArgumentException(string.Concat(new object[] + { + "Could not find MaterialProperty: '", + propertyName, + "', Num properties: ", + properties.Length + })); + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderGUIUtility.cs b/UnityEditor/UnityEditor/ShaderGUIUtility.cs new file mode 100644 index 00000000..18d41a35 --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderGUIUtility.cs @@ -0,0 +1,37 @@ +using System; +using System.Reflection; +namespace UnityEditor +{ + internal static class ShaderGUIUtility + { + internal static ShaderGUI CreateShaderGUI(string customEditorName) + { + string value = "UnityEditor." + customEditorName; + Assembly[] loadedAssemblies = EditorAssemblies.loadedAssemblies; + for (int i = loadedAssemblies.Length - 1; i >= 0; i--) + { + Assembly assembly = loadedAssemblies[i]; + Type[] typesFromAssembly = AssemblyHelper.GetTypesFromAssembly(assembly); + Type[] array = typesFromAssembly; + int j = 0; + while (j < array.Length) + { + Type type = array[j]; + if (type.FullName.Equals(customEditorName, StringComparison.Ordinal) || type.FullName.Equals(value, StringComparison.Ordinal)) + { + if (typeof(ShaderGUI).IsAssignableFrom(type)) + { + return Activator.CreateInstance(type) as ShaderGUI; + } + return null; + } + else + { + j++; + } + } + } + return null; + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderImporterInspector.cs b/UnityEditor/UnityEditor/ShaderImporterInspector.cs index 57d2945d..7e882b0c 100644 --- a/UnityEditor/UnityEditor/ShaderImporterInspector.cs +++ b/UnityEditor/UnityEditor/ShaderImporterInspector.cs @@ -6,12 +6,13 @@ namespace UnityEditor [CustomEditor(typeof(ShaderImporter))] internal class ShaderImporterInspector : AssetImporterInspector { - private List names = new List(); + private List propertyNames = new List(); + private List displayNames = new List(); private List textures = new List(); private List dimensions = new List(); internal override void OnHeaderControlsGUI() { - Shader target = base.assetEditor.target as Shader; + Shader target = this.assetEditor.target as Shader; GUILayout.FlexibleSpace(); if (GUILayout.Button("Open...", EditorStyles.miniButton, new GUILayoutOption[0])) { @@ -23,23 +24,41 @@ public void OnEnable() { this.ResetValues(); } - private void ShowDefaultTextures(Shader shader, ShaderImporter importer) + private void ShowDefaultTextures() { - for (int i = 0; i < this.names.Count; i++) + if (this.propertyNames.Count == 0) + { + return; + } + EditorGUILayout.LabelField("Default Maps", EditorStyles.boldLabel, new GUILayoutOption[0]); + for (int i = 0; i < this.propertyNames.Count; i++) { - string name = this.names[i]; - string label = ObjectNames.NicifyVariableName(name); Texture obj = this.textures[i]; Texture value = null; EditorGUI.BeginChangeCheck(); + Type type; switch (this.dimensions[i]) { case ShaderUtil.ShaderPropertyTexDim.TexDim2D: - value = (EditorGUILayout.ObjectField(label, obj, typeof(Texture2D), false, new GUILayoutOption[0]) as Texture2D); + type = typeof(Texture); + break; + case ShaderUtil.ShaderPropertyTexDim.TexDim3D: + type = typeof(Texture3D); break; case ShaderUtil.ShaderPropertyTexDim.TexDimCUBE: - value = (EditorGUILayout.ObjectField(label, obj, typeof(Cubemap), false, new GUILayoutOption[0]) as Cubemap); + type = typeof(Cubemap); break; + case ShaderUtil.ShaderPropertyTexDim.TexDimAny: + type = typeof(Texture); + break; + default: + type = null; + break; + } + if (type != null) + { + string t = (!string.IsNullOrEmpty(this.displayNames[i])) ? this.displayNames[i] : ObjectNames.NicifyVariableName(this.propertyNames[i]); + value = (EditorGUILayout.MiniThumbnailObjectField(GUIContent.Temp(t), obj, type, null, new GUILayoutOption[0]) as Texture); } if (EditorGUI.EndChangeCheck()) { @@ -67,9 +86,9 @@ internal override bool HasModified() for (int i = 0; i < propertyCount; i++) { string propertyName = ShaderUtil.GetPropertyName(shader, i); - for (int j = 0; j < this.names.Count; j++) + for (int j = 0; j < this.propertyNames.Count; j++) { - if (this.names[j] == propertyName && this.textures[j] != shaderImporter.GetDefaultTexture(propertyName)) + if (this.propertyNames[j] == propertyName && this.textures[j] != shaderImporter.GetDefaultTexture(propertyName)) { return true; } @@ -80,7 +99,8 @@ internal override bool HasModified() internal override void ResetValues() { base.ResetValues(); - this.names = new List(); + this.propertyNames = new List(); + this.displayNames = new List(); this.textures = new List(); this.dimensions = new List(); ShaderImporter shaderImporter = this.target as ShaderImporter; @@ -99,8 +119,10 @@ internal override void ResetValues() if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { string propertyName = ShaderUtil.GetPropertyName(shader, i); + string propertyDescription = ShaderUtil.GetPropertyDescription(shader, i); Texture defaultTexture = shaderImporter.GetDefaultTexture(propertyName); - this.names.Add(propertyName); + this.propertyNames.Add(propertyName); + this.displayNames.Add(propertyDescription); this.textures.Add(defaultTexture); this.dimensions.Add(ShaderUtil.GetTexDim(shader, i)); } @@ -114,7 +136,7 @@ internal override void Apply() { return; } - shaderImporter.SetDefaultTextures(this.names.ToArray(), this.textures.ToArray()); + shaderImporter.SetDefaultTextures(this.propertyNames.ToArray(), this.textures.ToArray()); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(shaderImporter)); } private static int GetNumberOfTextures(Shader shader) @@ -142,11 +164,11 @@ public override void OnInspectorGUI() { return; } - if (ShaderImporterInspector.GetNumberOfTextures(shader) != this.names.Count) + if (ShaderImporterInspector.GetNumberOfTextures(shader) != this.propertyNames.Count) { this.ResetValues(); } - this.ShowDefaultTextures(shader, shaderImporter); + this.ShowDefaultTextures(); base.ApplyRevertGUI(); } } diff --git a/UnityEditor/UnityEditor/ShaderInspector.cs b/UnityEditor/UnityEditor/ShaderInspector.cs index 2e38276f..96abc97a 100644 --- a/UnityEditor/UnityEditor/ShaderInspector.cs +++ b/UnityEditor/UnityEditor/ShaderInspector.cs @@ -8,23 +8,14 @@ internal class ShaderInspector : Editor { internal class Styles { - public Texture2D errorIcon = EditorGUIUtility.LoadIcon("console.erroricon.sml"); - public Texture2D warningIcon = EditorGUIUtility.LoadIcon("console.warnicon.sml"); - public GUIContent showSurface = EditorGUIUtility.TextContent("ShaderInspector.ShowSurface"); - public GUIContent showCurrent = EditorGUIUtility.TextContent("ShaderInspector.ShowCurrent"); - public GUIContent showAll = EditorGUIUtility.TextContent("ShaderInspector.ShowAll"); - public GUIStyle messageStyle = "CN StatusInfo"; - public GUIStyle evenBackground = "CN EntryBackEven"; - } - internal class ShaderContextData - { - internal Shader shader; - internal int index; - internal ShaderContextData(Shader s, int i) - { - this.shader = s; - this.index = i; - } + public static Texture2D errorIcon = EditorGUIUtility.LoadIcon("console.erroricon.sml"); + public static Texture2D warningIcon = EditorGUIUtility.LoadIcon("console.warnicon.sml"); + public static GUIContent showSurface = EditorGUIUtility.TextContent("ShaderInspector.ShowSurface"); + public static GUIContent showCurrent = new GUIContent("Compile and show code | ▾"); + public static GUIStyle messageStyle = "CN StatusInfo"; + public static GUIStyle evenBackground = "CN EntryBackEven"; + public static GUIContent no = EditorGUIUtility.TextContent("ShaderInspector.No"); + public static GUIContent builtinSurfaceShader = EditorGUIUtility.TextContent("ShaderInspector.BuiltinSurfaceShader"); } private const float kSpace = 5f; private static readonly string[] kPropertyTypes = new string[] @@ -44,16 +35,6 @@ internal ShaderContextData(Shader s, int i) "Cubemap: ", "Any texture: " }; - private static readonly string[] kShaderLevels = new string[] - { - "Fixed function", - "SM1.x", - "SM2.0", - "SM3.0", - "SM4.0", - "SM5.0" - }; - internal static ShaderInspector.Styles ms_Styles; private static readonly int kErrorViewHash = "ShaderErrorView".GetHashCode(); private Vector2 m_ScrollPosition = Vector2.zero; public virtual void OnEnable() @@ -72,10 +53,6 @@ private static string GetPropertyType(Shader s, int index) } public override void OnInspectorGUI() { - if (ShaderInspector.ms_Styles == null) - { - ShaderInspector.ms_Styles = new ShaderInspector.Styles(); - } Shader shader = this.target as Shader; if (shader == null) { @@ -83,24 +60,38 @@ public override void OnInspectorGUI() } GUI.enabled = true; EditorGUI.indentLevel = 0; - if (!shader.isSupported) - { - GUILayout.Label("Shader has errors or is not supported by your graphics card", EditorStyles.helpBox, new GUILayoutOption[0]); - } - ShaderInspector.ShowSurfaceShaderButton(shader); + this.ShowShaderCodeArea(shader); if (shader.isSupported) { - EditorGUILayout.LabelField("Cast shadows", (!ShaderUtil.HasShadowCasterPass(shader) || !ShaderUtil.HasShadowCollectorPass(shader)) ? "no" : "yes", new GUILayoutOption[0]); + EditorGUILayout.LabelField("Cast shadows", (!ShaderUtil.HasShadowCasterPass(shader)) ? "no" : "yes", new GUILayoutOption[0]); EditorGUILayout.LabelField("Render queue", ShaderUtil.GetRenderQueue(shader).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[0]); EditorGUILayout.LabelField("LOD", ShaderUtil.GetLOD(shader).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[0]); - EditorGUILayout.LabelField("Geometry", ShaderUtil.GetSourceChannels(shader), new GUILayoutOption[0]); - EditorGUILayout.LabelField("Vertex shader", ShaderInspector.kShaderLevels[(int)ShaderUtil.GetVertexModel(shader)], new GUILayoutOption[0]); - EditorGUILayout.LabelField("Fragment shader", ShaderInspector.kShaderLevels[(int)ShaderUtil.GetFragmentModel(shader)], new GUILayoutOption[0]); EditorGUILayout.LabelField("Ignore projector", (!ShaderUtil.DoesIgnoreProjector(shader)) ? "no" : "yes", new GUILayoutOption[0]); + string label; + switch (shader.disableBatching) + { + case DisableBatchingType.False: + label = "no"; + break; + case DisableBatchingType.True: + label = "yes"; + break; + case DisableBatchingType.WhenLODFading: + label = "when LOD fading is on"; + break; + default: + label = "unknown"; + break; + } + EditorGUILayout.LabelField("Disable batching", label, new GUILayoutOption[0]); ShaderInspector.ShowShaderProperties(shader); } - this.ShowShaderErrors(shader); - ShaderInspector.ShowDebuggingData(shader); + } + private void ShowShaderCodeArea(Shader s) + { + ShaderInspector.ShowSurfaceShaderButton(s); + this.ShowCompiledCodeButton(s); + this.ShowShaderErrors(s); } private static void ShowShaderProperties(Shader s) { @@ -114,56 +105,6 @@ private static void ShowShaderProperties(Shader s) EditorGUILayout.LabelField(propertyName, label, new GUILayoutOption[0]); } } - private static void ShowShaderVariantsUI(Shader s) - { - EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PrefixLabel("Variants", EditorStyles.miniButton); - GUILayout.Label(ShaderUtil.GetComboCount(s).ToString(CultureInfo.InvariantCulture), new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - }); - if (GUILayout.Button("Show", EditorStyles.miniButton, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - })) - { - ShaderUtil.OpenShaderCombinations(s); - GUIUtility.ExitGUI(); - } - EditorGUILayout.EndHorizontal(); - } - private static void ShowCompiledShaderButtons(Shader s) - { - EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); - EditorGUILayout.PrefixLabel("Compiled code", EditorStyles.miniButton); - if (GUILayout.Button(ShaderInspector.ms_Styles.showCurrent, EditorStyles.miniButton, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - })) - { - ShaderUtil.OpenCompiledShader(s, false); - GUIUtility.ExitGUI(); - } - if (GUILayout.Button(ShaderInspector.ms_Styles.showAll, EditorStyles.miniButton, new GUILayoutOption[] - { - GUILayout.ExpandWidth(false) - })) - { - ShaderUtil.OpenCompiledShader(s, true); - GUIUtility.ExitGUI(); - } - EditorGUILayout.EndHorizontal(); - } - private void CopyShaderError(object o) - { - ShaderInspector.ShaderContextData shaderContextData = o as ShaderInspector.ShaderContextData; - if (shaderContextData == null) - { - return; - } - string shaderErrorMessage = ShaderUtil.GetShaderErrorMessage(shaderContextData.shader, shaderContextData.index); - EditorGUIUtility.systemCopyBuffer = shaderErrorMessage; - } private void ShowShaderErrors(Shader s) { int errorCount = ShaderUtil.GetErrorCount(s); @@ -180,12 +121,12 @@ private void ShowShaderErrors(Shader s) GUILayout.MinHeight(minHeight) }); EditorGUIUtility.SetIconSize(new Vector2(16f, 16f)); - float height = ShaderInspector.ms_Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(ShaderInspector.ms_Styles.errorIcon), 100f); + float height = ShaderInspector.Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(ShaderInspector.Styles.errorIcon), 100f); Event current = Event.current; for (int i = 0; i < errorCount; i++) { Rect controlRect = EditorGUILayout.GetControlRect(false, height, new GUILayoutOption[0]); - string shaderErrorMessage = ShaderUtil.GetShaderErrorMessage(s, i); + string shaderErrorMessage = ShaderUtil.GetShaderErrorMessage(s, i, false); string shaderErrorPlatform = ShaderUtil.GetShaderErrorPlatform(s, i); bool shaderErrorWarning = ShaderUtil.GetShaderErrorWarning(s, i); string shaderErrorFile = ShaderUtil.GetShaderErrorFile(s, i, true); @@ -197,14 +138,7 @@ private void ShowShaderErrors(Shader s) { string shaderErrorFile2 = ShaderUtil.GetShaderErrorFile(s, i, false); UnityEngine.Object @object = (!string.IsNullOrEmpty(shaderErrorFile2)) ? AssetDatabase.LoadMainAssetAtPath(shaderErrorFile2) : null; - if (@object != null) - { - AssetDatabase.OpenAsset(@object, shaderErrorLine); - } - else - { - AssetDatabase.OpenAsset(s, shaderErrorLine); - } + AssetDatabase.OpenAsset(@object ?? s, shaderErrorLine); GUIUtility.ExitGUI(); } current.Use(); @@ -213,12 +147,17 @@ private void ShowShaderErrors(Shader s) { current.Use(); GenericMenu genericMenu = new GenericMenu(); - genericMenu.AddItem(new GUIContent("Copy error text"), false, new GenericMenu.MenuFunction2(this.CopyShaderError), new ShaderInspector.ShaderContextData(s, i)); + int errorIndex = i; + genericMenu.AddItem(new GUIContent("Copy error text"), false, delegate + { + string shaderErrorMessage2 = ShaderUtil.GetShaderErrorMessage(s, errorIndex, true); + EditorGUIUtility.systemCopyBuffer = shaderErrorMessage2; + }); genericMenu.ShowAsContext(); } if (current.type == EventType.Repaint && (i & 1) == 0) { - GUIStyle evenBackground = ShaderInspector.ms_Styles.evenBackground; + GUIStyle evenBackground = ShaderInspector.Styles.evenBackground; evenBackground.Draw(controlRect, false, false, false, false); } Rect rect = controlRect; @@ -258,17 +197,41 @@ private void ShowShaderErrors(Shader s) } Rect position2 = controlRect; position2.xMax = position.xMin; - GUI.Label(position2, EditorGUIUtility.TempContent(shaderErrorMessage, (!shaderErrorWarning) ? ShaderInspector.ms_Styles.errorIcon : ShaderInspector.ms_Styles.warningIcon), ShaderInspector.ms_Styles.messageStyle); + GUI.Label(position2, EditorGUIUtility.TempContent(shaderErrorMessage, (!shaderErrorWarning) ? ShaderInspector.Styles.errorIcon : ShaderInspector.Styles.warningIcon), ShaderInspector.Styles.messageStyle); } EditorGUIUtility.SetIconSize(Vector2.zero); GUILayout.EndScrollView(); } - private static void ShowDebuggingData(Shader s) + private void ShowCompiledCodeButton(Shader s) { - GUILayout.Space(5f); - GUILayout.Label("Debugging:", EditorStyles.boldLabel, new GUILayoutOption[0]); - ShaderInspector.ShowCompiledShaderButtons(s); - ShaderInspector.ShowShaderVariantsUI(s); + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + EditorGUILayout.PrefixLabel("Compiled code", EditorStyles.miniButton); + bool flag = ShaderUtil.HasShaderSnippets(s) || ShaderUtil.HasSurfaceShaders(s); + if (flag) + { + GUIContent showCurrent = ShaderInspector.Styles.showCurrent; + Rect rect = GUILayoutUtility.GetRect(showCurrent, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + Rect position = new Rect(rect.xMax - 16f, rect.y, 16f, rect.height); + if (EditorGUI.ButtonMouseDown(position, GUIContent.none, FocusType.Passive, GUIStyle.none)) + { + Rect last = GUILayoutUtility.topLevel.GetLast(); + PopupWindow.Show(last, new ShaderInspectorPlatformsPopup(s)); + GUIUtility.ExitGUI(); + } + if (GUI.Button(rect, showCurrent, EditorStyles.miniButton)) + { + ShaderUtil.OpenCompiledShader(s, ShaderInspectorPlatformsPopup.currentMode, ShaderInspectorPlatformsPopup.currentPlatformMask, ShaderInspectorPlatformsPopup.currentVariantStripping == 0); + GUIUtility.ExitGUI(); + } + } + else + { + GUILayout.Button("none (fixed function shader)", GUI.skin.label, new GUILayoutOption[0]); + } + EditorGUILayout.EndHorizontal(); } private static void ShowSurfaceShaderButton(Shader s) { @@ -277,18 +240,25 @@ private static void ShowSurfaceShaderButton(Shader s) EditorGUILayout.PrefixLabel("Surface shader", EditorStyles.miniButton); if (flag) { - if (GUILayout.Button(ShaderInspector.ms_Styles.showSurface, EditorStyles.miniButton, new GUILayoutOption[] + if (!(AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(s)) == null)) { - GUILayout.ExpandWidth(false) - })) + if (GUILayout.Button(ShaderInspector.Styles.showSurface, EditorStyles.miniButton, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + })) + { + ShaderUtil.OpenParsedSurfaceShader(s); + GUIUtility.ExitGUI(); + } + } + else { - ShaderUtil.OpenParsedSurfaceShader(s); - GUIUtility.ExitGUI(); + GUILayout.Button(ShaderInspector.Styles.builtinSurfaceShader, GUI.skin.label, new GUILayoutOption[0]); } } else { - GUILayout.Label("no", new GUILayoutOption[0]); + GUILayout.Button(ShaderInspector.Styles.no, GUI.skin.label, new GUILayoutOption[0]); } EditorGUILayout.EndHorizontal(); } diff --git a/UnityEditor/UnityEditor/ShaderInspectorPlatformsPopup.cs b/UnityEditor/UnityEditor/ShaderInspectorPlatformsPopup.cs new file mode 100644 index 00000000..4768ceb0 --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderInspectorPlatformsPopup.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +namespace UnityEditor +{ + internal class ShaderInspectorPlatformsPopup : PopupWindowContent + { + private class Styles + { + public static readonly GUIStyle menuItem = "MenuItem"; + public static readonly GUIStyle separator = "sv_iconselector_sep"; + } + private const float kFrameWidth = 1f; + private const float kSeparatorHeight = 6f; + internal static readonly string[] s_PlatformModes = new string[] + { + "Current graphics device", + "Current build platform", + "All platforms", + "Custom:" + }; + private static string[] s_ShaderPlatformNames; + private static int[] s_ShaderPlatformIndices; + private readonly Shader m_Shader; + private static int s_CurrentMode = -1; + private static int s_CurrentPlatformMask = -1; + private static int s_CurrentVariantStripping = -1; + public static int currentMode + { + get + { + if (ShaderInspectorPlatformsPopup.s_CurrentMode < 0) + { + ShaderInspectorPlatformsPopup.s_CurrentMode = EditorPrefs.GetInt("ShaderInspectorPlatformMode", 1); + } + return ShaderInspectorPlatformsPopup.s_CurrentMode; + } + set + { + ShaderInspectorPlatformsPopup.s_CurrentMode = value; + EditorPrefs.SetInt("ShaderInspectorPlatformMode", value); + } + } + public static int currentPlatformMask + { + get + { + if (ShaderInspectorPlatformsPopup.s_CurrentPlatformMask < 0) + { + ShaderInspectorPlatformsPopup.s_CurrentPlatformMask = EditorPrefs.GetInt("ShaderInspectorPlatformMask", 32767); + } + return ShaderInspectorPlatformsPopup.s_CurrentPlatformMask; + } + set + { + ShaderInspectorPlatformsPopup.s_CurrentPlatformMask = value; + EditorPrefs.SetInt("ShaderInspectorPlatformMask", value); + } + } + public static int currentVariantStripping + { + get + { + if (ShaderInspectorPlatformsPopup.s_CurrentVariantStripping < 0) + { + ShaderInspectorPlatformsPopup.s_CurrentVariantStripping = EditorPrefs.GetInt("ShaderInspectorVariantStripping", 1); + } + return ShaderInspectorPlatformsPopup.s_CurrentVariantStripping; + } + set + { + ShaderInspectorPlatformsPopup.s_CurrentVariantStripping = value; + EditorPrefs.SetInt("ShaderInspectorVariantStripping", value); + } + } + public ShaderInspectorPlatformsPopup(Shader shader) + { + this.m_Shader = shader; + ShaderInspectorPlatformsPopup.InitializeShaderPlatforms(); + } + private static void InitializeShaderPlatforms() + { + if (ShaderInspectorPlatformsPopup.s_ShaderPlatformNames != null) + { + return; + } + int availableShaderCompilerPlatforms = ShaderUtil.GetAvailableShaderCompilerPlatforms(); + List list = new List(); + List list2 = new List(); + for (int i = 0; i < 32; i++) + { + if ((availableShaderCompilerPlatforms & 1 << i) != 0) + { + list.Add(((ShaderUtil.ShaderCompilerPlatformType)i).ToString()); + list2.Add(i); + } + } + ShaderInspectorPlatformsPopup.s_ShaderPlatformNames = list.ToArray(); + ShaderInspectorPlatformsPopup.s_ShaderPlatformIndices = list2.ToArray(); + } + public override Vector2 GetWindowSize() + { + int num = ShaderInspectorPlatformsPopup.s_PlatformModes.Length + ShaderInspectorPlatformsPopup.s_ShaderPlatformNames.Length + 2; + float num2 = (float)num * 16f + 18f; + num2 += 2f; + Vector2 result = new Vector2(210f, num2); + return result; + } + public override void OnGUI(Rect rect) + { + if (this.m_Shader == null) + { + return; + } + if (Event.current.type == EventType.Layout) + { + return; + } + this.Draw(base.editorWindow, rect.width); + if (Event.current.type == EventType.MouseMove) + { + Event.current.Use(); + } + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + base.editorWindow.Close(); + GUIUtility.ExitGUI(); + } + } + private void DrawSeparator(ref Rect rect) + { + GUI.Label(new Rect(rect.x + 5f, rect.y + 3f, rect.width - 10f, 3f), GUIContent.none, ShaderInspectorPlatformsPopup.Styles.separator); + rect.y += 6f; + } + private void Draw(EditorWindow caller, float listElementWidth) + { + Rect rect = new Rect(0f, 0f, listElementWidth, 16f); + for (int i = 0; i < ShaderInspectorPlatformsPopup.s_PlatformModes.Length; i++) + { + this.DoOneMode(rect, i); + rect.y += 16f; + } + Color color = GUI.color; + if (ShaderInspectorPlatformsPopup.currentMode != 3) + { + GUI.color *= new Color(1f, 1f, 1f, 0.7f); + } + rect.xMin += 16f; + for (int j = 0; j < ShaderInspectorPlatformsPopup.s_ShaderPlatformNames.Length; j++) + { + this.DoCustomPlatformBit(rect, j); + rect.y += 16f; + } + GUI.color = color; + rect.xMin -= 16f; + this.DrawSeparator(ref rect); + this.DoShaderVariants(caller, ref rect); + } + private void DoOneMode(Rect rect, int index) + { + EditorGUI.BeginChangeCheck(); + GUI.Toggle(rect, ShaderInspectorPlatformsPopup.currentMode == index, EditorGUIUtility.TempContent(ShaderInspectorPlatformsPopup.s_PlatformModes[index]), ShaderInspectorPlatformsPopup.Styles.menuItem); + if (EditorGUI.EndChangeCheck()) + { + ShaderInspectorPlatformsPopup.currentMode = index; + } + } + private void DoCustomPlatformBit(Rect rect, int index) + { + EditorGUI.BeginChangeCheck(); + int num = 1 << ShaderInspectorPlatformsPopup.s_ShaderPlatformIndices[index]; + bool flag = (ShaderInspectorPlatformsPopup.currentPlatformMask & num) != 0; + flag = GUI.Toggle(rect, flag, EditorGUIUtility.TempContent(ShaderInspectorPlatformsPopup.s_ShaderPlatformNames[index]), ShaderInspectorPlatformsPopup.Styles.menuItem); + if (EditorGUI.EndChangeCheck()) + { + if (flag) + { + ShaderInspectorPlatformsPopup.currentPlatformMask |= num; + } + else + { + ShaderInspectorPlatformsPopup.currentPlatformMask &= ~num; + } + ShaderInspectorPlatformsPopup.currentMode = 3; + } + } + private void DoShaderVariants(EditorWindow caller, ref Rect drawPos) + { + EditorGUI.BeginChangeCheck(); + bool flag = GUI.Toggle(drawPos, ShaderInspectorPlatformsPopup.currentVariantStripping == 1, EditorGUIUtility.TempContent("Skip unused shader_features"), ShaderInspectorPlatformsPopup.Styles.menuItem); + drawPos.y += 16f; + if (EditorGUI.EndChangeCheck()) + { + ShaderInspectorPlatformsPopup.currentVariantStripping = ((!flag) ? 0 : 1); + } + drawPos.y += 6f; + int comboCount = ShaderUtil.GetComboCount(this.m_Shader, flag); + string text = (!flag) ? (comboCount + " variants total") : (comboCount + " variants included"); + Rect position = drawPos; + position.x += (float)ShaderInspectorPlatformsPopup.Styles.menuItem.padding.left; + position.width -= (float)(ShaderInspectorPlatformsPopup.Styles.menuItem.padding.left + 4); + GUI.Label(position, text); + position.xMin = position.xMax - 40f; + if (GUI.Button(position, "Show", EditorStyles.miniButton)) + { + ShaderUtil.OpenShaderCombinations(this.m_Shader, flag); + caller.Close(); + GUIUtility.ExitGUI(); + } + } + } +} diff --git a/UnityEditor/UnityEditor/ShaderUtil.cs b/UnityEditor/UnityEditor/ShaderUtil.cs index c3302049..bc386b46 100644 --- a/UnityEditor/UnityEditor/ShaderUtil.cs +++ b/UnityEditor/UnityEditor/ShaderUtil.cs @@ -13,6 +13,25 @@ public enum ShaderPropertyType Range, TexEnv } + internal enum ShaderCompilerPlatformType + { + OpenGL, + D3D9, + Xbox360, + PS3, + D3D11, + OpenGLES20, + OpenGLES20Desktop, + Flash, + D3D11_9x, + OpenGLES30, + PSVita, + PS4, + XboxOne, + PSM, + Metal, + Count + } public enum ShaderPropertyTexDim { TexDimUnknown = -1, @@ -24,15 +43,6 @@ public enum ShaderPropertyTexDim TexDimAny, TexDimRECT = 5 } - internal enum ShaderModel - { - None, - SM1, - SM2, - SM3, - SM4, - SM5 - } internal static Rect rawViewportRect { get @@ -71,15 +81,9 @@ internal static extern bool hardwareSupportsFullNPOT [MethodImpl(MethodImplOptions.InternalCall)] get; } - internal static extern bool wireframeMode - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetAvailableShaderCompilerPlatforms(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void FetchCachedErrors(Shader s); @@ -88,7 +92,7 @@ internal static extern bool wireframeMode internal static extern int GetErrorCount(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetShaderErrorMessage(Shader s, int index); + internal static extern string GetShaderErrorMessage(Shader s, int index, bool includeDetails); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetShaderErrorPlatform(Shader s, int index); @@ -103,16 +107,13 @@ internal static extern bool wireframeMode internal static extern int GetShaderErrorLine(Shader s, int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetSnippetCount(Shader s); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetSnippetSize(Shader s); + internal static extern int GetComboCount(Shader s, bool usedBySceneOnly); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetComboCount(Shader s); + internal static extern bool HasSurfaceShaders(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool HasSurfaceShaders(Shader s); + internal static extern bool HasShaderSnippets(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetPropertyCount(Shader s); @@ -139,21 +140,15 @@ internal static extern bool wireframeMode public static extern bool IsShaderPropertyHidden(Shader s, int propertyIdx); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetShaderPropertyAttribute(Shader s, string name); + internal static extern string[] GetShaderPropertyAttributes(Shader s, string name); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasShadowCasterPass(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool HasShadowCollectorPass(Shader s); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasTangentChannel(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetSourceChannels(Shader s); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool DoesIgnoreProjector(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -163,34 +158,49 @@ internal static extern bool wireframeMode internal static extern int GetLOD(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetFallback(Shader s); + internal static extern string GetDependency(Shader s, string name); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetSubShaderCount(Shader s); + internal static extern int GetTextureBindingIndex(Shader s, int texturePropertyID); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetDependency(Shader s, string name); + internal static extern bool DoesShaderContainFixedFunctionPasses(Shader s); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern ShaderUtil.ShaderModel GetVertexModel(Shader s); + internal static extern void OpenCompiledShader(Shader shader, int mode, int customPlatformsMask, bool includeAllVariants); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern ShaderUtil.ShaderModel GetFragmentModel(Shader s); + internal static extern void OpenParsedSurfaceShader(Shader shader); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool DoesShaderContainFixedFunctionPasses(Shader s); + internal static extern void OpenShaderSnippets(Shader shader); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void OpenCompiledShader(Shader shader, bool allPlatforms); + internal static extern void OpenShaderCombinations(Shader shader, bool usedBySceneOnly); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void OpenParsedSurfaceShader(Shader shader); + internal static extern void CalculateLightmapStrippingFromCurrentScene(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void OpenShaderSnippets(Shader shader); + internal static extern void CalculateFogStrippingFromCurrentScene(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SaveCurrentShaderVariantCollection(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ClearCurrentShaderVariantCollection(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetCurrentShaderVariantCollectionShaderCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetCurrentShaderVariantCollectionVariantCount(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void GetShaderVariantEntries(Shader shader, ShaderVariantCollection skipAlreadyInCollection, out int[] types, out string[] keywords); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void OpenShaderCombinations(Shader shader); + internal static extern bool AddNewShaderToCollection(Shader shader, ShaderVariantCollection collection); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_get_rawViewportRect(out Rect value); diff --git a/UnityEditor/UnityEditor/ShaderVariantCollectionInspector.cs b/UnityEditor/UnityEditor/ShaderVariantCollectionInspector.cs new file mode 100644 index 00000000..eee1a78c --- /dev/null +++ b/UnityEditor/UnityEditor/ShaderVariantCollectionInspector.cs @@ -0,0 +1,129 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; +namespace UnityEditor +{ + [CustomEditor(typeof(ShaderVariantCollection))] + internal class ShaderVariantCollectionInspector : Editor + { + private class Styles + { + public static GUIContent iconAdd = EditorGUIUtility.IconContent("Toolbar Plus", "Add variant"); + public static GUIContent iconRemove = EditorGUIUtility.IconContent("Toolbar Minus", "Remove entry"); + public static GUIStyle invisibleButton = "InvisibleButton"; + } + internal class AddVariantMenuData + { + public Shader shader; + public ShaderVariantCollection collection; + public int[] types; + public string[] keywords; + } + private SerializedProperty m_Shaders; + public virtual void OnEnable() + { + this.m_Shaders = base.serializedObject.FindProperty("m_Shaders"); + } + private static Rect GetAddRemoveButtonRect(Rect r) + { + Vector2 vector = ShaderVariantCollectionInspector.Styles.invisibleButton.CalcSize(ShaderVariantCollectionInspector.Styles.iconRemove); + return new Rect(r.xMax - vector.x, r.y + (float)((int)(r.height / 2f - vector.y / 2f)), vector.x, vector.y); + } + private void AddVariantMenuSelected(object userData, string[] options, int selected) + { + ShaderVariantCollectionInspector.AddVariantMenuData addVariantMenuData = (ShaderVariantCollectionInspector.AddVariantMenuData)userData; + string[] keywords = addVariantMenuData.keywords[selected].Split(new char[] + { + ' ' + }); + ShaderVariantCollection.ShaderVariant variant = new ShaderVariantCollection.ShaderVariant(addVariantMenuData.shader, (PassType)addVariantMenuData.types[selected], keywords); + Undo.RecordObject(addVariantMenuData.collection, "Add variant"); + addVariantMenuData.collection.Add(variant); + } + private void DisplayAddVariantsMenu(Rect rect, Shader shader, ShaderVariantCollection collection) + { + ShaderVariantCollectionInspector.AddVariantMenuData addVariantMenuData = new ShaderVariantCollectionInspector.AddVariantMenuData(); + addVariantMenuData.shader = shader; + addVariantMenuData.collection = collection; + ShaderUtil.GetShaderVariantEntries(shader, collection, out addVariantMenuData.types, out addVariantMenuData.keywords); + if (addVariantMenuData.keywords.Length == 0) + { + EditorApplication.Beep(); + return; + } + string[] array = new string[addVariantMenuData.keywords.Length]; + for (int i = 0; i < addVariantMenuData.keywords.Length; i++) + { + array[i] = (PassType)addVariantMenuData.types[i] + "/" + ((!string.IsNullOrEmpty(addVariantMenuData.keywords[i])) ? addVariantMenuData.keywords[i] : ""); + } + EditorUtility.DisplayCustomMenu(rect, array, null, new EditorUtility.SelectMenuItemFunction(this.AddVariantMenuSelected), addVariantMenuData); + } + private void DrawShaderEntry(int shaderIndex) + { + SerializedProperty arrayElementAtIndex = this.m_Shaders.GetArrayElementAtIndex(shaderIndex); + Shader shader = (Shader)arrayElementAtIndex.FindPropertyRelative("first").objectReferenceValue; + SerializedProperty serializedProperty = arrayElementAtIndex.FindPropertyRelative("second.variants"); + using (new GUILayout.HorizontalScope(new GUILayoutOption[0])) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.boldLabel); + Rect addRemoveButtonRect = ShaderVariantCollectionInspector.GetAddRemoveButtonRect(rect); + rect.xMax = addRemoveButtonRect.x; + GUI.Label(rect, shader.name, EditorStyles.boldLabel); + if (GUI.Button(addRemoveButtonRect, ShaderVariantCollectionInspector.Styles.iconRemove, ShaderVariantCollectionInspector.Styles.invisibleButton)) + { + this.m_Shaders.DeleteArrayElementAtIndex(shaderIndex); + return; + } + } + for (int i = 0; i < serializedProperty.arraySize; i++) + { + SerializedProperty arrayElementAtIndex2 = serializedProperty.GetArrayElementAtIndex(i); + string text = arrayElementAtIndex2.FindPropertyRelative("keywords").stringValue; + if (string.IsNullOrEmpty(text)) + { + text = ""; + } + PassType intValue = (PassType)arrayElementAtIndex2.FindPropertyRelative("passType").intValue; + Rect rect2 = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel); + Rect addRemoveButtonRect2 = ShaderVariantCollectionInspector.GetAddRemoveButtonRect(rect2); + rect2.xMax = addRemoveButtonRect2.x; + GUI.Label(rect2, intValue + " " + text, EditorStyles.miniLabel); + if (GUI.Button(addRemoveButtonRect2, ShaderVariantCollectionInspector.Styles.iconRemove, ShaderVariantCollectionInspector.Styles.invisibleButton)) + { + serializedProperty.DeleteArrayElementAtIndex(i); + } + } + Rect rect3 = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.miniLabel); + Rect addRemoveButtonRect3 = ShaderVariantCollectionInspector.GetAddRemoveButtonRect(rect3); + if (GUI.Button(addRemoveButtonRect3, ShaderVariantCollectionInspector.Styles.iconAdd, ShaderVariantCollectionInspector.Styles.invisibleButton)) + { + this.DisplayAddVariantsMenu(addRemoveButtonRect3, shader, this.target as ShaderVariantCollection); + } + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + for (int i = 0; i < this.m_Shaders.arraySize; i++) + { + this.DrawShaderEntry(i); + } + if (GUILayout.Button("Add shader", new GUILayoutOption[0])) + { + ObjectSelector.get.Show(null, typeof(Shader), null, false); + ObjectSelector.get.objectSelectorID = "ShaderVariantSelector".GetHashCode(); + GUIUtility.ExitGUI(); + } + if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == "ObjectSelectorClosed" && ObjectSelector.get.objectSelectorID == "ShaderVariantSelector".GetHashCode()) + { + Shader shader = ObjectSelector.GetCurrentObject() as Shader; + if (shader != null) + { + ShaderUtil.AddNewShaderToCollection(shader, this.target as ShaderVariantCollection); + } + Event.current.Use(); + GUIUtility.ExitGUI(); + } + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/ShadowCascadeSplitGUI.cs b/UnityEditor/UnityEditor/ShadowCascadeSplitGUI.cs new file mode 100644 index 00000000..01cd24fc --- /dev/null +++ b/UnityEditor/UnityEditor/ShadowCascadeSplitGUI.cs @@ -0,0 +1,159 @@ +using System; +using System.Linq; +using UnityEngine; +namespace UnityEditor +{ + internal static class ShadowCascadeSplitGUI + { + private class DragCache + { + public int m_ActivePartition; + public float m_NormalizedPartitionSize; + public Vector2 m_LastCachedMousePosition; + public DragCache(int activePartition, float normalizedPartitionSize, Vector2 currentMousePos) + { + this.m_ActivePartition = activePartition; + this.m_NormalizedPartitionSize = normalizedPartitionSize; + this.m_LastCachedMousePosition = currentMousePos; + } + } + private const int kSliderbarTopMargin = 2; + private const int kSliderbarHeight = 24; + private const int kSliderbarBottomMargin = 2; + private const int kPartitionHandleWidth = 2; + private const int kPartitionHandleExtraHitAreaWidth = 2; + private static readonly Color[] kCascadeColors = new Color[] + { + new Color(0.5f, 0.5f, 0.6f, 1f), + new Color(0.5f, 0.6f, 0.5f, 1f), + new Color(0.6f, 0.6f, 0.5f, 1f), + new Color(0.6f, 0.5f, 0.5f, 1f) + }; + private static readonly GUIStyle s_CascadeSliderBG = "LODSliderRange"; + private static readonly GUIStyle s_TextCenteredStyle = new GUIStyle(EditorStyles.whiteMiniLabel) + { + alignment = TextAnchor.MiddleCenter + }; + private static ShadowCascadeSplitGUI.DragCache s_DragCache; + private static readonly int s_CascadeSliderId = "s_CascadeSliderId".GetHashCode(); + private static SceneView s_RestoreSceneView; + private static DrawCameraMode s_OldSceneDrawMode = DrawCameraMode.Textured; + private static bool s_OldSceneLightingMode; + public static void HandleCascadeSliderGUI(ref float[] normalizedCascadePartitions) + { + GUILayout.Label("Cascade splits", new GUILayoutOption[0]); + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, ShadowCascadeSplitGUI.s_CascadeSliderBG, new GUILayoutOption[] + { + GUILayout.Height(28f), + GUILayout.ExpandWidth(true) + }); + GUI.Box(rect, GUIContent.none); + float num = rect.x; + float top = rect.y + 2f; + float num2 = rect.width - (float)(normalizedCascadePartitions.Length * 2); + Color color = GUI.color; + Color backgroundColor = GUI.backgroundColor; + int num3 = -1; + float[] array = new float[normalizedCascadePartitions.Length + 1]; + Array.Copy(normalizedCascadePartitions, array, normalizedCascadePartitions.Length); + array[array.Length - 1] = 1f - normalizedCascadePartitions.Sum(); + int controlID = GUIUtility.GetControlID(ShadowCascadeSplitGUI.s_CascadeSliderId, FocusType.Passive); + Event current = Event.current; + int num4 = -1; + for (int i = 0; i < array.Length; i++) + { + float num5 = array[i]; + num3 = (num3 + 1) % ShadowCascadeSplitGUI.kCascadeColors.Length; + GUI.backgroundColor = ShadowCascadeSplitGUI.kCascadeColors[num3]; + float num6 = num2 * num5; + Rect rect2 = new Rect(num, top, num6, 24f); + GUI.Box(rect2, GUIContent.none, ShadowCascadeSplitGUI.s_CascadeSliderBG); + num += num6; + GUI.color = Color.white; + Rect position = rect2; + string text = string.Format("{0}\n{1:F1}%", i, num5 * 100f); + GUI.Label(position, GUIContent.Temp(text, text), ShadowCascadeSplitGUI.s_TextCenteredStyle); + if (i == array.Length - 1) + { + break; + } + GUI.backgroundColor = Color.black; + Rect rect3 = rect2; + rect3.x = num; + rect3.width = 2f; + GUI.Box(rect3, GUIContent.none, ShadowCascadeSplitGUI.s_CascadeSliderBG); + Rect position2 = rect3; + position2.xMin -= 2f; + position2.xMax += 2f; + if (position2.Contains(current.mousePosition)) + { + num4 = i; + } + if (ShadowCascadeSplitGUI.s_DragCache == null) + { + EditorGUIUtility.AddCursorRect(position2, MouseCursor.ResizeHorizontal, controlID); + } + num += 2f; + } + GUI.color = color; + GUI.backgroundColor = backgroundColor; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + if (num4 >= 0) + { + ShadowCascadeSplitGUI.s_DragCache = new ShadowCascadeSplitGUI.DragCache(num4, normalizedCascadePartitions[num4], current.mousePosition); + if (GUIUtility.hotControl == 0) + { + GUIUtility.hotControl = controlID; + } + current.Use(); + if (ShadowCascadeSplitGUI.s_RestoreSceneView == null) + { + ShadowCascadeSplitGUI.s_RestoreSceneView = SceneView.lastActiveSceneView; + if (ShadowCascadeSplitGUI.s_RestoreSceneView != null) + { + ShadowCascadeSplitGUI.s_OldSceneDrawMode = ShadowCascadeSplitGUI.s_RestoreSceneView.renderMode; + ShadowCascadeSplitGUI.s_OldSceneLightingMode = ShadowCascadeSplitGUI.s_RestoreSceneView.m_SceneLighting; + ShadowCascadeSplitGUI.s_RestoreSceneView.renderMode = DrawCameraMode.ShadowCascades; + } + } + } + break; + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + ShadowCascadeSplitGUI.s_DragCache = null; + if (ShadowCascadeSplitGUI.s_RestoreSceneView != null) + { + ShadowCascadeSplitGUI.s_RestoreSceneView.renderMode = ShadowCascadeSplitGUI.s_OldSceneDrawMode; + ShadowCascadeSplitGUI.s_RestoreSceneView.m_SceneLighting = ShadowCascadeSplitGUI.s_OldSceneLightingMode; + ShadowCascadeSplitGUI.s_RestoreSceneView = null; + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID) + { + float num7 = (current.mousePosition - ShadowCascadeSplitGUI.s_DragCache.m_LastCachedMousePosition).x / num2; + bool flag = array[ShadowCascadeSplitGUI.s_DragCache.m_ActivePartition] + num7 > 0f; + bool flag2 = array[ShadowCascadeSplitGUI.s_DragCache.m_ActivePartition + 1] - num7 > 0f; + if (flag && flag2) + { + ShadowCascadeSplitGUI.s_DragCache.m_NormalizedPartitionSize += num7; + normalizedCascadePartitions[ShadowCascadeSplitGUI.s_DragCache.m_ActivePartition] = ShadowCascadeSplitGUI.s_DragCache.m_NormalizedPartitionSize; + if (ShadowCascadeSplitGUI.s_DragCache.m_ActivePartition < normalizedCascadePartitions.Length - 1) + { + normalizedCascadePartitions[ShadowCascadeSplitGUI.s_DragCache.m_ActivePartition + 1] -= num7; + } + } + ShadowCascadeSplitGUI.s_DragCache.m_LastCachedMousePosition = current.mousePosition; + current.Use(); + } + break; + } + } + } +} diff --git a/UnityEditor/UnityEditor/ShapeModuleUI.cs b/UnityEditor/UnityEditor/ShapeModuleUI.cs index 4986d5bd..56d5fb8e 100644 --- a/UnityEditor/UnityEditor/ShapeModuleUI.cs +++ b/UnityEditor/UnityEditor/ShapeModuleUI.cs @@ -15,7 +15,10 @@ private enum ShapeTypes Mesh, ConeShell, ConeVolume, - ConeVolumeShell + ConeVolumeShell, + Circle, + CircleEdge, + SingleSidedEdge } private class Texts { @@ -29,7 +32,9 @@ private class Texts public GUIContent mesh = new GUIContent("Mesh", "Mesh that the particle system will emit from."); public GUIContent randomDirection = new GUIContent("Random Direction", "Randomizes the starting direction of particles."); public GUIContent emitFromShell = new GUIContent("Emit from Shell", "Emit from shell of the sphere. If disabled particles will be emitted from the volume of the shape."); + public GUIContent emitFromEdge = new GUIContent("Emit from Edge", "Emit from edge of the shape. If disabled particles will be emitted from the volume of the shape."); public GUIContent emitFrom = new GUIContent("Emit from:", "Specifies from where particles are emitted."); + public GUIContent arc = new GUIContent("Arc", "Circle arc angle."); } private SerializedProperty m_Type; private SerializedProperty m_RandomDirection; @@ -39,6 +44,7 @@ private class Texts private SerializedProperty m_BoxX; private SerializedProperty m_BoxY; private SerializedProperty m_BoxZ; + private SerializedProperty m_Arc; private SerializedProperty m_PlacementMode; private SerializedProperty m_Mesh; private Material m_Material; @@ -51,7 +57,9 @@ private class Texts "HemiSphere", "Cone", "Box", - "Mesh" + "Mesh", + "Circle", + "Edge" }; private ShapeModuleUI.ShapeTypes[] m_GuiTypes = new ShapeModuleUI.ShapeTypes[] { @@ -59,7 +67,9 @@ private class Texts ShapeModuleUI.ShapeTypes.HemiSphere, ShapeModuleUI.ShapeTypes.Cone, ShapeModuleUI.ShapeTypes.Box, - ShapeModuleUI.ShapeTypes.Mesh + ShapeModuleUI.ShapeTypes.Mesh, + ShapeModuleUI.ShapeTypes.Circle, + ShapeModuleUI.ShapeTypes.SingleSidedEdge }; private int[] m_TypeToGuiTypeIndex = new int[] { @@ -72,7 +82,10 @@ private class Texts 4, 2, 2, - 2 + 2, + 5, + 5, + 6 }; private static ShapeModuleUI.Texts s_Texts = new ShapeModuleUI.Texts(); public ShapeModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "ShapeModule", displayName, ModuleUI.VisibilityState.VisibleAndFolded) @@ -96,10 +109,11 @@ protected override void Init() this.m_BoxX = base.GetProperty("boxX"); this.m_BoxY = base.GetProperty("boxY"); this.m_BoxZ = base.GetProperty("boxZ"); + this.m_Arc = base.GetProperty("arc"); this.m_PlacementMode = base.GetProperty("placementMode"); this.m_Mesh = base.GetProperty("m_Mesh"); this.m_RandomDirection = base.GetProperty("randomDirection"); - this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Diffuse.mat") as Material); + this.m_Material = (EditorGUIUtility.GetBuiltinExtraResource(typeof(Material), "Default-Material.mat") as Material); this.m_BoxEditor.SetAlwaysDisplayHandles(true); } public override float GetXAxisScalar() @@ -144,7 +158,7 @@ private int ConvertConeTypeToConeEmitFrom(ShapeModuleUI.ShapeTypes shapeType) } private bool GetUsesShell(ShapeModuleUI.ShapeTypes shapeType) { - return shapeType == ShapeModuleUI.ShapeTypes.HemiSphereShell || shapeType == ShapeModuleUI.ShapeTypes.SphereShell || shapeType == ShapeModuleUI.ShapeTypes.ConeShell || shapeType == ShapeModuleUI.ShapeTypes.ConeVolumeShell; + return shapeType == ShapeModuleUI.ShapeTypes.HemiSphereShell || shapeType == ShapeModuleUI.ShapeTypes.SphereShell || shapeType == ShapeModuleUI.ShapeTypes.ConeShell || shapeType == ShapeModuleUI.ShapeTypes.ConeVolumeShell || shapeType == ShapeModuleUI.ShapeTypes.CircleEdge; } public override void OnInspectorGUI(ParticleSystem s) { @@ -214,6 +228,17 @@ public override void OnInspectorGUI(ParticleSystem s) ModuleUI.GUIObject(ShapeModuleUI.s_Texts.mesh, this.m_Mesh); break; } + case ShapeModuleUI.ShapeTypes.Circle: + { + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.radius, this.m_Radius); + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.arc, this.m_Arc); + bool flag3 = ModuleUI.GUIToggle(ShapeModuleUI.s_Texts.emitFromEdge, usesShell); + num = ((!flag3) ? 10 : 11); + break; + } + case ShapeModuleUI.ShapeTypes.SingleSidedEdge: + ModuleUI.GUIFloat(ShapeModuleUI.s_Texts.radius, this.m_Radius); + break; } this.m_Type.intValue = num; ModuleUI.GUIToggle(ShapeModuleUI.s_Texts.randomDirection, this.m_RandomDirection); @@ -232,6 +257,14 @@ public override void OnSceneGUI(ParticleSystem s, InitialModuleUI initial) { this.m_Radius.floatValue = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, this.m_Radius.floatValue, false); } + if (intValue == 10 || intValue == 11) + { + float floatValue = this.m_Radius.floatValue; + float floatValue2 = this.m_Arc.floatValue; + Handles.DoSimpleRadiusArcHandleXY(Quaternion.identity, Vector3.zero, ref floatValue, ref floatValue2); + this.m_Radius.floatValue = floatValue; + this.m_Arc.floatValue = floatValue2; + } else { if (intValue == 2 || intValue == 3) @@ -273,16 +306,23 @@ public override void OnSceneGUI(ParticleSystem s, InitialModuleUI initial) } else { - if (intValue == 6) + if (intValue == 12) + { + this.m_Radius.floatValue = Handles.DoSimpleEdgeHandle(Quaternion.identity, Vector3.zero, this.m_Radius.floatValue); + } + else { - Mesh mesh = (Mesh)this.m_Mesh.objectReferenceValue; - if (mesh) + if (intValue == 6) { - bool wireframeMode = ShaderUtil.wireframeMode; - ShaderUtil.wireframeMode = true; - this.m_Material.SetPass(0); - Graphics.DrawMeshNow(mesh, s.transform.localToWorldMatrix); - ShaderUtil.wireframeMode = wireframeMode; + Mesh mesh = (Mesh)this.m_Mesh.objectReferenceValue; + if (mesh) + { + bool wireframe = GL.wireframe; + GL.wireframe = true; + this.m_Material.SetPass(0); + Graphics.DrawMeshNow(mesh, s.transform.localToWorldMatrix); + GL.wireframe = wireframe; + } } } } diff --git a/UnityEditor/UnityEditor/SimpleProfiler.cs b/UnityEditor/UnityEditor/SimpleProfiler.cs index 865e12a8..1d845840 100644 --- a/UnityEditor/UnityEditor/SimpleProfiler.cs +++ b/UnityEditor/UnityEditor/SimpleProfiler.cs @@ -9,6 +9,7 @@ internal class SimpleProfiler private static Stack m_Names = new Stack(); private static Stack m_StartTime = new Stack(); private static Dictionary m_Timers = new Dictionary(); + private static Dictionary m_Calls = new Dictionary(); [Conditional("SIMPLE_PROFILER")] public static void Begin(string label) { @@ -33,6 +34,19 @@ public static void End() { SimpleProfiler.m_Timers[text] = num; } + if (SimpleProfiler.m_Calls.ContainsKey(text)) + { + Dictionary calls; + Dictionary expr_6E = calls = SimpleProfiler.m_Calls; + string key; + string expr_72 = key = text; + int num3 = calls[key]; + expr_6E[expr_72] = num3 + 1; + } + else + { + SimpleProfiler.m_Calls[text] = 1; + } } [Conditional("SIMPLE_PROFILER")] public static void PrintTimes() @@ -40,12 +54,13 @@ public static void PrintTimes() string text = "Measured execution times:\n----------------------------\n"; foreach (KeyValuePair current in SimpleProfiler.m_Timers) { - text += string.Format("{0,6:0.0} ms: {1}\n", current.Value * 1000f, current.Key); + text += string.Format("{0,6:0.0} ms: {1} in {2} calls\n", current.Value * 1000f, current.Key, SimpleProfiler.m_Calls[current.Key]); } UnityEngine.Debug.Log(text); SimpleProfiler.m_Names.Clear(); SimpleProfiler.m_StartTime.Clear(); SimpleProfiler.m_Timers.Clear(); + SimpleProfiler.m_Calls.Clear(); } } } diff --git a/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs b/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs index ac2934bc..6c0817bb 100644 --- a/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs +++ b/UnityEditor/UnityEditor/SkinnedMeshRendererEditor.cs @@ -1,32 +1,43 @@ using System; +using System.Collections.Generic; using UnityEngine; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(SkinnedMeshRenderer))] - internal class SkinnedMeshRendererEditor : Editor + internal class SkinnedMeshRendererEditor : RendererEditorBase { private static int s_BoxHash = "SkinnedMeshRendererEditor".GetHashCode(); private SerializedProperty m_CastShadows; private SerializedProperty m_ReceiveShadows; private SerializedProperty m_Materials; - private SerializedProperty m_UseLightProbes; - private SerializedProperty m_LightProbeAnchor; private SerializedProperty m_AABB; private SerializedProperty m_DirtyAABB; private SerializedProperty m_BlendShapeWeights; private BoxEditor m_BoxEditor = new BoxEditor(false, SkinnedMeshRendererEditor.s_BoxHash); - public void OnEnable() + private string[] m_ExcludedProperties; + public override void OnEnable() { + base.OnEnable(); this.m_CastShadows = base.serializedObject.FindProperty("m_CastShadows"); this.m_ReceiveShadows = base.serializedObject.FindProperty("m_ReceiveShadows"); this.m_Materials = base.serializedObject.FindProperty("m_Materials"); - this.m_UseLightProbes = base.serializedObject.FindProperty("m_UseLightProbes"); - this.m_LightProbeAnchor = base.serializedObject.FindProperty("m_LightProbeAnchor"); this.m_BlendShapeWeights = base.serializedObject.FindProperty("m_BlendShapeWeights"); this.m_AABB = base.serializedObject.FindProperty("m_AABB"); this.m_DirtyAABB = base.serializedObject.FindProperty("m_DirtyAABB"); this.m_BoxEditor.OnEnable(); this.m_BoxEditor.SetAlwaysDisplayHandles(true); + base.InitializeProbeFields(); + List list = new List(); + list.AddRange(new string[] + { + "m_CastShadows", + "m_ReceiveShadows", + "m_Materials", + "m_BlendShapeWeights", + "m_AABB" + }); + list.AddRange(RendererEditorBase.Probes.GetFieldsStringArray()); + this.m_ExcludedProperties = list.ToArray(); } public void OnDisable() { @@ -39,23 +50,8 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(this.m_CastShadows, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_ReceiveShadows, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Materials, true, new GUILayoutOption[0]); - EditorGUILayout.PropertyField(this.m_UseLightProbes, new GUILayoutOption[0]); - if (this.m_UseLightProbes.boolValue) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(this.m_LightProbeAnchor, new GUIContent("Anchor Override", this.m_LightProbeAnchor.tooltip), new GUILayoutOption[0]); - EditorGUI.indentLevel--; - } - Editor.DrawPropertiesExcluding(base.serializedObject, new string[] - { - "m_CastShadows", - "m_ReceiveShadows", - "m_Materials", - "m_UseLightProbes", - "m_LightProbeAnchor", - "m_BlendShapeWeights", - "m_AABB" - }); + base.RenderProbeFields(); + Editor.DrawPropertiesExcluding(base.serializedObject, this.m_ExcludedProperties); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(this.m_AABB, new GUIContent("Bounds"), new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) diff --git a/UnityEditor/UnityEditor/SliderLabels.cs b/UnityEditor/UnityEditor/SliderLabels.cs new file mode 100644 index 00000000..e2a2902d --- /dev/null +++ b/UnityEditor/UnityEditor/SliderLabels.cs @@ -0,0 +1,22 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal struct SliderLabels + { + public GUIContent leftLabel; + public GUIContent rightLabel; + public void SetLabels(GUIContent leftLabel, GUIContent rightLabel) + { + if (Event.current.type == EventType.Repaint) + { + this.leftLabel = leftLabel; + this.rightLabel = rightLabel; + } + } + public bool HasLabels() + { + return Event.current.type == EventType.Repaint && this.leftLabel != null && this.rightLabel != null; + } + } +} diff --git a/UnityEditor/UnityEditor/SpeedTreeImporter.cs b/UnityEditor/UnityEditor/SpeedTreeImporter.cs new file mode 100644 index 00000000..104fee8f --- /dev/null +++ b/UnityEditor/UnityEditor/SpeedTreeImporter.cs @@ -0,0 +1,229 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +using UnityEngine.Rendering; +namespace UnityEditor +{ + public sealed class SpeedTreeImporter : AssetImporter + { + public static readonly string[] windQualityNames = new string[] + { + "None", + "Fastest", + "Fast", + "Better", + "Best", + "Palm" + }; + public extern bool hasImported + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string materialFolderPath + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern float scaleFactor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color mainColor + { + get + { + Color result; + this.INTERNAL_get_mainColor(out result); + return result; + } + set + { + this.INTERNAL_set_mainColor(ref value); + } + } + public Color specColor + { + get + { + Color result; + this.INTERNAL_get_specColor(out result); + return result; + } + set + { + this.INTERNAL_set_specColor(ref value); + } + } + public Color hueVariation + { + get + { + Color result; + this.INTERNAL_get_hueVariation(out result); + return result; + } + set + { + this.INTERNAL_set_hueVariation(ref value); + } + } + public extern float shininess + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float alphaTestRef + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasBillboard + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool enableSmoothLODTransition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float billboardTransitionCrossFadeWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float fadeOutWidth + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float[] LODHeights + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool[] castShadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool[] receiveShadows + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool[] useLightProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ReflectionProbeUsage[] reflectionProbeUsages + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool[] enableBump + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool[] enableHue + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int bestWindQuality + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int[] windQualities + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_mainColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_mainColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_specColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_specColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_hueVariation(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_hueVariation(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void GenerateMaterials(); + } +} diff --git a/UnityEditor/UnityEditor/SpeedTreeImporterInspector.cs b/UnityEditor/UnityEditor/SpeedTreeImporterInspector.cs new file mode 100644 index 00000000..16fb0610 --- /dev/null +++ b/UnityEditor/UnityEditor/SpeedTreeImporterInspector.cs @@ -0,0 +1,361 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.AnimatedValues; +using UnityEditor.VersionControl; +using UnityEngine; +using UnityEngine.Events; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(SpeedTreeImporter))] + internal class SpeedTreeImporterInspector : AssetImporterInspector + { + private class Styles + { + public static GUIContent LODHeader = EditorGUIUtility.TextContent("SpeedTreeImporter.LODHeader"); + public static GUIContent ResetLOD = EditorGUIUtility.TextContent("SpeedTreeImporter.ResetLOD"); + public static GUIContent SmoothLOD = EditorGUIUtility.TextContent("SpeedTreeImporter.SmoothLOD"); + public static GUIContent CrossFadeWidth = EditorGUIUtility.TextContent("SpeedTreeImporter.CrossFadeWidth"); + public static GUIContent FadeOutWidth = EditorGUIUtility.TextContent("SpeedTreeImporter.FadeOutWidth"); + public static GUIContent MeshesHeader = EditorGUIUtility.TextContent("SpeedTreeImporter.MeshesHeader"); + public static GUIContent ScaleFactor = EditorGUIUtility.TextContent("SpeedTreeImporter.ScaleFactor"); + public static GUIContent ScaleFactorHelp = EditorGUIUtility.TextContent("SpeedTreeImporter.ScaleFactorHelp"); + public static GUIContent MaterialsHeader = EditorGUIUtility.TextContent("SpeedTreeImporter.MaterialsHeader"); + public static GUIContent MainColor = EditorGUIUtility.TextContent("SpeedTreeImporter.MainColor"); + public static GUIContent SpecColor = EditorGUIUtility.TextContent("SpeedTreeImporter.SpecColor"); + public static GUIContent HueVariation = EditorGUIUtility.TextContent("SpeedTreeImporter.HueVariation"); + public static GUIContent Shininess = EditorGUIUtility.TextContent("SpeedTreeImporter.Shininess"); + public static GUIContent AlphaTestRef = EditorGUIUtility.TextContent("SpeedTreeImporter.AlphaTestRef"); + public static GUIContent CastShadows = EditorGUIUtility.TextContent("SpeedTreeImporter.CastShadows"); + public static GUIContent ReceiveShadows = EditorGUIUtility.TextContent("SpeedTreeImporter.ReceiveShadows"); + public static GUIContent UseLightProbes = EditorGUIUtility.TextContent("SpeedTreeImporter.UseLightProbes"); + public static GUIContent UseReflectionProbes = EditorGUIUtility.TextContent("SpeedTreeImporter.UseReflectionProbes"); + public static GUIContent EnableBump = EditorGUIUtility.TextContent("SpeedTreeImporter.EnableBump"); + public static GUIContent EnableHue = EditorGUIUtility.TextContent("SpeedTreeImporter.EnableHue"); + public static GUIContent WindQuality = EditorGUIUtility.TextContent("SpeedTreeImporter.WindQuality"); + public static GUIContent ApplyAndGenerate = EditorGUIUtility.TextContent("SpeedTreeImporter.ApplyAndGenerate"); + public static GUIContent Regenerate = EditorGUIUtility.TextContent("SpeedTreeImporter.Regenerate"); + } + private const float kFeetToMetersRatio = 0.3048f; + private SerializedProperty m_LODSettings; + private SerializedProperty m_EnableSmoothLOD; + private SerializedProperty m_BillboardTransitionCrossFadeWidth; + private SerializedProperty m_FadeOutWidth; + private SerializedProperty m_MainColor; + private SerializedProperty m_SpecColor; + private SerializedProperty m_HueVariation; + private SerializedProperty m_Shininess; + private SerializedProperty m_AlphaTestRef; + private SerializedProperty m_ScaleFactor; + private int m_SelectedLODSlider = -1; + private int m_SelectedLODRange; + private readonly AnimBool m_ShowSmoothLODOptions = new AnimBool(); + private readonly int m_LODSliderId = "LODSliderIDHash".GetHashCode(); + private SpeedTreeImporter[] importers + { + get + { + return base.targets.Cast().ToArray(); + } + } + private void OnEnable() + { + this.m_LODSettings = base.serializedObject.FindProperty("m_LODSettings"); + this.m_EnableSmoothLOD = base.serializedObject.FindProperty("m_EnableSmoothLODTransition"); + this.m_BillboardTransitionCrossFadeWidth = base.serializedObject.FindProperty("m_BillboardTransitionCrossFadeWidth"); + this.m_FadeOutWidth = base.serializedObject.FindProperty("m_FadeOutWidth"); + this.m_MainColor = base.serializedObject.FindProperty("m_MainColor"); + this.m_SpecColor = base.serializedObject.FindProperty("m_SpecColor"); + this.m_HueVariation = base.serializedObject.FindProperty("m_HueVariation"); + this.m_Shininess = base.serializedObject.FindProperty("m_Shininess"); + this.m_AlphaTestRef = base.serializedObject.FindProperty("m_AlphaTestRef"); + this.m_ScaleFactor = base.serializedObject.FindProperty("m_ScaleFactor"); + this.m_ShowSmoothLODOptions.value = (this.m_EnableSmoothLOD.hasMultipleDifferentValues || this.m_EnableSmoothLOD.boolValue); + this.m_ShowSmoothLODOptions.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + public override void OnDisable() + { + base.OnDisable(); + this.m_ShowSmoothLODOptions.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + } + protected override bool ApplyRevertGUIButtons() + { + EditorGUI.BeginDisabledGroup(!this.HasModified()); + base.RevertButton(); + bool result = base.ApplyButton("Apply Prefab"); + EditorGUI.EndDisabledGroup(); + GUIContent content; + if (this.HasModified()) + { + content = SpeedTreeImporterInspector.Styles.ApplyAndGenerate; + } + else + { + content = SpeedTreeImporterInspector.Styles.Regenerate; + } + if (GUILayout.Button(content, new GUILayoutOption[0])) + { + bool flag = this.HasModified(); + if (flag) + { + this.Apply(); + } + this.GenerateMaterials(); + if (flag) + { + base.ApplyAndImport(); + result = true; + } + } + return result; + } + private void GenerateMaterials() + { + string[] array = ( + from im in this.importers + select im.materialFolderPath).ToArray(); + string[] source = AssetDatabase.FindAssets("t:Material", array); + string[] array2 = ( + from guid in source + select AssetDatabase.GUIDToAssetPath(guid)).ToArray(); + bool flag = true; + if (array2.Length > 0) + { + flag = Provider.PromptAndCheckoutIfNeeded(array2, string.Format("Materials will be checked out in:\n{0}", string.Join("\n", array))); + } + if (flag) + { + SpeedTreeImporter[] importers = this.importers; + for (int i = 0; i < importers.Length; i++) + { + SpeedTreeImporter speedTreeImporter = importers[i]; + speedTreeImporter.GenerateMaterials(); + } + } + } + internal List GetLODInfoArray(Rect area) + { + int lodCount = this.m_LODSettings.arraySize; + return LODGroupGUI.CreateLODInfos(lodCount, area, (int i) => (i != lodCount - 1 || !(this.target as SpeedTreeImporter).hasBillboard) ? string.Format("LOD {0}", i) : "Billboard", (int i) => this.m_LODSettings.GetArrayElementAtIndex(i).FindPropertyRelative("height").floatValue); + } + public bool HasSameLODConfig() + { + if (base.serializedObject.FindProperty("m_HasBillboard").hasMultipleDifferentValues) + { + return false; + } + if (this.m_LODSettings.FindPropertyRelative("Array.size").hasMultipleDifferentValues) + { + return false; + } + for (int i = 0; i < this.m_LODSettings.arraySize; i++) + { + if (this.m_LODSettings.GetArrayElementAtIndex(i).FindPropertyRelative("height").hasMultipleDifferentValues) + { + return false; + } + } + return true; + } + public bool CanUnifyLODConfig() + { + return !base.serializedObject.FindProperty("m_HasBillboard").hasMultipleDifferentValues && !this.m_LODSettings.FindPropertyRelative("Array.size").hasMultipleDifferentValues; + } + public override void OnInspectorGUI() + { + this.ShowMeshGUI(); + this.ShowMaterialGUI(); + this.ShowLODGUI(); + EditorGUILayout.Space(); + base.ApplyRevertGUI(); + } + private void ShowMeshGUI() + { + GUILayout.Label(SpeedTreeImporterInspector.Styles.MeshesHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ScaleFactor, SpeedTreeImporterInspector.Styles.ScaleFactor, new GUILayoutOption[0]); + if (!this.m_ScaleFactor.hasMultipleDifferentValues && Mathf.Approximately(this.m_ScaleFactor.floatValue, 0.3048f)) + { + EditorGUILayout.HelpBox(SpeedTreeImporterInspector.Styles.ScaleFactorHelp.text, MessageType.Info); + } + } + private void ShowMaterialGUI() + { + GUILayout.Label(SpeedTreeImporterInspector.Styles.MaterialsHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_MainColor, SpeedTreeImporterInspector.Styles.MainColor, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_SpecColor, SpeedTreeImporterInspector.Styles.SpecColor, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_HueVariation, SpeedTreeImporterInspector.Styles.HueVariation, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_Shininess, 0.01f, 1f, SpeedTreeImporterInspector.Styles.Shininess, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_AlphaTestRef, 0f, 1f, SpeedTreeImporterInspector.Styles.AlphaTestRef, new GUILayoutOption[0]); + } + private void ShowLODGUI() + { + this.m_ShowSmoothLODOptions.target = (this.m_EnableSmoothLOD.hasMultipleDifferentValues || this.m_EnableSmoothLOD.boolValue); + GUILayout.Label(SpeedTreeImporterInspector.Styles.LODHeader, EditorStyles.boldLabel, new GUILayoutOption[0]); + if (!Application.HasAdvancedLicense()) + { + EditorGUILayout.HelpBox("LOD only available in Unity Pro", MessageType.Warning); + return; + } + EditorGUILayout.PropertyField(this.m_EnableSmoothLOD, SpeedTreeImporterInspector.Styles.SmoothLOD, new GUILayoutOption[0]); + EditorGUI.indentLevel++; + if (EditorGUILayout.BeginFadeGroup(this.m_ShowSmoothLODOptions.faded)) + { + EditorGUILayout.Slider(this.m_BillboardTransitionCrossFadeWidth, 0f, 1f, SpeedTreeImporterInspector.Styles.CrossFadeWidth, new GUILayoutOption[0]); + EditorGUILayout.Slider(this.m_FadeOutWidth, 0f, 1f, SpeedTreeImporterInspector.Styles.FadeOutWidth, new GUILayoutOption[0]); + } + EditorGUILayout.EndFadeGroup(); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + if (this.HasSameLODConfig()) + { + EditorGUILayout.Space(); + Rect rect = GUILayoutUtility.GetRect(0f, 30f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + List lODInfoArray = this.GetLODInfoArray(rect); + this.DrawLODLevelSlider(rect, lODInfoArray); + EditorGUILayout.Space(); + EditorGUILayout.Space(); + if (this.m_SelectedLODRange != -1 && lODInfoArray.Count > 0) + { + EditorGUILayout.LabelField(lODInfoArray[this.m_SelectedLODRange].LODName + " Options", EditorStyles.boldLabel, new GUILayoutOption[0]); + bool flag = this.m_SelectedLODRange == lODInfoArray.Count - 1 && this.importers[0].hasBillboard; + if (!flag) + { + EditorGUILayout.PropertyField(this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("castShadows"), SpeedTreeImporterInspector.Styles.CastShadows, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("receiveShadows"), SpeedTreeImporterInspector.Styles.ReceiveShadows, new GUILayoutOption[0]); + } + SerializedProperty serializedProperty = this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("useLightProbes"); + EditorGUILayout.PropertyField(serializedProperty, SpeedTreeImporterInspector.Styles.UseLightProbes, new GUILayoutOption[0]); + if (!serializedProperty.hasMultipleDifferentValues && serializedProperty.boolValue && flag) + { + EditorGUILayout.HelpBox("Enabling Light Probe for billboards breaks batched rendering and may cause performance problem.", MessageType.Warning); + } + EditorGUILayout.PropertyField(this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("enableBump"), SpeedTreeImporterInspector.Styles.EnableBump, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("enableHue"), SpeedTreeImporterInspector.Styles.EnableHue, new GUILayoutOption[0]); + int num = this.importers.Min((SpeedTreeImporter im) => im.bestWindQuality); + if (num > 0) + { + if (flag) + { + num = ((num < 1) ? 0 : 1); + } + EditorGUILayout.Popup(this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODRange).FindPropertyRelative("windQuality"), ( + from s in SpeedTreeImporter.windQualityNames.Take(num + 1) + select new GUIContent(s)).ToArray(), SpeedTreeImporterInspector.Styles.WindQuality, new GUILayoutOption[0]); + } + } + } + else + { + if (this.CanUnifyLODConfig()) + { + EditorGUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.FlexibleSpace(); + Rect rect2 = GUILayoutUtility.GetRect(SpeedTreeImporterInspector.Styles.ResetLOD, EditorStyles.miniButton); + if (GUI.Button(rect2, SpeedTreeImporterInspector.Styles.ResetLOD, EditorStyles.miniButton)) + { + GenericMenu genericMenu = new GenericMenu(); + foreach (SpeedTreeImporter current in base.targets.Cast()) + { + string text = string.Format("{0}: {1}", Path.GetFileNameWithoutExtension(current.assetPath), string.Join(" | ", ( + from height in current.LODHeights + select string.Format("{0:0}%", height * 100f)).ToArray())); + genericMenu.AddItem(new GUIContent(text), false, new GenericMenu.MenuFunction2(this.OnResetLODMenuClick), current); + } + genericMenu.DropDown(rect2); + } + EditorGUILayout.EndHorizontal(); + } + Rect rect3 = GUILayoutUtility.GetRect(0f, 30f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(true) + }); + if (Event.current.type == EventType.Repaint) + { + LODGroupGUI.DrawMixedValueLODSlider(rect3); + } + } + EditorGUILayout.Space(); + } + private void DrawLODLevelSlider(Rect sliderPosition, List lods) + { + int controlID = GUIUtility.GetControlID(this.m_LODSliderId, FocusType.Passive); + Event current = Event.current; + switch (current.GetTypeForControl(controlID)) + { + case EventType.MouseDown: + { + Rect rect = sliderPosition; + rect.x -= 5f; + rect.width += 10f; + if (rect.Contains(current.mousePosition)) + { + current.Use(); + GUIUtility.hotControl = controlID; + IOrderedEnumerable collection = + from lod in lods + where lod.ScreenPercent > 0.5f + select lod into x + orderby x.LODLevel descending + select x; + IOrderedEnumerable collection2 = + from lod in lods + where lod.ScreenPercent <= 0.5f + select lod into x + orderby x.LODLevel + select x; + List list = new List(); + list.AddRange(collection); + list.AddRange(collection2); + foreach (LODGroupGUI.LODInfo current2 in list) + { + if (current2.m_ButtonPosition.Contains(current.mousePosition)) + { + this.m_SelectedLODSlider = current2.LODLevel; + this.m_SelectedLODRange = current2.LODLevel; + break; + } + if (current2.m_RangePosition.Contains(current.mousePosition)) + { + this.m_SelectedLODSlider = -1; + this.m_SelectedLODRange = current2.LODLevel; + break; + } + } + } + break; + } + case EventType.MouseUp: + if (GUIUtility.hotControl == controlID) + { + GUIUtility.hotControl = 0; + current.Use(); + } + break; + case EventType.MouseDrag: + if (GUIUtility.hotControl == controlID && this.m_SelectedLODSlider >= 0 && lods[this.m_SelectedLODSlider] != null) + { + current.Use(); + float num = Mathf.Clamp01(1f - (current.mousePosition.x - sliderPosition.x) / sliderPosition.width); + LODGroupGUI.SetSelectedLODLevelPercentage(num - 0.001f, this.m_SelectedLODSlider, lods); + this.m_LODSettings.GetArrayElementAtIndex(this.m_SelectedLODSlider).FindPropertyRelative("height").floatValue = lods[this.m_SelectedLODSlider].RawScreenPercent; + } + break; + case EventType.Repaint: + LODGroupGUI.DrawLODSlider(sliderPosition, lods, this.m_SelectedLODRange); + break; + } + } + private void OnResetLODMenuClick(object userData) + { + float[] lODHeights = (userData as SpeedTreeImporter).LODHeights; + for (int i = 0; i < lODHeights.Length; i++) + { + this.m_LODSettings.GetArrayElementAtIndex(i).FindPropertyRelative("height").floatValue = lODHeights[i]; + } + } + } +} diff --git a/UnityEditor/UnityEditor/SpeedTreeMaterialInspector.cs b/UnityEditor/UnityEditor/SpeedTreeMaterialInspector.cs new file mode 100644 index 00000000..528e1fa5 --- /dev/null +++ b/UnityEditor/UnityEditor/SpeedTreeMaterialInspector.cs @@ -0,0 +1,174 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using UnityEngine.Rendering; +namespace UnityEditor +{ + [CanEditMultipleObjects] + internal class SpeedTreeMaterialInspector : MaterialEditor + { + private enum SpeedTreeGeometryType + { + Branch, + BranchDetail, + BranchBlend, + Frond, + Leaf, + FacingLeaf, + Mesh + } + private string[] speedTreeGeometryTypeString = new string[] + { + "GEOM_TYPE_BRANCH", + "GEOM_TYPE_BRANCH_DETAIL", + "GEOM_TYPE_BRANCH_BLEND", + "GEOM_TYPE_FROND", + "GEOM_TYPE_LEAF", + "GEOM_TYPE_FACING_LEAF", + "GEOM_TYPE_MESH" + }; + private bool ShouldEnableAlphaTest(SpeedTreeMaterialInspector.SpeedTreeGeometryType geomType) + { + return geomType == SpeedTreeMaterialInspector.SpeedTreeGeometryType.Frond || geomType == SpeedTreeMaterialInspector.SpeedTreeGeometryType.Leaf || geomType == SpeedTreeMaterialInspector.SpeedTreeGeometryType.FacingLeaf; + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + SerializedProperty serializedProperty = base.serializedObject.FindProperty("m_Shader"); + if (!base.isVisible || serializedProperty.hasMultipleDifferentValues || serializedProperty.objectReferenceValue == null) + { + return; + } + List list = new List(MaterialEditor.GetMaterialProperties(base.targets)); + base.SetDefaultGUIWidths(); + SpeedTreeMaterialInspector.SpeedTreeGeometryType[] array = new SpeedTreeMaterialInspector.SpeedTreeGeometryType[base.targets.Length]; + for (int i = 0; i < base.targets.Length; i++) + { + array[i] = SpeedTreeMaterialInspector.SpeedTreeGeometryType.Branch; + for (int j = 0; j < this.speedTreeGeometryTypeString.Length; j++) + { + if (((Material)base.targets[i]).shaderKeywords.Contains(this.speedTreeGeometryTypeString[j])) + { + array[i] = (SpeedTreeMaterialInspector.SpeedTreeGeometryType)j; + break; + } + } + } + EditorGUI.showMixedValue = (array.Distinct().Count() > 1); + EditorGUI.BeginChangeCheck(); + SpeedTreeMaterialInspector.SpeedTreeGeometryType speedTreeGeometryType = (SpeedTreeMaterialInspector.SpeedTreeGeometryType)EditorGUILayout.EnumPopup("Geometry Type", array[0], new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + bool flag = this.ShouldEnableAlphaTest(speedTreeGeometryType); + CullMode value = (!flag) ? CullMode.Back : CullMode.Off; + foreach (Material current in base.targets.Cast()) + { + for (int k = 0; k < this.speedTreeGeometryTypeString.Length; k++) + { + current.DisableKeyword(this.speedTreeGeometryTypeString[k]); + } + current.EnableKeyword(this.speedTreeGeometryTypeString[(int)speedTreeGeometryType]); + current.renderQueue = ((!flag) ? 2000 : 2450); + current.SetInt("_Cull", (int)value); + } + } + EditorGUI.showMixedValue = false; + MaterialProperty materialProperty = list.Find((MaterialProperty prop) => prop.name == "_MainTex"); + if (materialProperty != null) + { + list.Remove(materialProperty); + base.ShaderProperty(materialProperty, materialProperty.displayName); + } + MaterialProperty materialProperty2 = list.Find((MaterialProperty prop) => prop.name == "_BumpMap"); + if (materialProperty2 != null) + { + list.Remove(materialProperty2); + IEnumerable source = + from t in base.targets + select ((Material)t).shaderKeywords.Contains("EFFECT_BUMP"); + bool? flag2 = this.ToggleShaderProperty(materialProperty2, source.First(), source.Distinct().Count() > 1); + if (flag2.HasValue) + { + foreach (Material current2 in base.targets.Cast()) + { + if (flag2.Value) + { + current2.EnableKeyword("EFFECT_BUMP"); + } + else + { + current2.DisableKeyword("EFFECT_BUMP"); + } + } + } + } + MaterialProperty materialProperty3 = list.Find((MaterialProperty prop) => prop.name == "_DetailTex"); + if (materialProperty3 != null) + { + list.Remove(materialProperty3); + if (array.Contains(SpeedTreeMaterialInspector.SpeedTreeGeometryType.BranchDetail)) + { + base.ShaderProperty(materialProperty3, materialProperty3.displayName); + } + } + IEnumerable enumerable = + from t in base.targets + select ((Material)t).shaderKeywords.Contains("EFFECT_HUE_VARIATION"); + MaterialProperty materialProperty4 = list.Find((MaterialProperty prop) => prop.name == "_HueVariation"); + if (enumerable != null && materialProperty4 != null) + { + list.Remove(materialProperty4); + bool? flag3 = this.ToggleShaderProperty(materialProperty4, enumerable.First(), enumerable.Distinct().Count() > 1); + if (flag3.HasValue) + { + foreach (Material current3 in base.targets.Cast()) + { + if (flag3.Value) + { + current3.EnableKeyword("EFFECT_HUE_VARIATION"); + } + else + { + current3.DisableKeyword("EFFECT_HUE_VARIATION"); + } + } + } + } + MaterialProperty materialProperty5 = list.Find((MaterialProperty prop) => prop.name == "_Cutoff"); + if (materialProperty5 != null) + { + list.Remove(materialProperty5); + if (array.Any((SpeedTreeMaterialInspector.SpeedTreeGeometryType t) => this.ShouldEnableAlphaTest(t))) + { + base.ShaderProperty(materialProperty5, materialProperty5.displayName); + } + } + foreach (MaterialProperty current4 in list) + { + if ((current4.flags & MaterialProperty.PropFlags.HideInInspector) == MaterialProperty.PropFlags.None) + { + base.ShaderProperty(current4, current4.displayName); + } + } + } + private bool? ToggleShaderProperty(MaterialProperty prop, bool enable, bool hasMixedEnable) + { + EditorGUI.BeginChangeCheck(); + EditorGUI.showMixedValue = hasMixedEnable; + enable = EditorGUI.ToggleLeft(EditorGUILayout.GetControlRect(false, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }), prop.displayName, enable); + EditorGUI.showMixedValue = false; + bool? result = (!EditorGUI.EndChangeCheck()) ? null : new bool?(enable); + GUILayout.Space(-EditorGUIUtility.singleLineHeight); + EditorGUI.BeginDisabledGroup(!enable && !hasMixedEnable); + EditorGUI.showMixedValue = prop.hasMixedValue; + base.ShaderProperty(prop, " "); + EditorGUI.showMixedValue = false; + EditorGUI.EndDisabledGroup(); + return result; + } + } +} diff --git a/UnityEditor/UnityEditor/SplitterGUILayout.cs b/UnityEditor/UnityEditor/SplitterGUILayout.cs index ba4d7c04..6c8f5201 100644 --- a/UnityEditor/UnityEditor/SplitterGUILayout.cs +++ b/UnityEditor/UnityEditor/SplitterGUILayout.cs @@ -166,7 +166,7 @@ public static void BeginSplit(SplitterState state, GUIStyle style, bool vertical for (int j = 0; j < state.relativeSizes.Length - 1; j++) { Rect position = (!gUISplitterGroup.isVertical) ? new Rect(state.xOffset + (float)num4 + (float)state.realSizes[j] - (float)(state.splitSize / 2), gUISplitterGroup.rect.y, (float)state.splitSize, gUISplitterGroup.rect.height) : new Rect(state.xOffset + gUISplitterGroup.rect.x, (float)(num4 + state.realSizes[j] - state.splitSize / 2), gUISplitterGroup.rect.width, (float)state.splitSize); - EditorGUIUtility.AddCursorRect(position, (!gUISplitterGroup.isVertical) ? MouseCursor.SplitResizeLeftRight : MouseCursor.ResizeVertical); + EditorGUIUtility.AddCursorRect(position, (!gUISplitterGroup.isVertical) ? MouseCursor.SplitResizeLeftRight : MouseCursor.ResizeVertical, state.ID); num4 += state.realSizes[j]; } break; diff --git a/UnityEditor/UnityEditor/SpriteEditorWindow.cs b/UnityEditor/UnityEditor/SpriteEditorWindow.cs index 43753ce1..4e142110 100644 --- a/UnityEditor/UnityEditor/SpriteEditorWindow.cs +++ b/UnityEditor/UnityEditor/SpriteEditorWindow.cs @@ -36,21 +36,6 @@ public enum AutoSlicingMethod private SpriteEditorWindow.GizmoMode m_GizmoMode; [SerializeField] private SpriteRect m_Selected; - public readonly GUIContent[] spriteAlignmentOptions = new GUIContent[] - { - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight"), - EditorGUIUtility.TextContent("SpriteInspector.Pivot.Custom") - }; - public static GUIContent s_PivotLabel = EditorGUIUtility.TextContent("Pivot"); - public static GUIContent s_NoSelectionWarning = EditorGUIUtility.TextContent("SpriteEditor.NoTextureOrSpriteSelected"); public Texture2D originalTexture { get @@ -252,10 +237,6 @@ private void RefreshRects() UnityEngine.Object.DestroyImmediate(this.m_RectsCache); } this.m_RectsCache = ScriptableObject.CreateInstance(); - if (this.m_TextureImporter.spriteImportMode == SpriteImportMode.None) - { - return; - } if (this.multipleSprites) { for (int i = 0; i < this.m_TextureImporterSprites.arraySize; i++) @@ -295,7 +276,7 @@ private void OnGUI() if (!this.activeTextureSelected) { EditorGUI.BeginDisabledGroup(true); - GUILayout.Label(SpriteEditorWindow.s_NoSelectionWarning, new GUILayoutOption[0]); + GUILayout.Label(SpriteUtilityWindow.Styles.s_NoSelectionWarning, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); return; } @@ -312,7 +293,6 @@ private void OnGUI() base.DoTextureGUI(); EditorGUILayout.EndHorizontal(); this.DoSelectedFrameInspector(); - this.DoHotkeys(); Handles.matrix = matrix; } protected override void DoTextureGUIExtras() @@ -371,9 +351,12 @@ private void DoToolbarGUI() } } EditorGUI.BeginDisabledGroup(this.selected == null); - if (GUILayout.Button(new GUIContent("Trim", "Trims selected rectangle (T)"), EditorStyles.toolbarButton, new GUILayoutOption[0])) + if (GUILayout.Button(new GUIContent("Trim", "Trims selected rectangle (T)"), EditorStyles.toolbarButton, new GUILayoutOption[0]) || SpriteEditorWindow.k_SpriteEditorTrim.activated) { - this.TrimSelectedSprite(); + Rect rect = this.TrimAlpha(this.selected.m_Rect); + rect = this.ClampSpriteRect(rect); + this.selected.m_Rect = rect; + base.Repaint(); } EditorGUI.EndDisabledGroup(); EditorGUI.EndDisabledGroup(); @@ -389,86 +372,107 @@ private void DoSelectedFrameInspector() GUILayout.BeginArea(this.inspectorRect); GUILayout.BeginVertical(new GUIContent("Sprite"), GUI.skin.window, new GUILayoutOption[0]); EditorGUI.BeginDisabledGroup(!this.multipleSprites); - EditorGUI.BeginChangeCheck(); - string name = this.selected.m_Name; - string text = EditorGUILayout.TextField("Name", name, new GUILayoutOption[0]); - Rect rect = this.selected.m_Rect; - Rect rect2 = EditorGUILayout.RectField("Position", this.FlipNegativeRect(rect), new GUILayoutOption[0]); - EditorGUI.EndDisabledGroup(); - Rect rect3 = GUILayoutUtility.GetRect(322f, 322f, 32f, 32f); - Vector4 vector = this.ClampSpriteBorder(this.selected.m_Border); - Vector4 border = vector; - Rect position = rect3; - position.width = EditorGUIUtility.labelWidth; - position.height = 16f; - GUI.Label(position, "Border"); - Rect position2 = rect3; - position2.width -= EditorGUIUtility.labelWidth; - position2.height = 16f; - position2.x += EditorGUIUtility.labelWidth; - position2.width /= 2f; - position2.width -= 2f; - EditorGUIUtility.labelWidth = 12f; - border.x = (float)EditorGUI.IntField(position2, "L", Mathf.RoundToInt(border.x)); - position2.x += position2.width + 3f; - border.y = (float)EditorGUI.IntField(position2, "B", Mathf.RoundToInt(border.y)); - position2.y += 16f; - position2.x -= position2.width + 3f; - border.z = (float)EditorGUI.IntField(position2, "R", Mathf.RoundToInt(border.z)); - position2.x += position2.width + 3f; - border.w = (float)EditorGUI.IntField(position2, "T", Mathf.RoundToInt(border.w)); - EditorGUIUtility.labelWidth = 135f; - this.selected.m_Alignment = (SpriteAlignment)EditorGUILayout.Popup(SpriteEditorWindow.s_PivotLabel, (int)this.selected.m_Alignment, this.spriteAlignmentOptions, new GUILayoutOption[0]); - Vector2 pivot = this.selected.m_Pivot; - Vector2 customOffset = pivot; - EditorGUI.BeginDisabledGroup(this.selected.m_Alignment != SpriteAlignment.Custom); - position2.x = 5f; - position2.y += 36f; - position2.width = 414f; - customOffset = EditorGUI.Vector2Field(position2, "Custom Pivot", pivot); + this.DoNameField(); + this.DoPositionField(); EditorGUI.EndDisabledGroup(); - if (EditorGUI.EndChangeCheck()) - { - Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Modify sprite"); - if (this.multipleSprites) - { - text = InternalEditorUtility.RemoveInvalidCharsFromFileName(text, true); - if (string.IsNullOrEmpty(this.selected.m_OriginalName) && text != name) - { - this.selected.m_OriginalName = name; - } - if (string.IsNullOrEmpty(text)) - { - text = name; - } - foreach (SpriteRect current in this.m_RectsCache.m_Rects) - { - if (current.m_Name == text) - { - text = this.selected.m_OriginalName; - break; - } - } - this.selected.m_Name = text; - this.selected.m_Rect = this.ClampSpriteRect(rect2); - this.selected.m_Border = this.ClampSpriteBorder(border); - } - this.selected.m_Border = this.ClampSpriteBorder(border); - this.selected.m_Pivot = SpriteEditorUtility.GetPivotValue(this.selected.m_Alignment, customOffset); - this.textureIsDirty = true; - } + Rect fieldLocation; + this.DoBorderFields(out fieldLocation); + this.DoPivotFields(fieldLocation); GUILayout.EndVertical(); GUILayout.EndArea(); EditorGUIUtility.labelWidth = labelWidth; } } - private void DoHotkeys() + private void DoPivotFields(Rect fieldLocation) { - Event current = Event.current; - if (SpriteEditorWindow.k_SpriteEditorTrim.activated && current.type == EventType.KeyDown) + EditorGUI.BeginChangeCheck(); + this.selected.m_Alignment = (SpriteAlignment)EditorGUILayout.Popup(SpriteUtilityWindow.Styles.s_PivotLabel, (int)this.selected.m_Alignment, SpriteUtilityWindow.Styles.spriteAlignmentOptions, new GUILayoutOption[0]); + Vector2 pivot = this.selected.m_Pivot; + EditorGUI.BeginDisabledGroup(this.selected.m_Alignment != SpriteAlignment.Custom); + fieldLocation.x = 5f; + fieldLocation.y += 36f; + fieldLocation.width = 414f; + Vector2 customOffset = EditorGUI.Vector2Field(fieldLocation, "Custom Pivot", pivot); + EditorGUI.EndDisabledGroup(); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Change Sprite Pivot"); + this.textureIsDirty = true; + this.selected.m_Pivot = SpriteEditorUtility.GetPivotValue(this.selected.m_Alignment, customOffset); + } + } + private void DoBorderFields(out Rect fieldLocation) + { + EditorGUI.BeginChangeCheck(); + Rect rect = GUILayoutUtility.GetRect(322f, 322f, 32f, 32f); + Vector4 vector = this.ClampSpriteBorder(this.selected.m_Border); + Vector4 border = vector; + Rect position = rect; + position.width = EditorGUIUtility.labelWidth; + position.height = 16f; + GUI.Label(position, "Border"); + fieldLocation = rect; + fieldLocation.width -= EditorGUIUtility.labelWidth; + fieldLocation.height = 16f; + fieldLocation.x += EditorGUIUtility.labelWidth; + fieldLocation.width /= 2f; + fieldLocation.width -= 2f; + EditorGUIUtility.labelWidth = 12f; + border.x = (float)EditorGUI.IntField(fieldLocation, "L", Mathf.RoundToInt(border.x)); + fieldLocation.x += fieldLocation.width + 3f; + border.w = (float)EditorGUI.IntField(fieldLocation, "T", Mathf.RoundToInt(border.w)); + fieldLocation.y += 16f; + fieldLocation.x -= fieldLocation.width + 3f; + border.z = (float)EditorGUI.IntField(fieldLocation, "R", Mathf.RoundToInt(border.z)); + fieldLocation.x += fieldLocation.width + 3f; + border.y = (float)EditorGUI.IntField(fieldLocation, "B", Mathf.RoundToInt(border.y)); + EditorGUIUtility.labelWidth = 135f; + if (EditorGUI.EndChangeCheck()) { - this.TrimSelectedSprite(); - current.Use(); + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Change Sprite Border"); + this.textureIsDirty = true; + this.selected.m_Border = this.ClampSpriteBorder(border); + } + } + private void DoPositionField() + { + EditorGUI.BeginChangeCheck(); + Rect rect = this.selected.m_Rect; + Rect rect2 = EditorGUILayout.RectField("Position", this.FlipNegativeRect(rect), new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Change Sprite Position"); + this.textureIsDirty = true; + this.selected.m_Rect = this.ClampSpriteRect(rect2); + } + } + private void DoNameField() + { + EditorGUI.BeginChangeCheck(); + string name = this.selected.m_Name; + string text = EditorGUILayout.TextField("Name", name, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Change Sprite Name"); + this.textureIsDirty = true; + text = InternalEditorUtility.RemoveInvalidCharsFromFileName(text, true); + if (string.IsNullOrEmpty(this.selected.m_OriginalName) && text != name) + { + this.selected.m_OriginalName = name; + } + if (string.IsNullOrEmpty(text)) + { + text = name; + } + foreach (SpriteRect current in this.m_RectsCache.m_Rects) + { + if (current.m_Name == text) + { + text = this.selected.m_OriginalName; + break; + } + } + this.selected.m_Name = text; } } private void DoApplyRevertGUI() @@ -494,6 +498,10 @@ private void DoApply() for (int i = 0; i < this.m_RectsCache.Count; i++) { SpriteRect spriteRect = this.m_RectsCache.RectAt(i); + if (string.IsNullOrEmpty(spriteRect.m_Name)) + { + spriteRect.m_Name = "Empty"; + } if (!string.IsNullOrEmpty(spriteRect.m_OriginalName)) { list.Add(spriteRect.m_OriginalName); @@ -556,6 +564,7 @@ private void HandleCreate() { Undo.RegisterCompleteObjectUndo(this.m_RectsCache, "Create sprite"); this.selected = this.AddSprite(rect, 0, this.defaultColliderAlphaCutoff, this.defaultColliderDetail); + GUIUtility.keyboardControl = 0; } } } @@ -630,13 +639,6 @@ private void HandlePivotHandle() } } } - private void TrimSelectedSprite() - { - Rect rect = this.TrimAlpha(this.selected.m_Rect); - rect = this.ClampSpriteRect(rect); - this.selected.m_Rect = rect; - base.Repaint(); - } private Rect ClampSpriteRect(Rect rect) { return SpriteEditorUtility.RoundedRect(new Rect @@ -763,13 +765,13 @@ private Texture2D GetSelectedTexture2D() { if (Selection.activeObject is Sprite) { - texture2D = DataUtility.GetSpriteTexture(Selection.activeObject as Sprite, false); + texture2D = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(Selection.activeObject as Sprite, false); } else { if (Selection.activeGameObject && Selection.activeGameObject.GetComponent() && Selection.activeGameObject.GetComponent().sprite) { - texture2D = DataUtility.GetSpriteTexture(Selection.activeGameObject.GetComponent().sprite, false); + texture2D = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(Selection.activeGameObject.GetComponent().sprite, false); } } } diff --git a/UnityEditor/UnityEditor/SpriteInspector.cs b/UnityEditor/UnityEditor/SpriteInspector.cs index e4d9fffa..6c4d8ad4 100644 --- a/UnityEditor/UnityEditor/SpriteInspector.cs +++ b/UnityEditor/UnityEditor/SpriteInspector.cs @@ -2,7 +2,6 @@ using UnityEditor.Sprites; using UnityEditorInternal; using UnityEngine; -using UnityEngine.Sprites; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(Sprite))] @@ -164,7 +163,7 @@ private static Texture2D BuildPreviewTexture(int width, int height, Sprite sprit } float width2 = sprite.rect.width; float height2 = sprite.rect.height; - Texture2D spriteTexture = UnityEditor.Sprites.DataUtility.GetSpriteTexture(sprite, false); + Texture2D spriteTexture = UnityEditor.Sprites.SpriteUtility.GetSpriteTexture(sprite, false); PreviewHelpers.AdjustWidthAndHeightForStaticPreview((int)width2, (int)height2, ref width, ref height); EditorUtility.SetTemporarilyAllowIndieRenderTexture(true); SavedRenderTargetState savedRenderTargetState = new SavedRenderTargetState(); @@ -202,23 +201,23 @@ private static Texture2D BuildPreviewTexture(int width, int height, Sprite sprit material.mainTexture = spriteTexture; material.SetPass(0); } - Vector4 spriteOuterUV = InternalEditorUtility.GetSpriteOuterUV(sprite, false); - Vector4 padding = UnityEngine.Sprites.DataUtility.GetPadding(sprite); - Rect textureRect = sprite.textureRect; - float width3 = textureRect.width; - float height3 = textureRect.height; + float num = sprite.rect.width / sprite.bounds.size.x; + Vector2[] vertices = sprite.vertices; + Vector2[] uv = sprite.uv; + ushort[] triangles = sprite.triangles; + Vector2 pivot = sprite.pivot; GL.PushMatrix(); GL.LoadOrtho(); - GL.Begin(7); GL.Color(new Color(1f, 1f, 1f, 1f)); - GL.TexCoord(new Vector3(spriteOuterUV.x, spriteOuterUV.w, 0f)); - GL.Vertex3(padding.x / width2, (padding.y + height3) / height2, 0f); - GL.TexCoord(new Vector3(spriteOuterUV.z, spriteOuterUV.w, 0f)); - GL.Vertex3((padding.x + width3) / width2, (padding.y + height3) / height2, 0f); - GL.TexCoord(new Vector3(spriteOuterUV.z, spriteOuterUV.y, 0f)); - GL.Vertex3((padding.x + width3) / width2, padding.y / height2, 0f); - GL.TexCoord(new Vector3(spriteOuterUV.x, spriteOuterUV.y, 0f)); - GL.Vertex3(padding.x / width2, padding.y / height2, 0f); + GL.Begin(4); + for (int i = 0; i < sprite.triangles.Length; i++) + { + ushort num2 = triangles[i]; + Vector2 vector2 = vertices[(int)num2]; + Vector2 vector3 = uv[(int)num2]; + GL.TexCoord(new Vector3(vector3.x, vector3.y, 0f)); + GL.Vertex3((vector2.x * num + pivot.x) / width2, (vector2.y * num + pivot.y) / height2, 0f); + } GL.End(); GL.PopMatrix(); GL.sRGBWrite = false; diff --git a/UnityEditor/UnityEditor/SpriteRendererInspector.cs b/UnityEditor/UnityEditor/SpriteRendererEditor.cs similarity index 69% rename from UnityEditor/UnityEditor/SpriteRendererInspector.cs rename to UnityEditor/UnityEditor/SpriteRendererEditor.cs index 1ee74bbe..56824899 100644 --- a/UnityEditor/UnityEditor/SpriteRendererInspector.cs +++ b/UnityEditor/UnityEditor/SpriteRendererEditor.cs @@ -3,24 +3,19 @@ namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(SpriteRenderer))] - internal class SpriteRendererInspector : Editor + internal class SpriteRendererEditor : RendererEditorBase { private SerializedProperty m_Sprite; private SerializedProperty m_Color; private SerializedProperty m_Material; - private SerializedProperty m_SortingOrder; - private SerializedProperty m_SortingLayerID; private static Texture2D s_WarningIcon; private GUIContent m_MaterialStyle = EditorGUIUtility.TextContent("SpriteRenderer.Material"); - private GUIContent m_SortingLayerStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingLayer"); - private GUIContent m_SortingOrderStyle = EditorGUIUtility.TextContent("SpriteRenderer.SortingOrder"); - public void OnEnable() + public override void OnEnable() { + base.OnEnable(); this.m_Sprite = base.serializedObject.FindProperty("m_Sprite"); this.m_Color = base.serializedObject.FindProperty("m_Color"); this.m_Material = base.serializedObject.FindProperty("m_Materials.Array"); - this.m_SortingOrder = base.serializedObject.FindProperty("m_SortingOrder"); - this.m_SortingLayerID = base.serializedObject.FindProperty("m_SortingLayerID"); EditorUtility.SetSelectedWireframeHidden(this.target as SpriteRenderer, true); } public void OnDisable() @@ -37,9 +32,7 @@ public override void OnInspectorGUI() this.m_Material.InsertArrayElementAtIndex(0); } EditorGUILayout.PropertyField(this.m_Material.GetArrayElementAtIndex(0), this.m_MaterialStyle, true, new GUILayoutOption[0]); - EditorGUILayout.Space(); - EditorGUILayout.SortingLayerField(this.m_SortingLayerStyle, this.m_SortingLayerID, EditorStyles.popup); - EditorGUILayout.PropertyField(this.m_SortingOrder, this.m_SortingOrderStyle, new GUILayoutOption[0]); + base.RenderSortingLayerFields(); this.CheckForErrors(); base.serializedObject.ApplyModifiedProperties(); } @@ -47,22 +40,22 @@ private void CheckForErrors() { if (this.IsMaterialUsingFixedFunction()) { - SpriteRendererInspector.ShowError("Material uses fixed function shader. It is not compatible with SpriteRenderer."); + SpriteRendererEditor.ShowError("Material uses fixed function shader. It is not compatible with SpriteRenderer."); } if (this.IsMaterialTextureAtlasConflict()) { - SpriteRendererInspector.ShowError("Material has CanUseSpriteAtlas=False tag. Sprite texture has atlasHint set. Rendering artifacts possible."); + SpriteRendererEditor.ShowError("Material has CanUseSpriteAtlas=False tag. Sprite texture has atlasHint set. Rendering artifacts possible."); } bool flag; if (!this.DoesMaterialHaveSpriteTexture(out flag)) { - SpriteRendererInspector.ShowError("Material does not have a _MainTex texture property. It is required for SpriteRenderer."); + SpriteRendererEditor.ShowError("Material does not have a _MainTex texture property. It is required for SpriteRenderer."); } else { if (flag) { - SpriteRendererInspector.ShowError("Material texture property _MainTex has offset/scale set. It is incompatible with SpriteRenderer."); + SpriteRendererEditor.ShowError("Material texture property _MainTex has offset/scale set. It is incompatible with SpriteRenderer."); } } } @@ -112,13 +105,13 @@ private bool DoesMaterialHaveSpriteTexture(out bool tiled) } private static void ShowError(string error) { - if (SpriteRendererInspector.s_WarningIcon == null) + if (SpriteRendererEditor.s_WarningIcon == null) { - SpriteRendererInspector.s_WarningIcon = EditorGUIUtility.LoadIcon("console.warnicon"); + SpriteRendererEditor.s_WarningIcon = EditorGUIUtility.LoadIcon("console.warnicon"); } GUIContent content = new GUIContent(error) { - image = SpriteRendererInspector.s_WarningIcon + image = SpriteRendererEditor.s_WarningIcon }; GUILayout.Space(5f); GUILayout.BeginVertical(EditorStyles.helpBox, new GUILayoutOption[0]); diff --git a/UnityEditor/UnityEditor/SpriteUtility.cs b/UnityEditor/UnityEditor/SpriteUtility.cs index 7a03bead..17ddba09 100644 --- a/UnityEditor/UnityEditor/SpriteUtility.cs +++ b/UnityEditor/UnityEditor/SpriteUtility.cs @@ -19,8 +19,8 @@ public static void OnSceneDrag(SceneView sceneView) { return; } - Sprite sprite = spriteFromDraggedPathsOrObjects[0]; - if (sprite == null) + Sprite x = spriteFromDraggedPathsOrObjects[0]; + if (x == null) { return; } @@ -30,7 +30,7 @@ public static void OnSceneDrag(SceneView sceneView) { Vector3 point = HandleUtility.GUIPointToWorldRay(current.mousePosition).GetPoint(10f); point.z = 0f; - GameObject objectToUndo = SpriteUtility.DropFramesToSceneToCreateGO(sprite.name, spriteFromDraggedPathsOrObjects, point); + GameObject objectToUndo = SpriteUtility.DropFramesToSceneToCreateGO(spriteFromDraggedPathsOrObjects, point); Undo.RegisterCreatedObjectUndo(objectToUndo, "Create Sprite"); current.Use(); } @@ -77,7 +77,7 @@ public static Sprite[] GetSpriteFromDraggedPathsOrObjects() { if (@object is Texture2D) { - list.Add(SpriteUtility.TextureToSprite(@object as Texture2D)); + list.AddRange(SpriteUtility.TextureToSprites(@object as Texture2D)); } } } @@ -106,11 +106,7 @@ public static Sprite[] GetSpritesFromDraggedObjects() { if (@object.GetType() == typeof(Texture2D)) { - Sprite sprite = SpriteUtility.TextureToSprite(@object as Texture2D); - if (sprite != null) - { - list.Add(sprite); - } + list.AddRange(SpriteUtility.TextureToSprites(@object as Texture2D)); } } } @@ -150,7 +146,7 @@ public static bool HandleMultipleSpritesDragIntoHierarchy(IHierarchyProperty pro { Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites to empty hierarchy", "null", 1); gameObject = new GameObject(); - gameObject.name = sprites[0].name; + gameObject.name = ((!string.IsNullOrEmpty(sprites[0].name)) ? sprites[0].name : "Sprite"); gameObject.transform.position = SpriteUtility.GetDefaultInstantiatePosition(); } } @@ -194,7 +190,7 @@ public static bool HandleSingleSpriteDragIntoHierarchy(IHierarchyProperty proper if (perform) { Vector3 defaultInstantiatePosition = SpriteUtility.GetDefaultInstantiatePosition(); - GameObject gameObject2 = SpriteUtility.DropSpriteToSceneToCreateGO(sprite.name, sprite, defaultInstantiatePosition); + GameObject gameObject2 = SpriteUtility.DropSpriteToSceneToCreateGO(sprite, defaultInstantiatePosition); if (gameObject != null) { Analytics.Event("Sprite Drag and Drop", "Drop single sprite to existing gameobject", "null", 1); @@ -267,11 +263,13 @@ private static Sprite GenerateDefaultSprite(Texture2D texture) } return @object as Sprite; } - public static GameObject DropFramesToSceneToCreateGO(string name, Sprite[] frames, Vector3 position) + public static GameObject DropFramesToSceneToCreateGO(Sprite[] frames, Vector3 position) { if (frames.Length > 0) { Sprite sprite = frames[0]; + string name = (!string.IsNullOrEmpty(sprite.name)) ? sprite.name : "Sprite"; + name = GameObjectUtility.GetUniqueNameForSibling(null, name); GameObject gameObject = new GameObject(name); SpriteRenderer spriteRenderer = gameObject.AddComponent(); spriteRenderer.sprite = sprite; @@ -294,10 +292,9 @@ public static GameObject DropFramesToSceneToCreateGO(string name, Sprite[] frame } return null; } - public static GameObject DropSpriteToSceneToCreateGO(string name, Sprite sprite, Vector3 position) + public static GameObject DropSpriteToSceneToCreateGO(Sprite sprite, Vector3 position) { - GameObject gameObject = new GameObject(name); - gameObject.name = sprite.name; + GameObject gameObject = new GameObject((!string.IsNullOrEmpty(sprite.name)) ? sprite.name : "Sprite"); SpriteRenderer spriteRenderer = gameObject.AddComponent(); spriteRenderer.sprite = sprite; gameObject.transform.position = position; @@ -323,22 +320,39 @@ public static Sprite RemapObjectToSprite(UnityEngine.Object obj) } return null; } - public static Sprite TextureToSprite(Texture2D tex) + public static Sprite[] TextureToSprites(Texture2D tex) { UnityEngine.Object[] array = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); + List list = new List(); for (int i = 0; i < array.Length; i++) { if (array[i].GetType() == typeof(Sprite)) { - return array[i] as Sprite; + list.Add(array[i] as Sprite); } } - return SpriteUtility.GenerateDefaultSprite(tex); + if (list.Count > 0) + { + return list.ToArray(); + } + return new Sprite[] + { + SpriteUtility.GenerateDefaultSprite(tex) + }; + } + public static Sprite TextureToSprite(Texture2D tex) + { + Sprite[] array = SpriteUtility.TextureToSprites(tex); + if (array.Length > 0) + { + return array[0]; + } + return null; } private static bool ValidPathForTextureAsset(string path) { string a = FileUtil.GetPathExtension(path).ToLower(); - return a == "jpg" || a == "jpeg" || a == "tif" || a == "tiff" || a == "tga" || a == "gif" || a == "png" || a == "psd" || a == "bmp" || a == "iff" || a == "pict" || a == "pic" || a == "pct" || a == "exr"; + return a == "jpg" || a == "jpeg" || a == "tif" || a == "tiff" || a == "tga" || a == "gif" || a == "png" || a == "psd" || a == "bmp" || a == "iff" || a == "pict" || a == "pic" || a == "pct" || a == "exr" || a == "hdr"; } } } diff --git a/UnityEditor/UnityEditor/SpriteUtilityWindow.cs b/UnityEditor/UnityEditor/SpriteUtilityWindow.cs index d375b6cb..716f1a00 100644 --- a/UnityEditor/UnityEditor/SpriteUtilityWindow.cs +++ b/UnityEditor/UnityEditor/SpriteUtilityWindow.cs @@ -27,6 +27,21 @@ protected class Styles public readonly GUIStyle notice; public readonly GUIContent smallMip; public readonly GUIContent largeMip; + public static readonly GUIContent[] spriteAlignmentOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Center"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Top"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.TopRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Left"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Right"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomLeft"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Bottom"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.BottomRight"), + EditorGUIUtility.TextContent("SpriteInspector.Pivot.Custom") + }; + public static GUIContent s_PivotLabel = EditorGUIUtility.TextContent("Pivot"); + public static GUIContent s_NoSelectionWarning = EditorGUIUtility.TextContent("SpriteEditor.NoTextureOrSpriteSelected"); public Styles() { this.toolbar = new GUIStyle(EditorStyles.inspectorBig); diff --git a/UnityEditor/UnityEditor/StandardShaderGUI.cs b/UnityEditor/UnityEditor/StandardShaderGUI.cs new file mode 100644 index 00000000..c8978411 --- /dev/null +++ b/UnityEditor/UnityEditor/StandardShaderGUI.cs @@ -0,0 +1,386 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class StandardShaderGUI : ShaderGUI + { + private enum WorkflowMode + { + Specular, + Metallic, + Dielectric + } + public enum BlendMode + { + Opaque, + Cutout, + Fade, + Transparent + } + private static class Styles + { + public static GUIStyle optionsButton = "PaneOptions"; + public static GUIContent uvSetLabel = new GUIContent("UV Set"); + public static GUIContent[] uvSetOptions = new GUIContent[] + { + new GUIContent("UV channel 0"), + new GUIContent("UV channel 1") + }; + public static string emptyTootip = string.Empty; + public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); + public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); + public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)"); + public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); + public static GUIContent smoothnessText = new GUIContent("Smoothness", string.Empty); + public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); + public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)"); + public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)"); + public static GUIContent emissionText = new GUIContent("Emission", "Emission (RGB)"); + public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)"); + public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); + public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map"); + public static string whiteSpaceString = " "; + public static string primaryMapsText = "Main Maps"; + public static string secondaryMapsText = "Secondary Maps"; + public static string renderingMode = "Rendering Mode"; + public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); + public static GUIContent emissiveColorWarning = new GUIContent("Ensure emissive color is non-black for emission to have effect."); + public static readonly string[] blendNames = Enum.GetNames(typeof(StandardShaderGUI.BlendMode)); + } + private MaterialProperty blendMode; + private MaterialProperty albedoMap; + private MaterialProperty albedoColor; + private MaterialProperty alphaCutoff; + private MaterialProperty specularMap; + private MaterialProperty specularColor; + private MaterialProperty metallicMap; + private MaterialProperty metallic; + private MaterialProperty smoothness; + private MaterialProperty bumpScale; + private MaterialProperty bumpMap; + private MaterialProperty occlusionStrength; + private MaterialProperty occlusionMap; + private MaterialProperty heigtMapScale; + private MaterialProperty heightMap; + private MaterialProperty emissionScaleUI; + private MaterialProperty emissionColorUI; + private MaterialProperty emissionColorForRendering; + private MaterialProperty emissionMap; + private MaterialProperty detailMask; + private MaterialProperty detailAlbedoMap; + private MaterialProperty detailNormalMapScale; + private MaterialProperty detailNormalMap; + private MaterialProperty uvSetSecondary; + private MaterialEditor m_MaterialEditor; + private StandardShaderGUI.WorkflowMode m_WorkflowMode; + private bool m_FirstTimeApply = true; + public void FindProperties(MaterialProperty[] props) + { + this.blendMode = ShaderGUI.FindProperty("_Mode", props); + this.albedoMap = ShaderGUI.FindProperty("_MainTex", props); + this.albedoColor = ShaderGUI.FindProperty("_Color", props); + this.alphaCutoff = ShaderGUI.FindProperty("_Cutoff", props); + this.specularMap = ShaderGUI.FindProperty("_SpecGlossMap", props, false); + this.specularColor = ShaderGUI.FindProperty("_SpecColor", props, false); + this.metallicMap = ShaderGUI.FindProperty("_MetallicGlossMap", props, false); + this.metallic = ShaderGUI.FindProperty("_Metallic", props, false); + if (this.specularMap != null && this.specularColor != null) + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Specular; + } + else + { + if (this.metallicMap != null && this.metallic != null) + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Metallic; + } + else + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Dielectric; + } + } + this.smoothness = ShaderGUI.FindProperty("_Glossiness", props); + this.bumpScale = ShaderGUI.FindProperty("_BumpScale", props); + this.bumpMap = ShaderGUI.FindProperty("_BumpMap", props); + this.heigtMapScale = ShaderGUI.FindProperty("_Parallax", props); + this.heightMap = ShaderGUI.FindProperty("_ParallaxMap", props); + this.occlusionStrength = ShaderGUI.FindProperty("_OcclusionStrength", props); + this.occlusionMap = ShaderGUI.FindProperty("_OcclusionMap", props); + this.emissionScaleUI = ShaderGUI.FindProperty("_EmissionScaleUI", props); + this.emissionColorUI = ShaderGUI.FindProperty("_EmissionColorUI", props); + this.emissionColorForRendering = ShaderGUI.FindProperty("_EmissionColor", props); + this.emissionMap = ShaderGUI.FindProperty("_EmissionMap", props); + this.detailMask = ShaderGUI.FindProperty("_DetailMask", props); + this.detailAlbedoMap = ShaderGUI.FindProperty("_DetailAlbedoMap", props); + this.detailNormalMapScale = ShaderGUI.FindProperty("_DetailNormalMapScale", props); + this.detailNormalMap = ShaderGUI.FindProperty("_DetailNormalMap", props); + this.uvSetSecondary = ShaderGUI.FindProperty("_UVSec", props); + } + public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) + { + this.FindProperties(props); + this.m_MaterialEditor = materialEditor; + Material material = materialEditor.target as Material; + this.ShaderPropertiesGUI(material); + if (this.m_FirstTimeApply) + { + StandardShaderGUI.SetMaterialKeywords(material, this.m_WorkflowMode); + this.m_FirstTimeApply = false; + } + } + public void ShaderPropertiesGUI(Material material) + { + EditorGUIUtility.labelWidth = 0f; + EditorGUI.BeginChangeCheck(); + this.BlendModePopup(); + GUILayout.Label(StandardShaderGUI.Styles.primaryMapsText, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.DoAlbedoArea(material); + this.DoSpecularMetallicArea(); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.normalMapText, this.bumpMap, (!(this.bumpMap.textureValue != null)) ? null : this.bumpScale); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.heightMapText, this.heightMap, (!(this.heightMap.textureValue != null)) ? null : this.heigtMapScale); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.occlusionText, this.occlusionMap, (!(this.occlusionMap.textureValue != null)) ? null : this.occlusionStrength); + this.DoEmissionArea(material); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.detailMaskText, this.detailMask); + EditorGUI.BeginChangeCheck(); + this.m_MaterialEditor.TextureScaleOffsetProperty(this.albedoMap); + if (EditorGUI.EndChangeCheck()) + { + this.emissionMap.textureScaleAndOffset = this.albedoMap.textureScaleAndOffset; + } + EditorGUILayout.Space(); + GUILayout.Label(StandardShaderGUI.Styles.secondaryMapsText, EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.detailAlbedoText, this.detailAlbedoMap); + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.detailNormalMapText, this.detailNormalMap, this.detailNormalMapScale); + this.m_MaterialEditor.TextureScaleOffsetProperty(this.detailAlbedoMap); + this.m_MaterialEditor.ShaderProperty(this.uvSetSecondary, StandardShaderGUI.Styles.uvSetLabel.text); + if (EditorGUI.EndChangeCheck()) + { + UnityEngine.Object[] targets = this.blendMode.targets; + for (int i = 0; i < targets.Length; i++) + { + UnityEngine.Object @object = targets[i]; + StandardShaderGUI.MaterialChanged((Material)@object, this.m_WorkflowMode); + } + } + } + internal void DetermineWorkflow(MaterialProperty[] props) + { + if (ShaderGUI.FindProperty("_SpecGlossMap", props, false) != null && ShaderGUI.FindProperty("_SpecColor", props, false) != null) + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Specular; + } + else + { + if (ShaderGUI.FindProperty("_MetallicGlossMap", props, false) != null && ShaderGUI.FindProperty("_Metallic", props, false) != null) + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Metallic; + } + else + { + this.m_WorkflowMode = StandardShaderGUI.WorkflowMode.Dielectric; + } + } + } + public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) + { + base.AssignNewShaderToMaterial(material, oldShader, newShader); + if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/")) + { + return; + } + StandardShaderGUI.BlendMode blendMode = StandardShaderGUI.BlendMode.Opaque; + if (oldShader.name.Contains("/Transparent/Cutout/")) + { + blendMode = StandardShaderGUI.BlendMode.Cutout; + } + else + { + if (oldShader.name.Contains("/Transparent/")) + { + blendMode = StandardShaderGUI.BlendMode.Fade; + } + } + material.SetFloat("_Mode", (float)blendMode); + this.DetermineWorkflow(ShaderUtil.GetMaterialProperties(new Material[] + { + material + })); + StandardShaderGUI.MaterialChanged(material, this.m_WorkflowMode); + } + private void BlendModePopup() + { + EditorGUI.showMixedValue = this.blendMode.hasMixedValue; + StandardShaderGUI.BlendMode blendMode = (StandardShaderGUI.BlendMode)this.blendMode.floatValue; + EditorGUI.BeginChangeCheck(); + blendMode = (StandardShaderGUI.BlendMode)EditorGUILayout.Popup(StandardShaderGUI.Styles.renderingMode, (int)blendMode, StandardShaderGUI.Styles.blendNames, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + this.m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); + this.blendMode.floatValue = (float)blendMode; + } + EditorGUI.showMixedValue = false; + } + private void DoAlbedoArea(Material material) + { + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.albedoText, this.albedoMap, this.albedoColor); + if ((int)material.GetFloat("_Mode") == 1) + { + this.m_MaterialEditor.ShaderProperty(this.alphaCutoff, StandardShaderGUI.Styles.alphaCutoffText.text, 3); + } + } + private void DoEmissionArea(Material material) + { + bool flag = this.emissionScaleUI.floatValue > 0f; + bool flag2 = this.emissionMap.textureValue != null; + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.emissionText, this.emissionMap, (!flag) ? null : this.emissionColorUI, this.emissionScaleUI); + if (this.emissionMap.textureValue != null && !flag2 && this.emissionScaleUI.floatValue <= 0f) + { + this.emissionScaleUI.floatValue = 1f; + } + if (flag) + { + bool flag3 = StandardShaderGUI.ShouldEmissionBeEnabled(StandardShaderGUI.EvalFinalEmissionColor(material)); + EditorGUI.BeginDisabledGroup(!flag3); + this.m_MaterialEditor.LightmapEmissionProperty(3); + EditorGUI.EndDisabledGroup(); + } + if (!this.HasValidEmissiveKeyword(material)) + { + EditorGUILayout.HelpBox(StandardShaderGUI.Styles.emissiveWarning.text, MessageType.Warning); + } + } + private void DoSpecularMetallicArea() + { + if (this.m_WorkflowMode == StandardShaderGUI.WorkflowMode.Specular) + { + if (this.specularMap.textureValue == null) + { + this.m_MaterialEditor.TexturePropertyTwoLines(StandardShaderGUI.Styles.specularMapText, this.specularMap, this.specularColor, StandardShaderGUI.Styles.smoothnessText, this.smoothness); + } + else + { + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.specularMapText, this.specularMap); + } + } + else + { + if (this.m_WorkflowMode == StandardShaderGUI.WorkflowMode.Metallic) + { + if (this.metallicMap.textureValue == null) + { + this.m_MaterialEditor.TexturePropertyTwoLines(StandardShaderGUI.Styles.metallicMapText, this.metallicMap, this.metallic, StandardShaderGUI.Styles.smoothnessText, this.smoothness); + } + else + { + this.m_MaterialEditor.TexturePropertySingleLine(StandardShaderGUI.Styles.metallicMapText, this.metallicMap); + } + } + } + } + public static void SetupMaterialWithBlendMode(Material material, StandardShaderGUI.BlendMode blendMode) + { + switch (blendMode) + { + case StandardShaderGUI.BlendMode.Opaque: + material.SetInt("_SrcBlend", 1); + material.SetInt("_DstBlend", 0); + material.SetInt("_ZWrite", 1); + material.DisableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = -1; + break; + case StandardShaderGUI.BlendMode.Cutout: + material.SetInt("_SrcBlend", 1); + material.SetInt("_DstBlend", 0); + material.SetInt("_ZWrite", 1); + material.EnableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 2450; + break; + case StandardShaderGUI.BlendMode.Fade: + material.SetInt("_SrcBlend", 5); + material.SetInt("_DstBlend", 10); + material.SetInt("_ZWrite", 0); + material.DisableKeyword("_ALPHATEST_ON"); + material.EnableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 3000; + break; + case StandardShaderGUI.BlendMode.Transparent: + material.SetInt("_SrcBlend", 1); + material.SetInt("_DstBlend", 10); + material.SetInt("_ZWrite", 0); + material.DisableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 3000; + break; + } + } + private static Color EvalFinalEmissionColor(Material material) + { + return material.GetColor("_EmissionColorUI") * material.GetFloat("_EmissionScaleUI"); + } + private static bool ShouldEmissionBeEnabled(Color color) + { + return color.grayscale > 0.000392156857f; + } + private static void SetMaterialKeywords(Material material, StandardShaderGUI.WorkflowMode workflowMode) + { + StandardShaderGUI.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap")); + if (workflowMode == StandardShaderGUI.WorkflowMode.Specular) + { + StandardShaderGUI.SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); + } + else + { + if (workflowMode == StandardShaderGUI.WorkflowMode.Metallic) + { + StandardShaderGUI.SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); + } + } + StandardShaderGUI.SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); + StandardShaderGUI.SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); + bool flag = StandardShaderGUI.ShouldEmissionBeEnabled(material.GetColor("_EmissionColor")); + StandardShaderGUI.SetKeyword(material, "_EMISSION", flag); + MaterialGlobalIlluminationFlags materialGlobalIlluminationFlags = material.globalIlluminationFlags; + if ((materialGlobalIlluminationFlags & (MaterialGlobalIlluminationFlags.RealtimeEmissive | MaterialGlobalIlluminationFlags.BakedEmissive)) != MaterialGlobalIlluminationFlags.None) + { + materialGlobalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; + if (!flag) + { + materialGlobalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack; + } + material.globalIlluminationFlags = materialGlobalIlluminationFlags; + } + } + private bool HasValidEmissiveKeyword(Material material) + { + return material.IsKeywordEnabled("_EMISSION") || !StandardShaderGUI.ShouldEmissionBeEnabled(this.emissionColorForRendering.colorValue); + } + private static void MaterialChanged(Material material, StandardShaderGUI.WorkflowMode workflowMode) + { + if (material.GetFloat("_EmissionScaleUI") < 0f) + { + material.SetFloat("_EmissionScaleUI", 0f); + } + Color color = StandardShaderGUI.EvalFinalEmissionColor(material); + material.SetColor("_EmissionColor", color); + StandardShaderGUI.SetupMaterialWithBlendMode(material, (StandardShaderGUI.BlendMode)material.GetFloat("_Mode")); + StandardShaderGUI.SetMaterialKeywords(material, workflowMode); + } + private static void SetKeyword(Material m, string keyword, bool state) + { + if (state) + { + m.EnableKeyword(keyword); + } + else + { + m.DisableKeyword(keyword); + } + } + } +} diff --git a/UnityEditor/UnityEditor/StaticEditorFlags.cs b/UnityEditor/UnityEditor/StaticEditorFlags.cs index 458d5988..2360e351 100644 --- a/UnityEditor/UnityEditor/StaticEditorFlags.cs +++ b/UnityEditor/UnityEditor/StaticEditorFlags.cs @@ -9,6 +9,7 @@ public enum StaticEditorFlags OccludeeStatic = 16, BatchingStatic = 4, NavigationStatic = 8, - OffMeshLinkGeneration = 32 + OffMeshLinkGeneration = 32, + ReflectionProbeStatic = 64 } } diff --git a/UnityEditor/UnityEditor/SubstanceImporter.cs b/UnityEditor/UnityEditor/SubstanceImporter.cs index 6c37862c..655fc3e3 100644 --- a/UnityEditor/UnityEditor/SubstanceImporter.cs +++ b/UnityEditor/UnityEditor/SubstanceImporter.cs @@ -102,10 +102,10 @@ public void SetGenerateMipMaps(ProceduralMaterial material, bool mode) private extern void SetMaterialInformation(ProceduralMaterial material, ProceduralMaterialInformation information); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string ProceduralOutputTypeToUnityShaderPropertyName(ProceduralOutputType substanceType); + internal static extern bool CanShaderPropertyHostProceduralOutput(string name, ProceduralOutputType substanceType); internal static bool IsProceduralTextureSlot(Material material, Texture tex, string name) { - return material is ProceduralMaterial && tex is ProceduralTexture && SubstanceImporter.ProceduralOutputTypeToUnityShaderPropertyName((tex as ProceduralTexture).GetProceduralOutputType()) == name && SubstanceImporter.IsSubstanceParented(tex as ProceduralTexture, material as ProceduralMaterial); + return material is ProceduralMaterial && tex is ProceduralTexture && SubstanceImporter.CanShaderPropertyHostProceduralOutput(name, (tex as ProceduralTexture).GetProceduralOutputType()) && SubstanceImporter.IsSubstanceParented(tex as ProceduralTexture, material as ProceduralMaterial); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/SubstanceImporterInspector.cs b/UnityEditor/UnityEditor/SubstanceImporterInspector.cs index 6e46daad..b8bf24dc 100644 --- a/UnityEditor/UnityEditor/SubstanceImporterInspector.cs +++ b/UnityEditor/UnityEditor/SubstanceImporterInspector.cs @@ -140,6 +140,15 @@ private Editor GetSelectedMaterialInspector() if (selectedMaterial) { this.m_MaterialInspector = Editor.CreateEditor(selectedMaterial); + if (!(this.m_MaterialInspector is ProceduralMaterialInspector) && this.m_MaterialInspector != null) + { + if (selectedMaterial.shader != null) + { + Debug.LogError("The shader: '" + selectedMaterial.shader.name + "' is using a custom editor deriving from MaterialEditor, please derive from ShaderGUI instead. Only the ShaderGUI approach works with Procedural Materials. Search the docs for 'ShaderGUI'"); + } + UnityEngine.Object.DestroyImmediate(this.m_MaterialInspector); + this.m_MaterialInspector = Editor.CreateEditor(selectedMaterial, typeof(ProceduralMaterialInspector)); + } ProceduralMaterialInspector proceduralMaterialInspector = (ProceduralMaterialInspector)this.m_MaterialInspector; proceduralMaterialInspector.DisableReimportOnDisable(); } @@ -367,20 +376,21 @@ private void Init() gameObject.SetActive(false); foreach (Transform transform in gameObject.transform) { + MeshFilter component = transform.GetComponent(); string name = transform.name; switch (name) { case "sphere": - SubstanceImporterInspector.s_Meshes[0] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + SubstanceImporterInspector.s_Meshes[0] = component.sharedMesh; continue; case "cube": - SubstanceImporterInspector.s_Meshes[1] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + SubstanceImporterInspector.s_Meshes[1] = component.sharedMesh; continue; case "cylinder": - SubstanceImporterInspector.s_Meshes[2] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + SubstanceImporterInspector.s_Meshes[2] = component.sharedMesh; continue; case "torus": - SubstanceImporterInspector.s_Meshes[3] = ((MeshFilter)transform.GetComponent("MeshFilter")).sharedMesh; + SubstanceImporterInspector.s_Meshes[3] = component.sharedMesh; continue; } Debug.Log("Something is wrong, weird object found: " + transform.name); @@ -432,16 +442,16 @@ protected void DoRenderPreview(UnityEngine.Object[] subAssets) Color ambient; if (this.lightMode == 0) { - this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].intensity = 1f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(30f, 30f, 0f); this.m_PreviewUtility.m_Light[1].intensity = 0f; ambient = new Color(0.2f, 0.2f, 0.2f, 0f); } else { - this.m_PreviewUtility.m_Light[0].intensity = 0.5f; + this.m_PreviewUtility.m_Light[0].intensity = 1f; this.m_PreviewUtility.m_Light[0].transform.rotation = Quaternion.Euler(50f, 50f, 0f); - this.m_PreviewUtility.m_Light[1].intensity = 0.5f; + this.m_PreviewUtility.m_Light[1].intensity = 1f; ambient = new Color(0.2f, 0.2f, 0.2f, 0f); } InternalEditorUtility.SetCustomLighting(this.m_PreviewUtility.m_Light, ambient); diff --git a/UnityEditor/UnityEditor/SyncVS.cs b/UnityEditor/UnityEditor/SyncVS.cs index f840b87f..3c5795fc 100644 --- a/UnityEditor/UnityEditor/SyncVS.cs +++ b/UnityEditor/UnityEditor/SyncVS.cs @@ -20,7 +20,7 @@ public override int VisualStudioVersion get { string externalScriptEditor = InternalEditorUtility.GetExternalScriptEditor(); - if (SyncVS.InstalledVisualStudios.ContainsKey(UnityEditor.VisualStudioVersion.VisualStudio2008) && SyncVS.PathsAreEquivalent(SyncVS.InstalledVisualStudios[UnityEditor.VisualStudioVersion.VisualStudio2008], externalScriptEditor)) + if (SyncVS.InstalledVisualStudios.ContainsKey(UnityEditor.VisualStudioVersion.VisualStudio2008) && externalScriptEditor != string.Empty && SyncVS.PathsAreEquivalent(SyncVS.InstalledVisualStudios[UnityEditor.VisualStudioVersion.VisualStudio2008], externalScriptEditor)) { return 9; } @@ -268,14 +268,8 @@ private static bool PathsAreEquivalent(string aPath, string zPath) { return false; } - if (aPath.Length > 0) - { - aPath = Path.GetFullPath(aPath); - } - if (zPath.Length > 0) - { - zPath = Path.GetFullPath(zPath); - } + aPath = Path.GetFullPath(aPath); + zPath = Path.GetFullPath(zPath); StringComparison comparisonType = StringComparison.OrdinalIgnoreCase; if (!SyncVS.SolutionSynchronizationSettings.IsOSX && !SyncVS.SolutionSynchronizationSettings.IsWindows) { diff --git a/UnityEditor/UnityEditor/TagManagerInspector.cs b/UnityEditor/UnityEditor/TagManagerInspector.cs index bd171e25..3db2ce86 100644 --- a/UnityEditor/UnityEditor/TagManagerInspector.cs +++ b/UnityEditor/UnityEditor/TagManagerInspector.cs @@ -8,9 +8,11 @@ internal class TagManagerInspector : Editor { protected SerializedProperty m_Tags; protected SerializedProperty m_SortingLayers; - protected SerializedProperty[] m_Layers; - protected bool m_LayersExpanded = true; + protected SerializedProperty m_Layers; + private ReorderableList m_TagsList; private ReorderableList m_SortLayersList; + private ReorderableList m_LayersList; + protected bool m_IsEditable; public TagManager tagManager { get @@ -28,13 +30,16 @@ internal override string targetTitle public virtual void OnEnable() { this.m_Tags = base.serializedObject.FindProperty("tags"); - this.m_SortingLayers = base.serializedObject.FindProperty("m_SortingLayers"); - this.m_Layers = new SerializedProperty[32]; - for (int i = 0; i < 32; i++) + if (this.m_TagsList == null) { - string propertyPath = ((i < 8) ? "Builtin Layer " : "User Layer ") + i; - this.m_Layers[i] = base.serializedObject.FindProperty(propertyPath); + this.m_TagsList = new ReorderableList(base.serializedObject, this.m_Tags, false, false, true, true); + this.m_TagsList.onAddCallback = new ReorderableList.AddCallbackDelegate(this.AddToTagsList); + this.m_TagsList.onRemoveCallback = new ReorderableList.RemoveCallbackDelegate(this.RemoveFromTagsList); + this.m_TagsList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawTagListElement); + this.m_TagsList.elementHeight = EditorGUIUtility.singleLineHeight + 2f; + this.m_TagsList.headerHeight = 3f; } + this.m_SortingLayers = base.serializedObject.FindProperty("m_SortingLayers"); if (this.m_SortLayersList == null) { this.m_SortLayersList = new ReorderableList(base.serializedObject, this.m_SortingLayers, true, false, true, true); @@ -46,9 +51,17 @@ public virtual void OnEnable() this.m_SortLayersList.elementHeight = EditorGUIUtility.singleLineHeight + 2f; this.m_SortLayersList.headerHeight = 3f; } - this.m_LayersExpanded = false; - this.m_SortingLayers.isExpanded = false; + this.m_Layers = base.serializedObject.FindProperty("layers"); + if (this.m_LayersList == null) + { + this.m_LayersList = new ReorderableList(base.serializedObject, this.m_Layers, false, false, false, false); + this.m_LayersList.drawElementCallback = new ReorderableList.ElementCallbackDelegate(this.DrawLayerListElement); + this.m_LayersList.elementHeight = EditorGUIUtility.singleLineHeight + 2f; + this.m_LayersList.headerHeight = 3f; + } this.m_Tags.isExpanded = false; + this.m_SortingLayers.isExpanded = false; + this.m_Layers.isExpanded = false; string defaultExpandedFoldout = this.tagManager.m_DefaultExpandedFoldout; switch (defaultExpandedFoldout) { @@ -59,10 +72,36 @@ public virtual void OnEnable() this.m_SortingLayers.isExpanded = true; return; case "Layers": - this.m_LayersExpanded = true; + this.m_Layers.isExpanded = true; return; } - this.m_LayersExpanded = true; + this.m_Layers.isExpanded = true; + } + private void AddToTagsList(ReorderableList list) + { + int arraySize = this.m_Tags.arraySize; + this.m_Tags.InsertArrayElementAtIndex(arraySize); + SerializedProperty arrayElementAtIndex = this.m_Tags.GetArrayElementAtIndex(arraySize); + arrayElementAtIndex.stringValue = "New Tag"; + list.index = list.serializedProperty.arraySize - 1; + } + private void RemoveFromTagsList(ReorderableList list) + { + ReorderableList.defaultBehaviours.DoRemoveButton(list); + } + private void DrawTagListElement(Rect rect, int index, bool selected, bool focused) + { + rect.height -= 2f; + rect.xMin -= 20f; + bool enabled = GUI.enabled; + GUI.enabled = this.m_IsEditable; + string stringValue = this.m_Tags.GetArrayElementAtIndex(index).stringValue; + string text = EditorGUI.TextField(rect, " Tag " + index, stringValue); + if (text != stringValue) + { + this.m_Tags.GetArrayElementAtIndex(index).stringValue = text; + } + GUI.enabled = enabled; } private void AddToSortLayerList(ReorderableList list) { @@ -95,10 +134,9 @@ private void DrawSortLayerListElement(Rect rect, int index, bool selected, bool rect.height -= 2f; rect.xMin -= 20f; bool enabled = GUI.enabled; - GUI.enabled = this.CanEditSortLayerEntry(index); + GUI.enabled = (this.m_IsEditable && this.CanEditSortLayerEntry(index)); string sortingLayerName = InternalEditorUtility.GetSortingLayerName(index); - int sortingLayerUserID = InternalEditorUtility.GetSortingLayerUserID(index); - string text = EditorGUI.TextField(rect, " Layer " + sortingLayerUserID, sortingLayerName); + string text = EditorGUI.TextField(rect, " Layer ", sortingLayerName); if (text != sortingLayerName) { base.serializedObject.ApplyModifiedProperties(); @@ -107,10 +145,42 @@ private void DrawSortLayerListElement(Rect rect, int index, bool selected, bool } GUI.enabled = enabled; } + private void DrawLayerListElement(Rect rect, int index, bool selected, bool focused) + { + rect.height -= 2f; + rect.xMin -= 20f; + bool flag = index >= 8; + bool enabled = GUI.enabled; + GUI.enabled = (this.m_IsEditable && flag); + string stringValue = this.m_Layers.GetArrayElementAtIndex(index).stringValue; + string text; + if (flag) + { + text = EditorGUI.TextField(rect, " User Layer " + index, stringValue); + } + else + { + text = EditorGUI.TextField(rect, " Builtin Layer " + index, stringValue); + } + if (text != stringValue) + { + this.m_Layers.GetArrayElementAtIndex(index).stringValue = text; + } + GUI.enabled = enabled; + } public override void OnInspectorGUI() { base.serializedObject.Update(); - EditorGUILayout.PropertyField(this.m_Tags, true, new GUILayoutOption[0]); + this.m_IsEditable = AssetDatabase.IsOpenForEdit("ProjectSettings/TagManager.asset"); + bool enabled = GUI.enabled; + GUI.enabled = this.m_IsEditable; + this.m_Tags.isExpanded = EditorGUILayout.Foldout(this.m_Tags.isExpanded, "Tags"); + if (this.m_Tags.isExpanded) + { + EditorGUI.indentLevel++; + this.m_TagsList.DoLayoutList(); + EditorGUI.indentLevel--; + } this.m_SortingLayers.isExpanded = EditorGUILayout.Foldout(this.m_SortingLayers.isExpanded, "Sorting Layers"); if (this.m_SortingLayers.isExpanded) { @@ -118,16 +188,14 @@ public override void OnInspectorGUI() this.m_SortLayersList.DoLayoutList(); EditorGUI.indentLevel--; } - this.m_LayersExpanded = EditorGUILayout.Foldout(this.m_LayersExpanded, "Layers", EditorStyles.foldout); - if (this.m_LayersExpanded) + this.m_Layers.isExpanded = EditorGUILayout.Foldout(this.m_Layers.isExpanded, "Layers"); + if (this.m_Layers.isExpanded) { EditorGUI.indentLevel++; - for (int i = 0; i < this.m_Layers.Length; i++) - { - EditorGUILayout.PropertyField(this.m_Layers[i], new GUILayoutOption[0]); - } + this.m_LayersList.DoLayoutList(); EditorGUI.indentLevel--; } + GUI.enabled = enabled; base.serializedObject.ApplyModifiedProperties(); } } diff --git a/UnityEditor/UnityEditor/TerrainEditorUtility.cs b/UnityEditor/UnityEditor/TerrainEditorUtility.cs index dbf70f53..4dfc2fff 100644 --- a/UnityEditor/UnityEditor/TerrainEditorUtility.cs +++ b/UnityEditor/UnityEditor/TerrainEditorUtility.cs @@ -1,42 +1,9 @@ using System; -using System.Collections.Generic; using UnityEngine; namespace UnityEditor { internal class TerrainEditorUtility { - private static void Extract(uint staticFlag, ref TerrainData[] datas, ref Vector3[] positions, ref int[] castShadows, ref Material[] materials, ref int[] lightmapSizes, ref int[] lightmapIndices, ref bool[] selection) - { - List list = new List(); - List list2 = new List(); - List list3 = new List(); - List list4 = new List(); - List list5 = new List(); - List list6 = new List(); - List list7 = new List(); - int num = Terrain.activeTerrains.Length; - for (int i = 0; i < num; i++) - { - Terrain terrain = Terrain.activeTerrains[i]; - if (GameObjectUtility.AreStaticEditorFlagsSet(terrain.gameObject, (StaticEditorFlags)staticFlag) && terrain.terrainData) - { - list.Add(terrain.terrainData); - list2.Add(terrain.GetPosition()); - list3.Add((!terrain.castShadows) ? 0 : 1); - list4.Add(terrain.materialTemplate); - list5.Add(terrain.lightmapSize); - list6.Add(terrain.lightmapIndex); - list7.Add(Selection.Contains(terrain.gameObject)); - } - } - datas = list.ToArray(); - positions = list2.ToArray(); - castShadows = list3.ToArray(); - materials = list4.ToArray(); - lightmapSizes = list5.ToArray(); - lightmapIndices = list6.ToArray(); - selection = list7.ToArray(); - } internal static void RemoveSplatTexture(TerrainData terrainData, int index) { Undo.RegisterCompleteObjectUndo(terrainData, "Remove texture"); diff --git a/UnityEditor/UnityEditor/TerrainInspector.cs b/UnityEditor/UnityEditor/TerrainInspector.cs index ec8c9404..fcfe4054 100644 --- a/UnityEditor/UnityEditor/TerrainInspector.cs +++ b/UnityEditor/UnityEditor/TerrainInspector.cs @@ -1,9 +1,11 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Globalization; +using UnityEditor.AnimatedValues; using UnityEditorInternal; using UnityEngine; +using UnityEngine.Events; +using UnityEngine.Rendering; namespace UnityEditor { [CustomEditor(typeof(Terrain))] @@ -47,11 +49,16 @@ private class Styles public GUIContent noTrees = EditorGUIUtility.TextContent("TerrainInspector.Trees.NoTrees"); public GUIContent editTrees = EditorGUIUtility.TextContent("TerrainInspector.Trees.EditTrees"); public GUIContent treeDensity = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeDensity"); - public GUIContent treeColorVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.ColorVar"); public GUIContent treeHeight = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeight"); - public GUIContent treeHeightVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeightVar"); + public GUIContent treeHeightRandomLabel = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeightRandomLabel"); + public GUIContent treeHeightRandomToggle = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeHeightRandomToggle"); + public GUIContent lockWidth = EditorGUIUtility.TextContent("TerrainInspector.Trees.LockWidth"); public GUIContent treeWidth = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidth"); - public GUIContent treeWidthVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidthVar"); + public GUIContent treeWidthRandomLabel = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidthRandomLabel"); + public GUIContent treeWidthRandomToggle = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeWidthRandomToggle"); + public GUIContent treeColorVar = EditorGUIUtility.TextContent("TerrainInspector.Trees.ColorVar"); + public GUIContent treeRotation = EditorGUIUtility.TextContent("TerrainInspector.Trees.TreeRotation"); + public GUIContent massPlaceTrees = EditorGUIUtility.TextContent("TerrainInspector.Trees.MassPlaceTrees"); public GUIContent details = EditorGUIUtility.TextContent("TerrainInspector.Details.Details"); public GUIContent editDetails = EditorGUIUtility.TextContent("TerrainInspector.Details.Edit"); public GUIContent detailTargetStrength = EditorGUIUtility.TextContent("TerrainInspector.Details.TargetStrength"); @@ -59,9 +66,10 @@ private class Styles public GUIContent importRaw = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.ImportRaw"); public GUIContent exportRaw = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.ExportRaw"); public GUIContent flatten = EditorGUIUtility.TextContent("TerrainInspector.Heightmaps.Flatten"); + public GUIContent overrideSmoothness = EditorGUIUtility.TextContent("TerrainInspector.OverrideSmoothness"); + public GUIContent bakeLightProbesForTrees = EditorGUIUtility.TextContent("TerrainInspector.BakeLightProbes"); public GUIContent resolution = EditorGUIUtility.TextContent("TerrainInspector.Resolution"); public GUIContent refresh = EditorGUIUtility.TextContent("TerrainInspector.Refresh"); - public GUIContent massPlaceTrees = EditorGUIUtility.TextContent("TerrainInspector.MassPlaceTrees"); } private const float kHeightmapBrushScale = 0.01f; private const float kMinBrushStrength = 0.00167849252f; @@ -80,6 +88,7 @@ private class Styles internal static PrefKey s_PrevTexture = new PrefKey("Terrain/Previous Detail", "#,"); internal static PrefKey s_NextTexture = new PrefKey("Terrain/Next Detail", "#."); private Terrain m_Terrain; + private Texture2D[] m_SplatIcons; private GUIContent[] m_TreeContents; private GUIContent[] m_DetailContents; private SavedFloat m_TargetHeight = new SavedFloat("TerrainBrushTargetHeight", 0.2f); @@ -94,6 +103,11 @@ private class Styles private int m_SelectedSplat; private int m_SelectedDetail; private static int s_TerrainEditorHash = "TerrainEditor".GetHashCode(); + private List m_BlendInfoList = new List(); + private AnimBool m_ShowBuiltinSpecularSettings = new AnimBool(); + private AnimBool m_ShowBuiltinStandardSettings = new AnimBool(); + private AnimBool m_ShowCustomMaterialSettings = new AnimBool(); + private AnimBool m_ShowReflectionProbesGUI = new AnimBool(); private SavedInt m_SelectedTool = new SavedInt("TerrainSelectedTool", 0); private TerrainTool selectedTool { @@ -234,8 +248,27 @@ private void Initialize() this.LoadBrushIcons(); } } + public void OnEnable() + { + this.m_ShowBuiltinSpecularSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowBuiltinStandardSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowCustomMaterialSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); + this.m_ShowReflectionProbesGUI.valueChanged.AddListener(new UnityAction(base.Repaint)); + Terrain terrain = this.target as Terrain; + if (terrain != null) + { + this.m_ShowBuiltinSpecularSettings.value = (terrain.materialType == Terrain.MaterialType.BuiltInLegacySpecular); + this.m_ShowBuiltinStandardSettings.value = (terrain.materialType == Terrain.MaterialType.BuiltInStandard); + this.m_ShowCustomMaterialSettings.value = (terrain.materialType == Terrain.MaterialType.Custom); + this.m_ShowReflectionProbesGUI.value = (terrain.materialType == Terrain.MaterialType.BuiltInStandard || terrain.materialType == Terrain.MaterialType.Custom); + } + } public void OnDisable() { + this.m_ShowReflectionProbesGUI.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_ShowCustomMaterialSettings.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_ShowBuiltinStandardSettings.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + this.m_ShowBuiltinSpecularSettings.valueChanged.RemoveListener(new UnityAction(base.Repaint)); if (this.m_CachedBrush != null) { this.m_CachedBrush.Dispose(); @@ -322,6 +355,15 @@ public static int AspectSelectionGridImageAndText(int selected, GUIContent[] tex GUILayout.EndVertical(); return result; } + private void LoadSplatIcons() + { + SplatPrototype[] splatPrototypes = this.m_Terrain.terrainData.splatPrototypes; + this.m_SplatIcons = new Texture2D[splatPrototypes.Length]; + for (int i = 0; i < this.m_SplatIcons.Length; i++) + { + this.m_SplatIcons[i] = (AssetPreview.GetAssetPreview(splatPrototypes[i].texture) ?? splatPrototypes[i].texture); + } + } private void LoadTreeIcons() { TreePrototype[] treePrototypes = this.m_Terrain.terrainData.treePrototypes; @@ -412,14 +454,83 @@ public void ShowTrees() TreePainter.spacing = (1.1f - num2) * 3f; } GUILayout.Space(5f); - TreePainter.treeColorAdjustment = EditorGUILayout.Slider(TerrainInspector.styles.treeColorVar, TreePainter.treeColorAdjustment, 0f, 1f, new GUILayoutOption[0]); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(TerrainInspector.styles.treeHeight, new GUILayoutOption[] + { + GUILayout.Width(EditorGUIUtility.labelWidth - 6f) + }); + GUILayout.Label(TerrainInspector.styles.treeHeightRandomLabel, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + TreePainter.allowHeightVar = GUILayout.Toggle(TreePainter.allowHeightVar, TerrainInspector.styles.treeHeightRandomToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + if (TreePainter.allowHeightVar) + { + EditorGUI.BeginChangeCheck(); + float num3 = TreePainter.treeHeight * (1f - TreePainter.treeHeightVariation); + float num4 = TreePainter.treeHeight * (1f + TreePainter.treeHeightVariation); + EditorGUILayout.MinMaxSlider(ref num3, ref num4, 0.01f, 2f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + TreePainter.treeHeight = (num3 + num4) * 0.5f; + TreePainter.treeHeightVariation = (num4 - num3) / (num3 + num4); + } + } + else + { + TreePainter.treeHeight = EditorGUILayout.Slider(TreePainter.treeHeight, 0.01f, 2f, new GUILayoutOption[0]); + TreePainter.treeHeightVariation = 0f; + } + GUILayout.EndHorizontal(); GUILayout.Space(5f); - TreePainter.treeHeight = TerrainInspector.PercentSlider(TerrainInspector.styles.treeHeight, TreePainter.treeHeight, 0.5f, 2f); - TreePainter.treeHeightVariation = TerrainInspector.PercentSlider(TerrainInspector.styles.treeHeightVar, TreePainter.treeHeightVariation, 0f, 0.3f); + TreePainter.lockWidthToHeight = EditorGUILayout.Toggle(TerrainInspector.styles.lockWidth, TreePainter.lockWidthToHeight, new GUILayoutOption[0]); + if (TreePainter.lockWidthToHeight) + { + TreePainter.treeWidth = TreePainter.treeHeight; + TreePainter.treeWidthVariation = TreePainter.treeHeightVariation; + TreePainter.allowWidthVar = TreePainter.allowHeightVar; + } + GUILayout.Space(5f); + EditorGUI.BeginDisabledGroup(TreePainter.lockWidthToHeight); + GUILayout.BeginHorizontal(new GUILayoutOption[0]); + GUILayout.Label(TerrainInspector.styles.treeWidth, new GUILayoutOption[] + { + GUILayout.Width(EditorGUIUtility.labelWidth - 6f) + }); + GUILayout.Label(TerrainInspector.styles.treeWidthRandomLabel, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + TreePainter.allowWidthVar = GUILayout.Toggle(TreePainter.allowWidthVar, TerrainInspector.styles.treeWidthRandomToggle, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }); + if (TreePainter.allowWidthVar) + { + EditorGUI.BeginChangeCheck(); + float num5 = TreePainter.treeWidth * (1f - TreePainter.treeWidthVariation); + float num6 = TreePainter.treeWidth * (1f + TreePainter.treeWidthVariation); + EditorGUILayout.MinMaxSlider(ref num5, ref num6, 0.01f, 2f, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + TreePainter.treeWidth = (num5 + num6) * 0.5f; + TreePainter.treeWidthVariation = (num6 - num5) / (num5 + num6); + } + } + else + { + TreePainter.treeWidth = EditorGUILayout.Slider(TreePainter.treeWidth, 0.01f, 2f, new GUILayoutOption[0]); + TreePainter.treeWidthVariation = 0f; + } + GUILayout.EndHorizontal(); + EditorGUI.EndDisabledGroup(); GUILayout.Space(5f); - TreePainter.treeWidth = TerrainInspector.PercentSlider(TerrainInspector.styles.treeWidth, TreePainter.treeWidth, 0.5f, 2f); - TreePainter.treeWidthVariation = TerrainInspector.PercentSlider(TerrainInspector.styles.treeWidthVar, TreePainter.treeWidthVariation, 0f, 0.3f); + TreePainter.treeColorAdjustment = EditorGUILayout.Slider(TerrainInspector.styles.treeColorVar, TreePainter.treeColorAdjustment, 0f, 1f, new GUILayoutOption[0]); GUILayout.Space(5f); + TreePainter.randomRotation = EditorGUILayout.Toggle(TerrainInspector.styles.treeRotation, TreePainter.randomRotation, new GUILayoutOption[0]); } public void ShowDetails() { @@ -450,29 +561,71 @@ public void ShowSettings() TerrainData terrainData = this.m_Terrain.terrainData; EditorGUI.BeginChangeCheck(); GUILayout.Label("Base Terrain", EditorStyles.boldLabel, new GUILayoutOption[0]); + this.m_Terrain.drawHeightmap = EditorGUILayout.Toggle("Draw", this.m_Terrain.drawHeightmap, new GUILayoutOption[0]); this.m_Terrain.heightmapPixelError = EditorGUILayout.Slider("Pixel Error", this.m_Terrain.heightmapPixelError, 1f, 200f, new GUILayoutOption[0]); this.m_Terrain.basemapDistance = EditorGUILayout.Slider("Base Map Dist.", this.m_Terrain.basemapDistance, 0f, 2000f, new GUILayoutOption[0]); - this.m_Terrain.castShadows = EditorGUILayout.Toggle("Cast shadows", this.m_Terrain.castShadows, new GUILayoutOption[0]); - this.m_Terrain.materialTemplate = (EditorGUILayout.ObjectField("Material", this.m_Terrain.materialTemplate, typeof(Material), false, new GUILayoutOption[0]) as Material); - if (this.m_Terrain.materialTemplate != null) - { - Shader shader = this.m_Terrain.materialTemplate.shader; - if (ShaderUtil.HasTangentChannel(shader)) + this.m_Terrain.castShadows = EditorGUILayout.Toggle("Cast Shadows", this.m_Terrain.castShadows, new GUILayoutOption[0]); + this.m_Terrain.materialType = (Terrain.MaterialType)EditorGUILayout.EnumPopup("Material", this.m_Terrain.materialType, new GUILayoutOption[0]); + if (this.m_Terrain.materialType != Terrain.MaterialType.Custom) + { + this.m_Terrain.materialTemplate = null; + } + this.m_ShowBuiltinSpecularSettings.target = (this.m_Terrain.materialType == Terrain.MaterialType.BuiltInLegacySpecular); + this.m_ShowBuiltinStandardSettings.target = (this.m_Terrain.materialType == Terrain.MaterialType.BuiltInStandard); + this.m_ShowCustomMaterialSettings.target = (this.m_Terrain.materialType == Terrain.MaterialType.Custom); + this.m_ShowReflectionProbesGUI.target = (this.m_Terrain.materialType == Terrain.MaterialType.BuiltInStandard || this.m_Terrain.materialType == Terrain.MaterialType.Custom); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBuiltinSpecularSettings.faded)) + { + EditorGUI.indentLevel++; + this.m_Terrain.legacySpecular = EditorGUILayout.ColorField("Specular Color", this.m_Terrain.legacySpecular, new GUILayoutOption[0]); + this.m_Terrain.legacyShininess = EditorGUILayout.Slider("Shininess", this.m_Terrain.legacyShininess, 0.03f, 1f, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowBuiltinStandardSettings.faded)) + { + EditorGUI.indentLevel++; + this.m_Terrain.useDefaultSmoothness = EditorGUILayout.Toggle(TerrainInspector.styles.overrideSmoothness, this.m_Terrain.useDefaultSmoothness, new GUILayoutOption[0]); + EditorGUI.BeginDisabledGroup(!this.m_Terrain.useDefaultSmoothness); + this.m_Terrain.defaultSmoothness = EditorGUILayout.Slider("Smoothness", this.m_Terrain.defaultSmoothness, 0f, 1f, new GUILayoutOption[0]); + EditorGUI.EndDisabledGroup(); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowCustomMaterialSettings.faded)) + { + EditorGUI.indentLevel++; + this.m_Terrain.materialTemplate = (EditorGUILayout.ObjectField("Custom Material", this.m_Terrain.materialTemplate, typeof(Material), false, new GUILayoutOption[0]) as Material); + if (this.m_Terrain.materialTemplate != null) { - GUIContent gUIContent = EditorGUIUtility.TextContent("TerrainInspector.ShaderWarning"); - EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + Shader shader = this.m_Terrain.materialTemplate.shader; + if (ShaderUtil.HasTangentChannel(shader)) + { + GUIContent gUIContent = EditorGUIUtility.TextContent("TerrainInspector.ShaderWarning"); + EditorGUILayout.HelpBox(gUIContent.text, MessageType.Warning, false); + } } + EditorGUI.indentLevel--; } - EditorGUI.BeginChangeCheck(); - PhysicMaterial physicMaterial = EditorGUILayout.ObjectField("Physics Material", terrainData.physicMaterial, typeof(PhysicMaterial), false, new GUILayoutOption[0]) as PhysicMaterial; - if (EditorGUI.EndChangeCheck()) + EditorGUILayout.EndFadeGroup(); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowReflectionProbesGUI.faded)) { - terrainData.physicMaterial = physicMaterial; + this.m_Terrain.reflectionProbeUsage = (ReflectionProbeUsage)EditorGUILayout.EnumPopup("Reflection Probes", this.m_Terrain.reflectionProbeUsage, new GUILayoutOption[0]); + if (this.m_Terrain.reflectionProbeUsage != ReflectionProbeUsage.Off) + { + EditorGUI.indentLevel++; + this.m_Terrain.GetClosestReflectionProbes(this.m_BlendInfoList); + RendererEditorBase.Probes.ShowClosestReflectionProbes(this.m_BlendInfoList); + EditorGUI.indentLevel--; + } } + EditorGUILayout.EndFadeGroup(); + terrainData.thickness = EditorGUILayout.FloatField("Thickness", terrainData.thickness, new GUILayoutOption[0]); GUILayout.Label("Tree & Detail Objects", EditorStyles.boldLabel, new GUILayoutOption[0]); this.m_Terrain.drawTreesAndFoliage = EditorGUILayout.Toggle("Draw", this.m_Terrain.drawTreesAndFoliage, new GUILayoutOption[0]); - this.m_Terrain.collectDetailPatches = EditorGUILayout.Toggle("Collect Detail Patches", this.m_Terrain.collectDetailPatches, new GUILayoutOption[0]); + this.m_Terrain.bakeLightProbesForTrees = EditorGUILayout.Toggle(TerrainInspector.styles.bakeLightProbesForTrees, this.m_Terrain.bakeLightProbesForTrees, new GUILayoutOption[0]); this.m_Terrain.detailObjectDistance = EditorGUILayout.Slider("Detail Distance", this.m_Terrain.detailObjectDistance, 0f, 250f, new GUILayoutOption[0]); + this.m_Terrain.collectDetailPatches = EditorGUILayout.Toggle("Collect Detail Patches", this.m_Terrain.collectDetailPatches, new GUILayoutOption[0]); this.m_Terrain.detailObjectDensity = EditorGUILayout.Slider("Detail Density", this.m_Terrain.detailObjectDensity, 0f, 1f, new GUILayoutOption[0]); this.m_Terrain.treeDistance = EditorGUILayout.Slider("Tree Distance", this.m_Terrain.treeDistance, 0f, 2000f, new GUILayoutOption[0]); this.m_Terrain.treeBillboardDistance = EditorGUILayout.Slider("Billboard Start", this.m_Terrain.treeBillboardDistance, 5f, 2000f, new GUILayoutOption[0]); @@ -513,17 +666,12 @@ public void ShowSmoothHeight() } public void ShowTextures() { + this.LoadSplatIcons(); this.ShowBrushes(); GUILayout.Label(TerrainInspector.styles.textures, EditorStyles.boldLabel, new GUILayoutOption[0]); - SplatPrototype[] splatPrototypes = this.m_Terrain.terrainData.splatPrototypes; - Texture2D[] array = new Texture2D[splatPrototypes.Length]; - for (int i = 0; i < splatPrototypes.Length; i++) - { - array[i] = splatPrototypes[i].texture; - } GUI.changed = false; bool flag; - this.m_SelectedSplat = TerrainInspector.AspectSelectionGrid(this.m_SelectedSplat, array, 64, TerrainInspector.styles.gridList, "No terrain textures defined.", out flag); + this.m_SelectedSplat = TerrainInspector.AspectSelectionGrid(this.m_SelectedSplat, this.m_SplatIcons, 64, TerrainInspector.styles.gridList, "No terrain textures defined.", out flag); if (flag) { TerrainSplatContextMenus.EditSplat(new MenuCommand(this.m_Terrain, this.m_SelectedSplat)); @@ -570,31 +718,43 @@ public void ShowResolution() int num7 = this.m_Terrain.terrainData.alphamapResolution; int num8 = this.m_Terrain.terrainData.baseMapResolution; EditorGUI.BeginChangeCheck(); - num = this.DelayedFloatField("Terrain Width", num); + num = EditorGUI.DelayedFloatField(EditorGUIUtility.TempContent("Terrain Width"), num); if (num <= 0f) { num = 1f; } - num3 = this.DelayedFloatField("Terrain Length", num3); + if (num > 100000f) + { + num = 100000f; + } + num3 = EditorGUI.DelayedFloatField(EditorGUIUtility.TempContent("Terrain Length"), num3); if (num3 <= 0f) { num3 = 1f; } - num2 = this.DelayedFloatField("Terrain Height", num2); + if (num3 > 100000f) + { + num3 = 100000f; + } + num2 = EditorGUI.DelayedFloatField(EditorGUIUtility.TempContent("Terrain Height"), num2); if (num2 <= 0f) { num2 = 1f; } - num4 = this.DelayedIntField("Heightmap Resolution", num4); + if (num2 > 10000f) + { + num2 = 10000f; + } + num4 = EditorGUI.DelayedIntField(EditorGUIUtility.TempContent("Heightmap Resolution"), num4); num4 = Mathf.Clamp(num4, 33, 4097); num4 = this.m_Terrain.terrainData.GetAdjustedSize(num4); - num5 = this.DelayedIntField("Detail Resolution", num5); + num5 = EditorGUI.DelayedIntField(EditorGUIUtility.TempContent("Detail Resolution"), num5); num5 = Mathf.Clamp(num5, 0, 4048); - num6 = this.DelayedIntField("Detail Resolution Per Patch", num6); + num6 = EditorGUI.DelayedIntField(EditorGUIUtility.TempContent("Detail Resolution Per Patch"), num6); num6 = Mathf.Clamp(num6, 8, 128); - num7 = this.DelayedIntField("Control Texture Resolution", num7); + num7 = EditorGUI.DelayedIntField(EditorGUIUtility.TempContent("Control Texture Resolution"), num7); num7 = Mathf.Clamp(Mathf.ClosestPowerOfTwo(num7), 16, 2048); - num8 = this.DelayedIntField("Base Texture Resolution", num8); + num8 = EditorGUI.DelayedIntField(EditorGUIUtility.TempContent("Base Texture Resolution"), num8); num8 = Mathf.Clamp(Mathf.ClosestPowerOfTwo(num8), 16, 2048); if (EditorGUI.EndChangeCheck()) { @@ -643,36 +803,6 @@ private void ResizeDetailResolution(TerrainData terrainData, int resolution, int terrainData.SetDetailResolution(resolution, resolutionPerPatch); } } - internal float DelayedFloatField(string label, float value) - { - float num = value; - float num2 = num; - Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); - rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TempContent(label)); - EditorGUI.BeginChangeCheck(); - string s = EditorGUI.DelayedTextField(rect, num.ToString(), "inftynaeINFTYNAE0123456789.,-", EditorStyles.numberField); - if (EditorGUI.EndChangeCheck() && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out num2) && num2 != num) - { - value = num2; - GUI.changed = true; - } - return num2; - } - internal int DelayedIntField(string label, int value) - { - int num = value; - int num2 = num; - Rect rect = EditorGUILayout.GetControlRect(new GUILayoutOption[0]); - rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TempContent(label)); - EditorGUI.BeginChangeCheck(); - string s = EditorGUI.DelayedTextField(rect, num.ToString(), "0123456789-", EditorStyles.numberField); - if (EditorGUI.EndChangeCheck() && int.TryParse(s, out num2) && num2 != num) - { - value = num2; - GUI.changed = true; - } - return num2; - } public void ShowRefreshPrototypes() { if (GUILayout.Button(TerrainInspector.styles.refresh, new GUILayoutOption[0])) @@ -814,7 +944,7 @@ public bool Raycast(out Vector2 uv, out Vector3 pos) { Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit raycastHit; - if (this.m_Terrain.collider.Raycast(ray, out raycastHit, float.PositiveInfinity)) + if (this.m_Terrain.GetComponent().Raycast(ray, out raycastHit, float.PositiveInfinity)) { uv = raycastHit.textureCoord; pos = raycastHit.point; @@ -1030,14 +1160,13 @@ public void OnSceneGUI() { Undo.RegisterCompleteObjectUndo(this.m_Terrain.terrainData, "Place Tree"); } - TreePainter.terrain = this.m_Terrain; if (!Event.current.shift && !Event.current.control) { - TreePainter.PlaceTrees(vector.x, vector.y); + TreePainter.PlaceTrees(this.m_Terrain, vector.x, vector.y); } else { - TreePainter.RemoveTrees(vector.x, vector.y, Event.current.control); + TreePainter.RemoveTrees(this.m_Terrain, vector.x, vector.y, Event.current.control); } } else diff --git a/UnityEditor/UnityEditor/TerrainInspectorUtil.cs b/UnityEditor/UnityEditor/TerrainInspectorUtil.cs index 7568249f..c98a2125 100644 --- a/UnityEditor/UnityEditor/TerrainInspectorUtil.cs +++ b/UnityEditor/UnityEditor/TerrainInspectorUtil.cs @@ -23,7 +23,7 @@ public static bool CheckTreeDistance(TerrainData terrainData, Vector3 position, public static extern int GetPrototypeCount(TerrainData terrainData); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool PrototypeHasMaterials(TerrainData terrainData, int prototypeIndex); + public static extern bool PrototypeIsRenderable(TerrainData terrainData, int prototypeIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RefreshPhysicsInEditMode(); diff --git a/UnityEditor/UnityEditor/TerrainMenus.cs b/UnityEditor/UnityEditor/TerrainMenus.cs index 47f12889..476b52ab 100644 --- a/UnityEditor/UnityEditor/TerrainMenus.cs +++ b/UnityEditor/UnityEditor/TerrainMenus.cs @@ -8,8 +8,8 @@ internal class TerrainMenus private static void CreateTerrain(MenuCommand menuCommand) { TerrainData terrainData = new TerrainData(); - terrainData.heightmapResolution = 513; - terrainData.size = new Vector3(2000f, 600f, 2000f); + terrainData.heightmapResolution = 1025; + terrainData.size = new Vector3(1000f, 600f, 1000f); terrainData.heightmapResolution = 512; terrainData.baseMapResolution = 1024; terrainData.SetDetailResolution(1024, terrainData.detailResolutionPerPatch); diff --git a/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs b/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs index 5d031bde..36419a67 100644 --- a/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs +++ b/UnityEditor/UnityEditor/TerrainSplatContextMenus.cs @@ -12,7 +12,24 @@ internal static void AddSplat(MenuCommand item) [MenuItem("CONTEXT/TerrainEngineSplats/Edit Texture...")] internal static void EditSplat(MenuCommand item) { - TerrainSplatEditor.ShowTerrainSplatEditor("Edit Terrain Texture", "Apply", (Terrain)item.context, item.userData); + Terrain terrain = (Terrain)item.context; + string text = "Edit Terrain Texture"; + switch (terrain.materialType) + { + case Terrain.MaterialType.BuiltInStandard: + text += " (Standard)"; + break; + case Terrain.MaterialType.BuiltInLegacyDiffuse: + text += " (Diffuse)"; + break; + case Terrain.MaterialType.BuiltInLegacySpecular: + text += " (Specular)"; + break; + case Terrain.MaterialType.Custom: + text += " (Custom)"; + break; + } + TerrainSplatEditor.ShowTerrainSplatEditor(text, "Apply", (Terrain)item.context, item.userData); } [MenuItem("CONTEXT/TerrainEngineSplats/Edit Texture...", true)] internal static bool EditSplatCheck(MenuCommand item) diff --git a/UnityEditor/UnityEditor/TerrainSplatEditor.cs b/UnityEditor/UnityEditor/TerrainSplatEditor.cs index ee7bf1c8..d23c19c4 100644 --- a/UnityEditor/UnityEditor/TerrainSplatEditor.cs +++ b/UnityEditor/UnityEditor/TerrainSplatEditor.cs @@ -12,6 +12,8 @@ internal class TerrainSplatEditor : EditorWindow public Texture2D m_NormalMap; private Vector2 m_TileSize; private Vector2 m_TileOffset; + private Color m_Specular; + private float m_Metallic; public TerrainSplatEditor() { base.position = new Rect(50f, 50f, 200f, 300f); @@ -40,6 +42,8 @@ private void InitializeData(Terrain terrain, int index) this.m_NormalMap = splatPrototype.normalMap; this.m_TileSize = splatPrototype.tileSize; this.m_TileOffset = splatPrototype.tileOffset; + this.m_Specular = splatPrototype.specular; + this.m_Metallic = splatPrototype.metallic; } private void ApplyTerrainSplat() { @@ -60,6 +64,8 @@ private void ApplyTerrainSplat() array[this.m_Index].normalMap = this.m_NormalMap; array[this.m_Index].tileSize = this.m_TileSize; array[this.m_Index].tileOffset = this.m_TileOffset; + array[this.m_Index].specular = this.m_Specular; + array[this.m_Index].metallic = this.m_Metallic; this.m_Terrain.terrainData.splatPrototypes = array; EditorUtility.SetDirty(this.m_Terrain); } @@ -91,14 +97,7 @@ private bool ValidateMainTexture(Texture2D tex) } return true; } - private void ShowNormalMapShaderWarning() - { - if (this.m_NormalMap != null && this.m_Terrain != null && (this.m_Terrain.materialTemplate == null || !this.m_Terrain.materialTemplate.HasProperty("_Normal0"))) - { - EditorGUILayout.HelpBox("Note: in order for normal map to have effect, a custom material with normal mapped terrain shader needs to be used.", MessageType.Info); - } - } - private static void TextureFieldGUI(string label, ref Texture2D texture) + private static void TextureFieldGUI(string label, ref Texture2D texture, float alignmentOffset) { GUILayout.Space(6f); GUILayout.BeginVertical(new GUILayoutOption[] @@ -111,6 +110,7 @@ private static void TextureFieldGUI(string label, ref Texture2D texture) { GUILayout.MaxWidth(64f) }); + rect.x += alignmentOffset; texture = (EditorGUI.DoObjectField(rect, rect, GUIUtility.GetControlID(12354, EditorGUIUtility.native, rect), texture, typeFromHandle, null, null, false) as Texture2D); GUILayout.EndVertical(); } @@ -158,6 +158,14 @@ private static void SplatSizeGUI(ref Vector2 scale, ref Vector2 offset) GUILayout.EndVertical(); GUILayout.EndHorizontal(); } + private static bool IsUsingMetallic(Terrain.MaterialType materialType, Material materialTemplate) + { + return materialType == Terrain.MaterialType.BuiltInStandard || (materialType == Terrain.MaterialType.Custom && materialTemplate != null && materialTemplate.HasProperty("_Metallic0")); + } + private static bool IsUsingSpecular(Terrain.MaterialType materialType, Material materialTemplate) + { + return materialType == Terrain.MaterialType.BuiltInStandard || (materialType == Terrain.MaterialType.Custom && materialTemplate != null && materialTemplate.HasProperty("_Specular0")); + } private void OnGUI() { EditorGUIUtility.labelWidth = (float)Screen.width - 64f - 20f; @@ -166,12 +174,57 @@ private void OnGUI() flag &= this.ValidateTerrain(); EditorGUI.BeginChangeCheck(); GUILayout.BeginHorizontal(new GUILayoutOption[0]); - TerrainSplatEditor.TextureFieldGUI("Texture", ref this.m_Texture); - TerrainSplatEditor.TextureFieldGUI("Normal Map", ref this.m_NormalMap); + string label = string.Empty; + float alignmentOffset = 0f; + switch (this.m_Terrain.materialType) + { + case Terrain.MaterialType.BuiltInStandard: + if (this.m_Terrain.useDefaultSmoothness) + { + label = "\n Albedo (RGB)"; + } + else + { + label = " Albedo (RGB)\nSmoothness (A)"; + } + alignmentOffset = 15f; + break; + case Terrain.MaterialType.BuiltInLegacyDiffuse: + label = "\n Diffuse (RGB)"; + alignmentOffset = 15f; + break; + case Terrain.MaterialType.BuiltInLegacySpecular: + label = "Diffuse (RGB)\n Gloss (A)"; + alignmentOffset = 12f; + break; + case Terrain.MaterialType.Custom: + label = " \n Splat"; + alignmentOffset = 0f; + break; + } + TerrainSplatEditor.TextureFieldGUI(label, ref this.m_Texture, alignmentOffset); + TerrainSplatEditor.TextureFieldGUI("\nNormal", ref this.m_NormalMap, -4f); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); flag &= this.ValidateMainTexture(this.m_Texture); - this.ShowNormalMapShaderWarning(); + if (flag) + { + if (TerrainSplatEditor.IsUsingMetallic(this.m_Terrain.materialType, this.m_Terrain.materialTemplate)) + { + EditorGUILayout.Space(); + float labelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 60f; + this.m_Metallic = EditorGUILayout.Slider("Metallic", this.m_Metallic, 0f, 1f, new GUILayoutOption[0]); + EditorGUIUtility.labelWidth = labelWidth; + } + else + { + if (TerrainSplatEditor.IsUsingSpecular(this.m_Terrain.materialType, this.m_Terrain.materialTemplate)) + { + this.m_Specular = EditorGUILayout.ColorField("Specular", this.m_Specular, new GUILayoutOption[0]); + } + } + } TerrainSplatEditor.SplatSizeGUI(ref this.m_TileSize, ref this.m_TileOffset); bool flag2 = EditorGUI.EndChangeCheck(); EditorGUILayout.EndScrollView(); diff --git a/UnityEditor/UnityEditor/TextAssetInspector.cs b/UnityEditor/UnityEditor/TextAssetInspector.cs index 437dd6bf..b6ba5159 100644 --- a/UnityEditor/UnityEditor/TextAssetInspector.cs +++ b/UnityEditor/UnityEditor/TextAssetInspector.cs @@ -6,6 +6,7 @@ namespace UnityEditor internal class TextAssetInspector : Editor { private const int kMaxChars = 7000; + [NonSerialized] private GUIStyle m_TextStyle; public override void OnInspectorGUI() { diff --git a/UnityEditor/UnityEditor/Texture3DInspector.cs b/UnityEditor/UnityEditor/Texture3DInspector.cs index 8498ea9b..a68986bb 100644 --- a/UnityEditor/UnityEditor/Texture3DInspector.cs +++ b/UnityEditor/UnityEditor/Texture3DInspector.cs @@ -8,7 +8,7 @@ internal class Texture3DInspector : TextureInspector private PreviewRenderUtility m_PreviewUtility; private Material m_Material; private Mesh m_Mesh; - public Vector2 previewDir = new Vector2(0f, 0f); + public Vector2 m_PreviewDir = new Vector2(0f, 0f); public override void OnInspectorGUI() { base.OnInspectorGUI(); @@ -25,19 +25,14 @@ public override string GetInfoString() EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySize(texture3D)) }); } - public void OnDisable() + protected override void OnDisable() { + base.OnDisable(); if (this.m_PreviewUtility != null) { this.m_PreviewUtility.Cleanup(); this.m_PreviewUtility = null; } - if (this.m_Material) - { - UnityEngine.Object.DestroyImmediate(this.m_Material.shader, true); - UnityEngine.Object.DestroyImmediate(this.m_Material, true); - this.m_Material = null; - } } public override void OnPreviewSettings() { @@ -57,7 +52,7 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) } return; } - this.previewDir = PreviewGUI.Drag2D(this.previewDir, r); + this.m_PreviewDir = PreviewGUI.Drag2D(this.m_PreviewDir, r); if (Event.current.type != EventType.Repaint) { return; @@ -69,7 +64,7 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) Unsupported.SetRenderSettingsUseFogNoDirty(false); this.m_PreviewUtility.m_Camera.transform.position = -Vector3.forward * 3f; this.m_PreviewUtility.m_Camera.transform.rotation = Quaternion.identity; - Quaternion rot = Quaternion.Euler(this.previewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.previewDir.x, 0f); + Quaternion rot = Quaternion.Euler(this.m_PreviewDir.y, 0f, 0f) * Quaternion.Euler(0f, this.m_PreviewDir.x, 0f); this.m_PreviewUtility.DrawMesh(this.m_Mesh, Vector3.zero, rot, this.m_Material, 0); this.m_PreviewUtility.m_Camera.Render(); Unsupported.SetRenderSettingsUseFogNoDirty(fog); @@ -82,22 +77,14 @@ private void InitPreview() { this.m_PreviewUtility = new PreviewRenderUtility(); this.m_PreviewUtility.m_CameraFieldOfView = 30f; - this.m_Material = new Material("Shader \"Hidden/3DTextureInspector\" {\n Properties {\n\t _MainTex (\"\", 3D) = \"\" { TexGen ObjectLinear }\n }\n SubShader {\n Tags { \"ForceSupported\" = \"True\" } \n\t Pass { SetTexture[_MainTex] { combine texture } }\n }\n Fallback Off\n }"); - this.m_Material.hideFlags = HideFlags.HideAndDontSave; - this.m_Material.shader.hideFlags = HideFlags.HideAndDontSave; - this.m_Material.mainTexture = (this.target as Texture); } if (this.m_Mesh == null) { - GameObject gameObject = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx"); - gameObject.SetActive(false); - foreach (Transform transform in gameObject.transform) - { - if (transform.name == "sphere") - { - this.m_Mesh = transform.GetComponent().sharedMesh; - } - } + this.m_Mesh = PreviewRenderUtility.GetPreviewSphere(); + } + if (this.m_Material == null) + { + this.m_Material = (EditorGUIUtility.LoadRequired("Previews/Preview3DTextureMaterial.mat") as Material); } } } diff --git a/UnityEditor/UnityEditor/TextureImportInstructions.cs b/UnityEditor/UnityEditor/TextureImportInstructions.cs deleted file mode 100644 index 73b9d453..00000000 --- a/UnityEditor/UnityEditor/TextureImportInstructions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using UnityEngine; -namespace UnityEditor -{ - [Serializable] - public sealed class TextureImportInstructions - { - [SerializeField] - public TextureFormat compressedFormat; - [SerializeField] - public TextureFormat uncompressedFormat; - [SerializeField] - public TextureFormat recommendedFormat; - [SerializeField] - public TextureFormat desiredFormat; - [SerializeField] - public TextureUsageMode usageMode; - [SerializeField] - public ColorSpace colorSpace; - [SerializeField] - public int width; - [SerializeField] - public int height; - [SerializeField] - public int compressionQuality; - } -} diff --git a/UnityEditor/UnityEditor/TextureImporter.cs b/UnityEditor/UnityEditor/TextureImporter.cs index da3ffed4..2af16aa3 100644 --- a/UnityEditor/UnityEditor/TextureImporter.cs +++ b/UnityEditor/UnityEditor/TextureImporter.cs @@ -350,7 +350,7 @@ public void SetPlatformTextureSettings(string platform, int maxTextureSize, Text internal static extern TextureImporterFormat FullToSimpleTextureFormat(TextureImporterFormat format); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern TextureImporterFormat SimpleToFullTextureFormat2(TextureImporterFormat simpleFormat, TextureImporterType tType, TextureImporterSettings settings, bool doesTextureContainAlpha, bool doesTextureContainColor, BuildTarget destinationPlatform); + internal static extern TextureImporterFormat SimpleToFullTextureFormat2(TextureImporterFormat simpleFormat, TextureImporterType tType, TextureImporterSettings settings, bool doesTextureContainAlpha, bool sourceWasHDR, BuildTarget destinationPlatform); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_spritePivot(out Vector2 value); @@ -368,9 +368,12 @@ public void SetPlatformTextureSettings(string platform, int maxTextureSize, Text internal extern void GetWidthAndHeight(ref int width, ref int height); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern bool DoesSourceTextureHaveAlpha(); + internal extern bool IsSourceTextureHDR(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool DoesSourceTextureHaveAlpha(); + [Obsolete("DoesSourceTextureHaveColor always returns true in Unity."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public extern bool DoesSourceTextureHaveColor(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -383,6 +386,6 @@ public void SetPlatformTextureSettings(string platform, int maxTextureSize, Text internal extern string GetImportWarnings(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void ReadTextureImportInstructions(TextureImportInstructions dest, BuildTarget target); + public extern void ReadTextureImportInstructions(BuildTarget target, out TextureFormat desiredFormat, out ColorSpace colorSpace, out int compressionQuality); } } diff --git a/UnityEditor/UnityEditor/TextureImporterCubemapConvolution.cs b/UnityEditor/UnityEditor/TextureImporterCubemapConvolution.cs new file mode 100644 index 00000000..56374486 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterCubemapConvolution.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterCubemapConvolution + { + None, + Specular, + Diffuse + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterFormat.cs b/UnityEditor/UnityEditor/TextureImporterFormat.cs index 08c2d6b9..fda3d041 100644 --- a/UnityEditor/UnityEditor/TextureImporterFormat.cs +++ b/UnityEditor/UnityEditor/TextureImporterFormat.cs @@ -22,10 +22,7 @@ public enum TextureImporterFormat ETC_RGB4, ATC_RGB4, ATC_RGBA8, - ATF_RGB_DXT1 = 38, - ATF_RGBA_JPG, - ATF_RGB_JPG, - EAC_R, + EAC_R = 41, EAC_R_SIGNED, EAC_RG, EAC_RG_SIGNED, diff --git a/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs b/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs index 23ee97a6..7d3495c3 100644 --- a/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs +++ b/UnityEditor/UnityEditor/TextureImporterGenerateCubemap.cs @@ -8,6 +8,7 @@ public enum TextureImporterGenerateCubemap Cylindrical, SimpleSpheremap, NiceSpheremap, - FullCubemap + FullCubemap, + AutoCubemap } } diff --git a/UnityEditor/UnityEditor/TextureImporterInspector.cs b/UnityEditor/UnityEditor/TextureImporterInspector.cs index d426715f..0437ae15 100644 --- a/UnityEditor/UnityEditor/TextureImporterInspector.cs +++ b/UnityEditor/UnityEditor/TextureImporterInspector.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; @@ -188,21 +187,18 @@ public void SetOverriddenForAll(bool overridden) } public void SetMaxTextureSizeForAll(int maxTextureSize) { - Assert.IsTrue(this.allAreOverridden, "Attempting to set max texture size for all platforms even though settings are not overwritten for all platforms."); this.m_MaxTextureSize = maxTextureSize; this.m_MaxTextureSizeIsDifferent = false; this.m_HasChanged = true; } public void SetCompressionQualityForAll(int quality) { - Assert.IsTrue(this.allAreOverridden, "Attempting to set texture compression quality for all platforms even though settings are not overwritten for all platforms."); this.m_CompressionQuality = quality; this.m_CompressionQualityIsDifferent = false; this.m_HasChanged = true; } public void SetTextureFormatForAll(TextureImporterFormat format) { - Assert.IsTrue(this.allAreOverridden, "Attempting to set texture format for all platforms even though settings are not overwritten for all platforms."); for (int i = 0; i < this.m_TextureFormatArray.Length; i++) { this.m_TextureFormatArray[i] = format; @@ -217,39 +213,39 @@ public bool SupportsFormat(TextureImporterFormat format, TextureImporter importe int[] array; switch (target) { - case BuildTarget.Android: - array = TextureImporterInspector.kTextureFormatsValueAndroid; - goto IL_D9; - case BuildTarget.StandaloneGLESEmu: - array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueGLESEmu : TextureImporterInspector.kNormalFormatsValueWeb); - goto IL_D9; - case (BuildTarget)15: - case BuildTarget.NaCl: - case BuildTarget.StandaloneLinux: + case BuildTarget.iOS: + array = TextureImporterInspector.kTextureFormatsValueiPhone; + goto IL_C4; + case BuildTarget.PS3: + case BuildTarget.XBOX360: + case (BuildTarget)12: IL_30: if (target == BuildTarget.BB10) { array = TextureImporterInspector.kTextureFormatsValueBB10; - goto IL_D9; + goto IL_C4; } if (target == BuildTarget.Tizen) { array = TextureImporterInspector.kTextureFormatsValueTizen; - goto IL_D9; + goto IL_C4; } - if (target != BuildTarget.iPhone) + if (target != BuildTarget.SamsungTV) { array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueWeb : TextureImporterInspector.kNormalFormatsValueWeb); - goto IL_D9; + goto IL_C4; } - array = TextureImporterInspector.kTextureFormatsValueiPhone; - goto IL_D9; - case BuildTarget.FlashPlayer: - array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueFlash : TextureImporterInspector.kNormalFormatsValueFlash); - goto IL_D9; + array = TextureImporterInspector.kTextureFormatsValueSTV; + goto IL_C4; + case BuildTarget.Android: + array = TextureImporterInspector.kTextureFormatsValueAndroid; + goto IL_C4; + case BuildTarget.StandaloneGLESEmu: + array = ((!settings.normalMap) ? TextureImporterInspector.kTextureFormatsValueGLESEmu : TextureImporterInspector.kNormalFormatsValueWeb); + goto IL_C4; } goto IL_30; - IL_D9: + IL_C4: return ((IList)array).Contains((int)format); } public TextureImporterSettings GetSettings(TextureImporter importer) @@ -291,7 +287,7 @@ public void Sync() } if (this.m_TextureFormatArray[i] < (TextureImporterFormat)0) { - this.m_TextureFormatArray[i] = TextureImporter.SimpleToFullTextureFormat2(this.m_TextureFormatArray[i], textureType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.DoesSourceTextureHaveColor(), this.m_Target); + this.m_TextureFormatArray[i] = TextureImporter.SimpleToFullTextureFormat2(this.m_TextureFormatArray[i], textureType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.IsSourceTextureHDR(), this.m_Target); } goto IL_14A; } @@ -405,7 +401,7 @@ private class Styles EditorGUIUtility.TextContent("TextureImporter.TextureType.GUI"), EditorGUIUtility.TextContent("TextureImporter.TextureType.Sprite"), EditorGUIUtility.TextContent("TextureImporter.TextureType.Cursor"), - EditorGUIUtility.TextContent("TextureImporter.TextureType.Reflection"), + EditorGUIUtility.TextContent("TextureImporter.TextureType.Cubemap"), EditorGUIUtility.TextContent("TextureImporter.TextureType.Cookie"), EditorGUIUtility.TextContent("TextureImporter.TextureType.Lightmap"), EditorGUIUtility.TextContent("TextureImporter.TextureType.Advanced") @@ -427,15 +423,39 @@ private class Styles EditorGUIUtility.TextContent("TextureImporter.BumpFiltering.Sharp"), EditorGUIUtility.TextContent("TextureImporter.BumpFiltering.Smooth") }; - public readonly GUIContent refMap = EditorGUIUtility.TextContent("TextureImporter.RefMap"); - public readonly GUIContent[] refMapOptions = new GUIContent[] + public readonly GUIContent cubemap = EditorGUIUtility.TextContent("TextureImporter.RefMap"); + public readonly GUIContent[] cubemapOptions = new GUIContent[] { - EditorGUIUtility.TextContent("TextureImporter.RefMap.Sphere"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.None"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.Auto"), + EditorGUIUtility.TextContent("TextureImporter.RefMap.FullCubemap"), EditorGUIUtility.TextContent("TextureImporter.RefMap.Cylindrical"), - EditorGUIUtility.TextContent("TextureImporter.RefMap.SimpleSphere"), - EditorGUIUtility.TextContent("TextureImporter.RefMap.NiceSphere"), - EditorGUIUtility.TextContent("TextureImporter.RefMap.FullCubemap") + EditorGUIUtility.TextContent("TextureImporter.RefMap.Sphere") + }; + public readonly int[] cubemapValues = new int[] + { + 0, + 6, + 5, + 2, + 1 + }; + public readonly GUIContent cubemapConvolution = EditorGUIUtility.TextContent("TextureImporter.CubemapConvolution"); + public readonly GUIContent[] cubemapConvolutionOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.CubemapConvolution.None"), + EditorGUIUtility.TextContent("TextureImporter.CubemapConvolution.Specular"), + EditorGUIUtility.TextContent("TextureImporter.CubemapConvolution.Diffuse") + }; + public readonly int[] cubemapConvolutionValues = new int[] + { + 0, + 1, + 2 }; + public readonly GUIContent cubemapConvolutionSimple = EditorGUIUtility.TextContent("TextureImporter.CubemapConvolution.SpecularSimple"); + public readonly GUIContent cubemapConvolutionSteps = EditorGUIUtility.TextContent("TextureImporter.CubemapConvolutionSteps"); + public readonly GUIContent cubemapConvolutionExp = EditorGUIUtility.TextContent("TextureImporter.CubemapConvolutionExp"); public readonly GUIContent seamlessCubemap = EditorGUIUtility.TextContent("TextureImporter.SeamlessCubemap"); public readonly GUIContent maxSize = EditorGUIUtility.TextContent("TextureImporter.MaxSize"); public readonly GUIContent textureFormat = EditorGUIUtility.TextContent("TextureImporter.TextureFormat"); @@ -449,6 +469,14 @@ private class Styles public readonly GUIContent mipmapFadeOutToggle = EditorGUIUtility.TextContent("TextureImporter.MipmapFadeToggle"); public readonly GUIContent mipmapFadeOut = EditorGUIUtility.TextContent("TextureImporter.MipmapFade"); public readonly GUIContent readWrite = EditorGUIUtility.TextContent("TextureImporter.ReadWrite"); + public readonly GUIContent rgbmEncoding = EditorGUIUtility.TextContent("TextureImporter.RGBMEncoding"); + public readonly GUIContent[] rgbmEncodingOptions = new GUIContent[] + { + EditorGUIUtility.TextContent("TextureImporter.RGBMEncoding.Auto"), + EditorGUIUtility.TextContent("TextureImporter.RGBMEncoding.On"), + EditorGUIUtility.TextContent("TextureImporter.RGBMEncoding.Off"), + EditorGUIUtility.TextContent("TextureImporter.RGBMEncoding.Encoded") + }; public readonly GUIContent generateMipMaps = EditorGUIUtility.TextContent("TextureImporter.GenerateMipMaps"); public readonly GUIContent mipMapsInLinearSpace = EditorGUIUtility.TextContent("TextureImporter.MipMapsInLinearSpace"); public readonly GUIContent linearTexture = EditorGUIUtility.TextContent("TextureImporter.LinearTexture"); @@ -587,11 +615,13 @@ private class Styles 13, 4 }; - private static readonly int[] kTextureFormatsValueFlash = new int[] + private static readonly int[] kTextureFormatsValueSTV = new int[] { - 40, - 39, + 34, + 7, 3, + 1, + 13, 4 }; private static readonly int[] kTextureFormatsValueGLESEmu = new int[] @@ -629,11 +659,6 @@ private class Styles 2, 5 }; - private static readonly int[] kNormalFormatsValueFlash = new int[] - { - 39, - 4 - }; private static readonly TextureImporterFormat[] kFormatsWithCompressionSettings = new TextureImporterFormat[] { TextureImporterFormat.PVRTC_RGB2, @@ -643,8 +668,6 @@ private class Styles TextureImporterFormat.ATC_RGB4, TextureImporterFormat.ATC_RGBA8, TextureImporterFormat.ETC_RGB4, - TextureImporterFormat.ATF_RGB_JPG, - TextureImporterFormat.ATF_RGBA_JPG, TextureImporterFormat.ETC2_RGB4, TextureImporterFormat.ETC2_RGB4_PUNCHTHROUGH_ALPHA, TextureImporterFormat.ETC2_RGBA8, @@ -667,13 +690,13 @@ private class Styles private static string[] s_TextureFormatStringsAndroid; private static string[] s_TextureFormatStringsBB10; private static string[] s_TextureFormatStringsTizen; - private static string[] s_TextureFormatStringsFlash; + private static string[] s_TextureFormatStringsSTV; private static string[] s_TextureFormatStringsWeb; private static string[] s_NormalFormatStringsAll; - private static string[] s_NormalFormatStringsFlash; private static string[] s_NormalFormatStringsWeb; private readonly AnimBool m_ShowBumpGenerationSettings = new AnimBool(); private readonly AnimBool m_ShowCookieCubeMapSettings = new AnimBool(); + private readonly AnimBool m_ShowConvolutionCubeMapSettings = new AnimBool(); private readonly AnimBool m_ShowGenericSpriteSettings = new AnimBool(); private readonly AnimBool m_ShowManualAtlasGenerationSettings = new AnimBool(); private readonly GUIContent m_EmptyContent = new GUIContent(" "); @@ -703,11 +726,15 @@ private class Styles private SerializedProperty m_HeightScale; private SerializedProperty m_NormalMapFilter; private SerializedProperty m_GenerateCubemap; + private SerializedProperty m_CubemapConvolution; + private SerializedProperty m_CubemapConvolutionSteps; + private SerializedProperty m_CubemapConvolutionExponent; private SerializedProperty m_SeamlessCubemap; private SerializedProperty m_BorderMipMap; private SerializedProperty m_NPOTScale; private SerializedProperty m_IsReadable; private SerializedProperty m_LinearTexture; + private SerializedProperty m_RGBM; private SerializedProperty m_EnableMipMap; private SerializedProperty m_GenerateMipsInLinearSpace; private SerializedProperty m_MipMapMode; @@ -735,7 +762,8 @@ private class Styles "512", "1024", "2048", - "4096" + "4096", + "8192" }; private static readonly int[] kMaxTextureSizeValues = new int[] { @@ -746,7 +774,8 @@ private class Styles 512, 1024, 2048, - 4096 + 4096, + 8192 }; private TextureImporterType textureType { @@ -816,9 +845,9 @@ private static int[] TextureFormatsValueAll BuildTarget defaultTarget = buildPlatform.DefaultTarget; switch (defaultTarget) { - case BuildTarget.iPhone: + case BuildTarget.iOS: flag2 = true; - goto IL_B1; + goto IL_C1; case BuildTarget.PS3: case BuildTarget.XBOX360: case (BuildTarget)12: @@ -827,30 +856,35 @@ private static int[] TextureFormatsValueAll { flag2 = true; flag = true; - goto IL_B1; + goto IL_C1; } - if (defaultTarget != BuildTarget.Tizen) + if (defaultTarget == BuildTarget.Tizen) { - goto IL_B1; + flag = true; + goto IL_C1; + } + if (defaultTarget != BuildTarget.SamsungTV) + { + goto IL_C1; } flag = true; - goto IL_B1; + goto IL_C1; case BuildTarget.Android: flag2 = true; flag = true; flag3 = true; flag4 = true; flag5 = true; - goto IL_B1; + goto IL_C1; case BuildTarget.StandaloneGLESEmu: flag2 = true; flag = true; flag4 = true; flag5 = true; - goto IL_B1; + goto IL_C1; } goto IL_60; - IL_B1:; + IL_C1:; } List list = new List(); list.AddRange(new int[] @@ -941,7 +975,7 @@ private static int[] NormalFormatsValueAll BuildTarget defaultTarget = buildPlatform.DefaultTarget; switch (defaultTarget) { - case BuildTarget.iPhone: + case BuildTarget.iOS: flag2 = true; flag = true; goto IL_A3; @@ -1054,7 +1088,7 @@ private static int[] NormalFormatsValueAll } internal static bool IsGLESMobileTargetPlatform(BuildTarget target) { - return target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.BB10 || target == BuildTarget.Tizen; + return target == BuildTarget.iOS || target == BuildTarget.Android || target == BuildTarget.BB10 || target == BuildTarget.Tizen || target == BuildTarget.SamsungTV; } private void UpdateImportWarning() { @@ -1090,6 +1124,7 @@ private void CacheSerializedProperties() this.m_NPOTScale = base.serializedObject.FindProperty("m_NPOTScale"); this.m_IsReadable = base.serializedObject.FindProperty("m_IsReadable"); this.m_LinearTexture = base.serializedObject.FindProperty("m_LinearTexture"); + this.m_RGBM = base.serializedObject.FindProperty("m_RGBM"); this.m_EnableMipMap = base.serializedObject.FindProperty("m_EnableMipMap"); this.m_MipMapMode = base.serializedObject.FindProperty("m_MipMapMode"); this.m_GenerateMipsInLinearSpace = base.serializedObject.FindProperty("correctGamma"); @@ -1100,6 +1135,9 @@ private void CacheSerializedProperties() this.m_Aniso = base.serializedObject.FindProperty("m_TextureSettings.m_Aniso"); this.m_FilterMode = base.serializedObject.FindProperty("m_TextureSettings.m_FilterMode"); this.m_WrapMode = base.serializedObject.FindProperty("m_TextureSettings.m_WrapMode"); + this.m_CubemapConvolution = base.serializedObject.FindProperty("m_CubemapConvolution"); + this.m_CubemapConvolutionSteps = base.serializedObject.FindProperty("m_CubemapConvolutionSteps"); + this.m_CubemapConvolutionExponent = base.serializedObject.FindProperty("m_CubemapConvolutionExponent"); this.m_SpriteMode = base.serializedObject.FindProperty("m_SpriteMode"); this.m_SpritePackingTag = base.serializedObject.FindProperty("m_SpritePackingTag"); this.m_SpritePixelsToUnits = base.serializedObject.FindProperty("m_SpritePixelsToUnits"); @@ -1115,7 +1153,7 @@ public virtual void OnEnable() this.m_ShowBumpGenerationSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); this.m_ShowCookieCubeMapSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); this.m_ShowCookieCubeMapSettings.value = (this.textureType == TextureImporterType.Cookie && this.m_GenerateCubemap.intValue != 0); - this.m_ShowBumpGenerationSettings.value = (this.m_ConvertToNormalMap.intValue > 0); + this.m_ShowConvolutionCubeMapSettings.value = (this.m_CubemapConvolution.intValue == 1 && this.m_GenerateCubemap.intValue != 0); this.m_ShowGenericSpriteSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); this.m_ShowManualAtlasGenerationSettings.valueChanged.AddListener(new UnityAction(base.Repaint)); this.m_ShowGenericSpriteSettings.value = (this.m_SpriteMode.intValue != 0); @@ -1129,12 +1167,16 @@ private void SetSerializedPropertySettings(TextureImporterSettings settings) this.m_HeightScale.floatValue = settings.heightmapScale; this.m_NormalMapFilter.intValue = (int)settings.normalMapFilter; this.m_GenerateCubemap.intValue = (int)settings.generateCubemap; + this.m_CubemapConvolution.intValue = (int)settings.cubemapConvolution; + this.m_CubemapConvolutionSteps.intValue = settings.cubemapConvolutionSteps; + this.m_CubemapConvolutionExponent.floatValue = settings.cubemapConvolutionExponent; this.m_SeamlessCubemap.intValue = ((!settings.seamlessCubemap) ? 0 : 1); this.m_BorderMipMap.intValue = ((!settings.borderMipmap) ? 0 : 1); this.m_NPOTScale.intValue = (int)settings.npotScale; this.m_IsReadable.intValue = ((!settings.readable) ? 0 : 1); this.m_EnableMipMap.intValue = ((!settings.mipmapEnabled) ? 0 : 1); this.m_LinearTexture.intValue = ((!settings.linearTexture) ? 0 : 1); + this.m_RGBM.intValue = (int)settings.rgbm; this.m_MipMapMode.intValue = (int)settings.mipmapFilter; this.m_GenerateMipsInLinearSpace.intValue = ((!settings.generateMipsInLinearSpace) ? 0 : 1); this.m_FadeOut.intValue = ((!settings.fadeOut) ? 0 : 1); @@ -1181,6 +1223,18 @@ private TextureImporterSettings GetSerializedPropertySettings(TextureImporterSet { settings.generateCubemap = (TextureImporterGenerateCubemap)this.m_GenerateCubemap.intValue; } + if (!this.m_CubemapConvolution.hasMultipleDifferentValues) + { + settings.cubemapConvolution = (TextureImporterCubemapConvolution)this.m_CubemapConvolution.intValue; + } + if (!this.m_CubemapConvolutionSteps.hasMultipleDifferentValues) + { + settings.cubemapConvolutionSteps = this.m_CubemapConvolutionSteps.intValue; + } + if (!this.m_CubemapConvolutionExponent.hasMultipleDifferentValues) + { + settings.cubemapConvolutionExponent = this.m_CubemapConvolutionExponent.floatValue; + } if (!this.m_SeamlessCubemap.hasMultipleDifferentValues) { settings.seamlessCubemap = (this.m_SeamlessCubemap.intValue > 0); @@ -1201,6 +1255,10 @@ private TextureImporterSettings GetSerializedPropertySettings(TextureImporterSet { settings.linearTexture = (this.m_LinearTexture.intValue > 0); } + if (!this.m_RGBM.hasMultipleDifferentValues) + { + settings.rgbm = (TextureImporterRGBMMode)this.m_RGBM.intValue; + } if (!this.m_EnableMipMap.hasMultipleDifferentValues) { settings.mipmapEnabled = (this.m_EnableMipMap.intValue > 0); @@ -1301,8 +1359,8 @@ public override void OnInspectorGUI() case TextureImporterType.Bump: this.BumpGUI(); break; - case TextureImporterType.Reflection: - this.ReflectionGUI(); + case TextureImporterType.Cubemap: + this.CubemapGUI(); break; case TextureImporterType.Cookie: this.CookieGUI(); @@ -1332,7 +1390,7 @@ public override void OnInspectorGUI() private void PreviewableGUI() { EditorGUI.BeginChangeCheck(); - if (this.textureType != TextureImporterType.GUI && this.textureType != TextureImporterType.Sprite && this.textureType != TextureImporterType.Reflection && this.textureType != TextureImporterType.Cookie && this.textureType != TextureImporterType.Lightmap) + if (this.textureType != TextureImporterType.GUI && this.textureType != TextureImporterType.Sprite && this.textureType != TextureImporterType.Cubemap && this.textureType != TextureImporterType.Cookie && this.textureType != TextureImporterType.Lightmap) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = this.m_WrapMode.hasMultipleDifferentValues; @@ -1347,7 +1405,7 @@ private void PreviewableGUI() { this.m_WrapMode.intValue = (int)textureWrapMode; } - if (textureWrapMode == TextureWrapMode.Repeat && !ShaderUtil.hardwareSupportsFullNPOT) + if (this.m_NPOTScale.intValue == 0 && textureWrapMode == TextureWrapMode.Repeat && !ShaderUtil.hardwareSupportsFullNPOT) { bool flag = false; UnityEngine.Object[] targets = base.targets; @@ -1566,20 +1624,59 @@ private void SpriteGUI(bool showMipMapControls) this.ToggleFromInt(this.m_EnableMipMap, TextureImporterInspector.s_Styles.generateMipMaps); } } - private void ReflectionGUI() + private void CubemapGUI() { - this.ReflectionMappingGUI(); + this.CubemapMappingGUI(false); } - private void ReflectionMappingGUI() + private void CubemapMappingGUI(bool advancedMode) { EditorGUI.showMixedValue = (this.m_GenerateCubemap.hasMultipleDifferentValues || this.m_SeamlessCubemap.hasMultipleDifferentValues); EditorGUI.BeginChangeCheck(); - int intValue = EditorGUILayout.Popup(TextureImporterInspector.s_Styles.refMap, this.m_GenerateCubemap.intValue - 1, TextureImporterInspector.s_Styles.refMapOptions, new GUILayoutOption[0]) + 1; + int count = (!advancedMode) ? 1 : 0; + List list = new List(TextureImporterInspector.s_Styles.cubemapOptions); + list.RemoveRange(0, count); + List list2 = new List(TextureImporterInspector.s_Styles.cubemapValues); + list2.RemoveRange(0, count); + int num = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.cubemap, this.m_GenerateCubemap.intValue, list.ToArray(), list2.ToArray(), new GUILayoutOption[0]); if (EditorGUI.EndChangeCheck()) { - this.m_GenerateCubemap.intValue = intValue; + this.m_GenerateCubemap.intValue = num; + } + EditorGUI.BeginDisabledGroup(num == 0); + if (advancedMode) + { + EditorGUI.indentLevel++; + } + if (advancedMode) + { + EditorGUILayout.IntPopup(this.m_CubemapConvolution, TextureImporterInspector.s_Styles.cubemapConvolutionOptions, TextureImporterInspector.s_Styles.cubemapConvolutionValues.ToArray(), TextureImporterInspector.s_Styles.cubemapConvolution, new GUILayoutOption[0]); + } + else + { + this.ToggleFromInt(this.m_CubemapConvolution, TextureImporterInspector.s_Styles.cubemapConvolutionSimple); + if (this.m_CubemapConvolution.intValue != 0) + { + this.m_CubemapConvolution.intValue = 1; + } + } + if (advancedMode) + { + this.m_ShowConvolutionCubeMapSettings.target = (this.m_CubemapConvolution.intValue == 1); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowConvolutionCubeMapSettings.faded)) + { + EditorGUI.indentLevel++; + this.m_CubemapConvolutionSteps.intValue = EditorGUILayout.IntField(TextureImporterInspector.s_Styles.cubemapConvolutionSteps, this.m_CubemapConvolutionSteps.intValue, new GUILayoutOption[0]); + this.m_CubemapConvolutionExponent.floatValue = EditorGUILayout.FloatField(TextureImporterInspector.s_Styles.cubemapConvolutionExp, this.m_CubemapConvolutionExponent.floatValue, new GUILayoutOption[0]); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndFadeGroup(); } this.ToggleFromInt(this.m_SeamlessCubemap, TextureImporterInspector.s_Styles.seamlessCubemap); + if (advancedMode) + { + EditorGUI.indentLevel--; + } + EditorGUI.EndDisabledGroup(); EditorGUI.showMixedValue = false; } private void CookieGUI() @@ -1609,7 +1706,7 @@ private void CookieGUI() this.m_ShowCookieCubeMapSettings.target = (cookieMode == TextureImporterInspector.CookieMode.Point); if (EditorGUILayout.BeginFadeGroup(this.m_ShowCookieCubeMapSettings.faded)) { - this.ReflectionMappingGUI(); + this.CubemapMappingGUI(false); } EditorGUILayout.EndFadeGroup(); this.ToggleFromInt(this.m_GrayscaleToAlpha, TextureImporterInspector.s_Styles.generateAlphaFromGrayscale); @@ -1631,7 +1728,7 @@ private void SetCookieMode(TextureImporterInspector.CookieMode cm) case TextureImporterInspector.CookieMode.Point: this.m_BorderMipMap.intValue = 0; this.m_WrapMode.intValue = 1; - this.m_GenerateCubemap.intValue = 3; + this.m_GenerateCubemap.intValue = 1; break; } } @@ -1661,7 +1758,7 @@ private void AdvancedGUI() this.EnumPopup(this.m_NPOTScale, typeof(TextureImporterNPOTScale), TextureImporterInspector.s_Styles.npot); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(!flag && this.m_NPOTScale.intValue == 0); - this.EnumPopup(this.m_GenerateCubemap, typeof(TextureImporterGenerateCubemap), TextureImporterInspector.s_Styles.generateCubemap); + this.CubemapMappingGUI(true); EditorGUI.EndDisabledGroup(); this.ToggleFromInt(this.m_IsReadable, TextureImporterInspector.s_Styles.readWrite); TextureImporterInspector.AdvancedTextureType advancedTextureType = TextureImporterInspector.AdvancedTextureType.Default; @@ -1696,12 +1793,14 @@ private void AdvancedGUI() this.m_NormalMap.intValue = 1; this.m_Lightmap.intValue = 0; this.m_LinearTexture.intValue = 1; + this.m_RGBM.intValue = 0; break; case TextureImporterInspector.AdvancedTextureType.LightMap: this.m_NormalMap.intValue = 0; this.m_Lightmap.intValue = 1; this.m_ConvertToNormalMap.intValue = 0; this.m_LinearTexture.intValue = 1; + this.m_RGBM.intValue = 0; break; } } @@ -1722,6 +1821,7 @@ private void AdvancedGUI() this.ToggleFromInt(this.m_GrayscaleToAlpha, TextureImporterInspector.s_Styles.generateAlphaFromGrayscale); this.DoAlphaIsTransparencyGUI(); this.ToggleFromInt(this.m_LinearTexture, TextureImporterInspector.s_Styles.linearTexture); + EditorGUILayout.Popup(this.m_RGBM, TextureImporterInspector.s_Styles.rgbmEncodingOptions, TextureImporterInspector.s_Styles.rgbmEncoding, new GUILayoutOption[0]); this.SpriteGUI(false); } } @@ -1857,7 +1957,7 @@ protected void SizeAndFormatGUI() int num5 = num4; if (!platformSetting.isDefault && num4 < 0) { - num5 = (int)TextureImporter.SimpleToFullTextureFormat2((TextureImporterFormat)num5, textureImporterType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.DoesSourceTextureHaveColor(), platformSetting.m_Target); + num5 = (int)TextureImporter.SimpleToFullTextureFormat2((TextureImporterFormat)num5, textureImporterType, settings, textureImporter.DoesSourceTextureHaveAlpha(), textureImporter.IsSourceTextureHDR(), platformSetting.m_Target); } if (settings.normalMap && !TextureImporterInspector.IsGLESMobileTargetPlatform(platformSetting.m_Target)) { @@ -1891,15 +1991,27 @@ protected void SizeAndFormatGUI() { TextureImporterInspector.s_TextureFormatStringsAndroid = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueAndroid); } - if (platformSetting.m_Target == BuildTarget.iPhone) + if (platformSetting.m_Target == BuildTarget.iOS) { array3 = TextureImporterInspector.kTextureFormatsValueiPhone; array4 = TextureImporterInspector.s_TextureFormatStringsiPhone; } else { - array3 = TextureImporterInspector.kTextureFormatsValueAndroid; - array4 = TextureImporterInspector.s_TextureFormatStringsAndroid; + if (platformSetting.m_Target == BuildTarget.SamsungTV) + { + if (TextureImporterInspector.s_TextureFormatStringsSTV == null) + { + TextureImporterInspector.s_TextureFormatStringsSTV = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueSTV); + } + array3 = TextureImporterInspector.kTextureFormatsValueSTV; + array4 = TextureImporterInspector.s_TextureFormatStringsSTV; + } + else + { + array3 = TextureImporterInspector.kTextureFormatsValueAndroid; + array4 = TextureImporterInspector.s_TextureFormatStringsAndroid; + } } } else @@ -1910,10 +2022,6 @@ protected void SizeAndFormatGUI() { TextureImporterInspector.s_TextureFormatStringsAll = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.TextureFormatsValueAll); } - if (TextureImporterInspector.s_TextureFormatStringsFlash == null) - { - TextureImporterInspector.s_TextureFormatStringsFlash = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueFlash); - } if (TextureImporterInspector.s_TextureFormatStringsGLESEmu == null) { TextureImporterInspector.s_TextureFormatStringsGLESEmu = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kTextureFormatsValueGLESEmu); @@ -1936,16 +2044,8 @@ protected void SizeAndFormatGUI() } else { - if (platformSetting.m_Target == BuildTarget.FlashPlayer) - { - array3 = TextureImporterInspector.kTextureFormatsValueFlash; - array4 = TextureImporterInspector.s_TextureFormatStringsFlash; - } - else - { - array3 = TextureImporterInspector.kTextureFormatsValueWeb; - array4 = TextureImporterInspector.s_TextureFormatStringsWeb; - } + array3 = TextureImporterInspector.kTextureFormatsValueWeb; + array4 = TextureImporterInspector.s_TextureFormatStringsWeb; } } } @@ -1955,10 +2055,6 @@ protected void SizeAndFormatGUI() { TextureImporterInspector.s_NormalFormatStringsAll = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.NormalFormatsValueAll); } - if (TextureImporterInspector.s_NormalFormatStringsFlash == null) - { - TextureImporterInspector.s_NormalFormatStringsFlash = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kNormalFormatsValueFlash); - } if (TextureImporterInspector.s_NormalFormatStringsWeb == null) { TextureImporterInspector.s_NormalFormatStringsWeb = TextureImporterInspector.BuildTextureStrings(TextureImporterInspector.kNormalFormatsValueWeb); @@ -1970,16 +2066,8 @@ protected void SizeAndFormatGUI() } else { - if (platformSetting.m_Target == BuildTarget.FlashPlayer) - { - array3 = TextureImporterInspector.kNormalFormatsValueFlash; - array4 = TextureImporterInspector.s_NormalFormatStringsFlash; - } - else - { - array3 = TextureImporterInspector.kNormalFormatsValueWeb; - array4 = TextureImporterInspector.s_NormalFormatStringsWeb; - } + array3 = TextureImporterInspector.kNormalFormatsValueWeb; + array4 = TextureImporterInspector.s_NormalFormatStringsWeb; } } } @@ -2050,39 +2138,32 @@ protected void SizeAndFormatGUI() } private int EditCompressionQuality(BuildTarget target, int compression) { - if (target == BuildTarget.iPhone || target == BuildTarget.Android || target == BuildTarget.BB10 || target == BuildTarget.Tizen) + if (target != BuildTarget.iOS && target != BuildTarget.Android && target != BuildTarget.BB10 && target != BuildTarget.Tizen && target != BuildTarget.SamsungTV) { - int selectedIndex = 1; - if (compression == 0) - { - selectedIndex = 0; - } - else - { - if (compression == 100) - { - selectedIndex = 2; - } - } - switch (EditorGUILayout.Popup(TextureImporterInspector.s_Styles.compressionQuality, selectedIndex, TextureImporterInspector.s_Styles.mobileCompressionQualityOptions, new GUILayoutOption[0])) - { - case 0: - return 0; - case 1: - return 50; - case 2: - return 100; - default: - return 50; - } + return compression; + } + int selectedIndex = 1; + if (compression == 0) + { + selectedIndex = 0; } else { - if (target == BuildTarget.FlashPlayer) + if (compression == 100) { - return EditorGUILayout.IntSlider(TextureImporterInspector.s_Styles.compressionQuality, compression, 0, 100, new GUILayoutOption[0]); + selectedIndex = 2; } - return compression; + } + switch (EditorGUILayout.Popup(TextureImporterInspector.s_Styles.compressionQuality, selectedIndex, TextureImporterInspector.s_Styles.mobileCompressionQualityOptions, new GUILayoutOption[0])) + { + case 0: + return 0; + case 1: + return 50; + case 2: + return 100; + default: + return 50; } } private static bool IsPowerOfTwo(int f) @@ -2095,10 +2176,7 @@ public static BuildPlayerWindow.BuildPlatform[] GetBuildPlayerValidPlatforms() List list = new List(); foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) { - if (current.targetGroup != BuildTargetGroup.NaCl) - { - list.Add(current); - } + list.Add(current); } return list.ToArray(); } @@ -2129,13 +2207,27 @@ internal override bool HasModified() } return false; } + public static void SelectMainAssets(UnityEngine.Object[] targets) + { + ArrayList arrayList = new ArrayList(); + for (int i = 0; i < targets.Length; i++) + { + AssetImporter assetImporter = (AssetImporter)targets[i]; + Texture texture = AssetDatabase.LoadMainAssetAtPath(assetImporter.assetPath) as Texture; + if (texture) + { + arrayList.Add(texture); + } + } + Selection.objects = (arrayList.ToArray(typeof(UnityEngine.Object)) as UnityEngine.Object[]); + } internal override void ResetValues() { base.ResetValues(); this.CacheSerializedProperties(); this.BuildTargetList(); - Assert.IsFalse(this.HasModified(), "TextureImporter settings are marked as modified after calling Reset."); this.ApplySettingsToTexture(); + TextureImporterInspector.SelectMainAssets(base.targets); } internal override void Apply() { diff --git a/UnityEditor/UnityEditor/TextureImporterRGBMMode.cs b/UnityEditor/UnityEditor/TextureImporterRGBMMode.cs new file mode 100644 index 00000000..583408a3 --- /dev/null +++ b/UnityEditor/UnityEditor/TextureImporterRGBMMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum TextureImporterRGBMMode + { + Auto, + On, + Off, + Encoded + } +} diff --git a/UnityEditor/UnityEditor/TextureImporterSettings.cs b/UnityEditor/UnityEditor/TextureImporterSettings.cs index fdf635a3..2a6ba191 100644 --- a/UnityEditor/UnityEditor/TextureImporterSettings.cs +++ b/UnityEditor/UnityEditor/TextureImporterSettings.cs @@ -45,6 +45,8 @@ public sealed class TextureImporterSettings [SerializeField] private int m_LinearTexture; [SerializeField] + private int m_RGBM; + [SerializeField] private int m_CompressionQuality; [SerializeField] private int m_SpriteMode; @@ -63,6 +65,12 @@ public sealed class TextureImporterSettings [SerializeField] private int m_GenerateCubemap; [SerializeField] + private int m_CubemapConvolution; + [SerializeField] + private int m_CubemapConvolutionSteps; + [SerializeField] + private float m_CubemapConvolutionExponent; + [SerializeField] private int m_SeamlessCubemap; [SerializeField] private int m_AlphaIsTransparency; @@ -272,6 +280,17 @@ public bool lightmap this.m_Lightmap = ((!value) ? 0 : 1); } } + public TextureImporterRGBMMode rgbm + { + get + { + return (TextureImporterRGBMMode)this.m_RGBM; + } + set + { + this.m_RGBM = (int)value; + } + } public TextureImporterGenerateCubemap generateCubemap { get @@ -283,6 +302,39 @@ public TextureImporterGenerateCubemap generateCubemap this.m_GenerateCubemap = (int)value; } } + public TextureImporterCubemapConvolution cubemapConvolution + { + get + { + return (TextureImporterCubemapConvolution)this.m_CubemapConvolution; + } + set + { + this.m_CubemapConvolution = (int)value; + } + } + public int cubemapConvolutionSteps + { + get + { + return this.m_CubemapConvolutionSteps; + } + set + { + this.m_CubemapConvolutionSteps = value; + } + } + public float cubemapConvolutionExponent + { + get + { + return this.m_CubemapConvolutionExponent; + } + set + { + this.m_CubemapConvolutionExponent = value; + } + } public bool seamlessCubemap { get diff --git a/UnityEditor/UnityEditor/TextureImporterType.cs b/UnityEditor/UnityEditor/TextureImporterType.cs index 234f1f8c..c3993baf 100644 --- a/UnityEditor/UnityEditor/TextureImporterType.cs +++ b/UnityEditor/UnityEditor/TextureImporterType.cs @@ -8,6 +8,7 @@ public enum TextureImporterType GUI, Sprite = 8, Cursor = 7, + Cubemap = 3, Reflection = 3, Cookie, Lightmap = 6, diff --git a/UnityEditor/UnityEditor/TextureInspector.cs b/UnityEditor/UnityEditor/TextureInspector.cs index 3ed0b031..e194fa44 100644 --- a/UnityEditor/UnityEditor/TextureInspector.cs +++ b/UnityEditor/UnityEditor/TextureInspector.cs @@ -5,15 +5,31 @@ namespace UnityEditor [CanEditMultipleObjects, CustomEditor(typeof(Texture2D))] internal class TextureInspector : Editor { - private static GUIContent s_SmallZoom; - private static GUIContent s_LargeZoom; - private static GUIContent s_AlphaIcon; - private static GUIContent s_RGBIcon; - private static GUIStyle s_PreButton; - private static GUIStyle s_PreSlider; - private static GUIStyle s_PreSliderThumb; - private static GUIStyle s_PreLabel; - private bool m_bShowAlpha; + private class Styles + { + public GUIContent smallZoom; + public GUIContent largeZoom; + public GUIContent alphaIcon; + public GUIContent RGBIcon; + public GUIStyle previewButton; + public GUIStyle previewSlider; + public GUIStyle previewSliderThumb; + public GUIStyle previewLabel; + public Styles() + { + this.smallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); + this.largeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); + this.alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); + this.RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); + this.previewButton = "preButton"; + this.previewSlider = "preSlider"; + this.previewSliderThumb = "preSliderThumb"; + this.previewLabel = new GUIStyle("preLabel"); + this.previewLabel.alignment = TextAnchor.UpperCenter; + } + } + private static TextureInspector.Styles s_Styles; + private bool m_ShowAlpha; private SerializedProperty m_WrapMode; private SerializedProperty m_FilterMode; private SerializedProperty m_Aniso; @@ -21,6 +37,23 @@ internal class TextureInspector : Editor protected Vector2 m_Pos; [SerializeField] private float m_MipLevel; + private CubemapPreview m_CubemapPreview = new CubemapPreview(); + public float mipLevel + { + get + { + if (this.IsCubemap()) + { + return this.m_CubemapPreview.mipLevel; + } + return this.m_MipLevel; + } + set + { + this.m_CubemapPreview.mipLevel = value; + this.m_MipLevel = value; + } + } public static bool IsNormalMap(Texture t) { TextureUsageMode usageMode = TextureUtil.GetUsageMode(t); @@ -28,15 +61,33 @@ public static bool IsNormalMap(Texture t) } protected virtual void OnEnable() { - float realtimeSinceStartup = Time.realtimeSinceStartup; - if (Time.realtimeSinceStartup - realtimeSinceStartup > 1f) - { - Debug.LogWarning("Took " + (Time.realtimeSinceStartup - realtimeSinceStartup) + " seconds to create SerializedObject!"); - } this.m_WrapMode = base.serializedObject.FindProperty("m_TextureSettings.m_WrapMode"); this.m_FilterMode = base.serializedObject.FindProperty("m_TextureSettings.m_FilterMode"); this.m_Aniso = base.serializedObject.FindProperty("m_TextureSettings.m_Aniso"); } + protected virtual void OnDisable() + { + this.m_CubemapPreview.OnDisable(); + } + internal void SetCubemapIntensity(float intensity) + { + if (this.m_CubemapPreview != null) + { + this.m_CubemapPreview.SetIntensity(intensity); + } + } + public float GetMipLevelForRendering() + { + if (this.target == null) + { + return 0f; + } + if (this.IsCubemap()) + { + return this.m_CubemapPreview.GetMipLevelForRendering(this.target as Texture); + } + return Mathf.Min(this.m_MipLevel, (float)(TextureUtil.CountMipmaps(this.target as Texture) - 1)); + } public override void OnInspectorGUI() { base.serializedObject.Update(); @@ -69,20 +120,27 @@ public override void OnInspectorGUI() } base.serializedObject.ApplyModifiedProperties(); } - private static void Init() + private bool IsCubemap() { - TextureInspector.s_SmallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); - TextureInspector.s_LargeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); - TextureInspector.s_AlphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); - TextureInspector.s_RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); - TextureInspector.s_PreButton = "preButton"; - TextureInspector.s_PreSlider = "preSlider"; - TextureInspector.s_PreSliderThumb = "preSliderThumb"; - TextureInspector.s_PreLabel = "preLabel"; + RenderTexture renderTexture = this.target as RenderTexture; + if (renderTexture != null && renderTexture.isCubemap) + { + return true; + } + Cubemap x = this.target as Cubemap; + return x != null; } public override void OnPreviewSettings() { - TextureInspector.Init(); + if (this.IsCubemap()) + { + this.m_CubemapPreview.OnPreviewSettings(base.targets); + return; + } + if (TextureInspector.s_Styles == null) + { + TextureInspector.s_Styles = new TextureInspector.Styles(); + } Texture t = this.target as Texture; bool flag = true; bool flag2 = false; @@ -119,7 +177,7 @@ public override void OnPreviewSettings() { flag2 = false; } - if (TextureUtil.HasAlphaTextureFormat(format)) + if (TextureUtil.HasAlphaTextureFormat(format) && TextureUtil.GetUsageMode(texture) == TextureUsageMode.Default) { flag3 = true; } @@ -127,29 +185,29 @@ public override void OnPreviewSettings() } if (flag2) { - this.m_bShowAlpha = true; + this.m_ShowAlpha = true; flag = false; } else { if (!flag3) { - this.m_bShowAlpha = false; + this.m_ShowAlpha = false; flag = false; } } if (flag && !TextureInspector.IsNormalMap(t)) { - this.m_bShowAlpha = GUILayout.Toggle(this.m_bShowAlpha, (!this.m_bShowAlpha) ? TextureInspector.s_RGBIcon : TextureInspector.s_AlphaIcon, TextureInspector.s_PreButton, new GUILayoutOption[0]); + this.m_ShowAlpha = GUILayout.Toggle(this.m_ShowAlpha, (!this.m_ShowAlpha) ? TextureInspector.s_Styles.RGBIcon : TextureInspector.s_Styles.alphaIcon, TextureInspector.s_Styles.previewButton, new GUILayoutOption[0]); } GUI.enabled = (num != 1); - GUILayout.Box(TextureInspector.s_SmallZoom, TextureInspector.s_PreLabel, new GUILayoutOption[0]); + GUILayout.Box(TextureInspector.s_Styles.smallZoom, TextureInspector.s_Styles.previewLabel, new GUILayoutOption[0]); GUI.changed = false; - this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, TextureInspector.s_PreSlider, TextureInspector.s_PreSliderThumb, new GUILayoutOption[] + this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, TextureInspector.s_Styles.previewSlider, TextureInspector.s_Styles.previewSliderThumb, new GUILayoutOption[] { GUILayout.MaxWidth(64f) })); - GUILayout.Box(TextureInspector.s_LargeZoom, TextureInspector.s_PreLabel, new GUILayoutOption[0]); + GUILayout.Box(TextureInspector.s_Styles.largeZoom, TextureInspector.s_Styles.previewLabel, new GUILayoutOption[0]); GUI.enabled = true; } public override bool HasPreviewGUI() @@ -164,21 +222,30 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) } Texture texture = this.target as Texture; RenderTexture renderTexture = texture as RenderTexture; - if (renderTexture != null && !renderTexture.IsCreated()) + if (renderTexture != null) { + if (!SystemInfo.SupportsRenderTextureFormat(renderTexture.format)) + { + return; + } renderTexture.Create(); } + if (this.IsCubemap()) + { + this.m_CubemapPreview.OnPreviewGUI(texture, r, background); + return; + } int num = Mathf.Max(texture.width, 1); int num2 = Mathf.Max(texture.height, 1); - float num3 = (!(texture is Texture2D) && !(texture is ProceduralTexture)) ? 0f : Mathf.Min(this.m_MipLevel, (float)(TextureUtil.CountMipmaps(texture) - 1)); - float num4 = Mathf.Min(Mathf.Min(r.width / (float)num, r.height / (float)num2), 1f); - Rect rect = new Rect(r.x, r.y, (float)num * num4, (float)num2 * num4); + float mipLevelForRendering = this.GetMipLevelForRendering(); + float num3 = Mathf.Min(Mathf.Min(r.width / (float)num, r.height / (float)num2), 1f); + Rect rect = new Rect(r.x, r.y, (float)num * num3, (float)num2 * num3); PreviewGUI.BeginScrollView(r, this.m_Pos, rect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); float mipMapBias = texture.mipMapBias; - TextureUtil.SetMipMapBiasNoDirty(texture, num3 - this.Log2((float)num / rect.width)); + TextureUtil.SetMipMapBiasNoDirty(texture, mipLevelForRendering - this.Log2((float)num / rect.width)); FilterMode filterMode = texture.filterMode; TextureUtil.SetFilterModeNoDirty(texture, FilterMode.Point); - if (this.m_bShowAlpha) + if (this.m_ShowAlpha) { EditorGUI.DrawTextureAlpha(rect, texture); } @@ -207,8 +274,8 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) int width = texture.width; int height = texture.height; textureImporter.GetWidthAndHeight(ref width, ref height); - float num5 = (float)texture.width / (float)width; - HandleUtility.handleWireMaterial.SetPass(0); + float num4 = (float)texture.width / (float)width; + HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(1); @@ -220,10 +287,10 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) Rect rect4 = spriteMetaData.rect; this.DrawRect(new Rect { - xMin = rect2.xMin + rect2.width * (rect4.xMin / (float)texture.width * num5), - xMax = rect2.xMin + rect2.width * (rect4.xMax / (float)texture.width * num5), - yMin = rect2.yMin + rect2.height * (1f - rect4.yMin / (float)texture.height * num5), - yMax = rect2.yMin + rect2.height * (1f - rect4.yMax / (float)texture.height * num5) + xMin = rect2.xMin + rect2.width * (rect4.xMin / (float)texture.width * num4), + xMax = rect2.xMin + rect2.width * (rect4.xMax / (float)texture.width * num4), + yMin = rect2.yMin + rect2.height * (1f - rect4.yMin / (float)texture.height * num4), + yMax = rect2.yMin + rect2.height * (1f - rect4.yMax / (float)texture.height * num4) }); } GL.End(); @@ -233,9 +300,9 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) TextureUtil.SetMipMapBiasNoDirty(texture, mipMapBias); TextureUtil.SetFilterModeNoDirty(texture, filterMode); this.m_Pos = PreviewGUI.EndScrollView(); - if (num3 != 0f) + if (mipLevelForRendering != 0f) { - EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Mip " + num3); + EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Mip " + mipLevelForRendering); } } private void DrawRect(Rect rect) diff --git a/UnityEditor/UnityEditor/TextureUsageMode.cs b/UnityEditor/UnityEditor/TextureUsageMode.cs index 28d10aa0..28a402f0 100644 --- a/UnityEditor/UnityEditor/TextureUsageMode.cs +++ b/UnityEditor/UnityEditor/TextureUsageMode.cs @@ -1,13 +1,14 @@ using System; namespace UnityEditor { - public enum TextureUsageMode + internal enum TextureUsageMode { Default, LightmapDoubleLDR, LightmapRGBM, NormalmapDXT5nm, NormalmapPlain, - AlwaysPadded = 6 + RGBMEncoded, + AlwaysPadded } } diff --git a/UnityEditor/UnityEditor/TickTimerHelper.cs b/UnityEditor/UnityEditor/TickTimerHelper.cs new file mode 100644 index 00000000..10239d27 --- /dev/null +++ b/UnityEditor/UnityEditor/TickTimerHelper.cs @@ -0,0 +1,26 @@ +using System; +namespace UnityEditor +{ + internal class TickTimerHelper + { + private double m_NextTick; + private double m_Interval; + public TickTimerHelper(double intervalBetweenTicksInSeconds) + { + this.m_Interval = intervalBetweenTicksInSeconds; + } + public bool DoTick() + { + if (EditorApplication.timeSinceStartup > this.m_NextTick) + { + this.m_NextTick = EditorApplication.timeSinceStartup + this.m_Interval; + return true; + } + return false; + } + public void Reset() + { + this.m_NextTick = 0.0; + } + } +} diff --git a/UnityEditor/UnityEditor/TimeArea.cs b/UnityEditor/UnityEditor/TimeArea.cs index 71917202..606ec275 100644 --- a/UnityEditor/UnityEditor/TimeArea.cs +++ b/UnityEditor/UnityEditor/TimeArea.cs @@ -112,7 +112,7 @@ private static void InitStyles() TimeArea.styles = new TimeArea.Styles2(); } } - private void ApplySettings() + protected virtual void ApplySettings() { base.hRangeLocked = this.settings.hRangeLocked; base.vRangeLocked = this.settings.vRangeLocked; @@ -174,7 +174,7 @@ public void TimeRuler(Rect position, float frameRate) return; } TimeArea.InitStyles(); - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); Color backgroundColor = GUI.backgroundColor; this.SetTickMarkerRanges(); diff --git a/UnityEditor/UnityEditor/TimeControl.cs b/UnityEditor/UnityEditor/TimeControl.cs index 39481f9c..c06a2e6f 100644 --- a/UnityEditor/UnityEditor/TimeControl.cs +++ b/UnityEditor/UnityEditor/TimeControl.cs @@ -132,6 +132,17 @@ public void DoTimeControl(Rect rect) this.m_MouseDrag += current.delta.x * this.playbackSpeed; if (this.loop && ((this.m_MouseDrag < 0f && this.m_WrapForwardDrag) || this.m_MouseDrag > rect3.width)) { + if (this.m_MouseDrag > rect3.width) + { + this.currentTime -= this.stopTime - this.startTime; + } + else + { + if (this.m_MouseDrag < 0f) + { + this.currentTime += this.stopTime - this.startTime; + } + } this.m_WrapForwardDrag = true; this.m_MouseDrag = Mathf.Repeat(this.m_MouseDrag, rect3.width); } diff --git a/UnityEditor/UnityEditor/TizenBuildSubtarget.cs b/UnityEditor/UnityEditor/TizenBuildSubtarget.cs deleted file mode 100644 index 72cb6f40..00000000 --- a/UnityEditor/UnityEditor/TizenBuildSubtarget.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -namespace UnityEditor -{ - public enum TizenBuildSubtarget - { - Generic, - ATC, - ETC - } -} diff --git a/UnityEditor/UnityEditor/Toolbar.cs b/UnityEditor/UnityEditor/Toolbar.cs index 7e2110b5..5d89944f 100644 --- a/UnityEditor/UnityEditor/Toolbar.cs +++ b/UnityEditor/UnityEditor/Toolbar.cs @@ -5,54 +5,12 @@ namespace UnityEditor { internal class Toolbar : GUIView { - private static GUIContent[] s_ToolIcons = new GUIContent[] - { - EditorGUIUtility.IconContent("MoveTool"), - EditorGUIUtility.IconContent("RotateTool"), - EditorGUIUtility.IconContent("ScaleTool"), - EditorGUIUtility.IconContent("RectTool"), - EditorGUIUtility.IconContent("MoveTool On"), - EditorGUIUtility.IconContent("RotateTool On"), - EditorGUIUtility.IconContent("ScaleTool On"), - EditorGUIUtility.IconContent("RectTool On") - }; - private static GUIContent[] s_ViewToolIcons = new GUIContent[] - { - EditorGUIUtility.IconContent("ViewToolOrbit"), - EditorGUIUtility.IconContent("ViewToolMove"), - EditorGUIUtility.IconContent("ViewToolZoom"), - EditorGUIUtility.IconContent("ViewToolOrbit"), - EditorGUIUtility.IconContent("ViewToolOrbit On"), - EditorGUIUtility.IconContent("ViewToolMove On"), - EditorGUIUtility.IconContent("ViewToolZoom On"), - EditorGUIUtility.IconContent("ViewToolOrbit On") - }; - private static GUIContent[] s_PivotIcons = new GUIContent[] - { - EditorGUIUtility.TextContent("ToolHandleCenter"), - EditorGUIUtility.TextContent("ToolHandlePivot") - }; - private static GUIContent[] s_PivotRotation = new GUIContent[] - { - EditorGUIUtility.TextContent("ToolHandleLocal"), - EditorGUIUtility.TextContent("ToolHandleGlobal") - }; - private static GUIContent s_LayerContent = EditorGUIUtility.TextContent("ToolbarLayers"); - private static GUIContent[] s_PlayIcons = new GUIContent[] - { - EditorGUIUtility.IconContent("PlayButton"), - EditorGUIUtility.IconContent("PauseButton"), - EditorGUIUtility.IconContent("StepButton"), - EditorGUIUtility.IconContent("PlayButtonProfile"), - EditorGUIUtility.IconContent("PlayButton On"), - EditorGUIUtility.IconContent("PauseButton On"), - EditorGUIUtility.IconContent("StepButton On"), - EditorGUIUtility.IconContent("PlayButtonProfile On"), - EditorGUIUtility.IconContent("PlayButton Anim"), - EditorGUIUtility.IconContent("PauseButton Anim"), - EditorGUIUtility.IconContent("StepButton Anim"), - EditorGUIUtility.IconContent("PlayButtonProfile Anim") - }; + private static GUIContent[] s_ToolIcons; + private static GUIContent[] s_ViewToolIcons; + private static GUIContent[] s_PivotIcons; + private static GUIContent[] s_PivotRotation; + private static GUIContent s_LayerContent; + private static GUIContent[] s_PlayIcons; private bool t1; private bool t2; private bool t3; @@ -72,6 +30,61 @@ internal static string lastLoadedLayoutName Toolbar.get.Repaint(); } } + private static void InitializeToolIcons() + { + if (Toolbar.s_ToolIcons != null) + { + return; + } + Toolbar.s_ToolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("MoveTool"), + EditorGUIUtility.IconContent("RotateTool"), + EditorGUIUtility.IconContent("ScaleTool"), + EditorGUIUtility.IconContent("RectTool"), + EditorGUIUtility.IconContent("MoveTool On"), + EditorGUIUtility.IconContent("RotateTool On"), + EditorGUIUtility.IconContent("ScaleTool On"), + EditorGUIUtility.IconContent("RectTool On") + }; + Toolbar.s_ViewToolIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("ViewToolOrbit"), + EditorGUIUtility.IconContent("ViewToolMove"), + EditorGUIUtility.IconContent("ViewToolZoom"), + EditorGUIUtility.IconContent("ViewToolOrbit"), + EditorGUIUtility.IconContent("ViewToolOrbit On"), + EditorGUIUtility.IconContent("ViewToolMove On"), + EditorGUIUtility.IconContent("ViewToolZoom On"), + EditorGUIUtility.IconContent("ViewToolOrbit On") + }; + Toolbar.s_PivotIcons = new GUIContent[] + { + EditorGUIUtility.TextContent("ToolHandleCenter"), + EditorGUIUtility.TextContent("ToolHandlePivot") + }; + Toolbar.s_PivotRotation = new GUIContent[] + { + EditorGUIUtility.TextContent("ToolHandleLocal"), + EditorGUIUtility.TextContent("ToolHandleGlobal") + }; + Toolbar.s_LayerContent = EditorGUIUtility.TextContent("ToolbarLayers"); + Toolbar.s_PlayIcons = new GUIContent[] + { + EditorGUIUtility.IconContent("PlayButton"), + EditorGUIUtility.IconContent("PauseButton"), + EditorGUIUtility.IconContent("StepButton"), + EditorGUIUtility.IconContent("PlayButtonProfile"), + EditorGUIUtility.IconContent("PlayButton On"), + EditorGUIUtility.IconContent("PauseButton On"), + EditorGUIUtility.IconContent("StepButton On"), + EditorGUIUtility.IconContent("PlayButtonProfile On"), + EditorGUIUtility.IconContent("PlayButton Anim"), + EditorGUIUtility.IconContent("PauseButton Anim"), + EditorGUIUtility.IconContent("StepButton Anim"), + EditorGUIUtility.IconContent("PlayButtonProfile Anim") + }; + } public void OnEnable() { EditorApplication.modifierKeysChanged = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.modifierKeysChanged, new EditorApplication.CallbackFunction(base.Repaint)); @@ -90,10 +103,12 @@ protected override bool OnFocus() private void OnSelectionChange() { Tools.OnSelectionChange(); + EditMode.OnSelectionChange(); base.Repaint(); } private void OnGUI() { + Toolbar.InitializeToolIcons(); bool isPlayingOrWillChangePlaymode = EditorApplication.isPlayingOrWillChangePlaymode; if (isPlayingOrWillChangePlaymode) { diff --git a/UnityEditor/UnityEditor/Tools.cs b/UnityEditor/UnityEditor/Tools.cs index 34df6a87..16334e2f 100644 --- a/UnityEditor/UnityEditor/Tools.cs +++ b/UnityEditor/UnityEditor/Tools.cs @@ -5,8 +5,9 @@ namespace UnityEditor { public sealed class Tools : ScriptableObject { + internal delegate void OnToolChangedFunc(Tool from, Tool to); private static Tools s_Get; - internal static Tool s_LockedTool = Tool.None; + internal static Tools.OnToolChangedFunc onToolChanged; internal static ViewTool s_LockedViewTool = ViewTool.None; internal static int s_ButtonDown = -1; private PivotMode m_PivotMode; @@ -49,13 +50,18 @@ public static Tool current { get { - return (Tools.s_LockedTool != Tool.None) ? Tools.s_LockedTool : Tools.get.currentTool; + return Tools.get.currentTool; } set { if (Tools.get.currentTool != value) { + Tool from = Tools.get.currentTool; Tools.get.currentTool = value; + if (Tools.onToolChanged != null) + { + Tools.onToolChanged(from, value); + } Tools.RepaintAllToolViews(); } } @@ -65,7 +71,7 @@ public static ViewTool viewTool get { Event current = Event.current; - if (Tools.viewToolActive) + if (current != null && Tools.viewToolActive) { if (Tools.s_LockedViewTool == ViewTool.None) { @@ -305,7 +311,7 @@ internal static Vector3 GetHandlePosition() { return Tools.handleRotation * InternalEditorUtility.CalculateSelectionBoundsInSpace(Vector3.zero, Tools.handleRotation, Tools.rectBlueprintMode).center + b; } - return InternalEditorUtility.CalculateSelectionBounds(true).center + b; + return InternalEditorUtility.CalculateSelectionBounds(true, false).center + b; } } private static int GetRectAxisForViewDir(Bounds bounds, Quaternion rotation, Vector3 viewDir) diff --git a/UnityEditor/UnityEditor/TooltipView.cs b/UnityEditor/UnityEditor/TooltipView.cs index 173d8c4b..e2e3edde 100644 --- a/UnityEditor/UnityEditor/TooltipView.cs +++ b/UnityEditor/UnityEditor/TooltipView.cs @@ -30,10 +30,7 @@ private void Setup(string tooltip, Rect rect) { this.m_hoverRect = rect; this.m_tooltip.text = tooltip; - if (this.m_Style == null) - { - this.m_Style = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle("Tooltip"); - } + this.m_Style = EditorStyles.tooltip; this.m_Style.wordWrap = false; this.m_optimalSize = this.m_Style.CalcSize(this.m_tooltip); if (this.m_optimalSize.x > 300f) @@ -47,6 +44,7 @@ private void Setup(string tooltip, Rect rect) this.m_tooltipContainer.ShowPopup(); this.m_tooltipContainer.SetAlpha(1f); TooltipView.s_guiView.mouseRayInvisible = true; + base.RepaintImmediately(); } public static void Show(string tooltip, Rect rect) { diff --git a/UnityEditor/UnityEditor/TrailRendererInspector.cs b/UnityEditor/UnityEditor/TrailRendererInspector.cs new file mode 100644 index 00000000..5d3559aa --- /dev/null +++ b/UnityEditor/UnityEditor/TrailRendererInspector.cs @@ -0,0 +1,19 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + [CanEditMultipleObjects, CustomEditor(typeof(TrailRenderer))] + internal class TrailRendererInspector : RendererEditorBase + { + public override void OnEnable() + { + base.OnEnable(); + } + public override void OnInspectorGUI() + { + base.serializedObject.Update(); + Editor.DrawPropertiesExcluding(this.m_SerializedObject, new string[0]); + base.serializedObject.ApplyModifiedProperties(); + } + } +} diff --git a/UnityEditor/UnityEditor/TransformRotationGUI.cs b/UnityEditor/UnityEditor/TransformRotationGUI.cs index 0d47f1c1..e14860cc 100644 --- a/UnityEditor/UnityEditor/TransformRotationGUI.cs +++ b/UnityEditor/UnityEditor/TransformRotationGUI.cs @@ -31,11 +31,10 @@ public void RotationField(bool disabled) this.m_OldQuaternion = localRotation; } bool flag = false; - UnityEngine.Object[] array = this.targets; - for (int i = 0; i < array.Length; i++) + for (int i = 1; i < this.targets.Length; i++) { - Transform transform2 = (Transform)array[i]; - flag |= (transform2.localEulerAngles != this.m_EulerAngles); + Quaternion localRotation2 = (this.targets[i] as Transform).localRotation; + flag |= (localRotation2.x != localRotation.x || localRotation2.y != localRotation.y || localRotation2.z != localRotation.z || localRotation2.w != localRotation.w); } Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (float)((!EditorGUIUtility.wideMode) ? 2 : 1), new GUILayoutOption[0]); GUIContent label = EditorGUI.BeginProperty(rect, this.rotationContent, this.m_Rotation); @@ -50,14 +49,14 @@ public void RotationField(bool disabled) if (EditorGUI.EndChangeCheck()) { Undo.RecordObjects(this.targets, "Inspector"); - UnityEngine.Object[] array2 = this.targets; - for (int j = 0; j < array2.Length; j++) + UnityEngine.Object[] array = this.targets; + for (int j = 0; j < array.Length; j++) { - Transform transform3 = (Transform)array2[j]; - transform3.localEulerAngles = this.m_EulerAngles; - if (transform3.parent != null) + Transform transform2 = (Transform)array[j]; + transform2.localEulerAngles = this.m_EulerAngles; + if (transform2.parent != null) { - transform3.SendTransformChangedScale(); + transform2.SendTransformChangedScale(); } } this.m_Rotation.serializedObject.SetIsDifferentCacheDirty(); diff --git a/UnityEditor/UnityEditor/TransformSort.cs b/UnityEditor/UnityEditor/TransformSort.cs index b53d287e..65bdc863 100644 --- a/UnityEditor/UnityEditor/TransformSort.cs +++ b/UnityEditor/UnityEditor/TransformSort.cs @@ -4,8 +4,7 @@ namespace UnityEditor { public class TransformSort : BaseHierarchySort { - private const string kDefaultSorting = "DefaultSorting"; - private GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("DefaultSorting"), "Transform child order"); + private readonly GUIContent m_Content = new GUIContent(EditorGUIUtility.FindTexture("DefaultSorting"), "Transform Child Order"); public override GUIContent content { get diff --git a/UnityEditor/UnityEditor/TransitionPreview.cs b/UnityEditor/UnityEditor/TransitionPreview.cs index ea5062d7..c9f50b96 100644 --- a/UnityEditor/UnityEditor/TransitionPreview.cs +++ b/UnityEditor/UnityEditor/TransitionPreview.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -13,8 +13,8 @@ private class ParameterInfo } private class TransitionInfo { - private State m_SrcState; - private State m_DstState; + private AnimatorState m_SrcState; + private AnimatorState m_DstState; private float m_TransitionDuration; private float m_TransitionOffset; private float m_ExitTime; @@ -34,31 +34,15 @@ private void Init() this.m_TransitionOffset = 0f; this.m_ExitTime = 0.5f; } - public void Set(Transition transition, State srcState) + public void Set(AnimatorStateTransition transition, AnimatorState srcState, AnimatorState dstState) { if (transition != null) { - if (srcState != null) - { - this.m_SrcState = srcState; - } - else - { - this.m_SrcState = transition.srcState; - } - this.m_DstState = transition.dstState; + this.m_SrcState = srcState; + this.m_DstState = dstState; this.m_TransitionDuration = transition.duration; this.m_TransitionOffset = transition.offset; this.m_ExitTime = 0.5f; - for (int i = 0; i < transition.conditionCount; i++) - { - AnimatorCondition condition = transition.GetCondition(i); - if (condition.mode == TransitionConditionMode.ExitTime) - { - this.m_ExitTime = condition.exitTime; - break; - } - } } else { @@ -69,23 +53,26 @@ public void Set(Transition transition, State srcState) private AvatarPreview m_AvatarPreview; private Timeline m_Timeline; private AnimatorController m_Controller; - private StateMachine m_StateMachine; + private AnimatorStateMachine m_StateMachine; private List m_ParameterMinMax = new List(); private List m_ParameterInfoList; - private Transition m_RefTransition; + private AnimatorStateTransition m_RefTransition; private TransitionPreview.TransitionInfo m_RefTransitionInfo = new TransitionPreview.TransitionInfo(); - private Transition m_Transition; - private State m_SrcState; - private State m_DstState; - private State m_RefSrcState; + private AnimatorStateTransition m_Transition; + private AnimatorState m_SrcState; + private AnimatorState m_DstState; + private AnimatorState m_RefSrcState; + private AnimatorState m_RefDstState; + private Motion m_SrcMotion; + private Motion m_DstMotion; private bool m_ShowBlendValue; private bool m_MustResample = true; private bool m_MustSampleMotions; private float m_LastEvalTime = -1f; + private bool m_IsResampling; private AvatarMask m_LayerMask; private int m_LayerIndex; - private int m_MotionSetIndex; - private float m_ExitTime = 0.5f; + private bool m_ValidTransition = true; private float m_LeftStateWeightA; private float m_LeftStateWeightB = 1f; private float m_LeftStateTimeA; @@ -121,57 +108,27 @@ private int FindParameterInfo(List parameterInf } return num; } - private bool HasExitTime(Transition t) + private void SetMotion(AnimatorState state, int layerIndex, Motion motion) { - for (int i = 0; i < t.conditionCount; i++) - { - if (t.GetCondition(i).mode == TransitionConditionMode.ExitTime) - { - return true; - } - } - return false; - } - private void SetExitTime(Transition t, float time) - { - for (int i = 0; i < t.conditionCount; i++) - { - AnimatorCondition condition = t.GetCondition(i); - if (condition.mode == TransitionConditionMode.ExitTime) - { - condition.exitTime = time; - break; - } - } - this.m_ExitTime = time; + AnimatorControllerLayer[] layers = this.m_Controller.layers; + state.motion = motion; + this.m_Controller.layers = layers; } - private float GetExitTime(Transition t) - { - for (int i = 0; i < t.conditionCount; i++) - { - AnimatorCondition condition = t.GetCondition(i); - if (condition.mode == TransitionConditionMode.ExitTime) - { - return condition.exitTime; - } - } - return this.m_ExitTime; - } - private void CopyStateForPreview(State src, ref State dst) + private void CopyStateForPreview(AnimatorState src, ref AnimatorState dst) { dst.name = src.name; dst.iKOnFeet = src.iKOnFeet; dst.speed = src.speed; dst.mirror = src.mirror; - dst.SetMotionInternal(src.GetMotionInternal(this.m_MotionSetIndex)); + dst.motion = src.motion; } - private void CopyTransitionForPreview(Transition src, ref Transition dst) + private void CopyTransitionForPreview(AnimatorStateTransition src, ref AnimatorStateTransition dst) { if (src != null) { dst.duration = src.duration; dst.offset = src.offset; - this.SetExitTime(dst, this.GetExitTime(src)); + dst.exitTime = src.exitTime; } } private bool MustResample(TransitionPreview.TransitionInfo info) @@ -182,20 +139,21 @@ private void WriteParametersInController() { if (this.m_Controller) { - int parameterCount = this.m_Controller.parameterCount; - for (int i = 0; i < parameterCount; i++) + int num = this.m_Controller.parameters.Length; + for (int i = 0; i < num; i++) { - string parameterName = this.m_Controller.GetParameterName(i); - int num = this.FindParameterInfo(this.m_ParameterInfoList, parameterName); - if (num != -1) + string name = this.m_Controller.parameters[i].name; + int num2 = this.FindParameterInfo(this.m_ParameterInfoList, name); + if (num2 != -1) { - this.m_AvatarPreview.Animator.SetFloat(parameterName, this.m_ParameterInfoList[num].m_Value); + this.m_AvatarPreview.Animator.SetFloat(name, this.m_ParameterInfoList[num2].m_Value); } } } } - private void ResampleTransition(Transition transition, AvatarMask layerMask, TransitionPreview.TransitionInfo info, Animator previewObject) + private void ResampleTransition(AnimatorStateTransition transition, AvatarMask layerMask, TransitionPreview.TransitionInfo info, Animator previewObject) { + this.m_IsResampling = true; this.m_MustResample = false; bool flag = this.m_RefTransition != transition; this.m_RefTransition = transition; @@ -207,8 +165,8 @@ private void ResampleTransition(Transition transition, AvatarMask layerMask, Tra this.m_AvatarPreview = null; } this.ClearController(); - Motion motion = (!transition.srcState) ? this.m_RefSrcState.GetMotionInternal(this.m_MotionSetIndex) : transition.srcState.GetMotionInternal(this.m_MotionSetIndex); - this.Init(previewObject, (!(motion != null)) ? transition.dstState.GetMotionInternal(this.m_MotionSetIndex) : motion); + Motion motion = this.m_RefSrcState.motion; + this.Init(previewObject, (!(motion != null)) ? this.m_RefDstState.motion : motion); if (this.m_Controller == null) { return; @@ -232,16 +190,20 @@ private void ResampleTransition(Transition transition, AvatarMask layerMask, Tra { this.m_AvatarPreview.Animator.stabilizeFeet = false; } - float num = length2 * this.GetExitTime(this.m_RefTransition) + length2 * this.m_Transition.duration + length; + float num = length2 * this.m_RefTransition.exitTime + length2 * this.m_Transition.duration + length; if (num > 2000f) { Debug.LogWarning("Transition duration is longer than 2000 second, Disabling previewer."); + this.m_ValidTransition = false; return; } - float num2 = (length2 <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length2 / 300f, 0.0333333351f), length2 / 5f); - float num3 = (length <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length / 300f, 0.0333333351f), length / 5f); - float num4 = num2; - float num5 = 0f; + float num2 = (this.m_RefTransition.exitTime <= 0f) ? length2 : (length2 * this.m_RefTransition.exitTime); + float num3 = (num2 <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(num2 / 300f, 0.0333333351f), num2 / 5f); + float num4 = (length <= 0f) ? 0.0333333351f : Mathf.Min(Mathf.Max(length / 300f, 0.0333333351f), length / 5f); + num3 = Mathf.Max(num3, num / 300f); + num4 = Mathf.Max(num4, num / 300f); + float num5 = num3; + float num6 = 0f; bool flag2 = false; bool flag3 = false; bool flag4 = false; @@ -249,82 +211,90 @@ private void ResampleTransition(Transition transition, AvatarMask layerMask, Tra this.m_LeftStateWeightA = 0f; this.m_LeftStateTimeA = 0f; this.m_AvatarPreview.Animator.Update(0f); + int num7 = 0; while (!flag4) { - this.m_AvatarPreview.Animator.Update(num4); + num7++; + this.m_AvatarPreview.Animator.Update(num5); AnimatorStateInfo currentAnimatorStateInfo = this.m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(this.m_LayerIndex); - num5 += num4; + num6 += num5; if (!flag2) { this.m_LeftStateWeightA = currentAnimatorStateInfo.normalizedTime; - this.m_LeftStateTimeA = num5; + this.m_LeftStateTimeA = num6; flag2 = true; } - if (flag3 && num5 >= num) + if (flag3 && num6 >= num) { flag4 = true; } - if (!flag3 && currentAnimatorStateInfo.IsName(this.m_DstState.uniqueName)) + if (!flag3 && currentAnimatorStateInfo.IsName(this.m_DstState.name)) { this.m_RightStateWeightA = currentAnimatorStateInfo.normalizedTime; - this.m_RightStateTimeA = num5; + this.m_RightStateTimeA = num6; flag3 = true; } if (!flag3) { this.m_LeftStateWeightB = currentAnimatorStateInfo.normalizedTime; - this.m_LeftStateTimeB = num5; + this.m_LeftStateTimeB = num6; } if (flag3) { this.m_RightStateWeightB = currentAnimatorStateInfo.normalizedTime; - this.m_RightStateTimeB = num5; + this.m_RightStateTimeB = num6; } if (this.m_AvatarPreview.Animator.IsInTransition(this.m_LayerIndex)) { - num4 = num3; + num5 = num4; } } - float stopTime = num5; + float stopTime = num6; this.m_AvatarPreview.Animator.StopRecording(); - float num6 = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); - float num7 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); + if (Mathf.Approximately(this.m_LeftStateWeightB, this.m_LeftStateWeightA) || Mathf.Approximately(this.m_RightStateWeightB, this.m_RightStateWeightA)) + { + Debug.LogWarning("Speed difference between states is too big. Transition preview will be disabled."); + this.m_ValidTransition = false; + return; + } + float num8 = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); + float num9 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); if (this.m_MustSampleMotions) { this.m_MustSampleMotions = false; this.m_SrcPivotList.Clear(); this.m_DstPivotList.Clear(); - num4 = num3; + num5 = num4; this.m_StateMachine.defaultState = this.m_DstState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); - num5 = 0f; - while (num5 <= num7) + num6 = 0f; + while (num6 <= num9) { - this.m_AvatarPreview.Animator.Update(num4 * 2f); - num5 += num4 * 2f; + this.m_AvatarPreview.Animator.Update(num5 * 2f); + num6 += num5 * 2f; Timeline.PivotSample pivotSample = new Timeline.PivotSample(); - pivotSample.m_Time = num5; + pivotSample.m_Time = num6; pivotSample.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_DstPivotList.Add(pivotSample); } - num4 = num2; + num5 = num3; this.m_StateMachine.defaultState = this.m_SrcState; this.m_Transition.mute = true; AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); this.m_AvatarPreview.Animator.Update(1E-07f); this.WriteParametersInController(); this.m_AvatarPreview.Animator.SetLayerWeight(this.m_LayerIndex, 1f); - num5 = 0f; - while (num5 <= num6) + num6 = 0f; + while (num6 <= num8) { - this.m_AvatarPreview.Animator.Update(num4 * 2f); - num5 += num4 * 2f; + this.m_AvatarPreview.Animator.Update(num5 * 2f); + num6 += num5 * 2f; Timeline.PivotSample pivotSample2 = new Timeline.PivotSample(); - pivotSample2.m_Time = num5; + pivotSample2.m_Time = num6; pivotSample2.m_Weight = this.m_AvatarPreview.Animator.pivotWeight; this.m_SrcPivotList.Add(pivotSample2); } @@ -337,33 +307,24 @@ private void ResampleTransition(Transition transition, AvatarMask layerMask, Tra this.m_AvatarPreview.timeControl.currentTime = this.m_Timeline.Time; if (flag) { - Timeline arg_6DE_0 = this.m_Timeline; - float num8 = this.m_AvatarPreview.timeControl.currentTime = (this.m_AvatarPreview.timeControl.startTime = 0f); - this.m_Timeline.StartTime = num8; - arg_6DE_0.Time = num8; + Timeline arg_74F_0 = this.m_Timeline; + float num10 = this.m_AvatarPreview.timeControl.currentTime = (this.m_AvatarPreview.timeControl.startTime = 0f); + this.m_Timeline.StartTime = num10; + arg_74F_0.Time = num10; this.m_Timeline.ResetRange(); } this.m_AvatarPreview.Animator.StartPlayback(); + this.m_IsResampling = false; } - public void SetAnyStateTransition(Transition transition, State sourceState, AvatarMask layerMask, int motionSetIndex, Animator previewObject) - { - TransitionPreview.TransitionInfo transitionInfo = new TransitionPreview.TransitionInfo(); - transitionInfo.Set(transition, sourceState); - this.m_MotionSetIndex = motionSetIndex; - if (this.MustResample(transitionInfo)) - { - this.m_RefSrcState = sourceState; - this.ResampleTransition(transition, layerMask, transitionInfo, previewObject); - } - } - public void SetTransition(Transition transition, AvatarMask layerMask, int motionSetIndex, Animator previewObject) + public void SetTransition(AnimatorStateTransition transition, AnimatorState sourceState, AnimatorState destinationState, AnimatorControllerLayer srcLayer, Animator previewObject) { + this.m_RefSrcState = sourceState; + this.m_RefDstState = destinationState; TransitionPreview.TransitionInfo transitionInfo = new TransitionPreview.TransitionInfo(); - transitionInfo.Set(transition, null); - this.m_MotionSetIndex = motionSetIndex; + transitionInfo.Set(transition, sourceState, destinationState); if (this.MustResample(transitionInfo)) { - this.ResampleTransition(transition, layerMask, transitionInfo, previewObject); + this.ResampleTransition(transition, srcLayer.avatarMask, transitionInfo, previewObject); } } private void OnPreviewAvatarChanged() @@ -392,13 +353,13 @@ private void ClearController() private void CreateParameterInfoList() { this.m_ParameterInfoList = new List(); - if (this.m_Controller) + if (this.m_Controller && this.m_Controller.parameters != null) { - int parameterCount = this.m_Controller.parameterCount; - for (int i = 0; i < parameterCount; i++) + int num = this.m_Controller.parameters.Length; + for (int i = 0; i < num; i++) { TransitionPreview.ParameterInfo parameterInfo = new TransitionPreview.ParameterInfo(); - parameterInfo.m_Name = this.m_Controller.GetParameterName(i); + parameterInfo.m_Name = this.m_Controller.parameters[i].name; this.m_ParameterInfoList.Add(parameterInfo); } } @@ -409,7 +370,8 @@ private void CreateController() { this.m_LayerIndex = 0; this.m_Controller = new AnimatorController(); - this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.pushUndo = false; + this.m_Controller.hideFlags = HideFlags.HideAndDontSave; this.m_Controller.AddLayer("preview"); bool flag = true; if (this.m_LayerMask != null) @@ -428,34 +390,37 @@ private void CreateController() { this.m_Controller.AddLayer("Additionnal"); this.m_LayerIndex++; - this.m_Controller.SetLayerMask(this.m_LayerIndex, this.m_LayerMask); + AnimatorControllerLayer[] layers = this.m_Controller.layers; + layers[this.m_LayerIndex].avatarMask = this.m_LayerMask; + this.m_Controller.layers = layers; } } - this.m_StateMachine = this.m_Controller.GetLayerStateMachine(this.m_LayerIndex); - State state = (!this.m_RefTransition.srcState) ? this.m_RefSrcState : this.m_RefTransition.srcState; + this.m_StateMachine = this.m_Controller.layers[this.m_LayerIndex].stateMachine; + this.m_StateMachine.pushUndo = false; + this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; + this.m_SrcMotion = this.m_RefSrcState.motion; + this.m_DstMotion = this.m_RefDstState.motion; this.m_ParameterMinMax.Clear(); - Motion motionInternal = state.GetMotionInternal(this.m_MotionSetIndex); - if (motionInternal && motionInternal is BlendTree) + if (this.m_SrcMotion && this.m_SrcMotion is BlendTree) { - BlendTree blendTree = motionInternal as BlendTree; + BlendTree blendTree = this.m_SrcMotion as BlendTree; for (int i = 0; i < blendTree.recursiveBlendParameterCount; i++) { string recursiveBlendParameter = blendTree.GetRecursiveBlendParameter(i); - if (this.m_Controller.FindParameter(recursiveBlendParameter) == -1) + if (this.m_Controller.IndexOfParameter(recursiveBlendParameter) == -1) { this.m_Controller.AddParameter(recursiveBlendParameter, AnimatorControllerParameterType.Float); this.m_ParameterMinMax.Add(new Vector2(blendTree.GetRecursiveBlendParameterMin(i), blendTree.GetRecursiveBlendParameterMax(i))); } } } - Motion motionInternal2 = this.m_RefTransition.dstState.GetMotionInternal(this.m_MotionSetIndex); - if (motionInternal2 && motionInternal2 is BlendTree) + if (this.m_DstMotion && this.m_DstMotion is BlendTree) { - BlendTree blendTree2 = motionInternal2 as BlendTree; + BlendTree blendTree2 = this.m_DstMotion as BlendTree; for (int j = 0; j < blendTree2.recursiveBlendParameterCount; j++) { string recursiveBlendParameter2 = blendTree2.GetRecursiveBlendParameter(j); - int num2 = this.m_Controller.FindParameter(recursiveBlendParameter2); + int num2 = this.m_Controller.IndexOfParameter(recursiveBlendParameter2); if (num2 == -1) { this.m_Controller.AddParameter(recursiveBlendParameter2, AnimatorControllerParameterType.Float); @@ -467,23 +432,35 @@ private void CreateController() } } } - this.m_SrcState = this.m_StateMachine.AddState(state.name); - this.m_SrcState.hideFlags = HideFlags.DontSave; - this.m_DstState = this.m_StateMachine.AddState(this.m_RefTransition.dstState.name); - this.m_DstState.hideFlags = HideFlags.DontSave; - this.CopyStateForPreview(state, ref this.m_SrcState); - this.CopyStateForPreview(this.m_RefTransition.dstState, ref this.m_DstState); - this.m_Transition = this.m_StateMachine.AddTransition(this.m_SrcState, this.m_DstState); + this.m_SrcState = this.m_StateMachine.AddState(this.m_RefSrcState.name); + this.m_SrcState.pushUndo = false; + this.m_SrcState.hideFlags = HideFlags.HideAndDontSave; + this.m_DstState = this.m_StateMachine.AddState(this.m_RefDstState.name); + this.m_DstState.pushUndo = false; + this.m_DstState.hideFlags = HideFlags.HideAndDontSave; + this.CopyStateForPreview(this.m_RefSrcState, ref this.m_SrcState); + this.CopyStateForPreview(this.m_RefDstState, ref this.m_DstState); + this.m_Transition = this.m_SrcState.AddTransition(this.m_DstState, true); + this.m_Transition.pushUndo = false; this.m_Transition.hideFlags = HideFlags.DontSave; this.CopyTransitionForPreview(this.m_RefTransition, ref this.m_Transition); this.DisableIKOnFeetIfNeeded(); AnimatorController.SetAnimatorController(this.m_AvatarPreview.Animator, this.m_Controller); + AnimatorController expr_400 = this.m_Controller; + expr_400.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_400.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + } + } + private void ControllerDirty() + { + if (!this.m_IsResampling) + { + this.m_MustResample = true; } } private void DisableIKOnFeetIfNeeded() { bool flag = false; - if (this.m_SrcState.GetMotion() == null || this.m_DstState.GetMotion() == null) + if (this.m_SrcMotion == null || this.m_DstMotion == null) { flag = true; } @@ -527,16 +504,17 @@ public void DoTransitionPreview() this.m_AvatarPreview.timeControl.Update(); } this.DoTimeline(); - if (this.m_Controller.parameterCount > 0) + AnimatorControllerParameter[] parameters = this.m_Controller.parameters; + if (parameters.Length > 0) { this.m_ShowBlendValue = EditorGUILayout.Foldout(this.m_ShowBlendValue, "BlendTree Parameters"); if (this.m_ShowBlendValue) { - for (int i = 0; i < this.m_Controller.parameterCount; i++) + for (int i = 0; i < parameters.Length; i++) { - string parameterName = this.m_Controller.GetParameterName(i); + AnimatorControllerParameter animatorControllerParameter = this.m_Controller.parameters[i]; float value = this.m_ParameterInfoList[i].m_Value; - float num = EditorGUILayout.Slider(parameterName, value, this.m_ParameterMinMax[i][0], this.m_ParameterMinMax[i][1], new GUILayoutOption[0]); + float num = EditorGUILayout.Slider(animatorControllerParameter.name, value, this.m_ParameterMinMax[i][0], this.m_ParameterMinMax[i][1], new GUILayoutOption[0]); if (num != value) { this.m_ParameterInfoList[i].m_Value = num; @@ -549,16 +527,20 @@ public void DoTransitionPreview() } private void DoTimeline() { + if (!this.m_ValidTransition) + { + return; + } float num = (this.m_LeftStateTimeB - this.m_LeftStateTimeA) / (this.m_LeftStateWeightB - this.m_LeftStateWeightA); float num2 = (this.m_RightStateTimeB - this.m_RightStateTimeA) / (this.m_RightStateWeightB - this.m_RightStateWeightA); float num3 = this.m_Transition.duration * num; this.m_Timeline.SrcStartTime = 0f; this.m_Timeline.SrcStopTime = num; this.m_Timeline.SrcName = this.m_SrcState.name; - this.m_Timeline.HasExitTime = this.HasExitTime(this.m_RefTransition); - this.m_Timeline.srcLoop = (this.m_SrcState.GetMotion() && this.m_SrcState.GetMotion().isLooping); - this.m_Timeline.dstLoop = (this.m_DstState.GetMotion() && this.m_DstState.GetMotion().isLooping); - this.m_Timeline.TransitionStartTime = this.GetExitTime(this.m_RefTransition) * num; + this.m_Timeline.HasExitTime = this.m_RefTransition.hasExitTime; + this.m_Timeline.srcLoop = (this.m_SrcMotion && this.m_SrcMotion.isLooping); + this.m_Timeline.dstLoop = (this.m_DstMotion && this.m_DstMotion.isLooping); + this.m_Timeline.TransitionStartTime = this.m_RefTransition.exitTime * num; this.m_Timeline.TransitionStopTime = this.m_Timeline.TransitionStartTime + num3; this.m_Timeline.Time = this.m_AvatarPreview.timeControl.currentTime; this.m_Timeline.DstStartTime = this.m_Timeline.TransitionStartTime - this.m_RefTransition.offset * num2; @@ -578,7 +560,7 @@ private void DoTimeline() if (flag) { Undo.RegisterCompleteObjectUndo(this.m_RefTransition, "Edit Transition"); - this.SetExitTime(this.m_RefTransition, this.m_Timeline.TransitionStartTime / this.m_Timeline.SrcDuration); + this.m_RefTransition.exitTime = this.m_Timeline.TransitionStartTime / this.m_Timeline.SrcDuration; this.m_RefTransition.duration = this.m_Timeline.TransitionDuration / this.m_Timeline.SrcDuration; this.m_RefTransition.offset = (this.m_Timeline.TransitionStartTime - this.m_Timeline.DstStartTime) / this.m_Timeline.DstDuration; } diff --git a/UnityEditor/UnityEditor/TreeAO.cs b/UnityEditor/UnityEditor/TreeAO.cs index 5dd44ae4..bd87c1e1 100644 --- a/UnityEditor/UnityEditor/TreeAO.cs +++ b/UnityEditor/UnityEditor/TreeAO.cs @@ -52,9 +52,9 @@ public static void CalcSoftOcclusion(Mesh mesh) { GameObject gameObject = new GameObject("Test"); gameObject.layer = 29; - MeshFilter meshFilter = (MeshFilter)gameObject.AddComponent("MeshFilter"); + MeshFilter meshFilter = gameObject.AddComponent(); meshFilter.mesh = mesh; - gameObject.AddComponent("MeshCollider"); + gameObject.AddComponent(); if (TreeAO.directions == null) { TreeAO.InitializeDirections(); @@ -84,9 +84,9 @@ public static void CalcSoftOcclusion(Mesh mesh) num /= (float)vertices.Length; for (int l = 0; l < vertices.Length; l++) { - Vector4[] expr_1E3_cp_0 = array2; - int expr_1E3_cp_1 = l; - expr_1E3_cp_0[expr_1E3_cp_1].w = expr_1E3_cp_0[expr_1E3_cp_1].w - num; + Vector4[] expr_1D4_cp_0 = array2; + int expr_1D4_cp_1 = l; + expr_1D4_cp_0[expr_1D4_cp_1].w = expr_1D4_cp_0[expr_1D4_cp_1].w - num; } mesh.tangents = array2; UnityEngine.Object.DestroyImmediate(gameObject); diff --git a/UnityEditor/UnityEditor/TreePainter.cs b/UnityEditor/UnityEditor/TreePainter.cs index 5d9f6ae1..95063d8f 100644 --- a/UnityEditor/UnityEditor/TreePainter.cs +++ b/UnityEditor/UnityEditor/TreePainter.cs @@ -6,35 +6,44 @@ internal class TreePainter { public static float brushSize = 40f; public static float spacing = 0.8f; + public static bool lockWidthToHeight = true; + public static bool randomRotation = true; + public static bool allowHeightVar = true; + public static bool allowWidthVar = true; public static float treeColorAdjustment = 0.4f; - public static float treeWidth = 1f; public static float treeHeight = 1f; - public static float treeWidthVariation = 0.1f; public static float treeHeightVariation = 0.1f; + public static float treeWidth = 1f; + public static float treeWidthVariation = 0.1f; public static int selectedTree; - public static Terrain terrain; private static Color GetTreeColor() { Color result = Color.white * UnityEngine.Random.Range(1f, 1f - TreePainter.treeColorAdjustment); result.a = 1f; return result; } + private static float GetTreeHeight() + { + float num = (!TreePainter.allowHeightVar) ? 0f : TreePainter.treeHeightVariation; + return TreePainter.treeHeight * UnityEngine.Random.Range(1f - num, 1f + num); + } private static float GetTreeWidth() { - return TreePainter.treeWidth * UnityEngine.Random.Range(1f - TreePainter.treeWidthVariation, 1f + TreePainter.treeWidthVariation); + float num = (!TreePainter.allowWidthVar) ? 0f : TreePainter.treeWidthVariation; + return TreePainter.treeWidth * UnityEngine.Random.Range(1f - num, 1f + num); } - private static float GetTreeHeight() + private static float GetTreeRotation() { - return TreePainter.treeHeight * UnityEngine.Random.Range(1f - TreePainter.treeHeightVariation, 1f + TreePainter.treeHeightVariation); + return (!TreePainter.randomRotation) ? 0f : UnityEngine.Random.Range(0f, 6.28318548f); } - public static void PlaceTrees(float xBase, float yBase) + public static void PlaceTrees(Terrain terrain, float xBase, float yBase) { - if (TreePainter.terrain.terrainData.treePrototypes.Length == 0) + if (terrain.terrainData.treePrototypes.Length == 0) { return; } - TreePainter.selectedTree = Mathf.Min(TerrainInspectorUtil.GetPrototypeCount(TreePainter.terrain.terrainData) - 1, TreePainter.selectedTree); - if (!TerrainInspectorUtil.PrototypeHasMaterials(TreePainter.terrain.terrainData, TreePainter.selectedTree)) + TreePainter.selectedTree = Mathf.Min(TerrainInspectorUtil.GetPrototypeCount(terrain.terrainData) - 1, TreePainter.selectedTree); + if (!TerrainInspectorUtil.PrototypeIsRenderable(terrain.terrainData, TreePainter.selectedTree)) { return; } @@ -44,15 +53,16 @@ public static void PlaceTrees(float xBase, float yBase) instance.color = TreePainter.GetTreeColor(); instance.lightmapColor = Color.white; instance.prototypeIndex = TreePainter.selectedTree; - instance.widthScale = TreePainter.GetTreeWidth(); instance.heightScale = TreePainter.GetTreeHeight(); + instance.widthScale = ((!TreePainter.lockWidthToHeight) ? TreePainter.GetTreeWidth() : instance.heightScale); + instance.rotation = TreePainter.GetTreeRotation(); bool flag = Event.current.type == EventType.MouseDrag || TreePainter.brushSize > 1f; - if (!flag || TerrainInspectorUtil.CheckTreeDistance(TreePainter.terrain.terrainData, instance.position, instance.prototypeIndex, TreePainter.spacing)) + if (!flag || TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, instance.position, instance.prototypeIndex, TreePainter.spacing)) { - TreePainter.terrain.AddTreeInstance(instance); + terrain.AddTreeInstance(instance); num++; } - Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(TreePainter.terrain.terrainData, TreePainter.selectedTree); + Vector3 prototypeExtent = TerrainInspectorUtil.GetPrototypeExtent(terrain.terrainData, TreePainter.selectedTree); prototypeExtent.y = 0f; float num2 = TreePainter.brushSize / (prototypeExtent.magnitude * TreePainter.spacing * 0.5f); int num3 = (int)(num2 * num2 * 0.5f); @@ -61,32 +71,70 @@ public static void PlaceTrees(float xBase, float yBase) while (num4 < num3 && num < num3) { Vector2 insideUnitCircle = UnityEngine.Random.insideUnitCircle; - insideUnitCircle.x *= TreePainter.brushSize / TreePainter.terrain.terrainData.size.x; - insideUnitCircle.y *= TreePainter.brushSize / TreePainter.terrain.terrainData.size.z; + insideUnitCircle.x *= TreePainter.brushSize / terrain.terrainData.size.x; + insideUnitCircle.y *= TreePainter.brushSize / terrain.terrainData.size.z; Vector3 position = new Vector3(xBase + insideUnitCircle.x, 0f, yBase + insideUnitCircle.y); - if (position.x >= 0f && position.x <= 1f && position.z >= 0f && position.z <= 1f && TerrainInspectorUtil.CheckTreeDistance(TreePainter.terrain.terrainData, position, TreePainter.selectedTree, TreePainter.spacing * 0.5f)) + if (position.x >= 0f && position.x <= 1f && position.z >= 0f && position.z <= 1f && TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, position, TreePainter.selectedTree, TreePainter.spacing * 0.5f)) { instance = default(TreeInstance); instance.position = position; instance.color = TreePainter.GetTreeColor(); instance.lightmapColor = Color.white; instance.prototypeIndex = TreePainter.selectedTree; - instance.widthScale = TreePainter.GetTreeWidth(); instance.heightScale = TreePainter.GetTreeHeight(); - TreePainter.terrain.AddTreeInstance(instance); + instance.widthScale = ((!TreePainter.lockWidthToHeight) ? TreePainter.GetTreeWidth() : instance.heightScale); + instance.rotation = TreePainter.GetTreeRotation(); + terrain.AddTreeInstance(instance); num++; } num4++; } } - private float GetTreePlacementSize(float treeCount) + private float GetTreePlacementSize(TerrainData terrainData, float treeCount) + { + return TerrainInspectorUtil.GetTreePlacementSize(terrainData, TreePainter.selectedTree, TreePainter.spacing, treeCount); + } + public static void RemoveTrees(Terrain terrain, float xBase, float yBase, bool clearSelectedOnly) { - return TerrainInspectorUtil.GetTreePlacementSize(TreePainter.terrain.terrainData, TreePainter.selectedTree, TreePainter.spacing, treeCount); + float radius = TreePainter.brushSize / terrain.terrainData.size.x; + terrain.RemoveTrees(new Vector2(xBase, yBase), radius, (!clearSelectedOnly) ? -1 : TreePainter.selectedTree); } - public static void RemoveTrees(float xBase, float yBase, bool clearSelectedOnly) + public static void MassPlaceTrees(TerrainData terrainData, int numberOfTrees, bool randomTreeColor, bool keepExistingTrees) { - float radius = TreePainter.brushSize / TreePainter.terrain.terrainData.size.x; - TreePainter.terrain.RemoveTrees(new Vector2(xBase, yBase), radius, (!clearSelectedOnly) ? -1 : TreePainter.selectedTree); + int num = terrainData.treePrototypes.Length; + if (num == 0) + { + Debug.Log("Can't place trees because no prototypes are defined"); + return; + } + Undo.RegisterCompleteObjectUndo(terrainData, "Mass Place Trees"); + TreeInstance[] array = new TreeInstance[numberOfTrees]; + int i = 0; + while (i < array.Length) + { + TreeInstance treeInstance = default(TreeInstance); + treeInstance.position = new Vector3(UnityEngine.Random.value, 0f, UnityEngine.Random.value); + if (terrainData.GetSteepness(treeInstance.position.x, treeInstance.position.z) < 30f) + { + treeInstance.color = ((!randomTreeColor) ? Color.white : TreePainter.GetTreeColor()); + treeInstance.lightmapColor = Color.white; + treeInstance.prototypeIndex = UnityEngine.Random.Range(0, num); + treeInstance.heightScale = TreePainter.GetTreeHeight(); + treeInstance.widthScale = ((!TreePainter.lockWidthToHeight) ? TreePainter.GetTreeWidth() : treeInstance.heightScale); + treeInstance.rotation = TreePainter.GetTreeRotation(); + array[i++] = treeInstance; + } + } + if (keepExistingTrees) + { + TreeInstance[] treeInstances = terrainData.treeInstances; + TreeInstance[] array2 = new TreeInstance[treeInstances.Length + array.Length]; + Array.Copy(treeInstances, 0, array2, 0, treeInstances.Length); + Array.Copy(array, 0, array2, treeInstances.Length, array.Length); + array = array2; + } + terrainData.treeInstances = array; + terrainData.RecalculateTreePositions(); } } } diff --git a/UnityEditor/UnityEditor/TreePlacementUtility.cs b/UnityEditor/UnityEditor/TreePlacementUtility.cs deleted file mode 100644 index 0511beb5..00000000 --- a/UnityEditor/UnityEditor/TreePlacementUtility.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using UnityEngine; -namespace UnityEditor -{ - internal class TreePlacementUtility - { - public static void PlaceRandomTrees(TerrainData terrainData, int treeCount) - { - int num = terrainData.treePrototypes.Length; - if (num == 0) - { - Debug.Log("Can't place trees because no prototypes are defined"); - return; - } - Undo.RegisterCompleteObjectUndo(terrainData, "Mass Place Trees"); - TreeInstance[] array = new TreeInstance[treeCount]; - int i = 0; - while (i < array.Length) - { - TreeInstance treeInstance = default(TreeInstance); - treeInstance.position = new Vector3(UnityEngine.Random.value, 0f, UnityEngine.Random.value); - if (terrainData.GetSteepness(treeInstance.position.x, treeInstance.position.z) < 30f) - { - Color color = Color.Lerp(Color.white, Color.gray * 0.7f, UnityEngine.Random.value); - color.a = 1f; - treeInstance.color = color; - treeInstance.lightmapColor = Color.white; - treeInstance.prototypeIndex = UnityEngine.Random.Range(0, num); - treeInstance.widthScale = 1f; - treeInstance.heightScale = 1f; - array[i] = treeInstance; - i++; - } - } - terrainData.treeInstances = array; - terrainData.RecalculateTreePositions(); - } - } -} diff --git a/UnityEditor/UnityEditor/TreeView.cs b/UnityEditor/UnityEditor/TreeView.cs index e838c595..1b1ffcf5 100644 --- a/UnityEditor/UnityEditor/TreeView.cs +++ b/UnityEditor/UnityEditor/TreeView.cs @@ -41,6 +41,16 @@ public Action keyboardInputCallback get; set; } + public Action expandedStateChanged + { + get; + set; + } + public Action searchChanged + { + get; + set; + } public Action onGUIRowCallback { get; @@ -71,6 +81,29 @@ public bool deselectOnUnhandledMouseDown get; set; } + public bool isSearching + { + get + { + return !string.IsNullOrEmpty(this.state.searchString); + } + } + public string searchString + { + get + { + return this.state.searchString; + } + set + { + this.state.searchString = value; + this.data.OnSearchChanged(); + if (this.searchChanged != null) + { + this.searchChanged(this.state.searchString); + } + } + } public TreeView(EditorWindow editorWindow, TreeViewState treeViewState) { this.m_EditorWindow = editorWindow; @@ -330,7 +363,7 @@ public void OnGUI(Rect rect, int keyboardControlID) } List visibleRows = this.data.GetVisibleRows(); Vector2 totalSize = this.gui.GetTotalSize(visibleRows); - Rect viewRect = new Rect(0f, 0f, totalSize.x, totalSize.y + this.gui.halfDropBetweenHeight * 2f); + Rect viewRect = new Rect(0f, 0f, totalSize.x, totalSize.y); if (this.m_UseScrollView) { this.state.scrollPos = GUI.BeginScrollView(this.m_TotalRect, this.state.scrollPos, viewRect); @@ -367,18 +400,20 @@ private void HandleUnusedEvents() switch (type) { case EventType.DragUpdated: - if (this.dragging != null) + if (this.dragging != null && this.m_TotalRect.Contains(Event.current.mousePosition)) { this.dragging.DragElement(null, default(Rect), false); this.Repaint(); + Event.current.Use(); } return; case EventType.DragPerform: - if (this.dragging != null) + if (this.dragging != null && this.m_TotalRect.Contains(Event.current.mousePosition)) { this.m_DragSelection.Clear(); this.dragging.DragElement(null, default(Rect), false); this.Repaint(); + Event.current.Use(); } return; case EventType.Ignore: @@ -606,11 +641,11 @@ public void OffsetSelection(int offset) { return; } + Event.current.Use(); int indexOfID = TreeView.GetIndexOfID(visibleRows, this.state.lastClickedID); int num = Mathf.Clamp(indexOfID + offset, 0, visibleRows.Count - 1); - this.SelectionByKey(visibleRows[num]); this.EnsureRowIsVisible(num, visibleRows); - Event.current.Use(); + this.SelectionByKey(visibleRows[num]); } private bool GetFirstAndLastSelected(List items, out int firstIndex, out int lastIndex) { diff --git a/UnityEditor/UnityEditor/TreeViewDataSource.cs b/UnityEditor/UnityEditor/TreeViewDataSource.cs index 7dea1e6d..e309031e 100644 --- a/UnityEditor/UnityEditor/TreeViewDataSource.cs +++ b/UnityEditor/UnityEditor/TreeViewDataSource.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; @@ -12,6 +11,7 @@ internal abstract class TreeViewDataSource : ITreeViewDataSource protected List m_VisibleRows; protected bool m_NeedRefreshVisibleFolders = true; protected TreeViewItem m_FakeItem; + public Action onVisibleRowsChanged; public bool showRootNode { get; @@ -22,6 +22,11 @@ public bool rootIsCollapsable get; set; } + public bool alwaysAddFirstItemToSearchResult + { + get; + set; + } public TreeViewItem root { get @@ -56,6 +61,10 @@ public virtual TreeViewItem FindItem(int id) { return TreeViewUtility.FindItem(id, this.m_RootItem); } + public virtual void OnSearchChanged() + { + this.m_NeedRefreshVisibleFolders = true; + } protected void GetVisibleItemsRecursive(TreeViewItem item, List items) { if (item != this.m_RootItem || this.showRootNode) @@ -70,13 +79,74 @@ protected void GetVisibleItemsRecursive(TreeViewItem item, List it } } } + protected void SearchRecursive(TreeViewItem item, string search, List searchResult) + { + if (item.displayName.ToLower().Contains(search)) + { + searchResult.Add(item); + } + foreach (TreeViewItem current in item.children) + { + this.SearchRecursive(current, search, searchResult); + } + } + protected virtual List ExpandedRows(TreeViewItem root) + { + List list = new List(); + this.GetVisibleItemsRecursive(this.m_RootItem, list); + return list; + } + protected virtual List Search(TreeViewItem root, string search) + { + List list = new List(); + if (this.showRootNode) + { + this.SearchRecursive(root, search, list); + list.Sort(new TreeViewItemAlphaNumericSort()); + } + else + { + int num = (!this.alwaysAddFirstItemToSearchResult) ? 0 : 1; + if (root.hasChildren) + { + for (int i = num; i < root.children.Count; i++) + { + this.SearchRecursive(root.children[i], search, list); + } + list.Sort(new TreeViewItemAlphaNumericSort()); + if (this.alwaysAddFirstItemToSearchResult) + { + list.Insert(0, root.children[0]); + } + } + } + return list; + } public virtual List GetVisibleRows() { if (this.m_VisibleRows == null || this.m_NeedRefreshVisibleFolders) { - this.m_VisibleRows = new List(); - this.GetVisibleItemsRecursive(this.m_RootItem, this.m_VisibleRows); + if (this.m_RootItem != null) + { + if (this.m_TreeView.isSearching) + { + this.m_VisibleRows = this.Search(this.m_RootItem, this.m_TreeView.searchString.ToLower()); + } + else + { + this.m_VisibleRows = this.ExpandedRows(this.m_RootItem); + } + } + else + { + Debug.LogError("TreeView root item is null. Ensure that your TreeViewDataSource sets up at least a root item."); + this.m_VisibleRows = new List(); + } this.m_NeedRefreshVisibleFolders = false; + if (this.onVisibleRowsChanged != null) + { + this.onVisibleRowsChanged(); + } this.m_TreeView.Repaint(); } return this.m_VisibleRows; @@ -103,7 +173,6 @@ public virtual bool SetExpanded(int id, bool expand) { if (expand) { - Assert.That(!this.expandedIDs.Contains(id)); this.expandedIDs.Add(id); this.expandedIDs.Sort(); } @@ -155,7 +224,7 @@ public virtual bool IsExpanded(TreeViewItem item) } public virtual bool IsExpandable(TreeViewItem item) { - return item.hasChildren; + return !this.m_TreeView.isSearching && item.hasChildren; } public virtual bool CanBeMultiSelected(TreeViewItem item) { @@ -167,6 +236,10 @@ public virtual bool CanBeParent(TreeViewItem item) } public virtual void OnExpandedStateChanged() { + if (this.m_TreeView.expandedStateChanged != null) + { + this.m_TreeView.expandedStateChanged(); + } } public virtual bool IsRenamingItemAllowed(TreeViewItem item) { diff --git a/UnityEditor/UnityEditor/TreeViewDragging.cs b/UnityEditor/UnityEditor/TreeViewDragging.cs index 66e3f6b2..45c2fa3b 100644 --- a/UnityEditor/UnityEditor/TreeViewDragging.cs +++ b/UnityEditor/UnityEditor/TreeViewDragging.cs @@ -6,7 +6,7 @@ namespace UnityEditor { internal abstract class TreeViewDragging : ITreeViewDragging { - private class DropData + protected class DropData { public int[] expandedArrayBeforeDrag; public int lastControlID; @@ -23,7 +23,7 @@ public enum DropPosition } private const double k_DropExpandTimeout = 0.7; protected TreeView m_TreeView; - private TreeViewDragging.DropData m_DropData = new TreeViewDragging.DropData(); + protected TreeViewDragging.DropData m_DropData = new TreeViewDragging.DropData(); public bool drawRowMarkerAbove { get; @@ -42,23 +42,28 @@ public int GetRowMarkerControlID() return this.m_DropData.rowMarkerControlID; } public abstract void StartDrag(TreeViewItem draggedItem, List draggedItemIDs); - public abstract DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dragPos); + public abstract DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, TreeViewDragging.DropPosition dropPosition); public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bool firstItem) { if (targetItem == null) { - DragAndDrop.visualMode = DragAndDropVisualMode.None; if (this.m_DropData != null) { this.m_DropData.dropTargetControlID = 0; this.m_DropData.rowMarkerControlID = 0; } + bool flag = Event.current.type == EventType.DragPerform; + DragAndDrop.visualMode = this.DoDrag(null, null, flag, TreeViewDragging.DropPosition.Below); + if (DragAndDrop.visualMode != DragAndDropVisualMode.None && flag) + { + this.FinalizeDragPerformed(true); + } return false; } Vector2 mousePosition = Event.current.mousePosition; - bool flag = this.m_TreeView.data.CanBeParent(targetItem); + bool flag2 = this.m_TreeView.data.CanBeParent(targetItem); Rect rect = targetItemRect; - float num = (!flag) ? (targetItemRect.height * 0.5f) : this.m_TreeView.gui.halfDropBetweenHeight; + float num = (!flag2) ? (targetItemRect.height * 0.5f) : this.m_TreeView.gui.halfDropBetweenHeight; if (firstItem) { rect.yMin -= num; @@ -69,13 +74,13 @@ public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bo return false; } TreeViewDragging.DropPosition dropPosition; - if (!flag || mousePosition.y >= targetItemRect.yMax - num) + if (!flag2 || mousePosition.y >= targetItemRect.yMax - num) { dropPosition = TreeViewDragging.DropPosition.Below; } else { - if (!flag || (firstItem && mousePosition.y <= targetItemRect.yMin + num)) + if (!flag2 || (firstItem && mousePosition.y <= targetItemRect.yMin + num)) { dropPosition = TreeViewDragging.DropPosition.Above; } @@ -106,23 +111,7 @@ public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bo } if (dragAndDropVisualMode != DragAndDropVisualMode.None) { - DragAndDrop.AcceptDrag(); - this.DragCleanup(false); - List list = new List(DragAndDrop.objectReferences); - bool draggedItemsFromOwnTreeView = true; - if (list.Count > 0 && TreeViewUtility.FindItemInList(list[0].GetInstanceID(), this.m_TreeView.data.GetVisibleRows()) == null) - { - draggedItemsFromOwnTreeView = false; - } - int[] array = new int[list.Count]; - for (int i = 0; i < list.Count; i++) - { - if (!(list[i] == null)) - { - array[i] = list[i].GetInstanceID(); - } - } - this.m_TreeView.NotifyListenersThatDragEnded(array, draggedItemsFromOwnTreeView); + this.FinalizeDragPerformed(false); } else { @@ -167,6 +156,26 @@ public virtual bool DragElement(TreeViewItem targetItem, Rect targetItemRect, bo Event.current.Use(); return true; } + private void FinalizeDragPerformed(bool revertExpanded) + { + this.DragCleanup(revertExpanded); + DragAndDrop.AcceptDrag(); + List list = new List(DragAndDrop.objectReferences); + bool draggedItemsFromOwnTreeView = true; + if (list.Count > 0 && list[0] != null && TreeViewUtility.FindItemInList(list[0].GetInstanceID(), this.m_TreeView.data.GetVisibleRows()) == null) + { + draggedItemsFromOwnTreeView = false; + } + int[] array = new int[list.Count]; + for (int i = 0; i < list.Count; i++) + { + if (!(list[i] == null)) + { + array[i] = list[i].GetInstanceID(); + } + } + this.m_TreeView.NotifyListenersThatDragEnded(array, draggedItemsFromOwnTreeView); + } protected virtual void HandleAutoExpansion(int itemControlID, TreeViewItem targetItem, Rect targetItemRect, float betweenHalfHeight, Vector2 currentMousePos) { float contentIndent = this.m_TreeView.gui.GetContentIndent(targetItem); diff --git a/UnityEditor/UnityEditor/TreeViewForAudioMixerGroup.cs b/UnityEditor/UnityEditor/TreeViewForAudioMixerGroup.cs new file mode 100644 index 00000000..63ab67f1 --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewForAudioMixerGroup.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using UnityEditor.Audio; +using UnityEditorInternal; +using UnityEngine; +namespace UnityEditor +{ + internal static class TreeViewForAudioMixerGroup + { + private class GroupTreeViewGUI : TreeViewGUI + { + private const float k_SpaceBetween = 25f; + private const float k_HeaderHeight = 20f; + private readonly Texture2D k_AudioGroupIcon = EditorGUIUtility.FindTexture("AudioMixerGroup Icon"); + private readonly Texture2D k_AudioListenerIcon = EditorGUIUtility.FindTexture("AudioListener Icon"); + private List m_RowRects = new List(); + public GroupTreeViewGUI(TreeView treeView) : base(treeView) + { + } + public override Rect OnRowGUI(TreeViewItem item, int row, float rowWidth, bool selected, bool focused) + { + if (this.m_TreeView.isSearching) + { + return base.OnRowGUI(item, row, rowWidth, selected, focused); + } + Rect rect = this.m_RowRects[row]; + this.DoNodeGUI(rect, item, selected, focused, false); + bool flag = item.parent == this.m_TreeView.data.root; + bool flag2 = item.id == TreeViewForAudioMixerGroup.kNoneItemID; + if (flag && !flag2) + { + AudioMixerController controller = (item.userData as AudioMixerGroupController).controller; + GUI.Label(new Rect(rect.x + 2f, rect.y - 18f, rect.width, 18f), GUIContent.Temp(controller.name), EditorStyles.boldLabel); + } + return rect; + } + protected override Texture GetIconForNode(TreeViewItem item) + { + if (item != null && item.icon != null) + { + return item.icon; + } + if (item.id == TreeViewForAudioMixerGroup.kNoneItemID) + { + return this.k_AudioListenerIcon; + } + return this.k_AudioGroupIcon; + } + protected override void SyncFakeItem() + { + } + protected override void RenameEnded() + { + } + private bool IsController(TreeViewItem item) + { + return item.parent == this.m_TreeView.data.root && item.id != TreeViewForAudioMixerGroup.kNoneItemID; + } + public void CalculateRowRects() + { + if (this.m_TreeView.isSearching) + { + return; + } + float width = GUIClip.visibleRect.width; + List visibleRows = this.m_TreeView.data.GetVisibleRows(); + this.m_RowRects = new List(visibleRows.Count); + float num = 2f; + for (int i = 0; i < visibleRows.Count; i++) + { + bool flag = this.IsController(visibleRows[i]); + num += ((!flag) ? 0f : 25f); + float k_LineHeight = this.k_LineHeight; + this.m_RowRects.Add(new Rect(0f, num, width, k_LineHeight)); + num += k_LineHeight; + } + } + public override Vector2 GetTotalSize(List rows) + { + if (this.m_TreeView.isSearching) + { + Vector2 totalSize = base.GetTotalSize(rows); + totalSize.x = 1f; + return totalSize; + } + if (this.m_RowRects.Count == 0) + { + return new Vector2(1f, 1f); + } + return new Vector2(1f, this.m_RowRects[this.m_RowRects.Count - 1].yMax); + } + public override float GetTopPixelOfRow(int row, List rows) + { + if (this.m_TreeView.isSearching) + { + return base.GetTopPixelOfRow(row, rows); + } + return this.m_RowRects[row].y; + } + public override float GetHeightOfLastRow() + { + if (this.m_TreeView.isSearching) + { + return base.GetHeightOfLastRow(); + } + return this.m_RowRects[this.m_RowRects.Count - 1].height; + } + public override int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) + { + if (this.m_TreeView.isSearching) + { + return base.GetNumRowsOnPageUpDown(fromItem, pageUp, heightOfTreeView); + } + return (int)Mathf.Floor(heightOfTreeView / this.k_LineHeight); + } + public override void GetFirstAndLastRowVisible(List rows, float topPixel, float heightInPixels, out int firstRowVisible, out int lastRowVisible) + { + if (this.m_TreeView.isSearching) + { + base.GetFirstAndLastRowVisible(rows, topPixel, heightInPixels, out firstRowVisible, out lastRowVisible); + return; + } + if (rows.Count != this.m_RowRects.Count) + { + Debug.LogError("Mismatch in state: rows vs cached rects"); + } + int num = -1; + int num2 = -1; + for (int i = 0; i < this.m_RowRects.Count; i++) + { + bool flag = (this.m_RowRects[i].y > topPixel && this.m_RowRects[i].y < topPixel + heightInPixels) || (this.m_RowRects[i].yMax > topPixel && this.m_RowRects[i].yMax < topPixel + heightInPixels); + if (flag) + { + if (num == -1) + { + num = i; + } + num2 = i; + } + } + if (num != -1 && num2 != -1) + { + firstRowVisible = num; + lastRowVisible = num2; + } + else + { + firstRowVisible = 0; + lastRowVisible = rows.Count - 1; + } + } + } + private class TreeViewDataSourceForMixers : TreeViewDataSource + { + public AudioMixerController ignoreThisController + { + get; + private set; + } + public TreeViewDataSourceForMixers(TreeView treeView, AudioMixerController ignoreController) : base(treeView) + { + base.showRootNode = false; + base.rootIsCollapsable = false; + this.ignoreThisController = ignoreController; + base.alwaysAddFirstItemToSearchResult = true; + } + private bool ShouldShowController(AudioMixerController controller, List allowedInstanceIDs) + { + return controller && (allowedInstanceIDs == null || allowedInstanceIDs.Count <= 0 || allowedInstanceIDs.Contains(controller.GetInstanceID())); + } + public override void FetchData() + { + int depth = -1; + this.m_RootItem = new TreeViewItem(1010101010, depth, null, "InvisibleRoot"); + this.SetExpanded(this.m_RootItem.id, true); + List allowedInstanceIDs = ObjectSelector.get.allowedInstanceIDs; + HierarchyProperty hierarchyProperty = new HierarchyProperty(HierarchyType.Assets); + hierarchyProperty.SetSearchFilter(new SearchFilter + { + classNames = new string[] + { + "AudioMixerController" + } + }); + List list = new List(); + while (hierarchyProperty.Next(null)) + { + AudioMixerController audioMixerController = hierarchyProperty.pptrValue as AudioMixerController; + if (this.ShouldShowController(audioMixerController, allowedInstanceIDs)) + { + list.Add(audioMixerController); + } + } + List list2 = new List(); + list2.Add(new TreeViewItem(TreeViewForAudioMixerGroup.kNoneItemID, 0, this.m_RootItem, TreeViewForAudioMixerGroup.s_NoneText)); + foreach (AudioMixerController current in list) + { + list2.Add(this.BuildSubTree(current)); + } + this.m_RootItem.children = list2; + if (list.Count == 1) + { + this.m_TreeView.data.SetExpandedWithChildren(this.m_RootItem, true); + } + this.m_NeedRefreshVisibleFolders = true; + } + private TreeViewItem BuildSubTree(AudioMixerController controller) + { + AudioMixerGroupController masterGroup = controller.masterGroup; + TreeViewItem treeViewItem = new TreeViewItem(masterGroup.GetInstanceID(), 0, this.m_RootItem, masterGroup.name); + treeViewItem.userData = masterGroup; + this.AddChildrenRecursive(masterGroup, treeViewItem); + return treeViewItem; + } + private void AddChildrenRecursive(AudioMixerGroupController group, TreeViewItem item) + { + item.children = new List(group.children.Length); + for (int i = 0; i < group.children.Length; i++) + { + item.children.Add(new TreeViewItem(group.children[i].GetInstanceID(), item.depth + 1, item, group.children[i].name)); + item.children[i].userData = group.children[i]; + this.AddChildrenRecursive(group.children[i], item.children[i]); + } + } + public override bool CanBeMultiSelected(TreeViewItem item) + { + return false; + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return false; + } + } + private static readonly int kNoneItemID; + private static string s_NoneText = "None"; + public static void CreateAndSetTreeView(ObjectTreeForSelector.TreeSelectorData data) + { + AudioMixerController ignoreController = InternalEditorUtility.GetObjectFromInstanceID(data.userData) as AudioMixerController; + TreeView treeView = new TreeView(data.editorWindow, data.state); + TreeViewForAudioMixerGroup.GroupTreeViewGUI groupTreeViewGUI = new TreeViewForAudioMixerGroup.GroupTreeViewGUI(treeView); + TreeViewForAudioMixerGroup.TreeViewDataSourceForMixers treeViewDataSourceForMixers = new TreeViewForAudioMixerGroup.TreeViewDataSourceForMixers(treeView, ignoreController); + TreeViewForAudioMixerGroup.TreeViewDataSourceForMixers expr_33 = treeViewDataSourceForMixers; + expr_33.onVisibleRowsChanged = (Action)Delegate.Combine(expr_33.onVisibleRowsChanged, new Action(groupTreeViewGUI.CalculateRowRects)); + treeView.deselectOnUnhandledMouseDown = false; + treeView.Init(data.treeViewRect, treeViewDataSourceForMixers, groupTreeViewGUI, null); + data.objectTreeForSelector.SetTreeView(treeView); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewGUI.cs b/UnityEditor/UnityEditor/TreeViewGUI.cs index 63212a97..8832b8c9 100644 --- a/UnityEditor/UnityEditor/TreeViewGUI.cs +++ b/UnityEditor/UnityEditor/TreeViewGUI.cs @@ -38,6 +38,7 @@ public Styles() protected float k_IconWidth = 16f; protected float k_SpaceBetweenIconAndText = 2f; protected float k_TopRowMargin; + protected float k_BottomRowMargin; protected float k_HalfDropBetweenHeight = 4f; protected static TreeViewGUI.Styles s_Styles; public float iconLeftPadding @@ -83,6 +84,13 @@ public virtual float topRowMargin return this.k_TopRowMargin; } } + public virtual float bottomRowMargin + { + get + { + return this.k_BottomRowMargin; + } + } public TreeViewGUI(TreeView treeView) { this.m_TreeView = treeView; @@ -108,10 +116,11 @@ public virtual Vector2 GetTotalSize(List rows) { x = this.GetMaxWidth(rows); } - return new Vector2(x, (float)rows.Count * this.k_LineHeight); + return new Vector2(x, (float)rows.Count * this.k_LineHeight + this.topRowMargin + this.bottomRowMargin); } protected float GetMaxWidth(List rows) { + this.InitStyles(); float num = 1f; foreach (TreeViewItem current in rows) { @@ -200,7 +209,7 @@ protected virtual void DoNodeGUI(Rect rect, TreeViewItem item, bool selected, bo } bool flag2 = this.IsRenaming(item.id); bool flag3 = this.m_TreeView.data.IsExpandable(item); - if (flag2 && rect.width > 1f) + if (flag2 && Event.current.type == EventType.Repaint) { float num = foldoutIndent + this.k_FoldoutWidth + this.k_IconWidth + this.iconTotalPadding - 1f; this.GetRenameOverlay().editFieldRect = new Rect(rect.x + num, rect.y, rect.width - num, rect.height); @@ -351,11 +360,15 @@ protected virtual void ClearRenameAndNewNodeState() } public virtual float GetFoldoutIndent(TreeViewItem item) { + if (this.m_TreeView.isSearching) + { + return this.k_BaseIndent; + } return this.k_BaseIndent + (float)item.depth * this.indentWidth; } public virtual float GetContentIndent(TreeViewItem item) { - return this.k_BaseIndent + (float)item.depth * this.indentWidth + this.k_FoldoutWidth; + return this.GetFoldoutIndent(item) + this.k_FoldoutWidth; } } } diff --git a/UnityEditor/UnityEditor/TreeViewItem.cs b/UnityEditor/UnityEditor/TreeViewItem.cs index b00fe13c..63122a2e 100644 --- a/UnityEditor/UnityEditor/TreeViewItem.cs +++ b/UnityEditor/UnityEditor/TreeViewItem.cs @@ -11,6 +11,7 @@ internal class TreeViewItem : IComparable private int m_Depth; private string m_DisplayName; private Texture2D m_Icon; + private object m_UserData; public virtual int id { get @@ -35,6 +36,10 @@ public virtual int depth { return this.m_Depth; } + set + { + this.m_Depth = value; + } } public virtual bool hasChildren { @@ -76,6 +81,17 @@ public virtual Texture2D icon this.m_Icon = value; } } + public virtual object userData + { + get + { + return this.m_UserData; + } + set + { + this.m_UserData = value; + } + } public TreeViewItem(int id, int depth, TreeViewItem parent, string displayName) { this.m_Depth = depth; diff --git a/UnityEditor/UnityEditor/TreeViewItemAlphaNumericSort.cs b/UnityEditor/UnityEditor/TreeViewItemAlphaNumericSort.cs new file mode 100644 index 00000000..5776f29a --- /dev/null +++ b/UnityEditor/UnityEditor/TreeViewItemAlphaNumericSort.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +namespace UnityEditor +{ + internal class TreeViewItemAlphaNumericSort : IComparer + { + public int Compare(TreeViewItem lhs, TreeViewItem rhs) + { + if (lhs == rhs) + { + return 0; + } + if (lhs == null) + { + return -1; + } + if (rhs == null) + { + return 1; + } + return EditorUtility.NaturalCompare(lhs.displayName, rhs.displayName); + } + } +} diff --git a/UnityEditor/UnityEditor/TreeViewState.cs b/UnityEditor/UnityEditor/TreeViewState.cs index d7ab2cf0..8b07ee08 100644 --- a/UnityEditor/UnityEditor/TreeViewState.cs +++ b/UnityEditor/UnityEditor/TreeViewState.cs @@ -18,6 +18,8 @@ internal class TreeViewState [SerializeField] private CreateAssetUtility m_CreateAssetUtility = new CreateAssetUtility(); [SerializeField] + private string m_SearchString; + [SerializeField] private float[] m_ColumnWidths; public List selectedIDs { @@ -85,6 +87,17 @@ public float[] columnWidths this.m_ColumnWidths = value; } } + public string searchString + { + get + { + return this.m_SearchString; + } + set + { + this.m_SearchString = value; + } + } public void OnAwake() { this.m_RenameOverlay.Clear(); diff --git a/UnityEditor/UnityEditor/TreeViewUtility.cs b/UnityEditor/UnityEditor/TreeViewUtility.cs index 858d2329..7bfd6802 100644 --- a/UnityEditor/UnityEditor/TreeViewUtility.cs +++ b/UnityEditor/UnityEditor/TreeViewUtility.cs @@ -12,9 +12,9 @@ from x in treeViewItems where itemIDs.Contains(x.id) select x).ToList(); } - public static TreeViewItem FindItemInList(int id, List treeViewItems) + public static TreeViewItem FindItemInList(int id, List treeViewItems) where T : TreeViewItem { - return treeViewItems.FirstOrDefault((TreeViewItem t) => t.id == id); + return treeViewItems.FirstOrDefault((T t) => t.id == id); } public static TreeViewItem FindItem(int id, TreeViewItem searchFromThisItem) { @@ -62,64 +62,82 @@ public static void DebugPrintToEditorLogRecursive(TreeViewItem item) } public static void SetChildParentReferences(List visibleItems, TreeViewItem root) { - Dictionary> dictionary = new Dictionary>(); for (int i = 0; i < visibleItems.Count; i++) { - TreeViewItem treeViewItem = visibleItems[i]; - TreeViewItem treeViewItem2 = TreeViewUtility.FindParent(visibleItems, treeViewItem.depth, i); - if (treeViewItem2 == null) - { - treeViewItem2 = root; - } - if (!dictionary.ContainsKey(treeViewItem2)) + visibleItems[i].parent = null; + } + int num = 0; + for (int j = 0; j < visibleItems.Count; j++) + { + TreeViewUtility.SetChildParentReferences(j, visibleItems); + if (visibleItems[j].parent == null) { - dictionary.Add(treeViewItem2, new List(4)); + num++; } - dictionary[treeViewItem2].Add(treeViewItem); - treeViewItem.parent = treeViewItem2; } - foreach (KeyValuePair> current in dictionary) + if (num > 0) { - TreeViewUtility.SetParent(current.Value, current.Key); + List list = new List(num); + for (int k = 0; k < visibleItems.Count; k++) + { + if (visibleItems[k].parent == null) + { + list.Add(visibleItems[k]); + visibleItems[k].parent = root; + } + } + root.children = list; } } - private static void SetParent(List children, TreeViewItem parent) + private static void SetChildren(TreeViewItem item, List newChildList) { - if (parent.hasChildren && parent.children[0] == null) - { - parent.children.RemoveAt(0); - } - if (parent.children == null) + if (LazyTreeViewDataSource.IsChildListForACollapsedParent(item.children) && newChildList == null) { - parent.children = new List(children.Count); + return; } - parent.children.AddRange(children); + item.children = newChildList; } - private static void SetParent(TreeViewItem child, TreeViewItem parent) + private static void SetChildParentReferences(int parentIndex, List visibleItems) { - child.parent = parent; - if (parent.hasChildren && parent.children[0] == null) + TreeViewItem treeViewItem = visibleItems[parentIndex]; + bool flag = treeViewItem.children != null && treeViewItem.children.Count > 0 && treeViewItem.children[0] != null; + if (flag) { - parent.children.RemoveAt(0); + return; } - parent.AddChild(child); - } - private static TreeViewItem FindParent(List visibleItems, int childDepth, int childIndex) - { - if (childDepth == 0) + int depth = treeViewItem.depth; + int num = 0; + for (int i = parentIndex + 1; i < visibleItems.Count; i++) { - return null; + if (visibleItems[i].depth == depth + 1) + { + num++; + } + if (visibleItems[i].depth <= depth) + { + break; + } } - while (childIndex >= 0) + List list = null; + if (num != 0) { - TreeViewItem treeViewItem = visibleItems[childIndex]; - if (treeViewItem.depth == childDepth - 1) + list = new List(num); + num = 0; + for (int j = parentIndex + 1; j < visibleItems.Count; j++) { - return treeViewItem; + if (visibleItems[j].depth == depth + 1) + { + visibleItems[j].parent = treeViewItem; + list.Add(visibleItems[j]); + num++; + } + if (visibleItems[j].depth <= depth) + { + break; + } } - childIndex--; } - return null; + TreeViewUtility.SetChildren(treeViewItem, list); } } } diff --git a/UnityEditor/UnityEditor/TreeWizard.cs b/UnityEditor/UnityEditor/TreeWizard.cs index 18843a39..ea533855 100644 --- a/UnityEditor/UnityEditor/TreeWizard.cs +++ b/UnityEditor/UnityEditor/TreeWizard.cs @@ -7,10 +7,27 @@ internal class TreeWizard : TerrainWizard public GameObject m_Tree; public float m_BendFactor; private int m_PrototypeIndex = -1; + private bool m_IsValidTree; public void OnEnable() { base.minSize = new Vector2(400f, 150f); } + private static bool IsValidTree(GameObject tree, int prototypeIndex, Terrain terrain) + { + if (tree == null) + { + return false; + } + TreePrototype[] treePrototypes = terrain.terrainData.treePrototypes; + for (int i = 0; i < treePrototypes.Length; i++) + { + if (i != prototypeIndex && treePrototypes[i].m_Prefab == tree) + { + return false; + } + } + return true; + } internal void InitializeDefaults(Terrain terrain, int index) { this.m_Terrain = terrain; @@ -25,6 +42,7 @@ internal void InitializeDefaults(Terrain terrain, int index) this.m_Tree = this.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].prefab; this.m_BendFactor = this.m_Terrain.terrainData.treePrototypes[this.m_PrototypeIndex].bendFactor; } + this.m_IsValidTree = TreeWizard.IsValidTree(this.m_Tree, this.m_PrototypeIndex, terrain); this.OnWizardUpdate(); } private void DoApply() @@ -64,6 +82,22 @@ private void OnWizardOtherButton() { this.DoApply(); } + protected override bool DrawWizardGUI() + { + EditorGUI.BeginChangeCheck(); + this.m_Tree = (GameObject)EditorGUILayout.ObjectField("Tree Prefab", this.m_Tree, typeof(GameObject), false, new GUILayoutOption[0]); + bool flag = this.m_Tree != null && this.m_Tree.GetComponent() == null; + if (flag) + { + this.m_BendFactor = EditorGUILayout.FloatField("Bend Factor", this.m_BendFactor, new GUILayoutOption[0]); + } + bool flag2 = EditorGUI.EndChangeCheck(); + if (flag2) + { + this.m_IsValidTree = TreeWizard.IsValidTree(this.m_Tree, this.m_PrototypeIndex, this.m_Terrain); + } + return flag2; + } internal override void OnWizardUpdate() { base.OnWizardUpdate(); @@ -74,9 +108,17 @@ internal override void OnWizardUpdate() } else { - if (this.m_PrototypeIndex != -1) + if (!this.m_IsValidTree) + { + base.errorString = "Tree has already been selected as a prototype"; + base.isValid = false; + } + else { - this.DoApply(); + if (this.m_PrototypeIndex != -1) + { + this.DoApply(); + } } } } diff --git a/UnityEditor/UnityEditor/TypeSelection.cs b/UnityEditor/UnityEditor/TypeSelection.cs index a4505fcb..d6df5c7d 100644 --- a/UnityEditor/UnityEditor/TypeSelection.cs +++ b/UnityEditor/UnityEditor/TypeSelection.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using UnityEngine; namespace UnityEditor @@ -9,7 +8,6 @@ internal class TypeSelection : IComparable public UnityEngine.Object[] objects; public TypeSelection(string typeName, UnityEngine.Object[] objects) { - Assert.That(objects != null || objects.Length >= 1); this.objects = objects; this.label = new GUIContent(string.Concat(new object[] { diff --git a/UnityEditor/UnityEditor/Undo.cs b/UnityEditor/UnityEditor/Undo.cs index 44a5f5f2..2d505c6a 100644 --- a/UnityEditor/UnityEditor/Undo.cs +++ b/UnityEditor/UnityEditor/Undo.cs @@ -49,7 +49,7 @@ public static T AddComponent(GameObject gameObject) where T : Component [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToUndo, string name); [Obsolete("Use Undo.RegisterFullObjectHierarchyUndo(Object, string) instead")] - private static void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToUndo) + public static void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToUndo) { Undo.RegisterFullObjectHierarchyUndo(objectToUndo, "Full Object Hierarchy"); } @@ -76,6 +76,12 @@ private static void RegisterFullObjectHierarchyUndo(UnityEngine.Object objectToU public static extern int GetCurrentGroup(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetCurrentGroupName(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetCurrentGroupName(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RevertAllInCurrentGroup(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditor/UnityStats.cs b/UnityEditor/UnityEditor/UnityStats.cs index 9ee15151..0d698b05 100644 --- a/UnityEditor/UnityEditor/UnityStats.cs +++ b/UnityEditor/UnityEditor/UnityStats.cs @@ -5,19 +5,43 @@ namespace UnityEditor { public sealed class UnityStats { + public static extern int batches + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern int drawCalls { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern int batchedDrawCalls + public static extern int dynamicBatchedDrawCalls { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern int batches + public static extern int staticBatchedDrawCalls + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int dynamicBatches + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int staticBatches + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int setPassCalls { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -59,6 +83,30 @@ public static extern float renderTime [MethodImpl(MethodImplOptions.InternalCall)] get; } + public static extern float audioLevel + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float audioClippingAmount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float audioDSPLoad + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern float audioStreamLoad + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern int renderTextureCount { [WrapperlessIcall] diff --git a/UnityEditor/UnityEditor/Unsupported.cs b/UnityEditor/UnityEditor/Unsupported.cs index d178b811..4d48c20d 100644 --- a/UnityEditor/UnityEditor/Unsupported.cs +++ b/UnityEditor/UnityEditor/Unsupported.cs @@ -1,6 +1,6 @@ using System; using System.Runtime.CompilerServices; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { @@ -141,15 +141,31 @@ public static bool IsDeveloperBuild() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool PasteComponentValuesFromPasteboard(Component component); + public static void CopyStateMachineDataToPasteboard(UnityEngine.Object stateMachineObject, AnimatorController controller, int layerIndex) + { + Unsupported.CopyStateMachineDataToPasteboard(new UnityEngine.Object[] + { + stateMachineObject + }, new Vector3[] + { + default(Vector3) + }, controller, layerIndex); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CopyStateToPasteboard(State state, AnimatorController controller); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CopyStateMachineToPasteboard(StateMachine stateMachine, AnimatorController controller); + public static extern void CopyStateMachineDataToPasteboard(UnityEngine.Object[] stateMachineObjects, Vector3[] monoPositions, AnimatorController controller, int layerIndex); + public static void PasteToStateMachineFromPasteboard(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, Vector3 position) + { + Undo.RegisterCompleteObjectUndo(sm, "Paste to StateMachine"); + Unsupported.PasteToStateMachineFromPasteboardInternal(sm, controller, layerIndex, position); + } + internal static void PasteToStateMachineFromPasteboardInternal(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, Vector3 position) + { + Unsupported.INTERNAL_CALL_PasteToStateMachineFromPasteboardInternal(sm, controller, layerIndex, ref position); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void PasteToStateMachineFromPasteboard(StateMachine sm, AnimatorController controller); + private static extern void INTERNAL_CALL_PasteToStateMachineFromPasteboardInternal(AnimatorStateMachine sm, AnimatorController controller, int layerIndex, ref Vector3 position); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasStateMachineDataInPasteboard(); diff --git a/UnityEditor/UnityEditor/VisualizationBlendTree.cs b/UnityEditor/UnityEditor/VisualizationBlendTree.cs index 5b6e7cab..30c9078f 100644 --- a/UnityEditor/UnityEditor/VisualizationBlendTree.cs +++ b/UnityEditor/UnityEditor/VisualizationBlendTree.cs @@ -1,13 +1,13 @@ using System; -using UnityEditorInternal; +using UnityEditor.Animations; using UnityEngine; namespace UnityEditor { internal class VisualizationBlendTree { private AnimatorController m_Controller; - private StateMachine m_StateMachine; - private State m_State; + private AnimatorStateMachine m_StateMachine; + private AnimatorState m_State; private BlendTree m_BlendTree; private Animator m_Animator; private bool m_ControllerIsDirty; @@ -18,6 +18,13 @@ public Animator animator return this.m_Animator; } } + public bool controllerDirty + { + get + { + return this.m_ControllerIsDirty; + } + } public void Init(BlendTree blendTree, Animator animator) { this.m_BlendTree = blendTree; @@ -34,14 +41,9 @@ protected virtual void ControllerDirty() } private void CreateParameters() { - int parameterCount = this.m_Controller.parameterCount; - for (int i = 0; i < parameterCount; i++) - { - this.m_Controller.RemoveParameter(0); - } - for (int j = 0; j < this.m_BlendTree.recursiveBlendParameterCount; j++) + for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) { - this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(j), AnimatorControllerParameterType.Float); + this.m_Controller.AddParameter(this.m_BlendTree.GetRecursiveBlendParameter(i), AnimatorControllerParameterType.Float); } } private void CreateStateMachine() @@ -49,17 +51,21 @@ private void CreateStateMachine() if (this.m_Controller == null) { this.m_Controller = new AnimatorController(); - this.m_Controller.hideFlags = HideFlags.DontSave; + this.m_Controller.pushUndo = false; this.m_Controller.AddLayer("preview"); - this.m_StateMachine = this.m_Controller.GetLayerStateMachine(0); + this.m_StateMachine = this.m_Controller.layers[0].stateMachine; + this.m_StateMachine.pushUndo = false; this.CreateParameters(); this.m_State = this.m_StateMachine.AddState("preview"); - this.m_State.SetMotionInternal(this.m_BlendTree); + this.m_State.pushUndo = false; + this.m_State.motion = this.m_BlendTree; this.m_State.iKOnFeet = false; - this.m_State.hideFlags = HideFlags.DontSave; + this.m_State.hideFlags = HideFlags.HideAndDontSave; + this.m_StateMachine.hideFlags = HideFlags.HideAndDontSave; + this.m_Controller.hideFlags = HideFlags.HideAndDontSave; AnimatorController.SetAnimatorController(this.m_Animator, this.m_Controller); - AnimatorController expr_A7 = this.m_Controller; - expr_A7.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_A7.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); + AnimatorController expr_DF = this.m_Controller; + expr_DF.OnAnimatorControllerDirty = (Action)Delegate.Combine(expr_DF.OnAnimatorControllerDirty, new Action(this.ControllerDirty)); this.m_ControllerIsDirty = false; } } @@ -95,7 +101,12 @@ public void Update() { this.Reset(); } - for (int i = 0; i < this.m_BlendTree.recursiveBlendParameterCount; i++) + int recursiveBlendParameterCount = this.m_BlendTree.recursiveBlendParameterCount; + if (this.m_Controller.parameters.Length < recursiveBlendParameterCount) + { + return; + } + for (int i = 0; i < recursiveBlendParameterCount; i++) { string recursiveBlendParameter = this.m_BlendTree.GetRecursiveBlendParameter(i); float inputBlendValue = this.m_BlendTree.GetInputBlendValue(recursiveBlendParameter); diff --git a/UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs b/UnityEditor/UnityEditor/WSABuildAndRunDeployTarget.cs similarity index 72% rename from UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs rename to UnityEditor/UnityEditor/WSABuildAndRunDeployTarget.cs index f1efbea4..13344831 100644 --- a/UnityEditor/UnityEditor/MetroBuildAndRunDeployTarget.cs +++ b/UnityEditor/UnityEditor/WSABuildAndRunDeployTarget.cs @@ -1,7 +1,7 @@ using System; namespace UnityEditor { - public enum MetroBuildAndRunDeployTarget + public enum WSABuildAndRunDeployTarget { LocalMachine, WindowsPhone, diff --git a/UnityEditor/UnityEditor/MetroSDK.cs b/UnityEditor/UnityEditor/WSASDK.cs similarity index 81% rename from UnityEditor/UnityEditor/MetroSDK.cs rename to UnityEditor/UnityEditor/WSASDK.cs index b3d89a46..580a4beb 100644 --- a/UnityEditor/UnityEditor/MetroSDK.cs +++ b/UnityEditor/UnityEditor/WSASDK.cs @@ -1,7 +1,7 @@ using System; namespace UnityEditor { - public enum MetroSDK + public enum WSASDK { SDK80, SDK81, diff --git a/UnityEditor/UnityEditor/WebScriptObject.cs b/UnityEditor/UnityEditor/WebScriptObject.cs deleted file mode 100644 index a663cb43..00000000 --- a/UnityEditor/UnityEditor/WebScriptObject.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine; -using UnityEngine.Internal; -namespace UnityEditor -{ - [StructLayout(LayoutKind.Sequential)] - public sealed class WebScriptObject : IDisposable - { - private IntPtr webScriptObjectWrapper; - public void Dispose() - { - this.DestroyScriptObject(); - } - ~WebScriptObject() - { - this.DestroyScriptObject(); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void DestroyScriptObject(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern object MonoObjectFromJSON(string json); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern WebScriptObject EvalJavaScript(string script); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern WebScriptObject InvokeMethodArray(string method, object[] args); - public WebScriptObject InvokeMethod(string method, params object[] args) - { - return this.InvokeMethodArray(method, args); - } - public WebScriptObject Invoke(params object[] args) - { - object[] array = new object[args.Length + 1]; - args.CopyTo(array, 1); - array[0] = this; - return this.InvokeMethodArray("call", array); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern WebScriptObject Internal_GetKey(string key); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetKey(string key, object value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Remove(string key); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern WebScriptObject Internal_GetIndex(int i); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetIndex(int i, object value); - public WebScriptObject Get(int key) - { - return this.Internal_GetIndex(key); - } - public WebScriptObject Get(string key) - { - WebScriptObject webScriptObject = this; - string[] array = key.Split(new char[] - { - '.' - }); - for (int i = 0; i < array.Length; i++) - { - string key2 = array[i]; - webScriptObject = webScriptObject.Internal_GetKey(key2); - if (webScriptObject == null) - { - break; - } - } - return webScriptObject; - } - public T Get(int key) - { - return this.Internal_GetIndex(key).Convert(); - } - public T Get(string key) - { - return this.Get(key).Convert(); - } - public void Set(int key, T value) - { - this.Internal_SetIndex(key, value); - } - public void Set(string key, T value) - { - this.Internal_SetKey(key, value); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern object ConvertToType(Type t); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool IsValid(); - public T Convert() - { - return (T)((object)this.ConvertToType(typeof(T))); - } - [ExcludeFromDocs] - public string GetAsJSON(string key) - { - int indent = 0; - return this.GetAsJSON(key, indent); - } - public string GetAsJSON(string key, [DefaultValue("0")] int indent) - { - return this.Internal_GetKey(key).ToJSON(indent); - } - [ExcludeFromDocs] - public string GetAsJSON(int i) - { - int indent = 0; - return this.GetAsJSON(i, indent); - } - public string GetAsJSON(int i, [DefaultValue("0")] int indent) - { - return this.Internal_GetIndex(i).ToJSON(indent); - } - public void SetFromJSON(string key, string value) - { - this.Internal_SetKey(key, this.ParseJSON(value)); - } - public void SetFromJSON(int i, string value) - { - this.Internal_SetIndex(i, this.ParseJSON(value)); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern string ToJSON([DefaultValue("0")] int indent); - [ExcludeFromDocs] - public string ToJSON() - { - int indent = 0; - return this.ToJSON(indent); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public override extern string ToString(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern WebScriptObject ParseJSON(string json); - public static implicit operator bool(WebScriptObject o) - { - return o != null && o.IsValid() && o.Convert(); - } - public static implicit operator int(WebScriptObject o) - { - return o.Convert(); - } - public static implicit operator float(WebScriptObject o) - { - return o.Convert(); - } - public static implicit operator double(WebScriptObject o) - { - return o.Convert(); - } - public static implicit operator string(WebScriptObject o) - { - if (o == null || !o.IsValid()) - { - return string.Empty; - } - return o.ToString(); - } - } -} diff --git a/UnityEditor/UnityEditor/WebTemplate.cs b/UnityEditor/UnityEditor/WebTemplate.cs new file mode 100644 index 00000000..b87c0e96 --- /dev/null +++ b/UnityEditor/UnityEditor/WebTemplate.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +namespace UnityEditor +{ + internal class WebTemplate + { + public string m_Path; + public string m_Name; + public Texture2D m_Thumbnail; + public string[] m_CustomKeys; + public string[] CustomKeys + { + get + { + return this.m_CustomKeys; + } + } + public override bool Equals(object other) + { + return other is WebTemplate && other.ToString().Equals(this.ToString()); + } + public override int GetHashCode() + { + return base.GetHashCode() ^ this.m_Path.GetHashCode(); + } + public override string ToString() + { + return this.m_Path; + } + public GUIContent ToGUIContent(Texture2D defaultIcon) + { + return new GUIContent(this.m_Name, (!(this.m_Thumbnail == null)) ? this.m_Thumbnail : defaultIcon); + } + } +} diff --git a/UnityEditor/UnityEditor/WebTemplateManagerBase.cs b/UnityEditor/UnityEditor/WebTemplateManagerBase.cs new file mode 100644 index 00000000..b153e8fd --- /dev/null +++ b/UnityEditor/UnityEditor/WebTemplateManagerBase.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using UnityEngine; +namespace UnityEditor +{ + internal abstract class WebTemplateManagerBase + { + private class Styles + { + public GUIStyle thumbnail = "IN ThumbnailShadow"; + public GUIStyle thumbnailLabel = "IN ThumbnailSelection"; + } + private const float kWebTemplateGridPadding = 15f; + private const float kThumbnailSize = 80f; + private const float kThumbnailLabelHeight = 20f; + private const float kThumbnailPadding = 5f; + private static WebTemplateManagerBase.Styles s_Styles; + private WebTemplate[] s_Templates; + private GUIContent[] s_TemplateGUIThumbnails; + public abstract string customTemplatesFolder + { + get; + } + public abstract string builtinTemplatesFolder + { + get; + } + public abstract Texture2D defaultIcon + { + get; + } + public WebTemplate[] Templates + { + get + { + if (this.s_Templates == null || this.s_TemplateGUIThumbnails == null) + { + this.BuildTemplateList(); + } + return this.s_Templates; + } + } + public GUIContent[] TemplateGUIThumbnails + { + get + { + if (this.s_Templates == null || this.s_TemplateGUIThumbnails == null) + { + this.BuildTemplateList(); + } + return this.s_TemplateGUIThumbnails; + } + } + public int GetTemplateIndex(string path) + { + for (int i = 0; i < this.Templates.Length; i++) + { + if (path.Equals(this.Templates[i].ToString())) + { + return i; + } + } + return 0; + } + public void ClearTemplates() + { + this.s_Templates = null; + this.s_TemplateGUIThumbnails = null; + } + private void BuildTemplateList() + { + List list = new List(); + if (Directory.Exists(this.customTemplatesFolder)) + { + list.AddRange(this.ListTemplates(this.customTemplatesFolder)); + } + if (Directory.Exists(this.builtinTemplatesFolder)) + { + list.AddRange(this.ListTemplates(this.builtinTemplatesFolder)); + } + else + { + Debug.LogError("Did not find built-in templates."); + } + this.s_Templates = list.ToArray(); + this.s_TemplateGUIThumbnails = new GUIContent[this.s_Templates.Length]; + for (int i = 0; i < this.s_TemplateGUIThumbnails.Length; i++) + { + this.s_TemplateGUIThumbnails[i] = this.s_Templates[i].ToGUIContent(this.defaultIcon); + } + } + private WebTemplate Load(string path) + { + if (!Directory.Exists(path) || Directory.GetFiles(path, "index.*").Length < 1) + { + return null; + } + string[] array = path.Split(new char[] + { + Path.DirectorySeparatorChar + }); + WebTemplate webTemplate = new WebTemplate(); + webTemplate.m_Name = array[array.Length - 1]; + if (array.Length > 3 && array[array.Length - 3].Equals("Assets")) + { + webTemplate.m_Path = "PROJECT:" + webTemplate.m_Name; + } + else + { + webTemplate.m_Path = "APPLICATION:" + webTemplate.m_Name; + } + string[] files = Directory.GetFiles(path, "thumbnail.*"); + if (files.Length > 0) + { + webTemplate.m_Thumbnail = new Texture2D(2, 2); + webTemplate.m_Thumbnail.LoadImage(File.ReadAllBytes(files[0])); + } + List list = new List(); + Regex regex = new Regex("\\%UNITY_CUSTOM_([A-Z_]+)\\%"); + MatchCollection matchCollection = regex.Matches(File.ReadAllText(Directory.GetFiles(path, "index.*")[0])); + foreach (Match match in matchCollection) + { + string text = match.Value.Substring("%UNITY_CUSTOM_".Length); + text = text.Substring(0, text.Length - 1); + if (!list.Contains(text)) + { + list.Add(text); + } + } + webTemplate.m_CustomKeys = list.ToArray(); + return webTemplate; + } + private List ListTemplates(string path) + { + List list = new List(); + string[] directories = Directory.GetDirectories(path); + string[] array = directories; + for (int i = 0; i < array.Length; i++) + { + string path2 = array[i]; + WebTemplate webTemplate = this.Load(path2); + if (webTemplate != null) + { + list.Add(webTemplate); + } + } + return list; + } + public void SelectionUI(SerializedProperty templateProp) + { + if (WebTemplateManagerBase.s_Styles == null) + { + WebTemplateManagerBase.s_Styles = new WebTemplateManagerBase.Styles(); + } + if (this.TemplateGUIThumbnails.Length < 1) + { + GUILayout.Label(EditorGUIUtility.TextContent("PlayerSettings.NoTemplatesFound"), new GUILayoutOption[0]); + } + else + { + int num = Mathf.Min((int)Mathf.Max(((float)Screen.width - 30f) / 80f, 1f), this.TemplateGUIThumbnails.Length); + int num2 = Mathf.Max((int)Mathf.Ceil((float)this.TemplateGUIThumbnails.Length / (float)num), 1); + bool changed = GUI.changed; + templateProp.stringValue = this.Templates[WebTemplateManagerBase.ThumbnailList(GUILayoutUtility.GetRect((float)num * 80f, (float)num2 * 100f, new GUILayoutOption[] + { + GUILayout.ExpandWidth(false) + }), this.GetTemplateIndex(templateProp.stringValue), this.TemplateGUIThumbnails, num)].ToString(); + bool flag = !changed && GUI.changed; + bool changed2 = GUI.changed; + GUI.changed = false; + string[] templateCustomKeys = PlayerSettings.templateCustomKeys; + for (int i = 0; i < templateCustomKeys.Length; i++) + { + string text = templateCustomKeys[i]; + string text2 = PlayerSettings.GetTemplateCustomValue(text); + text2 = EditorGUILayout.TextField(WebTemplateManagerBase.PrettyTemplateKeyName(text), text2, new GUILayoutOption[0]); + PlayerSettings.SetTemplateCustomValue(text, text2); + } + if (GUI.changed) + { + templateProp.serializedObject.Update(); + } + GUI.changed |= changed2; + if (flag) + { + GUIUtility.hotControl = 0; + GUIUtility.keyboardControl = 0; + templateProp.serializedObject.ApplyModifiedProperties(); + PlayerSettings.templateCustomKeys = this.Templates[this.GetTemplateIndex(templateProp.stringValue)].CustomKeys; + templateProp.serializedObject.Update(); + } + } + } + private static int ThumbnailList(Rect rect, int selection, GUIContent[] thumbnails, int maxRowItems) + { + int num = 0; + int i = 0; + while (i < thumbnails.Length) + { + int num2 = 0; + while (num2 < maxRowItems && i < thumbnails.Length) + { + if (WebTemplateManagerBase.ThumbnailListItem(new Rect(rect.x + (float)num2 * 80f, rect.y + (float)num * 100f, 80f, 100f), i == selection, thumbnails[i])) + { + selection = i; + } + num2++; + i++; + } + num++; + } + return selection; + } + private static bool ThumbnailListItem(Rect rect, bool selected, GUIContent content) + { + EventType type = Event.current.type; + if (type != EventType.MouseDown) + { + if (type == EventType.Repaint) + { + Rect position = new Rect(rect.x + 5f, rect.y + 5f, rect.width - 10f, rect.height - 20f - 10f); + WebTemplateManagerBase.s_Styles.thumbnail.Draw(position, content.image, false, false, selected, selected); + WebTemplateManagerBase.s_Styles.thumbnailLabel.Draw(new Rect(rect.x, rect.y + rect.height - 20f, rect.width, 20f), content.text, false, false, selected, selected); + } + } + else + { + if (rect.Contains(Event.current.mousePosition)) + { + if (!selected) + { + GUI.changed = true; + } + selected = true; + Event.current.Use(); + } + } + return selected; + } + private static string PrettyTemplateKeyName(string name) + { + string[] array = name.Split(new char[] + { + '_' + }); + array[0] = WebTemplateManagerBase.UppercaseFirst(array[0].ToLower()); + for (int i = 1; i < array.Length; i++) + { + array[i] = array[i].ToLower(); + } + return string.Join(" ", array); + } + private static string UppercaseFirst(string target) + { + if (string.IsNullOrEmpty(target)) + { + return string.Empty; + } + return char.ToUpper(target[0]) + target.Substring(1); + } + } +} diff --git a/UnityEditor/UnityEditor/WebView.cs b/UnityEditor/UnityEditor/WebView.cs index c0b22118..4d722996 100644 --- a/UnityEditor/UnityEditor/WebView.cs +++ b/UnityEditor/UnityEditor/WebView.cs @@ -1,42 +1,14 @@ using System; -using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using UnityEngine; namespace UnityEditor { [StructLayout(LayoutKind.Sequential)] - public sealed class WebView : ScriptableObject + internal sealed class WebView : ScriptableObject { [SerializeField] - private MonoReloadableIntPtr webViewWrapper; - internal extern Texture2D texture - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern WebScriptObject windowScriptObject - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern bool needsRepaint - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public WebView(int width, int height, bool showResizeHandle) - { - this.InitWebView(width, height, showResizeHandle); - } - public WebView(int width, int height, string url) - { - this.InitWebView(width, height, false); - this.LoadURL(url); - } + private MonoReloadableIntPtr WebViewWindow; public void OnDestroy() { this.DestroyWebView(); @@ -46,7 +18,7 @@ public void OnDestroy() private extern void DestroyWebView(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void InitWebView(int width, int height, bool showResizeHandle); + public extern void InitWebView(GUIView host, int x, int y, int width, int height, bool showResizeHandle); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void LoadURL(string url); @@ -55,231 +27,40 @@ public void OnDestroy() public extern void LoadFile(string path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool IntPtrIsNull(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetDelegateObject(ScriptableObject value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetWebkitControlsGlobalLocation(int x, int y); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void Resize(int width, int height); + public extern void Evaluate(string scriptCode); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void InjectMouseDown(int x, int y, int button, int clickCount); + public extern bool DefineScriptObject(string path, ScriptableObject obj); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void Cut(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void Copy(); + public extern void SetDelegateObject(ScriptableObject value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void Paste(); + public extern void SetHostView(GUIView view); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SelectAll(); + public extern void SetSizeAndPosition(int x, int y, int width, int height); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void InjectMouseUp(int x, int y, int button, int clickCount); + public extern void SetFocus(bool value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void InjectMouseMove(int x, int y); + public extern void Show(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void InjectMouseDrag(int x, int y, int button); - internal void InjectScrollWheel(int x, int y, Vector2 delta) - { - WebView.INTERNAL_CALL_InjectScrollWheel(this, x, y, ref delta); - } + public extern void Hide(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_InjectScrollWheel(WebView self, int x, int y, ref Vector2 delta); + public extern void Back(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void InjectKeyboardEvent(Event e); + public extern void Forward(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Focus(); + public extern void Reload(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void UnFocus(); - internal bool InjectEvent(Event e, Rect position) - { - switch (e.type) - { - case EventType.MouseDown: - this.InjectMouseDown((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), (Application.platform != RuntimePlatform.OSXEditor || !e.control || e.button != 0) ? e.button : 1, e.clickCount); - goto IL_1D5; - case EventType.MouseUp: - this.InjectMouseUp((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), (Application.platform != RuntimePlatform.OSXEditor || !e.control || e.button != 0) ? e.button : 1, e.clickCount); - goto IL_1D5; - case EventType.MouseMove: - this.InjectMouseMove((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y)); - goto IL_1D5; - case EventType.MouseDrag: - this.InjectMouseDrag((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), e.button); - goto IL_1D5; - case EventType.KeyDown: - break; - case EventType.KeyUp: - break; - case EventType.ScrollWheel: - this.InjectScrollWheel((int)(e.mousePosition.x - position.x), (int)(e.mousePosition.y - position.y), e.delta); - goto IL_1D5; - default: - return false; - } - this.InjectKeyboardEvent(e); - IL_1D5: - if (Event.current == null) - { - GUIUtility.ExitGUI(); - } - return true; - } - public void DoGUI(Rect position) - { - int controlID = GUIUtility.GetControlID(this.GetHashCode(), FocusType.Native, position); - EventType type = Event.current.type; - switch (type) - { - case EventType.MouseDown: - { - Vector2 vector = GUIUtility.GUIToScreenPoint(new Vector2(position.x, position.y)); - this.SetWebkitControlsGlobalLocation((int)vector.x, (int)vector.y); - if (position.Contains(Event.current.mousePosition)) - { - GUIUtility.hotControl = controlID; - } - goto IL_251; - } - case EventType.MouseUp: - if (GUIUtility.hotControl == controlID) - { - GUIUtility.hotControl = 0; - } - goto IL_251; - case EventType.MouseMove: - case EventType.KeyDown: - case EventType.KeyUp: - case EventType.ScrollWheel: - { - IL_43: - string commandName; - if (type == EventType.ValidateCommand) - { - commandName = Event.current.commandName; - if (commandName != null) - { - if (WebView.<>f__switch$map1A == null) - { - WebView.<>f__switch$map1A = new Dictionary(4) - { - - { - "Cut", - 0 - }, - - { - "Copy", - 0 - }, - - { - "Paste", - 0 - }, - - { - "SelectAll", - 0 - } - }; - } - int num; - if (WebView.<>f__switch$map1A.TryGetValue(commandName, out num)) - { - if (num == 0) - { - Event.current.Use(); - } - } - } - return; - } - if (type != EventType.ExecuteCommand) - { - goto IL_251; - } - commandName = Event.current.commandName; - switch (commandName) - { - case "Cut": - this.Cut(); - break; - case "Copy": - this.Copy(); - break; - case "Paste": - this.Paste(); - break; - case "SelectAll": - this.SelectAll(); - break; - } - return; - } - case EventType.MouseDrag: - if (GUIUtility.hotControl == controlID) - { - Event.current.Use(); - } - goto IL_251; - case EventType.Repaint: - GUI.DrawTexture(position, this.texture); - return; - case EventType.Layout: - this.Resize((int)position.width, (int)position.height); - return; - } - goto IL_43; - IL_251: - if (this.InjectEvent(Event.current, position)) - { - Event.current.Use(); - } - else - { - if (GUIUtility.hotControl == controlID) - { - GUIUtility.hotControl = 0; - } - } - } - public void DoGUILayout(params GUILayoutOption[] options) - { - Rect rect = GUILayoutUtility.GetRect(new GUIContent(), EditorStyles.textField, options); - if (Event.current.type != EventType.Layout && Event.current.type != EventType.MouseUp) - { - this.Resize((int)rect.width, (int)rect.height); - this.DoGUI(rect); - } - } - public void Back() - { - this.windowScriptObject.EvalJavaScript("history.back();"); - } - public void Forward() - { - this.windowScriptObject.EvalJavaScript("history.forward();"); - } - public void Reload() - { - this.windowScriptObject.EvalJavaScript("document.location.reload(true);"); - } + private extern bool IntPtrIsNull(); public static implicit operator bool(WebView exists) { return exists != null && !exists.IntPtrIsNull(); diff --git a/UnityEditor/UnityEditor/WheelColliderEditor.cs b/UnityEditor/UnityEditor/WheelColliderEditor.cs index 3b1fdd23..b13d187e 100644 --- a/UnityEditor/UnityEditor/WheelColliderEditor.cs +++ b/UnityEditor/UnityEditor/WheelColliderEditor.cs @@ -3,22 +3,26 @@ namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(WheelCollider))] - internal class WheelColliderEditor : Collider3DEditorBase + internal class WheelColliderEditor : Editor { private SerializedProperty m_Center; private SerializedProperty m_Radius; private SerializedProperty m_SuspensionDistance; private SerializedProperty m_SuspensionSpring; + private SerializedProperty m_ForceAppPointDistance; private SerializedProperty m_Mass; + private SerializedProperty m_WheelDampingRate; private SerializedProperty m_ForwardFriction; private SerializedProperty m_SidewaysFriction; - public override void OnEnable() + public void OnEnable() { this.m_Center = base.serializedObject.FindProperty("m_Center"); this.m_Radius = base.serializedObject.FindProperty("m_Radius"); this.m_SuspensionDistance = base.serializedObject.FindProperty("m_SuspensionDistance"); this.m_SuspensionSpring = base.serializedObject.FindProperty("m_SuspensionSpring"); this.m_Mass = base.serializedObject.FindProperty("m_Mass"); + this.m_ForceAppPointDistance = base.serializedObject.FindProperty("m_ForceAppPointDistance"); + this.m_WheelDampingRate = base.serializedObject.FindProperty("m_WheelDampingRate"); this.m_ForwardFriction = base.serializedObject.FindProperty("m_ForwardFriction"); this.m_SidewaysFriction = base.serializedObject.FindProperty("m_SidewaysFriction"); } @@ -27,7 +31,9 @@ public override void OnInspectorGUI() base.serializedObject.Update(); EditorGUILayout.PropertyField(this.m_Mass, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_Radius, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_WheelDampingRate, new GUILayoutOption[0]); EditorGUILayout.PropertyField(this.m_SuspensionDistance, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_ForceAppPointDistance, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUILayout.PropertyField(this.m_Center, new GUILayoutOption[0]); EditorGUILayout.Space(); diff --git a/UnityEditor/UnityEditor/WindInspector.cs b/UnityEditor/UnityEditor/WindInspector.cs index eef293d2..080a8dd0 100644 --- a/UnityEditor/UnityEditor/WindInspector.cs +++ b/UnityEditor/UnityEditor/WindInspector.cs @@ -1,28 +1,57 @@ using System; +using UnityEditor.AnimatedValues; using UnityEngine; +using UnityEngine.Events; namespace UnityEditor { [CanEditMultipleObjects, CustomEditor(typeof(WindZone))] internal class WindInspector : Editor { + private class Styles + { + public static GUIContent Mode = EditorGUIUtility.TextContent("WindZone.Mode"); + public static GUIContent Radius = EditorGUIUtility.TextContent("WindZone.Radius"); + public static GUIContent WindMain = EditorGUIUtility.TextContent("WindZone.WindMain"); + public static GUIContent WindTurbulence = EditorGUIUtility.TextContent("WindZone.WindTurbulence"); + public static GUIContent WindPulseMagnitude = EditorGUIUtility.TextContent("WindZone.WindPulseMagnitude"); + public static GUIContent WindPulseFrequency = EditorGUIUtility.TextContent("WindZone.WindPulseFrequency"); + } + private SerializedProperty m_Mode; + private SerializedProperty m_Radius; + private SerializedProperty m_WindMain; + private SerializedProperty m_WindTurbulence; + private SerializedProperty m_WindPulseMagnitude; + private SerializedProperty m_WindPulseFrequency; + private readonly AnimBool m_ShowRadius = new AnimBool(); + private void OnEnable() + { + this.m_Mode = base.serializedObject.FindProperty("m_Mode"); + this.m_Radius = base.serializedObject.FindProperty("m_Radius"); + this.m_WindMain = base.serializedObject.FindProperty("m_WindMain"); + this.m_WindTurbulence = base.serializedObject.FindProperty("m_WindTurbulence"); + this.m_WindPulseMagnitude = base.serializedObject.FindProperty("m_WindPulseMagnitude"); + this.m_WindPulseFrequency = base.serializedObject.FindProperty("m_WindPulseFrequency"); + this.m_ShowRadius.value = (!this.m_Mode.hasMultipleDifferentValues && this.m_Mode.intValue == 1); + this.m_ShowRadius.valueChanged.AddListener(new UnityAction(base.Repaint)); + } + private void OnDisable() + { + this.m_ShowRadius.valueChanged.RemoveListener(new UnityAction(base.Repaint)); + } public override void OnInspectorGUI() { base.serializedObject.Update(); - GUI.enabled = true; - WindZone windZone = this.target as WindZone; - if (windZone == null) + EditorGUILayout.PropertyField(this.m_Mode, WindInspector.Styles.Mode, new GUILayoutOption[0]); + this.m_ShowRadius.target = (!this.m_Mode.hasMultipleDifferentValues && this.m_Mode.intValue == 1); + if (EditorGUILayout.BeginFadeGroup(this.m_ShowRadius.faded)) { - GUILayout.Label("Error: Not a WindZode", new GUILayoutOption[0]); - return; + EditorGUILayout.PropertyField(this.m_Radius, WindInspector.Styles.Radius, new GUILayoutOption[0]); } - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_Mode"), new GUILayoutOption[0]); - GUI.enabled = (windZone.mode == WindZoneMode.Spherical); - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_Radius"), new GUILayoutOption[0]); - GUI.enabled = true; - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindMain"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindTurbulence"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindPulseMagnitude"), new GUILayoutOption[0]); - EditorGUILayout.PropertyField(base.serializedObject.FindProperty("m_WindPulseFrequency"), new GUILayoutOption[0]); + EditorGUILayout.EndFadeGroup(); + EditorGUILayout.PropertyField(this.m_WindMain, WindInspector.Styles.WindMain, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_WindTurbulence, WindInspector.Styles.WindTurbulence, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_WindPulseMagnitude, WindInspector.Styles.WindPulseMagnitude, new GUILayoutOption[0]); + EditorGUILayout.PropertyField(this.m_WindPulseFrequency, WindInspector.Styles.WindPulseFrequency, new GUILayoutOption[0]); base.serializedObject.ApplyModifiedProperties(); } } diff --git a/UnityEditor/UnityEditor/WindowLayout.cs b/UnityEditor/UnityEditor/WindowLayout.cs index 26a634bd..2214ae30 100644 --- a/UnityEditor/UnityEditor/WindowLayout.cs +++ b/UnityEditor/UnityEditor/WindowLayout.cs @@ -12,7 +12,6 @@ internal class WindowLayout { private const string kMaximizeRestoreFile = "CurrentMaximizeLayout.dwlt"; internal static PrefKey s_MaximizeKey = new PrefKey("Window/Maximize View", "# "); - private static bool ms_IsLoadingWindowLayout = false; internal static string layoutsPreferencesPath { get @@ -27,13 +26,6 @@ internal static string layoutsProjectPath return Directory.GetCurrentDirectory() + "/Library"; } } - public static void WarnBrokenRepaint() - { - if (!WindowLayout.ms_IsLoadingWindowLayout) - { - UnityEngine.Debug.LogError("WindowLayouts are invalid. Please use 'Window -> Layouts -> Revert Factory Settings...' menu to fix it."); - } - } private static void ShowWindowImmediate(EditorWindow win) { win.Show(true); @@ -50,8 +42,8 @@ internal static EditorWindow FindEditorWindowOfType(Type type) [DebuggerHidden] private static IEnumerable FindEditorWindowsOfType() where T : class { - WindowLayout.c__Iterator3 c__Iterator = new WindowLayout.c__Iterator3(); - WindowLayout.c__Iterator3 expr_07 = c__Iterator; + WindowLayout.c__Iterator4 c__Iterator = new WindowLayout.c__Iterator4(); + WindowLayout.c__Iterator4 expr_07 = c__Iterator; expr_07.$PC = -2; return expr_07; } @@ -251,9 +243,7 @@ public static void Unmaximize(EditorWindow win) WindowLayout.RevertFactorySettings(); return; } - WindowLayout.ms_IsLoadingWindowLayout = true; UnityEngine.Object[] array = InternalEditorUtility.LoadSerializedFileAndForget(Path.Combine(WindowLayout.layoutsProjectPath, "CurrentMaximizeLayout.dwlt")); - WindowLayout.ms_IsLoadingWindowLayout = false; if (array.Length < 2) { UnityEngine.Debug.Log("Maximized serialized file backup not found"); @@ -446,9 +436,7 @@ public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated { ContainerWindow.SetFreezeDisplay(true); WindowLayout.CloseWindows(); - WindowLayout.ms_IsLoadingWindowLayout = true; UnityEngine.Object[] array3 = InternalEditorUtility.LoadSerializedFileAndForget(path); - WindowLayout.ms_IsLoadingWindowLayout = false; ContainerWindow containerWindow2 = null; ContainerWindow containerWindow3 = null; UnityEngine.Object[] array4 = array3; @@ -527,7 +515,7 @@ public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated catch (Exception arg) { UnityEngine.Debug.LogError("Failed to load window layout: " + arg); - switch (EditorUtility.DisplayDialogComplex("Failed to load window layout.", "This can happen if layout contains custom windows and there are compile errors in the project.", "Load Default Layout", "Quit", "Revert Factory Settings")) + switch (EditorUtility.DisplayDialogComplex("Failed to load window layout", "This can happen if layout contains custom windows and there are compile errors in the project.", "Load Default Layout", "Quit", "Revert Factory Settings")) { case 0: WindowLayout.LoadDefaultLayout(); @@ -543,7 +531,6 @@ public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated } finally { - WindowLayout.ms_IsLoadingWindowLayout = false; ContainerWindow.SetFreezeDisplay(false); if (Path.GetExtension(path) == ".wlt") { diff --git a/UnityEditor/UnityEditor/XboxOneDeployMethod.cs b/UnityEditor/UnityEditor/XboxOneDeployMethod.cs new file mode 100644 index 00000000..2303dcae --- /dev/null +++ b/UnityEditor/UnityEditor/XboxOneDeployMethod.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditor +{ + public enum XboxOneDeployMethod + { + Push, + Pull, + Package, + PackageStreaming + } +} diff --git a/UnityEditor/UnityEditor/XboxOneEncryptionLevel.cs b/UnityEditor/UnityEditor/XboxOneEncryptionLevel.cs new file mode 100644 index 00000000..80954f40 --- /dev/null +++ b/UnityEditor/UnityEditor/XboxOneEncryptionLevel.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum XboxOneEncryptionLevel + { + None, + DevkitCompatible, + FullEncryption + } +} diff --git a/UnityEditor/UnityEditor/XboxOneRunMethod.cs b/UnityEditor/UnityEditor/XboxOneRunMethod.cs deleted file mode 100644 index 8c2a2837..00000000 --- a/UnityEditor/UnityEditor/XboxOneRunMethod.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; -namespace UnityEditor -{ - public enum XboxOneRunMethod - { - Push, - Pull - } -} diff --git a/UnityEditor/UnityEditor/ZoomableArea.cs b/UnityEditor/UnityEditor/ZoomableArea.cs index deb23fd8..e18d860e 100644 --- a/UnityEditor/UnityEditor/ZoomableArea.cs +++ b/UnityEditor/UnityEditor/ZoomableArea.cs @@ -61,10 +61,14 @@ public void InitGUIStyles(bool minimalGUI) private static int zoomableAreaHash = "ZoomableArea".GetHashCode(); private bool m_HRangeLocked; private bool m_VRangeLocked; - private float m_HRangeMin = float.NegativeInfinity; - private float m_HRangeMax = float.PositiveInfinity; - private float m_VRangeMin = float.NegativeInfinity; - private float m_VRangeMax = float.PositiveInfinity; + private float m_HBaseRangeMin; + private float m_HBaseRangeMax = 1f; + private float m_VBaseRangeMin; + private float m_VBaseRangeMax = 1f; + private bool m_HAllowExceedBaseRangeMin = true; + private bool m_HAllowExceedBaseRangeMax = true; + private bool m_VAllowExceedBaseRangeMin = true; + private bool m_VAllowExceedBaseRangeMax = true; private float m_HScaleMin = 0.001f; private float m_HScaleMax = 100000f; private float m_VScaleMin = 0.001f; @@ -72,6 +76,7 @@ public void InitGUIStyles(bool minimalGUI) private bool m_ScaleWithWindow; private bool m_HSlider = true; private bool m_VSlider = true; + public bool m_UniformScale; private bool m_IgnoreScrollWheelUntilClicked; private Rect m_DrawArea = new Rect(0f, 0f, 100f, 100f); internal Vector2 m_Scale = new Vector2(1f, -1f); @@ -107,48 +112,136 @@ public bool vRangeLocked this.m_VRangeLocked = value; } } + public float hBaseRangeMin + { + get + { + return this.m_HBaseRangeMin; + } + set + { + this.m_HBaseRangeMin = value; + } + } + public float hBaseRangeMax + { + get + { + return this.m_HBaseRangeMax; + } + set + { + this.m_HBaseRangeMax = value; + } + } + public float vBaseRangeMin + { + get + { + return this.m_VBaseRangeMin; + } + set + { + this.m_VBaseRangeMin = value; + } + } + public float vBaseRangeMax + { + get + { + return this.m_VBaseRangeMax; + } + set + { + this.m_VBaseRangeMax = value; + } + } + public bool hAllowExceedBaseRangeMin + { + get + { + return this.m_HAllowExceedBaseRangeMin; + } + set + { + this.m_HAllowExceedBaseRangeMin = value; + } + } + public bool hAllowExceedBaseRangeMax + { + get + { + return this.m_HAllowExceedBaseRangeMax; + } + set + { + this.m_HAllowExceedBaseRangeMax = value; + } + } + public bool vAllowExceedBaseRangeMin + { + get + { + return this.m_VAllowExceedBaseRangeMin; + } + set + { + this.m_VAllowExceedBaseRangeMin = value; + } + } + public bool vAllowExceedBaseRangeMax + { + get + { + return this.m_VAllowExceedBaseRangeMax; + } + set + { + this.m_VAllowExceedBaseRangeMax = value; + } + } public float hRangeMin { get { - return this.m_HRangeMin; + return (!this.hAllowExceedBaseRangeMin) ? this.hBaseRangeMin : float.NegativeInfinity; } set { - this.m_HRangeMin = value; + this.SetAllowExceed(ref this.m_HBaseRangeMin, ref this.m_HAllowExceedBaseRangeMin, value); } } public float hRangeMax { get { - return this.m_HRangeMax; + return (!this.hAllowExceedBaseRangeMax) ? this.hBaseRangeMax : float.PositiveInfinity; } set { - this.m_HRangeMax = value; + this.SetAllowExceed(ref this.m_HBaseRangeMax, ref this.m_HAllowExceedBaseRangeMax, value); } } public float vRangeMin { get { - return this.m_VRangeMin; + return (!this.vAllowExceedBaseRangeMin) ? this.vBaseRangeMin : float.NegativeInfinity; } set { - this.m_VRangeMin = value; + this.SetAllowExceed(ref this.m_VBaseRangeMin, ref this.m_VAllowExceedBaseRangeMin, value); } } public float vRangeMax { get { - return this.m_VRangeMax; + return (!this.vAllowExceedBaseRangeMax) ? this.vBaseRangeMax : float.PositiveInfinity; } set { - this.m_VRangeMax = value; + this.SetAllowExceed(ref this.m_VBaseRangeMax, ref this.m_VAllowExceedBaseRangeMax, value); } } public bool scaleWithWindow @@ -188,6 +281,17 @@ public bool vSlider this.rect = rect; } } + public bool uniformScale + { + get + { + return this.m_UniformScale; + } + set + { + this.m_UniformScale = value; + } + } public bool ignoreScrollWheelUntilClicked { get @@ -346,9 +450,7 @@ public virtual Bounds drawingBounds { get { - bool flag = this.hRangeMin > float.NegativeInfinity && this.hRangeMax < float.PositiveInfinity; - bool flag2 = this.vRangeMin > float.NegativeInfinity && this.vRangeMax < float.PositiveInfinity; - return new Bounds(new Vector3((!flag) ? 0f : ((this.hRangeMin + this.hRangeMax) * 0.5f), (!flag2) ? 0f : ((this.vRangeMin + this.hRangeMax) * 0.5f), 0f), new Vector3((!flag) ? 2f : (this.hRangeMax - this.hRangeMin), (!flag2) ? 2f : (this.vRangeMax - this.vRangeMin), 1f)); + return new Bounds(new Vector3((this.hBaseRangeMin + this.hBaseRangeMax) * 0.5f, (this.vBaseRangeMin + this.vBaseRangeMax) * 0.5f, 0f), new Vector3(this.hBaseRangeMax - this.hBaseRangeMin, this.vBaseRangeMax - this.vBaseRangeMin, 1f)); } } public Matrix4x4 drawingToViewMatrix @@ -375,6 +477,19 @@ public ZoomableArea(bool minimalGUI) this.m_MinimalGUI = minimalGUI; this.styles = new ZoomableArea.Styles(minimalGUI); } + private void SetAllowExceed(ref float rangeEnd, ref bool allowExceed, float value) + { + if (value == float.NegativeInfinity || value == float.PositiveInfinity) + { + rangeEnd = (float)((value != float.NegativeInfinity) ? 1 : 0); + allowExceed = true; + } + else + { + rangeEnd = value; + allowExceed = false; + } + } internal void SetDrawRectHack(Rect r, bool scrollbars) { this.m_DrawArea = r; @@ -544,6 +659,7 @@ private void SliderGUI() Rect shownAreaInsideMargins = this.shownAreaInsideMargins; float num = this.styles.sliderWidth - this.styles.visualSliderWidth; float num2 = (!this.vSlider || !this.hSlider) ? 0f : num; + Vector2 a = this.m_Scale; if (this.m_HSlider) { Rect position = new Rect(this.drawRect.x + 1f, this.drawRect.yMax - num, this.drawRect.width - num2, this.styles.sliderWidth); @@ -580,6 +696,16 @@ private void SliderGUI() } this.SetShownVRangeInsideMargins(num3, num4); } + if (this.uniformScale) + { + float num6 = this.drawRect.width / this.drawRect.height; + a -= this.m_Scale; + Vector2 b = new Vector2(-a.y * num6, -a.x / num6); + this.m_Scale -= b; + this.m_Translation.x = this.m_Translation.x - a.y / 2f; + this.m_Translation.y = this.m_Translation.y - a.x / 2f; + this.EnforceScaleAndRange(); + } } private void Pan() { diff --git a/UnityEditor/UnityEditor/iOSAppInBackgroundBehavior.cs b/UnityEditor/UnityEditor/iOSAppInBackgroundBehavior.cs new file mode 100644 index 00000000..16c4ea0c --- /dev/null +++ b/UnityEditor/UnityEditor/iOSAppInBackgroundBehavior.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEditor +{ + public enum iOSAppInBackgroundBehavior + { + Custom = -1, + Suspend, + Exit + } +} diff --git a/UnityEditor/UnityEditor/iOSLaunchScreenType.cs b/UnityEditor/UnityEditor/iOSLaunchScreenType.cs deleted file mode 100644 index d6f13cb7..00000000 --- a/UnityEditor/UnityEditor/iOSLaunchScreenType.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -namespace UnityEditor -{ - internal enum iOSLaunchScreenType - { - Default, - None, - ImageAndBackgroundRelative, - ImageAndBackgroundConstant, - CustomXib - } -} diff --git a/UnityEditor/UnityEditor/iPhoneArchitecture.cs b/UnityEditor/UnityEditor/iPhoneArchitecture.cs deleted file mode 100644 index 4a5af6b6..00000000 --- a/UnityEditor/UnityEditor/iPhoneArchitecture.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; -namespace UnityEditor -{ - public enum iPhoneArchitecture - { - ARMv7, - ARM64, - Universal - } -} diff --git a/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs b/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs index dd8d9962..0459b219 100644 --- a/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs +++ b/UnityEditor/UnityEditorInternal.VersionControl/ListControl.cs @@ -446,7 +446,7 @@ private bool HandleMouse(Rect area) if (current.type == EventType.ContextClick) { this.singleSelect = null; - if (this.IsSelectedFolder() && !string.IsNullOrEmpty(this.menuFolder)) + if (!this.IsSelectedAsset() && !string.IsNullOrEmpty(this.menuFolder)) { ListControl.s_uniqueIDList[this.uniqueID] = this; EditorUtility.DisplayPopupMenu(new Rect(current.mousePosition.x, current.mousePosition.y, 0f, 0f), this.menuFolder, new MenuCommand(null, this.uniqueID)); @@ -908,16 +908,16 @@ private bool IsSelected(ListItem item) } return item.Change != null && this.selectList.ContainsKey("_chkeyprfx_" + item.Change.id.ToString()); } - private bool IsSelectedFolder() + private bool IsSelectedAsset() { foreach (KeyValuePair current in this.selectList) { - if (current.Value != null && current.Value.Asset != null && !current.Value.Asset.isFolder) + if (current.Value != null && current.Value.Asset != null) { - return false; + return true; } } - return true; + return false; } private void SelectedClear() { diff --git a/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs b/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs index fb019eb4..b816ace6 100644 --- a/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs +++ b/UnityEditor/UnityEditorInternal.VersionControl/Overlay.cs @@ -70,46 +70,67 @@ private static void DrawOverlays() { Overlay.DrawOverlay(Asset.States.AddedLocal, iconRect); } - if (Overlay.IsState(Asset.States.AddedRemote)) - { - Overlay.DrawOverlay(Asset.States.AddedRemote, iconRect2); - } - if (Overlay.IsState(Asset.States.CheckedOutLocal) && !Overlay.IsState(Asset.States.LockedLocal) && !Overlay.IsState(Asset.States.AddedLocal)) - { - Overlay.DrawOverlay(Asset.States.CheckedOutLocal, iconRect); - } - if (Overlay.IsState(Asset.States.CheckedOutRemote) && !Overlay.IsState(Asset.States.LockedRemote) && !Overlay.IsState(Asset.States.AddedRemote)) - { - Overlay.DrawOverlay(Asset.States.CheckedOutRemote, iconRect2); - } - if (Overlay.IsState(Asset.States.DeletedLocal)) - { - Overlay.DrawOverlay(Asset.States.DeletedLocal, iconRect); - } - if (Overlay.IsState(Asset.States.DeletedRemote)) + else { - Overlay.DrawOverlay(Asset.States.DeletedRemote, iconRect2); + if (Overlay.IsState(Asset.States.DeletedLocal)) + { + Overlay.DrawOverlay(Asset.States.DeletedLocal, iconRect); + } + else + { + if (Overlay.IsState(Asset.States.LockedLocal)) + { + Overlay.DrawOverlay(Asset.States.LockedLocal, iconRect); + } + else + { + if (Overlay.IsState(Asset.States.CheckedOutLocal)) + { + Overlay.DrawOverlay(Asset.States.CheckedOutLocal, iconRect); + } + else + { + if (Overlay.IsState(Asset.States.Local) && !Overlay.IsState(Asset.States.OutOfSync) && !Overlay.IsState(Asset.States.Synced)) + { + Overlay.DrawOverlay(Asset.States.Local, iconRect3); + } + } + } + } } - if (Overlay.IsState(Asset.States.Local) && !Overlay.IsState(Asset.States.OutOfSync) && !Overlay.IsState(Asset.States.Synced) && !Overlay.IsState(Asset.States.AddedLocal)) + if (Overlay.IsState(Asset.States.Conflicted)) { - Overlay.DrawOverlay(Asset.States.Local, iconRect3); + Overlay.DrawOverlay(Asset.States.Conflicted, iconRect3); } - if (Overlay.IsState(Asset.States.LockedLocal)) + if (Overlay.IsState(Asset.States.AddedRemote)) { - Overlay.DrawOverlay(Asset.States.LockedLocal, iconRect); + Overlay.DrawOverlay(Asset.States.AddedRemote, iconRect2); } - if (Overlay.IsState(Asset.States.LockedRemote)) + else { - Overlay.DrawOverlay(Asset.States.LockedRemote, iconRect2); + if (Overlay.IsState(Asset.States.DeletedRemote)) + { + Overlay.DrawOverlay(Asset.States.DeletedRemote, iconRect2); + } + else + { + if (Overlay.IsState(Asset.States.LockedRemote)) + { + Overlay.DrawOverlay(Asset.States.LockedRemote, iconRect2); + } + else + { + if (Overlay.IsState(Asset.States.CheckedOutRemote)) + { + Overlay.DrawOverlay(Asset.States.CheckedOutRemote, iconRect2); + } + } + } } if (Overlay.IsState(Asset.States.OutOfSync)) { Overlay.DrawOverlay(Asset.States.OutOfSync, iconRect4); } - if (Overlay.IsState(Asset.States.Conflicted)) - { - Overlay.DrawOverlay(Asset.States.Conflicted, iconRect3); - } } private static bool IsState(Asset.States state) { diff --git a/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs b/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs index 2006fc6c..8e01639a 100644 --- a/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs +++ b/UnityEditor/UnityEditorInternal.VersionControl/PendingWindowContextMenu.cs @@ -76,9 +76,9 @@ private static bool ShowInExplorerTest(int userData) { return ListControl.FromID(userData).SelectedAssets.Count > 0; } - private static void ShowInExplorer(int userDatad) + private static void ShowInExplorer(int userData) { - EditorApplication.ExecuteMenuItem("Assets/Show in Explorer"); + EditorApplication.ExecuteMenuItem("Assets/Reveal in Finder"); } private static bool NewChangeSetTest(int userData) { diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs index 718082ce..638d0328 100644 --- a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchy.cs @@ -32,7 +32,7 @@ public void InitIfNeeded(EditorWindow owner, Rect rect) this.m_TreeView.deselectOnUnhandledMouseDown = true; this.m_TreeViewDataSource = new AddCurvesPopupHierarchyDataSource(this.m_TreeView, this.state); TreeViewGUI gui = new AddCurvesPopupHierarchyGUI(this.m_TreeView, this.state, owner); - this.m_TreeView.Init(rect, this.m_TreeViewDataSource, gui, new AssetOrGameObjectTreeViewDragging(this.m_TreeView, HierarchyType.GameObjects)); + this.m_TreeView.Init(rect, this.m_TreeViewDataSource, gui, new GameObjectsTreeViewDragging(this.m_TreeView)); this.m_TreeViewDataSource.UpdateData(); return; } diff --git a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs index 36109c11..a0309f16 100644 --- a/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs +++ b/UnityEditor/UnityEditorInternal/AddCurvesPopupHierarchyGUI.cs @@ -19,7 +19,7 @@ public bool showPlusButton get; set; } - public AddCurvesPopupHierarchyGUI(TreeView treeView, AnimationWindowState state, EditorWindow owner) : base(treeView) + public AddCurvesPopupHierarchyGUI(TreeView treeView, AnimationWindowState state, EditorWindow owner) : base(treeView, true) { this.owner = owner; this.state = state; diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs index 0fa52672..6b6c22f5 100644 --- a/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs +++ b/UnityEditor/UnityEditorInternal/AnimationWindowHierarchyGUI.cs @@ -23,11 +23,12 @@ internal class AnimationWindowHierarchyGUI : TreeViewGUI private GUIStyle animationSelectionTextField; private GUIStyle animationLineStyle; private GUIStyle animationCurveDropdown; + private readonly GUIContent k_AnimatePropertyLabel = new GUIContent("Add Property"); private AnimationWindowHierarchyNode m_RenamedNode; private Color m_LightSkinPropertyTextColor = new Color(0.35f, 0.35f, 0.35f); - private static Color k_KeyColorInDopesheetMode = new Color(0.7f, 0.7f, 0.7f, 1f); - private static Color k_KeyColorForNonCurves = new Color(0.7f, 0.7f, 0.7f, 0.5f); - private static Color k_LeftoverCurveColor = Color.yellow; + private static readonly Color k_KeyColorInDopesheetMode = new Color(0.7f, 0.7f, 0.7f, 1f); + private static readonly Color k_KeyColorForNonCurves = new Color(0.7f, 0.7f, 0.7f, 0.5f); + private static readonly Color k_LeftoverCurveColor = Color.yellow; internal static int s_WasInsideValueRectFrame = -1; public AnimationWindowState state { @@ -114,10 +115,10 @@ public override void BeginRowGUI() } private void DoAddCurveButton(Rect rect) { - float num = 24f; + float num = (rect.width - 230f) / 2f; float num2 = 10f; Rect rect2 = new Rect(rect.xMin + num, rect.yMin + num2, rect.width - num * 2f, rect.height - num2 * 2f); - if (GUI.Button(rect2, "Add Curve")) + if (GUI.Button(rect2, this.k_AnimatePropertyLabel)) { if (!this.state.m_AnimationWindow.EnsureAnimationMode()) { @@ -203,6 +204,19 @@ private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool se rect.width -= 77f; } bool flag2 = AnimationWindowUtility.IsNodeLeftOverCurve(node, this.state.m_RootGameObject); + bool flag3 = AnimationWindowUtility.IsNodeAmbiguous(node, this.state.m_RootGameObject); + string text = string.Empty; + string tooltip = string.Empty; + if (flag2) + { + text = " (Missing!)"; + tooltip = "The GameObject or Component is missing (" + node.path + ")"; + } + if (flag3) + { + text = " (Duplicate GameObject name!)"; + tooltip = "Target for curve is ambiguous since there are multiple GameObjects with same name (" + node.path + ")"; + } if (node.depth == 0) { Transform x = this.state.m_RootGameObject.transform.Find(node.path); @@ -210,26 +224,24 @@ private void DoIconAndName(Rect rect, AnimationWindowHierarchyNode node, bool se { flag2 = true; } - GUIContent content = new GUIContent(this.GetGameObjectName(node.path) + " : " + node.displayName, this.GetIconForNode(node)); + TreeViewGUI.s_Styles.content = new GUIContent(this.GetGameObjectName(node.path) + " : " + node.displayName + text, this.GetIconForNode(node), tooltip); Color textColor = this.animationLineStyle.normal.textColor; Color color = (!EditorGUIUtility.isProSkin) ? Color.black : (Color.gray * 1.35f); - color = ((!flag2) ? color : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); + color = ((!flag2 && !flag3) ? color : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); this.SetStyleTextColor(this.animationLineStyle, color); rect.xMin += (float)((int)(indent + this.k_FoldoutWidth)); - this.animationLineStyle.Draw(rect, content, flag, flag, selected, focused); + GUI.Label(rect, TreeViewGUI.s_Styles.content, this.animationLineStyle); this.SetStyleTextColor(this.animationLineStyle, textColor); } else { - TreeViewGUI.s_Styles.content.text = node.displayName; - Texture iconForNode = this.GetIconForNode(node); - TreeViewGUI.s_Styles.content.image = iconForNode; + TreeViewGUI.s_Styles.content = new GUIContent(node.displayName + text, this.GetIconForNode(node), tooltip); Color textColor2 = this.animationLineStyle.normal.textColor; Color color2 = (!EditorGUIUtility.isProSkin) ? this.m_LightSkinPropertyTextColor : Color.gray; - color2 = ((!flag2) ? color2 : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); + color2 = ((!flag2 && !flag3) ? color2 : AnimationWindowHierarchyGUI.k_LeftoverCurveColor); this.SetStyleTextColor(this.animationLineStyle, color2); rect.xMin += (float)((int)(indent + this.k_IndentWidth + this.k_FoldoutWidth)); - this.animationLineStyle.Draw(rect, TreeViewGUI.s_Styles.content, flag, flag, selected, focused); + GUI.Label(rect, TreeViewGUI.s_Styles.content, this.animationLineStyle); this.SetStyleTextColor(this.animationLineStyle, textColor2); if (this.m_TreeView.dragging.GetRowMarkerControlID() == itemControlID) { @@ -272,8 +284,8 @@ private void DoValueField(Rect rect, AnimationWindowHierarchyNode node, int row) EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); if (node is AnimationWindowHierarchyPropertyNode) { - AnimationWindowCurve[] curves = this.state.GetCurves(node, false); - if (curves == null || curves.Length == 0) + List curves = this.state.GetCurves(node, false); + if (curves == null || curves.Count == 0) { return; } @@ -439,7 +451,7 @@ private GenericMenu GenerateMenu(List interactedNo genericMenu.AddItem(new GUIContent((curvesAffectedByNodes.Count <= 1 && !flag) ? "Remove Property" : "Remove Properties"), false, new GenericMenu.MenuFunction(this.RemoveCurvesFromSelectedNodes)); bool flag2 = true; EditorCurveBinding[] array = new EditorCurveBinding[curvesAffectedByNodes2.Count]; - for (int i = 0; i < curvesAffectedByNodes.Count; i++) + for (int i = 0; i < curvesAffectedByNodes2.Count; i++) { array[i] = curvesAffectedByNodes2[i].binding; } @@ -582,20 +594,18 @@ private void RemoveCurvesFromNodes(List nodes) } } } - AnimationWindowCurve[] array; + List list; if (animationWindowHierarchyNode is AnimationWindowHierarchyPropertyGroupNode || animationWindowHierarchyNode is AnimationWindowHierarchyPropertyNode) { - array = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType, animationWindowHierarchyNode.propertyName); + list = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType, animationWindowHierarchyNode.propertyName); } else { - array = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType); + list = AnimationWindowUtility.FilterCurves(this.state.allCurves.ToArray(), animationWindowHierarchyNode.path, animationWindowHierarchyNode.animatableObjectType); } - AnimationWindowCurve[] array2 = array; - for (int i = 0; i < array2.Length; i++) + foreach (AnimationWindowCurve current2 in list) { - AnimationWindowCurve curve = array2[i]; - this.state.RemoveCurve(curve); + this.state.RemoveCurve(current2); } } this.m_TreeView.ReloadData(); @@ -606,24 +616,10 @@ private List GetCurvesAffectedByNodes(List activeCurves AnimationWindowHierarchyNode animationWindowHierarchyNode = treeViewItem as AnimationWindowHierarchyNode; if (animationWindowHierarchyNode != null) { - AnimationWindowCurve[] curves = this.GetCurves(animationWindowHierarchyNode, true); - AnimationWindowCurve[] array = curves; - for (int i = 0; i < array.Length; i++) + List curves = this.GetCurves(animationWindowHierarchyNode, true); + foreach (AnimationWindowCurve current2 in curves) { - AnimationWindowCurve item = array[i]; - if (!this.m_ActiveCurvesCache.Contains(item)) + if (!this.m_ActiveCurvesCache.Contains(current2)) { - this.m_ActiveCurvesCache.Add(item); + this.m_ActiveCurvesCache.Add(current2); } } } @@ -149,16 +147,16 @@ public List dopelines AnimationWindowHierarchyNode animationWindowHierarchyNode = current as AnimationWindowHierarchyNode; if (animationWindowHierarchyNode != null && !(animationWindowHierarchyNode is AnimationWindowHierarchyAddButtonNode)) { - AnimationWindowCurve[] curves; + List list; if (current is AnimationWindowHierarchyMasterNode) { - curves = this.allCurves.ToArray(); + list = this.allCurves; } else { - curves = this.GetCurves(animationWindowHierarchyNode, true); + list = this.GetCurves(animationWindowHierarchyNode, true); } - DopeLine dopeLine = new DopeLine(current.id, curves); + DopeLine dopeLine = new DopeLine(current.id, list.ToArray()); dopeLine.tallMode = this.m_hierarchyState.getTallMode(animationWindowHierarchyNode); dopeLine.objectType = animationWindowHierarchyNode.animatableObjectType; dopeLine.hasChildren = !(animationWindowHierarchyNode is AnimationWindowHierarchyPropertyNode); @@ -256,14 +254,14 @@ public bool IsReadOnly { get { - return !this.m_ActiveAnimationClip || !this.IsEditable; + return !this.m_ActiveAnimationClip || !this.IsEditable || (this.m_ActiveAnimationClip.hideFlags & HideFlags.NotEditable) != HideFlags.None; } } public bool IsEditable { get { - return this.m_ActiveGameObject && (!this.m_ActiveAnimationClip || (this.m_ActiveAnimationClip.hideFlags & HideFlags.NotEditable) == HideFlags.None) && !this.IsPrefab; + return this.m_ActiveGameObject && !this.IsPrefab; } } public bool IsClipEditable @@ -315,6 +313,15 @@ public float frameRate } this.SaveCurve(current); } + AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(this.m_ActiveAnimationClip); + AnimationEvent[] array = animationEvents; + for (int i = 0; i < array.Length; i++) + { + AnimationEvent animationEvent = array[i]; + int frame2 = AnimationKeyTime.Time(animationEvent.time, this.frameRate).frame; + animationEvent.time = AnimationKeyTime.Frame(frame2, value).time; + } + AnimationUtility.SetAnimationEvents(this.m_ActiveAnimationClip, animationEvents); this.m_ActiveAnimationClip.frameRate = value; this.m_CurveEditorIsDirty = true; } @@ -712,7 +719,7 @@ public void Repaint() this.m_Window.Repaint(); } } - public AnimationWindowCurve[] GetCurves(AnimationWindowHierarchyNode hierarchyNode, bool entireHierarchy) + public List GetCurves(AnimationWindowHierarchyNode hierarchyNode, bool entireHierarchy) { return AnimationWindowUtility.FilterCurves(this.allCurves.ToArray(), hierarchyNode.path, hierarchyNode.animatableObjectType, hierarchyNode.propertyName); } @@ -769,6 +776,45 @@ public void ClearHierarchySelection() { this.m_hierarchyState.selectedIDs.Clear(); } + public List GetAffectedHierarchyIDs(List keyframes) + { + List list = new List(); + foreach (DopeLine current in this.GetAffectedDopelines(keyframes)) + { + if (!list.Contains(current.m_HierarchyNodeID)) + { + list.Add(current.m_HierarchyNodeID); + } + } + return list; + } + public List GetAffectedDopelines(List keyframes) + { + List list = new List(); + foreach (AnimationWindowCurve current in this.GetAffectedCurves(keyframes)) + { + foreach (DopeLine current2 in this.dopelines) + { + if (!list.Contains(current2) && current2.m_Curves.Contains(current)) + { + list.Add(current2); + } + } + } + return list; + } + public List GetAffectedCurves(List keyframes) + { + List list = new List(); + foreach (AnimationWindowKeyframe current in keyframes) + { + if (!list.Contains(current.curve)) + { + list.Add(current.curve); + } + } + return list; + } private void SyncSceneSelection(int[] selectedNodeIDs) { List list = new List(); diff --git a/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs b/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs index da9b3e89..540aa380 100644 --- a/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs +++ b/UnityEditor/UnityEditorInternal/AnimationWindowUtility.cs @@ -64,6 +64,31 @@ public static bool IsNodeLeftOverCurve(AnimationWindowHierarchyNode node, GameOb } return false; } + public static bool IsNodeAmbiguous(AnimationWindowHierarchyNode node, GameObject rootGameObject) + { + if (rootGameObject == null) + { + return false; + } + EditorCurveBinding? binding = node.binding; + if (binding.HasValue) + { + return AnimationUtility.AmbiguousBinding(node.binding.Value.path, node.binding.Value.m_ClassID, rootGameObject.transform); + } + if (node.hasChildren) + { + using (List.Enumerator enumerator = node.children.GetEnumerator()) + { + if (enumerator.MoveNext()) + { + TreeViewItem current = enumerator.Current; + return AnimationWindowUtility.IsNodeAmbiguous(current as AnimationWindowHierarchyNode, rootGameObject); + } + } + return false; + } + return false; + } public static void AddSelectedKeyframes(AnimationWindowState state, AnimationKeyTime time) { foreach (AnimationWindowCurve current in state.activeCurves) @@ -126,7 +151,7 @@ public static AnimationWindowKeyframe AddKeyframeToCurve(AnimationWindowCurve cu } return animationWindowKeyframe2; } - public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, bool entireHierarchy) + public static List FilterCurves(AnimationWindowCurve[] curves, string path, bool entireHierarchy) { List list = new List(); for (int i = 0; i < curves.Length; i++) @@ -137,9 +162,9 @@ public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, list.Add(animationWindowCurve); } } - return list.ToArray(); + return list; } - public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType) + public static List FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType) { List list = new List(); for (int i = 0; i < curves.Length; i++) @@ -150,7 +175,7 @@ public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, list.Add(animationWindowCurve); } } - return list.ToArray(); + return list; } public static bool IsCurveCreated(AnimationClip clip, EditorCurveBinding binding) { @@ -183,18 +208,21 @@ public static bool ContainsFloatKeyframes(List keyframe } return false; } - public static AnimationWindowCurve[] FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType, string propertyName) + public static List FilterCurves(AnimationWindowCurve[] curves, string path, Type animatableObjectType, string propertyName) { List list = new List(); + string propertyGroupName = AnimationWindowUtility.GetPropertyGroupName(propertyName); + bool flag = propertyGroupName == propertyName; for (int i = 0; i < curves.Length; i++) { AnimationWindowCurve animationWindowCurve = curves[i]; - if (animationWindowCurve.path.Equals(path) && animationWindowCurve.type == animatableObjectType && (animationWindowCurve.propertyName.Equals(propertyName) || animationWindowCurve.propertyName.Contains(propertyName))) + bool flag2 = (!flag) ? animationWindowCurve.propertyName.Equals(propertyName) : AnimationWindowUtility.GetPropertyGroupName(animationWindowCurve.propertyName).Equals(propertyGroupName); + if (animationWindowCurve.path.Equals(path) && animationWindowCurve.type == animatableObjectType && flag2) { list.Add(animationWindowCurve); } } - return list.ToArray(); + return list; } public static object GetCurrentValue(GameObject rootGameObject, EditorCurveBinding curveBinding) { @@ -208,7 +236,7 @@ public static object GetCurrentValue(GameObject rootGameObject, EditorCurveBindi AnimationUtility.GetFloatValue(rootGameObject, curveBinding, out num); return num; } - public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, GameObject gameObject, Type valueType) + public static List GetAnimatableProperties(GameObject root, GameObject gameObject, Type valueType) { EditorCurveBinding[] animatableBindings = AnimationUtility.GetAnimatableBindings(root, gameObject); List list = new List(); @@ -221,9 +249,9 @@ public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, Game list.Add(editorCurveBinding); } } - return list.ToArray(); + return list; } - public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, GameObject gameObject, Type objectType, Type valueType) + public static List GetAnimatableProperties(GameObject root, GameObject gameObject, Type objectType, Type valueType) { EditorCurveBinding[] animatableBindings = AnimationUtility.GetAnimatableBindings(root, gameObject); List list = new List(); @@ -236,7 +264,7 @@ public static EditorCurveBinding[] GetAnimatableProperties(GameObject root, Game list.Add(editorCurveBinding); } } - return list.ToArray(); + return list; } public static bool CurveExists(EditorCurveBinding binding, AnimationWindowCurve[] curves) { @@ -402,7 +430,7 @@ public static int GetPropertyNodeID(string path, Type type, string propertyName) } public static Transform GetClosestAnimationComponentInParents(Transform tr) { - while (!tr.animation && !tr.GetComponent()) + while (!tr.GetComponent() && !tr.GetComponent()) { if (tr == tr.root) { diff --git a/UnityEditor/UnityEditorInternal/AnimatorCondition.cs b/UnityEditor/UnityEditorInternal/AnimatorCondition.cs deleted file mode 100644 index d198da77..00000000 --- a/UnityEditor/UnityEditorInternal/AnimatorCondition.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System; -using UnityEngine; -namespace UnityEditorInternal -{ - public sealed class AnimatorCondition - { - private Transition m_Transition; - private int m_Index; - private bool m_Valid; - public TransitionConditionMode mode - { - get - { - return (!this.checkValid()) ? ((TransitionConditionMode)0) : this.m_Transition.GetConditionMode(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Transition.SetConditionMode(this.m_Index, value); - } - } - } - public string parameter - { - get - { - return (!this.checkValid()) ? string.Empty : this.m_Transition.GetConditionParameter(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Transition.SetConditionParameter(this.m_Index, value); - } - } - } - public float threshold - { - get - { - return (!this.checkValid()) ? 0f : this.m_Transition.GetParameterTreshold(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Transition.SetParameterTreshold(this.m_Index, value); - } - } - } - public float exitTime - { - get - { - return (!this.checkValid()) ? 0f : this.m_Transition.GetExitTime(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Transition.SetExitTime(this.m_Index, value); - } - } - } - internal AnimatorCondition(Transition transition, int index) - { - this.m_Transition = transition; - this.m_Index = index; - transition.onRemovedCondition = (Transition.RemovedCondition)Delegate.Combine(transition.onRemovedCondition, new Transition.RemovedCondition(this.RemoveCondition)); - this.m_Valid = true; - } - private bool checkValid() - { - if (!this.m_Valid) - { - Debug.LogError("AnimatorCondition is not valid anymore. It was removed"); - return false; - } - return true; - } - private void RemoveCondition(int index) - { - if (index == this.m_Index) - { - this.m_Valid = false; - } - else - { - if (index < this.m_Index) - { - this.m_Index--; - } - } - } - } -} diff --git a/UnityEditor/UnityEditorInternal/AnimatorController.cs b/UnityEditor/UnityEditorInternal/AnimatorController.cs index 8c0ff384..7e9241dc 100644 --- a/UnityEditor/UnityEditorInternal/AnimatorController.cs +++ b/UnityEditor/UnityEditorInternal/AnimatorController.cs @@ -1,250 +1,9 @@ using System; -using System.IO; -using System.Runtime.CompilerServices; -using UnityEditor; using UnityEngine; namespace UnityEditorInternal { - public sealed class AnimatorController : RuntimeAnimatorController + [Obsolete("AnimatorController is obsolete. Use UnityEditor.Animations.AnimatorController instead (UnityUpgradable).", true)] + public class AnimatorController : RuntimeAnimatorController { - internal delegate void RemovedParameter(int index); - internal delegate void RemovedLayer(int index); - private const string kControllerExtension = "controller"; - public Action OnAnimatorControllerDirty; - internal AnimatorController.RemovedParameter onRemovedParameter; - internal AnimatorController.RemovedLayer onRemovedLayer; - public extern int layerCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int parameterCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - internal extern bool isAssetBundled - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public AnimatorController() - { - AnimatorController.Internal_Create(this); - } - internal string GetDefaultBlendTreeParameter() - { - for (int i = 0; i < this.parameterCount; i++) - { - if (this.GetParameterType(i) == AnimatorControllerParameterType.Float) - { - return this.GetParameterName(i); - } - } - return "Blend"; - } - internal static void OnInvalidateAnimatorController(AnimatorController controller) - { - if (controller.OnAnimatorControllerDirty != null) - { - controller.OnAnimatorControllerDirty(); - } - } - public static AnimatorController CreateAnimatorControllerAtPath(string path) - { - AnimatorController animatorController = new AnimatorController(); - animatorController.name = Path.GetFileName(path); - AssetDatabase.CreateAsset(animatorController, path); - animatorController.AddLayer("Base Layer"); - return animatorController; - } - public static AnimationClip AllocateAnimatorClip(string name) - { - AnimationClip animationClip = AnimationSelection.AllocateAndSetupClip(true); - animationClip.name = name; - return animationClip; - } - public static AnimatorController CreateAnimatorControllerForClip(AnimationClip clip, GameObject animatedObject) - { - string text = AssetDatabase.GetAssetPath(clip); - if (string.IsNullOrEmpty(text)) - { - return null; - } - text = Path.Combine(FileUtil.DeleteLastPathNameComponent(text), animatedObject.name + ".controller"); - text = AssetDatabase.GenerateUniqueAssetPath(text); - if (string.IsNullOrEmpty(text)) - { - return null; - } - return AnimatorController.CreateAnimatorControllerAtPathWithClip(text, clip); - } - public static State AddAnimationClipToController(AnimatorController controller, AnimationClip clip) - { - StateMachine layerStateMachine = controller.GetLayerStateMachine(0); - Vector3 position = (layerStateMachine.stateCount <= 0) ? new Vector3(200f, 0f, 0f) : (layerStateMachine.GetState(layerStateMachine.stateCount - 1).position + new Vector3(35f, 65f)); - State state = layerStateMachine.AddState(clip.name); - state.position = position; - state.SetAnimationClip(clip); - return state; - } - public static AnimatorController CreateAnimatorControllerAtPathWithClip(string path, AnimationClip clip) - { - AnimatorController animatorController = AnimatorController.CreateAnimatorControllerAtPath(path); - State state = animatorController.GetLayerStateMachine(0).AddState(clip.name); - state.SetAnimationClip(clip); - return animatorController; - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_Create(AnimatorController mono); - public AnimatorControllerLayer GetLayer(int index) - { - return (!this.ValidateLayerIndex(index)) ? null : new AnimatorControllerLayer(this, index); - } - public AnimatorControllerLayer AddLayer(string name) - { - this.AddLayerInternal(name); - return this.GetLayer(this.layerCount - 1); - } - public void RemoveLayer(int index) - { - if (this.onRemovedLayer != null) - { - this.onRemovedLayer(index); - } - this.RemoveLayerInternal(index); - } - public AnimatorControllerParameter GetParameter(int index) - { - return (!this.ValidateParameterIndex(index)) ? null : new AnimatorControllerParameter(this, index); - } - public AnimatorControllerParameter AddParameter(string name, AnimatorControllerParameterType type) - { - this.AddParameterInternal(name, type); - return this.GetParameter(this.parameterCount - 1); - } - public void RemoveParameter(int index) - { - if (this.onRemovedParameter != null) - { - this.onRemovedParameter(index); - } - this.RemoveParameterInternal(index); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern int FindParameter(string name); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern AnimatorController GetEffectiveAnimatorController(Animator behavior); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetAnimatorController(Animator behavior, AnimatorController controller); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern UnityEngine.Object[] CollectObjectsUsingParameter(string parameterName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void RemoveLayerInternal(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void RemoveParameterInternal(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void AddParameterInternal(string name, AnimatorControllerParameterType type); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void AddLayerInternal(string name); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool ValidateLayerIndex(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool ValidateParameterIndex(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern string GetLayerName(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerName(int index, string value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern StateMachine GetLayerStateMachine(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerStateMachine(int index, StateMachine value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern AvatarMask GetLayerMask(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerMask(int index, AvatarMask value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern AnimatorLayerBlendingMode GetLayerBlendingMode(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerBlendingMode(int index, AnimatorLayerBlendingMode value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern int GetLayerSyncedIndex(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerSyncedIndex(int index, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern int GetLayerMotionSetIndex(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool GetLayerIKPass(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerIKPass(int index, bool value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool GetSyncedLayerAffectsTiming(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetSyncedLayerAffectsTiming(int index, bool value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetLayerDefaultWeight(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetLayerDefaultWeight(int index, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern string GetParameterName(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterName(int index, string value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern AnimatorControllerParameterType GetParameterType(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterType(int index, AnimatorControllerParameterType value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetParameterDefaultFloat(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterDefaultFloat(int index, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern int GetParameterDefaultInt(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterDefaultInt(int index, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool GetParameterDefaultBool(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterDefaultBool(int index, bool value); } } diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs index 633bdce4..a196e37e 100644 --- a/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerLayer.cs @@ -1,153 +1,8 @@ using System; -using UnityEngine; namespace UnityEditorInternal { - public sealed class AnimatorControllerLayer + [Obsolete("AnimatorControllerLayer is obsolete. Use UnityEditor.Animations.AnimatorControllerLayer instead (UnityUpgradable).", true)] + public class AnimatorControllerLayer { - private AnimatorController m_Controller; - private int m_Index; - private bool m_Valid; - public string name - { - get - { - return (!this.checkValid()) ? string.Empty : this.m_Controller.GetLayerName(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerName(this.m_Index, value); - } - } - } - public StateMachine stateMachine - { - get - { - return (!this.checkValid()) ? null : this.m_Controller.GetLayerStateMachine(this.m_Index); - } - } - public AvatarMask avatarMask - { - get - { - return (!this.checkValid()) ? null : this.m_Controller.GetLayerMask(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerMask(this.m_Index, value); - } - } - } - public AnimatorLayerBlendingMode blendingMode - { - get - { - return (!this.checkValid()) ? AnimatorLayerBlendingMode.Override : this.m_Controller.GetLayerBlendingMode(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerBlendingMode(this.m_Index, value); - } - } - } - public int syncedLayerIndex - { - get - { - return (!this.checkValid()) ? 0 : this.m_Controller.GetLayerSyncedIndex(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerSyncedIndex(this.m_Index, value); - } - } - } - public int motionSetIndex - { - get - { - return (!this.checkValid()) ? 0 : this.m_Controller.GetLayerMotionSetIndex(this.m_Index); - } - } - public bool iKPass - { - get - { - return this.checkValid() && this.m_Controller.GetLayerIKPass(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerIKPass(this.m_Index, value); - } - } - } - public float defaultWeight - { - get - { - return (!this.checkValid()) ? 0f : this.m_Controller.GetLayerDefaultWeight(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetLayerDefaultWeight(this.m_Index, value); - } - } - } - public bool syncedLayerAffectsTiming - { - get - { - return this.checkValid() && this.m_Controller.GetSyncedLayerAffectsTiming(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetSyncedLayerAffectsTiming(this.m_Index, value); - } - } - } - public AnimatorControllerLayer(AnimatorController controller, int index) - { - this.m_Controller = controller; - this.m_Index = index; - controller.onRemovedLayer = (AnimatorController.RemovedLayer)Delegate.Combine(controller.onRemovedLayer, new AnimatorController.RemovedLayer(this.RemoveLayer)); - this.m_Valid = true; - } - private bool checkValid() - { - if (!this.m_Valid) - { - Debug.LogError("AnimatorControllerLayer is not valid anymore. It was removed"); - return false; - } - return true; - } - private void RemoveLayer(int index) - { - if (index == this.m_Index) - { - this.m_Valid = false; - } - else - { - if (index < this.m_Index) - { - this.m_Index--; - } - } - } } } diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs index 6491fe5d..349c31dd 100644 --- a/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerParameter.cs @@ -1,111 +1,8 @@ using System; -using UnityEngine; namespace UnityEditorInternal { - public sealed class AnimatorControllerParameter + [Obsolete("AnimatorControllerParameter is obsolete. Use UnityEngine.AnimatorControllerParameter instead (UnityUpgradable).", true)] + public class AnimatorControllerParameter { - private AnimatorController m_Controller; - private int m_Index; - private bool m_Valid; - public string name - { - get - { - return (!this.checkValid()) ? string.Empty : this.m_Controller.GetParameterName(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetParameterName(this.m_Index, value); - } - } - } - public AnimatorControllerParameterType type - { - get - { - return (!this.checkValid()) ? AnimatorControllerParameterType.Float : this.m_Controller.GetParameterType(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetParameterType(this.m_Index, value); - } - } - } - public float defaultFloat - { - get - { - return (!this.checkValid()) ? 0f : this.m_Controller.GetParameterDefaultFloat(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetParameterDefaultFloat(this.m_Index, value); - } - } - } - public int defaultInt - { - get - { - return (!this.checkValid()) ? 0 : this.m_Controller.GetParameterDefaultInt(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetParameterDefaultInt(this.m_Index, value); - } - } - } - public bool defaultBool - { - get - { - return this.checkValid() && this.m_Controller.GetParameterDefaultBool(this.m_Index); - } - set - { - if (this.checkValid()) - { - this.m_Controller.SetParameterDefaultBool(this.m_Index, value); - } - } - } - public AnimatorControllerParameter(AnimatorController controller, int index) - { - this.m_Controller = controller; - this.m_Index = index; - this.m_Valid = true; - controller.onRemovedParameter = (AnimatorController.RemovedParameter)Delegate.Combine(controller.onRemovedParameter, new AnimatorController.RemovedParameter(this.RemoveParameter)); - } - private bool checkValid() - { - if (!this.m_Valid) - { - Debug.LogError("AnimatorControllerParameter is not valid anymore. It was removed"); - return false; - } - return true; - } - private void RemoveParameter(int index) - { - if (index == this.m_Index) - { - this.m_Valid = false; - } - else - { - if (index < this.m_Index) - { - this.m_Index--; - } - } - } } } diff --git a/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs b/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs index d6880970..82d5fe8f 100644 --- a/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs +++ b/UnityEditor/UnityEditorInternal/AnimatorControllerParameterType.cs @@ -1,11 +1,9 @@ using System; namespace UnityEditorInternal { + [Obsolete("AnimatorControllerParameterType is obsolete. Use UnityEngine.AnimatorControllerParameterType instead (UnityUpgradable).", true)] public enum AnimatorControllerParameterType { - Float = 1, - Int = 3, - Bool, - Trigger = 9 + } } diff --git a/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs b/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs index 3c14f173..dec6947f 100644 --- a/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs +++ b/UnityEditor/UnityEditorInternal/AnimatorLayerBlendingMode.cs @@ -1,9 +1,9 @@ using System; namespace UnityEditorInternal { + [Obsolete("AnimatorLayerBlendingMode is obsolete. Use UnityEditor.Animations.AnimatorLayerBlendingMode instead (UnityUpgradable).", true)] public enum AnimatorLayerBlendingMode { - Override, - Additive + } } diff --git a/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs b/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs index 796266cc..c7b867b9 100644 --- a/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs +++ b/UnityEditor/UnityEditorInternal/AssetStoreToolUtils.cs @@ -6,6 +6,9 @@ namespace UnityEditorInternal { public sealed class AssetStoreToolUtils { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BuildAssetStoreAssetBundle(UnityEngine.Object targetObject, string targetPath); public static bool PreviewAssetStoreAssetBundleInInspector(AssetBundle bundle, AssetStoreAsset info) { info.id = 0; @@ -20,8 +23,5 @@ public static void UpdatePreloadingInternal() { AssetStoreUtils.UpdatePreloading(); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool BuildAssetStoreAssetBundle(UnityEngine.Object targetObject, string targetPath); } } diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerBackend.cs b/UnityEditor/UnityEditorInternal/AudioProfilerBackend.cs new file mode 100644 index 00000000..0043bfea --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerBackend.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +namespace UnityEditorInternal +{ + internal class AudioProfilerBackend + { + public delegate void DataUpdateDelegate(); + public AudioProfilerBackend.DataUpdateDelegate OnUpdate; + public AudioProfilerTreeViewState m_TreeViewState; + public List items + { + get; + private set; + } + public AudioProfilerBackend(AudioProfilerTreeViewState state) + { + this.m_TreeViewState = state; + this.items = new List(); + } + public void SetData(List data) + { + this.items = data; + this.UpdateSorting(); + } + public void UpdateSorting() + { + this.items.Sort(new AudioProfilerInfoHelper.AudioProfilerInfoComparer((AudioProfilerInfoHelper.ColumnIndices)this.m_TreeViewState.selectedColumn, (AudioProfilerInfoHelper.ColumnIndices)this.m_TreeViewState.prevSelectedColumn, this.m_TreeViewState.sortByDescendingOrder)); + if (this.OnUpdate != null) + { + this.OnUpdate(); + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerInfo.cs b/UnityEditor/UnityEditorInternal/AudioProfilerInfo.cs new file mode 100644 index 00000000..a4ac06bf --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerInfo.cs @@ -0,0 +1,24 @@ +using System; +namespace UnityEditorInternal +{ + [Serializable] + public struct AudioProfilerInfo + { + public int assetInstanceId; + public int objectInstanceId; + public int assetNameOffset; + public int objectNameOffset; + public int parentId; + public int uniqueId; + public int flags; + public int playCount; + public float distanceToListener; + public float volume; + public float audibility; + public float minDist; + public float maxDist; + public float time; + public float duration; + public float frequency; + } +} diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerInfoHelper.cs b/UnityEditor/UnityEditorInternal/AudioProfilerInfoHelper.cs new file mode 100644 index 00000000..2d522591 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerInfoHelper.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AudioProfilerInfoHelper + { + public enum ColumnIndices + { + ObjectName, + AssetName, + Volume, + Audibility, + PlayCount, + Is3D, + IsPaused, + IsMuted, + IsVirtual, + IsOneShot, + IsLooped, + DistanceToListener, + MinDist, + MaxDist, + Time, + Duration, + Frequency, + IsStream, + IsCompressed, + IsNonBlocking, + IsOpenUser, + IsOpenMemory, + IsOpenMemoryPoint, + _LastColumn + } + public class AudioProfilerInfoComparer : IComparer + { + public AudioProfilerInfoHelper.ColumnIndices primarySortKey; + public AudioProfilerInfoHelper.ColumnIndices secondarySortKey; + public bool sortByDescendingOrder; + public AudioProfilerInfoComparer(AudioProfilerInfoHelper.ColumnIndices primarySortKey, AudioProfilerInfoHelper.ColumnIndices secondarySortKey, bool sortByDescendingOrder) + { + this.primarySortKey = primarySortKey; + this.secondarySortKey = secondarySortKey; + this.sortByDescendingOrder = sortByDescendingOrder; + } + private int CompareInternal(AudioProfilerInfoWrapper a, AudioProfilerInfoWrapper b, AudioProfilerInfoHelper.ColumnIndices key) + { + int num = 0; + switch (key) + { + case AudioProfilerInfoHelper.ColumnIndices.ObjectName: + num = a.objectName.CompareTo(b.objectName); + break; + case AudioProfilerInfoHelper.ColumnIndices.AssetName: + num = a.assetName.CompareTo(b.assetName); + break; + case AudioProfilerInfoHelper.ColumnIndices.Volume: + num = a.info.volume.CompareTo(b.info.volume); + break; + case AudioProfilerInfoHelper.ColumnIndices.Audibility: + num = a.info.audibility.CompareTo(b.info.audibility); + break; + case AudioProfilerInfoHelper.ColumnIndices.PlayCount: + num = a.info.playCount.CompareTo(b.info.playCount); + break; + case AudioProfilerInfoHelper.ColumnIndices.Is3D: + num = (a.info.flags & 1).CompareTo(b.info.flags & 1); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsPaused: + num = (a.info.flags & 4).CompareTo(b.info.flags & 4); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsMuted: + num = (a.info.flags & 8).CompareTo(b.info.flags & 8); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsVirtual: + num = (a.info.flags & 16).CompareTo(b.info.flags & 16); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsOneShot: + num = (a.info.flags & 32).CompareTo(b.info.flags & 32); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsLooped: + num = (a.info.flags & 512).CompareTo(b.info.flags & 512); + break; + case AudioProfilerInfoHelper.ColumnIndices.DistanceToListener: + num = a.info.distanceToListener.CompareTo(b.info.distanceToListener); + break; + case AudioProfilerInfoHelper.ColumnIndices.MinDist: + num = a.info.minDist.CompareTo(b.info.minDist); + break; + case AudioProfilerInfoHelper.ColumnIndices.MaxDist: + num = a.info.maxDist.CompareTo(b.info.maxDist); + break; + case AudioProfilerInfoHelper.ColumnIndices.Time: + num = a.info.time.CompareTo(b.info.time); + break; + case AudioProfilerInfoHelper.ColumnIndices.Duration: + num = a.info.duration.CompareTo(b.info.duration); + break; + case AudioProfilerInfoHelper.ColumnIndices.Frequency: + num = a.info.frequency.CompareTo(b.info.frequency); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsStream: + num = (a.info.flags & 128).CompareTo(b.info.flags & 128); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsCompressed: + num = (a.info.flags & 256).CompareTo(b.info.flags & 256); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsNonBlocking: + num = (a.info.flags & 8192).CompareTo(b.info.flags & 8192); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenUser: + num = (a.info.flags & 4096).CompareTo(b.info.flags & 4096); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenMemory: + num = (a.info.flags & 1024).CompareTo(b.info.flags & 1024); + break; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenMemoryPoint: + num = (a.info.flags & 2048).CompareTo(b.info.flags & 2048); + break; + } + return (!this.sortByDescendingOrder) ? num : (-num); + } + public int Compare(AudioProfilerInfoWrapper a, AudioProfilerInfoWrapper b) + { + int num = this.CompareInternal(a, b, this.primarySortKey); + return (num != 0) ? num : this.CompareInternal(a, b, this.secondarySortKey); + } + } + public const int AUDIOPROFILER_FLAGS_3D = 1; + public const int AUDIOPROFILER_FLAGS_PAUSED = 4; + public const int AUDIOPROFILER_FLAGS_MUTED = 8; + public const int AUDIOPROFILER_FLAGS_VIRTUAL = 16; + public const int AUDIOPROFILER_FLAGS_ONESHOT = 32; + public const int AUDIOPROFILER_FLAGS_GROUP = 64; + public const int AUDIOPROFILER_FLAGS_STREAM = 128; + public const int AUDIOPROFILER_FLAGS_COMPRESSED = 256; + public const int AUDIOPROFILER_FLAGS_LOOPED = 512; + public const int AUDIOPROFILER_FLAGS_OPENMEMORY = 1024; + public const int AUDIOPROFILER_FLAGS_OPENMEMORYPOINT = 2048; + public const int AUDIOPROFILER_FLAGS_OPENUSER = 4096; + public const int AUDIOPROFILER_FLAGS_NONBLOCKING = 8192; + private static string FormatDb(float vol) + { + if (vol == 0f) + { + return "-∞ dB"; + } + return string.Format("{0:0.00} dB", 20f * Mathf.Log10(vol)); + } + public static string GetColumnString(AudioProfilerInfoWrapper info, AudioProfilerInfoHelper.ColumnIndices index) + { + bool flag = (info.info.flags & 1) != 0; + bool flag2 = (info.info.flags & 64) != 0; + switch (index) + { + case AudioProfilerInfoHelper.ColumnIndices.ObjectName: + return info.objectName; + case AudioProfilerInfoHelper.ColumnIndices.AssetName: + return info.assetName; + case AudioProfilerInfoHelper.ColumnIndices.Volume: + return AudioProfilerInfoHelper.FormatDb(info.info.volume); + case AudioProfilerInfoHelper.ColumnIndices.Audibility: + return (!flag2) ? AudioProfilerInfoHelper.FormatDb(info.info.audibility) : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.PlayCount: + return (!flag2) ? info.info.playCount.ToString() : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.Is3D: + return (!flag2) ? ((!flag) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsPaused: + return (!flag2) ? (((info.info.flags & 4) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsMuted: + return (!flag2) ? (((info.info.flags & 8) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsVirtual: + return (!flag2) ? (((info.info.flags & 16) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsOneShot: + return (!flag2) ? (((info.info.flags & 32) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsLooped: + return (!flag2) ? (((info.info.flags & 512) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.DistanceToListener: + return (!flag2) ? (flag ? ((info.info.distanceToListener < 1000f) ? string.Format("{0:0.00} m", info.info.distanceToListener) : string.Format("{0:0.00} km", info.info.distanceToListener * 0.001f)) : "N/A") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.MinDist: + return (!flag2) ? (flag ? ((info.info.minDist < 1000f) ? string.Format("{0:0.00} m", info.info.minDist) : string.Format("{0:0.00} km", info.info.minDist * 0.001f)) : "N/A") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.MaxDist: + return (!flag2) ? (flag ? ((info.info.maxDist < 1000f) ? string.Format("{0:0.00} m", info.info.maxDist) : string.Format("{0:0.00} km", info.info.maxDist * 0.001f)) : "N/A") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.Time: + return (!flag2) ? string.Format("{0:0.00} s", info.info.time) : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.Duration: + return (!flag2) ? string.Format("{0:0.00} s", info.info.duration) : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.Frequency: + return (!flag2) ? ((info.info.frequency < 1000f) ? string.Format("{0:0.00} Hz", info.info.frequency) : string.Format("{0:0.00} kHz", info.info.frequency * 0.001f)) : string.Format("{0:0.00} x", info.info.frequency); + case AudioProfilerInfoHelper.ColumnIndices.IsStream: + return (!flag2) ? (((info.info.flags & 128) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsCompressed: + return (!flag2) ? (((info.info.flags & 256) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsNonBlocking: + return (!flag2) ? (((info.info.flags & 8192) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenUser: + return (!flag2) ? (((info.info.flags & 4096) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenMemory: + return (!flag2) ? (((info.info.flags & 1024) == 0) ? "NO" : "YES") : string.Empty; + case AudioProfilerInfoHelper.ColumnIndices.IsOpenMemoryPoint: + return (!flag2) ? (((info.info.flags & 2048) == 0) ? "NO" : "YES") : string.Empty; + default: + return "Unknown"; + } + } + public static int GetLastColumnIndex() + { + return (!Unsupported.IsDeveloperBuild()) ? 15 : 22; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerInfoWrapper.cs b/UnityEditor/UnityEditorInternal/AudioProfilerInfoWrapper.cs new file mode 100644 index 00000000..46976727 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerInfoWrapper.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditorInternal +{ + internal class AudioProfilerInfoWrapper + { + public AudioProfilerInfo info; + public string assetName; + public string objectName; + public bool addToRoot; + public AudioProfilerInfoWrapper(AudioProfilerInfo info, string assetName, string objectName, bool addToRoot) + { + this.info = info; + this.assetName = assetName; + this.objectName = objectName; + this.addToRoot = addToRoot; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerTreeViewState.cs b/UnityEditor/UnityEditorInternal/AudioProfilerTreeViewState.cs new file mode 100644 index 00000000..f8f58972 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerTreeViewState.cs @@ -0,0 +1,27 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AudioProfilerTreeViewState : TreeViewState + { + [SerializeField] + public int selectedColumn = 3; + [SerializeField] + public int prevSelectedColumn = 5; + [SerializeField] + public bool sortByDescendingOrder = true; + public void SetSelectedColumn(int index) + { + if (index != this.selectedColumn) + { + this.prevSelectedColumn = this.selectedColumn; + } + else + { + this.sortByDescendingOrder = !this.sortByDescendingOrder; + } + this.selectedColumn = index; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/AudioProfilerView.cs b/UnityEditor/UnityEditorInternal/AudioProfilerView.cs new file mode 100644 index 00000000..7b7ef55e --- /dev/null +++ b/UnityEditor/UnityEditorInternal/AudioProfilerView.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class AudioProfilerView + { + internal class AudioProfilerTreeViewItem : TreeViewItem + { + public AudioProfilerInfoWrapper info + { + get; + set; + } + public AudioProfilerTreeViewItem(int id, int depth, TreeViewItem parent, string displayName, AudioProfilerInfoWrapper info) : base(id, depth, parent, displayName) + { + this.info = info; + } + } + internal class AudioProfilerDataSource : TreeViewDataSource + { + private AudioProfilerBackend m_Backend; + public AudioProfilerDataSource(TreeView treeView, AudioProfilerBackend backend) : base(treeView) + { + this.m_Backend = backend; + this.m_Backend.OnUpdate = new AudioProfilerBackend.DataUpdateDelegate(this.FetchData); + base.showRootNode = false; + base.rootIsCollapsable = false; + this.FetchData(); + } + private void FillTreeItems(AudioProfilerView.AudioProfilerTreeViewItem parentNode, int depth, int parentId, List items) + { + int num = 0; + foreach (AudioProfilerInfoWrapper current in items) + { + if (parentId == ((!current.addToRoot) ? current.info.parentId : 0)) + { + num++; + } + } + if (num > 0) + { + parentNode.children = new List(num); + foreach (AudioProfilerInfoWrapper current2 in items) + { + if (parentId == ((!current2.addToRoot) ? current2.info.parentId : 0)) + { + AudioProfilerView.AudioProfilerTreeViewItem audioProfilerTreeViewItem = new AudioProfilerView.AudioProfilerTreeViewItem(current2.info.uniqueId, (!current2.addToRoot) ? depth : 1, parentNode, current2.objectName, current2); + parentNode.children.Add(audioProfilerTreeViewItem); + this.FillTreeItems(audioProfilerTreeViewItem, depth + 1, current2.info.uniqueId, items); + } + } + } + } + public override void FetchData() + { + AudioProfilerView.AudioProfilerTreeViewItem audioProfilerTreeViewItem = new AudioProfilerView.AudioProfilerTreeViewItem(1, 0, null, "ROOT", new AudioProfilerInfoWrapper(default(AudioProfilerInfo), "ROOT", "ROOT", false)); + this.FillTreeItems(audioProfilerTreeViewItem, 1, 0, this.m_Backend.items); + this.m_RootItem = audioProfilerTreeViewItem; + this.SetExpandedWithChildren(this.m_RootItem, true); + this.m_NeedRefreshVisibleFolders = true; + } + public override bool CanBeParent(TreeViewItem item) + { + return item.hasChildren; + } + } + internal class AudioProfilerViewColumnHeader + { + private AudioProfilerTreeViewState m_TreeViewState; + private GUIStyle m_HeaderStyle; + private AudioProfilerBackend m_Backend; + public float[] columnWidths + { + get; + set; + } + public float minColumnWidth + { + get; + set; + } + public float dragWidth + { + get; + set; + } + public AudioProfilerViewColumnHeader(AudioProfilerTreeViewState state, AudioProfilerBackend backend) + { + this.m_TreeViewState = state; + this.m_Backend = backend; + this.minColumnWidth = 10f; + this.dragWidth = 6f; + } + public void OnGUI(Rect rect, bool allowSorting) + { + float num = rect.x; + int lastColumnIndex = AudioProfilerInfoHelper.GetLastColumnIndex(); + for (int i = 0; i <= lastColumnIndex; i++) + { + Rect position = new Rect(num, rect.y, this.columnWidths[i], rect.height); + num += this.columnWidths[i]; + Rect position2 = new Rect(num - this.dragWidth / 2f, rect.y, 3f, rect.height); + float x = EditorGUI.MouseDeltaReader(position2, true).x; + if (x != 0f) + { + this.columnWidths[i] += x; + this.columnWidths[i] = Mathf.Max(this.columnWidths[i], this.minColumnWidth); + } + if (this.m_HeaderStyle == null) + { + this.m_HeaderStyle = new GUIStyle("PR Label"); + this.m_HeaderStyle.padding.left = 4; + } + this.m_HeaderStyle.alignment = ((i != 0) ? TextAnchor.MiddleRight : TextAnchor.MiddleLeft); + string[] array = new string[] + { + "Object", + "Asset", + "Volume", + "Audibility", + "Plays", + "3D", + "Paused", + "Muted", + "Virtual", + "OneShot", + "Looped", + "Distance", + "MinDist", + "MaxDist", + "Time", + "Duration", + "Frequency", + "Stream", + "Compressed", + "NonBlocking", + "User", + "Memory", + "MemoryPoint" + }; + string text = array[i]; + if (allowSorting && i == this.m_TreeViewState.selectedColumn) + { + text += ((!this.m_TreeViewState.sortByDescendingOrder) ? " ▲" : " ▼"); + } + GUI.Label(position, text, this.m_HeaderStyle); + if (allowSorting && Event.current.type == EventType.MouseDown && position.Contains(Event.current.mousePosition)) + { + this.m_TreeViewState.SetSelectedColumn(i); + this.m_Backend.UpdateSorting(); + } + if (Event.current.type == EventType.Repaint) + { + EditorGUIUtility.AddCursorRect(position2, MouseCursor.SplitResizeLeftRight); + } + } + } + } + internal class AudioProfilerViewGUI : TreeViewGUI + { + private float[] columnWidths + { + get + { + return this.m_TreeView.state.columnWidths; + } + } + public AudioProfilerViewGUI(TreeView treeView) : base(treeView) + { + this.k_IconWidth = 0f; + } + protected override Texture GetIconForNode(TreeViewItem item) + { + return null; + } + protected override void RenameEnded() + { + } + protected override void SyncFakeItem() + { + } + protected override void DrawIconAndLabel(Rect rect, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + GUIStyle gUIStyle = (!useBoldFont) ? TreeViewGUI.s_Styles.lineStyle : TreeViewGUI.s_Styles.lineBoldStyle; + gUIStyle.alignment = TextAnchor.MiddleLeft; + gUIStyle.padding.left = 0; + base.DrawIconAndLabel(new Rect(rect.x, rect.y, this.columnWidths[0], rect.height), item, label, selected, focused, useBoldFont, isPinging); + gUIStyle.alignment = TextAnchor.MiddleRight; + rect.x += this.columnWidths[0]; + AudioProfilerView.AudioProfilerTreeViewItem audioProfilerTreeViewItem = item as AudioProfilerView.AudioProfilerTreeViewItem; + for (int i = 1; i < this.columnWidths.Length; i++) + { + rect.width = this.columnWidths[i] - 3f; + gUIStyle.Draw(rect, AudioProfilerInfoHelper.GetColumnString(audioProfilerTreeViewItem.info, (AudioProfilerInfoHelper.ColumnIndices)i), false, false, selected, focused); + rect.x += this.columnWidths[i]; + } + gUIStyle.alignment = TextAnchor.MiddleLeft; + } + } + private TreeView m_TreeView; + private AudioProfilerTreeViewState m_TreeViewState; + private EditorWindow m_EditorWindow; + private AudioProfilerView.AudioProfilerViewColumnHeader m_ColumnHeader; + private AudioProfilerBackend m_Backend; + private GUIStyle m_HeaderStyle; + private int delayedPingObject; + public AudioProfilerView(EditorWindow editorWindow, AudioProfilerTreeViewState state) + { + this.m_EditorWindow = editorWindow; + this.m_TreeViewState = state; + } + public int GetNumItemsInData() + { + return this.m_Backend.items.Count; + } + public void Init(Rect rect, AudioProfilerBackend backend) + { + this.m_HeaderStyle = "PR Label"; + if (this.m_TreeView != null) + { + return; + } + this.m_Backend = backend; + if (this.m_TreeViewState.columnWidths == null) + { + int num = AudioProfilerInfoHelper.GetLastColumnIndex() + 1; + this.m_TreeViewState.columnWidths = new float[num]; + for (int i = 0; i < num; i++) + { + this.m_TreeViewState.columnWidths[i] = (float)((i < 18) ? 55 : 80); + } + this.m_TreeViewState.columnWidths[0] = 200f; + this.m_TreeViewState.columnWidths[1] = 200f; + this.m_TreeViewState.columnWidths[2] = 80f; + this.m_TreeViewState.columnWidths[3] = 80f; + } + this.m_TreeView = new TreeView(this.m_EditorWindow, this.m_TreeViewState); + ITreeViewGUI gui = new AudioProfilerView.AudioProfilerViewGUI(this.m_TreeView); + ITreeViewDataSource data = new AudioProfilerView.AudioProfilerDataSource(this.m_TreeView, this.m_Backend); + this.m_TreeView.Init(rect, data, gui, null); + this.m_ColumnHeader = new AudioProfilerView.AudioProfilerViewColumnHeader(this.m_TreeViewState, this.m_Backend); + this.m_ColumnHeader.columnWidths = this.m_TreeViewState.columnWidths; + this.m_ColumnHeader.minColumnWidth = 30f; + TreeView expr_14C = this.m_TreeView; + expr_14C.selectionChangedCallback = (Action)Delegate.Combine(expr_14C.selectionChangedCallback, new Action(this.OnTreeSelectionChanged)); + } + private void PingObjectDelayed() + { + EditorGUIUtility.PingObject(this.delayedPingObject); + } + public void OnTreeSelectionChanged(int[] selection) + { + if (selection.Length == 1) + { + TreeViewItem treeViewItem = this.m_TreeView.FindNode(selection[0]); + AudioProfilerView.AudioProfilerTreeViewItem audioProfilerTreeViewItem = treeViewItem as AudioProfilerView.AudioProfilerTreeViewItem; + if (audioProfilerTreeViewItem != null) + { + EditorGUIUtility.PingObject(audioProfilerTreeViewItem.info.info.assetInstanceId); + this.delayedPingObject = audioProfilerTreeViewItem.info.info.objectInstanceId; + EditorApplication.CallDelayed(new EditorApplication.CallbackFunction(this.PingObjectDelayed), 1f); + } + } + } + public void OnGUI(Rect rect, bool allowSorting) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard, rect); + Rect rect2 = new Rect(rect.x, rect.y, rect.width, 17f); + Rect rect3 = new Rect(rect.x, rect.yMax - 20f, rect.width, 20f); + GUI.Label(rect2, string.Empty, this.m_HeaderStyle); + this.m_ColumnHeader.OnGUI(rect2, allowSorting); + rect.y += rect2.height; + rect.height -= rect2.height + rect3.height; + this.m_TreeView.OnEvent(); + this.m_TreeView.OnGUI(rect, controlID); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/BlendTree.cs b/UnityEditor/UnityEditorInternal/BlendTree.cs index 69ffbc1b..d393d26d 100644 --- a/UnityEditor/UnityEditorInternal/BlendTree.cs +++ b/UnityEditor/UnityEditorInternal/BlendTree.cs @@ -1,136 +1,9 @@ using System; -using System.Runtime.CompilerServices; using UnityEngine; namespace UnityEditorInternal { - public sealed class BlendTree : Motion + [Obsolete("BlendTree is obsolete. Use UnityEditor.Animations.BlendTree instead (UnityUpgradable).", true)] + public class BlendTree : Motion { - public extern string blendParameter - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string blendParameterY - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern BlendTreeType blendType - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern int childCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern bool automaticThresholds - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float minThreshold - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float maxThreshold - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - internal extern int recursiveBlendParameterCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - private BlendTree() - { - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void RemoveChild(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern BlendTree AddNewBlendTree(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void AddAnimationClip(AnimationClip clip); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Motion GetMotion(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Vector2 GetChildPosition(int index); - public void SetChildPosition(int index, Vector2 val) - { - BlendTree.INTERNAL_CALL_SetChildPosition(this, index, ref val); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetChildPosition(BlendTree self, int index, ref Vector2 val); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SortChildren(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern float GetChildThreshold(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetChildThreshold(int index, float val); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern float GetChildTimeScale(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetChildTimeScale(int index, float val); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern string GetRecursiveBlendParameter(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetRecursiveBlendParameterMin(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetRecursiveBlendParameterMax(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetInputBlendValue(string blendValueName, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetInputBlendValue(string blendValueName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetMotion(int index, Motion motion); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern AnimationClip[] GetAnimationClipsFlattened(); } } diff --git a/UnityEditor/UnityEditorInternal/CameraUtility.cs b/UnityEditor/UnityEditorInternal/CameraUtility.cs deleted file mode 100644 index ebaa368c..00000000 --- a/UnityEditor/UnityEditorInternal/CameraUtility.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using UnityEngine; -namespace UnityEditorInternal -{ - internal sealed class CameraUtility - { - public static bool DoesAnyCameraUseDeferred() - { - bool result = false; - Camera[] allCameras = Camera.allCameras; - for (int i = 0; i < allCameras.Length; i++) - { - if (allCameras[i].actualRenderingPath == RenderingPath.DeferredLighting) - { - result = true; - } - } - return result; - } - } -} diff --git a/UnityEditor/UnityEditorInternal/Chart.cs b/UnityEditor/UnityEditorInternal/Chart.cs index c9dd1cbd..49cf899f 100644 --- a/UnityEditor/UnityEditorInternal/Chart.cs +++ b/UnityEditor/UnityEditorInternal/Chart.cs @@ -18,6 +18,7 @@ internal enum ChartType } internal class Styles { + public GUIContent performanceWarning = new GUIContent(string.Empty, EditorGUIUtility.LoadIcon("console.warnicon.sml"), "Collecting GPU Profiler data might have overhead. Close graph if you don't need its data"); public GUIStyle background = "OL Box"; public GUIStyle leftPane = "ProfilerLeftPane"; public GUIStyle rightPane = "ProfilerRightPane"; @@ -111,7 +112,7 @@ private int HandleFrameSelectionEvents(int selectedFrame, int chartControlID, Re } return selectedFrame; } - public int DoGUI(Chart.ChartType type, int selectedFrame, ChartData cdata, bool active, GUIContent icon, out Chart.ChartAction action) + public int DoGUI(Chart.ChartType type, int selectedFrame, ChartData cdata, ProfilerArea area, bool active, GUIContent icon, out Chart.ChartAction action) { action = Chart.ChartAction.None; if (cdata == null) @@ -143,6 +144,7 @@ public int DoGUI(Chart.ChartType type, int selectedFrame, ChartData cdata, bool Rect rect3 = rect2; rect3.x -= 170f; rect3.width = 170f; + GUI.Label(new Rect(rect3.x, rect3.y, rect3.width, 20f), GUIContent.Temp(string.Empty, icon.tooltip)); if (current.type == EventType.Repaint) { Chart.ms_Styles.rightPane.Draw(rect2, false, false, active, false); @@ -177,6 +179,10 @@ public int DoGUI(Chart.ChartType type, int selectedFrame, ChartData cdata, bool rect3.y += 10f; this.LabelDraggerDrag(controlID, type, cdata, rect3, active); } + if (area == ProfilerArea.GPU) + { + GUI.Label(new Rect(rect.x + 170f - (float)Chart.ms_Styles.performanceWarning.image.width, rect.yMax - (float)Chart.ms_Styles.performanceWarning.image.height - 2f, (float)Chart.ms_Styles.performanceWarning.image.width, (float)Chart.ms_Styles.performanceWarning.image.height), Chart.ms_Styles.performanceWarning); + } if (GUI.Button(new Rect(rect.x + 170f - 13f - 2f, rect.y + 2f, 13f, 13f), GUIContent.none, Chart.ms_Styles.closeButton)) { action = Chart.ChartAction.Closed; @@ -189,7 +195,7 @@ private void DrawSelectedFrame(int selectedFrame, ChartData cdata, Rect r) { float num = (float)cdata.NumberOfFrames; selectedFrame -= cdata.firstFrame; - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(7); GL.Color(new Color(1f, 1f, 1f, 0.6f)); GL.Vertex3(r.x + r.width / num * (float)selectedFrame, r.y + 1f, 0f); @@ -211,7 +217,7 @@ private void DrawChartLine(int selectedFrame, ChartData cdata, Rect r) } private void DrawChartStacked(int selectedFrame, ChartData cdata, Rect r) { - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); float[] sumbuf = new float[cdata.NumberOfFrames]; for (int i = 0; i < cdata.charts.Length; i++) { @@ -243,6 +249,10 @@ private void DrawChartStacked(int selectedFrame, ChartData cdata, Rect r) } private void DoLabel(float x, float y, string text, float alignment) { + if (string.IsNullOrEmpty(text)) + { + return; + } GUIContent content = new GUIContent(text); Vector2 vector = Chart.ms_Styles.whiteLabel.CalcSize(content); Rect position = new Rect(x + vector.x * alignment, y, vector.x, vector.y); diff --git a/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs b/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs index d1d34b11..3f6399e1 100644 --- a/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs +++ b/UnityEditor/UnityEditorInternal/DopeSheetEditor.cs @@ -263,7 +263,7 @@ internal void OnDestroy() } public void OnGUI(Rect position, Vector2 scrollPosition) { - EditorGUI.BeginDisabledGroup(!this.state.IsEditable); + EditorGUI.BeginDisabledGroup(!this.state.IsClipEditable); this.HandleDragAndDropToEmptyArea(); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(this.state.IsReadOnly); @@ -334,7 +334,7 @@ private Rect DopelinesGUI(Rect position, Vector2 scrollPosition) goto IL_1B7; case EventType.DragUpdated: case EventType.DragPerform: - if (this.state.IsEditable) + if (this.state.IsClipEditable) { this.HandleDragAndDrop(current); } @@ -473,7 +473,7 @@ private void DopeLineRepaint(DopeLine dopeline) } } } - if (this.state.IsEditable && this.DoDragAndDrop(dopeline, dopeline.position, false)) + if (this.state.IsClipEditable && this.DoDragAndDrop(dopeline, dopeline.position, false)) { float num2 = Mathf.Max(this.state.PixelToTime(Event.current.mousePosition.x), 0f); Color color3 = Color.gray.RGBMultiplied(1.2f); @@ -510,7 +510,7 @@ private Rect GetDragAndDropRect(DopeLine dopeline, float screenX) { Rect keyframeRect = this.GetKeyframeRect(dopeline, 0f); float keyframeOffset = this.GetKeyframeOffset(dopeline); - float time = this.state.PixelToTime(screenX - keyframeRect.width * 0.5f, true); + float time = Mathf.Max(this.state.PixelToTime(screenX - keyframeRect.width * 0.5f, true), 0f); keyframeRect.center = new Vector2(this.state.TimeToPixel(time) + keyframeRect.width * 0.5f + keyframeOffset, keyframeRect.center.y); return keyframeRect; } @@ -523,7 +523,7 @@ private static void DrawBox(Rect position, Color color) } private static void DrawLine(Vector2 p1, Vector2 p2, Color color) { - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.Begin(1); GL.Color(color); GL.Vertex(new Vector3(p1.x, p1.y, 0f)); @@ -815,21 +815,19 @@ private bool DopelineForValueTypeExists(Type valueType) } private EditorCurveBinding? CreateNewPptrDopeline(Type valueType) { - EditorCurveBinding[] animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, valueType); - if (animatableProperties.Length == 0 && valueType == typeof(Sprite)) + List animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, valueType); + if (animatableProperties.Count == 0 && valueType == typeof(Sprite)) { return this.CreateNewSpriteRendererDopeline(); } - if (animatableProperties.Length == 1) + if (animatableProperties.Count == 1) { return new EditorCurveBinding?(animatableProperties[0]); } List list = new List(); - EditorCurveBinding[] array = animatableProperties; - for (int i = 0; i < array.Length; i++) + foreach (EditorCurveBinding current in animatableProperties) { - EditorCurveBinding editorCurveBinding = array[i]; - list.Add(editorCurveBinding.type.Name); + list.Add(current.type.Name); } Rect position = new Rect(Event.current.mousePosition.x, Event.current.mousePosition.y, 1f, 1f); EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(list.ToArray()), -1, new EditorUtility.SelectMenuItemFunction(this.SelectTypeForCreatingNewPptrDopeline), animatableProperties); @@ -849,8 +847,8 @@ private void SelectTypeForCreatingNewPptrDopeline(object userData, string[] opti { this.state.m_ActiveGameObject.AddComponent(); } - EditorCurveBinding[] animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, typeof(SpriteRenderer), typeof(Sprite)); - if (animatableProperties.Length == 1) + List animatableProperties = AnimationWindowUtility.GetAnimatableProperties(this.state.m_RootGameObject, this.state.m_RootGameObject, typeof(SpriteRenderer), typeof(Sprite)); + if (animatableProperties.Count == 1) { return new EditorCurveBinding?(animatableProperties[0]); } @@ -930,7 +928,10 @@ private void HandleMouseDown(DopeLine dopeline) { this.state.SelectKey(current4); } - this.state.SelectHierarchyItem(dopeline, current.control || current.shift); + if (!dopeline.isMasterDopeline) + { + this.state.SelectHierarchyItem(dopeline, current.control || current.shift); + } } else { @@ -945,6 +946,15 @@ private void HandleMouseDown(DopeLine dopeline) current.Use(); } } + if (dopeline.isMasterDopeline) + { + this.state.ClearHierarchySelection(); + List affectedHierarchyIDs = this.state.GetAffectedHierarchyIDs(this.state.selectedKeys); + foreach (int current6 in affectedHierarchyIDs) + { + this.state.SelectHierarchyItem(current6, true, true); + } + } if (dopeline.position.Contains(Event.current.mousePosition)) { if (current.clickCount == 2 && current.button == 0 && !Event.current.shift && !Event.current.control) @@ -1129,7 +1139,7 @@ private bool DoDragAndDrop(DopeLine dopeLine, Rect position, bool ignoreMousePos Analytics.Event("Sprite Drag and Drop", "Drop multiple sprites into existing dopeline", "null", 1); } Rect dragAndDropRect = this.GetDragAndDropRect(dopeLine, Event.current.mousePosition.x); - float time = this.state.PixelToTime(dragAndDropRect.xMin, true); + float time = Mathf.Max(this.state.PixelToTime(dragAndDropRect.xMin, true), 0f); AnimationWindowCurve curveOfType = this.GetCurveOfType(dopeLine, type); this.PeformDragAndDrop(curveOfType, time); } diff --git a/UnityEditor/UnityEditorInternal/EditMode.cs b/UnityEditor/UnityEditorInternal/EditMode.cs new file mode 100644 index 00000000..d5d96259 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/EditMode.cs @@ -0,0 +1,259 @@ +using System; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + [InitializeOnLoad] + public class EditMode + { + public enum SceneViewEditMode + { + None, + Collider, + Cloth, + ReflectionProbeBox, + ReflectionProbeOrigin + } + public delegate void OnEditModeStopFunc(Editor editor); + public delegate void OnEditModeStartFunc(Editor editor, EditMode.SceneViewEditMode mode); + private const string kEditModeStringKey = "EditModeState"; + private const string kPrevToolStringKey = "EditModePrevTool"; + private const string kOwnerStringKey = "EditModeOwner"; + private const float k_EditColliderbuttonWidth = 33f; + private const float k_EditColliderbuttonHeight = 23f; + private const float k_SpaceBetweenLabelAndButton = 5f; + private static bool s_Debug; + private static GUIStyle s_ToolbarBaseStyle; + private static GUIStyle s_EditColliderButtonStyle; + public static EditMode.OnEditModeStopFunc onEditModeEndDelegate; + public static EditMode.OnEditModeStartFunc onEditModeStartDelegate; + private static Tool s_ToolBeforeEnteringEditMode; + private static int s_OwnerID; + private static EditMode.SceneViewEditMode s_EditMode; + private static Tool toolBeforeEnteringEditMode + { + get + { + return EditMode.s_ToolBeforeEnteringEditMode; + } + set + { + EditMode.s_ToolBeforeEnteringEditMode = value; + InspectorState.SetInt("EditModePrevTool", (int)EditMode.s_ToolBeforeEnteringEditMode); + if (EditMode.s_Debug) + { + Debug.Log("Set toolBeforeEnteringEditMode " + value); + } + } + } + private static int ownerID + { + get + { + return EditMode.s_OwnerID; + } + set + { + EditMode.s_OwnerID = value; + InspectorState.SetInt("EditModeOwner", EditMode.s_OwnerID); + if (EditMode.s_Debug) + { + Debug.Log("Set ownerID " + value); + } + } + } + public static EditMode.SceneViewEditMode editMode + { + get + { + return EditMode.s_EditMode; + } + private set + { + if (EditMode.s_EditMode == EditMode.SceneViewEditMode.None && value != EditMode.SceneViewEditMode.None) + { + EditMode.toolBeforeEnteringEditMode = ((Tools.current == Tool.None) ? Tool.Move : Tools.current); + Tools.current = Tool.None; + } + else + { + if (EditMode.s_EditMode != EditMode.SceneViewEditMode.None && value == EditMode.SceneViewEditMode.None) + { + EditMode.ResetToolToPrevious(); + } + } + EditMode.s_EditMode = value; + InspectorState.SetInt("EditModeState", (int)EditMode.s_EditMode); + if (EditMode.s_Debug) + { + Debug.Log("Set editMode " + EditMode.s_EditMode); + } + } + } + static EditMode() + { + EditMode.s_ToolBeforeEnteringEditMode = Tool.Move; + EditMode.ownerID = InspectorState.GetInt("EditModeOwner", EditMode.ownerID); + EditMode.editMode = (EditMode.SceneViewEditMode)InspectorState.GetInt("EditModeState", (int)EditMode.editMode); + EditMode.toolBeforeEnteringEditMode = (Tool)InspectorState.GetInt("EditModePrevTool", (int)EditMode.toolBeforeEnteringEditMode); + if (EditMode.s_Debug) + { + Debug.Log(string.Concat(new object[] + { + "EditMode static constructor: ", + EditMode.ownerID, + " ", + EditMode.editMode, + " ", + EditMode.toolBeforeEnteringEditMode + })); + } + } + public static bool IsOwner(Editor editor) + { + return editor.GetInstanceID() == EditMode.ownerID; + } + public static void ResetToolToPrevious() + { + if (Tools.current == Tool.None) + { + Tools.current = EditMode.toolBeforeEnteringEditMode; + } + } + private static void EndSceneViewEditing() + { + EditMode.ChangeEditMode(EditMode.SceneViewEditMode.None, default(Bounds), null); + } + public static void OnSelectionChange() + { + if (Tools.current == Tool.None && EditMode.editMode != EditMode.SceneViewEditMode.None) + { + EditMode.ResetToolToPrevious(); + } + EditMode.EndSceneViewEditing(); + } + private static void DetectMainToolChange() + { + if (Tools.current != Tool.None && EditMode.editMode != EditMode.SceneViewEditMode.None) + { + EditMode.EndSceneViewEditing(); + } + } + public static void DoEditModeInspectorModeButton(EditMode.SceneViewEditMode mode, string label, GUIContent icon, Bounds bounds, Editor caller) + { + if (EditorUtility.IsPersistent(caller.target)) + { + return; + } + EditMode.DetectMainToolChange(); + if (EditMode.s_EditColliderButtonStyle == null) + { + EditMode.s_EditColliderButtonStyle = new GUIStyle("Button"); + EditMode.s_EditColliderButtonStyle.padding = new RectOffset(0, 0, 0, 0); + EditMode.s_EditColliderButtonStyle.margin = new RectOffset(0, 0, 0, 0); + } + Rect controlRect = EditorGUILayout.GetControlRect(true, 23f, new GUILayoutOption[0]); + Rect position = new Rect(controlRect.xMin + EditorGUIUtility.labelWidth, controlRect.yMin, 33f, 23f); + GUIContent content = new GUIContent(label); + Vector2 vector = GUI.skin.label.CalcSize(content); + Rect position2 = new Rect(position.xMax + 5f, controlRect.yMin + (controlRect.height - vector.y) * 0.5f, vector.x, controlRect.height); + int instanceID = caller.GetInstanceID(); + bool value = EditMode.editMode == mode && EditMode.ownerID == instanceID; + EditorGUI.BeginChangeCheck(); + bool flag = GUI.Toggle(position, value, icon, EditMode.s_EditColliderButtonStyle); + GUI.Label(position2, label); + if (EditorGUI.EndChangeCheck()) + { + EditMode.ChangeEditMode((!flag) ? EditMode.SceneViewEditMode.None : mode, bounds, caller); + } + } + public static void DoInspectorToolbar(EditMode.SceneViewEditMode[] modes, GUIContent[] guiContents, Bounds bounds, Editor caller) + { + if (EditorUtility.IsPersistent(caller.target)) + { + return; + } + EditMode.DetectMainToolChange(); + if (EditMode.s_ToolbarBaseStyle == null) + { + EditMode.s_ToolbarBaseStyle = "Command"; + } + int instanceID = caller.GetInstanceID(); + int num = ArrayUtility.IndexOf(modes, EditMode.editMode); + if (EditMode.ownerID != instanceID) + { + num = -1; + } + EditorGUI.BeginChangeCheck(); + int num2 = GUILayout.Toolbar(num, guiContents, EditMode.s_ToolbarBaseStyle, new GUILayoutOption[0]); + if (EditorGUI.EndChangeCheck()) + { + EditMode.SceneViewEditMode mode = (num2 != num) ? modes[num2] : EditMode.SceneViewEditMode.None; + EditMode.ChangeEditMode(mode, bounds, caller); + } + } + private static void ChangeEditMode(EditMode.SceneViewEditMode mode, Bounds bounds, Editor caller) + { + Editor editor = InternalEditorUtility.GetObjectFromInstanceID(EditMode.ownerID) as Editor; + EditMode.editMode = mode; + EditMode.ownerID = ((mode == EditMode.SceneViewEditMode.None) ? 0 : caller.GetInstanceID()); + if (EditMode.onEditModeEndDelegate != null) + { + EditMode.onEditModeEndDelegate(editor); + } + if (EditMode.editMode != EditMode.SceneViewEditMode.None && EditMode.onEditModeStartDelegate != null) + { + EditMode.onEditModeStartDelegate(caller, EditMode.editMode); + } + EditMode.EditModeChanged(bounds); + InspectorWindow.RepaintAllInspectors(); + } + private static void EditModeChanged(Bounds bounds) + { + if (EditMode.editMode != EditMode.SceneViewEditMode.None && SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null && !EditMode.SeenByCamera(SceneView.lastActiveSceneView.camera, bounds)) + { + SceneView.lastActiveSceneView.Frame(bounds); + } + SceneView.RepaintAll(); + } + private static bool SeenByCamera(Camera camera, Bounds bounds) + { + return EditMode.AnyPointSeenByCamera(camera, EditMode.GetPoints(bounds)); + } + private static Vector3[] GetPoints(Bounds bounds) + { + return EditMode.BoundsToPoints(bounds); + } + private static Vector3[] BoundsToPoints(Bounds bounds) + { + return new Vector3[] + { + new Vector3(bounds.min.x, bounds.min.y, bounds.min.z), + new Vector3(bounds.min.x, bounds.min.y, bounds.max.z), + new Vector3(bounds.min.x, bounds.max.y, bounds.min.z), + new Vector3(bounds.min.x, bounds.max.y, bounds.max.z), + new Vector3(bounds.max.x, bounds.min.y, bounds.min.z), + new Vector3(bounds.max.x, bounds.min.y, bounds.max.z), + new Vector3(bounds.max.x, bounds.max.y, bounds.min.z), + new Vector3(bounds.max.x, bounds.max.y, bounds.max.z) + }; + } + private static bool AnyPointSeenByCamera(Camera camera, Vector3[] points) + { + for (int i = 0; i < points.Length; i++) + { + Vector3 point = points[i]; + if (EditMode.PointSeenByCamera(camera, point)) + { + return true; + } + } + return false; + } + private static bool PointSeenByCamera(Camera camera, Vector3 point) + { + Vector3 vector = camera.WorldToViewportPoint(point); + return vector.x > 0f && vector.x < 1f && vector.y > 0f && vector.y < 1f; + } + } +} diff --git a/UnityEditor/UnityEditorInternal/FrameDebuggerEvent.cs b/UnityEditor/UnityEditorInternal/FrameDebuggerEvent.cs new file mode 100644 index 00000000..8f3ffcf5 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FrameDebuggerEvent.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEditorInternal +{ + internal struct FrameDebuggerEvent + { + public FrameEventType type; + public int vertexCount; + public int indexCount; + public string rtName; + public int rtWidth; + public int rtHeight; + public int rtFormat; + public int rtDim; + public int rtFace; + public short rtCount; + public short rtHasDepthTexture; + } +} diff --git a/UnityEditor/UnityEditorInternal/FrameDebuggerTreeView.cs b/UnityEditor/UnityEditorInternal/FrameDebuggerTreeView.cs new file mode 100644 index 00000000..f0bef304 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FrameDebuggerTreeView.cs @@ -0,0 +1,225 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class FrameDebuggerTreeView + { + private class FDTreeViewItem : TreeViewItem + { + public FrameDebuggerEvent m_FrameEvent; + public int m_ChildEventCount; + public int m_EventIndex; + public FDTreeViewItem(int id, int depth, FrameDebuggerTreeView.FDTreeViewItem parent, string displayName) : base(id, depth, parent, displayName) + { + this.m_EventIndex = id; + } + } + private class FDTreeViewGUI : TreeViewGUI + { + private const float kSmallMargin = 4f; + public FDTreeViewGUI(TreeView treeView) : base(treeView) + { + } + protected override Texture GetIconForNode(TreeViewItem item) + { + return null; + } + protected override void DrawIconAndLabel(Rect rect, TreeViewItem itemRaw, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) + { + FrameDebuggerTreeView.FDTreeViewItem fDTreeViewItem = (FrameDebuggerTreeView.FDTreeViewItem)itemRaw; + float contentIndent = this.GetContentIndent(fDTreeViewItem); + rect.x += contentIndent; + rect.width -= contentIndent; + string text; + GUIContent content; + GUIStyle gUIStyle; + if (fDTreeViewItem.m_ChildEventCount > 0) + { + Rect position = rect; + position.width -= 4f; + text = fDTreeViewItem.m_ChildEventCount.ToString(CultureInfo.InvariantCulture); + content = EditorGUIUtility.TempContent(text); + gUIStyle = FrameDebuggerWindow.styles.rowTextRight; + gUIStyle.Draw(position, content, false, false, false, false); + rect.width -= gUIStyle.CalcSize(content).x + 8f; + } + if (fDTreeViewItem.id <= 0) + { + text = fDTreeViewItem.displayName; + } + else + { + text = FrameDebuggerWindow.s_FrameEventTypeNames[(int)fDTreeViewItem.m_FrameEvent.type] + fDTreeViewItem.displayName; + } + if (string.IsNullOrEmpty(text)) + { + text = ""; + } + content = EditorGUIUtility.TempContent(text); + gUIStyle = FrameDebuggerWindow.styles.rowText; + gUIStyle.Draw(rect, content, false, false, false, selected && focused); + } + protected override void RenameEnded() + { + } + } + internal class FDTreeViewDataSource : TreeViewDataSource + { + private class FDTreeHierarchyLevel + { + internal readonly FrameDebuggerTreeView.FDTreeViewItem item; + internal readonly List children; + internal FDTreeHierarchyLevel(int depth, int id, string name, FrameDebuggerTreeView.FDTreeViewItem parent) + { + this.item = new FrameDebuggerTreeView.FDTreeViewItem(id, depth, parent, name); + this.children = new List(); + } + } + private FrameDebuggerEvent[] m_FrameEvents; + public FDTreeViewDataSource(TreeView treeView, FrameDebuggerEvent[] frameEvents) : base(treeView) + { + this.m_FrameEvents = frameEvents; + base.rootIsCollapsable = false; + base.showRootNode = false; + } + public void SetEvents(FrameDebuggerEvent[] frameEvents) + { + bool flag = this.m_FrameEvents == null || this.m_FrameEvents.Length < 1; + this.m_FrameEvents = frameEvents; + this.m_NeedRefreshVisibleFolders = true; + this.ReloadData(); + if (flag) + { + this.SetExpandedWithChildren(this.m_RootItem, true); + } + } + public override bool IsRenamingItemAllowed(TreeViewItem item) + { + return false; + } + public override bool CanBeMultiSelected(TreeViewItem item) + { + return false; + } + private static void CloseLastHierarchyLevel(List eventStack, int prevFrameEventIndex) + { + int index = eventStack.Count - 1; + eventStack[index].item.children = eventStack[index].children; + eventStack[index].item.m_EventIndex = prevFrameEventIndex; + if (eventStack[index].item.parent != null) + { + ((FrameDebuggerTreeView.FDTreeViewItem)eventStack[index].item.parent).m_ChildEventCount += eventStack[index].item.m_ChildEventCount; + } + eventStack.RemoveAt(index); + } + public override void FetchData() + { + FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel fDTreeHierarchyLevel = new FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel(0, 0, string.Empty, null); + List list = new List(); + list.Add(fDTreeHierarchyLevel); + int num = -1; + for (int i = 0; i < this.m_FrameEvents.Length; i++) + { + string text = "/" + (FrameDebuggerUtility.GetFrameEventInfoName(i) ?? string.Empty); + string[] array = text.Split(new char[] + { + '/' + }); + int num2 = 0; + while (num2 < list.Count && num2 < array.Length) + { + if (array[num2] != list[num2].item.displayName) + { + break; + } + num2++; + } + while (list.Count > 0 && list.Count > num2) + { + FrameDebuggerTreeView.FDTreeViewDataSource.CloseLastHierarchyLevel(list, i); + } + for (int j = num2; j < array.Length; j++) + { + FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel fDTreeHierarchyLevel2 = list[list.Count - 1]; + FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel fDTreeHierarchyLevel3 = new FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel(list.Count - 1, --num, array[j], fDTreeHierarchyLevel2.item); + fDTreeHierarchyLevel2.children.Add(fDTreeHierarchyLevel3.item); + list.Add(fDTreeHierarchyLevel3); + } + GameObject gameObjectForEvent = FrameDebuggerWindow.GetGameObjectForEvent(i); + string displayName = (!gameObjectForEvent) ? string.Empty : (" " + gameObjectForEvent.name); + FrameDebuggerTreeView.FDTreeViewDataSource.FDTreeHierarchyLevel fDTreeHierarchyLevel4 = list[list.Count - 1]; + int id = i + 1; + FrameDebuggerTreeView.FDTreeViewItem fDTreeViewItem = new FrameDebuggerTreeView.FDTreeViewItem(id, list.Count - 1, fDTreeHierarchyLevel4.item, displayName); + fDTreeViewItem.m_FrameEvent = this.m_FrameEvents[i]; + fDTreeHierarchyLevel4.children.Add(fDTreeViewItem); + fDTreeHierarchyLevel4.item.m_ChildEventCount++; + } + while (list.Count > 0) + { + FrameDebuggerTreeView.FDTreeViewDataSource.CloseLastHierarchyLevel(list, this.m_FrameEvents.Length); + } + this.m_RootItem = fDTreeHierarchyLevel.item; + } + } + internal readonly TreeView m_TreeView; + internal FrameDebuggerTreeView.FDTreeViewDataSource m_DataSource; + private readonly FrameDebuggerWindow m_FrameDebugger; + public FrameDebuggerTreeView(FrameDebuggerEvent[] frameEvents, TreeViewState treeViewState, FrameDebuggerWindow window, Rect startRect) + { + this.m_FrameDebugger = window; + this.m_TreeView = new TreeView(window, treeViewState); + this.m_DataSource = new FrameDebuggerTreeView.FDTreeViewDataSource(this.m_TreeView, frameEvents); + FrameDebuggerTreeView.FDTreeViewGUI gui = new FrameDebuggerTreeView.FDTreeViewGUI(this.m_TreeView); + this.m_TreeView.Init(startRect, this.m_DataSource, gui, null); + this.m_TreeView.ReloadData(); + TreeView expr_5E = this.m_TreeView; + expr_5E.selectionChangedCallback = (Action)Delegate.Combine(expr_5E.selectionChangedCallback, new Action(this.SelectionChanged)); + } + private void SelectionChanged(int[] selectedIDs) + { + if (selectedIDs.Length < 1) + { + return; + } + int num = selectedIDs[0]; + int num2 = num; + if (num2 <= 0) + { + FrameDebuggerTreeView.FDTreeViewItem fDTreeViewItem = this.m_TreeView.FindNode(num) as FrameDebuggerTreeView.FDTreeViewItem; + if (fDTreeViewItem != null) + { + num2 = fDTreeViewItem.m_EventIndex; + } + } + if (num2 <= 0) + { + return; + } + this.m_FrameDebugger.ChangeFrameEventLimit(num2); + } + public void SelectFrameEventIndex(int eventIndex) + { + int[] selection = this.m_TreeView.GetSelection(); + if (selection.Length > 0) + { + FrameDebuggerTreeView.FDTreeViewItem fDTreeViewItem = this.m_TreeView.FindNode(selection[0]) as FrameDebuggerTreeView.FDTreeViewItem; + if (fDTreeViewItem != null && eventIndex == fDTreeViewItem.m_EventIndex) + { + return; + } + } + this.m_TreeView.SetSelection(new int[] + { + eventIndex + }, true); + } + public void OnGUI(Rect rect) + { + int controlID = GUIUtility.GetControlID(FocusType.Keyboard); + this.m_TreeView.OnGUI(rect, controlID); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/FrameDebuggerUtility.cs b/UnityEditor/UnityEditorInternal/FrameDebuggerUtility.cs new file mode 100644 index 00000000..f1d62970 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FrameDebuggerUtility.cs @@ -0,0 +1,70 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class FrameDebuggerUtility + { + public static extern bool enabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int count + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int limit + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int eventsHash + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static void SetRenderTargetDisplayOptions(int rtIndex, Vector4 channels, float blackLevel, float whiteLevel) + { + FrameDebuggerUtility.INTERNAL_CALL_SetRenderTargetDisplayOptions(rtIndex, ref channels, blackLevel, whiteLevel); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetRenderTargetDisplayOptions(int rtIndex, ref Vector4 channels, float blackLevel, float whiteLevel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern FrameDebuggerEvent[] GetFrameEvents(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetFrameEventInfoName(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetFrameEventShaderKeywords(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrameEventShaderID(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrameEventShaderPassIndex(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrameEventRendererID(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrameEventMeshID(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetFrameEventMeshSubset(int index); + } +} diff --git a/UnityEditor/UnityEditorInternal/FrameEventType.cs b/UnityEditor/UnityEditorInternal/FrameEventType.cs new file mode 100644 index 00000000..b336e720 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/FrameEventType.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEditorInternal +{ + internal enum FrameEventType + { + ClearNone, + ClearColor, + ClearDepth, + ClearColorDepth, + ClearStencil, + ClearColorStencil, + ClearDepthStencil, + ClearAll, + SetRenderTarget, + ResolveRT, + ResolveDepth, + GrabIntoRT, + StaticBatch, + DynamicBatch, + Mesh, + DynamicGeometry, + GLDraw, + SkinOnGPU, + DrawProcedural, + ComputeDispatch, + PluginEvent + } +} diff --git a/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs b/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs index 0bfcc78e..75a04f2a 100644 --- a/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs +++ b/UnityEditor/UnityEditorInternal/IProfilerWindowController.cs @@ -6,6 +6,10 @@ internal interface IProfilerWindowController void SetSelectedPropertyPath(string path); void ClearSelectedPropertyPath(); ProfilerProperty CreateProperty(bool details); + int GetActiveVisibleFrameIndex(); + void SetSearch(string searchString); + string GetSearch(); + bool IsSearching(); void Repaint(); } } diff --git a/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs b/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs index efd132bc..3975c15c 100644 --- a/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs +++ b/UnityEditor/UnityEditorInternal/InternalEditorUtility.cs @@ -1,4 +1,3 @@ -using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; @@ -114,520 +113,89 @@ public static extern bool ignoreInspectorChanges [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static Texture2D GetIconForFile(string fileName) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void BumpMapSettingsFixingWindowReportResult(int result); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BumpMapTextureNeedsFixingInternal(Material material, string propName, bool flaggedAsNormal); + internal static bool BumpMapTextureNeedsFixing(MaterialProperty prop) { - int num = fileName.LastIndexOf('.'); - string text = (num != -1) ? fileName.Substring(num + 1).ToLower() : string.Empty; - string text2 = text; - switch (text2) + if (prop.type != MaterialProperty.PropType.Texture) { - case "boo": - return EditorGUIUtility.FindTexture("boo Script Icon"); - case "cginc": - return EditorGUIUtility.FindTexture("CGProgram Icon"); - case "cs": - return EditorGUIUtility.FindTexture("cs Script Icon"); - case "guiskin": - return EditorGUIUtility.FindTexture("GUISkin Icon"); - case "js": - return EditorGUIUtility.FindTexture("Js Script Icon"); - case "mat": - return EditorGUIUtility.FindTexture("Material Icon"); - case "prefab": - return EditorGUIUtility.FindTexture("PrefabNormal Icon"); - case "shader": - return EditorGUIUtility.FindTexture("Shader Icon"); - case "txt": - return EditorGUIUtility.FindTexture("TextAsset Icon"); - case "unity": - return EditorGUIUtility.FindTexture("SceneAsset Icon"); - case "asset": - case "prefs": - return EditorGUIUtility.FindTexture("GameManager Icon"); - case "anim": - return EditorGUIUtility.FindTexture("Animation Icon"); - case "meta": - return EditorGUIUtility.FindTexture("MetaFile Icon"); - case "ttf": - case "otf": - case "fon": - case "fnt": - return EditorGUIUtility.FindTexture("Font Icon"); - 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": - return EditorGUIUtility.FindTexture("AudioClip Icon"); - 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": - return EditorGUIUtility.FindTexture("Texture Icon"); - 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("Mesh Icon"); - 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 "m4v": - case "mjp": - case "mov": - case "movie": - case "mp21": - case "mp4": - case "mpe": - case "mpeg": - case "mpg": - case "mpv2": - case "ogm": - case "qt": - case "rm": - case "rmvb": - case "wmw": - case "xvid": - return EditorGUIUtility.FindTexture("MovieTexture Icon"); - case "colors": - case "gradients": - case "curves": - case "curvesnormalized": - case "particlecurves": - case "particlecurvessigned": - case "particledoublecurves": - case "particledoublecurvessigned": - return EditorGUIUtility.FindTexture("ScriptableObject Icon"); + return false; } - return EditorGUIUtility.FindTexture("DefaultAsset Icon"); - } - public static string[] GetEditorSettingsList(string prefix, int count) - { - ArrayList arrayList = new ArrayList(); - for (int i = 1; i <= count; i++) + bool flaggedAsNormal = (prop.flags & MaterialProperty.PropFlags.Normal) != MaterialProperty.PropFlags.None; + UnityEngine.Object[] targets = prop.targets; + for (int i = 0; i < targets.Length; i++) { - string @string = EditorPrefs.GetString(prefix + i, "defaultValue"); - if (@string == "defaultValue") + Material material = (Material)targets[i]; + if (InternalEditorUtility.BumpMapTextureNeedsFixingInternal(material, prop.name, flaggedAsNormal)) { - break; + return true; } - arrayList.Add(@string); } - return arrayList.ToArray(typeof(string)) as string[]; + return false; } - public static void SaveEditorSettingsList(string prefix, string[] aList, int count) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void FixNormalmapTextureInternal(Material material, string propName); + internal static void FixNormalmapTexture(MaterialProperty prop) { - for (int i = 0; i < aList.Length; i++) - { - EditorPrefs.SetString(prefix + (i + 1), aList[i]); - } - for (int i = aList.Length + 1; i <= count; i++) + UnityEngine.Object[] targets = prop.targets; + for (int i = 0; i < targets.Length; i++) { - EditorPrefs.DeleteKey(prefix + i); + Material material = (Material)targets[i]; + InternalEditorUtility.FixNormalmapTextureInternal(material, prop.name); } } - public static Camera[] GetSceneViewCameras() - { - return SceneView.GetAllSceneCameras(); - } - public static void ShowGameView() + internal static bool HDRTextureNeedsFixing(MaterialProperty prop, out bool canBeFixedAutomatically) { - WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true); + if ((prop.flags & MaterialProperty.PropFlags.HDR) != MaterialProperty.PropFlags.None || prop.displayName.Contains("(HDR")) + { + Texture textureValue = prop.textureValue; + if (textureValue) + { + string assetPath = AssetDatabase.GetAssetPath(textureValue); + TextureImporter x = AssetImporter.GetAtPath(assetPath) as TextureImporter; + canBeFixedAutomatically = (x != null); + bool flag = TextureUtil.HasAlphaTextureFormat(TextureUtil.GetTextureFormat(textureValue)); + bool flag2 = TextureUtil.GetUsageMode(textureValue) == TextureUsageMode.RGBMEncoded; + if (flag && !flag2) + { + return true; + } + } + } + canBeFixedAutomatically = false; + return false; } - public static List GetNewSelection(int clickedInstanceID, List allInstanceIDs, List selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection) + internal static void FixHDRTexture(MaterialProperty prop) { - List list = new List(); - bool flag = Event.current.shift || (EditorGUI.actionKey && useShiftAsActionKey); - bool flag2 = EditorGUI.actionKey && !useShiftAsActionKey; - if (!allowMultiSelection) + string assetPath = AssetDatabase.GetAssetPath(prop.textureValue); + TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; + if (!textureImporter) { - flag2 = (flag = false); + return; } - if (flag2) + TextureImporterFormat textureFormat = TextureImporterFormat.RGB24; + textureImporter.textureFormat = textureFormat; + List validPlatforms = BuildPlayerWindow.GetValidPlatforms(); + foreach (BuildPlayerWindow.BuildPlatform current in validPlatforms) { - list.AddRange(selectedInstanceIDs); - if (list.Contains(clickedInstanceID)) + int maxTextureSize; + TextureImporterFormat textureImporterFormat; + int compressionQuality; + bool platformTextureSettings = textureImporter.GetPlatformTextureSettings(current.name, out maxTextureSize, out textureImporterFormat, out compressionQuality); + if (platformTextureSettings) { - list.Remove(clickedInstanceID); - } - else - { - list.Add(clickedInstanceID); + textureImporter.SetPlatformTextureSettings(current.name, maxTextureSize, textureFormat, compressionQuality); } } - else - { - if (flag) - { - if (clickedInstanceID == lastClickedInstanceID) - { - return selectedInstanceIDs; - } - int num; - int num2; - if (!InternalEditorUtility.GetFirstAndLastSelected(allInstanceIDs, selectedInstanceIDs, out num, out num2)) - { - list.Add(clickedInstanceID); - return list; - } - int num3 = -1; - int num4 = -1; - for (int i = 0; i < allInstanceIDs.Count; i++) - { - if (allInstanceIDs[i] == clickedInstanceID) - { - num3 = i; - } - if (lastClickedInstanceID != 0 && allInstanceIDs[i] == lastClickedInstanceID) - { - num4 = i; - } - } - Assert.That(num3 != -1); - int num5 = 0; - if (num4 != -1) - { - num5 = ((num3 <= num4) ? -1 : 1); - } - int num6; - int num7; - if (num3 > num2) - { - num6 = num; - num7 = num3; - } - else - { - if (num3 >= num && num3 < num2) - { - if (num5 > 0) - { - num6 = num3; - num7 = num2; - } - else - { - num6 = num; - num7 = num3; - } - } - else - { - num6 = num3; - num7 = num2; - } - } - for (int j = num6; j <= num7; j++) - { - list.Add(allInstanceIDs[j]); - } - } - else - { - if (keepMultiSelection && selectedInstanceIDs.Contains(clickedInstanceID)) - { - list.AddRange(selectedInstanceIDs); - return list; - } - list.Add(clickedInstanceID); - } - } - return list; - } - private static bool GetFirstAndLastSelected(List allInstanceIDs, List selectedInstanceIDs, out int firstIndex, out int lastIndex) - { - firstIndex = -1; - lastIndex = -1; - for (int i = 0; i < allInstanceIDs.Count; i++) - { - if (selectedInstanceIDs.Contains(allInstanceIDs[i])) - { - if (firstIndex == -1) - { - firstIndex = i; - } - lastIndex = i; - } - } - return firstIndex != -1 && lastIndex != -1; - } - public static bool IsValidFileName(string filename) - { - string text = InternalEditorUtility.RemoveInvalidCharsFromFileName(filename, false); - return !(text != filename) && !string.IsNullOrEmpty(text); - } - public static string RemoveInvalidCharsFromFileName(string filename, bool logIfInvalidChars) - { - if (string.IsNullOrEmpty(filename)) - { - return filename; - } - filename = filename.Trim(); - if (string.IsNullOrEmpty(filename)) - { - return filename; - } - string text = new string(Path.GetInvalidFileNameChars()); - string text2 = string.Empty; - bool flag = false; - string text3 = filename; - for (int i = 0; i < text3.Length; i++) - { - char c = text3[i]; - if (text.IndexOf(c) == -1) - { - text2 += c; - } - else - { - flag = true; - } - } - if (flag && logIfInvalidChars) - { - string displayStringOfInvalidCharsOfFileName = InternalEditorUtility.GetDisplayStringOfInvalidCharsOfFileName(filename); - if (displayStringOfInvalidCharsOfFileName.Length > 0) - { - Debug.LogWarning(string.Format("A filename cannot contain the following character{0}: {1}", (displayStringOfInvalidCharsOfFileName.Length <= 1) ? string.Empty : "s", displayStringOfInvalidCharsOfFileName)); - } - } - return text2; - } - public static string GetDisplayStringOfInvalidCharsOfFileName(string filename) - { - if (string.IsNullOrEmpty(filename)) - { - return string.Empty; - } - string text = new string(Path.GetInvalidFileNameChars()); - string text2 = string.Empty; - for (int i = 0; i < filename.Length; i++) - { - char c = filename[i]; - if (text.IndexOf(c) >= 0 && text2.IndexOf(c) == -1) - { - if (text2.Length > 0) - { - text2 += " "; - } - text2 += c; - } - } - return text2; - } - internal static bool IsScriptOrAssembly(string filename) - { - if (string.IsNullOrEmpty(filename)) - { - return false; - } - string text = Path.GetExtension(filename).ToLower(); - if (text != null) - { - if (InternalEditorUtility.<>f__switch$map6 == null) - { - InternalEditorUtility.<>f__switch$map6 = new Dictionary(5) - { - - { - ".cs", - 0 - }, - - { - ".js", - 0 - }, - - { - ".boo", - 0 - }, - - { - ".dll", - 1 - }, - - { - ".exe", - 1 - } - }; - } - int num; - if (InternalEditorUtility.<>f__switch$map6.TryGetValue(text, out num)) - { - if (num == 0) - { - return true; - } - if (num == 1) - { - return AssemblyHelper.IsManagedAssembly(filename); - } - } - } - return false; - } - internal static T ParentHasComponent(Transform trans) where T : Component - { - if (!(trans != null)) - { - return (T)((object)null); - } - T component = trans.GetComponent(); - if (component) - { - return component; - } - return InternalEditorUtility.ParentHasComponent(trans.parent); - } - internal static IEnumerable GetAllScriptGUIDs() - { - return - from asset in AssetDatabase.GetAllAssetPaths() - where InternalEditorUtility.IsScriptOrAssembly(asset) - select AssetDatabase.AssetPathToGUID(asset); - } - public static bool DetectDotNetDll(string path) - { - bool result; - using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) - { - using (BinaryReader binaryReader = new BinaryReader(stream)) - { - if (stream.Length < 64L) - { - result = false; - } - else - { - stream.Position = 60L; - uint num = binaryReader.ReadUInt32(); - if (num == 0u) - { - num = 128u; - } - if ((ulong)num > (ulong)(stream.Length - 256L)) - { - result = false; - } - else - { - stream.Position = (long)((ulong)num); - uint num2 = binaryReader.ReadUInt32(); - if (num2 != 17744u) - { - result = false; - } - else - { - stream.Position += 20L; - ushort num3 = binaryReader.ReadUInt16(); - if (num3 != 267 && num3 != 523) - { - result = false; - } - else - { - ushort num4 = (ushort)((ulong)num + (ulong)((num3 != 267) ? 248L : 232L)); - stream.Position = (long)num4; - if (binaryReader.ReadUInt32() == 0u) - { - result = false; - } - else - { - result = true; - } - } - } - } - } - } - } - return result; + AssetDatabase.ImportAsset(assetPath); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void BumpMapSettingsFixingWindowReportResult(int result); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool BumpMapTextureNeedsFixing(Material material); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void FixNormalmapTexture(Material material); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetEditorAssemblyPath(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -661,6 +229,9 @@ public static bool DetectDotNetDll(string path) public static extern int AddScriptComponentUnchecked(GameObject gameObject, MonoScript script); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int CreateScriptableObjectUnchecked(MonoScript script); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RequestScriptReload(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -685,7 +256,7 @@ public static bool DetectDotNetDll(string path) public static extern DragAndDropVisualMode ProjectWindowDrag(HierarchyProperty property, bool perform); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern DragAndDropVisualMode HierarchyWindowDrag(HierarchyProperty property, bool perform, InternalEditorUtility.HierarchyDropMode options); + public static extern DragAndDropVisualMode HierarchyWindowDrag(HierarchyProperty property, bool perform, InternalEditorUtility.HierarchyDropMode dropMode); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern DragAndDropVisualMode InspectorWindowDrag(UnityEngine.Object[] targets, bool perform); @@ -705,10 +276,16 @@ public static void SetRectTransformTemporaryRect(RectTransform rectTransform, Re private static extern void INTERNAL_CALL_SetRectTransformTemporaryRect(RectTransform rectTransform, ref Rect rect); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool HasMaint(); + public static extern bool HasPro(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool HasPro(); + public static extern bool HasFreeLicense(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasEduLicense(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool HasProFeaturesEnabled(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasAdvancedLicenseOnBuildTarget(BuildTarget target); @@ -724,10 +301,10 @@ public static Rect GetBoundsOfDesktopAtPoint(Vector2 pos) internal static extern string GetSortingLayerName(int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern string GetSortingLayerNameFromUniqueID(int id); + internal static extern int GetSortingLayerUniqueID(int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern int GetSortingLayerUserID(int index); + internal static extern string GetSortingLayerNameFromUniqueID(int id); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetSortingLayerCount(); @@ -781,10 +358,21 @@ public static Rect GetBoundsOfDesktopAtPoint(Vector2 pos) public static extern void LoadDefaultLayout(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void CalculateAmbientProbeFromSkybox(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetupShaderMenu(Material material); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetFullUnityVersion(); + public static Version GetUnityVersion() + { + Version version = new Version(InternalEditorUtility.GetUnityVersionDigits()); + return new Version(version.Major, version.Minor, version.Build, InternalEditorUtility.GetUnityRevision()); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetUnityVersionDigits(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetUnityBuildBranch(); @@ -1026,10 +614,13 @@ public static void SetCustomLighting(Light[] lights, Color ambient) private static extern void INTERNAL_CALL_SetCustomLighting(Light[] lights, ref Color ambient); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void ClearSceneLighting(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RemoveCustomLighting(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool CalculateShouldEnableLights(); + internal static extern void DrawSkyboxMaterial(Material mat, Camera cam); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasFullscreenCamera(); @@ -1038,7 +629,7 @@ public static void SetCustomLighting(Light[] lights, Color ambient) public static extern void ResetCursor(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern Bounds CalculateSelectionBounds(bool usePivotOnlyForParticles); + public static extern Bounds CalculateSelectionBounds(bool usePivotOnlyForParticles, bool onlyUseActiveSelection); internal static Bounds CalculateSelectionBoundsInSpace(Vector3 position, Quaternion rotation, bool rectBlueprintMode) { Quaternion rotation2 = Quaternion.Inverse(rotation); @@ -1056,115 +647,611 @@ internal static Bounds CalculateSelectionBoundsInSpace(Vector3 position, Quatern { for (int k = 0; k < 2; k++) { - for (int l = 0; l < 2; l++) + for (int l = 0; l < 2; l++) + { + Vector3 vector3 = new Vector3(array[j].x, array[k].y, array[l].z); + if (rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(gameObject.transform)) + { + Vector3 localPosition = gameObject.transform.localPosition; + localPosition.z = 0f; + vector3 = gameObject.transform.parent.TransformPoint(vector3 + localPosition); + } + else + { + vector3 = gameObject.transform.TransformPoint(vector3); + } + vector3 = rotation2 * (vector3 - position); + for (int m = 0; m < 3; m++) + { + vector[m] = Mathf.Min(vector[m], vector3[m]); + vector2[m] = Mathf.Max(vector2[m], vector3[m]); + } + } + } + } + } + return new Bounds((vector + vector2) * 0.5f, vector2 - vector); + } + internal static bool SupportsRectLayout(Transform tr) + { + return !(tr == null) && !(tr.parent == null) && !(tr.GetComponent() == null) && !(tr.parent.GetComponent() == null); + } + private static Bounds GetLocalBounds(GameObject gameObject) + { + RectTransform component = gameObject.GetComponent(); + if (component) + { + return new Bounds(component.rect.center, component.rect.size); + } + Renderer component2 = gameObject.GetComponent(); + if (component2 is MeshRenderer) + { + MeshFilter component3 = component2.GetComponent(); + if (component3 != null && component3.sharedMesh != null) + { + return component3.sharedMesh.bounds; + } + } + if (component2 is SpriteRenderer) + { + SpriteRenderer spriteRenderer = component2 as SpriteRenderer; + if (spriteRenderer.sprite != null) + { + Bounds bounds = spriteRenderer.sprite.bounds; + Vector3 size = bounds.size; + size.z = 0f; + bounds.size = size; + return bounds; + } + } + return new Bounds(Vector3.zero, Vector3.zero); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void OnGameViewFocus(bool focus); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool OpenFileAtLineExternal(string filename, int line); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern MonoIsland[] GetMonoIslands(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Xbox360GenerateSPAConfig(string spaPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool Xbox360SaveSplashScreenToFile(Texture2D image, string spaPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool CanConnectToCacheServer(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool DetectDotNetDll(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string GetCrashReportFolder(); + [ExcludeFromDocs] + internal static bool RunningUnderWindows8() + { + bool orHigher = true; + return InternalEditorUtility.RunningUnderWindows8(orHigher); + } + internal static bool RunningUnderWindows8([DefaultValue("true")] bool orHigher) + { + if (Application.platform != RuntimePlatform.WindowsEditor) + { + return false; + } + OperatingSystem oSVersion = Environment.OSVersion; + int major = oSVersion.Version.Major; + int minor = oSVersion.Version.Minor; + if (orHigher) + { + return major > 6 || (major == 6 && minor >= 2); + } + return major == 6 && minor == 2; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int DetermineDepthOrder(Transform lhs, Transform rhs); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ShowPackageManagerWindow(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void AuxWindowManager_OnAssemblyReload(); + public static Vector2 PassAndReturnVector2(Vector2 v) + { + return InternalEditorUtility.INTERNAL_CALL_PassAndReturnVector2(ref v); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector2 INTERNAL_CALL_PassAndReturnVector2(ref Vector2 v); + public static Color32 PassAndReturnColor32(Color32 c) + { + return InternalEditorUtility.INTERNAL_CALL_PassAndReturnColor32(ref c); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Color32 INTERNAL_CALL_PassAndReturnColor32(ref Color32 c); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool EnsureSceneHasBeenSaved(string operation); + public static Texture2D GetIconForFile(string fileName) + { + int num = fileName.LastIndexOf('.'); + string text = (num != -1) ? fileName.Substring(num + 1).ToLower() : string.Empty; + string text2 = text; + switch (text2) + { + case "boo": + return EditorGUIUtility.FindTexture("boo Script Icon"); + case "cginc": + return EditorGUIUtility.FindTexture("CGProgram Icon"); + case "cs": + return EditorGUIUtility.FindTexture("cs Script Icon"); + case "guiskin": + return EditorGUIUtility.FindTexture("GUISkin Icon"); + case "js": + return EditorGUIUtility.FindTexture("Js Script Icon"); + case "mat": + return EditorGUIUtility.FindTexture("Material Icon"); + case "prefab": + return EditorGUIUtility.FindTexture("PrefabNormal Icon"); + case "shader": + return EditorGUIUtility.FindTexture("Shader Icon"); + case "txt": + return EditorGUIUtility.FindTexture("TextAsset Icon"); + case "unity": + return EditorGUIUtility.FindTexture("SceneAsset Icon"); + case "asset": + case "prefs": + return EditorGUIUtility.FindTexture("GameManager Icon"); + case "anim": + return EditorGUIUtility.FindTexture("Animation Icon"); + case "meta": + return EditorGUIUtility.FindTexture("MetaFile Icon"); + case "mixer": + return EditorGUIUtility.FindTexture("AudioMixerController Icon"); + case "ttf": + case "otf": + case "fon": + case "fnt": + return EditorGUIUtility.FindTexture("Font Icon"); + 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": + return EditorGUIUtility.FindTexture("AudioClip Icon"); + 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("Texture Icon"); + 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("Mesh Icon"); + 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 "m4v": + case "mjp": + case "mov": + case "movie": + case "mp21": + case "mp4": + case "mpe": + case "mpeg": + case "mpg": + case "mpv2": + case "ogm": + case "qt": + case "rm": + case "rmvb": + case "wmw": + case "xvid": + return EditorGUIUtility.FindTexture("MovieTexture Icon"); + case "colors": + case "gradients": + case "curves": + case "curvesnormalized": + case "particlecurves": + case "particlecurvessigned": + case "particledoublecurves": + case "particledoublecurvessigned": + return EditorGUIUtility.FindTexture("ScriptableObject Icon"); + } + return EditorGUIUtility.FindTexture("DefaultAsset Icon"); + } + public static string[] GetEditorSettingsList(string prefix, int count) + { + ArrayList arrayList = new ArrayList(); + for (int i = 1; i <= count; i++) + { + string @string = EditorPrefs.GetString(prefix + i, "defaultValue"); + if (@string == "defaultValue") + { + break; + } + arrayList.Add(@string); + } + return arrayList.ToArray(typeof(string)) as string[]; + } + public static void SaveEditorSettingsList(string prefix, string[] aList, int count) + { + for (int i = 0; i < aList.Length; i++) + { + EditorPrefs.SetString(prefix + (i + 1), aList[i]); + } + for (int i = aList.Length + 1; i <= count; i++) + { + EditorPrefs.DeleteKey(prefix + i); + } + } + public static string TextAreaForDocBrowser(Rect position, string text, GUIStyle style) + { + int controlID = GUIUtility.GetControlID("TextAreaWithTabHandling".GetHashCode(), FocusType.Keyboard, position); + EditorGUI.RecycledTextEditor s_RecycledEditor = EditorGUI.s_RecycledEditor; + Event current = Event.current; + if (s_RecycledEditor.IsEditingControl(controlID) && current.type == EventType.KeyDown) + { + if (current.character == '\t') + { + s_RecycledEditor.Insert('\t'); + current.Use(); + GUI.changed = true; + text = s_RecycledEditor.content.text; + } + if (current.character == '\n') + { + s_RecycledEditor.Insert('\n'); + current.Use(); + GUI.changed = true; + text = s_RecycledEditor.content.text; + } + } + bool flag; + text = EditorGUI.DoTextField(s_RecycledEditor, controlID, EditorGUI.IndentedRect(position), text, style, null, out flag, false, true, false); + return text; + } + public static Camera[] GetSceneViewCameras() + { + return SceneView.GetAllSceneCameras(); + } + public static void ShowGameView() + { + WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true); + } + public static List GetNewSelection(int clickedInstanceID, List allInstanceIDs, List selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection) + { + List list = new List(); + bool flag = Event.current.shift || (EditorGUI.actionKey && useShiftAsActionKey); + bool flag2 = EditorGUI.actionKey && !useShiftAsActionKey; + if (!allowMultiSelection) + { + flag2 = (flag = false); + } + if (flag2) + { + list.AddRange(selectedInstanceIDs); + if (list.Contains(clickedInstanceID)) + { + list.Remove(clickedInstanceID); + } + else + { + list.Add(clickedInstanceID); + } + } + else + { + if (flag) + { + if (clickedInstanceID == lastClickedInstanceID) + { + return selectedInstanceIDs; + } + int num; + int num2; + if (!InternalEditorUtility.GetFirstAndLastSelected(allInstanceIDs, selectedInstanceIDs, out num, out num2)) + { + list.Add(clickedInstanceID); + return list; + } + int num3 = -1; + int num4 = -1; + for (int i = 0; i < allInstanceIDs.Count; i++) + { + if (allInstanceIDs[i] == clickedInstanceID) { - Vector3 vector3 = new Vector3(array[j].x, array[k].y, array[l].z); - if (rectBlueprintMode && InternalEditorUtility.SupportsRectLayout(gameObject.transform)) + num3 = i; + } + if (lastClickedInstanceID != 0 && allInstanceIDs[i] == lastClickedInstanceID) + { + num4 = i; + } + } + int num5 = 0; + if (num4 != -1) + { + num5 = ((num3 <= num4) ? -1 : 1); + } + int num6; + int num7; + if (num3 > num2) + { + num6 = num; + num7 = num3; + } + else + { + if (num3 >= num && num3 < num2) + { + if (num5 > 0) { - Vector3 localPosition = gameObject.transform.localPosition; - localPosition.z = 0f; - vector3 = gameObject.transform.parent.TransformPoint(vector3 + localPosition); + num6 = num3; + num7 = num2; } else { - vector3 = gameObject.transform.TransformPoint(vector3); - } - vector3 = rotation2 * (vector3 - position); - for (int m = 0; m < 3; m++) - { - vector[m] = Mathf.Min(vector[m], vector3[m]); - vector2[m] = Mathf.Max(vector2[m], vector3[m]); + num6 = num; + num7 = num3; } } + else + { + num6 = num3; + num7 = num2; + } + } + for (int j = num6; j <= num7; j++) + { + list.Add(allInstanceIDs[j]); + } + } + else + { + if (keepMultiSelection && selectedInstanceIDs.Contains(clickedInstanceID)) + { + list.AddRange(selectedInstanceIDs); + return list; } + list.Add(clickedInstanceID); } } - return new Bounds((vector + vector2) * 0.5f, vector2 - vector); + return list; } - internal static bool SupportsRectLayout(Transform tr) + private static bool GetFirstAndLastSelected(List allInstanceIDs, List selectedInstanceIDs, out int firstIndex, out int lastIndex) { - return !(tr == null) && !(tr.parent == null) && !(tr.GetComponent() == null) && !(tr.parent.GetComponent() == null); + firstIndex = -1; + lastIndex = -1; + for (int i = 0; i < allInstanceIDs.Count; i++) + { + if (selectedInstanceIDs.Contains(allInstanceIDs[i])) + { + if (firstIndex == -1) + { + firstIndex = i; + } + lastIndex = i; + } + } + return firstIndex != -1 && lastIndex != -1; } - private static Bounds GetLocalBounds(GameObject gameObject) + public static bool IsValidFileName(string filename) { - RectTransform component = gameObject.GetComponent(); - if (component) + string text = InternalEditorUtility.RemoveInvalidCharsFromFileName(filename, false); + return !(text != filename) && !string.IsNullOrEmpty(text); + } + public static string RemoveInvalidCharsFromFileName(string filename, bool logIfInvalidChars) + { + if (string.IsNullOrEmpty(filename)) { - return new Bounds(component.rect.center, component.rect.size); + return filename; } - Renderer component2 = gameObject.GetComponent(); - if (component2 is MeshRenderer) + filename = filename.Trim(); + if (string.IsNullOrEmpty(filename)) { - MeshFilter component3 = component2.GetComponent(); - if (component3 != null && component3.sharedMesh != null) + return filename; + } + string text = new string(Path.GetInvalidFileNameChars()); + string text2 = string.Empty; + bool flag = false; + string text3 = filename; + for (int i = 0; i < text3.Length; i++) + { + char c = text3[i]; + if (text.IndexOf(c) == -1) { - return component3.sharedMesh.bounds; + text2 += c; + } + else + { + flag = true; } } - if (component2 is SpriteRenderer) + if (flag && logIfInvalidChars) { - SpriteRenderer spriteRenderer = component2 as SpriteRenderer; - if (spriteRenderer.sprite != null) + string displayStringOfInvalidCharsOfFileName = InternalEditorUtility.GetDisplayStringOfInvalidCharsOfFileName(filename); + if (displayStringOfInvalidCharsOfFileName.Length > 0) { - Bounds bounds = spriteRenderer.sprite.bounds; - Vector3 size = bounds.size; - size.z = 0f; - bounds.size = size; - return bounds; + Debug.LogWarningFormat("A filename cannot contain the following character{0}: {1}", new object[] + { + (displayStringOfInvalidCharsOfFileName.Length <= 1) ? string.Empty : "s", + displayStringOfInvalidCharsOfFileName + }); } } - return new Bounds(Vector3.zero, Vector3.zero); + return text2; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void OnGameViewFocus(bool focus); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool OpenFileAtLineExternal(string filename, int line); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern MonoIsland[] GetMonoIslands(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool Xbox360GenerateSPAConfig(string spaPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool Xbox360SaveSplashScreenToFile(Texture2D image, string spaPath); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool CanConnectToCacheServer(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern string GetCrashReportFolder(); - [ExcludeFromDocs] - internal static bool RunningUnderWindows8() + public static string GetDisplayStringOfInvalidCharsOfFileName(string filename) { - bool orHigher = true; - return InternalEditorUtility.RunningUnderWindows8(orHigher); + if (string.IsNullOrEmpty(filename)) + { + return string.Empty; + } + string text = new string(Path.GetInvalidFileNameChars()); + string text2 = string.Empty; + for (int i = 0; i < filename.Length; i++) + { + char c = filename[i]; + if (text.IndexOf(c) >= 0 && text2.IndexOf(c) == -1) + { + if (text2.Length > 0) + { + text2 += " "; + } + text2 += c; + } + } + return text2; } - internal static bool RunningUnderWindows8([DefaultValue("true")] bool orHigher) + internal static bool IsScriptOrAssembly(string filename) { - if (Application.platform != RuntimePlatform.WindowsEditor) + if (string.IsNullOrEmpty(filename)) { return false; } - OperatingSystem oSVersion = Environment.OSVersion; - int major = oSVersion.Version.Major; - int minor = oSVersion.Version.Minor; - if (orHigher) + string text = Path.GetExtension(filename).ToLower(); + if (text != null) { - return major > 6 || (major == 6 && minor >= 2); + if (InternalEditorUtility.<>f__switch$map8 == null) + { + InternalEditorUtility.<>f__switch$map8 = new Dictionary(5) + { + + { + ".cs", + 0 + }, + + { + ".js", + 0 + }, + + { + ".boo", + 0 + }, + + { + ".dll", + 1 + }, + + { + ".exe", + 1 + } + }; + } + int num; + if (InternalEditorUtility.<>f__switch$map8.TryGetValue(text, out num)) + { + if (num == 0) + { + return true; + } + if (num == 1) + { + return AssemblyHelper.IsManagedAssembly(filename); + } + } } - return major == 6 && minor == 2; + return false; + } + internal static T ParentHasComponent(Transform trans) where T : Component + { + if (!(trans != null)) + { + return (T)((object)null); + } + T component = trans.GetComponent(); + if (component) + { + return component; + } + return InternalEditorUtility.ParentHasComponent(trans.parent); + } + internal static IEnumerable GetAllScriptGUIDs() + { + return + from asset in AssetDatabase.GetAllAssetPaths() + where InternalEditorUtility.IsScriptOrAssembly(asset) + select AssetDatabase.AssetPathToGUID(asset); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern int DetermineDepthOrder(Transform lhs, Transform rhs); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ShowPackageManagerWindow(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void AuxWindowManager_OnAssemblyReload(); } } diff --git a/UnityEditor/UnityEditorInternal/LogEntries.cs b/UnityEditor/UnityEditorInternal/LogEntries.cs index 78d300a3..edad6b2f 100644 --- a/UnityEditor/UnityEditorInternal/LogEntries.cs +++ b/UnityEditor/UnityEditorInternal/LogEntries.cs @@ -16,7 +16,7 @@ public static extern int consoleFlags } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void OpenEntryFile(int index); + public static extern void RowGotDoubleClicked(int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetStatusText(); diff --git a/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs b/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs index 08dd0bbb..1ab526f3 100644 --- a/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs +++ b/UnityEditor/UnityEditorInternal/MaterialAnimationUtility.cs @@ -53,28 +53,35 @@ public static bool IsAnimated(MaterialProperty materialProp, Renderer target) } return AnimationMode.IsPropertyAnimated(target, "material." + materialProp.name); } - public static bool ApplyMaterialModificationToAnimationRecording(MaterialProperty materialProp, int changedMask, Renderer target, object oldValue) + public static void SetupMaterialPropertyBlock(MaterialProperty materialProp, int changedMask, Renderer target) { MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock(); target.GetPropertyBlock(materialPropertyBlock); materialProp.WriteToMaterialPropertyBlock(materialPropertyBlock, changedMask); target.SetPropertyBlock(materialPropertyBlock); + } + public static bool ApplyMaterialModificationToAnimationRecording(MaterialProperty materialProp, int changedMask, Renderer target, object oldValue) + { switch (materialProp.type) { case MaterialProperty.PropType.Color: + MaterialAnimationUtility.SetupMaterialPropertyBlock(materialProp, changedMask, target); MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (Color)oldValue); return true; case MaterialProperty.PropType.Vector: + MaterialAnimationUtility.SetupMaterialPropertyBlock(materialProp, changedMask, target); MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (Vector4)oldValue); return true; case MaterialProperty.PropType.Float: case MaterialProperty.PropType.Range: + MaterialAnimationUtility.SetupMaterialPropertyBlock(materialProp, changedMask, target); MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(materialProp, target, (float)oldValue); return true; case MaterialProperty.PropType.Texture: if (MaterialProperty.IsTextureOffsetAndScaleChangedMask(changedMask)) { string name = materialProp.name + "_ST"; + MaterialAnimationUtility.SetupMaterialPropertyBlock(materialProp, changedMask, target); MaterialAnimationUtility.ApplyMaterialModificationToAnimationRecording(name, target, (Vector4)oldValue); return true; } diff --git a/UnityEditor/UnityEditorInternal/ModuleMetadata.cs b/UnityEditor/UnityEditorInternal/ModuleMetadata.cs new file mode 100644 index 00000000..d9173d57 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ModuleMetadata.cs @@ -0,0 +1,18 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + internal sealed class ModuleMetadata + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetModuleNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool GetModuleStrippable(string moduleName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int[] GetModuleClasses(string moduleName); + } +} diff --git a/UnityEditor/UnityEditorInternal/PluginsHelper.cs b/UnityEditor/UnityEditorInternal/PluginsHelper.cs new file mode 100644 index 00000000..a598625f --- /dev/null +++ b/UnityEditor/UnityEditorInternal/PluginsHelper.cs @@ -0,0 +1,29 @@ +using System; +using UnityEditor; +using UnityEditor.Modules; +namespace UnityEditorInternal +{ + internal class PluginsHelper + { + public static bool CheckFileCollisions(BuildTarget buildTarget) + { + IPluginImporterExtension pluginImporterExtension = null; + if (ModuleManager.IsPlatformSupported(buildTarget)) + { + pluginImporterExtension = ModuleManager.GetPluginImporterExtension(buildTarget); + } + if (pluginImporterExtension == null) + { + if (BuildPipeline.GetBuildTargetGroup(buildTarget) == BuildTargetGroup.Standalone) + { + pluginImporterExtension = new DesktopPluginImporterExtension(); + } + else + { + pluginImporterExtension = new DefaultPluginImporterExtension(null); + } + } + return pluginImporterExtension.CheckFileCollisions(BuildPipeline.GetBuildTargetName(buildTarget)); + } + } +} diff --git a/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs b/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs deleted file mode 100644 index e4eae41f..00000000 --- a/UnityEditor/UnityEditorInternal/PostProcessNaclPlayer.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Security.Cryptography; -using System.Text; -using System.Threading; -using UnityEditor; -namespace UnityEditorInternal -{ - internal class PostProcessNaclPlayer - { - private static bool s_ChromeFailedToLaunch; - private static string ProgramFilesx86 - { - get - { - if (IntPtr.Size == 8 || !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))) - { - return Environment.GetEnvironmentVariable("ProgramFiles(x86)"); - } - return Environment.GetEnvironmentVariable("ProgramFiles"); - } - } - private static bool IsWindows - { - get - { - return Environment.OSVersion.Platform != PlatformID.Unix; - } - } - private static string BrowserPath - { - get - { - if (PostProcessNaclPlayer.IsWindows) - { - string text = Path.Combine(PostProcessNaclPlayer.ProgramFilesx86, Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe")))); - if (File.Exists(text)) - { - return text; - } - string text2 = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; - if (File.Exists(text2)) - { - return text2; - } - string text3 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Path.Combine("Google", Path.Combine("Chrome", Path.Combine("Application", "chrome.exe")))); - if (File.Exists(text3)) - { - return text3; - } - throw new Exception("Cannot find Chrome"); - } - else - { - string text4 = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; - if (File.Exists(text4)) - { - return text4; - } - throw new Exception("Cannot find Chrome"); - } - } - } - internal static void Launch(BuildTarget target, string targetfile) - { - targetfile = Path.GetFullPath(targetfile); - byte[] buffer = (!PostProcessNaclPlayer.IsWindows) ? Encoding.UTF8.GetBytes(targetfile) : Encoding.Unicode.GetBytes(targetfile); - byte[] array = new SHA256Managed().ComputeHash(buffer); - string text = string.Empty; - for (int i = 0; i < 16; i++) - { - text += (char)(97 + (array[i] >> 4)); - text += (char)(97 + (array[i] & 15)); - } - string text2 = string.Concat(new string[] - { - "chrome-extension://", - text, - "/", - Path.GetFileName(targetfile), - "_nacl.html" - }); - do - { - PostProcessNaclPlayer.s_ChromeFailedToLaunch = false; - Process process = new Process(); - process.StartInfo.FileName = PostProcessNaclPlayer.BrowserPath; - process.StartInfo.Arguments = string.Concat(new string[] - { - " --load-extension=\"", - targetfile, - "\" \"", - text2, - "\"" - }); - process.StartInfo.UseShellExecute = false; - process.Start(); - Thread.Sleep(5000); - PostProcessNaclPlayer.s_ChromeFailedToLaunch = process.HasExited; - if (PostProcessNaclPlayer.s_ChromeFailedToLaunch) - { - if (PostProcessNaclPlayer.IsWindows) - { - PostProcessNaclPlayer.s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Is Google Chrome already running?", "If Chrome is already running, you will only be able to test content which has been installed into Chrome before. If your content is not showing in Chrome, please quit Chrome and try again.", "Try again", "Cancel"); - } - else - { - PostProcessNaclPlayer.s_ChromeFailedToLaunch = EditorUtility.DisplayDialog("Could not start Google Chrome. Is it already running?", "Please quit any running instances of Chrome and try again.", "Try again", "Cancel"); - } - } - } - while (PostProcessNaclPlayer.s_ChromeFailedToLaunch); - } - private static void StripPhysicsFiles(string path, bool stripPhysics) - { - string[] files = Directory.GetFiles(path); - string[] array = files; - for (int i = 0; i < array.Length; i++) - { - string text = array[i]; - if (text.Contains("_nophysx")) - { - if (stripPhysics) - { - string text2 = text.Replace("_nophysx", string.Empty); - File.Delete(text2); - File.Move(text, text2); - } - else - { - File.Delete(text); - } - } - } - string[] directories = Directory.GetDirectories(path); - string[] array2 = directories; - for (int j = 0; j < array2.Length; j++) - { - string path2 = array2[j]; - PostProcessNaclPlayer.StripPhysicsFiles(path2, stripPhysics); - } - } - internal static void PostProcess(BuildOptions options, string installPath, string downloadWebplayerUrl, int width, int height) - { - PostProcessWebPlayer.PostProcess(options, installPath, downloadWebplayerUrl, width, height); - string fileName = Path.GetFileName(installPath); - string playbackEngineDirectory = BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.NaCl, BuildOptions.None); - string text = "unity_nacl_files_3.x.x"; - string text2 = Path.Combine(installPath, text); - string from = Path.Combine(playbackEngineDirectory, "unity_nacl_files"); - if (Directory.Exists(text2)) - { - FileUtil.DeleteFileOrDirectory(text2); - } - FileUtil.CopyFileOrDirectory(from, text2); - PostProcessNaclPlayer.StripPhysicsFiles(text2, PlayerSettings.stripPhysics); - string from2 = Path.Combine(playbackEngineDirectory, "template.html"); - string text3 = Path.Combine(installPath, fileName + "_nacl.html"); - if (File.Exists(text3)) - { - FileUtil.DeleteFileOrDirectory(text3); - } - FileUtil.CopyFileOrDirectory(from2, text3); - string from3 = Path.Combine(playbackEngineDirectory, "template.json"); - string text4 = Path.Combine(installPath, "manifest.json"); - if (File.Exists(text4)) - { - FileUtil.DeleteFileOrDirectory(text4); - } - FileUtil.CopyFileOrDirectory(from3, text4); - List list = new List(); - list.Add("%UNITY_WIDTH%"); - list.Add(width.ToString()); - list.Add("%UNITY_HEIGHT%"); - list.Add(height.ToString()); - list.Add("%UNITY_WEB_NAME%"); - list.Add(PlayerSettings.productName); - list.Add("%UNITY_WEB_PATH%"); - list.Add(fileName + ".unity3d"); - list.Add("%UNITY_WEB_HTML_PATH%"); - list.Add(fileName + "_nacl.html"); - list.Add("%UNITY_NACL_PARAMETERS%"); - list.Add(((options & BuildOptions.Development) == BuildOptions.None) ? string.Empty : "softexceptions=\"1\""); - list.Add("%UNITY_NACL_ENGINE_PATH%"); - list.Add(text); - list.Add("%UNITY_BETA_WARNING%"); - list.Add((!InternalEditorUtility.IsUnityBeta()) ? string.Empty : "\r\n\t\t

Built with beta version of Unity.

"); - string[] templateCustomKeys = PlayerSettings.templateCustomKeys; - for (int i = 0; i < templateCustomKeys.Length; i++) - { - string text5 = templateCustomKeys[i]; - list.Add("%UNITY_CUSTOM_" + text5.ToUpper() + "%"); - list.Add(PlayerSettings.GetTemplateCustomValue(text5)); - } - FileUtil.ReplaceText(text3, list.ToArray()); - FileUtil.ReplaceText(text4, list.ToArray()); - } - } -} diff --git a/UnityEditor/UnityEditorInternal/ProfilerAudioView.cs b/UnityEditor/UnityEditorInternal/ProfilerAudioView.cs new file mode 100644 index 00000000..8d3e4c56 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ProfilerAudioView.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEditorInternal +{ + public enum ProfilerAudioView + { + Stats, + Channels, + Groups, + ChannelsAndGroups + } +} diff --git a/UnityEditor/UnityEditorInternal/ProfilerChart.cs b/UnityEditor/UnityEditorInternal/ProfilerChart.cs index 5f08e493..5f3cbe70 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerChart.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerChart.cs @@ -5,14 +5,31 @@ namespace UnityEditorInternal { internal class ProfilerChart { + private const string kPrefCharts = "ProfilerChart"; + private bool m_Active; public ProfilerArea m_Area; public Chart.ChartType m_Type; public float m_DataScale; public Chart m_Chart; public ChartData m_Data; public ChartSeries[] m_Series; - public bool m_Active; public GUIContent m_Icon; + public bool active + { + get + { + return this.m_Active; + } + set + { + if (this.m_Active != value) + { + this.m_Active = value; + this.ApplyActiveState(); + this.SaveActiveState(); + } + } + } public ProfilerChart(ProfilerArea area, Chart.ChartType type, float dataScale, int seriesCount) { this.m_Area = area; @@ -21,8 +38,8 @@ public ProfilerChart(ProfilerArea area, Chart.ChartType type, float dataScale, i this.m_Chart = new Chart(); this.m_Data = new ChartData(); this.m_Series = new ChartSeries[seriesCount]; - this.m_Active = EditorPrefs.GetBool("ProfilerChart" + area, true); - this.m_Icon = EditorGUIUtility.TextContent("Profiler." + Enum.GetName(typeof(ProfilerArea), area)); + this.m_Active = this.ReadActiveState(); + this.ApplyActiveState(); } public int DoChartGUI(int currentFrame, ProfilerArea currentArea, out Chart.ChartAction action) { @@ -37,11 +54,41 @@ public int DoChartGUI(int currentFrame, ProfilerArea currentArea, out Chart.Char } this.m_Data.selectedLabels = array; } - return this.m_Chart.DoGUI(this.m_Type, currentFrame, this.m_Data, currentArea == this.m_Area, this.m_Icon, out action); + if (this.m_Icon == null) + { + this.m_Icon = EditorGUIUtility.TextContent("Profiler." + Enum.GetName(typeof(ProfilerArea), this.m_Area)); + } + return this.m_Chart.DoGUI(this.m_Type, currentFrame, this.m_Data, this.m_Area, currentArea == this.m_Area, this.m_Icon, out action); } public void LoadAndBindSettings() { this.m_Chart.LoadAndBindSettings("ProfilerChart" + this.m_Area, this.m_Data); } + private void ApplyActiveState() + { + if (this.m_Area == ProfilerArea.GPU) + { + ProfilerDriver.profileGPU = this.active; + } + } + private bool ReadActiveState() + { + if (this.m_Area == ProfilerArea.GPU) + { + return InspectorState.GetBool("ProfilerChart" + this.m_Area, false); + } + return EditorPrefs.GetBool("ProfilerChart" + this.m_Area, true); + } + private void SaveActiveState() + { + if (this.m_Area == ProfilerArea.GPU) + { + InspectorState.SetBool("ProfilerChart" + this.m_Area, this.m_Active); + } + else + { + EditorPrefs.SetBool("ProfilerChart" + this.m_Area, this.m_Active); + } + } } } diff --git a/UnityEditor/UnityEditorInternal/ProfilerDriver.cs b/UnityEditor/UnityEditorInternal/ProfilerDriver.cs index cf7f4096..e4d4f152 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerDriver.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerDriver.cs @@ -32,6 +32,15 @@ public static extern string selectedPropertyPath [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool profileGPU + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern bool profileEditor { [WrapperlessIcall] @@ -50,6 +59,12 @@ public static extern bool deepProfiling [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern string directConnectionUrl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern int connectedProfiler { [WrapperlessIcall] @@ -103,6 +118,9 @@ public static extern bool isGPUProfilerSupported public static extern void EndFrame(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetHistory(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetNextFrameIndex(int frame); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs b/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs index e53c0944..ba13e2da 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerFrameDataIterator.cs @@ -36,6 +36,12 @@ public extern int id [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern int instanceId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern float frameTimeMS { [WrapperlessIcall] diff --git a/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs b/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs index 20957cd9..c4c3ba75 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerHierarchyGUI.cs @@ -15,6 +15,204 @@ internal class Styles public GUIStyle entryOdd = "OL EntryBackOdd"; public GUIStyle numberLabel = "OL Label"; public GUIStyle foldout = "IN foldout"; + public GUIContent disabledSearchText = new GUIContent("Showing search results are disabled while recording with deep profiling.\nStop recording to view search results."); + public GUIContent notShowingAllResults = new GUIContent("...", "Narrow your search. Not all search results can be shown."); + } + internal class SearchResults + { + private struct SearchResult + { + public string propertyPath; + public string[] columnValues; + } + private ProfilerHierarchyGUI.SearchResults.SearchResult[] m_SearchResults; + private int m_NumResultsUsed; + private ProfilerColumn[] m_ColumnsToShow; + private int m_SelectedSearchIndex; + private bool m_FoundAllResults; + private string m_LastSearchString; + private int m_LastFrameIndex; + private ProfilerColumn m_LastSortType; + public int numRows + { + get + { + return this.m_NumResultsUsed + ((!this.m_FoundAllResults) ? 1 : 0); + } + } + public int selectedSearchIndex + { + get + { + return this.m_SelectedSearchIndex; + } + set + { + if (value < this.m_NumResultsUsed) + { + this.m_SelectedSearchIndex = value; + } + else + { + this.m_SelectedSearchIndex = -1; + } + if (this.m_SelectedSearchIndex >= 0) + { + string propertyPath = this.m_SearchResults[this.m_SelectedSearchIndex].propertyPath; + if (propertyPath != ProfilerDriver.selectedPropertyPath) + { + ProfilerDriver.selectedPropertyPath = propertyPath; + } + } + } + } + public void Init(int maxNumberSearchResults) + { + this.m_SearchResults = new ProfilerHierarchyGUI.SearchResults.SearchResult[maxNumberSearchResults]; + this.m_NumResultsUsed = 0; + this.m_LastSearchString = string.Empty; + this.m_LastFrameIndex = -1; + this.m_FoundAllResults = false; + this.m_ColumnsToShow = null; + this.m_SelectedSearchIndex = -1; + } + public void Filter(ProfilerProperty property, ProfilerColumn[] columns, string searchString, int frameIndex, ProfilerColumn sortType) + { + if (searchString == this.m_LastSearchString && frameIndex == this.m_LastFrameIndex && sortType == this.m_LastSortType) + { + return; + } + this.m_LastSearchString = searchString; + this.m_LastFrameIndex = frameIndex; + this.m_LastSortType = sortType; + this.IterateProfilingData(property, columns, searchString); + } + private void IterateProfilingData(ProfilerProperty property, ProfilerColumn[] columns, string searchString) + { + this.m_NumResultsUsed = 0; + this.m_ColumnsToShow = columns; + this.m_FoundAllResults = true; + this.m_SelectedSearchIndex = -1; + int num = 0; + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + while (property.Next(true)) + { + if (num >= this.m_SearchResults.Length) + { + this.m_FoundAllResults = false; + break; + } + string propertyPath = property.propertyPath; + int startIndex = Mathf.Max(propertyPath.LastIndexOf('/'), 0); + if (propertyPath.IndexOf(searchString, startIndex, StringComparison.CurrentCultureIgnoreCase) > -1) + { + string[] array = new string[this.m_ColumnsToShow.Length]; + for (int i = 0; i < this.m_ColumnsToShow.Length; i++) + { + array[i] = property.GetColumn(this.m_ColumnsToShow[i]); + } + this.m_SearchResults[num].propertyPath = propertyPath; + this.m_SearchResults[num].columnValues = array; + if (propertyPath == selectedPropertyPath) + { + this.m_SelectedSearchIndex = num; + } + num++; + } + } + this.m_NumResultsUsed = num; + } + public void Draw(ProfilerHierarchyGUI gui, int controlID) + { + this.HandleCommandEvents(gui); + Event current = Event.current; + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + int num; + int num2; + ProfilerHierarchyGUI.SearchResults.GetFirstAndLastRowVisible(this.m_NumResultsUsed, 16f, gui.m_TextScroll.y, (float)gui.m_ScrollViewHeight, out num, out num2); + for (int i = num; i <= num2; i++) + { + bool flag = selectedPropertyPath == this.m_SearchResults[i].propertyPath; + Rect rowRect = gui.GetRowRect(i); + GUIStyle rowBackgroundStyle = gui.GetRowBackgroundStyle(i); + if (current.type == EventType.MouseDown && rowRect.Contains(current.mousePosition)) + { + this.m_SelectedSearchIndex = i; + gui.RowMouseDown(this.m_SearchResults[i].propertyPath); + GUIUtility.keyboardControl = controlID; + current.Use(); + } + if (current.type == EventType.Repaint) + { + rowBackgroundStyle.Draw(rowRect, GUIContent.none, false, false, flag, GUIUtility.keyboardControl == controlID); + if (rowRect.Contains(current.mousePosition)) + { + string text = this.m_SearchResults[i].propertyPath.Replace("/", "/\n"); + if (this.m_SelectedSearchIndex >= 0) + { + text += "\n\n(Press 'F' to frame selection)"; + } + GUI.Label(rowRect, GUIContent.Temp(string.Empty, text)); + } + gui.DrawTextColumn(ref rowRect, this.m_SearchResults[i].columnValues[0], 0, 4f, flag); + ProfilerHierarchyGUI.styles.numberLabel.alignment = TextAnchor.MiddleRight; + int num3 = 1; + for (int j = 1; j < gui.m_VisibleColumns.Length; j++) + { + if (gui.ColIsVisible(j)) + { + rowRect.x += (float)gui.m_Splitter.realSizes[num3 - 1]; + rowRect.width = (float)gui.m_Splitter.realSizes[num3] - 4f; + num3++; + ProfilerHierarchyGUI.styles.numberLabel.Draw(rowRect, this.m_SearchResults[i].columnValues[j], false, false, false, flag); + } + } + ProfilerHierarchyGUI.styles.numberLabel.alignment = TextAnchor.MiddleLeft; + } + } + if (!this.m_FoundAllResults && current.type == EventType.Repaint) + { + int numResultsUsed = this.m_NumResultsUsed; + Rect position = new Rect(1f, 16f * (float)numResultsUsed, GUIClip.visibleRect.width, 16f); + GUIStyle gUIStyle = (numResultsUsed % 2 != 0) ? ProfilerHierarchyGUI.styles.entryOdd : ProfilerHierarchyGUI.styles.entryEven; + GUI.Label(position, GUIContent.Temp(string.Empty, ProfilerHierarchyGUI.styles.notShowingAllResults.tooltip), GUIStyle.none); + gUIStyle.Draw(position, GUIContent.none, false, false, false, false); + gui.DrawTextColumn(ref position, ProfilerHierarchyGUI.styles.notShowingAllResults.text, 0, 4f, false); + } + } + private static void GetFirstAndLastRowVisible(int numRows, float rowHeight, float scrollBarY, float scrollAreaHeight, out int firstRowVisible, out int lastRowVisible) + { + firstRowVisible = (int)Mathf.Floor(scrollBarY / rowHeight); + lastRowVisible = firstRowVisible + (int)Mathf.Ceil(scrollAreaHeight / rowHeight); + firstRowVisible = Mathf.Max(firstRowVisible, 0); + lastRowVisible = Mathf.Min(lastRowVisible, numRows - 1); + } + public void MoveSelection(int steps, ProfilerHierarchyGUI gui) + { + int num = Mathf.Clamp(this.m_SelectedSearchIndex + steps, 0, this.m_NumResultsUsed - 1); + if (num != this.m_SelectedSearchIndex) + { + this.m_SelectedSearchIndex = num; + gui.m_Window.SetSelectedPropertyPath(this.m_SearchResults[num].propertyPath); + } + } + private void HandleCommandEvents(ProfilerHierarchyGUI gui) + { + Event current = Event.current; + EventType type = current.type; + if (type == EventType.ExecuteCommand || type == EventType.ValidateCommand) + { + bool flag = type == EventType.ExecuteCommand; + if (Event.current.commandName == "FrameSelected") + { + if (flag) + { + gui.FrameSelection(); + } + current.Use(); + } + } + } } private const float kRowHeight = 16f; private const float kFoldoutSize = 14f; @@ -25,7 +223,7 @@ internal class Styles private const int kLast = 999999; private const float kScrollbarWidth = 16f; private static int hierarchyViewHash = "HierarchyView".GetHashCode(); - private static ProfilerHierarchyGUI.Styles ms_Styles; + protected static ProfilerHierarchyGUI.Styles ms_Styles; private IProfilerWindowController m_Window; private SplitterState m_Splitter; private ProfilerColumn[] m_ColumnsToShow; @@ -36,15 +234,18 @@ internal class Styles private string m_ColumnSettingsName; private Vector2 m_TextScroll = Vector2.zero; private GUIContent[] m_HeaderContent; + private GUIContent m_SearchHeader; private SerializedStringTable m_ExpandedHash = new SerializedStringTable(); private bool m_ExpandAll; private int m_ScrollViewHeight; private int m_DoScroll; private int m_SelectedIndex = -1; private bool m_DetailPane; + private ProfilerHierarchyGUI.SearchResults m_SearchResults; + private bool m_SetKeyboardFocus; private ProfilerColumn m_SortType = ProfilerColumn.TotalTime; private string m_DetailViewSelectedProperty = string.Empty; - private static ProfilerHierarchyGUI.Styles styles + protected static ProfilerHierarchyGUI.Styles styles { get { @@ -60,11 +261,22 @@ public int selectedIndex { get { + if (this.IsSearchActive()) + { + return this.m_SearchResults.selectedSearchIndex; + } return this.m_SelectedIndex; } set { - this.m_SelectedIndex = value; + if (this.IsSearchActive()) + { + this.m_SearchResults.selectedSearchIndex = value; + } + else + { + this.m_SelectedIndex = value; + } } } public ProfilerColumn sortType @@ -96,11 +308,23 @@ public ProfilerHierarchyGUI(IProfilerWindowController window, string columnSetti { throw new ArgumentException("Number of columns to show does not match number of column names."); } + this.m_SearchHeader = new GUIContent("Search"); this.m_VisibleColumns = new bool[columnNames.Length]; for (int j = 0; j < this.m_VisibleColumns.Length; j++) { this.m_VisibleColumns[j] = true; } + this.m_SearchResults = new ProfilerHierarchyGUI.SearchResults(); + this.m_SearchResults.Init(100); + this.m_Window.Repaint(); + } + public void SetKeyboardFocus() + { + this.m_SetKeyboardFocus = true; + } + public void SelectFirstRow() + { + this.MoveSelection(-999999); } private void SetupSplitter() { @@ -108,9 +332,9 @@ private void SetupSplitter() { return; } - this.m_SplitterRelativeSizes = new float[this.m_ColumnNames.Length]; - this.m_SplitterMinWidths = new int[this.m_ColumnNames.Length]; - for (int i = 0; i < this.m_SplitterRelativeSizes.Length; i++) + this.m_SplitterRelativeSizes = new float[this.m_ColumnNames.Length + 1]; + this.m_SplitterMinWidths = new int[this.m_ColumnNames.Length + 1]; + for (int i = 0; i < this.m_ColumnNames.Length; i++) { this.m_SplitterMinWidths[i] = (int)ProfilerHierarchyGUI.styles.header.CalcSize(this.m_HeaderContent[i]).x; this.m_SplitterRelativeSizes[i] = 70f; @@ -119,6 +343,8 @@ private void SetupSplitter() this.m_SplitterRelativeSizes[i] = 1f; } } + this.m_SplitterMinWidths[this.m_ColumnNames.Length] = 16; + this.m_SplitterRelativeSizes[this.m_ColumnNames.Length] = 0f; if (this.m_ColumnsToShow[0] == ProfilerColumn.FunctionName) { this.m_SplitterRelativeSizes[0] = 400f; @@ -158,8 +384,33 @@ private void DoScroll() { this.m_DoScroll = 2; } + public void FrameSelection() + { + if (string.IsNullOrEmpty(ProfilerDriver.selectedPropertyPath)) + { + return; + } + this.m_Window.SetSearch(string.Empty); + string selectedPropertyPath = ProfilerDriver.selectedPropertyPath; + string[] array = selectedPropertyPath.Split(new char[] + { + '/' + }); + string text = array[0]; + for (int i = 1; i < array.Length; i++) + { + this.SetExpanded(text, true); + text = text + "/" + array[i]; + } + this.DoScroll(); + } private void MoveSelection(int steps) { + if (this.IsSearchActive()) + { + this.m_SearchResults.MoveSelection(steps, this); + return; + } int num = this.m_SelectedIndex + steps; if (num < 0) { @@ -226,26 +477,34 @@ private void HandleKeyboard(int id) { return; } + bool flag = this.IsSearchActive(); + int num = 0; switch (current.keyCode) { case KeyCode.UpArrow: - this.MoveSelection(-1); - goto IL_16A; + num = -1; + goto IL_161; case KeyCode.DownArrow: - this.MoveSelection(1); - goto IL_16A; + num = 1; + goto IL_161; case KeyCode.RightArrow: - this.SetExpanded(ProfilerDriver.selectedPropertyPath, true); - goto IL_16A; + if (!flag) + { + this.SetExpanded(ProfilerDriver.selectedPropertyPath, true); + } + goto IL_161; case KeyCode.LeftArrow: - this.SetExpanded(ProfilerDriver.selectedPropertyPath, false); - goto IL_16A; + if (!flag) + { + this.SetExpanded(ProfilerDriver.selectedPropertyPath, false); + } + goto IL_161; case KeyCode.Home: - this.MoveSelection(-999999); - goto IL_16A; + num = -999999; + goto IL_161; case KeyCode.End: - this.MoveSelection(999999); - goto IL_16A; + num = 999999; + goto IL_161; case KeyCode.PageUp: if (Application.platform == RuntimePlatform.OSXEditor) { @@ -257,8 +516,8 @@ private void HandleKeyboard(int id) current.Use(); return; } - this.MoveSelection(-Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f)); - goto IL_16A; + num = -Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f); + goto IL_161; case KeyCode.PageDown: if (Application.platform == RuntimePlatform.OSXEditor) { @@ -266,15 +525,23 @@ private void HandleKeyboard(int id) current.Use(); return; } - this.MoveSelection(Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f)); - goto IL_16A; + num = Mathf.RoundToInt((float)this.m_ScrollViewHeight / 16f); + goto IL_161; } return; - IL_16A: + IL_161: + if (num != 0) + { + this.MoveSelection(num); + } this.DoScroll(); current.Use(); } - private void DrawColumnsHeader() + private bool IsSearchActive() + { + return this.m_Window.IsSearching(); + } + private void DrawColumnsHeader(string searchString) { bool flag = false; GUILayout.BeginHorizontal(new GUILayoutOption[0]); @@ -283,22 +550,20 @@ private void DrawColumnsHeader() flag = true; Event.current.type = EventType.Used; } - SplitterGUILayout.BeginHorizontalSplit(this.m_Splitter, EditorStyles.toolbar, new GUILayoutOption[0]); - for (int i = 0; i < this.m_ColumnNames.Length; i++) + SplitterGUILayout.BeginHorizontalSplit(this.m_Splitter, GUIStyle.none, new GUILayoutOption[0]); + this.DrawTitle((!this.IsSearchActive()) ? this.m_HeaderContent[0] : this.m_SearchHeader, 0); + for (int i = 1; i < this.m_ColumnNames.Length; i++) { this.DrawTitle(this.m_HeaderContent[i], i); } SplitterGUILayout.EndHorizontalSplit(); - GUILayout.Box(string.Empty, ProfilerHierarchyGUI.ms_Styles.header, new GUILayoutOption[] - { - GUILayout.Width(16f) - }); GUILayout.EndHorizontal(); if (flag) { Event.current.type = EventType.MouseDown; this.HandleHeaderMouse(GUILayoutUtility.GetLastRect()); } + GUILayout.Space(1f); } private bool IsExpanded(string expanded) { @@ -308,7 +573,37 @@ private void SetExpanded(ProfilerProperty property, bool expanded) { this.SetExpanded(property.propertyPath, expanded); } - private int DrawProfilingData(ProfilerProperty property, int id) + private int DrawProfilingData(ProfilerProperty property, string searchString, int id) + { + int num; + if (this.IsSearchActive()) + { + num = this.DrawSearchResult(property, searchString, id); + } + else + { + num = this.DrawTreeView(property, id); + } + if (num == 0) + { + Rect rowRect = this.GetRowRect(0); + rowRect.height = 1f; + GUI.Label(rowRect, GUIContent.none, ProfilerHierarchyGUI.styles.entryEven); + } + return num; + } + private int DrawSearchResult(ProfilerProperty property, string searchString, int id) + { + if (!this.AllowSearching()) + { + this.DoSearchingDisabledInfoGUI(); + return 0; + } + this.m_SearchResults.Filter(property, this.m_ColumnsToShow, searchString, this.m_Window.GetActiveVisibleFrameIndex(), this.sortType); + this.m_SearchResults.Draw(this, id); + return this.m_SearchResults.numRows; + } + private int DrawTreeView(ProfilerProperty property, int id) { this.m_SelectedIndex = -1; bool enterChildren = true; @@ -336,6 +631,20 @@ private int DrawProfilingData(ProfilerProperty property, int id) } return num; } + private void DoSearchingDisabledInfoGUI() + { + EditorGUI.BeginDisabledGroup(true); + TextAnchor alignment = EditorStyles.label.alignment; + EditorStyles.label.alignment = TextAnchor.MiddleCenter; + GUI.Label(new Rect(0f, 10f, GUIClip.visibleRect.width, 30f), ProfilerHierarchyGUI.styles.disabledSearchText, EditorStyles.label); + EditorStyles.label.alignment = alignment; + EditorGUI.EndDisabledGroup(); + } + private bool AllowSearching() + { + bool flag = Profiler.enabled && (ProfilerDriver.profileEditor || EditorApplication.isPlaying); + return !flag || !ProfilerDriver.deepProfiling; + } private void UnselectIfClickedOnEmptyArea(int rowCount) { Rect rect = GUILayoutUtility.GetRect(GUIClip.visibleRect.width, 16f * (float)rowCount, new GUILayoutOption[] @@ -430,7 +739,7 @@ private void ColumnContextClick(object userData, string[] options, int selected) { this.SetColumnVisible(selected, !this.ColIsVisible(selected)); } - private void DrawTextColumn(ref Rect currentRect, string text, int index, float margin, bool selected) + protected void DrawTextColumn(ref Rect currentRect, string text, int index, float margin, bool selected) { if (index != 0) { @@ -453,16 +762,35 @@ private static string DetailViewSelectedPropertyPath(ProfilerProperty property, { return property.propertyPath + "/" + instanceId; } + private Rect GetRowRect(int rowIndex) + { + return new Rect(1f, 16f * (float)rowIndex, GUIClip.visibleRect.width, 16f); + } + private GUIStyle GetRowBackgroundStyle(int rowIndex) + { + return (rowIndex % 2 != 0) ? ProfilerHierarchyGUI.styles.entryOdd : ProfilerHierarchyGUI.styles.entryEven; + } + private void RowMouseDown(string propertyPath) + { + if (propertyPath == ProfilerDriver.selectedPropertyPath) + { + this.m_Window.ClearSelectedPropertyPath(); + } + else + { + this.m_Window.SetSelectedPropertyPath(propertyPath); + } + } private bool DrawProfileDataItem(ProfilerProperty property, int rowCount, bool selected, int id) { bool flag = false; Event current = Event.current; - Rect rect = new Rect(1f, 16f * (float)rowCount, GUIClip.visibleRect.width, 16f); - Rect position = rect; - GUIStyle gUIStyle = (rowCount % 2 != 0) ? ProfilerHierarchyGUI.styles.entryOdd : ProfilerHierarchyGUI.styles.entryEven; + Rect rowRect = this.GetRowRect(rowCount); + Rect position = rowRect; + GUIStyle rowBackgroundStyle = this.GetRowBackgroundStyle(rowCount); if (current.type == EventType.Repaint) { - gUIStyle.Draw(position, GUIContent.none, false, false, selected, false); + rowBackgroundStyle.Draw(position, GUIContent.none, false, false, selected, false); } float num = (float)property.depth * 16f + 4f; if (property.HasChildren) @@ -495,7 +823,7 @@ private bool DrawProfileDataItem(ProfilerProperty property, int rowCount, bool s } ProfilerHierarchyGUI.styles.numberLabel.alignment = TextAnchor.MiddleLeft; } - if (current.type == EventType.MouseDown && rect.Contains(current.mousePosition)) + if (current.type == EventType.MouseDown && rowRect.Contains(current.mousePosition)) { GUIUtility.hotControl = 0; if (!EditorGUI.actionKey) @@ -513,7 +841,10 @@ private bool DrawProfileDataItem(ProfilerProperty property, int rowCount, bool s { @object = ((Component)@object).gameObject; } - EditorGUIUtility.PingObject(@object.GetInstanceID()); + if (@object != null) + { + EditorGUIUtility.PingObject(@object.GetInstanceID()); + } } else { @@ -531,14 +862,7 @@ private bool DrawProfileDataItem(ProfilerProperty property, int rowCount, bool s } else { - if (property.propertyPath == ProfilerDriver.selectedPropertyPath) - { - this.m_Window.ClearSelectedPropertyPath(); - } - else - { - this.m_Window.SetSelectedPropertyPath(property.propertyPath); - } + this.RowMouseDown(property.propertyPath); } this.DoScroll(); } @@ -613,7 +937,7 @@ private void DoScrolling() this.m_DoScroll--; if (this.m_DoScroll == 0) { - float num = 16f * (float)this.m_SelectedIndex; + float num = 16f * (float)this.selectedIndex; float min = num - (float)this.m_ScrollViewHeight + 16f; this.m_TextScroll.y = Mathf.Clamp(this.m_TextScroll.y, min, num); } @@ -623,15 +947,15 @@ private void DoScrolling() } } } - public void DoGUI(ProfilerProperty property, bool expandAll) + public void DoGUI(ProfilerProperty property, string searchString, bool expandAll) { this.m_ExpandAll = expandAll; this.SetupSplitter(); this.DoScrolling(); - int controlID = GUIUtility.GetControlID(ProfilerHierarchyGUI.hierarchyViewHash, FocusType.Passive); - this.DrawColumnsHeader(); + int controlID = GUIUtility.GetControlID(ProfilerHierarchyGUI.hierarchyViewHash, FocusType.Keyboard); + this.DrawColumnsHeader(searchString); this.m_TextScroll = EditorGUILayout.BeginScrollView(this.m_TextScroll, ProfilerHierarchyGUI.ms_Styles.background, new GUILayoutOption[0]); - int rowCount = this.DrawProfilingData(property, controlID); + int rowCount = this.DrawProfilingData(property, searchString, controlID); property.Cleanup(); this.UnselectIfClickedOnEmptyArea(rowCount); if (Event.current.type == EventType.Repaint) @@ -640,6 +964,12 @@ public void DoGUI(ProfilerProperty property, bool expandAll) } GUILayout.EndScrollView(); this.HandleKeyboard(controlID); + if (this.m_SetKeyboardFocus && Event.current.type == EventType.Repaint) + { + this.m_SetKeyboardFocus = false; + GUIUtility.keyboardControl = controlID; + this.m_Window.Repaint(); + } } } } diff --git a/UnityEditor/UnityEditorInternal/ProfilerProperty.cs b/UnityEditor/UnityEditorInternal/ProfilerProperty.cs index 4723b179..82be03f5 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerProperty.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerProperty.cs @@ -91,5 +91,11 @@ public extern bool frameDataReady [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern string GetColumn(ProfilerColumn column); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AudioProfilerInfo[] GetAudioProfilerInfo(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string GetAudioProfilerNameByOffset(int offset); } } diff --git a/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs b/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs index 2ea54e4e..cba1674c 100644 --- a/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs +++ b/UnityEditor/UnityEditorInternal/ProfilerTimelineGUI.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace UnityEditorInternal @@ -12,24 +13,30 @@ internal class Styles public GUIStyle tooltip = "AnimationEventTooltip"; public GUIStyle tooltipArrow = "AnimationEventTooltipArrow"; public GUIStyle bar; + public GUIStyle profilerGraphBackground = new GUIStyle("ProfilerScrollviewBackground"); + public GUIStyle leftPane = new GUIStyle("ProfilerLeftPane"); + public GUIStyle rightPane = "ProfilerRightPane"; internal Styles() { this.bar = new GUIStyle(EditorStyles.miniButton); this.bar.margin = new RectOffset(0, 0, 0, 0); this.bar.padding = new RectOffset(0, 0, 0, 0); this.bar.border = new RectOffset(1, 1, 1, 1); - GUIStyleState arg_B8_0 = this.bar.normal; + GUIStyleState arg_F2_0 = this.bar.normal; Texture2D texture2D = EditorGUIUtility.whiteTexture; this.bar.active.background = texture2D; texture2D = texture2D; this.bar.hover.background = texture2D; - arg_B8_0.background = texture2D; - GUIStyleState arg_F3_0 = this.bar.normal; + arg_F2_0.background = texture2D; + GUIStyleState arg_12D_0 = this.bar.normal; Color color = Color.black; this.bar.active.textColor = color; color = color; this.bar.hover.textColor = color; - arg_F3_0.textColor = color; + arg_12D_0.textColor = color; + this.profilerGraphBackground.overflow.left = -169; + this.leftPane.padding.left = this.leftPane.padding.left - 40; + this.leftPane.padding.top = 4; } } private const float kSmallWidth = 7f; @@ -69,18 +76,31 @@ private float GetThreadY(Rect r, int thread, int threadCount) } return r.y + r.height / (float)(threadCount + 2) * (float)thread; } + private void DrawBars(Rect r, int frameIndex) + { + ProfilerFrameDataIterator profilerFrameDataIterator = new ProfilerFrameDataIterator(); + profilerFrameDataIterator.SetRoot(frameIndex, 0); + int threadCount = profilerFrameDataIterator.GetThreadCount(frameIndex); + if (Event.current.type == EventType.Repaint) + { + for (int i = 0; i < threadCount; i++) + { + profilerFrameDataIterator.SetRoot(frameIndex, i); + float threadY = this.GetThreadY(r, i, threadCount); + float height = this.GetThreadY(r, i + 1, threadCount) - threadY; + Rect position = new Rect(r.x - 170f, threadY, 170f, height); + Rect position2 = new Rect(r.x, threadY, r.width, height); + ProfilerTimelineGUI.styles.rightPane.Draw(position2, false, false, false, false); + ProfilerTimelineGUI.styles.leftPane.Draw(position, GUIContent.Temp(profilerFrameDataIterator.GetThreadName()), false, false, false, false); + } + } + } private void DrawGrid(Rect r, int threadCount, float frameTime) { - HandleUtility.handleWireMaterial.SetPass(0); float num = 16.66667f; + HandleUtility.ApplyWireMaterial(); GL.Begin(1); GL.Color(new Color(1f, 1f, 1f, 0.2f)); - for (int i = 0; i < threadCount; i++) - { - float threadY = this.GetThreadY(r, i, threadCount); - GL.Vertex3(r.x, threadY, 0f); - GL.Vertex3(r.x + r.width, threadY, 0f); - } float num3; for (float num2 = num; num2 <= frameTime; num2 += num) { @@ -145,10 +165,8 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa float num6 = 0f; r.y = num6; r.x = num6; - if (!ghost) - { - GUI.Label(new Rect(r.x, r.y + r.height * 0.5f - 8f, r.width, 16f), iter.GetThreadName()); - } + bool flag2 = Event.current.clickCount == 1 && Event.current.type == EventType.MouseDown; + bool flag3 = Event.current.clickCount == 2 && Event.current.type == EventType.MouseDown; Rect shownArea = this.m_TimeArea.shownArea; float rectWidthDivShownWidth = r.width / shownArea.width; float x2 = r.x; @@ -156,7 +174,7 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa while (iter.Next(enterChildren)) { enterChildren = true; - float num7 = iter.startTimeMS + timeOffset * 1000f; + float num7 = iter.startTimeMS + timeOffset; float durationMS = iter.durationMS; float num8 = Mathf.Max(durationMS, 0.0003f); float num9 = ProfilerTimelineGUI.TimeToPixelCached(num7, rectWidthDivShownWidth, x3, x2); @@ -172,20 +190,20 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa float num13 = r.y + num12 * 16f; if (flag) { - bool flag2 = false; + bool flag4 = false; if (num11 >= num) { - flag2 = true; + flag4 = true; } if (num3 != num13) { - flag2 = true; + flag4 = true; } if (num9 - num2 > 6f) { - flag2 = true; + flag4 = true; } - if (flag2) + if (flag4) { this.DrawSmallGroup(x, num2, num3, num4); flag = false; @@ -208,22 +226,22 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa { int id = iter.id; string path = iter.path; - bool flag3 = path == selectedPropertyPath && !ghost; + bool flag5 = path == selectedPropertyPath && !ghost; if (this.m_SelectedID >= 0) { - flag3 &= (id == this.m_SelectedID); + flag5 &= (id == this.m_SelectedID); } - flag3 &= (threadIdx == this.m_SelectedThread); + flag5 &= (threadIdx == this.m_SelectedThread); Color white = Color.white; Color color2 = colors[iter.group % colors.Length]; - color2.a = ((!flag3) ? 0.75f : 1f); + color2.a = ((!flag5) ? 0.75f : 1f); if (ghost) { color2.a = 0.4f; white.a = 0.5f; } string text2 = iter.name; - if (flag3) + if (flag5) { text = text2; this.m_SelectedTime = num7; @@ -236,7 +254,7 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa } else { - if (num11 < 50f && !flag3) + if (num11 < 50f && !flag5) { white.a *= (num11 - 20f) / 30f; } @@ -247,11 +265,36 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa } GUI.color = color2; GUI.contentColor = white; - if (GUI.Button(new Rect(num9, num13, num11, 14f), text2, ProfilerTimelineGUI.styles.bar)) + Rect position = new Rect(num9, num13, num11, 14f); + GUI.Label(position, text2, ProfilerTimelineGUI.styles.bar); + if ((flag2 || flag3) && position.Contains(Event.current.mousePosition)) { this.m_Window.SetSelectedPropertyPath(path); this.m_SelectedThread = threadIdx; this.m_SelectedID = id; + UnityEngine.Object @object = EditorUtility.InstanceIDToObject(iter.instanceId); + if (@object is Component) + { + @object = ((Component)@object).gameObject; + } + if (@object != null) + { + if (flag2) + { + EditorGUIUtility.PingObject(@object.GetInstanceID()); + } + else + { + if (flag3) + { + Selection.objects = new List + { + @object + }.ToArray(); + } + } + } + Event.current.Use(); } flag = false; } @@ -278,26 +321,26 @@ private void DrawProfilingData(ProfilerFrameDataIterator iter, Rect r, int threa { num14 = r.xMax - 20f; } - Rect position; + Rect position2; if (num5 + 6f + vector.y < r.yMax) { - position = new Rect(num14 - 32f, num5, 50f, 7f); - GUI.Label(position, GUIContent.none, ProfilerTimelineGUI.styles.tooltipArrow); + position2 = new Rect(num14 - 32f, num5, 50f, 7f); + GUI.Label(position2, GUIContent.none, ProfilerTimelineGUI.styles.tooltipArrow); } - position = new Rect(num14, num5 + 6f, vector.x, vector.y); - if (position.xMax > r.xMax + 20f) + position2 = new Rect(num14, num5 + 6f, vector.x, vector.y); + if (position2.xMax > r.xMax + 20f) { - position.x = r.xMax - position.width + 20f; + position2.x = r.xMax - position2.width + 20f; } - if (position.yMax > r.yMax) + if (position2.yMax > r.yMax) { - position.y = r.yMax - position.height; + position2.y = r.yMax - position2.height; } - if (position.y < r.y) + if (position2.y < r.y) { - position.y = r.y; + position2.y = r.y; } - GUI.Label(position, content, tooltip); + GUI.Label(position2, content, tooltip); } if (Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition)) { @@ -317,7 +360,7 @@ private void PerformFrameSelected(float frameMS) num = 0f; num2 = frameMS; } - this.m_TimeArea.SetShownHRange(num - num2 * 0.1f, num + num2 * 1.1f); + this.m_TimeArea.SetShownHRangeInsideMargins(num - num2 * 0.2f, num + num2 * 1.2f); } private void HandleFrameSelected(float frameMS) { @@ -332,11 +375,10 @@ private void HandleFrameSelected(float frameMS) current.Use(); } } - private void DoProfilerFrame(int frameIndex, Rect fullRect, bool ghost, ref int threadCount, ref double startTime) + private void DoProfilerFrame(int frameIndex, Rect fullRect, bool ghost, ref int threadCount, float offset) { ProfilerFrameDataIterator profilerFrameDataIterator = new ProfilerFrameDataIterator(); int threadCount2 = profilerFrameDataIterator.GetThreadCount(frameIndex); - double frameStartS = profilerFrameDataIterator.GetFrameStartS(frameIndex); if (ghost && threadCount2 != threadCount) { return; @@ -344,7 +386,6 @@ private void DoProfilerFrame(int frameIndex, Rect fullRect, bool ghost, ref int if (!ghost) { threadCount = threadCount2; - startTime = frameStartS; } for (int i = 0; i < threadCount; i++) { @@ -357,44 +398,68 @@ private void DoProfilerFrame(int frameIndex, Rect fullRect, bool ghost, ref int this.DrawGrid(fullRect, threadCount, profilerFrameDataIterator.frameTimeMS); this.HandleFrameSelected(profilerFrameDataIterator.frameTimeMS); } - this.DrawProfilingData(profilerFrameDataIterator, r, i, (float)(frameStartS - startTime), ghost); + this.DrawProfilingData(profilerFrameDataIterator, r, i, offset, ghost); } } public void DoGUI(int frameIndex, float width, float ypos, float height) { - Rect drawRect = new Rect(0f, ypos, width, height); + Rect drawRect = new Rect(0f, ypos - 1f, width, height + 1f); + float num = 169f; + if (Event.current.type == EventType.Repaint) + { + ProfilerTimelineGUI.styles.profilerGraphBackground.Draw(drawRect, false, false, false, false); + EditorStyles.toolbar.Draw(new Rect(0f, ypos + height - 15f, num, 15f), false, false, false, false); + } + bool flag = false; if (this.m_TimeArea == null) { + flag = true; this.m_TimeArea = new ZoomableArea(); this.m_TimeArea.hRangeLocked = false; this.m_TimeArea.vRangeLocked = true; this.m_TimeArea.hSlider = true; this.m_TimeArea.vSlider = false; this.m_TimeArea.scaleWithWindow = true; - this.m_TimeArea.rect = drawRect; - this.m_TimeArea.SetShownHRangeInsideMargins(-2f, 33.3f); + this.m_TimeArea.rect = new Rect(drawRect.x + num - 1f, drawRect.y, drawRect.width - num, drawRect.height); + this.m_TimeArea.margin = 10f; this.m_TimeArea.OnEnable(); } - this.m_TimeArea.rect = drawRect; + ProfilerFrameDataIterator profilerFrameDataIterator = new ProfilerFrameDataIterator(); + profilerFrameDataIterator.SetRoot(frameIndex, 0); + this.m_TimeArea.hBaseRangeMin = 0f; + this.m_TimeArea.hBaseRangeMax = profilerFrameDataIterator.frameTimeMS; + if (flag) + { + this.PerformFrameSelected(profilerFrameDataIterator.frameTimeMS); + } + this.m_TimeArea.rect = new Rect(drawRect.x + num, drawRect.y, drawRect.width - num, drawRect.height); this.m_TimeArea.BeginViewGUI(); this.m_TimeArea.EndViewGUI(); drawRect = this.m_TimeArea.drawRect; - int num = 0; - double num2 = 0.0; - this.DoProfilerFrame(frameIndex, drawRect, false, ref num, ref num2); + this.DrawBars(drawRect, frameIndex); + GUI.BeginClip(this.m_TimeArea.drawRect); + drawRect.x = 0f; + drawRect.y = 0f; + int num2 = 0; + this.DoProfilerFrame(frameIndex, drawRect, false, ref num2, 0f); bool enabled = GUI.enabled; GUI.enabled = false; int previousFrameIndex = ProfilerDriver.GetPreviousFrameIndex(frameIndex); if (previousFrameIndex != -1) { - this.DoProfilerFrame(previousFrameIndex, drawRect, true, ref num, ref num2); + ProfilerFrameDataIterator profilerFrameDataIterator2 = new ProfilerFrameDataIterator(); + profilerFrameDataIterator2.SetRoot(previousFrameIndex, 0); + this.DoProfilerFrame(previousFrameIndex, drawRect, true, ref num2, -profilerFrameDataIterator2.frameTimeMS); } int nextFrameIndex = ProfilerDriver.GetNextFrameIndex(frameIndex); if (nextFrameIndex != -1) { - this.DoProfilerFrame(nextFrameIndex, drawRect, true, ref num, ref num2); + ProfilerFrameDataIterator profilerFrameDataIterator3 = new ProfilerFrameDataIterator(); + profilerFrameDataIterator3.SetRoot(frameIndex, 0); + this.DoProfilerFrame(nextFrameIndex, drawRect, true, ref num2, profilerFrameDataIterator3.frameTimeMS); } GUI.enabled = enabled; + GUI.EndClip(); } } } diff --git a/UnityEditor/UnityEditorInternal/ReorderableList.cs b/UnityEditor/UnityEditorInternal/ReorderableList.cs index bcfe4b2c..425de686 100644 --- a/UnityEditor/UnityEditorInternal/ReorderableList.cs +++ b/UnityEditor/UnityEditorInternal/ReorderableList.cs @@ -154,15 +154,18 @@ public void DrawHeader(Rect headerRect, SerializedObject serializedObject, Seria { EditorGUI.LabelField(headerRect, EditorGUIUtility.TempContent((element == null) ? "IList" : "Serialized Property")); } - public void DrawElementBackground(Rect rect, bool selected, bool focused, bool draggable) + public void DrawElementBackground(Rect rect, int index, bool selected, bool focused, bool draggable) { if (Event.current.type == EventType.Repaint) { this.elementBackground.Draw(rect, false, selected, selected, focused); - if (draggable) - { - this.draggingHandle.Draw(new Rect(rect.x + 5f, rect.y + 7f, 10f, rect.height - (rect.height - 7f)), false, false, false, false); - } + } + } + public void DrawElementDraggingHandle(Rect rect, int index, bool selected, bool focused, bool draggable) + { + if (Event.current.type == EventType.Repaint && draggable) + { + this.draggingHandle.Draw(new Rect(rect.x + 5f, rect.y + 7f, 10f, rect.height - (rect.height - 7f)), false, false, false, false); } } public void DrawElement(Rect rect, SerializedProperty element, object listItem, bool selected, bool focused, bool draggable) @@ -175,6 +178,7 @@ public void DrawNoneElement(Rect rect, bool draggable) } } public delegate void HeaderCallbackDelegate(Rect rect); + public delegate void FooterCallbackDelegate(Rect rect); public delegate void ElementCallbackDelegate(Rect rect, int index, bool isActive, bool isFocused); public delegate void ReorderCallbackDelegate(ReorderableList list); public delegate void SelectCallbackDelegate(ReorderableList list); @@ -184,12 +188,15 @@ public void DrawNoneElement(Rect rect, bool draggable) public delegate void ChangedCallbackDelegate(ReorderableList list); public delegate bool CanRemoveCallbackDelegate(ReorderableList list); public ReorderableList.HeaderCallbackDelegate drawHeaderCallback; + public ReorderableList.FooterCallbackDelegate drawFooterCallback; public ReorderableList.ElementCallbackDelegate drawElementCallback; + public ReorderableList.ElementCallbackDelegate drawElementBackgroundCallback; public ReorderableList.ReorderCallbackDelegate onReorderCallback; public ReorderableList.SelectCallbackDelegate onSelectCallback; public ReorderableList.AddCallbackDelegate onAddCallback; public ReorderableList.AddDropdownCallbackDelegate onAddDropdownCallback; public ReorderableList.RemoveCallbackDelegate onRemoveCallback; + public ReorderableList.SelectCallbackDelegate onMouseUpCallback; public ReorderableList.CanRemoveCallbackDelegate onCanRemoveCallback; public ReorderableList.ChangedCallbackDelegate onChangedCallback; private int m_ActiveElement = -1; @@ -210,6 +217,7 @@ public void DrawNoneElement(Rect rect, bool draggable) public float elementHeight = 21f; public float headerHeight = 18f; public float footerHeight = 13f; + public bool showDefaultBackground = true; public static ReorderableList.Defaults defaultBehaviours { get @@ -336,6 +344,10 @@ private Rect GetContentRect(Rect rect) result.xMax -= 6f; return result; } + private Rect GetRowRect(int index, Rect listRect) + { + return new Rect(listRect.x, listRect.y + (float)index * this.elementHeight, listRect.width, this.elementHeight); + } public void DoLayoutList() { if (ReorderableList.s_Defaults == null) @@ -390,12 +402,12 @@ private float GetListElementHeight() private void DoListElements(Rect listRect) { int count = this.count; - if (Event.current.type == EventType.Repaint) + if (this.showDefaultBackground && Event.current.type == EventType.Repaint) { ReorderableList.s_Defaults.boxBackground.Draw(listRect, false, false, false, false); } listRect.yMin += 2f; - listRect.yMax -= 3f; + listRect.yMax -= 5f; Rect rect = listRect; rect.height = this.elementHeight; Rect rect2 = rect; @@ -419,7 +431,15 @@ private void DoListElements(Rect listRect) { rect.y = listRect.y + (float)j * this.elementHeight; rect = this.m_SlideGroup.GetRect(this.m_NonDragTargetIndices[j], rect); - ReorderableList.s_Defaults.DrawElementBackground(rect, false, false, this.m_Draggable); + if (this.drawElementBackgroundCallback == null) + { + ReorderableList.s_Defaults.DrawElementBackground(rect, j, false, false, this.m_Draggable); + } + else + { + this.drawElementBackgroundCallback(rect, j, false, false); + } + ReorderableList.s_Defaults.DrawElementDraggingHandle(rect, j, false, false, this.m_Draggable); rect2 = this.GetContentRect(rect); if (this.drawElementCallback == null) { @@ -439,7 +459,15 @@ private void DoListElements(Rect listRect) } } rect.y = this.m_DraggedY - this.m_DragOffset + listRect.y; - ReorderableList.s_Defaults.DrawElementBackground(rect, true, true, this.m_Draggable); + if (this.drawElementBackgroundCallback == null) + { + ReorderableList.s_Defaults.DrawElementBackground(rect, this.m_ActiveElement, true, true, this.m_Draggable); + } + else + { + this.drawElementBackgroundCallback(rect, this.m_ActiveElement, true, true); + } + ReorderableList.s_Defaults.DrawElementDraggingHandle(rect, this.m_ActiveElement, true, true, this.m_Draggable); rect2 = this.GetContentRect(rect); if (this.drawElementCallback == null) { @@ -462,9 +490,17 @@ private void DoListElements(Rect listRect) for (int k = 0; k < count; k++) { bool flag = k == this.m_ActiveElement; - bool flag2 = k == this.m_ActiveElement && GUIUtility.keyboardControl == this.id; + bool flag2 = k == this.m_ActiveElement && this.HasKeyboardControl(); rect.y = listRect.y + (float)k * this.elementHeight; - ReorderableList.s_Defaults.DrawElementBackground(rect, flag, flag2, this.m_Draggable); + if (this.drawElementBackgroundCallback == null) + { + ReorderableList.s_Defaults.DrawElementBackground(rect, k, flag, flag2, this.m_Draggable); + } + else + { + this.drawElementBackgroundCallback(rect, k, flag, flag2); + } + ReorderableList.s_Defaults.DrawElementDraggingHandle(rect, k, flag, flag2, this.m_Draggable); rect2 = this.GetContentRect(rect); if (this.drawElementCallback == null) { @@ -488,7 +524,15 @@ private void DoListElements(Rect listRect) else { rect.y = listRect.y; - ReorderableList.s_Defaults.DrawElementBackground(rect, false, false, false); + if (this.drawElementBackgroundCallback == null) + { + ReorderableList.s_Defaults.DrawElementBackground(rect, -1, false, false, false); + } + else + { + this.drawElementBackgroundCallback(rect, -1, false, false); + } + ReorderableList.s_Defaults.DrawElementDraggingHandle(rect, -1, false, false, false); rect2 = rect; rect2.xMin += 6f; rect2.xMax -= 6f; @@ -497,7 +541,7 @@ private void DoListElements(Rect listRect) } private void DoListHeader(Rect headerRect) { - if (Event.current.type == EventType.Repaint) + if (this.showDefaultBackground && Event.current.type == EventType.Repaint) { ReorderableList.s_Defaults.DrawHeaderBackground(headerRect); } @@ -505,33 +549,41 @@ private void DoListHeader(Rect headerRect) headerRect.xMax -= 6f; headerRect.height -= 2f; headerRect.y += 1f; - if (this.drawHeaderCallback == null && this.m_DisplayHeader) + if (this.drawHeaderCallback != null) { - ReorderableList.s_Defaults.DrawHeader(headerRect, this.m_SerializedObject, this.m_Elements, this.m_ElementList); + this.drawHeaderCallback(headerRect); } else { - if (this.drawHeaderCallback != null) + if (this.m_DisplayHeader) { - this.drawHeaderCallback(headerRect); + ReorderableList.s_Defaults.DrawHeader(headerRect, this.m_SerializedObject, this.m_Elements, this.m_ElementList); } } } private void DoListFooter(Rect footerRect) { - if (this.displayAdd || this.displayRemove) + if (this.drawFooterCallback != null) { - ReorderableList.s_Defaults.DrawFooter(footerRect, this); + this.drawFooterCallback(footerRect); + } + else + { + if (this.displayAdd || this.displayRemove) + { + ReorderableList.s_Defaults.DrawFooter(footerRect, this); + } } } private void DoDraggingAndSelection(Rect listRect) { Event current = Event.current; int activeElement = this.m_ActiveElement; + bool flag = false; switch (current.GetTypeForControl(this.id)) { case EventType.MouseDown: - if (listRect.Contains(Event.current.mousePosition)) + if (listRect.Contains(Event.current.mousePosition) && Event.current.button == 0) { EditorGUI.EndEditingActiveTextField(); this.m_ActiveElement = Mathf.FloorToInt((Event.current.mousePosition.y - listRect.y) / this.elementHeight); @@ -540,67 +592,85 @@ private void DoDraggingAndSelection(Rect listRect) this.m_DragOffset = Event.current.mousePosition.y - listRect.y - (float)this.m_ActiveElement * this.elementHeight; this.UpdateDraggedY(listRect); GUIUtility.hotControl = this.id; - this.m_Dragging = true; this.m_SlideGroup.Reset(); this.m_NonDragTargetIndices = new List(); } - GUIUtility.keyboardControl = this.id; + this.GrabKeyboardFocus(); current.Use(); + flag = true; } break; case EventType.MouseUp: - if (this.m_Draggable && GUIUtility.hotControl == this.id) + if (!this.m_Draggable) { - current.Use(); - this.m_Dragging = false; - int num = this.CalculateRowIndex(); - if (this.m_ActiveElement != num) + if (this.onMouseUpCallback != null && this.IsMouseInsideActiveElement(listRect)) { - if (this.m_SerializedObject != null && this.m_Elements != null) - { - this.m_Elements.MoveArrayElement(this.m_ActiveElement, num); - this.m_SerializedObject.ApplyModifiedProperties(); - this.m_SerializedObject.Update(); - } - else + this.onMouseUpCallback(this); + } + } + else + { + if (GUIUtility.hotControl == this.id) + { + current.Use(); + this.m_Dragging = false; + int num = this.CalculateRowIndex(); + if (this.m_ActiveElement != num) { - if (this.m_ElementList != null) + if (this.m_SerializedObject != null && this.m_Elements != null) + { + this.m_Elements.MoveArrayElement(this.m_ActiveElement, num); + this.m_SerializedObject.ApplyModifiedProperties(); + this.m_SerializedObject.Update(); + } + else { - object value = this.m_ElementList[this.m_ActiveElement]; - for (int i = 0; i < this.m_ElementList.Count - 1; i++) + if (this.m_ElementList != null) { - if (i >= this.m_ActiveElement) + object value = this.m_ElementList[this.m_ActiveElement]; + for (int i = 0; i < this.m_ElementList.Count - 1; i++) { - this.m_ElementList[i] = this.m_ElementList[i + 1]; + if (i >= this.m_ActiveElement) + { + this.m_ElementList[i] = this.m_ElementList[i + 1]; + } } - } - for (int j = this.m_ElementList.Count - 1; j > 0; j--) - { - if (j > num) + for (int j = this.m_ElementList.Count - 1; j > 0; j--) { - this.m_ElementList[j] = this.m_ElementList[j - 1]; + if (j > num) + { + this.m_ElementList[j] = this.m_ElementList[j - 1]; + } } + this.m_ElementList[num] = value; } - this.m_ElementList[num] = value; + } + this.m_ActiveElement = num; + if (this.onReorderCallback != null) + { + this.onReorderCallback(this); + } + if (this.onChangedCallback != null) + { + this.onChangedCallback(this); } } - this.m_ActiveElement = num; - if (this.onReorderCallback != null) - { - this.onReorderCallback(this); - } - if (this.onChangedCallback != null) + else { - this.onChangedCallback(this); + if (this.onMouseUpCallback != null) + { + this.onMouseUpCallback(this); + } } + GUIUtility.hotControl = 0; + this.m_NonDragTargetIndices = null; } - GUIUtility.hotControl = 0; - this.m_NonDragTargetIndices = null; } break; case EventType.MouseDrag: if (this.m_Draggable && GUIUtility.hotControl == this.id) { + this.m_Dragging = true; this.UpdateDraggedY(listRect); current.Use(); } @@ -629,23 +699,46 @@ private void DoDraggingAndSelection(Rect listRect) this.m_ActiveElement = Mathf.Clamp(this.m_ActiveElement, 0, (this.m_Elements == null) ? (this.m_ElementList.Count - 1) : (this.m_Elements.arraySize - 1)); break; } - if (this.m_ActiveElement != activeElement && this.onSelectCallback != null) + if ((this.m_ActiveElement != activeElement || flag) && this.onSelectCallback != null) { this.onSelectCallback(this); } } + private bool IsMouseInsideActiveElement(Rect listRect) + { + int rowIndex = this.GetRowIndex(Event.current.mousePosition.y - listRect.y); + return rowIndex == this.m_ActiveElement && this.GetRowRect(rowIndex, listRect).Contains(Event.current.mousePosition); + } private void UpdateDraggedY(Rect listRect) { this.m_DraggedY = Mathf.Clamp(Event.current.mousePosition.y - listRect.y, this.m_DragOffset, listRect.height - (this.elementHeight - this.m_DragOffset)); } private int CalculateRowIndex() { - int num = (this.m_Elements == null) ? this.m_ElementList.Count : this.m_Elements.arraySize; - return Mathf.Clamp(Mathf.FloorToInt(this.m_DraggedY / this.elementHeight), 0, num - 1); + return this.GetRowIndex(this.m_DraggedY); + } + private int GetRowIndex(float localY) + { + return Mathf.Clamp(Mathf.FloorToInt(localY / this.elementHeight), 0, this.count - 1); } private bool IsDragging() { return this.m_Dragging; } + public void GrabKeyboardFocus() + { + GUIUtility.keyboardControl = this.id; + } + public void ReleaseKeyboardFocus() + { + if (GUIUtility.keyboardControl == this.id) + { + GUIUtility.keyboardControl = 0; + } + } + public bool HasKeyboardControl() + { + return GUIUtility.keyboardControl == this.id; + } } } diff --git a/UnityEditor/UnityEditorInternal/ReorderableListWithRenameAndScrollView.cs b/UnityEditor/UnityEditorInternal/ReorderableListWithRenameAndScrollView.cs new file mode 100644 index 00000000..3c16bdd7 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ReorderableListWithRenameAndScrollView.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +namespace UnityEditorInternal +{ + internal class ReorderableListWithRenameAndScrollView + { + [Serializable] + public class State + { + public Vector2 m_ScrollPos = new Vector2(0f, 0f); + public RenameOverlay m_RenameOverlay = new RenameOverlay(); + } + public class Styles + { + public GUIStyle reorderableListLabel = new GUIStyle("PR Label"); + public GUIStyle reorderableListLabelRightAligned; + public Styles() + { + Texture2D background = this.reorderableListLabel.hover.background; + this.reorderableListLabel.normal.background = background; + this.reorderableListLabel.active.background = background; + this.reorderableListLabel.focused.background = background; + this.reorderableListLabel.onNormal.background = background; + this.reorderableListLabel.onHover.background = background; + this.reorderableListLabel.onActive.background = background; + this.reorderableListLabel.onFocused.background = background; + RectOffset arg_C2_0 = this.reorderableListLabel.padding; + int num = 0; + this.reorderableListLabel.padding.right = num; + arg_C2_0.left = num; + this.reorderableListLabel.alignment = TextAnchor.MiddleLeft; + this.reorderableListLabelRightAligned = new GUIStyle(this.reorderableListLabel); + this.reorderableListLabelRightAligned.alignment = TextAnchor.MiddleRight; + this.reorderableListLabelRightAligned.clipping = TextClipping.Overflow; + } + } + private ReorderableList m_ReorderableList; + private ReorderableListWithRenameAndScrollView.State m_State; + private int m_LastSelectedIndex = -1; + private bool m_HadKeyFocusAtMouseDown; + private int m_FrameIndex = -1; + public GUIStyle listElementStyle; + public GUIStyle renameOverlayStyle; + public Func onGetNameAtIndex; + public Action onNameChangedAtIndex; + public Action onSelectionChanged; + public Action onDeleteItemAtIndex; + public ReorderableList.ElementCallbackDelegate onCustomDrawElement; + private static ReorderableListWithRenameAndScrollView.Styles s_Styles; + public ReorderableList list + { + get + { + return this.m_ReorderableList; + } + } + public GUIStyle elementStyle + { + get + { + return this.listElementStyle ?? ReorderableListWithRenameAndScrollView.s_Styles.reorderableListLabel; + } + } + public GUIStyle elementStyleRightAligned + { + get + { + return ReorderableListWithRenameAndScrollView.s_Styles.reorderableListLabelRightAligned; + } + } + public ReorderableListWithRenameAndScrollView(ReorderableList list, ReorderableListWithRenameAndScrollView.State state) + { + this.m_State = state; + this.m_ReorderableList = list; + ReorderableList expr_28 = this.m_ReorderableList; + expr_28.drawElementCallback = (ReorderableList.ElementCallbackDelegate)Delegate.Combine(expr_28.drawElementCallback, new ReorderableList.ElementCallbackDelegate(this.DrawElement)); + ReorderableList expr_4F = this.m_ReorderableList; + expr_4F.onSelectCallback = (ReorderableList.SelectCallbackDelegate)Delegate.Combine(expr_4F.onSelectCallback, new ReorderableList.SelectCallbackDelegate(this.SelectCallback)); + ReorderableList expr_76 = this.m_ReorderableList; + expr_76.onMouseUpCallback = (ReorderableList.SelectCallbackDelegate)Delegate.Combine(expr_76.onMouseUpCallback, new ReorderableList.SelectCallbackDelegate(this.MouseUpCallback)); + ReorderableList expr_9D = this.m_ReorderableList; + expr_9D.onReorderCallback = (ReorderableList.ReorderCallbackDelegate)Delegate.Combine(expr_9D.onReorderCallback, new ReorderableList.ReorderCallbackDelegate(this.ReorderCallback)); + } + private RenameOverlay GetRenameOverlay() + { + return this.m_State.m_RenameOverlay; + } + public void OnEvent() + { + this.GetRenameOverlay().OnEvent(); + } + private void EnsureRowIsVisible(int index, float scrollGUIHeight) + { + if (index < 0) + { + return; + } + float num = this.m_ReorderableList.elementHeight * (float)index + 2f; + float min = num - scrollGUIHeight + this.m_ReorderableList.elementHeight + 3f; + this.m_State.m_ScrollPos.y = Mathf.Clamp(this.m_State.m_ScrollPos.y, min, num); + } + public void OnGUI(Rect rect) + { + if (ReorderableListWithRenameAndScrollView.s_Styles == null) + { + ReorderableListWithRenameAndScrollView.s_Styles = new ReorderableListWithRenameAndScrollView.Styles(); + } + if (this.onGetNameAtIndex == null) + { + Debug.LogError("Ensure to set: 'onGetNameAtIndex'"); + } + Event current = Event.current; + if (current.type == EventType.MouseDown && rect.Contains(current.mousePosition)) + { + this.m_HadKeyFocusAtMouseDown = this.m_ReorderableList.HasKeyboardControl(); + } + if (this.m_FrameIndex != -1) + { + this.EnsureRowIsVisible(this.m_FrameIndex, rect.height); + this.m_FrameIndex = -1; + } + GUILayout.BeginArea(rect); + this.m_State.m_ScrollPos = GUILayout.BeginScrollView(this.m_State.m_ScrollPos, new GUILayoutOption[0]); + this.m_ReorderableList.DoLayoutList(); + GUILayout.EndScrollView(); + GUILayout.EndArea(); + AudioMixerDrawUtils.DrawScrollDropShadow(rect, this.m_State.m_ScrollPos.y, this.m_ReorderableList.GetHeight()); + this.KeyboardHandling(); + this.CommandHandling(); + } + public bool IsRenamingIndex(int index) + { + return this.GetRenameOverlay().IsRenaming() && this.GetRenameOverlay().userData == index && !this.GetRenameOverlay().isWaitingForDelay; + } + public void DrawElement(Rect r, int index, bool isActive, bool isFocused) + { + if (this.IsRenamingIndex(index)) + { + if (r.width >= 0f && r.height >= 0f) + { + r.x -= 2f; + this.GetRenameOverlay().editFieldRect = r; + } + this.DoRenameOverlay(); + } + else + { + if (this.onCustomDrawElement != null) + { + this.onCustomDrawElement(r, index, isActive, isFocused); + } + else + { + this.DrawElementText(r, index, isActive, index == this.m_ReorderableList.index, isFocused); + } + } + } + public void DrawElementText(Rect r, int index, bool isActive, bool isSelected, bool isFocused) + { + if (Event.current.type == EventType.Repaint && this.onGetNameAtIndex != null) + { + this.elementStyle.Draw(r, this.onGetNameAtIndex(index), false, false, isSelected, true); + } + } + public virtual void DoRenameOverlay() + { + if (this.GetRenameOverlay().IsRenaming() && !this.GetRenameOverlay().OnGUI()) + { + this.RenameEnded(); + } + } + public void BeginRename(int index, float delay) + { + this.GetRenameOverlay().BeginRename(this.onGetNameAtIndex(index), index, delay); + this.m_ReorderableList.index = index; + this.m_LastSelectedIndex = index; + this.FrameItem(index); + } + private void RenameEnded() + { + if (this.GetRenameOverlay().userAcceptedRename && this.onNameChangedAtIndex != null) + { + string arg = (!string.IsNullOrEmpty(this.GetRenameOverlay().name)) ? this.GetRenameOverlay().name : this.GetRenameOverlay().originalName; + int userData = this.GetRenameOverlay().userData; + this.onNameChangedAtIndex(userData, arg); + } + if (this.GetRenameOverlay().HasKeyboardFocus()) + { + this.m_ReorderableList.GrabKeyboardFocus(); + } + this.GetRenameOverlay().Clear(); + } + public void EndRename(bool acceptChanges) + { + if (this.GetRenameOverlay().IsRenaming()) + { + this.GetRenameOverlay().EndRename(acceptChanges); + this.RenameEnded(); + } + } + public void ReorderCallback(ReorderableList list) + { + this.m_LastSelectedIndex = list.index; + } + public void MouseUpCallback(ReorderableList list) + { + if (this.m_HadKeyFocusAtMouseDown && list.index == this.m_LastSelectedIndex) + { + this.BeginRename(list.index, 0.5f); + } + this.m_LastSelectedIndex = list.index; + } + public void SelectCallback(ReorderableList list) + { + this.FrameItem(list.index); + if (this.onSelectionChanged != null) + { + this.onSelectionChanged(list.index); + } + } + private void RemoveSelected() + { + if (this.m_ReorderableList.index < 0 || this.m_ReorderableList.index >= this.m_ReorderableList.count) + { + Debug.Log("Invalid index to remove " + this.m_ReorderableList.index); + return; + } + if (this.onDeleteItemAtIndex != null) + { + this.onDeleteItemAtIndex(this.m_ReorderableList.index); + } + } + public void FrameItem(int index) + { + this.m_FrameIndex = index; + } + private bool CanBeginRename() + { + return !this.GetRenameOverlay().IsRenaming() && this.m_ReorderableList.index >= 0; + } + private void CommandHandling() + { + Event current = Event.current; + if (Event.current.type == EventType.ExecuteCommand) + { + string commandName = current.commandName; + if (commandName != null) + { + if (ReorderableListWithRenameAndScrollView.<>f__switch$map12 == null) + { + ReorderableListWithRenameAndScrollView.<>f__switch$map12 = new Dictionary(1) + { + + { + "OnLostFocus", + 0 + } + }; + } + int num; + if (ReorderableListWithRenameAndScrollView.<>f__switch$map12.TryGetValue(commandName, out num)) + { + if (num == 0) + { + this.EndRename(true); + current.Use(); + } + } + } + } + } + private void KeyboardHandling() + { + Event current = Event.current; + if (current.type != EventType.KeyDown) + { + return; + } + if (this.m_ReorderableList.HasKeyboardControl()) + { + KeyCode keyCode = Event.current.keyCode; + switch (keyCode) + { + case KeyCode.Home: + current.Use(); + this.m_ReorderableList.index = 0; + this.FrameItem(this.m_ReorderableList.index); + return; + case KeyCode.End: + current.Use(); + this.m_ReorderableList.index = this.m_ReorderableList.count - 1; + this.FrameItem(this.m_ReorderableList.index); + return; + case KeyCode.PageUp: + case KeyCode.PageDown: + case KeyCode.F1: + IL_52: + if (keyCode != KeyCode.Return) + { + if (keyCode == KeyCode.Delete) + { + this.RemoveSelected(); + current.Use(); + return; + } + if (keyCode != KeyCode.KeypadEnter) + { + return; + } + } + if (this.CanBeginRename() && Application.platform == RuntimePlatform.OSXEditor) + { + this.BeginRename(this.m_ReorderableList.index, 0f); + current.Use(); + } + return; + case KeyCode.F2: + if (this.CanBeginRename() && Application.platform == RuntimePlatform.WindowsEditor) + { + this.BeginRename(this.m_ReorderableList.index, 0f); + current.Use(); + } + return; + } + goto IL_52; + } + } + } +} diff --git a/UnityEditor/UnityEditorInternal/ScriptUpdatingManager.cs b/UnityEditor/UnityEditorInternal/ScriptUpdatingManager.cs new file mode 100644 index 00000000..103ce543 --- /dev/null +++ b/UnityEditor/UnityEditorInternal/ScriptUpdatingManager.cs @@ -0,0 +1,21 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEditorInternal +{ + public sealed class ScriptUpdatingManager + { + public static extern int numberOfTimesAsked + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool WaitForVCSServerConnection(bool reportTimeout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ReportExpectedUpdateFailure(); + } +} diff --git a/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs b/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs index 31395b94..48ea947f 100644 --- a/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs +++ b/UnityEditor/UnityEditorInternal/SpriteEditorUtility.cs @@ -116,7 +116,7 @@ public static void DrawLine(Vector3 p1, Vector3 p2) } public static void BeginLines(Color color) { - HandleUtility.handleWireMaterial.SetPass(0); + HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(1); diff --git a/UnityEditor/UnityEditorInternal/State.cs b/UnityEditor/UnityEditorInternal/State.cs index 451bba37..32edf88f 100644 --- a/UnityEditor/UnityEditorInternal/State.cs +++ b/UnityEditor/UnityEditorInternal/State.cs @@ -1,140 +1,9 @@ using System; -using System.Runtime.CompilerServices; using UnityEngine; -using UnityEngine.Internal; namespace UnityEditorInternal { - public sealed class State : UnityEngine.Object + [Obsolete("State is obsolete. Use UnityEditor.Animations.AnimatorState instead (UnityUpgradable).", true)] + public class State : UnityEngine.Object { - public extern string uniqueName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int uniqueNameHash - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern float speed - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool mirror - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool iKOnFeet - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string tag - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern StateMachine stateMachine - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public Vector3 position - { - get - { - Vector3 result; - this.INTERNAL_get_position(out result); - return result; - } - set - { - this.INTERNAL_set_position(ref value); - } - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_position(out Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_position(ref Vector3 value); - [ExcludeFromDocs] - public Motion GetMotion() - { - AnimatorControllerLayer layer = null; - return this.GetMotion(layer); - } - public Motion GetMotion([DefaultValue("null")] AnimatorControllerLayer layer) - { - return this.GetMotionInternal((layer == null) ? 0 : layer.motionSetIndex); - } - [ExcludeFromDocs] - public void SetAnimationClip(AnimationClip clip) - { - AnimatorControllerLayer layer = null; - this.SetAnimationClip(clip, layer); - } - public void SetAnimationClip(AnimationClip clip, [DefaultValue("null")] AnimatorControllerLayer layer) - { - this.SetMotionInternal(clip, (layer == null) ? 0 : layer.motionSetIndex); - } - [ExcludeFromDocs] - public BlendTree CreateBlendTree() - { - AnimatorControllerLayer layer = null; - return this.CreateBlendTree(layer); - } - public BlendTree CreateBlendTree([DefaultValue("null")] AnimatorControllerLayer layer) - { - return this.CreateBlendTreeInternal((layer == null) ? 0 : layer.motionSetIndex); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetMotionInternal(Motion motion, [DefaultValue("0")] int motionSetIndex); - [ExcludeFromDocs] - internal void SetMotionInternal(Motion motion) - { - int motionSetIndex = 0; - this.SetMotionInternal(motion, motionSetIndex); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern Motion GetMotionInternal([DefaultValue("0")] int motionSetIndex); - [ExcludeFromDocs] - internal Motion GetMotionInternal() - { - int motionSetIndex = 0; - return this.GetMotionInternal(motionSetIndex); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern BlendTree CreateBlendTreeInternal([DefaultValue("0")] int motionSetIndex); - [ExcludeFromDocs] - internal BlendTree CreateBlendTreeInternal() - { - int motionSetIndex = 0; - return this.CreateBlendTreeInternal(motionSetIndex); - } } } diff --git a/UnityEditor/UnityEditorInternal/StateMachine.cs b/UnityEditor/UnityEditorInternal/StateMachine.cs index 7aaae419..f44a96ff 100644 --- a/UnityEditor/UnityEditorInternal/StateMachine.cs +++ b/UnityEditor/UnityEditorInternal/StateMachine.cs @@ -1,280 +1,9 @@ -using NUnit.Framework; using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using UnityEditor; using UnityEngine; namespace UnityEditorInternal { - public sealed class StateMachine : UnityEngine.Object + [Obsolete("StateMachine is obsolete. Use UnityEditor.Animations.AnimatorStateMachine instead (UnityUpgradable).", true)] + public class StateMachine : UnityEngine.Object { - internal IEnumerable states - { - get - { - State[] array = new State[this.stateCount]; - for (int i = 0; i < this.stateCount; i++) - { - array[i] = this.GetState(i); - } - return array; - } - } - internal List statesRecursive - { - get - { - List list = new List(); - list.AddRange(this.states); - for (int i = 0; i < this.stateMachineCount; i++) - { - list.AddRange(this.GetStateMachine(i).statesRecursive); - } - return list; - } - } - internal IEnumerable stateMachines - { - get - { - StateMachine[] array = new StateMachine[this.stateMachineCount]; - for (int i = 0; i < this.stateMachineCount; i++) - { - array[i] = this.GetStateMachine(i); - } - return array; - } - } - internal List stateMachinesRecursive - { - get - { - List list = new List(); - list.AddRange(this.stateMachines); - for (int i = 0; i < this.stateMachineCount; i++) - { - list.AddRange(this.GetStateMachine(i).stateMachinesRecursive); - } - return list; - } - } - internal List transitions - { - get - { - List statesRecursive = this.statesRecursive; - List list = new List(); - foreach (State current in statesRecursive) - { - list.AddRange(this.GetTransitionsFromState(current)); - } - list.AddRange(this.GetTransitionsFromState(null)); - return list; - } - } - public extern int stateCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int stateMachineCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern State defaultState - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public Vector3 anyStatePosition - { - get - { - Vector3 result; - this.INTERNAL_get_anyStatePosition(out result); - return result; - } - set - { - this.INTERNAL_set_anyStatePosition(ref value); - } - } - public Vector3 parentStateMachinePosition - { - get - { - Vector3 result; - this.INTERNAL_get_parentStateMachinePosition(out result); - return result; - } - set - { - this.INTERNAL_set_parentStateMachinePosition(ref value); - } - } - public extern int motionSetCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - internal extern int transitionCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - internal Vector3 GetStateMachinePosition(StateMachine stateMachine) - { - for (int i = 0; i < this.stateMachineCount; i++) - { - if (stateMachine == this.GetStateMachine(i)) - { - return this.GetStateMachinePosition(i); - } - } - Assert.Fail(string.Concat(new string[] - { - "Can't find state machine (", - stateMachine.name, - ") in parent state machine (", - base.name, - ")." - })); - return Vector3.zero; - } - internal void SetStateMachinePosition(StateMachine stateMachine, Vector3 position) - { - for (int i = 0; i < this.stateMachineCount; i++) - { - if (stateMachine == this.GetStateMachine(i)) - { - this.SetStateMachinePosition(i, position); - return; - } - } - Assert.Fail(string.Concat(new string[] - { - "Can't find state machine (", - stateMachine.name, - ") in parent state machine (", - base.name, - ")." - })); - } - internal State CreateState(Vector3 position) - { - Undo.RegisterCompleteObjectUndo(this, "State added"); - State state = this.AddState("New State"); - state.position = position; - return state; - } - internal State FindState(string stateUniqueName) - { - return this.statesRecursive.Find((State s) => s.uniqueName == stateUniqueName); - } - internal State FindState(int stateUniqueNameHash) - { - return this.statesRecursive.Find((State s) => s.uniqueNameHash == stateUniqueNameHash); - } - internal Transition FindTransition(string transitionUniqueName) - { - return this.transitions.Find((Transition t) => t.uniqueName == transitionUniqueName); - } - internal Transition FindTransition(int transitionUniqueName) - { - return this.transitions.Find((Transition t) => t.uniqueNameHash == transitionUniqueName); - } - internal bool HasState(State state) - { - return this.statesRecursive.Any((State s) => s == state); - } - internal bool IsDirectParent(StateMachine stateMachine) - { - return this.stateMachines.Any((StateMachine sm) => sm == stateMachine); - } - internal bool HasStateMachine(StateMachine child) - { - return this.stateMachinesRecursive.Any((StateMachine sm) => sm == child); - } - internal bool HasTransition(State stateA, State stateB) - { - return this.GetTransitionsFromState(stateA).Any((Transition t) => t.dstState == stateB) || this.GetTransitionsFromState(stateB).Any((Transition t) => t.dstState == stateA); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern State GetState(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern State AddState(string stateName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void RemoveState(State state); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern StateMachine GetStateMachine(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern StateMachine AddStateMachine(string stateMachineName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void RemoveStateMachine(StateMachine stateMachine); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Transition AddTransition(State src, State dst); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Transition AddAnyStateTransition(State dst); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void RemoveTransition(Transition transition); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_anyStatePosition(out Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_anyStatePosition(ref Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_parentStateMachinePosition(out Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_parentStateMachinePosition(ref Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Vector3 GetStateMachinePosition(int i); - public void SetStateMachinePosition(int i, Vector3 pos) - { - StateMachine.INTERNAL_CALL_SetStateMachinePosition(this, i, ref pos); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetStateMachinePosition(StateMachine self, int i, ref Vector3 pos); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Transition[] GetTransitionsFromState(State srcState); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void MoveState(State state, StateMachine target); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void MoveStateMachine(StateMachine stateMachine, StateMachine target); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool HasState(State state, bool recursive); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool HasStateMachine(StateMachine state, bool recursive); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetTransitionsFromState(State srcState, Transition[] transitions); } } diff --git a/UnityEditor/UnityEditorInternal/Transition.cs b/UnityEditor/UnityEditorInternal/Transition.cs index b32f4567..8982e450 100644 --- a/UnityEditor/UnityEditorInternal/Transition.cs +++ b/UnityEditor/UnityEditorInternal/Transition.cs @@ -1,162 +1,9 @@ using System; -using System.Runtime.CompilerServices; -using UnityEditor; using UnityEngine; namespace UnityEditorInternal { - public sealed class Transition : UnityEngine.Object + [Obsolete("Transition is obsolete. Use UnityEditor.Animations.AnimatorTransition instead (UnityUpgradable).", true)] + public class Transition : UnityEngine.Object { - internal delegate void RemovedCondition(int index); - private static readonly GUIContent s_TransitionTempContent = new GUIContent(); - internal Transition.RemovedCondition onRemovedCondition; - public extern string uniqueName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int uniqueNameHash - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int conditionCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern float duration - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float offset - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool atomic - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool solo - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool mute - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool canTransitionToSelf - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern State srcState - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern State dstState - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - internal extern string shortDisplayName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public GUIContent GetTransitionContentForRect(Rect rect) - { - Transition.s_TransitionTempContent.text = this.uniqueName; - if (EditorStyles.label.CalcSize(Transition.s_TransitionTempContent).x > rect.width) - { - Transition.s_TransitionTempContent.text = this.shortDisplayName; - } - return Transition.s_TransitionTempContent; - } - public AnimatorCondition GetCondition(int index) - { - return (!this.ValidateConditionIndex(index)) ? null : new AnimatorCondition(this, index); - } - public AnimatorCondition AddCondition() - { - this.AddConditionInternal(); - return this.GetCondition(this.conditionCount - 1); - } - public void RemoveCondition(int index) - { - if (this.onRemovedCondition != null) - { - this.onRemovedCondition(index); - } - this.RemoveConditionInternal(index); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void AddConditionInternal(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void RemoveConditionInternal(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool ValidateConditionIndex(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern TransitionConditionMode GetConditionMode(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetConditionMode(int index, TransitionConditionMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern string GetConditionParameter(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetConditionParameter(int index, string eventName); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetParameterTreshold(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetParameterTreshold(int index, float threshold); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern float GetExitTime(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void SetExitTime(int index, float exit); } } diff --git a/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs b/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs deleted file mode 100644 index 05c3da40..00000000 --- a/UnityEditor/UnityEditorInternal/TransitionConditionMode.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -namespace UnityEditorInternal -{ - public enum TransitionConditionMode - { - If = 1, - IfNot, - Greater, - Less, - ExitTime, - Equals, - NotEqual - } -} diff --git a/UnityEditor/UnityEngine/NScreenBridge.cs b/UnityEditor/UnityEngine/NScreenBridge.cs new file mode 100644 index 00000000..0611b975 --- /dev/null +++ b/UnityEditor/UnityEngine/NScreenBridge.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class NScreenBridge : Object + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern NScreenBridge(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void InitServer(int id); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Update(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void StartWatchdogForPid(int pid); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetResolution(int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetInput(int x, int y, int button, int key, int type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ResetInput(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Texture2D GetScreenTexture(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Shutdown(); + } +} diff --git a/UnityEditor/UnityEngine/RuntimeInitializeClassInfo.cs b/UnityEditor/UnityEngine/RuntimeInitializeClassInfo.cs new file mode 100644 index 00000000..d4d4453f --- /dev/null +++ b/UnityEditor/UnityEngine/RuntimeInitializeClassInfo.cs @@ -0,0 +1,45 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + internal sealed class RuntimeInitializeClassInfo + { + private string m_AssemblyName; + private string m_ClassName; + private string[] m_MethodNames; + internal string assemblyName + { + get + { + return this.m_AssemblyName; + } + set + { + this.m_AssemblyName = value; + } + } + internal string className + { + get + { + return this.m_ClassName; + } + set + { + this.m_ClassName = value; + } + } + internal string[] methodNames + { + get + { + return this.m_MethodNames; + } + set + { + this.m_MethodNames = value; + } + } + } +} diff --git a/UnityEditor/UnityEngine/RuntimeInitializeMethodInfo.cs b/UnityEditor/UnityEngine/RuntimeInitializeMethodInfo.cs new file mode 100644 index 00000000..6627d7cb --- /dev/null +++ b/UnityEditor/UnityEngine/RuntimeInitializeMethodInfo.cs @@ -0,0 +1,57 @@ +using System; +using System.Runtime.InteropServices; +namespace UnityEngine +{ + [StructLayout(LayoutKind.Sequential)] + internal sealed class RuntimeInitializeMethodInfo + { + private string m_FullClassName; + private string m_MethodName; + private int m_OrderNumber; + private bool m_IsUnityClass; + internal string fullClassName + { + get + { + return this.m_FullClassName; + } + set + { + this.m_FullClassName = value; + } + } + internal string methodName + { + get + { + return this.m_MethodName; + } + set + { + this.m_MethodName = value; + } + } + internal int orderNumber + { + get + { + return this.m_OrderNumber; + } + set + { + this.m_OrderNumber = value; + } + } + internal bool isUnityClass + { + get + { + return this.m_IsUnityClass; + } + set + { + this.m_IsUnityClass = value; + } + } + } +} diff --git a/UnityEditor/UnityEngine/RuntimeInitializeOnLoadManager.cs b/UnityEditor/UnityEngine/RuntimeInitializeOnLoadManager.cs new file mode 100644 index 00000000..6d3197b7 --- /dev/null +++ b/UnityEditor/UnityEngine/RuntimeInitializeOnLoadManager.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class RuntimeInitializeOnLoadManager + { + internal static extern string[] dontStripClassNames + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal static extern RuntimeInitializeMethodInfo[] methodInfos + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateMethodExecutionOrders(int[] changedIndices, int[] changedOrder); + } +} diff --git a/UnityEditor/WindowsDesktopStandalonePostProcessor.cs b/UnityEditor/WindowsDesktopStandalonePostProcessor.cs deleted file mode 100644 index 2317dc62..00000000 --- a/UnityEditor/WindowsDesktopStandalonePostProcessor.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System; -using System.IO; -using UnityEditor; -using UnityEditor.Modules; -using UnityEditor.WindowsStandalone; -using UnityEditorInternal; -internal class WindowsDesktopStandalonePostProcessor : DesktopStandalonePostProcessor -{ - protected override string DestinationFolderForInstallingIntoBuildsFolder - { - get - { - string str = (!base.Development) ? "win32_nondevelopment" : "win32_development"; - return "build/WindowsStandaloneSupport/Variations/" + str + "/Data"; - } - } - private string FullDataFolderPath - { - get - { - return Path.Combine(base.DestinationFolder, this.DestinationFileWithoutExtension + "_Data"); - } - } - private string DestinationFileWithoutExtension - { - get - { - return FileUtil.UnityGetFileNameWithoutExtension(this.FullPathToExe); - } - } - private string FullPathToExe - { - get - { - return this.m_PostProcessArgs.installPath; - } - } - protected override string StagingAreaPluginsFolder - { - get - { - return base.StagingArea + "/Data/Plugins"; - } - } - public WindowsDesktopStandalonePostProcessor(BuildPostProcessArgs postProcessArgs) : base(postProcessArgs) - { - } - protected override void RenameFilesInStagingArea() - { - string fileName = Path.GetFileName(this.m_PostProcessArgs.installPath); - FileUtil.MoveFileOrDirectory(base.StagingArea + "/player_win.exe", base.StagingArea + "/" + fileName); - FileUtil.MoveFileOrDirectory(base.StagingArea + "/Data", base.StagingArea + "/" + Path.GetFileNameWithoutExtension(fileName) + "_Data"); - } - protected override void DeleteDestination() - { - FileUtil.DeleteFileOrDirectory(this.FullPathToExe); - FileUtil.DeleteFileOrDirectory(this.FullDataFolderPath); - FileUtil.DeleteFileOrDirectory(Path.Combine(base.DestinationFolder, "UnityPlayer_Symbols.pdb")); - } - protected override string GetVariationName() - { - if (this.m_PostProcessArgs.target == BuildTarget.StandaloneGLESEmu) - { - return "glesemulator"; - } - return base.GetVariationName(); - } - protected override string PlatformStringFor(BuildTarget target) - { - if (target == BuildTarget.StandaloneWindows) - { - return "win32"; - } - if (target != BuildTarget.StandaloneWindows64) - { - throw new ArgumentException("Unexpected target: " + target); - } - return "win64"; - } - protected override IIl2CppPlatformProvider GetPlatformProvider(BuildTarget target) - { - if (target != BuildTarget.StandaloneWindows && target != BuildTarget.StandaloneWindows64) - { - throw new Exception("Build target not supported."); - } - return new WindowsStandaloneIl2CppPlatformProvider(target, base.DataFolder, base.Development); - } -} diff --git a/UnityEngine/JetBrains.Annotations/AssertionMethodAttribute.cs b/UnityEngine/JetBrains.Annotations/AssertionMethodAttribute.cs new file mode 100644 index 00000000..16ce184b --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/AssertionMethodAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public sealed class AssertionMethodAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/BaseTypeRequiredAttribute.cs b/UnityEngine/JetBrains.Annotations/BaseTypeRequiredAttribute.cs new file mode 100644 index 00000000..ee80ecda --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/BaseTypeRequiredAttribute.cs @@ -0,0 +1,18 @@ +using System; +namespace JetBrains.Annotations +{ + [BaseTypeRequired(typeof(Attribute)), AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] + public sealed class BaseTypeRequiredAttribute : Attribute + { + [NotNull] + public Type BaseType + { + get; + private set; + } + public BaseTypeRequiredAttribute([NotNull] Type baseType) + { + this.BaseType = baseType; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/CanBeNullAttribute.cs b/UnityEngine/JetBrains.Annotations/CanBeNullAttribute.cs new file mode 100644 index 00000000..26a16918 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/CanBeNullAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate, AllowMultiple = false, Inherited = true)] + public sealed class CanBeNullAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/CannotApplyEqualityOperatorAttribute.cs b/UnityEngine/JetBrains.Annotations/CannotApplyEqualityOperatorAttribute.cs new file mode 100644 index 00000000..e17d8714 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/CannotApplyEqualityOperatorAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] + public sealed class CannotApplyEqualityOperatorAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/ContractAnnotationAttribute.cs b/UnityEngine/JetBrains.Annotations/ContractAnnotationAttribute.cs new file mode 100644 index 00000000..a6eb64e3 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/ContractAnnotationAttribute.cs @@ -0,0 +1,26 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)] + public sealed class ContractAnnotationAttribute : Attribute + { + public string Contract + { + get; + private set; + } + public bool ForceFullStates + { + get; + private set; + } + public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) + { + } + public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) + { + this.Contract = contract; + this.ForceFullStates = forceFullStates; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/ImplicitUseKindFlags.cs b/UnityEngine/JetBrains.Annotations/ImplicitUseKindFlags.cs new file mode 100644 index 00000000..88fab58e --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/ImplicitUseKindFlags.cs @@ -0,0 +1,13 @@ +using System; +namespace JetBrains.Annotations +{ + [Flags] + public enum ImplicitUseKindFlags + { + Default = 7, + Access = 1, + Assign = 2, + InstantiatedWithFixedConstructorSignature = 4, + InstantiatedNoFixedConstructorSignature = 8 + } +} diff --git a/UnityEngine/JetBrains.Annotations/ImplicitUseTargetFlags.cs b/UnityEngine/JetBrains.Annotations/ImplicitUseTargetFlags.cs new file mode 100644 index 00000000..72022370 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/ImplicitUseTargetFlags.cs @@ -0,0 +1,12 @@ +using System; +namespace JetBrains.Annotations +{ + [Flags] + public enum ImplicitUseTargetFlags + { + Default = 1, + Itself = 1, + Members = 2, + WithMembers = 3 + } +} diff --git a/UnityEngine/JetBrains.Annotations/InstantHandleAttribute.cs b/UnityEngine/JetBrains.Annotations/InstantHandleAttribute.cs new file mode 100644 index 00000000..b9efc5e1 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/InstantHandleAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Parameter, Inherited = true)] + public sealed class InstantHandleAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/InvokerParameterNameAttribute.cs b/UnityEngine/JetBrains.Annotations/InvokerParameterNameAttribute.cs new file mode 100644 index 00000000..118a712a --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/InvokerParameterNameAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] + public sealed class InvokerParameterNameAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/LinqTunnelAttribute.cs b/UnityEngine/JetBrains.Annotations/LinqTunnelAttribute.cs new file mode 100644 index 00000000..a831d2b3 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/LinqTunnelAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method)] + public sealed class LinqTunnelAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/LocalizationRequiredAttribute.cs b/UnityEngine/JetBrains.Annotations/LocalizationRequiredAttribute.cs new file mode 100644 index 00000000..a930f0f2 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/LocalizationRequiredAttribute.cs @@ -0,0 +1,20 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + public sealed class LocalizationRequiredAttribute : Attribute + { + public bool Required + { + get; + private set; + } + public LocalizationRequiredAttribute() : this(true) + { + } + public LocalizationRequiredAttribute(bool required) + { + this.Required = required; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/MeansImplicitUseAttribute.cs b/UnityEngine/JetBrains.Annotations/MeansImplicitUseAttribute.cs new file mode 100644 index 00000000..4ae66e81 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/MeansImplicitUseAttribute.cs @@ -0,0 +1,34 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] + public sealed class MeansImplicitUseAttribute : Attribute + { + [UsedImplicitly] + public ImplicitUseKindFlags UseKindFlags + { + get; + private set; + } + [UsedImplicitly] + public ImplicitUseTargetFlags TargetFlags + { + get; + private set; + } + public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + { + } + public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) + { + } + public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) + { + } + public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) + { + this.UseKindFlags = useKindFlags; + this.TargetFlags = targetFlags; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/NoEnumerationAttribute.cs b/UnityEngine/JetBrains.Annotations/NoEnumerationAttribute.cs new file mode 100644 index 00000000..3390073a --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/NoEnumerationAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Parameter)] + public sealed class NoEnumerationAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/NotNullAttribute.cs b/UnityEngine/JetBrains.Annotations/NotNullAttribute.cs new file mode 100644 index 00000000..6f8ab7a7 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/NotNullAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate, AllowMultiple = false, Inherited = true)] + public sealed class NotNullAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/NotifyPropertyChangedInvocatorAttribute.cs b/UnityEngine/JetBrains.Annotations/NotifyPropertyChangedInvocatorAttribute.cs new file mode 100644 index 00000000..e5c4b31f --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/NotifyPropertyChangedInvocatorAttribute.cs @@ -0,0 +1,20 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute + { + public string ParameterName + { + get; + private set; + } + public NotifyPropertyChangedInvocatorAttribute() + { + } + public NotifyPropertyChangedInvocatorAttribute(string parameterName) + { + this.ParameterName = parameterName; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/PathReferenceAttribute.cs b/UnityEngine/JetBrains.Annotations/PathReferenceAttribute.cs new file mode 100644 index 00000000..0bdb3aac --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/PathReferenceAttribute.cs @@ -0,0 +1,21 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Parameter)] + public class PathReferenceAttribute : Attribute + { + [NotNull] + public string BasePath + { + get; + private set; + } + public PathReferenceAttribute() + { + } + public PathReferenceAttribute([PathReference] string basePath) + { + this.BasePath = basePath; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/PublicAPIAttribute.cs b/UnityEngine/JetBrains.Annotations/PublicAPIAttribute.cs new file mode 100644 index 00000000..8c7ec28c --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/PublicAPIAttribute.cs @@ -0,0 +1,21 @@ +using System; +namespace JetBrains.Annotations +{ + [MeansImplicitUse] + public sealed class PublicAPIAttribute : Attribute + { + [NotNull] + public string Comment + { + get; + private set; + } + public PublicAPIAttribute() + { + } + public PublicAPIAttribute([NotNull] string comment) + { + this.Comment = comment; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/PureAttribute.cs b/UnityEngine/JetBrains.Annotations/PureAttribute.cs new file mode 100644 index 00000000..9356390a --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/PureAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Method, Inherited = true)] + public sealed class PureAttribute : Attribute + { + } +} diff --git a/UnityEngine/JetBrains.Annotations/StringFormatMethodAttribute.cs b/UnityEngine/JetBrains.Annotations/StringFormatMethodAttribute.cs new file mode 100644 index 00000000..0c9f722c --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/StringFormatMethodAttribute.cs @@ -0,0 +1,17 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + public sealed class StringFormatMethodAttribute : Attribute + { + public string FormatParameterName + { + get; + private set; + } + public StringFormatMethodAttribute(string formatParameterName) + { + this.FormatParameterName = formatParameterName; + } + } +} diff --git a/UnityEngine/JetBrains.Annotations/UsedImplicitlyAttribute.cs b/UnityEngine/JetBrains.Annotations/UsedImplicitlyAttribute.cs new file mode 100644 index 00000000..fb4c3d56 --- /dev/null +++ b/UnityEngine/JetBrains.Annotations/UsedImplicitlyAttribute.cs @@ -0,0 +1,32 @@ +using System; +namespace JetBrains.Annotations +{ + [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] + public sealed class UsedImplicitlyAttribute : Attribute + { + public ImplicitUseKindFlags UseKindFlags + { + get; + private set; + } + public ImplicitUseTargetFlags TargetFlags + { + get; + private set; + } + public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + { + } + public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) + { + } + public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) + { + } + public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) + { + this.UseKindFlags = useKindFlags; + this.TargetFlags = targetFlags; + } + } +} diff --git a/UnityEngine/Properties/AssemblyInfo.cs b/UnityEngine/Properties/AssemblyInfo.cs index db26cd2d..238244e2 100644 --- a/UnityEngine/Properties/AssemblyInfo.cs +++ b/UnityEngine/Properties/AssemblyInfo.cs @@ -1,10 +1,26 @@ using System; using System.Reflection; using System.Runtime.CompilerServices; +using System.Security; +using System.Security.Permissions; [assembly: AssemblyVersion("0.0.0.0")] [assembly: InternalsVisibleTo("Unity.PureCSharpTests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("UnityEditor.Graphs")] [assembly: InternalsVisibleTo("UnityEditor.Xbox360.Extensions")] +[assembly: InternalsVisibleTo("UnityEngine.Physics")] +[assembly: InternalsVisibleTo("UnityEngine.Terrain")] +[assembly: InternalsVisibleTo("UnityEngine.TerrainPhysics")] +[assembly: InternalsVisibleTo("UnityEngine.Networking")] +[assembly: InternalsVisibleTo("UnityEngine.Cloud")] +[assembly: InternalsVisibleTo("UnityEngine.Advertisements")] +[assembly: InternalsVisibleTo("Unity.Automation")] +[assembly: InternalsVisibleTo("Unity.IntegrationTests")] +[assembly: InternalsVisibleTo("Unity.IntegrationTests.Framework")] +[assembly: InternalsVisibleTo("Unity.RuntimeTests")] +[assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework")] +[assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework.Tests")] [assembly: InternalsVisibleTo("UnityEditor")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] +[assembly: PermissionSet(SecurityAction.RequestMinimum, XML = "\r\n\r\n\r\n")] +[module: UnverifiableCode] diff --git a/UnityEngine/UnityEngine.Audio/AudioMixer.cs b/UnityEngine/UnityEngine.Audio/AudioMixer.cs new file mode 100644 index 00000000..5d470ac6 --- /dev/null +++ b/UnityEngine/UnityEngine.Audio/AudioMixer.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.Audio +{ + public class AudioMixer : UnityEngine.Object + { + public extern AudioMixerGroup outputAudioMixerGroup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal AudioMixer() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AudioMixerGroup[] FindMatchingGroups(string subPath); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AudioMixerSnapshot FindSnapshot(string name); + private void TransitionToSnapshot(AudioMixerSnapshot snapshot, float timeToReach) + { + if (snapshot == null || snapshot.audioMixer != this) + { + return; + } + snapshot.TransitionTo(timeToReach); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void TransitionToSnapshots(AudioMixerSnapshot[] snapshots, float[] weights, float timeToReach); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SetFloat(string name, float value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool ClearFloat(string name); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool GetFloat(string name, out float value); + } +} diff --git a/UnityEngine/UnityEngine.Audio/AudioMixerGroup.cs b/UnityEngine/UnityEngine.Audio/AudioMixerGroup.cs new file mode 100644 index 00000000..48878499 --- /dev/null +++ b/UnityEngine/UnityEngine.Audio/AudioMixerGroup.cs @@ -0,0 +1,17 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.Audio +{ + public class AudioMixerGroup : UnityEngine.Object + { + public extern AudioMixer audioMixer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal AudioMixerGroup() + { + } + } +} diff --git a/UnityEngine/UnityEngine.Audio/AudioMixerSnapshot.cs b/UnityEngine/UnityEngine.Audio/AudioMixerSnapshot.cs new file mode 100644 index 00000000..57724623 --- /dev/null +++ b/UnityEngine/UnityEngine.Audio/AudioMixerSnapshot.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.Audio +{ + public class AudioMixerSnapshot : UnityEngine.Object + { + public extern AudioMixer audioMixer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal AudioMixerSnapshot() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void TransitionTo(float timeToReach); + } +} diff --git a/UnityEngine/UnityEngine.Events/UnityEvent.cs b/UnityEngine/UnityEngine.Events/UnityEvent.cs index bfed4ae6..f9d35606 100644 --- a/UnityEngine/UnityEngine.Events/UnityEvent.cs +++ b/UnityEngine/UnityEngine.Events/UnityEvent.cs @@ -31,10 +31,15 @@ public void Invoke() base.Invoke(this.m_InvokeArray); } internal void AddPersistentListener(UnityAction call) + { + this.AddPersistentListener(call, UnityEventCallState.RuntimeOnly); + } + internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) { int persistentEventCount = base.GetPersistentEventCount(); base.AddPersistentListener(); this.RegisterPersistentListener(persistentEventCount, call); + base.SetPersistentListenerState(persistentEventCount, callState); } internal void RegisterPersistentListener(int index, UnityAction call) { @@ -79,10 +84,15 @@ public void Invoke(T0 arg0) base.Invoke(this.m_InvokeArray); } internal void AddPersistentListener(UnityAction call) + { + this.AddPersistentListener(call, UnityEventCallState.RuntimeOnly); + } + internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) { int persistentEventCount = base.GetPersistentEventCount(); base.AddPersistentListener(); this.RegisterPersistentListener(persistentEventCount, call); + base.SetPersistentListenerState(persistentEventCount, callState); } internal void RegisterPersistentListener(int index, UnityAction call) { @@ -129,10 +139,15 @@ public void Invoke(T0 arg0, T1 arg1) base.Invoke(this.m_InvokeArray); } internal void AddPersistentListener(UnityAction call) + { + this.AddPersistentListener(call, UnityEventCallState.RuntimeOnly); + } + internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) { int persistentEventCount = base.GetPersistentEventCount(); base.AddPersistentListener(); this.RegisterPersistentListener(persistentEventCount, call); + base.SetPersistentListenerState(persistentEventCount, callState); } internal void RegisterPersistentListener(int index, UnityAction call) { @@ -181,10 +196,15 @@ public void Invoke(T0 arg0, T1 arg1, T2 arg2) base.Invoke(this.m_InvokeArray); } internal void AddPersistentListener(UnityAction call) + { + this.AddPersistentListener(call, UnityEventCallState.RuntimeOnly); + } + internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) { int persistentEventCount = base.GetPersistentEventCount(); base.AddPersistentListener(); this.RegisterPersistentListener(persistentEventCount, call); + base.SetPersistentListenerState(persistentEventCount, callState); } internal void RegisterPersistentListener(int index, UnityAction call) { @@ -235,10 +255,15 @@ public void Invoke(T0 arg0, T1 arg1, T2 arg2, T3 arg3) base.Invoke(this.m_InvokeArray); } internal void AddPersistentListener(UnityAction call) + { + this.AddPersistentListener(call, UnityEventCallState.RuntimeOnly); + } + internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) { int persistentEventCount = base.GetPersistentEventCount(); base.AddPersistentListener(); this.RegisterPersistentListener(persistentEventCount, call); + base.SetPersistentListenerState(persistentEventCount, callState); } internal void RegisterPersistentListener(int index, UnityAction call) { diff --git a/UnityEngine/UnityEngine.Flash/ActionScript.cs b/UnityEngine/UnityEngine.Flash/ActionScript.cs deleted file mode 100644 index 27ba9351..00000000 --- a/UnityEngine/UnityEngine.Flash/ActionScript.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Diagnostics; -namespace UnityEngine.Flash -{ - [NotConverted] - public sealed class ActionScript - { - [Conditional("UNITY_FLASH")] - public static void Import(string package) - { - } - [Conditional("UNITY_FLASH")] - public static void Statement(string formatString, params object[] arguments) - { - } - public static T Expression(string formatString, params object[] arguments) - { - throw new InvalidOperationException(); - } - } -} diff --git a/UnityEngine/UnityEngine.Flash/FlashPlayer.cs b/UnityEngine/UnityEngine.Flash/FlashPlayer.cs deleted file mode 100644 index 6323e1c4..00000000 --- a/UnityEngine/UnityEngine.Flash/FlashPlayer.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -namespace UnityEngine.Flash -{ - public sealed class FlashPlayer - { - public static string TargetVersion - { - get - { - return FlashPlayer.GetUnityAppConstants("TargetFlashPlayerVersion"); - } - } - public static string TargetSwfVersion - { - get - { - return FlashPlayer.GetUnityAppConstants("TargetSwfVersion"); - } - } - internal static string GetUnityAppConstants(string name) - { - return ActionScript.Expression("UnityNative.getUnityAppConstants()[{0}]", new object[] - { - name - }); - } - } -} diff --git a/UnityEngine/UnityEngine.Rendering/AmbientMode.cs b/UnityEngine/UnityEngine.Rendering/AmbientMode.cs new file mode 100644 index 00000000..4feb718f --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/AmbientMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum AmbientMode + { + Skybox, + Trilight, + Flat = 3, + Custom + } +} diff --git a/UnityEngine/UnityEngine.Rendering/BuiltinRenderTextureType.cs b/UnityEngine/UnityEngine.Rendering/BuiltinRenderTextureType.cs new file mode 100644 index 00000000..105efba4 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/BuiltinRenderTextureType.cs @@ -0,0 +1,19 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum BuiltinRenderTextureType + { + None, + CurrentActive, + CameraTarget, + Depth, + DepthNormals, + PrepassNormalsSpec = 7, + PrepassLight, + PrepassLightSpec, + GBuffer0, + GBuffer1, + GBuffer2, + GBuffer3 + } +} diff --git a/UnityEngine/UnityEngine.Rendering/CameraEvent.cs b/UnityEngine/UnityEngine.Rendering/CameraEvent.cs new file mode 100644 index 00000000..5baa3e09 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/CameraEvent.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum CameraEvent + { + BeforeDepthTexture, + AfterDepthTexture, + BeforeDepthNormalsTexture, + AfterDepthNormalsTexture, + BeforeGBuffer, + AfterGBuffer, + BeforeLighting, + AfterLighting, + BeforeFinalPass, + AfterFinalPass, + BeforeForwardOpaque, + AfterForwardOpaque, + BeforeImageEffectsOpaque, + AfterImageEffectsOpaque, + BeforeSkybox, + AfterSkybox, + BeforeForwardAlpha, + AfterForwardAlpha, + BeforeImageEffects, + AfterImageEffects, + AfterEverything + } +} diff --git a/UnityEngine/UnityEngine.Rendering/CommandBuffer.cs b/UnityEngine/UnityEngine.Rendering/CommandBuffer.cs new file mode 100644 index 00000000..ee7d92cc --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/CommandBuffer.cs @@ -0,0 +1,275 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +namespace UnityEngine.Rendering +{ + public sealed class CommandBuffer : IDisposable + { + internal IntPtr m_Ptr; + public extern string name + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int sizeInBytes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public CommandBuffer() + { + this.m_Ptr = IntPtr.Zero; + CommandBuffer.InitBuffer(this); + } + ~CommandBuffer() + { + this.Dispose(false); + } + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + private void Dispose(bool disposing) + { + this.ReleaseBuffer(); + this.m_Ptr = IntPtr.Zero; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void InitBuffer(CommandBuffer buf); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void ReleaseBuffer(); + public void Release() + { + this.Dispose(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Clear(); + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, [DefaultValue("0")] int submeshIndex, [DefaultValue("-1")] int shaderPass, [DefaultValue("null")] MaterialPropertyBlock properties) + { + CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties); + } + [ExcludeFromDocs] + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass) + { + MaterialPropertyBlock properties = null; + CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties); + } + [ExcludeFromDocs] + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex) + { + MaterialPropertyBlock properties = null; + int shaderPass = -1; + CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties); + } + [ExcludeFromDocs] + public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material) + { + MaterialPropertyBlock properties = null; + int shaderPass = -1; + int submeshIndex = 0; + CommandBuffer.INTERNAL_CALL_DrawMesh(this, mesh, ref matrix, material, submeshIndex, shaderPass, properties); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawMesh(CommandBuffer self, Mesh mesh, ref Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass, MaterialPropertyBlock properties); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void DrawRenderer(Renderer renderer, Material material, [DefaultValue("0")] int submeshIndex, [DefaultValue("-1")] int shaderPass); + [ExcludeFromDocs] + public void DrawRenderer(Renderer renderer, Material material, int submeshIndex) + { + int shaderPass = -1; + this.DrawRenderer(renderer, material, submeshIndex, shaderPass); + } + [ExcludeFromDocs] + public void DrawRenderer(Renderer renderer, Material material) + { + int shaderPass = -1; + int submeshIndex = 0; + this.DrawRenderer(renderer, material, submeshIndex, shaderPass); + } + public void SetRenderTarget(RenderTargetIdentifier rt) + { + this.SetRenderTarget_Single(ref rt); + } + public void SetRenderTarget(RenderTargetIdentifier color, RenderTargetIdentifier depth) + { + this.SetRenderTarget_ColDepth(ref color, ref depth); + } + public void SetRenderTarget(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth) + { + this.SetRenderTarget_Multiple(colors, ref depth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetRenderTarget_Single(ref RenderTargetIdentifier rt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetRenderTarget_ColDepth(ref RenderTargetIdentifier color, ref RenderTargetIdentifier depth); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetRenderTarget_Multiple(RenderTargetIdentifier[] color, ref RenderTargetIdentifier depth); + public void Blit(Texture source, RenderTargetIdentifier dest) + { + this.Blit_Texture(source, ref dest, null, -1); + } + public void Blit(Texture source, RenderTargetIdentifier dest, Material mat) + { + this.Blit_Texture(source, ref dest, mat, -1); + } + public void Blit(Texture source, RenderTargetIdentifier dest, Material mat, int pass) + { + this.Blit_Texture(source, ref dest, mat, pass); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Blit_Texture(Texture source, ref RenderTargetIdentifier dest, Material mat, int pass); + public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest) + { + this.Blit_Identifier(ref source, ref dest, null, -1); + } + public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Material mat) + { + this.Blit_Identifier(ref source, ref dest, mat, -1); + } + public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Material mat, int pass) + { + this.Blit_Identifier(ref source, ref dest, mat, pass); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Blit_Identifier(ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest, [DefaultValue("null")] Material mat, [DefaultValue("-1")] int pass); + [ExcludeFromDocs] + private void Blit_Identifier(ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest, Material mat) + { + int pass = -1; + this.Blit_Identifier(ref source, ref dest, mat, pass); + } + [ExcludeFromDocs] + private void Blit_Identifier(ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest) + { + int pass = -1; + Material mat = null; + this.Blit_Identifier(ref source, ref dest, mat, pass); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void GetTemporaryRT(int nameID, int width, int height, [DefaultValue("0")] int depthBuffer, [DefaultValue("FilterMode.Point")] FilterMode filter, [DefaultValue("RenderTextureFormat.Default")] RenderTextureFormat format, [DefaultValue("RenderTextureReadWrite.Default")] RenderTextureReadWrite readWrite, [DefaultValue("1")] int antiAliasing); + [ExcludeFromDocs] + public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite) + { + int antiAliasing = 1; + this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + RenderTextureFormat format = RenderTextureFormat.Default; + this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + RenderTextureFormat format = RenderTextureFormat.Default; + FilterMode filter = FilterMode.Point; + this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing); + } + [ExcludeFromDocs] + public void GetTemporaryRT(int nameID, int width, int height) + { + int antiAliasing = 1; + RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default; + RenderTextureFormat format = RenderTextureFormat.Default; + FilterMode filter = FilterMode.Point; + int depthBuffer = 0; + this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ReleaseTemporaryRT(int nameID); + public void ClearRenderTarget(bool clearDepth, bool clearColor, Color backgroundColor, [DefaultValue("1.0f")] float depth) + { + CommandBuffer.INTERNAL_CALL_ClearRenderTarget(this, clearDepth, clearColor, ref backgroundColor, depth); + } + [ExcludeFromDocs] + public void ClearRenderTarget(bool clearDepth, bool clearColor, Color backgroundColor) + { + float depth = 1f; + CommandBuffer.INTERNAL_CALL_ClearRenderTarget(this, clearDepth, clearColor, ref backgroundColor, depth); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearRenderTarget(CommandBuffer self, bool clearDepth, bool clearColor, ref Color backgroundColor, float depth); + public void SetGlobalFloat(string name, float value) + { + this.SetGlobalFloat(Shader.PropertyToID(name), value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetGlobalFloat(int nameID, float value); + public void SetGlobalVector(string name, Vector4 value) + { + this.SetGlobalVector(Shader.PropertyToID(name), value); + } + public void SetGlobalVector(int nameID, Vector4 value) + { + CommandBuffer.INTERNAL_CALL_SetGlobalVector(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetGlobalVector(CommandBuffer self, int nameID, ref Vector4 value); + public void SetGlobalColor(string name, Color value) + { + this.SetGlobalColor(Shader.PropertyToID(name), value); + } + public void SetGlobalColor(int nameID, Color value) + { + CommandBuffer.INTERNAL_CALL_SetGlobalColor(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetGlobalColor(CommandBuffer self, int nameID, ref Color value); + public void SetGlobalMatrix(string name, Matrix4x4 value) + { + this.SetGlobalMatrix(Shader.PropertyToID(name), value); + } + public void SetGlobalMatrix(int nameID, Matrix4x4 value) + { + CommandBuffer.INTERNAL_CALL_SetGlobalMatrix(this, nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetGlobalMatrix(CommandBuffer self, int nameID, ref Matrix4x4 value); + public void SetGlobalTexture(string name, RenderTargetIdentifier value) + { + this.SetGlobalTexture(Shader.PropertyToID(name), value); + } + public void SetGlobalTexture(int nameID, RenderTargetIdentifier value) + { + this.SetGlobalTexture_Impl(nameID, ref value); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetGlobalTexture_Impl(int nameID, ref RenderTargetIdentifier rt); + } +} diff --git a/UnityEngine/UnityEngine.Rendering/DefaultReflectionMode.cs b/UnityEngine/UnityEngine.Rendering/DefaultReflectionMode.cs new file mode 100644 index 00000000..aa3989b0 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/DefaultReflectionMode.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum DefaultReflectionMode + { + Skybox, + Custom + } +} diff --git a/UnityEngine/UnityEngine.Rendering/PassType.cs b/UnityEngine/UnityEngine.Rendering/PassType.cs new file mode 100644 index 00000000..a7a2d9e1 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/PassType.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum PassType + { + Normal, + Vertex, + VertexLM, + VertexLMRGBM, + ForwardBase, + ForwardAdd, + LightPrePassBase, + LightPrePassFinal, + ShadowCaster, + Deferred = 10, + Meta + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeBlendInfo.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeBlendInfo.cs new file mode 100644 index 00000000..616b5eb3 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeBlendInfo.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public struct ReflectionProbeBlendInfo + { + public ReflectionProbe probe; + public float weight; + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeClearFlags.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeClearFlags.cs new file mode 100644 index 00000000..931f4043 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeClearFlags.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeClearFlags + { + Skybox = 1, + SolidColor + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeMode.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeMode.cs new file mode 100644 index 00000000..e39a1064 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeMode + { + Baked, + Realtime, + Custom + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeRefreshMode.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeRefreshMode.cs new file mode 100644 index 00000000..ee2d56e1 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeRefreshMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeRefreshMode + { + OnAwake, + EveryFrame, + ViaScripting + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeTimeSlicingMode.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeTimeSlicingMode.cs new file mode 100644 index 00000000..65aeca42 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeTimeSlicingMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeTimeSlicingMode + { + AllFacesAtOnce, + IndividualFaces, + NoTimeSlicing + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeType.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeType.cs new file mode 100644 index 00000000..82bb928f --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeType.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeType + { + Cube, + Card + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ReflectionProbeUsage.cs b/UnityEngine/UnityEngine.Rendering/ReflectionProbeUsage.cs new file mode 100644 index 00000000..b78270b5 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ReflectionProbeUsage.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ReflectionProbeUsage + { + Off, + BlendProbes, + BlendProbesAndSkybox, + Simple + } +} diff --git a/UnityEngine/UnityEngine.Rendering/RenderBufferLoadAction.cs b/UnityEngine/UnityEngine.Rendering/RenderBufferLoadAction.cs new file mode 100644 index 00000000..45572b35 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/RenderBufferLoadAction.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum RenderBufferLoadAction + { + Load, + DontCare = 2 + } +} diff --git a/UnityEngine/UnityEngine.Rendering/RenderBufferStoreAction.cs b/UnityEngine/UnityEngine.Rendering/RenderBufferStoreAction.cs new file mode 100644 index 00000000..121ec765 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/RenderBufferStoreAction.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum RenderBufferStoreAction + { + Store, + DontCare + } +} diff --git a/UnityEngine/UnityEngine.Rendering/RenderTargetIdentifier.cs b/UnityEngine/UnityEngine.Rendering/RenderTargetIdentifier.cs new file mode 100644 index 00000000..ffb9c30a --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/RenderTargetIdentifier.cs @@ -0,0 +1,50 @@ +using System; +namespace UnityEngine.Rendering +{ + public struct RenderTargetIdentifier + { + private BuiltinRenderTextureType m_Type; + private int m_NameID; + private int m_InstanceID; + public RenderTargetIdentifier(BuiltinRenderTextureType type) + { + this.m_Type = type; + this.m_NameID = 0; + this.m_InstanceID = 0; + } + public RenderTargetIdentifier(string name) + { + this.m_Type = BuiltinRenderTextureType.None; + this.m_NameID = Shader.PropertyToID(name); + this.m_InstanceID = 0; + } + public RenderTargetIdentifier(int nameID) + { + this.m_Type = BuiltinRenderTextureType.None; + this.m_NameID = nameID; + this.m_InstanceID = 0; + } + public RenderTargetIdentifier(RenderTexture rt) + { + this.m_Type = BuiltinRenderTextureType.None; + this.m_NameID = 0; + this.m_InstanceID = ((!rt) ? 0 : rt.GetInstanceID()); + } + public static implicit operator RenderTargetIdentifier(BuiltinRenderTextureType type) + { + return new RenderTargetIdentifier(type); + } + public static implicit operator RenderTargetIdentifier(string name) + { + return new RenderTargetIdentifier(name); + } + public static implicit operator RenderTargetIdentifier(int nameID) + { + return new RenderTargetIdentifier(nameID); + } + public static implicit operator RenderTargetIdentifier(RenderTexture rt) + { + return new RenderTargetIdentifier(rt); + } + } +} diff --git a/UnityEngine/UnityEngine.Rendering/ShadowCastingMode.cs b/UnityEngine/UnityEngine.Rendering/ShadowCastingMode.cs new file mode 100644 index 00000000..5b0843f5 --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/ShadowCastingMode.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine.Rendering +{ + public enum ShadowCastingMode + { + Off, + On, + TwoSided, + ShadowsOnly + } +} diff --git a/UnityEngine/UnityEngine.Rendering/SphericalHarmonicsL2.cs b/UnityEngine/UnityEngine.Rendering/SphericalHarmonicsL2.cs new file mode 100644 index 00000000..8162cb4c --- /dev/null +++ b/UnityEngine/UnityEngine.Rendering/SphericalHarmonicsL2.cs @@ -0,0 +1,370 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.Rendering +{ + public struct SphericalHarmonicsL2 + { + private float shr0; + private float shr1; + private float shr2; + private float shr3; + private float shr4; + private float shr5; + private float shr6; + private float shr7; + private float shr8; + private float shg0; + private float shg1; + private float shg2; + private float shg3; + private float shg4; + private float shg5; + private float shg6; + private float shg7; + private float shg8; + private float shb0; + private float shb1; + private float shb2; + private float shb3; + private float shb4; + private float shb5; + private float shb6; + private float shb7; + private float shb8; + public float this[int rgb, int coefficient] + { + get + { + switch (rgb * 9 + coefficient) + { + case 0: + return this.shr0; + case 1: + return this.shr1; + case 2: + return this.shr2; + case 3: + return this.shr3; + case 4: + return this.shr4; + case 5: + return this.shr5; + case 6: + return this.shr6; + case 7: + return this.shr7; + case 8: + return this.shr8; + case 9: + return this.shg0; + case 10: + return this.shg1; + case 11: + return this.shg2; + case 12: + return this.shg3; + case 13: + return this.shg4; + case 14: + return this.shg5; + case 15: + return this.shg6; + case 16: + return this.shg7; + case 17: + return this.shg8; + case 18: + return this.shb0; + case 19: + return this.shb1; + case 20: + return this.shb2; + case 21: + return this.shb3; + case 22: + return this.shb4; + case 23: + return this.shb5; + case 24: + return this.shb6; + case 25: + return this.shb7; + case 26: + return this.shb8; + default: + throw new IndexOutOfRangeException("Invalid index!"); + } + } + set + { + switch (rgb * 9 + coefficient) + { + case 0: + this.shr0 = value; + break; + case 1: + this.shr1 = value; + break; + case 2: + this.shr2 = value; + break; + case 3: + this.shr3 = value; + break; + case 4: + this.shr4 = value; + break; + case 5: + this.shr5 = value; + break; + case 6: + this.shr6 = value; + break; + case 7: + this.shr7 = value; + break; + case 8: + this.shr8 = value; + break; + case 9: + this.shg0 = value; + break; + case 10: + this.shg1 = value; + break; + case 11: + this.shg2 = value; + break; + case 12: + this.shg3 = value; + break; + case 13: + this.shg4 = value; + break; + case 14: + this.shg5 = value; + break; + case 15: + this.shg6 = value; + break; + case 16: + this.shg7 = value; + break; + case 17: + this.shg8 = value; + break; + case 18: + this.shb0 = value; + break; + case 19: + this.shb1 = value; + break; + case 20: + this.shb2 = value; + break; + case 21: + this.shb3 = value; + break; + case 22: + this.shb4 = value; + break; + case 23: + this.shb5 = value; + break; + case 24: + this.shb6 = value; + break; + case 25: + this.shb7 = value; + break; + case 26: + this.shb8 = value; + break; + default: + throw new IndexOutOfRangeException("Invalid index!"); + } + } + } + public void Clear() + { + SphericalHarmonicsL2.ClearInternal(ref this); + } + private static void ClearInternal(ref SphericalHarmonicsL2 sh) + { + SphericalHarmonicsL2.INTERNAL_CALL_ClearInternal(ref sh); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearInternal(ref SphericalHarmonicsL2 sh); + public void AddAmbientLight(Color color) + { + SphericalHarmonicsL2.AddAmbientLightInternal(color, ref this); + } + private static void AddAmbientLightInternal(Color color, ref SphericalHarmonicsL2 sh) + { + SphericalHarmonicsL2.INTERNAL_CALL_AddAmbientLightInternal(ref color, ref sh); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddAmbientLightInternal(ref Color color, ref SphericalHarmonicsL2 sh); + public void AddDirectionalLight(Vector3 direction, Color color, float intensity) + { + Color color2 = color * (2f * intensity); + SphericalHarmonicsL2.AddDirectionalLightInternal(direction, color2, ref this); + } + private static void AddDirectionalLightInternal(Vector3 direction, Color color, ref SphericalHarmonicsL2 sh) + { + SphericalHarmonicsL2.INTERNAL_CALL_AddDirectionalLightInternal(ref direction, ref color, ref sh); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_AddDirectionalLightInternal(ref Vector3 direction, ref Color color, ref SphericalHarmonicsL2 sh); + public override int GetHashCode() + { + int num = 17; + num = num * 23 + this.shr0.GetHashCode(); + num = num * 23 + this.shr1.GetHashCode(); + num = num * 23 + this.shr2.GetHashCode(); + num = num * 23 + this.shr3.GetHashCode(); + num = num * 23 + this.shr4.GetHashCode(); + num = num * 23 + this.shr5.GetHashCode(); + num = num * 23 + this.shr6.GetHashCode(); + num = num * 23 + this.shr7.GetHashCode(); + num = num * 23 + this.shr8.GetHashCode(); + num = num * 23 + this.shg0.GetHashCode(); + num = num * 23 + this.shg1.GetHashCode(); + num = num * 23 + this.shg2.GetHashCode(); + num = num * 23 + this.shg3.GetHashCode(); + num = num * 23 + this.shg4.GetHashCode(); + num = num * 23 + this.shg5.GetHashCode(); + num = num * 23 + this.shg6.GetHashCode(); + num = num * 23 + this.shg7.GetHashCode(); + num = num * 23 + this.shg8.GetHashCode(); + num = num * 23 + this.shb0.GetHashCode(); + num = num * 23 + this.shb1.GetHashCode(); + num = num * 23 + this.shb2.GetHashCode(); + num = num * 23 + this.shb3.GetHashCode(); + num = num * 23 + this.shb4.GetHashCode(); + num = num * 23 + this.shb5.GetHashCode(); + num = num * 23 + this.shb6.GetHashCode(); + num = num * 23 + this.shb7.GetHashCode(); + return num * 23 + this.shb8.GetHashCode(); + } + public override bool Equals(object other) + { + if (!(other is SphericalHarmonicsL2)) + { + return false; + } + SphericalHarmonicsL2 rhs = (SphericalHarmonicsL2)other; + return this == rhs; + } + public static SphericalHarmonicsL2 operator *(SphericalHarmonicsL2 lhs, float rhs) + { + return new SphericalHarmonicsL2 + { + shr0 = lhs.shr0 * rhs, + shr1 = lhs.shr1 * rhs, + shr2 = lhs.shr2 * rhs, + shr3 = lhs.shr3 * rhs, + shr4 = lhs.shr4 * rhs, + shr5 = lhs.shr5 * rhs, + shr6 = lhs.shr6 * rhs, + shr7 = lhs.shr7 * rhs, + shr8 = lhs.shr8 * rhs, + shg0 = lhs.shg0 * rhs, + shg1 = lhs.shg1 * rhs, + shg2 = lhs.shg2 * rhs, + shg3 = lhs.shg3 * rhs, + shg4 = lhs.shg4 * rhs, + shg5 = lhs.shg5 * rhs, + shg6 = lhs.shg6 * rhs, + shg7 = lhs.shg7 * rhs, + shg8 = lhs.shg8 * rhs, + shb0 = lhs.shb0 * rhs, + shb1 = lhs.shb1 * rhs, + shb2 = lhs.shb2 * rhs, + shb3 = lhs.shb3 * rhs, + shb4 = lhs.shb4 * rhs, + shb5 = lhs.shb5 * rhs, + shb6 = lhs.shb6 * rhs, + shb7 = lhs.shb7 * rhs, + shb8 = lhs.shb8 * rhs + }; + } + public static SphericalHarmonicsL2 operator *(float lhs, SphericalHarmonicsL2 rhs) + { + return new SphericalHarmonicsL2 + { + shr0 = rhs.shr0 * lhs, + shr1 = rhs.shr1 * lhs, + shr2 = rhs.shr2 * lhs, + shr3 = rhs.shr3 * lhs, + shr4 = rhs.shr4 * lhs, + shr5 = rhs.shr5 * lhs, + shr6 = rhs.shr6 * lhs, + shr7 = rhs.shr7 * lhs, + shr8 = rhs.shr8 * lhs, + shg0 = rhs.shg0 * lhs, + shg1 = rhs.shg1 * lhs, + shg2 = rhs.shg2 * lhs, + shg3 = rhs.shg3 * lhs, + shg4 = rhs.shg4 * lhs, + shg5 = rhs.shg5 * lhs, + shg6 = rhs.shg6 * lhs, + shg7 = rhs.shg7 * lhs, + shg8 = rhs.shg8 * lhs, + shb0 = rhs.shb0 * lhs, + shb1 = rhs.shb1 * lhs, + shb2 = rhs.shb2 * lhs, + shb3 = rhs.shb3 * lhs, + shb4 = rhs.shb4 * lhs, + shb5 = rhs.shb5 * lhs, + shb6 = rhs.shb6 * lhs, + shb7 = rhs.shb7 * lhs, + shb8 = rhs.shb8 * lhs + }; + } + public static SphericalHarmonicsL2 operator +(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) + { + return new SphericalHarmonicsL2 + { + shr0 = lhs.shr0 + rhs.shr0, + shr1 = lhs.shr1 + rhs.shr1, + shr2 = lhs.shr2 + rhs.shr2, + shr3 = lhs.shr3 + rhs.shr3, + shr4 = lhs.shr4 + rhs.shr4, + shr5 = lhs.shr5 + rhs.shr5, + shr6 = lhs.shr6 + rhs.shr6, + shr7 = lhs.shr7 + rhs.shr7, + shr8 = lhs.shr8 + rhs.shr8, + shg0 = lhs.shg0 + rhs.shg0, + shg1 = lhs.shg1 + rhs.shg1, + shg2 = lhs.shg2 + rhs.shg2, + shg3 = lhs.shg3 + rhs.shg3, + shg4 = lhs.shg4 + rhs.shg4, + shg5 = lhs.shg5 + rhs.shg5, + shg6 = lhs.shg6 + rhs.shg6, + shg7 = lhs.shg7 + rhs.shg7, + shg8 = lhs.shg8 + rhs.shg8, + shb0 = lhs.shb0 + rhs.shb0, + shb1 = lhs.shb1 + rhs.shb1, + shb2 = lhs.shb2 + rhs.shb2, + shb3 = lhs.shb3 + rhs.shb3, + shb4 = lhs.shb4 + rhs.shb4, + shb5 = lhs.shb5 + rhs.shb5, + shb6 = lhs.shb6 + rhs.shb6, + shb7 = lhs.shb7 + rhs.shb7, + shb8 = lhs.shb8 + rhs.shb8 + }; + } + public static bool operator ==(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) + { + return lhs.shr0 == rhs.shr0 && lhs.shr1 == rhs.shr1 && lhs.shr2 == rhs.shr2 && lhs.shr3 == rhs.shr3 && lhs.shr4 == rhs.shr4 && lhs.shr5 == rhs.shr5 && lhs.shr6 == rhs.shr6 && lhs.shr7 == rhs.shr7 && lhs.shr8 == rhs.shr8 && lhs.shg0 == rhs.shg0 && lhs.shg1 == rhs.shg1 && lhs.shg2 == rhs.shg2 && lhs.shg3 == rhs.shg3 && lhs.shg4 == rhs.shg4 && lhs.shg5 == rhs.shg5 && lhs.shg6 == rhs.shg6 && lhs.shg7 == rhs.shg7 && lhs.shg8 == rhs.shg8 && lhs.shb0 == rhs.shb0 && lhs.shb1 == rhs.shb1 && lhs.shb2 == rhs.shb2 && lhs.shb3 == rhs.shb3 && lhs.shb4 == rhs.shb4 && lhs.shb5 == rhs.shb5 && lhs.shb6 == rhs.shb6 && lhs.shb7 == rhs.shb7 && lhs.shb8 == rhs.shb8; + } + public static bool operator !=(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) + { + return !(lhs == rhs); + } + } +} diff --git a/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs b/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs deleted file mode 100644 index e582641d..00000000 --- a/UnityEngine/UnityEngine.Serialization/SerializationHelper.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -namespace UnityEngine.Serialization -{ - internal class SerializationHelper - { - private static bool alreadyWarned; - public static void LogSerializationDepthWarning(string namespaze, string name) - { - if (SerializationHelper.alreadyWarned) - { - return; - } - SerializationHelper.alreadyWarned = true; - string str = (namespaze.Length <= 0) ? name : (namespaze + "." + name); - Debug.LogWarning("Serialization of " + str + " has too many depth levels. This means you have fallen of a performance cliff. Check the Serialization section of the docs for more details about this problem and how to fix it."); - } - } -} diff --git a/UnityEngine/UnityEngine.csproj b/UnityEngine/UnityEngine.csproj index 373dd3a0..cfd5bf0a 100644 --- a/UnityEngine/UnityEngine.csproj +++ b/UnityEngine/UnityEngine.csproj @@ -1,14 +1,13 @@ - + - {731BEF47-7B99-4BB3-86B7-595906204083} + {B138D295-6267-41DD-8863-2B8580406018} Debug AnyCPU Library UnityEngine - v4.0 + v2.0 4 - AnyCPU @@ -26,12 +25,36 @@ true - + + + + + + + + + + + + + + + + + + + + + + + + + @@ -44,20 +67,46 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - @@ -80,9 +129,14 @@ + + + + + @@ -110,27 +164,40 @@ + + + + + + + + + + + + + @@ -148,8 +215,11 @@ + + + @@ -163,19 +233,19 @@ - + - + @@ -197,6 +267,7 @@ + @@ -214,6 +285,7 @@ + @@ -221,13 +293,19 @@ + + + + + + @@ -238,6 +316,7 @@ + @@ -278,6 +357,7 @@ + @@ -300,7 +380,6 @@ - @@ -315,7 +394,6 @@ - @@ -349,6 +427,7 @@ + @@ -356,7 +435,6 @@ - @@ -368,12 +446,14 @@ + + @@ -388,6 +468,7 @@ + @@ -416,10 +497,13 @@ + + + @@ -428,12 +512,15 @@ + + + @@ -455,21 +542,22 @@ - - + + + @@ -487,9 +575,9 @@ + - @@ -503,9 +591,10 @@ + + - @@ -515,6 +604,7 @@ + @@ -529,7 +619,9 @@ + + @@ -566,6 +658,7 @@ + @@ -576,6 +669,8 @@ + + diff --git a/UnityEngine/UnityEngine.iOS/ADBannerView.cs b/UnityEngine/UnityEngine.iOS/ADBannerView.cs new file mode 100644 index 00000000..487d1c6f --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/ADBannerView.cs @@ -0,0 +1,181 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class ADBannerView + { + public enum Layout + { + Top, + Bottom, + TopLeft = 0, + TopRight = 4, + TopCenter = 8, + BottomLeft = 1, + BottomRight = 5, + BottomCenter = 9, + CenterLeft = 2, + CenterRight = 6, + Center = 10, + Manual = -1 + } + public enum Type + { + Banner, + MediumRect + } + public delegate void BannerWasClickedDelegate(); + public delegate void BannerWasLoadedDelegate(); + private ADBannerView.Layout _layout; + private IntPtr _bannerView; + private static bool _AlwaysFalseDummy; + public static event ADBannerView.BannerWasClickedDelegate onBannerWasClicked + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Combine(ADBannerView.onBannerWasClicked, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Remove(ADBannerView.onBannerWasClicked, value); + } + } + public static event ADBannerView.BannerWasLoadedDelegate onBannerWasLoaded + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Combine(ADBannerView.onBannerWasLoaded, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Remove(ADBannerView.onBannerWasLoaded, value); + } + } + public bool loaded + { + get + { + return ADBannerView.Native_BannerAdLoaded(this._bannerView); + } + } + public bool visible + { + get + { + return ADBannerView.Native_BannerAdVisible(this._bannerView); + } + set + { + ADBannerView.Native_ShowBanner(this._bannerView, value); + } + } + public ADBannerView.Layout layout + { + get + { + return this._layout; + } + set + { + this._layout = value; + ADBannerView.Native_LayoutBanner(this._bannerView, (int)this._layout); + } + } + public Vector2 position + { + get + { + Vector2 v; + ADBannerView.Native_BannerPosition(this._bannerView, out v); + return this.OSToScreenCoords(v); + } + set + { + Vector2 pos = new Vector2(value.x / (float)Screen.width, value.y / (float)Screen.height); + ADBannerView.Native_MoveBanner(this._bannerView, pos); + } + } + public Vector2 size + { + get + { + Vector2 v; + ADBannerView.Native_BannerSize(this._bannerView, out v); + return this.OSToScreenCoords(v); + } + } + public ADBannerView(ADBannerView.Type type, ADBannerView.Layout layout) + { + if (ADBannerView._AlwaysFalseDummy) + { + ADBannerView.FireBannerWasClicked(); + ADBannerView.FireBannerWasLoaded(); + } + this._bannerView = ADBannerView.Native_CreateBanner((int)type, (int)layout); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr Native_CreateBanner(int type, int layout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ShowBanner(IntPtr view, bool show); + private static void Native_MoveBanner(IntPtr view, Vector2 pos) + { + ADBannerView.INTERNAL_CALL_Native_MoveBanner(view, ref pos); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_Native_MoveBanner(IntPtr view, ref Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_LayoutBanner(IntPtr view, int layout); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerTypeAvailable(int type); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_BannerPosition(IntPtr view, out Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_BannerSize(IntPtr view, out Vector2 pos); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerAdLoaded(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_BannerAdVisible(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_DestroyBanner(IntPtr view); + public static bool IsAvailable(ADBannerView.Type type) + { + return ADBannerView.Native_BannerTypeAvailable((int)type); + } + ~ADBannerView() + { + ADBannerView.Native_DestroyBanner(this._bannerView); + } + private Vector2 OSToScreenCoords(Vector2 v) + { + return new Vector2(v.x * (float)Screen.width, v.y * (float)Screen.height); + } + private static void FireBannerWasClicked() + { + if (ADBannerView.onBannerWasClicked != null) + { + ADBannerView.onBannerWasClicked(); + } + } + private static void FireBannerWasLoaded() + { + if (ADBannerView.onBannerWasLoaded != null) + { + ADBannerView.onBannerWasLoaded(); + } + } + } +} diff --git a/UnityEngine/UnityEngine.iOS/ADInterstitialAd.cs b/UnityEngine/UnityEngine.iOS/ADInterstitialAd.cs new file mode 100644 index 00000000..1fcff5c0 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/ADInterstitialAd.cs @@ -0,0 +1,98 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class ADInterstitialAd + { + public delegate void InterstitialWasLoadedDelegate(); + private IntPtr interstitialView; + private static bool _AlwaysFalseDummy; + public static event ADInterstitialAd.InterstitialWasLoadedDelegate onInterstitialWasLoaded + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Combine(ADInterstitialAd.onInterstitialWasLoaded, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Remove(ADInterstitialAd.onInterstitialWasLoaded, value); + } + } + public static bool isAvailable + { + get + { + return ADInterstitialAd.Native_InterstitialAvailable(); + } + } + public bool loaded + { + get + { + return ADInterstitialAd.Native_InterstitialAdLoaded(this.interstitialView); + } + } + public ADInterstitialAd(bool autoReload) + { + this.CtorImpl(autoReload); + } + public ADInterstitialAd() + { + this.CtorImpl(false); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern IntPtr Native_CreateInterstitial(bool autoReload); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ShowInterstitial(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_ReloadInterstitial(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_InterstitialAdLoaded(IntPtr view); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool Native_InterstitialAvailable(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Native_DestroyInterstitial(IntPtr view); + private void CtorImpl(bool autoReload) + { + if (ADInterstitialAd._AlwaysFalseDummy) + { + ADInterstitialAd.FireInterstitialWasLoaded(); + } + this.interstitialView = ADInterstitialAd.Native_CreateInterstitial(autoReload); + } + ~ADInterstitialAd() + { + ADInterstitialAd.Native_DestroyInterstitial(this.interstitialView); + } + public void Show() + { + if (this.loaded) + { + ADInterstitialAd.Native_ShowInterstitial(this.interstitialView); + } + else + { + Debug.Log("Calling ADInterstitialAd.Show() when the ad is not loaded"); + } + } + public void ReloadAd() + { + ADInterstitialAd.Native_ReloadInterstitial(this.interstitialView); + } + private static void FireInterstitialWasLoaded() + { + if (ADInterstitialAd.onInterstitialWasLoaded != null) + { + ADInterstitialAd.onInterstitialWasLoaded(); + } + } + } +} diff --git a/UnityEngine/UnityEngine.iOS/ActivityIndicatorStyle.cs b/UnityEngine/UnityEngine.iOS/ActivityIndicatorStyle.cs new file mode 100644 index 00000000..f0095976 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/ActivityIndicatorStyle.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine.iOS +{ + public enum ActivityIndicatorStyle + { + DontShow = -1, + WhiteLarge, + White, + Gray + } +} diff --git a/UnityEngine/UnityEngine.iOS/CalendarIdentifier.cs b/UnityEngine/UnityEngine.iOS/CalendarIdentifier.cs new file mode 100644 index 00000000..a9175461 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/CalendarIdentifier.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine.iOS +{ + public enum CalendarIdentifier + { + GregorianCalendar, + BuddhistCalendar, + ChineseCalendar, + HebrewCalendar, + IslamicCalendar, + IslamicCivilCalendar, + JapaneseCalendar, + RepublicOfChinaCalendar, + PersianCalendar, + IndianCalendar, + ISO8601Calendar + } +} diff --git a/UnityEngine/UnityEngine.iOS/CalendarUnit.cs b/UnityEngine/UnityEngine.iOS/CalendarUnit.cs new file mode 100644 index 00000000..8dc550ea --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/CalendarUnit.cs @@ -0,0 +1,18 @@ +using System; +namespace UnityEngine.iOS +{ + public enum CalendarUnit + { + Era = 2, + Year = 4, + Month = 8, + Day = 16, + Hour = 32, + Minute = 64, + Second = 128, + Week = 256, + Weekday = 512, + WeekdayOrdinal = 1024, + Quarter = 2048 + } +} diff --git a/UnityEngine/UnityEngine.iOS/Device.cs b/UnityEngine/UnityEngine.iOS/Device.cs new file mode 100644 index 00000000..2747df21 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/Device.cs @@ -0,0 +1,44 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class Device + { + public static extern DeviceGeneration generation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string systemVersion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string vendorIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string advertisingIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool advertisingTrackingEnabled + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetNoBackupFlag(string path); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetNoBackupFlag(string path); + } +} diff --git a/UnityEngine/UnityEngine.iOS/DeviceGeneration.cs b/UnityEngine/UnityEngine.iOS/DeviceGeneration.cs new file mode 100644 index 00000000..e1133c43 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/DeviceGeneration.cs @@ -0,0 +1,36 @@ +using System; +namespace UnityEngine.iOS +{ + public enum DeviceGeneration + { + Unknown, + iPhone, + iPhone3G, + iPhone3GS, + iPodTouch1Gen, + iPodTouch2Gen, + iPodTouch3Gen, + iPad1Gen, + iPhone4, + iPodTouch4Gen, + iPad2Gen, + iPhone4S, + iPad3Gen, + iPhone5, + iPodTouch5Gen, + iPadMini1Gen, + iPad4Gen, + iPhone5C, + iPhone5S, + iPadAir1, + iPad5Gen = 19, + iPadMini2Gen, + iPhone6, + iPhone6Plus, + iPadMini3Gen, + iPadAir2, + iPhoneUnknown = 10001, + iPadUnknown, + iPodTouchUnknown + } +} diff --git a/UnityEngine/UnityEngine.iOS/LocalNotification.cs b/UnityEngine/UnityEngine.iOS/LocalNotification.cs new file mode 100644 index 00000000..6682ef12 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/LocalNotification.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class LocalNotification + { + private IntPtr notificationWrapper; + private static long m_NSReferenceDateTicks; + public DateTime fireDate + { + get + { + return new DateTime((long)(this.GetFireDate() * 10000000.0) + LocalNotification.m_NSReferenceDateTicks); + } + set + { + this.SetFireDate((double)(value.ToUniversalTime().Ticks - LocalNotification.m_NSReferenceDateTicks) / 10000000.0); + } + } + public extern string timeZone + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CalendarUnit repeatInterval + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CalendarIdentifier repeatCalendar + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hasAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string alertLaunchImage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int applicationIconBadgeNumber + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern string soundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern string defaultSoundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern IDictionary userInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public LocalNotification() + { + this.InitWrapper(); + } + static LocalNotification() + { + // Note: this type is marked as 'beforefieldinit'. + DateTime dateTime = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); + LocalNotification.m_NSReferenceDateTicks = dateTime.Ticks; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern double GetFireDate(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetFireDate(double dt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~LocalNotification() + { + this.Destroy(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void InitWrapper(); + } +} diff --git a/UnityEngine/UnityEngine.iOS/NotificationServices.cs b/UnityEngine/UnityEngine.iOS/NotificationServices.cs new file mode 100644 index 00000000..1cb5facb --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/NotificationServices.cs @@ -0,0 +1,104 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class NotificationServices + { + public static extern int localNotificationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static LocalNotification[] localNotifications + { + get + { + int localNotificationCount = NotificationServices.localNotificationCount; + LocalNotification[] array = new LocalNotification[localNotificationCount]; + for (int i = 0; i < localNotificationCount; i++) + { + array[i] = NotificationServices.GetLocalNotification(i); + } + return array; + } + } + public static extern LocalNotification[] scheduledLocalNotifications + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern int remoteNotificationCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static RemoteNotification[] remoteNotifications + { + get + { + int remoteNotificationCount = NotificationServices.remoteNotificationCount; + RemoteNotification[] array = new RemoteNotification[remoteNotificationCount]; + for (int i = 0; i < remoteNotificationCount; i++) + { + array[i] = NotificationServices.GetRemoteNotification(i); + } + return array; + } + } + public static extern NotificationType enabledNotificationTypes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern byte[] deviceToken + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string registrationError + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern LocalNotification GetLocalNotification(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ScheduleLocalNotification(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PresentLocalNotificationNow(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CancelLocalNotification(LocalNotification notification); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CancelAllLocalNotifications(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern RemoteNotification GetRemoteNotification(int index); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearLocalNotifications(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ClearRemoteNotifications(); + public static void RegisterForNotifications(NotificationType notificationTypes) + { + NotificationServices.RegisterForNotifications(notificationTypes, true); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void RegisterForNotifications(NotificationType notificationTypes, bool registerForRemote); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UnregisterForRemoteNotifications(); + } +} diff --git a/UnityEngine/UnityEngine/LocalNotificationType.cs b/UnityEngine/UnityEngine.iOS/NotificationType.cs similarity index 52% rename from UnityEngine/UnityEngine/LocalNotificationType.cs rename to UnityEngine/UnityEngine.iOS/NotificationType.cs index ec352b64..bf5643be 100644 --- a/UnityEngine/UnityEngine/LocalNotificationType.cs +++ b/UnityEngine/UnityEngine.iOS/NotificationType.cs @@ -1,7 +1,7 @@ using System; -namespace UnityEngine +namespace UnityEngine.iOS { - public enum LocalNotificationType + public enum NotificationType { None, Badge, diff --git a/UnityEngine/UnityEngine.iOS/RemoteNotification.cs b/UnityEngine/UnityEngine.iOS/RemoteNotification.cs new file mode 100644 index 00000000..913bab76 --- /dev/null +++ b/UnityEngine/UnityEngine.iOS/RemoteNotification.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Runtime.CompilerServices; +namespace UnityEngine.iOS +{ + public sealed class RemoteNotification + { + private IntPtr notificationWrapper; + public extern string alertBody + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool hasAction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int applicationIconBadgeNumber + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern string soundName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern IDictionary userInfo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + private RemoteNotification() + { + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Destroy(); + ~RemoteNotification() + { + this.Destroy(); + } + } +} diff --git a/UnityEngine/UnityEngine/ADBannerView.cs b/UnityEngine/UnityEngine/ADBannerView.cs index 074e6c1b..21d83b5b 100644 --- a/UnityEngine/UnityEngine/ADBannerView.cs +++ b/UnityEngine/UnityEngine/ADBannerView.cs @@ -1,181 +1,8 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("ADBannerView class is deprecated (UnityUpgradable). Please use iOS.ADBannerView instead.", true)] public sealed class ADBannerView { - public enum Layout - { - Top, - Bottom, - TopLeft = 0, - TopRight = 4, - TopCenter = 8, - BottomLeft = 1, - BottomRight = 5, - BottomCenter = 9, - CenterLeft = 2, - CenterRight = 6, - Center = 10, - Manual = -1 - } - public enum Type - { - Banner, - MediumRect - } - public delegate void BannerWasClickedDelegate(); - public delegate void BannerWasLoadedDelegate(); - private ADBannerView.Layout _layout; - private IntPtr _bannerView; - private static bool _AlwaysFalseDummy; - public static event ADBannerView.BannerWasClickedDelegate onBannerWasClicked - { - [MethodImpl(MethodImplOptions.Synchronized)] - add - { - ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Combine(ADBannerView.onBannerWasClicked, value); - } - [MethodImpl(MethodImplOptions.Synchronized)] - remove - { - ADBannerView.onBannerWasClicked = (ADBannerView.BannerWasClickedDelegate)Delegate.Remove(ADBannerView.onBannerWasClicked, value); - } - } - public static event ADBannerView.BannerWasLoadedDelegate onBannerWasLoaded - { - [MethodImpl(MethodImplOptions.Synchronized)] - add - { - ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Combine(ADBannerView.onBannerWasLoaded, value); - } - [MethodImpl(MethodImplOptions.Synchronized)] - remove - { - ADBannerView.onBannerWasLoaded = (ADBannerView.BannerWasLoadedDelegate)Delegate.Remove(ADBannerView.onBannerWasLoaded, value); - } - } - public bool loaded - { - get - { - return ADBannerView.Native_BannerAdLoaded(this._bannerView); - } - } - public bool visible - { - get - { - return ADBannerView.Native_BannerAdVisible(this._bannerView); - } - set - { - ADBannerView.Native_ShowBanner(this._bannerView, value); - } - } - public ADBannerView.Layout layout - { - get - { - return this._layout; - } - set - { - this._layout = value; - ADBannerView.Native_LayoutBanner(this._bannerView, (int)this._layout); - } - } - public Vector2 position - { - get - { - Vector2 v; - ADBannerView.Native_BannerPosition(this._bannerView, out v); - return this.OSToScreenCoords(v); - } - set - { - Vector2 pos = new Vector2(value.x / (float)Screen.width, value.y / (float)Screen.height); - ADBannerView.Native_MoveBanner(this._bannerView, pos); - } - } - public Vector2 size - { - get - { - Vector2 v; - ADBannerView.Native_BannerSize(this._bannerView, out v); - return this.OSToScreenCoords(v); - } - } - public ADBannerView(ADBannerView.Type type, ADBannerView.Layout layout) - { - if (ADBannerView._AlwaysFalseDummy) - { - ADBannerView.FireBannerWasClicked(); - ADBannerView.FireBannerWasLoaded(); - } - this._bannerView = ADBannerView.Native_CreateBanner((int)type, (int)layout); - } - public static bool IsAvailable(ADBannerView.Type type) - { - return ADBannerView.Native_BannerTypeAvailable((int)type); - } - ~ADBannerView() - { - ADBannerView.Native_DestroyBanner(this._bannerView); - } - private Vector2 OSToScreenCoords(Vector2 v) - { - return new Vector2(v.x * (float)Screen.width, v.y * (float)Screen.height); - } - private static void FireBannerWasClicked() - { - if (ADBannerView.onBannerWasClicked != null) - { - ADBannerView.onBannerWasClicked(); - } - } - private static void FireBannerWasLoaded() - { - if (ADBannerView.onBannerWasLoaded != null) - { - ADBannerView.onBannerWasLoaded(); - } - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern IntPtr Native_CreateBanner(int type, int layout); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_ShowBanner(IntPtr view, bool show); - private static void Native_MoveBanner(IntPtr view, Vector2 pos) - { - ADBannerView.INTERNAL_CALL_Native_MoveBanner(view, ref pos); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Native_MoveBanner(IntPtr view, ref Vector2 pos); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_LayoutBanner(IntPtr view, int layout); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Native_BannerTypeAvailable(int type); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_BannerPosition(IntPtr view, out Vector2 pos); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_BannerSize(IntPtr view, out Vector2 pos); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Native_BannerAdLoaded(IntPtr view); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Native_BannerAdVisible(IntPtr view); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_DestroyBanner(IntPtr view); } } diff --git a/UnityEngine/UnityEngine/ADInterstitialAd.cs b/UnityEngine/UnityEngine/ADInterstitialAd.cs index d5b0e6e2..ce6093ad 100644 --- a/UnityEngine/UnityEngine/ADInterstitialAd.cs +++ b/UnityEngine/UnityEngine/ADInterstitialAd.cs @@ -1,98 +1,8 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("ADInterstitialAd class is deprecated (UnityUpgradable). Please use iOS.ADInterstitialAd instead.", true)] public sealed class ADInterstitialAd { - public delegate void InterstitialWasLoadedDelegate(); - private IntPtr interstitialView; - private static bool _AlwaysFalseDummy; - public static event ADInterstitialAd.InterstitialWasLoadedDelegate onInterstitialWasLoaded - { - [MethodImpl(MethodImplOptions.Synchronized)] - add - { - ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Combine(ADInterstitialAd.onInterstitialWasLoaded, value); - } - [MethodImpl(MethodImplOptions.Synchronized)] - remove - { - ADInterstitialAd.onInterstitialWasLoaded = (ADInterstitialAd.InterstitialWasLoadedDelegate)Delegate.Remove(ADInterstitialAd.onInterstitialWasLoaded, value); - } - } - public static bool isAvailable - { - get - { - return ADInterstitialAd.Native_InterstitialAvailable(); - } - } - public bool loaded - { - get - { - return ADInterstitialAd.Native_InterstitialAdLoaded(this.interstitialView); - } - } - public ADInterstitialAd(bool autoReload) - { - this.CtorImpl(autoReload); - } - public ADInterstitialAd() - { - this.CtorImpl(false); - } - private void CtorImpl(bool autoReload) - { - if (ADInterstitialAd._AlwaysFalseDummy) - { - ADInterstitialAd.FireInterstitialWasLoaded(); - } - this.interstitialView = ADInterstitialAd.Native_CreateInterstitial(autoReload); - } - ~ADInterstitialAd() - { - ADInterstitialAd.Native_DestroyInterstitial(this.interstitialView); - } - public void Show() - { - if (this.loaded) - { - ADInterstitialAd.Native_ShowInterstitial(this.interstitialView); - } - else - { - Debug.Log("Calling ADInterstitialAd.Show() when the ad is not loaded"); - } - } - public void ReloadAd() - { - ADInterstitialAd.Native_ReloadInterstitial(this.interstitialView); - } - private static void FireInterstitialWasLoaded() - { - if (ADInterstitialAd.onInterstitialWasLoaded != null) - { - ADInterstitialAd.onInterstitialWasLoaded(); - } - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern IntPtr Native_CreateInterstitial(bool autoReload); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_ShowInterstitial(IntPtr view); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_ReloadInterstitial(IntPtr view); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Native_InterstitialAdLoaded(IntPtr view); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool Native_InterstitialAvailable(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Native_DestroyInterstitial(IntPtr view); } } diff --git a/UnityEngine/UnityEngine/AndroidJavaClass.cs b/UnityEngine/UnityEngine/AndroidJavaClass.cs index 7277ed18..fe96385e 100644 --- a/UnityEngine/UnityEngine/AndroidJavaClass.cs +++ b/UnityEngine/UnityEngine/AndroidJavaClass.cs @@ -3,6 +3,10 @@ namespace UnityEngine { public class AndroidJavaClass : AndroidJavaObject { + public AndroidJavaClass(string className) + { + this._AndroidJavaClass(className); + } internal AndroidJavaClass(IntPtr jclass) { if (jclass == IntPtr.Zero) @@ -12,10 +16,6 @@ internal AndroidJavaClass(IntPtr jclass) this.m_jclass = AndroidJNI.NewGlobalRef(jclass); this.m_jobject = IntPtr.Zero; } - public AndroidJavaClass(string className) - { - this._AndroidJavaClass(className); - } private void _AndroidJavaClass(string className) { base.DebugPrint("Creating AndroidJavaClass from " + className); diff --git a/UnityEngine/UnityEngine/AndroidJavaObject.cs b/UnityEngine/UnityEngine/AndroidJavaObject.cs index 37709e8a..a40bb048 100644 --- a/UnityEngine/UnityEngine/AndroidJavaObject.cs +++ b/UnityEngine/UnityEngine/AndroidJavaObject.cs @@ -20,6 +20,10 @@ protected static AndroidJavaClass JavaLangClass return AndroidJavaObject.s_JavaLangClass; } } + public AndroidJavaObject(string className, params object[] args) : this() + { + this._AndroidJavaObject(className, args); + } internal AndroidJavaObject(IntPtr jobject) : this() { if (jobject == IntPtr.Zero) @@ -34,9 +38,49 @@ internal AndroidJavaObject(IntPtr jobject) : this() internal AndroidJavaObject() { } - public AndroidJavaObject(string className, params object[] args) : this() + public void Dispose() { - this._AndroidJavaObject(className, args); + this._Dispose(); + } + public void Call(string methodName, params object[] args) + { + this._Call(methodName, args); + } + public void CallStatic(string methodName, params object[] args) + { + this._CallStatic(methodName, args); + } + public FieldType Get(string fieldName) + { + return this._Get(fieldName); + } + public void Set(string fieldName, FieldType val) + { + this._Set(fieldName, val); + } + public FieldType GetStatic(string fieldName) + { + return this._GetStatic(fieldName); + } + public void SetStatic(string fieldName, FieldType val) + { + this._SetStatic(fieldName, val); + } + public IntPtr GetRawObject() + { + return this._GetRawObject(); + } + public IntPtr GetRawClass() + { + return this._GetRawClass(); + } + public ReturnType Call(string methodName, params object[] args) + { + return this._Call(methodName, args); + } + public ReturnType CallStatic(string methodName, params object[] args) + { + return this._CallStatic(methodName, args); } protected void DebugPrint(string msg) { @@ -714,49 +758,5 @@ protected static AndroidJavaObject FindClass(string name) name.Replace('/', '.') }); } - public void Dispose() - { - this._Dispose(); - } - public void Call(string methodName, params object[] args) - { - this._Call(methodName, args); - } - public void CallStatic(string methodName, params object[] args) - { - this._CallStatic(methodName, args); - } - public FieldType Get(string fieldName) - { - return this._Get(fieldName); - } - public void Set(string fieldName, FieldType val) - { - this._Set(fieldName, val); - } - public FieldType GetStatic(string fieldName) - { - return this._GetStatic(fieldName); - } - public void SetStatic(string fieldName, FieldType val) - { - this._SetStatic(fieldName, val); - } - public IntPtr GetRawObject() - { - return this._GetRawObject(); - } - public IntPtr GetRawClass() - { - return this._GetRawClass(); - } - public ReturnType Call(string methodName, params object[] args) - { - return this._Call(methodName, args); - } - public ReturnType CallStatic(string methodName, params object[] args) - { - return this._CallStatic(methodName, args); - } } } diff --git a/UnityEngine/UnityEngine/AnimationClip.cs b/UnityEngine/UnityEngine/AnimationClip.cs index b43e93ec..f0eb84e5 100644 --- a/UnityEngine/UnityEngine/AnimationClip.cs +++ b/UnityEngine/UnityEngine/AnimationClip.cs @@ -53,12 +53,41 @@ public Bounds localBounds this.INTERNAL_set_localBounds(ref value); } } + public new extern bool legacy + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool humanMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public AnimationEvent[] events + { + get + { + return (AnimationEvent[])this.GetEventsInternal(); + } + set + { + this.SetEventsInternal(value); + } + } public AnimationClip() { AnimationClip.Internal_CreateAnimationClip(this); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SampleAnimation(GameObject go, float time); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_CreateAnimationClip([Writable] AnimationClip self); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -79,12 +108,22 @@ public void ClearCurves() private static extern void INTERNAL_CALL_ClearCurves(AnimationClip self); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void AddEvent(AnimationEvent evt); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_localBounds(out Bounds value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_set_localBounds(ref Bounds value); + public void AddEvent(AnimationEvent evt) + { + this.AddEventInternal(evt); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void AddEventInternal(object evt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetEventsInternal(Array value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Array GetEventsInternal(); } } diff --git a/UnityEngine/UnityEngine/AnimationEvent.cs b/UnityEngine/UnityEngine/AnimationEvent.cs index f8699995..877c01f8 100644 --- a/UnityEngine/UnityEngine/AnimationEvent.cs +++ b/UnityEngine/UnityEngine/AnimationEvent.cs @@ -1,110 +1,169 @@ using System; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnityEngine { + [Serializable] [StructLayout(LayoutKind.Sequential)] public sealed class AnimationEvent { - [NotRenamed] - internal IntPtr m_Ptr; - private int m_OwnsData; + internal float m_Time; + internal string m_FunctionName; + internal string m_StringParameter; + internal Object m_ObjectReferenceParameter; + internal float m_FloatParameter; + internal int m_IntParameter; + internal int m_MessageOptions; + internal AnimationEventSource m_Source; + internal AnimationState m_StateSender; + internal AnimatorStateInfo m_AnimatorStateInfo; + internal AnimatorClipInfo m_AnimatorClipInfo; [Obsolete("Use stringParameter instead")] - public extern string data + public string data { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_StringParameter; + } + set + { + this.m_StringParameter = value; + } + } + public string stringParameter + { + get + { + return this.m_StringParameter; + } + set + { + this.m_StringParameter = value; + } + } + public float floatParameter + { + get + { + return this.m_FloatParameter; + } + set + { + this.m_FloatParameter = value; + } } - public extern string stringParameter + public int intParameter { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_IntParameter; + } + set + { + this.m_IntParameter = value; + } } - public extern float floatParameter + public Object objectReferenceParameter { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_ObjectReferenceParameter; + } + set + { + this.m_ObjectReferenceParameter = value; + } } - public extern int intParameter + public string functionName { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_FunctionName; + } + set + { + this.m_FunctionName = value; + } } - public extern Object objectReferenceParameter + public float time { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_Time; + } + set + { + this.m_Time = value; + } } - public extern string functionName + public SendMessageOptions messageOptions { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return (SendMessageOptions)this.m_MessageOptions; + } + set + { + this.m_MessageOptions = (int)value; + } } - public extern float time + public bool isFiredByLegacy { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_Source == AnimationEventSource.Legacy; + } } - public extern SendMessageOptions messageOptions + public bool isFiredByAnimator { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return this.m_Source == AnimationEventSource.Animator; + } } - public extern AnimationState animationState + public AnimationState animationState { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + if (!this.isFiredByLegacy) + { + Debug.LogError("AnimationEvent was not fired by Animation component, you shouldn't use AnimationEvent.animationState"); + } + return this.m_StateSender; + } } - public AnimationEvent() + public AnimatorStateInfo animatorStateInfo { - this.m_OwnsData = 1; - this.Create(); + get + { + if (!this.isFiredByAnimator) + { + Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorStateInfo"); + } + return this.m_AnimatorStateInfo; + } } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Create(); - ~AnimationEvent() + public AnimatorClipInfo animatorClipInfo { - if (this.m_OwnsData != 0) + get { - this.Destroy(); + if (!this.isFiredByAnimator) + { + Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorClipInfo"); + } + return this.m_AnimatorClipInfo; } } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Destroy(); + public AnimationEvent() + { + this.m_Time = 0f; + this.m_FunctionName = string.Empty; + this.m_StringParameter = string.Empty; + this.m_ObjectReferenceParameter = null; + this.m_FloatParameter = 0f; + this.m_IntParameter = 0; + this.m_MessageOptions = 0; + this.m_Source = AnimationEventSource.NoSource; + this.m_StateSender = null; + } } } diff --git a/UnityEngine/UnityEngine/AnimationEventSource.cs b/UnityEngine/UnityEngine/AnimationEventSource.cs new file mode 100644 index 00000000..70b65bbd --- /dev/null +++ b/UnityEngine/UnityEngine/AnimationEventSource.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal enum AnimationEventSource + { + NoSource, + Legacy, + Animator + } +} diff --git a/UnityEngine/UnityEngine/AnimationInfo.cs b/UnityEngine/UnityEngine/AnimationInfo.cs index c73ad25b..8cce2f05 100644 --- a/UnityEngine/UnityEngine/AnimationInfo.cs +++ b/UnityEngine/UnityEngine/AnimationInfo.cs @@ -1,27 +1,8 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("Use AnimatorClipInfo instead (UnityUpgradable)", true)] public struct AnimationInfo { - private int m_ClipInstanceID; - private float m_Weight; - public AnimationClip clip - { - get - { - return (this.m_ClipInstanceID == 0) ? null : AnimationInfo.ClipInstanceToScriptingObject(this.m_ClipInstanceID); - } - } - public float weight - { - get - { - return this.m_Weight; - } - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern AnimationClip ClipInstanceToScriptingObject(int instanceID); } } diff --git a/UnityEngine/UnityEngine/Animator.cs b/UnityEngine/UnityEngine/Animator.cs index 86f438ab..fda52568 100644 --- a/UnityEngine/UnityEngine/Animator.cs +++ b/UnityEngine/UnityEngine/Animator.cs @@ -23,6 +23,12 @@ public extern bool hasRootMotion [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal extern bool isRootPositionOrRotationControlledByCurves + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern float humanScale { [WrapperlessIcall] @@ -41,6 +47,18 @@ public extern Quaternion deltaRotation [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern Vector3 velocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector3 angularVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public Vector3 rootPosition { get @@ -76,7 +94,16 @@ public extern bool applyRootMotion [MethodImpl(MethodImplOptions.InternalCall)] set; } - [Obsolete("Use AnimationMode.updateMode instead")] + public extern bool linearVelocityBlending + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Use Animator.updateMode instead")] public bool animatePhysics { get @@ -159,6 +186,12 @@ public extern int layerCount [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern AnimatorControllerParameter[] parameters + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern float feetPivotActive { [WrapperlessIcall] @@ -249,6 +282,12 @@ public extern float recorderStopTime [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern AnimatorRecorderMode recorderMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern RuntimeAnimatorController runtimeAnimatorController { [WrapperlessIcall] @@ -422,48 +461,126 @@ public bool IsParameterControlledByCurve(int id) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_set_bodyRotation(ref Quaternion value); + public Vector3 GetIKPosition(AvatarIKGoal goal) + { + this.CheckIfInIKPass(); + return this.GetIKPositionInternal(goal); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern Vector3 GetIKPosition(AvatarIKGoal goal); + internal extern Vector3 GetIKPositionInternal(AvatarIKGoal goal); public void SetIKPosition(AvatarIKGoal goal, Vector3 goalPosition) { - Animator.INTERNAL_CALL_SetIKPosition(this, goal, ref goalPosition); + this.CheckIfInIKPass(); + this.SetIKPositionInternal(goal, goalPosition); + } + internal void SetIKPositionInternal(AvatarIKGoal goal, Vector3 goalPosition) + { + Animator.INTERNAL_CALL_SetIKPositionInternal(this, goal, ref goalPosition); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetIKPosition(Animator self, AvatarIKGoal goal, ref Vector3 goalPosition); + private static extern void INTERNAL_CALL_SetIKPositionInternal(Animator self, AvatarIKGoal goal, ref Vector3 goalPosition); + public Quaternion GetIKRotation(AvatarIKGoal goal) + { + this.CheckIfInIKPass(); + return this.GetIKRotationInternal(goal); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern Quaternion GetIKRotation(AvatarIKGoal goal); + internal extern Quaternion GetIKRotationInternal(AvatarIKGoal goal); public void SetIKRotation(AvatarIKGoal goal, Quaternion goalRotation) { - Animator.INTERNAL_CALL_SetIKRotation(this, goal, ref goalRotation); + this.CheckIfInIKPass(); + this.SetIKRotationInternal(goal, goalRotation); + } + internal void SetIKRotationInternal(AvatarIKGoal goal, Quaternion goalRotation) + { + Animator.INTERNAL_CALL_SetIKRotationInternal(this, goal, ref goalRotation); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetIKRotation(Animator self, AvatarIKGoal goal, ref Quaternion goalRotation); + private static extern void INTERNAL_CALL_SetIKRotationInternal(Animator self, AvatarIKGoal goal, ref Quaternion goalRotation); + public float GetIKPositionWeight(AvatarIKGoal goal) + { + this.CheckIfInIKPass(); + return this.GetIKPositionWeightInternal(goal); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern float GetIKPositionWeight(AvatarIKGoal goal); + internal extern float GetIKPositionWeightInternal(AvatarIKGoal goal); + public void SetIKPositionWeight(AvatarIKGoal goal, float value) + { + this.CheckIfInIKPass(); + this.SetIKPositionWeightInternal(goal, value); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetIKPositionWeight(AvatarIKGoal goal, float value); + internal extern void SetIKPositionWeightInternal(AvatarIKGoal goal, float value); + public float GetIKRotationWeight(AvatarIKGoal goal) + { + this.CheckIfInIKPass(); + return this.GetIKRotationWeightInternal(goal); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern float GetIKRotationWeight(AvatarIKGoal goal); + internal extern float GetIKRotationWeightInternal(AvatarIKGoal goal); + public void SetIKRotationWeight(AvatarIKGoal goal, float value) + { + this.CheckIfInIKPass(); + this.SetIKRotationWeightInternal(goal, value); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetIKRotationWeight(AvatarIKGoal goal, float value); - public void SetLookAtPosition(Vector3 lookAtPosition) + internal extern void SetIKRotationWeightInternal(AvatarIKGoal goal, float value); + public Vector3 GetIKHintPosition(AvatarIKHint hint) { - Animator.INTERNAL_CALL_SetLookAtPosition(this, ref lookAtPosition); + this.CheckIfInIKPass(); + return this.GetIKHintPositionInternal(hint); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_SetLookAtPosition(Animator self, ref Vector3 lookAtPosition); + internal extern Vector3 GetIKHintPositionInternal(AvatarIKHint hint); + public void SetIKHintPosition(AvatarIKHint hint, Vector3 hintPosition) + { + this.CheckIfInIKPass(); + this.SetIKHintPositionInternal(hint, hintPosition); + } + internal void SetIKHintPositionInternal(AvatarIKHint hint, Vector3 hintPosition) + { + Animator.INTERNAL_CALL_SetIKHintPositionInternal(this, hint, ref hintPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetIKHintPositionInternal(Animator self, AvatarIKHint hint, ref Vector3 hintPosition); + public float GetIKHintPositionWeight(AvatarIKHint hint) + { + this.CheckIfInIKPass(); + return this.GetHintWeightPositionInternal(hint); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern float GetHintWeightPositionInternal(AvatarIKHint hint); + public void SetIKHintPositionWeight(AvatarIKHint hint, float value) + { + this.CheckIfInIKPass(); + this.SetIKHintPositionWeightInternal(hint, value); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetLookAtWeight(float weight, [DefaultValue("0.00f")] float bodyWeight, [DefaultValue("1.00f")] float headWeight, [DefaultValue("0.00f")] float eyesWeight, [DefaultValue("0.50f")] float clampWeight); + internal extern void SetIKHintPositionWeightInternal(AvatarIKHint hint, float value); + public void SetLookAtPosition(Vector3 lookAtPosition) + { + this.CheckIfInIKPass(); + this.SetLookAtPositionInternal(lookAtPosition); + } + internal void SetLookAtPositionInternal(Vector3 lookAtPosition) + { + Animator.INTERNAL_CALL_SetLookAtPositionInternal(this, ref lookAtPosition); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetLookAtPositionInternal(Animator self, ref Vector3 lookAtPosition); [ExcludeFromDocs] public void SetLookAtWeight(float weight, float bodyWeight, float headWeight, float eyesWeight) { @@ -494,11 +611,79 @@ public void SetLookAtWeight(float weight) float bodyWeight = 0f; this.SetLookAtWeight(weight, bodyWeight, headWeight, eyesWeight, clampWeight); } + public void SetLookAtWeight(float weight, [DefaultValue("0.00f")] float bodyWeight, [DefaultValue("1.00f")] float headWeight, [DefaultValue("0.00f")] float eyesWeight, [DefaultValue("0.50f")] float clampWeight) + { + this.CheckIfInIKPass(); + this.SetLookAtWeightInternal(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void SetLookAtWeightInternal(float weight, [DefaultValue("0.00f")] float bodyWeight, [DefaultValue("1.00f")] float headWeight, [DefaultValue("0.00f")] float eyesWeight, [DefaultValue("0.50f")] float clampWeight); + [ExcludeFromDocs] + internal void SetLookAtWeightInternal(float weight, float bodyWeight, float headWeight, float eyesWeight) + { + float clampWeight = 0.5f; + this.SetLookAtWeightInternal(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + internal void SetLookAtWeightInternal(float weight, float bodyWeight, float headWeight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + this.SetLookAtWeightInternal(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + internal void SetLookAtWeightInternal(float weight, float bodyWeight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + float headWeight = 1f; + this.SetLookAtWeightInternal(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [ExcludeFromDocs] + internal void SetLookAtWeightInternal(float weight) + { + float clampWeight = 0.5f; + float eyesWeight = 0f; + float headWeight = 1f; + float bodyWeight = 0f; + this.SetLookAtWeightInternal(weight, bodyWeight, headWeight, eyesWeight, clampWeight); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern ScriptableObject GetBehaviour(Type type); + public T GetBehaviour() where T : StateMachineBehaviour + { + return this.GetBehaviour(typeof(T)) as T; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern ScriptableObject[] GetBehaviours(Type type); + internal static T[] ConvertStateMachineBehaviour(ScriptableObject[] rawObjects) where T : StateMachineBehaviour + { + if (rawObjects == null) + { + return null; + } + T[] array = new T[rawObjects.Length]; + for (int i = 0; i < array.Length; i++) + { + array[i] = (T)((object)rawObjects[i]); + } + return array; + } + public T[] GetBehaviours() where T : StateMachineBehaviour + { + return Animator.ConvertStateMachineBehaviour(this.GetBehaviours(typeof(T))); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern string GetLayerName(int layerIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetLayerIndex(string layerName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetLayerWeight(int layerIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -512,12 +697,18 @@ public void SetLookAtWeight(float weight) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern AnimatorTransitionInfo GetAnimatorTransitionInfo(int layerIndex); + [Obsolete("GetCurrentAnimationClipState is obsolete. Use GetCurrentAnimatorClipInfo instead (UnityUpgradable).", true), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorClipInfo[] GetCurrentAnimationClipState(int layerIndex); + [Obsolete("GetNextAnimationClipState is obsolete. Use GetNextAnimatorClipInfo instead (UnityUpgradable).", true), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern AnimatorClipInfo[] GetNextAnimationClipState(int layerIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern AnimationInfo[] GetCurrentAnimationClipState(int layerIndex); + public extern AnimatorClipInfo[] GetCurrentAnimatorClipInfo(int layerIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern AnimationInfo[] GetNextAnimationClipState(int layerIndex); + public extern AnimatorClipInfo[] GetNextAnimatorClipInfo(int layerIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern bool IsInTransition(int layerIndex); @@ -640,10 +831,23 @@ public void Play(int stateNameHash) public extern void StopRecording(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool HasState(int layerIndex, int stateID); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern int StringToHash(string name); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal extern string GetStats(); + private void CheckIfInIKPass() + { + if (this.logWarnings && !this.CheckIfInIKPassInternal()) + { + Debug.LogWarning("Setting and getting IK Goals should only be done in OnAnimatorIK or OnStateIK"); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool CheckIfInIKPassInternal(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetFloatString(string name, float value); @@ -722,6 +926,9 @@ public void Play(int stateNameHash) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal extern string GetNextStateName(int layerIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern string ResolveHash(int hash); [Obsolete("GetVector is deprecated.")] public Vector3 GetVector(string name) { diff --git a/UnityEngine/UnityEngine/AnimatorClipInfo.cs b/UnityEngine/UnityEngine/AnimatorClipInfo.cs new file mode 100644 index 00000000..a346daa6 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorClipInfo.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct AnimatorClipInfo + { + private int m_ClipInstanceID; + private float m_Weight; + public AnimationClip clip + { + get + { + return (this.m_ClipInstanceID == 0) ? null : AnimatorClipInfo.ClipInstanceToScriptingObject(this.m_ClipInstanceID); + } + } + public float weight + { + get + { + return this.m_Weight; + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern AnimationClip ClipInstanceToScriptingObject(int instanceID); + } +} diff --git a/UnityEngine/UnityEngine/AnimatorControllerParameter.cs b/UnityEngine/UnityEngine/AnimatorControllerParameter.cs new file mode 100644 index 00000000..f1a05646 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorControllerParameter.cs @@ -0,0 +1,83 @@ +using System; +namespace UnityEngine +{ + public sealed class AnimatorControllerParameter + { + internal string m_Name = string.Empty; + internal AnimatorControllerParameterType m_Type; + internal float m_DefaultFloat; + internal int m_DefaultInt; + internal bool m_DefaultBool; + public string name + { + get + { + return this.m_Name; + } + set + { + this.m_Name = value; + } + } + public int nameHash + { + get + { + return Animator.StringToHash(this.m_Name); + } + } + public AnimatorControllerParameterType type + { + get + { + return this.m_Type; + } + set + { + this.m_Type = value; + } + } + public float defaultFloat + { + get + { + return this.m_DefaultFloat; + } + set + { + this.m_DefaultFloat = value; + } + } + public int defaultInt + { + get + { + return this.m_DefaultInt; + } + set + { + this.m_DefaultInt = value; + } + } + public bool defaultBool + { + get + { + return this.m_DefaultBool; + } + set + { + this.m_DefaultBool = value; + } + } + public override bool Equals(object o) + { + AnimatorControllerParameter animatorControllerParameter = o as AnimatorControllerParameter; + return animatorControllerParameter != null && this.m_Name == animatorControllerParameter.m_Name && this.m_Type == animatorControllerParameter.m_Type && this.m_DefaultFloat == animatorControllerParameter.m_DefaultFloat && this.m_DefaultInt == animatorControllerParameter.m_DefaultInt && this.m_DefaultBool == animatorControllerParameter.m_DefaultBool; + } + public override int GetHashCode() + { + return this.name.GetHashCode(); + } + } +} diff --git a/UnityEngine/UnityEngine/AnimatorControllerParameterType.cs b/UnityEngine/UnityEngine/AnimatorControllerParameterType.cs new file mode 100644 index 00000000..10f61642 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorControllerParameterType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum AnimatorControllerParameterType + { + Float = 1, + Int = 3, + Bool, + Trigger = 9 + } +} diff --git a/UnityEngine/UnityEngine/AnimatorCullingMode.cs b/UnityEngine/UnityEngine/AnimatorCullingMode.cs index 7a5fe2b9..f0b77d6f 100644 --- a/UnityEngine/UnityEngine/AnimatorCullingMode.cs +++ b/UnityEngine/UnityEngine/AnimatorCullingMode.cs @@ -4,6 +4,8 @@ namespace UnityEngine public enum AnimatorCullingMode { AlwaysAnimate, - BasedOnRenderers + CullUpdateTransforms, + CullCompletely, + BasedOnRenderers = 1 } } diff --git a/UnityEngine/UnityEngine/AnimatorOverrideController.cs b/UnityEngine/UnityEngine/AnimatorOverrideController.cs index cfef4d84..86f665f1 100644 --- a/UnityEngine/UnityEngine/AnimatorOverrideController.cs +++ b/UnityEngine/UnityEngine/AnimatorOverrideController.cs @@ -43,18 +43,15 @@ public AnimationClipPair[] clips get { AnimationClip[] array = this.GetOriginalClips(); - if (this.ShouldHideDuplicateOriginalClips()) + Dictionary dictionary = new Dictionary(array.Length); + AnimationClip[] array2 = array; + for (int i = 0; i < array2.Length; i++) { - Dictionary dictionary = new Dictionary(array.Length); - AnimationClip[] array2 = array; - for (int i = 0; i < array2.Length; i++) - { - AnimationClip key = array2[i]; - dictionary[key] = true; - } - array = new AnimationClip[dictionary.Count]; - dictionary.Keys.CopyTo(array, 0); + AnimationClip key = array2[i]; + dictionary[key] = true; } + array = new AnimationClip[dictionary.Count]; + dictionary.Keys.CopyTo(array, 0); AnimationClipPair[] array3 = new AnimationClipPair[array.Length]; for (int j = 0; j < array.Length; j++) { @@ -100,15 +97,12 @@ internal static void OnInvalidateOverrideController(AnimatorOverrideController c } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool ShouldHideDuplicateOriginalClips(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] private extern AnimationClip[] GetOriginalClips(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern AnimationClip[] GetOverrideClips(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void PerformOverrideClipListCleanup(); + internal extern void PerformOverrideClipListCleanup(); } } diff --git a/UnityEngine/UnityEngine/AnimatorRecorderMode.cs b/UnityEngine/UnityEngine/AnimatorRecorderMode.cs new file mode 100644 index 00000000..30940dc2 --- /dev/null +++ b/UnityEngine/UnityEngine/AnimatorRecorderMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AnimatorRecorderMode + { + Offline, + Playback, + Record + } +} diff --git a/UnityEngine/UnityEngine/AnimatorStateInfo.cs b/UnityEngine/UnityEngine/AnimatorStateInfo.cs index 291c5eeb..d3deb00c 100644 --- a/UnityEngine/UnityEngine/AnimatorStateInfo.cs +++ b/UnityEngine/UnityEngine/AnimatorStateInfo.cs @@ -5,10 +5,19 @@ public struct AnimatorStateInfo { private int m_Name; private int m_Path; + private int m_FullPath; private float m_NormalizedTime; private float m_Length; private int m_Tag; private int m_Loop; + public int fullPathHash + { + get + { + return this.m_FullPath; + } + } + [Obsolete("Use AnimatorStateInfo.fullPathHash instead.")] public int nameHash { get @@ -16,6 +25,13 @@ public int nameHash return this.m_Path; } } + public int shortNameHash + { + get + { + return this.m_Name; + } + } public float normalizedTime { get @@ -47,7 +63,7 @@ public bool loop public bool IsName(string name) { int num = Animator.StringToHash(name); - return num == this.m_Name || num == this.m_Path; + return num == this.m_FullPath || num == this.m_Name || num == this.m_Path; } public bool IsTag(string tag) { diff --git a/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs b/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs index be4cba1f..a9c99620 100644 --- a/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs +++ b/UnityEngine/UnityEngine/AnimatorTransitionInfo.cs @@ -3,9 +3,19 @@ namespace UnityEngine { public struct AnimatorTransitionInfo { - private int m_Name; + private int m_FullPath; private int m_UserName; + private int m_Name; private float m_NormalizedTime; + private bool m_AnyState; + private int m_TransitionType; + public int fullPathHash + { + get + { + return this.m_FullPath; + } + } public int nameHash { get @@ -27,9 +37,30 @@ public float normalizedTime return this.m_NormalizedTime; } } + public bool anyState + { + get + { + return this.m_AnyState; + } + } + internal bool entry + { + get + { + return (this.m_TransitionType & 2) != 0; + } + } + internal bool exit + { + get + { + return (this.m_TransitionType & 4) != 0; + } + } public bool IsName(string name) { - return Animator.StringToHash(name) == this.m_Name; + return Animator.StringToHash(name) == this.m_Name || Animator.StringToHash(name) == this.m_FullPath; } public bool IsUserName(string name) { diff --git a/UnityEngine/UnityEngine/Application.cs b/UnityEngine/UnityEngine/Application.cs index e310f7f2..1c660b7a 100644 --- a/UnityEngine/UnityEngine/Application.cs +++ b/UnityEngine/UnityEngine/Application.cs @@ -10,7 +10,33 @@ namespace UnityEngine public sealed class Application { public delegate void LogCallback(string condition, string stackTrace, LogType type); - private static volatile Application.LogCallback s_LogCallback; + private static Application.LogCallback s_LogCallbackHandler; + private static Application.LogCallback s_LogCallbackHandlerThreaded; + private static volatile Application.LogCallback s_RegisterLogCallbackDeprecated; + public static event Application.LogCallback logMessageReceived + { + add + { + Application.s_LogCallbackHandler = (Application.LogCallback)Delegate.Combine(Application.s_LogCallbackHandler, value); + Application.SetLogCallbackDefined(true, Application.s_LogCallbackHandlerThreaded != null); + } + remove + { + Application.s_LogCallbackHandler = (Application.LogCallback)Delegate.Remove(Application.s_LogCallbackHandler, value); + } + } + public static event Application.LogCallback logMessageReceivedThreaded + { + add + { + Application.s_LogCallbackHandlerThreaded = (Application.LogCallback)Delegate.Combine(Application.s_LogCallbackHandlerThreaded, value); + Application.SetLogCallbackDefined(true, true); + } + remove + { + Application.s_LogCallbackHandlerThreaded = (Application.LogCallback)Delegate.Remove(Application.s_LogCallbackHandlerThreaded, value); + } + } public static extern int loadedLevel { [WrapperlessIcall] @@ -135,7 +161,7 @@ public static extern string absoluteURL [MethodImpl(MethodImplOptions.InternalCall)] get; } - [Obsolete("Please use absoluteURL instead")] + [Obsolete("absoluteUrl is deprecated (UnityUpgradable). Please use absoluteURL instead.", true)] public static string absoluteUrl { get @@ -149,6 +175,48 @@ public static extern string unityVersion [MethodImpl(MethodImplOptions.InternalCall)] get; } + public static extern string version + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string bundleIdentifier + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ApplicationInstallMode installMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern ApplicationSandboxType sandboxType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string productName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string companyName + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern string cloudProjectId + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static extern bool webSecurityEnabled { [WrapperlessIcall] @@ -203,6 +271,12 @@ public static extern bool genuineCheckAvailable [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal static extern bool submitAnalytics + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Quit(); @@ -388,21 +462,23 @@ public static void ExternalEval(string script) [Obsolete("For internal use only"), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CommitSuicide(int mode); - public static void RegisterLogCallback(Application.LogCallback handler) - { - Application.s_LogCallback = handler; - Application.SetLogCallbackDefined(handler != null, false); - } - public static void RegisterLogCallbackThreaded(Application.LogCallback handler) - { - Application.s_LogCallback = handler; - Application.SetLogCallbackDefined(handler != null, true); - } - private static void CallLogCallback(string logString, string stackTrace, LogType type) + private static void CallLogCallback(string logString, string stackTrace, LogType type, bool invokedOnMainThread) { - if (Application.s_LogCallback != null) + if (invokedOnMainThread) + { + Application.LogCallback logCallback = Application.s_LogCallbackHandler; + if (logCallback != null) + { + logCallback(logString, stackTrace, type); + } + } + if (!invokedOnMainThread) { - Application.s_LogCallback(logString, stackTrace, type); + Application.LogCallback logCallback2 = Application.s_LogCallbackHandlerThreaded; + if (logCallback2 != null) + { + logCallback2(logString, stackTrace, type); + } } } [WrapperlessIcall] @@ -430,5 +506,35 @@ internal static UserAuthorization GetUserAuthorizationRequestMode() { return (UserAuthorization)Application.GetUserAuthorizationRequestMode_Internal(); } + [Obsolete("Application.RegisterLogCallback is deprecated. Use Application.logMessageReceived instead.")] + public static void RegisterLogCallback(Application.LogCallback handler) + { + Application.RegisterLogCallback(handler, false); + } + [Obsolete("Application.RegisterLogCallbackThreaded is deprecated. Use Application.logMessageReceivedThreaded instead.")] + public static void RegisterLogCallbackThreaded(Application.LogCallback handler) + { + Application.RegisterLogCallback(handler, true); + } + private static void RegisterLogCallback(Application.LogCallback handler, bool threaded) + { + if (Application.s_RegisterLogCallbackDeprecated != null) + { + Application.logMessageReceived -= Application.s_RegisterLogCallbackDeprecated; + Application.logMessageReceivedThreaded -= Application.s_RegisterLogCallbackDeprecated; + } + Application.s_RegisterLogCallbackDeprecated = handler; + if (handler != null) + { + if (threaded) + { + Application.logMessageReceivedThreaded += handler; + } + else + { + Application.logMessageReceived += handler; + } + } + } } } diff --git a/UnityEngine/UnityEngine/ApplicationInstallMode.cs b/UnityEngine/UnityEngine/ApplicationInstallMode.cs new file mode 100644 index 00000000..b00f80e5 --- /dev/null +++ b/UnityEngine/UnityEngine/ApplicationInstallMode.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum ApplicationInstallMode + { + Unknown, + Store, + DeveloperBuild, + Adhoc, + Enterprise, + Editor + } +} diff --git a/UnityEngine/UnityEngine/ApplicationSandboxType.cs b/UnityEngine/UnityEngine/ApplicationSandboxType.cs new file mode 100644 index 00000000..d813ef27 --- /dev/null +++ b/UnityEngine/UnityEngine/ApplicationSandboxType.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum ApplicationSandboxType + { + Unknown, + NotSandboxed, + Sandboxed, + SandboxBroken + } +} diff --git a/UnityEngine/UnityEngine/AreaEffector2D.cs b/UnityEngine/UnityEngine/AreaEffector2D.cs new file mode 100644 index 00000000..b4857ce8 --- /dev/null +++ b/UnityEngine/UnityEngine/AreaEffector2D.cs @@ -0,0 +1,62 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AreaEffector2D : Effector2D + { + public extern float forceDirection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float forceMagnitude + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float forceVariation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float drag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularDrag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern EffectorSelection2D forceTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/AssetBundle.cs b/UnityEngine/UnityEngine/AssetBundle.cs index 407f31da..b8c06f6f 100644 --- a/UnityEngine/UnityEngine/AssetBundle.cs +++ b/UnityEngine/UnityEngine/AssetBundle.cs @@ -23,25 +23,189 @@ public extern Object mainAsset [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern bool Contains(string name); + [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true)] public Object Load(string name) { - return this.Load(name, typeof(Object)); + return null; } - [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true)] + public T Load(string name) where T : Object + { + return (T)((object)null); + } + [Obsolete("Method Load has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAsset instead and check the documentation for details.", true), WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] [MethodImpl(MethodImplOptions.InternalCall)] public extern Object Load(string name, Type type); - [WrapperlessIcall] + [Obsolete("Method LoadAsync has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAssetAsync instead and check the documentation for details.", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern AssetBundleRequest LoadAsync(string name, Type type); - [WrapperlessIcall] + [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern Object[] LoadAll(Type type); + [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true)] public Object[] LoadAll() { - return this.LoadAll(typeof(Object)); + return null; + } + [Obsolete("Method LoadAll has been deprecated. Script updater cannot update it as the loading behaviour has changed. Please use LoadAllAssets instead and check the documentation for details.", true)] + public T[] LoadAll() where T : Object + { + return null; + } + public Object LoadAsset(string name) + { + return this.LoadAsset(name, typeof(Object)); + } + public T LoadAsset(string name) where T : Object + { + return (T)((object)this.LoadAsset(name, typeof(T))); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + public Object LoadAsset(string name, Type type) + { + if (name == null) + { + throw new NullReferenceException("The input asset name cannot be null."); + } + if (name.Length == 0) + { + throw new ArgumentException("The input asset name cannot be empty."); + } + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAsset_Internal(name, type); + } + [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern Object LoadAsset_Internal(string name, Type type); + public AssetBundleRequest LoadAssetAsync(string name) + { + return this.LoadAssetAsync(name, typeof(Object)); + } + public AssetBundleRequest LoadAssetAsync(string name) + { + return this.LoadAssetAsync(name, typeof(T)); + } + public AssetBundleRequest LoadAssetAsync(string name, Type type) + { + if (name == null) + { + throw new NullReferenceException("The input asset name cannot be null."); + } + if (name.Length == 0) + { + throw new ArgumentException("The input asset name cannot be empty."); + } + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAssetAsync_Internal(name, type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AssetBundleRequest LoadAssetAsync_Internal(string name, Type type); + public Object[] LoadAssetWithSubAssets(string name) + { + return this.LoadAssetWithSubAssets(name, typeof(Object)); + } + public T[] LoadAssetWithSubAssets(string name) where T : Object + { + return Resources.ConvertObjects(this.LoadAssetWithSubAssets(name, typeof(T))); + } + public Object[] LoadAssetWithSubAssets(string name, Type type) + { + if (name == null) + { + throw new NullReferenceException("The input asset name cannot be null."); + } + if (name.Length == 0) + { + throw new ArgumentException("The input asset name cannot be empty."); + } + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAssetWithSubAssets_Internal(name, type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Object[] LoadAssetWithSubAssets_Internal(string name, Type type); + public AssetBundleRequest LoadAssetWithSubAssetsAsync(string name) + { + return this.LoadAssetWithSubAssetsAsync(name, typeof(Object)); + } + public AssetBundleRequest LoadAssetWithSubAssetsAsync(string name) + { + return this.LoadAssetWithSubAssetsAsync(name, typeof(T)); + } + public AssetBundleRequest LoadAssetWithSubAssetsAsync(string name, Type type) + { + if (name == null) + { + throw new NullReferenceException("The input asset name cannot be null."); + } + if (name.Length == 0) + { + throw new ArgumentException("The input asset name cannot be empty."); + } + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAssetWithSubAssetsAsync_Internal(name, type); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern AssetBundleRequest LoadAssetWithSubAssetsAsync_Internal(string name, Type type); + public Object[] LoadAllAssets() + { + return this.LoadAllAssets(typeof(Object)); + } + public T[] LoadAllAssets() where T : Object + { + return Resources.ConvertObjects(this.LoadAllAssets(typeof(T))); + } + public Object[] LoadAllAssets(Type type) + { + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAssetWithSubAssets_Internal(string.Empty, type); + } + public AssetBundleRequest LoadAllAssetsAsync() + { + return this.LoadAllAssetsAsync(typeof(Object)); + } + public AssetBundleRequest LoadAllAssetsAsync() + { + return this.LoadAllAssetsAsync(typeof(T)); + } + public AssetBundleRequest LoadAllAssetsAsync(Type type) + { + if (type == null) + { + throw new NullReferenceException("The input type cannot be null."); + } + return this.LoadAssetWithSubAssetsAsync_Internal(string.Empty, type); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void Unload(bool unloadAllLoadedObjects); + [Obsolete("This method is deprecated. Use GetAllAssetNames() instead.")] + public string[] AllAssetNames() + { + return this.GetAllAssetNames(); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetAllAssetNames(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetAllScenePaths(); } } diff --git a/UnityEngine/UnityEngine/AssetBundleManifest.cs b/UnityEngine/UnityEngine/AssetBundleManifest.cs new file mode 100644 index 00000000..94d58777 --- /dev/null +++ b/UnityEngine/UnityEngine/AssetBundleManifest.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class AssetBundleManifest : Object + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetAllAssetBundles(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetAllAssetBundlesWithVariant(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Hash128 GetAssetBundleHash(string assetBundleName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetDirectDependencies(string assetBundleName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern string[] GetAllDependencies(string assetBundleName); + } +} diff --git a/UnityEngine/UnityEngine/AssetBundleRequest.cs b/UnityEngine/UnityEngine/AssetBundleRequest.cs index 18838919..282d1bc7 100644 --- a/UnityEngine/UnityEngine/AssetBundleRequest.cs +++ b/UnityEngine/UnityEngine/AssetBundleRequest.cs @@ -12,7 +12,14 @@ public Object asset { get { - return this.m_AssetBundle.Load(this.m_Path, this.m_Type); + return this.m_AssetBundle.LoadAsset(this.m_Path, this.m_Type); + } + } + public Object[] allAssets + { + get + { + return this.m_AssetBundle.LoadAssetWithSubAssets_Internal(this.m_Path, this.m_Type); } } } diff --git a/UnityEngine/UnityEngine/AsyncOperation.cs b/UnityEngine/UnityEngine/AsyncOperation.cs index d31a8c0f..03712589 100644 --- a/UnityEngine/UnityEngine/AsyncOperation.cs +++ b/UnityEngine/UnityEngine/AsyncOperation.cs @@ -6,7 +6,6 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public class AsyncOperation : YieldInstruction { - [NotRenamed] internal IntPtr m_Ptr; public extern bool isDone { diff --git a/UnityEngine/UnityEngine/AudioClip.cs b/UnityEngine/UnityEngine/AudioClip.cs index aff23bc5..244bc847 100644 --- a/UnityEngine/UnityEngine/AudioClip.cs +++ b/UnityEngine/UnityEngine/AudioClip.cs @@ -56,27 +56,73 @@ public extern int frequency [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("Use AudioClip.loadState instead to get more detailed information about the loading process.")] public extern bool isReadyToPlay { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern AudioClipLoadType loadType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool preloadAudioData + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern AudioDataLoadState loadState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool loadInBackground + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool LoadAudioData(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void GetData(float[] data, int offsetSamples); + public extern bool UnloadAudioData(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetData(float[] data, int offsetSamples); + public extern bool GetData(float[] data, int offsetSamples); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool SetData(float[] data, int offsetSamples); + [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream) { - return AudioClip.Create(name, lengthSamples, channels, frequency, _3D, stream, null, null); + return AudioClip.Create(name, lengthSamples, channels, frequency, stream); } + [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, AudioClip.PCMReaderCallback pcmreadercallback) { - return AudioClip.Create(name, lengthSamples, channels, frequency, _3D, stream, pcmreadercallback, null); + return AudioClip.Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, null); } + [Obsolete("The _3D argument of AudioClip is deprecated. Use the spatialBlend property of AudioSource instead to morph between 2D and 3D playback.")] public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream, AudioClip.PCMReaderCallback pcmreadercallback, AudioClip.PCMSetPositionCallback pcmsetpositioncallback) + { + return AudioClip.Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, pcmsetpositioncallback); + } + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream) + { + return AudioClip.Create(name, lengthSamples, channels, frequency, stream, null, null); + } + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream, AudioClip.PCMReaderCallback pcmreadercallback) + { + return AudioClip.Create(name, lengthSamples, channels, frequency, stream, pcmreadercallback, null); + } + public static AudioClip Create(string name, int lengthSamples, int channels, int frequency, bool stream, AudioClip.PCMReaderCallback pcmreadercallback, AudioClip.PCMSetPositionCallback pcmsetpositioncallback) { if (name == null) { @@ -105,7 +151,7 @@ public static AudioClip Create(string name, int lengthSamples, int channels, int AudioClip expr_6F = audioClip; expr_6F.m_PCMSetPositionCallback = (AudioClip.PCMSetPositionCallback)Delegate.Combine(expr_6F.m_PCMSetPositionCallback, pcmsetpositioncallback); } - audioClip.Init_Internal(name, lengthSamples, channels, frequency, _3D, stream); + audioClip.Init_Internal(name, lengthSamples, channels, frequency, stream); return audioClip; } private void InvokePCMReaderCallback_Internal(float[] data) @@ -127,6 +173,6 @@ private void InvokePCMSetPositionCallback_Internal(int position) private static extern AudioClip Construct_Internal(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Init_Internal(string name, int lengthSamples, int channels, int frequency, bool _3D, bool stream); + private extern void Init_Internal(string name, int lengthSamples, int channels, int frequency, bool stream); } } diff --git a/UnityEngine/UnityEngine/AudioClipLoadType.cs b/UnityEngine/UnityEngine/AudioClipLoadType.cs new file mode 100644 index 00000000..92f4c2d1 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioClipLoadType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum AudioClipLoadType + { + DecompressOnLoad, + CompressedInMemory, + Streaming + } +} diff --git a/UnityEngine/UnityEngine/AudioCompressionFormat.cs b/UnityEngine/UnityEngine/AudioCompressionFormat.cs new file mode 100644 index 00000000..5a000a47 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioCompressionFormat.cs @@ -0,0 +1,13 @@ +using System; +namespace UnityEngine +{ + public enum AudioCompressionFormat + { + PCM, + Vorbis, + ADPCM, + MP3, + VAG, + HEVAG + } +} diff --git a/UnityEngine/UnityEngine/AudioConfiguration.cs b/UnityEngine/UnityEngine/AudioConfiguration.cs new file mode 100644 index 00000000..9e7dc273 --- /dev/null +++ b/UnityEngine/UnityEngine/AudioConfiguration.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + public struct AudioConfiguration + { + public AudioSpeakerMode speakerMode; + public int dspBufferSize; + public int sampleRate; + public int numRealVoices; + public int numVirtualVoices; + } +} diff --git a/UnityEngine/UnityEngine/AudioDataLoadState.cs b/UnityEngine/UnityEngine/AudioDataLoadState.cs new file mode 100644 index 00000000..ced669ee --- /dev/null +++ b/UnityEngine/UnityEngine/AudioDataLoadState.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum AudioDataLoadState + { + Unloaded, + Loading, + Loaded, + Failed + } +} diff --git a/UnityEngine/UnityEngine/AudioHighPassFilter.cs b/UnityEngine/UnityEngine/AudioHighPassFilter.cs index b7f488fd..3400e5aa 100644 --- a/UnityEngine/UnityEngine/AudioHighPassFilter.cs +++ b/UnityEngine/UnityEngine/AudioHighPassFilter.cs @@ -13,6 +13,16 @@ public extern float cutoffFrequency [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float highpassResonanceQ + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("highpassResonaceQ is obsolete. Use highpassResonanceQ instead (UnityUpgradable).", true)] public extern float highpassResonaceQ { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/AudioLowPassFilter.cs b/UnityEngine/UnityEngine/AudioLowPassFilter.cs index 420d2075..967dd974 100644 --- a/UnityEngine/UnityEngine/AudioLowPassFilter.cs +++ b/UnityEngine/UnityEngine/AudioLowPassFilter.cs @@ -13,6 +13,16 @@ public extern float cutoffFrequency [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float lowpassResonanceQ + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("lowpassResonaceQ is obsolete. Use lowpassResonanceQ instead (UnityUpgradable).", true)] public extern float lowpassResonaceQ { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/AudioReverbFilter.cs b/UnityEngine/UnityEngine/AudioReverbFilter.cs index 319441c7..8ae20203 100644 --- a/UnityEngine/UnityEngine/AudioReverbFilter.cs +++ b/UnityEngine/UnityEngine/AudioReverbFilter.cs @@ -139,6 +139,16 @@ public extern float roomLF [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float lfReference + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("lFReference is obsolete. Use lfReference instead (UnityUpgradable).", true)] public extern float lFReference { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/AudioSettings.cs b/UnityEngine/UnityEngine/AudioSettings.cs index 1dbb1b99..1d0bfa77 100644 --- a/UnityEngine/UnityEngine/AudioSettings.cs +++ b/UnityEngine/UnityEngine/AudioSettings.cs @@ -4,6 +4,27 @@ namespace UnityEngine { public sealed class AudioSettings { + public delegate void AudioConfigurationChangeHandler(bool deviceWasChanged); + public static event AudioSettings.AudioConfigurationChangeHandler OnAudioConfigurationChanged + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + AudioSettings.OnAudioConfigurationChanged = (AudioSettings.AudioConfigurationChangeHandler)Delegate.Combine(AudioSettings.OnAudioConfigurationChanged, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + AudioSettings.OnAudioConfigurationChanged = (AudioSettings.AudioConfigurationChangeHandler)Delegate.Remove(AudioSettings.OnAudioConfigurationChanged, value); + } + } + public static extern AudioSpeakerMode driverCapabilities + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("driverCaps is obsolete. Use driverCapabilities instead (UnityUpgradable).", true)] public static extern AudioSpeakerMode driverCaps { [WrapperlessIcall] @@ -34,11 +55,37 @@ public static extern int outputSampleRate [MethodImpl(MethodImplOptions.InternalCall)] set; } + internal static extern bool editingInPlaymode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void GetDSPBufferSize(out int bufferLength, out int numBuffers); + [Obsolete("AudioSettings.SetDSPBufferSize is deprecated and has been replaced by audio project settings and the AudioSettings.GetConfiguration/AudioSettings.Reset API."), WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetDSPBufferSize(int bufferLength, int numBuffers); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void GetDSPBufferSize(out int bufferLength, out int numBuffers); + public static extern AudioConfiguration GetConfiguration(); + public static bool Reset(AudioConfiguration config) + { + return AudioSettings.INTERNAL_CALL_Reset(ref config); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Reset(ref AudioConfiguration config); + internal void InvokeOnAudioConfigurationChanged(bool deviceWasChanged) + { + if (AudioSettings.OnAudioConfigurationChanged != null) + { + AudioSettings.OnAudioConfigurationChanged(deviceWasChanged); + } + } } } diff --git a/UnityEngine/UnityEngine/AudioSource.cs b/UnityEngine/UnityEngine/AudioSource.cs index 566096a3..ee63d5e9 100644 --- a/UnityEngine/UnityEngine/AudioSource.cs +++ b/UnityEngine/UnityEngine/AudioSource.cs @@ -1,5 +1,7 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; +using UnityEngine.Audio; using UnityEngine.Internal; namespace UnityEngine { @@ -50,6 +52,15 @@ public extern AudioClip clip [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern AudioMixerGroup outputAudioMixerGroup + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool isPlaying { [WrapperlessIcall] @@ -101,6 +112,34 @@ public extern AudioVelocityUpdateMode velocityUpdateMode [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float panStereo + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float spatialBlend + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float reverbZoneMix + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("UnityEditor.panLevel has been deprecated. Use AudioSource.spatialBlend instead (UnityUpgradable).", true)] public extern float panLevel { [WrapperlessIcall] @@ -110,6 +149,16 @@ public extern float panLevel [MethodImpl(MethodImplOptions.InternalCall)] set; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("UnityEditor.pan has been deprecated. Use AudioSource.panStereo instead (UnityUpgradable).", true)] + public extern float pan + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool bypassEffects { [WrapperlessIcall] @@ -191,15 +240,6 @@ public extern float maxDistance [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float pan - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public extern AudioRolloffMode rolloffMode { [WrapperlessIcall] @@ -241,7 +281,7 @@ public extern float rolloffFactor } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Play([DefaultValue("0")] ulong delay); + public extern void Play([UnityEngine.Internal.DefaultValue("0")] ulong delay); [ExcludeFromDocs] public void Play() { @@ -270,9 +310,16 @@ public void Pause() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_Pause(AudioSource self); + public void UnPause() + { + AudioSource.INTERNAL_CALL_UnPause(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_UnPause(AudioSource self); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void PlayOneShot(AudioClip clip, [DefaultValue("1.0F")] float volumeScale); + public extern void PlayOneShot(AudioClip clip, [UnityEngine.Internal.DefaultValue("1.0F")] float volumeScale); [ExcludeFromDocs] public void PlayOneShot(AudioClip clip) { @@ -285,7 +332,7 @@ public static void PlayClipAtPoint(AudioClip clip, Vector3 position) float volume = 1f; AudioSource.PlayClipAtPoint(clip, position, volume); } - public static void PlayClipAtPoint(AudioClip clip, Vector3 position, [DefaultValue("1.0F")] float volume) + public static void PlayClipAtPoint(AudioClip clip, Vector3 position, [UnityEngine.Internal.DefaultValue("1.0F")] float volume) { GameObject gameObject = new GameObject("One shot audio"); gameObject.transform.position = position; diff --git a/UnityEngine/UnityEngine/AvatarIKHint.cs b/UnityEngine/UnityEngine/AvatarIKHint.cs new file mode 100644 index 00000000..f8ecda40 --- /dev/null +++ b/UnityEngine/UnityEngine/AvatarIKHint.cs @@ -0,0 +1,11 @@ +using System; +namespace UnityEngine +{ + public enum AvatarIKHint + { + LeftKnee, + RightKnee, + LeftElbow, + RightElbow + } +} diff --git a/UnityEngine/UnityEngine/BillboardAsset.cs b/UnityEngine/UnityEngine/BillboardAsset.cs new file mode 100644 index 00000000..b8641115 --- /dev/null +++ b/UnityEngine/UnityEngine/BillboardAsset.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class BillboardAsset : Object + { + public extern float width + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float height + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float bottom + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int imageCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int vertexCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int indexCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Material material + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MakeRenderMesh(Mesh mesh); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MakeMaterialProperties(MaterialPropertyBlock properties, Camera camera, float widthScale, float heightScale, float rotation); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void MakePreviewMesh(Mesh mesh); + } +} diff --git a/UnityEngine/UnityEngine/ClothRenderer.cs b/UnityEngine/UnityEngine/BillboardRenderer.cs similarity index 73% rename from UnityEngine/UnityEngine/ClothRenderer.cs rename to UnityEngine/UnityEngine/BillboardRenderer.cs index d73877ad..b589514c 100644 --- a/UnityEngine/UnityEngine/ClothRenderer.cs +++ b/UnityEngine/UnityEngine/BillboardRenderer.cs @@ -2,9 +2,9 @@ using System.Runtime.CompilerServices; namespace UnityEngine { - public sealed class ClothRenderer : Renderer + public sealed class BillboardRenderer : Renderer { - public extern bool pauseWhenNotVisible + public extern BillboardAsset billboard { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/Bounds.cs b/UnityEngine/UnityEngine/Bounds.cs index 58ff57fc..894a964b 100644 --- a/UnityEngine/UnityEngine/Bounds.cs +++ b/UnityEngine/UnityEngine/Bounds.cs @@ -144,6 +144,17 @@ public bool IntersectRay(Ray ray, out float distance) { return Bounds.Internal_IntersectRay(ref ray, ref this, out distance); } + private static Vector3 Internal_GetClosestPoint(ref Bounds bounds, ref Vector3 point) + { + return Bounds.INTERNAL_CALL_Internal_GetClosestPoint(ref bounds, ref point); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Vector3 INTERNAL_CALL_Internal_GetClosestPoint(ref Bounds bounds, ref Vector3 point); + public Vector3 ClosestPoint(Vector3 point) + { + return Bounds.Internal_GetClosestPoint(ref this, ref point); + } public override string ToString() { return UnityString.Format("Center: {0}, Extents: {1}", new object[] diff --git a/UnityEngine/UnityEngine/BoxCollider2D.cs b/UnityEngine/UnityEngine/BoxCollider2D.cs index f8525b80..8f6fcb4b 100644 --- a/UnityEngine/UnityEngine/BoxCollider2D.cs +++ b/UnityEngine/UnityEngine/BoxCollider2D.cs @@ -4,40 +4,32 @@ namespace UnityEngine { public sealed class BoxCollider2D : Collider2D { - public Vector2 center + public Vector2 size { get { Vector2 result; - this.INTERNAL_get_center(out result); + this.INTERNAL_get_size(out result); return result; } set { - this.INTERNAL_set_center(ref value); + this.INTERNAL_set_size(ref value); } } - public Vector2 size + [Obsolete("BoxCollider2D.center has been deprecated. Use BoxCollider2D.offset instead (UnityUpgradable).", true)] + public Vector2 center { get { - Vector2 result; - this.INTERNAL_get_size(out result); - return result; + return Vector2.zero; } set { - this.INTERNAL_set_size(ref value); } } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_center(out Vector2 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_center(ref Vector2 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_size(out Vector2 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/Caching.cs b/UnityEngine/UnityEngine/Caching.cs index 8624d117..bc1ad457 100644 --- a/UnityEngine/UnityEngine/Caching.cs +++ b/UnityEngine/UnityEngine/Caching.cs @@ -99,17 +99,49 @@ public static bool Authorize(string name, string domain, int size, string signat [Obsolete("This function is obsolete and will always return -1. Use IsVersionCached instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetVersionFromCache(string url); + public static bool IsVersionCached(string url, int version) + { + Hash128 hash = new Hash128(0u, 0u, 0u, (uint)version); + return Caching.IsVersionCached(url, hash); + } + public static bool IsVersionCached(string url, Hash128 hash) + { + return Caching.INTERNAL_CALL_IsVersionCached(url, ref hash); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool IsVersionCached(string url, int version); + private static extern bool INTERNAL_CALL_IsVersionCached(string url, ref Hash128 hash); + public static bool MarkAsUsed(string url, int version) + { + Hash128 hash = new Hash128(0u, 0u, 0u, (uint)version); + return Caching.MarkAsUsed(url, hash); + } + public static bool MarkAsUsed(string url, Hash128 hash) + { + return Caching.INTERNAL_CALL_MarkAsUsed(url, ref hash); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern bool MarkAsUsed(string url, int version); + private static extern bool INTERNAL_CALL_MarkAsUsed(string url, ref Hash128 hash); + public static void SetNoBackupFlag(string url, int version) + { + } + public static void SetNoBackupFlag(string url, Hash128 hash) + { + Caching.INTERNAL_CALL_SetNoBackupFlag(url, ref hash); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetNoBackupFlag(string url, int version); + private static extern void INTERNAL_CALL_SetNoBackupFlag(string url, ref Hash128 hash); + public static void ResetNoBackupFlag(string url, int version) + { + } + public static void ResetNoBackupFlag(string url, Hash128 hash) + { + Caching.INTERNAL_CALL_ResetNoBackupFlag(url, ref hash); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ResetNoBackupFlag(string url, int version); + private static extern void INTERNAL_CALL_ResetNoBackupFlag(string url, ref Hash128 hash); } } diff --git a/UnityEngine/UnityEngine/CalendarIdentifier.cs b/UnityEngine/UnityEngine/CalendarIdentifier.cs index 19a8ad9e..086d7049 100644 --- a/UnityEngine/UnityEngine/CalendarIdentifier.cs +++ b/UnityEngine/UnityEngine/CalendarIdentifier.cs @@ -1,18 +1,9 @@ using System; namespace UnityEngine { + [Obsolete("CalendarIdentifier is deprecated (UnityUpgradable). Please use iOS.CalendarIdentifier instead.", true)] public enum CalendarIdentifier { - GregorianCalendar, - BuddhistCalendar, - ChineseCalendar, - HebrewCalendar, - IslamicCalendar, - IslamicCivilCalendar, - JapaneseCalendar, - RepublicOfChinaCalendar, - PersianCalendar, - IndianCalendar, - ISO8601Calendar + } } diff --git a/UnityEngine/UnityEngine/CalendarUnit.cs b/UnityEngine/UnityEngine/CalendarUnit.cs index 3b17987e..abea97ef 100644 --- a/UnityEngine/UnityEngine/CalendarUnit.cs +++ b/UnityEngine/UnityEngine/CalendarUnit.cs @@ -1,18 +1,9 @@ using System; namespace UnityEngine { + [Obsolete("CalendarUnit is deprecated (UnityUpgradable). Please use iOS.CalendarUnit instead.", true)] public enum CalendarUnit { - Era = 2, - Year = 4, - Month = 8, - Day = 16, - Hour = 32, - Minute = 64, - Second = 128, - Week = 256, - Weekday = 512, - WeekdayOrdinal = 1024, - Quarter = 2048 + } } diff --git a/UnityEngine/UnityEngine/Camera.cs b/UnityEngine/UnityEngine/Camera.cs index d87fd582..1c6bbb7e 100644 --- a/UnityEngine/UnityEngine/Camera.cs +++ b/UnityEngine/UnityEngine/Camera.cs @@ -1,10 +1,16 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; using UnityEngine.Internal; +using UnityEngine.Rendering; namespace UnityEngine { public sealed class Camera : Behaviour { + public delegate void CameraCallback(Camera cam); + public static Camera.CameraCallback onPreCull; + public static Camera.CameraCallback onPreRender; + public static Camera.CameraCallback onPostRender; [Obsolete("use Camera.fieldOfView instead.")] public float fov { @@ -101,6 +107,17 @@ public extern float orthographicSize [MethodImpl(MethodImplOptions.InternalCall)] set; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property isOrthoGraphic has been deprecated. Use orthographic (UnityUpgradable).", true)] + public bool isOrthoGraphic + { + get + { + return false; + } + set + { + } + } public extern bool orthographic { [WrapperlessIcall] @@ -119,17 +136,6 @@ public extern TransparencySortMode transparencySortMode [MethodImpl(MethodImplOptions.InternalCall)] set; } - public bool isOrthoGraphic - { - get - { - return this.orthographic; - } - set - { - this.orthographic = value; - } - } public extern float depth { [WrapperlessIcall] @@ -157,6 +163,12 @@ public extern int cullingMask [MethodImpl(MethodImplOptions.InternalCall)] set; } + internal static extern int PreviewCullingLayer + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern int eventMask { [WrapperlessIcall] @@ -214,13 +226,13 @@ public extern RenderTexture targetTexture [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float pixelWidth + public extern int pixelWidth { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern float pixelHeight + public extern int pixelHeight { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -303,6 +315,15 @@ public extern float stereoConvergence [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int targetDisplay + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern Camera main { [WrapperlessIcall] @@ -327,12 +348,12 @@ public static extern int allCamerasCount [MethodImpl(MethodImplOptions.InternalCall)] get; } - [Obsolete("use Camera.main instead.")] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property mainCamera has been deprecated. Use Camera.main instead (UnityUpgradable).", true)] public static Camera mainCamera { get { - return Camera.main; + return null; } } public extern bool useOcclusionCulling @@ -380,6 +401,12 @@ public extern bool clearStencilAfterLightingPass [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int commandBufferCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_backgroundColor(out Color value); @@ -510,15 +537,36 @@ public Ray ScreenPointToRay(Vector3 position) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetAllCameras(Camera[] cameras); - [Obsolete("use Screen.width instead."), WrapperlessIcall] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property GetScreenWidth() has been deprecated. Use Screen.width instead (UnityUpgradable).", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetScreenWidth(); - [Obsolete("use Screen.height instead."), WrapperlessIcall] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property GetScreenHeight() has been deprecated. Use Screen.height instead (UnityUpgradable).", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetScreenHeight(); - [Obsolete("Camera.DoClear is deprecated and may be removed in the future."), WrapperlessIcall] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Camera.DoClear has been deprecated (UnityUpgradable).", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void DoClear(); + private static void FireOnPreCull(Camera cam) + { + if (Camera.onPreCull != null) + { + Camera.onPreCull(cam); + } + } + private static void FireOnPreRender(Camera cam) + { + if (Camera.onPreRender != null) + { + Camera.onPreRender(cam); + } + } + private static void FireOnPostRender(Camera cam) + { + if (Camera.onPostRender != null) + { + Camera.onPostRender(cam); + } + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void Render(); @@ -547,7 +595,7 @@ public bool RenderToCubemap(Cubemap cubemap) int faceMask = 63; return this.RenderToCubemap(cubemap, faceMask); } - public bool RenderToCubemap(Cubemap cubemap, [DefaultValue("63")] int faceMask) + public bool RenderToCubemap(Cubemap cubemap, [UnityEngine.Internal.DefaultValue("63")] int faceMask) { return this.Internal_RenderToCubemapTexture(cubemap, faceMask); } @@ -557,7 +605,7 @@ public bool RenderToCubemap(RenderTexture cubemap) int faceMask = 63; return this.RenderToCubemap(cubemap, faceMask); } - public bool RenderToCubemap(RenderTexture cubemap, [DefaultValue("63")] int faceMask) + public bool RenderToCubemap(RenderTexture cubemap, [UnityEngine.Internal.DefaultValue("63")] int faceMask) { return this.Internal_RenderToCubemapRT(cubemap, faceMask); } @@ -573,6 +621,35 @@ public bool RenderToCubemap(RenderTexture cubemap, [DefaultValue("63")] int face [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal extern bool IsFiltered(GameObject go); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void AddCommandBuffer(CameraEvent evt, CommandBuffer buffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveCommandBuffer(CameraEvent evt, CommandBuffer buffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveCommandBuffers(CameraEvent evt); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void RemoveAllCommandBuffers(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern CommandBuffer[] GetCommandBuffers(CameraEvent evt); + internal GameObject RaycastTry(Ray ray, float distance, int layerMask) + { + return Camera.INTERNAL_CALL_RaycastTry(this, ref ray, distance, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GameObject INTERNAL_CALL_RaycastTry(Camera self, ref Ray ray, float distance, int layerMask); + internal GameObject RaycastTry2D(Ray ray, float distance, int layerMask) + { + return Camera.INTERNAL_CALL_RaycastTry2D(this, ref ray, distance, layerMask); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern GameObject INTERNAL_CALL_RaycastTry2D(Camera self, ref Ray ray, float distance, int layerMask); public Matrix4x4 CalculateObliqueMatrix(Vector4 clipPlane) { return Camera.INTERNAL_CALL_CalculateObliqueMatrix(this, ref clipPlane); @@ -580,5 +657,11 @@ public Matrix4x4 CalculateObliqueMatrix(Vector4 clipPlane) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern Matrix4x4 INTERNAL_CALL_CalculateObliqueMatrix(Camera self, ref Vector4 clipPlane); + internal void OnlyUsedForTesting1() + { + } + internal void OnlyUsedForTesting2() + { + } } } diff --git a/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs b/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs deleted file mode 100644 index f95a1511..00000000 --- a/UnityEngine/UnityEngine/CanConvertToFlashAttribute.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Diagnostics; -namespace UnityEngine -{ - [Conditional("UNITY_FLASH")] - internal class CanConvertToFlashAttribute : Attribute - { - public CanConvertToFlashAttribute() - { - } - public CanConvertToFlashAttribute(params string[] members) - { - } - } -} diff --git a/UnityEngine/UnityEngine/CastHelper.cs b/UnityEngine/UnityEngine/CastHelper.cs new file mode 100644 index 00000000..1ed6b768 --- /dev/null +++ b/UnityEngine/UnityEngine/CastHelper.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + internal struct CastHelper + { + public T t; + public IntPtr onePointerFurtherThanT; + } +} diff --git a/UnityEngine/UnityEngine/CharacterInfo.cs b/UnityEngine/UnityEngine/CharacterInfo.cs index 6b6cfef5..b1747bad 100644 --- a/UnityEngine/UnityEngine/CharacterInfo.cs +++ b/UnityEngine/UnityEngine/CharacterInfo.cs @@ -4,11 +4,128 @@ namespace UnityEngine public struct CharacterInfo { public int index; + [Obsolete("CharacterInfo.uv is deprecated. Use uvBottomLeft, uvBottomRight, uvTopRight or uvTopLeft instead.")] public Rect uv; + [Obsolete("CharacterInfo.vert is deprecated. Use minX, maxX, minY, maxY instead.")] public Rect vert; + [Obsolete("CharacterInfo.width is deprecated. Use advance instead.")] public float width; public int size; public FontStyle style; + [Obsolete("CharacterInfo.flipped is deprecated. Use uvBottomLeft, uvBottomRight, uvTopRight or uvTopLeft instead, which will be correct regardless of orientation.")] public bool flipped; + private int ascent; + public int advance + { + get + { + return (int)this.width; + } + } + public int glyphWidth + { + get + { + return (int)this.vert.width; + } + } + public int glyphHeight + { + get + { + return (int)(-(int)this.vert.height); + } + } + public int bearing + { + get + { + return (int)this.vert.x; + } + } + public int minY + { + get + { + return this.ascent + (int)(this.vert.y + this.vert.height); + } + } + public int maxY + { + get + { + return this.ascent + (int)this.vert.y; + } + } + public int minX + { + get + { + return (int)this.vert.x; + } + } + public int maxX + { + get + { + return (int)(this.vert.x + this.vert.width); + } + } + internal Vector2 uvBottomLeftUnFlipped + { + get + { + return new Vector2(this.uv.x, this.uv.y); + } + } + internal Vector2 uvBottomRightUnFlipped + { + get + { + return new Vector2(this.uv.x + this.uv.width, this.uv.y); + } + } + internal Vector2 uvTopRightUnFlipped + { + get + { + return new Vector2(this.uv.x + this.uv.width, this.uv.y + this.uv.height); + } + } + internal Vector2 uvTopLeftUnFlipped + { + get + { + return new Vector2(this.uv.x, this.uv.y + this.uv.height); + } + } + public Vector2 uvBottomLeft + { + get + { + return (!this.flipped) ? this.uvBottomLeftUnFlipped : this.uvBottomLeftUnFlipped; + } + } + public Vector2 uvBottomRight + { + get + { + return (!this.flipped) ? this.uvBottomRightUnFlipped : this.uvTopLeftUnFlipped; + } + } + public Vector2 uvTopRight + { + get + { + return (!this.flipped) ? this.uvTopRightUnFlipped : this.uvTopRightUnFlipped; + } + } + public Vector2 uvTopLeft + { + get + { + return (!this.flipped) ? this.uvTopLeftUnFlipped : this.uvBottomRightUnFlipped; + } + } } } diff --git a/UnityEngine/UnityEngine/CharacterJoint.cs b/UnityEngine/UnityEngine/CharacterJoint.cs index 43e7c805..73f26dac 100644 --- a/UnityEngine/UnityEngine/CharacterJoint.cs +++ b/UnityEngine/UnityEngine/CharacterJoint.cs @@ -4,6 +4,12 @@ namespace UnityEngine { public sealed class CharacterJoint : Joint { + [Obsolete("TargetRotation not in use for Unity 5 and assumed disabled.", true)] + public Quaternion targetRotation; + [Obsolete("TargetAngularVelocity not in use for Unity 5 and assumed disabled.", true)] + public Vector3 targetAngularVelocity; + [Obsolete("RotationDrive not in use for Unity 5 and assumed disabled.", true)] + public JointDrive rotationDrive; public Vector3 swingAxis { get @@ -17,96 +23,110 @@ public Vector3 swingAxis this.INTERNAL_set_swingAxis(ref value); } } - public SoftJointLimit lowTwistLimit + public SoftJointLimitSpring twistLimitSpring { get { - SoftJointLimit result; - this.INTERNAL_get_lowTwistLimit(out result); + SoftJointLimitSpring result; + this.INTERNAL_get_twistLimitSpring(out result); return result; } set { - this.INTERNAL_set_lowTwistLimit(ref value); + this.INTERNAL_set_twistLimitSpring(ref value); } } - public SoftJointLimit highTwistLimit + public SoftJointLimitSpring swingLimitSpring { get { - SoftJointLimit result; - this.INTERNAL_get_highTwistLimit(out result); + SoftJointLimitSpring result; + this.INTERNAL_get_swingLimitSpring(out result); return result; } set { - this.INTERNAL_set_highTwistLimit(ref value); + this.INTERNAL_set_swingLimitSpring(ref value); } } - public SoftJointLimit swing1Limit + public SoftJointLimit lowTwistLimit { get { SoftJointLimit result; - this.INTERNAL_get_swing1Limit(out result); + this.INTERNAL_get_lowTwistLimit(out result); return result; } set { - this.INTERNAL_set_swing1Limit(ref value); + this.INTERNAL_set_lowTwistLimit(ref value); } } - public SoftJointLimit swing2Limit + public SoftJointLimit highTwistLimit { get { SoftJointLimit result; - this.INTERNAL_get_swing2Limit(out result); + this.INTERNAL_get_highTwistLimit(out result); return result; } set { - this.INTERNAL_set_swing2Limit(ref value); + this.INTERNAL_set_highTwistLimit(ref value); } } - public Quaternion targetRotation + public SoftJointLimit swing1Limit { get { - Quaternion result; - this.INTERNAL_get_targetRotation(out result); + SoftJointLimit result; + this.INTERNAL_get_swing1Limit(out result); return result; } set { - this.INTERNAL_set_targetRotation(ref value); + this.INTERNAL_set_swing1Limit(ref value); } } - public Vector3 targetAngularVelocity + public SoftJointLimit swing2Limit { get { - Vector3 result; - this.INTERNAL_get_targetAngularVelocity(out result); + SoftJointLimit result; + this.INTERNAL_get_swing2Limit(out result); return result; } set { - this.INTERNAL_set_targetAngularVelocity(ref value); + this.INTERNAL_set_swing2Limit(ref value); } } - public JointDrive rotationDrive + public extern bool enableProjection { - get - { - JointDrive result; - this.INTERNAL_get_rotationDrive(out result); - return result; - } - set - { - this.INTERNAL_set_rotationDrive(ref value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float projectionDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float projectionAngle + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -116,45 +136,39 @@ public JointDrive rotationDrive private extern void INTERNAL_set_swingAxis(ref Vector3 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_lowTwistLimit(out SoftJointLimit value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_lowTwistLimit(ref SoftJointLimit value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_highTwistLimit(out SoftJointLimit value); + private extern void INTERNAL_get_twistLimitSpring(out SoftJointLimitSpring value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_highTwistLimit(ref SoftJointLimit value); + private extern void INTERNAL_set_twistLimitSpring(ref SoftJointLimitSpring value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_swing1Limit(out SoftJointLimit value); + private extern void INTERNAL_get_swingLimitSpring(out SoftJointLimitSpring value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_swing1Limit(ref SoftJointLimit value); + private extern void INTERNAL_set_swingLimitSpring(ref SoftJointLimitSpring value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_swing2Limit(out SoftJointLimit value); + private extern void INTERNAL_get_lowTwistLimit(out SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_swing2Limit(ref SoftJointLimit value); + private extern void INTERNAL_set_lowTwistLimit(ref SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_targetRotation(out Quaternion value); + private extern void INTERNAL_get_highTwistLimit(out SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_targetRotation(ref Quaternion value); + private extern void INTERNAL_set_highTwistLimit(ref SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_targetAngularVelocity(out Vector3 value); + private extern void INTERNAL_get_swing1Limit(out SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_targetAngularVelocity(ref Vector3 value); + private extern void INTERNAL_set_swing1Limit(ref SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_rotationDrive(out JointDrive value); + private extern void INTERNAL_get_swing2Limit(out SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_rotationDrive(ref JointDrive value); + private extern void INTERNAL_set_swing2Limit(ref SoftJointLimit value); } } diff --git a/UnityEngine/UnityEngine/CircleCollider2D.cs b/UnityEngine/UnityEngine/CircleCollider2D.cs index 1fddc20c..053c7ad9 100644 --- a/UnityEngine/UnityEngine/CircleCollider2D.cs +++ b/UnityEngine/UnityEngine/CircleCollider2D.cs @@ -4,19 +4,6 @@ namespace UnityEngine { public sealed class CircleCollider2D : Collider2D { - public Vector2 center - { - get - { - Vector2 result; - this.INTERNAL_get_center(out result); - return result; - } - set - { - this.INTERNAL_set_center(ref value); - } - } public extern float radius { [WrapperlessIcall] @@ -26,11 +13,16 @@ public extern float radius [MethodImpl(MethodImplOptions.InternalCall)] set; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_center(out Vector2 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_center(ref Vector2 value); + [Obsolete("CircleCollider2D.center has been deprecated. Use CircleCollider2D.offset instead (UnityUpgradable).", true)] + public Vector2 center + { + get + { + return Vector2.zero; + } + set + { + } + } } } diff --git a/UnityEngine/UnityEngine/Cloth.cs b/UnityEngine/UnityEngine/Cloth.cs index a383d665..80d4dbf8 100644 --- a/UnityEngine/UnityEngine/Cloth.cs +++ b/UnityEngine/UnityEngine/Cloth.cs @@ -1,10 +1,11 @@ using System; using System.Runtime.CompilerServices; +using UnityEngine.Internal; namespace UnityEngine { - public class Cloth : Component + public sealed class Cloth : Component { - public extern float bendingStiffness + public extern float sleepThreshold { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -13,7 +14,7 @@ public extern float bendingStiffness [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float stretchingStiffness + public extern float bendingStiffness { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -22,7 +23,7 @@ public extern float stretchingStiffness [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float damping + public extern float stretchingStiffness { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -31,7 +32,7 @@ public extern float damping [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float thickness + public extern float damping { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -75,6 +76,7 @@ public extern bool useGravity [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("Deprecated. Cloth.selfCollisions is no longer supported since Unity 5.0.", true)] public extern bool selfCollision { [WrapperlessIcall] @@ -105,6 +107,96 @@ public extern Vector3[] normals [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern float friction + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float collisionMassScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float useContinuousCollision + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float useVirtualParticles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ClothSkinningCoefficient[] coefficients + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float worldVelocityScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float worldAccelerationScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool solverFrequency + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern CapsuleCollider[] capsuleColliders + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ClothSphereColliderPair[] sphereColliders + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_externalAcceleration(out Vector3 value); @@ -117,5 +209,21 @@ public extern Vector3[] normals [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_set_randomAcceleration(ref Vector3 value); + public void ClearTransformMotion() + { + Cloth.INTERNAL_CALL_ClearTransformMotion(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_ClearTransformMotion(Cloth self); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetEnabledFading(bool enabled, [DefaultValue("0.5f")] float interpolationTime); + [ExcludeFromDocs] + public void SetEnabledFading(bool enabled) + { + float interpolationTime = 0.5f; + this.SetEnabledFading(enabled, interpolationTime); + } } } diff --git a/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs b/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs index e30160c9..23ac3484 100644 --- a/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs +++ b/UnityEngine/UnityEngine/ClothSkinningCoefficient.cs @@ -4,8 +4,6 @@ namespace UnityEngine public struct ClothSkinningCoefficient { public float maxDistance; - public float maxDistanceBias; - public float collisionSphereRadius; public float collisionSphereDistance; } } diff --git a/UnityEngine/UnityEngine/ClothSphereColliderPair.cs b/UnityEngine/UnityEngine/ClothSphereColliderPair.cs new file mode 100644 index 00000000..7c2f4a3c --- /dev/null +++ b/UnityEngine/UnityEngine/ClothSphereColliderPair.cs @@ -0,0 +1,45 @@ +using System; +namespace UnityEngine +{ + public struct ClothSphereColliderPair + { + private SphereCollider m_First; + private SphereCollider m_Second; + public SphereCollider first + { + get + { + return this.m_First; + } + set + { + this.m_First = value; + } + } + public SphereCollider second + { + get + { + return this.m_Second; + } + set + { + this.m_Second = value; + } + } + public ClothSphereColliderPair(SphereCollider a) + { + this.m_First = null; + this.m_Second = null; + this.first = a; + this.second = null; + } + public ClothSphereColliderPair(SphereCollider a, SphereCollider b) + { + this.m_First = null; + this.m_Second = null; + this.first = a; + this.second = b; + } + } +} diff --git a/UnityEngine/UnityEngine/Collider.cs b/UnityEngine/UnityEngine/Collider.cs index b137816c..716e136e 100644 --- a/UnityEngine/UnityEngine/Collider.cs +++ b/UnityEngine/UnityEngine/Collider.cs @@ -28,6 +28,15 @@ public extern bool isTrigger [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float contactOffset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern PhysicMaterial material { [WrapperlessIcall] @@ -65,16 +74,16 @@ public Vector3 ClosestPointOnBounds(Vector3 position) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_bounds(out Bounds value); - private static bool Internal_Raycast(Collider col, Ray ray, out RaycastHit hitInfo, float distance) + private static bool Internal_Raycast(Collider col, Ray ray, out RaycastHit hitInfo, float maxDistance) { - return Collider.INTERNAL_CALL_Internal_Raycast(col, ref ray, out hitInfo, distance); + return Collider.INTERNAL_CALL_Internal_Raycast(col, ref ray, out hitInfo, maxDistance); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Internal_Raycast(Collider col, ref Ray ray, out RaycastHit hitInfo, float distance); - public bool Raycast(Ray ray, out RaycastHit hitInfo, float distance) + private static extern bool INTERNAL_CALL_Internal_Raycast(Collider col, ref Ray ray, out RaycastHit hitInfo, float maxDistance); + public bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance) { - return Collider.Internal_Raycast(this, ray, out hitInfo, distance); + return Collider.Internal_Raycast(this, ray, out hitInfo, maxDistance); } } } diff --git a/UnityEngine/UnityEngine/Collider2D.cs b/UnityEngine/UnityEngine/Collider2D.cs index 17e412da..b78e6325 100644 --- a/UnityEngine/UnityEngine/Collider2D.cs +++ b/UnityEngine/UnityEngine/Collider2D.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using UnityEngine.Internal; namespace UnityEngine { public class Collider2D : Behaviour @@ -13,6 +14,28 @@ public extern bool isTrigger [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern bool usedByEffector + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector2 offset + { + get + { + Vector2 result; + this.INTERNAL_get_offset(out result); + return result; + } + set + { + this.INTERNAL_set_offset(ref value); + } + } public extern Rigidbody2D attachedRigidbody { [WrapperlessIcall] @@ -51,6 +74,12 @@ public extern PhysicsMaterial2D sharedMaterial } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_offset(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_offset(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_bounds(out Bounds value); public bool OverlapPoint(Vector2 point) { @@ -59,5 +88,17 @@ public bool OverlapPoint(Vector2 point) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool INTERNAL_CALL_OverlapPoint(Collider2D self, ref Vector2 point); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsTouching(Collider2D collider); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsTouchingLayers([DefaultValue("Physics2D.AllLayers")] int layerMask); + [ExcludeFromDocs] + public bool IsTouchingLayers() + { + int layerMask = -1; + return this.IsTouchingLayers(layerMask); + } } } diff --git a/UnityEngine/UnityEngine/Collision2D.cs b/UnityEngine/UnityEngine/Collision2D.cs index 53296d29..b4fbda41 100644 --- a/UnityEngine/UnityEngine/Collision2D.cs +++ b/UnityEngine/UnityEngine/Collision2D.cs @@ -9,6 +9,14 @@ public class Collision2D internal Collider2D m_Collider; internal ContactPoint2D[] m_Contacts; internal Vector2 m_RelativeVelocity; + internal bool m_Enabled; + public bool enabled + { + get + { + return this.m_Enabled; + } + } public Rigidbody2D rigidbody { get diff --git a/UnityEngine/UnityEngine/Component.cs b/UnityEngine/UnityEngine/Component.cs index ef00f956..6be0e7f4 100644 --- a/UnityEngine/UnityEngine/Component.cs +++ b/UnityEngine/UnityEngine/Component.cs @@ -1,171 +1,196 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Security; using UnityEngine.Internal; using UnityEngineInternal; namespace UnityEngine { public class Component : Object { - public Transform transform - { - get - { - return this.InternalGetTransform(); - } - } - public extern Rigidbody rigidbody + public extern Transform transform { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern Rigidbody2D rigidbody2D + public extern GameObject gameObject { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern Camera camera + public string tag { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return this.gameObject.tag; + } + set + { + this.gameObject.tag = value; + } } - public extern Light light + [Obsolete("Property rigidbody has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component rigidbody { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("rigidbody property has been deprecated"); + } } - public extern Animation animation + [Obsolete("Property rigidbody2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component rigidbody2D { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("rigidbody2D property has been deprecated"); + } } - public extern ConstantForce constantForce + [Obsolete("Property camera has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component camera { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("camera property has been deprecated"); + } } - public extern Renderer renderer + [Obsolete("Property light has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component light { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("light property has been deprecated"); + } } - public extern AudioSource audio + [Obsolete("Property animation has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component animation { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("animation property has been deprecated"); + } } - public extern GUIText guiText + [Obsolete("Property constantForce has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component constantForce { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("constantForce property has been deprecated"); + } } - public extern NetworkView networkView + [Obsolete("Property renderer has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component renderer { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("renderer property has been deprecated"); + } } - [Obsolete("Please use guiTexture instead")] - public extern GUIElement guiElement + [Obsolete("Property audio has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component audio { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("audio property has been deprecated"); + } } - public extern GUITexture guiTexture + [Obsolete("Property guiText has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiText { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("guiText property has been deprecated"); + } } - public extern Collider collider + [Obsolete("Property networkView has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component networkView { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("networkView property has been deprecated"); + } } - public extern Collider2D collider2D + [Obsolete("Property guiElement has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiElement { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("guiElement property has been deprecated"); + } } - public extern HingeJoint hingeJoint + [Obsolete("Property guiTexture has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiTexture { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("guiTexture property has been deprecated"); + } } - public extern ParticleEmitter particleEmitter + [Obsolete("Property collider has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component collider { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("collider property has been deprecated"); + } } - public extern ParticleSystem particleSystem + [Obsolete("Property collider2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component collider2D { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("collider2D property has been deprecated"); + } } - public GameObject gameObject + [Obsolete("Property hingeJoint has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component hingeJoint { get { - return this.InternalGetGameObject(); + throw new NotSupportedException("hingeJoint property has been deprecated"); } } - [Obsolete("the active property is deprecated on components. Please use gameObject.active instead. If you meant to enable / disable a single component use enabled instead.")] - public extern bool active + [Obsolete("Property particleEmitter has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component particleEmitter { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + throw new NotSupportedException("particleEmitter property has been deprecated"); + } } - public extern string tag + [Obsolete("Property particleSystem has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component particleSystem { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + throw new NotSupportedException("particleSystem property has been deprecated"); + } } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern Transform InternalGetTransform(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern GameObject InternalGetGameObject(); - [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern Component GetComponent(Type type); - public T GetComponent() where T : Component + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public Component GetComponent(Type type) { - return this.GetComponent(typeof(T)) as T; + return this.gameObject.GetComponent(type); } - public Component GetComponent(string type) + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue); + [SecuritySafeCritical] + public unsafe T GetComponent() { - return this.gameObject.GetComponent(type); + CastHelper castHelper = default(CastHelper); + this.GetComponentFastPath(typeof(T), new IntPtr((void*)(&castHelper.onePointerFurtherThanT))); + return castHelper.t; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern Component GetComponent(string type); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInChildren(Type t) { return this.gameObject.GetComponentInChildren(t); } - public T GetComponentInChildren() where T : Component + public T GetComponentInChildren() { return (T)((object)this.GetComponentInChildren(typeof(T))); } @@ -179,19 +204,19 @@ public Component[] GetComponentsInChildren(Type t, [DefaultValue("false")] bool { return this.gameObject.GetComponentsInChildren(t, includeInactive); } - public T[] GetComponentsInChildren(bool includeInactive) where T : Component + public T[] GetComponentsInChildren(bool includeInactive) { return this.gameObject.GetComponentsInChildren(includeInactive); } - public void GetComponentsInChildren(bool includeInactive, List result) where T : Component + public void GetComponentsInChildren(bool includeInactive, List result) { this.gameObject.GetComponentsInChildren(includeInactive, result); } - public T[] GetComponentsInChildren() where T : Component + public T[] GetComponentsInChildren() { return this.GetComponentsInChildren(false); } - public void GetComponentsInChildren(List results) where T : Component + public void GetComponentsInChildren(List results) { this.GetComponentsInChildren(false, results); } @@ -200,7 +225,7 @@ public Component GetComponentInParent(Type t) { return this.gameObject.GetComponentInParent(t); } - public T GetComponentInParent() where T : Component + public T GetComponentInParent() { return (T)((object)this.GetComponentInParent(typeof(T))); } @@ -214,34 +239,36 @@ public Component[] GetComponentsInParent(Type t, [DefaultValue("false")] bool in { return this.gameObject.GetComponentsInParent(t, includeInactive); } - public T[] GetComponentsInParent(bool includeInactive) where T : Component + public T[] GetComponentsInParent(bool includeInactive) { return this.gameObject.GetComponentsInParent(includeInactive); } - public T[] GetComponentsInParent() where T : Component + public void GetComponentsInParent(bool includeInactive, List results) + { + this.gameObject.GetComponentsInParent(includeInactive, results); + } + public T[] GetComponentsInParent() { return this.GetComponentsInParent(false); } + public Component[] GetComponents(Type type) + { + return this.gameObject.GetComponents(type); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern Component[] GetComponents(Type type); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern Component[] GetComponentsWithCorrectReturnType(Type type); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void GetComponentsForListInternal(Type searchType, Type listElementType, bool recursive, bool includeInactive, object resultList); - public T[] GetComponents() where T : Component + private extern void GetComponentsForListInternal(Type searchType, object resultList); + public void GetComponents(Type type, List results) { - return (T[])this.GetComponentsWithCorrectReturnType(typeof(T)); + this.GetComponentsForListInternal(type, results); } - public void GetComponents(Type type, List results) + public void GetComponents(List results) { - this.GetComponentsForListInternal(type, typeof(Component), false, true, results); + this.GetComponentsForListInternal(typeof(T), results); } - public void GetComponents(List results) where T : Component + public T[] GetComponents() { - this.GetComponentsForListInternal(typeof(T), typeof(T), false, true, results); + return this.gameObject.GetComponents(); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/ConfigurableJoint.cs b/UnityEngine/UnityEngine/ConfigurableJoint.cs index 3bcef89e..d230430c 100644 --- a/UnityEngine/UnityEngine/ConfigurableJoint.cs +++ b/UnityEngine/UnityEngine/ConfigurableJoint.cs @@ -71,6 +71,45 @@ public extern ConfigurableJointMotion angularZMotion [MethodImpl(MethodImplOptions.InternalCall)] set; } + public SoftJointLimitSpring linearLimitSpring + { + get + { + SoftJointLimitSpring result; + this.INTERNAL_get_linearLimitSpring(out result); + return result; + } + set + { + this.INTERNAL_set_linearLimitSpring(ref value); + } + } + public SoftJointLimitSpring angularXLimitSpring + { + get + { + SoftJointLimitSpring result; + this.INTERNAL_get_angularXLimitSpring(out result); + return result; + } + set + { + this.INTERNAL_set_angularXLimitSpring(ref value); + } + } + public SoftJointLimitSpring angularYZLimitSpring + { + get + { + SoftJointLimitSpring result; + this.INTERNAL_get_angularYZLimitSpring(out result); + return result; + } + set + { + this.INTERNAL_set_angularYZLimitSpring(ref value); + } + } public SoftJointLimit linearLimit { get @@ -328,6 +367,24 @@ public extern bool swapBodies private extern void INTERNAL_set_secondaryAxis(ref Vector3 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_linearLimitSpring(out SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_linearLimitSpring(ref SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularXLimitSpring(out SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularXLimitSpring(ref SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_angularYZLimitSpring(out SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_angularYZLimitSpring(ref SoftJointLimitSpring value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_linearLimit(out SoftJointLimit value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/ConstantForce2D.cs b/UnityEngine/UnityEngine/ConstantForce2D.cs new file mode 100644 index 00000000..c53cb6a4 --- /dev/null +++ b/UnityEngine/UnityEngine/ConstantForce2D.cs @@ -0,0 +1,55 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class ConstantForce2D : PhysicsUpdateBehaviour2D + { + public Vector2 force + { + get + { + Vector2 result; + this.INTERNAL_get_force(out result); + return result; + } + set + { + this.INTERNAL_set_force(ref value); + } + } + public Vector2 relativeForce + { + get + { + Vector2 result; + this.INTERNAL_get_relativeForce(out result); + return result; + } + set + { + this.INTERNAL_set_relativeForce(ref value); + } + } + public extern float torque + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_force(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_force(ref Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_relativeForce(out Vector2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_relativeForce(ref Vector2 value); + } +} diff --git a/UnityEngine/UnityEngine/ContactPoint.cs b/UnityEngine/UnityEngine/ContactPoint.cs index 32dca647..4cbcac55 100644 --- a/UnityEngine/UnityEngine/ContactPoint.cs +++ b/UnityEngine/UnityEngine/ContactPoint.cs @@ -1,12 +1,13 @@ using System; +using System.Runtime.CompilerServices; namespace UnityEngine { public struct ContactPoint { internal Vector3 m_Point; internal Vector3 m_Normal; - internal Collider m_ThisCollider; - internal Collider m_OtherCollider; + internal int m_ThisColliderInstanceID; + internal int m_OtherColliderInstanceID; public Vector3 point { get @@ -25,15 +26,18 @@ public Collider thisCollider { get { - return this.m_ThisCollider; + return ContactPoint.ColliderFromInstanceId(this.m_ThisColliderInstanceID); } } public Collider otherCollider { get { - return this.m_OtherCollider; + return ContactPoint.ColliderFromInstanceId(this.m_OtherColliderInstanceID); } } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider ColliderFromInstanceId(int instanceID); } } diff --git a/UnityEngine/UnityEngine/Cursor.cs b/UnityEngine/UnityEngine/Cursor.cs index 445dfd51..5d3b2f20 100644 --- a/UnityEngine/UnityEngine/Cursor.cs +++ b/UnityEngine/UnityEngine/Cursor.cs @@ -4,6 +4,24 @@ namespace UnityEngine { public sealed class Cursor { + public static extern bool visible + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern CursorLockMode lockState + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } private static void SetCursor(Texture2D texture, CursorMode cursorMode) { Cursor.SetCursor(texture, Vector2.zero, cursorMode); diff --git a/UnityEngine/UnityEngine/CursorLockMode.cs b/UnityEngine/UnityEngine/CursorLockMode.cs new file mode 100644 index 00000000..1341e5a1 --- /dev/null +++ b/UnityEngine/UnityEngine/CursorLockMode.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum CursorLockMode + { + None, + Locked, + Confined + } +} diff --git a/UnityEngine/UnityEngine/Debug.cs b/UnityEngine/UnityEngine/Debug.cs index 4d85dcfa..2f7cce17 100644 --- a/UnityEngine/UnityEngine/Debug.cs +++ b/UnityEngine/UnityEngine/Debug.cs @@ -93,6 +93,14 @@ public static void Log(object message, Object context) { Debug.Internal_Log(0, (message == null) ? "Null" : message.ToString(), context); } + public static void LogFormat(string format, params object[] args) + { + Debug.Log(string.Format(format, args)); + } + public static void LogFormat(Object context, string format, params object[] args) + { + Debug.Log(string.Format(format, args), context); + } public static void LogError(object message) { Debug.Internal_Log(2, (message == null) ? "Null" : message.ToString(), null); @@ -101,9 +109,20 @@ public static void LogError(object message, Object context) { Debug.Internal_Log(2, message.ToString(), context); } + public static void LogErrorFormat(string format, params object[] args) + { + Debug.LogError(string.Format(format, args)); + } + public static void LogErrorFormat(Object context, string format, params object[] args) + { + Debug.LogError(string.Format(format, args), context); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void ClearDeveloperConsole(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void WriteLineToLogFile(string message); public static void LogException(Exception exception) { Debug.Internal_LogException(exception, null); @@ -123,6 +142,14 @@ public static void LogWarning(object message, Object context) { Debug.Internal_Log(1, message.ToString(), context); } + public static void LogWarningFormat(string format, params object[] args) + { + Debug.LogWarning(string.Format(format, args)); + } + public static void LogWarningFormat(Object context, string format, params object[] args) + { + Debug.LogWarning(string.Format(format, args), context); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void OpenConsoleFile(); diff --git a/UnityEngine/UnityEngine/DisableBatchingType.cs b/UnityEngine/UnityEngine/DisableBatchingType.cs new file mode 100644 index 00000000..4e370b3c --- /dev/null +++ b/UnityEngine/UnityEngine/DisableBatchingType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal enum DisableBatchingType + { + False, + True, + WhenLODFading + } +} diff --git a/UnityEngine/UnityEngine/Display.cs b/UnityEngine/UnityEngine/Display.cs index 0b2e87bd..7b105d27 100644 --- a/UnityEngine/UnityEngine/Display.cs +++ b/UnityEngine/UnityEngine/Display.cs @@ -106,12 +106,36 @@ static Display() } public void Activate() { - Display.ActivateDisplayImpl(this.nativeDisplay); + Display.ActivateDisplayImpl(this.nativeDisplay, 0, 0, 60); + } + public void Activate(int width, int height, int refreshRate) + { + Display.ActivateDisplayImpl(this.nativeDisplay, width, height, refreshRate); + } + public void SetParams(int width, int height, int x, int y) + { + Display.SetParamsImpl(this.nativeDisplay, width, height, x, y); } public void SetRenderingResolution(int w, int h) { Display.SetRenderingResolutionImpl(this.nativeDisplay, w, h); } + public static bool MultiDisplayLicense() + { + return Display.MultiDisplayLicenseImpl(); + } + public static Vector3 RelativeMouseAt(Vector3 inputMouseCoordinates) + { + int num = 0; + int num2 = 0; + int x = (int)inputMouseCoordinates.x; + int y = (int)inputMouseCoordinates.y; + Vector3 result; + result.z = (float)Display.RelativeMouseAtImpl(x, y, out num, out num2); + result.x = (float)num; + result.y = (float)num2; + return result; + } private static void RecreateDisplayList(IntPtr[] nativeDisplay) { Display.displays = new Display[nativeDisplay.Length]; @@ -142,6 +166,15 @@ private static void FireDisplaysUpdated() private static extern void SetRenderingResolutionImpl(IntPtr nativeDisplay, int w, int h); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void ActivateDisplayImpl(IntPtr nativeDisplay); + private static extern void ActivateDisplayImpl(IntPtr nativeDisplay, int width, int height, int refreshRate); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void SetParamsImpl(IntPtr nativeDisplay, int width, int height, int x, int y); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool MultiDisplayLicenseImpl(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern int RelativeMouseAtImpl(int x, int y, out int rx, out int ry); } } diff --git a/UnityEngine/UnityEngine/DynamicGI.cs b/UnityEngine/UnityEngine/DynamicGI.cs new file mode 100644 index 00000000..1e021890 --- /dev/null +++ b/UnityEngine/UnityEngine/DynamicGI.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class DynamicGI + { + public static extern float indirectScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float updateThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool synchronousMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static void SetEmissive(Renderer renderer, Color color) + { + DynamicGI.INTERNAL_CALL_SetEmissive(renderer, ref color); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetEmissive(Renderer renderer, ref Color color); + public static void UpdateMaterials(Renderer renderer) + { + DynamicGI.UpdateMaterialsForRenderer(renderer); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void UpdateMaterialsForRenderer(Renderer renderer); + public static void UpdateMaterials(Terrain terrain) + { + if (terrain == null) + { + throw new ArgumentNullException("terrain"); + } + if (terrain.terrainData == null) + { + throw new ArgumentException("Invalid terrainData."); + } + DynamicGI.UpdateMaterialsForTerrain(terrain, new Rect(0f, 0f, 1f, 1f)); + } + public static void UpdateMaterials(Terrain terrain, int x, int y, int width, int height) + { + if (terrain == null) + { + throw new ArgumentNullException("terrain"); + } + if (terrain.terrainData == null) + { + throw new ArgumentException("Invalid terrainData."); + } + float num = (float)terrain.terrainData.alphamapWidth; + float num2 = (float)terrain.terrainData.alphamapHeight; + DynamicGI.UpdateMaterialsForTerrain(terrain, new Rect((float)x / num, (float)y / num2, (float)width / num, (float)height / num2)); + } + internal static void UpdateMaterialsForTerrain(Terrain terrain, Rect uvBounds) + { + DynamicGI.INTERNAL_CALL_UpdateMaterialsForTerrain(terrain, ref uvBounds); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_UpdateMaterialsForTerrain(Terrain terrain, ref Rect uvBounds); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void UpdateEnvironment(); + } +} diff --git a/UnityEngine/UnityEngine/Effector2D.cs b/UnityEngine/UnityEngine/Effector2D.cs new file mode 100644 index 00000000..f0c9aa1d --- /dev/null +++ b/UnityEngine/UnityEngine/Effector2D.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public class Effector2D : Behaviour + { + public extern int colliderMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + internal extern bool requiresCollider + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool designedForTrigger + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + internal extern bool designedForNonTrigger + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + } +} diff --git a/UnityEngine/UnityEngine/EffectorForceMode2D.cs b/UnityEngine/UnityEngine/EffectorForceMode2D.cs new file mode 100644 index 00000000..f981774c --- /dev/null +++ b/UnityEngine/UnityEngine/EffectorForceMode2D.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum EffectorForceMode2D + { + Constant, + InverseLinear, + InverseSquared + } +} diff --git a/UnityEngine/UnityEngine/EffectorSelection2D.cs b/UnityEngine/UnityEngine/EffectorSelection2D.cs new file mode 100644 index 00000000..329e30cf --- /dev/null +++ b/UnityEngine/UnityEngine/EffectorSelection2D.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum EffectorSelection2D + { + Rigidbody, + Collider + } +} diff --git a/UnityEngine/UnityEngine/EllipsoidParticleEmitter.cs b/UnityEngine/UnityEngine/EllipsoidParticleEmitter.cs new file mode 100644 index 00000000..855b3ff8 --- /dev/null +++ b/UnityEngine/UnityEngine/EllipsoidParticleEmitter.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public sealed class EllipsoidParticleEmitter : ParticleEmitter + { + internal EllipsoidParticleEmitter() + { + } + } +} diff --git a/UnityEngine/UnityEngine/Event.cs b/UnityEngine/UnityEngine/Event.cs index 5b78b144..1103f397 100644 --- a/UnityEngine/UnityEngine/Event.cs +++ b/UnityEngine/UnityEngine/Event.cs @@ -6,7 +6,6 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public sealed class Event { - [NotRenamed] [NonSerialized] internal IntPtr m_Ptr; private static Event s_Current; @@ -657,13 +656,13 @@ public override bool Equals(object obj) return false; } Event @event = (Event)obj; - if (this.type != @event.type || this.modifiers != @event.modifiers) + if (this.type != @event.type || (this.modifiers & ~EventModifiers.CapsLock) != (@event.modifiers & ~EventModifiers.CapsLock)) { return false; } if (this.isKey) { - return this.keyCode == @event.keyCode && this.modifiers == @event.modifiers; + return this.keyCode == @event.keyCode; } return this.isMouse && this.mousePosition == @event.mousePosition; } diff --git a/UnityEngine/UnityEngine/FlareLayer.cs b/UnityEngine/UnityEngine/FlareLayer.cs new file mode 100644 index 00000000..d6169352 --- /dev/null +++ b/UnityEngine/UnityEngine/FlareLayer.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public sealed class FlareLayer : Behaviour + { + internal FlareLayer() + { + } + } +} diff --git a/UnityEngine/UnityEngine/Font.cs b/UnityEngine/UnityEngine/Font.cs index 6245065d..95d023f7 100644 --- a/UnityEngine/UnityEngine/Font.cs +++ b/UnityEngine/UnityEngine/Font.cs @@ -1,11 +1,26 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; using UnityEngine.Internal; namespace UnityEngine { public sealed class Font : Object { + [EditorBrowsable(EditorBrowsableState.Never)] public delegate void FontTextureRebuildCallback(); + public static event Action textureRebuilt + { + [MethodImpl(MethodImplOptions.Synchronized)] + add + { + Font.textureRebuilt = (Action)Delegate.Combine(Font.textureRebuilt, value); + } + [MethodImpl(MethodImplOptions.Synchronized)] + remove + { + Font.textureRebuilt = (Action)Delegate.Remove(Font.textureRebuilt, value); + } + } private event Font.FontTextureRebuildCallback m_FontTextureRebuildCallback { [MethodImpl(MethodImplOptions.Synchronized)] @@ -46,6 +61,7 @@ public extern CharacterInfo[] characterInfo [MethodImpl(MethodImplOptions.InternalCall)] set; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Font.textureRebuildCallback has been deprecated. Use Font.textureRebuilt instead.")] public Font.FontTextureRebuildCallback textureRebuildCallback { get @@ -63,6 +79,18 @@ public extern bool dynamic [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern int ascent + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int lineHeight + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern int fontSize { [WrapperlessIcall] @@ -77,15 +105,36 @@ public Font(string name) { Font.Internal_CreateFont(this, name); } + private Font(string[] names, int size) + { + Font.Internal_CreateDynamicFont(this, names, size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern string[] GetOSInstalledFontNames(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_CreateFont([Writable] Font _font, string name); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CreateDynamicFont([Writable] Font _font, string[] _names, int size); + public static Font CreateDynamicFontFromOSFont(string fontname, int size) + { + return new Font(new string[] + { + fontname + }, size); + } + public static Font CreateDynamicFontFromOSFont(string[] fontnames, int size) + { + return new Font(fontnames, size); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public extern bool HasCharacter(char c); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void RequestCharactersInTexture(string characters, [DefaultValue("0")] int size, [DefaultValue("FontStyle.Normal")] FontStyle style); + public extern void RequestCharactersInTexture(string characters, [UnityEngine.Internal.DefaultValue("0")] int size, [UnityEngine.Internal.DefaultValue("FontStyle.Normal")] FontStyle style); [ExcludeFromDocs] public void RequestCharactersInTexture(string characters, int size) { @@ -99,11 +148,16 @@ public void RequestCharactersInTexture(string characters) int size = 0; this.RequestCharactersInTexture(characters, size, style); } - private void InvokeTextureRebuilt_Internal() + private static void InvokeTextureRebuilt_Internal(Font font) { - if (this.m_FontTextureRebuildCallback != null) + Action action = Font.textureRebuilt; + if (action != null) + { + action(font); + } + if (font.m_FontTextureRebuildCallback != null) { - this.m_FontTextureRebuildCallback(); + font.m_FontTextureRebuildCallback(); } } public static int GetMaxVertsForString(string str) @@ -112,7 +166,7 @@ public static int GetMaxVertsForString(string str) } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern bool GetCharacterInfo(char ch, out CharacterInfo info, [DefaultValue("0")] int size, [DefaultValue("FontStyle.Normal")] FontStyle style); + public extern bool GetCharacterInfo(char ch, out CharacterInfo info, [UnityEngine.Internal.DefaultValue("0")] int size, [UnityEngine.Internal.DefaultValue("FontStyle.Normal")] FontStyle style); [ExcludeFromDocs] public bool GetCharacterInfo(char ch, out CharacterInfo info, int size) { diff --git a/UnityEngine/UnityEngine/GL.cs b/UnityEngine/UnityEngine/GL.cs index 8b914b4a..939bf3c6 100644 --- a/UnityEngine/UnityEngine/GL.cs +++ b/UnityEngine/UnityEngine/GL.cs @@ -40,6 +40,15 @@ public static extern bool sRGBWrite [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool invertCulling + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Vertex3(float x, float y, float z); @@ -145,7 +154,7 @@ public static Matrix4x4 GetGPUProjectionMatrix(Matrix4x4 proj, bool renderIntoTe [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern Matrix4x4 INTERNAL_CALL_GetGPUProjectionMatrix(ref Matrix4x4 proj, bool renderIntoTexture); - [WrapperlessIcall] + [Obsolete("Use invertCulling property"), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetRevertBackfacing(bool revertBackFaces); [ExcludeFromDocs] diff --git a/UnityEngine/UnityEngine/GUI.cs b/UnityEngine/UnityEngine/GUI.cs index b9790f93..254f43c5 100644 --- a/UnityEngine/UnityEngine/GUI.cs +++ b/UnityEngine/UnityEngine/GUI.cs @@ -85,6 +85,116 @@ internal Vector2 ScrollNeeded(Rect position) return zero; } } + public abstract class Scope : IDisposable + { + private bool m_Disposed; + protected abstract void CloseScope(); + ~Scope() + { + if (!this.m_Disposed) + { + Debug.LogError("Scope was not disposed! You should use the 'using' keyword or manually call Dispose."); + this.Dispose(); + } + } + public void Dispose() + { + if (this.m_Disposed) + { + return; + } + this.m_Disposed = true; + this.CloseScope(); + } + } + public class GroupScope : GUI.Scope + { + public GroupScope(Rect position) + { + GUI.BeginGroup(position); + } + public GroupScope(Rect position, string text) + { + GUI.BeginGroup(position, text); + } + public GroupScope(Rect position, Texture image) + { + GUI.BeginGroup(position, image); + } + public GroupScope(Rect position, GUIContent content) + { + GUI.BeginGroup(position, content); + } + public GroupScope(Rect position, GUIStyle style) + { + GUI.BeginGroup(position, style); + } + public GroupScope(Rect position, string text, GUIStyle style) + { + GUI.BeginGroup(position, text, style); + } + public GroupScope(Rect position, Texture image, GUIStyle style) + { + GUI.BeginGroup(position, image, style); + } + protected override void CloseScope() + { + GUI.EndGroup(); + } + } + public class ScrollViewScope : GUI.Scope + { + public Vector2 scrollPosition + { + get; + private set; + } + public bool handleScrollWheel + { + get; + set; + } + public ScrollViewScope(Rect position, Vector2 scrollPosition, Rect viewRect) + { + this.handleScrollWheel = true; + this.scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect); + } + public ScrollViewScope(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical) + { + this.handleScrollWheel = true; + this.scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical); + } + public ScrollViewScope(Rect position, Vector2 scrollPosition, Rect viewRect, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar) + { + this.handleScrollWheel = true; + this.scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect, horizontalScrollbar, verticalScrollbar); + } + public ScrollViewScope(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar) + { + this.handleScrollWheel = true; + this.scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar); + } + internal ScrollViewScope(Rect position, Vector2 scrollPosition, Rect viewRect, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background) + { + this.handleScrollWheel = true; + this.scrollPosition = GUI.BeginScrollView(position, scrollPosition, viewRect, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background); + } + protected override void CloseScope() + { + GUI.EndScrollView(this.handleScrollWheel); + } + } + public class ClipScope : GUI.Scope + { + public ClipScope(Rect position) + { + GUI.BeginClip(position); + } + protected override void CloseScope() + { + GUI.EndClip(); + } + } public delegate void WindowFunction(int id); private static float scrollStepSize; private static int scrollControlID; @@ -1312,6 +1422,15 @@ public static void EndGroup() { GUIClip.Pop(); } + public static void BeginClip(Rect position) + { + GUIUtility.CheckOnGUI(); + GUIClip.Push(position, Vector2.zero, Vector2.zero, false); + } + public static void EndClip() + { + GUIClip.Pop(); + } public static Vector2 BeginScrollView(Rect position, Vector2 scrollPosition, Rect viewRect) { return GUI.BeginScrollView(position, scrollPosition, viewRect, false, false, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.scrollView); diff --git a/UnityEngine/UnityEngine/GUIContent.cs b/UnityEngine/UnityEngine/GUIContent.cs index 9ffb7a7a..6b643718 100644 --- a/UnityEngine/UnityEngine/GUIContent.cs +++ b/UnityEngine/UnityEngine/GUIContent.cs @@ -102,6 +102,13 @@ public GUIContent(GUIContent src) internal static GUIContent Temp(string t) { GUIContent.s_Text.m_Text = t; + GUIContent.s_Text.m_Tooltip = string.Empty; + return GUIContent.s_Text; + } + internal static GUIContent Temp(string t, string tooltip) + { + GUIContent.s_Text.m_Text = t; + GUIContent.s_Text.m_Tooltip = tooltip; return GUIContent.s_Text; } internal static GUIContent Temp(Texture i) diff --git a/UnityEngine/UnityEngine/GUILayout.cs b/UnityEngine/UnityEngine/GUILayout.cs index 46fa392f..0ed06001 100644 --- a/UnityEngine/UnityEngine/GUILayout.cs +++ b/UnityEngine/UnityEngine/GUILayout.cs @@ -39,6 +39,142 @@ public void DoWindow(int windowID) this.func(windowID); } } + public class HorizontalScope : GUI.Scope + { + public HorizontalScope(params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(options); + } + public HorizontalScope(GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(style, options); + } + public HorizontalScope(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(text, style, options); + } + public HorizontalScope(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(image, style, options); + } + public HorizontalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginHorizontal(content, style, options); + } + protected override void CloseScope() + { + GUILayout.EndHorizontal(); + } + } + public class VerticalScope : GUI.Scope + { + public VerticalScope(params GUILayoutOption[] options) + { + GUILayout.BeginVertical(options); + } + public VerticalScope(GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(style, options); + } + public VerticalScope(string text, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(text, style, options); + } + public VerticalScope(Texture image, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(image, style, options); + } + public VerticalScope(GUIContent content, GUIStyle style, params GUILayoutOption[] options) + { + GUILayout.BeginVertical(content, style, options); + } + protected override void CloseScope() + { + GUILayout.EndVertical(); + } + } + public class AreaScope : GUI.Scope + { + public AreaScope(Rect screenRect) + { + GUILayout.BeginArea(screenRect); + } + public AreaScope(Rect screenRect, string text) + { + GUILayout.BeginArea(screenRect, text); + } + public AreaScope(Rect screenRect, Texture image) + { + GUILayout.BeginArea(screenRect, image); + } + public AreaScope(Rect screenRect, GUIContent content) + { + GUILayout.BeginArea(screenRect, content); + } + public AreaScope(Rect screenRect, string text, GUIStyle style) + { + GUILayout.BeginArea(screenRect, text, style); + } + public AreaScope(Rect screenRect, Texture image, GUIStyle style) + { + GUILayout.BeginArea(screenRect, image, style); + } + public AreaScope(Rect screenRect, GUIContent content, GUIStyle style) + { + GUILayout.BeginArea(screenRect, content, style); + } + protected override void CloseScope() + { + GUILayout.EndArea(); + } + } + public class ScrollViewScope : GUI.Scope + { + public Vector2 scrollPosition + { + get; + private set; + } + public bool handleScrollWheel + { + get; + set; + } + public ScrollViewScope(Vector2 scrollPosition, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, options); + } + public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, options); + } + public ScrollViewScope(Vector2 scrollPosition, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, horizontalScrollbar, verticalScrollbar, options); + } + public ScrollViewScope(Vector2 scrollPosition, GUIStyle style, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, style, options); + } + public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, options); + } + public ScrollViewScope(Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, GUIStyle horizontalScrollbar, GUIStyle verticalScrollbar, GUIStyle background, params GUILayoutOption[] options) + { + this.handleScrollWheel = true; + this.scrollPosition = GUILayout.BeginScrollView(scrollPosition, alwaysShowHorizontal, alwaysShowVertical, horizontalScrollbar, verticalScrollbar, background, options); + } + protected override void CloseScope() + { + GUILayout.EndScrollView(this.handleScrollWheel); + } + } public static void Label(Texture image, params GUILayoutOption[] options) { GUILayout.DoLabel(GUIContent.Temp(image), GUI.skin.label, options); diff --git a/UnityEngine/UnityEngine/GUISkin.cs b/UnityEngine/UnityEngine/GUISkin.cs index 50da04cc..99fe048b 100644 --- a/UnityEngine/UnityEngine/GUISkin.cs +++ b/UnityEngine/UnityEngine/GUISkin.cs @@ -351,10 +351,6 @@ public GUISkin() internal void OnEnable() { this.Apply(); - foreach (GUIStyle gUIStyle in this.styles.Values) - { - gUIStyle.CreateObjectReferences(); - } } internal void Apply() { diff --git a/UnityEngine/UnityEngine/GUIStyle.cs b/UnityEngine/UnityEngine/GUIStyle.cs index 077699cb..c92bc8c5 100644 --- a/UnityEngine/UnityEngine/GUIStyle.cs +++ b/UnityEngine/UnityEngine/GUIStyle.cs @@ -8,7 +8,6 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public sealed class GUIStyle { - [NotRenamed] [NonSerialized] internal IntPtr m_Ptr; [NonSerialized] @@ -414,17 +413,17 @@ public GUIStyle(GUIStyle other) { this.Cleanup(); } - internal void CreateObjectReferences() + internal void InternalOnAfterDeserialize() { this.m_FontInternal = this.GetFontInternal(); - this.normal.RefreshAssetReference(); - this.hover.RefreshAssetReference(); - this.active.RefreshAssetReference(); - this.focused.RefreshAssetReference(); - this.onNormal.RefreshAssetReference(); - this.onHover.RefreshAssetReference(); - this.onActive.RefreshAssetReference(); - this.onFocused.RefreshAssetReference(); + this.m_Normal = new GUIStyleState(this, this.GetStyleStatePtr(0)); + this.m_Hover = new GUIStyleState(this, this.GetStyleStatePtr(1)); + this.m_Active = new GUIStyleState(this, this.GetStyleStatePtr(2)); + this.m_Focused = new GUIStyleState(this, this.GetStyleStatePtr(3)); + this.m_OnNormal = new GUIStyleState(this, this.GetStyleStatePtr(4)); + this.m_OnHover = new GUIStyleState(this, this.GetStyleStatePtr(5)); + this.m_OnActive = new GUIStyleState(this, this.GetStyleStatePtr(6)); + this.m_OnFocused = new GUIStyleState(this, this.GetStyleStatePtr(7)); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/GUIStyleState.cs b/UnityEngine/UnityEngine/GUIStyleState.cs index 3af244f3..6c01a1fb 100644 --- a/UnityEngine/UnityEngine/GUIStyleState.cs +++ b/UnityEngine/UnityEngine/GUIStyleState.cs @@ -7,12 +7,11 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public sealed class GUIStyleState { - [NotRenamed] [NonSerialized] internal IntPtr m_Ptr; private GUIStyle m_SourceStyle; [NonSerialized] - private Texture2D m_BackgroundInternal; + private Texture2D m_Background; public Texture2D background { get @@ -22,7 +21,7 @@ public Texture2D background set { this.SetBackgroundInternal(value); - this.m_BackgroundInternal = value; + this.m_Background = value; } } public Color textColor @@ -46,11 +45,7 @@ internal GUIStyleState(GUIStyle sourceStyle, IntPtr source) { this.m_SourceStyle = sourceStyle; this.m_Ptr = source; - this.RefreshAssetReference(); - } - internal void RefreshAssetReference() - { - this.m_BackgroundInternal = this.GetBackgroundInternal(); + this.m_Background = this.GetBackgroundInternal(); } ~GUIStyleState() { diff --git a/UnityEngine/UnityEngine/GUIUtility.cs b/UnityEngine/UnityEngine/GUIUtility.cs index b3fec09d..b33880db 100644 --- a/UnityEngine/UnityEngine/GUIUtility.cs +++ b/UnityEngine/UnityEngine/GUIUtility.cs @@ -4,9 +4,7 @@ namespace UnityEngine { public class GUIUtility { - [NotRenamed] internal static int s_SkinMode; - [NotRenamed] internal static int s_OriginalID; internal static Vector2 s_EditorScreenPointOffset = Vector2.zero; internal static bool s_HasKeyboardFocus = false; diff --git a/UnityEngine/UnityEngine/GameObject.cs b/UnityEngine/UnityEngine/GameObject.cs index bce3731f..c2d4b625 100644 --- a/UnityEngine/UnityEngine/GameObject.cs +++ b/UnityEngine/UnityEngine/GameObject.cs @@ -1,181 +1,215 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using System.Security; using UnityEngine.Internal; using UnityEngineInternal; namespace UnityEngine { public sealed class GameObject : Object { - public extern bool isStatic + public extern Transform transform { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; } - internal extern bool isStaticBatchable + public extern int layer { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public extern Transform transform - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public extern Rigidbody rigidbody + [Obsolete("GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.")] + public extern bool active { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public extern Rigidbody2D rigidbody2D - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public extern Camera camera + public extern bool activeSelf { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern Light light + public extern bool activeInHierarchy { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern Animation animation + public extern bool isStatic { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public extern ConstantForce constantForce - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public extern Renderer renderer + internal extern bool isStaticBatchable { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern AudioSource audio + public extern string tag { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - } - public extern GUIText guiText - { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - get; + set; } - public extern NetworkView networkView + public GameObject gameObject { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return this; + } } - [Obsolete("Please use guiTexture instead")] - public extern GUIElement guiElement + [Obsolete("Property rigidbody has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component rigidbody { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("rigidbody property has been deprecated"); + } } - public extern GUITexture guiTexture + [Obsolete("Property rigidbody2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component rigidbody2D { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("rigidbody2D property has been deprecated"); + } } - public extern Collider collider + [Obsolete("Property camera has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component camera { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("camera property has been deprecated"); + } } - public extern Collider2D collider2D + [Obsolete("Property light has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component light { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("light property has been deprecated"); + } } - public extern HingeJoint hingeJoint + [Obsolete("Property animation has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component animation { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("animation property has been deprecated"); + } } - public extern ParticleEmitter particleEmitter + [Obsolete("Property constantForce has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component constantForce { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("constantForce property has been deprecated"); + } } - public extern ParticleSystem particleSystem + [Obsolete("Property renderer has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component renderer { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("renderer property has been deprecated"); + } } - public extern int layer + [Obsolete("Property audio has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component audio { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + throw new NotSupportedException("audio property has been deprecated"); + } } - [Obsolete("GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.")] - public extern bool active + [Obsolete("Property guiText has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiText { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + throw new NotSupportedException("guiText property has been deprecated"); + } } - public extern bool activeSelf + [Obsolete("Property networkView has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component networkView { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("networkView property has been deprecated"); + } } - public extern bool activeInHierarchy + [Obsolete("Property guiElement has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiElement { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + throw new NotSupportedException("guiElement property has been deprecated"); + } } - public extern string tag + [Obsolete("Property guiTexture has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component guiTexture { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + throw new NotSupportedException("guiTexture property has been deprecated"); + } } - public GameObject gameObject + [Obsolete("Property collider has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component collider { get { - return this; + throw new NotSupportedException("collider property has been deprecated"); + } + } + [Obsolete("Property collider2D has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component collider2D + { + get + { + throw new NotSupportedException("collider2D property has been deprecated"); + } + } + [Obsolete("Property hingeJoint has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component hingeJoint + { + get + { + throw new NotSupportedException("hingeJoint property has been deprecated"); + } + } + [Obsolete("Property particleEmitter has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component particleEmitter + { + get + { + throw new NotSupportedException("particleEmitter property has been deprecated"); + } + } + [Obsolete("Property particleSystem has been deprecated. Use GetComponent() instead. (UnityUpgradable)", true)] + public Component particleSystem + { + get + { + throw new NotSupportedException("particleSystem property has been deprecated"); } } public GameObject(string name) @@ -197,24 +231,27 @@ public GameObject(string name, params Type[] components) } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SampleAnimation(AnimationClip animation, float time); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public static extern GameObject CreatePrimitive(PrimitiveType type); [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] [MethodImpl(MethodImplOptions.InternalCall)] public extern Component GetComponent(Type type); - public T GetComponent() where T : Component + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue); + [SecuritySafeCritical] + public unsafe T GetComponent() { - return this.GetComponent(typeof(T)) as T; + CastHelper castHelper = default(CastHelper); + this.GetComponentFastPath(typeof(T), new IntPtr((void*)(&castHelper.onePointerFurtherThanT))); + return castHelper.t; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern Component GetComponentByName(string type); public Component GetComponent(string type) { return this.GetComponentByName(type); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern Component GetComponentByName(string type); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInChildren(Type type) { @@ -240,9 +277,9 @@ public Component GetComponentInChildren(Type type) } return null; } - public T GetComponentInChildren() where T : Component + public T GetComponentInChildren() { - return this.GetComponentInChildren(typeof(T)) as T; + return (T)((object)this.GetComponentInChildren(typeof(T))); } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInParent(Type type) @@ -273,30 +310,25 @@ public Component GetComponentInParent(Type type) } return null; } - public T GetComponentInParent() where T : Component + public T GetComponentInParent() { - return this.GetComponentInParent(typeof(T)) as T; + return (T)((object)this.GetComponentInParent(typeof(T))); } - public void GetComponentsInParent(bool includeInactive, List results) where T : Component - { - this.GetComponentsForListInternal(typeof(T), typeof(T), true, includeInactive, true, results); - } - [CanConvertToFlash] public Component[] GetComponents(Type type) { - return this.GetComponentsInternal(type, false, false, true, false); + return (Component[])this.GetComponentsInternal(type, false, false, true, false, null); } - public T[] GetComponents() where T : Component + public T[] GetComponents() { - return (T[])this.GetComponentsInternal(typeof(T), true, false, true, false); + return (T[])this.GetComponentsInternal(typeof(T), true, false, true, false, null); } public void GetComponents(Type type, List results) { - this.GetComponentsForListInternal(type, typeof(Component), false, true, false, results); + this.GetComponentsInternal(type, false, false, true, false, results); } - public void GetComponents(List results) where T : Component + public void GetComponents(List results) { - this.GetComponentsForListInternal(typeof(T), typeof(T), false, true, false, results); + this.GetComponentsInternal(typeof(T), false, false, true, false, results); } [ExcludeFromDocs] public Component[] GetComponentsInChildren(Type type) @@ -306,21 +338,21 @@ public Component[] GetComponentsInChildren(Type type) } public Component[] GetComponentsInChildren(Type type, [DefaultValue("false")] bool includeInactive) { - return this.GetComponentsInternal(type, false, true, includeInactive, false); + return (Component[])this.GetComponentsInternal(type, false, true, includeInactive, false, null); } - public T[] GetComponentsInChildren(bool includeInactive) where T : Component + public T[] GetComponentsInChildren(bool includeInactive) { - return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, false); + return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, false, null); } - public void GetComponentsInChildren(bool includeInactive, List results) where T : Component + public void GetComponentsInChildren(bool includeInactive, List results) { - this.GetComponentsForListInternal(typeof(T), typeof(T), true, includeInactive, false, results); + this.GetComponentsInternal(typeof(T), true, true, includeInactive, false, results); } - public T[] GetComponentsInChildren() where T : Component + public T[] GetComponentsInChildren() { return this.GetComponentsInChildren(false); } - public void GetComponentsInChildren(List results) where T : Component + public void GetComponentsInChildren(List results) { this.GetComponentsInChildren(false, results); } @@ -332,22 +364,26 @@ public Component[] GetComponentsInParent(Type type) } public Component[] GetComponentsInParent(Type type, [DefaultValue("false")] bool includeInactive) { - return this.GetComponentsInternal(type, false, true, includeInactive, true); + return (Component[])this.GetComponentsInternal(type, false, true, includeInactive, true, null); } - public T[] GetComponentsInParent(bool includeInactive) where T : Component + public void GetComponentsInParent(bool includeInactive, List results) { - return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, true); + this.GetComponentsInternal(typeof(T), true, true, includeInactive, true, results); } - public T[] GetComponentsInParent() where T : Component + public T[] GetComponentsInParent(bool includeInactive) + { + return (T[])this.GetComponentsInternal(typeof(T), true, true, includeInactive, true, null); + } + public T[] GetComponentsInParent() { return this.GetComponentsInParent(false); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void GetComponentsForListInternal(Type searchType, Type listElementType, bool recursive, bool includeInactive, bool reverse, object resultList); + private extern Array GetComponentsInternal(Type type, bool useSearchTypeAsArrayReturnType, bool recursive, bool includeInactive, bool reverse, object resultList); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern Component[] GetComponentsInternal(Type type, bool isGenericTypeArray, bool recursive, bool includeInactive, bool reverse); + internal extern Component AddComponentInternal(string className); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetActive(bool value); @@ -429,15 +465,12 @@ public void BroadcastMessage(string methodName, SendMessageOptions options) } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern Component AddComponent(string className); + private extern Component Internal_AddComponentWithType(Type componentType); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component AddComponent(Type componentType) { return this.Internal_AddComponentWithType(componentType); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern Component Internal_AddComponentWithType(Type componentType); public T AddComponent() where T : Component { return this.AddComponent(typeof(T)) as T; @@ -445,14 +478,28 @@ public T AddComponent() where T : Component [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_CreateGameObject([Writable] GameObject mono, string name); - [Obsolete("gameObject.PlayAnimation is not supported anymore. Use animation.Play"), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void PlayAnimation(AnimationClip animation); - [Obsolete("gameObject.StopAnimation is not supported anymore. Use animation.Stop"), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void StopAnimation(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern GameObject Find(string name); + [Obsolete("GameObject.SampleAnimation(AnimationClip, float) has been deprecated. Use AnimationClip.SampleAnimation(GameObject, float) instead (UnityUpgradable).", true)] + public void SampleAnimation(Object clip, float time) + { + throw new NotSupportedException("GameObject.SampleAnimation is deprecated"); + } + [Obsolete("GameObject.AddComponent with string argument has been deprecated. Use GameObject.AddComponent() instead. (UnityUpgradable).", true)] + public Component AddComponent(string className) + { + throw new NotSupportedException("AddComponent(string) is deprecated"); + } + [Obsolete("gameObject.PlayAnimation is not supported anymore. Use animation.Play()", true)] + public void PlayAnimation(Object animation) + { + throw new NotSupportedException("gameObject.PlayAnimation is not supported anymore. Use animation.Play();"); + } + [Obsolete("gameObject.StopAnimation is not supported anymore. Use animation.Stop()", true)] + public void StopAnimation() + { + throw new NotSupportedException("gameObject.StopAnimation(); is not supported anymore. Use animation.Stop();"); + } } } diff --git a/UnityEngine/UnityEngine/Gizmos.cs b/UnityEngine/UnityEngine/Gizmos.cs index cb6d47a9..12f09ab8 100644 --- a/UnityEngine/UnityEngine/Gizmos.cs +++ b/UnityEngine/UnityEngine/Gizmos.cs @@ -74,6 +74,112 @@ public static void DrawCube(Vector3 center, Vector3 size) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_DrawCube(ref Vector3 center, ref Vector3 size); + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation) + { + Vector3 one = Vector3.one; + Gizmos.DrawMesh(mesh, position, rotation, one); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Gizmos.DrawMesh(mesh, position, identity, one); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Vector3 zero = Vector3.zero; + Gizmos.DrawMesh(mesh, zero, identity, one); + } + public static void DrawMesh(Mesh mesh, [DefaultValue("Vector3.zero")] Vector3 position, [DefaultValue("Quaternion.identity")] Quaternion rotation, [DefaultValue("Vector3.one")] Vector3 scale) + { + Gizmos.DrawMesh(mesh, -1, position, rotation, scale); + } + public static void DrawMesh(Mesh mesh, int submeshIndex, [DefaultValue("Vector3.zero")] Vector3 position, [DefaultValue("Quaternion.identity")] Quaternion rotation, [DefaultValue("Vector3.one")] Vector3 scale) + { + Gizmos.INTERNAL_CALL_DrawMesh(mesh, submeshIndex, ref position, ref rotation, ref scale); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, int submeshIndex, Vector3 position, Quaternion rotation) + { + Vector3 one = Vector3.one; + Gizmos.INTERNAL_CALL_DrawMesh(mesh, submeshIndex, ref position, ref rotation, ref one); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, int submeshIndex, Vector3 position) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Gizmos.INTERNAL_CALL_DrawMesh(mesh, submeshIndex, ref position, ref identity, ref one); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, int submeshIndex) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Vector3 zero = Vector3.zero; + Gizmos.INTERNAL_CALL_DrawMesh(mesh, submeshIndex, ref zero, ref identity, ref one); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawMesh(Mesh mesh, int submeshIndex, ref Vector3 position, ref Quaternion rotation, ref Vector3 scale); + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh, Vector3 position, Quaternion rotation) + { + Vector3 one = Vector3.one; + Gizmos.DrawWireMesh(mesh, position, rotation, one); + } + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh, Vector3 position) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Gizmos.DrawWireMesh(mesh, position, identity, one); + } + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Vector3 zero = Vector3.zero; + Gizmos.DrawWireMesh(mesh, zero, identity, one); + } + public static void DrawWireMesh(Mesh mesh, [DefaultValue("Vector3.zero")] Vector3 position, [DefaultValue("Quaternion.identity")] Quaternion rotation, [DefaultValue("Vector3.one")] Vector3 scale) + { + Gizmos.DrawWireMesh(mesh, -1, position, rotation, scale); + } + public static void DrawWireMesh(Mesh mesh, int submeshIndex, [DefaultValue("Vector3.zero")] Vector3 position, [DefaultValue("Quaternion.identity")] Quaternion rotation, [DefaultValue("Vector3.one")] Vector3 scale) + { + Gizmos.INTERNAL_CALL_DrawWireMesh(mesh, submeshIndex, ref position, ref rotation, ref scale); + } + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh, int submeshIndex, Vector3 position, Quaternion rotation) + { + Vector3 one = Vector3.one; + Gizmos.INTERNAL_CALL_DrawWireMesh(mesh, submeshIndex, ref position, ref rotation, ref one); + } + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh, int submeshIndex, Vector3 position) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Gizmos.INTERNAL_CALL_DrawWireMesh(mesh, submeshIndex, ref position, ref identity, ref one); + } + [ExcludeFromDocs] + public static void DrawWireMesh(Mesh mesh, int submeshIndex) + { + Vector3 one = Vector3.one; + Quaternion identity = Quaternion.identity; + Vector3 zero = Vector3.zero; + Gizmos.INTERNAL_CALL_DrawWireMesh(mesh, submeshIndex, ref zero, ref identity, ref one); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_DrawWireMesh(Mesh mesh, int submeshIndex, ref Vector3 position, ref Quaternion rotation, ref Vector3 scale); public static void DrawIcon(Vector3 center, string name, [DefaultValue("true")] bool allowScaling) { Gizmos.INTERNAL_CALL_DrawIcon(ref center, name, allowScaling); diff --git a/UnityEngine/UnityEngine/Graphics.cs b/UnityEngine/UnityEngine/Graphics.cs index 6a690c8f..3c5c071b 100644 --- a/UnityEngine/UnityEngine/Graphics.cs +++ b/UnityEngine/UnityEngine/Graphics.cs @@ -1,6 +1,8 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; using UnityEngine.Internal; +using UnityEngine.Rendering; namespace UnityEngine { public sealed class Graphics @@ -23,7 +25,7 @@ public static RenderBuffer activeDepthBuffer return result; } } - [Obsolete("Use SystemInfo.graphicsDeviceName instead.")] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property deviceName has been deprecated. Use SystemInfo.graphicsDeviceName instead (UnityUpgradable).", true)] public static string deviceName { get @@ -31,7 +33,7 @@ public static string deviceName return SystemInfo.graphicsDeviceName; } } - [Obsolete("Use SystemInfo.graphicsDeviceVendor instead.")] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property deviceVendor has been deprecated. Use SystemInfo.graphicsDeviceVendor instead (UnityUpgradable).", true)] public static string deviceVendor { get @@ -39,7 +41,7 @@ public static string deviceVendor return SystemInfo.graphicsDeviceVendor; } } - [Obsolete("Use SystemInfo.graphicsDeviceVersion instead.")] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property deviceVersion has been deprecated. Use SystemInfo.graphicsDeviceVersion instead (UnityUpgradable).", true)] public static string deviceVersion { get @@ -47,95 +49,132 @@ public static string deviceVersion return SystemInfo.graphicsDeviceVersion; } } - [Obsolete("Use SystemInfo.supportsVertexPrograms instead.")] - public static bool supportsVertexProgram + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows) { - get - { - return SystemInfo.supportsVertexPrograms; - } + bool receiveShadows = true; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties) + { + bool receiveShadows = true; + bool castShadows = true; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; - Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; int submeshIndex = 0; - Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; int submeshIndex = 0; Camera camera = null; - Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); + } + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("0")] int submeshIndex, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("true")] bool castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows) + { + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, (!castShadows) ? ShadowCastingMode.Off : ShadowCastingMode.On, receiveShadows); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows) + { + Transform probeAnchor = null; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor); } - public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, [DefaultValue("null")] Camera camera, [DefaultValue("0")] int submeshIndex, [DefaultValue("null")] MaterialPropertyBlock properties) + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows) + { + Transform probeAnchor = null; + bool receiveShadows = true; + Graphics.DrawMesh(mesh, position, rotation, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor); + } + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("null")] Transform probeAnchor) { Internal_DrawMeshTRArguments internal_DrawMeshTRArguments = default(Internal_DrawMeshTRArguments); internal_DrawMeshTRArguments.position = position; internal_DrawMeshTRArguments.rotation = rotation; internal_DrawMeshTRArguments.layer = layer; internal_DrawMeshTRArguments.submeshIndex = submeshIndex; - internal_DrawMeshTRArguments.castShadows = 1; - internal_DrawMeshTRArguments.receiveShadows = 1; + internal_DrawMeshTRArguments.castShadows = (int)castShadows; + internal_DrawMeshTRArguments.receiveShadows = ((!receiveShadows) ? 0 : 1); + internal_DrawMeshTRArguments.reflectionProbeAnchorInstanceID = ((!(probeAnchor != null)) ? 0 : probeAnchor.GetInstanceID()); Graphics.Internal_DrawMeshTR(ref internal_DrawMeshTRArguments, properties, material, mesh, camera); } [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows) + { + bool receiveShadows = true; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); + } + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties) + { + bool receiveShadows = true; + bool castShadows = true; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); + } + [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; - Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; int submeshIndex = 0; - Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer) { + bool receiveShadows = true; + bool castShadows = true; MaterialPropertyBlock properties = null; int submeshIndex = 0; Camera camera = null; - Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties); + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } - public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, [DefaultValue("null")] Camera camera, [DefaultValue("0")] int submeshIndex, [DefaultValue("null")] MaterialPropertyBlock properties) + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("0")] int submeshIndex, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("true")] bool castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows) { - Internal_DrawMeshMatrixArguments internal_DrawMeshMatrixArguments = default(Internal_DrawMeshMatrixArguments); - internal_DrawMeshMatrixArguments.matrix = matrix; - internal_DrawMeshMatrixArguments.layer = layer; - internal_DrawMeshMatrixArguments.submeshIndex = submeshIndex; - internal_DrawMeshMatrixArguments.castShadows = 1; - internal_DrawMeshMatrixArguments.receiveShadows = 1; - Graphics.Internal_DrawMeshMatrix(ref internal_DrawMeshMatrixArguments, properties, material, mesh, camera); + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, (!castShadows) ? ShadowCastingMode.Off : ShadowCastingMode.On, receiveShadows); } - public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) + [ExcludeFromDocs] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows) { - Internal_DrawMeshTRArguments internal_DrawMeshTRArguments = default(Internal_DrawMeshTRArguments); - internal_DrawMeshTRArguments.position = position; - internal_DrawMeshTRArguments.rotation = rotation; - internal_DrawMeshTRArguments.layer = layer; - internal_DrawMeshTRArguments.submeshIndex = submeshIndex; - internal_DrawMeshTRArguments.castShadows = ((!castShadows) ? 0 : 1); - internal_DrawMeshTRArguments.receiveShadows = ((!receiveShadows) ? 0 : 1); - Graphics.Internal_DrawMeshTR(ref internal_DrawMeshTRArguments, properties, material, mesh, camera); + bool receiveShadows = true; + Graphics.DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows); } - public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows) { Internal_DrawMeshMatrixArguments internal_DrawMeshMatrixArguments = default(Internal_DrawMeshMatrixArguments); internal_DrawMeshMatrixArguments.matrix = matrix; internal_DrawMeshMatrixArguments.layer = layer; internal_DrawMeshMatrixArguments.submeshIndex = submeshIndex; - internal_DrawMeshMatrixArguments.castShadows = ((!castShadows) ? 0 : 1); + internal_DrawMeshMatrixArguments.castShadows = (int)castShadows; internal_DrawMeshMatrixArguments.receiveShadows = ((!receiveShadows) ? 0 : 1); Graphics.Internal_DrawMeshMatrix(ref internal_DrawMeshMatrixArguments, properties, material, mesh, camera); } @@ -177,7 +216,7 @@ private static void Internal_DrawMeshNow2(Mesh mesh, Matrix4x4 matrix, int mater private static extern void INTERNAL_CALL_Internal_DrawMeshNow2(Mesh mesh, ref Matrix4x4 matrix, int materialIndex); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void DrawProcedural(MeshTopology topology, int vertexCount, [DefaultValue("1")] int instanceCount); + public static extern void DrawProcedural(MeshTopology topology, int vertexCount, [UnityEngine.Internal.DefaultValue("1")] int instanceCount); [ExcludeFromDocs] public static void DrawProcedural(MeshTopology topology, int vertexCount) { @@ -186,7 +225,7 @@ public static void DrawProcedural(MeshTopology topology, int vertexCount) } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void DrawProceduralIndirect(MeshTopology topology, ComputeBuffer bufferWithArgs, [DefaultValue("0")] int argsOffset); + public static extern void DrawProceduralIndirect(MeshTopology topology, ComputeBuffer bufferWithArgs, [UnityEngine.Internal.DefaultValue("0")] int argsOffset); [ExcludeFromDocs] public static void DrawProceduralIndirect(MeshTopology topology, ComputeBuffer bufferWithArgs) { @@ -200,33 +239,13 @@ internal static void DrawSprite(Sprite sprite, Matrix4x4 matrix, Material materi [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_DrawSprite(Sprite sprite, ref Matrix4x4 matrix, Material material, int layer, Camera camera, ref Color color, MaterialPropertyBlock properties); - [Obsolete("Use Graphics.DrawMeshNow instead.")] - public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation) - { - Graphics.Internal_DrawMeshNow1(mesh, position, rotation, -1); - } - [Obsolete("Use Graphics.DrawMeshNow instead.")] - public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) - { - Graphics.Internal_DrawMeshNow1(mesh, position, rotation, materialIndex); - } - [Obsolete("Use Graphics.DrawMeshNow instead.")] - public static void DrawMesh(Mesh mesh, Matrix4x4 matrix) - { - Graphics.Internal_DrawMeshNow2(mesh, matrix, -1); - } - [Obsolete("Use Graphics.DrawMeshNow instead.")] - public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, int materialIndex) - { - Graphics.Internal_DrawMeshNow2(mesh, matrix, materialIndex); - } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture) { Material mat = null; Graphics.DrawTexture(screenRect, texture, mat); } - public static void DrawTexture(Rect screenRect, Texture texture, [DefaultValue("null")] Material mat) + public static void DrawTexture(Rect screenRect, Texture texture, [UnityEngine.Internal.DefaultValue("null")] Material mat) { Graphics.DrawTexture(screenRect, texture, 0, 0, 0, 0, mat); } @@ -236,7 +255,7 @@ public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, Material mat = null; Graphics.DrawTexture(screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); } - public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [DefaultValue("null")] Material mat) + public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat) { Graphics.DrawTexture(screenRect, texture, new Rect(0f, 0f, 1f, 1f), leftBorder, rightBorder, topBorder, bottomBorder, mat); } @@ -246,7 +265,7 @@ public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect Material mat = null; Graphics.DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, mat); } - public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [DefaultValue("null")] Material mat) + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat) { InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); internalDrawTextureArguments.screenRect = screenRect; @@ -268,7 +287,7 @@ public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect Material mat = null; Graphics.DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, mat); } - public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, [DefaultValue("null")] Material mat) + public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, [UnityEngine.Internal.DefaultValue("null")] Material mat) { InternalDrawTextureArguments internalDrawTextureArguments = default(InternalDrawTextureArguments); internalDrawTextureArguments.screenRect = screenRect; @@ -287,6 +306,9 @@ public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect internal static extern void DrawTexture(ref InternalDrawTextureArguments arguments); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ExecuteCommandBuffer(CommandBuffer buffer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Blit(Texture source, RenderTexture dest); [ExcludeFromDocs] public static void Blit(Texture source, RenderTexture dest, Material mat) @@ -294,7 +316,7 @@ public static void Blit(Texture source, RenderTexture dest, Material mat) int pass = -1; Graphics.Blit(source, dest, mat, pass); } - public static void Blit(Texture source, RenderTexture dest, Material mat, [DefaultValue("-1")] int pass) + public static void Blit(Texture source, RenderTexture dest, Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { Graphics.Internal_BlitMaterial(source, dest, mat, pass, true); } @@ -304,7 +326,7 @@ public static void Blit(Texture source, Material mat) int pass = -1; Graphics.Blit(source, mat, pass); } - public static void Blit(Texture source, Material mat, [DefaultValue("-1")] int pass) + public static void Blit(Texture source, Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { Graphics.Internal_BlitMaterial(source, null, mat, pass, false); } @@ -318,35 +340,21 @@ public static void BlitMultiTap(Texture source, RenderTexture dest, Material mat [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_BlitMultiTap(Texture source, RenderTexture dest, Material mat, Vector2[] offsets); - public static void SetRenderTarget(RenderTexture rt) - { - Graphics.Internal_SetRT(rt, 0, -1); - } - public static void SetRenderTarget(RenderTexture rt, int mipLevel) - { - Graphics.Internal_SetRT(rt, mipLevel, -1); - } - public static void SetRenderTarget(RenderTexture rt, int mipLevel, CubemapFace face) - { - Graphics.Internal_SetRT(rt, mipLevel, (int)face); - } - public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer) - { - Graphics.Internal_SetRTBuffer(out colorBuffer, out depthBuffer); - } - public static void SetRenderTarget(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer) - { - Graphics.Internal_SetRTBuffers(colorBuffers, out depthBuffer); - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_SetRT(RenderTexture rt, int mipLevel, int face); + private static extern void Internal_SetNullRT(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetRTFullSetup(out RenderBuffer color, out RenderBuffer depth, int mip, int face, RenderBufferLoadAction colorLoad, RenderBufferStoreAction colorStore, RenderBufferLoadAction depthLoad, RenderBufferStoreAction depthStore); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_SetRTBuffer(out RenderBuffer colorBuffer, out RenderBuffer depthBuffer); + private static extern void Internal_SetRTSimple(out RenderBuffer color, out RenderBuffer depth, int mip, int face); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_SetRTBuffers(RenderBuffer[] colorBuffers, out RenderBuffer depthBuffer); + private static extern void Internal_SetMRTFullSetup(RenderBuffer[] color, out RenderBuffer depth, int mip, int face, RenderBufferLoadAction[] colorLoad, RenderBufferStoreAction[] colorStore, RenderBufferLoadAction depthLoad, RenderBufferStoreAction depthStore); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_SetMRTSimple(RenderBuffer[] color, out RenderBuffer depth, int mip, int face); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetActiveColorBuffer(out RenderBuffer res); @@ -370,8 +378,97 @@ public static void SetRandomWriteTarget(int index, ComputeBuffer uav) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_SetRandomWriteTargetBuffer(int index, ComputeBuffer uav); + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Method DrawMesh has been deprecated. Use Graphics.DrawMeshNow instead (UnityUpgradable).", true)] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation) + { + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Method DrawMesh has been deprecated. Use Graphics.DrawMeshNow instead (UnityUpgradable).", true)] + public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) + { + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Method DrawMesh has been deprecated. Use Graphics.DrawMeshNow instead (UnityUpgradable).", true)] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix) + { + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Method DrawMesh has been deprecated. Use Graphics.DrawMeshNow instead (UnityUpgradable).", true)] + public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, int materialIndex) + { + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetupVertexLights(Light[] lights); + internal static void SetRenderTargetImpl(RenderTargetSetup setup) + { + if (setup.color.Length == 0) + { + Debug.LogError("Invalid color buffer count for SetRenderTarget"); + return; + } + if (setup.color.Length != setup.colorLoad.Length) + { + Debug.LogError("Color LoadAction and Buffer arrays have different sizes"); + return; + } + if (setup.color.Length != setup.colorStore.Length) + { + Debug.LogError("Color StoreAction and Buffer arrays have different sizes"); + return; + } + Graphics.Internal_SetMRTFullSetup(setup.color, out setup.depth, setup.mipLevel, setup.cubemapFace, setup.colorLoad, setup.colorStore, setup.depthLoad, setup.depthStore); + } + internal static void SetRenderTargetImpl(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel, int face) + { + RenderBuffer renderBuffer = colorBuffer; + RenderBuffer renderBuffer2 = depthBuffer; + Graphics.Internal_SetRTSimple(out renderBuffer, out renderBuffer2, mipLevel, face); + } + internal static void SetRenderTargetImpl(RenderTexture rt, int mipLevel, int face) + { + if (rt) + { + Graphics.SetRenderTargetImpl(rt.colorBuffer, rt.depthBuffer, mipLevel, face); + } + else + { + Graphics.Internal_SetNullRT(); + } + } + internal static void SetRenderTargetImpl(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer, int mipLevel, int face) + { + RenderBuffer renderBuffer = depthBuffer; + Graphics.Internal_SetMRTSimple(colorBuffers, out renderBuffer, mipLevel, face); + } + public static void SetRenderTarget(RenderTexture rt) + { + Graphics.SetRenderTargetImpl(rt, 0, -1); + } + public static void SetRenderTarget(RenderTexture rt, int mipLevel) + { + Graphics.SetRenderTargetImpl(rt, mipLevel, -1); + } + public static void SetRenderTarget(RenderTexture rt, int mipLevel, CubemapFace face) + { + Graphics.SetRenderTargetImpl(rt, mipLevel, (int)face); + } + public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer) + { + Graphics.SetRenderTargetImpl(colorBuffer, depthBuffer, 0, -1); + } + public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel) + { + Graphics.SetRenderTargetImpl(colorBuffer, depthBuffer, mipLevel, -1); + } + public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel, CubemapFace face) + { + Graphics.SetRenderTargetImpl(colorBuffer, depthBuffer, mipLevel, (int)face); + } + public static void SetRenderTarget(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer) + { + Graphics.SetRenderTargetImpl(colorBuffers, depthBuffer, 0, -1); + } + internal static void SetRenderTarget(RenderTargetSetup setup) + { + Graphics.SetRenderTargetImpl(setup); + } } } diff --git a/UnityEngine/UnityEngine/Handheld.cs b/UnityEngine/UnityEngine/Handheld.cs index 86a7cdb9..37b2c81c 100644 --- a/UnityEngine/UnityEngine/Handheld.cs +++ b/UnityEngine/UnityEngine/Handheld.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using UnityEngine.Internal; +using UnityEngine.iOS; namespace UnityEngine { public sealed class Handheld @@ -48,7 +49,7 @@ public static bool PlayFullScreenMovie(string path) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetActivityIndicatorStyleImpl(int style); - public static void SetActivityIndicatorStyle(iOSActivityIndicatorStyle style) + public static void SetActivityIndicatorStyle(ActivityIndicatorStyle style) { Handheld.SetActivityIndicatorStyleImpl((int)style); } diff --git a/UnityEngine/UnityEngine/Hash128.cs b/UnityEngine/UnityEngine/Hash128.cs new file mode 100644 index 00000000..cd649302 --- /dev/null +++ b/UnityEngine/UnityEngine/Hash128.cs @@ -0,0 +1,25 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct Hash128 + { + private uint m_u32_0; + private uint m_u32_1; + private uint m_u32_2; + private uint m_u32_3; + public Hash128(uint u32_0, uint u32_1, uint u32_2, uint u32_3) + { + this.m_u32_0 = u32_0; + this.m_u32_1 = u32_1; + this.m_u32_2 = u32_2; + this.m_u32_3 = u32_3; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public override extern string ToString(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern Hash128 Parse(string hashString); + } +} diff --git a/UnityEngine/UnityEngine/HideFlags.cs b/UnityEngine/UnityEngine/HideFlags.cs index 8131bf95..916ed865 100644 --- a/UnityEngine/UnityEngine/HideFlags.cs +++ b/UnityEngine/UnityEngine/HideFlags.cs @@ -7,8 +7,11 @@ public enum HideFlags None = 0, HideInHierarchy = 1, HideInInspector = 2, - DontSave = 4, + DontSaveInEditor = 4, NotEditable = 8, - HideAndDontSave = 13 + DontUnloadUnusedAsset = 16, + DontSaveInBuild = 32, + DontSave = 52, + HideAndDontSave = 61 } } diff --git a/UnityEngine/UnityEngine/Input.cs b/UnityEngine/UnityEngine/Input.cs index b6c3ac88..5c692222 100644 --- a/UnityEngine/UnityEngine/Input.cs +++ b/UnityEngine/UnityEngine/Input.cs @@ -40,7 +40,7 @@ public static extern Vector3 mousePosition [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern Vector3 mouseScrollDelta + public static extern Vector2 mouseScrollDelta { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -277,6 +277,9 @@ public static bool GetKeyUp(KeyCode key) public static extern string[] GetJoystickNames(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsJoystickPreconfigured(string joystickName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool GetMouseButton(int button); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/InteractiveCloth.cs b/UnityEngine/UnityEngine/InteractiveCloth.cs deleted file mode 100644 index 51e1144a..00000000 --- a/UnityEngine/UnityEngine/InteractiveCloth.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using UnityEngine.Internal; -namespace UnityEngine -{ - public sealed class InteractiveCloth : Cloth - { - public extern Mesh mesh - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float friction - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float density - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float pressure - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float collisionResponse - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float tearFactor - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float attachmentTearFactor - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern float attachmentResponse - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool isTeared - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public void AddForceAtPosition(Vector3 force, Vector3 position, float radius, [DefaultValue("ForceMode.Force")] ForceMode mode) - { - InteractiveCloth.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, radius, mode); - } - [ExcludeFromDocs] - public void AddForceAtPosition(Vector3 force, Vector3 position, float radius) - { - ForceMode mode = ForceMode.Force; - InteractiveCloth.INTERNAL_CALL_AddForceAtPosition(this, ref force, ref position, radius, mode); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_AddForceAtPosition(InteractiveCloth self, ref Vector3 force, ref Vector3 position, float radius, ForceMode mode); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void AttachToCollider(Collider collider, [DefaultValue("false")] bool tearable, [DefaultValue("false")] bool twoWayInteraction); - [ExcludeFromDocs] - public void AttachToCollider(Collider collider, bool tearable) - { - bool twoWayInteraction = false; - this.AttachToCollider(collider, tearable, twoWayInteraction); - } - [ExcludeFromDocs] - public void AttachToCollider(Collider collider) - { - bool twoWayInteraction = false; - bool tearable = false; - this.AttachToCollider(collider, tearable, twoWayInteraction); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void DetachFromCollider(Collider collider); - } -} diff --git a/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs b/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs index eb92f92a..3e37895a 100644 --- a/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs +++ b/UnityEngine/UnityEngine/InternalStaticBatchingUtility.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; namespace UnityEngine { internal class InternalStaticBatchingUtility @@ -49,7 +50,7 @@ private static Renderer GetRenderer(GameObject go) { return null; } - return meshFilter.renderer; + return meshFilter.GetComponent(); } } private const int MaxVerticesInBatch = 64000; @@ -102,13 +103,16 @@ public static void Combine(GameObject[] gos, GameObject staticBatchRoot) MeshFilter meshFilter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; if (!(meshFilter == null)) { - if (!(meshFilter.sharedMesh == null)) + Mesh sharedMesh = meshFilter.sharedMesh; + if (!(sharedMesh == null) && sharedMesh.canAccess) { - if (meshFilter.sharedMesh.canAccess) + Renderer component = meshFilter.GetComponent(); + if (!(component == null) && component.enabled) { - if (!(meshFilter.renderer == null) && meshFilter.renderer.enabled) + if (component.staticBatchIndex == 0) { - if (meshFilter.renderer.staticBatchIndex == 0) + Material[] array = meshFilter.GetComponent().sharedMaterials; + if (!array.Any((Material m) => m != null && m.shader != null && m.shader.disableBatching != DisableBatchingType.False)) { if (num + meshFilter.sharedMesh.vertexCount > 64000) { @@ -119,12 +123,17 @@ public static void Combine(GameObject[] gos, GameObject staticBatchRoot) num = 0; } MeshSubsetCombineUtility.MeshInstance item = default(MeshSubsetCombineUtility.MeshInstance); - Mesh sharedMesh = meshFilter.sharedMesh; item.meshInstanceID = sharedMesh.GetInstanceID(); + item.rendererInstanceID = component.GetInstanceID(); + MeshRenderer meshRenderer = component as MeshRenderer; + if (meshRenderer != null && meshRenderer.additionalVertexStreams != null) + { + item.additionalVertexStreamsMeshInstanceID = meshRenderer.additionalVertexStreams.GetInstanceID(); + } item.transform = lhs * meshFilter.transform.localToWorldMatrix; - item.lightmapTilingOffset = meshFilter.renderer.lightmapTilingOffset; + item.lightmapScaleOffset = component.lightmapScaleOffset; + item.realtimeLightmapScaleOffset = component.realtimeLightmapScaleOffset; list.Add(item); - Material[] array = meshFilter.renderer.sharedMaterials; if (array.Length > sharedMesh.subMeshCount) { Debug.LogWarning(string.Concat(new object[] @@ -134,13 +143,13 @@ public static void Combine(GameObject[] gos, GameObject staticBatchRoot) ") than subsets (", sharedMesh.subMeshCount, ")" - })); + }), meshFilter.GetComponent()); Material[] array2 = new Material[sharedMesh.subMeshCount]; for (int j = 0; j < sharedMesh.subMeshCount; j++) { - array2[j] = meshFilter.renderer.sharedMaterials[j]; + array2[j] = meshFilter.GetComponent().sharedMaterials[j]; } - meshFilter.renderer.sharedMaterials = array2; + meshFilter.GetComponent().sharedMaterials = array2; array = array2; } for (int k = 0; k < Math.Min(array.Length, sharedMesh.subMeshCount); k++) @@ -188,10 +197,16 @@ private static void MakeBatch(List meshes Mesh sharedMesh = mesh; MeshFilter meshFilter = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter)); meshFilter.sharedMesh = sharedMesh; - gameObject.renderer.SetSubsetIndex(subMeshInstance.subMeshIndex, num); - gameObject.renderer.staticBatchRootTransform = staticBatchRootTransform; - gameObject.renderer.enabled = false; - gameObject.renderer.enabled = true; + Renderer component = gameObject.GetComponent(); + component.SetSubsetIndex(subMeshInstance.subMeshIndex, num); + component.staticBatchRootTransform = staticBatchRootTransform; + component.enabled = false; + component.enabled = true; + MeshRenderer meshRenderer = component as MeshRenderer; + if (meshRenderer != null) + { + meshRenderer.additionalVertexStreams = null; + } num++; } } diff --git a/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs b/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs index 3fbf5218..c4edc668 100644 --- a/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs +++ b/UnityEngine/UnityEngine/Internal_DrawMeshTRArguments.cs @@ -9,5 +9,6 @@ internal struct Internal_DrawMeshTRArguments public Vector3 position; public int castShadows; public int receiveShadows; + public int reflectionProbeAnchorInstanceID; } } diff --git a/UnityEngine/UnityEngine/Joint.cs b/UnityEngine/UnityEngine/Joint.cs index ed84159c..60fedcb9 100644 --- a/UnityEngine/UnityEngine/Joint.cs +++ b/UnityEngine/UnityEngine/Joint.cs @@ -88,6 +88,15 @@ public extern bool enableCollision [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern bool enablePreprocessing + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_axis(out Vector3 value); diff --git a/UnityEngine/UnityEngine/JointLimits.cs b/UnityEngine/UnityEngine/JointLimits.cs index 32d814d9..0f4706cf 100644 --- a/UnityEngine/UnityEngine/JointLimits.cs +++ b/UnityEngine/UnityEngine/JointLimits.cs @@ -9,6 +9,7 @@ public struct JointLimits private float m_Max; private float m_MaxBounce; private float m_MaxHardness; + private float m_ContactDistance; public float min { get @@ -53,5 +54,16 @@ public float maxBounce this.m_MaxBounce = value; } } + public float contactDistance + { + get + { + return this.m_ContactDistance; + } + set + { + this.m_ContactDistance = value; + } + } } } diff --git a/UnityEngine/UnityEngine/KeyCode.cs b/UnityEngine/UnityEngine/KeyCode.cs index f755753f..6d88e5c3 100644 --- a/UnityEngine/UnityEngine/KeyCode.cs +++ b/UnityEngine/UnityEngine/KeyCode.cs @@ -243,6 +243,86 @@ public enum KeyCode Joystick4Button16, Joystick4Button17, Joystick4Button18, - Joystick4Button19 + Joystick4Button19, + Joystick5Button0, + Joystick5Button1, + Joystick5Button2, + Joystick5Button3, + Joystick5Button4, + Joystick5Button5, + Joystick5Button6, + Joystick5Button7, + Joystick5Button8, + Joystick5Button9, + Joystick5Button10, + Joystick5Button11, + Joystick5Button12, + Joystick5Button13, + Joystick5Button14, + Joystick5Button15, + Joystick5Button16, + Joystick5Button17, + Joystick5Button18, + Joystick5Button19, + Joystick6Button0, + Joystick6Button1, + Joystick6Button2, + Joystick6Button3, + Joystick6Button4, + Joystick6Button5, + Joystick6Button6, + Joystick6Button7, + Joystick6Button8, + Joystick6Button9, + Joystick6Button10, + Joystick6Button11, + Joystick6Button12, + Joystick6Button13, + Joystick6Button14, + Joystick6Button15, + Joystick6Button16, + Joystick6Button17, + Joystick6Button18, + Joystick6Button19, + Joystick7Button0, + Joystick7Button1, + Joystick7Button2, + Joystick7Button3, + Joystick7Button4, + Joystick7Button5, + Joystick7Button6, + Joystick7Button7, + Joystick7Button8, + Joystick7Button9, + Joystick7Button10, + Joystick7Button11, + Joystick7Button12, + Joystick7Button13, + Joystick7Button14, + Joystick7Button15, + Joystick7Button16, + Joystick7Button17, + Joystick7Button18, + Joystick7Button19, + Joystick8Button0, + Joystick8Button1, + Joystick8Button2, + Joystick8Button3, + Joystick8Button4, + Joystick8Button5, + Joystick8Button6, + Joystick8Button7, + Joystick8Button8, + Joystick8Button9, + Joystick8Button10, + Joystick8Button11, + Joystick8Button12, + Joystick8Button13, + Joystick8Button14, + Joystick8Button15, + Joystick8Button16, + Joystick8Button17, + Joystick8Button18, + Joystick8Button19 } } diff --git a/UnityEngine/UnityEngine/Light.cs b/UnityEngine/UnityEngine/Light.cs index 88917cfc..80206900 100644 --- a/UnityEngine/UnityEngine/Light.cs +++ b/UnityEngine/UnityEngine/Light.cs @@ -35,6 +35,15 @@ public extern float intensity [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float bounceIntensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern LightShadows shadows { [WrapperlessIcall] @@ -62,6 +71,16 @@ public extern float shadowBias [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float shadowNormalBias + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [Obsolete("Shadow softness is removed in Unity 5.0+")] public extern float shadowSoftness { [WrapperlessIcall] @@ -71,6 +90,7 @@ public extern float shadowSoftness [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("Shadow softness is removed in Unity 5.0+")] public extern float shadowSoftnessFade { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/LightProbes.cs b/UnityEngine/UnityEngine/LightProbes.cs index 9612a756..a3f842bf 100644 --- a/UnityEngine/UnityEngine/LightProbes.cs +++ b/UnityEngine/UnityEngine/LightProbes.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using UnityEngine.Rendering; namespace UnityEngine { public sealed class LightProbes : Object @@ -10,7 +11,7 @@ public extern Vector3[] positions [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern float[] coefficients + public extern SphericalHarmonicsL2[] bakedProbes { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -31,12 +32,27 @@ public extern int cellCount [MethodImpl(MethodImplOptions.InternalCall)] get; } - public void GetInterpolatedLightProbe(Vector3 position, Renderer renderer, float[] coefficients) + [Obsolete("coefficients property has been deprecated. Please use bakedProbes instead.", true)] + public float[] coefficients + { + get + { + return new float[0]; + } + set + { + } + } + public static void GetInterpolatedProbe(Vector3 position, Renderer renderer, out SphericalHarmonicsL2 probe) { - LightProbes.INTERNAL_CALL_GetInterpolatedLightProbe(this, ref position, renderer, coefficients); + LightProbes.INTERNAL_CALL_GetInterpolatedProbe(ref position, renderer, out probe); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_GetInterpolatedLightProbe(LightProbes self, ref Vector3 position, Renderer renderer, float[] coefficients); + private static extern void INTERNAL_CALL_GetInterpolatedProbe(ref Vector3 position, Renderer renderer, out SphericalHarmonicsL2 probe); + [Obsolete("GetInterpolatedLightProbe has been deprecated. Please use the static GetInterpolatedProbe instead.", true)] + public void GetInterpolatedLightProbe(Vector3 position, Renderer renderer, float[] coefficients) + { + } } } diff --git a/UnityEngine/UnityEngine/LightmapData.cs b/UnityEngine/UnityEngine/LightmapData.cs index d8967ccb..24d18911 100644 --- a/UnityEngine/UnityEngine/LightmapData.cs +++ b/UnityEngine/UnityEngine/LightmapData.cs @@ -1,44 +1,44 @@ using System; +using System.ComponentModel; using System.Runtime.InteropServices; namespace UnityEngine { [StructLayout(LayoutKind.Sequential)] public sealed class LightmapData { - internal Texture2D m_Lightmap; - internal Texture2D m_IndirectLightmap; + internal Texture2D m_Light; + internal Texture2D m_Dir; public Texture2D lightmapFar { get { - return this.m_Lightmap; + return this.m_Light; } set { - this.m_Lightmap = value; + this.m_Light = value; } } - [Obsolete("Use lightmapFar instead")] + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property LightmapData.lightmap has been deprecated. Use Lightmap.lightmapFar instead (UnityUpgradable).", true)] public Texture2D lightmap { get { - return this.m_Lightmap; + return null; } set { - this.m_Lightmap = value; } } public Texture2D lightmapNear { get { - return this.m_IndirectLightmap; + return this.m_Dir; } set { - this.m_IndirectLightmap = value; + this.m_Dir = value; } } } diff --git a/UnityEngine/UnityEngine/LightmapSettings.cs b/UnityEngine/UnityEngine/LightmapSettings.cs index fe3efbff..09f3d79e 100644 --- a/UnityEngine/UnityEngine/LightmapSettings.cs +++ b/UnityEngine/UnityEngine/LightmapSettings.cs @@ -13,7 +13,8 @@ public static extern LightmapData[] lightmaps [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern LightmapsMode lightmapsMode + [Obsolete("Use lightmapsMode property")] + public static extern LightmapsModeLegacy lightmapsModeLegacy { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -22,7 +23,7 @@ public static extern LightmapsMode lightmapsMode [MethodImpl(MethodImplOptions.InternalCall)] set; } - public static extern ColorSpace bakedColorSpace + public static extern LightmapsMode lightmapsMode { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -31,6 +32,17 @@ public static extern ColorSpace bakedColorSpace [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("bakedColorSpace is no longer valid. Use QualitySettings.desiredColorSpace.", false)] + public static ColorSpace bakedColorSpace + { + get + { + return QualitySettings.desiredColorSpace; + } + set + { + } + } public static extern LightProbes lightProbes { [WrapperlessIcall] @@ -40,5 +52,8 @@ public static extern LightProbes lightProbes [MethodImpl(MethodImplOptions.InternalCall)] set; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Reset(); } } diff --git a/UnityEngine/UnityEngine/LightmapsMode.cs b/UnityEngine/UnityEngine/LightmapsMode.cs index 482fb43e..05526536 100644 --- a/UnityEngine/UnityEngine/LightmapsMode.cs +++ b/UnityEngine/UnityEngine/LightmapsMode.cs @@ -3,7 +3,10 @@ namespace UnityEngine { public enum LightmapsMode { - Single, + NonDirectional, + CombinedDirectional, + SeparateDirectional, + Single = 0, Dual, Directional } diff --git a/UnityEngine/UnityEngine/LightmapsModeLegacy.cs b/UnityEngine/UnityEngine/LightmapsModeLegacy.cs new file mode 100644 index 00000000..c6e21c14 --- /dev/null +++ b/UnityEngine/UnityEngine/LightmapsModeLegacy.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public enum LightmapsModeLegacy + { + Single, + Dual, + Directional + } +} diff --git a/UnityEngine/UnityEngine/LocalNotification.cs b/UnityEngine/UnityEngine/LocalNotification.cs index eecb48bb..7a3dcb0b 100644 --- a/UnityEngine/UnityEngine/LocalNotification.cs +++ b/UnityEngine/UnityEngine/LocalNotification.cs @@ -1,144 +1,8 @@ using System; -using System.Collections; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("LocalNotification is deprecated (UnityUpgradable). Please use iOS.LocalNotification instead.", true)] public sealed class LocalNotification { - private IntPtr notificationWrapper; - private static long m_NSReferenceDateTicks; - public DateTime fireDate - { - get - { - return new DateTime((long)(this.GetFireDate() * 10000000.0) + LocalNotification.m_NSReferenceDateTicks); - } - set - { - this.SetFireDate((double)(value.ToUniversalTime().Ticks - LocalNotification.m_NSReferenceDateTicks) / 10000000.0); - } - } - public extern string timeZone - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern CalendarUnit repeatInterval - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern CalendarIdentifier repeatCalendar - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string alertBody - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string alertAction - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool hasAction - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string alertLaunchImage - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern int applicationIconBadgeNumber - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern string soundName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public static extern string defaultSoundName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern IDictionary userInfo - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public LocalNotification() - { - this.InitWrapper(); - } - static LocalNotification() - { - // Note: this type is marked as 'beforefieldinit'. - DateTime dateTime = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); - LocalNotification.m_NSReferenceDateTicks = dateTime.Ticks; - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern double GetFireDate(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void SetFireDate(double dt); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Destroy(); - ~LocalNotification() - { - this.Destroy(); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void InitWrapper(); } } diff --git a/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs b/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs index 05dc46d4..dfaf8d23 100644 --- a/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs +++ b/UnityEngine/UnityEngine/MarshallOnlyFirstField.cs @@ -2,7 +2,7 @@ using System.Diagnostics; namespace UnityEngine { - [Conditional("UNITY_FLASH"), Conditional("UNITY_WINRT")] + [Conditional("UNITY_WINRT")] internal class MarshallOnlyFirstField : Attribute { } diff --git a/UnityEngine/UnityEngine/Material.cs b/UnityEngine/UnityEngine/Material.cs index 2fef9a14..b96a8221 100644 --- a/UnityEngine/UnityEngine/Material.cs +++ b/UnityEngine/UnityEngine/Material.cs @@ -82,6 +82,15 @@ public extern string[] shaderKeywords [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern MaterialGlobalIlluminationFlags globalIlluminationFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public Material(string contents) { Material.Internal_CreateWithString(this, contents); @@ -272,5 +281,8 @@ public static Material Create(string scriptContents) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void DisableKeyword(string keyword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsKeywordEnabled(string keyword); } } diff --git a/UnityEngine/UnityEngine/MaterialGlobalIlluminationFlags.cs b/UnityEngine/UnityEngine/MaterialGlobalIlluminationFlags.cs new file mode 100644 index 00000000..c1d3d13f --- /dev/null +++ b/UnityEngine/UnityEngine/MaterialGlobalIlluminationFlags.cs @@ -0,0 +1,12 @@ +using System; +namespace UnityEngine +{ + [Flags] + public enum MaterialGlobalIlluminationFlags + { + None = 0, + RealtimeEmissive = 1, + BakedEmissive = 2, + EmissiveIsBlack = 4 + } +} diff --git a/UnityEngine/UnityEngine/Mathf.cs b/UnityEngine/UnityEngine/Mathf.cs index 609da9f6..42c4b52a 100644 --- a/UnityEngine/UnityEngine/Mathf.cs +++ b/UnityEngine/UnityEngine/Mathf.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.CompilerServices; using UnityEngine.Internal; +using UnityEngineInternal; namespace UnityEngine { public struct Mathf @@ -10,7 +11,7 @@ public struct Mathf public const float NegativeInfinity = float.NegativeInfinity; public const float Deg2Rad = 0.0174532924f; public const float Rad2Deg = 57.29578f; - public const float Epsilon = 1.401298E-45f; + public static readonly float Epsilon = (!MathfInternal.IsFlushToZeroEnabled) ? MathfInternal.FloatMinDenormal : MathfInternal.FloatMinNormal; public static float Sin(float f) { return (float)Math.Sin((double)f); @@ -274,7 +275,7 @@ public static float Gamma(float value, float absmax, float gamma) } public static bool Approximately(float a, float b) { - return Mathf.Abs(b - a) < Mathf.Max(1E-06f * Mathf.Max(Mathf.Abs(a), Mathf.Abs(b)), 1.121039E-44f); + return Mathf.Abs(b - a) < Mathf.Max(1E-06f * Mathf.Max(Mathf.Abs(a), Mathf.Abs(b)), Mathf.Epsilon * 8f); } [ExcludeFromDocs] public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) @@ -440,5 +441,11 @@ internal static bool LineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, result = new Vector2(p1.x + num8 * num, p1.y + num8 * num2); return true; } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern ushort FloatToHalf(float val); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float HalfToFloat(ushort val); } } diff --git a/UnityEngine/UnityEngine/Mesh.cs b/UnityEngine/UnityEngine/Mesh.cs index fc193980..ef3f3366 100644 --- a/UnityEngine/UnityEngine/Mesh.cs +++ b/UnityEngine/UnityEngine/Mesh.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; using UnityEngine.Internal; namespace UnityEngine @@ -53,6 +54,17 @@ public extern Vector2[] uv [MethodImpl(MethodImplOptions.InternalCall)] set; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property Mesh.uv1 has been deprecated. Use Mesh.uv2 instead (UnityUpgradable).", true)] + public Vector2[] uv1 + { + get + { + return null; + } + set + { + } + } public extern Vector2[] uv2 { [WrapperlessIcall] @@ -62,16 +74,23 @@ public extern Vector2[] uv2 [MethodImpl(MethodImplOptions.InternalCall)] set; } - public Vector2[] uv1 + public extern Vector2[] uv3 { - get - { - return this.uv2; - } - set - { - this.uv2 = value; - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Vector2[] uv4 + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } public Bounds bounds { @@ -161,7 +180,7 @@ public Mesh() private static extern void Internal_Create([Writable] Mesh mono); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Clear([DefaultValue("true")] bool keepVertexLayout); + public extern void Clear([UnityEngine.Internal.DefaultValue("true")] bool keepVertexLayout); [ExcludeFromDocs] public void Clear() { @@ -198,15 +217,9 @@ public void Clear() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern MeshTopology GetTopology(int submesh); - [Obsolete("Use SetTriangles instead. Internally this function will convert the triangle strip to a list of triangles anyway."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetTriangleStrip(int[] triangles, int submesh); - [Obsolete("Use GetTriangles instead. Internally this function converts a list of triangles to a strip, so it might be slow, it might be a mess."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern int[] GetTriangleStrip(int submesh); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void CombineMeshes(CombineInstance[] combine, [DefaultValue("true")] bool mergeSubMeshes, [DefaultValue("true")] bool useMatrices); + public extern void CombineMeshes(CombineInstance[] combine, [UnityEngine.Internal.DefaultValue("true")] bool mergeSubMeshes, [UnityEngine.Internal.DefaultValue("true")] bool useMatrices); [ExcludeFromDocs] public void CombineMeshes(CombineInstance[] combine, bool mergeSubMeshes) { diff --git a/UnityEngine/UnityEngine/MeshCollider.cs b/UnityEngine/UnityEngine/MeshCollider.cs index 0c6359cf..f7311848 100644 --- a/UnityEngine/UnityEngine/MeshCollider.cs +++ b/UnityEngine/UnityEngine/MeshCollider.cs @@ -4,18 +4,6 @@ namespace UnityEngine { public sealed class MeshCollider : Collider { - [Obsolete("mesh has been replaced with sharedMesh and will be deprecated")] - public Mesh mesh - { - get - { - return this.sharedMesh; - } - set - { - this.sharedMesh = value; - } - } public extern Mesh sharedMesh { [WrapperlessIcall] @@ -34,14 +22,16 @@ public extern bool convex [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern bool smoothSphereCollisions + [Obsolete("Configuring smooth sphere collisions is no longer needed. PhysX3 has a better behaviour in place.")] + public bool smoothSphereCollisions { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return true; + } + set + { + } } } } diff --git a/UnityEngine/UnityEngine/MeshParticleEmitter.cs b/UnityEngine/UnityEngine/MeshParticleEmitter.cs new file mode 100644 index 00000000..9993f047 --- /dev/null +++ b/UnityEngine/UnityEngine/MeshParticleEmitter.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + public sealed class MeshParticleEmitter : ParticleEmitter + { + internal MeshParticleEmitter() + { + } + } +} diff --git a/UnityEngine/UnityEngine/MeshRenderer.cs b/UnityEngine/UnityEngine/MeshRenderer.cs index a5f537ca..6f10cb6a 100644 --- a/UnityEngine/UnityEngine/MeshRenderer.cs +++ b/UnityEngine/UnityEngine/MeshRenderer.cs @@ -1,7 +1,17 @@ using System; +using System.Runtime.CompilerServices; namespace UnityEngine { public sealed class MeshRenderer : Renderer { + public extern Mesh additionalVertexStreams + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } } } diff --git a/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs b/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs index f7aec954..12dfd902 100644 --- a/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs +++ b/UnityEngine/UnityEngine/MeshSubsetCombineUtility.cs @@ -6,8 +6,11 @@ internal class MeshSubsetCombineUtility public struct MeshInstance { public int meshInstanceID; + public int rendererInstanceID; + public int additionalVertexStreamsMeshInstanceID; public Matrix4x4 transform; - public Vector4 lightmapTilingOffset; + public Vector4 lightmapScaleOffset; + public Vector4 realtimeLightmapScaleOffset; } public struct SubMeshInstance { diff --git a/UnityEngine/UnityEngine/Motion.cs b/UnityEngine/UnityEngine/Motion.cs index ec031e04..f1e983f9 100644 --- a/UnityEngine/UnityEngine/Motion.cs +++ b/UnityEngine/UnityEngine/Motion.cs @@ -34,7 +34,7 @@ public extern bool isLooping [MethodImpl(MethodImplOptions.InternalCall)] get; } - public extern bool isAnimatorMotion + public extern bool legacy { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -46,8 +46,15 @@ public extern bool isHumanMotion [MethodImpl(MethodImplOptions.InternalCall)] get; } - [WrapperlessIcall] + [Obsolete("isAnimatorMotion is not supported anymore. Use !legacy instead.", true)] + public extern bool isAnimatorMotion + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [Obsolete("ValidateIfRetargetable is not supported anymore. Use isHumanMotion instead.", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern bool ValidateIfRetargetable(bool showWarning); + public extern bool ValidateIfRetargetable(bool val); } } diff --git a/UnityEngine/UnityEngine/NavMesh.cs b/UnityEngine/UnityEngine/NavMesh.cs index e78cde1b..c4ab42e8 100644 --- a/UnityEngine/UnityEngine/NavMesh.cs +++ b/UnityEngine/UnityEngine/NavMesh.cs @@ -2,67 +2,111 @@ using System.Runtime.CompilerServices; namespace UnityEngine { - public sealed class NavMesh : Object + public sealed class NavMesh { - public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int passableMask) + public const int AllAreas = -1; + public static float avoidancePredictionTime { - return NavMesh.INTERNAL_CALL_Raycast(ref sourcePosition, ref targetPosition, out hit, passableMask); + get + { + return NavMesh.GetAvoidancePredictionTime(); + } + set + { + NavMesh.SetAvoidancePredictionTime(value); + } + } + public static int pathfindingIterationsPerFrame + { + get + { + return NavMesh.GetPathfindingIterationsPerFrame(); + } + set + { + NavMesh.SetPathfindingIterationsPerFrame(value); + } + } + public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int areaMask) + { + return NavMesh.INTERNAL_CALL_Raycast(ref sourcePosition, ref targetPosition, out hit, areaMask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Raycast(ref Vector3 sourcePosition, ref Vector3 targetPosition, out NavMeshHit hit, int passableMask); - public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int passableMask, NavMeshPath path) + private static extern bool INTERNAL_CALL_Raycast(ref Vector3 sourcePosition, ref Vector3 targetPosition, out NavMeshHit hit, int areaMask); + public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path) { path.ClearCorners(); - return NavMesh.CalculatePathInternal(sourcePosition, targetPosition, passableMask, path); + return NavMesh.CalculatePathInternal(sourcePosition, targetPosition, areaMask, path); } - internal static bool CalculatePathInternal(Vector3 sourcePosition, Vector3 targetPosition, int passableMask, NavMeshPath path) + internal static bool CalculatePathInternal(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path) { - return NavMesh.INTERNAL_CALL_CalculatePathInternal(ref sourcePosition, ref targetPosition, passableMask, path); + return NavMesh.INTERNAL_CALL_CalculatePathInternal(ref sourcePosition, ref targetPosition, areaMask, path); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_CalculatePathInternal(ref Vector3 sourcePosition, ref Vector3 targetPosition, int passableMask, NavMeshPath path); - public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int passableMask) + private static extern bool INTERNAL_CALL_CalculatePathInternal(ref Vector3 sourcePosition, ref Vector3 targetPosition, int areaMask, NavMeshPath path); + public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int areaMask) { - return NavMesh.INTERNAL_CALL_FindClosestEdge(ref sourcePosition, out hit, passableMask); + return NavMesh.INTERNAL_CALL_FindClosestEdge(ref sourcePosition, out hit, areaMask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_FindClosestEdge(ref Vector3 sourcePosition, out NavMeshHit hit, int passableMask); - public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int allowedMask) + private static extern bool INTERNAL_CALL_FindClosestEdge(ref Vector3 sourcePosition, out NavMeshHit hit, int areaMask); + public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask) { - return NavMesh.INTERNAL_CALL_SamplePosition(ref sourcePosition, out hit, maxDistance, allowedMask); + return NavMesh.INTERNAL_CALL_SamplePosition(ref sourcePosition, out hit, maxDistance, areaMask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_SamplePosition(ref Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int allowedMask); - [WrapperlessIcall] + private static extern bool INTERNAL_CALL_SamplePosition(ref Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask); + [Obsolete("Use SetAreaCost instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetLayerCost(int layer, float cost); - [WrapperlessIcall] + [Obsolete("Use GetAreaCost instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern float GetLayerCost(int layer); - [WrapperlessIcall] + [Obsolete("Use GetAreaFromName instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetNavMeshLayerFromName(string layerName); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void SetAreaCost(int areaIndex, float cost); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern float GetAreaCost(int areaIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern int GetAreaFromName(string areaName); public static NavMeshTriangulation CalculateTriangulation() { NavMeshTriangulation result = default(NavMeshTriangulation); - NavMesh.TriangulateInternal(ref result.vertices, ref result.indices, ref result.layers); + NavMesh.TriangulateInternal(ref result.vertices, ref result.indices, ref result.areas); return result; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern void TriangulateInternal(ref Vector3[] vertices, ref int[] indices, ref int[] layers); + internal static extern void TriangulateInternal(ref Vector3[] vertices, ref int[] indices, ref int[] areas); [Obsolete("use NavMesh.CalculateTriangulation() instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Triangulate(out Vector3[] vertices, out int[] indices); - [WrapperlessIcall] + [Obsolete("AddOffMeshLinks has no effect and is deprecated."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void AddOffMeshLinks(); - [WrapperlessIcall] + [Obsolete("RestoreNavMesh has no effect and is deprecated."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RestoreNavMesh(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetAvoidancePredictionTime(float t); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern float GetAvoidancePredictionTime(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetPathfindingIterationsPerFrame(int iter); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetPathfindingIterationsPerFrame(); } } diff --git a/UnityEngine/UnityEngine/NavMeshAgent.cs b/UnityEngine/UnityEngine/NavMeshAgent.cs index 111cd9c8..a86afc2c 100644 --- a/UnityEngine/UnityEngine/NavMeshAgent.cs +++ b/UnityEngine/UnityEngine/NavMeshAgent.cs @@ -1,6 +1,5 @@ using System; using System.Runtime.CompilerServices; -using UnityEngine.Internal; namespace UnityEngine { public sealed class NavMeshAgent : Behaviour @@ -183,6 +182,7 @@ public NavMeshPath path this.SetPath(value); } } + [Obsolete("Use areaMask instead.")] public extern int walkableMask { [WrapperlessIcall] @@ -192,6 +192,15 @@ public extern int walkableMask [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int areaMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern float speed { [WrapperlessIcall] @@ -273,6 +282,12 @@ public extern int avoidancePriority [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern bool isOnNavMesh + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public bool SetDestination(Vector3 target) { return NavMeshAgent.INTERNAL_CALL_SetDestination(this, ref target); @@ -333,14 +348,17 @@ public void Move(Vector3 offset) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_Move(NavMeshAgent self, ref Vector3 offset); + public void Stop() + { + this.StopInternal(); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Stop([DefaultValue("false")] bool stopUpdates); - [ExcludeFromDocs] - public void Stop() + internal extern void StopInternal(); + [Obsolete("Use Stop() instead")] + public void Stop(bool stopUpdates) { - bool stopUpdates = false; - this.Stop(stopUpdates); + this.StopInternal(); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -378,12 +396,18 @@ private bool CalculatePathInternal(Vector3 targetPosition, NavMeshPath path) private static extern bool INTERNAL_CALL_CalculatePathInternal(NavMeshAgent self, ref Vector3 targetPosition, NavMeshPath path); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern bool SamplePathPosition(int passableMask, float maxDistance, out NavMeshHit hit); - [WrapperlessIcall] + public extern bool SamplePathPosition(int areaMask, float maxDistance, out NavMeshHit hit); + [Obsolete("Use SetAreaCost instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetLayerCost(int layer, float cost); - [WrapperlessIcall] + [Obsolete("Use GetAreaCost instead."), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetLayerCost(int layer); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void SetAreaCost(int areaIndex, float areaCost); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern float GetAreaCost(int areaIndex); } } diff --git a/UnityEngine/UnityEngine/NavMeshObstacle.cs b/UnityEngine/UnityEngine/NavMeshObstacle.cs index ce86edc0..4a6c6670 100644 --- a/UnityEngine/UnityEngine/NavMeshObstacle.cs +++ b/UnityEngine/UnityEngine/NavMeshObstacle.cs @@ -44,6 +44,15 @@ public extern bool carving [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern bool carveOnlyStationary + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern float carvingMoveThreshold { [WrapperlessIcall] @@ -53,11 +62,70 @@ public extern float carvingMoveThreshold [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float carvingTimeToStationary + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern NavMeshObstacleShape shape + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public Vector3 size + { + get + { + Vector3 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_velocity(out Vector3 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_set_velocity(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal extern void FitExtents(); } } diff --git a/UnityEngine/UnityEngine/NavMeshObstacleShape.cs b/UnityEngine/UnityEngine/NavMeshObstacleShape.cs new file mode 100644 index 00000000..f158d9ba --- /dev/null +++ b/UnityEngine/UnityEngine/NavMeshObstacleShape.cs @@ -0,0 +1,9 @@ +using System; +namespace UnityEngine +{ + public enum NavMeshObstacleShape + { + Capsule, + Box + } +} diff --git a/UnityEngine/UnityEngine/NavMeshPath.cs b/UnityEngine/UnityEngine/NavMeshPath.cs index fa817180..a88a9d6d 100644 --- a/UnityEngine/UnityEngine/NavMeshPath.cs +++ b/UnityEngine/UnityEngine/NavMeshPath.cs @@ -35,6 +35,9 @@ public extern NavMeshPathStatus status } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern int GetCornersNonAlloc(Vector3[] results); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private extern Vector3[] CalculateCornersInternal(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/NavMeshTriangulation.cs b/UnityEngine/UnityEngine/NavMeshTriangulation.cs index bbc3fee9..c43bb7c1 100644 --- a/UnityEngine/UnityEngine/NavMeshTriangulation.cs +++ b/UnityEngine/UnityEngine/NavMeshTriangulation.cs @@ -5,6 +5,14 @@ public struct NavMeshTriangulation { public Vector3[] vertices; public int[] indices; - public int[] layers; + public int[] areas; + [Obsolete("Use areas instead.")] + public int[] layers + { + get + { + return this.areas; + } + } } } diff --git a/UnityEngine/UnityEngine/Network.cs b/UnityEngine/UnityEngine/Network.cs index dbb8aed4..4a0b1c0a 100644 --- a/UnityEngine/UnityEngine/Network.cs +++ b/UnityEngine/UnityEngine/Network.cs @@ -310,10 +310,10 @@ public static void Destroy(GameObject gameObject) { if (gameObject != null) { - NetworkView networkView = gameObject.networkView; - if (networkView != null) + NetworkView component = gameObject.GetComponent(); + if (component != null) { - Network.Destroy(networkView.viewID); + Network.Destroy(component.viewID); } else { diff --git a/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs b/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs index 5ce74b2c..75afc78e 100644 --- a/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs +++ b/UnityEngine/UnityEngine/NotFlashValidatedAttribute.cs @@ -1,7 +1,7 @@ using System; namespace UnityEngine { - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), NotConverted] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), Obsolete("NotFlashValidatedAttribute was used for the Flash buildtarget, which is not supported anymore starting Unity 5.0", true), NotConverted] public sealed class NotFlashValidatedAttribute : Attribute { } diff --git a/UnityEngine/UnityEngine/NotRenamedAttribute.cs b/UnityEngine/UnityEngine/NotRenamedAttribute.cs index 156c9817..1f763ad0 100644 --- a/UnityEngine/UnityEngine/NotRenamedAttribute.cs +++ b/UnityEngine/UnityEngine/NotRenamedAttribute.cs @@ -1,7 +1,7 @@ using System; namespace UnityEngine { - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), NotConverted] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface), Obsolete("NotRenamedAttribute was used for the Flash buildtarget, which is not supported anymore starting Unity 5.0", true), NotConverted] public sealed class NotRenamedAttribute : Attribute { } diff --git a/UnityEngine/UnityEngine/NotificationServices.cs b/UnityEngine/UnityEngine/NotificationServices.cs index 0401adc8..9fc899a2 100644 --- a/UnityEngine/UnityEngine/NotificationServices.cs +++ b/UnityEngine/UnityEngine/NotificationServices.cs @@ -1,103 +1,12 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("NotificationServices is deprecated (UnityUpgradable). Please use iOS.NotificationServices instead.", true)] public sealed class NotificationServices { - public static extern int localNotificationCount + [Obsolete("RegisterForRemoteNotificationTypes is deprecated (UnityUpgradable). Please use RegisterForNotifications instead.", true)] + public static void RegisterForRemoteNotificationTypes(RemoteNotificationType notificationTypes) { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; } - public static LocalNotification[] localNotifications - { - get - { - int localNotificationCount = NotificationServices.localNotificationCount; - LocalNotification[] array = new LocalNotification[localNotificationCount]; - for (int i = 0; i < localNotificationCount; i++) - { - array[i] = NotificationServices.GetLocalNotification(i); - } - return array; - } - } - public static extern LocalNotification[] scheduledLocalNotifications - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern int remoteNotificationCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static RemoteNotification[] remoteNotifications - { - get - { - int remoteNotificationCount = NotificationServices.remoteNotificationCount; - RemoteNotification[] array = new RemoteNotification[remoteNotificationCount]; - for (int i = 0; i < remoteNotificationCount; i++) - { - array[i] = NotificationServices.GetRemoteNotification(i); - } - return array; - } - } - public static extern RemoteNotificationType enabledRemoteNotificationTypes - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern byte[] deviceToken - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string registrationError - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern LocalNotification GetLocalNotification(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ScheduleLocalNotification(LocalNotification notification); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void PresentLocalNotificationNow(LocalNotification notification); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CancelLocalNotification(LocalNotification notification); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void CancelAllLocalNotifications(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern RemoteNotification GetRemoteNotification(int index); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ClearLocalNotifications(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ClearRemoteNotifications(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void RegisterForLocalNotificationTypes(LocalNotificationType notificationTypes); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void RegisterForRemoteNotificationTypes(RemoteNotificationType notificationTypes); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void UnregisterForRemoteNotifications(); } } diff --git a/UnityEngine/UnityEngine/Object.cs b/UnityEngine/UnityEngine/Object.cs index ead35cbd..6de1653b 100644 --- a/UnityEngine/UnityEngine/Object.cs +++ b/UnityEngine/UnityEngine/Object.cs @@ -8,7 +8,8 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public class Object { - private ReferenceData m_UnityRuntimeReferenceData; + private int m_InstanceID; + private IntPtr m_CachedPtr; private string m_UnityRuntimeErrorString; public extern string name { @@ -28,26 +29,6 @@ public extern HideFlags hideFlags [MethodImpl(MethodImplOptions.InternalCall)] set; } - public override bool Equals(object o) - { - return Object.CompareBaseObjects(this, o as Object); - } - public override int GetHashCode() - { - return this.GetInstanceID(); - } - private static bool CompareBaseObjects(Object lhs, Object rhs) - { - return Object.CompareBaseObjectsInternal(lhs, rhs); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool CompareBaseObjectsInternal([Writable] Object lhs, [Writable] Object rhs); - [NotRenamed] - public int GetInstanceID() - { - return this.m_UnityRuntimeReferenceData.instanceID; - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object Internal_CloneSingle(Object data); @@ -58,25 +39,6 @@ private static Object Internal_InstantiateSingle(Object data, Vector3 pos, Quate [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object INTERNAL_CALL_Internal_InstantiateSingle(Object data, ref Vector3 pos, ref Quaternion rot); - [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] - public static Object Instantiate(Object original, Vector3 position, Quaternion rotation) - { - Object.CheckNullArgument(original, "The prefab you want to instantiate is null."); - return Object.Internal_InstantiateSingle(original, position, rotation); - } - [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] - public static Object Instantiate(Object original) - { - Object.CheckNullArgument(original, "The thing you want to instantiate is null."); - return Object.Internal_CloneSingle(original); - } - private static void CheckNullArgument(object arg, string message) - { - if (arg == null) - { - throw new ArgumentException(message); - } - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Destroy(Object obj, [DefaultValue("0.0F")] float t); @@ -98,24 +60,6 @@ public static void DestroyImmediate(Object obj) [WrapperlessIcall, TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Object[] FindObjectsOfType(Type type); - public static T[] FindObjectsOfType() where T : Object - { - return Resources.ConvertObjects(Object.FindObjectsOfType(typeof(T))); - } - [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] - public static Object FindObjectOfType(Type type) - { - Object[] array = Object.FindObjectsOfType(type); - if (array.Length > 0) - { - return array[0]; - } - return null; - } - public static T FindObjectOfType() where T : Object - { - return (T)((object)Object.FindObjectOfType(typeof(T))); - } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DontDestroyOnLoad(Object target); @@ -142,6 +86,89 @@ public static Object[] FindObjectsOfTypeAll(Type type) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public override extern string ToString(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern bool DoesObjectWithInstanceIDExist(int instanceID); + public override bool Equals(object o) + { + return Object.CompareBaseObjects(this, o as Object); + } + public override int GetHashCode() + { + return this.GetInstanceID(); + } + private static bool CompareBaseObjects(Object lhs, Object rhs) + { + bool flag = lhs == null; + bool flag2 = rhs == null; + if (flag2 && flag) + { + return true; + } + if (flag2) + { + return !Object.IsNativeObjectAlive(lhs); + } + if (flag) + { + return !Object.IsNativeObjectAlive(rhs); + } + return lhs.m_InstanceID == rhs.m_InstanceID; + } + private static bool IsNativeObjectAlive(Object o) + { + return o.GetCachedPtr() != IntPtr.Zero || (!(o is MonoBehaviour) && !(o is ScriptableObject) && Object.DoesObjectWithInstanceIDExist(o.GetInstanceID())); + } + public int GetInstanceID() + { + return this.m_InstanceID; + } + private IntPtr GetCachedPtr() + { + return this.m_CachedPtr; + } + [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] + public static Object Instantiate(Object original, Vector3 position, Quaternion rotation) + { + Object.CheckNullArgument(original, "The thing you want to instantiate is null."); + return Object.Internal_InstantiateSingle(original, position, rotation); + } + [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] + public static Object Instantiate(Object original) + { + Object.CheckNullArgument(original, "The thing you want to instantiate is null."); + return Object.Internal_CloneSingle(original); + } + public static T Instantiate(T original) where T : Object + { + Object.CheckNullArgument(original, "The thing you want to instantiate is null."); + return (T)((object)Object.Internal_CloneSingle(original)); + } + private static void CheckNullArgument(object arg, string message) + { + if (arg == null) + { + throw new ArgumentException(message); + } + } + public static T[] FindObjectsOfType() where T : Object + { + return Resources.ConvertObjects(Object.FindObjectsOfType(typeof(T))); + } + [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] + public static Object FindObjectOfType(Type type) + { + Object[] array = Object.FindObjectsOfType(type); + if (array.Length > 0) + { + return array[0]; + } + return null; + } + public static T FindObjectOfType() where T : Object + { + return (T)((object)Object.FindObjectOfType(typeof(T))); + } public static implicit operator bool(Object exists) { return !Object.CompareBaseObjects(exists, null); diff --git a/UnityEngine/UnityEngine/OffMeshLink.cs b/UnityEngine/UnityEngine/OffMeshLink.cs index 2ee76bd5..3fc4f714 100644 --- a/UnityEngine/UnityEngine/OffMeshLink.cs +++ b/UnityEngine/UnityEngine/OffMeshLink.cs @@ -37,6 +37,7 @@ public extern bool biDirectional [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("Use area instead.")] public extern int navMeshLayer { [WrapperlessIcall] @@ -46,6 +47,15 @@ public extern int navMeshLayer [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int area + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool autoUpdatePositions { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/ParticleCollisionEvent.cs b/UnityEngine/UnityEngine/ParticleCollisionEvent.cs new file mode 100644 index 00000000..c93eda44 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleCollisionEvent.cs @@ -0,0 +1,43 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public struct ParticleCollisionEvent + { + private Vector3 m_Intersection; + private Vector3 m_Normal; + private Vector3 m_Velocity; + private int m_ColliderInstanceID; + public Vector3 intersection + { + get + { + return this.m_Intersection; + } + } + public Vector3 normal + { + get + { + return this.m_Normal; + } + } + public Vector3 velocity + { + get + { + return this.m_Velocity; + } + } + public Collider collider + { + get + { + return ParticleCollisionEvent.InstanceIDToCollider(this.m_ColliderInstanceID); + } + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern Collider InstanceIDToCollider(int instanceID); + } +} diff --git a/UnityEngine/UnityEngine/ParticleEmitter.cs b/UnityEngine/UnityEngine/ParticleEmitter.cs index dfe6ffc1..21c77170 100644 --- a/UnityEngine/UnityEngine/ParticleEmitter.cs +++ b/UnityEngine/UnityEngine/ParticleEmitter.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; namespace UnityEngine { - public sealed class ParticleEmitter : Component + public class ParticleEmitter : Component { public extern bool emit { @@ -175,6 +175,9 @@ public extern bool enabled [MethodImpl(MethodImplOptions.InternalCall)] set; } + internal ParticleEmitter() + { + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_worldVelocity(out Vector3 value); diff --git a/UnityEngine/UnityEngine/ParticlePhysicsExtensions.cs b/UnityEngine/UnityEngine/ParticlePhysicsExtensions.cs new file mode 100644 index 00000000..b35a83a7 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticlePhysicsExtensions.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngine +{ + public static class ParticlePhysicsExtensions + { + public static int GetSafeCollisionEventSize(this ParticleSystem ps) + { + return ParticleSystemExtensionsImpl.GetSafeCollisionEventSize(ps); + } + public static int GetCollisionEvents(this ParticleSystem ps, GameObject go, ParticleCollisionEvent[] collisionEvents) + { + return ParticleSystemExtensionsImpl.GetCollisionEvents(ps, go, collisionEvents); + } + } +} diff --git a/UnityEngine/UnityEngine/ParticleSystem.cs b/UnityEngine/UnityEngine/ParticleSystem.cs index 8b06a3de..8c093ce5 100644 --- a/UnityEngine/UnityEngine/ParticleSystem.cs +++ b/UnityEngine/UnityEngine/ParticleSystem.cs @@ -144,41 +144,6 @@ public uint randomSeed } } } - public struct CollisionEvent - { - private Vector3 m_Intersection; - private Vector3 m_Normal; - private Vector3 m_Velocity; - private int m_ColliderInstanceID; - public Vector3 intersection - { - get - { - return this.m_Intersection; - } - } - public Vector3 normal - { - get - { - return this.m_Normal; - } - } - public Vector3 velocity - { - get - { - return this.m_Velocity; - } - } - public Collider collider - { - get - { - return ParticleSystem.InstanceIDToCollider(this.m_ColliderInstanceID); - } - } - } public extern float startDelay { [WrapperlessIcall] @@ -254,6 +219,7 @@ public extern int particleCount [MethodImpl(MethodImplOptions.InternalCall)] get; } + [Obsolete("Use GetSafeCollisionEventSize() instead (UnityUpgradable)")] public extern int safeCollisionEventSize { [WrapperlessIcall] @@ -365,9 +331,6 @@ public extern uint randomSeed } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Collider InstanceIDToCollider(int instanceID); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] private extern void INTERNAL_get_startColor(out Color value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -380,9 +343,6 @@ public extern uint randomSeed public extern int GetParticles(ParticleSystem.Particle[] particles); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern int GetCollisionEvents(GameObject go, ParticleSystem.CollisionEvent[] collisionEvents); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_Simulate(float t, bool restart); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/ParticleSystemExtensionsImpl.cs b/UnityEngine/UnityEngine/ParticleSystemExtensionsImpl.cs new file mode 100644 index 00000000..7b7067f0 --- /dev/null +++ b/UnityEngine/UnityEngine/ParticleSystemExtensionsImpl.cs @@ -0,0 +1,14 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal sealed class ParticleSystemExtensionsImpl + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetSafeCollisionEventSize(ParticleSystem ps); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetCollisionEvents(ParticleSystem ps, GameObject go, ParticleCollisionEvent[] collisionEvents); + } +} diff --git a/UnityEngine/UnityEngine/Physics.cs b/UnityEngine/UnityEngine/Physics.cs index f602e9e2..a6b4bfa6 100644 --- a/UnityEngine/UnityEngine/Physics.cs +++ b/UnityEngine/UnityEngine/Physics.cs @@ -24,6 +24,7 @@ public static Vector3 gravity Physics.INTERNAL_set_gravity(ref value); } } + [Obsolete("use Physics.defaultContactOffset or Collider.contactOffset instead.", true)] public static extern float minPenetrationForPenalty { [WrapperlessIcall] @@ -33,6 +34,15 @@ public static extern float minPenetrationForPenalty [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern float defaultContactOffset + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern float bounceThreshold { [WrapperlessIcall] @@ -54,6 +64,7 @@ public static float bounceTreshold Physics.bounceThreshold = value; } } + [Obsolete("The sleepVelocity is no longer supported. Use sleepThreshold. Note that sleepThreshold is energy but not velocity.")] public static extern float sleepVelocity { [WrapperlessIcall] @@ -63,6 +74,7 @@ public static extern float sleepVelocity [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("The sleepAngularVelocity is no longer supported. Use sleepThreshold. Note that sleepThreshold is energy but not velocity.")] public static extern float sleepAngularVelocity { [WrapperlessIcall] @@ -72,6 +84,7 @@ public static extern float sleepAngularVelocity [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("use Rigidbody.maxAngularVelocity instead.", true)] public static extern float maxAngularVelocity { [WrapperlessIcall] @@ -90,6 +103,15 @@ public static extern int solverIterationCount [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern float sleepThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [Obsolete("penetrationPenaltyForce has no effect.")] public static extern float penetrationPenaltyForce { @@ -106,132 +128,132 @@ public static extern float penetrationPenaltyForce [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_set_gravity(ref Vector3 value); - private static bool Internal_Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float distance, int layermask) + private static bool Internal_Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layermask) { - return Physics.INTERNAL_CALL_Internal_Raycast(ref origin, ref direction, out hitInfo, distance, layermask); + return Physics.INTERNAL_CALL_Internal_Raycast(ref origin, ref direction, out hitInfo, maxDistance, layermask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Internal_Raycast(ref Vector3 origin, ref Vector3 direction, out RaycastHit hitInfo, float distance, int layermask); - private static bool Internal_CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float distance, int layermask) + private static extern bool INTERNAL_CALL_Internal_Raycast(ref Vector3 origin, ref Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layermask); + private static bool Internal_CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layermask) { - return Physics.INTERNAL_CALL_Internal_CapsuleCast(ref point1, ref point2, radius, ref direction, out hitInfo, distance, layermask); + return Physics.INTERNAL_CALL_Internal_CapsuleCast(ref point1, ref point2, radius, ref direction, out hitInfo, maxDistance, layermask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Internal_CapsuleCast(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, out RaycastHit hitInfo, float distance, int layermask); - private static bool Internal_RaycastTest(Vector3 origin, Vector3 direction, float distance, int layermask) + private static extern bool INTERNAL_CALL_Internal_CapsuleCast(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layermask); + private static bool Internal_RaycastTest(Vector3 origin, Vector3 direction, float maxDistance, int layermask) { - return Physics.INTERNAL_CALL_Internal_RaycastTest(ref origin, ref direction, distance, layermask); + return Physics.INTERNAL_CALL_Internal_RaycastTest(ref origin, ref direction, maxDistance, layermask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Internal_RaycastTest(ref Vector3 origin, ref Vector3 direction, float distance, int layermask); + private static extern bool INTERNAL_CALL_Internal_RaycastTest(ref Vector3 origin, ref Vector3 direction, float maxDistance, int layermask); [ExcludeFromDocs] - public static bool Raycast(Vector3 origin, Vector3 direction, float distance) + public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance) { int layerMask = -5; - return Physics.Raycast(origin, direction, distance, layerMask); + return Physics.Raycast(origin, direction, maxDistance, layerMask); } [ExcludeFromDocs] public static bool Raycast(Vector3 origin, Vector3 direction) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.Raycast(origin, direction, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.Raycast(origin, direction, maxDistance, layerMask); } - public static bool Raycast(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool Raycast(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Internal_RaycastTest(origin, direction, distance, layerMask); + return Physics.Internal_RaycastTest(origin, direction, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float distance) + public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance) { int layerMask = -5; - return Physics.Raycast(origin, direction, out hitInfo, distance, layerMask); + return Physics.Raycast(origin, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.Raycast(origin, direction, out hitInfo, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.Raycast(origin, direction, out hitInfo, maxDistance, layerMask); } - public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Internal_Raycast(origin, direction, out hitInfo, distance, layerMask); + return Physics.Internal_Raycast(origin, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool Raycast(Ray ray, float distance) + public static bool Raycast(Ray ray, float maxDistance) { int layerMask = -5; - return Physics.Raycast(ray, distance, layerMask); + return Physics.Raycast(ray, maxDistance, layerMask); } [ExcludeFromDocs] public static bool Raycast(Ray ray) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.Raycast(ray, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.Raycast(ray, maxDistance, layerMask); } - public static bool Raycast(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool Raycast(Ray ray, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Raycast(ray.origin, ray.direction, distance, layerMask); + return Physics.Raycast(ray.origin, ray.direction, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool Raycast(Ray ray, out RaycastHit hitInfo, float distance) + public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance) { int layerMask = -5; - return Physics.Raycast(ray, out hitInfo, distance, layerMask); + return Physics.Raycast(ray, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] public static bool Raycast(Ray ray, out RaycastHit hitInfo) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.Raycast(ray, out hitInfo, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.Raycast(ray, out hitInfo, maxDistance, layerMask); } - public static bool Raycast(Ray ray, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool Raycast(Ray ray, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Raycast(ray.origin, ray.direction, out hitInfo, distance, layerMask); + return Physics.Raycast(ray.origin, ray.direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] - public static RaycastHit[] RaycastAll(Ray ray, float distance) + public static RaycastHit[] RaycastAll(Ray ray, float maxDistance) { int layerMask = -5; - return Physics.RaycastAll(ray, distance, layerMask); + return Physics.RaycastAll(ray, maxDistance, layerMask); } [ExcludeFromDocs] public static RaycastHit[] RaycastAll(Ray ray) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.RaycastAll(ray, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.RaycastAll(ray, maxDistance, layerMask); } - public static RaycastHit[] RaycastAll(Ray ray, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static RaycastHit[] RaycastAll(Ray ray, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.RaycastAll(ray.origin, ray.direction, distance, layerMask); + return Physics.RaycastAll(ray.origin, ray.direction, maxDistance, layerMask); } - public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layermask) + public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layermask) { - return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, maxDistance, layermask); } [ExcludeFromDocs] - public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float distance) + public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction, float maxDistance) { int layermask = -5; - return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, maxDistance, layermask); } [ExcludeFromDocs] public static RaycastHit[] RaycastAll(Vector3 origin, Vector3 direction) { int layermask = -5; - float distance = float.PositiveInfinity; - return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, distance, layermask); + float maxDistance = float.PositiveInfinity; + return Physics.INTERNAL_CALL_RaycastAll(ref origin, ref direction, maxDistance, layermask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern RaycastHit[] INTERNAL_CALL_RaycastAll(ref Vector3 origin, ref Vector3 direction, float distance, int layermask); + private static extern RaycastHit[] INTERNAL_CALL_RaycastAll(ref Vector3 origin, ref Vector3 direction, float maxDistance, int layermask); [ExcludeFromDocs] public static bool Linecast(Vector3 start, Vector3 end) { @@ -268,145 +290,145 @@ public static Collider[] OverlapSphere(Vector3 position, float radius) [MethodImpl(MethodImplOptions.InternalCall)] private static extern Collider[] INTERNAL_CALL_OverlapSphere(ref Vector3 position, float radius, int layerMask); [ExcludeFromDocs] - public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float distance) + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float maxDistance) { int layerMask = -5; - return Physics.CapsuleCast(point1, point2, radius, direction, distance, layerMask); + return Physics.CapsuleCast(point1, point2, radius, direction, maxDistance, layerMask); } [ExcludeFromDocs] public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.CapsuleCast(point1, point2, radius, direction, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.CapsuleCast(point1, point2, radius, direction, maxDistance, layerMask); } - public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { RaycastHit raycastHit; - return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out raycastHit, distance, layerMask); + return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out raycastHit, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float distance) + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance) { int layerMask = -5; - return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.CapsuleCast(point1, point2, radius, direction, out hitInfo, maxDistance, layerMask); } - public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out hitInfo, distance, layerMask); + return Physics.Internal_CapsuleCast(point1, point2, radius, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float distance) + public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance) { int layerMask = -5; - return Physics.SphereCast(origin, radius, direction, out hitInfo, distance, layerMask); + return Physics.SphereCast(origin, radius, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.SphereCast(origin, radius, direction, out hitInfo, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.SphereCast(origin, radius, direction, out hitInfo, maxDistance, layerMask); } - public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Internal_CapsuleCast(origin, origin, radius, direction, out hitInfo, distance, layerMask); + return Physics.Internal_CapsuleCast(origin, origin, radius, direction, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool SphereCast(Ray ray, float radius, float distance) + public static bool SphereCast(Ray ray, float radius, float maxDistance) { int layerMask = -5; - return Physics.SphereCast(ray, radius, distance, layerMask); + return Physics.SphereCast(ray, radius, maxDistance, layerMask); } [ExcludeFromDocs] public static bool SphereCast(Ray ray, float radius) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.SphereCast(ray, radius, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.SphereCast(ray, radius, maxDistance, layerMask); } - public static bool SphereCast(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool SphereCast(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { RaycastHit raycastHit; - return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out raycastHit, distance, layerMask); + return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out raycastHit, maxDistance, layerMask); } [ExcludeFromDocs] - public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, float distance) + public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, float maxDistance) { int layerMask = -5; - return Physics.SphereCast(ray, radius, out hitInfo, distance, layerMask); + return Physics.SphereCast(ray, radius, out hitInfo, maxDistance, layerMask); } [ExcludeFromDocs] public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.SphereCast(ray, radius, out hitInfo, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.SphereCast(ray, radius, out hitInfo, maxDistance, layerMask); } - public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out hitInfo, distance, layerMask); + return Physics.Internal_CapsuleCast(ray.origin, ray.origin, radius, ray.direction, out hitInfo, maxDistance, layerMask); } - public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layermask) + public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layermask) { - return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, maxDistance, layermask); } [ExcludeFromDocs] - public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float distance) + public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction, float maxDistance) { int layermask = -5; - return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, maxDistance, layermask); } [ExcludeFromDocs] public static RaycastHit[] CapsuleCastAll(Vector3 point1, Vector3 point2, float radius, Vector3 direction) { int layermask = -5; - float distance = float.PositiveInfinity; - return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, distance, layermask); + float maxDistance = float.PositiveInfinity; + return Physics.INTERNAL_CALL_CapsuleCastAll(ref point1, ref point2, radius, ref direction, maxDistance, layermask); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern RaycastHit[] INTERNAL_CALL_CapsuleCastAll(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, float distance, int layermask); + private static extern RaycastHit[] INTERNAL_CALL_CapsuleCastAll(ref Vector3 point1, ref Vector3 point2, float radius, ref Vector3 direction, float maxDistance, int layermask); [ExcludeFromDocs] - public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, float distance) + public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, float maxDistance) { int layerMask = -5; - return Physics.SphereCastAll(origin, radius, direction, distance, layerMask); + return Physics.SphereCastAll(origin, radius, direction, maxDistance, layerMask); } [ExcludeFromDocs] public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.SphereCastAll(origin, radius, direction, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.SphereCastAll(origin, radius, direction, maxDistance, layerMask); } - public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.CapsuleCastAll(origin, origin, radius, direction, distance, layerMask); + return Physics.CapsuleCastAll(origin, origin, radius, direction, maxDistance, layerMask); } [ExcludeFromDocs] - public static RaycastHit[] SphereCastAll(Ray ray, float radius, float distance) + public static RaycastHit[] SphereCastAll(Ray ray, float radius, float maxDistance) { int layerMask = -5; - return Physics.SphereCastAll(ray, radius, distance, layerMask); + return Physics.SphereCastAll(ray, radius, maxDistance, layerMask); } [ExcludeFromDocs] public static RaycastHit[] SphereCastAll(Ray ray, float radius) { int layerMask = -5; - float distance = float.PositiveInfinity; - return Physics.SphereCastAll(ray, radius, distance, layerMask); + float maxDistance = float.PositiveInfinity; + return Physics.SphereCastAll(ray, radius, maxDistance, layerMask); } - public static RaycastHit[] SphereCastAll(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float distance, [DefaultValue("DefaultRaycastLayers")] int layerMask) + public static RaycastHit[] SphereCastAll(Ray ray, float radius, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask) { - return Physics.CapsuleCastAll(ray.origin, ray.origin, radius, ray.direction, distance, layerMask); + return Physics.CapsuleCastAll(ray.origin, ray.origin, radius, ray.direction, maxDistance, layerMask); } public static bool CheckSphere(Vector3 position, float radius, [DefaultValue("DefaultRaycastLayers")] int layerMask) { diff --git a/UnityEngine/UnityEngine/Physics2D.cs b/UnityEngine/UnityEngine/Physics2D.cs index 505a774d..0a04899c 100644 --- a/UnityEngine/UnityEngine/Physics2D.cs +++ b/UnityEngine/UnityEngine/Physics2D.cs @@ -207,6 +207,18 @@ public static void IgnoreLayerCollision(int layer1, int layer2) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool GetIgnoreLayerCollision(int layer1, int layer2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsTouching(Collider2D collider1, Collider2D collider2); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsTouchingLayers(Collider2D collider, [DefaultValue("AllLayers")] int layerMask); + [ExcludeFromDocs] + public static bool IsTouchingLayers(Collider2D collider) + { + int layerMask = -1; + return Physics2D.IsTouchingLayers(collider, layerMask); + } internal static void SetEditorDragMovement(bool dragging, GameObject[] objs) { foreach (Rigidbody2D current in Physics2D.m_LastDisabledRigidbody2D) diff --git a/UnityEngine/UnityEngine/PhysicsUpdateBehaviour2D.cs b/UnityEngine/UnityEngine/PhysicsUpdateBehaviour2D.cs new file mode 100644 index 00000000..a1463c61 --- /dev/null +++ b/UnityEngine/UnityEngine/PhysicsUpdateBehaviour2D.cs @@ -0,0 +1,7 @@ +using System; +namespace UnityEngine +{ + public class PhysicsUpdateBehaviour2D : Behaviour + { + } +} diff --git a/UnityEngine/UnityEngine/SkinnedCloth.cs b/UnityEngine/UnityEngine/PlatformEffector2D.cs similarity index 52% rename from UnityEngine/UnityEngine/SkinnedCloth.cs rename to UnityEngine/UnityEngine/PlatformEffector2D.cs index c83f9df7..3c6226be 100644 --- a/UnityEngine/UnityEngine/SkinnedCloth.cs +++ b/UnityEngine/UnityEngine/PlatformEffector2D.cs @@ -1,11 +1,10 @@ using System; using System.Runtime.CompilerServices; -using UnityEngine.Internal; namespace UnityEngine { - public sealed class SkinnedCloth : Cloth + public sealed class PlatformEffector2D : Effector2D { - public extern ClothSkinningCoefficient[] coefficients + public extern bool oneWay { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -14,7 +13,7 @@ public extern ClothSkinningCoefficient[] coefficients [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float worldVelocityScale + public extern bool sideFriction { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -23,7 +22,7 @@ public extern float worldVelocityScale [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern float worldAccelerationScale + public extern bool sideBounce { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -32,14 +31,14 @@ public extern float worldAccelerationScale [MethodImpl(MethodImplOptions.InternalCall)] set; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetEnabledFading(bool enabled, [DefaultValue("0.5f")] float interpolationTime); - [ExcludeFromDocs] - public void SetEnabledFading(bool enabled) + public extern float sideAngleVariance { - float interpolationTime = 0.5f; - this.SetEnabledFading(enabled, interpolationTime); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } } } diff --git a/UnityEngine/UnityEngine/PointEffector2D.cs b/UnityEngine/UnityEngine/PointEffector2D.cs new file mode 100644 index 00000000..4bb4f0e4 --- /dev/null +++ b/UnityEngine/UnityEngine/PointEffector2D.cs @@ -0,0 +1,80 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class PointEffector2D : Effector2D + { + public extern float forceMagnitude + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float forceVariation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float distanceScale + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float drag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float angularDrag + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern EffectorSelection2D forceSource + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern EffectorSelection2D forceTarget + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern EffectorForceMode2D forceMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/ProceduralOutputType.cs b/UnityEngine/UnityEngine/ProceduralOutputType.cs index 41cdb829..5d192310 100644 --- a/UnityEngine/UnityEngine/ProceduralOutputType.cs +++ b/UnityEngine/UnityEngine/ProceduralOutputType.cs @@ -9,6 +9,11 @@ public enum ProceduralOutputType Height, Emissive, Specular, - Opacity + Opacity, + Smoothness, + AmbientOcclusion, + DetailMask, + Metallic, + Roughness } } diff --git a/UnityEngine/UnityEngine/Projector.cs b/UnityEngine/UnityEngine/Projector.cs index b02f5949..88d16710 100644 --- a/UnityEngine/UnityEngine/Projector.cs +++ b/UnityEngine/UnityEngine/Projector.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; namespace UnityEngine { @@ -40,15 +41,26 @@ public extern float aspectRatio [MethodImpl(MethodImplOptions.InternalCall)] set; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property isOrthoGraphic has been deprecated. Use orthographic instead (UnityUpgradable).", true)] public bool isOrthoGraphic { get { - return this.orthographic; + return false; + } + set + { + } + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property orthoGraphicSize has been deprecated. Use orthographicSize instead (UnityUpgradable).", true)] + public float orthoGraphicSize + { + get + { + return -1f; } set { - this.orthographic = value; } } public extern bool orthographic @@ -69,17 +81,6 @@ public extern float orthographicSize [MethodImpl(MethodImplOptions.InternalCall)] set; } - public float orthoGraphicSize - { - get - { - return this.orthographicSize; - } - set - { - this.orthographicSize = value; - } - } public extern int ignoreLayers { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/QualitySettings.cs b/UnityEngine/UnityEngine/QualitySettings.cs index e24b4f1a..22b23465 100644 --- a/UnityEngine/UnityEngine/QualitySettings.cs +++ b/UnityEngine/UnityEngine/QualitySettings.cs @@ -57,6 +57,28 @@ public static extern float shadowDistance [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern float shadowCascade2Split + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Vector3 shadowCascade4Split + { + get + { + Vector3 result; + QualitySettings.INTERNAL_get_shadowCascade4Split(out result); + return result; + } + set + { + QualitySettings.INTERNAL_set_shadowCascade4Split(ref value); + } + } public static extern int masterTextureLimit { [WrapperlessIcall] @@ -111,6 +133,24 @@ public static extern bool softVegetation [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern bool realtimeReflectionProbes + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern bool billboardsFaceCameraPosition + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern int maxQueuedFrames { [WrapperlessIcall] @@ -189,5 +229,11 @@ public static void DecreaseLevel() bool applyExpensiveChanges = false; QualitySettings.DecreaseLevel(applyExpensiveChanges); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_shadowCascade4Split(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_shadowCascade4Split(ref Vector3 value); } } diff --git a/UnityEngine/UnityEngine/RaycastCollider.cs b/UnityEngine/UnityEngine/RaycastCollider.cs deleted file mode 100644 index 7ea3837e..00000000 --- a/UnityEngine/UnityEngine/RaycastCollider.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -namespace UnityEngine -{ - [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable")] - public sealed class RaycastCollider : Collider - { - public Vector3 center - { - get - { - Vector3 result; - this.INTERNAL_get_center(out result); - return result; - } - set - { - this.INTERNAL_set_center(ref value); - } - } - [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable")] - public extern float length - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - [Obsolete("Use WheelCollider or BoxCollider instead, RaycastCollider is unreliable"), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_center(out Vector3 value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_center(ref Vector3 value); - } -} diff --git a/UnityEngine/UnityEngine/RaycastHit.cs b/UnityEngine/UnityEngine/RaycastHit.cs index bdde329c..34f3620e 100644 --- a/UnityEngine/UnityEngine/RaycastHit.cs +++ b/UnityEngine/UnityEngine/RaycastHit.cs @@ -95,11 +95,11 @@ public Vector2 lightmapCoord { Vector2 result; RaycastHit.CalculateRaycastTexCoord(out result, this.collider, this.m_UV, this.m_Point, this.m_FaceID, 1); - if (this.collider.renderer != null) + if (this.collider.GetComponent() != null) { - Vector4 lightmapTilingOffset = this.collider.renderer.lightmapTilingOffset; - result.x = result.x * lightmapTilingOffset.x + lightmapTilingOffset.z; - result.y = result.y * lightmapTilingOffset.y + lightmapTilingOffset.w; + Vector4 lightmapScaleOffset = this.collider.GetComponent().lightmapScaleOffset; + result.x = result.x * lightmapScaleOffset.x + lightmapScaleOffset.z; + result.y = result.y * lightmapScaleOffset.y + lightmapScaleOffset.w; } return result; } diff --git a/UnityEngine/UnityEngine/RectOffset.cs b/UnityEngine/UnityEngine/RectOffset.cs index 5e67bc7c..59889b32 100644 --- a/UnityEngine/UnityEngine/RectOffset.cs +++ b/UnityEngine/UnityEngine/RectOffset.cs @@ -7,7 +7,6 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public sealed class RectOffset { - [NotRenamed] [NonSerialized] internal IntPtr m_Ptr; private GUIStyle m_SourceStyle; diff --git a/UnityEngine/UnityEngine/ReferenceData.cs b/UnityEngine/UnityEngine/ReferenceData.cs deleted file mode 100644 index 628ec6a4..00000000 --- a/UnityEngine/UnityEngine/ReferenceData.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; -namespace UnityEngine -{ - internal struct ReferenceData - { - public int instanceID; - public IntPtr cachedPtr; - } -} diff --git a/UnityEngine/UnityEngine/ReflectionProbe.cs b/UnityEngine/UnityEngine/ReflectionProbe.cs new file mode 100644 index 00000000..b240759c --- /dev/null +++ b/UnityEngine/UnityEngine/ReflectionProbe.cs @@ -0,0 +1,244 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Internal; +using UnityEngine.Rendering; +namespace UnityEngine +{ + public sealed class ReflectionProbe : Behaviour + { + public extern ReflectionProbeType type + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool hdr + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Vector3 size + { + get + { + Vector3 result; + this.INTERNAL_get_size(out result); + return result; + } + set + { + this.INTERNAL_set_size(ref value); + } + } + public Vector3 center + { + get + { + Vector3 result; + this.INTERNAL_get_center(out result); + return result; + } + set + { + this.INTERNAL_set_center(ref value); + } + } + public extern float nearClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float farClipPlane + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float shadowDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int resolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int cullingMask + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ReflectionProbeClearFlags clearFlags + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Color backgroundColor + { + get + { + Color result; + this.INTERNAL_get_backgroundColor(out result); + return result; + } + set + { + this.INTERNAL_set_backgroundColor(ref value); + } + } + public extern float intensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern bool boxProjection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public Bounds bounds + { + get + { + Bounds result; + this.INTERNAL_get_bounds(out result); + return result; + } + } + public extern ReflectionProbeMode mode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern int importance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ReflectionProbeRefreshMode refreshMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ReflectionProbeTimeSlicingMode timeSlicingMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Texture bakedTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Texture customBakedTexture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern Texture texture + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_size(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_size(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_center(out Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_center(ref Vector3 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_backgroundColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_backgroundColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_bounds(out Bounds value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern int RenderProbe([DefaultValue("null")] RenderTexture targetTexture); + [ExcludeFromDocs] + public int RenderProbe() + { + RenderTexture targetTexture = null; + return this.RenderProbe(targetTexture); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern bool IsFinishedRendering(int renderId); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool BlendCubemap(Texture src, Texture dst, float blend, RenderTexture target); + } +} diff --git a/UnityEngine/UnityEngine/RemoteNotification.cs b/UnityEngine/UnityEngine/RemoteNotification.cs index 89f00729..65be772c 100644 --- a/UnityEngine/UnityEngine/RemoteNotification.cs +++ b/UnityEngine/UnityEngine/RemoteNotification.cs @@ -1,50 +1,8 @@ using System; -using System.Collections; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("RemoteNotification is deprecated (UnityUpgradable). Please use iOS.RemoteNotification instead.", true)] public sealed class RemoteNotification { - private IntPtr notificationWrapper; - public extern string alertBody - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern bool hasAction - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern int applicationIconBadgeNumber - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern string soundName - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public extern IDictionary userInfo - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - private RemoteNotification() - { - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Destroy(); - ~RemoteNotification() - { - this.Destroy(); - } } } diff --git a/UnityEngine/UnityEngine/RemoteNotificationType.cs b/UnityEngine/UnityEngine/RemoteNotificationType.cs index f31b126c..b3d38433 100644 --- a/UnityEngine/UnityEngine/RemoteNotificationType.cs +++ b/UnityEngine/UnityEngine/RemoteNotificationType.cs @@ -1,6 +1,7 @@ using System; namespace UnityEngine { + [Obsolete("RemoteNotificationType is deprecated (UnityUpgradable). Please use iOS.NotificationType instead.", true)] public enum RemoteNotificationType { None, diff --git a/UnityEngine/UnityEngine/RenderBuffer.cs b/UnityEngine/UnityEngine/RenderBuffer.cs index a3bfb9a0..4163d73e 100644 --- a/UnityEngine/UnityEngine/RenderBuffer.cs +++ b/UnityEngine/UnityEngine/RenderBuffer.cs @@ -1,9 +1,40 @@ using System; +using UnityEngine.Rendering; namespace UnityEngine { public struct RenderBuffer { internal int m_RenderTextureInstanceID; internal IntPtr m_BufferPtr; + internal RenderBufferLoadAction loadAction + { + get + { + return (RenderBufferLoadAction)RenderBufferHelper.GetLoadAction(out this); + } + set + { + this.SetLoadAction(value); + } + } + internal RenderBufferStoreAction storeAction + { + get + { + return (RenderBufferStoreAction)RenderBufferHelper.GetStoreAction(out this); + } + set + { + this.SetStoreAction(value); + } + } + internal void SetLoadAction(RenderBufferLoadAction action) + { + RenderBufferHelper.SetLoadAction(out this, (int)action); + } + internal void SetStoreAction(RenderBufferStoreAction action) + { + RenderBufferHelper.SetStoreAction(out this, (int)action); + } } } diff --git a/UnityEngine/UnityEngine/RenderBufferHelper.cs b/UnityEngine/UnityEngine/RenderBufferHelper.cs new file mode 100644 index 00000000..0d9ef46e --- /dev/null +++ b/UnityEngine/UnityEngine/RenderBufferHelper.cs @@ -0,0 +1,20 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + internal struct RenderBufferHelper + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetLoadAction(out RenderBuffer b); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetLoadAction(out RenderBuffer b, int a); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern int GetStoreAction(out RenderBuffer b); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void SetStoreAction(out RenderBuffer b, int a); + } +} diff --git a/UnityEngine/UnityEngine/RenderSettings.cs b/UnityEngine/UnityEngine/RenderSettings.cs index ff905d8b..2d03fcb0 100644 --- a/UnityEngine/UnityEngine/RenderSettings.cs +++ b/UnityEngine/UnityEngine/RenderSettings.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using UnityEngine.Rendering; namespace UnityEngine { public sealed class RenderSettings : Object @@ -62,6 +63,54 @@ public static extern float fogEndDistance [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern AmbientMode ambientMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static Color ambientSkyColor + { + get + { + Color result; + RenderSettings.INTERNAL_get_ambientSkyColor(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_ambientSkyColor(ref value); + } + } + public static Color ambientEquatorColor + { + get + { + Color result; + RenderSettings.INTERNAL_get_ambientEquatorColor(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_ambientEquatorColor(ref value); + } + } + public static Color ambientGroundColor + { + get + { + Color result; + RenderSettings.INTERNAL_get_ambientGroundColor(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_ambientGroundColor(ref value); + } + } public static Color ambientLight { get @@ -75,6 +124,56 @@ public static Color ambientLight RenderSettings.INTERNAL_set_ambientLight(ref value); } } + [Obsolete("Use RenderSettings.ambientIntensity instead (UnityUpgradable) -> ambientIntensity")] + public static extern float ambientSkyboxAmount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern float ambientIntensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static SphericalHarmonicsL2 ambientProbe + { + get + { + SphericalHarmonicsL2 result; + RenderSettings.INTERNAL_get_ambientProbe(out result); + return result; + } + set + { + RenderSettings.INTERNAL_set_ambientProbe(ref value); + } + } + public static extern float reflectionIntensity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int reflectionBounces + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public static extern float haloStrength { [WrapperlessIcall] @@ -111,6 +210,33 @@ public static extern Material skybox [MethodImpl(MethodImplOptions.InternalCall)] set; } + public static extern DefaultReflectionMode defaultReflectionMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern int defaultReflectionResolution + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public static extern Cubemap customReflection + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_get_fogColor(out Color value); @@ -119,9 +245,39 @@ public static extern Material skybox private static extern void INTERNAL_set_fogColor(ref Color value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_ambientSkyColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_ambientSkyColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_ambientEquatorColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_ambientEquatorColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_ambientGroundColor(out Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_ambientGroundColor(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_get_ambientLight(out Color value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_set_ambientLight(ref Color value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_get_ambientProbe(out SphericalHarmonicsL2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_set_ambientProbe(ref SphericalHarmonicsL2 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern void Reset(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + internal static extern Object GetRenderSettings(); } } diff --git a/UnityEngine/UnityEngine/RenderTargetSetup.cs b/UnityEngine/UnityEngine/RenderTargetSetup.cs new file mode 100644 index 00000000..7937b980 --- /dev/null +++ b/UnityEngine/UnityEngine/RenderTargetSetup.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine.Rendering; +namespace UnityEngine +{ + internal struct RenderTargetSetup + { + public RenderBuffer[] color; + public RenderBuffer depth; + public int mipLevel; + public int cubemapFace; + public RenderBufferLoadAction[] colorLoad; + public RenderBufferStoreAction[] colorStore; + public RenderBufferLoadAction depthLoad; + public RenderBufferStoreAction depthStore; + internal RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mip, int face, RenderBufferLoadAction[] colorLoad, RenderBufferStoreAction[] colorStore, RenderBufferLoadAction depthLoad, RenderBufferStoreAction depthStore) + { + this.color = color; + this.depth = depth; + this.mipLevel = mip; + this.cubemapFace = face; + this.colorLoad = colorLoad; + this.colorStore = colorStore; + this.depthLoad = depthLoad; + this.depthStore = depthStore; + } + internal RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mip, int face) + { + this = new RenderTargetSetup(color, depth, mip, face, RenderTargetSetup.LoadActions(color), RenderTargetSetup.StoreActions(color), depth.loadAction, depth.storeAction); + } + public RenderTargetSetup(RenderBuffer color, RenderBuffer depth) + { + this = new RenderTargetSetup(new RenderBuffer[] + { + color + }, depth); + } + public RenderTargetSetup(RenderBuffer color, RenderBuffer depth, int mipLevel) + { + this = new RenderTargetSetup(new RenderBuffer[] + { + color + }, depth, mipLevel); + } + public RenderTargetSetup(RenderBuffer color, RenderBuffer depth, int mipLevel, CubemapFace face) + { + this = new RenderTargetSetup(new RenderBuffer[] + { + color + }, depth, mipLevel, face); + } + public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth) + { + this = new RenderTargetSetup(color, depth, 0, -1); + } + public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mipLevel) + { + this = new RenderTargetSetup(color, depth, mipLevel, -1); + } + public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mipLevel, CubemapFace face) + { + this = new RenderTargetSetup(color, depth, mipLevel, (int)face); + } + internal static RenderBufferLoadAction[] LoadActions(RenderBuffer[] buf) + { + RenderBufferLoadAction[] array = new RenderBufferLoadAction[buf.Length]; + for (int i = 0; i < buf.Length; i++) + { + array[i] = buf[i].loadAction; + buf[i].loadAction = RenderBufferLoadAction.Load; + } + return array; + } + internal static RenderBufferStoreAction[] StoreActions(RenderBuffer[] buf) + { + RenderBufferStoreAction[] array = new RenderBufferStoreAction[buf.Length]; + for (int i = 0; i < buf.Length; i++) + { + array[i] = buf[i].storeAction; + buf[i].storeAction = RenderBufferStoreAction.Store; + } + return array; + } + } +} diff --git a/UnityEngine/UnityEngine/RenderTexture.cs b/UnityEngine/UnityEngine/RenderTexture.cs index 0d3c6f38..f1796850 100644 --- a/UnityEngine/UnityEngine/RenderTexture.cs +++ b/UnityEngine/UnityEngine/RenderTexture.cs @@ -305,7 +305,7 @@ public Vector2 GetTexelOffset() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool SupportsStencil(RenderTexture rt); - [Obsolete("RenderTexture.SetBorderColor was removed", true)] + [Obsolete("SetBorderColor is no longer supported.", true)] public void SetBorderColor(Color color) { } diff --git a/UnityEngine/UnityEngine/RenderTextureFormat.cs b/UnityEngine/UnityEngine/RenderTextureFormat.cs index 8a952446..0d26944f 100644 --- a/UnityEngine/UnityEngine/RenderTextureFormat.cs +++ b/UnityEngine/UnityEngine/RenderTextureFormat.cs @@ -6,11 +6,13 @@ public enum RenderTextureFormat ARGB32, Depth, ARGBHalf, - RGB565 = 4, + Shadowmap, + RGB565, ARGB4444, ARGB1555, Default, - DefaultHDR = 9, + ARGB2101010, + DefaultHDR, ARGBFloat = 11, RGFloat, RGHalf, diff --git a/UnityEngine/UnityEngine/Renderer.cs b/UnityEngine/UnityEngine/Renderer.cs index 5a6f4be4..837d74da 100644 --- a/UnityEngine/UnityEngine/Renderer.cs +++ b/UnityEngine/UnityEngine/Renderer.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Generic; +using System.ComponentModel; using System.Runtime.CompilerServices; +using UnityEngine.Rendering; namespace UnityEngine { public class Renderer : Component @@ -52,6 +55,16 @@ public extern bool enabled [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern ShadowCastingMode shadowCastingMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property castShadows has been deprecated. Use shadowCastingMode instead.")] public extern bool castShadows { [WrapperlessIcall] @@ -88,7 +101,7 @@ public extern Material sharedMaterial [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern Material[] sharedMaterials + public extern Material[] materials { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -97,7 +110,7 @@ public extern Material[] sharedMaterials [MethodImpl(MethodImplOptions.InternalCall)] set; } - public extern Material[] materials + public extern Material[] sharedMaterials { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -121,17 +134,47 @@ public extern int lightmapIndex [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int realtimeLightmapIndex + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property lightmapTilingOffset has been deprecated. Use lightmapScaleOffset (UnityUpgradable).", true)] public Vector4 lightmapTilingOffset + { + get + { + return Vector4.zero; + } + set + { + } + } + public Vector4 lightmapScaleOffset { get { Vector4 result; - this.INTERNAL_get_lightmapTilingOffset(out result); + this.INTERNAL_get_lightmapScaleOffset(out result); return result; } set { - this.INTERNAL_set_lightmapTilingOffset(ref value); + this.INTERNAL_set_lightmapScaleOffset(ref value); + } + } + public Vector4 realtimeLightmapScaleOffset + { + get + { + Vector4 result; + this.INTERNAL_get_realtimeLightmapScaleOffset(out result); + return result; + } + set + { + this.INTERNAL_set_realtimeLightmapScaleOffset(ref value); } } public extern bool isVisible @@ -149,6 +192,7 @@ public extern bool useLightProbes [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("Use probeAnchor instead (UnityUpgradable).", true)] public extern Transform lightProbeAnchor { [WrapperlessIcall] @@ -158,6 +202,24 @@ public extern Transform lightProbeAnchor [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern Transform probeAnchor + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern ReflectionProbeUsage reflectionProbeUsage + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern string sortingLayerName { [WrapperlessIcall] @@ -196,10 +258,16 @@ public extern int sortingOrder private extern void INTERNAL_get_localToWorldMatrix(out Matrix4x4 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_get_lightmapTilingOffset(out Vector4 value); + private extern void INTERNAL_get_lightmapScaleOffset(out Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_set_lightmapScaleOffset(ref Vector4 value); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void INTERNAL_get_realtimeLightmapScaleOffset(out Vector4 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void INTERNAL_set_lightmapTilingOffset(ref Vector4 value); + private extern void INTERNAL_set_realtimeLightmapScaleOffset(ref Vector4 value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetPropertyBlock(MaterialPropertyBlock properties); @@ -208,6 +276,13 @@ public extern int sortingOrder public extern void GetPropertyBlock(MaterialPropertyBlock dest); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void Render(int material); + internal extern void RenderNow(int material); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetClosestReflectionProbesInternal(object result); + public void GetClosestReflectionProbes(List result) + { + this.GetClosestReflectionProbesInternal(result); + } } } diff --git a/UnityEngine/UnityEngine/RenderingPath.cs b/UnityEngine/UnityEngine/RenderingPath.cs index 1977b08e..d3febccd 100644 --- a/UnityEngine/UnityEngine/RenderingPath.cs +++ b/UnityEngine/UnityEngine/RenderingPath.cs @@ -6,6 +6,7 @@ public enum RenderingPath UsePlayerSettings = -1, VertexLit, Forward, - DeferredLighting + DeferredLighting, + DeferredShading } } diff --git a/UnityEngine/UnityEngine/Rigidbody.cs b/UnityEngine/UnityEngine/Rigidbody.cs index 12d518a5..cd106e8a 100644 --- a/UnityEngine/UnityEngine/Rigidbody.cs +++ b/UnityEngine/UnityEngine/Rigidbody.cs @@ -67,6 +67,15 @@ public extern bool useGravity [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float maxDepenetrationVelocity + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern bool isKinematic { [WrapperlessIcall] @@ -213,6 +222,7 @@ public extern int solverIterationCount [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("The sleepVelocity is no longer supported. Use sleepThreshold. Note that sleepThreshold is energy but not velocity.")] public extern float sleepVelocity { [WrapperlessIcall] @@ -222,6 +232,7 @@ public extern float sleepVelocity [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("The sleepAngularVelocity is no longer supported. Set Use sleepThreshold to specify energy.")] public extern float sleepAngularVelocity { [WrapperlessIcall] @@ -231,6 +242,15 @@ public extern float sleepAngularVelocity [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float sleepThreshold + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern float maxAngularVelocity { [WrapperlessIcall] @@ -473,32 +493,32 @@ public void WakeUp() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_WakeUp(Rigidbody self); - public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float distance) + public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance) { - return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, distance); + return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, maxDistance); } [ExcludeFromDocs] public bool SweepTest(Vector3 direction, out RaycastHit hitInfo) { - float distance = float.PositiveInfinity; - return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, distance); + float maxDistance = float.PositiveInfinity; + return Rigidbody.INTERNAL_CALL_SweepTest(this, ref direction, out hitInfo, maxDistance); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_SweepTest(Rigidbody self, ref Vector3 direction, out RaycastHit hitInfo, float distance); - public RaycastHit[] SweepTestAll(Vector3 direction, [DefaultValue("Mathf.Infinity")] float distance) + private static extern bool INTERNAL_CALL_SweepTest(Rigidbody self, ref Vector3 direction, out RaycastHit hitInfo, float maxDistance); + public RaycastHit[] SweepTestAll(Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance) { - return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, distance); + return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, maxDistance); } [ExcludeFromDocs] public RaycastHit[] SweepTestAll(Vector3 direction) { - float distance = float.PositiveInfinity; - return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, distance); + float maxDistance = float.PositiveInfinity; + return Rigidbody.INTERNAL_CALL_SweepTestAll(this, ref direction, maxDistance); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern RaycastHit[] INTERNAL_CALL_SweepTestAll(Rigidbody self, ref Vector3 direction, float distance); + private static extern RaycastHit[] INTERNAL_CALL_SweepTestAll(Rigidbody self, ref Vector3 direction, float maxDistance); [Obsolete("use Rigidbody.maxAngularVelocity instead.")] public void SetMaxAngularVelocity(float a) { diff --git a/UnityEngine/UnityEngine/RuntimeAnimatorController.cs b/UnityEngine/UnityEngine/RuntimeAnimatorController.cs index 6a612fa6..94dd7941 100644 --- a/UnityEngine/UnityEngine/RuntimeAnimatorController.cs +++ b/UnityEngine/UnityEngine/RuntimeAnimatorController.cs @@ -1,7 +1,14 @@ using System; +using System.Runtime.CompilerServices; namespace UnityEngine { public class RuntimeAnimatorController : Object { + public extern AnimationClip[] animationClips + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } } } diff --git a/UnityEngine/UnityEngine/RuntimeInitializeOnLoadMethodAttribute.cs b/UnityEngine/UnityEngine/RuntimeInitializeOnLoadMethodAttribute.cs new file mode 100644 index 00000000..37d2b0d9 --- /dev/null +++ b/UnityEngine/UnityEngine/RuntimeInitializeOnLoadMethodAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] + public class RuntimeInitializeOnLoadMethodAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/RuntimePlatform.cs b/UnityEngine/UnityEngine/RuntimePlatform.cs index 5507d05a..6035f011 100644 --- a/UnityEngine/UnityEngine/RuntimePlatform.cs +++ b/UnityEngine/UnityEngine/RuntimePlatform.cs @@ -15,18 +15,22 @@ public enum RuntimePlatform PS3 = 9, Android = 11, NaCl, - LinuxPlayer, FlashPlayer = 15, - MetroPlayerX86 = 18, + LinuxPlayer = 13, + WebGLPlayer = 17, + MetroPlayerX86, + WSAPlayerX86 = 18, MetroPlayerX64, + WSAPlayerX64 = 19, MetroPlayerARM, + WSAPlayerARM = 20, WP8Player, BB10Player, BlackBerryPlayer = 22, TizenPlayer, PSP2, PS4, - PSMPlayer, + PSM, XboxOne, SamsungTVPlayer } diff --git a/UnityEngine/UnityEngine/Screen.cs b/UnityEngine/UnityEngine/Screen.cs index 73338800..f16bd09d 100644 --- a/UnityEngine/UnityEngine/Screen.cs +++ b/UnityEngine/UnityEngine/Screen.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Runtime.CompilerServices; using UnityEngine.Internal; namespace UnityEngine @@ -11,36 +12,46 @@ public static extern Resolution[] resolutions [MethodImpl(MethodImplOptions.InternalCall)] get; } + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property GetResolution has been deprecated. Use resolutions instead (UnityUpgradable).", true)] public static Resolution[] GetResolution { get { - return Screen.resolutions; + return null; } } - public static extern Resolution currentResolution + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property showCursor has been deprecated. Use Cursor.visible instead (UnityUpgradable).", true)] + public static bool showCursor { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] get; + set; } - public static extern bool showCursor + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property lockCursor has been deprecated. Use Cursor.lockState and Cursor.visible instead.")] + public static bool lockCursor { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return CursorLockMode.None == Cursor.lockState; + } + set + { + if (value) + { + Cursor.visible = false; + Cursor.lockState = CursorLockMode.Locked; + } + else + { + Cursor.lockState = CursorLockMode.None; + Cursor.visible = true; + } + } } - public static extern bool lockCursor + public static extern Resolution currentResolution { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; } public static extern int width { @@ -125,7 +136,7 @@ public static extern int sleepTimeout } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetResolution(int width, int height, bool fullscreen, [DefaultValue("0")] int preferredRefreshRate); + public static extern void SetResolution(int width, int height, bool fullscreen, [UnityEngine.Internal.DefaultValue("0")] int preferredRefreshRate); [ExcludeFromDocs] public static void SetResolution(int width, int height, bool fullscreen) { diff --git a/UnityEngine/UnityEngine/Security.cs b/UnityEngine/UnityEngine/Security.cs index 261fc4cb..06cd7f53 100644 --- a/UnityEngine/UnityEngine/Security.cs +++ b/UnityEngine/UnityEngine/Security.cs @@ -14,6 +14,37 @@ public sealed class Security private const string publicVerificationKey = "uP7lsvrE6fNoQWhUIdJnQrgKoGXBkgWgs5l1xmS9gfyNkFSXgugIpfmN/0YrtL57PezYFXN0CogAnOpOtcUmpcIrh524VL/7bIh+jDUaOCG292PIx92dtzqCTvbUdCYUmaag9VlrdAw05FxYQJi2iZ/X6EiuO1TnqpVNFCDb6pXPAssoO4Uxn9JXBzL0muNRdcmFGRiLp7JQOL7a2aeU9mF9qjMprnww0k8COa6tHdnNWJqaxdFO+Etk3os0ns/gQ2FWrztKemM1Wfu7lk/B1F+V2g0adwlTiuyNHw6to+5VQXWK775RXB9wAGr8KhsVD5IJvmxrdBT8KVEWve+OXQ==AQAB"; private static List _verifiedAssemblies = new List(); private static readonly string kSignatureExtension = ".signature"; + [ExcludeFromDocs] + public static bool PrefetchSocketPolicy(string ip, int atPort) + { + int timeout = 3000; + return Security.PrefetchSocketPolicy(ip, atPort, timeout); + } + public static bool PrefetchSocketPolicy(string ip, int atPort, [DefaultValue("3000")] int timeout) + { + MethodInfo unityCrossDomainHelperMethod = Security.GetUnityCrossDomainHelperMethod("PrefetchSocketPolicy"); + object obj = unityCrossDomainHelperMethod.Invoke(null, new object[] + { + ip, + atPort, + timeout + }); + return (bool)obj; + } + [SecuritySafeCritical] + public static string GetChainOfTrustValue(string name) + { + Assembly callingAssembly = Assembly.GetCallingAssembly(); + if (!Security._verifiedAssemblies.Contains(callingAssembly)) + { + throw new ArgumentException("Calling assembly needs to be verified by Security.LoadAndVerifyAssembly"); + } + byte[] publicKeyToken = callingAssembly.GetName().GetPublicKeyToken(); + return Security.GetChainOfTrustValueInternal(name, Security.TokenToHex(publicKeyToken)); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern string GetChainOfTrustValueInternal(string name, string publicKeyToken); private static MethodInfo GetUnityCrossDomainHelperMethod(string methodname) { Type type = Types.GetType("UnityEngine.UnityCrossDomainHelper", "CrossDomainPolicyParser, Version=1.0.0.0, Culture=neutral"); @@ -137,36 +168,5 @@ internal static bool VerifySignature(string file, byte[] publicKey) } return false; } - [ExcludeFromDocs] - public static bool PrefetchSocketPolicy(string ip, int atPort) - { - int timeout = 3000; - return Security.PrefetchSocketPolicy(ip, atPort, timeout); - } - public static bool PrefetchSocketPolicy(string ip, int atPort, [DefaultValue("3000")] int timeout) - { - MethodInfo unityCrossDomainHelperMethod = Security.GetUnityCrossDomainHelperMethod("PrefetchSocketPolicy"); - object obj = unityCrossDomainHelperMethod.Invoke(null, new object[] - { - ip, - atPort, - timeout - }); - return (bool)obj; - } - [SecuritySafeCritical] - public static string GetChainOfTrustValue(string name) - { - Assembly callingAssembly = Assembly.GetCallingAssembly(); - if (!Security._verifiedAssemblies.Contains(callingAssembly)) - { - throw new ArgumentException("Calling assembly needs to be verified by Security.LoadAndVerifyAssembly"); - } - byte[] publicKeyToken = callingAssembly.GetName().GetPublicKeyToken(); - return Security.GetChainOfTrustValueInternal(name, Security.TokenToHex(publicKeyToken)); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern string GetChainOfTrustValueInternal(string name, string publicKeyToken); } } diff --git a/UnityEngine/UnityEngine/SendMouseEvents.cs b/UnityEngine/UnityEngine/SendMouseEvents.cs index ae934521..1ee0fdc9 100644 --- a/UnityEngine/UnityEngine/SendMouseEvents.cs +++ b/UnityEngine/UnityEngine/SendMouseEvents.cs @@ -41,12 +41,7 @@ public static implicit operator bool(SendMouseEvents.HitInfo exists) default(SendMouseEvents.HitInfo), default(SendMouseEvents.HitInfo) }; - private static readonly RaycastHit2D[] m_MouseRayHits2D = new RaycastHit2D[] - { - default(RaycastHit2D) - }; private static Camera[] m_Cameras; - [NotRenamed] private static void DoSendMouseEvents(int mouseUsed, int skipRTCameras) { Vector3 mousePosition = Input.mousePosition; @@ -55,16 +50,17 @@ private static void DoSendMouseEvents(int mouseUsed, int skipRTCameras) { SendMouseEvents.m_Cameras = new Camera[allCamerasCount]; } - int allCameras = Camera.GetAllCameras(SendMouseEvents.m_Cameras); + Camera.GetAllCameras(SendMouseEvents.m_Cameras); for (int i = 0; i < SendMouseEvents.m_CurrentHit.Length; i++) { SendMouseEvents.m_CurrentHit[i] = default(SendMouseEvents.HitInfo); } if (mouseUsed == 0) { - for (int j = 0; j < allCameras; j++) + Camera[] cameras = SendMouseEvents.m_Cameras; + for (int j = 0; j < cameras.Length; j++) { - Camera camera = SendMouseEvents.m_Cameras[j]; + Camera camera = cameras[j]; if (!(camera == null) && (skipRTCameras == 0 || !(camera.targetTexture != null))) { if (camera.pixelRect.Contains(mousePosition)) @@ -88,12 +84,12 @@ private static void DoSendMouseEvents(int mouseUsed, int skipRTCameras) { Ray ray = camera.ScreenPointToRay(mousePosition); float z = ray.direction.z; - float num = (!Mathf.Approximately(0f, z)) ? Mathf.Abs((camera.farClipPlane - camera.nearClipPlane) / z) : float.PositiveInfinity; - RaycastHit raycastHit; - if (Physics.Raycast(ray, out raycastHit, num + 1f, camera.cullingMask & camera.eventMask & -5)) + float distance = (!Mathf.Approximately(0f, z)) ? Mathf.Abs((camera.farClipPlane - camera.nearClipPlane) / z) : float.PositiveInfinity; + GameObject gameObject = camera.RaycastTry(ray, distance, camera.cullingMask & camera.eventMask); + if (gameObject != null) { + SendMouseEvents.m_CurrentHit[1].target = gameObject; SendMouseEvents.m_CurrentHit[1].camera = camera; - SendMouseEvents.m_CurrentHit[1].target = ((!raycastHit.rigidbody) ? raycastHit.collider.gameObject : raycastHit.rigidbody.gameObject); } else { @@ -103,10 +99,11 @@ private static void DoSendMouseEvents(int mouseUsed, int skipRTCameras) SendMouseEvents.m_CurrentHit[1].camera = null; } } - if (Physics2D.GetRayIntersectionNonAlloc(ray, SendMouseEvents.m_MouseRayHits2D, num, camera.cullingMask & camera.eventMask & -5) == 1) + GameObject gameObject2 = camera.RaycastTry2D(ray, distance, camera.cullingMask & camera.eventMask); + if (gameObject2 != null) { + SendMouseEvents.m_CurrentHit[2].target = gameObject2; SendMouseEvents.m_CurrentHit[2].camera = camera; - SendMouseEvents.m_CurrentHit[2].target = ((!SendMouseEvents.m_MouseRayHits2D[0].rigidbody) ? SendMouseEvents.m_MouseRayHits2D[0].collider.gameObject : SendMouseEvents.m_MouseRayHits2D[0].rigidbody.gameObject); } else { diff --git a/UnityEngine/UnityEngine/Shader.cs b/UnityEngine/UnityEngine/Shader.cs index 51ff8c65..f44ef591 100644 --- a/UnityEngine/UnityEngine/Shader.cs +++ b/UnityEngine/UnityEngine/Shader.cs @@ -40,6 +40,12 @@ public extern int renderQueue [MethodImpl(MethodImplOptions.InternalCall)] get; } + internal extern DisableBatchingType disableBatching + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern Shader Find(string name); @@ -52,6 +58,9 @@ public extern int renderQueue [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DisableKeyword(string keyword); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool IsKeywordEnabled(string keyword); public static void SetGlobalColor(string propertyName, Color color) { Shader.SetGlobalColor(Shader.PropertyToID(propertyName), color); @@ -104,10 +113,10 @@ public static void SetGlobalMatrix(int nameID, Matrix4x4 mat) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_SetGlobalMatrix(int nameID, ref Matrix4x4 mat); - [WrapperlessIcall] + [Obsolete("SetGlobalTexGenMode is not supported anymore. Use programmable shaders to achieve the same effect.", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetGlobalTexGenMode(string propertyName, TexGenMode mode); - [WrapperlessIcall] + [Obsolete("SetGlobalTextureMatrixName is not supported anymore. Use programmable shaders to achieve the same effect.", true), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetGlobalTextureMatrixName(string propertyName, string matrixName); [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/ShaderVariantCollection.cs b/UnityEngine/UnityEngine/ShaderVariantCollection.cs new file mode 100644 index 00000000..4a21c65e --- /dev/null +++ b/UnityEngine/UnityEngine/ShaderVariantCollection.cs @@ -0,0 +1,77 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine.Rendering; +namespace UnityEngine +{ + public sealed class ShaderVariantCollection : Object + { + public struct ShaderVariant + { + public Shader shader; + public PassType passType; + public string[] keywords; + public ShaderVariant(Shader shader, PassType passType, params string[] keywords) + { + this.shader = shader; + this.passType = passType; + this.keywords = keywords; + ShaderVariantCollection.ShaderVariant.Internal_CheckVariant(shader, passType, keywords); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_CheckVariant(Shader shader, PassType passType, string[] keywords); + } + public extern int shaderCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern int variantCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern bool isWarmedUp + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public ShaderVariantCollection() + { + ShaderVariantCollection.Internal_Create(this); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_Create([Writable] ShaderVariantCollection mono); + public bool Add(ShaderVariantCollection.ShaderVariant variant) + { + return this.AddInternal(variant.shader, variant.passType, variant.keywords); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool AddInternal(Shader shader, PassType passType, string[] keywords); + public bool Remove(ShaderVariantCollection.ShaderVariant variant) + { + return this.RemoveInternal(variant.shader, variant.passType, variant.keywords); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool RemoveInternal(Shader shader, PassType passType, string[] keywords); + public bool Contains(ShaderVariantCollection.ShaderVariant variant) + { + return this.ContainsInternal(variant.shader, variant.passType, variant.keywords); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern bool ContainsInternal(Shader shader, PassType passType, string[] keywords); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void Clear(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void WarmUp(); + } +} diff --git a/UnityEngine/UnityEngine/SharedBetweenAnimatorsAttribute.cs b/UnityEngine/UnityEngine/SharedBetweenAnimatorsAttribute.cs new file mode 100644 index 00000000..c23bf4dd --- /dev/null +++ b/UnityEngine/UnityEngine/SharedBetweenAnimatorsAttribute.cs @@ -0,0 +1,8 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public sealed class SharedBetweenAnimatorsAttribute : Attribute + { + } +} diff --git a/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs b/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs index eb777efc..10451326 100644 --- a/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs +++ b/UnityEngine/UnityEngine/SkinnedMeshRenderer.cs @@ -40,17 +40,6 @@ public extern Mesh sharedMesh [MethodImpl(MethodImplOptions.InternalCall)] set; } - [Obsolete("Has no effect.")] - public bool skinNormals - { - get - { - return true; - } - set - { - } - } public extern bool updateWhenOffscreen { [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/SliderHandler.cs b/UnityEngine/UnityEngine/SliderHandler.cs index 6ad698ad..b48b47cf 100644 --- a/UnityEngine/UnityEngine/SliderHandler.cs +++ b/UnityEngine/UnityEngine/SliderHandler.cs @@ -98,7 +98,10 @@ private float OnMouseUp() private float OnRepaint() { this.slider.Draw(this.position, GUIContent.none, this.id); - this.thumb.Draw(this.ThumbRect(), GUIContent.none, this.id); + if (!this.IsEmptySlider()) + { + this.thumb.Draw(this.ThumbRect(), GUIContent.none, this.id); + } if (GUIUtility.hotControl != this.id || !this.position.Contains(this.CurrentEvent().mousePosition) || this.IsEmptySlider()) { return this.currentValue; diff --git a/UnityEngine/UnityEngine/SoftJointLimit.cs b/UnityEngine/UnityEngine/SoftJointLimit.cs index 5b2b9055..4feea1c5 100644 --- a/UnityEngine/UnityEngine/SoftJointLimit.cs +++ b/UnityEngine/UnityEngine/SoftJointLimit.cs @@ -5,8 +5,7 @@ public struct SoftJointLimit { private float m_Limit; private float m_Bounciness; - private float m_Spring; - private float m_Damper; + private float m_ContactDistance; public float limit { get @@ -18,26 +17,26 @@ public float limit this.m_Limit = value; } } + [Obsolete("spring has been moved to SoftJointLimitSpring class in Unity 5", true)] public float spring { get { - return this.m_Spring; + return 0f; } set { - this.m_Spring = value; } } + [Obsolete("damper has been moved to SoftJointLimitSpring class in Unity 5", true)] public float damper { get { - return this.m_Damper; + return 0f; } set { - this.m_Damper = value; } } public float bounciness @@ -51,6 +50,17 @@ public float bounciness this.m_Bounciness = value; } } + public float contactDistance + { + get + { + return this.m_ContactDistance; + } + set + { + this.m_ContactDistance = value; + } + } [Obsolete("Use SoftJointLimit.bounciness instead", true)] public float bouncyness { diff --git a/UnityEngine/UnityEngine/SoftJointLimitSpring.cs b/UnityEngine/UnityEngine/SoftJointLimitSpring.cs new file mode 100644 index 00000000..dea71f44 --- /dev/null +++ b/UnityEngine/UnityEngine/SoftJointLimitSpring.cs @@ -0,0 +1,31 @@ +using System; +namespace UnityEngine +{ + public struct SoftJointLimitSpring + { + private float m_Spring; + private float m_Damper; + public float spring + { + get + { + return this.m_Spring; + } + set + { + this.m_Spring = value; + } + } + public float damper + { + get + { + return this.m_Damper; + } + set + { + this.m_Damper = value; + } + } + } +} diff --git a/UnityEngine/UnityEngine/SplatPrototype.cs b/UnityEngine/UnityEngine/SplatPrototype.cs index bbc7d507..2b158372 100644 --- a/UnityEngine/UnityEngine/SplatPrototype.cs +++ b/UnityEngine/UnityEngine/SplatPrototype.cs @@ -9,6 +9,7 @@ public sealed class SplatPrototype private Texture2D m_NormalMap; private Vector2 m_TileSize = new Vector2(15f, 15f); private Vector2 m_TileOffset = new Vector2(0f, 0f); + private Vector4 m_SpecularMetallic = new Vector4(0f, 0f, 0f, 0f); public Texture2D texture { get @@ -53,5 +54,29 @@ public Vector2 tileOffset this.m_TileOffset = value; } } + public Color specular + { + get + { + return new Color(this.m_SpecularMetallic.x, this.m_SpecularMetallic.y, this.m_SpecularMetallic.z); + } + set + { + this.m_SpecularMetallic.x = value.r; + this.m_SpecularMetallic.y = value.g; + this.m_SpecularMetallic.z = value.b; + } + } + public float metallic + { + get + { + return this.m_SpecularMetallic.w; + } + set + { + this.m_SpecularMetallic.w = value; + } + } } } diff --git a/UnityEngine/UnityEngine/Sprite.cs b/UnityEngine/UnityEngine/Sprite.cs index 30d95727..0e2f7f43 100644 --- a/UnityEngine/UnityEngine/Sprite.cs +++ b/UnityEngine/UnityEngine/Sprite.cs @@ -62,12 +62,39 @@ public extern SpritePackingRotation packingRotation [MethodImpl(MethodImplOptions.InternalCall)] get; } + public Vector2 pivot + { + get + { + Vector2 result; + Sprite.Internal_GetPivot(this, out result); + return result; + } + } public extern Vector4 border { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern Vector2[] vertices + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern ushort[] triangles + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public extern Vector2[] uv + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, [DefaultValue("100.0f")] float pixelsPerUnit, [DefaultValue("0")] uint extrude, [DefaultValue("SpriteMeshType.Tight")] SpriteMeshType meshType, [DefaultValue("Vector4.zero")] Vector4 border) { return Sprite.INTERNAL_CALL_Create(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref border); @@ -108,5 +135,11 @@ public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot) [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_GetTextureRectOffset(Sprite sprite, out Vector2 output); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void Internal_GetPivot(Sprite sprite, out Vector2 output); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void OverrideGeometry(Vector2[] vertices, ushort[] triangles); } } diff --git a/UnityEngine/UnityEngine/StackTraceUtility.cs b/UnityEngine/UnityEngine/StackTraceUtility.cs index afd428b0..75342908 100644 --- a/UnityEngine/UnityEngine/StackTraceUtility.cs +++ b/UnityEngine/UnityEngine/StackTraceUtility.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Reflection; +using System.Security; using System.Text; namespace UnityEngine { @@ -11,6 +12,7 @@ internal static void SetProjectFolder(string folder) { StackTraceUtility.projectFolder = folder; } + [SecuritySafeCritical] public static string ExtractStackTrace() { StackTrace stackTrace = new StackTrace(1, true); @@ -28,6 +30,7 @@ public static string ExtractStringFromException(object exception) StackTraceUtility.ExtractStringFromExceptionInternal(exception, out empty, out empty2); return empty + "\n" + empty2; } + [SecuritySafeCritical] internal static void ExtractStringFromExceptionInternal(object exceptiono, out string message, out string stackTrace) { if (exceptiono == null) @@ -156,6 +159,7 @@ internal static string PostprocessStacktrace(string oldString, bool stripEngineI } return stringBuilder.ToString(); } + [SecuritySafeCritical] internal static string ExtractFormattedStackTrace(StackTrace stackTrace) { StringBuilder stringBuilder = new StringBuilder(255); diff --git a/UnityEngine/UnityEngine/StateMachineBehaviour.cs b/UnityEngine/UnityEngine/StateMachineBehaviour.cs new file mode 100644 index 00000000..cb4c55ff --- /dev/null +++ b/UnityEngine/UnityEngine/StateMachineBehaviour.cs @@ -0,0 +1,28 @@ +using System; +namespace UnityEngine +{ + public abstract class StateMachineBehaviour : ScriptableObject + { + public virtual void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) + { + } + public virtual void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) + { + } + public virtual void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) + { + } + public virtual void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) + { + } + public virtual void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) + { + } + public virtual void OnStateMachineEnter(Animator animator, int stateMachinePathHash) + { + } + public virtual void OnStateMachineExit(Animator animator, int stateMachinePathHash) + { + } + } +} diff --git a/UnityEngine/UnityEngine/SurfaceEffector2D.cs b/UnityEngine/UnityEngine/SurfaceEffector2D.cs new file mode 100644 index 00000000..94695152 --- /dev/null +++ b/UnityEngine/UnityEngine/SurfaceEffector2D.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class SurfaceEffector2D : Effector2D + { + public extern float speed + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float speedVariation + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + } +} diff --git a/UnityEngine/UnityEngine/SystemInfo.cs b/UnityEngine/UnityEngine/SystemInfo.cs index cd0d6b9f..28e22e40 100644 --- a/UnityEngine/UnityEngine/SystemInfo.cs +++ b/UnityEngine/UnityEngine/SystemInfo.cs @@ -70,7 +70,23 @@ public static extern int graphicsShaderLevel [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern int graphicsPixelFillrate + [Obsolete("graphicsPixelFillrate is no longer supported in Unity 5.0+.")] + public static int graphicsPixelFillrate + { + get + { + return -1; + } + } + [Obsolete("Vertex program support is required in Unity 5.0+")] + public static bool supportsVertexPrograms + { + get + { + return true; + } + } + public static extern bool graphicsMultiThreaded { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -136,12 +152,6 @@ public static extern int supportsStencil [MethodImpl(MethodImplOptions.InternalCall)] get; } - public static extern bool supportsVertexPrograms - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } public static extern NPOTSupport npotSupport { [WrapperlessIcall] @@ -205,5 +215,8 @@ public static extern int maxTextureSize [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool SupportsRenderTextureFormat(RenderTextureFormat format); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern bool SupportsTextureFormat(TextureFormat format); } } diff --git a/UnityEngine/UnityEngine/SystemLanguage.cs b/UnityEngine/UnityEngine/SystemLanguage.cs index 2a4c3060..e01f723b 100644 --- a/UnityEngine/UnityEngine/SystemLanguage.cs +++ b/UnityEngine/UnityEngine/SystemLanguage.cs @@ -43,6 +43,8 @@ public enum SystemLanguage Turkish, Ukrainian, Vietnamese, + ChineseSimplified, + ChineseTraditional, Unknown, Hungarian = 18 } diff --git a/UnityEngine/UnityEngine/Terrain.cs b/UnityEngine/UnityEngine/Terrain.cs index 7c8cb7f2..030e636e 100644 --- a/UnityEngine/UnityEngine/Terrain.cs +++ b/UnityEngine/UnityEngine/Terrain.cs @@ -1,247 +1,125 @@ using System; using System.Collections.Generic; using System.Runtime.CompilerServices; +using UnityEngine.Rendering; namespace UnityEngine { - [AddComponentMenu(""), ExecuteInEditMode] - public sealed class Terrain : MonoBehaviour + public sealed class Terrain : Behaviour { - [SerializeField] - private TerrainData m_TerrainData; - [SerializeField] - private float m_TreeDistance = 5000f; - [SerializeField] - private float m_TreeBillboardDistance = 50f; - [SerializeField] - private float m_TreeCrossFadeLength = 5f; - [SerializeField] - private int m_TreeMaximumFullLODCount = 50; - [SerializeField] - private float m_DetailObjectDistance = 80f; - [SerializeField] - private float m_DetailObjectDensity = 1f; - [SerializeField] - private float m_HeightmapPixelError = 5f; - [SerializeField] - private float m_SplatMapDistance = 1000f; - [SerializeField] - private int m_HeightmapMaximumLOD; - [SerializeField] - private bool m_CastShadows = true; - [SerializeField] - private int m_LightmapIndex = -1; - [SerializeField] - private int m_LightmapSize = 1024; - [SerializeField] - private bool m_DrawTreesAndFoliage = true; - [SerializeField] - private bool m_CollectDetailPatches = true; - [SerializeField] - private Material m_MaterialTemplate; - [NonSerialized] - private IntPtr m_TerrainInstance; - private IntPtr InstanceObject + public enum MaterialType { - get - { - this.MakeSureObjectIsAlive(); - if (this.m_TerrainInstance == IntPtr.Zero) - { - this.m_TerrainInstance = this.Construct(); - this.Internal_SetTerrainData(this.m_TerrainInstance, this.m_TerrainData); - this.Internal_SetTreeDistance(this.m_TerrainInstance, this.m_TreeDistance); - this.Internal_SetTreeBillboardDistance(this.m_TerrainInstance, this.m_TreeBillboardDistance); - this.Internal_SetTreeCrossFadeLength(this.m_TerrainInstance, this.m_TreeCrossFadeLength); - this.Internal_SetTreeMaximumFullLODCount(this.m_TerrainInstance, this.m_TreeMaximumFullLODCount); - this.Internal_SetDetailObjectDistance(this.m_TerrainInstance, this.m_DetailObjectDistance); - this.Internal_SetDetailObjectDensity(this.m_TerrainInstance, this.m_DetailObjectDensity); - this.Internal_SetHeightmapPixelError(this.m_TerrainInstance, this.m_HeightmapPixelError); - this.Internal_SetBasemapDistance(this.m_TerrainInstance, this.m_SplatMapDistance); - this.Internal_SetHeightmapMaximumLOD(this.m_TerrainInstance, this.m_HeightmapMaximumLOD); - this.Internal_SetCastShadows(this.m_TerrainInstance, this.m_CastShadows); - this.Internal_SetLightmapIndex(this.m_TerrainInstance, this.m_LightmapIndex); - this.Internal_SetLightmapSize(this.m_TerrainInstance, this.m_LightmapSize); - this.Internal_SetDrawTreesAndFoliage(this.m_TerrainInstance, this.m_DrawTreesAndFoliage); - this.Internal_SetCollectDetailPatches(this.m_TerrainInstance, this.m_CollectDetailPatches); - this.Internal_SetMaterialTemplate(this.m_TerrainInstance, this.m_MaterialTemplate); - } - return this.m_TerrainInstance; - } - set - { - this.m_TerrainInstance = value; - } + BuiltInStandard, + BuiltInLegacyDiffuse, + BuiltInLegacySpecular, + Custom } - public TerrainRenderFlags editorRenderFlags + public extern TerrainRenderFlags editorRenderFlags { - get - { - return (TerrainRenderFlags)this.GetEditorRenderFlags(this.InstanceObject); - } - set - { - this.SetEditorRenderFlags(this.InstanceObject, (int)value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public TerrainData terrainData + public extern TerrainData terrainData { - get - { - if (this.m_TerrainData != this.Internal_GetTerrainData(this.InstanceObject)) - { - this.Internal_SetTerrainData(this.InstanceObject, this.m_TerrainData); - } - return this.m_TerrainData; - } - set - { - this.m_TerrainData = value; - this.Internal_SetTerrainData(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float treeDistance + public extern float treeDistance { - get - { - if (this.m_TreeDistance != this.Internal_GetTreeDistance(this.InstanceObject)) - { - this.Internal_SetTreeDistance(this.InstanceObject, this.m_TreeDistance); - } - return this.m_TreeDistance; - } - set - { - this.m_TreeDistance = value; - this.Internal_SetTreeDistance(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float treeBillboardDistance + public extern float treeBillboardDistance { - get - { - if (this.m_TreeBillboardDistance != this.Internal_GetTreeBillboardDistance(this.InstanceObject)) - { - this.Internal_SetTreeBillboardDistance(this.InstanceObject, this.m_TreeBillboardDistance); - } - return this.m_TreeBillboardDistance; - } - set - { - this.m_TreeBillboardDistance = value; - this.Internal_SetTreeBillboardDistance(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float treeCrossFadeLength + public extern float treeCrossFadeLength { - get - { - if (this.m_TreeCrossFadeLength != this.Internal_GetTreeCrossFadeLength(this.InstanceObject)) - { - this.Internal_SetTreeCrossFadeLength(this.InstanceObject, this.m_TreeCrossFadeLength); - } - return this.m_TreeCrossFadeLength; - } - set - { - this.m_TreeCrossFadeLength = value; - this.Internal_SetTreeCrossFadeLength(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public int treeMaximumFullLODCount + public extern int treeMaximumFullLODCount { - get - { - if (this.m_TreeMaximumFullLODCount != this.Internal_GetTreeMaximumFullLODCount(this.InstanceObject)) - { - this.Internal_SetTreeMaximumFullLODCount(this.InstanceObject, this.m_TreeMaximumFullLODCount); - } - return this.m_TreeMaximumFullLODCount; - } - set - { - this.m_TreeMaximumFullLODCount = value; - this.Internal_SetTreeMaximumFullLODCount(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float detailObjectDistance + public extern float detailObjectDistance { - get - { - if (this.m_DetailObjectDistance != this.Internal_GetDetailObjectDistance(this.InstanceObject)) - { - this.Internal_SetDetailObjectDistance(this.InstanceObject, this.m_DetailObjectDistance); - } - return this.m_DetailObjectDistance; - } - set - { - this.m_DetailObjectDistance = value; - this.Internal_SetDetailObjectDistance(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float detailObjectDensity + public extern float detailObjectDensity { - get - { - if (this.m_DetailObjectDensity != this.Internal_GetDetailObjectDensity(this.InstanceObject)) - { - this.Internal_SetDetailObjectDensity(this.InstanceObject, this.m_DetailObjectDensity); - } - return this.m_DetailObjectDensity; - } - set - { - this.m_DetailObjectDensity = value; - this.Internal_SetDetailObjectDensity(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float heightmapPixelError + public extern bool collectDetailPatches { - get - { - if (this.m_HeightmapPixelError != this.Internal_GetHeightmapPixelError(this.InstanceObject)) - { - this.Internal_SetHeightmapPixelError(this.InstanceObject, this.m_HeightmapPixelError); - } - return this.m_HeightmapPixelError; - } - set - { - this.m_HeightmapPixelError = value; - this.Internal_SetHeightmapPixelError(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public int heightmapMaximumLOD + public extern float heightmapPixelError { - get - { - if (this.m_HeightmapMaximumLOD != this.Internal_GetHeightmapMaximumLOD(this.InstanceObject)) - { - this.Internal_SetHeightmapMaximumLOD(this.InstanceObject, this.m_HeightmapMaximumLOD); - } - return this.m_HeightmapMaximumLOD; - } - set - { - this.m_HeightmapMaximumLOD = value; - this.Internal_SetHeightmapMaximumLOD(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public float basemapDistance + public extern int heightmapMaximumLOD { - get - { - if (this.m_SplatMapDistance != this.Internal_GetBasemapDistance(this.InstanceObject)) - { - this.Internal_SetBasemapDistance(this.InstanceObject, this.m_SplatMapDistance); - } - return this.m_SplatMapDistance; - } - set - { - this.m_SplatMapDistance = value; - this.Internal_SetBasemapDistance(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + public extern float basemapDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } [Obsolete("use basemapDistance", true)] public float splatmapDistance @@ -255,354 +133,181 @@ public float splatmapDistance this.basemapDistance = value; } } - public int lightmapIndex + public extern int lightmapIndex { - get - { - if (this.m_LightmapIndex != this.Internal_GetLightmapIndex(this.InstanceObject)) - { - this.Internal_SetLightmapIndex(this.InstanceObject, this.m_LightmapIndex); - } - return this.m_LightmapIndex; - } - set - { - this.m_LightmapIndex = value; - this.Internal_SetLightmapIndex(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - internal int lightmapSize + public extern bool castShadows { - get - { - if (this.m_LightmapSize != this.Internal_GetLightmapSize(this.InstanceObject)) - { - this.Internal_SetLightmapSize(this.InstanceObject, this.m_LightmapSize); - } - return this.m_LightmapSize; - } - set - { - this.m_LightmapSize = value; - this.Internal_SetLightmapSize(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public bool castShadows + public extern ReflectionProbeUsage reflectionProbeUsage { - get - { - if (this.m_CastShadows != this.Internal_GetCastShadows(this.InstanceObject)) - { - this.Internal_SetCastShadows(this.InstanceObject, this.m_CastShadows); - } - return this.m_CastShadows; - } - set - { - this.m_CastShadows = value; - this.Internal_SetCastShadows(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public Material materialTemplate + public extern Terrain.MaterialType materialType { - get - { - if (this.m_MaterialTemplate != this.Internal_GetMaterialTemplate(this.InstanceObject)) - { - this.Internal_SetMaterialTemplate(this.InstanceObject, this.m_MaterialTemplate); - } - return this.m_MaterialTemplate; - } - set - { - this.m_MaterialTemplate = value; - this.Internal_SetMaterialTemplate(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - internal bool drawTreesAndFoliage + public extern Material materialTemplate { - get - { - if (this.m_DrawTreesAndFoliage != this.Internal_GetDrawTreesAndFoliage(this.InstanceObject)) - { - this.Internal_SetDrawTreesAndFoliage(this.InstanceObject, this.m_DrawTreesAndFoliage); - } - return this.m_DrawTreesAndFoliage; - } - set - { - this.m_DrawTreesAndFoliage = value; - this.Internal_SetDrawTreesAndFoliage(this.InstanceObject, value); - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public bool collectDetailPatches + public Color legacySpecular { get { - if (this.m_CollectDetailPatches != this.Internal_GetCollectDetailPatches(this.InstanceObject)) - { - this.Internal_SetCollectDetailPatches(this.InstanceObject, this.m_CollectDetailPatches); - } - return this.m_CollectDetailPatches; + Color result; + this.INTERNAL_get_legacySpecular(out result); + return result; } set { - this.m_CollectDetailPatches = value; - this.Internal_SetCollectDetailPatches(this.InstanceObject, value); + this.INTERNAL_set_legacySpecular(ref value); } } - public static extern Terrain activeTerrain + public extern float legacyShininess { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - public static extern Terrain[] activeTerrains + public extern bool useDefaultSmoothness { [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - private void OnDestroy() + public extern float defaultSmoothness { - this.OnDisable(); - this.Cleanup(this.m_TerrainInstance); - this.m_TerrainInstance = IntPtr.Zero; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void MakeSureObjectIsAlive(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Cleanup(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int GetEditorRenderFlags(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void SetEditorRenderFlags(IntPtr terrainInstance, int flags); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern TerrainData Internal_GetTerrainData(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetTerrainData(IntPtr terrainInstance, TerrainData value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetTreeDistance(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetTreeDistance(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetTreeBillboardDistance(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetTreeBillboardDistance(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetTreeCrossFadeLength(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetTreeCrossFadeLength(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetTreeMaximumFullLODCount(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetTreeMaximumFullLODCount(IntPtr terrainInstance, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetDetailObjectDistance(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetDetailObjectDistance(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetDetailObjectDensity(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetDetailObjectDensity(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetHeightmapPixelError(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetHeightmapPixelError(IntPtr terrainInstance, float value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetHeightmapMaximumLOD(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetHeightmapMaximumLOD(IntPtr terrainInstance, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern float Internal_GetBasemapDistance(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetBasemapDistance(IntPtr terrainInstance, float value); - private void SetLightmapIndex(int value) + public extern bool drawHeightmap { - this.lightmapIndex = value; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - private void ShiftLightmapIndex(int offset) + public extern bool drawTreesAndFoliage { - this.lightmapIndex += offset; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetLightmapIndex(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetLightmapIndex(IntPtr terrainInstance, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern int Internal_GetLightmapSize(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetLightmapSize(IntPtr terrainInstance, int value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool Internal_GetCastShadows(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetCastShadows(IntPtr terrainInstance, bool value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern Material Internal_GetMaterialTemplate(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetMaterialTemplate(IntPtr terrainInstance, Material value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool Internal_GetDrawTreesAndFoliage(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetDrawTreesAndFoliage(IntPtr terrainInstance, bool value); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern bool Internal_GetCollectDetailPatches(IntPtr terrainInstance); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetCollectDetailPatches(IntPtr terrainInstance, bool value); - public float SampleHeight(Vector3 worldPosition) + public extern bool bakeLightProbesForTrees { - return this.Internal_SampleHeight(this.InstanceObject, worldPosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; } - private float Internal_SampleHeight(IntPtr terrainInstance, Vector3 worldPosition) + public static extern Terrain activeTerrain { - return Terrain.INTERNAL_CALL_Internal_SampleHeight(this, terrainInstance, ref worldPosition); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern float INTERNAL_CALL_Internal_SampleHeight(Terrain self, IntPtr terrainInstance, ref Vector3 worldPosition); - internal void ApplyDelayedHeightmapModification() + public static extern Terrain[] activeTerrains { - this.Internal_ApplyDelayedHeightmapModification(this.InstanceObject); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void Internal_ApplyDelayedHeightmapModification(IntPtr terrainInstance); - public void AddTreeInstance(TreeInstance instance) - { - this.Internal_AddTreeInstance(this.InstanceObject, instance); - } - private void Internal_AddTreeInstance(IntPtr terrainInstance, TreeInstance instance) - { - Terrain.INTERNAL_CALL_Internal_AddTreeInstance(this, terrainInstance, ref instance); - } + private extern void ShiftLightmapIndex(int offset); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Internal_AddTreeInstance(Terrain self, IntPtr terrainInstance, ref TreeInstance instance); - public void SetNeighbors(Terrain left, Terrain top, Terrain right, Terrain bottom) + private extern void GetClosestReflectionProbesInternal(object result); + public void GetClosestReflectionProbes(List result) { - this.Internal_SetNeighbors(this.InstanceObject, (!(left != null)) ? IntPtr.Zero : left.InstanceObject, (!(top != null)) ? IntPtr.Zero : top.InstanceObject, (!(right != null)) ? IntPtr.Zero : right.InstanceObject, (!(bottom != null)) ? IntPtr.Zero : bottom.InstanceObject); + this.GetClosestReflectionProbesInternal(result); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_SetNeighbors(IntPtr terrainInstance, IntPtr left, IntPtr top, IntPtr right, IntPtr bottom); - public Vector3 GetPosition() - { - return this.Internal_GetPosition(this.InstanceObject); - } + private extern void INTERNAL_get_legacySpecular(out Color value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern Vector3 Internal_GetPosition(IntPtr terrainInstance); - public void Flush() + private extern void INTERNAL_set_legacySpecular(ref Color value); + public float SampleHeight(Vector3 worldPosition) { - this.Internal_Flush(this.InstanceObject); + return Terrain.INTERNAL_CALL_SampleHeight(this, ref worldPosition); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_Flush(IntPtr terrainInstance); - internal void RemoveTrees(Vector2 position, float radius, int prototypeIndex) - { - this.Internal_RemoveTrees(this.InstanceObject, position, radius, prototypeIndex); - } - private void Internal_RemoveTrees(IntPtr terrainInstance, Vector2 position, float radius, int prototypeIndex) - { - Terrain.INTERNAL_CALL_Internal_RemoveTrees(this, terrainInstance, ref position, radius, prototypeIndex); - } + private static extern float INTERNAL_CALL_SampleHeight(Terrain self, ref Vector3 worldPosition); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_Internal_RemoveTrees(Terrain self, IntPtr terrainInstance, ref Vector2 position, float radius, int prototypeIndex); - private void OnTerrainChanged(TerrainChangedFlags flags) + internal extern void ApplyDelayedHeightmapModification(); + public void AddTreeInstance(TreeInstance instance) { - this.Internal_OnTerrainChanged(this.InstanceObject, flags); + Terrain.INTERNAL_CALL_AddTreeInstance(this, ref instance); } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_OnTerrainChanged(IntPtr terrainInstance, TerrainChangedFlags flags); + private static extern void INTERNAL_CALL_AddTreeInstance(Terrain self, ref TreeInstance instance); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern IntPtr Construct(); - internal void OnEnable() - { - this.Internal_OnEnable(this.InstanceObject); - } + public extern void SetNeighbors(Terrain left, Terrain top, Terrain right, Terrain bottom); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_OnEnable(IntPtr terrainInstance); - internal void OnDisable() - { - this.Internal_OnDisable(this.InstanceObject); - } + public extern Vector3 GetPosition(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Internal_OnDisable(IntPtr terrainInstance); - public static GameObject CreateTerrainGameObject(TerrainData assignTerrain) + public extern void Flush(); + internal void RemoveTrees(Vector2 position, float radius, int prototypeIndex) { - GameObject gameObject = new GameObject("Terrain", new Type[] - { - typeof(Terrain), - typeof(TerrainCollider) - }); - gameObject.isStatic = true; - Terrain terrain = gameObject.GetComponent(typeof(Terrain)) as Terrain; - TerrainCollider terrainCollider = gameObject.GetComponent(typeof(TerrainCollider)) as TerrainCollider; - terrainCollider.terrainData = assignTerrain; - terrain.terrainData = assignTerrain; - terrain.OnEnable(); - return gameObject; - } - private static void ReconnectTerrainData() - { - List list = new List(Terrain.activeTerrains); - foreach (Terrain current in list) - { - if (current.terrainData == null) - { - current.OnDisable(); - } - else - { - if (!current.terrainData.HasUser(current.gameObject)) - { - current.OnDisable(); - current.OnEnable(); - } - } - } + Terrain.INTERNAL_CALL_RemoveTrees(this, ref position, radius, prototypeIndex); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_RemoveTrees(Terrain self, ref Vector2 position, float radius, int prototypeIndex); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern GameObject CreateTerrainGameObject(TerrainData assignTerrain); } } diff --git a/UnityEngine/UnityEngine/TerrainData.cs b/UnityEngine/UnityEngine/TerrainData.cs index f6579b5c..aabbd3a5 100644 --- a/UnityEngine/UnityEngine/TerrainData.cs +++ b/UnityEngine/UnityEngine/TerrainData.cs @@ -4,15 +4,6 @@ namespace UnityEngine { public sealed class TerrainData : Object { - public extern PhysicMaterial physicMaterial - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } public extern int heightmapWidth { [WrapperlessIcall] @@ -53,6 +44,15 @@ public Vector3 size this.INTERNAL_set_size(ref value); } } + public extern float thickness + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern float wavingGrassStrength { [WrapperlessIcall] @@ -135,6 +135,12 @@ public extern TreeInstance[] treeInstances [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern int treeInstanceCount + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern TreePrototype[] treePrototypes { [WrapperlessIcall] @@ -305,6 +311,16 @@ public void SetDetailLayer(int xBase, int yBase, int layer, int[,] details) private extern void Internal_SetDetailLayer(int xBase, int yBase, int totalWidth, int totalHeight, int detailIndex, int[,] data); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern TreeInstance GetTreeInstance(int index); + public void SetTreeInstance(int index, TreeInstance instance) + { + TerrainData.INTERNAL_CALL_SetTreeInstance(this, index, ref instance); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern void INTERNAL_CALL_SetTreeInstance(TerrainData self, int index, ref TreeInstance instance); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] internal extern void RemoveTreePrototype(int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -340,9 +356,6 @@ public void SetAlphamaps(int x, int y, float[,,] map) private extern Texture2D GetAlphamapTexture(int index); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool HasTreeInstances(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] internal extern void AddTree(out TreeInstance tree); internal int RemoveTrees(Vector2 position, float radius, int prototypeIndex) { diff --git a/UnityEngine/UnityEngine/TextEditor.cs b/UnityEngine/UnityEngine/TextEditor.cs index 08e22c13..6e290f4c 100644 --- a/UnityEngine/UnityEngine/TextEditor.cs +++ b/UnityEngine/UnityEngine/TextEditor.cs @@ -1264,12 +1264,23 @@ public void Copy() } GUIUtility.systemCopyBuffer = systemCopyBuffer; } + private static string ReplaceNewlinesWithSpaces(string value) + { + value = value.Replace("\r\n", " "); + value = value.Replace('\n', ' '); + value = value.Replace('\r', ' '); + return value; + } public bool Paste() { - string systemCopyBuffer = GUIUtility.systemCopyBuffer; - if (systemCopyBuffer != string.Empty) + string text = GUIUtility.systemCopyBuffer; + if (text != string.Empty) { - this.ReplaceSelection(systemCopyBuffer); + if (!this.multiline) + { + text = TextEditor.ReplaceNewlinesWithSpaces(text); + } + this.ReplaceSelection(text); return true; } return false; diff --git a/UnityEngine/UnityEngine/TextGenerator.cs b/UnityEngine/UnityEngine/TextGenerator.cs index 20a31cb5..0e48f967 100644 --- a/UnityEngine/UnityEngine/TextGenerator.cs +++ b/UnityEngine/UnityEngine/TextGenerator.cs @@ -22,42 +22,6 @@ public sealed class TextGenerator : IDisposable private static int s_NextId = 0; private int m_Id; private static readonly Dictionary s_Instances = new Dictionary(); - public IList verts - { - get - { - if (!this.m_CachedVerts) - { - this.GetVertices(this.m_Verts); - this.m_CachedVerts = true; - } - return this.m_Verts; - } - } - public IList characters - { - get - { - if (!this.m_CachedCharacters) - { - this.GetCharacters(this.m_Characters); - this.m_CachedCharacters = true; - } - return this.m_Characters; - } - } - public IList lines - { - get - { - if (!this.m_CachedLines) - { - this.GetLines(this.m_Lines); - this.m_CachedLines = true; - } - return this.m_Lines; - } - } public extern Rect rectExtents { [WrapperlessIcall] @@ -95,6 +59,42 @@ public extern int fontSizeUsedForBestFit [MethodImpl(MethodImplOptions.InternalCall)] get; } + public IList verts + { + get + { + if (!this.m_CachedVerts) + { + this.GetVertices(this.m_Verts); + this.m_CachedVerts = true; + } + return this.m_Verts; + } + } + public IList characters + { + get + { + if (!this.m_CachedCharacters) + { + this.GetCharacters(this.m_Characters); + this.m_CachedCharacters = true; + } + return this.m_Characters; + } + } + public IList lines + { + get + { + if (!this.m_CachedLines) + { + this.GetLines(this.m_Lines); + this.m_CachedLines = true; + } + return this.m_Lines; + } + } public TextGenerator() : this(50) { } @@ -130,6 +130,41 @@ void IDisposable.Dispose() } this.Dispose_cpp(); } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Init(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void Dispose_cpp(); + internal bool Populate_Internal(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, VerticalWrapMode verticalOverFlow, HorizontalWrapMode horizontalOverflow, bool updateBounds, TextAnchor anchor, Vector2 extents, Vector2 pivot, bool generateOutOfBounds) + { + return this.Populate_Internal_cpp(str, font, color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, (int)verticalOverFlow, (int)horizontalOverflow, updateBounds, anchor, extents.x, extents.y, pivot.x, pivot.y, generateOutOfBounds); + } + internal bool Populate_Internal_cpp(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds) + { + return TextGenerator.INTERNAL_CALL_Populate_Internal_cpp(this, str, font, ref color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, verticalOverFlow, horizontalOverflow, updateBounds, anchor, extentsX, extentsY, pivotX, pivotY, generateOutOfBounds); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private static extern bool INTERNAL_CALL_Populate_Internal_cpp(TextGenerator self, string str, Font font, ref Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetVerticesInternal(object vertices); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UIVertex[] GetVerticesArray(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetCharactersInternal(object characters); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UICharInfo[] GetCharactersArray(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void GetLinesInternal(object lines); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern UILineInfo[] GetLinesArray(); ~TextGenerator() { ((IDisposable)this).Dispose(); @@ -224,40 +259,5 @@ private bool PopulateAlways(string str, TextGenerationSettings settings) this.m_LastValid = this.Populate_Internal(str, textGenerationSettings.font, textGenerationSettings.color, textGenerationSettings.fontSize, textGenerationSettings.lineSpacing, textGenerationSettings.fontStyle, textGenerationSettings.richText, textGenerationSettings.resizeTextForBestFit, textGenerationSettings.resizeTextMinSize, textGenerationSettings.resizeTextMaxSize, textGenerationSettings.verticalOverflow, textGenerationSettings.horizontalOverflow, textGenerationSettings.updateBounds, textGenerationSettings.textAnchor, textGenerationSettings.generationExtents, textGenerationSettings.pivot, textGenerationSettings.generateOutOfBounds); return this.m_LastValid; } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Init(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Dispose_cpp(); - internal bool Populate_Internal(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, VerticalWrapMode verticalOverFlow, HorizontalWrapMode horizontalOverflow, bool updateBounds, TextAnchor anchor, Vector2 extents, Vector2 pivot, bool generateOutOfBounds) - { - return this.Populate_Internal_cpp(str, font, color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, (int)verticalOverFlow, (int)horizontalOverflow, updateBounds, anchor, extents.x, extents.y, pivot.x, pivot.y, generateOutOfBounds); - } - internal bool Populate_Internal_cpp(string str, Font font, Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds) - { - return TextGenerator.INTERNAL_CALL_Populate_Internal_cpp(this, str, font, ref color, fontSize, lineSpacing, style, richText, resizeTextForBestFit, resizeTextMinSize, resizeTextMaxSize, verticalOverFlow, horizontalOverflow, updateBounds, anchor, extentsX, extentsY, pivotX, pivotY, generateOutOfBounds); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern bool INTERNAL_CALL_Populate_Internal_cpp(TextGenerator self, string str, Font font, ref Color color, int fontSize, float lineSpacing, FontStyle style, bool richText, bool resizeTextForBestFit, int resizeTextMinSize, int resizeTextMaxSize, int verticalOverFlow, int horizontalOverflow, bool updateBounds, TextAnchor anchor, float extentsX, float extentsY, float pivotX, float pivotY, bool generateOutOfBounds); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void GetVerticesInternal(object vertices); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern UIVertex[] GetVerticesArray(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void GetCharactersInternal(object characters); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern UICharInfo[] GetCharactersArray(); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void GetLinesInternal(object lines); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public extern UILineInfo[] GetLinesArray(); } } diff --git a/UnityEngine/UnityEngine/Texture.cs b/UnityEngine/UnityEngine/Texture.cs index 6894e9fd..b7f30c1e 100644 --- a/UnityEngine/UnityEngine/Texture.cs +++ b/UnityEngine/UnityEngine/Texture.cs @@ -80,14 +80,11 @@ public extern float mipMapBias [MethodImpl(MethodImplOptions.InternalCall)] set; } - public Vector2 texelSize + public extern Vector2 texelSize { - get - { - Vector2 result; - Texture.Internal_GetTexelSize(this, out result); - return result; - } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] @@ -100,9 +97,6 @@ public Vector2 texelSize private static extern int Internal_GetHeight(Texture mono); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void Internal_GetTexelSize(Texture tex, out Vector2 output); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] public extern IntPtr GetNativeTexturePtr(); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] diff --git a/UnityEngine/UnityEngine/Texture2D.cs b/UnityEngine/UnityEngine/Texture2D.cs index 57e174aa..934f1cbc 100644 --- a/UnityEngine/UnityEngine/Texture2D.cs +++ b/UnityEngine/UnityEngine/Texture2D.cs @@ -108,13 +108,30 @@ public void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] col } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void SetPixels32(Color32[] colors, [DefaultValue("0")] int miplevel); + private extern void SetAllPixels32(Color32[] colors, int miplevel); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + private extern void SetBlockOfPixels32(int x, int y, int blockWidth, int blockHeight, Color32[] colors, int miplevel); [ExcludeFromDocs] public void SetPixels32(Color32[] colors) { int miplevel = 0; this.SetPixels32(colors, miplevel); } + public void SetPixels32(Color32[] colors, [DefaultValue("0")] int miplevel) + { + this.SetAllPixels32(colors, miplevel); + } + [ExcludeFromDocs] + public void SetPixels32(int x, int y, int blockWidth, int blockHeight, Color32[] colors) + { + int miplevel = 0; + this.SetPixels32(x, y, blockWidth, blockHeight, colors, miplevel); + } + public void SetPixels32(int x, int y, int blockWidth, int blockHeight, Color32[] colors, [DefaultValue("0")] int miplevel) + { + this.SetBlockOfPixels32(x, y, blockWidth, blockHeight, colors, miplevel); + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern bool LoadImage(byte[] data); diff --git a/UnityEngine/UnityEngine/TextureFormat.cs b/UnityEngine/UnityEngine/TextureFormat.cs index 7cd1df44..2bd156a7 100644 --- a/UnityEngine/UnityEngine/TextureFormat.cs +++ b/UnityEngine/UnityEngine/TextureFormat.cs @@ -9,10 +9,18 @@ public enum TextureFormat RGBA32, ARGB32, RGB565 = 7, - DXT1 = 10, + R16 = 9, + DXT1, DXT5 = 12, RGBA4444, BGRA32, + RHalf, + RGHalf, + RGBAHalf, + RFloat, + RGFloat, + RGBAFloat, + YUY2, PVRTC_RGB2 = 30, PVRTC_RGBA2, PVRTC_RGB4, @@ -20,10 +28,7 @@ public enum TextureFormat ETC_RGB4, ATC_RGB4, ATC_RGBA8, - ATF_RGB_DXT1 = 38, - ATF_RGBA_JPG, - ATF_RGB_JPG, - EAC_R, + EAC_R = 41, EAC_R_SIGNED, EAC_RG, EAC_RG_SIGNED, @@ -42,9 +47,9 @@ public enum TextureFormat ASTC_RGBA_8x8, ASTC_RGBA_10x10, ASTC_RGBA_12x12, - PVRTC_2BPP_RGB = 30, - PVRTC_2BPP_RGBA, - PVRTC_4BPP_RGB, - PVRTC_4BPP_RGBA + PVRTC_2BPP_RGB = -127, + PVRTC_2BPP_RGBA = -127, + PVRTC_4BPP_RGB = -127, + PVRTC_4BPP_RGBA = -127 } } diff --git a/UnityEngine/UnityEngine/TouchScreenKeyboard.cs b/UnityEngine/UnityEngine/TouchScreenKeyboard.cs index 2200c56e..e1f5112c 100644 --- a/UnityEngine/UnityEngine/TouchScreenKeyboard.cs +++ b/UnityEngine/UnityEngine/TouchScreenKeyboard.cs @@ -5,27 +5,37 @@ namespace UnityEngine { public sealed class TouchScreenKeyboard { - [NotRenamed] [NonSerialized] internal IntPtr m_Ptr; public static bool isSupported { get { - switch (Application.platform) + RuntimePlatform platform = Application.platform; + RuntimePlatform runtimePlatform = platform; + switch (runtimePlatform) { - case RuntimePlatform.IPhonePlayer: - case RuntimePlatform.Android: + case RuntimePlatform.MetroPlayerX86: + case RuntimePlatform.MetroPlayerX64: + case RuntimePlatform.MetroPlayerARM: + return false; case RuntimePlatform.WP8Player: case RuntimePlatform.BB10Player: case RuntimePlatform.TizenPlayer: + case RuntimePlatform.PSM: return true; - case RuntimePlatform.MetroPlayerX86: - case RuntimePlatform.MetroPlayerX64: - case RuntimePlatform.MetroPlayerARM: + case RuntimePlatform.PSP2: + case RuntimePlatform.PS4: + IL_35: + switch (runtimePlatform) + { + case RuntimePlatform.IPhonePlayer: + case RuntimePlatform.Android: + return true; + } return false; } - return false; + goto IL_35; } } public extern string text diff --git a/UnityEngine/UnityEngine/TrackedReference.cs b/UnityEngine/UnityEngine/TrackedReference.cs index a06b02d6..ab208bd9 100644 --- a/UnityEngine/UnityEngine/TrackedReference.cs +++ b/UnityEngine/UnityEngine/TrackedReference.cs @@ -5,7 +5,6 @@ namespace UnityEngine [StructLayout(LayoutKind.Sequential)] public class TrackedReference { - [NotRenamed] internal IntPtr m_Ptr; protected TrackedReference() { diff --git a/UnityEngine/UnityEngine/TransitionType.cs b/UnityEngine/UnityEngine/TransitionType.cs new file mode 100644 index 00000000..d3e625f0 --- /dev/null +++ b/UnityEngine/UnityEngine/TransitionType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngine +{ + internal enum TransitionType + { + Normal = 1, + Entry, + Exit = 4 + } +} diff --git a/UnityEngine/UnityEngine/Tree.cs b/UnityEngine/UnityEngine/Tree.cs index 1cff91f5..80576f34 100644 --- a/UnityEngine/UnityEngine/Tree.cs +++ b/UnityEngine/UnityEngine/Tree.cs @@ -13,5 +13,11 @@ public extern ScriptableObject data [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern bool hasSpeedTreeWind + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } } } diff --git a/UnityEngine/UnityEngine/TreeInstance.cs b/UnityEngine/UnityEngine/TreeInstance.cs index 50a6ea70..a0b0e05c 100644 --- a/UnityEngine/UnityEngine/TreeInstance.cs +++ b/UnityEngine/UnityEngine/TreeInstance.cs @@ -3,89 +3,13 @@ namespace UnityEngine { public struct TreeInstance { - private Vector3 m_Position; - private float m_WidthScale; - private float m_HeightScale; - private Color32 m_Color; - private Color32 m_LightmapColor; - private int m_Index; - private float m_TemporaryDistance; - public Vector3 position - { - get - { - return this.m_Position; - } - set - { - this.m_Position = value; - } - } - public float widthScale - { - get - { - return this.m_WidthScale; - } - set - { - this.m_WidthScale = value; - } - } - public float heightScale - { - get - { - return this.m_HeightScale; - } - set - { - this.m_HeightScale = value; - } - } - public Color color - { - get - { - return this.m_Color; - } - set - { - this.m_Color = value; - } - } - public Color lightmapColor - { - get - { - return this.m_LightmapColor; - } - set - { - this.m_LightmapColor = value; - } - } - public int prototypeIndex - { - get - { - return this.m_Index; - } - set - { - this.m_Index = value; - } - } - internal float temporaryDistance - { - get - { - return this.m_TemporaryDistance; - } - set - { - this.m_TemporaryDistance = value; - } - } + public Vector3 position; + public float widthScale; + public float heightScale; + public float rotation; + public Color32 color; + public Color32 lightmapColor; + public int prototypeIndex; + internal float temporaryDistance; } } diff --git a/UnityEngine/UnityEngine/UnityAPICompatibilityVersionAttribute.cs b/UnityEngine/UnityEngine/UnityAPICompatibilityVersionAttribute.cs new file mode 100644 index 00000000..210d8196 --- /dev/null +++ b/UnityEngine/UnityEngine/UnityAPICompatibilityVersionAttribute.cs @@ -0,0 +1,20 @@ +using System; +namespace UnityEngine +{ + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public class UnityAPICompatibilityVersionAttribute : Attribute + { + private string _version; + public string version + { + get + { + return this._version; + } + } + public UnityAPICompatibilityVersionAttribute(string version) + { + this._version = version; + } + } +} diff --git a/UnityEngine/UnityEngine/UnityEventQueueSystem.cs b/UnityEngine/UnityEngine/UnityEventQueueSystem.cs new file mode 100644 index 00000000..847cb7b7 --- /dev/null +++ b/UnityEngine/UnityEngine/UnityEventQueueSystem.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.CompilerServices; +namespace UnityEngine +{ + public sealed class UnityEventQueueSystem + { + public static string GenerateEventIdForPayload(string eventPayloadName) + { + byte[] array = Guid.NewGuid().ToByteArray(); + return string.Format("REGISTER_EVENT_ID(0x{0:X2}{1:X2}{2:X2}{3:X2}{4:X2}{5:X2}{6:X2}{7:X2}ULL,0x{8:X2}{9:X2}{10:X2}{11:X2}{12:X2}{13:X2}{14:X2}{15:X2}ULL,{16})", new object[] + { + array[0], + array[1], + array[2], + array[3], + array[4], + array[5], + array[6], + array[7], + array[8], + array[9], + array[10], + array[11], + array[12], + array[13], + array[14], + array[15], + eventPayloadName + }); + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern IntPtr GetGlobalEventQueue(); + } +} diff --git a/UnityEngine/UnityEngine/Vector3.cs b/UnityEngine/UnityEngine/Vector3.cs index 82f56efe..4486893c 100644 --- a/UnityEngine/UnityEngine/Vector3.cs +++ b/UnityEngine/UnityEngine/Vector3.cs @@ -308,7 +308,7 @@ public static float Dot(Vector3 lhs, Vector3 rhs) public static Vector3 Project(Vector3 vector, Vector3 onNormal) { float num = Vector3.Dot(onNormal, onNormal); - if (num < 1.401298E-45f) + if (num < Mathf.Epsilon) { return Vector3.zero; } diff --git a/UnityEngine/UnityEngine/WWW.cs b/UnityEngine/UnityEngine/WWW.cs index 622ef0e5..6fc13d1c 100644 --- a/UnityEngine/UnityEngine/WWW.cs +++ b/UnityEngine/UnityEngine/WWW.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using System.Text; @@ -9,6 +10,7 @@ namespace UnityEngine { public sealed class WWW : IDisposable { + internal IntPtr m_Ptr; private static readonly char[] forbiddenCharacters = new char[] { '\0', @@ -74,7 +76,6 @@ public sealed class WWW : IDisposable "Via", "X-Unity-Version" }; - internal IntPtr m_Ptr; public Dictionary responseHeaders { get @@ -100,7 +101,8 @@ public string text { throw new UnityException("WWW is not ready downloading yet"); } - return this.GetTextEncoder().GetString(this.bytes, 0, this.bytes.Length); + byte[] bytes = this.bytes; + return this.GetTextEncoder().GetString(bytes, 0, bytes.Length); } } internal static Encoding DefaultEncoding @@ -187,12 +189,13 @@ public extern int bytesDownloaded [MethodImpl(MethodImplOptions.InternalCall)] get; } - [Obsolete(".oggVorbis accessor is deprecated, use .audioClip or GetAudioClip() instead.")] - public extern AudioClip oggVorbis + [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Property WWW.oggVorbis has been deprecated. Use WWW.audioClip instead (UnityUpgradable).", true)] + public AudioClip oggVorbis { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return null; + } } public extern string url { @@ -232,15 +235,10 @@ public WWW(string url, byte[] postData) { this.InitWWW(url, postData, null); } - [Obsolete("This overload is deprecated. Use the one with Dictionary argument.")] + [Obsolete("This overload is deprecated. Use the one with Dictionary argument.", true)] public WWW(string url, byte[] postData, Hashtable headers) { - string[] array = WWW.FlattenedHeadersFrom(headers); - if (this.enforceWebSecurityRestrictions()) - { - WWW.CheckSecurityOnHeaders(array); - } - this.InitWWW(url, postData, array); + Debug.LogError("This overload is deprecated. Use the one with Dictionary argument."); } public WWW(string url, byte[] postData, Dictionary headers) { @@ -251,107 +249,9 @@ public WWW(string url, byte[] postData, Dictionary headers) } this.InitWWW(url, postData, array); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - internal extern WWW(string url, int version, uint crc); - private static void CheckSecurityOnHeaders(string[] headers) + internal WWW(string url, Hash128 hash, uint crc) { - bool flag = Application.GetBuildUnityVersion() >= Application.GetNumericUnityVersion("4.3.0b1"); - for (int i = 0; i < headers.Length; i += 2) - { - string[] array = WWW.forbiddenHeaderKeys; - for (int j = 0; j < array.Length; j++) - { - string b = array[j]; - if (string.Equals(headers[i], b, StringComparison.CurrentCultureIgnoreCase)) - { - if (flag) - { - throw new ArgumentException("Cannot overwrite header: " + headers[i]); - } - Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); - } - } - if (headers[i].StartsWith("Sec-") || headers[i].StartsWith("Proxy-")) - { - if (flag) - { - throw new ArgumentException("Cannot overwrite header: " + headers[i]); - } - Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); - } - if (headers[i].IndexOfAny(WWW.forbiddenCharacters) > -1 || headers[i].IndexOfAny(WWW.forbiddenCharactersForNames) > -1 || headers[i + 1].IndexOfAny(WWW.forbiddenCharacters) > -1) - { - if (flag) - { - throw new ArgumentException("Cannot include control characters in a HTTP header, either as key or value."); - } - Debug.LogError("Illegal control characters in header, this will fail in 4.3 and above"); - } - } - } - private static string[] FlattenedHeadersFrom(Hashtable headers) - { - if (headers == null) - { - return null; - } - string[] array = new string[headers.Count * 2]; - int num = 0; - foreach (DictionaryEntry dictionaryEntry in headers) - { - array[num++] = dictionaryEntry.Key.ToString(); - array[num++] = dictionaryEntry.Value.ToString(); - } - return array; - } - private static string[] FlattenedHeadersFrom(Dictionary headers) - { - if (headers == null) - { - return null; - } - string[] array = new string[headers.Count * 2]; - int num = 0; - foreach (KeyValuePair current in headers) - { - array[num++] = current.Key.ToString(); - array[num++] = current.Value.ToString(); - } - return array; - } - internal static Dictionary ParseHTTPHeaderString(string input) - { - if (input == null) - { - throw new ArgumentException("input was null to ParseHTTPHeaderString"); - } - Dictionary dictionary = new Dictionary(); - StringReader stringReader = new StringReader(input); - int num = 0; - while (true) - { - string text = stringReader.ReadLine(); - if (text == null) - { - break; - } - if (num++ == 0 && text.StartsWith("HTTP")) - { - dictionary["STATUS"] = text; - } - else - { - int num2 = text.IndexOf(": "); - if (num2 != -1) - { - string key = text.Substring(0, num2).ToUpper(); - string value = text.Substring(num2 + 2); - dictionary[key] = value; - } - } - } - return dictionary; + WWW.INTERNAL_CALL_WWW(this, url, ref hash, crc); } public void Dispose() { @@ -376,7 +276,7 @@ public static string EscapeURL(string s) Encoding uTF = Encoding.UTF8; return WWW.EscapeURL(s, uTF); } - public static string EscapeURL(string s, [DefaultValue("System.Text.Encoding.UTF8")] Encoding e) + public static string EscapeURL(string s, [UnityEngine.Internal.DefaultValue("System.Text.Encoding.UTF8")] Encoding e) { if (s == null) { @@ -398,7 +298,7 @@ public static string UnEscapeURL(string s) Encoding uTF = Encoding.UTF8; return WWW.UnEscapeURL(s, uTF); } - public static string UnEscapeURL(string s, [DefaultValue("System.Text.Encoding.UTF8")] Encoding e) + public static string UnEscapeURL(string s, [UnityEngine.Internal.DefaultValue("System.Text.Encoding.UTF8")] Encoding e) { if (s == null) { @@ -485,18 +385,117 @@ public static Texture2D GetTextureFromURL(string url) { return new WWW(url).texture; } + [Obsolete("LoadUnityWeb is no longer supported. Please use javascript to reload the web player on a different url instead", true)] + public void LoadUnityWeb() + { + } [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] - public extern void LoadUnityWeb(); + private static extern void INTERNAL_CALL_WWW(WWW self, string url, ref Hash128 hash, uint crc); [ExcludeFromDocs] public static WWW LoadFromCacheOrDownload(string url, int version) { uint crc = 0u; return WWW.LoadFromCacheOrDownload(url, version, crc); } - public static WWW LoadFromCacheOrDownload(string url, int version, [DefaultValue("0")] uint crc) + public static WWW LoadFromCacheOrDownload(string url, int version, [UnityEngine.Internal.DefaultValue("0")] uint crc) + { + Hash128 hash = new Hash128(0u, 0u, 0u, (uint)version); + return WWW.LoadFromCacheOrDownload(url, hash, crc); + } + [ExcludeFromDocs] + public static WWW LoadFromCacheOrDownload(string url, Hash128 hash) + { + uint crc = 0u; + return WWW.LoadFromCacheOrDownload(url, hash, crc); + } + public static WWW LoadFromCacheOrDownload(string url, Hash128 hash, [UnityEngine.Internal.DefaultValue("0")] uint crc) + { + return new WWW(url, hash, crc); + } + private static void CheckSecurityOnHeaders(string[] headers) { - return new WWW(url, version, crc); + bool flag = Application.GetBuildUnityVersion() >= Application.GetNumericUnityVersion("4.3.0b1"); + for (int i = 0; i < headers.Length; i += 2) + { + string[] array = WWW.forbiddenHeaderKeys; + for (int j = 0; j < array.Length; j++) + { + string b = array[j]; + if (string.Equals(headers[i], b, StringComparison.CurrentCultureIgnoreCase)) + { + if (flag) + { + throw new ArgumentException("Cannot overwrite header: " + headers[i]); + } + Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); + } + } + if (headers[i].StartsWith("Sec-") || headers[i].StartsWith("Proxy-")) + { + if (flag) + { + throw new ArgumentException("Cannot overwrite header: " + headers[i]); + } + Debug.LogError("Illegal header overwrite, this will fail in 4.3 and above: " + headers[i]); + } + if (headers[i].IndexOfAny(WWW.forbiddenCharacters) > -1 || headers[i].IndexOfAny(WWW.forbiddenCharactersForNames) > -1 || headers[i + 1].IndexOfAny(WWW.forbiddenCharacters) > -1) + { + if (flag) + { + throw new ArgumentException("Cannot include control characters in a HTTP header, either as key or value."); + } + Debug.LogError("Illegal control characters in header, this will fail in 4.3 and above"); + } + } + } + private static string[] FlattenedHeadersFrom(Dictionary headers) + { + if (headers == null) + { + return null; + } + string[] array = new string[headers.Count * 2]; + int num = 0; + foreach (KeyValuePair current in headers) + { + array[num++] = current.Key.ToString(); + array[num++] = current.Value.ToString(); + } + return array; + } + internal static Dictionary ParseHTTPHeaderString(string input) + { + if (input == null) + { + throw new ArgumentException("input was null to ParseHTTPHeaderString"); + } + Dictionary dictionary = new Dictionary(); + StringReader stringReader = new StringReader(input); + int num = 0; + while (true) + { + string text = stringReader.ReadLine(); + if (text == null) + { + break; + } + if (num++ == 0 && text.StartsWith("HTTP")) + { + dictionary["STATUS"] = text; + } + else + { + int num2 = text.IndexOf(": "); + if (num2 != -1) + { + string key = text.Substring(0, num2).ToUpper(); + string value = text.Substring(num2 + 2); + dictionary[key] = value; + } + } + } + return dictionary; } } } diff --git a/UnityEngine/UnityEngine/WWWForm.cs b/UnityEngine/UnityEngine/WWWForm.cs index 1e9ddb8f..46d2707b 100644 --- a/UnityEngine/UnityEngine/WWWForm.cs +++ b/UnityEngine/UnityEngine/WWWForm.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; @@ -14,20 +13,20 @@ public sealed class WWWForm private List types; private byte[] boundary; private bool containsFiles; - public Hashtable headers + public Dictionary headers { get { - Hashtable hashtable = new Hashtable(); + Dictionary dictionary = new Dictionary(); if (this.containsFiles) { - hashtable["Content-Type"] = "multipart/form-data; boundary=\"" + Encoding.UTF8.GetString(this.boundary) + "\""; + dictionary["Content-Type"] = "multipart/form-data; boundary=\"" + Encoding.UTF8.GetString(this.boundary, 0, this.boundary.Length) + "\""; } else { - hashtable["Content-Type"] = "application/x-www-form-urlencoded"; + dictionary["Content-Type"] = "application/x-www-form-urlencoded"; } - return hashtable; + return dictionary; } } public byte[] data diff --git a/UnityEngine/UnityEngine/WebCamTexture.cs b/UnityEngine/UnityEngine/WebCamTexture.cs index 573561ca..76127c29 100644 --- a/UnityEngine/UnityEngine/WebCamTexture.cs +++ b/UnityEngine/UnityEngine/WebCamTexture.cs @@ -47,6 +47,7 @@ public extern int requestedHeight [MethodImpl(MethodImplOptions.InternalCall)] set; } + [Obsolete("since Unity 5.0 iOS WebCamTexture always goes through CVTextureCache and is read to memory on-demand")] public extern bool isReadable { [WrapperlessIcall] @@ -125,7 +126,7 @@ public void Stop() [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] private static extern void INTERNAL_CALL_Stop(WebCamTexture self); - [WrapperlessIcall] + [Obsolete("since Unity 5.0 iOS WebCamTexture always goes through CVTextureCache and is read to memory on-demand"), WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] public extern void MarkNonReadable(); [WrapperlessIcall] diff --git a/UnityEngine/UnityEngine/WheelCollider.cs b/UnityEngine/UnityEngine/WheelCollider.cs index 181530ab..75b16ee3 100644 --- a/UnityEngine/UnityEngine/WheelCollider.cs +++ b/UnityEngine/UnityEngine/WheelCollider.cs @@ -48,6 +48,15 @@ public JointSpring suspensionSpring this.INTERNAL_set_suspensionSpring(ref value); } } + public extern float forceAppPointDistance + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public extern float mass { [WrapperlessIcall] @@ -57,6 +66,15 @@ public extern float mass [MethodImpl(MethodImplOptions.InternalCall)] set; } + public extern float wheelDampingRate + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } public WheelFrictionCurve forwardFriction { get @@ -116,6 +134,12 @@ public extern bool isGrounded [MethodImpl(MethodImplOptions.InternalCall)] get; } + public extern float sprungMass + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } public extern float rpm { [WrapperlessIcall] @@ -148,6 +172,12 @@ public extern float rpm private extern void INTERNAL_set_sidewaysFriction(ref WheelFrictionCurve value); [WrapperlessIcall] [MethodImpl(MethodImplOptions.InternalCall)] + public extern void ConfigureVehicleSubsteps(float speedThreshold, int stepsBelowThreshold, int stepsAboveThreshold); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] public extern bool GetGroundHit(out WheelHit hit); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public extern void GetWorldPose(out Vector3 pos, out Quaternion quat); } } diff --git a/UnityEngine/UnityEngine/WindZone.cs b/UnityEngine/UnityEngine/WindZone.cs index a6f6b47e..b4efb6cc 100644 --- a/UnityEngine/UnityEngine/WindZone.cs +++ b/UnityEngine/UnityEngine/WindZone.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; namespace UnityEngine { - internal sealed class WindZone : Component + public sealed class WindZone : Component { public extern WindZoneMode mode { diff --git a/UnityEngine/UnityEngine/WindZoneMode.cs b/UnityEngine/UnityEngine/WindZoneMode.cs index 2eb8182d..263cf79a 100644 --- a/UnityEngine/UnityEngine/WindZoneMode.cs +++ b/UnityEngine/UnityEngine/WindZoneMode.cs @@ -1,7 +1,7 @@ using System; namespace UnityEngine { - internal enum WindZoneMode + public enum WindZoneMode { Directional, Spherical diff --git a/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs b/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs index 67b84410..3ca00cd0 100644 --- a/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs +++ b/UnityEngine/UnityEngine/iOSActivityIndicatorStyle.cs @@ -1,11 +1,9 @@ using System; namespace UnityEngine { + [Obsolete("iOSActivityIndicatorStyle enumeration is deprecated (UnityUpgradable). Please use iOS.ActivityIndicatorStyle instead.", true)] public enum iOSActivityIndicatorStyle { - DontShow = -1, - WhiteLarge, - White, - Gray + } } diff --git a/UnityEngine/UnityEngine/iPhone.cs b/UnityEngine/UnityEngine/iPhone.cs index e6c2ae4f..36e40bec 100644 --- a/UnityEngine/UnityEngine/iPhone.cs +++ b/UnityEngine/UnityEngine/iPhone.cs @@ -1,113 +1,8 @@ using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace UnityEngine { + [Obsolete("iPhone class is deprecated (UnityUpgradable). Please use iOS.Device instead.", true)] public sealed class iPhone { - public sealed class NSError - { - private IntPtr _nativeError; - public int code - { - get - { - return iPhone.NSError.UnityNSError_Code(this._nativeError); - } - } - public string description - { - get - { - return Marshal.PtrToStringAnsi(iPhone.NSError.UnityNSError_Description(this._nativeError)); - } - } - public string reason - { - get - { - return Marshal.PtrToStringAnsi(iPhone.NSError.UnityNSError_Reason(this._nativeError)); - } - } - private NSError(IntPtr nativeError) - { - this._nativeError = nativeError; - iPhone.UnityNSObject_RetainObject(this._nativeError); - } - [DllImport("__Internal")] - private static extern int UnityNSError_Code(IntPtr errorObj); - [DllImport("__Internal")] - private static extern IntPtr UnityNSError_Description(IntPtr errorObj); - [DllImport("__Internal")] - private static extern IntPtr UnityNSError_Reason(IntPtr errorObj); - ~NSError() - { - iPhone.UnityNSObject_ReleaseObject(this._nativeError); - } - public static iPhone.NSError CreateNSError(IntPtr nativeError) - { - return (!(nativeError == IntPtr.Zero)) ? new iPhone.NSError(nativeError) : null; - } - } - public sealed class NSNotification - { - private IntPtr _nativeNotification; - public string name - { - get - { - return Marshal.PtrToStringAnsi(iPhone.NSNotification.UnityNSNotification_Name(this._nativeNotification)); - } - } - private NSNotification(IntPtr nativeNotification) - { - this._nativeNotification = nativeNotification; - iPhone.UnityNSObject_RetainObject(this._nativeNotification); - } - [DllImport("__Internal")] - private static extern IntPtr UnityNSNotification_Name(IntPtr notificationObj); - ~NSNotification() - { - iPhone.UnityNSObject_ReleaseObject(this._nativeNotification); - } - public static iPhone.NSNotification CreateNSNotification(IntPtr nativeNotification) - { - return (!(nativeNotification == IntPtr.Zero)) ? new iPhone.NSNotification(nativeNotification) : null; - } - } - public static extern iPhoneGeneration generation - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string vendorIdentifier - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern string advertisingIdentifier - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern bool advertisingTrackingEnabled - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [DllImport("__Internal")] - internal static extern void UnityNSObject_RetainObject(IntPtr obj); - [DllImport("__Internal")] - internal static extern void UnityNSObject_ReleaseObject(IntPtr obj); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void SetNoBackupFlag(string path); - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void ResetNoBackupFlag(string path); } } diff --git a/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs b/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs index ccad396c..3fa0b0a1 100644 --- a/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs +++ b/UnityEngine/UnityEngine/iPhoneAccelerationEvent.cs @@ -1,31 +1,15 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneAccelerationEvent struct is deprecated. Please use AccelerationEvent instead.")] + [Obsolete("iPhoneAccelerationEvent struct is deprecated (UnityUpgradable). Please use AccelerationEvent instead.", true)] public struct iPhoneAccelerationEvent { - private Vector3 m_Acceleration; - private float m_TimeDelta; - public Vector3 acceleration - { - get - { - return this.m_Acceleration; - } - } - public float deltaTime - { - get - { - return this.m_TimeDelta; - } - } - [Obsolete("timeDelta property is deprecated. Please use iPhoneAccelerationEvent.deltaTime instead.")] + [Obsolete("timeDelta property is deprecated (UnityUpgradable). Please use AccelerationEvent.deltaTime instead.", true)] public float timeDelta { get { - return this.m_TimeDelta; + return 0f; } } } diff --git a/UnityEngine/UnityEngine/iPhoneGeneration.cs b/UnityEngine/UnityEngine/iPhoneGeneration.cs index a78ac728..f60c80c0 100644 --- a/UnityEngine/UnityEngine/iPhoneGeneration.cs +++ b/UnityEngine/UnityEngine/iPhoneGeneration.cs @@ -1,35 +1,9 @@ using System; namespace UnityEngine { + [Obsolete("iPhoneGeneration enumeration is deprecated (UnityUpgradable). Please use iOS.DeviceGeneration instead.", true)] public enum iPhoneGeneration { - Unknown, - iPhone, - iPhone3G, - iPhone3GS, - iPodTouch1Gen, - iPodTouch2Gen, - iPodTouch3Gen, - iPad1Gen, - iPhone4, - iPodTouch4Gen, - iPad2Gen, - iPhone4S, - iPad3Gen, - iPhone5, - iPodTouch5Gen, - iPadMini1Gen, - iPad4Gen, - iPhone5C, - iPhone5S, - iPad5Gen, - iPadMini2Gen, - iPhone6, - iPhone6Plus, - iPadMini3Gen, - iPadAir2, - iPhoneUnknown = 10001, - iPadUnknown, - iPodTouchUnknown + } } diff --git a/UnityEngine/UnityEngine/iPhoneInput.cs b/UnityEngine/UnityEngine/iPhoneInput.cs index 1f80738c..6351a64a 100644 --- a/UnityEngine/UnityEngine/iPhoneInput.cs +++ b/UnityEngine/UnityEngine/iPhoneInput.cs @@ -1,87 +1,24 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { + [Obsolete("iPhoneInput class is deprecated (UnityUpgradable). Please use Input instead", true)] public sealed class iPhoneInput { - [Obsolete("accelerationEvents property is deprecated. Please use Input.accelerationEvents instead.")] - public static iPhoneAccelerationEvent[] accelerationEvents + [Obsolete("orientation property is deprecated (UnityUpgradable). Please use Input.deviceOrientation instead.", true)] + public static iPhoneOrientation orientation { get { - int accelerationEventCount = iPhoneInput.accelerationEventCount; - iPhoneAccelerationEvent[] array = new iPhoneAccelerationEvent[accelerationEventCount]; - for (int i = 0; i < accelerationEventCount; i++) - { - array[i] = iPhoneInput.GetAccelerationEvent(i); - } - return array; + return (iPhoneOrientation)0; } } - [Obsolete("touches property is deprecated. Please use Input.touches instead.")] - public static iPhoneTouch[] touches + [Obsolete("lastLocation property is deprecated. Please use Input.location.lastData instead.", true)] + private static LocationInfo lastLocation { get { - int touchCount = iPhoneInput.touchCount; - iPhoneTouch[] array = new iPhoneTouch[touchCount]; - for (int i = 0; i < touchCount; i++) - { - array[i] = iPhoneInput.GetTouch(i); - } - return array; + return default(LocationInfo); } } - [Obsolete("touchCount property is deprecated. Please use Input.touchCount instead.")] - public static extern int touchCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [Obsolete("multiTouchEnabled property is deprecated. Please use Input.multiTouchEnabled instead.")] - public static extern bool multiTouchEnabled - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - [Obsolete("accelerationEventCount property is deprecated. Please use Input.accelerationEventCount instead.")] - public static extern int accelerationEventCount - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [Obsolete("acceleration property is deprecated. Please use Input.acceleration instead.")] - public static extern Vector3 acceleration - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [Obsolete("orientation property is deprecated. Please use Input.deviceOrientation instead.")] - public static extern iPhoneOrientation orientation - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [Obsolete("lastLocation property is deprecated. Please use Input.location.lastData instead.")] - public static extern LocationInfo lastLocation - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - [Obsolete("GetTouch method is deprecated. Please use Input.GetTouch instead."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern iPhoneTouch GetTouch(int index); - [Obsolete("GetAccelerationEvent method is deprecated. Please use Input.GetAccelerationEvent instead."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern iPhoneAccelerationEvent GetAccelerationEvent(int index); } } diff --git a/UnityEngine/UnityEngine/iPhoneKeyboard.cs b/UnityEngine/UnityEngine/iPhoneKeyboard.cs index 22277e97..d4f5f22c 100644 --- a/UnityEngine/UnityEngine/iPhoneKeyboard.cs +++ b/UnityEngine/UnityEngine/iPhoneKeyboard.cs @@ -1,134 +1,8 @@ using System; -using System.Runtime.CompilerServices; -using UnityEngine.Internal; namespace UnityEngine { - [Obsolete("iPhoneKeyboard class is deprecated. Please use TouchScreenKeyboard instead.")] + [Obsolete("iPhoneKeyboard class is deprecated (UnityUpgradable). Please use TouchScreenKeyboard instead.", true)] public sealed class iPhoneKeyboard { - private IntPtr keyboardWrapper; - public extern string text - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public static extern bool hideInput - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool active - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; - } - public extern bool done - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern Rect area - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public static extern bool visible - { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - } - public iPhoneKeyboard(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder) - { - this.iPhoneKeyboard_InternalConstructorHelper(new iPhoneKeyboard_InternalConstructorHelperArguments - { - text = text, - keyboardType = Convert.ToUInt32(keyboardType), - autocorrection = Convert.ToUInt32(autocorrection), - multiline = Convert.ToUInt32(multiline), - secure = Convert.ToUInt32(secure), - alert = Convert.ToUInt32(alert), - textPlaceholder = textPlaceholder - }); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void Destroy(); - ~iPhoneKeyboard() - { - this.Destroy(); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private extern void iPhoneKeyboard_InternalConstructorHelper(iPhoneKeyboard_InternalConstructorHelperArguments arguments); - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert) - { - string empty = string.Empty; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure) - { - string empty = string.Empty; - bool alert = false; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection, bool multiline) - { - string empty = string.Empty; - bool alert = false; - bool secure = false; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType, bool autocorrection) - { - string empty = string.Empty; - bool alert = false; - bool secure = false; - bool multiline = false; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text, iPhoneKeyboardType keyboardType) - { - string empty = string.Empty; - bool alert = false; - bool secure = false; - bool multiline = false; - bool autocorrection = true; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - [ExcludeFromDocs] - public static iPhoneKeyboard Open(string text) - { - string empty = string.Empty; - bool alert = false; - bool secure = false; - bool multiline = false; - bool autocorrection = true; - iPhoneKeyboardType keyboardType = iPhoneKeyboardType.Default; - return iPhoneKeyboard.Open(text, keyboardType, autocorrection, multiline, secure, alert, empty); - } - public static iPhoneKeyboard Open(string text, [DefaultValue("iPhoneKeyboardType.Default")] iPhoneKeyboardType keyboardType, [DefaultValue("true")] bool autocorrection, [DefaultValue("false")] bool multiline, [DefaultValue("false")] bool secure, [DefaultValue("false")] bool alert, [DefaultValue("\"\"")] string textPlaceholder) - { - return new iPhoneKeyboard(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); - } } } diff --git a/UnityEngine/UnityEngine/iPhoneKeyboardType.cs b/UnityEngine/UnityEngine/iPhoneKeyboardType.cs index cad3ab13..e2d50928 100644 --- a/UnityEngine/UnityEngine/iPhoneKeyboardType.cs +++ b/UnityEngine/UnityEngine/iPhoneKeyboardType.cs @@ -1,16 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneKeyboardType enumeration is deprecated. Please use TouchScreenKeyboardType instead.")] + [Obsolete("iPhoneKeyboardType enumeration is deprecated (UnityUpgradable). Please use TouchScreenKeyboardType instead.", true)] public enum iPhoneKeyboardType { - Default, - ASCIICapable, - NumbersAndPunctuation, - URL, - NumberPad, - PhonePad, - NamePhonePad, - EmailAddress + } } diff --git a/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs b/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs deleted file mode 100644 index fb5dda9a..00000000 --- a/UnityEngine/UnityEngine/iPhoneKeyboard_InternalConstructorHelperArguments.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -namespace UnityEngine -{ - internal struct iPhoneKeyboard_InternalConstructorHelperArguments - { - public string text; - public string textPlaceholder; - public uint keyboardType; - public uint autocorrection; - public uint multiline; - public uint secure; - public uint alert; - } -} diff --git a/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs b/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs index 7b4dc654..9e5761c9 100644 --- a/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs +++ b/UnityEngine/UnityEngine/iPhoneMovieControlMode.cs @@ -1,13 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneMovieControlMode enumeration is deprecated. Please use FullScreenMovieControlMode instead.")] + [Obsolete("iPhoneMovieControlMode enumeration is deprecated (UnityUpgradable). Please use FullScreenMovieControlMode instead.", true)] public enum iPhoneMovieControlMode { - Full, - Minimal, - CancelOnTouch, - Hidden, - VolumeOnly = 1 + } } diff --git a/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs b/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs index 61cc6397..4dd515ee 100644 --- a/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs +++ b/UnityEngine/UnityEngine/iPhoneMovieScalingMode.cs @@ -1,12 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneMovieScalingMode enumeration is deprecated. Please use FullScreenMovieScalingMode instead.")] + [Obsolete("iPhoneMovieScalingMode enumeration is deprecated (UnityUpgradable). Please use FullScreenMovieScalingMode instead.", true)] public enum iPhoneMovieScalingMode { - None, - AspectFit, - AspectFill, - Fill + } } diff --git a/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs b/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs index e0045aa3..90354a07 100644 --- a/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs +++ b/UnityEngine/UnityEngine/iPhoneNetworkReachability.cs @@ -1,11 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneNetworkReachability enumeration is deprecated. Please use NetworkReachability instead.")] + [Obsolete("iPhoneNetworkReachability enumeration is deprecated (UnityUpgradable). Please use NetworkReachability instead.", true)] public enum iPhoneNetworkReachability { - NotReachable, - ReachableViaCarrierDataNetwork, - ReachableViaWiFiNetwork + } } diff --git a/UnityEngine/UnityEngine/iPhoneOrientation.cs b/UnityEngine/UnityEngine/iPhoneOrientation.cs index f52b2015..c60cc972 100644 --- a/UnityEngine/UnityEngine/iPhoneOrientation.cs +++ b/UnityEngine/UnityEngine/iPhoneOrientation.cs @@ -1,15 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneOrientation enumeration is deprecated. Please use DeviceOrientation instead.")] + [Obsolete("iPhoneOrientation enumeration is deprecated (UnityUpgradable). Please use DeviceOrientation instead.", true)] public enum iPhoneOrientation { - Unknown, - Portrait, - PortraitUpsideDown, - LandscapeLeft, - LandscapeRight, - FaceUp, - FaceDown + } } diff --git a/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs b/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs index f7fdc66a..4f328b69 100644 --- a/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs +++ b/UnityEngine/UnityEngine/iPhoneScreenOrientation.cs @@ -1,14 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneScreenOrientation enumeration is deprecated. Please use ScreenOrientation instead.")] + [Obsolete("iPhoneScreenOrientation enumeration is deprecated (UnityUpgradable). Please use ScreenOrientation instead.", true)] public enum iPhoneScreenOrientation { - Unknown, - Portrait, - PortraitUpsideDown, - LandscapeLeft, - LandscapeRight, - Landscape = 3 + } } diff --git a/UnityEngine/UnityEngine/iPhoneSettings.cs b/UnityEngine/UnityEngine/iPhoneSettings.cs index f0deb31e..efd41be3 100644 --- a/UnityEngine/UnityEngine/iPhoneSettings.cs +++ b/UnityEngine/UnityEngine/iPhoneSettings.cs @@ -1,117 +1,123 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { public sealed class iPhoneSettings { - [Obsolete("screenOrientation property is deprecated. Please use Screen.orientation instead.")] - public static extern iPhoneScreenOrientation screenOrientation + [Obsolete("screenOrientation property is deprecated (UnityUpgradable). Please use Screen.orientation instead.", true)] + public static iPhoneScreenOrientation screenOrientation { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return (iPhoneScreenOrientation)0; + } } - [Obsolete("verticalOrientation property is deprecated. Please use Screen.orientation instead.")] - public static extern bool verticalOrientation + [Obsolete("verticalOrientation property is deprecated. Please use Screen.orientation == ScreenOrientation.Portrait instead.")] + public static bool verticalOrientation { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return false; + } } - [Obsolete("screenCanDarken property is deprecated. Please use Screen.sleepTimeout instead.")] - public static extern bool screenCanDarken + [Obsolete("screenCanDarken property is deprecated. Please use (Screen.sleepTimeout != SleepTimeout.NeverSleep) instead.")] + public static bool screenCanDarken { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - set; + get + { + return false; + } } - [Obsolete("uniqueIdentifier property is deprecated. Please use SystemInfo.deviceUniqueIdentifier instead.")] - public static extern string uniqueIdentifier + [Obsolete("uniqueIdentifier property is deprecated (UnityUpgradable). Please use SystemInfo.deviceUniqueIdentifier instead.", true)] + public static string uniqueIdentifier { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return string.Empty; + } } - [Obsolete("name property is deprecated. Please use SystemInfo.deviceName instead.")] - public static extern string name + [Obsolete("name property is deprecated (UnityUpgradable). Please use SystemInfo.deviceName instead.", true)] + public static string name { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return string.Empty; + } } - [Obsolete("model property is deprecated. Please use SystemInfo.deviceModel instead.")] - public static extern string model + [Obsolete("model property is deprecated (UnityUpgradable). Please use SystemInfo.deviceModel instead.", true)] + public static string model { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return string.Empty; + } } - [Obsolete("systemName property is deprecated. Please use SystemInfo.operatingSystem instead.")] - public static extern string systemName + [Obsolete("systemName property is deprecated (UnityUpgradable). Please use SystemInfo.operatingSystem instead.", true)] + public static string systemName { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return string.Empty; + } } - [Obsolete("systemVersion property is deprecated. Please use SystemInfo.operatingSystem instead.")] - public static extern string systemVersion + [Obsolete("systemVersion property is deprecated (UnityUpgradable). Please use iOS.Device.systemVersion instead.", true)] + public static string systemVersion { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return string.Empty; + } } - [Obsolete("internetReachability property is deprecated. Please use Application.internetReachability instead.")] - public static extern iPhoneNetworkReachability internetReachability + [Obsolete("internetReachability property is deprecated (UnityUpgradable). Please use Application.internetReachability instead.", true)] + public static iPhoneNetworkReachability internetReachability { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return (iPhoneNetworkReachability)0; + } } - [Obsolete("generation property is deprecated. Please use iPhone.generation instead.")] - public static extern iPhoneGeneration generation + [Obsolete("generation property is deprecated (UnityUpgradable). Please use iPhone.generation instead.", true)] + public static iPhoneGeneration generation { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return (iPhoneGeneration)0; + } } [Obsolete("locationServiceStatus property is deprecated. Please use Input.location.status instead.")] - public static extern LocationServiceStatus locationServiceStatus + public static LocationServiceStatus locationServiceStatus { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return Input.location.status; + } } [Obsolete("locationServiceEnabledByUser property is deprecated. Please use Input.location.isEnabledByUser instead.")] - public static extern bool locationServiceEnabledByUser + public static bool locationServiceEnabledByUser { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return Input.location.isEnabledByUser; + } + } + [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead.")] + public static void StartLocationServiceUpdates(float desiredAccuracyInMeters, float updateDistanceInMeters) + { + Input.location.Start(desiredAccuracyInMeters, updateDistanceInMeters); } - [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void StartLocationServiceUpdates(float desiredAccuracyInMeters, float updateDistanceInMeters); [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead.")] public static void StartLocationServiceUpdates(float desiredAccuracyInMeters) { - iPhoneSettings.StartLocationServiceUpdates(desiredAccuracyInMeters, 10f); + Input.location.Start(desiredAccuracyInMeters); } [Obsolete("StartLocationServiceUpdates method is deprecated. Please use Input.location.Start instead.")] public static void StartLocationServiceUpdates() { - iPhoneSettings.StartLocationServiceUpdates(10f, 10f); + Input.location.Start(); + } + [Obsolete("StopLocationServiceUpdates method is deprecated. Please use Input.location.Stop instead.")] + public static void StopLocationServiceUpdates() + { + Input.location.Stop(); } - [Obsolete("StopLocationServiceUpdates method is deprecated. Please use Input.location.Stop instead."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void StopLocationServiceUpdates(); } } diff --git a/UnityEngine/UnityEngine/iPhoneTouch.cs b/UnityEngine/UnityEngine/iPhoneTouch.cs index aee4b19a..5291a9b5 100644 --- a/UnityEngine/UnityEngine/iPhoneTouch.cs +++ b/UnityEngine/UnityEngine/iPhoneTouch.cs @@ -1,71 +1,23 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneTouch struct is deprecated. Please use Touch instead.")] + [Obsolete("iPhoneTouch struct is deprecated (UnityUpgradable). Please use Touch instead.", true)] public struct iPhoneTouch { - private int m_FingerId; - private Vector2 m_Position; - private Vector2 m_PositionDelta; - private float m_TimeDelta; - private int m_TapCount; - private iPhoneTouchPhase m_Phase; - public int fingerId - { - get - { - return this.m_FingerId; - } - } - public Vector2 position - { - get - { - return this.m_Position; - } - } - public Vector2 deltaPosition - { - get - { - return this.m_PositionDelta; - } - } - public float deltaTime - { - get - { - return this.m_TimeDelta; - } - } - public int tapCount - { - get - { - return this.m_TapCount; - } - } - public iPhoneTouchPhase phase - { - get - { - return this.m_Phase; - } - } - [Obsolete("positionDelta property is deprecated. Please use iPhoneTouch.deltaPosition instead.")] + [Obsolete("positionDelta property is deprecated (UnityUpgradable). Please use Touch.deltaPosition instead.", true)] public Vector2 positionDelta { get { - return this.m_PositionDelta; + return default(Vector2); } } - [Obsolete("timeDelta property is deprecated. Please use iPhoneTouch.deltaTime instead.")] + [Obsolete("timeDelta property is deprecated (UnityUpgradable). Please use Touch.deltaTime instead.", true)] public float timeDelta { get { - return this.m_TimeDelta; + return 0f; } } } diff --git a/UnityEngine/UnityEngine/iPhoneTouchPhase.cs b/UnityEngine/UnityEngine/iPhoneTouchPhase.cs index f8b56d48..71a316a8 100644 --- a/UnityEngine/UnityEngine/iPhoneTouchPhase.cs +++ b/UnityEngine/UnityEngine/iPhoneTouchPhase.cs @@ -1,13 +1,9 @@ using System; namespace UnityEngine { - [Obsolete("iPhoneTouchPhase enumeration is deprecated. Please use TouchPhase instead.")] + [Obsolete("iPhoneTouchPhase enumeration is deprecated (UnityUpgradable). Please use TouchPhase instead.", true)] public enum iPhoneTouchPhase { - Began, - Moved, - Stationary, - Ended, - Canceled + } } diff --git a/UnityEngine/UnityEngine/iPhoneUtils.cs b/UnityEngine/UnityEngine/iPhoneUtils.cs index 3349540f..3dcea87e 100644 --- a/UnityEngine/UnityEngine/iPhoneUtils.cs +++ b/UnityEngine/UnityEngine/iPhoneUtils.cs @@ -1,71 +1,51 @@ using System; -using System.Runtime.CompilerServices; namespace UnityEngine { public sealed class iPhoneUtils { - [Obsolete("isApplicationGenuine property is deprecated. Please use Application.genuine instead.")] - public static extern bool isApplicationGenuine + [Obsolete("isApplicationGenuine property is deprecated (UnityUpgradable). Please use Application.genuine instead.", true)] + public static bool isApplicationGenuine { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return false; + } } - [Obsolete("isApplicationGenuineAvailable property is deprecated. Please use Application.genuineCheckAvailable instead.")] - public static extern bool isApplicationGenuineAvailable + [Obsolete("isApplicationGenuineAvailable property is deprecated (UnityUpgradable). Please use Application.genuineCheckAvailable instead.", true)] + public static bool isApplicationGenuineAvailable { - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - get; + get + { + return false; + } } - [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] - public static void PlayMovie(string path, Color bgColor, int controlMode, int scalingMode) - { - iPhoneUtils.INTERNAL_CALL_PlayMovie(path, ref bgColor, controlMode, scalingMode); - } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_PlayMovie(string path, ref Color bgColor, int controlMode, int scalingMode); - [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovie method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovie(string path, Color bgColor, iPhoneMovieControlMode controlMode, iPhoneMovieScalingMode scalingMode) { - iPhoneUtils.PlayMovie(path, bgColor, (int)controlMode, (int)scalingMode); } - [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovie method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovie(string path, Color bgColor, iPhoneMovieControlMode controlMode) { - iPhoneUtils.PlayMovie(path, bgColor, (int)controlMode, 1); } - [Obsolete("PlayMovie method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovie method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovie(string path, Color bgColor) { - iPhoneUtils.PlayMovie(path, bgColor, 0, 1); - } - [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] - public static void PlayMovieURL(string url, Color bgColor, int controlMode, int scalingMode) - { - iPhoneUtils.INTERNAL_CALL_PlayMovieURL(url, ref bgColor, controlMode, scalingMode); } - [WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void INTERNAL_CALL_PlayMovieURL(string url, ref Color bgColor, int controlMode, int scalingMode); - [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovieURL method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovieURL(string url, Color bgColor, iPhoneMovieControlMode controlMode, iPhoneMovieScalingMode scalingMode) { - iPhoneUtils.PlayMovieURL(url, bgColor, (int)controlMode, (int)scalingMode); } - [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovieURL method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovieURL(string url, Color bgColor, iPhoneMovieControlMode controlMode) { - iPhoneUtils.PlayMovieURL(url, bgColor, (int)controlMode, 1); } - [Obsolete("PlayMovieURL method is deprecated. Please use Handheld.PlayFullScreenMovie instead.")] + [Obsolete("PlayMovieURL method is deprecated (UnityUpgradable). Please use Handheld.PlayFullScreenMovie instead.", true)] public static void PlayMovieURL(string url, Color bgColor) { - iPhoneUtils.PlayMovieURL(url, bgColor, 0, 1); } - [Obsolete("Vibrate method is deprecated. Please use Handheld.Vibrate instead."), WrapperlessIcall] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void Vibrate(); + [Obsolete("Vibrate method is deprecated (UnityUpgradable). Please use Handheld.Vibrate instead.", true)] + public static void Vibrate() + { + } } } diff --git a/UnityEngine/UnityEngineInternal/APIUpdaterRuntimeServices.cs b/UnityEngine/UnityEngineInternal/APIUpdaterRuntimeServices.cs new file mode 100644 index 00000000..06885739 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/APIUpdaterRuntimeServices.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEngine; +namespace UnityEngineInternal +{ + public sealed class APIUpdaterRuntimeServices + { + private static IList ComponentsFromUnityEngine; + static APIUpdaterRuntimeServices() + { + Type typeFromHandle = typeof(Component); + APIUpdaterRuntimeServices.ComponentsFromUnityEngine = typeFromHandle.Assembly.GetTypes().Where(new Func(typeFromHandle.IsAssignableFrom)).ToList(); + } + [Obsolete("AddComponent(string) has been deprecated. Use GameObject.AddComponent() / GameObject.AddComponent(Type) instead.\nAPI Updater could not automatically update the original call to AddComponent(string name), because it was unable to resolve the type specified in parameter 'name'.\nInstead, this call has been replaced with a call to APIUpdaterRuntimeServices.AddComponent() so you can try to test your game in the editor.\nIn order to be able to build the game, replace this call (APIUpdaterRuntimeServices.AddComponent()) with a call to GameObject.AddComponent() / GameObject.AddComponent(Type).")] + public static Component AddComponent(GameObject go, string sourceInfo, string name) + { + Debug.LogWarningFormat("Performing a potentially slow search for component {0}.", new object[] + { + name + }); + Type type = APIUpdaterRuntimeServices.ResolveType(name, Assembly.GetCallingAssembly(), sourceInfo); + return (type != null) ? go.AddComponent(type) : null; + } + private static Type ResolveType(string name, Assembly callingAssembly, string sourceInfo) + { + Type type = APIUpdaterRuntimeServices.ComponentsFromUnityEngine.FirstOrDefault((Type t) => (t.Name == name || t.FullName == name) && !APIUpdaterRuntimeServices.IsMarkedAsObsolete(t)); + if (type != null) + { + Debug.LogWarningFormat("[{1}] Type '{0}' found in UnityEngine, consider replacing with go.AddComponent<{0}>();", new object[] + { + name, + sourceInfo + }); + return type; + } + Type type2 = callingAssembly.GetType(name); + if (type2 != null) + { + Debug.LogWarningFormat("[{1}] Component type '{0}' found on caller assembly. Consider replacing the call method call with: AddComponent<{0}>()", new object[] + { + type2.FullName, + sourceInfo + }); + return type2; + } + type2 = AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly a) => a.GetTypes()).SingleOrDefault((Type t) => t.Name == name && typeof(Component).IsAssignableFrom(t)); + if (type2 != null) + { + Debug.LogWarningFormat("[{2}] Component type '{0}' found on assembly {1}. Consider replacing the call method with: AddComponent<{0}>()", new object[] + { + type2.FullName, + type2.Assembly.Location, + sourceInfo + }); + return type2; + } + Debug.LogErrorFormat("[{1}] Component Type '{0}' not found.", new object[] + { + name, + sourceInfo + }); + return null; + } + private static bool IsMarkedAsObsolete(Type t) + { + return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Any(); + } + } +} diff --git a/UnityEngine/UnityEngineInternal/GIDebugVisualisation.cs b/UnityEngine/UnityEngineInternal/GIDebugVisualisation.cs new file mode 100644 index 00000000..d5d7be89 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/GIDebugVisualisation.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.CompilerServices; +using UnityEngine; +namespace UnityEngineInternal +{ + public sealed class GIDebugVisualisation + { + public static extern bool cycleMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern bool pauseCycleMode + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + } + public static extern GITextureType texType + { + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + get; + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + set; + } + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void ResetRuntimeInputTextures(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PlayCycleMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void PauseCycleMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void StopCycleMode(); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CycleSkipInstances(int skip); + [WrapperlessIcall] + [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void CycleSkipSystems(int skip); + } +} diff --git a/UnityEngine/UnityEngineInternal/GITextureType.cs b/UnityEngine/UnityEngineInternal/GITextureType.cs new file mode 100644 index 00000000..bb3066e8 --- /dev/null +++ b/UnityEngine/UnityEngineInternal/GITextureType.cs @@ -0,0 +1,15 @@ +using System; +namespace UnityEngineInternal +{ + public enum GITextureType + { + Charting, + Albedo, + Emissive, + Irradiance, + Directionality, + Baked, + BakedDirectional, + InputWorkspace + } +} diff --git a/UnityEngine/UnityEngineInternal/LightmapType.cs b/UnityEngine/UnityEngineInternal/LightmapType.cs new file mode 100644 index 00000000..e6932d6a --- /dev/null +++ b/UnityEngine/UnityEngineInternal/LightmapType.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngineInternal +{ + public enum LightmapType + { + NoLightmap = -1, + StaticLightmap, + DynamicLightmap + } +} diff --git a/UnityEngine/UnityEngineInternal/MathfInternal.cs b/UnityEngine/UnityEngineInternal/MathfInternal.cs new file mode 100644 index 00000000..700342bf --- /dev/null +++ b/UnityEngine/UnityEngineInternal/MathfInternal.cs @@ -0,0 +1,10 @@ +using System; +namespace UnityEngineInternal +{ + public struct MathfInternal + { + public static volatile float FloatMinNormal = 1.17549435E-38f; + public static volatile float FloatMinDenormal = 1.401298E-45f; + public static bool IsFlushToZeroEnabled = MathfInternal.FloatMinDenormal == 0f; + } +}